[
  {
    "path": "CITATION.cff",
    "content": "cff-version: 1.2.0\npreferred-citation:\n  type: software\n  message: If you use this software, please cite it as below.\n  authors:\n  - family-names: Jocher\n    given-names: Glenn\n    orcid: \"https://orcid.org/0000-0001-5950-6979\"\n  - family-names: Chaurasia\n    given-names: Ayush\n    orcid: \"https://orcid.org/0000-0002-7603-6750\"\n  - family-names: Qiu\n    given-names: Jing\n    orcid: \"https://orcid.org/0000-0003-3783-7069\"\n  title: \"YOLO by Ultralytics\"\n  version: 8.0.0\n  # doi: 10.5281/zenodo.3908559  # TODO\n  date-released: 2023-1-10\n  license: AGPL-3.0\n  url: \"https://github.com/ultralytics/ultralytics\"\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "## Contributing to YOLOv8 🚀\n\nWe love your input! We want to make contributing to YOLOv8 as easy and transparent as possible, whether it's:\n\n- Reporting a bug\n- Discussing the current state of the code\n- Submitting a fix\n- Proposing a new feature\n- Becoming a maintainer\n\nYOLOv8 works so well due to our combined community effort, and for every small improvement you contribute you will be\nhelping push the frontiers of what's possible in AI 😃!\n\n## Submitting a Pull Request (PR) 🛠️\n\nSubmitting a PR is easy! This example shows how to submit a PR for updating `requirements.txt` in 4 steps:\n\n### 1. Select File to Update\n\nSelect `requirements.txt` to update by clicking on it in GitHub.\n\n<p align=\"center\"><img width=\"800\" alt=\"PR_step1\" src=\"https://user-images.githubusercontent.com/26833433/122260847-08be2600-ced4-11eb-828b-8287ace4136c.png\"></p>\n\n### 2. Click 'Edit this file'\n\nButton is in top-right corner.\n\n<p align=\"center\"><img width=\"800\" alt=\"PR_step2\" src=\"https://user-images.githubusercontent.com/26833433/122260844-06f46280-ced4-11eb-9eec-b8a24be519ca.png\"></p>\n\n### 3. Make Changes\n\nChange `matplotlib` version from `3.2.2` to `3.3`.\n\n<p align=\"center\"><img width=\"800\" alt=\"PR_step3\" src=\"https://user-images.githubusercontent.com/26833433/122260853-0a87e980-ced4-11eb-9fd2-3650fb6e0842.png\"></p>\n\n### 4. Preview Changes and Submit PR\n\nClick on the **Preview changes** tab to verify your updates. At the bottom of the screen select 'Create a **new branch**\nfor this commit', assign your branch a descriptive name such as `fix/matplotlib_version` and click the green **Propose\nchanges** button. All done, your PR is now submitted to YOLOv8 for review and approval 😃!\n\n<p align=\"center\"><img width=\"800\" alt=\"PR_step4\" src=\"https://user-images.githubusercontent.com/26833433/122260856-0b208000-ced4-11eb-8e8e-77b6151cbcc3.png\"></p>\n\n### PR recommendations\n\nTo allow your work to be integrated as seamlessly as possible, we advise you to:\n\n- ✅ Verify your PR is **up-to-date** with `ultralytics/ultralytics` `main` branch. If your PR is behind you can update\n  your code by clicking the 'Update branch' button or by running `git pull` and `git merge main` locally.\n\n<p align=\"center\"><img width=\"751\" alt=\"Screenshot 2022-08-29 at 22 47 15\" src=\"https://user-images.githubusercontent.com/26833433/187295893-50ed9f44-b2c9-4138-a614-de69bd1753d7.png\"></p>\n\n- ✅ Verify all YOLOv8 Continuous Integration (CI) **checks are passing**.\n\n<p align=\"center\"><img width=\"751\" alt=\"Screenshot 2022-08-29 at 22 47 03\" src=\"https://user-images.githubusercontent.com/26833433/187296922-545c5498-f64a-4d8c-8300-5fa764360da6.png\"></p>\n\n- ✅ Reduce changes to the absolute **minimum** required for your bug fix or feature addition. _\"It is not daily increase\n  but daily decrease, hack away the unessential. The closer to the source, the less wastage there is.\"_  — Bruce Lee\n\n### Docstrings\n\nNot all functions or classes require docstrings but when they do, we\nfollow [google-style docstrings format](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings).\nHere is an example:\n\n```python\n\"\"\"\n   What the function does. Performs NMS on given detection predictions.\n\n    Args:\n        arg1: The description of the 1st argument\n        arg2: The description of the 2nd argument\n\n    Returns:\n        What the function returns. Empty if nothing is returned.\n\n    Raises:\n        Exception Class: When and why this exception can be raised by the function.\n\"\"\"\n```\n\n## Submitting a Bug Report 🐛\n\nIf you spot a problem with YOLOv8 please submit a Bug Report!\n\nFor us to start investigating a possible problem we need to be able to reproduce it ourselves first. We've created a few\nshort guidelines below to help users provide what we need in order to get started.\n\nWhen asking a question, people will be better able to provide help if you provide **code** that they can easily\nunderstand and use to **reproduce** the problem. This is referred to by community members as creating\na [minimum reproducible example](https://docs.ultralytics.com/help/minimum_reproducible_example/). Your code that reproduces\nthe problem should be:\n\n- ✅ **Minimal** – Use as little code as possible that still produces the same problem\n- ✅ **Complete** – Provide **all** parts someone else needs to reproduce your problem in the question itself\n- ✅ **Reproducible** – Test the code you're about to provide to make sure it reproduces the problem\n\nIn addition to the above requirements, for [Ultralytics](https://ultralytics.com/) to provide assistance your code\nshould be:\n\n- ✅ **Current** – Verify that your code is up-to-date with current\n  GitHub [main](https://github.com/ultralytics/ultralytics/tree/main) branch, and if necessary `git pull` or `git clone`\n  a new copy to ensure your problem has not already been resolved by previous commits.\n- ✅ **Unmodified** – Your problem must be reproducible without any modifications to the codebase in this\n  repository. [Ultralytics](https://ultralytics.com/) does not provide support for custom code ⚠️.\n\nIf you believe your problem meets all of the above criteria, please close this issue and raise a new one using the 🐛\n**Bug Report** [template](https://github.com/ultralytics/ultralytics/issues/new/choose) and providing\na [minimum reproducible example](https://docs.ultralytics.com/help/minimum_reproducible_example/) to help us better\nunderstand and diagnose your problem.\n\n## License\n\nBy contributing, you agree that your contributions will be licensed under\nthe [AGPL-3.0 license](https://choosealicense.com/licenses/agpl-3.0/)\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "include *.md\ninclude requirements.txt\ninclude LICENSE\ninclude setup.py\ninclude ultralytics/assets/bus.jpg\ninclude ultralytics/assets/zidane.jpg\nrecursive-include ultralytics *.yaml\nrecursive-exclude __pycache__ *\n"
  },
  {
    "path": "README.md",
    "content": "<div align=\"left\">   \n\n\n## You Only Look at Once for Real-time and Generic Multi-Task\nThis repository(Yolov8 multi-task) is the official PyTorch implementation of the paper \"You Only Look at Once for Real-time and Generic Multi-Task\".  \n\n> [**You Only Look at Once for Real-time and Generic Multi-Task**](https://ieeexplore.ieee.org/document/10509552)\n>\n> by [Jiayuan Wang](https://scholar.google.ca/citations?user=1z6x5_UAAAAJ&hl=zh-CN&oi=ao), [Q. M. Jonathan Wu](https://scholar.google.com/citations?user=BJSAsE8AAAAJ&hl=zh-CN)<sup> :email:</sup> and [Ning Zhang](https://scholar.google.ca/citations?hl=zh-CN&user=ZcYihtoAAAAJ)\n>\n>  (<sup>:email:</sup>) corresponding author.\n>\n> *[IEEE Transactions on Vehicular Technology](https://ieeexplore.ieee.org/document/10509552)*\n\n---\n\n### The Illustration of A-YOLOM\n\n![YOLOv8-multi-task](pictures/constructure.jpg)\n\n### Contributions\n\n* We have developed a lightweight model capable of integrating three tasks into a single unified model. This is particularly beneficial for multi-task that demand real-time processing.\n* We have designed a novel Adaptive Concatenate Module specifically for the neck region of segmentation architectures. This module can adaptively concatenate features without manual design, further enhancing the model's generality.\n* We designed a lightweight, simple, and generic segmentation head. We have a unified loss function for the same type of task head, meaning we don't need to custom design for specific tasks. It is only built by a series of convolutional layers.\n* Extensive experiments are conducted based on publicly accessible autonomous driving datasets, which demonstrate that our model can outperform existing works, particularly in terms of inference time and visualization. Moreover, we further conducted experiments using real road datasets, which also demonstrate that our model significantly outperformed the state-of-the-art approaches.\n\n### Results\n\n#### Parameters and speed\n| Model          | Parameters  | FPS (bs=1) | FPS (bs=32) |\n|----------------|-------------|------------|-------------|\n| YOLOP          | 7.9M        | 26.0       | 134.8       |\n| HybridNet      | 12.83M      | 11.7       | 26.9        |\n| YOLOv8n(det)   | 3.16M       | 102        | 802.9       |\n| YOLOv8n(seg)   | 3.26M       | 82.55      | 610.49      |\n| A-YOLOM(n)     | 4.43M       | 39.9       | 172.2       |\n| A-YOLOM(s)     | 13.61M      | 39.7       | 96.2        |\n\n\n#### Traffic Object Detection Result\n\n| Model       | Recall (%) | mAP50 (%) |\n|-------------|------------|------------|\n| MultiNet    | 81.3       | 60.2       |\n| DLT-Net     | **89.4**   | 68.4       |\n| Faster R-CNN| 81.2       | 64.9       |\n| YOLOv5s     | 86.8       | 77.2       |\n| YOLOv8n(det)| 82.2       | 75.1       |\n| YOLOP       | 88.6       | 76.5       |\n| A-YOLOM(n)  | 85.3       | 78.0       |\n| A-YOLOM(s)  | 86.9       | **81.1**   |\n\n#### Drivable Area Segmentation Result\n\n| Model          | mIoU (%) |\n|----------------|----------|\n| MultiNet       | 71.6     |\n| DLT-Net        | 72.1     |\n| PSPNet         | 89.6     |\n| YOLOv8n(seg)   | 78.1     |\n| YOLOP          | **91.6** |\n| A-YOLOM(n)     | 90.5     |\n| A-YOLOM(s)     | 91.0     |\n\n\n#### Lane Detection Result:\n\n| Model          | Accuracy (%) | IoU (%) |\n|----------------|--------------|---------|\n| Enet           | N/A          | 14.64   |\n| SCNN           | N/A          | 15.84   |\n| ENet-SAD       | N/A          | 16.02   |\n| YOLOv8n(seg)   | 80.5         | 22.9    |\n| YOLOP          | 84.8         | 26.5    |\n| A-YOLOM(n)     | 81.3         | 28.2    |\n| A-YOLOM(s)     | **84.9**     | **28.8** |\n\n\n#### Ablation Studies 1: Adaptive concatenation module:\n\n| Training method | Recall (%) | mAP50 (%) | mIoU (%) | Accuracy (%) | IoU (%) |\n|-----------------|------------|-----------|----------|--------------|---------|\n| YOLOM(n)        | 85.2       | 77.7      | 90.6     | 80.8         | 26.7    |\n| A-YOLOM(n)      | 85.3       | 78        | 90.5     | 81.3         | 28.2    |\n| YOLOM(s)        | 86.9       | 81.1      | 90.9     | 83.9         | 28.2    |\n| A-YOLOM(s)      | 86.9       | 81.1      | 91       | 84.9         | 28.8    |\n\n\n#### Ablation Studies 2: Results of different Multi-task model and segmentation structure:\n\n| Model          | Parameters | mIoU (%) | Accuracy (%) | IoU (%) |\n|----------------|------------|----------|--------------|---------|\n| YOLOv8(segda)  | 1004275    | 78.1     | -            | -       |\n| YOLOv8(segll)  | 1004275    | -        | 80.5         | 22.9    |\n| YOLOv8(multi)  | 2008550    | 84.2     | 81.7         | 24.3    |\n| YOLOM(n)       | 15880      | 90.6     | 80.8         | 26.7    |\n\nYOLOv8(multi) and YOLOM(n) only display two segmentation head parameters in total. They indeed have three heads, we ignore the detection head parameters because this is an ablation study for segmentation structure.\n\n  \n**Notes**: \n\n- The works we has use for reference including `Multinet`  ([paper](https://arxiv.org/pdf/1612.07695.pdf?utm_campaign=affiliate-ir-Optimise%20media%28%20South%20East%20Asia%29%20Pte.%20ltd._156_-99_national_R_all_ACQ_cpa_en&utm_content=&utm_source=%20388939),[code](https://github.com/MarvinTeichmann/MultiNet)）,`DLT-Net`   ([paper](https://ieeexplore.ieee.org/abstract/document/8937825)）,`Faster R-CNN`  ([paper](https://proceedings.neurips.cc/paper/2015/file/14bfa6bb14875e45bba028a21ed38046-Paper.pdf),[code](https://github.com/ShaoqingRen/faster_rcnn)）,`YOLOv5s`（[code](https://github.com/ultralytics/yolov5))  ,`PSPNet`([paper](https://openaccess.thecvf.com/content_cvpr_2017/papers/Zhao_Pyramid_Scene_Parsing_CVPR_2017_paper.pdf),[code](https://github.com/hszhao/PSPNet)) ,`ENet`([paper](https://arxiv.org/pdf/1606.02147.pdf),[code](https://github.com/osmr/imgclsmob))    `SCNN`([paper](https://www.aaai.org/ocs/index.php/AAAI/AAAI18/paper/download/16802/16322),[code](https://github.com/XingangPan/SCNN))    `SAD-ENet`([paper](https://openaccess.thecvf.com/content_ICCV_2019/papers/Hou_Learning_Lightweight_Lane_Detection_CNNs_by_Self_Attention_Distillation_ICCV_2019_paper.pdf),[code](https://github.com/cardwing/Codes-for-Lane-Detection)), `YOLOP`([paper](https://link.springer.com/article/10.1007/s11633-022-1339-y),[code](https://github.com/hustvl/YOLOP)), `HybridNets`([paper](https://arxiv.org/abs/2203.09035),[code](https://github.com/datvuthanh/HybridNets)), `YOLOv8`([code](https://github.com/ultralytics/ultralytics)). Thanks for their wonderful works.\n\n### Recommendation:\n- If you seek higher performance and can tolerate reduced speed and increased model complexity, we recommend our latest model, [RMT-PPAD](https://github.com/JiayuanWang-JW/RMT-PPAD). It is built on RT-DETR to implement multi-task learning and still achieves real-time performance on an RTX 4090 GPU.\n---\n\n### Visualization\n\n#### Real Road\n\n![Real Rold](pictures/real-road.png)\n\n---\n\n\n### Requirement\n\nThis codebase has been developed with [**Python==3.7.16**](https://www.python.org/) with [**PyTorch==1.13.1**](https://pytorch.org/get-started/locally/).\n\nYou can use a 1080Ti GPU with 16 batch sizes. That will be fine. Only need more time to train. We recommend using a 4090 or more powerful GPU, which will be fast. \n\nWe strongly recommend you create a pure environment and follow our instructions to build yours. Otherwise, you may encounter some issues because the YOLOv8 has many mechanisms to detect your environment package automatically. Then it will change some variable values to further affect the code running. \n\n```setup\ncd YOLOv8-multi-task\npip install -e .\n```\n\n### Data preparation and Pre-trained model\n\n#### Download\n\n- Download the images from [images](https://bdd-data.berkeley.edu/).\n\n- Pre-trained model: [A-YOLOM](https://uwin365-my.sharepoint.com/:f:/g/personal/wang621_uwindsor_ca/EoUsIoFgcEhBgnO4kTjDQG4BUUSHMFXG4ami9qjvTUTofA?e=0xuAJG) # which include two version, scale \"n\" and \"s\".\n  \n- Download the annotations of detection from [detection-object](https://uwin365-my.sharepoint.com/:u:/g/personal/wang621_uwindsor_ca/EeHOFLpSbp1EpN3FA1T97xABbjVEoeYefI8Kx0uKieR6xw?e=tnqHHx). \n- Download the annotations of drivable area segmentation from [seg-drivable-10](https://uwin365-my.sharepoint.com/:u:/g/personal/wang621_uwindsor_ca/EYu4C5h9qjZNg2HkNkw9nT0BImRO9HnTl2rozFFhD7zj-Q?e=gFLhpv). \n- Download the annotations of lane line segmentation from [seg-lane-11](https://uwin365-my.sharepoint.com/:u:/g/personal/wang621_uwindsor_ca/EZowlpA7sKZAuXZpphDvTBABIvAOZ6957aTYplBYGFLpeQ?e=4DNH5W). \n\nWe recommend the dataset directory structure to be the following:\n\n```\n# The id represent the correspondence relation\n├─dataset root\n│ ├─images\n│ │ ├─train2017\n│ │ ├─val2017\n│ ├─detection-object\n│ │ ├─labels\n│ │ │ ├─train2017\n│ │ │ ├─val2017\n│ ├─seg-drivable-10\n│ │ ├─labels\n│ │ │ ├─train2017\n│ │ │ ├─val2017\n│ ├─seg-lane-11\n│ │ ├─labels\n│ │ │ ├─train2017\n│ │ │ ├─val2017\n```\n\nUpdate the your dataset path in the `./ultralytics/datasets/bdd-multi.yaml`.\n\n### Training\n\nYou can set the training configuration in the `./ultralytics/yolo/cfg/default.yaml`.\n\n\n```\npython train.py\n```\nYou can change the setting in train.py\n\n```python\n# setting\n\nsys.path.insert(0, \"/home/jiayuan/ultralytics-main/ultralytics\")\n# You should change the path to your local path to \"ultralytics\" file\nmodel = YOLO('/home/jiayuan/ultralytics-main/ultralytics/models/v8/yolov8-bdd-v4-one-dropout-individual.yaml', task='multi')\n# You need to change the model path for yours.\n# The model files saved under \"./ultralytics/models/v8\" \nmodel.train(data='/home/jiayuan/ultralytics-main/ultralytics/datasets/bdd-multi-toy.yaml', batch=4, epochs=300, imgsz=(640,640), device=[4], name='v4_640', val=True, task='multi',classes=[2,3,4,9,10,11],combine_class=[2,3,4,9],single_cls=True)\n```\n- data: Please change the \"data\" path to yours. You can find it under \"./ultralytics/datasets\"\n\n- device: If you have multi-GPUs, please list your GPU numbers, such as [0,1,2,3,4,5,6,7,8]\n\n- name: Your project name, the result and trained model will save under \"./ultralytics/runs/multi/Your Project Name\"\n\n- task: If you want to use the Multi-task model, please keep \"multi\" here\n\n- classes: You can change this to control which classfication in training, 10 and 11 means drivable area and lane line segmentation. You can create or change dataset map under \"./ultralytics/datasets/bdd-multi.yaml\"\n\n- combine_class: means the model will combine \"classes\" into one class, such as our project combining the \"car\", \"bus\", \"truck\", and \"train\" into \"vehicle\".\n\n- single_cls: This will combine whole detection classes into one class, for example, you have 7 classes in your dataset, and when you use \"single_cls\", it will automatically combine them into one class. When you set single_cls=False or delete the single_cls from model.train(). Please follow the below Note to change the \"tnc\" in both dataset.yaml and model.yaml, \"nc_list\" in dataset.yaml, the output of the detection head as well. \n\n\n\n\n### Evaluation\n\nYou can set the evaluation configuration in the `./ultralytics/yolo/cfg/default.yaml`\n\n\n```\npython val.py\n```\nYou can change the setting in val.py\n\n```python\n# setting\n\nsys.path.insert(0, \"/home/jiayuan/yolom/ultralytics\")\n# The same with train, you should change the path to yours.\n\nmodel = YOLO('/home/jiayuan/ultralytics-main/ultralytics/runs/best.pt')\n# Please change this path to your well-trained model. You can use our provide the pre-train model or your model under \"./ultralytics/runs/multi/Your Project Name/weight/best.pt\"\nmetrics = model.val(data='/home/jiayuan/ultralytics-main/ultralytics/datasets/bdd-multi.yaml',device=[3],task='multi',name='val',iou=0.6,conf=0.001, imgsz=(640,640),classes=[2,3,4,9,10,11],combine_class=[2,3,4,9],single_cls=True)\n```\n- data: Please change the \"data\" path to yours. You can find it under \"./ultralytics/datasets\"\n- device: If you have multi-GPUs, please list your GPU numbers, such as [0,1,2,3,4,5,6,7,8]. We do not recommend you use multi-GPU in val because usually, one GPU is enough.\n- speed: If you want to calculate the FPS, you should set \"speed=True\". This FPS calculation method reference from `HybridNets`([code](https://github.com/datvuthanh/HybridNets))\n- single_cls: should keep the same bool value with training. \n\n### Prediction\n\n```\npython predict.py\n```\nYou can change the setting in predict.py\n\n```python\n# setting \n\nsys.path.insert(0, \"/home/jiayuan/ultralytics-main/ultralytics\")\nnumber = 3 #input how many tasks in your work, if you have 1 detection and 3 segmentation tasks, here should be 4.\nmodel = YOLO('/home/jiayuan/ultralytics-main/ultralytics/runs/best.pt')  \nmodel.predict(source='/data/jiayuan/dash_camara_dataset/daytime', imgsz=(384,672), device=[3],name='v4_daytime', save=True, conf=0.25, iou=0.45, show_labels=False)\n# The predict results will save under \"runs\" folder\n```\n\nPS: If you want to use our provided pre-trained model, please make sure that your input images are (720,1280) size and keep \"imgsz=(384,672)\" to achieve the best performance, you can change the \"imgsz\" value, but the results maybe different because he is different from the training size.\n\n- source: Your input or want to predict images folder.\n- show_labels=False: close the display of the labels. Please keep in mind, when you use a pre-trained model with \"single cell=True\", labels will default to display the first class name instead.\n- boxes=False: close the bos for segmentation tasks.\n\n\n\n\n\n### Note\n- This code is easy to extend the tasks to any multi-segmentation and detection tasks, only need to modify the model yaml and dataset yaml file information and create your dataset follows our labels format, please keep in mind, you should keep \"det\" in your detection tasks name and \"seg\" in your segmentation tasks name. Then the code will be working. No need to modify the basic code, We have done the necessary work in the basic code.\n\n- Please keep in mind, when you change the detection task number of classes, please change the \"tnc\" in dataset.yaml and modle.yaml. \"tcn\" means the total number of classes, including detection and segmentation. Such as you have 7 classes for detection, 1 segmentation and another 1 segmentation. \"tnc\" should be set to 9.\n\n  - \"nc_list\" also needs to update, it should match your \"labels_list\" order. Such as detection-object, seg-drivable, seg-lane in your \"labels_list\". Then \"nc_list\" should be [7,1,1]. That means you have 7 classes in detection-object, 1 class in drivable segmentation, and 1 class in lane segmentation. \n\n  - You also need to change the detection head output numbers, that in model.yaml, such as \"  - [[15, 18, 21], 1, Detect, [int number for detection class]]  # 36 Detect(P3, P4, P5)\", please change \"int number for detection class\" to your number of classes in your detection tasks, follow above examples, here should be 7.\n\n- If you want to change some basic code to implement your idea. Please search the \"###### Jiayuan\" or \"######Jiayuan\", We have changed these parts based on `YOLOv8`([code](https://github.com/ultralytics/ultralytics)) to implement multi-task in a single model.\n\n\n\n## Citation\n\nIf you find our paper and code useful for your research, please consider giving a star :star:   and citation :pencil: :\n\n```BibTeX\n@ARTICLE{wang2024you,\n  author={Wang, Jiayuan and Wu, Q. M. Jonathan and Zhang, Ning},\n  journal={IEEE Transactions on Vehicular Technology}, \n  title={You Only Look at Once for Real-Time and Generic Multi-Task}, \n  year={2024},\n  pages={1-13},\n  keywords={Multi-task learning;panoptic driving perception;object detection;drivable area segmentation;lane line segmentation},\n  doi={10.1109/TVT.2024.3394350}}\n```\n"
  },
  {
    "path": "bin/activate",
    "content": "# This file must be used with \"source bin/activate\" *from bash*\n# you cannot run it directly\n\n\nif [ \"${BASH_SOURCE-}\" = \"$0\" ]; then\n    echo \"You must source this script: \\$ source $0\" >&2\n    exit 33\nfi\n\ndeactivate () {\n    unset -f pydoc >/dev/null 2>&1 || true\n\n    # reset old environment variables\n    # ! [ -z ${VAR+_} ] returns true if VAR is declared at all\n    if ! [ -z \"${_OLD_VIRTUAL_PATH:+_}\" ] ; then\n        PATH=\"$_OLD_VIRTUAL_PATH\"\n        export PATH\n        unset _OLD_VIRTUAL_PATH\n    fi\n    if ! [ -z \"${_OLD_VIRTUAL_PYTHONHOME+_}\" ] ; then\n        PYTHONHOME=\"$_OLD_VIRTUAL_PYTHONHOME\"\n        export PYTHONHOME\n        unset _OLD_VIRTUAL_PYTHONHOME\n    fi\n\n    # The hash command must be called to get it to forget past\n    # commands. Without forgetting past commands the $PATH changes\n    # we made may not be respected\n    hash -r 2>/dev/null\n\n    if ! [ -z \"${_OLD_VIRTUAL_PS1+_}\" ] ; then\n        PS1=\"$_OLD_VIRTUAL_PS1\"\n        export PS1\n        unset _OLD_VIRTUAL_PS1\n    fi\n\n    unset VIRTUAL_ENV\n    if [ ! \"${1-}\" = \"nondestructive\" ] ; then\n    # Self destruct!\n        unset -f deactivate\n    fi\n}\n\n# unset irrelevant variables\ndeactivate nondestructive\n\nVIRTUAL_ENV='/home/jiayuan/ultralytics-main'\nif ([ \"$OSTYPE\" = \"cygwin\" ] || [ \"$OSTYPE\" = \"msys\" ]) && $(command -v cygpath &> /dev/null) ; then\n    VIRTUAL_ENV=$(cygpath -u \"$VIRTUAL_ENV\")\nfi\nexport VIRTUAL_ENV\n\n_OLD_VIRTUAL_PATH=\"$PATH\"\nPATH=\"$VIRTUAL_ENV/bin:$PATH\"\nexport PATH\n\n# unset PYTHONHOME if set\nif ! [ -z \"${PYTHONHOME+_}\" ] ; then\n    _OLD_VIRTUAL_PYTHONHOME=\"$PYTHONHOME\"\n    unset PYTHONHOME\nfi\n\nif [ -z \"${VIRTUAL_ENV_DISABLE_PROMPT-}\" ] ; then\n    _OLD_VIRTUAL_PS1=\"${PS1-}\"\n    if [ \"x\" != x ] ; then\n        PS1=\"() ${PS1-}\"\n    else\n        PS1=\"(`basename \\\"$VIRTUAL_ENV\\\"`) ${PS1-}\"\n    fi\n    export PS1\nfi\n\n# Make sure to unalias pydoc if it's already there\nalias pydoc 2>/dev/null >/dev/null && unalias pydoc || true\n\npydoc () {\n    python -m pydoc \"$@\"\n}\n\n# The hash command must be called to get it to forget past\n# commands. Without forgetting past commands the $PATH changes\n# we made may not be respected\nhash -r 2>/dev/null\n"
  },
  {
    "path": "bin/activate.csh",
    "content": "# This file must be used with \"source bin/activate.csh\" *from csh*.\n# You cannot run it directly.\n# Created by Davide Di Blasi <davidedb@gmail.com>.\n\nset newline='\\\n'\n\nalias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH \"$_OLD_VIRTUAL_PATH:q\" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt=\"$_OLD_VIRTUAL_PROMPT:q\" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test \"\\!:*\" != \"nondestructive\" && unalias deactivate && unalias pydoc'\n\n# Unset irrelevant variables.\ndeactivate nondestructive\n\nsetenv VIRTUAL_ENV '/home/jiayuan/ultralytics-main'\n\nset _OLD_VIRTUAL_PATH=\"$PATH:q\"\nsetenv PATH \"$VIRTUAL_ENV:q/bin:$PATH:q\"\n\n\n\nif ('' != \"\") then\n    set env_name = '() '\nelse\n    set env_name = '('\"$VIRTUAL_ENV:t:q\"') '\nendif\n\nif ( $?VIRTUAL_ENV_DISABLE_PROMPT ) then\n    if ( $VIRTUAL_ENV_DISABLE_PROMPT == \"\" ) then\n        set do_prompt = \"1\"\n    else\n        set do_prompt = \"0\"\n    endif\nelse\n    set do_prompt = \"1\"\nendif\n\nif ( $do_prompt == \"1\" ) then\n    # Could be in a non-interactive environment,\n    # in which case, $prompt is undefined and we wouldn't\n    # care about the prompt anyway.\n    if ( $?prompt ) then\n        set _OLD_VIRTUAL_PROMPT=\"$prompt:q\"\n        if ( \"$prompt:q\" =~ *\"$newline:q\"* ) then\n            :\n        else\n            set prompt = \"$env_name:q$prompt:q\"\n        endif\n    endif\nendif\n\nunset env_name\nunset do_prompt\n\nalias pydoc python -m pydoc\n\nrehash\n"
  },
  {
    "path": "bin/activate.fish",
    "content": "# This file must be used using `source bin/activate.fish` *within a running fish ( http://fishshell.com ) session*.\n# Do not run it directly.\n\nfunction _bashify_path -d \"Converts a fish path to something bash can recognize\"\n    set fishy_path $argv\n    set bashy_path $fishy_path[1]\n    for path_part in $fishy_path[2..-1]\n        set bashy_path \"$bashy_path:$path_part\"\n    end\n    echo $bashy_path\nend\n\nfunction _fishify_path -d \"Converts a bash path to something fish can recognize\"\n    echo $argv | tr ':' '\\n'\nend\n\nfunction deactivate -d 'Exit virtualenv mode and return to the normal environment.'\n    # reset old environment variables\n    if test -n \"$_OLD_VIRTUAL_PATH\"\n        # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling\n        if test (echo $FISH_VERSION | head -c 1) -lt 3\n            set -gx PATH (_fishify_path \"$_OLD_VIRTUAL_PATH\")\n        else\n            set -gx PATH $_OLD_VIRTUAL_PATH\n        end\n        set -e _OLD_VIRTUAL_PATH\n    end\n\n    if test -n \"$_OLD_VIRTUAL_PYTHONHOME\"\n        set -gx PYTHONHOME \"$_OLD_VIRTUAL_PYTHONHOME\"\n        set -e _OLD_VIRTUAL_PYTHONHOME\n    end\n\n    if test -n \"$_OLD_FISH_PROMPT_OVERRIDE\"\n       and functions -q _old_fish_prompt\n        # Set an empty local `$fish_function_path` to allow the removal of `fish_prompt` using `functions -e`.\n        set -l fish_function_path\n\n        # Erase virtualenv's `fish_prompt` and restore the original.\n        functions -e fish_prompt\n        functions -c _old_fish_prompt fish_prompt\n        functions -e _old_fish_prompt\n        set -e _OLD_FISH_PROMPT_OVERRIDE\n    end\n\n    set -e VIRTUAL_ENV\n\n    if test \"$argv[1]\" != 'nondestructive'\n        # Self-destruct!\n        functions -e pydoc\n        functions -e deactivate\n        functions -e _bashify_path\n        functions -e _fishify_path\n    end\nend\n\n# Unset irrelevant variables.\ndeactivate nondestructive\n\nset -gx VIRTUAL_ENV '/home/jiayuan/ultralytics-main'\n\n# https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling\nif test (echo $FISH_VERSION | head -c 1) -lt 3\n   set -gx _OLD_VIRTUAL_PATH (_bashify_path $PATH)\nelse\n    set -gx _OLD_VIRTUAL_PATH $PATH\nend\nset -gx PATH \"$VIRTUAL_ENV\"'/bin' $PATH\n\n# Unset `$PYTHONHOME` if set.\nif set -q PYTHONHOME\n    set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME\n    set -e PYTHONHOME\nend\n\nfunction pydoc\n    python -m pydoc $argv\nend\n\nif test -z \"$VIRTUAL_ENV_DISABLE_PROMPT\"\n    # Copy the current `fish_prompt` function as `_old_fish_prompt`.\n    functions -c fish_prompt _old_fish_prompt\n\n    function fish_prompt\n        # Run the user's prompt first; it might depend on (pipe)status.\n        set -l prompt (_old_fish_prompt)\n\n        # Prompt override provided?\n        # If not, just prepend the environment name.\n        if test -n ''\n            printf '(%s) ' ''\n        else\n            printf '(%s) ' (basename \"$VIRTUAL_ENV\")\n        end\n\n        string join -- \\n $prompt # handle multi-line prompts\n    end\n\n    set -gx _OLD_FISH_PROMPT_OVERRIDE \"$VIRTUAL_ENV\"\nend\n"
  },
  {
    "path": "bin/activate.nu",
    "content": "# This command prepares the required environment variables\ndef-env activate-virtualenv [] {\n    def is-string [x] {\n        ($x | describe) == 'string'\n    }\n\n    def has-env [name: string] {\n        $name in (env).name\n    }\n\n    let is_windows = ((sys).host.name | str downcase) == 'windows'\n    let virtual_env = '/home/jiayuan/ultralytics-main'\n    let bin = 'bin'\n    let path_sep = ':'\n    let path_name = if $is_windows {\n        if (has-env 'Path') {\n            'Path'\n        } else {\n            'PATH'\n        }\n    } else {\n        'PATH'\n    }\n\n    let old_path = (\n        if $is_windows {\n            if (has-env 'Path') {\n                $env.Path\n            } else {\n                $env.PATH\n            }\n        } else {\n            $env.PATH\n        } | if (is-string $in) {\n            # if Path/PATH is a string, make it a list\n            $in | split row $path_sep | path expand\n        } else {\n            $in\n        }\n    )\n\n    let venv_path = ([$virtual_env $bin] | path join)\n    let new_path = ($old_path | prepend $venv_path | str collect $path_sep)\n\n    # Creating the new prompt for the session\n    let virtual_prompt = if ('' == '') {\n        $'(char lparen)($virtual_env | path basename)(char rparen) '\n    } else {\n        '() '\n    }\n\n    # Back up the old prompt builder\n    let old_prompt_command = if (has-env 'VIRTUAL_ENV') && (has-env '_OLD_PROMPT_COMMAND') {\n        $env._OLD_PROMPT_COMMAND\n    } else {\n        if (has-env 'PROMPT_COMMAND') {\n            $env.PROMPT_COMMAND\n        } else {\n            ''\n        }\n    }\n\n    # If there is no default prompt, then only the env is printed in the prompt\n    let new_prompt = if (has-env 'PROMPT_COMMAND') {\n        if ($old_prompt_command | describe) == 'block' {\n            { $'($virtual_prompt)(do $old_prompt_command)' }\n        } else {\n            { $'($virtual_prompt)($old_prompt_command)' }\n        }\n    } else {\n        { $'($virtual_prompt)' }\n    }\n\n    # Environment variables that will be batched loaded to the virtual env\n    let new_env = {\n        $path_name          : $new_path\n        VIRTUAL_ENV         : $virtual_env\n        _OLD_VIRTUAL_PATH   : ($old_path | str collect $path_sep)\n        _OLD_PROMPT_COMMAND : $old_prompt_command\n        PROMPT_COMMAND      : $new_prompt\n        VIRTUAL_PROMPT      : $virtual_prompt\n    }\n\n    # Activate the environment variables\n    load-env $new_env\n}\n\n# Activate the virtualenv\nactivate-virtualenv\n\nalias pydoc = python -m pydoc\nalias deactivate = source '/home/jiayuan/ultralytics-main/bin/deactivate.nu'\n"
  },
  {
    "path": "bin/activate.ps1",
    "content": "$script:THIS_PATH = $myinvocation.mycommand.path\n$script:BASE_DIR = Split-Path (Resolve-Path \"$THIS_PATH/..\") -Parent\n\nfunction global:deactivate([switch] $NonDestructive) {\n    if (Test-Path variable:_OLD_VIRTUAL_PATH) {\n        $env:PATH = $variable:_OLD_VIRTUAL_PATH\n        Remove-Variable \"_OLD_VIRTUAL_PATH\" -Scope global\n    }\n\n    if (Test-Path function:_old_virtual_prompt) {\n        $function:prompt = $function:_old_virtual_prompt\n        Remove-Item function:\\_old_virtual_prompt\n    }\n\n    if ($env:VIRTUAL_ENV) {\n        Remove-Item env:VIRTUAL_ENV -ErrorAction SilentlyContinue\n    }\n\n    if (!$NonDestructive) {\n        # Self destruct!\n        Remove-Item function:deactivate\n        Remove-Item function:pydoc\n    }\n}\n\nfunction global:pydoc {\n    python -m pydoc $args\n}\n\n# unset irrelevant variables\ndeactivate -nondestructive\n\n$VIRTUAL_ENV = $BASE_DIR\n$env:VIRTUAL_ENV = $VIRTUAL_ENV\n\nNew-Variable -Scope global -Name _OLD_VIRTUAL_PATH -Value $env:PATH\n\n$env:PATH = \"$env:VIRTUAL_ENV/bin:\" + $env:PATH\nif (!$env:VIRTUAL_ENV_DISABLE_PROMPT) {\n    function global:_old_virtual_prompt {\n        \"\"\n    }\n    $function:_old_virtual_prompt = $function:prompt\n\n    if (\"\" -ne \"\") {\n        function global:prompt {\n            # Add the custom prefix to the existing prompt\n            $previous_prompt_value = & $function:_old_virtual_prompt\n            (\"() \" + $previous_prompt_value)\n        }\n    }\n    else {\n        function global:prompt {\n            # Add a prefix to the current prompt, but don't discard it.\n            $previous_prompt_value = & $function:_old_virtual_prompt\n            $new_prompt_value = \"($( Split-Path $env:VIRTUAL_ENV -Leaf )) \"\n            ($new_prompt_value + $previous_prompt_value)\n        }\n    }\n}\n"
  },
  {
    "path": "bin/activate_this.py",
    "content": "\"\"\"Activate virtualenv for current interpreter:\n\nUse exec(open(this_file).read(), {'__file__': this_file}).\n\nThis can be used when you must use an existing Python interpreter, not the virtualenv bin/python.\n\"\"\"\nimport os\nimport site\nimport sys\n\ntry:\n    abs_file = os.path.abspath(__file__)\nexcept NameError:\n    raise AssertionError(\"You must use exec(open(this_file).read(), {'__file__': this_file}))\")\n\nbin_dir = os.path.dirname(abs_file)\nbase = bin_dir[: -len(\"bin\") - 1]  # strip away the bin part from the __file__, plus the path separator\n\n# prepend bin to PATH (this file is inside the bin directory)\nos.environ[\"PATH\"] = os.pathsep.join([bin_dir] + os.environ.get(\"PATH\", \"\").split(os.pathsep))\nos.environ[\"VIRTUAL_ENV\"] = base  # virtual env is right above bin directory\n\n# add the virtual environments libraries to the host python import mechanism\nprev_length = len(sys.path)\nfor lib in \"../lib/python3.7/site-packages\".split(os.pathsep):\n    path = os.path.realpath(os.path.join(bin_dir, lib))\n    site.addsitedir(path.decode(\"utf-8\") if \"\" else path)\nsys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]\n\nsys.real_prefix = sys.prefix\nsys.prefix = base\n"
  },
  {
    "path": "bin/deactivate.nu",
    "content": "def-env deactivate-virtualenv [] {\n    def has-env [name: string] {\n        $name in (env).name\n    }\n\n    let is_windows = ((sys).host.name | str downcase) == 'windows'\n\n    let path_name = if $is_windows {\n        if (has-env 'Path') {\n            'Path'\n        } else {\n            'PATH'\n        }\n    } else {\n        'PATH'\n    }\n\n    load-env { $path_name : $env._OLD_VIRTUAL_PATH }\n\n    let-env PROMPT_COMMAND = $env._OLD_PROMPT_COMMAND\n\n    # Hiding the environment variables that were created when activating the env\n    hide _OLD_VIRTUAL_PATH\n    hide _OLD_PROMPT_COMMAND\n    hide VIRTUAL_ENV\n    hide VIRTUAL_PROMPT\n}\n\ndeactivate-virtualenv\n\nhide pydoc\nhide deactivate\n"
  },
  {
    "path": "bin/pip",
    "content": "#!/home/jiayuan/ultralytics-main/bin/python\n# -*- coding: utf-8 -*-\nimport re\nimport sys\nfrom pip._internal.cli.main import main\nif __name__ == '__main__':\n    sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n    sys.exit(main())\n"
  },
  {
    "path": "bin/pip-3.7",
    "content": "#!/home/jiayuan/ultralytics-main/bin/python\n# -*- coding: utf-8 -*-\nimport re\nimport sys\nfrom pip._internal.cli.main import main\nif __name__ == '__main__':\n    sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n    sys.exit(main())\n"
  },
  {
    "path": "bin/pip3",
    "content": "#!/home/jiayuan/ultralytics-main/bin/python\n# -*- coding: utf-8 -*-\nimport re\nimport sys\nfrom pip._internal.cli.main import main\nif __name__ == '__main__':\n    sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n    sys.exit(main())\n"
  },
  {
    "path": "bin/pip3.7",
    "content": "#!/home/jiayuan/ultralytics-main/bin/python\n# -*- coding: utf-8 -*-\nimport re\nimport sys\nfrom pip._internal.cli.main import main\nif __name__ == '__main__':\n    sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n    sys.exit(main())\n"
  },
  {
    "path": "bin/wheel",
    "content": "#!/home/jiayuan/ultralytics-main/bin/python\n# -*- coding: utf-8 -*-\nimport re\nimport sys\nfrom wheel.cli import main\nif __name__ == '__main__':\n    sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n    sys.exit(main())\n"
  },
  {
    "path": "bin/wheel-3.7",
    "content": "#!/home/jiayuan/ultralytics-main/bin/python\n# -*- coding: utf-8 -*-\nimport re\nimport sys\nfrom wheel.cli import main\nif __name__ == '__main__':\n    sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n    sys.exit(main())\n"
  },
  {
    "path": "bin/wheel3",
    "content": "#!/home/jiayuan/ultralytics-main/bin/python\n# -*- coding: utf-8 -*-\nimport re\nimport sys\nfrom wheel.cli import main\nif __name__ == '__main__':\n    sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n    sys.exit(main())\n"
  },
  {
    "path": "bin/wheel3.7",
    "content": "#!/home/jiayuan/ultralytics-main/bin/python\n# -*- coding: utf-8 -*-\nimport re\nimport sys\nfrom wheel.cli import main\nif __name__ == '__main__':\n    sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n    sys.exit(main())\n"
  },
  {
    "path": "docker/Dockerfile",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Builds ultralytics/ultralytics:latest image on DockerHub https://hub.docker.com/r/ultralytics/ultralytics\n# Image is CUDA-optimized for YOLOv8 single/multi-GPU training and inference\n\n# Start FROM PyTorch image https://hub.docker.com/r/pytorch/pytorch or nvcr.io/nvidia/pytorch:23.03-py3\nFROM pytorch/pytorch:2.0.0-cuda11.7-cudnn8-runtime\n\n# Downloads to user config dir\nADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/\n\n# Install linux packages\n# g++ required to build 'tflite_support' package\nRUN apt update \\\n    && apt install --no-install-recommends -y gcc git zip curl htop libgl1-mesa-glx libglib2.0-0 libpython3-dev gnupg g++\n# RUN alias python=python3\n\n# Security updates\n# https://security.snyk.io/vuln/SNYK-UBUNTU1804-OPENSSL-3314796\nRUN apt upgrade --no-install-recommends -y openssl tar\n\n# Create working directory\nRUN mkdir -p /usr/src/ultralytics\nWORKDIR /usr/src/ultralytics\n\n# Copy contents\n# COPY . /usr/src/app  (issues as not a .git directory)\nRUN git clone https://github.com/ultralytics/ultralytics /usr/src/ultralytics\nADD https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt /usr/src/ultralytics/\n\n# Install pip packages\nRUN python3 -m pip install --upgrade pip wheel\nRUN pip install --no-cache -e . albumentations comet tensorboard\n\n# Set environment variables\nENV OMP_NUM_THREADS=1\n\n\n# Usage Examples -------------------------------------------------------------------------------------------------------\n\n# Build and Push\n# t=ultralytics/ultralytics:latest && sudo docker build -f docker/Dockerfile -t $t . && sudo docker push $t\n\n# Pull and Run\n# t=ultralytics/ultralytics:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all $t\n\n# Pull and Run with local directory access\n# t=ultralytics/ultralytics:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v \"$(pwd)\"/datasets:/usr/src/datasets $t\n\n# Kill all\n# sudo docker kill $(sudo docker ps -q)\n\n# Kill all image-based\n# sudo docker kill $(sudo docker ps -qa --filter ancestor=ultralytics/ultralytics:latest)\n\n# DockerHub tag update\n# t=ultralytics/ultralytics:latest tnew=ultralytics/ultralytics:v6.2 && sudo docker pull $t && sudo docker tag $t $tnew && sudo docker push $tnew\n\n# Clean up\n# sudo docker system prune -a --volumes\n\n# Update Ubuntu drivers\n# https://www.maketecheasier.com/install-nvidia-drivers-ubuntu/\n\n# DDP test\n# python -m torch.distributed.run --nproc_per_node 2 --master_port 1 train.py --epochs 3\n\n# GCP VM from Image\n# docker.io/ultralytics/ultralytics:latest\n"
  },
  {
    "path": "docker/Dockerfile-arm64",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Builds ultralytics/ultralytics:latest-arm64 image on DockerHub https://hub.docker.com/r/ultralytics/ultralytics\n# Image is aarch64-compatible for Apple M1 and other ARM architectures i.e. Jetson Nano and Raspberry Pi\n\n# Start FROM Ubuntu image https://hub.docker.com/_/ubuntu\nFROM arm64v8/ubuntu:22.10\n\n# Downloads to user config dir\nADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/\n\n# Install linux packages\nRUN apt update \\\n    && apt install --no-install-recommends -y python3-pip git zip curl htop gcc libgl1-mesa-glx libglib2.0-0 libpython3-dev\n# RUN alias python=python3\n\n# Create working directory\nRUN mkdir -p /usr/src/ultralytics\nWORKDIR /usr/src/ultralytics\n\n# Copy contents\n# COPY . /usr/src/app  (issues as not a .git directory)\nRUN git clone https://github.com/ultralytics/ultralytics /usr/src/ultralytics\nADD https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt /usr/src/ultralytics/\n\n# Install pip packages\nRUN python3 -m pip install --upgrade pip wheel\nRUN pip install --no-cache -e .\n\n\n# Usage Examples -------------------------------------------------------------------------------------------------------\n\n# Build and Push\n# t=ultralytics/ultralytics:latest-arm64 && sudo docker build --platform linux/arm64 -f docker/Dockerfile-arm64 -t $t . && sudo docker push $t\n\n# Pull and Run\n# t=ultralytics/ultralytics:latest-arm64 && sudo docker pull $t && sudo docker run -it --ipc=host -v \"$(pwd)\"/datasets:/usr/src/datasets $t\n"
  },
  {
    "path": "docker/Dockerfile-cpu",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Builds ultralytics/ultralytics:latest-cpu image on DockerHub https://hub.docker.com/r/ultralytics/ultralytics\n# Image is CPU-optimized for ONNX, OpenVINO and PyTorch YOLOv8 deployments\n\n# Start FROM Ubuntu image https://hub.docker.com/_/ubuntu\nFROM ubuntu:22.10\n\n# Downloads to user config dir\nADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/\n\n# Install linux packages\n# g++ required to build 'tflite_support' package\nRUN apt update \\\n    && apt install --no-install-recommends -y python3-pip git zip curl htop libgl1-mesa-glx libglib2.0-0 libpython3-dev gnupg g++\n# RUN alias python=python3\n\n# Create working directory\nRUN mkdir -p /usr/src/ultralytics\nWORKDIR /usr/src/ultralytics\n\n# Copy contents\n# COPY . /usr/src/app  (issues as not a .git directory)\nRUN git clone https://github.com/ultralytics/ultralytics /usr/src/ultralytics\nADD https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt /usr/src/ultralytics/\n\n# Install pip packages\nRUN python3 -m pip install --upgrade pip wheel\nRUN pip install --no-cache -e . --extra-index-url https://download.pytorch.org/whl/cpu\n\n\n# Usage Examples -------------------------------------------------------------------------------------------------------\n\n# Build and Push\n# t=ultralytics/ultralytics:latest-cpu && sudo docker build -f docker/Dockerfile-cpu -t $t . && sudo docker push $t\n\n# Pull and Run\n# t=ultralytics/ultralytics:latest-cpu && sudo docker pull $t && sudo docker run -it --ipc=host -v \"$(pwd)\"/datasets:/usr/src/datasets $t\n"
  },
  {
    "path": "docker/Dockerfile-jetson",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Builds ultralytics/ultralytics:jetson image on DockerHub https://hub.docker.com/r/ultralytics/ultralytics\n# Supports JetPack for YOLOv8 on Jetson Nano, TX1/TX2, Xavier NX, AGX Xavier, AGX Orin, and Orin NX\n\n# Start FROM https://catalog.ngc.nvidia.com/orgs/nvidia/containers/l4t-pytorch\nFROM nvcr.io/nvidia/l4t-pytorch:r35.2.1-pth2.0-py3\n\n# Downloads to user config dir\nADD https://ultralytics.com/assets/Arial.ttf https://ultralytics.com/assets/Arial.Unicode.ttf /root/.config/Ultralytics/\n\n# Install linux packages\n# g++ required to build 'tflite_support' package\nRUN apt update \\\n    && apt install --no-install-recommends -y gcc git zip curl htop libgl1-mesa-glx libglib2.0-0 libpython3-dev gnupg g++\n# RUN alias python=python3\n\n# Create working directory\nRUN mkdir -p /usr/src/ultralytics\nWORKDIR /usr/src/ultralytics\n\n# Copy contents\n# COPY . /usr/src/app  (issues as not a .git directory)\nRUN git clone https://github.com/ultralytics/ultralytics /usr/src/ultralytics\nADD https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt /usr/src/ultralytics/\n\n# Install pip packages manually for TensorRT compatibility https://github.com/NVIDIA/TensorRT/issues/2567\nRUN python3 -m pip install --upgrade pip wheel\nRUN pip install --no-cache tqdm matplotlib pyyaml psutil pandas onnx \"numpy==1.23\"\nRUN pip install --no-cache -e .\n\n# Set environment variables\nENV OMP_NUM_THREADS=1\n\n\n# Usage Examples -------------------------------------------------------------------------------------------------------\n\n# Build and Push\n# t=ultralytics/ultralytics:latest-jetson && sudo docker build --platform linux/arm64 -f docker/Dockerfile-jetson -t $t . && sudo docker push $t\n\n# Pull and Run\n# t=ultralytics/ultralytics:jetson && sudo docker pull $t && sudo docker run -it --runtime=nvidia $t\n"
  },
  {
    "path": "docs/CNAME",
    "content": "docs.ultralytics.com"
  },
  {
    "path": "docs/README.md",
    "content": "---\ndescription: Learn how to install the Ultralytics package in developer mode and build/serve locally using MkDocs. Deploy your project to your host easily.\n---\n\n# Ultralytics Docs\n\nUltralytics Docs are deployed to [https://docs.ultralytics.com](https://docs.ultralytics.com).\n\n### Install Ultralytics package\n\nTo install the ultralytics package in developer mode, you will need to have Git and Python 3 installed on your system.\nThen, follow these steps:\n\n1. Clone the ultralytics repository to your local machine using Git:\n\n```bash\ngit clone https://github.com/ultralytics/ultralytics.git\n```\n\n2. Navigate to the root directory of the repository:\n\n```bash\ncd ultralytics\n```\n\n3. Install the package in developer mode using pip:\n\n```bash\npip install -e '.[dev]'\n```\n\nThis will install the ultralytics package and its dependencies in developer mode, allowing you to make changes to the\npackage code and have them reflected immediately in your Python environment.\n\nNote that you may need to use the pip3 command instead of pip if you have multiple versions of Python installed on your\nsystem.\n\n### Building and Serving Locally\n\nThe `mkdocs serve` command is used to build and serve a local version of the MkDocs documentation site. It is typically\nused during the development and testing phase of a documentation project.\n\n```bash\nmkdocs serve\n```\n\nHere is a breakdown of what this command does:\n\n- `mkdocs`: This is the command-line interface (CLI) for the MkDocs static site generator. It is used to build and serve\n  MkDocs sites.\n- `serve`: This is a subcommand of the `mkdocs` CLI that tells it to build and serve the documentation site locally.\n- `-a`: This flag specifies the hostname and port number to bind the server to. The default value is `localhost:8000`.\n- `-t`: This flag specifies the theme to use for the documentation site. The default value is `mkdocs`.\n- `-s`: This flag tells the `serve` command to serve the site in silent mode, which means it will not display any log\n  messages or progress updates.\n  When you run the `mkdocs serve` command, it will build the documentation site using the files in the `docs/` directory\n  and serve it at the specified hostname and port number. You can then view the site by going to the URL in your web\n  browser.\n\nWhile the site is being served, you can make changes to the documentation files and see them reflected in the live site\nimmediately. This is useful for testing and debugging your documentation before deploying it to a live server.\n\nTo stop the serve command and terminate the local server, you can use the `CTRL+C` keyboard shortcut.\n\n### Deploying Your Documentation Site\n\nTo deploy your MkDocs documentation site, you will need to choose a hosting provider and a deployment method. Some\npopular options include GitHub Pages, GitLab Pages, and Amazon S3.\n\nBefore you can deploy your site, you will need to configure your `mkdocs.yml` file to specify the remote host and any\nother necessary deployment settings.\n\nOnce you have configured your `mkdocs.yml` file, you can use the `mkdocs deploy` command to build and deploy your site.\nThis command will build the documentation site using the files in the `docs/` directory and the specified configuration\nfile and theme, and then deploy the site to the specified remote host.\n\nFor example, to deploy your site to GitHub Pages using the gh-deploy plugin, you can use the following command:\n\n```bash\nmkdocs gh-deploy\n```\n\nIf you are using GitHub Pages, you can set a custom domain for your documentation site by going to the \"Settings\" page\nfor your repository and updating the \"Custom domain\" field in the \"GitHub Pages\" section.\n\n![196814117-fc16e711-d2be-4722-9536-b7c6d78fd167](https://user-images.githubusercontent.com/26833433/210150206-9e86dcd7-10af-43e4-9eb2-9518b3799eac.png)\n\nFor more information on deploying your MkDocs documentation site, see\nthe [MkDocs documentation](https://www.mkdocs.org/user-guide/deploying-your-docs/)."
  },
  {
    "path": "docs/SECURITY.md",
    "content": "---\ndescription: Learn how Ultralytics prioritize security. Get insights into Snyk and GitHub CodeQL scans, and how to report security issues in YOLOv8.\n---\n\n# Security Policy\n\nAt [Ultralytics](https://ultralytics.com), the security of our users' data and systems is of utmost importance. To\nensure the safety and security of our [open-source projects](https://github.com/ultralytics), we have implemented\nseveral measures to detect and prevent security vulnerabilities.\n\n[![ultralytics](https://snyk.io/advisor/python/ultralytics/badge.svg)](https://snyk.io/advisor/python/ultralytics)\n\n## Snyk Scanning\n\nWe use [Snyk](https://snyk.io/advisor/python/ultralytics) to regularly scan the YOLOv8 repository for vulnerabilities\nand security issues. Our goal is to identify and remediate any potential threats as soon as possible, to minimize any\nrisks to our users.\n\n## GitHub CodeQL Scanning\n\nIn addition to our Snyk scans, we also use\nGitHub's [CodeQL](https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/about-code-scanning-with-codeql)\nscans to proactively identify and address security vulnerabilities.\n\n## Reporting Security Issues\n\nIf you suspect or discover a security vulnerability in the YOLOv8 repository, please let us know immediately. You can\nreach out to us directly via our [contact form](https://ultralytics.com/contact) or\nvia [security@ultralytics.com](mailto:security@ultralytics.com). Our security team will investigate and respond as soon\nas possible.\n\nWe appreciate your help in keeping the YOLOv8 repository secure and safe for everyone."
  },
  {
    "path": "docs/build_reference.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nHelper file to build Ultralytics Docs reference section. Recursively walks through ultralytics dir and builds an MkDocs\nreference section of *.md files composed of classes and functions, and also creates a nav menu for use in mkdocs.yaml.\n\nNote: Must be run from repository root directory. Do not run from docs directory.\n\"\"\"\n\nimport os\nimport re\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom ultralytics.yolo.utils import ROOT\n\nNEW_YAML_DIR = ROOT.parent\nCODE_DIR = ROOT\nREFERENCE_DIR = ROOT.parent / 'docs/reference'\n\n\ndef extract_classes_and_functions(filepath):\n    with open(filepath, 'r') as file:\n        content = file.read()\n\n    class_pattern = r\"(?:^|\\n)class\\s(\\w+)(?:\\(|:)\"\n    func_pattern = r\"(?:^|\\n)def\\s(\\w+)\\(\"\n\n    classes = re.findall(class_pattern, content)\n    functions = re.findall(func_pattern, content)\n\n    return classes, functions\n\n\ndef create_markdown(py_filepath, module_path, classes, functions):\n    md_filepath = py_filepath.with_suffix('.md')\n\n    # Read existing content and keep header content between first two ---\n    header_content = \"\"\n    if md_filepath.exists():\n        with open(md_filepath, 'r') as file:\n            existing_content = file.read()\n            header_parts = existing_content.split('---', 2)\n            if len(header_parts) >= 3:\n                header_content = f\"{header_parts[0]}---{header_parts[1]}---\\n\\n\"\n\n    md_content = [f\"# {class_name}\\n---\\n:::{module_path}.{class_name}\\n<br><br>\\n\" for class_name in classes]\n    md_content.extend(f\"# {func_name}\\n---\\n:::{module_path}.{func_name}\\n<br><br>\\n\" for func_name in functions)\n    md_content = header_content + \"\\n\".join(md_content)\n\n    os.makedirs(os.path.dirname(md_filepath), exist_ok=True)\n    with open(md_filepath, 'w') as file:\n        file.write(md_content)\n\n    return md_filepath.relative_to(NEW_YAML_DIR)\n\n\ndef nested_dict():\n    return defaultdict(nested_dict)\n\n\ndef sort_nested_dict(d):\n    return {\n        key: sort_nested_dict(value) if isinstance(value, dict) else value\n        for key, value in sorted(d.items())\n    }\n\n\ndef create_nav_menu_yaml(nav_items):\n    nav_tree = nested_dict()\n\n    for item_str in nav_items:\n        item = Path(item_str)\n        parts = item.parts\n        current_level = nav_tree['reference']\n        for part in parts[2:-1]:  # skip the first two parts (docs and reference) and the last part (filename)\n            current_level = current_level[part]\n\n        md_file_name = parts[-1].replace('.md', '')\n        current_level[md_file_name] = item\n\n    nav_tree_sorted = sort_nested_dict(nav_tree)\n\n    def _dict_to_yaml(d, level=0):\n        yaml_str = \"\"\n        indent = \"  \" * level\n        for k, v in d.items():\n            if isinstance(v, dict):\n                yaml_str += f\"{indent}- {k}:\\n{_dict_to_yaml(v, level + 1)}\"\n            else:\n                yaml_str += f\"{indent}- {k}: {str(v).replace('docs/', '')}\\n\"\n        return yaml_str\n\n    with open(NEW_YAML_DIR / 'nav_menu_updated.yml', 'w') as file:\n        yaml_str = _dict_to_yaml(nav_tree_sorted)\n        file.write(yaml_str)\n\n\ndef main():\n    nav_items = []\n    for root, _, files in os.walk(CODE_DIR):\n        for file in files:\n            if file.endswith(\".py\") and file != \"__init__.py\":\n                py_filepath = Path(root) / file\n                classes, functions = extract_classes_and_functions(py_filepath)\n\n                if classes or functions:\n                    py_filepath_rel = py_filepath.relative_to(CODE_DIR)\n                    md_filepath = REFERENCE_DIR / py_filepath_rel\n                    module_path = f\"ultralytics.{py_filepath_rel.with_suffix('').as_posix().replace('/', '.')}\"\n                    md_rel_filepath = create_markdown(md_filepath, module_path, classes, functions)\n                    nav_items.append(str(md_rel_filepath))\n\n    create_nav_menu_yaml(nav_items)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "docs/datasets/classify/caltech101.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/datasets/classify/caltech256.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/datasets/classify/cifar10.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/datasets/classify/cifar100.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/datasets/classify/fashion-mnist.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/datasets/classify/imagenet.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/datasets/classify/imagenet10.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/datasets/classify/imagenette.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/datasets/classify/imagewoof.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/datasets/classify/index.md",
    "content": "---\ncomments: true\ndescription: Learn how torchvision organizes classification image datasets. Use this code to create and train models. CLI and Python code shown.\n---\n\n# Image Classification Datasets Overview\n\n## Dataset format\n\nThe folder structure for classification datasets in torchvision typically follows a standard format:\n\n```\nroot/\n|-- class1/\n|   |-- img1.jpg\n|   |-- img2.jpg\n|   |-- ...\n|\n|-- class2/\n|   |-- img1.jpg\n|   |-- img2.jpg\n|   |-- ...\n|\n|-- class3/\n|   |-- img1.jpg\n|   |-- img2.jpg\n|   |-- ...\n|\n|-- ...\n```\n\nIn this folder structure, the `root` directory contains one subdirectory for each class in the dataset. Each subdirectory is named after the corresponding class and contains all the images for that class. Each image file is named uniquely and is typically in a common image file format such as JPEG or PNG.\n\n** Example **\n\nFor example, in the CIFAR10 dataset, the folder structure would look like this:\n\n```\ncifar-10-/\n|\n|-- train/\n|   |-- airplane/\n|   |   |-- 10008_airplane.png\n|   |   |-- 10009_airplane.png\n|   |   |-- ...\n|   |\n|   |-- automobile/\n|   |   |-- 1000_automobile.png\n|   |   |-- 1001_automobile.png\n|   |   |-- ...\n|   |\n|   |-- bird/\n|   |   |-- 10014_bird.png\n|   |   |-- 10015_bird.png\n|   |   |-- ...\n|   |\n|   |-- ...\n|\n|-- test/\n|   |-- airplane/\n|   |   |-- 10_airplane.png\n|   |   |-- 11_airplane.png\n|   |   |-- ...\n|   |\n|   |-- automobile/\n|   |   |-- 100_automobile.png\n|   |   |-- 101_automobile.png\n|   |   |-- ...\n|   |\n|   |-- bird/\n|   |   |-- 1000_bird.png\n|   |   |-- 1001_bird.png\n|   |   |-- ...\n|   |\n|   |-- ...\n```\n\nIn this example, the `train` directory contains subdirectories for each class in the dataset, and each class subdirectory contains all the images for that class. The `test` directory has a similar structure. The `root` directory also contains other files that are part of the CIFAR10 dataset.\n\n## Usage\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-cls.pt')  # load a pretrained model (recommended for training)\n\n        # Train the model\n        model.train(data='path/to/dataset', epochs=100, imgsz=640)\n        ```\n    === \"CLI\"\n    \n        ```bash\n        # Start training from a pretrained *.pt model\n        yolo detect train data=path/to/data model=yolov8n-seg.pt epochs=100 imgsz=640\n        ```\n\n## Supported Datasets\n\nTODO"
  },
  {
    "path": "docs/datasets/classify/mnist.md",
    "content": "---\ncomments: true\ndescription: Learn about the MNIST dataset, a large database of handwritten digits commonly used for training various image processing systems and machine learning models.\n---\n\n# MNIST Dataset\n\nThe [MNIST](http://yann.lecun.com/exdb/mnist/) (Modified National Institute of Standards and Technology) dataset is a large database of handwritten digits that is commonly used for training various image processing systems and machine learning models. It was created by \"re-mixing\" the samples from NIST's original datasets and has become a benchmark for evaluating the performance of image classification algorithms.\n\n## Key Features\n\n- MNIST contains 60,000 training images and 10,000 testing images of handwritten digits.\n- The dataset comprises grayscale images of size 28x28 pixels.\n- The images are normalized to fit into a 28x28 pixel bounding box and anti-aliased, introducing grayscale levels.\n- MNIST is widely used for training and testing in the field of machine learning, especially for image classification tasks.\n\n## Dataset Structure\n\nThe MNIST dataset is split into two subsets:\n\n1. **Training Set**: This subset contains 60,000 images of handwritten digits used for training machine learning models.\n2. **Testing Set**: This subset consists of 10,000 images used for testing and benchmarking the trained models.\n\n## Extended MNIST (EMNIST)\n\nExtended MNIST (EMNIST) is a newer dataset developed and released by NIST to be the successor to MNIST. While MNIST included images only of handwritten digits, EMNIST includes all the images from NIST Special Database 19, which is a large database of handwritten uppercase and lowercase letters as well as digits. The images in EMNIST were converted into the same 28x28 pixel format, by the same process, as were the MNIST images. Accordingly, tools that work with the older, smaller MNIST dataset will likely work unmodified with EMNIST.\n\n## Applications\n\nThe MNIST dataset is widely used for training and evaluating deep learning models in image classification tasks, such as Convolutional Neural Networks (CNNs), Support Vector Machines (SVMs), and various other machine learning algorithms. The dataset's simple and well-structured format makes it an essential resource for researchers and practitioners in the field of machine learning and computer vision.\n\n## Usage\n\nTo train a CNN model on the MNIST dataset for 100 epochs with an image size of 32x32, you can use the following code snippets. For a comprehensive list of available arguments, refer to the model [Training](../../modes/train.md) page.\n\n!!! example \"Train Example\"\n\n    === \"Python\"\n\n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-cls.pt')  # load a pretrained model (recommended for training)\n        \n        # Train the model\n        model.train(data='mnist', epochs=100, imgsz=32)\n        ```\n\n    === \"CLI\"\n\n        ```bash\n        # Start training from a pretrained *.pt model\n        cnn detect train data=MNIST.yaml model=cnn_mnist.pt epochs=100 imgsz=28\n        ```\n\n## Sample Images and Annotations\n\nThe MNIST dataset contains grayscale images of handwritten digits, providing a well-structured dataset for image classification tasks. Here are some examples of images from the dataset:\n\n![Dataset sample image](https://upload.wikimedia.org/wikipedia/commons/2/27/MnistExamples.png)\n\nThe example showcases the variety and complexity of the handwritten digits in the MNIST dataset, highlighting the importance of a diverse dataset for training robust image classification models.\n\n## Citations and Acknowledgments\n\nIf you use the MNIST dataset in your\n\nresearch or development work, please cite the following paper:\n\n```bibtex\n@article{lecun2010mnist,\n  title={MNIST handwritten digit database},\n  author={LeCun, Yann and Cortes, Corinna and Burges, CJ},\n  journal={ATT Labs [Online]. Available: http://yann.lecun.com/exdb/mnist},\n  volume={2},\n  year={2010}\n}\n```\n\nWe would like to acknowledge Yann LeCun, Corinna Cortes, and Christopher J.C. Burges for creating and maintaining the MNIST dataset as a valuable resource for the machine learning and computer vision research community. For more information about the MNIST dataset and its creators, visit the [MNIST dataset website](http://yann.lecun.com/exdb/mnist/)."
  },
  {
    "path": "docs/datasets/detect/argoverse.md",
    "content": "---\ncomments: true\ndescription: Learn about the Argoverse dataset, a rich dataset designed to support research in autonomous driving tasks such as 3D tracking, motion forecasting, and stereo depth estimation.\n---\n\n# Argoverse Dataset\n\nThe [Argoverse](https://www.argoverse.org/) dataset is a collection of data designed to support research in autonomous driving tasks, such as 3D tracking, motion forecasting, and stereo depth estimation. Developed by Argo AI, the dataset provides a wide range of high-quality sensor data, including high-resolution images, LiDAR point clouds, and map data.\n\n## Key Features\n\n- Argoverse contains over 290K labeled 3D object tracks and 5 million object instances across 1,263 distinct scenes.\n- The dataset includes high-resolution camera images, LiDAR point clouds, and richly annotated HD maps.\n- Annotations include 3D bounding boxes for objects, object tracks, and trajectory information.\n- Argoverse provides multiple subsets for different tasks, such as 3D tracking, motion forecasting, and stereo depth estimation.\n\n## Dataset Structure\n\nThe Argoverse dataset is organized into three main subsets:\n\n1. **Argoverse 3D Tracking**: This subset contains 113 scenes with over 290K labeled 3D object tracks, focusing on 3D object tracking tasks. It includes LiDAR point clouds, camera images, and sensor calibration information.\n2. **Argoverse Motion Forecasting**: This subset consists of 324K vehicle trajectories collected from 60 hours of driving data, suitable for motion forecasting tasks.\n3. **Argoverse Stereo Depth Estimation**: This subset is designed for stereo depth estimation tasks and includes over 10K stereo image pairs with corresponding LiDAR point clouds for ground truth depth estimation.\n\n## Applications\n\nThe Argoverse dataset is widely used for training and evaluating deep learning models in autonomous driving tasks such as 3D object tracking, motion forecasting, and stereo depth estimation. The dataset's diverse set of sensor data, object annotations, and map information make it a valuable resource for researchers and practitioners in the field of autonomous driving.\n\n## Dataset YAML\n\nA YAML (Yet Another Markup Language) file is used to define the dataset configuration. It contains information about the dataset's paths, classes, and other relevant information. For the case of the Argoverse dataset, the `Argoverse.yaml` file is maintained at [https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/Argoverse.yaml](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/Argoverse.yaml).\n\n!!! example \"ultralytics/datasets/Argoverse.yaml\"\n\n    ```yaml\n    --8<-- \"ultralytics/datasets/Argoverse.yaml\"\n    ```\n\n## Usage\n\nTo train a YOLOv8n model on the Argoverse dataset for 100 epochs with an image size of 640, you can use the following code snippets. For a comprehensive list of available arguments, refer to the model [Training](../../modes/train.md) page.\n\n!!! example \"Train Example\"\n\n    === \"Python\"\n\n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n        \n        # Train the model\n        model.train(data='Argoverse.yaml', epochs=100, imgsz=640)\n        ```\n\n    === \"CLI\"\n\n        ```bash\n        # Start training from a pretrained *.pt model\n        yolo detect train data=Argoverse.yaml model=yolov8n.pt epochs=100 imgsz=640\n        ```\n\n## Sample Data and Annotations\n\nThe Argoverse dataset contains a diverse set of sensor data, including camera images, LiDAR point clouds, and HD map information, providing rich context for autonomous driving tasks. Here are some examples of data from the dataset, along with their corresponding annotations:\n\n![Dataset sample image](https://www.argoverse.org/assets/images/reference_images/av2_ground_height.png)\n\n- **Argoverse 3D Tracking**: This image demonstrates an example of 3D object tracking, where objects are annotated with 3D bounding boxes. The dataset provides LiDAR point clouds and camera images to facilitate the development of models for this task.\n\nThe example showcases the variety and complexity of the data in the Argoverse dataset and highlights the importance of high-quality sensor data for autonomous driving tasks.\n\n## Citations and Acknowledgments\n\nIf you use the Argoverse dataset in your research or development work, please cite the following paper:\n\n```bibtex\n@inproceedings{chang2019argoverse,\n  title={Argoverse: 3D Tracking and Forecasting with Rich Maps},\n  author={Chang, Ming-Fang and Lambert, John and Sangkloy, Patsorn and Singh, Jagjeet and Bak, Slawomir and Hartnett, Andrew and Wang, Dequan and Carr, Peter and Lucey, Simon and Ramanan, Deva and others},\n  booktitle={Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition},\n  pages={8748--8757},\n  year={2019}\n}\n```\n\nWe would like to acknowledge Argo AI for creating and maintaining the Argoverse dataset as a valuable resource for the autonomous driving research community. For more information about the Argoverse dataset and its creators, visit the [Argoverse dataset website](https://www.argoverse.org/)."
  },
  {
    "path": "docs/datasets/detect/coco.md",
    "content": "---\ncomments: true\ndescription: Learn about the COCO dataset, designed to encourage research on object detection, segmentation, and captioning with standardized evaluation metrics.\n---\n\n# COCO Dataset\n\nThe [COCO](https://cocodataset.org/#home) (Common Objects in Context) dataset is a large-scale object detection, segmentation, and captioning dataset. It is designed to encourage research on a wide variety of object categories and is commonly used for benchmarking computer vision models. It is an essential dataset for researchers and developers working on object detection, segmentation, and pose estimation tasks.\n\n## Key Features\n\n- COCO contains 330K images, with 200K images having annotations for object detection, segmentation, and captioning tasks.\n- The dataset comprises 80 object categories, including common objects like cars, bicycles, and animals, as well as more specific categories such as umbrellas, handbags, and sports equipment.\n- Annotations include object bounding boxes, segmentation masks, and captions for each image.\n- COCO provides standardized evaluation metrics like mean Average Precision (mAP) for object detection, and mean Average Recall (mAR) for segmentation tasks, making it suitable for comparing model performance.\n\n## Dataset Structure\n\nThe COCO dataset is split into three subsets:\n\n1. **Train2017**: This subset contains 118K images for training object detection, segmentation, and captioning models.\n2. **Val2017**: This subset has 5K images used for validation purposes during model training.\n3. **Test2017**: This subset consists of 20K images used for testing and benchmarking the trained models. Ground truth annotations for this subset are not publicly available, and the results are submitted to the [COCO evaluation server](https://competitions.codalab.org/competitions/5181) for performance evaluation.\n\n## Applications\n\nThe COCO dataset is widely used for training and evaluating deep learning models in object detection (such as YOLO, Faster R-CNN, and SSD), instance segmentation (such as Mask R-CNN), and keypoint detection (such as OpenPose). The dataset's diverse set of object categories, large number of annotated images, and standardized evaluation metrics make it an essential resource for computer vision researchers and practitioners.\n\n## Dataset YAML\n\nA YAML (Yet Another Markup Language) file is used to define the dataset configuration. It contains information about the dataset's paths, classes, and other relevant information. In the case of the COCO dataset, the `coco.yaml` file is maintained at [https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco.yaml](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco.yaml).\n\n!!! example \"ultralytics/datasets/coco.yaml\"\n\n    ```yaml\n    --8<-- \"ultralytics/datasets/coco.yaml\"\n    ```\n\n## Usage\n\nTo train a YOLOv8n model on the COCO dataset for 100 epochs with an image size of 640, you can use the following code snippets. For a comprehensive list of available arguments, refer to the model [Training](../../modes/train.md) page.\n\n!!! example \"Train Example\"\n\n    === \"Python\"\n\n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n        \n        # Train the model\n        model.train(data='coco.yaml', epochs=100, imgsz=640)\n        ```\n\n    === \"CLI\"\n\n        ```bash\n        # Start training from a pretrained *.pt model\n        yolo detect train data=coco.yaml model=yolov8n.pt epochs=100 imgsz=640\n        ```\n\n## Sample Images and Annotations\n\nThe COCO dataset contains a diverse set of images with various object categories and complex scenes. Here are some examples of images from the dataset, along with their corresponding annotations:\n\n![Dataset sample image](https://user-images.githubusercontent.com/26833433/236811818-5b566576-1e92-42fa-9462-4b6a848abe89.jpg)\n\n- **Mosaiced Image**: This image demonstrates a training batch composed of mosaiced dataset images. Mosaicing is a technique used during training that combines multiple images into a single image to increase the variety of objects and scenes within each training batch. This helps improve the model's ability to generalize to different object sizes, aspect ratios, and contexts.\n\nThe example showcases the variety and complexity of the images in the COCO dataset and the benefits of using mosaicing during the training process.\n\n## Citations and Acknowledgments\n\nIf you use the COCO dataset in your research or development work, please cite the following paper:\n\n```bibtex\n@misc{lin2015microsoft,\n      title={Microsoft COCO: Common Objects in Context}, \n      author={Tsung-Yi Lin and Michael Maire and Serge Belongie and Lubomir Bourdev and Ross Girshick and James Hays and Pietro Perona and Deva Ramanan and C. Lawrence Zitnick and Piotr Dollár},\n      year={2015},\n      eprint={1405.0312},\n      archivePrefix={arXiv},\n      primaryClass={cs.CV}\n}\n```\n\nWe would like to acknowledge the COCO Consortium for creating and maintaining this valuable resource for the computer vision community. For more information about the COCO dataset and its creators, visit the [COCO dataset website](https://cocodataset.org/#home)."
  },
  {
    "path": "docs/datasets/detect/coco8.md",
    "content": "---\ncomments: true\ndescription: Get started with Ultralytics COCO8. Ideal for testing and debugging object detection models or experimenting with new detection approaches.\n---\n\n# COCO8 Dataset\n\n## Introduction\n\n[Ultralytics](https://ultralytics.com) COCO8 is a small, but versatile object detection dataset composed of the first 8\nimages of the COCO train 2017 set, 4 for training and 4 for validation. This dataset is ideal for testing and debugging\nobject detection models, or for experimenting with new detection approaches. With 8 images, it is small enough to be\neasily manageable, yet diverse enough to test training pipelines for errors and act as a sanity check before training\nlarger datasets.\n\nThis dataset is intended for use with Ultralytics [HUB](https://hub.ultralytics.com)\nand [YOLOv8](https://github.com/ultralytics/ultralytics).\n\n## Dataset YAML\n\nA YAML (Yet Another Markup Language) file is used to define the dataset configuration. It contains information about the dataset's paths, classes, and other relevant information. In the case of the COCO8 dataset, the `coco8.yaml` file is maintained at [https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco8.yaml](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco8.yaml).\n\n!!! example \"ultralytics/datasets/coco8.yaml\"\n\n    ```yaml\n    --8<-- \"ultralytics/datasets/coco8.yaml\"\n    ```\n\n## Usage\n\nTo train a YOLOv8n model on the COCO8 dataset for 100 epochs with an image size of 640, you can use the following code snippets. For a comprehensive list of available arguments, refer to the model [Training](../../modes/train.md) page.\n\n!!! example \"Train Example\"\n\n    === \"Python\"\n\n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n        \n        # Train the model\n        model.train(data='coco8.yaml', epochs=100, imgsz=640)\n        ```\n\n    === \"CLI\"\n\n        ```bash\n        # Start training from a pretrained *.pt model\n        yolo detect train data=coco8.yaml model=yolov8n.pt epochs=100 imgsz=640\n        ```\n\n## Sample Images and Annotations\n\nHere are some examples of images from the COCO8 dataset, along with their corresponding annotations:\n\n<img src=\"https://user-images.githubusercontent.com/26833433/236818348-e6260a3d-0454-436b-83a9-de366ba07235.jpg\" alt=\"Dataset sample image\" width=\"800\">\n\n- **Mosaiced Image**: This image demonstrates a training batch composed of mosaiced dataset images. Mosaicing is a technique used during training that combines multiple images into a single image to increase the variety of objects and scenes within each training batch. This helps improve the model's ability to generalize to different object sizes, aspect ratios, and contexts.\n\nThe example showcases the variety and complexity of the images in the COCO8 dataset and the benefits of using mosaicing during the training process.\n\n## Citations and Acknowledgments\n\nIf you use the COCO dataset in your research or development work, please cite the following paper:\n\n```bibtex\n@misc{lin2015microsoft,\n      title={Microsoft COCO: Common Objects in Context}, \n      author={Tsung-Yi Lin and Michael Maire and Serge Belongie and Lubomir Bourdev and Ross Girshick and James Hays and Pietro Perona and Deva Ramanan and C. Lawrence Zitnick and Piotr Dollár},\n      year={2015},\n      eprint={1405.0312},\n      archivePrefix={arXiv},\n      primaryClass={cs.CV}\n}\n```\n\nWe would like to acknowledge the COCO Consortium for creating and maintaining this valuable resource for the computer vision community. For more information about the COCO dataset and its creators, visit the [COCO dataset website](https://cocodataset.org/#home)."
  },
  {
    "path": "docs/datasets/detect/globalwheat2020.md",
    "content": "---\ncomments: true\ndescription: Learn about the Global Wheat Head Dataset, aimed at supporting the development of accurate wheat head models for applications in wheat phenotyping and crop management.\n---\n\n# Global Wheat Head Dataset\n\nThe [Global Wheat Head Dataset](http://www.global-wheat.com/) is a collection of images designed to support the development of accurate wheat head detection models for applications in wheat phenotyping and crop management. Wheat heads, also known as spikes, are the grain-bearing parts of the wheat plant. Accurate estimation of wheat head density and size is essential for assessing crop health, maturity, and yield potential. The dataset, created by a collaboration of nine research institutes from seven countries, covers multiple growing regions to ensure models generalize well across different environments.\n\n## Key Features\n\n- The dataset contains over 3,000 training images from Europe (France, UK, Switzerland) and North America (Canada).\n- It includes approximately 1,000 test images from Australia, Japan, and China.\n- Images are outdoor field images, capturing the natural variability in wheat head appearances.\n- Annotations include wheat head bounding boxes to support object detection tasks.\n\n## Dataset Structure\n\nThe Global Wheat Head Dataset is organized into two main subsets:\n\n1. **Training Set**: This subset contains over 3,000 images from Europe and North America. The images are labeled with wheat head bounding boxes, providing ground truth for training object detection models.\n2. **Test Set**: This subset consists of approximately 1,000 images from Australia, Japan, and China. These images are used for evaluating the performance of trained models on unseen genotypes, environments, and observational conditions.\n\n## Applications\n\nThe Global Wheat Head Dataset is widely used for training and evaluating deep learning models in wheat head detection tasks. The dataset's diverse set of images, capturing a wide range of appearances, environments, and conditions, make it a valuable resource for researchers and practitioners in the field of plant phenotyping and crop management.\n\n## Dataset YAML\n\nA YAML (Yet Another Markup Language) file is used to define the dataset configuration. It contains information about the dataset's paths, classes, and other relevant information. For the case of the Global Wheat Head Dataset, the `GlobalWheat2020.yaml` file is maintained at [https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/GlobalWheat2020.yaml](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/GlobalWheat2020.yaml).\n\n!!! example \"ultralytics/datasets/GlobalWheat2020.yaml\"\n\n    ```yaml\n    --8<-- \"ultralytics/datasets/GlobalWheat2020.yaml\"\n    ```\n\n## Usage\n\nTo train a YOLOv8n model on the Global Wheat Head Dataset for 100 epochs with an image size of 640, you can use the following code snippets. For a comprehensive list of available arguments, refer to the model [Training](../../modes/train.md) page.\n\n!!! example \"Train Example\"\n\n    === \"Python\"\n\n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n        \n        # Train the model\n        model.train(data='GlobalWheat2020.yaml', epochs=100, imgsz=640)\n        ```\n\n    === \"CLI\"\n\n        ```bash\n        # Start training from a pretrained *.pt model\n        yolo detect train data=GlobalWheat2020.yaml model=yolov8n.pt epochs=100 imgsz=640\n        ```\n\n## Sample Data and Annotations\n\nThe Global Wheat Head Dataset contains a diverse set of outdoor field images, capturing the natural variability in wheat head appearances, environments, and conditions. Here are some examples of data from the dataset, along with their corresponding annotations:\n\n![Dataset sample image](https://i.ytimg.com/vi/yqvMuw-uedU/maxresdefault.jpg)\n\n- **Wheat Head Detection**: This image demonstrates an example of wheat head detection, where wheat heads are annotated with bounding boxes. The dataset provides a variety of images to facilitate the development of models for this task.\n\nThe example showcases the variety and complexity of the data in the Global Wheat Head Dataset and highlights the importance of accurate wheat head detection for applications in wheat phenotyping and crop management.\n\n## Citations and Acknowledgments\n\nIf you use the Global Wheat Head Dataset in your research or development work, please cite the following paper:\n\n```bibtex\n@article{david2020global,\n  title={Global Wheat Head Detection (GWHD) Dataset: A Large and Diverse Dataset of High-Resolution RGB-Labelled Images to Develop and Benchmark Wheat Head Detection Methods},\n  author={David, Etienne and Madec, Simon and Sadeghi-Tehran, Pouria and Aasen, Helge and Zheng, Bangyou and Liu, Shouyang and Kirchgessner, Norbert and Ishikawa, Goro and Nagasawa, Koichi and Badhon, Minhajul and others},\n  journal={arXiv preprint arXiv:2005.02162},\n  year={2020}\n}\n```\n\nWe would like to acknowledge the researchers and institutions that contributed to the creation and maintenance of the Global Wheat Head Dataset as a valuable resource for the plant phenotyping and crop management research community. For more information about the dataset and its creators, visit the [Global Wheat Head Dataset website](http://www.global-wheat.com/)."
  },
  {
    "path": "docs/datasets/detect/index.md",
    "content": "---\ncomments: true\ndescription: Learn about supported dataset formats for training YOLO detection models, including Ultralytics YOLO and COCO, in this Object Detection Datasets Overview.\n---\n\n# Object Detection Datasets Overview\n\n## Supported Dataset Formats\n\n### Ultralytics YOLO format\n\n** Label Format **\n\nThe dataset format used for training YOLO detection models is as follows:\n\n1. One text file per image: Each image in the dataset has a corresponding text file with the same name as the image file and the \".txt\" extension.\n2. One row per object: Each row in the text file corresponds to one object instance in the image.\n3. Object information per row: Each row contains the following information about the object instance:\n    - Object class index: An integer representing the class of the object (e.g., 0 for person, 1 for car, etc.).\n    - Object center coordinates: The x and y coordinates of the center of the object, normalized to be between 0 and 1.\n    - Object width and height: The width and height of the object, normalized to be between 0 and 1.\n\nThe format for a single row in the detection dataset file is as follows:\n\n```\n<object-class> <x> <y> <width> <height>\n```\n\nHere is an example of the YOLO dataset format for a single image with two object instances:\n\n```\n0 0.5 0.4 0.3 0.6\n1 0.3 0.7 0.4 0.2\n```\n\nIn this example, the first object is of class 0 (person), with its center at (0.5, 0.4), width of 0.3, and height of 0.6. The second object is of class 1 (car), with its center at (0.3, 0.7), width of 0.4, and height of 0.2.\n\n** Dataset file format **\n\nThe Ultralytics framework uses a YAML file format to define the dataset and model configuration for training Detection Models. Here is an example of the YAML format used for defining a detection dataset:\n\n```\ntrain: <path-to-training-images>\nval: <path-to-validation-images>\n\nnc: <number-of-classes>\nnames: [<class-1>, <class-2>, ..., <class-n>]\n\n```\n\nThe `train` and `val` fields specify the paths to the directories containing the training and validation images, respectively.\n\nThe `nc` field specifies the number of object classes in the dataset.\n\nThe `names` field is a list of the names of the object classes. The order of the names should match the order of the object class indices in the YOLO dataset files.\n\nNOTE: Either `nc` or `names` must be defined. Defining both are not mandatory\n\nAlternatively, you can directly define class names like this:\n\n```yaml\nnames:\n  0: person\n  1: bicycle\n```\n\n** Example **\n\n```yaml\ntrain: data/train/\nval: data/val/\n\nnc: 2\nnames: ['person', 'car']\n```\n\n## Usage\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n\n        # Train the model\n        model.train(data='coco128.yaml', epochs=100, imgsz=640)\n        ```\n    === \"CLI\"\n    \n        ```bash\n        # Start training from a pretrained *.pt model\n        yolo detect train data=coco128.yaml model=yolov8n.pt epochs=100 imgsz=640\n        ```\n\n## Supported Datasets\n\nTODO\n\n## Port or Convert label formats\n\n### COCO dataset format to YOLO format\n\n```\nfrom ultralytics.yolo.data.converter import convert_coco\n\nconvert_coco(labels_dir='../coco/annotations/')\n```"
  },
  {
    "path": "docs/datasets/detect/objects365.md",
    "content": "---\ncomments: true\ndescription: Discover the Objects365 dataset, designed for object detection research with a focus on diverse objects, featuring 365 categories, 2 million images, and 30 million bounding boxes.\n---\n\n# Objects365 Dataset\n\nThe [Objects365](https://www.objects365.org/) dataset is a large-scale, high-quality dataset designed to foster object detection research with a focus on diverse objects in the wild. Created by a team of [Megvii](https://en.megvii.com/) researchers, the dataset offers a wide range of high-resolution images with a comprehensive set of annotated bounding boxes covering 365 object categories.\n\n## Key Features\n\n- Objects365 contains 365 object categories, with 2 million images and over 30 million bounding boxes.\n- The dataset includes diverse objects in various scenarios, providing a rich and challenging benchmark for object detection tasks.\n- Annotations include bounding boxes for objects, making it suitable for training and evaluating object detection models.\n- Objects365 pre-trained models significantly outperform ImageNet pre-trained models, leading to better generalization on various tasks.\n\n## Dataset Structure\n\nThe Objects365 dataset is organized into a single set of images with corresponding annotations:\n\n- **Images**: The dataset includes 2 million high-resolution images, each containing a variety of objects across 365 categories.\n- **Annotations**: The images are annotated with over 30 million bounding boxes, providing comprehensive ground truth information for object detection tasks.\n\n## Applications\n\nThe Objects365 dataset is widely used for training and evaluating deep learning models in object detection tasks. The dataset's diverse set of object categories and high-quality annotations make it a valuable resource for researchers and practitioners in the field of computer vision.\n\n## Dataset YAML\n\nA YAML (Yet Another Markup Language) file is used to define the dataset configuration. It contains information about the dataset's paths, classes, and other relevant information. For the case of the Objects365 Dataset, the `Objects365.yaml` file is maintained at [https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/Objects365.yaml](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/Objects365.yaml).\n\n!!! example \"ultralytics/datasets/Objects365.yaml\"\n\n    ```yaml\n    --8<-- \"ultralytics/datasets/Objects365.yaml\"\n    ```\n\n## Usage\n\nTo train a YOLOv8n model on the Objects365 dataset for 100 epochs with an image size of 640, you can use the following code snippets. For a comprehensive list of available arguments, refer to the model [Training](../../modes/train.md) page.\n\n!!! example \"Train Example\"\n\n    === \"Python\"\n\n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n        \n        # Train the model\n        model.train(data='Objects365.yaml', epochs=100, imgsz=640)\n        ```\n\n    === \"CLI\"\n\n        ```bash\n        # Start training from a pretrained *.pt model\n        yolo detect train data=Objects365.yaml model=yolov8n.pt epochs=100 imgsz=640\n        ```\n\n## Sample Data and Annotations\n\nThe Objects365 dataset contains a diverse set of high-resolution images with objects from 365 categories, providing rich context for object detection tasks. Here are some examples of the images in the dataset:\n\n![Dataset sample image](https://user-images.githubusercontent.com/26833433/238215467-caf757dd-0b87-4b0d-bb19-d94a547f7fbf.jpg)\n\n- **Objects365**: This image demonstrates an example of object detection, where objects are annotated with bounding boxes. The dataset provides a wide range of images to facilitate the development of models for this task.\n\nThe example showcases the variety and complexity of the data in the Objects365 dataset and highlights the importance of accurate object detection for computer vision applications.\n\n## Citations and Acknowledgments\n\nIf you use the Objects365 dataset in your research or development work, please cite the following paper:\n\n```bibtex\n@inproceedings{shao2019objects365,\n  title={Objects365: A Large-scale, High-quality Dataset for Object Detection},\n  author={Shao, Shuai and Li, Zeming and Zhang, Tianyuan and Peng, Chao and Yu, Gang and Li, Jing and Zhang, Xiangyu and Sun, Jian},\n  booktitle={Proceedings of the IEEE/CVF International Conference on Computer Vision},\n  pages={8425--8434},\n  year={2019}\n}\n```\n\nWe would like to acknowledge the team of researchers who created and maintain the Objects365 dataset as a valuable resource for the computer vision research community. For more information about the Objects365 dataset and its creators, visit the [Objects365 dataset website](https://www.objects365.org/).\n"
  },
  {
    "path": "docs/datasets/detect/sku-110k.md",
    "content": "---\ncomments: true\ndescription: Explore the SKU-110k dataset, designed for object detection in densely packed retail shelf images, featuring over 110k unique SKU categories and annotations.\n---\n\n# SKU-110k Dataset\n\nThe [SKU-110k](https://github.com/eg4000/SKU110K_CVPR19) dataset is a collection of densely packed retail shelf images, designed to support research in object detection tasks. Developed by Eran Goldman et al., the dataset contains over 110,000 unique store keeping unit (SKU) categories with densely packed objects, often looking similar or even identical, positioned in close proximity.\n\n![Dataset sample image](https://github.com/eg4000/SKU110K_CVPR19/raw/master/figures/benchmarks_comparison.jpg)\n\n## Key Features\n\n- SKU-110k contains images of store shelves from around the world, featuring densely packed objects that pose challenges for state-of-the-art object detectors.\n- The dataset includes over 110,000 unique SKU categories, providing a diverse range of object appearances.\n- Annotations include bounding boxes for objects and SKU category labels.\n\n## Dataset Structure\n\nThe SKU-110k dataset is organized into three main subsets:\n\n1. **Training set**: This subset contains images and annotations used for training object detection models.\n2. **Validation set**: This subset consists of images and annotations used for model validation during training.\n3. **Test set**: This subset is designed for the final evaluation of trained object detection models.\n\n## Applications\n\nThe SKU-110k dataset is widely used for training and evaluating deep learning models in object detection tasks, especially in densely packed scenes such as retail shelf displays. The dataset's diverse set of SKU categories and densely packed object arrangements make it a valuable resource for researchers and practitioners in the field of computer vision.\n\n## Dataset YAML\n\nA YAML (Yet Another Markup Language) file is used to define the dataset configuration. It contains information about the dataset's paths, classes, and other relevant information. For the case of the SKU-110K dataset, the `SKU-110K.yaml` file is maintained at [https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/SKU-110K.yaml](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/SKU-110K.yaml).\n\n!!! example \"ultralytics/datasets/SKU-110K.yaml\"\n\n    ```yaml\n    --8<-- \"ultralytics/datasets/SKU-110K.yaml\"\n    ```\n\n## Usage\n\nTo train a YOLOv8n model on the SKU-110K dataset for 100 epochs with an image size of 640, you can use the following code snippets. For a comprehensive list of available arguments, refer to the model [Training](../../modes/train.md) page.\n\n!!! example \"Train Example\"\n\n    === \"Python\"\n\n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n        \n        # Train the model\n        model.train(data='SKU-110K.yaml', epochs=100, imgsz=640)\n        ```\n\n    === \"CLI\"\n\n        ```bash\n        # Start training from a pretrained *.pt model\n        yolo detect train data=SKU-110K.yaml model=yolov8n.pt epochs=100 imgsz=640\n\n## Sample Data and Annotations\n\nThe SKU-110k dataset contains a diverse set of retail shelf images with densely packed objects, providing rich context for object detection tasks. Here are some examples of data from the dataset, along with their corresponding annotations:\n\n![Dataset sample image](https://user-images.githubusercontent.com/26833433/238215979-1ab791c4-15d9-46f6-a5d6-0092c05dff7a.jpg)\n\n- **Densely packed retail shelf image**: This image demonstrates an example of densely packed objects in a retail shelf setting. Objects are annotated with bounding boxes and SKU category labels.\n\nThe example showcases the variety and complexity of the data in the SKU-110k dataset and highlights the importance of high-quality data for object detection tasks.\n\n## Citations and Acknowledgments\n\nIf you use the SKU-110k dataset in your research or development work, please cite the following paper:\n\n```bibtex\n@inproceedings{goldman2019dense,\n author    = {Eran Goldman and Roei Herzig and Aviv Eisenschtat and Jacob Goldberger and Tal Hassner},\n title     = {Precise Detection in Densely Packed Scenes},\n booktitle = {Proc. Conf. Comput. Vision Pattern Recognition (CVPR)},\n year      = {2019}\n}\n```\n\nWe would like to acknowledge Eran Goldman et al. for creating and maintaining the SKU-110k dataset as a valuable resource for the computer vision research community. For more information about the SKU-110k dataset and its creators, visit the [SKU-110k dataset GitHub repository](https://github.com/eg4000/SKU110K_CVPR19)."
  },
  {
    "path": "docs/datasets/detect/visdrone.md",
    "content": "---\ncomments: true\ndescription: Discover the VisDrone dataset, a comprehensive benchmark for drone-based computer vision tasks, including object detection, tracking, and crowd counting.\n---\n\n# VisDrone Dataset\n\nThe [VisDrone Dataset](https://github.com/VisDrone/VisDrone-Dataset) is a large-scale benchmark created by the AISKYEYE team at the Lab of Machine Learning and Data Mining, Tianjin University, China. It contains carefully annotated ground truth data for various computer vision tasks related to drone-based image and video analysis.\n\nVisDrone is composed of 288 video clips with 261,908 frames and 10,209 static images, captured by various drone-mounted cameras. The dataset covers a wide range of aspects, including location (14 different cities across China), environment (urban and rural), objects (pedestrians, vehicles, bicycles, etc.), and density (sparse and crowded scenes). The dataset was collected using various drone platforms under different scenarios and weather and lighting conditions. These frames are manually annotated with over 2.6 million bounding boxes of targets such as pedestrians, cars, bicycles, and tricycles. Attributes like scene visibility, object class, and occlusion are also provided for better data utilization.\n\n## Citation\n\nIf you use the VisDrone dataset in your research or development work, please cite the following paper:\n\n```bibtex\n@ARTICLE{9573394,\n  author={Zhu, Pengfei and Wen, Longyin and Du, Dawei and Bian, Xiao and Fan, Heng and Hu, Qinghua and Ling, Haibin},\n  journal={IEEE Transactions on Pattern Analysis and Machine Intelligence}, \n  title={Detection and Tracking Meet Drones Challenge}, \n  year={2021},\n  volume={},\n  number={},\n  pages={1-1},\n  doi={10.1109/TPAMI.2021.3119563}}\n```\n\n## Dataset Structure\n\nThe VisDrone dataset is organized into five main subsets, each focusing on a specific task:\n\n1. **Task 1**: Object detection in images\n2. **Task 2**: Object detection in videos\n3. **Task 3**: Single-object tracking\n4. **Task 4**: Multi-object tracking\n5. **Task 5**: Crowd counting\n\n## Applications\n\nThe VisDrone dataset is widely used for training and evaluating deep learning models in drone-based computer vision tasks such as object detection, object tracking, and crowd counting. The dataset's diverse set of sensor data, object annotations, and attributes make it a valuable resource for researchers and practitioners in the field of drone-based computer vision.\n\n## Dataset YAML\n\nA YAML (Yet Another Markup Language) file is used to define the dataset configuration. It contains information about the dataset's paths, classes, and other relevant information. In the case of the Visdrone dataset, the `VisDrone.yaml` file is maintained at [https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/VisDrone.yaml](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/VisDrone.yaml).\n\n!!! example \"ultralytics/datasets/VisDrone.yaml\"\n\n    ```yaml\n    --8<-- \"ultralytics/datasets/VisDrone.yaml\"\n    ```\n\n## Usage\n\nTo train a YOLOv8n model on the VisDrone dataset for 100 epochs with an image size of 640, you can use the following code snippets. For a comprehensive list of available arguments, refer to the model [Training](../../modes/train.md) page.\n\n!!! example \"Train Example\"\n\n    === \"Python\"\n\n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n        \n        # Train the model\n        model.train(data='VisDrone.yaml', epochs=100, imgsz=640)\n        ```\n\n    === \"CLI\"\n\n        ```bash\n        # Start training from a pretrained *.pt model\n        yolo detect train data=VisDrone.yaml model=yolov8n.pt epochs=100 imgsz=640\n        ```\n\n## Sample Data and Annotations\n\nThe VisDrone dataset contains a diverse set of images and videos captured by drone-mounted cameras. Here are some examples of data from the dataset, along with their corresponding annotations:\n\n![Dataset sample image](https://user-images.githubusercontent.com/26833433/238217600-df0b7334-4c9e-4c77-81a5-c70cd33429cc.jpg)\n\n- **Task 1**: Object detection in images - This image demonstrates an example of object detection in images, where objects are annotated with bounding boxes. The dataset provides a wide variety of images taken from different locations, environments, and densities to facilitate the development of models for this task.\n\nThe example showcases the variety and complexity of the data in the VisDrone dataset and highlights the importance of high-quality sensor data for drone-based computer vision tasks.\n\n## Citations and Acknowledgments\n\nIf you use the VisDrone dataset in your research or development work, please cite the following paper:\n\n```bibtex\n@ARTICLE{9573394,\n  author={Zhu, Pengfei and Wen, Longyin and Du, Dawei and Bian, Xiao and Fan, Heng and Hu, Qinghua and Ling, Haibin},\n  journal={IEEE Transactions on Pattern Analysis and Machine Intelligence}, \n  title={Detection and Tracking Meet Drones Challenge}, \n  year={2021},\n  volume={},\n  number={},\n  pages={1-1},\n  doi={10.1109/TPAMI.2021.3119563}}\n```\n\nWe would like to acknowledge the AISKYEYE team at the Lab of Machine Learning and Data Mining, Tianjin University, China, for creating and maintaining the VisDrone dataset as a valuable resource for the drone-based computer vision research community. For more information about the VisDrone dataset and its creators, visit the [VisDrone Dataset GitHub repository](https://github.com/VisDrone/VisDrone-Dataset)."
  },
  {
    "path": "docs/datasets/detect/voc.md",
    "content": "---\ncomments: true\ndescription: Learn about the VOC dataset, designed to encourage research on object detection, segmentation, and classification with standardized evaluation metrics.\n---\n\n# VOC Dataset\n\nThe [PASCAL VOC](http://host.robots.ox.ac.uk/pascal/VOC/) (Visual Object Classes) dataset is a well-known object detection, segmentation, and classification dataset. It is designed to encourage research on a wide variety of object categories and is commonly used for benchmarking computer vision models. It is an essential dataset for researchers and developers working on object detection, segmentation, and classification tasks.\n\n## Key Features\n\n- VOC dataset includes two main challenges: VOC2007 and VOC2012.\n- The dataset comprises 20 object categories, including common objects like cars, bicycles, and animals, as well as more specific categories such as boats, sofas, and dining tables.\n- Annotations include object bounding boxes and class labels for object detection and classification tasks, and segmentation masks for the segmentation tasks.\n- VOC provides standardized evaluation metrics like mean Average Precision (mAP) for object detection and classification, making it suitable for comparing model performance.\n\n## Dataset Structure\n\nThe VOC dataset is split into three subsets:\n\n1. **Train**: This subset contains images for training object detection, segmentation, and classification models.\n2. **Validation**: This subset has images used for validation purposes during model training.\n3. **Test**: This subset consists of images used for testing and benchmarking the trained models. Ground truth annotations for this subset are not publicly available, and the results are submitted to the [PASCAL VOC evaluation server](http://host.robots.ox.ac.uk:8080/leaderboard/displaylb.php) for performance evaluation.\n\n## Applications\n\nThe VOC dataset is widely used for training and evaluating deep learning models in object detection (such as YOLO, Faster R-CNN, and SSD), instance segmentation (such as Mask R-CNN), and image classification. The dataset's diverse set of object categories, large number of annotated images, and standardized evaluation metrics make it an essential resource for computer vision researchers and practitioners.\n\n## Dataset YAML\n\nA YAML (Yet Another Markup Language) file is used to define the dataset configuration. It contains information about the dataset's paths, classes, and other relevant information. In the case of the VOC dataset, the `VOC.yaml` file is maintained at [https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/VOC.yaml](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/VOC.yaml).\n\n!!! example \"ultralytics/datasets/VOC.yaml\"\n\n    ```yaml\n    --8<-- \"ultralytics/datasets/VOC.yaml\"\n    ```\n\n## Usage\n\nTo train a YOLOv8n model on the VOC dataset for 100 epochs with an image size of 640, you can use the following code snippets. For a comprehensive list of available arguments, refer to the model [Training](../../modes/train.md) page.\n\n!!! example \"Train Example\"\n\n    === \"Python\"\n\n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n        \n        # Train the model\n        model.train(data='VOC.yaml', epochs=100, imgsz=640)\n        ```\n\n    === \"CLI\"\n\n        ```bash\n        # Start training from\n        a pretrained *.pt model\n        yolo detect train data=VOC.yaml model=yolov8n.pt epochs=100 imgsz=640\n        ```\n\n## Sample Images and Annotations\n\nThe VOC dataset contains a diverse set of images with various object categories and complex scenes. Here are some examples of images from the dataset, along with their corresponding annotations:\n\n![Dataset sample image](https://github.com/ultralytics/ultralytics/assets/26833433/7d4c18f4-774e-43f8-a5f3-9467cda7de4a)\n\n- **Mosaiced Image**: This image demonstrates a training batch composed of mosaiced dataset images. Mosaicing is a technique used during training that combines multiple images into a single image to increase the variety of objects and scenes within each training batch. This helps improve the model's ability to generalize to different object sizes, aspect ratios, and contexts.\n\nThe example showcases the variety and complexity of the images in the VOC dataset and the benefits of using mosaicing during the training process.\n\n## Citations and Acknowledgments\n\nIf you use the VOC dataset in your research or development work, please cite the following paper:\n\n```bibtex\n@misc{everingham2010pascal,\n      title={The PASCAL Visual Object Classes (VOC) Challenge}, \n      author={Mark Everingham and Luc Van Gool and Christopher K. I. Williams and John Winn and Andrew Zisserman},\n      year={2010},\n      eprint={0909.5206},\n      archivePrefix={arXiv},\n      primaryClass={cs.CV}\n}\n```\n\nWe would like to acknowledge the PASCAL VOC Consortium for creating and maintaining this valuable resource for the computer vision community. For more information about the VOC dataset and its creators, visit the [PASCAL VOC dataset website](http://host.robots.ox.ac.uk/pascal/VOC/)."
  },
  {
    "path": "docs/datasets/detect/xview.md",
    "content": "---\ncomments: true\ndescription: Discover the xView Dataset, a large-scale overhead imagery dataset for object detection tasks, featuring 1M instances, 60 classes, and high-resolution images.\n---\n\n# xView Dataset\n\nThe [xView](http://xviewdataset.org/) dataset is one of the largest publicly available datasets of overhead imagery, containing images from complex scenes around the world annotated using bounding boxes. The goal of the xView dataset is to accelerate progress in four computer vision frontiers:\n\n1. Reduce minimum resolution for detection.\n2. Improve learning efficiency.\n3. Enable discovery of more object classes.\n4. Improve detection of fine-grained classes.\n\nxView builds on the success of challenges like Common Objects in Context (COCO) and aims to leverage computer vision to analyze the growing amount of available imagery from space in order to understand the visual world in new ways and address a range of important applications.\n\n## Key Features\n\n- xView contains over 1 million object instances across 60 classes.\n- The dataset has a resolution of 0.3 meters, providing higher resolution imagery than most public satellite imagery datasets.\n- xView features a diverse collection of small, rare, fine-grained, and multi-type objects with bounding box annotation.\n- Comes with a pre-trained baseline model using the TensorFlow object detection API and an example for PyTorch.\n\n## Dataset Structure\n\nThe xView dataset is composed of satellite images collected from WorldView-3 satellites at a 0.3m ground sample distance. It contains over 1 million objects across 60 classes in over 1,400 km² of imagery.\n\n## Applications\n\nThe xView dataset is widely used for training and evaluating deep learning models for object detection in overhead imagery. The dataset's diverse set of object classes and high-resolution imagery make it a valuable resource for researchers and practitioners in the field of computer vision, especially for satellite imagery analysis.\n\n## Dataset YAML\n\nA YAML (Yet Another Markup Language) file is used to define the dataset configuration. It contains information about the dataset's paths, classes, and other relevant information. In the case of the xView dataset, the `xView.yaml` file is maintained at [https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/xView.yaml](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/xView.yaml).\n\n!!! example \"ultralytics/datasets/xView.yaml\"\n\n    ```yaml\n    --8<-- \"ultralytics/datasets/xView.yaml\"\n    ```\n\n## Usage\n\nTo train a model on the xView dataset for 100 epochs with an image size of 640, you can use the following code snippets. For a comprehensive list of available arguments, refer to the model [Training](../../modes/train.md) page.\n\n!!! example \"Train Example\"\n\n    === \"Python\"\n\n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n        \n        # Train the model\n        model.train(data='xView.yaml', epochs=100, imgsz=640)\n        ```\n\n    === \"CLI\"\n\n        ```bash\n        # Start training from a pretrained *.pt model\n        yolo detect train data=xView.yaml model=yolov8n.pt epochs=100 imgsz=640\n        ```\n\n## Sample Data and Annotations\n\nThe xView dataset contains high-resolution satellite images with a diverse set of objects annotated using bounding boxes. Here are some examples of data from the dataset, along with their corresponding annotations:\n\n![Dataset sample image](https://github-production-user-asset-6210df.s3.amazonaws.com/26833433/238799379-bb3b02f0-dee4-4e67-80ae-4b2378b813ad.jpg)\n\n- **Overhead Imagery**: This image demonstrates an example of object detection in overhead imagery, where objects are annotated with bounding boxes. The dataset provides high-resolution satellite images to facilitate the development of models for this task.\n\nThe example showcases the variety and complexity of the data in the xView dataset and highlights the importance of high-quality satellite imagery for object detection tasks.\n\n## Citations and Acknowledgments\n\nIf you use the xView dataset in your research or development work, please cite the following paper:\n\n```bibtex\n@misc{lam2018xview,\n      title={xView: Objects in Context in Overhead Imagery}, \n      author={Darius Lam and Richard Kuzma and Kevin McGee and Samuel Dooley and Michael Laielli and Matthew Klaric and Yaroslav Bulatov and Brendan McCord},\n      year={2018},\n      eprint={1802.07856},\n      archivePrefix={arXiv},\n      primaryClass={cs.CV}\n}\n```\n\nWe would like to acknowledge the [Defense Innovation Unit](https://www.diu.mil/) (DIU) and the creators of the xView dataset for their valuable contribution to the computer vision research community. For more information about the xView dataset and its creators, visit the [xView dataset website](http://xviewdataset.org/).\n"
  },
  {
    "path": "docs/datasets/index.md",
    "content": "---\ncomments: true\ndescription: Ultralytics provides support for various datasets to facilitate multiple computer vision tasks. Check out our list of main datasets and their summaries.\n---\n\n# Datasets Overview\n\nUltralytics provides support for various datasets to facilitate computer vision tasks such as detection, instance segmentation, pose estimation, classification, and multi-object tracking. Below is a list of the main Ultralytics datasets, followed by a summary of each computer vision task and the respective datasets.\n\n## [Detection Datasets](detect/index.md)\n\nBounding box object detection is a computer vision technique that involves detecting and localizing objects in an image by drawing a bounding box around each object.\n\n* [Argoverse](detect/argoverse.md): A dataset containing 3D tracking and motion forecasting data from urban environments with rich annotations.\n* [COCO](detect/coco.md): A large-scale dataset designed for object detection, segmentation, and captioning with over 200K labeled images.\n* [COCO8](detect/coco8.md): Contains the first 4 images from COCO train and COCO val, suitable for quick tests.\n* [Global Wheat 2020](detect/globalwheat2020.md): A dataset of wheat head images collected from around the world for object detection and localization tasks.\n* [Objects365](detect/objects365.md): A high-quality, large-scale dataset for object detection with 365 object categories and over 600K annotated images.\n* [SKU-110K](detect/sku-110k.md): A dataset featuring dense object detection in retail environments with over 11K images and 1.7 million bounding boxes.\n* [VisDrone](detect/visdrone.md): A dataset containing object detection and multi-object tracking data from drone-captured imagery with over 10K images and video sequences.\n* [VOC](detect/voc.md): The Pascal Visual Object Classes (VOC) dataset for object detection and segmentation with 20 object classes and over 11K images.\n* [xView](detect/xview.md): A dataset for object detection in overhead imagery with 60 object categories and over 1 million annotated objects.\n\n## [Instance Segmentation Datasets](segment/index.md)\n\nInstance segmentation is a computer vision technique that involves identifying and localizing objects in an image at the pixel level.\n\n* [COCO](segment/coco.md): A large-scale dataset designed for object detection, segmentation, and captioning tasks with over 200K labeled images.\n* [COCO8-seg](segment/coco8-seg.md): A smaller dataset for instance segmentation tasks, containing a subset of 8 COCO images with segmentation annotations.\n\n## [Pose Estimation](pose/index.md)\n\nPose estimation is a technique used to determine the pose of the object relative to the camera or the world coordinate system.\n\n* [COCO](pose/coco.md): A large-scale dataset with human pose annotations designed for pose estimation tasks.\n* [COCO8-pose](pose/coco8-pose.md): A smaller dataset for pose estimation tasks, containing a subset of 8 COCO images with human pose annotations.\n\n## [Classification](classify/index.md)\n\nImage classification is a computer vision task that involves categorizing an image into one or more predefined classes or categories based on its visual content.\n\n* [Caltech 101](classify/caltech101.md): A dataset containing images of 101 object categories for image classification tasks.\n* [Caltech 256](classify/caltech256.md): An extended version of Caltech 101 with 256 object categories and more challenging images.\n* [CIFAR-10](classify/cifar10.md): A dataset of 60K 32x32 color images in 10 classes, with 6K images per class.\n* [CIFAR-100](classify/cifar100.md): An extended version of CIFAR-10 with 100 object categories and 600 images per class.\n* [Fashion-MNIST](classify/fashion-mnist.md): A dataset consisting of 70,000 grayscale images of 10 fashion categories for image classification tasks.\n* [ImageNet](classify/imagenet.md): A large-scale dataset for object detection and image classification with over 14 million images and 20,000 categories.\n* [ImageNet-10](classify/imagenet10.md): A smaller subset of ImageNet with 10 categories for faster experimentation and testing.\n* [Imagenette](classify/imagenette.md): A smaller subset of ImageNet that contains 10 easily distinguishable classes for quicker training and testing.\n* [Imagewoof](classify/imagewoof.md): A more challenging subset of ImageNet containing 10 dog breed categories for image classification tasks.\n* [MNIST](classify/mnist.md): A dataset of 70,000 grayscale images of handwritten digits for image classification tasks.\n\n## [Multi-Object Tracking](track/index.md)\n\nMulti-object tracking is a computer vision technique that involves detecting and tracking multiple objects over time in a video sequence.\n\n* [Argoverse](detect/argoverse.md): A dataset containing 3D tracking and motion forecasting data from urban environments with rich annotations for multi-object tracking tasks.\n* [VisDrone](detect/visdrone.md): A dataset containing object detection and multi-object tracking data from drone-captured imagery with over 10K images and video sequences."
  },
  {
    "path": "docs/datasets/pose/coco.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/datasets/pose/coco8-pose.md",
    "content": "---\ncomments: true\ndescription: Test and debug object detection models with Ultralytics COCO8-Pose Dataset - a small, versatile pose detection dataset with 8 images.\n---\n\n# COCO8-Pose Dataset\n\n## Introduction\n\n[Ultralytics](https://ultralytics.com) COCO8-Pose is a small, but versatile pose detection dataset composed of the first\n8 images of the COCO train 2017 set, 4 for training and 4 for validation. This dataset is ideal for testing and\ndebugging object detection models, or for experimenting with new detection approaches. With 8 images, it is small enough\nto be easily manageable, yet diverse enough to test training pipelines for errors and act as a sanity check before\ntraining larger datasets.\n\nThis dataset is intended for use with Ultralytics [HUB](https://hub.ultralytics.com)\nand [YOLOv8](https://github.com/ultralytics/ultralytics).\n\n## Dataset YAML\n\nA YAML (Yet Another Markup Language) file is used to define the dataset configuration. It contains information about the dataset's paths, classes, and other relevant information. In the case of the COCO8-Pose dataset, the `coco8-pose.yaml` file is maintained at [https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco8-pose.yaml](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco8-pose.yaml).\n\n!!! example \"ultralytics/datasets/coco8-pose.yaml\"\n\n    ```yaml\n    --8<-- \"ultralytics/datasets/coco8-pose.yaml\"\n    ```\n\n## Usage\n\nTo train a YOLOv8n model on the COCO8-Pose dataset for 100 epochs with an image size of 640, you can use the following code snippets. For a comprehensive list of available arguments, refer to the model [Training](../../modes/train.md) page.\n\n!!! example \"Train Example\"\n\n    === \"Python\"\n\n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n        \n        # Train the model\n        model.train(data='coco8-pose.yaml', epochs=100, imgsz=640)\n        ```\n\n    === \"CLI\"\n\n        ```bash\n        # Start training from a pretrained *.pt model\n        yolo detect train data=coco8-pose.yaml model=yolov8n.pt epochs=100 imgsz=640\n        ```\n\n## Sample Images and Annotations\n\nHere are some examples of images from the COCO8-Pose dataset, along with their corresponding annotations:\n\n<img src=\"https://user-images.githubusercontent.com/26833433/236818283-52eecb96-fc6a-420d-8a26-d488b352dd4c.jpg\" alt=\"Dataset sample image\" width=\"800\">\n\n- **Mosaiced Image**: This image demonstrates a training batch composed of mosaiced dataset images. Mosaicing is a technique used during training that combines multiple images into a single image to increase the variety of objects and scenes within each training batch. This helps improve the model's ability to generalize to different object sizes, aspect ratios, and contexts.\n\nThe example showcases the variety and complexity of the images in the COCO8-Pose dataset and the benefits of using mosaicing during the training process.\n\n## Citations and Acknowledgments\n\nIf you use the COCO dataset in your research or development work, please cite the following paper:\n\n```bibtex\n@misc{lin2015microsoft,\n      title={Microsoft COCO: Common Objects in Context}, \n      author={Tsung-Yi Lin and Michael Maire and Serge Belongie and Lubomir Bourdev and Ross Girshick and James Hays and Pietro Perona and Deva Ramanan and C. Lawrence Zitnick and Piotr Dollár},\n      year={2015},\n      eprint={1405.0312},\n      archivePrefix={arXiv},\n      primaryClass={cs.CV}\n}\n```\n\nWe would like to acknowledge the COCO Consortium for creating and maintaining this valuable resource for the computer vision community. For more information about the COCO dataset and its creators, visit the [COCO dataset website](https://cocodataset.org/#home)."
  },
  {
    "path": "docs/datasets/pose/index.md",
    "content": "---\ncomments: true\ndescription: Learn how to format your dataset for training YOLO models with Ultralytics YOLO format using our concise tutorial and example YAML files.\n---\n\n# Pose Estimation Datasets Overview\n\n## Supported Dataset Formats\n\n### Ultralytics YOLO format\n\n** Label Format **\n\nThe dataset format used for training YOLO segmentation models is as follows:\n\n1. One text file per image: Each image in the dataset has a corresponding text file with the same name as the image file and the \".txt\" extension.\n2. One row per object: Each row in the text file corresponds to one object instance in the image.\n3. Object information per row: Each row contains the following information about the object instance:\n    - Object class index: An integer representing the class of the object (e.g., 0 for person, 1 for car, etc.).\n    - Object center coordinates: The x and y coordinates of the center of the object, normalized to be between 0 and 1.\n    - Object width and height: The width and height of the object, normalized to be between 0 and 1.\n    - Object keypoint coordinates: The keypoints of the object, normalized to be between 0 and 1.\n\nHere is an example of the label format for pose estimation task:\n\nFormat with Dim = 2\n\n```\n<class-index> <x> <y> <width> <height> <px1> <py1> <px2> <py2> ... <pxn> <pyn>\n```\n\nFormat with Dim = 3\n\n```\n<class-index> <x> <y> <width> <height> <px1> <py1> <p1-visibility> <px2> <py2> <p2-visibility> <pxn> <pyn> <p2-visibility>\n```\n\nIn this format, `<class-index>` is the index of the class for the object,`<x> <y> <width> <height>` are coordinates of boudning box, and `<px1> <py1> <px2> <py2> ... <pxn> <pyn>` are the pixel coordinates of the keypoints. The coordinates are separated by spaces.\n\n** Dataset file format **\n\nThe Ultralytics framework uses a YAML file format to define the dataset and model configuration for training Detection Models. Here is an example of the YAML format used for defining a detection dataset:\n\n```yaml\ntrain: <path-to-training-images>\nval: <path-to-validation-images>\n\nnc: <number-of-classes>\nnames: [<class-1>, <class-2>, ..., <class-n>]\n\n# Keypoints\nkpt_shape: [num_kpts, dim]  # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)\nflip_idx: [n1, n2 ... , n(num_kpts)]\n\n```\n\nThe `train` and `val` fields specify the paths to the directories containing the training and validation images, respectively.\n\nThe `nc` field specifies the number of object classes in the dataset.\n\nThe `names` field is a list of the names of the object classes. The order of the names should match the order of the object class indices in the YOLO dataset files.\n\nNOTE: Either `nc` or `names` must be defined. Defining both are not mandatory\n\nAlternatively, you can directly define class names like this:\n\n```\nnames:\n  0: person\n  1: bicycle\n```\n\n(Optional) if the points are symmetric then need flip_idx, like left-right side of human or face.\nFor example let's say there're five keypoints of facial landmark: [left eye, right eye, nose, left point of mouth, right point of mouse], and the original index is [0, 1, 2, 3, 4], then flip_idx is [1, 0, 2, 4, 3].(just exchange the left-right index, i.e 0-1 and 3-4, and do not modify others like nose in this example)\n\n** Example **\n\n```yaml\ntrain: data/train/\nval: data/val/\n\nnc: 2\nnames: ['person', 'car']\n\n# Keypoints\nkpt_shape: [17, 3]  # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)\nflip_idx: [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15]\n```\n\n## Usage\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-pose.pt')  # load a pretrained model (recommended for training)\n\n        # Train the model\n        model.train(data='coco128-pose.yaml', epochs=100, imgsz=640)\n        ```\n    === \"CLI\"\n    \n        ```bash\n        # Start training from a pretrained *.pt model\n        yolo detect train data=coco128-pose.yaml model=yolov8n-pose.pt epochs=100 imgsz=640\n        ```\n\n## Supported Datasets\n\nTODO\n\n## Port or Convert label formats\n\n### COCO dataset format to YOLO format\n\n```\nfrom ultralytics.yolo.data.converter import convert_coco\n\nconvert_coco(labels_dir='../coco/annotations/', use_keypoints=True)\n```"
  },
  {
    "path": "docs/datasets/segment/coco.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/datasets/segment/coco8-seg.md",
    "content": "---\ncomments: true\ndescription: Test and debug segmentation models on small, versatile COCO8-Seg instance segmentation dataset, now available for use with YOLOv8 and Ultralytics HUB.\n---\n\n# COCO8-Seg Dataset\n\n## Introduction\n\n[Ultralytics](https://ultralytics.com) COCO8-Seg is a small, but versatile instance segmentation dataset composed of the\nfirst 8 images of the COCO train 2017 set, 4 for training and 4 for validation. This dataset is ideal for testing and\ndebugging segmentation models, or for experimenting with new detection approaches. With 8 images, it is small enough to\nbe easily manageable, yet diverse enough to test training pipelines for errors and act as a sanity check before training\nlarger datasets.\n\nThis dataset is intended for use with Ultralytics [HUB](https://hub.ultralytics.com)\nand [YOLOv8](https://github.com/ultralytics/ultralytics).\n\n## Dataset YAML\n\nA YAML (Yet Another Markup Language) file is used to define the dataset configuration. It contains information about the dataset's paths, classes, and other relevant information. In the case of the COCO8-Seg dataset, the `coco8-seg.yaml` file is maintained at [https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco8-seg.yaml](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco8-seg.yaml).\n\n!!! example \"ultralytics/datasets/coco8-seg.yaml\"\n\n    ```yaml\n    --8<-- \"ultralytics/datasets/coco8-seg.yaml\"\n    ```\n\n## Usage\n\nTo train a YOLOv8n model on the COCO8-Seg dataset for 100 epochs with an image size of 640, you can use the following code snippets. For a comprehensive list of available arguments, refer to the model [Training](../../modes/train.md) page.\n\n!!! example \"Train Example\"\n\n    === \"Python\"\n\n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n        \n        # Train the model\n        model.train(data='coco8-seg.yaml', epochs=100, imgsz=640)\n        ```\n\n    === \"CLI\"\n\n        ```bash\n        # Start training from a pretrained *.pt model\n        yolo detect train data=coco8-seg.yaml model=yolov8n.pt epochs=100 imgsz=640\n        ```\n\n## Sample Images and Annotations\n\nHere are some examples of images from the COCO8-Seg dataset, along with their corresponding annotations:\n\n<img src=\"https://user-images.githubusercontent.com/26833433/236818387-f7bde7df-caaa-46d1-8341-1f7504cd11a1.jpg\" alt=\"Dataset sample image\" width=\"800\">\n\n- **Mosaiced Image**: This image demonstrates a training batch composed of mosaiced dataset images. Mosaicing is a technique used during training that combines multiple images into a single image to increase the variety of objects and scenes within each training batch. This helps improve the model's ability to generalize to different object sizes, aspect ratios, and contexts.\n\nThe example showcases the variety and complexity of the images in the COCO8-Seg dataset and the benefits of using mosaicing during the training process.\n\n## Citations and Acknowledgments\n\nIf you use the COCO dataset in your research or development work, please cite the following paper:\n\n```bibtex\n@misc{lin2015microsoft,\n      title={Microsoft COCO: Common Objects in Context}, \n      author={Tsung-Yi Lin and Michael Maire and Serge Belongie and Lubomir Bourdev and Ross Girshick and James Hays and Pietro Perona and Deva Ramanan and C. Lawrence Zitnick and Piotr Dollár},\n      year={2015},\n      eprint={1405.0312},\n      archivePrefix={arXiv},\n      primaryClass={cs.CV}\n}\n```\n\nWe would like to acknowledge the COCO Consortium for creating and maintaining this valuable resource for the computer vision community. For more information about the COCO dataset and its creators, visit the [COCO dataset website](https://cocodataset.org/#home)."
  },
  {
    "path": "docs/datasets/segment/index.md",
    "content": "---\ncomments: true\ndescription: Learn about the Ultralytics YOLO dataset format for segmentation models. Use YAML to train Detection Models. Convert COCO to YOLO format using Python.\n---\n\n# Instance Segmentation Datasets Overview\n\n## Supported Dataset Formats\n\n### Ultralytics YOLO format\n\n** Label Format **\n\nThe dataset format used for training YOLO segmentation models is as follows:\n\n1. One text file per image: Each image in the dataset has a corresponding text file with the same name as the image file and the \".txt\" extension.\n2. One row per object: Each row in the text file corresponds to one object instance in the image.\n3. Object information per row: Each row contains the following information about the object instance:\n    - Object class index: An integer representing the class of the object (e.g., 0 for person, 1 for car, etc.).\n    - Object bounding coordinates: The bounding coordinates around the mask area, normalized to be between 0 and 1.\n\nThe format for a single row in the segmentation dataset file is as follows:\n\n```\n<class-index> <x1> <y1> <x2> <y2> ... <xn> <yn>\n```\n\nIn this format, `<class-index>` is the index of the class for the object, and `<x1> <y1> <x2> <y2> ... <xn> <yn>` are the bounding coordinates of the object's segmentation mask. The coordinates are separated by spaces.\n\nHere is an example of the YOLO dataset format for a single image with two object instances:\n\n```\n0 0.6812 0.48541 0.67 0.4875 0.67656 0.487 0.675 0.489 0.66\n1 0.5046 0.0 0.5015 0.004 0.4984 0.00416 0.4937 0.010 0.492 0.0104\n```\n\nNote: The length of each row does not have to be equal.\n\n** Dataset file format **\n\nThe Ultralytics framework uses a YAML file format to define the dataset and model configuration for training Detection Models. Here is an example of the YAML format used for defining a detection dataset:\n\n```yaml\ntrain: <path-to-training-images>\nval: <path-to-validation-images>\n\nnc: <number-of-classes>\nnames: [ <class-1>, <class-2>, ..., <class-n> ]\n\n```\n\nThe `train` and `val` fields specify the paths to the directories containing the training and validation images, respectively.\n\nThe `nc` field specifies the number of object classes in the dataset.\n\nThe `names` field is a list of the names of the object classes. The order of the names should match the order of the object class indices in the YOLO dataset files.\n\nNOTE: Either `nc` or `names` must be defined. Defining both are not mandatory.\n\nAlternatively, you can directly define class names like this:\n\n```yaml\nnames:\n  0: person\n  1: bicycle\n```\n\n** Example **\n\n```yaml\ntrain: data/train/\nval: data/val/\n\nnc: 2\nnames: [ 'person', 'car' ]\n```\n\n## Usage\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-seg.pt')  # load a pretrained model (recommended for training)\n\n        # Train the model\n        model.train(data='coco128-seg.yaml', epochs=100, imgsz=640)\n        ```\n    === \"CLI\"\n    \n        ```bash\n        # Start training from a pretrained *.pt model\n        yolo detect train data=coco128-seg.yaml model=yolov8n-seg.pt epochs=100 imgsz=640\n        ```\n\n## Supported Datasets\n\n## Port or Convert label formats\n\n### COCO dataset format to YOLO format\n\n```\nfrom ultralytics.yolo.data.converter import convert_coco\n\nconvert_coco(labels_dir='../coco/annotations/', use_segments=True)\n```\n\n## Auto-Annotation\n\nAuto-annotation is an essential feature that allows you to generate a segmentation dataset using a pre-trained detection model. It enables you to quickly and accurately annotate a large number of images without the need for manual labeling, saving time and effort.\n\n### Generate Segmentation Dataset Using a Detection Model\n\nTo auto-annotate your dataset using the Ultralytics framework, you can use the `auto_annotate` function as shown below:\n\n```python\nfrom ultralytics.yolo.data.annotator import auto_annotate\n\nauto_annotate(data=\"path/to/images\", det_model=\"yolov8x.pt\", sam_model='sam_b.pt')\n```\n\n| Argument   | Type                | Description                                                                                             | Default      |\n|------------|---------------------|---------------------------------------------------------------------------------------------------------|--------------|\n| data       | str                 | Path to a folder containing images to be annotated.                                                     |              |\n| det_model  | str, optional       | Pre-trained YOLO detection model. Defaults to 'yolov8x.pt'.                                             | 'yolov8x.pt' |\n| sam_model  | str, optional       | Pre-trained SAM segmentation model. Defaults to 'sam_b.pt'.                                             | 'sam_b.pt'   |\n| device     | str, optional       | Device to run the models on. Defaults to an empty string (CPU or GPU, if available).                    |              |\n| output_dir | str, None, optional | Directory to save the annotated results. Defaults to a 'labels' folder in the same directory as 'data'. | None         |\n\nThe `auto_annotate` function takes the path to your images, along with optional arguments for specifying the pre-trained detection and [SAM segmentation models](https://docs.ultralytics.com/models/sam), the device to run the models on, and the output directory for saving the annotated results.\n\nBy leveraging the power of pre-trained models, auto-annotation can significantly reduce the time and effort required for creating high-quality segmentation datasets. This feature is particularly useful for researchers and developers working with large image collections, as it allows them to focus on model development and evaluation rather than manual annotation."
  },
  {
    "path": "docs/datasets/track/index.md",
    "content": "---\ncomments: true\ndescription: Discover the datasets compatible with Multi-Object Detector. Train your trackers and make your detections more efficient with Ultralytics' YOLO.\n---\n\n# Multi-object Tracking Datasets Overview\n\n## Dataset Format (Coming Soon)\n\nMulti-Object Detector doesn't need standalone training and directly supports pre-trained detection, segmentation or Pose models.\nSupport for training trackers alone is coming soon\n\n## Usage\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n\n        model = YOLO('yolov8n.pt')\n        results = model.track(source=\"https://youtu.be/Zgi9g1ksQHc\", conf=0.3, iou=0.5, show=True) \n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo track model=yolov8n.pt source=\"https://youtu.be/Zgi9g1ksQHc\" conf=0.3, iou=0.5 show\n        ```"
  },
  {
    "path": "docs/help/CLA.md",
    "content": "---\ndescription: Individual Contributor License Agreement. Settle Intellectual Property issues for Contributions made to anything open source released by Ultralytics.\n---\n\n# Ultralytics Individual Contributor License Agreement\n\nThank you for your interest in contributing to open source software projects (“Projects”) made available by Ultralytics\nSE or its affiliates (“Ultralytics”). This Individual Contributor License Agreement (“Agreement”) sets out the terms\ngoverning any source code, object code, bug fixes, configuration changes, tools, specifications, documentation, data,\nmaterials, feedback, information or other works of authorship that you submit or have submitted, in any form and in any\nmanner, to Ultralytics in respect of any of the Projects (collectively “Contributions”). If you have any questions\nrespecting this Agreement, please contact hello@ultralytics.com.\n\nYou agree that the following terms apply to all of your past, present and future Contributions. Except for the licenses\ngranted in this Agreement, you retain all of your right, title and interest in and to your Contributions.\n\n**Copyright License.** You hereby grant, and agree to grant, to Ultralytics a non-exclusive, perpetual, irrevocable,\nworldwide, fully-paid, royalty-free, transferable copyright license to reproduce, prepare derivative works of, publicly\ndisplay, publicly perform, and distribute your Contributions and such derivative works, with the right to sublicense the\nforegoing rights through multiple tiers of sublicensees.\n\n**Patent License.** You hereby grant, and agree to grant, to Ultralytics a non-exclusive, perpetual, irrevocable,\nworldwide, fully-paid, royalty-free, transferable patent license to make, have made, use, offer to sell, sell,\nimport, and otherwise transfer your Contributions, where such license applies only to those patent claims\nlicensable by you that are necessarily infringed by your Contributions alone or by combination of your\nContributions with the Project to which such Contributions were submitted, with the right to sublicense the\nforegoing rights through multiple tiers of sublicensees.\n\n**Moral Rights.** To the fullest extent permitted under applicable law, you hereby waive, and agree not to\nassert, all of your “moral rights” in or relating to your Contributions for the benefit of Ultralytics, its assigns, and\ntheir respective direct and indirect sublicensees.\n\n**Third Party Content/Rights.** If your Contribution includes or is based on any source code, object code, bug\nfixes, configuration changes, tools, specifications, documentation, data, materials, feedback, information or\nother works of authorship that were not authored by you (“Third Party Content”) or if you are aware of any\nthird party intellectual property or proprietary rights associated with your Contribution (“Third Party Rights”),\nthen you agree to include with the submission of your Contribution full details respecting such Third Party\nContent and Third Party Rights, including, without limitation, identification of which aspects of your\nContribution contain Third Party Content or are associated with Third Party Rights, the owner/author of the\nThird Party Content and Third Party Rights, where you obtained the Third Party Content, and any applicable\nthird party license terms or restrictions respecting the Third Party Content and Third Party Rights. For greater\ncertainty, the foregoing obligations respecting the identification of Third Party Content and Third Party Rights\ndo not apply to any portion of a Project that is incorporated into your Contribution to that same Project.\n\n**Representations.** You represent that, other than the Third Party Content and Third Party Rights identified by\nyou in accordance with this Agreement, you are the sole author of your Contributions and are legally entitled\nto grant the foregoing licenses and waivers in respect of your Contributions. If your Contributions were\ncreated in the course of your employment with your past or present employer(s), you represent that such\nemployer(s) has authorized you to make your Contributions on behalf of such employer(s) or such employer\n(s) has waived all of their right, title or interest in or to your Contributions.\n\n**Disclaimer.** To the fullest extent permitted under applicable law, your Contributions are provided on an \"asis\"\nbasis, without any warranties or conditions, express or implied, including, without limitation, any implied\nwarranties or conditions of non-infringement, merchantability or fitness for a particular purpose. You are not\nrequired to provide support for your Contributions, except to the extent you desire to provide support.\n\n**No Obligation.** You acknowledge that Ultralytics is under no obligation to use or incorporate your Contributions\ninto any of the Projects. The decision to use or incorporate your Contributions into any of the Projects will be\nmade at the sole discretion of Ultralytics or its authorized delegates ..\n\n**Disputes.** This Agreement shall be governed by and construed in accordance with the laws of the State of\nNew York, United States of America, without giving effect to its principles or rules regarding conflicts of laws,\nother than such principles directing application of New York law. The parties hereby submit to venue in, and\njurisdiction of the courts located in New York, New York for purposes relating to this Agreement. In the event\nthat any of the provisions of this Agreement shall be held by a court or other tribunal of competent jurisdiction\nto be unenforceable, the remaining portions hereof shall remain in full force and effect.\n\n**Assignment.** You agree that Ultralytics may assign this Agreement, and all of its rights, obligations and licenses\nhereunder."
  },
  {
    "path": "docs/help/FAQ.md",
    "content": "---\ncomments: true\ndescription: 'Get quick answers to common Ultralytics YOLO questions: Hardware requirements, fine-tuning, conversion, real-time detection, and accuracy tips.'\n---\n\n# Ultralytics YOLO Frequently Asked Questions (FAQ)\n\nThis FAQ section addresses some common questions and issues users might encounter while working with Ultralytics YOLO repositories.\n\n## 1. What are the hardware requirements for running Ultralytics YOLO?\n\nUltralytics YOLO can be run on a variety of hardware configurations, including CPUs, GPUs, and even some edge devices. However, for optimal performance and faster training and inference, we recommend using a GPU with a minimum of 8GB of memory. NVIDIA GPUs with CUDA support are ideal for this purpose.\n\n## 2. How do I fine-tune a pre-trained YOLO model on my custom dataset?\n\nTo fine-tune a pre-trained YOLO model on your custom dataset, you'll need to create a dataset configuration file (YAML) that defines the dataset's properties, such as the path to the images, the number of classes, and class names. Next, you'll need to modify the model configuration file to match the number of classes in your dataset. Finally, use the `train.py` script to start the training process with your custom dataset and the pre-trained model. You can find a detailed guide on fine-tuning YOLO in the Ultralytics documentation.\n\n## 3. How do I convert a YOLO model to ONNX or TensorFlow format?\n\nUltralytics provides built-in support for converting YOLO models to ONNX format. You can use the `export.py` script to convert a saved model to ONNX format. If you need to convert the model to TensorFlow format, you can use the ONNX model as an intermediary and then use the ONNX-TensorFlow converter to convert the ONNX model to TensorFlow format.\n\n## 4. Can I use Ultralytics YOLO for real-time object detection?\n\nYes, Ultralytics YOLO is designed to be efficient and fast, making it suitable for real-time object detection tasks. The actual performance will depend on your hardware configuration and the complexity of the model. Using a GPU and optimizing the model for your specific use case can help achieve real-time performance.\n\n## 5. How can I improve the accuracy of my YOLO model?\n\nImproving the accuracy of a YOLO model may involve several strategies, such as:\n\n- Fine-tuning the model on more annotated data\n- Data augmentation to increase the variety of training samples\n- Using a larger or more complex model architecture\n- Adjusting the learning rate, batch size, and other hyperparameters\n- Using techniques like transfer learning or knowledge distillation\n\nRemember that there's often a trade-off between accuracy and inference speed, so finding the right balance is crucial for your specific application.\n\nIf you have any more questions or need assistance, don't hesitate to consult the Ultralytics documentation or reach out to the community through GitHub Issues or the official discussion forum."
  },
  {
    "path": "docs/help/code_of_conduct.md",
    "content": "---\ncomments: true\ndescription: Read the Ultralytics Contributor Covenant Code of Conduct. Learn ways to create a welcoming community & consequences for inappropriate conduct.\n---\n\n# Ultralytics Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participation in our\ncommunity a harassment-free experience for everyone, regardless of age, body\nsize, visible or invisible disability, ethnicity, sex characteristics, gender\nidentity and expression, level of experience, education, socio-economic status,\nnationality, personal appearance, race, religion, or sexual identity\nand orientation.\n\nWe pledge to act and interact in ways that contribute to an open, welcoming,\ndiverse, inclusive, and healthy community.\n\n## Our Standards\n\nExamples of behavior that contributes to a positive environment for our\ncommunity include:\n\n- Demonstrating empathy and kindness toward other people\n- Being respectful of differing opinions, viewpoints, and experiences\n- Giving and gracefully accepting constructive feedback\n- Accepting responsibility and apologizing to those affected by our mistakes,\n  and learning from the experience\n- Focusing on what is best not just for us as individuals, but for the\n  overall community\n\nExamples of unacceptable behavior include:\n\n- The use of sexualized language or imagery, and sexual attention or\n  advances of any kind\n- Trolling, insulting or derogatory comments, and personal or political attacks\n- Public or private harassment\n- Publishing others' private information, such as a physical or email\n  address, without their explicit permission\n- Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Enforcement Responsibilities\n\nCommunity leaders are responsible for clarifying and enforcing our standards of\nacceptable behavior and will take appropriate and fair corrective action in\nresponse to any behavior that they deem inappropriate, threatening, offensive,\nor harmful.\n\nCommunity leaders have the right and responsibility to remove, edit, or reject\ncomments, commits, code, wiki edits, issues, and other contributions that are\nnot aligned to this Code of Conduct, and will communicate reasons for moderation\ndecisions when appropriate.\n\n## Scope\n\nThis Code of Conduct applies within all community spaces, and also applies when\nan individual is officially representing the community in public spaces.\nExamples of representing our community include using an official e-mail address,\nposting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported to the community leaders responsible for enforcement at\nhello@ultralytics.com.\nAll complaints will be reviewed and investigated promptly and fairly.\n\nAll community leaders are obligated to respect the privacy and security of the\nreporter of any incident.\n\n## Enforcement Guidelines\n\nCommunity leaders will follow these Community Impact Guidelines in determining\nthe consequences for any action they deem in violation of this Code of Conduct:\n\n### 1. Correction\n\n**Community Impact**: Use of inappropriate language or other behavior deemed\nunprofessional or unwelcome in the community.\n\n**Consequence**: A private, written warning from community leaders, providing\nclarity around the nature of the violation and an explanation of why the\nbehavior was inappropriate. A public apology may be requested.\n\n### 2. Warning\n\n**Community Impact**: A violation through a single incident or series\nof actions.\n\n**Consequence**: A warning with consequences for continued behavior. No\ninteraction with the people involved, including unsolicited interaction with\nthose enforcing the Code of Conduct, for a specified period of time. This\nincludes avoiding interactions in community spaces as well as external channels\nlike social media. Violating these terms may lead to a temporary or\npermanent ban.\n\n### 3. Temporary Ban\n\n**Community Impact**: A serious violation of community standards, including\nsustained inappropriate behavior.\n\n**Consequence**: A temporary ban from any sort of interaction or public\ncommunication with the community for a specified period of time. No public or\nprivate interaction with the people involved, including unsolicited interaction\nwith those enforcing the Code of Conduct, is allowed during this period.\nViolating these terms may lead to a permanent ban.\n\n### 4. Permanent Ban\n\n**Community Impact**: Demonstrating a pattern of violation of community\nstandards, including sustained inappropriate behavior, harassment of an\nindividual, or aggression toward or disparagement of classes of individuals.\n\n**Consequence**: A permanent ban from any sort of public interaction within\nthe community.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage],\nversion 2.0, available at\nhttps://www.contributor-covenant.org/version/2/0/code_of_conduct.html.\n\nCommunity Impact Guidelines were inspired by [Mozilla's code of conduct\nenforcement ladder](https://github.com/mozilla/diversity).\n\nFor answers to common questions about this code of conduct, see the FAQ at\nhttps://www.contributor-covenant.org/faq. Translations are available at\nhttps://www.contributor-covenant.org/translations.\n\n[homepage]: https://www.contributor-covenant.org"
  },
  {
    "path": "docs/help/contributing.md",
    "content": "---\ncomments: true\ndescription: Learn how to contribute to Ultralytics Open-Source YOLO Repositories with contributions guidelines, pull requests requirements, and GitHub CI tests.\n---\n\n# Contributing to Ultralytics Open-Source YOLO Repositories\n\nFirst of all, thank you for your interest in contributing to Ultralytics open-source YOLO repositories! Your contributions will help improve the project and benefit the community. This document provides guidelines and best practices for contributing to Ultralytics YOLO repositories.\n\n## Table of Contents\n\n- [Code of Conduct](#code-of-conduct)\n- [Pull Requests](#pull-requests)\n    - [CLA Signing](#cla-signing)\n    - [Google-Style Docstrings](#google-style-docstrings)\n    - [GitHub Actions CI Tests](#github-actions-ci-tests)\n- [Bug Reports](#bug-reports)\n    - [Minimum Reproducible Example](#minimum-reproducible-example)\n- [License and Copyright](#license-and-copyright)\n\n## Code of Conduct\n\nAll contributors are expected to adhere to the [Code of Conduct](code_of_conduct.md) to ensure a welcoming and inclusive environment for everyone.\n\n## Pull Requests\n\nWe welcome contributions in the form of pull requests. To make the review process smoother, please follow these guidelines:\n\n1. **Fork the repository**: Fork the Ultralytics YOLO repository to your own GitHub account.\n\n2. **Create a branch**: Create a new branch in your forked repository with a descriptive name for your changes.\n\n3. **Make your changes**: Make the changes you want to contribute. Ensure that your changes follow the coding style of the project and do not introduce new errors or warnings.\n\n4. **Test your changes**: Test your changes locally to ensure that they work as expected and do not introduce new issues.\n\n5. **Commit your changes**: Commit your changes with a descriptive commit message. Make sure to include any relevant issue numbers in your commit message.\n\n6. **Create a pull request**: Create a pull request from your forked repository to the main Ultralytics YOLO repository. In the pull request description, provide a clear explanation of your changes and how they improve the project.\n\n### CLA Signing\n\nBefore we can accept your pull request, you need to sign a [Contributor License Agreement (CLA)](CLA.md). This is a legal document stating that you agree to the terms of contributing to the Ultralytics YOLO repositories. The CLA ensures that your contributions are properly licensed and that the project can continue to be distributed under the AGPL-3.0 license.\n\nTo sign the CLA, follow the instructions provided by the CLA bot after you submit your PR.\n\n### Google-Style Docstrings\n\nWhen adding new functions or classes, please include a [Google-style docstring](https://google.github.io/styleguide/pyguide.html) to provide clear and concise documentation for other developers. This will help ensure that your contributions are easy to understand and maintain.\n\nExample Google-style docstring:\n\n```python\ndef example_function(arg1: int, arg2: str) -> bool:\n    \"\"\"Example function that demonstrates Google-style docstrings.\n\n    Args:\n        arg1 (int): The first argument.\n        arg2 (str): The second argument.\n\n    Returns:\n        bool: True if successful, False otherwise.\n\n    Raises:\n        ValueError: If `arg1` is negative or `arg2` is empty.\n    \"\"\"\n    if arg1 < 0 or not arg2:\n        raise ValueError(\"Invalid input values\")\n    return True\n```\n\n### GitHub Actions CI Tests\n\nBefore your pull request can be merged, all GitHub Actions Continuous Integration (CI) tests must pass. These tests include linting, unit tests, and other checks to ensure that your changes meet the quality standards of the project. Make sure to review the output of the GitHub Actions and fix any issues"
  },
  {
    "path": "docs/help/index.md",
    "content": "---\ncomments: true\ndescription: Get comprehensive resources for Ultralytics YOLO repositories. Find guides, FAQs, MRE creation, CLA & more. Join the supportive community now!\n---\n\nWelcome to the Ultralytics Help page! We are committed to providing you with comprehensive resources to make your experience with Ultralytics YOLO repositories as smooth and enjoyable as possible. On this page, you'll find essential links to guides and documents that will help you navigate through common tasks and address any questions you might have while using our repositories.\n\n- [Frequently Asked Questions (FAQ)](FAQ.md): Find answers to common questions and issues faced by users and contributors of Ultralytics YOLO repositories.\n- [Contributing Guide](contributing.md): Learn the best practices for submitting pull requests, reporting bugs, and contributing to the development of our repositories.\n- [Contributor License Agreement (CLA)](CLA.md): Familiarize yourself with our CLA to understand the terms and conditions for contributing to Ultralytics projects.\n- [Minimum Reproducible Example (MRE) Guide](minimum_reproducible_example.md): Understand how to create an MRE when submitting bug reports to ensure that our team can quickly and efficiently address the issue.\n- [Code of Conduct](code_of_conduct.md): Learn about our community guidelines and expectations to ensure a welcoming and inclusive environment for all participants.\n- [Security Policy](../SECURITY.md): Understand our security practices and how to report security vulnerabilities responsibly.\n\nWe highly recommend going through these guides to make the most of your collaboration with the Ultralytics community. Our goal is to maintain a welcoming and supportive environment for all users and contributors. If you need further assistance, don't hesitate to reach out to us through GitHub Issues or the official discussion forum. Happy coding!"
  },
  {
    "path": "docs/help/minimum_reproducible_example.md",
    "content": "---\ncomments: true\ndescription: Learn how to create a Minimum Reproducible Example (MRE) for Ultralytics YOLO bug reports to help maintainers and contributors understand your issue better.\n---\n\n# Creating a Minimum Reproducible Example for Bug Reports in Ultralytics YOLO Repositories\n\nWhen submitting a bug report for Ultralytics YOLO repositories, it's essential to provide a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) (MRE). An MRE is a small, self-contained piece of code that demonstrates the problem you're experiencing. Providing an MRE helps maintainers and contributors understand the issue and work on a fix more efficiently. This guide explains how to create an MRE when submitting bug reports to Ultralytics YOLO repositories.\n\n## 1. Isolate the Problem\n\nThe first step in creating an MRE is to isolate the problem. This means removing any unnecessary code or dependencies that are not directly related to the issue. Focus on the specific part of the code that is causing the problem and remove any irrelevant code.\n\n## 2. Use Public Models and Datasets\n\nWhen creating an MRE, use publicly available models and datasets to reproduce the issue. For example, use the 'yolov8n.pt' model and the 'coco8.yaml' dataset. This ensures that the maintainers and contributors can easily run your example and investigate the problem without needing access to proprietary data or custom models.\n\n## 3. Include All Necessary Dependencies\n\nMake sure to include all the necessary dependencies in your MRE. If your code relies on external libraries, specify the required packages and their versions. Ideally, provide a `requirements.txt` file or list the dependencies in your bug report.\n\n## 4. Write a Clear Description of the Issue\n\nProvide a clear and concise description of the issue you're experiencing. Explain the expected behavior and the actual behavior you're encountering. If applicable, include any relevant error messages or logs.\n\n## 5. Format Your Code Properly\n\nWhen submitting an MRE, format your code properly using code blocks in the issue description. This makes it easier for others to read and understand your code. In GitHub, you can create a code block by wrapping your code with triple backticks (\\```) and specifying the language:\n\n<pre>\n```python\n# Your Python code goes here\n```\n</pre>\n\n## 6. Test Your MRE\n\nBefore submitting your MRE, test it to ensure that it accurately reproduces the issue. Make sure that others can run your example without any issues or modifications.\n\n## Example of an MRE\n\nHere's an example of an MRE for a hypothetical bug report:\n\n**Bug description:**\n\nWhen running the `detect.py` script on the sample image from the 'coco8.yaml' dataset, I get an error related to the dimensions of the input tensor.\n\n**MRE:**\n\n```python\nimport torch\nfrom ultralytics import YOLO\n\n# Load the model\nmodel = YOLO(\"yolov8n.pt\")\n\n# Load a 0-channel image\nimage = torch.rand(1, 0, 640, 640)\n\n# Run the model\nresults = model(image)\n```\n\n**Error message:**\n\n```\nRuntimeError: Expected input[1, 0, 640, 640] to have 3 channels, but got 0 channels instead\n```\n\n**Dependencies:**\n\n- torch==2.0.0\n- ultralytics==8.0.90\n\nIn this example, the MRE demonstrates the issue with a minimal amount of code, uses a public model ('yolov8n.pt'), includes all necessary dependencies, and provides a clear description of the problem along with the error message.\n\nBy following these guidelines, you'll help the maintainers and contributors of Ultralytics YOLO repositories to understand and resolve your issue more efficiently."
  },
  {
    "path": "docs/hub/app/android.md",
    "content": "---\ncomments: true\ndescription: Run YOLO models on your Android device for real-time object detection with Ultralytics Android App. Utilizes TensorFlow Lite and hardware delegates.\n---\n\n# Ultralytics Android App: Real-time Object Detection with YOLO Models\n\nThe Ultralytics Android App is a powerful tool that allows you to run YOLO models directly on your Android device for real-time object detection. This app utilizes TensorFlow Lite for model optimization and various hardware delegates for acceleration, enabling fast and efficient object detection.\n\n## Quantization and Acceleration\n\nTo achieve real-time performance on your Android device, YOLO models are quantized to either FP16 or INT8 precision. Quantization is a process that reduces the numerical precision of the model's weights and biases, thus reducing the model's size and the amount of computation required. This results in faster inference times without significantly affecting the model's accuracy.\n\n### FP16 Quantization\n\nFP16 (or half-precision) quantization converts the model's 32-bit floating-point numbers to 16-bit floating-point numbers. This reduces the model's size by half and speeds up the inference process, while maintaining a good balance between accuracy and performance.\n\n### INT8 Quantization\n\nINT8 (or 8-bit integer) quantization further reduces the model's size and computation requirements by converting its 32-bit floating-point numbers to 8-bit integers. This quantization method can result in a significant speedup, but it may lead to a slight reduction in mean average precision (mAP) due to the lower numerical precision.\n\n!!! tip \"mAP Reduction in INT8 Models\"\n\n    The reduced numerical precision in INT8 models can lead to some loss of information during the quantization process, which may result in a slight decrease in mAP. However, this trade-off is often acceptable considering the substantial performance gains offered by INT8 quantization.\n\n## Delegates and Performance Variability\n\nDifferent delegates are available on Android devices to accelerate model inference. These delegates include CPU, [GPU](https://www.tensorflow.org/lite/android/delegates/gpu), [Hexagon](https://www.tensorflow.org/lite/android/delegates/hexagon) and [NNAPI](https://www.tensorflow.org/lite/android/delegates/nnapi). The performance of these delegates varies depending on the device's hardware vendor, product line, and specific chipsets used in the device.\n\n1. **CPU**: The default option, with reasonable performance on most devices.\n2. **GPU**: Utilizes the device's GPU for faster inference. It can provide a significant performance boost on devices with powerful GPUs.\n3. **Hexagon**: Leverages Qualcomm's Hexagon DSP for faster and more efficient processing. This option is available on devices with Qualcomm Snapdragon processors.\n4. **NNAPI**: The Android Neural Networks API (NNAPI) serves as an abstraction layer for running ML models on Android devices. NNAPI can utilize various hardware accelerators, such as CPU, GPU, and dedicated AI chips (e.g., Google's Edge TPU, or the Pixel Neural Core).\n\nHere's a table showing the primary vendors, their product lines, popular devices, and supported delegates:\n\n| Vendor                                  | Product Lines                                                                                                 | Popular Devices                                                                                                                                                                | Delegates Supported      |\n|-----------------------------------------|---------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------|\n| [Qualcomm](https://www.qualcomm.com/)   | [Snapdragon (e.g., 800 series)](https://www.qualcomm.com/snapdragon)                                          | [Samsung Galaxy S21](https://www.samsung.com/global/galaxy/galaxy-s21-5g/), [OnePlus 9](https://www.oneplus.com/9), [Google Pixel 6](https://store.google.com/product/pixel_6) | CPU, GPU, Hexagon, NNAPI |\n| [Samsung](https://www.samsung.com/)     | [Exynos (e.g., Exynos 2100)](https://www.samsung.com/semiconductor/minisite/exynos/)                          | [Samsung Galaxy S21 (Global version)](https://www.samsung.com/global/galaxy/galaxy-s21-5g/)                                                                                    | CPU, GPU, NNAPI          |\n| [MediaTek](https://www.mediatek.com/)   | [Dimensity (e.g., Dimensity 1200)](https://www.mediatek.com/products/smartphones)                             | [Realme GT](https://www.realme.com/global/realme-gt), [Xiaomi Redmi Note](https://www.mi.com/en/phone/redmi/note-list)                                                         | CPU, GPU, NNAPI          |\n| [HiSilicon](https://www.hisilicon.com/) | [Kirin (e.g., Kirin 990)](https://www.hisilicon.com/en/products/Kirin)                                        | [Huawei P40 Pro](https://consumer.huawei.com/en/phones/p40-pro/), [Huawei Mate 30 Pro](https://consumer.huawei.com/en/phones/mate30-pro/)                                      | CPU, GPU, NNAPI          |\n| [NVIDIA](https://www.nvidia.com/)       | [Tegra (e.g., Tegra X1)](https://www.nvidia.com/en-us/autonomous-machines/embedded-systems-dev-kits-modules/) | [NVIDIA Shield TV](https://www.nvidia.com/en-us/shield/shield-tv/), [Nintendo Switch](https://www.nintendo.com/switch/)                                                        | CPU, GPU, NNAPI          |\n\nPlease note that the list of devices mentioned is not exhaustive and may vary depending on the specific chipsets and device models. Always test your models on your target devices to ensure compatibility and optimal performance.\n\nKeep in mind that the choice of delegate can affect performance and model compatibility. For example, some models may not work with certain delegates, or a delegate may not be available on a specific device. As such, it's essential to test your model and the chosen delegate on your target devices for the best results.\n\n## Getting Started with the Ultralytics Android App\n\nTo get started with the Ultralytics Android App, follow these steps:\n\n1. Download the Ultralytics App from the [Google Play Store](https://play.google.com/store/apps/details?id=com.ultralytics.ultralytics_app).\n\n2. Launch the app on your Android device and sign in with your Ultralytics account. If you don't have an account yet, create one [here](https://hub.ultralytics.com/).\n\n3. Once signed in, you will see a list of your trained YOLO models. Select a model to use for object detection.\n\n4. Grant the app permission to access your device's camera.\n\n5. Point your device's camera at objects you want to detect. The app will display bounding boxes and class labels in real-time as it detects objects.\n\n6. Explore the app's settings to adjust the detection threshold, enable or disable specific object classes, and more.\n\nWith the Ultralytics Android App, you now have the power of real-time object detection using YOLO models right at your fingertips. Enjoy exploring the app's features and optimizing its settings to suit your specific use cases."
  },
  {
    "path": "docs/hub/app/index.md",
    "content": "---\ncomments: true\ndescription: Experience the power of YOLOv5 and YOLOv8 models with Ultralytics HUB app. Download from Google Play and App Store now.\n---\n\n# Ultralytics HUB App\n\n<a href=\"https://bit.ly/ultralytics_hub\" target=\"_blank\">\n<img width=\"100%\" src=\"https://github.com/ultralytics/assets/raw/main/im/ultralytics-hub.png\"></a>\n<br>\n<div align=\"center\">\n  <a href=\"https://github.com/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-github.png\" width=\"2%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"2%\" alt=\"\" />\n  <a href=\"https://www.linkedin.com/company/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-linkedin.png\" width=\"2%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"2%\" alt=\"\" />\n  <a href=\"https://twitter.com/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-twitter.png\" width=\"2%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"2%\" alt=\"\" />\n  <a href=\"https://youtube.com/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-youtube.png\" width=\"2%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"2%\" alt=\"\" />\n  <a href=\"https://www.tiktok.com/@ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-tiktok.png\" width=\"2%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"2%\" alt=\"\" />\n  <a href=\"https://www.instagram.com/ultralytics/\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-instagram.png\" width=\"2%\" alt=\"\" /></a>\n  <br>\n  <br>\n  <a href=\"https://play.google.com/store/apps/details?id=com.ultralytics.ultralytics_app\" style=\"text-decoration:none;\">\n    <img src=\"https://raw.githubusercontent.com/ultralytics/assets/master/app/google-play.svg\" width=\"15%\" alt=\"\" /></a>&nbsp;\n  <a href=\"https://apps.apple.com/xk/app/ultralytics/id1583935240\" style=\"text-decoration:none;\">\n    <img src=\"https://raw.githubusercontent.com/ultralytics/assets/master/app/app-store.svg\" width=\"15%\" alt=\"\" /></a>\n</div>\n\nWelcome to the Ultralytics HUB App! We are excited to introduce this powerful mobile app that allows you to run YOLOv5 and YOLOv8 models directly on your [iOS](https://apps.apple.com/xk/app/ultralytics/id1583935240) and [Android](https://play.google.com/store/apps/details?id=com.ultralytics.ultralytics_app) devices. With the HUB App, you can utilize hardware acceleration features like Apple's Neural Engine (ANE) or Android GPU and Neural Network API (NNAPI) delegates to achieve impressive performance on your mobile device.\n\n## Features\n\n- **Run YOLOv5 and YOLOv8 models**: Experience the power of YOLO models on your mobile device for real-time object detection and image recognition tasks.\n- **Hardware Acceleration**: Benefit from Apple ANE on iOS devices or Android GPU and NNAPI delegates for optimized performance.\n- **Custom Model Training**: Train custom models with the Ultralytics HUB platform and preview them live using the HUB App.\n- **Mobile Compatibility**: The HUB App supports both iOS and Android devices, bringing the power of YOLO models to a wide range of users.\n\n## App Documentation\n\n- [**iOS**](./ios.md): Learn about YOLO CoreML models accelerated on Apple's Neural Engine for iPhones and iPads.\n- [**Android**](./android.md): Explore TFLite acceleration on Android mobile devices.\n\nGet started today by downloading the Ultralytics HUB App on your mobile device and unlock the potential of YOLOv5 and YOLOv8 models on-the-go. Don't forget to check out our comprehensive [HUB Docs](../) for more information on training, deploying, and using your custom models with the Ultralytics HUB platform."
  },
  {
    "path": "docs/hub/app/ios.md",
    "content": "---\ncomments: true\ndescription: Get started with the Ultralytics iOS app and run YOLO models in real-time for object detection on your iPhone or iPad with the Apple Neural Engine.\n---\n\n# Ultralytics iOS App: Real-time Object Detection with YOLO Models\n\nThe Ultralytics iOS App is a powerful tool that allows you to run YOLO models directly on your iPhone or iPad for real-time object detection. This app utilizes the Apple Neural Engine and Core ML for model optimization and acceleration, enabling fast and efficient object detection.\n\n## Quantization and Acceleration\n\nTo achieve real-time performance on your iOS device, YOLO models are quantized to either FP16 or INT8 precision. Quantization is a process that reduces the numerical precision of the model's weights and biases, thus reducing the model's size and the amount of computation required. This results in faster inference times without significantly affecting the model's accuracy.\n\n### FP16 Quantization\n\nFP16 (or half-precision) quantization converts the model's 32-bit floating-point numbers to 16-bit floating-point numbers. This reduces the model's size by half and speeds up the inference process, while maintaining a good balance between accuracy and performance.\n\n### INT8 Quantization\n\nINT8 (or 8-bit integer) quantization further reduces the model's size and computation requirements by converting its 32-bit floating-point numbers to 8-bit integers. This quantization method can result in a significant speedup, but it may lead to a slight reduction in accuracy.\n\n## Apple Neural Engine\n\nThe Apple Neural Engine (ANE) is a dedicated hardware component integrated into Apple's A-series and M-series chips. It's designed to accelerate machine learning tasks, particularly for neural networks, allowing for faster and more efficient execution of your YOLO models.\n\nBy combining quantized YOLO models with the Apple Neural Engine, the Ultralytics iOS App achieves real-time object detection on your iOS device without compromising on accuracy or performance.\n\n| Release Year | iPhone Name                                          | Chipset Name                                          | Node Size | ANE TOPs |\n|--------------|------------------------------------------------------|-------------------------------------------------------|-----------|----------|\n| 2017         | [iPhone X](https://en.wikipedia.org/wiki/IPhone_X)   | [A11 Bionic](https://en.wikipedia.org/wiki/Apple_A11) | 10 nm     | 0.6      |\n| 2018         | [iPhone XS](https://en.wikipedia.org/wiki/IPhone_XS) | [A12 Bionic](https://en.wikipedia.org/wiki/Apple_A12) | 7 nm      | 5        |\n| 2019         | [iPhone 11](https://en.wikipedia.org/wiki/IPhone_11) | [A13 Bionic](https://en.wikipedia.org/wiki/Apple_A13) | 7 nm      | 6        |\n| 2020         | [iPhone 12](https://en.wikipedia.org/wiki/IPhone_12) | [A14 Bionic](https://en.wikipedia.org/wiki/Apple_A14) | 5 nm      | 11       |\n| 2021         | [iPhone 13](https://en.wikipedia.org/wiki/IPhone_13) | [A15 Bionic](https://en.wikipedia.org/wiki/Apple_A15) | 5 nm      | 15.8     |\n| 2022         | [iPhone 14](https://en.wikipedia.org/wiki/IPhone_14) | [A16 Bionic](https://en.wikipedia.org/wiki/Apple_A16) | 4 nm      | 17.0     |\n\nPlease note that this list only includes iPhone models from 2017 onwards, and the ANE TOPs values are approximate.\n\n## Getting Started with the Ultralytics iOS App\n\nTo get started with the Ultralytics iOS App, follow these steps:\n\n1. Download the Ultralytics App from the [App Store](https://apps.apple.com/xk/app/ultralytics/id1583935240).\n\n2. Launch the app on your iOS device and sign in with your Ultralytics account. If you don't have an account yet, create one [here](https://hub.ultralytics.com/).\n\n3. Once signed in, you will see a list of your trained YOLO models. Select a model to use for object detection.\n\n4. Grant the app permission to access your device's camera.\n\n5. Point your device's camera at objects you want to detect. The app will display bounding boxes and class labels in real-time as it detects objects.\n\n6. Explore the app's settings to adjust the detection threshold, enable or disable specific object classes, and more.\n\nWith the Ultralytics iOS App, you can now leverage the power of YOLO models for real-time object detection on your iPhone or iPad, powered by the Apple Neural Engine and optimized with FP16 or INT8 quantization."
  },
  {
    "path": "docs/hub/datasets.md",
    "content": "---\ncomments: true\ndescription: Upload custom datasets to Ultralytics HUB for YOLOv5 and YOLOv8 models. Follow YAML structure, zip and upload. Scan & train new models.\n---\n\n# HUB Datasets\n\n## 1. Upload a Dataset\n\nUltralytics HUB datasets are just like YOLOv5 and YOLOv8 🚀 datasets, they use the same structure and the same label formats to keep\neverything simple.\n\nWhen you upload a dataset to Ultralytics HUB, make sure to **place your dataset YAML inside the dataset root directory**\nas in the example shown below, and then zip for upload to [https://hub.ultralytics.com](https://hub.ultralytics.com/). Your **dataset YAML, directory\nand zip** should all share the same name. For example, if your dataset is called 'coco8' as in our\nexample [ultralytics/hub/example_datasets/coco8.zip](https://github.com/ultralytics/hub/blob/master/example_datasets/coco8.zip), then you should have a `coco8.yaml` inside your `coco8/` directory, which should zip to create `coco8.zip` for upload:\n\n```bash\nzip -r coco8.zip coco8\n```\n\nThe [example_datasets/coco8.zip](https://github.com/ultralytics/hub/blob/master/example_datasets/coco8.zip) dataset in this repository can be downloaded and unzipped to see exactly how to structure your custom dataset.\n\n<p align=\"center\">\n<img width=\"80%\" src=\"https://user-images.githubusercontent.com/26833433/201424843-20fa081b-ad4b-4d6c-a095-e810775908d8.png\" title=\"COCO8\" />\n</p>\n\nThe dataset YAML is the same standard YOLOv5 and YOLOv8 YAML format. See\nthe [YOLOv5 and YOLOv8 Train Custom Data tutorial](https://docs.ultralytics.com/yolov5/tutorials/train_custom_data/) for full details.\n\n```yaml\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath:  # dataset root dir (leave empty for HUB)\ntrain: images/train  # train images (relative to 'path') 8 images\nval: images/val  # val images (relative to 'path') 8 images\ntest:  # test images (optional)\n\n# Classes\nnames:\n  0: person\n  1: bicycle\n  2: car\n  3: motorcycle\n  ...\n```\n\nAfter zipping your dataset, sign in to [Ultralytics HUB](https://bit.ly/ultralytics_hub) and click the Datasets tab.\nClick 'Upload Dataset' to upload, scan and visualize your new dataset before training new YOLOv5 or YOLOv8 models on it!\n\n<img width=\"100%\" alt=\"HUB Dataset Upload\" src=\"https://user-images.githubusercontent.com/26833433/216763338-9a8812c8-a4e5-4362-8102-40dad7818396.png\">"
  },
  {
    "path": "docs/hub/index.md",
    "content": "---\ncomments: true\ndescription: 'Ultralytics HUB: Train & deploy YOLO models from one spot! Use drag-and-drop interface with templates & pre-training models. Check quickstart, datasets, and more.'\n---\n\n# Ultralytics HUB\n\n<a href=\"https://bit.ly/ultralytics_hub\" target=\"_blank\">\n<img width=\"100%\" src=\"https://github.com/ultralytics/assets/raw/main/im/ultralytics-hub.png\"></a>\n<br>\n<br>\n<div align=\"center\">\n  <a href=\"https://github.com/ultralytics/hub/actions/workflows/ci.yaml\">\n    <img src=\"https://github.com/ultralytics/hub/actions/workflows/ci.yaml/badge.svg\" alt=\"CI CPU\"></a>\n  <a href=\"https://colab.research.google.com/github/ultralytics/hub/blob/master/hub.ipynb\">\n    <img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n</div>\n<br>\n\n👋 Hello from the [Ultralytics](https://ultralytics.com/) Team! We've been working hard these last few months to\nlaunch [Ultralytics HUB](https://bit.ly/ultralytics_hub), a new web tool for training and deploying all your YOLOv5 and YOLOv8 🚀\nmodels from one spot!\n\n## Introduction\n\nHUB is designed to be user-friendly and intuitive, with a drag-and-drop interface that allows users to\neasily upload their data and train new models quickly. It offers a range of pre-trained models and\ntemplates to choose from, making it easy for users to get started with training their own models. Once a model is\ntrained, it can be easily deployed and used for real-time object detection, instance segmentation and classification tasks.\n\nWe hope that the resources here will help you get the most out of HUB. Please browse the HUB <a href=\"https://docs.ultralytics.com/hub\">Docs</a> for details, raise an issue on <a href=\"https://github.com/ultralytics/hub/issues/new/choose\">GitHub</a> for support, and join our <a href=\"https://discord.gg/n6cFeSPZdD\">Discord</a> community for questions and discussions!\n\n- [**Quickstart**](./quickstart.md). Start training and deploying YOLO models with HUB in seconds.\n- [**Datasets: Preparing and Uploading**](./datasets.md). Learn how to prepare and upload your datasets to HUB in YOLO format.\n- [**Projects: Creating and Managing**](./projects.md). Group your models into projects for improved organization.\n- [**Models: Training and Exporting**](./models.md). Train YOLOv5 and YOLOv8 models on your custom datasets and export them to various formats for deployment.\n- [**Integrations: Options**](./integrations.md). Explore different integration options for your trained models, such as TensorFlow, ONNX, OpenVINO, CoreML, and PaddlePaddle.\n- [**Ultralytics HUB App**](./app/index.md). Learn about the Ultralytics App for iOS and Android, which allows you to run models directly on your mobile device.\n    * [**iOS**](./app/ios.md). Learn about YOLO CoreML models accelerated on Apple's Neural Engine on iPhones and iPads.\n    * [**Android**](./app/android.md). Explore TFLite acceleration on mobile devices.\n- [**Inference API**](./inference_api.md). Understand how to use the Inference API for running your trained models in the cloud to generate predictions."
  },
  {
    "path": "docs/hub/inference_api.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n\n# YOLO Inference API\n\nThe YOLO Inference API allows you to access the YOLOv8 object detection capabilities via a RESTful API. This enables you to run object detection on images without the need to install and set up the YOLOv8 environment locally.\n\n## API URL\n\nThe API URL is the address used to access the YOLO Inference API. In this case, the base URL is:\n\n```\nhttps://api.ultralytics.com/v1/predict\n```\n\n## Example Usage in Python\n\nTo access the YOLO Inference API with the specified model and API key using Python, you can use the following code:\n\n```python\nimport requests\n\n# API URL, use actual MODEL_ID\nurl = f\"https://api.ultralytics.com/v1/predict/MODEL_ID\"\n\n# Headers, use actual API_KEY\nheaders = {\"x-api-key\": \"API_KEY\"}\n\n# Inference arguments (optional)\ndata = {\"size\": 640, \"confidence\": 0.25, \"iou\": 0.45}\n\n# Load image and send request\nwith open(\"path/to/image.jpg\", \"rb\") as image_file:\n    files = {\"image\": image_file}\n    response = requests.post(url, headers=headers, files=files, data=data)\n\nprint(response.json())\n```\n\nIn this example, replace `API_KEY` with your actual API key, `MODEL_ID` with the desired model ID, and `path/to/image.jpg` with the path to the image you want to analyze.\n\n## Example Usage with CLI\n\nYou can use the YOLO Inference API with the command-line interface (CLI) by utilizing the `curl` command. Replace `API_KEY` with your actual API key, `MODEL_ID` with the desired model ID, and `image.jpg` with the path to the image you want to analyze:\n\n```bash\ncurl -X POST \"https://api.ultralytics.com/v1/predict/MODEL_ID\" \\\n\t-H \"x-api-key: API_KEY\" \\\n\t-F \"image=@/path/to/image.jpg\" \\\n\t-F \"size=640\" \\\n\t-F \"confidence=0.25\" \\\n\t-F \"iou=0.45\"\n```\n\n## Passing Arguments\n\nThis command sends a POST request to the YOLO Inference API with the specified `MODEL_ID` in the URL and the `API_KEY` in the request `headers`, along with the image file specified by `@path/to/image.jpg`.\n\nHere's an example of passing the `size`, `confidence`, and `iou` arguments via the API URL using the `requests` library in Python:\n\n```python\nimport requests\n\n# API URL, use actual MODEL_ID\nurl = f\"https://api.ultralytics.com/v1/predict/MODEL_ID\"\n\n# Headers, use actual API_KEY\nheaders = {\"x-api-key\": \"API_KEY\"}\n\n# Inference arguments (optional)\ndata = {\"size\": 640, \"confidence\": 0.25, \"iou\": 0.45}\n\n# Load image and send request\nwith open(\"path/to/image.jpg\", \"rb\") as image_file:\n    files = {\"image\": image_file}\n    response = requests.post(url, headers=headers, files=files, data=data)\n\nprint(response.json())\n```\n\nIn this example, the `data` dictionary contains the query arguments `size`, `confidence`, and `iou`, which tells the API to run inference at image size 640 with confidence and IoU thresholds of 0.25 and 0.45.\n\nThis will send the query parameters along with the file in the POST request. See the table below for a full list of available inference arguments.\n\n| Inference Argument | Default | Type    | Notes                                          |\n|--------------------|---------|---------|------------------------------------------------|\n| `size`             | `640`   | `int`   | valid range is `32` - `1280` pixels            |\n| `confidence`       | `0.25`  | `float` | valid range is `0.01` - `1.0`                  |\n| `iou`              | `0.45`  | `float` | valid range is `0.0` - `0.95`                  |\n| `url`              | `''`    | `str`   | optional image URL if not image file is passed |\n| `normalize`        | `False` | `bool`  |                                                |\n\n## Return JSON format\n\nThe YOLO Inference API returns a JSON list with the detection results. The format of the JSON list will be the same as the one produced locally by the `results[0].tojson()` command.\n\nThe JSON list contains information about the detected objects, their coordinates, classes, and confidence scores.\n\n### Detect Model Format\n\nYOLO detection models, such as `yolov8n.pt`, can return JSON responses from local inference, CLI API inference, and Python API inference. All of these methods produce the same JSON response format.\n\n!!! example \"Detect Model JSON Response\"\n\n    === \"Local\"\n        ```python\n        from ultralytics import YOLO\n        \n        # Load model\n        model = YOLO('yolov8n.pt')\n\n        # Run inference\n        results = model('image.jpg')\n\n        # Print image.jpg results in JSON format\n        print(results[0].tojson())  \n        ```\n\n    === \"CLI API\"\n        ```bash\n        curl -X POST \"https://api.ultralytics.com/v1/predict/MODEL_ID\" \\ \n            -H \"x-api-key: API_KEY\" \\\n            -F \"image=@/path/to/image.jpg\" \\\n            -F \"size=640\" \\\n            -F \"confidence=0.25\" \\\n            -F \"iou=0.45\"\n        ```\n\n    === \"Python API\"\n        ```python\n        import requests\n        \n        # API URL, use actual MODEL_ID\n        url = f\"https://api.ultralytics.com/v1/predict/MODEL_ID\"\n        \n        # Headers, use actual API_KEY\n        headers = {\"x-api-key\": \"API_KEY\"}\n        \n        # Inference arguments (optional)\n        data = {\"size\": 640, \"confidence\": 0.25, \"iou\": 0.45}\n        \n        # Load image and send request\n        with open(\"path/to/image.jpg\", \"rb\") as image_file:\n            files = {\"image\": image_file}\n            response = requests.post(url, headers=headers, files=files, data=data)\n        \n        print(response.json())\n        ```\n\n    === \"JSON Response\"\n        ```json\n        {\n          \"success\": True,\n          \"message\": \"Inference complete.\",\n          \"data\": [\n            {\n              \"name\": \"person\",\n              \"class\": 0,\n              \"confidence\": 0.8359682559967041,\n              \"box\": {\n                \"x1\": 0.08974208831787109,\n                \"y1\": 0.27418340047200523,\n                \"x2\": 0.8706787109375,\n                \"y2\": 0.9887352837456598\n              }\n            },\n            {\n              \"name\": \"person\",\n              \"class\": 0,\n              \"confidence\": 0.8189555406570435,\n              \"box\": {\n                \"x1\": 0.5847355842590332,\n                \"y1\": 0.05813225640190972,\n                \"x2\": 0.8930277824401855,\n                \"y2\": 0.9903111775716146\n              }\n            },\n            {\n              \"name\": \"tie\",\n              \"class\": 27,\n              \"confidence\": 0.2909725308418274,\n              \"box\": {\n                \"x1\": 0.3433395862579346,\n                \"y1\": 0.6070465511745877,\n                \"x2\": 0.40964522361755373,\n                \"y2\": 0.9849439832899306\n              }\n            }\n          ]\n        }\n        ```\n\n### Segment Model Format\n\nYOLO segmentation models, such as `yolov8n-seg.pt`, can return JSON responses from local inference, CLI API inference, and Python API inference. All of these methods produce the same JSON response format.\n\n!!! example \"Segment Model JSON Response\"\n\n    === \"Local\"\n        ```python\n        from ultralytics import YOLO\n        \n        # Load model\n        model = YOLO('yolov8n-seg.pt')\n\n        # Run inference\n        results = model('image.jpg')\n\n        # Print image.jpg results in JSON format\n        print(results[0].tojson())  \n        ```\n\n    === \"CLI API\"\n        ```bash\n        curl -X POST \"https://api.ultralytics.com/v1/predict/MODEL_ID\" \\ \n            -H \"x-api-key: API_KEY\" \\\n            -F \"image=@/path/to/image.jpg\" \\\n            -F \"size=640\" \\\n            -F \"confidence=0.25\" \\\n            -F \"iou=0.45\"\n        ```\n\n    === \"Python API\"\n        ```python\n        import requests\n        \n        # API URL, use actual MODEL_ID\n        url = f\"https://api.ultralytics.com/v1/predict/MODEL_ID\"\n        \n        # Headers, use actual API_KEY\n        headers = {\"x-api-key\": \"API_KEY\"}\n        \n        # Inference arguments (optional)\n        data = {\"size\": 640, \"confidence\": 0.25, \"iou\": 0.45}\n        \n        # Load image and send request\n        with open(\"path/to/image.jpg\", \"rb\") as image_file:\n            files = {\"image\": image_file}\n            response = requests.post(url, headers=headers, files=files, data=data)\n        \n        print(response.json())\n        ```\n\n    === \"JSON Response\"\n        Note `segments` `x` and `y` lengths may vary from one object to another. Larger or more complex objects may have more segment points.\n        ```json\n        {\n          \"success\": True,\n          \"message\": \"Inference complete.\",\n          \"data\": [\n            {\n              \"name\": \"person\",\n              \"class\": 0,\n              \"confidence\": 0.856913149356842,\n              \"box\": {\n                \"x1\": 0.1064866065979004,\n                \"y1\": 0.2798851860894097,\n                \"x2\": 0.8738358497619629,\n                \"y2\": 0.9894873725043403\n              },\n              \"segments\": {\n                \"x\": [\n                  0.421875,\n                  0.4203124940395355,\n                  0.41718751192092896\n                  ...\n                ],\n                \"y\": [\n                  0.2888889014720917,\n                  0.2916666567325592,\n                  0.2916666567325592\n                  ...\n                ]\n              }\n            },\n            {\n              \"name\": \"person\",\n              \"class\": 0,\n              \"confidence\": 0.8512625694274902,\n              \"box\": {\n                \"x1\": 0.5757311820983887,\n                \"y1\": 0.053943040635850696,\n                \"x2\": 0.8960096359252929,\n                \"y2\": 0.985154045952691\n              },\n              \"segments\": {\n                \"x\": [\n                  0.7515624761581421,\n                  0.75,\n                  0.7437499761581421\n                  ...\n                ],\n                \"y\": [\n                  0.0555555559694767,\n                  0.05833333358168602,\n                  0.05833333358168602\n                  ...\n                ]\n              }\n            },\n            {\n              \"name\": \"tie\",\n              \"class\": 27,\n              \"confidence\": 0.6485961675643921,\n              \"box\": {\n                \"x1\": 0.33911995887756347,\n                \"y1\": 0.6057066175672743,\n                \"x2\": 0.4081430912017822,\n                \"y2\": 0.9916408962673611\n              },\n              \"segments\": {\n                \"x\": [\n                  0.37187498807907104,\n                  0.37031251192092896,\n                  0.3687500059604645\n                  ...\n                ],\n                \"y\": [\n                  0.6111111044883728,\n                  0.6138888597488403,\n                  0.6138888597488403\n                  ...\n                ]\n              }\n            }\n          ]\n        }\n        ```\n\n### Pose Model Format\n\nYOLO pose models, such as `yolov8n-pose.pt`, can return JSON responses from local inference, CLI API inference, and Python API inference. All of these methods produce the same JSON response format.\n\n!!! example \"Pose Model JSON Response\"\n\n    === \"Local\"\n        ```python\n        from ultralytics import YOLO\n        \n        # Load model\n        model = YOLO('yolov8n-seg.pt')\n\n        # Run inference\n        results = model('image.jpg')\n\n        # Print image.jpg results in JSON format\n        print(results[0].tojson())  \n        ```\n\n    === \"CLI API\"\n        ```bash\n        curl -X POST \"https://api.ultralytics.com/v1/predict/MODEL_ID\" \\ \n            -H \"x-api-key: API_KEY\" \\\n            -F \"image=@/path/to/image.jpg\" \\\n            -F \"size=640\" \\\n            -F \"confidence=0.25\" \\\n            -F \"iou=0.45\"\n        ```\n\n    === \"Python API\"\n        ```python\n        import requests\n        \n        # API URL, use actual MODEL_ID\n        url = f\"https://api.ultralytics.com/v1/predict/MODEL_ID\"\n        \n        # Headers, use actual API_KEY\n        headers = {\"x-api-key\": \"API_KEY\"}\n        \n        # Inference arguments (optional)\n        data = {\"size\": 640, \"confidence\": 0.25, \"iou\": 0.45}\n        \n        # Load image and send request\n        with open(\"path/to/image.jpg\", \"rb\") as image_file:\n            files = {\"image\": image_file}\n            response = requests.post(url, headers=headers, files=files, data=data)\n        \n        print(response.json())\n        ```\n\n    === \"JSON Response\"\n        Note COCO-keypoints pretrained models will have 17 human keypoints. The `visible` part of the keypoints indicates whether a keypoint is visible or obscured. Obscured keypoints may be outside the image or may not be visible, i.e. a person's eyes facing away from the camera.\n        ```json\n        {\n          \"success\": True,\n          \"message\": \"Inference complete.\",\n          \"data\": [\n            {\n              \"name\": \"person\",\n              \"class\": 0,\n              \"confidence\": 0.8439509868621826,\n              \"box\": {\n                \"x1\": 0.1125,\n                \"y1\": 0.28194444444444444,\n                \"x2\": 0.7953125,\n                \"y2\": 0.9902777777777778\n              },\n              \"keypoints\": {\n                \"x\": [\n                  0.5058594942092896,\n                  0.5103894472122192,\n                  0.4920862317085266\n                  ...\n                ],\n                \"y\": [\n                  0.48964157700538635,\n                  0.4643048942089081,\n                  0.4465252459049225\n                  ...\n                ],\n                \"visible\": [\n                  0.8726999163627625,\n                  0.653947651386261,\n                  0.9130823612213135\n                  ...\n                ]\n              }\n            },\n            {\n              \"name\": \"person\",\n              \"class\": 0,\n              \"confidence\": 0.7474289536476135,\n              \"box\": {\n                \"x1\": 0.58125,\n                \"y1\": 0.0625,\n                \"x2\": 0.8859375,\n                \"y2\": 0.9888888888888889\n              },\n              \"keypoints\": {\n                \"x\": [\n                  0.778544008731842,\n                  0.7976160049438477,\n                  0.7530890107154846\n                  ...\n                ],\n                \"y\": [\n                  0.27595141530036926,\n                  0.2378823608160019,\n                  0.23644638061523438\n                  ...\n                ],\n                \"visible\": [\n                  0.8900790810585022,\n                  0.789978563785553,\n                  0.8974530100822449\n                  ...\n                ]\n              }\n            }\n          ]\n        }\n        ```"
  },
  {
    "path": "docs/hub/integrations.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/hub/models.md",
    "content": "---\ncomments: true\ndescription: Train and Deploy your Model to 13 different formats, including TensorFlow, ONNX, OpenVINO, CoreML, Paddle or directly on Mobile.\n---\n\n# HUB Models\n\n## Train a Model\n\nConnect to the Ultralytics HUB notebook and use your model API key to begin training!\n\n<a href=\"https://colab.research.google.com/github/ultralytics/hub/blob/master/hub.ipynb\" target=\"_blank\">\n<img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n\n## Deploy to Real World\n\nExport your model to 13 different formats, including TensorFlow, ONNX, OpenVINO, CoreML, Paddle and many others. Run\nmodels directly on your [iOS](https://apps.apple.com/xk/app/ultralytics/id1583935240) or\n[Android](https://play.google.com/store/apps/details?id=com.ultralytics.ultralytics_app) mobile device by downloading\nthe [Ultralytics App](https://ultralytics.com/app_install)!"
  },
  {
    "path": "docs/hub/projects.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/hub/quickstart.md",
    "content": "---\ncomments: true\n---\n\n# 🚧 Page Under Construction ⚒\n\nThis page is currently under construction!️ 👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/index.md",
    "content": "---\ncomments: true\ndescription: Explore Ultralytics YOLOv8, a cutting-edge real-time object detection and image segmentation model for various applications and hardware platforms.\n---\n\n<div align=\"center\">\n  <p>\n    <a href=\"https://github.com/ultralytics/ultralytics\" target=\"_blank\">\n    <img width=\"1024\" src=\"https://raw.githubusercontent.com/ultralytics/assets/main/yolov8/banner-yolov8.png\"></a>\n  </p>\n  <a href=\"https://github.com/ultralytics/ultralytics/actions/workflows/ci.yaml\"><img src=\"https://github.com/ultralytics/ultralytics/actions/workflows/ci.yaml/badge.svg\" alt=\"Ultralytics CI\"></a>\n  <a href=\"https://zenodo.org/badge/latestdoi/264818686\"><img src=\"https://zenodo.org/badge/264818686.svg\" alt=\"YOLOv8 Citation\"></a>\n  <a href=\"https://hub.docker.com/r/ultralytics/ultralytics\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/ultralytics?logo=docker\" alt=\"Docker Pulls\"></a>\n  <br>\n  <a href=\"https://console.paperspace.com/github/ultralytics/ultralytics\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"/></a>\n  <a href=\"https://colab.research.google.com/github/ultralytics/ultralytics/blob/main/examples/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n  <a href=\"https://www.kaggle.com/ultralytics/yolov8\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n</div>\n\nIntroducing [Ultralytics](https://ultralytics.com) [YOLOv8](https://github.com/ultralytics/ultralytics), the latest version of the acclaimed real-time object detection and image segmentation model. YOLOv8 is built on cutting-edge advancements in deep learning and computer vision, offering unparalleled performance in terms of speed and accuracy. Its streamlined design makes it suitable for various applications and easily adaptable to different hardware platforms, from edge devices to cloud APIs.\n\nExplore the YOLOv8 Docs, a comprehensive resource designed to help you understand and utilize its features and capabilities. Whether you are a seasoned machine learning practitioner or new to the field, this hub aims to maximize YOLOv8's potential in your projects\n\n## Where to Start\n\n- **Install** `ultralytics` with pip and get up and running in minutes &nbsp; [:material-clock-fast: Get Started](quickstart.md){ .md-button }\n- **Predict** new images and videos with YOLOv8 &nbsp; [:octicons-image-16: Predict on Images](modes/predict.md){ .md-button }\n- **Train** a new YOLOv8 model on your own custom dataset &nbsp; [:fontawesome-solid-brain: Train a Model](modes/train.md){ .md-button }\n- **Explore** YOLOv8 tasks like segment, classify, pose and track &nbsp; [:material-magnify-expand: Explore Tasks](tasks/index.md){ .md-button }\n\n## YOLO: A Brief History\n\n[YOLO](https://arxiv.org/abs/1506.02640) (You Only Look Once), a popular object detection and image segmentation model, was developed by Joseph Redmon and Ali Farhadi at the University of Washington. Launched in 2015, YOLO quickly gained popularity for its high speed and accuracy.\n\n- [YOLOv2](https://arxiv.org/abs/1612.08242), released in 2016, improved the original model by incorporating batch normalization, anchor boxes, and dimension clusters.\n- [YOLOv3](https://pjreddie.com/media/files/papers/YOLOv3.pdf), launched in 2018, further enhanced the model's performance using a more efficient backbone network, multiple anchors and spatial pyramid pooling.\n- [YOLOv4](https://arxiv.org/abs/2004.10934) was released in 2020, introducing innovations like Mosaic data augmentation, a new anchor-free detection head, and a new loss function.\n- [YOLOv5](https://github.com/ultralytics/yolov5) further improved the model's performance and added new features such as hyperparameter optimization, integrated experiment tracking and automatic export to popular export formats.\n- [YOLOv6](https://github.com/meituan/YOLOv6) was open-sourced by [Meituan](https://about.meituan.com/) in 2022 and is in use in many of the company's autonomous delivery robots.\n- [YOLOv7](https://github.com/WongKinYiu/yolov7) added additional tasks such as pose estimation on the COCO keypoints dataset.\n- [YOLOv8](https://github.com/ultralytics/ultralytics) is the latest version of YOLO by Ultralytics. As a cutting-edge, state-of-the-art (SOTA) model, YOLOv8 builds on the success of previous versions, introducing new features and improvements for enhanced performance, flexibility, and efficiency. YOLOv8 supports a full range of vision AI tasks, including [detection](tasks/detect.md), [segmentation](tasks/segment.md), [pose estimation](tasks/pose.md), [tracking](modes/track.md), and [classification](tasks/classify.md). This versatility allows users to leverage YOLOv8's capabilities across diverse applications and domains."
  },
  {
    "path": "docs/models/index.md",
    "content": "---\ncomments: true\ndescription: Learn about the supported models and architectures, such as YOLOv3, YOLOv5, and YOLOv8, and how to contribute your own model to Ultralytics.\n---\n\n# Models\n\nUltralytics supports many models and architectures with more to come in the future. Want to add your model architecture? [Here's](../help/contributing.md) how you can contribute.\n\nIn this documentation, we provide information on four major models:\n\n1. [YOLOv3](./yolov3.md): The third iteration of the YOLO model family, known for its efficient real-time object detection capabilities.\n2. [YOLOv5](./yolov5.md): An improved version of the YOLO architecture, offering better performance and speed tradeoffs compared to previous versions.\n3. [YOLOv8](./yolov8.md): The latest version of the YOLO family, featuring enhanced capabilities such as instance segmentation, pose/keypoints estimation, and classification.\n4. [Segment Anything Model (SAM)](./sam.md): Meta's Segment Anything Model (SAM).\n5. [Realtime Detection Transformers (RT-DETR)](./rtdetr.md): Baidu's RT-DETR model.\n\nYou can use these models directly in the Command Line Interface (CLI) or in a Python environment. Below are examples of how to use the models with CLI and Python:\n\n## CLI Example\n\n```bash\nyolo task=detect mode=train model=yolov8n.yaml data=coco128.yaml epochs=100\n```\n\n## Python Example\n\n```python\nfrom ultralytics import YOLO\n\nmodel = YOLO(\"model.yaml\")  # build a YOLOv8n model from scratch\n# YOLO(\"model.pt\")  use pre-trained model if available\nmodel.info()  # display model information\nmodel.train(data=\"coco128.yaml\", epochs=100)  # train the model\n```\n\nFor more details on each model, their supported tasks, modes, and performance, please visit their respective documentation pages linked above."
  },
  {
    "path": "docs/models/rtdetr.md",
    "content": "---\ncomments: true\ndescription: Explore RT-DETR, a high-performance real-time object detector. Learn how to use pre-trained models with Ultralytics Python API for various tasks.\n---\n\n# RT-DETR\n\n## Overview\n\nReal-Time Detection Transformer (RT-DETR) is an end-to-end object detector that provides real-time performance while maintaining high accuracy. It efficiently processes multi-scale features by decoupling intra-scale interaction and cross-scale fusion, and supports flexible adjustment of inference speed using different decoder layers without retraining. RT-DETR outperforms many real-time object detectors on accelerated backends like CUDA with TensorRT.\n\n![Model example image](https://user-images.githubusercontent.com/26833433/238963168-90e8483f-90aa-4eb6-a5e1-0d408b23dd33.png)\n**Overview of RT-DETR.** Model architecture diagram showing the last three stages of the backbone {S3, S4, S5} as the input\nto the encoder. The efficient hybrid encoder transforms multiscale features into a sequence of image features through intrascale feature interaction (AIFI) and cross-scale feature-fusion module (CCFM). The IoU-aware query selection is employed\nto select a fixed number of image features to serve as initial object queries for the decoder. Finally, the decoder with auxiliary\nprediction heads iteratively optimizes object queries to generate boxes and confidence scores ([source](https://arxiv.org/pdf/2304.08069.pdf)).\n\n### Key Features\n\n- **Efficient Hybrid Encoder:** RT-DETR uses an efficient hybrid encoder that processes multi-scale features by decoupling intra-scale interaction and cross-scale fusion. This design reduces computational costs and allows for real-time object detection.\n- **IoU-aware Query Selection:** RT-DETR improves object query initialization by utilizing IoU-aware query selection. This allows the model to focus on the most relevant objects in the scene.\n- **Adaptable Inference Speed:** RT-DETR supports flexible adjustments of inference speed by using different decoder layers without the need for retraining. This adaptability facilitates practical application in various real-time object detection scenarios.\n\n## Pre-trained Models\n\nUltralytics RT-DETR provides several pre-trained models with different scales:\n\n- RT-DETR-L: 53.0% AP on COCO val2017, 114 FPS on T4 GPU\n- RT-DETR-X: 54.8% AP on COCO val2017, 74 FPS on T4 GPU\n\n## Usage\n\n### Python API\n\n```python\nfrom ultralytics import RTDETR\n\nmodel = RTDETR(\"rtdetr-l.pt\")\nmodel.info()  # display model information\nmodel.predict(\"path/to/image.jpg\")  # predict\n```\n\n### Supported Tasks\n\n| Model Type          | Pre-trained Weights | Tasks Supported  |\n|---------------------|---------------------|------------------|\n| RT-DETR Large       | `rtdetr-l.pt`       | Object Detection |\n| RT-DETR Extra-Large | `rtdetr-x.pt`       | Object Detection |\n\n### Supported Modes\n\n| Mode       | Supported          |\n|------------|--------------------|\n| Inference  | :heavy_check_mark: |\n| Validation | :heavy_check_mark: |\n| Training   | :x: (Coming soon)  |\n\n# Citations and Acknowledgements\n\nIf you use RT-DETR in your research or development work, please cite the [original paper](https://arxiv.org/abs/2304.08069):\n\n```bibtex\n@misc{lv2023detrs,\n      title={DETRs Beat YOLOs on Real-time Object Detection},\n      author={Wenyu Lv and Shangliang Xu and Yian Zhao and Guanzhong Wang and Jinman Wei and Cheng Cui and Yuning Du and Qingqing Dang and Yi Liu},\n      year={2023},\n      eprint={2304.08069},\n      archivePrefix={arXiv},\n      primaryClass={cs.CV}\n}\n```\n\nWe would like to acknowledge Baidu's [PaddlePaddle](https://github.com/PaddlePaddle/PaddleDetection) team for creating and maintaining this valuable resource for the computer vision community.\n"
  },
  {
    "path": "docs/models/sam.md",
    "content": "---\ncomments: true\ndescription: Learn about the Segment Anything Model (SAM) and how it provides promptable image segmentation through an advanced architecture and the SA-1B dataset.\n---\n\n# Segment Anything Model (SAM)\n\n## Overview\n\nThe Segment Anything Model (SAM) is a groundbreaking image segmentation model that enables promptable segmentation with real-time performance. It forms the foundation for the Segment Anything project, which introduces a new task, model, and dataset for image segmentation. SAM is designed to be promptable, allowing it to transfer zero-shot to new image distributions and tasks. The model is trained on the [SA-1B dataset](https://ai.facebook.com/datasets/segment-anything/), which contains over 1 billion masks on 11 million licensed and privacy-respecting images. SAM has demonstrated impressive zero-shot performance, often surpassing prior fully supervised results.\n\n![Dataset sample image](https://user-images.githubusercontent.com/26833433/238056229-0e8ffbeb-f81a-477e-a490-aff3d82fd8ce.jpg)\nExample images with overlaid masks from our newly introduced dataset, SA-1B. SA-1B contains 11M diverse, high-resolution, licensed, and privacy protecting images and 1.1B high-quality segmentation masks. These masks were annotated fully automatically by SAM, and as verified by human ratings and numerous experiments, are of high quality and diversity. Images are grouped by number of masks per image for visualization (there are ∼100 masks per image on average).\n\n## Key Features\n\n- **Promptable Segmentation Task:** SAM is designed for a promptable segmentation task, enabling it to return a valid segmentation mask given any segmentation prompt, such as spatial or text information identifying an object.\n- **Advanced Architecture:** SAM utilizes a powerful image encoder, a prompt encoder, and a lightweight mask decoder. This architecture enables flexible prompting, real-time mask computation, and ambiguity awareness in segmentation.\n- **SA-1B Dataset:** The Segment Anything project introduces the SA-1B dataset, which contains over 1 billion masks on 11 million images. This dataset is the largest segmentation dataset to date, providing SAM with a diverse and large-scale source of data for training.\n- **Zero-Shot Performance:** SAM demonstrates remarkable zero-shot performance across a range of segmentation tasks, allowing it to be used out-of-the-box with prompt engineering for various applications.\n\nFor more information about the Segment Anything Model and the SA-1B dataset, please refer to the [Segment Anything website](https://segment-anything.com) and the research paper [Segment Anything](https://arxiv.org/abs/2304.02643).\n\n## Usage\n\nSAM can be used for a variety of downstream tasks involving object and image distributions beyond its training data. Examples include edge detection, object proposal generation, instance segmentation, and preliminary text-to-mask prediction. By employing prompt engineering, SAM can adapt to new tasks and data distributions in a zero-shot manner, making it a versatile and powerful tool for image segmentation tasks.\n\n```python\nfrom ultralytics.vit import SAM\n\nmodel = SAM('sam_b.pt')\nmodel.info()  # display model information\nmodel.predict('path/to/image.jpg')  # predict\n```\n\n## Supported Tasks\n\n| Model Type | Pre-trained Weights | Tasks Supported       |\n|------------|---------------------|-----------------------|\n| sam base   | `sam_b.pt`          | Instance Segmentation |\n| sam large  | `sam_l.pt`          | Instance Segmentation |\n\n## Supported Modes\n\n| Mode       | Supported          |\n|------------|--------------------|\n| Inference  | :heavy_check_mark: |\n| Validation | :x:                |\n| Training   | :x:                |\n\n## Auto-Annotation\n\nAuto-annotation is an essential feature that allows you to generate a [segmentation dataset](https://docs.ultralytics.com/datasets/segment) using a pre-trained detection model. It enables you to quickly and accurately annotate a large number of images without the need for manual labeling, saving time and effort.\n\n### Generate Segmentation Dataset Using a Detection Model\n\nTo auto-annotate your dataset using the Ultralytics framework, you can use the `auto_annotate` function as shown below:\n\n```python\nfrom ultralytics.yolo.data.annotator import auto_annotate\n\nauto_annotate(data=\"path/to/images\", det_model=\"yolov8x.pt\", sam_model='sam_b.pt')\n```\n\n| Argument   | Type                | Description                                                                                             | Default      |\n|------------|---------------------|---------------------------------------------------------------------------------------------------------|--------------|\n| data       | str                 | Path to a folder containing images to be annotated.                                                     |              |\n| det_model  | str, optional       | Pre-trained YOLO detection model. Defaults to 'yolov8x.pt'.                                             | 'yolov8x.pt' |\n| sam_model  | str, optional       | Pre-trained SAM segmentation model. Defaults to 'sam_b.pt'.                                             | 'sam_b.pt'   |\n| device     | str, optional       | Device to run the models on. Defaults to an empty string (CPU or GPU, if available).                    |              |\n| output_dir | str, None, optional | Directory to save the annotated results. Defaults to a 'labels' folder in the same directory as 'data'. | None         |\n\nThe `auto_annotate` function takes the path to your images, along with optional arguments for specifying the pre-trained detection and SAM segmentation models, the device to run the models on, and the output directory for saving the annotated results.\n\nBy leveraging the power of pre-trained models, auto-annotation can significantly reduce the time and effort required for creating high-quality segmentation datasets. This feature is particularly useful for researchers and developers working with large image collections, as it allows them to focus on model development and evaluation rather than manual annotation.\n\n## Citations and Acknowledgements\n\nIf you use SAM in your research or development work, please cite the following paper:\n\n```bibtex\n@misc{kirillov2023segment,\n      title={Segment Anything}, \n      author={Alexander Kirillov and Eric Mintun and Nikhila Ravi and Hanzi Mao and Chloe Rolland and Laura Gustafson and Tete Xiao and Spencer Whitehead and Alexander C. Berg and Wan-Yen Lo and Piotr Dollár and Ross Girshick},\n      year={2023},\n      eprint={2304.02643},\n      archivePrefix={arXiv},\n      primaryClass={cs.CV}\n}\n```\n\nWe would like to acknowledge Meta AI for creating and maintaining this valuable resource for the computer vision community."
  },
  {
    "path": "docs/models/yolov3.md",
    "content": "---\ncomments: true\n---\n\n# 🚧Page Under Construction ⚒\n\nThis page is currently under construction!️👷Please check back later for updates. 😃🔜\n"
  },
  {
    "path": "docs/models/yolov5.md",
    "content": "---\ncomments: true\ndescription: Detect objects faster and more accurately using Ultralytics YOLOv5u. Find pre-trained models for each task, including Inference, Validation and Training.\n---\n\n# YOLOv5u\n\n## Overview\n\nYOLOv5u is an updated version of YOLOv5 that incorporates the anchor-free split Ultralytics head used in the YOLOv8 models. It retains the same backbone and neck architecture as YOLOv5 but offers improved accuracy-speed tradeoff for object detection tasks.\n\n## Key Features\n\n- **Anchor-free Split Ultralytics Head:** YOLOv5u replaces the traditional anchor-based detection head with an anchor-free split Ultralytics head, resulting in improved performance.\n- **Optimized Accuracy-Speed Tradeoff:** The updated model offers a better balance between accuracy and speed, making it more suitable for a wider range of applications.\n- **Variety of Pre-trained Models:** YOLOv5u offers a range of pre-trained models tailored for various tasks, including Inference, Validation, and Training.\n\n## Supported Tasks\n\n| Model Type | Pre-trained Weights                                                                                                         | Task      |\n|------------|-----------------------------------------------------------------------------------------------------------------------------|-----------|\n| YOLOv5u    | `yolov5nu`, `yolov5su`, `yolov5mu`, `yolov5lu`, `yolov5xu`, `yolov5n6u`, `yolov5s6u`, `yolov5m6u`, `yolov5l6u`, `yolov5x6u` | Detection |\n\n## Supported Modes\n\n| Mode       | Supported          |\n|------------|--------------------|\n| Inference  | :heavy_check_mark: |\n| Validation | :heavy_check_mark: |\n| Training   | :heavy_check_mark: |\n\n??? Performance\n\n    === \"Detection\"\n\n        | Model                                                                                    | size<br><sup>(pixels) | mAP<sup>val<br>50-95 | Speed<br><sup>CPU ONNX<br>(ms) | Speed<br><sup>A100 TensorRT<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>(B) |\n        | ---------------------------------------------------------------------------------------- | --------------------- | -------------------- | ------------------------------ | ----------------------------------- | ------------------ | ----------------- |\n        | [YOLOv5nu](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov5nu.pt)   | 640                   | 34.3                 | 73.6                           | 1.06                                | 2.6                | 7.7               |\n        | [YOLOv5su](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov5su.pt)   | 640                   | 43.0                 | 120.7                          | 1.27                                | 9.1                | 24.0              |\n        | [YOLOv5mu](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov5mu.pt)   | 640                   | 49.0                 | 233.9                          | 1.86                                | 25.1               | 64.2              |\n        | [YOLOv5lu](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov5lu.pt)   | 640                   | 52.2                 | 408.4                          | 2.50                                | 53.2               | 135.0             |\n        | [YOLOv5xu](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov5xu.pt)   | 640                   | 53.2                 | 763.2                          | 3.81                                | 97.2               | 246.4             |\n        |                                                                                          |                       |                      |                                |                                     |                    |                   |\n        | [YOLOv5n6u](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov5n6u.pt) | 1280                  | 42.1                 | -                              | -                                   | 4.3                | 7.8               |\n        | [YOLOv5s6u](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov5s6u.pt) | 1280                  | 48.6                 | -                              | -                                   | 15.3               | 24.6              |\n        | [YOLOv5m6u](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov5m6u.pt) | 1280                  | 53.6                 | -                              | -                                   | 41.2               | 65.7              |\n        | [YOLOv5l6u](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov5l6u.pt) | 1280                  | 55.7                 | -                              | -                                   | 86.1               | 137.4             |\n        | [YOLOv5x6u](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov5x6u.pt) | 1280                  | 56.8                 | -                              | -                                   | 155.4              | 250.7             |"
  },
  {
    "path": "docs/models/yolov8.md",
    "content": "---\ncomments: true\ndescription: Learn about YOLOv8's pre-trained weights supporting detection, instance segmentation, pose, and classification tasks. Get performance details.\n---\n\n# YOLOv8\n\n## Overview\n\nYOLOv8 is the latest iteration in the YOLO series of real-time object detectors, offering cutting-edge performance in terms of accuracy and speed. Building upon the advancements of previous YOLO versions, YOLOv8 introduces new features and optimizations that make it an ideal choice for various object detection tasks in a wide range of applications.\n\n## Key Features\n\n- **Advanced Backbone and Neck Architectures:** YOLOv8 employs state-of-the-art backbone and neck architectures, resulting in improved feature extraction and object detection performance.\n- **Anchor-free Split Ultralytics Head:** YOLOv8 adopts an anchor-free split Ultralytics head, which contributes to better accuracy and a more efficient detection process compared to anchor-based approaches.\n- **Optimized Accuracy-Speed Tradeoff:** With a focus on maintaining an optimal balance between accuracy and speed, YOLOv8 is suitable for real-time object detection tasks in diverse application areas.\n- **Variety of Pre-trained Models:** YOLOv8 offers a range of pre-trained models to cater to various tasks and performance requirements, making it easier to find the right model for your specific use case.\n\n## Supported Tasks\n\n| Model Type  | Pre-trained Weights                                                                                              | Task                  |\n|-------------|------------------------------------------------------------------------------------------------------------------|-----------------------|\n| YOLOv8      | `yolov8n.pt`, `yolov8s.pt`, `yolov8m.pt`, `yolov8l.pt`, `yolov8x.pt`                                             | Detection             |\n| YOLOv8-seg  | `yolov8n-seg.pt`, `yolov8s-seg.pt`, `yolov8m-seg.pt`, `yolov8l-seg.pt`, `yolov8x-seg.pt`                         | Instance Segmentation |\n| YOLOv8-pose | `yolov8n-pose.pt`, `yolov8s-pose.pt`, `yolov8m-pose.pt`, `yolov8l-pose.pt`, `yolov8x-pose.pt` ,`yolov8x-pose-p6` | Pose/Keypoints        |\n| YOLOv8-cls  | `yolov8n-cls.pt`, `yolov8s-cls.pt`, `yolov8m-cls.pt`, `yolov8l-cls.pt`, `yolov8x-cls.pt`                         | Classification        |\n\n## Supported Modes\n\n| Mode       | Supported          |\n|------------|--------------------|\n| Inference  | :heavy_check_mark: |\n| Validation | :heavy_check_mark: |\n| Training   | :heavy_check_mark: |\n\n??? Performance\n\n    === \"Detection\"\n\n        | Model                                                                                | size<br><sup>(pixels) | mAP<sup>val<br>50-95 | Speed<br><sup>CPU ONNX<br>(ms) | Speed<br><sup>A100 TensorRT<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>(B) |\n        | ------------------------------------------------------------------------------------ | --------------------- | -------------------- | ------------------------------ | ----------------------------------- | ------------------ | ----------------- |\n        | [YOLOv8n](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt) | 640                   | 37.3                 | 80.4                           | 0.99                                | 3.2                | 8.7               |\n        | [YOLOv8s](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s.pt) | 640                   | 44.9                 | 128.4                          | 1.20                                | 11.2               | 28.6              |\n        | [YOLOv8m](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m.pt) | 640                   | 50.2                 | 234.7                          | 1.83                                | 25.9               | 78.9              |\n        | [YOLOv8l](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l.pt) | 640                   | 52.9                 | 375.2                          | 2.39                                | 43.7               | 165.2             |\n        | [YOLOv8x](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x.pt) | 640                   | 53.9                 | 479.1                          | 3.53                                | 68.2               | 257.8             |\n\n    === \"Segmentation\"\n\n        | Model                                                                                        | size<br><sup>(pixels) | mAP<sup>box<br>50-95 | mAP<sup>mask<br>50-95 | Speed<br><sup>CPU ONNX<br>(ms) | Speed<br><sup>A100 TensorRT<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>(B) |\n        | -------------------------------------------------------------------------------------------- | --------------------- | -------------------- | --------------------- | ------------------------------ | ----------------------------------- | ------------------ | ----------------- |\n        | [YOLOv8n-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n-seg.pt) | 640                   | 36.7                 | 30.5                  | 96.1                           | 1.21                                | 3.4                | 12.6              |\n        | [YOLOv8s-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s-seg.pt) | 640                   | 44.6                 | 36.8                  | 155.7                          | 1.47                                | 11.8               | 42.6              |\n        | [YOLOv8m-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m-seg.pt) | 640                   | 49.9                 | 40.8                  | 317.0                          | 2.18                                | 27.3               | 110.2             |\n        | [YOLOv8l-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l-seg.pt) | 640                   | 52.3                 | 42.6                  | 572.4                          | 2.79                                | 46.0               | 220.5             |\n        | [YOLOv8x-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-seg.pt) | 640                   | 53.4                 | 43.4                  | 712.1                          | 4.02                                | 71.8               | 344.1             |\n\n    === \"Classification\"\n\n        | Model                                                                                        | size<br><sup>(pixels) | acc<br><sup>top1 | acc<br><sup>top5 | Speed<br><sup>CPU ONNX<br>(ms) | Speed<br><sup>A100 TensorRT<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>(B) at 640 |\n        | -------------------------------------------------------------------------------------------- | --------------------- | ---------------- | ---------------- | ------------------------------ | ----------------------------------- | ------------------ | ------------------------ |\n        | [YOLOv8n-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n-cls.pt) | 224                   | 66.6             | 87.0             | 12.9                           | 0.31                                | 2.7                | 4.3                      |\n        | [YOLOv8s-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s-cls.pt) | 224                   | 72.3             | 91.1             | 23.4                           | 0.35                                | 6.4                | 13.5                     |\n        | [YOLOv8m-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m-cls.pt) | 224                   | 76.4             | 93.2             | 85.4                           | 0.62                                | 17.0               | 42.7                     |\n        | [YOLOv8l-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l-cls.pt) | 224                   | 78.0             | 94.1             | 163.0                          | 0.87                                | 37.5               | 99.7                     |\n        | [YOLOv8x-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-cls.pt) | 224                   | 78.4             | 94.3             | 232.0                          | 1.01                                | 57.4               | 154.8                    |\n\n    === \"Pose\"\n\n        | Model                                                                                                | size<br><sup>(pixels) | mAP<sup>pose<br>50-95 | mAP<sup>pose<br>50 | Speed<br><sup>CPU ONNX<br>(ms) | Speed<br><sup>A100 TensorRT<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>(B) |\n        | ---------------------------------------------------------------------------------------------------- | --------------------- | --------------------- | ------------------ | ------------------------------ | ----------------------------------- | ------------------ | ----------------- |\n        | [YOLOv8n-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n-pose.pt)       | 640                   | 50.4                  | 80.1               | 131.8                          | 1.18                                | 3.3                | 9.2               |\n        | [YOLOv8s-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s-pose.pt)       | 640                   | 60.0                  | 86.2               | 233.2                          | 1.42                                | 11.6               | 30.2              |\n        | [YOLOv8m-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m-pose.pt)       | 640                   | 65.0                  | 88.8               | 456.3                          | 2.00                                | 26.4               | 81.0              |\n        | [YOLOv8l-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l-pose.pt)       | 640                   | 67.6                  | 90.0               | 784.5                          | 2.59                                | 44.4               | 168.6             |\n        | [YOLOv8x-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-pose.pt)       | 640                   | 69.2                  | 90.2               | 1607.1                         | 3.73                                | 69.4               | 263.2             |\n        | [YOLOv8x-pose-p6](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-pose-p6.pt) | 1280                  | 71.6                  | 91.2               | 4088.7                         | 10.04                               | 99.1               | 1066.4            |"
  },
  {
    "path": "docs/modes/benchmark.md",
    "content": "---\ncomments: true\ndescription: Benchmark mode compares speed and accuracy of various YOLOv8 export formats like ONNX or OpenVINO. Optimize formats for speed or accuracy.\n---\n\n<img width=\"1024\" src=\"https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png\">\n\n**Benchmark mode** is used to profile the speed and accuracy of various export formats for YOLOv8. The benchmarks\nprovide information on the size of the exported format, its `mAP50-95` metrics (for object detection, segmentation and pose)\nor `accuracy_top5` metrics (for classification), and the inference time in milliseconds per image across various export\nformats like ONNX, OpenVINO, TensorRT and others. This information can help users choose the optimal export format for\ntheir specific use case based on their requirements for speed and accuracy.\n\n!!! tip \"Tip\"\n\n    * Export to ONNX or OpenVINO for up to 3x CPU speedup.\n    * Export to TensorRT for up to 5x GPU speedup.\n\n## Usage Examples\n\nRun YOLOv8n benchmarks on all supported export formats including ONNX, TensorRT etc. See Arguments section below for a\nfull list of export arguments.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics.yolo.utils.benchmarks import benchmark\n        \n        # Benchmark on GPU\n        benchmark(model='yolov8n.pt', imgsz=640, half=False, device=0)\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo benchmark model=yolov8n.pt imgsz=640 half=False device=0\n        ```\n\n## Arguments\n\nArguments such as `model`, `imgsz`, `half`, `device`, and `hard_fail` provide users with the flexibility to fine-tune\nthe benchmarks to their specific needs and compare the performance of different export formats with ease.\n\n| Key         | Value   | Description                                                          |\n|-------------|---------|----------------------------------------------------------------------|\n| `model`     | `None`  | path to model file, i.e. yolov8n.pt, yolov8n.yaml                    |\n| `imgsz`     | `640`   | image size as scalar or (h, w) list, i.e. (640, 480)                 |\n| `half`      | `False` | FP16 quantization                                                    |\n| `int8`      | `False` | INT8 quantization                                                    |\n| `device`    | `None`  | device to run on, i.e. cuda device=0 or device=0,1,2,3 or device=cpu |\n| `hard_fail` | `False` | do not continue on error (bool), or val floor threshold (float)      |\n\n## Export Formats\n\nBenchmarks will attempt to run automatically on all possible export formats below.\n\n| Format                                                             | `format` Argument | Model                     | Metadata |\n|--------------------------------------------------------------------|-------------------|---------------------------|----------|\n| [PyTorch](https://pytorch.org/)                                    | -                 | `yolov8n.pt`              | ✅        |\n| [TorchScript](https://pytorch.org/docs/stable/jit.html)            | `torchscript`     | `yolov8n.torchscript`     | ✅        |\n| [ONNX](https://onnx.ai/)                                           | `onnx`            | `yolov8n.onnx`            | ✅        |\n| [OpenVINO](https://docs.openvino.ai/latest/index.html)             | `openvino`        | `yolov8n_openvino_model/` | ✅        |\n| [TensorRT](https://developer.nvidia.com/tensorrt)                  | `engine`          | `yolov8n.engine`          | ✅        |\n| [CoreML](https://github.com/apple/coremltools)                     | `coreml`          | `yolov8n.mlmodel`         | ✅        |\n| [TF SavedModel](https://www.tensorflow.org/guide/saved_model)      | `saved_model`     | `yolov8n_saved_model/`    | ✅        |\n| [TF GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb`              | `yolov8n.pb`              | ❌        |\n| [TF Lite](https://www.tensorflow.org/lite)                         | `tflite`          | `yolov8n.tflite`          | ✅        |\n| [TF Edge TPU](https://coral.ai/docs/edgetpu/models-intro/)         | `edgetpu`         | `yolov8n_edgetpu.tflite`  | ✅        |\n| [TF.js](https://www.tensorflow.org/js)                             | `tfjs`            | `yolov8n_web_model/`      | ✅        |\n| [PaddlePaddle](https://github.com/PaddlePaddle)                    | `paddle`          | `yolov8n_paddle_model/`   | ✅        |\n\nSee full `export` details in the [Export](https://docs.ultralytics.com/modes/export/) page."
  },
  {
    "path": "docs/modes/export.md",
    "content": "---\ncomments: true\ndescription: 'Export mode: Create a deployment-ready YOLOv8 model by converting it to various formats. Export to ONNX or OpenVINO for up to 3x CPU speedup.'\n---\n\n<img width=\"1024\" src=\"https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png\">\n\n**Export mode** is used for exporting a YOLOv8 model to a format that can be used for deployment. In this mode, the\nmodel is converted to a format that can be used by other software applications or hardware devices. This mode is useful\nwhen deploying the model to production environments.\n\n!!! tip \"Tip\"\n\n    * Export to ONNX or OpenVINO for up to 3x CPU speedup.\n    * Export to TensorRT for up to 5x GPU speedup.\n\n## Usage Examples\n\nExport a YOLOv8n model to a different format like ONNX or TensorRT. See Arguments section below for a full list of\nexport arguments.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load an official model\n        model = YOLO('path/to/best.pt')  # load a custom trained\n        \n        # Export the model\n        model.export(format='onnx')\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo export model=yolov8n.pt format=onnx  # export official model\n        yolo export model=path/to/best.pt format=onnx  # export custom trained model\n        ```\n\n## Arguments\n\nExport settings for YOLO models refer to the various configurations and options used to save or\nexport the model for use in other environments or platforms. These settings can affect the model's performance, size,\nand compatibility with different systems. Some common YOLO export settings include the format of the exported model\nfile (e.g. ONNX, TensorFlow SavedModel), the device on which the model will be run (e.g. CPU, GPU), and the presence of\nadditional features such as masks or multiple labels per box. Other factors that may affect the export process include\nthe specific task the model is being used for and the requirements or constraints of the target environment or platform.\nIt is important to carefully consider and configure these settings to ensure that the exported model is optimized for\nthe intended use case and can be used effectively in the target environment.\n\n| Key         | Value           | Description                                          |\n|-------------|-----------------|------------------------------------------------------|\n| `format`    | `'torchscript'` | format to export to                                  |\n| `imgsz`     | `640`           | image size as scalar or (h, w) list, i.e. (640, 480) |\n| `keras`     | `False`         | use Keras for TF SavedModel export                   |\n| `optimize`  | `False`         | TorchScript: optimize for mobile                     |\n| `half`      | `False`         | FP16 quantization                                    |\n| `int8`      | `False`         | INT8 quantization                                    |\n| `dynamic`   | `False`         | ONNX/TensorRT: dynamic axes                          |\n| `simplify`  | `False`         | ONNX/TensorRT: simplify model                        |\n| `opset`     | `None`          | ONNX: opset version (optional, defaults to latest)   |\n| `workspace` | `4`             | TensorRT: workspace size (GB)                        |\n| `nms`       | `False`         | CoreML: add NMS                                      |\n\n## Export Formats\n\nAvailable YOLOv8 export formats are in the table below. You can export to any format using the `format` argument,\ni.e. `format='onnx'` or `format='engine'`.\n\n| Format                                                             | `format` Argument | Model                     | Metadata | Arguments                                           |\n|--------------------------------------------------------------------|-------------------|---------------------------|----------|-----------------------------------------------------|\n| [PyTorch](https://pytorch.org/)                                    | -                 | `yolov8n.pt`              | ✅        | -                                                   |\n| [TorchScript](https://pytorch.org/docs/stable/jit.html)            | `torchscript`     | `yolov8n.torchscript`     | ✅        | `imgsz`, `optimize`                                 |\n| [ONNX](https://onnx.ai/)                                           | `onnx`            | `yolov8n.onnx`            | ✅        | `imgsz`, `half`, `dynamic`, `simplify`, `opset`     |\n| [OpenVINO](https://docs.openvino.ai/latest/index.html)             | `openvino`        | `yolov8n_openvino_model/` | ✅        | `imgsz`, `half`                                     |\n| [TensorRT](https://developer.nvidia.com/tensorrt)                  | `engine`          | `yolov8n.engine`          | ✅        | `imgsz`, `half`, `dynamic`, `simplify`, `workspace` |\n| [CoreML](https://github.com/apple/coremltools)                     | `coreml`          | `yolov8n.mlmodel`         | ✅        | `imgsz`, `half`, `int8`, `nms`                      |\n| [TF SavedModel](https://www.tensorflow.org/guide/saved_model)      | `saved_model`     | `yolov8n_saved_model/`    | ✅        | `imgsz`, `keras`                                    |\n| [TF GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb`              | `yolov8n.pb`              | ❌        | `imgsz`                                             |\n| [TF Lite](https://www.tensorflow.org/lite)                         | `tflite`          | `yolov8n.tflite`          | ✅        | `imgsz`, `half`, `int8`                             |\n| [TF Edge TPU](https://coral.ai/docs/edgetpu/models-intro/)         | `edgetpu`         | `yolov8n_edgetpu.tflite`  | ✅        | `imgsz`                                             |\n| [TF.js](https://www.tensorflow.org/js)                             | `tfjs`            | `yolov8n_web_model/`      | ✅        | `imgsz`                                             |\n| [PaddlePaddle](https://github.com/PaddlePaddle)                    | `paddle`          | `yolov8n_paddle_model/`   | ✅        | `imgsz`                                             |"
  },
  {
    "path": "docs/modes/index.md",
    "content": "---\ncomments: true\ndescription: Use Ultralytics YOLOv8 Modes (Train, Val, Predict, Export, Track, Benchmark) to train, validate, predict, track, export or benchmark.\n---\n\n# Ultralytics YOLOv8 Modes\n\n<img width=\"1024\" src=\"https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png\">\n\nUltralytics YOLOv8 supports several **modes** that can be used to perform different tasks. These modes are:\n\n**Train**: For training a YOLOv8 model on a custom dataset.  \n**Val**: For validating a YOLOv8 model after it has been trained.  \n**Predict**: For making predictions using a trained YOLOv8 model on new images or videos.  \n**Export**: For exporting a YOLOv8 model to a format that can be used for deployment.  \n**Track**: For tracking objects in real-time using a YOLOv8 model.  \n**Benchmark**: For benchmarking YOLOv8 exports (ONNX, TensorRT, etc.) speed and accuracy.\n\n## [Train](train.md)\n\nTrain mode is used for training a YOLOv8 model on a custom dataset. In this mode, the model is trained using the\nspecified dataset and hyperparameters. The training process involves optimizing the model's parameters so that it can\naccurately predict the classes and locations of objects in an image.\n\n[Train Examples](train.md){ .md-button .md-button--primary}\n\n## [Val](val.md)\n\nVal mode is used for validating a YOLOv8 model after it has been trained. In this mode, the model is evaluated on a\nvalidation set to measure its accuracy and generalization performance. This mode can be used to tune the hyperparameters\nof the model to improve its performance.\n\n[Val Examples](val.md){ .md-button .md-button--primary}\n\n## [Predict](predict.md)\n\nPredict mode is used for making predictions using a trained YOLOv8 model on new images or videos. In this mode, the\nmodel is loaded from a checkpoint file, and the user can provide images or videos to perform inference. The model\npredicts the classes and locations of objects in the input images or videos.\n\n[Predict Examples](predict.md){ .md-button .md-button--primary}\n\n## [Export](export.md)\n\nExport mode is used for exporting a YOLOv8 model to a format that can be used for deployment. In this mode, the model is\nconverted to a format that can be used by other software applications or hardware devices. This mode is useful when\ndeploying the model to production environments.\n\n[Export Examples](export.md){ .md-button .md-button--primary}\n\n## [Track](track.md)\n\nTrack mode is used for tracking objects in real-time using a YOLOv8 model. In this mode, the model is loaded from a\ncheckpoint file, and the user can provide a live video stream to perform real-time object tracking. This mode is useful\nfor applications such as surveillance systems or self-driving cars.\n\n[Track Examples](track.md){ .md-button .md-button--primary}\n\n## [Benchmark](benchmark.md)\n\nBenchmark mode is used to profile the speed and accuracy of various export formats for YOLOv8. The benchmarks provide\ninformation on the size of the exported format, its `mAP50-95` metrics (for object detection, segmentation and pose)\nor `accuracy_top5` metrics (for classification), and the inference time in milliseconds per image across various export\nformats like ONNX, OpenVINO, TensorRT and others. This information can help users choose the optimal export format for\ntheir specific use case based on their requirements for speed and accuracy.\n\n[Benchmark Examples](benchmark.md){ .md-button .md-button--primary}"
  },
  {
    "path": "docs/modes/predict.md",
    "content": "---\ncomments: true\ndescription: Get started with YOLOv8 Predict mode and input sources. Accepts various input sources such as images, videos, and directories.\n---\n\n<img width=\"1024\" src=\"https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png\">\n\nYOLOv8 **predict mode** can generate predictions for various tasks, returning either a list of `Results` objects or a\nmemory-efficient generator of `Results` objects when using the streaming mode. Enable streaming mode by\npassing `stream=True` in the predictor's call method.\n\n!!! example \"Predict\"\n\n    === \"Return a list with `Stream=False`\"\n        ```python\n        inputs = [img, img]  # list of numpy arrays\n        results = model(inputs)  # list of Results objects\n        \n        for result in results:\n            boxes = result.boxes  # Boxes object for bbox outputs\n            masks = result.masks  # Masks object for segmentation masks outputs\n            probs = result.probs  # Class probabilities for classification outputs\n        ```\n\n    === \"Return a generator with `Stream=True`\"\n        ```python\n        inputs = [img, img]  # list of numpy arrays\n        results = model(inputs, stream=True)  # generator of Results objects\n        \n        for result in results:\n            boxes = result.boxes  # Boxes object for bbox outputs\n            masks = result.masks  # Masks object for segmentation masks outputs\n            probs = result.probs  # Class probabilities for classification outputs\n        ```\n\n!!! tip \"Tip\"\n\n    Streaming mode with `stream=True` should be used for long videos or large predict sources, otherwise results will accumuate in memory and will eventually cause out-of-memory errors. \n\n## Sources\n\nYOLOv8 can accept various input sources, as shown in the table below. This includes images, URLs, PIL images, OpenCV,\nnumpy arrays, torch tensors, CSV files, videos, directories, globs, YouTube videos, and streams. The table indicates\nwhether each source can be used in streaming mode with `stream=True` ✅ and an example argument for each source.\n\n| source      | model(arg)                                 | type           | notes            |\n|-------------|--------------------------------------------|----------------|------------------|\n| image       | `'im.jpg'`                                 | `str`, `Path`  |                  |\n| URL         | `'https://ultralytics.com/images/bus.jpg'` | `str`          |                  |\n| screenshot  | `'screen'`                                 | `str`          |                  |\n| PIL         | `Image.open('im.jpg')`                     | `PIL.Image`    | HWC, RGB         |\n| OpenCV      | `cv2.imread('im.jpg')`                     | `np.ndarray`   | HWC, BGR         |\n| numpy       | `np.zeros((640,1280,3))`                   | `np.ndarray`   | HWC              |\n| torch       | `torch.zeros(16,3,320,640)`                | `torch.Tensor` | BCHW, RGB        |\n| CSV         | `'sources.csv'`                            | `str`, `Path`  | RTSP, RTMP, HTTP |         \n| video ✅     | `'vid.mp4'`                                | `str`, `Path`  |                  |\n| directory ✅ | `'path/'`                                  | `str`, `Path`  |                  |\n| glob ✅      | `'path/*.jpg'`                             | `str`          | Use `*` operator |\n| YouTube ✅   | `'https://youtu.be/Zgi9g1ksQHc'`           | `str`          |                  |\n| stream ✅    | `'rtsp://example.com/media.mp4'`           | `str`          | RTSP, RTMP, HTTP |\n\n## Arguments\n\n`model.predict` accepts multiple arguments that control the prediction operation. These arguments can be passed directly to `model.predict`:\n!!! example\n\n    ```\n    model.predict(source, save=True, imgsz=320, conf=0.5)\n    ```\n\nAll supported arguments:\n\n| Key            | Value                  | Description                                                                    |\n|----------------|------------------------|--------------------------------------------------------------------------------|\n| `source`       | `'ultralytics/assets'` | source directory for images or videos                                          |\n| `conf`         | `0.25`                 | object confidence threshold for detection                                      |\n| `iou`          | `0.7`                  | intersection over union (IoU) threshold for NMS                                |\n| `half`         | `False`                | use half precision (FP16)                                                      |\n| `device`       | `None`                 | device to run on, i.e. cuda device=0/1/2/3 or device=cpu                       |\n| `show`         | `False`                | show results if possible                                                       |\n| `save`         | `False`                | save images with results                                                       |\n| `save_txt`     | `False`                | save results as .txt file                                                      |\n| `save_conf`    | `False`                | save results with confidence scores                                            |\n| `save_crop`    | `False`                | save cropped images with results                                               |\n| `hide_labels`  | `False`                | hide labels                                                                    |\n| `hide_conf`    | `False`                | hide confidence scores                                                         |\n| `max_det`      | `300`                  | maximum number of detections per image                                         |\n| `vid_stride`   | `False`                | video frame-rate stride                                                        |\n| `line_width`   | `None`                 | The line width of the bounding boxes. If None, it is scaled to the image size. |\n| `visualize`    | `False`                | visualize model features                                                       |\n| `augment`      | `False`                | apply image augmentation to prediction sources                                 |\n| `agnostic_nms` | `False`                | class-agnostic NMS                                                             |\n| `retina_masks` | `False`                | use high-resolution segmentation masks                                         |\n| `classes`      | `None`                 | filter results by class, i.e. class=0, or class=[0,2,3]                        |\n| `boxes`        | `True`                 | Show boxes in segmentation predictions                                         |\n\n## Image and Video Formats\n\nYOLOv8 supports various image and video formats, as specified\nin [yolo/data/utils.py](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/yolo/data/utils.py). See the\ntables below for the valid suffixes and example predict commands.\n\n### Image Suffixes\n\n| Image Suffixes | Example Predict Command          | Reference                                                                     |\n|----------------|----------------------------------|-------------------------------------------------------------------------------|\n| .bmp           | `yolo predict source=image.bmp`  | [Microsoft BMP File Format](https://en.wikipedia.org/wiki/BMP_file_format)    |\n| .dng           | `yolo predict source=image.dng`  | [Adobe DNG](https://www.adobe.com/products/photoshop/extend.displayTab2.html) |\n| .jpeg          | `yolo predict source=image.jpeg` | [JPEG](https://en.wikipedia.org/wiki/JPEG)                                    |\n| .jpg           | `yolo predict source=image.jpg`  | [JPEG](https://en.wikipedia.org/wiki/JPEG)                                    |\n| .mpo           | `yolo predict source=image.mpo`  | [Multi Picture Object](https://fileinfo.com/extension/mpo)                    |\n| .png           | `yolo predict source=image.png`  | [Portable Network Graphics](https://en.wikipedia.org/wiki/PNG)                |\n| .tif           | `yolo predict source=image.tif`  | [Tag Image File Format](https://en.wikipedia.org/wiki/TIFF)                   |\n| .tiff          | `yolo predict source=image.tiff` | [Tag Image File Format](https://en.wikipedia.org/wiki/TIFF)                   |\n| .webp          | `yolo predict source=image.webp` | [WebP](https://en.wikipedia.org/wiki/WebP)                                    |\n| .pfm           | `yolo predict source=image.pfm`  | [Portable FloatMap](https://en.wikipedia.org/wiki/Netpbm#File_formats)        |\n\n### Video Suffixes\n\n| Video Suffixes | Example Predict Command          | Reference                                                                        |\n|----------------|----------------------------------|----------------------------------------------------------------------------------|\n| .asf           | `yolo predict source=video.asf`  | [Advanced Systems Format](https://en.wikipedia.org/wiki/Advanced_Systems_Format) |\n| .avi           | `yolo predict source=video.avi`  | [Audio Video Interleave](https://en.wikipedia.org/wiki/Audio_Video_Interleave)   |\n| .gif           | `yolo predict source=video.gif`  | [Graphics Interchange Format](https://en.wikipedia.org/wiki/GIF)                 |\n| .m4v           | `yolo predict source=video.m4v`  | [MPEG-4 Part 14](https://en.wikipedia.org/wiki/M4V)                              |\n| .mkv           | `yolo predict source=video.mkv`  | [Matroska](https://en.wikipedia.org/wiki/Matroska)                               |\n| .mov           | `yolo predict source=video.mov`  | [QuickTime File Format](https://en.wikipedia.org/wiki/QuickTime_File_Format)     |\n| .mp4           | `yolo predict source=video.mp4`  | [MPEG-4 Part 14 - Wikipedia](https://en.wikipedia.org/wiki/MPEG-4_Part_14)       |\n| .mpeg          | `yolo predict source=video.mpeg` | [MPEG-1 Part 2](https://en.wikipedia.org/wiki/MPEG-1)                            |\n| .mpg           | `yolo predict source=video.mpg`  | [MPEG-1 Part 2](https://en.wikipedia.org/wiki/MPEG-1)                            |\n| .ts            | `yolo predict source=video.ts`   | [MPEG Transport Stream](https://en.wikipedia.org/wiki/MPEG_transport_stream)     |\n| .wmv           | `yolo predict source=video.wmv`  | [Windows Media Video](https://en.wikipedia.org/wiki/Windows_Media_Video)         |\n| .webm          | `yolo predict source=video.webm` | [WebM Project](https://en.wikipedia.org/wiki/WebM)                               |\n\n## Working with Results\n\nThe `Results` object contains the following components:\n\n- `Results.boxes`: `Boxes` object with properties and methods for manipulating bounding boxes\n- `Results.masks`: `Masks` object for indexing masks or getting segment coordinates\n- `Results.probs`: `torch.Tensor` containing class probabilities or logits\n- `Results.orig_img`: Original image loaded in memory\n- `Results.path`: `Path` containing the path to the input image\n\nEach result is composed of a `torch.Tensor` by default, which allows for easy manipulation:\n\n!!! example \"Results\"\n\n    ```python\n    results = results.cuda()\n    results = results.cpu()\n    results = results.to('cpu')\n    results = results.numpy()\n    ```\n\n### Boxes\n\n`Boxes` object can be used to index, manipulate, and convert bounding boxes to different formats. Box format conversion\noperations are cached, meaning they're only calculated once per object, and those values are reused for future calls.\n\n- Indexing a `Boxes` object returns a `Boxes` object:\n\n!!! example \"Boxes\"\n\n    ```python\n    results = model(img)\n    boxes = results[0].boxes\n    box = boxes[0]  # returns one box\n    box.xyxy\n    ```\n\n- Properties and conversions\n\n!!! example \"Boxes Properties\"\n\n    ```python\n    boxes.xyxy  # box with xyxy format, (N, 4)\n    boxes.xywh  # box with xywh format, (N, 4)\n    boxes.xyxyn  # box with xyxy format but normalized, (N, 4)\n    boxes.xywhn  # box with xywh format but normalized, (N, 4)\n    boxes.conf  # confidence score, (N, 1)\n    boxes.cls  # cls, (N, 1)\n    boxes.data  # raw bboxes tensor, (N, 6) or boxes.boxes\n    ```\n\n### Masks\n\n`Masks` object can be used index, manipulate and convert masks to segments. The segment conversion operation is cached.\n\n!!! example \"Masks\"\n\n    ```python\n    results = model(inputs)\n    masks = results[0].masks  # Masks object\n    masks.xy  # x, y segments (pixels), List[segment] * N\n    masks.xyn  # x, y segments (normalized), List[segment] * N\n    masks.data  # raw masks tensor, (N, H, W) or masks.masks \n    ```\n\n### probs\n\n`probs` attribute of `Results` class is a `Tensor` containing class probabilities of a classification operation.\n\n!!! example \"Probs\"\n\n    ```python\n    results = model(inputs)\n    results[0].probs  # cls prob, (num_class, )\n    ```\n\nClass reference documentation for `Results` module and its components can be found [here](../reference/yolo/engine/results.md)\n\n## Plotting results\n\nYou can use `plot()` function of `Result` object to plot results on in image object. It plots all components(boxes,\nmasks, classification logits, etc.) found in the results object\n\n!!! example \"Plotting\"\n\n    ```python\n    res = model(img)\n    res_plotted = res[0].plot()\n    cv2.imshow(\"result\", res_plotted)\n    ```\n\n| Argument                      | Description                                                                            |\n|-------------------------------|----------------------------------------------------------------------------------------|\n| `conf (bool)`                 | Whether to plot the detection confidence score.                                        |\n| `line_width (int, optional)`  | The line width of the bounding boxes. If None, it is scaled to the image size.         |\n| `font_size (float, optional)` | The font size of the text. If None, it is scaled to the image size.                    |\n| `font (str)`                  | The font to use for the text.                                                          |\n| `pil (bool)`                  | Whether to use PIL for image plotting.                                                 |\n| `example (str)`               | An example string to display. Useful for indicating the expected format of the output. |\n| `img (numpy.ndarray)`         | Plot to another image. if not, plot to original image.                                 |\n| `labels (bool)`               | Whether to plot the label of bounding boxes.                                           |\n| `boxes (bool)`                | Whether to plot the bounding boxes.                                                    |\n| `masks (bool)`                | Whether to plot the masks.                                                             |\n| `probs (bool)`                | Whether to plot classification probability.                                            |\n\n## Streaming Source `for`-loop\n\nHere's a Python script using OpenCV (cv2) and YOLOv8 to run inference on video frames. This script assumes you have already installed the necessary packages (opencv-python and ultralytics).\n\n!!! example \"Streaming for-loop\"\n\n    ```python\n    import cv2\n    from ultralytics import YOLO\n    \n    # Load the YOLOv8 model\n    model = YOLO('yolov8n.pt')\n    \n    # Open the video file\n    video_path = \"path/to/your/video/file.mp4\"\n    cap = cv2.VideoCapture(video_path)\n    \n    # Loop through the video frames\n    while cap.isOpened():\n        # Read a frame from the video\n        success, frame = cap.read()\n    \n        if success:\n            # Run YOLOv8 inference on the frame\n            results = model(frame)\n    \n            # Visualize the results on the frame\n            annotated_frame = results[0].plot()\n    \n            # Display the annotated frame\n            cv2.imshow(\"YOLOv8 Inference\", annotated_frame)\n    \n            # Break the loop if 'q' is pressed\n            if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n                break\n        else:\n            # Break the loop if the end of the video is reached\n            break\n    \n    # Release the video capture object and close the display window\n    cap.release()\n    cv2.destroyAllWindows()\n    ```\n"
  },
  {
    "path": "docs/modes/track.md",
    "content": "---\ncomments: true\ndescription: Explore YOLOv8n-based object tracking with Ultralytics' BoT-SORT and ByteTrack. Learn configuration, usage, and customization tips.\n---\n\n<img width=\"1024\" src=\"https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png\">\n\nObject tracking is a task that involves identifying the location and class of objects, then assigning a unique ID to\nthat detection in video streams.\n\nThe output of tracker is the same as detection with an added object ID.\n\n## Available Trackers\n\nThe following tracking algorithms have been implemented and can be enabled by passing `tracker=tracker_type.yaml`\n\n* [BoT-SORT](https://github.com/NirAharon/BoT-SORT) - `botsort.yaml`\n* [ByteTrack](https://github.com/ifzhang/ByteTrack) - `bytetrack.yaml`\n\nThe default tracker is BoT-SORT.\n\n## Tracking\n\nUse a trained YOLOv8n/YOLOv8n-seg model to run tracker on video streams.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load an official detection model\n        model = YOLO('yolov8n-seg.pt')  # load an official segmentation model\n        model = YOLO('path/to/best.pt')  # load a custom model\n        \n        # Track with the model\n        results = model.track(source=\"https://youtu.be/Zgi9g1ksQHc\", show=True) \n        results = model.track(source=\"https://youtu.be/Zgi9g1ksQHc\", show=True, tracker=\"bytetrack.yaml\") \n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo track model=yolov8n.pt source=\"https://youtu.be/Zgi9g1ksQHc\"  # official detection model\n        yolo track model=yolov8n-seg.pt source=...   # official segmentation model\n        yolo track model=path/to/best.pt source=...  # custom model\n        yolo track model=path/to/best.pt  tracker=\"bytetrack.yaml\" # bytetrack tracker\n\n        ```\n\nAs in the above usage, we support both the detection and segmentation models for tracking and the only thing you need to\ndo is loading the corresponding (detection or segmentation) model.\n\n## Configuration\n\n### Tracking\n\nTracking shares the configuration with predict, i.e `conf`, `iou`, `show`. More configurations please refer\nto [predict page](https://docs.ultralytics.com/modes/predict/).\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        model = YOLO('yolov8n.pt')\n        results = model.track(source=\"https://youtu.be/Zgi9g1ksQHc\", conf=0.3, iou=0.5, show=True) \n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo track model=yolov8n.pt source=\"https://youtu.be/Zgi9g1ksQHc\" conf=0.3, iou=0.5 show\n\n        ```\n\n### Tracker\n\nWe also support using a modified tracker config file, just copy a config file i.e `custom_tracker.yaml`\nfrom [ultralytics/tracker/cfg](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/tracker/cfg) and modify\nany configurations(expect the `tracker_type`) you need to.\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        model = YOLO('yolov8n.pt')\n        results = model.track(source=\"https://youtu.be/Zgi9g1ksQHc\", tracker='custom_tracker.yaml') \n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo track model=yolov8n.pt source=\"https://youtu.be/Zgi9g1ksQHc\" tracker='custom_tracker.yaml'\n        ```\n\nPlease refer to [ultralytics/tracker/cfg](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/tracker/cfg)\npage\n\n"
  },
  {
    "path": "docs/modes/train.md",
    "content": "---\ncomments: true\ndescription: Learn how to train custom YOLOv8 models on various datasets, configure hyperparameters, and use Ultralytics' YOLO for seamless training.\n---\n\n<img width=\"1024\" src=\"https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png\">\n\n**Train mode** is used for training a YOLOv8 model on a custom dataset. In this mode, the model is trained using the\nspecified dataset and hyperparameters. The training process involves optimizing the model's parameters so that it can\naccurately predict the classes and locations of objects in an image.\n\n!!! tip \"Tip\"\n\n    * YOLOv8 datasets like COCO, VOC, ImageNet and many others automatically download on first use, i.e. `yolo train data=coco.yaml`\n\n## Usage Examples\n\nTrain YOLOv8n on the COCO128 dataset for 100 epochs at image size 640. See Arguments section below for a full list of\ntraining arguments.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.yaml')  # build a new model from YAML\n        model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n        model = YOLO('yolov8n.yaml').load('yolov8n.pt')  # build from YAML and transfer weights\n        \n        # Train the model\n        model.train(data='coco128.yaml', epochs=100, imgsz=640)\n        ```\n    === \"CLI\"\n    \n        ```bash\n        # Build a new model from YAML and start training from scratch\n        yolo detect train data=coco128.yaml model=yolov8n.yaml epochs=100 imgsz=640\n\n        # Start training from a pretrained *.pt model\n        yolo detect train data=coco128.yaml model=yolov8n.pt epochs=100 imgsz=640\n\n        # Build a new model from YAML, transfer pretrained weights to it and start training\n        yolo detect train data=coco128.yaml model=yolov8n.yaml pretrained=yolov8n.pt epochs=100 imgsz=640\n        ```\n\n## Arguments\n\nTraining settings for YOLO models refer to the various hyperparameters and configurations used to train the model on a\ndataset. These settings can affect the model's performance, speed, and accuracy. Some common YOLO training settings\ninclude the batch size, learning rate, momentum, and weight decay. Other factors that may affect the training process\ninclude the choice of optimizer, the choice of loss function, and the size and composition of the training dataset. It\nis important to carefully tune and experiment with these settings to achieve the best possible performance for a given\ntask.\n\n| Key               | Value    | Description                                                                 |\n|-------------------|----------|-----------------------------------------------------------------------------|\n| `model`           | `None`   | path to model file, i.e. yolov8n.pt, yolov8n.yaml                           |\n| `data`            | `None`   | path to data file, i.e. coco128.yaml                                        |\n| `epochs`          | `100`    | number of epochs to train for                                               |\n| `patience`        | `50`     | epochs to wait for no observable improvement for early stopping of training |\n| `batch`           | `16`     | number of images per batch (-1 for AutoBatch)                               |\n| `imgsz`           | `640`    | size of input images as integer or w,h                                      |\n| `save`            | `True`   | save train checkpoints and predict results                                  |\n| `save_period`     | `-1`     | Save checkpoint every x epochs (disabled if < 1)                            |\n| `cache`           | `False`  | True/ram, disk or False. Use cache for data loading                         |\n| `device`          | `None`   | device to run on, i.e. cuda device=0 or device=0,1,2,3 or device=cpu        |\n| `workers`         | `8`      | number of worker threads for data loading (per RANK if DDP)                 |\n| `project`         | `None`   | project name                                                                |\n| `name`            | `None`   | experiment name                                                             |\n| `exist_ok`        | `False`  | whether to overwrite existing experiment                                    |\n| `pretrained`      | `False`  | whether to use a pretrained model                                           |\n| `optimizer`       | `'SGD'`  | optimizer to use, choices=['SGD', 'Adam', 'AdamW', 'RMSProp']               |\n| `verbose`         | `False`  | whether to print verbose output                                             |\n| `seed`            | `0`      | random seed for reproducibility                                             |\n| `deterministic`   | `True`   | whether to enable deterministic mode                                        |\n| `single_cls`      | `False`  | train multi-class data as single-class                                      |\n| `rect`            | `False`  | rectangular training with each batch collated for minimum padding           |\n| `cos_lr`          | `False`  | use cosine learning rate scheduler                                          |\n| `close_mosaic`    | `0`      | (int) disable mosaic augmentation for final epochs                          |\n| `resume`          | `False`  | resume training from last checkpoint                                        |\n| `amp`             | `True`   | Automatic Mixed Precision (AMP) training, choices=[True, False]             |\n| `lr0`             | `0.01`   | initial learning rate (i.e. SGD=1E-2, Adam=1E-3)                            |\n| `lrf`             | `0.01`   | final learning rate (lr0 * lrf)                                             |\n| `momentum`        | `0.937`  | SGD momentum/Adam beta1                                                     |\n| `weight_decay`    | `0.0005` | optimizer weight decay 5e-4                                                 |\n| `warmup_epochs`   | `3.0`    | warmup epochs (fractions ok)                                                |\n| `warmup_momentum` | `0.8`    | warmup initial momentum                                                     |\n| `warmup_bias_lr`  | `0.1`    | warmup initial bias lr                                                      |\n| `box`             | `7.5`    | box loss gain                                                               |\n| `cls`             | `0.5`    | cls loss gain (scale with pixels)                                           |\n| `dfl`             | `1.5`    | dfl loss gain                                                               |\n| `pose`            | `12.0`   | pose loss gain (pose-only)                                                  |\n| `kobj`            | `2.0`    | keypoint obj loss gain (pose-only)                                          |\n| `label_smoothing` | `0.0`    | label smoothing (fraction)                                                  |\n| `nbs`             | `64`     | nominal batch size                                                          |\n| `overlap_mask`    | `True`   | masks should overlap during training (segment train only)                   |\n| `mask_ratio`      | `4`      | mask downsample ratio (segment train only)                                  |\n| `dropout`         | `0.0`    | use dropout regularization (classify train only)                            |\n| `val`             | `True`   | validate/test during training                                               |\n"
  },
  {
    "path": "docs/modes/val.md",
    "content": "---\ncomments: true\ndescription: Validate and improve YOLOv8n model accuracy on COCO128 and other datasets using hyperparameter & configuration tuning, in Val mode.\n---\n\n<img width=\"1024\" src=\"https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png\">\n\n**Val mode** is used for validating a YOLOv8 model after it has been trained. In this mode, the model is evaluated on a\nvalidation set to measure its accuracy and generalization performance. This mode can be used to tune the hyperparameters\nof the model to improve its performance.\n\n!!! tip \"Tip\"\n\n    * YOLOv8 models automatically remember their training settings, so you can validate a model at the same image size and on the original dataset easily with just `yolo val model=yolov8n.pt` or `model('yolov8n.pt').val()`\n\n## Usage Examples\n\nValidate trained YOLOv8n model accuracy on the COCO128 dataset. No argument need to passed as the `model` retains it's\ntraining `data` and arguments as model attributes. See Arguments section below for a full list of export arguments.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load an official model\n        model = YOLO('path/to/best.pt')  # load a custom model\n        \n        # Validate the model\n        metrics = model.val()  # no arguments needed, dataset and settings remembered\n        metrics.box.map    # map50-95\n        metrics.box.map50  # map50\n        metrics.box.map75  # map75\n        metrics.box.maps   # a list contains map50-95 of each category\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo detect val model=yolov8n.pt  # val official model\n        yolo detect val model=path/to/best.pt  # val custom model\n        ```\n\n## Arguments\n\nValidation settings for YOLO models refer to the various hyperparameters and configurations used to\nevaluate the model's performance on a validation dataset. These settings can affect the model's performance, speed, and\naccuracy. Some common YOLO validation settings include the batch size, the frequency with which validation is performed\nduring training, and the metrics used to evaluate the model's performance. Other factors that may affect the validation\nprocess include the size and composition of the validation dataset and the specific task the model is being used for. It\nis important to carefully tune and experiment with these settings to ensure that the model is performing well on the\nvalidation dataset and to detect and prevent overfitting.\n\n| Key           | Value   | Description                                                        |\n|---------------|---------|--------------------------------------------------------------------|\n| `data`        | `None`  | path to data file, i.e. coco128.yaml                               |\n| `imgsz`       | `640`   | image size as scalar or (h, w) list, i.e. (640, 480)               |\n| `batch`       | `16`    | number of images per batch (-1 for AutoBatch)                      |\n| `save_json`   | `False` | save results to JSON file                                          |\n| `save_hybrid` | `False` | save hybrid version of labels (labels + additional predictions)    |\n| `conf`        | `0.001` | object confidence threshold for detection                          |\n| `iou`         | `0.6`   | intersection over union (IoU) threshold for NMS                    |\n| `max_det`     | `300`   | maximum number of detections per image                             |\n| `half`        | `True`  | use half precision (FP16)                                          |\n| `device`      | `None`  | device to run on, i.e. cuda device=0/1/2/3 or device=cpu           |\n| `dnn`         | `False` | use OpenCV DNN for ONNX inference                                  |\n| `plots`       | `False` | show plots during training                                         |\n| `rect`        | `False` | rectangular val with each batch collated for minimum padding       |\n| `split`       | `val`   | dataset split to use for validation, i.e. 'val', 'test' or 'train' |\n\n## Export Formats\n\nAvailable YOLOv8 export formats are in the table below. You can export to any format using the `format` argument,\ni.e. `format='onnx'` or `format='engine'`.\n\n| Format                                                             | `format` Argument | Model                     | Metadata | Arguments                                           |\n|--------------------------------------------------------------------|-------------------|---------------------------|----------|-----------------------------------------------------|\n| [PyTorch](https://pytorch.org/)                                    | -                 | `yolov8n.pt`              | ✅        | -                                                   |\n| [TorchScript](https://pytorch.org/docs/stable/jit.html)            | `torchscript`     | `yolov8n.torchscript`     | ✅        | `imgsz`, `optimize`                                 |\n| [ONNX](https://onnx.ai/)                                           | `onnx`            | `yolov8n.onnx`            | ✅        | `imgsz`, `half`, `dynamic`, `simplify`, `opset`     |\n| [OpenVINO](https://docs.openvino.ai/latest/index.html)             | `openvino`        | `yolov8n_openvino_model/` | ✅        | `imgsz`, `half`                                     |\n| [TensorRT](https://developer.nvidia.com/tensorrt)                  | `engine`          | `yolov8n.engine`          | ✅        | `imgsz`, `half`, `dynamic`, `simplify`, `workspace` |\n| [CoreML](https://github.com/apple/coremltools)                     | `coreml`          | `yolov8n.mlmodel`         | ✅        | `imgsz`, `half`, `int8`, `nms`                      |\n| [TF SavedModel](https://www.tensorflow.org/guide/saved_model)      | `saved_model`     | `yolov8n_saved_model/`    | ✅        | `imgsz`, `keras`                                    |\n| [TF GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb`              | `yolov8n.pb`              | ❌        | `imgsz`                                             |\n| [TF Lite](https://www.tensorflow.org/lite)                         | `tflite`          | `yolov8n.tflite`          | ✅        | `imgsz`, `half`, `int8`                             |\n| [TF Edge TPU](https://coral.ai/docs/edgetpu/models-intro/)         | `edgetpu`         | `yolov8n_edgetpu.tflite`  | ✅        | `imgsz`                                             |\n| [TF.js](https://www.tensorflow.org/js)                             | `tfjs`            | `yolov8n_web_model/`      | ✅        | `imgsz`                                             |\n| [PaddlePaddle](https://github.com/PaddlePaddle)                    | `paddle`          | `yolov8n_paddle_model/`   | ✅        | `imgsz`                                             |"
  },
  {
    "path": "docs/overrides/partials/comments.html",
    "content": "{% if page.meta.comments %}\n<h2 id=\"__comments\">{{ lang.t(\"meta.comments\") }}</h2>\n\n<!-- Insert Giscus code snippet from https://giscus.app/ here -->\n<script src=\"https://giscus.app/client.js\"\n        data-repo=\"ultralytics/ultralytics\"\n        data-repo-id=\"R_kgDOH-jzvQ\"\n        data-category=\"Docs\"\n        data-category-id=\"DIC_kwDOH-jzvc4CWLkL\"\n        data-mapping=\"title\"\n        data-strict=\"0\"\n        data-reactions-enabled=\"1\"\n        data-emit-metadata=\"0\"\n        data-input-position=\"bottom\"\n        data-theme=\"preferred_color_scheme\"\n        data-lang=\"en\"\n        crossorigin=\"anonymous\"\n        async>\n</script>\n\n<!-- Synchronize Giscus theme with palette -->\n<script>\n    var giscus = document.querySelector(\"script[src*=giscus]\")\n\n    /* Set palette on initial load */\n    var palette = __md_get(\"__palette\")\n    if (palette && typeof palette.color === \"object\") {\n      var theme = palette.color.scheme === \"slate\" ? \"dark\" : \"light\"\n      giscus.setAttribute(\"data-theme\", theme)\n    }\n\n    /* Register event handlers after documented loaded */\n    document.addEventListener(\"DOMContentLoaded\", function() {\n      var ref = document.querySelector(\"[data-md-component=palette]\")\n      ref.addEventListener(\"change\", function() {\n        var palette = __md_get(\"__palette\")\n        if (palette && typeof palette.color === \"object\") {\n          var theme = palette.color.scheme === \"slate\" ? \"dark\" : \"light\"\n\n          /* Instruct Giscus to change theme */\n          var frame = document.querySelector(\".giscus-frame\")\n          frame.contentWindow.postMessage(\n            { giscus: { setConfig: { theme } } },\n            \"https://giscus.app\"\n          )\n        }\n      })\n    })\n</script>\n{% endif %}\n"
  },
  {
    "path": "docs/overrides/partials/source-file.html",
    "content": "{% import \"partials/language.html\" as lang with context %}\n\n<!-- taken from\nhttps://github.com/squidfunk/mkdocs-material/blob/master/src/partials/source-file.html -->\n\n<br>\n<div class=\"md-source-file\">\n    <small>\n\n        <!-- mkdocs-git-revision-date-localized-plugin -->\n        {% if page.meta.git_revision_date_localized %}\n        📅 {{ lang.t(\"source.file.date.updated\") }}:\n        {{ page.meta.git_revision_date_localized }}\n        {% if page.meta.git_creation_date_localized %}\n        <br/>\n        🎂 {{ lang.t(\"source.file.date.created\") }}:\n        {{ page.meta.git_creation_date_localized }}\n        {% endif %}\n\n        <!-- mkdocs-git-revision-date-plugin -->\n        {% elif page.meta.revision_date %}\n        📅 {{ lang.t(\"source.file.date.updated\") }}:\n        {{ page.meta.revision_date }}\n        {% endif %}\n    </small>\n</div>\n"
  },
  {
    "path": "docs/quickstart.md",
    "content": "---\ncomments: true\ndescription: Install and use YOLOv8 via CLI or Python. Run single-line commands or integrate with Python projects for object detection, segmentation, and classification.\n---\n\n## Install\n\nInstall YOLOv8 via the `ultralytics` pip package for the latest stable release or by cloning\nthe [https://github.com/ultralytics/ultralytics](https://github.com/ultralytics/ultralytics) repository for the most\nup-to-date version.\n\n!!! example \"Install\"\n\n    === \"pip install (recommended)\"\n        ```bash\n        pip install ultralytics\n        ```\n\n    === \"git clone (for development)\"\n        ```bash\n        git clone https://github.com/ultralytics/ultralytics\n        cd ultralytics\n        pip install -e .\n        ```\n\nSee the `ultralytics` [requirements.txt](https://github.com/ultralytics/ultralytics/blob/main/requirements.txt) file for a list of dependencies. Note that `pip` automatically installs all required dependencies.\n\n!!! tip \"Tip\"\n\n    PyTorch requirements vary by operating system and CUDA requirements, so it's recommended to install PyTorch first following instructions at [https://pytorch.org/get-started/locally](https://pytorch.org/get-started/locally).\n\n    <a href=\"https://pytorch.org/get-started/locally/\">\n        <img width=\"800\" alt=\"PyTorch Installation Instructions\" src=\"https://user-images.githubusercontent.com/26833433/228650108-ab0ec98a-b328-4f40-a40d-95355e8a84e3.png\">\n    </a>\n\n## Use with CLI\n\nThe YOLO command line interface (CLI) allows for simple single-line commands without the need for a Python environment.\nCLI requires no customization or Python code. You can simply run all tasks from the terminal with the `yolo` command. Check out the [CLI Guide](usage/cli.md) to learn more about using YOLOv8 from the command line.\n\n!!! example\n\n    === \"Syntax\"\n\n        Ultralytics `yolo` commands use the following syntax:\n        ```bash\n        yolo TASK MODE ARGS\n\n        Where   TASK (optional) is one of [detect, segment, classify]\n                MODE (required) is one of [train, val, predict, export, track]\n                ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.\n        ```\n        See all ARGS in the full [Configuration Guide](usage/cfg.md) or with `yolo cfg`\n\n    === \"Train\"\n\n        Train a detection model for 10 epochs with an initial learning_rate of 0.01\n        ```bash\n        yolo train data=coco128.yaml model=yolov8n.pt epochs=10 lr0=0.01\n        ```\n\n    === \"Predict\"\n\n        Predict a YouTube video using a pretrained segmentation model at image size 320:\n        ```bash\n        yolo predict model=yolov8n-seg.pt source='https://youtu.be/Zgi9g1ksQHc' imgsz=320\n        ```\n\n    === \"Val\"\n\n        Val a pretrained detection model at batch-size 1 and image size 640:\n        ```bash\n        yolo val model=yolov8n.pt data=coco128.yaml batch=1 imgsz=640\n        ```\n\n    === \"Export\"\n\n        Export a YOLOv8n classification model to ONNX format at image size 224 by 128 (no TASK required)\n        ```bash\n        yolo export model=yolov8n-cls.pt format=onnx imgsz=224,128\n        ```\n\n    === \"Special\"\n\n        Run special commands to see version, view settings, run checks and more:\n        ```bash\n        yolo help\n        yolo checks\n        yolo version\n        yolo settings\n        yolo copy-cfg\n        yolo cfg\n        ```\n\n!!! warning \"Warning\"\n\n    Arguments must be passed as `arg=val` pairs, split by an equals `=` sign and delimited by spaces ` ` between pairs. Do not use `--` argument prefixes or commas `,` between arguments.\n\n    - `yolo predict model=yolov8n.pt imgsz=640 conf=0.25` &nbsp; ✅\n    - `yolo predict model yolov8n.pt imgsz 640 conf 0.25` &nbsp; ❌\n    - `yolo predict --model yolov8n.pt --imgsz 640 --conf 0.25` &nbsp; ❌\n\n[CLI Guide](usage/cli.md){ .md-button .md-button--primary}\n\n## Use with Python\n\nYOLOv8's Python interface allows for seamless integration into your Python projects, making it easy to load, run, and process the model's output. Designed with simplicity and ease of use in mind, the Python interface enables users to quickly implement object detection, segmentation, and classification in their projects. This makes YOLOv8's Python interface an invaluable tool for anyone looking to incorporate these functionalities into their Python projects.\n\nFor example, users can load a model, train it, evaluate its performance on a validation set, and even export it to ONNX format with just a few lines of code. Check out the [Python Guide](usage/python.md) to learn more about using YOLOv8 within your Python projects.\n\n!!! example\n\n    ```python\n    from ultralytics import YOLO\n    \n    # Create a new YOLO model from scratch\n    model = YOLO('yolov8n.yaml')\n    \n    # Load a pretrained YOLO model (recommended for training)\n    model = YOLO('yolov8n.pt')\n    \n    # Train the model using the 'coco128.yaml' dataset for 3 epochs\n    results = model.train(data='coco128.yaml', epochs=3)\n    \n    # Evaluate the model's performance on the validation set\n    results = model.val()\n    \n    # Perform object detection on an image using the model\n    results = model('https://ultralytics.com/images/bus.jpg')\n    \n    # Export the model to ONNX format\n    success = model.export(format='onnx')\n    ```\n\n[Python Guide](usage/python.md){.md-button .md-button--primary}"
  },
  {
    "path": "docs/reference/hub/auth.md",
    "content": "---\ndescription: Learn how to use Ultralytics hub authentication in your projects with examples and guidelines from the Auth page on Ultralytics Docs.\n---\n\n# Auth\n---\n:::ultralytics.hub.auth.Auth\n<br><br>\n"
  },
  {
    "path": "docs/reference/hub/session.md",
    "content": "---\ndescription: Accelerate your AI development with the Ultralytics HUB Training Session. High-performance training of object detection models.\n---\n\n# HUBTrainingSession\n---\n:::ultralytics.hub.session.HUBTrainingSession\n<br><br>\n"
  },
  {
    "path": "docs/reference/hub/utils.md",
    "content": "---\ndescription: Explore Ultralytics events, including 'request_with_credentials' and 'smart_request', to improve your project's performance and efficiency.\n---\n\n# Events\n---\n:::ultralytics.hub.utils.Events\n<br><br>\n\n# request_with_credentials\n---\n:::ultralytics.hub.utils.request_with_credentials\n<br><br>\n\n# requests_with_progress\n---\n:::ultralytics.hub.utils.requests_with_progress\n<br><br>\n\n# smart_request\n---\n:::ultralytics.hub.utils.smart_request\n<br><br>\n"
  },
  {
    "path": "docs/reference/nn/autobackend.md",
    "content": "---\ndescription: Ensure class names match filenames for easy imports. Use AutoBackend to automatically rename and refactor model files.\n---\n\n# AutoBackend\n---\n:::ultralytics.nn.autobackend.AutoBackend\n<br><br>\n\n# check_class_names\n---\n:::ultralytics.nn.autobackend.check_class_names\n<br><br>\n"
  },
  {
    "path": "docs/reference/nn/autoshape.md",
    "content": "---\ndescription: Detect 80+ object categories with bounding box coordinates and class probabilities using AutoShape in Ultralytics YOLO. Explore Detections now.\n---\n\n# AutoShape\n---\n:::ultralytics.nn.autoshape.AutoShape\n<br><br>\n\n# Detections\n---\n:::ultralytics.nn.autoshape.Detections\n<br><br>\n"
  },
  {
    "path": "docs/reference/nn/modules/block.md",
    "content": "---\ndescription: Explore ultralytics.nn.modules.block to build powerful YOLO object detection models. Master DFL, HGStem, SPP, CSP components and more.\n---\n\n# DFL\n---\n:::ultralytics.nn.modules.block.DFL\n<br><br>\n\n# Proto\n---\n:::ultralytics.nn.modules.block.Proto\n<br><br>\n\n# HGStem\n---\n:::ultralytics.nn.modules.block.HGStem\n<br><br>\n\n# HGBlock\n---\n:::ultralytics.nn.modules.block.HGBlock\n<br><br>\n\n# SPP\n---\n:::ultralytics.nn.modules.block.SPP\n<br><br>\n\n# SPPF\n---\n:::ultralytics.nn.modules.block.SPPF\n<br><br>\n\n# C1\n---\n:::ultralytics.nn.modules.block.C1\n<br><br>\n\n# C2\n---\n:::ultralytics.nn.modules.block.C2\n<br><br>\n\n# C2f\n---\n:::ultralytics.nn.modules.block.C2f\n<br><br>\n\n# C3\n---\n:::ultralytics.nn.modules.block.C3\n<br><br>\n\n# C3x\n---\n:::ultralytics.nn.modules.block.C3x\n<br><br>\n\n# RepC3\n---\n:::ultralytics.nn.modules.block.RepC3\n<br><br>\n\n# C3TR\n---\n:::ultralytics.nn.modules.block.C3TR\n<br><br>\n\n# C3Ghost\n---\n:::ultralytics.nn.modules.block.C3Ghost\n<br><br>\n\n# GhostBottleneck\n---\n:::ultralytics.nn.modules.block.GhostBottleneck\n<br><br>\n\n# Bottleneck\n---\n:::ultralytics.nn.modules.block.Bottleneck\n<br><br>\n\n# BottleneckCSP\n---\n:::ultralytics.nn.modules.block.BottleneckCSP\n<br><br>\n"
  },
  {
    "path": "docs/reference/nn/modules/conv.md",
    "content": "---\ndescription: Explore convolutional neural network modules & techniques such as LightConv, DWConv, ConvTranspose, GhostConv, CBAM & autopad with Ultralytics Docs.\n---\n\n# Conv\n---\n:::ultralytics.nn.modules.conv.Conv\n<br><br>\n\n# LightConv\n---\n:::ultralytics.nn.modules.conv.LightConv\n<br><br>\n\n# DWConv\n---\n:::ultralytics.nn.modules.conv.DWConv\n<br><br>\n\n# DWConvTranspose2d\n---\n:::ultralytics.nn.modules.conv.DWConvTranspose2d\n<br><br>\n\n# ConvTranspose\n---\n:::ultralytics.nn.modules.conv.ConvTranspose\n<br><br>\n\n# Focus\n---\n:::ultralytics.nn.modules.conv.Focus\n<br><br>\n\n# GhostConv\n---\n:::ultralytics.nn.modules.conv.GhostConv\n<br><br>\n\n# RepConv\n---\n:::ultralytics.nn.modules.conv.RepConv\n<br><br>\n\n# ChannelAttention\n---\n:::ultralytics.nn.modules.conv.ChannelAttention\n<br><br>\n\n# SpatialAttention\n---\n:::ultralytics.nn.modules.conv.SpatialAttention\n<br><br>\n\n# CBAM\n---\n:::ultralytics.nn.modules.conv.CBAM\n<br><br>\n\n# Concat\n---\n:::ultralytics.nn.modules.conv.Concat\n<br><br>\n\n# autopad\n---\n:::ultralytics.nn.modules.conv.autopad\n<br><br>\n"
  },
  {
    "path": "docs/reference/nn/modules/head.md",
    "content": "---\ndescription: 'Learn about Ultralytics YOLO modules: Segment, Classify, and RTDETRDecoder. Optimize object detection and classification in your project.'\n---\n\n# Detect\n---\n:::ultralytics.nn.modules.head.Detect\n<br><br>\n\n# Segment\n---\n:::ultralytics.nn.modules.head.Segment\n<br><br>\n\n# Pose\n---\n:::ultralytics.nn.modules.head.Pose\n<br><br>\n\n# Classify\n---\n:::ultralytics.nn.modules.head.Classify\n<br><br>\n\n# RTDETRDecoder\n---\n:::ultralytics.nn.modules.head.RTDETRDecoder\n<br><br>\n"
  },
  {
    "path": "docs/reference/nn/modules/transformer.md",
    "content": "---\ndescription: Explore the Ultralytics nn modules pages on Transformer and MLP blocks, LayerNorm2d, and Deformable Transformer Decoder Layer.\n---\n\n# TransformerEncoderLayer\n---\n:::ultralytics.nn.modules.transformer.TransformerEncoderLayer\n<br><br>\n\n# AIFI\n---\n:::ultralytics.nn.modules.transformer.AIFI\n<br><br>\n\n# TransformerLayer\n---\n:::ultralytics.nn.modules.transformer.TransformerLayer\n<br><br>\n\n# TransformerBlock\n---\n:::ultralytics.nn.modules.transformer.TransformerBlock\n<br><br>\n\n# MLPBlock\n---\n:::ultralytics.nn.modules.transformer.MLPBlock\n<br><br>\n\n# MLP\n---\n:::ultralytics.nn.modules.transformer.MLP\n<br><br>\n\n# LayerNorm2d\n---\n:::ultralytics.nn.modules.transformer.LayerNorm2d\n<br><br>\n\n# MSDeformAttn\n---\n:::ultralytics.nn.modules.transformer.MSDeformAttn\n<br><br>\n\n# DeformableTransformerDecoderLayer\n---\n:::ultralytics.nn.modules.transformer.DeformableTransformerDecoderLayer\n<br><br>\n\n# DeformableTransformerDecoder\n---\n:::ultralytics.nn.modules.transformer.DeformableTransformerDecoder\n<br><br>\n"
  },
  {
    "path": "docs/reference/nn/modules/utils.md",
    "content": "---\ndescription: 'Learn about Ultralytics NN modules: get_clones, linear_init_, and multi_scale_deformable_attn_pytorch. Code examples and usage tips.'\n---\n\n# _get_clones\n---\n:::ultralytics.nn.modules.utils._get_clones\n<br><br>\n\n# bias_init_with_prob\n---\n:::ultralytics.nn.modules.utils.bias_init_with_prob\n<br><br>\n\n# linear_init_\n---\n:::ultralytics.nn.modules.utils.linear_init_\n<br><br>\n\n# inverse_sigmoid\n---\n:::ultralytics.nn.modules.utils.inverse_sigmoid\n<br><br>\n\n# multi_scale_deformable_attn_pytorch\n---\n:::ultralytics.nn.modules.utils.multi_scale_deformable_attn_pytorch\n<br><br>\n"
  },
  {
    "path": "docs/reference/nn/tasks.md",
    "content": "---\ndescription: Learn how to work with Ultralytics YOLO Detection, Segmentation & Classification Models, load weights and parse models in PyTorch.\n---\n\n# BaseModel\n---\n:::ultralytics.nn.tasks.BaseModel\n<br><br>\n\n# DetectionModel\n---\n:::ultralytics.nn.tasks.DetectionModel\n<br><br>\n\n# SegmentationModel\n---\n:::ultralytics.nn.tasks.SegmentationModel\n<br><br>\n\n# PoseModel\n---\n:::ultralytics.nn.tasks.PoseModel\n<br><br>\n\n# ClassificationModel\n---\n:::ultralytics.nn.tasks.ClassificationModel\n<br><br>\n\n# Ensemble\n---\n:::ultralytics.nn.tasks.Ensemble\n<br><br>\n\n# torch_safe_load\n---\n:::ultralytics.nn.tasks.torch_safe_load\n<br><br>\n\n# attempt_load_weights\n---\n:::ultralytics.nn.tasks.attempt_load_weights\n<br><br>\n\n# attempt_load_one_weight\n---\n:::ultralytics.nn.tasks.attempt_load_one_weight\n<br><br>\n\n# parse_model\n---\n:::ultralytics.nn.tasks.parse_model\n<br><br>\n\n# yaml_model_load\n---\n:::ultralytics.nn.tasks.yaml_model_load\n<br><br>\n\n# guess_model_scale\n---\n:::ultralytics.nn.tasks.guess_model_scale\n<br><br>\n\n# guess_model_task\n---\n:::ultralytics.nn.tasks.guess_model_task\n<br><br>\n"
  },
  {
    "path": "docs/reference/tracker/track.md",
    "content": "---\ndescription: Learn how to register custom event-tracking and track predictions with Ultralytics YOLO via on_predict_start and register_tracker methods.\n---\n\n# on_predict_start\n---\n:::ultralytics.tracker.track.on_predict_start\n<br><br>\n\n# on_predict_postprocess_end\n---\n:::ultralytics.tracker.track.on_predict_postprocess_end\n<br><br>\n\n# register_tracker\n---\n:::ultralytics.tracker.track.register_tracker\n<br><br>\n"
  },
  {
    "path": "docs/reference/tracker/trackers/basetrack.md",
    "content": "---\ndescription: 'TrackState: A comprehensive guide to Ultralytics tracker''s BaseTrack for monitoring model performance. Improve your tracking capabilities now!'\n---\n\n# TrackState\n---\n:::ultralytics.tracker.trackers.basetrack.TrackState\n<br><br>\n\n# BaseTrack\n---\n:::ultralytics.tracker.trackers.basetrack.BaseTrack\n<br><br>\n"
  },
  {
    "path": "docs/reference/tracker/trackers/bot_sort.md",
    "content": "---\ndescription: '\"Optimize tracking with Ultralytics BOTrack. Easily sort and track bots with BOTSORT. Streamline data collection for improved performance.\"'\n---\n\n# BOTrack\n---\n:::ultralytics.tracker.trackers.bot_sort.BOTrack\n<br><br>\n\n# BOTSORT\n---\n:::ultralytics.tracker.trackers.bot_sort.BOTSORT\n<br><br>\n"
  },
  {
    "path": "docs/reference/tracker/trackers/byte_tracker.md",
    "content": "---\ndescription: Learn how to track ByteAI model sizes and tips for model optimization with STrack, a byte tracking tool from Ultralytics.\n---\n\n# STrack\n---\n:::ultralytics.tracker.trackers.byte_tracker.STrack\n<br><br>\n\n# BYTETracker\n---\n:::ultralytics.tracker.trackers.byte_tracker.BYTETracker\n<br><br>\n"
  },
  {
    "path": "docs/reference/tracker/utils/gmc.md",
    "content": "---\ndescription: '\"Track Google Marketing Campaigns in GMC with Ultralytics Tracker. Learn to set up and use GMC for detailed analytics. Get started now.\"'\n---\n\n# GMC\n---\n:::ultralytics.tracker.utils.gmc.GMC\n<br><br>\n"
  },
  {
    "path": "docs/reference/tracker/utils/kalman_filter.md",
    "content": "---\ndescription: Improve object tracking with KalmanFilterXYAH in Ultralytics YOLO - an efficient and accurate algorithm for state estimation.\n---\n\n# KalmanFilterXYAH\n---\n:::ultralytics.tracker.utils.kalman_filter.KalmanFilterXYAH\n<br><br>\n\n# KalmanFilterXYWH\n---\n:::ultralytics.tracker.utils.kalman_filter.KalmanFilterXYWH\n<br><br>\n"
  },
  {
    "path": "docs/reference/tracker/utils/matching.md",
    "content": "---\ndescription: Learn how to match and fuse object detections for accurate target tracking using Ultralytics' YOLO merge_matches, iou_distance, and embedding_distance.\n---\n\n# merge_matches\n---\n:::ultralytics.tracker.utils.matching.merge_matches\n<br><br>\n\n# _indices_to_matches\n---\n:::ultralytics.tracker.utils.matching._indices_to_matches\n<br><br>\n\n# linear_assignment\n---\n:::ultralytics.tracker.utils.matching.linear_assignment\n<br><br>\n\n# ious\n---\n:::ultralytics.tracker.utils.matching.ious\n<br><br>\n\n# iou_distance\n---\n:::ultralytics.tracker.utils.matching.iou_distance\n<br><br>\n\n# v_iou_distance\n---\n:::ultralytics.tracker.utils.matching.v_iou_distance\n<br><br>\n\n# embedding_distance\n---\n:::ultralytics.tracker.utils.matching.embedding_distance\n<br><br>\n\n# gate_cost_matrix\n---\n:::ultralytics.tracker.utils.matching.gate_cost_matrix\n<br><br>\n\n# fuse_motion\n---\n:::ultralytics.tracker.utils.matching.fuse_motion\n<br><br>\n\n# fuse_iou\n---\n:::ultralytics.tracker.utils.matching.fuse_iou\n<br><br>\n\n# fuse_score\n---\n:::ultralytics.tracker.utils.matching.fuse_score\n<br><br>\n\n# bbox_ious\n---\n:::ultralytics.tracker.utils.matching.bbox_ious\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/data/annotator.md",
    "content": "---\ndescription: Learn how to use auto_annotate in Ultralytics YOLO to generate annotations automatically for your dataset. Simplify object detection workflows.\n---\n\n# auto_annotate\n---\n:::ultralytics.yolo.data.annotator.auto_annotate\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/data/augment.md",
    "content": "---\ndescription: Use Ultralytics YOLO Data Augmentation transforms with Base, MixUp, and Albumentations for object detection and classification.\n---\n\n# BaseTransform\n---\n:::ultralytics.yolo.data.augment.BaseTransform\n<br><br>\n\n# Compose\n---\n:::ultralytics.yolo.data.augment.Compose\n<br><br>\n\n# BaseMixTransform\n---\n:::ultralytics.yolo.data.augment.BaseMixTransform\n<br><br>\n\n# Mosaic\n---\n:::ultralytics.yolo.data.augment.Mosaic\n<br><br>\n\n# MixUp\n---\n:::ultralytics.yolo.data.augment.MixUp\n<br><br>\n\n# RandomPerspective\n---\n:::ultralytics.yolo.data.augment.RandomPerspective\n<br><br>\n\n# RandomHSV\n---\n:::ultralytics.yolo.data.augment.RandomHSV\n<br><br>\n\n# RandomFlip\n---\n:::ultralytics.yolo.data.augment.RandomFlip\n<br><br>\n\n# LetterBox\n---\n:::ultralytics.yolo.data.augment.LetterBox\n<br><br>\n\n# CopyPaste\n---\n:::ultralytics.yolo.data.augment.CopyPaste\n<br><br>\n\n# Albumentations\n---\n:::ultralytics.yolo.data.augment.Albumentations\n<br><br>\n\n# Format\n---\n:::ultralytics.yolo.data.augment.Format\n<br><br>\n\n# ClassifyLetterBox\n---\n:::ultralytics.yolo.data.augment.ClassifyLetterBox\n<br><br>\n\n# CenterCrop\n---\n:::ultralytics.yolo.data.augment.CenterCrop\n<br><br>\n\n# ToTensor\n---\n:::ultralytics.yolo.data.augment.ToTensor\n<br><br>\n\n# v8_transforms\n---\n:::ultralytics.yolo.data.augment.v8_transforms\n<br><br>\n\n# classify_transforms\n---\n:::ultralytics.yolo.data.augment.classify_transforms\n<br><br>\n\n# classify_albumentations\n---\n:::ultralytics.yolo.data.augment.classify_albumentations\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/data/base.md",
    "content": "---\ndescription: Learn about BaseDataset in Ultralytics YOLO, a flexible dataset class for object detection. Maximize your YOLO performance with custom datasets.\n---\n\n# BaseDataset\n---\n:::ultralytics.yolo.data.base.BaseDataset\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/data/build.md",
    "content": "---\ndescription: Maximize YOLO performance with Ultralytics' InfiniteDataLoader, seed_worker, build_dataloader, and load_inference_source functions.\n---\n\n# InfiniteDataLoader\n---\n:::ultralytics.yolo.data.build.InfiniteDataLoader\n<br><br>\n\n# _RepeatSampler\n---\n:::ultralytics.yolo.data.build._RepeatSampler\n<br><br>\n\n# seed_worker\n---\n:::ultralytics.yolo.data.build.seed_worker\n<br><br>\n\n# build_yolo_dataset\n---\n:::ultralytics.yolo.data.build.build_yolo_dataset\n<br><br>\n\n# build_dataloader\n---\n:::ultralytics.yolo.data.build.build_dataloader\n<br><br>\n\n# check_source\n---\n:::ultralytics.yolo.data.build.check_source\n<br><br>\n\n# load_inference_source\n---\n:::ultralytics.yolo.data.build.load_inference_source\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/data/converter.md",
    "content": "---\ndescription: Convert COCO-91 to COCO-80 class, RLE to polygon, and merge multi-segment images with Ultralytics YOLO data converter. Improve your object detection.\n---\n\n# coco91_to_coco80_class\n---\n:::ultralytics.yolo.data.converter.coco91_to_coco80_class\n<br><br>\n\n# convert_coco\n---\n:::ultralytics.yolo.data.converter.convert_coco\n<br><br>\n\n# rle2polygon\n---\n:::ultralytics.yolo.data.converter.rle2polygon\n<br><br>\n\n# min_index\n---\n:::ultralytics.yolo.data.converter.min_index\n<br><br>\n\n# merge_multi_segment\n---\n:::ultralytics.yolo.data.converter.merge_multi_segment\n<br><br>\n\n# delete_dsstore\n---\n:::ultralytics.yolo.data.converter.delete_dsstore\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/data/dataloaders/stream_loaders.md",
    "content": "---\ndescription: 'Ultralytics YOLO Docs: Learn about stream loaders for image and tensor data, as well as autocasting techniques. Check out SourceTypes and more.'\n---\n\n# SourceTypes\n---\n:::ultralytics.yolo.data.dataloaders.stream_loaders.SourceTypes\n<br><br>\n\n# LoadStreams\n---\n:::ultralytics.yolo.data.dataloaders.stream_loaders.LoadStreams\n<br><br>\n\n# LoadScreenshots\n---\n:::ultralytics.yolo.data.dataloaders.stream_loaders.LoadScreenshots\n<br><br>\n\n# LoadImages\n---\n:::ultralytics.yolo.data.dataloaders.stream_loaders.LoadImages\n<br><br>\n\n# LoadPilAndNumpy\n---\n:::ultralytics.yolo.data.dataloaders.stream_loaders.LoadPilAndNumpy\n<br><br>\n\n# LoadTensor\n---\n:::ultralytics.yolo.data.dataloaders.stream_loaders.LoadTensor\n<br><br>\n\n# autocast_list\n---\n:::ultralytics.yolo.data.dataloaders.stream_loaders.autocast_list\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/data/dataloaders/v5augmentations.md",
    "content": "---\ndescription: Enhance image data with Albumentations CenterCrop, normalize, augment_hsv, replicate, random_perspective, cutout, & box_candidates.\n---\n\n# Albumentations\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.Albumentations\n<br><br>\n\n# LetterBox\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.LetterBox\n<br><br>\n\n# CenterCrop\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.CenterCrop\n<br><br>\n\n# ToTensor\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.ToTensor\n<br><br>\n\n# normalize\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.normalize\n<br><br>\n\n# denormalize\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.denormalize\n<br><br>\n\n# augment_hsv\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.augment_hsv\n<br><br>\n\n# hist_equalize\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.hist_equalize\n<br><br>\n\n# replicate\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.replicate\n<br><br>\n\n# letterbox\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.letterbox\n<br><br>\n\n# random_perspective\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.random_perspective\n<br><br>\n\n# copy_paste\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.copy_paste\n<br><br>\n\n# cutout\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.cutout\n<br><br>\n\n# mixup\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.mixup\n<br><br>\n\n# box_candidates\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.box_candidates\n<br><br>\n\n# classify_albumentations\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.classify_albumentations\n<br><br>\n\n# classify_transforms\n---\n:::ultralytics.yolo.data.dataloaders.v5augmentations.classify_transforms\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/data/dataloaders/v5loader.md",
    "content": "---\ndescription: Efficiently load images and labels to models using Ultralytics YOLO's InfiniteDataLoader, LoadScreenshots, and LoadStreams.\n---\n\n# InfiniteDataLoader\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.InfiniteDataLoader\n<br><br>\n\n# _RepeatSampler\n---\n:::ultralytics.yolo.data.dataloaders.v5loader._RepeatSampler\n<br><br>\n\n# LoadScreenshots\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.LoadScreenshots\n<br><br>\n\n# LoadImages\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.LoadImages\n<br><br>\n\n# LoadStreams\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.LoadStreams\n<br><br>\n\n# LoadImagesAndLabels\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.LoadImagesAndLabels\n<br><br>\n\n# ClassificationDataset\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.ClassificationDataset\n<br><br>\n\n# get_hash\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.get_hash\n<br><br>\n\n# exif_size\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.exif_size\n<br><br>\n\n# exif_transpose\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.exif_transpose\n<br><br>\n\n# seed_worker\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.seed_worker\n<br><br>\n\n# create_dataloader\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.create_dataloader\n<br><br>\n\n# img2label_paths\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.img2label_paths\n<br><br>\n\n# flatten_recursive\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.flatten_recursive\n<br><br>\n\n# extract_boxes\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.extract_boxes\n<br><br>\n\n# autosplit\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.autosplit\n<br><br>\n\n# verify_image_label\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.verify_image_label\n<br><br>\n\n# create_classification_dataloader\n---\n:::ultralytics.yolo.data.dataloaders.v5loader.create_classification_dataloader\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/data/dataset.md",
    "content": "---\ndescription: Create custom YOLOv5 datasets with Ultralytics YOLODataset and SemanticDataset. Streamline your object detection and segmentation projects.\n---\n\n# YOLODataset\n---\n:::ultralytics.yolo.data.dataset.YOLODataset\n<br><br>\n\n# ClassificationDataset\n---\n:::ultralytics.yolo.data.dataset.ClassificationDataset\n<br><br>\n\n# SemanticDataset\n---\n:::ultralytics.yolo.data.dataset.SemanticDataset\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/data/dataset_wrappers.md",
    "content": "---\ndescription: Create a custom dataset of mixed and oriented rectangular objects with Ultralytics YOLO's MixAndRectDataset.\n---\n\n# MixAndRectDataset\n---\n:::ultralytics.yolo.data.dataset_wrappers.MixAndRectDataset\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/data/utils.md",
    "content": "---\ndescription: Efficiently handle data in YOLO with Ultralytics. Utilize HUBDatasetStats and customize dataset with these data utility functions.\n---\n\n# HUBDatasetStats\n---\n:::ultralytics.yolo.data.utils.HUBDatasetStats\n<br><br>\n\n# img2label_paths\n---\n:::ultralytics.yolo.data.utils.img2label_paths\n<br><br>\n\n# get_hash\n---\n:::ultralytics.yolo.data.utils.get_hash\n<br><br>\n\n# exif_size\n---\n:::ultralytics.yolo.data.utils.exif_size\n<br><br>\n\n# verify_image_label\n---\n:::ultralytics.yolo.data.utils.verify_image_label\n<br><br>\n\n# polygon2mask\n---\n:::ultralytics.yolo.data.utils.polygon2mask\n<br><br>\n\n# polygons2masks\n---\n:::ultralytics.yolo.data.utils.polygons2masks\n<br><br>\n\n# polygons2masks_overlap\n---\n:::ultralytics.yolo.data.utils.polygons2masks_overlap\n<br><br>\n\n# check_det_dataset\n---\n:::ultralytics.yolo.data.utils.check_det_dataset\n<br><br>\n\n# check_cls_dataset\n---\n:::ultralytics.yolo.data.utils.check_cls_dataset\n<br><br>\n\n# compress_one_image\n---\n:::ultralytics.yolo.data.utils.compress_one_image\n<br><br>\n\n# delete_dsstore\n---\n:::ultralytics.yolo.data.utils.delete_dsstore\n<br><br>\n\n# zip_directory\n---\n:::ultralytics.yolo.data.utils.zip_directory\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/engine/exporter.md",
    "content": "---\ndescription: Learn how to export your YOLO model in various formats using Ultralytics' exporter package - iOS, GDC, and more.\n---\n\n# Exporter\n---\n:::ultralytics.yolo.engine.exporter.Exporter\n<br><br>\n\n# iOSDetectModel\n---\n:::ultralytics.yolo.engine.exporter.iOSDetectModel\n<br><br>\n\n# export_formats\n---\n:::ultralytics.yolo.engine.exporter.export_formats\n<br><br>\n\n# gd_outputs\n---\n:::ultralytics.yolo.engine.exporter.gd_outputs\n<br><br>\n\n# try_export\n---\n:::ultralytics.yolo.engine.exporter.try_export\n<br><br>\n\n# export\n---\n:::ultralytics.yolo.engine.exporter.export\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/engine/model.md",
    "content": "---\ndescription: Discover the YOLO model of Ultralytics engine to simplify your object detection tasks with state-of-the-art models.\n---\n\n# YOLO\n---\n:::ultralytics.yolo.engine.model.YOLO\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/engine/predictor.md",
    "content": "---\ndescription: '\"The BasePredictor class in Ultralytics YOLO Engine predicts object detection in images and videos. Learn to implement YOLO with ease.\"'\n---\n\n# BasePredictor\n---\n:::ultralytics.yolo.engine.predictor.BasePredictor\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/engine/results.md",
    "content": "---\ndescription: Learn about BaseTensor & Boxes in Ultralytics YOLO Engine. Check out Ultralytics Docs for quality tutorials and resources on object detection.\n---\n\n# BaseTensor\n---\n:::ultralytics.yolo.engine.results.BaseTensor\n<br><br>\n\n# Results\n---\n:::ultralytics.yolo.engine.results.Results\n<br><br>\n\n# Boxes\n---\n:::ultralytics.yolo.engine.results.Boxes\n<br><br>\n\n# Masks\n---\n:::ultralytics.yolo.engine.results.Masks\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/engine/trainer.md",
    "content": "---\ndescription: Train faster with mixed precision. Learn how to use BaseTrainer with Advanced Mixed Precision to optimize YOLOv3 and YOLOv4 models.\n---\n\n# BaseTrainer\n---\n:::ultralytics.yolo.engine.trainer.BaseTrainer\n<br><br>\n\n# check_amp\n---\n:::ultralytics.yolo.engine.trainer.check_amp\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/engine/validator.md",
    "content": "---\ndescription: Ensure YOLOv5 models meet constraints and standards with the BaseValidator class. Learn how to use it here.\n---\n\n# BaseValidator\n---\n:::ultralytics.yolo.engine.validator.BaseValidator\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/autobatch.md",
    "content": "---\ndescription: Dynamically adjusts input size to optimize GPU memory usage during training. Learn how to use check_train_batch_size with Ultralytics YOLO.\n---\n\n# check_train_batch_size\n---\n:::ultralytics.yolo.utils.autobatch.check_train_batch_size\n<br><br>\n\n# autobatch\n---\n:::ultralytics.yolo.utils.autobatch.autobatch\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/benchmarks.md",
    "content": "---\ndescription: Improve your YOLO's performance and measure its speed. Benchmark utility for YOLOv5.\n---\n\n# benchmark\n---\n:::ultralytics.yolo.utils.benchmarks.benchmark\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/callbacks/base.md",
    "content": "---\ndescription: Learn about YOLO's callback functions from on_train_start to add_integration_callbacks. See how these callbacks modify and save models.\n---\n\n# on_pretrain_routine_start\n---\n:::ultralytics.yolo.utils.callbacks.base.on_pretrain_routine_start\n<br><br>\n\n# on_pretrain_routine_end\n---\n:::ultralytics.yolo.utils.callbacks.base.on_pretrain_routine_end\n<br><br>\n\n# on_train_start\n---\n:::ultralytics.yolo.utils.callbacks.base.on_train_start\n<br><br>\n\n# on_train_epoch_start\n---\n:::ultralytics.yolo.utils.callbacks.base.on_train_epoch_start\n<br><br>\n\n# on_train_batch_start\n---\n:::ultralytics.yolo.utils.callbacks.base.on_train_batch_start\n<br><br>\n\n# optimizer_step\n---\n:::ultralytics.yolo.utils.callbacks.base.optimizer_step\n<br><br>\n\n# on_before_zero_grad\n---\n:::ultralytics.yolo.utils.callbacks.base.on_before_zero_grad\n<br><br>\n\n# on_train_batch_end\n---\n:::ultralytics.yolo.utils.callbacks.base.on_train_batch_end\n<br><br>\n\n# on_train_epoch_end\n---\n:::ultralytics.yolo.utils.callbacks.base.on_train_epoch_end\n<br><br>\n\n# on_fit_epoch_end\n---\n:::ultralytics.yolo.utils.callbacks.base.on_fit_epoch_end\n<br><br>\n\n# on_model_save\n---\n:::ultralytics.yolo.utils.callbacks.base.on_model_save\n<br><br>\n\n# on_train_end\n---\n:::ultralytics.yolo.utils.callbacks.base.on_train_end\n<br><br>\n\n# on_params_update\n---\n:::ultralytics.yolo.utils.callbacks.base.on_params_update\n<br><br>\n\n# teardown\n---\n:::ultralytics.yolo.utils.callbacks.base.teardown\n<br><br>\n\n# on_val_start\n---\n:::ultralytics.yolo.utils.callbacks.base.on_val_start\n<br><br>\n\n# on_val_batch_start\n---\n:::ultralytics.yolo.utils.callbacks.base.on_val_batch_start\n<br><br>\n\n# on_val_batch_end\n---\n:::ultralytics.yolo.utils.callbacks.base.on_val_batch_end\n<br><br>\n\n# on_val_end\n---\n:::ultralytics.yolo.utils.callbacks.base.on_val_end\n<br><br>\n\n# on_predict_start\n---\n:::ultralytics.yolo.utils.callbacks.base.on_predict_start\n<br><br>\n\n# on_predict_batch_start\n---\n:::ultralytics.yolo.utils.callbacks.base.on_predict_batch_start\n<br><br>\n\n# on_predict_batch_end\n---\n:::ultralytics.yolo.utils.callbacks.base.on_predict_batch_end\n<br><br>\n\n# on_predict_postprocess_end\n---\n:::ultralytics.yolo.utils.callbacks.base.on_predict_postprocess_end\n<br><br>\n\n# on_predict_end\n---\n:::ultralytics.yolo.utils.callbacks.base.on_predict_end\n<br><br>\n\n# on_export_start\n---\n:::ultralytics.yolo.utils.callbacks.base.on_export_start\n<br><br>\n\n# on_export_end\n---\n:::ultralytics.yolo.utils.callbacks.base.on_export_end\n<br><br>\n\n# get_default_callbacks\n---\n:::ultralytics.yolo.utils.callbacks.base.get_default_callbacks\n<br><br>\n\n# add_integration_callbacks\n---\n:::ultralytics.yolo.utils.callbacks.base.add_integration_callbacks\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/callbacks/clearml.md",
    "content": "---\ndescription: Improve your YOLOv5 model training with callbacks from ClearML. Learn about log debug samples, pre-training routines, validation and more.\n---\n\n# _log_debug_samples\n---\n:::ultralytics.yolo.utils.callbacks.clearml._log_debug_samples\n<br><br>\n\n# _log_plot\n---\n:::ultralytics.yolo.utils.callbacks.clearml._log_plot\n<br><br>\n\n# on_pretrain_routine_start\n---\n:::ultralytics.yolo.utils.callbacks.clearml.on_pretrain_routine_start\n<br><br>\n\n# on_train_epoch_end\n---\n:::ultralytics.yolo.utils.callbacks.clearml.on_train_epoch_end\n<br><br>\n\n# on_fit_epoch_end\n---\n:::ultralytics.yolo.utils.callbacks.clearml.on_fit_epoch_end\n<br><br>\n\n# on_val_end\n---\n:::ultralytics.yolo.utils.callbacks.clearml.on_val_end\n<br><br>\n\n# on_train_end\n---\n:::ultralytics.yolo.utils.callbacks.clearml.on_train_end\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/callbacks/comet.md",
    "content": "---\ndescription: Learn about YOLO callbacks using the Comet.ml platform, enhancing object detection training and testing with custom logging and visualizations.\n---\n\n# _get_comet_mode\n---\n:::ultralytics.yolo.utils.callbacks.comet._get_comet_mode\n<br><br>\n\n# _get_comet_model_name\n---\n:::ultralytics.yolo.utils.callbacks.comet._get_comet_model_name\n<br><br>\n\n# _get_eval_batch_logging_interval\n---\n:::ultralytics.yolo.utils.callbacks.comet._get_eval_batch_logging_interval\n<br><br>\n\n# _get_max_image_predictions_to_log\n---\n:::ultralytics.yolo.utils.callbacks.comet._get_max_image_predictions_to_log\n<br><br>\n\n# _scale_confidence_score\n---\n:::ultralytics.yolo.utils.callbacks.comet._scale_confidence_score\n<br><br>\n\n# _should_log_confusion_matrix\n---\n:::ultralytics.yolo.utils.callbacks.comet._should_log_confusion_matrix\n<br><br>\n\n# _should_log_image_predictions\n---\n:::ultralytics.yolo.utils.callbacks.comet._should_log_image_predictions\n<br><br>\n\n# _get_experiment_type\n---\n:::ultralytics.yolo.utils.callbacks.comet._get_experiment_type\n<br><br>\n\n# _create_experiment\n---\n:::ultralytics.yolo.utils.callbacks.comet._create_experiment\n<br><br>\n\n# _fetch_trainer_metadata\n---\n:::ultralytics.yolo.utils.callbacks.comet._fetch_trainer_metadata\n<br><br>\n\n# _scale_bounding_box_to_original_image_shape\n---\n:::ultralytics.yolo.utils.callbacks.comet._scale_bounding_box_to_original_image_shape\n<br><br>\n\n# _format_ground_truth_annotations_for_detection\n---\n:::ultralytics.yolo.utils.callbacks.comet._format_ground_truth_annotations_for_detection\n<br><br>\n\n# _format_prediction_annotations_for_detection\n---\n:::ultralytics.yolo.utils.callbacks.comet._format_prediction_annotations_for_detection\n<br><br>\n\n# _fetch_annotations\n---\n:::ultralytics.yolo.utils.callbacks.comet._fetch_annotations\n<br><br>\n\n# _create_prediction_metadata_map\n---\n:::ultralytics.yolo.utils.callbacks.comet._create_prediction_metadata_map\n<br><br>\n\n# _log_confusion_matrix\n---\n:::ultralytics.yolo.utils.callbacks.comet._log_confusion_matrix\n<br><br>\n\n# _log_images\n---\n:::ultralytics.yolo.utils.callbacks.comet._log_images\n<br><br>\n\n# _log_image_predictions\n---\n:::ultralytics.yolo.utils.callbacks.comet._log_image_predictions\n<br><br>\n\n# _log_plots\n---\n:::ultralytics.yolo.utils.callbacks.comet._log_plots\n<br><br>\n\n# _log_model\n---\n:::ultralytics.yolo.utils.callbacks.comet._log_model\n<br><br>\n\n# on_pretrain_routine_start\n---\n:::ultralytics.yolo.utils.callbacks.comet.on_pretrain_routine_start\n<br><br>\n\n# on_train_epoch_end\n---\n:::ultralytics.yolo.utils.callbacks.comet.on_train_epoch_end\n<br><br>\n\n# on_fit_epoch_end\n---\n:::ultralytics.yolo.utils.callbacks.comet.on_fit_epoch_end\n<br><br>\n\n# on_train_end\n---\n:::ultralytics.yolo.utils.callbacks.comet.on_train_end\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/callbacks/hub.md",
    "content": "---\ndescription: Improve YOLOv5 model training with Ultralytics' on-train callbacks. Boost performance on-pretrain-routine-end, model-save, train/predict start.\n---\n\n# on_pretrain_routine_end\n---\n:::ultralytics.yolo.utils.callbacks.hub.on_pretrain_routine_end\n<br><br>\n\n# on_fit_epoch_end\n---\n:::ultralytics.yolo.utils.callbacks.hub.on_fit_epoch_end\n<br><br>\n\n# on_model_save\n---\n:::ultralytics.yolo.utils.callbacks.hub.on_model_save\n<br><br>\n\n# on_train_end\n---\n:::ultralytics.yolo.utils.callbacks.hub.on_train_end\n<br><br>\n\n# on_train_start\n---\n:::ultralytics.yolo.utils.callbacks.hub.on_train_start\n<br><br>\n\n# on_val_start\n---\n:::ultralytics.yolo.utils.callbacks.hub.on_val_start\n<br><br>\n\n# on_predict_start\n---\n:::ultralytics.yolo.utils.callbacks.hub.on_predict_start\n<br><br>\n\n# on_export_start\n---\n:::ultralytics.yolo.utils.callbacks.hub.on_export_start\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/callbacks/mlflow.md",
    "content": "---\ndescription: Track model performance and metrics with MLflow in YOLOv5. Use callbacks like on_pretrain_routine_end or on_train_end to log information.\n---\n\n# on_pretrain_routine_end\n---\n:::ultralytics.yolo.utils.callbacks.mlflow.on_pretrain_routine_end\n<br><br>\n\n# on_fit_epoch_end\n---\n:::ultralytics.yolo.utils.callbacks.mlflow.on_fit_epoch_end\n<br><br>\n\n# on_train_end\n---\n:::ultralytics.yolo.utils.callbacks.mlflow.on_train_end\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/callbacks/neptune.md",
    "content": "---\ndescription: Improve YOLOv5 training with Neptune, a powerful logging tool. Track metrics like images, plots, and epochs for better model performance.\n---\n\n# _log_scalars\n---\n:::ultralytics.yolo.utils.callbacks.neptune._log_scalars\n<br><br>\n\n# _log_images\n---\n:::ultralytics.yolo.utils.callbacks.neptune._log_images\n<br><br>\n\n# _log_plot\n---\n:::ultralytics.yolo.utils.callbacks.neptune._log_plot\n<br><br>\n\n# on_pretrain_routine_start\n---\n:::ultralytics.yolo.utils.callbacks.neptune.on_pretrain_routine_start\n<br><br>\n\n# on_train_epoch_end\n---\n:::ultralytics.yolo.utils.callbacks.neptune.on_train_epoch_end\n<br><br>\n\n# on_fit_epoch_end\n---\n:::ultralytics.yolo.utils.callbacks.neptune.on_fit_epoch_end\n<br><br>\n\n# on_val_end\n---\n:::ultralytics.yolo.utils.callbacks.neptune.on_val_end\n<br><br>\n\n# on_train_end\n---\n:::ultralytics.yolo.utils.callbacks.neptune.on_train_end\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/callbacks/raytune.md",
    "content": "---\ndescription: '\"Improve YOLO model performance with on_fit_epoch_end callback. Learn to integrate with Ray Tune for hyperparameter tuning. Ultralytics YOLO docs.\"'\n---\n\n# on_fit_epoch_end\n---\n:::ultralytics.yolo.utils.callbacks.raytune.on_fit_epoch_end\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/callbacks/tensorboard.md",
    "content": "---\ndescription: Learn how to monitor the training process with Tensorboard using Ultralytics YOLO's \"_log_scalars\" and \"on_batch_end\" methods.\n---\n\n# _log_scalars\n---\n:::ultralytics.yolo.utils.callbacks.tensorboard._log_scalars\n<br><br>\n\n# on_pretrain_routine_start\n---\n:::ultralytics.yolo.utils.callbacks.tensorboard.on_pretrain_routine_start\n<br><br>\n\n# on_batch_end\n---\n:::ultralytics.yolo.utils.callbacks.tensorboard.on_batch_end\n<br><br>\n\n# on_fit_epoch_end\n---\n:::ultralytics.yolo.utils.callbacks.tensorboard.on_fit_epoch_end\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/callbacks/wb.md",
    "content": "---\ndescription: Learn how to use Ultralytics YOLO's built-in callbacks `on_pretrain_routine_start` and `on_train_epoch_end` for improved training performance.\n---\n\n# on_pretrain_routine_start\n---\n:::ultralytics.yolo.utils.callbacks.wb.on_pretrain_routine_start\n<br><br>\n\n# on_fit_epoch_end\n---\n:::ultralytics.yolo.utils.callbacks.wb.on_fit_epoch_end\n<br><br>\n\n# on_train_epoch_end\n---\n:::ultralytics.yolo.utils.callbacks.wb.on_train_epoch_end\n<br><br>\n\n# on_train_end\n---\n:::ultralytics.yolo.utils.callbacks.wb.on_train_end\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/checks.md",
    "content": "---\ndescription: 'Check functions for YOLO utils: image size, version, font, requirements, filename suffix, YAML file, YOLO, and Git version.'\n---\n\n# is_ascii\n---\n:::ultralytics.yolo.utils.checks.is_ascii\n<br><br>\n\n# check_imgsz\n---\n:::ultralytics.yolo.utils.checks.check_imgsz\n<br><br>\n\n# check_version\n---\n:::ultralytics.yolo.utils.checks.check_version\n<br><br>\n\n# check_latest_pypi_version\n---\n:::ultralytics.yolo.utils.checks.check_latest_pypi_version\n<br><br>\n\n# check_pip_update_available\n---\n:::ultralytics.yolo.utils.checks.check_pip_update_available\n<br><br>\n\n# check_font\n---\n:::ultralytics.yolo.utils.checks.check_font\n<br><br>\n\n# check_python\n---\n:::ultralytics.yolo.utils.checks.check_python\n<br><br>\n\n# check_requirements\n---\n:::ultralytics.yolo.utils.checks.check_requirements\n<br><br>\n\n# check_suffix\n---\n:::ultralytics.yolo.utils.checks.check_suffix\n<br><br>\n\n# check_yolov5u_filename\n---\n:::ultralytics.yolo.utils.checks.check_yolov5u_filename\n<br><br>\n\n# check_file\n---\n:::ultralytics.yolo.utils.checks.check_file\n<br><br>\n\n# check_yaml\n---\n:::ultralytics.yolo.utils.checks.check_yaml\n<br><br>\n\n# check_imshow\n---\n:::ultralytics.yolo.utils.checks.check_imshow\n<br><br>\n\n# check_yolo\n---\n:::ultralytics.yolo.utils.checks.check_yolo\n<br><br>\n\n# git_describe\n---\n:::ultralytics.yolo.utils.checks.git_describe\n<br><br>\n\n# print_args\n---\n:::ultralytics.yolo.utils.checks.print_args\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/dist.md",
    "content": "---\ndescription: Learn how to find free network port and generate DDP (Distributed Data Parallel) command in Ultralytics YOLO with easy examples.\n---\n\n# find_free_network_port\n---\n:::ultralytics.yolo.utils.dist.find_free_network_port\n<br><br>\n\n# generate_ddp_file\n---\n:::ultralytics.yolo.utils.dist.generate_ddp_file\n<br><br>\n\n# generate_ddp_command\n---\n:::ultralytics.yolo.utils.dist.generate_ddp_command\n<br><br>\n\n# ddp_cleanup\n---\n:::ultralytics.yolo.utils.dist.ddp_cleanup\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/downloads.md",
    "content": "---\ndescription: Download and unzip YOLO pretrained models. Ultralytics YOLO docs utils.downloads.unzip_file, checks disk space, downloads and attempts assets.\n---\n\n# is_url\n---\n:::ultralytics.yolo.utils.downloads.is_url\n<br><br>\n\n# unzip_file\n---\n:::ultralytics.yolo.utils.downloads.unzip_file\n<br><br>\n\n# check_disk_space\n---\n:::ultralytics.yolo.utils.downloads.check_disk_space\n<br><br>\n\n# safe_download\n---\n:::ultralytics.yolo.utils.downloads.safe_download\n<br><br>\n\n# attempt_download_asset\n---\n:::ultralytics.yolo.utils.downloads.attempt_download_asset\n<br><br>\n\n# download\n---\n:::ultralytics.yolo.utils.downloads.download\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/errors.md",
    "content": "---\ndescription: Learn about HUBModelError in Ultralytics YOLO Docs. Resolve the error and get the most out of your YOLO model.\n---\n\n# HUBModelError\n---\n:::ultralytics.yolo.utils.errors.HUBModelError\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/files.md",
    "content": "---\ndescription: 'Learn about Ultralytics YOLO files and directory utilities: WorkingDirectory, file_age, file_size, and make_dirs.'\n---\n\n# WorkingDirectory\n---\n:::ultralytics.yolo.utils.files.WorkingDirectory\n<br><br>\n\n# increment_path\n---\n:::ultralytics.yolo.utils.files.increment_path\n<br><br>\n\n# file_age\n---\n:::ultralytics.yolo.utils.files.file_age\n<br><br>\n\n# file_date\n---\n:::ultralytics.yolo.utils.files.file_date\n<br><br>\n\n# file_size\n---\n:::ultralytics.yolo.utils.files.file_size\n<br><br>\n\n# get_latest_run\n---\n:::ultralytics.yolo.utils.files.get_latest_run\n<br><br>\n\n# make_dirs\n---\n:::ultralytics.yolo.utils.files.make_dirs\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/instance.md",
    "content": "---\ndescription: Learn about Bounding Boxes (Bboxes) and _ntuple in Ultralytics YOLO for object detection. Improve accuracy and speed with these powerful tools.\n---\n\n# Bboxes\n---\n:::ultralytics.yolo.utils.instance.Bboxes\n<br><br>\n\n# Instances\n---\n:::ultralytics.yolo.utils.instance.Instances\n<br><br>\n\n# _ntuple\n---\n:::ultralytics.yolo.utils.instance._ntuple\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/loss.md",
    "content": "---\ndescription: Learn about Varifocal Loss and Keypoint Loss in Ultralytics YOLO for advanced bounding box and pose estimation. Visit our docs for more.\n---\n\n# VarifocalLoss\n---\n:::ultralytics.yolo.utils.loss.VarifocalLoss\n<br><br>\n\n# BboxLoss\n---\n:::ultralytics.yolo.utils.loss.BboxLoss\n<br><br>\n\n# KeypointLoss\n---\n:::ultralytics.yolo.utils.loss.KeypointLoss\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/metrics.md",
    "content": "---\ndescription: Explore Ultralytics YOLO's FocalLoss, DetMetrics, PoseMetrics, ClassifyMetrics, and more with Ultralytics Metrics documentation.\n---\n\n# FocalLoss\n---\n:::ultralytics.yolo.utils.metrics.FocalLoss\n<br><br>\n\n# ConfusionMatrix\n---\n:::ultralytics.yolo.utils.metrics.ConfusionMatrix\n<br><br>\n\n# Metric\n---\n:::ultralytics.yolo.utils.metrics.Metric\n<br><br>\n\n# DetMetrics\n---\n:::ultralytics.yolo.utils.metrics.DetMetrics\n<br><br>\n\n# SegmentMetrics\n---\n:::ultralytics.yolo.utils.metrics.SegmentMetrics\n<br><br>\n\n# PoseMetrics\n---\n:::ultralytics.yolo.utils.metrics.PoseMetrics\n<br><br>\n\n# ClassifyMetrics\n---\n:::ultralytics.yolo.utils.metrics.ClassifyMetrics\n<br><br>\n\n# box_area\n---\n:::ultralytics.yolo.utils.metrics.box_area\n<br><br>\n\n# bbox_ioa\n---\n:::ultralytics.yolo.utils.metrics.bbox_ioa\n<br><br>\n\n# box_iou\n---\n:::ultralytics.yolo.utils.metrics.box_iou\n<br><br>\n\n# bbox_iou\n---\n:::ultralytics.yolo.utils.metrics.bbox_iou\n<br><br>\n\n# mask_iou\n---\n:::ultralytics.yolo.utils.metrics.mask_iou\n<br><br>\n\n# kpt_iou\n---\n:::ultralytics.yolo.utils.metrics.kpt_iou\n<br><br>\n\n# smooth_BCE\n---\n:::ultralytics.yolo.utils.metrics.smooth_BCE\n<br><br>\n\n# smooth\n---\n:::ultralytics.yolo.utils.metrics.smooth\n<br><br>\n\n# plot_pr_curve\n---\n:::ultralytics.yolo.utils.metrics.plot_pr_curve\n<br><br>\n\n# plot_mc_curve\n---\n:::ultralytics.yolo.utils.metrics.plot_mc_curve\n<br><br>\n\n# compute_ap\n---\n:::ultralytics.yolo.utils.metrics.compute_ap\n<br><br>\n\n# ap_per_class\n---\n:::ultralytics.yolo.utils.metrics.ap_per_class\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/ops.md",
    "content": "---\ndescription: Learn about various utility functions in Ultralytics YOLO, including x, y, width, height conversions, non-max suppression, and more.\n---\n\n# Profile\n---\n:::ultralytics.yolo.utils.ops.Profile\n<br><br>\n\n# coco80_to_coco91_class\n---\n:::ultralytics.yolo.utils.ops.coco80_to_coco91_class\n<br><br>\n\n# segment2box\n---\n:::ultralytics.yolo.utils.ops.segment2box\n<br><br>\n\n# scale_boxes\n---\n:::ultralytics.yolo.utils.ops.scale_boxes\n<br><br>\n\n# make_divisible\n---\n:::ultralytics.yolo.utils.ops.make_divisible\n<br><br>\n\n# non_max_suppression\n---\n:::ultralytics.yolo.utils.ops.non_max_suppression\n<br><br>\n\n# clip_boxes\n---\n:::ultralytics.yolo.utils.ops.clip_boxes\n<br><br>\n\n# clip_coords\n---\n:::ultralytics.yolo.utils.ops.clip_coords\n<br><br>\n\n# scale_image\n---\n:::ultralytics.yolo.utils.ops.scale_image\n<br><br>\n\n# xyxy2xywh\n---\n:::ultralytics.yolo.utils.ops.xyxy2xywh\n<br><br>\n\n# xywh2xyxy\n---\n:::ultralytics.yolo.utils.ops.xywh2xyxy\n<br><br>\n\n# xywhn2xyxy\n---\n:::ultralytics.yolo.utils.ops.xywhn2xyxy\n<br><br>\n\n# xyxy2xywhn\n---\n:::ultralytics.yolo.utils.ops.xyxy2xywhn\n<br><br>\n\n# xyn2xy\n---\n:::ultralytics.yolo.utils.ops.xyn2xy\n<br><br>\n\n# xywh2ltwh\n---\n:::ultralytics.yolo.utils.ops.xywh2ltwh\n<br><br>\n\n# xyxy2ltwh\n---\n:::ultralytics.yolo.utils.ops.xyxy2ltwh\n<br><br>\n\n# ltwh2xywh\n---\n:::ultralytics.yolo.utils.ops.ltwh2xywh\n<br><br>\n\n# ltwh2xyxy\n---\n:::ultralytics.yolo.utils.ops.ltwh2xyxy\n<br><br>\n\n# segments2boxes\n---\n:::ultralytics.yolo.utils.ops.segments2boxes\n<br><br>\n\n# resample_segments\n---\n:::ultralytics.yolo.utils.ops.resample_segments\n<br><br>\n\n# crop_mask\n---\n:::ultralytics.yolo.utils.ops.crop_mask\n<br><br>\n\n# process_mask_upsample\n---\n:::ultralytics.yolo.utils.ops.process_mask_upsample\n<br><br>\n\n# process_mask\n---\n:::ultralytics.yolo.utils.ops.process_mask\n<br><br>\n\n# process_mask_native\n---\n:::ultralytics.yolo.utils.ops.process_mask_native\n<br><br>\n\n# scale_coords\n---\n:::ultralytics.yolo.utils.ops.scale_coords\n<br><br>\n\n# masks2segments\n---\n:::ultralytics.yolo.utils.ops.masks2segments\n<br><br>\n\n# clean_str\n---\n:::ultralytics.yolo.utils.ops.clean_str\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/plotting.md",
    "content": "---\ndescription: 'Discover the power of YOLO''s plotting functions: Colors, Labels and Images. Code examples to output targets and visualize features. Check it now.'\n---\n\n# Colors\n---\n:::ultralytics.yolo.utils.plotting.Colors\n<br><br>\n\n# Annotator\n---\n:::ultralytics.yolo.utils.plotting.Annotator\n<br><br>\n\n# plot_labels\n---\n:::ultralytics.yolo.utils.plotting.plot_labels\n<br><br>\n\n# save_one_box\n---\n:::ultralytics.yolo.utils.plotting.save_one_box\n<br><br>\n\n# plot_images\n---\n:::ultralytics.yolo.utils.plotting.plot_images\n<br><br>\n\n# plot_results\n---\n:::ultralytics.yolo.utils.plotting.plot_results\n<br><br>\n\n# output_to_target\n---\n:::ultralytics.yolo.utils.plotting.output_to_target\n<br><br>\n\n# feature_visualization\n---\n:::ultralytics.yolo.utils.plotting.feature_visualization\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/tal.md",
    "content": "---\ndescription: Improve your YOLO models with Ultralytics' TaskAlignedAssigner, select_highest_overlaps, and dist2bbox utilities. Streamline your workflow today.\n---\n\n# TaskAlignedAssigner\n---\n:::ultralytics.yolo.utils.tal.TaskAlignedAssigner\n<br><br>\n\n# select_candidates_in_gts\n---\n:::ultralytics.yolo.utils.tal.select_candidates_in_gts\n<br><br>\n\n# select_highest_overlaps\n---\n:::ultralytics.yolo.utils.tal.select_highest_overlaps\n<br><br>\n\n# make_anchors\n---\n:::ultralytics.yolo.utils.tal.make_anchors\n<br><br>\n\n# dist2bbox\n---\n:::ultralytics.yolo.utils.tal.dist2bbox\n<br><br>\n\n# bbox2dist\n---\n:::ultralytics.yolo.utils.tal.bbox2dist\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/utils/torch_utils.md",
    "content": "---\ndescription: Optimize your PyTorch models with Ultralytics YOLO's torch_utils functions such as ModelEMA, select_device, and is_parallel.\n---\n\n# ModelEMA\n---\n:::ultralytics.yolo.utils.torch_utils.ModelEMA\n<br><br>\n\n# EarlyStopping\n---\n:::ultralytics.yolo.utils.torch_utils.EarlyStopping\n<br><br>\n\n# torch_distributed_zero_first\n---\n:::ultralytics.yolo.utils.torch_utils.torch_distributed_zero_first\n<br><br>\n\n# smart_inference_mode\n---\n:::ultralytics.yolo.utils.torch_utils.smart_inference_mode\n<br><br>\n\n# select_device\n---\n:::ultralytics.yolo.utils.torch_utils.select_device\n<br><br>\n\n# time_sync\n---\n:::ultralytics.yolo.utils.torch_utils.time_sync\n<br><br>\n\n# fuse_conv_and_bn\n---\n:::ultralytics.yolo.utils.torch_utils.fuse_conv_and_bn\n<br><br>\n\n# fuse_deconv_and_bn\n---\n:::ultralytics.yolo.utils.torch_utils.fuse_deconv_and_bn\n<br><br>\n\n# model_info\n---\n:::ultralytics.yolo.utils.torch_utils.model_info\n<br><br>\n\n# get_num_params\n---\n:::ultralytics.yolo.utils.torch_utils.get_num_params\n<br><br>\n\n# get_num_gradients\n---\n:::ultralytics.yolo.utils.torch_utils.get_num_gradients\n<br><br>\n\n# get_flops\n---\n:::ultralytics.yolo.utils.torch_utils.get_flops\n<br><br>\n\n# initialize_weights\n---\n:::ultralytics.yolo.utils.torch_utils.initialize_weights\n<br><br>\n\n# scale_img\n---\n:::ultralytics.yolo.utils.torch_utils.scale_img\n<br><br>\n\n# make_divisible\n---\n:::ultralytics.yolo.utils.torch_utils.make_divisible\n<br><br>\n\n# copy_attr\n---\n:::ultralytics.yolo.utils.torch_utils.copy_attr\n<br><br>\n\n# get_latest_opset\n---\n:::ultralytics.yolo.utils.torch_utils.get_latest_opset\n<br><br>\n\n# intersect_dicts\n---\n:::ultralytics.yolo.utils.torch_utils.intersect_dicts\n<br><br>\n\n# is_parallel\n---\n:::ultralytics.yolo.utils.torch_utils.is_parallel\n<br><br>\n\n# de_parallel\n---\n:::ultralytics.yolo.utils.torch_utils.de_parallel\n<br><br>\n\n# one_cycle\n---\n:::ultralytics.yolo.utils.torch_utils.one_cycle\n<br><br>\n\n# init_seeds\n---\n:::ultralytics.yolo.utils.torch_utils.init_seeds\n<br><br>\n\n# strip_optimizer\n---\n:::ultralytics.yolo.utils.torch_utils.strip_optimizer\n<br><br>\n\n# profile\n---\n:::ultralytics.yolo.utils.torch_utils.profile\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/v8/classify/predict.md",
    "content": "---\ndescription: Learn how to use ClassificationPredictor in Ultralytics YOLOv8 for object classification tasks in a simple and efficient way.\n---\n\n# ClassificationPredictor\n---\n:::ultralytics.yolo.v8.classify.predict.ClassificationPredictor\n<br><br>\n\n# predict\n---\n:::ultralytics.yolo.v8.classify.predict.predict\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/v8/classify/train.md",
    "content": "---\ndescription: Train a custom image classification model using Ultralytics YOLOv8 with ClassificationTrainer. Boost accuracy and efficiency today.\n---\n\n# ClassificationTrainer\n---\n:::ultralytics.yolo.v8.classify.train.ClassificationTrainer\n<br><br>\n\n# train\n---\n:::ultralytics.yolo.v8.classify.train.train\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/v8/classify/val.md",
    "content": "---\ndescription: Ensure model classification accuracy with Ultralytics YOLO's ClassificationValidator. Validate and improve your model with ease.\n---\n\n# ClassificationValidator\n---\n:::ultralytics.yolo.v8.classify.val.ClassificationValidator\n<br><br>\n\n# val\n---\n:::ultralytics.yolo.v8.classify.val.val\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/v8/detect/predict.md",
    "content": "---\ndescription: Detect and predict objects in images and videos using the Ultralytics YOLO v8 model with DetectionPredictor.\n---\n\n# DetectionPredictor\n---\n:::ultralytics.yolo.v8.detect.predict.DetectionPredictor\n<br><br>\n\n# predict\n---\n:::ultralytics.yolo.v8.detect.predict.predict\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/v8/detect/train.md",
    "content": "---\ndescription: Train and optimize custom object detection models with Ultralytics DetectionTrainer and train functions. Get started with YOLO v8 today.\n---\n\n# DetectionTrainer\n---\n:::ultralytics.yolo.v8.detect.train.DetectionTrainer\n<br><br>\n\n# Loss\n---\n:::ultralytics.yolo.v8.detect.train.Loss\n<br><br>\n\n# train\n---\n:::ultralytics.yolo.v8.detect.train.train\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/v8/detect/val.md",
    "content": "---\ndescription: Validate YOLOv5 detections using this PyTorch module. Ensure model accuracy with NMS IOU threshold tuning and label mapping.\n---\n\n# DetectionValidator\n---\n:::ultralytics.yolo.v8.detect.val.DetectionValidator\n<br><br>\n\n# val\n---\n:::ultralytics.yolo.v8.detect.val.val\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/v8/pose/predict.md",
    "content": "---\ndescription: Predict human pose coordinates and confidence scores using YOLOv5. Use on real-time video streams or static images.\n---\n\n# PosePredictor\n---\n:::ultralytics.yolo.v8.pose.predict.PosePredictor\n<br><br>\n\n# predict\n---\n:::ultralytics.yolo.v8.pose.predict.predict\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/v8/pose/train.md",
    "content": "---\ndescription: Boost posture detection using PoseTrainer and train models using train() API. Learn PoseLoss for ultra-fast and accurate pose detection with Ultralytics YOLO.\n---\n\n# PoseTrainer\n---\n:::ultralytics.yolo.v8.pose.train.PoseTrainer\n<br><br>\n\n# PoseLoss\n---\n:::ultralytics.yolo.v8.pose.train.PoseLoss\n<br><br>\n\n# train\n---\n:::ultralytics.yolo.v8.pose.train.train\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/v8/pose/val.md",
    "content": "---\ndescription: Ensure proper human poses in images with YOLOv8 Pose Validation, part of the Ultralytics YOLO v8 suite.\n---\n\n# PoseValidator\n---\n:::ultralytics.yolo.v8.pose.val.PoseValidator\n<br><br>\n\n# val\n---\n:::ultralytics.yolo.v8.pose.val.val\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/v8/segment/predict.md",
    "content": "---\ndescription: '\"Use SegmentationPredictor in YOLOv8 for efficient object detection and segmentation. Explore Ultralytics YOLO Docs for more information.\"'\n---\n\n# SegmentationPredictor\n---\n:::ultralytics.yolo.v8.segment.predict.SegmentationPredictor\n<br><br>\n\n# predict\n---\n:::ultralytics.yolo.v8.segment.predict.predict\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/v8/segment/train.md",
    "content": "---\ndescription: Learn about SegmentationTrainer and Train in Ultralytics YOLO v8 for efficient object detection models. Improve your training with Ultralytics Docs.\n---\n\n# SegmentationTrainer\n---\n:::ultralytics.yolo.v8.segment.train.SegmentationTrainer\n<br><br>\n\n# SegLoss\n---\n:::ultralytics.yolo.v8.segment.train.SegLoss\n<br><br>\n\n# train\n---\n:::ultralytics.yolo.v8.segment.train.train\n<br><br>\n"
  },
  {
    "path": "docs/reference/yolo/v8/segment/val.md",
    "content": "---\ndescription: Ensure segmentation quality on large datasets with SegmentationValidator. Review and visualize results with ease. Learn more at Ultralytics Docs.\n---\n\n# SegmentationValidator\n---\n:::ultralytics.yolo.v8.segment.val.SegmentationValidator\n<br><br>\n\n# val\n---\n:::ultralytics.yolo.v8.segment.val.val\n<br><br>\n"
  },
  {
    "path": "docs/robots.txt",
    "content": "User-agent: *\n"
  },
  {
    "path": "docs/stylesheets/style.css",
    "content": "/* Table format like GitHub ----------------------------------------------------------------------------------------- */\nth, td {\n    border: 1px solid var(--md-typeset-table-color);\n    border-spacing: 0;\n    border-bottom: none;\n    border-left: none;\n    border-top: none;\n}\n\n.md-typeset__table {\n    line-height: 1;\n}\n\n.md-typeset__table table:not([class]) {\n    font-size: .74rem;\n    border-right: none;\n}\n\n.md-typeset__table table:not([class]) td,\n.md-typeset__table table:not([class]) th {\n    padding: 9px;\n}\n\n/* light mode alternating table bg colors */\n.md-typeset__table tr:nth-child(2n) {\n    background-color: #f8f8f8;\n}\n\n/* dark mode alternating table bg colors */\n[data-md-color-scheme=\"slate\"] .md-typeset__table tr:nth-child(2n) {\n    background-color: hsla(var(--md-hue),25%,25%,1)\n}\n/* Table format like GitHub ----------------------------------------------------------------------------------------- */\n\n/* Code block vertical scroll */\n.md-typeset pre > code {\n    max-height: 20rem;\n}"
  },
  {
    "path": "docs/tasks/classify.md",
    "content": "---\ncomments: true\ndescription: Check YOLO class label with only one class for the whole image, using image classification. Get strategies for training and validation models.\n---\n\nImage classification is the simplest of the three tasks and involves classifying an entire image into one of a set of\npredefined classes.\n\n<img width=\"1024\" src=\"https://user-images.githubusercontent.com/26833433/212094133-6bb8c21c-3d47-41df-a512-81c5931054ae.png\">\n\nThe output of an image classifier is a single class label and a confidence score. Image\nclassification is useful when you need to know only what class an image belongs to and don't need to know where objects\nof that class are located or what their exact shape is.\n\n!!! tip \"Tip\"\n\n    YOLOv8 Classify models use the `-cls` suffix, i.e. `yolov8n-cls.pt` and are pretrained on [ImageNet](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/ImageNet.yaml).\n\n## [Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models/v8)\n\nYOLOv8 pretrained Classify models are shown here. Detect, Segment and Pose models are pretrained on\nthe [COCO](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco.yaml) dataset, while Classify\nmodels are pretrained on\nthe [ImageNet](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/ImageNet.yaml) dataset.\n\n[Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models) download automatically from the latest\nUltralytics [release](https://github.com/ultralytics/assets/releases) on first use.\n\n| Model                                                                                        | size<br><sup>(pixels) | acc<br><sup>top1 | acc<br><sup>top5 | Speed<br><sup>CPU ONNX<br>(ms) | Speed<br><sup>A100 TensorRT<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>(B) at 640 |\n|----------------------------------------------------------------------------------------------|-----------------------|------------------|------------------|--------------------------------|-------------------------------------|--------------------|--------------------------|\n| [YOLOv8n-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n-cls.pt) | 224                   | 66.6             | 87.0             | 12.9                           | 0.31                                | 2.7                | 4.3                      |\n| [YOLOv8s-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s-cls.pt) | 224                   | 72.3             | 91.1             | 23.4                           | 0.35                                | 6.4                | 13.5                     |\n| [YOLOv8m-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m-cls.pt) | 224                   | 76.4             | 93.2             | 85.4                           | 0.62                                | 17.0               | 42.7                     |\n| [YOLOv8l-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l-cls.pt) | 224                   | 78.0             | 94.1             | 163.0                          | 0.87                                | 37.5               | 99.7                     |\n| [YOLOv8x-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-cls.pt) | 224                   | 78.4             | 94.3             | 232.0                          | 1.01                                | 57.4               | 154.8                    |\n\n- **acc** values are model accuracies on the [ImageNet](https://www.image-net.org/) dataset validation set.\n  <br>Reproduce by `yolo val classify data=path/to/ImageNet device=0`\n- **Speed** averaged over ImageNet val images using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/)\n  instance.\n  <br>Reproduce by `yolo val classify data=path/to/ImageNet batch=1 device=0|cpu`\n\n## Train\n\nTrain YOLOv8n-cls on the MNIST160 dataset for 100 epochs at image size 64. For a full list of available arguments\nsee the [Configuration](../usage/cfg.md) page.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-cls.yaml')  # build a new model from YAML\n        model = YOLO('yolov8n-cls.pt')  # load a pretrained model (recommended for training)\n        model = YOLO('yolov8n-cls.yaml').load('yolov8n-cls.pt')  # build from YAML and transfer weights\n        \n        # Train the model\n        model.train(data='mnist160', epochs=100, imgsz=64)\n        ```\n\n    === \"CLI\"\n\n        ```bash\n        # Build a new model from YAML and start training from scratch\n        yolo classify train data=mnist160 model=yolov8n-cls.yaml epochs=100 imgsz=64\n\n        # Start training from a pretrained *.pt model\n        yolo classify train data=mnist160 model=yolov8n-cls.pt epochs=100 imgsz=64\n\n        # Build a new model from YAML, transfer pretrained weights to it and start training\n        yolo classify train data=mnist160 model=yolov8n-cls.yaml pretrained=yolov8n-cls.pt epochs=100 imgsz=64\n        ```\n\n### Dataset format\n\nThe YOLO classification dataset format is same as the torchvision format. Each class of images has its own folder and you have to simply pass the path of the dataset folder, i.e, `yolo classify train data=\"path/to/dataset\"`\n\n```\ndataset/\n├── train/\n├──── class1/\n├──── class2/\n├──── class3/\n├──── ...\n├── val/\n├──── class1/\n├──── class2/\n├──── class3/\n├──── ...\n```\n\n## Val\n\nValidate trained YOLOv8n-cls model accuracy on the MNIST160 dataset. No argument need to passed as the `model` retains\nit's training `data` and arguments as model attributes.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-cls.pt')  # load an official model\n        model = YOLO('path/to/best.pt')  # load a custom model\n        \n        # Validate the model\n        metrics = model.val()  # no arguments needed, dataset and settings remembered\n        metrics.top1   # top1 accuracy\n        metrics.top5   # top5 accuracy\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo classify val model=yolov8n-cls.pt  # val official model\n        yolo classify val model=path/to/best.pt  # val custom model\n        ```\n\n## Predict\n\nUse a trained YOLOv8n-cls model to run predictions on images.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-cls.pt')  # load an official model\n        model = YOLO('path/to/best.pt')  # load a custom model\n        \n        # Predict with the model\n        results = model('https://ultralytics.com/images/bus.jpg')  # predict on an image\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo classify predict model=yolov8n-cls.pt source='https://ultralytics.com/images/bus.jpg'  # predict with official model\n        yolo classify predict model=path/to/best.pt source='https://ultralytics.com/images/bus.jpg'  # predict with custom model\n        ```\n\nSee full `predict` mode details in the [Predict](https://docs.ultralytics.com/modes/predict/) page.\n\n## Export\n\nExport a YOLOv8n-cls model to a different format like ONNX, CoreML, etc.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-cls.pt')  # load an official model\n        model = YOLO('path/to/best.pt')  # load a custom trained\n        \n        # Export the model\n        model.export(format='onnx')\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo export model=yolov8n-cls.pt format=onnx  # export official model\n        yolo export model=path/to/best.pt format=onnx  # export custom trained model\n        ```\n\nAvailable YOLOv8-cls export formats are in the table below. You can predict or validate directly on exported models,\ni.e. `yolo predict model=yolov8n-cls.onnx`. Usage examples are shown for your model after export completes.\n\n| Format                                                             | `format` Argument | Model                         | Metadata | Arguments                                           |\n|--------------------------------------------------------------------|-------------------|-------------------------------|----------|-----------------------------------------------------|\n| [PyTorch](https://pytorch.org/)                                    | -                 | `yolov8n-cls.pt`              | ✅        | -                                                   |\n| [TorchScript](https://pytorch.org/docs/stable/jit.html)            | `torchscript`     | `yolov8n-cls.torchscript`     | ✅        | `imgsz`, `optimize`                                 |\n| [ONNX](https://onnx.ai/)                                           | `onnx`            | `yolov8n-cls.onnx`            | ✅        | `imgsz`, `half`, `dynamic`, `simplify`, `opset`     |\n| [OpenVINO](https://docs.openvino.ai/latest/index.html)             | `openvino`        | `yolov8n-cls_openvino_model/` | ✅        | `imgsz`, `half`                                     |\n| [TensorRT](https://developer.nvidia.com/tensorrt)                  | `engine`          | `yolov8n-cls.engine`          | ✅        | `imgsz`, `half`, `dynamic`, `simplify`, `workspace` |\n| [CoreML](https://github.com/apple/coremltools)                     | `coreml`          | `yolov8n-cls.mlmodel`         | ✅        | `imgsz`, `half`, `int8`, `nms`                      |\n| [TF SavedModel](https://www.tensorflow.org/guide/saved_model)      | `saved_model`     | `yolov8n-cls_saved_model/`    | ✅        | `imgsz`, `keras`                                    |\n| [TF GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb`              | `yolov8n-cls.pb`              | ❌        | `imgsz`                                             |\n| [TF Lite](https://www.tensorflow.org/lite)                         | `tflite`          | `yolov8n-cls.tflite`          | ✅        | `imgsz`, `half`, `int8`                             |\n| [TF Edge TPU](https://coral.ai/docs/edgetpu/models-intro/)         | `edgetpu`         | `yolov8n-cls_edgetpu.tflite`  | ✅        | `imgsz`                                             |\n| [TF.js](https://www.tensorflow.org/js)                             | `tfjs`            | `yolov8n-cls_web_model/`      | ✅        | `imgsz`                                             |\n| [PaddlePaddle](https://github.com/PaddlePaddle)                    | `paddle`          | `yolov8n-cls_paddle_model/`   | ✅        | `imgsz`                                             |\n\nSee full `export` details in the [Export](https://docs.ultralytics.com/modes/export/) page."
  },
  {
    "path": "docs/tasks/detect.md",
    "content": "---\ncomments: true\ndescription: Learn how to use YOLOv8, an object detection model pre-trained with COCO and about the different YOLOv8 models and how to train and export them.\n---\n\nObject detection is a task that involves identifying the location and class of objects in an image or video stream.\n\n<img width=\"1024\" src=\"https://user-images.githubusercontent.com/26833433/212094133-6bb8c21c-3d47-41df-a512-81c5931054ae.png\">\n\nThe output of an object detector is a set of bounding boxes that enclose the objects in the image, along with class labels and confidence scores for each box. Object detection is a good choice when you need to identify objects of interest in a scene, but don't need to know exactly where the object is or its exact shape.\n\n!!! tip \"Tip\"\n\n    YOLOv8 Detect models are the default YOLOv8 models, i.e. `yolov8n.pt` and are pretrained on [COCO](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco.yaml).\n\n## [Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models/v8)\n\nYOLOv8 pretrained Detect models are shown here. Detect, Segment and Pose models are pretrained on the [COCO](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco.yaml) dataset, while Classify models are pretrained on the [ImageNet](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/ImageNet.yaml) dataset.\n\n[Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models) download automatically from the latest Ultralytics [release](https://github.com/ultralytics/assets/releases) on first use.\n\n| Model                                                                                | size<br><sup>(pixels) | mAP<sup>val<br>50-95 | Speed<br><sup>CPU ONNX<br>(ms) | Speed<br><sup>A100 TensorRT<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>(B) |\n|--------------------------------------------------------------------------------------|-----------------------|----------------------|--------------------------------|-------------------------------------|--------------------|-------------------|\n| [YOLOv8n](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt) | 640                   | 37.3                 | 80.4                           | 0.99                                | 3.2                | 8.7               |\n| [YOLOv8s](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s.pt) | 640                   | 44.9                 | 128.4                          | 1.20                                | 11.2               | 28.6              |\n| [YOLOv8m](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m.pt) | 640                   | 50.2                 | 234.7                          | 1.83                                | 25.9               | 78.9              |\n| [YOLOv8l](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l.pt) | 640                   | 52.9                 | 375.2                          | 2.39                                | 43.7               | 165.2             |\n| [YOLOv8x](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x.pt) | 640                   | 53.9                 | 479.1                          | 3.53                                | 68.2               | 257.8             |\n\n- **mAP<sup>val</sup>** values are for single-model single-scale on [COCO val2017](http://cocodataset.org) dataset.\n  <br>Reproduce by `yolo val detect data=coco.yaml device=0`\n- **Speed** averaged over COCO val images using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/)\n  instance.\n  <br>Reproduce by `yolo val detect data=coco128.yaml batch=1 device=0|cpu`\n\n## Train\n\nTrain YOLOv8n on the COCO128 dataset for 100 epochs at image size 640. For a full list of available arguments see the [Configuration](../usage/cfg.md) page.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.yaml')  # build a new model from YAML\n        model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n        model = YOLO('yolov8n.yaml').load('yolov8n.pt')  # build from YAML and transfer weights\n        \n        # Train the model\n        model.train(data='coco128.yaml', epochs=100, imgsz=640)\n        ```\n    === \"CLI\"\n    \n        ```bash\n        # Build a new model from YAML and start training from scratch\n        yolo detect train data=coco128.yaml model=yolov8n.yaml epochs=100 imgsz=640\n\n        # Start training from a pretrained *.pt model\n        yolo detect train data=coco128.yaml model=yolov8n.pt epochs=100 imgsz=640\n\n        # Build a new model from YAML, transfer pretrained weights to it and start training\n        yolo detect train data=coco128.yaml model=yolov8n.yaml pretrained=yolov8n.pt epochs=100 imgsz=640\n        ```\n\n### Dataset format\n\nYOLO detection dataset format can be found in detail in the [Dataset Guide](../yolov5/tutorials/train_custom_data.md). To convert your existing dataset from other formats( like COCO, VOC etc.) to YOLO format, please use [json2yolo tool](https://github.com/ultralytics/JSON2YOLO) by Ultralytics.\n\n## Val\n\nValidate trained YOLOv8n model accuracy on the COCO128 dataset. No argument need to passed as the `model` retains it's training `data` and arguments as model attributes.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load an official model\n        model = YOLO('path/to/best.pt')  # load a custom model\n        \n        # Validate the model\n        metrics = model.val()  # no arguments needed, dataset and settings remembered\n        metrics.box.map    # map50-95\n        metrics.box.map50  # map50\n        metrics.box.map75  # map75\n        metrics.box.maps   # a list contains map50-95 of each category\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo detect val model=yolov8n.pt  # val official model\n        yolo detect val model=path/to/best.pt  # val custom model\n        ```\n\n## Predict\n\nUse a trained YOLOv8n model to run predictions on images.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load an official model\n        model = YOLO('path/to/best.pt')  # load a custom model\n        \n        # Predict with the model\n        results = model('https://ultralytics.com/images/bus.jpg')  # predict on an image\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo detect predict model=yolov8n.pt source='https://ultralytics.com/images/bus.jpg'  # predict with official model\n        yolo detect predict model=path/to/best.pt source='https://ultralytics.com/images/bus.jpg'  # predict with custom model\n        ```\n\nSee full `predict` mode details in the [Predict](https://docs.ultralytics.com/modes/predict/) page.\n\n## Export\n\nExport a YOLOv8n model to a different format like ONNX, CoreML, etc.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load an official model\n        model = YOLO('path/to/best.pt')  # load a custom trained\n        \n        # Export the model\n        model.export(format='onnx')\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo export model=yolov8n.pt format=onnx  # export official model\n        yolo export model=path/to/best.pt format=onnx  # export custom trained model\n        ```\n\nAvailable YOLOv8 export formats are in the table below. You can predict or validate directly on exported models, i.e. `yolo predict model=yolov8n.onnx`. Usage examples are shown for your model after export completes.\n\n| Format                                                             | `format` Argument | Model                     | Metadata | Arguments                                           |\n|--------------------------------------------------------------------|-------------------|---------------------------|----------|-----------------------------------------------------|\n| [PyTorch](https://pytorch.org/)                                    | -                 | `yolov8n.pt`              | ✅        | -                                                   |\n| [TorchScript](https://pytorch.org/docs/stable/jit.html)            | `torchscript`     | `yolov8n.torchscript`     | ✅        | `imgsz`, `optimize`                                 |\n| [ONNX](https://onnx.ai/)                                           | `onnx`            | `yolov8n.onnx`            | ✅        | `imgsz`, `half`, `dynamic`, `simplify`, `opset`     |\n| [OpenVINO](https://docs.openvino.ai/latest/index.html)             | `openvino`        | `yolov8n_openvino_model/` | ✅        | `imgsz`, `half`                                     |\n| [TensorRT](https://developer.nvidia.com/tensorrt)                  | `engine`          | `yolov8n.engine`          | ✅        | `imgsz`, `half`, `dynamic`, `simplify`, `workspace` |\n| [CoreML](https://github.com/apple/coremltools)                     | `coreml`          | `yolov8n.mlmodel`         | ✅        | `imgsz`, `half`, `int8`, `nms`                      |\n| [TF SavedModel](https://www.tensorflow.org/guide/saved_model)      | `saved_model`     | `yolov8n_saved_model/`    | ✅        | `imgsz`, `keras`                                    |\n| [TF GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb`              | `yolov8n.pb`              | ❌        | `imgsz`                                             |\n| [TF Lite](https://www.tensorflow.org/lite)                         | `tflite`          | `yolov8n.tflite`          | ✅        | `imgsz`, `half`, `int8`                             |\n| [TF Edge TPU](https://coral.ai/docs/edgetpu/models-intro/)         | `edgetpu`         | `yolov8n_edgetpu.tflite`  | ✅        | `imgsz`                                             |\n| [TF.js](https://www.tensorflow.org/js)                             | `tfjs`            | `yolov8n_web_model/`      | ✅        | `imgsz`                                             |\n| [PaddlePaddle](https://github.com/PaddlePaddle)                    | `paddle`          | `yolov8n_paddle_model/`   | ✅        | `imgsz`                                             |\n\nSee full `export` details in the [Export](https://docs.ultralytics.com/modes/export/) page."
  },
  {
    "path": "docs/tasks/index.md",
    "content": "---\ncomments: true\ndescription: Learn how Ultralytics YOLOv8 AI framework supports detection, segmentation, classification, and pose/keypoint estimation tasks.\n---\n\n# Ultralytics YOLOv8 Tasks\n\nYOLOv8 is an AI framework that supports multiple computer vision **tasks**. The framework can be used to\nperform [detection](detect.md), [segmentation](segment.md), [classification](classify.md),\nand [pose](pose.md) estimation. Each of these tasks has a different objective and use case.\n\n<img width=\"1024\" src=\"https://user-images.githubusercontent.com/26833433/212094133-6bb8c21c-3d47-41df-a512-81c5931054ae.png\">\n\n## [Detection](detect.md)\n\nDetection is the primary task supported by YOLOv8. It involves detecting objects in an image or video frame and drawing\nbounding boxes around them. The detected objects are classified into different categories based on their features.\nYOLOv8 can detect multiple objects in a single image or video frame with high accuracy and speed.\n\n[Detection Examples](detect.md){ .md-button .md-button--primary}\n\n## [Segmentation](segment.md)\n\nSegmentation is a task that involves segmenting an image into different regions based on the content of the image. Each\nregion is assigned a label based on its content. This task is useful in applications such as image segmentation and\nmedical imaging. YOLOv8 uses a variant of the U-Net architecture to perform segmentation.\n\n[Segmentation Examples](segment.md){ .md-button .md-button--primary}\n\n## [Classification](classify.md)\n\nClassification is a task that involves classifying an image into different categories. YOLOv8 can be used to classify\nimages based on their content. It uses a variant of the EfficientNet architecture to perform classification.\n\n[Classification Examples](classify.md){ .md-button .md-button--primary}\n\n## [Pose](pose.md)\n\nPose/keypoint detection is a task that involves detecting specific points in an image or video frame. These points are\nreferred to as keypoints and are used to track movement or pose estimation. YOLOv8 can detect keypoints in an image or\nvideo frame with high accuracy and speed.\n\n[Pose Examples](pose.md){ .md-button .md-button--primary}\n\n## Conclusion\n\nYOLOv8 supports multiple tasks, including detection, segmentation, classification, and keypoints detection. Each of\nthese tasks has different objectives and use cases. By understanding the differences between these tasks, you can choose\nthe appropriate task for your computer vision application."
  },
  {
    "path": "docs/tasks/pose.md",
    "content": "---\ncomments: true\ndescription: Learn how to use YOLOv8 pose estimation models to identify the position of keypoints on objects in an image, and how to train, validate, predict, and export these models for use with various formats such as ONNX or CoreML.\n---\n\nPose estimation is a task that involves identifying the location of specific points in an image, usually referred\nto as keypoints. The keypoints can represent various parts of the object such as joints, landmarks, or other distinctive\nfeatures. The locations of the keypoints are usually represented as a set of 2D `[x, y]` or 3D `[x, y, visible]`\ncoordinates.\n\n<img width=\"1024\" src=\"https://user-images.githubusercontent.com/26833433/212094133-6bb8c21c-3d47-41df-a512-81c5931054ae.png\">\n\nThe output of a pose estimation model is a set of points that represent the keypoints on an object in the image, usually\nalong with the confidence scores for each point. Pose estimation is a good choice when you need to identify specific\nparts of an object in a scene, and their location in relation to each other.\n\n!!! tip \"Tip\"\n\n    YOLOv8 _pose_ models use the `-pose` suffix, i.e. `yolov8n-pose.pt`. These models are trained on the [COCO keypoints](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco-pose.yaml) dataset and are suitable for a variety of pose estimation tasks.\n\n## [Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models/v8)\n\nYOLOv8 pretrained Pose models are shown here. Detect, Segment and Pose models are pretrained on\nthe [COCO](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco.yaml) dataset, while Classify\nmodels are pretrained on\nthe [ImageNet](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/ImageNet.yaml) dataset.\n\n[Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models) download automatically from the latest\nUltralytics [release](https://github.com/ultralytics/assets/releases) on first use.\n\n| Model                                                                                                | size<br><sup>(pixels) | mAP<sup>pose<br>50-95 | mAP<sup>pose<br>50 | Speed<br><sup>CPU ONNX<br>(ms) | Speed<br><sup>A100 TensorRT<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>(B) |\n|------------------------------------------------------------------------------------------------------|-----------------------|-----------------------|--------------------|--------------------------------|-------------------------------------|--------------------|-------------------|\n| [YOLOv8n-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n-pose.pt)       | 640                   | 50.4                  | 80.1               | 131.8                          | 1.18                                | 3.3                | 9.2               |\n| [YOLOv8s-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s-pose.pt)       | 640                   | 60.0                  | 86.2               | 233.2                          | 1.42                                | 11.6               | 30.2              |\n| [YOLOv8m-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m-pose.pt)       | 640                   | 65.0                  | 88.8               | 456.3                          | 2.00                                | 26.4               | 81.0              |\n| [YOLOv8l-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l-pose.pt)       | 640                   | 67.6                  | 90.0               | 784.5                          | 2.59                                | 44.4               | 168.6             |\n| [YOLOv8x-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-pose.pt)       | 640                   | 69.2                  | 90.2               | 1607.1                         | 3.73                                | 69.4               | 263.2             |\n| [YOLOv8x-pose-p6](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-pose-p6.pt) | 1280                  | 71.6                  | 91.2               | 4088.7                         | 10.04                               | 99.1               | 1066.4            |\n\n- **mAP<sup>val</sup>** values are for single-model single-scale on [COCO Keypoints val2017](http://cocodataset.org)\n  dataset.\n  <br>Reproduce by `yolo val pose data=coco-pose.yaml device=0`\n- **Speed** averaged over COCO val images using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/)\n  instance.\n  <br>Reproduce by `yolo val pose data=coco8-pose.yaml batch=1 device=0|cpu`\n\n## Train\n\nTrain a YOLOv8-pose model on the COCO128-pose dataset.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-pose.yaml')  # build a new model from YAML\n        model = YOLO('yolov8n-pose.pt')  # load a pretrained model (recommended for training)\n        model = YOLO('yolov8n-pose.yaml').load('yolov8n-pose.pt')  # build from YAML and transfer weights\n        \n        # Train the model\n        model.train(data='coco8-pose.yaml', epochs=100, imgsz=640)\n        ```\n    === \"CLI\"\n    \n        ```bash\n        # Build a new model from YAML and start training from scratch\n        yolo pose train data=coco8-pose.yaml model=yolov8n-pose.yaml epochs=100 imgsz=640\n\n        # Start training from a pretrained *.pt model\n        yolo pose train data=coco8-pose.yaml model=yolov8n-pose.pt epochs=100 imgsz=640\n\n        # Build a new model from YAML, transfer pretrained weights to it and start training\n        yolo pose train data=coco8-pose.yaml model=yolov8n-pose.yaml pretrained=yolov8n-pose.pt epochs=100 imgsz=640\n        ```\n\n## Val\n\nValidate trained YOLOv8n-pose model accuracy on the COCO128-pose dataset. No argument need to passed as the `model`\nretains it's\ntraining `data` and arguments as model attributes.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-pose.pt')  # load an official model\n        model = YOLO('path/to/best.pt')  # load a custom model\n        \n        # Validate the model\n        metrics = model.val()  # no arguments needed, dataset and settings remembered\n        metrics.box.map    # map50-95\n        metrics.box.map50  # map50\n        metrics.box.map75  # map75\n        metrics.box.maps   # a list contains map50-95 of each category\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo pose val model=yolov8n-pose.pt  # val official model\n        yolo pose val model=path/to/best.pt  # val custom model\n        ```\n\n## Predict\n\nUse a trained YOLOv8n-pose model to run predictions on images.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-pose.pt')  # load an official model\n        model = YOLO('path/to/best.pt')  # load a custom model\n        \n        # Predict with the model\n        results = model('https://ultralytics.com/images/bus.jpg')  # predict on an image\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo pose predict model=yolov8n-pose.pt source='https://ultralytics.com/images/bus.jpg'  # predict with official model\n        yolo pose predict model=path/to/best.pt source='https://ultralytics.com/images/bus.jpg'  # predict with custom model\n        ```\n\nSee full `predict` mode details in the [Predict](https://docs.ultralytics.com/modes/predict/) page.\n\n## Export\n\nExport a YOLOv8n Pose model to a different format like ONNX, CoreML, etc.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-pose.pt')  # load an official model\n        model = YOLO('path/to/best.pt')  # load a custom trained\n        \n        # Export the model\n        model.export(format='onnx')\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo export model=yolov8n-pose.pt format=onnx  # export official model\n        yolo export model=path/to/best.pt format=onnx  # export custom trained model\n        ```\n\nAvailable YOLOv8-pose export formats are in the table below. You can predict or validate directly on exported models,\ni.e. `yolo predict model=yolov8n-pose.onnx`. Usage examples are shown for your model after export completes.\n\n| Format                                                             | `format` Argument | Model                          | Metadata | Arguments                                           |\n|--------------------------------------------------------------------|-------------------|--------------------------------|----------|-----------------------------------------------------|\n| [PyTorch](https://pytorch.org/)                                    | -                 | `yolov8n-pose.pt`              | ✅        | -                                                   |\n| [TorchScript](https://pytorch.org/docs/stable/jit.html)            | `torchscript`     | `yolov8n-pose.torchscript`     | ✅        | `imgsz`, `optimize`                                 |\n| [ONNX](https://onnx.ai/)                                           | `onnx`            | `yolov8n-pose.onnx`            | ✅        | `imgsz`, `half`, `dynamic`, `simplify`, `opset`     |\n| [OpenVINO](https://docs.openvino.ai/latest/index.html)             | `openvino`        | `yolov8n-pose_openvino_model/` | ✅        | `imgsz`, `half`                                     |\n| [TensorRT](https://developer.nvidia.com/tensorrt)                  | `engine`          | `yolov8n-pose.engine`          | ✅        | `imgsz`, `half`, `dynamic`, `simplify`, `workspace` |\n| [CoreML](https://github.com/apple/coremltools)                     | `coreml`          | `yolov8n-pose.mlmodel`         | ✅        | `imgsz`, `half`, `int8`, `nms`                      |\n| [TF SavedModel](https://www.tensorflow.org/guide/saved_model)      | `saved_model`     | `yolov8n-pose_saved_model/`    | ✅        | `imgsz`, `keras`                                    |\n| [TF GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb`              | `yolov8n-pose.pb`              | ❌        | `imgsz`                                             |\n| [TF Lite](https://www.tensorflow.org/lite)                         | `tflite`          | `yolov8n-pose.tflite`          | ✅        | `imgsz`, `half`, `int8`                             |\n| [TF Edge TPU](https://coral.ai/docs/edgetpu/models-intro/)         | `edgetpu`         | `yolov8n-pose_edgetpu.tflite`  | ✅        | `imgsz`                                             |\n| [TF.js](https://www.tensorflow.org/js)                             | `tfjs`            | `yolov8n-pose_web_model/`      | ✅        | `imgsz`                                             |\n| [PaddlePaddle](https://github.com/PaddlePaddle)                    | `paddle`          | `yolov8n-pose_paddle_model/`   | ✅        | `imgsz`                                             |\n\nSee full `export` details in the [Export](https://docs.ultralytics.com/modes/export/) page."
  },
  {
    "path": "docs/tasks/segment.md",
    "content": "---\ncomments: true\ndescription: Learn what Instance segmentation is. Get pretrained YOLOv8 segment models, and how to train and export them to segments masks. Check the preformance metrics!\n---\n\nInstance segmentation goes a step further than object detection and involves identifying individual objects in an image\nand segmenting them from the rest of the image.\n\n<img width=\"1024\" src=\"https://user-images.githubusercontent.com/26833433/212094133-6bb8c21c-3d47-41df-a512-81c5931054ae.png\">\n\nThe output of an instance segmentation model is a set of masks or\ncontours that outline each object in the image, along with class labels and confidence scores for each object. Instance\nsegmentation is useful when you need to know not only where objects are in an image, but also what their exact shape is.\n\n!!! tip \"Tip\"\n\n    YOLOv8 Segment models use the `-seg` suffix, i.e. `yolov8n-seg.pt` and are pretrained on [COCO](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco.yaml).\n\n## [Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models/v8)\n\nYOLOv8 pretrained Segment models are shown here. Detect, Segment and Pose models are pretrained on\nthe [COCO](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco.yaml) dataset, while Classify\nmodels are pretrained on\nthe [ImageNet](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/ImageNet.yaml) dataset.\n\n[Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models) download automatically from the latest\nUltralytics [release](https://github.com/ultralytics/assets/releases) on first use.\n\n| Model                                                                                        | size<br><sup>(pixels) | mAP<sup>box<br>50-95 | mAP<sup>mask<br>50-95 | Speed<br><sup>CPU ONNX<br>(ms) | Speed<br><sup>A100 TensorRT<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>(B) |\n|----------------------------------------------------------------------------------------------|-----------------------|----------------------|-----------------------|--------------------------------|-------------------------------------|--------------------|-------------------|\n| [YOLOv8n-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n-seg.pt) | 640                   | 36.7                 | 30.5                  | 96.1                           | 1.21                                | 3.4                | 12.6              |\n| [YOLOv8s-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s-seg.pt) | 640                   | 44.6                 | 36.8                  | 155.7                          | 1.47                                | 11.8               | 42.6              |\n| [YOLOv8m-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m-seg.pt) | 640                   | 49.9                 | 40.8                  | 317.0                          | 2.18                                | 27.3               | 110.2             |\n| [YOLOv8l-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l-seg.pt) | 640                   | 52.3                 | 42.6                  | 572.4                          | 2.79                                | 46.0               | 220.5             |\n| [YOLOv8x-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-seg.pt) | 640                   | 53.4                 | 43.4                  | 712.1                          | 4.02                                | 71.8               | 344.1             |\n\n- **mAP<sup>val</sup>** values are for single-model single-scale on [COCO val2017](http://cocodataset.org) dataset.\n  <br>Reproduce by `yolo val segment data=coco.yaml device=0`\n- **Speed** averaged over COCO val images using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/)\n  instance.\n  <br>Reproduce by `yolo val segment data=coco128-seg.yaml batch=1 device=0|cpu`\n\n## Train\n\nTrain YOLOv8n-seg on the COCO128-seg dataset for 100 epochs at image size 640. For a full list of available\narguments see the [Configuration](../usage/cfg.md) page.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-seg.yaml')  # build a new model from YAML\n        model = YOLO('yolov8n-seg.pt')  # load a pretrained model (recommended for training)\n        model = YOLO('yolov8n-seg.yaml').load('yolov8n.pt')  # build from YAML and transfer weights\n        \n        # Train the model\n        model.train(data='coco128-seg.yaml', epochs=100, imgsz=640)\n        ```\n    === \"CLI\"\n    \n        ```bash\n        # Build a new model from YAML and start training from scratch\n        yolo segment train data=coco128-seg.yaml model=yolov8n-seg.yaml epochs=100 imgsz=640\n\n        # Start training from a pretrained *.pt model\n        yolo segment train data=coco128-seg.yaml model=yolov8n-seg.pt epochs=100 imgsz=640\n\n        # Build a new model from YAML, transfer pretrained weights to it and start training\n        yolo segment train data=coco128-seg.yaml model=yolov8n-seg.yaml pretrained=yolov8n-seg.pt epochs=100 imgsz=640\n        ```\n\n### Dataset format\n\nYOLO segmentation dataset label format extends detection format with segment points.\n\n`cls x1 y1 x2 y2 p1 p2 ... pn`\n\nTo convert your existing dataset from other formats( like COCO, VOC etc.) to YOLO format, please use [json2yolo tool](https://github.com/ultralytics/JSON2YOLO) by Ultralytics.\n\n## Val\n\nValidate trained YOLOv8n-seg model accuracy on the COCO128-seg dataset. No argument need to passed as the `model`\nretains it's training `data` and arguments as model attributes.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-seg.pt')  # load an official model\n        model = YOLO('path/to/best.pt')  # load a custom model\n        \n        # Validate the model\n        metrics = model.val()  # no arguments needed, dataset and settings remembered\n        metrics.box.map    # map50-95(B)\n        metrics.box.map50  # map50(B)\n        metrics.box.map75  # map75(B)\n        metrics.box.maps   # a list contains map50-95(B) of each category\n        metrics.seg.map    # map50-95(M)\n        metrics.seg.map50  # map50(M)\n        metrics.seg.map75  # map75(M)\n        metrics.seg.maps   # a list contains map50-95(M) of each category\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo segment val model=yolov8n-seg.pt  # val official model\n        yolo segment val model=path/to/best.pt  # val custom model\n        ```\n\n## Predict\n\nUse a trained YOLOv8n-seg model to run predictions on images.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-seg.pt')  # load an official model\n        model = YOLO('path/to/best.pt')  # load a custom model\n        \n        # Predict with the model\n        results = model('https://ultralytics.com/images/bus.jpg')  # predict on an image\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo segment predict model=yolov8n-seg.pt source='https://ultralytics.com/images/bus.jpg'  # predict with official model\n        yolo segment predict model=path/to/best.pt source='https://ultralytics.com/images/bus.jpg'  # predict with custom model\n        ```\n\nSee full `predict` mode details in the [Predict](https://docs.ultralytics.com/modes/predict/) page.\n\n## Export\n\nExport a YOLOv8n-seg model to a different format like ONNX, CoreML, etc.\n\n!!! example \"\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n-seg.pt')  # load an official model\n        model = YOLO('path/to/best.pt')  # load a custom trained\n        \n        # Export the model\n        model.export(format='onnx')\n        ```\n    === \"CLI\"\n    \n        ```bash\n        yolo export model=yolov8n-seg.pt format=onnx  # export official model\n        yolo export model=path/to/best.pt format=onnx  # export custom trained model\n        ```\n\nAvailable YOLOv8-seg export formats are in the table below. You can predict or validate directly on exported models,\ni.e. `yolo predict model=yolov8n-seg.onnx`. Usage examples are shown for your model after export completes.\n\n| Format                                                             | `format` Argument | Model                         | Metadata | Arguments                                           |\n|--------------------------------------------------------------------|-------------------|-------------------------------|----------|-----------------------------------------------------|\n| [PyTorch](https://pytorch.org/)                                    | -                 | `yolov8n-seg.pt`              | ✅        | -                                                   |\n| [TorchScript](https://pytorch.org/docs/stable/jit.html)            | `torchscript`     | `yolov8n-seg.torchscript`     | ✅        | `imgsz`, `optimize`                                 |\n| [ONNX](https://onnx.ai/)                                           | `onnx`            | `yolov8n-seg.onnx`            | ✅        | `imgsz`, `half`, `dynamic`, `simplify`, `opset`     |\n| [OpenVINO](https://docs.openvino.ai/latest/index.html)             | `openvino`        | `yolov8n-seg_openvino_model/` | ✅        | `imgsz`, `half`                                     |\n| [TensorRT](https://developer.nvidia.com/tensorrt)                  | `engine`          | `yolov8n-seg.engine`          | ✅        | `imgsz`, `half`, `dynamic`, `simplify`, `workspace` |\n| [CoreML](https://github.com/apple/coremltools)                     | `coreml`          | `yolov8n-seg.mlmodel`         | ✅        | `imgsz`, `half`, `int8`, `nms`                      |\n| [TF SavedModel](https://www.tensorflow.org/guide/saved_model)      | `saved_model`     | `yolov8n-seg_saved_model/`    | ✅        | `imgsz`, `keras`                                    |\n| [TF GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb`              | `yolov8n-seg.pb`              | ❌        | `imgsz`                                             |\n| [TF Lite](https://www.tensorflow.org/lite)                         | `tflite`          | `yolov8n-seg.tflite`          | ✅        | `imgsz`, `half`, `int8`                             |\n| [TF Edge TPU](https://coral.ai/docs/edgetpu/models-intro/)         | `edgetpu`         | `yolov8n-seg_edgetpu.tflite`  | ✅        | `imgsz`                                             |\n| [TF.js](https://www.tensorflow.org/js)                             | `tfjs`            | `yolov8n-seg_web_model/`      | ✅        | `imgsz`                                             |\n| [PaddlePaddle](https://github.com/PaddlePaddle)                    | `paddle`          | `yolov8n-seg_paddle_model/`   | ✅        | `imgsz`                                             |\n\nSee full `export` details in the [Export](https://docs.ultralytics.com/modes/export/) page."
  },
  {
    "path": "docs/usage/callbacks.md",
    "content": "---\ncomments: true\ndescription: Learn how to leverage callbacks in Ultralytics YOLO framework to perform custom tasks in trainer, validator, predictor and exporter modes.\n---\n\n## Callbacks\n\nUltralytics framework supports callbacks as entry points in strategic stages of train, val, export, and predict modes.\nEach callback accepts a `Trainer`, `Validator`, or `Predictor` object depending on the operation type. All properties of\nthese objects can be found in Reference section of the docs.\n\n## Examples\n\n### Returning additional information with Prediction\n\nIn this example, we want to return the original frame with each result object. Here's how we can do that\n\n```python\ndef on_predict_batch_end(predictor):\n    # Retrieve the batch data\n    _, im0s, _, _ = predictor.batch\n    \n    # Ensure that im0s is a list\n    im0s = im0s if isinstance(im0s, list) else [im0s]\n    \n    # Combine the prediction results with the corresponding frames\n    predictor.results = zip(predictor.results, im0s)\n\n# Create a YOLO model instance\nmodel = YOLO(f'yolov8n.pt')\n\n# Add the custom callback to the model\nmodel.add_callback(\"on_predict_batch_end\", on_predict_batch_end)\n\n# Iterate through the results and frames\nfor (result, frame) in model.track/predict():\n    pass\n```\n\n## All callbacks\n\nHere are all supported callbacks. See callbacks [source code](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/yolo/utils/callbacks/base.py) for additional details.\n\n### Trainer Callbacks\n\n| Callback                    | Description                                             |\n|-----------------------------|---------------------------------------------------------|\n| `on_pretrain_routine_start` | Triggered at the beginning of pre-training routine      |\n| `on_pretrain_routine_end`   | Triggered at the end of pre-training routine            |\n| `on_train_start`            | Triggered when the training starts                      |\n| `on_train_epoch_start`      | Triggered at the start of each training epoch           |\n| `on_train_batch_start`      | Triggered at the start of each training batch           |\n| `optimizer_step`            | Triggered during the optimizer step                     |\n| `on_before_zero_grad`       | Triggered before gradients are zeroed                   |\n| `on_train_batch_end`        | Triggered at the end of each training batch             |\n| `on_train_epoch_end`        | Triggered at the end of each training epoch             |\n| `on_fit_epoch_end`          | Triggered at the end of each fit epoch                  |\n| `on_model_save`             | Triggered when the model is saved                       |\n| `on_train_end`              | Triggered when the training process ends                |\n| `on_params_update`          | Triggered when model parameters are updated             |\n| `teardown`                  | Triggered when the training process is being cleaned up |\n\n### Validator Callbacks\n\n| Callback             | Description                                     |\n|----------------------|-------------------------------------------------|\n| `on_val_start`       | Triggered when the validation starts            |\n| `on_val_batch_start` | Triggered at the start of each validation batch |\n| `on_val_batch_end`   | Triggered at the end of each validation batch   |\n| `on_val_end`         | Triggered when the validation ends              |\n\n### Predictor Callbacks\n\n| Callback                     | Description                                       |\n|------------------------------|---------------------------------------------------|\n| `on_predict_start`           | Triggered when the prediction process starts      |\n| `on_predict_batch_start`     | Triggered at the start of each prediction batch   |\n| `on_predict_postprocess_end` | Triggered at the end of prediction postprocessing |\n| `on_predict_batch_end`       | Triggered at the end of each prediction batch     |\n| `on_predict_end`             | Triggered when the prediction process ends        |\n\n### Exporter Callbacks\n\n| Callback          | Description                              |\n|-------------------|------------------------------------------|\n| `on_export_start` | Triggered when the export process starts |\n| `on_export_end`   | Triggered when the export process ends   |"
  },
  {
    "path": "docs/usage/cfg.md",
    "content": "---\ncomments: true\ndescription: 'Learn about YOLO settings and modes for different tasks like detection, segmentation etc. Train and predict with custom argparse commands.'\n---\n\nYOLO settings and hyperparameters play a critical role in the model's performance, speed, and accuracy. These settings\nand hyperparameters can affect the model's behavior at various stages of the model development process, including\ntraining, validation, and prediction.\n\nYOLOv8 'yolo' CLI commands use the following syntax:\n\n!!! example \"\"\n\n    === \"CLI\"\n    \n        ```bash\n        yolo TASK MODE ARGS\n        ```\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a YOLOv8 model from a pre-trained weights file\n        model = YOLO('yolov8n.pt')\n         \n        # Run MODE mode using the custom arguments ARGS (guess TASK)\n        model.MODE(ARGS)\n        ```\n\nWhere:\n\n- `TASK` (optional) is one of `[detect, segment, classify, pose]`. If it is not passed explicitly YOLOv8 will try to\n  guess\n  the `TASK` from the model type.\n- `MODE` (required) is one of `[train, val, predict, export, track, benchmark]`\n- `ARGS` (optional) are any number of custom `arg=value` pairs like `imgsz=320` that override defaults.\n  For a full list of available `ARGS` see the [Configuration](cfg.md) page and `defaults.yaml`\n  GitHub [source](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/yolo/cfg/default.yaml).\n\n#### Tasks\n\nYOLO models can be used for a variety of tasks, including detection, segmentation, classification and pose. These tasks\ndiffer in the type of output they produce and the specific problem they are designed to solve.\n\n**Detect**: For identifying and localizing objects or regions of interest in an image or video.  \n**Segment**: For dividing an image or video into regions or pixels that correspond to different objects or classes.  \n**Classify**: For predicting the class label of an input image.  \n**Pose**: For identifying objects and estimating their keypoints in an image or video.\n\n| Key    | Value      | Description                                     |\n|--------|------------|-------------------------------------------------|\n| `task` | `'detect'` | YOLO task, i.e. detect, segment, classify, pose |\n\n[Tasks Guide](../tasks/index.md){ .md-button .md-button--primary}\n\n#### Modes\n\nYOLO models can be used in different modes depending on the specific problem you are trying to solve. These modes\ninclude:\n\n**Train**: For training a YOLOv8 model on a custom dataset.  \n**Val**: For validating a YOLOv8 model after it has been trained.  \n**Predict**: For making predictions using a trained YOLOv8 model on new images or videos.  \n**Export**: For exporting a YOLOv8 model to a format that can be used for deployment.  \n**Track**: For tracking objects in real-time using a YOLOv8 model.  \n**Benchmark**: For benchmarking YOLOv8 exports (ONNX, TensorRT, etc.) speed and accuracy.\n\n| Key    | Value     | Description                                                   |\n|--------|-----------|---------------------------------------------------------------|\n| `mode` | `'train'` | YOLO mode, i.e. train, val, predict, export, track, benchmark |\n\n[Modes Guide](../modes/index.md){ .md-button .md-button--primary}\n\n## Train\n\nThe training settings for YOLO models encompass various hyperparameters and configurations used during the training process. These settings influence the model's performance, speed, and accuracy. Key training settings include batch size, learning rate, momentum, and weight decay. Additionally, the choice of optimizer, loss function, and training dataset composition can impact the training process. Careful tuning and experimentation with these settings are crucial for optimizing performance.\n\n| Key               | Value    | Description                                                                 |\n|-------------------|----------|-----------------------------------------------------------------------------|\n| `model`           | `None`   | path to model file, i.e. yolov8n.pt, yolov8n.yaml                           |\n| `data`            | `None`   | path to data file, i.e. coco128.yaml                                        |\n| `epochs`          | `100`    | number of epochs to train for                                               |\n| `patience`        | `50`     | epochs to wait for no observable improvement for early stopping of training |\n| `batch`           | `16`     | number of images per batch (-1 for AutoBatch)                               |\n| `imgsz`           | `640`    | size of input images as integer or w,h                                      |\n| `save`            | `True`   | save train checkpoints and predict results                                  |\n| `save_period`     | `-1`     | Save checkpoint every x epochs (disabled if < 1)                            |\n| `cache`           | `False`  | True/ram, disk or False. Use cache for data loading                         |\n| `device`          | `None`   | device to run on, i.e. cuda device=0 or device=0,1,2,3 or device=cpu        |\n| `workers`         | `8`      | number of worker threads for data loading (per RANK if DDP)                 |\n| `project`         | `None`   | project name                                                                |\n| `name`            | `None`   | experiment name                                                             |\n| `exist_ok`        | `False`  | whether to overwrite existing experiment                                    |\n| `pretrained`      | `False`  | whether to use a pretrained model                                           |\n| `optimizer`       | `'SGD'`  | optimizer to use, choices=['SGD', 'Adam', 'AdamW', 'RMSProp']               |\n| `verbose`         | `False`  | whether to print verbose output                                             |\n| `seed`            | `0`      | random seed for reproducibility                                             |\n| `deterministic`   | `True`   | whether to enable deterministic mode                                        |\n| `single_cls`      | `False`  | train multi-class data as single-class                                      |\n| `rect`            | `False`  | rectangular training with each batch collated for minimum padding           |\n| `cos_lr`          | `False`  | use cosine learning rate scheduler                                          |\n| `close_mosaic`    | `0`      | (int) disable mosaic augmentation for final epochs                          |\n| `resume`          | `False`  | resume training from last checkpoint                                        |\n| `amp`             | `True`   | Automatic Mixed Precision (AMP) training, choices=[True, False]             |\n| `lr0`             | `0.01`   | initial learning rate (i.e. SGD=1E-2, Adam=1E-3)                            |\n| `lrf`             | `0.01`   | final learning rate (lr0 * lrf)                                             |\n| `momentum`        | `0.937`  | SGD momentum/Adam beta1                                                     |\n| `weight_decay`    | `0.0005` | optimizer weight decay 5e-4                                                 |\n| `warmup_epochs`   | `3.0`    | warmup epochs (fractions ok)                                                |\n| `warmup_momentum` | `0.8`    | warmup initial momentum                                                     |\n| `warmup_bias_lr`  | `0.1`    | warmup initial bias lr                                                      |\n| `box`             | `7.5`    | box loss gain                                                               |\n| `cls`             | `0.5`    | cls loss gain (scale with pixels)                                           |\n| `dfl`             | `1.5`    | dfl loss gain                                                               |\n| `pose`            | `12.0`   | pose loss gain (pose-only)                                                  |\n| `kobj`            | `2.0`    | keypoint obj loss gain (pose-only)                                          |\n| `label_smoothing` | `0.0`    | label smoothing (fraction)                                                  |\n| `nbs`             | `64`     | nominal batch size                                                          |\n| `overlap_mask`    | `True`   | masks should overlap during training (segment train only)                   |\n| `mask_ratio`      | `4`      | mask downsample ratio (segment train only)                                  |\n| `dropout`         | `0.0`    | use dropout regularization (classify train only)                            |\n| `val`             | `True`   | validate/test during training                                               |\n\n[Train Guide](../modes/train.md){ .md-button .md-button--primary}\n\n## Predict\n\nThe prediction settings for YOLO models encompass a range of hyperparameters and configurations that influence the model's performance, speed, and accuracy during inference on new data. Careful tuning and experimentation with these settings are essential to achieve optimal performance for a specific task. Key settings include the confidence threshold, Non-Maximum Suppression (NMS) threshold, and the number of classes considered. Additional factors affecting the prediction process are input data size and format, the presence of supplementary features such as masks or multiple labels per box, and the particular task the model is employed for.\n\n| Key            | Value                  | Description                                                                    |\n|----------------|------------------------|--------------------------------------------------------------------------------|\n| `source`       | `'ultralytics/assets'` | source directory for images or videos                                          |\n| `conf`         | `0.25`                 | object confidence threshold for detection                                      |\n| `iou`          | `0.7`                  | intersection over union (IoU) threshold for NMS                                |\n| `half`         | `False`                | use half precision (FP16)                                                      |\n| `device`       | `None`                 | device to run on, i.e. cuda device=0/1/2/3 or device=cpu                       |\n| `show`         | `False`                | show results if possible                                                       |\n| `save`         | `False`                | save images with results                                                       |\n| `save_txt`     | `False`                | save results as .txt file                                                      |\n| `save_conf`    | `False`                | save results with confidence scores                                            |\n| `save_crop`    | `False`                | save cropped images with results                                               |\n| `show_labels`  | `True`                 | show object labels in plots                                                    |\n| `show_conf`    | `True`                 | show object confidence scores in plots                                         |\n| `max_det`      | `300`                  | maximum number of detections per image                                         |\n| `vid_stride`   | `False`                | video frame-rate stride                                                        |\n| `line_width`   | `None`                 | The line width of the bounding boxes. If None, it is scaled to the image size. |\n| `visualize`    | `False`                | visualize model features                                                       |\n| `augment`      | `False`                | apply image augmentation to prediction sources                                 |\n| `agnostic_nms` | `False`                | class-agnostic NMS                                                             |\n| `retina_masks` | `False`                | use high-resolution segmentation masks                                         |\n| `classes`      | `None`                 | filter results by class, i.e. class=0, or class=[0,2,3]                        |\n| `boxes`        | `True`                 | Show boxes in segmentation predictions                                         |\n\n[Predict Guide](../modes/predict.md){ .md-button .md-button--primary}\n\n## Val\n\nThe val (validation) settings for YOLO models involve various hyperparameters and configurations used to evaluate the model's performance on a validation dataset. These settings influence the model's performance, speed, and accuracy. Common YOLO validation settings include batch size, validation frequency during training, and performance evaluation metrics. Other factors affecting the validation process include the validation dataset's size and composition, as well as the specific task the model is employed for. Careful tuning and experimentation with these settings are crucial to ensure optimal performance on the validation dataset and detect and prevent overfitting.\n\n| Key           | Value   | Description                                                        |\n|---------------|---------|--------------------------------------------------------------------|\n| `save_json`   | `False` | save results to JSON file                                          |\n| `save_hybrid` | `False` | save hybrid version of labels (labels + additional predictions)    |\n| `conf`        | `0.001` | object confidence threshold for detection                          |\n| `iou`         | `0.6`   | intersection over union (IoU) threshold for NMS                    |\n| `max_det`     | `300`   | maximum number of detections per image                             |\n| `half`        | `True`  | use half precision (FP16)                                          |\n| `device`      | `None`  | device to run on, i.e. cuda device=0/1/2/3 or device=cpu           |\n| `dnn`         | `False` | use OpenCV DNN for ONNX inference                                  |\n| `plots`       | `False` | show plots during training                                         |\n| `rect`        | `False` | rectangular val with each batch collated for minimum padding       |\n| `split`       | `val`   | dataset split to use for validation, i.e. 'val', 'test' or 'train' |\n\n[Val Guide](../modes/val.md){ .md-button .md-button--primary}\n\n## Export\n\nExport settings for YOLO models encompass configurations and options related to saving or exporting the model for use in different environments or platforms. These settings can impact the model's performance, size, and compatibility with various systems. Key export settings include the exported model file format (e.g., ONNX, TensorFlow SavedModel), the target device (e.g., CPU, GPU), and additional features such as masks or multiple labels per box. The export process may also be affected by the model's specific task and the requirements or constraints of the destination environment or platform. It is crucial to thoughtfully configure these settings to ensure the exported model is optimized for the intended use case and functions effectively in the target environment.\n\n| Key         | Value           | Description                                          |\n|-------------|-----------------|------------------------------------------------------|\n| `format`    | `'torchscript'` | format to export to                                  |\n| `imgsz`     | `640`           | image size as scalar or (h, w) list, i.e. (640, 480) |\n| `keras`     | `False`         | use Keras for TF SavedModel export                   |\n| `optimize`  | `False`         | TorchScript: optimize for mobile                     |\n| `half`      | `False`         | FP16 quantization                                    |\n| `int8`      | `False`         | INT8 quantization                                    |\n| `dynamic`   | `False`         | ONNX/TF/TensorRT: dynamic axes                       |\n| `simplify`  | `False`         | ONNX: simplify model                                 |\n| `opset`     | `None`          | ONNX: opset version (optional, defaults to latest)   |\n| `workspace` | `4`             | TensorRT: workspace size (GB)                        |\n| `nms`       | `False`         | CoreML: add NMS                                      |\n\n[Export Guide](../modes/export.md){ .md-button .md-button--primary}\n\n## Augmentation\n\nAugmentation settings for YOLO models refer to the various transformations and modifications\napplied to the training data to increase the diversity and size of the dataset. These settings can affect the model's\nperformance, speed, and accuracy. Some common YOLO augmentation settings include the type and intensity of the\ntransformations applied (e.g. random flips, rotations, cropping, color changes), the probability with which each\ntransformation is applied, and the presence of additional features such as masks or multiple labels per box. Other\nfactors that may affect the augmentation process include the size and composition of the original dataset and the\nspecific task the model is being used for. It is important to carefully tune and experiment with these settings to\nensure that the augmented dataset is diverse and representative enough to train a high-performing model.\n\n| Key           | Value | Description                                     |\n|---------------|-------|-------------------------------------------------|\n| `hsv_h`       | 0.015 | image HSV-Hue augmentation (fraction)           |\n| `hsv_s`       | 0.7   | image HSV-Saturation augmentation (fraction)    |\n| `hsv_v`       | 0.4   | image HSV-Value augmentation (fraction)         |\n| `degrees`     | 0.0   | image rotation (+/- deg)                        |\n| `translate`   | 0.1   | image translation (+/- fraction)                |\n| `scale`       | 0.5   | image scale (+/- gain)                          |\n| `shear`       | 0.0   | image shear (+/- deg)                           |\n| `perspective` | 0.0   | image perspective (+/- fraction), range 0-0.001 |\n| `flipud`      | 0.0   | image flip up-down (probability)                |\n| `fliplr`      | 0.5   | image flip left-right (probability)             |\n| `mosaic`      | 1.0   | image mosaic (probability)                      |\n| `mixup`       | 0.0   | image mixup (probability)                       |\n| `copy_paste`  | 0.0   | segment copy-paste (probability)                |\n\n## Logging, checkpoints, plotting and file management\n\nLogging, checkpoints, plotting, and file management are important considerations when training a YOLO model.\n\n- Logging: It is often helpful to log various metrics and statistics during training to track the model's progress and\n  diagnose any issues that may arise. This can be done using a logging library such as TensorBoard or by writing log\n  messages to a file.\n- Checkpoints: It is a good practice to save checkpoints of the model at regular intervals during training. This allows\n  you to resume training from a previous point if the training process is interrupted or if you want to experiment with\n  different training configurations.\n- Plotting: Visualizing the model's performance and training progress can be helpful for understanding how the model is\n  behaving and identifying potential issues. This can be done using a plotting library such as matplotlib or by\n  generating plots using a logging library such as TensorBoard.\n- File management: Managing the various files generated during the training process, such as model checkpoints, log\n  files, and plots, can be challenging. It is important to have a clear and organized file structure to keep track of\n  these files and make it easy to access and analyze them as needed.\n\nEffective logging, checkpointing, plotting, and file management can help you keep track of the model's progress and make\nit easier to debug and optimize the training process.\n\n| Key        | Value    | Description                                                                                    |\n|------------|----------|------------------------------------------------------------------------------------------------|\n| `project`  | `'runs'` | project name                                                                                   |\n| `name`     | `'exp'`  | experiment name. `exp` gets automatically incremented if not specified, i.e, `exp`, `exp2` ... |\n| `exist_ok` | `False`  | whether to overwrite existing experiment                                                       |\n| `plots`    | `False`  | save plots during train/val                                                                    |\n| `save`     | `False`  | save train checkpoints and predict results                                                     |"
  },
  {
    "path": "docs/usage/cli.md",
    "content": "---\ncomments: true\ndescription: Learn how to use YOLOv8 from the Command Line Interface (CLI) through simple, single-line commands with `yolo` without Python code.\n---\n\n# Command Line Interface Usage\n\nThe YOLO command line interface (CLI) allows for simple single-line commands without the need for a Python environment.\nCLI requires no customization or Python code. You can simply run all tasks from the terminal with the `yolo` command.\n\n!!! example\n\n    === \"Syntax\"\n\n        Ultralytics `yolo` commands use the following syntax:\n        ```bash\n        yolo TASK MODE ARGS\n\n        Where   TASK (optional) is one of [detect, segment, classify]\n                MODE (required) is one of [train, val, predict, export, track]\n                ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.\n        ```\n        See all ARGS in the full [Configuration Guide](./cfg.md) or with `yolo cfg`\n\n    === \"Train\"\n\n        Train a detection model for 10 epochs with an initial learning_rate of 0.01\n        ```bash\n        yolo train data=coco128.yaml model=yolov8n.pt epochs=10 lr0=0.01\n        ```\n\n    === \"Predict\"\n\n        Predict a YouTube video using a pretrained segmentation model at image size 320:\n        ```bash\n        yolo predict model=yolov8n-seg.pt source='https://youtu.be/Zgi9g1ksQHc' imgsz=320\n        ```\n\n    === \"Val\"\n\n        Val a pretrained detection model at batch-size 1 and image size 640:\n        ```bash\n        yolo val model=yolov8n.pt data=coco128.yaml batch=1 imgsz=640\n        ```\n\n    === \"Export\"\n\n        Export a YOLOv8n classification model to ONNX format at image size 224 by 128 (no TASK required)\n        ```bash\n        yolo export model=yolov8n-cls.pt format=onnx imgsz=224,128\n        ```\n\n    === \"Special\"\n\n        Run special commands to see version, view settings, run checks and more:\n        ```bash\n        yolo help\n        yolo checks\n        yolo version\n        yolo settings\n        yolo copy-cfg\n        yolo cfg\n        ```\n\nWhere:\n\n- `TASK` (optional) is one of `[detect, segment, classify]`. If it is not passed explicitly YOLOv8 will try to guess\n  the `TASK` from the model type.\n- `MODE` (required) is one of `[train, val, predict, export, track]`\n- `ARGS` (optional) are any number of custom `arg=value` pairs like `imgsz=320` that override defaults.\n  For a full list of available `ARGS` see the [Configuration](cfg.md) page and `defaults.yaml`\n  GitHub [source](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/yolo/cfg/default.yaml).\n\n!!! warning \"Warning\"\n\n    Arguments must be passed as `arg=val` pairs, split by an equals `=` sign and delimited by spaces ` ` between pairs. Do not use `--` argument prefixes or commas `,` beteen arguments.\n\n    - `yolo predict model=yolov8n.pt imgsz=640 conf=0.25` &nbsp; ✅\n    - `yolo predict model yolov8n.pt imgsz 640 conf 0.25` &nbsp; ❌\n    - `yolo predict --model yolov8n.pt --imgsz 640 --conf 0.25` &nbsp; ❌\n\n## Train\n\nTrain YOLOv8n on the COCO128 dataset for 100 epochs at image size 640. For a full list of available arguments see\nthe [Configuration](cfg.md) page.\n\n!!! example \"Example\"\n\n    === \"Train\"\n        \n        Start training YOLOv8n on COCO128 for 100 epochs at image-size 640.\n        ```bash\n        yolo detect train data=coco128.yaml model=yolov8n.pt epochs=100 imgsz=640\n        ```\n\n    === \"Resume\"\n\n        Resume an interrupted training.\n        ```bash\n        yolo detect train resume model=last.pt\n        ```\n\n## Val\n\nValidate trained YOLOv8n model accuracy on the COCO128 dataset. No argument need to passed as the `model` retains it's\ntraining `data` and arguments as model attributes.\n\n!!! example \"Example\"\n\n    === \"Official\"\n\n        Validate an official YOLOv8n model.\n        ```bash\n        yolo detect val model=yolov8n.pt\n        ```\n\n    === \"Custom\"\n\n        Validate a custom-trained model.\n        ```bash\n        yolo detect val model=path/to/best.pt\n        ```\n\n## Predict\n\nUse a trained YOLOv8n model to run predictions on images.\n\n!!! example \"Example\"\n\n    === \"Official\"\n\n        Predict with an official YOLOv8n model.\n        ```bash\n        yolo detect predict model=yolov8n.pt source='https://ultralytics.com/images/bus.jpg'\n        ```\n\n    === \"Custom\"\n\n        Predict with a custom model.\n        ```bash\n        yolo detect predict model=path/to/best.pt source='https://ultralytics.com/images/bus.jpg'\n        ```\n\n## Export\n\nExport a YOLOv8n model to a different format like ONNX, CoreML, etc.\n\n!!! example \"Example\"\n\n    === \"Official\"\n\n        Export an official YOLOv8n model to ONNX format.\n        ```bash\n        yolo export model=yolov8n.pt format=onnx\n        ```\n\n    === \"Custom\"\n\n        Export a custom-trained model to ONNX format.\n        ```bash\n        yolo export model=path/to/best.pt format=onnx\n        ```\n\nAvailable YOLOv8 export formats are in the table below. You can export to any format using the `format` argument,\ni.e. `format='onnx'` or `format='engine'`.\n\n| Format                                                             | `format` Argument | Model                     | Metadata |\n|--------------------------------------------------------------------|-------------------|---------------------------|----------|\n| [PyTorch](https://pytorch.org/)                                    | -                 | `yolov8n.pt`              | ✅        |\n| [TorchScript](https://pytorch.org/docs/stable/jit.html)            | `torchscript`     | `yolov8n.torchscript`     | ✅        |\n| [ONNX](https://onnx.ai/)                                           | `onnx`            | `yolov8n.onnx`            | ✅        |\n| [OpenVINO](https://docs.openvino.ai/latest/index.html)             | `openvino`        | `yolov8n_openvino_model/` | ✅        |\n| [TensorRT](https://developer.nvidia.com/tensorrt)                  | `engine`          | `yolov8n.engine`          | ✅        |\n| [CoreML](https://github.com/apple/coremltools)                     | `coreml`          | `yolov8n.mlmodel`         | ✅        |\n| [TF SavedModel](https://www.tensorflow.org/guide/saved_model)      | `saved_model`     | `yolov8n_saved_model/`    | ✅        |\n| [TF GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb`              | `yolov8n.pb`              | ❌        |\n| [TF Lite](https://www.tensorflow.org/lite)                         | `tflite`          | `yolov8n.tflite`          | ✅        |\n| [TF Edge TPU](https://coral.ai/docs/edgetpu/models-intro/)         | `edgetpu`         | `yolov8n_edgetpu.tflite`  | ✅        |\n| [TF.js](https://www.tensorflow.org/js)                             | `tfjs`            | `yolov8n_web_model/`      | ✅        |\n| [PaddlePaddle](https://github.com/PaddlePaddle)                    | `paddle`          | `yolov8n_paddle_model/`   | ✅        |\n\n---\n\n## Overriding default arguments\n\nDefault arguments can be overridden by simply passing them as arguments in the CLI in `arg=value` pairs.\n\n!!! tip \"\"\n\n    === \"Train\"\n        Train a detection model for `10 epochs` with `learning_rate` of `0.01`\n        ```bash\n        yolo detect train data=coco128.yaml model=yolov8n.pt epochs=10 lr0=0.01\n        ```\n\n    === \"Predict\"\n        Predict a YouTube video using a pretrained segmentation model at image size 320:\n        ```bash\n        yolo segment predict model=yolov8n-seg.pt source='https://youtu.be/Zgi9g1ksQHc' imgsz=320\n        ```\n\n    === \"Val\"\n        Validate a pretrained detection model at batch-size 1 and image size 640:\n        ```bash\n        yolo detect val model=yolov8n.pt data=coco128.yaml batch=1 imgsz=640\n        ```\n\n---\n\n## Overriding default config file\n\nYou can override the `default.yaml` config file entirely by passing a new file with the `cfg` arguments,\ni.e. `cfg=custom.yaml`.\n\nTo do this first create a copy of `default.yaml` in your current working dir with the `yolo copy-cfg` command.\n\nThis will create `default_copy.yaml`, which you can then pass as `cfg=default_copy.yaml` along with any additional args,\nlike `imgsz=320` in this example:\n\n!!! example \"\"\n\n    === \"CLI\"\n        ```bash\n        yolo copy-cfg\n        yolo cfg=default_copy.yaml imgsz=320\n        ```"
  },
  {
    "path": "docs/usage/engine.md",
    "content": "---\ncomments: true\ndescription: Learn how to train and customize your models fast with the Ultralytics YOLO 'DetectionTrainer' and 'CustomTrainer'. Read more here!\n---\n\nBoth the Ultralytics YOLO command-line and python interfaces are simply a high-level abstraction on the base engine\nexecutors. Let's take a look at the Trainer engine.\n\n## BaseTrainer\n\nBaseTrainer contains the generic boilerplate training routine. It can be customized for any task based over overriding\nthe required functions or operations as long the as correct formats are followed. For example, you can support your own\ncustom model and dataloader by just overriding these functions:\n\n* `get_model(cfg, weights)` - The function that builds the model to be trained\n* `get_dataloder()` - The function that builds the dataloader\n  More details and source code can be found in [`BaseTrainer` Reference](../reference/yolo/engine/trainer.md)\n\n## DetectionTrainer\n\nHere's how you can use the YOLOv8 `DetectionTrainer` and customize it.\n\n```python\nfrom ultralytics.yolo.v8.detect import DetectionTrainer\n\ntrainer = DetectionTrainer(overrides={...})\ntrainer.train()\ntrained_model = trainer.best  # get best model\n```\n\n### Customizing the DetectionTrainer\n\nLet's customize the trainer **to train a custom detection model** that is not supported directly. You can do this by\nsimply overloading the existing the `get_model` functionality:\n\n```python\nfrom ultralytics.yolo.v8.detect import DetectionTrainer\n\n\nclass CustomTrainer(DetectionTrainer):\n    def get_model(self, cfg, weights):\n        ...\n\n\ntrainer = CustomTrainer(overrides={...})\ntrainer.train()\n```\n\nYou now realize that you need to customize the trainer further to:\n\n* Customize the `loss function`.\n* Add `callback` that uploads model to your Google Drive after every 10 `epochs`\n  Here's how you can do it:\n\n```python\nfrom ultralytics.yolo.v8.detect import DetectionTrainer\n\n\nclass CustomTrainer(DetectionTrainer):\n    def get_model(self, cfg, weights):\n        ...\n\n    def criterion(self, preds, batch):\n        # get ground truth\n        imgs = batch[\"imgs\"]\n        bboxes = batch[\"bboxes\"]\n        ...\n        return loss, loss_items  # see Reference-> Trainer for details on the expected format\n\n\n# callback to upload model weights\ndef log_model(trainer):\n    last_weight_path = trainer.last\n    ...\n\n\ntrainer = CustomTrainer(overrides={...})\ntrainer.add_callback(\"on_train_epoch_end\", log_model)  # Adds to existing callback\ntrainer.train()\n```\n\nTo know more about Callback triggering events and entry point, checkout our [Callbacks Guide](callbacks.md)\n\n## Other engine components\n\nThere are other components that can be customized similarly like `Validators` and `Predictors`\nSee Reference section for more information on these."
  },
  {
    "path": "docs/usage/hyperparameter_tuning.md",
    "content": "---\ncomments: true\ndescription: Discover how to integrate hyperparameter tuning with Ray Tune and Ultralytics YOLOv8. Speed up the tuning process and optimize your model's performance.\n---\n\n# Hyperparameter Tuning with Ray Tune and YOLOv8\n\nHyperparameter tuning (or hyperparameter optimization) is the process of determining the right combination of hyperparameters that maximizes model performance. It works by running multiple trials in a single training process, evaluating the performance of each trial, and selecting the best hyperparameter values based on the evaluation results.\n\n## Ultralytics YOLOv8 and Ray Tune Integration\n\n[Ultralytics](https://ultralytics.com) YOLOv8 integrates hyperparameter tuning with Ray Tune, allowing you to easily optimize your YOLOv8 model's hyperparameters. By using Ray Tune, you can leverage advanced search algorithms, parallelism, and early stopping to speed up the tuning process and achieve better model performance.\n\n### Ray Tune\n\n<div align=\"center\">\n<a href=\"https://docs.ray.io/en/latest/tune/index.html\" target=\"_blank\">\n<img width=\"480\" src=\"https://docs.ray.io/en/latest/_images/tune_overview.png\"></a>\n</div>\n\n[Ray Tune](https://docs.ray.io/en/latest/tune/index.html) is a powerful and flexible hyperparameter tuning library for machine learning models. It provides an efficient way to optimize hyperparameters by supporting various search algorithms, parallelism, and early stopping strategies. Ray Tune's flexible architecture enables seamless integration with popular machine learning frameworks, including Ultralytics YOLOv8.\n\n### Weights & Biases\n\nYOLOv8 also supports optional integration with [Weights & Biases](https://wandb.ai/site) (wandb) for tracking the tuning progress.\n\n## Installation\n\nTo install the required packages, run:\n\n!!! tip \"Installation\"\n\n    ```bash\n    pip install -U ultralytics \"ray[tune]\"  # install and/or update\n    pip install wandb  # optional\n    ```\n\n## Usage\n\n!!! example \"Usage\"\n\n    ```python\n    from ultralytics import YOLO\n\n    model = YOLO(\"yolov8n.pt\")\n    results = model.tune(data=\"coco128.yaml\")\n    ```\n\n## `tune()` Method Parameters\n\nThe `tune()` method in YOLOv8 provides an easy-to-use interface for hyperparameter tuning with Ray Tune. It accepts several arguments that allow you to customize the tuning process. Below is a detailed explanation of each parameter:\n\n| Parameter       | Type           | Description                                                                                                                                                                                                                                                                                                                   | Default Value |\n|-----------------|----------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------|\n| `data`          | str            | The dataset configuration file (in YAML format) to run the tuner on. This file should specify the training and validation data paths, as well as other dataset-specific settings.                                                                                                                                             |               |\n| `space`         | dict, optional | A dictionary defining the hyperparameter search space for Ray Tune. Each key corresponds to a hyperparameter name, and the value specifies the range of values to explore during tuning. If not provided, YOLOv8 uses a default search space with various hyperparameters.                                                    |               |\n| `grace_period`  | int, optional  | The grace period in epochs for the [ASHA scheduler](https://docs.ray.io/en/latest/tune/api_docs/schedulers.html#asha-tune-schedulers-asha) in Ray Tune. The scheduler will not terminate any trial before this number of epochs, allowing the model to have some minimum training before making a decision on early stopping. | 10            |\n| `gpu_per_trial` | int, optional  | The number of GPUs to allocate per trial during tuning. This helps manage GPU usage, particularly in multi-GPU environments. If not provided, the tuner will use all available GPUs.                                                                                                                                          | None          |\n| `max_samples`   | int, optional  | The maximum number of trials to run during tuning. This parameter helps control the total number of hyperparameter combinations tested, ensuring the tuning process does not run indefinitely.                                                                                                                                | 10            |\n| `train_args`    | dict, optional | A dictionary of additional arguments to pass to the `train()` method during tuning. These arguments can include settings like the number of training epochs, batch size, and other training-specific configurations.                                                                                                          | {}            |\n\nBy customizing these parameters, you can fine-tune the hyperparameter optimization process to suit your specific needs and available computational resources.\n\n## Default Search Space Description\n\nThe following table lists the default search space parameters for hyperparameter tuning in YOLOv8 with Ray Tune. Each parameter has a specific value range defined by `tune.uniform()`.\n\n| Parameter       | Value Range                | Description                              |\n|-----------------|----------------------------|------------------------------------------|\n| lr0             | `tune.uniform(1e-5, 1e-1)` | Initial learning rate                    |\n| lrf             | `tune.uniform(0.01, 1.0)`  | Final learning rate factor               |\n| momentum        | `tune.uniform(0.6, 0.98)`  | Momentum                                 |\n| weight_decay    | `tune.uniform(0.0, 0.001)` | Weight decay                             |\n| warmup_epochs   | `tune.uniform(0.0, 5.0)`   | Warmup epochs                            |\n| warmup_momentum | `tune.uniform(0.0, 0.95)`  | Warmup momentum                          |\n| box             | `tune.uniform(0.02, 0.2)`  | Box loss weight                          |\n| cls             | `tune.uniform(0.2, 4.0)`   | Class loss weight                        |\n| hsv_h           | `tune.uniform(0.0, 0.1)`   | Hue augmentation range                   |\n| hsv_s           | `tune.uniform(0.0, 0.9)`   | Saturation augmentation range            |\n| hsv_v           | `tune.uniform(0.0, 0.9)`   | Value (brightness) augmentation range    |\n| degrees         | `tune.uniform(0.0, 45.0)`  | Rotation augmentation range (degrees)    |\n| translate       | `tune.uniform(0.0, 0.9)`   | Translation augmentation range           |\n| scale           | `tune.uniform(0.0, 0.9)`   | Scaling augmentation range               |\n| shear           | `tune.uniform(0.0, 10.0)`  | Shear augmentation range (degrees)       |\n| perspective     | `tune.uniform(0.0, 0.001)` | Perspective augmentation range           |\n| flipud          | `tune.uniform(0.0, 1.0)`   | Vertical flip augmentation probability   |\n| fliplr          | `tune.uniform(0.0, 1.0)`   | Horizontal flip augmentation probability |\n| mosaic          | `tune.uniform(0.0, 1.0)`   | Mosaic augmentation probability          |\n| mixup           | `tune.uniform(0.0, 1.0)`   | Mixup augmentation probability           |\n| copy_paste      | `tune.uniform(0.0, 1.0)`   | Copy-paste augmentation probability      |\n\n## Custom Search Space Example\n\nIn this example, we demonstrate how to use a custom search space for hyperparameter tuning with Ray Tune and YOLOv8. By providing a custom search space, you can focus the tuning process on specific hyperparameters of interest.\n\n!!! example \"Usage\"\n\n    ```python\n    from ultralytics import YOLO\n    from ray import tune\n    \n    model = YOLO(\"yolov8n.pt\")\n    result = model.tune(\n        data=\"coco128.yaml\",\n        space={\"lr0\": tune.uniform(1e-5, 1e-1)},\n        train_args={\"epochs\": 50}\n    )\n    ```\n\nIn the code snippet above, we create a YOLO model with the \"yolov8n.pt\" pretrained weights. Then, we call the `tune()` method, specifying the dataset configuration with \"coco128.yaml\". We provide a custom search space for the initial learning rate `lr0` using a dictionary with the key \"lr0\" and the value `tune.uniform(1e-5, 1e-1)`. Finally, we pass additional training arguments, such as the number of epochs, using the `train_args` parameter."
  },
  {
    "path": "docs/usage/python.md",
    "content": "---\ncomments: true\ndescription: Integrate YOLOv8 in Python. Load, use pretrained models, train, and infer images. Export to ONNX. Track objects in videos.\n---\n\n# Python Usage\n\nWelcome to the YOLOv8 Python Usage documentation! This guide is designed to help you seamlessly integrate YOLOv8 into\nyour Python projects for object detection, segmentation, and classification. Here, you'll learn how to load and use\npretrained models, train new models, and perform predictions on images. The easy-to-use Python interface is a valuable\nresource for anyone looking to incorporate YOLOv8 into their Python projects, allowing you to quickly implement advanced\nobject detection capabilities. Let's get started!\n\nFor example, users can load a model, train it, evaluate its performance on a validation set, and even export it to ONNX\nformat with just a few lines of code.\n\n!!! example \"Python\"\n\n    ```python\n    from ultralytics import YOLO\n    \n    # Create a new YOLO model from scratch\n    model = YOLO('yolov8n.yaml')\n    \n    # Load a pretrained YOLO model (recommended for training)\n    model = YOLO('yolov8n.pt')\n    \n    # Train the model using the 'coco128.yaml' dataset for 3 epochs\n    results = model.train(data='coco128.yaml', epochs=3)\n    \n    # Evaluate the model's performance on the validation set\n    results = model.val()\n    \n    # Perform object detection on an image using the model\n    results = model('https://ultralytics.com/images/bus.jpg')\n    \n    # Export the model to ONNX format\n    success = model.export(format='onnx')\n    ```\n\n## [Train](../modes/train.md)\n\nTrain mode is used for training a YOLOv8 model on a custom dataset. In this mode, the model is trained using the\nspecified dataset and hyperparameters. The training process involves optimizing the model's parameters so that it can\naccurately predict the classes and locations of objects in an image.\n\n!!! example \"Train\"\n\n    === \"From pretrained(recommended)\"\n        ```python\n        from ultralytics import YOLO\n\n        model = YOLO('yolov8n.pt') # pass any model type\n        model.train(epochs=5)\n        ```\n\n    === \"From scratch\"\n        ```python\n        from ultralytics import YOLO\n\n        model = YOLO('yolov8n.yaml')\n        model.train(data='coco128.yaml', epochs=5)\n        ```\n\n    === \"Resume\"\n        ```python\n        model = YOLO(\"last.pt\")\n        model.train(resume=True)\n        ```\n\n[Train Examples](../modes/train.md){ .md-button .md-button--primary}\n\n## [Val](../modes/val.md)\n\nVal mode is used for validating a YOLOv8 model after it has been trained. In this mode, the model is evaluated on a\nvalidation set to measure its accuracy and generalization performance. This mode can be used to tune the hyperparameters\nof the model to improve its performance.\n\n!!! example \"Val\"\n\n    === \"Val after training\"\n        ```python\n          from ultralytics import YOLO\n\n          model = YOLO('yolov8n.yaml')\n          model.train(data='coco128.yaml', epochs=5)\n          model.val()  # It'll automatically evaluate the data you trained.\n        ```\n\n    === \"Val independently\"\n        ```python\n          from ultralytics import YOLO\n\n          model = YOLO(\"model.pt\")\n          # It'll use the data yaml file in model.pt if you don't set data.\n          model.val()\n          # or you can set the data you want to val\n          model.val(data='coco128.yaml')\n        ```\n\n[Val Examples](../modes/val.md){ .md-button .md-button--primary}\n\n## [Predict](../modes/predict.md)\n\nPredict mode is used for making predictions using a trained YOLOv8 model on new images or videos. In this mode, the\nmodel is loaded from a checkpoint file, and the user can provide images or videos to perform inference. The model\npredicts the classes and locations of objects in the input images or videos.\n\n!!! example \"Predict\"\n\n    === \"From source\"\n        ```python\n        from ultralytics import YOLO\n        from PIL import Image\n        import cv2\n\n        model = YOLO(\"model.pt\")\n        # accepts all formats - image/dir/Path/URL/video/PIL/ndarray. 0 for webcam\n        results = model.predict(source=\"0\")\n        results = model.predict(source=\"folder\", show=True) # Display preds. Accepts all YOLO predict arguments\n\n        # from PIL\n        im1 = Image.open(\"bus.jpg\")\n        results = model.predict(source=im1, save=True)  # save plotted images\n\n        # from ndarray\n        im2 = cv2.imread(\"bus.jpg\")\n        results = model.predict(source=im2, save=True, save_txt=True)  # save predictions as labels\n\n        # from list of PIL/ndarray\n        results = model.predict(source=[im1, im2])\n        ```\n\n    === \"Results usage\"\n        ```python\n        # results would be a list of Results object including all the predictions by default\n        # but be careful as it could occupy a lot memory when there're many images, \n        # especially the task is segmentation.\n        # 1. return as a list\n        results = model.predict(source=\"folder\")\n\n        # results would be a generator which is more friendly to memory by setting stream=True\n        # 2. return as a generator\n        results = model.predict(source=0, stream=True)\n\n        for result in results:\n            # Detection\n            result.boxes.xyxy   # box with xyxy format, (N, 4)\n            result.boxes.xywh   # box with xywh format, (N, 4)\n            result.boxes.xyxyn  # box with xyxy format but normalized, (N, 4)\n            result.boxes.xywhn  # box with xywh format but normalized, (N, 4)\n            result.boxes.conf   # confidence score, (N, 1)\n            result.boxes.cls    # cls, (N, 1)\n\n            # Segmentation\n            result.masks.data      # masks, (N, H, W)\n            result.masks.xy        # x,y segments (pixels), List[segment] * N\n            result.masks.xyn       # x,y segments (normalized), List[segment] * N\n\n            # Classification\n            result.probs     # cls prob, (num_class, )\n\n        # Each result is composed of torch.Tensor by default, \n        # in which you can easily use following functionality:\n        result = result.cuda()\n        result = result.cpu()\n        result = result.to(\"cpu\")\n        result = result.numpy()\n        ```\n\n[Predict Examples](../modes/predict.md){ .md-button .md-button--primary}\n\n## [Export](../modes/export.md)\n\nExport mode is used for exporting a YOLOv8 model to a format that can be used for deployment. In this mode, the model is\nconverted to a format that can be used by other software applications or hardware devices. This mode is useful when\ndeploying the model to production environments.\n\n!!! example \"Export\"\n\n    === \"Export to ONNX\"\n\n        Export an official YOLOv8n model to ONNX with dynamic batch-size and image-size.\n        ```python\n          from ultralytics import YOLO\n\n          model = YOLO('yolov8n.pt')\n          model.export(format='onnx', dynamic=True)\n        ```\n\n    === \"Export to TensorRT\"\n\n        Export an official YOLOv8n model to TensorRT on `device=0` for acceleration on CUDA devices.\n        ```python\n          from ultralytics import YOLO\n\n          model = YOLO('yolov8n.pt')\n          model.export(format='onnx', device=0)\n        ```\n\n[Export Examples](../modes/export.md){ .md-button .md-button--primary}\n\n## [Track](../modes/track.md)\n\nTrack mode is used for tracking objects in real-time using a YOLOv8 model. In this mode, the model is loaded from a\ncheckpoint file, and the user can provide a live video stream to perform real-time object tracking. This mode is useful\nfor applications such as surveillance systems or self-driving cars.\n\n!!! example \"Track\"\n\n    === \"Python\"\n    \n        ```python\n        from ultralytics import YOLO\n        \n        # Load a model\n        model = YOLO('yolov8n.pt')  # load an official detection model\n        model = YOLO('yolov8n-seg.pt')  # load an official segmentation model\n        model = YOLO('path/to/best.pt')  # load a custom model\n        \n        # Track with the model\n        results = model.track(source=\"https://youtu.be/Zgi9g1ksQHc\", show=True) \n        results = model.track(source=\"https://youtu.be/Zgi9g1ksQHc\", show=True, tracker=\"bytetrack.yaml\") \n        ```\n\n[Track Examples](../modes/track.md){ .md-button .md-button--primary}\n\n## [Benchmark](../modes/benchmark.md)\n\nBenchmark mode is used to profile the speed and accuracy of various export formats for YOLOv8. The benchmarks provide\ninformation on the size of the exported format, its `mAP50-95` metrics (for object detection and segmentation)\nor `accuracy_top5` metrics (for classification), and the inference time in milliseconds per image across various export\nformats like ONNX, OpenVINO, TensorRT and others. This information can help users choose the optimal export format for\ntheir specific use case based on their requirements for speed and accuracy.\n\n!!! example \"Benchmark\"\n\n    === \"Python\"\n    \n        Benchmark an official YOLOv8n model across all export formats.\n        ```python\n        from ultralytics.yolo.utils.benchmarks import benchmark\n        \n        # Benchmark\n        benchmark(model='yolov8n.pt', imgsz=640, half=False, device=0)\n        ```\n\n[Benchmark Examples](../modes/benchmark.md){ .md-button .md-button--primary}\n\n## Using Trainers\n\n`YOLO` model class is a high-level wrapper on the Trainer classes. Each YOLO task has its own trainer that inherits\nfrom `BaseTrainer`.\n\n!!! tip \"Detection Trainer Example\"\n\n        ```python\n        from ultralytics.yolo import v8 import DetectionTrainer, DetectionValidator, DetectionPredictor\n\n        # trainer\n        trainer = DetectionTrainer(overrides={})\n        trainer.train()\n        trained_model = trainer.best\n\n        # Validator\n        val = DetectionValidator(args=...)\n        val(model=trained_model)\n\n        # predictor\n        pred = DetectionPredictor(overrides={})\n        pred(source=SOURCE, model=trained_model)\n\n        # resume from last weight\n        overrides[\"resume\"] = trainer.last\n        trainer = detect.DetectionTrainer(overrides=overrides)\n        ```\n\nYou can easily customize Trainers to support custom tasks or explore R&D ideas.\nLearn more about Customizing `Trainers`, `Validators` and `Predictors` to suit your project needs in the Customization\nSection.\n\n[Customization tutorials](engine.md){ .md-button .md-button--primary}"
  },
  {
    "path": "docs/yolov5/environments/aws_quickstart_tutorial.md",
    "content": "---\ncomments: true\ndescription: Get started with YOLOv5 on AWS. Our comprehensive guide provides everything you need to know to run YOLOv5 on an Amazon Deep Learning instance.\n---\n\n# YOLOv5 🚀 on AWS Deep Learning Instance: A Comprehensive Guide\n\nThis guide will help new users run YOLOv5 on an Amazon Web Services (AWS) Deep Learning instance. AWS offers a [Free Tier](https://aws.amazon.com/free/) and a [credit program](https://aws.amazon.com/activate/) for a quick and affordable start.\n\nOther quickstart options for YOLOv5 include our [Colab Notebook](https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb) <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>, [GCP Deep Learning VM](https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial), and our Docker image at [Docker Hub](https://hub.docker.com/r/ultralytics/yolov5) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>. *Updated: 21 April 2023*.\n\n## 1. AWS Console Sign-in\n\nCreate an account or sign in to the AWS console at [https://aws.amazon.com/console/](https://aws.amazon.com/console/) and select the **EC2** service.\n\n![Console](https://user-images.githubusercontent.com/26833433/106323804-debddd00-622c-11eb-997f-b8217dc0e975.png)\n\n## 2. Launch Instance\n\nIn the EC2 section of the AWS console, click the **Launch instance** button.\n\n![Launch](https://user-images.githubusercontent.com/26833433/106323950-204e8800-622d-11eb-915d-5c90406973ea.png)\n\n### Choose an Amazon Machine Image (AMI)\n\nEnter 'Deep Learning' in the search field and select the most recent Ubuntu Deep Learning AMI (recommended), or an alternative Deep Learning AMI. For more information on selecting an AMI, see [Choosing Your DLAMI](https://docs.aws.amazon.com/dlami/latest/devguide/options.html).\n\n![Choose AMI](https://user-images.githubusercontent.com/26833433/106326107-c9e34880-6230-11eb-97c9-3b5fc2f4e2ff.png)\n\n### Select an Instance Type\n\nA GPU instance is recommended for most deep learning purposes. Training new models will be faster on a GPU instance than a CPU instance. Multi-GPU instances or distributed training across multiple instances with GPUs can offer sub-linear scaling. To set up distributed training, see [Distributed Training](https://docs.aws.amazon.com/dlami/latest/devguide/distributed-training.html).\n\n**Note:** The size of your model should be a factor in selecting an instance. If your model exceeds an instance's available RAM, select a different instance type with enough memory for your application.\n\nRefer to [EC2 Instance Types](https://aws.amazon.com/ec2/instance-types/) and choose Accelerated Computing to see the different GPU instance options.\n\n![Choose Type](https://user-images.githubusercontent.com/26833433/106324624-52141e80-622e-11eb-9662-1a376d9c887d.png)\n\nFor more information on GPU monitoring and optimization, see [GPU Monitoring and Optimization](https://docs.aws.amazon.com/dlami/latest/devguide/tutorial-gpu.html). For pricing, see [On-Demand Pricing](https://aws.amazon.com/ec2/pricing/on-demand/) and [Spot Pricing](https://aws.amazon.com/ec2/spot/pricing/).\n\n### Configure Instance Details\n\nAmazon EC2 Spot Instances let you take advantage of unused EC2 capacity in the AWS cloud. Spot Instances are available at up to a 70% discount compared to On-Demand prices. We recommend a persistent spot instance, which will save your data and restart automatically when spot instance availability returns after spot instance termination. For full-price On-Demand instances, leave these settings at their default values.\n\n![Spot Request](https://user-images.githubusercontent.com/26833433/106324835-ac14e400-622e-11eb-8853-df5ec9b16dfc.png)\n\nComplete Steps 4-7 to finalize your instance hardware and security settings, and then launch the instance.\n\n## 3. Connect to Instance\n\nSelect the checkbox next to your running instance, and then click Connect. Copy and paste the SSH terminal command into a terminal of your choice to connect to your instance.\n\n![Connect](https://user-images.githubusercontent.com/26833433/106325530-cf8c5e80-622f-11eb-9f64-5b313a9d57a1.png)\n\n## 4. Run YOLOv5\n\nOnce you have logged in to your instance, clone the repository and install the dependencies in a [**Python>=3.7.0**](https://www.python.org/) environment, including [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). [Models](https://github.com/ultralytics/yolov5/tree/master/models) and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).\n\n```bash\ngit clone https://github.com/ultralytics/yolov5  # clone\ncd yolov5\npip install -r requirements.txt  # install\n```\n\nThen, start training, testing, detecting, and exporting YOLOv5 models:\n\n```bash\npython train.py  # train a model\npython val.py --weights yolov5s.pt  # validate a model for Precision, Recall, and mAP\npython detect.py --weights yolov5s.pt --source path/to/images  # run inference on images and videos\npython export.py --weights yolov5s.pt --include onnx coreml tflite  # export models to other formats\n```\n\n## Optional Extras\n\nAdd 64GB of swap memory (to `--cache` large datasets):\n\n```bash\nsudo fallocate -l 64G /swapfile\nsudo chmod 600 /swapfile\nsudo mkswap /swapfile\nsudo swapon /swapfile\nfree -h  # check memory\n```\n\nNow you have successfully set up and run YOLOv5 on an AWS Deep Learning instance. Enjoy training, testing, and deploying your object detection models!"
  },
  {
    "path": "docs/yolov5/environments/docker_image_quickstart_tutorial.md",
    "content": "---\ncomments: true\ndescription: Get started with YOLOv5 in a Docker container. Learn to set up and run YOLOv5 models and explore other quickstart options. 🚀\n---\n\n# Get Started with YOLOv5 🚀 in Docker\n\nThis tutorial will guide you through the process of setting up and running YOLOv5 in a Docker container.\n\nYou can also explore other quickstart options for YOLOv5, such as our [Colab Notebook](https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb) <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>, [GCP Deep Learning VM](https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial), and [Amazon AWS](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial). *Updated: 21 April 2023*.\n\n## Prerequisites\n\n1. **Nvidia Driver**: Version 455.23 or higher. Download from [Nvidia's website](https://www.nvidia.com/Download/index.aspx).\n2. **Nvidia-Docker**: Allows Docker to interact with your local GPU. Installation instructions are available on the [Nvidia-Docker GitHub repository](https://github.com/NVIDIA/nvidia-docker).\n3. **Docker Engine - CE**: Version 19.03 or higher. Download and installation instructions can be found on the [Docker website](https://docs.docker.com/install/).\n\n## Step 1: Pull the YOLOv5 Docker Image\n\nThe Ultralytics YOLOv5 DockerHub repository is available at [https://hub.docker.com/r/ultralytics/yolov5](https://hub.docker.com/r/ultralytics/yolov5). Docker Autobuild ensures that the `ultralytics/yolov5:latest` image is always in sync with the most recent repository commit. To pull the latest image, run the following command:\n\n```bash\nsudo docker pull ultralytics/yolov5:latest\n```\n\n## Step 2: Run the Docker Container\n\n### Basic container:\n\nRun an interactive instance of the YOLOv5 Docker image (called a \"container\") using the `-it` flag:\n\n```bash\nsudo docker run --ipc=host -it ultralytics/yolov5:latest\n```\n\n### Container with local file access:\n\nTo run a container with access to local files (e.g., COCO training data in `/datasets`), use the `-v` flag:\n\n```bash\nsudo docker run --ipc=host -it -v \"$(pwd)\"/datasets:/usr/src/datasets ultralytics/yolov5:latest\n```\n\n### Container with GPU access:\n\nTo run a container with GPU access, use the `--gpus all` flag:\n\n```bash\nsudo docker run --ipc=host -it --gpus all ultralytics/yolov5:latest\n```\n\n## Step 3: Use YOLOv5 🚀 within the Docker Container\n\nNow you can train, test, detect, and export YOLOv5 models within the running Docker container:\n\n```bash\npython train.py  # train a model\npython val.py --weights yolov5s.pt  # validate a model for Precision, Recall, and mAP\npython detect.py --weights yolov5s.pt --source path/to/images  # run inference on images and videos\npython export.py --weights yolov5s.pt --include onnx coreml tflite  # export models to other formats\n```\n\n<p align=\"center\"><img width=\"1000\" src=\"https://user-images.githubusercontent.com/26833433/142224770-6e57caaf-ac01-4719-987f-c37d1b6f401f.png\"></p>"
  },
  {
    "path": "docs/yolov5/environments/google_cloud_quickstart_tutorial.md",
    "content": "---\ncomments: true\ndescription: Set up YOLOv5 on a Google Cloud Platform (GCP) Deep Learning VM. Train, test, detect, and export YOLOv5 models. Tutorial updated April 2023.\n---\n\n# Run YOLOv5 🚀 on Google Cloud Platform (GCP) Deep Learning Virtual Machine (VM) ⭐\n\nThis tutorial will guide you through the process of setting up and running YOLOv5 on a GCP Deep Learning VM. New GCP users are eligible for a [$300 free credit offer](https://cloud.google.com/free/docs/gcp-free-tier#free-trial).\n\nYou can also explore other quickstart options for YOLOv5, such as our [Colab Notebook](https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb) <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>, [Amazon AWS](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial) and our Docker image at [Docker Hub](https://hub.docker.com/r/ultralytics/yolov5) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>. *Updated: 21 April 2023*.\n\n**Last Updated**: 6 May 2022\n\n## Step 1: Create a Deep Learning VM\n\n1. Go to the [GCP marketplace](https://console.cloud.google.com/marketplace/details/click-to-deploy-images/deeplearning) and select a **Deep Learning VM**.\n2. Choose an **n1-standard-8** instance (with 8 vCPUs and 30 GB memory).\n3. Add a GPU of your choice.\n4. Check 'Install NVIDIA GPU driver automatically on first startup?'\n5. Select a 300 GB SSD Persistent Disk for sufficient I/O speed.\n6. Click 'Deploy'.\n\nThe preinstalled [Anaconda](https://docs.anaconda.com/anaconda/packages/pkg-docs/) Python environment includes all dependencies.\n\n<img width=\"1000\" alt=\"GCP Marketplace\" src=\"https://user-images.githubusercontent.com/26833433/105811495-95863880-5f61-11eb-841d-c2f2a5aa0ffe.png\">\n\n## Step 2: Set Up the VM\n\nClone the YOLOv5 repository and install the [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a [**Python>=3.7.0**](https://www.python.org/) environment, including [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). [Models](https://github.com/ultralytics/yolov5/tree/master/models) and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) will be downloaded automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).\n\n```bash\ngit clone https://github.com/ultralytics/yolov5  # clone\ncd yolov5\npip install -r requirements.txt  # install\n```\n\n## Step 3: Run YOLOv5 🚀 on the VM\n\nYou can now train, test, detect, and export YOLOv5 models on your VM:\n\n```bash\npython train.py  # train a model\npython val.py --weights yolov5s.pt  # validate a model for Precision, Recall, and mAP\npython detect.py --weights yolov5s.pt --source path/to/images  # run inference on images and videos\npython export.py --weights yolov5s.pt --include onnx coreml tflite  # export models to other formats\n```\n\n<img width=\"1000\" alt=\"GCP terminal\" src=\"https://user-images.githubusercontent.com/26833433/142223900-275e5c9e-e2b5-43f7-a21c-35c4ca7de87c.png\">"
  },
  {
    "path": "docs/yolov5/index.md",
    "content": "---\ncomments: true\ndescription: Discover the YOLOv5 object detection model designed to deliver fast and accurate real-time results. Let's dive into this documentation to harness its full potential!\n---\n\n# Ultralytics YOLOv5\n\n<div align=\"center\">\n  <p>\n    <a href=\"https://ultralytics.com/yolov5\" target=\"_blank\">\n    <img width=\"100%\" src=\"https://raw.githubusercontent.com/ultralytics/assets/main/yolov5/v70/splash.png\"></a>\n  </p>\n\n<a href=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml\"><img src=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg\" alt=\"YOLOv5 CI\"></a>\n<a href=\"https://zenodo.org/badge/latestdoi/264818686\"><img src=\"https://zenodo.org/badge/264818686.svg\" alt=\"YOLOv5 Citation\"></a>\n<a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n<br>\n<a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a>\n<a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n<a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n<br>\n<br>\n\nWelcome to the Ultralytics YOLOv5 🚀 Docs! YOLOv5, or You Only Look Once version 5, is an Ultralytics object detection model designed to deliver fast and accurate real-time results.\n<br><br>\nThis powerful deep learning framework is built on the PyTorch platform and has gained immense popularity due to its ease of use, high performance, and versatility. In this documentation, we will guide you through the installation process, explain the model's architecture, showcase various use-cases, and provide detailed tutorials to help you harness the full potential of YOLOv5 for your computer vision projects. Let's dive in!\n\n</div>\n\n## Tutorials\n\n* [Train Custom Data](tutorials/train_custom_data.md) 🚀 RECOMMENDED\n* [Tips for Best Training Results](tutorials/tips_for_best_training_results.md) ☘️\n* [Multi-GPU Training](tutorials/multi_gpu_training.md)\n* [PyTorch Hub](tutorials/pytorch_hub_model_loading.md) 🌟 NEW\n* [TFLite, ONNX, CoreML, TensorRT Export](tutorials/model_export.md) 🚀\n* [NVIDIA Jetson platform Deployment](tutorials/running_on_jetson_nano.md) 🌟 NEW\n* [Test-Time Augmentation (TTA)](tutorials/test_time_augmentation.md)\n* [Model Ensembling](tutorials/model_ensembling.md)\n* [Model Pruning/Sparsity](tutorials/model_pruning_and_sparsity.md)\n* [Hyperparameter Evolution](tutorials/hyperparameter_evolution.md)\n* [Transfer Learning with Frozen Layers](tutorials/transfer_learning_with_frozen_layers.md)\n* [Architecture Summary](tutorials/architecture_description.md) 🌟 NEW\n* [Roboflow for Datasets, Labeling, and Active Learning](tutorials/roboflow_datasets_integration.md)\n* [ClearML Logging](tutorials/clearml_logging_integration.md) 🌟 NEW\n* [YOLOv5 with Neural Magic's Deepsparse](tutorials/neural_magic_pruning_quantization.md) 🌟 NEW\n* [Comet Logging](tutorials/comet_logging_integration.md) 🌟 NEW\n\n## Environments\n\nYOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies\nincluding [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/)\nand [PyTorch](https://pytorch.org/) preinstalled):\n\n- **Notebooks** with free\n  GPU: <a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a> <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n- **Google Cloud** Deep Learning VM.\n  See [GCP Quickstart Guide](environments/google_cloud_quickstart_tutorial.md)\n- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](environments/aws_quickstart_tutorial.md)\n- **Docker Image**.\n  See [Docker Quickstart Guide](environments/docker_image_quickstart_tutorial.md) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n\n## Status\n\n<a href=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml\"><img src=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg\" alt=\"YOLOv5 CI\"></a>\n\nIf this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous\nIntegration (CI) tests are currently passing. CI tests verify correct operation of\nYOLOv5 [training](https://github.com/ultralytics/yolov5/blob/master/train.py), [validation](https://github.com/ultralytics/yolov5/blob/master/val.py), [inference](https://github.com/ultralytics/yolov5/blob/master/detect.py), [export](https://github.com/ultralytics/yolov5/blob/master/export.py)\nand [benchmarks](https://github.com/ultralytics/yolov5/blob/master/benchmarks.py) on macOS, Windows, and Ubuntu every 24\nhours and on every commit.\n\n<br>\n<div align=\"center\">\n  <a href=\"https://github.com/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-github.png\" width=\"3%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"3%\" alt=\"\" />\n  <a href=\"https://www.linkedin.com/company/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-linkedin.png\" width=\"3%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"3%\" alt=\"\" />\n  <a href=\"https://twitter.com/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-twitter.png\" width=\"3%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"3%\" alt=\"\" />\n  <a href=\"https://youtube.com/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-youtube.png\" width=\"3%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"3%\" alt=\"\" />\n  <a href=\"https://www.tiktok.com/@ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-tiktok.png\" width=\"3%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"3%\" alt=\"\" />\n  <a href=\"https://www.instagram.com/ultralytics/\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-instagram.png\" width=\"3%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"3%\" alt=\"\" />\n  <a href=\"https://discord.gg/n6cFeSPZdD\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/blob/main/social/logo-social-discord.png\" width=\"3%\" alt=\"\" /></a>\n</div>"
  },
  {
    "path": "docs/yolov5/quickstart_tutorial.md",
    "content": "---\ncomments: true\ndescription: Learn how to quickly start using YOLOv5 including installation, inference, and training on this Ultralytics Docs page.\n---\n\n# YOLOv5 Quickstart\n\nSee below for quickstart examples.\n\n## Install\n\nClone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a\n[**Python>=3.7.0**](https://www.python.org/) environment, including\n[**PyTorch>=1.7**](https://pytorch.org/get-started/locally/).\n\n```bash\ngit clone https://github.com/ultralytics/yolov5  # clone\ncd yolov5\npip install -r requirements.txt  # install\n```\n\n## Inference\n\nYOLOv5 [PyTorch Hub](https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading) inference. [Models](https://github.com/ultralytics/yolov5/tree/master/models) download automatically from the latest\nYOLOv5 [release](https://github.com/ultralytics/yolov5/releases).\n\n```python\nimport torch\n\n# Model\nmodel = torch.hub.load(\"ultralytics/yolov5\", \"yolov5s\")  # or yolov5n - yolov5x6, custom\n\n# Images\nimg = \"https://ultralytics.com/images/zidane.jpg\"  # or file, Path, PIL, OpenCV, numpy, list\n\n# Inference\nresults = model(img)\n\n# Results\nresults.print()  # or .show(), .save(), .crop(), .pandas(), etc.\n```\n\n## Inference with detect.py\n\n`detect.py` runs inference on a variety of sources, downloading [models](https://github.com/ultralytics/yolov5/tree/master/models) automatically from\nthe latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases) and saving results to `runs/detect`.\n\n```bash\npython detect.py --weights yolov5s.pt --source 0                               # webcam\n                                               img.jpg                         # image\n                                               vid.mp4                         # video\n                                               screen                          # screenshot\n                                               path/                           # directory\n                                               list.txt                        # list of images\n                                               list.streams                    # list of streams\n                                               'path/*.jpg'                    # glob\n                                               'https://youtu.be/Zgi9g1ksQHc'  # YouTube\n                                               'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP stream\n```\n\n## Training\n\nThe commands below reproduce YOLOv5 [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh)\nresults. [Models](https://github.com/ultralytics/yolov5/tree/master/models)\nand [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest\nYOLOv5 [release](https://github.com/ultralytics/yolov5/releases). Training times for YOLOv5n/s/m/l/x are\n1/2/4/6/8 days on a V100 GPU ([Multi-GPU](https://docs.ultralytics.com/yolov5/tutorials/multi_gpu_training) times faster). Use the\nlargest `--batch-size` possible, or pass `--batch-size -1` for\nYOLOv5 [AutoBatch](https://github.com/ultralytics/yolov5/pull/5092). Batch sizes shown for V100-16GB.\n\n```bash\npython train.py --data coco.yaml --epochs 300 --weights '' --cfg yolov5n.yaml  --batch-size 128\n                                                                 yolov5s                    64\n                                                                 yolov5m                    40\n                                                                 yolov5l                    24\n                                                                 yolov5x                    16\n```\n\n<img width=\"800\" src=\"https://user-images.githubusercontent.com/26833433/90222759-949d8800-ddc1-11ea-9fa1-1c97eed2b963.png\">"
  },
  {
    "path": "docs/yolov5/tutorials/architecture_description.md",
    "content": "---\ncomments: true\ndescription: 'Ultralytics YOLOv5 Docs: Learn model structure, data augmentation &amp; training strategies. Build targets and the losses of object detection.'\n---\n\n## 1. Model Structure\n\nYOLOv5 (v6.0/6.1) consists of:\n\n- **Backbone**: `New CSP-Darknet53`\n- **Neck**: `SPPF`, `New CSP-PAN`\n- **Head**: `YOLOv3 Head`\n\nModel structure (`yolov5l.yaml`):\n\n![yolov5](https://user-images.githubusercontent.com/31005897/172404576-c260dcf9-76bb-4bc8-b6a9-f2d987792583.png)\n\nSome minor changes compared to previous versions:\n\n1. Replace the `Focus` structure with `6x6 Conv2d`(more efficient, refer #4825)\n2. Replace the `SPP` structure with `SPPF`(more than double the speed)\n\n<details markdown>\n<summary>test code</summary>\n\n```python\nimport time\nimport torch\nimport torch.nn as nn\n\n\nclass SPP(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.maxpool1 = nn.MaxPool2d(5, 1, padding=2)\n        self.maxpool2 = nn.MaxPool2d(9, 1, padding=4)\n        self.maxpool3 = nn.MaxPool2d(13, 1, padding=6)\n\n    def forward(self, x):\n        o1 = self.maxpool1(x)\n        o2 = self.maxpool2(x)\n        o3 = self.maxpool3(x)\n        return torch.cat([x, o1, o2, o3], dim=1)\n\n\nclass SPPF(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.maxpool = nn.MaxPool2d(5, 1, padding=2)\n\n    def forward(self, x):\n        o1 = self.maxpool(x)\n        o2 = self.maxpool(o1)\n        o3 = self.maxpool(o2)\n        return torch.cat([x, o1, o2, o3], dim=1)\n\n\ndef main():\n    input_tensor = torch.rand(8, 32, 16, 16)\n    spp = SPP()\n    sppf = SPPF()\n    output1 = spp(input_tensor)\n    output2 = sppf(input_tensor)\n\n    print(torch.equal(output1, output2))\n\n    t_start = time.time()\n    for _ in range(100):\n        spp(input_tensor)\n    print(f\"spp time: {time.time() - t_start}\")\n\n    t_start = time.time()\n    for _ in range(100):\n        sppf(input_tensor)\n    print(f\"sppf time: {time.time() - t_start}\")\n\n\nif __name__ == '__main__':\n    main()\n```\n\nresult:\n\n```\nTrue\nspp time: 0.5373051166534424\nsppf time: 0.20780706405639648\n```\n\n</details>\n\n## 2. Data Augmentation\n\n- Mosaic\n  <img src=\"https://user-images.githubusercontent.com/31005897/159109235-c7aad8f2-1d4f-41f9-8d5f-b2fde6f2885e.png#pic_center\" width=80%>\n\n- Copy paste\n  <img src=\"https://user-images.githubusercontent.com/31005897/159116277-91b45033-6bec-4f82-afc4-41138866628e.png#pic_center\" width=80%>\n\n- Random affine(Rotation, Scale, Translation and Shear)\n  <img src=\"https://user-images.githubusercontent.com/31005897/159109326-45cd5acb-14fa-43e7-9235-0f21b0021c7d.png#pic_center\" width=80%>\n\n- MixUp\n  <img src=\"https://user-images.githubusercontent.com/31005897/159109361-3b24333b-f481-478b-ae00-df7838f0b5cd.png#pic_center\" width=80%>\n\n- Albumentations\n- Augment HSV(Hue, Saturation, Value)\n  <img src=\"https://user-images.githubusercontent.com/31005897/159109407-83d100ba-1aba-4f4b-aa03-4f048f815981.png#pic_center\" width=80%>\n\n- Random horizontal flip\n  <img src=\"https://user-images.githubusercontent.com/31005897/159109429-0d44619a-a76a-49eb-bfc0-6709860c043e.png#pic_center\" width=80%>\n\n## 3. Training Strategies\n\n- Multi-scale training(0.5~1.5x)\n- AutoAnchor(For training custom data)\n- Warmup and Cosine LR scheduler\n- EMA(Exponential Moving Average)\n- Mixed precision\n- Evolve hyper-parameters\n\n## 4. Others\n\n### 4.1 Compute Losses\n\nThe YOLOv5 loss consists of three parts:\n\n- Classes loss(BCE loss)\n- Objectness loss(BCE loss)\n- Location loss(CIoU loss)\n\n![loss](https://latex.codecogs.com/svg.image?Loss=\\lambda_1L_{cls}+\\lambda_2L_{obj}+\\lambda_3L_{loc})\n\n### 4.2 Balance Losses\n\nThe objectness losses of the three prediction layers(`P3`, `P4`, `P5`) are weighted differently. The balance weights are `[4.0, 1.0, 0.4]` respectively.\n\n![obj_loss](https://latex.codecogs.com/svg.image?L_{obj}=4.0\\cdot&space;L_{obj}^{small}+1.0\\cdot&space;L_{obj}^{medium}+0.4\\cdot&space;L_{obj}^{large})\n\n### 4.3 Eliminate Grid Sensitivity\n\nIn YOLOv2 and YOLOv3, the formula for calculating the predicted target information is:\n\n![b_x](https://latex.codecogs.com/svg.image?b_x=\\sigma(t_x)+c_x)  \n![b_y](https://latex.codecogs.com/svg.image?b_y=\\sigma(t_y)+c_y)  \n![b_w](https://latex.codecogs.com/svg.image?b_w=p_w\\cdot&space;e^{t_w})  \n![b_h](https://latex.codecogs.com/svg.image?b_h=p_h\\cdot&space;e^{t_h})\n\n<img src=\"https://user-images.githubusercontent.com/31005897/158508027-8bf63c28-8290-467b-8a3e-4ad09235001a.png#pic_center\" width=40%>\n\n\n\nIn YOLOv5, the formula is:\n\n![bx](https://latex.codecogs.com/svg.image?b_x=(2\\cdot\\sigma(t_x)-0.5)+c_x)  \n![by](https://latex.codecogs.com/svg.image?b_y=(2\\cdot\\sigma(t_y)-0.5)+c_y)  \n![bw](https://latex.codecogs.com/svg.image?b_w=p_w\\cdot(2\\cdot\\sigma(t_w))^2)    \n![bh](https://latex.codecogs.com/svg.image?b_h=p_h\\cdot(2\\cdot\\sigma(t_h))^2)\n\nCompare the center point offset before and after scaling. The center point offset range is adjusted from (0, 1) to (-0.5, 1.5).\nTherefore, offset can easily get 0 or 1.\n\n<img src=\"https://user-images.githubusercontent.com/31005897/158508052-c24bc5e8-05c1-4154-ac97-2e1ec71f582e.png#pic_center\" width=40%>\n\nCompare the height and width scaling ratio(relative to anchor) before and after adjustment. The original yolo/darknet box equations have a serious flaw. Width and Height are completely unbounded as they are simply out=exp(in), which is dangerous, as it can lead to runaway gradients, instabilities, NaN losses and ultimately a complete loss of training. [refer this issue](https://github.com/ultralytics/yolov5/issues/471#issuecomment-662009779)\n\n<img src=\"https://user-images.githubusercontent.com/31005897/158508089-5ac0c7a3-6358-44b7-863e-a6e45babb842.png#pic_center\" width=40%>\n\n### 4.4 Build Targets\n\nMatch positive samples:\n\n- Calculate the aspect ratio of GT and Anchor Templates\n\n![rw](https://latex.codecogs.com/svg.image?r_w=w_{gt}/w_{at})\n\n![rh](https://latex.codecogs.com/svg.image?r_h=h_{gt}/h_{at})\n\n![rwmax](https://latex.codecogs.com/svg.image?r_w^{max}=max(r_w,1/r_w))\n\n![rhmax](https://latex.codecogs.com/svg.image?r_h^{max}=max(r_h,1/r_h))\n\n![rmax](https://latex.codecogs.com/svg.image?r^{max}=max(r_w^{max},r_h^{max}))\n\n![match](https://latex.codecogs.com/svg.image?r^{max}<{\\rm&space;anchor_t})\n\n<img src=\"https://user-images.githubusercontent.com/31005897/158508119-fbb2e483-7b8c-4975-8e1f-f510d367f8ff.png#pic_center\" width=70%>\n\n- Assign the successfully matched Anchor Templates to the corresponding cells\n\n<img src=\"https://user-images.githubusercontent.com/31005897/158508771-b6e7cab4-8de6-47f9-9abf-cdf14c275dfe.png#pic_center\" width=70%>\n\n- Because the center point offset range is adjusted from (0, 1) to (-0.5, 1.5). GT Box can be assigned to more anchors.\n\n<img src=\"https://user-images.githubusercontent.com/31005897/158508139-9db4e8c2-cf96-47e0-bc80-35d11512f296.png#pic_center\" width=70%>"
  },
  {
    "path": "docs/yolov5/tutorials/clearml_logging_integration.md",
    "content": "---\ncomments: true\ndescription: Integrate ClearML with YOLOv5 to track experiments and manage data versions. Optimize hyperparameters and remotely monitor your runs.\n---\n\n# ClearML Integration\n\n<img align=\"center\" src=\"https://github.com/thepycoder/clearml_screenshots/raw/main/logos_dark.png#gh-light-mode-only\" alt=\"Clear|ML\"><img align=\"center\" src=\"https://github.com/thepycoder/clearml_screenshots/raw/main/logos_light.png#gh-dark-mode-only\" alt=\"Clear|ML\">\n\n## About ClearML\n\n[ClearML](https://cutt.ly/yolov5-tutorial-clearml) is an [open-source](https://github.com/allegroai/clearml) toolbox designed to save you time ⏱️.\n\n🔨 Track every YOLOv5 training run in the <b>experiment manager</b>\n\n🔧 Version and easily access your custom training data with the integrated ClearML <b>Data Versioning Tool</b>\n\n🔦 <b>Remotely train and monitor</b> your YOLOv5 training runs using ClearML Agent\n\n🔬 Get the very best mAP using ClearML <b>Hyperparameter Optimization</b>\n\n🔭 Turn your newly trained <b>YOLOv5 model into an API</b> with just a few commands using ClearML Serving\n\n<br />\nAnd so much more. It's up to you how many of these tools you want to use, you can stick to the experiment manager, or chain them all together into an impressive pipeline!\n<br />\n<br />\n\n![ClearML scalars dashboard](https://github.com/thepycoder/clearml_screenshots/raw/main/experiment_manager_with_compare.gif)\n\n<br />\n<br />\n\n## 🦾 Setting Things Up\n\nTo keep track of your experiments and/or data, ClearML needs to communicate to a server. You have 2 options to get one:\n\nEither sign up for free to the [ClearML Hosted Service](https://cutt.ly/yolov5-tutorial-clearml) or you can set up your own server, see [here](https://clear.ml/docs/latest/docs/deploying_clearml/clearml_server). Even the server is open-source, so even if you're dealing with sensitive data, you should be good to go!\n\n1. Install the `clearml` python package:\n\n   ```bash\n   pip install clearml\n   ```\n\n2. Connect the ClearML SDK to the server by [creating credentials](https://app.clear.ml/settings/workspace-configuration) (go right top to Settings -> Workspace -> Create new credentials), then execute the command below and follow the instructions:\n\n   ```bash\n   clearml-init\n   ```\n\nThat's it! You're done 😎\n\n<br />\n\n## 🚀 Training YOLOv5 With ClearML\n\nTo enable ClearML experiment tracking, simply install the ClearML pip package.\n\n```bash\npip install clearml>=1.2.0\n```\n\nThis will enable integration with the YOLOv5 training script. Every training run from now on, will be captured and stored by the ClearML experiment manager.\n\nIf you want to change the `project_name` or `task_name`, use the `--project` and `--name` arguments of the `train.py` script, by default the project will be called `YOLOv5` and the task `Training`.\nPLEASE NOTE: ClearML uses `/` as a delimiter for subprojects, so be careful when using `/` in your project name!\n\n```bash\npython train.py --img 640 --batch 16 --epochs 3 --data coco128.yaml --weights yolov5s.pt --cache\n```\n\nor with custom project and task name:\n\n```bash\npython train.py --project my_project --name my_training --img 640 --batch 16 --epochs 3 --data coco128.yaml --weights yolov5s.pt --cache\n```\n\nThis will capture:\n\n- Source code + uncommitted changes\n- Installed packages\n- (Hyper)parameters\n- Model files (use `--save-period n` to save a checkpoint every n epochs)\n- Console output\n- Scalars (mAP_0.5, mAP_0.5:0.95, precision, recall, losses, learning rates, ...)\n- General info such as machine details, runtime, creation date etc.\n- All produced plots such as label correlogram and confusion matrix\n- Images with bounding boxes per epoch\n- Mosaic per epoch\n- Validation images per epoch\n- ...\n\nThat's a lot right? 🤯\nNow, we can visualize all of this information in the ClearML UI to get an overview of our training progress. Add custom columns to the table view (such as e.g. mAP_0.5) so you can easily sort on the best performing model. Or select multiple experiments and directly compare them!\n\nThere even more we can do with all of this information, like hyperparameter optimization and remote execution, so keep reading if you want to see how that works!\n\n<br />\n\n## 🔗 Dataset Version Management\n\nVersioning your data separately from your code is generally a good idea and makes it easy to acquire the latest version too. This repository supports supplying a dataset version ID, and it will make sure to get the data if it's not there yet. Next to that, this workflow also saves the used dataset ID as part of the task parameters, so you will always know for sure which data was used in which experiment!\n\n![ClearML Dataset Interface](https://github.com/thepycoder/clearml_screenshots/raw/main/clearml_data.gif)\n\n### Prepare Your Dataset\n\nThe YOLOv5 repository supports a number of different datasets by using yaml files containing their information. By default datasets are downloaded to the `../datasets` folder in relation to the repository root folder. So if you downloaded the `coco128` dataset using the link in the yaml or with the scripts provided by yolov5, you get this folder structure:\n\n```\n..\n|_ yolov5\n|_ datasets\n    |_ coco128\n        |_ images\n        |_ labels\n        |_ LICENSE\n        |_ README.txt\n```\n\nBut this can be any dataset you wish. Feel free to use your own, as long as you keep to this folder structure.\n\nNext, ⚠️**copy the corresponding yaml file to the root of the dataset folder**⚠️. This yaml files contains the information ClearML will need to properly use the dataset. You can make this yourself too, of course, just follow the structure of the example yamls.\n\nBasically we need the following keys: `path`, `train`, `test`, `val`, `nc`, `names`.\n\n```\n..\n|_ yolov5\n|_ datasets\n    |_ coco128\n        |_ images\n        |_ labels\n        |_ coco128.yaml  # <---- HERE!\n        |_ LICENSE\n        |_ README.txt\n```\n\n### Upload Your Dataset\n\nTo get this dataset into ClearML as a versioned dataset, go to the dataset root folder and run the following command:\n\n```bash\ncd coco128\nclearml-data sync --project YOLOv5 --name coco128 --folder .\n```\n\nThe command `clearml-data sync` is actually a shorthand command. You could also run these commands one after the other:\n\n```bash\n# Optionally add --parent <parent_dataset_id> if you want to base\n# this version on another dataset version, so no duplicate files are uploaded!\nclearml-data create --name coco128 --project YOLOv5\nclearml-data add --files .\nclearml-data close\n```\n\n### Run Training Using A ClearML Dataset\n\nNow that you have a ClearML dataset, you can very simply use it to train custom YOLOv5 🚀 models!\n\n```bash\npython train.py --img 640 --batch 16 --epochs 3 --data clearml://<your_dataset_id> --weights yolov5s.pt --cache\n```\n\n<br />\n\n## 👀 Hyperparameter Optimization\n\nNow that we have our experiments and data versioned, it's time to take a look at what we can build on top!\n\nUsing the code information, installed packages and environment details, the experiment itself is now **completely reproducible**. In fact, ClearML allows you to clone an experiment and even change its parameters. We can then just rerun it with these new parameters automatically, this is basically what HPO does!\n\nTo **run hyperparameter optimization locally**, we've included a pre-made script for you. Just make sure a training task has been run at least once, so it is in the ClearML experiment manager, we will essentially clone it and change its hyperparameters.\n\nYou'll need to fill in the ID of this `template task` in the script found at `utils/loggers/clearml/hpo.py` and then just run it :) You can change `task.execute_locally()` to `task.execute()` to put it in a ClearML queue and have a remote agent work on it instead.\n\n```bash\n# To use optuna, install it first, otherwise you can change the optimizer to just be RandomSearch\npip install optuna\npython utils/loggers/clearml/hpo.py\n```\n\n![HPO](https://github.com/thepycoder/clearml_screenshots/raw/main/hpo.png)\n\n## 🤯 Remote Execution (advanced)\n\nRunning HPO locally is really handy, but what if we want to run our experiments on a remote machine instead? Maybe you have access to a very powerful GPU machine on-site, or you have some budget to use cloud GPUs.\nThis is where the ClearML Agent comes into play. Check out what the agent can do here:\n\n- [YouTube video](https://youtu.be/MX3BrXnaULs)\n- [Documentation](https://clear.ml/docs/latest/docs/clearml_agent)\n\nIn short: every experiment tracked by the experiment manager contains enough information to reproduce it on a different machine (installed packages, uncommitted changes etc.). So a ClearML agent does just that: it listens to a queue for incoming tasks and when it finds one, it recreates the environment and runs it while still reporting scalars, plots etc. to the experiment manager.\n\nYou can turn any machine (a cloud VM, a local GPU machine, your own laptop ... ) into a ClearML agent by simply running:\n\n```bash\nclearml-agent daemon --queue <queues_to_listen_to> [--docker]\n```\n\n### Cloning, Editing And Enqueuing\n\nWith our agent running, we can give it some work. Remember from the HPO section that we can clone a task and edit the hyperparameters? We can do that from the interface too!\n\n🪄 Clone the experiment by right-clicking it\n\n🎯 Edit the hyperparameters to what you wish them to be\n\n⏳ Enqueue the task to any of the queues by right-clicking it\n\n![Enqueue a task from the UI](https://github.com/thepycoder/clearml_screenshots/raw/main/enqueue.gif)\n\n### Executing A Task Remotely\n\nNow you can clone a task like we explained above, or simply mark your current script by adding `task.execute_remotely()` and on execution it will be put into a queue, for the agent to start working on!\n\nTo run the YOLOv5 training script remotely, all you have to do is add this line to the training.py script after the clearml logger has been instantiated:\n\n```python\n# ...\n# Loggers\ndata_dict = None\nif RANK in {-1, 0}:\n    loggers = Loggers(save_dir, weights, opt, hyp, LOGGER)  # loggers instance\n    if loggers.clearml:\n        loggers.clearml.task.execute_remotely(queue=\"my_queue\")  # <------ ADD THIS LINE\n        # Data_dict is either None is user did not choose for ClearML dataset or is filled in by ClearML\n        data_dict = loggers.clearml.data_dict\n# ...\n```\n\nWhen running the training script after this change, python will run the script up until that line, after which it will package the code and send it to the queue instead!\n\n### Autoscaling workers\n\nClearML comes with autoscalers too! This tool will automatically spin up new remote machines in the cloud of your choice (AWS, GCP, Azure) and turn them into ClearML agents for you whenever there are experiments detected in the queue. Once the tasks are processed, the autoscaler will automatically shut down the remote machines, and you stop paying!\n\nCheck out the autoscalers getting started video below.\n\n[![Watch the video](https://img.youtube.com/vi/j4XVMAaUt3E/0.jpg)](https://youtu.be/j4XVMAaUt3E)"
  },
  {
    "path": "docs/yolov5/tutorials/comet_logging_integration.md",
    "content": "---\ncomments: true\ndescription: Learn how to use YOLOv5 with Comet, a tool for logging and visualizing machine learning model metrics in real-time. Install, log and analyze seamlessly.\n---\n\n<img src=\"https://cdn.comet.ml/img/notebook_logo.png\">\n\n# YOLOv5 with Comet\n\nThis guide will cover how to use YOLOv5 with [Comet](https://bit.ly/yolov5-readme-comet2)\n\n# About Comet\n\nComet builds tools that help data scientists, engineers, and team leaders accelerate and optimize machine learning and deep learning models.\n\nTrack and visualize model metrics in real time, save your hyperparameters, datasets, and model checkpoints, and visualize your model predictions with [Comet Custom Panels](https://www.comet.com/docs/v2/guides/comet-dashboard/code-panels/about-panels/?utm_source=yolov5&utm_medium=partner&utm_campaign=partner_yolov5_2022&utm_content=github)!\nComet makes sure you never lose track of your work and makes it easy to share results and collaborate across teams of all sizes!\n\n# Getting Started\n\n## Install Comet\n\n```shell\npip install comet_ml\n```\n\n## Configure Comet Credentials\n\nThere are two ways to configure Comet with YOLOv5.\n\nYou can either set your credentials through environment variables\n\n**Environment Variables**\n\n```shell\nexport COMET_API_KEY=<Your Comet API Key>\nexport COMET_PROJECT_NAME=<Your Comet Project Name> # This will default to 'yolov5'\n```\n\nOr create a `.comet.config` file in your working directory and set your credentials there.\n\n**Comet Configuration File**\n\n```\n[comet]\napi_key=<Your Comet API Key>\nproject_name=<Your Comet Project Name> # This will default to 'yolov5'\n```\n\n## Run the Training Script\n\n```shell\n# Train YOLOv5s on COCO128 for 5 epochs\npython train.py --img 640 --batch 16 --epochs 5 --data coco128.yaml --weights yolov5s.pt\n```\n\nThat's it! Comet will automatically log your hyperparameters, command line arguments, training and validation metrics. You can visualize and analyze your runs in the Comet UI\n\n<img width=\"1920\" alt=\"yolo-ui\" src=\"https://user-images.githubusercontent.com/26833433/202851203-164e94e1-2238-46dd-91f8-de020e9d6b41.png\">\n\n# Try out an Example!\n\nCheck out an example of a [completed run here](https://www.comet.com/examples/comet-example-yolov5/a0e29e0e9b984e4a822db2a62d0cb357?experiment-tab=chart&showOutliers=true&smoothing=0&transformY=smoothing&xAxis=step&utm_source=yolov5&utm_medium=partner&utm_campaign=partner_yolov5_2022&utm_content=github)\n\nOr better yet, try it out yourself in this Colab Notebook\n\n[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1RG0WOQyxlDlo5Km8GogJpIEJlg_5lyYO?usp=sharing)\n\n# Log automatically\n\nBy default, Comet will log the following items\n\n## Metrics\n\n- Box Loss, Object Loss, Classification Loss for the training and validation data\n- mAP_0.5, mAP_0.5:0.95 metrics for the validation data.\n- Precision and Recall for the validation data\n\n## Parameters\n\n- Model Hyperparameters\n- All parameters passed through the command line options\n\n## Visualizations\n\n- Confusion Matrix of the model predictions on the validation data\n- Plots for the PR and F1 curves across all classes\n- Correlogram of the Class Labels\n\n# Configure Comet Logging\n\nComet can be configured to log additional data either through command line flags passed to the training script\nor through environment variables.\n\n```shell\nexport COMET_MODE=online # Set whether to run Comet in 'online' or 'offline' mode. Defaults to online\nexport COMET_MODEL_NAME=<your model name> #Set the name for the saved model. Defaults to yolov5\nexport COMET_LOG_CONFUSION_MATRIX=false # Set to disable logging a Comet Confusion Matrix. Defaults to true\nexport COMET_MAX_IMAGE_UPLOADS=<number of allowed images to upload to Comet> # Controls how many total image predictions to log to Comet. Defaults to 100.\nexport COMET_LOG_PER_CLASS_METRICS=true # Set to log evaluation metrics for each detected class at the end of training. Defaults to false\nexport COMET_DEFAULT_CHECKPOINT_FILENAME=<your checkpoint filename> # Set this if you would like to resume training from a different checkpoint. Defaults to 'last.pt'\nexport COMET_LOG_BATCH_LEVEL_METRICS=true # Set this if you would like to log training metrics at the batch level. Defaults to false.\nexport COMET_LOG_PREDICTIONS=true # Set this to false to disable logging model predictions\n```\n\n## Logging Checkpoints with Comet\n\nLogging Models to Comet is disabled by default. To enable it, pass the `save-period` argument to the training script. This will save the\nlogged checkpoints to Comet based on the interval value provided by `save-period`\n\n```shell\npython train.py \\\n--img 640 \\\n--batch 16 \\\n--epochs 5 \\\n--data coco128.yaml \\\n--weights yolov5s.pt \\\n--save-period 1\n```\n\n## Logging Model Predictions\n\nBy default, model predictions (images, ground truth labels and bounding boxes) will be logged to Comet.\n\nYou can control the frequency of logged predictions and the associated images by passing the `bbox_interval` command line argument. Predictions can be visualized using Comet's Object Detection Custom Panel. This frequency corresponds to every Nth batch of data per epoch. In the example below, we are logging every 2nd batch of data for each epoch.\n\n**Note:** The YOLOv5 validation dataloader will default to a batch size of 32, so you will have to set the logging frequency accordingly.\n\nHere is an [example project using the Panel](https://www.comet.com/examples/comet-example-yolov5?shareable=YcwMiJaZSXfcEXpGOHDD12vA1&utm_source=yolov5&utm_medium=partner&utm_campaign=partner_yolov5_2022&utm_content=github)\n\n```shell\npython train.py \\\n--img 640 \\\n--batch 16 \\\n--epochs 5 \\\n--data coco128.yaml \\\n--weights yolov5s.pt \\\n--bbox_interval 2\n```\n\n### Controlling the number of Prediction Images logged to Comet\n\nWhen logging predictions from YOLOv5, Comet will log the images associated with each set of predictions. By default a maximum of 100 validation images are logged. You can increase or decrease this number using the `COMET_MAX_IMAGE_UPLOADS` environment variable.\n\n```shell\nenv COMET_MAX_IMAGE_UPLOADS=200 python train.py \\\n--img 640 \\\n--batch 16 \\\n--epochs 5 \\\n--data coco128.yaml \\\n--weights yolov5s.pt \\\n--bbox_interval 1\n```\n\n### Logging Class Level Metrics\n\nUse the `COMET_LOG_PER_CLASS_METRICS` environment variable to log mAP, precision, recall, f1 for each class.\n\n```shell\nenv COMET_LOG_PER_CLASS_METRICS=true python train.py \\\n--img 640 \\\n--batch 16 \\\n--epochs 5 \\\n--data coco128.yaml \\\n--weights yolov5s.pt\n```\n\n## Uploading a Dataset to Comet Artifacts\n\nIf you would like to store your data using [Comet Artifacts](https://www.comet.com/docs/v2/guides/data-management/using-artifacts/#learn-more?utm_source=yolov5&utm_medium=partner&utm_campaign=partner_yolov5_2022&utm_content=github), you can do so using the `upload_dataset` flag.\n\nThe dataset be organized in the way described in the [YOLOv5 documentation](train_custom_data.md). The dataset config `yaml` file must follow the same format as that of the `coco128.yaml` file.\n\n```shell\npython train.py \\\n--img 640 \\\n--batch 16 \\\n--epochs 5 \\\n--data coco128.yaml \\\n--weights yolov5s.pt \\\n--upload_dataset\n```\n\nYou can find the uploaded dataset in the Artifacts tab in your Comet Workspace\n<img width=\"1073\" alt=\"artifact-1\" src=\"https://user-images.githubusercontent.com/7529846/186929193-162718bf-ec7b-4eb9-8c3b-86b3763ef8ea.png\">\n\nYou can preview the data directly in the Comet UI.\n<img width=\"1082\" alt=\"artifact-2\" src=\"https://user-images.githubusercontent.com/7529846/186929215-432c36a9-c109-4eb0-944b-84c2786590d6.png\">\n\nArtifacts are versioned and also support adding metadata about the dataset. Comet will automatically log the metadata from your dataset `yaml` file\n<img width=\"963\" alt=\"artifact-3\" src=\"https://user-images.githubusercontent.com/7529846/186929256-9d44d6eb-1a19-42de-889a-bcbca3018f2e.png\">\n\n### Using a saved Artifact\n\nIf you would like to use a dataset from Comet Artifacts, set the `path` variable in your dataset `yaml` file to point to the following Artifact resource URL.\n\n```\n# contents of artifact.yaml file\npath: \"comet://<workspace name>/<artifact name>:<artifact version or alias>\"\n```\n\nThen pass this file to your training script in the following way\n\n```shell\npython train.py \\\n--img 640 \\\n--batch 16 \\\n--epochs 5 \\\n--data artifact.yaml \\\n--weights yolov5s.pt\n```\n\nArtifacts also allow you to track the lineage of data as it flows through your Experimentation workflow. Here you can see a graph that shows you all the experiments that have used your uploaded dataset.\n<img width=\"1391\" alt=\"artifact-4\" src=\"https://user-images.githubusercontent.com/7529846/186929264-4c4014fa-fe51-4f3c-a5c5-f6d24649b1b4.png\">\n\n## Resuming a Training Run\n\nIf your training run is interrupted for any reason, e.g. disrupted internet connection, you can resume the run using the `resume` flag and the Comet Run Path.\n\nThe Run Path has the following format `comet://<your workspace name>/<your project name>/<experiment id>`.\n\nThis will restore the run to its state before the interruption, which includes restoring the model from a checkpoint, restoring all hyperparameters and training arguments and downloading Comet dataset Artifacts if they were used in the original run. The resumed run will continue logging to the existing Experiment in the Comet UI\n\n```shell\npython train.py \\\n--resume \"comet://<your run path>\"\n```\n\n## Hyperparameter Search with the Comet Optimizer\n\nYOLOv5 is also integrated with Comet's Optimizer, making is simple to visualize hyperparameter sweeps in the Comet UI.\n\n### Configuring an Optimizer Sweep\n\nTo configure the Comet Optimizer, you will have to create a JSON file with the information about the sweep. An example file has been provided in `utils/loggers/comet/optimizer_config.json`\n\n```shell\npython utils/loggers/comet/hpo.py \\\n  --comet_optimizer_config \"utils/loggers/comet/optimizer_config.json\"\n```\n\nThe `hpo.py` script accepts the same arguments as `train.py`. If you wish to pass additional arguments to your sweep simply add them after\nthe script.\n\n```shell\npython utils/loggers/comet/hpo.py \\\n  --comet_optimizer_config \"utils/loggers/comet/optimizer_config.json\" \\\n  --save-period 1 \\\n  --bbox_interval 1\n```\n\n### Running a Sweep in Parallel\n\n```shell\ncomet optimizer -j <set number of workers> utils/loggers/comet/hpo.py \\\n  utils/loggers/comet/optimizer_config.json\"\n```\n\n### Visualizing Results\n\nComet provides a number of ways to visualize the results of your sweep. Take a look at a [project with a completed sweep here](https://www.comet.com/examples/comet-example-yolov5/view/PrlArHGuuhDTKC1UuBmTtOSXD/panels?utm_source=yolov5&utm_medium=partner&utm_campaign=partner_yolov5_2022&utm_content=github)\n\n<img width=\"1626\" alt=\"hyperparameter-yolo\" src=\"https://user-images.githubusercontent.com/7529846/186914869-7dc1de14-583f-4323-967b-c9a66a29e495.png\">"
  },
  {
    "path": "docs/yolov5/tutorials/hyperparameter_evolution.md",
    "content": "---\ncomments: true\ndescription: Learn to find optimum YOLOv5 hyperparameters via **evolution**. A guide to learn hyperparameter tuning with Genetic Algorithms.\n---\n\n📚 This guide explains **hyperparameter evolution** for YOLOv5 🚀. Hyperparameter evolution is a method of [Hyperparameter Optimization](https://en.wikipedia.org/wiki/Hyperparameter_optimization) using a [Genetic Algorithm](https://en.wikipedia.org/wiki/Genetic_algorithm) (GA) for optimization. UPDATED 25 September 2022.\n\nHyperparameters in ML control various aspects of training, and finding optimal values for them can be a challenge. Traditional methods like grid searches can quickly become intractable due to 1) the high dimensional search space 2) unknown correlations among the dimensions, and 3) expensive nature of evaluating the fitness at each point, making GA a suitable candidate for hyperparameter searches.\n\n## Before You Start\n\nClone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a [**Python>=3.7.0**](https://www.python.org/) environment, including [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). [Models](https://github.com/ultralytics/yolov5/tree/master/models) and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).\n\n```bash\ngit clone https://github.com/ultralytics/yolov5  # clone\ncd yolov5\npip install -r requirements.txt  # install\n```\n\n## 1. Initialize Hyperparameters\n\nYOLOv5 has about 30 hyperparameters used for various training settings. These are defined in `*.yaml` files in the `/data/hyps` directory. Better initial guesses will produce better final results, so it is important to initialize these values properly before evolving. If in doubt, simply use the default values, which are optimized for YOLOv5 COCO training from scratch.\n\n```yaml\n# YOLOv5 🚀 by Ultralytics, AGPL-3.0 license\n# Hyperparameters for low-augmentation COCO training from scratch\n# python train.py --batch 64 --cfg yolov5n6.yaml --weights '' --data coco.yaml --img 640 --epochs 300 --linear\n# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials\n\nlr0: 0.01  # initial learning rate (SGD=1E-2, Adam=1E-3)\nlrf: 0.01  # final OneCycleLR learning rate (lr0 * lrf)\nmomentum: 0.937  # SGD momentum/Adam beta1\nweight_decay: 0.0005  # optimizer weight decay 5e-4\nwarmup_epochs: 3.0  # warmup epochs (fractions ok)\nwarmup_momentum: 0.8  # warmup initial momentum\nwarmup_bias_lr: 0.1  # warmup initial bias lr\nbox: 0.05  # box loss gain\ncls: 0.5  # cls loss gain\ncls_pw: 1.0  # cls BCELoss positive_weight\nobj: 1.0  # obj loss gain (scale with pixels)\nobj_pw: 1.0  # obj BCELoss positive_weight\niou_t: 0.20  # IoU training threshold\nanchor_t: 4.0  # anchor-multiple threshold\n# anchors: 3  # anchors per output layer (0 to ignore)\nfl_gamma: 0.0  # focal loss gamma (efficientDet default gamma=1.5)\nhsv_h: 0.015  # image HSV-Hue augmentation (fraction)\nhsv_s: 0.7  # image HSV-Saturation augmentation (fraction)\nhsv_v: 0.4  # image HSV-Value augmentation (fraction)\ndegrees: 0.0  # image rotation (+/- deg)\ntranslate: 0.1  # image translation (+/- fraction)\nscale: 0.5  # image scale (+/- gain)\nshear: 0.0  # image shear (+/- deg)\nperspective: 0.0  # image perspective (+/- fraction), range 0-0.001\nflipud: 0.0  # image flip up-down (probability)\nfliplr: 0.5  # image flip left-right (probability)\nmosaic: 1.0  # image mosaic (probability)\nmixup: 0.0  # image mixup (probability)\ncopy_paste: 0.0  # segment copy-paste (probability)\n```\n\n## 2. Define Fitness\n\nFitness is the value we seek to maximize. In YOLOv5 we define a default fitness function as a weighted combination of metrics: `mAP@0.5` contributes 10% of the weight and `mAP@0.5:0.95` contributes the remaining 90%, with [Precision `P` and Recall `R`](https://en.wikipedia.org/wiki/Precision_and_recall) absent. You may adjust these as you see fit or use the default fitness definition in utils/metrics.py (recommended).\n\n```python\ndef fitness(x): \n    # Model fitness as a weighted combination of metrics \n    w = [0.0, 0.0, 0.1, 0.9]  # weights for [P, R, mAP@0.5, mAP@0.5:0.95] \n    return (x[:, :4] * w).sum(1) \n```\n\n## 3. Evolve\n\nEvolution is performed about a base scenario which we seek to improve upon. The base scenario in this example is finetuning COCO128 for 10 epochs using pretrained YOLOv5s. The base scenario training command is:\n\n```bash\npython train.py --epochs 10 --data coco128.yaml --weights yolov5s.pt --cache\n```\n\nTo evolve hyperparameters **specific to this scenario**, starting from our initial values defined in **Section 1.**, and maximizing the fitness defined in **Section 2.**, append `--evolve`:\n\n```bash\n# Single-GPU\npython train.py --epochs 10 --data coco128.yaml --weights yolov5s.pt --cache --evolve\n\n# Multi-GPU\nfor i in 0 1 2 3 4 5 6 7; do\n  sleep $(expr 30 \\* $i) &&  # 30-second delay (optional)\n  echo 'Starting GPU '$i'...' &&\n  nohup python train.py --epochs 10 --data coco128.yaml --weights yolov5s.pt --cache --device $i --evolve > evolve_gpu_$i.log &\ndone\n\n# Multi-GPU bash-while (not recommended)\nfor i in 0 1 2 3 4 5 6 7; do\n  sleep $(expr 30 \\* $i) &&  # 30-second delay (optional)\n  echo 'Starting GPU '$i'...' &&\n  \"$(while true; do nohup python train.py... --device $i --evolve 1 > evolve_gpu_$i.log; done)\" &\ndone\n```\n\nThe default evolution settings will run the base scenario 300 times, i.e. for 300 generations. You can modify generations via the `--evolve` argument, i.e. `python train.py --evolve 1000`.\nhttps://github.com/ultralytics/yolov5/blob/6a3ee7cf03efb17fbffde0e68b1a854e80fe3213/train.py#L608\n\nThe main genetic operators are **crossover** and **mutation**. In this work mutation is used, with an 80% probability and a 0.04 variance to create new offspring based on a combination of the best parents from all previous generations. Results are logged to `runs/evolve/exp/evolve.csv`, and the highest fitness offspring is saved every generation as `runs/evolve/hyp_evolved.yaml`:\n\n```yaml\n# YOLOv5 Hyperparameter Evolution Results\n# Best generation: 287\n# Last generation: 300\n#    metrics/precision,       metrics/recall,      metrics/mAP_0.5, metrics/mAP_0.5:0.95,         val/box_loss,         val/obj_loss,         val/cls_loss\n#              0.54634,              0.55625,              0.58201,              0.33665,             0.056451,             0.042892,             0.013441\n\nlr0: 0.01  # initial learning rate (SGD=1E-2, Adam=1E-3)\nlrf: 0.2  # final OneCycleLR learning rate (lr0 * lrf)\nmomentum: 0.937  # SGD momentum/Adam beta1\nweight_decay: 0.0005  # optimizer weight decay 5e-4\nwarmup_epochs: 3.0  # warmup epochs (fractions ok)\nwarmup_momentum: 0.8  # warmup initial momentum\nwarmup_bias_lr: 0.1  # warmup initial bias lr\nbox: 0.05  # box loss gain\ncls: 0.5  # cls loss gain\ncls_pw: 1.0  # cls BCELoss positive_weight\nobj: 1.0  # obj loss gain (scale with pixels)\nobj_pw: 1.0  # obj BCELoss positive_weight\niou_t: 0.20  # IoU training threshold\nanchor_t: 4.0  # anchor-multiple threshold\n# anchors: 3  # anchors per output layer (0 to ignore)\nfl_gamma: 0.0  # focal loss gamma (efficientDet default gamma=1.5)\nhsv_h: 0.015  # image HSV-Hue augmentation (fraction)\nhsv_s: 0.7  # image HSV-Saturation augmentation (fraction)\nhsv_v: 0.4  # image HSV-Value augmentation (fraction)\ndegrees: 0.0  # image rotation (+/- deg)\ntranslate: 0.1  # image translation (+/- fraction)\nscale: 0.5  # image scale (+/- gain)\nshear: 0.0  # image shear (+/- deg)\nperspective: 0.0  # image perspective (+/- fraction), range 0-0.001\nflipud: 0.0  # image flip up-down (probability)\nfliplr: 0.5  # image flip left-right (probability)\nmosaic: 1.0  # image mosaic (probability)\nmixup: 0.0  # image mixup (probability)\ncopy_paste: 0.0  # segment copy-paste (probability)\n```\n\nWe recommend a minimum of 300 generations of evolution for best results. Note that **evolution is generally expensive and time-consuming**, as the base scenario is trained hundreds of times, possibly requiring hundreds or thousands of GPU hours.\n\n## 4. Visualize\n\n`evolve.csv` is plotted as `evolve.png` by `utils.plots.plot_evolve()` after evolution finishes with one subplot per hyperparameter showing fitness (y-axis) vs hyperparameter values (x-axis). Yellow indicates higher concentrations. Vertical distributions indicate that a parameter has been disabled and does not mutate. This is user selectable in the `meta` dictionary in train.py, and is useful for fixing parameters and preventing them from evolving.\n\n![evolve](https://user-images.githubusercontent.com/26833433/89130469-f43e8e00-d4b9-11ea-9e28-f8ae3622516d.png)\n\n## Environments\n\nYOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):\n\n- **Notebooks** with free GPU: <a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a> <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial/)\n- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/)\n- **Docker Image**. See [Docker Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/docker_image_quickstart_tutorial/) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n\n## Status\n\n<a href=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml\"><img src=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg\" alt=\"YOLOv5 CI\"></a>\n\nIf this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 [training](https://github.com/ultralytics/yolov5/blob/master/train.py), [validation](https://github.com/ultralytics/yolov5/blob/master/val.py), [inference](https://github.com/ultralytics/yolov5/blob/master/detect.py), [export](https://github.com/ultralytics/yolov5/blob/master/export.py) and [benchmarks](https://github.com/ultralytics/yolov5/blob/master/benchmarks.py) on macOS, Windows, and Ubuntu every 24 hours and on every commit."
  },
  {
    "path": "docs/yolov5/tutorials/model_ensembling.md",
    "content": "---\ncomments: true\ndescription: Learn how to ensemble YOLOv5 models for improved mAP and Recall! Clone the repo, install requirements, and start testing and inference.\n---\n\n📚 This guide explains how to use YOLOv5 🚀 **model ensembling** during testing and inference for improved mAP and Recall.  \nUPDATED 25 September 2022.\n\nFrom [https://en.wikipedia.org/wiki/Ensemble_learning](https://en.wikipedia.org/wiki/Ensemble_learning):\n> Ensemble modeling is a process where multiple diverse models are created to predict an outcome, either by using many different modeling algorithms or using different training data sets. The ensemble model then aggregates the prediction of each base model and results in once final prediction for the unseen data. The motivation for using ensemble models is to reduce the generalization error of the prediction. As long as the base models are diverse and independent, the prediction error of the model decreases when the ensemble approach is used. The approach seeks the wisdom of crowds in making a prediction. Even though the ensemble model has multiple base models within the model, it acts and performs as a single model.\n\n## Before You Start\n\nClone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a [**Python>=3.7.0**](https://www.python.org/) environment, including [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). [Models](https://github.com/ultralytics/yolov5/tree/master/models) and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).\n\n```bash\ngit clone https://github.com/ultralytics/yolov5  # clone\ncd yolov5\npip install -r requirements.txt  # install\n```\n\n## Test Normally\n\nBefore ensembling we want to establish the baseline performance of a single model. This command tests YOLOv5x on COCO val2017 at image size 640 pixels. `yolov5x.pt` is the largest and most accurate model available. Other options are `yolov5s.pt`, `yolov5m.pt` and `yolov5l.pt`, or you own checkpoint from training a custom dataset `./weights/best.pt`. For details on all available models please see our README [table](https://github.com/ultralytics/yolov5#pretrained-checkpoints).\n\n```bash\npython val.py --weights yolov5x.pt --data coco.yaml --img 640 --half\n```\n\nOutput:\n\n```shell\nval: data=./data/coco.yaml, weights=['yolov5x.pt'], batch_size=32, imgsz=640, conf_thres=0.001, iou_thres=0.65, task=val, device=, single_cls=False, augment=False, verbose=False, save_txt=False, save_hybrid=False, save_conf=False, save_json=True, project=runs/val, name=exp, exist_ok=False, half=True\nYOLOv5 🚀 v5.0-267-g6a3ee7c torch 1.9.0+cu102 CUDA:0 (Tesla P100-PCIE-16GB, 16280.875MB)\n\nFusing layers... \nModel Summary: 476 layers, 87730285 parameters, 0 gradients\n\nval: Scanning '../datasets/coco/val2017' images and labels...4952 found, 48 missing, 0 empty, 0 corrupted: 100% 5000/5000 [00:01<00:00, 2846.03it/s]\nval: New cache created: ../datasets/coco/val2017.cache\n               Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 157/157 [02:30<00:00,  1.05it/s]\n                 all       5000      36335      0.746      0.626       0.68       0.49\nSpeed: 0.1ms pre-process, 22.4ms inference, 1.4ms NMS per image at shape (32, 3, 640, 640)  # <--- baseline speed\n\nEvaluating pycocotools mAP... saving runs/val/exp/yolov5x_predictions.json...\n...\n Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.504  # <--- baseline mAP\n Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.688\n Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.546\n Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.351\n Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.551\n Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.644\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.382\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.628\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.681  # <--- baseline mAR\n Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.524\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.735\n Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.826\n```\n\n## Ensemble Test\n\nMultiple pretrained models may be ensembled together at test and inference time by simply appending extra models to the `--weights` argument in any existing val.py or detect.py command. This example tests an ensemble of 2 models together:\n\n- YOLOv5x\n- YOLOv5l6\n\n```bash\npython val.py --weights yolov5x.pt yolov5l6.pt --data coco.yaml --img 640 --half\n```\n\nOutput:\n\n```shell\nval: data=./data/coco.yaml, weights=['yolov5x.pt', 'yolov5l6.pt'], batch_size=32, imgsz=640, conf_thres=0.001, iou_thres=0.6, task=val, device=, single_cls=False, augment=False, verbose=False, save_txt=False, save_hybrid=False, save_conf=False, save_json=True, project=runs/val, name=exp, exist_ok=False, half=True\nYOLOv5 🚀 v5.0-267-g6a3ee7c torch 1.9.0+cu102 CUDA:0 (Tesla P100-PCIE-16GB, 16280.875MB)\n\nFusing layers... \nModel Summary: 476 layers, 87730285 parameters, 0 gradients  # Model 1\nFusing layers... \nModel Summary: 501 layers, 77218620 parameters, 0 gradients  # Model 2\nEnsemble created with ['yolov5x.pt', 'yolov5l6.pt']  # Ensemble notice\n\nval: Scanning '../datasets/coco/val2017.cache' images and labels... 4952 found, 48 missing, 0 empty, 0 corrupted: 100% 5000/5000 [00:00<00:00, 49695545.02it/s]\n               Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 157/157 [03:58<00:00,  1.52s/it]\n                 all       5000      36335      0.747      0.637      0.692      0.502\nSpeed: 0.1ms pre-process, 39.5ms inference, 2.0ms NMS per image at shape (32, 3, 640, 640)  # <--- ensemble speed\n\nEvaluating pycocotools mAP... saving runs/val/exp3/yolov5x_predictions.json...\n...\n Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.515  # <--- ensemble mAP\n Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.699\n Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.557\n Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.356\n Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.563\n Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.668\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.387\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.638\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.689  # <--- ensemble mAR\n Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.526\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.743\n Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.844\n```\n\n## Ensemble Inference\n\nAppend extra models to the `--weights` argument to run ensemble inference:\n\n```bash\npython detect.py --weights yolov5x.pt yolov5l6.pt --img 640 --source data/images\n```\n\nOutput:\n\n```bash\ndetect: weights=['yolov5x.pt', 'yolov5l6.pt'], source=data/images, imgsz=640, conf_thres=0.25, iou_thres=0.45, max_det=1000, device=, view_img=False, save_txt=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=False, update=False, project=runs/detect, name=exp, exist_ok=False, line_width=3, hide_labels=False, hide_conf=False, half=False\nYOLOv5 🚀 v5.0-267-g6a3ee7c torch 1.9.0+cu102 CUDA:0 (Tesla P100-PCIE-16GB, 16280.875MB)\n\nFusing layers... \nModel Summary: 476 layers, 87730285 parameters, 0 gradients\nFusing layers... \nModel Summary: 501 layers, 77218620 parameters, 0 gradients\nEnsemble created with ['yolov5x.pt', 'yolov5l6.pt']\n\nimage 1/2 /content/yolov5/data/images/bus.jpg: 640x512 4 persons, 1 bus, 1 tie, Done. (0.063s)\nimage 2/2 /content/yolov5/data/images/zidane.jpg: 384x640 3 persons, 2 ties, Done. (0.056s)\nResults saved to runs/detect/exp2\nDone. (0.223s)\n```\n\n<img src=\"https://user-images.githubusercontent.com/26833433/124489091-ea4f9a00-ddb0-11eb-8ef1-d6f335c97f6f.jpg\" width=\"500\">\n\n## Environments\n\nYOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):\n\n- **Notebooks** with free GPU: <a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a> <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial/)\n- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/)\n- **Docker Image**. See [Docker Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/docker_image_quickstart_tutorial/) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n\n## Status\n\n<a href=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml\"><img src=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg\" alt=\"YOLOv5 CI\"></a>\n\nIf this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 [training](https://github.com/ultralytics/yolov5/blob/master/train.py), [validation](https://github.com/ultralytics/yolov5/blob/master/val.py), [inference](https://github.com/ultralytics/yolov5/blob/master/detect.py), [export](https://github.com/ultralytics/yolov5/blob/master/export.py) and [benchmarks](https://github.com/ultralytics/yolov5/blob/master/benchmarks.py) on macOS, Windows, and Ubuntu every 24 hours and on every commit."
  },
  {
    "path": "docs/yolov5/tutorials/model_export.md",
    "content": "---\ncomments: true\ndescription: Export YOLOv5 models to TFLite, ONNX, CoreML, and TensorRT formats. Achieve up to 5x GPU speedup using TensorRT. Benchmarks included.\n---\n\n# TFLite, ONNX, CoreML, TensorRT Export\n\n📚 This guide explains how to export a trained YOLOv5 🚀 model from PyTorch to ONNX and TorchScript formats.  \nUPDATED 8 December 2022.\n\n## Before You Start\n\nClone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a [**Python>=3.7.0**](https://www.python.org/) environment, including [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). [Models](https://github.com/ultralytics/yolov5/tree/master/models) and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).\n\n```bash\ngit clone https://github.com/ultralytics/yolov5  # clone\ncd yolov5\npip install -r requirements.txt  # install\n```\n\nFor [TensorRT](https://developer.nvidia.com/tensorrt) export example (requires GPU) see our Colab [notebook](https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb#scrollTo=VTRwsvA9u7ln&line=2&uniqifier=1) appendix section. <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n\n## Formats\n\nYOLOv5 inference is officially supported in 11 formats:\n\n💡 ProTip: Export to ONNX or OpenVINO for up to 3x CPU speedup. See [CPU Benchmarks](https://github.com/ultralytics/yolov5/pull/6613).\n💡 ProTip: Export to TensorRT for up to 5x GPU speedup. See [GPU Benchmarks](https://github.com/ultralytics/yolov5/pull/6963).\n\n| Format                                                                     | `export.py --include` | Model                     |\n|:---------------------------------------------------------------------------|:----------------------|:--------------------------|\n| [PyTorch](https://pytorch.org/)                                            | -                     | `yolov5s.pt`              |\n| [TorchScript](https://pytorch.org/docs/stable/jit.html)                    | `torchscript`         | `yolov5s.torchscript`     |\n| [ONNX](https://onnx.ai/)                                                   | `onnx`                | `yolov5s.onnx`            |\n| [OpenVINO](https://docs.openvino.ai/latest/index.html)                     | `openvino`            | `yolov5s_openvino_model/` |\n| [TensorRT](https://developer.nvidia.com/tensorrt)                          | `engine`              | `yolov5s.engine`          |\n| [CoreML](https://github.com/apple/coremltools)                             | `coreml`              | `yolov5s.mlmodel`         |\n| [TensorFlow SavedModel](https://www.tensorflow.org/guide/saved_model)      | `saved_model`         | `yolov5s_saved_model/`    |\n| [TensorFlow GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb`                  | `yolov5s.pb`              |\n| [TensorFlow Lite](https://www.tensorflow.org/lite)                         | `tflite`              | `yolov5s.tflite`          |\n| [TensorFlow Edge TPU](https://coral.ai/docs/edgetpu/models-intro/)         | `edgetpu`             | `yolov5s_edgetpu.tflite`  |\n| [TensorFlow.js](https://www.tensorflow.org/js)                             | `tfjs`                | `yolov5s_web_model/`      |\n| [PaddlePaddle](https://github.com/PaddlePaddle)                            | `paddle`              | `yolov5s_paddle_model/`   |\n\n## Benchmarks\n\nBenchmarks below run on a Colab Pro with the YOLOv5 tutorial notebook <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>. To reproduce:\n\n```bash\npython benchmarks.py --weights yolov5s.pt --imgsz 640 --device 0\n```\n\n### Colab Pro V100 GPU\n\n```\nbenchmarks: weights=/content/yolov5/yolov5s.pt, imgsz=640, batch_size=1, data=/content/yolov5/data/coco128.yaml, device=0, half=False, test=False\nChecking setup...\nYOLOv5 🚀 v6.1-135-g7926afc torch 1.10.0+cu111 CUDA:0 (Tesla V100-SXM2-16GB, 16160MiB)\nSetup complete ✅ (8 CPUs, 51.0 GB RAM, 46.7/166.8 GB disk)\n\nBenchmarks complete (458.07s)\n                   Format  mAP@0.5:0.95  Inference time (ms)\n0                 PyTorch        0.4623                10.19\n1             TorchScript        0.4623                 6.85\n2                    ONNX        0.4623                14.63\n3                OpenVINO           NaN                  NaN\n4                TensorRT        0.4617                 1.89\n5                  CoreML           NaN                  NaN\n6   TensorFlow SavedModel        0.4623                21.28\n7     TensorFlow GraphDef        0.4623                21.22\n8         TensorFlow Lite           NaN                  NaN\n9     TensorFlow Edge TPU           NaN                  NaN\n10          TensorFlow.js           NaN                  NaN\n```\n\n### Colab Pro CPU\n\n```\nbenchmarks: weights=/content/yolov5/yolov5s.pt, imgsz=640, batch_size=1, data=/content/yolov5/data/coco128.yaml, device=cpu, half=False, test=False\nChecking setup...\nYOLOv5 🚀 v6.1-135-g7926afc torch 1.10.0+cu111 CPU\nSetup complete ✅ (8 CPUs, 51.0 GB RAM, 41.5/166.8 GB disk)\n\nBenchmarks complete (241.20s)\n                   Format  mAP@0.5:0.95  Inference time (ms)\n0                 PyTorch        0.4623               127.61\n1             TorchScript        0.4623               131.23\n2                    ONNX        0.4623                69.34\n3                OpenVINO        0.4623                66.52\n4                TensorRT           NaN                  NaN\n5                  CoreML           NaN                  NaN\n6   TensorFlow SavedModel        0.4623               123.79\n7     TensorFlow GraphDef        0.4623               121.57\n8         TensorFlow Lite        0.4623               316.61\n9     TensorFlow Edge TPU           NaN                  NaN\n10          TensorFlow.js           NaN                  NaN\n```\n\n## Export a Trained YOLOv5 Model\n\nThis command exports a pretrained YOLOv5s model to TorchScript and ONNX formats. `yolov5s.pt` is the 'small' model, the second-smallest model available. Other options are `yolov5n.pt`, `yolov5m.pt`, `yolov5l.pt` and `yolov5x.pt`, along with their P6 counterparts i.e. `yolov5s6.pt` or you own custom training checkpoint i.e. `runs/exp/weights/best.pt`. For details on all available models please see our README [table](https://github.com/ultralytics/yolov5#pretrained-checkpoints).\n\n```bash\npython export.py --weights yolov5s.pt --include torchscript onnx\n```\n\n💡 ProTip: Add `--half` to export models at FP16 half precision for smaller file sizes\n\nOutput:\n\n```bash\nexport: data=data/coco128.yaml, weights=['yolov5s.pt'], imgsz=[640, 640], batch_size=1, device=cpu, half=False, inplace=False, train=False, keras=False, optimize=False, int8=False, dynamic=False, simplify=False, opset=12, verbose=False, workspace=4, nms=False, agnostic_nms=False, topk_per_class=100, topk_all=100, iou_thres=0.45, conf_thres=0.25, include=['torchscript', 'onnx']\nYOLOv5 🚀 v6.2-104-ge3e5122 Python-3.7.13 torch-1.12.1+cu113 CPU\n\nDownloading https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5s.pt to yolov5s.pt...\n100% 14.1M/14.1M [00:00<00:00, 274MB/s]\n\nFusing layers... \nYOLOv5s summary: 213 layers, 7225885 parameters, 0 gradients\n\nPyTorch: starting from yolov5s.pt with output shape (1, 25200, 85) (14.1 MB)\n\nTorchScript: starting export with torch 1.12.1+cu113...\nTorchScript: export success ✅ 1.7s, saved as yolov5s.torchscript (28.1 MB)\n\nONNX: starting export with onnx 1.12.0...\nONNX: export success ✅ 2.3s, saved as yolov5s.onnx (28.0 MB)\n\nExport complete (5.5s)\nResults saved to /content/yolov5\nDetect:          python detect.py --weights yolov5s.onnx \nValidate:        python val.py --weights yolov5s.onnx \nPyTorch Hub:     model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s.onnx')\nVisualize:       https://netron.app/\n```\n\nThe 3 exported models will be saved alongside the original PyTorch model:\n<p align=\"center\"><img width=\"700\" src=\"https://user-images.githubusercontent.com/26833433/122827190-57a8f880-d2e4-11eb-860e-dbb7f9fc57fb.png\"></p>\n\n[Netron Viewer](https://github.com/lutzroeder/netron) is recommended for visualizing exported models:\n<p align=\"center\"><img width=\"850\" src=\"https://user-images.githubusercontent.com/26833433/191003260-f94011a7-5b2e-4fe3-93c1-e1a935e0a728.png\"></p>\n\n## Exported Model Usage Examples\n\n`detect.py` runs inference on exported models:\n\n```bash\npython detect.py --weights yolov5s.pt                 # PyTorch\n                           yolov5s.torchscript        # TorchScript\n                           yolov5s.onnx               # ONNX Runtime or OpenCV DNN with --dnn\n                           yolov5s_openvino_model     # OpenVINO\n                           yolov5s.engine             # TensorRT\n                           yolov5s.mlmodel            # CoreML (macOS only)\n                           yolov5s_saved_model        # TensorFlow SavedModel\n                           yolov5s.pb                 # TensorFlow GraphDef\n                           yolov5s.tflite             # TensorFlow Lite\n                           yolov5s_edgetpu.tflite     # TensorFlow Edge TPU\n                           yolov5s_paddle_model       # PaddlePaddle\n```\n\n`val.py` runs validation on exported models:\n\n```bash\npython val.py --weights yolov5s.pt                 # PyTorch\n                        yolov5s.torchscript        # TorchScript\n                        yolov5s.onnx               # ONNX Runtime or OpenCV DNN with --dnn\n                        yolov5s_openvino_model     # OpenVINO\n                        yolov5s.engine             # TensorRT\n                        yolov5s.mlmodel            # CoreML (macOS Only)\n                        yolov5s_saved_model        # TensorFlow SavedModel\n                        yolov5s.pb                 # TensorFlow GraphDef\n                        yolov5s.tflite             # TensorFlow Lite\n                        yolov5s_edgetpu.tflite     # TensorFlow Edge TPU\n                        yolov5s_paddle_model       # PaddlePaddle\n```\n\nUse PyTorch Hub with exported YOLOv5 models:\n\n``` python\nimport torch\n\n# Model\nmodel = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s.pt')\n                                                       'yolov5s.torchscript ')       # TorchScript\n                                                       'yolov5s.onnx')               # ONNX Runtime\n                                                       'yolov5s_openvino_model')     # OpenVINO\n                                                       'yolov5s.engine')             # TensorRT\n                                                       'yolov5s.mlmodel')            # CoreML (macOS Only)\n                                                       'yolov5s_saved_model')        # TensorFlow SavedModel\n                                                       'yolov5s.pb')                 # TensorFlow GraphDef\n                                                       'yolov5s.tflite')             # TensorFlow Lite\n                                                       'yolov5s_edgetpu.tflite')     # TensorFlow Edge TPU\n                                                       'yolov5s_paddle_model')       # PaddlePaddle\n\n# Images\nimg = 'https://ultralytics.com/images/zidane.jpg'  # or file, Path, PIL, OpenCV, numpy, list\n\n# Inference\nresults = model(img)\n\n# Results\nresults.print()  # or .show(), .save(), .crop(), .pandas(), etc.\n```\n\n## OpenCV DNN inference\n\nOpenCV inference with ONNX models:\n\n```bash\npython export.py --weights yolov5s.pt --include onnx\n\npython detect.py --weights yolov5s.onnx --dnn  # detect\npython val.py --weights yolov5s.onnx --dnn  # validate\n```\n\n## C++ Inference\n\nYOLOv5 OpenCV DNN C++ inference on exported ONNX model examples:\n\n- [https://github.com/Hexmagic/ONNX-yolov5/blob/master/src/test.cpp](https://github.com/Hexmagic/ONNX-yolov5/blob/master/src/test.cpp)\n- [https://github.com/doleron/yolov5-opencv-cpp-python](https://github.com/doleron/yolov5-opencv-cpp-python)\n\nYOLOv5 OpenVINO C++ inference examples:\n\n- [https://github.com/dacquaviva/yolov5-openvino-cpp-python](https://github.com/dacquaviva/yolov5-openvino-cpp-python)\n- [https://github.com/UNeedCryDear/yolov5-seg-opencv-dnn-cpp](https://github.com/UNeedCryDear/yolov5-seg-opencv-dnn-cpp)\n\n## TensorFlow.js Web Browser Inference\n\n- [https://aukerul-shuvo.github.io/YOLOv5_TensorFlow-JS/](https://aukerul-shuvo.github.io/YOLOv5_TensorFlow-JS/)\n\n## Environments\n\nYOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):\n\n- **Notebooks** with free GPU: <a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a> <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial/)\n- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/)\n- **Docker Image**. See [Docker Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/docker_image_quickstart_tutorial/) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n\n## Status\n\n<a href=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml\"><img src=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg\" alt=\"YOLOv5 CI\"></a>\n\nIf this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 [training](https://github.com/ultralytics/yolov5/blob/master/train.py), [validation](https://github.com/ultralytics/yolov5/blob/master/val.py), [inference](https://github.com/ultralytics/yolov5/blob/master/detect.py), [export](https://github.com/ultralytics/yolov5/blob/master/export.py) and [benchmarks](https://github.com/ultralytics/yolov5/blob/master/benchmarks.py) on macOS, Windows, and Ubuntu every 24 hours and on every commit."
  },
  {
    "path": "docs/yolov5/tutorials/model_pruning_and_sparsity.md",
    "content": "---\ncomments: true\ndescription: Learn how to apply pruning to your YOLOv5 models. See the before and after performance with an explanation of sparsity and more.\n---\n\n📚 This guide explains how to apply **pruning** to YOLOv5 🚀 models.  \nUPDATED 25 September 2022.\n\n## Before You Start\n\nClone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a [**Python>=3.7.0**](https://www.python.org/) environment, including [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). [Models](https://github.com/ultralytics/yolov5/tree/master/models) and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).\n\n```bash\ngit clone https://github.com/ultralytics/yolov5  # clone\ncd yolov5\npip install -r requirements.txt  # install\n```\n\n## Test Normally\n\nBefore pruning we want to establish a baseline performance to compare to. This command tests YOLOv5x on COCO val2017 at image size 640 pixels. `yolov5x.pt` is the largest and most accurate model available. Other options are `yolov5s.pt`, `yolov5m.pt` and `yolov5l.pt`, or you own checkpoint from training a custom dataset `./weights/best.pt`. For details on all available models please see our README [table](https://github.com/ultralytics/yolov5#pretrained-checkpoints).\n\n```bash\npython val.py --weights yolov5x.pt --data coco.yaml --img 640 --half\n```\n\nOutput:\n\n```shell\nval: data=/content/yolov5/data/coco.yaml, weights=['yolov5x.pt'], batch_size=32, imgsz=640, conf_thres=0.001, iou_thres=0.65, task=val, device=, workers=8, single_cls=False, augment=False, verbose=False, save_txt=False, save_hybrid=False, save_conf=False, save_json=True, project=runs/val, name=exp, exist_ok=False, half=True, dnn=False\nYOLOv5 🚀 v6.0-224-g4c40933 torch 1.10.0+cu111 CUDA:0 (Tesla V100-SXM2-16GB, 16160MiB)\n\nFusing layers... \nModel Summary: 444 layers, 86705005 parameters, 0 gradients\nval: Scanning '/content/datasets/coco/val2017.cache' images and labels... 4952 found, 48 missing, 0 empty, 0 corrupt: 100% 5000/5000 [00:00<?, ?it/s]\n               Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 157/157 [01:12<00:00,  2.16it/s]\n                 all       5000      36335      0.732      0.628      0.683      0.496\nSpeed: 0.1ms pre-process, 5.2ms inference, 1.7ms NMS per image at shape (32, 3, 640, 640)  # <--- base speed\n\nEvaluating pycocotools mAP... saving runs/val/exp2/yolov5x_predictions.json...\n...\n Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.507  # <--- base mAP\n Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.689\n Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.552\n Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.345\n Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.559\n Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.652\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.381\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.630\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.682\n Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.526\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.731\n Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.829\nResults saved to runs/val/exp\n```\n\n## Test YOLOv5x on COCO (0.30 sparsity)\n\nWe repeat the above test with a pruned model by using the `torch_utils.prune()` command. We update `val.py` to prune YOLOv5x to 0.3 sparsity:\n\n<img width=\"894\" alt=\"Screenshot 2022-02-02 at 22 54 18\" src=\"https://user-images.githubusercontent.com/26833433/152243799-b0ac2777-b1a8-47b1-801a-2e4c93c06ead.png\">\n\n30% pruned output:\n\n```bash\nval: data=/content/yolov5/data/coco.yaml, weights=['yolov5x.pt'], batch_size=32, imgsz=640, conf_thres=0.001, iou_thres=0.65, task=val, device=, workers=8, single_cls=False, augment=False, verbose=False, save_txt=False, save_hybrid=False, save_conf=False, save_json=True, project=runs/val, name=exp, exist_ok=False, half=True, dnn=False\nYOLOv5 🚀 v6.0-224-g4c40933 torch 1.10.0+cu111 CUDA:0 (Tesla V100-SXM2-16GB, 16160MiB)\n\nFusing layers... \nModel Summary: 444 layers, 86705005 parameters, 0 gradients\nPruning model...  0.3 global sparsity\nval: Scanning '/content/datasets/coco/val2017.cache' images and labels... 4952 found, 48 missing, 0 empty, 0 corrupt: 100% 5000/5000 [00:00<?, ?it/s]\n               Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 157/157 [01:11<00:00,  2.19it/s]\n                 all       5000      36335      0.724      0.614      0.671      0.478\nSpeed: 0.1ms pre-process, 5.2ms inference, 1.7ms NMS per image at shape (32, 3, 640, 640)  # <--- prune mAP\n\nEvaluating pycocotools mAP... saving runs/val/exp3/yolov5x_predictions.json...\n...\n Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.489  # <--- prune mAP\n Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.677\n Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.537\n Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.334\n Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.542\n Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.635\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.370\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.612\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.664\n Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.496\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.722\n Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.803\nResults saved to runs/val/exp3\n```\n\nIn the results we can observe that we have achieved a **sparsity of 30%** in our model after pruning, which means that 30% of the model's weight parameters in `nn.Conv2d` layers are equal to 0. **Inference time is essentially unchanged**, while the model's **AP and AR scores a slightly reduced**.\n\n## Environments\n\nYOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):\n\n- **Notebooks** with free GPU: <a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a> <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial/)\n- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/)\n- **Docker Image**. See [Docker Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/docker_image_quickstart_tutorial/) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n\n## Status\n\n<a href=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml\"><img src=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg\" alt=\"YOLOv5 CI\"></a>\n\nIf this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 [training](https://github.com/ultralytics/yolov5/blob/master/train.py), [validation](https://github.com/ultralytics/yolov5/blob/master/val.py), [inference](https://github.com/ultralytics/yolov5/blob/master/detect.py), [export](https://github.com/ultralytics/yolov5/blob/master/export.py) and [benchmarks](https://github.com/ultralytics/yolov5/blob/master/benchmarks.py) on macOS, Windows, and Ubuntu every 24 hours and on every commit."
  },
  {
    "path": "docs/yolov5/tutorials/multi_gpu_training.md",
    "content": "---\ncomments: true\ndescription: Learn how to train your dataset on single or multiple machines using YOLOv5 on multiple GPUs. Use simple commands with DDP mode for faster performance.\n---\n\n📚 This guide explains how to properly use **multiple** GPUs to train a dataset with YOLOv5 🚀 on single or multiple machine(s).  \nUPDATED 25 December 2022.\n\n## Before You Start\n\nClone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a [**Python>=3.7.0**](https://www.python.org/) environment, including [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). [Models](https://github.com/ultralytics/yolov5/tree/master/models) and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).\n\n```bash\ngit clone https://github.com/ultralytics/yolov5  # clone\ncd yolov5\npip install -r requirements.txt  # install\n```\n\n💡 ProTip! **Docker Image** is recommended for all Multi-GPU trainings. See [Docker Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/docker_image_quickstart_tutorial/) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n\n💡 ProTip! `torch.distributed.run` replaces `torch.distributed.launch` in **PyTorch>=1.9**. See [docs](https://pytorch.org/docs/stable/distributed.html) for details.\n\n## Training\n\nSelect a pretrained model to start training from. Here we select [YOLOv5s](https://github.com/ultralytics/yolov5/blob/master/models/yolov5s.yaml), the smallest and fastest model available. See our README [table](https://github.com/ultralytics/yolov5#pretrained-checkpoints) for a full comparison of all models. We will train this model with Multi-GPU on the [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh) dataset.\n\n<p align=\"center\"><img width=\"700\" alt=\"YOLOv5 Models\" src=\"https://github.com/ultralytics/yolov5/releases/download/v1.0/model_comparison.png\"></p>\n\n### Single GPU\n\n```bash\npython train.py  --batch 64 --data coco.yaml --weights yolov5s.pt --device 0\n```\n\n### Multi-GPU [DataParallel](https://pytorch.org/docs/stable/nn.html#torch.nn.DataParallel) Mode (⚠️ not recommended)\n\nYou can increase the `device` to use Multiple GPUs in DataParallel mode.\n\n```bash\npython train.py  --batch 64 --data coco.yaml --weights yolov5s.pt --device 0,1\n```\n\nThis method is slow and barely speeds up training compared to using just 1 GPU.\n\n### Multi-GPU [DistributedDataParallel](https://pytorch.org/docs/stable/nn.html#torch.nn.parallel.DistributedDataParallel) Mode (✅ recommended)\n\nYou will have to pass `python -m torch.distributed.run --nproc_per_node`, followed by the usual arguments.\n\n```bash\npython -m torch.distributed.run --nproc_per_node 2 train.py --batch 64 --data coco.yaml --weights yolov5s.pt --device 0,1\n```\n\n`--nproc_per_node` specifies how many GPUs you would like to use. In the example above, it is 2.\n`--batch ` is the total batch-size. It will be divided evenly to each GPU. In the example above, it is 64/2=32 per GPU.\n\nThe code above will use GPUs `0... (N-1)`.\n\n<details markdown>\n  <summary>Use specific GPUs (click to expand)</summary>\n\nYou can do so by simply passing `--device` followed by your specific GPUs. For example, in the code below, we will use GPUs `2,3`.\n\n```bash\npython -m torch.distributed.run --nproc_per_node 2 train.py --batch 64 --data coco.yaml --cfg yolov5s.yaml --weights '' --device 2,3\n```\n\n</details>\n\n<details markdown>\n  <summary>Use SyncBatchNorm (click to expand)</summary>\n\n[SyncBatchNorm](https://pytorch.org/docs/master/generated/torch.nn.SyncBatchNorm.html) could increase accuracy for multiple gpu training, however, it will slow down training by a significant factor. It is **only** available for Multiple GPU DistributedDataParallel training.\n\nIt is best used when the batch-size on **each** GPU is small (<= 8).\n\nTo use SyncBatchNorm, simple pass `--sync-bn` to the command like below,\n\n```bash\npython -m torch.distributed.run --nproc_per_node 2 train.py --batch 64 --data coco.yaml --cfg yolov5s.yaml --weights '' --sync-bn\n```\n\n</details>\n\n<details markdown>\n  <summary>Use Multiple machines (click to expand)</summary>\n\nThis is **only** available for Multiple GPU DistributedDataParallel training.\n\nBefore we continue, make sure the files on all machines are the same, dataset, codebase, etc. Afterwards, make sure the machines can communicate to each other.\n\nYou will have to choose a master machine(the machine that the others will talk to). Note down its address(`master_addr`) and choose a port(`master_port`). I will use `master_addr = 192.168.1.1` and `master_port = 1234` for the example below.\n\nTo use it, you can do as the following,\n\n```bash\n# On master machine 0\npython -m torch.distributed.run --nproc_per_node G --nnodes N --node_rank 0 --master_addr \"192.168.1.1\" --master_port 1234 train.py --batch 64 --data coco.yaml --cfg yolov5s.yaml --weights ''\n```\n\n```bash\n# On machine R\npython -m torch.distributed.run --nproc_per_node G --nnodes N --node_rank R --master_addr \"192.168.1.1\" --master_port 1234 train.py --batch 64 --data coco.yaml --cfg yolov5s.yaml --weights ''\n```\n\nwhere `G` is number of GPU per machine, `N` is the number of machines, and `R` is the machine number from `0...(N-1)`.\nLet's say I have two machines with two GPUs each, it would be `G = 2` , `N = 2`, and `R = 1` for the above.\n\nTraining will not start until <b>all </b> `N` machines are connected. Output will only be shown on master machine!\n\n</details>\n\n### Notes\n\n- Windows support is untested, Linux is recommended.\n- `--batch ` must be a multiple of the number of GPUs.\n- GPU 0 will take slightly more memory than the other GPUs as it maintains EMA and is responsible for checkpointing etc.\n- If you get `RuntimeError: Address already in use`, it could be because you are running multiple trainings at a time. To fix this, simply use a different port number by adding `--master_port` like below,\n\n```bash\npython -m torch.distributed.run --master_port 1234 --nproc_per_node 2 ...\n```\n\n## Results\n\nDDP profiling results on an [AWS EC2 P4d instance](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/) with 8x A100 SXM4-40GB for YOLOv5l for 1 COCO epoch.\n\n<details markdown>\n  <summary>Profiling code</summary>\n\n```bash\n# prepare\nt=ultralytics/yolov5:latest && sudo docker pull $t && sudo docker run -it --ipc=host --gpus all -v \"$(pwd)\"/coco:/usr/src/coco $t\npip3 install torch==1.9.0+cu111 torchvision==0.10.0+cu111 -f https://download.pytorch.org/whl/torch_stable.html\ncd .. && rm -rf app && git clone https://github.com/ultralytics/yolov5 -b master app && cd app\ncp data/coco.yaml data/coco_profile.yaml\n\n# profile\npython train.py --batch-size 16 --data coco_profile.yaml --weights yolov5l.pt --epochs 1 --device 0 \npython -m torch.distributed.run --nproc_per_node 2 train.py --batch-size 32 --data coco_profile.yaml --weights yolov5l.pt --epochs 1 --device 0,1   \npython -m torch.distributed.run --nproc_per_node 4 train.py --batch-size 64 --data coco_profile.yaml --weights yolov5l.pt --epochs 1 --device 0,1,2,3  \npython -m torch.distributed.run --nproc_per_node 8 train.py --batch-size 128 --data coco_profile.yaml --weights yolov5l.pt --epochs 1 --device 0,1,2,3,4,5,6,7\n```\n\n</details>\n\n| GPUs<br>A100 | batch-size | CUDA_mem<br><sup>device0 (G) | COCO<br><sup>train | COCO<br><sup>val |\n|--------------|------------|------------------------------|--------------------|------------------|\n| 1x           | 16         | 26GB                         | 20:39              | 0:55             |\n| 2x           | 32         | 26GB                         | 11:43              | 0:57             |\n| 4x           | 64         | 26GB                         | 5:57               | 0:55             |\n| 8x           | 128        | 26GB                         | 3:09               | 0:57             |\n\n## FAQ\n\nIf an error occurs, please read the checklist below first! (It could save your time)\n\n<details markdown>\n  <summary>Checklist (click to expand) </summary>\n\n<ul>\n    <li>Have you properly read this post?  </li>\n    <li>Have you tried to reclone the codebase? The code changes <b>daily</b>.</li>\n    <li>Have you tried to search for your error? Someone may have already encountered it in this repo or in another and have the solution. </li>\n    <li>Have you installed all the requirements listed on top (including the correct Python and Pytorch versions)? </li>\n    <li>Have you tried in other environments listed in the \"Environments\" section below? </li>\n    <li>Have you tried with another dataset like coco128 or coco2017? It will make it easier to find the root cause. </li>\n</ul>\n\nIf you went through all the above, feel free to raise an Issue by giving as much detail as possible following the template.\n\n</details>\n\n## Environments\n\nYOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):\n\n- **Notebooks** with free GPU: <a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a> <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial/)\n- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/)\n- **Docker Image**. See [Docker Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/docker_image_quickstart_tutorial/) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n\n## Status\n\n<a href=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml\"><img src=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg\" alt=\"YOLOv5 CI\"></a>\n\nIf this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 [training](https://github.com/ultralytics/yolov5/blob/master/train.py), [validation](https://github.com/ultralytics/yolov5/blob/master/val.py), [inference](https://github.com/ultralytics/yolov5/blob/master/detect.py), [export](https://github.com/ultralytics/yolov5/blob/master/export.py) and [benchmarks](https://github.com/ultralytics/yolov5/blob/master/benchmarks.py) on macOS, Windows, and Ubuntu every 24 hours and on every commit.\n\n## Credits\n\nI would like to thank @MagicFrogSJTU, who did all the heavy lifting, and @glenn-jocher for guiding us along the way."
  },
  {
    "path": "docs/yolov5/tutorials/neural_magic_pruning_quantization.md",
    "content": "---\ncomments: true\ndescription: Learn how to deploy YOLOv5 with DeepSparse to achieve exceptional CPU performance close to GPUs, using pruning, and quantization.<br>\n---\n\n<!--\nCopyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n   http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing,\nsoftware distributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n-->\n\nWelcome to software-delivered AI.\n\nThis guide explains how to deploy YOLOv5 with Neural Magic's DeepSparse.\n\nDeepSparse is an inference runtime with exceptional performance on CPUs. For instance, compared to the ONNX Runtime baseline, DeepSparse offers a 5.8x speed-up for YOLOv5s, running on the same machine!\n\n<p align=\"center\">\n  <img width=\"60%\" src=\"https://github.com/neuralmagic/deepsparse/raw/main/examples/ultralytics-yolo/ultralytics-readmes/performance-chart-5.8x.png\">\n</p>\n\nFor the first time, your deep learning workloads can meet the performance demands of production without the complexity and costs of hardware accelerators.\nPut simply, DeepSparse gives you the performance of GPUs and the simplicity of software:\n\n- **Flexible Deployments**: Run consistently across cloud, data center, and edge with any hardware provider from Intel to AMD to ARM\n- **Infinite Scalability**: Scale vertically to 100s of cores, out with standard Kubernetes, or fully-abstracted with Serverless\n- **Easy Integration**: Clean APIs for integrating your model into an application and monitoring it in production\n\n### How Does DeepSparse Achieve GPU-Class Performance?\n\nDeepSparse takes advantage of model sparsity to gain its performance speedup.\n\nSparsification through pruning and quantization is a broadly studied technique, allowing order-of-magnitude reductions in the size and compute needed to\nexecute a network, while maintaining high accuracy. DeepSparse is sparsity-aware, meaning it skips the zeroed out parameters, shrinking amount of compute\nin a forward pass. Since the sparse computation is now memory bound, DeepSparse executes the network depth-wise, breaking the problem into Tensor Columns,\nvertical stripes of computation that fit in cache.\n\n<p align=\"center\">\n  <img width=\"60%\" src=\"https://github.com/neuralmagic/deepsparse/raw/main/examples/ultralytics-yolo/ultralytics-readmes/tensor-columns.png\">\n</p>\n\nSparse networks with compressed computation, executed depth-wise in cache, allows DeepSparse to deliver GPU-class performance on CPUs!\n\n### How Do I Create A Sparse Version of YOLOv5 Trained on My Data?\n\nNeural Magic's open-source model repository, SparseZoo, contains pre-sparsified checkpoints of each YOLOv5 model. Using SparseML, which is integrated with Ultralytics, you can fine-tune a sparse checkpoint onto your data with a single CLI command.\n\n[Checkout Neural Magic's YOLOv5 documentation for more details](https://docs.neuralmagic.com/use-cases/object-detection/sparsifying).\n\n## DeepSparse Usage\n\nWe will walk through an example benchmarking and deploying a sparse version of YOLOv5s with DeepSparse.\n\n### Install DeepSparse\n\nRun the following to install DeepSparse. We recommend you use a virtual environment with Python.\n\n```bash\npip install deepsparse[server,yolo,onnxruntime]\n```\n\n### Collect an ONNX File\n\nDeepSparse accepts a model in the ONNX format, passed either as:\n\n- A SparseZoo stub which identifies an ONNX file in the SparseZoo\n- A local path to an ONNX model in a filesystem\n\nThe examples below use the standard dense and pruned-quantized YOLOv5s checkpoints, identified by the following SparseZoo stubs:\n\n```bash\nzoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/base-none\nzoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/pruned65_quant-none\n```\n\n### Deploy a Model\n\nDeepSparse offers convenient APIs for integrating your model into an application.\n\nTo try the deployment examples below, pull down a sample image and save it as `basilica.jpg` with the following:\n\n```bash\nwget -O basilica.jpg https://raw.githubusercontent.com/neuralmagic/deepsparse/main/src/deepsparse/yolo/sample_images/basilica.jpg\n```\n\n#### Python API\n\n`Pipelines` wrap pre-processing and output post-processing around the runtime, providing a clean interface for adding DeepSparse to an application.\nThe DeepSparse-Ultralytics integration includes an out-of-the-box `Pipeline` that accepts raw images and outputs the bounding boxes.\n\nCreate a `Pipeline` and run inference:\n\n```python\nfrom deepsparse import Pipeline\n\n# list of images in local filesystem\nimages = [\"basilica.jpg\"]\n\n# create Pipeline\nmodel_stub = \"zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/pruned65_quant-none\"\nyolo_pipeline = Pipeline.create(\n    task=\"yolo\",\n    model_path=model_stub,\n)\n\n# run inference on images, receive bounding boxes + classes\npipeline_outputs = yolo_pipeline(images=images, iou_thres=0.6, conf_thres=0.001)\nprint(pipeline_outputs)\n```\n\nIf you are running in the cloud, you may get an error that open-cv cannot find `libGL.so.1`. Running the following on Ubuntu installs it:\n\n```\napt-get install libgl1-mesa-glx\n```\n\n#### HTTP Server\n\nDeepSparse Server runs on top of the popular FastAPI web framework and Uvicorn web server. With just a single CLI command, you can easily setup a model\nservice endpoint with DeepSparse. The Server supports any Pipeline from DeepSparse, including object detection with YOLOv5, enabling you to send raw\nimages to the endpoint and receive the bounding boxes.\n\nSpin up the Server with the pruned-quantized YOLOv5s:\n\n```bash\ndeepsparse.server \\\n    --task yolo \\\n    --model_path zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/pruned65_quant-none\n```\n\nAn example request, using Python's `requests` package:\n\n```python\nimport requests, json\n\n# list of images for inference (local files on client side)\npath = ['basilica.jpg'] \nfiles = [('request', open(img, 'rb')) for img in path]\n\n# send request over HTTP to /predict/from_files endpoint\nurl = 'http://0.0.0.0:5543/predict/from_files'\nresp = requests.post(url=url, files=files)\n\n# response is returned in JSON\nannotations = json.loads(resp.text) # dictionary of annotation results\nbounding_boxes = annotations[\"boxes\"]\nlabels = annotations[\"labels\"]\n```\n\n#### Annotate CLI\n\nYou can also use the annotate command to have the engine save an annotated photo on disk. Try --source 0 to annotate your live webcam feed!\n\n```bash\ndeepsparse.object_detection.annotate --model_filepath zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/pruned65_quant-none --source basilica.jpg\n```\n\nRunning the above command will create an `annotation-results` folder and save the annotated image inside.\n\n<p align = \"center\">\n<img src=\"https://github.com/neuralmagic/deepsparse/raw/d31f02596ebff2ec62761d0bc9ca14c4663e8858/src/deepsparse/yolo/sample_images/basilica-annotated.jpg\" alt=\"annotated\" width=\"60%\"/>\n</p>\n\n## Benchmarking Performance\n\nWe will compare DeepSparse's throughput to ONNX Runtime's throughput on YOLOv5s, using DeepSparse's benchmarking script.\n\nThe benchmarks were run on an AWS `c6i.8xlarge` instance (16 cores).\n\n### Batch 32 Performance Comparison\n\n#### ONNX Runtime Baseline\n\nAt batch 32, ONNX Runtime achieves 42 images/sec with the standard dense YOLOv5s:\n\n```bash\ndeepsparse.benchmark zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/base-none -s sync -b 32 -nstreams 1 -e onnxruntime\n\n> Original Model Path: zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/base-none\n> Batch Size: 32\n> Scenario: sync\n> Throughput (items/sec): 41.9025\n```\n\n#### DeepSparse Dense Performance\n\nWhile DeepSparse offers its best performance with optimized sparse models, it also performs well with the standard dense YOLOv5s.\n\nAt batch 32, DeepSparse achieves 70 images/sec with the standard dense YOLOv5s, a **1.7x performance improvement over ORT**!\n\n```bash\ndeepsparse.benchmark zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/base-none -s sync -b 32 -nstreams 1\n\n> Original Model Path: zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/base-none\n> Batch Size: 32\n> Scenario: sync\n> Throughput (items/sec): 69.5546\n```\n\n#### DeepSparse Sparse Performance\n\nWhen sparsity is applied to the model, DeepSparse's performance gains over ONNX Runtime is even stronger.\n\nAt batch 32, DeepSparse achieves 241 images/sec with the pruned-quantized YOLOv5s, a **5.8x performance improvement over ORT**!\n\n```bash\ndeepsparse.benchmark zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/pruned65_quant-none -s sync -b 32 -nstreams 1\n\n> Original Model Path: zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/pruned65_quant-none\n> Batch Size: 32\n> Scenario: sync\n> Throughput (items/sec): 241.2452\n```\n\n### Batch 1 Performance Comparison\n\nDeepSparse is also able to gain a speed-up over ONNX Runtime for the latency-sensitive, batch 1 scenario.\n\n#### ONNX Runtime Baseline\n\nAt batch 1, ONNX Runtime achieves 48 images/sec with the standard, dense YOLOv5s.\n\n```bash\ndeepsparse.benchmark zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/base-none -s sync -b 1 -nstreams 1 -e onnxruntime\n\n> Original Model Path: zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/base-none\n> Batch Size: 1\n> Scenario: sync\n> Throughput (items/sec): 48.0921\n```\n\n#### DeepSparse Sparse Performance\n\nAt batch 1, DeepSparse achieves 135 items/sec with a pruned-quantized YOLOv5s, **a 2.8x performance gain over ONNX Runtime!**\n\n```bash\ndeepsparse.benchmark zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/pruned65_quant-none -s sync -b 1 -nstreams 1\n\n> Original Model Path: zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/pruned65_quant-none\n> Batch Size: 1\n> Scenario: sync\n> Throughput (items/sec): 134.9468\n```\n\nSince `c6i.8xlarge` instances have VNNI instructions, DeepSparse's throughput can be pushed further if weights are pruned in blocks of 4.\n\nAt batch 1, DeepSparse achieves 180 items/sec with a 4-block pruned-quantized YOLOv5s, a **3.7x performance gain over ONNX Runtime!**\n\n```bash\ndeepsparse.benchmark zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/pruned35_quant-none-vnni -s sync -b 1 -nstreams 1\n\n> Original Model Path: zoo:cv/detection/yolov5-s/pytorch/ultralytics/coco/pruned35_quant-none-vnni\n> Batch Size: 1\n> Scenario: sync\n> Throughput (items/sec): 179.7375\n```\n\n## Get Started With DeepSparse\n\n**Research or Testing?** DeepSparse Community is free for research and testing. Get started with our [Documentation](https://docs.neuralmagic.com/)."
  },
  {
    "path": "docs/yolov5/tutorials/pytorch_hub_model_loading.md",
    "content": "---\ncomments: true\ndescription: Learn how to load YOLOv5🚀 from PyTorch Hub at https://pytorch.org/hub/ultralytics_yolov5 and perform image inference. UPDATED 26 March 2023.\n---\n\n📚 This guide explains how to load YOLOv5 🚀 from PyTorch Hub at [https://pytorch.org/hub/ultralytics_yolov5](https://pytorch.org/hub/ultralytics_yolov5).  \nUPDATED 26 March 2023.\n\n## Before You Start\n\nInstall [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a [**Python>=3.7.0**](https://www.python.org/) environment, including [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). [Models](https://github.com/ultralytics/yolov5/tree/master/models) and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).\n\n```bash\npip install -r https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt\n```\n\n💡 ProTip: Cloning [https://github.com/ultralytics/yolov5](https://github.com/ultralytics/yolov5) is **not** required 😃\n\n## Load YOLOv5 with PyTorch Hub\n\n### Simple Example\n\nThis example loads a pretrained YOLOv5s model from PyTorch Hub as `model` and passes an image for inference. `'yolov5s'` is the lightest and fastest YOLOv5 model. For details on all available models please see the [README](https://github.com/ultralytics/yolov5#pretrained-checkpoints).\n\n```python\nimport torch\n\n# Model\nmodel = torch.hub.load('ultralytics/yolov5', 'yolov5s')\n\n# Image\nim = 'https://ultralytics.com/images/zidane.jpg'\n\n# Inference\nresults = model(im)\n\nresults.pandas().xyxy[0]\n#      xmin    ymin    xmax   ymax  confidence  class    name\n# 0  749.50   43.50  1148.0  704.5    0.874023      0  person\n# 1  433.50  433.50   517.5  714.5    0.687988     27     tie\n# 2  114.75  195.75  1095.0  708.0    0.624512      0  person\n# 3  986.00  304.00  1028.0  420.0    0.286865     27     tie\n```\n\n### Detailed Example\n\nThis example shows **batched inference** with **PIL** and **OpenCV** image sources. `results` can be **printed** to console, **saved** to `runs/hub`, **showed** to screen on supported environments, and returned as **tensors** or **pandas** dataframes.\n\n```python\nimport cv2\nimport torch\nfrom PIL import Image\n\n# Model\nmodel = torch.hub.load('ultralytics/yolov5', 'yolov5s')\n\n# Images\nfor f in 'zidane.jpg', 'bus.jpg':\n    torch.hub.download_url_to_file('https://ultralytics.com/images/' + f, f)  # download 2 images\nim1 = Image.open('zidane.jpg')  # PIL image\nim2 = cv2.imread('bus.jpg')[..., ::-1]  # OpenCV image (BGR to RGB)\n\n# Inference\nresults = model([im1, im2], size=640) # batch of images\n\n# Results\nresults.print()  \nresults.save()  # or .show()\n\nresults.xyxy[0]  # im1 predictions (tensor)\nresults.pandas().xyxy[0]  # im1 predictions (pandas)\n#      xmin    ymin    xmax   ymax  confidence  class    name\n# 0  749.50   43.50  1148.0  704.5    0.874023      0  person\n# 1  433.50  433.50   517.5  714.5    0.687988     27     tie\n# 2  114.75  195.75  1095.0  708.0    0.624512      0  person\n# 3  986.00  304.00  1028.0  420.0    0.286865     27     tie\n```\n\n<img src=\"https://user-images.githubusercontent.com/26833433/124915064-62a49e00-dff1-11eb-86b3-a85b97061afb.jpg\" width=\"500\">  <img src=\"https://user-images.githubusercontent.com/26833433/124915055-60424400-dff1-11eb-9055-24585b375a29.jpg\" width=\"300\">\n\nFor all inference options see YOLOv5 `AutoShape()` forward [method](https://github.com/ultralytics/yolov5/blob/30e4c4f09297b67afedf8b2bcd851833ddc9dead/models/common.py#L243-L252).\n\n### Inference Settings\n\nYOLOv5 models contain various inference attributes such as **confidence threshold**, **IoU threshold**, etc. which can be set by:\n\n```python\nmodel.conf = 0.25  # NMS confidence threshold\n      iou = 0.45  # NMS IoU threshold\n      agnostic = False  # NMS class-agnostic\n      multi_label = False  # NMS multiple labels per box\n      classes = None  # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs\n      max_det = 1000  # maximum number of detections per image\n      amp = False  # Automatic Mixed Precision (AMP) inference\n\nresults = model(im, size=320)  # custom inference size\n```\n\n### Device\n\nModels can be transferred to any device after creation:\n\n```python\nmodel.cpu()  # CPU\nmodel.cuda()  # GPU\nmodel.to(device)  # i.e. device=torch.device(0)\n```\n\nModels can also be created directly on any `device`:\n\n```python\nmodel = torch.hub.load('ultralytics/yolov5', 'yolov5s', device='cpu')  # load on CPU\n```\n\n💡 ProTip: Input images are automatically transferred to the correct model device before inference.\n\n### Silence Outputs\n\nModels can be loaded silently with `_verbose=False`:\n\n```python\nmodel = torch.hub.load('ultralytics/yolov5', 'yolov5s', _verbose=False)  # load silently\n```\n\n### Input Channels\n\nTo load a pretrained YOLOv5s model with 4 input channels rather than the default 3:\n\n```python\nmodel = torch.hub.load('ultralytics/yolov5', 'yolov5s', channels=4)\n```\n\nIn this case the model will be composed of pretrained weights **except for** the very first input layer, which is no longer the same shape as the pretrained input layer. The input layer will remain initialized by random weights.\n\n### Number of Classes\n\nTo load a pretrained YOLOv5s model with 10 output classes rather than the default 80:\n\n```python\nmodel = torch.hub.load('ultralytics/yolov5', 'yolov5s', classes=10)\n```\n\nIn this case the model will be composed of pretrained weights **except for** the output layers, which are no longer the same shape as the pretrained output layers. The output layers will remain initialized by random weights.\n\n### Force Reload\n\nIf you run into problems with the above steps, setting `force_reload=True` may help by discarding the existing cache and force a fresh download of the latest YOLOv5 version from PyTorch Hub.\n\n```python\nmodel = torch.hub.load('ultralytics/yolov5', 'yolov5s', force_reload=True)  # force reload\n```\n\n### Screenshot Inference\n\nTo run inference on your desktop screen:\n\n```python\nimport torch\nfrom PIL import ImageGrab\n\n# Model\nmodel = torch.hub.load('ultralytics/yolov5', 'yolov5s')\n\n# Image\nim = ImageGrab.grab()  # take a screenshot\n\n# Inference\nresults = model(im)\n```\n\n### Multi-GPU Inference\n\nYOLOv5 models can be loaded to multiple GPUs in parallel with threaded inference:\n\n```python\nimport torch\nimport threading\n\ndef run(model, im):\n  results = model(im)\n  results.save()\n\n# Models\nmodel0 = torch.hub.load('ultralytics/yolov5', 'yolov5s', device=0)\nmodel1 = torch.hub.load('ultralytics/yolov5', 'yolov5s', device=1)\n\n# Inference\nthreading.Thread(target=run, args=[model0, 'https://ultralytics.com/images/zidane.jpg'], daemon=True).start()\nthreading.Thread(target=run, args=[model1, 'https://ultralytics.com/images/bus.jpg'], daemon=True).start()\n```\n\n### Training\n\nTo load a YOLOv5 model for training rather than inference, set `autoshape=False`. To load a model with randomly initialized weights (to train from scratch) use `pretrained=False`. You must provide your own training script in this case. Alternatively see our YOLOv5 [Train Custom Data Tutorial](https://docs.ultralytics.com/yolov5/tutorials/train_custom_data) for model training.\n\n```python\nmodel = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False)  # load pretrained\nmodel = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False, pretrained=False)  # load scratch\n```\n\n### Base64 Results\n\nFor use with API services. See https://github.com/ultralytics/yolov5/pull/2291 and [Flask REST API](https://github.com/ultralytics/yolov5/tree/master/utils/flask_rest_api) example for details.\n\n```python\nresults = model(im)  # inference\n\nresults.ims # array of original images (as np array) passed to model for inference\nresults.render()  # updates results.ims with boxes and labels\nfor im in results.ims:\n    buffered = BytesIO()\n    im_base64 = Image.fromarray(im)\n    im_base64.save(buffered, format=\"JPEG\")\n    print(base64.b64encode(buffered.getvalue()).decode('utf-8'))  # base64 encoded image with results\n```\n\n### Cropped Results\n\nResults can be returned and saved as detection crops:\n\n```python\nresults = model(im)  # inference\ncrops = results.crop(save=True)  # cropped detections dictionary\n```\n\n### Pandas Results\n\nResults can be returned as [Pandas DataFrames](https://pandas.pydata.org/):\n\n```python\nresults = model(im)  # inference\nresults.pandas().xyxy[0]  # Pandas DataFrame\n```\n\n<details markdown>\n  <summary>Pandas Output (click to expand)</summary>\n\n```python\nprint(results.pandas().xyxy[0])\n#      xmin    ymin    xmax   ymax  confidence  class    name\n# 0  749.50   43.50  1148.0  704.5    0.874023      0  person\n# 1  433.50  433.50   517.5  714.5    0.687988     27     tie\n# 2  114.75  195.75  1095.0  708.0    0.624512      0  person\n# 3  986.00  304.00  1028.0  420.0    0.286865     27     tie\n```\n\n</details>\n\n### Sorted Results\n\nResults can be sorted by column, i.e. to sort license plate digit detection left-to-right (x-axis):\n\n```python\nresults = model(im)  # inference\nresults.pandas().xyxy[0].sort_values('xmin')  # sorted left-right\n```\n\n### Box-Cropped Results\n\nResults can be returned and saved as detection crops:\n\n```python\nresults = model(im)  # inference\ncrops = results.crop(save=True)  # cropped detections dictionary\n```\n\n### JSON Results\n\nResults can be returned in JSON format once converted to `.pandas()` dataframes using the `.to_json()` method. The JSON format can be modified using the `orient` argument. See pandas `.to_json()` [documentation](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html) for details.\n\n```python\nresults = model(ims)  # inference\nresults.pandas().xyxy[0].to_json(orient=\"records\")  # JSON img1 predictions\n```\n\n<details markdown>\n  <summary>JSON Output (click to expand)</summary>\n\n```json\n[\n{\"xmin\":749.5,\"ymin\":43.5,\"xmax\":1148.0,\"ymax\":704.5,\"confidence\":0.8740234375,\"class\":0,\"name\":\"person\"},\n{\"xmin\":433.5,\"ymin\":433.5,\"xmax\":517.5,\"ymax\":714.5,\"confidence\":0.6879882812,\"class\":27,\"name\":\"tie\"},\n{\"xmin\":115.25,\"ymin\":195.75,\"xmax\":1096.0,\"ymax\":708.0,\"confidence\":0.6254882812,\"class\":0,\"name\":\"person\"},\n{\"xmin\":986.0,\"ymin\":304.0,\"xmax\":1028.0,\"ymax\":420.0,\"confidence\":0.2873535156,\"class\":27,\"name\":\"tie\"}\n]\n```\n\n</details>\n\n## Custom Models\n\nThis example loads a custom 20-class [VOC](https://github.com/ultralytics/yolov5/blob/master/data/VOC.yaml)-trained YOLOv5s model `'best.pt'` with PyTorch Hub.\n\n```python\nmodel = torch.hub.load('ultralytics/yolov5', 'custom', path='path/to/best.pt')  # local model\nmodel = torch.hub.load('path/to/yolov5', 'custom', path='path/to/best.pt', source='local')  # local repo\n```\n\n## TensorRT, ONNX and OpenVINO Models\n\nPyTorch Hub supports inference on most YOLOv5 export formats, including custom trained models. See [TFLite, ONNX, CoreML, TensorRT Export tutorial](https://docs.ultralytics.com/yolov5/tutorials/model_export) for details on exporting models.\n\n💡 ProTip: **TensorRT** may be up to 2-5X faster than PyTorch on [**GPU benchmarks**](https://github.com/ultralytics/yolov5/pull/6963)  \n💡 ProTip: **ONNX** and **OpenVINO** may be up to 2-3X faster than PyTorch on [**CPU benchmarks**](https://github.com/ultralytics/yolov5/pull/6613)\n\n```python\nmodel = torch.hub.load('ultralytics/yolov5', 'custom', path='yolov5s.pt')  # PyTorch\n                                                            'yolov5s.torchscript')  # TorchScript\n                                                            'yolov5s.onnx')  # ONNX\n                                                            'yolov5s_openvino_model/')  # OpenVINO\n                                                            'yolov5s.engine')  # TensorRT\n                                                            'yolov5s.mlmodel')  # CoreML (macOS-only)\n                                                            'yolov5s.tflite')  # TFLite\n                                                            'yolov5s_paddle_model/')  # PaddlePaddle\n```\n\n## Environments\n\nYOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):\n\n- **Notebooks** with free GPU: <a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a> <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial/)\n- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/)\n- **Docker Image**. See [Docker Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/docker_image_quickstart_tutorial/) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n\n## Status\n\n<a href=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml\"><img src=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg\" alt=\"YOLOv5 CI\"></a>\n\nIf this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 [training](https://github.com/ultralytics/yolov5/blob/master/train.py), [validation](https://github.com/ultralytics/yolov5/blob/master/val.py), [inference](https://github.com/ultralytics/yolov5/blob/master/detect.py), [export](https://github.com/ultralytics/yolov5/blob/master/export.py) and [benchmarks](https://github.com/ultralytics/yolov5/blob/master/benchmarks.py) on macOS, Windows, and Ubuntu every 24 hours and on every commit."
  },
  {
    "path": "docs/yolov5/tutorials/roboflow_datasets_integration.md",
    "content": "---\ncomments: true\ndescription: Use Roboflow to organize, label, prepare, version & host datasets for training YOLOv5 models. Upload via UI, API, or Python, making versions with custom preprocessing and offline augmentation. Export in YOLOv5 format and access custom training tutorials. Use active learning to improve model deployments.\n---\n\n# Roboflow Datasets\n\nYou can now use Roboflow to organize, label, prepare, version, and host your datasets for training YOLOv5 🚀 models. Roboflow is free to use with YOLOv5 if you make your workspace public.  \nUPDATED 30 September 2021.\n\n## Upload\n\nYou can upload your data to Roboflow via [web UI](https://docs.roboflow.com/adding-data), [rest API](https://docs.roboflow.com/adding-data/upload-api), or [python](https://docs.roboflow.com/python).\n\n## Labeling\n\nAfter uploading data to Roboflow, you can label your data and review previous labels.\n\n[![Roboflow Annotate](https://roboflow-darknet.s3.us-east-2.amazonaws.com/roboflow-annotate.gif)](https://roboflow.com/annotate)\n\n## Versioning\n\nYou can make versions of your dataset with different preprocessing and offline augmentation options. YOLOv5 does online augmentations natively, so be intentional when layering Roboflow's offline augs on top.\n\n![Roboflow Preprocessing](https://roboflow-darknet.s3.us-east-2.amazonaws.com/robolfow-preprocessing.png)\n\n## Exporting Data\n\nYou can download your data in YOLOv5 format to quickly begin training.\n\n```\nfrom roboflow import Roboflow\nrf = Roboflow(api_key=\"YOUR API KEY HERE\")\nproject = rf.workspace().project(\"YOUR PROJECT\")\ndataset = project.version(\"YOUR VERSION\").download(\"yolov5\")\n```\n\n## Custom Training\n\nWe have released a custom training tutorial demonstrating all of the above capabilities. You can access the code here:\n\n[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/roboflow-ai/yolov5-custom-training-tutorial/blob/main/yolov5-custom-training.ipynb)\n\n## Active Learning\n\nThe real world is messy and your model will invariably encounter situations your dataset didn't anticipate. Using [active learning](https://blog.roboflow.com/what-is-active-learning/) is an important strategy to iteratively improve your dataset and model. With the Roboflow and YOLOv5 integration, you can quickly make improvements on your model deployments by using a battle tested machine learning pipeline.\n\n<p align=\"\"><a href=\"https://roboflow.com/?ref=ultralytics\"><img width=\"1000\" src=\"https://uploads-ssl.webflow.com/5f6bc60e665f54545a1e52a5/615627e5824c9c6195abfda9_computer-vision-cycle.png\"/></a></p>"
  },
  {
    "path": "docs/yolov5/tutorials/running_on_jetson_nano.md",
    "content": "---\ncomments: true\ndescription: Deploy YOLOv5 on NVIDIA Jetson using TensorRT and DeepStream SDK for high performance inference. Step-by-step guide with code snippets.\n---\n\n# Deploy on NVIDIA Jetson using TensorRT and DeepStream SDK\n\n📚 This guide explains how to deploy a trained model into NVIDIA Jetson Platform and perform inference using TensorRT and DeepStream SDK. Here we use TensorRT to maximize the inference performance on the Jetson platform.  \nUPDATED 18 November 2022.\n\n## Hardware Verification\n\nWe have tested and verified this guide on the following Jetson devices\n\n- [Seeed reComputer J1010 built with Jetson Nano module](https://www.seeedstudio.com/Jetson-10-1-A0-p-5336.html)\n- [Seeed reComputer J2021 built with Jetson Xavier NX module](https://www.seeedstudio.com/reComputer-J2021-p-5438.html)\n\n## Before You Start\n\nMake sure you have properly installed **JetPack SDK** with all the **SDK Components** and **DeepStream SDK** on the Jetson device as this includes CUDA, TensorRT and DeepStream SDK which are needed for this guide.\n\nJetPack SDK provides a full development environment for hardware-accelerated AI-at-the-edge development. All Jetson modules and developer kits are supported by JetPack SDK.\n\nThere are two major installation methods including,\n\n1. SD Card Image Method\n2. NVIDIA SDK Manager Method\n\nYou can find a very detailed installation guide from NVIDIA [official website](https://developer.nvidia.com/jetpack-sdk-461). You can also find guides corresponding to the above-mentioned [reComputer J1010](https://wiki.seeedstudio.com/reComputer_J1010_J101_Flash_Jetpack) and [reComputer J2021](https://wiki.seeedstudio.com/reComputer_J2021_J202_Flash_Jetpack).\n\n## Install Necessary Packages\n\n- **Step 1.** Access the terminal of Jetson device, install pip and upgrade it\n\n```sh\nsudo apt update\nsudo apt install -y python3-pip\npip3 install --upgrade pip\n```\n\n- **Step 2.** Clone the following repo\n\n```sh\ngit clone https://github.com/ultralytics/yolov5\n```\n\n- **Step 3.** Open **requirements.txt**\n\n```sh\ncd yolov5\nvi requirements.txt\n```\n\n- **Step 5.** Edit the following lines. Here you need to press **i** first to enter editing mode. Press **ESC**, then type **:wq** to save and quit\n\n```sh\n# torch>=1.7.0\n# torchvision>=0.8.1\n```\n\n**Note:** torch and torchvision are excluded for now because they will be installed later.\n\n- **Step 6.** install the below dependency\n\n```sh\nsudo apt install -y libfreetype6-dev\n```\n\n- **Step 7.** Install the necessary packages\n\n```sh\npip3 install -r requirements.txt\n```\n\n## Install PyTorch and Torchvision\n\nWe cannot install PyTorch and Torchvision from pip because they are not compatible to run on Jetson platform which is based on **ARM aarch64 architecture**. Therefore, we need to manually install pre-built PyTorch pip wheel and compile/ install Torchvision from source.\n\nVisit [this page](https://forums.developer.nvidia.com/t/pytorch-for-jetson) to access all the PyTorch and Torchvision links.\n\nHere are some of the versions supported by JetPack 4.6 and above.\n\n**PyTorch v1.10.0**\n\nSupported by JetPack 4.4 (L4T R32.4.3) / JetPack 4.4.1 (L4T R32.4.4) / JetPack 4.5 (L4T R32.5.0) / JetPack 4.5.1 (L4T R32.5.1) / JetPack 4.6 (L4T R32.6.1) with Python 3.6\n\n**file_name:** torch-1.10.0-cp36-cp36m-linux_aarch64.whl\n**URL:** [https://nvidia.box.com/shared/static/fjtbno0vpo676a25cgvuqc1wty0fkkg6.whl](https://nvidia.box.com/shared/static/fjtbno0vpo676a25cgvuqc1wty0fkkg6.whl)\n\n**PyTorch v1.12.0**\n\nSupported by JetPack 5.0 (L4T R34.1.0) / JetPack 5.0.1 (L4T R34.1.1) / JetPack 5.0.2 (L4T R35.1.0) with Python 3.8\n\n**file_name:** torch-1.12.0a0+2c916ef.nv22.3-cp38-cp38-linux_aarch64.whl\n**URL:** [https://developer.download.nvidia.com/compute/redist/jp/v50/pytorch/torch-1.12.0a0+2c916ef.nv22.3-cp38-cp38-linux_aarch64.whl](https://developer.download.nvidia.com/compute/redist/jp/v50/pytorch/torch-1.12.0a0+2c916ef.nv22.3-cp38-cp38-linux_aarch64.whl)\n\n- **Step 1.** Install torch according to your JetPack version in the following format\n\n```sh\nwget <URL> -O <file_name>\npip3 install <file_name>\n```\n\nFor example, here we are running **JP4.6.1**, and therefore we choose **PyTorch v1.10.0**\n\n```sh\ncd ~\nsudo apt-get install -y libopenblas-base libopenmpi-dev\nwget https://nvidia.box.com/shared/static/fjtbno0vpo676a25cgvuqc1wty0fkkg6.whl -O torch-1.10.0-cp36-cp36m-linux_aarch64.whl\npip3 install torch-1.10.0-cp36-cp36m-linux_aarch64.whl\n```\n\n- **Step 2.** Install torchvision depending on the version of PyTorch that you have installed. For example, we chose **PyTorch v1.10.0**, which means, we need to choose **Torchvision v0.11.1**\n\n```sh\nsudo apt install -y libjpeg-dev zlib1g-dev\ngit clone --branch v0.11.1 https://github.com/pytorch/vision torchvision\ncd torchvision\nsudo python3 setup.py install \n```\n\nHere a list of the corresponding torchvision version that you need to install according to the PyTorch version:\n\n- PyTorch v1.10 - torchvision v0.11.1\n- PyTorch v1.12 - torchvision v0.13.0\n\n## DeepStream Configuration for YOLOv5\n\n- **Step 1.** Clone the following repo\n\n```sh\ncd ~\ngit clone https://github.com/marcoslucianops/DeepStream-Yolo\n```\n\n- **Step 2.** Copy **gen_wts_yoloV5.py** from **DeepStream-Yolo/utils** into **yolov5** directory\n\n```sh\ncp DeepStream-Yolo/utils/gen_wts_yoloV5.py yolov5\n```\n\n- **Step 3.** Inside the yolov5 repo, download **pt file** from YOLOv5 releases (example for YOLOv5s 6.1)\n\n```sh\ncd yolov5\nwget https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5s.pt\n```\n\n- **Step 4.** Generate the **cfg** and **wts** files\n\n```sh\npython3 gen_wts_yoloV5.py -w yolov5s.pt\n```\n\n**Note**: To change the inference size (default: 640)\n\n```sh\n-s SIZE\n--size SIZE\n-s HEIGHT WIDTH\n--size HEIGHT WIDTH\n\nExample for 1280:\n\n-s 1280\nor\n-s 1280 1280\n```\n\n- **Step 5.** Copy the generated **cfg** and **wts** files into the **DeepStream-Yolo** folder\n\n```sh\ncp yolov5s.cfg ~/DeepStream-Yolo\ncp yolov5s.wts ~/DeepStream-Yolo\n```\n\n- **Step 6.** Open the **DeepStream-Yolo** folder and compile the library\n\n```sh\ncd ~/DeepStream-Yolo\nCUDA_VER=11.4 make -C nvdsinfer_custom_impl_Yolo  # for DeepStream 6.1\nCUDA_VER=10.2 make -C nvdsinfer_custom_impl_Yolo  # for DeepStream 6.0.1 / 6.0\n```\n\n- **Step 7.** Edit the **config_infer_primary_yoloV5.txt** file according to your model\n\n```sh\n[property]\n...\ncustom-network-config=yolov5s.cfg\nmodel-file=yolov5s.wts\n...\n```\n\n- **Step 8.** Edit the **deepstream_app_config** file\n\n```sh\n...\n[primary-gie]\n...\nconfig-file=config_infer_primary_yoloV5.txt\n```\n\n- **Step 9.** Change the video source in **deepstream_app_config** file. Here a default video file is loaded as you can see below\n\n```sh\n...\n[source0]\n...\nuri=file:///opt/nvidia/deepstream/deepstream/samples/streams/sample_1080p_h264.mp4\n```\n\n## Run the Inference\n\n```sh\ndeepstream-app -c deepstream_app_config.txt\n```\n\n<div align=center><img width=1000 src=\"https://files.seeedstudio.com/wiki/YOLOV5/FP32-yolov5s.gif\"/></div>\n\nThe above result is running on **Jetson Xavier NX** with **FP32** and **YOLOv5s 640x640**. We can see that the **FPS** is around **30**.\n\n## INT8 Calibration\n\nIf you want to use INT8 precision for inference, you need to follow the steps below\n\n- **Step 1.** Install OpenCV\n\n```sh\nsudo apt-get install libopencv-dev\n```\n\n- **Step 2.** Compile/recompile the **nvdsinfer_custom_impl_Yolo** library with OpenCV support\n\n```sh\ncd ~/DeepStream-Yolo\nCUDA_VER=11.4 OPENCV=1 make -C nvdsinfer_custom_impl_Yolo  # for DeepStream 6.1\nCUDA_VER=10.2 OPENCV=1 make -C nvdsinfer_custom_impl_Yolo  # for DeepStream 6.0.1 / 6.0\n```\n\n- **Step 3.** For COCO dataset, download the [val2017](https://drive.google.com/file/d/1gbvfn7mcsGDRZ_luJwtITL-ru2kK99aK/view?usp=sharing), extract, and move to **DeepStream-Yolo** folder\n\n- **Step 4.** Make a new directory for calibration images\n\n```sh\nmkdir calibration\n```\n\n- **Step 5.** Run the following to select 1000 random images from COCO dataset to run calibration\n\n```sh\nfor jpg in $(ls -1 val2017/*.jpg | sort -R | head -1000); do \\\n    cp ${jpg} calibration/; \\\ndone\n```\n\n**Note:** NVIDIA recommends at least 500 images to get a good accuracy. On this example, 1000 images are chosen to get better accuracy (more images = more accuracy). Higher INT8_CALIB_BATCH_SIZE values will result in more accuracy and faster calibration speed. Set it according to you GPU memory. You can set it from **head -1000**. For example, for 2000 images, **head -2000**. This process can take a long time.\n\n- **Step 6.** Create the **calibration.txt** file with all selected images\n\n```sh\nrealpath calibration/*jpg > calibration.txt\n```\n\n- **Step 7.** Set environment variables\n\n```sh\nexport INT8_CALIB_IMG_PATH=calibration.txt\nexport INT8_CALIB_BATCH_SIZE=1\n```\n\n- **Step 8.** Update the **config_infer_primary_yoloV5.txt** file\n\nFrom\n\n```sh\n...\nmodel-engine-file=model_b1_gpu0_fp32.engine\n#int8-calib-file=calib.table\n...\nnetwork-mode=0\n...\n```\n\nTo\n\n```sh\n...\nmodel-engine-file=model_b1_gpu0_int8.engine\nint8-calib-file=calib.table\n...\nnetwork-mode=1\n...\n```\n\n- **Step 9.** Run the inference\n\n```sh\ndeepstream-app -c deepstream_app_config.txt\n```\n\n<div align=center><img width=1000  src=\"https://files.seeedstudio.com/wiki/YOLOV5/INT8-yolov5s.gif\"/></div>\n\nThe above result is running on **Jetson Xavier NX** with **INT8** and **YOLOv5s 640x640**. We can see that the **FPS** is around **60**.\n\n## Benchmark results\n\nThe following table summarizes how different models perform on **Jetson Xavier NX**.\n\n| Model Name | Precision | Inference Size | Inference Time (ms) | FPS |\n|------------|-----------|----------------|---------------------|-----|\n| YOLOv5s    | FP32      | 320x320        | 16.66               | 60  |                    \n|            | FP32      | 640x640        | 33.33               | 30  |                    \n|            | INT8      | 640x640        | 16.66               | 60  |                    \n| YOLOv5n    | FP32      | 640x640        | 16.66               | 60  |                    \n\n### Additional\n\nThis tutorial is written by our friends at seeed @lakshanthad and Elaine"
  },
  {
    "path": "docs/yolov5/tutorials/test_time_augmentation.md",
    "content": "---\ncomments: true\ndescription: Learn how to use Test Time Augmentation (TTA) with YOLOv5 to improve mAP and Recall during testing and inference. Code examples included.\n---\n\n# Test-Time Augmentation (TTA)\n\n📚 This guide explains how to use Test Time Augmentation (TTA) during testing and inference for improved mAP and Recall with YOLOv5 🚀.  \nUPDATED 25 September 2022.\n\n## Before You Start\n\nClone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a [**Python>=3.7.0**](https://www.python.org/) environment, including [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). [Models](https://github.com/ultralytics/yolov5/tree/master/models) and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).\n\n```bash\ngit clone https://github.com/ultralytics/yolov5  # clone\ncd yolov5\npip install -r requirements.txt  # install\n```\n\n## Test Normally\n\nBefore trying TTA we want to establish a baseline performance to compare to. This command tests YOLOv5x on COCO val2017 at image size 640 pixels. `yolov5x.pt` is the largest and most accurate model available. Other options are `yolov5s.pt`, `yolov5m.pt` and `yolov5l.pt`, or you own checkpoint from training a custom dataset `./weights/best.pt`. For details on all available models please see our README [table](https://github.com/ultralytics/yolov5#pretrained-checkpoints).\n\n```bash\npython val.py --weights yolov5x.pt --data coco.yaml --img 640 --half\n```\n\nOutput:\n\n```shell\nval: data=./data/coco.yaml, weights=['yolov5x.pt'], batch_size=32, imgsz=640, conf_thres=0.001, iou_thres=0.65, task=val, device=, single_cls=False, augment=False, verbose=False, save_txt=False, save_hybrid=False, save_conf=False, save_json=True, project=runs/val, name=exp, exist_ok=False, half=True\nYOLOv5 🚀 v5.0-267-g6a3ee7c torch 1.9.0+cu102 CUDA:0 (Tesla P100-PCIE-16GB, 16280.875MB)\n\nFusing layers... \nModel Summary: 476 layers, 87730285 parameters, 0 gradients\n\nval: Scanning '../datasets/coco/val2017' images and labels...4952 found, 48 missing, 0 empty, 0 corrupted: 100% 5000/5000 [00:01<00:00, 2846.03it/s]\nval: New cache created: ../datasets/coco/val2017.cache\n               Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 157/157 [02:30<00:00,  1.05it/s]\n                 all       5000      36335      0.746      0.626       0.68       0.49\nSpeed: 0.1ms pre-process, 22.4ms inference, 1.4ms NMS per image at shape (32, 3, 640, 640)  # <--- baseline speed\n\nEvaluating pycocotools mAP... saving runs/val/exp/yolov5x_predictions.json...\n...\n Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.504  # <--- baseline mAP\n Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.688\n Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.546\n Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.351\n Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.551\n Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.644\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.382\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.628\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.681  # <--- baseline mAR\n Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.524\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.735\n Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.826\n```\n\n## Test with TTA\n\nAppend `--augment` to any existing `val.py` command to enable TTA, and increase the image size by about 30% for improved results. Note that inference with TTA enabled will typically take about 2-3X the time of normal inference as the images are being left-right flipped and processed at 3 different resolutions, with the outputs merged before NMS. Part of the speed decrease is simply due to larger image sizes (832 vs 640), while part is due to the actual TTA operations.\n\n```bash\npython val.py --weights yolov5x.pt --data coco.yaml --img 832 --augment --half\n```\n\nOutput:\n\n```shell\nval: data=./data/coco.yaml, weights=['yolov5x.pt'], batch_size=32, imgsz=832, conf_thres=0.001, iou_thres=0.6, task=val, device=, single_cls=False, augment=True, verbose=False, save_txt=False, save_hybrid=False, save_conf=False, save_json=True, project=runs/val, name=exp, exist_ok=False, half=True\nYOLOv5 🚀 v5.0-267-g6a3ee7c torch 1.9.0+cu102 CUDA:0 (Tesla P100-PCIE-16GB, 16280.875MB)\n\nFusing layers... \n/usr/local/lib/python3.7/dist-packages/torch/nn/functional.py:718: UserWarning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (Triggered internally at  /pytorch/c10/core/TensorImpl.h:1156.)\n  return torch.max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode)\nModel Summary: 476 layers, 87730285 parameters, 0 gradients\nval: Scanning '../datasets/coco/val2017' images and labels...4952 found, 48 missing, 0 empty, 0 corrupted: 100% 5000/5000 [00:01<00:00, 2885.61it/s]\nval: New cache created: ../datasets/coco/val2017.cache\n               Class     Images     Labels          P          R     mAP@.5 mAP@.5:.95: 100% 157/157 [07:29<00:00,  2.86s/it]\n                 all       5000      36335      0.718      0.656      0.695      0.503\nSpeed: 0.2ms pre-process, 80.6ms inference, 2.7ms NMS per image at shape (32, 3, 832, 832)  # <--- TTA speed\n\nEvaluating pycocotools mAP... saving runs/val/exp2/yolov5x_predictions.json...\n...\n Average Precision  (AP) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.516  # <--- TTA mAP\n Average Precision  (AP) @[ IoU=0.50      | area=   all | maxDets=100 ] = 0.701\n Average Precision  (AP) @[ IoU=0.75      | area=   all | maxDets=100 ] = 0.562\n Average Precision  (AP) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.361\n Average Precision  (AP) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.564\n Average Precision  (AP) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.656\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=  1 ] = 0.388\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets= 10 ] = 0.640\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=   all | maxDets=100 ] = 0.696  # <--- TTA mAR\n Average Recall     (AR) @[ IoU=0.50:0.95 | area= small | maxDets=100 ] = 0.553\n Average Recall     (AR) @[ IoU=0.50:0.95 | area=medium | maxDets=100 ] = 0.744\n Average Recall     (AR) @[ IoU=0.50:0.95 | area= large | maxDets=100 ] = 0.833\n```\n\n## Inference with TTA\n\n`detect.py` TTA inference operates identically to `val.py` TTA: simply append `--augment` to any existing `detect.py` command:\n\n```bash\npython detect.py --weights yolov5s.pt --img 832 --source data/images --augment\n```\n\nOutput:\n\n```bash\ndetect: weights=['yolov5s.pt'], source=data/images, imgsz=832, conf_thres=0.25, iou_thres=0.45, max_det=1000, device=, view_img=False, save_txt=False, save_conf=False, save_crop=False, nosave=False, classes=None, agnostic_nms=False, augment=True, update=False, project=runs/detect, name=exp, exist_ok=False, line_width=3, hide_labels=False, hide_conf=False, half=False\nYOLOv5 🚀 v5.0-267-g6a3ee7c torch 1.9.0+cu102 CUDA:0 (Tesla P100-PCIE-16GB, 16280.875MB)\n\nDownloading https://github.com/ultralytics/yolov5/releases/download/v5.0/yolov5s.pt to yolov5s.pt...\n100% 14.1M/14.1M [00:00<00:00, 81.9MB/s]\n\nFusing layers... \nModel Summary: 224 layers, 7266973 parameters, 0 gradients\nimage 1/2 /content/yolov5/data/images/bus.jpg: 832x640 4 persons, 1 bus, 1 fire hydrant, Done. (0.029s)\nimage 2/2 /content/yolov5/data/images/zidane.jpg: 480x832 3 persons, 3 ties, Done. (0.024s)\nResults saved to runs/detect/exp\nDone. (0.156s)\n```\n\n<img src=\"https://user-images.githubusercontent.com/26833433/124491703-dbb6b200-ddb3-11eb-8b57-ed0d58d0d8b4.jpg\" width=\"500\">\n\n### PyTorch Hub TTA\n\nTTA is automatically integrated into all [YOLOv5 PyTorch Hub](https://pytorch.org/hub/ultralytics_yolov5) models, and can be accessed by passing `augment=True` at inference time.\n\n```python\nimport torch\n\n# Model\nmodel = torch.hub.load('ultralytics/yolov5', 'yolov5s')  # or yolov5m, yolov5x, custom\n\n# Images\nimg = 'https://ultralytics.com/images/zidane.jpg'  # or file, PIL, OpenCV, numpy, multiple\n\n# Inference\nresults = model(img, augment=True)  # <--- TTA inference\n\n# Results\nresults.print()  # or .show(), .save(), .crop(), .pandas(), etc.\n```\n\n### Customize\n\nYou can customize the TTA ops applied in the YOLOv5 `forward_augment()` method [here](https://github.com/ultralytics/yolov5/blob/8c6f9e15bfc0000d18b976a95b9d7c17d407ec91/models/yolo.py#L125-L137).\n\n## Environments\n\nYOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):\n\n- **Notebooks** with free GPU: <a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a> <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial/)\n- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/)\n- **Docker Image**. See [Docker Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/docker_image_quickstart_tutorial/) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n\n## Status\n\n<a href=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml\"><img src=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg\" alt=\"YOLOv5 CI\"></a>\n\nIf this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 [training](https://github.com/ultralytics/yolov5/blob/master/train.py), [validation](https://github.com/ultralytics/yolov5/blob/master/val.py), [inference](https://github.com/ultralytics/yolov5/blob/master/detect.py), [export](https://github.com/ultralytics/yolov5/blob/master/export.py) and [benchmarks](https://github.com/ultralytics/yolov5/blob/master/benchmarks.py) on macOS, Windows, and Ubuntu every 24 hours and on every commit."
  },
  {
    "path": "docs/yolov5/tutorials/tips_for_best_training_results.md",
    "content": "---\ncomments: true\ndescription: Get the most out of YOLOv5 with this guide; producing best results, checking dataset, hypertuning & more. Updated May 2022.\n---\n\n📚 This guide explains how to produce the best mAP and training results with YOLOv5 🚀.  \nUPDATED 25 May 2022.\n\nMost of the time good results can be obtained with no changes to the models or training settings, **provided your dataset is sufficiently large and well labelled**. If at first you don't get good results, there are steps you might be able to take to improve, but we always recommend users **first train with all default settings** before considering any changes. This helps establish a performance baseline and spot areas for improvement.\n\nIf you have questions about your training results **we recommend you provide the maximum amount of information possible** if you expect a helpful response, including results plots (train losses, val losses, P, R, mAP), PR curve, confusion matrix, training mosaics, test results and dataset statistics images such as labels.png. All of these are located in your `project/name` directory, typically `yolov5/runs/train/exp`.\n\nWe've put together a full guide for users looking to get the best results on their YOLOv5 trainings below.\n\n## Dataset\n\n- **Images per class.** ≥ 1500 images per class recommended\n- **Instances per class.** ≥ 10000 instances (labeled objects) per class recommended\n- **Image variety.** Must be representative of deployed environment. For real-world use cases we recommend images from different times of day, different seasons, different weather, different lighting, different angles, different sources (scraped online, collected locally, different cameras) etc.\n- **Label consistency.** All instances of all classes in all images must be labelled. Partial labelling will not work.\n- **Label accuracy.** Labels must closely enclose each object. No space should exist between an object and it's bounding box. No objects should be missing a label.\n- **Label verification.** View `train_batch*.jpg` on train start to verify your labels appear correct, i.e. see [example](https://docs.ultralytics.com/yolov5/tutorials/train_custom_data#local-logging) mosaic.\n- **Background images.** Background images are images with no objects that are added to a dataset to reduce False Positives (FP). We recommend about 0-10% background images to help reduce FPs (COCO has 1000 background images for reference, 1% of the total). No labels are required for background images.\n\n<a href=\"https://arxiv.org/abs/1405.0312\"><img width=\"800\" src=\"https://user-images.githubusercontent.com/26833433/109398377-82b0ac00-78f1-11eb-9c76-cc7820669d0d.png\" alt=\"COCO Analysis\"></a>\n\n## Model Selection\n\nLarger models like YOLOv5x and [YOLOv5x6](https://github.com/ultralytics/yolov5/releases/tag/v5.0) will produce better results in nearly all cases, but have more parameters, require more CUDA memory to train, and are slower to run. For **mobile** deployments we recommend YOLOv5s/m, for **cloud** deployments we recommend YOLOv5l/x. See our README [table](https://github.com/ultralytics/yolov5#pretrained-checkpoints) for a full comparison of all models.\n\n<p align=\"center\"><img width=\"700\" alt=\"YOLOv5 Models\" src=\"https://github.com/ultralytics/yolov5/releases/download/v1.0/model_comparison.png\"></p>\n\n- **Start from Pretrained weights.** Recommended for small to medium-sized datasets (i.e. [VOC](https://github.com/ultralytics/yolov5/blob/master/data/VOC.yaml), [VisDrone](https://github.com/ultralytics/yolov5/blob/master/data/VisDrone.yaml), [GlobalWheat](https://github.com/ultralytics/yolov5/blob/master/data/GlobalWheat2020.yaml)). Pass the name of the model to the `--weights` argument. Models download automatically from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases).\n\n```shell\npython train.py --data custom.yaml --weights yolov5s.pt\n                                             yolov5m.pt\n                                             yolov5l.pt\n                                             yolov5x.pt\n                                             custom_pretrained.pt\n```\n\n- **Start from Scratch.** Recommended for large datasets (i.e. [COCO](https://github.com/ultralytics/yolov5/blob/master/data/coco.yaml), [Objects365](https://github.com/ultralytics/yolov5/blob/master/data/Objects365.yaml), [OIv6](https://storage.googleapis.com/openimages/web/index.html)). Pass the model architecture yaml you are interested in, along with an empty `--weights ''` argument:\n\n```bash\npython train.py --data custom.yaml --weights '' --cfg yolov5s.yaml\n                                                      yolov5m.yaml\n                                                      yolov5l.yaml\n                                                      yolov5x.yaml\n```\n\n## Training Settings\n\nBefore modifying anything, **first train with default settings to establish a performance baseline**. A full list of train.py settings can be found in the [train.py](https://github.com/ultralytics/yolov5/blob/master/train.py) argparser.\n\n- **Epochs.** Start with 300 epochs. If this overfits early then you can reduce epochs. If overfitting does not occur after 300 epochs, train longer, i.e. 600, 1200 etc epochs.\n- **Image size.** COCO trains at native resolution of `--img 640`, though due to the high amount of small objects in the dataset it can benefit from training at higher resolutions such as `--img 1280`. If there are many small objects then custom datasets will benefit from training at native or higher resolution. Best inference results are obtained at the same `--img` as the training was run at, i.e. if you train at `--img 1280` you should also test and detect at `--img 1280`.\n- **Batch size.** Use the largest `--batch-size` that your hardware allows for. Small batch sizes produce poor batchnorm statistics and should be avoided.\n- **Hyperparameters.** Default hyperparameters are in [hyp.scratch-low.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-low.yaml). We recommend you train with default hyperparameters first before thinking of modifying any. In general, increasing augmentation hyperparameters will reduce and delay overfitting, allowing for longer trainings and higher final mAP. Reduction in loss component gain hyperparameters like `hyp['obj']` will help reduce overfitting in those specific loss components. For an automated method of optimizing these hyperparameters, see our [Hyperparameter Evolution Tutorial](https://docs.ultralytics.com/yolov5/tutorials/hyperparameter_evolution).\n\n## Further Reading\n\nIf you'd like to know more, a good place to start is Karpathy's 'Recipe for Training Neural Networks', which has great ideas for training that apply broadly across all ML domains: [http://karpathy.github.io/2019/04/25/recipe/](http://karpathy.github.io/2019/04/25/recipe/)\n\nGood luck 🍀 and let us know if you have any other questions!"
  },
  {
    "path": "docs/yolov5/tutorials/train_custom_data.md",
    "content": "---\ncomments: true\ndescription: Train your custom dataset with YOLOv5. Learn to collect, label and annotate images, and train and deploy models. Get started now.\n---\n\n📚 This guide explains how to train your own **custom dataset** with [YOLOv5](https://github.com/ultralytics/yolov5) 🚀.  \nUPDATED 26 March 2023.\n\n## Before You Start\n\nClone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a [**Python>=3.7.0**](https://www.python.org/) environment, including [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). [Models](https://github.com/ultralytics/yolov5/tree/master/models) and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).\n\n```bash\ngit clone https://github.com/ultralytics/yolov5  # clone\ncd yolov5\npip install -r requirements.txt  # install\n```\n\n## Train On Custom Data\n\n<a href=\"https://bit.ly/ultralytics_hub\" target=\"_blank\">\n<img width=\"100%\" src=\"https://github.com/ultralytics/assets/raw/main/im/integrations-loop.png\"></a>\n<br>\n<br>\n\nCreating a custom model to detect your objects is an iterative process of collecting and organizing images, labeling your objects of interest, training a model, deploying it into the wild to make predictions, and then using that deployed model to collect examples of edge cases to repeat and improve.\n\n### 1. Create Dataset\n\nYOLOv5 models must be trained on labelled data in order to learn classes of objects in that data. There are two options for creating your dataset before you start training:\n\n<details open markdown>\n<summary>Use <a href=\"https://roboflow.com/?ref=ultralytics\">Roboflow</a> to create your dataset in YOLO format</summary>\n\n### 1.1 Collect Images\n\nYour model will learn by example. Training on images similar to the ones it will see in the wild is of the utmost importance. Ideally, you will collect a wide variety of images from the same configuration (camera, angle, lighting, etc.) as you will ultimately deploy your project.\n\nIf this is not possible, you can start from [a public dataset](https://universe.roboflow.com/?ref=ultralytics) to train your initial model and then [sample images from the wild during inference](https://blog.roboflow.com/computer-vision-active-learning-tips/?ref=ultralytics) to improve your dataset and model iteratively.\n\n### 1.2 Create Labels\n\nOnce you have collected images, you will need to annotate the objects of interest to create a ground truth for your model to learn from.\n\n<p align=\"center\"><a href=\"https://app.roboflow.com/?model=yolov5&ref=ultralytics\" title=\"Create a Free Roboflow Account\"><img width=\"450\" src=\"https://uploads-ssl.webflow.com/5f6bc60e665f54545a1e52a5/6152a275ad4b4ac20cd2e21a_roboflow-annotate.gif\" /></a></p>\n\n[Roboflow Annotate](https://roboflow.com/annotate?ref=ultralytics) is a simple\nweb-based tool for managing and labeling your images with your team and exporting\nthem in [YOLOv5's annotation format](https://roboflow.com/formats/yolov5-pytorch-txt?ref=ultralytics).\n\n### 1.3 Prepare Dataset for YOLOv5\n\nWhether you [label your images with Roboflow](https://roboflow.com/annotate?ref=ultralytics) or not, you can use it to convert your dataset into YOLO format, create a YOLOv5 YAML configuration file, and host it for importing into your training script.\n\n[Create a free Roboflow account](https://app.roboflow.com/?model=yolov5&ref=ultralytics)\nand upload your dataset to a `Public` workspace, label any unannotated images,\nthen generate and export a version of your dataset in `YOLOv5 Pytorch` format.\n\nNote: YOLOv5 does online augmentation during training, so we do not recommend\napplying any augmentation steps in Roboflow for training with YOLOv5. But we\nrecommend applying the following preprocessing steps:\n\n<p align=\"center\"><img width=\"450\" src=\"https://uploads-ssl.webflow.com/5f6bc60e665f54545a1e52a5/6152a273477fccf42a0fd3d6_roboflow-preprocessing.png\" title=\"Recommended Preprocessing Steps\" /></p>\n\n* **Auto-Orient** - to strip EXIF orientation from your images.\n* **Resize (Stretch)** - to the square input size of your model (640x640 is the YOLOv5 default).\n\nGenerating a version will give you a point in time snapshot of your dataset so\nyou can always go back and compare your future model training runs against it,\neven if you add more images or change its configuration later.\n\n<p align=\"center\"><img width=\"450\" src=\"https://uploads-ssl.webflow.com/5f6bc60e665f54545a1e52a5/6152a2733fd1da943619934e_roboflow-export.png\" title=\"Export in YOLOv5 Format\" /></p>\n\nExport in `YOLOv5 Pytorch` format, then copy the snippet into your training\nscript or notebook to download your dataset.\n\n<p align=\"center\"><img width=\"450\" src=\"https://uploads-ssl.webflow.com/5f6bc60e665f54545a1e52a5/6152a273a92e4f5cb72594df_roboflow-snippet.png\" title=\"Roboflow dataset download snippet\" /></p>\n\nNow continue with `2. Select a Model`.\n</details>\n\n<details open markdown>\n<summary>Or manually prepare your dataset</summary>\n\n### 1.1 Create dataset.yaml\n\n[COCO128](https://www.kaggle.com/ultralytics/coco128) is an example small tutorial dataset composed of the first 128 images in [COCO](http://cocodataset.org/#home) train2017. These same 128 images are used for both training and validation to verify our training pipeline is capable of overfitting. [data/coco128.yaml](https://github.com/ultralytics/yolov5/blob/master/data/coco128.yaml), shown below, is the dataset config file that defines 1) the dataset root directory `path` and relative paths to `train` / `val` / `test` image directories (or *.txt files with image paths) and 2) a class `names` dictionary:\n\n```yaml\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/coco128  # dataset root dir\ntrain: images/train2017  # train images (relative to 'path') 128 images\nval: images/train2017  # val images (relative to 'path') 128 images\ntest:  # test images (optional)\n\n# Classes (80 COCO classes)\nnames:\n  0: person\n  1: bicycle\n  2: car\n  ...\n  77: teddy bear\n  78: hair drier\n  79: toothbrush\n```\n\n### 1.2 Create Labels\n\nAfter using an annotation tool to label your images, export your labels to **YOLO format**, with one `*.txt` file per image (if no objects in image, no `*.txt` file is required). The `*.txt` file specifications are:\n\n- One row per object\n- Each row is `class x_center y_center width height` format.\n- Box coordinates must be in **normalized xywh** format (from 0 - 1). If your boxes are in pixels, divide `x_center` and `width` by image width, and `y_center` and `height` by image height.\n- Class numbers are zero-indexed (start from 0).\n\n<p align=\"center\"><img width=\"750\" src=\"https://user-images.githubusercontent.com/26833433/91506361-c7965000-e886-11ea-8291-c72b98c25eec.jpg\"></p>\n\nThe label file corresponding to the above image contains 2 persons (class `0`) and a tie (class `27`):\n\n<p align=\"center\"><img width=\"428\" src=\"https://user-images.githubusercontent.com/26833433/112467037-d2568c00-8d66-11eb-8796-55402ac0d62f.png\"></p>\n\n### 1.3 Organize Directories\n\nOrganize your train and val images and labels according to the example below. YOLOv5 assumes  `/coco128` is inside a `/datasets` directory **next to** the `/yolov5` directory. **YOLOv5 locates labels automatically for each image** by replacing the last instance of `/images/` in each image path with `/labels/`. For example:\n\n```bash\n../datasets/coco128/images/im0.jpg  # image\n../datasets/coco128/labels/im0.txt  # label\n```\n\n<p align=\"center\"><img width=\"700\" src=\"https://user-images.githubusercontent.com/26833433/134436012-65111ad1-9541-4853-81a6-f19a3468b75f.png\"></p>\n</details>\n\n### 2. Select a Model\n\nSelect a pretrained model to start training from. Here we select [YOLOv5s](https://github.com/ultralytics/yolov5/blob/master/models/yolov5s.yaml), the second-smallest and fastest model available. See our README [table](https://github.com/ultralytics/yolov5#pretrained-checkpoints) for a full comparison of all models.\n\n<p align=\"center\"><img width=\"800\" alt=\"YOLOv5 Models\" src=\"https://github.com/ultralytics/yolov5/releases/download/v1.0/model_comparison.png\"></p>\n\n### 3. Train\n\nTrain a YOLOv5s model on COCO128 by specifying dataset, batch-size, image size and either pretrained `--weights yolov5s.pt` (recommended), or randomly initialized `--weights '' --cfg yolov5s.yaml` (not recommended). Pretrained weights are auto-downloaded from the [latest YOLOv5 release](https://github.com/ultralytics/yolov5/releases).\n\n```bash\npython train.py --img 640 --epochs 3 --data coco128.yaml --weights yolov5s.pt\n```\n\n!!! tip \"Tip\"\n\n    💡 Add `--cache ram` or `--cache disk` to speed up training (requires significant RAM/disk resources).  \n\n!!! tip \"Tip\"\n\n    💡 Always train from a local dataset. Mounted or network drives like Google Drive will be very slow. \n\nAll training results are saved to `runs/train/` with incrementing run directories, i.e. `runs/train/exp2`, `runs/train/exp3` etc. For more details see the Training section of our tutorial notebook. <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n\n### 4. Visualize\n\n#### Comet Logging and Visualization 🌟 NEW\n\n[Comet](https://bit.ly/yolov5-readme-comet) is now fully integrated with YOLOv5. Track and visualize model metrics in real time, save your hyperparameters, datasets, and model checkpoints, and visualize your model predictions with [Comet Custom Panels](https://bit.ly/yolov5-colab-comet-panels)! Comet makes sure you never lose track of your work and makes it easy to share results and collaborate across teams of all sizes!\n\nGetting started is easy:\n\n```shell\npip install comet_ml  # 1. install\nexport COMET_API_KEY=<Your API Key>  # 2. paste API key\npython train.py --img 640 --epochs 3 --data coco128.yaml --weights yolov5s.pt  # 3. train\n```\n\nTo learn more about all the supported Comet features for this integration, check out the [Comet Tutorial](https://docs.ultralytics.com/yolov5/tutorials/comet_logging_integration). If you'd like to learn more about Comet, head over to our [documentation](https://bit.ly/yolov5-colab-comet-docs). Get started by trying out the Comet Colab Notebook:\n[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1RG0WOQyxlDlo5Km8GogJpIEJlg_5lyYO?usp=sharing)\n\n<img width=\"1920\" alt=\"yolo-ui\" src=\"https://user-images.githubusercontent.com/26833433/202851203-164e94e1-2238-46dd-91f8-de020e9d6b41.png\">\n\n#### ClearML Logging and Automation 🌟 NEW\n\n[ClearML](https://cutt.ly/yolov5-notebook-clearml) is completely integrated into YOLOv5 to track your experimentation, manage dataset versions and even remotely execute training runs. To enable ClearML:\n\n- `pip install clearml`\n- run `clearml-init` to connect to a ClearML server (**deploy your own open-source server [here](https://github.com/allegroai/clearml-server)**, or use our free hosted server [here](https://cutt.ly/yolov5-notebook-clearml))\n\nYou'll get all the great expected features from an experiment manager: live updates, model upload, experiment comparison etc. but ClearML also tracks uncommitted changes and installed packages for example. Thanks to that ClearML Tasks (which is what we call experiments) are also reproducible on different machines! With only 1 extra line, we can schedule a YOLOv5 training task on a queue to be executed by any number of ClearML Agents (workers).\n\nYou can use ClearML Data to version your dataset and then pass it to YOLOv5 simply using its unique ID. This will help you keep track of your data without adding extra hassle. Explore the [ClearML Tutorial](https://docs.ultralytics.com/yolov5/tutorials/clearml_logging_integration) for details!\n\n<a href=\"https://cutt.ly/yolov5-notebook-clearml\">\n<img alt=\"ClearML Experiment Management UI\" src=\"https://github.com/thepycoder/clearml_screenshots/raw/main/scalars.jpg\" width=\"1280\"/></a>\n\n#### Local Logging\n\nTraining results are automatically logged with [Tensorboard](https://www.tensorflow.org/tensorboard) and [CSV](https://github.com/ultralytics/yolov5/pull/4148) loggers to `runs/train`, with a new experiment directory created for each new training as `runs/train/exp2`, `runs/train/exp3`, etc.\n\nThis directory contains train and val statistics, mosaics, labels, predictions and augmented mosaics, as well as metrics and charts including precision-recall (PR) curves and confusion matrices.\n\n<img alt=\"Local logging results\" src=\"https://github.com/ultralytics/yolov5/releases/download/v1.0/image-local_logging.jpg\" width=\"1280\"/>\n\nResults file `results.csv` is updated after each epoch, and then plotted as `results.png` (below) after training completes. You can also plot any `results.csv` file manually:\n\n```python\nfrom utils.plots import plot_results\nplot_results('path/to/results.csv')  # plot 'results.csv' as 'results.png'\n```\n\n<p align=\"center\"><img width=\"800\" alt=\"results.png\" src=\"https://github.com/ultralytics/yolov5/releases/download/v1.0/results.png\"></p>\n\n## Next Steps\n\nOnce your model is trained you can use your best checkpoint `best.pt` to:\n\n* Run [CLI](https://github.com/ultralytics/yolov5#quick-start-examples) or [Python](https://docs.ultralytics.com/yolov5/tutorials/pytorch_hub_model_loading) inference on new images and videos\n* [Validate](https://github.com/ultralytics/yolov5/blob/master/val.py) accuracy on train, val and test splits\n* [Export](https://docs.ultralytics.com/yolov5/tutorials/model_export) to TensorFlow, Keras, ONNX, TFlite, TF.js, CoreML and TensorRT formats\n* [Evolve](https://docs.ultralytics.com/yolov5/tutorials/hyperparameter_evolution) hyperparameters to improve performance\n* [Improve](https://docs.roboflow.com/adding-data/upload-api?ref=ultralytics) your model by sampling real-world images and adding them to your dataset\n\n## Environments\n\nYOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):\n\n- **Notebooks** with free GPU: <a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a> <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial/)\n- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/)\n- **Docker Image**. See [Docker Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/docker_image_quickstart_tutorial/) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n\n## Status\n\n<a href=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml\"><img src=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg\" alt=\"YOLOv5 CI\"></a>\n\nIf this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 [training](https://github.com/ultralytics/yolov5/blob/master/train.py), [validation](https://github.com/ultralytics/yolov5/blob/master/val.py), [inference](https://github.com/ultralytics/yolov5/blob/master/detect.py), [export](https://github.com/ultralytics/yolov5/blob/master/export.py) and [benchmarks](https://github.com/ultralytics/yolov5/blob/master/benchmarks.py) on macOS, Windows, and Ubuntu every 24 hours and on every commit."
  },
  {
    "path": "docs/yolov5/tutorials/transfer_learning_with_frozen_layers.md",
    "content": "---\ncomments: true\ndescription: Learn how to freeze YOLOv5 when transfer learning. Retrain a pre-trained model on new data faster and with fewer resources.\n---\n\n📚 This guide explains how to **freeze** YOLOv5 🚀 layers when **transfer learning**. Transfer learning is a useful way to quickly retrain a model on new data without having to retrain the entire network. Instead, part of the initial weights are frozen in place, and the rest of the weights are used to compute loss and are updated by the optimizer. This requires less resources than normal training and allows for faster training times, though it may also result in reductions to final trained accuracy.  \nUPDATED 25 September 2022.\n\n## Before You Start\n\nClone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a [**Python>=3.7.0**](https://www.python.org/) environment, including [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). [Models](https://github.com/ultralytics/yolov5/tree/master/models) and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).\n\n```bash\ngit clone https://github.com/ultralytics/yolov5  # clone\ncd yolov5\npip install -r requirements.txt  # install\n```\n\n## Freeze Backbone\n\nAll layers that match the train.py `freeze` list in train.py will be frozen by setting their gradients to zero before training starts.\n\n```python\n # Freeze \n freeze = [f'model.{x}.' for x in range(freeze)]  # layers to freeze \n for k, v in model.named_parameters(): \n     v.requires_grad = True  # train all layers \n     if any(x in k for x in freeze): \n         print(f'freezing {k}') \n         v.requires_grad = False \n```\n\nTo see a list of module names:\n\n```python\nfor k, v in model.named_parameters():\n    print(k)\n\n# Output\nmodel.0.conv.conv.weight\nmodel.0.conv.bn.weight\nmodel.0.conv.bn.bias\nmodel.1.conv.weight\nmodel.1.bn.weight\nmodel.1.bn.bias\nmodel.2.cv1.conv.weight\nmodel.2.cv1.bn.weight\n...\nmodel.23.m.0.cv2.bn.weight\nmodel.23.m.0.cv2.bn.bias\nmodel.24.m.0.weight\nmodel.24.m.0.bias\nmodel.24.m.1.weight\nmodel.24.m.1.bias\nmodel.24.m.2.weight\nmodel.24.m.2.bias\n```\n\nLooking at the model architecture we can see that the model backbone is layers 0-9:\n\n```yaml\n# YOLOv5 backbone \n backbone: \n   # [from, number, module, args] \n   [[-1, 1, Focus, [64, 3]],  # 0-P1/2 \n    [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4 \n    [-1, 3, BottleneckCSP, [128]], \n    [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8 \n    [-1, 9, BottleneckCSP, [256]], \n    [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16 \n    [-1, 9, BottleneckCSP, [512]], \n    [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32 \n    [-1, 1, SPP, [1024, [5, 9, 13]]], \n    [-1, 3, BottleneckCSP, [1024, False]],  # 9 \n   ] \n  \n # YOLOv5 head \n head: \n   [[-1, 1, Conv, [512, 1, 1]], \n    [-1, 1, nn.Upsample, [None, 2, 'nearest']], \n    [[-1, 6], 1, Concat, [1]],  # cat backbone P4 \n    [-1, 3, BottleneckCSP, [512, False]],  # 13 \n  \n    [-1, 1, Conv, [256, 1, 1]], \n    [-1, 1, nn.Upsample, [None, 2, 'nearest']], \n    [[-1, 4], 1, Concat, [1]],  # cat backbone P3 \n    [-1, 3, BottleneckCSP, [256, False]],  # 17 (P3/8-small) \n  \n    [-1, 1, Conv, [256, 3, 2]], \n    [[-1, 14], 1, Concat, [1]],  # cat head P4 \n    [-1, 3, BottleneckCSP, [512, False]],  # 20 (P4/16-medium) \n  \n    [-1, 1, Conv, [512, 3, 2]], \n    [[-1, 10], 1, Concat, [1]],  # cat head P5 \n    [-1, 3, BottleneckCSP, [1024, False]],  # 23 (P5/32-large) \n  \n    [[17, 20, 23], 1, Detect, [nc, anchors]],  # Detect(P3, P4, P5) \n   ] \n```\n\nso we can define the freeze list to contain all modules with 'model.0.' - 'model.9.' in their names:\n\n```bash\npython train.py --freeze 10\n```\n\n## Freeze All Layers\n\nTo freeze the full model except for the final output convolution layers in Detect(), we set freeze list to contain all modules with 'model.0.' - 'model.23.' in their names:\n\n```bash\npython train.py --freeze 24\n```\n\n## Results\n\nWe train YOLOv5m on VOC on both of the above scenarios, along with a default model (no freezing), starting from the official COCO pretrained `--weights yolov5m.pt`:\n\n```python\ntrain.py --batch 48 --weights yolov5m.pt --data voc.yaml --epochs 50 --cache --img 512 --hyp hyp.finetune.yaml\n```\n\n### Accuracy Comparison\n\nThe results show that freezing speeds up training, but reduces final accuracy slightly.\n\n![](https://user-images.githubusercontent.com/26833433/98394454-11579f80-205b-11eb-8e57-d8318e1cc2f8.png)\n\n![](https://user-images.githubusercontent.com/26833433/98394459-13216300-205b-11eb-871b-49e20691a423.png)\n\n<img width=\"922\" alt=\"Screenshot 2020-11-06 at 18 08 13\" src=\"https://user-images.githubusercontent.com/26833433/98394485-22081580-205b-11eb-9e37-1f9869fe91d8.png\">\n\n### GPU Utilization Comparison\n\nInterestingly, the more modules are frozen the less GPU memory is required to train, and the lower GPU utilization. This indicates that larger models, or models trained at larger --image-size may benefit from freezing in order to train faster.\n\n![](https://user-images.githubusercontent.com/26833433/98394920-c2f6d080-205b-11eb-9611-fd68522b4e0e.png)\n\n![](https://user-images.githubusercontent.com/26833433/98394918-bf634980-205b-11eb-948d-311036ef9325.png)\n\n## Environments\n\nYOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):\n\n- **Notebooks** with free GPU: <a href=\"https://bit.ly/yolov5-paperspace-notebook\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"></a> <a href=\"https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a> <a href=\"https://www.kaggle.com/ultralytics/yolov5\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/google_cloud_quickstart_tutorial/)\n- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/aws_quickstart_tutorial/)\n- **Docker Image**. See [Docker Quickstart Guide](https://docs.ultralytics.com/yolov5/environments/docker_image_quickstart_tutorial/) <a href=\"https://hub.docker.com/r/ultralytics/yolov5\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker\" alt=\"Docker Pulls\"></a>\n\n## Status\n\n<a href=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml\"><img src=\"https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg\" alt=\"YOLOv5 CI\"></a>\n\nIf this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 [training](https://github.com/ultralytics/yolov5/blob/master/train.py), [validation](https://github.com/ultralytics/yolov5/blob/master/val.py), [inference](https://github.com/ultralytics/yolov5/blob/master/detect.py), [export](https://github.com/ultralytics/yolov5/blob/master/export.py) and [benchmarks](https://github.com/ultralytics/yolov5/blob/master/benchmarks.py) on macOS, Windows, and Ubuntu every 24 hours and on every commit."
  },
  {
    "path": "examples/README.md",
    "content": "## Ultralytics YOLOv8 Example Applications\n\nThis repository features a collection of real-world applications and walkthroughs, provided as either Python files or notebooks. Explore the examples below to see how YOLOv8 can be integrated into various applications.\n\n### Ultralytics YOLO Example Applications\n\n| Title                                                                                                          | Format             | Contributor                                         |\n| -------------------------------------------------------------------------------------------------------------- | ------------------ | --------------------------------------------------- |\n| [YOLO ONNX Detection Inference with C++](./YOLOv8-CPP-Inference)                                               | C++/ONNX           | [Justas Bartnykas](https://github.com/JustasBart)   |\n| [YOLO OpenCV ONNX Detection Python](./YOLOv8-OpenCV-ONNX-Python)                                               | OpenCV/Python/ONNX | [Farid Inawan](https://github.com/frdteknikelektro) |\n| [YOLO .Net ONNX Detection C#](https://www.nuget.org/packages/Yolov8.Net)                                       | C# .Net            | [Samuel Stainback](https://github.com/sstainba)     |\n| [YOLOv8 on NVIDIA Jetson(TensorRT and DeepStream)](https://wiki.seeedstudio.com/YOLOv8-DeepStream-TRT-Jetson/) | Python             | [Lakshantha](https://github.com/lakshanthad)        |\n\n### How to Contribute\n\nWe welcome contributions from the community in the form of examples, applications, and guides. To contribute, please follow these steps:\n\n1. Create a pull request (PR) with the `[Example]` prefix in the title, adding your project folder to the `examples/` directory in the repository.\n1. Ensure that your project meets the following criteria:\n   - Utilizes the `ultralytics` package.\n   - Includes a `README.md` file with instructions on how to run the project.\n   - Avoids adding large assets or dependencies unless absolutely necessary.\n   - The contributor is expected to provide support for issues related to their examples.\n\nIf you have any questions or concerns about these requirements, please submit a PR, and we will be more than happy to guide you.\n"
  },
  {
    "path": "examples/YOLOv8-CPP-Inference/CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 3.5)\n\nproject(Yolov8CPPInference VERSION 0.1)\n\nset(CMAKE_INCLUDE_CURRENT_DIR ON)\n\n# CUDA\nset(CUDA_TOOLKIT_ROOT_DIR \"/usr/local/cuda\")\nfind_package(CUDA 11 REQUIRED)\n\nset(CMAKE_CUDA_STANDARD 11)\nset(CMAKE_CUDA_STANDARD_REQUIRED ON)\n# !CUDA\n\n# OpenCV\nfind_package(OpenCV REQUIRED)\ninclude_directories(${OpenCV_INCLUDE_DIRS})\n# !OpenCV\n\nset(PROJECT_SOURCES\n    main.cpp\n\n    inference.h\n    inference.cpp\n)\n\nadd_executable(Yolov8CPPInference ${PROJECT_SOURCES})\ntarget_link_libraries(Yolov8CPPInference ${OpenCV_LIBS})\n"
  },
  {
    "path": "examples/YOLOv8-CPP-Inference/README.md",
    "content": "# YOLOv8/YOLOv5 Inference C++\n\nThis example demonstrates how to perform inference using YOLOv8 and YOLOv5 models in C++ with OpenCV's DNN API.\n\n## Usage\n\n```bash\ngit clone ultralytics\ncd ultralytics\npip install .\ncd examples/cpp_\n\n# Add a **yolov8\\_.onnx** and/or **yolov5\\_.onnx** model(s) to the ultralytics folder.\n# Edit the **main.cpp** to change the **projectBasePath** to match your user.\n\n# Note that by default the CMake file will try and import the CUDA library to be used with the OpenCVs dnn (cuDNN) GPU Inference.\n# If your OpenCV build does not use CUDA/cuDNN you can remove that import call and run the example on CPU.\n\nmkdir build\ncd build\ncmake ..\nmake\n./Yolov8CPPInference\n```\n\n## Exporting YOLOv8 and YOLOv5 Models\n\nTo export YOLOv8 models:\n\n```commandline\nyolo export model=yolov8s.pt imgsz=480,640 format=onnx opset=12\n```\n\nTo export YOLOv5 models:\n\n```commandline\npython3 export.py --weights yolov5s.pt --img 480 640 --include onnx --opset 12\n```\n\nyolov8s.onnx:\n\n![image](https://user-images.githubusercontent.com/40023722/217356132-a4cecf2e-2729-4acb-b80a-6559022d7707.png)\n\nyolov5s.onnx:\n\n![image](https://user-images.githubusercontent.com/40023722/217357005-07464492-d1da-42e3-98a7-fc753f87d5e6.png)\n\nThis repository utilizes OpenCV's DNN API to run ONNX exported models of YOLOv5 and YOLOv8. In theory, it should work for YOLOv6 and YOLOv7 as well, but they have not been tested. Note that the example networks are exported with rectangular (640x480) resolutions, but any exported resolution will work. You may want to use the letterbox approach for square images, depending on your use case.\n\nThe **main** branch version uses Qt as a GUI wrapper. The primary focus here is the **Inference** class file, which demonstrates how to transpose YOLOv8 models to work as YOLOv5 models.\n"
  },
  {
    "path": "examples/YOLOv8-CPP-Inference/inference.cpp",
    "content": "#include \"inference.h\"\n\nInference::Inference(const std::string &onnxModelPath, const cv::Size &modelInputShape, const std::string &classesTxtFile, const bool &runWithCuda)\n{\n    modelPath = onnxModelPath;\n    modelShape = modelInputShape;\n    classesPath = classesTxtFile;\n    cudaEnabled = runWithCuda;\n\n    loadOnnxNetwork();\n    // loadClassesFromFile(); The classes are hard-coded for this example\n}\n\nstd::vector<Detection> Inference::runInference(const cv::Mat &input)\n{\n    cv::Mat modelInput = input;\n    if (letterBoxForSquare && modelShape.width == modelShape.height)\n        modelInput = formatToSquare(modelInput);\n\n    cv::Mat blob;\n    cv::dnn::blobFromImage(modelInput, blob, 1.0/255.0, modelShape, cv::Scalar(), true, false);\n    net.setInput(blob);\n\n    std::vector<cv::Mat> outputs;\n    net.forward(outputs, net.getUnconnectedOutLayersNames());\n\n    int rows = outputs[0].size[1];\n    int dimensions = outputs[0].size[2];\n\n    bool yolov8 = false;\n    // yolov5 has an output of shape (batchSize, 25200, 85) (Num classes + box[x,y,w,h] + confidence[c])\n    // yolov8 has an output of shape (batchSize, 84,  8400) (Num classes + box[x,y,w,h])\n    if (dimensions > rows) // Check if the shape[2] is more than shape[1] (yolov8)\n    {\n        yolov8 = true;\n        rows = outputs[0].size[2];\n        dimensions = outputs[0].size[1];\n\n        outputs[0] = outputs[0].reshape(1, dimensions);\n        cv::transpose(outputs[0], outputs[0]);\n    }\n    float *data = (float *)outputs[0].data;\n\n    float x_factor = modelInput.cols / modelShape.width;\n    float y_factor = modelInput.rows / modelShape.height;\n\n    std::vector<int> class_ids;\n    std::vector<float> confidences;\n    std::vector<cv::Rect> boxes;\n\n    for (int i = 0; i < rows; ++i)\n    {\n        if (yolov8)\n        {\n            float *classes_scores = data+4;\n\n            cv::Mat scores(1, classes.size(), CV_32FC1, classes_scores);\n            cv::Point class_id;\n            double maxClassScore;\n\n            minMaxLoc(scores, 0, &maxClassScore, 0, &class_id);\n\n            if (maxClassScore > modelScoreThreshold)\n            {\n                confidences.push_back(maxClassScore);\n                class_ids.push_back(class_id.x);\n\n                float x = data[0];\n                float y = data[1];\n                float w = data[2];\n                float h = data[3];\n\n                int left = int((x - 0.5 * w) * x_factor);\n                int top = int((y - 0.5 * h) * y_factor);\n\n                int width = int(w * x_factor);\n                int height = int(h * y_factor);\n\n                boxes.push_back(cv::Rect(left, top, width, height));\n            }\n        }\n        else // yolov5\n        {\n            float confidence = data[4];\n\n            if (confidence >= modelConfidenceThreshold)\n            {\n                float *classes_scores = data+5;\n\n                cv::Mat scores(1, classes.size(), CV_32FC1, classes_scores);\n                cv::Point class_id;\n                double max_class_score;\n\n                minMaxLoc(scores, 0, &max_class_score, 0, &class_id);\n\n                if (max_class_score > modelScoreThreshold)\n                {\n                    confidences.push_back(confidence);\n                    class_ids.push_back(class_id.x);\n\n                    float x = data[0];\n                    float y = data[1];\n                    float w = data[2];\n                    float h = data[3];\n\n                    int left = int((x - 0.5 * w) * x_factor);\n                    int top = int((y - 0.5 * h) * y_factor);\n\n                    int width = int(w * x_factor);\n                    int height = int(h * y_factor);\n\n                    boxes.push_back(cv::Rect(left, top, width, height));\n                }\n            }\n        }\n\n        data += dimensions;\n    }\n\n    std::vector<int> nms_result;\n    cv::dnn::NMSBoxes(boxes, confidences, modelScoreThreshold, modelNMSThreshold, nms_result);\n\n    std::vector<Detection> detections{};\n    for (unsigned long i = 0; i < nms_result.size(); ++i)\n    {\n        int idx = nms_result[i];\n\n        Detection result;\n        result.class_id = class_ids[idx];\n        result.confidence = confidences[idx];\n\n        std::random_device rd;\n        std::mt19937 gen(rd());\n        std::uniform_int_distribution<int> dis(100, 255);\n        result.color = cv::Scalar(dis(gen),\n                                  dis(gen),\n                                  dis(gen));\n\n        result.className = classes[result.class_id];\n        result.box = boxes[idx];\n\n        detections.push_back(result);\n    }\n\n    return detections;\n}\n\nvoid Inference::loadClassesFromFile()\n{\n    std::ifstream inputFile(classesPath);\n    if (inputFile.is_open())\n    {\n        std::string classLine;\n        while (std::getline(inputFile, classLine))\n            classes.push_back(classLine);\n        inputFile.close();\n    }\n}\n\nvoid Inference::loadOnnxNetwork()\n{\n    net = cv::dnn::readNetFromONNX(modelPath);\n    if (cudaEnabled)\n    {\n        std::cout << \"\\nRunning on CUDA\" << std::endl;\n        net.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);\n        net.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);\n    }\n    else\n    {\n        std::cout << \"\\nRunning on CPU\" << std::endl;\n        net.setPreferableBackend(cv::dnn::DNN_BACKEND_OPENCV);\n        net.setPreferableTarget(cv::dnn::DNN_TARGET_CPU);\n    }\n}\n\ncv::Mat Inference::formatToSquare(const cv::Mat &source)\n{\n    int col = source.cols;\n    int row = source.rows;\n    int _max = MAX(col, row);\n    cv::Mat result = cv::Mat::zeros(_max, _max, CV_8UC3);\n    source.copyTo(result(cv::Rect(0, 0, col, row)));\n    return result;\n}\n"
  },
  {
    "path": "examples/YOLOv8-CPP-Inference/inference.h",
    "content": "#ifndef INFERENCE_H\n#define INFERENCE_H\n\n// Cpp native\n#include <fstream>\n#include <vector>\n#include <string>\n#include <random>\n\n// OpenCV / DNN / Inference\n#include <opencv2/imgproc.hpp>\n#include <opencv2/opencv.hpp>\n#include <opencv2/dnn.hpp>\n\nstruct Detection\n{\n    int class_id{0};\n    std::string className{};\n    float confidence{0.0};\n    cv::Scalar color{};\n    cv::Rect box{};\n};\n\nclass Inference\n{\npublic:\n    Inference(const std::string &onnxModelPath, const cv::Size &modelInputShape = {640, 640}, const std::string &classesTxtFile = \"\", const bool &runWithCuda = true);\n    std::vector<Detection> runInference(const cv::Mat &input);\n\nprivate:\n    void loadClassesFromFile();\n    void loadOnnxNetwork();\n    cv::Mat formatToSquare(const cv::Mat &source);\n\n    std::string modelPath{};\n    std::string classesPath{};\n    bool cudaEnabled{};\n\n    std::vector<std::string> classes{\"person\", \"bicycle\", \"car\", \"motorcycle\", \"airplane\", \"bus\", \"train\", \"truck\", \"boat\", \"traffic light\", \"fire hydrant\", \"stop sign\", \"parking meter\", \"bench\", \"bird\", \"cat\", \"dog\", \"horse\", \"sheep\", \"cow\", \"elephant\", \"bear\", \"zebra\", \"giraffe\", \"backpack\", \"umbrella\", \"handbag\", \"tie\", \"suitcase\", \"frisbee\", \"skis\", \"snowboard\", \"sports ball\", \"kite\", \"baseball bat\", \"baseball glove\", \"skateboard\", \"surfboard\", \"tennis racket\", \"bottle\", \"wine glass\", \"cup\", \"fork\", \"knife\", \"spoon\", \"bowl\", \"banana\", \"apple\", \"sandwich\", \"orange\", \"broccoli\", \"carrot\", \"hot dog\", \"pizza\", \"donut\", \"cake\", \"chair\", \"couch\", \"potted plant\", \"bed\", \"dining table\", \"toilet\", \"tv\", \"laptop\", \"mouse\", \"remote\", \"keyboard\", \"cell phone\", \"microwave\", \"oven\", \"toaster\", \"sink\", \"refrigerator\", \"book\", \"clock\", \"vase\", \"scissors\", \"teddy bear\", \"hair drier\", \"toothbrush\"};\n\n    cv::Size2f modelShape{};\n\n    float modelConfidenceThreshold {0.25};\n    float modelScoreThreshold      {0.45};\n    float modelNMSThreshold        {0.50};\n\n    bool letterBoxForSquare = true;\n\n    cv::dnn::Net net;\n};\n\n#endif // INFERENCE_H\n"
  },
  {
    "path": "examples/YOLOv8-CPP-Inference/main.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <getopt.h>\n\n#include <opencv2/opencv.hpp>\n\n#include \"inference.h\"\n\nusing namespace std;\nusing namespace cv;\n\nint main(int argc, char **argv)\n{\n    std::string projectBasePath = \"/home/user/ultralytics\"; // Set your ultralytics base path\n\n    bool runOnGPU = true;\n\n    //\n    // Pass in either:\n    //\n    // \"yolov8s.onnx\" or \"yolov5s.onnx\"\n    //\n    // To run Inference with yolov8/yolov5 (ONNX)\n    //\n\n    // Note that in this example the classes are hard-coded and 'classes.txt' is a place holder.\n    Inference inf(projectBasePath + \"/yolov8s.onnx\", cv::Size(640, 480), \"classes.txt\", runOnGPU);\n\n    std::vector<std::string> imageNames;\n    imageNames.push_back(projectBasePath + \"/ultralytics/assets/bus.jpg\");\n    imageNames.push_back(projectBasePath + \"/ultralytics/assets/zidane.jpg\");\n\n    for (int i = 0; i < imageNames.size(); ++i)\n    {\n        cv::Mat frame = cv::imread(imageNames[i]);\n\n        // Inference starts here...\n        std::vector<Detection> output = inf.runInference(frame);\n\n        int detections = output.size();\n        std::cout << \"Number of detections:\" << detections << std::endl;\n\n        for (int i = 0; i < detections; ++i)\n        {\n            Detection detection = output[i];\n\n            cv::Rect box = detection.box;\n            cv::Scalar color = detection.color;\n\n            // Detection box\n            cv::rectangle(frame, box, color, 2);\n\n            // Detection box text\n            std::string classString = detection.className + ' ' + std::to_string(detection.confidence).substr(0, 4);\n            cv::Size textSize = cv::getTextSize(classString, cv::FONT_HERSHEY_DUPLEX, 1, 2, 0);\n            cv::Rect textBox(box.x, box.y - 40, textSize.width + 10, textSize.height + 20);\n\n            cv::rectangle(frame, textBox, color, cv::FILLED);\n            cv::putText(frame, classString, cv::Point(box.x + 5, box.y - 10), cv::FONT_HERSHEY_DUPLEX, 1, cv::Scalar(0, 0, 0), 2, 0);\n        }\n        // Inference ends here...\n\n        // This is only for preview purposes\n        float scale = 0.8;\n        cv::resize(frame, frame, cv::Size(frame.cols*scale, frame.rows*scale));\n        cv::imshow(\"Inference\", frame);\n\n        cv::waitKey(-1);\n    }\n}\n"
  },
  {
    "path": "examples/YOLOv8-OpenCV-ONNX-Python/README.md",
    "content": "# YOLOv8 - OpenCV\n\nImplementation YOLOv8 on OpenCV using ONNX Format.\n\nJust simply clone and run\n\n```bash\npip install -r requirements.txt\npython main.py --model yolov8n.onnx --img image.jpg\n```\n\nIf you start from scratch:\n\n```bash\npip install ultralytics\nyolo export model=yolov8n.pt imgsz=640 format=onnx opset=12\n```\n\n_\\*Make sure to include \"opset=12\"_\n"
  },
  {
    "path": "examples/YOLOv8-OpenCV-ONNX-Python/main.py",
    "content": "import argparse\n\nimport cv2.dnn\nimport numpy as np\n\nfrom ultralytics.yolo.utils import ROOT, yaml_load\nfrom ultralytics.yolo.utils.checks import check_yaml\n\nCLASSES = yaml_load(check_yaml('coco128.yaml'))['names']\n\ncolors = np.random.uniform(0, 255, size=(len(CLASSES), 3))\n\n\ndef draw_bounding_box(img, class_id, confidence, x, y, x_plus_w, y_plus_h):\n    label = f'{CLASSES[class_id]} ({confidence:.2f})'\n    color = colors[class_id]\n    cv2.rectangle(img, (x, y), (x_plus_w, y_plus_h), color, 2)\n    cv2.putText(img, label, (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)\n\n\ndef main(onnx_model, input_image):\n    model: cv2.dnn.Net = cv2.dnn.readNetFromONNX(onnx_model)\n    original_image: np.ndarray = cv2.imread(input_image)\n    [height, width, _] = original_image.shape\n    length = max((height, width))\n    image = np.zeros((length, length, 3), np.uint8)\n    image[0:height, 0:width] = original_image\n    scale = length / 640\n\n    blob = cv2.dnn.blobFromImage(image, scalefactor=1 / 255, size=(640, 640), swapRB=True)\n    model.setInput(blob)\n    outputs = model.forward()\n\n    outputs = np.array([cv2.transpose(outputs[0])])\n    rows = outputs.shape[1]\n\n    boxes = []\n    scores = []\n    class_ids = []\n\n    for i in range(rows):\n        classes_scores = outputs[0][i][4:]\n        (minScore, maxScore, minClassLoc, (x, maxClassIndex)) = cv2.minMaxLoc(classes_scores)\n        if maxScore >= 0.25:\n            box = [\n                outputs[0][i][0] - (0.5 * outputs[0][i][2]), outputs[0][i][1] - (0.5 * outputs[0][i][3]),\n                outputs[0][i][2], outputs[0][i][3]]\n            boxes.append(box)\n            scores.append(maxScore)\n            class_ids.append(maxClassIndex)\n\n    result_boxes = cv2.dnn.NMSBoxes(boxes, scores, 0.25, 0.45, 0.5)\n\n    detections = []\n    for i in range(len(result_boxes)):\n        index = result_boxes[i]\n        box = boxes[index]\n        detection = {\n            'class_id': class_ids[index],\n            'class_name': CLASSES[class_ids[index]],\n            'confidence': scores[index],\n            'box': box,\n            'scale': scale}\n        detections.append(detection)\n        draw_bounding_box(original_image, class_ids[index], scores[index], round(box[0] * scale), round(box[1] * scale),\n                          round((box[0] + box[2]) * scale), round((box[1] + box[3]) * scale))\n\n    cv2.imshow('image', original_image)\n    cv2.waitKey(0)\n    cv2.destroyAllWindows()\n\n    return detections\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('--model', default='yolov8n.onnx', help='Input your onnx model.')\n    parser.add_argument('--img', default=str(ROOT / 'assets/bus.jpg'), help='Path to input image.')\n    args = parser.parse_args()\n    main(args.model, args.img)\n"
  },
  {
    "path": "examples/hub.ipynb",
    "content": "{\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0,\n  \"metadata\": {\n    \"colab\": {\n      \"name\": \"Ultralytics HUB\",\n      \"provenance\": []\n    },\n    \"kernelspec\": {\n      \"name\": \"python3\",\n      \"display_name\": \"Python 3\"\n    },\n    \"language_info\": {\n      \"name\": \"python\"\n    },\n    \"accelerator\": \"GPU\"\n  },\n  \"cells\": [\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"FIzICjaph_Wy\"\n      },\n      \"source\": [\n        \"<a align=\\\"center\\\" href=\\\"https://hub.ultralytics.com\\\" target=\\\"_blank\\\">\\n\",\n        \"<img width=\\\"1024\\\", src=\\\"https://github.com/ultralytics/assets/raw/main/im/ultralytics-hub.png\\\"></a>\\n\",\n        \"\\n\",\n        \"<div align=\\\"center\\\">\\n\",\n        \"  <a href=\\\"https://github.com/ultralytics/ultralytics/actions/workflows/ci.yaml\\\">\\n\",\n        \"    <img src=\\\"https://github.com/ultralytics/ultralytics/actions/workflows/ci.yaml/badge.svg\\\" alt=\\\"CI CPU\\\"></a>\\n\",\n        \"  <a href=\\\"https://colab.research.google.com/github/ultralytics/ultralytics/blob/main/examples/hub.ipynb\\\">\\n\",\n        \"    <img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"></a>\\n\",\n        \"\\n\",\n        \"Welcome to the [Ultralytics](https://ultralytics.com/) HUB notebook! \\n\",\n        \"\\n\",\n        \"This notebook allows you to train [YOLOv5](https://github.com/ultralytics/yolov5) and [YOLOv8](https://github.com/ultralytics/ultralytics) 🚀 models using [HUB](https://hub.ultralytics.com/). Please browse the YOLOv8 <a href=\\\"https://docs.ultralytics.com\\\">Docs</a> for details, raise an issue on <a href=\\\"https://github.com/ultralytics/ultralytics/issues/new/choose\\\">GitHub</a> for support, and join our <a href=\\\"https://discord.gg/n6cFeSPZdD\\\">Discord</a> community for questions and discussions!\\n\",\n        \"</div>\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"eRQ2ow94MiOv\"\n      },\n      \"source\": [\n        \"# Setup\\n\",\n        \"\\n\",\n        \"Pip install `ultralytics` and [dependencies](https://github.com/ultralytics/ultralytics/blob/main/requirements.txt) and check software and hardware.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"metadata\": {\n        \"id\": \"FyDnXd-n4c7Y\",\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"outputId\": \"22dcbc27-9c6f-44fb-9745-620431f93793\"\n      },\n      \"source\": [\n        \"%pip install ultralytics  # install\\n\",\n        \"from ultralytics import YOLO, checks, hub\\n\",\n        \"checks()  # checks\"\n      ],\n      \"execution_count\": null,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"name\": \"stderr\",\n          \"text\": [\n            \"Ultralytics YOLOv8.0.64 🚀 Python-3.9.16 torch-2.0.0+cu118 CUDA:0 (Tesla T4, 15102MiB)\\n\",\n            \"Setup complete ✅ (2 CPUs, 12.7 GB RAM, 28.3/166.8 GB disk)\\n\"\n          ]\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"cQ9BwaAqxAm4\"\n      },\n      \"source\": [\n        \"# Start\\n\",\n        \"\\n\",\n        \"Login with your [API key](https://hub.ultralytics.com/settings?tab=api+keys), select your YOLO 🚀 model and start training!\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"metadata\": {\n        \"id\": \"XSlZaJ9Iw_iZ\"\n      },\n      \"source\": [\n        \"hub.login('API_KEY')  # use your API key\\n\",\n        \"\\n\",\n        \"model = YOLO('https://hub.ultralytics.com/MODEL_ID')  # use your model URL\\n\",\n        \"model.train()  # train model\"\n      ],\n      \"execution_count\": null,\n      \"outputs\": []\n    }\n  ]\n}\n"
  },
  {
    "path": "examples/tutorial.ipynb",
    "content": "{\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0,\n  \"metadata\": {\n    \"colab\": {\n      \"name\": \"YOLOv8 Tutorial\",\n      \"provenance\": [],\n      \"toc_visible\": true\n    },\n    \"kernelspec\": {\n      \"name\": \"python3\",\n      \"display_name\": \"Python 3\"\n    },\n    \"accelerator\": \"GPU\"\n  },\n  \"cells\": [\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"t6MPjfT5NrKQ\"\n      },\n      \"source\": [\n        \"<div align=\\\"center\\\">\\n\",\n        \"\\n\",\n        \"  <a href=\\\"https://ultralytics.com/yolov8\\\" target=\\\"_blank\\\">\\n\",\n        \"    <img width=\\\"1024\\\", src=\\\"https://raw.githubusercontent.com/ultralytics/assets/main/yolov8/banner-yolov8.png\\\"></a>\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"<br>\\n\",\n        \"  <a href=\\\"https://console.paperspace.com/github/ultralytics/ultralytics\\\"><img src=\\\"https://assets.paperspace.io/img/gradient-badge.svg\\\" alt=\\\"Run on Gradient\\\"/></a>\\n\",\n        \"  <a href=\\\"https://colab.research.google.com/github/ultralytics/ultralytics/blob/main/examples/tutorial.ipynb\\\"><img src=\\\"https://colab.research.google.com/assets/colab-badge.svg\\\" alt=\\\"Open In Colab\\\"></a>\\n\",\n        \"  <a href=\\\"https://www.kaggle.com/ultralytics/yolov8\\\"><img src=\\\"https://kaggle.com/static/images/open-in-kaggle.svg\\\" alt=\\\"Open In Kaggle\\\"></a>\\n\",\n        \"<br>\\n\",\n        \"\\n\",\n        \"Welcome to the Ultralytics YOLOv8 🚀 notebook! <a href=\\\"https://github.com/ultralytics/ultralytics\\\">YOLOv8</a> is the latest version of the YOLO (You Only Look Once) AI models developed by <a href=\\\"https://ultralytics.com\\\">Ultralytics</a>. This notebook serves as the starting point for exploring the various resources available to help you get started with YOLOv8 and understand its features and capabilities.\\n\",\n        \"\\n\",\n        \"YOLOv8 models are fast, accurate, and easy to use, making them ideal for various object detection and image segmentation tasks. They can be trained on large datasets and run on diverse hardware platforms, from CPUs to GPUs.\\n\",\n        \"\\n\",\n        \"We hope that the resources in this notebook will help you get the most out of YOLOv8. Please browse the YOLOv8 <a href=\\\"https://docs.ultralytics.com/\\\">Docs</a> for details, raise an issue on <a href=\\\"https://github.com/ultralytics/ultralytics\\\">GitHub</a> for support, and join our <a href=\\\"https://discord.gg/n6cFeSPZdD\\\">Discord</a> community for questions and discussions!\\n\",\n        \"\\n\",\n        \"</div>\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"7mGmQbAO5pQb\"\n      },\n      \"source\": [\n        \"# Setup\\n\",\n        \"\\n\",\n        \"Pip install `ultralytics` and [dependencies](https://github.com/ultralytics/ultralytics/blob/main/requirements.txt) and check software and hardware.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"metadata\": {\n        \"id\": \"wbvMlHd_QwMG\",\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"outputId\": \"2ea6e0b9-1a62-4355-c246-5e8b7b1dafff\"\n      },\n      \"source\": [\n        \"%pip install ultralytics\\n\",\n        \"import ultralytics\\n\",\n        \"ultralytics.checks()\"\n      ],\n      \"execution_count\": 1,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"name\": \"stderr\",\n          \"text\": [\n            \"Ultralytics YOLOv8.0.71 🚀 Python-3.9.16 torch-2.0.0+cu118 CUDA:0 (Tesla T4, 15102MiB)\\n\",\n            \"Setup complete ✅ (2 CPUs, 12.7 GB RAM, 23.3/166.8 GB disk)\\n\"\n          ]\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"4JnkELT0cIJg\"\n      },\n      \"source\": [\n        \"# 1. Predict\\n\",\n        \"\\n\",\n        \"YOLOv8 may be used directly in the Command Line Interface (CLI) with a `yolo` command for a variety of tasks and modes and accepts additional arguments, i.e. `imgsz=640`. See a full list of available `yolo` [arguments](https://docs.ultralytics.com/usage/cfg/) and other details in the [YOLOv8 Predict Docs](https://docs.ultralytics.com/modes/train/).\\n\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"metadata\": {\n        \"id\": \"zR9ZbuQCH7FX\",\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"outputId\": \"c578afbd-47cd-4d11-beec-8b5c31fcfba8\"\n      },\n      \"source\": [\n        \"# Run inference on an image with YOLOv8n\\n\",\n        \"!yolo predict model=yolov8n.pt source='https://ultralytics.com/images/zidane.jpg'\"\n      ],\n      \"execution_count\": 2,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"name\": \"stdout\",\n          \"text\": [\n            \"Downloading https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt to yolov8n.pt...\\n\",\n            \"100% 6.23M/6.23M [00:00<00:00, 195MB/s]\\n\",\n            \"Ultralytics YOLOv8.0.71 🚀 Python-3.9.16 torch-2.0.0+cu118 CUDA:0 (Tesla T4, 15102MiB)\\n\",\n            \"YOLOv8n summary (fused): 168 layers, 3151904 parameters, 0 gradients, 8.7 GFLOPs\\n\",\n            \"\\n\",\n            \"Downloading https://ultralytics.com/images/zidane.jpg to zidane.jpg...\\n\",\n            \"100% 165k/165k [00:00<00:00, 51.7MB/s]\\n\",\n            \"image 1/1 /content/zidane.jpg: 384x640 2 persons, 1 tie, 60.9ms\\n\",\n            \"Speed: 0.6ms preprocess, 60.9ms inference, 301.3ms postprocess per image at shape (1, 3, 640, 640)\\n\",\n            \"Results saved to \\u001b[1mruns/detect/predict\\u001b[0m\\n\"\n          ]\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"hkAzDWJ7cWTr\"\n      },\n      \"source\": [\n        \"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\\n\",\n        \"<img align=\\\"left\\\" src=\\\"https://user-images.githubusercontent.com/26833433/212889447-69e5bdf1-5800-4e29-835e-2ed2336dede2.jpg\\\" width=\\\"600\\\">\"\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"0eq1SMWl6Sfn\"\n      },\n      \"source\": [\n        \"# 2. Val\\n\",\n        \"Validate a model's accuracy on the [COCO](https://cocodataset.org/#home) dataset's `val` or `test` splits. The latest YOLOv8 [models](https://github.com/ultralytics/ultralytics#models) are downloaded automatically the first time they are used. See [YOLOv8 Val Docs](https://docs.ultralytics.com/modes/val/) for more information.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"metadata\": {\n        \"id\": \"WQPtK1QYVaD_\"\n      },\n      \"source\": [\n        \"# Download COCO val\\n\",\n        \"import torch\\n\",\n        \"torch.hub.download_url_to_file('https://ultralytics.com/assets/coco2017val.zip', 'tmp.zip')  # download (780M - 5000 images)\\n\",\n        \"!unzip -q tmp.zip -d datasets && rm tmp.zip  # unzip\"\n      ],\n      \"execution_count\": null,\n      \"outputs\": []\n    },\n    {\n      \"cell_type\": \"code\",\n      \"metadata\": {\n        \"id\": \"X58w8JLpMnjH\",\n        \"outputId\": \"3e5a9c48-8eba-45eb-d92f-8456cf94b60e\",\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        }\n      },\n      \"source\": [\n        \"# Validate YOLOv8n on COCO128 val\\n\",\n        \"!yolo val model=yolov8n.pt data=coco128.yaml\"\n      ],\n      \"execution_count\": 3,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"name\": \"stdout\",\n          \"text\": [\n            \"Ultralytics YOLOv8.0.71 🚀 Python-3.9.16 torch-2.0.0+cu118 CUDA:0 (Tesla T4, 15102MiB)\\n\",\n            \"YOLOv8n summary (fused): 168 layers, 3151904 parameters, 0 gradients, 8.7 GFLOPs\\n\",\n            \"\\n\",\n            \"Dataset 'coco128.yaml' images not found ⚠️, missing paths ['/content/datasets/coco128/images/train2017']\\n\",\n            \"Downloading https://ultralytics.com/assets/coco128.zip to /content/datasets/coco128.zip...\\n\",\n            \"100% 6.66M/6.66M [00:01<00:00, 6.80MB/s]\\n\",\n            \"Unzipping /content/datasets/coco128.zip to /content/datasets...\\n\",\n            \"Dataset download success ✅ (2.2s), saved to \\u001b[1m/content/datasets\\u001b[0m\\n\",\n            \"\\n\",\n            \"Downloading https://ultralytics.com/assets/Arial.ttf to /root/.config/Ultralytics/Arial.ttf...\\n\",\n            \"100% 755k/755k [00:00<00:00, 107MB/s]\\n\",\n            \"\\u001b[34m\\u001b[1mval: \\u001b[0mScanning /content/datasets/coco128/labels/train2017... 126 images, 2 backgrounds, 80 corrupt: 100% 128/128 [00:00<00:00, 1183.28it/s]\\n\",\n            \"\\u001b[34m\\u001b[1mval: \\u001b[0mNew cache created: /content/datasets/coco128/labels/train2017.cache\\n\",\n            \"                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100% 8/8 [00:12<00:00,  1.54s/it]\\n\",\n            \"                   all        128        929       0.64      0.537      0.605      0.446\\n\",\n            \"                person        128        254      0.797      0.677      0.764      0.538\\n\",\n            \"               bicycle        128          6      0.514      0.333      0.315      0.264\\n\",\n            \"                   car        128         46      0.813      0.217      0.273      0.168\\n\",\n            \"            motorcycle        128          5      0.687      0.887      0.898      0.685\\n\",\n            \"              airplane        128          6       0.82      0.833      0.927      0.675\\n\",\n            \"                   bus        128          7      0.491      0.714      0.728      0.671\\n\",\n            \"                 train        128          3      0.534      0.667      0.706      0.604\\n\",\n            \"                 truck        128         12          1      0.332      0.473      0.297\\n\",\n            \"                  boat        128          6      0.226      0.167      0.316      0.134\\n\",\n            \"         traffic light        128         14      0.734        0.2      0.202      0.139\\n\",\n            \"             stop sign        128          2          1      0.992      0.995      0.701\\n\",\n            \"                 bench        128          9      0.839      0.582       0.62      0.365\\n\",\n            \"                  bird        128         16      0.921      0.728      0.864       0.51\\n\",\n            \"                   cat        128          4      0.875          1      0.995      0.791\\n\",\n            \"                   dog        128          9      0.603      0.889      0.785      0.585\\n\",\n            \"                 horse        128          2      0.597          1      0.995      0.518\\n\",\n            \"              elephant        128         17      0.849      0.765        0.9      0.679\\n\",\n            \"                  bear        128          1      0.593          1      0.995      0.995\\n\",\n            \"                 zebra        128          4      0.848          1      0.995      0.965\\n\",\n            \"               giraffe        128          9       0.72          1      0.951      0.722\\n\",\n            \"              backpack        128          6      0.589      0.333      0.376      0.232\\n\",\n            \"              umbrella        128         18      0.804        0.5      0.643      0.414\\n\",\n            \"               handbag        128         19      0.424     0.0526      0.165     0.0889\\n\",\n            \"                   tie        128          7      0.804      0.714      0.674      0.476\\n\",\n            \"              suitcase        128          4      0.635      0.883      0.745      0.534\\n\",\n            \"               frisbee        128          5      0.675        0.8      0.759      0.688\\n\",\n            \"                  skis        128          1      0.567          1      0.995      0.497\\n\",\n            \"             snowboard        128          7      0.742      0.714      0.747        0.5\\n\",\n            \"           sports ball        128          6      0.716      0.433      0.485      0.278\\n\",\n            \"                  kite        128         10      0.817       0.45      0.569      0.184\\n\",\n            \"          baseball bat        128          4      0.551       0.25      0.353      0.175\\n\",\n            \"        baseball glove        128          7      0.624      0.429      0.429      0.293\\n\",\n            \"            skateboard        128          5      0.846        0.6        0.6       0.41\\n\",\n            \"         tennis racket        128          7      0.726      0.387      0.487       0.33\\n\",\n            \"                bottle        128         18      0.448      0.389      0.376      0.208\\n\",\n            \"            wine glass        128         16      0.743      0.362      0.584      0.333\\n\",\n            \"                   cup        128         36       0.58      0.278      0.404       0.29\\n\",\n            \"                  fork        128          6      0.527      0.167      0.246      0.184\\n\",\n            \"                 knife        128         16      0.564        0.5       0.59       0.36\\n\",\n            \"                 spoon        128         22      0.597      0.182      0.328       0.19\\n\",\n            \"                  bowl        128         28      0.648      0.643      0.618      0.491\\n\",\n            \"                banana        128          1          0          0      0.124     0.0379\\n\",\n            \"              sandwich        128          2      0.249        0.5      0.308      0.308\\n\",\n            \"                orange        128          4          1       0.31      0.995      0.623\\n\",\n            \"              broccoli        128         11      0.374      0.182      0.249      0.203\\n\",\n            \"                carrot        128         24      0.648      0.458      0.572      0.362\\n\",\n            \"               hot dog        128          2      0.351      0.553      0.745      0.721\\n\",\n            \"                 pizza        128          5      0.644          1      0.995      0.843\\n\",\n            \"                 donut        128         14      0.657          1       0.94      0.864\\n\",\n            \"                  cake        128          4      0.618          1      0.945      0.845\\n\",\n            \"                 chair        128         35      0.506      0.514      0.442      0.239\\n\",\n            \"                 couch        128          6      0.463        0.5      0.706      0.555\\n\",\n            \"          potted plant        128         14       0.65      0.643      0.711      0.472\\n\",\n            \"                   bed        128          3      0.698      0.667      0.789      0.625\\n\",\n            \"          dining table        128         13      0.432      0.615      0.485      0.366\\n\",\n            \"                toilet        128          2      0.615        0.5      0.695      0.676\\n\",\n            \"                    tv        128          2      0.373       0.62      0.745      0.696\\n\",\n            \"                laptop        128          3          1          0      0.451      0.361\\n\",\n            \"                 mouse        128          2          1          0     0.0625    0.00625\\n\",\n            \"                remote        128          8      0.843        0.5      0.605      0.529\\n\",\n            \"            cell phone        128          8          0          0     0.0549     0.0393\\n\",\n            \"             microwave        128          3      0.435      0.667      0.806      0.718\\n\",\n            \"                  oven        128          5      0.412        0.4      0.339       0.27\\n\",\n            \"                  sink        128          6       0.35      0.167      0.182      0.129\\n\",\n            \"          refrigerator        128          5      0.589        0.4      0.604      0.452\\n\",\n            \"                  book        128         29      0.629      0.103      0.346      0.178\\n\",\n            \"                 clock        128          9      0.788       0.83      0.875       0.74\\n\",\n            \"                  vase        128          2      0.376          1      0.828      0.795\\n\",\n            \"              scissors        128          1          1          0      0.249     0.0746\\n\",\n            \"            teddy bear        128         21      0.877      0.333      0.591      0.394\\n\",\n            \"            toothbrush        128          5      0.743        0.6      0.638      0.374\\n\",\n            \"Speed: 5.3ms preprocess, 20.1ms inference, 0.0ms loss, 11.7ms postprocess per image\\n\",\n            \"Results saved to \\u001b[1mruns/detect/val\\u001b[0m\\n\"\n          ]\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"ZY2VXXXu74w5\"\n      },\n      \"source\": [\n        \"# 3. Train\\n\",\n        \"\\n\",\n        \"<p align=\\\"\\\"><a href=\\\"https://bit.ly/ultralytics_hub\\\"><img width=\\\"1000\\\" src=\\\"https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png\\\"/></a></p>\\n\",\n        \"\\n\",\n        \"Train YOLOv8 on [Detect](https://docs.ultralytics.com/tasks/detect/), [Segment](https://docs.ultralytics.com/tasks/segment/), [Classify](https://docs.ultralytics.com/tasks/classify/) and [Pose](https://docs.ultralytics.com/tasks/pose/) datasets. See [YOLOv8 Train Docs](https://docs.ultralytics.com/modes/train/) for more information.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"metadata\": {\n        \"id\": \"1NcFxRcFdJ_O\",\n        \"outputId\": \"b60a1f74-8035-4f9e-b4b0-604f9cf76231\",\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        }\n      },\n      \"source\": [\n        \"# Train YOLOv8n on COCO128 for 3 epochs\\n\",\n        \"!yolo train model=yolov8n.pt data=coco128.yaml epochs=3 imgsz=640\"\n      ],\n      \"execution_count\": 4,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"name\": \"stdout\",\n          \"text\": [\n            \"Ultralytics YOLOv8.0.71 🚀 Python-3.9.16 torch-2.0.0+cu118 CUDA:0 (Tesla T4, 15102MiB)\\n\",\n            \"\\u001b[34m\\u001b[1myolo/engine/trainer: \\u001b[0mtask=detect, mode=train, model=yolov8n.pt, data=coco128.yaml, epochs=3, patience=50, batch=16, imgsz=640, save=True, save_period=-1, cache=False, device=None, workers=8, project=None, name=None, exist_ok=False, pretrained=False, optimizer=SGD, verbose=True, seed=0, deterministic=True, single_cls=False, image_weights=False, rect=False, cos_lr=False, close_mosaic=0, resume=False, amp=True, overlap_mask=True, mask_ratio=4, dropout=0.0, val=True, split=val, save_json=False, save_hybrid=False, conf=None, iou=0.7, max_det=300, half=False, dnn=False, plots=True, source=None, show=False, save_txt=False, save_conf=False, save_crop=False, show_labels=True, show_conf=True, vid_stride=1, line_width=3, visualize=False, augment=False, agnostic_nms=False, classes=None, retina_masks=False, boxes=True, format=torchscript, keras=False, optimize=False, int8=False, dynamic=False, simplify=False, opset=None, workspace=4, nms=False, lr0=0.01, lrf=0.01, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=7.5, cls=0.5, dfl=1.5, pose=12.0, kobj=1.0, label_smoothing=0.0, nbs=64, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, mosaic=1.0, mixup=0.0, copy_paste=0.0, cfg=None, v5loader=False, tracker=botsort.yaml, save_dir=runs/detect/train\\n\",\n            \"\\n\",\n            \"                   from  n    params  module                                       arguments                     \\n\",\n            \"  0                  -1  1       464  ultralytics.nn.modules.Conv                  [3, 16, 3, 2]                 \\n\",\n            \"  1                  -1  1      4672  ultralytics.nn.modules.Conv                  [16, 32, 3, 2]                \\n\",\n            \"  2                  -1  1      7360  ultralytics.nn.modules.C2f                   [32, 32, 1, True]             \\n\",\n            \"  3                  -1  1     18560  ultralytics.nn.modules.Conv                  [32, 64, 3, 2]                \\n\",\n            \"  4                  -1  2     49664  ultralytics.nn.modules.C2f                   [64, 64, 2, True]             \\n\",\n            \"  5                  -1  1     73984  ultralytics.nn.modules.Conv                  [64, 128, 3, 2]               \\n\",\n            \"  6                  -1  2    197632  ultralytics.nn.modules.C2f                   [128, 128, 2, True]           \\n\",\n            \"  7                  -1  1    295424  ultralytics.nn.modules.Conv                  [128, 256, 3, 2]              \\n\",\n            \"  8                  -1  1    460288  ultralytics.nn.modules.C2f                   [256, 256, 1, True]           \\n\",\n            \"  9                  -1  1    164608  ultralytics.nn.modules.SPPF                  [256, 256, 5]                 \\n\",\n            \" 10                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']          \\n\",\n            \" 11             [-1, 6]  1         0  ultralytics.nn.modules.Concat                [1]                           \\n\",\n            \" 12                  -1  1    148224  ultralytics.nn.modules.C2f                   [384, 128, 1]                 \\n\",\n            \" 13                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']          \\n\",\n            \" 14             [-1, 4]  1         0  ultralytics.nn.modules.Concat                [1]                           \\n\",\n            \" 15                  -1  1     37248  ultralytics.nn.modules.C2f                   [192, 64, 1]                  \\n\",\n            \" 16                  -1  1     36992  ultralytics.nn.modules.Conv                  [64, 64, 3, 2]                \\n\",\n            \" 17            [-1, 12]  1         0  ultralytics.nn.modules.Concat                [1]                           \\n\",\n            \" 18                  -1  1    123648  ultralytics.nn.modules.C2f                   [192, 128, 1]                 \\n\",\n            \" 19                  -1  1    147712  ultralytics.nn.modules.Conv                  [128, 128, 3, 2]              \\n\",\n            \" 20             [-1, 9]  1         0  ultralytics.nn.modules.Concat                [1]                           \\n\",\n            \" 21                  -1  1    493056  ultralytics.nn.modules.C2f                   [384, 256, 1]                 \\n\",\n            \" 22        [15, 18, 21]  1    897664  ultralytics.nn.modules.Detect                [80, [64, 128, 256]]          \\n\",\n            \"Model summary: 225 layers, 3157200 parameters, 3157184 gradients, 8.9 GFLOPs\\n\",\n            \"\\n\",\n            \"Transferred 355/355 items from pretrained weights\\n\",\n            \"\\u001b[34m\\u001b[1mTensorBoard: \\u001b[0mStart with 'tensorboard --logdir runs/detect/train', view at http://localhost:6006/\\n\",\n            \"\\u001b[34m\\u001b[1mAMP: \\u001b[0mrunning Automatic Mixed Precision (AMP) checks with YOLOv8n...\\n\",\n            \"\\u001b[34m\\u001b[1mAMP: \\u001b[0mchecks passed ✅\\n\",\n            \"\\u001b[34m\\u001b[1moptimizer:\\u001b[0m SGD(lr=0.01) with parameter groups 57 weight(decay=0.0), 64 weight(decay=0.0005), 63 bias\\n\",\n            \"\\u001b[34m\\u001b[1mtrain: \\u001b[0mScanning /content/datasets/coco128/labels/train2017.cache... 126 images, 2 backgrounds, 80 corrupt: 100% 128/128 [00:00<?, ?it/s]\\n\",\n            \"\\u001b[34m\\u001b[1malbumentations: \\u001b[0mBlur(p=0.01, blur_limit=(3, 7)), MedianBlur(p=0.01, blur_limit=(3, 7)), ToGray(p=0.01), CLAHE(p=0.01, clip_limit=(1, 4.0), tile_grid_size=(8, 8))\\n\",\n            \"\\u001b[34m\\u001b[1mval: \\u001b[0mScanning /content/datasets/coco128/labels/train2017.cache... 126 images, 2 backgrounds, 80 corrupt: 100% 128/128 [00:00<?, ?it/s]\\n\",\n            \"Plotting labels to runs/detect/train/labels.jpg... \\n\",\n            \"Image sizes 640 train, 640 val\\n\",\n            \"Using 2 dataloader workers\\n\",\n            \"Logging results to \\u001b[1mruns/detect/train\\u001b[0m\\n\",\n            \"Starting training for 3 epochs...\\n\",\n            \"\\n\",\n            \"      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\\n\",\n            \"        1/3      2.78G      1.177      1.338       1.25        230        640: 100% 8/8 [00:06<00:00,  1.21it/s]\\n\",\n            \"                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100% 4/4 [00:04<00:00,  1.21s/it]\\n\",\n            \"                   all        128        929      0.631      0.549      0.614      0.455\\n\",\n            \"\\n\",\n            \"      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\\n\",\n            \"        2/3      2.69G      1.131      1.405       1.24        179        640: 100% 8/8 [00:02<00:00,  3.13it/s]\\n\",\n            \"                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100% 4/4 [00:02<00:00,  1.51it/s]\\n\",\n            \"                   all        128        929      0.669      0.569      0.634      0.478\\n\",\n            \"\\n\",\n            \"      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\\n\",\n            \"        3/3      2.84G      1.151      1.281      1.212        214        640: 100% 8/8 [00:02<00:00,  3.27it/s]\\n\",\n            \"                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100% 4/4 [00:09<00:00,  2.42s/it]\\n\",\n            \"                   all        128        929      0.687       0.58       0.65      0.488\\n\",\n            \"\\n\",\n            \"3 epochs completed in 0.010 hours.\\n\",\n            \"Optimizer stripped from runs/detect/train/weights/last.pt, 6.5MB\\n\",\n            \"Optimizer stripped from runs/detect/train/weights/best.pt, 6.5MB\\n\",\n            \"\\n\",\n            \"Validating runs/detect/train/weights/best.pt...\\n\",\n            \"Ultralytics YOLOv8.0.71 🚀 Python-3.9.16 torch-2.0.0+cu118 CUDA:0 (Tesla T4, 15102MiB)\\n\",\n            \"Model summary (fused): 168 layers, 3151904 parameters, 0 gradients, 8.7 GFLOPs\\n\",\n            \"                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100% 4/4 [00:06<00:00,  1.63s/it]\\n\",\n            \"                   all        128        929      0.689      0.578       0.65      0.486\\n\",\n            \"                person        128        254      0.763      0.673      0.769      0.544\\n\",\n            \"               bicycle        128          6          1      0.328      0.379      0.332\\n\",\n            \"                   car        128         46       0.84      0.217      0.292       0.18\\n\",\n            \"            motorcycle        128          5      0.612        0.8      0.872      0.709\\n\",\n            \"              airplane        128          6      0.766      0.833      0.894      0.694\\n\",\n            \"                   bus        128          7      0.748      0.714      0.721      0.675\\n\",\n            \"                 train        128          3      0.686          1      0.913       0.83\\n\",\n            \"                 truck        128         12      0.889        0.5      0.529      0.342\\n\",\n            \"                  boat        128          6      0.393      0.333       0.44      0.216\\n\",\n            \"         traffic light        128         14          1       0.21      0.224      0.142\\n\",\n            \"             stop sign        128          2          1      0.977      0.995      0.697\\n\",\n            \"                 bench        128          9      0.795      0.434      0.658      0.418\\n\",\n            \"                  bird        128         16      0.933      0.868      0.955      0.656\\n\",\n            \"                   cat        128          4      0.796          1      0.995      0.786\\n\",\n            \"                   dog        128          9      0.713      0.889      0.823      0.608\\n\",\n            \"                 horse        128          2      0.576          1      0.995      0.547\\n\",\n            \"              elephant        128         17      0.786      0.824      0.911      0.719\\n\",\n            \"                  bear        128          1      0.432          1      0.995      0.895\\n\",\n            \"                 zebra        128          4       0.86          1      0.995      0.935\\n\",\n            \"               giraffe        128          9      0.966          1      0.995      0.727\\n\",\n            \"              backpack        128          6      0.534      0.333      0.399      0.227\\n\",\n            \"              umbrella        128         18      0.757      0.519      0.665      0.447\\n\",\n            \"               handbag        128         19      0.939      0.105       0.25       0.14\\n\",\n            \"                   tie        128          7      0.677      0.602      0.682      0.505\\n\",\n            \"              suitcase        128          4      0.636          1      0.995      0.646\\n\",\n            \"               frisbee        128          5          1      0.789      0.799      0.689\\n\",\n            \"                  skis        128          1      0.794          1      0.995      0.497\\n\",\n            \"             snowboard        128          7      0.575      0.714      0.762       0.48\\n\",\n            \"           sports ball        128          6      0.703      0.407      0.514      0.288\\n\",\n            \"                  kite        128         10      0.645        0.4      0.506      0.206\\n\",\n            \"          baseball bat        128          4      0.436      0.404      0.253      0.125\\n\",\n            \"        baseball glove        128          7      0.786      0.429       0.43      0.303\\n\",\n            \"            skateboard        128          5      0.752        0.6        0.6      0.433\\n\",\n            \"         tennis racket        128          7      0.707      0.286      0.508      0.313\\n\",\n            \"                bottle        128         18      0.484      0.389       0.43      0.271\\n\",\n            \"            wine glass        128         16      0.471      0.562      0.584      0.327\\n\",\n            \"                   cup        128         36      0.569      0.278      0.404      0.286\\n\",\n            \"                  fork        128          6      0.529      0.167      0.207      0.192\\n\",\n            \"                 knife        128         16      0.697      0.562      0.594      0.377\\n\",\n            \"                 spoon        128         22       0.68      0.182      0.376      0.213\\n\",\n            \"                  bowl        128         28      0.623      0.679      0.653      0.536\\n\",\n            \"                banana        128          1          0          0      0.142     0.0363\\n\",\n            \"              sandwich        128          2          1          0      0.745      0.745\\n\",\n            \"                orange        128          4          1      0.457      0.849       0.56\\n\",\n            \"              broccoli        128         11      0.465      0.273      0.284      0.246\\n\",\n            \"                carrot        128         24      0.581      0.751      0.745      0.489\\n\",\n            \"               hot dog        128          2      0.654      0.961      0.828      0.763\\n\",\n            \"                 pizza        128          5      0.631          1      0.995      0.854\\n\",\n            \"                 donut        128         14      0.583          1      0.933       0.84\\n\",\n            \"                  cake        128          4      0.643          1      0.995       0.88\\n\",\n            \"                 chair        128         35        0.5      0.543      0.459      0.272\\n\",\n            \"                 couch        128          6      0.488        0.5      0.624       0.47\\n\",\n            \"          potted plant        128         14      0.645      0.714      0.747      0.542\\n\",\n            \"                   bed        128          3      0.718          1      0.995      0.798\\n\",\n            \"          dining table        128         13      0.448      0.615      0.538      0.437\\n\",\n            \"                toilet        128          2          1      0.884      0.995      0.946\\n\",\n            \"                    tv        128          2      0.548      0.644      0.828      0.762\\n\",\n            \"                laptop        128          3          1      0.563       0.72      0.639\\n\",\n            \"                 mouse        128          2          1          0     0.0623     0.0125\\n\",\n            \"                remote        128          8      0.697        0.5      0.578      0.496\\n\",\n            \"            cell phone        128          8          0          0      0.102     0.0471\\n\",\n            \"             microwave        128          3      0.651      0.667      0.863      0.738\\n\",\n            \"                  oven        128          5      0.471        0.4      0.415      0.309\\n\",\n            \"                  sink        128          6       0.45      0.284      0.268      0.159\\n\",\n            \"          refrigerator        128          5      0.679        0.4      0.695      0.537\\n\",\n            \"                  book        128         29      0.656      0.133      0.424      0.227\\n\",\n            \"                 clock        128          9      0.878      0.778      0.898      0.759\\n\",\n            \"                  vase        128          2      0.413          1      0.828      0.745\\n\",\n            \"              scissors        128          1          1          0      0.199     0.0597\\n\",\n            \"            teddy bear        128         21      0.553      0.472      0.669      0.447\\n\",\n            \"            toothbrush        128          5          1      0.518        0.8      0.521\\n\",\n            \"Speed: 2.7ms preprocess, 3.5ms inference, 0.0ms loss, 3.2ms postprocess per image\\n\",\n            \"Results saved to \\u001b[1mruns/detect/train\\u001b[0m\\n\"\n          ]\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"source\": [\n        \"# 4. Export\\n\",\n        \"\\n\",\n        \"Export a YOLOv8 model to any supported format below with the `format` argument, i.e. `format=onnx`. See [YOLOv8 Export Docs](https://docs.ultralytics.com/modes/export/) for more information.\\n\",\n        \"\\n\",\n        \"- 💡 ProTip: Export to [ONNX](https://onnx.ai/) or [OpenVINO](https://docs.openvino.ai/latest/index.html) for up to 3x CPU speedup.  \\n\",\n        \"- 💡 ProTip: Export to [TensorRT](https://developer.nvidia.com/tensorrt) for up to 5x GPU speedup.\\n\",\n        \"\\n\",\n        \"\\n\",\n        \"| Format                                                                     | `format=`          | Model                     |\\n\",\n        \"|----------------------------------------------------------------------------|--------------------|---------------------------|\\n\",\n        \"| [PyTorch](https://pytorch.org/)                                            | -                  | `yolov8n.pt`              |\\n\",\n        \"| [TorchScript](https://pytorch.org/docs/stable/jit.html)                    | `torchscript`      | `yolov8n.torchscript`     |\\n\",\n        \"| [ONNX](https://onnx.ai/)                                                   | `onnx`             | `yolov8n.onnx`            |\\n\",\n        \"| [OpenVINO](https://docs.openvino.ai/latest/index.html)                     | `openvino`         | `yolov8n_openvino_model/` |\\n\",\n        \"| [TensorRT](https://developer.nvidia.com/tensorrt)                          | `engine`           | `yolov8n.engine`          |\\n\",\n        \"| [CoreML](https://github.com/apple/coremltools)                             | `coreml`           | `yolov8n.mlmodel`         |\\n\",\n        \"| [TensorFlow SavedModel](https://www.tensorflow.org/guide/saved_model)      | `saved_model`      | `yolov8n_saved_model/`    |\\n\",\n        \"| [TensorFlow GraphDef](https://www.tensorflow.org/api_docs/python/tf/Graph) | `pb`               | `yolov8n.pb`              |\\n\",\n        \"| [TensorFlow Lite](https://www.tensorflow.org/lite)                         | `tflite`           | `yolov8n.tflite`          |\\n\",\n        \"| [TensorFlow Edge TPU](https://coral.ai/docs/edgetpu/models-intro/)         | `edgetpu`          | `yolov8n_edgetpu.tflite`  |\\n\",\n        \"| [TensorFlow.js](https://www.tensorflow.org/js)                             | `tfjs`             | `yolov8n_web_model/`      |\\n\",\n        \"| [PaddlePaddle](https://github.com/PaddlePaddle)                            | `paddle`           | `yolov8n_paddle_model/`   |\\n\",\n        \"\\n\"\n      ],\n      \"metadata\": {\n        \"id\": \"nPZZeNrLCQG6\"\n      }\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"!yolo export model=yolov8n.pt format=torchscript\"\n      ],\n      \"metadata\": {\n        \"colab\": {\n          \"base_uri\": \"https://localhost:8080/\"\n        },\n        \"id\": \"CYIjW4igCjqD\",\n        \"outputId\": \"fc41bf7a-0ea2-41a6-9ec5-dd0455af43bc\"\n      },\n      \"execution_count\": 5,\n      \"outputs\": [\n        {\n          \"output_type\": \"stream\",\n          \"name\": \"stdout\",\n          \"text\": [\n            \"Ultralytics YOLOv8.0.71 🚀 Python-3.9.16 torch-2.0.0+cu118 CPU\\n\",\n            \"YOLOv8n summary (fused): 168 layers, 3151904 parameters, 0 gradients, 8.7 GFLOPs\\n\",\n            \"\\n\",\n            \"\\u001b[34m\\u001b[1mPyTorch:\\u001b[0m starting from yolov8n.pt with input shape (1, 3, 640, 640) BCHW and output shape(s) (1, 84, 8400) (6.2 MB)\\n\",\n            \"\\n\",\n            \"\\u001b[34m\\u001b[1mTorchScript:\\u001b[0m starting export with torch 2.0.0+cu118...\\n\",\n            \"\\u001b[34m\\u001b[1mTorchScript:\\u001b[0m export success ✅ 2.3s, saved as yolov8n.torchscript (12.4 MB)\\n\",\n            \"\\n\",\n            \"Export complete (3.1s)\\n\",\n            \"Results saved to \\u001b[1m/content\\u001b[0m\\n\",\n            \"Predict:         yolo predict task=detect model=yolov8n.torchscript imgsz=640 \\n\",\n            \"Validate:        yolo val task=detect model=yolov8n.torchscript imgsz=640 data=coco.yaml \\n\",\n            \"Visualize:       https://netron.app\\n\"\n          ]\n        }\n      ]\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"source\": [\n        \"# 5. Python Usage\\n\",\n        \"\\n\",\n        \"YOLOv8 was reimagined using Python-first principles for the most seamless Python YOLO experience yet. YOLOv8 models can be loaded from a trained checkpoint or created from scratch. Then methods are used to train, val, predict, and export the model. See detailed Python usage examples in the [YOLOv8 Python Docs](https://docs.ultralytics.com/usage/python/).\"\n      ],\n      \"metadata\": {\n        \"id\": \"kUMOQ0OeDBJG\"\n      }\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"from ultralytics import YOLO\\n\",\n        \"\\n\",\n        \"# Load a model\\n\",\n        \"model = YOLO('yolov8n.yaml')  # build a new model from scratch\\n\",\n        \"model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\\n\",\n        \"\\n\",\n        \"# Use the model\\n\",\n        \"results = model.train(data='coco128.yaml', epochs=3)  # train the model\\n\",\n        \"results = model.val()  # evaluate model performance on the validation set\\n\",\n        \"results = model('https://ultralytics.com/images/bus.jpg')  # predict on an image\\n\",\n        \"success = model.export(format='onnx')  # export the model to ONNX format\"\n      ],\n      \"metadata\": {\n        \"id\": \"bpF9-vS_DAaf\"\n      },\n      \"execution_count\": null,\n      \"outputs\": []\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"source\": [\n        \"# 6. Tasks\\n\",\n        \"\\n\",\n        \"YOLOv8 can train, val, predict and export models for the most common tasks in vision AI: [Detect](https://docs.ultralytics.com/tasks/detect/), [Segment](https://docs.ultralytics.com/tasks/segment/), [Classify](https://docs.ultralytics.com/tasks/classify/) and [Pose](https://docs.ultralytics.com/tasks/pose/). See [YOLOv8 Tasks Docs](https://docs.ultralytics.com/tasks/) for more information.\\n\",\n        \"\\n\",\n        \"<img width=\\\"1024\\\" src=\\\"https://user-images.githubusercontent.com/26833433/212094133-6bb8c21c-3d47-41df-a512-81c5931054ae.png\\\">\\n\"\n      ],\n      \"metadata\": {\n        \"id\": \"Phm9ccmOKye5\"\n      }\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"source\": [\n        \"## 1. Detection\\n\",\n        \"\\n\",\n        \"YOLOv8 _detection_ models have no suffix and are the default YOLOv8 models, i.e. `yolov8n.pt` and are pretrained on COCO. See [Detection Docs](https://docs.ultralytics.com/tasks/detect/) for full details.\\n\"\n      ],\n      \"metadata\": {\n        \"id\": \"yq26lwpYK1lq\"\n      }\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"# Load YOLOv8n, train it on COCO128 for 3 epochs and predict an image with it\\n\",\n        \"from ultralytics import YOLO\\n\",\n        \"\\n\",\n        \"model = YOLO('yolov8n.pt')  # load a pretrained YOLOv8n detection model\\n\",\n        \"model.train(data='coco128.yaml', epochs=3)  # train the model\\n\",\n        \"model('https://ultralytics.com/images/bus.jpg')  # predict on an image\"\n      ],\n      \"metadata\": {\n        \"id\": \"8Go5qqS9LbC5\"\n      },\n      \"execution_count\": null,\n      \"outputs\": []\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"source\": [\n        \"## 2. Segmentation\\n\",\n        \"\\n\",\n        \"YOLOv8 _segmentation_ models use the `-seg` suffix, i.e. `yolov8n-seg.pt` and are pretrained on COCO. See [Segmentation Docs](https://docs.ultralytics.com/tasks/segment/) for full details.\\n\"\n      ],\n      \"metadata\": {\n        \"id\": \"7ZW58jUzK66B\"\n      }\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"# Load YOLOv8n-seg, train it on COCO128-seg for 3 epochs and predict an image with it\\n\",\n        \"from ultralytics import YOLO\\n\",\n        \"\\n\",\n        \"model = YOLO('yolov8n-seg.pt')  # load a pretrained YOLOv8n segmentation model\\n\",\n        \"model.train(data='coco128-seg.yaml', epochs=3)  # train the model\\n\",\n        \"model('https://ultralytics.com/images/bus.jpg')  # predict on an image\"\n      ],\n      \"metadata\": {\n        \"id\": \"WFPJIQl_L5HT\"\n      },\n      \"execution_count\": null,\n      \"outputs\": []\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"source\": [\n        \"## 3. Classification\\n\",\n        \"\\n\",\n        \"YOLOv8 _classification_ models use the `-cls` suffix, i.e. `yolov8n-cls.pt` and are pretrained on ImageNet. See [Classification Docs](https://docs.ultralytics.com/tasks/classify/) for full details.\\n\"\n      ],\n      \"metadata\": {\n        \"id\": \"ax3p94VNK9zR\"\n      }\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"# Load YOLOv8n-cls, train it on mnist160 for 3 epochs and predict an image with it\\n\",\n        \"from ultralytics import YOLO\\n\",\n        \"\\n\",\n        \"model = YOLO('yolov8n-cls.pt')  # load a pretrained YOLOv8n classification model\\n\",\n        \"model.train(data='mnist160', epochs=3)  # train the model\\n\",\n        \"model('https://ultralytics.com/images/bus.jpg')  # predict on an image\"\n      ],\n      \"metadata\": {\n        \"id\": \"5q9Zu6zlL5rS\"\n      },\n      \"execution_count\": null,\n      \"outputs\": []\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"source\": [\n        \"## 4. Pose\\n\",\n        \"\\n\",\n        \"YOLOv8 _pose_ models use the `-pose` suffix, i.e. `yolov8n-pose.pt` and are pretrained on COCO Keypoints. See [Pose Docs](https://docs.ultralytics.com/tasks/pose/) for full details.\"\n      ],\n      \"metadata\": {\n        \"id\": \"SpIaFLiO11TG\"\n      }\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"# Load YOLOv8n-pose, train it on COCO8-pose for 3 epochs and predict an image with it\\n\",\n        \"from ultralytics import YOLO\\n\",\n        \"\\n\",\n        \"model = YOLO('yolov8n-pose.pt')  # load a pretrained YOLOv8n classification model\\n\",\n        \"model.train(data='coco8-pose.yaml', epochs=3)  # train the model\\n\",\n        \"model('https://ultralytics.com/images/bus.jpg')  # predict on an image\"\n      ],\n      \"metadata\": {\n        \"id\": \"si4aKFNg19vX\"\n      },\n      \"execution_count\": null,\n      \"outputs\": []\n    },\n    {\n      \"cell_type\": \"markdown\",\n      \"metadata\": {\n        \"id\": \"IEijrePND_2I\"\n      },\n      \"source\": [\n        \"# Appendix\\n\",\n        \"\\n\",\n        \"Additional content below.\"\n      ]\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"# Git clone and run tests on updates branch\\n\",\n        \"!git clone https://github.com/ultralytics/ultralytics -b updates\\n\",\n        \"%pip install -qe ultralytics\\n\",\n        \"!pytest ultralytics/tests\"\n      ],\n      \"metadata\": {\n        \"id\": \"uRKlwxSJdhd1\"\n      },\n      \"execution_count\": null,\n      \"outputs\": []\n    },\n    {\n      \"cell_type\": \"code\",\n      \"source\": [\n        \"# Validate multiple models\\n\",\n        \"for x in 'nsmlx':\\n\",\n        \"  !yolo val model=yolov8{x}.pt data=coco.yaml\"\n      ],\n      \"metadata\": {\n        \"id\": \"Wdc6t_bfzDDk\"\n      },\n      \"execution_count\": null,\n      \"outputs\": []\n    }\n  ]\n}\n"
  },
  {
    "path": "lib/python3.7/site-packages/_distutils_hack/__init__.py",
    "content": "# don't import any costly modules\nimport sys\nimport os\n\n\nis_pypy = '__pypy__' in sys.builtin_module_names\n\n\ndef warn_distutils_present():\n    if 'distutils' not in sys.modules:\n        return\n    if is_pypy and sys.version_info < (3, 7):\n        # PyPy for 3.6 unconditionally imports distutils, so bypass the warning\n        # https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250\n        return\n    import warnings\n\n    warnings.warn(\n        \"Distutils was imported before Setuptools, but importing Setuptools \"\n        \"also replaces the `distutils` module in `sys.modules`. This may lead \"\n        \"to undesirable behaviors or errors. To avoid these issues, avoid \"\n        \"using distutils directly, ensure that setuptools is installed in the \"\n        \"traditional way (e.g. not an editable install), and/or make sure \"\n        \"that setuptools is always imported before distutils.\"\n    )\n\n\ndef clear_distutils():\n    if 'distutils' not in sys.modules:\n        return\n    import warnings\n\n    warnings.warn(\"Setuptools is replacing distutils.\")\n    mods = [\n        name\n        for name in sys.modules\n        if name == \"distutils\" or name.startswith(\"distutils.\")\n    ]\n    for name in mods:\n        del sys.modules[name]\n\n\ndef enabled():\n    \"\"\"\n    Allow selection of distutils by environment variable.\n    \"\"\"\n    which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')\n    return which == 'local'\n\n\ndef ensure_local_distutils():\n    import importlib\n\n    clear_distutils()\n\n    # With the DistutilsMetaFinder in place,\n    # perform an import to cause distutils to be\n    # loaded from setuptools._distutils. Ref #2906.\n    with shim():\n        importlib.import_module('distutils')\n\n    # check that submodules load as expected\n    core = importlib.import_module('distutils.core')\n    assert '_distutils' in core.__file__, core.__file__\n    assert 'setuptools._distutils.log' not in sys.modules\n\n\ndef do_override():\n    \"\"\"\n    Ensure that the local copy of distutils is preferred over stdlib.\n\n    See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401\n    for more motivation.\n    \"\"\"\n    if enabled():\n        warn_distutils_present()\n        ensure_local_distutils()\n\n\nclass _TrivialRe:\n    def __init__(self, *patterns):\n        self._patterns = patterns\n\n    def match(self, string):\n        return all(pat in string for pat in self._patterns)\n\n\nclass DistutilsMetaFinder:\n    def find_spec(self, fullname, path, target=None):\n        # optimization: only consider top level modules and those\n        # found in the CPython test suite.\n        if path is not None and not fullname.startswith('test.'):\n            return\n\n        method_name = 'spec_for_{fullname}'.format(**locals())\n        method = getattr(self, method_name, lambda: None)\n        return method()\n\n    def spec_for_distutils(self):\n        if self.is_cpython():\n            return\n\n        import importlib\n        import importlib.abc\n        import importlib.util\n\n        try:\n            mod = importlib.import_module('setuptools._distutils')\n        except Exception:\n            # There are a couple of cases where setuptools._distutils\n            # may not be present:\n            # - An older Setuptools without a local distutils is\n            #   taking precedence. Ref #2957.\n            # - Path manipulation during sitecustomize removes\n            #   setuptools from the path but only after the hook\n            #   has been loaded. Ref #2980.\n            # In either case, fall back to stdlib behavior.\n            return\n\n        class DistutilsLoader(importlib.abc.Loader):\n            def create_module(self, spec):\n                mod.__name__ = 'distutils'\n                return mod\n\n            def exec_module(self, module):\n                pass\n\n        return importlib.util.spec_from_loader(\n            'distutils', DistutilsLoader(), origin=mod.__file__\n        )\n\n    @staticmethod\n    def is_cpython():\n        \"\"\"\n        Suppress supplying distutils for CPython (build and tests).\n        Ref #2965 and #3007.\n        \"\"\"\n        return os.path.isfile('pybuilddir.txt')\n\n    def spec_for_pip(self):\n        \"\"\"\n        Ensure stdlib distutils when running under pip.\n        See pypa/pip#8761 for rationale.\n        \"\"\"\n        if self.pip_imported_during_build():\n            return\n        clear_distutils()\n        self.spec_for_distutils = lambda: None\n\n    @classmethod\n    def pip_imported_during_build(cls):\n        \"\"\"\n        Detect if pip is being imported in a build script. Ref #2355.\n        \"\"\"\n        import traceback\n\n        return any(\n            cls.frame_file_is_setup(frame) for frame, line in traceback.walk_stack(None)\n        )\n\n    @staticmethod\n    def frame_file_is_setup(frame):\n        \"\"\"\n        Return True if the indicated frame suggests a setup.py file.\n        \"\"\"\n        # some frames may not have __file__ (#2940)\n        return frame.f_globals.get('__file__', '').endswith('setup.py')\n\n    def spec_for_sensitive_tests(self):\n        \"\"\"\n        Ensure stdlib distutils when running select tests under CPython.\n\n        python/cpython#91169\n        \"\"\"\n        clear_distutils()\n        self.spec_for_distutils = lambda: None\n\n    sensitive_tests = (\n        [\n            'test.test_distutils',\n            'test.test_peg_generator',\n            'test.test_importlib',\n        ]\n        if sys.version_info < (3, 10)\n        else [\n            'test.test_distutils',\n        ]\n    )\n\n\nfor name in DistutilsMetaFinder.sensitive_tests:\n    setattr(\n        DistutilsMetaFinder,\n        f'spec_for_{name}',\n        DistutilsMetaFinder.spec_for_sensitive_tests,\n    )\n\n\nDISTUTILS_FINDER = DistutilsMetaFinder()\n\n\ndef add_shim():\n    DISTUTILS_FINDER in sys.meta_path or insert_shim()\n\n\nclass shim:\n    def __enter__(self):\n        insert_shim()\n\n    def __exit__(self, exc, value, tb):\n        remove_shim()\n\n\ndef insert_shim():\n    sys.meta_path.insert(0, DISTUTILS_FINDER)\n\n\ndef remove_shim():\n    try:\n        sys.meta_path.remove(DISTUTILS_FINDER)\n    except ValueError:\n        pass\n"
  },
  {
    "path": "lib/python3.7/site-packages/_distutils_hack/override.py",
    "content": "__import__('_distutils_hack').do_override()\n"
  },
  {
    "path": "lib/python3.7/site-packages/_virtualenv.pth",
    "content": "import _virtualenv"
  },
  {
    "path": "lib/python3.7/site-packages/_virtualenv.py",
    "content": "\"\"\"Patches that are applied at runtime to the virtual environment\"\"\"\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\n\nVIRTUALENV_PATCH_FILE = os.path.join(__file__)\n\n\ndef patch_dist(dist):\n    \"\"\"\n    Distutils allows user to configure some arguments via a configuration file:\n    https://docs.python.org/3/install/index.html#distutils-configuration-files\n\n    Some of this arguments though don't make sense in context of the virtual environment files, let's fix them up.\n    \"\"\"\n    # we cannot allow some install config as that would get packages installed outside of the virtual environment\n    old_parse_config_files = dist.Distribution.parse_config_files\n\n    def parse_config_files(self, *args, **kwargs):\n        result = old_parse_config_files(self, *args, **kwargs)\n        install = self.get_option_dict(\"install\")\n\n        if \"prefix\" in install:  # the prefix governs where to install the libraries\n            install[\"prefix\"] = VIRTUALENV_PATCH_FILE, os.path.abspath(sys.prefix)\n        for base in (\"purelib\", \"platlib\", \"headers\", \"scripts\", \"data\"):\n            key = \"install_{}\".format(base)\n            if key in install:  # do not allow global configs to hijack venv paths\n                install.pop(key, None)\n        return result\n\n    dist.Distribution.parse_config_files = parse_config_files\n\n\n# Import hook that patches some modules to ignore configuration values that break package installation in case\n# of virtual environments.\n_DISTUTILS_PATCH = \"distutils.dist\", \"setuptools.dist\"\nif sys.version_info > (3, 4):\n    # https://docs.python.org/3/library/importlib.html#setting-up-an-importer\n\n    class _Finder:\n        \"\"\"A meta path finder that allows patching the imported distutils modules\"\"\"\n\n        fullname = None\n\n        # lock[0] is threading.Lock(), but initialized lazily to avoid importing threading very early at startup,\n        # because there are gevent-based applications that need to be first to import threading by themselves.\n        # See https://github.com/pypa/virtualenv/issues/1895 for details.\n        lock = []\n\n        def find_spec(self, fullname, path, target=None):  # noqa: U100\n            if fullname in _DISTUTILS_PATCH and self.fullname is None:\n                # initialize lock[0] lazily\n                if len(self.lock) == 0:\n                    import threading\n\n                    lock = threading.Lock()\n                    # there is possibility that two threads T1 and T2 are simultaneously running into find_spec,\n                    # observing .lock as empty, and further going into hereby initialization. However due to the GIL,\n                    # list.append() operation is atomic and this way only one of the threads will \"win\" to put the lock\n                    # - that every thread will use - into .lock[0].\n                    # https://docs.python.org/3/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe\n                    self.lock.append(lock)\n\n                from functools import partial\n                from importlib.util import find_spec\n\n                with self.lock[0]:\n                    self.fullname = fullname\n                    try:\n                        spec = find_spec(fullname, path)\n                        if spec is not None:\n                            # https://www.python.org/dev/peps/pep-0451/#how-loading-will-work\n                            is_new_api = hasattr(spec.loader, \"exec_module\")\n                            func_name = \"exec_module\" if is_new_api else \"load_module\"\n                            old = getattr(spec.loader, func_name)\n                            func = self.exec_module if is_new_api else self.load_module\n                            if old is not func:\n                                try:\n                                    setattr(spec.loader, func_name, partial(func, old))\n                                except AttributeError:\n                                    pass  # C-Extension loaders are r/o such as zipimporter with <python 3.7\n                            return spec\n                    finally:\n                        self.fullname = None\n\n        @staticmethod\n        def exec_module(old, module):\n            old(module)\n            if module.__name__ in _DISTUTILS_PATCH:\n                patch_dist(module)\n\n        @staticmethod\n        def load_module(old, name):\n            module = old(name)\n            if module.__name__ in _DISTUTILS_PATCH:\n                patch_dist(module)\n            return module\n\n    sys.meta_path.insert(0, _Finder())\nelse:\n    # https://www.python.org/dev/peps/pep-0302/\n    from imp import find_module\n    from pkgutil import ImpImporter, ImpLoader\n\n    class _VirtualenvImporter(object, ImpImporter):\n        def __init__(self, path=None):\n            object.__init__(self)\n            ImpImporter.__init__(self, path)\n\n        def find_module(self, fullname, path=None):\n            if fullname in _DISTUTILS_PATCH:\n                try:\n                    return _VirtualenvLoader(fullname, *find_module(fullname.split(\".\")[-1], path))\n                except ImportError:\n                    pass\n            return None\n\n    class _VirtualenvLoader(object, ImpLoader):\n        def __init__(self, fullname, file, filename, etc):\n            object.__init__(self)\n            ImpLoader.__init__(self, fullname, file, filename, etc)\n\n        def load_module(self, fullname):\n            module = super(_VirtualenvLoader, self).load_module(fullname)\n            patch_dist(module)\n            module.__loader__ = None  # distlib fallback\n            return module\n\n    sys.meta_path.append(_VirtualenvImporter())\n"
  },
  {
    "path": "lib/python3.7/site-packages/distutils-precedence.pth",
    "content": "import os; var = 'SETUPTOOLS_USE_DISTUTILS'; enabled = os.environ.get(var, 'local') == 'local'; enabled and __import__('_distutils_hack').add_shim(); \n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/__init__.py",
    "content": "from typing import List, Optional\n\n__version__ = \"22.3.1\"\n\n\ndef main(args: Optional[List[str]] = None) -> int:\n    \"\"\"This is an internal API only meant for use by pip's own console scripts.\n\n    For additional details, see https://github.com/pypa/pip/issues/7498.\n    \"\"\"\n    from pip._internal.utils.entrypoints import _wrapper\n\n    return _wrapper(args)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/__main__.py",
    "content": "import os\nimport sys\nimport warnings\n\n# Remove '' and current working directory from the first entry\n# of sys.path, if present to avoid using current directory\n# in pip commands check, freeze, install, list and show,\n# when invoked as python -m pip <command>\nif sys.path[0] in (\"\", os.getcwd()):\n    sys.path.pop(0)\n\n# If we are running from a wheel, add the wheel to sys.path\n# This allows the usage python pip-*.whl/pip install pip-*.whl\nif __package__ == \"\":\n    # __file__ is pip-*.whl/pip/__main__.py\n    # first dirname call strips of '/__main__.py', second strips off '/pip'\n    # Resulting path is the name of the wheel itself\n    # Add that to sys.path so we can import pip\n    path = os.path.dirname(os.path.dirname(__file__))\n    sys.path.insert(0, path)\n\nif __name__ == \"__main__\":\n    # Work around the error reported in #9540, pending a proper fix.\n    # Note: It is essential the warning filter is set *before* importing\n    #       pip, as the deprecation happens at import time, not runtime.\n    warnings.filterwarnings(\n        \"ignore\", category=DeprecationWarning, module=\".*packaging\\\\.version\"\n    )\n    from pip._internal.cli.main import main as _main\n\n    sys.exit(_main())\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/__pip-runner__.py",
    "content": "\"\"\"Execute exactly this copy of pip, within a different environment.\n\nThis file is named as it is, to ensure that this module can't be imported via\nan import statement.\n\"\"\"\n\n# /!\\ This version compatibility check section must be Python 2 compatible. /!\\\n\nimport sys\n\n# Copied from setup.py\nPYTHON_REQUIRES = (3, 7)\n\n\ndef version_str(version):  # type: ignore\n    return \".\".join(str(v) for v in version)\n\n\nif sys.version_info[:2] < PYTHON_REQUIRES:\n    raise SystemExit(\n        \"This version of pip does not support python {} (requires >={}).\".format(\n            version_str(sys.version_info[:2]), version_str(PYTHON_REQUIRES)\n        )\n    )\n\n# From here on, we can use Python 3 features, but the syntax must remain\n# Python 2 compatible.\n\nimport runpy  # noqa: E402\nfrom importlib.machinery import PathFinder  # noqa: E402\nfrom os.path import dirname  # noqa: E402\n\nPIP_SOURCES_ROOT = dirname(dirname(__file__))\n\n\nclass PipImportRedirectingFinder:\n    @classmethod\n    def find_spec(self, fullname, path=None, target=None):  # type: ignore\n        if fullname != \"pip\":\n            return None\n\n        spec = PathFinder.find_spec(fullname, [PIP_SOURCES_ROOT], target)\n        assert spec, (PIP_SOURCES_ROOT, fullname)\n        return spec\n\n\nsys.meta_path.insert(0, PipImportRedirectingFinder())\n\nassert __name__ == \"__main__\", \"Cannot run __pip-runner__.py as a non-main module\"\nrunpy.run_module(\"pip\", run_name=\"__main__\", alter_sys=True)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/__init__.py",
    "content": "from typing import List, Optional\n\nimport pip._internal.utils.inject_securetransport  # noqa\nfrom pip._internal.utils import _log\n\n# init_logging() must be called before any call to logging.getLogger()\n# which happens at import of most modules.\n_log.init_logging()\n\n\ndef main(args: (Optional[List[str]]) = None) -> int:\n    \"\"\"This is preserved for old console scripts that may still be referencing\n    it.\n\n    For additional details, see https://github.com/pypa/pip/issues/7498.\n    \"\"\"\n    from pip._internal.utils.entrypoints import _wrapper\n\n    return _wrapper(args)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/build_env.py",
    "content": "\"\"\"Build Environment used for isolation during sdist building\n\"\"\"\n\nimport logging\nimport os\nimport pathlib\nimport site\nimport sys\nimport textwrap\nfrom collections import OrderedDict\nfrom sysconfig import get_paths\nfrom types import TracebackType\nfrom typing import TYPE_CHECKING, Iterable, List, Optional, Set, Tuple, Type\n\nfrom pip._vendor.certifi import where\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.version import Version\n\nfrom pip import __file__ as pip_location\nfrom pip._internal.cli.spinners import open_spinner\nfrom pip._internal.locations import get_platlib, get_prefixed_libs, get_purelib\nfrom pip._internal.metadata import get_default_environment, get_environment\nfrom pip._internal.utils.subprocess import call_subprocess\nfrom pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds\n\nif TYPE_CHECKING:\n    from pip._internal.index.package_finder import PackageFinder\n\nlogger = logging.getLogger(__name__)\n\n\nclass _Prefix:\n    def __init__(self, path: str) -> None:\n        self.path = path\n        self.setup = False\n        self.bin_dir = get_paths(\n            \"nt\" if os.name == \"nt\" else \"posix_prefix\",\n            vars={\"base\": path, \"platbase\": path},\n        )[\"scripts\"]\n        self.lib_dirs = get_prefixed_libs(path)\n\n\ndef get_runnable_pip() -> str:\n    \"\"\"Get a file to pass to a Python executable, to run the currently-running pip.\n\n    This is used to run a pip subprocess, for installing requirements into the build\n    environment.\n    \"\"\"\n    source = pathlib.Path(pip_location).resolve().parent\n\n    if not source.is_dir():\n        # This would happen if someone is using pip from inside a zip file. In that\n        # case, we can use that directly.\n        return str(source)\n\n    return os.fsdecode(source / \"__pip-runner__.py\")\n\n\ndef _get_system_sitepackages() -> Set[str]:\n    \"\"\"Get system site packages\n\n    Usually from site.getsitepackages,\n    but fallback on `get_purelib()/get_platlib()` if unavailable\n    (e.g. in a virtualenv created by virtualenv<20)\n\n    Returns normalized set of strings.\n    \"\"\"\n    if hasattr(site, \"getsitepackages\"):\n        system_sites = site.getsitepackages()\n    else:\n        # virtualenv < 20 overwrites site.py without getsitepackages\n        # fallback on get_purelib/get_platlib.\n        # this is known to miss things, but shouldn't in the cases\n        # where getsitepackages() has been removed (inside a virtualenv)\n        system_sites = [get_purelib(), get_platlib()]\n    return {os.path.normcase(path) for path in system_sites}\n\n\nclass BuildEnvironment:\n    \"\"\"Creates and manages an isolated environment to install build deps\"\"\"\n\n    def __init__(self) -> None:\n        temp_dir = TempDirectory(kind=tempdir_kinds.BUILD_ENV, globally_managed=True)\n\n        self._prefixes = OrderedDict(\n            (name, _Prefix(os.path.join(temp_dir.path, name)))\n            for name in (\"normal\", \"overlay\")\n        )\n\n        self._bin_dirs: List[str] = []\n        self._lib_dirs: List[str] = []\n        for prefix in reversed(list(self._prefixes.values())):\n            self._bin_dirs.append(prefix.bin_dir)\n            self._lib_dirs.extend(prefix.lib_dirs)\n\n        # Customize site to:\n        # - ensure .pth files are honored\n        # - prevent access to system site packages\n        system_sites = _get_system_sitepackages()\n\n        self._site_dir = os.path.join(temp_dir.path, \"site\")\n        if not os.path.exists(self._site_dir):\n            os.mkdir(self._site_dir)\n        with open(\n            os.path.join(self._site_dir, \"sitecustomize.py\"), \"w\", encoding=\"utf-8\"\n        ) as fp:\n            fp.write(\n                textwrap.dedent(\n                    \"\"\"\n                import os, site, sys\n\n                # First, drop system-sites related paths.\n                original_sys_path = sys.path[:]\n                known_paths = set()\n                for path in {system_sites!r}:\n                    site.addsitedir(path, known_paths=known_paths)\n                system_paths = set(\n                    os.path.normcase(path)\n                    for path in sys.path[len(original_sys_path):]\n                )\n                original_sys_path = [\n                    path for path in original_sys_path\n                    if os.path.normcase(path) not in system_paths\n                ]\n                sys.path = original_sys_path\n\n                # Second, add lib directories.\n                # ensuring .pth file are processed.\n                for path in {lib_dirs!r}:\n                    assert not path in sys.path\n                    site.addsitedir(path)\n                \"\"\"\n                ).format(system_sites=system_sites, lib_dirs=self._lib_dirs)\n            )\n\n    def __enter__(self) -> None:\n        self._save_env = {\n            name: os.environ.get(name, None)\n            for name in (\"PATH\", \"PYTHONNOUSERSITE\", \"PYTHONPATH\")\n        }\n\n        path = self._bin_dirs[:]\n        old_path = self._save_env[\"PATH\"]\n        if old_path:\n            path.extend(old_path.split(os.pathsep))\n\n        pythonpath = [self._site_dir]\n\n        os.environ.update(\n            {\n                \"PATH\": os.pathsep.join(path),\n                \"PYTHONNOUSERSITE\": \"1\",\n                \"PYTHONPATH\": os.pathsep.join(pythonpath),\n            }\n        )\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        for varname, old_value in self._save_env.items():\n            if old_value is None:\n                os.environ.pop(varname, None)\n            else:\n                os.environ[varname] = old_value\n\n    def check_requirements(\n        self, reqs: Iterable[str]\n    ) -> Tuple[Set[Tuple[str, str]], Set[str]]:\n        \"\"\"Return 2 sets:\n        - conflicting requirements: set of (installed, wanted) reqs tuples\n        - missing requirements: set of reqs\n        \"\"\"\n        missing = set()\n        conflicting = set()\n        if reqs:\n            env = (\n                get_environment(self._lib_dirs)\n                if hasattr(self, \"_lib_dirs\")\n                else get_default_environment()\n            )\n            for req_str in reqs:\n                req = Requirement(req_str)\n                # We're explicitly evaluating with an empty extra value, since build\n                # environments are not provided any mechanism to select specific extras.\n                if req.marker is not None and not req.marker.evaluate({\"extra\": \"\"}):\n                    continue\n                dist = env.get_distribution(req.name)\n                if not dist:\n                    missing.add(req_str)\n                    continue\n                if isinstance(dist.version, Version):\n                    installed_req_str = f\"{req.name}=={dist.version}\"\n                else:\n                    installed_req_str = f\"{req.name}==={dist.version}\"\n                if not req.specifier.contains(dist.version, prereleases=True):\n                    conflicting.add((installed_req_str, req_str))\n                # FIXME: Consider direct URL?\n        return conflicting, missing\n\n    def install_requirements(\n        self,\n        finder: \"PackageFinder\",\n        requirements: Iterable[str],\n        prefix_as_string: str,\n        *,\n        kind: str,\n    ) -> None:\n        prefix = self._prefixes[prefix_as_string]\n        assert not prefix.setup\n        prefix.setup = True\n        if not requirements:\n            return\n        self._install_requirements(\n            get_runnable_pip(),\n            finder,\n            requirements,\n            prefix,\n            kind=kind,\n        )\n\n    @staticmethod\n    def _install_requirements(\n        pip_runnable: str,\n        finder: \"PackageFinder\",\n        requirements: Iterable[str],\n        prefix: _Prefix,\n        *,\n        kind: str,\n    ) -> None:\n        args: List[str] = [\n            sys.executable,\n            pip_runnable,\n            \"install\",\n            \"--ignore-installed\",\n            \"--no-user\",\n            \"--prefix\",\n            prefix.path,\n            \"--no-warn-script-location\",\n        ]\n        if logger.getEffectiveLevel() <= logging.DEBUG:\n            args.append(\"-v\")\n        for format_control in (\"no_binary\", \"only_binary\"):\n            formats = getattr(finder.format_control, format_control)\n            args.extend(\n                (\n                    \"--\" + format_control.replace(\"_\", \"-\"),\n                    \",\".join(sorted(formats or {\":none:\"})),\n                )\n            )\n\n        index_urls = finder.index_urls\n        if index_urls:\n            args.extend([\"-i\", index_urls[0]])\n            for extra_index in index_urls[1:]:\n                args.extend([\"--extra-index-url\", extra_index])\n        else:\n            args.append(\"--no-index\")\n        for link in finder.find_links:\n            args.extend([\"--find-links\", link])\n\n        for host in finder.trusted_hosts:\n            args.extend([\"--trusted-host\", host])\n        if finder.allow_all_prereleases:\n            args.append(\"--pre\")\n        if finder.prefer_binary:\n            args.append(\"--prefer-binary\")\n        args.append(\"--\")\n        args.extend(requirements)\n        extra_environ = {\"_PIP_STANDALONE_CERT\": where()}\n        with open_spinner(f\"Installing {kind}\") as spinner:\n            call_subprocess(\n                args,\n                command_desc=f\"pip subprocess to install {kind}\",\n                spinner=spinner,\n                extra_environ=extra_environ,\n            )\n\n\nclass NoOpBuildEnvironment(BuildEnvironment):\n    \"\"\"A no-op drop-in replacement for BuildEnvironment\"\"\"\n\n    def __init__(self) -> None:\n        pass\n\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        pass\n\n    def cleanup(self) -> None:\n        pass\n\n    def install_requirements(\n        self,\n        finder: \"PackageFinder\",\n        requirements: Iterable[str],\n        prefix_as_string: str,\n        *,\n        kind: str,\n    ) -> None:\n        raise NotImplementedError()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/cache.py",
    "content": "\"\"\"Cache Management\n\"\"\"\n\nimport hashlib\nimport json\nimport logging\nimport os\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Set\n\nfrom pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_version\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.exceptions import InvalidWheelFilename\nfrom pip._internal.models.direct_url import DirectUrl\nfrom pip._internal.models.format_control import FormatControl\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds\nfrom pip._internal.utils.urls import path_to_url\n\nlogger = logging.getLogger(__name__)\n\nORIGIN_JSON_NAME = \"origin.json\"\n\n\ndef _hash_dict(d: Dict[str, str]) -> str:\n    \"\"\"Return a stable sha224 of a dictionary.\"\"\"\n    s = json.dumps(d, sort_keys=True, separators=(\",\", \":\"), ensure_ascii=True)\n    return hashlib.sha224(s.encode(\"ascii\")).hexdigest()\n\n\nclass Cache:\n    \"\"\"An abstract class - provides cache directories for data from links\n\n\n    :param cache_dir: The root of the cache.\n    :param format_control: An object of FormatControl class to limit\n        binaries being read from the cache.\n    :param allowed_formats: which formats of files the cache should store.\n        ('binary' and 'source' are the only allowed values)\n    \"\"\"\n\n    def __init__(\n        self, cache_dir: str, format_control: FormatControl, allowed_formats: Set[str]\n    ) -> None:\n        super().__init__()\n        assert not cache_dir or os.path.isabs(cache_dir)\n        self.cache_dir = cache_dir or None\n        self.format_control = format_control\n        self.allowed_formats = allowed_formats\n\n        _valid_formats = {\"source\", \"binary\"}\n        assert self.allowed_formats.union(_valid_formats) == _valid_formats\n\n    def _get_cache_path_parts(self, link: Link) -> List[str]:\n        \"\"\"Get parts of part that must be os.path.joined with cache_dir\"\"\"\n\n        # We want to generate an url to use as our cache key, we don't want to\n        # just re-use the URL because it might have other items in the fragment\n        # and we don't care about those.\n        key_parts = {\"url\": link.url_without_fragment}\n        if link.hash_name is not None and link.hash is not None:\n            key_parts[link.hash_name] = link.hash\n        if link.subdirectory_fragment:\n            key_parts[\"subdirectory\"] = link.subdirectory_fragment\n\n        # Include interpreter name, major and minor version in cache key\n        # to cope with ill-behaved sdists that build a different wheel\n        # depending on the python version their setup.py is being run on,\n        # and don't encode the difference in compatibility tags.\n        # https://github.com/pypa/pip/issues/7296\n        key_parts[\"interpreter_name\"] = interpreter_name()\n        key_parts[\"interpreter_version\"] = interpreter_version()\n\n        # Encode our key url with sha224, we'll use this because it has similar\n        # security properties to sha256, but with a shorter total output (and\n        # thus less secure). However the differences don't make a lot of\n        # difference for our use case here.\n        hashed = _hash_dict(key_parts)\n\n        # We want to nest the directories some to prevent having a ton of top\n        # level directories where we might run out of sub directories on some\n        # FS.\n        parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]\n\n        return parts\n\n    def _get_candidates(self, link: Link, canonical_package_name: str) -> List[Any]:\n        can_not_cache = not self.cache_dir or not canonical_package_name or not link\n        if can_not_cache:\n            return []\n\n        formats = self.format_control.get_allowed_formats(canonical_package_name)\n        if not self.allowed_formats.intersection(formats):\n            return []\n\n        candidates = []\n        path = self.get_path_for_link(link)\n        if os.path.isdir(path):\n            for candidate in os.listdir(path):\n                candidates.append((candidate, path))\n        return candidates\n\n    def get_path_for_link(self, link: Link) -> str:\n        \"\"\"Return a directory to store cached items in for link.\"\"\"\n        raise NotImplementedError()\n\n    def get(\n        self,\n        link: Link,\n        package_name: Optional[str],\n        supported_tags: List[Tag],\n    ) -> Link:\n        \"\"\"Returns a link to a cached item if it exists, otherwise returns the\n        passed link.\n        \"\"\"\n        raise NotImplementedError()\n\n\nclass SimpleWheelCache(Cache):\n    \"\"\"A cache of wheels for future installs.\"\"\"\n\n    def __init__(self, cache_dir: str, format_control: FormatControl) -> None:\n        super().__init__(cache_dir, format_control, {\"binary\"})\n\n    def get_path_for_link(self, link: Link) -> str:\n        \"\"\"Return a directory to store cached wheels for link\n\n        Because there are M wheels for any one sdist, we provide a directory\n        to cache them in, and then consult that directory when looking up\n        cache hits.\n\n        We only insert things into the cache if they have plausible version\n        numbers, so that we don't contaminate the cache with things that were\n        not unique. E.g. ./package might have dozens of installs done for it\n        and build a version of 0.0...and if we built and cached a wheel, we'd\n        end up using the same wheel even if the source has been edited.\n\n        :param link: The link of the sdist for which this will cache wheels.\n        \"\"\"\n        parts = self._get_cache_path_parts(link)\n        assert self.cache_dir\n        # Store wheels within the root cache_dir\n        return os.path.join(self.cache_dir, \"wheels\", *parts)\n\n    def get(\n        self,\n        link: Link,\n        package_name: Optional[str],\n        supported_tags: List[Tag],\n    ) -> Link:\n        candidates = []\n\n        if not package_name:\n            return link\n\n        canonical_package_name = canonicalize_name(package_name)\n        for wheel_name, wheel_dir in self._get_candidates(link, canonical_package_name):\n            try:\n                wheel = Wheel(wheel_name)\n            except InvalidWheelFilename:\n                continue\n            if canonicalize_name(wheel.name) != canonical_package_name:\n                logger.debug(\n                    \"Ignoring cached wheel %s for %s as it \"\n                    \"does not match the expected distribution name %s.\",\n                    wheel_name,\n                    link,\n                    package_name,\n                )\n                continue\n            if not wheel.supported(supported_tags):\n                # Built for a different python/arch/etc\n                continue\n            candidates.append(\n                (\n                    wheel.support_index_min(supported_tags),\n                    wheel_name,\n                    wheel_dir,\n                )\n            )\n\n        if not candidates:\n            return link\n\n        _, wheel_name, wheel_dir = min(candidates)\n        return Link(path_to_url(os.path.join(wheel_dir, wheel_name)))\n\n\nclass EphemWheelCache(SimpleWheelCache):\n    \"\"\"A SimpleWheelCache that creates it's own temporary cache directory\"\"\"\n\n    def __init__(self, format_control: FormatControl) -> None:\n        self._temp_dir = TempDirectory(\n            kind=tempdir_kinds.EPHEM_WHEEL_CACHE,\n            globally_managed=True,\n        )\n\n        super().__init__(self._temp_dir.path, format_control)\n\n\nclass CacheEntry:\n    def __init__(\n        self,\n        link: Link,\n        persistent: bool,\n    ):\n        self.link = link\n        self.persistent = persistent\n        self.origin: Optional[DirectUrl] = None\n        origin_direct_url_path = Path(self.link.file_path).parent / ORIGIN_JSON_NAME\n        if origin_direct_url_path.exists():\n            self.origin = DirectUrl.from_json(origin_direct_url_path.read_text())\n\n\nclass WheelCache(Cache):\n    \"\"\"Wraps EphemWheelCache and SimpleWheelCache into a single Cache\n\n    This Cache allows for gracefully degradation, using the ephem wheel cache\n    when a certain link is not found in the simple wheel cache first.\n    \"\"\"\n\n    def __init__(\n        self, cache_dir: str, format_control: Optional[FormatControl] = None\n    ) -> None:\n        if format_control is None:\n            format_control = FormatControl()\n        super().__init__(cache_dir, format_control, {\"binary\"})\n        self._wheel_cache = SimpleWheelCache(cache_dir, format_control)\n        self._ephem_cache = EphemWheelCache(format_control)\n\n    def get_path_for_link(self, link: Link) -> str:\n        return self._wheel_cache.get_path_for_link(link)\n\n    def get_ephem_path_for_link(self, link: Link) -> str:\n        return self._ephem_cache.get_path_for_link(link)\n\n    def get(\n        self,\n        link: Link,\n        package_name: Optional[str],\n        supported_tags: List[Tag],\n    ) -> Link:\n        cache_entry = self.get_cache_entry(link, package_name, supported_tags)\n        if cache_entry is None:\n            return link\n        return cache_entry.link\n\n    def get_cache_entry(\n        self,\n        link: Link,\n        package_name: Optional[str],\n        supported_tags: List[Tag],\n    ) -> Optional[CacheEntry]:\n        \"\"\"Returns a CacheEntry with a link to a cached item if it exists or\n        None. The cache entry indicates if the item was found in the persistent\n        or ephemeral cache.\n        \"\"\"\n        retval = self._wheel_cache.get(\n            link=link,\n            package_name=package_name,\n            supported_tags=supported_tags,\n        )\n        if retval is not link:\n            return CacheEntry(retval, persistent=True)\n\n        retval = self._ephem_cache.get(\n            link=link,\n            package_name=package_name,\n            supported_tags=supported_tags,\n        )\n        if retval is not link:\n            return CacheEntry(retval, persistent=False)\n\n        return None\n\n    @staticmethod\n    def record_download_origin(cache_dir: str, download_info: DirectUrl) -> None:\n        origin_path = Path(cache_dir) / ORIGIN_JSON_NAME\n        if origin_path.is_file():\n            origin = DirectUrl.from_json(origin_path.read_text())\n            # TODO: use DirectUrl.equivalent when https://github.com/pypa/pip/pull/10564\n            # is merged.\n            if origin.url != download_info.url:\n                logger.warning(\n                    \"Origin URL %s in cache entry %s does not match download URL %s. \"\n                    \"This is likely a pip bug or a cache corruption issue.\",\n                    origin.url,\n                    cache_dir,\n                    download_info.url,\n                )\n        origin_path.write_text(download_info.to_json(), encoding=\"utf-8\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/cli/__init__.py",
    "content": "\"\"\"Subpackage containing all of pip's command line interface related code\n\"\"\"\n\n# This file intentionally does not import submodules\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/cli/autocompletion.py",
    "content": "\"\"\"Logic that powers autocompletion installed by ``pip completion``.\n\"\"\"\n\nimport optparse\nimport os\nimport sys\nfrom itertools import chain\nfrom typing import Any, Iterable, List, Optional\n\nfrom pip._internal.cli.main_parser import create_main_parser\nfrom pip._internal.commands import commands_dict, create_command\nfrom pip._internal.metadata import get_default_environment\n\n\ndef autocomplete() -> None:\n    \"\"\"Entry Point for completion of main and subcommand options.\"\"\"\n    # Don't complete if user hasn't sourced bash_completion file.\n    if \"PIP_AUTO_COMPLETE\" not in os.environ:\n        return\n    cwords = os.environ[\"COMP_WORDS\"].split()[1:]\n    cword = int(os.environ[\"COMP_CWORD\"])\n    try:\n        current = cwords[cword - 1]\n    except IndexError:\n        current = \"\"\n\n    parser = create_main_parser()\n    subcommands = list(commands_dict)\n    options = []\n\n    # subcommand\n    subcommand_name: Optional[str] = None\n    for word in cwords:\n        if word in subcommands:\n            subcommand_name = word\n            break\n    # subcommand options\n    if subcommand_name is not None:\n        # special case: 'help' subcommand has no options\n        if subcommand_name == \"help\":\n            sys.exit(1)\n        # special case: list locally installed dists for show and uninstall\n        should_list_installed = not current.startswith(\"-\") and subcommand_name in [\n            \"show\",\n            \"uninstall\",\n        ]\n        if should_list_installed:\n            env = get_default_environment()\n            lc = current.lower()\n            installed = [\n                dist.canonical_name\n                for dist in env.iter_installed_distributions(local_only=True)\n                if dist.canonical_name.startswith(lc)\n                and dist.canonical_name not in cwords[1:]\n            ]\n            # if there are no dists installed, fall back to option completion\n            if installed:\n                for dist in installed:\n                    print(dist)\n                sys.exit(1)\n\n        should_list_installables = (\n            not current.startswith(\"-\") and subcommand_name == \"install\"\n        )\n        if should_list_installables:\n            for path in auto_complete_paths(current, \"path\"):\n                print(path)\n            sys.exit(1)\n\n        subcommand = create_command(subcommand_name)\n\n        for opt in subcommand.parser.option_list_all:\n            if opt.help != optparse.SUPPRESS_HELP:\n                for opt_str in opt._long_opts + opt._short_opts:\n                    options.append((opt_str, opt.nargs))\n\n        # filter out previously specified options from available options\n        prev_opts = [x.split(\"=\")[0] for x in cwords[1 : cword - 1]]\n        options = [(x, v) for (x, v) in options if x not in prev_opts]\n        # filter options by current input\n        options = [(k, v) for k, v in options if k.startswith(current)]\n        # get completion type given cwords and available subcommand options\n        completion_type = get_path_completion_type(\n            cwords,\n            cword,\n            subcommand.parser.option_list_all,\n        )\n        # get completion files and directories if ``completion_type`` is\n        # ``<file>``, ``<dir>`` or ``<path>``\n        if completion_type:\n            paths = auto_complete_paths(current, completion_type)\n            options = [(path, 0) for path in paths]\n        for option in options:\n            opt_label = option[0]\n            # append '=' to options which require args\n            if option[1] and option[0][:2] == \"--\":\n                opt_label += \"=\"\n            print(opt_label)\n    else:\n        # show main parser options only when necessary\n\n        opts = [i.option_list for i in parser.option_groups]\n        opts.append(parser.option_list)\n        flattened_opts = chain.from_iterable(opts)\n        if current.startswith(\"-\"):\n            for opt in flattened_opts:\n                if opt.help != optparse.SUPPRESS_HELP:\n                    subcommands += opt._long_opts + opt._short_opts\n        else:\n            # get completion type given cwords and all available options\n            completion_type = get_path_completion_type(cwords, cword, flattened_opts)\n            if completion_type:\n                subcommands = list(auto_complete_paths(current, completion_type))\n\n        print(\" \".join([x for x in subcommands if x.startswith(current)]))\n    sys.exit(1)\n\n\ndef get_path_completion_type(\n    cwords: List[str], cword: int, opts: Iterable[Any]\n) -> Optional[str]:\n    \"\"\"Get the type of path completion (``file``, ``dir``, ``path`` or None)\n\n    :param cwords: same as the environmental variable ``COMP_WORDS``\n    :param cword: same as the environmental variable ``COMP_CWORD``\n    :param opts: The available options to check\n    :return: path completion type (``file``, ``dir``, ``path`` or None)\n    \"\"\"\n    if cword < 2 or not cwords[cword - 2].startswith(\"-\"):\n        return None\n    for opt in opts:\n        if opt.help == optparse.SUPPRESS_HELP:\n            continue\n        for o in str(opt).split(\"/\"):\n            if cwords[cword - 2].split(\"=\")[0] == o:\n                if not opt.metavar or any(\n                    x in (\"path\", \"file\", \"dir\") for x in opt.metavar.split(\"/\")\n                ):\n                    return opt.metavar\n    return None\n\n\ndef auto_complete_paths(current: str, completion_type: str) -> Iterable[str]:\n    \"\"\"If ``completion_type`` is ``file`` or ``path``, list all regular files\n    and directories starting with ``current``; otherwise only list directories\n    starting with ``current``.\n\n    :param current: The word to be completed\n    :param completion_type: path completion type(``file``, ``path`` or ``dir``)\n    :return: A generator of regular files and/or directories\n    \"\"\"\n    directory, filename = os.path.split(current)\n    current_path = os.path.abspath(directory)\n    # Don't complete paths if they can't be accessed\n    if not os.access(current_path, os.R_OK):\n        return\n    filename = os.path.normcase(filename)\n    # list all files that start with ``filename``\n    file_list = (\n        x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)\n    )\n    for f in file_list:\n        opt = os.path.join(current_path, f)\n        comp_file = os.path.normcase(os.path.join(directory, f))\n        # complete regular files when there is not ``<dir>`` after option\n        # complete directories when there is ``<file>``, ``<path>`` or\n        # ``<dir>``after option\n        if completion_type != \"dir\" and os.path.isfile(opt):\n            yield comp_file\n        elif os.path.isdir(opt):\n            yield os.path.join(comp_file, \"\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/cli/base_command.py",
    "content": "\"\"\"Base Command class, and related routines\"\"\"\n\nimport functools\nimport logging\nimport logging.config\nimport optparse\nimport os\nimport sys\nimport traceback\nfrom optparse import Values\nfrom typing import Any, Callable, List, Optional, Tuple\n\nfrom pip._vendor.rich import traceback as rich_traceback\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.command_context import CommandContextMixIn\nfrom pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter\nfrom pip._internal.cli.status_codes import (\n    ERROR,\n    PREVIOUS_BUILD_DIR_ERROR,\n    UNKNOWN_ERROR,\n    VIRTUALENV_NOT_FOUND,\n)\nfrom pip._internal.exceptions import (\n    BadCommand,\n    CommandError,\n    DiagnosticPipError,\n    InstallationError,\n    NetworkConnectionError,\n    PreviousBuildDirError,\n    UninstallationError,\n)\nfrom pip._internal.utils.filesystem import check_path_owner\nfrom pip._internal.utils.logging import BrokenStdoutLoggingError, setup_logging\nfrom pip._internal.utils.misc import get_prog, normalize_path\nfrom pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistry\nfrom pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registry\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\n__all__ = [\"Command\"]\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(CommandContextMixIn):\n    usage: str = \"\"\n    ignore_require_venv: bool = False\n\n    def __init__(self, name: str, summary: str, isolated: bool = False) -> None:\n        super().__init__()\n\n        self.name = name\n        self.summary = summary\n        self.parser = ConfigOptionParser(\n            usage=self.usage,\n            prog=f\"{get_prog()} {name}\",\n            formatter=UpdatingDefaultsHelpFormatter(),\n            add_help_option=False,\n            name=name,\n            description=self.__doc__,\n            isolated=isolated,\n        )\n\n        self.tempdir_registry: Optional[TempDirRegistry] = None\n\n        # Commands should add options to this option group\n        optgroup_name = f\"{self.name.capitalize()} Options\"\n        self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)\n\n        # Add the general options\n        gen_opts = cmdoptions.make_option_group(\n            cmdoptions.general_group,\n            self.parser,\n        )\n        self.parser.add_option_group(gen_opts)\n\n        self.add_options()\n\n    def add_options(self) -> None:\n        pass\n\n    def handle_pip_version_check(self, options: Values) -> None:\n        \"\"\"\n        This is a no-op so that commands by default do not do the pip version\n        check.\n        \"\"\"\n        # Make sure we do the pip version check if the index_group options\n        # are present.\n        assert not hasattr(options, \"no_index\")\n\n    def run(self, options: Values, args: List[str]) -> int:\n        raise NotImplementedError\n\n    def parse_args(self, args: List[str]) -> Tuple[Values, List[str]]:\n        # factored out for testability\n        return self.parser.parse_args(args)\n\n    def main(self, args: List[str]) -> int:\n        try:\n            with self.main_context():\n                return self._main(args)\n        finally:\n            logging.shutdown()\n\n    def _main(self, args: List[str]) -> int:\n        # We must initialize this before the tempdir manager, otherwise the\n        # configuration would not be accessible by the time we clean up the\n        # tempdir manager.\n        self.tempdir_registry = self.enter_context(tempdir_registry())\n        # Intentionally set as early as possible so globally-managed temporary\n        # directories are available to the rest of the code.\n        self.enter_context(global_tempdir_manager())\n\n        options, args = self.parse_args(args)\n\n        # Set verbosity so that it can be used elsewhere.\n        self.verbosity = options.verbose - options.quiet\n\n        level_number = setup_logging(\n            verbosity=self.verbosity,\n            no_color=options.no_color,\n            user_log_file=options.log,\n        )\n\n        # TODO: Try to get these passing down from the command?\n        #       without resorting to os.environ to hold these.\n        #       This also affects isolated builds and it should.\n\n        if options.no_input:\n            os.environ[\"PIP_NO_INPUT\"] = \"1\"\n\n        if options.exists_action:\n            os.environ[\"PIP_EXISTS_ACTION\"] = \" \".join(options.exists_action)\n\n        if options.require_venv and not self.ignore_require_venv:\n            # If a venv is required check if it can really be found\n            if not running_under_virtualenv():\n                logger.critical(\"Could not find an activated virtualenv (required).\")\n                sys.exit(VIRTUALENV_NOT_FOUND)\n\n        if options.cache_dir:\n            options.cache_dir = normalize_path(options.cache_dir)\n            if not check_path_owner(options.cache_dir):\n                logger.warning(\n                    \"The directory '%s' or its parent directory is not owned \"\n                    \"or is not writable by the current user. The cache \"\n                    \"has been disabled. Check the permissions and owner of \"\n                    \"that directory. If executing pip with sudo, you should \"\n                    \"use sudo's -H flag.\",\n                    options.cache_dir,\n                )\n                options.cache_dir = None\n\n        def intercepts_unhandled_exc(\n            run_func: Callable[..., int]\n        ) -> Callable[..., int]:\n            @functools.wraps(run_func)\n            def exc_logging_wrapper(*args: Any) -> int:\n                try:\n                    status = run_func(*args)\n                    assert isinstance(status, int)\n                    return status\n                except DiagnosticPipError as exc:\n                    logger.error(\"[present-rich] %s\", exc)\n                    logger.debug(\"Exception information:\", exc_info=True)\n\n                    return ERROR\n                except PreviousBuildDirError as exc:\n                    logger.critical(str(exc))\n                    logger.debug(\"Exception information:\", exc_info=True)\n\n                    return PREVIOUS_BUILD_DIR_ERROR\n                except (\n                    InstallationError,\n                    UninstallationError,\n                    BadCommand,\n                    NetworkConnectionError,\n                ) as exc:\n                    logger.critical(str(exc))\n                    logger.debug(\"Exception information:\", exc_info=True)\n\n                    return ERROR\n                except CommandError as exc:\n                    logger.critical(\"%s\", exc)\n                    logger.debug(\"Exception information:\", exc_info=True)\n\n                    return ERROR\n                except BrokenStdoutLoggingError:\n                    # Bypass our logger and write any remaining messages to\n                    # stderr because stdout no longer works.\n                    print(\"ERROR: Pipe to stdout was broken\", file=sys.stderr)\n                    if level_number <= logging.DEBUG:\n                        traceback.print_exc(file=sys.stderr)\n\n                    return ERROR\n                except KeyboardInterrupt:\n                    logger.critical(\"Operation cancelled by user\")\n                    logger.debug(\"Exception information:\", exc_info=True)\n\n                    return ERROR\n                except BaseException:\n                    logger.critical(\"Exception:\", exc_info=True)\n\n                    return UNKNOWN_ERROR\n\n            return exc_logging_wrapper\n\n        try:\n            if not options.debug_mode:\n                run = intercepts_unhandled_exc(self.run)\n            else:\n                run = self.run\n                rich_traceback.install(show_locals=True)\n            return run(options, args)\n        finally:\n            self.handle_pip_version_check(options)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/cli/cmdoptions.py",
    "content": "\"\"\"\nshared options and groups\n\nThe principle here is to define options once, but *not* instantiate them\nglobally. One reason being that options with action='append' can carry state\nbetween parses. pip parses general options twice internally, and shouldn't\npass on state. To be consistent, all options will follow this design.\n\"\"\"\n\n# The following comment should be removed at some point in the future.\n# mypy: strict-optional=False\n\nimport importlib.util\nimport logging\nimport os\nimport textwrap\nfrom functools import partial\nfrom optparse import SUPPRESS_HELP, Option, OptionGroup, OptionParser, Values\nfrom textwrap import dedent\nfrom typing import Any, Callable, Dict, Optional, Tuple\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.cli.parser import ConfigOptionParser\nfrom pip._internal.exceptions import CommandError\nfrom pip._internal.locations import USER_CACHE_DIR, get_src_prefix\nfrom pip._internal.models.format_control import FormatControl\nfrom pip._internal.models.index import PyPI\nfrom pip._internal.models.target_python import TargetPython\nfrom pip._internal.utils.hashes import STRONG_HASHES\nfrom pip._internal.utils.misc import strtobool\n\nlogger = logging.getLogger(__name__)\n\n\ndef raise_option_error(parser: OptionParser, option: Option, msg: str) -> None:\n    \"\"\"\n    Raise an option parsing error using parser.error().\n\n    Args:\n      parser: an OptionParser instance.\n      option: an Option instance.\n      msg: the error text.\n    \"\"\"\n    msg = f\"{option} error: {msg}\"\n    msg = textwrap.fill(\" \".join(msg.split()))\n    parser.error(msg)\n\n\ndef make_option_group(group: Dict[str, Any], parser: ConfigOptionParser) -> OptionGroup:\n    \"\"\"\n    Return an OptionGroup object\n    group  -- assumed to be dict with 'name' and 'options' keys\n    parser -- an optparse Parser\n    \"\"\"\n    option_group = OptionGroup(parser, group[\"name\"])\n    for option in group[\"options\"]:\n        option_group.add_option(option())\n    return option_group\n\n\ndef check_dist_restriction(options: Values, check_target: bool = False) -> None:\n    \"\"\"Function for determining if custom platform options are allowed.\n\n    :param options: The OptionParser options.\n    :param check_target: Whether or not to check if --target is being used.\n    \"\"\"\n    dist_restriction_set = any(\n        [\n            options.python_version,\n            options.platforms,\n            options.abis,\n            options.implementation,\n        ]\n    )\n\n    binary_only = FormatControl(set(), {\":all:\"})\n    sdist_dependencies_allowed = (\n        options.format_control != binary_only and not options.ignore_dependencies\n    )\n\n    # Installations or downloads using dist restrictions must not combine\n    # source distributions and dist-specific wheels, as they are not\n    # guaranteed to be locally compatible.\n    if dist_restriction_set and sdist_dependencies_allowed:\n        raise CommandError(\n            \"When restricting platform and interpreter constraints using \"\n            \"--python-version, --platform, --abi, or --implementation, \"\n            \"either --no-deps must be set, or --only-binary=:all: must be \"\n            \"set and --no-binary must not be set (or must be set to \"\n            \":none:).\"\n        )\n\n    if check_target:\n        if dist_restriction_set and not options.target_dir:\n            raise CommandError(\n                \"Can not use any platform or abi specific options unless \"\n                \"installing via '--target'\"\n            )\n\n\ndef _path_option_check(option: Option, opt: str, value: str) -> str:\n    return os.path.expanduser(value)\n\n\ndef _package_name_option_check(option: Option, opt: str, value: str) -> str:\n    return canonicalize_name(value)\n\n\nclass PipOption(Option):\n    TYPES = Option.TYPES + (\"path\", \"package_name\")\n    TYPE_CHECKER = Option.TYPE_CHECKER.copy()\n    TYPE_CHECKER[\"package_name\"] = _package_name_option_check\n    TYPE_CHECKER[\"path\"] = _path_option_check\n\n\n###########\n# options #\n###########\n\nhelp_: Callable[..., Option] = partial(\n    Option,\n    \"-h\",\n    \"--help\",\n    dest=\"help\",\n    action=\"help\",\n    help=\"Show help.\",\n)\n\ndebug_mode: Callable[..., Option] = partial(\n    Option,\n    \"--debug\",\n    dest=\"debug_mode\",\n    action=\"store_true\",\n    default=False,\n    help=(\n        \"Let unhandled exceptions propagate outside the main subroutine, \"\n        \"instead of logging them to stderr.\"\n    ),\n)\n\nisolated_mode: Callable[..., Option] = partial(\n    Option,\n    \"--isolated\",\n    dest=\"isolated_mode\",\n    action=\"store_true\",\n    default=False,\n    help=(\n        \"Run pip in an isolated mode, ignoring environment variables and user \"\n        \"configuration.\"\n    ),\n)\n\nrequire_virtualenv: Callable[..., Option] = partial(\n    Option,\n    \"--require-virtualenv\",\n    \"--require-venv\",\n    dest=\"require_venv\",\n    action=\"store_true\",\n    default=False,\n    help=(\n        \"Allow pip to only run in a virtual environment; \"\n        \"exit with an error otherwise.\"\n    ),\n)\n\npython: Callable[..., Option] = partial(\n    Option,\n    \"--python\",\n    dest=\"python\",\n    help=\"Run pip with the specified Python interpreter.\",\n)\n\nverbose: Callable[..., Option] = partial(\n    Option,\n    \"-v\",\n    \"--verbose\",\n    dest=\"verbose\",\n    action=\"count\",\n    default=0,\n    help=\"Give more output. Option is additive, and can be used up to 3 times.\",\n)\n\nno_color: Callable[..., Option] = partial(\n    Option,\n    \"--no-color\",\n    dest=\"no_color\",\n    action=\"store_true\",\n    default=False,\n    help=\"Suppress colored output.\",\n)\n\nversion: Callable[..., Option] = partial(\n    Option,\n    \"-V\",\n    \"--version\",\n    dest=\"version\",\n    action=\"store_true\",\n    help=\"Show version and exit.\",\n)\n\nquiet: Callable[..., Option] = partial(\n    Option,\n    \"-q\",\n    \"--quiet\",\n    dest=\"quiet\",\n    action=\"count\",\n    default=0,\n    help=(\n        \"Give less output. Option is additive, and can be used up to 3\"\n        \" times (corresponding to WARNING, ERROR, and CRITICAL logging\"\n        \" levels).\"\n    ),\n)\n\nprogress_bar: Callable[..., Option] = partial(\n    Option,\n    \"--progress-bar\",\n    dest=\"progress_bar\",\n    type=\"choice\",\n    choices=[\"on\", \"off\"],\n    default=\"on\",\n    help=\"Specify whether the progress bar should be used [on, off] (default: on)\",\n)\n\nlog: Callable[..., Option] = partial(\n    PipOption,\n    \"--log\",\n    \"--log-file\",\n    \"--local-log\",\n    dest=\"log\",\n    metavar=\"path\",\n    type=\"path\",\n    help=\"Path to a verbose appending log.\",\n)\n\nno_input: Callable[..., Option] = partial(\n    Option,\n    # Don't ask for input\n    \"--no-input\",\n    dest=\"no_input\",\n    action=\"store_true\",\n    default=False,\n    help=\"Disable prompting for input.\",\n)\n\nproxy: Callable[..., Option] = partial(\n    Option,\n    \"--proxy\",\n    dest=\"proxy\",\n    type=\"str\",\n    default=\"\",\n    help=\"Specify a proxy in the form scheme://[user:passwd@]proxy.server:port.\",\n)\n\nretries: Callable[..., Option] = partial(\n    Option,\n    \"--retries\",\n    dest=\"retries\",\n    type=\"int\",\n    default=5,\n    help=\"Maximum number of retries each connection should attempt \"\n    \"(default %default times).\",\n)\n\ntimeout: Callable[..., Option] = partial(\n    Option,\n    \"--timeout\",\n    \"--default-timeout\",\n    metavar=\"sec\",\n    dest=\"timeout\",\n    type=\"float\",\n    default=15,\n    help=\"Set the socket timeout (default %default seconds).\",\n)\n\n\ndef exists_action() -> Option:\n    return Option(\n        # Option when path already exist\n        \"--exists-action\",\n        dest=\"exists_action\",\n        type=\"choice\",\n        choices=[\"s\", \"i\", \"w\", \"b\", \"a\"],\n        default=[],\n        action=\"append\",\n        metavar=\"action\",\n        help=\"Default action when a path already exists: \"\n        \"(s)witch, (i)gnore, (w)ipe, (b)ackup, (a)bort.\",\n    )\n\n\ncert: Callable[..., Option] = partial(\n    PipOption,\n    \"--cert\",\n    dest=\"cert\",\n    type=\"path\",\n    metavar=\"path\",\n    help=(\n        \"Path to PEM-encoded CA certificate bundle. \"\n        \"If provided, overrides the default. \"\n        \"See 'SSL Certificate Verification' in pip documentation \"\n        \"for more information.\"\n    ),\n)\n\nclient_cert: Callable[..., Option] = partial(\n    PipOption,\n    \"--client-cert\",\n    dest=\"client_cert\",\n    type=\"path\",\n    default=None,\n    metavar=\"path\",\n    help=\"Path to SSL client certificate, a single file containing the \"\n    \"private key and the certificate in PEM format.\",\n)\n\nindex_url: Callable[..., Option] = partial(\n    Option,\n    \"-i\",\n    \"--index-url\",\n    \"--pypi-url\",\n    dest=\"index_url\",\n    metavar=\"URL\",\n    default=PyPI.simple_url,\n    help=\"Base URL of the Python Package Index (default %default). \"\n    \"This should point to a repository compliant with PEP 503 \"\n    \"(the simple repository API) or a local directory laid out \"\n    \"in the same format.\",\n)\n\n\ndef extra_index_url() -> Option:\n    return Option(\n        \"--extra-index-url\",\n        dest=\"extra_index_urls\",\n        metavar=\"URL\",\n        action=\"append\",\n        default=[],\n        help=\"Extra URLs of package indexes to use in addition to \"\n        \"--index-url. Should follow the same rules as \"\n        \"--index-url.\",\n    )\n\n\nno_index: Callable[..., Option] = partial(\n    Option,\n    \"--no-index\",\n    dest=\"no_index\",\n    action=\"store_true\",\n    default=False,\n    help=\"Ignore package index (only looking at --find-links URLs instead).\",\n)\n\n\ndef find_links() -> Option:\n    return Option(\n        \"-f\",\n        \"--find-links\",\n        dest=\"find_links\",\n        action=\"append\",\n        default=[],\n        metavar=\"url\",\n        help=\"If a URL or path to an html file, then parse for links to \"\n        \"archives such as sdist (.tar.gz) or wheel (.whl) files. \"\n        \"If a local path or file:// URL that's a directory, \"\n        \"then look for archives in the directory listing. \"\n        \"Links to VCS project URLs are not supported.\",\n    )\n\n\ndef trusted_host() -> Option:\n    return Option(\n        \"--trusted-host\",\n        dest=\"trusted_hosts\",\n        action=\"append\",\n        metavar=\"HOSTNAME\",\n        default=[],\n        help=\"Mark this host or host:port pair as trusted, even though it \"\n        \"does not have valid or any HTTPS.\",\n    )\n\n\ndef constraints() -> Option:\n    return Option(\n        \"-c\",\n        \"--constraint\",\n        dest=\"constraints\",\n        action=\"append\",\n        default=[],\n        metavar=\"file\",\n        help=\"Constrain versions using the given constraints file. \"\n        \"This option can be used multiple times.\",\n    )\n\n\ndef requirements() -> Option:\n    return Option(\n        \"-r\",\n        \"--requirement\",\n        dest=\"requirements\",\n        action=\"append\",\n        default=[],\n        metavar=\"file\",\n        help=\"Install from the given requirements file. \"\n        \"This option can be used multiple times.\",\n    )\n\n\ndef editable() -> Option:\n    return Option(\n        \"-e\",\n        \"--editable\",\n        dest=\"editables\",\n        action=\"append\",\n        default=[],\n        metavar=\"path/url\",\n        help=(\n            \"Install a project in editable mode (i.e. setuptools \"\n            '\"develop mode\") from a local project path or a VCS url.'\n        ),\n    )\n\n\ndef _handle_src(option: Option, opt_str: str, value: str, parser: OptionParser) -> None:\n    value = os.path.abspath(value)\n    setattr(parser.values, option.dest, value)\n\n\nsrc: Callable[..., Option] = partial(\n    PipOption,\n    \"--src\",\n    \"--source\",\n    \"--source-dir\",\n    \"--source-directory\",\n    dest=\"src_dir\",\n    type=\"path\",\n    metavar=\"dir\",\n    default=get_src_prefix(),\n    action=\"callback\",\n    callback=_handle_src,\n    help=\"Directory to check out editable projects into. \"\n    'The default in a virtualenv is \"<venv path>/src\". '\n    'The default for global installs is \"<current dir>/src\".',\n)\n\n\ndef _get_format_control(values: Values, option: Option) -> Any:\n    \"\"\"Get a format_control object.\"\"\"\n    return getattr(values, option.dest)\n\n\ndef _handle_no_binary(\n    option: Option, opt_str: str, value: str, parser: OptionParser\n) -> None:\n    existing = _get_format_control(parser.values, option)\n    FormatControl.handle_mutual_excludes(\n        value,\n        existing.no_binary,\n        existing.only_binary,\n    )\n\n\ndef _handle_only_binary(\n    option: Option, opt_str: str, value: str, parser: OptionParser\n) -> None:\n    existing = _get_format_control(parser.values, option)\n    FormatControl.handle_mutual_excludes(\n        value,\n        existing.only_binary,\n        existing.no_binary,\n    )\n\n\ndef no_binary() -> Option:\n    format_control = FormatControl(set(), set())\n    return Option(\n        \"--no-binary\",\n        dest=\"format_control\",\n        action=\"callback\",\n        callback=_handle_no_binary,\n        type=\"str\",\n        default=format_control,\n        help=\"Do not use binary packages. Can be supplied multiple times, and \"\n        'each time adds to the existing value. Accepts either \":all:\" to '\n        'disable all binary packages, \":none:\" to empty the set (notice '\n        \"the colons), or one or more package names with commas between \"\n        \"them (no colons). Note that some packages are tricky to compile \"\n        \"and may fail to install when this option is used on them.\",\n    )\n\n\ndef only_binary() -> Option:\n    format_control = FormatControl(set(), set())\n    return Option(\n        \"--only-binary\",\n        dest=\"format_control\",\n        action=\"callback\",\n        callback=_handle_only_binary,\n        type=\"str\",\n        default=format_control,\n        help=\"Do not use source packages. Can be supplied multiple times, and \"\n        'each time adds to the existing value. Accepts either \":all:\" to '\n        'disable all source packages, \":none:\" to empty the set, or one '\n        \"or more package names with commas between them. Packages \"\n        \"without binary distributions will fail to install when this \"\n        \"option is used on them.\",\n    )\n\n\nplatforms: Callable[..., Option] = partial(\n    Option,\n    \"--platform\",\n    dest=\"platforms\",\n    metavar=\"platform\",\n    action=\"append\",\n    default=None,\n    help=(\n        \"Only use wheels compatible with <platform>. Defaults to the \"\n        \"platform of the running system. Use this option multiple times to \"\n        \"specify multiple platforms supported by the target interpreter.\"\n    ),\n)\n\n\n# This was made a separate function for unit-testing purposes.\ndef _convert_python_version(value: str) -> Tuple[Tuple[int, ...], Optional[str]]:\n    \"\"\"\n    Convert a version string like \"3\", \"37\", or \"3.7.3\" into a tuple of ints.\n\n    :return: A 2-tuple (version_info, error_msg), where `error_msg` is\n        non-None if and only if there was a parsing error.\n    \"\"\"\n    if not value:\n        # The empty string is the same as not providing a value.\n        return (None, None)\n\n    parts = value.split(\".\")\n    if len(parts) > 3:\n        return ((), \"at most three version parts are allowed\")\n\n    if len(parts) == 1:\n        # Then we are in the case of \"3\" or \"37\".\n        value = parts[0]\n        if len(value) > 1:\n            parts = [value[0], value[1:]]\n\n    try:\n        version_info = tuple(int(part) for part in parts)\n    except ValueError:\n        return ((), \"each version part must be an integer\")\n\n    return (version_info, None)\n\n\ndef _handle_python_version(\n    option: Option, opt_str: str, value: str, parser: OptionParser\n) -> None:\n    \"\"\"\n    Handle a provided --python-version value.\n    \"\"\"\n    version_info, error_msg = _convert_python_version(value)\n    if error_msg is not None:\n        msg = \"invalid --python-version value: {!r}: {}\".format(\n            value,\n            error_msg,\n        )\n        raise_option_error(parser, option=option, msg=msg)\n\n    parser.values.python_version = version_info\n\n\npython_version: Callable[..., Option] = partial(\n    Option,\n    \"--python-version\",\n    dest=\"python_version\",\n    metavar=\"python_version\",\n    action=\"callback\",\n    callback=_handle_python_version,\n    type=\"str\",\n    default=None,\n    help=dedent(\n        \"\"\"\\\n    The Python interpreter version to use for wheel and \"Requires-Python\"\n    compatibility checks. Defaults to a version derived from the running\n    interpreter. The version can be specified using up to three dot-separated\n    integers (e.g. \"3\" for 3.0.0, \"3.7\" for 3.7.0, or \"3.7.3\"). A major-minor\n    version can also be given as a string without dots (e.g. \"37\" for 3.7.0).\n    \"\"\"\n    ),\n)\n\n\nimplementation: Callable[..., Option] = partial(\n    Option,\n    \"--implementation\",\n    dest=\"implementation\",\n    metavar=\"implementation\",\n    default=None,\n    help=(\n        \"Only use wheels compatible with Python \"\n        \"implementation <implementation>, e.g. 'pp', 'jy', 'cp', \"\n        \" or 'ip'. If not specified, then the current \"\n        \"interpreter implementation is used.  Use 'py' to force \"\n        \"implementation-agnostic wheels.\"\n    ),\n)\n\n\nabis: Callable[..., Option] = partial(\n    Option,\n    \"--abi\",\n    dest=\"abis\",\n    metavar=\"abi\",\n    action=\"append\",\n    default=None,\n    help=(\n        \"Only use wheels compatible with Python abi <abi>, e.g. 'pypy_41'. \"\n        \"If not specified, then the current interpreter abi tag is used. \"\n        \"Use this option multiple times to specify multiple abis supported \"\n        \"by the target interpreter. Generally you will need to specify \"\n        \"--implementation, --platform, and --python-version when using this \"\n        \"option.\"\n    ),\n)\n\n\ndef add_target_python_options(cmd_opts: OptionGroup) -> None:\n    cmd_opts.add_option(platforms())\n    cmd_opts.add_option(python_version())\n    cmd_opts.add_option(implementation())\n    cmd_opts.add_option(abis())\n\n\ndef make_target_python(options: Values) -> TargetPython:\n    target_python = TargetPython(\n        platforms=options.platforms,\n        py_version_info=options.python_version,\n        abis=options.abis,\n        implementation=options.implementation,\n    )\n\n    return target_python\n\n\ndef prefer_binary() -> Option:\n    return Option(\n        \"--prefer-binary\",\n        dest=\"prefer_binary\",\n        action=\"store_true\",\n        default=False,\n        help=\"Prefer older binary packages over newer source packages.\",\n    )\n\n\ncache_dir: Callable[..., Option] = partial(\n    PipOption,\n    \"--cache-dir\",\n    dest=\"cache_dir\",\n    default=USER_CACHE_DIR,\n    metavar=\"dir\",\n    type=\"path\",\n    help=\"Store the cache data in <dir>.\",\n)\n\n\ndef _handle_no_cache_dir(\n    option: Option, opt: str, value: str, parser: OptionParser\n) -> None:\n    \"\"\"\n    Process a value provided for the --no-cache-dir option.\n\n    This is an optparse.Option callback for the --no-cache-dir option.\n    \"\"\"\n    # The value argument will be None if --no-cache-dir is passed via the\n    # command-line, since the option doesn't accept arguments.  However,\n    # the value can be non-None if the option is triggered e.g. by an\n    # environment variable, like PIP_NO_CACHE_DIR=true.\n    if value is not None:\n        # Then parse the string value to get argument error-checking.\n        try:\n            strtobool(value)\n        except ValueError as exc:\n            raise_option_error(parser, option=option, msg=str(exc))\n\n    # Originally, setting PIP_NO_CACHE_DIR to a value that strtobool()\n    # converted to 0 (like \"false\" or \"no\") caused cache_dir to be disabled\n    # rather than enabled (logic would say the latter).  Thus, we disable\n    # the cache directory not just on values that parse to True, but (for\n    # backwards compatibility reasons) also on values that parse to False.\n    # In other words, always set it to False if the option is provided in\n    # some (valid) form.\n    parser.values.cache_dir = False\n\n\nno_cache: Callable[..., Option] = partial(\n    Option,\n    \"--no-cache-dir\",\n    dest=\"cache_dir\",\n    action=\"callback\",\n    callback=_handle_no_cache_dir,\n    help=\"Disable the cache.\",\n)\n\nno_deps: Callable[..., Option] = partial(\n    Option,\n    \"--no-deps\",\n    \"--no-dependencies\",\n    dest=\"ignore_dependencies\",\n    action=\"store_true\",\n    default=False,\n    help=\"Don't install package dependencies.\",\n)\n\nignore_requires_python: Callable[..., Option] = partial(\n    Option,\n    \"--ignore-requires-python\",\n    dest=\"ignore_requires_python\",\n    action=\"store_true\",\n    help=\"Ignore the Requires-Python information.\",\n)\n\nno_build_isolation: Callable[..., Option] = partial(\n    Option,\n    \"--no-build-isolation\",\n    dest=\"build_isolation\",\n    action=\"store_false\",\n    default=True,\n    help=\"Disable isolation when building a modern source distribution. \"\n    \"Build dependencies specified by PEP 518 must be already installed \"\n    \"if this option is used.\",\n)\n\ncheck_build_deps: Callable[..., Option] = partial(\n    Option,\n    \"--check-build-dependencies\",\n    dest=\"check_build_deps\",\n    action=\"store_true\",\n    default=False,\n    help=\"Check the build dependencies when PEP517 is used.\",\n)\n\n\ndef _handle_no_use_pep517(\n    option: Option, opt: str, value: str, parser: OptionParser\n) -> None:\n    \"\"\"\n    Process a value provided for the --no-use-pep517 option.\n\n    This is an optparse.Option callback for the no_use_pep517 option.\n    \"\"\"\n    # Since --no-use-pep517 doesn't accept arguments, the value argument\n    # will be None if --no-use-pep517 is passed via the command-line.\n    # However, the value can be non-None if the option is triggered e.g.\n    # by an environment variable, for example \"PIP_NO_USE_PEP517=true\".\n    if value is not None:\n        msg = \"\"\"A value was passed for --no-use-pep517,\n        probably using either the PIP_NO_USE_PEP517 environment variable\n        or the \"no-use-pep517\" config file option. Use an appropriate value\n        of the PIP_USE_PEP517 environment variable or the \"use-pep517\"\n        config file option instead.\n        \"\"\"\n        raise_option_error(parser, option=option, msg=msg)\n\n    # If user doesn't wish to use pep517, we check if setuptools is installed\n    # and raise error if it is not.\n    if not importlib.util.find_spec(\"setuptools\"):\n        msg = \"It is not possible to use --no-use-pep517 without setuptools installed.\"\n        raise_option_error(parser, option=option, msg=msg)\n\n    # Otherwise, --no-use-pep517 was passed via the command-line.\n    parser.values.use_pep517 = False\n\n\nuse_pep517: Any = partial(\n    Option,\n    \"--use-pep517\",\n    dest=\"use_pep517\",\n    action=\"store_true\",\n    default=None,\n    help=\"Use PEP 517 for building source distributions \"\n    \"(use --no-use-pep517 to force legacy behaviour).\",\n)\n\nno_use_pep517: Any = partial(\n    Option,\n    \"--no-use-pep517\",\n    dest=\"use_pep517\",\n    action=\"callback\",\n    callback=_handle_no_use_pep517,\n    default=None,\n    help=SUPPRESS_HELP,\n)\n\n\ndef _handle_config_settings(\n    option: Option, opt_str: str, value: str, parser: OptionParser\n) -> None:\n    key, sep, val = value.partition(\"=\")\n    if sep != \"=\":\n        parser.error(f\"Arguments to {opt_str} must be of the form KEY=VAL\")  # noqa\n    dest = getattr(parser.values, option.dest)\n    if dest is None:\n        dest = {}\n        setattr(parser.values, option.dest, dest)\n    dest[key] = val\n\n\nconfig_settings: Callable[..., Option] = partial(\n    Option,\n    \"--config-settings\",\n    dest=\"config_settings\",\n    type=str,\n    action=\"callback\",\n    callback=_handle_config_settings,\n    metavar=\"settings\",\n    help=\"Configuration settings to be passed to the PEP 517 build backend. \"\n    \"Settings take the form KEY=VALUE. Use multiple --config-settings options \"\n    \"to pass multiple keys to the backend.\",\n)\n\ninstall_options: Callable[..., Option] = partial(\n    Option,\n    \"--install-option\",\n    dest=\"install_options\",\n    action=\"append\",\n    metavar=\"options\",\n    help=\"Extra arguments to be supplied to the setup.py install \"\n    'command (use like --install-option=\"--install-scripts=/usr/local/'\n    'bin\"). Use multiple --install-option options to pass multiple '\n    \"options to setup.py install. If you are using an option with a \"\n    \"directory path, be sure to use absolute path.\",\n)\n\nbuild_options: Callable[..., Option] = partial(\n    Option,\n    \"--build-option\",\n    dest=\"build_options\",\n    metavar=\"options\",\n    action=\"append\",\n    help=\"Extra arguments to be supplied to 'setup.py bdist_wheel'.\",\n)\n\nglobal_options: Callable[..., Option] = partial(\n    Option,\n    \"--global-option\",\n    dest=\"global_options\",\n    action=\"append\",\n    metavar=\"options\",\n    help=\"Extra global options to be supplied to the setup.py \"\n    \"call before the install or bdist_wheel command.\",\n)\n\nno_clean: Callable[..., Option] = partial(\n    Option,\n    \"--no-clean\",\n    action=\"store_true\",\n    default=False,\n    help=\"Don't clean up build directories.\",\n)\n\npre: Callable[..., Option] = partial(\n    Option,\n    \"--pre\",\n    action=\"store_true\",\n    default=False,\n    help=\"Include pre-release and development versions. By default, \"\n    \"pip only finds stable versions.\",\n)\n\ndisable_pip_version_check: Callable[..., Option] = partial(\n    Option,\n    \"--disable-pip-version-check\",\n    dest=\"disable_pip_version_check\",\n    action=\"store_true\",\n    default=False,\n    help=\"Don't periodically check PyPI to determine whether a new version \"\n    \"of pip is available for download. Implied with --no-index.\",\n)\n\nroot_user_action: Callable[..., Option] = partial(\n    Option,\n    \"--root-user-action\",\n    dest=\"root_user_action\",\n    default=\"warn\",\n    choices=[\"warn\", \"ignore\"],\n    help=\"Action if pip is run as a root user. By default, a warning message is shown.\",\n)\n\n\ndef _handle_merge_hash(\n    option: Option, opt_str: str, value: str, parser: OptionParser\n) -> None:\n    \"\"\"Given a value spelled \"algo:digest\", append the digest to a list\n    pointed to in a dict by the algo name.\"\"\"\n    if not parser.values.hashes:\n        parser.values.hashes = {}\n    try:\n        algo, digest = value.split(\":\", 1)\n    except ValueError:\n        parser.error(\n            \"Arguments to {} must be a hash name \"  # noqa\n            \"followed by a value, like --hash=sha256:\"\n            \"abcde...\".format(opt_str)\n        )\n    if algo not in STRONG_HASHES:\n        parser.error(\n            \"Allowed hash algorithms for {} are {}.\".format(  # noqa\n                opt_str, \", \".join(STRONG_HASHES)\n            )\n        )\n    parser.values.hashes.setdefault(algo, []).append(digest)\n\n\nhash: Callable[..., Option] = partial(\n    Option,\n    \"--hash\",\n    # Hash values eventually end up in InstallRequirement.hashes due to\n    # __dict__ copying in process_line().\n    dest=\"hashes\",\n    action=\"callback\",\n    callback=_handle_merge_hash,\n    type=\"string\",\n    help=\"Verify that the package's archive matches this \"\n    \"hash before installing. Example: --hash=sha256:abcdef...\",\n)\n\n\nrequire_hashes: Callable[..., Option] = partial(\n    Option,\n    \"--require-hashes\",\n    dest=\"require_hashes\",\n    action=\"store_true\",\n    default=False,\n    help=\"Require a hash to check each requirement against, for \"\n    \"repeatable installs. This option is implied when any package in a \"\n    \"requirements file has a --hash option.\",\n)\n\n\nlist_path: Callable[..., Option] = partial(\n    PipOption,\n    \"--path\",\n    dest=\"path\",\n    type=\"path\",\n    action=\"append\",\n    help=\"Restrict to the specified installation path for listing \"\n    \"packages (can be used multiple times).\",\n)\n\n\ndef check_list_path_option(options: Values) -> None:\n    if options.path and (options.user or options.local):\n        raise CommandError(\"Cannot combine '--path' with '--user' or '--local'\")\n\n\nlist_exclude: Callable[..., Option] = partial(\n    PipOption,\n    \"--exclude\",\n    dest=\"excludes\",\n    action=\"append\",\n    metavar=\"package\",\n    type=\"package_name\",\n    help=\"Exclude specified package from the output\",\n)\n\n\nno_python_version_warning: Callable[..., Option] = partial(\n    Option,\n    \"--no-python-version-warning\",\n    dest=\"no_python_version_warning\",\n    action=\"store_true\",\n    default=False,\n    help=\"Silence deprecation warnings for upcoming unsupported Pythons.\",\n)\n\n\nuse_new_feature: Callable[..., Option] = partial(\n    Option,\n    \"--use-feature\",\n    dest=\"features_enabled\",\n    metavar=\"feature\",\n    action=\"append\",\n    default=[],\n    choices=[\n        \"fast-deps\",\n        \"truststore\",\n        \"no-binary-enable-wheel-cache\",\n    ],\n    help=\"Enable new functionality, that may be backward incompatible.\",\n)\n\nuse_deprecated_feature: Callable[..., Option] = partial(\n    Option,\n    \"--use-deprecated\",\n    dest=\"deprecated_features_enabled\",\n    metavar=\"feature\",\n    action=\"append\",\n    default=[],\n    choices=[\n        \"legacy-resolver\",\n    ],\n    help=(\"Enable deprecated functionality, that will be removed in the future.\"),\n)\n\n\n##########\n# groups #\n##########\n\ngeneral_group: Dict[str, Any] = {\n    \"name\": \"General Options\",\n    \"options\": [\n        help_,\n        debug_mode,\n        isolated_mode,\n        require_virtualenv,\n        python,\n        verbose,\n        version,\n        quiet,\n        log,\n        no_input,\n        proxy,\n        retries,\n        timeout,\n        exists_action,\n        trusted_host,\n        cert,\n        client_cert,\n        cache_dir,\n        no_cache,\n        disable_pip_version_check,\n        no_color,\n        no_python_version_warning,\n        use_new_feature,\n        use_deprecated_feature,\n    ],\n}\n\nindex_group: Dict[str, Any] = {\n    \"name\": \"Package Index Options\",\n    \"options\": [\n        index_url,\n        extra_index_url,\n        no_index,\n        find_links,\n    ],\n}\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/cli/command_context.py",
    "content": "from contextlib import ExitStack, contextmanager\nfrom typing import ContextManager, Generator, TypeVar\n\n_T = TypeVar(\"_T\", covariant=True)\n\n\nclass CommandContextMixIn:\n    def __init__(self) -> None:\n        super().__init__()\n        self._in_main_context = False\n        self._main_context = ExitStack()\n\n    @contextmanager\n    def main_context(self) -> Generator[None, None, None]:\n        assert not self._in_main_context\n\n        self._in_main_context = True\n        try:\n            with self._main_context:\n                yield\n        finally:\n            self._in_main_context = False\n\n    def enter_context(self, context_provider: ContextManager[_T]) -> _T:\n        assert self._in_main_context\n\n        return self._main_context.enter_context(context_provider)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/cli/main.py",
    "content": "\"\"\"Primary application entrypoint.\n\"\"\"\nimport locale\nimport logging\nimport os\nimport sys\nfrom typing import List, Optional\n\nfrom pip._internal.cli.autocompletion import autocomplete\nfrom pip._internal.cli.main_parser import parse_command\nfrom pip._internal.commands import create_command\nfrom pip._internal.exceptions import PipError\nfrom pip._internal.utils import deprecation\n\nlogger = logging.getLogger(__name__)\n\n\n# Do not import and use main() directly! Using it directly is actively\n# discouraged by pip's maintainers. The name, location and behavior of\n# this function is subject to change, so calling it directly is not\n# portable across different pip versions.\n\n# In addition, running pip in-process is unsupported and unsafe. This is\n# elaborated in detail at\n# https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.\n# That document also provides suggestions that should work for nearly\n# all users that are considering importing and using main() directly.\n\n# However, we know that certain users will still want to invoke pip\n# in-process. If you understand and accept the implications of using pip\n# in an unsupported manner, the best approach is to use runpy to avoid\n# depending on the exact location of this entry point.\n\n# The following example shows how to use runpy to invoke pip in that\n# case:\n#\n#     sys.argv = [\"pip\", your, args, here]\n#     runpy.run_module(\"pip\", run_name=\"__main__\")\n#\n# Note that this will exit the process after running, unlike a direct\n# call to main. As it is not safe to do any processing after calling\n# main, this should not be an issue in practice.\n\n\ndef main(args: Optional[List[str]] = None) -> int:\n    if args is None:\n        args = sys.argv[1:]\n\n    # Configure our deprecation warnings to be sent through loggers\n    deprecation.install_warning_logger()\n\n    autocomplete()\n\n    try:\n        cmd_name, cmd_args = parse_command(args)\n    except PipError as exc:\n        sys.stderr.write(f\"ERROR: {exc}\")\n        sys.stderr.write(os.linesep)\n        sys.exit(1)\n\n    # Needed for locale.getpreferredencoding(False) to work\n    # in pip._internal.utils.encoding.auto_decode\n    try:\n        locale.setlocale(locale.LC_ALL, \"\")\n    except locale.Error as e:\n        # setlocale can apparently crash if locale are uninitialized\n        logger.debug(\"Ignoring error %s when setting locale\", e)\n    command = create_command(cmd_name, isolated=(\"--isolated\" in cmd_args))\n\n    return command.main(cmd_args)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/cli/main_parser.py",
    "content": "\"\"\"A single place for constructing and exposing the main parser\n\"\"\"\n\nimport os\nimport subprocess\nimport sys\nfrom typing import List, Optional, Tuple\n\nfrom pip._internal.build_env import get_runnable_pip\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter\nfrom pip._internal.commands import commands_dict, get_similar_commands\nfrom pip._internal.exceptions import CommandError\nfrom pip._internal.utils.misc import get_pip_version, get_prog\n\n__all__ = [\"create_main_parser\", \"parse_command\"]\n\n\ndef create_main_parser() -> ConfigOptionParser:\n    \"\"\"Creates and returns the main parser for pip's CLI\"\"\"\n\n    parser = ConfigOptionParser(\n        usage=\"\\n%prog <command> [options]\",\n        add_help_option=False,\n        formatter=UpdatingDefaultsHelpFormatter(),\n        name=\"global\",\n        prog=get_prog(),\n    )\n    parser.disable_interspersed_args()\n\n    parser.version = get_pip_version()\n\n    # add the general options\n    gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)\n    parser.add_option_group(gen_opts)\n\n    # so the help formatter knows\n    parser.main = True  # type: ignore\n\n    # create command listing for description\n    description = [\"\"] + [\n        f\"{name:27} {command_info.summary}\"\n        for name, command_info in commands_dict.items()\n    ]\n    parser.description = \"\\n\".join(description)\n\n    return parser\n\n\ndef identify_python_interpreter(python: str) -> Optional[str]:\n    # If the named file exists, use it.\n    # If it's a directory, assume it's a virtual environment and\n    # look for the environment's Python executable.\n    if os.path.exists(python):\n        if os.path.isdir(python):\n            # bin/python for Unix, Scripts/python.exe for Windows\n            # Try both in case of odd cases like cygwin.\n            for exe in (\"bin/python\", \"Scripts/python.exe\"):\n                py = os.path.join(python, exe)\n                if os.path.exists(py):\n                    return py\n        else:\n            return python\n\n    # Could not find the interpreter specified\n    return None\n\n\ndef parse_command(args: List[str]) -> Tuple[str, List[str]]:\n    parser = create_main_parser()\n\n    # Note: parser calls disable_interspersed_args(), so the result of this\n    # call is to split the initial args into the general options before the\n    # subcommand and everything else.\n    # For example:\n    #  args: ['--timeout=5', 'install', '--user', 'INITools']\n    #  general_options: ['--timeout==5']\n    #  args_else: ['install', '--user', 'INITools']\n    general_options, args_else = parser.parse_args(args)\n\n    # --python\n    if general_options.python and \"_PIP_RUNNING_IN_SUBPROCESS\" not in os.environ:\n        # Re-invoke pip using the specified Python interpreter\n        interpreter = identify_python_interpreter(general_options.python)\n        if interpreter is None:\n            raise CommandError(\n                f\"Could not locate Python interpreter {general_options.python}\"\n            )\n\n        pip_cmd = [\n            interpreter,\n            get_runnable_pip(),\n        ]\n        pip_cmd.extend(args)\n\n        # Set a flag so the child doesn't re-invoke itself, causing\n        # an infinite loop.\n        os.environ[\"_PIP_RUNNING_IN_SUBPROCESS\"] = \"1\"\n        returncode = 0\n        try:\n            proc = subprocess.run(pip_cmd)\n            returncode = proc.returncode\n        except (subprocess.SubprocessError, OSError) as exc:\n            raise CommandError(f\"Failed to run pip under {interpreter}: {exc}\")\n        sys.exit(returncode)\n\n    # --version\n    if general_options.version:\n        sys.stdout.write(parser.version)\n        sys.stdout.write(os.linesep)\n        sys.exit()\n\n    # pip || pip help -> print_help()\n    if not args_else or (args_else[0] == \"help\" and len(args_else) == 1):\n        parser.print_help()\n        sys.exit()\n\n    # the subcommand name\n    cmd_name = args_else[0]\n\n    if cmd_name not in commands_dict:\n        guess = get_similar_commands(cmd_name)\n\n        msg = [f'unknown command \"{cmd_name}\"']\n        if guess:\n            msg.append(f'maybe you meant \"{guess}\"')\n\n        raise CommandError(\" - \".join(msg))\n\n    # all the args without the subcommand\n    cmd_args = args[:]\n    cmd_args.remove(cmd_name)\n\n    return cmd_name, cmd_args\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/cli/parser.py",
    "content": "\"\"\"Base option parser setup\"\"\"\n\nimport logging\nimport optparse\nimport shutil\nimport sys\nimport textwrap\nfrom contextlib import suppress\nfrom typing import Any, Dict, Generator, List, Tuple\n\nfrom pip._internal.cli.status_codes import UNKNOWN_ERROR\nfrom pip._internal.configuration import Configuration, ConfigurationError\nfrom pip._internal.utils.misc import redact_auth_from_url, strtobool\n\nlogger = logging.getLogger(__name__)\n\n\nclass PrettyHelpFormatter(optparse.IndentedHelpFormatter):\n    \"\"\"A prettier/less verbose help formatter for optparse.\"\"\"\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        # help position must be aligned with __init__.parseopts.description\n        kwargs[\"max_help_position\"] = 30\n        kwargs[\"indent_increment\"] = 1\n        kwargs[\"width\"] = shutil.get_terminal_size()[0] - 2\n        super().__init__(*args, **kwargs)\n\n    def format_option_strings(self, option: optparse.Option) -> str:\n        return self._format_option_strings(option)\n\n    def _format_option_strings(\n        self, option: optparse.Option, mvarfmt: str = \" <{}>\", optsep: str = \", \"\n    ) -> str:\n        \"\"\"\n        Return a comma-separated list of option strings and metavars.\n\n        :param option:  tuple of (short opt, long opt), e.g: ('-f', '--format')\n        :param mvarfmt: metavar format string\n        :param optsep:  separator\n        \"\"\"\n        opts = []\n\n        if option._short_opts:\n            opts.append(option._short_opts[0])\n        if option._long_opts:\n            opts.append(option._long_opts[0])\n        if len(opts) > 1:\n            opts.insert(1, optsep)\n\n        if option.takes_value():\n            assert option.dest is not None\n            metavar = option.metavar or option.dest.lower()\n            opts.append(mvarfmt.format(metavar.lower()))\n\n        return \"\".join(opts)\n\n    def format_heading(self, heading: str) -> str:\n        if heading == \"Options\":\n            return \"\"\n        return heading + \":\\n\"\n\n    def format_usage(self, usage: str) -> str:\n        \"\"\"\n        Ensure there is only one newline between usage and the first heading\n        if there is no description.\n        \"\"\"\n        msg = \"\\nUsage: {}\\n\".format(self.indent_lines(textwrap.dedent(usage), \"  \"))\n        return msg\n\n    def format_description(self, description: str) -> str:\n        # leave full control over description to us\n        if description:\n            if hasattr(self.parser, \"main\"):\n                label = \"Commands\"\n            else:\n                label = \"Description\"\n            # some doc strings have initial newlines, some don't\n            description = description.lstrip(\"\\n\")\n            # some doc strings have final newlines and spaces, some don't\n            description = description.rstrip()\n            # dedent, then reindent\n            description = self.indent_lines(textwrap.dedent(description), \"  \")\n            description = f\"{label}:\\n{description}\\n\"\n            return description\n        else:\n            return \"\"\n\n    def format_epilog(self, epilog: str) -> str:\n        # leave full control over epilog to us\n        if epilog:\n            return epilog\n        else:\n            return \"\"\n\n    def indent_lines(self, text: str, indent: str) -> str:\n        new_lines = [indent + line for line in text.split(\"\\n\")]\n        return \"\\n\".join(new_lines)\n\n\nclass UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):\n    \"\"\"Custom help formatter for use in ConfigOptionParser.\n\n    This is updates the defaults before expanding them, allowing\n    them to show up correctly in the help listing.\n\n    Also redact auth from url type options\n    \"\"\"\n\n    def expand_default(self, option: optparse.Option) -> str:\n        default_values = None\n        if self.parser is not None:\n            assert isinstance(self.parser, ConfigOptionParser)\n            self.parser._update_defaults(self.parser.defaults)\n            assert option.dest is not None\n            default_values = self.parser.defaults.get(option.dest)\n        help_text = super().expand_default(option)\n\n        if default_values and option.metavar == \"URL\":\n            if isinstance(default_values, str):\n                default_values = [default_values]\n\n            # If its not a list, we should abort and just return the help text\n            if not isinstance(default_values, list):\n                default_values = []\n\n            for val in default_values:\n                help_text = help_text.replace(val, redact_auth_from_url(val))\n\n        return help_text\n\n\nclass CustomOptionParser(optparse.OptionParser):\n    def insert_option_group(\n        self, idx: int, *args: Any, **kwargs: Any\n    ) -> optparse.OptionGroup:\n        \"\"\"Insert an OptionGroup at a given position.\"\"\"\n        group = self.add_option_group(*args, **kwargs)\n\n        self.option_groups.pop()\n        self.option_groups.insert(idx, group)\n\n        return group\n\n    @property\n    def option_list_all(self) -> List[optparse.Option]:\n        \"\"\"Get a list of all options, including those in option groups.\"\"\"\n        res = self.option_list[:]\n        for i in self.option_groups:\n            res.extend(i.option_list)\n\n        return res\n\n\nclass ConfigOptionParser(CustomOptionParser):\n    \"\"\"Custom option parser which updates its defaults by checking the\n    configuration files and environmental variables\"\"\"\n\n    def __init__(\n        self,\n        *args: Any,\n        name: str,\n        isolated: bool = False,\n        **kwargs: Any,\n    ) -> None:\n        self.name = name\n        self.config = Configuration(isolated)\n\n        assert self.name\n        super().__init__(*args, **kwargs)\n\n    def check_default(self, option: optparse.Option, key: str, val: Any) -> Any:\n        try:\n            return option.check_value(key, val)\n        except optparse.OptionValueError as exc:\n            print(f\"An error occurred during configuration: {exc}\")\n            sys.exit(3)\n\n    def _get_ordered_configuration_items(\n        self,\n    ) -> Generator[Tuple[str, Any], None, None]:\n        # Configuration gives keys in an unordered manner. Order them.\n        override_order = [\"global\", self.name, \":env:\"]\n\n        # Pool the options into different groups\n        section_items: Dict[str, List[Tuple[str, Any]]] = {\n            name: [] for name in override_order\n        }\n        for section_key, val in self.config.items():\n            # ignore empty values\n            if not val:\n                logger.debug(\n                    \"Ignoring configuration key '%s' as it's value is empty.\",\n                    section_key,\n                )\n                continue\n\n            section, key = section_key.split(\".\", 1)\n            if section in override_order:\n                section_items[section].append((key, val))\n\n        # Yield each group in their override order\n        for section in override_order:\n            for key, val in section_items[section]:\n                yield key, val\n\n    def _update_defaults(self, defaults: Dict[str, Any]) -> Dict[str, Any]:\n        \"\"\"Updates the given defaults with values from the config files and\n        the environ. Does a little special handling for certain types of\n        options (lists).\"\"\"\n\n        # Accumulate complex default state.\n        self.values = optparse.Values(self.defaults)\n        late_eval = set()\n        # Then set the options with those values\n        for key, val in self._get_ordered_configuration_items():\n            # '--' because configuration supports only long names\n            option = self.get_option(\"--\" + key)\n\n            # Ignore options not present in this parser. E.g. non-globals put\n            # in [global] by users that want them to apply to all applicable\n            # commands.\n            if option is None:\n                continue\n\n            assert option.dest is not None\n\n            if option.action in (\"store_true\", \"store_false\"):\n                try:\n                    val = strtobool(val)\n                except ValueError:\n                    self.error(\n                        \"{} is not a valid value for {} option, \"  # noqa\n                        \"please specify a boolean value like yes/no, \"\n                        \"true/false or 1/0 instead.\".format(val, key)\n                    )\n            elif option.action == \"count\":\n                with suppress(ValueError):\n                    val = strtobool(val)\n                with suppress(ValueError):\n                    val = int(val)\n                if not isinstance(val, int) or val < 0:\n                    self.error(\n                        \"{} is not a valid value for {} option, \"  # noqa\n                        \"please instead specify either a non-negative integer \"\n                        \"or a boolean value like yes/no or false/true \"\n                        \"which is equivalent to 1/0.\".format(val, key)\n                    )\n            elif option.action == \"append\":\n                val = val.split()\n                val = [self.check_default(option, key, v) for v in val]\n            elif option.action == \"callback\":\n                assert option.callback is not None\n                late_eval.add(option.dest)\n                opt_str = option.get_opt_string()\n                val = option.convert_value(opt_str, val)\n                # From take_action\n                args = option.callback_args or ()\n                kwargs = option.callback_kwargs or {}\n                option.callback(option, opt_str, val, self, *args, **kwargs)\n            else:\n                val = self.check_default(option, key, val)\n\n            defaults[option.dest] = val\n\n        for key in late_eval:\n            defaults[key] = getattr(self.values, key)\n        self.values = None\n        return defaults\n\n    def get_default_values(self) -> optparse.Values:\n        \"\"\"Overriding to make updating the defaults after instantiation of\n        the option parser possible, _update_defaults() does the dirty work.\"\"\"\n        if not self.process_default_values:\n            # Old, pre-Optik 1.5 behaviour.\n            return optparse.Values(self.defaults)\n\n        # Load the configuration, or error out in case of an error\n        try:\n            self.config.load()\n        except ConfigurationError as err:\n            self.exit(UNKNOWN_ERROR, str(err))\n\n        defaults = self._update_defaults(self.defaults.copy())  # ours\n        for option in self._get_all_options():\n            assert option.dest is not None\n            default = defaults.get(option.dest)\n            if isinstance(default, str):\n                opt_str = option.get_opt_string()\n                defaults[option.dest] = option.check_value(opt_str, default)\n        return optparse.Values(defaults)\n\n    def error(self, msg: str) -> None:\n        self.print_usage(sys.stderr)\n        self.exit(UNKNOWN_ERROR, f\"{msg}\\n\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/cli/progress_bars.py",
    "content": "import functools\nfrom typing import Callable, Generator, Iterable, Iterator, Optional, Tuple\n\nfrom pip._vendor.rich.progress import (\n    BarColumn,\n    DownloadColumn,\n    FileSizeColumn,\n    Progress,\n    ProgressColumn,\n    SpinnerColumn,\n    TextColumn,\n    TimeElapsedColumn,\n    TimeRemainingColumn,\n    TransferSpeedColumn,\n)\n\nfrom pip._internal.utils.logging import get_indentation\n\nDownloadProgressRenderer = Callable[[Iterable[bytes]], Iterator[bytes]]\n\n\ndef _rich_progress_bar(\n    iterable: Iterable[bytes],\n    *,\n    bar_type: str,\n    size: int,\n) -> Generator[bytes, None, None]:\n    assert bar_type == \"on\", \"This should only be used in the default mode.\"\n\n    if not size:\n        total = float(\"inf\")\n        columns: Tuple[ProgressColumn, ...] = (\n            TextColumn(\"[progress.description]{task.description}\"),\n            SpinnerColumn(\"line\", speed=1.5),\n            FileSizeColumn(),\n            TransferSpeedColumn(),\n            TimeElapsedColumn(),\n        )\n    else:\n        total = size\n        columns = (\n            TextColumn(\"[progress.description]{task.description}\"),\n            BarColumn(),\n            DownloadColumn(),\n            TransferSpeedColumn(),\n            TextColumn(\"eta\"),\n            TimeRemainingColumn(),\n        )\n\n    progress = Progress(*columns, refresh_per_second=30)\n    task_id = progress.add_task(\" \" * (get_indentation() + 2), total=total)\n    with progress:\n        for chunk in iterable:\n            yield chunk\n            progress.update(task_id, advance=len(chunk))\n\n\ndef get_download_progress_renderer(\n    *, bar_type: str, size: Optional[int] = None\n) -> DownloadProgressRenderer:\n    \"\"\"Get an object that can be used to render the download progress.\n\n    Returns a callable, that takes an iterable to \"wrap\".\n    \"\"\"\n    if bar_type == \"on\":\n        return functools.partial(_rich_progress_bar, bar_type=bar_type, size=size)\n    else:\n        return iter  # no-op, when passed an iterator\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/cli/req_command.py",
    "content": "\"\"\"Contains the Command base classes that depend on PipSession.\n\nThe classes in this module are in a separate module so the commands not\nneeding download / PackageFinder capability don't unnecessarily import the\nPackageFinder machinery and all its vendored dependencies, etc.\n\"\"\"\n\nimport logging\nimport os\nimport sys\nfrom functools import partial\nfrom optparse import Values\nfrom typing import TYPE_CHECKING, Any, List, Optional, Tuple\n\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.command_context import CommandContextMixIn\nfrom pip._internal.exceptions import CommandError, PreviousBuildDirError\nfrom pip._internal.index.collector import LinkCollector\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.models.selection_prefs import SelectionPreferences\nfrom pip._internal.models.target_python import TargetPython\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.operations.build.build_tracker import BuildTracker\nfrom pip._internal.operations.prepare import RequirementPreparer\nfrom pip._internal.req.constructors import (\n    install_req_from_editable,\n    install_req_from_line,\n    install_req_from_parsed_requirement,\n    install_req_from_req_string,\n)\nfrom pip._internal.req.req_file import parse_requirements\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.resolution.base import BaseResolver\nfrom pip._internal.self_outdated_check import pip_self_version_check\nfrom pip._internal.utils.temp_dir import (\n    TempDirectory,\n    TempDirectoryTypeRegistry,\n    tempdir_kinds,\n)\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\nif TYPE_CHECKING:\n    from ssl import SSLContext\n\nlogger = logging.getLogger(__name__)\n\n\ndef _create_truststore_ssl_context() -> Optional[\"SSLContext\"]:\n    if sys.version_info < (3, 10):\n        raise CommandError(\"The truststore feature is only available for Python 3.10+\")\n\n    try:\n        import ssl\n    except ImportError:\n        logger.warning(\"Disabling truststore since ssl support is missing\")\n        return None\n\n    try:\n        import truststore\n    except ImportError:\n        raise CommandError(\n            \"To use the truststore feature, 'truststore' must be installed into \"\n            \"pip's current environment.\"\n        )\n\n    return truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)\n\n\nclass SessionCommandMixin(CommandContextMixIn):\n\n    \"\"\"\n    A class mixin for command classes needing _build_session().\n    \"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n        self._session: Optional[PipSession] = None\n\n    @classmethod\n    def _get_index_urls(cls, options: Values) -> Optional[List[str]]:\n        \"\"\"Return a list of index urls from user-provided options.\"\"\"\n        index_urls = []\n        if not getattr(options, \"no_index\", False):\n            url = getattr(options, \"index_url\", None)\n            if url:\n                index_urls.append(url)\n        urls = getattr(options, \"extra_index_urls\", None)\n        if urls:\n            index_urls.extend(urls)\n        # Return None rather than an empty list\n        return index_urls or None\n\n    def get_default_session(self, options: Values) -> PipSession:\n        \"\"\"Get a default-managed session.\"\"\"\n        if self._session is None:\n            self._session = self.enter_context(self._build_session(options))\n            # there's no type annotation on requests.Session, so it's\n            # automatically ContextManager[Any] and self._session becomes Any,\n            # then https://github.com/python/mypy/issues/7696 kicks in\n            assert self._session is not None\n        return self._session\n\n    def _build_session(\n        self,\n        options: Values,\n        retries: Optional[int] = None,\n        timeout: Optional[int] = None,\n        fallback_to_certifi: bool = False,\n    ) -> PipSession:\n        cache_dir = options.cache_dir\n        assert not cache_dir or os.path.isabs(cache_dir)\n\n        if \"truststore\" in options.features_enabled:\n            try:\n                ssl_context = _create_truststore_ssl_context()\n            except Exception:\n                if not fallback_to_certifi:\n                    raise\n                ssl_context = None\n        else:\n            ssl_context = None\n\n        session = PipSession(\n            cache=os.path.join(cache_dir, \"http\") if cache_dir else None,\n            retries=retries if retries is not None else options.retries,\n            trusted_hosts=options.trusted_hosts,\n            index_urls=self._get_index_urls(options),\n            ssl_context=ssl_context,\n        )\n\n        # Handle custom ca-bundles from the user\n        if options.cert:\n            session.verify = options.cert\n\n        # Handle SSL client certificate\n        if options.client_cert:\n            session.cert = options.client_cert\n\n        # Handle timeouts\n        if options.timeout or timeout:\n            session.timeout = timeout if timeout is not None else options.timeout\n\n        # Handle configured proxies\n        if options.proxy:\n            session.proxies = {\n                \"http\": options.proxy,\n                \"https\": options.proxy,\n            }\n\n        # Determine if we can prompt the user for authentication or not\n        session.auth.prompting = not options.no_input\n\n        return session\n\n\nclass IndexGroupCommand(Command, SessionCommandMixin):\n\n    \"\"\"\n    Abstract base class for commands with the index_group options.\n\n    This also corresponds to the commands that permit the pip version check.\n    \"\"\"\n\n    def handle_pip_version_check(self, options: Values) -> None:\n        \"\"\"\n        Do the pip version check if not disabled.\n\n        This overrides the default behavior of not doing the check.\n        \"\"\"\n        # Make sure the index_group options are present.\n        assert hasattr(options, \"no_index\")\n\n        if options.disable_pip_version_check or options.no_index:\n            return\n\n        # Otherwise, check if we're using the latest version of pip available.\n        session = self._build_session(\n            options,\n            retries=0,\n            timeout=min(5, options.timeout),\n            # This is set to ensure the function does not fail when truststore is\n            # specified in use-feature but cannot be loaded. This usually raises a\n            # CommandError and shows a nice user-facing error, but this function is not\n            # called in that try-except block.\n            fallback_to_certifi=True,\n        )\n        with session:\n            pip_self_version_check(session, options)\n\n\nKEEPABLE_TEMPDIR_TYPES = [\n    tempdir_kinds.BUILD_ENV,\n    tempdir_kinds.EPHEM_WHEEL_CACHE,\n    tempdir_kinds.REQ_BUILD,\n]\n\n\ndef warn_if_run_as_root() -> None:\n    \"\"\"Output a warning for sudo users on Unix.\n\n    In a virtual environment, sudo pip still writes to virtualenv.\n    On Windows, users may run pip as Administrator without issues.\n    This warning only applies to Unix root users outside of virtualenv.\n    \"\"\"\n    if running_under_virtualenv():\n        return\n    if not hasattr(os, \"getuid\"):\n        return\n    # On Windows, there are no \"system managed\" Python packages. Installing as\n    # Administrator via pip is the correct way of updating system environments.\n    #\n    # We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform\n    # checks: https://mypy.readthedocs.io/en/stable/common_issues.html\n    if sys.platform == \"win32\" or sys.platform == \"cygwin\":\n        return\n\n    if os.getuid() != 0:\n        return\n\n    logger.warning(\n        \"Running pip as the 'root' user can result in broken permissions and \"\n        \"conflicting behaviour with the system package manager. \"\n        \"It is recommended to use a virtual environment instead: \"\n        \"https://pip.pypa.io/warnings/venv\"\n    )\n\n\ndef with_cleanup(func: Any) -> Any:\n    \"\"\"Decorator for common logic related to managing temporary\n    directories.\n    \"\"\"\n\n    def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None:\n        for t in KEEPABLE_TEMPDIR_TYPES:\n            registry.set_delete(t, False)\n\n    def wrapper(\n        self: RequirementCommand, options: Values, args: List[Any]\n    ) -> Optional[int]:\n        assert self.tempdir_registry is not None\n        if options.no_clean:\n            configure_tempdir_registry(self.tempdir_registry)\n\n        try:\n            return func(self, options, args)\n        except PreviousBuildDirError:\n            # This kind of conflict can occur when the user passes an explicit\n            # build directory with a pre-existing folder. In that case we do\n            # not want to accidentally remove it.\n            configure_tempdir_registry(self.tempdir_registry)\n            raise\n\n    return wrapper\n\n\nclass RequirementCommand(IndexGroupCommand):\n    def __init__(self, *args: Any, **kw: Any) -> None:\n        super().__init__(*args, **kw)\n\n        self.cmd_opts.add_option(cmdoptions.no_clean())\n\n    @staticmethod\n    def determine_resolver_variant(options: Values) -> str:\n        \"\"\"Determines which resolver should be used, based on the given options.\"\"\"\n        if \"legacy-resolver\" in options.deprecated_features_enabled:\n            return \"legacy\"\n\n        return \"2020-resolver\"\n\n    @classmethod\n    def make_requirement_preparer(\n        cls,\n        temp_build_dir: TempDirectory,\n        options: Values,\n        build_tracker: BuildTracker,\n        session: PipSession,\n        finder: PackageFinder,\n        use_user_site: bool,\n        download_dir: Optional[str] = None,\n        verbosity: int = 0,\n    ) -> RequirementPreparer:\n        \"\"\"\n        Create a RequirementPreparer instance for the given parameters.\n        \"\"\"\n        temp_build_dir_path = temp_build_dir.path\n        assert temp_build_dir_path is not None\n\n        resolver_variant = cls.determine_resolver_variant(options)\n        if resolver_variant == \"2020-resolver\":\n            lazy_wheel = \"fast-deps\" in options.features_enabled\n            if lazy_wheel:\n                logger.warning(\n                    \"pip is using lazily downloaded wheels using HTTP \"\n                    \"range requests to obtain dependency information. \"\n                    \"This experimental feature is enabled through \"\n                    \"--use-feature=fast-deps and it is not ready for \"\n                    \"production.\"\n                )\n        else:\n            lazy_wheel = False\n            if \"fast-deps\" in options.features_enabled:\n                logger.warning(\n                    \"fast-deps has no effect when used with the legacy resolver.\"\n                )\n\n        return RequirementPreparer(\n            build_dir=temp_build_dir_path,\n            src_dir=options.src_dir,\n            download_dir=download_dir,\n            build_isolation=options.build_isolation,\n            check_build_deps=options.check_build_deps,\n            build_tracker=build_tracker,\n            session=session,\n            progress_bar=options.progress_bar,\n            finder=finder,\n            require_hashes=options.require_hashes,\n            use_user_site=use_user_site,\n            lazy_wheel=lazy_wheel,\n            verbosity=verbosity,\n        )\n\n    @classmethod\n    def make_resolver(\n        cls,\n        preparer: RequirementPreparer,\n        finder: PackageFinder,\n        options: Values,\n        wheel_cache: Optional[WheelCache] = None,\n        use_user_site: bool = False,\n        ignore_installed: bool = True,\n        ignore_requires_python: bool = False,\n        force_reinstall: bool = False,\n        upgrade_strategy: str = \"to-satisfy-only\",\n        use_pep517: Optional[bool] = None,\n        py_version_info: Optional[Tuple[int, ...]] = None,\n    ) -> BaseResolver:\n        \"\"\"\n        Create a Resolver instance for the given parameters.\n        \"\"\"\n        make_install_req = partial(\n            install_req_from_req_string,\n            isolated=options.isolated_mode,\n            use_pep517=use_pep517,\n            config_settings=getattr(options, \"config_settings\", None),\n        )\n        resolver_variant = cls.determine_resolver_variant(options)\n        # The long import name and duplicated invocation is needed to convince\n        # Mypy into correctly typechecking. Otherwise it would complain the\n        # \"Resolver\" class being redefined.\n        if resolver_variant == \"2020-resolver\":\n            import pip._internal.resolution.resolvelib.resolver\n\n            return pip._internal.resolution.resolvelib.resolver.Resolver(\n                preparer=preparer,\n                finder=finder,\n                wheel_cache=wheel_cache,\n                make_install_req=make_install_req,\n                use_user_site=use_user_site,\n                ignore_dependencies=options.ignore_dependencies,\n                ignore_installed=ignore_installed,\n                ignore_requires_python=ignore_requires_python,\n                force_reinstall=force_reinstall,\n                upgrade_strategy=upgrade_strategy,\n                py_version_info=py_version_info,\n            )\n        import pip._internal.resolution.legacy.resolver\n\n        return pip._internal.resolution.legacy.resolver.Resolver(\n            preparer=preparer,\n            finder=finder,\n            wheel_cache=wheel_cache,\n            make_install_req=make_install_req,\n            use_user_site=use_user_site,\n            ignore_dependencies=options.ignore_dependencies,\n            ignore_installed=ignore_installed,\n            ignore_requires_python=ignore_requires_python,\n            force_reinstall=force_reinstall,\n            upgrade_strategy=upgrade_strategy,\n            py_version_info=py_version_info,\n        )\n\n    def get_requirements(\n        self,\n        args: List[str],\n        options: Values,\n        finder: PackageFinder,\n        session: PipSession,\n    ) -> List[InstallRequirement]:\n        \"\"\"\n        Parse command-line arguments into the corresponding requirements.\n        \"\"\"\n        requirements: List[InstallRequirement] = []\n        for filename in options.constraints:\n            for parsed_req in parse_requirements(\n                filename,\n                constraint=True,\n                finder=finder,\n                options=options,\n                session=session,\n            ):\n                req_to_add = install_req_from_parsed_requirement(\n                    parsed_req,\n                    isolated=options.isolated_mode,\n                    user_supplied=False,\n                )\n                requirements.append(req_to_add)\n\n        for req in args:\n            req_to_add = install_req_from_line(\n                req,\n                None,\n                isolated=options.isolated_mode,\n                use_pep517=options.use_pep517,\n                user_supplied=True,\n                config_settings=getattr(options, \"config_settings\", None),\n            )\n            requirements.append(req_to_add)\n\n        for req in options.editables:\n            req_to_add = install_req_from_editable(\n                req,\n                user_supplied=True,\n                isolated=options.isolated_mode,\n                use_pep517=options.use_pep517,\n                config_settings=getattr(options, \"config_settings\", None),\n            )\n            requirements.append(req_to_add)\n\n        # NOTE: options.require_hashes may be set if --require-hashes is True\n        for filename in options.requirements:\n            for parsed_req in parse_requirements(\n                filename, finder=finder, options=options, session=session\n            ):\n                req_to_add = install_req_from_parsed_requirement(\n                    parsed_req,\n                    isolated=options.isolated_mode,\n                    use_pep517=options.use_pep517,\n                    user_supplied=True,\n                )\n                requirements.append(req_to_add)\n\n        # If any requirement has hash options, enable hash checking.\n        if any(req.has_hash_options for req in requirements):\n            options.require_hashes = True\n\n        if not (args or options.editables or options.requirements):\n            opts = {\"name\": self.name}\n            if options.find_links:\n                raise CommandError(\n                    \"You must give at least one requirement to {name} \"\n                    '(maybe you meant \"pip {name} {links}\"?)'.format(\n                        **dict(opts, links=\" \".join(options.find_links))\n                    )\n                )\n            else:\n                raise CommandError(\n                    \"You must give at least one requirement to {name} \"\n                    '(see \"pip help {name}\")'.format(**opts)\n                )\n\n        return requirements\n\n    @staticmethod\n    def trace_basic_info(finder: PackageFinder) -> None:\n        \"\"\"\n        Trace basic information about the provided objects.\n        \"\"\"\n        # Display where finder is looking for packages\n        search_scope = finder.search_scope\n        locations = search_scope.get_formatted_locations()\n        if locations:\n            logger.info(locations)\n\n    def _build_package_finder(\n        self,\n        options: Values,\n        session: PipSession,\n        target_python: Optional[TargetPython] = None,\n        ignore_requires_python: Optional[bool] = None,\n    ) -> PackageFinder:\n        \"\"\"\n        Create a package finder appropriate to this requirement command.\n\n        :param ignore_requires_python: Whether to ignore incompatible\n            \"Requires-Python\" values in links. Defaults to False.\n        \"\"\"\n        link_collector = LinkCollector.create(session, options=options)\n        selection_prefs = SelectionPreferences(\n            allow_yanked=True,\n            format_control=options.format_control,\n            allow_all_prereleases=options.pre,\n            prefer_binary=options.prefer_binary,\n            ignore_requires_python=ignore_requires_python,\n        )\n\n        return PackageFinder.create(\n            link_collector=link_collector,\n            selection_prefs=selection_prefs,\n            target_python=target_python,\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/cli/spinners.py",
    "content": "import contextlib\nimport itertools\nimport logging\nimport sys\nimport time\nfrom typing import IO, Generator, Optional\n\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.logging import get_indentation\n\nlogger = logging.getLogger(__name__)\n\n\nclass SpinnerInterface:\n    def spin(self) -> None:\n        raise NotImplementedError()\n\n    def finish(self, final_status: str) -> None:\n        raise NotImplementedError()\n\n\nclass InteractiveSpinner(SpinnerInterface):\n    def __init__(\n        self,\n        message: str,\n        file: Optional[IO[str]] = None,\n        spin_chars: str = \"-\\\\|/\",\n        # Empirically, 8 updates/second looks nice\n        min_update_interval_seconds: float = 0.125,\n    ):\n        self._message = message\n        if file is None:\n            file = sys.stdout\n        self._file = file\n        self._rate_limiter = RateLimiter(min_update_interval_seconds)\n        self._finished = False\n\n        self._spin_cycle = itertools.cycle(spin_chars)\n\n        self._file.write(\" \" * get_indentation() + self._message + \" ... \")\n        self._width = 0\n\n    def _write(self, status: str) -> None:\n        assert not self._finished\n        # Erase what we wrote before by backspacing to the beginning, writing\n        # spaces to overwrite the old text, and then backspacing again\n        backup = \"\\b\" * self._width\n        self._file.write(backup + \" \" * self._width + backup)\n        # Now we have a blank slate to add our status\n        self._file.write(status)\n        self._width = len(status)\n        self._file.flush()\n        self._rate_limiter.reset()\n\n    def spin(self) -> None:\n        if self._finished:\n            return\n        if not self._rate_limiter.ready():\n            return\n        self._write(next(self._spin_cycle))\n\n    def finish(self, final_status: str) -> None:\n        if self._finished:\n            return\n        self._write(final_status)\n        self._file.write(\"\\n\")\n        self._file.flush()\n        self._finished = True\n\n\n# Used for dumb terminals, non-interactive installs (no tty), etc.\n# We still print updates occasionally (once every 60 seconds by default) to\n# act as a keep-alive for systems like Travis-CI that take lack-of-output as\n# an indication that a task has frozen.\nclass NonInteractiveSpinner(SpinnerInterface):\n    def __init__(self, message: str, min_update_interval_seconds: float = 60.0) -> None:\n        self._message = message\n        self._finished = False\n        self._rate_limiter = RateLimiter(min_update_interval_seconds)\n        self._update(\"started\")\n\n    def _update(self, status: str) -> None:\n        assert not self._finished\n        self._rate_limiter.reset()\n        logger.info(\"%s: %s\", self._message, status)\n\n    def spin(self) -> None:\n        if self._finished:\n            return\n        if not self._rate_limiter.ready():\n            return\n        self._update(\"still running...\")\n\n    def finish(self, final_status: str) -> None:\n        if self._finished:\n            return\n        self._update(f\"finished with status '{final_status}'\")\n        self._finished = True\n\n\nclass RateLimiter:\n    def __init__(self, min_update_interval_seconds: float) -> None:\n        self._min_update_interval_seconds = min_update_interval_seconds\n        self._last_update: float = 0\n\n    def ready(self) -> bool:\n        now = time.time()\n        delta = now - self._last_update\n        return delta >= self._min_update_interval_seconds\n\n    def reset(self) -> None:\n        self._last_update = time.time()\n\n\n@contextlib.contextmanager\ndef open_spinner(message: str) -> Generator[SpinnerInterface, None, None]:\n    # Interactive spinner goes directly to sys.stdout rather than being routed\n    # through the logging system, but it acts like it has level INFO,\n    # i.e. it's only displayed if we're at level INFO or better.\n    # Non-interactive spinner goes through the logging system, so it is always\n    # in sync with logging configuration.\n    if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO:\n        spinner: SpinnerInterface = InteractiveSpinner(message)\n    else:\n        spinner = NonInteractiveSpinner(message)\n    try:\n        with hidden_cursor(sys.stdout):\n            yield spinner\n    except KeyboardInterrupt:\n        spinner.finish(\"canceled\")\n        raise\n    except Exception:\n        spinner.finish(\"error\")\n        raise\n    else:\n        spinner.finish(\"done\")\n\n\nHIDE_CURSOR = \"\\x1b[?25l\"\nSHOW_CURSOR = \"\\x1b[?25h\"\n\n\n@contextlib.contextmanager\ndef hidden_cursor(file: IO[str]) -> Generator[None, None, None]:\n    # The Windows terminal does not support the hide/show cursor ANSI codes,\n    # even via colorama. So don't even try.\n    if WINDOWS:\n        yield\n    # We don't want to clutter the output with control characters if we're\n    # writing to a file, or if the user is running with --quiet.\n    # See https://github.com/pypa/pip/issues/3418\n    elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO:\n        yield\n    else:\n        file.write(HIDE_CURSOR)\n        try:\n            yield\n        finally:\n            file.write(SHOW_CURSOR)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/cli/status_codes.py",
    "content": "SUCCESS = 0\nERROR = 1\nUNKNOWN_ERROR = 2\nVIRTUALENV_NOT_FOUND = 3\nPREVIOUS_BUILD_DIR_ERROR = 4\nNO_MATCHES_FOUND = 23\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/__init__.py",
    "content": "\"\"\"\nPackage containing all pip commands\n\"\"\"\n\nimport importlib\nfrom collections import namedtuple\nfrom typing import Any, Dict, Optional\n\nfrom pip._internal.cli.base_command import Command\n\nCommandInfo = namedtuple(\"CommandInfo\", \"module_path, class_name, summary\")\n\n# This dictionary does a bunch of heavy lifting for help output:\n# - Enables avoiding additional (costly) imports for presenting `--help`.\n# - The ordering matters for help display.\n#\n# Even though the module path starts with the same \"pip._internal.commands\"\n# prefix, the full path makes testing easier (specifically when modifying\n# `commands_dict` in test setup / teardown).\ncommands_dict: Dict[str, CommandInfo] = {\n    \"install\": CommandInfo(\n        \"pip._internal.commands.install\",\n        \"InstallCommand\",\n        \"Install packages.\",\n    ),\n    \"download\": CommandInfo(\n        \"pip._internal.commands.download\",\n        \"DownloadCommand\",\n        \"Download packages.\",\n    ),\n    \"uninstall\": CommandInfo(\n        \"pip._internal.commands.uninstall\",\n        \"UninstallCommand\",\n        \"Uninstall packages.\",\n    ),\n    \"freeze\": CommandInfo(\n        \"pip._internal.commands.freeze\",\n        \"FreezeCommand\",\n        \"Output installed packages in requirements format.\",\n    ),\n    \"inspect\": CommandInfo(\n        \"pip._internal.commands.inspect\",\n        \"InspectCommand\",\n        \"Inspect the python environment.\",\n    ),\n    \"list\": CommandInfo(\n        \"pip._internal.commands.list\",\n        \"ListCommand\",\n        \"List installed packages.\",\n    ),\n    \"show\": CommandInfo(\n        \"pip._internal.commands.show\",\n        \"ShowCommand\",\n        \"Show information about installed packages.\",\n    ),\n    \"check\": CommandInfo(\n        \"pip._internal.commands.check\",\n        \"CheckCommand\",\n        \"Verify installed packages have compatible dependencies.\",\n    ),\n    \"config\": CommandInfo(\n        \"pip._internal.commands.configuration\",\n        \"ConfigurationCommand\",\n        \"Manage local and global configuration.\",\n    ),\n    \"search\": CommandInfo(\n        \"pip._internal.commands.search\",\n        \"SearchCommand\",\n        \"Search PyPI for packages.\",\n    ),\n    \"cache\": CommandInfo(\n        \"pip._internal.commands.cache\",\n        \"CacheCommand\",\n        \"Inspect and manage pip's wheel cache.\",\n    ),\n    \"index\": CommandInfo(\n        \"pip._internal.commands.index\",\n        \"IndexCommand\",\n        \"Inspect information available from package indexes.\",\n    ),\n    \"wheel\": CommandInfo(\n        \"pip._internal.commands.wheel\",\n        \"WheelCommand\",\n        \"Build wheels from your requirements.\",\n    ),\n    \"hash\": CommandInfo(\n        \"pip._internal.commands.hash\",\n        \"HashCommand\",\n        \"Compute hashes of package archives.\",\n    ),\n    \"completion\": CommandInfo(\n        \"pip._internal.commands.completion\",\n        \"CompletionCommand\",\n        \"A helper command used for command completion.\",\n    ),\n    \"debug\": CommandInfo(\n        \"pip._internal.commands.debug\",\n        \"DebugCommand\",\n        \"Show information useful for debugging.\",\n    ),\n    \"help\": CommandInfo(\n        \"pip._internal.commands.help\",\n        \"HelpCommand\",\n        \"Show help for commands.\",\n    ),\n}\n\n\ndef create_command(name: str, **kwargs: Any) -> Command:\n    \"\"\"\n    Create an instance of the Command class with the given name.\n    \"\"\"\n    module_path, class_name, summary = commands_dict[name]\n    module = importlib.import_module(module_path)\n    command_class = getattr(module, class_name)\n    command = command_class(name=name, summary=summary, **kwargs)\n\n    return command\n\n\ndef get_similar_commands(name: str) -> Optional[str]:\n    \"\"\"Command name auto-correct.\"\"\"\n    from difflib import get_close_matches\n\n    name = name.lower()\n\n    close_commands = get_close_matches(name, commands_dict.keys())\n\n    if close_commands:\n        return close_commands[0]\n    else:\n        return None\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/cache.py",
    "content": "import os\nimport textwrap\nfrom optparse import Values\nfrom typing import Any, List\n\nimport pip._internal.utils.filesystem as filesystem\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.exceptions import CommandError, PipError\nfrom pip._internal.utils.logging import getLogger\n\nlogger = getLogger(__name__)\n\n\nclass CacheCommand(Command):\n    \"\"\"\n    Inspect and manage pip's wheel cache.\n\n    Subcommands:\n\n    - dir: Show the cache directory.\n    - info: Show information about the cache.\n    - list: List filenames of packages stored in the cache.\n    - remove: Remove one or more package from the cache.\n    - purge: Remove all items from the cache.\n\n    ``<pattern>`` can be a glob expression or a package name.\n    \"\"\"\n\n    ignore_require_venv = True\n    usage = \"\"\"\n        %prog dir\n        %prog info\n        %prog list [<pattern>] [--format=[human, abspath]]\n        %prog remove <pattern>\n        %prog purge\n    \"\"\"\n\n    def add_options(self) -> None:\n\n        self.cmd_opts.add_option(\n            \"--format\",\n            action=\"store\",\n            dest=\"list_format\",\n            default=\"human\",\n            choices=(\"human\", \"abspath\"),\n            help=\"Select the output format among: human (default) or abspath\",\n        )\n\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: List[str]) -> int:\n        handlers = {\n            \"dir\": self.get_cache_dir,\n            \"info\": self.get_cache_info,\n            \"list\": self.list_cache_items,\n            \"remove\": self.remove_cache_items,\n            \"purge\": self.purge_cache,\n        }\n\n        if not options.cache_dir:\n            logger.error(\"pip cache commands can not function since cache is disabled.\")\n            return ERROR\n\n        # Determine action\n        if not args or args[0] not in handlers:\n            logger.error(\n                \"Need an action (%s) to perform.\",\n                \", \".join(sorted(handlers)),\n            )\n            return ERROR\n\n        action = args[0]\n\n        # Error handling happens here, not in the action-handlers.\n        try:\n            handlers[action](options, args[1:])\n        except PipError as e:\n            logger.error(e.args[0])\n            return ERROR\n\n        return SUCCESS\n\n    def get_cache_dir(self, options: Values, args: List[Any]) -> None:\n        if args:\n            raise CommandError(\"Too many arguments\")\n\n        logger.info(options.cache_dir)\n\n    def get_cache_info(self, options: Values, args: List[Any]) -> None:\n        if args:\n            raise CommandError(\"Too many arguments\")\n\n        num_http_files = len(self._find_http_files(options))\n        num_packages = len(self._find_wheels(options, \"*\"))\n\n        http_cache_location = self._cache_dir(options, \"http\")\n        wheels_cache_location = self._cache_dir(options, \"wheels\")\n        http_cache_size = filesystem.format_directory_size(http_cache_location)\n        wheels_cache_size = filesystem.format_directory_size(wheels_cache_location)\n\n        message = (\n            textwrap.dedent(\n                \"\"\"\n                    Package index page cache location: {http_cache_location}\n                    Package index page cache size: {http_cache_size}\n                    Number of HTTP files: {num_http_files}\n                    Locally built wheels location: {wheels_cache_location}\n                    Locally built wheels size: {wheels_cache_size}\n                    Number of locally built wheels: {package_count}\n                \"\"\"\n            )\n            .format(\n                http_cache_location=http_cache_location,\n                http_cache_size=http_cache_size,\n                num_http_files=num_http_files,\n                wheels_cache_location=wheels_cache_location,\n                package_count=num_packages,\n                wheels_cache_size=wheels_cache_size,\n            )\n            .strip()\n        )\n\n        logger.info(message)\n\n    def list_cache_items(self, options: Values, args: List[Any]) -> None:\n        if len(args) > 1:\n            raise CommandError(\"Too many arguments\")\n\n        if args:\n            pattern = args[0]\n        else:\n            pattern = \"*\"\n\n        files = self._find_wheels(options, pattern)\n        if options.list_format == \"human\":\n            self.format_for_human(files)\n        else:\n            self.format_for_abspath(files)\n\n    def format_for_human(self, files: List[str]) -> None:\n        if not files:\n            logger.info(\"No locally built wheels cached.\")\n            return\n\n        results = []\n        for filename in files:\n            wheel = os.path.basename(filename)\n            size = filesystem.format_file_size(filename)\n            results.append(f\" - {wheel} ({size})\")\n        logger.info(\"Cache contents:\\n\")\n        logger.info(\"\\n\".join(sorted(results)))\n\n    def format_for_abspath(self, files: List[str]) -> None:\n        if not files:\n            return\n\n        results = []\n        for filename in files:\n            results.append(filename)\n\n        logger.info(\"\\n\".join(sorted(results)))\n\n    def remove_cache_items(self, options: Values, args: List[Any]) -> None:\n        if len(args) > 1:\n            raise CommandError(\"Too many arguments\")\n\n        if not args:\n            raise CommandError(\"Please provide a pattern\")\n\n        files = self._find_wheels(options, args[0])\n\n        no_matching_msg = \"No matching packages\"\n        if args[0] == \"*\":\n            # Only fetch http files if no specific pattern given\n            files += self._find_http_files(options)\n        else:\n            # Add the pattern to the log message\n            no_matching_msg += ' for pattern \"{}\"'.format(args[0])\n\n        if not files:\n            logger.warning(no_matching_msg)\n\n        for filename in files:\n            os.unlink(filename)\n            logger.verbose(\"Removed %s\", filename)\n        logger.info(\"Files removed: %s\", len(files))\n\n    def purge_cache(self, options: Values, args: List[Any]) -> None:\n        if args:\n            raise CommandError(\"Too many arguments\")\n\n        return self.remove_cache_items(options, [\"*\"])\n\n    def _cache_dir(self, options: Values, subdir: str) -> str:\n        return os.path.join(options.cache_dir, subdir)\n\n    def _find_http_files(self, options: Values) -> List[str]:\n        http_dir = self._cache_dir(options, \"http\")\n        return filesystem.find_files(http_dir, \"*\")\n\n    def _find_wheels(self, options: Values, pattern: str) -> List[str]:\n        wheel_dir = self._cache_dir(options, \"wheels\")\n\n        # The wheel filename format, as specified in PEP 427, is:\n        #     {distribution}-{version}(-{build})?-{python}-{abi}-{platform}.whl\n        #\n        # Additionally, non-alphanumeric values in the distribution are\n        # normalized to underscores (_), meaning hyphens can never occur\n        # before `-{version}`.\n        #\n        # Given that information:\n        # - If the pattern we're given contains a hyphen (-), the user is\n        #   providing at least the version. Thus, we can just append `*.whl`\n        #   to match the rest of it.\n        # - If the pattern we're given doesn't contain a hyphen (-), the\n        #   user is only providing the name. Thus, we append `-*.whl` to\n        #   match the hyphen before the version, followed by anything else.\n        #\n        # PEP 427: https://www.python.org/dev/peps/pep-0427/\n        pattern = pattern + (\"*.whl\" if \"-\" in pattern else \"-*.whl\")\n\n        return filesystem.find_files(wheel_dir, pattern)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/check.py",
    "content": "import logging\nfrom optparse import Values\nfrom typing import List\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.operations.check import (\n    check_package_set,\n    create_package_set_from_installed,\n)\nfrom pip._internal.utils.misc import write_output\n\nlogger = logging.getLogger(__name__)\n\n\nclass CheckCommand(Command):\n    \"\"\"Verify installed packages have compatible dependencies.\"\"\"\n\n    usage = \"\"\"\n      %prog [options]\"\"\"\n\n    def run(self, options: Values, args: List[str]) -> int:\n\n        package_set, parsing_probs = create_package_set_from_installed()\n        missing, conflicting = check_package_set(package_set)\n\n        for project_name in missing:\n            version = package_set[project_name].version\n            for dependency in missing[project_name]:\n                write_output(\n                    \"%s %s requires %s, which is not installed.\",\n                    project_name,\n                    version,\n                    dependency[0],\n                )\n\n        for project_name in conflicting:\n            version = package_set[project_name].version\n            for dep_name, dep_version, req in conflicting[project_name]:\n                write_output(\n                    \"%s %s has requirement %s, but you have %s %s.\",\n                    project_name,\n                    version,\n                    req,\n                    dep_name,\n                    dep_version,\n                )\n\n        if missing or conflicting or parsing_probs:\n            return ERROR\n        else:\n            write_output(\"No broken requirements found.\")\n            return SUCCESS\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/completion.py",
    "content": "import sys\nimport textwrap\nfrom optparse import Values\nfrom typing import List\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.utils.misc import get_prog\n\nBASE_COMPLETION = \"\"\"\n# pip {shell} completion start{script}# pip {shell} completion end\n\"\"\"\n\nCOMPLETION_SCRIPTS = {\n    \"bash\": \"\"\"\n        _pip_completion()\n        {{\n            COMPREPLY=( $( COMP_WORDS=\"${{COMP_WORDS[*]}}\" \\\\\n                           COMP_CWORD=$COMP_CWORD \\\\\n                           PIP_AUTO_COMPLETE=1 $1 2>/dev/null ) )\n        }}\n        complete -o default -F _pip_completion {prog}\n    \"\"\",\n    \"zsh\": \"\"\"\n        function _pip_completion {{\n          local words cword\n          read -Ac words\n          read -cn cword\n          reply=( $( COMP_WORDS=\"$words[*]\" \\\\\n                     COMP_CWORD=$(( cword-1 )) \\\\\n                     PIP_AUTO_COMPLETE=1 $words[1] 2>/dev/null ))\n        }}\n        compctl -K _pip_completion {prog}\n    \"\"\",\n    \"fish\": \"\"\"\n        function __fish_complete_pip\n            set -lx COMP_WORDS (commandline -o) \"\"\n            set -lx COMP_CWORD ( \\\\\n                math (contains -i -- (commandline -t) $COMP_WORDS)-1 \\\\\n            )\n            set -lx PIP_AUTO_COMPLETE 1\n            string split \\\\  -- (eval $COMP_WORDS[1])\n        end\n        complete -fa \"(__fish_complete_pip)\" -c {prog}\n    \"\"\",\n    \"powershell\": \"\"\"\n        if ((Test-Path Function:\\\\TabExpansion) -and -not `\n            (Test-Path Function:\\\\_pip_completeBackup)) {{\n            Rename-Item Function:\\\\TabExpansion _pip_completeBackup\n        }}\n        function TabExpansion($line, $lastWord) {{\n            $lastBlock = [regex]::Split($line, '[|;]')[-1].TrimStart()\n            if ($lastBlock.StartsWith(\"{prog} \")) {{\n                $Env:COMP_WORDS=$lastBlock\n                $Env:COMP_CWORD=$lastBlock.Split().Length - 1\n                $Env:PIP_AUTO_COMPLETE=1\n                (& {prog}).Split()\n                Remove-Item Env:COMP_WORDS\n                Remove-Item Env:COMP_CWORD\n                Remove-Item Env:PIP_AUTO_COMPLETE\n            }}\n            elseif (Test-Path Function:\\\\_pip_completeBackup) {{\n                # Fall back on existing tab expansion\n                _pip_completeBackup $line $lastWord\n            }}\n        }}\n    \"\"\",\n}\n\n\nclass CompletionCommand(Command):\n    \"\"\"A helper command to be used for command completion.\"\"\"\n\n    ignore_require_venv = True\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"--bash\",\n            \"-b\",\n            action=\"store_const\",\n            const=\"bash\",\n            dest=\"shell\",\n            help=\"Emit completion code for bash\",\n        )\n        self.cmd_opts.add_option(\n            \"--zsh\",\n            \"-z\",\n            action=\"store_const\",\n            const=\"zsh\",\n            dest=\"shell\",\n            help=\"Emit completion code for zsh\",\n        )\n        self.cmd_opts.add_option(\n            \"--fish\",\n            \"-f\",\n            action=\"store_const\",\n            const=\"fish\",\n            dest=\"shell\",\n            help=\"Emit completion code for fish\",\n        )\n        self.cmd_opts.add_option(\n            \"--powershell\",\n            \"-p\",\n            action=\"store_const\",\n            const=\"powershell\",\n            dest=\"shell\",\n            help=\"Emit completion code for powershell\",\n        )\n\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: List[str]) -> int:\n        \"\"\"Prints the completion code of the given shell\"\"\"\n        shells = COMPLETION_SCRIPTS.keys()\n        shell_options = [\"--\" + shell for shell in sorted(shells)]\n        if options.shell in shells:\n            script = textwrap.dedent(\n                COMPLETION_SCRIPTS.get(options.shell, \"\").format(prog=get_prog())\n            )\n            print(BASE_COMPLETION.format(script=script, shell=options.shell))\n            return SUCCESS\n        else:\n            sys.stderr.write(\n                \"ERROR: You must pass {}\\n\".format(\" or \".join(shell_options))\n            )\n            return SUCCESS\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/configuration.py",
    "content": "import logging\nimport os\nimport subprocess\nfrom optparse import Values\nfrom typing import Any, List, Optional\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.configuration import (\n    Configuration,\n    Kind,\n    get_configuration_files,\n    kinds,\n)\nfrom pip._internal.exceptions import PipError\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import get_prog, write_output\n\nlogger = logging.getLogger(__name__)\n\n\nclass ConfigurationCommand(Command):\n    \"\"\"\n    Manage local and global configuration.\n\n    Subcommands:\n\n    - list: List the active configuration (or from the file specified)\n    - edit: Edit the configuration file in an editor\n    - get: Get the value associated with command.option\n    - set: Set the command.option=value\n    - unset: Unset the value associated with command.option\n    - debug: List the configuration files and values defined under them\n\n    Configuration keys should be dot separated command and option name,\n    with the special prefix \"global\" affecting any command. For example,\n    \"pip config set global.index-url https://example.org/\" would configure\n    the index url for all commands, but \"pip config set download.timeout 10\"\n    would configure a 10 second timeout only for \"pip download\" commands.\n\n    If none of --user, --global and --site are passed, a virtual\n    environment configuration file is used if one is active and the file\n    exists. Otherwise, all modifications happen to the user file by\n    default.\n    \"\"\"\n\n    ignore_require_venv = True\n    usage = \"\"\"\n        %prog [<file-option>] list\n        %prog [<file-option>] [--editor <editor-path>] edit\n\n        %prog [<file-option>] get command.option\n        %prog [<file-option>] set command.option value\n        %prog [<file-option>] unset command.option\n        %prog [<file-option>] debug\n    \"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"--editor\",\n            dest=\"editor\",\n            action=\"store\",\n            default=None,\n            help=(\n                \"Editor to use to edit the file. Uses VISUAL or EDITOR \"\n                \"environment variables if not provided.\"\n            ),\n        )\n\n        self.cmd_opts.add_option(\n            \"--global\",\n            dest=\"global_file\",\n            action=\"store_true\",\n            default=False,\n            help=\"Use the system-wide configuration file only\",\n        )\n\n        self.cmd_opts.add_option(\n            \"--user\",\n            dest=\"user_file\",\n            action=\"store_true\",\n            default=False,\n            help=\"Use the user configuration file only\",\n        )\n\n        self.cmd_opts.add_option(\n            \"--site\",\n            dest=\"site_file\",\n            action=\"store_true\",\n            default=False,\n            help=\"Use the current environment configuration file only\",\n        )\n\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: List[str]) -> int:\n        handlers = {\n            \"list\": self.list_values,\n            \"edit\": self.open_in_editor,\n            \"get\": self.get_name,\n            \"set\": self.set_name_value,\n            \"unset\": self.unset_name,\n            \"debug\": self.list_config_values,\n        }\n\n        # Determine action\n        if not args or args[0] not in handlers:\n            logger.error(\n                \"Need an action (%s) to perform.\",\n                \", \".join(sorted(handlers)),\n            )\n            return ERROR\n\n        action = args[0]\n\n        # Determine which configuration files are to be loaded\n        #    Depends on whether the command is modifying.\n        try:\n            load_only = self._determine_file(\n                options, need_value=(action in [\"get\", \"set\", \"unset\", \"edit\"])\n            )\n        except PipError as e:\n            logger.error(e.args[0])\n            return ERROR\n\n        # Load a new configuration\n        self.configuration = Configuration(\n            isolated=options.isolated_mode, load_only=load_only\n        )\n        self.configuration.load()\n\n        # Error handling happens here, not in the action-handlers.\n        try:\n            handlers[action](options, args[1:])\n        except PipError as e:\n            logger.error(e.args[0])\n            return ERROR\n\n        return SUCCESS\n\n    def _determine_file(self, options: Values, need_value: bool) -> Optional[Kind]:\n        file_options = [\n            key\n            for key, value in (\n                (kinds.USER, options.user_file),\n                (kinds.GLOBAL, options.global_file),\n                (kinds.SITE, options.site_file),\n            )\n            if value\n        ]\n\n        if not file_options:\n            if not need_value:\n                return None\n            # Default to user, unless there's a site file.\n            elif any(\n                os.path.exists(site_config_file)\n                for site_config_file in get_configuration_files()[kinds.SITE]\n            ):\n                return kinds.SITE\n            else:\n                return kinds.USER\n        elif len(file_options) == 1:\n            return file_options[0]\n\n        raise PipError(\n            \"Need exactly one file to operate upon \"\n            \"(--user, --site, --global) to perform.\"\n        )\n\n    def list_values(self, options: Values, args: List[str]) -> None:\n        self._get_n_args(args, \"list\", n=0)\n\n        for key, value in sorted(self.configuration.items()):\n            write_output(\"%s=%r\", key, value)\n\n    def get_name(self, options: Values, args: List[str]) -> None:\n        key = self._get_n_args(args, \"get [name]\", n=1)\n        value = self.configuration.get_value(key)\n\n        write_output(\"%s\", value)\n\n    def set_name_value(self, options: Values, args: List[str]) -> None:\n        key, value = self._get_n_args(args, \"set [name] [value]\", n=2)\n        self.configuration.set_value(key, value)\n\n        self._save_configuration()\n\n    def unset_name(self, options: Values, args: List[str]) -> None:\n        key = self._get_n_args(args, \"unset [name]\", n=1)\n        self.configuration.unset_value(key)\n\n        self._save_configuration()\n\n    def list_config_values(self, options: Values, args: List[str]) -> None:\n        \"\"\"List config key-value pairs across different config files\"\"\"\n        self._get_n_args(args, \"debug\", n=0)\n\n        self.print_env_var_values()\n        # Iterate over config files and print if they exist, and the\n        # key-value pairs present in them if they do\n        for variant, files in sorted(self.configuration.iter_config_files()):\n            write_output(\"%s:\", variant)\n            for fname in files:\n                with indent_log():\n                    file_exists = os.path.exists(fname)\n                    write_output(\"%s, exists: %r\", fname, file_exists)\n                    if file_exists:\n                        self.print_config_file_values(variant)\n\n    def print_config_file_values(self, variant: Kind) -> None:\n        \"\"\"Get key-value pairs from the file of a variant\"\"\"\n        for name, value in self.configuration.get_values_in_config(variant).items():\n            with indent_log():\n                write_output(\"%s: %s\", name, value)\n\n    def print_env_var_values(self) -> None:\n        \"\"\"Get key-values pairs present as environment variables\"\"\"\n        write_output(\"%s:\", \"env_var\")\n        with indent_log():\n            for key, value in sorted(self.configuration.get_environ_vars()):\n                env_var = f\"PIP_{key.upper()}\"\n                write_output(\"%s=%r\", env_var, value)\n\n    def open_in_editor(self, options: Values, args: List[str]) -> None:\n        editor = self._determine_editor(options)\n\n        fname = self.configuration.get_file_to_edit()\n        if fname is None:\n            raise PipError(\"Could not determine appropriate file.\")\n        elif '\"' in fname:\n            # This shouldn't happen, unless we see a username like that.\n            # If that happens, we'd appreciate a pull request fixing this.\n            raise PipError(\n                f'Can not open an editor for a file name containing \"\\n{fname}'\n            )\n\n        try:\n            subprocess.check_call(f'{editor} \"{fname}\"', shell=True)\n        except FileNotFoundError as e:\n            if not e.filename:\n                e.filename = editor\n            raise\n        except subprocess.CalledProcessError as e:\n            raise PipError(\n                \"Editor Subprocess exited with exit code {}\".format(e.returncode)\n            )\n\n    def _get_n_args(self, args: List[str], example: str, n: int) -> Any:\n        \"\"\"Helper to make sure the command got the right number of arguments\"\"\"\n        if len(args) != n:\n            msg = (\n                \"Got unexpected number of arguments, expected {}. \"\n                '(example: \"{} config {}\")'\n            ).format(n, get_prog(), example)\n            raise PipError(msg)\n\n        if n == 1:\n            return args[0]\n        else:\n            return args\n\n    def _save_configuration(self) -> None:\n        # We successfully ran a modifying command. Need to save the\n        # configuration.\n        try:\n            self.configuration.save()\n        except Exception:\n            logger.exception(\n                \"Unable to save configuration. Please report this as a bug.\"\n            )\n            raise PipError(\"Internal Error.\")\n\n    def _determine_editor(self, options: Values) -> str:\n        if options.editor is not None:\n            return options.editor\n        elif \"VISUAL\" in os.environ:\n            return os.environ[\"VISUAL\"]\n        elif \"EDITOR\" in os.environ:\n            return os.environ[\"EDITOR\"]\n        else:\n            raise PipError(\"Could not determine editor to use.\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/debug.py",
    "content": "import importlib.resources\nimport locale\nimport logging\nimport os\nimport sys\nfrom optparse import Values\nfrom types import ModuleType\nfrom typing import Any, Dict, List, Optional\n\nimport pip._vendor\nfrom pip._vendor.certifi import where\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.cmdoptions import make_target_python\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.configuration import Configuration\nfrom pip._internal.metadata import get_environment\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import get_pip_version\n\nlogger = logging.getLogger(__name__)\n\n\ndef show_value(name: str, value: Any) -> None:\n    logger.info(\"%s: %s\", name, value)\n\n\ndef show_sys_implementation() -> None:\n    logger.info(\"sys.implementation:\")\n    implementation_name = sys.implementation.name\n    with indent_log():\n        show_value(\"name\", implementation_name)\n\n\ndef create_vendor_txt_map() -> Dict[str, str]:\n    with importlib.resources.open_text(\"pip._vendor\", \"vendor.txt\") as f:\n        # Purge non version specifying lines.\n        # Also, remove any space prefix or suffixes (including comments).\n        lines = [\n            line.strip().split(\" \", 1)[0] for line in f.readlines() if \"==\" in line\n        ]\n\n    # Transform into \"module\" -> version dict.\n    return dict(line.split(\"==\", 1) for line in lines)\n\n\ndef get_module_from_module_name(module_name: str) -> ModuleType:\n    # Module name can be uppercase in vendor.txt for some reason...\n    module_name = module_name.lower()\n    # PATCH: setuptools is actually only pkg_resources.\n    if module_name == \"setuptools\":\n        module_name = \"pkg_resources\"\n\n    __import__(f\"pip._vendor.{module_name}\", globals(), locals(), level=0)\n    return getattr(pip._vendor, module_name)\n\n\ndef get_vendor_version_from_module(module_name: str) -> Optional[str]:\n    module = get_module_from_module_name(module_name)\n    version = getattr(module, \"__version__\", None)\n\n    if not version:\n        # Try to find version in debundled module info.\n        assert module.__file__ is not None\n        env = get_environment([os.path.dirname(module.__file__)])\n        dist = env.get_distribution(module_name)\n        if dist:\n            version = str(dist.version)\n\n    return version\n\n\ndef show_actual_vendor_versions(vendor_txt_versions: Dict[str, str]) -> None:\n    \"\"\"Log the actual version and print extra info if there is\n    a conflict or if the actual version could not be imported.\n    \"\"\"\n    for module_name, expected_version in vendor_txt_versions.items():\n        extra_message = \"\"\n        actual_version = get_vendor_version_from_module(module_name)\n        if not actual_version:\n            extra_message = (\n                \" (Unable to locate actual module version, using\"\n                \" vendor.txt specified version)\"\n            )\n            actual_version = expected_version\n        elif parse_version(actual_version) != parse_version(expected_version):\n            extra_message = (\n                \" (CONFLICT: vendor.txt suggests version should\"\n                \" be {})\".format(expected_version)\n            )\n        logger.info(\"%s==%s%s\", module_name, actual_version, extra_message)\n\n\ndef show_vendor_versions() -> None:\n    logger.info(\"vendored library versions:\")\n\n    vendor_txt_versions = create_vendor_txt_map()\n    with indent_log():\n        show_actual_vendor_versions(vendor_txt_versions)\n\n\ndef show_tags(options: Values) -> None:\n    tag_limit = 10\n\n    target_python = make_target_python(options)\n    tags = target_python.get_tags()\n\n    # Display the target options that were explicitly provided.\n    formatted_target = target_python.format_given()\n    suffix = \"\"\n    if formatted_target:\n        suffix = f\" (target: {formatted_target})\"\n\n    msg = \"Compatible tags: {}{}\".format(len(tags), suffix)\n    logger.info(msg)\n\n    if options.verbose < 1 and len(tags) > tag_limit:\n        tags_limited = True\n        tags = tags[:tag_limit]\n    else:\n        tags_limited = False\n\n    with indent_log():\n        for tag in tags:\n            logger.info(str(tag))\n\n        if tags_limited:\n            msg = (\n                \"...\\n[First {tag_limit} tags shown. Pass --verbose to show all.]\"\n            ).format(tag_limit=tag_limit)\n            logger.info(msg)\n\n\ndef ca_bundle_info(config: Configuration) -> str:\n    levels = set()\n    for key, _ in config.items():\n        levels.add(key.split(\".\")[0])\n\n    if not levels:\n        return \"Not specified\"\n\n    levels_that_override_global = [\"install\", \"wheel\", \"download\"]\n    global_overriding_level = [\n        level for level in levels if level in levels_that_override_global\n    ]\n    if not global_overriding_level:\n        return \"global\"\n\n    if \"global\" in levels:\n        levels.remove(\"global\")\n    return \", \".join(levels)\n\n\nclass DebugCommand(Command):\n    \"\"\"\n    Display debug information.\n    \"\"\"\n\n    usage = \"\"\"\n      %prog <options>\"\"\"\n    ignore_require_venv = True\n\n    def add_options(self) -> None:\n        cmdoptions.add_target_python_options(self.cmd_opts)\n        self.parser.insert_option_group(0, self.cmd_opts)\n        self.parser.config.load()\n\n    def run(self, options: Values, args: List[str]) -> int:\n        logger.warning(\n            \"This command is only meant for debugging. \"\n            \"Do not use this with automation for parsing and getting these \"\n            \"details, since the output and options of this command may \"\n            \"change without notice.\"\n        )\n        show_value(\"pip version\", get_pip_version())\n        show_value(\"sys.version\", sys.version)\n        show_value(\"sys.executable\", sys.executable)\n        show_value(\"sys.getdefaultencoding\", sys.getdefaultencoding())\n        show_value(\"sys.getfilesystemencoding\", sys.getfilesystemencoding())\n        show_value(\n            \"locale.getpreferredencoding\",\n            locale.getpreferredencoding(),\n        )\n        show_value(\"sys.platform\", sys.platform)\n        show_sys_implementation()\n\n        show_value(\"'cert' config value\", ca_bundle_info(self.parser.config))\n        show_value(\"REQUESTS_CA_BUNDLE\", os.environ.get(\"REQUESTS_CA_BUNDLE\"))\n        show_value(\"CURL_CA_BUNDLE\", os.environ.get(\"CURL_CA_BUNDLE\"))\n        show_value(\"pip._vendor.certifi.where()\", where())\n        show_value(\"pip._vendor.DEBUNDLED\", pip._vendor.DEBUNDLED)\n\n        show_vendor_versions()\n\n        show_tags(options)\n\n        return SUCCESS\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/download.py",
    "content": "import logging\nimport os\nfrom optparse import Values\nfrom typing import List\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.cmdoptions import make_target_python\nfrom pip._internal.cli.req_command import RequirementCommand, with_cleanup\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.operations.build.build_tracker import get_build_tracker\nfrom pip._internal.req.req_install import (\n    LegacySetupPyOptionsCheckMode,\n    check_legacy_setup_py_options,\n)\nfrom pip._internal.utils.misc import ensure_dir, normalize_path, write_output\nfrom pip._internal.utils.temp_dir import TempDirectory\n\nlogger = logging.getLogger(__name__)\n\n\nclass DownloadCommand(RequirementCommand):\n    \"\"\"\n    Download packages from:\n\n    - PyPI (and other indexes) using requirement specifiers.\n    - VCS project urls.\n    - Local project directories.\n    - Local or remote source archives.\n\n    pip also supports downloading from \"requirements files\", which provide\n    an easy way to specify a whole environment to be downloaded.\n    \"\"\"\n\n    usage = \"\"\"\n      %prog [options] <requirement specifier> [package-index-options] ...\n      %prog [options] -r <requirements file> [package-index-options] ...\n      %prog [options] <vcs project url> ...\n      %prog [options] <local project path> ...\n      %prog [options] <archive url/path> ...\"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(cmdoptions.constraints())\n        self.cmd_opts.add_option(cmdoptions.requirements())\n        self.cmd_opts.add_option(cmdoptions.no_deps())\n        self.cmd_opts.add_option(cmdoptions.global_options())\n        self.cmd_opts.add_option(cmdoptions.no_binary())\n        self.cmd_opts.add_option(cmdoptions.only_binary())\n        self.cmd_opts.add_option(cmdoptions.prefer_binary())\n        self.cmd_opts.add_option(cmdoptions.src())\n        self.cmd_opts.add_option(cmdoptions.pre())\n        self.cmd_opts.add_option(cmdoptions.require_hashes())\n        self.cmd_opts.add_option(cmdoptions.progress_bar())\n        self.cmd_opts.add_option(cmdoptions.no_build_isolation())\n        self.cmd_opts.add_option(cmdoptions.use_pep517())\n        self.cmd_opts.add_option(cmdoptions.no_use_pep517())\n        self.cmd_opts.add_option(cmdoptions.check_build_deps())\n        self.cmd_opts.add_option(cmdoptions.ignore_requires_python())\n\n        self.cmd_opts.add_option(\n            \"-d\",\n            \"--dest\",\n            \"--destination-dir\",\n            \"--destination-directory\",\n            dest=\"download_dir\",\n            metavar=\"dir\",\n            default=os.curdir,\n            help=\"Download packages into <dir>.\",\n        )\n\n        cmdoptions.add_target_python_options(self.cmd_opts)\n\n        index_opts = cmdoptions.make_option_group(\n            cmdoptions.index_group,\n            self.parser,\n        )\n\n        self.parser.insert_option_group(0, index_opts)\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    @with_cleanup\n    def run(self, options: Values, args: List[str]) -> int:\n\n        options.ignore_installed = True\n        # editable doesn't really make sense for `pip download`, but the bowels\n        # of the RequirementSet code require that property.\n        options.editables = []\n\n        cmdoptions.check_dist_restriction(options)\n\n        options.download_dir = normalize_path(options.download_dir)\n        ensure_dir(options.download_dir)\n\n        session = self.get_default_session(options)\n\n        target_python = make_target_python(options)\n        finder = self._build_package_finder(\n            options=options,\n            session=session,\n            target_python=target_python,\n            ignore_requires_python=options.ignore_requires_python,\n        )\n\n        build_tracker = self.enter_context(get_build_tracker())\n\n        directory = TempDirectory(\n            delete=not options.no_clean,\n            kind=\"download\",\n            globally_managed=True,\n        )\n\n        reqs = self.get_requirements(args, options, finder, session)\n        check_legacy_setup_py_options(\n            options, reqs, LegacySetupPyOptionsCheckMode.DOWNLOAD\n        )\n\n        preparer = self.make_requirement_preparer(\n            temp_build_dir=directory,\n            options=options,\n            build_tracker=build_tracker,\n            session=session,\n            finder=finder,\n            download_dir=options.download_dir,\n            use_user_site=False,\n            verbosity=self.verbosity,\n        )\n\n        resolver = self.make_resolver(\n            preparer=preparer,\n            finder=finder,\n            options=options,\n            ignore_requires_python=options.ignore_requires_python,\n            use_pep517=options.use_pep517,\n            py_version_info=options.python_version,\n        )\n\n        self.trace_basic_info(finder)\n\n        requirement_set = resolver.resolve(reqs, check_supported_wheels=True)\n\n        downloaded: List[str] = []\n        for req in requirement_set.requirements.values():\n            if req.satisfied_by is None:\n                assert req.name is not None\n                preparer.save_linked_requirement(req)\n                downloaded.append(req.name)\n        if downloaded:\n            write_output(\"Successfully downloaded %s\", \" \".join(downloaded))\n\n        return SUCCESS\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/freeze.py",
    "content": "import sys\nfrom optparse import Values\nfrom typing import List\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.operations.freeze import freeze\nfrom pip._internal.utils.compat import stdlib_pkgs\n\nDEV_PKGS = {\"pip\", \"setuptools\", \"distribute\", \"wheel\"}\n\n\nclass FreezeCommand(Command):\n    \"\"\"\n    Output installed packages in requirements format.\n\n    packages are listed in a case-insensitive sorted order.\n    \"\"\"\n\n    usage = \"\"\"\n      %prog [options]\"\"\"\n    log_streams = (\"ext://sys.stderr\", \"ext://sys.stderr\")\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"-r\",\n            \"--requirement\",\n            dest=\"requirements\",\n            action=\"append\",\n            default=[],\n            metavar=\"file\",\n            help=(\n                \"Use the order in the given requirements file and its \"\n                \"comments when generating output. This option can be \"\n                \"used multiple times.\"\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"-l\",\n            \"--local\",\n            dest=\"local\",\n            action=\"store_true\",\n            default=False,\n            help=(\n                \"If in a virtualenv that has global access, do not output \"\n                \"globally-installed packages.\"\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"--user\",\n            dest=\"user\",\n            action=\"store_true\",\n            default=False,\n            help=\"Only output packages installed in user-site.\",\n        )\n        self.cmd_opts.add_option(cmdoptions.list_path())\n        self.cmd_opts.add_option(\n            \"--all\",\n            dest=\"freeze_all\",\n            action=\"store_true\",\n            help=(\n                \"Do not skip these packages in the output:\"\n                \" {}\".format(\", \".join(DEV_PKGS))\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"--exclude-editable\",\n            dest=\"exclude_editable\",\n            action=\"store_true\",\n            help=\"Exclude editable package from output.\",\n        )\n        self.cmd_opts.add_option(cmdoptions.list_exclude())\n\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: List[str]) -> int:\n        skip = set(stdlib_pkgs)\n        if not options.freeze_all:\n            skip.update(DEV_PKGS)\n\n        if options.excludes:\n            skip.update(options.excludes)\n\n        cmdoptions.check_list_path_option(options)\n\n        for line in freeze(\n            requirement=options.requirements,\n            local_only=options.local,\n            user_only=options.user,\n            paths=options.path,\n            isolated=options.isolated_mode,\n            skip=skip,\n            exclude_editable=options.exclude_editable,\n        ):\n            sys.stdout.write(line + \"\\n\")\n        return SUCCESS\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/hash.py",
    "content": "import hashlib\nimport logging\nimport sys\nfrom optparse import Values\nfrom typing import List\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.utils.hashes import FAVORITE_HASH, STRONG_HASHES\nfrom pip._internal.utils.misc import read_chunks, write_output\n\nlogger = logging.getLogger(__name__)\n\n\nclass HashCommand(Command):\n    \"\"\"\n    Compute a hash of a local package archive.\n\n    These can be used with --hash in a requirements file to do repeatable\n    installs.\n    \"\"\"\n\n    usage = \"%prog [options] <file> ...\"\n    ignore_require_venv = True\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"-a\",\n            \"--algorithm\",\n            dest=\"algorithm\",\n            choices=STRONG_HASHES,\n            action=\"store\",\n            default=FAVORITE_HASH,\n            help=\"The hash algorithm to use: one of {}\".format(\n                \", \".join(STRONG_HASHES)\n            ),\n        )\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: List[str]) -> int:\n        if not args:\n            self.parser.print_usage(sys.stderr)\n            return ERROR\n\n        algorithm = options.algorithm\n        for path in args:\n            write_output(\n                \"%s:\\n--hash=%s:%s\", path, algorithm, _hash_of_file(path, algorithm)\n            )\n        return SUCCESS\n\n\ndef _hash_of_file(path: str, algorithm: str) -> str:\n    \"\"\"Return the hash digest of a file.\"\"\"\n    with open(path, \"rb\") as archive:\n        hash = hashlib.new(algorithm)\n        for chunk in read_chunks(archive):\n            hash.update(chunk)\n    return hash.hexdigest()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/help.py",
    "content": "from optparse import Values\nfrom typing import List\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.exceptions import CommandError\n\n\nclass HelpCommand(Command):\n    \"\"\"Show help for commands\"\"\"\n\n    usage = \"\"\"\n      %prog <command>\"\"\"\n    ignore_require_venv = True\n\n    def run(self, options: Values, args: List[str]) -> int:\n        from pip._internal.commands import (\n            commands_dict,\n            create_command,\n            get_similar_commands,\n        )\n\n        try:\n            # 'pip help' with no args is handled by pip.__init__.parseopt()\n            cmd_name = args[0]  # the command we need help for\n        except IndexError:\n            return SUCCESS\n\n        if cmd_name not in commands_dict:\n            guess = get_similar_commands(cmd_name)\n\n            msg = [f'unknown command \"{cmd_name}\"']\n            if guess:\n                msg.append(f'maybe you meant \"{guess}\"')\n\n            raise CommandError(\" - \".join(msg))\n\n        command = create_command(cmd_name)\n        command.parser.print_help()\n\n        return SUCCESS\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/index.py",
    "content": "import logging\nfrom optparse import Values\nfrom typing import Any, Iterable, List, Optional, Union\n\nfrom pip._vendor.packaging.version import LegacyVersion, Version\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.req_command import IndexGroupCommand\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.commands.search import print_dist_installation_info\nfrom pip._internal.exceptions import CommandError, DistributionNotFound, PipError\nfrom pip._internal.index.collector import LinkCollector\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.models.selection_prefs import SelectionPreferences\nfrom pip._internal.models.target_python import TargetPython\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.utils.misc import write_output\n\nlogger = logging.getLogger(__name__)\n\n\nclass IndexCommand(IndexGroupCommand):\n    \"\"\"\n    Inspect information available from package indexes.\n    \"\"\"\n\n    usage = \"\"\"\n        %prog versions <package>\n    \"\"\"\n\n    def add_options(self) -> None:\n        cmdoptions.add_target_python_options(self.cmd_opts)\n\n        self.cmd_opts.add_option(cmdoptions.ignore_requires_python())\n        self.cmd_opts.add_option(cmdoptions.pre())\n        self.cmd_opts.add_option(cmdoptions.no_binary())\n        self.cmd_opts.add_option(cmdoptions.only_binary())\n\n        index_opts = cmdoptions.make_option_group(\n            cmdoptions.index_group,\n            self.parser,\n        )\n\n        self.parser.insert_option_group(0, index_opts)\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: List[str]) -> int:\n        handlers = {\n            \"versions\": self.get_available_package_versions,\n        }\n\n        logger.warning(\n            \"pip index is currently an experimental command. \"\n            \"It may be removed/changed in a future release \"\n            \"without prior warning.\"\n        )\n\n        # Determine action\n        if not args or args[0] not in handlers:\n            logger.error(\n                \"Need an action (%s) to perform.\",\n                \", \".join(sorted(handlers)),\n            )\n            return ERROR\n\n        action = args[0]\n\n        # Error handling happens here, not in the action-handlers.\n        try:\n            handlers[action](options, args[1:])\n        except PipError as e:\n            logger.error(e.args[0])\n            return ERROR\n\n        return SUCCESS\n\n    def _build_package_finder(\n        self,\n        options: Values,\n        session: PipSession,\n        target_python: Optional[TargetPython] = None,\n        ignore_requires_python: Optional[bool] = None,\n    ) -> PackageFinder:\n        \"\"\"\n        Create a package finder appropriate to the index command.\n        \"\"\"\n        link_collector = LinkCollector.create(session, options=options)\n\n        # Pass allow_yanked=False to ignore yanked versions.\n        selection_prefs = SelectionPreferences(\n            allow_yanked=False,\n            allow_all_prereleases=options.pre,\n            ignore_requires_python=ignore_requires_python,\n        )\n\n        return PackageFinder.create(\n            link_collector=link_collector,\n            selection_prefs=selection_prefs,\n            target_python=target_python,\n        )\n\n    def get_available_package_versions(self, options: Values, args: List[Any]) -> None:\n        if len(args) != 1:\n            raise CommandError(\"You need to specify exactly one argument\")\n\n        target_python = cmdoptions.make_target_python(options)\n        query = args[0]\n\n        with self._build_session(options) as session:\n            finder = self._build_package_finder(\n                options=options,\n                session=session,\n                target_python=target_python,\n                ignore_requires_python=options.ignore_requires_python,\n            )\n\n            versions: Iterable[Union[LegacyVersion, Version]] = (\n                candidate.version for candidate in finder.find_all_candidates(query)\n            )\n\n            if not options.pre:\n                # Remove prereleases\n                versions = (\n                    version for version in versions if not version.is_prerelease\n                )\n            versions = set(versions)\n\n            if not versions:\n                raise DistributionNotFound(\n                    \"No matching distribution found for {}\".format(query)\n                )\n\n            formatted_versions = [str(ver) for ver in sorted(versions, reverse=True)]\n            latest = formatted_versions[0]\n\n        write_output(\"{} ({})\".format(query, latest))\n        write_output(\"Available versions: {}\".format(\", \".join(formatted_versions)))\n        print_dist_installation_info(query, latest)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/inspect.py",
    "content": "import logging\nfrom optparse import Values\nfrom typing import Any, Dict, List\n\nfrom pip._vendor.packaging.markers import default_environment\nfrom pip._vendor.rich import print_json\n\nfrom pip import __version__\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.req_command import Command\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.metadata import BaseDistribution, get_environment\nfrom pip._internal.utils.compat import stdlib_pkgs\nfrom pip._internal.utils.urls import path_to_url\n\nlogger = logging.getLogger(__name__)\n\n\nclass InspectCommand(Command):\n    \"\"\"\n    Inspect the content of a Python environment and produce a report in JSON format.\n    \"\"\"\n\n    ignore_require_venv = True\n    usage = \"\"\"\n      %prog [options]\"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"--local\",\n            action=\"store_true\",\n            default=False,\n            help=(\n                \"If in a virtualenv that has global access, do not list \"\n                \"globally-installed packages.\"\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"--user\",\n            dest=\"user\",\n            action=\"store_true\",\n            default=False,\n            help=\"Only output packages installed in user-site.\",\n        )\n        self.cmd_opts.add_option(cmdoptions.list_path())\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: List[str]) -> int:\n        logger.warning(\n            \"pip inspect is currently an experimental command. \"\n            \"The output format may change in a future release without prior warning.\"\n        )\n\n        cmdoptions.check_list_path_option(options)\n        dists = get_environment(options.path).iter_installed_distributions(\n            local_only=options.local,\n            user_only=options.user,\n            skip=set(stdlib_pkgs),\n        )\n        output = {\n            \"version\": \"0\",\n            \"pip_version\": __version__,\n            \"installed\": [self._dist_to_dict(dist) for dist in dists],\n            \"environment\": default_environment(),\n            # TODO tags? scheme?\n        }\n        print_json(data=output)\n        return SUCCESS\n\n    def _dist_to_dict(self, dist: BaseDistribution) -> Dict[str, Any]:\n        res: Dict[str, Any] = {\n            \"metadata\": dist.metadata_dict,\n            \"metadata_location\": dist.info_location,\n        }\n        # direct_url. Note that we don't have download_info (as in the installation\n        # report) since it is not recorded in installed metadata.\n        direct_url = dist.direct_url\n        if direct_url is not None:\n            res[\"direct_url\"] = direct_url.to_dict()\n        else:\n            # Emulate direct_url for legacy editable installs.\n            editable_project_location = dist.editable_project_location\n            if editable_project_location is not None:\n                res[\"direct_url\"] = {\n                    \"url\": path_to_url(editable_project_location),\n                    \"dir_info\": {\n                        \"editable\": True,\n                    },\n                }\n        # installer\n        installer = dist.installer\n        if dist.installer:\n            res[\"installer\"] = installer\n        # requested\n        if dist.installed_with_dist_info:\n            res[\"requested\"] = dist.requested\n        return res\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/install.py",
    "content": "import errno\nimport json\nimport operator\nimport os\nimport shutil\nimport site\nfrom optparse import SUPPRESS_HELP, Values\nfrom typing import Iterable, List, Optional\n\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.rich import print_json\n\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.cmdoptions import make_target_python\nfrom pip._internal.cli.req_command import (\n    RequirementCommand,\n    warn_if_run_as_root,\n    with_cleanup,\n)\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.exceptions import CommandError, InstallationError\nfrom pip._internal.locations import get_scheme\nfrom pip._internal.metadata import get_environment\nfrom pip._internal.models.format_control import FormatControl\nfrom pip._internal.models.installation_report import InstallationReport\nfrom pip._internal.operations.build.build_tracker import get_build_tracker\nfrom pip._internal.operations.check import ConflictDetails, check_install_conflicts\nfrom pip._internal.req import install_given_reqs\nfrom pip._internal.req.req_install import (\n    InstallRequirement,\n    LegacySetupPyOptionsCheckMode,\n    check_legacy_setup_py_options,\n)\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.deprecation import (\n    LegacyInstallReasonFailedBdistWheel,\n    deprecated,\n)\nfrom pip._internal.utils.distutils_args import parse_distutils_args\nfrom pip._internal.utils.filesystem import test_writable_dir\nfrom pip._internal.utils.logging import getLogger\nfrom pip._internal.utils.misc import (\n    ensure_dir,\n    get_pip_version,\n    protect_pip_from_modification_on_windows,\n    write_output,\n)\nfrom pip._internal.utils.temp_dir import TempDirectory\nfrom pip._internal.utils.virtualenv import (\n    running_under_virtualenv,\n    virtualenv_no_global,\n)\nfrom pip._internal.wheel_builder import (\n    BdistWheelAllowedPredicate,\n    build,\n    should_build_for_install_command,\n)\n\nlogger = getLogger(__name__)\n\n\ndef get_check_bdist_wheel_allowed(\n    format_control: FormatControl,\n) -> BdistWheelAllowedPredicate:\n    def check_binary_allowed(req: InstallRequirement) -> bool:\n        canonical_name = canonicalize_name(req.name or \"\")\n        allowed_formats = format_control.get_allowed_formats(canonical_name)\n        return \"binary\" in allowed_formats\n\n    return check_binary_allowed\n\n\nclass InstallCommand(RequirementCommand):\n    \"\"\"\n    Install packages from:\n\n    - PyPI (and other indexes) using requirement specifiers.\n    - VCS project urls.\n    - Local project directories.\n    - Local or remote source archives.\n\n    pip also supports installing from \"requirements files\", which provide\n    an easy way to specify a whole environment to be installed.\n    \"\"\"\n\n    usage = \"\"\"\n      %prog [options] <requirement specifier> [package-index-options] ...\n      %prog [options] -r <requirements file> [package-index-options] ...\n      %prog [options] [-e] <vcs project url> ...\n      %prog [options] [-e] <local project path> ...\n      %prog [options] <archive url/path> ...\"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(cmdoptions.requirements())\n        self.cmd_opts.add_option(cmdoptions.constraints())\n        self.cmd_opts.add_option(cmdoptions.no_deps())\n        self.cmd_opts.add_option(cmdoptions.pre())\n\n        self.cmd_opts.add_option(cmdoptions.editable())\n        self.cmd_opts.add_option(\n            \"--dry-run\",\n            action=\"store_true\",\n            dest=\"dry_run\",\n            default=False,\n            help=(\n                \"Don't actually install anything, just print what would be. \"\n                \"Can be used in combination with --ignore-installed \"\n                \"to 'resolve' the requirements.\"\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"-t\",\n            \"--target\",\n            dest=\"target_dir\",\n            metavar=\"dir\",\n            default=None,\n            help=(\n                \"Install packages into <dir>. \"\n                \"By default this will not replace existing files/folders in \"\n                \"<dir>. Use --upgrade to replace existing packages in <dir> \"\n                \"with new versions.\"\n            ),\n        )\n        cmdoptions.add_target_python_options(self.cmd_opts)\n\n        self.cmd_opts.add_option(\n            \"--user\",\n            dest=\"use_user_site\",\n            action=\"store_true\",\n            help=(\n                \"Install to the Python user install directory for your \"\n                \"platform. Typically ~/.local/, or %APPDATA%\\\\Python on \"\n                \"Windows. (See the Python documentation for site.USER_BASE \"\n                \"for full details.)\"\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"--no-user\",\n            dest=\"use_user_site\",\n            action=\"store_false\",\n            help=SUPPRESS_HELP,\n        )\n        self.cmd_opts.add_option(\n            \"--root\",\n            dest=\"root_path\",\n            metavar=\"dir\",\n            default=None,\n            help=\"Install everything relative to this alternate root directory.\",\n        )\n        self.cmd_opts.add_option(\n            \"--prefix\",\n            dest=\"prefix_path\",\n            metavar=\"dir\",\n            default=None,\n            help=(\n                \"Installation prefix where lib, bin and other top-level \"\n                \"folders are placed\"\n            ),\n        )\n\n        self.cmd_opts.add_option(cmdoptions.src())\n\n        self.cmd_opts.add_option(\n            \"-U\",\n            \"--upgrade\",\n            dest=\"upgrade\",\n            action=\"store_true\",\n            help=(\n                \"Upgrade all specified packages to the newest available \"\n                \"version. The handling of dependencies depends on the \"\n                \"upgrade-strategy used.\"\n            ),\n        )\n\n        self.cmd_opts.add_option(\n            \"--upgrade-strategy\",\n            dest=\"upgrade_strategy\",\n            default=\"only-if-needed\",\n            choices=[\"only-if-needed\", \"eager\"],\n            help=(\n                \"Determines how dependency upgrading should be handled \"\n                \"[default: %default]. \"\n                '\"eager\" - dependencies are upgraded regardless of '\n                \"whether the currently installed version satisfies the \"\n                \"requirements of the upgraded package(s). \"\n                '\"only-if-needed\" -  are upgraded only when they do not '\n                \"satisfy the requirements of the upgraded package(s).\"\n            ),\n        )\n\n        self.cmd_opts.add_option(\n            \"--force-reinstall\",\n            dest=\"force_reinstall\",\n            action=\"store_true\",\n            help=\"Reinstall all packages even if they are already up-to-date.\",\n        )\n\n        self.cmd_opts.add_option(\n            \"-I\",\n            \"--ignore-installed\",\n            dest=\"ignore_installed\",\n            action=\"store_true\",\n            help=(\n                \"Ignore the installed packages, overwriting them. \"\n                \"This can break your system if the existing package \"\n                \"is of a different version or was installed \"\n                \"with a different package manager!\"\n            ),\n        )\n\n        self.cmd_opts.add_option(cmdoptions.ignore_requires_python())\n        self.cmd_opts.add_option(cmdoptions.no_build_isolation())\n        self.cmd_opts.add_option(cmdoptions.use_pep517())\n        self.cmd_opts.add_option(cmdoptions.no_use_pep517())\n        self.cmd_opts.add_option(cmdoptions.check_build_deps())\n\n        self.cmd_opts.add_option(cmdoptions.config_settings())\n        self.cmd_opts.add_option(cmdoptions.install_options())\n        self.cmd_opts.add_option(cmdoptions.global_options())\n\n        self.cmd_opts.add_option(\n            \"--compile\",\n            action=\"store_true\",\n            dest=\"compile\",\n            default=True,\n            help=\"Compile Python source files to bytecode\",\n        )\n\n        self.cmd_opts.add_option(\n            \"--no-compile\",\n            action=\"store_false\",\n            dest=\"compile\",\n            help=\"Do not compile Python source files to bytecode\",\n        )\n\n        self.cmd_opts.add_option(\n            \"--no-warn-script-location\",\n            action=\"store_false\",\n            dest=\"warn_script_location\",\n            default=True,\n            help=\"Do not warn when installing scripts outside PATH\",\n        )\n        self.cmd_opts.add_option(\n            \"--no-warn-conflicts\",\n            action=\"store_false\",\n            dest=\"warn_about_conflicts\",\n            default=True,\n            help=\"Do not warn about broken dependencies\",\n        )\n        self.cmd_opts.add_option(cmdoptions.no_binary())\n        self.cmd_opts.add_option(cmdoptions.only_binary())\n        self.cmd_opts.add_option(cmdoptions.prefer_binary())\n        self.cmd_opts.add_option(cmdoptions.require_hashes())\n        self.cmd_opts.add_option(cmdoptions.progress_bar())\n        self.cmd_opts.add_option(cmdoptions.root_user_action())\n\n        index_opts = cmdoptions.make_option_group(\n            cmdoptions.index_group,\n            self.parser,\n        )\n\n        self.parser.insert_option_group(0, index_opts)\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n        self.cmd_opts.add_option(\n            \"--report\",\n            dest=\"json_report_file\",\n            metavar=\"file\",\n            default=None,\n            help=(\n                \"Generate a JSON file describing what pip did to install \"\n                \"the provided requirements. \"\n                \"Can be used in combination with --dry-run and --ignore-installed \"\n                \"to 'resolve' the requirements. \"\n                \"When - is used as file name it writes to stdout. \"\n                \"When writing to stdout, please combine with the --quiet option \"\n                \"to avoid mixing pip logging output with JSON output.\"\n            ),\n        )\n\n    @with_cleanup\n    def run(self, options: Values, args: List[str]) -> int:\n        if options.use_user_site and options.target_dir is not None:\n            raise CommandError(\"Can not combine '--user' and '--target'\")\n\n        upgrade_strategy = \"to-satisfy-only\"\n        if options.upgrade:\n            upgrade_strategy = options.upgrade_strategy\n\n        cmdoptions.check_dist_restriction(options, check_target=True)\n\n        install_options = options.install_options or []\n\n        logger.verbose(\"Using %s\", get_pip_version())\n        options.use_user_site = decide_user_install(\n            options.use_user_site,\n            prefix_path=options.prefix_path,\n            target_dir=options.target_dir,\n            root_path=options.root_path,\n            isolated_mode=options.isolated_mode,\n        )\n\n        target_temp_dir: Optional[TempDirectory] = None\n        target_temp_dir_path: Optional[str] = None\n        if options.target_dir:\n            options.ignore_installed = True\n            options.target_dir = os.path.abspath(options.target_dir)\n            if (\n                # fmt: off\n                os.path.exists(options.target_dir) and\n                not os.path.isdir(options.target_dir)\n                # fmt: on\n            ):\n                raise CommandError(\n                    \"Target path exists but is not a directory, will not continue.\"\n                )\n\n            # Create a target directory for using with the target option\n            target_temp_dir = TempDirectory(kind=\"target\")\n            target_temp_dir_path = target_temp_dir.path\n            self.enter_context(target_temp_dir)\n\n        global_options = options.global_options or []\n\n        session = self.get_default_session(options)\n\n        target_python = make_target_python(options)\n        finder = self._build_package_finder(\n            options=options,\n            session=session,\n            target_python=target_python,\n            ignore_requires_python=options.ignore_requires_python,\n        )\n        build_tracker = self.enter_context(get_build_tracker())\n\n        directory = TempDirectory(\n            delete=not options.no_clean,\n            kind=\"install\",\n            globally_managed=True,\n        )\n\n        try:\n            reqs = self.get_requirements(args, options, finder, session)\n            check_legacy_setup_py_options(\n                options, reqs, LegacySetupPyOptionsCheckMode.INSTALL\n            )\n\n            if \"no-binary-enable-wheel-cache\" in options.features_enabled:\n                # TODO: remove format_control from WheelCache when the deprecation cycle\n                # is over\n                wheel_cache = WheelCache(options.cache_dir)\n            else:\n                if options.format_control.no_binary:\n                    deprecated(\n                        reason=(\n                            \"--no-binary currently disables reading from \"\n                            \"the cache of locally built wheels. In the future \"\n                            \"--no-binary will not influence the wheel cache.\"\n                        ),\n                        replacement=\"to use the --no-cache-dir option\",\n                        feature_flag=\"no-binary-enable-wheel-cache\",\n                        issue=11453,\n                        gone_in=\"23.1\",\n                    )\n                wheel_cache = WheelCache(options.cache_dir, options.format_control)\n\n            # Only when installing is it permitted to use PEP 660.\n            # In other circumstances (pip wheel, pip download) we generate\n            # regular (i.e. non editable) metadata and wheels.\n            for req in reqs:\n                req.permit_editable_wheels = True\n\n            reject_location_related_install_options(reqs, options.install_options)\n\n            preparer = self.make_requirement_preparer(\n                temp_build_dir=directory,\n                options=options,\n                build_tracker=build_tracker,\n                session=session,\n                finder=finder,\n                use_user_site=options.use_user_site,\n                verbosity=self.verbosity,\n            )\n            resolver = self.make_resolver(\n                preparer=preparer,\n                finder=finder,\n                options=options,\n                wheel_cache=wheel_cache,\n                use_user_site=options.use_user_site,\n                ignore_installed=options.ignore_installed,\n                ignore_requires_python=options.ignore_requires_python,\n                force_reinstall=options.force_reinstall,\n                upgrade_strategy=upgrade_strategy,\n                use_pep517=options.use_pep517,\n            )\n\n            self.trace_basic_info(finder)\n\n            requirement_set = resolver.resolve(\n                reqs, check_supported_wheels=not options.target_dir\n            )\n\n            if options.json_report_file:\n                logger.warning(\n                    \"--report is currently an experimental option. \"\n                    \"The output format may change in a future release \"\n                    \"without prior warning.\"\n                )\n\n                report = InstallationReport(requirement_set.requirements_to_install)\n                if options.json_report_file == \"-\":\n                    print_json(data=report.to_dict())\n                else:\n                    with open(options.json_report_file, \"w\", encoding=\"utf-8\") as f:\n                        json.dump(report.to_dict(), f, indent=2, ensure_ascii=False)\n\n            if options.dry_run:\n                would_install_items = sorted(\n                    (r.metadata[\"name\"], r.metadata[\"version\"])\n                    for r in requirement_set.requirements_to_install\n                )\n                if would_install_items:\n                    write_output(\n                        \"Would install %s\",\n                        \" \".join(\"-\".join(item) for item in would_install_items),\n                    )\n                return SUCCESS\n\n            try:\n                pip_req = requirement_set.get_requirement(\"pip\")\n            except KeyError:\n                modifying_pip = False\n            else:\n                # If we're not replacing an already installed pip,\n                # we're not modifying it.\n                modifying_pip = pip_req.satisfied_by is None\n            protect_pip_from_modification_on_windows(modifying_pip=modifying_pip)\n\n            check_bdist_wheel_allowed = get_check_bdist_wheel_allowed(\n                finder.format_control\n            )\n\n            reqs_to_build = [\n                r\n                for r in requirement_set.requirements.values()\n                if should_build_for_install_command(r, check_bdist_wheel_allowed)\n            ]\n\n            _, build_failures = build(\n                reqs_to_build,\n                wheel_cache=wheel_cache,\n                verify=True,\n                build_options=[],\n                global_options=global_options,\n            )\n\n            # If we're using PEP 517, we cannot do a legacy setup.py install\n            # so we fail here.\n            pep517_build_failure_names: List[str] = [\n                r.name for r in build_failures if r.use_pep517  # type: ignore\n            ]\n            if pep517_build_failure_names:\n                raise InstallationError(\n                    \"Could not build wheels for {}, which is required to \"\n                    \"install pyproject.toml-based projects\".format(\n                        \", \".join(pep517_build_failure_names)\n                    )\n                )\n\n            # For now, we just warn about failures building legacy\n            # requirements, as we'll fall through to a setup.py install for\n            # those.\n            for r in build_failures:\n                if not r.use_pep517:\n                    r.legacy_install_reason = LegacyInstallReasonFailedBdistWheel\n\n            to_install = resolver.get_installation_order(requirement_set)\n\n            # Check for conflicts in the package set we're installing.\n            conflicts: Optional[ConflictDetails] = None\n            should_warn_about_conflicts = (\n                not options.ignore_dependencies and options.warn_about_conflicts\n            )\n            if should_warn_about_conflicts:\n                conflicts = self._determine_conflicts(to_install)\n\n            # Don't warn about script install locations if\n            # --target or --prefix has been specified\n            warn_script_location = options.warn_script_location\n            if options.target_dir or options.prefix_path:\n                warn_script_location = False\n\n            installed = install_given_reqs(\n                to_install,\n                install_options,\n                global_options,\n                root=options.root_path,\n                home=target_temp_dir_path,\n                prefix=options.prefix_path,\n                warn_script_location=warn_script_location,\n                use_user_site=options.use_user_site,\n                pycompile=options.compile,\n            )\n\n            lib_locations = get_lib_location_guesses(\n                user=options.use_user_site,\n                home=target_temp_dir_path,\n                root=options.root_path,\n                prefix=options.prefix_path,\n                isolated=options.isolated_mode,\n            )\n            env = get_environment(lib_locations)\n\n            installed.sort(key=operator.attrgetter(\"name\"))\n            items = []\n            for result in installed:\n                item = result.name\n                try:\n                    installed_dist = env.get_distribution(item)\n                    if installed_dist is not None:\n                        item = f\"{item}-{installed_dist.version}\"\n                except Exception:\n                    pass\n                items.append(item)\n\n            if conflicts is not None:\n                self._warn_about_conflicts(\n                    conflicts,\n                    resolver_variant=self.determine_resolver_variant(options),\n                )\n\n            installed_desc = \" \".join(items)\n            if installed_desc:\n                write_output(\n                    \"Successfully installed %s\",\n                    installed_desc,\n                )\n        except OSError as error:\n            show_traceback = self.verbosity >= 1\n\n            message = create_os_error_message(\n                error,\n                show_traceback,\n                options.use_user_site,\n            )\n            logger.error(message, exc_info=show_traceback)  # noqa\n\n            return ERROR\n\n        if options.target_dir:\n            assert target_temp_dir\n            self._handle_target_dir(\n                options.target_dir, target_temp_dir, options.upgrade\n            )\n        if options.root_user_action == \"warn\":\n            warn_if_run_as_root()\n        return SUCCESS\n\n    def _handle_target_dir(\n        self, target_dir: str, target_temp_dir: TempDirectory, upgrade: bool\n    ) -> None:\n        ensure_dir(target_dir)\n\n        # Checking both purelib and platlib directories for installed\n        # packages to be moved to target directory\n        lib_dir_list = []\n\n        # Checking both purelib and platlib directories for installed\n        # packages to be moved to target directory\n        scheme = get_scheme(\"\", home=target_temp_dir.path)\n        purelib_dir = scheme.purelib\n        platlib_dir = scheme.platlib\n        data_dir = scheme.data\n\n        if os.path.exists(purelib_dir):\n            lib_dir_list.append(purelib_dir)\n        if os.path.exists(platlib_dir) and platlib_dir != purelib_dir:\n            lib_dir_list.append(platlib_dir)\n        if os.path.exists(data_dir):\n            lib_dir_list.append(data_dir)\n\n        for lib_dir in lib_dir_list:\n            for item in os.listdir(lib_dir):\n                if lib_dir == data_dir:\n                    ddir = os.path.join(data_dir, item)\n                    if any(s.startswith(ddir) for s in lib_dir_list[:-1]):\n                        continue\n                target_item_dir = os.path.join(target_dir, item)\n                if os.path.exists(target_item_dir):\n                    if not upgrade:\n                        logger.warning(\n                            \"Target directory %s already exists. Specify \"\n                            \"--upgrade to force replacement.\",\n                            target_item_dir,\n                        )\n                        continue\n                    if os.path.islink(target_item_dir):\n                        logger.warning(\n                            \"Target directory %s already exists and is \"\n                            \"a link. pip will not automatically replace \"\n                            \"links, please remove if replacement is \"\n                            \"desired.\",\n                            target_item_dir,\n                        )\n                        continue\n                    if os.path.isdir(target_item_dir):\n                        shutil.rmtree(target_item_dir)\n                    else:\n                        os.remove(target_item_dir)\n\n                shutil.move(os.path.join(lib_dir, item), target_item_dir)\n\n    def _determine_conflicts(\n        self, to_install: List[InstallRequirement]\n    ) -> Optional[ConflictDetails]:\n        try:\n            return check_install_conflicts(to_install)\n        except Exception:\n            logger.exception(\n                \"Error while checking for conflicts. Please file an issue on \"\n                \"pip's issue tracker: https://github.com/pypa/pip/issues/new\"\n            )\n            return None\n\n    def _warn_about_conflicts(\n        self, conflict_details: ConflictDetails, resolver_variant: str\n    ) -> None:\n        package_set, (missing, conflicting) = conflict_details\n        if not missing and not conflicting:\n            return\n\n        parts: List[str] = []\n        if resolver_variant == \"legacy\":\n            parts.append(\n                \"pip's legacy dependency resolver does not consider dependency \"\n                \"conflicts when selecting packages. This behaviour is the \"\n                \"source of the following dependency conflicts.\"\n            )\n        else:\n            assert resolver_variant == \"2020-resolver\"\n            parts.append(\n                \"pip's dependency resolver does not currently take into account \"\n                \"all the packages that are installed. This behaviour is the \"\n                \"source of the following dependency conflicts.\"\n            )\n\n        # NOTE: There is some duplication here, with commands/check.py\n        for project_name in missing:\n            version = package_set[project_name][0]\n            for dependency in missing[project_name]:\n                message = (\n                    \"{name} {version} requires {requirement}, \"\n                    \"which is not installed.\"\n                ).format(\n                    name=project_name,\n                    version=version,\n                    requirement=dependency[1],\n                )\n                parts.append(message)\n\n        for project_name in conflicting:\n            version = package_set[project_name][0]\n            for dep_name, dep_version, req in conflicting[project_name]:\n                message = (\n                    \"{name} {version} requires {requirement}, but {you} have \"\n                    \"{dep_name} {dep_version} which is incompatible.\"\n                ).format(\n                    name=project_name,\n                    version=version,\n                    requirement=req,\n                    dep_name=dep_name,\n                    dep_version=dep_version,\n                    you=(\"you\" if resolver_variant == \"2020-resolver\" else \"you'll\"),\n                )\n                parts.append(message)\n\n        logger.critical(\"\\n\".join(parts))\n\n\ndef get_lib_location_guesses(\n    user: bool = False,\n    home: Optional[str] = None,\n    root: Optional[str] = None,\n    isolated: bool = False,\n    prefix: Optional[str] = None,\n) -> List[str]:\n    scheme = get_scheme(\n        \"\",\n        user=user,\n        home=home,\n        root=root,\n        isolated=isolated,\n        prefix=prefix,\n    )\n    return [scheme.purelib, scheme.platlib]\n\n\ndef site_packages_writable(root: Optional[str], isolated: bool) -> bool:\n    return all(\n        test_writable_dir(d)\n        for d in set(get_lib_location_guesses(root=root, isolated=isolated))\n    )\n\n\ndef decide_user_install(\n    use_user_site: Optional[bool],\n    prefix_path: Optional[str] = None,\n    target_dir: Optional[str] = None,\n    root_path: Optional[str] = None,\n    isolated_mode: bool = False,\n) -> bool:\n    \"\"\"Determine whether to do a user install based on the input options.\n\n    If use_user_site is False, no additional checks are done.\n    If use_user_site is True, it is checked for compatibility with other\n    options.\n    If use_user_site is None, the default behaviour depends on the environment,\n    which is provided by the other arguments.\n    \"\"\"\n    # In some cases (config from tox), use_user_site can be set to an integer\n    # rather than a bool, which 'use_user_site is False' wouldn't catch.\n    if (use_user_site is not None) and (not use_user_site):\n        logger.debug(\"Non-user install by explicit request\")\n        return False\n\n    if use_user_site:\n        if prefix_path:\n            raise CommandError(\n                \"Can not combine '--user' and '--prefix' as they imply \"\n                \"different installation locations\"\n            )\n        if virtualenv_no_global():\n            raise InstallationError(\n                \"Can not perform a '--user' install. User site-packages \"\n                \"are not visible in this virtualenv.\"\n            )\n        logger.debug(\"User install by explicit request\")\n        return True\n\n    # If we are here, user installs have not been explicitly requested/avoided\n    assert use_user_site is None\n\n    # user install incompatible with --prefix/--target\n    if prefix_path or target_dir:\n        logger.debug(\"Non-user install due to --prefix or --target option\")\n        return False\n\n    # If user installs are not enabled, choose a non-user install\n    if not site.ENABLE_USER_SITE:\n        logger.debug(\"Non-user install because user site-packages disabled\")\n        return False\n\n    # If we have permission for a non-user install, do that,\n    # otherwise do a user install.\n    if site_packages_writable(root=root_path, isolated=isolated_mode):\n        logger.debug(\"Non-user install because site-packages writeable\")\n        return False\n\n    logger.info(\n        \"Defaulting to user installation because normal site-packages \"\n        \"is not writeable\"\n    )\n    return True\n\n\ndef reject_location_related_install_options(\n    requirements: List[InstallRequirement], options: Optional[List[str]]\n) -> None:\n    \"\"\"If any location-changing --install-option arguments were passed for\n    requirements or on the command-line, then show a deprecation warning.\n    \"\"\"\n\n    def format_options(option_names: Iterable[str]) -> List[str]:\n        return [\"--{}\".format(name.replace(\"_\", \"-\")) for name in option_names]\n\n    offenders = []\n\n    for requirement in requirements:\n        install_options = requirement.install_options\n        location_options = parse_distutils_args(install_options)\n        if location_options:\n            offenders.append(\n                \"{!r} from {}\".format(\n                    format_options(location_options.keys()), requirement\n                )\n            )\n\n    if options:\n        location_options = parse_distutils_args(options)\n        if location_options:\n            offenders.append(\n                \"{!r} from command line\".format(format_options(location_options.keys()))\n            )\n\n    if not offenders:\n        return\n\n    raise CommandError(\n        \"Location-changing options found in --install-option: {}.\"\n        \" This is unsupported, use pip-level options like --user,\"\n        \" --prefix, --root, and --target instead.\".format(\"; \".join(offenders))\n    )\n\n\ndef create_os_error_message(\n    error: OSError, show_traceback: bool, using_user_site: bool\n) -> str:\n    \"\"\"Format an error message for an OSError\n\n    It may occur anytime during the execution of the install command.\n    \"\"\"\n    parts = []\n\n    # Mention the error if we are not going to show a traceback\n    parts.append(\"Could not install packages due to an OSError\")\n    if not show_traceback:\n        parts.append(\": \")\n        parts.append(str(error))\n    else:\n        parts.append(\".\")\n\n    # Spilt the error indication from a helper message (if any)\n    parts[-1] += \"\\n\"\n\n    # Suggest useful actions to the user:\n    #  (1) using user site-packages or (2) verifying the permissions\n    if error.errno == errno.EACCES:\n        user_option_part = \"Consider using the `--user` option\"\n        permissions_part = \"Check the permissions\"\n\n        if not running_under_virtualenv() and not using_user_site:\n            parts.extend(\n                [\n                    user_option_part,\n                    \" or \",\n                    permissions_part.lower(),\n                ]\n            )\n        else:\n            parts.append(permissions_part)\n        parts.append(\".\\n\")\n\n    # Suggest the user to enable Long Paths if path length is\n    # more than 260\n    if (\n        WINDOWS\n        and error.errno == errno.ENOENT\n        and error.filename\n        and len(error.filename) > 260\n    ):\n        parts.append(\n            \"HINT: This error might have occurred since \"\n            \"this system does not have Windows Long Path \"\n            \"support enabled. You can find information on \"\n            \"how to enable this at \"\n            \"https://pip.pypa.io/warnings/enable-long-paths\\n\"\n        )\n\n    return \"\".join(parts).strip() + \"\\n\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/list.py",
    "content": "import json\nimport logging\nfrom optparse import Values\nfrom typing import TYPE_CHECKING, Generator, List, Optional, Sequence, Tuple, cast\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.req_command import IndexGroupCommand\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.exceptions import CommandError\nfrom pip._internal.index.collector import LinkCollector\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.metadata import BaseDistribution, get_environment\nfrom pip._internal.models.selection_prefs import SelectionPreferences\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.utils.compat import stdlib_pkgs\nfrom pip._internal.utils.misc import tabulate, write_output\n\nif TYPE_CHECKING:\n    from pip._internal.metadata.base import DistributionVersion\n\n    class _DistWithLatestInfo(BaseDistribution):\n        \"\"\"Give the distribution object a couple of extra fields.\n\n        These will be populated during ``get_outdated()``. This is dirty but\n        makes the rest of the code much cleaner.\n        \"\"\"\n\n        latest_version: DistributionVersion\n        latest_filetype: str\n\n    _ProcessedDists = Sequence[_DistWithLatestInfo]\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass ListCommand(IndexGroupCommand):\n    \"\"\"\n    List installed packages, including editables.\n\n    Packages are listed in a case-insensitive sorted order.\n    \"\"\"\n\n    ignore_require_venv = True\n    usage = \"\"\"\n      %prog [options]\"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"-o\",\n            \"--outdated\",\n            action=\"store_true\",\n            default=False,\n            help=\"List outdated packages\",\n        )\n        self.cmd_opts.add_option(\n            \"-u\",\n            \"--uptodate\",\n            action=\"store_true\",\n            default=False,\n            help=\"List uptodate packages\",\n        )\n        self.cmd_opts.add_option(\n            \"-e\",\n            \"--editable\",\n            action=\"store_true\",\n            default=False,\n            help=\"List editable projects.\",\n        )\n        self.cmd_opts.add_option(\n            \"-l\",\n            \"--local\",\n            action=\"store_true\",\n            default=False,\n            help=(\n                \"If in a virtualenv that has global access, do not list \"\n                \"globally-installed packages.\"\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"--user\",\n            dest=\"user\",\n            action=\"store_true\",\n            default=False,\n            help=\"Only output packages installed in user-site.\",\n        )\n        self.cmd_opts.add_option(cmdoptions.list_path())\n        self.cmd_opts.add_option(\n            \"--pre\",\n            action=\"store_true\",\n            default=False,\n            help=(\n                \"Include pre-release and development versions. By default, \"\n                \"pip only finds stable versions.\"\n            ),\n        )\n\n        self.cmd_opts.add_option(\n            \"--format\",\n            action=\"store\",\n            dest=\"list_format\",\n            default=\"columns\",\n            choices=(\"columns\", \"freeze\", \"json\"),\n            help=\"Select the output format among: columns (default), freeze, or json\",\n        )\n\n        self.cmd_opts.add_option(\n            \"--not-required\",\n            action=\"store_true\",\n            dest=\"not_required\",\n            help=\"List packages that are not dependencies of installed packages.\",\n        )\n\n        self.cmd_opts.add_option(\n            \"--exclude-editable\",\n            action=\"store_false\",\n            dest=\"include_editable\",\n            help=\"Exclude editable package from output.\",\n        )\n        self.cmd_opts.add_option(\n            \"--include-editable\",\n            action=\"store_true\",\n            dest=\"include_editable\",\n            help=\"Include editable package from output.\",\n            default=True,\n        )\n        self.cmd_opts.add_option(cmdoptions.list_exclude())\n        index_opts = cmdoptions.make_option_group(cmdoptions.index_group, self.parser)\n\n        self.parser.insert_option_group(0, index_opts)\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def _build_package_finder(\n        self, options: Values, session: PipSession\n    ) -> PackageFinder:\n        \"\"\"\n        Create a package finder appropriate to this list command.\n        \"\"\"\n        link_collector = LinkCollector.create(session, options=options)\n\n        # Pass allow_yanked=False to ignore yanked versions.\n        selection_prefs = SelectionPreferences(\n            allow_yanked=False,\n            allow_all_prereleases=options.pre,\n        )\n\n        return PackageFinder.create(\n            link_collector=link_collector,\n            selection_prefs=selection_prefs,\n        )\n\n    def run(self, options: Values, args: List[str]) -> int:\n        if options.outdated and options.uptodate:\n            raise CommandError(\"Options --outdated and --uptodate cannot be combined.\")\n\n        if options.outdated and options.list_format == \"freeze\":\n            raise CommandError(\n                \"List format 'freeze' can not be used with the --outdated option.\"\n            )\n\n        cmdoptions.check_list_path_option(options)\n\n        skip = set(stdlib_pkgs)\n        if options.excludes:\n            skip.update(canonicalize_name(n) for n in options.excludes)\n\n        packages: \"_ProcessedDists\" = [\n            cast(\"_DistWithLatestInfo\", d)\n            for d in get_environment(options.path).iter_installed_distributions(\n                local_only=options.local,\n                user_only=options.user,\n                editables_only=options.editable,\n                include_editables=options.include_editable,\n                skip=skip,\n            )\n        ]\n\n        # get_not_required must be called firstly in order to find and\n        # filter out all dependencies correctly. Otherwise a package\n        # can't be identified as requirement because some parent packages\n        # could be filtered out before.\n        if options.not_required:\n            packages = self.get_not_required(packages, options)\n\n        if options.outdated:\n            packages = self.get_outdated(packages, options)\n        elif options.uptodate:\n            packages = self.get_uptodate(packages, options)\n\n        self.output_package_listing(packages, options)\n        return SUCCESS\n\n    def get_outdated(\n        self, packages: \"_ProcessedDists\", options: Values\n    ) -> \"_ProcessedDists\":\n        return [\n            dist\n            for dist in self.iter_packages_latest_infos(packages, options)\n            if dist.latest_version > dist.version\n        ]\n\n    def get_uptodate(\n        self, packages: \"_ProcessedDists\", options: Values\n    ) -> \"_ProcessedDists\":\n        return [\n            dist\n            for dist in self.iter_packages_latest_infos(packages, options)\n            if dist.latest_version == dist.version\n        ]\n\n    def get_not_required(\n        self, packages: \"_ProcessedDists\", options: Values\n    ) -> \"_ProcessedDists\":\n        dep_keys = {\n            canonicalize_name(dep.name)\n            for dist in packages\n            for dep in (dist.iter_dependencies() or ())\n        }\n\n        # Create a set to remove duplicate packages, and cast it to a list\n        # to keep the return type consistent with get_outdated and\n        # get_uptodate\n        return list({pkg for pkg in packages if pkg.canonical_name not in dep_keys})\n\n    def iter_packages_latest_infos(\n        self, packages: \"_ProcessedDists\", options: Values\n    ) -> Generator[\"_DistWithLatestInfo\", None, None]:\n        with self._build_session(options) as session:\n            finder = self._build_package_finder(options, session)\n\n            def latest_info(\n                dist: \"_DistWithLatestInfo\",\n            ) -> Optional[\"_DistWithLatestInfo\"]:\n                all_candidates = finder.find_all_candidates(dist.canonical_name)\n                if not options.pre:\n                    # Remove prereleases\n                    all_candidates = [\n                        candidate\n                        for candidate in all_candidates\n                        if not candidate.version.is_prerelease\n                    ]\n\n                evaluator = finder.make_candidate_evaluator(\n                    project_name=dist.canonical_name,\n                )\n                best_candidate = evaluator.sort_best_candidate(all_candidates)\n                if best_candidate is None:\n                    return None\n\n                remote_version = best_candidate.version\n                if best_candidate.link.is_wheel:\n                    typ = \"wheel\"\n                else:\n                    typ = \"sdist\"\n                dist.latest_version = remote_version\n                dist.latest_filetype = typ\n                return dist\n\n            for dist in map(latest_info, packages):\n                if dist is not None:\n                    yield dist\n\n    def output_package_listing(\n        self, packages: \"_ProcessedDists\", options: Values\n    ) -> None:\n        packages = sorted(\n            packages,\n            key=lambda dist: dist.canonical_name,\n        )\n        if options.list_format == \"columns\" and packages:\n            data, header = format_for_columns(packages, options)\n            self.output_package_listing_columns(data, header)\n        elif options.list_format == \"freeze\":\n            for dist in packages:\n                if options.verbose >= 1:\n                    write_output(\n                        \"%s==%s (%s)\", dist.raw_name, dist.version, dist.location\n                    )\n                else:\n                    write_output(\"%s==%s\", dist.raw_name, dist.version)\n        elif options.list_format == \"json\":\n            write_output(format_for_json(packages, options))\n\n    def output_package_listing_columns(\n        self, data: List[List[str]], header: List[str]\n    ) -> None:\n        # insert the header first: we need to know the size of column names\n        if len(data) > 0:\n            data.insert(0, header)\n\n        pkg_strings, sizes = tabulate(data)\n\n        # Create and add a separator.\n        if len(data) > 0:\n            pkg_strings.insert(1, \" \".join(map(lambda x: \"-\" * x, sizes)))\n\n        for val in pkg_strings:\n            write_output(val)\n\n\ndef format_for_columns(\n    pkgs: \"_ProcessedDists\", options: Values\n) -> Tuple[List[List[str]], List[str]]:\n    \"\"\"\n    Convert the package data into something usable\n    by output_package_listing_columns.\n    \"\"\"\n    header = [\"Package\", \"Version\"]\n\n    running_outdated = options.outdated\n    if running_outdated:\n        header.extend([\"Latest\", \"Type\"])\n\n    has_editables = any(x.editable for x in pkgs)\n    if has_editables:\n        header.append(\"Editable project location\")\n\n    if options.verbose >= 1:\n        header.append(\"Location\")\n    if options.verbose >= 1:\n        header.append(\"Installer\")\n\n    data = []\n    for proj in pkgs:\n        # if we're working on the 'outdated' list, separate out the\n        # latest_version and type\n        row = [proj.raw_name, str(proj.version)]\n\n        if running_outdated:\n            row.append(str(proj.latest_version))\n            row.append(proj.latest_filetype)\n\n        if has_editables:\n            row.append(proj.editable_project_location or \"\")\n\n        if options.verbose >= 1:\n            row.append(proj.location or \"\")\n        if options.verbose >= 1:\n            row.append(proj.installer)\n\n        data.append(row)\n\n    return data, header\n\n\ndef format_for_json(packages: \"_ProcessedDists\", options: Values) -> str:\n    data = []\n    for dist in packages:\n        info = {\n            \"name\": dist.raw_name,\n            \"version\": str(dist.version),\n        }\n        if options.verbose >= 1:\n            info[\"location\"] = dist.location or \"\"\n            info[\"installer\"] = dist.installer\n        if options.outdated:\n            info[\"latest_version\"] = str(dist.latest_version)\n            info[\"latest_filetype\"] = dist.latest_filetype\n        editable_project_location = dist.editable_project_location\n        if editable_project_location:\n            info[\"editable_project_location\"] = editable_project_location\n        data.append(info)\n    return json.dumps(data)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/search.py",
    "content": "import logging\nimport shutil\nimport sys\nimport textwrap\nimport xmlrpc.client\nfrom collections import OrderedDict\nfrom optparse import Values\nfrom typing import TYPE_CHECKING, Dict, List, Optional\n\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.req_command import SessionCommandMixin\nfrom pip._internal.cli.status_codes import NO_MATCHES_FOUND, SUCCESS\nfrom pip._internal.exceptions import CommandError\nfrom pip._internal.metadata import get_default_environment\nfrom pip._internal.models.index import PyPI\nfrom pip._internal.network.xmlrpc import PipXmlrpcTransport\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import write_output\n\nif TYPE_CHECKING:\n    from typing import TypedDict\n\n    class TransformedHit(TypedDict):\n        name: str\n        summary: str\n        versions: List[str]\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass SearchCommand(Command, SessionCommandMixin):\n    \"\"\"Search for PyPI packages whose name or summary contains <query>.\"\"\"\n\n    usage = \"\"\"\n      %prog [options] <query>\"\"\"\n    ignore_require_venv = True\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"-i\",\n            \"--index\",\n            dest=\"index\",\n            metavar=\"URL\",\n            default=PyPI.pypi_url,\n            help=\"Base URL of Python Package Index (default %default)\",\n        )\n\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: List[str]) -> int:\n        if not args:\n            raise CommandError(\"Missing required argument (search query).\")\n        query = args\n        pypi_hits = self.search(query, options)\n        hits = transform_hits(pypi_hits)\n\n        terminal_width = None\n        if sys.stdout.isatty():\n            terminal_width = shutil.get_terminal_size()[0]\n\n        print_results(hits, terminal_width=terminal_width)\n        if pypi_hits:\n            return SUCCESS\n        return NO_MATCHES_FOUND\n\n    def search(self, query: List[str], options: Values) -> List[Dict[str, str]]:\n        index_url = options.index\n\n        session = self.get_default_session(options)\n\n        transport = PipXmlrpcTransport(index_url, session)\n        pypi = xmlrpc.client.ServerProxy(index_url, transport)\n        try:\n            hits = pypi.search({\"name\": query, \"summary\": query}, \"or\")\n        except xmlrpc.client.Fault as fault:\n            message = \"XMLRPC request failed [code: {code}]\\n{string}\".format(\n                code=fault.faultCode,\n                string=fault.faultString,\n            )\n            raise CommandError(message)\n        assert isinstance(hits, list)\n        return hits\n\n\ndef transform_hits(hits: List[Dict[str, str]]) -> List[\"TransformedHit\"]:\n    \"\"\"\n    The list from pypi is really a list of versions. We want a list of\n    packages with the list of versions stored inline. This converts the\n    list from pypi into one we can use.\n    \"\"\"\n    packages: Dict[str, \"TransformedHit\"] = OrderedDict()\n    for hit in hits:\n        name = hit[\"name\"]\n        summary = hit[\"summary\"]\n        version = hit[\"version\"]\n\n        if name not in packages.keys():\n            packages[name] = {\n                \"name\": name,\n                \"summary\": summary,\n                \"versions\": [version],\n            }\n        else:\n            packages[name][\"versions\"].append(version)\n\n            # if this is the highest version, replace summary and score\n            if version == highest_version(packages[name][\"versions\"]):\n                packages[name][\"summary\"] = summary\n\n    return list(packages.values())\n\n\ndef print_dist_installation_info(name: str, latest: str) -> None:\n    env = get_default_environment()\n    dist = env.get_distribution(name)\n    if dist is not None:\n        with indent_log():\n            if dist.version == latest:\n                write_output(\"INSTALLED: %s (latest)\", dist.version)\n            else:\n                write_output(\"INSTALLED: %s\", dist.version)\n                if parse_version(latest).pre:\n                    write_output(\n                        \"LATEST:    %s (pre-release; install\"\n                        \" with `pip install --pre`)\",\n                        latest,\n                    )\n                else:\n                    write_output(\"LATEST:    %s\", latest)\n\n\ndef print_results(\n    hits: List[\"TransformedHit\"],\n    name_column_width: Optional[int] = None,\n    terminal_width: Optional[int] = None,\n) -> None:\n    if not hits:\n        return\n    if name_column_width is None:\n        name_column_width = (\n            max(\n                [\n                    len(hit[\"name\"]) + len(highest_version(hit.get(\"versions\", [\"-\"])))\n                    for hit in hits\n                ]\n            )\n            + 4\n        )\n\n    for hit in hits:\n        name = hit[\"name\"]\n        summary = hit[\"summary\"] or \"\"\n        latest = highest_version(hit.get(\"versions\", [\"-\"]))\n        if terminal_width is not None:\n            target_width = terminal_width - name_column_width - 5\n            if target_width > 10:\n                # wrap and indent summary to fit terminal\n                summary_lines = textwrap.wrap(summary, target_width)\n                summary = (\"\\n\" + \" \" * (name_column_width + 3)).join(summary_lines)\n\n        name_latest = f\"{name} ({latest})\"\n        line = f\"{name_latest:{name_column_width}} - {summary}\"\n        try:\n            write_output(line)\n            print_dist_installation_info(name, latest)\n        except UnicodeEncodeError:\n            pass\n\n\ndef highest_version(versions: List[str]) -> str:\n    return max(versions, key=parse_version)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/show.py",
    "content": "import logging\nfrom optparse import Values\nfrom typing import Generator, Iterable, Iterator, List, NamedTuple, Optional\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.status_codes import ERROR, SUCCESS\nfrom pip._internal.metadata import BaseDistribution, get_default_environment\nfrom pip._internal.utils.misc import write_output\n\nlogger = logging.getLogger(__name__)\n\n\nclass ShowCommand(Command):\n    \"\"\"\n    Show information about one or more installed packages.\n\n    The output is in RFC-compliant mail header format.\n    \"\"\"\n\n    usage = \"\"\"\n      %prog [options] <package> ...\"\"\"\n    ignore_require_venv = True\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"-f\",\n            \"--files\",\n            dest=\"files\",\n            action=\"store_true\",\n            default=False,\n            help=\"Show the full list of installed files for each package.\",\n        )\n\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: List[str]) -> int:\n        if not args:\n            logger.warning(\"ERROR: Please provide a package name or names.\")\n            return ERROR\n        query = args\n\n        results = search_packages_info(query)\n        if not print_results(\n            results, list_files=options.files, verbose=options.verbose\n        ):\n            return ERROR\n        return SUCCESS\n\n\nclass _PackageInfo(NamedTuple):\n    name: str\n    version: str\n    location: str\n    requires: List[str]\n    required_by: List[str]\n    installer: str\n    metadata_version: str\n    classifiers: List[str]\n    summary: str\n    homepage: str\n    project_urls: List[str]\n    author: str\n    author_email: str\n    license: str\n    entry_points: List[str]\n    files: Optional[List[str]]\n\n\ndef search_packages_info(query: List[str]) -> Generator[_PackageInfo, None, None]:\n    \"\"\"\n    Gather details from installed distributions. Print distribution name,\n    version, location, and installed files. Installed files requires a\n    pip generated 'installed-files.txt' in the distributions '.egg-info'\n    directory.\n    \"\"\"\n    env = get_default_environment()\n\n    installed = {dist.canonical_name: dist for dist in env.iter_all_distributions()}\n    query_names = [canonicalize_name(name) for name in query]\n    missing = sorted(\n        [name for name, pkg in zip(query, query_names) if pkg not in installed]\n    )\n    if missing:\n        logger.warning(\"Package(s) not found: %s\", \", \".join(missing))\n\n    def _get_requiring_packages(current_dist: BaseDistribution) -> Iterator[str]:\n        return (\n            dist.metadata[\"Name\"] or \"UNKNOWN\"\n            for dist in installed.values()\n            if current_dist.canonical_name\n            in {canonicalize_name(d.name) for d in dist.iter_dependencies()}\n        )\n\n    for query_name in query_names:\n        try:\n            dist = installed[query_name]\n        except KeyError:\n            continue\n\n        requires = sorted((req.name for req in dist.iter_dependencies()), key=str.lower)\n        required_by = sorted(_get_requiring_packages(dist), key=str.lower)\n\n        try:\n            entry_points_text = dist.read_text(\"entry_points.txt\")\n            entry_points = entry_points_text.splitlines(keepends=False)\n        except FileNotFoundError:\n            entry_points = []\n\n        files_iter = dist.iter_declared_entries()\n        if files_iter is None:\n            files: Optional[List[str]] = None\n        else:\n            files = sorted(files_iter)\n\n        metadata = dist.metadata\n\n        yield _PackageInfo(\n            name=dist.raw_name,\n            version=str(dist.version),\n            location=dist.location or \"\",\n            requires=requires,\n            required_by=required_by,\n            installer=dist.installer,\n            metadata_version=dist.metadata_version or \"\",\n            classifiers=metadata.get_all(\"Classifier\", []),\n            summary=metadata.get(\"Summary\", \"\"),\n            homepage=metadata.get(\"Home-page\", \"\"),\n            project_urls=metadata.get_all(\"Project-URL\", []),\n            author=metadata.get(\"Author\", \"\"),\n            author_email=metadata.get(\"Author-email\", \"\"),\n            license=metadata.get(\"License\", \"\"),\n            entry_points=entry_points,\n            files=files,\n        )\n\n\ndef print_results(\n    distributions: Iterable[_PackageInfo],\n    list_files: bool,\n    verbose: bool,\n) -> bool:\n    \"\"\"\n    Print the information from installed distributions found.\n    \"\"\"\n    results_printed = False\n    for i, dist in enumerate(distributions):\n        results_printed = True\n        if i > 0:\n            write_output(\"---\")\n\n        write_output(\"Name: %s\", dist.name)\n        write_output(\"Version: %s\", dist.version)\n        write_output(\"Summary: %s\", dist.summary)\n        write_output(\"Home-page: %s\", dist.homepage)\n        write_output(\"Author: %s\", dist.author)\n        write_output(\"Author-email: %s\", dist.author_email)\n        write_output(\"License: %s\", dist.license)\n        write_output(\"Location: %s\", dist.location)\n        write_output(\"Requires: %s\", \", \".join(dist.requires))\n        write_output(\"Required-by: %s\", \", \".join(dist.required_by))\n\n        if verbose:\n            write_output(\"Metadata-Version: %s\", dist.metadata_version)\n            write_output(\"Installer: %s\", dist.installer)\n            write_output(\"Classifiers:\")\n            for classifier in dist.classifiers:\n                write_output(\"  %s\", classifier)\n            write_output(\"Entry-points:\")\n            for entry in dist.entry_points:\n                write_output(\"  %s\", entry.strip())\n            write_output(\"Project-URLs:\")\n            for project_url in dist.project_urls:\n                write_output(\"  %s\", project_url)\n        if list_files:\n            write_output(\"Files:\")\n            if dist.files is None:\n                write_output(\"Cannot locate RECORD or installed-files.txt\")\n            else:\n                for line in dist.files:\n                    write_output(\"  %s\", line.strip())\n    return results_printed\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/uninstall.py",
    "content": "import logging\nfrom optparse import Values\nfrom typing import List\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.base_command import Command\nfrom pip._internal.cli.req_command import SessionCommandMixin, warn_if_run_as_root\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.req import parse_requirements\nfrom pip._internal.req.constructors import (\n    install_req_from_line,\n    install_req_from_parsed_requirement,\n)\nfrom pip._internal.utils.misc import protect_pip_from_modification_on_windows\n\nlogger = logging.getLogger(__name__)\n\n\nclass UninstallCommand(Command, SessionCommandMixin):\n    \"\"\"\n    Uninstall packages.\n\n    pip is able to uninstall most installed packages. Known exceptions are:\n\n    - Pure distutils packages installed with ``python setup.py install``, which\n      leave behind no metadata to determine what files were installed.\n    - Script wrappers installed by ``python setup.py develop``.\n    \"\"\"\n\n    usage = \"\"\"\n      %prog [options] <package> ...\n      %prog [options] -r <requirements file> ...\"\"\"\n\n    def add_options(self) -> None:\n        self.cmd_opts.add_option(\n            \"-r\",\n            \"--requirement\",\n            dest=\"requirements\",\n            action=\"append\",\n            default=[],\n            metavar=\"file\",\n            help=(\n                \"Uninstall all the packages listed in the given requirements \"\n                \"file.  This option can be used multiple times.\"\n            ),\n        )\n        self.cmd_opts.add_option(\n            \"-y\",\n            \"--yes\",\n            dest=\"yes\",\n            action=\"store_true\",\n            help=\"Don't ask for confirmation of uninstall deletions.\",\n        )\n        self.cmd_opts.add_option(cmdoptions.root_user_action())\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    def run(self, options: Values, args: List[str]) -> int:\n        session = self.get_default_session(options)\n\n        reqs_to_uninstall = {}\n        for name in args:\n            req = install_req_from_line(\n                name,\n                isolated=options.isolated_mode,\n            )\n            if req.name:\n                reqs_to_uninstall[canonicalize_name(req.name)] = req\n            else:\n                logger.warning(\n                    \"Invalid requirement: %r ignored -\"\n                    \" the uninstall command expects named\"\n                    \" requirements.\",\n                    name,\n                )\n        for filename in options.requirements:\n            for parsed_req in parse_requirements(\n                filename, options=options, session=session\n            ):\n                req = install_req_from_parsed_requirement(\n                    parsed_req, isolated=options.isolated_mode\n                )\n                if req.name:\n                    reqs_to_uninstall[canonicalize_name(req.name)] = req\n        if not reqs_to_uninstall:\n            raise InstallationError(\n                f\"You must give at least one requirement to {self.name} (see \"\n                f'\"pip help {self.name}\")'\n            )\n\n        protect_pip_from_modification_on_windows(\n            modifying_pip=\"pip\" in reqs_to_uninstall\n        )\n\n        for req in reqs_to_uninstall.values():\n            uninstall_pathset = req.uninstall(\n                auto_confirm=options.yes,\n                verbose=self.verbosity > 0,\n            )\n            if uninstall_pathset:\n                uninstall_pathset.commit()\n        if options.root_user_action == \"warn\":\n            warn_if_run_as_root()\n        return SUCCESS\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/commands/wheel.py",
    "content": "import logging\nimport os\nimport shutil\nfrom optparse import Values\nfrom typing import List\n\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.cli.req_command import RequirementCommand, with_cleanup\nfrom pip._internal.cli.status_codes import SUCCESS\nfrom pip._internal.exceptions import CommandError\nfrom pip._internal.operations.build.build_tracker import get_build_tracker\nfrom pip._internal.req.req_install import (\n    InstallRequirement,\n    LegacySetupPyOptionsCheckMode,\n    check_legacy_setup_py_options,\n)\nfrom pip._internal.utils.deprecation import deprecated\nfrom pip._internal.utils.misc import ensure_dir, normalize_path\nfrom pip._internal.utils.temp_dir import TempDirectory\nfrom pip._internal.wheel_builder import build, should_build_for_wheel_command\n\nlogger = logging.getLogger(__name__)\n\n\nclass WheelCommand(RequirementCommand):\n    \"\"\"\n    Build Wheel archives for your requirements and dependencies.\n\n    Wheel is a built-package format, and offers the advantage of not\n    recompiling your software during every install. For more details, see the\n    wheel docs: https://wheel.readthedocs.io/en/latest/\n\n    'pip wheel' uses the build system interface as described here:\n    https://pip.pypa.io/en/stable/reference/build-system/\n\n    \"\"\"\n\n    usage = \"\"\"\n      %prog [options] <requirement specifier> ...\n      %prog [options] -r <requirements file> ...\n      %prog [options] [-e] <vcs project url> ...\n      %prog [options] [-e] <local project path> ...\n      %prog [options] <archive url/path> ...\"\"\"\n\n    def add_options(self) -> None:\n\n        self.cmd_opts.add_option(\n            \"-w\",\n            \"--wheel-dir\",\n            dest=\"wheel_dir\",\n            metavar=\"dir\",\n            default=os.curdir,\n            help=(\n                \"Build wheels into <dir>, where the default is the \"\n                \"current working directory.\"\n            ),\n        )\n        self.cmd_opts.add_option(cmdoptions.no_binary())\n        self.cmd_opts.add_option(cmdoptions.only_binary())\n        self.cmd_opts.add_option(cmdoptions.prefer_binary())\n        self.cmd_opts.add_option(cmdoptions.no_build_isolation())\n        self.cmd_opts.add_option(cmdoptions.use_pep517())\n        self.cmd_opts.add_option(cmdoptions.no_use_pep517())\n        self.cmd_opts.add_option(cmdoptions.check_build_deps())\n        self.cmd_opts.add_option(cmdoptions.constraints())\n        self.cmd_opts.add_option(cmdoptions.editable())\n        self.cmd_opts.add_option(cmdoptions.requirements())\n        self.cmd_opts.add_option(cmdoptions.src())\n        self.cmd_opts.add_option(cmdoptions.ignore_requires_python())\n        self.cmd_opts.add_option(cmdoptions.no_deps())\n        self.cmd_opts.add_option(cmdoptions.progress_bar())\n\n        self.cmd_opts.add_option(\n            \"--no-verify\",\n            dest=\"no_verify\",\n            action=\"store_true\",\n            default=False,\n            help=\"Don't verify if built wheel is valid.\",\n        )\n\n        self.cmd_opts.add_option(cmdoptions.config_settings())\n        self.cmd_opts.add_option(cmdoptions.build_options())\n        self.cmd_opts.add_option(cmdoptions.global_options())\n\n        self.cmd_opts.add_option(\n            \"--pre\",\n            action=\"store_true\",\n            default=False,\n            help=(\n                \"Include pre-release and development versions. By default, \"\n                \"pip only finds stable versions.\"\n            ),\n        )\n\n        self.cmd_opts.add_option(cmdoptions.require_hashes())\n\n        index_opts = cmdoptions.make_option_group(\n            cmdoptions.index_group,\n            self.parser,\n        )\n\n        self.parser.insert_option_group(0, index_opts)\n        self.parser.insert_option_group(0, self.cmd_opts)\n\n    @with_cleanup\n    def run(self, options: Values, args: List[str]) -> int:\n        session = self.get_default_session(options)\n\n        finder = self._build_package_finder(options, session)\n        wheel_cache = WheelCache(options.cache_dir, options.format_control)\n\n        options.wheel_dir = normalize_path(options.wheel_dir)\n        ensure_dir(options.wheel_dir)\n\n        build_tracker = self.enter_context(get_build_tracker())\n\n        directory = TempDirectory(\n            delete=not options.no_clean,\n            kind=\"wheel\",\n            globally_managed=True,\n        )\n\n        reqs = self.get_requirements(args, options, finder, session)\n        check_legacy_setup_py_options(\n            options, reqs, LegacySetupPyOptionsCheckMode.WHEEL\n        )\n\n        if \"no-binary-enable-wheel-cache\" in options.features_enabled:\n            # TODO: remove format_control from WheelCache when the deprecation cycle\n            # is over\n            wheel_cache = WheelCache(options.cache_dir)\n        else:\n            if options.format_control.no_binary:\n                deprecated(\n                    reason=(\n                        \"--no-binary currently disables reading from \"\n                        \"the cache of locally built wheels. In the future \"\n                        \"--no-binary will not influence the wheel cache.\"\n                    ),\n                    replacement=\"to use the --no-cache-dir option\",\n                    feature_flag=\"no-binary-enable-wheel-cache\",\n                    issue=11453,\n                    gone_in=\"23.1\",\n                )\n            wheel_cache = WheelCache(options.cache_dir, options.format_control)\n\n        preparer = self.make_requirement_preparer(\n            temp_build_dir=directory,\n            options=options,\n            build_tracker=build_tracker,\n            session=session,\n            finder=finder,\n            download_dir=options.wheel_dir,\n            use_user_site=False,\n            verbosity=self.verbosity,\n        )\n\n        resolver = self.make_resolver(\n            preparer=preparer,\n            finder=finder,\n            options=options,\n            wheel_cache=wheel_cache,\n            ignore_requires_python=options.ignore_requires_python,\n            use_pep517=options.use_pep517,\n        )\n\n        self.trace_basic_info(finder)\n\n        requirement_set = resolver.resolve(reqs, check_supported_wheels=True)\n\n        reqs_to_build: List[InstallRequirement] = []\n        for req in requirement_set.requirements.values():\n            if req.is_wheel:\n                preparer.save_linked_requirement(req)\n            elif should_build_for_wheel_command(req):\n                reqs_to_build.append(req)\n\n        # build wheels\n        build_successes, build_failures = build(\n            reqs_to_build,\n            wheel_cache=wheel_cache,\n            verify=(not options.no_verify),\n            build_options=options.build_options or [],\n            global_options=options.global_options or [],\n        )\n        for req in build_successes:\n            assert req.link and req.link.is_wheel\n            assert req.local_file_path\n            # copy from cache to target directory\n            try:\n                shutil.copy(req.local_file_path, options.wheel_dir)\n            except OSError as e:\n                logger.warning(\n                    \"Building wheel for %s failed: %s\",\n                    req.name,\n                    e,\n                )\n                build_failures.append(req)\n        if len(build_failures) != 0:\n            raise CommandError(\"Failed to build one or more wheels\")\n\n        return SUCCESS\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/configuration.py",
    "content": "\"\"\"Configuration management setup\n\nSome terminology:\n- name\n  As written in config files.\n- value\n  Value associated with a name\n- key\n  Name combined with it's section (section.name)\n- variant\n  A single word describing where the configuration key-value pair came from\n\"\"\"\n\nimport configparser\nimport locale\nimport os\nimport sys\nfrom typing import Any, Dict, Iterable, List, NewType, Optional, Tuple\n\nfrom pip._internal.exceptions import (\n    ConfigurationError,\n    ConfigurationFileCouldNotBeLoaded,\n)\nfrom pip._internal.utils import appdirs\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.logging import getLogger\nfrom pip._internal.utils.misc import ensure_dir, enum\n\nRawConfigParser = configparser.RawConfigParser  # Shorthand\nKind = NewType(\"Kind\", str)\n\nCONFIG_BASENAME = \"pip.ini\" if WINDOWS else \"pip.conf\"\nENV_NAMES_IGNORED = \"version\", \"help\"\n\n# The kinds of configurations there are.\nkinds = enum(\n    USER=\"user\",  # User Specific\n    GLOBAL=\"global\",  # System Wide\n    SITE=\"site\",  # [Virtual] Environment Specific\n    ENV=\"env\",  # from PIP_CONFIG_FILE\n    ENV_VAR=\"env-var\",  # from Environment Variables\n)\nOVERRIDE_ORDER = kinds.GLOBAL, kinds.USER, kinds.SITE, kinds.ENV, kinds.ENV_VAR\nVALID_LOAD_ONLY = kinds.USER, kinds.GLOBAL, kinds.SITE\n\nlogger = getLogger(__name__)\n\n\n# NOTE: Maybe use the optionx attribute to normalize keynames.\ndef _normalize_name(name: str) -> str:\n    \"\"\"Make a name consistent regardless of source (environment or file)\"\"\"\n    name = name.lower().replace(\"_\", \"-\")\n    if name.startswith(\"--\"):\n        name = name[2:]  # only prefer long opts\n    return name\n\n\ndef _disassemble_key(name: str) -> List[str]:\n    if \".\" not in name:\n        error_message = (\n            \"Key does not contain dot separated section and key. \"\n            \"Perhaps you wanted to use 'global.{}' instead?\"\n        ).format(name)\n        raise ConfigurationError(error_message)\n    return name.split(\".\", 1)\n\n\ndef get_configuration_files() -> Dict[Kind, List[str]]:\n    global_config_files = [\n        os.path.join(path, CONFIG_BASENAME) for path in appdirs.site_config_dirs(\"pip\")\n    ]\n\n    site_config_file = os.path.join(sys.prefix, CONFIG_BASENAME)\n    legacy_config_file = os.path.join(\n        os.path.expanduser(\"~\"),\n        \"pip\" if WINDOWS else \".pip\",\n        CONFIG_BASENAME,\n    )\n    new_config_file = os.path.join(appdirs.user_config_dir(\"pip\"), CONFIG_BASENAME)\n    return {\n        kinds.GLOBAL: global_config_files,\n        kinds.SITE: [site_config_file],\n        kinds.USER: [legacy_config_file, new_config_file],\n    }\n\n\nclass Configuration:\n    \"\"\"Handles management of configuration.\n\n    Provides an interface to accessing and managing configuration files.\n\n    This class converts provides an API that takes \"section.key-name\" style\n    keys and stores the value associated with it as \"key-name\" under the\n    section \"section\".\n\n    This allows for a clean interface wherein the both the section and the\n    key-name are preserved in an easy to manage form in the configuration files\n    and the data stored is also nice.\n    \"\"\"\n\n    def __init__(self, isolated: bool, load_only: Optional[Kind] = None) -> None:\n        super().__init__()\n\n        if load_only is not None and load_only not in VALID_LOAD_ONLY:\n            raise ConfigurationError(\n                \"Got invalid value for load_only - should be one of {}\".format(\n                    \", \".join(map(repr, VALID_LOAD_ONLY))\n                )\n            )\n        self.isolated = isolated\n        self.load_only = load_only\n\n        # Because we keep track of where we got the data from\n        self._parsers: Dict[Kind, List[Tuple[str, RawConfigParser]]] = {\n            variant: [] for variant in OVERRIDE_ORDER\n        }\n        self._config: Dict[Kind, Dict[str, Any]] = {\n            variant: {} for variant in OVERRIDE_ORDER\n        }\n        self._modified_parsers: List[Tuple[str, RawConfigParser]] = []\n\n    def load(self) -> None:\n        \"\"\"Loads configuration from configuration files and environment\"\"\"\n        self._load_config_files()\n        if not self.isolated:\n            self._load_environment_vars()\n\n    def get_file_to_edit(self) -> Optional[str]:\n        \"\"\"Returns the file with highest priority in configuration\"\"\"\n        assert self.load_only is not None, \"Need to be specified a file to be editing\"\n\n        try:\n            return self._get_parser_to_modify()[0]\n        except IndexError:\n            return None\n\n    def items(self) -> Iterable[Tuple[str, Any]]:\n        \"\"\"Returns key-value pairs like dict.items() representing the loaded\n        configuration\n        \"\"\"\n        return self._dictionary.items()\n\n    def get_value(self, key: str) -> Any:\n        \"\"\"Get a value from the configuration.\"\"\"\n        orig_key = key\n        key = _normalize_name(key)\n        try:\n            return self._dictionary[key]\n        except KeyError:\n            # disassembling triggers a more useful error message than simply\n            # \"No such key\" in the case that the key isn't in the form command.option\n            _disassemble_key(key)\n            raise ConfigurationError(f\"No such key - {orig_key}\")\n\n    def set_value(self, key: str, value: Any) -> None:\n        \"\"\"Modify a value in the configuration.\"\"\"\n        key = _normalize_name(key)\n        self._ensure_have_load_only()\n\n        assert self.load_only\n        fname, parser = self._get_parser_to_modify()\n\n        if parser is not None:\n            section, name = _disassemble_key(key)\n\n            # Modify the parser and the configuration\n            if not parser.has_section(section):\n                parser.add_section(section)\n            parser.set(section, name, value)\n\n        self._config[self.load_only][key] = value\n        self._mark_as_modified(fname, parser)\n\n    def unset_value(self, key: str) -> None:\n        \"\"\"Unset a value in the configuration.\"\"\"\n        orig_key = key\n        key = _normalize_name(key)\n        self._ensure_have_load_only()\n\n        assert self.load_only\n        if key not in self._config[self.load_only]:\n            raise ConfigurationError(f\"No such key - {orig_key}\")\n\n        fname, parser = self._get_parser_to_modify()\n\n        if parser is not None:\n            section, name = _disassemble_key(key)\n            if not (\n                parser.has_section(section) and parser.remove_option(section, name)\n            ):\n                # The option was not removed.\n                raise ConfigurationError(\n                    \"Fatal Internal error [id=1]. Please report as a bug.\"\n                )\n\n            # The section may be empty after the option was removed.\n            if not parser.items(section):\n                parser.remove_section(section)\n            self._mark_as_modified(fname, parser)\n\n        del self._config[self.load_only][key]\n\n    def save(self) -> None:\n        \"\"\"Save the current in-memory state.\"\"\"\n        self._ensure_have_load_only()\n\n        for fname, parser in self._modified_parsers:\n            logger.info(\"Writing to %s\", fname)\n\n            # Ensure directory exists.\n            ensure_dir(os.path.dirname(fname))\n\n            with open(fname, \"w\") as f:\n                parser.write(f)\n\n    #\n    # Private routines\n    #\n\n    def _ensure_have_load_only(self) -> None:\n        if self.load_only is None:\n            raise ConfigurationError(\"Needed a specific file to be modifying.\")\n        logger.debug(\"Will be working with %s variant only\", self.load_only)\n\n    @property\n    def _dictionary(self) -> Dict[str, Any]:\n        \"\"\"A dictionary representing the loaded configuration.\"\"\"\n        # NOTE: Dictionaries are not populated if not loaded. So, conditionals\n        #       are not needed here.\n        retval = {}\n\n        for variant in OVERRIDE_ORDER:\n            retval.update(self._config[variant])\n\n        return retval\n\n    def _load_config_files(self) -> None:\n        \"\"\"Loads configuration from configuration files\"\"\"\n        config_files = dict(self.iter_config_files())\n        if config_files[kinds.ENV][0:1] == [os.devnull]:\n            logger.debug(\n                \"Skipping loading configuration files due to \"\n                \"environment's PIP_CONFIG_FILE being os.devnull\"\n            )\n            return\n\n        for variant, files in config_files.items():\n            for fname in files:\n                # If there's specific variant set in `load_only`, load only\n                # that variant, not the others.\n                if self.load_only is not None and variant != self.load_only:\n                    logger.debug(\"Skipping file '%s' (variant: %s)\", fname, variant)\n                    continue\n\n                parser = self._load_file(variant, fname)\n\n                # Keeping track of the parsers used\n                self._parsers[variant].append((fname, parser))\n\n    def _load_file(self, variant: Kind, fname: str) -> RawConfigParser:\n        logger.verbose(\"For variant '%s', will try loading '%s'\", variant, fname)\n        parser = self._construct_parser(fname)\n\n        for section in parser.sections():\n            items = parser.items(section)\n            self._config[variant].update(self._normalized_keys(section, items))\n\n        return parser\n\n    def _construct_parser(self, fname: str) -> RawConfigParser:\n        parser = configparser.RawConfigParser()\n        # If there is no such file, don't bother reading it but create the\n        # parser anyway, to hold the data.\n        # Doing this is useful when modifying and saving files, where we don't\n        # need to construct a parser.\n        if os.path.exists(fname):\n            locale_encoding = locale.getpreferredencoding(False)\n            try:\n                parser.read(fname, encoding=locale_encoding)\n            except UnicodeDecodeError:\n                # See https://github.com/pypa/pip/issues/4963\n                raise ConfigurationFileCouldNotBeLoaded(\n                    reason=f\"contains invalid {locale_encoding} characters\",\n                    fname=fname,\n                )\n            except configparser.Error as error:\n                # See https://github.com/pypa/pip/issues/4893\n                raise ConfigurationFileCouldNotBeLoaded(error=error)\n        return parser\n\n    def _load_environment_vars(self) -> None:\n        \"\"\"Loads configuration from environment variables\"\"\"\n        self._config[kinds.ENV_VAR].update(\n            self._normalized_keys(\":env:\", self.get_environ_vars())\n        )\n\n    def _normalized_keys(\n        self, section: str, items: Iterable[Tuple[str, Any]]\n    ) -> Dict[str, Any]:\n        \"\"\"Normalizes items to construct a dictionary with normalized keys.\n\n        This routine is where the names become keys and are made the same\n        regardless of source - configuration files or environment.\n        \"\"\"\n        normalized = {}\n        for name, val in items:\n            key = section + \".\" + _normalize_name(name)\n            normalized[key] = val\n        return normalized\n\n    def get_environ_vars(self) -> Iterable[Tuple[str, str]]:\n        \"\"\"Returns a generator with all environmental vars with prefix PIP_\"\"\"\n        for key, val in os.environ.items():\n            if key.startswith(\"PIP_\"):\n                name = key[4:].lower()\n                if name not in ENV_NAMES_IGNORED:\n                    yield name, val\n\n    # XXX: This is patched in the tests.\n    def iter_config_files(self) -> Iterable[Tuple[Kind, List[str]]]:\n        \"\"\"Yields variant and configuration files associated with it.\n\n        This should be treated like items of a dictionary.\n        \"\"\"\n        # SMELL: Move the conditions out of this function\n\n        # environment variables have the lowest priority\n        config_file = os.environ.get(\"PIP_CONFIG_FILE\", None)\n        if config_file is not None:\n            yield kinds.ENV, [config_file]\n        else:\n            yield kinds.ENV, []\n\n        config_files = get_configuration_files()\n\n        # at the base we have any global configuration\n        yield kinds.GLOBAL, config_files[kinds.GLOBAL]\n\n        # per-user configuration next\n        should_load_user_config = not self.isolated and not (\n            config_file and os.path.exists(config_file)\n        )\n        if should_load_user_config:\n            # The legacy config file is overridden by the new config file\n            yield kinds.USER, config_files[kinds.USER]\n\n        # finally virtualenv configuration first trumping others\n        yield kinds.SITE, config_files[kinds.SITE]\n\n    def get_values_in_config(self, variant: Kind) -> Dict[str, Any]:\n        \"\"\"Get values present in a config file\"\"\"\n        return self._config[variant]\n\n    def _get_parser_to_modify(self) -> Tuple[str, RawConfigParser]:\n        # Determine which parser to modify\n        assert self.load_only\n        parsers = self._parsers[self.load_only]\n        if not parsers:\n            # This should not happen if everything works correctly.\n            raise ConfigurationError(\n                \"Fatal Internal error [id=2]. Please report as a bug.\"\n            )\n\n        # Use the highest priority parser.\n        return parsers[-1]\n\n    # XXX: This is patched in the tests.\n    def _mark_as_modified(self, fname: str, parser: RawConfigParser) -> None:\n        file_parser_tuple = (fname, parser)\n        if file_parser_tuple not in self._modified_parsers:\n            self._modified_parsers.append(file_parser_tuple)\n\n    def __repr__(self) -> str:\n        return f\"{self.__class__.__name__}({self._dictionary!r})\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/distributions/__init__.py",
    "content": "from pip._internal.distributions.base import AbstractDistribution\nfrom pip._internal.distributions.sdist import SourceDistribution\nfrom pip._internal.distributions.wheel import WheelDistribution\nfrom pip._internal.req.req_install import InstallRequirement\n\n\ndef make_distribution_for_install_requirement(\n    install_req: InstallRequirement,\n) -> AbstractDistribution:\n    \"\"\"Returns a Distribution for the given InstallRequirement\"\"\"\n    # Editable requirements will always be source distributions. They use the\n    # legacy logic until we create a modern standard for them.\n    if install_req.editable:\n        return SourceDistribution(install_req)\n\n    # If it's a wheel, it's a WheelDistribution\n    if install_req.is_wheel:\n        return WheelDistribution(install_req)\n\n    # Otherwise, a SourceDistribution\n    return SourceDistribution(install_req)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/distributions/base.py",
    "content": "import abc\n\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.metadata.base import BaseDistribution\nfrom pip._internal.req import InstallRequirement\n\n\nclass AbstractDistribution(metaclass=abc.ABCMeta):\n    \"\"\"A base class for handling installable artifacts.\n\n    The requirements for anything installable are as follows:\n\n     - we must be able to determine the requirement name\n       (or we can't correctly handle the non-upgrade case).\n\n     - for packages with setup requirements, we must also be able\n       to determine their requirements without installing additional\n       packages (for the same reason as run-time dependencies)\n\n     - we must be able to create a Distribution object exposing the\n       above metadata.\n    \"\"\"\n\n    def __init__(self, req: InstallRequirement) -> None:\n        super().__init__()\n        self.req = req\n\n    @abc.abstractmethod\n    def get_metadata_distribution(self) -> BaseDistribution:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def prepare_distribution_metadata(\n        self,\n        finder: PackageFinder,\n        build_isolation: bool,\n        check_build_deps: bool,\n    ) -> None:\n        raise NotImplementedError()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/distributions/installed.py",
    "content": "from pip._internal.distributions.base import AbstractDistribution\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.metadata import BaseDistribution\n\n\nclass InstalledDistribution(AbstractDistribution):\n    \"\"\"Represents an installed package.\n\n    This does not need any preparation as the required information has already\n    been computed.\n    \"\"\"\n\n    def get_metadata_distribution(self) -> BaseDistribution:\n        assert self.req.satisfied_by is not None, \"not actually installed\"\n        return self.req.satisfied_by\n\n    def prepare_distribution_metadata(\n        self,\n        finder: PackageFinder,\n        build_isolation: bool,\n        check_build_deps: bool,\n    ) -> None:\n        pass\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/distributions/sdist.py",
    "content": "import logging\nfrom typing import Iterable, Set, Tuple\n\nfrom pip._internal.build_env import BuildEnvironment\nfrom pip._internal.distributions.base import AbstractDistribution\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.metadata import BaseDistribution\nfrom pip._internal.utils.subprocess import runner_with_spinner_message\n\nlogger = logging.getLogger(__name__)\n\n\nclass SourceDistribution(AbstractDistribution):\n    \"\"\"Represents a source distribution.\n\n    The preparation step for these needs metadata for the packages to be\n    generated, either using PEP 517 or using the legacy `setup.py egg_info`.\n    \"\"\"\n\n    def get_metadata_distribution(self) -> BaseDistribution:\n        return self.req.get_dist()\n\n    def prepare_distribution_metadata(\n        self,\n        finder: PackageFinder,\n        build_isolation: bool,\n        check_build_deps: bool,\n    ) -> None:\n        # Load pyproject.toml, to determine whether PEP 517 is to be used\n        self.req.load_pyproject_toml()\n\n        # Set up the build isolation, if this requirement should be isolated\n        should_isolate = self.req.use_pep517 and build_isolation\n        if should_isolate:\n            # Setup an isolated environment and install the build backend static\n            # requirements in it.\n            self._prepare_build_backend(finder)\n            # Check that if the requirement is editable, it either supports PEP 660 or\n            # has a setup.py or a setup.cfg. This cannot be done earlier because we need\n            # to setup the build backend to verify it supports build_editable, nor can\n            # it be done later, because we want to avoid installing build requirements\n            # needlessly. Doing it here also works around setuptools generating\n            # UNKNOWN.egg-info when running get_requires_for_build_wheel on a directory\n            # without setup.py nor setup.cfg.\n            self.req.isolated_editable_sanity_check()\n            # Install the dynamic build requirements.\n            self._install_build_reqs(finder)\n        # Check if the current environment provides build dependencies\n        should_check_deps = self.req.use_pep517 and check_build_deps\n        if should_check_deps:\n            pyproject_requires = self.req.pyproject_requires\n            assert pyproject_requires is not None\n            conflicting, missing = self.req.build_env.check_requirements(\n                pyproject_requires\n            )\n            if conflicting:\n                self._raise_conflicts(\"the backend dependencies\", conflicting)\n            if missing:\n                self._raise_missing_reqs(missing)\n        self.req.prepare_metadata()\n\n    def _prepare_build_backend(self, finder: PackageFinder) -> None:\n        # Isolate in a BuildEnvironment and install the build-time\n        # requirements.\n        pyproject_requires = self.req.pyproject_requires\n        assert pyproject_requires is not None\n\n        self.req.build_env = BuildEnvironment()\n        self.req.build_env.install_requirements(\n            finder, pyproject_requires, \"overlay\", kind=\"build dependencies\"\n        )\n        conflicting, missing = self.req.build_env.check_requirements(\n            self.req.requirements_to_check\n        )\n        if conflicting:\n            self._raise_conflicts(\"PEP 517/518 supported requirements\", conflicting)\n        if missing:\n            logger.warning(\n                \"Missing build requirements in pyproject.toml for %s.\",\n                self.req,\n            )\n            logger.warning(\n                \"The project does not specify a build backend, and \"\n                \"pip cannot fall back to setuptools without %s.\",\n                \" and \".join(map(repr, sorted(missing))),\n            )\n\n    def _get_build_requires_wheel(self) -> Iterable[str]:\n        with self.req.build_env:\n            runner = runner_with_spinner_message(\"Getting requirements to build wheel\")\n            backend = self.req.pep517_backend\n            assert backend is not None\n            with backend.subprocess_runner(runner):\n                return backend.get_requires_for_build_wheel()\n\n    def _get_build_requires_editable(self) -> Iterable[str]:\n        with self.req.build_env:\n            runner = runner_with_spinner_message(\n                \"Getting requirements to build editable\"\n            )\n            backend = self.req.pep517_backend\n            assert backend is not None\n            with backend.subprocess_runner(runner):\n                return backend.get_requires_for_build_editable()\n\n    def _install_build_reqs(self, finder: PackageFinder) -> None:\n        # Install any extra build dependencies that the backend requests.\n        # This must be done in a second pass, as the pyproject.toml\n        # dependencies must be installed before we can call the backend.\n        if (\n            self.req.editable\n            and self.req.permit_editable_wheels\n            and self.req.supports_pyproject_editable()\n        ):\n            build_reqs = self._get_build_requires_editable()\n        else:\n            build_reqs = self._get_build_requires_wheel()\n        conflicting, missing = self.req.build_env.check_requirements(build_reqs)\n        if conflicting:\n            self._raise_conflicts(\"the backend dependencies\", conflicting)\n        self.req.build_env.install_requirements(\n            finder, missing, \"normal\", kind=\"backend dependencies\"\n        )\n\n    def _raise_conflicts(\n        self, conflicting_with: str, conflicting_reqs: Set[Tuple[str, str]]\n    ) -> None:\n        format_string = (\n            \"Some build dependencies for {requirement} \"\n            \"conflict with {conflicting_with}: {description}.\"\n        )\n        error_message = format_string.format(\n            requirement=self.req,\n            conflicting_with=conflicting_with,\n            description=\", \".join(\n                f\"{installed} is incompatible with {wanted}\"\n                for installed, wanted in sorted(conflicting_reqs)\n            ),\n        )\n        raise InstallationError(error_message)\n\n    def _raise_missing_reqs(self, missing: Set[str]) -> None:\n        format_string = (\n            \"Some build dependencies for {requirement} are missing: {missing}.\"\n        )\n        error_message = format_string.format(\n            requirement=self.req, missing=\", \".join(map(repr, sorted(missing)))\n        )\n        raise InstallationError(error_message)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/distributions/wheel.py",
    "content": "from pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.distributions.base import AbstractDistribution\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.metadata import (\n    BaseDistribution,\n    FilesystemWheel,\n    get_wheel_distribution,\n)\n\n\nclass WheelDistribution(AbstractDistribution):\n    \"\"\"Represents a wheel distribution.\n\n    This does not need any preparation as wheels can be directly unpacked.\n    \"\"\"\n\n    def get_metadata_distribution(self) -> BaseDistribution:\n        \"\"\"Loads the metadata from the wheel file into memory and returns a\n        Distribution that uses it, not relying on the wheel file or\n        requirement.\n        \"\"\"\n        assert self.req.local_file_path, \"Set as part of preparation during download\"\n        assert self.req.name, \"Wheels are never unnamed\"\n        wheel = FilesystemWheel(self.req.local_file_path)\n        return get_wheel_distribution(wheel, canonicalize_name(self.req.name))\n\n    def prepare_distribution_metadata(\n        self,\n        finder: PackageFinder,\n        build_isolation: bool,\n        check_build_deps: bool,\n    ) -> None:\n        pass\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/exceptions.py",
    "content": "\"\"\"Exceptions used throughout package.\n\nThis module MUST NOT try to import from anything within `pip._internal` to\noperate. This is expected to be importable from any/all files within the\nsubpackage and, thus, should not depend on them.\n\"\"\"\n\nimport configparser\nimport re\nfrom itertools import chain, groupby, repeat\nfrom typing import TYPE_CHECKING, Dict, List, Optional, Union\n\nfrom pip._vendor.requests.models import Request, Response\nfrom pip._vendor.rich.console import Console, ConsoleOptions, RenderResult\nfrom pip._vendor.rich.markup import escape\nfrom pip._vendor.rich.text import Text\n\nif TYPE_CHECKING:\n    from hashlib import _Hash\n    from typing import Literal\n\n    from pip._internal.metadata import BaseDistribution\n    from pip._internal.req.req_install import InstallRequirement\n\n\n#\n# Scaffolding\n#\ndef _is_kebab_case(s: str) -> bool:\n    return re.match(r\"^[a-z]+(-[a-z]+)*$\", s) is not None\n\n\ndef _prefix_with_indent(\n    s: Union[Text, str],\n    console: Console,\n    *,\n    prefix: str,\n    indent: str,\n) -> Text:\n    if isinstance(s, Text):\n        text = s\n    else:\n        text = console.render_str(s)\n\n    return console.render_str(prefix, overflow=\"ignore\") + console.render_str(\n        f\"\\n{indent}\", overflow=\"ignore\"\n    ).join(text.split(allow_blank=True))\n\n\nclass PipError(Exception):\n    \"\"\"The base pip error.\"\"\"\n\n\nclass DiagnosticPipError(PipError):\n    \"\"\"An error, that presents diagnostic information to the user.\n\n    This contains a bunch of logic, to enable pretty presentation of our error\n    messages. Each error gets a unique reference. Each error can also include\n    additional context, a hint and/or a note -- which are presented with the\n    main error message in a consistent style.\n\n    This is adapted from the error output styling in `sphinx-theme-builder`.\n    \"\"\"\n\n    reference: str\n\n    def __init__(\n        self,\n        *,\n        kind: 'Literal[\"error\", \"warning\"]' = \"error\",\n        reference: Optional[str] = None,\n        message: Union[str, Text],\n        context: Optional[Union[str, Text]],\n        hint_stmt: Optional[Union[str, Text]],\n        note_stmt: Optional[Union[str, Text]] = None,\n        link: Optional[str] = None,\n    ) -> None:\n        # Ensure a proper reference is provided.\n        if reference is None:\n            assert hasattr(self, \"reference\"), \"error reference not provided!\"\n            reference = self.reference\n        assert _is_kebab_case(reference), \"error reference must be kebab-case!\"\n\n        self.kind = kind\n        self.reference = reference\n\n        self.message = message\n        self.context = context\n\n        self.note_stmt = note_stmt\n        self.hint_stmt = hint_stmt\n\n        self.link = link\n\n        super().__init__(f\"<{self.__class__.__name__}: {self.reference}>\")\n\n    def __repr__(self) -> str:\n        return (\n            f\"<{self.__class__.__name__}(\"\n            f\"reference={self.reference!r}, \"\n            f\"message={self.message!r}, \"\n            f\"context={self.context!r}, \"\n            f\"note_stmt={self.note_stmt!r}, \"\n            f\"hint_stmt={self.hint_stmt!r}\"\n            \")>\"\n        )\n\n    def __rich_console__(\n        self,\n        console: Console,\n        options: ConsoleOptions,\n    ) -> RenderResult:\n        colour = \"red\" if self.kind == \"error\" else \"yellow\"\n\n        yield f\"[{colour} bold]{self.kind}[/]: [bold]{self.reference}[/]\"\n        yield \"\"\n\n        if not options.ascii_only:\n            # Present the main message, with relevant context indented.\n            if self.context is not None:\n                yield _prefix_with_indent(\n                    self.message,\n                    console,\n                    prefix=f\"[{colour}]×[/] \",\n                    indent=f\"[{colour}]│[/] \",\n                )\n                yield _prefix_with_indent(\n                    self.context,\n                    console,\n                    prefix=f\"[{colour}]╰─>[/] \",\n                    indent=f\"[{colour}]   [/] \",\n                )\n            else:\n                yield _prefix_with_indent(\n                    self.message,\n                    console,\n                    prefix=\"[red]×[/] \",\n                    indent=\"  \",\n                )\n        else:\n            yield self.message\n            if self.context is not None:\n                yield \"\"\n                yield self.context\n\n        if self.note_stmt is not None or self.hint_stmt is not None:\n            yield \"\"\n\n        if self.note_stmt is not None:\n            yield _prefix_with_indent(\n                self.note_stmt,\n                console,\n                prefix=\"[magenta bold]note[/]: \",\n                indent=\"      \",\n            )\n        if self.hint_stmt is not None:\n            yield _prefix_with_indent(\n                self.hint_stmt,\n                console,\n                prefix=\"[cyan bold]hint[/]: \",\n                indent=\"      \",\n            )\n\n        if self.link is not None:\n            yield \"\"\n            yield f\"Link: {self.link}\"\n\n\n#\n# Actual Errors\n#\nclass ConfigurationError(PipError):\n    \"\"\"General exception in configuration\"\"\"\n\n\nclass InstallationError(PipError):\n    \"\"\"General exception during installation\"\"\"\n\n\nclass UninstallationError(PipError):\n    \"\"\"General exception during uninstallation\"\"\"\n\n\nclass MissingPyProjectBuildRequires(DiagnosticPipError):\n    \"\"\"Raised when pyproject.toml has `build-system`, but no `build-system.requires`.\"\"\"\n\n    reference = \"missing-pyproject-build-system-requires\"\n\n    def __init__(self, *, package: str) -> None:\n        super().__init__(\n            message=f\"Can not process {escape(package)}\",\n            context=Text(\n                \"This package has an invalid pyproject.toml file.\\n\"\n                \"The [build-system] table is missing the mandatory `requires` key.\"\n            ),\n            note_stmt=\"This is an issue with the package mentioned above, not pip.\",\n            hint_stmt=Text(\"See PEP 518 for the detailed specification.\"),\n        )\n\n\nclass InvalidPyProjectBuildRequires(DiagnosticPipError):\n    \"\"\"Raised when pyproject.toml an invalid `build-system.requires`.\"\"\"\n\n    reference = \"invalid-pyproject-build-system-requires\"\n\n    def __init__(self, *, package: str, reason: str) -> None:\n        super().__init__(\n            message=f\"Can not process {escape(package)}\",\n            context=Text(\n                \"This package has an invalid `build-system.requires` key in \"\n                f\"pyproject.toml.\\n{reason}\"\n            ),\n            note_stmt=\"This is an issue with the package mentioned above, not pip.\",\n            hint_stmt=Text(\"See PEP 518 for the detailed specification.\"),\n        )\n\n\nclass NoneMetadataError(PipError):\n    \"\"\"Raised when accessing a Distribution's \"METADATA\" or \"PKG-INFO\".\n\n    This signifies an inconsistency, when the Distribution claims to have\n    the metadata file (if not, raise ``FileNotFoundError`` instead), but is\n    not actually able to produce its content. This may be due to permission\n    errors.\n    \"\"\"\n\n    def __init__(\n        self,\n        dist: \"BaseDistribution\",\n        metadata_name: str,\n    ) -> None:\n        \"\"\"\n        :param dist: A Distribution object.\n        :param metadata_name: The name of the metadata being accessed\n            (can be \"METADATA\" or \"PKG-INFO\").\n        \"\"\"\n        self.dist = dist\n        self.metadata_name = metadata_name\n\n    def __str__(self) -> str:\n        # Use `dist` in the error message because its stringification\n        # includes more information, like the version and location.\n        return \"None {} metadata found for distribution: {}\".format(\n            self.metadata_name,\n            self.dist,\n        )\n\n\nclass UserInstallationInvalid(InstallationError):\n    \"\"\"A --user install is requested on an environment without user site.\"\"\"\n\n    def __str__(self) -> str:\n        return \"User base directory is not specified\"\n\n\nclass InvalidSchemeCombination(InstallationError):\n    def __str__(self) -> str:\n        before = \", \".join(str(a) for a in self.args[:-1])\n        return f\"Cannot set {before} and {self.args[-1]} together\"\n\n\nclass DistributionNotFound(InstallationError):\n    \"\"\"Raised when a distribution cannot be found to satisfy a requirement\"\"\"\n\n\nclass RequirementsFileParseError(InstallationError):\n    \"\"\"Raised when a general error occurs parsing a requirements file line.\"\"\"\n\n\nclass BestVersionAlreadyInstalled(PipError):\n    \"\"\"Raised when the most up-to-date version of a package is already\n    installed.\"\"\"\n\n\nclass BadCommand(PipError):\n    \"\"\"Raised when virtualenv or a command is not found\"\"\"\n\n\nclass CommandError(PipError):\n    \"\"\"Raised when there is an error in command-line arguments\"\"\"\n\n\nclass PreviousBuildDirError(PipError):\n    \"\"\"Raised when there's a previous conflicting build directory\"\"\"\n\n\nclass NetworkConnectionError(PipError):\n    \"\"\"HTTP connection error\"\"\"\n\n    def __init__(\n        self,\n        error_msg: str,\n        response: Optional[Response] = None,\n        request: Optional[Request] = None,\n    ) -> None:\n        \"\"\"\n        Initialize NetworkConnectionError with  `request` and `response`\n        objects.\n        \"\"\"\n        self.response = response\n        self.request = request\n        self.error_msg = error_msg\n        if (\n            self.response is not None\n            and not self.request\n            and hasattr(response, \"request\")\n        ):\n            self.request = self.response.request\n        super().__init__(error_msg, response, request)\n\n    def __str__(self) -> str:\n        return str(self.error_msg)\n\n\nclass InvalidWheelFilename(InstallationError):\n    \"\"\"Invalid wheel filename.\"\"\"\n\n\nclass UnsupportedWheel(InstallationError):\n    \"\"\"Unsupported wheel.\"\"\"\n\n\nclass InvalidWheel(InstallationError):\n    \"\"\"Invalid (e.g. corrupt) wheel.\"\"\"\n\n    def __init__(self, location: str, name: str):\n        self.location = location\n        self.name = name\n\n    def __str__(self) -> str:\n        return f\"Wheel '{self.name}' located at {self.location} is invalid.\"\n\n\nclass MetadataInconsistent(InstallationError):\n    \"\"\"Built metadata contains inconsistent information.\n\n    This is raised when the metadata contains values (e.g. name and version)\n    that do not match the information previously obtained from sdist filename,\n    user-supplied ``#egg=`` value, or an install requirement name.\n    \"\"\"\n\n    def __init__(\n        self, ireq: \"InstallRequirement\", field: str, f_val: str, m_val: str\n    ) -> None:\n        self.ireq = ireq\n        self.field = field\n        self.f_val = f_val\n        self.m_val = m_val\n\n    def __str__(self) -> str:\n        return (\n            f\"Requested {self.ireq} has inconsistent {self.field}: \"\n            f\"expected {self.f_val!r}, but metadata has {self.m_val!r}\"\n        )\n\n\nclass LegacyInstallFailure(DiagnosticPipError):\n    \"\"\"Error occurred while executing `setup.py install`\"\"\"\n\n    reference = \"legacy-install-failure\"\n\n    def __init__(self, package_details: str) -> None:\n        super().__init__(\n            message=\"Encountered error while trying to install package.\",\n            context=package_details,\n            hint_stmt=\"See above for output from the failure.\",\n            note_stmt=\"This is an issue with the package mentioned above, not pip.\",\n        )\n\n\nclass InstallationSubprocessError(DiagnosticPipError, InstallationError):\n    \"\"\"A subprocess call failed.\"\"\"\n\n    reference = \"subprocess-exited-with-error\"\n\n    def __init__(\n        self,\n        *,\n        command_description: str,\n        exit_code: int,\n        output_lines: Optional[List[str]],\n    ) -> None:\n        if output_lines is None:\n            output_prompt = Text(\"See above for output.\")\n        else:\n            output_prompt = (\n                Text.from_markup(f\"[red][{len(output_lines)} lines of output][/]\\n\")\n                + Text(\"\".join(output_lines))\n                + Text.from_markup(R\"[red]\\[end of output][/]\")\n            )\n\n        super().__init__(\n            message=(\n                f\"[green]{escape(command_description)}[/] did not run successfully.\\n\"\n                f\"exit code: {exit_code}\"\n            ),\n            context=output_prompt,\n            hint_stmt=None,\n            note_stmt=(\n                \"This error originates from a subprocess, and is likely not a \"\n                \"problem with pip.\"\n            ),\n        )\n\n        self.command_description = command_description\n        self.exit_code = exit_code\n\n    def __str__(self) -> str:\n        return f\"{self.command_description} exited with {self.exit_code}\"\n\n\nclass MetadataGenerationFailed(InstallationSubprocessError, InstallationError):\n    reference = \"metadata-generation-failed\"\n\n    def __init__(\n        self,\n        *,\n        package_details: str,\n    ) -> None:\n        super(InstallationSubprocessError, self).__init__(\n            message=\"Encountered error while generating package metadata.\",\n            context=escape(package_details),\n            hint_stmt=\"See above for details.\",\n            note_stmt=\"This is an issue with the package mentioned above, not pip.\",\n        )\n\n    def __str__(self) -> str:\n        return \"metadata generation failed\"\n\n\nclass HashErrors(InstallationError):\n    \"\"\"Multiple HashError instances rolled into one for reporting\"\"\"\n\n    def __init__(self) -> None:\n        self.errors: List[\"HashError\"] = []\n\n    def append(self, error: \"HashError\") -> None:\n        self.errors.append(error)\n\n    def __str__(self) -> str:\n        lines = []\n        self.errors.sort(key=lambda e: e.order)\n        for cls, errors_of_cls in groupby(self.errors, lambda e: e.__class__):\n            lines.append(cls.head)\n            lines.extend(e.body() for e in errors_of_cls)\n        if lines:\n            return \"\\n\".join(lines)\n        return \"\"\n\n    def __bool__(self) -> bool:\n        return bool(self.errors)\n\n\nclass HashError(InstallationError):\n    \"\"\"\n    A failure to verify a package against known-good hashes\n\n    :cvar order: An int sorting hash exception classes by difficulty of\n        recovery (lower being harder), so the user doesn't bother fretting\n        about unpinned packages when he has deeper issues, like VCS\n        dependencies, to deal with. Also keeps error reports in a\n        deterministic order.\n    :cvar head: A section heading for display above potentially many\n        exceptions of this kind\n    :ivar req: The InstallRequirement that triggered this error. This is\n        pasted on after the exception is instantiated, because it's not\n        typically available earlier.\n\n    \"\"\"\n\n    req: Optional[\"InstallRequirement\"] = None\n    head = \"\"\n    order: int = -1\n\n    def body(self) -> str:\n        \"\"\"Return a summary of me for display under the heading.\n\n        This default implementation simply prints a description of the\n        triggering requirement.\n\n        :param req: The InstallRequirement that provoked this error, with\n            its link already populated by the resolver's _populate_link().\n\n        \"\"\"\n        return f\"    {self._requirement_name()}\"\n\n    def __str__(self) -> str:\n        return f\"{self.head}\\n{self.body()}\"\n\n    def _requirement_name(self) -> str:\n        \"\"\"Return a description of the requirement that triggered me.\n\n        This default implementation returns long description of the req, with\n        line numbers\n\n        \"\"\"\n        return str(self.req) if self.req else \"unknown package\"\n\n\nclass VcsHashUnsupported(HashError):\n    \"\"\"A hash was provided for a version-control-system-based requirement, but\n    we don't have a method for hashing those.\"\"\"\n\n    order = 0\n    head = (\n        \"Can't verify hashes for these requirements because we don't \"\n        \"have a way to hash version control repositories:\"\n    )\n\n\nclass DirectoryUrlHashUnsupported(HashError):\n    \"\"\"A hash was provided for a version-control-system-based requirement, but\n    we don't have a method for hashing those.\"\"\"\n\n    order = 1\n    head = (\n        \"Can't verify hashes for these file:// requirements because they \"\n        \"point to directories:\"\n    )\n\n\nclass HashMissing(HashError):\n    \"\"\"A hash was needed for a requirement but is absent.\"\"\"\n\n    order = 2\n    head = (\n        \"Hashes are required in --require-hashes mode, but they are \"\n        \"missing from some requirements. Here is a list of those \"\n        \"requirements along with the hashes their downloaded archives \"\n        \"actually had. Add lines like these to your requirements files to \"\n        \"prevent tampering. (If you did not enable --require-hashes \"\n        \"manually, note that it turns on automatically when any package \"\n        \"has a hash.)\"\n    )\n\n    def __init__(self, gotten_hash: str) -> None:\n        \"\"\"\n        :param gotten_hash: The hash of the (possibly malicious) archive we\n            just downloaded\n        \"\"\"\n        self.gotten_hash = gotten_hash\n\n    def body(self) -> str:\n        # Dodge circular import.\n        from pip._internal.utils.hashes import FAVORITE_HASH\n\n        package = None\n        if self.req:\n            # In the case of URL-based requirements, display the original URL\n            # seen in the requirements file rather than the package name,\n            # so the output can be directly copied into the requirements file.\n            package = (\n                self.req.original_link\n                if self.req.original_link\n                # In case someone feeds something downright stupid\n                # to InstallRequirement's constructor.\n                else getattr(self.req, \"req\", None)\n            )\n        return \"    {} --hash={}:{}\".format(\n            package or \"unknown package\", FAVORITE_HASH, self.gotten_hash\n        )\n\n\nclass HashUnpinned(HashError):\n    \"\"\"A requirement had a hash specified but was not pinned to a specific\n    version.\"\"\"\n\n    order = 3\n    head = (\n        \"In --require-hashes mode, all requirements must have their \"\n        \"versions pinned with ==. These do not:\"\n    )\n\n\nclass HashMismatch(HashError):\n    \"\"\"\n    Distribution file hash values don't match.\n\n    :ivar package_name: The name of the package that triggered the hash\n        mismatch. Feel free to write to this after the exception is raise to\n        improve its error message.\n\n    \"\"\"\n\n    order = 4\n    head = (\n        \"THESE PACKAGES DO NOT MATCH THE HASHES FROM THE REQUIREMENTS \"\n        \"FILE. If you have updated the package versions, please update \"\n        \"the hashes. Otherwise, examine the package contents carefully; \"\n        \"someone may have tampered with them.\"\n    )\n\n    def __init__(self, allowed: Dict[str, List[str]], gots: Dict[str, \"_Hash\"]) -> None:\n        \"\"\"\n        :param allowed: A dict of algorithm names pointing to lists of allowed\n            hex digests\n        :param gots: A dict of algorithm names pointing to hashes we\n            actually got from the files under suspicion\n        \"\"\"\n        self.allowed = allowed\n        self.gots = gots\n\n    def body(self) -> str:\n        return \"    {}:\\n{}\".format(self._requirement_name(), self._hash_comparison())\n\n    def _hash_comparison(self) -> str:\n        \"\"\"\n        Return a comparison of actual and expected hash values.\n\n        Example::\n\n               Expected sha256 abcdeabcdeabcdeabcdeabcdeabcdeabcdeabcdeabcde\n                            or 123451234512345123451234512345123451234512345\n                    Got        bcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdefbcdef\n\n        \"\"\"\n\n        def hash_then_or(hash_name: str) -> \"chain[str]\":\n            # For now, all the decent hashes have 6-char names, so we can get\n            # away with hard-coding space literals.\n            return chain([hash_name], repeat(\"    or\"))\n\n        lines: List[str] = []\n        for hash_name, expecteds in self.allowed.items():\n            prefix = hash_then_or(hash_name)\n            lines.extend(\n                (\"        Expected {} {}\".format(next(prefix), e)) for e in expecteds\n            )\n            lines.append(\n                \"             Got        {}\\n\".format(self.gots[hash_name].hexdigest())\n            )\n        return \"\\n\".join(lines)\n\n\nclass UnsupportedPythonVersion(InstallationError):\n    \"\"\"Unsupported python version according to Requires-Python package\n    metadata.\"\"\"\n\n\nclass ConfigurationFileCouldNotBeLoaded(ConfigurationError):\n    \"\"\"When there are errors while loading a configuration file\"\"\"\n\n    def __init__(\n        self,\n        reason: str = \"could not be loaded\",\n        fname: Optional[str] = None,\n        error: Optional[configparser.Error] = None,\n    ) -> None:\n        super().__init__(error)\n        self.reason = reason\n        self.fname = fname\n        self.error = error\n\n    def __str__(self) -> str:\n        if self.fname is not None:\n            message_part = f\" in {self.fname}.\"\n        else:\n            assert self.error is not None\n            message_part = f\".\\n{self.error}\\n\"\n        return f\"Configuration file {self.reason}{message_part}\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/index/__init__.py",
    "content": "\"\"\"Index interaction code\n\"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/index/collector.py",
    "content": "\"\"\"\nThe main purpose of this module is to expose LinkCollector.collect_sources().\n\"\"\"\n\nimport collections\nimport email.message\nimport functools\nimport itertools\nimport json\nimport logging\nimport os\nimport urllib.parse\nimport urllib.request\nfrom html.parser import HTMLParser\nfrom optparse import Values\nfrom typing import (\n    TYPE_CHECKING,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    MutableMapping,\n    NamedTuple,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n)\n\nfrom pip._vendor import requests\nfrom pip._vendor.requests import Response\nfrom pip._vendor.requests.exceptions import RetryError, SSLError\n\nfrom pip._internal.exceptions import NetworkConnectionError\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.search_scope import SearchScope\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.network.utils import raise_for_status\nfrom pip._internal.utils.filetypes import is_archive_file\nfrom pip._internal.utils.misc import redact_auth_from_url\nfrom pip._internal.vcs import vcs\n\nfrom .sources import CandidatesFromPage, LinkSource, build_source\n\nif TYPE_CHECKING:\n    from typing import Protocol\nelse:\n    Protocol = object\n\nlogger = logging.getLogger(__name__)\n\nResponseHeaders = MutableMapping[str, str]\n\n\ndef _match_vcs_scheme(url: str) -> Optional[str]:\n    \"\"\"Look for VCS schemes in the URL.\n\n    Returns the matched VCS scheme, or None if there's no match.\n    \"\"\"\n    for scheme in vcs.schemes:\n        if url.lower().startswith(scheme) and url[len(scheme)] in \"+:\":\n            return scheme\n    return None\n\n\nclass _NotAPIContent(Exception):\n    def __init__(self, content_type: str, request_desc: str) -> None:\n        super().__init__(content_type, request_desc)\n        self.content_type = content_type\n        self.request_desc = request_desc\n\n\ndef _ensure_api_header(response: Response) -> None:\n    \"\"\"\n    Check the Content-Type header to ensure the response contains a Simple\n    API Response.\n\n    Raises `_NotAPIContent` if the content type is not a valid content-type.\n    \"\"\"\n    content_type = response.headers.get(\"Content-Type\", \"Unknown\")\n\n    content_type_l = content_type.lower()\n    if content_type_l.startswith(\n        (\n            \"text/html\",\n            \"application/vnd.pypi.simple.v1+html\",\n            \"application/vnd.pypi.simple.v1+json\",\n        )\n    ):\n        return\n\n    raise _NotAPIContent(content_type, response.request.method)\n\n\nclass _NotHTTP(Exception):\n    pass\n\n\ndef _ensure_api_response(url: str, session: PipSession) -> None:\n    \"\"\"\n    Send a HEAD request to the URL, and ensure the response contains a simple\n    API Response.\n\n    Raises `_NotHTTP` if the URL is not available for a HEAD request, or\n    `_NotAPIContent` if the content type is not a valid content type.\n    \"\"\"\n    scheme, netloc, path, query, fragment = urllib.parse.urlsplit(url)\n    if scheme not in {\"http\", \"https\"}:\n        raise _NotHTTP()\n\n    resp = session.head(url, allow_redirects=True)\n    raise_for_status(resp)\n\n    _ensure_api_header(resp)\n\n\ndef _get_simple_response(url: str, session: PipSession) -> Response:\n    \"\"\"Access an Simple API response with GET, and return the response.\n\n    This consists of three parts:\n\n    1. If the URL looks suspiciously like an archive, send a HEAD first to\n       check the Content-Type is HTML or Simple API, to avoid downloading a\n       large file. Raise `_NotHTTP` if the content type cannot be determined, or\n       `_NotAPIContent` if it is not HTML or a Simple API.\n    2. Actually perform the request. Raise HTTP exceptions on network failures.\n    3. Check the Content-Type header to make sure we got a Simple API response,\n       and raise `_NotAPIContent` otherwise.\n    \"\"\"\n    if is_archive_file(Link(url).filename):\n        _ensure_api_response(url, session=session)\n\n    logger.debug(\"Getting page %s\", redact_auth_from_url(url))\n\n    resp = session.get(\n        url,\n        headers={\n            \"Accept\": \", \".join(\n                [\n                    \"application/vnd.pypi.simple.v1+json\",\n                    \"application/vnd.pypi.simple.v1+html; q=0.1\",\n                    \"text/html; q=0.01\",\n                ]\n            ),\n            # We don't want to blindly returned cached data for\n            # /simple/, because authors generally expecting that\n            # twine upload && pip install will function, but if\n            # they've done a pip install in the last ~10 minutes\n            # it won't. Thus by setting this to zero we will not\n            # blindly use any cached data, however the benefit of\n            # using max-age=0 instead of no-cache, is that we will\n            # still support conditional requests, so we will still\n            # minimize traffic sent in cases where the page hasn't\n            # changed at all, we will just always incur the round\n            # trip for the conditional GET now instead of only\n            # once per 10 minutes.\n            # For more information, please see pypa/pip#5670.\n            \"Cache-Control\": \"max-age=0\",\n        },\n    )\n    raise_for_status(resp)\n\n    # The check for archives above only works if the url ends with\n    # something that looks like an archive. However that is not a\n    # requirement of an url. Unless we issue a HEAD request on every\n    # url we cannot know ahead of time for sure if something is a\n    # Simple API response or not. However we can check after we've\n    # downloaded it.\n    _ensure_api_header(resp)\n\n    logger.debug(\n        \"Fetched page %s as %s\",\n        redact_auth_from_url(url),\n        resp.headers.get(\"Content-Type\", \"Unknown\"),\n    )\n\n    return resp\n\n\ndef _get_encoding_from_headers(headers: ResponseHeaders) -> Optional[str]:\n    \"\"\"Determine if we have any encoding information in our headers.\"\"\"\n    if headers and \"Content-Type\" in headers:\n        m = email.message.Message()\n        m[\"content-type\"] = headers[\"Content-Type\"]\n        charset = m.get_param(\"charset\")\n        if charset:\n            return str(charset)\n    return None\n\n\nclass CacheablePageContent:\n    def __init__(self, page: \"IndexContent\") -> None:\n        assert page.cache_link_parsing\n        self.page = page\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, type(self)) and self.page.url == other.page.url\n\n    def __hash__(self) -> int:\n        return hash(self.page.url)\n\n\nclass ParseLinks(Protocol):\n    def __call__(self, page: \"IndexContent\") -> Iterable[Link]:\n        ...\n\n\ndef with_cached_index_content(fn: ParseLinks) -> ParseLinks:\n    \"\"\"\n    Given a function that parses an Iterable[Link] from an IndexContent, cache the\n    function's result (keyed by CacheablePageContent), unless the IndexContent\n    `page` has `page.cache_link_parsing == False`.\n    \"\"\"\n\n    @functools.lru_cache(maxsize=None)\n    def wrapper(cacheable_page: CacheablePageContent) -> List[Link]:\n        return list(fn(cacheable_page.page))\n\n    @functools.wraps(fn)\n    def wrapper_wrapper(page: \"IndexContent\") -> List[Link]:\n        if page.cache_link_parsing:\n            return wrapper(CacheablePageContent(page))\n        return list(fn(page))\n\n    return wrapper_wrapper\n\n\n@with_cached_index_content\ndef parse_links(page: \"IndexContent\") -> Iterable[Link]:\n    \"\"\"\n    Parse a Simple API's Index Content, and yield its anchor elements as Link objects.\n    \"\"\"\n\n    content_type_l = page.content_type.lower()\n    if content_type_l.startswith(\"application/vnd.pypi.simple.v1+json\"):\n        data = json.loads(page.content)\n        for file in data.get(\"files\", []):\n            link = Link.from_json(file, page.url)\n            if link is None:\n                continue\n            yield link\n        return\n\n    parser = HTMLLinkParser(page.url)\n    encoding = page.encoding or \"utf-8\"\n    parser.feed(page.content.decode(encoding))\n\n    url = page.url\n    base_url = parser.base_url or url\n    for anchor in parser.anchors:\n        link = Link.from_element(anchor, page_url=url, base_url=base_url)\n        if link is None:\n            continue\n        yield link\n\n\nclass IndexContent:\n    \"\"\"Represents one response (or page), along with its URL\"\"\"\n\n    def __init__(\n        self,\n        content: bytes,\n        content_type: str,\n        encoding: Optional[str],\n        url: str,\n        cache_link_parsing: bool = True,\n    ) -> None:\n        \"\"\"\n        :param encoding: the encoding to decode the given content.\n        :param url: the URL from which the HTML was downloaded.\n        :param cache_link_parsing: whether links parsed from this page's url\n                                   should be cached. PyPI index urls should\n                                   have this set to False, for example.\n        \"\"\"\n        self.content = content\n        self.content_type = content_type\n        self.encoding = encoding\n        self.url = url\n        self.cache_link_parsing = cache_link_parsing\n\n    def __str__(self) -> str:\n        return redact_auth_from_url(self.url)\n\n\nclass HTMLLinkParser(HTMLParser):\n    \"\"\"\n    HTMLParser that keeps the first base HREF and a list of all anchor\n    elements' attributes.\n    \"\"\"\n\n    def __init__(self, url: str) -> None:\n        super().__init__(convert_charrefs=True)\n\n        self.url: str = url\n        self.base_url: Optional[str] = None\n        self.anchors: List[Dict[str, Optional[str]]] = []\n\n    def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None:\n        if tag == \"base\" and self.base_url is None:\n            href = self.get_href(attrs)\n            if href is not None:\n                self.base_url = href\n        elif tag == \"a\":\n            self.anchors.append(dict(attrs))\n\n    def get_href(self, attrs: List[Tuple[str, Optional[str]]]) -> Optional[str]:\n        for name, value in attrs:\n            if name == \"href\":\n                return value\n        return None\n\n\ndef _handle_get_simple_fail(\n    link: Link,\n    reason: Union[str, Exception],\n    meth: Optional[Callable[..., None]] = None,\n) -> None:\n    if meth is None:\n        meth = logger.debug\n    meth(\"Could not fetch URL %s: %s - skipping\", link, reason)\n\n\ndef _make_index_content(\n    response: Response, cache_link_parsing: bool = True\n) -> IndexContent:\n    encoding = _get_encoding_from_headers(response.headers)\n    return IndexContent(\n        response.content,\n        response.headers[\"Content-Type\"],\n        encoding=encoding,\n        url=response.url,\n        cache_link_parsing=cache_link_parsing,\n    )\n\n\ndef _get_index_content(link: Link, *, session: PipSession) -> Optional[\"IndexContent\"]:\n    url = link.url.split(\"#\", 1)[0]\n\n    # Check for VCS schemes that do not support lookup as web pages.\n    vcs_scheme = _match_vcs_scheme(url)\n    if vcs_scheme:\n        logger.warning(\n            \"Cannot look at %s URL %s because it does not support lookup as web pages.\",\n            vcs_scheme,\n            link,\n        )\n        return None\n\n    # Tack index.html onto file:// URLs that point to directories\n    scheme, _, path, _, _, _ = urllib.parse.urlparse(url)\n    if scheme == \"file\" and os.path.isdir(urllib.request.url2pathname(path)):\n        # add trailing slash if not present so urljoin doesn't trim\n        # final segment\n        if not url.endswith(\"/\"):\n            url += \"/\"\n        # TODO: In the future, it would be nice if pip supported PEP 691\n        #       style respones in the file:// URLs, however there's no\n        #       standard file extension for application/vnd.pypi.simple.v1+json\n        #       so we'll need to come up with something on our own.\n        url = urllib.parse.urljoin(url, \"index.html\")\n        logger.debug(\" file: URL is directory, getting %s\", url)\n\n    try:\n        resp = _get_simple_response(url, session=session)\n    except _NotHTTP:\n        logger.warning(\n            \"Skipping page %s because it looks like an archive, and cannot \"\n            \"be checked by a HTTP HEAD request.\",\n            link,\n        )\n    except _NotAPIContent as exc:\n        logger.warning(\n            \"Skipping page %s because the %s request got Content-Type: %s. \"\n            \"The only supported Content-Types are application/vnd.pypi.simple.v1+json, \"\n            \"application/vnd.pypi.simple.v1+html, and text/html\",\n            link,\n            exc.request_desc,\n            exc.content_type,\n        )\n    except NetworkConnectionError as exc:\n        _handle_get_simple_fail(link, exc)\n    except RetryError as exc:\n        _handle_get_simple_fail(link, exc)\n    except SSLError as exc:\n        reason = \"There was a problem confirming the ssl certificate: \"\n        reason += str(exc)\n        _handle_get_simple_fail(link, reason, meth=logger.info)\n    except requests.ConnectionError as exc:\n        _handle_get_simple_fail(link, f\"connection error: {exc}\")\n    except requests.Timeout:\n        _handle_get_simple_fail(link, \"timed out\")\n    else:\n        return _make_index_content(resp, cache_link_parsing=link.cache_link_parsing)\n    return None\n\n\nclass CollectedSources(NamedTuple):\n    find_links: Sequence[Optional[LinkSource]]\n    index_urls: Sequence[Optional[LinkSource]]\n\n\nclass LinkCollector:\n\n    \"\"\"\n    Responsible for collecting Link objects from all configured locations,\n    making network requests as needed.\n\n    The class's main method is its collect_sources() method.\n    \"\"\"\n\n    def __init__(\n        self,\n        session: PipSession,\n        search_scope: SearchScope,\n    ) -> None:\n        self.search_scope = search_scope\n        self.session = session\n\n    @classmethod\n    def create(\n        cls,\n        session: PipSession,\n        options: Values,\n        suppress_no_index: bool = False,\n    ) -> \"LinkCollector\":\n        \"\"\"\n        :param session: The Session to use to make requests.\n        :param suppress_no_index: Whether to ignore the --no-index option\n            when constructing the SearchScope object.\n        \"\"\"\n        index_urls = [options.index_url] + options.extra_index_urls\n        if options.no_index and not suppress_no_index:\n            logger.debug(\n                \"Ignoring indexes: %s\",\n                \",\".join(redact_auth_from_url(url) for url in index_urls),\n            )\n            index_urls = []\n\n        # Make sure find_links is a list before passing to create().\n        find_links = options.find_links or []\n\n        search_scope = SearchScope.create(\n            find_links=find_links,\n            index_urls=index_urls,\n            no_index=options.no_index,\n        )\n        link_collector = LinkCollector(\n            session=session,\n            search_scope=search_scope,\n        )\n        return link_collector\n\n    @property\n    def find_links(self) -> List[str]:\n        return self.search_scope.find_links\n\n    def fetch_response(self, location: Link) -> Optional[IndexContent]:\n        \"\"\"\n        Fetch an HTML page containing package links.\n        \"\"\"\n        return _get_index_content(location, session=self.session)\n\n    def collect_sources(\n        self,\n        project_name: str,\n        candidates_from_page: CandidatesFromPage,\n    ) -> CollectedSources:\n        # The OrderedDict calls deduplicate sources by URL.\n        index_url_sources = collections.OrderedDict(\n            build_source(\n                loc,\n                candidates_from_page=candidates_from_page,\n                page_validator=self.session.is_secure_origin,\n                expand_dir=False,\n                cache_link_parsing=False,\n            )\n            for loc in self.search_scope.get_index_urls_locations(project_name)\n        ).values()\n        find_links_sources = collections.OrderedDict(\n            build_source(\n                loc,\n                candidates_from_page=candidates_from_page,\n                page_validator=self.session.is_secure_origin,\n                expand_dir=True,\n                cache_link_parsing=True,\n            )\n            for loc in self.find_links\n        ).values()\n\n        if logger.isEnabledFor(logging.DEBUG):\n            lines = [\n                f\"* {s.link}\"\n                for s in itertools.chain(find_links_sources, index_url_sources)\n                if s is not None and s.link is not None\n            ]\n            lines = [\n                f\"{len(lines)} location(s) to search \"\n                f\"for versions of {project_name}:\"\n            ] + lines\n            logger.debug(\"\\n\".join(lines))\n\n        return CollectedSources(\n            find_links=list(find_links_sources),\n            index_urls=list(index_url_sources),\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/index/package_finder.py",
    "content": "\"\"\"Routines related to PyPI, indexes\"\"\"\n\n# The following comment should be removed at some point in the future.\n# mypy: strict-optional=False\n\nimport enum\nimport functools\nimport itertools\nimport logging\nimport re\nfrom typing import FrozenSet, Iterable, List, Optional, Set, Tuple, Union\n\nfrom pip._vendor.packaging import specifiers\nfrom pip._vendor.packaging.tags import Tag\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.packaging.version import _BaseVersion\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip._internal.exceptions import (\n    BestVersionAlreadyInstalled,\n    DistributionNotFound,\n    InvalidWheelFilename,\n    UnsupportedWheel,\n)\nfrom pip._internal.index.collector import LinkCollector, parse_links\nfrom pip._internal.models.candidate import InstallationCandidate\nfrom pip._internal.models.format_control import FormatControl\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.search_scope import SearchScope\nfrom pip._internal.models.selection_prefs import SelectionPreferences\nfrom pip._internal.models.target_python import TargetPython\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.req import InstallRequirement\nfrom pip._internal.utils._log import getLogger\nfrom pip._internal.utils.filetypes import WHEEL_EXTENSION\nfrom pip._internal.utils.hashes import Hashes\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import build_netloc\nfrom pip._internal.utils.packaging import check_requires_python\nfrom pip._internal.utils.unpacking import SUPPORTED_EXTENSIONS\n\n__all__ = [\"FormatControl\", \"BestCandidateResult\", \"PackageFinder\"]\n\n\nlogger = getLogger(__name__)\n\nBuildTag = Union[Tuple[()], Tuple[int, str]]\nCandidateSortingKey = Tuple[int, int, int, _BaseVersion, Optional[int], BuildTag]\n\n\ndef _check_link_requires_python(\n    link: Link,\n    version_info: Tuple[int, int, int],\n    ignore_requires_python: bool = False,\n) -> bool:\n    \"\"\"\n    Return whether the given Python version is compatible with a link's\n    \"Requires-Python\" value.\n\n    :param version_info: A 3-tuple of ints representing the Python\n        major-minor-micro version to check.\n    :param ignore_requires_python: Whether to ignore the \"Requires-Python\"\n        value if the given Python version isn't compatible.\n    \"\"\"\n    try:\n        is_compatible = check_requires_python(\n            link.requires_python,\n            version_info=version_info,\n        )\n    except specifiers.InvalidSpecifier:\n        logger.debug(\n            \"Ignoring invalid Requires-Python (%r) for link: %s\",\n            link.requires_python,\n            link,\n        )\n    else:\n        if not is_compatible:\n            version = \".\".join(map(str, version_info))\n            if not ignore_requires_python:\n                logger.verbose(\n                    \"Link requires a different Python (%s not in: %r): %s\",\n                    version,\n                    link.requires_python,\n                    link,\n                )\n                return False\n\n            logger.debug(\n                \"Ignoring failed Requires-Python check (%s not in: %r) for link: %s\",\n                version,\n                link.requires_python,\n                link,\n            )\n\n    return True\n\n\nclass LinkType(enum.Enum):\n    candidate = enum.auto()\n    different_project = enum.auto()\n    yanked = enum.auto()\n    format_unsupported = enum.auto()\n    format_invalid = enum.auto()\n    platform_mismatch = enum.auto()\n    requires_python_mismatch = enum.auto()\n\n\nclass LinkEvaluator:\n\n    \"\"\"\n    Responsible for evaluating links for a particular project.\n    \"\"\"\n\n    _py_version_re = re.compile(r\"-py([123]\\.?[0-9]?)$\")\n\n    # Don't include an allow_yanked default value to make sure each call\n    # site considers whether yanked releases are allowed. This also causes\n    # that decision to be made explicit in the calling code, which helps\n    # people when reading the code.\n    def __init__(\n        self,\n        project_name: str,\n        canonical_name: str,\n        formats: FrozenSet[str],\n        target_python: TargetPython,\n        allow_yanked: bool,\n        ignore_requires_python: Optional[bool] = None,\n    ) -> None:\n        \"\"\"\n        :param project_name: The user supplied package name.\n        :param canonical_name: The canonical package name.\n        :param formats: The formats allowed for this package. Should be a set\n            with 'binary' or 'source' or both in it.\n        :param target_python: The target Python interpreter to use when\n            evaluating link compatibility. This is used, for example, to\n            check wheel compatibility, as well as when checking the Python\n            version, e.g. the Python version embedded in a link filename\n            (or egg fragment) and against an HTML link's optional PEP 503\n            \"data-requires-python\" attribute.\n        :param allow_yanked: Whether files marked as yanked (in the sense\n            of PEP 592) are permitted to be candidates for install.\n        :param ignore_requires_python: Whether to ignore incompatible\n            PEP 503 \"data-requires-python\" values in HTML links. Defaults\n            to False.\n        \"\"\"\n        if ignore_requires_python is None:\n            ignore_requires_python = False\n\n        self._allow_yanked = allow_yanked\n        self._canonical_name = canonical_name\n        self._ignore_requires_python = ignore_requires_python\n        self._formats = formats\n        self._target_python = target_python\n\n        self.project_name = project_name\n\n    def evaluate_link(self, link: Link) -> Tuple[LinkType, str]:\n        \"\"\"\n        Determine whether a link is a candidate for installation.\n\n        :return: A tuple (result, detail), where *result* is an enum\n            representing whether the evaluation found a candidate, or the reason\n            why one is not found. If a candidate is found, *detail* will be the\n            candidate's version string; if one is not found, it contains the\n            reason the link fails to qualify.\n        \"\"\"\n        version = None\n        if link.is_yanked and not self._allow_yanked:\n            reason = link.yanked_reason or \"<none given>\"\n            return (LinkType.yanked, f\"yanked for reason: {reason}\")\n\n        if link.egg_fragment:\n            egg_info = link.egg_fragment\n            ext = link.ext\n        else:\n            egg_info, ext = link.splitext()\n            if not ext:\n                return (LinkType.format_unsupported, \"not a file\")\n            if ext not in SUPPORTED_EXTENSIONS:\n                return (\n                    LinkType.format_unsupported,\n                    f\"unsupported archive format: {ext}\",\n                )\n            if \"binary\" not in self._formats and ext == WHEEL_EXTENSION:\n                reason = f\"No binaries permitted for {self.project_name}\"\n                return (LinkType.format_unsupported, reason)\n            if \"macosx10\" in link.path and ext == \".zip\":\n                return (LinkType.format_unsupported, \"macosx10 one\")\n            if ext == WHEEL_EXTENSION:\n                try:\n                    wheel = Wheel(link.filename)\n                except InvalidWheelFilename:\n                    return (\n                        LinkType.format_invalid,\n                        \"invalid wheel filename\",\n                    )\n                if canonicalize_name(wheel.name) != self._canonical_name:\n                    reason = f\"wrong project name (not {self.project_name})\"\n                    return (LinkType.different_project, reason)\n\n                supported_tags = self._target_python.get_tags()\n                if not wheel.supported(supported_tags):\n                    # Include the wheel's tags in the reason string to\n                    # simplify troubleshooting compatibility issues.\n                    file_tags = \", \".join(wheel.get_formatted_file_tags())\n                    reason = (\n                        f\"none of the wheel's tags ({file_tags}) are compatible \"\n                        f\"(run pip debug --verbose to show compatible tags)\"\n                    )\n                    return (LinkType.platform_mismatch, reason)\n\n                version = wheel.version\n\n        # This should be up by the self.ok_binary check, but see issue 2700.\n        if \"source\" not in self._formats and ext != WHEEL_EXTENSION:\n            reason = f\"No sources permitted for {self.project_name}\"\n            return (LinkType.format_unsupported, reason)\n\n        if not version:\n            version = _extract_version_from_fragment(\n                egg_info,\n                self._canonical_name,\n            )\n        if not version:\n            reason = f\"Missing project version for {self.project_name}\"\n            return (LinkType.format_invalid, reason)\n\n        match = self._py_version_re.search(version)\n        if match:\n            version = version[: match.start()]\n            py_version = match.group(1)\n            if py_version != self._target_python.py_version:\n                return (\n                    LinkType.platform_mismatch,\n                    \"Python version is incorrect\",\n                )\n\n        supports_python = _check_link_requires_python(\n            link,\n            version_info=self._target_python.py_version_info,\n            ignore_requires_python=self._ignore_requires_python,\n        )\n        if not supports_python:\n            reason = f\"{version} Requires-Python {link.requires_python}\"\n            return (LinkType.requires_python_mismatch, reason)\n\n        logger.debug(\"Found link %s, version: %s\", link, version)\n\n        return (LinkType.candidate, version)\n\n\ndef filter_unallowed_hashes(\n    candidates: List[InstallationCandidate],\n    hashes: Hashes,\n    project_name: str,\n) -> List[InstallationCandidate]:\n    \"\"\"\n    Filter out candidates whose hashes aren't allowed, and return a new\n    list of candidates.\n\n    If at least one candidate has an allowed hash, then all candidates with\n    either an allowed hash or no hash specified are returned.  Otherwise,\n    the given candidates are returned.\n\n    Including the candidates with no hash specified when there is a match\n    allows a warning to be logged if there is a more preferred candidate\n    with no hash specified.  Returning all candidates in the case of no\n    matches lets pip report the hash of the candidate that would otherwise\n    have been installed (e.g. permitting the user to more easily update\n    their requirements file with the desired hash).\n    \"\"\"\n    if not hashes:\n        logger.debug(\n            \"Given no hashes to check %s links for project %r: \"\n            \"discarding no candidates\",\n            len(candidates),\n            project_name,\n        )\n        # Make sure we're not returning back the given value.\n        return list(candidates)\n\n    matches_or_no_digest = []\n    # Collect the non-matches for logging purposes.\n    non_matches = []\n    match_count = 0\n    for candidate in candidates:\n        link = candidate.link\n        if not link.has_hash:\n            pass\n        elif link.is_hash_allowed(hashes=hashes):\n            match_count += 1\n        else:\n            non_matches.append(candidate)\n            continue\n\n        matches_or_no_digest.append(candidate)\n\n    if match_count:\n        filtered = matches_or_no_digest\n    else:\n        # Make sure we're not returning back the given value.\n        filtered = list(candidates)\n\n    if len(filtered) == len(candidates):\n        discard_message = \"discarding no candidates\"\n    else:\n        discard_message = \"discarding {} non-matches:\\n  {}\".format(\n            len(non_matches),\n            \"\\n  \".join(str(candidate.link) for candidate in non_matches),\n        )\n\n    logger.debug(\n        \"Checked %s links for project %r against %s hashes \"\n        \"(%s matches, %s no digest): %s\",\n        len(candidates),\n        project_name,\n        hashes.digest_count,\n        match_count,\n        len(matches_or_no_digest) - match_count,\n        discard_message,\n    )\n\n    return filtered\n\n\nclass CandidatePreferences:\n\n    \"\"\"\n    Encapsulates some of the preferences for filtering and sorting\n    InstallationCandidate objects.\n    \"\"\"\n\n    def __init__(\n        self,\n        prefer_binary: bool = False,\n        allow_all_prereleases: bool = False,\n    ) -> None:\n        \"\"\"\n        :param allow_all_prereleases: Whether to allow all pre-releases.\n        \"\"\"\n        self.allow_all_prereleases = allow_all_prereleases\n        self.prefer_binary = prefer_binary\n\n\nclass BestCandidateResult:\n    \"\"\"A collection of candidates, returned by `PackageFinder.find_best_candidate`.\n\n    This class is only intended to be instantiated by CandidateEvaluator's\n    `compute_best_candidate()` method.\n    \"\"\"\n\n    def __init__(\n        self,\n        candidates: List[InstallationCandidate],\n        applicable_candidates: List[InstallationCandidate],\n        best_candidate: Optional[InstallationCandidate],\n    ) -> None:\n        \"\"\"\n        :param candidates: A sequence of all available candidates found.\n        :param applicable_candidates: The applicable candidates.\n        :param best_candidate: The most preferred candidate found, or None\n            if no applicable candidates were found.\n        \"\"\"\n        assert set(applicable_candidates) <= set(candidates)\n\n        if best_candidate is None:\n            assert not applicable_candidates\n        else:\n            assert best_candidate in applicable_candidates\n\n        self._applicable_candidates = applicable_candidates\n        self._candidates = candidates\n\n        self.best_candidate = best_candidate\n\n    def iter_all(self) -> Iterable[InstallationCandidate]:\n        \"\"\"Iterate through all candidates.\"\"\"\n        return iter(self._candidates)\n\n    def iter_applicable(self) -> Iterable[InstallationCandidate]:\n        \"\"\"Iterate through the applicable candidates.\"\"\"\n        return iter(self._applicable_candidates)\n\n\nclass CandidateEvaluator:\n\n    \"\"\"\n    Responsible for filtering and sorting candidates for installation based\n    on what tags are valid.\n    \"\"\"\n\n    @classmethod\n    def create(\n        cls,\n        project_name: str,\n        target_python: Optional[TargetPython] = None,\n        prefer_binary: bool = False,\n        allow_all_prereleases: bool = False,\n        specifier: Optional[specifiers.BaseSpecifier] = None,\n        hashes: Optional[Hashes] = None,\n    ) -> \"CandidateEvaluator\":\n        \"\"\"Create a CandidateEvaluator object.\n\n        :param target_python: The target Python interpreter to use when\n            checking compatibility. If None (the default), a TargetPython\n            object will be constructed from the running Python.\n        :param specifier: An optional object implementing `filter`\n            (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable\n            versions.\n        :param hashes: An optional collection of allowed hashes.\n        \"\"\"\n        if target_python is None:\n            target_python = TargetPython()\n        if specifier is None:\n            specifier = specifiers.SpecifierSet()\n\n        supported_tags = target_python.get_tags()\n\n        return cls(\n            project_name=project_name,\n            supported_tags=supported_tags,\n            specifier=specifier,\n            prefer_binary=prefer_binary,\n            allow_all_prereleases=allow_all_prereleases,\n            hashes=hashes,\n        )\n\n    def __init__(\n        self,\n        project_name: str,\n        supported_tags: List[Tag],\n        specifier: specifiers.BaseSpecifier,\n        prefer_binary: bool = False,\n        allow_all_prereleases: bool = False,\n        hashes: Optional[Hashes] = None,\n    ) -> None:\n        \"\"\"\n        :param supported_tags: The PEP 425 tags supported by the target\n            Python in order of preference (most preferred first).\n        \"\"\"\n        self._allow_all_prereleases = allow_all_prereleases\n        self._hashes = hashes\n        self._prefer_binary = prefer_binary\n        self._project_name = project_name\n        self._specifier = specifier\n        self._supported_tags = supported_tags\n        # Since the index of the tag in the _supported_tags list is used\n        # as a priority, precompute a map from tag to index/priority to be\n        # used in wheel.find_most_preferred_tag.\n        self._wheel_tag_preferences = {\n            tag: idx for idx, tag in enumerate(supported_tags)\n        }\n\n    def get_applicable_candidates(\n        self,\n        candidates: List[InstallationCandidate],\n    ) -> List[InstallationCandidate]:\n        \"\"\"\n        Return the applicable candidates from a list of candidates.\n        \"\"\"\n        # Using None infers from the specifier instead.\n        allow_prereleases = self._allow_all_prereleases or None\n        specifier = self._specifier\n        versions = {\n            str(v)\n            for v in specifier.filter(\n                # We turn the version object into a str here because otherwise\n                # when we're debundled but setuptools isn't, Python will see\n                # packaging.version.Version and\n                # pkg_resources._vendor.packaging.version.Version as different\n                # types. This way we'll use a str as a common data interchange\n                # format. If we stop using the pkg_resources provided specifier\n                # and start using our own, we can drop the cast to str().\n                (str(c.version) for c in candidates),\n                prereleases=allow_prereleases,\n            )\n        }\n\n        # Again, converting version to str to deal with debundling.\n        applicable_candidates = [c for c in candidates if str(c.version) in versions]\n\n        filtered_applicable_candidates = filter_unallowed_hashes(\n            candidates=applicable_candidates,\n            hashes=self._hashes,\n            project_name=self._project_name,\n        )\n\n        return sorted(filtered_applicable_candidates, key=self._sort_key)\n\n    def _sort_key(self, candidate: InstallationCandidate) -> CandidateSortingKey:\n        \"\"\"\n        Function to pass as the `key` argument to a call to sorted() to sort\n        InstallationCandidates by preference.\n\n        Returns a tuple such that tuples sorting as greater using Python's\n        default comparison operator are more preferred.\n\n        The preference is as follows:\n\n        First and foremost, candidates with allowed (matching) hashes are\n        always preferred over candidates without matching hashes. This is\n        because e.g. if the only candidate with an allowed hash is yanked,\n        we still want to use that candidate.\n\n        Second, excepting hash considerations, candidates that have been\n        yanked (in the sense of PEP 592) are always less preferred than\n        candidates that haven't been yanked. Then:\n\n        If not finding wheels, they are sorted by version only.\n        If finding wheels, then the sort order is by version, then:\n          1. existing installs\n          2. wheels ordered via Wheel.support_index_min(self._supported_tags)\n          3. source archives\n        If prefer_binary was set, then all wheels are sorted above sources.\n\n        Note: it was considered to embed this logic into the Link\n              comparison operators, but then different sdist links\n              with the same version, would have to be considered equal\n        \"\"\"\n        valid_tags = self._supported_tags\n        support_num = len(valid_tags)\n        build_tag: BuildTag = ()\n        binary_preference = 0\n        link = candidate.link\n        if link.is_wheel:\n            # can raise InvalidWheelFilename\n            wheel = Wheel(link.filename)\n            try:\n                pri = -(\n                    wheel.find_most_preferred_tag(\n                        valid_tags, self._wheel_tag_preferences\n                    )\n                )\n            except ValueError:\n                raise UnsupportedWheel(\n                    \"{} is not a supported wheel for this platform. It \"\n                    \"can't be sorted.\".format(wheel.filename)\n                )\n            if self._prefer_binary:\n                binary_preference = 1\n            if wheel.build_tag is not None:\n                match = re.match(r\"^(\\d+)(.*)$\", wheel.build_tag)\n                build_tag_groups = match.groups()\n                build_tag = (int(build_tag_groups[0]), build_tag_groups[1])\n        else:  # sdist\n            pri = -(support_num)\n        has_allowed_hash = int(link.is_hash_allowed(self._hashes))\n        yank_value = -1 * int(link.is_yanked)  # -1 for yanked.\n        return (\n            has_allowed_hash,\n            yank_value,\n            binary_preference,\n            candidate.version,\n            pri,\n            build_tag,\n        )\n\n    def sort_best_candidate(\n        self,\n        candidates: List[InstallationCandidate],\n    ) -> Optional[InstallationCandidate]:\n        \"\"\"\n        Return the best candidate per the instance's sort order, or None if\n        no candidate is acceptable.\n        \"\"\"\n        if not candidates:\n            return None\n        best_candidate = max(candidates, key=self._sort_key)\n        return best_candidate\n\n    def compute_best_candidate(\n        self,\n        candidates: List[InstallationCandidate],\n    ) -> BestCandidateResult:\n        \"\"\"\n        Compute and return a `BestCandidateResult` instance.\n        \"\"\"\n        applicable_candidates = self.get_applicable_candidates(candidates)\n\n        best_candidate = self.sort_best_candidate(applicable_candidates)\n\n        return BestCandidateResult(\n            candidates,\n            applicable_candidates=applicable_candidates,\n            best_candidate=best_candidate,\n        )\n\n\nclass PackageFinder:\n    \"\"\"This finds packages.\n\n    This is meant to match easy_install's technique for looking for\n    packages, by reading pages and looking for appropriate links.\n    \"\"\"\n\n    def __init__(\n        self,\n        link_collector: LinkCollector,\n        target_python: TargetPython,\n        allow_yanked: bool,\n        format_control: Optional[FormatControl] = None,\n        candidate_prefs: Optional[CandidatePreferences] = None,\n        ignore_requires_python: Optional[bool] = None,\n    ) -> None:\n        \"\"\"\n        This constructor is primarily meant to be used by the create() class\n        method and from tests.\n\n        :param format_control: A FormatControl object, used to control\n            the selection of source packages / binary packages when consulting\n            the index and links.\n        :param candidate_prefs: Options to use when creating a\n            CandidateEvaluator object.\n        \"\"\"\n        if candidate_prefs is None:\n            candidate_prefs = CandidatePreferences()\n\n        format_control = format_control or FormatControl(set(), set())\n\n        self._allow_yanked = allow_yanked\n        self._candidate_prefs = candidate_prefs\n        self._ignore_requires_python = ignore_requires_python\n        self._link_collector = link_collector\n        self._target_python = target_python\n\n        self.format_control = format_control\n\n        # These are boring links that have already been logged somehow.\n        self._logged_links: Set[Tuple[Link, LinkType, str]] = set()\n\n    # Don't include an allow_yanked default value to make sure each call\n    # site considers whether yanked releases are allowed. This also causes\n    # that decision to be made explicit in the calling code, which helps\n    # people when reading the code.\n    @classmethod\n    def create(\n        cls,\n        link_collector: LinkCollector,\n        selection_prefs: SelectionPreferences,\n        target_python: Optional[TargetPython] = None,\n    ) -> \"PackageFinder\":\n        \"\"\"Create a PackageFinder.\n\n        :param selection_prefs: The candidate selection preferences, as a\n            SelectionPreferences object.\n        :param target_python: The target Python interpreter to use when\n            checking compatibility. If None (the default), a TargetPython\n            object will be constructed from the running Python.\n        \"\"\"\n        if target_python is None:\n            target_python = TargetPython()\n\n        candidate_prefs = CandidatePreferences(\n            prefer_binary=selection_prefs.prefer_binary,\n            allow_all_prereleases=selection_prefs.allow_all_prereleases,\n        )\n\n        return cls(\n            candidate_prefs=candidate_prefs,\n            link_collector=link_collector,\n            target_python=target_python,\n            allow_yanked=selection_prefs.allow_yanked,\n            format_control=selection_prefs.format_control,\n            ignore_requires_python=selection_prefs.ignore_requires_python,\n        )\n\n    @property\n    def target_python(self) -> TargetPython:\n        return self._target_python\n\n    @property\n    def search_scope(self) -> SearchScope:\n        return self._link_collector.search_scope\n\n    @search_scope.setter\n    def search_scope(self, search_scope: SearchScope) -> None:\n        self._link_collector.search_scope = search_scope\n\n    @property\n    def find_links(self) -> List[str]:\n        return self._link_collector.find_links\n\n    @property\n    def index_urls(self) -> List[str]:\n        return self.search_scope.index_urls\n\n    @property\n    def trusted_hosts(self) -> Iterable[str]:\n        for host_port in self._link_collector.session.pip_trusted_origins:\n            yield build_netloc(*host_port)\n\n    @property\n    def allow_all_prereleases(self) -> bool:\n        return self._candidate_prefs.allow_all_prereleases\n\n    def set_allow_all_prereleases(self) -> None:\n        self._candidate_prefs.allow_all_prereleases = True\n\n    @property\n    def prefer_binary(self) -> bool:\n        return self._candidate_prefs.prefer_binary\n\n    def set_prefer_binary(self) -> None:\n        self._candidate_prefs.prefer_binary = True\n\n    def requires_python_skipped_reasons(self) -> List[str]:\n        reasons = {\n            detail\n            for _, result, detail in self._logged_links\n            if result == LinkType.requires_python_mismatch\n        }\n        return sorted(reasons)\n\n    def make_link_evaluator(self, project_name: str) -> LinkEvaluator:\n        canonical_name = canonicalize_name(project_name)\n        formats = self.format_control.get_allowed_formats(canonical_name)\n\n        return LinkEvaluator(\n            project_name=project_name,\n            canonical_name=canonical_name,\n            formats=formats,\n            target_python=self._target_python,\n            allow_yanked=self._allow_yanked,\n            ignore_requires_python=self._ignore_requires_python,\n        )\n\n    def _sort_links(self, links: Iterable[Link]) -> List[Link]:\n        \"\"\"\n        Returns elements of links in order, non-egg links first, egg links\n        second, while eliminating duplicates\n        \"\"\"\n        eggs, no_eggs = [], []\n        seen: Set[Link] = set()\n        for link in links:\n            if link not in seen:\n                seen.add(link)\n                if link.egg_fragment:\n                    eggs.append(link)\n                else:\n                    no_eggs.append(link)\n        return no_eggs + eggs\n\n    def _log_skipped_link(self, link: Link, result: LinkType, detail: str) -> None:\n        entry = (link, result, detail)\n        if entry not in self._logged_links:\n            # Put the link at the end so the reason is more visible and because\n            # the link string is usually very long.\n            logger.debug(\"Skipping link: %s: %s\", detail, link)\n            self._logged_links.add(entry)\n\n    def get_install_candidate(\n        self, link_evaluator: LinkEvaluator, link: Link\n    ) -> Optional[InstallationCandidate]:\n        \"\"\"\n        If the link is a candidate for install, convert it to an\n        InstallationCandidate and return it. Otherwise, return None.\n        \"\"\"\n        result, detail = link_evaluator.evaluate_link(link)\n        if result != LinkType.candidate:\n            self._log_skipped_link(link, result, detail)\n            return None\n\n        return InstallationCandidate(\n            name=link_evaluator.project_name,\n            link=link,\n            version=detail,\n        )\n\n    def evaluate_links(\n        self, link_evaluator: LinkEvaluator, links: Iterable[Link]\n    ) -> List[InstallationCandidate]:\n        \"\"\"\n        Convert links that are candidates to InstallationCandidate objects.\n        \"\"\"\n        candidates = []\n        for link in self._sort_links(links):\n            candidate = self.get_install_candidate(link_evaluator, link)\n            if candidate is not None:\n                candidates.append(candidate)\n\n        return candidates\n\n    def process_project_url(\n        self, project_url: Link, link_evaluator: LinkEvaluator\n    ) -> List[InstallationCandidate]:\n        logger.debug(\n            \"Fetching project page and analyzing links: %s\",\n            project_url,\n        )\n        index_response = self._link_collector.fetch_response(project_url)\n        if index_response is None:\n            return []\n\n        page_links = list(parse_links(index_response))\n\n        with indent_log():\n            package_links = self.evaluate_links(\n                link_evaluator,\n                links=page_links,\n            )\n\n        return package_links\n\n    @functools.lru_cache(maxsize=None)\n    def find_all_candidates(self, project_name: str) -> List[InstallationCandidate]:\n        \"\"\"Find all available InstallationCandidate for project_name\n\n        This checks index_urls and find_links.\n        All versions found are returned as an InstallationCandidate list.\n\n        See LinkEvaluator.evaluate_link() for details on which files\n        are accepted.\n        \"\"\"\n        link_evaluator = self.make_link_evaluator(project_name)\n\n        collected_sources = self._link_collector.collect_sources(\n            project_name=project_name,\n            candidates_from_page=functools.partial(\n                self.process_project_url,\n                link_evaluator=link_evaluator,\n            ),\n        )\n\n        page_candidates_it = itertools.chain.from_iterable(\n            source.page_candidates()\n            for sources in collected_sources\n            for source in sources\n            if source is not None\n        )\n        page_candidates = list(page_candidates_it)\n\n        file_links_it = itertools.chain.from_iterable(\n            source.file_links()\n            for sources in collected_sources\n            for source in sources\n            if source is not None\n        )\n        file_candidates = self.evaluate_links(\n            link_evaluator,\n            sorted(file_links_it, reverse=True),\n        )\n\n        if logger.isEnabledFor(logging.DEBUG) and file_candidates:\n            paths = []\n            for candidate in file_candidates:\n                assert candidate.link.url  # we need to have a URL\n                try:\n                    paths.append(candidate.link.file_path)\n                except Exception:\n                    paths.append(candidate.link.url)  # it's not a local file\n\n            logger.debug(\"Local files found: %s\", \", \".join(paths))\n\n        # This is an intentional priority ordering\n        return file_candidates + page_candidates\n\n    def make_candidate_evaluator(\n        self,\n        project_name: str,\n        specifier: Optional[specifiers.BaseSpecifier] = None,\n        hashes: Optional[Hashes] = None,\n    ) -> CandidateEvaluator:\n        \"\"\"Create a CandidateEvaluator object to use.\"\"\"\n        candidate_prefs = self._candidate_prefs\n        return CandidateEvaluator.create(\n            project_name=project_name,\n            target_python=self._target_python,\n            prefer_binary=candidate_prefs.prefer_binary,\n            allow_all_prereleases=candidate_prefs.allow_all_prereleases,\n            specifier=specifier,\n            hashes=hashes,\n        )\n\n    @functools.lru_cache(maxsize=None)\n    def find_best_candidate(\n        self,\n        project_name: str,\n        specifier: Optional[specifiers.BaseSpecifier] = None,\n        hashes: Optional[Hashes] = None,\n    ) -> BestCandidateResult:\n        \"\"\"Find matches for the given project and specifier.\n\n        :param specifier: An optional object implementing `filter`\n            (e.g. `packaging.specifiers.SpecifierSet`) to filter applicable\n            versions.\n\n        :return: A `BestCandidateResult` instance.\n        \"\"\"\n        candidates = self.find_all_candidates(project_name)\n        candidate_evaluator = self.make_candidate_evaluator(\n            project_name=project_name,\n            specifier=specifier,\n            hashes=hashes,\n        )\n        return candidate_evaluator.compute_best_candidate(candidates)\n\n    def find_requirement(\n        self, req: InstallRequirement, upgrade: bool\n    ) -> Optional[InstallationCandidate]:\n        \"\"\"Try to find a Link matching req\n\n        Expects req, an InstallRequirement and upgrade, a boolean\n        Returns a InstallationCandidate if found,\n        Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise\n        \"\"\"\n        hashes = req.hashes(trust_internet=False)\n        best_candidate_result = self.find_best_candidate(\n            req.name,\n            specifier=req.specifier,\n            hashes=hashes,\n        )\n        best_candidate = best_candidate_result.best_candidate\n\n        installed_version: Optional[_BaseVersion] = None\n        if req.satisfied_by is not None:\n            installed_version = req.satisfied_by.version\n\n        def _format_versions(cand_iter: Iterable[InstallationCandidate]) -> str:\n            # This repeated parse_version and str() conversion is needed to\n            # handle different vendoring sources from pip and pkg_resources.\n            # If we stop using the pkg_resources provided specifier and start\n            # using our own, we can drop the cast to str().\n            return (\n                \", \".join(\n                    sorted(\n                        {str(c.version) for c in cand_iter},\n                        key=parse_version,\n                    )\n                )\n                or \"none\"\n            )\n\n        if installed_version is None and best_candidate is None:\n            logger.critical(\n                \"Could not find a version that satisfies the requirement %s \"\n                \"(from versions: %s)\",\n                req,\n                _format_versions(best_candidate_result.iter_all()),\n            )\n\n            raise DistributionNotFound(\n                \"No matching distribution found for {}\".format(req)\n            )\n\n        best_installed = False\n        if installed_version and (\n            best_candidate is None or best_candidate.version <= installed_version\n        ):\n            best_installed = True\n\n        if not upgrade and installed_version is not None:\n            if best_installed:\n                logger.debug(\n                    \"Existing installed version (%s) is most up-to-date and \"\n                    \"satisfies requirement\",\n                    installed_version,\n                )\n            else:\n                logger.debug(\n                    \"Existing installed version (%s) satisfies requirement \"\n                    \"(most up-to-date version is %s)\",\n                    installed_version,\n                    best_candidate.version,\n                )\n            return None\n\n        if best_installed:\n            # We have an existing version, and its the best version\n            logger.debug(\n                \"Installed version (%s) is most up-to-date (past versions: %s)\",\n                installed_version,\n                _format_versions(best_candidate_result.iter_applicable()),\n            )\n            raise BestVersionAlreadyInstalled\n\n        logger.debug(\n            \"Using version %s (newest of versions: %s)\",\n            best_candidate.version,\n            _format_versions(best_candidate_result.iter_applicable()),\n        )\n        return best_candidate\n\n\ndef _find_name_version_sep(fragment: str, canonical_name: str) -> int:\n    \"\"\"Find the separator's index based on the package's canonical name.\n\n    :param fragment: A <package>+<version> filename \"fragment\" (stem) or\n        egg fragment.\n    :param canonical_name: The package's canonical name.\n\n    This function is needed since the canonicalized name does not necessarily\n    have the same length as the egg info's name part. An example::\n\n    >>> fragment = 'foo__bar-1.0'\n    >>> canonical_name = 'foo-bar'\n    >>> _find_name_version_sep(fragment, canonical_name)\n    8\n    \"\"\"\n    # Project name and version must be separated by one single dash. Find all\n    # occurrences of dashes; if the string in front of it matches the canonical\n    # name, this is the one separating the name and version parts.\n    for i, c in enumerate(fragment):\n        if c != \"-\":\n            continue\n        if canonicalize_name(fragment[:i]) == canonical_name:\n            return i\n    raise ValueError(f\"{fragment} does not match {canonical_name}\")\n\n\ndef _extract_version_from_fragment(fragment: str, canonical_name: str) -> Optional[str]:\n    \"\"\"Parse the version string from a <package>+<version> filename\n    \"fragment\" (stem) or egg fragment.\n\n    :param fragment: The string to parse. E.g. foo-2.1\n    :param canonical_name: The canonicalized name of the package this\n        belongs to.\n    \"\"\"\n    try:\n        version_start = _find_name_version_sep(fragment, canonical_name) + 1\n    except ValueError:\n        return None\n    version = fragment[version_start:]\n    if not version:\n        return None\n    return version\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/index/sources.py",
    "content": "import logging\nimport mimetypes\nimport os\nimport pathlib\nfrom typing import Callable, Iterable, Optional, Tuple\n\nfrom pip._internal.models.candidate import InstallationCandidate\nfrom pip._internal.models.link import Link\nfrom pip._internal.utils.urls import path_to_url, url_to_path\nfrom pip._internal.vcs import is_url\n\nlogger = logging.getLogger(__name__)\n\nFoundCandidates = Iterable[InstallationCandidate]\nFoundLinks = Iterable[Link]\nCandidatesFromPage = Callable[[Link], Iterable[InstallationCandidate]]\nPageValidator = Callable[[Link], bool]\n\n\nclass LinkSource:\n    @property\n    def link(self) -> Optional[Link]:\n        \"\"\"Returns the underlying link, if there's one.\"\"\"\n        raise NotImplementedError()\n\n    def page_candidates(self) -> FoundCandidates:\n        \"\"\"Candidates found by parsing an archive listing HTML file.\"\"\"\n        raise NotImplementedError()\n\n    def file_links(self) -> FoundLinks:\n        \"\"\"Links found by specifying archives directly.\"\"\"\n        raise NotImplementedError()\n\n\ndef _is_html_file(file_url: str) -> bool:\n    return mimetypes.guess_type(file_url, strict=False)[0] == \"text/html\"\n\n\nclass _FlatDirectorySource(LinkSource):\n    \"\"\"Link source specified by ``--find-links=<path-to-dir>``.\n\n    This looks the content of the directory, and returns:\n\n    * ``page_candidates``: Links listed on each HTML file in the directory.\n    * ``file_candidates``: Archives in the directory.\n    \"\"\"\n\n    def __init__(\n        self,\n        candidates_from_page: CandidatesFromPage,\n        path: str,\n    ) -> None:\n        self._candidates_from_page = candidates_from_page\n        self._path = pathlib.Path(os.path.realpath(path))\n\n    @property\n    def link(self) -> Optional[Link]:\n        return None\n\n    def page_candidates(self) -> FoundCandidates:\n        for path in self._path.iterdir():\n            url = path_to_url(str(path))\n            if not _is_html_file(url):\n                continue\n            yield from self._candidates_from_page(Link(url))\n\n    def file_links(self) -> FoundLinks:\n        for path in self._path.iterdir():\n            url = path_to_url(str(path))\n            if _is_html_file(url):\n                continue\n            yield Link(url)\n\n\nclass _LocalFileSource(LinkSource):\n    \"\"\"``--find-links=<path-or-url>`` or ``--[extra-]index-url=<path-or-url>``.\n\n    If a URL is supplied, it must be a ``file:`` URL. If a path is supplied to\n    the option, it is converted to a URL first. This returns:\n\n    * ``page_candidates``: Links listed on an HTML file.\n    * ``file_candidates``: The non-HTML file.\n    \"\"\"\n\n    def __init__(\n        self,\n        candidates_from_page: CandidatesFromPage,\n        link: Link,\n    ) -> None:\n        self._candidates_from_page = candidates_from_page\n        self._link = link\n\n    @property\n    def link(self) -> Optional[Link]:\n        return self._link\n\n    def page_candidates(self) -> FoundCandidates:\n        if not _is_html_file(self._link.url):\n            return\n        yield from self._candidates_from_page(self._link)\n\n    def file_links(self) -> FoundLinks:\n        if _is_html_file(self._link.url):\n            return\n        yield self._link\n\n\nclass _RemoteFileSource(LinkSource):\n    \"\"\"``--find-links=<url>`` or ``--[extra-]index-url=<url>``.\n\n    This returns:\n\n    * ``page_candidates``: Links listed on an HTML file.\n    * ``file_candidates``: The non-HTML file.\n    \"\"\"\n\n    def __init__(\n        self,\n        candidates_from_page: CandidatesFromPage,\n        page_validator: PageValidator,\n        link: Link,\n    ) -> None:\n        self._candidates_from_page = candidates_from_page\n        self._page_validator = page_validator\n        self._link = link\n\n    @property\n    def link(self) -> Optional[Link]:\n        return self._link\n\n    def page_candidates(self) -> FoundCandidates:\n        if not self._page_validator(self._link):\n            return\n        yield from self._candidates_from_page(self._link)\n\n    def file_links(self) -> FoundLinks:\n        yield self._link\n\n\nclass _IndexDirectorySource(LinkSource):\n    \"\"\"``--[extra-]index-url=<path-to-directory>``.\n\n    This is treated like a remote URL; ``candidates_from_page`` contains logic\n    for this by appending ``index.html`` to the link.\n    \"\"\"\n\n    def __init__(\n        self,\n        candidates_from_page: CandidatesFromPage,\n        link: Link,\n    ) -> None:\n        self._candidates_from_page = candidates_from_page\n        self._link = link\n\n    @property\n    def link(self) -> Optional[Link]:\n        return self._link\n\n    def page_candidates(self) -> FoundCandidates:\n        yield from self._candidates_from_page(self._link)\n\n    def file_links(self) -> FoundLinks:\n        return ()\n\n\ndef build_source(\n    location: str,\n    *,\n    candidates_from_page: CandidatesFromPage,\n    page_validator: PageValidator,\n    expand_dir: bool,\n    cache_link_parsing: bool,\n) -> Tuple[Optional[str], Optional[LinkSource]]:\n\n    path: Optional[str] = None\n    url: Optional[str] = None\n    if os.path.exists(location):  # Is a local path.\n        url = path_to_url(location)\n        path = location\n    elif location.startswith(\"file:\"):  # A file: URL.\n        url = location\n        path = url_to_path(location)\n    elif is_url(location):\n        url = location\n\n    if url is None:\n        msg = (\n            \"Location '%s' is ignored: \"\n            \"it is either a non-existing path or lacks a specific scheme.\"\n        )\n        logger.warning(msg, location)\n        return (None, None)\n\n    if path is None:\n        source: LinkSource = _RemoteFileSource(\n            candidates_from_page=candidates_from_page,\n            page_validator=page_validator,\n            link=Link(url, cache_link_parsing=cache_link_parsing),\n        )\n        return (url, source)\n\n    if os.path.isdir(path):\n        if expand_dir:\n            source = _FlatDirectorySource(\n                candidates_from_page=candidates_from_page,\n                path=path,\n            )\n        else:\n            source = _IndexDirectorySource(\n                candidates_from_page=candidates_from_page,\n                link=Link(url, cache_link_parsing=cache_link_parsing),\n            )\n        return (url, source)\n    elif os.path.isfile(path):\n        source = _LocalFileSource(\n            candidates_from_page=candidates_from_page,\n            link=Link(url, cache_link_parsing=cache_link_parsing),\n        )\n        return (url, source)\n    logger.warning(\n        \"Location '%s' is ignored: it is neither a file nor a directory.\",\n        location,\n    )\n    return (url, None)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/locations/__init__.py",
    "content": "import functools\nimport logging\nimport os\nimport pathlib\nimport sys\nimport sysconfig\nfrom typing import Any, Dict, Generator, List, Optional, Tuple\n\nfrom pip._internal.models.scheme import SCHEME_KEYS, Scheme\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.deprecation import deprecated\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\nfrom . import _sysconfig\nfrom .base import (\n    USER_CACHE_DIR,\n    get_major_minor_version,\n    get_src_prefix,\n    is_osx_framework,\n    site_packages,\n    user_site,\n)\n\n__all__ = [\n    \"USER_CACHE_DIR\",\n    \"get_bin_prefix\",\n    \"get_bin_user\",\n    \"get_major_minor_version\",\n    \"get_platlib\",\n    \"get_prefixed_libs\",\n    \"get_purelib\",\n    \"get_scheme\",\n    \"get_src_prefix\",\n    \"site_packages\",\n    \"user_site\",\n]\n\n\nlogger = logging.getLogger(__name__)\n\n\n_PLATLIBDIR: str = getattr(sys, \"platlibdir\", \"lib\")\n\n_USE_SYSCONFIG_DEFAULT = sys.version_info >= (3, 10)\n\n\ndef _should_use_sysconfig() -> bool:\n    \"\"\"This function determines the value of _USE_SYSCONFIG.\n\n    By default, pip uses sysconfig on Python 3.10+.\n    But Python distributors can override this decision by setting:\n        sysconfig._PIP_USE_SYSCONFIG = True / False\n    Rationale in https://github.com/pypa/pip/issues/10647\n\n    This is a function for testability, but should be constant during any one\n    run.\n    \"\"\"\n    return bool(getattr(sysconfig, \"_PIP_USE_SYSCONFIG\", _USE_SYSCONFIG_DEFAULT))\n\n\n_USE_SYSCONFIG = _should_use_sysconfig()\n\nif not _USE_SYSCONFIG:\n    # Import distutils lazily to avoid deprecation warnings,\n    # but import it soon enough that it is in memory and available during\n    # a pip reinstall.\n    from . import _distutils\n\n# Be noisy about incompatibilities if this platforms \"should\" be using\n# sysconfig, but is explicitly opting out and using distutils instead.\nif _USE_SYSCONFIG_DEFAULT and not _USE_SYSCONFIG:\n    _MISMATCH_LEVEL = logging.WARNING\nelse:\n    _MISMATCH_LEVEL = logging.DEBUG\n\n\ndef _looks_like_bpo_44860() -> bool:\n    \"\"\"The resolution to bpo-44860 will change this incorrect platlib.\n\n    See <https://bugs.python.org/issue44860>.\n    \"\"\"\n    from distutils.command.install import INSTALL_SCHEMES\n\n    try:\n        unix_user_platlib = INSTALL_SCHEMES[\"unix_user\"][\"platlib\"]\n    except KeyError:\n        return False\n    return unix_user_platlib == \"$usersite\"\n\n\ndef _looks_like_red_hat_patched_platlib_purelib(scheme: Dict[str, str]) -> bool:\n    platlib = scheme[\"platlib\"]\n    if \"/$platlibdir/\" in platlib:\n        platlib = platlib.replace(\"/$platlibdir/\", f\"/{_PLATLIBDIR}/\")\n    if \"/lib64/\" not in platlib:\n        return False\n    unpatched = platlib.replace(\"/lib64/\", \"/lib/\")\n    return unpatched.replace(\"$platbase/\", \"$base/\") == scheme[\"purelib\"]\n\n\n@functools.lru_cache(maxsize=None)\ndef _looks_like_red_hat_lib() -> bool:\n    \"\"\"Red Hat patches platlib in unix_prefix and unix_home, but not purelib.\n\n    This is the only way I can see to tell a Red Hat-patched Python.\n    \"\"\"\n    from distutils.command.install import INSTALL_SCHEMES\n\n    return all(\n        k in INSTALL_SCHEMES\n        and _looks_like_red_hat_patched_platlib_purelib(INSTALL_SCHEMES[k])\n        for k in (\"unix_prefix\", \"unix_home\")\n    )\n\n\n@functools.lru_cache(maxsize=None)\ndef _looks_like_debian_scheme() -> bool:\n    \"\"\"Debian adds two additional schemes.\"\"\"\n    from distutils.command.install import INSTALL_SCHEMES\n\n    return \"deb_system\" in INSTALL_SCHEMES and \"unix_local\" in INSTALL_SCHEMES\n\n\n@functools.lru_cache(maxsize=None)\ndef _looks_like_red_hat_scheme() -> bool:\n    \"\"\"Red Hat patches ``sys.prefix`` and ``sys.exec_prefix``.\n\n    Red Hat's ``00251-change-user-install-location.patch`` changes the install\n    command's ``prefix`` and ``exec_prefix`` to append ``\"/local\"``. This is\n    (fortunately?) done quite unconditionally, so we create a default command\n    object without any configuration to detect this.\n    \"\"\"\n    from distutils.command.install import install\n    from distutils.dist import Distribution\n\n    cmd: Any = install(Distribution())\n    cmd.finalize_options()\n    return (\n        cmd.exec_prefix == f\"{os.path.normpath(sys.exec_prefix)}/local\"\n        and cmd.prefix == f\"{os.path.normpath(sys.prefix)}/local\"\n    )\n\n\n@functools.lru_cache(maxsize=None)\ndef _looks_like_slackware_scheme() -> bool:\n    \"\"\"Slackware patches sysconfig but fails to patch distutils and site.\n\n    Slackware changes sysconfig's user scheme to use ``\"lib64\"`` for the lib\n    path, but does not do the same to the site module.\n    \"\"\"\n    if user_site is None:  # User-site not available.\n        return False\n    try:\n        paths = sysconfig.get_paths(scheme=\"posix_user\", expand=False)\n    except KeyError:  # User-site not available.\n        return False\n    return \"/lib64/\" in paths[\"purelib\"] and \"/lib64/\" not in user_site\n\n\n@functools.lru_cache(maxsize=None)\ndef _looks_like_msys2_mingw_scheme() -> bool:\n    \"\"\"MSYS2 patches distutils and sysconfig to use a UNIX-like scheme.\n\n    However, MSYS2 incorrectly patches sysconfig ``nt`` scheme. The fix is\n    likely going to be included in their 3.10 release, so we ignore the warning.\n    See msys2/MINGW-packages#9319.\n\n    MSYS2 MINGW's patch uses lowercase ``\"lib\"`` instead of the usual uppercase,\n    and is missing the final ``\"site-packages\"``.\n    \"\"\"\n    paths = sysconfig.get_paths(\"nt\", expand=False)\n    return all(\n        \"Lib\" not in p and \"lib\" in p and not p.endswith(\"site-packages\")\n        for p in (paths[key] for key in (\"platlib\", \"purelib\"))\n    )\n\n\ndef _fix_abiflags(parts: Tuple[str]) -> Generator[str, None, None]:\n    ldversion = sysconfig.get_config_var(\"LDVERSION\")\n    abiflags = getattr(sys, \"abiflags\", None)\n\n    # LDVERSION does not end with sys.abiflags. Just return the path unchanged.\n    if not ldversion or not abiflags or not ldversion.endswith(abiflags):\n        yield from parts\n        return\n\n    # Strip sys.abiflags from LDVERSION-based path components.\n    for part in parts:\n        if part.endswith(ldversion):\n            part = part[: (0 - len(abiflags))]\n        yield part\n\n\n@functools.lru_cache(maxsize=None)\ndef _warn_mismatched(old: pathlib.Path, new: pathlib.Path, *, key: str) -> None:\n    issue_url = \"https://github.com/pypa/pip/issues/10151\"\n    message = (\n        \"Value for %s does not match. Please report this to <%s>\"\n        \"\\ndistutils: %s\"\n        \"\\nsysconfig: %s\"\n    )\n    logger.log(_MISMATCH_LEVEL, message, key, issue_url, old, new)\n\n\ndef _warn_if_mismatch(old: pathlib.Path, new: pathlib.Path, *, key: str) -> bool:\n    if old == new:\n        return False\n    _warn_mismatched(old, new, key=key)\n    return True\n\n\n@functools.lru_cache(maxsize=None)\ndef _log_context(\n    *,\n    user: bool = False,\n    home: Optional[str] = None,\n    root: Optional[str] = None,\n    prefix: Optional[str] = None,\n) -> None:\n    parts = [\n        \"Additional context:\",\n        \"user = %r\",\n        \"home = %r\",\n        \"root = %r\",\n        \"prefix = %r\",\n    ]\n\n    logger.log(_MISMATCH_LEVEL, \"\\n\".join(parts), user, home, root, prefix)\n\n\ndef get_scheme(\n    dist_name: str,\n    user: bool = False,\n    home: Optional[str] = None,\n    root: Optional[str] = None,\n    isolated: bool = False,\n    prefix: Optional[str] = None,\n) -> Scheme:\n    new = _sysconfig.get_scheme(\n        dist_name,\n        user=user,\n        home=home,\n        root=root,\n        isolated=isolated,\n        prefix=prefix,\n    )\n    if _USE_SYSCONFIG:\n        return new\n\n    old = _distutils.get_scheme(\n        dist_name,\n        user=user,\n        home=home,\n        root=root,\n        isolated=isolated,\n        prefix=prefix,\n    )\n\n    warning_contexts = []\n    for k in SCHEME_KEYS:\n        old_v = pathlib.Path(getattr(old, k))\n        new_v = pathlib.Path(getattr(new, k))\n\n        if old_v == new_v:\n            continue\n\n        # distutils incorrectly put PyPy packages under ``site-packages/python``\n        # in the ``posix_home`` scheme, but PyPy devs said they expect the\n        # directory name to be ``pypy`` instead. So we treat this as a bug fix\n        # and not warn about it. See bpo-43307 and python/cpython#24628.\n        skip_pypy_special_case = (\n            sys.implementation.name == \"pypy\"\n            and home is not None\n            and k in (\"platlib\", \"purelib\")\n            and old_v.parent == new_v.parent\n            and old_v.name.startswith(\"python\")\n            and new_v.name.startswith(\"pypy\")\n        )\n        if skip_pypy_special_case:\n            continue\n\n        # sysconfig's ``osx_framework_user`` does not include ``pythonX.Y`` in\n        # the ``include`` value, but distutils's ``headers`` does. We'll let\n        # CPython decide whether this is a bug or feature. See bpo-43948.\n        skip_osx_framework_user_special_case = (\n            user\n            and is_osx_framework()\n            and k == \"headers\"\n            and old_v.parent.parent == new_v.parent\n            and old_v.parent.name.startswith(\"python\")\n        )\n        if skip_osx_framework_user_special_case:\n            continue\n\n        # On Red Hat and derived Linux distributions, distutils is patched to\n        # use \"lib64\" instead of \"lib\" for platlib.\n        if k == \"platlib\" and _looks_like_red_hat_lib():\n            continue\n\n        # On Python 3.9+, sysconfig's posix_user scheme sets platlib against\n        # sys.platlibdir, but distutils's unix_user incorrectly coninutes\n        # using the same $usersite for both platlib and purelib. This creates a\n        # mismatch when sys.platlibdir is not \"lib\".\n        skip_bpo_44860 = (\n            user\n            and k == \"platlib\"\n            and not WINDOWS\n            and sys.version_info >= (3, 9)\n            and _PLATLIBDIR != \"lib\"\n            and _looks_like_bpo_44860()\n        )\n        if skip_bpo_44860:\n            continue\n\n        # Slackware incorrectly patches posix_user to use lib64 instead of lib,\n        # but not usersite to match the location.\n        skip_slackware_user_scheme = (\n            user\n            and k in (\"platlib\", \"purelib\")\n            and not WINDOWS\n            and _looks_like_slackware_scheme()\n        )\n        if skip_slackware_user_scheme:\n            continue\n\n        # Both Debian and Red Hat patch Python to place the system site under\n        # /usr/local instead of /usr. Debian also places lib in dist-packages\n        # instead of site-packages, but the /usr/local check should cover it.\n        skip_linux_system_special_case = (\n            not (user or home or prefix or running_under_virtualenv())\n            and old_v.parts[1:3] == (\"usr\", \"local\")\n            and len(new_v.parts) > 1\n            and new_v.parts[1] == \"usr\"\n            and (len(new_v.parts) < 3 or new_v.parts[2] != \"local\")\n            and (_looks_like_red_hat_scheme() or _looks_like_debian_scheme())\n        )\n        if skip_linux_system_special_case:\n            continue\n\n        # On Python 3.7 and earlier, sysconfig does not include sys.abiflags in\n        # the \"pythonX.Y\" part of the path, but distutils does.\n        skip_sysconfig_abiflag_bug = (\n            sys.version_info < (3, 8)\n            and not WINDOWS\n            and k in (\"headers\", \"platlib\", \"purelib\")\n            and tuple(_fix_abiflags(old_v.parts)) == new_v.parts\n        )\n        if skip_sysconfig_abiflag_bug:\n            continue\n\n        # MSYS2 MINGW's sysconfig patch does not include the \"site-packages\"\n        # part of the path. This is incorrect and will be fixed in MSYS.\n        skip_msys2_mingw_bug = (\n            WINDOWS and k in (\"platlib\", \"purelib\") and _looks_like_msys2_mingw_scheme()\n        )\n        if skip_msys2_mingw_bug:\n            continue\n\n        # CPython's POSIX install script invokes pip (via ensurepip) against the\n        # interpreter located in the source tree, not the install site. This\n        # triggers special logic in sysconfig that's not present in distutils.\n        # https://github.com/python/cpython/blob/8c21941ddaf/Lib/sysconfig.py#L178-L194\n        skip_cpython_build = (\n            sysconfig.is_python_build(check_home=True)\n            and not WINDOWS\n            and k in (\"headers\", \"include\", \"platinclude\")\n        )\n        if skip_cpython_build:\n            continue\n\n        warning_contexts.append((old_v, new_v, f\"scheme.{k}\"))\n\n    if not warning_contexts:\n        return old\n\n    # Check if this path mismatch is caused by distutils config files. Those\n    # files will no longer work once we switch to sysconfig, so this raises a\n    # deprecation message for them.\n    default_old = _distutils.distutils_scheme(\n        dist_name,\n        user,\n        home,\n        root,\n        isolated,\n        prefix,\n        ignore_config_files=True,\n    )\n    if any(default_old[k] != getattr(old, k) for k in SCHEME_KEYS):\n        deprecated(\n            reason=(\n                \"Configuring installation scheme with distutils config files \"\n                \"is deprecated and will no longer work in the near future. If you \"\n                \"are using a Homebrew or Linuxbrew Python, please see discussion \"\n                \"at https://github.com/Homebrew/homebrew-core/issues/76621\"\n            ),\n            replacement=None,\n            gone_in=None,\n        )\n        return old\n\n    # Post warnings about this mismatch so user can report them back.\n    for old_v, new_v, key in warning_contexts:\n        _warn_mismatched(old_v, new_v, key=key)\n    _log_context(user=user, home=home, root=root, prefix=prefix)\n\n    return old\n\n\ndef get_bin_prefix() -> str:\n    new = _sysconfig.get_bin_prefix()\n    if _USE_SYSCONFIG:\n        return new\n\n    old = _distutils.get_bin_prefix()\n    if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key=\"bin_prefix\"):\n        _log_context()\n    return old\n\n\ndef get_bin_user() -> str:\n    return _sysconfig.get_scheme(\"\", user=True).scripts\n\n\ndef _looks_like_deb_system_dist_packages(value: str) -> bool:\n    \"\"\"Check if the value is Debian's APT-controlled dist-packages.\n\n    Debian's ``distutils.sysconfig.get_python_lib()`` implementation returns the\n    default package path controlled by APT, but does not patch ``sysconfig`` to\n    do the same. This is similar to the bug worked around in ``get_scheme()``,\n    but here the default is ``deb_system`` instead of ``unix_local``. Ultimately\n    we can't do anything about this Debian bug, and this detection allows us to\n    skip the warning when needed.\n    \"\"\"\n    if not _looks_like_debian_scheme():\n        return False\n    if value == \"/usr/lib/python3/dist-packages\":\n        return True\n    return False\n\n\ndef get_purelib() -> str:\n    \"\"\"Return the default pure-Python lib location.\"\"\"\n    new = _sysconfig.get_purelib()\n    if _USE_SYSCONFIG:\n        return new\n\n    old = _distutils.get_purelib()\n    if _looks_like_deb_system_dist_packages(old):\n        return old\n    if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key=\"purelib\"):\n        _log_context()\n    return old\n\n\ndef get_platlib() -> str:\n    \"\"\"Return the default platform-shared lib location.\"\"\"\n    new = _sysconfig.get_platlib()\n    if _USE_SYSCONFIG:\n        return new\n\n    from . import _distutils\n\n    old = _distutils.get_platlib()\n    if _looks_like_deb_system_dist_packages(old):\n        return old\n    if _warn_if_mismatch(pathlib.Path(old), pathlib.Path(new), key=\"platlib\"):\n        _log_context()\n    return old\n\n\ndef _deduplicated(v1: str, v2: str) -> List[str]:\n    \"\"\"Deduplicate values from a list.\"\"\"\n    if v1 == v2:\n        return [v1]\n    return [v1, v2]\n\n\ndef _looks_like_apple_library(path: str) -> bool:\n    \"\"\"Apple patches sysconfig to *always* look under */Library/Python*.\"\"\"\n    if sys.platform[:6] != \"darwin\":\n        return False\n    return path == f\"/Library/Python/{get_major_minor_version()}/site-packages\"\n\n\ndef get_prefixed_libs(prefix: str) -> List[str]:\n    \"\"\"Return the lib locations under ``prefix``.\"\"\"\n    new_pure, new_plat = _sysconfig.get_prefixed_libs(prefix)\n    if _USE_SYSCONFIG:\n        return _deduplicated(new_pure, new_plat)\n\n    old_pure, old_plat = _distutils.get_prefixed_libs(prefix)\n    old_lib_paths = _deduplicated(old_pure, old_plat)\n\n    # Apple's Python (shipped with Xcode and Command Line Tools) hard-code\n    # platlib and purelib to '/Library/Python/X.Y/site-packages'. This will\n    # cause serious build isolation bugs when Apple starts shipping 3.10 because\n    # pip will install build backends to the wrong location. This tells users\n    # who is at fault so Apple may notice it and fix the issue in time.\n    if all(_looks_like_apple_library(p) for p in old_lib_paths):\n        deprecated(\n            reason=(\n                \"Python distributed by Apple's Command Line Tools incorrectly \"\n                \"patches sysconfig to always point to '/Library/Python'. This \"\n                \"will cause build isolation to operate incorrectly on Python \"\n                \"3.10 or later. Please help report this to Apple so they can \"\n                \"fix this. https://developer.apple.com/bug-reporting/\"\n            ),\n            replacement=None,\n            gone_in=None,\n        )\n        return old_lib_paths\n\n    warned = [\n        _warn_if_mismatch(\n            pathlib.Path(old_pure),\n            pathlib.Path(new_pure),\n            key=\"prefixed-purelib\",\n        ),\n        _warn_if_mismatch(\n            pathlib.Path(old_plat),\n            pathlib.Path(new_plat),\n            key=\"prefixed-platlib\",\n        ),\n    ]\n    if any(warned):\n        _log_context(prefix=prefix)\n\n    return old_lib_paths\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/locations/_distutils.py",
    "content": "\"\"\"Locations where we look for configs, install stuff, etc\"\"\"\n\n# The following comment should be removed at some point in the future.\n# mypy: strict-optional=False\n\n# If pip's going to use distutils, it should not be using the copy that setuptools\n# might have injected into the environment. This is done by removing the injected\n# shim, if it's injected.\n#\n# See https://github.com/pypa/pip/issues/8761 for the original discussion and\n# rationale for why this is done within pip.\ntry:\n    __import__(\"_distutils_hack\").remove_shim()\nexcept (ImportError, AttributeError):\n    pass\n\nimport logging\nimport os\nimport sys\nfrom distutils.cmd import Command as DistutilsCommand\nfrom distutils.command.install import SCHEME_KEYS\nfrom distutils.command.install import install as distutils_install_command\nfrom distutils.sysconfig import get_python_lib\nfrom typing import Dict, List, Optional, Tuple, Union, cast\n\nfrom pip._internal.models.scheme import Scheme\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\nfrom .base import get_major_minor_version\n\nlogger = logging.getLogger(__name__)\n\n\ndef distutils_scheme(\n    dist_name: str,\n    user: bool = False,\n    home: Optional[str] = None,\n    root: Optional[str] = None,\n    isolated: bool = False,\n    prefix: Optional[str] = None,\n    *,\n    ignore_config_files: bool = False,\n) -> Dict[str, str]:\n    \"\"\"\n    Return a distutils install scheme\n    \"\"\"\n    from distutils.dist import Distribution\n\n    dist_args: Dict[str, Union[str, List[str]]] = {\"name\": dist_name}\n    if isolated:\n        dist_args[\"script_args\"] = [\"--no-user-cfg\"]\n\n    d = Distribution(dist_args)\n    if not ignore_config_files:\n        try:\n            d.parse_config_files()\n        except UnicodeDecodeError:\n            # Typeshed does not include find_config_files() for some reason.\n            paths = d.find_config_files()  # type: ignore\n            logger.warning(\n                \"Ignore distutils configs in %s due to encoding errors.\",\n                \", \".join(os.path.basename(p) for p in paths),\n            )\n    obj: Optional[DistutilsCommand] = None\n    obj = d.get_command_obj(\"install\", create=True)\n    assert obj is not None\n    i = cast(distutils_install_command, obj)\n    # NOTE: setting user or home has the side-effect of creating the home dir\n    # or user base for installations during finalize_options()\n    # ideally, we'd prefer a scheme class that has no side-effects.\n    assert not (user and prefix), f\"user={user} prefix={prefix}\"\n    assert not (home and prefix), f\"home={home} prefix={prefix}\"\n    i.user = user or i.user\n    if user or home:\n        i.prefix = \"\"\n    i.prefix = prefix or i.prefix\n    i.home = home or i.home\n    i.root = root or i.root\n    i.finalize_options()\n\n    scheme = {}\n    for key in SCHEME_KEYS:\n        scheme[key] = getattr(i, \"install_\" + key)\n\n    # install_lib specified in setup.cfg should install *everything*\n    # into there (i.e. it takes precedence over both purelib and\n    # platlib).  Note, i.install_lib is *always* set after\n    # finalize_options(); we only want to override here if the user\n    # has explicitly requested it hence going back to the config\n    if \"install_lib\" in d.get_option_dict(\"install\"):\n        scheme.update(dict(purelib=i.install_lib, platlib=i.install_lib))\n\n    if running_under_virtualenv():\n        if home:\n            prefix = home\n        elif user:\n            prefix = i.install_userbase\n        else:\n            prefix = i.prefix\n        scheme[\"headers\"] = os.path.join(\n            prefix,\n            \"include\",\n            \"site\",\n            f\"python{get_major_minor_version()}\",\n            dist_name,\n        )\n\n        if root is not None:\n            path_no_drive = os.path.splitdrive(os.path.abspath(scheme[\"headers\"]))[1]\n            scheme[\"headers\"] = os.path.join(root, path_no_drive[1:])\n\n    return scheme\n\n\ndef get_scheme(\n    dist_name: str,\n    user: bool = False,\n    home: Optional[str] = None,\n    root: Optional[str] = None,\n    isolated: bool = False,\n    prefix: Optional[str] = None,\n) -> Scheme:\n    \"\"\"\n    Get the \"scheme\" corresponding to the input parameters. The distutils\n    documentation provides the context for the available schemes:\n    https://docs.python.org/3/install/index.html#alternate-installation\n\n    :param dist_name: the name of the package to retrieve the scheme for, used\n        in the headers scheme path\n    :param user: indicates to use the \"user\" scheme\n    :param home: indicates to use the \"home\" scheme and provides the base\n        directory for the same\n    :param root: root under which other directories are re-based\n    :param isolated: equivalent to --no-user-cfg, i.e. do not consider\n        ~/.pydistutils.cfg (posix) or ~/pydistutils.cfg (non-posix) for\n        scheme paths\n    :param prefix: indicates to use the \"prefix\" scheme and provides the\n        base directory for the same\n    \"\"\"\n    scheme = distutils_scheme(dist_name, user, home, root, isolated, prefix)\n    return Scheme(\n        platlib=scheme[\"platlib\"],\n        purelib=scheme[\"purelib\"],\n        headers=scheme[\"headers\"],\n        scripts=scheme[\"scripts\"],\n        data=scheme[\"data\"],\n    )\n\n\ndef get_bin_prefix() -> str:\n    # XXX: In old virtualenv versions, sys.prefix can contain '..' components,\n    # so we need to call normpath to eliminate them.\n    prefix = os.path.normpath(sys.prefix)\n    if WINDOWS:\n        bin_py = os.path.join(prefix, \"Scripts\")\n        # buildout uses 'bin' on Windows too?\n        if not os.path.exists(bin_py):\n            bin_py = os.path.join(prefix, \"bin\")\n        return bin_py\n    # Forcing to use /usr/local/bin for standard macOS framework installs\n    # Also log to ~/Library/Logs/ for use with the Console.app log viewer\n    if sys.platform[:6] == \"darwin\" and prefix[:16] == \"/System/Library/\":\n        return \"/usr/local/bin\"\n    return os.path.join(prefix, \"bin\")\n\n\ndef get_purelib() -> str:\n    return get_python_lib(plat_specific=False)\n\n\ndef get_platlib() -> str:\n    return get_python_lib(plat_specific=True)\n\n\ndef get_prefixed_libs(prefix: str) -> Tuple[str, str]:\n    return (\n        get_python_lib(plat_specific=False, prefix=prefix),\n        get_python_lib(plat_specific=True, prefix=prefix),\n    )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/locations/_sysconfig.py",
    "content": "import logging\nimport os\nimport sys\nimport sysconfig\nimport typing\n\nfrom pip._internal.exceptions import InvalidSchemeCombination, UserInstallationInvalid\nfrom pip._internal.models.scheme import SCHEME_KEYS, Scheme\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\nfrom .base import change_root, get_major_minor_version, is_osx_framework\n\nlogger = logging.getLogger(__name__)\n\n\n# Notes on _infer_* functions.\n# Unfortunately ``get_default_scheme()`` didn't exist before 3.10, so there's no\n# way to ask things like \"what is the '_prefix' scheme on this platform\". These\n# functions try to answer that with some heuristics while accounting for ad-hoc\n# platforms not covered by CPython's default sysconfig implementation. If the\n# ad-hoc implementation does not fully implement sysconfig, we'll fall back to\n# a POSIX scheme.\n\n_AVAILABLE_SCHEMES = set(sysconfig.get_scheme_names())\n\n_PREFERRED_SCHEME_API = getattr(sysconfig, \"get_preferred_scheme\", None)\n\n\ndef _should_use_osx_framework_prefix() -> bool:\n    \"\"\"Check for Apple's ``osx_framework_library`` scheme.\n\n    Python distributed by Apple's Command Line Tools has this special scheme\n    that's used when:\n\n    * This is a framework build.\n    * We are installing into the system prefix.\n\n    This does not account for ``pip install --prefix`` (also means we're not\n    installing to the system prefix), which should use ``posix_prefix``, but\n    logic here means ``_infer_prefix()`` outputs ``osx_framework_library``. But\n    since ``prefix`` is not available for ``sysconfig.get_default_scheme()``,\n    which is the stdlib replacement for ``_infer_prefix()``, presumably Apple\n    wouldn't be able to magically switch between ``osx_framework_library`` and\n    ``posix_prefix``. ``_infer_prefix()`` returning ``osx_framework_library``\n    means its behavior is consistent whether we use the stdlib implementation\n    or our own, and we deal with this special case in ``get_scheme()`` instead.\n    \"\"\"\n    return (\n        \"osx_framework_library\" in _AVAILABLE_SCHEMES\n        and not running_under_virtualenv()\n        and is_osx_framework()\n    )\n\n\ndef _infer_prefix() -> str:\n    \"\"\"Try to find a prefix scheme for the current platform.\n\n    This tries:\n\n    * A special ``osx_framework_library`` for Python distributed by Apple's\n      Command Line Tools, when not running in a virtual environment.\n    * Implementation + OS, used by PyPy on Windows (``pypy_nt``).\n    * Implementation without OS, used by PyPy on POSIX (``pypy``).\n    * OS + \"prefix\", used by CPython on POSIX (``posix_prefix``).\n    * Just the OS name, used by CPython on Windows (``nt``).\n\n    If none of the above works, fall back to ``posix_prefix``.\n    \"\"\"\n    if _PREFERRED_SCHEME_API:\n        return _PREFERRED_SCHEME_API(\"prefix\")\n    if _should_use_osx_framework_prefix():\n        return \"osx_framework_library\"\n    implementation_suffixed = f\"{sys.implementation.name}_{os.name}\"\n    if implementation_suffixed in _AVAILABLE_SCHEMES:\n        return implementation_suffixed\n    if sys.implementation.name in _AVAILABLE_SCHEMES:\n        return sys.implementation.name\n    suffixed = f\"{os.name}_prefix\"\n    if suffixed in _AVAILABLE_SCHEMES:\n        return suffixed\n    if os.name in _AVAILABLE_SCHEMES:  # On Windows, prefx is just called \"nt\".\n        return os.name\n    return \"posix_prefix\"\n\n\ndef _infer_user() -> str:\n    \"\"\"Try to find a user scheme for the current platform.\"\"\"\n    if _PREFERRED_SCHEME_API:\n        return _PREFERRED_SCHEME_API(\"user\")\n    if is_osx_framework() and not running_under_virtualenv():\n        suffixed = \"osx_framework_user\"\n    else:\n        suffixed = f\"{os.name}_user\"\n    if suffixed in _AVAILABLE_SCHEMES:\n        return suffixed\n    if \"posix_user\" not in _AVAILABLE_SCHEMES:  # User scheme unavailable.\n        raise UserInstallationInvalid()\n    return \"posix_user\"\n\n\ndef _infer_home() -> str:\n    \"\"\"Try to find a home for the current platform.\"\"\"\n    if _PREFERRED_SCHEME_API:\n        return _PREFERRED_SCHEME_API(\"home\")\n    suffixed = f\"{os.name}_home\"\n    if suffixed in _AVAILABLE_SCHEMES:\n        return suffixed\n    return \"posix_home\"\n\n\n# Update these keys if the user sets a custom home.\n_HOME_KEYS = [\n    \"installed_base\",\n    \"base\",\n    \"installed_platbase\",\n    \"platbase\",\n    \"prefix\",\n    \"exec_prefix\",\n]\nif sysconfig.get_config_var(\"userbase\") is not None:\n    _HOME_KEYS.append(\"userbase\")\n\n\ndef get_scheme(\n    dist_name: str,\n    user: bool = False,\n    home: typing.Optional[str] = None,\n    root: typing.Optional[str] = None,\n    isolated: bool = False,\n    prefix: typing.Optional[str] = None,\n) -> Scheme:\n    \"\"\"\n    Get the \"scheme\" corresponding to the input parameters.\n\n    :param dist_name: the name of the package to retrieve the scheme for, used\n        in the headers scheme path\n    :param user: indicates to use the \"user\" scheme\n    :param home: indicates to use the \"home\" scheme\n    :param root: root under which other directories are re-based\n    :param isolated: ignored, but kept for distutils compatibility (where\n        this controls whether the user-site pydistutils.cfg is honored)\n    :param prefix: indicates to use the \"prefix\" scheme and provides the\n        base directory for the same\n    \"\"\"\n    if user and prefix:\n        raise InvalidSchemeCombination(\"--user\", \"--prefix\")\n    if home and prefix:\n        raise InvalidSchemeCombination(\"--home\", \"--prefix\")\n\n    if home is not None:\n        scheme_name = _infer_home()\n    elif user:\n        scheme_name = _infer_user()\n    else:\n        scheme_name = _infer_prefix()\n\n    # Special case: When installing into a custom prefix, use posix_prefix\n    # instead of osx_framework_library. See _should_use_osx_framework_prefix()\n    # docstring for details.\n    if prefix is not None and scheme_name == \"osx_framework_library\":\n        scheme_name = \"posix_prefix\"\n\n    if home is not None:\n        variables = {k: home for k in _HOME_KEYS}\n    elif prefix is not None:\n        variables = {k: prefix for k in _HOME_KEYS}\n    else:\n        variables = {}\n\n    paths = sysconfig.get_paths(scheme=scheme_name, vars=variables)\n\n    # Logic here is very arbitrary, we're doing it for compatibility, don't ask.\n    # 1. Pip historically uses a special header path in virtual environments.\n    # 2. If the distribution name is not known, distutils uses 'UNKNOWN'. We\n    #    only do the same when not running in a virtual environment because\n    #    pip's historical header path logic (see point 1) did not do this.\n    if running_under_virtualenv():\n        if user:\n            base = variables.get(\"userbase\", sys.prefix)\n        else:\n            base = variables.get(\"base\", sys.prefix)\n        python_xy = f\"python{get_major_minor_version()}\"\n        paths[\"include\"] = os.path.join(base, \"include\", \"site\", python_xy)\n    elif not dist_name:\n        dist_name = \"UNKNOWN\"\n\n    scheme = Scheme(\n        platlib=paths[\"platlib\"],\n        purelib=paths[\"purelib\"],\n        headers=os.path.join(paths[\"include\"], dist_name),\n        scripts=paths[\"scripts\"],\n        data=paths[\"data\"],\n    )\n    if root is not None:\n        for key in SCHEME_KEYS:\n            value = change_root(root, getattr(scheme, key))\n            setattr(scheme, key, value)\n    return scheme\n\n\ndef get_bin_prefix() -> str:\n    # Forcing to use /usr/local/bin for standard macOS framework installs.\n    if sys.platform[:6] == \"darwin\" and sys.prefix[:16] == \"/System/Library/\":\n        return \"/usr/local/bin\"\n    return sysconfig.get_paths()[\"scripts\"]\n\n\ndef get_purelib() -> str:\n    return sysconfig.get_paths()[\"purelib\"]\n\n\ndef get_platlib() -> str:\n    return sysconfig.get_paths()[\"platlib\"]\n\n\ndef get_prefixed_libs(prefix: str) -> typing.Tuple[str, str]:\n    paths = sysconfig.get_paths(vars={\"base\": prefix, \"platbase\": prefix})\n    return (paths[\"purelib\"], paths[\"platlib\"])\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/locations/base.py",
    "content": "import functools\nimport os\nimport site\nimport sys\nimport sysconfig\nimport typing\n\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.utils import appdirs\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\n# Application Directories\nUSER_CACHE_DIR = appdirs.user_cache_dir(\"pip\")\n\n# FIXME doesn't account for venv linked to global site-packages\nsite_packages: typing.Optional[str] = sysconfig.get_path(\"purelib\")\n\n\ndef get_major_minor_version() -> str:\n    \"\"\"\n    Return the major-minor version of the current Python as a string, e.g.\n    \"3.7\" or \"3.10\".\n    \"\"\"\n    return \"{}.{}\".format(*sys.version_info)\n\n\ndef change_root(new_root: str, pathname: str) -> str:\n    \"\"\"Return 'pathname' with 'new_root' prepended.\n\n    If 'pathname' is relative, this is equivalent to os.path.join(new_root, pathname).\n    Otherwise, it requires making 'pathname' relative and then joining the\n    two, which is tricky on DOS/Windows and Mac OS.\n\n    This is borrowed from Python's standard library's distutils module.\n    \"\"\"\n    if os.name == \"posix\":\n        if not os.path.isabs(pathname):\n            return os.path.join(new_root, pathname)\n        else:\n            return os.path.join(new_root, pathname[1:])\n\n    elif os.name == \"nt\":\n        (drive, path) = os.path.splitdrive(pathname)\n        if path[0] == \"\\\\\":\n            path = path[1:]\n        return os.path.join(new_root, path)\n\n    else:\n        raise InstallationError(\n            f\"Unknown platform: {os.name}\\n\"\n            \"Can not change root path prefix on unknown platform.\"\n        )\n\n\ndef get_src_prefix() -> str:\n    if running_under_virtualenv():\n        src_prefix = os.path.join(sys.prefix, \"src\")\n    else:\n        # FIXME: keep src in cwd for now (it is not a temporary folder)\n        try:\n            src_prefix = os.path.join(os.getcwd(), \"src\")\n        except OSError:\n            # In case the current working directory has been renamed or deleted\n            sys.exit(\"The folder you are executing pip from can no longer be found.\")\n\n    # under macOS + virtualenv sys.prefix is not properly resolved\n    # it is something like /path/to/python/bin/..\n    return os.path.abspath(src_prefix)\n\n\ntry:\n    # Use getusersitepackages if this is present, as it ensures that the\n    # value is initialised properly.\n    user_site: typing.Optional[str] = site.getusersitepackages()\nexcept AttributeError:\n    user_site = site.USER_SITE\n\n\n@functools.lru_cache(maxsize=None)\ndef is_osx_framework() -> bool:\n    return bool(sysconfig.get_config_var(\"PYTHONFRAMEWORK\"))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/main.py",
    "content": "from typing import List, Optional\n\n\ndef main(args: Optional[List[str]] = None) -> int:\n    \"\"\"This is preserved for old console scripts that may still be referencing\n    it.\n\n    For additional details, see https://github.com/pypa/pip/issues/7498.\n    \"\"\"\n    from pip._internal.utils.entrypoints import _wrapper\n\n    return _wrapper(args)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/metadata/__init__.py",
    "content": "import contextlib\nimport functools\nimport os\nimport sys\nfrom typing import TYPE_CHECKING, List, Optional, Type, cast\n\nfrom pip._internal.utils.misc import strtobool\n\nfrom .base import BaseDistribution, BaseEnvironment, FilesystemWheel, MemoryWheel, Wheel\n\nif TYPE_CHECKING:\n    from typing import Protocol\nelse:\n    Protocol = object\n\n__all__ = [\n    \"BaseDistribution\",\n    \"BaseEnvironment\",\n    \"FilesystemWheel\",\n    \"MemoryWheel\",\n    \"Wheel\",\n    \"get_default_environment\",\n    \"get_environment\",\n    \"get_wheel_distribution\",\n    \"select_backend\",\n]\n\n\ndef _should_use_importlib_metadata() -> bool:\n    \"\"\"Whether to use the ``importlib.metadata`` or ``pkg_resources`` backend.\n\n    By default, pip uses ``importlib.metadata`` on Python 3.11+, and\n    ``pkg_resourcess`` otherwise. This can be overridden by a couple of ways:\n\n    * If environment variable ``_PIP_USE_IMPORTLIB_METADATA`` is set, it\n      dictates whether ``importlib.metadata`` is used, regardless of Python\n      version.\n    * On Python 3.11+, Python distributors can patch ``importlib.metadata``\n      to add a global constant ``_PIP_USE_IMPORTLIB_METADATA = False``. This\n      makes pip use ``pkg_resources`` (unless the user set the aforementioned\n      environment variable to *True*).\n    \"\"\"\n    with contextlib.suppress(KeyError, ValueError):\n        return bool(strtobool(os.environ[\"_PIP_USE_IMPORTLIB_METADATA\"]))\n    if sys.version_info < (3, 11):\n        return False\n    import importlib.metadata\n\n    return bool(getattr(importlib.metadata, \"_PIP_USE_IMPORTLIB_METADATA\", True))\n\n\nclass Backend(Protocol):\n    Distribution: Type[BaseDistribution]\n    Environment: Type[BaseEnvironment]\n\n\n@functools.lru_cache(maxsize=None)\ndef select_backend() -> Backend:\n    if _should_use_importlib_metadata():\n        from . import importlib\n\n        return cast(Backend, importlib)\n    from . import pkg_resources\n\n    return cast(Backend, pkg_resources)\n\n\ndef get_default_environment() -> BaseEnvironment:\n    \"\"\"Get the default representation for the current environment.\n\n    This returns an Environment instance from the chosen backend. The default\n    Environment instance should be built from ``sys.path`` and may use caching\n    to share instance state accorss calls.\n    \"\"\"\n    return select_backend().Environment.default()\n\n\ndef get_environment(paths: Optional[List[str]]) -> BaseEnvironment:\n    \"\"\"Get a representation of the environment specified by ``paths``.\n\n    This returns an Environment instance from the chosen backend based on the\n    given import paths. The backend must build a fresh instance representing\n    the state of installed distributions when this function is called.\n    \"\"\"\n    return select_backend().Environment.from_paths(paths)\n\n\ndef get_directory_distribution(directory: str) -> BaseDistribution:\n    \"\"\"Get the distribution metadata representation in the specified directory.\n\n    This returns a Distribution instance from the chosen backend based on\n    the given on-disk ``.dist-info`` directory.\n    \"\"\"\n    return select_backend().Distribution.from_directory(directory)\n\n\ndef get_wheel_distribution(wheel: Wheel, canonical_name: str) -> BaseDistribution:\n    \"\"\"Get the representation of the specified wheel's distribution metadata.\n\n    This returns a Distribution instance from the chosen backend based on\n    the given wheel's ``.dist-info`` directory.\n\n    :param canonical_name: Normalized project name of the given wheel.\n    \"\"\"\n    return select_backend().Distribution.from_wheel(wheel, canonical_name)\n\n\ndef get_metadata_distribution(\n    metadata_contents: bytes,\n    filename: str,\n    canonical_name: str,\n) -> BaseDistribution:\n    \"\"\"Get the dist representation of the specified METADATA file contents.\n\n    This returns a Distribution instance from the chosen backend sourced from the data\n    in `metadata_contents`.\n\n    :param metadata_contents: Contents of a METADATA file within a dist, or one served\n                              via PEP 658.\n    :param filename: Filename for the dist this metadata represents.\n    :param canonical_name: Normalized project name of the given dist.\n    \"\"\"\n    return select_backend().Distribution.from_metadata_file_contents(\n        metadata_contents,\n        filename,\n        canonical_name,\n    )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/metadata/_json.py",
    "content": "# Extracted from https://github.com/pfmoore/pkg_metadata\n\nfrom email.header import Header, decode_header, make_header\nfrom email.message import Message\nfrom typing import Any, Dict, List, Union\n\nMETADATA_FIELDS = [\n    # Name, Multiple-Use\n    (\"Metadata-Version\", False),\n    (\"Name\", False),\n    (\"Version\", False),\n    (\"Dynamic\", True),\n    (\"Platform\", True),\n    (\"Supported-Platform\", True),\n    (\"Summary\", False),\n    (\"Description\", False),\n    (\"Description-Content-Type\", False),\n    (\"Keywords\", False),\n    (\"Home-page\", False),\n    (\"Download-URL\", False),\n    (\"Author\", False),\n    (\"Author-email\", False),\n    (\"Maintainer\", False),\n    (\"Maintainer-email\", False),\n    (\"License\", False),\n    (\"Classifier\", True),\n    (\"Requires-Dist\", True),\n    (\"Requires-Python\", False),\n    (\"Requires-External\", True),\n    (\"Project-URL\", True),\n    (\"Provides-Extra\", True),\n    (\"Provides-Dist\", True),\n    (\"Obsoletes-Dist\", True),\n]\n\n\ndef json_name(field: str) -> str:\n    return field.lower().replace(\"-\", \"_\")\n\n\ndef msg_to_json(msg: Message) -> Dict[str, Any]:\n    \"\"\"Convert a Message object into a JSON-compatible dictionary.\"\"\"\n\n    def sanitise_header(h: Union[Header, str]) -> str:\n        if isinstance(h, Header):\n            chunks = []\n            for bytes, encoding in decode_header(h):\n                if encoding == \"unknown-8bit\":\n                    try:\n                        # See if UTF-8 works\n                        bytes.decode(\"utf-8\")\n                        encoding = \"utf-8\"\n                    except UnicodeDecodeError:\n                        # If not, latin1 at least won't fail\n                        encoding = \"latin1\"\n                chunks.append((bytes, encoding))\n            return str(make_header(chunks))\n        return str(h)\n\n    result = {}\n    for field, multi in METADATA_FIELDS:\n        if field not in msg:\n            continue\n        key = json_name(field)\n        if multi:\n            value: Union[str, List[str]] = [\n                sanitise_header(v) for v in msg.get_all(field)\n            ]\n        else:\n            value = sanitise_header(msg.get(field))\n            if key == \"keywords\":\n                # Accept both comma-separated and space-separated\n                # forms, for better compatibility with old data.\n                if \",\" in value:\n                    value = [v.strip() for v in value.split(\",\")]\n                else:\n                    value = value.split()\n        result[key] = value\n\n    payload = msg.get_payload()\n    if payload:\n        result[\"description\"] = payload\n\n    return result\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/metadata/base.py",
    "content": "import csv\nimport email.message\nimport functools\nimport json\nimport logging\nimport pathlib\nimport re\nimport zipfile\nfrom typing import (\n    IO,\n    TYPE_CHECKING,\n    Any,\n    Collection,\n    Container,\n    Dict,\n    Iterable,\n    Iterator,\n    List,\n    NamedTuple,\n    Optional,\n    Tuple,\n    Union,\n)\n\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.specifiers import InvalidSpecifier, SpecifierSet\nfrom pip._vendor.packaging.utils import NormalizedName\nfrom pip._vendor.packaging.version import LegacyVersion, Version\n\nfrom pip._internal.exceptions import NoneMetadataError\nfrom pip._internal.locations import site_packages, user_site\nfrom pip._internal.models.direct_url import (\n    DIRECT_URL_METADATA_NAME,\n    DirectUrl,\n    DirectUrlValidationError,\n)\nfrom pip._internal.utils.compat import stdlib_pkgs  # TODO: Move definition here.\nfrom pip._internal.utils.egg_link import egg_link_path_from_sys_path\nfrom pip._internal.utils.misc import is_local, normalize_path\nfrom pip._internal.utils.packaging import safe_extra\nfrom pip._internal.utils.urls import url_to_path\n\nfrom ._json import msg_to_json\n\nif TYPE_CHECKING:\n    from typing import Protocol\nelse:\n    Protocol = object\n\nDistributionVersion = Union[LegacyVersion, Version]\n\nInfoPath = Union[str, pathlib.PurePath]\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseEntryPoint(Protocol):\n    @property\n    def name(self) -> str:\n        raise NotImplementedError()\n\n    @property\n    def value(self) -> str:\n        raise NotImplementedError()\n\n    @property\n    def group(self) -> str:\n        raise NotImplementedError()\n\n\ndef _convert_installed_files_path(\n    entry: Tuple[str, ...],\n    info: Tuple[str, ...],\n) -> str:\n    \"\"\"Convert a legacy installed-files.txt path into modern RECORD path.\n\n    The legacy format stores paths relative to the info directory, while the\n    modern format stores paths relative to the package root, e.g. the\n    site-packages directory.\n\n    :param entry: Path parts of the installed-files.txt entry.\n    :param info: Path parts of the egg-info directory relative to package root.\n    :returns: The converted entry.\n\n    For best compatibility with symlinks, this does not use ``abspath()`` or\n    ``Path.resolve()``, but tries to work with path parts:\n\n    1. While ``entry`` starts with ``..``, remove the equal amounts of parts\n       from ``info``; if ``info`` is empty, start appending ``..`` instead.\n    2. Join the two directly.\n    \"\"\"\n    while entry and entry[0] == \"..\":\n        if not info or info[-1] == \"..\":\n            info += (\"..\",)\n        else:\n            info = info[:-1]\n        entry = entry[1:]\n    return str(pathlib.Path(*info, *entry))\n\n\nclass RequiresEntry(NamedTuple):\n    requirement: str\n    extra: str\n    marker: str\n\n\nclass BaseDistribution(Protocol):\n    @classmethod\n    def from_directory(cls, directory: str) -> \"BaseDistribution\":\n        \"\"\"Load the distribution from a metadata directory.\n\n        :param directory: Path to a metadata directory, e.g. ``.dist-info``.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def from_metadata_file_contents(\n        cls,\n        metadata_contents: bytes,\n        filename: str,\n        project_name: str,\n    ) -> \"BaseDistribution\":\n        \"\"\"Load the distribution from the contents of a METADATA file.\n\n        This is used to implement PEP 658 by generating a \"shallow\" dist object that can\n        be used for resolution without downloading or building the actual dist yet.\n\n        :param metadata_contents: The contents of a METADATA file.\n        :param filename: File name for the dist with this metadata.\n        :param project_name: Name of the project this dist represents.\n        \"\"\"\n        raise NotImplementedError()\n\n    @classmethod\n    def from_wheel(cls, wheel: \"Wheel\", name: str) -> \"BaseDistribution\":\n        \"\"\"Load the distribution from a given wheel.\n\n        :param wheel: A concrete wheel definition.\n        :param name: File name of the wheel.\n\n        :raises InvalidWheel: Whenever loading of the wheel causes a\n            :py:exc:`zipfile.BadZipFile` exception to be thrown.\n        :raises UnsupportedWheel: If the wheel is a valid zip, but malformed\n            internally.\n        \"\"\"\n        raise NotImplementedError()\n\n    def __repr__(self) -> str:\n        return f\"{self.raw_name} {self.version} ({self.location})\"\n\n    def __str__(self) -> str:\n        return f\"{self.raw_name} {self.version}\"\n\n    @property\n    def location(self) -> Optional[str]:\n        \"\"\"Where the distribution is loaded from.\n\n        A string value is not necessarily a filesystem path, since distributions\n        can be loaded from other sources, e.g. arbitrary zip archives. ``None``\n        means the distribution is created in-memory.\n\n        Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If\n        this is a symbolic link, we want to preserve the relative path between\n        it and files in the distribution.\n        \"\"\"\n        raise NotImplementedError()\n\n    @property\n    def editable_project_location(self) -> Optional[str]:\n        \"\"\"The project location for editable distributions.\n\n        This is the directory where pyproject.toml or setup.py is located.\n        None if the distribution is not installed in editable mode.\n        \"\"\"\n        # TODO: this property is relatively costly to compute, memoize it ?\n        direct_url = self.direct_url\n        if direct_url:\n            if direct_url.is_local_editable():\n                return url_to_path(direct_url.url)\n        else:\n            # Search for an .egg-link file by walking sys.path, as it was\n            # done before by dist_is_editable().\n            egg_link_path = egg_link_path_from_sys_path(self.raw_name)\n            if egg_link_path:\n                # TODO: get project location from second line of egg_link file\n                #       (https://github.com/pypa/pip/issues/10243)\n                return self.location\n        return None\n\n    @property\n    def installed_location(self) -> Optional[str]:\n        \"\"\"The distribution's \"installed\" location.\n\n        This should generally be a ``site-packages`` directory. This is\n        usually ``dist.location``, except for legacy develop-installed packages,\n        where ``dist.location`` is the source code location, and this is where\n        the ``.egg-link`` file is.\n\n        The returned location is normalized (in particular, with symlinks removed).\n        \"\"\"\n        raise NotImplementedError()\n\n    @property\n    def info_location(self) -> Optional[str]:\n        \"\"\"Location of the .[egg|dist]-info directory or file.\n\n        Similarly to ``location``, a string value is not necessarily a\n        filesystem path. ``None`` means the distribution is created in-memory.\n\n        For a modern .dist-info installation on disk, this should be something\n        like ``{location}/{raw_name}-{version}.dist-info``.\n\n        Do not canonicalize this value with e.g. ``pathlib.Path.resolve()``. If\n        this is a symbolic link, we want to preserve the relative path between\n        it and other files in the distribution.\n        \"\"\"\n        raise NotImplementedError()\n\n    @property\n    def installed_by_distutils(self) -> bool:\n        \"\"\"Whether this distribution is installed with legacy distutils format.\n\n        A distribution installed with \"raw\" distutils not patched by setuptools\n        uses one single file at ``info_location`` to store metadata. We need to\n        treat this specially on uninstallation.\n        \"\"\"\n        info_location = self.info_location\n        if not info_location:\n            return False\n        return pathlib.Path(info_location).is_file()\n\n    @property\n    def installed_as_egg(self) -> bool:\n        \"\"\"Whether this distribution is installed as an egg.\n\n        This usually indicates the distribution was installed by (older versions\n        of) easy_install.\n        \"\"\"\n        location = self.location\n        if not location:\n            return False\n        return location.endswith(\".egg\")\n\n    @property\n    def installed_with_setuptools_egg_info(self) -> bool:\n        \"\"\"Whether this distribution is installed with the ``.egg-info`` format.\n\n        This usually indicates the distribution was installed with setuptools\n        with an old pip version or with ``single-version-externally-managed``.\n\n        Note that this ensure the metadata store is a directory. distutils can\n        also installs an ``.egg-info``, but as a file, not a directory. This\n        property is *False* for that case. Also see ``installed_by_distutils``.\n        \"\"\"\n        info_location = self.info_location\n        if not info_location:\n            return False\n        if not info_location.endswith(\".egg-info\"):\n            return False\n        return pathlib.Path(info_location).is_dir()\n\n    @property\n    def installed_with_dist_info(self) -> bool:\n        \"\"\"Whether this distribution is installed with the \"modern format\".\n\n        This indicates a \"modern\" installation, e.g. storing metadata in the\n        ``.dist-info`` directory. This applies to installations made by\n        setuptools (but through pip, not directly), or anything using the\n        standardized build backend interface (PEP 517).\n        \"\"\"\n        info_location = self.info_location\n        if not info_location:\n            return False\n        if not info_location.endswith(\".dist-info\"):\n            return False\n        return pathlib.Path(info_location).is_dir()\n\n    @property\n    def canonical_name(self) -> NormalizedName:\n        raise NotImplementedError()\n\n    @property\n    def version(self) -> DistributionVersion:\n        raise NotImplementedError()\n\n    @property\n    def setuptools_filename(self) -> str:\n        \"\"\"Convert a project name to its setuptools-compatible filename.\n\n        This is a copy of ``pkg_resources.to_filename()`` for compatibility.\n        \"\"\"\n        return self.raw_name.replace(\"-\", \"_\")\n\n    @property\n    def direct_url(self) -> Optional[DirectUrl]:\n        \"\"\"Obtain a DirectUrl from this distribution.\n\n        Returns None if the distribution has no `direct_url.json` metadata,\n        or if `direct_url.json` is invalid.\n        \"\"\"\n        try:\n            content = self.read_text(DIRECT_URL_METADATA_NAME)\n        except FileNotFoundError:\n            return None\n        try:\n            return DirectUrl.from_json(content)\n        except (\n            UnicodeDecodeError,\n            json.JSONDecodeError,\n            DirectUrlValidationError,\n        ) as e:\n            logger.warning(\n                \"Error parsing %s for %s: %s\",\n                DIRECT_URL_METADATA_NAME,\n                self.canonical_name,\n                e,\n            )\n            return None\n\n    @property\n    def installer(self) -> str:\n        try:\n            installer_text = self.read_text(\"INSTALLER\")\n        except (OSError, ValueError, NoneMetadataError):\n            return \"\"  # Fail silently if the installer file cannot be read.\n        for line in installer_text.splitlines():\n            cleaned_line = line.strip()\n            if cleaned_line:\n                return cleaned_line\n        return \"\"\n\n    @property\n    def requested(self) -> bool:\n        return self.is_file(\"REQUESTED\")\n\n    @property\n    def editable(self) -> bool:\n        return bool(self.editable_project_location)\n\n    @property\n    def local(self) -> bool:\n        \"\"\"If distribution is installed in the current virtual environment.\n\n        Always True if we're not in a virtualenv.\n        \"\"\"\n        if self.installed_location is None:\n            return False\n        return is_local(self.installed_location)\n\n    @property\n    def in_usersite(self) -> bool:\n        if self.installed_location is None or user_site is None:\n            return False\n        return self.installed_location.startswith(normalize_path(user_site))\n\n    @property\n    def in_site_packages(self) -> bool:\n        if self.installed_location is None or site_packages is None:\n            return False\n        return self.installed_location.startswith(normalize_path(site_packages))\n\n    def is_file(self, path: InfoPath) -> bool:\n        \"\"\"Check whether an entry in the info directory is a file.\"\"\"\n        raise NotImplementedError()\n\n    def iter_distutils_script_names(self) -> Iterator[str]:\n        \"\"\"Find distutils 'scripts' entries metadata.\n\n        If 'scripts' is supplied in ``setup.py``, distutils records those in the\n        installed distribution's ``scripts`` directory, a file for each script.\n        \"\"\"\n        raise NotImplementedError()\n\n    def read_text(self, path: InfoPath) -> str:\n        \"\"\"Read a file in the info directory.\n\n        :raise FileNotFoundError: If ``path`` does not exist in the directory.\n        :raise NoneMetadataError: If ``path`` exists in the info directory, but\n            cannot be read.\n        \"\"\"\n        raise NotImplementedError()\n\n    def iter_entry_points(self) -> Iterable[BaseEntryPoint]:\n        raise NotImplementedError()\n\n    def _metadata_impl(self) -> email.message.Message:\n        raise NotImplementedError()\n\n    @functools.lru_cache(maxsize=1)\n    def _metadata_cached(self) -> email.message.Message:\n        # When we drop python 3.7 support, move this to the metadata property and use\n        # functools.cached_property instead of lru_cache.\n        metadata = self._metadata_impl()\n        self._add_egg_info_requires(metadata)\n        return metadata\n\n    @property\n    def metadata(self) -> email.message.Message:\n        \"\"\"Metadata of distribution parsed from e.g. METADATA or PKG-INFO.\n\n        This should return an empty message if the metadata file is unavailable.\n\n        :raises NoneMetadataError: If the metadata file is available, but does\n            not contain valid metadata.\n        \"\"\"\n        return self._metadata_cached()\n\n    @property\n    def metadata_dict(self) -> Dict[str, Any]:\n        \"\"\"PEP 566 compliant JSON-serializable representation of METADATA or PKG-INFO.\n\n        This should return an empty dict if the metadata file is unavailable.\n\n        :raises NoneMetadataError: If the metadata file is available, but does\n            not contain valid metadata.\n        \"\"\"\n        return msg_to_json(self.metadata)\n\n    @property\n    def metadata_version(self) -> Optional[str]:\n        \"\"\"Value of \"Metadata-Version:\" in distribution metadata, if available.\"\"\"\n        return self.metadata.get(\"Metadata-Version\")\n\n    @property\n    def raw_name(self) -> str:\n        \"\"\"Value of \"Name:\" in distribution metadata.\"\"\"\n        # The metadata should NEVER be missing the Name: key, but if it somehow\n        # does, fall back to the known canonical name.\n        return self.metadata.get(\"Name\", self.canonical_name)\n\n    @property\n    def requires_python(self) -> SpecifierSet:\n        \"\"\"Value of \"Requires-Python:\" in distribution metadata.\n\n        If the key does not exist or contains an invalid value, an empty\n        SpecifierSet should be returned.\n        \"\"\"\n        value = self.metadata.get(\"Requires-Python\")\n        if value is None:\n            return SpecifierSet()\n        try:\n            # Convert to str to satisfy the type checker; this can be a Header object.\n            spec = SpecifierSet(str(value))\n        except InvalidSpecifier as e:\n            message = \"Package %r has an invalid Requires-Python: %s\"\n            logger.warning(message, self.raw_name, e)\n            return SpecifierSet()\n        return spec\n\n    def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:\n        \"\"\"Dependencies of this distribution.\n\n        For modern .dist-info distributions, this is the collection of\n        \"Requires-Dist:\" entries in distribution metadata.\n        \"\"\"\n        raise NotImplementedError()\n\n    def iter_provided_extras(self) -> Iterable[str]:\n        \"\"\"Extras provided by this distribution.\n\n        For modern .dist-info distributions, this is the collection of\n        \"Provides-Extra:\" entries in distribution metadata.\n        \"\"\"\n        raise NotImplementedError()\n\n    def _iter_declared_entries_from_record(self) -> Optional[Iterator[str]]:\n        try:\n            text = self.read_text(\"RECORD\")\n        except FileNotFoundError:\n            return None\n        # This extra Path-str cast normalizes entries.\n        return (str(pathlib.Path(row[0])) for row in csv.reader(text.splitlines()))\n\n    def _iter_declared_entries_from_legacy(self) -> Optional[Iterator[str]]:\n        try:\n            text = self.read_text(\"installed-files.txt\")\n        except FileNotFoundError:\n            return None\n        paths = (p for p in text.splitlines(keepends=False) if p)\n        root = self.location\n        info = self.info_location\n        if root is None or info is None:\n            return paths\n        try:\n            info_rel = pathlib.Path(info).relative_to(root)\n        except ValueError:  # info is not relative to root.\n            return paths\n        if not info_rel.parts:  # info *is* root.\n            return paths\n        return (\n            _convert_installed_files_path(pathlib.Path(p).parts, info_rel.parts)\n            for p in paths\n        )\n\n    def iter_declared_entries(self) -> Optional[Iterator[str]]:\n        \"\"\"Iterate through file entries declared in this distribution.\n\n        For modern .dist-info distributions, this is the files listed in the\n        ``RECORD`` metadata file. For legacy setuptools distributions, this\n        comes from ``installed-files.txt``, with entries normalized to be\n        compatible with the format used by ``RECORD``.\n\n        :return: An iterator for listed entries, or None if the distribution\n            contains neither ``RECORD`` nor ``installed-files.txt``.\n        \"\"\"\n        return (\n            self._iter_declared_entries_from_record()\n            or self._iter_declared_entries_from_legacy()\n        )\n\n    def _iter_requires_txt_entries(self) -> Iterator[RequiresEntry]:\n        \"\"\"Parse a ``requires.txt`` in an egg-info directory.\n\n        This is an INI-ish format where an egg-info stores dependencies. A\n        section name describes extra other environment markers, while each entry\n        is an arbitrary string (not a key-value pair) representing a dependency\n        as a requirement string (no markers).\n\n        There is a construct in ``importlib.metadata`` called ``Sectioned`` that\n        does mostly the same, but the format is currently considered private.\n        \"\"\"\n        try:\n            content = self.read_text(\"requires.txt\")\n        except FileNotFoundError:\n            return\n        extra = marker = \"\"  # Section-less entries don't have markers.\n        for line in content.splitlines():\n            line = line.strip()\n            if not line or line.startswith(\"#\"):  # Comment; ignored.\n                continue\n            if line.startswith(\"[\") and line.endswith(\"]\"):  # A section header.\n                extra, _, marker = line.strip(\"[]\").partition(\":\")\n                continue\n            yield RequiresEntry(requirement=line, extra=extra, marker=marker)\n\n    def _iter_egg_info_extras(self) -> Iterable[str]:\n        \"\"\"Get extras from the egg-info directory.\"\"\"\n        known_extras = {\"\"}\n        for entry in self._iter_requires_txt_entries():\n            if entry.extra in known_extras:\n                continue\n            known_extras.add(entry.extra)\n            yield entry.extra\n\n    def _iter_egg_info_dependencies(self) -> Iterable[str]:\n        \"\"\"Get distribution dependencies from the egg-info directory.\n\n        To ease parsing, this converts a legacy dependency entry into a PEP 508\n        requirement string. Like ``_iter_requires_txt_entries()``, there is code\n        in ``importlib.metadata`` that does mostly the same, but not do exactly\n        what we need.\n\n        Namely, ``importlib.metadata`` does not normalize the extra name before\n        putting it into the requirement string, which causes marker comparison\n        to fail because the dist-info format do normalize. This is consistent in\n        all currently available PEP 517 backends, although not standardized.\n        \"\"\"\n        for entry in self._iter_requires_txt_entries():\n            if entry.extra and entry.marker:\n                marker = f'({entry.marker}) and extra == \"{safe_extra(entry.extra)}\"'\n            elif entry.extra:\n                marker = f'extra == \"{safe_extra(entry.extra)}\"'\n            elif entry.marker:\n                marker = entry.marker\n            else:\n                marker = \"\"\n            if marker:\n                yield f\"{entry.requirement} ; {marker}\"\n            else:\n                yield entry.requirement\n\n    def _add_egg_info_requires(self, metadata: email.message.Message) -> None:\n        \"\"\"Add egg-info requires.txt information to the metadata.\"\"\"\n        if not metadata.get_all(\"Requires-Dist\"):\n            for dep in self._iter_egg_info_dependencies():\n                metadata[\"Requires-Dist\"] = dep\n        if not metadata.get_all(\"Provides-Extra\"):\n            for extra in self._iter_egg_info_extras():\n                metadata[\"Provides-Extra\"] = extra\n\n\nclass BaseEnvironment:\n    \"\"\"An environment containing distributions to introspect.\"\"\"\n\n    @classmethod\n    def default(cls) -> \"BaseEnvironment\":\n        raise NotImplementedError()\n\n    @classmethod\n    def from_paths(cls, paths: Optional[List[str]]) -> \"BaseEnvironment\":\n        raise NotImplementedError()\n\n    def get_distribution(self, name: str) -> Optional[\"BaseDistribution\"]:\n        \"\"\"Given a requirement name, return the installed distributions.\n\n        The name may not be normalized. The implementation must canonicalize\n        it for lookup.\n        \"\"\"\n        raise NotImplementedError()\n\n    def _iter_distributions(self) -> Iterator[\"BaseDistribution\"]:\n        \"\"\"Iterate through installed distributions.\n\n        This function should be implemented by subclass, but never called\n        directly. Use the public ``iter_distribution()`` instead, which\n        implements additional logic to make sure the distributions are valid.\n        \"\"\"\n        raise NotImplementedError()\n\n    def iter_all_distributions(self) -> Iterator[BaseDistribution]:\n        \"\"\"Iterate through all installed distributions without any filtering.\"\"\"\n        for dist in self._iter_distributions():\n            # Make sure the distribution actually comes from a valid Python\n            # packaging distribution. Pip's AdjacentTempDirectory leaves folders\n            # e.g. ``~atplotlib.dist-info`` if cleanup was interrupted. The\n            # valid project name pattern is taken from PEP 508.\n            project_name_valid = re.match(\n                r\"^([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])$\",\n                dist.canonical_name,\n                flags=re.IGNORECASE,\n            )\n            if not project_name_valid:\n                logger.warning(\n                    \"Ignoring invalid distribution %s (%s)\",\n                    dist.canonical_name,\n                    dist.location,\n                )\n                continue\n            yield dist\n\n    def iter_installed_distributions(\n        self,\n        local_only: bool = True,\n        skip: Container[str] = stdlib_pkgs,\n        include_editables: bool = True,\n        editables_only: bool = False,\n        user_only: bool = False,\n    ) -> Iterator[BaseDistribution]:\n        \"\"\"Return a list of installed distributions.\n\n        This is based on ``iter_all_distributions()`` with additional filtering\n        options. Note that ``iter_installed_distributions()`` without arguments\n        is *not* equal to ``iter_all_distributions()``, since some of the\n        configurations exclude packages by default.\n\n        :param local_only: If True (default), only return installations\n        local to the current virtualenv, if in a virtualenv.\n        :param skip: An iterable of canonicalized project names to ignore;\n            defaults to ``stdlib_pkgs``.\n        :param include_editables: If False, don't report editables.\n        :param editables_only: If True, only report editables.\n        :param user_only: If True, only report installations in the user\n        site directory.\n        \"\"\"\n        it = self.iter_all_distributions()\n        if local_only:\n            it = (d for d in it if d.local)\n        if not include_editables:\n            it = (d for d in it if not d.editable)\n        if editables_only:\n            it = (d for d in it if d.editable)\n        if user_only:\n            it = (d for d in it if d.in_usersite)\n        return (d for d in it if d.canonical_name not in skip)\n\n\nclass Wheel(Protocol):\n    location: str\n\n    def as_zipfile(self) -> zipfile.ZipFile:\n        raise NotImplementedError()\n\n\nclass FilesystemWheel(Wheel):\n    def __init__(self, location: str) -> None:\n        self.location = location\n\n    def as_zipfile(self) -> zipfile.ZipFile:\n        return zipfile.ZipFile(self.location, allowZip64=True)\n\n\nclass MemoryWheel(Wheel):\n    def __init__(self, location: str, stream: IO[bytes]) -> None:\n        self.location = location\n        self.stream = stream\n\n    def as_zipfile(self) -> zipfile.ZipFile:\n        return zipfile.ZipFile(self.stream, allowZip64=True)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/metadata/importlib/__init__.py",
    "content": "from ._dists import Distribution\nfrom ._envs import Environment\n\n__all__ = [\"Distribution\", \"Environment\"]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/metadata/importlib/_compat.py",
    "content": "import importlib.metadata\nfrom typing import Any, Optional, Protocol, cast\n\n\nclass BadMetadata(ValueError):\n    def __init__(self, dist: importlib.metadata.Distribution, *, reason: str) -> None:\n        self.dist = dist\n        self.reason = reason\n\n    def __str__(self) -> str:\n        return f\"Bad metadata in {self.dist} ({self.reason})\"\n\n\nclass BasePath(Protocol):\n    \"\"\"A protocol that various path objects conform.\n\n    This exists because importlib.metadata uses both ``pathlib.Path`` and\n    ``zipfile.Path``, and we need a common base for type hints (Union does not\n    work well since ``zipfile.Path`` is too new for our linter setup).\n\n    This does not mean to be exhaustive, but only contains things that present\n    in both classes *that we need*.\n    \"\"\"\n\n    @property\n    def name(self) -> str:\n        raise NotImplementedError()\n\n    @property\n    def parent(self) -> \"BasePath\":\n        raise NotImplementedError()\n\n\ndef get_info_location(d: importlib.metadata.Distribution) -> Optional[BasePath]:\n    \"\"\"Find the path to the distribution's metadata directory.\n\n    HACK: This relies on importlib.metadata's private ``_path`` attribute. Not\n    all distributions exist on disk, so importlib.metadata is correct to not\n    expose the attribute as public. But pip's code base is old and not as clean,\n    so we do this to avoid having to rewrite too many things. Hopefully we can\n    eliminate this some day.\n    \"\"\"\n    return getattr(d, \"_path\", None)\n\n\ndef get_dist_name(dist: importlib.metadata.Distribution) -> str:\n    \"\"\"Get the distribution's project name.\n\n    The ``name`` attribute is only available in Python 3.10 or later. We are\n    targeting exactly that, but Mypy does not know this.\n    \"\"\"\n    name = cast(Any, dist).name\n    if not isinstance(name, str):\n        raise BadMetadata(dist, reason=\"invalid metadata entry 'name'\")\n    return name\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/metadata/importlib/_dists.py",
    "content": "import email.message\nimport importlib.metadata\nimport os\nimport pathlib\nimport zipfile\nfrom typing import (\n    Collection,\n    Dict,\n    Iterable,\n    Iterator,\n    Mapping,\n    Optional,\n    Sequence,\n    cast,\n)\n\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip._internal.exceptions import InvalidWheel, UnsupportedWheel\nfrom pip._internal.metadata.base import (\n    BaseDistribution,\n    BaseEntryPoint,\n    DistributionVersion,\n    InfoPath,\n    Wheel,\n)\nfrom pip._internal.utils.misc import normalize_path\nfrom pip._internal.utils.packaging import safe_extra\nfrom pip._internal.utils.temp_dir import TempDirectory\nfrom pip._internal.utils.wheel import parse_wheel, read_wheel_metadata_file\n\nfrom ._compat import BasePath, get_dist_name\n\n\nclass WheelDistribution(importlib.metadata.Distribution):\n    \"\"\"An ``importlib.metadata.Distribution`` read from a wheel.\n\n    Although ``importlib.metadata.PathDistribution`` accepts ``zipfile.Path``,\n    its implementation is too \"lazy\" for pip's needs (we can't keep the ZipFile\n    handle open for the entire lifetime of the distribution object).\n\n    This implementation eagerly reads the entire metadata directory into the\n    memory instead, and operates from that.\n    \"\"\"\n\n    def __init__(\n        self,\n        files: Mapping[pathlib.PurePosixPath, bytes],\n        info_location: pathlib.PurePosixPath,\n    ) -> None:\n        self._files = files\n        self.info_location = info_location\n\n    @classmethod\n    def from_zipfile(\n        cls,\n        zf: zipfile.ZipFile,\n        name: str,\n        location: str,\n    ) -> \"WheelDistribution\":\n        info_dir, _ = parse_wheel(zf, name)\n        paths = (\n            (name, pathlib.PurePosixPath(name.split(\"/\", 1)[-1]))\n            for name in zf.namelist()\n            if name.startswith(f\"{info_dir}/\")\n        )\n        files = {\n            relpath: read_wheel_metadata_file(zf, fullpath)\n            for fullpath, relpath in paths\n        }\n        info_location = pathlib.PurePosixPath(location, info_dir)\n        return cls(files, info_location)\n\n    def iterdir(self, path: InfoPath) -> Iterator[pathlib.PurePosixPath]:\n        # Only allow iterating through the metadata directory.\n        if pathlib.PurePosixPath(str(path)) in self._files:\n            return iter(self._files)\n        raise FileNotFoundError(path)\n\n    def read_text(self, filename: str) -> Optional[str]:\n        try:\n            data = self._files[pathlib.PurePosixPath(filename)]\n        except KeyError:\n            return None\n        try:\n            text = data.decode(\"utf-8\")\n        except UnicodeDecodeError as e:\n            wheel = self.info_location.parent\n            error = f\"Error decoding metadata for {wheel}: {e} in {filename} file\"\n            raise UnsupportedWheel(error)\n        return text\n\n\nclass Distribution(BaseDistribution):\n    def __init__(\n        self,\n        dist: importlib.metadata.Distribution,\n        info_location: Optional[BasePath],\n        installed_location: Optional[BasePath],\n    ) -> None:\n        self._dist = dist\n        self._info_location = info_location\n        self._installed_location = installed_location\n\n    @classmethod\n    def from_directory(cls, directory: str) -> BaseDistribution:\n        info_location = pathlib.Path(directory)\n        dist = importlib.metadata.Distribution.at(info_location)\n        return cls(dist, info_location, info_location.parent)\n\n    @classmethod\n    def from_metadata_file_contents(\n        cls,\n        metadata_contents: bytes,\n        filename: str,\n        project_name: str,\n    ) -> BaseDistribution:\n        # Generate temp dir to contain the metadata file, and write the file contents.\n        temp_dir = pathlib.Path(\n            TempDirectory(kind=\"metadata\", globally_managed=True).path\n        )\n        metadata_path = temp_dir / \"METADATA\"\n        metadata_path.write_bytes(metadata_contents)\n        # Construct dist pointing to the newly created directory.\n        dist = importlib.metadata.Distribution.at(metadata_path.parent)\n        return cls(dist, metadata_path.parent, None)\n\n    @classmethod\n    def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution:\n        try:\n            with wheel.as_zipfile() as zf:\n                dist = WheelDistribution.from_zipfile(zf, name, wheel.location)\n        except zipfile.BadZipFile as e:\n            raise InvalidWheel(wheel.location, name) from e\n        except UnsupportedWheel as e:\n            raise UnsupportedWheel(f\"{name} has an invalid wheel, {e}\")\n        return cls(dist, dist.info_location, pathlib.PurePosixPath(wheel.location))\n\n    @property\n    def location(self) -> Optional[str]:\n        if self._info_location is None:\n            return None\n        return str(self._info_location.parent)\n\n    @property\n    def info_location(self) -> Optional[str]:\n        if self._info_location is None:\n            return None\n        return str(self._info_location)\n\n    @property\n    def installed_location(self) -> Optional[str]:\n        if self._installed_location is None:\n            return None\n        return normalize_path(str(self._installed_location))\n\n    def _get_dist_name_from_location(self) -> Optional[str]:\n        \"\"\"Try to get the name from the metadata directory name.\n\n        This is much faster than reading metadata.\n        \"\"\"\n        if self._info_location is None:\n            return None\n        stem, suffix = os.path.splitext(self._info_location.name)\n        if suffix not in (\".dist-info\", \".egg-info\"):\n            return None\n        return stem.split(\"-\", 1)[0]\n\n    @property\n    def canonical_name(self) -> NormalizedName:\n        name = self._get_dist_name_from_location() or get_dist_name(self._dist)\n        return canonicalize_name(name)\n\n    @property\n    def version(self) -> DistributionVersion:\n        return parse_version(self._dist.version)\n\n    def is_file(self, path: InfoPath) -> bool:\n        return self._dist.read_text(str(path)) is not None\n\n    def iter_distutils_script_names(self) -> Iterator[str]:\n        # A distutils installation is always \"flat\" (not in e.g. egg form), so\n        # if this distribution's info location is NOT a pathlib.Path (but e.g.\n        # zipfile.Path), it can never contain any distutils scripts.\n        if not isinstance(self._info_location, pathlib.Path):\n            return\n        for child in self._info_location.joinpath(\"scripts\").iterdir():\n            yield child.name\n\n    def read_text(self, path: InfoPath) -> str:\n        content = self._dist.read_text(str(path))\n        if content is None:\n            raise FileNotFoundError(path)\n        return content\n\n    def iter_entry_points(self) -> Iterable[BaseEntryPoint]:\n        # importlib.metadata's EntryPoint structure sasitfies BaseEntryPoint.\n        return self._dist.entry_points\n\n    def _metadata_impl(self) -> email.message.Message:\n        # From Python 3.10+, importlib.metadata declares PackageMetadata as the\n        # return type. This protocol is unfortunately a disaster now and misses\n        # a ton of fields that we need, including get() and get_payload(). We\n        # rely on the implementation that the object is actually a Message now,\n        # until upstream can improve the protocol. (python/cpython#94952)\n        return cast(email.message.Message, self._dist.metadata)\n\n    def iter_provided_extras(self) -> Iterable[str]:\n        return (\n            safe_extra(extra) for extra in self.metadata.get_all(\"Provides-Extra\", [])\n        )\n\n    def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:\n        contexts: Sequence[Dict[str, str]] = [{\"extra\": safe_extra(e)} for e in extras]\n        for req_string in self.metadata.get_all(\"Requires-Dist\", []):\n            req = Requirement(req_string)\n            if not req.marker:\n                yield req\n            elif not extras and req.marker.evaluate({\"extra\": \"\"}):\n                yield req\n            elif any(req.marker.evaluate(context) for context in contexts):\n                yield req\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/metadata/importlib/_envs.py",
    "content": "import functools\nimport importlib.metadata\nimport logging\nimport os\nimport pathlib\nimport sys\nimport zipfile\nimport zipimport\nfrom typing import Iterator, List, Optional, Sequence, Set, Tuple\n\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\n\nfrom pip._internal.metadata.base import BaseDistribution, BaseEnvironment\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.utils.deprecation import deprecated\nfrom pip._internal.utils.filetypes import WHEEL_EXTENSION\n\nfrom ._compat import BadMetadata, BasePath, get_dist_name, get_info_location\nfrom ._dists import Distribution\n\nlogger = logging.getLogger(__name__)\n\n\ndef _looks_like_wheel(location: str) -> bool:\n    if not location.endswith(WHEEL_EXTENSION):\n        return False\n    if not os.path.isfile(location):\n        return False\n    if not Wheel.wheel_file_re.match(os.path.basename(location)):\n        return False\n    return zipfile.is_zipfile(location)\n\n\nclass _DistributionFinder:\n    \"\"\"Finder to locate distributions.\n\n    The main purpose of this class is to memoize found distributions' names, so\n    only one distribution is returned for each package name. At lot of pip code\n    assumes this (because it is setuptools's behavior), and not doing the same\n    can potentially cause a distribution in lower precedence path to override a\n    higher precedence one if the caller is not careful.\n\n    Eventually we probably want to make it possible to see lower precedence\n    installations as well. It's useful feature, after all.\n    \"\"\"\n\n    FoundResult = Tuple[importlib.metadata.Distribution, Optional[BasePath]]\n\n    def __init__(self) -> None:\n        self._found_names: Set[NormalizedName] = set()\n\n    def _find_impl(self, location: str) -> Iterator[FoundResult]:\n        \"\"\"Find distributions in a location.\"\"\"\n        # Skip looking inside a wheel. Since a package inside a wheel is not\n        # always valid (due to .data directories etc.), its .dist-info entry\n        # should not be considered an installed distribution.\n        if _looks_like_wheel(location):\n            return\n        # To know exactly where we find a distribution, we have to feed in the\n        # paths one by one, instead of dumping the list to importlib.metadata.\n        for dist in importlib.metadata.distributions(path=[location]):\n            info_location = get_info_location(dist)\n            try:\n                raw_name = get_dist_name(dist)\n            except BadMetadata as e:\n                logger.warning(\"Skipping %s due to %s\", info_location, e.reason)\n                continue\n            normalized_name = canonicalize_name(raw_name)\n            if normalized_name in self._found_names:\n                continue\n            self._found_names.add(normalized_name)\n            yield dist, info_location\n\n    def find(self, location: str) -> Iterator[BaseDistribution]:\n        \"\"\"Find distributions in a location.\n\n        The path can be either a directory, or a ZIP archive.\n        \"\"\"\n        for dist, info_location in self._find_impl(location):\n            if info_location is None:\n                installed_location: Optional[BasePath] = None\n            else:\n                installed_location = info_location.parent\n            yield Distribution(dist, info_location, installed_location)\n\n    def find_linked(self, location: str) -> Iterator[BaseDistribution]:\n        \"\"\"Read location in egg-link files and return distributions in there.\n\n        The path should be a directory; otherwise this returns nothing. This\n        follows how setuptools does this for compatibility. The first non-empty\n        line in the egg-link is read as a path (resolved against the egg-link's\n        containing directory if relative). Distributions found at that linked\n        location are returned.\n        \"\"\"\n        path = pathlib.Path(location)\n        if not path.is_dir():\n            return\n        for child in path.iterdir():\n            if child.suffix != \".egg-link\":\n                continue\n            with child.open() as f:\n                lines = (line.strip() for line in f)\n                target_rel = next((line for line in lines if line), \"\")\n            if not target_rel:\n                continue\n            target_location = str(path.joinpath(target_rel))\n            for dist, info_location in self._find_impl(target_location):\n                yield Distribution(dist, info_location, path)\n\n    def _find_eggs_in_dir(self, location: str) -> Iterator[BaseDistribution]:\n        from pip._vendor.pkg_resources import find_distributions\n\n        from pip._internal.metadata import pkg_resources as legacy\n\n        with os.scandir(location) as it:\n            for entry in it:\n                if not entry.name.endswith(\".egg\"):\n                    continue\n                for dist in find_distributions(entry.path):\n                    yield legacy.Distribution(dist)\n\n    def _find_eggs_in_zip(self, location: str) -> Iterator[BaseDistribution]:\n        from pip._vendor.pkg_resources import find_eggs_in_zip\n\n        from pip._internal.metadata import pkg_resources as legacy\n\n        try:\n            importer = zipimport.zipimporter(location)\n        except zipimport.ZipImportError:\n            return\n        for dist in find_eggs_in_zip(importer, location):\n            yield legacy.Distribution(dist)\n\n    def find_eggs(self, location: str) -> Iterator[BaseDistribution]:\n        \"\"\"Find eggs in a location.\n\n        This actually uses the old *pkg_resources* backend. We likely want to\n        deprecate this so we can eventually remove the *pkg_resources*\n        dependency entirely. Before that, this should first emit a deprecation\n        warning for some versions when using the fallback since importing\n        *pkg_resources* is slow for those who don't need it.\n        \"\"\"\n        if os.path.isdir(location):\n            yield from self._find_eggs_in_dir(location)\n        if zipfile.is_zipfile(location):\n            yield from self._find_eggs_in_zip(location)\n\n\n@functools.lru_cache(maxsize=None)  # Warn a distribution exactly once.\ndef _emit_egg_deprecation(location: Optional[str]) -> None:\n    deprecated(\n        reason=f\"Loading egg at {location} is deprecated.\",\n        replacement=\"to use pip for package installation.\",\n        gone_in=None,\n    )\n\n\nclass Environment(BaseEnvironment):\n    def __init__(self, paths: Sequence[str]) -> None:\n        self._paths = paths\n\n    @classmethod\n    def default(cls) -> BaseEnvironment:\n        return cls(sys.path)\n\n    @classmethod\n    def from_paths(cls, paths: Optional[List[str]]) -> BaseEnvironment:\n        if paths is None:\n            return cls(sys.path)\n        return cls(paths)\n\n    def _iter_distributions(self) -> Iterator[BaseDistribution]:\n        finder = _DistributionFinder()\n        for location in self._paths:\n            yield from finder.find(location)\n            for dist in finder.find_eggs(location):\n                # _emit_egg_deprecation(dist.location)  # TODO: Enable this.\n                yield dist\n            # This must go last because that's how pkg_resources tie-breaks.\n            yield from finder.find_linked(location)\n\n    def get_distribution(self, name: str) -> Optional[BaseDistribution]:\n        matches = (\n            distribution\n            for distribution in self.iter_all_distributions()\n            if distribution.canonical_name == canonicalize_name(name)\n        )\n        return next(matches, None)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/metadata/pkg_resources.py",
    "content": "import email.message\nimport email.parser\nimport logging\nimport os\nimport zipfile\nfrom typing import Collection, Iterable, Iterator, List, Mapping, NamedTuple, Optional\n\nfrom pip._vendor import pkg_resources\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\nfrom pip._vendor.packaging.version import parse as parse_version\n\nfrom pip._internal.exceptions import InvalidWheel, NoneMetadataError, UnsupportedWheel\nfrom pip._internal.utils.egg_link import egg_link_path_from_location\nfrom pip._internal.utils.misc import display_path, normalize_path\nfrom pip._internal.utils.wheel import parse_wheel, read_wheel_metadata_file\n\nfrom .base import (\n    BaseDistribution,\n    BaseEntryPoint,\n    BaseEnvironment,\n    DistributionVersion,\n    InfoPath,\n    Wheel,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass EntryPoint(NamedTuple):\n    name: str\n    value: str\n    group: str\n\n\nclass InMemoryMetadata:\n    \"\"\"IMetadataProvider that reads metadata files from a dictionary.\n\n    This also maps metadata decoding exceptions to our internal exception type.\n    \"\"\"\n\n    def __init__(self, metadata: Mapping[str, bytes], wheel_name: str) -> None:\n        self._metadata = metadata\n        self._wheel_name = wheel_name\n\n    def has_metadata(self, name: str) -> bool:\n        return name in self._metadata\n\n    def get_metadata(self, name: str) -> str:\n        try:\n            return self._metadata[name].decode()\n        except UnicodeDecodeError as e:\n            # Augment the default error with the origin of the file.\n            raise UnsupportedWheel(\n                f\"Error decoding metadata for {self._wheel_name}: {e} in {name} file\"\n            )\n\n    def get_metadata_lines(self, name: str) -> Iterable[str]:\n        return pkg_resources.yield_lines(self.get_metadata(name))\n\n    def metadata_isdir(self, name: str) -> bool:\n        return False\n\n    def metadata_listdir(self, name: str) -> List[str]:\n        return []\n\n    def run_script(self, script_name: str, namespace: str) -> None:\n        pass\n\n\nclass Distribution(BaseDistribution):\n    def __init__(self, dist: pkg_resources.Distribution) -> None:\n        self._dist = dist\n\n    @classmethod\n    def from_directory(cls, directory: str) -> BaseDistribution:\n        dist_dir = directory.rstrip(os.sep)\n\n        # Build a PathMetadata object, from path to metadata. :wink:\n        base_dir, dist_dir_name = os.path.split(dist_dir)\n        metadata = pkg_resources.PathMetadata(base_dir, dist_dir)\n\n        # Determine the correct Distribution object type.\n        if dist_dir.endswith(\".egg-info\"):\n            dist_cls = pkg_resources.Distribution\n            dist_name = os.path.splitext(dist_dir_name)[0]\n        else:\n            assert dist_dir.endswith(\".dist-info\")\n            dist_cls = pkg_resources.DistInfoDistribution\n            dist_name = os.path.splitext(dist_dir_name)[0].split(\"-\")[0]\n\n        dist = dist_cls(base_dir, project_name=dist_name, metadata=metadata)\n        return cls(dist)\n\n    @classmethod\n    def from_metadata_file_contents(\n        cls,\n        metadata_contents: bytes,\n        filename: str,\n        project_name: str,\n    ) -> BaseDistribution:\n        metadata_dict = {\n            \"METADATA\": metadata_contents,\n        }\n        dist = pkg_resources.DistInfoDistribution(\n            location=filename,\n            metadata=InMemoryMetadata(metadata_dict, filename),\n            project_name=project_name,\n        )\n        return cls(dist)\n\n    @classmethod\n    def from_wheel(cls, wheel: Wheel, name: str) -> BaseDistribution:\n        try:\n            with wheel.as_zipfile() as zf:\n                info_dir, _ = parse_wheel(zf, name)\n                metadata_dict = {\n                    path.split(\"/\", 1)[-1]: read_wheel_metadata_file(zf, path)\n                    for path in zf.namelist()\n                    if path.startswith(f\"{info_dir}/\")\n                }\n        except zipfile.BadZipFile as e:\n            raise InvalidWheel(wheel.location, name) from e\n        except UnsupportedWheel as e:\n            raise UnsupportedWheel(f\"{name} has an invalid wheel, {e}\")\n        dist = pkg_resources.DistInfoDistribution(\n            location=wheel.location,\n            metadata=InMemoryMetadata(metadata_dict, wheel.location),\n            project_name=name,\n        )\n        return cls(dist)\n\n    @property\n    def location(self) -> Optional[str]:\n        return self._dist.location\n\n    @property\n    def installed_location(self) -> Optional[str]:\n        egg_link = egg_link_path_from_location(self.raw_name)\n        if egg_link:\n            location = egg_link\n        elif self.location:\n            location = self.location\n        else:\n            return None\n        return normalize_path(location)\n\n    @property\n    def info_location(self) -> Optional[str]:\n        return self._dist.egg_info\n\n    @property\n    def installed_by_distutils(self) -> bool:\n        # A distutils-installed distribution is provided by FileMetadata. This\n        # provider has a \"path\" attribute not present anywhere else. Not the\n        # best introspection logic, but pip has been doing this for a long time.\n        try:\n            return bool(self._dist._provider.path)\n        except AttributeError:\n            return False\n\n    @property\n    def canonical_name(self) -> NormalizedName:\n        return canonicalize_name(self._dist.project_name)\n\n    @property\n    def version(self) -> DistributionVersion:\n        return parse_version(self._dist.version)\n\n    def is_file(self, path: InfoPath) -> bool:\n        return self._dist.has_metadata(str(path))\n\n    def iter_distutils_script_names(self) -> Iterator[str]:\n        yield from self._dist.metadata_listdir(\"scripts\")\n\n    def read_text(self, path: InfoPath) -> str:\n        name = str(path)\n        if not self._dist.has_metadata(name):\n            raise FileNotFoundError(name)\n        content = self._dist.get_metadata(name)\n        if content is None:\n            raise NoneMetadataError(self, name)\n        return content\n\n    def iter_entry_points(self) -> Iterable[BaseEntryPoint]:\n        for group, entries in self._dist.get_entry_map().items():\n            for name, entry_point in entries.items():\n                name, _, value = str(entry_point).partition(\"=\")\n                yield EntryPoint(name=name.strip(), value=value.strip(), group=group)\n\n    def _metadata_impl(self) -> email.message.Message:\n        \"\"\"\n        :raises NoneMetadataError: if the distribution reports `has_metadata()`\n            True but `get_metadata()` returns None.\n        \"\"\"\n        if isinstance(self._dist, pkg_resources.DistInfoDistribution):\n            metadata_name = \"METADATA\"\n        else:\n            metadata_name = \"PKG-INFO\"\n        try:\n            metadata = self.read_text(metadata_name)\n        except FileNotFoundError:\n            if self.location:\n                displaying_path = display_path(self.location)\n            else:\n                displaying_path = repr(self.location)\n            logger.warning(\"No metadata found in %s\", displaying_path)\n            metadata = \"\"\n        feed_parser = email.parser.FeedParser()\n        feed_parser.feed(metadata)\n        return feed_parser.close()\n\n    def iter_dependencies(self, extras: Collection[str] = ()) -> Iterable[Requirement]:\n        if extras:  # pkg_resources raises on invalid extras, so we sanitize.\n            extras = frozenset(extras).intersection(self._dist.extras)\n        return self._dist.requires(extras)\n\n    def iter_provided_extras(self) -> Iterable[str]:\n        return self._dist.extras\n\n\nclass Environment(BaseEnvironment):\n    def __init__(self, ws: pkg_resources.WorkingSet) -> None:\n        self._ws = ws\n\n    @classmethod\n    def default(cls) -> BaseEnvironment:\n        return cls(pkg_resources.working_set)\n\n    @classmethod\n    def from_paths(cls, paths: Optional[List[str]]) -> BaseEnvironment:\n        return cls(pkg_resources.WorkingSet(paths))\n\n    def _iter_distributions(self) -> Iterator[BaseDistribution]:\n        for dist in self._ws:\n            yield Distribution(dist)\n\n    def _search_distribution(self, name: str) -> Optional[BaseDistribution]:\n        \"\"\"Find a distribution matching the ``name`` in the environment.\n\n        This searches from *all* distributions available in the environment, to\n        match the behavior of ``pkg_resources.get_distribution()``.\n        \"\"\"\n        canonical_name = canonicalize_name(name)\n        for dist in self.iter_all_distributions():\n            if dist.canonical_name == canonical_name:\n                return dist\n        return None\n\n    def get_distribution(self, name: str) -> Optional[BaseDistribution]:\n        # Search the distribution by looking through the working set.\n        dist = self._search_distribution(name)\n        if dist:\n            return dist\n\n        # If distribution could not be found, call working_set.require to\n        # update the working set, and try to find the distribution again.\n        # This might happen for e.g. when you install a package twice, once\n        # using setup.py develop and again using setup.py install. Now when\n        # running pip uninstall twice, the package gets removed from the\n        # working set in the first uninstall, so we have to populate the\n        # working set again so that pip knows about it and the packages gets\n        # picked up and is successfully uninstalled the second time too.\n        try:\n            # We didn't pass in any version specifiers, so this can never\n            # raise pkg_resources.VersionConflict.\n            self._ws.require(name)\n        except pkg_resources.DistributionNotFound:\n            return None\n        return self._search_distribution(name)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/models/__init__.py",
    "content": "\"\"\"A package that contains models that represent entities.\n\"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/models/candidate.py",
    "content": "from pip._vendor.packaging.version import parse as parse_version\n\nfrom pip._internal.models.link import Link\nfrom pip._internal.utils.models import KeyBasedCompareMixin\n\n\nclass InstallationCandidate(KeyBasedCompareMixin):\n    \"\"\"Represents a potential \"candidate\" for installation.\"\"\"\n\n    __slots__ = [\"name\", \"version\", \"link\"]\n\n    def __init__(self, name: str, version: str, link: Link) -> None:\n        self.name = name\n        self.version = parse_version(version)\n        self.link = link\n\n        super().__init__(\n            key=(self.name, self.version, self.link),\n            defining_class=InstallationCandidate,\n        )\n\n    def __repr__(self) -> str:\n        return \"<InstallationCandidate({!r}, {!r}, {!r})>\".format(\n            self.name,\n            self.version,\n            self.link,\n        )\n\n    def __str__(self) -> str:\n        return \"{!r} candidate (version {} at {})\".format(\n            self.name,\n            self.version,\n            self.link,\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/models/direct_url.py",
    "content": "\"\"\" PEP 610 \"\"\"\nimport json\nimport re\nimport urllib.parse\nfrom typing import Any, Dict, Iterable, Optional, Type, TypeVar, Union\n\n__all__ = [\n    \"DirectUrl\",\n    \"DirectUrlValidationError\",\n    \"DirInfo\",\n    \"ArchiveInfo\",\n    \"VcsInfo\",\n]\n\nT = TypeVar(\"T\")\n\nDIRECT_URL_METADATA_NAME = \"direct_url.json\"\nENV_VAR_RE = re.compile(r\"^\\$\\{[A-Za-z0-9-_]+\\}(:\\$\\{[A-Za-z0-9-_]+\\})?$\")\n\n\nclass DirectUrlValidationError(Exception):\n    pass\n\n\ndef _get(\n    d: Dict[str, Any], expected_type: Type[T], key: str, default: Optional[T] = None\n) -> Optional[T]:\n    \"\"\"Get value from dictionary and verify expected type.\"\"\"\n    if key not in d:\n        return default\n    value = d[key]\n    if not isinstance(value, expected_type):\n        raise DirectUrlValidationError(\n            \"{!r} has unexpected type for {} (expected {})\".format(\n                value, key, expected_type\n            )\n        )\n    return value\n\n\ndef _get_required(\n    d: Dict[str, Any], expected_type: Type[T], key: str, default: Optional[T] = None\n) -> T:\n    value = _get(d, expected_type, key, default)\n    if value is None:\n        raise DirectUrlValidationError(f\"{key} must have a value\")\n    return value\n\n\ndef _exactly_one_of(infos: Iterable[Optional[\"InfoType\"]]) -> \"InfoType\":\n    infos = [info for info in infos if info is not None]\n    if not infos:\n        raise DirectUrlValidationError(\n            \"missing one of archive_info, dir_info, vcs_info\"\n        )\n    if len(infos) > 1:\n        raise DirectUrlValidationError(\n            \"more than one of archive_info, dir_info, vcs_info\"\n        )\n    assert infos[0] is not None\n    return infos[0]\n\n\ndef _filter_none(**kwargs: Any) -> Dict[str, Any]:\n    \"\"\"Make dict excluding None values.\"\"\"\n    return {k: v for k, v in kwargs.items() if v is not None}\n\n\nclass VcsInfo:\n    name = \"vcs_info\"\n\n    def __init__(\n        self,\n        vcs: str,\n        commit_id: str,\n        requested_revision: Optional[str] = None,\n    ) -> None:\n        self.vcs = vcs\n        self.requested_revision = requested_revision\n        self.commit_id = commit_id\n\n    @classmethod\n    def _from_dict(cls, d: Optional[Dict[str, Any]]) -> Optional[\"VcsInfo\"]:\n        if d is None:\n            return None\n        return cls(\n            vcs=_get_required(d, str, \"vcs\"),\n            commit_id=_get_required(d, str, \"commit_id\"),\n            requested_revision=_get(d, str, \"requested_revision\"),\n        )\n\n    def _to_dict(self) -> Dict[str, Any]:\n        return _filter_none(\n            vcs=self.vcs,\n            requested_revision=self.requested_revision,\n            commit_id=self.commit_id,\n        )\n\n\nclass ArchiveInfo:\n    name = \"archive_info\"\n\n    def __init__(\n        self,\n        hash: Optional[str] = None,\n    ) -> None:\n        self.hash = hash\n\n    @classmethod\n    def _from_dict(cls, d: Optional[Dict[str, Any]]) -> Optional[\"ArchiveInfo\"]:\n        if d is None:\n            return None\n        return cls(hash=_get(d, str, \"hash\"))\n\n    def _to_dict(self) -> Dict[str, Any]:\n        return _filter_none(hash=self.hash)\n\n\nclass DirInfo:\n    name = \"dir_info\"\n\n    def __init__(\n        self,\n        editable: bool = False,\n    ) -> None:\n        self.editable = editable\n\n    @classmethod\n    def _from_dict(cls, d: Optional[Dict[str, Any]]) -> Optional[\"DirInfo\"]:\n        if d is None:\n            return None\n        return cls(editable=_get_required(d, bool, \"editable\", default=False))\n\n    def _to_dict(self) -> Dict[str, Any]:\n        return _filter_none(editable=self.editable or None)\n\n\nInfoType = Union[ArchiveInfo, DirInfo, VcsInfo]\n\n\nclass DirectUrl:\n    def __init__(\n        self,\n        url: str,\n        info: InfoType,\n        subdirectory: Optional[str] = None,\n    ) -> None:\n        self.url = url\n        self.info = info\n        self.subdirectory = subdirectory\n\n    def _remove_auth_from_netloc(self, netloc: str) -> str:\n        if \"@\" not in netloc:\n            return netloc\n        user_pass, netloc_no_user_pass = netloc.split(\"@\", 1)\n        if (\n            isinstance(self.info, VcsInfo)\n            and self.info.vcs == \"git\"\n            and user_pass == \"git\"\n        ):\n            return netloc\n        if ENV_VAR_RE.match(user_pass):\n            return netloc\n        return netloc_no_user_pass\n\n    @property\n    def redacted_url(self) -> str:\n        \"\"\"url with user:password part removed unless it is formed with\n        environment variables as specified in PEP 610, or it is ``git``\n        in the case of a git URL.\n        \"\"\"\n        purl = urllib.parse.urlsplit(self.url)\n        netloc = self._remove_auth_from_netloc(purl.netloc)\n        surl = urllib.parse.urlunsplit(\n            (purl.scheme, netloc, purl.path, purl.query, purl.fragment)\n        )\n        return surl\n\n    def validate(self) -> None:\n        self.from_dict(self.to_dict())\n\n    @classmethod\n    def from_dict(cls, d: Dict[str, Any]) -> \"DirectUrl\":\n        return DirectUrl(\n            url=_get_required(d, str, \"url\"),\n            subdirectory=_get(d, str, \"subdirectory\"),\n            info=_exactly_one_of(\n                [\n                    ArchiveInfo._from_dict(_get(d, dict, \"archive_info\")),\n                    DirInfo._from_dict(_get(d, dict, \"dir_info\")),\n                    VcsInfo._from_dict(_get(d, dict, \"vcs_info\")),\n                ]\n            ),\n        )\n\n    def to_dict(self) -> Dict[str, Any]:\n        res = _filter_none(\n            url=self.redacted_url,\n            subdirectory=self.subdirectory,\n        )\n        res[self.info.name] = self.info._to_dict()\n        return res\n\n    @classmethod\n    def from_json(cls, s: str) -> \"DirectUrl\":\n        return cls.from_dict(json.loads(s))\n\n    def to_json(self) -> str:\n        return json.dumps(self.to_dict(), sort_keys=True)\n\n    def is_local_editable(self) -> bool:\n        return isinstance(self.info, DirInfo) and self.info.editable\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/models/format_control.py",
    "content": "from typing import FrozenSet, Optional, Set\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.exceptions import CommandError\n\n\nclass FormatControl:\n    \"\"\"Helper for managing formats from which a package can be installed.\"\"\"\n\n    __slots__ = [\"no_binary\", \"only_binary\"]\n\n    def __init__(\n        self,\n        no_binary: Optional[Set[str]] = None,\n        only_binary: Optional[Set[str]] = None,\n    ) -> None:\n        if no_binary is None:\n            no_binary = set()\n        if only_binary is None:\n            only_binary = set()\n\n        self.no_binary = no_binary\n        self.only_binary = only_binary\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, self.__class__):\n            return NotImplemented\n\n        if self.__slots__ != other.__slots__:\n            return False\n\n        return all(getattr(self, k) == getattr(other, k) for k in self.__slots__)\n\n    def __repr__(self) -> str:\n        return \"{}({}, {})\".format(\n            self.__class__.__name__, self.no_binary, self.only_binary\n        )\n\n    @staticmethod\n    def handle_mutual_excludes(value: str, target: Set[str], other: Set[str]) -> None:\n        if value.startswith(\"-\"):\n            raise CommandError(\n                \"--no-binary / --only-binary option requires 1 argument.\"\n            )\n        new = value.split(\",\")\n        while \":all:\" in new:\n            other.clear()\n            target.clear()\n            target.add(\":all:\")\n            del new[: new.index(\":all:\") + 1]\n            # Without a none, we want to discard everything as :all: covers it\n            if \":none:\" not in new:\n                return\n        for name in new:\n            if name == \":none:\":\n                target.clear()\n                continue\n            name = canonicalize_name(name)\n            other.discard(name)\n            target.add(name)\n\n    def get_allowed_formats(self, canonical_name: str) -> FrozenSet[str]:\n        result = {\"binary\", \"source\"}\n        if canonical_name in self.only_binary:\n            result.discard(\"source\")\n        elif canonical_name in self.no_binary:\n            result.discard(\"binary\")\n        elif \":all:\" in self.only_binary:\n            result.discard(\"source\")\n        elif \":all:\" in self.no_binary:\n            result.discard(\"binary\")\n        return frozenset(result)\n\n    def disallow_binaries(self) -> None:\n        self.handle_mutual_excludes(\n            \":all:\",\n            self.no_binary,\n            self.only_binary,\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/models/index.py",
    "content": "import urllib.parse\n\n\nclass PackageIndex:\n    \"\"\"Represents a Package Index and provides easier access to endpoints\"\"\"\n\n    __slots__ = [\"url\", \"netloc\", \"simple_url\", \"pypi_url\", \"file_storage_domain\"]\n\n    def __init__(self, url: str, file_storage_domain: str) -> None:\n        super().__init__()\n        self.url = url\n        self.netloc = urllib.parse.urlsplit(url).netloc\n        self.simple_url = self._url_for_path(\"simple\")\n        self.pypi_url = self._url_for_path(\"pypi\")\n\n        # This is part of a temporary hack used to block installs of PyPI\n        # packages which depend on external urls only necessary until PyPI can\n        # block such packages themselves\n        self.file_storage_domain = file_storage_domain\n\n    def _url_for_path(self, path: str) -> str:\n        return urllib.parse.urljoin(self.url, path)\n\n\nPyPI = PackageIndex(\"https://pypi.org/\", file_storage_domain=\"files.pythonhosted.org\")\nTestPyPI = PackageIndex(\n    \"https://test.pypi.org/\", file_storage_domain=\"test-files.pythonhosted.org\"\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/models/installation_report.py",
    "content": "from typing import Any, Dict, Sequence\n\nfrom pip._vendor.packaging.markers import default_environment\n\nfrom pip import __version__\nfrom pip._internal.req.req_install import InstallRequirement\n\n\nclass InstallationReport:\n    def __init__(self, install_requirements: Sequence[InstallRequirement]):\n        self._install_requirements = install_requirements\n\n    @classmethod\n    def _install_req_to_dict(cls, ireq: InstallRequirement) -> Dict[str, Any]:\n        assert ireq.download_info, f\"No download_info for {ireq}\"\n        res = {\n            # PEP 610 json for the download URL. download_info.archive_info.hash may\n            # be absent when the requirement was installed from the wheel cache\n            # and the cache entry was populated by an older pip version that did not\n            # record origin.json.\n            \"download_info\": ireq.download_info.to_dict(),\n            # is_direct is true if the requirement was a direct URL reference (which\n            # includes editable requirements), and false if the requirement was\n            # downloaded from a PEP 503 index or --find-links.\n            \"is_direct\": bool(ireq.original_link),\n            # requested is true if the requirement was specified by the user (aka\n            # top level requirement), and false if it was installed as a dependency of a\n            # requirement. https://peps.python.org/pep-0376/#requested\n            \"requested\": ireq.user_supplied,\n            # PEP 566 json encoding for metadata\n            # https://www.python.org/dev/peps/pep-0566/#json-compatible-metadata\n            \"metadata\": ireq.get_dist().metadata_dict,\n        }\n        if ireq.user_supplied and ireq.extras:\n            # For top level requirements, the list of requested extras, if any.\n            res[\"requested_extras\"] = list(sorted(ireq.extras))\n        return res\n\n    def to_dict(self) -> Dict[str, Any]:\n        return {\n            \"version\": \"0\",\n            \"pip_version\": __version__,\n            \"install\": [\n                self._install_req_to_dict(ireq) for ireq in self._install_requirements\n            ],\n            # https://peps.python.org/pep-0508/#environment-markers\n            # TODO: currently, the resolver uses the default environment to evaluate\n            # environment markers, so that is what we report here. In the future, it\n            # should also take into account options such as --python-version or\n            # --platform, perhaps under the form of an environment_override field?\n            # https://github.com/pypa/pip/issues/11198\n            \"environment\": default_environment(),\n        }\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/models/link.py",
    "content": "import functools\nimport itertools\nimport logging\nimport os\nimport posixpath\nimport re\nimport urllib.parse\nfrom dataclasses import dataclass\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Dict,\n    List,\n    Mapping,\n    NamedTuple,\n    Optional,\n    Tuple,\n    Union,\n)\n\nfrom pip._internal.utils.filetypes import WHEEL_EXTENSION\nfrom pip._internal.utils.hashes import Hashes\nfrom pip._internal.utils.misc import (\n    pairwise,\n    redact_auth_from_url,\n    split_auth_from_netloc,\n    splitext,\n)\nfrom pip._internal.utils.models import KeyBasedCompareMixin\nfrom pip._internal.utils.urls import path_to_url, url_to_path\n\nif TYPE_CHECKING:\n    from pip._internal.index.collector import IndexContent\n\nlogger = logging.getLogger(__name__)\n\n\n# Order matters, earlier hashes have a precedence over later hashes for what\n# we will pick to use.\n_SUPPORTED_HASHES = (\"sha512\", \"sha384\", \"sha256\", \"sha224\", \"sha1\", \"md5\")\n\n\n@dataclass(frozen=True)\nclass LinkHash:\n    \"\"\"Links to content may have embedded hash values. This class parses those.\n\n    `name` must be any member of `_SUPPORTED_HASHES`.\n\n    This class can be converted to and from `ArchiveInfo`. While ArchiveInfo intends to\n    be JSON-serializable to conform to PEP 610, this class contains the logic for\n    parsing a hash name and value for correctness, and then checking whether that hash\n    conforms to a schema with `.is_hash_allowed()`.\"\"\"\n\n    name: str\n    value: str\n\n    _hash_re = re.compile(\n        # NB: we do not validate that the second group (.*) is a valid hex\n        # digest. Instead, we simply keep that string in this class, and then check it\n        # against Hashes when hash-checking is needed. This is easier to debug than\n        # proactively discarding an invalid hex digest, as we handle incorrect hashes\n        # and malformed hashes in the same place.\n        r\"({choices})=(.*)\".format(\n            choices=\"|\".join(re.escape(hash_name) for hash_name in _SUPPORTED_HASHES)\n        ),\n    )\n\n    def __post_init__(self) -> None:\n        assert self._hash_re.match(f\"{self.name}={self.value}\")\n\n    @classmethod\n    @functools.lru_cache(maxsize=None)\n    def split_hash_name_and_value(cls, url: str) -> Optional[\"LinkHash\"]:\n        \"\"\"Search a string for a checksum algorithm name and encoded output value.\"\"\"\n        match = cls._hash_re.search(url)\n        if match is None:\n            return None\n        name, value = match.groups()\n        return cls(name=name, value=value)\n\n    def as_hashes(self) -> Hashes:\n        \"\"\"Return a Hashes instance which checks only for the current hash.\"\"\"\n        return Hashes({self.name: [self.value]})\n\n    def is_hash_allowed(self, hashes: Optional[Hashes]) -> bool:\n        \"\"\"\n        Return True if the current hash is allowed by `hashes`.\n        \"\"\"\n        if hashes is None:\n            return False\n        return hashes.is_hash_allowed(self.name, hex_digest=self.value)\n\n\ndef _clean_url_path_part(part: str) -> str:\n    \"\"\"\n    Clean a \"part\" of a URL path (i.e. after splitting on \"@\" characters).\n    \"\"\"\n    # We unquote prior to quoting to make sure nothing is double quoted.\n    return urllib.parse.quote(urllib.parse.unquote(part))\n\n\ndef _clean_file_url_path(part: str) -> str:\n    \"\"\"\n    Clean the first part of a URL path that corresponds to a local\n    filesystem path (i.e. the first part after splitting on \"@\" characters).\n    \"\"\"\n    # We unquote prior to quoting to make sure nothing is double quoted.\n    # Also, on Windows the path part might contain a drive letter which\n    # should not be quoted. On Linux where drive letters do not\n    # exist, the colon should be quoted. We rely on urllib.request\n    # to do the right thing here.\n    return urllib.request.pathname2url(urllib.request.url2pathname(part))\n\n\n# percent-encoded:                   /\n_reserved_chars_re = re.compile(\"(@|%2F)\", re.IGNORECASE)\n\n\ndef _clean_url_path(path: str, is_local_path: bool) -> str:\n    \"\"\"\n    Clean the path portion of a URL.\n    \"\"\"\n    if is_local_path:\n        clean_func = _clean_file_url_path\n    else:\n        clean_func = _clean_url_path_part\n\n    # Split on the reserved characters prior to cleaning so that\n    # revision strings in VCS URLs are properly preserved.\n    parts = _reserved_chars_re.split(path)\n\n    cleaned_parts = []\n    for to_clean, reserved in pairwise(itertools.chain(parts, [\"\"])):\n        cleaned_parts.append(clean_func(to_clean))\n        # Normalize %xx escapes (e.g. %2f -> %2F)\n        cleaned_parts.append(reserved.upper())\n\n    return \"\".join(cleaned_parts)\n\n\ndef _ensure_quoted_url(url: str) -> str:\n    \"\"\"\n    Make sure a link is fully quoted.\n    For example, if ' ' occurs in the URL, it will be replaced with \"%20\",\n    and without double-quoting other characters.\n    \"\"\"\n    # Split the URL into parts according to the general structure\n    # `scheme://netloc/path;parameters?query#fragment`.\n    result = urllib.parse.urlparse(url)\n    # If the netloc is empty, then the URL refers to a local filesystem path.\n    is_local_path = not result.netloc\n    path = _clean_url_path(result.path, is_local_path=is_local_path)\n    return urllib.parse.urlunparse(result._replace(path=path))\n\n\nclass Link(KeyBasedCompareMixin):\n    \"\"\"Represents a parsed link from a Package Index's simple URL\"\"\"\n\n    __slots__ = [\n        \"_parsed_url\",\n        \"_url\",\n        \"_hashes\",\n        \"comes_from\",\n        \"requires_python\",\n        \"yanked_reason\",\n        \"dist_info_metadata\",\n        \"link_hash\",\n        \"cache_link_parsing\",\n    ]\n\n    def __init__(\n        self,\n        url: str,\n        comes_from: Optional[Union[str, \"IndexContent\"]] = None,\n        requires_python: Optional[str] = None,\n        yanked_reason: Optional[str] = None,\n        dist_info_metadata: Optional[str] = None,\n        link_hash: Optional[LinkHash] = None,\n        cache_link_parsing: bool = True,\n        hashes: Optional[Mapping[str, str]] = None,\n    ) -> None:\n        \"\"\"\n        :param url: url of the resource pointed to (href of the link)\n        :param comes_from: instance of IndexContent where the link was found,\n            or string.\n        :param requires_python: String containing the `Requires-Python`\n            metadata field, specified in PEP 345. This may be specified by\n            a data-requires-python attribute in the HTML link tag, as\n            described in PEP 503.\n        :param yanked_reason: the reason the file has been yanked, if the\n            file has been yanked, or None if the file hasn't been yanked.\n            This is the value of the \"data-yanked\" attribute, if present, in\n            a simple repository HTML link. If the file has been yanked but\n            no reason was provided, this should be the empty string. See\n            PEP 592 for more information and the specification.\n        :param dist_info_metadata: the metadata attached to the file, or None if no such\n            metadata is provided. This is the value of the \"data-dist-info-metadata\"\n            attribute, if present, in a simple repository HTML link. This may be parsed\n            into its own `Link` by `self.metadata_link()`. See PEP 658 for more\n            information and the specification.\n        :param link_hash: a checksum for the content the link points to. If not\n            provided, this will be extracted from the link URL, if the URL has\n            any checksum.\n        :param cache_link_parsing: A flag that is used elsewhere to determine\n                                   whether resources retrieved from this link\n                                   should be cached. PyPI index urls should\n                                   generally have this set to False, for\n                                   example.\n        :param hashes: A mapping of hash names to digests to allow us to\n                       determine the validity of a download.\n        \"\"\"\n\n        # url can be a UNC windows share\n        if url.startswith(\"\\\\\\\\\"):\n            url = path_to_url(url)\n\n        self._parsed_url = urllib.parse.urlsplit(url)\n        # Store the url as a private attribute to prevent accidentally\n        # trying to set a new value.\n        self._url = url\n        self._hashes = hashes if hashes is not None else {}\n\n        self.comes_from = comes_from\n        self.requires_python = requires_python if requires_python else None\n        self.yanked_reason = yanked_reason\n        self.dist_info_metadata = dist_info_metadata\n        self.link_hash = link_hash or LinkHash.split_hash_name_and_value(self._url)\n\n        super().__init__(key=url, defining_class=Link)\n\n        self.cache_link_parsing = cache_link_parsing\n\n    @classmethod\n    def from_json(\n        cls,\n        file_data: Dict[str, Any],\n        page_url: str,\n    ) -> Optional[\"Link\"]:\n        \"\"\"\n        Convert an pypi json document from a simple repository page into a Link.\n        \"\"\"\n        file_url = file_data.get(\"url\")\n        if file_url is None:\n            return None\n\n        url = _ensure_quoted_url(urllib.parse.urljoin(page_url, file_url))\n        pyrequire = file_data.get(\"requires-python\")\n        yanked_reason = file_data.get(\"yanked\")\n        dist_info_metadata = file_data.get(\"dist-info-metadata\")\n        hashes = file_data.get(\"hashes\", {})\n\n        # The Link.yanked_reason expects an empty string instead of a boolean.\n        if yanked_reason and not isinstance(yanked_reason, str):\n            yanked_reason = \"\"\n        # The Link.yanked_reason expects None instead of False.\n        elif not yanked_reason:\n            yanked_reason = None\n\n        return cls(\n            url,\n            comes_from=page_url,\n            requires_python=pyrequire,\n            yanked_reason=yanked_reason,\n            hashes=hashes,\n            dist_info_metadata=dist_info_metadata,\n        )\n\n    @classmethod\n    def from_element(\n        cls,\n        anchor_attribs: Dict[str, Optional[str]],\n        page_url: str,\n        base_url: str,\n    ) -> Optional[\"Link\"]:\n        \"\"\"\n        Convert an anchor element's attributes in a simple repository page to a Link.\n        \"\"\"\n        href = anchor_attribs.get(\"href\")\n        if not href:\n            return None\n\n        url = _ensure_quoted_url(urllib.parse.urljoin(base_url, href))\n        pyrequire = anchor_attribs.get(\"data-requires-python\")\n        yanked_reason = anchor_attribs.get(\"data-yanked\")\n        dist_info_metadata = anchor_attribs.get(\"data-dist-info-metadata\")\n\n        return cls(\n            url,\n            comes_from=page_url,\n            requires_python=pyrequire,\n            yanked_reason=yanked_reason,\n            dist_info_metadata=dist_info_metadata,\n        )\n\n    def __str__(self) -> str:\n        if self.requires_python:\n            rp = f\" (requires-python:{self.requires_python})\"\n        else:\n            rp = \"\"\n        if self.comes_from:\n            return \"{} (from {}){}\".format(\n                redact_auth_from_url(self._url), self.comes_from, rp\n            )\n        else:\n            return redact_auth_from_url(str(self._url))\n\n    def __repr__(self) -> str:\n        return f\"<Link {self}>\"\n\n    @property\n    def url(self) -> str:\n        return self._url\n\n    @property\n    def filename(self) -> str:\n        path = self.path.rstrip(\"/\")\n        name = posixpath.basename(path)\n        if not name:\n            # Make sure we don't leak auth information if the netloc\n            # includes a username and password.\n            netloc, user_pass = split_auth_from_netloc(self.netloc)\n            return netloc\n\n        name = urllib.parse.unquote(name)\n        assert name, f\"URL {self._url!r} produced no filename\"\n        return name\n\n    @property\n    def file_path(self) -> str:\n        return url_to_path(self.url)\n\n    @property\n    def scheme(self) -> str:\n        return self._parsed_url.scheme\n\n    @property\n    def netloc(self) -> str:\n        \"\"\"\n        This can contain auth information.\n        \"\"\"\n        return self._parsed_url.netloc\n\n    @property\n    def path(self) -> str:\n        return urllib.parse.unquote(self._parsed_url.path)\n\n    def splitext(self) -> Tuple[str, str]:\n        return splitext(posixpath.basename(self.path.rstrip(\"/\")))\n\n    @property\n    def ext(self) -> str:\n        return self.splitext()[1]\n\n    @property\n    def url_without_fragment(self) -> str:\n        scheme, netloc, path, query, fragment = self._parsed_url\n        return urllib.parse.urlunsplit((scheme, netloc, path, query, \"\"))\n\n    _egg_fragment_re = re.compile(r\"[#&]egg=([^&]*)\")\n\n    @property\n    def egg_fragment(self) -> Optional[str]:\n        match = self._egg_fragment_re.search(self._url)\n        if not match:\n            return None\n        return match.group(1)\n\n    _subdirectory_fragment_re = re.compile(r\"[#&]subdirectory=([^&]*)\")\n\n    @property\n    def subdirectory_fragment(self) -> Optional[str]:\n        match = self._subdirectory_fragment_re.search(self._url)\n        if not match:\n            return None\n        return match.group(1)\n\n    def metadata_link(self) -> Optional[\"Link\"]:\n        \"\"\"Implementation of PEP 658 parsing.\"\"\"\n        # Note that Link.from_element() parsing the \"data-dist-info-metadata\" attribute\n        # from an HTML anchor tag is typically how the Link.dist_info_metadata attribute\n        # gets set.\n        if self.dist_info_metadata is None:\n            return None\n        metadata_url = f\"{self.url_without_fragment}.metadata\"\n        link_hash: Optional[LinkHash] = None\n        # If data-dist-info-metadata=\"true\" is set, then the metadata file exists,\n        # but there is no information about its checksum or anything else.\n        if self.dist_info_metadata != \"true\":\n            link_hash = LinkHash.split_hash_name_and_value(self.dist_info_metadata)\n        return Link(metadata_url, link_hash=link_hash)\n\n    def as_hashes(self) -> Optional[Hashes]:\n        if self.link_hash is not None:\n            return self.link_hash.as_hashes()\n        return None\n\n    @property\n    def hash(self) -> Optional[str]:\n        if self.link_hash is not None:\n            return self.link_hash.value\n        return None\n\n    @property\n    def hash_name(self) -> Optional[str]:\n        if self.link_hash is not None:\n            return self.link_hash.name\n        return None\n\n    @property\n    def show_url(self) -> str:\n        return posixpath.basename(self._url.split(\"#\", 1)[0].split(\"?\", 1)[0])\n\n    @property\n    def is_file(self) -> bool:\n        return self.scheme == \"file\"\n\n    def is_existing_dir(self) -> bool:\n        return self.is_file and os.path.isdir(self.file_path)\n\n    @property\n    def is_wheel(self) -> bool:\n        return self.ext == WHEEL_EXTENSION\n\n    @property\n    def is_vcs(self) -> bool:\n        from pip._internal.vcs import vcs\n\n        return self.scheme in vcs.all_schemes\n\n    @property\n    def is_yanked(self) -> bool:\n        return self.yanked_reason is not None\n\n    @property\n    def has_hash(self) -> bool:\n        return self.link_hash is not None\n\n    def is_hash_allowed(self, hashes: Optional[Hashes]) -> bool:\n        \"\"\"\n        Return True if the link has a hash and it is allowed by `hashes`.\n        \"\"\"\n        if self.link_hash is None:\n            return False\n        return self.link_hash.is_hash_allowed(hashes)\n\n\nclass _CleanResult(NamedTuple):\n    \"\"\"Convert link for equivalency check.\n\n    This is used in the resolver to check whether two URL-specified requirements\n    likely point to the same distribution and can be considered equivalent. This\n    equivalency logic avoids comparing URLs literally, which can be too strict\n    (e.g. \"a=1&b=2\" vs \"b=2&a=1\") and produce conflicts unexpecting to users.\n\n    Currently this does three things:\n\n    1. Drop the basic auth part. This is technically wrong since a server can\n       serve different content based on auth, but if it does that, it is even\n       impossible to guarantee two URLs without auth are equivalent, since\n       the user can input different auth information when prompted. So the\n       practical solution is to assume the auth doesn't affect the response.\n    2. Parse the query to avoid the ordering issue. Note that ordering under the\n       same key in the query are NOT cleaned; i.e. \"a=1&a=2\" and \"a=2&a=1\" are\n       still considered different.\n    3. Explicitly drop most of the fragment part, except ``subdirectory=`` and\n       hash values, since it should have no impact the downloaded content. Note\n       that this drops the \"egg=\" part historically used to denote the requested\n       project (and extras), which is wrong in the strictest sense, but too many\n       people are supplying it inconsistently to cause superfluous resolution\n       conflicts, so we choose to also ignore them.\n    \"\"\"\n\n    parsed: urllib.parse.SplitResult\n    query: Dict[str, List[str]]\n    subdirectory: str\n    hashes: Dict[str, str]\n\n\ndef _clean_link(link: Link) -> _CleanResult:\n    parsed = link._parsed_url\n    netloc = parsed.netloc.rsplit(\"@\", 1)[-1]\n    # According to RFC 8089, an empty host in file: means localhost.\n    if parsed.scheme == \"file\" and not netloc:\n        netloc = \"localhost\"\n    fragment = urllib.parse.parse_qs(parsed.fragment)\n    if \"egg\" in fragment:\n        logger.debug(\"Ignoring egg= fragment in %s\", link)\n    try:\n        # If there are multiple subdirectory values, use the first one.\n        # This matches the behavior of Link.subdirectory_fragment.\n        subdirectory = fragment[\"subdirectory\"][0]\n    except (IndexError, KeyError):\n        subdirectory = \"\"\n    # If there are multiple hash values under the same algorithm, use the\n    # first one. This matches the behavior of Link.hash_value.\n    hashes = {k: fragment[k][0] for k in _SUPPORTED_HASHES if k in fragment}\n    return _CleanResult(\n        parsed=parsed._replace(netloc=netloc, query=\"\", fragment=\"\"),\n        query=urllib.parse.parse_qs(parsed.query),\n        subdirectory=subdirectory,\n        hashes=hashes,\n    )\n\n\n@functools.lru_cache(maxsize=None)\ndef links_equivalent(link1: Link, link2: Link) -> bool:\n    return _clean_link(link1) == _clean_link(link2)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/models/scheme.py",
    "content": "\"\"\"\nFor types associated with installation schemes.\n\nFor a general overview of available schemes and their context, see\nhttps://docs.python.org/3/install/index.html#alternate-installation.\n\"\"\"\n\n\nSCHEME_KEYS = [\"platlib\", \"purelib\", \"headers\", \"scripts\", \"data\"]\n\n\nclass Scheme:\n    \"\"\"A Scheme holds paths which are used as the base directories for\n    artifacts associated with a Python package.\n    \"\"\"\n\n    __slots__ = SCHEME_KEYS\n\n    def __init__(\n        self,\n        platlib: str,\n        purelib: str,\n        headers: str,\n        scripts: str,\n        data: str,\n    ) -> None:\n        self.platlib = platlib\n        self.purelib = purelib\n        self.headers = headers\n        self.scripts = scripts\n        self.data = data\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/models/search_scope.py",
    "content": "import itertools\nimport logging\nimport os\nimport posixpath\nimport urllib.parse\nfrom typing import List\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.models.index import PyPI\nfrom pip._internal.utils.compat import has_tls\nfrom pip._internal.utils.misc import normalize_path, redact_auth_from_url\n\nlogger = logging.getLogger(__name__)\n\n\nclass SearchScope:\n\n    \"\"\"\n    Encapsulates the locations that pip is configured to search.\n    \"\"\"\n\n    __slots__ = [\"find_links\", \"index_urls\", \"no_index\"]\n\n    @classmethod\n    def create(\n        cls,\n        find_links: List[str],\n        index_urls: List[str],\n        no_index: bool,\n    ) -> \"SearchScope\":\n        \"\"\"\n        Create a SearchScope object after normalizing the `find_links`.\n        \"\"\"\n        # Build find_links. If an argument starts with ~, it may be\n        # a local file relative to a home directory. So try normalizing\n        # it and if it exists, use the normalized version.\n        # This is deliberately conservative - it might be fine just to\n        # blindly normalize anything starting with a ~...\n        built_find_links: List[str] = []\n        for link in find_links:\n            if link.startswith(\"~\"):\n                new_link = normalize_path(link)\n                if os.path.exists(new_link):\n                    link = new_link\n            built_find_links.append(link)\n\n        # If we don't have TLS enabled, then WARN if anyplace we're looking\n        # relies on TLS.\n        if not has_tls():\n            for link in itertools.chain(index_urls, built_find_links):\n                parsed = urllib.parse.urlparse(link)\n                if parsed.scheme == \"https\":\n                    logger.warning(\n                        \"pip is configured with locations that require \"\n                        \"TLS/SSL, however the ssl module in Python is not \"\n                        \"available.\"\n                    )\n                    break\n\n        return cls(\n            find_links=built_find_links,\n            index_urls=index_urls,\n            no_index=no_index,\n        )\n\n    def __init__(\n        self,\n        find_links: List[str],\n        index_urls: List[str],\n        no_index: bool,\n    ) -> None:\n        self.find_links = find_links\n        self.index_urls = index_urls\n        self.no_index = no_index\n\n    def get_formatted_locations(self) -> str:\n        lines = []\n        redacted_index_urls = []\n        if self.index_urls and self.index_urls != [PyPI.simple_url]:\n            for url in self.index_urls:\n\n                redacted_index_url = redact_auth_from_url(url)\n\n                # Parse the URL\n                purl = urllib.parse.urlsplit(redacted_index_url)\n\n                # URL is generally invalid if scheme and netloc is missing\n                # there are issues with Python and URL parsing, so this test\n                # is a bit crude. See bpo-20271, bpo-23505. Python doesn't\n                # always parse invalid URLs correctly - it should raise\n                # exceptions for malformed URLs\n                if not purl.scheme and not purl.netloc:\n                    logger.warning(\n                        'The index url \"%s\" seems invalid, please provide a scheme.',\n                        redacted_index_url,\n                    )\n\n                redacted_index_urls.append(redacted_index_url)\n\n            lines.append(\n                \"Looking in indexes: {}\".format(\", \".join(redacted_index_urls))\n            )\n\n        if self.find_links:\n            lines.append(\n                \"Looking in links: {}\".format(\n                    \", \".join(redact_auth_from_url(url) for url in self.find_links)\n                )\n            )\n        return \"\\n\".join(lines)\n\n    def get_index_urls_locations(self, project_name: str) -> List[str]:\n        \"\"\"Returns the locations found via self.index_urls\n\n        Checks the url_name on the main (first in the list) index and\n        use this url_name to produce all locations\n        \"\"\"\n\n        def mkurl_pypi_url(url: str) -> str:\n            loc = posixpath.join(\n                url, urllib.parse.quote(canonicalize_name(project_name))\n            )\n            # For maximum compatibility with easy_install, ensure the path\n            # ends in a trailing slash.  Although this isn't in the spec\n            # (and PyPI can handle it without the slash) some other index\n            # implementations might break if they relied on easy_install's\n            # behavior.\n            if not loc.endswith(\"/\"):\n                loc = loc + \"/\"\n            return loc\n\n        return [mkurl_pypi_url(url) for url in self.index_urls]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/models/selection_prefs.py",
    "content": "from typing import Optional\n\nfrom pip._internal.models.format_control import FormatControl\n\n\nclass SelectionPreferences:\n    \"\"\"\n    Encapsulates the candidate selection preferences for downloading\n    and installing files.\n    \"\"\"\n\n    __slots__ = [\n        \"allow_yanked\",\n        \"allow_all_prereleases\",\n        \"format_control\",\n        \"prefer_binary\",\n        \"ignore_requires_python\",\n    ]\n\n    # Don't include an allow_yanked default value to make sure each call\n    # site considers whether yanked releases are allowed. This also causes\n    # that decision to be made explicit in the calling code, which helps\n    # people when reading the code.\n    def __init__(\n        self,\n        allow_yanked: bool,\n        allow_all_prereleases: bool = False,\n        format_control: Optional[FormatControl] = None,\n        prefer_binary: bool = False,\n        ignore_requires_python: Optional[bool] = None,\n    ) -> None:\n        \"\"\"Create a SelectionPreferences object.\n\n        :param allow_yanked: Whether files marked as yanked (in the sense\n            of PEP 592) are permitted to be candidates for install.\n        :param format_control: A FormatControl object or None. Used to control\n            the selection of source packages / binary packages when consulting\n            the index and links.\n        :param prefer_binary: Whether to prefer an old, but valid, binary\n            dist over a new source dist.\n        :param ignore_requires_python: Whether to ignore incompatible\n            \"Requires-Python\" values in links. Defaults to False.\n        \"\"\"\n        if ignore_requires_python is None:\n            ignore_requires_python = False\n\n        self.allow_yanked = allow_yanked\n        self.allow_all_prereleases = allow_all_prereleases\n        self.format_control = format_control\n        self.prefer_binary = prefer_binary\n        self.ignore_requires_python = ignore_requires_python\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/models/target_python.py",
    "content": "import sys\nfrom typing import List, Optional, Tuple\n\nfrom pip._vendor.packaging.tags import Tag\n\nfrom pip._internal.utils.compatibility_tags import get_supported, version_info_to_nodot\nfrom pip._internal.utils.misc import normalize_version_info\n\n\nclass TargetPython:\n\n    \"\"\"\n    Encapsulates the properties of a Python interpreter one is targeting\n    for a package install, download, etc.\n    \"\"\"\n\n    __slots__ = [\n        \"_given_py_version_info\",\n        \"abis\",\n        \"implementation\",\n        \"platforms\",\n        \"py_version\",\n        \"py_version_info\",\n        \"_valid_tags\",\n    ]\n\n    def __init__(\n        self,\n        platforms: Optional[List[str]] = None,\n        py_version_info: Optional[Tuple[int, ...]] = None,\n        abis: Optional[List[str]] = None,\n        implementation: Optional[str] = None,\n    ) -> None:\n        \"\"\"\n        :param platforms: A list of strings or None. If None, searches for\n            packages that are supported by the current system. Otherwise, will\n            find packages that can be built on the platforms passed in. These\n            packages will only be downloaded for distribution: they will\n            not be built locally.\n        :param py_version_info: An optional tuple of ints representing the\n            Python version information to use (e.g. `sys.version_info[:3]`).\n            This can have length 1, 2, or 3 when provided.\n        :param abis: A list of strings or None. This is passed to\n            compatibility_tags.py's get_supported() function as is.\n        :param implementation: A string or None. This is passed to\n            compatibility_tags.py's get_supported() function as is.\n        \"\"\"\n        # Store the given py_version_info for when we call get_supported().\n        self._given_py_version_info = py_version_info\n\n        if py_version_info is None:\n            py_version_info = sys.version_info[:3]\n        else:\n            py_version_info = normalize_version_info(py_version_info)\n\n        py_version = \".\".join(map(str, py_version_info[:2]))\n\n        self.abis = abis\n        self.implementation = implementation\n        self.platforms = platforms\n        self.py_version = py_version\n        self.py_version_info = py_version_info\n\n        # This is used to cache the return value of get_tags().\n        self._valid_tags: Optional[List[Tag]] = None\n\n    def format_given(self) -> str:\n        \"\"\"\n        Format the given, non-None attributes for display.\n        \"\"\"\n        display_version = None\n        if self._given_py_version_info is not None:\n            display_version = \".\".join(\n                str(part) for part in self._given_py_version_info\n            )\n\n        key_values = [\n            (\"platforms\", self.platforms),\n            (\"version_info\", display_version),\n            (\"abis\", self.abis),\n            (\"implementation\", self.implementation),\n        ]\n        return \" \".join(\n            f\"{key}={value!r}\" for key, value in key_values if value is not None\n        )\n\n    def get_tags(self) -> List[Tag]:\n        \"\"\"\n        Return the supported PEP 425 tags to check wheel candidates against.\n\n        The tags are returned in order of preference (most preferred first).\n        \"\"\"\n        if self._valid_tags is None:\n            # Pass versions=None if no py_version_info was given since\n            # versions=None uses special default logic.\n            py_version_info = self._given_py_version_info\n            if py_version_info is None:\n                version = None\n            else:\n                version = version_info_to_nodot(py_version_info)\n\n            tags = get_supported(\n                version=version,\n                platforms=self.platforms,\n                abis=self.abis,\n                impl=self.implementation,\n            )\n            self._valid_tags = tags\n\n        return self._valid_tags\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/models/wheel.py",
    "content": "\"\"\"Represents a wheel file and provides access to the various parts of the\nname that have meaning.\n\"\"\"\nimport re\nfrom typing import Dict, Iterable, List\n\nfrom pip._vendor.packaging.tags import Tag\n\nfrom pip._internal.exceptions import InvalidWheelFilename\n\n\nclass Wheel:\n    \"\"\"A wheel file\"\"\"\n\n    wheel_file_re = re.compile(\n        r\"\"\"^(?P<namever>(?P<name>[^\\s-]+?)-(?P<ver>[^\\s-]*?))\n        ((-(?P<build>\\d[^-]*?))?-(?P<pyver>[^\\s-]+?)-(?P<abi>[^\\s-]+?)-(?P<plat>[^\\s-]+?)\n        \\.whl|\\.dist-info)$\"\"\",\n        re.VERBOSE,\n    )\n\n    def __init__(self, filename: str) -> None:\n        \"\"\"\n        :raises InvalidWheelFilename: when the filename is invalid for a wheel\n        \"\"\"\n        wheel_info = self.wheel_file_re.match(filename)\n        if not wheel_info:\n            raise InvalidWheelFilename(f\"{filename} is not a valid wheel filename.\")\n        self.filename = filename\n        self.name = wheel_info.group(\"name\").replace(\"_\", \"-\")\n        # we'll assume \"_\" means \"-\" due to wheel naming scheme\n        # (https://github.com/pypa/pip/issues/1150)\n        self.version = wheel_info.group(\"ver\").replace(\"_\", \"-\")\n        self.build_tag = wheel_info.group(\"build\")\n        self.pyversions = wheel_info.group(\"pyver\").split(\".\")\n        self.abis = wheel_info.group(\"abi\").split(\".\")\n        self.plats = wheel_info.group(\"plat\").split(\".\")\n\n        # All the tag combinations from this file\n        self.file_tags = {\n            Tag(x, y, z) for x in self.pyversions for y in self.abis for z in self.plats\n        }\n\n    def get_formatted_file_tags(self) -> List[str]:\n        \"\"\"Return the wheel's tags as a sorted list of strings.\"\"\"\n        return sorted(str(tag) for tag in self.file_tags)\n\n    def support_index_min(self, tags: List[Tag]) -> int:\n        \"\"\"Return the lowest index that one of the wheel's file_tag combinations\n        achieves in the given list of supported tags.\n\n        For example, if there are 8 supported tags and one of the file tags\n        is first in the list, then return 0.\n\n        :param tags: the PEP 425 tags to check the wheel against, in order\n            with most preferred first.\n\n        :raises ValueError: If none of the wheel's file tags match one of\n            the supported tags.\n        \"\"\"\n        try:\n            return next(i for i, t in enumerate(tags) if t in self.file_tags)\n        except StopIteration:\n            raise ValueError()\n\n    def find_most_preferred_tag(\n        self, tags: List[Tag], tag_to_priority: Dict[Tag, int]\n    ) -> int:\n        \"\"\"Return the priority of the most preferred tag that one of the wheel's file\n        tag combinations achieves in the given list of supported tags using the given\n        tag_to_priority mapping, where lower priorities are more-preferred.\n\n        This is used in place of support_index_min in some cases in order to avoid\n        an expensive linear scan of a large list of tags.\n\n        :param tags: the PEP 425 tags to check the wheel against.\n        :param tag_to_priority: a mapping from tag to priority of that tag, where\n            lower is more preferred.\n\n        :raises ValueError: If none of the wheel's file tags match one of\n            the supported tags.\n        \"\"\"\n        return min(\n            tag_to_priority[tag] for tag in self.file_tags if tag in tag_to_priority\n        )\n\n    def supported(self, tags: Iterable[Tag]) -> bool:\n        \"\"\"Return whether the wheel is compatible with one of the given tags.\n\n        :param tags: the PEP 425 tags to check the wheel against.\n        \"\"\"\n        return not self.file_tags.isdisjoint(tags)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/network/__init__.py",
    "content": "\"\"\"Contains purely network-related utilities.\n\"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/network/auth.py",
    "content": "\"\"\"Network Authentication Helpers\n\nContains interface (MultiDomainBasicAuth) and associated glue code for\nproviding credentials in the context of network requests.\n\"\"\"\n\nimport urllib.parse\nfrom typing import Any, Dict, List, Optional, Tuple\n\nfrom pip._vendor.requests.auth import AuthBase, HTTPBasicAuth\nfrom pip._vendor.requests.models import Request, Response\nfrom pip._vendor.requests.utils import get_netrc_auth\n\nfrom pip._internal.utils.logging import getLogger\nfrom pip._internal.utils.misc import (\n    ask,\n    ask_input,\n    ask_password,\n    remove_auth_from_url,\n    split_auth_netloc_from_url,\n)\nfrom pip._internal.vcs.versioncontrol import AuthInfo\n\nlogger = getLogger(__name__)\n\nCredentials = Tuple[str, str, str]\n\ntry:\n    import keyring\nexcept ImportError:\n    keyring = None  # type: ignore[assignment]\nexcept Exception as exc:\n    logger.warning(\n        \"Keyring is skipped due to an exception: %s\",\n        str(exc),\n    )\n    keyring = None  # type: ignore[assignment]\n\n\ndef get_keyring_auth(url: Optional[str], username: Optional[str]) -> Optional[AuthInfo]:\n    \"\"\"Return the tuple auth for a given url from keyring.\"\"\"\n    global keyring\n    if not url or not keyring:\n        return None\n\n    try:\n        try:\n            get_credential = keyring.get_credential\n        except AttributeError:\n            pass\n        else:\n            logger.debug(\"Getting credentials from keyring for %s\", url)\n            cred = get_credential(url, username)\n            if cred is not None:\n                return cred.username, cred.password\n            return None\n\n        if username:\n            logger.debug(\"Getting password from keyring for %s\", url)\n            password = keyring.get_password(url, username)\n            if password:\n                return username, password\n\n    except Exception as exc:\n        logger.warning(\n            \"Keyring is skipped due to an exception: %s\",\n            str(exc),\n        )\n        keyring = None  # type: ignore[assignment]\n    return None\n\n\nclass MultiDomainBasicAuth(AuthBase):\n    def __init__(\n        self, prompting: bool = True, index_urls: Optional[List[str]] = None\n    ) -> None:\n        self.prompting = prompting\n        self.index_urls = index_urls\n        self.passwords: Dict[str, AuthInfo] = {}\n        # When the user is prompted to enter credentials and keyring is\n        # available, we will offer to save them. If the user accepts,\n        # this value is set to the credentials they entered. After the\n        # request authenticates, the caller should call\n        # ``save_credentials`` to save these.\n        self._credentials_to_save: Optional[Credentials] = None\n\n    def _get_index_url(self, url: str) -> Optional[str]:\n        \"\"\"Return the original index URL matching the requested URL.\n\n        Cached or dynamically generated credentials may work against\n        the original index URL rather than just the netloc.\n\n        The provided url should have had its username and password\n        removed already. If the original index url had credentials then\n        they will be included in the return value.\n\n        Returns None if no matching index was found, or if --no-index\n        was specified by the user.\n        \"\"\"\n        if not url or not self.index_urls:\n            return None\n\n        for u in self.index_urls:\n            prefix = remove_auth_from_url(u).rstrip(\"/\") + \"/\"\n            if url.startswith(prefix):\n                return u\n        return None\n\n    def _get_new_credentials(\n        self,\n        original_url: str,\n        allow_netrc: bool = True,\n        allow_keyring: bool = False,\n    ) -> AuthInfo:\n        \"\"\"Find and return credentials for the specified URL.\"\"\"\n        # Split the credentials and netloc from the url.\n        url, netloc, url_user_password = split_auth_netloc_from_url(\n            original_url,\n        )\n\n        # Start with the credentials embedded in the url\n        username, password = url_user_password\n        if username is not None and password is not None:\n            logger.debug(\"Found credentials in url for %s\", netloc)\n            return url_user_password\n\n        # Find a matching index url for this request\n        index_url = self._get_index_url(url)\n        if index_url:\n            # Split the credentials from the url.\n            index_info = split_auth_netloc_from_url(index_url)\n            if index_info:\n                index_url, _, index_url_user_password = index_info\n                logger.debug(\"Found index url %s\", index_url)\n\n        # If an index URL was found, try its embedded credentials\n        if index_url and index_url_user_password[0] is not None:\n            username, password = index_url_user_password\n            if username is not None and password is not None:\n                logger.debug(\"Found credentials in index url for %s\", netloc)\n                return index_url_user_password\n\n        # Get creds from netrc if we still don't have them\n        if allow_netrc:\n            netrc_auth = get_netrc_auth(original_url)\n            if netrc_auth:\n                logger.debug(\"Found credentials in netrc for %s\", netloc)\n                return netrc_auth\n\n        # If we don't have a password and keyring is available, use it.\n        if allow_keyring:\n            # The index url is more specific than the netloc, so try it first\n            # fmt: off\n            kr_auth = (\n                get_keyring_auth(index_url, username) or\n                get_keyring_auth(netloc, username)\n            )\n            # fmt: on\n            if kr_auth:\n                logger.debug(\"Found credentials in keyring for %s\", netloc)\n                return kr_auth\n\n        return username, password\n\n    def _get_url_and_credentials(\n        self, original_url: str\n    ) -> Tuple[str, Optional[str], Optional[str]]:\n        \"\"\"Return the credentials to use for the provided URL.\n\n        If allowed, netrc and keyring may be used to obtain the\n        correct credentials.\n\n        Returns (url_without_credentials, username, password). Note\n        that even if the original URL contains credentials, this\n        function may return a different username and password.\n        \"\"\"\n        url, netloc, _ = split_auth_netloc_from_url(original_url)\n\n        # Try to get credentials from original url\n        username, password = self._get_new_credentials(original_url)\n\n        # If credentials not found, use any stored credentials for this netloc.\n        # Do this if either the username or the password is missing.\n        # This accounts for the situation in which the user has specified\n        # the username in the index url, but the password comes from keyring.\n        if (username is None or password is None) and netloc in self.passwords:\n            un, pw = self.passwords[netloc]\n            # It is possible that the cached credentials are for a different username,\n            # in which case the cache should be ignored.\n            if username is None or username == un:\n                username, password = un, pw\n\n        if username is not None or password is not None:\n            # Convert the username and password if they're None, so that\n            # this netloc will show up as \"cached\" in the conditional above.\n            # Further, HTTPBasicAuth doesn't accept None, so it makes sense to\n            # cache the value that is going to be used.\n            username = username or \"\"\n            password = password or \"\"\n\n            # Store any acquired credentials.\n            self.passwords[netloc] = (username, password)\n\n        assert (\n            # Credentials were found\n            (username is not None and password is not None)\n            # Credentials were not found\n            or (username is None and password is None)\n        ), f\"Could not load credentials from url: {original_url}\"\n\n        return url, username, password\n\n    def __call__(self, req: Request) -> Request:\n        # Get credentials for this request\n        url, username, password = self._get_url_and_credentials(req.url)\n\n        # Set the url of the request to the url without any credentials\n        req.url = url\n\n        if username is not None and password is not None:\n            # Send the basic auth with this request\n            req = HTTPBasicAuth(username, password)(req)\n\n        # Attach a hook to handle 401 responses\n        req.register_hook(\"response\", self.handle_401)\n\n        return req\n\n    # Factored out to allow for easy patching in tests\n    def _prompt_for_password(\n        self, netloc: str\n    ) -> Tuple[Optional[str], Optional[str], bool]:\n        username = ask_input(f\"User for {netloc}: \")\n        if not username:\n            return None, None, False\n        auth = get_keyring_auth(netloc, username)\n        if auth and auth[0] is not None and auth[1] is not None:\n            return auth[0], auth[1], False\n        password = ask_password(\"Password: \")\n        return username, password, True\n\n    # Factored out to allow for easy patching in tests\n    def _should_save_password_to_keyring(self) -> bool:\n        if not keyring:\n            return False\n        return ask(\"Save credentials to keyring [y/N]: \", [\"y\", \"n\"]) == \"y\"\n\n    def handle_401(self, resp: Response, **kwargs: Any) -> Response:\n        # We only care about 401 responses, anything else we want to just\n        #   pass through the actual response\n        if resp.status_code != 401:\n            return resp\n\n        # We are not able to prompt the user so simply return the response\n        if not self.prompting:\n            return resp\n\n        parsed = urllib.parse.urlparse(resp.url)\n\n        # Query the keyring for credentials:\n        username, password = self._get_new_credentials(\n            resp.url,\n            allow_netrc=False,\n            allow_keyring=True,\n        )\n\n        # Prompt the user for a new username and password\n        save = False\n        if not username and not password:\n            username, password, save = self._prompt_for_password(parsed.netloc)\n\n        # Store the new username and password to use for future requests\n        self._credentials_to_save = None\n        if username is not None and password is not None:\n            self.passwords[parsed.netloc] = (username, password)\n\n            # Prompt to save the password to keyring\n            if save and self._should_save_password_to_keyring():\n                self._credentials_to_save = (parsed.netloc, username, password)\n\n        # Consume content and release the original connection to allow our new\n        #   request to reuse the same one.\n        resp.content\n        resp.raw.release_conn()\n\n        # Add our new username and password to the request\n        req = HTTPBasicAuth(username or \"\", password or \"\")(resp.request)\n        req.register_hook(\"response\", self.warn_on_401)\n\n        # On successful request, save the credentials that were used to\n        # keyring. (Note that if the user responded \"no\" above, this member\n        # is not set and nothing will be saved.)\n        if self._credentials_to_save:\n            req.register_hook(\"response\", self.save_credentials)\n\n        # Send our new request\n        new_resp = resp.connection.send(req, **kwargs)\n        new_resp.history.append(resp)\n\n        return new_resp\n\n    def warn_on_401(self, resp: Response, **kwargs: Any) -> None:\n        \"\"\"Response callback to warn about incorrect credentials.\"\"\"\n        if resp.status_code == 401:\n            logger.warning(\n                \"401 Error, Credentials not correct for %s\",\n                resp.request.url,\n            )\n\n    def save_credentials(self, resp: Response, **kwargs: Any) -> None:\n        \"\"\"Response callback to save credentials on success.\"\"\"\n        assert keyring is not None, \"should never reach here without keyring\"\n        if not keyring:\n            return\n\n        creds = self._credentials_to_save\n        self._credentials_to_save = None\n        if creds and resp.status_code < 400:\n            try:\n                logger.info(\"Saving credentials to keyring\")\n                keyring.set_password(*creds)\n            except Exception:\n                logger.exception(\"Failed to save credentials\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/network/cache.py",
    "content": "\"\"\"HTTP cache implementation.\n\"\"\"\n\nimport os\nfrom contextlib import contextmanager\nfrom typing import Generator, Optional\n\nfrom pip._vendor.cachecontrol.cache import BaseCache\nfrom pip._vendor.cachecontrol.caches import FileCache\nfrom pip._vendor.requests.models import Response\n\nfrom pip._internal.utils.filesystem import adjacent_tmp_file, replace\nfrom pip._internal.utils.misc import ensure_dir\n\n\ndef is_from_cache(response: Response) -> bool:\n    return getattr(response, \"from_cache\", False)\n\n\n@contextmanager\ndef suppressed_cache_errors() -> Generator[None, None, None]:\n    \"\"\"If we can't access the cache then we can just skip caching and process\n    requests as if caching wasn't enabled.\n    \"\"\"\n    try:\n        yield\n    except OSError:\n        pass\n\n\nclass SafeFileCache(BaseCache):\n    \"\"\"\n    A file based cache which is safe to use even when the target directory may\n    not be accessible or writable.\n    \"\"\"\n\n    def __init__(self, directory: str) -> None:\n        assert directory is not None, \"Cache directory must not be None.\"\n        super().__init__()\n        self.directory = directory\n\n    def _get_cache_path(self, name: str) -> str:\n        # From cachecontrol.caches.file_cache.FileCache._fn, brought into our\n        # class for backwards-compatibility and to avoid using a non-public\n        # method.\n        hashed = FileCache.encode(name)\n        parts = list(hashed[:5]) + [hashed]\n        return os.path.join(self.directory, *parts)\n\n    def get(self, key: str) -> Optional[bytes]:\n        path = self._get_cache_path(key)\n        with suppressed_cache_errors():\n            with open(path, \"rb\") as f:\n                return f.read()\n\n    def set(self, key: str, value: bytes, expires: Optional[int] = None) -> None:\n        path = self._get_cache_path(key)\n        with suppressed_cache_errors():\n            ensure_dir(os.path.dirname(path))\n\n            with adjacent_tmp_file(path) as f:\n                f.write(value)\n\n            replace(f.name, path)\n\n    def delete(self, key: str) -> None:\n        path = self._get_cache_path(key)\n        with suppressed_cache_errors():\n            os.remove(path)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/network/download.py",
    "content": "\"\"\"Download files with progress indicators.\n\"\"\"\nimport email.message\nimport logging\nimport mimetypes\nimport os\nfrom typing import Iterable, Optional, Tuple\n\nfrom pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response\n\nfrom pip._internal.cli.progress_bars import get_download_progress_renderer\nfrom pip._internal.exceptions import NetworkConnectionError\nfrom pip._internal.models.index import PyPI\nfrom pip._internal.models.link import Link\nfrom pip._internal.network.cache import is_from_cache\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.network.utils import HEADERS, raise_for_status, response_chunks\nfrom pip._internal.utils.misc import format_size, redact_auth_from_url, splitext\n\nlogger = logging.getLogger(__name__)\n\n\ndef _get_http_response_size(resp: Response) -> Optional[int]:\n    try:\n        return int(resp.headers[\"content-length\"])\n    except (ValueError, KeyError, TypeError):\n        return None\n\n\ndef _prepare_download(\n    resp: Response,\n    link: Link,\n    progress_bar: str,\n) -> Iterable[bytes]:\n    total_length = _get_http_response_size(resp)\n\n    if link.netloc == PyPI.file_storage_domain:\n        url = link.show_url\n    else:\n        url = link.url_without_fragment\n\n    logged_url = redact_auth_from_url(url)\n\n    if total_length:\n        logged_url = \"{} ({})\".format(logged_url, format_size(total_length))\n\n    if is_from_cache(resp):\n        logger.info(\"Using cached %s\", logged_url)\n    else:\n        logger.info(\"Downloading %s\", logged_url)\n\n    if logger.getEffectiveLevel() > logging.INFO:\n        show_progress = False\n    elif is_from_cache(resp):\n        show_progress = False\n    elif not total_length:\n        show_progress = True\n    elif total_length > (40 * 1000):\n        show_progress = True\n    else:\n        show_progress = False\n\n    chunks = response_chunks(resp, CONTENT_CHUNK_SIZE)\n\n    if not show_progress:\n        return chunks\n\n    renderer = get_download_progress_renderer(bar_type=progress_bar, size=total_length)\n    return renderer(chunks)\n\n\ndef sanitize_content_filename(filename: str) -> str:\n    \"\"\"\n    Sanitize the \"filename\" value from a Content-Disposition header.\n    \"\"\"\n    return os.path.basename(filename)\n\n\ndef parse_content_disposition(content_disposition: str, default_filename: str) -> str:\n    \"\"\"\n    Parse the \"filename\" value from a Content-Disposition header, and\n    return the default filename if the result is empty.\n    \"\"\"\n    m = email.message.Message()\n    m[\"content-type\"] = content_disposition\n    filename = m.get_param(\"filename\")\n    if filename:\n        # We need to sanitize the filename to prevent directory traversal\n        # in case the filename contains \"..\" path parts.\n        filename = sanitize_content_filename(str(filename))\n    return filename or default_filename\n\n\ndef _get_http_response_filename(resp: Response, link: Link) -> str:\n    \"\"\"Get an ideal filename from the given HTTP response, falling back to\n    the link filename if not provided.\n    \"\"\"\n    filename = link.filename  # fallback\n    # Have a look at the Content-Disposition header for a better guess\n    content_disposition = resp.headers.get(\"content-disposition\")\n    if content_disposition:\n        filename = parse_content_disposition(content_disposition, filename)\n    ext: Optional[str] = splitext(filename)[1]\n    if not ext:\n        ext = mimetypes.guess_extension(resp.headers.get(\"content-type\", \"\"))\n        if ext:\n            filename += ext\n    if not ext and link.url != resp.url:\n        ext = os.path.splitext(resp.url)[1]\n        if ext:\n            filename += ext\n    return filename\n\n\ndef _http_get_download(session: PipSession, link: Link) -> Response:\n    target_url = link.url.split(\"#\", 1)[0]\n    resp = session.get(target_url, headers=HEADERS, stream=True)\n    raise_for_status(resp)\n    return resp\n\n\nclass Downloader:\n    def __init__(\n        self,\n        session: PipSession,\n        progress_bar: str,\n    ) -> None:\n        self._session = session\n        self._progress_bar = progress_bar\n\n    def __call__(self, link: Link, location: str) -> Tuple[str, str]:\n        \"\"\"Download the file given by link into location.\"\"\"\n        try:\n            resp = _http_get_download(self._session, link)\n        except NetworkConnectionError as e:\n            assert e.response is not None\n            logger.critical(\n                \"HTTP error %s while getting %s\", e.response.status_code, link\n            )\n            raise\n\n        filename = _get_http_response_filename(resp, link)\n        filepath = os.path.join(location, filename)\n\n        chunks = _prepare_download(resp, link, self._progress_bar)\n        with open(filepath, \"wb\") as content_file:\n            for chunk in chunks:\n                content_file.write(chunk)\n        content_type = resp.headers.get(\"Content-Type\", \"\")\n        return filepath, content_type\n\n\nclass BatchDownloader:\n    def __init__(\n        self,\n        session: PipSession,\n        progress_bar: str,\n    ) -> None:\n        self._session = session\n        self._progress_bar = progress_bar\n\n    def __call__(\n        self, links: Iterable[Link], location: str\n    ) -> Iterable[Tuple[Link, Tuple[str, str]]]:\n        \"\"\"Download the files given by links into location.\"\"\"\n        for link in links:\n            try:\n                resp = _http_get_download(self._session, link)\n            except NetworkConnectionError as e:\n                assert e.response is not None\n                logger.critical(\n                    \"HTTP error %s while getting %s\",\n                    e.response.status_code,\n                    link,\n                )\n                raise\n\n            filename = _get_http_response_filename(resp, link)\n            filepath = os.path.join(location, filename)\n\n            chunks = _prepare_download(resp, link, self._progress_bar)\n            with open(filepath, \"wb\") as content_file:\n                for chunk in chunks:\n                    content_file.write(chunk)\n            content_type = resp.headers.get(\"Content-Type\", \"\")\n            yield link, (filepath, content_type)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/network/lazy_wheel.py",
    "content": "\"\"\"Lazy ZIP over HTTP\"\"\"\n\n__all__ = [\"HTTPRangeRequestUnsupported\", \"dist_from_wheel_url\"]\n\nfrom bisect import bisect_left, bisect_right\nfrom contextlib import contextmanager\nfrom tempfile import NamedTemporaryFile\nfrom typing import Any, Dict, Generator, List, Optional, Tuple\nfrom zipfile import BadZipfile, ZipFile\n\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response\n\nfrom pip._internal.metadata import BaseDistribution, MemoryWheel, get_wheel_distribution\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.network.utils import HEADERS, raise_for_status, response_chunks\n\n\nclass HTTPRangeRequestUnsupported(Exception):\n    pass\n\n\ndef dist_from_wheel_url(name: str, url: str, session: PipSession) -> BaseDistribution:\n    \"\"\"Return a distribution object from the given wheel URL.\n\n    This uses HTTP range requests to only fetch the portion of the wheel\n    containing metadata, just enough for the object to be constructed.\n    If such requests are not supported, HTTPRangeRequestUnsupported\n    is raised.\n    \"\"\"\n    with LazyZipOverHTTP(url, session) as zf:\n        # For read-only ZIP files, ZipFile only needs methods read,\n        # seek, seekable and tell, not the whole IO protocol.\n        wheel = MemoryWheel(zf.name, zf)  # type: ignore\n        # After context manager exit, wheel.name\n        # is an invalid file by intention.\n        return get_wheel_distribution(wheel, canonicalize_name(name))\n\n\nclass LazyZipOverHTTP:\n    \"\"\"File-like object mapped to a ZIP file over HTTP.\n\n    This uses HTTP range requests to lazily fetch the file's content,\n    which is supposed to be fed to ZipFile.  If such requests are not\n    supported by the server, raise HTTPRangeRequestUnsupported\n    during initialization.\n    \"\"\"\n\n    def __init__(\n        self, url: str, session: PipSession, chunk_size: int = CONTENT_CHUNK_SIZE\n    ) -> None:\n        head = session.head(url, headers=HEADERS)\n        raise_for_status(head)\n        assert head.status_code == 200\n        self._session, self._url, self._chunk_size = session, url, chunk_size\n        self._length = int(head.headers[\"Content-Length\"])\n        self._file = NamedTemporaryFile()\n        self.truncate(self._length)\n        self._left: List[int] = []\n        self._right: List[int] = []\n        if \"bytes\" not in head.headers.get(\"Accept-Ranges\", \"none\"):\n            raise HTTPRangeRequestUnsupported(\"range request is not supported\")\n        self._check_zip()\n\n    @property\n    def mode(self) -> str:\n        \"\"\"Opening mode, which is always rb.\"\"\"\n        return \"rb\"\n\n    @property\n    def name(self) -> str:\n        \"\"\"Path to the underlying file.\"\"\"\n        return self._file.name\n\n    def seekable(self) -> bool:\n        \"\"\"Return whether random access is supported, which is True.\"\"\"\n        return True\n\n    def close(self) -> None:\n        \"\"\"Close the file.\"\"\"\n        self._file.close()\n\n    @property\n    def closed(self) -> bool:\n        \"\"\"Whether the file is closed.\"\"\"\n        return self._file.closed\n\n    def read(self, size: int = -1) -> bytes:\n        \"\"\"Read up to size bytes from the object and return them.\n\n        As a convenience, if size is unspecified or -1,\n        all bytes until EOF are returned.  Fewer than\n        size bytes may be returned if EOF is reached.\n        \"\"\"\n        download_size = max(size, self._chunk_size)\n        start, length = self.tell(), self._length\n        stop = length if size < 0 else min(start + download_size, length)\n        start = max(0, stop - download_size)\n        self._download(start, stop - 1)\n        return self._file.read(size)\n\n    def readable(self) -> bool:\n        \"\"\"Return whether the file is readable, which is True.\"\"\"\n        return True\n\n    def seek(self, offset: int, whence: int = 0) -> int:\n        \"\"\"Change stream position and return the new absolute position.\n\n        Seek to offset relative position indicated by whence:\n        * 0: Start of stream (the default).  pos should be >= 0;\n        * 1: Current position - pos may be negative;\n        * 2: End of stream - pos usually negative.\n        \"\"\"\n        return self._file.seek(offset, whence)\n\n    def tell(self) -> int:\n        \"\"\"Return the current position.\"\"\"\n        return self._file.tell()\n\n    def truncate(self, size: Optional[int] = None) -> int:\n        \"\"\"Resize the stream to the given size in bytes.\n\n        If size is unspecified resize to the current position.\n        The current stream position isn't changed.\n\n        Return the new file size.\n        \"\"\"\n        return self._file.truncate(size)\n\n    def writable(self) -> bool:\n        \"\"\"Return False.\"\"\"\n        return False\n\n    def __enter__(self) -> \"LazyZipOverHTTP\":\n        self._file.__enter__()\n        return self\n\n    def __exit__(self, *exc: Any) -> None:\n        self._file.__exit__(*exc)\n\n    @contextmanager\n    def _stay(self) -> Generator[None, None, None]:\n        \"\"\"Return a context manager keeping the position.\n\n        At the end of the block, seek back to original position.\n        \"\"\"\n        pos = self.tell()\n        try:\n            yield\n        finally:\n            self.seek(pos)\n\n    def _check_zip(self) -> None:\n        \"\"\"Check and download until the file is a valid ZIP.\"\"\"\n        end = self._length - 1\n        for start in reversed(range(0, end, self._chunk_size)):\n            self._download(start, end)\n            with self._stay():\n                try:\n                    # For read-only ZIP files, ZipFile only needs\n                    # methods read, seek, seekable and tell.\n                    ZipFile(self)  # type: ignore\n                except BadZipfile:\n                    pass\n                else:\n                    break\n\n    def _stream_response(\n        self, start: int, end: int, base_headers: Dict[str, str] = HEADERS\n    ) -> Response:\n        \"\"\"Return HTTP response to a range request from start to end.\"\"\"\n        headers = base_headers.copy()\n        headers[\"Range\"] = f\"bytes={start}-{end}\"\n        # TODO: Get range requests to be correctly cached\n        headers[\"Cache-Control\"] = \"no-cache\"\n        return self._session.get(self._url, headers=headers, stream=True)\n\n    def _merge(\n        self, start: int, end: int, left: int, right: int\n    ) -> Generator[Tuple[int, int], None, None]:\n        \"\"\"Return a generator of intervals to be fetched.\n\n        Args:\n            start (int): Start of needed interval\n            end (int): End of needed interval\n            left (int): Index of first overlapping downloaded data\n            right (int): Index after last overlapping downloaded data\n        \"\"\"\n        lslice, rslice = self._left[left:right], self._right[left:right]\n        i = start = min([start] + lslice[:1])\n        end = max([end] + rslice[-1:])\n        for j, k in zip(lslice, rslice):\n            if j > i:\n                yield i, j - 1\n            i = k + 1\n        if i <= end:\n            yield i, end\n        self._left[left:right], self._right[left:right] = [start], [end]\n\n    def _download(self, start: int, end: int) -> None:\n        \"\"\"Download bytes from start to end inclusively.\"\"\"\n        with self._stay():\n            left = bisect_left(self._right, start)\n            right = bisect_right(self._left, end)\n            for start, end in self._merge(start, end, left, right):\n                response = self._stream_response(start, end)\n                response.raise_for_status()\n                self.seek(start)\n                for chunk in response_chunks(response, self._chunk_size):\n                    self._file.write(chunk)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/network/session.py",
    "content": "\"\"\"PipSession and supporting code, containing all pip-specific\nnetwork request configuration and behavior.\n\"\"\"\n\nimport email.utils\nimport io\nimport ipaddress\nimport json\nimport logging\nimport mimetypes\nimport os\nimport platform\nimport shutil\nimport subprocess\nimport sys\nimport urllib.parse\nimport warnings\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Dict,\n    Generator,\n    List,\n    Mapping,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n)\n\nfrom pip._vendor import requests, urllib3\nfrom pip._vendor.cachecontrol import CacheControlAdapter as _BaseCacheControlAdapter\nfrom pip._vendor.requests.adapters import DEFAULT_POOLBLOCK, BaseAdapter\nfrom pip._vendor.requests.adapters import HTTPAdapter as _BaseHTTPAdapter\nfrom pip._vendor.requests.models import PreparedRequest, Response\nfrom pip._vendor.requests.structures import CaseInsensitiveDict\nfrom pip._vendor.urllib3.connectionpool import ConnectionPool\nfrom pip._vendor.urllib3.exceptions import InsecureRequestWarning\n\nfrom pip import __version__\nfrom pip._internal.metadata import get_default_environment\nfrom pip._internal.models.link import Link\nfrom pip._internal.network.auth import MultiDomainBasicAuth\nfrom pip._internal.network.cache import SafeFileCache\n\n# Import ssl from compat so the initial import occurs in only one place.\nfrom pip._internal.utils.compat import has_tls\nfrom pip._internal.utils.glibc import libc_ver\nfrom pip._internal.utils.misc import build_url_from_netloc, parse_netloc\nfrom pip._internal.utils.urls import url_to_path\n\nif TYPE_CHECKING:\n    from ssl import SSLContext\n\n    from pip._vendor.urllib3.poolmanager import PoolManager\n\n\nlogger = logging.getLogger(__name__)\n\nSecureOrigin = Tuple[str, str, Optional[Union[int, str]]]\n\n\n# Ignore warning raised when using --trusted-host.\nwarnings.filterwarnings(\"ignore\", category=InsecureRequestWarning)\n\n\nSECURE_ORIGINS: List[SecureOrigin] = [\n    # protocol, hostname, port\n    # Taken from Chrome's list of secure origins (See: http://bit.ly/1qrySKC)\n    (\"https\", \"*\", \"*\"),\n    (\"*\", \"localhost\", \"*\"),\n    (\"*\", \"127.0.0.0/8\", \"*\"),\n    (\"*\", \"::1/128\", \"*\"),\n    (\"file\", \"*\", None),\n    # ssh is always secure.\n    (\"ssh\", \"*\", \"*\"),\n]\n\n\n# These are environment variables present when running under various\n# CI systems.  For each variable, some CI systems that use the variable\n# are indicated.  The collection was chosen so that for each of a number\n# of popular systems, at least one of the environment variables is used.\n# This list is used to provide some indication of and lower bound for\n# CI traffic to PyPI.  Thus, it is okay if the list is not comprehensive.\n# For more background, see: https://github.com/pypa/pip/issues/5499\nCI_ENVIRONMENT_VARIABLES = (\n    # Azure Pipelines\n    \"BUILD_BUILDID\",\n    # Jenkins\n    \"BUILD_ID\",\n    # AppVeyor, CircleCI, Codeship, Gitlab CI, Shippable, Travis CI\n    \"CI\",\n    # Explicit environment variable.\n    \"PIP_IS_CI\",\n)\n\n\ndef looks_like_ci() -> bool:\n    \"\"\"\n    Return whether it looks like pip is running under CI.\n    \"\"\"\n    # We don't use the method of checking for a tty (e.g. using isatty())\n    # because some CI systems mimic a tty (e.g. Travis CI).  Thus that\n    # method doesn't provide definitive information in either direction.\n    return any(name in os.environ for name in CI_ENVIRONMENT_VARIABLES)\n\n\ndef user_agent() -> str:\n    \"\"\"\n    Return a string representing the user agent.\n    \"\"\"\n    data: Dict[str, Any] = {\n        \"installer\": {\"name\": \"pip\", \"version\": __version__},\n        \"python\": platform.python_version(),\n        \"implementation\": {\n            \"name\": platform.python_implementation(),\n        },\n    }\n\n    if data[\"implementation\"][\"name\"] == \"CPython\":\n        data[\"implementation\"][\"version\"] = platform.python_version()\n    elif data[\"implementation\"][\"name\"] == \"PyPy\":\n        pypy_version_info = sys.pypy_version_info  # type: ignore\n        if pypy_version_info.releaselevel == \"final\":\n            pypy_version_info = pypy_version_info[:3]\n        data[\"implementation\"][\"version\"] = \".\".join(\n            [str(x) for x in pypy_version_info]\n        )\n    elif data[\"implementation\"][\"name\"] == \"Jython\":\n        # Complete Guess\n        data[\"implementation\"][\"version\"] = platform.python_version()\n    elif data[\"implementation\"][\"name\"] == \"IronPython\":\n        # Complete Guess\n        data[\"implementation\"][\"version\"] = platform.python_version()\n\n    if sys.platform.startswith(\"linux\"):\n        from pip._vendor import distro\n\n        linux_distribution = distro.name(), distro.version(), distro.codename()\n        distro_infos: Dict[str, Any] = dict(\n            filter(\n                lambda x: x[1],\n                zip([\"name\", \"version\", \"id\"], linux_distribution),\n            )\n        )\n        libc = dict(\n            filter(\n                lambda x: x[1],\n                zip([\"lib\", \"version\"], libc_ver()),\n            )\n        )\n        if libc:\n            distro_infos[\"libc\"] = libc\n        if distro_infos:\n            data[\"distro\"] = distro_infos\n\n    if sys.platform.startswith(\"darwin\") and platform.mac_ver()[0]:\n        data[\"distro\"] = {\"name\": \"macOS\", \"version\": platform.mac_ver()[0]}\n\n    if platform.system():\n        data.setdefault(\"system\", {})[\"name\"] = platform.system()\n\n    if platform.release():\n        data.setdefault(\"system\", {})[\"release\"] = platform.release()\n\n    if platform.machine():\n        data[\"cpu\"] = platform.machine()\n\n    if has_tls():\n        import _ssl as ssl\n\n        data[\"openssl_version\"] = ssl.OPENSSL_VERSION\n\n    setuptools_dist = get_default_environment().get_distribution(\"setuptools\")\n    if setuptools_dist is not None:\n        data[\"setuptools_version\"] = str(setuptools_dist.version)\n\n    if shutil.which(\"rustc\") is not None:\n        # If for any reason `rustc --version` fails, silently ignore it\n        try:\n            rustc_output = subprocess.check_output(\n                [\"rustc\", \"--version\"], stderr=subprocess.STDOUT, timeout=0.5\n            )\n        except Exception:\n            pass\n        else:\n            if rustc_output.startswith(b\"rustc \"):\n                # The format of `rustc --version` is:\n                # `b'rustc 1.52.1 (9bc8c42bb 2021-05-09)\\n'`\n                # We extract just the middle (1.52.1) part\n                data[\"rustc_version\"] = rustc_output.split(b\" \")[1].decode()\n\n    # Use None rather than False so as not to give the impression that\n    # pip knows it is not being run under CI.  Rather, it is a null or\n    # inconclusive result.  Also, we include some value rather than no\n    # value to make it easier to know that the check has been run.\n    data[\"ci\"] = True if looks_like_ci() else None\n\n    user_data = os.environ.get(\"PIP_USER_AGENT_USER_DATA\")\n    if user_data is not None:\n        data[\"user_data\"] = user_data\n\n    return \"{data[installer][name]}/{data[installer][version]} {json}\".format(\n        data=data,\n        json=json.dumps(data, separators=(\",\", \":\"), sort_keys=True),\n    )\n\n\nclass LocalFSAdapter(BaseAdapter):\n    def send(\n        self,\n        request: PreparedRequest,\n        stream: bool = False,\n        timeout: Optional[Union[float, Tuple[float, float]]] = None,\n        verify: Union[bool, str] = True,\n        cert: Optional[Union[str, Tuple[str, str]]] = None,\n        proxies: Optional[Mapping[str, str]] = None,\n    ) -> Response:\n        pathname = url_to_path(request.url)\n\n        resp = Response()\n        resp.status_code = 200\n        resp.url = request.url\n\n        try:\n            stats = os.stat(pathname)\n        except OSError as exc:\n            # format the exception raised as a io.BytesIO object,\n            # to return a better error message:\n            resp.status_code = 404\n            resp.reason = type(exc).__name__\n            resp.raw = io.BytesIO(f\"{resp.reason}: {exc}\".encode(\"utf8\"))\n        else:\n            modified = email.utils.formatdate(stats.st_mtime, usegmt=True)\n            content_type = mimetypes.guess_type(pathname)[0] or \"text/plain\"\n            resp.headers = CaseInsensitiveDict(\n                {\n                    \"Content-Type\": content_type,\n                    \"Content-Length\": stats.st_size,\n                    \"Last-Modified\": modified,\n                }\n            )\n\n            resp.raw = open(pathname, \"rb\")\n            resp.close = resp.raw.close\n\n        return resp\n\n    def close(self) -> None:\n        pass\n\n\nclass _SSLContextAdapterMixin:\n    \"\"\"Mixin to add the ``ssl_context`` constructor argument to HTTP adapters.\n\n    The additional argument is forwarded directly to the pool manager. This allows us\n    to dynamically decide what SSL store to use at runtime, which is used to implement\n    the optional ``truststore`` backend.\n    \"\"\"\n\n    def __init__(\n        self,\n        *,\n        ssl_context: Optional[\"SSLContext\"] = None,\n        **kwargs: Any,\n    ) -> None:\n        self._ssl_context = ssl_context\n        super().__init__(**kwargs)\n\n    def init_poolmanager(\n        self,\n        connections: int,\n        maxsize: int,\n        block: bool = DEFAULT_POOLBLOCK,\n        **pool_kwargs: Any,\n    ) -> \"PoolManager\":\n        if self._ssl_context is not None:\n            pool_kwargs.setdefault(\"ssl_context\", self._ssl_context)\n        return super().init_poolmanager(  # type: ignore[misc]\n            connections=connections,\n            maxsize=maxsize,\n            block=block,\n            **pool_kwargs,\n        )\n\n\nclass HTTPAdapter(_SSLContextAdapterMixin, _BaseHTTPAdapter):\n    pass\n\n\nclass CacheControlAdapter(_SSLContextAdapterMixin, _BaseCacheControlAdapter):\n    pass\n\n\nclass InsecureHTTPAdapter(HTTPAdapter):\n    def cert_verify(\n        self,\n        conn: ConnectionPool,\n        url: str,\n        verify: Union[bool, str],\n        cert: Optional[Union[str, Tuple[str, str]]],\n    ) -> None:\n        super().cert_verify(conn=conn, url=url, verify=False, cert=cert)\n\n\nclass InsecureCacheControlAdapter(CacheControlAdapter):\n    def cert_verify(\n        self,\n        conn: ConnectionPool,\n        url: str,\n        verify: Union[bool, str],\n        cert: Optional[Union[str, Tuple[str, str]]],\n    ) -> None:\n        super().cert_verify(conn=conn, url=url, verify=False, cert=cert)\n\n\nclass PipSession(requests.Session):\n\n    timeout: Optional[int] = None\n\n    def __init__(\n        self,\n        *args: Any,\n        retries: int = 0,\n        cache: Optional[str] = None,\n        trusted_hosts: Sequence[str] = (),\n        index_urls: Optional[List[str]] = None,\n        ssl_context: Optional[\"SSLContext\"] = None,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"\n        :param trusted_hosts: Domains not to emit warnings for when not using\n            HTTPS.\n        \"\"\"\n        super().__init__(*args, **kwargs)\n\n        # Namespace the attribute with \"pip_\" just in case to prevent\n        # possible conflicts with the base class.\n        self.pip_trusted_origins: List[Tuple[str, Optional[int]]] = []\n\n        # Attach our User Agent to the request\n        self.headers[\"User-Agent\"] = user_agent()\n\n        # Attach our Authentication handler to the session\n        self.auth = MultiDomainBasicAuth(index_urls=index_urls)\n\n        # Create our urllib3.Retry instance which will allow us to customize\n        # how we handle retries.\n        retries = urllib3.Retry(\n            # Set the total number of retries that a particular request can\n            # have.\n            total=retries,\n            # A 503 error from PyPI typically means that the Fastly -> Origin\n            # connection got interrupted in some way. A 503 error in general\n            # is typically considered a transient error so we'll go ahead and\n            # retry it.\n            # A 500 may indicate transient error in Amazon S3\n            # A 520 or 527 - may indicate transient error in CloudFlare\n            status_forcelist=[500, 503, 520, 527],\n            # Add a small amount of back off between failed requests in\n            # order to prevent hammering the service.\n            backoff_factor=0.25,\n        )  # type: ignore\n\n        # Our Insecure HTTPAdapter disables HTTPS validation. It does not\n        # support caching so we'll use it for all http:// URLs.\n        # If caching is disabled, we will also use it for\n        # https:// hosts that we've marked as ignoring\n        # TLS errors for (trusted-hosts).\n        insecure_adapter = InsecureHTTPAdapter(max_retries=retries)\n\n        # We want to _only_ cache responses on securely fetched origins or when\n        # the host is specified as trusted. We do this because\n        # we can't validate the response of an insecurely/untrusted fetched\n        # origin, and we don't want someone to be able to poison the cache and\n        # require manual eviction from the cache to fix it.\n        if cache:\n            secure_adapter = CacheControlAdapter(\n                cache=SafeFileCache(cache),\n                max_retries=retries,\n                ssl_context=ssl_context,\n            )\n            self._trusted_host_adapter = InsecureCacheControlAdapter(\n                cache=SafeFileCache(cache),\n                max_retries=retries,\n            )\n        else:\n            secure_adapter = HTTPAdapter(max_retries=retries, ssl_context=ssl_context)\n            self._trusted_host_adapter = insecure_adapter\n\n        self.mount(\"https://\", secure_adapter)\n        self.mount(\"http://\", insecure_adapter)\n\n        # Enable file:// urls\n        self.mount(\"file://\", LocalFSAdapter())\n\n        for host in trusted_hosts:\n            self.add_trusted_host(host, suppress_logging=True)\n\n    def update_index_urls(self, new_index_urls: List[str]) -> None:\n        \"\"\"\n        :param new_index_urls: New index urls to update the authentication\n            handler with.\n        \"\"\"\n        self.auth.index_urls = new_index_urls\n\n    def add_trusted_host(\n        self, host: str, source: Optional[str] = None, suppress_logging: bool = False\n    ) -> None:\n        \"\"\"\n        :param host: It is okay to provide a host that has previously been\n            added.\n        :param source: An optional source string, for logging where the host\n            string came from.\n        \"\"\"\n        if not suppress_logging:\n            msg = f\"adding trusted host: {host!r}\"\n            if source is not None:\n                msg += f\" (from {source})\"\n            logger.info(msg)\n\n        host_port = parse_netloc(host)\n        if host_port not in self.pip_trusted_origins:\n            self.pip_trusted_origins.append(host_port)\n\n        self.mount(\n            build_url_from_netloc(host, scheme=\"http\") + \"/\", self._trusted_host_adapter\n        )\n        self.mount(build_url_from_netloc(host) + \"/\", self._trusted_host_adapter)\n        if not host_port[1]:\n            self.mount(\n                build_url_from_netloc(host, scheme=\"http\") + \":\",\n                self._trusted_host_adapter,\n            )\n            # Mount wildcard ports for the same host.\n            self.mount(build_url_from_netloc(host) + \":\", self._trusted_host_adapter)\n\n    def iter_secure_origins(self) -> Generator[SecureOrigin, None, None]:\n        yield from SECURE_ORIGINS\n        for host, port in self.pip_trusted_origins:\n            yield (\"*\", host, \"*\" if port is None else port)\n\n    def is_secure_origin(self, location: Link) -> bool:\n        # Determine if this url used a secure transport mechanism\n        parsed = urllib.parse.urlparse(str(location))\n        origin_protocol, origin_host, origin_port = (\n            parsed.scheme,\n            parsed.hostname,\n            parsed.port,\n        )\n\n        # The protocol to use to see if the protocol matches.\n        # Don't count the repository type as part of the protocol: in\n        # cases such as \"git+ssh\", only use \"ssh\". (I.e., Only verify against\n        # the last scheme.)\n        origin_protocol = origin_protocol.rsplit(\"+\", 1)[-1]\n\n        # Determine if our origin is a secure origin by looking through our\n        # hardcoded list of secure origins, as well as any additional ones\n        # configured on this PackageFinder instance.\n        for secure_origin in self.iter_secure_origins():\n            secure_protocol, secure_host, secure_port = secure_origin\n            if origin_protocol != secure_protocol and secure_protocol != \"*\":\n                continue\n\n            try:\n                addr = ipaddress.ip_address(origin_host or \"\")\n                network = ipaddress.ip_network(secure_host)\n            except ValueError:\n                # We don't have both a valid address or a valid network, so\n                # we'll check this origin against hostnames.\n                if (\n                    origin_host\n                    and origin_host.lower() != secure_host.lower()\n                    and secure_host != \"*\"\n                ):\n                    continue\n            else:\n                # We have a valid address and network, so see if the address\n                # is contained within the network.\n                if addr not in network:\n                    continue\n\n            # Check to see if the port matches.\n            if (\n                origin_port != secure_port\n                and secure_port != \"*\"\n                and secure_port is not None\n            ):\n                continue\n\n            # If we've gotten here, then this origin matches the current\n            # secure origin and we should return True\n            return True\n\n        # If we've gotten to this point, then the origin isn't secure and we\n        # will not accept it as a valid location to search. We will however\n        # log a warning that we are ignoring it.\n        logger.warning(\n            \"The repository located at %s is not a trusted or secure host and \"\n            \"is being ignored. If this repository is available via HTTPS we \"\n            \"recommend you use HTTPS instead, otherwise you may silence \"\n            \"this warning and allow it anyway with '--trusted-host %s'.\",\n            origin_host,\n            origin_host,\n        )\n\n        return False\n\n    def request(self, method: str, url: str, *args: Any, **kwargs: Any) -> Response:\n        # Allow setting a default timeout on a session\n        kwargs.setdefault(\"timeout\", self.timeout)\n        # Allow setting a default proxies on a session\n        kwargs.setdefault(\"proxies\", self.proxies)\n\n        # Dispatch the actual request\n        return super().request(method, url, *args, **kwargs)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/network/utils.py",
    "content": "from typing import Dict, Generator\n\nfrom pip._vendor.requests.models import CONTENT_CHUNK_SIZE, Response\n\nfrom pip._internal.exceptions import NetworkConnectionError\n\n# The following comments and HTTP headers were originally added by\n# Donald Stufft in git commit 22c562429a61bb77172039e480873fb239dd8c03.\n#\n# We use Accept-Encoding: identity here because requests defaults to\n# accepting compressed responses. This breaks in a variety of ways\n# depending on how the server is configured.\n# - Some servers will notice that the file isn't a compressible file\n#   and will leave the file alone and with an empty Content-Encoding\n# - Some servers will notice that the file is already compressed and\n#   will leave the file alone, adding a Content-Encoding: gzip header\n# - Some servers won't notice anything at all and will take a file\n#   that's already been compressed and compress it again, and set\n#   the Content-Encoding: gzip header\n# By setting this to request only the identity encoding we're hoping\n# to eliminate the third case.  Hopefully there does not exist a server\n# which when given a file will notice it is already compressed and that\n# you're not asking for a compressed file and will then decompress it\n# before sending because if that's the case I don't think it'll ever be\n# possible to make this work.\nHEADERS: Dict[str, str] = {\"Accept-Encoding\": \"identity\"}\n\n\ndef raise_for_status(resp: Response) -> None:\n    http_error_msg = \"\"\n    if isinstance(resp.reason, bytes):\n        # We attempt to decode utf-8 first because some servers\n        # choose to localize their reason strings. If the string\n        # isn't utf-8, we fall back to iso-8859-1 for all other\n        # encodings.\n        try:\n            reason = resp.reason.decode(\"utf-8\")\n        except UnicodeDecodeError:\n            reason = resp.reason.decode(\"iso-8859-1\")\n    else:\n        reason = resp.reason\n\n    if 400 <= resp.status_code < 500:\n        http_error_msg = (\n            f\"{resp.status_code} Client Error: {reason} for url: {resp.url}\"\n        )\n\n    elif 500 <= resp.status_code < 600:\n        http_error_msg = (\n            f\"{resp.status_code} Server Error: {reason} for url: {resp.url}\"\n        )\n\n    if http_error_msg:\n        raise NetworkConnectionError(http_error_msg, response=resp)\n\n\ndef response_chunks(\n    response: Response, chunk_size: int = CONTENT_CHUNK_SIZE\n) -> Generator[bytes, None, None]:\n    \"\"\"Given a requests Response, provide the data chunks.\"\"\"\n    try:\n        # Special case for urllib3.\n        for chunk in response.raw.stream(\n            chunk_size,\n            # We use decode_content=False here because we don't\n            # want urllib3 to mess with the raw bytes we get\n            # from the server. If we decompress inside of\n            # urllib3 then we cannot verify the checksum\n            # because the checksum will be of the compressed\n            # file. This breakage will only occur if the\n            # server adds a Content-Encoding header, which\n            # depends on how the server was configured:\n            # - Some servers will notice that the file isn't a\n            #   compressible file and will leave the file alone\n            #   and with an empty Content-Encoding\n            # - Some servers will notice that the file is\n            #   already compressed and will leave the file\n            #   alone and will add a Content-Encoding: gzip\n            #   header\n            # - Some servers won't notice anything at all and\n            #   will take a file that's already been compressed\n            #   and compress it again and set the\n            #   Content-Encoding: gzip header\n            #\n            # By setting this not to decode automatically we\n            # hope to eliminate problems with the second case.\n            decode_content=False,\n        ):\n            yield chunk\n    except AttributeError:\n        # Standard file-like object.\n        while True:\n            chunk = response.raw.read(chunk_size)\n            if not chunk:\n                break\n            yield chunk\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/network/xmlrpc.py",
    "content": "\"\"\"xmlrpclib.Transport implementation\n\"\"\"\n\nimport logging\nimport urllib.parse\nimport xmlrpc.client\nfrom typing import TYPE_CHECKING, Tuple\n\nfrom pip._internal.exceptions import NetworkConnectionError\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.network.utils import raise_for_status\n\nif TYPE_CHECKING:\n    from xmlrpc.client import _HostType, _Marshallable\n\nlogger = logging.getLogger(__name__)\n\n\nclass PipXmlrpcTransport(xmlrpc.client.Transport):\n    \"\"\"Provide a `xmlrpclib.Transport` implementation via a `PipSession`\n    object.\n    \"\"\"\n\n    def __init__(\n        self, index_url: str, session: PipSession, use_datetime: bool = False\n    ) -> None:\n        super().__init__(use_datetime)\n        index_parts = urllib.parse.urlparse(index_url)\n        self._scheme = index_parts.scheme\n        self._session = session\n\n    def request(\n        self,\n        host: \"_HostType\",\n        handler: str,\n        request_body: bytes,\n        verbose: bool = False,\n    ) -> Tuple[\"_Marshallable\", ...]:\n        assert isinstance(host, str)\n        parts = (self._scheme, host, handler, None, None, None)\n        url = urllib.parse.urlunparse(parts)\n        try:\n            headers = {\"Content-Type\": \"text/xml\"}\n            response = self._session.post(\n                url,\n                data=request_body,\n                headers=headers,\n                stream=True,\n            )\n            raise_for_status(response)\n            self.verbose = verbose\n            return self.parse_response(response.raw)\n        except NetworkConnectionError as exc:\n            assert exc.response\n            logger.critical(\n                \"HTTP error %s while getting %s\",\n                exc.response.status_code,\n                url,\n            )\n            raise\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/build/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/build/build_tracker.py",
    "content": "import contextlib\nimport hashlib\nimport logging\nimport os\nfrom types import TracebackType\nfrom typing import Dict, Generator, Optional, Set, Type, Union\n\nfrom pip._internal.models.link import Link\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.utils.temp_dir import TempDirectory\n\nlogger = logging.getLogger(__name__)\n\n\n@contextlib.contextmanager\ndef update_env_context_manager(**changes: str) -> Generator[None, None, None]:\n    target = os.environ\n\n    # Save values from the target and change them.\n    non_existent_marker = object()\n    saved_values: Dict[str, Union[object, str]] = {}\n    for name, new_value in changes.items():\n        try:\n            saved_values[name] = target[name]\n        except KeyError:\n            saved_values[name] = non_existent_marker\n        target[name] = new_value\n\n    try:\n        yield\n    finally:\n        # Restore original values in the target.\n        for name, original_value in saved_values.items():\n            if original_value is non_existent_marker:\n                del target[name]\n            else:\n                assert isinstance(original_value, str)  # for mypy\n                target[name] = original_value\n\n\n@contextlib.contextmanager\ndef get_build_tracker() -> Generator[\"BuildTracker\", None, None]:\n    root = os.environ.get(\"PIP_BUILD_TRACKER\")\n    with contextlib.ExitStack() as ctx:\n        if root is None:\n            root = ctx.enter_context(TempDirectory(kind=\"build-tracker\")).path\n            ctx.enter_context(update_env_context_manager(PIP_BUILD_TRACKER=root))\n            logger.debug(\"Initialized build tracking at %s\", root)\n\n        with BuildTracker(root) as tracker:\n            yield tracker\n\n\nclass BuildTracker:\n    def __init__(self, root: str) -> None:\n        self._root = root\n        self._entries: Set[InstallRequirement] = set()\n        logger.debug(\"Created build tracker: %s\", self._root)\n\n    def __enter__(self) -> \"BuildTracker\":\n        logger.debug(\"Entered build tracker: %s\", self._root)\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.cleanup()\n\n    def _entry_path(self, link: Link) -> str:\n        hashed = hashlib.sha224(link.url_without_fragment.encode()).hexdigest()\n        return os.path.join(self._root, hashed)\n\n    def add(self, req: InstallRequirement) -> None:\n        \"\"\"Add an InstallRequirement to build tracking.\"\"\"\n\n        assert req.link\n        # Get the file to write information about this requirement.\n        entry_path = self._entry_path(req.link)\n\n        # Try reading from the file. If it exists and can be read from, a build\n        # is already in progress, so a LookupError is raised.\n        try:\n            with open(entry_path) as fp:\n                contents = fp.read()\n        except FileNotFoundError:\n            pass\n        else:\n            message = \"{} is already being built: {}\".format(req.link, contents)\n            raise LookupError(message)\n\n        # If we're here, req should really not be building already.\n        assert req not in self._entries\n\n        # Start tracking this requirement.\n        with open(entry_path, \"w\", encoding=\"utf-8\") as fp:\n            fp.write(str(req))\n        self._entries.add(req)\n\n        logger.debug(\"Added %s to build tracker %r\", req, self._root)\n\n    def remove(self, req: InstallRequirement) -> None:\n        \"\"\"Remove an InstallRequirement from build tracking.\"\"\"\n\n        assert req.link\n        # Delete the created file and the corresponding entries.\n        os.unlink(self._entry_path(req.link))\n        self._entries.remove(req)\n\n        logger.debug(\"Removed %s from build tracker %r\", req, self._root)\n\n    def cleanup(self) -> None:\n        for req in set(self._entries):\n            self.remove(req)\n\n        logger.debug(\"Removed build tracker: %r\", self._root)\n\n    @contextlib.contextmanager\n    def track(self, req: InstallRequirement) -> Generator[None, None, None]:\n        self.add(req)\n        yield\n        self.remove(req)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/build/metadata.py",
    "content": "\"\"\"Metadata generation logic for source distributions.\n\"\"\"\n\nimport os\n\nfrom pip._vendor.pep517.wrappers import Pep517HookCaller\n\nfrom pip._internal.build_env import BuildEnvironment\nfrom pip._internal.exceptions import (\n    InstallationSubprocessError,\n    MetadataGenerationFailed,\n)\nfrom pip._internal.utils.subprocess import runner_with_spinner_message\nfrom pip._internal.utils.temp_dir import TempDirectory\n\n\ndef generate_metadata(\n    build_env: BuildEnvironment, backend: Pep517HookCaller, details: str\n) -> str:\n    \"\"\"Generate metadata using mechanisms described in PEP 517.\n\n    Returns the generated metadata directory.\n    \"\"\"\n    metadata_tmpdir = TempDirectory(kind=\"modern-metadata\", globally_managed=True)\n\n    metadata_dir = metadata_tmpdir.path\n\n    with build_env:\n        # Note that Pep517HookCaller implements a fallback for\n        # prepare_metadata_for_build_wheel, so we don't have to\n        # consider the possibility that this hook doesn't exist.\n        runner = runner_with_spinner_message(\"Preparing metadata (pyproject.toml)\")\n        with backend.subprocess_runner(runner):\n            try:\n                distinfo_dir = backend.prepare_metadata_for_build_wheel(metadata_dir)\n            except InstallationSubprocessError as error:\n                raise MetadataGenerationFailed(package_details=details) from error\n\n    return os.path.join(metadata_dir, distinfo_dir)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/build/metadata_editable.py",
    "content": "\"\"\"Metadata generation logic for source distributions.\n\"\"\"\n\nimport os\n\nfrom pip._vendor.pep517.wrappers import Pep517HookCaller\n\nfrom pip._internal.build_env import BuildEnvironment\nfrom pip._internal.exceptions import (\n    InstallationSubprocessError,\n    MetadataGenerationFailed,\n)\nfrom pip._internal.utils.subprocess import runner_with_spinner_message\nfrom pip._internal.utils.temp_dir import TempDirectory\n\n\ndef generate_editable_metadata(\n    build_env: BuildEnvironment, backend: Pep517HookCaller, details: str\n) -> str:\n    \"\"\"Generate metadata using mechanisms described in PEP 660.\n\n    Returns the generated metadata directory.\n    \"\"\"\n    metadata_tmpdir = TempDirectory(kind=\"modern-metadata\", globally_managed=True)\n\n    metadata_dir = metadata_tmpdir.path\n\n    with build_env:\n        # Note that Pep517HookCaller implements a fallback for\n        # prepare_metadata_for_build_wheel/editable, so we don't have to\n        # consider the possibility that this hook doesn't exist.\n        runner = runner_with_spinner_message(\n            \"Preparing editable metadata (pyproject.toml)\"\n        )\n        with backend.subprocess_runner(runner):\n            try:\n                distinfo_dir = backend.prepare_metadata_for_build_editable(metadata_dir)\n            except InstallationSubprocessError as error:\n                raise MetadataGenerationFailed(package_details=details) from error\n\n    return os.path.join(metadata_dir, distinfo_dir)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/build/metadata_legacy.py",
    "content": "\"\"\"Metadata generation logic for legacy source distributions.\n\"\"\"\n\nimport logging\nimport os\n\nfrom pip._internal.build_env import BuildEnvironment\nfrom pip._internal.cli.spinners import open_spinner\nfrom pip._internal.exceptions import (\n    InstallationError,\n    InstallationSubprocessError,\n    MetadataGenerationFailed,\n)\nfrom pip._internal.utils.setuptools_build import make_setuptools_egg_info_args\nfrom pip._internal.utils.subprocess import call_subprocess\nfrom pip._internal.utils.temp_dir import TempDirectory\n\nlogger = logging.getLogger(__name__)\n\n\ndef _find_egg_info(directory: str) -> str:\n    \"\"\"Find an .egg-info subdirectory in `directory`.\"\"\"\n    filenames = [f for f in os.listdir(directory) if f.endswith(\".egg-info\")]\n\n    if not filenames:\n        raise InstallationError(f\"No .egg-info directory found in {directory}\")\n\n    if len(filenames) > 1:\n        raise InstallationError(\n            \"More than one .egg-info directory found in {}\".format(directory)\n        )\n\n    return os.path.join(directory, filenames[0])\n\n\ndef generate_metadata(\n    build_env: BuildEnvironment,\n    setup_py_path: str,\n    source_dir: str,\n    isolated: bool,\n    details: str,\n) -> str:\n    \"\"\"Generate metadata using setup.py-based defacto mechanisms.\n\n    Returns the generated metadata directory.\n    \"\"\"\n    logger.debug(\n        \"Running setup.py (path:%s) egg_info for package %s\",\n        setup_py_path,\n        details,\n    )\n\n    egg_info_dir = TempDirectory(kind=\"pip-egg-info\", globally_managed=True).path\n\n    args = make_setuptools_egg_info_args(\n        setup_py_path,\n        egg_info_dir=egg_info_dir,\n        no_user_config=isolated,\n    )\n\n    with build_env:\n        with open_spinner(\"Preparing metadata (setup.py)\") as spinner:\n            try:\n                call_subprocess(\n                    args,\n                    cwd=source_dir,\n                    command_desc=\"python setup.py egg_info\",\n                    spinner=spinner,\n                )\n            except InstallationSubprocessError as error:\n                raise MetadataGenerationFailed(package_details=details) from error\n\n    # Return the .egg-info directory.\n    return _find_egg_info(egg_info_dir)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/build/wheel.py",
    "content": "import logging\nimport os\nfrom typing import Optional\n\nfrom pip._vendor.pep517.wrappers import Pep517HookCaller\n\nfrom pip._internal.utils.subprocess import runner_with_spinner_message\n\nlogger = logging.getLogger(__name__)\n\n\ndef build_wheel_pep517(\n    name: str,\n    backend: Pep517HookCaller,\n    metadata_directory: str,\n    tempd: str,\n) -> Optional[str]:\n    \"\"\"Build one InstallRequirement using the PEP 517 build process.\n\n    Returns path to wheel if successfully built. Otherwise, returns None.\n    \"\"\"\n    assert metadata_directory is not None\n    try:\n        logger.debug(\"Destination directory: %s\", tempd)\n\n        runner = runner_with_spinner_message(\n            f\"Building wheel for {name} (pyproject.toml)\"\n        )\n        with backend.subprocess_runner(runner):\n            wheel_name = backend.build_wheel(\n                tempd,\n                metadata_directory=metadata_directory,\n            )\n    except Exception:\n        logger.error(\"Failed building wheel for %s\", name)\n        return None\n    return os.path.join(tempd, wheel_name)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/build/wheel_editable.py",
    "content": "import logging\nimport os\nfrom typing import Optional\n\nfrom pip._vendor.pep517.wrappers import HookMissing, Pep517HookCaller\n\nfrom pip._internal.utils.subprocess import runner_with_spinner_message\n\nlogger = logging.getLogger(__name__)\n\n\ndef build_wheel_editable(\n    name: str,\n    backend: Pep517HookCaller,\n    metadata_directory: str,\n    tempd: str,\n) -> Optional[str]:\n    \"\"\"Build one InstallRequirement using the PEP 660 build process.\n\n    Returns path to wheel if successfully built. Otherwise, returns None.\n    \"\"\"\n    assert metadata_directory is not None\n    try:\n        logger.debug(\"Destination directory: %s\", tempd)\n\n        runner = runner_with_spinner_message(\n            f\"Building editable for {name} (pyproject.toml)\"\n        )\n        with backend.subprocess_runner(runner):\n            try:\n                wheel_name = backend.build_editable(\n                    tempd,\n                    metadata_directory=metadata_directory,\n                )\n            except HookMissing as e:\n                logger.error(\n                    \"Cannot build editable %s because the build \"\n                    \"backend does not have the %s hook\",\n                    name,\n                    e,\n                )\n                return None\n    except Exception:\n        logger.error(\"Failed building editable for %s\", name)\n        return None\n    return os.path.join(tempd, wheel_name)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/build/wheel_legacy.py",
    "content": "import logging\nimport os.path\nfrom typing import List, Optional\n\nfrom pip._internal.cli.spinners import open_spinner\nfrom pip._internal.utils.setuptools_build import make_setuptools_bdist_wheel_args\nfrom pip._internal.utils.subprocess import call_subprocess, format_command_args\n\nlogger = logging.getLogger(__name__)\n\n\ndef format_command_result(\n    command_args: List[str],\n    command_output: str,\n) -> str:\n    \"\"\"Format command information for logging.\"\"\"\n    command_desc = format_command_args(command_args)\n    text = f\"Command arguments: {command_desc}\\n\"\n\n    if not command_output:\n        text += \"Command output: None\"\n    elif logger.getEffectiveLevel() > logging.DEBUG:\n        text += \"Command output: [use --verbose to show]\"\n    else:\n        if not command_output.endswith(\"\\n\"):\n            command_output += \"\\n\"\n        text += f\"Command output:\\n{command_output}\"\n\n    return text\n\n\ndef get_legacy_build_wheel_path(\n    names: List[str],\n    temp_dir: str,\n    name: str,\n    command_args: List[str],\n    command_output: str,\n) -> Optional[str]:\n    \"\"\"Return the path to the wheel in the temporary build directory.\"\"\"\n    # Sort for determinism.\n    names = sorted(names)\n    if not names:\n        msg = (\"Legacy build of wheel for {!r} created no files.\\n\").format(name)\n        msg += format_command_result(command_args, command_output)\n        logger.warning(msg)\n        return None\n\n    if len(names) > 1:\n        msg = (\n            \"Legacy build of wheel for {!r} created more than one file.\\n\"\n            \"Filenames (choosing first): {}\\n\"\n        ).format(name, names)\n        msg += format_command_result(command_args, command_output)\n        logger.warning(msg)\n\n    return os.path.join(temp_dir, names[0])\n\n\ndef build_wheel_legacy(\n    name: str,\n    setup_py_path: str,\n    source_dir: str,\n    global_options: List[str],\n    build_options: List[str],\n    tempd: str,\n) -> Optional[str]:\n    \"\"\"Build one unpacked package using the \"legacy\" build process.\n\n    Returns path to wheel if successfully built. Otherwise, returns None.\n    \"\"\"\n    wheel_args = make_setuptools_bdist_wheel_args(\n        setup_py_path,\n        global_options=global_options,\n        build_options=build_options,\n        destination_dir=tempd,\n    )\n\n    spin_message = f\"Building wheel for {name} (setup.py)\"\n    with open_spinner(spin_message) as spinner:\n        logger.debug(\"Destination directory: %s\", tempd)\n\n        try:\n            output = call_subprocess(\n                wheel_args,\n                command_desc=\"python setup.py bdist_wheel\",\n                cwd=source_dir,\n                spinner=spinner,\n            )\n        except Exception:\n            spinner.finish(\"error\")\n            logger.error(\"Failed building wheel for %s\", name)\n            return None\n\n        names = os.listdir(tempd)\n        wheel_path = get_legacy_build_wheel_path(\n            names=names,\n            temp_dir=tempd,\n            name=name,\n            command_args=wheel_args,\n            command_output=output,\n        )\n        return wheel_path\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/check.py",
    "content": "\"\"\"Validation of dependencies of packages\n\"\"\"\n\nimport logging\nfrom typing import Callable, Dict, List, NamedTuple, Optional, Set, Tuple\n\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\n\nfrom pip._internal.distributions import make_distribution_for_install_requirement\nfrom pip._internal.metadata import get_default_environment\nfrom pip._internal.metadata.base import DistributionVersion\nfrom pip._internal.req.req_install import InstallRequirement\n\nlogger = logging.getLogger(__name__)\n\n\nclass PackageDetails(NamedTuple):\n    version: DistributionVersion\n    dependencies: List[Requirement]\n\n\n# Shorthands\nPackageSet = Dict[NormalizedName, PackageDetails]\nMissing = Tuple[NormalizedName, Requirement]\nConflicting = Tuple[NormalizedName, DistributionVersion, Requirement]\n\nMissingDict = Dict[NormalizedName, List[Missing]]\nConflictingDict = Dict[NormalizedName, List[Conflicting]]\nCheckResult = Tuple[MissingDict, ConflictingDict]\nConflictDetails = Tuple[PackageSet, CheckResult]\n\n\ndef create_package_set_from_installed() -> Tuple[PackageSet, bool]:\n    \"\"\"Converts a list of distributions into a PackageSet.\"\"\"\n    package_set = {}\n    problems = False\n    env = get_default_environment()\n    for dist in env.iter_installed_distributions(local_only=False, skip=()):\n        name = dist.canonical_name\n        try:\n            dependencies = list(dist.iter_dependencies())\n            package_set[name] = PackageDetails(dist.version, dependencies)\n        except (OSError, ValueError) as e:\n            # Don't crash on unreadable or broken metadata.\n            logger.warning(\"Error parsing requirements for %s: %s\", name, e)\n            problems = True\n    return package_set, problems\n\n\ndef check_package_set(\n    package_set: PackageSet, should_ignore: Optional[Callable[[str], bool]] = None\n) -> CheckResult:\n    \"\"\"Check if a package set is consistent\n\n    If should_ignore is passed, it should be a callable that takes a\n    package name and returns a boolean.\n    \"\"\"\n\n    missing = {}\n    conflicting = {}\n\n    for package_name, package_detail in package_set.items():\n        # Info about dependencies of package_name\n        missing_deps: Set[Missing] = set()\n        conflicting_deps: Set[Conflicting] = set()\n\n        if should_ignore and should_ignore(package_name):\n            continue\n\n        for req in package_detail.dependencies:\n            name = canonicalize_name(req.name)\n\n            # Check if it's missing\n            if name not in package_set:\n                missed = True\n                if req.marker is not None:\n                    missed = req.marker.evaluate()\n                if missed:\n                    missing_deps.add((name, req))\n                continue\n\n            # Check if there's a conflict\n            version = package_set[name].version\n            if not req.specifier.contains(version, prereleases=True):\n                conflicting_deps.add((name, version, req))\n\n        if missing_deps:\n            missing[package_name] = sorted(missing_deps, key=str)\n        if conflicting_deps:\n            conflicting[package_name] = sorted(conflicting_deps, key=str)\n\n    return missing, conflicting\n\n\ndef check_install_conflicts(to_install: List[InstallRequirement]) -> ConflictDetails:\n    \"\"\"For checking if the dependency graph would be consistent after \\\n    installing given requirements\n    \"\"\"\n    # Start from the current state\n    package_set, _ = create_package_set_from_installed()\n    # Install packages\n    would_be_installed = _simulate_installation_of(to_install, package_set)\n\n    # Only warn about directly-dependent packages; create a whitelist of them\n    whitelist = _create_whitelist(would_be_installed, package_set)\n\n    return (\n        package_set,\n        check_package_set(\n            package_set, should_ignore=lambda name: name not in whitelist\n        ),\n    )\n\n\ndef _simulate_installation_of(\n    to_install: List[InstallRequirement], package_set: PackageSet\n) -> Set[NormalizedName]:\n    \"\"\"Computes the version of packages after installing to_install.\"\"\"\n    # Keep track of packages that were installed\n    installed = set()\n\n    # Modify it as installing requirement_set would (assuming no errors)\n    for inst_req in to_install:\n        abstract_dist = make_distribution_for_install_requirement(inst_req)\n        dist = abstract_dist.get_metadata_distribution()\n        name = dist.canonical_name\n        package_set[name] = PackageDetails(dist.version, list(dist.iter_dependencies()))\n\n        installed.add(name)\n\n    return installed\n\n\ndef _create_whitelist(\n    would_be_installed: Set[NormalizedName], package_set: PackageSet\n) -> Set[NormalizedName]:\n    packages_affected = set(would_be_installed)\n\n    for package_name in package_set:\n        if package_name in packages_affected:\n            continue\n\n        for req in package_set[package_name].dependencies:\n            if canonicalize_name(req.name) in packages_affected:\n                packages_affected.add(package_name)\n                break\n\n    return packages_affected\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/freeze.py",
    "content": "import collections\nimport logging\nimport os\nfrom typing import Container, Dict, Generator, Iterable, List, NamedTuple, Optional, Set\n\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.packaging.version import Version\n\nfrom pip._internal.exceptions import BadCommand, InstallationError\nfrom pip._internal.metadata import BaseDistribution, get_environment\nfrom pip._internal.req.constructors import (\n    install_req_from_editable,\n    install_req_from_line,\n)\nfrom pip._internal.req.req_file import COMMENT_RE\nfrom pip._internal.utils.direct_url_helpers import direct_url_as_pep440_direct_reference\n\nlogger = logging.getLogger(__name__)\n\n\nclass _EditableInfo(NamedTuple):\n    requirement: str\n    comments: List[str]\n\n\ndef freeze(\n    requirement: Optional[List[str]] = None,\n    local_only: bool = False,\n    user_only: bool = False,\n    paths: Optional[List[str]] = None,\n    isolated: bool = False,\n    exclude_editable: bool = False,\n    skip: Container[str] = (),\n) -> Generator[str, None, None]:\n    installations: Dict[str, FrozenRequirement] = {}\n\n    dists = get_environment(paths).iter_installed_distributions(\n        local_only=local_only,\n        skip=(),\n        user_only=user_only,\n    )\n    for dist in dists:\n        req = FrozenRequirement.from_dist(dist)\n        if exclude_editable and req.editable:\n            continue\n        installations[req.canonical_name] = req\n\n    if requirement:\n        # the options that don't get turned into an InstallRequirement\n        # should only be emitted once, even if the same option is in multiple\n        # requirements files, so we need to keep track of what has been emitted\n        # so that we don't emit it again if it's seen again\n        emitted_options: Set[str] = set()\n        # keep track of which files a requirement is in so that we can\n        # give an accurate warning if a requirement appears multiple times.\n        req_files: Dict[str, List[str]] = collections.defaultdict(list)\n        for req_file_path in requirement:\n            with open(req_file_path) as req_file:\n                for line in req_file:\n                    if (\n                        not line.strip()\n                        or line.strip().startswith(\"#\")\n                        or line.startswith(\n                            (\n                                \"-r\",\n                                \"--requirement\",\n                                \"-f\",\n                                \"--find-links\",\n                                \"-i\",\n                                \"--index-url\",\n                                \"--pre\",\n                                \"--trusted-host\",\n                                \"--process-dependency-links\",\n                                \"--extra-index-url\",\n                                \"--use-feature\",\n                            )\n                        )\n                    ):\n                        line = line.rstrip()\n                        if line not in emitted_options:\n                            emitted_options.add(line)\n                            yield line\n                        continue\n\n                    if line.startswith(\"-e\") or line.startswith(\"--editable\"):\n                        if line.startswith(\"-e\"):\n                            line = line[2:].strip()\n                        else:\n                            line = line[len(\"--editable\") :].strip().lstrip(\"=\")\n                        line_req = install_req_from_editable(\n                            line,\n                            isolated=isolated,\n                        )\n                    else:\n                        line_req = install_req_from_line(\n                            COMMENT_RE.sub(\"\", line).strip(),\n                            isolated=isolated,\n                        )\n\n                    if not line_req.name:\n                        logger.info(\n                            \"Skipping line in requirement file [%s] because \"\n                            \"it's not clear what it would install: %s\",\n                            req_file_path,\n                            line.strip(),\n                        )\n                        logger.info(\n                            \"  (add #egg=PackageName to the URL to avoid\"\n                            \" this warning)\"\n                        )\n                    else:\n                        line_req_canonical_name = canonicalize_name(line_req.name)\n                        if line_req_canonical_name not in installations:\n                            # either it's not installed, or it is installed\n                            # but has been processed already\n                            if not req_files[line_req.name]:\n                                logger.warning(\n                                    \"Requirement file [%s] contains %s, but \"\n                                    \"package %r is not installed\",\n                                    req_file_path,\n                                    COMMENT_RE.sub(\"\", line).strip(),\n                                    line_req.name,\n                                )\n                            else:\n                                req_files[line_req.name].append(req_file_path)\n                        else:\n                            yield str(installations[line_req_canonical_name]).rstrip()\n                            del installations[line_req_canonical_name]\n                            req_files[line_req.name].append(req_file_path)\n\n        # Warn about requirements that were included multiple times (in a\n        # single requirements file or in different requirements files).\n        for name, files in req_files.items():\n            if len(files) > 1:\n                logger.warning(\n                    \"Requirement %s included multiple times [%s]\",\n                    name,\n                    \", \".join(sorted(set(files))),\n                )\n\n        yield (\"## The following requirements were added by pip freeze:\")\n    for installation in sorted(installations.values(), key=lambda x: x.name.lower()):\n        if installation.canonical_name not in skip:\n            yield str(installation).rstrip()\n\n\ndef _format_as_name_version(dist: BaseDistribution) -> str:\n    if isinstance(dist.version, Version):\n        return f\"{dist.raw_name}=={dist.version}\"\n    return f\"{dist.raw_name}==={dist.version}\"\n\n\ndef _get_editable_info(dist: BaseDistribution) -> _EditableInfo:\n    \"\"\"\n    Compute and return values (req, comments) for use in\n    FrozenRequirement.from_dist().\n    \"\"\"\n    editable_project_location = dist.editable_project_location\n    assert editable_project_location\n    location = os.path.normcase(os.path.abspath(editable_project_location))\n\n    from pip._internal.vcs import RemoteNotFoundError, RemoteNotValidError, vcs\n\n    vcs_backend = vcs.get_backend_for_dir(location)\n\n    if vcs_backend is None:\n        display = _format_as_name_version(dist)\n        logger.debug(\n            'No VCS found for editable requirement \"%s\" in: %r',\n            display,\n            location,\n        )\n        return _EditableInfo(\n            requirement=location,\n            comments=[f\"# Editable install with no version control ({display})\"],\n        )\n\n    vcs_name = type(vcs_backend).__name__\n\n    try:\n        req = vcs_backend.get_src_requirement(location, dist.raw_name)\n    except RemoteNotFoundError:\n        display = _format_as_name_version(dist)\n        return _EditableInfo(\n            requirement=location,\n            comments=[f\"# Editable {vcs_name} install with no remote ({display})\"],\n        )\n    except RemoteNotValidError as ex:\n        display = _format_as_name_version(dist)\n        return _EditableInfo(\n            requirement=location,\n            comments=[\n                f\"# Editable {vcs_name} install ({display}) with either a deleted \"\n                f\"local remote or invalid URI:\",\n                f\"# '{ex.url}'\",\n            ],\n        )\n    except BadCommand:\n        logger.warning(\n            \"cannot determine version of editable source in %s \"\n            \"(%s command not found in path)\",\n            location,\n            vcs_backend.name,\n        )\n        return _EditableInfo(requirement=location, comments=[])\n    except InstallationError as exc:\n        logger.warning(\"Error when trying to get requirement for VCS system %s\", exc)\n    else:\n        return _EditableInfo(requirement=req, comments=[])\n\n    logger.warning(\"Could not determine repository location of %s\", location)\n\n    return _EditableInfo(\n        requirement=location,\n        comments=[\"## !! Could not determine repository location\"],\n    )\n\n\nclass FrozenRequirement:\n    def __init__(\n        self,\n        name: str,\n        req: str,\n        editable: bool,\n        comments: Iterable[str] = (),\n    ) -> None:\n        self.name = name\n        self.canonical_name = canonicalize_name(name)\n        self.req = req\n        self.editable = editable\n        self.comments = comments\n\n    @classmethod\n    def from_dist(cls, dist: BaseDistribution) -> \"FrozenRequirement\":\n        editable = dist.editable\n        if editable:\n            req, comments = _get_editable_info(dist)\n        else:\n            comments = []\n            direct_url = dist.direct_url\n            if direct_url:\n                # if PEP 610 metadata is present, use it\n                req = direct_url_as_pep440_direct_reference(direct_url, dist.raw_name)\n            else:\n                # name==version requirement\n                req = _format_as_name_version(dist)\n\n        return cls(dist.raw_name, req, editable, comments=comments)\n\n    def __str__(self) -> str:\n        req = self.req\n        if self.editable:\n            req = f\"-e {req}\"\n        return \"\\n\".join(list(self.comments) + [str(req)]) + \"\\n\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/install/__init__.py",
    "content": "\"\"\"For modules related to installing packages.\n\"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/install/editable_legacy.py",
    "content": "\"\"\"Legacy editable installation process, i.e. `setup.py develop`.\n\"\"\"\nimport logging\nfrom typing import List, Optional, Sequence\n\nfrom pip._internal.build_env import BuildEnvironment\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.setuptools_build import make_setuptools_develop_args\nfrom pip._internal.utils.subprocess import call_subprocess\n\nlogger = logging.getLogger(__name__)\n\n\ndef install_editable(\n    install_options: List[str],\n    global_options: Sequence[str],\n    prefix: Optional[str],\n    home: Optional[str],\n    use_user_site: bool,\n    name: str,\n    setup_py_path: str,\n    isolated: bool,\n    build_env: BuildEnvironment,\n    unpacked_source_directory: str,\n) -> None:\n    \"\"\"Install a package in editable mode. Most arguments are pass-through\n    to setuptools.\n    \"\"\"\n    logger.info(\"Running setup.py develop for %s\", name)\n\n    args = make_setuptools_develop_args(\n        setup_py_path,\n        global_options=global_options,\n        install_options=install_options,\n        no_user_config=isolated,\n        prefix=prefix,\n        home=home,\n        use_user_site=use_user_site,\n    )\n\n    with indent_log():\n        with build_env:\n            call_subprocess(\n                args,\n                command_desc=\"python setup.py develop\",\n                cwd=unpacked_source_directory,\n            )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/install/legacy.py",
    "content": "\"\"\"Legacy installation process, i.e. `setup.py install`.\n\"\"\"\n\nimport logging\nimport os\nfrom typing import List, Optional, Sequence\n\nfrom pip._internal.build_env import BuildEnvironment\nfrom pip._internal.exceptions import InstallationError, LegacyInstallFailure\nfrom pip._internal.locations.base import change_root\nfrom pip._internal.models.scheme import Scheme\nfrom pip._internal.utils.misc import ensure_dir\nfrom pip._internal.utils.setuptools_build import make_setuptools_install_args\nfrom pip._internal.utils.subprocess import runner_with_spinner_message\nfrom pip._internal.utils.temp_dir import TempDirectory\n\nlogger = logging.getLogger(__name__)\n\n\ndef write_installed_files_from_setuptools_record(\n    record_lines: List[str],\n    root: Optional[str],\n    req_description: str,\n) -> None:\n    def prepend_root(path: str) -> str:\n        if root is None or not os.path.isabs(path):\n            return path\n        else:\n            return change_root(root, path)\n\n    for line in record_lines:\n        directory = os.path.dirname(line)\n        if directory.endswith(\".egg-info\"):\n            egg_info_dir = prepend_root(directory)\n            break\n    else:\n        message = (\n            \"{} did not indicate that it installed an \"\n            \".egg-info directory. Only setup.py projects \"\n            \"generating .egg-info directories are supported.\"\n        ).format(req_description)\n        raise InstallationError(message)\n\n    new_lines = []\n    for line in record_lines:\n        filename = line.strip()\n        if os.path.isdir(filename):\n            filename += os.path.sep\n        new_lines.append(os.path.relpath(prepend_root(filename), egg_info_dir))\n    new_lines.sort()\n    ensure_dir(egg_info_dir)\n    inst_files_path = os.path.join(egg_info_dir, \"installed-files.txt\")\n    with open(inst_files_path, \"w\") as f:\n        f.write(\"\\n\".join(new_lines) + \"\\n\")\n\n\ndef install(\n    install_options: List[str],\n    global_options: Sequence[str],\n    root: Optional[str],\n    home: Optional[str],\n    prefix: Optional[str],\n    use_user_site: bool,\n    pycompile: bool,\n    scheme: Scheme,\n    setup_py_path: str,\n    isolated: bool,\n    req_name: str,\n    build_env: BuildEnvironment,\n    unpacked_source_directory: str,\n    req_description: str,\n) -> bool:\n\n    header_dir = scheme.headers\n\n    with TempDirectory(kind=\"record\") as temp_dir:\n        try:\n            record_filename = os.path.join(temp_dir.path, \"install-record.txt\")\n            install_args = make_setuptools_install_args(\n                setup_py_path,\n                global_options=global_options,\n                install_options=install_options,\n                record_filename=record_filename,\n                root=root,\n                prefix=prefix,\n                header_dir=header_dir,\n                home=home,\n                use_user_site=use_user_site,\n                no_user_config=isolated,\n                pycompile=pycompile,\n            )\n\n            runner = runner_with_spinner_message(\n                f\"Running setup.py install for {req_name}\"\n            )\n            with build_env:\n                runner(\n                    cmd=install_args,\n                    cwd=unpacked_source_directory,\n                )\n\n            if not os.path.exists(record_filename):\n                logger.debug(\"Record file %s not found\", record_filename)\n                # Signal to the caller that we didn't install the new package\n                return False\n\n        except Exception as e:\n            # Signal to the caller that we didn't install the new package\n            raise LegacyInstallFailure(package_details=req_name) from e\n\n        # At this point, we have successfully installed the requirement.\n\n        # We intentionally do not use any encoding to read the file because\n        # setuptools writes the file using distutils.file_util.write_file,\n        # which does not specify an encoding.\n        with open(record_filename) as f:\n            record_lines = f.read().splitlines()\n\n    write_installed_files_from_setuptools_record(record_lines, root, req_description)\n    return True\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/install/wheel.py",
    "content": "\"\"\"Support for installing and building the \"wheel\" binary package format.\n\"\"\"\n\nimport collections\nimport compileall\nimport contextlib\nimport csv\nimport importlib\nimport logging\nimport os.path\nimport re\nimport shutil\nimport sys\nimport warnings\nfrom base64 import urlsafe_b64encode\nfrom email.message import Message\nfrom itertools import chain, filterfalse, starmap\nfrom typing import (\n    IO,\n    TYPE_CHECKING,\n    Any,\n    BinaryIO,\n    Callable,\n    Dict,\n    Generator,\n    Iterable,\n    Iterator,\n    List,\n    NewType,\n    Optional,\n    Sequence,\n    Set,\n    Tuple,\n    Union,\n    cast,\n)\nfrom zipfile import ZipFile, ZipInfo\n\nfrom pip._vendor.distlib.scripts import ScriptMaker\nfrom pip._vendor.distlib.util import get_export_entry\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.locations import get_major_minor_version\nfrom pip._internal.metadata import (\n    BaseDistribution,\n    FilesystemWheel,\n    get_wheel_distribution,\n)\nfrom pip._internal.models.direct_url import DIRECT_URL_METADATA_NAME, DirectUrl\nfrom pip._internal.models.scheme import SCHEME_KEYS, Scheme\nfrom pip._internal.utils.filesystem import adjacent_tmp_file, replace\nfrom pip._internal.utils.misc import captured_stdout, ensure_dir, hash_file, partition\nfrom pip._internal.utils.unpacking import (\n    current_umask,\n    is_within_directory,\n    set_extracted_file_to_default_mode_plus_executable,\n    zip_item_is_executable,\n)\nfrom pip._internal.utils.wheel import parse_wheel\n\nif TYPE_CHECKING:\n    from typing import Protocol\n\n    class File(Protocol):\n        src_record_path: \"RecordPath\"\n        dest_path: str\n        changed: bool\n\n        def save(self) -> None:\n            pass\n\n\nlogger = logging.getLogger(__name__)\n\nRecordPath = NewType(\"RecordPath\", str)\nInstalledCSVRow = Tuple[RecordPath, str, Union[int, str]]\n\n\ndef rehash(path: str, blocksize: int = 1 << 20) -> Tuple[str, str]:\n    \"\"\"Return (encoded_digest, length) for path using hashlib.sha256()\"\"\"\n    h, length = hash_file(path, blocksize)\n    digest = \"sha256=\" + urlsafe_b64encode(h.digest()).decode(\"latin1\").rstrip(\"=\")\n    return (digest, str(length))\n\n\ndef csv_io_kwargs(mode: str) -> Dict[str, Any]:\n    \"\"\"Return keyword arguments to properly open a CSV file\n    in the given mode.\n    \"\"\"\n    return {\"mode\": mode, \"newline\": \"\", \"encoding\": \"utf-8\"}\n\n\ndef fix_script(path: str) -> bool:\n    \"\"\"Replace #!python with #!/path/to/python\n    Return True if file was changed.\n    \"\"\"\n    # XXX RECORD hashes will need to be updated\n    assert os.path.isfile(path)\n\n    with open(path, \"rb\") as script:\n        firstline = script.readline()\n        if not firstline.startswith(b\"#!python\"):\n            return False\n        exename = sys.executable.encode(sys.getfilesystemencoding())\n        firstline = b\"#!\" + exename + os.linesep.encode(\"ascii\")\n        rest = script.read()\n    with open(path, \"wb\") as script:\n        script.write(firstline)\n        script.write(rest)\n    return True\n\n\ndef wheel_root_is_purelib(metadata: Message) -> bool:\n    return metadata.get(\"Root-Is-Purelib\", \"\").lower() == \"true\"\n\n\ndef get_entrypoints(dist: BaseDistribution) -> Tuple[Dict[str, str], Dict[str, str]]:\n    console_scripts = {}\n    gui_scripts = {}\n    for entry_point in dist.iter_entry_points():\n        if entry_point.group == \"console_scripts\":\n            console_scripts[entry_point.name] = entry_point.value\n        elif entry_point.group == \"gui_scripts\":\n            gui_scripts[entry_point.name] = entry_point.value\n    return console_scripts, gui_scripts\n\n\ndef message_about_scripts_not_on_PATH(scripts: Sequence[str]) -> Optional[str]:\n    \"\"\"Determine if any scripts are not on PATH and format a warning.\n    Returns a warning message if one or more scripts are not on PATH,\n    otherwise None.\n    \"\"\"\n    if not scripts:\n        return None\n\n    # Group scripts by the path they were installed in\n    grouped_by_dir: Dict[str, Set[str]] = collections.defaultdict(set)\n    for destfile in scripts:\n        parent_dir = os.path.dirname(destfile)\n        script_name = os.path.basename(destfile)\n        grouped_by_dir[parent_dir].add(script_name)\n\n    # We don't want to warn for directories that are on PATH.\n    not_warn_dirs = [\n        os.path.normcase(i).rstrip(os.sep)\n        for i in os.environ.get(\"PATH\", \"\").split(os.pathsep)\n    ]\n    # If an executable sits with sys.executable, we don't warn for it.\n    #     This covers the case of venv invocations without activating the venv.\n    not_warn_dirs.append(os.path.normcase(os.path.dirname(sys.executable)))\n    warn_for: Dict[str, Set[str]] = {\n        parent_dir: scripts\n        for parent_dir, scripts in grouped_by_dir.items()\n        if os.path.normcase(parent_dir) not in not_warn_dirs\n    }\n    if not warn_for:\n        return None\n\n    # Format a message\n    msg_lines = []\n    for parent_dir, dir_scripts in warn_for.items():\n        sorted_scripts: List[str] = sorted(dir_scripts)\n        if len(sorted_scripts) == 1:\n            start_text = \"script {} is\".format(sorted_scripts[0])\n        else:\n            start_text = \"scripts {} are\".format(\n                \", \".join(sorted_scripts[:-1]) + \" and \" + sorted_scripts[-1]\n            )\n\n        msg_lines.append(\n            \"The {} installed in '{}' which is not on PATH.\".format(\n                start_text, parent_dir\n            )\n        )\n\n    last_line_fmt = (\n        \"Consider adding {} to PATH or, if you prefer \"\n        \"to suppress this warning, use --no-warn-script-location.\"\n    )\n    if len(msg_lines) == 1:\n        msg_lines.append(last_line_fmt.format(\"this directory\"))\n    else:\n        msg_lines.append(last_line_fmt.format(\"these directories\"))\n\n    # Add a note if any directory starts with ~\n    warn_for_tilde = any(\n        i[0] == \"~\" for i in os.environ.get(\"PATH\", \"\").split(os.pathsep) if i\n    )\n    if warn_for_tilde:\n        tilde_warning_msg = (\n            \"NOTE: The current PATH contains path(s) starting with `~`, \"\n            \"which may not be expanded by all applications.\"\n        )\n        msg_lines.append(tilde_warning_msg)\n\n    # Returns the formatted multiline message\n    return \"\\n\".join(msg_lines)\n\n\ndef _normalized_outrows(\n    outrows: Iterable[InstalledCSVRow],\n) -> List[Tuple[str, str, str]]:\n    \"\"\"Normalize the given rows of a RECORD file.\n\n    Items in each row are converted into str. Rows are then sorted to make\n    the value more predictable for tests.\n\n    Each row is a 3-tuple (path, hash, size) and corresponds to a record of\n    a RECORD file (see PEP 376 and PEP 427 for details).  For the rows\n    passed to this function, the size can be an integer as an int or string,\n    or the empty string.\n    \"\"\"\n    # Normally, there should only be one row per path, in which case the\n    # second and third elements don't come into play when sorting.\n    # However, in cases in the wild where a path might happen to occur twice,\n    # we don't want the sort operation to trigger an error (but still want\n    # determinism).  Since the third element can be an int or string, we\n    # coerce each element to a string to avoid a TypeError in this case.\n    # For additional background, see--\n    # https://github.com/pypa/pip/issues/5868\n    return sorted(\n        (record_path, hash_, str(size)) for record_path, hash_, size in outrows\n    )\n\n\ndef _record_to_fs_path(record_path: RecordPath, lib_dir: str) -> str:\n    return os.path.join(lib_dir, record_path)\n\n\ndef _fs_to_record_path(path: str, lib_dir: str) -> RecordPath:\n    # On Windows, do not handle relative paths if they belong to different\n    # logical disks\n    if os.path.splitdrive(path)[0].lower() == os.path.splitdrive(lib_dir)[0].lower():\n        path = os.path.relpath(path, lib_dir)\n\n    path = path.replace(os.path.sep, \"/\")\n    return cast(\"RecordPath\", path)\n\n\ndef get_csv_rows_for_installed(\n    old_csv_rows: List[List[str]],\n    installed: Dict[RecordPath, RecordPath],\n    changed: Set[RecordPath],\n    generated: List[str],\n    lib_dir: str,\n) -> List[InstalledCSVRow]:\n    \"\"\"\n    :param installed: A map from archive RECORD path to installation RECORD\n        path.\n    \"\"\"\n    installed_rows: List[InstalledCSVRow] = []\n    for row in old_csv_rows:\n        if len(row) > 3:\n            logger.warning(\"RECORD line has more than three elements: %s\", row)\n        old_record_path = cast(\"RecordPath\", row[0])\n        new_record_path = installed.pop(old_record_path, old_record_path)\n        if new_record_path in changed:\n            digest, length = rehash(_record_to_fs_path(new_record_path, lib_dir))\n        else:\n            digest = row[1] if len(row) > 1 else \"\"\n            length = row[2] if len(row) > 2 else \"\"\n        installed_rows.append((new_record_path, digest, length))\n    for f in generated:\n        path = _fs_to_record_path(f, lib_dir)\n        digest, length = rehash(f)\n        installed_rows.append((path, digest, length))\n    for installed_record_path in installed.values():\n        installed_rows.append((installed_record_path, \"\", \"\"))\n    return installed_rows\n\n\ndef get_console_script_specs(console: Dict[str, str]) -> List[str]:\n    \"\"\"\n    Given the mapping from entrypoint name to callable, return the relevant\n    console script specs.\n    \"\"\"\n    # Don't mutate caller's version\n    console = console.copy()\n\n    scripts_to_generate = []\n\n    # Special case pip and setuptools to generate versioned wrappers\n    #\n    # The issue is that some projects (specifically, pip and setuptools) use\n    # code in setup.py to create \"versioned\" entry points - pip2.7 on Python\n    # 2.7, pip3.3 on Python 3.3, etc. But these entry points are baked into\n    # the wheel metadata at build time, and so if the wheel is installed with\n    # a *different* version of Python the entry points will be wrong. The\n    # correct fix for this is to enhance the metadata to be able to describe\n    # such versioned entry points, but that won't happen till Metadata 2.0 is\n    # available.\n    # In the meantime, projects using versioned entry points will either have\n    # incorrect versioned entry points, or they will not be able to distribute\n    # \"universal\" wheels (i.e., they will need a wheel per Python version).\n    #\n    # Because setuptools and pip are bundled with _ensurepip and virtualenv,\n    # we need to use universal wheels. So, as a stopgap until Metadata 2.0, we\n    # override the versioned entry points in the wheel and generate the\n    # correct ones. This code is purely a short-term measure until Metadata 2.0\n    # is available.\n    #\n    # To add the level of hack in this section of code, in order to support\n    # ensurepip this code will look for an ``ENSUREPIP_OPTIONS`` environment\n    # variable which will control which version scripts get installed.\n    #\n    # ENSUREPIP_OPTIONS=altinstall\n    #   - Only pipX.Y and easy_install-X.Y will be generated and installed\n    # ENSUREPIP_OPTIONS=install\n    #   - pipX.Y, pipX, easy_install-X.Y will be generated and installed. Note\n    #     that this option is technically if ENSUREPIP_OPTIONS is set and is\n    #     not altinstall\n    # DEFAULT\n    #   - The default behavior is to install pip, pipX, pipX.Y, easy_install\n    #     and easy_install-X.Y.\n    pip_script = console.pop(\"pip\", None)\n    if pip_script:\n        if \"ENSUREPIP_OPTIONS\" not in os.environ:\n            scripts_to_generate.append(\"pip = \" + pip_script)\n\n        if os.environ.get(\"ENSUREPIP_OPTIONS\", \"\") != \"altinstall\":\n            scripts_to_generate.append(\n                \"pip{} = {}\".format(sys.version_info[0], pip_script)\n            )\n\n        scripts_to_generate.append(f\"pip{get_major_minor_version()} = {pip_script}\")\n        # Delete any other versioned pip entry points\n        pip_ep = [k for k in console if re.match(r\"pip(\\d+(\\.\\d+)?)?$\", k)]\n        for k in pip_ep:\n            del console[k]\n    easy_install_script = console.pop(\"easy_install\", None)\n    if easy_install_script:\n        if \"ENSUREPIP_OPTIONS\" not in os.environ:\n            scripts_to_generate.append(\"easy_install = \" + easy_install_script)\n\n        scripts_to_generate.append(\n            \"easy_install-{} = {}\".format(\n                get_major_minor_version(), easy_install_script\n            )\n        )\n        # Delete any other versioned easy_install entry points\n        easy_install_ep = [\n            k for k in console if re.match(r\"easy_install(-\\d+\\.\\d+)?$\", k)\n        ]\n        for k in easy_install_ep:\n            del console[k]\n\n    # Generate the console entry points specified in the wheel\n    scripts_to_generate.extend(starmap(\"{} = {}\".format, console.items()))\n\n    return scripts_to_generate\n\n\nclass ZipBackedFile:\n    def __init__(\n        self, src_record_path: RecordPath, dest_path: str, zip_file: ZipFile\n    ) -> None:\n        self.src_record_path = src_record_path\n        self.dest_path = dest_path\n        self._zip_file = zip_file\n        self.changed = False\n\n    def _getinfo(self) -> ZipInfo:\n        return self._zip_file.getinfo(self.src_record_path)\n\n    def save(self) -> None:\n        # directory creation is lazy and after file filtering\n        # to ensure we don't install empty dirs; empty dirs can't be\n        # uninstalled.\n        parent_dir = os.path.dirname(self.dest_path)\n        ensure_dir(parent_dir)\n\n        # When we open the output file below, any existing file is truncated\n        # before we start writing the new contents. This is fine in most\n        # cases, but can cause a segfault if pip has loaded a shared\n        # object (e.g. from pyopenssl through its vendored urllib3)\n        # Since the shared object is mmap'd an attempt to call a\n        # symbol in it will then cause a segfault. Unlinking the file\n        # allows writing of new contents while allowing the process to\n        # continue to use the old copy.\n        if os.path.exists(self.dest_path):\n            os.unlink(self.dest_path)\n\n        zipinfo = self._getinfo()\n\n        with self._zip_file.open(zipinfo) as f:\n            with open(self.dest_path, \"wb\") as dest:\n                shutil.copyfileobj(f, dest)\n\n        if zip_item_is_executable(zipinfo):\n            set_extracted_file_to_default_mode_plus_executable(self.dest_path)\n\n\nclass ScriptFile:\n    def __init__(self, file: \"File\") -> None:\n        self._file = file\n        self.src_record_path = self._file.src_record_path\n        self.dest_path = self._file.dest_path\n        self.changed = False\n\n    def save(self) -> None:\n        self._file.save()\n        self.changed = fix_script(self.dest_path)\n\n\nclass MissingCallableSuffix(InstallationError):\n    def __init__(self, entry_point: str) -> None:\n        super().__init__(\n            \"Invalid script entry point: {} - A callable \"\n            \"suffix is required. Cf https://packaging.python.org/\"\n            \"specifications/entry-points/#use-for-scripts for more \"\n            \"information.\".format(entry_point)\n        )\n\n\ndef _raise_for_invalid_entrypoint(specification: str) -> None:\n    entry = get_export_entry(specification)\n    if entry is not None and entry.suffix is None:\n        raise MissingCallableSuffix(str(entry))\n\n\nclass PipScriptMaker(ScriptMaker):\n    def make(\n        self, specification: str, options: Optional[Dict[str, Any]] = None\n    ) -> List[str]:\n        _raise_for_invalid_entrypoint(specification)\n        return super().make(specification, options)\n\n\ndef _install_wheel(\n    name: str,\n    wheel_zip: ZipFile,\n    wheel_path: str,\n    scheme: Scheme,\n    pycompile: bool = True,\n    warn_script_location: bool = True,\n    direct_url: Optional[DirectUrl] = None,\n    requested: bool = False,\n) -> None:\n    \"\"\"Install a wheel.\n\n    :param name: Name of the project to install\n    :param wheel_zip: open ZipFile for wheel being installed\n    :param scheme: Distutils scheme dictating the install directories\n    :param req_description: String used in place of the requirement, for\n        logging\n    :param pycompile: Whether to byte-compile installed Python files\n    :param warn_script_location: Whether to check that scripts are installed\n        into a directory on PATH\n    :raises UnsupportedWheel:\n        * when the directory holds an unpacked wheel with incompatible\n          Wheel-Version\n        * when the .dist-info dir does not match the wheel\n    \"\"\"\n    info_dir, metadata = parse_wheel(wheel_zip, name)\n\n    if wheel_root_is_purelib(metadata):\n        lib_dir = scheme.purelib\n    else:\n        lib_dir = scheme.platlib\n\n    # Record details of the files moved\n    #   installed = files copied from the wheel to the destination\n    #   changed = files changed while installing (scripts #! line typically)\n    #   generated = files newly generated during the install (script wrappers)\n    installed: Dict[RecordPath, RecordPath] = {}\n    changed: Set[RecordPath] = set()\n    generated: List[str] = []\n\n    def record_installed(\n        srcfile: RecordPath, destfile: str, modified: bool = False\n    ) -> None:\n        \"\"\"Map archive RECORD paths to installation RECORD paths.\"\"\"\n        newpath = _fs_to_record_path(destfile, lib_dir)\n        installed[srcfile] = newpath\n        if modified:\n            changed.add(newpath)\n\n    def is_dir_path(path: RecordPath) -> bool:\n        return path.endswith(\"/\")\n\n    def assert_no_path_traversal(dest_dir_path: str, target_path: str) -> None:\n        if not is_within_directory(dest_dir_path, target_path):\n            message = (\n                \"The wheel {!r} has a file {!r} trying to install\"\n                \" outside the target directory {!r}\"\n            )\n            raise InstallationError(\n                message.format(wheel_path, target_path, dest_dir_path)\n            )\n\n    def root_scheme_file_maker(\n        zip_file: ZipFile, dest: str\n    ) -> Callable[[RecordPath], \"File\"]:\n        def make_root_scheme_file(record_path: RecordPath) -> \"File\":\n            normed_path = os.path.normpath(record_path)\n            dest_path = os.path.join(dest, normed_path)\n            assert_no_path_traversal(dest, dest_path)\n            return ZipBackedFile(record_path, dest_path, zip_file)\n\n        return make_root_scheme_file\n\n    def data_scheme_file_maker(\n        zip_file: ZipFile, scheme: Scheme\n    ) -> Callable[[RecordPath], \"File\"]:\n        scheme_paths = {key: getattr(scheme, key) for key in SCHEME_KEYS}\n\n        def make_data_scheme_file(record_path: RecordPath) -> \"File\":\n            normed_path = os.path.normpath(record_path)\n            try:\n                _, scheme_key, dest_subpath = normed_path.split(os.path.sep, 2)\n            except ValueError:\n                message = (\n                    \"Unexpected file in {}: {!r}. .data directory contents\"\n                    \" should be named like: '<scheme key>/<path>'.\"\n                ).format(wheel_path, record_path)\n                raise InstallationError(message)\n\n            try:\n                scheme_path = scheme_paths[scheme_key]\n            except KeyError:\n                valid_scheme_keys = \", \".join(sorted(scheme_paths))\n                message = (\n                    \"Unknown scheme key used in {}: {} (for file {!r}). .data\"\n                    \" directory contents should be in subdirectories named\"\n                    \" with a valid scheme key ({})\"\n                ).format(wheel_path, scheme_key, record_path, valid_scheme_keys)\n                raise InstallationError(message)\n\n            dest_path = os.path.join(scheme_path, dest_subpath)\n            assert_no_path_traversal(scheme_path, dest_path)\n            return ZipBackedFile(record_path, dest_path, zip_file)\n\n        return make_data_scheme_file\n\n    def is_data_scheme_path(path: RecordPath) -> bool:\n        return path.split(\"/\", 1)[0].endswith(\".data\")\n\n    paths = cast(List[RecordPath], wheel_zip.namelist())\n    file_paths = filterfalse(is_dir_path, paths)\n    root_scheme_paths, data_scheme_paths = partition(is_data_scheme_path, file_paths)\n\n    make_root_scheme_file = root_scheme_file_maker(wheel_zip, lib_dir)\n    files: Iterator[File] = map(make_root_scheme_file, root_scheme_paths)\n\n    def is_script_scheme_path(path: RecordPath) -> bool:\n        parts = path.split(\"/\", 2)\n        return len(parts) > 2 and parts[0].endswith(\".data\") and parts[1] == \"scripts\"\n\n    other_scheme_paths, script_scheme_paths = partition(\n        is_script_scheme_path, data_scheme_paths\n    )\n\n    make_data_scheme_file = data_scheme_file_maker(wheel_zip, scheme)\n    other_scheme_files = map(make_data_scheme_file, other_scheme_paths)\n    files = chain(files, other_scheme_files)\n\n    # Get the defined entry points\n    distribution = get_wheel_distribution(\n        FilesystemWheel(wheel_path),\n        canonicalize_name(name),\n    )\n    console, gui = get_entrypoints(distribution)\n\n    def is_entrypoint_wrapper(file: \"File\") -> bool:\n        # EP, EP.exe and EP-script.py are scripts generated for\n        # entry point EP by setuptools\n        path = file.dest_path\n        name = os.path.basename(path)\n        if name.lower().endswith(\".exe\"):\n            matchname = name[:-4]\n        elif name.lower().endswith(\"-script.py\"):\n            matchname = name[:-10]\n        elif name.lower().endswith(\".pya\"):\n            matchname = name[:-4]\n        else:\n            matchname = name\n        # Ignore setuptools-generated scripts\n        return matchname in console or matchname in gui\n\n    script_scheme_files: Iterator[File] = map(\n        make_data_scheme_file, script_scheme_paths\n    )\n    script_scheme_files = filterfalse(is_entrypoint_wrapper, script_scheme_files)\n    script_scheme_files = map(ScriptFile, script_scheme_files)\n    files = chain(files, script_scheme_files)\n\n    for file in files:\n        file.save()\n        record_installed(file.src_record_path, file.dest_path, file.changed)\n\n    def pyc_source_file_paths() -> Generator[str, None, None]:\n        # We de-duplicate installation paths, since there can be overlap (e.g.\n        # file in .data maps to same location as file in wheel root).\n        # Sorting installation paths makes it easier to reproduce and debug\n        # issues related to permissions on existing files.\n        for installed_path in sorted(set(installed.values())):\n            full_installed_path = os.path.join(lib_dir, installed_path)\n            if not os.path.isfile(full_installed_path):\n                continue\n            if not full_installed_path.endswith(\".py\"):\n                continue\n            yield full_installed_path\n\n    def pyc_output_path(path: str) -> str:\n        \"\"\"Return the path the pyc file would have been written to.\"\"\"\n        return importlib.util.cache_from_source(path)\n\n    # Compile all of the pyc files for the installed files\n    if pycompile:\n        with captured_stdout() as stdout:\n            with warnings.catch_warnings():\n                warnings.filterwarnings(\"ignore\")\n                for path in pyc_source_file_paths():\n                    success = compileall.compile_file(path, force=True, quiet=True)\n                    if success:\n                        pyc_path = pyc_output_path(path)\n                        assert os.path.exists(pyc_path)\n                        pyc_record_path = cast(\n                            \"RecordPath\", pyc_path.replace(os.path.sep, \"/\")\n                        )\n                        record_installed(pyc_record_path, pyc_path)\n        logger.debug(stdout.getvalue())\n\n    maker = PipScriptMaker(None, scheme.scripts)\n\n    # Ensure old scripts are overwritten.\n    # See https://github.com/pypa/pip/issues/1800\n    maker.clobber = True\n\n    # Ensure we don't generate any variants for scripts because this is almost\n    # never what somebody wants.\n    # See https://bitbucket.org/pypa/distlib/issue/35/\n    maker.variants = {\"\"}\n\n    # This is required because otherwise distlib creates scripts that are not\n    # executable.\n    # See https://bitbucket.org/pypa/distlib/issue/32/\n    maker.set_mode = True\n\n    # Generate the console and GUI entry points specified in the wheel\n    scripts_to_generate = get_console_script_specs(console)\n\n    gui_scripts_to_generate = list(starmap(\"{} = {}\".format, gui.items()))\n\n    generated_console_scripts = maker.make_multiple(scripts_to_generate)\n    generated.extend(generated_console_scripts)\n\n    generated.extend(maker.make_multiple(gui_scripts_to_generate, {\"gui\": True}))\n\n    if warn_script_location:\n        msg = message_about_scripts_not_on_PATH(generated_console_scripts)\n        if msg is not None:\n            logger.warning(msg)\n\n    generated_file_mode = 0o666 & ~current_umask()\n\n    @contextlib.contextmanager\n    def _generate_file(path: str, **kwargs: Any) -> Generator[BinaryIO, None, None]:\n        with adjacent_tmp_file(path, **kwargs) as f:\n            yield f\n        os.chmod(f.name, generated_file_mode)\n        replace(f.name, path)\n\n    dest_info_dir = os.path.join(lib_dir, info_dir)\n\n    # Record pip as the installer\n    installer_path = os.path.join(dest_info_dir, \"INSTALLER\")\n    with _generate_file(installer_path) as installer_file:\n        installer_file.write(b\"pip\\n\")\n    generated.append(installer_path)\n\n    # Record the PEP 610 direct URL reference\n    if direct_url is not None:\n        direct_url_path = os.path.join(dest_info_dir, DIRECT_URL_METADATA_NAME)\n        with _generate_file(direct_url_path) as direct_url_file:\n            direct_url_file.write(direct_url.to_json().encode(\"utf-8\"))\n        generated.append(direct_url_path)\n\n    # Record the REQUESTED file\n    if requested:\n        requested_path = os.path.join(dest_info_dir, \"REQUESTED\")\n        with open(requested_path, \"wb\"):\n            pass\n        generated.append(requested_path)\n\n    record_text = distribution.read_text(\"RECORD\")\n    record_rows = list(csv.reader(record_text.splitlines()))\n\n    rows = get_csv_rows_for_installed(\n        record_rows,\n        installed=installed,\n        changed=changed,\n        generated=generated,\n        lib_dir=lib_dir,\n    )\n\n    # Record details of all files installed\n    record_path = os.path.join(dest_info_dir, \"RECORD\")\n\n    with _generate_file(record_path, **csv_io_kwargs(\"w\")) as record_file:\n        # Explicitly cast to typing.IO[str] as a workaround for the mypy error:\n        # \"writer\" has incompatible type \"BinaryIO\"; expected \"_Writer\"\n        writer = csv.writer(cast(\"IO[str]\", record_file))\n        writer.writerows(_normalized_outrows(rows))\n\n\n@contextlib.contextmanager\ndef req_error_context(req_description: str) -> Generator[None, None, None]:\n    try:\n        yield\n    except InstallationError as e:\n        message = \"For req: {}. {}\".format(req_description, e.args[0])\n        raise InstallationError(message) from e\n\n\ndef install_wheel(\n    name: str,\n    wheel_path: str,\n    scheme: Scheme,\n    req_description: str,\n    pycompile: bool = True,\n    warn_script_location: bool = True,\n    direct_url: Optional[DirectUrl] = None,\n    requested: bool = False,\n) -> None:\n    with ZipFile(wheel_path, allowZip64=True) as z:\n        with req_error_context(req_description):\n            _install_wheel(\n                name=name,\n                wheel_zip=z,\n                wheel_path=wheel_path,\n                scheme=scheme,\n                pycompile=pycompile,\n                warn_script_location=warn_script_location,\n                direct_url=direct_url,\n                requested=requested,\n            )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/operations/prepare.py",
    "content": "\"\"\"Prepares a distribution for installation\n\"\"\"\n\n# The following comment should be removed at some point in the future.\n# mypy: strict-optional=False\n\nimport logging\nimport mimetypes\nimport os\nimport shutil\nfrom typing import Dict, Iterable, List, Optional\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.distributions import make_distribution_for_install_requirement\nfrom pip._internal.distributions.installed import InstalledDistribution\nfrom pip._internal.exceptions import (\n    DirectoryUrlHashUnsupported,\n    HashMismatch,\n    HashUnpinned,\n    InstallationError,\n    MetadataInconsistent,\n    NetworkConnectionError,\n    PreviousBuildDirError,\n    VcsHashUnsupported,\n)\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.metadata import BaseDistribution, get_metadata_distribution\nfrom pip._internal.models.direct_url import ArchiveInfo\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.network.download import BatchDownloader, Downloader\nfrom pip._internal.network.lazy_wheel import (\n    HTTPRangeRequestUnsupported,\n    dist_from_wheel_url,\n)\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.operations.build.build_tracker import BuildTracker\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.utils.direct_url_helpers import (\n    direct_url_for_editable,\n    direct_url_from_link,\n)\nfrom pip._internal.utils.hashes import Hashes, MissingHashes\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import (\n    display_path,\n    hash_file,\n    hide_url,\n    is_installable_dir,\n)\nfrom pip._internal.utils.temp_dir import TempDirectory\nfrom pip._internal.utils.unpacking import unpack_file\nfrom pip._internal.vcs import vcs\n\nlogger = logging.getLogger(__name__)\n\n\ndef _get_prepared_distribution(\n    req: InstallRequirement,\n    build_tracker: BuildTracker,\n    finder: PackageFinder,\n    build_isolation: bool,\n    check_build_deps: bool,\n) -> BaseDistribution:\n    \"\"\"Prepare a distribution for installation.\"\"\"\n    abstract_dist = make_distribution_for_install_requirement(req)\n    with build_tracker.track(req):\n        abstract_dist.prepare_distribution_metadata(\n            finder, build_isolation, check_build_deps\n        )\n    return abstract_dist.get_metadata_distribution()\n\n\ndef unpack_vcs_link(link: Link, location: str, verbosity: int) -> None:\n    vcs_backend = vcs.get_backend_for_scheme(link.scheme)\n    assert vcs_backend is not None\n    vcs_backend.unpack(location, url=hide_url(link.url), verbosity=verbosity)\n\n\nclass File:\n    def __init__(self, path: str, content_type: Optional[str]) -> None:\n        self.path = path\n        if content_type is None:\n            self.content_type = mimetypes.guess_type(path)[0]\n        else:\n            self.content_type = content_type\n\n\ndef get_http_url(\n    link: Link,\n    download: Downloader,\n    download_dir: Optional[str] = None,\n    hashes: Optional[Hashes] = None,\n) -> File:\n    temp_dir = TempDirectory(kind=\"unpack\", globally_managed=True)\n    # If a download dir is specified, is the file already downloaded there?\n    already_downloaded_path = None\n    if download_dir:\n        already_downloaded_path = _check_download_dir(link, download_dir, hashes)\n\n    if already_downloaded_path:\n        from_path = already_downloaded_path\n        content_type = None\n    else:\n        # let's download to a tmp dir\n        from_path, content_type = download(link, temp_dir.path)\n        if hashes:\n            hashes.check_against_path(from_path)\n\n    return File(from_path, content_type)\n\n\ndef get_file_url(\n    link: Link, download_dir: Optional[str] = None, hashes: Optional[Hashes] = None\n) -> File:\n    \"\"\"Get file and optionally check its hash.\"\"\"\n    # If a download dir is specified, is the file already there and valid?\n    already_downloaded_path = None\n    if download_dir:\n        already_downloaded_path = _check_download_dir(link, download_dir, hashes)\n\n    if already_downloaded_path:\n        from_path = already_downloaded_path\n    else:\n        from_path = link.file_path\n\n    # If --require-hashes is off, `hashes` is either empty, the\n    # link's embedded hash, or MissingHashes; it is required to\n    # match. If --require-hashes is on, we are satisfied by any\n    # hash in `hashes` matching: a URL-based or an option-based\n    # one; no internet-sourced hash will be in `hashes`.\n    if hashes:\n        hashes.check_against_path(from_path)\n    return File(from_path, None)\n\n\ndef unpack_url(\n    link: Link,\n    location: str,\n    download: Downloader,\n    verbosity: int,\n    download_dir: Optional[str] = None,\n    hashes: Optional[Hashes] = None,\n) -> Optional[File]:\n    \"\"\"Unpack link into location, downloading if required.\n\n    :param hashes: A Hashes object, one of whose embedded hashes must match,\n        or HashMismatch will be raised. If the Hashes is empty, no matches are\n        required, and unhashable types of requirements (like VCS ones, which\n        would ordinarily raise HashUnsupported) are allowed.\n    \"\"\"\n    # non-editable vcs urls\n    if link.is_vcs:\n        unpack_vcs_link(link, location, verbosity=verbosity)\n        return None\n\n    assert not link.is_existing_dir()\n\n    # file urls\n    if link.is_file:\n        file = get_file_url(link, download_dir, hashes=hashes)\n\n    # http urls\n    else:\n        file = get_http_url(\n            link,\n            download,\n            download_dir,\n            hashes=hashes,\n        )\n\n    # unpack the archive to the build dir location. even when only downloading\n    # archives, they have to be unpacked to parse dependencies, except wheels\n    if not link.is_wheel:\n        unpack_file(file.path, location, file.content_type)\n\n    return file\n\n\ndef _check_download_dir(\n    link: Link, download_dir: str, hashes: Optional[Hashes]\n) -> Optional[str]:\n    \"\"\"Check download_dir for previously downloaded file with correct hash\n    If a correct file is found return its path else None\n    \"\"\"\n    download_path = os.path.join(download_dir, link.filename)\n\n    if not os.path.exists(download_path):\n        return None\n\n    # If already downloaded, does its hash match?\n    logger.info(\"File was already downloaded %s\", download_path)\n    if hashes:\n        try:\n            hashes.check_against_path(download_path)\n        except HashMismatch:\n            logger.warning(\n                \"Previously-downloaded file %s has bad hash. Re-downloading.\",\n                download_path,\n            )\n            os.unlink(download_path)\n            return None\n    return download_path\n\n\nclass RequirementPreparer:\n    \"\"\"Prepares a Requirement\"\"\"\n\n    def __init__(\n        self,\n        build_dir: str,\n        download_dir: Optional[str],\n        src_dir: str,\n        build_isolation: bool,\n        check_build_deps: bool,\n        build_tracker: BuildTracker,\n        session: PipSession,\n        progress_bar: str,\n        finder: PackageFinder,\n        require_hashes: bool,\n        use_user_site: bool,\n        lazy_wheel: bool,\n        verbosity: int,\n    ) -> None:\n        super().__init__()\n\n        self.src_dir = src_dir\n        self.build_dir = build_dir\n        self.build_tracker = build_tracker\n        self._session = session\n        self._download = Downloader(session, progress_bar)\n        self._batch_download = BatchDownloader(session, progress_bar)\n        self.finder = finder\n\n        # Where still-packed archives should be written to. If None, they are\n        # not saved, and are deleted immediately after unpacking.\n        self.download_dir = download_dir\n\n        # Is build isolation allowed?\n        self.build_isolation = build_isolation\n\n        # Should check build dependencies?\n        self.check_build_deps = check_build_deps\n\n        # Should hash-checking be required?\n        self.require_hashes = require_hashes\n\n        # Should install in user site-packages?\n        self.use_user_site = use_user_site\n\n        # Should wheels be downloaded lazily?\n        self.use_lazy_wheel = lazy_wheel\n\n        # How verbose should underlying tooling be?\n        self.verbosity = verbosity\n\n        # Memoized downloaded files, as mapping of url: path.\n        self._downloaded: Dict[str, str] = {}\n\n        # Previous \"header\" printed for a link-based InstallRequirement\n        self._previous_requirement_header = (\"\", \"\")\n\n    def _log_preparing_link(self, req: InstallRequirement) -> None:\n        \"\"\"Provide context for the requirement being prepared.\"\"\"\n        if req.link.is_file and not req.original_link_is_in_wheel_cache:\n            message = \"Processing %s\"\n            information = str(display_path(req.link.file_path))\n        else:\n            message = \"Collecting %s\"\n            information = str(req.req or req)\n\n        if (message, information) != self._previous_requirement_header:\n            self._previous_requirement_header = (message, information)\n            logger.info(message, information)\n\n        if req.original_link_is_in_wheel_cache:\n            with indent_log():\n                logger.info(\"Using cached %s\", req.link.filename)\n\n    def _ensure_link_req_src_dir(\n        self, req: InstallRequirement, parallel_builds: bool\n    ) -> None:\n        \"\"\"Ensure source_dir of a linked InstallRequirement.\"\"\"\n        # Since source_dir is only set for editable requirements.\n        if req.link.is_wheel:\n            # We don't need to unpack wheels, so no need for a source\n            # directory.\n            return\n        assert req.source_dir is None\n        if req.link.is_existing_dir():\n            # build local directories in-tree\n            req.source_dir = req.link.file_path\n            return\n\n        # We always delete unpacked sdists after pip runs.\n        req.ensure_has_source_dir(\n            self.build_dir,\n            autodelete=True,\n            parallel_builds=parallel_builds,\n        )\n\n        # If a checkout exists, it's unwise to keep going.  version\n        # inconsistencies are logged later, but do not fail the\n        # installation.\n        # FIXME: this won't upgrade when there's an existing\n        # package unpacked in `req.source_dir`\n        # TODO: this check is now probably dead code\n        if is_installable_dir(req.source_dir):\n            raise PreviousBuildDirError(\n                \"pip can't proceed with requirements '{}' due to a\"\n                \"pre-existing build directory ({}). This is likely \"\n                \"due to a previous installation that failed . pip is \"\n                \"being responsible and not assuming it can delete this. \"\n                \"Please delete it and try again.\".format(req, req.source_dir)\n            )\n\n    def _get_linked_req_hashes(self, req: InstallRequirement) -> Hashes:\n        # By the time this is called, the requirement's link should have\n        # been checked so we can tell what kind of requirements req is\n        # and raise some more informative errors than otherwise.\n        # (For example, we can raise VcsHashUnsupported for a VCS URL\n        # rather than HashMissing.)\n        if not self.require_hashes:\n            return req.hashes(trust_internet=True)\n\n        # We could check these first 2 conditions inside unpack_url\n        # and save repetition of conditions, but then we would\n        # report less-useful error messages for unhashable\n        # requirements, complaining that there's no hash provided.\n        if req.link.is_vcs:\n            raise VcsHashUnsupported()\n        if req.link.is_existing_dir():\n            raise DirectoryUrlHashUnsupported()\n\n        # Unpinned packages are asking for trouble when a new version\n        # is uploaded.  This isn't a security check, but it saves users\n        # a surprising hash mismatch in the future.\n        # file:/// URLs aren't pinnable, so don't complain about them\n        # not being pinned.\n        if req.original_link is None and not req.is_pinned:\n            raise HashUnpinned()\n\n        # If known-good hashes are missing for this requirement,\n        # shim it with a facade object that will provoke hash\n        # computation and then raise a HashMissing exception\n        # showing the user what the hash should be.\n        return req.hashes(trust_internet=False) or MissingHashes()\n\n    def _fetch_metadata_only(\n        self,\n        req: InstallRequirement,\n    ) -> Optional[BaseDistribution]:\n        if self.require_hashes:\n            logger.debug(\n                \"Metadata-only fetching is not used as hash checking is required\",\n            )\n            return None\n        # Try PEP 658 metadata first, then fall back to lazy wheel if unavailable.\n        return self._fetch_metadata_using_link_data_attr(\n            req\n        ) or self._fetch_metadata_using_lazy_wheel(req.link)\n\n    def _fetch_metadata_using_link_data_attr(\n        self,\n        req: InstallRequirement,\n    ) -> Optional[BaseDistribution]:\n        \"\"\"Fetch metadata from the data-dist-info-metadata attribute, if possible.\"\"\"\n        # (1) Get the link to the metadata file, if provided by the backend.\n        metadata_link = req.link.metadata_link()\n        if metadata_link is None:\n            return None\n        assert req.req is not None\n        logger.info(\n            \"Obtaining dependency information for %s from %s\",\n            req.req,\n            metadata_link,\n        )\n        # (2) Download the contents of the METADATA file, separate from the dist itself.\n        metadata_file = get_http_url(\n            metadata_link,\n            self._download,\n            hashes=metadata_link.as_hashes(),\n        )\n        with open(metadata_file.path, \"rb\") as f:\n            metadata_contents = f.read()\n        # (3) Generate a dist just from those file contents.\n        metadata_dist = get_metadata_distribution(\n            metadata_contents,\n            req.link.filename,\n            req.req.name,\n        )\n        # (4) Ensure the Name: field from the METADATA file matches the name from the\n        #     install requirement.\n        #\n        #     NB: raw_name will fall back to the name from the install requirement if\n        #     the Name: field is not present, but it's noted in the raw_name docstring\n        #     that that should NEVER happen anyway.\n        if metadata_dist.raw_name != req.req.name:\n            raise MetadataInconsistent(\n                req, \"Name\", req.req.name, metadata_dist.raw_name\n            )\n        return metadata_dist\n\n    def _fetch_metadata_using_lazy_wheel(\n        self,\n        link: Link,\n    ) -> Optional[BaseDistribution]:\n        \"\"\"Fetch metadata using lazy wheel, if possible.\"\"\"\n        # --use-feature=fast-deps must be provided.\n        if not self.use_lazy_wheel:\n            return None\n        if link.is_file or not link.is_wheel:\n            logger.debug(\n                \"Lazy wheel is not used as %r does not point to a remote wheel\",\n                link,\n            )\n            return None\n\n        wheel = Wheel(link.filename)\n        name = canonicalize_name(wheel.name)\n        logger.info(\n            \"Obtaining dependency information from %s %s\",\n            name,\n            wheel.version,\n        )\n        url = link.url.split(\"#\", 1)[0]\n        try:\n            return dist_from_wheel_url(name, url, self._session)\n        except HTTPRangeRequestUnsupported:\n            logger.debug(\"%s does not support range requests\", url)\n            return None\n\n    def _complete_partial_requirements(\n        self,\n        partially_downloaded_reqs: Iterable[InstallRequirement],\n        parallel_builds: bool = False,\n    ) -> None:\n        \"\"\"Download any requirements which were only fetched by metadata.\"\"\"\n        # Download to a temporary directory. These will be copied over as\n        # needed for downstream 'download', 'wheel', and 'install' commands.\n        temp_dir = TempDirectory(kind=\"unpack\", globally_managed=True).path\n\n        # Map each link to the requirement that owns it. This allows us to set\n        # `req.local_file_path` on the appropriate requirement after passing\n        # all the links at once into BatchDownloader.\n        links_to_fully_download: Dict[Link, InstallRequirement] = {}\n        for req in partially_downloaded_reqs:\n            assert req.link\n            links_to_fully_download[req.link] = req\n\n        batch_download = self._batch_download(\n            links_to_fully_download.keys(),\n            temp_dir,\n        )\n        for link, (filepath, _) in batch_download:\n            logger.debug(\"Downloading link %s to %s\", link, filepath)\n            req = links_to_fully_download[link]\n            req.local_file_path = filepath\n\n        # This step is necessary to ensure all lazy wheels are processed\n        # successfully by the 'download', 'wheel', and 'install' commands.\n        for req in partially_downloaded_reqs:\n            self._prepare_linked_requirement(req, parallel_builds)\n\n    def prepare_linked_requirement(\n        self, req: InstallRequirement, parallel_builds: bool = False\n    ) -> BaseDistribution:\n        \"\"\"Prepare a requirement to be obtained from req.link.\"\"\"\n        assert req.link\n        self._log_preparing_link(req)\n        with indent_log():\n            # Check if the relevant file is already available\n            # in the download directory\n            file_path = None\n            if self.download_dir is not None and req.link.is_wheel:\n                hashes = self._get_linked_req_hashes(req)\n                file_path = _check_download_dir(req.link, self.download_dir, hashes)\n\n            if file_path is not None:\n                # The file is already available, so mark it as downloaded\n                self._downloaded[req.link.url] = file_path\n            else:\n                # The file is not available, attempt to fetch only metadata\n                metadata_dist = self._fetch_metadata_only(req)\n                if metadata_dist is not None:\n                    req.needs_more_preparation = True\n                    return metadata_dist\n\n            # None of the optimizations worked, fully prepare the requirement\n            return self._prepare_linked_requirement(req, parallel_builds)\n\n    def prepare_linked_requirements_more(\n        self, reqs: Iterable[InstallRequirement], parallel_builds: bool = False\n    ) -> None:\n        \"\"\"Prepare linked requirements more, if needed.\"\"\"\n        reqs = [req for req in reqs if req.needs_more_preparation]\n        for req in reqs:\n            # Determine if any of these requirements were already downloaded.\n            if self.download_dir is not None and req.link.is_wheel:\n                hashes = self._get_linked_req_hashes(req)\n                file_path = _check_download_dir(req.link, self.download_dir, hashes)\n                if file_path is not None:\n                    self._downloaded[req.link.url] = file_path\n                    req.needs_more_preparation = False\n\n        # Prepare requirements we found were already downloaded for some\n        # reason. The other downloads will be completed separately.\n        partially_downloaded_reqs: List[InstallRequirement] = []\n        for req in reqs:\n            if req.needs_more_preparation:\n                partially_downloaded_reqs.append(req)\n            else:\n                self._prepare_linked_requirement(req, parallel_builds)\n\n        # TODO: separate this part out from RequirementPreparer when the v1\n        # resolver can be removed!\n        self._complete_partial_requirements(\n            partially_downloaded_reqs,\n            parallel_builds=parallel_builds,\n        )\n\n    def _prepare_linked_requirement(\n        self, req: InstallRequirement, parallel_builds: bool\n    ) -> BaseDistribution:\n        assert req.link\n        link = req.link\n\n        self._ensure_link_req_src_dir(req, parallel_builds)\n        hashes = self._get_linked_req_hashes(req)\n\n        if link.is_existing_dir():\n            local_file = None\n        elif link.url not in self._downloaded:\n            try:\n                local_file = unpack_url(\n                    link,\n                    req.source_dir,\n                    self._download,\n                    self.verbosity,\n                    self.download_dir,\n                    hashes,\n                )\n            except NetworkConnectionError as exc:\n                raise InstallationError(\n                    \"Could not install requirement {} because of HTTP \"\n                    \"error {} for URL {}\".format(req, exc, link)\n                )\n        else:\n            file_path = self._downloaded[link.url]\n            if hashes:\n                hashes.check_against_path(file_path)\n            local_file = File(file_path, content_type=None)\n\n        # If download_info is set, we got it from the wheel cache.\n        if req.download_info is None:\n            # Editables don't go through this function (see\n            # prepare_editable_requirement).\n            assert not req.editable\n            req.download_info = direct_url_from_link(link, req.source_dir)\n            # Make sure we have a hash in download_info. If we got it as part of the\n            # URL, it will have been verified and we can rely on it. Otherwise we\n            # compute it from the downloaded file.\n            if (\n                isinstance(req.download_info.info, ArchiveInfo)\n                and not req.download_info.info.hash\n                and local_file\n            ):\n                hash = hash_file(local_file.path)[0].hexdigest()\n                req.download_info.info.hash = f\"sha256={hash}\"\n\n        # For use in later processing,\n        # preserve the file path on the requirement.\n        if local_file:\n            req.local_file_path = local_file.path\n\n        dist = _get_prepared_distribution(\n            req,\n            self.build_tracker,\n            self.finder,\n            self.build_isolation,\n            self.check_build_deps,\n        )\n        return dist\n\n    def save_linked_requirement(self, req: InstallRequirement) -> None:\n        assert self.download_dir is not None\n        assert req.link is not None\n        link = req.link\n        if link.is_vcs or (link.is_existing_dir() and req.editable):\n            # Make a .zip of the source_dir we already created.\n            req.archive(self.download_dir)\n            return\n\n        if link.is_existing_dir():\n            logger.debug(\n                \"Not copying link to destination directory \"\n                \"since it is a directory: %s\",\n                link,\n            )\n            return\n        if req.local_file_path is None:\n            # No distribution was downloaded for this requirement.\n            return\n\n        download_location = os.path.join(self.download_dir, link.filename)\n        if not os.path.exists(download_location):\n            shutil.copy(req.local_file_path, download_location)\n            download_path = display_path(download_location)\n            logger.info(\"Saved %s\", download_path)\n\n    def prepare_editable_requirement(\n        self,\n        req: InstallRequirement,\n    ) -> BaseDistribution:\n        \"\"\"Prepare an editable requirement.\"\"\"\n        assert req.editable, \"cannot prepare a non-editable req as editable\"\n\n        logger.info(\"Obtaining %s\", req)\n\n        with indent_log():\n            if self.require_hashes:\n                raise InstallationError(\n                    \"The editable requirement {} cannot be installed when \"\n                    \"requiring hashes, because there is no single file to \"\n                    \"hash.\".format(req)\n                )\n            req.ensure_has_source_dir(self.src_dir)\n            req.update_editable()\n            assert req.source_dir\n            req.download_info = direct_url_for_editable(req.unpacked_source_directory)\n\n            dist = _get_prepared_distribution(\n                req,\n                self.build_tracker,\n                self.finder,\n                self.build_isolation,\n                self.check_build_deps,\n            )\n\n            req.check_if_exists(self.use_user_site)\n\n        return dist\n\n    def prepare_installed_requirement(\n        self,\n        req: InstallRequirement,\n        skip_reason: str,\n    ) -> BaseDistribution:\n        \"\"\"Prepare an already-installed requirement.\"\"\"\n        assert req.satisfied_by, \"req should have been satisfied but isn't\"\n        assert skip_reason is not None, (\n            \"did not get skip reason skipped but req.satisfied_by \"\n            \"is set to {}\".format(req.satisfied_by)\n        )\n        logger.info(\n            \"Requirement %s: %s (%s)\", skip_reason, req, req.satisfied_by.version\n        )\n        with indent_log():\n            if self.require_hashes:\n                logger.debug(\n                    \"Since it is already installed, we are trusting this \"\n                    \"package without checking its hash. To ensure a \"\n                    \"completely repeatable environment, install into an \"\n                    \"empty virtualenv.\"\n                )\n            return InstalledDistribution(req).get_metadata_distribution()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/pyproject.py",
    "content": "import importlib.util\nimport os\nfrom collections import namedtuple\nfrom typing import Any, List, Optional\n\nfrom pip._vendor import tomli\nfrom pip._vendor.packaging.requirements import InvalidRequirement, Requirement\n\nfrom pip._internal.exceptions import (\n    InstallationError,\n    InvalidPyProjectBuildRequires,\n    MissingPyProjectBuildRequires,\n)\n\n\ndef _is_list_of_str(obj: Any) -> bool:\n    return isinstance(obj, list) and all(isinstance(item, str) for item in obj)\n\n\ndef make_pyproject_path(unpacked_source_directory: str) -> str:\n    return os.path.join(unpacked_source_directory, \"pyproject.toml\")\n\n\nBuildSystemDetails = namedtuple(\n    \"BuildSystemDetails\", [\"requires\", \"backend\", \"check\", \"backend_path\"]\n)\n\n\ndef load_pyproject_toml(\n    use_pep517: Optional[bool], pyproject_toml: str, setup_py: str, req_name: str\n) -> Optional[BuildSystemDetails]:\n    \"\"\"Load the pyproject.toml file.\n\n    Parameters:\n        use_pep517 - Has the user requested PEP 517 processing? None\n                     means the user hasn't explicitly specified.\n        pyproject_toml - Location of the project's pyproject.toml file\n        setup_py - Location of the project's setup.py file\n        req_name - The name of the requirement we're processing (for\n                   error reporting)\n\n    Returns:\n        None if we should use the legacy code path, otherwise a tuple\n        (\n            requirements from pyproject.toml,\n            name of PEP 517 backend,\n            requirements we should check are installed after setting\n                up the build environment\n            directory paths to import the backend from (backend-path),\n                relative to the project root.\n        )\n    \"\"\"\n    has_pyproject = os.path.isfile(pyproject_toml)\n    has_setup = os.path.isfile(setup_py)\n\n    if not has_pyproject and not has_setup:\n        raise InstallationError(\n            f\"{req_name} does not appear to be a Python project: \"\n            f\"neither 'setup.py' nor 'pyproject.toml' found.\"\n        )\n\n    if has_pyproject:\n        with open(pyproject_toml, encoding=\"utf-8\") as f:\n            pp_toml = tomli.loads(f.read())\n        build_system = pp_toml.get(\"build-system\")\n    else:\n        build_system = None\n\n    # The following cases must use PEP 517\n    # We check for use_pep517 being non-None and falsey because that means\n    # the user explicitly requested --no-use-pep517.  The value 0 as\n    # opposed to False can occur when the value is provided via an\n    # environment variable or config file option (due to the quirk of\n    # strtobool() returning an integer in pip's configuration code).\n    if has_pyproject and not has_setup:\n        if use_pep517 is not None and not use_pep517:\n            raise InstallationError(\n                \"Disabling PEP 517 processing is invalid: \"\n                \"project does not have a setup.py\"\n            )\n        use_pep517 = True\n    elif build_system and \"build-backend\" in build_system:\n        if use_pep517 is not None and not use_pep517:\n            raise InstallationError(\n                \"Disabling PEP 517 processing is invalid: \"\n                \"project specifies a build backend of {} \"\n                \"in pyproject.toml\".format(build_system[\"build-backend\"])\n            )\n        use_pep517 = True\n\n    # If we haven't worked out whether to use PEP 517 yet,\n    # and the user hasn't explicitly stated a preference,\n    # we do so if the project has a pyproject.toml file\n    # or if we cannot import setuptools.\n\n    # We fallback to PEP 517 when without setuptools,\n    # so setuptools can be installed as a default build backend.\n    # For more info see:\n    # https://discuss.python.org/t/pip-without-setuptools-could-the-experience-be-improved/11810/9\n    elif use_pep517 is None:\n        use_pep517 = has_pyproject or not importlib.util.find_spec(\"setuptools\")\n\n    # At this point, we know whether we're going to use PEP 517.\n    assert use_pep517 is not None\n\n    # If we're using the legacy code path, there is nothing further\n    # for us to do here.\n    if not use_pep517:\n        return None\n\n    if build_system is None:\n        # Either the user has a pyproject.toml with no build-system\n        # section, or the user has no pyproject.toml, but has opted in\n        # explicitly via --use-pep517.\n        # In the absence of any explicit backend specification, we\n        # assume the setuptools backend that most closely emulates the\n        # traditional direct setup.py execution, and require wheel and\n        # a version of setuptools that supports that backend.\n\n        build_system = {\n            \"requires\": [\"setuptools>=40.8.0\", \"wheel\"],\n            \"build-backend\": \"setuptools.build_meta:__legacy__\",\n        }\n\n    # If we're using PEP 517, we have build system information (either\n    # from pyproject.toml, or defaulted by the code above).\n    # Note that at this point, we do not know if the user has actually\n    # specified a backend, though.\n    assert build_system is not None\n\n    # Ensure that the build-system section in pyproject.toml conforms\n    # to PEP 518.\n\n    # Specifying the build-system table but not the requires key is invalid\n    if \"requires\" not in build_system:\n        raise MissingPyProjectBuildRequires(package=req_name)\n\n    # Error out if requires is not a list of strings\n    requires = build_system[\"requires\"]\n    if not _is_list_of_str(requires):\n        raise InvalidPyProjectBuildRequires(\n            package=req_name,\n            reason=\"It is not a list of strings.\",\n        )\n\n    # Each requirement must be valid as per PEP 508\n    for requirement in requires:\n        try:\n            Requirement(requirement)\n        except InvalidRequirement as error:\n            raise InvalidPyProjectBuildRequires(\n                package=req_name,\n                reason=f\"It contains an invalid requirement: {requirement!r}\",\n            ) from error\n\n    backend = build_system.get(\"build-backend\")\n    backend_path = build_system.get(\"backend-path\", [])\n    check: List[str] = []\n    if backend is None:\n        # If the user didn't specify a backend, we assume they want to use\n        # the setuptools backend. But we can't be sure they have included\n        # a version of setuptools which supplies the backend, or wheel\n        # (which is needed by the backend) in their requirements. So we\n        # make a note to check that those requirements are present once\n        # we have set up the environment.\n        # This is quite a lot of work to check for a very specific case. But\n        # the problem is, that case is potentially quite common - projects that\n        # adopted PEP 518 early for the ability to specify requirements to\n        # execute setup.py, but never considered needing to mention the build\n        # tools themselves. The original PEP 518 code had a similar check (but\n        # implemented in a different way).\n        backend = \"setuptools.build_meta:__legacy__\"\n        check = [\"setuptools>=40.8.0\", \"wheel\"]\n\n    return BuildSystemDetails(requires, backend, check, backend_path)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/req/__init__.py",
    "content": "import collections\nimport logging\nfrom typing import Generator, List, Optional, Sequence, Tuple\n\nfrom pip._internal.utils.logging import indent_log\n\nfrom .req_file import parse_requirements\nfrom .req_install import InstallRequirement\nfrom .req_set import RequirementSet\n\n__all__ = [\n    \"RequirementSet\",\n    \"InstallRequirement\",\n    \"parse_requirements\",\n    \"install_given_reqs\",\n]\n\nlogger = logging.getLogger(__name__)\n\n\nclass InstallationResult:\n    def __init__(self, name: str) -> None:\n        self.name = name\n\n    def __repr__(self) -> str:\n        return f\"InstallationResult(name={self.name!r})\"\n\n\ndef _validate_requirements(\n    requirements: List[InstallRequirement],\n) -> Generator[Tuple[str, InstallRequirement], None, None]:\n    for req in requirements:\n        assert req.name, f\"invalid to-be-installed requirement: {req}\"\n        yield req.name, req\n\n\ndef install_given_reqs(\n    requirements: List[InstallRequirement],\n    install_options: List[str],\n    global_options: Sequence[str],\n    root: Optional[str],\n    home: Optional[str],\n    prefix: Optional[str],\n    warn_script_location: bool,\n    use_user_site: bool,\n    pycompile: bool,\n) -> List[InstallationResult]:\n    \"\"\"\n    Install everything in the given list.\n\n    (to be called after having downloaded and unpacked the packages)\n    \"\"\"\n    to_install = collections.OrderedDict(_validate_requirements(requirements))\n\n    if to_install:\n        logger.info(\n            \"Installing collected packages: %s\",\n            \", \".join(to_install.keys()),\n        )\n\n    installed = []\n\n    with indent_log():\n        for req_name, requirement in to_install.items():\n            if requirement.should_reinstall:\n                logger.info(\"Attempting uninstall: %s\", req_name)\n                with indent_log():\n                    uninstalled_pathset = requirement.uninstall(auto_confirm=True)\n            else:\n                uninstalled_pathset = None\n\n            try:\n                requirement.install(\n                    install_options,\n                    global_options,\n                    root=root,\n                    home=home,\n                    prefix=prefix,\n                    warn_script_location=warn_script_location,\n                    use_user_site=use_user_site,\n                    pycompile=pycompile,\n                )\n            except Exception:\n                # if install did not succeed, rollback previous uninstall\n                if uninstalled_pathset and not requirement.install_succeeded:\n                    uninstalled_pathset.rollback()\n                raise\n            else:\n                if uninstalled_pathset and requirement.install_succeeded:\n                    uninstalled_pathset.commit()\n\n            installed.append(InstallationResult(req_name))\n\n    return installed\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/req/constructors.py",
    "content": "\"\"\"Backing implementation for InstallRequirement's various constructors\n\nThe idea here is that these formed a major chunk of InstallRequirement's size\nso, moving them and support code dedicated to them outside of that class\nhelps creates for better understandability for the rest of the code.\n\nThese are meant to be used elsewhere within pip to create instances of\nInstallRequirement.\n\"\"\"\n\nimport logging\nimport os\nimport re\nfrom typing import Any, Dict, Optional, Set, Tuple, Union\n\nfrom pip._vendor.packaging.markers import Marker\nfrom pip._vendor.packaging.requirements import InvalidRequirement, Requirement\nfrom pip._vendor.packaging.specifiers import Specifier\n\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.models.index import PyPI, TestPyPI\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.req.req_file import ParsedRequirement\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.utils.filetypes import is_archive_file\nfrom pip._internal.utils.misc import is_installable_dir\nfrom pip._internal.utils.packaging import get_requirement\nfrom pip._internal.utils.urls import path_to_url\nfrom pip._internal.vcs import is_url, vcs\n\n__all__ = [\n    \"install_req_from_editable\",\n    \"install_req_from_line\",\n    \"parse_editable\",\n]\n\nlogger = logging.getLogger(__name__)\noperators = Specifier._operators.keys()\n\n\ndef _strip_extras(path: str) -> Tuple[str, Optional[str]]:\n    m = re.match(r\"^(.+)(\\[[^\\]]+\\])$\", path)\n    extras = None\n    if m:\n        path_no_extras = m.group(1)\n        extras = m.group(2)\n    else:\n        path_no_extras = path\n\n    return path_no_extras, extras\n\n\ndef convert_extras(extras: Optional[str]) -> Set[str]:\n    if not extras:\n        return set()\n    return get_requirement(\"placeholder\" + extras.lower()).extras\n\n\ndef parse_editable(editable_req: str) -> Tuple[Optional[str], str, Set[str]]:\n    \"\"\"Parses an editable requirement into:\n        - a requirement name\n        - an URL\n        - extras\n        - editable options\n    Accepted requirements:\n        svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir\n        .[some_extra]\n    \"\"\"\n\n    url = editable_req\n\n    # If a file path is specified with extras, strip off the extras.\n    url_no_extras, extras = _strip_extras(url)\n\n    if os.path.isdir(url_no_extras):\n        # Treating it as code that has already been checked out\n        url_no_extras = path_to_url(url_no_extras)\n\n    if url_no_extras.lower().startswith(\"file:\"):\n        package_name = Link(url_no_extras).egg_fragment\n        if extras:\n            return (\n                package_name,\n                url_no_extras,\n                get_requirement(\"placeholder\" + extras.lower()).extras,\n            )\n        else:\n            return package_name, url_no_extras, set()\n\n    for version_control in vcs:\n        if url.lower().startswith(f\"{version_control}:\"):\n            url = f\"{version_control}+{url}\"\n            break\n\n    link = Link(url)\n\n    if not link.is_vcs:\n        backends = \", \".join(vcs.all_schemes)\n        raise InstallationError(\n            f\"{editable_req} is not a valid editable requirement. \"\n            f\"It should either be a path to a local project or a VCS URL \"\n            f\"(beginning with {backends}).\"\n        )\n\n    package_name = link.egg_fragment\n    if not package_name:\n        raise InstallationError(\n            \"Could not detect requirement name for '{}', please specify one \"\n            \"with #egg=your_package_name\".format(editable_req)\n        )\n    return package_name, url, set()\n\n\ndef check_first_requirement_in_file(filename: str) -> None:\n    \"\"\"Check if file is parsable as a requirements file.\n\n    This is heavily based on ``pkg_resources.parse_requirements``, but\n    simplified to just check the first meaningful line.\n\n    :raises InvalidRequirement: If the first meaningful line cannot be parsed\n        as an requirement.\n    \"\"\"\n    with open(filename, encoding=\"utf-8\", errors=\"ignore\") as f:\n        # Create a steppable iterator, so we can handle \\-continuations.\n        lines = (\n            line\n            for line in (line.strip() for line in f)\n            if line and not line.startswith(\"#\")  # Skip blank lines/comments.\n        )\n\n        for line in lines:\n            # Drop comments -- a hash without a space may be in a URL.\n            if \" #\" in line:\n                line = line[: line.find(\" #\")]\n            # If there is a line continuation, drop it, and append the next line.\n            if line.endswith(\"\\\\\"):\n                line = line[:-2].strip() + next(lines, \"\")\n            Requirement(line)\n            return\n\n\ndef deduce_helpful_msg(req: str) -> str:\n    \"\"\"Returns helpful msg in case requirements file does not exist,\n    or cannot be parsed.\n\n    :params req: Requirements file path\n    \"\"\"\n    if not os.path.exists(req):\n        return f\" File '{req}' does not exist.\"\n    msg = \" The path does exist. \"\n    # Try to parse and check if it is a requirements file.\n    try:\n        check_first_requirement_in_file(req)\n    except InvalidRequirement:\n        logger.debug(\"Cannot parse '%s' as requirements file\", req)\n    else:\n        msg += (\n            f\"The argument you provided \"\n            f\"({req}) appears to be a\"\n            f\" requirements file. If that is the\"\n            f\" case, use the '-r' flag to install\"\n            f\" the packages specified within it.\"\n        )\n    return msg\n\n\nclass RequirementParts:\n    def __init__(\n        self,\n        requirement: Optional[Requirement],\n        link: Optional[Link],\n        markers: Optional[Marker],\n        extras: Set[str],\n    ):\n        self.requirement = requirement\n        self.link = link\n        self.markers = markers\n        self.extras = extras\n\n\ndef parse_req_from_editable(editable_req: str) -> RequirementParts:\n    name, url, extras_override = parse_editable(editable_req)\n\n    if name is not None:\n        try:\n            req: Optional[Requirement] = Requirement(name)\n        except InvalidRequirement:\n            raise InstallationError(f\"Invalid requirement: '{name}'\")\n    else:\n        req = None\n\n    link = Link(url)\n\n    return RequirementParts(req, link, None, extras_override)\n\n\n# ---- The actual constructors follow ----\n\n\ndef install_req_from_editable(\n    editable_req: str,\n    comes_from: Optional[Union[InstallRequirement, str]] = None,\n    use_pep517: Optional[bool] = None,\n    isolated: bool = False,\n    options: Optional[Dict[str, Any]] = None,\n    constraint: bool = False,\n    user_supplied: bool = False,\n    permit_editable_wheels: bool = False,\n    config_settings: Optional[Dict[str, str]] = None,\n) -> InstallRequirement:\n\n    parts = parse_req_from_editable(editable_req)\n\n    return InstallRequirement(\n        parts.requirement,\n        comes_from=comes_from,\n        user_supplied=user_supplied,\n        editable=True,\n        permit_editable_wheels=permit_editable_wheels,\n        link=parts.link,\n        constraint=constraint,\n        use_pep517=use_pep517,\n        isolated=isolated,\n        install_options=options.get(\"install_options\", []) if options else [],\n        global_options=options.get(\"global_options\", []) if options else [],\n        hash_options=options.get(\"hashes\", {}) if options else {},\n        config_settings=config_settings,\n        extras=parts.extras,\n    )\n\n\ndef _looks_like_path(name: str) -> bool:\n    \"\"\"Checks whether the string \"looks like\" a path on the filesystem.\n\n    This does not check whether the target actually exists, only judge from the\n    appearance.\n\n    Returns true if any of the following conditions is true:\n    * a path separator is found (either os.path.sep or os.path.altsep);\n    * a dot is found (which represents the current directory).\n    \"\"\"\n    if os.path.sep in name:\n        return True\n    if os.path.altsep is not None and os.path.altsep in name:\n        return True\n    if name.startswith(\".\"):\n        return True\n    return False\n\n\ndef _get_url_from_path(path: str, name: str) -> Optional[str]:\n    \"\"\"\n    First, it checks whether a provided path is an installable directory. If it\n    is, returns the path.\n\n    If false, check if the path is an archive file (such as a .whl).\n    The function checks if the path is a file. If false, if the path has\n    an @, it will treat it as a PEP 440 URL requirement and return the path.\n    \"\"\"\n    if _looks_like_path(name) and os.path.isdir(path):\n        if is_installable_dir(path):\n            return path_to_url(path)\n        # TODO: The is_installable_dir test here might not be necessary\n        #       now that it is done in load_pyproject_toml too.\n        raise InstallationError(\n            f\"Directory {name!r} is not installable. Neither 'setup.py' \"\n            \"nor 'pyproject.toml' found.\"\n        )\n    if not is_archive_file(path):\n        return None\n    if os.path.isfile(path):\n        return path_to_url(path)\n    urlreq_parts = name.split(\"@\", 1)\n    if len(urlreq_parts) >= 2 and not _looks_like_path(urlreq_parts[0]):\n        # If the path contains '@' and the part before it does not look\n        # like a path, try to treat it as a PEP 440 URL req instead.\n        return None\n    logger.warning(\n        \"Requirement %r looks like a filename, but the file does not exist\",\n        name,\n    )\n    return path_to_url(path)\n\n\ndef parse_req_from_line(name: str, line_source: Optional[str]) -> RequirementParts:\n    if is_url(name):\n        marker_sep = \"; \"\n    else:\n        marker_sep = \";\"\n    if marker_sep in name:\n        name, markers_as_string = name.split(marker_sep, 1)\n        markers_as_string = markers_as_string.strip()\n        if not markers_as_string:\n            markers = None\n        else:\n            markers = Marker(markers_as_string)\n    else:\n        markers = None\n    name = name.strip()\n    req_as_string = None\n    path = os.path.normpath(os.path.abspath(name))\n    link = None\n    extras_as_string = None\n\n    if is_url(name):\n        link = Link(name)\n    else:\n        p, extras_as_string = _strip_extras(path)\n        url = _get_url_from_path(p, name)\n        if url is not None:\n            link = Link(url)\n\n    # it's a local file, dir, or url\n    if link:\n        # Handle relative file URLs\n        if link.scheme == \"file\" and re.search(r\"\\.\\./\", link.url):\n            link = Link(path_to_url(os.path.normpath(os.path.abspath(link.path))))\n        # wheel file\n        if link.is_wheel:\n            wheel = Wheel(link.filename)  # can raise InvalidWheelFilename\n            req_as_string = f\"{wheel.name}=={wheel.version}\"\n        else:\n            # set the req to the egg fragment.  when it's not there, this\n            # will become an 'unnamed' requirement\n            req_as_string = link.egg_fragment\n\n    # a requirement specifier\n    else:\n        req_as_string = name\n\n    extras = convert_extras(extras_as_string)\n\n    def with_source(text: str) -> str:\n        if not line_source:\n            return text\n        return f\"{text} (from {line_source})\"\n\n    def _parse_req_string(req_as_string: str) -> Requirement:\n        try:\n            req = get_requirement(req_as_string)\n        except InvalidRequirement:\n            if os.path.sep in req_as_string:\n                add_msg = \"It looks like a path.\"\n                add_msg += deduce_helpful_msg(req_as_string)\n            elif \"=\" in req_as_string and not any(\n                op in req_as_string for op in operators\n            ):\n                add_msg = \"= is not a valid operator. Did you mean == ?\"\n            else:\n                add_msg = \"\"\n            msg = with_source(f\"Invalid requirement: {req_as_string!r}\")\n            if add_msg:\n                msg += f\"\\nHint: {add_msg}\"\n            raise InstallationError(msg)\n        else:\n            # Deprecate extras after specifiers: \"name>=1.0[extras]\"\n            # This currently works by accident because _strip_extras() parses\n            # any extras in the end of the string and those are saved in\n            # RequirementParts\n            for spec in req.specifier:\n                spec_str = str(spec)\n                if spec_str.endswith(\"]\"):\n                    msg = f\"Extras after version '{spec_str}'.\"\n                    raise InstallationError(msg)\n        return req\n\n    if req_as_string is not None:\n        req: Optional[Requirement] = _parse_req_string(req_as_string)\n    else:\n        req = None\n\n    return RequirementParts(req, link, markers, extras)\n\n\ndef install_req_from_line(\n    name: str,\n    comes_from: Optional[Union[str, InstallRequirement]] = None,\n    use_pep517: Optional[bool] = None,\n    isolated: bool = False,\n    options: Optional[Dict[str, Any]] = None,\n    constraint: bool = False,\n    line_source: Optional[str] = None,\n    user_supplied: bool = False,\n    config_settings: Optional[Dict[str, str]] = None,\n) -> InstallRequirement:\n    \"\"\"Creates an InstallRequirement from a name, which might be a\n    requirement, directory containing 'setup.py', filename, or URL.\n\n    :param line_source: An optional string describing where the line is from,\n        for logging purposes in case of an error.\n    \"\"\"\n    parts = parse_req_from_line(name, line_source)\n\n    return InstallRequirement(\n        parts.requirement,\n        comes_from,\n        link=parts.link,\n        markers=parts.markers,\n        use_pep517=use_pep517,\n        isolated=isolated,\n        install_options=options.get(\"install_options\", []) if options else [],\n        global_options=options.get(\"global_options\", []) if options else [],\n        hash_options=options.get(\"hashes\", {}) if options else {},\n        config_settings=config_settings,\n        constraint=constraint,\n        extras=parts.extras,\n        user_supplied=user_supplied,\n    )\n\n\ndef install_req_from_req_string(\n    req_string: str,\n    comes_from: Optional[InstallRequirement] = None,\n    isolated: bool = False,\n    use_pep517: Optional[bool] = None,\n    user_supplied: bool = False,\n    config_settings: Optional[Dict[str, str]] = None,\n) -> InstallRequirement:\n    try:\n        req = get_requirement(req_string)\n    except InvalidRequirement:\n        raise InstallationError(f\"Invalid requirement: '{req_string}'\")\n\n    domains_not_allowed = [\n        PyPI.file_storage_domain,\n        TestPyPI.file_storage_domain,\n    ]\n    if (\n        req.url\n        and comes_from\n        and comes_from.link\n        and comes_from.link.netloc in domains_not_allowed\n    ):\n        # Explicitly disallow pypi packages that depend on external urls\n        raise InstallationError(\n            \"Packages installed from PyPI cannot depend on packages \"\n            \"which are not also hosted on PyPI.\\n\"\n            \"{} depends on {} \".format(comes_from.name, req)\n        )\n\n    return InstallRequirement(\n        req,\n        comes_from,\n        isolated=isolated,\n        use_pep517=use_pep517,\n        user_supplied=user_supplied,\n        config_settings=config_settings,\n    )\n\n\ndef install_req_from_parsed_requirement(\n    parsed_req: ParsedRequirement,\n    isolated: bool = False,\n    use_pep517: Optional[bool] = None,\n    user_supplied: bool = False,\n    config_settings: Optional[Dict[str, str]] = None,\n) -> InstallRequirement:\n    if parsed_req.is_editable:\n        req = install_req_from_editable(\n            parsed_req.requirement,\n            comes_from=parsed_req.comes_from,\n            use_pep517=use_pep517,\n            constraint=parsed_req.constraint,\n            isolated=isolated,\n            user_supplied=user_supplied,\n            config_settings=config_settings,\n        )\n\n    else:\n        req = install_req_from_line(\n            parsed_req.requirement,\n            comes_from=parsed_req.comes_from,\n            use_pep517=use_pep517,\n            isolated=isolated,\n            options=parsed_req.options,\n            constraint=parsed_req.constraint,\n            line_source=parsed_req.line_source,\n            user_supplied=user_supplied,\n            config_settings=config_settings,\n        )\n    return req\n\n\ndef install_req_from_link_and_ireq(\n    link: Link, ireq: InstallRequirement\n) -> InstallRequirement:\n    return InstallRequirement(\n        req=ireq.req,\n        comes_from=ireq.comes_from,\n        editable=ireq.editable,\n        link=link,\n        markers=ireq.markers,\n        use_pep517=ireq.use_pep517,\n        isolated=ireq.isolated,\n        install_options=ireq.install_options,\n        global_options=ireq.global_options,\n        hash_options=ireq.hash_options,\n        config_settings=ireq.config_settings,\n        user_supplied=ireq.user_supplied,\n    )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/req/req_file.py",
    "content": "\"\"\"\nRequirements file parsing\n\"\"\"\n\nimport optparse\nimport os\nimport re\nimport shlex\nimport urllib.parse\nfrom optparse import Values\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Generator,\n    Iterable,\n    List,\n    Optional,\n    Tuple,\n)\n\nfrom pip._internal.cli import cmdoptions\nfrom pip._internal.exceptions import InstallationError, RequirementsFileParseError\nfrom pip._internal.models.search_scope import SearchScope\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.network.utils import raise_for_status\nfrom pip._internal.utils.encoding import auto_decode\nfrom pip._internal.utils.urls import get_url_scheme\n\nif TYPE_CHECKING:\n    # NoReturn introduced in 3.6.2; imported only for type checking to maintain\n    # pip compatibility with older patch versions of Python 3.6\n    from typing import NoReturn\n\n    from pip._internal.index.package_finder import PackageFinder\n\n__all__ = [\"parse_requirements\"]\n\nReqFileLines = Iterable[Tuple[int, str]]\n\nLineParser = Callable[[str], Tuple[str, Values]]\n\nSCHEME_RE = re.compile(r\"^(http|https|file):\", re.I)\nCOMMENT_RE = re.compile(r\"(^|\\s+)#.*$\")\n\n# Matches environment variable-style values in '${MY_VARIABLE_1}' with the\n# variable name consisting of only uppercase letters, digits or the '_'\n# (underscore). This follows the POSIX standard defined in IEEE Std 1003.1,\n# 2013 Edition.\nENV_VAR_RE = re.compile(r\"(?P<var>\\$\\{(?P<name>[A-Z0-9_]+)\\})\")\n\nSUPPORTED_OPTIONS: List[Callable[..., optparse.Option]] = [\n    cmdoptions.index_url,\n    cmdoptions.extra_index_url,\n    cmdoptions.no_index,\n    cmdoptions.constraints,\n    cmdoptions.requirements,\n    cmdoptions.editable,\n    cmdoptions.find_links,\n    cmdoptions.no_binary,\n    cmdoptions.only_binary,\n    cmdoptions.prefer_binary,\n    cmdoptions.require_hashes,\n    cmdoptions.pre,\n    cmdoptions.trusted_host,\n    cmdoptions.use_new_feature,\n]\n\n# options to be passed to requirements\nSUPPORTED_OPTIONS_REQ: List[Callable[..., optparse.Option]] = [\n    cmdoptions.install_options,\n    cmdoptions.global_options,\n    cmdoptions.hash,\n]\n\n# the 'dest' string values\nSUPPORTED_OPTIONS_REQ_DEST = [str(o().dest) for o in SUPPORTED_OPTIONS_REQ]\n\n\nclass ParsedRequirement:\n    def __init__(\n        self,\n        requirement: str,\n        is_editable: bool,\n        comes_from: str,\n        constraint: bool,\n        options: Optional[Dict[str, Any]] = None,\n        line_source: Optional[str] = None,\n    ) -> None:\n        self.requirement = requirement\n        self.is_editable = is_editable\n        self.comes_from = comes_from\n        self.options = options\n        self.constraint = constraint\n        self.line_source = line_source\n\n\nclass ParsedLine:\n    def __init__(\n        self,\n        filename: str,\n        lineno: int,\n        args: str,\n        opts: Values,\n        constraint: bool,\n    ) -> None:\n        self.filename = filename\n        self.lineno = lineno\n        self.opts = opts\n        self.constraint = constraint\n\n        if args:\n            self.is_requirement = True\n            self.is_editable = False\n            self.requirement = args\n        elif opts.editables:\n            self.is_requirement = True\n            self.is_editable = True\n            # We don't support multiple -e on one line\n            self.requirement = opts.editables[0]\n        else:\n            self.is_requirement = False\n\n\ndef parse_requirements(\n    filename: str,\n    session: PipSession,\n    finder: Optional[\"PackageFinder\"] = None,\n    options: Optional[optparse.Values] = None,\n    constraint: bool = False,\n) -> Generator[ParsedRequirement, None, None]:\n    \"\"\"Parse a requirements file and yield ParsedRequirement instances.\n\n    :param filename:    Path or url of requirements file.\n    :param session:     PipSession instance.\n    :param finder:      Instance of pip.index.PackageFinder.\n    :param options:     cli options.\n    :param constraint:  If true, parsing a constraint file rather than\n        requirements file.\n    \"\"\"\n    line_parser = get_line_parser(finder)\n    parser = RequirementsFileParser(session, line_parser)\n\n    for parsed_line in parser.parse(filename, constraint):\n        parsed_req = handle_line(\n            parsed_line, options=options, finder=finder, session=session\n        )\n        if parsed_req is not None:\n            yield parsed_req\n\n\ndef preprocess(content: str) -> ReqFileLines:\n    \"\"\"Split, filter, and join lines, and return a line iterator\n\n    :param content: the content of the requirements file\n    \"\"\"\n    lines_enum: ReqFileLines = enumerate(content.splitlines(), start=1)\n    lines_enum = join_lines(lines_enum)\n    lines_enum = ignore_comments(lines_enum)\n    lines_enum = expand_env_variables(lines_enum)\n    return lines_enum\n\n\ndef handle_requirement_line(\n    line: ParsedLine,\n    options: Optional[optparse.Values] = None,\n) -> ParsedRequirement:\n\n    # preserve for the nested code path\n    line_comes_from = \"{} {} (line {})\".format(\n        \"-c\" if line.constraint else \"-r\",\n        line.filename,\n        line.lineno,\n    )\n\n    assert line.is_requirement\n\n    if line.is_editable:\n        # For editable requirements, we don't support per-requirement\n        # options, so just return the parsed requirement.\n        return ParsedRequirement(\n            requirement=line.requirement,\n            is_editable=line.is_editable,\n            comes_from=line_comes_from,\n            constraint=line.constraint,\n        )\n    else:\n        # get the options that apply to requirements\n        req_options = {}\n        for dest in SUPPORTED_OPTIONS_REQ_DEST:\n            if dest in line.opts.__dict__ and line.opts.__dict__[dest]:\n                req_options[dest] = line.opts.__dict__[dest]\n\n        line_source = f\"line {line.lineno} of {line.filename}\"\n        return ParsedRequirement(\n            requirement=line.requirement,\n            is_editable=line.is_editable,\n            comes_from=line_comes_from,\n            constraint=line.constraint,\n            options=req_options,\n            line_source=line_source,\n        )\n\n\ndef handle_option_line(\n    opts: Values,\n    filename: str,\n    lineno: int,\n    finder: Optional[\"PackageFinder\"] = None,\n    options: Optional[optparse.Values] = None,\n    session: Optional[PipSession] = None,\n) -> None:\n\n    if options:\n        # percolate options upward\n        if opts.require_hashes:\n            options.require_hashes = opts.require_hashes\n        if opts.features_enabled:\n            options.features_enabled.extend(\n                f for f in opts.features_enabled if f not in options.features_enabled\n            )\n\n    # set finder options\n    if finder:\n        find_links = finder.find_links\n        index_urls = finder.index_urls\n        no_index = finder.search_scope.no_index\n        if opts.no_index is True:\n            no_index = True\n            index_urls = []\n        if opts.index_url and not no_index:\n            index_urls = [opts.index_url]\n        if opts.extra_index_urls and not no_index:\n            index_urls.extend(opts.extra_index_urls)\n        if opts.find_links:\n            # FIXME: it would be nice to keep track of the source\n            # of the find_links: support a find-links local path\n            # relative to a requirements file.\n            value = opts.find_links[0]\n            req_dir = os.path.dirname(os.path.abspath(filename))\n            relative_to_reqs_file = os.path.join(req_dir, value)\n            if os.path.exists(relative_to_reqs_file):\n                value = relative_to_reqs_file\n            find_links.append(value)\n\n        if session:\n            # We need to update the auth urls in session\n            session.update_index_urls(index_urls)\n\n        search_scope = SearchScope(\n            find_links=find_links,\n            index_urls=index_urls,\n            no_index=no_index,\n        )\n        finder.search_scope = search_scope\n\n        if opts.pre:\n            finder.set_allow_all_prereleases()\n\n        if opts.prefer_binary:\n            finder.set_prefer_binary()\n\n        if session:\n            for host in opts.trusted_hosts or []:\n                source = f\"line {lineno} of {filename}\"\n                session.add_trusted_host(host, source=source)\n\n\ndef handle_line(\n    line: ParsedLine,\n    options: Optional[optparse.Values] = None,\n    finder: Optional[\"PackageFinder\"] = None,\n    session: Optional[PipSession] = None,\n) -> Optional[ParsedRequirement]:\n    \"\"\"Handle a single parsed requirements line; This can result in\n    creating/yielding requirements, or updating the finder.\n\n    :param line:        The parsed line to be processed.\n    :param options:     CLI options.\n    :param finder:      The finder - updated by non-requirement lines.\n    :param session:     The session - updated by non-requirement lines.\n\n    Returns a ParsedRequirement object if the line is a requirement line,\n    otherwise returns None.\n\n    For lines that contain requirements, the only options that have an effect\n    are from SUPPORTED_OPTIONS_REQ, and they are scoped to the\n    requirement. Other options from SUPPORTED_OPTIONS may be present, but are\n    ignored.\n\n    For lines that do not contain requirements, the only options that have an\n    effect are from SUPPORTED_OPTIONS. Options from SUPPORTED_OPTIONS_REQ may\n    be present, but are ignored. These lines may contain multiple options\n    (although our docs imply only one is supported), and all our parsed and\n    affect the finder.\n    \"\"\"\n\n    if line.is_requirement:\n        parsed_req = handle_requirement_line(line, options)\n        return parsed_req\n    else:\n        handle_option_line(\n            line.opts,\n            line.filename,\n            line.lineno,\n            finder,\n            options,\n            session,\n        )\n        return None\n\n\nclass RequirementsFileParser:\n    def __init__(\n        self,\n        session: PipSession,\n        line_parser: LineParser,\n    ) -> None:\n        self._session = session\n        self._line_parser = line_parser\n\n    def parse(\n        self, filename: str, constraint: bool\n    ) -> Generator[ParsedLine, None, None]:\n        \"\"\"Parse a given file, yielding parsed lines.\"\"\"\n        yield from self._parse_and_recurse(filename, constraint)\n\n    def _parse_and_recurse(\n        self, filename: str, constraint: bool\n    ) -> Generator[ParsedLine, None, None]:\n        for line in self._parse_file(filename, constraint):\n            if not line.is_requirement and (\n                line.opts.requirements or line.opts.constraints\n            ):\n                # parse a nested requirements file\n                if line.opts.requirements:\n                    req_path = line.opts.requirements[0]\n                    nested_constraint = False\n                else:\n                    req_path = line.opts.constraints[0]\n                    nested_constraint = True\n\n                # original file is over http\n                if SCHEME_RE.search(filename):\n                    # do a url join so relative paths work\n                    req_path = urllib.parse.urljoin(filename, req_path)\n                # original file and nested file are paths\n                elif not SCHEME_RE.search(req_path):\n                    # do a join so relative paths work\n                    req_path = os.path.join(\n                        os.path.dirname(filename),\n                        req_path,\n                    )\n\n                yield from self._parse_and_recurse(req_path, nested_constraint)\n            else:\n                yield line\n\n    def _parse_file(\n        self, filename: str, constraint: bool\n    ) -> Generator[ParsedLine, None, None]:\n        _, content = get_file_content(filename, self._session)\n\n        lines_enum = preprocess(content)\n\n        for line_number, line in lines_enum:\n            try:\n                args_str, opts = self._line_parser(line)\n            except OptionParsingError as e:\n                # add offending line\n                msg = f\"Invalid requirement: {line}\\n{e.msg}\"\n                raise RequirementsFileParseError(msg)\n\n            yield ParsedLine(\n                filename,\n                line_number,\n                args_str,\n                opts,\n                constraint,\n            )\n\n\ndef get_line_parser(finder: Optional[\"PackageFinder\"]) -> LineParser:\n    def parse_line(line: str) -> Tuple[str, Values]:\n        # Build new parser for each line since it accumulates appendable\n        # options.\n        parser = build_parser()\n        defaults = parser.get_default_values()\n        defaults.index_url = None\n        if finder:\n            defaults.format_control = finder.format_control\n\n        args_str, options_str = break_args_options(line)\n\n        try:\n            options = shlex.split(options_str)\n        except ValueError as e:\n            raise OptionParsingError(f\"Could not split options: {options_str}\") from e\n\n        opts, _ = parser.parse_args(options, defaults)\n\n        return args_str, opts\n\n    return parse_line\n\n\ndef break_args_options(line: str) -> Tuple[str, str]:\n    \"\"\"Break up the line into an args and options string.  We only want to shlex\n    (and then optparse) the options, not the args.  args can contain markers\n    which are corrupted by shlex.\n    \"\"\"\n    tokens = line.split(\" \")\n    args = []\n    options = tokens[:]\n    for token in tokens:\n        if token.startswith(\"-\") or token.startswith(\"--\"):\n            break\n        else:\n            args.append(token)\n            options.pop(0)\n    return \" \".join(args), \" \".join(options)\n\n\nclass OptionParsingError(Exception):\n    def __init__(self, msg: str) -> None:\n        self.msg = msg\n\n\ndef build_parser() -> optparse.OptionParser:\n    \"\"\"\n    Return a parser for parsing requirement lines\n    \"\"\"\n    parser = optparse.OptionParser(add_help_option=False)\n\n    option_factories = SUPPORTED_OPTIONS + SUPPORTED_OPTIONS_REQ\n    for option_factory in option_factories:\n        option = option_factory()\n        parser.add_option(option)\n\n    # By default optparse sys.exits on parsing errors. We want to wrap\n    # that in our own exception.\n    def parser_exit(self: Any, msg: str) -> \"NoReturn\":\n        raise OptionParsingError(msg)\n\n    # NOTE: mypy disallows assigning to a method\n    #       https://github.com/python/mypy/issues/2427\n    parser.exit = parser_exit  # type: ignore\n\n    return parser\n\n\ndef join_lines(lines_enum: ReqFileLines) -> ReqFileLines:\n    \"\"\"Joins a line ending in '\\' with the previous line (except when following\n    comments).  The joined line takes on the index of the first line.\n    \"\"\"\n    primary_line_number = None\n    new_line: List[str] = []\n    for line_number, line in lines_enum:\n        if not line.endswith(\"\\\\\") or COMMENT_RE.match(line):\n            if COMMENT_RE.match(line):\n                # this ensures comments are always matched later\n                line = \" \" + line\n            if new_line:\n                new_line.append(line)\n                assert primary_line_number is not None\n                yield primary_line_number, \"\".join(new_line)\n                new_line = []\n            else:\n                yield line_number, line\n        else:\n            if not new_line:\n                primary_line_number = line_number\n            new_line.append(line.strip(\"\\\\\"))\n\n    # last line contains \\\n    if new_line:\n        assert primary_line_number is not None\n        yield primary_line_number, \"\".join(new_line)\n\n    # TODO: handle space after '\\'.\n\n\ndef ignore_comments(lines_enum: ReqFileLines) -> ReqFileLines:\n    \"\"\"\n    Strips comments and filter empty lines.\n    \"\"\"\n    for line_number, line in lines_enum:\n        line = COMMENT_RE.sub(\"\", line)\n        line = line.strip()\n        if line:\n            yield line_number, line\n\n\ndef expand_env_variables(lines_enum: ReqFileLines) -> ReqFileLines:\n    \"\"\"Replace all environment variables that can be retrieved via `os.getenv`.\n\n    The only allowed format for environment variables defined in the\n    requirement file is `${MY_VARIABLE_1}` to ensure two things:\n\n    1. Strings that contain a `$` aren't accidentally (partially) expanded.\n    2. Ensure consistency across platforms for requirement files.\n\n    These points are the result of a discussion on the `github pull\n    request #3514 <https://github.com/pypa/pip/pull/3514>`_.\n\n    Valid characters in variable names follow the `POSIX standard\n    <http://pubs.opengroup.org/onlinepubs/9699919799/>`_ and are limited\n    to uppercase letter, digits and the `_` (underscore).\n    \"\"\"\n    for line_number, line in lines_enum:\n        for env_var, var_name in ENV_VAR_RE.findall(line):\n            value = os.getenv(var_name)\n            if not value:\n                continue\n\n            line = line.replace(env_var, value)\n\n        yield line_number, line\n\n\ndef get_file_content(url: str, session: PipSession) -> Tuple[str, str]:\n    \"\"\"Gets the content of a file; it may be a filename, file: URL, or\n    http: URL.  Returns (location, content).  Content is unicode.\n    Respects # -*- coding: declarations on the retrieved files.\n\n    :param url:         File path or url.\n    :param session:     PipSession instance.\n    \"\"\"\n    scheme = get_url_scheme(url)\n\n    # Pip has special support for file:// URLs (LocalFSAdapter).\n    if scheme in [\"http\", \"https\", \"file\"]:\n        resp = session.get(url)\n        raise_for_status(resp)\n        return resp.url, resp.text\n\n    # Assume this is a bare path.\n    try:\n        with open(url, \"rb\") as f:\n            content = auto_decode(f.read())\n    except OSError as exc:\n        raise InstallationError(f\"Could not open requirements file: {exc}\")\n    return url, content\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/req/req_install.py",
    "content": "# The following comment should be removed at some point in the future.\n# mypy: strict-optional=False\n\nimport functools\nimport logging\nimport os\nimport shutil\nimport sys\nimport uuid\nimport zipfile\nfrom enum import Enum\nfrom optparse import Values\nfrom typing import Any, Collection, Dict, Iterable, List, Optional, Sequence, Union\n\nfrom pip._vendor.packaging.markers import Marker\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.specifiers import SpecifierSet\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.packaging.version import Version\nfrom pip._vendor.packaging.version import parse as parse_version\nfrom pip._vendor.pep517.wrappers import Pep517HookCaller\n\nfrom pip._internal.build_env import BuildEnvironment, NoOpBuildEnvironment\nfrom pip._internal.exceptions import InstallationError, LegacyInstallFailure\nfrom pip._internal.locations import get_scheme\nfrom pip._internal.metadata import (\n    BaseDistribution,\n    get_default_environment,\n    get_directory_distribution,\n    get_wheel_distribution,\n)\nfrom pip._internal.metadata.base import FilesystemWheel\nfrom pip._internal.models.direct_url import DirectUrl\nfrom pip._internal.models.link import Link\nfrom pip._internal.operations.build.metadata import generate_metadata\nfrom pip._internal.operations.build.metadata_editable import generate_editable_metadata\nfrom pip._internal.operations.build.metadata_legacy import (\n    generate_metadata as generate_metadata_legacy,\n)\nfrom pip._internal.operations.install.editable_legacy import (\n    install_editable as install_editable_legacy,\n)\nfrom pip._internal.operations.install.legacy import install as install_legacy\nfrom pip._internal.operations.install.wheel import install_wheel\nfrom pip._internal.pyproject import load_pyproject_toml, make_pyproject_path\nfrom pip._internal.req.req_uninstall import UninstallPathSet\nfrom pip._internal.utils.deprecation import LegacyInstallReason, deprecated\nfrom pip._internal.utils.direct_url_helpers import (\n    direct_url_for_editable,\n    direct_url_from_link,\n)\nfrom pip._internal.utils.hashes import Hashes\nfrom pip._internal.utils.misc import (\n    ConfiguredPep517HookCaller,\n    ask_path_exists,\n    backup_dir,\n    display_path,\n    hide_url,\n    redact_auth_from_url,\n)\nfrom pip._internal.utils.packaging import safe_extra\nfrom pip._internal.utils.subprocess import runner_with_spinner_message\nfrom pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\nfrom pip._internal.vcs import vcs\n\nlogger = logging.getLogger(__name__)\n\n\nclass InstallRequirement:\n    \"\"\"\n    Represents something that may be installed later on, may have information\n    about where to fetch the relevant requirement and also contains logic for\n    installing the said requirement.\n    \"\"\"\n\n    def __init__(\n        self,\n        req: Optional[Requirement],\n        comes_from: Optional[Union[str, \"InstallRequirement\"]],\n        editable: bool = False,\n        link: Optional[Link] = None,\n        markers: Optional[Marker] = None,\n        use_pep517: Optional[bool] = None,\n        isolated: bool = False,\n        install_options: Optional[List[str]] = None,\n        global_options: Optional[List[str]] = None,\n        hash_options: Optional[Dict[str, List[str]]] = None,\n        config_settings: Optional[Dict[str, str]] = None,\n        constraint: bool = False,\n        extras: Collection[str] = (),\n        user_supplied: bool = False,\n        permit_editable_wheels: bool = False,\n    ) -> None:\n        assert req is None or isinstance(req, Requirement), req\n        self.req = req\n        self.comes_from = comes_from\n        self.constraint = constraint\n        self.editable = editable\n        self.permit_editable_wheels = permit_editable_wheels\n        self.legacy_install_reason: Optional[LegacyInstallReason] = None\n\n        # source_dir is the local directory where the linked requirement is\n        # located, or unpacked. In case unpacking is needed, creating and\n        # populating source_dir is done by the RequirementPreparer. Note this\n        # is not necessarily the directory where pyproject.toml or setup.py is\n        # located - that one is obtained via unpacked_source_directory.\n        self.source_dir: Optional[str] = None\n        if self.editable:\n            assert link\n            if link.is_file:\n                self.source_dir = os.path.normpath(os.path.abspath(link.file_path))\n\n        if link is None and req and req.url:\n            # PEP 508 URL requirement\n            link = Link(req.url)\n        self.link = self.original_link = link\n        self.original_link_is_in_wheel_cache = False\n\n        # Information about the location of the artifact that was downloaded . This\n        # property is guaranteed to be set in resolver results.\n        self.download_info: Optional[DirectUrl] = None\n\n        # Path to any downloaded or already-existing package.\n        self.local_file_path: Optional[str] = None\n        if self.link and self.link.is_file:\n            self.local_file_path = self.link.file_path\n\n        if extras:\n            self.extras = extras\n        elif req:\n            self.extras = {safe_extra(extra) for extra in req.extras}\n        else:\n            self.extras = set()\n        if markers is None and req:\n            markers = req.marker\n        self.markers = markers\n\n        # This holds the Distribution object if this requirement is already installed.\n        self.satisfied_by: Optional[BaseDistribution] = None\n        # Whether the installation process should try to uninstall an existing\n        # distribution before installing this requirement.\n        self.should_reinstall = False\n        # Temporary build location\n        self._temp_build_dir: Optional[TempDirectory] = None\n        # Set to True after successful installation\n        self.install_succeeded: Optional[bool] = None\n        # Supplied options\n        self.install_options = install_options if install_options else []\n        self.global_options = global_options if global_options else []\n        self.hash_options = hash_options if hash_options else {}\n        self.config_settings = config_settings\n        # Set to True after successful preparation of this requirement\n        self.prepared = False\n        # User supplied requirement are explicitly requested for installation\n        # by the user via CLI arguments or requirements files, as opposed to,\n        # e.g. dependencies, extras or constraints.\n        self.user_supplied = user_supplied\n\n        self.isolated = isolated\n        self.build_env: BuildEnvironment = NoOpBuildEnvironment()\n\n        # For PEP 517, the directory where we request the project metadata\n        # gets stored. We need this to pass to build_wheel, so the backend\n        # can ensure that the wheel matches the metadata (see the PEP for\n        # details).\n        self.metadata_directory: Optional[str] = None\n\n        # The static build requirements (from pyproject.toml)\n        self.pyproject_requires: Optional[List[str]] = None\n\n        # Build requirements that we will check are available\n        self.requirements_to_check: List[str] = []\n\n        # The PEP 517 backend we should use to build the project\n        self.pep517_backend: Optional[Pep517HookCaller] = None\n\n        # Are we using PEP 517 for this requirement?\n        # After pyproject.toml has been loaded, the only valid values are True\n        # and False. Before loading, None is valid (meaning \"use the default\").\n        # Setting an explicit value before loading pyproject.toml is supported,\n        # but after loading this flag should be treated as read only.\n        self.use_pep517 = use_pep517\n\n        # This requirement needs more preparation before it can be built\n        self.needs_more_preparation = False\n\n    def __str__(self) -> str:\n        if self.req:\n            s = str(self.req)\n            if self.link:\n                s += \" from {}\".format(redact_auth_from_url(self.link.url))\n        elif self.link:\n            s = redact_auth_from_url(self.link.url)\n        else:\n            s = \"<InstallRequirement>\"\n        if self.satisfied_by is not None:\n            s += \" in {}\".format(display_path(self.satisfied_by.location))\n        if self.comes_from:\n            if isinstance(self.comes_from, str):\n                comes_from: Optional[str] = self.comes_from\n            else:\n                comes_from = self.comes_from.from_path()\n            if comes_from:\n                s += f\" (from {comes_from})\"\n        return s\n\n    def __repr__(self) -> str:\n        return \"<{} object: {} editable={!r}>\".format(\n            self.__class__.__name__, str(self), self.editable\n        )\n\n    def format_debug(self) -> str:\n        \"\"\"An un-tested helper for getting state, for debugging.\"\"\"\n        attributes = vars(self)\n        names = sorted(attributes)\n\n        state = (\"{}={!r}\".format(attr, attributes[attr]) for attr in sorted(names))\n        return \"<{name} object: {{{state}}}>\".format(\n            name=self.__class__.__name__,\n            state=\", \".join(state),\n        )\n\n    # Things that are valid for all kinds of requirements?\n    @property\n    def name(self) -> Optional[str]:\n        if self.req is None:\n            return None\n        return self.req.name\n\n    @functools.lru_cache()  # use cached_property in python 3.8+\n    def supports_pyproject_editable(self) -> bool:\n        if not self.use_pep517:\n            return False\n        assert self.pep517_backend\n        with self.build_env:\n            runner = runner_with_spinner_message(\n                \"Checking if build backend supports build_editable\"\n            )\n            with self.pep517_backend.subprocess_runner(runner):\n                return \"build_editable\" in self.pep517_backend._supported_features()\n\n    @property\n    def specifier(self) -> SpecifierSet:\n        return self.req.specifier\n\n    @property\n    def is_pinned(self) -> bool:\n        \"\"\"Return whether I am pinned to an exact version.\n\n        For example, some-package==1.2 is pinned; some-package>1.2 is not.\n        \"\"\"\n        specifiers = self.specifier\n        return len(specifiers) == 1 and next(iter(specifiers)).operator in {\"==\", \"===\"}\n\n    def match_markers(self, extras_requested: Optional[Iterable[str]] = None) -> bool:\n        if not extras_requested:\n            # Provide an extra to safely evaluate the markers\n            # without matching any extra\n            extras_requested = (\"\",)\n        if self.markers is not None:\n            return any(\n                self.markers.evaluate({\"extra\": extra}) for extra in extras_requested\n            )\n        else:\n            return True\n\n    @property\n    def has_hash_options(self) -> bool:\n        \"\"\"Return whether any known-good hashes are specified as options.\n\n        These activate --require-hashes mode; hashes specified as part of a\n        URL do not.\n\n        \"\"\"\n        return bool(self.hash_options)\n\n    def hashes(self, trust_internet: bool = True) -> Hashes:\n        \"\"\"Return a hash-comparer that considers my option- and URL-based\n        hashes to be known-good.\n\n        Hashes in URLs--ones embedded in the requirements file, not ones\n        downloaded from an index server--are almost peers with ones from\n        flags. They satisfy --require-hashes (whether it was implicitly or\n        explicitly activated) but do not activate it. md5 and sha224 are not\n        allowed in flags, which should nudge people toward good algos. We\n        always OR all hashes together, even ones from URLs.\n\n        :param trust_internet: Whether to trust URL-based (#md5=...) hashes\n            downloaded from the internet, as by populate_link()\n\n        \"\"\"\n        good_hashes = self.hash_options.copy()\n        link = self.link if trust_internet else self.original_link\n        if link and link.hash:\n            good_hashes.setdefault(link.hash_name, []).append(link.hash)\n        return Hashes(good_hashes)\n\n    def from_path(self) -> Optional[str]:\n        \"\"\"Format a nice indicator to show where this \"comes from\" \"\"\"\n        if self.req is None:\n            return None\n        s = str(self.req)\n        if self.comes_from:\n            if isinstance(self.comes_from, str):\n                comes_from = self.comes_from\n            else:\n                comes_from = self.comes_from.from_path()\n            if comes_from:\n                s += \"->\" + comes_from\n        return s\n\n    def ensure_build_location(\n        self, build_dir: str, autodelete: bool, parallel_builds: bool\n    ) -> str:\n        assert build_dir is not None\n        if self._temp_build_dir is not None:\n            assert self._temp_build_dir.path\n            return self._temp_build_dir.path\n        if self.req is None:\n            # Some systems have /tmp as a symlink which confuses custom\n            # builds (such as numpy). Thus, we ensure that the real path\n            # is returned.\n            self._temp_build_dir = TempDirectory(\n                kind=tempdir_kinds.REQ_BUILD, globally_managed=True\n            )\n\n            return self._temp_build_dir.path\n\n        # This is the only remaining place where we manually determine the path\n        # for the temporary directory. It is only needed for editables where\n        # it is the value of the --src option.\n\n        # When parallel builds are enabled, add a UUID to the build directory\n        # name so multiple builds do not interfere with each other.\n        dir_name: str = canonicalize_name(self.name)\n        if parallel_builds:\n            dir_name = f\"{dir_name}_{uuid.uuid4().hex}\"\n\n        # FIXME: Is there a better place to create the build_dir? (hg and bzr\n        # need this)\n        if not os.path.exists(build_dir):\n            logger.debug(\"Creating directory %s\", build_dir)\n            os.makedirs(build_dir)\n        actual_build_dir = os.path.join(build_dir, dir_name)\n        # `None` indicates that we respect the globally-configured deletion\n        # settings, which is what we actually want when auto-deleting.\n        delete_arg = None if autodelete else False\n        return TempDirectory(\n            path=actual_build_dir,\n            delete=delete_arg,\n            kind=tempdir_kinds.REQ_BUILD,\n            globally_managed=True,\n        ).path\n\n    def _set_requirement(self) -> None:\n        \"\"\"Set requirement after generating metadata.\"\"\"\n        assert self.req is None\n        assert self.metadata is not None\n        assert self.source_dir is not None\n\n        # Construct a Requirement object from the generated metadata\n        if isinstance(parse_version(self.metadata[\"Version\"]), Version):\n            op = \"==\"\n        else:\n            op = \"===\"\n\n        self.req = Requirement(\n            \"\".join(\n                [\n                    self.metadata[\"Name\"],\n                    op,\n                    self.metadata[\"Version\"],\n                ]\n            )\n        )\n\n    def warn_on_mismatching_name(self) -> None:\n        metadata_name = canonicalize_name(self.metadata[\"Name\"])\n        if canonicalize_name(self.req.name) == metadata_name:\n            # Everything is fine.\n            return\n\n        # If we're here, there's a mismatch. Log a warning about it.\n        logger.warning(\n            \"Generating metadata for package %s \"\n            \"produced metadata for project name %s. Fix your \"\n            \"#egg=%s fragments.\",\n            self.name,\n            metadata_name,\n            self.name,\n        )\n        self.req = Requirement(metadata_name)\n\n    def check_if_exists(self, use_user_site: bool) -> None:\n        \"\"\"Find an installed distribution that satisfies or conflicts\n        with this requirement, and set self.satisfied_by or\n        self.should_reinstall appropriately.\n        \"\"\"\n        if self.req is None:\n            return\n        existing_dist = get_default_environment().get_distribution(self.req.name)\n        if not existing_dist:\n            return\n\n        version_compatible = self.req.specifier.contains(\n            existing_dist.version,\n            prereleases=True,\n        )\n        if not version_compatible:\n            self.satisfied_by = None\n            if use_user_site:\n                if existing_dist.in_usersite:\n                    self.should_reinstall = True\n                elif running_under_virtualenv() and existing_dist.in_site_packages:\n                    raise InstallationError(\n                        f\"Will not install to the user site because it will \"\n                        f\"lack sys.path precedence to {existing_dist.raw_name} \"\n                        f\"in {existing_dist.location}\"\n                    )\n            else:\n                self.should_reinstall = True\n        else:\n            if self.editable:\n                self.should_reinstall = True\n                # when installing editables, nothing pre-existing should ever\n                # satisfy\n                self.satisfied_by = None\n            else:\n                self.satisfied_by = existing_dist\n\n    # Things valid for wheels\n    @property\n    def is_wheel(self) -> bool:\n        if not self.link:\n            return False\n        return self.link.is_wheel\n\n    # Things valid for sdists\n    @property\n    def unpacked_source_directory(self) -> str:\n        return os.path.join(\n            self.source_dir, self.link and self.link.subdirectory_fragment or \"\"\n        )\n\n    @property\n    def setup_py_path(self) -> str:\n        assert self.source_dir, f\"No source dir for {self}\"\n        setup_py = os.path.join(self.unpacked_source_directory, \"setup.py\")\n\n        return setup_py\n\n    @property\n    def setup_cfg_path(self) -> str:\n        assert self.source_dir, f\"No source dir for {self}\"\n        setup_cfg = os.path.join(self.unpacked_source_directory, \"setup.cfg\")\n\n        return setup_cfg\n\n    @property\n    def pyproject_toml_path(self) -> str:\n        assert self.source_dir, f\"No source dir for {self}\"\n        return make_pyproject_path(self.unpacked_source_directory)\n\n    def load_pyproject_toml(self) -> None:\n        \"\"\"Load the pyproject.toml file.\n\n        After calling this routine, all of the attributes related to PEP 517\n        processing for this requirement have been set. In particular, the\n        use_pep517 attribute can be used to determine whether we should\n        follow the PEP 517 or legacy (setup.py) code path.\n        \"\"\"\n        pyproject_toml_data = load_pyproject_toml(\n            self.use_pep517, self.pyproject_toml_path, self.setup_py_path, str(self)\n        )\n\n        if pyproject_toml_data is None:\n            self.use_pep517 = False\n            return\n\n        self.use_pep517 = True\n        requires, backend, check, backend_path = pyproject_toml_data\n        self.requirements_to_check = check\n        self.pyproject_requires = requires\n        self.pep517_backend = ConfiguredPep517HookCaller(\n            self,\n            self.unpacked_source_directory,\n            backend,\n            backend_path=backend_path,\n        )\n\n    def isolated_editable_sanity_check(self) -> None:\n        \"\"\"Check that an editable requirement if valid for use with PEP 517/518.\n\n        This verifies that an editable that has a pyproject.toml either supports PEP 660\n        or as a setup.py or a setup.cfg\n        \"\"\"\n        if (\n            self.editable\n            and self.use_pep517\n            and not self.supports_pyproject_editable()\n            and not os.path.isfile(self.setup_py_path)\n            and not os.path.isfile(self.setup_cfg_path)\n        ):\n            raise InstallationError(\n                f\"Project {self} has a 'pyproject.toml' and its build \"\n                f\"backend is missing the 'build_editable' hook. Since it does not \"\n                f\"have a 'setup.py' nor a 'setup.cfg', \"\n                f\"it cannot be installed in editable mode. \"\n                f\"Consider using a build backend that supports PEP 660.\"\n            )\n\n    def prepare_metadata(self) -> None:\n        \"\"\"Ensure that project metadata is available.\n\n        Under PEP 517 and PEP 660, call the backend hook to prepare the metadata.\n        Under legacy processing, call setup.py egg-info.\n        \"\"\"\n        assert self.source_dir\n        details = self.name or f\"from {self.link}\"\n\n        if self.use_pep517:\n            assert self.pep517_backend is not None\n            if (\n                self.editable\n                and self.permit_editable_wheels\n                and self.supports_pyproject_editable()\n            ):\n                self.metadata_directory = generate_editable_metadata(\n                    build_env=self.build_env,\n                    backend=self.pep517_backend,\n                    details=details,\n                )\n            else:\n                self.metadata_directory = generate_metadata(\n                    build_env=self.build_env,\n                    backend=self.pep517_backend,\n                    details=details,\n                )\n        else:\n            self.metadata_directory = generate_metadata_legacy(\n                build_env=self.build_env,\n                setup_py_path=self.setup_py_path,\n                source_dir=self.unpacked_source_directory,\n                isolated=self.isolated,\n                details=details,\n            )\n\n        # Act on the newly generated metadata, based on the name and version.\n        if not self.name:\n            self._set_requirement()\n        else:\n            self.warn_on_mismatching_name()\n\n        self.assert_source_matches_version()\n\n    @property\n    def metadata(self) -> Any:\n        if not hasattr(self, \"_metadata\"):\n            self._metadata = self.get_dist().metadata\n\n        return self._metadata\n\n    def get_dist(self) -> BaseDistribution:\n        if self.metadata_directory:\n            return get_directory_distribution(self.metadata_directory)\n        elif self.local_file_path and self.is_wheel:\n            return get_wheel_distribution(\n                FilesystemWheel(self.local_file_path), canonicalize_name(self.name)\n            )\n        raise AssertionError(\n            f\"InstallRequirement {self} has no metadata directory and no wheel: \"\n            f\"can't make a distribution.\"\n        )\n\n    def assert_source_matches_version(self) -> None:\n        assert self.source_dir\n        version = self.metadata[\"version\"]\n        if self.req.specifier and version not in self.req.specifier:\n            logger.warning(\n                \"Requested %s, but installing version %s\",\n                self,\n                version,\n            )\n        else:\n            logger.debug(\n                \"Source in %s has version %s, which satisfies requirement %s\",\n                display_path(self.source_dir),\n                version,\n                self,\n            )\n\n    # For both source distributions and editables\n    def ensure_has_source_dir(\n        self,\n        parent_dir: str,\n        autodelete: bool = False,\n        parallel_builds: bool = False,\n    ) -> None:\n        \"\"\"Ensure that a source_dir is set.\n\n        This will create a temporary build dir if the name of the requirement\n        isn't known yet.\n\n        :param parent_dir: The ideal pip parent_dir for the source_dir.\n            Generally src_dir for editables and build_dir for sdists.\n        :return: self.source_dir\n        \"\"\"\n        if self.source_dir is None:\n            self.source_dir = self.ensure_build_location(\n                parent_dir,\n                autodelete=autodelete,\n                parallel_builds=parallel_builds,\n            )\n\n    # For editable installations\n    def update_editable(self) -> None:\n        if not self.link:\n            logger.debug(\n                \"Cannot update repository at %s; repository location is unknown\",\n                self.source_dir,\n            )\n            return\n        assert self.editable\n        assert self.source_dir\n        if self.link.scheme == \"file\":\n            # Static paths don't get updated\n            return\n        vcs_backend = vcs.get_backend_for_scheme(self.link.scheme)\n        # Editable requirements are validated in Requirement constructors.\n        # So here, if it's neither a path nor a valid VCS URL, it's a bug.\n        assert vcs_backend, f\"Unsupported VCS URL {self.link.url}\"\n        hidden_url = hide_url(self.link.url)\n        vcs_backend.obtain(self.source_dir, url=hidden_url, verbosity=0)\n\n    # Top-level Actions\n    def uninstall(\n        self, auto_confirm: bool = False, verbose: bool = False\n    ) -> Optional[UninstallPathSet]:\n        \"\"\"\n        Uninstall the distribution currently satisfying this requirement.\n\n        Prompts before removing or modifying files unless\n        ``auto_confirm`` is True.\n\n        Refuses to delete or modify files outside of ``sys.prefix`` -\n        thus uninstallation within a virtual environment can only\n        modify that virtual environment, even if the virtualenv is\n        linked to global site-packages.\n\n        \"\"\"\n        assert self.req\n        dist = get_default_environment().get_distribution(self.req.name)\n        if not dist:\n            logger.warning(\"Skipping %s as it is not installed.\", self.name)\n            return None\n        logger.info(\"Found existing installation: %s\", dist)\n\n        uninstalled_pathset = UninstallPathSet.from_dist(dist)\n        uninstalled_pathset.remove(auto_confirm, verbose)\n        return uninstalled_pathset\n\n    def _get_archive_name(self, path: str, parentdir: str, rootdir: str) -> str:\n        def _clean_zip_name(name: str, prefix: str) -> str:\n            assert name.startswith(\n                prefix + os.path.sep\n            ), f\"name {name!r} doesn't start with prefix {prefix!r}\"\n            name = name[len(prefix) + 1 :]\n            name = name.replace(os.path.sep, \"/\")\n            return name\n\n        path = os.path.join(parentdir, path)\n        name = _clean_zip_name(path, rootdir)\n        return self.name + \"/\" + name\n\n    def archive(self, build_dir: Optional[str]) -> None:\n        \"\"\"Saves archive to provided build_dir.\n\n        Used for saving downloaded VCS requirements as part of `pip download`.\n        \"\"\"\n        assert self.source_dir\n        if build_dir is None:\n            return\n\n        create_archive = True\n        archive_name = \"{}-{}.zip\".format(self.name, self.metadata[\"version\"])\n        archive_path = os.path.join(build_dir, archive_name)\n\n        if os.path.exists(archive_path):\n            response = ask_path_exists(\n                \"The file {} exists. (i)gnore, (w)ipe, \"\n                \"(b)ackup, (a)bort \".format(display_path(archive_path)),\n                (\"i\", \"w\", \"b\", \"a\"),\n            )\n            if response == \"i\":\n                create_archive = False\n            elif response == \"w\":\n                logger.warning(\"Deleting %s\", display_path(archive_path))\n                os.remove(archive_path)\n            elif response == \"b\":\n                dest_file = backup_dir(archive_path)\n                logger.warning(\n                    \"Backing up %s to %s\",\n                    display_path(archive_path),\n                    display_path(dest_file),\n                )\n                shutil.move(archive_path, dest_file)\n            elif response == \"a\":\n                sys.exit(-1)\n\n        if not create_archive:\n            return\n\n        zip_output = zipfile.ZipFile(\n            archive_path,\n            \"w\",\n            zipfile.ZIP_DEFLATED,\n            allowZip64=True,\n        )\n        with zip_output:\n            dir = os.path.normcase(os.path.abspath(self.unpacked_source_directory))\n            for dirpath, dirnames, filenames in os.walk(dir):\n                for dirname in dirnames:\n                    dir_arcname = self._get_archive_name(\n                        dirname,\n                        parentdir=dirpath,\n                        rootdir=dir,\n                    )\n                    zipdir = zipfile.ZipInfo(dir_arcname + \"/\")\n                    zipdir.external_attr = 0x1ED << 16  # 0o755\n                    zip_output.writestr(zipdir, \"\")\n                for filename in filenames:\n                    file_arcname = self._get_archive_name(\n                        filename,\n                        parentdir=dirpath,\n                        rootdir=dir,\n                    )\n                    filename = os.path.join(dirpath, filename)\n                    zip_output.write(filename, file_arcname)\n\n        logger.info(\"Saved %s\", display_path(archive_path))\n\n    def install(\n        self,\n        install_options: List[str],\n        global_options: Optional[Sequence[str]] = None,\n        root: Optional[str] = None,\n        home: Optional[str] = None,\n        prefix: Optional[str] = None,\n        warn_script_location: bool = True,\n        use_user_site: bool = False,\n        pycompile: bool = True,\n    ) -> None:\n        scheme = get_scheme(\n            self.name,\n            user=use_user_site,\n            home=home,\n            root=root,\n            isolated=self.isolated,\n            prefix=prefix,\n        )\n\n        global_options = global_options if global_options is not None else []\n        if self.editable and not self.is_wheel:\n            install_editable_legacy(\n                install_options,\n                global_options,\n                prefix=prefix,\n                home=home,\n                use_user_site=use_user_site,\n                name=self.name,\n                setup_py_path=self.setup_py_path,\n                isolated=self.isolated,\n                build_env=self.build_env,\n                unpacked_source_directory=self.unpacked_source_directory,\n            )\n            self.install_succeeded = True\n            return\n\n        if self.is_wheel:\n            assert self.local_file_path\n            direct_url = None\n            # TODO this can be refactored to direct_url = self.download_info\n            if self.editable:\n                direct_url = direct_url_for_editable(self.unpacked_source_directory)\n            elif self.original_link:\n                direct_url = direct_url_from_link(\n                    self.original_link,\n                    self.source_dir,\n                    self.original_link_is_in_wheel_cache,\n                )\n            install_wheel(\n                self.name,\n                self.local_file_path,\n                scheme=scheme,\n                req_description=str(self.req),\n                pycompile=pycompile,\n                warn_script_location=warn_script_location,\n                direct_url=direct_url,\n                requested=self.user_supplied,\n            )\n            self.install_succeeded = True\n            return\n\n        # TODO: Why don't we do this for editable installs?\n\n        # Extend the list of global and install options passed on to\n        # the setup.py call with the ones from the requirements file.\n        # Options specified in requirements file override those\n        # specified on the command line, since the last option given\n        # to setup.py is the one that is used.\n        global_options = list(global_options) + self.global_options\n        install_options = list(install_options) + self.install_options\n\n        try:\n            if (\n                self.legacy_install_reason is not None\n                and self.legacy_install_reason.emit_before_install\n            ):\n                self.legacy_install_reason.emit_deprecation(self.name)\n            success = install_legacy(\n                install_options=install_options,\n                global_options=global_options,\n                root=root,\n                home=home,\n                prefix=prefix,\n                use_user_site=use_user_site,\n                pycompile=pycompile,\n                scheme=scheme,\n                setup_py_path=self.setup_py_path,\n                isolated=self.isolated,\n                req_name=self.name,\n                build_env=self.build_env,\n                unpacked_source_directory=self.unpacked_source_directory,\n                req_description=str(self.req),\n            )\n        except LegacyInstallFailure as exc:\n            self.install_succeeded = False\n            raise exc\n        except Exception:\n            self.install_succeeded = True\n            raise\n\n        self.install_succeeded = success\n\n        if (\n            success\n            and self.legacy_install_reason is not None\n            and self.legacy_install_reason.emit_after_success\n        ):\n            self.legacy_install_reason.emit_deprecation(self.name)\n\n\ndef check_invalid_constraint_type(req: InstallRequirement) -> str:\n\n    # Check for unsupported forms\n    problem = \"\"\n    if not req.name:\n        problem = \"Unnamed requirements are not allowed as constraints\"\n    elif req.editable:\n        problem = \"Editable requirements are not allowed as constraints\"\n    elif req.extras:\n        problem = \"Constraints cannot have extras\"\n\n    if problem:\n        deprecated(\n            reason=(\n                \"Constraints are only allowed to take the form of a package \"\n                \"name and a version specifier. Other forms were originally \"\n                \"permitted as an accident of the implementation, but were \"\n                \"undocumented. The new implementation of the resolver no \"\n                \"longer supports these forms.\"\n            ),\n            replacement=\"replacing the constraint with a requirement\",\n            # No plan yet for when the new resolver becomes default\n            gone_in=None,\n            issue=8210,\n        )\n\n    return problem\n\n\ndef _has_option(options: Values, reqs: List[InstallRequirement], option: str) -> bool:\n    if getattr(options, option, None):\n        return True\n    for req in reqs:\n        if getattr(req, option, None):\n            return True\n    return False\n\n\ndef _install_option_ignored(\n    install_options: List[str], reqs: List[InstallRequirement]\n) -> bool:\n    for req in reqs:\n        if (install_options or req.install_options) and not req.use_pep517:\n            return False\n    return True\n\n\nclass LegacySetupPyOptionsCheckMode(Enum):\n    INSTALL = 1\n    WHEEL = 2\n    DOWNLOAD = 3\n\n\ndef check_legacy_setup_py_options(\n    options: Values,\n    reqs: List[InstallRequirement],\n    mode: LegacySetupPyOptionsCheckMode,\n) -> None:\n    has_install_options = _has_option(options, reqs, \"install_options\")\n    has_build_options = _has_option(options, reqs, \"build_options\")\n    has_global_options = _has_option(options, reqs, \"global_options\")\n    legacy_setup_py_options_present = (\n        has_install_options or has_build_options or has_global_options\n    )\n    if not legacy_setup_py_options_present:\n        return\n\n    options.format_control.disallow_binaries()\n    logger.warning(\n        \"Implying --no-binary=:all: due to the presence of \"\n        \"--build-option / --global-option / --install-option. \"\n        \"Consider using --config-settings for more flexibility.\",\n    )\n    if mode == LegacySetupPyOptionsCheckMode.INSTALL and has_install_options:\n        if _install_option_ignored(options.install_options, reqs):\n            logger.warning(\n                \"Ignoring --install-option when building using PEP 517\",\n            )\n        else:\n            deprecated(\n                reason=(\n                    \"--install-option is deprecated because \"\n                    \"it forces pip to use the 'setup.py install' \"\n                    \"command which is itself deprecated.\"\n                ),\n                issue=11358,\n                replacement=\"to use --config-settings\",\n                gone_in=\"23.1\",\n            )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/req/req_set.py",
    "content": "import logging\nfrom collections import OrderedDict\nfrom typing import Dict, List\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.req.req_install import InstallRequirement\n\nlogger = logging.getLogger(__name__)\n\n\nclass RequirementSet:\n    def __init__(self, check_supported_wheels: bool = True) -> None:\n        \"\"\"Create a RequirementSet.\"\"\"\n\n        self.requirements: Dict[str, InstallRequirement] = OrderedDict()\n        self.check_supported_wheels = check_supported_wheels\n\n        self.unnamed_requirements: List[InstallRequirement] = []\n\n    def __str__(self) -> str:\n        requirements = sorted(\n            (req for req in self.requirements.values() if not req.comes_from),\n            key=lambda req: canonicalize_name(req.name or \"\"),\n        )\n        return \" \".join(str(req.req) for req in requirements)\n\n    def __repr__(self) -> str:\n        requirements = sorted(\n            self.requirements.values(),\n            key=lambda req: canonicalize_name(req.name or \"\"),\n        )\n\n        format_string = \"<{classname} object; {count} requirement(s): {reqs}>\"\n        return format_string.format(\n            classname=self.__class__.__name__,\n            count=len(requirements),\n            reqs=\", \".join(str(req.req) for req in requirements),\n        )\n\n    def add_unnamed_requirement(self, install_req: InstallRequirement) -> None:\n        assert not install_req.name\n        self.unnamed_requirements.append(install_req)\n\n    def add_named_requirement(self, install_req: InstallRequirement) -> None:\n        assert install_req.name\n\n        project_name = canonicalize_name(install_req.name)\n        self.requirements[project_name] = install_req\n\n    def has_requirement(self, name: str) -> bool:\n        project_name = canonicalize_name(name)\n\n        return (\n            project_name in self.requirements\n            and not self.requirements[project_name].constraint\n        )\n\n    def get_requirement(self, name: str) -> InstallRequirement:\n        project_name = canonicalize_name(name)\n\n        if project_name in self.requirements:\n            return self.requirements[project_name]\n\n        raise KeyError(f\"No project with the name {name!r}\")\n\n    @property\n    def all_requirements(self) -> List[InstallRequirement]:\n        return self.unnamed_requirements + list(self.requirements.values())\n\n    @property\n    def requirements_to_install(self) -> List[InstallRequirement]:\n        \"\"\"Return the list of requirements that need to be installed.\n\n        TODO remove this property together with the legacy resolver, since the new\n             resolver only returns requirements that need to be installed.\n        \"\"\"\n        return [\n            install_req\n            for install_req in self.all_requirements\n            if not install_req.constraint and not install_req.satisfied_by\n        ]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/req/req_uninstall.py",
    "content": "import functools\nimport os\nimport sys\nimport sysconfig\nfrom importlib.util import cache_from_source\nfrom typing import Any, Callable, Dict, Generator, Iterable, List, Optional, Set, Tuple\n\nfrom pip._internal.exceptions import UninstallationError\nfrom pip._internal.locations import get_bin_prefix, get_bin_user\nfrom pip._internal.metadata import BaseDistribution\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.egg_link import egg_link_path_from_location\nfrom pip._internal.utils.logging import getLogger, indent_log\nfrom pip._internal.utils.misc import ask, is_local, normalize_path, renames, rmtree\nfrom pip._internal.utils.temp_dir import AdjacentTempDirectory, TempDirectory\n\nlogger = getLogger(__name__)\n\n\ndef _script_names(\n    bin_dir: str, script_name: str, is_gui: bool\n) -> Generator[str, None, None]:\n    \"\"\"Create the fully qualified name of the files created by\n    {console,gui}_scripts for the given ``dist``.\n    Returns the list of file names\n    \"\"\"\n    exe_name = os.path.join(bin_dir, script_name)\n    yield exe_name\n    if not WINDOWS:\n        return\n    yield f\"{exe_name}.exe\"\n    yield f\"{exe_name}.exe.manifest\"\n    if is_gui:\n        yield f\"{exe_name}-script.pyw\"\n    else:\n        yield f\"{exe_name}-script.py\"\n\n\ndef _unique(\n    fn: Callable[..., Generator[Any, None, None]]\n) -> Callable[..., Generator[Any, None, None]]:\n    @functools.wraps(fn)\n    def unique(*args: Any, **kw: Any) -> Generator[Any, None, None]:\n        seen: Set[Any] = set()\n        for item in fn(*args, **kw):\n            if item not in seen:\n                seen.add(item)\n                yield item\n\n    return unique\n\n\n@_unique\ndef uninstallation_paths(dist: BaseDistribution) -> Generator[str, None, None]:\n    \"\"\"\n    Yield all the uninstallation paths for dist based on RECORD-without-.py[co]\n\n    Yield paths to all the files in RECORD. For each .py file in RECORD, add\n    the .pyc and .pyo in the same directory.\n\n    UninstallPathSet.add() takes care of the __pycache__ .py[co].\n\n    If RECORD is not found, raises UninstallationError,\n    with possible information from the INSTALLER file.\n\n    https://packaging.python.org/specifications/recording-installed-packages/\n    \"\"\"\n    location = dist.location\n    assert location is not None, \"not installed\"\n\n    entries = dist.iter_declared_entries()\n    if entries is None:\n        msg = \"Cannot uninstall {dist}, RECORD file not found.\".format(dist=dist)\n        installer = dist.installer\n        if not installer or installer == \"pip\":\n            dep = \"{}=={}\".format(dist.raw_name, dist.version)\n            msg += (\n                \" You might be able to recover from this via: \"\n                \"'pip install --force-reinstall --no-deps {}'.\".format(dep)\n            )\n        else:\n            msg += \" Hint: The package was installed by {}.\".format(installer)\n        raise UninstallationError(msg)\n\n    for entry in entries:\n        path = os.path.join(location, entry)\n        yield path\n        if path.endswith(\".py\"):\n            dn, fn = os.path.split(path)\n            base = fn[:-3]\n            path = os.path.join(dn, base + \".pyc\")\n            yield path\n            path = os.path.join(dn, base + \".pyo\")\n            yield path\n\n\ndef compact(paths: Iterable[str]) -> Set[str]:\n    \"\"\"Compact a path set to contain the minimal number of paths\n    necessary to contain all paths in the set. If /a/path/ and\n    /a/path/to/a/file.txt are both in the set, leave only the\n    shorter path.\"\"\"\n\n    sep = os.path.sep\n    short_paths: Set[str] = set()\n    for path in sorted(paths, key=len):\n        should_skip = any(\n            path.startswith(shortpath.rstrip(\"*\"))\n            and path[len(shortpath.rstrip(\"*\").rstrip(sep))] == sep\n            for shortpath in short_paths\n        )\n        if not should_skip:\n            short_paths.add(path)\n    return short_paths\n\n\ndef compress_for_rename(paths: Iterable[str]) -> Set[str]:\n    \"\"\"Returns a set containing the paths that need to be renamed.\n\n    This set may include directories when the original sequence of paths\n    included every file on disk.\n    \"\"\"\n    case_map = {os.path.normcase(p): p for p in paths}\n    remaining = set(case_map)\n    unchecked = sorted({os.path.split(p)[0] for p in case_map.values()}, key=len)\n    wildcards: Set[str] = set()\n\n    def norm_join(*a: str) -> str:\n        return os.path.normcase(os.path.join(*a))\n\n    for root in unchecked:\n        if any(os.path.normcase(root).startswith(w) for w in wildcards):\n            # This directory has already been handled.\n            continue\n\n        all_files: Set[str] = set()\n        all_subdirs: Set[str] = set()\n        for dirname, subdirs, files in os.walk(root):\n            all_subdirs.update(norm_join(root, dirname, d) for d in subdirs)\n            all_files.update(norm_join(root, dirname, f) for f in files)\n        # If all the files we found are in our remaining set of files to\n        # remove, then remove them from the latter set and add a wildcard\n        # for the directory.\n        if not (all_files - remaining):\n            remaining.difference_update(all_files)\n            wildcards.add(root + os.sep)\n\n    return set(map(case_map.__getitem__, remaining)) | wildcards\n\n\ndef compress_for_output_listing(paths: Iterable[str]) -> Tuple[Set[str], Set[str]]:\n    \"\"\"Returns a tuple of 2 sets of which paths to display to user\n\n    The first set contains paths that would be deleted. Files of a package\n    are not added and the top-level directory of the package has a '*' added\n    at the end - to signify that all it's contents are removed.\n\n    The second set contains files that would have been skipped in the above\n    folders.\n    \"\"\"\n\n    will_remove = set(paths)\n    will_skip = set()\n\n    # Determine folders and files\n    folders = set()\n    files = set()\n    for path in will_remove:\n        if path.endswith(\".pyc\"):\n            continue\n        if path.endswith(\"__init__.py\") or \".dist-info\" in path:\n            folders.add(os.path.dirname(path))\n        files.add(path)\n\n    # probably this one https://github.com/python/mypy/issues/390\n    _normcased_files = set(map(os.path.normcase, files))  # type: ignore\n\n    folders = compact(folders)\n\n    # This walks the tree using os.walk to not miss extra folders\n    # that might get added.\n    for folder in folders:\n        for dirpath, _, dirfiles in os.walk(folder):\n            for fname in dirfiles:\n                if fname.endswith(\".pyc\"):\n                    continue\n\n                file_ = os.path.join(dirpath, fname)\n                if (\n                    os.path.isfile(file_)\n                    and os.path.normcase(file_) not in _normcased_files\n                ):\n                    # We are skipping this file. Add it to the set.\n                    will_skip.add(file_)\n\n    will_remove = files | {os.path.join(folder, \"*\") for folder in folders}\n\n    return will_remove, will_skip\n\n\nclass StashedUninstallPathSet:\n    \"\"\"A set of file rename operations to stash files while\n    tentatively uninstalling them.\"\"\"\n\n    def __init__(self) -> None:\n        # Mapping from source file root to [Adjacent]TempDirectory\n        # for files under that directory.\n        self._save_dirs: Dict[str, TempDirectory] = {}\n        # (old path, new path) tuples for each move that may need\n        # to be undone.\n        self._moves: List[Tuple[str, str]] = []\n\n    def _get_directory_stash(self, path: str) -> str:\n        \"\"\"Stashes a directory.\n\n        Directories are stashed adjacent to their original location if\n        possible, or else moved/copied into the user's temp dir.\"\"\"\n\n        try:\n            save_dir: TempDirectory = AdjacentTempDirectory(path)\n        except OSError:\n            save_dir = TempDirectory(kind=\"uninstall\")\n        self._save_dirs[os.path.normcase(path)] = save_dir\n\n        return save_dir.path\n\n    def _get_file_stash(self, path: str) -> str:\n        \"\"\"Stashes a file.\n\n        If no root has been provided, one will be created for the directory\n        in the user's temp directory.\"\"\"\n        path = os.path.normcase(path)\n        head, old_head = os.path.dirname(path), None\n        save_dir = None\n\n        while head != old_head:\n            try:\n                save_dir = self._save_dirs[head]\n                break\n            except KeyError:\n                pass\n            head, old_head = os.path.dirname(head), head\n        else:\n            # Did not find any suitable root\n            head = os.path.dirname(path)\n            save_dir = TempDirectory(kind=\"uninstall\")\n            self._save_dirs[head] = save_dir\n\n        relpath = os.path.relpath(path, head)\n        if relpath and relpath != os.path.curdir:\n            return os.path.join(save_dir.path, relpath)\n        return save_dir.path\n\n    def stash(self, path: str) -> str:\n        \"\"\"Stashes the directory or file and returns its new location.\n        Handle symlinks as files to avoid modifying the symlink targets.\n        \"\"\"\n        path_is_dir = os.path.isdir(path) and not os.path.islink(path)\n        if path_is_dir:\n            new_path = self._get_directory_stash(path)\n        else:\n            new_path = self._get_file_stash(path)\n\n        self._moves.append((path, new_path))\n        if path_is_dir and os.path.isdir(new_path):\n            # If we're moving a directory, we need to\n            # remove the destination first or else it will be\n            # moved to inside the existing directory.\n            # We just created new_path ourselves, so it will\n            # be removable.\n            os.rmdir(new_path)\n        renames(path, new_path)\n        return new_path\n\n    def commit(self) -> None:\n        \"\"\"Commits the uninstall by removing stashed files.\"\"\"\n        for _, save_dir in self._save_dirs.items():\n            save_dir.cleanup()\n        self._moves = []\n        self._save_dirs = {}\n\n    def rollback(self) -> None:\n        \"\"\"Undoes the uninstall by moving stashed files back.\"\"\"\n        for p in self._moves:\n            logger.info(\"Moving to %s\\n from %s\", *p)\n\n        for new_path, path in self._moves:\n            try:\n                logger.debug(\"Replacing %s from %s\", new_path, path)\n                if os.path.isfile(new_path) or os.path.islink(new_path):\n                    os.unlink(new_path)\n                elif os.path.isdir(new_path):\n                    rmtree(new_path)\n                renames(path, new_path)\n            except OSError as ex:\n                logger.error(\"Failed to restore %s\", new_path)\n                logger.debug(\"Exception: %s\", ex)\n\n        self.commit()\n\n    @property\n    def can_rollback(self) -> bool:\n        return bool(self._moves)\n\n\nclass UninstallPathSet:\n    \"\"\"A set of file paths to be removed in the uninstallation of a\n    requirement.\"\"\"\n\n    def __init__(self, dist: BaseDistribution) -> None:\n        self._paths: Set[str] = set()\n        self._refuse: Set[str] = set()\n        self._pth: Dict[str, UninstallPthEntries] = {}\n        self._dist = dist\n        self._moved_paths = StashedUninstallPathSet()\n\n    def _permitted(self, path: str) -> bool:\n        \"\"\"\n        Return True if the given path is one we are permitted to\n        remove/modify, False otherwise.\n\n        \"\"\"\n        return is_local(path)\n\n    def add(self, path: str) -> None:\n        head, tail = os.path.split(path)\n\n        # we normalize the head to resolve parent directory symlinks, but not\n        # the tail, since we only want to uninstall symlinks, not their targets\n        path = os.path.join(normalize_path(head), os.path.normcase(tail))\n\n        if not os.path.exists(path):\n            return\n        if self._permitted(path):\n            self._paths.add(path)\n        else:\n            self._refuse.add(path)\n\n        # __pycache__ files can show up after 'installed-files.txt' is created,\n        # due to imports\n        if os.path.splitext(path)[1] == \".py\":\n            self.add(cache_from_source(path))\n\n    def add_pth(self, pth_file: str, entry: str) -> None:\n        pth_file = normalize_path(pth_file)\n        if self._permitted(pth_file):\n            if pth_file not in self._pth:\n                self._pth[pth_file] = UninstallPthEntries(pth_file)\n            self._pth[pth_file].add(entry)\n        else:\n            self._refuse.add(pth_file)\n\n    def remove(self, auto_confirm: bool = False, verbose: bool = False) -> None:\n        \"\"\"Remove paths in ``self._paths`` with confirmation (unless\n        ``auto_confirm`` is True).\"\"\"\n\n        if not self._paths:\n            logger.info(\n                \"Can't uninstall '%s'. No files were found to uninstall.\",\n                self._dist.raw_name,\n            )\n            return\n\n        dist_name_version = f\"{self._dist.raw_name}-{self._dist.version}\"\n        logger.info(\"Uninstalling %s:\", dist_name_version)\n\n        with indent_log():\n            if auto_confirm or self._allowed_to_proceed(verbose):\n                moved = self._moved_paths\n\n                for_rename = compress_for_rename(self._paths)\n\n                for path in sorted(compact(for_rename)):\n                    moved.stash(path)\n                    logger.verbose(\"Removing file or directory %s\", path)\n\n                for pth in self._pth.values():\n                    pth.remove()\n\n                logger.info(\"Successfully uninstalled %s\", dist_name_version)\n\n    def _allowed_to_proceed(self, verbose: bool) -> bool:\n        \"\"\"Display which files would be deleted and prompt for confirmation\"\"\"\n\n        def _display(msg: str, paths: Iterable[str]) -> None:\n            if not paths:\n                return\n\n            logger.info(msg)\n            with indent_log():\n                for path in sorted(compact(paths)):\n                    logger.info(path)\n\n        if not verbose:\n            will_remove, will_skip = compress_for_output_listing(self._paths)\n        else:\n            # In verbose mode, display all the files that are going to be\n            # deleted.\n            will_remove = set(self._paths)\n            will_skip = set()\n\n        _display(\"Would remove:\", will_remove)\n        _display(\"Would not remove (might be manually added):\", will_skip)\n        _display(\"Would not remove (outside of prefix):\", self._refuse)\n        if verbose:\n            _display(\"Will actually move:\", compress_for_rename(self._paths))\n\n        return ask(\"Proceed (Y/n)? \", (\"y\", \"n\", \"\")) != \"n\"\n\n    def rollback(self) -> None:\n        \"\"\"Rollback the changes previously made by remove().\"\"\"\n        if not self._moved_paths.can_rollback:\n            logger.error(\n                \"Can't roll back %s; was not uninstalled\",\n                self._dist.raw_name,\n            )\n            return\n        logger.info(\"Rolling back uninstall of %s\", self._dist.raw_name)\n        self._moved_paths.rollback()\n        for pth in self._pth.values():\n            pth.rollback()\n\n    def commit(self) -> None:\n        \"\"\"Remove temporary save dir: rollback will no longer be possible.\"\"\"\n        self._moved_paths.commit()\n\n    @classmethod\n    def from_dist(cls, dist: BaseDistribution) -> \"UninstallPathSet\":\n        dist_location = dist.location\n        info_location = dist.info_location\n        if dist_location is None:\n            logger.info(\n                \"Not uninstalling %s since it is not installed\",\n                dist.canonical_name,\n            )\n            return cls(dist)\n\n        normalized_dist_location = normalize_path(dist_location)\n        if not dist.local:\n            logger.info(\n                \"Not uninstalling %s at %s, outside environment %s\",\n                dist.canonical_name,\n                normalized_dist_location,\n                sys.prefix,\n            )\n            return cls(dist)\n\n        if normalized_dist_location in {\n            p\n            for p in {sysconfig.get_path(\"stdlib\"), sysconfig.get_path(\"platstdlib\")}\n            if p\n        }:\n            logger.info(\n                \"Not uninstalling %s at %s, as it is in the standard library.\",\n                dist.canonical_name,\n                normalized_dist_location,\n            )\n            return cls(dist)\n\n        paths_to_remove = cls(dist)\n        develop_egg_link = egg_link_path_from_location(dist.raw_name)\n\n        # Distribution is installed with metadata in a \"flat\" .egg-info\n        # directory. This means it is not a modern .dist-info installation, an\n        # egg, or legacy editable.\n        setuptools_flat_installation = (\n            dist.installed_with_setuptools_egg_info\n            and info_location is not None\n            and os.path.exists(info_location)\n            # If dist is editable and the location points to a ``.egg-info``,\n            # we are in fact in the legacy editable case.\n            and not info_location.endswith(f\"{dist.setuptools_filename}.egg-info\")\n        )\n\n        # Uninstall cases order do matter as in the case of 2 installs of the\n        # same package, pip needs to uninstall the currently detected version\n        if setuptools_flat_installation:\n            if info_location is not None:\n                paths_to_remove.add(info_location)\n            installed_files = dist.iter_declared_entries()\n            if installed_files is not None:\n                for installed_file in installed_files:\n                    paths_to_remove.add(os.path.join(dist_location, installed_file))\n            # FIXME: need a test for this elif block\n            # occurs with --single-version-externally-managed/--record outside\n            # of pip\n            elif dist.is_file(\"top_level.txt\"):\n                try:\n                    namespace_packages = dist.read_text(\"namespace_packages.txt\")\n                except FileNotFoundError:\n                    namespaces = []\n                else:\n                    namespaces = namespace_packages.splitlines(keepends=False)\n                for top_level_pkg in [\n                    p\n                    for p in dist.read_text(\"top_level.txt\").splitlines()\n                    if p and p not in namespaces\n                ]:\n                    path = os.path.join(dist_location, top_level_pkg)\n                    paths_to_remove.add(path)\n                    paths_to_remove.add(f\"{path}.py\")\n                    paths_to_remove.add(f\"{path}.pyc\")\n                    paths_to_remove.add(f\"{path}.pyo\")\n\n        elif dist.installed_by_distutils:\n            raise UninstallationError(\n                \"Cannot uninstall {!r}. It is a distutils installed project \"\n                \"and thus we cannot accurately determine which files belong \"\n                \"to it which would lead to only a partial uninstall.\".format(\n                    dist.raw_name,\n                )\n            )\n\n        elif dist.installed_as_egg:\n            # package installed by easy_install\n            # We cannot match on dist.egg_name because it can slightly vary\n            # i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg\n            paths_to_remove.add(dist_location)\n            easy_install_egg = os.path.split(dist_location)[1]\n            easy_install_pth = os.path.join(\n                os.path.dirname(dist_location),\n                \"easy-install.pth\",\n            )\n            paths_to_remove.add_pth(easy_install_pth, \"./\" + easy_install_egg)\n\n        elif dist.installed_with_dist_info:\n            for path in uninstallation_paths(dist):\n                paths_to_remove.add(path)\n\n        elif develop_egg_link:\n            # PEP 660 modern editable is handled in the ``.dist-info`` case\n            # above, so this only covers the setuptools-style editable.\n            with open(develop_egg_link) as fh:\n                link_pointer = os.path.normcase(fh.readline().strip())\n                normalized_link_pointer = normalize_path(link_pointer)\n            assert os.path.samefile(\n                normalized_link_pointer, normalized_dist_location\n            ), (\n                f\"Egg-link {link_pointer} does not match installed location of \"\n                f\"{dist.raw_name} (at {dist_location})\"\n            )\n            paths_to_remove.add(develop_egg_link)\n            easy_install_pth = os.path.join(\n                os.path.dirname(develop_egg_link), \"easy-install.pth\"\n            )\n            paths_to_remove.add_pth(easy_install_pth, dist_location)\n\n        else:\n            logger.debug(\n                \"Not sure how to uninstall: %s - Check: %s\",\n                dist,\n                dist_location,\n            )\n\n        if dist.in_usersite:\n            bin_dir = get_bin_user()\n        else:\n            bin_dir = get_bin_prefix()\n\n        # find distutils scripts= scripts\n        try:\n            for script in dist.iter_distutils_script_names():\n                paths_to_remove.add(os.path.join(bin_dir, script))\n                if WINDOWS:\n                    paths_to_remove.add(os.path.join(bin_dir, f\"{script}.bat\"))\n        except (FileNotFoundError, NotADirectoryError):\n            pass\n\n        # find console_scripts and gui_scripts\n        def iter_scripts_to_remove(\n            dist: BaseDistribution,\n            bin_dir: str,\n        ) -> Generator[str, None, None]:\n            for entry_point in dist.iter_entry_points():\n                if entry_point.group == \"console_scripts\":\n                    yield from _script_names(bin_dir, entry_point.name, False)\n                elif entry_point.group == \"gui_scripts\":\n                    yield from _script_names(bin_dir, entry_point.name, True)\n\n        for s in iter_scripts_to_remove(dist, bin_dir):\n            paths_to_remove.add(s)\n\n        return paths_to_remove\n\n\nclass UninstallPthEntries:\n    def __init__(self, pth_file: str) -> None:\n        self.file = pth_file\n        self.entries: Set[str] = set()\n        self._saved_lines: Optional[List[bytes]] = None\n\n    def add(self, entry: str) -> None:\n        entry = os.path.normcase(entry)\n        # On Windows, os.path.normcase converts the entry to use\n        # backslashes.  This is correct for entries that describe absolute\n        # paths outside of site-packages, but all the others use forward\n        # slashes.\n        # os.path.splitdrive is used instead of os.path.isabs because isabs\n        # treats non-absolute paths with drive letter markings like c:foo\\bar\n        # as absolute paths. It also does not recognize UNC paths if they don't\n        # have more than \"\\\\sever\\share\". Valid examples: \"\\\\server\\share\\\" or\n        # \"\\\\server\\share\\folder\".\n        if WINDOWS and not os.path.splitdrive(entry)[0]:\n            entry = entry.replace(\"\\\\\", \"/\")\n        self.entries.add(entry)\n\n    def remove(self) -> None:\n        logger.verbose(\"Removing pth entries from %s:\", self.file)\n\n        # If the file doesn't exist, log a warning and return\n        if not os.path.isfile(self.file):\n            logger.warning(\"Cannot remove entries from nonexistent file %s\", self.file)\n            return\n        with open(self.file, \"rb\") as fh:\n            # windows uses '\\r\\n' with py3k, but uses '\\n' with py2.x\n            lines = fh.readlines()\n            self._saved_lines = lines\n        if any(b\"\\r\\n\" in line for line in lines):\n            endline = \"\\r\\n\"\n        else:\n            endline = \"\\n\"\n        # handle missing trailing newline\n        if lines and not lines[-1].endswith(endline.encode(\"utf-8\")):\n            lines[-1] = lines[-1] + endline.encode(\"utf-8\")\n        for entry in self.entries:\n            try:\n                logger.verbose(\"Removing entry: %s\", entry)\n                lines.remove((entry + endline).encode(\"utf-8\"))\n            except ValueError:\n                pass\n        with open(self.file, \"wb\") as fh:\n            fh.writelines(lines)\n\n    def rollback(self) -> bool:\n        if self._saved_lines is None:\n            logger.error(\"Cannot roll back changes to %s, none were made\", self.file)\n            return False\n        logger.debug(\"Rolling %s back to previous state\", self.file)\n        with open(self.file, \"wb\") as fh:\n            fh.writelines(self._saved_lines)\n        return True\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/resolution/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/resolution/base.py",
    "content": "from typing import Callable, List, Optional\n\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.req.req_set import RequirementSet\n\nInstallRequirementProvider = Callable[\n    [str, Optional[InstallRequirement]], InstallRequirement\n]\n\n\nclass BaseResolver:\n    def resolve(\n        self, root_reqs: List[InstallRequirement], check_supported_wheels: bool\n    ) -> RequirementSet:\n        raise NotImplementedError()\n\n    def get_installation_order(\n        self, req_set: RequirementSet\n    ) -> List[InstallRequirement]:\n        raise NotImplementedError()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/resolution/legacy/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/resolution/legacy/resolver.py",
    "content": "\"\"\"Dependency Resolution\n\nThe dependency resolution in pip is performed as follows:\n\nfor top-level requirements:\n    a. only one spec allowed per project, regardless of conflicts or not.\n       otherwise a \"double requirement\" exception is raised\n    b. they override sub-dependency requirements.\nfor sub-dependencies\n    a. \"first found, wins\" (where the order is breadth first)\n\"\"\"\n\n# The following comment should be removed at some point in the future.\n# mypy: strict-optional=False\n\nimport logging\nimport sys\nfrom collections import defaultdict\nfrom itertools import chain\nfrom typing import DefaultDict, Iterable, List, Optional, Set, Tuple\n\nfrom pip._vendor.packaging import specifiers\nfrom pip._vendor.packaging.requirements import Requirement\n\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.exceptions import (\n    BestVersionAlreadyInstalled,\n    DistributionNotFound,\n    HashError,\n    HashErrors,\n    InstallationError,\n    NoneMetadataError,\n    UnsupportedPythonVersion,\n)\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.metadata import BaseDistribution\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.operations.prepare import RequirementPreparer\nfrom pip._internal.req.req_install import (\n    InstallRequirement,\n    check_invalid_constraint_type,\n)\nfrom pip._internal.req.req_set import RequirementSet\nfrom pip._internal.resolution.base import BaseResolver, InstallRequirementProvider\nfrom pip._internal.utils import compatibility_tags\nfrom pip._internal.utils.compatibility_tags import get_supported\nfrom pip._internal.utils.direct_url_helpers import direct_url_from_link\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import normalize_version_info\nfrom pip._internal.utils.packaging import check_requires_python\n\nlogger = logging.getLogger(__name__)\n\nDiscoveredDependencies = DefaultDict[str, List[InstallRequirement]]\n\n\ndef _check_dist_requires_python(\n    dist: BaseDistribution,\n    version_info: Tuple[int, int, int],\n    ignore_requires_python: bool = False,\n) -> None:\n    \"\"\"\n    Check whether the given Python version is compatible with a distribution's\n    \"Requires-Python\" value.\n\n    :param version_info: A 3-tuple of ints representing the Python\n        major-minor-micro version to check.\n    :param ignore_requires_python: Whether to ignore the \"Requires-Python\"\n        value if the given Python version isn't compatible.\n\n    :raises UnsupportedPythonVersion: When the given Python version isn't\n        compatible.\n    \"\"\"\n    # This idiosyncratically converts the SpecifierSet to str and let\n    # check_requires_python then parse it again into SpecifierSet. But this\n    # is the legacy resolver so I'm just not going to bother refactoring.\n    try:\n        requires_python = str(dist.requires_python)\n    except FileNotFoundError as e:\n        raise NoneMetadataError(dist, str(e))\n    try:\n        is_compatible = check_requires_python(\n            requires_python,\n            version_info=version_info,\n        )\n    except specifiers.InvalidSpecifier as exc:\n        logger.warning(\n            \"Package %r has an invalid Requires-Python: %s\", dist.raw_name, exc\n        )\n        return\n\n    if is_compatible:\n        return\n\n    version = \".\".join(map(str, version_info))\n    if ignore_requires_python:\n        logger.debug(\n            \"Ignoring failed Requires-Python check for package %r: %s not in %r\",\n            dist.raw_name,\n            version,\n            requires_python,\n        )\n        return\n\n    raise UnsupportedPythonVersion(\n        \"Package {!r} requires a different Python: {} not in {!r}\".format(\n            dist.raw_name, version, requires_python\n        )\n    )\n\n\nclass Resolver(BaseResolver):\n    \"\"\"Resolves which packages need to be installed/uninstalled to perform \\\n    the requested operation without breaking the requirements of any package.\n    \"\"\"\n\n    _allowed_strategies = {\"eager\", \"only-if-needed\", \"to-satisfy-only\"}\n\n    def __init__(\n        self,\n        preparer: RequirementPreparer,\n        finder: PackageFinder,\n        wheel_cache: Optional[WheelCache],\n        make_install_req: InstallRequirementProvider,\n        use_user_site: bool,\n        ignore_dependencies: bool,\n        ignore_installed: bool,\n        ignore_requires_python: bool,\n        force_reinstall: bool,\n        upgrade_strategy: str,\n        py_version_info: Optional[Tuple[int, ...]] = None,\n    ) -> None:\n        super().__init__()\n        assert upgrade_strategy in self._allowed_strategies\n\n        if py_version_info is None:\n            py_version_info = sys.version_info[:3]\n        else:\n            py_version_info = normalize_version_info(py_version_info)\n\n        self._py_version_info = py_version_info\n\n        self.preparer = preparer\n        self.finder = finder\n        self.wheel_cache = wheel_cache\n\n        self.upgrade_strategy = upgrade_strategy\n        self.force_reinstall = force_reinstall\n        self.ignore_dependencies = ignore_dependencies\n        self.ignore_installed = ignore_installed\n        self.ignore_requires_python = ignore_requires_python\n        self.use_user_site = use_user_site\n        self._make_install_req = make_install_req\n\n        self._discovered_dependencies: DiscoveredDependencies = defaultdict(list)\n\n    def resolve(\n        self, root_reqs: List[InstallRequirement], check_supported_wheels: bool\n    ) -> RequirementSet:\n        \"\"\"Resolve what operations need to be done\n\n        As a side-effect of this method, the packages (and their dependencies)\n        are downloaded, unpacked and prepared for installation. This\n        preparation is done by ``pip.operations.prepare``.\n\n        Once PyPI has static dependency metadata available, it would be\n        possible to move the preparation to become a step separated from\n        dependency resolution.\n        \"\"\"\n        requirement_set = RequirementSet(check_supported_wheels=check_supported_wheels)\n        for req in root_reqs:\n            if req.constraint:\n                check_invalid_constraint_type(req)\n            self._add_requirement_to_set(requirement_set, req)\n\n        # Actually prepare the files, and collect any exceptions. Most hash\n        # exceptions cannot be checked ahead of time, because\n        # _populate_link() needs to be called before we can make decisions\n        # based on link type.\n        discovered_reqs: List[InstallRequirement] = []\n        hash_errors = HashErrors()\n        for req in chain(requirement_set.all_requirements, discovered_reqs):\n            try:\n                discovered_reqs.extend(self._resolve_one(requirement_set, req))\n            except HashError as exc:\n                exc.req = req\n                hash_errors.append(exc)\n\n        if hash_errors:\n            raise hash_errors\n\n        return requirement_set\n\n    def _add_requirement_to_set(\n        self,\n        requirement_set: RequirementSet,\n        install_req: InstallRequirement,\n        parent_req_name: Optional[str] = None,\n        extras_requested: Optional[Iterable[str]] = None,\n    ) -> Tuple[List[InstallRequirement], Optional[InstallRequirement]]:\n        \"\"\"Add install_req as a requirement to install.\n\n        :param parent_req_name: The name of the requirement that needed this\n            added. The name is used because when multiple unnamed requirements\n            resolve to the same name, we could otherwise end up with dependency\n            links that point outside the Requirements set. parent_req must\n            already be added. Note that None implies that this is a user\n            supplied requirement, vs an inferred one.\n        :param extras_requested: an iterable of extras used to evaluate the\n            environment markers.\n        :return: Additional requirements to scan. That is either [] if\n            the requirement is not applicable, or [install_req] if the\n            requirement is applicable and has just been added.\n        \"\"\"\n        # If the markers do not match, ignore this requirement.\n        if not install_req.match_markers(extras_requested):\n            logger.info(\n                \"Ignoring %s: markers '%s' don't match your environment\",\n                install_req.name,\n                install_req.markers,\n            )\n            return [], None\n\n        # If the wheel is not supported, raise an error.\n        # Should check this after filtering out based on environment markers to\n        # allow specifying different wheels based on the environment/OS, in a\n        # single requirements file.\n        if install_req.link and install_req.link.is_wheel:\n            wheel = Wheel(install_req.link.filename)\n            tags = compatibility_tags.get_supported()\n            if requirement_set.check_supported_wheels and not wheel.supported(tags):\n                raise InstallationError(\n                    \"{} is not a supported wheel on this platform.\".format(\n                        wheel.filename\n                    )\n                )\n\n        # This next bit is really a sanity check.\n        assert (\n            not install_req.user_supplied or parent_req_name is None\n        ), \"a user supplied req shouldn't have a parent\"\n\n        # Unnamed requirements are scanned again and the requirement won't be\n        # added as a dependency until after scanning.\n        if not install_req.name:\n            requirement_set.add_unnamed_requirement(install_req)\n            return [install_req], None\n\n        try:\n            existing_req: Optional[\n                InstallRequirement\n            ] = requirement_set.get_requirement(install_req.name)\n        except KeyError:\n            existing_req = None\n\n        has_conflicting_requirement = (\n            parent_req_name is None\n            and existing_req\n            and not existing_req.constraint\n            and existing_req.extras == install_req.extras\n            and existing_req.req\n            and install_req.req\n            and existing_req.req.specifier != install_req.req.specifier\n        )\n        if has_conflicting_requirement:\n            raise InstallationError(\n                \"Double requirement given: {} (already in {}, name={!r})\".format(\n                    install_req, existing_req, install_req.name\n                )\n            )\n\n        # When no existing requirement exists, add the requirement as a\n        # dependency and it will be scanned again after.\n        if not existing_req:\n            requirement_set.add_named_requirement(install_req)\n            # We'd want to rescan this requirement later\n            return [install_req], install_req\n\n        # Assume there's no need to scan, and that we've already\n        # encountered this for scanning.\n        if install_req.constraint or not existing_req.constraint:\n            return [], existing_req\n\n        does_not_satisfy_constraint = install_req.link and not (\n            existing_req.link and install_req.link.path == existing_req.link.path\n        )\n        if does_not_satisfy_constraint:\n            raise InstallationError(\n                \"Could not satisfy constraints for '{}': \"\n                \"installation from path or url cannot be \"\n                \"constrained to a version\".format(install_req.name)\n            )\n        # If we're now installing a constraint, mark the existing\n        # object for real installation.\n        existing_req.constraint = False\n        # If we're now installing a user supplied requirement,\n        # mark the existing object as such.\n        if install_req.user_supplied:\n            existing_req.user_supplied = True\n        existing_req.extras = tuple(\n            sorted(set(existing_req.extras) | set(install_req.extras))\n        )\n        logger.debug(\n            \"Setting %s extras to: %s\",\n            existing_req,\n            existing_req.extras,\n        )\n        # Return the existing requirement for addition to the parent and\n        # scanning again.\n        return [existing_req], existing_req\n\n    def _is_upgrade_allowed(self, req: InstallRequirement) -> bool:\n        if self.upgrade_strategy == \"to-satisfy-only\":\n            return False\n        elif self.upgrade_strategy == \"eager\":\n            return True\n        else:\n            assert self.upgrade_strategy == \"only-if-needed\"\n            return req.user_supplied or req.constraint\n\n    def _set_req_to_reinstall(self, req: InstallRequirement) -> None:\n        \"\"\"\n        Set a requirement to be installed.\n        \"\"\"\n        # Don't uninstall the conflict if doing a user install and the\n        # conflict is not a user install.\n        if not self.use_user_site or req.satisfied_by.in_usersite:\n            req.should_reinstall = True\n        req.satisfied_by = None\n\n    def _check_skip_installed(\n        self, req_to_install: InstallRequirement\n    ) -> Optional[str]:\n        \"\"\"Check if req_to_install should be skipped.\n\n        This will check if the req is installed, and whether we should upgrade\n        or reinstall it, taking into account all the relevant user options.\n\n        After calling this req_to_install will only have satisfied_by set to\n        None if the req_to_install is to be upgraded/reinstalled etc. Any\n        other value will be a dist recording the current thing installed that\n        satisfies the requirement.\n\n        Note that for vcs urls and the like we can't assess skipping in this\n        routine - we simply identify that we need to pull the thing down,\n        then later on it is pulled down and introspected to assess upgrade/\n        reinstalls etc.\n\n        :return: A text reason for why it was skipped, or None.\n        \"\"\"\n        if self.ignore_installed:\n            return None\n\n        req_to_install.check_if_exists(self.use_user_site)\n        if not req_to_install.satisfied_by:\n            return None\n\n        if self.force_reinstall:\n            self._set_req_to_reinstall(req_to_install)\n            return None\n\n        if not self._is_upgrade_allowed(req_to_install):\n            if self.upgrade_strategy == \"only-if-needed\":\n                return \"already satisfied, skipping upgrade\"\n            return \"already satisfied\"\n\n        # Check for the possibility of an upgrade.  For link-based\n        # requirements we have to pull the tree down and inspect to assess\n        # the version #, so it's handled way down.\n        if not req_to_install.link:\n            try:\n                self.finder.find_requirement(req_to_install, upgrade=True)\n            except BestVersionAlreadyInstalled:\n                # Then the best version is installed.\n                return \"already up-to-date\"\n            except DistributionNotFound:\n                # No distribution found, so we squash the error.  It will\n                # be raised later when we re-try later to do the install.\n                # Why don't we just raise here?\n                pass\n\n        self._set_req_to_reinstall(req_to_install)\n        return None\n\n    def _find_requirement_link(self, req: InstallRequirement) -> Optional[Link]:\n        upgrade = self._is_upgrade_allowed(req)\n        best_candidate = self.finder.find_requirement(req, upgrade)\n        if not best_candidate:\n            return None\n\n        # Log a warning per PEP 592 if necessary before returning.\n        link = best_candidate.link\n        if link.is_yanked:\n            reason = link.yanked_reason or \"<none given>\"\n            msg = (\n                # Mark this as a unicode string to prevent\n                # \"UnicodeEncodeError: 'ascii' codec can't encode character\"\n                # in Python 2 when the reason contains non-ascii characters.\n                \"The candidate selected for download or install is a \"\n                \"yanked version: {candidate}\\n\"\n                \"Reason for being yanked: {reason}\"\n            ).format(candidate=best_candidate, reason=reason)\n            logger.warning(msg)\n\n        return link\n\n    def _populate_link(self, req: InstallRequirement) -> None:\n        \"\"\"Ensure that if a link can be found for this, that it is found.\n\n        Note that req.link may still be None - if the requirement is already\n        installed and not needed to be upgraded based on the return value of\n        _is_upgrade_allowed().\n\n        If preparer.require_hashes is True, don't use the wheel cache, because\n        cached wheels, always built locally, have different hashes than the\n        files downloaded from the index server and thus throw false hash\n        mismatches. Furthermore, cached wheels at present have undeterministic\n        contents due to file modification times.\n        \"\"\"\n        if req.link is None:\n            req.link = self._find_requirement_link(req)\n\n        if self.wheel_cache is None or self.preparer.require_hashes:\n            return\n        cache_entry = self.wheel_cache.get_cache_entry(\n            link=req.link,\n            package_name=req.name,\n            supported_tags=get_supported(),\n        )\n        if cache_entry is not None:\n            logger.debug(\"Using cached wheel link: %s\", cache_entry.link)\n            if req.link is req.original_link and cache_entry.persistent:\n                req.original_link_is_in_wheel_cache = True\n            if cache_entry.origin is not None:\n                req.download_info = cache_entry.origin\n            else:\n                # Legacy cache entry that does not have origin.json.\n                # download_info may miss the archive_info.hash field.\n                req.download_info = direct_url_from_link(\n                    req.link, link_is_in_wheel_cache=cache_entry.persistent\n                )\n            req.link = cache_entry.link\n\n    def _get_dist_for(self, req: InstallRequirement) -> BaseDistribution:\n        \"\"\"Takes a InstallRequirement and returns a single AbstractDist \\\n        representing a prepared variant of the same.\n        \"\"\"\n        if req.editable:\n            return self.preparer.prepare_editable_requirement(req)\n\n        # satisfied_by is only evaluated by calling _check_skip_installed,\n        # so it must be None here.\n        assert req.satisfied_by is None\n        skip_reason = self._check_skip_installed(req)\n\n        if req.satisfied_by:\n            return self.preparer.prepare_installed_requirement(req, skip_reason)\n\n        # We eagerly populate the link, since that's our \"legacy\" behavior.\n        self._populate_link(req)\n        dist = self.preparer.prepare_linked_requirement(req)\n\n        # NOTE\n        # The following portion is for determining if a certain package is\n        # going to be re-installed/upgraded or not and reporting to the user.\n        # This should probably get cleaned up in a future refactor.\n\n        # req.req is only avail after unpack for URL\n        # pkgs repeat check_if_exists to uninstall-on-upgrade\n        # (#14)\n        if not self.ignore_installed:\n            req.check_if_exists(self.use_user_site)\n\n        if req.satisfied_by:\n            should_modify = (\n                self.upgrade_strategy != \"to-satisfy-only\"\n                or self.force_reinstall\n                or self.ignore_installed\n                or req.link.scheme == \"file\"\n            )\n            if should_modify:\n                self._set_req_to_reinstall(req)\n            else:\n                logger.info(\n                    \"Requirement already satisfied (use --upgrade to upgrade): %s\",\n                    req,\n                )\n        return dist\n\n    def _resolve_one(\n        self,\n        requirement_set: RequirementSet,\n        req_to_install: InstallRequirement,\n    ) -> List[InstallRequirement]:\n        \"\"\"Prepare a single requirements file.\n\n        :return: A list of additional InstallRequirements to also install.\n        \"\"\"\n        # Tell user what we are doing for this requirement:\n        # obtain (editable), skipping, processing (local url), collecting\n        # (remote url or package name)\n        if req_to_install.constraint or req_to_install.prepared:\n            return []\n\n        req_to_install.prepared = True\n\n        # Parse and return dependencies\n        dist = self._get_dist_for(req_to_install)\n        # This will raise UnsupportedPythonVersion if the given Python\n        # version isn't compatible with the distribution's Requires-Python.\n        _check_dist_requires_python(\n            dist,\n            version_info=self._py_version_info,\n            ignore_requires_python=self.ignore_requires_python,\n        )\n\n        more_reqs: List[InstallRequirement] = []\n\n        def add_req(subreq: Requirement, extras_requested: Iterable[str]) -> None:\n            # This idiosyncratically converts the Requirement to str and let\n            # make_install_req then parse it again into Requirement. But this is\n            # the legacy resolver so I'm just not going to bother refactoring.\n            sub_install_req = self._make_install_req(str(subreq), req_to_install)\n            parent_req_name = req_to_install.name\n            to_scan_again, add_to_parent = self._add_requirement_to_set(\n                requirement_set,\n                sub_install_req,\n                parent_req_name=parent_req_name,\n                extras_requested=extras_requested,\n            )\n            if parent_req_name and add_to_parent:\n                self._discovered_dependencies[parent_req_name].append(add_to_parent)\n            more_reqs.extend(to_scan_again)\n\n        with indent_log():\n            # We add req_to_install before its dependencies, so that we\n            # can refer to it when adding dependencies.\n            if not requirement_set.has_requirement(req_to_install.name):\n                # 'unnamed' requirements will get added here\n                # 'unnamed' requirements can only come from being directly\n                # provided by the user.\n                assert req_to_install.user_supplied\n                self._add_requirement_to_set(\n                    requirement_set, req_to_install, parent_req_name=None\n                )\n\n            if not self.ignore_dependencies:\n                if req_to_install.extras:\n                    logger.debug(\n                        \"Installing extra requirements: %r\",\n                        \",\".join(req_to_install.extras),\n                    )\n                missing_requested = sorted(\n                    set(req_to_install.extras) - set(dist.iter_provided_extras())\n                )\n                for missing in missing_requested:\n                    logger.warning(\n                        \"%s %s does not provide the extra '%s'\",\n                        dist.raw_name,\n                        dist.version,\n                        missing,\n                    )\n\n                available_requested = sorted(\n                    set(dist.iter_provided_extras()) & set(req_to_install.extras)\n                )\n                for subreq in dist.iter_dependencies(available_requested):\n                    add_req(subreq, extras_requested=available_requested)\n\n        return more_reqs\n\n    def get_installation_order(\n        self, req_set: RequirementSet\n    ) -> List[InstallRequirement]:\n        \"\"\"Create the installation order.\n\n        The installation order is topological - requirements are installed\n        before the requiring thing. We break cycles at an arbitrary point,\n        and make no other guarantees.\n        \"\"\"\n        # The current implementation, which we may change at any point\n        # installs the user specified things in the order given, except when\n        # dependencies must come earlier to achieve topological order.\n        order = []\n        ordered_reqs: Set[InstallRequirement] = set()\n\n        def schedule(req: InstallRequirement) -> None:\n            if req.satisfied_by or req in ordered_reqs:\n                return\n            if req.constraint:\n                return\n            ordered_reqs.add(req)\n            for dep in self._discovered_dependencies[req.name]:\n                schedule(dep)\n            order.append(req)\n\n        for install_req in req_set.requirements.values():\n            schedule(install_req)\n        return order\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/base.py",
    "content": "from typing import FrozenSet, Iterable, Optional, Tuple, Union\n\nfrom pip._vendor.packaging.specifiers import SpecifierSet\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\nfrom pip._vendor.packaging.version import LegacyVersion, Version\n\nfrom pip._internal.models.link import Link, links_equivalent\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.utils.hashes import Hashes\n\nCandidateLookup = Tuple[Optional[\"Candidate\"], Optional[InstallRequirement]]\nCandidateVersion = Union[LegacyVersion, Version]\n\n\ndef format_name(project: str, extras: FrozenSet[str]) -> str:\n    if not extras:\n        return project\n    canonical_extras = sorted(canonicalize_name(e) for e in extras)\n    return \"{}[{}]\".format(project, \",\".join(canonical_extras))\n\n\nclass Constraint:\n    def __init__(\n        self, specifier: SpecifierSet, hashes: Hashes, links: FrozenSet[Link]\n    ) -> None:\n        self.specifier = specifier\n        self.hashes = hashes\n        self.links = links\n\n    @classmethod\n    def empty(cls) -> \"Constraint\":\n        return Constraint(SpecifierSet(), Hashes(), frozenset())\n\n    @classmethod\n    def from_ireq(cls, ireq: InstallRequirement) -> \"Constraint\":\n        links = frozenset([ireq.link]) if ireq.link else frozenset()\n        return Constraint(ireq.specifier, ireq.hashes(trust_internet=False), links)\n\n    def __bool__(self) -> bool:\n        return bool(self.specifier) or bool(self.hashes) or bool(self.links)\n\n    def __and__(self, other: InstallRequirement) -> \"Constraint\":\n        if not isinstance(other, InstallRequirement):\n            return NotImplemented\n        specifier = self.specifier & other.specifier\n        hashes = self.hashes & other.hashes(trust_internet=False)\n        links = self.links\n        if other.link:\n            links = links.union([other.link])\n        return Constraint(specifier, hashes, links)\n\n    def is_satisfied_by(self, candidate: \"Candidate\") -> bool:\n        # Reject if there are any mismatched URL constraints on this package.\n        if self.links and not all(_match_link(link, candidate) for link in self.links):\n            return False\n        # We can safely always allow prereleases here since PackageFinder\n        # already implements the prerelease logic, and would have filtered out\n        # prerelease candidates if the user does not expect them.\n        return self.specifier.contains(candidate.version, prereleases=True)\n\n\nclass Requirement:\n    @property\n    def project_name(self) -> NormalizedName:\n        \"\"\"The \"project name\" of a requirement.\n\n        This is different from ``name`` if this requirement contains extras,\n        in which case ``name`` would contain the ``[...]`` part, while this\n        refers to the name of the project.\n        \"\"\"\n        raise NotImplementedError(\"Subclass should override\")\n\n    @property\n    def name(self) -> str:\n        \"\"\"The name identifying this requirement in the resolver.\n\n        This is different from ``project_name`` if this requirement contains\n        extras, where ``project_name`` would not contain the ``[...]`` part.\n        \"\"\"\n        raise NotImplementedError(\"Subclass should override\")\n\n    def is_satisfied_by(self, candidate: \"Candidate\") -> bool:\n        return False\n\n    def get_candidate_lookup(self) -> CandidateLookup:\n        raise NotImplementedError(\"Subclass should override\")\n\n    def format_for_error(self) -> str:\n        raise NotImplementedError(\"Subclass should override\")\n\n\ndef _match_link(link: Link, candidate: \"Candidate\") -> bool:\n    if candidate.source_link:\n        return links_equivalent(link, candidate.source_link)\n    return False\n\n\nclass Candidate:\n    @property\n    def project_name(self) -> NormalizedName:\n        \"\"\"The \"project name\" of the candidate.\n\n        This is different from ``name`` if this candidate contains extras,\n        in which case ``name`` would contain the ``[...]`` part, while this\n        refers to the name of the project.\n        \"\"\"\n        raise NotImplementedError(\"Override in subclass\")\n\n    @property\n    def name(self) -> str:\n        \"\"\"The name identifying this candidate in the resolver.\n\n        This is different from ``project_name`` if this candidate contains\n        extras, where ``project_name`` would not contain the ``[...]`` part.\n        \"\"\"\n        raise NotImplementedError(\"Override in subclass\")\n\n    @property\n    def version(self) -> CandidateVersion:\n        raise NotImplementedError(\"Override in subclass\")\n\n    @property\n    def is_installed(self) -> bool:\n        raise NotImplementedError(\"Override in subclass\")\n\n    @property\n    def is_editable(self) -> bool:\n        raise NotImplementedError(\"Override in subclass\")\n\n    @property\n    def source_link(self) -> Optional[Link]:\n        raise NotImplementedError(\"Override in subclass\")\n\n    def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]:\n        raise NotImplementedError(\"Override in subclass\")\n\n    def get_install_requirement(self) -> Optional[InstallRequirement]:\n        raise NotImplementedError(\"Override in subclass\")\n\n    def format_for_error(self) -> str:\n        raise NotImplementedError(\"Subclass should override\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/candidates.py",
    "content": "import logging\nimport sys\nfrom typing import TYPE_CHECKING, Any, FrozenSet, Iterable, Optional, Tuple, Union, cast\n\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\nfrom pip._vendor.packaging.version import Version\n\nfrom pip._internal.exceptions import (\n    HashError,\n    InstallationSubprocessError,\n    MetadataInconsistent,\n)\nfrom pip._internal.metadata import BaseDistribution\nfrom pip._internal.models.link import Link, links_equivalent\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.req.constructors import (\n    install_req_from_editable,\n    install_req_from_line,\n)\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.utils.direct_url_helpers import direct_url_from_link\nfrom pip._internal.utils.misc import normalize_version_info\n\nfrom .base import Candidate, CandidateVersion, Requirement, format_name\n\nif TYPE_CHECKING:\n    from .factory import Factory\n\nlogger = logging.getLogger(__name__)\n\nBaseCandidate = Union[\n    \"AlreadyInstalledCandidate\",\n    \"EditableCandidate\",\n    \"LinkCandidate\",\n]\n\n# Avoid conflicting with the PyPI package \"Python\".\nREQUIRES_PYTHON_IDENTIFIER = cast(NormalizedName, \"<Python from Requires-Python>\")\n\n\ndef as_base_candidate(candidate: Candidate) -> Optional[BaseCandidate]:\n    \"\"\"The runtime version of BaseCandidate.\"\"\"\n    base_candidate_classes = (\n        AlreadyInstalledCandidate,\n        EditableCandidate,\n        LinkCandidate,\n    )\n    if isinstance(candidate, base_candidate_classes):\n        return candidate\n    return None\n\n\ndef make_install_req_from_link(\n    link: Link, template: InstallRequirement\n) -> InstallRequirement:\n    assert not template.editable, \"template is editable\"\n    if template.req:\n        line = str(template.req)\n    else:\n        line = link.url\n    ireq = install_req_from_line(\n        line,\n        user_supplied=template.user_supplied,\n        comes_from=template.comes_from,\n        use_pep517=template.use_pep517,\n        isolated=template.isolated,\n        constraint=template.constraint,\n        options=dict(\n            install_options=template.install_options,\n            global_options=template.global_options,\n            hashes=template.hash_options,\n        ),\n        config_settings=template.config_settings,\n    )\n    ireq.original_link = template.original_link\n    ireq.link = link\n    return ireq\n\n\ndef make_install_req_from_editable(\n    link: Link, template: InstallRequirement\n) -> InstallRequirement:\n    assert template.editable, \"template not editable\"\n    return install_req_from_editable(\n        link.url,\n        user_supplied=template.user_supplied,\n        comes_from=template.comes_from,\n        use_pep517=template.use_pep517,\n        isolated=template.isolated,\n        constraint=template.constraint,\n        permit_editable_wheels=template.permit_editable_wheels,\n        options=dict(\n            install_options=template.install_options,\n            global_options=template.global_options,\n            hashes=template.hash_options,\n        ),\n        config_settings=template.config_settings,\n    )\n\n\ndef _make_install_req_from_dist(\n    dist: BaseDistribution, template: InstallRequirement\n) -> InstallRequirement:\n    if template.req:\n        line = str(template.req)\n    elif template.link:\n        line = f\"{dist.canonical_name} @ {template.link.url}\"\n    else:\n        line = f\"{dist.canonical_name}=={dist.version}\"\n    ireq = install_req_from_line(\n        line,\n        user_supplied=template.user_supplied,\n        comes_from=template.comes_from,\n        use_pep517=template.use_pep517,\n        isolated=template.isolated,\n        constraint=template.constraint,\n        options=dict(\n            install_options=template.install_options,\n            global_options=template.global_options,\n            hashes=template.hash_options,\n        ),\n        config_settings=template.config_settings,\n    )\n    ireq.satisfied_by = dist\n    return ireq\n\n\nclass _InstallRequirementBackedCandidate(Candidate):\n    \"\"\"A candidate backed by an ``InstallRequirement``.\n\n    This represents a package request with the target not being already\n    in the environment, and needs to be fetched and installed. The backing\n    ``InstallRequirement`` is responsible for most of the leg work; this\n    class exposes appropriate information to the resolver.\n\n    :param link: The link passed to the ``InstallRequirement``. The backing\n        ``InstallRequirement`` will use this link to fetch the distribution.\n    :param source_link: The link this candidate \"originates\" from. This is\n        different from ``link`` when the link is found in the wheel cache.\n        ``link`` would point to the wheel cache, while this points to the\n        found remote link (e.g. from pypi.org).\n    \"\"\"\n\n    dist: BaseDistribution\n    is_installed = False\n\n    def __init__(\n        self,\n        link: Link,\n        source_link: Link,\n        ireq: InstallRequirement,\n        factory: \"Factory\",\n        name: Optional[NormalizedName] = None,\n        version: Optional[CandidateVersion] = None,\n    ) -> None:\n        self._link = link\n        self._source_link = source_link\n        self._factory = factory\n        self._ireq = ireq\n        self._name = name\n        self._version = version\n        self.dist = self._prepare()\n\n    def __str__(self) -> str:\n        return f\"{self.name} {self.version}\"\n\n    def __repr__(self) -> str:\n        return \"{class_name}({link!r})\".format(\n            class_name=self.__class__.__name__,\n            link=str(self._link),\n        )\n\n    def __hash__(self) -> int:\n        return hash((self.__class__, self._link))\n\n    def __eq__(self, other: Any) -> bool:\n        if isinstance(other, self.__class__):\n            return links_equivalent(self._link, other._link)\n        return False\n\n    @property\n    def source_link(self) -> Optional[Link]:\n        return self._source_link\n\n    @property\n    def project_name(self) -> NormalizedName:\n        \"\"\"The normalised name of the project the candidate refers to\"\"\"\n        if self._name is None:\n            self._name = self.dist.canonical_name\n        return self._name\n\n    @property\n    def name(self) -> str:\n        return self.project_name\n\n    @property\n    def version(self) -> CandidateVersion:\n        if self._version is None:\n            self._version = self.dist.version\n        return self._version\n\n    def format_for_error(self) -> str:\n        return \"{} {} (from {})\".format(\n            self.name,\n            self.version,\n            self._link.file_path if self._link.is_file else self._link,\n        )\n\n    def _prepare_distribution(self) -> BaseDistribution:\n        raise NotImplementedError(\"Override in subclass\")\n\n    def _check_metadata_consistency(self, dist: BaseDistribution) -> None:\n        \"\"\"Check for consistency of project name and version of dist.\"\"\"\n        if self._name is not None and self._name != dist.canonical_name:\n            raise MetadataInconsistent(\n                self._ireq,\n                \"name\",\n                self._name,\n                dist.canonical_name,\n            )\n        if self._version is not None and self._version != dist.version:\n            raise MetadataInconsistent(\n                self._ireq,\n                \"version\",\n                str(self._version),\n                str(dist.version),\n            )\n\n    def _prepare(self) -> BaseDistribution:\n        try:\n            dist = self._prepare_distribution()\n        except HashError as e:\n            # Provide HashError the underlying ireq that caused it. This\n            # provides context for the resulting error message to show the\n            # offending line to the user.\n            e.req = self._ireq\n            raise\n        except InstallationSubprocessError as exc:\n            # The output has been presented already, so don't duplicate it.\n            exc.context = \"See above for output.\"\n            raise\n\n        self._check_metadata_consistency(dist)\n        return dist\n\n    def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]:\n        requires = self.dist.iter_dependencies() if with_requires else ()\n        for r in requires:\n            yield self._factory.make_requirement_from_spec(str(r), self._ireq)\n        yield self._factory.make_requires_python_requirement(self.dist.requires_python)\n\n    def get_install_requirement(self) -> Optional[InstallRequirement]:\n        return self._ireq\n\n\nclass LinkCandidate(_InstallRequirementBackedCandidate):\n    is_editable = False\n\n    def __init__(\n        self,\n        link: Link,\n        template: InstallRequirement,\n        factory: \"Factory\",\n        name: Optional[NormalizedName] = None,\n        version: Optional[CandidateVersion] = None,\n    ) -> None:\n        source_link = link\n        cache_entry = factory.get_wheel_cache_entry(link, name)\n        if cache_entry is not None:\n            logger.debug(\"Using cached wheel link: %s\", cache_entry.link)\n            link = cache_entry.link\n        ireq = make_install_req_from_link(link, template)\n        assert ireq.link == link\n        if ireq.link.is_wheel and not ireq.link.is_file:\n            wheel = Wheel(ireq.link.filename)\n            wheel_name = canonicalize_name(wheel.name)\n            assert name == wheel_name, f\"{name!r} != {wheel_name!r} for wheel\"\n            # Version may not be present for PEP 508 direct URLs\n            if version is not None:\n                wheel_version = Version(wheel.version)\n                assert version == wheel_version, \"{!r} != {!r} for wheel {}\".format(\n                    version, wheel_version, name\n                )\n\n        if cache_entry is not None:\n            if cache_entry.persistent and template.link is template.original_link:\n                ireq.original_link_is_in_wheel_cache = True\n            if cache_entry.origin is not None:\n                ireq.download_info = cache_entry.origin\n            else:\n                # Legacy cache entry that does not have origin.json.\n                # download_info may miss the archive_info.hash field.\n                ireq.download_info = direct_url_from_link(\n                    source_link, link_is_in_wheel_cache=cache_entry.persistent\n                )\n\n        super().__init__(\n            link=link,\n            source_link=source_link,\n            ireq=ireq,\n            factory=factory,\n            name=name,\n            version=version,\n        )\n\n    def _prepare_distribution(self) -> BaseDistribution:\n        preparer = self._factory.preparer\n        return preparer.prepare_linked_requirement(self._ireq, parallel_builds=True)\n\n\nclass EditableCandidate(_InstallRequirementBackedCandidate):\n    is_editable = True\n\n    def __init__(\n        self,\n        link: Link,\n        template: InstallRequirement,\n        factory: \"Factory\",\n        name: Optional[NormalizedName] = None,\n        version: Optional[CandidateVersion] = None,\n    ) -> None:\n        super().__init__(\n            link=link,\n            source_link=link,\n            ireq=make_install_req_from_editable(link, template),\n            factory=factory,\n            name=name,\n            version=version,\n        )\n\n    def _prepare_distribution(self) -> BaseDistribution:\n        return self._factory.preparer.prepare_editable_requirement(self._ireq)\n\n\nclass AlreadyInstalledCandidate(Candidate):\n    is_installed = True\n    source_link = None\n\n    def __init__(\n        self,\n        dist: BaseDistribution,\n        template: InstallRequirement,\n        factory: \"Factory\",\n    ) -> None:\n        self.dist = dist\n        self._ireq = _make_install_req_from_dist(dist, template)\n        self._factory = factory\n\n        # This is just logging some messages, so we can do it eagerly.\n        # The returned dist would be exactly the same as self.dist because we\n        # set satisfied_by in _make_install_req_from_dist.\n        # TODO: Supply reason based on force_reinstall and upgrade_strategy.\n        skip_reason = \"already satisfied\"\n        factory.preparer.prepare_installed_requirement(self._ireq, skip_reason)\n\n    def __str__(self) -> str:\n        return str(self.dist)\n\n    def __repr__(self) -> str:\n        return \"{class_name}({distribution!r})\".format(\n            class_name=self.__class__.__name__,\n            distribution=self.dist,\n        )\n\n    def __hash__(self) -> int:\n        return hash((self.__class__, self.name, self.version))\n\n    def __eq__(self, other: Any) -> bool:\n        if isinstance(other, self.__class__):\n            return self.name == other.name and self.version == other.version\n        return False\n\n    @property\n    def project_name(self) -> NormalizedName:\n        return self.dist.canonical_name\n\n    @property\n    def name(self) -> str:\n        return self.project_name\n\n    @property\n    def version(self) -> CandidateVersion:\n        return self.dist.version\n\n    @property\n    def is_editable(self) -> bool:\n        return self.dist.editable\n\n    def format_for_error(self) -> str:\n        return f\"{self.name} {self.version} (Installed)\"\n\n    def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]:\n        if not with_requires:\n            return\n        for r in self.dist.iter_dependencies():\n            yield self._factory.make_requirement_from_spec(str(r), self._ireq)\n\n    def get_install_requirement(self) -> Optional[InstallRequirement]:\n        return None\n\n\nclass ExtrasCandidate(Candidate):\n    \"\"\"A candidate that has 'extras', indicating additional dependencies.\n\n    Requirements can be for a project with dependencies, something like\n    foo[extra].  The extras don't affect the project/version being installed\n    directly, but indicate that we need additional dependencies. We model that\n    by having an artificial ExtrasCandidate that wraps the \"base\" candidate.\n\n    The ExtrasCandidate differs from the base in the following ways:\n\n    1. It has a unique name, of the form foo[extra]. This causes the resolver\n       to treat it as a separate node in the dependency graph.\n    2. When we're getting the candidate's dependencies,\n       a) We specify that we want the extra dependencies as well.\n       b) We add a dependency on the base candidate.\n          See below for why this is needed.\n    3. We return None for the underlying InstallRequirement, as the base\n       candidate will provide it, and we don't want to end up with duplicates.\n\n    The dependency on the base candidate is needed so that the resolver can't\n    decide that it should recommend foo[extra1] version 1.0 and foo[extra2]\n    version 2.0. Having those candidates depend on foo=1.0 and foo=2.0\n    respectively forces the resolver to recognise that this is a conflict.\n    \"\"\"\n\n    def __init__(\n        self,\n        base: BaseCandidate,\n        extras: FrozenSet[str],\n    ) -> None:\n        self.base = base\n        self.extras = extras\n\n    def __str__(self) -> str:\n        name, rest = str(self.base).split(\" \", 1)\n        return \"{}[{}] {}\".format(name, \",\".join(self.extras), rest)\n\n    def __repr__(self) -> str:\n        return \"{class_name}(base={base!r}, extras={extras!r})\".format(\n            class_name=self.__class__.__name__,\n            base=self.base,\n            extras=self.extras,\n        )\n\n    def __hash__(self) -> int:\n        return hash((self.base, self.extras))\n\n    def __eq__(self, other: Any) -> bool:\n        if isinstance(other, self.__class__):\n            return self.base == other.base and self.extras == other.extras\n        return False\n\n    @property\n    def project_name(self) -> NormalizedName:\n        return self.base.project_name\n\n    @property\n    def name(self) -> str:\n        \"\"\"The normalised name of the project the candidate refers to\"\"\"\n        return format_name(self.base.project_name, self.extras)\n\n    @property\n    def version(self) -> CandidateVersion:\n        return self.base.version\n\n    def format_for_error(self) -> str:\n        return \"{} [{}]\".format(\n            self.base.format_for_error(), \", \".join(sorted(self.extras))\n        )\n\n    @property\n    def is_installed(self) -> bool:\n        return self.base.is_installed\n\n    @property\n    def is_editable(self) -> bool:\n        return self.base.is_editable\n\n    @property\n    def source_link(self) -> Optional[Link]:\n        return self.base.source_link\n\n    def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]:\n        factory = self.base._factory\n\n        # Add a dependency on the exact base\n        # (See note 2b in the class docstring)\n        yield factory.make_requirement_from_candidate(self.base)\n        if not with_requires:\n            return\n\n        # The user may have specified extras that the candidate doesn't\n        # support. We ignore any unsupported extras here.\n        valid_extras = self.extras.intersection(self.base.dist.iter_provided_extras())\n        invalid_extras = self.extras.difference(self.base.dist.iter_provided_extras())\n        for extra in sorted(invalid_extras):\n            logger.warning(\n                \"%s %s does not provide the extra '%s'\",\n                self.base.name,\n                self.version,\n                extra,\n            )\n\n        for r in self.base.dist.iter_dependencies(valid_extras):\n            requirement = factory.make_requirement_from_spec(\n                str(r), self.base._ireq, valid_extras\n            )\n            if requirement:\n                yield requirement\n\n    def get_install_requirement(self) -> Optional[InstallRequirement]:\n        # We don't return anything here, because we always\n        # depend on the base candidate, and we'll get the\n        # install requirement from that.\n        return None\n\n\nclass RequiresPythonCandidate(Candidate):\n    is_installed = False\n    source_link = None\n\n    def __init__(self, py_version_info: Optional[Tuple[int, ...]]) -> None:\n        if py_version_info is not None:\n            version_info = normalize_version_info(py_version_info)\n        else:\n            version_info = sys.version_info[:3]\n        self._version = Version(\".\".join(str(c) for c in version_info))\n\n    # We don't need to implement __eq__() and __ne__() since there is always\n    # only one RequiresPythonCandidate in a resolution, i.e. the host Python.\n    # The built-in object.__eq__() and object.__ne__() do exactly what we want.\n\n    def __str__(self) -> str:\n        return f\"Python {self._version}\"\n\n    @property\n    def project_name(self) -> NormalizedName:\n        return REQUIRES_PYTHON_IDENTIFIER\n\n    @property\n    def name(self) -> str:\n        return REQUIRES_PYTHON_IDENTIFIER\n\n    @property\n    def version(self) -> CandidateVersion:\n        return self._version\n\n    def format_for_error(self) -> str:\n        return f\"Python {self.version}\"\n\n    def iter_dependencies(self, with_requires: bool) -> Iterable[Optional[Requirement]]:\n        return ()\n\n    def get_install_requirement(self) -> Optional[InstallRequirement]:\n        return None\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/factory.py",
    "content": "import contextlib\nimport functools\nimport logging\nfrom typing import (\n    TYPE_CHECKING,\n    Dict,\n    FrozenSet,\n    Iterable,\n    Iterator,\n    List,\n    Mapping,\n    NamedTuple,\n    Optional,\n    Sequence,\n    Set,\n    Tuple,\n    TypeVar,\n    cast,\n)\n\nfrom pip._vendor.packaging.requirements import InvalidRequirement\nfrom pip._vendor.packaging.specifiers import SpecifierSet\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\nfrom pip._vendor.resolvelib import ResolutionImpossible\n\nfrom pip._internal.cache import CacheEntry, WheelCache\nfrom pip._internal.exceptions import (\n    DistributionNotFound,\n    InstallationError,\n    MetadataInconsistent,\n    UnsupportedPythonVersion,\n    UnsupportedWheel,\n)\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.metadata import BaseDistribution, get_default_environment\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.operations.prepare import RequirementPreparer\nfrom pip._internal.req.constructors import install_req_from_link_and_ireq\nfrom pip._internal.req.req_install import (\n    InstallRequirement,\n    check_invalid_constraint_type,\n)\nfrom pip._internal.resolution.base import InstallRequirementProvider\nfrom pip._internal.utils.compatibility_tags import get_supported\nfrom pip._internal.utils.hashes import Hashes\nfrom pip._internal.utils.packaging import get_requirement\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\nfrom .base import Candidate, CandidateVersion, Constraint, Requirement\nfrom .candidates import (\n    AlreadyInstalledCandidate,\n    BaseCandidate,\n    EditableCandidate,\n    ExtrasCandidate,\n    LinkCandidate,\n    RequiresPythonCandidate,\n    as_base_candidate,\n)\nfrom .found_candidates import FoundCandidates, IndexCandidateInfo\nfrom .requirements import (\n    ExplicitRequirement,\n    RequiresPythonRequirement,\n    SpecifierRequirement,\n    UnsatisfiableRequirement,\n)\n\nif TYPE_CHECKING:\n    from typing import Protocol\n\n    class ConflictCause(Protocol):\n        requirement: RequiresPythonRequirement\n        parent: Candidate\n\n\nlogger = logging.getLogger(__name__)\n\nC = TypeVar(\"C\")\nCache = Dict[Link, C]\n\n\nclass CollectedRootRequirements(NamedTuple):\n    requirements: List[Requirement]\n    constraints: Dict[str, Constraint]\n    user_requested: Dict[str, int]\n\n\nclass Factory:\n    def __init__(\n        self,\n        finder: PackageFinder,\n        preparer: RequirementPreparer,\n        make_install_req: InstallRequirementProvider,\n        wheel_cache: Optional[WheelCache],\n        use_user_site: bool,\n        force_reinstall: bool,\n        ignore_installed: bool,\n        ignore_requires_python: bool,\n        py_version_info: Optional[Tuple[int, ...]] = None,\n    ) -> None:\n        self._finder = finder\n        self.preparer = preparer\n        self._wheel_cache = wheel_cache\n        self._python_candidate = RequiresPythonCandidate(py_version_info)\n        self._make_install_req_from_spec = make_install_req\n        self._use_user_site = use_user_site\n        self._force_reinstall = force_reinstall\n        self._ignore_requires_python = ignore_requires_python\n\n        self._build_failures: Cache[InstallationError] = {}\n        self._link_candidate_cache: Cache[LinkCandidate] = {}\n        self._editable_candidate_cache: Cache[EditableCandidate] = {}\n        self._installed_candidate_cache: Dict[str, AlreadyInstalledCandidate] = {}\n        self._extras_candidate_cache: Dict[\n            Tuple[int, FrozenSet[str]], ExtrasCandidate\n        ] = {}\n\n        if not ignore_installed:\n            env = get_default_environment()\n            self._installed_dists = {\n                dist.canonical_name: dist\n                for dist in env.iter_installed_distributions(local_only=False)\n            }\n        else:\n            self._installed_dists = {}\n\n    @property\n    def force_reinstall(self) -> bool:\n        return self._force_reinstall\n\n    def _fail_if_link_is_unsupported_wheel(self, link: Link) -> None:\n        if not link.is_wheel:\n            return\n        wheel = Wheel(link.filename)\n        if wheel.supported(self._finder.target_python.get_tags()):\n            return\n        msg = f\"{link.filename} is not a supported wheel on this platform.\"\n        raise UnsupportedWheel(msg)\n\n    def _make_extras_candidate(\n        self, base: BaseCandidate, extras: FrozenSet[str]\n    ) -> ExtrasCandidate:\n        cache_key = (id(base), extras)\n        try:\n            candidate = self._extras_candidate_cache[cache_key]\n        except KeyError:\n            candidate = ExtrasCandidate(base, extras)\n            self._extras_candidate_cache[cache_key] = candidate\n        return candidate\n\n    def _make_candidate_from_dist(\n        self,\n        dist: BaseDistribution,\n        extras: FrozenSet[str],\n        template: InstallRequirement,\n    ) -> Candidate:\n        try:\n            base = self._installed_candidate_cache[dist.canonical_name]\n        except KeyError:\n            base = AlreadyInstalledCandidate(dist, template, factory=self)\n            self._installed_candidate_cache[dist.canonical_name] = base\n        if not extras:\n            return base\n        return self._make_extras_candidate(base, extras)\n\n    def _make_candidate_from_link(\n        self,\n        link: Link,\n        extras: FrozenSet[str],\n        template: InstallRequirement,\n        name: Optional[NormalizedName],\n        version: Optional[CandidateVersion],\n    ) -> Optional[Candidate]:\n        # TODO: Check already installed candidate, and use it if the link and\n        # editable flag match.\n\n        if link in self._build_failures:\n            # We already tried this candidate before, and it does not build.\n            # Don't bother trying again.\n            return None\n\n        if template.editable:\n            if link not in self._editable_candidate_cache:\n                try:\n                    self._editable_candidate_cache[link] = EditableCandidate(\n                        link,\n                        template,\n                        factory=self,\n                        name=name,\n                        version=version,\n                    )\n                except MetadataInconsistent as e:\n                    logger.info(\n                        \"Discarding [blue underline]%s[/]: [yellow]%s[reset]\",\n                        link,\n                        e,\n                        extra={\"markup\": True},\n                    )\n                    self._build_failures[link] = e\n                    return None\n\n            base: BaseCandidate = self._editable_candidate_cache[link]\n        else:\n            if link not in self._link_candidate_cache:\n                try:\n                    self._link_candidate_cache[link] = LinkCandidate(\n                        link,\n                        template,\n                        factory=self,\n                        name=name,\n                        version=version,\n                    )\n                except MetadataInconsistent as e:\n                    logger.info(\n                        \"Discarding [blue underline]%s[/]: [yellow]%s[reset]\",\n                        link,\n                        e,\n                        extra={\"markup\": True},\n                    )\n                    self._build_failures[link] = e\n                    return None\n            base = self._link_candidate_cache[link]\n\n        if not extras:\n            return base\n        return self._make_extras_candidate(base, extras)\n\n    def _iter_found_candidates(\n        self,\n        ireqs: Sequence[InstallRequirement],\n        specifier: SpecifierSet,\n        hashes: Hashes,\n        prefers_installed: bool,\n        incompatible_ids: Set[int],\n    ) -> Iterable[Candidate]:\n        if not ireqs:\n            return ()\n\n        # The InstallRequirement implementation requires us to give it a\n        # \"template\". Here we just choose the first requirement to represent\n        # all of them.\n        # Hopefully the Project model can correct this mismatch in the future.\n        template = ireqs[0]\n        assert template.req, \"Candidates found on index must be PEP 508\"\n        name = canonicalize_name(template.req.name)\n\n        extras: FrozenSet[str] = frozenset()\n        for ireq in ireqs:\n            assert ireq.req, \"Candidates found on index must be PEP 508\"\n            specifier &= ireq.req.specifier\n            hashes &= ireq.hashes(trust_internet=False)\n            extras |= frozenset(ireq.extras)\n\n        def _get_installed_candidate() -> Optional[Candidate]:\n            \"\"\"Get the candidate for the currently-installed version.\"\"\"\n            # If --force-reinstall is set, we want the version from the index\n            # instead, so we \"pretend\" there is nothing installed.\n            if self._force_reinstall:\n                return None\n            try:\n                installed_dist = self._installed_dists[name]\n            except KeyError:\n                return None\n            # Don't use the installed distribution if its version does not fit\n            # the current dependency graph.\n            if not specifier.contains(installed_dist.version, prereleases=True):\n                return None\n            candidate = self._make_candidate_from_dist(\n                dist=installed_dist,\n                extras=extras,\n                template=template,\n            )\n            # The candidate is a known incompatibility. Don't use it.\n            if id(candidate) in incompatible_ids:\n                return None\n            return candidate\n\n        def iter_index_candidate_infos() -> Iterator[IndexCandidateInfo]:\n            result = self._finder.find_best_candidate(\n                project_name=name,\n                specifier=specifier,\n                hashes=hashes,\n            )\n            icans = list(result.iter_applicable())\n\n            # PEP 592: Yanked releases are ignored unless the specifier\n            # explicitly pins a version (via '==' or '===') that can be\n            # solely satisfied by a yanked release.\n            all_yanked = all(ican.link.is_yanked for ican in icans)\n\n            def is_pinned(specifier: SpecifierSet) -> bool:\n                for sp in specifier:\n                    if sp.operator == \"===\":\n                        return True\n                    if sp.operator != \"==\":\n                        continue\n                    if sp.version.endswith(\".*\"):\n                        continue\n                    return True\n                return False\n\n            pinned = is_pinned(specifier)\n\n            # PackageFinder returns earlier versions first, so we reverse.\n            for ican in reversed(icans):\n                if not (all_yanked and pinned) and ican.link.is_yanked:\n                    continue\n                func = functools.partial(\n                    self._make_candidate_from_link,\n                    link=ican.link,\n                    extras=extras,\n                    template=template,\n                    name=name,\n                    version=ican.version,\n                )\n                yield ican.version, func\n\n        return FoundCandidates(\n            iter_index_candidate_infos,\n            _get_installed_candidate(),\n            prefers_installed,\n            incompatible_ids,\n        )\n\n    def _iter_explicit_candidates_from_base(\n        self,\n        base_requirements: Iterable[Requirement],\n        extras: FrozenSet[str],\n    ) -> Iterator[Candidate]:\n        \"\"\"Produce explicit candidates from the base given an extra-ed package.\n\n        :param base_requirements: Requirements known to the resolver. The\n            requirements are guaranteed to not have extras.\n        :param extras: The extras to inject into the explicit requirements'\n            candidates.\n        \"\"\"\n        for req in base_requirements:\n            lookup_cand, _ = req.get_candidate_lookup()\n            if lookup_cand is None:  # Not explicit.\n                continue\n            # We've stripped extras from the identifier, and should always\n            # get a BaseCandidate here, unless there's a bug elsewhere.\n            base_cand = as_base_candidate(lookup_cand)\n            assert base_cand is not None, \"no extras here\"\n            yield self._make_extras_candidate(base_cand, extras)\n\n    def _iter_candidates_from_constraints(\n        self,\n        identifier: str,\n        constraint: Constraint,\n        template: InstallRequirement,\n    ) -> Iterator[Candidate]:\n        \"\"\"Produce explicit candidates from constraints.\n\n        This creates \"fake\" InstallRequirement objects that are basically clones\n        of what \"should\" be the template, but with original_link set to link.\n        \"\"\"\n        for link in constraint.links:\n            self._fail_if_link_is_unsupported_wheel(link)\n            candidate = self._make_candidate_from_link(\n                link,\n                extras=frozenset(),\n                template=install_req_from_link_and_ireq(link, template),\n                name=canonicalize_name(identifier),\n                version=None,\n            )\n            if candidate:\n                yield candidate\n\n    def find_candidates(\n        self,\n        identifier: str,\n        requirements: Mapping[str, Iterable[Requirement]],\n        incompatibilities: Mapping[str, Iterator[Candidate]],\n        constraint: Constraint,\n        prefers_installed: bool,\n    ) -> Iterable[Candidate]:\n        # Collect basic lookup information from the requirements.\n        explicit_candidates: Set[Candidate] = set()\n        ireqs: List[InstallRequirement] = []\n        for req in requirements[identifier]:\n            cand, ireq = req.get_candidate_lookup()\n            if cand is not None:\n                explicit_candidates.add(cand)\n            if ireq is not None:\n                ireqs.append(ireq)\n\n        # If the current identifier contains extras, add explicit candidates\n        # from entries from extra-less identifier.\n        with contextlib.suppress(InvalidRequirement):\n            parsed_requirement = get_requirement(identifier)\n            explicit_candidates.update(\n                self._iter_explicit_candidates_from_base(\n                    requirements.get(parsed_requirement.name, ()),\n                    frozenset(parsed_requirement.extras),\n                ),\n            )\n\n        # Add explicit candidates from constraints. We only do this if there are\n        # known ireqs, which represent requirements not already explicit. If\n        # there are no ireqs, we're constraining already-explicit requirements,\n        # which is handled later when we return the explicit candidates.\n        if ireqs:\n            try:\n                explicit_candidates.update(\n                    self._iter_candidates_from_constraints(\n                        identifier,\n                        constraint,\n                        template=ireqs[0],\n                    ),\n                )\n            except UnsupportedWheel:\n                # If we're constrained to install a wheel incompatible with the\n                # target architecture, no candidates will ever be valid.\n                return ()\n\n        # Since we cache all the candidates, incompatibility identification\n        # can be made quicker by comparing only the id() values.\n        incompat_ids = {id(c) for c in incompatibilities.get(identifier, ())}\n\n        # If none of the requirements want an explicit candidate, we can ask\n        # the finder for candidates.\n        if not explicit_candidates:\n            return self._iter_found_candidates(\n                ireqs,\n                constraint.specifier,\n                constraint.hashes,\n                prefers_installed,\n                incompat_ids,\n            )\n\n        return (\n            c\n            for c in explicit_candidates\n            if id(c) not in incompat_ids\n            and constraint.is_satisfied_by(c)\n            and all(req.is_satisfied_by(c) for req in requirements[identifier])\n        )\n\n    def _make_requirement_from_install_req(\n        self, ireq: InstallRequirement, requested_extras: Iterable[str]\n    ) -> Optional[Requirement]:\n        if not ireq.match_markers(requested_extras):\n            logger.info(\n                \"Ignoring %s: markers '%s' don't match your environment\",\n                ireq.name,\n                ireq.markers,\n            )\n            return None\n        if not ireq.link:\n            return SpecifierRequirement(ireq)\n        self._fail_if_link_is_unsupported_wheel(ireq.link)\n        cand = self._make_candidate_from_link(\n            ireq.link,\n            extras=frozenset(ireq.extras),\n            template=ireq,\n            name=canonicalize_name(ireq.name) if ireq.name else None,\n            version=None,\n        )\n        if cand is None:\n            # There's no way we can satisfy a URL requirement if the underlying\n            # candidate fails to build. An unnamed URL must be user-supplied, so\n            # we fail eagerly. If the URL is named, an unsatisfiable requirement\n            # can make the resolver do the right thing, either backtrack (and\n            # maybe find some other requirement that's buildable) or raise a\n            # ResolutionImpossible eventually.\n            if not ireq.name:\n                raise self._build_failures[ireq.link]\n            return UnsatisfiableRequirement(canonicalize_name(ireq.name))\n        return self.make_requirement_from_candidate(cand)\n\n    def collect_root_requirements(\n        self, root_ireqs: List[InstallRequirement]\n    ) -> CollectedRootRequirements:\n        collected = CollectedRootRequirements([], {}, {})\n        for i, ireq in enumerate(root_ireqs):\n            if ireq.constraint:\n                # Ensure we only accept valid constraints\n                problem = check_invalid_constraint_type(ireq)\n                if problem:\n                    raise InstallationError(problem)\n                if not ireq.match_markers():\n                    continue\n                assert ireq.name, \"Constraint must be named\"\n                name = canonicalize_name(ireq.name)\n                if name in collected.constraints:\n                    collected.constraints[name] &= ireq\n                else:\n                    collected.constraints[name] = Constraint.from_ireq(ireq)\n            else:\n                req = self._make_requirement_from_install_req(\n                    ireq,\n                    requested_extras=(),\n                )\n                if req is None:\n                    continue\n                if ireq.user_supplied and req.name not in collected.user_requested:\n                    collected.user_requested[req.name] = i\n                collected.requirements.append(req)\n        return collected\n\n    def make_requirement_from_candidate(\n        self, candidate: Candidate\n    ) -> ExplicitRequirement:\n        return ExplicitRequirement(candidate)\n\n    def make_requirement_from_spec(\n        self,\n        specifier: str,\n        comes_from: Optional[InstallRequirement],\n        requested_extras: Iterable[str] = (),\n    ) -> Optional[Requirement]:\n        ireq = self._make_install_req_from_spec(specifier, comes_from)\n        return self._make_requirement_from_install_req(ireq, requested_extras)\n\n    def make_requires_python_requirement(\n        self,\n        specifier: SpecifierSet,\n    ) -> Optional[Requirement]:\n        if self._ignore_requires_python:\n            return None\n        # Don't bother creating a dependency for an empty Requires-Python.\n        if not str(specifier):\n            return None\n        return RequiresPythonRequirement(specifier, self._python_candidate)\n\n    def get_wheel_cache_entry(\n        self, link: Link, name: Optional[str]\n    ) -> Optional[CacheEntry]:\n        \"\"\"Look up the link in the wheel cache.\n\n        If ``preparer.require_hashes`` is True, don't use the wheel cache,\n        because cached wheels, always built locally, have different hashes\n        than the files downloaded from the index server and thus throw false\n        hash mismatches. Furthermore, cached wheels at present have\n        nondeterministic contents due to file modification times.\n        \"\"\"\n        if self._wheel_cache is None or self.preparer.require_hashes:\n            return None\n        return self._wheel_cache.get_cache_entry(\n            link=link,\n            package_name=name,\n            supported_tags=get_supported(),\n        )\n\n    def get_dist_to_uninstall(self, candidate: Candidate) -> Optional[BaseDistribution]:\n        # TODO: Are there more cases this needs to return True? Editable?\n        dist = self._installed_dists.get(candidate.project_name)\n        if dist is None:  # Not installed, no uninstallation required.\n            return None\n\n        # We're installing into global site. The current installation must\n        # be uninstalled, no matter it's in global or user site, because the\n        # user site installation has precedence over global.\n        if not self._use_user_site:\n            return dist\n\n        # We're installing into user site. Remove the user site installation.\n        if dist.in_usersite:\n            return dist\n\n        # We're installing into user site, but the installed incompatible\n        # package is in global site. We can't uninstall that, and would let\n        # the new user installation to \"shadow\" it. But shadowing won't work\n        # in virtual environments, so we error out.\n        if running_under_virtualenv() and dist.in_site_packages:\n            message = (\n                f\"Will not install to the user site because it will lack \"\n                f\"sys.path precedence to {dist.raw_name} in {dist.location}\"\n            )\n            raise InstallationError(message)\n        return None\n\n    def _report_requires_python_error(\n        self, causes: Sequence[\"ConflictCause\"]\n    ) -> UnsupportedPythonVersion:\n        assert causes, \"Requires-Python error reported with no cause\"\n\n        version = self._python_candidate.version\n\n        if len(causes) == 1:\n            specifier = str(causes[0].requirement.specifier)\n            message = (\n                f\"Package {causes[0].parent.name!r} requires a different \"\n                f\"Python: {version} not in {specifier!r}\"\n            )\n            return UnsupportedPythonVersion(message)\n\n        message = f\"Packages require a different Python. {version} not in:\"\n        for cause in causes:\n            package = cause.parent.format_for_error()\n            specifier = str(cause.requirement.specifier)\n            message += f\"\\n{specifier!r} (required by {package})\"\n        return UnsupportedPythonVersion(message)\n\n    def _report_single_requirement_conflict(\n        self, req: Requirement, parent: Optional[Candidate]\n    ) -> DistributionNotFound:\n        if parent is None:\n            req_disp = str(req)\n        else:\n            req_disp = f\"{req} (from {parent.name})\"\n\n        cands = self._finder.find_all_candidates(req.project_name)\n        skipped_by_requires_python = self._finder.requires_python_skipped_reasons()\n        versions = [str(v) for v in sorted({c.version for c in cands})]\n\n        if skipped_by_requires_python:\n            logger.critical(\n                \"Ignored the following versions that require a different python \"\n                \"version: %s\",\n                \"; \".join(skipped_by_requires_python) or \"none\",\n            )\n        logger.critical(\n            \"Could not find a version that satisfies the requirement %s \"\n            \"(from versions: %s)\",\n            req_disp,\n            \", \".join(versions) or \"none\",\n        )\n        if str(req) == \"requirements.txt\":\n            logger.info(\n                \"HINT: You are attempting to install a package literally \"\n                'named \"requirements.txt\" (which cannot exist). Consider '\n                \"using the '-r' flag to install the packages listed in \"\n                \"requirements.txt\"\n            )\n\n        return DistributionNotFound(f\"No matching distribution found for {req}\")\n\n    def get_installation_error(\n        self,\n        e: \"ResolutionImpossible[Requirement, Candidate]\",\n        constraints: Dict[str, Constraint],\n    ) -> InstallationError:\n\n        assert e.causes, \"Installation error reported with no cause\"\n\n        # If one of the things we can't solve is \"we need Python X.Y\",\n        # that is what we report.\n        requires_python_causes = [\n            cause\n            for cause in e.causes\n            if isinstance(cause.requirement, RequiresPythonRequirement)\n            and not cause.requirement.is_satisfied_by(self._python_candidate)\n        ]\n        if requires_python_causes:\n            # The comprehension above makes sure all Requirement instances are\n            # RequiresPythonRequirement, so let's cast for convenience.\n            return self._report_requires_python_error(\n                cast(\"Sequence[ConflictCause]\", requires_python_causes),\n            )\n\n        # Otherwise, we have a set of causes which can't all be satisfied\n        # at once.\n\n        # The simplest case is when we have *one* cause that can't be\n        # satisfied. We just report that case.\n        if len(e.causes) == 1:\n            req, parent = e.causes[0]\n            if req.name not in constraints:\n                return self._report_single_requirement_conflict(req, parent)\n\n        # OK, we now have a list of requirements that can't all be\n        # satisfied at once.\n\n        # A couple of formatting helpers\n        def text_join(parts: List[str]) -> str:\n            if len(parts) == 1:\n                return parts[0]\n\n            return \", \".join(parts[:-1]) + \" and \" + parts[-1]\n\n        def describe_trigger(parent: Candidate) -> str:\n            ireq = parent.get_install_requirement()\n            if not ireq or not ireq.comes_from:\n                return f\"{parent.name}=={parent.version}\"\n            if isinstance(ireq.comes_from, InstallRequirement):\n                return str(ireq.comes_from.name)\n            return str(ireq.comes_from)\n\n        triggers = set()\n        for req, parent in e.causes:\n            if parent is None:\n                # This is a root requirement, so we can report it directly\n                trigger = req.format_for_error()\n            else:\n                trigger = describe_trigger(parent)\n            triggers.add(trigger)\n\n        if triggers:\n            info = text_join(sorted(triggers))\n        else:\n            info = \"the requested packages\"\n\n        msg = (\n            \"Cannot install {} because these package versions \"\n            \"have conflicting dependencies.\".format(info)\n        )\n        logger.critical(msg)\n        msg = \"\\nThe conflict is caused by:\"\n\n        relevant_constraints = set()\n        for req, parent in e.causes:\n            if req.name in constraints:\n                relevant_constraints.add(req.name)\n            msg = msg + \"\\n    \"\n            if parent:\n                msg = msg + f\"{parent.name} {parent.version} depends on \"\n            else:\n                msg = msg + \"The user requested \"\n            msg = msg + req.format_for_error()\n        for key in relevant_constraints:\n            spec = constraints[key].specifier\n            msg += f\"\\n    The user requested (constraint) {key}{spec}\"\n\n        msg = (\n            msg\n            + \"\\n\\n\"\n            + \"To fix this you could try to:\\n\"\n            + \"1. loosen the range of package versions you've specified\\n\"\n            + \"2. remove package versions to allow pip attempt to solve \"\n            + \"the dependency conflict\\n\"\n        )\n\n        logger.info(msg)\n\n        return DistributionNotFound(\n            \"ResolutionImpossible: for help visit \"\n            \"https://pip.pypa.io/en/latest/topics/dependency-resolution/\"\n            \"#dealing-with-dependency-conflicts\"\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/found_candidates.py",
    "content": "\"\"\"Utilities to lazily create and visit candidates found.\n\nCreating and visiting a candidate is a *very* costly operation. It involves\nfetching, extracting, potentially building modules from source, and verifying\ndistribution metadata. It is therefore crucial for performance to keep\neverything here lazy all the way down, so we only touch candidates that we\nabsolutely need, and not \"download the world\" when we only need one version of\nsomething.\n\"\"\"\n\nimport functools\nfrom collections.abc import Sequence\nfrom typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, Set, Tuple\n\nfrom pip._vendor.packaging.version import _BaseVersion\n\nfrom .base import Candidate\n\nIndexCandidateInfo = Tuple[_BaseVersion, Callable[[], Optional[Candidate]]]\n\nif TYPE_CHECKING:\n    SequenceCandidate = Sequence[Candidate]\nelse:\n    # For compatibility: Python before 3.9 does not support using [] on the\n    # Sequence class.\n    #\n    # >>> from collections.abc import Sequence\n    # >>> Sequence[str]\n    # Traceback (most recent call last):\n    #   File \"<stdin>\", line 1, in <module>\n    # TypeError: 'ABCMeta' object is not subscriptable\n    #\n    # TODO: Remove this block after dropping Python 3.8 support.\n    SequenceCandidate = Sequence\n\n\ndef _iter_built(infos: Iterator[IndexCandidateInfo]) -> Iterator[Candidate]:\n    \"\"\"Iterator for ``FoundCandidates``.\n\n    This iterator is used when the package is not already installed. Candidates\n    from index come later in their normal ordering.\n    \"\"\"\n    versions_found: Set[_BaseVersion] = set()\n    for version, func in infos:\n        if version in versions_found:\n            continue\n        candidate = func()\n        if candidate is None:\n            continue\n        yield candidate\n        versions_found.add(version)\n\n\ndef _iter_built_with_prepended(\n    installed: Candidate, infos: Iterator[IndexCandidateInfo]\n) -> Iterator[Candidate]:\n    \"\"\"Iterator for ``FoundCandidates``.\n\n    This iterator is used when the resolver prefers the already-installed\n    candidate and NOT to upgrade. The installed candidate is therefore\n    always yielded first, and candidates from index come later in their\n    normal ordering, except skipped when the version is already installed.\n    \"\"\"\n    yield installed\n    versions_found: Set[_BaseVersion] = {installed.version}\n    for version, func in infos:\n        if version in versions_found:\n            continue\n        candidate = func()\n        if candidate is None:\n            continue\n        yield candidate\n        versions_found.add(version)\n\n\ndef _iter_built_with_inserted(\n    installed: Candidate, infos: Iterator[IndexCandidateInfo]\n) -> Iterator[Candidate]:\n    \"\"\"Iterator for ``FoundCandidates``.\n\n    This iterator is used when the resolver prefers to upgrade an\n    already-installed package. Candidates from index are returned in their\n    normal ordering, except replaced when the version is already installed.\n\n    The implementation iterates through and yields other candidates, inserting\n    the installed candidate exactly once before we start yielding older or\n    equivalent candidates, or after all other candidates if they are all newer.\n    \"\"\"\n    versions_found: Set[_BaseVersion] = set()\n    for version, func in infos:\n        if version in versions_found:\n            continue\n        # If the installed candidate is better, yield it first.\n        if installed.version >= version:\n            yield installed\n            versions_found.add(installed.version)\n        candidate = func()\n        if candidate is None:\n            continue\n        yield candidate\n        versions_found.add(version)\n\n    # If the installed candidate is older than all other candidates.\n    if installed.version not in versions_found:\n        yield installed\n\n\nclass FoundCandidates(SequenceCandidate):\n    \"\"\"A lazy sequence to provide candidates to the resolver.\n\n    The intended usage is to return this from `find_matches()` so the resolver\n    can iterate through the sequence multiple times, but only access the index\n    page when remote packages are actually needed. This improve performances\n    when suitable candidates are already installed on disk.\n    \"\"\"\n\n    def __init__(\n        self,\n        get_infos: Callable[[], Iterator[IndexCandidateInfo]],\n        installed: Optional[Candidate],\n        prefers_installed: bool,\n        incompatible_ids: Set[int],\n    ):\n        self._get_infos = get_infos\n        self._installed = installed\n        self._prefers_installed = prefers_installed\n        self._incompatible_ids = incompatible_ids\n\n    def __getitem__(self, index: Any) -> Any:\n        # Implemented to satisfy the ABC check. This is not needed by the\n        # resolver, and should not be used by the provider either (for\n        # performance reasons).\n        raise NotImplementedError(\"don't do this\")\n\n    def __iter__(self) -> Iterator[Candidate]:\n        infos = self._get_infos()\n        if not self._installed:\n            iterator = _iter_built(infos)\n        elif self._prefers_installed:\n            iterator = _iter_built_with_prepended(self._installed, infos)\n        else:\n            iterator = _iter_built_with_inserted(self._installed, infos)\n        return (c for c in iterator if id(c) not in self._incompatible_ids)\n\n    def __len__(self) -> int:\n        # Implemented to satisfy the ABC check. This is not needed by the\n        # resolver, and should not be used by the provider either (for\n        # performance reasons).\n        raise NotImplementedError(\"don't do this\")\n\n    @functools.lru_cache(maxsize=1)\n    def __bool__(self) -> bool:\n        if self._prefers_installed and self._installed:\n            return True\n        return any(self)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/provider.py",
    "content": "import collections\nimport math\nfrom typing import (\n    TYPE_CHECKING,\n    Dict,\n    Iterable,\n    Iterator,\n    Mapping,\n    Sequence,\n    TypeVar,\n    Union,\n)\n\nfrom pip._vendor.resolvelib.providers import AbstractProvider\n\nfrom .base import Candidate, Constraint, Requirement\nfrom .candidates import REQUIRES_PYTHON_IDENTIFIER\nfrom .factory import Factory\n\nif TYPE_CHECKING:\n    from pip._vendor.resolvelib.providers import Preference\n    from pip._vendor.resolvelib.resolvers import RequirementInformation\n\n    PreferenceInformation = RequirementInformation[Requirement, Candidate]\n\n    _ProviderBase = AbstractProvider[Requirement, Candidate, str]\nelse:\n    _ProviderBase = AbstractProvider\n\n# Notes on the relationship between the provider, the factory, and the\n# candidate and requirement classes.\n#\n# The provider is a direct implementation of the resolvelib class. Its role\n# is to deliver the API that resolvelib expects.\n#\n# Rather than work with completely abstract \"requirement\" and \"candidate\"\n# concepts as resolvelib does, pip has concrete classes implementing these two\n# ideas. The API of Requirement and Candidate objects are defined in the base\n# classes, but essentially map fairly directly to the equivalent provider\n# methods. In particular, `find_matches` and `is_satisfied_by` are\n# requirement methods, and `get_dependencies` is a candidate method.\n#\n# The factory is the interface to pip's internal mechanisms. It is stateless,\n# and is created by the resolver and held as a property of the provider. It is\n# responsible for creating Requirement and Candidate objects, and provides\n# services to those objects (access to pip's finder and preparer).\n\n\nD = TypeVar(\"D\")\nV = TypeVar(\"V\")\n\n\ndef _get_with_identifier(\n    mapping: Mapping[str, V],\n    identifier: str,\n    default: D,\n) -> Union[D, V]:\n    \"\"\"Get item from a package name lookup mapping with a resolver identifier.\n\n    This extra logic is needed when the target mapping is keyed by package\n    name, which cannot be directly looked up with an identifier (which may\n    contain requested extras). Additional logic is added to also look up a value\n    by \"cleaning up\" the extras from the identifier.\n    \"\"\"\n    if identifier in mapping:\n        return mapping[identifier]\n    # HACK: Theoretically we should check whether this identifier is a valid\n    # \"NAME[EXTRAS]\" format, and parse out the name part with packaging or\n    # some regular expression. But since pip's resolver only spits out three\n    # kinds of identifiers: normalized PEP 503 names, normalized names plus\n    # extras, and Requires-Python, we can cheat a bit here.\n    name, open_bracket, _ = identifier.partition(\"[\")\n    if open_bracket and name in mapping:\n        return mapping[name]\n    return default\n\n\nclass PipProvider(_ProviderBase):\n    \"\"\"Pip's provider implementation for resolvelib.\n\n    :params constraints: A mapping of constraints specified by the user. Keys\n        are canonicalized project names.\n    :params ignore_dependencies: Whether the user specified ``--no-deps``.\n    :params upgrade_strategy: The user-specified upgrade strategy.\n    :params user_requested: A set of canonicalized package names that the user\n        supplied for pip to install/upgrade.\n    \"\"\"\n\n    def __init__(\n        self,\n        factory: Factory,\n        constraints: Dict[str, Constraint],\n        ignore_dependencies: bool,\n        upgrade_strategy: str,\n        user_requested: Dict[str, int],\n    ) -> None:\n        self._factory = factory\n        self._constraints = constraints\n        self._ignore_dependencies = ignore_dependencies\n        self._upgrade_strategy = upgrade_strategy\n        self._user_requested = user_requested\n        self._known_depths: Dict[str, float] = collections.defaultdict(lambda: math.inf)\n\n    def identify(self, requirement_or_candidate: Union[Requirement, Candidate]) -> str:\n        return requirement_or_candidate.name\n\n    def get_preference(  # type: ignore\n        self,\n        identifier: str,\n        resolutions: Mapping[str, Candidate],\n        candidates: Mapping[str, Iterator[Candidate]],\n        information: Mapping[str, Iterable[\"PreferenceInformation\"]],\n        backtrack_causes: Sequence[\"PreferenceInformation\"],\n    ) -> \"Preference\":\n        \"\"\"Produce a sort key for given requirement based on preference.\n\n        The lower the return value is, the more preferred this group of\n        arguments is.\n\n        Currently pip considers the following in order:\n\n        * Prefer if any of the known requirements is \"direct\", e.g. points to an\n          explicit URL.\n        * If equal, prefer if any requirement is \"pinned\", i.e. contains\n          operator ``===`` or ``==``.\n        * If equal, calculate an approximate \"depth\" and resolve requirements\n          closer to the user-specified requirements first.\n        * Order user-specified requirements by the order they are specified.\n        * If equal, prefers \"non-free\" requirements, i.e. contains at least one\n          operator, such as ``>=`` or ``<``.\n        * If equal, order alphabetically for consistency (helps debuggability).\n        \"\"\"\n        lookups = (r.get_candidate_lookup() for r, _ in information[identifier])\n        candidate, ireqs = zip(*lookups)\n        operators = [\n            specifier.operator\n            for specifier_set in (ireq.specifier for ireq in ireqs if ireq)\n            for specifier in specifier_set\n        ]\n\n        direct = candidate is not None\n        pinned = any(op[:2] == \"==\" for op in operators)\n        unfree = bool(operators)\n\n        try:\n            requested_order: Union[int, float] = self._user_requested[identifier]\n        except KeyError:\n            requested_order = math.inf\n            parent_depths = (\n                self._known_depths[parent.name] if parent is not None else 0.0\n                for _, parent in information[identifier]\n            )\n            inferred_depth = min(d for d in parent_depths) + 1.0\n        else:\n            inferred_depth = 1.0\n        self._known_depths[identifier] = inferred_depth\n\n        requested_order = self._user_requested.get(identifier, math.inf)\n\n        # Requires-Python has only one candidate and the check is basically\n        # free, so we always do it first to avoid needless work if it fails.\n        requires_python = identifier == REQUIRES_PYTHON_IDENTIFIER\n\n        # HACK: Setuptools have a very long and solid backward compatibility\n        # track record, and extremely few projects would request a narrow,\n        # non-recent version range of it since that would break a lot things.\n        # (Most projects specify it only to request for an installer feature,\n        # which does not work, but that's another topic.) Intentionally\n        # delaying Setuptools helps reduce branches the resolver has to check.\n        # This serves as a temporary fix for issues like \"apache-airflow[all]\"\n        # while we work on \"proper\" branch pruning techniques.\n        delay_this = identifier == \"setuptools\"\n\n        # Prefer the causes of backtracking on the assumption that the problem\n        # resolving the dependency tree is related to the failures that caused\n        # the backtracking\n        backtrack_cause = self.is_backtrack_cause(identifier, backtrack_causes)\n\n        return (\n            not requires_python,\n            delay_this,\n            not direct,\n            not pinned,\n            not backtrack_cause,\n            inferred_depth,\n            requested_order,\n            not unfree,\n            identifier,\n        )\n\n    def find_matches(\n        self,\n        identifier: str,\n        requirements: Mapping[str, Iterator[Requirement]],\n        incompatibilities: Mapping[str, Iterator[Candidate]],\n    ) -> Iterable[Candidate]:\n        def _eligible_for_upgrade(identifier: str) -> bool:\n            \"\"\"Are upgrades allowed for this project?\n\n            This checks the upgrade strategy, and whether the project was one\n            that the user specified in the command line, in order to decide\n            whether we should upgrade if there's a newer version available.\n\n            (Note that we don't need access to the `--upgrade` flag, because\n            an upgrade strategy of \"to-satisfy-only\" means that `--upgrade`\n            was not specified).\n            \"\"\"\n            if self._upgrade_strategy == \"eager\":\n                return True\n            elif self._upgrade_strategy == \"only-if-needed\":\n                user_order = _get_with_identifier(\n                    self._user_requested,\n                    identifier,\n                    default=None,\n                )\n                return user_order is not None\n            return False\n\n        constraint = _get_with_identifier(\n            self._constraints,\n            identifier,\n            default=Constraint.empty(),\n        )\n        return self._factory.find_candidates(\n            identifier=identifier,\n            requirements=requirements,\n            constraint=constraint,\n            prefers_installed=(not _eligible_for_upgrade(identifier)),\n            incompatibilities=incompatibilities,\n        )\n\n    def is_satisfied_by(self, requirement: Requirement, candidate: Candidate) -> bool:\n        return requirement.is_satisfied_by(candidate)\n\n    def get_dependencies(self, candidate: Candidate) -> Sequence[Requirement]:\n        with_requires = not self._ignore_dependencies\n        return [r for r in candidate.iter_dependencies(with_requires) if r is not None]\n\n    @staticmethod\n    def is_backtrack_cause(\n        identifier: str, backtrack_causes: Sequence[\"PreferenceInformation\"]\n    ) -> bool:\n        for backtrack_cause in backtrack_causes:\n            if identifier == backtrack_cause.requirement.name:\n                return True\n            if backtrack_cause.parent and identifier == backtrack_cause.parent.name:\n                return True\n        return False\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/reporter.py",
    "content": "from collections import defaultdict\nfrom logging import getLogger\nfrom typing import Any, DefaultDict\n\nfrom pip._vendor.resolvelib.reporters import BaseReporter\n\nfrom .base import Candidate, Requirement\n\nlogger = getLogger(__name__)\n\n\nclass PipReporter(BaseReporter):\n    def __init__(self) -> None:\n        self.backtracks_by_package: DefaultDict[str, int] = defaultdict(int)\n\n        self._messages_at_backtrack = {\n            1: (\n                \"pip is looking at multiple versions of {package_name} to \"\n                \"determine which version is compatible with other \"\n                \"requirements. This could take a while.\"\n            ),\n            8: (\n                \"pip is looking at multiple versions of {package_name} to \"\n                \"determine which version is compatible with other \"\n                \"requirements. This could take a while.\"\n            ),\n            13: (\n                \"This is taking longer than usual. You might need to provide \"\n                \"the dependency resolver with stricter constraints to reduce \"\n                \"runtime. See https://pip.pypa.io/warnings/backtracking for \"\n                \"guidance. If you want to abort this run, press Ctrl + C.\"\n            ),\n        }\n\n    def backtracking(self, candidate: Candidate) -> None:\n        self.backtracks_by_package[candidate.name] += 1\n\n        count = self.backtracks_by_package[candidate.name]\n        if count not in self._messages_at_backtrack:\n            return\n\n        message = self._messages_at_backtrack[count]\n        logger.info(\"INFO: %s\", message.format(package_name=candidate.name))\n\n\nclass PipDebuggingReporter(BaseReporter):\n    \"\"\"A reporter that does an info log for every event it sees.\"\"\"\n\n    def starting(self) -> None:\n        logger.info(\"Reporter.starting()\")\n\n    def starting_round(self, index: int) -> None:\n        logger.info(\"Reporter.starting_round(%r)\", index)\n\n    def ending_round(self, index: int, state: Any) -> None:\n        logger.info(\"Reporter.ending_round(%r, state)\", index)\n\n    def ending(self, state: Any) -> None:\n        logger.info(\"Reporter.ending(%r)\", state)\n\n    def adding_requirement(self, requirement: Requirement, parent: Candidate) -> None:\n        logger.info(\"Reporter.adding_requirement(%r, %r)\", requirement, parent)\n\n    def backtracking(self, candidate: Candidate) -> None:\n        logger.info(\"Reporter.backtracking(%r)\", candidate)\n\n    def pinning(self, candidate: Candidate) -> None:\n        logger.info(\"Reporter.pinning(%r)\", candidate)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/requirements.py",
    "content": "from pip._vendor.packaging.specifiers import SpecifierSet\nfrom pip._vendor.packaging.utils import NormalizedName, canonicalize_name\n\nfrom pip._internal.req.req_install import InstallRequirement\n\nfrom .base import Candidate, CandidateLookup, Requirement, format_name\n\n\nclass ExplicitRequirement(Requirement):\n    def __init__(self, candidate: Candidate) -> None:\n        self.candidate = candidate\n\n    def __str__(self) -> str:\n        return str(self.candidate)\n\n    def __repr__(self) -> str:\n        return \"{class_name}({candidate!r})\".format(\n            class_name=self.__class__.__name__,\n            candidate=self.candidate,\n        )\n\n    @property\n    def project_name(self) -> NormalizedName:\n        # No need to canonicalize - the candidate did this\n        return self.candidate.project_name\n\n    @property\n    def name(self) -> str:\n        # No need to canonicalize - the candidate did this\n        return self.candidate.name\n\n    def format_for_error(self) -> str:\n        return self.candidate.format_for_error()\n\n    def get_candidate_lookup(self) -> CandidateLookup:\n        return self.candidate, None\n\n    def is_satisfied_by(self, candidate: Candidate) -> bool:\n        return candidate == self.candidate\n\n\nclass SpecifierRequirement(Requirement):\n    def __init__(self, ireq: InstallRequirement) -> None:\n        assert ireq.link is None, \"This is a link, not a specifier\"\n        self._ireq = ireq\n        self._extras = frozenset(ireq.extras)\n\n    def __str__(self) -> str:\n        return str(self._ireq.req)\n\n    def __repr__(self) -> str:\n        return \"{class_name}({requirement!r})\".format(\n            class_name=self.__class__.__name__,\n            requirement=str(self._ireq.req),\n        )\n\n    @property\n    def project_name(self) -> NormalizedName:\n        assert self._ireq.req, \"Specifier-backed ireq is always PEP 508\"\n        return canonicalize_name(self._ireq.req.name)\n\n    @property\n    def name(self) -> str:\n        return format_name(self.project_name, self._extras)\n\n    def format_for_error(self) -> str:\n\n        # Convert comma-separated specifiers into \"A, B, ..., F and G\"\n        # This makes the specifier a bit more \"human readable\", without\n        # risking a change in meaning. (Hopefully! Not all edge cases have\n        # been checked)\n        parts = [s.strip() for s in str(self).split(\",\")]\n        if len(parts) == 0:\n            return \"\"\n        elif len(parts) == 1:\n            return parts[0]\n\n        return \", \".join(parts[:-1]) + \" and \" + parts[-1]\n\n    def get_candidate_lookup(self) -> CandidateLookup:\n        return None, self._ireq\n\n    def is_satisfied_by(self, candidate: Candidate) -> bool:\n        assert candidate.name == self.name, (\n            f\"Internal issue: Candidate is not for this requirement \"\n            f\"{candidate.name} vs {self.name}\"\n        )\n        # We can safely always allow prereleases here since PackageFinder\n        # already implements the prerelease logic, and would have filtered out\n        # prerelease candidates if the user does not expect them.\n        assert self._ireq.req, \"Specifier-backed ireq is always PEP 508\"\n        spec = self._ireq.req.specifier\n        return spec.contains(candidate.version, prereleases=True)\n\n\nclass RequiresPythonRequirement(Requirement):\n    \"\"\"A requirement representing Requires-Python metadata.\"\"\"\n\n    def __init__(self, specifier: SpecifierSet, match: Candidate) -> None:\n        self.specifier = specifier\n        self._candidate = match\n\n    def __str__(self) -> str:\n        return f\"Python {self.specifier}\"\n\n    def __repr__(self) -> str:\n        return \"{class_name}({specifier!r})\".format(\n            class_name=self.__class__.__name__,\n            specifier=str(self.specifier),\n        )\n\n    @property\n    def project_name(self) -> NormalizedName:\n        return self._candidate.project_name\n\n    @property\n    def name(self) -> str:\n        return self._candidate.name\n\n    def format_for_error(self) -> str:\n        return str(self)\n\n    def get_candidate_lookup(self) -> CandidateLookup:\n        if self.specifier.contains(self._candidate.version, prereleases=True):\n            return self._candidate, None\n        return None, None\n\n    def is_satisfied_by(self, candidate: Candidate) -> bool:\n        assert candidate.name == self._candidate.name, \"Not Python candidate\"\n        # We can safely always allow prereleases here since PackageFinder\n        # already implements the prerelease logic, and would have filtered out\n        # prerelease candidates if the user does not expect them.\n        return self.specifier.contains(candidate.version, prereleases=True)\n\n\nclass UnsatisfiableRequirement(Requirement):\n    \"\"\"A requirement that cannot be satisfied.\"\"\"\n\n    def __init__(self, name: NormalizedName) -> None:\n        self._name = name\n\n    def __str__(self) -> str:\n        return f\"{self._name} (unavailable)\"\n\n    def __repr__(self) -> str:\n        return \"{class_name}({name!r})\".format(\n            class_name=self.__class__.__name__,\n            name=str(self._name),\n        )\n\n    @property\n    def project_name(self) -> NormalizedName:\n        return self._name\n\n    @property\n    def name(self) -> str:\n        return self._name\n\n    def format_for_error(self) -> str:\n        return str(self)\n\n    def get_candidate_lookup(self) -> CandidateLookup:\n        return None, None\n\n    def is_satisfied_by(self, candidate: Candidate) -> bool:\n        return False\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/resolution/resolvelib/resolver.py",
    "content": "import functools\nimport logging\nimport os\nfrom typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple, cast\n\nfrom pip._vendor.packaging.utils import canonicalize_name\nfrom pip._vendor.resolvelib import BaseReporter, ResolutionImpossible\nfrom pip._vendor.resolvelib import Resolver as RLResolver\nfrom pip._vendor.resolvelib.structs import DirectedGraph\n\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.operations.prepare import RequirementPreparer\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.req.req_set import RequirementSet\nfrom pip._internal.resolution.base import BaseResolver, InstallRequirementProvider\nfrom pip._internal.resolution.resolvelib.provider import PipProvider\nfrom pip._internal.resolution.resolvelib.reporter import (\n    PipDebuggingReporter,\n    PipReporter,\n)\n\nfrom .base import Candidate, Requirement\nfrom .factory import Factory\n\nif TYPE_CHECKING:\n    from pip._vendor.resolvelib.resolvers import Result as RLResult\n\n    Result = RLResult[Requirement, Candidate, str]\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Resolver(BaseResolver):\n    _allowed_strategies = {\"eager\", \"only-if-needed\", \"to-satisfy-only\"}\n\n    def __init__(\n        self,\n        preparer: RequirementPreparer,\n        finder: PackageFinder,\n        wheel_cache: Optional[WheelCache],\n        make_install_req: InstallRequirementProvider,\n        use_user_site: bool,\n        ignore_dependencies: bool,\n        ignore_installed: bool,\n        ignore_requires_python: bool,\n        force_reinstall: bool,\n        upgrade_strategy: str,\n        py_version_info: Optional[Tuple[int, ...]] = None,\n    ):\n        super().__init__()\n        assert upgrade_strategy in self._allowed_strategies\n\n        self.factory = Factory(\n            finder=finder,\n            preparer=preparer,\n            make_install_req=make_install_req,\n            wheel_cache=wheel_cache,\n            use_user_site=use_user_site,\n            force_reinstall=force_reinstall,\n            ignore_installed=ignore_installed,\n            ignore_requires_python=ignore_requires_python,\n            py_version_info=py_version_info,\n        )\n        self.ignore_dependencies = ignore_dependencies\n        self.upgrade_strategy = upgrade_strategy\n        self._result: Optional[Result] = None\n\n    def resolve(\n        self, root_reqs: List[InstallRequirement], check_supported_wheels: bool\n    ) -> RequirementSet:\n        collected = self.factory.collect_root_requirements(root_reqs)\n        provider = PipProvider(\n            factory=self.factory,\n            constraints=collected.constraints,\n            ignore_dependencies=self.ignore_dependencies,\n            upgrade_strategy=self.upgrade_strategy,\n            user_requested=collected.user_requested,\n        )\n        if \"PIP_RESOLVER_DEBUG\" in os.environ:\n            reporter: BaseReporter = PipDebuggingReporter()\n        else:\n            reporter = PipReporter()\n        resolver: RLResolver[Requirement, Candidate, str] = RLResolver(\n            provider,\n            reporter,\n        )\n\n        try:\n            try_to_avoid_resolution_too_deep = 2000000\n            result = self._result = resolver.resolve(\n                collected.requirements, max_rounds=try_to_avoid_resolution_too_deep\n            )\n\n        except ResolutionImpossible as e:\n            error = self.factory.get_installation_error(\n                cast(\"ResolutionImpossible[Requirement, Candidate]\", e),\n                collected.constraints,\n            )\n            raise error from e\n\n        req_set = RequirementSet(check_supported_wheels=check_supported_wheels)\n        for candidate in result.mapping.values():\n            ireq = candidate.get_install_requirement()\n            if ireq is None:\n                continue\n\n            # Check if there is already an installation under the same name,\n            # and set a flag for later stages to uninstall it, if needed.\n            installed_dist = self.factory.get_dist_to_uninstall(candidate)\n            if installed_dist is None:\n                # There is no existing installation -- nothing to uninstall.\n                ireq.should_reinstall = False\n            elif self.factory.force_reinstall:\n                # The --force-reinstall flag is set -- reinstall.\n                ireq.should_reinstall = True\n            elif installed_dist.version != candidate.version:\n                # The installation is different in version -- reinstall.\n                ireq.should_reinstall = True\n            elif candidate.is_editable or installed_dist.editable:\n                # The incoming distribution is editable, or different in\n                # editable-ness to installation -- reinstall.\n                ireq.should_reinstall = True\n            elif candidate.source_link and candidate.source_link.is_file:\n                # The incoming distribution is under file://\n                if candidate.source_link.is_wheel:\n                    # is a local wheel -- do nothing.\n                    logger.info(\n                        \"%s is already installed with the same version as the \"\n                        \"provided wheel. Use --force-reinstall to force an \"\n                        \"installation of the wheel.\",\n                        ireq.name,\n                    )\n                    continue\n\n                # is a local sdist or path -- reinstall\n                ireq.should_reinstall = True\n            else:\n                continue\n\n            link = candidate.source_link\n            if link and link.is_yanked:\n                # The reason can contain non-ASCII characters, Unicode\n                # is required for Python 2.\n                msg = (\n                    \"The candidate selected for download or install is a \"\n                    \"yanked version: {name!r} candidate (version {version} \"\n                    \"at {link})\\nReason for being yanked: {reason}\"\n                ).format(\n                    name=candidate.name,\n                    version=candidate.version,\n                    link=link,\n                    reason=link.yanked_reason or \"<none given>\",\n                )\n                logger.warning(msg)\n\n            req_set.add_named_requirement(ireq)\n\n        reqs = req_set.all_requirements\n        self.factory.preparer.prepare_linked_requirements_more(reqs)\n        return req_set\n\n    def get_installation_order(\n        self, req_set: RequirementSet\n    ) -> List[InstallRequirement]:\n        \"\"\"Get order for installation of requirements in RequirementSet.\n\n        The returned list contains a requirement before another that depends on\n        it. This helps ensure that the environment is kept consistent as they\n        get installed one-by-one.\n\n        The current implementation creates a topological ordering of the\n        dependency graph, giving more weight to packages with less\n        or no dependencies, while breaking any cycles in the graph at\n        arbitrary points. We make no guarantees about where the cycle\n        would be broken, other than it *would* be broken.\n        \"\"\"\n        assert self._result is not None, \"must call resolve() first\"\n\n        if not req_set.requirements:\n            # Nothing is left to install, so we do not need an order.\n            return []\n\n        graph = self._result.graph\n        weights = get_topological_weights(graph, set(req_set.requirements.keys()))\n\n        sorted_items = sorted(\n            req_set.requirements.items(),\n            key=functools.partial(_req_set_item_sorter, weights=weights),\n            reverse=True,\n        )\n        return [ireq for _, ireq in sorted_items]\n\n\ndef get_topological_weights(\n    graph: \"DirectedGraph[Optional[str]]\", requirement_keys: Set[str]\n) -> Dict[Optional[str], int]:\n    \"\"\"Assign weights to each node based on how \"deep\" they are.\n\n    This implementation may change at any point in the future without prior\n    notice.\n\n    We first simplify the dependency graph by pruning any leaves and giving them\n    the highest weight: a package without any dependencies should be installed\n    first. This is done again and again in the same way, giving ever less weight\n    to the newly found leaves. The loop stops when no leaves are left: all\n    remaining packages have at least one dependency left in the graph.\n\n    Then we continue with the remaining graph, by taking the length for the\n    longest path to any node from root, ignoring any paths that contain a single\n    node twice (i.e. cycles). This is done through a depth-first search through\n    the graph, while keeping track of the path to the node.\n\n    Cycles in the graph result would result in node being revisited while also\n    being on its own path. In this case, take no action. This helps ensure we\n    don't get stuck in a cycle.\n\n    When assigning weight, the longer path (i.e. larger length) is preferred.\n\n    We are only interested in the weights of packages that are in the\n    requirement_keys.\n    \"\"\"\n    path: Set[Optional[str]] = set()\n    weights: Dict[Optional[str], int] = {}\n\n    def visit(node: Optional[str]) -> None:\n        if node in path:\n            # We hit a cycle, so we'll break it here.\n            return\n\n        # Time to visit the children!\n        path.add(node)\n        for child in graph.iter_children(node):\n            visit(child)\n        path.remove(node)\n\n        if node not in requirement_keys:\n            return\n\n        last_known_parent_count = weights.get(node, 0)\n        weights[node] = max(last_known_parent_count, len(path))\n\n    # Simplify the graph, pruning leaves that have no dependencies.\n    # This is needed for large graphs (say over 200 packages) because the\n    # `visit` function is exponentially slower then, taking minutes.\n    # See https://github.com/pypa/pip/issues/10557\n    # We will loop until we explicitly break the loop.\n    while True:\n        leaves = set()\n        for key in graph:\n            if key is None:\n                continue\n            for _child in graph.iter_children(key):\n                # This means we have at least one child\n                break\n            else:\n                # No child.\n                leaves.add(key)\n        if not leaves:\n            # We are done simplifying.\n            break\n        # Calculate the weight for the leaves.\n        weight = len(graph) - 1\n        for leaf in leaves:\n            if leaf not in requirement_keys:\n                continue\n            weights[leaf] = weight\n        # Remove the leaves from the graph, making it simpler.\n        for leaf in leaves:\n            graph.remove(leaf)\n\n    # Visit the remaining graph.\n    # `None` is guaranteed to be the root node by resolvelib.\n    visit(None)\n\n    # Sanity check: all requirement keys should be in the weights,\n    # and no other keys should be in the weights.\n    difference = set(weights.keys()).difference(requirement_keys)\n    assert not difference, difference\n\n    return weights\n\n\ndef _req_set_item_sorter(\n    item: Tuple[str, InstallRequirement],\n    weights: Dict[Optional[str], int],\n) -> Tuple[int, str]:\n    \"\"\"Key function used to sort install requirements for installation.\n\n    Based on the \"weight\" mapping calculated in ``get_installation_order()``.\n    The canonical package name is returned as the second member as a tie-\n    breaker to ensure the result is predictable, which is useful in tests.\n    \"\"\"\n    name = canonicalize_name(item[0])\n    return weights[name], name\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/self_outdated_check.py",
    "content": "import datetime\nimport functools\nimport hashlib\nimport json\nimport logging\nimport optparse\nimport os.path\nimport sys\nfrom dataclasses import dataclass\nfrom typing import Any, Callable, Dict, Optional\n\nfrom pip._vendor.packaging.version import parse as parse_version\nfrom pip._vendor.rich.console import Group\nfrom pip._vendor.rich.markup import escape\nfrom pip._vendor.rich.text import Text\n\nfrom pip._internal.index.collector import LinkCollector\nfrom pip._internal.index.package_finder import PackageFinder\nfrom pip._internal.metadata import get_default_environment\nfrom pip._internal.metadata.base import DistributionVersion\nfrom pip._internal.models.selection_prefs import SelectionPreferences\nfrom pip._internal.network.session import PipSession\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.entrypoints import (\n    get_best_invocation_for_this_pip,\n    get_best_invocation_for_this_python,\n)\nfrom pip._internal.utils.filesystem import adjacent_tmp_file, check_path_owner, replace\nfrom pip._internal.utils.misc import ensure_dir\n\n_DATE_FMT = \"%Y-%m-%dT%H:%M:%SZ\"\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef _get_statefile_name(key: str) -> str:\n    key_bytes = key.encode()\n    name = hashlib.sha224(key_bytes).hexdigest()\n    return name\n\n\nclass SelfCheckState:\n    def __init__(self, cache_dir: str) -> None:\n        self._state: Dict[str, Any] = {}\n        self._statefile_path = None\n\n        # Try to load the existing state\n        if cache_dir:\n            self._statefile_path = os.path.join(\n                cache_dir, \"selfcheck\", _get_statefile_name(self.key)\n            )\n            try:\n                with open(self._statefile_path, encoding=\"utf-8\") as statefile:\n                    self._state = json.load(statefile)\n            except (OSError, ValueError, KeyError):\n                # Explicitly suppressing exceptions, since we don't want to\n                # error out if the cache file is invalid.\n                pass\n\n    @property\n    def key(self) -> str:\n        return sys.prefix\n\n    def get(self, current_time: datetime.datetime) -> Optional[str]:\n        \"\"\"Check if we have a not-outdated version loaded already.\"\"\"\n        if not self._state:\n            return None\n\n        if \"last_check\" not in self._state:\n            return None\n\n        if \"pypi_version\" not in self._state:\n            return None\n\n        seven_days_in_seconds = 7 * 24 * 60 * 60\n\n        # Determine if we need to refresh the state\n        last_check = datetime.datetime.strptime(self._state[\"last_check\"], _DATE_FMT)\n        seconds_since_last_check = (current_time - last_check).total_seconds()\n        if seconds_since_last_check > seven_days_in_seconds:\n            return None\n\n        return self._state[\"pypi_version\"]\n\n    def set(self, pypi_version: str, current_time: datetime.datetime) -> None:\n        # If we do not have a path to cache in, don't bother saving.\n        if not self._statefile_path:\n            return\n\n        # Check to make sure that we own the directory\n        if not check_path_owner(os.path.dirname(self._statefile_path)):\n            return\n\n        # Now that we've ensured the directory is owned by this user, we'll go\n        # ahead and make sure that all our directories are created.\n        ensure_dir(os.path.dirname(self._statefile_path))\n\n        state = {\n            # Include the key so it's easy to tell which pip wrote the\n            # file.\n            \"key\": self.key,\n            \"last_check\": current_time.strftime(_DATE_FMT),\n            \"pypi_version\": pypi_version,\n        }\n\n        text = json.dumps(state, sort_keys=True, separators=(\",\", \":\"))\n\n        with adjacent_tmp_file(self._statefile_path) as f:\n            f.write(text.encode())\n\n        try:\n            # Since we have a prefix-specific state file, we can just\n            # overwrite whatever is there, no need to check.\n            replace(f.name, self._statefile_path)\n        except OSError:\n            # Best effort.\n            pass\n\n\n@dataclass\nclass UpgradePrompt:\n    old: str\n    new: str\n\n    def __rich__(self) -> Group:\n        if WINDOWS:\n            pip_cmd = f\"{get_best_invocation_for_this_python()} -m pip\"\n        else:\n            pip_cmd = get_best_invocation_for_this_pip()\n\n        notice = \"[bold][[reset][blue]notice[reset][bold]][reset]\"\n        return Group(\n            Text(),\n            Text.from_markup(\n                f\"{notice} A new release of pip available: \"\n                f\"[red]{self.old}[reset] -> [green]{self.new}[reset]\"\n            ),\n            Text.from_markup(\n                f\"{notice} To update, run: \"\n                f\"[green]{escape(pip_cmd)} install --upgrade pip\"\n            ),\n        )\n\n\ndef was_installed_by_pip(pkg: str) -> bool:\n    \"\"\"Checks whether pkg was installed by pip\n\n    This is used not to display the upgrade message when pip is in fact\n    installed by system package manager, such as dnf on Fedora.\n    \"\"\"\n    dist = get_default_environment().get_distribution(pkg)\n    return dist is not None and \"pip\" == dist.installer\n\n\ndef _get_current_remote_pip_version(\n    session: PipSession, options: optparse.Values\n) -> str:\n    # Lets use PackageFinder to see what the latest pip version is\n    link_collector = LinkCollector.create(\n        session,\n        options=options,\n        suppress_no_index=True,\n    )\n\n    # Pass allow_yanked=False so we don't suggest upgrading to a\n    # yanked version.\n    selection_prefs = SelectionPreferences(\n        allow_yanked=False,\n        allow_all_prereleases=False,  # Explicitly set to False\n    )\n\n    finder = PackageFinder.create(\n        link_collector=link_collector,\n        selection_prefs=selection_prefs,\n    )\n    best_candidate = finder.find_best_candidate(\"pip\").best_candidate\n    if best_candidate is None:\n        return\n\n    return str(best_candidate.version)\n\n\ndef _self_version_check_logic(\n    *,\n    state: SelfCheckState,\n    current_time: datetime.datetime,\n    local_version: DistributionVersion,\n    get_remote_version: Callable[[], str],\n) -> Optional[UpgradePrompt]:\n    remote_version_str = state.get(current_time)\n    if remote_version_str is None:\n        remote_version_str = get_remote_version()\n        state.set(remote_version_str, current_time)\n\n    remote_version = parse_version(remote_version_str)\n    logger.debug(\"Remote version of pip: %s\", remote_version)\n    logger.debug(\"Local version of pip:  %s\", local_version)\n\n    pip_installed_by_pip = was_installed_by_pip(\"pip\")\n    logger.debug(\"Was pip installed by pip? %s\", pip_installed_by_pip)\n    if not pip_installed_by_pip:\n        return None  # Only suggest upgrade if pip is installed by pip.\n\n    local_version_is_older = (\n        local_version < remote_version\n        and local_version.base_version != remote_version.base_version\n    )\n    if local_version_is_older:\n        return UpgradePrompt(old=str(local_version), new=remote_version_str)\n\n    return None\n\n\ndef pip_self_version_check(session: PipSession, options: optparse.Values) -> None:\n    \"\"\"Check for an update for pip.\n\n    Limit the frequency of checks to once per week. State is stored either in\n    the active virtualenv or in the user's USER_CACHE_DIR keyed off the prefix\n    of the pip script path.\n    \"\"\"\n    installed_dist = get_default_environment().get_distribution(\"pip\")\n    if not installed_dist:\n        return\n\n    try:\n        upgrade_prompt = _self_version_check_logic(\n            state=SelfCheckState(cache_dir=options.cache_dir),\n            current_time=datetime.datetime.utcnow(),\n            local_version=installed_dist.version,\n            get_remote_version=functools.partial(\n                _get_current_remote_pip_version, session, options\n            ),\n        )\n        if upgrade_prompt is not None:\n            logger.warning(\"[present-rich] %s\", upgrade_prompt)\n    except Exception:\n        logger.warning(\"There was an error checking the latest version of pip.\")\n        logger.debug(\"See below for error\", exc_info=True)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/_log.py",
    "content": "\"\"\"Customize logging\n\nDefines custom logger class for the `logger.verbose(...)` method.\n\ninit_logging() must be called before any other modules that call logging.getLogger.\n\"\"\"\n\nimport logging\nfrom typing import Any, cast\n\n# custom log level for `--verbose` output\n# between DEBUG and INFO\nVERBOSE = 15\n\n\nclass VerboseLogger(logging.Logger):\n    \"\"\"Custom Logger, defining a verbose log-level\n\n    VERBOSE is between INFO and DEBUG.\n    \"\"\"\n\n    def verbose(self, msg: str, *args: Any, **kwargs: Any) -> None:\n        return self.log(VERBOSE, msg, *args, **kwargs)\n\n\ndef getLogger(name: str) -> VerboseLogger:\n    \"\"\"logging.getLogger, but ensures our VerboseLogger class is returned\"\"\"\n    return cast(VerboseLogger, logging.getLogger(name))\n\n\ndef init_logging() -> None:\n    \"\"\"Register our VerboseLogger and VERBOSE log level.\n\n    Should be called before any calls to getLogger(),\n    i.e. in pip._internal.__init__\n    \"\"\"\n    logging.setLoggerClass(VerboseLogger)\n    logging.addLevelName(VERBOSE, \"VERBOSE\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/appdirs.py",
    "content": "\"\"\"\nThis code wraps the vendored appdirs module to so the return values are\ncompatible for the current pip code base.\n\nThe intention is to rewrite current usages gradually, keeping the tests pass,\nand eventually drop this after all usages are changed.\n\"\"\"\n\nimport os\nimport sys\nfrom typing import List\n\nfrom pip._vendor import platformdirs as _appdirs\n\n\ndef user_cache_dir(appname: str) -> str:\n    return _appdirs.user_cache_dir(appname, appauthor=False)\n\n\ndef _macos_user_config_dir(appname: str, roaming: bool = True) -> str:\n    # Use ~/Application Support/pip, if the directory exists.\n    path = _appdirs.user_data_dir(appname, appauthor=False, roaming=roaming)\n    if os.path.isdir(path):\n        return path\n\n    # Use a Linux-like ~/.config/pip, by default.\n    linux_like_path = \"~/.config/\"\n    if appname:\n        linux_like_path = os.path.join(linux_like_path, appname)\n\n    return os.path.expanduser(linux_like_path)\n\n\ndef user_config_dir(appname: str, roaming: bool = True) -> str:\n    if sys.platform == \"darwin\":\n        return _macos_user_config_dir(appname, roaming)\n\n    return _appdirs.user_config_dir(appname, appauthor=False, roaming=roaming)\n\n\n# for the discussion regarding site_config_dir locations\n# see <https://github.com/pypa/pip/issues/1733>\ndef site_config_dirs(appname: str) -> List[str]:\n    if sys.platform == \"darwin\":\n        return [_appdirs.site_data_dir(appname, appauthor=False, multipath=True)]\n\n    dirval = _appdirs.site_config_dir(appname, appauthor=False, multipath=True)\n    if sys.platform == \"win32\":\n        return [dirval]\n\n    # Unix-y system. Look in /etc as well.\n    return dirval.split(os.pathsep) + [\"/etc\"]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/compat.py",
    "content": "\"\"\"Stuff that differs in different Python versions and platform\ndistributions.\"\"\"\n\nimport logging\nimport os\nimport sys\n\n__all__ = [\"get_path_uid\", \"stdlib_pkgs\", \"WINDOWS\"]\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef has_tls() -> bool:\n    try:\n        import _ssl  # noqa: F401  # ignore unused\n\n        return True\n    except ImportError:\n        pass\n\n    from pip._vendor.urllib3.util import IS_PYOPENSSL\n\n    return IS_PYOPENSSL\n\n\ndef get_path_uid(path: str) -> int:\n    \"\"\"\n    Return path's uid.\n\n    Does not follow symlinks:\n        https://github.com/pypa/pip/pull/935#discussion_r5307003\n\n    Placed this function in compat due to differences on AIX and\n    Jython, that should eventually go away.\n\n    :raises OSError: When path is a symlink or can't be read.\n    \"\"\"\n    if hasattr(os, \"O_NOFOLLOW\"):\n        fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)\n        file_uid = os.fstat(fd).st_uid\n        os.close(fd)\n    else:  # AIX and Jython\n        # WARNING: time of check vulnerability, but best we can do w/o NOFOLLOW\n        if not os.path.islink(path):\n            # older versions of Jython don't have `os.fstat`\n            file_uid = os.stat(path).st_uid\n        else:\n            # raise OSError for parity with os.O_NOFOLLOW above\n            raise OSError(f\"{path} is a symlink; Will not return uid for symlinks\")\n    return file_uid\n\n\n# packages in the stdlib that may have installation metadata, but should not be\n# considered 'installed'.  this theoretically could be determined based on\n# dist.location (py27:`sysconfig.get_paths()['stdlib']`,\n# py26:sysconfig.get_config_vars('LIBDEST')), but fear platform variation may\n# make this ineffective, so hard-coding\nstdlib_pkgs = {\"python\", \"wsgiref\", \"argparse\"}\n\n\n# windows detection, covers cpython and ironpython\nWINDOWS = sys.platform.startswith(\"win\") or (sys.platform == \"cli\" and os.name == \"nt\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/compatibility_tags.py",
    "content": "\"\"\"Generate and work with PEP 425 Compatibility Tags.\n\"\"\"\n\nimport re\nfrom typing import List, Optional, Tuple\n\nfrom pip._vendor.packaging.tags import (\n    PythonVersion,\n    Tag,\n    compatible_tags,\n    cpython_tags,\n    generic_tags,\n    interpreter_name,\n    interpreter_version,\n    mac_platforms,\n)\n\n_osx_arch_pat = re.compile(r\"(.+)_(\\d+)_(\\d+)_(.+)\")\n\n\ndef version_info_to_nodot(version_info: Tuple[int, ...]) -> str:\n    # Only use up to the first two numbers.\n    return \"\".join(map(str, version_info[:2]))\n\n\ndef _mac_platforms(arch: str) -> List[str]:\n    match = _osx_arch_pat.match(arch)\n    if match:\n        name, major, minor, actual_arch = match.groups()\n        mac_version = (int(major), int(minor))\n        arches = [\n            # Since we have always only checked that the platform starts\n            # with \"macosx\", for backwards-compatibility we extract the\n            # actual prefix provided by the user in case they provided\n            # something like \"macosxcustom_\". It may be good to remove\n            # this as undocumented or deprecate it in the future.\n            \"{}_{}\".format(name, arch[len(\"macosx_\") :])\n            for arch in mac_platforms(mac_version, actual_arch)\n        ]\n    else:\n        # arch pattern didn't match (?!)\n        arches = [arch]\n    return arches\n\n\ndef _custom_manylinux_platforms(arch: str) -> List[str]:\n    arches = [arch]\n    arch_prefix, arch_sep, arch_suffix = arch.partition(\"_\")\n    if arch_prefix == \"manylinux2014\":\n        # manylinux1/manylinux2010 wheels run on most manylinux2014 systems\n        # with the exception of wheels depending on ncurses. PEP 599 states\n        # manylinux1/manylinux2010 wheels should be considered\n        # manylinux2014 wheels:\n        # https://www.python.org/dev/peps/pep-0599/#backwards-compatibility-with-manylinux2010-wheels\n        if arch_suffix in {\"i686\", \"x86_64\"}:\n            arches.append(\"manylinux2010\" + arch_sep + arch_suffix)\n            arches.append(\"manylinux1\" + arch_sep + arch_suffix)\n    elif arch_prefix == \"manylinux2010\":\n        # manylinux1 wheels run on most manylinux2010 systems with the\n        # exception of wheels depending on ncurses. PEP 571 states\n        # manylinux1 wheels should be considered manylinux2010 wheels:\n        # https://www.python.org/dev/peps/pep-0571/#backwards-compatibility-with-manylinux1-wheels\n        arches.append(\"manylinux1\" + arch_sep + arch_suffix)\n    return arches\n\n\ndef _get_custom_platforms(arch: str) -> List[str]:\n    arch_prefix, arch_sep, arch_suffix = arch.partition(\"_\")\n    if arch.startswith(\"macosx\"):\n        arches = _mac_platforms(arch)\n    elif arch_prefix in [\"manylinux2014\", \"manylinux2010\"]:\n        arches = _custom_manylinux_platforms(arch)\n    else:\n        arches = [arch]\n    return arches\n\n\ndef _expand_allowed_platforms(platforms: Optional[List[str]]) -> Optional[List[str]]:\n    if not platforms:\n        return None\n\n    seen = set()\n    result = []\n\n    for p in platforms:\n        if p in seen:\n            continue\n        additions = [c for c in _get_custom_platforms(p) if c not in seen]\n        seen.update(additions)\n        result.extend(additions)\n\n    return result\n\n\ndef _get_python_version(version: str) -> PythonVersion:\n    if len(version) > 1:\n        return int(version[0]), int(version[1:])\n    else:\n        return (int(version[0]),)\n\n\ndef _get_custom_interpreter(\n    implementation: Optional[str] = None, version: Optional[str] = None\n) -> str:\n    if implementation is None:\n        implementation = interpreter_name()\n    if version is None:\n        version = interpreter_version()\n    return f\"{implementation}{version}\"\n\n\ndef get_supported(\n    version: Optional[str] = None,\n    platforms: Optional[List[str]] = None,\n    impl: Optional[str] = None,\n    abis: Optional[List[str]] = None,\n) -> List[Tag]:\n    \"\"\"Return a list of supported tags for each version specified in\n    `versions`.\n\n    :param version: a string version, of the form \"33\" or \"32\",\n        or None. The version will be assumed to support our ABI.\n    :param platform: specify a list of platforms you want valid\n        tags for, or None. If None, use the local system platform.\n    :param impl: specify the exact implementation you want valid\n        tags for, or None. If None, use the local interpreter impl.\n    :param abis: specify a list of abis you want valid\n        tags for, or None. If None, use the local interpreter abi.\n    \"\"\"\n    supported: List[Tag] = []\n\n    python_version: Optional[PythonVersion] = None\n    if version is not None:\n        python_version = _get_python_version(version)\n\n    interpreter = _get_custom_interpreter(impl, version)\n\n    platforms = _expand_allowed_platforms(platforms)\n\n    is_cpython = (impl or interpreter_name()) == \"cp\"\n    if is_cpython:\n        supported.extend(\n            cpython_tags(\n                python_version=python_version,\n                abis=abis,\n                platforms=platforms,\n            )\n        )\n    else:\n        supported.extend(\n            generic_tags(\n                interpreter=interpreter,\n                abis=abis,\n                platforms=platforms,\n            )\n        )\n    supported.extend(\n        compatible_tags(\n            python_version=python_version,\n            interpreter=interpreter,\n            platforms=platforms,\n        )\n    )\n\n    return supported\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/datetime.py",
    "content": "\"\"\"For when pip wants to check the date or time.\n\"\"\"\n\nimport datetime\n\n\ndef today_is_later_than(year: int, month: int, day: int) -> bool:\n    today = datetime.date.today()\n    given = datetime.date(year, month, day)\n\n    return today > given\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/deprecation.py",
    "content": "\"\"\"\nA module that implements tooling to enable easy warnings about deprecations.\n\"\"\"\n\nimport logging\nimport warnings\nfrom typing import Any, Optional, TextIO, Type, Union\n\nfrom pip._vendor.packaging.version import parse\n\nfrom pip import __version__ as current_version  # NOTE: tests patch this name.\n\nDEPRECATION_MSG_PREFIX = \"DEPRECATION: \"\n\n\nclass PipDeprecationWarning(Warning):\n    pass\n\n\n_original_showwarning: Any = None\n\n\n# Warnings <-> Logging Integration\ndef _showwarning(\n    message: Union[Warning, str],\n    category: Type[Warning],\n    filename: str,\n    lineno: int,\n    file: Optional[TextIO] = None,\n    line: Optional[str] = None,\n) -> None:\n    if file is not None:\n        if _original_showwarning is not None:\n            _original_showwarning(message, category, filename, lineno, file, line)\n    elif issubclass(category, PipDeprecationWarning):\n        # We use a specially named logger which will handle all of the\n        # deprecation messages for pip.\n        logger = logging.getLogger(\"pip._internal.deprecations\")\n        logger.warning(message)\n    else:\n        _original_showwarning(message, category, filename, lineno, file, line)\n\n\ndef install_warning_logger() -> None:\n    # Enable our Deprecation Warnings\n    warnings.simplefilter(\"default\", PipDeprecationWarning, append=True)\n\n    global _original_showwarning\n\n    if _original_showwarning is None:\n        _original_showwarning = warnings.showwarning\n        warnings.showwarning = _showwarning\n\n\ndef deprecated(\n    *,\n    reason: str,\n    replacement: Optional[str],\n    gone_in: Optional[str],\n    feature_flag: Optional[str] = None,\n    issue: Optional[int] = None,\n) -> None:\n    \"\"\"Helper to deprecate existing functionality.\n\n    reason:\n        Textual reason shown to the user about why this functionality has\n        been deprecated. Should be a complete sentence.\n    replacement:\n        Textual suggestion shown to the user about what alternative\n        functionality they can use.\n    gone_in:\n        The version of pip does this functionality should get removed in.\n        Raises an error if pip's current version is greater than or equal to\n        this.\n    feature_flag:\n        Command-line flag of the form --use-feature={feature_flag} for testing\n        upcoming functionality.\n    issue:\n        Issue number on the tracker that would serve as a useful place for\n        users to find related discussion and provide feedback.\n    \"\"\"\n\n    # Determine whether or not the feature is already gone in this version.\n    is_gone = gone_in is not None and parse(current_version) >= parse(gone_in)\n\n    message_parts = [\n        (reason, f\"{DEPRECATION_MSG_PREFIX}{{}}\"),\n        (\n            gone_in,\n            \"pip {} will enforce this behaviour change.\"\n            if not is_gone\n            else \"Since pip {}, this is no longer supported.\",\n        ),\n        (\n            replacement,\n            \"A possible replacement is {}.\",\n        ),\n        (\n            feature_flag,\n            \"You can use the flag --use-feature={} to test the upcoming behaviour.\"\n            if not is_gone\n            else None,\n        ),\n        (\n            issue,\n            \"Discussion can be found at https://github.com/pypa/pip/issues/{}\",\n        ),\n    ]\n\n    message = \" \".join(\n        format_str.format(value)\n        for value, format_str in message_parts\n        if format_str is not None and value is not None\n    )\n\n    # Raise as an error if this behaviour is deprecated.\n    if is_gone:\n        raise PipDeprecationWarning(message)\n\n    warnings.warn(message, category=PipDeprecationWarning, stacklevel=2)\n\n\nclass LegacyInstallReason:\n    def __init__(\n        self,\n        reason: str,\n        replacement: Optional[str] = None,\n        gone_in: Optional[str] = None,\n        feature_flag: Optional[str] = None,\n        issue: Optional[int] = None,\n        emit_after_success: bool = False,\n        emit_before_install: bool = False,\n    ):\n        self._reason = reason\n        self._replacement = replacement\n        self._gone_in = gone_in\n        self._feature_flag = feature_flag\n        self._issue = issue\n        self.emit_after_success = emit_after_success\n        self.emit_before_install = emit_before_install\n\n    def emit_deprecation(self, name: str) -> None:\n        deprecated(\n            reason=self._reason.format(name=name),\n            replacement=self._replacement,\n            gone_in=self._gone_in,\n            feature_flag=self._feature_flag,\n            issue=self._issue,\n        )\n\n\nLegacyInstallReasonFailedBdistWheel = LegacyInstallReason(\n    reason=(\n        \"{name} was installed using the legacy 'setup.py install' \"\n        \"method, because a wheel could not be built for it.\"\n    ),\n    replacement=\"to fix the wheel build issue reported above\",\n    gone_in=\"23.1\",\n    issue=8368,\n    emit_after_success=True,\n)\n\n\nLegacyInstallReasonMissingWheelPackage = LegacyInstallReason(\n    reason=(\n        \"{name} is being installed using the legacy \"\n        \"'setup.py install' method, because it does not have a \"\n        \"'pyproject.toml' and the 'wheel' package \"\n        \"is not installed.\"\n    ),\n    replacement=\"to enable the '--use-pep517' option\",\n    gone_in=\"23.1\",\n    issue=8559,\n    emit_before_install=True,\n)\n\nLegacyInstallReasonNoBinaryForcesSetuptoolsInstall = LegacyInstallReason(\n    reason=(\n        \"{name} is being installed using the legacy \"\n        \"'setup.py install' method, because the '--no-binary' option was enabled \"\n        \"for it and this currently disables local wheel building for projects that \"\n        \"don't have a 'pyproject.toml' file.\"\n    ),\n    replacement=\"to enable the '--use-pep517' option\",\n    gone_in=\"23.1\",\n    issue=11451,\n    emit_before_install=True,\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/direct_url_helpers.py",
    "content": "from typing import Optional\n\nfrom pip._internal.models.direct_url import ArchiveInfo, DirectUrl, DirInfo, VcsInfo\nfrom pip._internal.models.link import Link\nfrom pip._internal.utils.urls import path_to_url\nfrom pip._internal.vcs import vcs\n\n\ndef direct_url_as_pep440_direct_reference(direct_url: DirectUrl, name: str) -> str:\n    \"\"\"Convert a DirectUrl to a pip requirement string.\"\"\"\n    direct_url.validate()  # if invalid, this is a pip bug\n    requirement = name + \" @ \"\n    fragments = []\n    if isinstance(direct_url.info, VcsInfo):\n        requirement += \"{}+{}@{}\".format(\n            direct_url.info.vcs, direct_url.url, direct_url.info.commit_id\n        )\n    elif isinstance(direct_url.info, ArchiveInfo):\n        requirement += direct_url.url\n        if direct_url.info.hash:\n            fragments.append(direct_url.info.hash)\n    else:\n        assert isinstance(direct_url.info, DirInfo)\n        requirement += direct_url.url\n    if direct_url.subdirectory:\n        fragments.append(\"subdirectory=\" + direct_url.subdirectory)\n    if fragments:\n        requirement += \"#\" + \"&\".join(fragments)\n    return requirement\n\n\ndef direct_url_for_editable(source_dir: str) -> DirectUrl:\n    return DirectUrl(\n        url=path_to_url(source_dir),\n        info=DirInfo(editable=True),\n    )\n\n\ndef direct_url_from_link(\n    link: Link, source_dir: Optional[str] = None, link_is_in_wheel_cache: bool = False\n) -> DirectUrl:\n    if link.is_vcs:\n        vcs_backend = vcs.get_backend_for_scheme(link.scheme)\n        assert vcs_backend\n        url, requested_revision, _ = vcs_backend.get_url_rev_and_auth(\n            link.url_without_fragment\n        )\n        # For VCS links, we need to find out and add commit_id.\n        if link_is_in_wheel_cache:\n            # If the requested VCS link corresponds to a cached\n            # wheel, it means the requested revision was an\n            # immutable commit hash, otherwise it would not have\n            # been cached. In that case we don't have a source_dir\n            # with the VCS checkout.\n            assert requested_revision\n            commit_id = requested_revision\n        else:\n            # If the wheel was not in cache, it means we have\n            # had to checkout from VCS to build and we have a source_dir\n            # which we can inspect to find out the commit id.\n            assert source_dir\n            commit_id = vcs_backend.get_revision(source_dir)\n        return DirectUrl(\n            url=url,\n            info=VcsInfo(\n                vcs=vcs_backend.name,\n                commit_id=commit_id,\n                requested_revision=requested_revision,\n            ),\n            subdirectory=link.subdirectory_fragment,\n        )\n    elif link.is_existing_dir():\n        return DirectUrl(\n            url=link.url_without_fragment,\n            info=DirInfo(),\n            subdirectory=link.subdirectory_fragment,\n        )\n    else:\n        hash = None\n        hash_name = link.hash_name\n        if hash_name:\n            hash = f\"{hash_name}={link.hash}\"\n        return DirectUrl(\n            url=link.url_without_fragment,\n            info=ArchiveInfo(hash=hash),\n            subdirectory=link.subdirectory_fragment,\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/distutils_args.py",
    "content": "from getopt import GetoptError, getopt\nfrom typing import Dict, List\n\n_options = [\n    \"exec-prefix=\",\n    \"home=\",\n    \"install-base=\",\n    \"install-data=\",\n    \"install-headers=\",\n    \"install-lib=\",\n    \"install-platlib=\",\n    \"install-purelib=\",\n    \"install-scripts=\",\n    \"prefix=\",\n    \"root=\",\n    \"user\",\n]\n\n\ndef parse_distutils_args(args: List[str]) -> Dict[str, str]:\n    \"\"\"Parse provided arguments, returning an object that has the matched arguments.\n\n    Any unknown arguments are ignored.\n    \"\"\"\n    result = {}\n    for arg in args:\n        try:\n            parsed_opt, _ = getopt(args=[arg], shortopts=\"\", longopts=_options)\n        except GetoptError:\n            # We don't care about any other options, which here may be\n            # considered unrecognized since our option list is not\n            # exhaustive.\n            continue\n\n        if not parsed_opt:\n            continue\n\n        option = parsed_opt[0]\n        name_from_parsed = option[0][2:].replace(\"-\", \"_\")\n        value_from_parsed = option[1] or \"true\"\n        result[name_from_parsed] = value_from_parsed\n\n    return result\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/egg_link.py",
    "content": "# The following comment should be removed at some point in the future.\n# mypy: strict-optional=False\n\nimport os\nimport re\nimport sys\nfrom typing import Optional\n\nfrom pip._internal.locations import site_packages, user_site\nfrom pip._internal.utils.virtualenv import (\n    running_under_virtualenv,\n    virtualenv_no_global,\n)\n\n__all__ = [\n    \"egg_link_path_from_sys_path\",\n    \"egg_link_path_from_location\",\n]\n\n\ndef _egg_link_name(raw_name: str) -> str:\n    \"\"\"\n    Convert a Name metadata value to a .egg-link name, by applying\n    the same substitution as pkg_resources's safe_name function.\n    Note: we cannot use canonicalize_name because it has a different logic.\n    \"\"\"\n    return re.sub(\"[^A-Za-z0-9.]+\", \"-\", raw_name) + \".egg-link\"\n\n\ndef egg_link_path_from_sys_path(raw_name: str) -> Optional[str]:\n    \"\"\"\n    Look for a .egg-link file for project name, by walking sys.path.\n    \"\"\"\n    egg_link_name = _egg_link_name(raw_name)\n    for path_item in sys.path:\n        egg_link = os.path.join(path_item, egg_link_name)\n        if os.path.isfile(egg_link):\n            return egg_link\n    return None\n\n\ndef egg_link_path_from_location(raw_name: str) -> Optional[str]:\n    \"\"\"\n    Return the path for the .egg-link file if it exists, otherwise, None.\n\n    There's 3 scenarios:\n    1) not in a virtualenv\n       try to find in site.USER_SITE, then site_packages\n    2) in a no-global virtualenv\n       try to find in site_packages\n    3) in a yes-global virtualenv\n       try to find in site_packages, then site.USER_SITE\n       (don't look in global location)\n\n    For #1 and #3, there could be odd cases, where there's an egg-link in 2\n    locations.\n\n    This method will just return the first one found.\n    \"\"\"\n    sites = []\n    if running_under_virtualenv():\n        sites.append(site_packages)\n        if not virtualenv_no_global() and user_site:\n            sites.append(user_site)\n    else:\n        if user_site:\n            sites.append(user_site)\n        sites.append(site_packages)\n\n    egg_link_name = _egg_link_name(raw_name)\n    for site in sites:\n        egglink = os.path.join(site, egg_link_name)\n        if os.path.isfile(egglink):\n            return egglink\n    return None\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/encoding.py",
    "content": "import codecs\nimport locale\nimport re\nimport sys\nfrom typing import List, Tuple\n\nBOMS: List[Tuple[bytes, str]] = [\n    (codecs.BOM_UTF8, \"utf-8\"),\n    (codecs.BOM_UTF16, \"utf-16\"),\n    (codecs.BOM_UTF16_BE, \"utf-16-be\"),\n    (codecs.BOM_UTF16_LE, \"utf-16-le\"),\n    (codecs.BOM_UTF32, \"utf-32\"),\n    (codecs.BOM_UTF32_BE, \"utf-32-be\"),\n    (codecs.BOM_UTF32_LE, \"utf-32-le\"),\n]\n\nENCODING_RE = re.compile(rb\"coding[:=]\\s*([-\\w.]+)\")\n\n\ndef auto_decode(data: bytes) -> str:\n    \"\"\"Check a bytes string for a BOM to correctly detect the encoding\n\n    Fallback to locale.getpreferredencoding(False) like open() on Python3\"\"\"\n    for bom, encoding in BOMS:\n        if data.startswith(bom):\n            return data[len(bom) :].decode(encoding)\n    # Lets check the first two lines as in PEP263\n    for line in data.split(b\"\\n\")[:2]:\n        if line[0:1] == b\"#\" and ENCODING_RE.search(line):\n            result = ENCODING_RE.search(line)\n            assert result is not None\n            encoding = result.groups()[0].decode(\"ascii\")\n            return data.decode(encoding)\n    return data.decode(\n        locale.getpreferredencoding(False) or sys.getdefaultencoding(),\n    )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/entrypoints.py",
    "content": "import itertools\nimport os\nimport shutil\nimport sys\nfrom typing import List, Optional\n\nfrom pip._internal.cli.main import main\nfrom pip._internal.utils.compat import WINDOWS\n\n_EXECUTABLE_NAMES = [\n    \"pip\",\n    f\"pip{sys.version_info.major}\",\n    f\"pip{sys.version_info.major}.{sys.version_info.minor}\",\n]\nif WINDOWS:\n    _allowed_extensions = {\"\", \".exe\"}\n    _EXECUTABLE_NAMES = [\n        \"\".join(parts)\n        for parts in itertools.product(_EXECUTABLE_NAMES, _allowed_extensions)\n    ]\n\n\ndef _wrapper(args: Optional[List[str]] = None) -> int:\n    \"\"\"Central wrapper for all old entrypoints.\n\n    Historically pip has had several entrypoints defined. Because of issues\n    arising from PATH, sys.path, multiple Pythons, their interactions, and most\n    of them having a pip installed, users suffer every time an entrypoint gets\n    moved.\n\n    To alleviate this pain, and provide a mechanism for warning users and\n    directing them to an appropriate place for help, we now define all of\n    our old entrypoints as wrappers for the current one.\n    \"\"\"\n    sys.stderr.write(\n        \"WARNING: pip is being invoked by an old script wrapper. This will \"\n        \"fail in a future version of pip.\\n\"\n        \"Please see https://github.com/pypa/pip/issues/5599 for advice on \"\n        \"fixing the underlying issue.\\n\"\n        \"To avoid this problem you can invoke Python with '-m pip' instead of \"\n        \"running pip directly.\\n\"\n    )\n    return main(args)\n\n\ndef get_best_invocation_for_this_pip() -> str:\n    \"\"\"Try to figure out the best way to invoke pip in the current environment.\"\"\"\n    binary_directory = \"Scripts\" if WINDOWS else \"bin\"\n    binary_prefix = os.path.join(sys.prefix, binary_directory)\n\n    # Try to use pip[X[.Y]] names, if those executables for this environment are\n    # the first on PATH with that name.\n    path_parts = os.path.normcase(os.environ.get(\"PATH\", \"\")).split(os.pathsep)\n    exe_are_in_PATH = os.path.normcase(binary_prefix) in path_parts\n    if exe_are_in_PATH:\n        for exe_name in _EXECUTABLE_NAMES:\n            found_executable = shutil.which(exe_name)\n            binary_executable = os.path.join(binary_prefix, exe_name)\n            if (\n                found_executable\n                and os.path.exists(binary_executable)\n                and os.path.samefile(\n                    found_executable,\n                    binary_executable,\n                )\n            ):\n                return exe_name\n\n    # Use the `-m` invocation, if there's no \"nice\" invocation.\n    return f\"{get_best_invocation_for_this_python()} -m pip\"\n\n\ndef get_best_invocation_for_this_python() -> str:\n    \"\"\"Try to figure out the best way to invoke the current Python.\"\"\"\n    exe = sys.executable\n    exe_name = os.path.basename(exe)\n\n    # Try to use the basename, if it's the first executable.\n    found_executable = shutil.which(exe_name)\n    if found_executable and os.path.samefile(found_executable, exe):\n        return exe_name\n\n    # Use the full executable name, because we couldn't find something simpler.\n    return exe\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/filesystem.py",
    "content": "import fnmatch\nimport os\nimport os.path\nimport random\nimport sys\nfrom contextlib import contextmanager\nfrom tempfile import NamedTemporaryFile\nfrom typing import Any, BinaryIO, Generator, List, Union, cast\n\nfrom pip._vendor.tenacity import retry, stop_after_delay, wait_fixed\n\nfrom pip._internal.utils.compat import get_path_uid\nfrom pip._internal.utils.misc import format_size\n\n\ndef check_path_owner(path: str) -> bool:\n    # If we don't have a way to check the effective uid of this process, then\n    # we'll just assume that we own the directory.\n    if sys.platform == \"win32\" or not hasattr(os, \"geteuid\"):\n        return True\n\n    assert os.path.isabs(path)\n\n    previous = None\n    while path != previous:\n        if os.path.lexists(path):\n            # Check if path is writable by current user.\n            if os.geteuid() == 0:\n                # Special handling for root user in order to handle properly\n                # cases where users use sudo without -H flag.\n                try:\n                    path_uid = get_path_uid(path)\n                except OSError:\n                    return False\n                return path_uid == 0\n            else:\n                return os.access(path, os.W_OK)\n        else:\n            previous, path = path, os.path.dirname(path)\n    return False  # assume we don't own the path\n\n\n@contextmanager\ndef adjacent_tmp_file(path: str, **kwargs: Any) -> Generator[BinaryIO, None, None]:\n    \"\"\"Return a file-like object pointing to a tmp file next to path.\n\n    The file is created securely and is ensured to be written to disk\n    after the context reaches its end.\n\n    kwargs will be passed to tempfile.NamedTemporaryFile to control\n    the way the temporary file will be opened.\n    \"\"\"\n    with NamedTemporaryFile(\n        delete=False,\n        dir=os.path.dirname(path),\n        prefix=os.path.basename(path),\n        suffix=\".tmp\",\n        **kwargs,\n    ) as f:\n        result = cast(BinaryIO, f)\n        try:\n            yield result\n        finally:\n            result.flush()\n            os.fsync(result.fileno())\n\n\n# Tenacity raises RetryError by default, explicitly raise the original exception\n_replace_retry = retry(reraise=True, stop=stop_after_delay(1), wait=wait_fixed(0.25))\n\nreplace = _replace_retry(os.replace)\n\n\n# test_writable_dir and _test_writable_dir_win are copied from Flit,\n# with the author's agreement to also place them under pip's license.\ndef test_writable_dir(path: str) -> bool:\n    \"\"\"Check if a directory is writable.\n\n    Uses os.access() on POSIX, tries creating files on Windows.\n    \"\"\"\n    # If the directory doesn't exist, find the closest parent that does.\n    while not os.path.isdir(path):\n        parent = os.path.dirname(path)\n        if parent == path:\n            break  # Should never get here, but infinite loops are bad\n        path = parent\n\n    if os.name == \"posix\":\n        return os.access(path, os.W_OK)\n\n    return _test_writable_dir_win(path)\n\n\ndef _test_writable_dir_win(path: str) -> bool:\n    # os.access doesn't work on Windows: http://bugs.python.org/issue2528\n    # and we can't use tempfile: http://bugs.python.org/issue22107\n    basename = \"accesstest_deleteme_fishfingers_custard_\"\n    alphabet = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n    for _ in range(10):\n        name = basename + \"\".join(random.choice(alphabet) for _ in range(6))\n        file = os.path.join(path, name)\n        try:\n            fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL)\n        except FileExistsError:\n            pass\n        except PermissionError:\n            # This could be because there's a directory with the same name.\n            # But it's highly unlikely there's a directory called that,\n            # so we'll assume it's because the parent dir is not writable.\n            # This could as well be because the parent dir is not readable,\n            # due to non-privileged user access.\n            return False\n        else:\n            os.close(fd)\n            os.unlink(file)\n            return True\n\n    # This should never be reached\n    raise OSError(\"Unexpected condition testing for writable directory\")\n\n\ndef find_files(path: str, pattern: str) -> List[str]:\n    \"\"\"Returns a list of absolute paths of files beneath path, recursively,\n    with filenames which match the UNIX-style shell glob pattern.\"\"\"\n    result: List[str] = []\n    for root, _, files in os.walk(path):\n        matches = fnmatch.filter(files, pattern)\n        result.extend(os.path.join(root, f) for f in matches)\n    return result\n\n\ndef file_size(path: str) -> Union[int, float]:\n    # If it's a symlink, return 0.\n    if os.path.islink(path):\n        return 0\n    return os.path.getsize(path)\n\n\ndef format_file_size(path: str) -> str:\n    return format_size(file_size(path))\n\n\ndef directory_size(path: str) -> Union[int, float]:\n    size = 0.0\n    for root, _dirs, files in os.walk(path):\n        for filename in files:\n            file_path = os.path.join(root, filename)\n            size += file_size(file_path)\n    return size\n\n\ndef format_directory_size(path: str) -> str:\n    return format_size(directory_size(path))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/filetypes.py",
    "content": "\"\"\"Filetype information.\n\"\"\"\n\nfrom typing import Tuple\n\nfrom pip._internal.utils.misc import splitext\n\nWHEEL_EXTENSION = \".whl\"\nBZ2_EXTENSIONS: Tuple[str, ...] = (\".tar.bz2\", \".tbz\")\nXZ_EXTENSIONS: Tuple[str, ...] = (\n    \".tar.xz\",\n    \".txz\",\n    \".tlz\",\n    \".tar.lz\",\n    \".tar.lzma\",\n)\nZIP_EXTENSIONS: Tuple[str, ...] = (\".zip\", WHEEL_EXTENSION)\nTAR_EXTENSIONS: Tuple[str, ...] = (\".tar.gz\", \".tgz\", \".tar\")\nARCHIVE_EXTENSIONS = ZIP_EXTENSIONS + BZ2_EXTENSIONS + TAR_EXTENSIONS + XZ_EXTENSIONS\n\n\ndef is_archive_file(name: str) -> bool:\n    \"\"\"Return True if `name` is a considered as an archive file.\"\"\"\n    ext = splitext(name)[1].lower()\n    if ext in ARCHIVE_EXTENSIONS:\n        return True\n    return False\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/glibc.py",
    "content": "# The following comment should be removed at some point in the future.\n# mypy: strict-optional=False\n\nimport os\nimport sys\nfrom typing import Optional, Tuple\n\n\ndef glibc_version_string() -> Optional[str]:\n    \"Returns glibc version string, or None if not using glibc.\"\n    return glibc_version_string_confstr() or glibc_version_string_ctypes()\n\n\ndef glibc_version_string_confstr() -> Optional[str]:\n    \"Primary implementation of glibc_version_string using os.confstr.\"\n    # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely\n    # to be broken or missing. This strategy is used in the standard library\n    # platform module:\n    # https://github.com/python/cpython/blob/fcf1d003bf4f0100c9d0921ff3d70e1127ca1b71/Lib/platform.py#L175-L183\n    if sys.platform == \"win32\":\n        return None\n    try:\n        # os.confstr(\"CS_GNU_LIBC_VERSION\") returns a string like \"glibc 2.17\":\n        _, version = os.confstr(\"CS_GNU_LIBC_VERSION\").split()\n    except (AttributeError, OSError, ValueError):\n        # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...\n        return None\n    return version\n\n\ndef glibc_version_string_ctypes() -> Optional[str]:\n    \"Fallback implementation of glibc_version_string using ctypes.\"\n\n    try:\n        import ctypes\n    except ImportError:\n        return None\n\n    # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen\n    # manpage says, \"If filename is NULL, then the returned handle is for the\n    # main program\". This way we can let the linker do the work to figure out\n    # which libc our process is actually using.\n    process_namespace = ctypes.CDLL(None)\n    try:\n        gnu_get_libc_version = process_namespace.gnu_get_libc_version\n    except AttributeError:\n        # Symbol doesn't exist -> therefore, we are not linked to\n        # glibc.\n        return None\n\n    # Call gnu_get_libc_version, which returns a string like \"2.5\"\n    gnu_get_libc_version.restype = ctypes.c_char_p\n    version_str = gnu_get_libc_version()\n    # py2 / py3 compatibility:\n    if not isinstance(version_str, str):\n        version_str = version_str.decode(\"ascii\")\n\n    return version_str\n\n\n# platform.libc_ver regularly returns completely nonsensical glibc\n# versions. E.g. on my computer, platform says:\n#\n#   ~$ python2.7 -c 'import platform; print(platform.libc_ver())'\n#   ('glibc', '2.7')\n#   ~$ python3.5 -c 'import platform; print(platform.libc_ver())'\n#   ('glibc', '2.9')\n#\n# But the truth is:\n#\n#   ~$ ldd --version\n#   ldd (Debian GLIBC 2.22-11) 2.22\n#\n# This is unfortunate, because it means that the linehaul data on libc\n# versions that was generated by pip 8.1.2 and earlier is useless and\n# misleading. Solution: instead of using platform, use our code that actually\n# works.\ndef libc_ver() -> Tuple[str, str]:\n    \"\"\"Try to determine the glibc version\n\n    Returns a tuple of strings (lib, version) which default to empty strings\n    in case the lookup fails.\n    \"\"\"\n    glibc_version = glibc_version_string()\n    if glibc_version is None:\n        return (\"\", \"\")\n    else:\n        return (\"glibc\", glibc_version)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/hashes.py",
    "content": "import hashlib\nfrom typing import TYPE_CHECKING, BinaryIO, Dict, Iterable, List, Optional\n\nfrom pip._internal.exceptions import HashMismatch, HashMissing, InstallationError\nfrom pip._internal.utils.misc import read_chunks\n\nif TYPE_CHECKING:\n    from hashlib import _Hash\n\n    # NoReturn introduced in 3.6.2; imported only for type checking to maintain\n    # pip compatibility with older patch versions of Python 3.6\n    from typing import NoReturn\n\n\n# The recommended hash algo of the moment. Change this whenever the state of\n# the art changes; it won't hurt backward compatibility.\nFAVORITE_HASH = \"sha256\"\n\n\n# Names of hashlib algorithms allowed by the --hash option and ``pip hash``\n# Currently, those are the ones at least as collision-resistant as sha256.\nSTRONG_HASHES = [\"sha256\", \"sha384\", \"sha512\"]\n\n\nclass Hashes:\n    \"\"\"A wrapper that builds multiple hashes at once and checks them against\n    known-good values\n\n    \"\"\"\n\n    def __init__(self, hashes: Optional[Dict[str, List[str]]] = None) -> None:\n        \"\"\"\n        :param hashes: A dict of algorithm names pointing to lists of allowed\n            hex digests\n        \"\"\"\n        allowed = {}\n        if hashes is not None:\n            for alg, keys in hashes.items():\n                # Make sure values are always sorted (to ease equality checks)\n                allowed[alg] = sorted(keys)\n        self._allowed = allowed\n\n    def __and__(self, other: \"Hashes\") -> \"Hashes\":\n        if not isinstance(other, Hashes):\n            return NotImplemented\n\n        # If either of the Hashes object is entirely empty (i.e. no hash\n        # specified at all), all hashes from the other object are allowed.\n        if not other:\n            return self\n        if not self:\n            return other\n\n        # Otherwise only hashes that present in both objects are allowed.\n        new = {}\n        for alg, values in other._allowed.items():\n            if alg not in self._allowed:\n                continue\n            new[alg] = [v for v in values if v in self._allowed[alg]]\n        return Hashes(new)\n\n    @property\n    def digest_count(self) -> int:\n        return sum(len(digests) for digests in self._allowed.values())\n\n    def is_hash_allowed(self, hash_name: str, hex_digest: str) -> bool:\n        \"\"\"Return whether the given hex digest is allowed.\"\"\"\n        return hex_digest in self._allowed.get(hash_name, [])\n\n    def check_against_chunks(self, chunks: Iterable[bytes]) -> None:\n        \"\"\"Check good hashes against ones built from iterable of chunks of\n        data.\n\n        Raise HashMismatch if none match.\n\n        \"\"\"\n        gots = {}\n        for hash_name in self._allowed.keys():\n            try:\n                gots[hash_name] = hashlib.new(hash_name)\n            except (ValueError, TypeError):\n                raise InstallationError(f\"Unknown hash name: {hash_name}\")\n\n        for chunk in chunks:\n            for hash in gots.values():\n                hash.update(chunk)\n\n        for hash_name, got in gots.items():\n            if got.hexdigest() in self._allowed[hash_name]:\n                return\n        self._raise(gots)\n\n    def _raise(self, gots: Dict[str, \"_Hash\"]) -> \"NoReturn\":\n        raise HashMismatch(self._allowed, gots)\n\n    def check_against_file(self, file: BinaryIO) -> None:\n        \"\"\"Check good hashes against a file-like object\n\n        Raise HashMismatch if none match.\n\n        \"\"\"\n        return self.check_against_chunks(read_chunks(file))\n\n    def check_against_path(self, path: str) -> None:\n        with open(path, \"rb\") as file:\n            return self.check_against_file(file)\n\n    def __bool__(self) -> bool:\n        \"\"\"Return whether I know any known-good hashes.\"\"\"\n        return bool(self._allowed)\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Hashes):\n            return NotImplemented\n        return self._allowed == other._allowed\n\n    def __hash__(self) -> int:\n        return hash(\n            \",\".join(\n                sorted(\n                    \":\".join((alg, digest))\n                    for alg, digest_list in self._allowed.items()\n                    for digest in digest_list\n                )\n            )\n        )\n\n\nclass MissingHashes(Hashes):\n    \"\"\"A workalike for Hashes used when we're missing a hash for a requirement\n\n    It computes the actual hash of the requirement and raises a HashMissing\n    exception showing it to the user.\n\n    \"\"\"\n\n    def __init__(self) -> None:\n        \"\"\"Don't offer the ``hashes`` kwarg.\"\"\"\n        # Pass our favorite hash in to generate a \"gotten hash\". With the\n        # empty list, it will never match, so an error will always raise.\n        super().__init__(hashes={FAVORITE_HASH: []})\n\n    def _raise(self, gots: Dict[str, \"_Hash\"]) -> \"NoReturn\":\n        raise HashMissing(gots[FAVORITE_HASH].hexdigest())\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/inject_securetransport.py",
    "content": "\"\"\"A helper module that injects SecureTransport, on import.\n\nThe import should be done as early as possible, to ensure all requests and\nsessions (or whatever) are created after injecting SecureTransport.\n\nNote that we only do the injection on macOS, when the linked OpenSSL is too\nold to handle TLSv1.2.\n\"\"\"\n\nimport sys\n\n\ndef inject_securetransport() -> None:\n    # Only relevant on macOS\n    if sys.platform != \"darwin\":\n        return\n\n    try:\n        import ssl\n    except ImportError:\n        return\n\n    # Checks for OpenSSL 1.0.1\n    if ssl.OPENSSL_VERSION_NUMBER >= 0x1000100F:\n        return\n\n    try:\n        from pip._vendor.urllib3.contrib import securetransport\n    except (ImportError, OSError):\n        return\n\n    securetransport.inject_into_urllib3()\n\n\ninject_securetransport()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/logging.py",
    "content": "import contextlib\nimport errno\nimport logging\nimport logging.handlers\nimport os\nimport sys\nimport threading\nfrom dataclasses import dataclass\nfrom io import TextIOWrapper\nfrom logging import Filter\nfrom typing import Any, ClassVar, Generator, List, Optional, TextIO, Type\n\nfrom pip._vendor.rich.console import (\n    Console,\n    ConsoleOptions,\n    ConsoleRenderable,\n    RenderableType,\n    RenderResult,\n    RichCast,\n)\nfrom pip._vendor.rich.highlighter import NullHighlighter\nfrom pip._vendor.rich.logging import RichHandler\nfrom pip._vendor.rich.segment import Segment\nfrom pip._vendor.rich.style import Style\n\nfrom pip._internal.utils._log import VERBOSE, getLogger\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.deprecation import DEPRECATION_MSG_PREFIX\nfrom pip._internal.utils.misc import ensure_dir\n\n_log_state = threading.local()\nsubprocess_logger = getLogger(\"pip.subprocessor\")\n\n\nclass BrokenStdoutLoggingError(Exception):\n    \"\"\"\n    Raised if BrokenPipeError occurs for the stdout stream while logging.\n    \"\"\"\n\n\ndef _is_broken_pipe_error(exc_class: Type[BaseException], exc: BaseException) -> bool:\n    if exc_class is BrokenPipeError:\n        return True\n\n    # On Windows, a broken pipe can show up as EINVAL rather than EPIPE:\n    # https://bugs.python.org/issue19612\n    # https://bugs.python.org/issue30418\n    if not WINDOWS:\n        return False\n\n    return isinstance(exc, OSError) and exc.errno in (errno.EINVAL, errno.EPIPE)\n\n\n@contextlib.contextmanager\ndef indent_log(num: int = 2) -> Generator[None, None, None]:\n    \"\"\"\n    A context manager which will cause the log output to be indented for any\n    log messages emitted inside it.\n    \"\"\"\n    # For thread-safety\n    _log_state.indentation = get_indentation()\n    _log_state.indentation += num\n    try:\n        yield\n    finally:\n        _log_state.indentation -= num\n\n\ndef get_indentation() -> int:\n    return getattr(_log_state, \"indentation\", 0)\n\n\nclass IndentingFormatter(logging.Formatter):\n    default_time_format = \"%Y-%m-%dT%H:%M:%S\"\n\n    def __init__(\n        self,\n        *args: Any,\n        add_timestamp: bool = False,\n        **kwargs: Any,\n    ) -> None:\n        \"\"\"\n        A logging.Formatter that obeys the indent_log() context manager.\n\n        :param add_timestamp: A bool indicating output lines should be prefixed\n            with their record's timestamp.\n        \"\"\"\n        self.add_timestamp = add_timestamp\n        super().__init__(*args, **kwargs)\n\n    def get_message_start(self, formatted: str, levelno: int) -> str:\n        \"\"\"\n        Return the start of the formatted log message (not counting the\n        prefix to add to each line).\n        \"\"\"\n        if levelno < logging.WARNING:\n            return \"\"\n        if formatted.startswith(DEPRECATION_MSG_PREFIX):\n            # Then the message already has a prefix.  We don't want it to\n            # look like \"WARNING: DEPRECATION: ....\"\n            return \"\"\n        if levelno < logging.ERROR:\n            return \"WARNING: \"\n\n        return \"ERROR: \"\n\n    def format(self, record: logging.LogRecord) -> str:\n        \"\"\"\n        Calls the standard formatter, but will indent all of the log message\n        lines by our current indentation level.\n        \"\"\"\n        formatted = super().format(record)\n        message_start = self.get_message_start(formatted, record.levelno)\n        formatted = message_start + formatted\n\n        prefix = \"\"\n        if self.add_timestamp:\n            prefix = f\"{self.formatTime(record)} \"\n        prefix += \" \" * get_indentation()\n        formatted = \"\".join([prefix + line for line in formatted.splitlines(True)])\n        return formatted\n\n\n@dataclass\nclass IndentedRenderable:\n    renderable: RenderableType\n    indent: int\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        segments = console.render(self.renderable, options)\n        lines = Segment.split_lines(segments)\n        for line in lines:\n            yield Segment(\" \" * self.indent)\n            yield from line\n            yield Segment(\"\\n\")\n\n\nclass RichPipStreamHandler(RichHandler):\n    KEYWORDS: ClassVar[Optional[List[str]]] = []\n\n    def __init__(self, stream: Optional[TextIO], no_color: bool) -> None:\n        super().__init__(\n            console=Console(file=stream, no_color=no_color, soft_wrap=True),\n            show_time=False,\n            show_level=False,\n            show_path=False,\n            highlighter=NullHighlighter(),\n        )\n\n    # Our custom override on Rich's logger, to make things work as we need them to.\n    def emit(self, record: logging.LogRecord) -> None:\n        style: Optional[Style] = None\n\n        # If we are given a diagnostic error to present, present it with indentation.\n        assert isinstance(record.args, tuple)\n        if record.msg == \"[present-rich] %s\" and len(record.args) == 1:\n            rich_renderable = record.args[0]\n            assert isinstance(\n                rich_renderable, (ConsoleRenderable, RichCast, str)\n            ), f\"{rich_renderable} is not rich-console-renderable\"\n\n            renderable: RenderableType = IndentedRenderable(\n                rich_renderable, indent=get_indentation()\n            )\n        else:\n            message = self.format(record)\n            renderable = self.render_message(record, message)\n            if record.levelno is not None:\n                if record.levelno >= logging.ERROR:\n                    style = Style(color=\"red\")\n                elif record.levelno >= logging.WARNING:\n                    style = Style(color=\"yellow\")\n\n        try:\n            self.console.print(renderable, overflow=\"ignore\", crop=False, style=style)\n        except Exception:\n            self.handleError(record)\n\n    def handleError(self, record: logging.LogRecord) -> None:\n        \"\"\"Called when logging is unable to log some output.\"\"\"\n\n        exc_class, exc = sys.exc_info()[:2]\n        # If a broken pipe occurred while calling write() or flush() on the\n        # stdout stream in logging's Handler.emit(), then raise our special\n        # exception so we can handle it in main() instead of logging the\n        # broken pipe error and continuing.\n        if (\n            exc_class\n            and exc\n            and self.console.file is sys.stdout\n            and _is_broken_pipe_error(exc_class, exc)\n        ):\n            raise BrokenStdoutLoggingError()\n\n        return super().handleError(record)\n\n\nclass BetterRotatingFileHandler(logging.handlers.RotatingFileHandler):\n    def _open(self) -> TextIOWrapper:\n        ensure_dir(os.path.dirname(self.baseFilename))\n        return super()._open()\n\n\nclass MaxLevelFilter(Filter):\n    def __init__(self, level: int) -> None:\n        self.level = level\n\n    def filter(self, record: logging.LogRecord) -> bool:\n        return record.levelno < self.level\n\n\nclass ExcludeLoggerFilter(Filter):\n\n    \"\"\"\n    A logging Filter that excludes records from a logger (or its children).\n    \"\"\"\n\n    def filter(self, record: logging.LogRecord) -> bool:\n        # The base Filter class allows only records from a logger (or its\n        # children).\n        return not super().filter(record)\n\n\ndef setup_logging(verbosity: int, no_color: bool, user_log_file: Optional[str]) -> int:\n    \"\"\"Configures and sets up all of the logging\n\n    Returns the requested logging level, as its integer value.\n    \"\"\"\n\n    # Determine the level to be logging at.\n    if verbosity >= 2:\n        level_number = logging.DEBUG\n    elif verbosity == 1:\n        level_number = VERBOSE\n    elif verbosity == -1:\n        level_number = logging.WARNING\n    elif verbosity == -2:\n        level_number = logging.ERROR\n    elif verbosity <= -3:\n        level_number = logging.CRITICAL\n    else:\n        level_number = logging.INFO\n\n    level = logging.getLevelName(level_number)\n\n    # The \"root\" logger should match the \"console\" level *unless* we also need\n    # to log to a user log file.\n    include_user_log = user_log_file is not None\n    if include_user_log:\n        additional_log_file = user_log_file\n        root_level = \"DEBUG\"\n    else:\n        additional_log_file = \"/dev/null\"\n        root_level = level\n\n    # Disable any logging besides WARNING unless we have DEBUG level logging\n    # enabled for vendored libraries.\n    vendored_log_level = \"WARNING\" if level in [\"INFO\", \"ERROR\"] else \"DEBUG\"\n\n    # Shorthands for clarity\n    log_streams = {\n        \"stdout\": \"ext://sys.stdout\",\n        \"stderr\": \"ext://sys.stderr\",\n    }\n    handler_classes = {\n        \"stream\": \"pip._internal.utils.logging.RichPipStreamHandler\",\n        \"file\": \"pip._internal.utils.logging.BetterRotatingFileHandler\",\n    }\n    handlers = [\"console\", \"console_errors\", \"console_subprocess\"] + (\n        [\"user_log\"] if include_user_log else []\n    )\n\n    logging.config.dictConfig(\n        {\n            \"version\": 1,\n            \"disable_existing_loggers\": False,\n            \"filters\": {\n                \"exclude_warnings\": {\n                    \"()\": \"pip._internal.utils.logging.MaxLevelFilter\",\n                    \"level\": logging.WARNING,\n                },\n                \"restrict_to_subprocess\": {\n                    \"()\": \"logging.Filter\",\n                    \"name\": subprocess_logger.name,\n                },\n                \"exclude_subprocess\": {\n                    \"()\": \"pip._internal.utils.logging.ExcludeLoggerFilter\",\n                    \"name\": subprocess_logger.name,\n                },\n            },\n            \"formatters\": {\n                \"indent\": {\n                    \"()\": IndentingFormatter,\n                    \"format\": \"%(message)s\",\n                },\n                \"indent_with_timestamp\": {\n                    \"()\": IndentingFormatter,\n                    \"format\": \"%(message)s\",\n                    \"add_timestamp\": True,\n                },\n            },\n            \"handlers\": {\n                \"console\": {\n                    \"level\": level,\n                    \"class\": handler_classes[\"stream\"],\n                    \"no_color\": no_color,\n                    \"stream\": log_streams[\"stdout\"],\n                    \"filters\": [\"exclude_subprocess\", \"exclude_warnings\"],\n                    \"formatter\": \"indent\",\n                },\n                \"console_errors\": {\n                    \"level\": \"WARNING\",\n                    \"class\": handler_classes[\"stream\"],\n                    \"no_color\": no_color,\n                    \"stream\": log_streams[\"stderr\"],\n                    \"filters\": [\"exclude_subprocess\"],\n                    \"formatter\": \"indent\",\n                },\n                # A handler responsible for logging to the console messages\n                # from the \"subprocessor\" logger.\n                \"console_subprocess\": {\n                    \"level\": level,\n                    \"class\": handler_classes[\"stream\"],\n                    \"stream\": log_streams[\"stderr\"],\n                    \"no_color\": no_color,\n                    \"filters\": [\"restrict_to_subprocess\"],\n                    \"formatter\": \"indent\",\n                },\n                \"user_log\": {\n                    \"level\": \"DEBUG\",\n                    \"class\": handler_classes[\"file\"],\n                    \"filename\": additional_log_file,\n                    \"encoding\": \"utf-8\",\n                    \"delay\": True,\n                    \"formatter\": \"indent_with_timestamp\",\n                },\n            },\n            \"root\": {\n                \"level\": root_level,\n                \"handlers\": handlers,\n            },\n            \"loggers\": {\"pip._vendor\": {\"level\": vendored_log_level}},\n        }\n    )\n\n    return level_number\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/misc.py",
    "content": "# The following comment should be removed at some point in the future.\n# mypy: strict-optional=False\n\nimport contextlib\nimport errno\nimport getpass\nimport hashlib\nimport io\nimport logging\nimport os\nimport posixpath\nimport shutil\nimport stat\nimport sys\nimport urllib.parse\nfrom io import StringIO\nfrom itertools import filterfalse, tee, zip_longest\nfrom types import TracebackType\nfrom typing import (\n    Any,\n    BinaryIO,\n    Callable,\n    ContextManager,\n    Dict,\n    Generator,\n    Iterable,\n    Iterator,\n    List,\n    Optional,\n    TextIO,\n    Tuple,\n    Type,\n    TypeVar,\n    cast,\n)\n\nfrom pip._vendor.pep517 import Pep517HookCaller\nfrom pip._vendor.tenacity import retry, stop_after_delay, wait_fixed\n\nfrom pip import __version__\nfrom pip._internal.exceptions import CommandError\nfrom pip._internal.locations import get_major_minor_version\nfrom pip._internal.utils.compat import WINDOWS\nfrom pip._internal.utils.virtualenv import running_under_virtualenv\n\n__all__ = [\n    \"rmtree\",\n    \"display_path\",\n    \"backup_dir\",\n    \"ask\",\n    \"splitext\",\n    \"format_size\",\n    \"is_installable_dir\",\n    \"normalize_path\",\n    \"renames\",\n    \"get_prog\",\n    \"captured_stdout\",\n    \"ensure_dir\",\n    \"remove_auth_from_url\",\n    \"ConfiguredPep517HookCaller\",\n]\n\n\nlogger = logging.getLogger(__name__)\n\nT = TypeVar(\"T\")\nExcInfo = Tuple[Type[BaseException], BaseException, TracebackType]\nVersionInfo = Tuple[int, int, int]\nNetlocTuple = Tuple[str, Tuple[Optional[str], Optional[str]]]\n\n\ndef get_pip_version() -> str:\n    pip_pkg_dir = os.path.join(os.path.dirname(__file__), \"..\", \"..\")\n    pip_pkg_dir = os.path.abspath(pip_pkg_dir)\n\n    return \"pip {} from {} (python {})\".format(\n        __version__,\n        pip_pkg_dir,\n        get_major_minor_version(),\n    )\n\n\ndef normalize_version_info(py_version_info: Tuple[int, ...]) -> Tuple[int, int, int]:\n    \"\"\"\n    Convert a tuple of ints representing a Python version to one of length\n    three.\n\n    :param py_version_info: a tuple of ints representing a Python version,\n        or None to specify no version. The tuple can have any length.\n\n    :return: a tuple of length three if `py_version_info` is non-None.\n        Otherwise, return `py_version_info` unchanged (i.e. None).\n    \"\"\"\n    if len(py_version_info) < 3:\n        py_version_info += (3 - len(py_version_info)) * (0,)\n    elif len(py_version_info) > 3:\n        py_version_info = py_version_info[:3]\n\n    return cast(\"VersionInfo\", py_version_info)\n\n\ndef ensure_dir(path: str) -> None:\n    \"\"\"os.path.makedirs without EEXIST.\"\"\"\n    try:\n        os.makedirs(path)\n    except OSError as e:\n        # Windows can raise spurious ENOTEMPTY errors. See #6426.\n        if e.errno != errno.EEXIST and e.errno != errno.ENOTEMPTY:\n            raise\n\n\ndef get_prog() -> str:\n    try:\n        prog = os.path.basename(sys.argv[0])\n        if prog in (\"__main__.py\", \"-c\"):\n            return f\"{sys.executable} -m pip\"\n        else:\n            return prog\n    except (AttributeError, TypeError, IndexError):\n        pass\n    return \"pip\"\n\n\n# Retry every half second for up to 3 seconds\n# Tenacity raises RetryError by default, explicitly raise the original exception\n@retry(reraise=True, stop=stop_after_delay(3), wait=wait_fixed(0.5))\ndef rmtree(dir: str, ignore_errors: bool = False) -> None:\n    shutil.rmtree(dir, ignore_errors=ignore_errors, onerror=rmtree_errorhandler)\n\n\ndef rmtree_errorhandler(func: Callable[..., Any], path: str, exc_info: ExcInfo) -> None:\n    \"\"\"On Windows, the files in .svn are read-only, so when rmtree() tries to\n    remove them, an exception is thrown.  We catch that here, remove the\n    read-only attribute, and hopefully continue without problems.\"\"\"\n    try:\n        has_attr_readonly = not (os.stat(path).st_mode & stat.S_IWRITE)\n    except OSError:\n        # it's equivalent to os.path.exists\n        return\n\n    if has_attr_readonly:\n        # convert to read/write\n        os.chmod(path, stat.S_IWRITE)\n        # use the original function to repeat the operation\n        func(path)\n        return\n    else:\n        raise\n\n\ndef display_path(path: str) -> str:\n    \"\"\"Gives the display value for a given path, making it relative to cwd\n    if possible.\"\"\"\n    path = os.path.normcase(os.path.abspath(path))\n    if path.startswith(os.getcwd() + os.path.sep):\n        path = \".\" + path[len(os.getcwd()) :]\n    return path\n\n\ndef backup_dir(dir: str, ext: str = \".bak\") -> str:\n    \"\"\"Figure out the name of a directory to back up the given dir to\n    (adding .bak, .bak2, etc)\"\"\"\n    n = 1\n    extension = ext\n    while os.path.exists(dir + extension):\n        n += 1\n        extension = ext + str(n)\n    return dir + extension\n\n\ndef ask_path_exists(message: str, options: Iterable[str]) -> str:\n    for action in os.environ.get(\"PIP_EXISTS_ACTION\", \"\").split():\n        if action in options:\n            return action\n    return ask(message, options)\n\n\ndef _check_no_input(message: str) -> None:\n    \"\"\"Raise an error if no input is allowed.\"\"\"\n    if os.environ.get(\"PIP_NO_INPUT\"):\n        raise Exception(\n            f\"No input was expected ($PIP_NO_INPUT set); question: {message}\"\n        )\n\n\ndef ask(message: str, options: Iterable[str]) -> str:\n    \"\"\"Ask the message interactively, with the given possible responses\"\"\"\n    while 1:\n        _check_no_input(message)\n        response = input(message)\n        response = response.strip().lower()\n        if response not in options:\n            print(\n                \"Your response ({!r}) was not one of the expected responses: \"\n                \"{}\".format(response, \", \".join(options))\n            )\n        else:\n            return response\n\n\ndef ask_input(message: str) -> str:\n    \"\"\"Ask for input interactively.\"\"\"\n    _check_no_input(message)\n    return input(message)\n\n\ndef ask_password(message: str) -> str:\n    \"\"\"Ask for a password interactively.\"\"\"\n    _check_no_input(message)\n    return getpass.getpass(message)\n\n\ndef strtobool(val: str) -> int:\n    \"\"\"Convert a string representation of truth to true (1) or false (0).\n\n    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values\n    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if\n    'val' is anything else.\n    \"\"\"\n    val = val.lower()\n    if val in (\"y\", \"yes\", \"t\", \"true\", \"on\", \"1\"):\n        return 1\n    elif val in (\"n\", \"no\", \"f\", \"false\", \"off\", \"0\"):\n        return 0\n    else:\n        raise ValueError(f\"invalid truth value {val!r}\")\n\n\ndef format_size(bytes: float) -> str:\n    if bytes > 1000 * 1000:\n        return \"{:.1f} MB\".format(bytes / 1000.0 / 1000)\n    elif bytes > 10 * 1000:\n        return \"{} kB\".format(int(bytes / 1000))\n    elif bytes > 1000:\n        return \"{:.1f} kB\".format(bytes / 1000.0)\n    else:\n        return \"{} bytes\".format(int(bytes))\n\n\ndef tabulate(rows: Iterable[Iterable[Any]]) -> Tuple[List[str], List[int]]:\n    \"\"\"Return a list of formatted rows and a list of column sizes.\n\n    For example::\n\n    >>> tabulate([['foobar', 2000], [0xdeadbeef]])\n    (['foobar     2000', '3735928559'], [10, 4])\n    \"\"\"\n    rows = [tuple(map(str, row)) for row in rows]\n    sizes = [max(map(len, col)) for col in zip_longest(*rows, fillvalue=\"\")]\n    table = [\" \".join(map(str.ljust, row, sizes)).rstrip() for row in rows]\n    return table, sizes\n\n\ndef is_installable_dir(path: str) -> bool:\n    \"\"\"Is path is a directory containing pyproject.toml or setup.py?\n\n    If pyproject.toml exists, this is a PEP 517 project. Otherwise we look for\n    a legacy setuptools layout by identifying setup.py. We don't check for the\n    setup.cfg because using it without setup.py is only available for PEP 517\n    projects, which are already covered by the pyproject.toml check.\n    \"\"\"\n    if not os.path.isdir(path):\n        return False\n    if os.path.isfile(os.path.join(path, \"pyproject.toml\")):\n        return True\n    if os.path.isfile(os.path.join(path, \"setup.py\")):\n        return True\n    return False\n\n\ndef read_chunks(\n    file: BinaryIO, size: int = io.DEFAULT_BUFFER_SIZE\n) -> Generator[bytes, None, None]:\n    \"\"\"Yield pieces of data from a file-like object until EOF.\"\"\"\n    while True:\n        chunk = file.read(size)\n        if not chunk:\n            break\n        yield chunk\n\n\ndef normalize_path(path: str, resolve_symlinks: bool = True) -> str:\n    \"\"\"\n    Convert a path to its canonical, case-normalized, absolute version.\n\n    \"\"\"\n    path = os.path.expanduser(path)\n    if resolve_symlinks:\n        path = os.path.realpath(path)\n    else:\n        path = os.path.abspath(path)\n    return os.path.normcase(path)\n\n\ndef splitext(path: str) -> Tuple[str, str]:\n    \"\"\"Like os.path.splitext, but take off .tar too\"\"\"\n    base, ext = posixpath.splitext(path)\n    if base.lower().endswith(\".tar\"):\n        ext = base[-4:] + ext\n        base = base[:-4]\n    return base, ext\n\n\ndef renames(old: str, new: str) -> None:\n    \"\"\"Like os.renames(), but handles renaming across devices.\"\"\"\n    # Implementation borrowed from os.renames().\n    head, tail = os.path.split(new)\n    if head and tail and not os.path.exists(head):\n        os.makedirs(head)\n\n    shutil.move(old, new)\n\n    head, tail = os.path.split(old)\n    if head and tail:\n        try:\n            os.removedirs(head)\n        except OSError:\n            pass\n\n\ndef is_local(path: str) -> bool:\n    \"\"\"\n    Return True if path is within sys.prefix, if we're running in a virtualenv.\n\n    If we're not in a virtualenv, all paths are considered \"local.\"\n\n    Caution: this function assumes the head of path has been normalized\n    with normalize_path.\n    \"\"\"\n    if not running_under_virtualenv():\n        return True\n    return path.startswith(normalize_path(sys.prefix))\n\n\ndef write_output(msg: Any, *args: Any) -> None:\n    logger.info(msg, *args)\n\n\nclass StreamWrapper(StringIO):\n    orig_stream: TextIO = None\n\n    @classmethod\n    def from_stream(cls, orig_stream: TextIO) -> \"StreamWrapper\":\n        cls.orig_stream = orig_stream\n        return cls()\n\n    # compileall.compile_dir() needs stdout.encoding to print to stdout\n    # https://github.com/python/mypy/issues/4125\n    @property\n    def encoding(self):  # type: ignore\n        return self.orig_stream.encoding\n\n\n@contextlib.contextmanager\ndef captured_output(stream_name: str) -> Generator[StreamWrapper, None, None]:\n    \"\"\"Return a context manager used by captured_stdout/stdin/stderr\n    that temporarily replaces the sys stream *stream_name* with a StringIO.\n\n    Taken from Lib/support/__init__.py in the CPython repo.\n    \"\"\"\n    orig_stdout = getattr(sys, stream_name)\n    setattr(sys, stream_name, StreamWrapper.from_stream(orig_stdout))\n    try:\n        yield getattr(sys, stream_name)\n    finally:\n        setattr(sys, stream_name, orig_stdout)\n\n\ndef captured_stdout() -> ContextManager[StreamWrapper]:\n    \"\"\"Capture the output of sys.stdout:\n\n       with captured_stdout() as stdout:\n           print('hello')\n       self.assertEqual(stdout.getvalue(), 'hello\\n')\n\n    Taken from Lib/support/__init__.py in the CPython repo.\n    \"\"\"\n    return captured_output(\"stdout\")\n\n\ndef captured_stderr() -> ContextManager[StreamWrapper]:\n    \"\"\"\n    See captured_stdout().\n    \"\"\"\n    return captured_output(\"stderr\")\n\n\n# Simulates an enum\ndef enum(*sequential: Any, **named: Any) -> Type[Any]:\n    enums = dict(zip(sequential, range(len(sequential))), **named)\n    reverse = {value: key for key, value in enums.items()}\n    enums[\"reverse_mapping\"] = reverse\n    return type(\"Enum\", (), enums)\n\n\ndef build_netloc(host: str, port: Optional[int]) -> str:\n    \"\"\"\n    Build a netloc from a host-port pair\n    \"\"\"\n    if port is None:\n        return host\n    if \":\" in host:\n        # Only wrap host with square brackets when it is IPv6\n        host = f\"[{host}]\"\n    return f\"{host}:{port}\"\n\n\ndef build_url_from_netloc(netloc: str, scheme: str = \"https\") -> str:\n    \"\"\"\n    Build a full URL from a netloc.\n    \"\"\"\n    if netloc.count(\":\") >= 2 and \"@\" not in netloc and \"[\" not in netloc:\n        # It must be a bare IPv6 address, so wrap it with brackets.\n        netloc = f\"[{netloc}]\"\n    return f\"{scheme}://{netloc}\"\n\n\ndef parse_netloc(netloc: str) -> Tuple[str, Optional[int]]:\n    \"\"\"\n    Return the host-port pair from a netloc.\n    \"\"\"\n    url = build_url_from_netloc(netloc)\n    parsed = urllib.parse.urlparse(url)\n    return parsed.hostname, parsed.port\n\n\ndef split_auth_from_netloc(netloc: str) -> NetlocTuple:\n    \"\"\"\n    Parse out and remove the auth information from a netloc.\n\n    Returns: (netloc, (username, password)).\n    \"\"\"\n    if \"@\" not in netloc:\n        return netloc, (None, None)\n\n    # Split from the right because that's how urllib.parse.urlsplit()\n    # behaves if more than one @ is present (which can be checked using\n    # the password attribute of urlsplit()'s return value).\n    auth, netloc = netloc.rsplit(\"@\", 1)\n    pw: Optional[str] = None\n    if \":\" in auth:\n        # Split from the left because that's how urllib.parse.urlsplit()\n        # behaves if more than one : is present (which again can be checked\n        # using the password attribute of the return value)\n        user, pw = auth.split(\":\", 1)\n    else:\n        user, pw = auth, None\n\n    user = urllib.parse.unquote(user)\n    if pw is not None:\n        pw = urllib.parse.unquote(pw)\n\n    return netloc, (user, pw)\n\n\ndef redact_netloc(netloc: str) -> str:\n    \"\"\"\n    Replace the sensitive data in a netloc with \"****\", if it exists.\n\n    For example:\n        - \"user:pass@example.com\" returns \"user:****@example.com\"\n        - \"accesstoken@example.com\" returns \"****@example.com\"\n    \"\"\"\n    netloc, (user, password) = split_auth_from_netloc(netloc)\n    if user is None:\n        return netloc\n    if password is None:\n        user = \"****\"\n        password = \"\"\n    else:\n        user = urllib.parse.quote(user)\n        password = \":****\"\n    return \"{user}{password}@{netloc}\".format(\n        user=user, password=password, netloc=netloc\n    )\n\n\ndef _transform_url(\n    url: str, transform_netloc: Callable[[str], Tuple[Any, ...]]\n) -> Tuple[str, NetlocTuple]:\n    \"\"\"Transform and replace netloc in a url.\n\n    transform_netloc is a function taking the netloc and returning a\n    tuple. The first element of this tuple is the new netloc. The\n    entire tuple is returned.\n\n    Returns a tuple containing the transformed url as item 0 and the\n    original tuple returned by transform_netloc as item 1.\n    \"\"\"\n    purl = urllib.parse.urlsplit(url)\n    netloc_tuple = transform_netloc(purl.netloc)\n    # stripped url\n    url_pieces = (purl.scheme, netloc_tuple[0], purl.path, purl.query, purl.fragment)\n    surl = urllib.parse.urlunsplit(url_pieces)\n    return surl, cast(\"NetlocTuple\", netloc_tuple)\n\n\ndef _get_netloc(netloc: str) -> NetlocTuple:\n    return split_auth_from_netloc(netloc)\n\n\ndef _redact_netloc(netloc: str) -> Tuple[str]:\n    return (redact_netloc(netloc),)\n\n\ndef split_auth_netloc_from_url(url: str) -> Tuple[str, str, Tuple[str, str]]:\n    \"\"\"\n    Parse a url into separate netloc, auth, and url with no auth.\n\n    Returns: (url_without_auth, netloc, (username, password))\n    \"\"\"\n    url_without_auth, (netloc, auth) = _transform_url(url, _get_netloc)\n    return url_without_auth, netloc, auth\n\n\ndef remove_auth_from_url(url: str) -> str:\n    \"\"\"Return a copy of url with 'username:password@' removed.\"\"\"\n    # username/pass params are passed to subversion through flags\n    # and are not recognized in the url.\n    return _transform_url(url, _get_netloc)[0]\n\n\ndef redact_auth_from_url(url: str) -> str:\n    \"\"\"Replace the password in a given url with ****.\"\"\"\n    return _transform_url(url, _redact_netloc)[0]\n\n\nclass HiddenText:\n    def __init__(self, secret: str, redacted: str) -> None:\n        self.secret = secret\n        self.redacted = redacted\n\n    def __repr__(self) -> str:\n        return \"<HiddenText {!r}>\".format(str(self))\n\n    def __str__(self) -> str:\n        return self.redacted\n\n    # This is useful for testing.\n    def __eq__(self, other: Any) -> bool:\n        if type(self) != type(other):\n            return False\n\n        # The string being used for redaction doesn't also have to match,\n        # just the raw, original string.\n        return self.secret == other.secret\n\n\ndef hide_value(value: str) -> HiddenText:\n    return HiddenText(value, redacted=\"****\")\n\n\ndef hide_url(url: str) -> HiddenText:\n    redacted = redact_auth_from_url(url)\n    return HiddenText(url, redacted=redacted)\n\n\ndef protect_pip_from_modification_on_windows(modifying_pip: bool) -> None:\n    \"\"\"Protection of pip.exe from modification on Windows\n\n    On Windows, any operation modifying pip should be run as:\n        python -m pip ...\n    \"\"\"\n    pip_names = [\n        \"pip\",\n        f\"pip{sys.version_info.major}\",\n        f\"pip{sys.version_info.major}.{sys.version_info.minor}\",\n    ]\n\n    # See https://github.com/pypa/pip/issues/1299 for more discussion\n    should_show_use_python_msg = (\n        modifying_pip and WINDOWS and os.path.basename(sys.argv[0]) in pip_names\n    )\n\n    if should_show_use_python_msg:\n        new_command = [sys.executable, \"-m\", \"pip\"] + sys.argv[1:]\n        raise CommandError(\n            \"To modify pip, please run the following command:\\n{}\".format(\n                \" \".join(new_command)\n            )\n        )\n\n\ndef is_console_interactive() -> bool:\n    \"\"\"Is this console interactive?\"\"\"\n    return sys.stdin is not None and sys.stdin.isatty()\n\n\ndef hash_file(path: str, blocksize: int = 1 << 20) -> Tuple[Any, int]:\n    \"\"\"Return (hash, length) for path using hashlib.sha256()\"\"\"\n\n    h = hashlib.sha256()\n    length = 0\n    with open(path, \"rb\") as f:\n        for block in read_chunks(f, size=blocksize):\n            length += len(block)\n            h.update(block)\n    return h, length\n\n\ndef is_wheel_installed() -> bool:\n    \"\"\"\n    Return whether the wheel package is installed.\n    \"\"\"\n    try:\n        import wheel  # noqa: F401\n    except ImportError:\n        return False\n\n    return True\n\n\ndef pairwise(iterable: Iterable[Any]) -> Iterator[Tuple[Any, Any]]:\n    \"\"\"\n    Return paired elements.\n\n    For example:\n        s -> (s0, s1), (s2, s3), (s4, s5), ...\n    \"\"\"\n    iterable = iter(iterable)\n    return zip_longest(iterable, iterable)\n\n\ndef partition(\n    pred: Callable[[T], bool],\n    iterable: Iterable[T],\n) -> Tuple[Iterable[T], Iterable[T]]:\n    \"\"\"\n    Use a predicate to partition entries into false entries and true entries,\n    like\n\n        partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9\n    \"\"\"\n    t1, t2 = tee(iterable)\n    return filterfalse(pred, t1), filter(pred, t2)\n\n\nclass ConfiguredPep517HookCaller(Pep517HookCaller):\n    def __init__(\n        self,\n        config_holder: Any,\n        source_dir: str,\n        build_backend: str,\n        backend_path: Optional[str] = None,\n        runner: Optional[Callable[..., None]] = None,\n        python_executable: Optional[str] = None,\n    ):\n        super().__init__(\n            source_dir, build_backend, backend_path, runner, python_executable\n        )\n        self.config_holder = config_holder\n\n    def build_wheel(\n        self,\n        wheel_directory: str,\n        config_settings: Optional[Dict[str, str]] = None,\n        metadata_directory: Optional[str] = None,\n    ) -> str:\n        cs = self.config_holder.config_settings\n        return super().build_wheel(\n            wheel_directory, config_settings=cs, metadata_directory=metadata_directory\n        )\n\n    def build_sdist(\n        self, sdist_directory: str, config_settings: Optional[Dict[str, str]] = None\n    ) -> str:\n        cs = self.config_holder.config_settings\n        return super().build_sdist(sdist_directory, config_settings=cs)\n\n    def build_editable(\n        self,\n        wheel_directory: str,\n        config_settings: Optional[Dict[str, str]] = None,\n        metadata_directory: Optional[str] = None,\n    ) -> str:\n        cs = self.config_holder.config_settings\n        return super().build_editable(\n            wheel_directory, config_settings=cs, metadata_directory=metadata_directory\n        )\n\n    def get_requires_for_build_wheel(\n        self, config_settings: Optional[Dict[str, str]] = None\n    ) -> List[str]:\n        cs = self.config_holder.config_settings\n        return super().get_requires_for_build_wheel(config_settings=cs)\n\n    def get_requires_for_build_sdist(\n        self, config_settings: Optional[Dict[str, str]] = None\n    ) -> List[str]:\n        cs = self.config_holder.config_settings\n        return super().get_requires_for_build_sdist(config_settings=cs)\n\n    def get_requires_for_build_editable(\n        self, config_settings: Optional[Dict[str, str]] = None\n    ) -> List[str]:\n        cs = self.config_holder.config_settings\n        return super().get_requires_for_build_editable(config_settings=cs)\n\n    def prepare_metadata_for_build_wheel(\n        self,\n        metadata_directory: str,\n        config_settings: Optional[Dict[str, str]] = None,\n        _allow_fallback: bool = True,\n    ) -> str:\n        cs = self.config_holder.config_settings\n        return super().prepare_metadata_for_build_wheel(\n            metadata_directory=metadata_directory,\n            config_settings=cs,\n            _allow_fallback=_allow_fallback,\n        )\n\n    def prepare_metadata_for_build_editable(\n        self,\n        metadata_directory: str,\n        config_settings: Optional[Dict[str, str]] = None,\n        _allow_fallback: bool = True,\n    ) -> str:\n        cs = self.config_holder.config_settings\n        return super().prepare_metadata_for_build_editable(\n            metadata_directory=metadata_directory,\n            config_settings=cs,\n            _allow_fallback=_allow_fallback,\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/models.py",
    "content": "\"\"\"Utilities for defining models\n\"\"\"\n\nimport operator\nfrom typing import Any, Callable, Type\n\n\nclass KeyBasedCompareMixin:\n    \"\"\"Provides comparison capabilities that is based on a key\"\"\"\n\n    __slots__ = [\"_compare_key\", \"_defining_class\"]\n\n    def __init__(self, key: Any, defining_class: Type[\"KeyBasedCompareMixin\"]) -> None:\n        self._compare_key = key\n        self._defining_class = defining_class\n\n    def __hash__(self) -> int:\n        return hash(self._compare_key)\n\n    def __lt__(self, other: Any) -> bool:\n        return self._compare(other, operator.__lt__)\n\n    def __le__(self, other: Any) -> bool:\n        return self._compare(other, operator.__le__)\n\n    def __gt__(self, other: Any) -> bool:\n        return self._compare(other, operator.__gt__)\n\n    def __ge__(self, other: Any) -> bool:\n        return self._compare(other, operator.__ge__)\n\n    def __eq__(self, other: Any) -> bool:\n        return self._compare(other, operator.__eq__)\n\n    def _compare(self, other: Any, method: Callable[[Any, Any], bool]) -> bool:\n        if not isinstance(other, self._defining_class):\n            return NotImplemented\n\n        return method(self._compare_key, other._compare_key)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/packaging.py",
    "content": "import functools\nimport logging\nimport re\nfrom typing import NewType, Optional, Tuple, cast\n\nfrom pip._vendor.packaging import specifiers, version\nfrom pip._vendor.packaging.requirements import Requirement\n\nNormalizedExtra = NewType(\"NormalizedExtra\", str)\n\nlogger = logging.getLogger(__name__)\n\n\ndef check_requires_python(\n    requires_python: Optional[str], version_info: Tuple[int, ...]\n) -> bool:\n    \"\"\"\n    Check if the given Python version matches a \"Requires-Python\" specifier.\n\n    :param version_info: A 3-tuple of ints representing a Python\n        major-minor-micro version to check (e.g. `sys.version_info[:3]`).\n\n    :return: `True` if the given Python version satisfies the requirement.\n        Otherwise, return `False`.\n\n    :raises InvalidSpecifier: If `requires_python` has an invalid format.\n    \"\"\"\n    if requires_python is None:\n        # The package provides no information\n        return True\n    requires_python_specifier = specifiers.SpecifierSet(requires_python)\n\n    python_version = version.parse(\".\".join(map(str, version_info)))\n    return python_version in requires_python_specifier\n\n\n@functools.lru_cache(maxsize=512)\ndef get_requirement(req_string: str) -> Requirement:\n    \"\"\"Construct a packaging.Requirement object with caching\"\"\"\n    # Parsing requirement strings is expensive, and is also expected to happen\n    # with a low diversity of different arguments (at least relative the number\n    # constructed). This method adds a cache to requirement object creation to\n    # minimize repeated parsing of the same string to construct equivalent\n    # Requirement objects.\n    return Requirement(req_string)\n\n\ndef safe_extra(extra: str) -> NormalizedExtra:\n    \"\"\"Convert an arbitrary string to a standard 'extra' name\n\n    Any runs of non-alphanumeric characters are replaced with a single '_',\n    and the result is always lowercased.\n\n    This function is duplicated from ``pkg_resources``. Note that this is not\n    the same to either ``canonicalize_name`` or ``_egg_link_name``.\n    \"\"\"\n    return cast(NormalizedExtra, re.sub(\"[^A-Za-z0-9.-]+\", \"_\", extra).lower())\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/setuptools_build.py",
    "content": "import sys\nimport textwrap\nfrom typing import List, Optional, Sequence\n\n# Shim to wrap setup.py invocation with setuptools\n# Note that __file__ is handled via two {!r} *and* %r, to ensure that paths on\n# Windows are correctly handled (it should be \"C:\\\\Users\" not \"C:\\Users\").\n_SETUPTOOLS_SHIM = textwrap.dedent(\n    \"\"\"\n    exec(compile('''\n    # This is <pip-setuptools-caller> -- a caller that pip uses to run setup.py\n    #\n    # - It imports setuptools before invoking setup.py, to enable projects that directly\n    #   import from `distutils.core` to work with newer packaging standards.\n    # - It provides a clear error message when setuptools is not installed.\n    # - It sets `sys.argv[0]` to the underlying `setup.py`, when invoking `setup.py` so\n    #   setuptools doesn't think the script is `-c`. This avoids the following warning:\n    #     manifest_maker: standard file '-c' not found\".\n    # - It generates a shim setup.py, for handling setup.cfg-only projects.\n    import os, sys, tokenize\n\n    try:\n        import setuptools\n    except ImportError as error:\n        print(\n            \"ERROR: Can not execute `setup.py` since setuptools is not available in \"\n            \"the build environment.\",\n            file=sys.stderr,\n        )\n        sys.exit(1)\n\n    __file__ = %r\n    sys.argv[0] = __file__\n\n    if os.path.exists(__file__):\n        filename = __file__\n        with tokenize.open(__file__) as f:\n            setup_py_code = f.read()\n    else:\n        filename = \"<auto-generated setuptools caller>\"\n        setup_py_code = \"from setuptools import setup; setup()\"\n\n    exec(compile(setup_py_code, filename, \"exec\"))\n    ''' % ({!r},), \"<pip-setuptools-caller>\", \"exec\"))\n    \"\"\"\n).rstrip()\n\n\ndef make_setuptools_shim_args(\n    setup_py_path: str,\n    global_options: Optional[Sequence[str]] = None,\n    no_user_config: bool = False,\n    unbuffered_output: bool = False,\n) -> List[str]:\n    \"\"\"\n    Get setuptools command arguments with shim wrapped setup file invocation.\n\n    :param setup_py_path: The path to setup.py to be wrapped.\n    :param global_options: Additional global options.\n    :param no_user_config: If True, disables personal user configuration.\n    :param unbuffered_output: If True, adds the unbuffered switch to the\n     argument list.\n    \"\"\"\n    args = [sys.executable]\n    if unbuffered_output:\n        args += [\"-u\"]\n    args += [\"-c\", _SETUPTOOLS_SHIM.format(setup_py_path)]\n    if global_options:\n        args += global_options\n    if no_user_config:\n        args += [\"--no-user-cfg\"]\n    return args\n\n\ndef make_setuptools_bdist_wheel_args(\n    setup_py_path: str,\n    global_options: Sequence[str],\n    build_options: Sequence[str],\n    destination_dir: str,\n) -> List[str]:\n    # NOTE: Eventually, we'd want to also -S to the flags here, when we're\n    # isolating. Currently, it breaks Python in virtualenvs, because it\n    # relies on site.py to find parts of the standard library outside the\n    # virtualenv.\n    args = make_setuptools_shim_args(\n        setup_py_path, global_options=global_options, unbuffered_output=True\n    )\n    args += [\"bdist_wheel\", \"-d\", destination_dir]\n    args += build_options\n    return args\n\n\ndef make_setuptools_clean_args(\n    setup_py_path: str,\n    global_options: Sequence[str],\n) -> List[str]:\n    args = make_setuptools_shim_args(\n        setup_py_path, global_options=global_options, unbuffered_output=True\n    )\n    args += [\"clean\", \"--all\"]\n    return args\n\n\ndef make_setuptools_develop_args(\n    setup_py_path: str,\n    global_options: Sequence[str],\n    install_options: Sequence[str],\n    no_user_config: bool,\n    prefix: Optional[str],\n    home: Optional[str],\n    use_user_site: bool,\n) -> List[str]:\n    assert not (use_user_site and prefix)\n\n    args = make_setuptools_shim_args(\n        setup_py_path,\n        global_options=global_options,\n        no_user_config=no_user_config,\n    )\n\n    args += [\"develop\", \"--no-deps\"]\n\n    args += install_options\n\n    if prefix:\n        args += [\"--prefix\", prefix]\n    if home is not None:\n        args += [\"--install-dir\", home]\n\n    if use_user_site:\n        args += [\"--user\", \"--prefix=\"]\n\n    return args\n\n\ndef make_setuptools_egg_info_args(\n    setup_py_path: str,\n    egg_info_dir: Optional[str],\n    no_user_config: bool,\n) -> List[str]:\n    args = make_setuptools_shim_args(setup_py_path, no_user_config=no_user_config)\n\n    args += [\"egg_info\"]\n\n    if egg_info_dir:\n        args += [\"--egg-base\", egg_info_dir]\n\n    return args\n\n\ndef make_setuptools_install_args(\n    setup_py_path: str,\n    global_options: Sequence[str],\n    install_options: Sequence[str],\n    record_filename: str,\n    root: Optional[str],\n    prefix: Optional[str],\n    header_dir: Optional[str],\n    home: Optional[str],\n    use_user_site: bool,\n    no_user_config: bool,\n    pycompile: bool,\n) -> List[str]:\n    assert not (use_user_site and prefix)\n    assert not (use_user_site and root)\n\n    args = make_setuptools_shim_args(\n        setup_py_path,\n        global_options=global_options,\n        no_user_config=no_user_config,\n        unbuffered_output=True,\n    )\n    args += [\"install\", \"--record\", record_filename]\n    args += [\"--single-version-externally-managed\"]\n\n    if root is not None:\n        args += [\"--root\", root]\n    if prefix is not None:\n        args += [\"--prefix\", prefix]\n    if home is not None:\n        args += [\"--home\", home]\n    if use_user_site:\n        args += [\"--user\", \"--prefix=\"]\n\n    if pycompile:\n        args += [\"--compile\"]\n    else:\n        args += [\"--no-compile\"]\n\n    if header_dir:\n        args += [\"--install-headers\", header_dir]\n\n    args += install_options\n\n    return args\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/subprocess.py",
    "content": "import logging\nimport os\nimport shlex\nimport subprocess\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Iterable,\n    List,\n    Mapping,\n    Optional,\n    Union,\n)\n\nfrom pip._vendor.rich.markup import escape\n\nfrom pip._internal.cli.spinners import SpinnerInterface, open_spinner\nfrom pip._internal.exceptions import InstallationSubprocessError\nfrom pip._internal.utils.logging import VERBOSE, subprocess_logger\nfrom pip._internal.utils.misc import HiddenText\n\nif TYPE_CHECKING:\n    # Literal was introduced in Python 3.8.\n    #\n    # TODO: Remove `if TYPE_CHECKING` when dropping support for Python 3.7.\n    from typing import Literal\n\nCommandArgs = List[Union[str, HiddenText]]\n\n\ndef make_command(*args: Union[str, HiddenText, CommandArgs]) -> CommandArgs:\n    \"\"\"\n    Create a CommandArgs object.\n    \"\"\"\n    command_args: CommandArgs = []\n    for arg in args:\n        # Check for list instead of CommandArgs since CommandArgs is\n        # only known during type-checking.\n        if isinstance(arg, list):\n            command_args.extend(arg)\n        else:\n            # Otherwise, arg is str or HiddenText.\n            command_args.append(arg)\n\n    return command_args\n\n\ndef format_command_args(args: Union[List[str], CommandArgs]) -> str:\n    \"\"\"\n    Format command arguments for display.\n    \"\"\"\n    # For HiddenText arguments, display the redacted form by calling str().\n    # Also, we don't apply str() to arguments that aren't HiddenText since\n    # this can trigger a UnicodeDecodeError in Python 2 if the argument\n    # has type unicode and includes a non-ascii character.  (The type\n    # checker doesn't ensure the annotations are correct in all cases.)\n    return \" \".join(\n        shlex.quote(str(arg)) if isinstance(arg, HiddenText) else shlex.quote(arg)\n        for arg in args\n    )\n\n\ndef reveal_command_args(args: Union[List[str], CommandArgs]) -> List[str]:\n    \"\"\"\n    Return the arguments in their raw, unredacted form.\n    \"\"\"\n    return [arg.secret if isinstance(arg, HiddenText) else arg for arg in args]\n\n\ndef call_subprocess(\n    cmd: Union[List[str], CommandArgs],\n    show_stdout: bool = False,\n    cwd: Optional[str] = None,\n    on_returncode: 'Literal[\"raise\", \"warn\", \"ignore\"]' = \"raise\",\n    extra_ok_returncodes: Optional[Iterable[int]] = None,\n    extra_environ: Optional[Mapping[str, Any]] = None,\n    unset_environ: Optional[Iterable[str]] = None,\n    spinner: Optional[SpinnerInterface] = None,\n    log_failed_cmd: Optional[bool] = True,\n    stdout_only: Optional[bool] = False,\n    *,\n    command_desc: str,\n) -> str:\n    \"\"\"\n    Args:\n      show_stdout: if true, use INFO to log the subprocess's stderr and\n        stdout streams.  Otherwise, use DEBUG.  Defaults to False.\n      extra_ok_returncodes: an iterable of integer return codes that are\n        acceptable, in addition to 0. Defaults to None, which means [].\n      unset_environ: an iterable of environment variable names to unset\n        prior to calling subprocess.Popen().\n      log_failed_cmd: if false, failed commands are not logged, only raised.\n      stdout_only: if true, return only stdout, else return both. When true,\n        logging of both stdout and stderr occurs when the subprocess has\n        terminated, else logging occurs as subprocess output is produced.\n    \"\"\"\n    if extra_ok_returncodes is None:\n        extra_ok_returncodes = []\n    if unset_environ is None:\n        unset_environ = []\n    # Most places in pip use show_stdout=False. What this means is--\n    #\n    # - We connect the child's output (combined stderr and stdout) to a\n    #   single pipe, which we read.\n    # - We log this output to stderr at DEBUG level as it is received.\n    # - If DEBUG logging isn't enabled (e.g. if --verbose logging wasn't\n    #   requested), then we show a spinner so the user can still see the\n    #   subprocess is in progress.\n    # - If the subprocess exits with an error, we log the output to stderr\n    #   at ERROR level if it hasn't already been displayed to the console\n    #   (e.g. if --verbose logging wasn't enabled).  This way we don't log\n    #   the output to the console twice.\n    #\n    # If show_stdout=True, then the above is still done, but with DEBUG\n    # replaced by INFO.\n    if show_stdout:\n        # Then log the subprocess output at INFO level.\n        log_subprocess: Callable[..., None] = subprocess_logger.info\n        used_level = logging.INFO\n    else:\n        # Then log the subprocess output using VERBOSE.  This also ensures\n        # it will be logged to the log file (aka user_log), if enabled.\n        log_subprocess = subprocess_logger.verbose\n        used_level = VERBOSE\n\n    # Whether the subprocess will be visible in the console.\n    showing_subprocess = subprocess_logger.getEffectiveLevel() <= used_level\n\n    # Only use the spinner if we're not showing the subprocess output\n    # and we have a spinner.\n    use_spinner = not showing_subprocess and spinner is not None\n\n    log_subprocess(\"Running command %s\", command_desc)\n    env = os.environ.copy()\n    if extra_environ:\n        env.update(extra_environ)\n    for name in unset_environ:\n        env.pop(name, None)\n    try:\n        proc = subprocess.Popen(\n            # Convert HiddenText objects to the underlying str.\n            reveal_command_args(cmd),\n            stdin=subprocess.PIPE,\n            stdout=subprocess.PIPE,\n            stderr=subprocess.STDOUT if not stdout_only else subprocess.PIPE,\n            cwd=cwd,\n            env=env,\n            errors=\"backslashreplace\",\n        )\n    except Exception as exc:\n        if log_failed_cmd:\n            subprocess_logger.critical(\n                \"Error %s while executing command %s\",\n                exc,\n                command_desc,\n            )\n        raise\n    all_output = []\n    if not stdout_only:\n        assert proc.stdout\n        assert proc.stdin\n        proc.stdin.close()\n        # In this mode, stdout and stderr are in the same pipe.\n        while True:\n            line: str = proc.stdout.readline()\n            if not line:\n                break\n            line = line.rstrip()\n            all_output.append(line + \"\\n\")\n\n            # Show the line immediately.\n            log_subprocess(line)\n            # Update the spinner.\n            if use_spinner:\n                assert spinner\n                spinner.spin()\n        try:\n            proc.wait()\n        finally:\n            if proc.stdout:\n                proc.stdout.close()\n        output = \"\".join(all_output)\n    else:\n        # In this mode, stdout and stderr are in different pipes.\n        # We must use communicate() which is the only safe way to read both.\n        out, err = proc.communicate()\n        # log line by line to preserve pip log indenting\n        for out_line in out.splitlines():\n            log_subprocess(out_line)\n        all_output.append(out)\n        for err_line in err.splitlines():\n            log_subprocess(err_line)\n        all_output.append(err)\n        output = out\n\n    proc_had_error = proc.returncode and proc.returncode not in extra_ok_returncodes\n    if use_spinner:\n        assert spinner\n        if proc_had_error:\n            spinner.finish(\"error\")\n        else:\n            spinner.finish(\"done\")\n    if proc_had_error:\n        if on_returncode == \"raise\":\n            error = InstallationSubprocessError(\n                command_description=command_desc,\n                exit_code=proc.returncode,\n                output_lines=all_output if not showing_subprocess else None,\n            )\n            if log_failed_cmd:\n                subprocess_logger.error(\"[present-rich] %s\", error)\n                subprocess_logger.verbose(\n                    \"[bold magenta]full command[/]: [blue]%s[/]\",\n                    escape(format_command_args(cmd)),\n                    extra={\"markup\": True},\n                )\n                subprocess_logger.verbose(\n                    \"[bold magenta]cwd[/]: %s\",\n                    escape(cwd or \"[inherit]\"),\n                    extra={\"markup\": True},\n                )\n\n            raise error\n        elif on_returncode == \"warn\":\n            subprocess_logger.warning(\n                'Command \"%s\" had error code %s in %s',\n                command_desc,\n                proc.returncode,\n                cwd,\n            )\n        elif on_returncode == \"ignore\":\n            pass\n        else:\n            raise ValueError(f\"Invalid value: on_returncode={on_returncode!r}\")\n    return output\n\n\ndef runner_with_spinner_message(message: str) -> Callable[..., None]:\n    \"\"\"Provide a subprocess_runner that shows a spinner message.\n\n    Intended for use with for pep517's Pep517HookCaller. Thus, the runner has\n    an API that matches what's expected by Pep517HookCaller.subprocess_runner.\n    \"\"\"\n\n    def runner(\n        cmd: List[str],\n        cwd: Optional[str] = None,\n        extra_environ: Optional[Mapping[str, Any]] = None,\n    ) -> None:\n        with open_spinner(message) as spinner:\n            call_subprocess(\n                cmd,\n                command_desc=message,\n                cwd=cwd,\n                extra_environ=extra_environ,\n                spinner=spinner,\n            )\n\n    return runner\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/temp_dir.py",
    "content": "import errno\nimport itertools\nimport logging\nimport os.path\nimport tempfile\nfrom contextlib import ExitStack, contextmanager\nfrom typing import Any, Dict, Generator, Optional, TypeVar, Union\n\nfrom pip._internal.utils.misc import enum, rmtree\n\nlogger = logging.getLogger(__name__)\n\n_T = TypeVar(\"_T\", bound=\"TempDirectory\")\n\n\n# Kinds of temporary directories. Only needed for ones that are\n# globally-managed.\ntempdir_kinds = enum(\n    BUILD_ENV=\"build-env\",\n    EPHEM_WHEEL_CACHE=\"ephem-wheel-cache\",\n    REQ_BUILD=\"req-build\",\n)\n\n\n_tempdir_manager: Optional[ExitStack] = None\n\n\n@contextmanager\ndef global_tempdir_manager() -> Generator[None, None, None]:\n    global _tempdir_manager\n    with ExitStack() as stack:\n        old_tempdir_manager, _tempdir_manager = _tempdir_manager, stack\n        try:\n            yield\n        finally:\n            _tempdir_manager = old_tempdir_manager\n\n\nclass TempDirectoryTypeRegistry:\n    \"\"\"Manages temp directory behavior\"\"\"\n\n    def __init__(self) -> None:\n        self._should_delete: Dict[str, bool] = {}\n\n    def set_delete(self, kind: str, value: bool) -> None:\n        \"\"\"Indicate whether a TempDirectory of the given kind should be\n        auto-deleted.\n        \"\"\"\n        self._should_delete[kind] = value\n\n    def get_delete(self, kind: str) -> bool:\n        \"\"\"Get configured auto-delete flag for a given TempDirectory type,\n        default True.\n        \"\"\"\n        return self._should_delete.get(kind, True)\n\n\n_tempdir_registry: Optional[TempDirectoryTypeRegistry] = None\n\n\n@contextmanager\ndef tempdir_registry() -> Generator[TempDirectoryTypeRegistry, None, None]:\n    \"\"\"Provides a scoped global tempdir registry that can be used to dictate\n    whether directories should be deleted.\n    \"\"\"\n    global _tempdir_registry\n    old_tempdir_registry = _tempdir_registry\n    _tempdir_registry = TempDirectoryTypeRegistry()\n    try:\n        yield _tempdir_registry\n    finally:\n        _tempdir_registry = old_tempdir_registry\n\n\nclass _Default:\n    pass\n\n\n_default = _Default()\n\n\nclass TempDirectory:\n    \"\"\"Helper class that owns and cleans up a temporary directory.\n\n    This class can be used as a context manager or as an OO representation of a\n    temporary directory.\n\n    Attributes:\n        path\n            Location to the created temporary directory\n        delete\n            Whether the directory should be deleted when exiting\n            (when used as a contextmanager)\n\n    Methods:\n        cleanup()\n            Deletes the temporary directory\n\n    When used as a context manager, if the delete attribute is True, on\n    exiting the context the temporary directory is deleted.\n    \"\"\"\n\n    def __init__(\n        self,\n        path: Optional[str] = None,\n        delete: Union[bool, None, _Default] = _default,\n        kind: str = \"temp\",\n        globally_managed: bool = False,\n    ):\n        super().__init__()\n\n        if delete is _default:\n            if path is not None:\n                # If we were given an explicit directory, resolve delete option\n                # now.\n                delete = False\n            else:\n                # Otherwise, we wait until cleanup and see what\n                # tempdir_registry says.\n                delete = None\n\n        # The only time we specify path is in for editables where it\n        # is the value of the --src option.\n        if path is None:\n            path = self._create(kind)\n\n        self._path = path\n        self._deleted = False\n        self.delete = delete\n        self.kind = kind\n\n        if globally_managed:\n            assert _tempdir_manager is not None\n            _tempdir_manager.enter_context(self)\n\n    @property\n    def path(self) -> str:\n        assert not self._deleted, f\"Attempted to access deleted path: {self._path}\"\n        return self._path\n\n    def __repr__(self) -> str:\n        return f\"<{self.__class__.__name__} {self.path!r}>\"\n\n    def __enter__(self: _T) -> _T:\n        return self\n\n    def __exit__(self, exc: Any, value: Any, tb: Any) -> None:\n        if self.delete is not None:\n            delete = self.delete\n        elif _tempdir_registry:\n            delete = _tempdir_registry.get_delete(self.kind)\n        else:\n            delete = True\n\n        if delete:\n            self.cleanup()\n\n    def _create(self, kind: str) -> str:\n        \"\"\"Create a temporary directory and store its path in self.path\"\"\"\n        # We realpath here because some systems have their default tmpdir\n        # symlinked to another directory.  This tends to confuse build\n        # scripts, so we canonicalize the path by traversing potential\n        # symlinks here.\n        path = os.path.realpath(tempfile.mkdtemp(prefix=f\"pip-{kind}-\"))\n        logger.debug(\"Created temporary directory: %s\", path)\n        return path\n\n    def cleanup(self) -> None:\n        \"\"\"Remove the temporary directory created and reset state\"\"\"\n        self._deleted = True\n        if not os.path.exists(self._path):\n            return\n        rmtree(self._path)\n\n\nclass AdjacentTempDirectory(TempDirectory):\n    \"\"\"Helper class that creates a temporary directory adjacent to a real one.\n\n    Attributes:\n        original\n            The original directory to create a temp directory for.\n        path\n            After calling create() or entering, contains the full\n            path to the temporary directory.\n        delete\n            Whether the directory should be deleted when exiting\n            (when used as a contextmanager)\n\n    \"\"\"\n\n    # The characters that may be used to name the temp directory\n    # We always prepend a ~ and then rotate through these until\n    # a usable name is found.\n    # pkg_resources raises a different error for .dist-info folder\n    # with leading '-' and invalid metadata\n    LEADING_CHARS = \"-~.=%0123456789\"\n\n    def __init__(self, original: str, delete: Optional[bool] = None) -> None:\n        self.original = original.rstrip(\"/\\\\\")\n        super().__init__(delete=delete)\n\n    @classmethod\n    def _generate_names(cls, name: str) -> Generator[str, None, None]:\n        \"\"\"Generates a series of temporary names.\n\n        The algorithm replaces the leading characters in the name\n        with ones that are valid filesystem characters, but are not\n        valid package names (for both Python and pip definitions of\n        package).\n        \"\"\"\n        for i in range(1, len(name)):\n            for candidate in itertools.combinations_with_replacement(\n                cls.LEADING_CHARS, i - 1\n            ):\n                new_name = \"~\" + \"\".join(candidate) + name[i:]\n                if new_name != name:\n                    yield new_name\n\n        # If we make it this far, we will have to make a longer name\n        for i in range(len(cls.LEADING_CHARS)):\n            for candidate in itertools.combinations_with_replacement(\n                cls.LEADING_CHARS, i\n            ):\n                new_name = \"~\" + \"\".join(candidate) + name\n                if new_name != name:\n                    yield new_name\n\n    def _create(self, kind: str) -> str:\n        root, name = os.path.split(self.original)\n        for candidate in self._generate_names(name):\n            path = os.path.join(root, candidate)\n            try:\n                os.mkdir(path)\n            except OSError as ex:\n                # Continue if the name exists already\n                if ex.errno != errno.EEXIST:\n                    raise\n            else:\n                path = os.path.realpath(path)\n                break\n        else:\n            # Final fallback on the default behavior.\n            path = os.path.realpath(tempfile.mkdtemp(prefix=f\"pip-{kind}-\"))\n\n        logger.debug(\"Created temporary directory: %s\", path)\n        return path\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/unpacking.py",
    "content": "\"\"\"Utilities related archives.\n\"\"\"\n\nimport logging\nimport os\nimport shutil\nimport stat\nimport tarfile\nimport zipfile\nfrom typing import Iterable, List, Optional\nfrom zipfile import ZipInfo\n\nfrom pip._internal.exceptions import InstallationError\nfrom pip._internal.utils.filetypes import (\n    BZ2_EXTENSIONS,\n    TAR_EXTENSIONS,\n    XZ_EXTENSIONS,\n    ZIP_EXTENSIONS,\n)\nfrom pip._internal.utils.misc import ensure_dir\n\nlogger = logging.getLogger(__name__)\n\n\nSUPPORTED_EXTENSIONS = ZIP_EXTENSIONS + TAR_EXTENSIONS\n\ntry:\n    import bz2  # noqa\n\n    SUPPORTED_EXTENSIONS += BZ2_EXTENSIONS\nexcept ImportError:\n    logger.debug(\"bz2 module is not available\")\n\ntry:\n    # Only for Python 3.3+\n    import lzma  # noqa\n\n    SUPPORTED_EXTENSIONS += XZ_EXTENSIONS\nexcept ImportError:\n    logger.debug(\"lzma module is not available\")\n\n\ndef current_umask() -> int:\n    \"\"\"Get the current umask which involves having to set it temporarily.\"\"\"\n    mask = os.umask(0)\n    os.umask(mask)\n    return mask\n\n\ndef split_leading_dir(path: str) -> List[str]:\n    path = path.lstrip(\"/\").lstrip(\"\\\\\")\n    if \"/\" in path and (\n        (\"\\\\\" in path and path.find(\"/\") < path.find(\"\\\\\")) or \"\\\\\" not in path\n    ):\n        return path.split(\"/\", 1)\n    elif \"\\\\\" in path:\n        return path.split(\"\\\\\", 1)\n    else:\n        return [path, \"\"]\n\n\ndef has_leading_dir(paths: Iterable[str]) -> bool:\n    \"\"\"Returns true if all the paths have the same leading path name\n    (i.e., everything is in one subdirectory in an archive)\"\"\"\n    common_prefix = None\n    for path in paths:\n        prefix, rest = split_leading_dir(path)\n        if not prefix:\n            return False\n        elif common_prefix is None:\n            common_prefix = prefix\n        elif prefix != common_prefix:\n            return False\n    return True\n\n\ndef is_within_directory(directory: str, target: str) -> bool:\n    \"\"\"\n    Return true if the absolute path of target is within the directory\n    \"\"\"\n    abs_directory = os.path.abspath(directory)\n    abs_target = os.path.abspath(target)\n\n    prefix = os.path.commonprefix([abs_directory, abs_target])\n    return prefix == abs_directory\n\n\ndef set_extracted_file_to_default_mode_plus_executable(path: str) -> None:\n    \"\"\"\n    Make file present at path have execute for user/group/world\n    (chmod +x) is no-op on windows per python docs\n    \"\"\"\n    os.chmod(path, (0o777 & ~current_umask() | 0o111))\n\n\ndef zip_item_is_executable(info: ZipInfo) -> bool:\n    mode = info.external_attr >> 16\n    # if mode and regular file and any execute permissions for\n    # user/group/world?\n    return bool(mode and stat.S_ISREG(mode) and mode & 0o111)\n\n\ndef unzip_file(filename: str, location: str, flatten: bool = True) -> None:\n    \"\"\"\n    Unzip the file (with path `filename`) to the destination `location`.  All\n    files are written based on system defaults and umask (i.e. permissions are\n    not preserved), except that regular file members with any execute\n    permissions (user, group, or world) have \"chmod +x\" applied after being\n    written. Note that for windows, any execute changes using os.chmod are\n    no-ops per the python docs.\n    \"\"\"\n    ensure_dir(location)\n    zipfp = open(filename, \"rb\")\n    try:\n        zip = zipfile.ZipFile(zipfp, allowZip64=True)\n        leading = has_leading_dir(zip.namelist()) and flatten\n        for info in zip.infolist():\n            name = info.filename\n            fn = name\n            if leading:\n                fn = split_leading_dir(name)[1]\n            fn = os.path.join(location, fn)\n            dir = os.path.dirname(fn)\n            if not is_within_directory(location, fn):\n                message = (\n                    \"The zip file ({}) has a file ({}) trying to install \"\n                    \"outside target directory ({})\"\n                )\n                raise InstallationError(message.format(filename, fn, location))\n            if fn.endswith(\"/\") or fn.endswith(\"\\\\\"):\n                # A directory\n                ensure_dir(fn)\n            else:\n                ensure_dir(dir)\n                # Don't use read() to avoid allocating an arbitrarily large\n                # chunk of memory for the file's content\n                fp = zip.open(name)\n                try:\n                    with open(fn, \"wb\") as destfp:\n                        shutil.copyfileobj(fp, destfp)\n                finally:\n                    fp.close()\n                    if zip_item_is_executable(info):\n                        set_extracted_file_to_default_mode_plus_executable(fn)\n    finally:\n        zipfp.close()\n\n\ndef untar_file(filename: str, location: str) -> None:\n    \"\"\"\n    Untar the file (with path `filename`) to the destination `location`.\n    All files are written based on system defaults and umask (i.e. permissions\n    are not preserved), except that regular file members with any execute\n    permissions (user, group, or world) have \"chmod +x\" applied after being\n    written.  Note that for windows, any execute changes using os.chmod are\n    no-ops per the python docs.\n    \"\"\"\n    ensure_dir(location)\n    if filename.lower().endswith(\".gz\") or filename.lower().endswith(\".tgz\"):\n        mode = \"r:gz\"\n    elif filename.lower().endswith(BZ2_EXTENSIONS):\n        mode = \"r:bz2\"\n    elif filename.lower().endswith(XZ_EXTENSIONS):\n        mode = \"r:xz\"\n    elif filename.lower().endswith(\".tar\"):\n        mode = \"r\"\n    else:\n        logger.warning(\n            \"Cannot determine compression type for file %s\",\n            filename,\n        )\n        mode = \"r:*\"\n    tar = tarfile.open(filename, mode, encoding=\"utf-8\")\n    try:\n        leading = has_leading_dir([member.name for member in tar.getmembers()])\n        for member in tar.getmembers():\n            fn = member.name\n            if leading:\n                fn = split_leading_dir(fn)[1]\n            path = os.path.join(location, fn)\n            if not is_within_directory(location, path):\n                message = (\n                    \"The tar file ({}) has a file ({}) trying to install \"\n                    \"outside target directory ({})\"\n                )\n                raise InstallationError(message.format(filename, path, location))\n            if member.isdir():\n                ensure_dir(path)\n            elif member.issym():\n                try:\n                    tar._extract_member(member, path)\n                except Exception as exc:\n                    # Some corrupt tar files seem to produce this\n                    # (specifically bad symlinks)\n                    logger.warning(\n                        \"In the tar file %s the member %s is invalid: %s\",\n                        filename,\n                        member.name,\n                        exc,\n                    )\n                    continue\n            else:\n                try:\n                    fp = tar.extractfile(member)\n                except (KeyError, AttributeError) as exc:\n                    # Some corrupt tar files seem to produce this\n                    # (specifically bad symlinks)\n                    logger.warning(\n                        \"In the tar file %s the member %s is invalid: %s\",\n                        filename,\n                        member.name,\n                        exc,\n                    )\n                    continue\n                ensure_dir(os.path.dirname(path))\n                assert fp is not None\n                with open(path, \"wb\") as destfp:\n                    shutil.copyfileobj(fp, destfp)\n                fp.close()\n                # Update the timestamp (useful for cython compiled files)\n                tar.utime(member, path)\n                # member have any execute permissions for user/group/world?\n                if member.mode & 0o111:\n                    set_extracted_file_to_default_mode_plus_executable(path)\n    finally:\n        tar.close()\n\n\ndef unpack_file(\n    filename: str,\n    location: str,\n    content_type: Optional[str] = None,\n) -> None:\n    filename = os.path.realpath(filename)\n    if (\n        content_type == \"application/zip\"\n        or filename.lower().endswith(ZIP_EXTENSIONS)\n        or zipfile.is_zipfile(filename)\n    ):\n        unzip_file(filename, location, flatten=not filename.endswith(\".whl\"))\n    elif (\n        content_type == \"application/x-gzip\"\n        or tarfile.is_tarfile(filename)\n        or filename.lower().endswith(TAR_EXTENSIONS + BZ2_EXTENSIONS + XZ_EXTENSIONS)\n    ):\n        untar_file(filename, location)\n    else:\n        # FIXME: handle?\n        # FIXME: magic signatures?\n        logger.critical(\n            \"Cannot unpack file %s (downloaded from %s, content-type: %s); \"\n            \"cannot detect archive format\",\n            filename,\n            location,\n            content_type,\n        )\n        raise InstallationError(f\"Cannot determine archive format of {location}\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/urls.py",
    "content": "import os\nimport string\nimport urllib.parse\nimport urllib.request\nfrom typing import Optional\n\nfrom .compat import WINDOWS\n\n\ndef get_url_scheme(url: str) -> Optional[str]:\n    if \":\" not in url:\n        return None\n    return url.split(\":\", 1)[0].lower()\n\n\ndef path_to_url(path: str) -> str:\n    \"\"\"\n    Convert a path to a file: URL.  The path will be made absolute and have\n    quoted path parts.\n    \"\"\"\n    path = os.path.normpath(os.path.abspath(path))\n    url = urllib.parse.urljoin(\"file:\", urllib.request.pathname2url(path))\n    return url\n\n\ndef url_to_path(url: str) -> str:\n    \"\"\"\n    Convert a file: URL to a path.\n    \"\"\"\n    assert url.startswith(\n        \"file:\"\n    ), f\"You can only turn file: urls into filenames (not {url!r})\"\n\n    _, netloc, path, _, _ = urllib.parse.urlsplit(url)\n\n    if not netloc or netloc == \"localhost\":\n        # According to RFC 8089, same as empty authority.\n        netloc = \"\"\n    elif WINDOWS:\n        # If we have a UNC path, prepend UNC share notation.\n        netloc = \"\\\\\\\\\" + netloc\n    else:\n        raise ValueError(\n            f\"non-local file URIs are not supported on this platform: {url!r}\"\n        )\n\n    path = urllib.request.url2pathname(netloc + path)\n\n    # On Windows, urlsplit parses the path as something like \"/C:/Users/foo\".\n    # This creates issues for path-related functions like io.open(), so we try\n    # to detect and strip the leading slash.\n    if (\n        WINDOWS\n        and not netloc  # Not UNC.\n        and len(path) >= 3\n        and path[0] == \"/\"  # Leading slash to strip.\n        and path[1] in string.ascii_letters  # Drive letter.\n        and path[2:4] in (\":\", \":/\")  # Colon + end of string, or colon + absolute path.\n    ):\n        path = path[1:]\n\n    return path\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/virtualenv.py",
    "content": "import logging\nimport os\nimport re\nimport site\nimport sys\nfrom typing import List, Optional\n\nlogger = logging.getLogger(__name__)\n_INCLUDE_SYSTEM_SITE_PACKAGES_REGEX = re.compile(\n    r\"include-system-site-packages\\s*=\\s*(?P<value>true|false)\"\n)\n\n\ndef _running_under_venv() -> bool:\n    \"\"\"Checks if sys.base_prefix and sys.prefix match.\n\n    This handles PEP 405 compliant virtual environments.\n    \"\"\"\n    return sys.prefix != getattr(sys, \"base_prefix\", sys.prefix)\n\n\ndef _running_under_regular_virtualenv() -> bool:\n    \"\"\"Checks if sys.real_prefix is set.\n\n    This handles virtual environments created with pypa's virtualenv.\n    \"\"\"\n    # pypa/virtualenv case\n    return hasattr(sys, \"real_prefix\")\n\n\ndef running_under_virtualenv() -> bool:\n    \"\"\"Return True if we're running inside a virtualenv, False otherwise.\"\"\"\n    return _running_under_venv() or _running_under_regular_virtualenv()\n\n\ndef _get_pyvenv_cfg_lines() -> Optional[List[str]]:\n    \"\"\"Reads {sys.prefix}/pyvenv.cfg and returns its contents as list of lines\n\n    Returns None, if it could not read/access the file.\n    \"\"\"\n    pyvenv_cfg_file = os.path.join(sys.prefix, \"pyvenv.cfg\")\n    try:\n        # Although PEP 405 does not specify, the built-in venv module always\n        # writes with UTF-8. (pypa/pip#8717)\n        with open(pyvenv_cfg_file, encoding=\"utf-8\") as f:\n            return f.read().splitlines()  # avoids trailing newlines\n    except OSError:\n        return None\n\n\ndef _no_global_under_venv() -> bool:\n    \"\"\"Check `{sys.prefix}/pyvenv.cfg` for system site-packages inclusion\n\n    PEP 405 specifies that when system site-packages are not supposed to be\n    visible from a virtual environment, `pyvenv.cfg` must contain the following\n    line:\n\n        include-system-site-packages = false\n\n    Additionally, log a warning if accessing the file fails.\n    \"\"\"\n    cfg_lines = _get_pyvenv_cfg_lines()\n    if cfg_lines is None:\n        # We're not in a \"sane\" venv, so assume there is no system\n        # site-packages access (since that's PEP 405's default state).\n        logger.warning(\n            \"Could not access 'pyvenv.cfg' despite a virtual environment \"\n            \"being active. Assuming global site-packages is not accessible \"\n            \"in this environment.\"\n        )\n        return True\n\n    for line in cfg_lines:\n        match = _INCLUDE_SYSTEM_SITE_PACKAGES_REGEX.match(line)\n        if match is not None and match.group(\"value\") == \"false\":\n            return True\n    return False\n\n\ndef _no_global_under_regular_virtualenv() -> bool:\n    \"\"\"Check if \"no-global-site-packages.txt\" exists beside site.py\n\n    This mirrors logic in pypa/virtualenv for determining whether system\n    site-packages are visible in the virtual environment.\n    \"\"\"\n    site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))\n    no_global_site_packages_file = os.path.join(\n        site_mod_dir,\n        \"no-global-site-packages.txt\",\n    )\n    return os.path.exists(no_global_site_packages_file)\n\n\ndef virtualenv_no_global() -> bool:\n    \"\"\"Returns a boolean, whether running in venv with no system site-packages.\"\"\"\n    # PEP 405 compliance needs to be checked first since virtualenv >=20 would\n    # return True for both checks, but is only able to use the PEP 405 config.\n    if _running_under_venv():\n        return _no_global_under_venv()\n\n    if _running_under_regular_virtualenv():\n        return _no_global_under_regular_virtualenv()\n\n    return False\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/utils/wheel.py",
    "content": "\"\"\"Support functions for working with wheel files.\n\"\"\"\n\nimport logging\nfrom email.message import Message\nfrom email.parser import Parser\nfrom typing import Tuple\nfrom zipfile import BadZipFile, ZipFile\n\nfrom pip._vendor.packaging.utils import canonicalize_name\n\nfrom pip._internal.exceptions import UnsupportedWheel\n\nVERSION_COMPATIBLE = (1, 0)\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef parse_wheel(wheel_zip: ZipFile, name: str) -> Tuple[str, Message]:\n    \"\"\"Extract information from the provided wheel, ensuring it meets basic\n    standards.\n\n    Returns the name of the .dist-info directory and the parsed WHEEL metadata.\n    \"\"\"\n    try:\n        info_dir = wheel_dist_info_dir(wheel_zip, name)\n        metadata = wheel_metadata(wheel_zip, info_dir)\n        version = wheel_version(metadata)\n    except UnsupportedWheel as e:\n        raise UnsupportedWheel(\"{} has an invalid wheel, {}\".format(name, str(e)))\n\n    check_compatibility(version, name)\n\n    return info_dir, metadata\n\n\ndef wheel_dist_info_dir(source: ZipFile, name: str) -> str:\n    \"\"\"Returns the name of the contained .dist-info directory.\n\n    Raises AssertionError or UnsupportedWheel if not found, >1 found, or\n    it doesn't match the provided name.\n    \"\"\"\n    # Zip file path separators must be /\n    subdirs = {p.split(\"/\", 1)[0] for p in source.namelist()}\n\n    info_dirs = [s for s in subdirs if s.endswith(\".dist-info\")]\n\n    if not info_dirs:\n        raise UnsupportedWheel(\".dist-info directory not found\")\n\n    if len(info_dirs) > 1:\n        raise UnsupportedWheel(\n            \"multiple .dist-info directories found: {}\".format(\", \".join(info_dirs))\n        )\n\n    info_dir = info_dirs[0]\n\n    info_dir_name = canonicalize_name(info_dir)\n    canonical_name = canonicalize_name(name)\n    if not info_dir_name.startswith(canonical_name):\n        raise UnsupportedWheel(\n            \".dist-info directory {!r} does not start with {!r}\".format(\n                info_dir, canonical_name\n            )\n        )\n\n    return info_dir\n\n\ndef read_wheel_metadata_file(source: ZipFile, path: str) -> bytes:\n    try:\n        return source.read(path)\n        # BadZipFile for general corruption, KeyError for missing entry,\n        # and RuntimeError for password-protected files\n    except (BadZipFile, KeyError, RuntimeError) as e:\n        raise UnsupportedWheel(f\"could not read {path!r} file: {e!r}\")\n\n\ndef wheel_metadata(source: ZipFile, dist_info_dir: str) -> Message:\n    \"\"\"Return the WHEEL metadata of an extracted wheel, if possible.\n    Otherwise, raise UnsupportedWheel.\n    \"\"\"\n    path = f\"{dist_info_dir}/WHEEL\"\n    # Zip file path separators must be /\n    wheel_contents = read_wheel_metadata_file(source, path)\n\n    try:\n        wheel_text = wheel_contents.decode()\n    except UnicodeDecodeError as e:\n        raise UnsupportedWheel(f\"error decoding {path!r}: {e!r}\")\n\n    # FeedParser (used by Parser) does not raise any exceptions. The returned\n    # message may have .defects populated, but for backwards-compatibility we\n    # currently ignore them.\n    return Parser().parsestr(wheel_text)\n\n\ndef wheel_version(wheel_data: Message) -> Tuple[int, ...]:\n    \"\"\"Given WHEEL metadata, return the parsed Wheel-Version.\n    Otherwise, raise UnsupportedWheel.\n    \"\"\"\n    version_text = wheel_data[\"Wheel-Version\"]\n    if version_text is None:\n        raise UnsupportedWheel(\"WHEEL is missing Wheel-Version\")\n\n    version = version_text.strip()\n\n    try:\n        return tuple(map(int, version.split(\".\")))\n    except ValueError:\n        raise UnsupportedWheel(f\"invalid Wheel-Version: {version!r}\")\n\n\ndef check_compatibility(version: Tuple[int, ...], name: str) -> None:\n    \"\"\"Raises errors or warns if called with an incompatible Wheel-Version.\n\n    pip should refuse to install a Wheel-Version that's a major series\n    ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when\n    installing a version only minor version ahead (e.g 1.2 > 1.1).\n\n    version: a 2-tuple representing a Wheel-Version (Major, Minor)\n    name: name of wheel or package to raise exception about\n\n    :raises UnsupportedWheel: when an incompatible Wheel-Version is given\n    \"\"\"\n    if version[0] > VERSION_COMPATIBLE[0]:\n        raise UnsupportedWheel(\n            \"{}'s Wheel-Version ({}) is not compatible with this version \"\n            \"of pip\".format(name, \".\".join(map(str, version)))\n        )\n    elif version > VERSION_COMPATIBLE:\n        logger.warning(\n            \"Installing from a newer Wheel-Version (%s)\",\n            \".\".join(map(str, version)),\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/vcs/__init__.py",
    "content": "# Expose a limited set of classes and functions so callers outside of\n# the vcs package don't need to import deeper than `pip._internal.vcs`.\n# (The test directory may still need to import from a vcs sub-package.)\n# Import all vcs modules to register each VCS in the VcsSupport object.\nimport pip._internal.vcs.bazaar\nimport pip._internal.vcs.git\nimport pip._internal.vcs.mercurial\nimport pip._internal.vcs.subversion  # noqa: F401\nfrom pip._internal.vcs.versioncontrol import (  # noqa: F401\n    RemoteNotFoundError,\n    RemoteNotValidError,\n    is_url,\n    make_vcs_requirement_url,\n    vcs,\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/vcs/bazaar.py",
    "content": "import logging\nfrom typing import List, Optional, Tuple\n\nfrom pip._internal.utils.misc import HiddenText, display_path\nfrom pip._internal.utils.subprocess import make_command\nfrom pip._internal.utils.urls import path_to_url\nfrom pip._internal.vcs.versioncontrol import (\n    AuthInfo,\n    RemoteNotFoundError,\n    RevOptions,\n    VersionControl,\n    vcs,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass Bazaar(VersionControl):\n    name = \"bzr\"\n    dirname = \".bzr\"\n    repo_name = \"branch\"\n    schemes = (\n        \"bzr+http\",\n        \"bzr+https\",\n        \"bzr+ssh\",\n        \"bzr+sftp\",\n        \"bzr+ftp\",\n        \"bzr+lp\",\n        \"bzr+file\",\n    )\n\n    @staticmethod\n    def get_base_rev_args(rev: str) -> List[str]:\n        return [\"-r\", rev]\n\n    def fetch_new(\n        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int\n    ) -> None:\n        rev_display = rev_options.to_display()\n        logger.info(\n            \"Checking out %s%s to %s\",\n            url,\n            rev_display,\n            display_path(dest),\n        )\n        if verbosity <= 0:\n            flag = \"--quiet\"\n        elif verbosity == 1:\n            flag = \"\"\n        else:\n            flag = f\"-{'v'*verbosity}\"\n        cmd_args = make_command(\n            \"checkout\", \"--lightweight\", flag, rev_options.to_args(), url, dest\n        )\n        self.run_command(cmd_args)\n\n    def switch(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:\n        self.run_command(make_command(\"switch\", url), cwd=dest)\n\n    def update(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:\n        output = self.run_command(\n            make_command(\"info\"), show_stdout=False, stdout_only=True, cwd=dest\n        )\n        if output.startswith(\"Standalone \"):\n            # Older versions of pip used to create standalone branches.\n            # Convert the standalone branch to a checkout by calling \"bzr bind\".\n            cmd_args = make_command(\"bind\", \"-q\", url)\n            self.run_command(cmd_args, cwd=dest)\n\n        cmd_args = make_command(\"update\", \"-q\", rev_options.to_args())\n        self.run_command(cmd_args, cwd=dest)\n\n    @classmethod\n    def get_url_rev_and_auth(cls, url: str) -> Tuple[str, Optional[str], AuthInfo]:\n        # hotfix the URL scheme after removing bzr+ from bzr+ssh:// readd it\n        url, rev, user_pass = super().get_url_rev_and_auth(url)\n        if url.startswith(\"ssh://\"):\n            url = \"bzr+\" + url\n        return url, rev, user_pass\n\n    @classmethod\n    def get_remote_url(cls, location: str) -> str:\n        urls = cls.run_command(\n            [\"info\"], show_stdout=False, stdout_only=True, cwd=location\n        )\n        for line in urls.splitlines():\n            line = line.strip()\n            for x in (\"checkout of branch: \", \"parent branch: \"):\n                if line.startswith(x):\n                    repo = line.split(x)[1]\n                    if cls._is_local_repository(repo):\n                        return path_to_url(repo)\n                    return repo\n        raise RemoteNotFoundError\n\n    @classmethod\n    def get_revision(cls, location: str) -> str:\n        revision = cls.run_command(\n            [\"revno\"],\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        )\n        return revision.splitlines()[-1]\n\n    @classmethod\n    def is_commit_id_equal(cls, dest: str, name: Optional[str]) -> bool:\n        \"\"\"Always assume the versions don't match\"\"\"\n        return False\n\n\nvcs.register(Bazaar)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/vcs/git.py",
    "content": "import logging\nimport os.path\nimport pathlib\nimport re\nimport urllib.parse\nimport urllib.request\nfrom typing import List, Optional, Tuple\n\nfrom pip._internal.exceptions import BadCommand, InstallationError\nfrom pip._internal.utils.misc import HiddenText, display_path, hide_url\nfrom pip._internal.utils.subprocess import make_command\nfrom pip._internal.vcs.versioncontrol import (\n    AuthInfo,\n    RemoteNotFoundError,\n    RemoteNotValidError,\n    RevOptions,\n    VersionControl,\n    find_path_to_project_root_from_repo_root,\n    vcs,\n)\n\nurlsplit = urllib.parse.urlsplit\nurlunsplit = urllib.parse.urlunsplit\n\n\nlogger = logging.getLogger(__name__)\n\n\nGIT_VERSION_REGEX = re.compile(\n    r\"^git version \"  # Prefix.\n    r\"(\\d+)\"  # Major.\n    r\"\\.(\\d+)\"  # Dot, minor.\n    r\"(?:\\.(\\d+))?\"  # Optional dot, patch.\n    r\".*$\"  # Suffix, including any pre- and post-release segments we don't care about.\n)\n\nHASH_REGEX = re.compile(\"^[a-fA-F0-9]{40}$\")\n\n# SCP (Secure copy protocol) shorthand. e.g. 'git@example.com:foo/bar.git'\nSCP_REGEX = re.compile(\n    r\"\"\"^\n    # Optional user, e.g. 'git@'\n    (\\w+@)?\n    # Server, e.g. 'github.com'.\n    ([^/:]+):\n    # The server-side path. e.g. 'user/project.git'. Must start with an\n    # alphanumeric character so as not to be confusable with a Windows paths\n    # like 'C:/foo/bar' or 'C:\\foo\\bar'.\n    (\\w[^:]*)\n    $\"\"\",\n    re.VERBOSE,\n)\n\n\ndef looks_like_hash(sha: str) -> bool:\n    return bool(HASH_REGEX.match(sha))\n\n\nclass Git(VersionControl):\n    name = \"git\"\n    dirname = \".git\"\n    repo_name = \"clone\"\n    schemes = (\n        \"git+http\",\n        \"git+https\",\n        \"git+ssh\",\n        \"git+git\",\n        \"git+file\",\n    )\n    # Prevent the user's environment variables from interfering with pip:\n    # https://github.com/pypa/pip/issues/1130\n    unset_environ = (\"GIT_DIR\", \"GIT_WORK_TREE\")\n    default_arg_rev = \"HEAD\"\n\n    @staticmethod\n    def get_base_rev_args(rev: str) -> List[str]:\n        return [rev]\n\n    def is_immutable_rev_checkout(self, url: str, dest: str) -> bool:\n        _, rev_options = self.get_url_rev_options(hide_url(url))\n        if not rev_options.rev:\n            return False\n        if not self.is_commit_id_equal(dest, rev_options.rev):\n            # the current commit is different from rev,\n            # which means rev was something else than a commit hash\n            return False\n        # return False in the rare case rev is both a commit hash\n        # and a tag or a branch; we don't want to cache in that case\n        # because that branch/tag could point to something else in the future\n        is_tag_or_branch = bool(self.get_revision_sha(dest, rev_options.rev)[0])\n        return not is_tag_or_branch\n\n    def get_git_version(self) -> Tuple[int, ...]:\n        version = self.run_command(\n            [\"version\"],\n            command_desc=\"git version\",\n            show_stdout=False,\n            stdout_only=True,\n        )\n        match = GIT_VERSION_REGEX.match(version)\n        if not match:\n            logger.warning(\"Can't parse git version: %s\", version)\n            return ()\n        return tuple(int(c) for c in match.groups())\n\n    @classmethod\n    def get_current_branch(cls, location: str) -> Optional[str]:\n        \"\"\"\n        Return the current branch, or None if HEAD isn't at a branch\n        (e.g. detached HEAD).\n        \"\"\"\n        # git-symbolic-ref exits with empty stdout if \"HEAD\" is a detached\n        # HEAD rather than a symbolic ref.  In addition, the -q causes the\n        # command to exit with status code 1 instead of 128 in this case\n        # and to suppress the message to stderr.\n        args = [\"symbolic-ref\", \"-q\", \"HEAD\"]\n        output = cls.run_command(\n            args,\n            extra_ok_returncodes=(1,),\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        )\n        ref = output.strip()\n\n        if ref.startswith(\"refs/heads/\"):\n            return ref[len(\"refs/heads/\") :]\n\n        return None\n\n    @classmethod\n    def get_revision_sha(cls, dest: str, rev: str) -> Tuple[Optional[str], bool]:\n        \"\"\"\n        Return (sha_or_none, is_branch), where sha_or_none is a commit hash\n        if the revision names a remote branch or tag, otherwise None.\n\n        Args:\n          dest: the repository directory.\n          rev: the revision name.\n        \"\"\"\n        # Pass rev to pre-filter the list.\n        output = cls.run_command(\n            [\"show-ref\", rev],\n            cwd=dest,\n            show_stdout=False,\n            stdout_only=True,\n            on_returncode=\"ignore\",\n        )\n        refs = {}\n        # NOTE: We do not use splitlines here since that would split on other\n        #       unicode separators, which can be maliciously used to install a\n        #       different revision.\n        for line in output.strip().split(\"\\n\"):\n            line = line.rstrip(\"\\r\")\n            if not line:\n                continue\n            try:\n                ref_sha, ref_name = line.split(\" \", maxsplit=2)\n            except ValueError:\n                # Include the offending line to simplify troubleshooting if\n                # this error ever occurs.\n                raise ValueError(f\"unexpected show-ref line: {line!r}\")\n\n            refs[ref_name] = ref_sha\n\n        branch_ref = f\"refs/remotes/origin/{rev}\"\n        tag_ref = f\"refs/tags/{rev}\"\n\n        sha = refs.get(branch_ref)\n        if sha is not None:\n            return (sha, True)\n\n        sha = refs.get(tag_ref)\n\n        return (sha, False)\n\n    @classmethod\n    def _should_fetch(cls, dest: str, rev: str) -> bool:\n        \"\"\"\n        Return true if rev is a ref or is a commit that we don't have locally.\n\n        Branches and tags are not considered in this method because they are\n        assumed to be always available locally (which is a normal outcome of\n        ``git clone`` and ``git fetch --tags``).\n        \"\"\"\n        if rev.startswith(\"refs/\"):\n            # Always fetch remote refs.\n            return True\n\n        if not looks_like_hash(rev):\n            # Git fetch would fail with abbreviated commits.\n            return False\n\n        if cls.has_commit(dest, rev):\n            # Don't fetch if we have the commit locally.\n            return False\n\n        return True\n\n    @classmethod\n    def resolve_revision(\n        cls, dest: str, url: HiddenText, rev_options: RevOptions\n    ) -> RevOptions:\n        \"\"\"\n        Resolve a revision to a new RevOptions object with the SHA1 of the\n        branch, tag, or ref if found.\n\n        Args:\n          rev_options: a RevOptions object.\n        \"\"\"\n        rev = rev_options.arg_rev\n        # The arg_rev property's implementation for Git ensures that the\n        # rev return value is always non-None.\n        assert rev is not None\n\n        sha, is_branch = cls.get_revision_sha(dest, rev)\n\n        if sha is not None:\n            rev_options = rev_options.make_new(sha)\n            rev_options.branch_name = rev if is_branch else None\n\n            return rev_options\n\n        # Do not show a warning for the common case of something that has\n        # the form of a Git commit hash.\n        if not looks_like_hash(rev):\n            logger.warning(\n                \"Did not find branch or tag '%s', assuming revision or ref.\",\n                rev,\n            )\n\n        if not cls._should_fetch(dest, rev):\n            return rev_options\n\n        # fetch the requested revision\n        cls.run_command(\n            make_command(\"fetch\", \"-q\", url, rev_options.to_args()),\n            cwd=dest,\n        )\n        # Change the revision to the SHA of the ref we fetched\n        sha = cls.get_revision(dest, rev=\"FETCH_HEAD\")\n        rev_options = rev_options.make_new(sha)\n\n        return rev_options\n\n    @classmethod\n    def is_commit_id_equal(cls, dest: str, name: Optional[str]) -> bool:\n        \"\"\"\n        Return whether the current commit hash equals the given name.\n\n        Args:\n          dest: the repository directory.\n          name: a string name.\n        \"\"\"\n        if not name:\n            # Then avoid an unnecessary subprocess call.\n            return False\n\n        return cls.get_revision(dest) == name\n\n    def fetch_new(\n        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int\n    ) -> None:\n        rev_display = rev_options.to_display()\n        logger.info(\"Cloning %s%s to %s\", url, rev_display, display_path(dest))\n        if verbosity <= 0:\n            flags: Tuple[str, ...] = (\"--quiet\",)\n        elif verbosity == 1:\n            flags = ()\n        else:\n            flags = (\"--verbose\", \"--progress\")\n        if self.get_git_version() >= (2, 17):\n            # Git added support for partial clone in 2.17\n            # https://git-scm.com/docs/partial-clone\n            # Speeds up cloning by functioning without a complete copy of repository\n            self.run_command(\n                make_command(\n                    \"clone\",\n                    \"--filter=blob:none\",\n                    *flags,\n                    url,\n                    dest,\n                )\n            )\n        else:\n            self.run_command(make_command(\"clone\", *flags, url, dest))\n\n        if rev_options.rev:\n            # Then a specific revision was requested.\n            rev_options = self.resolve_revision(dest, url, rev_options)\n            branch_name = getattr(rev_options, \"branch_name\", None)\n            logger.debug(\"Rev options %s, branch_name %s\", rev_options, branch_name)\n            if branch_name is None:\n                # Only do a checkout if the current commit id doesn't match\n                # the requested revision.\n                if not self.is_commit_id_equal(dest, rev_options.rev):\n                    cmd_args = make_command(\n                        \"checkout\",\n                        \"-q\",\n                        rev_options.to_args(),\n                    )\n                    self.run_command(cmd_args, cwd=dest)\n            elif self.get_current_branch(dest) != branch_name:\n                # Then a specific branch was requested, and that branch\n                # is not yet checked out.\n                track_branch = f\"origin/{branch_name}\"\n                cmd_args = [\n                    \"checkout\",\n                    \"-b\",\n                    branch_name,\n                    \"--track\",\n                    track_branch,\n                ]\n                self.run_command(cmd_args, cwd=dest)\n        else:\n            sha = self.get_revision(dest)\n            rev_options = rev_options.make_new(sha)\n\n        logger.info(\"Resolved %s to commit %s\", url, rev_options.rev)\n\n        #: repo may contain submodules\n        self.update_submodules(dest)\n\n    def switch(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:\n        self.run_command(\n            make_command(\"config\", \"remote.origin.url\", url),\n            cwd=dest,\n        )\n        cmd_args = make_command(\"checkout\", \"-q\", rev_options.to_args())\n        self.run_command(cmd_args, cwd=dest)\n\n        self.update_submodules(dest)\n\n    def update(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:\n        # First fetch changes from the default remote\n        if self.get_git_version() >= (1, 9):\n            # fetch tags in addition to everything else\n            self.run_command([\"fetch\", \"-q\", \"--tags\"], cwd=dest)\n        else:\n            self.run_command([\"fetch\", \"-q\"], cwd=dest)\n        # Then reset to wanted revision (maybe even origin/master)\n        rev_options = self.resolve_revision(dest, url, rev_options)\n        cmd_args = make_command(\"reset\", \"--hard\", \"-q\", rev_options.to_args())\n        self.run_command(cmd_args, cwd=dest)\n        #: update submodules\n        self.update_submodules(dest)\n\n    @classmethod\n    def get_remote_url(cls, location: str) -> str:\n        \"\"\"\n        Return URL of the first remote encountered.\n\n        Raises RemoteNotFoundError if the repository does not have a remote\n        url configured.\n        \"\"\"\n        # We need to pass 1 for extra_ok_returncodes since the command\n        # exits with return code 1 if there are no matching lines.\n        stdout = cls.run_command(\n            [\"config\", \"--get-regexp\", r\"remote\\..*\\.url\"],\n            extra_ok_returncodes=(1,),\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        )\n        remotes = stdout.splitlines()\n        try:\n            found_remote = remotes[0]\n        except IndexError:\n            raise RemoteNotFoundError\n\n        for remote in remotes:\n            if remote.startswith(\"remote.origin.url \"):\n                found_remote = remote\n                break\n        url = found_remote.split(\" \")[1]\n        return cls._git_remote_to_pip_url(url.strip())\n\n    @staticmethod\n    def _git_remote_to_pip_url(url: str) -> str:\n        \"\"\"\n        Convert a remote url from what git uses to what pip accepts.\n\n        There are 3 legal forms **url** may take:\n\n            1. A fully qualified url: ssh://git@example.com/foo/bar.git\n            2. A local project.git folder: /path/to/bare/repository.git\n            3. SCP shorthand for form 1: git@example.com:foo/bar.git\n\n        Form 1 is output as-is. Form 2 must be converted to URI and form 3 must\n        be converted to form 1.\n\n        See the corresponding test test_git_remote_url_to_pip() for examples of\n        sample inputs/outputs.\n        \"\"\"\n        if re.match(r\"\\w+://\", url):\n            # This is already valid. Pass it though as-is.\n            return url\n        if os.path.exists(url):\n            # A local bare remote (git clone --mirror).\n            # Needs a file:// prefix.\n            return pathlib.PurePath(url).as_uri()\n        scp_match = SCP_REGEX.match(url)\n        if scp_match:\n            # Add an ssh:// prefix and replace the ':' with a '/'.\n            return scp_match.expand(r\"ssh://\\1\\2/\\3\")\n        # Otherwise, bail out.\n        raise RemoteNotValidError(url)\n\n    @classmethod\n    def has_commit(cls, location: str, rev: str) -> bool:\n        \"\"\"\n        Check if rev is a commit that is available in the local repository.\n        \"\"\"\n        try:\n            cls.run_command(\n                [\"rev-parse\", \"-q\", \"--verify\", \"sha^\" + rev],\n                cwd=location,\n                log_failed_cmd=False,\n            )\n        except InstallationError:\n            return False\n        else:\n            return True\n\n    @classmethod\n    def get_revision(cls, location: str, rev: Optional[str] = None) -> str:\n        if rev is None:\n            rev = \"HEAD\"\n        current_rev = cls.run_command(\n            [\"rev-parse\", rev],\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        )\n        return current_rev.strip()\n\n    @classmethod\n    def get_subdirectory(cls, location: str) -> Optional[str]:\n        \"\"\"\n        Return the path to Python project root, relative to the repo root.\n        Return None if the project root is in the repo root.\n        \"\"\"\n        # find the repo root\n        git_dir = cls.run_command(\n            [\"rev-parse\", \"--git-dir\"],\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        ).strip()\n        if not os.path.isabs(git_dir):\n            git_dir = os.path.join(location, git_dir)\n        repo_root = os.path.abspath(os.path.join(git_dir, \"..\"))\n        return find_path_to_project_root_from_repo_root(location, repo_root)\n\n    @classmethod\n    def get_url_rev_and_auth(cls, url: str) -> Tuple[str, Optional[str], AuthInfo]:\n        \"\"\"\n        Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'.\n        That's required because although they use SSH they sometimes don't\n        work with a ssh:// scheme (e.g. GitHub). But we need a scheme for\n        parsing. Hence we remove it again afterwards and return it as a stub.\n        \"\"\"\n        # Works around an apparent Git bug\n        # (see https://article.gmane.org/gmane.comp.version-control.git/146500)\n        scheme, netloc, path, query, fragment = urlsplit(url)\n        if scheme.endswith(\"file\"):\n            initial_slashes = path[: -len(path.lstrip(\"/\"))]\n            newpath = initial_slashes + urllib.request.url2pathname(path).replace(\n                \"\\\\\", \"/\"\n            ).lstrip(\"/\")\n            after_plus = scheme.find(\"+\") + 1\n            url = scheme[:after_plus] + urlunsplit(\n                (scheme[after_plus:], netloc, newpath, query, fragment),\n            )\n\n        if \"://\" not in url:\n            assert \"file:\" not in url\n            url = url.replace(\"git+\", \"git+ssh://\")\n            url, rev, user_pass = super().get_url_rev_and_auth(url)\n            url = url.replace(\"ssh://\", \"\")\n        else:\n            url, rev, user_pass = super().get_url_rev_and_auth(url)\n\n        return url, rev, user_pass\n\n    @classmethod\n    def update_submodules(cls, location: str) -> None:\n        if not os.path.exists(os.path.join(location, \".gitmodules\")):\n            return\n        cls.run_command(\n            [\"submodule\", \"update\", \"--init\", \"--recursive\", \"-q\"],\n            cwd=location,\n        )\n\n    @classmethod\n    def get_repository_root(cls, location: str) -> Optional[str]:\n        loc = super().get_repository_root(location)\n        if loc:\n            return loc\n        try:\n            r = cls.run_command(\n                [\"rev-parse\", \"--show-toplevel\"],\n                cwd=location,\n                show_stdout=False,\n                stdout_only=True,\n                on_returncode=\"raise\",\n                log_failed_cmd=False,\n            )\n        except BadCommand:\n            logger.debug(\n                \"could not determine if %s is under git control \"\n                \"because git is not available\",\n                location,\n            )\n            return None\n        except InstallationError:\n            return None\n        return os.path.normpath(r.rstrip(\"\\r\\n\"))\n\n    @staticmethod\n    def should_add_vcs_url_prefix(repo_url: str) -> bool:\n        \"\"\"In either https or ssh form, requirements must be prefixed with git+.\"\"\"\n        return True\n\n\nvcs.register(Git)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/vcs/mercurial.py",
    "content": "import configparser\nimport logging\nimport os\nfrom typing import List, Optional, Tuple\n\nfrom pip._internal.exceptions import BadCommand, InstallationError\nfrom pip._internal.utils.misc import HiddenText, display_path\nfrom pip._internal.utils.subprocess import make_command\nfrom pip._internal.utils.urls import path_to_url\nfrom pip._internal.vcs.versioncontrol import (\n    RevOptions,\n    VersionControl,\n    find_path_to_project_root_from_repo_root,\n    vcs,\n)\n\nlogger = logging.getLogger(__name__)\n\n\nclass Mercurial(VersionControl):\n    name = \"hg\"\n    dirname = \".hg\"\n    repo_name = \"clone\"\n    schemes = (\n        \"hg+file\",\n        \"hg+http\",\n        \"hg+https\",\n        \"hg+ssh\",\n        \"hg+static-http\",\n    )\n\n    @staticmethod\n    def get_base_rev_args(rev: str) -> List[str]:\n        return [rev]\n\n    def fetch_new(\n        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int\n    ) -> None:\n        rev_display = rev_options.to_display()\n        logger.info(\n            \"Cloning hg %s%s to %s\",\n            url,\n            rev_display,\n            display_path(dest),\n        )\n        if verbosity <= 0:\n            flags: Tuple[str, ...] = (\"--quiet\",)\n        elif verbosity == 1:\n            flags = ()\n        elif verbosity == 2:\n            flags = (\"--verbose\",)\n        else:\n            flags = (\"--verbose\", \"--debug\")\n        self.run_command(make_command(\"clone\", \"--noupdate\", *flags, url, dest))\n        self.run_command(\n            make_command(\"update\", *flags, rev_options.to_args()),\n            cwd=dest,\n        )\n\n    def switch(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:\n        repo_config = os.path.join(dest, self.dirname, \"hgrc\")\n        config = configparser.RawConfigParser()\n        try:\n            config.read(repo_config)\n            config.set(\"paths\", \"default\", url.secret)\n            with open(repo_config, \"w\") as config_file:\n                config.write(config_file)\n        except (OSError, configparser.NoSectionError) as exc:\n            logger.warning(\"Could not switch Mercurial repository to %s: %s\", url, exc)\n        else:\n            cmd_args = make_command(\"update\", \"-q\", rev_options.to_args())\n            self.run_command(cmd_args, cwd=dest)\n\n    def update(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:\n        self.run_command([\"pull\", \"-q\"], cwd=dest)\n        cmd_args = make_command(\"update\", \"-q\", rev_options.to_args())\n        self.run_command(cmd_args, cwd=dest)\n\n    @classmethod\n    def get_remote_url(cls, location: str) -> str:\n        url = cls.run_command(\n            [\"showconfig\", \"paths.default\"],\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        ).strip()\n        if cls._is_local_repository(url):\n            url = path_to_url(url)\n        return url.strip()\n\n    @classmethod\n    def get_revision(cls, location: str) -> str:\n        \"\"\"\n        Return the repository-local changeset revision number, as an integer.\n        \"\"\"\n        current_revision = cls.run_command(\n            [\"parents\", \"--template={rev}\"],\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        ).strip()\n        return current_revision\n\n    @classmethod\n    def get_requirement_revision(cls, location: str) -> str:\n        \"\"\"\n        Return the changeset identification hash, as a 40-character\n        hexadecimal string\n        \"\"\"\n        current_rev_hash = cls.run_command(\n            [\"parents\", \"--template={node}\"],\n            show_stdout=False,\n            stdout_only=True,\n            cwd=location,\n        ).strip()\n        return current_rev_hash\n\n    @classmethod\n    def is_commit_id_equal(cls, dest: str, name: Optional[str]) -> bool:\n        \"\"\"Always assume the versions don't match\"\"\"\n        return False\n\n    @classmethod\n    def get_subdirectory(cls, location: str) -> Optional[str]:\n        \"\"\"\n        Return the path to Python project root, relative to the repo root.\n        Return None if the project root is in the repo root.\n        \"\"\"\n        # find the repo root\n        repo_root = cls.run_command(\n            [\"root\"], show_stdout=False, stdout_only=True, cwd=location\n        ).strip()\n        if not os.path.isabs(repo_root):\n            repo_root = os.path.abspath(os.path.join(location, repo_root))\n        return find_path_to_project_root_from_repo_root(location, repo_root)\n\n    @classmethod\n    def get_repository_root(cls, location: str) -> Optional[str]:\n        loc = super().get_repository_root(location)\n        if loc:\n            return loc\n        try:\n            r = cls.run_command(\n                [\"root\"],\n                cwd=location,\n                show_stdout=False,\n                stdout_only=True,\n                on_returncode=\"raise\",\n                log_failed_cmd=False,\n            )\n        except BadCommand:\n            logger.debug(\n                \"could not determine if %s is under hg control \"\n                \"because hg is not available\",\n                location,\n            )\n            return None\n        except InstallationError:\n            return None\n        return os.path.normpath(r.rstrip(\"\\r\\n\"))\n\n\nvcs.register(Mercurial)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/vcs/subversion.py",
    "content": "import logging\nimport os\nimport re\nfrom typing import List, Optional, Tuple\n\nfrom pip._internal.utils.misc import (\n    HiddenText,\n    display_path,\n    is_console_interactive,\n    is_installable_dir,\n    split_auth_from_netloc,\n)\nfrom pip._internal.utils.subprocess import CommandArgs, make_command\nfrom pip._internal.vcs.versioncontrol import (\n    AuthInfo,\n    RemoteNotFoundError,\n    RevOptions,\n    VersionControl,\n    vcs,\n)\n\nlogger = logging.getLogger(__name__)\n\n_svn_xml_url_re = re.compile('url=\"([^\"]+)\"')\n_svn_rev_re = re.compile(r'committed-rev=\"(\\d+)\"')\n_svn_info_xml_rev_re = re.compile(r'\\s*revision=\"(\\d+)\"')\n_svn_info_xml_url_re = re.compile(r\"<url>(.*)</url>\")\n\n\nclass Subversion(VersionControl):\n    name = \"svn\"\n    dirname = \".svn\"\n    repo_name = \"checkout\"\n    schemes = (\"svn+ssh\", \"svn+http\", \"svn+https\", \"svn+svn\", \"svn+file\")\n\n    @classmethod\n    def should_add_vcs_url_prefix(cls, remote_url: str) -> bool:\n        return True\n\n    @staticmethod\n    def get_base_rev_args(rev: str) -> List[str]:\n        return [\"-r\", rev]\n\n    @classmethod\n    def get_revision(cls, location: str) -> str:\n        \"\"\"\n        Return the maximum revision for all files under a given location\n        \"\"\"\n        # Note: taken from setuptools.command.egg_info\n        revision = 0\n\n        for base, dirs, _ in os.walk(location):\n            if cls.dirname not in dirs:\n                dirs[:] = []\n                continue  # no sense walking uncontrolled subdirs\n            dirs.remove(cls.dirname)\n            entries_fn = os.path.join(base, cls.dirname, \"entries\")\n            if not os.path.exists(entries_fn):\n                # FIXME: should we warn?\n                continue\n\n            dirurl, localrev = cls._get_svn_url_rev(base)\n\n            if base == location:\n                assert dirurl is not None\n                base = dirurl + \"/\"  # save the root url\n            elif not dirurl or not dirurl.startswith(base):\n                dirs[:] = []\n                continue  # not part of the same svn tree, skip it\n            revision = max(revision, localrev)\n        return str(revision)\n\n    @classmethod\n    def get_netloc_and_auth(\n        cls, netloc: str, scheme: str\n    ) -> Tuple[str, Tuple[Optional[str], Optional[str]]]:\n        \"\"\"\n        This override allows the auth information to be passed to svn via the\n        --username and --password options instead of via the URL.\n        \"\"\"\n        if scheme == \"ssh\":\n            # The --username and --password options can't be used for\n            # svn+ssh URLs, so keep the auth information in the URL.\n            return super().get_netloc_and_auth(netloc, scheme)\n\n        return split_auth_from_netloc(netloc)\n\n    @classmethod\n    def get_url_rev_and_auth(cls, url: str) -> Tuple[str, Optional[str], AuthInfo]:\n        # hotfix the URL scheme after removing svn+ from svn+ssh:// readd it\n        url, rev, user_pass = super().get_url_rev_and_auth(url)\n        if url.startswith(\"ssh://\"):\n            url = \"svn+\" + url\n        return url, rev, user_pass\n\n    @staticmethod\n    def make_rev_args(\n        username: Optional[str], password: Optional[HiddenText]\n    ) -> CommandArgs:\n        extra_args: CommandArgs = []\n        if username:\n            extra_args += [\"--username\", username]\n        if password:\n            extra_args += [\"--password\", password]\n\n        return extra_args\n\n    @classmethod\n    def get_remote_url(cls, location: str) -> str:\n        # In cases where the source is in a subdirectory, we have to look up in\n        # the location until we find a valid project root.\n        orig_location = location\n        while not is_installable_dir(location):\n            last_location = location\n            location = os.path.dirname(location)\n            if location == last_location:\n                # We've traversed up to the root of the filesystem without\n                # finding a Python project.\n                logger.warning(\n                    \"Could not find Python project for directory %s (tried all \"\n                    \"parent directories)\",\n                    orig_location,\n                )\n                raise RemoteNotFoundError\n\n        url, _rev = cls._get_svn_url_rev(location)\n        if url is None:\n            raise RemoteNotFoundError\n\n        return url\n\n    @classmethod\n    def _get_svn_url_rev(cls, location: str) -> Tuple[Optional[str], int]:\n        from pip._internal.exceptions import InstallationError\n\n        entries_path = os.path.join(location, cls.dirname, \"entries\")\n        if os.path.exists(entries_path):\n            with open(entries_path) as f:\n                data = f.read()\n        else:  # subversion >= 1.7 does not have the 'entries' file\n            data = \"\"\n\n        url = None\n        if data.startswith(\"8\") or data.startswith(\"9\") or data.startswith(\"10\"):\n            entries = list(map(str.splitlines, data.split(\"\\n\\x0c\\n\")))\n            del entries[0][0]  # get rid of the '8'\n            url = entries[0][3]\n            revs = [int(d[9]) for d in entries if len(d) > 9 and d[9]] + [0]\n        elif data.startswith(\"<?xml\"):\n            match = _svn_xml_url_re.search(data)\n            if not match:\n                raise ValueError(f\"Badly formatted data: {data!r}\")\n            url = match.group(1)  # get repository URL\n            revs = [int(m.group(1)) for m in _svn_rev_re.finditer(data)] + [0]\n        else:\n            try:\n                # subversion >= 1.7\n                # Note that using get_remote_call_options is not necessary here\n                # because `svn info` is being run against a local directory.\n                # We don't need to worry about making sure interactive mode\n                # is being used to prompt for passwords, because passwords\n                # are only potentially needed for remote server requests.\n                xml = cls.run_command(\n                    [\"info\", \"--xml\", location],\n                    show_stdout=False,\n                    stdout_only=True,\n                )\n                match = _svn_info_xml_url_re.search(xml)\n                assert match is not None\n                url = match.group(1)\n                revs = [int(m.group(1)) for m in _svn_info_xml_rev_re.finditer(xml)]\n            except InstallationError:\n                url, revs = None, []\n\n        if revs:\n            rev = max(revs)\n        else:\n            rev = 0\n\n        return url, rev\n\n    @classmethod\n    def is_commit_id_equal(cls, dest: str, name: Optional[str]) -> bool:\n        \"\"\"Always assume the versions don't match\"\"\"\n        return False\n\n    def __init__(self, use_interactive: Optional[bool] = None) -> None:\n        if use_interactive is None:\n            use_interactive = is_console_interactive()\n        self.use_interactive = use_interactive\n\n        # This member is used to cache the fetched version of the current\n        # ``svn`` client.\n        # Special value definitions:\n        #   None: Not evaluated yet.\n        #   Empty tuple: Could not parse version.\n        self._vcs_version: Optional[Tuple[int, ...]] = None\n\n        super().__init__()\n\n    def call_vcs_version(self) -> Tuple[int, ...]:\n        \"\"\"Query the version of the currently installed Subversion client.\n\n        :return: A tuple containing the parts of the version information or\n            ``()`` if the version returned from ``svn`` could not be parsed.\n        :raises: BadCommand: If ``svn`` is not installed.\n        \"\"\"\n        # Example versions:\n        #   svn, version 1.10.3 (r1842928)\n        #      compiled Feb 25 2019, 14:20:39 on x86_64-apple-darwin17.0.0\n        #   svn, version 1.7.14 (r1542130)\n        #      compiled Mar 28 2018, 08:49:13 on x86_64-pc-linux-gnu\n        #   svn, version 1.12.0-SlikSvn (SlikSvn/1.12.0)\n        #      compiled May 28 2019, 13:44:56 on x86_64-microsoft-windows6.2\n        version_prefix = \"svn, version \"\n        version = self.run_command([\"--version\"], show_stdout=False, stdout_only=True)\n        if not version.startswith(version_prefix):\n            return ()\n\n        version = version[len(version_prefix) :].split()[0]\n        version_list = version.partition(\"-\")[0].split(\".\")\n        try:\n            parsed_version = tuple(map(int, version_list))\n        except ValueError:\n            return ()\n\n        return parsed_version\n\n    def get_vcs_version(self) -> Tuple[int, ...]:\n        \"\"\"Return the version of the currently installed Subversion client.\n\n        If the version of the Subversion client has already been queried,\n        a cached value will be used.\n\n        :return: A tuple containing the parts of the version information or\n            ``()`` if the version returned from ``svn`` could not be parsed.\n        :raises: BadCommand: If ``svn`` is not installed.\n        \"\"\"\n        if self._vcs_version is not None:\n            # Use cached version, if available.\n            # If parsing the version failed previously (empty tuple),\n            # do not attempt to parse it again.\n            return self._vcs_version\n\n        vcs_version = self.call_vcs_version()\n        self._vcs_version = vcs_version\n        return vcs_version\n\n    def get_remote_call_options(self) -> CommandArgs:\n        \"\"\"Return options to be used on calls to Subversion that contact the server.\n\n        These options are applicable for the following ``svn`` subcommands used\n        in this class.\n\n            - checkout\n            - switch\n            - update\n\n        :return: A list of command line arguments to pass to ``svn``.\n        \"\"\"\n        if not self.use_interactive:\n            # --non-interactive switch is available since Subversion 0.14.4.\n            # Subversion < 1.8 runs in interactive mode by default.\n            return [\"--non-interactive\"]\n\n        svn_version = self.get_vcs_version()\n        # By default, Subversion >= 1.8 runs in non-interactive mode if\n        # stdin is not a TTY. Since that is how pip invokes SVN, in\n        # call_subprocess(), pip must pass --force-interactive to ensure\n        # the user can be prompted for a password, if required.\n        #   SVN added the --force-interactive option in SVN 1.8. Since\n        # e.g. RHEL/CentOS 7, which is supported until 2024, ships with\n        # SVN 1.7, pip should continue to support SVN 1.7. Therefore, pip\n        # can't safely add the option if the SVN version is < 1.8 (or unknown).\n        if svn_version >= (1, 8):\n            return [\"--force-interactive\"]\n\n        return []\n\n    def fetch_new(\n        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int\n    ) -> None:\n        rev_display = rev_options.to_display()\n        logger.info(\n            \"Checking out %s%s to %s\",\n            url,\n            rev_display,\n            display_path(dest),\n        )\n        if verbosity <= 0:\n            flag = \"--quiet\"\n        else:\n            flag = \"\"\n        cmd_args = make_command(\n            \"checkout\",\n            flag,\n            self.get_remote_call_options(),\n            rev_options.to_args(),\n            url,\n            dest,\n        )\n        self.run_command(cmd_args)\n\n    def switch(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:\n        cmd_args = make_command(\n            \"switch\",\n            self.get_remote_call_options(),\n            rev_options.to_args(),\n            url,\n            dest,\n        )\n        self.run_command(cmd_args)\n\n    def update(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:\n        cmd_args = make_command(\n            \"update\",\n            self.get_remote_call_options(),\n            rev_options.to_args(),\n            dest,\n        )\n        self.run_command(cmd_args)\n\n\nvcs.register(Subversion)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/vcs/versioncontrol.py",
    "content": "\"\"\"Handles all VCS (version control) support\"\"\"\n\nimport logging\nimport os\nimport shutil\nimport sys\nimport urllib.parse\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Dict,\n    Iterable,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n    Tuple,\n    Type,\n    Union,\n)\n\nfrom pip._internal.cli.spinners import SpinnerInterface\nfrom pip._internal.exceptions import BadCommand, InstallationError\nfrom pip._internal.utils.misc import (\n    HiddenText,\n    ask_path_exists,\n    backup_dir,\n    display_path,\n    hide_url,\n    hide_value,\n    is_installable_dir,\n    rmtree,\n)\nfrom pip._internal.utils.subprocess import (\n    CommandArgs,\n    call_subprocess,\n    format_command_args,\n    make_command,\n)\nfrom pip._internal.utils.urls import get_url_scheme\n\nif TYPE_CHECKING:\n    # Literal was introduced in Python 3.8.\n    #\n    # TODO: Remove `if TYPE_CHECKING` when dropping support for Python 3.7.\n    from typing import Literal\n\n\n__all__ = [\"vcs\"]\n\n\nlogger = logging.getLogger(__name__)\n\nAuthInfo = Tuple[Optional[str], Optional[str]]\n\n\ndef is_url(name: str) -> bool:\n    \"\"\"\n    Return true if the name looks like a URL.\n    \"\"\"\n    scheme = get_url_scheme(name)\n    if scheme is None:\n        return False\n    return scheme in [\"http\", \"https\", \"file\", \"ftp\"] + vcs.all_schemes\n\n\ndef make_vcs_requirement_url(\n    repo_url: str, rev: str, project_name: str, subdir: Optional[str] = None\n) -> str:\n    \"\"\"\n    Return the URL for a VCS requirement.\n\n    Args:\n      repo_url: the remote VCS url, with any needed VCS prefix (e.g. \"git+\").\n      project_name: the (unescaped) project name.\n    \"\"\"\n    egg_project_name = project_name.replace(\"-\", \"_\")\n    req = f\"{repo_url}@{rev}#egg={egg_project_name}\"\n    if subdir:\n        req += f\"&subdirectory={subdir}\"\n\n    return req\n\n\ndef find_path_to_project_root_from_repo_root(\n    location: str, repo_root: str\n) -> Optional[str]:\n    \"\"\"\n    Find the the Python project's root by searching up the filesystem from\n    `location`. Return the path to project root relative to `repo_root`.\n    Return None if the project root is `repo_root`, or cannot be found.\n    \"\"\"\n    # find project root.\n    orig_location = location\n    while not is_installable_dir(location):\n        last_location = location\n        location = os.path.dirname(location)\n        if location == last_location:\n            # We've traversed up to the root of the filesystem without\n            # finding a Python project.\n            logger.warning(\n                \"Could not find a Python project for directory %s (tried all \"\n                \"parent directories)\",\n                orig_location,\n            )\n            return None\n\n    if os.path.samefile(repo_root, location):\n        return None\n\n    return os.path.relpath(location, repo_root)\n\n\nclass RemoteNotFoundError(Exception):\n    pass\n\n\nclass RemoteNotValidError(Exception):\n    def __init__(self, url: str):\n        super().__init__(url)\n        self.url = url\n\n\nclass RevOptions:\n\n    \"\"\"\n    Encapsulates a VCS-specific revision to install, along with any VCS\n    install options.\n\n    Instances of this class should be treated as if immutable.\n    \"\"\"\n\n    def __init__(\n        self,\n        vc_class: Type[\"VersionControl\"],\n        rev: Optional[str] = None,\n        extra_args: Optional[CommandArgs] = None,\n    ) -> None:\n        \"\"\"\n        Args:\n          vc_class: a VersionControl subclass.\n          rev: the name of the revision to install.\n          extra_args: a list of extra options.\n        \"\"\"\n        if extra_args is None:\n            extra_args = []\n\n        self.extra_args = extra_args\n        self.rev = rev\n        self.vc_class = vc_class\n        self.branch_name: Optional[str] = None\n\n    def __repr__(self) -> str:\n        return f\"<RevOptions {self.vc_class.name}: rev={self.rev!r}>\"\n\n    @property\n    def arg_rev(self) -> Optional[str]:\n        if self.rev is None:\n            return self.vc_class.default_arg_rev\n\n        return self.rev\n\n    def to_args(self) -> CommandArgs:\n        \"\"\"\n        Return the VCS-specific command arguments.\n        \"\"\"\n        args: CommandArgs = []\n        rev = self.arg_rev\n        if rev is not None:\n            args += self.vc_class.get_base_rev_args(rev)\n        args += self.extra_args\n\n        return args\n\n    def to_display(self) -> str:\n        if not self.rev:\n            return \"\"\n\n        return f\" (to revision {self.rev})\"\n\n    def make_new(self, rev: str) -> \"RevOptions\":\n        \"\"\"\n        Make a copy of the current instance, but with a new rev.\n\n        Args:\n          rev: the name of the revision for the new object.\n        \"\"\"\n        return self.vc_class.make_rev_options(rev, extra_args=self.extra_args)\n\n\nclass VcsSupport:\n    _registry: Dict[str, \"VersionControl\"] = {}\n    schemes = [\"ssh\", \"git\", \"hg\", \"bzr\", \"sftp\", \"svn\"]\n\n    def __init__(self) -> None:\n        # Register more schemes with urlparse for various version control\n        # systems\n        urllib.parse.uses_netloc.extend(self.schemes)\n        super().__init__()\n\n    def __iter__(self) -> Iterator[str]:\n        return self._registry.__iter__()\n\n    @property\n    def backends(self) -> List[\"VersionControl\"]:\n        return list(self._registry.values())\n\n    @property\n    def dirnames(self) -> List[str]:\n        return [backend.dirname for backend in self.backends]\n\n    @property\n    def all_schemes(self) -> List[str]:\n        schemes: List[str] = []\n        for backend in self.backends:\n            schemes.extend(backend.schemes)\n        return schemes\n\n    def register(self, cls: Type[\"VersionControl\"]) -> None:\n        if not hasattr(cls, \"name\"):\n            logger.warning(\"Cannot register VCS %s\", cls.__name__)\n            return\n        if cls.name not in self._registry:\n            self._registry[cls.name] = cls()\n            logger.debug(\"Registered VCS backend: %s\", cls.name)\n\n    def unregister(self, name: str) -> None:\n        if name in self._registry:\n            del self._registry[name]\n\n    def get_backend_for_dir(self, location: str) -> Optional[\"VersionControl\"]:\n        \"\"\"\n        Return a VersionControl object if a repository of that type is found\n        at the given directory.\n        \"\"\"\n        vcs_backends = {}\n        for vcs_backend in self._registry.values():\n            repo_path = vcs_backend.get_repository_root(location)\n            if not repo_path:\n                continue\n            logger.debug(\"Determine that %s uses VCS: %s\", location, vcs_backend.name)\n            vcs_backends[repo_path] = vcs_backend\n\n        if not vcs_backends:\n            return None\n\n        # Choose the VCS in the inner-most directory. Since all repository\n        # roots found here would be either `location` or one of its\n        # parents, the longest path should have the most path components,\n        # i.e. the backend representing the inner-most repository.\n        inner_most_repo_path = max(vcs_backends, key=len)\n        return vcs_backends[inner_most_repo_path]\n\n    def get_backend_for_scheme(self, scheme: str) -> Optional[\"VersionControl\"]:\n        \"\"\"\n        Return a VersionControl object or None.\n        \"\"\"\n        for vcs_backend in self._registry.values():\n            if scheme in vcs_backend.schemes:\n                return vcs_backend\n        return None\n\n    def get_backend(self, name: str) -> Optional[\"VersionControl\"]:\n        \"\"\"\n        Return a VersionControl object or None.\n        \"\"\"\n        name = name.lower()\n        return self._registry.get(name)\n\n\nvcs = VcsSupport()\n\n\nclass VersionControl:\n    name = \"\"\n    dirname = \"\"\n    repo_name = \"\"\n    # List of supported schemes for this Version Control\n    schemes: Tuple[str, ...] = ()\n    # Iterable of environment variable names to pass to call_subprocess().\n    unset_environ: Tuple[str, ...] = ()\n    default_arg_rev: Optional[str] = None\n\n    @classmethod\n    def should_add_vcs_url_prefix(cls, remote_url: str) -> bool:\n        \"\"\"\n        Return whether the vcs prefix (e.g. \"git+\") should be added to a\n        repository's remote url when used in a requirement.\n        \"\"\"\n        return not remote_url.lower().startswith(f\"{cls.name}:\")\n\n    @classmethod\n    def get_subdirectory(cls, location: str) -> Optional[str]:\n        \"\"\"\n        Return the path to Python project root, relative to the repo root.\n        Return None if the project root is in the repo root.\n        \"\"\"\n        return None\n\n    @classmethod\n    def get_requirement_revision(cls, repo_dir: str) -> str:\n        \"\"\"\n        Return the revision string that should be used in a requirement.\n        \"\"\"\n        return cls.get_revision(repo_dir)\n\n    @classmethod\n    def get_src_requirement(cls, repo_dir: str, project_name: str) -> str:\n        \"\"\"\n        Return the requirement string to use to redownload the files\n        currently at the given repository directory.\n\n        Args:\n          project_name: the (unescaped) project name.\n\n        The return value has a form similar to the following:\n\n            {repository_url}@{revision}#egg={project_name}\n        \"\"\"\n        repo_url = cls.get_remote_url(repo_dir)\n\n        if cls.should_add_vcs_url_prefix(repo_url):\n            repo_url = f\"{cls.name}+{repo_url}\"\n\n        revision = cls.get_requirement_revision(repo_dir)\n        subdir = cls.get_subdirectory(repo_dir)\n        req = make_vcs_requirement_url(repo_url, revision, project_name, subdir=subdir)\n\n        return req\n\n    @staticmethod\n    def get_base_rev_args(rev: str) -> List[str]:\n        \"\"\"\n        Return the base revision arguments for a vcs command.\n\n        Args:\n          rev: the name of a revision to install.  Cannot be None.\n        \"\"\"\n        raise NotImplementedError\n\n    def is_immutable_rev_checkout(self, url: str, dest: str) -> bool:\n        \"\"\"\n        Return true if the commit hash checked out at dest matches\n        the revision in url.\n\n        Always return False, if the VCS does not support immutable commit\n        hashes.\n\n        This method does not check if there are local uncommitted changes\n        in dest after checkout, as pip currently has no use case for that.\n        \"\"\"\n        return False\n\n    @classmethod\n    def make_rev_options(\n        cls, rev: Optional[str] = None, extra_args: Optional[CommandArgs] = None\n    ) -> RevOptions:\n        \"\"\"\n        Return a RevOptions object.\n\n        Args:\n          rev: the name of a revision to install.\n          extra_args: a list of extra options.\n        \"\"\"\n        return RevOptions(cls, rev, extra_args=extra_args)\n\n    @classmethod\n    def _is_local_repository(cls, repo: str) -> bool:\n        \"\"\"\n        posix absolute paths start with os.path.sep,\n        win32 ones start with drive (like c:\\\\folder)\n        \"\"\"\n        drive, tail = os.path.splitdrive(repo)\n        return repo.startswith(os.path.sep) or bool(drive)\n\n    @classmethod\n    def get_netloc_and_auth(\n        cls, netloc: str, scheme: str\n    ) -> Tuple[str, Tuple[Optional[str], Optional[str]]]:\n        \"\"\"\n        Parse the repository URL's netloc, and return the new netloc to use\n        along with auth information.\n\n        Args:\n          netloc: the original repository URL netloc.\n          scheme: the repository URL's scheme without the vcs prefix.\n\n        This is mainly for the Subversion class to override, so that auth\n        information can be provided via the --username and --password options\n        instead of through the URL.  For other subclasses like Git without\n        such an option, auth information must stay in the URL.\n\n        Returns: (netloc, (username, password)).\n        \"\"\"\n        return netloc, (None, None)\n\n    @classmethod\n    def get_url_rev_and_auth(cls, url: str) -> Tuple[str, Optional[str], AuthInfo]:\n        \"\"\"\n        Parse the repository URL to use, and return the URL, revision,\n        and auth info to use.\n\n        Returns: (url, rev, (username, password)).\n        \"\"\"\n        scheme, netloc, path, query, frag = urllib.parse.urlsplit(url)\n        if \"+\" not in scheme:\n            raise ValueError(\n                \"Sorry, {!r} is a malformed VCS url. \"\n                \"The format is <vcs>+<protocol>://<url>, \"\n                \"e.g. svn+http://myrepo/svn/MyApp#egg=MyApp\".format(url)\n            )\n        # Remove the vcs prefix.\n        scheme = scheme.split(\"+\", 1)[1]\n        netloc, user_pass = cls.get_netloc_and_auth(netloc, scheme)\n        rev = None\n        if \"@\" in path:\n            path, rev = path.rsplit(\"@\", 1)\n            if not rev:\n                raise InstallationError(\n                    \"The URL {!r} has an empty revision (after @) \"\n                    \"which is not supported. Include a revision after @ \"\n                    \"or remove @ from the URL.\".format(url)\n                )\n        url = urllib.parse.urlunsplit((scheme, netloc, path, query, \"\"))\n        return url, rev, user_pass\n\n    @staticmethod\n    def make_rev_args(\n        username: Optional[str], password: Optional[HiddenText]\n    ) -> CommandArgs:\n        \"\"\"\n        Return the RevOptions \"extra arguments\" to use in obtain().\n        \"\"\"\n        return []\n\n    def get_url_rev_options(self, url: HiddenText) -> Tuple[HiddenText, RevOptions]:\n        \"\"\"\n        Return the URL and RevOptions object to use in obtain(),\n        as a tuple (url, rev_options).\n        \"\"\"\n        secret_url, rev, user_pass = self.get_url_rev_and_auth(url.secret)\n        username, secret_password = user_pass\n        password: Optional[HiddenText] = None\n        if secret_password is not None:\n            password = hide_value(secret_password)\n        extra_args = self.make_rev_args(username, password)\n        rev_options = self.make_rev_options(rev, extra_args=extra_args)\n\n        return hide_url(secret_url), rev_options\n\n    @staticmethod\n    def normalize_url(url: str) -> str:\n        \"\"\"\n        Normalize a URL for comparison by unquoting it and removing any\n        trailing slash.\n        \"\"\"\n        return urllib.parse.unquote(url).rstrip(\"/\")\n\n    @classmethod\n    def compare_urls(cls, url1: str, url2: str) -> bool:\n        \"\"\"\n        Compare two repo URLs for identity, ignoring incidental differences.\n        \"\"\"\n        return cls.normalize_url(url1) == cls.normalize_url(url2)\n\n    def fetch_new(\n        self, dest: str, url: HiddenText, rev_options: RevOptions, verbosity: int\n    ) -> None:\n        \"\"\"\n        Fetch a revision from a repository, in the case that this is the\n        first fetch from the repository.\n\n        Args:\n          dest: the directory to fetch the repository to.\n          rev_options: a RevOptions object.\n          verbosity: verbosity level.\n        \"\"\"\n        raise NotImplementedError\n\n    def switch(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:\n        \"\"\"\n        Switch the repo at ``dest`` to point to ``URL``.\n\n        Args:\n          rev_options: a RevOptions object.\n        \"\"\"\n        raise NotImplementedError\n\n    def update(self, dest: str, url: HiddenText, rev_options: RevOptions) -> None:\n        \"\"\"\n        Update an already-existing repo to the given ``rev_options``.\n\n        Args:\n          rev_options: a RevOptions object.\n        \"\"\"\n        raise NotImplementedError\n\n    @classmethod\n    def is_commit_id_equal(cls, dest: str, name: Optional[str]) -> bool:\n        \"\"\"\n        Return whether the id of the current commit equals the given name.\n\n        Args:\n          dest: the repository directory.\n          name: a string name.\n        \"\"\"\n        raise NotImplementedError\n\n    def obtain(self, dest: str, url: HiddenText, verbosity: int) -> None:\n        \"\"\"\n        Install or update in editable mode the package represented by this\n        VersionControl object.\n\n        :param dest: the repository directory in which to install or update.\n        :param url: the repository URL starting with a vcs prefix.\n        :param verbosity: verbosity level.\n        \"\"\"\n        url, rev_options = self.get_url_rev_options(url)\n\n        if not os.path.exists(dest):\n            self.fetch_new(dest, url, rev_options, verbosity=verbosity)\n            return\n\n        rev_display = rev_options.to_display()\n        if self.is_repository_directory(dest):\n            existing_url = self.get_remote_url(dest)\n            if self.compare_urls(existing_url, url.secret):\n                logger.debug(\n                    \"%s in %s exists, and has correct URL (%s)\",\n                    self.repo_name.title(),\n                    display_path(dest),\n                    url,\n                )\n                if not self.is_commit_id_equal(dest, rev_options.rev):\n                    logger.info(\n                        \"Updating %s %s%s\",\n                        display_path(dest),\n                        self.repo_name,\n                        rev_display,\n                    )\n                    self.update(dest, url, rev_options)\n                else:\n                    logger.info(\"Skipping because already up-to-date.\")\n                return\n\n            logger.warning(\n                \"%s %s in %s exists with URL %s\",\n                self.name,\n                self.repo_name,\n                display_path(dest),\n                existing_url,\n            )\n            prompt = (\"(s)witch, (i)gnore, (w)ipe, (b)ackup \", (\"s\", \"i\", \"w\", \"b\"))\n        else:\n            logger.warning(\n                \"Directory %s already exists, and is not a %s %s.\",\n                dest,\n                self.name,\n                self.repo_name,\n            )\n            # https://github.com/python/mypy/issues/1174\n            prompt = (\"(i)gnore, (w)ipe, (b)ackup \", (\"i\", \"w\", \"b\"))  # type: ignore\n\n        logger.warning(\n            \"The plan is to install the %s repository %s\",\n            self.name,\n            url,\n        )\n        response = ask_path_exists(\"What to do?  {}\".format(prompt[0]), prompt[1])\n\n        if response == \"a\":\n            sys.exit(-1)\n\n        if response == \"w\":\n            logger.warning(\"Deleting %s\", display_path(dest))\n            rmtree(dest)\n            self.fetch_new(dest, url, rev_options, verbosity=verbosity)\n            return\n\n        if response == \"b\":\n            dest_dir = backup_dir(dest)\n            logger.warning(\"Backing up %s to %s\", display_path(dest), dest_dir)\n            shutil.move(dest, dest_dir)\n            self.fetch_new(dest, url, rev_options, verbosity=verbosity)\n            return\n\n        # Do nothing if the response is \"i\".\n        if response == \"s\":\n            logger.info(\n                \"Switching %s %s to %s%s\",\n                self.repo_name,\n                display_path(dest),\n                url,\n                rev_display,\n            )\n            self.switch(dest, url, rev_options)\n\n    def unpack(self, location: str, url: HiddenText, verbosity: int) -> None:\n        \"\"\"\n        Clean up current location and download the url repository\n        (and vcs infos) into location\n\n        :param url: the repository URL starting with a vcs prefix.\n        :param verbosity: verbosity level.\n        \"\"\"\n        if os.path.exists(location):\n            rmtree(location)\n        self.obtain(location, url=url, verbosity=verbosity)\n\n    @classmethod\n    def get_remote_url(cls, location: str) -> str:\n        \"\"\"\n        Return the url used at location\n\n        Raises RemoteNotFoundError if the repository does not have a remote\n        url configured.\n        \"\"\"\n        raise NotImplementedError\n\n    @classmethod\n    def get_revision(cls, location: str) -> str:\n        \"\"\"\n        Return the current commit id of the files at the given location.\n        \"\"\"\n        raise NotImplementedError\n\n    @classmethod\n    def run_command(\n        cls,\n        cmd: Union[List[str], CommandArgs],\n        show_stdout: bool = True,\n        cwd: Optional[str] = None,\n        on_returncode: 'Literal[\"raise\", \"warn\", \"ignore\"]' = \"raise\",\n        extra_ok_returncodes: Optional[Iterable[int]] = None,\n        command_desc: Optional[str] = None,\n        extra_environ: Optional[Mapping[str, Any]] = None,\n        spinner: Optional[SpinnerInterface] = None,\n        log_failed_cmd: bool = True,\n        stdout_only: bool = False,\n    ) -> str:\n        \"\"\"\n        Run a VCS subcommand\n        This is simply a wrapper around call_subprocess that adds the VCS\n        command name, and checks that the VCS is available\n        \"\"\"\n        cmd = make_command(cls.name, *cmd)\n        if command_desc is None:\n            command_desc = format_command_args(cmd)\n        try:\n            return call_subprocess(\n                cmd,\n                show_stdout,\n                cwd,\n                on_returncode=on_returncode,\n                extra_ok_returncodes=extra_ok_returncodes,\n                command_desc=command_desc,\n                extra_environ=extra_environ,\n                unset_environ=cls.unset_environ,\n                spinner=spinner,\n                log_failed_cmd=log_failed_cmd,\n                stdout_only=stdout_only,\n            )\n        except FileNotFoundError:\n            # errno.ENOENT = no such file or directory\n            # In other words, the VCS executable isn't available\n            raise BadCommand(\n                f\"Cannot find command {cls.name!r} - do you have \"\n                f\"{cls.name!r} installed and in your PATH?\"\n            )\n        except PermissionError:\n            # errno.EACCES = Permission denied\n            # This error occurs, for instance, when the command is installed\n            # only for another user. So, the current user don't have\n            # permission to call the other user command.\n            raise BadCommand(\n                f\"No permission to execute {cls.name!r} - install it \"\n                f\"locally, globally (ask admin), or check your PATH. \"\n                f\"See possible solutions at \"\n                f\"https://pip.pypa.io/en/latest/reference/pip_freeze/\"\n                f\"#fixing-permission-denied.\"\n            )\n\n    @classmethod\n    def is_repository_directory(cls, path: str) -> bool:\n        \"\"\"\n        Return whether a directory path is a repository directory.\n        \"\"\"\n        logger.debug(\"Checking in %s for %s (%s)...\", path, cls.dirname, cls.name)\n        return os.path.exists(os.path.join(path, cls.dirname))\n\n    @classmethod\n    def get_repository_root(cls, location: str) -> Optional[str]:\n        \"\"\"\n        Return the \"root\" (top-level) directory controlled by the vcs,\n        or `None` if the directory is not in any.\n\n        It is meant to be overridden to implement smarter detection\n        mechanisms for specific vcs.\n\n        This can do more than is_repository_directory() alone. For\n        example, the Git override checks that Git is actually available.\n        \"\"\"\n        if cls.is_repository_directory(location):\n            return location\n        return None\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_internal/wheel_builder.py",
    "content": "\"\"\"Orchestrator for building wheels from InstallRequirements.\n\"\"\"\n\nimport logging\nimport os.path\nimport re\nimport shutil\nfrom typing import Callable, Iterable, List, Optional, Tuple\n\nfrom pip._vendor.packaging.utils import canonicalize_name, canonicalize_version\nfrom pip._vendor.packaging.version import InvalidVersion, Version\n\nfrom pip._internal.cache import WheelCache\nfrom pip._internal.exceptions import InvalidWheelFilename, UnsupportedWheel\nfrom pip._internal.metadata import FilesystemWheel, get_wheel_distribution\nfrom pip._internal.models.link import Link\nfrom pip._internal.models.wheel import Wheel\nfrom pip._internal.operations.build.wheel import build_wheel_pep517\nfrom pip._internal.operations.build.wheel_editable import build_wheel_editable\nfrom pip._internal.operations.build.wheel_legacy import build_wheel_legacy\nfrom pip._internal.req.req_install import InstallRequirement\nfrom pip._internal.utils.deprecation import (\n    LegacyInstallReasonMissingWheelPackage,\n    LegacyInstallReasonNoBinaryForcesSetuptoolsInstall,\n)\nfrom pip._internal.utils.logging import indent_log\nfrom pip._internal.utils.misc import ensure_dir, hash_file, is_wheel_installed\nfrom pip._internal.utils.setuptools_build import make_setuptools_clean_args\nfrom pip._internal.utils.subprocess import call_subprocess\nfrom pip._internal.utils.temp_dir import TempDirectory\nfrom pip._internal.utils.urls import path_to_url\nfrom pip._internal.vcs import vcs\n\nlogger = logging.getLogger(__name__)\n\n_egg_info_re = re.compile(r\"([a-z0-9_.]+)-([a-z0-9_.!+-]+)\", re.IGNORECASE)\n\nBdistWheelAllowedPredicate = Callable[[InstallRequirement], bool]\nBuildResult = Tuple[List[InstallRequirement], List[InstallRequirement]]\n\n\ndef _contains_egg_info(s: str) -> bool:\n    \"\"\"Determine whether the string looks like an egg_info.\n\n    :param s: The string to parse. E.g. foo-2.1\n    \"\"\"\n    return bool(_egg_info_re.search(s))\n\n\ndef _should_build(\n    req: InstallRequirement,\n    need_wheel: bool,\n    check_bdist_wheel: Optional[BdistWheelAllowedPredicate] = None,\n) -> bool:\n    \"\"\"Return whether an InstallRequirement should be built into a wheel.\"\"\"\n    if req.constraint:\n        # never build requirements that are merely constraints\n        return False\n    if req.is_wheel:\n        if need_wheel:\n            logger.info(\n                \"Skipping %s, due to already being wheel.\",\n                req.name,\n            )\n        return False\n\n    if need_wheel:\n        # i.e. pip wheel, not pip install\n        return True\n\n    # From this point, this concerns the pip install command only\n    # (need_wheel=False).\n\n    if not req.source_dir:\n        return False\n\n    if req.editable:\n        # we only build PEP 660 editable requirements\n        return req.supports_pyproject_editable()\n\n    if req.use_pep517:\n        return True\n\n    assert check_bdist_wheel is not None\n    if not check_bdist_wheel(req):\n        # /!\\ When we change this to unconditionally return True, we must also remove\n        # support for `--install-option`. Indeed, `--install-option` implies\n        # `--no-binary` so we can return False here and run `setup.py install`.\n        # `--global-option` and `--build-option` can remain until we drop support for\n        # building with `setup.py bdist_wheel`.\n        req.legacy_install_reason = LegacyInstallReasonNoBinaryForcesSetuptoolsInstall\n        return False\n\n    if not is_wheel_installed():\n        # we don't build legacy requirements if wheel is not installed\n        req.legacy_install_reason = LegacyInstallReasonMissingWheelPackage\n        return False\n\n    return True\n\n\ndef should_build_for_wheel_command(\n    req: InstallRequirement,\n) -> bool:\n    return _should_build(req, need_wheel=True)\n\n\ndef should_build_for_install_command(\n    req: InstallRequirement,\n    check_bdist_wheel_allowed: BdistWheelAllowedPredicate,\n) -> bool:\n    return _should_build(\n        req, need_wheel=False, check_bdist_wheel=check_bdist_wheel_allowed\n    )\n\n\ndef _should_cache(\n    req: InstallRequirement,\n) -> Optional[bool]:\n    \"\"\"\n    Return whether a built InstallRequirement can be stored in the persistent\n    wheel cache, assuming the wheel cache is available, and _should_build()\n    has determined a wheel needs to be built.\n    \"\"\"\n    if req.editable or not req.source_dir:\n        # never cache editable requirements\n        return False\n\n    if req.link and req.link.is_vcs:\n        # VCS checkout. Do not cache\n        # unless it points to an immutable commit hash.\n        assert not req.editable\n        assert req.source_dir\n        vcs_backend = vcs.get_backend_for_scheme(req.link.scheme)\n        assert vcs_backend\n        if vcs_backend.is_immutable_rev_checkout(req.link.url, req.source_dir):\n            return True\n        return False\n\n    assert req.link\n    base, ext = req.link.splitext()\n    if _contains_egg_info(base):\n        return True\n\n    # Otherwise, do not cache.\n    return False\n\n\ndef _get_cache_dir(\n    req: InstallRequirement,\n    wheel_cache: WheelCache,\n) -> str:\n    \"\"\"Return the persistent or temporary cache directory where the built\n    wheel need to be stored.\n    \"\"\"\n    cache_available = bool(wheel_cache.cache_dir)\n    assert req.link\n    if cache_available and _should_cache(req):\n        cache_dir = wheel_cache.get_path_for_link(req.link)\n    else:\n        cache_dir = wheel_cache.get_ephem_path_for_link(req.link)\n    return cache_dir\n\n\ndef _verify_one(req: InstallRequirement, wheel_path: str) -> None:\n    canonical_name = canonicalize_name(req.name or \"\")\n    w = Wheel(os.path.basename(wheel_path))\n    if canonicalize_name(w.name) != canonical_name:\n        raise InvalidWheelFilename(\n            \"Wheel has unexpected file name: expected {!r}, \"\n            \"got {!r}\".format(canonical_name, w.name),\n        )\n    dist = get_wheel_distribution(FilesystemWheel(wheel_path), canonical_name)\n    dist_verstr = str(dist.version)\n    if canonicalize_version(dist_verstr) != canonicalize_version(w.version):\n        raise InvalidWheelFilename(\n            \"Wheel has unexpected file name: expected {!r}, \"\n            \"got {!r}\".format(dist_verstr, w.version),\n        )\n    metadata_version_value = dist.metadata_version\n    if metadata_version_value is None:\n        raise UnsupportedWheel(\"Missing Metadata-Version\")\n    try:\n        metadata_version = Version(metadata_version_value)\n    except InvalidVersion:\n        msg = f\"Invalid Metadata-Version: {metadata_version_value}\"\n        raise UnsupportedWheel(msg)\n    if metadata_version >= Version(\"1.2\") and not isinstance(dist.version, Version):\n        raise UnsupportedWheel(\n            \"Metadata 1.2 mandates PEP 440 version, \"\n            \"but {!r} is not\".format(dist_verstr)\n        )\n\n\ndef _build_one(\n    req: InstallRequirement,\n    output_dir: str,\n    verify: bool,\n    build_options: List[str],\n    global_options: List[str],\n    editable: bool,\n) -> Optional[str]:\n    \"\"\"Build one wheel.\n\n    :return: The filename of the built wheel, or None if the build failed.\n    \"\"\"\n    artifact = \"editable\" if editable else \"wheel\"\n    try:\n        ensure_dir(output_dir)\n    except OSError as e:\n        logger.warning(\n            \"Building %s for %s failed: %s\",\n            artifact,\n            req.name,\n            e,\n        )\n        return None\n\n    # Install build deps into temporary directory (PEP 518)\n    with req.build_env:\n        wheel_path = _build_one_inside_env(\n            req, output_dir, build_options, global_options, editable\n        )\n    if wheel_path and verify:\n        try:\n            _verify_one(req, wheel_path)\n        except (InvalidWheelFilename, UnsupportedWheel) as e:\n            logger.warning(\"Built %s for %s is invalid: %s\", artifact, req.name, e)\n            return None\n    return wheel_path\n\n\ndef _build_one_inside_env(\n    req: InstallRequirement,\n    output_dir: str,\n    build_options: List[str],\n    global_options: List[str],\n    editable: bool,\n) -> Optional[str]:\n    with TempDirectory(kind=\"wheel\") as temp_dir:\n        assert req.name\n        if req.use_pep517:\n            assert req.metadata_directory\n            assert req.pep517_backend\n            if global_options:\n                logger.warning(\n                    \"Ignoring --global-option when building %s using PEP 517\", req.name\n                )\n            if build_options:\n                logger.warning(\n                    \"Ignoring --build-option when building %s using PEP 517\", req.name\n                )\n            if editable:\n                wheel_path = build_wheel_editable(\n                    name=req.name,\n                    backend=req.pep517_backend,\n                    metadata_directory=req.metadata_directory,\n                    tempd=temp_dir.path,\n                )\n            else:\n                wheel_path = build_wheel_pep517(\n                    name=req.name,\n                    backend=req.pep517_backend,\n                    metadata_directory=req.metadata_directory,\n                    tempd=temp_dir.path,\n                )\n        else:\n            wheel_path = build_wheel_legacy(\n                name=req.name,\n                setup_py_path=req.setup_py_path,\n                source_dir=req.unpacked_source_directory,\n                global_options=global_options,\n                build_options=build_options,\n                tempd=temp_dir.path,\n            )\n\n        if wheel_path is not None:\n            wheel_name = os.path.basename(wheel_path)\n            dest_path = os.path.join(output_dir, wheel_name)\n            try:\n                wheel_hash, length = hash_file(wheel_path)\n                shutil.move(wheel_path, dest_path)\n                logger.info(\n                    \"Created wheel for %s: filename=%s size=%d sha256=%s\",\n                    req.name,\n                    wheel_name,\n                    length,\n                    wheel_hash.hexdigest(),\n                )\n                logger.info(\"Stored in directory: %s\", output_dir)\n                return dest_path\n            except Exception as e:\n                logger.warning(\n                    \"Building wheel for %s failed: %s\",\n                    req.name,\n                    e,\n                )\n        # Ignore return, we can't do anything else useful.\n        if not req.use_pep517:\n            _clean_one_legacy(req, global_options)\n        return None\n\n\ndef _clean_one_legacy(req: InstallRequirement, global_options: List[str]) -> bool:\n    clean_args = make_setuptools_clean_args(\n        req.setup_py_path,\n        global_options=global_options,\n    )\n\n    logger.info(\"Running setup.py clean for %s\", req.name)\n    try:\n        call_subprocess(\n            clean_args, command_desc=\"python setup.py clean\", cwd=req.source_dir\n        )\n        return True\n    except Exception:\n        logger.error(\"Failed cleaning build dir for %s\", req.name)\n        return False\n\n\ndef build(\n    requirements: Iterable[InstallRequirement],\n    wheel_cache: WheelCache,\n    verify: bool,\n    build_options: List[str],\n    global_options: List[str],\n) -> BuildResult:\n    \"\"\"Build wheels.\n\n    :return: The list of InstallRequirement that succeeded to build and\n        the list of InstallRequirement that failed to build.\n    \"\"\"\n    if not requirements:\n        return [], []\n\n    # Build the wheels.\n    logger.info(\n        \"Building wheels for collected packages: %s\",\n        \", \".join(req.name for req in requirements),  # type: ignore\n    )\n\n    with indent_log():\n        build_successes, build_failures = [], []\n        for req in requirements:\n            assert req.name\n            cache_dir = _get_cache_dir(req, wheel_cache)\n            wheel_file = _build_one(\n                req,\n                cache_dir,\n                verify,\n                build_options,\n                global_options,\n                req.editable and req.permit_editable_wheels,\n            )\n            if wheel_file:\n                # Record the download origin in the cache\n                if req.download_info is not None:\n                    # download_info is guaranteed to be set because when we build an\n                    # InstallRequirement it has been through the preparer before, but\n                    # let's be cautious.\n                    wheel_cache.record_download_origin(cache_dir, req.download_info)\n                # Update the link for this.\n                req.link = Link(path_to_url(wheel_file))\n                req.local_file_path = req.link.file_path\n                assert req.link.is_wheel\n                build_successes.append(req)\n            else:\n                build_failures.append(req)\n\n    # notify success/failure\n    if build_successes:\n        logger.info(\n            \"Successfully built %s\",\n            \" \".join([req.name for req in build_successes]),  # type: ignore\n        )\n    if build_failures:\n        logger.info(\n            \"Failed to build %s\",\n            \" \".join([req.name for req in build_failures]),  # type: ignore\n        )\n    # Return a list of requirements that failed to build\n    return build_successes, build_failures\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/__init__.py",
    "content": "\"\"\"\npip._vendor is for vendoring dependencies of pip to prevent needing pip to\ndepend on something external.\n\nFiles inside of pip._vendor should be considered immutable and should only be\nupdated to versions from upstream.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport glob\nimport os.path\nimport sys\n\n# Downstream redistributors which have debundled our dependencies should also\n# patch this value to be true. This will trigger the additional patching\n# to cause things like \"six\" to be available as pip.\nDEBUNDLED = False\n\n# By default, look in this directory for a bunch of .whl files which we will\n# add to the beginning of sys.path before attempting to import anything. This\n# is done to support downstream re-distributors like Debian and Fedora who\n# wish to create their own Wheels for our dependencies to aid in debundling.\nWHEEL_DIR = os.path.abspath(os.path.dirname(__file__))\n\n\n# Define a small helper function to alias our vendored modules to the real ones\n# if the vendored ones do not exist. This idea of this was taken from\n# https://github.com/kennethreitz/requests/pull/2567.\ndef vendored(modulename):\n    vendored_name = \"{0}.{1}\".format(__name__, modulename)\n\n    try:\n        __import__(modulename, globals(), locals(), level=0)\n    except ImportError:\n        # We can just silently allow import failures to pass here. If we\n        # got to this point it means that ``import pip._vendor.whatever``\n        # failed and so did ``import whatever``. Since we're importing this\n        # upfront in an attempt to alias imports, not erroring here will\n        # just mean we get a regular import error whenever pip *actually*\n        # tries to import one of these modules to use it, which actually\n        # gives us a better error message than we would have otherwise\n        # gotten.\n        pass\n    else:\n        sys.modules[vendored_name] = sys.modules[modulename]\n        base, head = vendored_name.rsplit(\".\", 1)\n        setattr(sys.modules[base], head, sys.modules[modulename])\n\n\n# If we're operating in a debundled setup, then we want to go ahead and trigger\n# the aliasing of our vendored libraries as well as looking for wheels to add\n# to our sys.path. This will cause all of this code to be a no-op typically\n# however downstream redistributors can enable it in a consistent way across\n# all platforms.\nif DEBUNDLED:\n    # Actually look inside of WHEEL_DIR to find .whl files and add them to the\n    # front of our sys.path.\n    sys.path[:] = glob.glob(os.path.join(WHEEL_DIR, \"*.whl\")) + sys.path\n\n    # Actually alias all of our vendored dependencies.\n    vendored(\"cachecontrol\")\n    vendored(\"certifi\")\n    vendored(\"colorama\")\n    vendored(\"distlib\")\n    vendored(\"distro\")\n    vendored(\"six\")\n    vendored(\"six.moves\")\n    vendored(\"six.moves.urllib\")\n    vendored(\"six.moves.urllib.parse\")\n    vendored(\"packaging\")\n    vendored(\"packaging.version\")\n    vendored(\"packaging.specifiers\")\n    vendored(\"pep517\")\n    vendored(\"pkg_resources\")\n    vendored(\"platformdirs\")\n    vendored(\"progress\")\n    vendored(\"requests\")\n    vendored(\"requests.exceptions\")\n    vendored(\"requests.packages\")\n    vendored(\"requests.packages.urllib3\")\n    vendored(\"requests.packages.urllib3._collections\")\n    vendored(\"requests.packages.urllib3.connection\")\n    vendored(\"requests.packages.urllib3.connectionpool\")\n    vendored(\"requests.packages.urllib3.contrib\")\n    vendored(\"requests.packages.urllib3.contrib.ntlmpool\")\n    vendored(\"requests.packages.urllib3.contrib.pyopenssl\")\n    vendored(\"requests.packages.urllib3.exceptions\")\n    vendored(\"requests.packages.urllib3.fields\")\n    vendored(\"requests.packages.urllib3.filepost\")\n    vendored(\"requests.packages.urllib3.packages\")\n    vendored(\"requests.packages.urllib3.packages.ordered_dict\")\n    vendored(\"requests.packages.urllib3.packages.six\")\n    vendored(\"requests.packages.urllib3.packages.ssl_match_hostname\")\n    vendored(\"requests.packages.urllib3.packages.ssl_match_hostname.\"\n             \"_implementation\")\n    vendored(\"requests.packages.urllib3.poolmanager\")\n    vendored(\"requests.packages.urllib3.request\")\n    vendored(\"requests.packages.urllib3.response\")\n    vendored(\"requests.packages.urllib3.util\")\n    vendored(\"requests.packages.urllib3.util.connection\")\n    vendored(\"requests.packages.urllib3.util.request\")\n    vendored(\"requests.packages.urllib3.util.response\")\n    vendored(\"requests.packages.urllib3.util.retry\")\n    vendored(\"requests.packages.urllib3.util.ssl_\")\n    vendored(\"requests.packages.urllib3.util.timeout\")\n    vendored(\"requests.packages.urllib3.util.url\")\n    vendored(\"resolvelib\")\n    vendored(\"rich\")\n    vendored(\"rich.console\")\n    vendored(\"rich.highlighter\")\n    vendored(\"rich.logging\")\n    vendored(\"rich.markup\")\n    vendored(\"rich.progress\")\n    vendored(\"rich.segment\")\n    vendored(\"rich.style\")\n    vendored(\"rich.text\")\n    vendored(\"rich.traceback\")\n    vendored(\"tenacity\")\n    vendored(\"tomli\")\n    vendored(\"urllib3\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/cachecontrol/__init__.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"CacheControl import Interface.\n\nMake it easy to import from cachecontrol without long namespaces.\n\"\"\"\n__author__ = \"Eric Larson\"\n__email__ = \"eric@ionrock.org\"\n__version__ = \"0.12.11\"\n\nfrom .wrapper import CacheControl\nfrom .adapter import CacheControlAdapter\nfrom .controller import CacheController\n\nimport logging\nlogging.getLogger(__name__).addHandler(logging.NullHandler())\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/cachecontrol/_cmd.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\nimport logging\n\nfrom pip._vendor import requests\n\nfrom pip._vendor.cachecontrol.adapter import CacheControlAdapter\nfrom pip._vendor.cachecontrol.cache import DictCache\nfrom pip._vendor.cachecontrol.controller import logger\n\nfrom argparse import ArgumentParser\n\n\ndef setup_logging():\n    logger.setLevel(logging.DEBUG)\n    handler = logging.StreamHandler()\n    logger.addHandler(handler)\n\n\ndef get_session():\n    adapter = CacheControlAdapter(\n        DictCache(), cache_etags=True, serializer=None, heuristic=None\n    )\n    sess = requests.Session()\n    sess.mount(\"http://\", adapter)\n    sess.mount(\"https://\", adapter)\n\n    sess.cache_controller = adapter.controller\n    return sess\n\n\ndef get_args():\n    parser = ArgumentParser()\n    parser.add_argument(\"url\", help=\"The URL to try and cache\")\n    return parser.parse_args()\n\n\ndef main(args=None):\n    args = get_args()\n    sess = get_session()\n\n    # Make a request to get a response\n    resp = sess.get(args.url)\n\n    # Turn on logging\n    setup_logging()\n\n    # try setting the cache\n    sess.cache_controller.cache_response(resp.request, resp.raw)\n\n    # Now try to get it\n    if sess.cache_controller.cached_request(resp.request):\n        print(\"Cached!\")\n    else:\n        print(\"Not cached :(\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/cachecontrol/adapter.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\nimport types\nimport functools\nimport zlib\n\nfrom pip._vendor.requests.adapters import HTTPAdapter\n\nfrom .controller import CacheController, PERMANENT_REDIRECT_STATUSES\nfrom .cache import DictCache\nfrom .filewrapper import CallbackFileWrapper\n\n\nclass CacheControlAdapter(HTTPAdapter):\n    invalidating_methods = {\"PUT\", \"PATCH\", \"DELETE\"}\n\n    def __init__(\n        self,\n        cache=None,\n        cache_etags=True,\n        controller_class=None,\n        serializer=None,\n        heuristic=None,\n        cacheable_methods=None,\n        *args,\n        **kw\n    ):\n        super(CacheControlAdapter, self).__init__(*args, **kw)\n        self.cache = DictCache() if cache is None else cache\n        self.heuristic = heuristic\n        self.cacheable_methods = cacheable_methods or (\"GET\",)\n\n        controller_factory = controller_class or CacheController\n        self.controller = controller_factory(\n            self.cache, cache_etags=cache_etags, serializer=serializer\n        )\n\n    def send(self, request, cacheable_methods=None, **kw):\n        \"\"\"\n        Send a request. Use the request information to see if it\n        exists in the cache and cache the response if we need to and can.\n        \"\"\"\n        cacheable = cacheable_methods or self.cacheable_methods\n        if request.method in cacheable:\n            try:\n                cached_response = self.controller.cached_request(request)\n            except zlib.error:\n                cached_response = None\n            if cached_response:\n                return self.build_response(request, cached_response, from_cache=True)\n\n            # check for etags and add headers if appropriate\n            request.headers.update(self.controller.conditional_headers(request))\n\n        resp = super(CacheControlAdapter, self).send(request, **kw)\n\n        return resp\n\n    def build_response(\n        self, request, response, from_cache=False, cacheable_methods=None\n    ):\n        \"\"\"\n        Build a response by making a request or using the cache.\n\n        This will end up calling send and returning a potentially\n        cached response\n        \"\"\"\n        cacheable = cacheable_methods or self.cacheable_methods\n        if not from_cache and request.method in cacheable:\n            # Check for any heuristics that might update headers\n            # before trying to cache.\n            if self.heuristic:\n                response = self.heuristic.apply(response)\n\n            # apply any expiration heuristics\n            if response.status == 304:\n                # We must have sent an ETag request. This could mean\n                # that we've been expired already or that we simply\n                # have an etag. In either case, we want to try and\n                # update the cache if that is the case.\n                cached_response = self.controller.update_cached_response(\n                    request, response\n                )\n\n                if cached_response is not response:\n                    from_cache = True\n\n                # We are done with the server response, read a\n                # possible response body (compliant servers will\n                # not return one, but we cannot be 100% sure) and\n                # release the connection back to the pool.\n                response.read(decode_content=False)\n                response.release_conn()\n\n                response = cached_response\n\n            # We always cache the 301 responses\n            elif int(response.status) in PERMANENT_REDIRECT_STATUSES:\n                self.controller.cache_response(request, response)\n            else:\n                # Wrap the response file with a wrapper that will cache the\n                #   response when the stream has been consumed.\n                response._fp = CallbackFileWrapper(\n                    response._fp,\n                    functools.partial(\n                        self.controller.cache_response, request, response\n                    ),\n                )\n                if response.chunked:\n                    super_update_chunk_length = response._update_chunk_length\n\n                    def _update_chunk_length(self):\n                        super_update_chunk_length()\n                        if self.chunk_left == 0:\n                            self._fp._close()\n\n                    response._update_chunk_length = types.MethodType(\n                        _update_chunk_length, response\n                    )\n\n        resp = super(CacheControlAdapter, self).build_response(request, response)\n\n        # See if we should invalidate the cache.\n        if request.method in self.invalidating_methods and resp.ok:\n            cache_url = self.controller.cache_url(request.url)\n            self.cache.delete(cache_url)\n\n        # Give the request a from_cache attr to let people use it\n        resp.from_cache = from_cache\n\n        return resp\n\n    def close(self):\n        self.cache.close()\n        super(CacheControlAdapter, self).close()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/cachecontrol/cache.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nThe cache object API for implementing caches. The default is a thread\nsafe in-memory dictionary.\n\"\"\"\nfrom threading import Lock\n\n\nclass BaseCache(object):\n\n    def get(self, key):\n        raise NotImplementedError()\n\n    def set(self, key, value, expires=None):\n        raise NotImplementedError()\n\n    def delete(self, key):\n        raise NotImplementedError()\n\n    def close(self):\n        pass\n\n\nclass DictCache(BaseCache):\n\n    def __init__(self, init_dict=None):\n        self.lock = Lock()\n        self.data = init_dict or {}\n\n    def get(self, key):\n        return self.data.get(key, None)\n\n    def set(self, key, value, expires=None):\n        with self.lock:\n            self.data.update({key: value})\n\n    def delete(self, key):\n        with self.lock:\n            if key in self.data:\n                self.data.pop(key)\n\n\nclass SeparateBodyBaseCache(BaseCache):\n    \"\"\"\n    In this variant, the body is not stored mixed in with the metadata, but is\n    passed in (as a bytes-like object) in a separate call to ``set_body()``.\n\n    That is, the expected interaction pattern is::\n\n        cache.set(key, serialized_metadata)\n        cache.set_body(key)\n\n    Similarly, the body should be loaded separately via ``get_body()``.\n    \"\"\"\n    def set_body(self, key, body):\n        raise NotImplementedError()\n\n    def get_body(self, key):\n        \"\"\"\n        Return the body as file-like object.\n        \"\"\"\n        raise NotImplementedError()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/cachecontrol/caches/__init__.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\nfrom .file_cache import FileCache, SeparateBodyFileCache\nfrom .redis_cache import RedisCache\n\n\n__all__ = [\"FileCache\", \"SeparateBodyFileCache\", \"RedisCache\"]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/cachecontrol/caches/file_cache.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\nimport hashlib\nimport os\nfrom textwrap import dedent\n\nfrom ..cache import BaseCache, SeparateBodyBaseCache\nfrom ..controller import CacheController\n\ntry:\n    FileNotFoundError\nexcept NameError:\n    # py2.X\n    FileNotFoundError = (IOError, OSError)\n\n\ndef _secure_open_write(filename, fmode):\n    # We only want to write to this file, so open it in write only mode\n    flags = os.O_WRONLY\n\n    # os.O_CREAT | os.O_EXCL will fail if the file already exists, so we only\n    #  will open *new* files.\n    # We specify this because we want to ensure that the mode we pass is the\n    # mode of the file.\n    flags |= os.O_CREAT | os.O_EXCL\n\n    # Do not follow symlinks to prevent someone from making a symlink that\n    # we follow and insecurely open a cache file.\n    if hasattr(os, \"O_NOFOLLOW\"):\n        flags |= os.O_NOFOLLOW\n\n    # On Windows we'll mark this file as binary\n    if hasattr(os, \"O_BINARY\"):\n        flags |= os.O_BINARY\n\n    # Before we open our file, we want to delete any existing file that is\n    # there\n    try:\n        os.remove(filename)\n    except (IOError, OSError):\n        # The file must not exist already, so we can just skip ahead to opening\n        pass\n\n    # Open our file, the use of os.O_CREAT | os.O_EXCL will ensure that if a\n    # race condition happens between the os.remove and this line, that an\n    # error will be raised. Because we utilize a lockfile this should only\n    # happen if someone is attempting to attack us.\n    fd = os.open(filename, flags, fmode)\n    try:\n        return os.fdopen(fd, \"wb\")\n\n    except:\n        # An error occurred wrapping our FD in a file object\n        os.close(fd)\n        raise\n\n\nclass _FileCacheMixin:\n    \"\"\"Shared implementation for both FileCache variants.\"\"\"\n\n    def __init__(\n        self,\n        directory,\n        forever=False,\n        filemode=0o0600,\n        dirmode=0o0700,\n        use_dir_lock=None,\n        lock_class=None,\n    ):\n\n        if use_dir_lock is not None and lock_class is not None:\n            raise ValueError(\"Cannot use use_dir_lock and lock_class together\")\n\n        try:\n            from lockfile import LockFile\n            from lockfile.mkdirlockfile import MkdirLockFile\n        except ImportError:\n            notice = dedent(\n                \"\"\"\n            NOTE: In order to use the FileCache you must have\n            lockfile installed. You can install it via pip:\n              pip install lockfile\n            \"\"\"\n            )\n            raise ImportError(notice)\n\n        else:\n            if use_dir_lock:\n                lock_class = MkdirLockFile\n\n            elif lock_class is None:\n                lock_class = LockFile\n\n        self.directory = directory\n        self.forever = forever\n        self.filemode = filemode\n        self.dirmode = dirmode\n        self.lock_class = lock_class\n\n    @staticmethod\n    def encode(x):\n        return hashlib.sha224(x.encode()).hexdigest()\n\n    def _fn(self, name):\n        # NOTE: This method should not change as some may depend on it.\n        #       See: https://github.com/ionrock/cachecontrol/issues/63\n        hashed = self.encode(name)\n        parts = list(hashed[:5]) + [hashed]\n        return os.path.join(self.directory, *parts)\n\n    def get(self, key):\n        name = self._fn(key)\n        try:\n            with open(name, \"rb\") as fh:\n                return fh.read()\n\n        except FileNotFoundError:\n            return None\n\n    def set(self, key, value, expires=None):\n        name = self._fn(key)\n        self._write(name, value)\n\n    def _write(self, path, data: bytes):\n        \"\"\"\n        Safely write the data to the given path.\n        \"\"\"\n        # Make sure the directory exists\n        try:\n            os.makedirs(os.path.dirname(path), self.dirmode)\n        except (IOError, OSError):\n            pass\n\n        with self.lock_class(path) as lock:\n            # Write our actual file\n            with _secure_open_write(lock.path, self.filemode) as fh:\n                fh.write(data)\n\n    def _delete(self, key, suffix):\n        name = self._fn(key) + suffix\n        if not self.forever:\n            try:\n                os.remove(name)\n            except FileNotFoundError:\n                pass\n\n\nclass FileCache(_FileCacheMixin, BaseCache):\n    \"\"\"\n    Traditional FileCache: body is stored in memory, so not suitable for large\n    downloads.\n    \"\"\"\n\n    def delete(self, key):\n        self._delete(key, \"\")\n\n\nclass SeparateBodyFileCache(_FileCacheMixin, SeparateBodyBaseCache):\n    \"\"\"\n    Memory-efficient FileCache: body is stored in a separate file, reducing\n    peak memory usage.\n    \"\"\"\n\n    def get_body(self, key):\n        name = self._fn(key) + \".body\"\n        try:\n            return open(name, \"rb\")\n        except FileNotFoundError:\n            return None\n\n    def set_body(self, key, body):\n        name = self._fn(key) + \".body\"\n        self._write(name, body)\n\n    def delete(self, key):\n        self._delete(key, \"\")\n        self._delete(key, \".body\")\n\n\ndef url_to_file_path(url, filecache):\n    \"\"\"Return the file cache path based on the URL.\n\n    This does not ensure the file exists!\n    \"\"\"\n    key = CacheController.cache_url(url)\n    return filecache._fn(key)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/cachecontrol/caches/redis_cache.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\nfrom __future__ import division\n\nfrom datetime import datetime\nfrom pip._vendor.cachecontrol.cache import BaseCache\n\n\nclass RedisCache(BaseCache):\n\n    def __init__(self, conn):\n        self.conn = conn\n\n    def get(self, key):\n        return self.conn.get(key)\n\n    def set(self, key, value, expires=None):\n        if not expires:\n            self.conn.set(key, value)\n        elif isinstance(expires, datetime):\n            expires = expires - datetime.utcnow()\n            self.conn.setex(key, int(expires.total_seconds()), value)\n        else:\n            self.conn.setex(key, expires, value)\n\n    def delete(self, key):\n        self.conn.delete(key)\n\n    def clear(self):\n        \"\"\"Helper for clearing all the keys in a database. Use with\n        caution!\"\"\"\n        for key in self.conn.keys():\n            self.conn.delete(key)\n\n    def close(self):\n        \"\"\"Redis uses connection pooling, no need to close the connection.\"\"\"\n        pass\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/cachecontrol/compat.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\ntry:\n    from urllib.parse import urljoin\nexcept ImportError:\n    from urlparse import urljoin\n\n\ntry:\n    import cPickle as pickle\nexcept ImportError:\n    import pickle\n\n# Handle the case where the requests module has been patched to not have\n# urllib3 bundled as part of its source.\ntry:\n    from pip._vendor.requests.packages.urllib3.response import HTTPResponse\nexcept ImportError:\n    from pip._vendor.urllib3.response import HTTPResponse\n\ntry:\n    from pip._vendor.requests.packages.urllib3.util import is_fp_closed\nexcept ImportError:\n    from pip._vendor.urllib3.util import is_fp_closed\n\n# Replicate some six behaviour\ntry:\n    text_type = unicode\nexcept NameError:\n    text_type = str\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/cachecontrol/controller.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nThe httplib2 algorithms ported for use with requests.\n\"\"\"\nimport logging\nimport re\nimport calendar\nimport time\nfrom email.utils import parsedate_tz\n\nfrom pip._vendor.requests.structures import CaseInsensitiveDict\n\nfrom .cache import DictCache, SeparateBodyBaseCache\nfrom .serialize import Serializer\n\n\nlogger = logging.getLogger(__name__)\n\nURI = re.compile(r\"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\")\n\nPERMANENT_REDIRECT_STATUSES = (301, 308)\n\n\ndef parse_uri(uri):\n    \"\"\"Parses a URI using the regex given in Appendix B of RFC 3986.\n\n    (scheme, authority, path, query, fragment) = parse_uri(uri)\n    \"\"\"\n    groups = URI.match(uri).groups()\n    return (groups[1], groups[3], groups[4], groups[6], groups[8])\n\n\nclass CacheController(object):\n    \"\"\"An interface to see if request should cached or not.\"\"\"\n\n    def __init__(\n        self, cache=None, cache_etags=True, serializer=None, status_codes=None\n    ):\n        self.cache = DictCache() if cache is None else cache\n        self.cache_etags = cache_etags\n        self.serializer = serializer or Serializer()\n        self.cacheable_status_codes = status_codes or (200, 203, 300, 301, 308)\n\n    @classmethod\n    def _urlnorm(cls, uri):\n        \"\"\"Normalize the URL to create a safe key for the cache\"\"\"\n        (scheme, authority, path, query, fragment) = parse_uri(uri)\n        if not scheme or not authority:\n            raise Exception(\"Only absolute URIs are allowed. uri = %s\" % uri)\n\n        scheme = scheme.lower()\n        authority = authority.lower()\n\n        if not path:\n            path = \"/\"\n\n        # Could do syntax based normalization of the URI before\n        # computing the digest. See Section 6.2.2 of Std 66.\n        request_uri = query and \"?\".join([path, query]) or path\n        defrag_uri = scheme + \"://\" + authority + request_uri\n\n        return defrag_uri\n\n    @classmethod\n    def cache_url(cls, uri):\n        return cls._urlnorm(uri)\n\n    def parse_cache_control(self, headers):\n        known_directives = {\n            # https://tools.ietf.org/html/rfc7234#section-5.2\n            \"max-age\": (int, True),\n            \"max-stale\": (int, False),\n            \"min-fresh\": (int, True),\n            \"no-cache\": (None, False),\n            \"no-store\": (None, False),\n            \"no-transform\": (None, False),\n            \"only-if-cached\": (None, False),\n            \"must-revalidate\": (None, False),\n            \"public\": (None, False),\n            \"private\": (None, False),\n            \"proxy-revalidate\": (None, False),\n            \"s-maxage\": (int, True),\n        }\n\n        cc_headers = headers.get(\"cache-control\", headers.get(\"Cache-Control\", \"\"))\n\n        retval = {}\n\n        for cc_directive in cc_headers.split(\",\"):\n            if not cc_directive.strip():\n                continue\n\n            parts = cc_directive.split(\"=\", 1)\n            directive = parts[0].strip()\n\n            try:\n                typ, required = known_directives[directive]\n            except KeyError:\n                logger.debug(\"Ignoring unknown cache-control directive: %s\", directive)\n                continue\n\n            if not typ or not required:\n                retval[directive] = None\n            if typ:\n                try:\n                    retval[directive] = typ(parts[1].strip())\n                except IndexError:\n                    if required:\n                        logger.debug(\n                            \"Missing value for cache-control \" \"directive: %s\",\n                            directive,\n                        )\n                except ValueError:\n                    logger.debug(\n                        \"Invalid value for cache-control directive \" \"%s, must be %s\",\n                        directive,\n                        typ.__name__,\n                    )\n\n        return retval\n\n    def cached_request(self, request):\n        \"\"\"\n        Return a cached response if it exists in the cache, otherwise\n        return False.\n        \"\"\"\n        cache_url = self.cache_url(request.url)\n        logger.debug('Looking up \"%s\" in the cache', cache_url)\n        cc = self.parse_cache_control(request.headers)\n\n        # Bail out if the request insists on fresh data\n        if \"no-cache\" in cc:\n            logger.debug('Request header has \"no-cache\", cache bypassed')\n            return False\n\n        if \"max-age\" in cc and cc[\"max-age\"] == 0:\n            logger.debug('Request header has \"max_age\" as 0, cache bypassed')\n            return False\n\n        # Request allows serving from the cache, let's see if we find something\n        cache_data = self.cache.get(cache_url)\n        if cache_data is None:\n            logger.debug(\"No cache entry available\")\n            return False\n\n        if isinstance(self.cache, SeparateBodyBaseCache):\n            body_file = self.cache.get_body(cache_url)\n        else:\n            body_file = None\n\n        # Check whether it can be deserialized\n        resp = self.serializer.loads(request, cache_data, body_file)\n        if not resp:\n            logger.warning(\"Cache entry deserialization failed, entry ignored\")\n            return False\n\n        # If we have a cached permanent redirect, return it immediately. We\n        # don't need to test our response for other headers b/c it is\n        # intrinsically \"cacheable\" as it is Permanent.\n        #\n        # See:\n        #   https://tools.ietf.org/html/rfc7231#section-6.4.2\n        #\n        # Client can try to refresh the value by repeating the request\n        # with cache busting headers as usual (ie no-cache).\n        if int(resp.status) in PERMANENT_REDIRECT_STATUSES:\n            msg = (\n                \"Returning cached permanent redirect response \"\n                \"(ignoring date and etag information)\"\n            )\n            logger.debug(msg)\n            return resp\n\n        headers = CaseInsensitiveDict(resp.headers)\n        if not headers or \"date\" not in headers:\n            if \"etag\" not in headers:\n                # Without date or etag, the cached response can never be used\n                # and should be deleted.\n                logger.debug(\"Purging cached response: no date or etag\")\n                self.cache.delete(cache_url)\n            logger.debug(\"Ignoring cached response: no date\")\n            return False\n\n        now = time.time()\n        date = calendar.timegm(parsedate_tz(headers[\"date\"]))\n        current_age = max(0, now - date)\n        logger.debug(\"Current age based on date: %i\", current_age)\n\n        # TODO: There is an assumption that the result will be a\n        #       urllib3 response object. This may not be best since we\n        #       could probably avoid instantiating or constructing the\n        #       response until we know we need it.\n        resp_cc = self.parse_cache_control(headers)\n\n        # determine freshness\n        freshness_lifetime = 0\n\n        # Check the max-age pragma in the cache control header\n        if \"max-age\" in resp_cc:\n            freshness_lifetime = resp_cc[\"max-age\"]\n            logger.debug(\"Freshness lifetime from max-age: %i\", freshness_lifetime)\n\n        # If there isn't a max-age, check for an expires header\n        elif \"expires\" in headers:\n            expires = parsedate_tz(headers[\"expires\"])\n            if expires is not None:\n                expire_time = calendar.timegm(expires) - date\n                freshness_lifetime = max(0, expire_time)\n                logger.debug(\"Freshness lifetime from expires: %i\", freshness_lifetime)\n\n        # Determine if we are setting freshness limit in the\n        # request. Note, this overrides what was in the response.\n        if \"max-age\" in cc:\n            freshness_lifetime = cc[\"max-age\"]\n            logger.debug(\n                \"Freshness lifetime from request max-age: %i\", freshness_lifetime\n            )\n\n        if \"min-fresh\" in cc:\n            min_fresh = cc[\"min-fresh\"]\n            # adjust our current age by our min fresh\n            current_age += min_fresh\n            logger.debug(\"Adjusted current age from min-fresh: %i\", current_age)\n\n        # Return entry if it is fresh enough\n        if freshness_lifetime > current_age:\n            logger.debug('The response is \"fresh\", returning cached response')\n            logger.debug(\"%i > %i\", freshness_lifetime, current_age)\n            return resp\n\n        # we're not fresh. If we don't have an Etag, clear it out\n        if \"etag\" not in headers:\n            logger.debug('The cached response is \"stale\" with no etag, purging')\n            self.cache.delete(cache_url)\n\n        # return the original handler\n        return False\n\n    def conditional_headers(self, request):\n        cache_url = self.cache_url(request.url)\n        resp = self.serializer.loads(request, self.cache.get(cache_url))\n        new_headers = {}\n\n        if resp:\n            headers = CaseInsensitiveDict(resp.headers)\n\n            if \"etag\" in headers:\n                new_headers[\"If-None-Match\"] = headers[\"ETag\"]\n\n            if \"last-modified\" in headers:\n                new_headers[\"If-Modified-Since\"] = headers[\"Last-Modified\"]\n\n        return new_headers\n\n    def _cache_set(self, cache_url, request, response, body=None, expires_time=None):\n        \"\"\"\n        Store the data in the cache.\n        \"\"\"\n        if isinstance(self.cache, SeparateBodyBaseCache):\n            # We pass in the body separately; just put a placeholder empty\n            # string in the metadata.\n            self.cache.set(\n                cache_url,\n                self.serializer.dumps(request, response, b\"\"),\n                expires=expires_time,\n            )\n            self.cache.set_body(cache_url, body)\n        else:\n            self.cache.set(\n                cache_url,\n                self.serializer.dumps(request, response, body),\n                expires=expires_time,\n            )\n\n    def cache_response(self, request, response, body=None, status_codes=None):\n        \"\"\"\n        Algorithm for caching requests.\n\n        This assumes a requests Response object.\n        \"\"\"\n        # From httplib2: Don't cache 206's since we aren't going to\n        #                handle byte range requests\n        cacheable_status_codes = status_codes or self.cacheable_status_codes\n        if response.status not in cacheable_status_codes:\n            logger.debug(\n                \"Status code %s not in %s\", response.status, cacheable_status_codes\n            )\n            return\n\n        response_headers = CaseInsensitiveDict(response.headers)\n\n        if \"date\" in response_headers:\n            date = calendar.timegm(parsedate_tz(response_headers[\"date\"]))\n        else:\n            date = 0\n\n        # If we've been given a body, our response has a Content-Length, that\n        # Content-Length is valid then we can check to see if the body we've\n        # been given matches the expected size, and if it doesn't we'll just\n        # skip trying to cache it.\n        if (\n            body is not None\n            and \"content-length\" in response_headers\n            and response_headers[\"content-length\"].isdigit()\n            and int(response_headers[\"content-length\"]) != len(body)\n        ):\n            return\n\n        cc_req = self.parse_cache_control(request.headers)\n        cc = self.parse_cache_control(response_headers)\n\n        cache_url = self.cache_url(request.url)\n        logger.debug('Updating cache with response from \"%s\"', cache_url)\n\n        # Delete it from the cache if we happen to have it stored there\n        no_store = False\n        if \"no-store\" in cc:\n            no_store = True\n            logger.debug('Response header has \"no-store\"')\n        if \"no-store\" in cc_req:\n            no_store = True\n            logger.debug('Request header has \"no-store\"')\n        if no_store and self.cache.get(cache_url):\n            logger.debug('Purging existing cache entry to honor \"no-store\"')\n            self.cache.delete(cache_url)\n        if no_store:\n            return\n\n        # https://tools.ietf.org/html/rfc7234#section-4.1:\n        # A Vary header field-value of \"*\" always fails to match.\n        # Storing such a response leads to a deserialization warning\n        # during cache lookup and is not allowed to ever be served,\n        # so storing it can be avoided.\n        if \"*\" in response_headers.get(\"vary\", \"\"):\n            logger.debug('Response header has \"Vary: *\"')\n            return\n\n        # If we've been given an etag, then keep the response\n        if self.cache_etags and \"etag\" in response_headers:\n            expires_time = 0\n            if response_headers.get(\"expires\"):\n                expires = parsedate_tz(response_headers[\"expires\"])\n                if expires is not None:\n                    expires_time = calendar.timegm(expires) - date\n\n            expires_time = max(expires_time, 14 * 86400)\n\n            logger.debug(\"etag object cached for {0} seconds\".format(expires_time))\n            logger.debug(\"Caching due to etag\")\n            self._cache_set(cache_url, request, response, body, expires_time)\n\n        # Add to the cache any permanent redirects. We do this before looking\n        # that the Date headers.\n        elif int(response.status) in PERMANENT_REDIRECT_STATUSES:\n            logger.debug(\"Caching permanent redirect\")\n            self._cache_set(cache_url, request, response, b\"\")\n\n        # Add to the cache if the response headers demand it. If there\n        # is no date header then we can't do anything about expiring\n        # the cache.\n        elif \"date\" in response_headers:\n            date = calendar.timegm(parsedate_tz(response_headers[\"date\"]))\n            # cache when there is a max-age > 0\n            if \"max-age\" in cc and cc[\"max-age\"] > 0:\n                logger.debug(\"Caching b/c date exists and max-age > 0\")\n                expires_time = cc[\"max-age\"]\n                self._cache_set(\n                    cache_url,\n                    request,\n                    response,\n                    body,\n                    expires_time,\n                )\n\n            # If the request can expire, it means we should cache it\n            # in the meantime.\n            elif \"expires\" in response_headers:\n                if response_headers[\"expires\"]:\n                    expires = parsedate_tz(response_headers[\"expires\"])\n                    if expires is not None:\n                        expires_time = calendar.timegm(expires) - date\n                    else:\n                        expires_time = None\n\n                    logger.debug(\n                        \"Caching b/c of expires header. expires in {0} seconds\".format(\n                            expires_time\n                        )\n                    )\n                    self._cache_set(\n                        cache_url,\n                        request,\n                        response,\n                        body,\n                        expires_time,\n                    )\n\n    def update_cached_response(self, request, response):\n        \"\"\"On a 304 we will get a new set of headers that we want to\n        update our cached value with, assuming we have one.\n\n        This should only ever be called when we've sent an ETag and\n        gotten a 304 as the response.\n        \"\"\"\n        cache_url = self.cache_url(request.url)\n\n        cached_response = self.serializer.loads(request, self.cache.get(cache_url))\n\n        if not cached_response:\n            # we didn't have a cached response\n            return response\n\n        # Lets update our headers with the headers from the new request:\n        # http://tools.ietf.org/html/draft-ietf-httpbis-p4-conditional-26#section-4.1\n        #\n        # The server isn't supposed to send headers that would make\n        # the cached body invalid. But... just in case, we'll be sure\n        # to strip out ones we know that might be problmatic due to\n        # typical assumptions.\n        excluded_headers = [\"content-length\"]\n\n        cached_response.headers.update(\n            dict(\n                (k, v)\n                for k, v in response.headers.items()\n                if k.lower() not in excluded_headers\n            )\n        )\n\n        # we want a 200 b/c we have content via the cache\n        cached_response.status = 200\n\n        # update our cache\n        self._cache_set(cache_url, request, cached_response)\n\n        return cached_response\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/cachecontrol/filewrapper.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\nfrom tempfile import NamedTemporaryFile\nimport mmap\n\n\nclass CallbackFileWrapper(object):\n    \"\"\"\n    Small wrapper around a fp object which will tee everything read into a\n    buffer, and when that file is closed it will execute a callback with the\n    contents of that buffer.\n\n    All attributes are proxied to the underlying file object.\n\n    This class uses members with a double underscore (__) leading prefix so as\n    not to accidentally shadow an attribute.\n\n    The data is stored in a temporary file until it is all available.  As long\n    as the temporary files directory is disk-based (sometimes it's a\n    memory-backed-``tmpfs`` on Linux), data will be unloaded to disk if memory\n    pressure is high.  For small files the disk usually won't be used at all,\n    it'll all be in the filesystem memory cache, so there should be no\n    performance impact.\n    \"\"\"\n\n    def __init__(self, fp, callback):\n        self.__buf = NamedTemporaryFile(\"rb+\", delete=True)\n        self.__fp = fp\n        self.__callback = callback\n\n    def __getattr__(self, name):\n        # The vaguaries of garbage collection means that self.__fp is\n        # not always set.  By using __getattribute__ and the private\n        # name[0] allows looking up the attribute value and raising an\n        # AttributeError when it doesn't exist. This stop thigns from\n        # infinitely recursing calls to getattr in the case where\n        # self.__fp hasn't been set.\n        #\n        # [0] https://docs.python.org/2/reference/expressions.html#atom-identifiers\n        fp = self.__getattribute__(\"_CallbackFileWrapper__fp\")\n        return getattr(fp, name)\n\n    def __is_fp_closed(self):\n        try:\n            return self.__fp.fp is None\n\n        except AttributeError:\n            pass\n\n        try:\n            return self.__fp.closed\n\n        except AttributeError:\n            pass\n\n        # We just don't cache it then.\n        # TODO: Add some logging here...\n        return False\n\n    def _close(self):\n        if self.__callback:\n            if self.__buf.tell() == 0:\n                # Empty file:\n                result = b\"\"\n            else:\n                # Return the data without actually loading it into memory,\n                # relying on Python's buffer API and mmap(). mmap() just gives\n                # a view directly into the filesystem's memory cache, so it\n                # doesn't result in duplicate memory use.\n                self.__buf.seek(0, 0)\n                result = memoryview(\n                    mmap.mmap(self.__buf.fileno(), 0, access=mmap.ACCESS_READ)\n                )\n            self.__callback(result)\n\n        # We assign this to None here, because otherwise we can get into\n        # really tricky problems where the CPython interpreter dead locks\n        # because the callback is holding a reference to something which\n        # has a __del__ method. Setting this to None breaks the cycle\n        # and allows the garbage collector to do it's thing normally.\n        self.__callback = None\n\n        # Closing the temporary file releases memory and frees disk space.\n        # Important when caching big files.\n        self.__buf.close()\n\n    def read(self, amt=None):\n        data = self.__fp.read(amt)\n        if data:\n            # We may be dealing with b'', a sign that things are over:\n            # it's passed e.g. after we've already closed self.__buf.\n            self.__buf.write(data)\n        if self.__is_fp_closed():\n            self._close()\n\n        return data\n\n    def _safe_read(self, amt):\n        data = self.__fp._safe_read(amt)\n        if amt == 2 and data == b\"\\r\\n\":\n            # urllib executes this read to toss the CRLF at the end\n            # of the chunk.\n            return data\n\n        self.__buf.write(data)\n        if self.__is_fp_closed():\n            self._close()\n\n        return data\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/cachecontrol/heuristics.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\nimport calendar\nimport time\n\nfrom email.utils import formatdate, parsedate, parsedate_tz\n\nfrom datetime import datetime, timedelta\n\nTIME_FMT = \"%a, %d %b %Y %H:%M:%S GMT\"\n\n\ndef expire_after(delta, date=None):\n    date = date or datetime.utcnow()\n    return date + delta\n\n\ndef datetime_to_header(dt):\n    return formatdate(calendar.timegm(dt.timetuple()))\n\n\nclass BaseHeuristic(object):\n\n    def warning(self, response):\n        \"\"\"\n        Return a valid 1xx warning header value describing the cache\n        adjustments.\n\n        The response is provided too allow warnings like 113\n        http://tools.ietf.org/html/rfc7234#section-5.5.4 where we need\n        to explicitly say response is over 24 hours old.\n        \"\"\"\n        return '110 - \"Response is Stale\"'\n\n    def update_headers(self, response):\n        \"\"\"Update the response headers with any new headers.\n\n        NOTE: This SHOULD always include some Warning header to\n              signify that the response was cached by the client, not\n              by way of the provided headers.\n        \"\"\"\n        return {}\n\n    def apply(self, response):\n        updated_headers = self.update_headers(response)\n\n        if updated_headers:\n            response.headers.update(updated_headers)\n            warning_header_value = self.warning(response)\n            if warning_header_value is not None:\n                response.headers.update({\"Warning\": warning_header_value})\n\n        return response\n\n\nclass OneDayCache(BaseHeuristic):\n    \"\"\"\n    Cache the response by providing an expires 1 day in the\n    future.\n    \"\"\"\n\n    def update_headers(self, response):\n        headers = {}\n\n        if \"expires\" not in response.headers:\n            date = parsedate(response.headers[\"date\"])\n            expires = expire_after(timedelta(days=1), date=datetime(*date[:6]))\n            headers[\"expires\"] = datetime_to_header(expires)\n            headers[\"cache-control\"] = \"public\"\n        return headers\n\n\nclass ExpiresAfter(BaseHeuristic):\n    \"\"\"\n    Cache **all** requests for a defined time period.\n    \"\"\"\n\n    def __init__(self, **kw):\n        self.delta = timedelta(**kw)\n\n    def update_headers(self, response):\n        expires = expire_after(self.delta)\n        return {\"expires\": datetime_to_header(expires), \"cache-control\": \"public\"}\n\n    def warning(self, response):\n        tmpl = \"110 - Automatically cached for %s. Response might be stale\"\n        return tmpl % self.delta\n\n\nclass LastModified(BaseHeuristic):\n    \"\"\"\n    If there is no Expires header already, fall back on Last-Modified\n    using the heuristic from\n    http://tools.ietf.org/html/rfc7234#section-4.2.2\n    to calculate a reasonable value.\n\n    Firefox also does something like this per\n    https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching_FAQ\n    http://lxr.mozilla.org/mozilla-release/source/netwerk/protocol/http/nsHttpResponseHead.cpp#397\n    Unlike mozilla we limit this to 24-hr.\n    \"\"\"\n    cacheable_by_default_statuses = {\n        200, 203, 204, 206, 300, 301, 404, 405, 410, 414, 501\n    }\n\n    def update_headers(self, resp):\n        headers = resp.headers\n\n        if \"expires\" in headers:\n            return {}\n\n        if \"cache-control\" in headers and headers[\"cache-control\"] != \"public\":\n            return {}\n\n        if resp.status not in self.cacheable_by_default_statuses:\n            return {}\n\n        if \"date\" not in headers or \"last-modified\" not in headers:\n            return {}\n\n        date = calendar.timegm(parsedate_tz(headers[\"date\"]))\n        last_modified = parsedate(headers[\"last-modified\"])\n        if date is None or last_modified is None:\n            return {}\n\n        now = time.time()\n        current_age = max(0, now - date)\n        delta = date - calendar.timegm(last_modified)\n        freshness_lifetime = max(0, min(delta / 10, 24 * 3600))\n        if freshness_lifetime <= current_age:\n            return {}\n\n        expires = date + freshness_lifetime\n        return {\"expires\": time.strftime(TIME_FMT, time.gmtime(expires))}\n\n    def warning(self, resp):\n        return None\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/cachecontrol/serialize.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\nimport base64\nimport io\nimport json\nimport zlib\n\nfrom pip._vendor import msgpack\nfrom pip._vendor.requests.structures import CaseInsensitiveDict\n\nfrom .compat import HTTPResponse, pickle, text_type\n\n\ndef _b64_decode_bytes(b):\n    return base64.b64decode(b.encode(\"ascii\"))\n\n\ndef _b64_decode_str(s):\n    return _b64_decode_bytes(s).decode(\"utf8\")\n\n\n_default_body_read = object()\n\n\nclass Serializer(object):\n    def dumps(self, request, response, body=None):\n        response_headers = CaseInsensitiveDict(response.headers)\n\n        if body is None:\n            # When a body isn't passed in, we'll read the response. We\n            # also update the response with a new file handler to be\n            # sure it acts as though it was never read.\n            body = response.read(decode_content=False)\n            response._fp = io.BytesIO(body)\n\n        # NOTE: This is all a bit weird, but it's really important that on\n        #       Python 2.x these objects are unicode and not str, even when\n        #       they contain only ascii. The problem here is that msgpack\n        #       understands the difference between unicode and bytes and we\n        #       have it set to differentiate between them, however Python 2\n        #       doesn't know the difference. Forcing these to unicode will be\n        #       enough to have msgpack know the difference.\n        data = {\n            u\"response\": {\n                u\"body\": body,  # Empty bytestring if body is stored separately\n                u\"headers\": dict(\n                    (text_type(k), text_type(v)) for k, v in response.headers.items()\n                ),\n                u\"status\": response.status,\n                u\"version\": response.version,\n                u\"reason\": text_type(response.reason),\n                u\"strict\": response.strict,\n                u\"decode_content\": response.decode_content,\n            }\n        }\n\n        # Construct our vary headers\n        data[u\"vary\"] = {}\n        if u\"vary\" in response_headers:\n            varied_headers = response_headers[u\"vary\"].split(\",\")\n            for header in varied_headers:\n                header = text_type(header).strip()\n                header_value = request.headers.get(header, None)\n                if header_value is not None:\n                    header_value = text_type(header_value)\n                data[u\"vary\"][header] = header_value\n\n        return b\",\".join([b\"cc=4\", msgpack.dumps(data, use_bin_type=True)])\n\n    def loads(self, request, data, body_file=None):\n        # Short circuit if we've been given an empty set of data\n        if not data:\n            return\n\n        # Determine what version of the serializer the data was serialized\n        # with\n        try:\n            ver, data = data.split(b\",\", 1)\n        except ValueError:\n            ver = b\"cc=0\"\n\n        # Make sure that our \"ver\" is actually a version and isn't a false\n        # positive from a , being in the data stream.\n        if ver[:3] != b\"cc=\":\n            data = ver + data\n            ver = b\"cc=0\"\n\n        # Get the version number out of the cc=N\n        ver = ver.split(b\"=\", 1)[-1].decode(\"ascii\")\n\n        # Dispatch to the actual load method for the given version\n        try:\n            return getattr(self, \"_loads_v{}\".format(ver))(request, data, body_file)\n\n        except AttributeError:\n            # This is a version we don't have a loads function for, so we'll\n            # just treat it as a miss and return None\n            return\n\n    def prepare_response(self, request, cached, body_file=None):\n        \"\"\"Verify our vary headers match and construct a real urllib3\n        HTTPResponse object.\n        \"\"\"\n        # Special case the '*' Vary value as it means we cannot actually\n        # determine if the cached response is suitable for this request.\n        # This case is also handled in the controller code when creating\n        # a cache entry, but is left here for backwards compatibility.\n        if \"*\" in cached.get(\"vary\", {}):\n            return\n\n        # Ensure that the Vary headers for the cached response match our\n        # request\n        for header, value in cached.get(\"vary\", {}).items():\n            if request.headers.get(header, None) != value:\n                return\n\n        body_raw = cached[\"response\"].pop(\"body\")\n\n        headers = CaseInsensitiveDict(data=cached[\"response\"][\"headers\"])\n        if headers.get(\"transfer-encoding\", \"\") == \"chunked\":\n            headers.pop(\"transfer-encoding\")\n\n        cached[\"response\"][\"headers\"] = headers\n\n        try:\n            if body_file is None:\n                body = io.BytesIO(body_raw)\n            else:\n                body = body_file\n        except TypeError:\n            # This can happen if cachecontrol serialized to v1 format (pickle)\n            # using Python 2. A Python 2 str(byte string) will be unpickled as\n            # a Python 3 str (unicode string), which will cause the above to\n            # fail with:\n            #\n            #     TypeError: 'str' does not support the buffer interface\n            body = io.BytesIO(body_raw.encode(\"utf8\"))\n\n        return HTTPResponse(body=body, preload_content=False, **cached[\"response\"])\n\n    def _loads_v0(self, request, data, body_file=None):\n        # The original legacy cache data. This doesn't contain enough\n        # information to construct everything we need, so we'll treat this as\n        # a miss.\n        return\n\n    def _loads_v1(self, request, data, body_file=None):\n        try:\n            cached = pickle.loads(data)\n        except ValueError:\n            return\n\n        return self.prepare_response(request, cached, body_file)\n\n    def _loads_v2(self, request, data, body_file=None):\n        assert body_file is None\n        try:\n            cached = json.loads(zlib.decompress(data).decode(\"utf8\"))\n        except (ValueError, zlib.error):\n            return\n\n        # We need to decode the items that we've base64 encoded\n        cached[\"response\"][\"body\"] = _b64_decode_bytes(cached[\"response\"][\"body\"])\n        cached[\"response\"][\"headers\"] = dict(\n            (_b64_decode_str(k), _b64_decode_str(v))\n            for k, v in cached[\"response\"][\"headers\"].items()\n        )\n        cached[\"response\"][\"reason\"] = _b64_decode_str(cached[\"response\"][\"reason\"])\n        cached[\"vary\"] = dict(\n            (_b64_decode_str(k), _b64_decode_str(v) if v is not None else v)\n            for k, v in cached[\"vary\"].items()\n        )\n\n        return self.prepare_response(request, cached, body_file)\n\n    def _loads_v3(self, request, data, body_file):\n        # Due to Python 2 encoding issues, it's impossible to know for sure\n        # exactly how to load v3 entries, thus we'll treat these as a miss so\n        # that they get rewritten out as v4 entries.\n        return\n\n    def _loads_v4(self, request, data, body_file=None):\n        try:\n            cached = msgpack.loads(data, raw=False)\n        except ValueError:\n            return\n\n        return self.prepare_response(request, cached, body_file)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/cachecontrol/wrapper.py",
    "content": "# SPDX-FileCopyrightText: 2015 Eric Larson\n#\n# SPDX-License-Identifier: Apache-2.0\n\nfrom .adapter import CacheControlAdapter\nfrom .cache import DictCache\n\n\ndef CacheControl(\n    sess,\n    cache=None,\n    cache_etags=True,\n    serializer=None,\n    heuristic=None,\n    controller_class=None,\n    adapter_class=None,\n    cacheable_methods=None,\n):\n\n    cache = DictCache() if cache is None else cache\n    adapter_class = adapter_class or CacheControlAdapter\n    adapter = adapter_class(\n        cache,\n        cache_etags=cache_etags,\n        serializer=serializer,\n        heuristic=heuristic,\n        controller_class=controller_class,\n        cacheable_methods=cacheable_methods,\n    )\n    sess.mount(\"http://\", adapter)\n    sess.mount(\"https://\", adapter)\n\n    return sess\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/certifi/__init__.py",
    "content": "from .core import contents, where\n\n__all__ = [\"contents\", \"where\"]\n__version__ = \"2022.09.24\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/certifi/__main__.py",
    "content": "import argparse\n\nfrom pip._vendor.certifi import contents, where\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-c\", \"--contents\", action=\"store_true\")\nargs = parser.parse_args()\n\nif args.contents:\n    print(contents())\nelse:\n    print(where())\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/certifi/cacert.pem",
    "content": "\n# Issuer: CN=GlobalSign Root CA O=GlobalSign nv-sa OU=Root CA\n# Subject: CN=GlobalSign Root CA O=GlobalSign nv-sa OU=Root CA\n# Label: \"GlobalSign Root CA\"\n# Serial: 4835703278459707669005204\n# MD5 Fingerprint: 3e:45:52:15:09:51:92:e1:b7:5d:37:9f:b1:87:29:8a\n# SHA1 Fingerprint: b1:bc:96:8b:d4:f4:9d:62:2a:a8:9a:81:f2:15:01:52:a4:1d:82:9c\n# SHA256 Fingerprint: eb:d4:10:40:e4:bb:3e:c7:42:c9:e3:81:d3:1e:f2:a4:1a:48:b6:68:5c:96:e7:ce:f3:c1:df:6c:d4:33:1c:99\n-----BEGIN CERTIFICATE-----\nMIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG\nA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv\nb3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw\nMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i\nYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT\naWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ\njc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp\nxy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp\n1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG\nsnUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ\nU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8\n9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E\nBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B\nAQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz\nyj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE\n38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP\nAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad\nDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME\nHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Entrust.net Certification Authority (2048) O=Entrust.net OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)/(c) 1999 Entrust.net Limited\n# Subject: CN=Entrust.net Certification Authority (2048) O=Entrust.net OU=www.entrust.net/CPS_2048 incorp. by ref. (limits liab.)/(c) 1999 Entrust.net Limited\n# Label: \"Entrust.net Premium 2048 Secure Server CA\"\n# Serial: 946069240\n# MD5 Fingerprint: ee:29:31:bc:32:7e:9a:e6:e8:b5:f7:51:b4:34:71:90\n# SHA1 Fingerprint: 50:30:06:09:1d:97:d4:f5:ae:39:f7:cb:e7:92:7d:7d:65:2d:34:31\n# SHA256 Fingerprint: 6d:c4:71:72:e0:1c:bc:b0:bf:62:58:0d:89:5f:e2:b8:ac:9a:d4:f8:73:80:1e:0c:10:b9:c8:37:d2:1e:b1:77\n-----BEGIN CERTIFICATE-----\nMIIEKjCCAxKgAwIBAgIEOGPe+DANBgkqhkiG9w0BAQUFADCBtDEUMBIGA1UEChML\nRW50cnVzdC5uZXQxQDA+BgNVBAsUN3d3dy5lbnRydXN0Lm5ldC9DUFNfMjA0OCBp\nbmNvcnAuIGJ5IHJlZi4gKGxpbWl0cyBsaWFiLikxJTAjBgNVBAsTHChjKSAxOTk5\nIEVudHJ1c3QubmV0IExpbWl0ZWQxMzAxBgNVBAMTKkVudHJ1c3QubmV0IENlcnRp\nZmljYXRpb24gQXV0aG9yaXR5ICgyMDQ4KTAeFw05OTEyMjQxNzUwNTFaFw0yOTA3\nMjQxNDE1MTJaMIG0MRQwEgYDVQQKEwtFbnRydXN0Lm5ldDFAMD4GA1UECxQ3d3d3\nLmVudHJ1c3QubmV0L0NQU18yMDQ4IGluY29ycC4gYnkgcmVmLiAobGltaXRzIGxp\nYWIuKTElMCMGA1UECxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEG\nA1UEAxMqRW50cnVzdC5uZXQgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgKDIwNDgp\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArU1LqRKGsuqjIAcVFmQq\nK0vRvwtKTY7tgHalZ7d4QMBzQshowNtTK91euHaYNZOLGp18EzoOH1u3Hs/lJBQe\nsYGpjX24zGtLA/ECDNyrpUAkAH90lKGdCCmziAv1h3edVc3kw37XamSrhRSGlVuX\nMlBvPci6Zgzj/L24ScF2iUkZ/cCovYmjZy/Gn7xxGWC4LeksyZB2ZnuU4q941mVT\nXTzWnLLPKQP5L6RQstRIzgUyVYr9smRMDuSYB3Xbf9+5CFVghTAp+XtIpGmG4zU/\nHoZdenoVve8AjhUiVBcAkCaTvA5JaJG/+EfTnZVCwQ5N328mz8MYIWJmQ3DW1cAH\n4QIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV\nHQ4EFgQUVeSB0RGAvtiJuQijMfmhJAkWuXAwDQYJKoZIhvcNAQEFBQADggEBADub\nj1abMOdTmXx6eadNl9cZlZD7Bh/KM3xGY4+WZiT6QBshJ8rmcnPyT/4xmf3IDExo\nU8aAghOY+rat2l098c5u9hURlIIM7j+VrxGrD9cv3h8Dj1csHsm7mhpElesYT6Yf\nzX1XEC+bBAlahLVu2B064dae0Wx5XnkcFMXj0EyTO2U87d89vqbllRrDtRnDvV5b\nu/8j72gZyxKTJ1wDLW8w0B62GqzeWvfRqqgnpv55gcR5mTNXuhKwqeBCbJPKVt7+\nbYQLCIt+jerXmCHG8+c8eS9enNFMFY3h7CI3zJpDC5fcgJCNs2ebb0gIFVbPv/Er\nfF6adulZkMV8gzURZVE=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Baltimore CyberTrust Root O=Baltimore OU=CyberTrust\n# Subject: CN=Baltimore CyberTrust Root O=Baltimore OU=CyberTrust\n# Label: \"Baltimore CyberTrust Root\"\n# Serial: 33554617\n# MD5 Fingerprint: ac:b6:94:a5:9c:17:e0:d7:91:52:9b:b1:97:06:a6:e4\n# SHA1 Fingerprint: d4:de:20:d0:5e:66:fc:53:fe:1a:50:88:2c:78:db:28:52:ca:e4:74\n# SHA256 Fingerprint: 16:af:57:a9:f6:76:b0:ab:12:60:95:aa:5e:ba:de:f2:2a:b3:11:19:d6:44:ac:95:cd:4b:93:db:f3:f2:6a:eb\n-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgIEAgAAuTANBgkqhkiG9w0BAQUFADBaMQswCQYDVQQGEwJJ\nRTESMBAGA1UEChMJQmFsdGltb3JlMRMwEQYDVQQLEwpDeWJlclRydXN0MSIwIAYD\nVQQDExlCYWx0aW1vcmUgQ3liZXJUcnVzdCBSb290MB4XDTAwMDUxMjE4NDYwMFoX\nDTI1MDUxMjIzNTkwMFowWjELMAkGA1UEBhMCSUUxEjAQBgNVBAoTCUJhbHRpbW9y\nZTETMBEGA1UECxMKQ3liZXJUcnVzdDEiMCAGA1UEAxMZQmFsdGltb3JlIEN5YmVy\nVHJ1c3QgUm9vdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKMEuyKr\nmD1X6CZymrV51Cni4eiVgLGw41uOKymaZN+hXe2wCQVt2yguzmKiYv60iNoS6zjr\nIZ3AQSsBUnuId9Mcj8e6uYi1agnnc+gRQKfRzMpijS3ljwumUNKoUMMo6vWrJYeK\nmpYcqWe4PwzV9/lSEy/CG9VwcPCPwBLKBsua4dnKM3p31vjsufFoREJIE9LAwqSu\nXmD+tqYF/LTdB1kC1FkYmGP1pWPgkAx9XbIGevOF6uvUA65ehD5f/xXtabz5OTZy\ndc93Uk3zyZAsuT3lySNTPx8kmCFcB5kpvcY67Oduhjprl3RjM71oGDHweI12v/ye\njl0qhqdNkNwnGjkCAwEAAaNFMEMwHQYDVR0OBBYEFOWdWTCCR1jMrPoIVDaGezq1\nBE3wMBIGA1UdEwEB/wQIMAYBAf8CAQMwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3\nDQEBBQUAA4IBAQCFDF2O5G9RaEIFoN27TyclhAO992T9Ldcw46QQF+vaKSm2eT92\n9hkTI7gQCvlYpNRhcL0EYWoSihfVCr3FvDB81ukMJY2GQE/szKN+OMY3EU/t3Wgx\njkzSswF07r51XgdIGn9w/xZchMB5hbgF/X++ZRGjD8ACtPhSNzkE1akxehi/oCr0\nEpn3o0WC4zxe9Z2etciefC7IpJ5OCBRLbf1wbWsaY71k5h+3zvDyny67G7fyUIhz\nksLi4xaNmjICq44Y3ekQEe5+NauQrz4wlHrQMz2nZQ/1/I6eYs9HRCwBXbsdtTLS\nR9I4LtD+gdwyah617jzV/OeBHRnDJELqYzmp\n-----END CERTIFICATE-----\n\n# Issuer: CN=Entrust Root Certification Authority O=Entrust, Inc. OU=www.entrust.net/CPS is incorporated by reference/(c) 2006 Entrust, Inc.\n# Subject: CN=Entrust Root Certification Authority O=Entrust, Inc. OU=www.entrust.net/CPS is incorporated by reference/(c) 2006 Entrust, Inc.\n# Label: \"Entrust Root Certification Authority\"\n# Serial: 1164660820\n# MD5 Fingerprint: d6:a5:c3:ed:5d:dd:3e:00:c1:3d:87:92:1f:1d:3f:e4\n# SHA1 Fingerprint: b3:1e:b1:b7:40:e3:6c:84:02:da:dc:37:d4:4d:f5:d4:67:49:52:f9\n# SHA256 Fingerprint: 73:c1:76:43:4f:1b:c6:d5:ad:f4:5b:0e:76:e7:27:28:7c:8d:e5:76:16:c1:e6:e6:14:1a:2b:2c:bc:7d:8e:4c\n-----BEGIN CERTIFICATE-----\nMIIEkTCCA3mgAwIBAgIERWtQVDANBgkqhkiG9w0BAQUFADCBsDELMAkGA1UEBhMC\nVVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xOTA3BgNVBAsTMHd3dy5lbnRydXN0\nLm5ldC9DUFMgaXMgaW5jb3Jwb3JhdGVkIGJ5IHJlZmVyZW5jZTEfMB0GA1UECxMW\nKGMpIDIwMDYgRW50cnVzdCwgSW5jLjEtMCsGA1UEAxMkRW50cnVzdCBSb290IENl\ncnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA2MTEyNzIwMjM0MloXDTI2MTEyNzIw\nNTM0MlowgbAxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMTkw\nNwYDVQQLEzB3d3cuZW50cnVzdC5uZXQvQ1BTIGlzIGluY29ycG9yYXRlZCBieSBy\nZWZlcmVuY2UxHzAdBgNVBAsTFihjKSAyMDA2IEVudHJ1c3QsIEluYy4xLTArBgNV\nBAMTJEVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASIwDQYJ\nKoZIhvcNAQEBBQADggEPADCCAQoCggEBALaVtkNC+sZtKm9I35RMOVcF7sN5EUFo\nNu3s/poBj6E4KPz3EEZmLk0eGrEaTsbRwJWIsMn/MYszA9u3g3s+IIRe7bJWKKf4\n4LlAcTfFy0cOlypowCKVYhXbR9n10Cv/gkvJrT7eTNuQgFA/CYqEAOwwCj0Yzfv9\nKlmaI5UXLEWeH25DeW0MXJj+SKfFI0dcXv1u5x609mhF0YaDW6KKjbHjKYD+JXGI\nrb68j6xSlkuqUY3kEzEZ6E5Nn9uss2rVvDlUccp6en+Q3X0dgNmBu1kmwhH+5pPi\n94DkZfs0Nw4pgHBNrziGLp5/V6+eF67rHMsoIV+2HNjnogQi+dPa2MsCAwEAAaOB\nsDCBrTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zArBgNVHRAEJDAi\ngA8yMDA2MTEyNzIwMjM0MlqBDzIwMjYxMTI3MjA1MzQyWjAfBgNVHSMEGDAWgBRo\nkORnpKZTgMeGZqTx90tD+4S9bTAdBgNVHQ4EFgQUaJDkZ6SmU4DHhmak8fdLQ/uE\nvW0wHQYJKoZIhvZ9B0EABBAwDhsIVjcuMTo0LjADAgSQMA0GCSqGSIb3DQEBBQUA\nA4IBAQCT1DCw1wMgKtD5Y+iRDAUgqV8ZyntyTtSx29CW+1RaGSwMCPeyvIWonX9t\nO1KzKtvn1ISMY/YPyyYBkVBs9F8U4pN0wBOeMDpQ47RgxRzwIkSNcUesyBrJ6Zua\nAGAT/3B+XxFNSRuzFVJ7yVTav52Vr2ua2J7p8eRDjeIRRDq/r72DQnNSi6q7pynP\n9WQcCk3RvKqsnyrQ/39/2n3qse0wJcGE2jTSW3iDVuycNsMm4hH2Z0kdkquM++v/\neu6FSqdQgPCnXEqULl8FmTxSQeDNtGPPAUO6nIPcj2A781q0tHuu2guQOHXvgR1m\n0vdXcDazv/wor3ElhVsT/h5/WrQ8\n-----END CERTIFICATE-----\n\n# Issuer: CN=AAA Certificate Services O=Comodo CA Limited\n# Subject: CN=AAA Certificate Services O=Comodo CA Limited\n# Label: \"Comodo AAA Services root\"\n# Serial: 1\n# MD5 Fingerprint: 49:79:04:b0:eb:87:19:ac:47:b0:bc:11:51:9b:74:d0\n# SHA1 Fingerprint: d1:eb:23:a4:6d:17:d6:8f:d9:25:64:c2:f1:f1:60:17:64:d8:e3:49\n# SHA256 Fingerprint: d7:a7:a0:fb:5d:7e:27:31:d7:71:e9:48:4e:bc:de:f7:1d:5f:0c:3e:0a:29:48:78:2b:c8:3e:e0:ea:69:9e:f4\n-----BEGIN CERTIFICATE-----\nMIIEMjCCAxqgAwIBAgIBATANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJHQjEb\nMBkGA1UECAwSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHDAdTYWxmb3JkMRow\nGAYDVQQKDBFDb21vZG8gQ0EgTGltaXRlZDEhMB8GA1UEAwwYQUFBIENlcnRpZmlj\nYXRlIFNlcnZpY2VzMB4XDTA0MDEwMTAwMDAwMFoXDTI4MTIzMTIzNTk1OVowezEL\nMAkGA1UEBhMCR0IxGzAZBgNVBAgMEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE\nBwwHU2FsZm9yZDEaMBgGA1UECgwRQ29tb2RvIENBIExpbWl0ZWQxITAfBgNVBAMM\nGEFBQSBDZXJ0aWZpY2F0ZSBTZXJ2aWNlczCCASIwDQYJKoZIhvcNAQEBBQADggEP\nADCCAQoCggEBAL5AnfRu4ep2hxxNRUSOvkbIgwadwSr+GB+O5AL686tdUIoWMQua\nBtDFcCLNSS1UY8y2bmhGC1Pqy0wkwLxyTurxFa70VJoSCsN6sjNg4tqJVfMiWPPe\n3M/vg4aijJRPn2jymJBGhCfHdr/jzDUsi14HZGWCwEiwqJH5YZ92IFCokcdmtet4\nYgNW8IoaE+oxox6gmf049vYnMlhvB/VruPsUK6+3qszWY19zjNoFmag4qMsXeDZR\nrOme9Hg6jc8P2ULimAyrL58OAd7vn5lJ8S3frHRNG5i1R8XlKdH5kBjHYpy+g8cm\nez6KJcfA3Z3mNWgQIJ2P2N7Sw4ScDV7oL8kCAwEAAaOBwDCBvTAdBgNVHQ4EFgQU\noBEKIz6W8Qfs4q8p74Klf9AwpLQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQF\nMAMBAf8wewYDVR0fBHQwcjA4oDagNIYyaHR0cDovL2NybC5jb21vZG9jYS5jb20v\nQUFBQ2VydGlmaWNhdGVTZXJ2aWNlcy5jcmwwNqA0oDKGMGh0dHA6Ly9jcmwuY29t\nb2RvLm5ldC9BQUFDZXJ0aWZpY2F0ZVNlcnZpY2VzLmNybDANBgkqhkiG9w0BAQUF\nAAOCAQEACFb8AvCb6P+k+tZ7xkSAzk/ExfYAWMymtrwUSWgEdujm7l3sAg9g1o1Q\nGE8mTgHj5rCl7r+8dFRBv/38ErjHT1r0iWAFf2C3BUrz9vHCv8S5dIa2LX1rzNLz\nRt0vxuBqw8M0Ayx9lt1awg6nCpnBBYurDC/zXDrPbDdVCYfeU0BsWO/8tqtlbgT2\nG9w84FoVxp7Z8VlIMCFlA2zs6SFz7JsDoeA3raAVGI/6ugLOpyypEBMs1OUIJqsi\nl2D4kF501KKaU73yqWjgom7C12yxow+ev+to51byrvLjKzg6CYG1a4XXvi3tPxq3\nsmPi9WIsgtRqAEFQ8TmDn5XpNpaYbg==\n-----END CERTIFICATE-----\n\n# Issuer: CN=QuoVadis Root CA 2 O=QuoVadis Limited\n# Subject: CN=QuoVadis Root CA 2 O=QuoVadis Limited\n# Label: \"QuoVadis Root CA 2\"\n# Serial: 1289\n# MD5 Fingerprint: 5e:39:7b:dd:f8:ba:ec:82:e9:ac:62:ba:0c:54:00:2b\n# SHA1 Fingerprint: ca:3a:fb:cf:12:40:36:4b:44:b2:16:20:88:80:48:39:19:93:7c:f7\n# SHA256 Fingerprint: 85:a0:dd:7d:d7:20:ad:b7:ff:05:f8:3d:54:2b:20:9d:c7:ff:45:28:f7:d6:77:b1:83:89:fe:a5:e5:c4:9e:86\n-----BEGIN CERTIFICATE-----\nMIIFtzCCA5+gAwIBAgICBQkwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0x\nGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJv\nb3QgQ0EgMjAeFw0wNjExMjQxODI3MDBaFw0zMTExMjQxODIzMzNaMEUxCzAJBgNV\nBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYDVQQDExJRdW9W\nYWRpcyBSb290IENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCa\nGMpLlA0ALa8DKYrwD4HIrkwZhR0In6spRIXzL4GtMh6QRr+jhiYaHv5+HBg6XJxg\nFyo6dIMzMH1hVBHL7avg5tKifvVrbxi3Cgst/ek+7wrGsxDp3MJGF/hd/aTa/55J\nWpzmM+Yklvc/ulsrHHo1wtZn/qtmUIttKGAr79dgw8eTvI02kfN/+NsRE8Scd3bB\nrrcCaoF6qUWD4gXmuVbBlDePSHFjIuwXZQeVikvfj8ZaCuWw419eaxGrDPmF60Tp\n+ARz8un+XJiM9XOva7R+zdRcAitMOeGylZUtQofX1bOQQ7dsE/He3fbE+Ik/0XX1\nksOR1YqI0JDs3G3eicJlcZaLDQP9nL9bFqyS2+r+eXyt66/3FsvbzSUr5R/7mp/i\nUcw6UwxI5g69ybR2BlLmEROFcmMDBOAENisgGQLodKcftslWZvB1JdxnwQ5hYIiz\nPtGo/KPaHbDRsSNU30R2be1B2MGyIrZTHN81Hdyhdyox5C315eXbyOD/5YDXC2Og\n/zOhD7osFRXql7PSorW+8oyWHhqPHWykYTe5hnMz15eWniN9gqRMgeKh0bpnX5UH\noycR7hYQe7xFSkyyBNKr79X9DFHOUGoIMfmR2gyPZFwDwzqLID9ujWc9Otb+fVuI\nyV77zGHcizN300QyNQliBJIWENieJ0f7OyHj+OsdWwIDAQABo4GwMIGtMA8GA1Ud\nEwEB/wQFMAMBAf8wCwYDVR0PBAQDAgEGMB0GA1UdDgQWBBQahGK8SEwzJQTU7tD2\nA8QZRtGUazBuBgNVHSMEZzBlgBQahGK8SEwzJQTU7tD2A8QZRtGUa6FJpEcwRTEL\nMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMT\nElF1b1ZhZGlzIFJvb3QgQ0EgMoICBQkwDQYJKoZIhvcNAQEFBQADggIBAD4KFk2f\nBluornFdLwUvZ+YTRYPENvbzwCYMDbVHZF34tHLJRqUDGCdViXh9duqWNIAXINzn\ng/iN/Ae42l9NLmeyhP3ZRPx3UIHmfLTJDQtyU/h2BwdBR5YM++CCJpNVjP4iH2Bl\nfF/nJrP3MpCYUNQ3cVX2kiF495V5+vgtJodmVjB3pjd4M1IQWK4/YY7yarHvGH5K\nWWPKjaJW1acvvFYfzznB4vsKqBUsfU16Y8Zsl0Q80m/DShcK+JDSV6IZUaUtl0Ha\nB0+pUNqQjZRG4T7wlP0QADj1O+hA4bRuVhogzG9Yje0uRY/W6ZM/57Es3zrWIozc\nhLsib9D45MY56QSIPMO661V6bYCZJPVsAfv4l7CUW+v90m/xd2gNNWQjrLhVoQPR\nTUIZ3Ph1WVaj+ahJefivDrkRoHy3au000LYmYjgahwz46P0u05B/B5EqHdZ+XIWD\nmbA4CD/pXvk1B+TJYm5Xf6dQlfe6yJvmjqIBxdZmv3lh8zwc4bmCXF2gw+nYSL0Z\nohEUGW6yhhtoPkg3Goi3XZZenMfvJ2II4pEZXNLxId26F0KCl3GBUzGpn/Z9Yr9y\n4aOTHcyKJloJONDO1w2AFrR4pTqHTI2KpdVGl/IsELm8VCLAAVBpQ570su9t+Oza\n8eOx79+Rj1QqCyXBJhnEUhAFZdWCEOrCMc0u\n-----END CERTIFICATE-----\n\n# Issuer: CN=QuoVadis Root CA 3 O=QuoVadis Limited\n# Subject: CN=QuoVadis Root CA 3 O=QuoVadis Limited\n# Label: \"QuoVadis Root CA 3\"\n# Serial: 1478\n# MD5 Fingerprint: 31:85:3c:62:94:97:63:b9:aa:fd:89:4e:af:6f:e0:cf\n# SHA1 Fingerprint: 1f:49:14:f7:d8:74:95:1d:dd:ae:02:c0:be:fd:3a:2d:82:75:51:85\n# SHA256 Fingerprint: 18:f1:fc:7f:20:5d:f8:ad:dd:eb:7f:e0:07:dd:57:e3:af:37:5a:9c:4d:8d:73:54:6b:f4:f1:fe:d1:e1:8d:35\n-----BEGIN CERTIFICATE-----\nMIIGnTCCBIWgAwIBAgICBcYwDQYJKoZIhvcNAQEFBQAwRTELMAkGA1UEBhMCQk0x\nGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxGzAZBgNVBAMTElF1b1ZhZGlzIFJv\nb3QgQ0EgMzAeFw0wNjExMjQxOTExMjNaFw0zMTExMjQxOTA2NDRaMEUxCzAJBgNV\nBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBMaW1pdGVkMRswGQYDVQQDExJRdW9W\nYWRpcyBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDM\nV0IWVJzmmNPTTe7+7cefQzlKZbPoFog02w1ZkXTPkrgEQK0CSzGrvI2RaNggDhoB\n4hp7Thdd4oq3P5kazethq8Jlph+3t723j/z9cI8LoGe+AaJZz3HmDyl2/7FWeUUr\nH556VOijKTVopAFPD6QuN+8bv+OPEKhyq1hX51SGyMnzW9os2l2ObjyjPtr7guXd\n8lyyBTNvijbO0BNO/79KDDRMpsMhvVAEVeuxu537RR5kFd5VAYwCdrXLoT9Cabwv\nvWhDFlaJKjdhkf2mrk7AyxRllDdLkgbvBNDInIjbC3uBr7E9KsRlOni27tyAsdLT\nmZw67mtaa7ONt9XOnMK+pUsvFrGeaDsGb659n/je7Mwpp5ijJUMv7/FfJuGITfhe\nbtfZFG4ZM2mnO4SJk8RTVROhUXhA+LjJou57ulJCg54U7QVSWllWp5f8nT8KKdjc\nT5EOE7zelaTfi5m+rJsziO+1ga8bxiJTyPbH7pcUsMV8eFLI8M5ud2CEpukqdiDt\nWAEXMJPpGovgc2PZapKUSU60rUqFxKMiMPwJ7Wgic6aIDFUhWMXhOp8q3crhkODZ\nc6tsgLjoC2SToJyMGf+z0gzskSaHirOi4XCPLArlzW1oUevaPwV/izLmE1xr/l9A\n4iLItLRkT9a6fUg+qGkM17uGcclzuD87nSVL2v9A6wIDAQABo4IBlTCCAZEwDwYD\nVR0TAQH/BAUwAwEB/zCB4QYDVR0gBIHZMIHWMIHTBgkrBgEEAb5YAAMwgcUwgZMG\nCCsGAQUFBwICMIGGGoGDQW55IHVzZSBvZiB0aGlzIENlcnRpZmljYXRlIGNvbnN0\naXR1dGVzIGFjY2VwdGFuY2Ugb2YgdGhlIFF1b1ZhZGlzIFJvb3QgQ0EgMyBDZXJ0\naWZpY2F0ZSBQb2xpY3kgLyBDZXJ0aWZpY2F0aW9uIFByYWN0aWNlIFN0YXRlbWVu\ndC4wLQYIKwYBBQUHAgEWIWh0dHA6Ly93d3cucXVvdmFkaXNnbG9iYWwuY29tL2Nw\nczALBgNVHQ8EBAMCAQYwHQYDVR0OBBYEFPLAE+CCQz777i9nMpY1XNu4ywLQMG4G\nA1UdIwRnMGWAFPLAE+CCQz777i9nMpY1XNu4ywLQoUmkRzBFMQswCQYDVQQGEwJC\nTTEZMBcGA1UEChMQUXVvVmFkaXMgTGltaXRlZDEbMBkGA1UEAxMSUXVvVmFkaXMg\nUm9vdCBDQSAzggIFxjANBgkqhkiG9w0BAQUFAAOCAgEAT62gLEz6wPJv92ZVqyM0\n7ucp2sNbtrCD2dDQ4iH782CnO11gUyeim/YIIirnv6By5ZwkajGxkHon24QRiSem\nd1o417+shvzuXYO8BsbRd2sPbSQvS3pspweWyuOEn62Iix2rFo1bZhfZFvSLgNLd\n+LJ2w/w4E6oM3kJpK27zPOuAJ9v1pkQNn1pVWQvVDVJIxa6f8i+AxeoyUDUSly7B\n4f/xI4hROJ/yZlZ25w9Rl6VSDE1JUZU2Pb+iSwwQHYaZTKrzchGT5Or2m9qoXadN\nt54CrnMAyNojA+j56hl0YgCUyyIgvpSnWbWCar6ZeXqp8kokUvd0/bpO5qgdAm6x\nDYBEwa7TIzdfu4V8K5Iu6H6li92Z4b8nby1dqnuH/grdS/yO9SbkbnBCbjPsMZ57\nk8HkyWkaPcBrTiJt7qtYTcbQQcEr6k8Sh17rRdhs9ZgC06DYVYoGmRmioHfRMJ6s\nzHXug/WwYjnPbFfiTNKRCw51KBuav/0aQ/HKd/s7j2G4aSgWQgRecCocIdiP4b0j\nWy10QJLZYxkNc91pvGJHvOB0K7Lrfb5BG7XARsWhIstfTsEokt4YutUqKLsRixeT\nmJlglFwjz1onl14LBQaTNx47aTbrqZ5hHY8y2o4M1nQ+ewkk2gF3R8Q7zTSMmfXK\n4SVhM7JZG+Ju1zdXtg2pEto=\n-----END CERTIFICATE-----\n\n# Issuer: O=SECOM Trust.net OU=Security Communication RootCA1\n# Subject: O=SECOM Trust.net OU=Security Communication RootCA1\n# Label: \"Security Communication Root CA\"\n# Serial: 0\n# MD5 Fingerprint: f1:bc:63:6a:54:e0:b5:27:f5:cd:e7:1a:e3:4d:6e:4a\n# SHA1 Fingerprint: 36:b1:2b:49:f9:81:9e:d7:4c:9e:bc:38:0f:c6:56:8f:5d:ac:b2:f7\n# SHA256 Fingerprint: e7:5e:72:ed:9f:56:0e:ec:6e:b4:80:00:73:a4:3f:c3:ad:19:19:5a:39:22:82:01:78:95:97:4a:99:02:6b:6c\n-----BEGIN CERTIFICATE-----\nMIIDWjCCAkKgAwIBAgIBADANBgkqhkiG9w0BAQUFADBQMQswCQYDVQQGEwJKUDEY\nMBYGA1UEChMPU0VDT00gVHJ1c3QubmV0MScwJQYDVQQLEx5TZWN1cml0eSBDb21t\ndW5pY2F0aW9uIFJvb3RDQTEwHhcNMDMwOTMwMDQyMDQ5WhcNMjMwOTMwMDQyMDQ5\nWjBQMQswCQYDVQQGEwJKUDEYMBYGA1UEChMPU0VDT00gVHJ1c3QubmV0MScwJQYD\nVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTEwggEiMA0GCSqGSIb3\nDQEBAQUAA4IBDwAwggEKAoIBAQCzs/5/022x7xZ8V6UMbXaKL0u/ZPtM7orw8yl8\n9f/uKuDp6bpbZCKamm8sOiZpUQWZJtzVHGpxxpp9Hp3dfGzGjGdnSj74cbAZJ6kJ\nDKaVv0uMDPpVmDvY6CKhS3E4eayXkmmziX7qIWgGmBSWh9JhNrxtJ1aeV+7AwFb9\nMs+k2Y7CI9eNqPPYJayX5HA49LY6tJ07lyZDo6G8SVlyTCMwhwFY9k6+HGhWZq/N\nQV3Is00qVUarH9oe4kA92819uZKAnDfdDJZkndwi92SL32HeFZRSFaB9UslLqCHJ\nxrHty8OVYNEP8Ktw+N/LTX7s1vqr2b1/VPKl6Xn62dZ2JChzAgMBAAGjPzA9MB0G\nA1UdDgQWBBSgc0mZaNyFW2XjmygvV5+9M7wHSDALBgNVHQ8EBAMCAQYwDwYDVR0T\nAQH/BAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAaECpqLvkT115swW1F7NgE+vG\nkl3g0dNq/vu+m22/xwVtWSDEHPC32oRYAmP6SBbvT6UL90qY8j+eG61Ha2POCEfr\nUj94nK9NrvjVT8+amCoQQTlSxN3Zmw7vkwGusi7KaEIkQmywszo+zenaSMQVy+n5\nBw+SUEmK3TGXX8npN6o7WWWXlDLJs58+OmJYxUmtYg5xpTKqL8aJdkNAExNnPaJU\nJRDL8Try2frbSVa7pv6nQTXD4IhhyYjH3zYQIphZ6rBK+1YWc26sTfcioU+tHXot\nRSflMMFe8toTyyVCUZVHA4xsIcx0Qu1T/zOLjw9XARYvz6buyXAiFL39vmwLAw==\n-----END CERTIFICATE-----\n\n# Issuer: CN=XRamp Global Certification Authority O=XRamp Security Services Inc OU=www.xrampsecurity.com\n# Subject: CN=XRamp Global Certification Authority O=XRamp Security Services Inc OU=www.xrampsecurity.com\n# Label: \"XRamp Global CA Root\"\n# Serial: 107108908803651509692980124233745014957\n# MD5 Fingerprint: a1:0b:44:b3:ca:10:d8:00:6e:9d:0f:d8:0f:92:0a:d1\n# SHA1 Fingerprint: b8:01:86:d1:eb:9c:86:a5:41:04:cf:30:54:f3:4c:52:b7:e5:58:c6\n# SHA256 Fingerprint: ce:cd:dc:90:50:99:d8:da:df:c5:b1:d2:09:b7:37:cb:e2:c1:8c:fb:2c:10:c0:ff:0b:cf:0d:32:86:fc:1a:a2\n-----BEGIN CERTIFICATE-----\nMIIEMDCCAxigAwIBAgIQUJRs7Bjq1ZxN1ZfvdY+grTANBgkqhkiG9w0BAQUFADCB\ngjELMAkGA1UEBhMCVVMxHjAcBgNVBAsTFXd3dy54cmFtcHNlY3VyaXR5LmNvbTEk\nMCIGA1UEChMbWFJhbXAgU2VjdXJpdHkgU2VydmljZXMgSW5jMS0wKwYDVQQDEyRY\nUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQxMTAxMTcx\nNDA0WhcNMzUwMTAxMDUzNzE5WjCBgjELMAkGA1UEBhMCVVMxHjAcBgNVBAsTFXd3\ndy54cmFtcHNlY3VyaXR5LmNvbTEkMCIGA1UEChMbWFJhbXAgU2VjdXJpdHkgU2Vy\ndmljZXMgSW5jMS0wKwYDVQQDEyRYUmFtcCBHbG9iYWwgQ2VydGlmaWNhdGlvbiBB\ndXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCYJB69FbS6\n38eMpSe2OAtp87ZOqCwuIR1cRN8hXX4jdP5efrRKt6atH67gBhbim1vZZ3RrXYCP\nKZ2GG9mcDZhtdhAoWORlsH9KmHmf4MMxfoArtYzAQDsRhtDLooY2YKTVMIJt2W7Q\nDxIEM5dfT2Fa8OT5kavnHTu86M/0ay00fOJIYRyO82FEzG+gSqmUsE3a56k0enI4\nqEHMPJQRfevIpoy3hsvKMzvZPTeL+3o+hiznc9cKV6xkmxnr9A8ECIqsAxcZZPRa\nJSKNNCyy9mgdEm3Tih4U2sSPpuIjhdV6Db1q4Ons7Be7QhtnqiXtRYMh/MHJfNVi\nPvryxS3T/dRlAgMBAAGjgZ8wgZwwEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0P\nBAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMZPoj0GY4QJnM5i5ASs\njVy16bYbMDYGA1UdHwQvMC0wK6ApoCeGJWh0dHA6Ly9jcmwueHJhbXBzZWN1cml0\neS5jb20vWEdDQS5jcmwwEAYJKwYBBAGCNxUBBAMCAQEwDQYJKoZIhvcNAQEFBQAD\nggEBAJEVOQMBG2f7Shz5CmBbodpNl2L5JFMn14JkTpAuw0kbK5rc/Kh4ZzXxHfAR\nvbdI4xD2Dd8/0sm2qlWkSLoC295ZLhVbO50WfUfXN+pfTXYSNrsf16GBBEYgoyxt\nqZ4Bfj8pzgCT3/3JknOJiWSe5yvkHJEs0rnOfc5vMZnT5r7SHpDwCRR5XCOrTdLa\nIR9NmXmd4c8nnxCbHIgNsIpkQTG4DmyQJKSbXHGPurt+HBvbaoAPIbzp26a3QPSy\ni6mx5O+aGtA9aZnuqCij4Tyz8LIRnM98QObd50N9otg6tamN8jSZxNQQ4Qb9CYQQ\nO+7ETPTsJ3xCwnR8gooJybQDJbw=\n-----END CERTIFICATE-----\n\n# Issuer: O=The Go Daddy Group, Inc. OU=Go Daddy Class 2 Certification Authority\n# Subject: O=The Go Daddy Group, Inc. OU=Go Daddy Class 2 Certification Authority\n# Label: \"Go Daddy Class 2 CA\"\n# Serial: 0\n# MD5 Fingerprint: 91:de:06:25:ab:da:fd:32:17:0c:bb:25:17:2a:84:67\n# SHA1 Fingerprint: 27:96:ba:e6:3f:18:01:e2:77:26:1b:a0:d7:77:70:02:8f:20:ee:e4\n# SHA256 Fingerprint: c3:84:6b:f2:4b:9e:93:ca:64:27:4c:0e:c6:7c:1e:cc:5e:02:4f:fc:ac:d2:d7:40:19:35:0e:81:fe:54:6a:e4\n-----BEGIN CERTIFICATE-----\nMIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh\nMB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE\nYWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3\nMDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkGA1UEBhMCVVMxITAfBgNVBAoTGFRo\nZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28gRGFkZHkgQ2xhc3Mg\nMiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQADggEN\nADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCA\nPVYYYwhv2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6w\nwdhFJ2+qN1j3hybX2C32qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXi\nEqITLdiOr18SPaAIBQi2XKVlOARFmR6jYGB0xUGlcmIbYsUfb18aQr4CUWWoriMY\navx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmYvLEHZ6IVDd2gWMZEewo+\nYihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0OBBYEFNLE\nsNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h\n/t2oatTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5\nIEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmlj\nYXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQAD\nggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wimPQoZ+YeAEW5p5JYXMP80kWNy\nOO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKtI3lpjbi2Tc7P\nTMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ\nHmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mER\ndEr/VxqHD3VILs9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5Cuf\nReYNnyicsbkqWletNw+vHX/bvZ8=\n-----END CERTIFICATE-----\n\n# Issuer: O=Starfield Technologies, Inc. OU=Starfield Class 2 Certification Authority\n# Subject: O=Starfield Technologies, Inc. OU=Starfield Class 2 Certification Authority\n# Label: \"Starfield Class 2 CA\"\n# Serial: 0\n# MD5 Fingerprint: 32:4a:4b:bb:c8:63:69:9b:be:74:9a:c6:dd:1d:46:24\n# SHA1 Fingerprint: ad:7e:1c:28:b0:64:ef:8f:60:03:40:20:14:c3:d0:e3:37:0e:b5:8a\n# SHA256 Fingerprint: 14:65:fa:20:53:97:b8:76:fa:a6:f0:a9:95:8e:55:90:e4:0f:cc:7f:aa:4f:b7:c2:c8:67:75:21:fb:5f:b6:58\n-----BEGIN CERTIFICATE-----\nMIIEDzCCAvegAwIBAgIBADANBgkqhkiG9w0BAQUFADBoMQswCQYDVQQGEwJVUzEl\nMCMGA1UEChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMp\nU3RhcmZpZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDQw\nNjI5MTczOTE2WhcNMzQwNjI5MTczOTE2WjBoMQswCQYDVQQGEwJVUzElMCMGA1UE\nChMcU3RhcmZpZWxkIFRlY2hub2xvZ2llcywgSW5jLjEyMDAGA1UECxMpU3RhcmZp\nZWxkIENsYXNzIDIgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggEgMA0GCSqGSIb3\nDQEBAQUAA4IBDQAwggEIAoIBAQC3Msj+6XGmBIWtDBFk385N78gDGIc/oav7PKaf\n8MOh2tTYbitTkPskpD6E8J7oX+zlJ0T1KKY/e97gKvDIr1MvnsoFAZMej2YcOadN\n+lq2cwQlZut3f+dZxkqZJRRU6ybH838Z1TBwj6+wRir/resp7defqgSHo9T5iaU0\nX9tDkYI22WY8sbi5gv2cOj4QyDvvBmVmepsZGD3/cVE8MC5fvj13c7JdBmzDI1aa\nK4UmkhynArPkPw2vCHmCuDY96pzTNbO8acr1zJ3o/WSNF4Azbl5KXZnJHoe0nRrA\n1W4TNSNe35tfPe/W93bC6j67eA0cQmdrBNj41tpvi/JEoAGrAgEDo4HFMIHCMB0G\nA1UdDgQWBBS/X7fRzt0fhvRbVazc1xDCDqmI5zCBkgYDVR0jBIGKMIGHgBS/X7fR\nzt0fhvRbVazc1xDCDqmI56FspGowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0\nYXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAsTKVN0YXJmaWVsZCBD\nbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8w\nDQYJKoZIhvcNAQEFBQADggEBAAWdP4id0ckaVaGsafPzWdqbAYcaT1epoXkJKtv3\nL7IezMdeatiDh6GX70k1PncGQVhiv45YuApnP+yz3SFmH8lU+nLMPUxA2IGvd56D\neruix/U0F47ZEUD0/CwqTRV/p2JdLiXTAAsgGh1o+Re49L2L7ShZ3U0WixeDyLJl\nxy16paq8U4Zt3VekyvggQQto8PT7dL5WXXp59fkdheMtlb71cZBDzI0fmgAKhynp\nVSJYACPq4xJDKVtHCN2MQWplBqjlIapBtJUhlbl90TSrE9atvNziPTnNvT51cKEY\nWQPJIrSPnNVeKtelttQKbfi3QBFGmh95DmK/D5fs4C8fF5Q=\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert Assured ID Root CA O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert Assured ID Root CA O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert Assured ID Root CA\"\n# Serial: 17154717934120587862167794914071425081\n# MD5 Fingerprint: 87:ce:0b:7b:2a:0e:49:00:e1:58:71:9b:37:a8:93:72\n# SHA1 Fingerprint: 05:63:b8:63:0d:62:d7:5a:bb:c8:ab:1e:4b:df:b5:a8:99:b2:4d:43\n# SHA256 Fingerprint: 3e:90:99:b5:01:5e:8f:48:6c:00:bc:ea:9d:11:1e:e7:21:fa:ba:35:5a:89:bc:f1:df:69:56:1e:3d:c6:32:5c\n-----BEGIN CERTIFICATE-----\nMIIDtzCCAp+gAwIBAgIQDOfg5RfYRv6P5WD8G/AwOTANBgkqhkiG9w0BAQUFADBl\nMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\nd3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv\nb3QgQ0EwHhcNMDYxMTEwMDAwMDAwWhcNMzExMTEwMDAwMDAwWjBlMQswCQYDVQQG\nEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl\ncnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgQ0EwggEi\nMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtDhXO5EOAXLGH87dg+XESpa7c\nJpSIqvTO9SA5KFhgDPiA2qkVlTJhPLWxKISKityfCgyDF3qPkKyK53lTXDGEKvYP\nmDI2dsze3Tyoou9q+yHyUmHfnyDXH+Kx2f4YZNISW1/5WBg1vEfNoTb5a3/UsDg+\nwRvDjDPZ2C8Y/igPs6eD1sNuRMBhNZYW/lmci3Zt1/GiSw0r/wty2p5g0I6QNcZ4\nVYcgoc/lbQrISXwxmDNsIumH0DJaoroTghHtORedmTpyoeb6pNnVFzF1roV9Iq4/\nAUaG9ih5yLHa5FcXxH4cDrC0kqZWs72yl+2qp/C3xag/lRbQ/6GW6whfGHdPAgMB\nAAGjYzBhMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW\nBBRF66Kv9JLLgjEtUYunpyGd823IDzAfBgNVHSMEGDAWgBRF66Kv9JLLgjEtUYun\npyGd823IDzANBgkqhkiG9w0BAQUFAAOCAQEAog683+Lt8ONyc3pklL/3cmbYMuRC\ndWKuh+vy1dneVrOfzM4UKLkNl2BcEkxY5NM9g0lFWJc1aRqoR+pWxnmrEthngYTf\nfwk8lOa4JiwgvT2zKIn3X/8i4peEH+ll74fg38FnSbNd67IJKusm7Xi+fT8r87cm\nNW1fiQG2SVufAQWbqz0lwcy2f8Lxb4bG+mRo64EtlOtCt/qMHt1i8b5QZ7dsvfPx\nH2sMNgcWfzd8qVttevESRmCD1ycEvkvOl77DZypoEd+A5wwzZr8TDRRu838fYxAe\n+o0bJW1sj6W3YQGx0qMmoRBxna3iw/nDmVG3KwcIzi7mULKn+gpFL6Lw8g==\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert Global Root CA O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert Global Root CA O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert Global Root CA\"\n# Serial: 10944719598952040374951832963794454346\n# MD5 Fingerprint: 79:e4:a9:84:0d:7d:3a:96:d7:c0:4f:e2:43:4c:89:2e\n# SHA1 Fingerprint: a8:98:5d:3a:65:e5:e5:c4:b2:d7:d6:6d:40:c6:dd:2f:b1:9c:54:36\n# SHA256 Fingerprint: 43:48:a0:e9:44:4c:78:cb:26:5e:05:8d:5e:89:44:b4:d8:4f:96:62:bd:26:db:25:7f:89:34:a4:43:c7:01:61\n-----BEGIN CERTIFICATE-----\nMIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\nMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\nd3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\nQTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\nMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\nb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\nCSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\nnh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\nT19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\ngdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\nBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\nTLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\nDQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\nhMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\nPnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\nYSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\nCAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert High Assurance EV Root CA O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert High Assurance EV Root CA O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert High Assurance EV Root CA\"\n# Serial: 3553400076410547919724730734378100087\n# MD5 Fingerprint: d4:74:de:57:5c:39:b2:d3:9c:85:83:c5:c0:65:49:8a\n# SHA1 Fingerprint: 5f:b7:ee:06:33:e2:59:db:ad:0c:4c:9a:e6:d3:8f:1a:61:c7:dc:25\n# SHA256 Fingerprint: 74:31:e5:f4:c3:c1:ce:46:90:77:4f:0b:61:e0:54:40:88:3b:a9:a0:1e:d0:0b:a6:ab:d7:80:6e:d3:b1:18:cf\n-----BEGIN CERTIFICATE-----\nMIIDxTCCAq2gAwIBAgIQAqxcJmoLQJuPC3nyrkYldzANBgkqhkiG9w0BAQUFADBs\nMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\nd3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j\nZSBFViBSb290IENBMB4XDTA2MTExMDAwMDAwMFoXDTMxMTExMDAwMDAwMFowbDEL\nMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3\nLmRpZ2ljZXJ0LmNvbTErMCkGA1UEAxMiRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug\nRVYgUm9vdCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAMbM5XPm\n+9S75S0tMqbf5YE/yc0lSbZxKsPVlDRnogocsF9ppkCxxLeyj9CYpKlBWTrT3JTW\nPNt0OKRKzE0lgvdKpVMSOO7zSW1xkX5jtqumX8OkhPhPYlG++MXs2ziS4wblCJEM\nxChBVfvLWokVfnHoNb9Ncgk9vjo4UFt3MRuNs8ckRZqnrG0AFFoEt7oT61EKmEFB\nIk5lYYeBQVCmeVyJ3hlKV9Uu5l0cUyx+mM0aBhakaHPQNAQTXKFx01p8VdteZOE3\nhzBWBOURtCmAEvF5OYiiAhF8J2a3iLd48soKqDirCmTCv2ZdlYTBoSUeh10aUAsg\nEsxBu24LUTi4S8sCAwEAAaNjMGEwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQF\nMAMBAf8wHQYDVR0OBBYEFLE+w2kD+L9HAdSYJhoIAu9jZCvDMB8GA1UdIwQYMBaA\nFLE+w2kD+L9HAdSYJhoIAu9jZCvDMA0GCSqGSIb3DQEBBQUAA4IBAQAcGgaX3Nec\nnzyIZgYIVyHbIUf4KmeqvxgydkAQV8GK83rZEWWONfqe/EW1ntlMMUu4kehDLI6z\neM7b41N5cdblIZQB2lWHmiRk9opmzN6cN82oNLFpmyPInngiK3BD41VHMWEZ71jF\nhS9OMPagMRYjyOfiZRYzy78aG6A9+MpeizGLYAiJLQwGXFK3xPkKmNEVX58Svnw2\nYzi9RKR/5CYrCsSXaQ3pjOLAEFe4yHYSkVXySGnYvCoCWw9E1CAx2/S6cCZdkGCe\nvEsXCS+0yx5DaMkHJ8HSXPfqIbloEpw8nL+e/IBcm2PN7EeqJSdnoDfzAIJ9VNep\n+OkuE6N36B9K\n-----END CERTIFICATE-----\n\n# Issuer: CN=SwissSign Gold CA - G2 O=SwissSign AG\n# Subject: CN=SwissSign Gold CA - G2 O=SwissSign AG\n# Label: \"SwissSign Gold CA - G2\"\n# Serial: 13492815561806991280\n# MD5 Fingerprint: 24:77:d9:a8:91:d1:3b:fa:88:2d:c2:ff:f8:cd:33:93\n# SHA1 Fingerprint: d8:c5:38:8a:b7:30:1b:1b:6e:d4:7a:e6:45:25:3a:6f:9f:1a:27:61\n# SHA256 Fingerprint: 62:dd:0b:e9:b9:f5:0a:16:3e:a0:f8:e7:5c:05:3b:1e:ca:57:ea:55:c8:68:8f:64:7c:68:81:f2:c8:35:7b:95\n-----BEGIN CERTIFICATE-----\nMIIFujCCA6KgAwIBAgIJALtAHEP1Xk+wMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV\nBAYTAkNIMRUwEwYDVQQKEwxTd2lzc1NpZ24gQUcxHzAdBgNVBAMTFlN3aXNzU2ln\nbiBHb2xkIENBIC0gRzIwHhcNMDYxMDI1MDgzMDM1WhcNMzYxMDI1MDgzMDM1WjBF\nMQswCQYDVQQGEwJDSDEVMBMGA1UEChMMU3dpc3NTaWduIEFHMR8wHQYDVQQDExZT\nd2lzc1NpZ24gR29sZCBDQSAtIEcyMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC\nCgKCAgEAr+TufoskDhJuqVAtFkQ7kpJcyrhdhJJCEyq8ZVeCQD5XJM1QiyUqt2/8\n76LQwB8CJEoTlo8jE+YoWACjR8cGp4QjK7u9lit/VcyLwVcfDmJlD909Vopz2q5+\nbbqBHH5CjCA12UNNhPqE21Is8w4ndwtrvxEvcnifLtg+5hg3Wipy+dpikJKVyh+c\n6bM8K8vzARO/Ws/BtQpgvd21mWRTuKCWs2/iJneRjOBiEAKfNA+k1ZIzUd6+jbqE\nemA8atufK+ze3gE/bk3lUIbLtK/tREDFylqM2tIrfKjuvqblCqoOpd8FUrdVxyJd\nMmqXl2MT28nbeTZ7hTpKxVKJ+STnnXepgv9VHKVxaSvRAiTysybUa9oEVeXBCsdt\nMDeQKuSeFDNeFhdVxVu1yzSJkvGdJo+hB9TGsnhQ2wwMC3wLjEHXuendjIj3o02y\nMszYF9rNt85mndT9Xv+9lz4pded+p2JYryU0pUHHPbwNUMoDAw8IWh+Vc3hiv69y\nFGkOpeUDDniOJihC8AcLYiAQZzlG+qkDzAQ4embvIIO1jEpWjpEA/I5cgt6IoMPi\naG59je883WX0XaxR7ySArqpWl2/5rX3aYT+YdzylkbYcjCbaZaIJbcHiVOO5ykxM\ngI93e2CaHt+28kgeDrpOVG2Y4OGiGqJ3UM/EY5LsRxmd6+ZrzsECAwEAAaOBrDCB\nqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUWyV7\nlqRlUX64OfPAeGZe6Drn8O4wHwYDVR0jBBgwFoAUWyV7lqRlUX64OfPAeGZe6Drn\n8O4wRgYDVR0gBD8wPTA7BglghXQBWQECAQEwLjAsBggrBgEFBQcCARYgaHR0cDov\nL3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIBACe6\n45R88a7A3hfm5djV9VSwg/S7zV4Fe0+fdWavPOhWfvxyeDgD2StiGwC5+OlgzczO\nUYrHUDFu4Up+GC9pWbY9ZIEr44OE5iKHjn3g7gKZYbge9LgriBIWhMIxkziWMaa5\nO1M/wySTVltpkuzFwbs4AOPsF6m43Md8AYOfMke6UiI0HTJ6CVanfCU2qT1L2sCC\nbwq7EsiHSycR+R4tx5M/nttfJmtS2S6K8RTGRI0Vqbe/vd6mGu6uLftIdxf+u+yv\nGPUqUfA5hJeVbG4bwyvEdGB5JbAKJ9/fXtI5z0V9QkvfsywexcZdylU6oJxpmo/a\n77KwPJ+HbBIrZXAVUjEaJM9vMSNQH4xPjyPDdEFjHFWoFN0+4FFQz/EbMFYOkrCC\nhdiDyyJkvC24JdVUorgG6q2SpCSgwYa1ShNqR88uC1aVVMvOmttqtKay20EIhid3\n92qgQmwLOM7XdVAyksLfKzAiSNDVQTglXaTpXZ/GlHXQRf0wl0OPkKsKx4ZzYEpp\nLd6leNcG2mqeSz53OiATIgHQv2ieY2BrNU0LbbqhPcCT4H8js1WtciVORvnSFu+w\nZMEBnunKoGqYDs/YYPIvSbjkQuE4NRb0yG5P94FW6LqjviOvrv1vA+ACOzB2+htt\nQc8Bsem4yWb02ybzOqR08kkkW8mw0FfB+j564ZfJ\n-----END CERTIFICATE-----\n\n# Issuer: CN=SwissSign Silver CA - G2 O=SwissSign AG\n# Subject: CN=SwissSign Silver CA - G2 O=SwissSign AG\n# Label: \"SwissSign Silver CA - G2\"\n# Serial: 5700383053117599563\n# MD5 Fingerprint: e0:06:a1:c9:7d:cf:c9:fc:0d:c0:56:75:96:d8:62:13\n# SHA1 Fingerprint: 9b:aa:e5:9f:56:ee:21:cb:43:5a:be:25:93:df:a7:f0:40:d1:1d:cb\n# SHA256 Fingerprint: be:6c:4d:a2:bb:b9:ba:59:b6:f3:93:97:68:37:42:46:c3:c0:05:99:3f:a9:8f:02:0d:1d:ed:be:d4:8a:81:d5\n-----BEGIN CERTIFICATE-----\nMIIFvTCCA6WgAwIBAgIITxvUL1S7L0swDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UE\nBhMCQ0gxFTATBgNVBAoTDFN3aXNzU2lnbiBBRzEhMB8GA1UEAxMYU3dpc3NTaWdu\nIFNpbHZlciBDQSAtIEcyMB4XDTA2MTAyNTA4MzI0NloXDTM2MTAyNTA4MzI0Nlow\nRzELMAkGA1UEBhMCQ0gxFTATBgNVBAoTDFN3aXNzU2lnbiBBRzEhMB8GA1UEAxMY\nU3dpc3NTaWduIFNpbHZlciBDQSAtIEcyMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A\nMIICCgKCAgEAxPGHf9N4Mfc4yfjDmUO8x/e8N+dOcbpLj6VzHVxumK4DV644N0Mv\nFz0fyM5oEMF4rhkDKxD6LHmD9ui5aLlV8gREpzn5/ASLHvGiTSf5YXu6t+WiE7br\nYT7QbNHm+/pe7R20nqA1W6GSy/BJkv6FCgU+5tkL4k+73JU3/JHpMjUi0R86TieF\nnbAVlDLaYQ1HTWBCrpJH6INaUFjpiou5XaHc3ZlKHzZnu0jkg7Y360g6rw9njxcH\n6ATK72oxh9TAtvmUcXtnZLi2kUpCe2UuMGoM9ZDulebyzYLs2aFK7PayS+VFheZt\neJMELpyCbTapxDFkH4aDCyr0NQp4yVXPQbBH6TCfmb5hqAaEuSh6XzjZG6k4sIN/\nc8HDO0gqgg8hm7jMqDXDhBuDsz6+pJVpATqJAHgE2cn0mRmrVn5bi4Y5FZGkECwJ\nMoBgs5PAKrYYC51+jUnyEEp/+dVGLxmSo5mnJqy7jDzmDrxHB9xzUfFwZC8I+bRH\nHTBsROopN4WSaGa8gzj+ezku01DwH/teYLappvonQfGbGHLy9YR0SslnxFSuSGTf\njNFusB3hB48IHpmccelM2KX3RxIfdNFRnobzwqIjQAtz20um53MGjMGg6cFZrEb6\n5i/4z3GcRm25xBWNOHkDRUjvxF3XCO6HOSKGsg0PWEP3calILv3q1h8CAwEAAaOB\nrDCBqTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU\nF6DNweRBtjpbO8tFnb0cwpj6hlgwHwYDVR0jBBgwFoAUF6DNweRBtjpbO8tFnb0c\nwpj6hlgwRgYDVR0gBD8wPTA7BglghXQBWQEDAQEwLjAsBggrBgEFBQcCARYgaHR0\ncDovL3JlcG9zaXRvcnkuc3dpc3NzaWduLmNvbS8wDQYJKoZIhvcNAQEFBQADggIB\nAHPGgeAn0i0P4JUw4ppBf1AsX19iYamGamkYDHRJ1l2E6kFSGG9YrVBWIGrGvShp\nWJHckRE1qTodvBqlYJ7YH39FkWnZfrt4csEGDyrOj4VwYaygzQu4OSlWhDJOhrs9\nxCrZ1x9y7v5RoSJBsXECYxqCsGKrXlcSH9/L3XWgwF15kIwb4FDm3jH+mHtwX6WQ\n2K34ArZv02DdQEsixT2tOnqfGhpHkXkzuoLcMmkDlm4fS/Bx/uNncqCxv1yL5PqZ\nIseEuRuNI5c/7SXgz2W79WEE790eslpBIlqhn10s6FvJbakMDHiqYMZWjwFaDGi8\naRl5xB9+lwW/xekkUV7U1UtT7dkjWjYDZaPBA61BMPNGG4WQr2W11bHkFlt4dR2X\nem1ZqSqPe97Dh4kQmUlzeMg9vVE1dCrV8X5pGyq7O70luJpaPXJhkGaH7gzWTdQR\ndAtq/gsD/KNVV4n+SsuuWxcFyPKNIzFTONItaj+CuY0IavdeQXRuwxF+B6wpYJE/\nOMpXEA29MC/HpeZBoNquBYeaoKRlbEwJDIm6uNO5wJOKMPqN5ZprFQFOZ6raYlY+\nhAhm0sQ2fac+EPyI4NSA5QC9qvNOBqN6avlicuMJT+ubDgEj8Z+7fNzcbBGXJbLy\ntGMU0gYqZ4yD9c7qB9iaah7s5Aq7KkzrCWA5zspi2C5u\n-----END CERTIFICATE-----\n\n# Issuer: CN=SecureTrust CA O=SecureTrust Corporation\n# Subject: CN=SecureTrust CA O=SecureTrust Corporation\n# Label: \"SecureTrust CA\"\n# Serial: 17199774589125277788362757014266862032\n# MD5 Fingerprint: dc:32:c3:a7:6d:25:57:c7:68:09:9d:ea:2d:a9:a2:d1\n# SHA1 Fingerprint: 87:82:c6:c3:04:35:3b:cf:d2:96:92:d2:59:3e:7d:44:d9:34:ff:11\n# SHA256 Fingerprint: f1:c1:b5:0a:e5:a2:0d:d8:03:0e:c9:f6:bc:24:82:3d:d3:67:b5:25:57:59:b4:e7:1b:61:fc:e9:f7:37:5d:73\n-----BEGIN CERTIFICATE-----\nMIIDuDCCAqCgAwIBAgIQDPCOXAgWpa1Cf/DrJxhZ0DANBgkqhkiG9w0BAQUFADBI\nMQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24x\nFzAVBgNVBAMTDlNlY3VyZVRydXN0IENBMB4XDTA2MTEwNzE5MzExOFoXDTI5MTIz\nMTE5NDA1NVowSDELMAkGA1UEBhMCVVMxIDAeBgNVBAoTF1NlY3VyZVRydXN0IENv\ncnBvcmF0aW9uMRcwFQYDVQQDEw5TZWN1cmVUcnVzdCBDQTCCASIwDQYJKoZIhvcN\nAQEBBQADggEPADCCAQoCggEBAKukgeWVzfX2FI7CT8rU4niVWJxB4Q2ZQCQXOZEz\nZum+4YOvYlyJ0fwkW2Gz4BERQRwdbvC4u/jep4G6pkjGnx29vo6pQT64lO0pGtSO\n0gMdA+9tDWccV9cGrcrI9f4Or2YlSASWC12juhbDCE/RRvgUXPLIXgGZbf2IzIao\nwW8xQmxSPmjL8xk037uHGFaAJsTQ3MBv396gwpEWoGQRS0S8Hvbn+mPeZqx2pHGj\n7DaUaHp3pLHnDi+BeuK1cobvomuL8A/b01k/unK8RCSc43Oz969XL0Imnal0ugBS\n8kvNU3xHCzaFDmapCJcWNFfBZveA4+1wVMeT4C4oFVmHursCAwEAAaOBnTCBmjAT\nBgkrBgEEAYI3FAIEBh4EAEMAQTALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB\n/zAdBgNVHQ4EFgQUQjK2FvoE/f5dS3rD/fdMQB1aQ68wNAYDVR0fBC0wKzApoCeg\nJYYjaHR0cDovL2NybC5zZWN1cmV0cnVzdC5jb20vU1RDQS5jcmwwEAYJKwYBBAGC\nNxUBBAMCAQAwDQYJKoZIhvcNAQEFBQADggEBADDtT0rhWDpSclu1pqNlGKa7UTt3\n6Z3q059c4EVlew3KW+JwULKUBRSuSceNQQcSc5R+DCMh/bwQf2AQWnL1mA6s7Ll/\n3XpvXdMc9P+IBWlCqQVxyLesJugutIxq/3HcuLHfmbx8IVQr5Fiiu1cprp6poxkm\nD5kuCLDv/WnPmRoJjeOnnyvJNjR7JLN4TJUXpAYmHrZkUjZfYGfZnMUFdAvnZyPS\nCPyI6a6Lf+Ew9Dd+/cYy2i2eRDAwbO4H3tI0/NL/QPZL9GZGBlSm8jIKYyYwa5vR\n3ItHuuG51WLQoqD0ZwV4KWMabwTW+MZMo5qxN7SN5ShLHZ4swrhovO0C7jE=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Secure Global CA O=SecureTrust Corporation\n# Subject: CN=Secure Global CA O=SecureTrust Corporation\n# Label: \"Secure Global CA\"\n# Serial: 9751836167731051554232119481456978597\n# MD5 Fingerprint: cf:f4:27:0d:d4:ed:dc:65:16:49:6d:3d:da:bf:6e:de\n# SHA1 Fingerprint: 3a:44:73:5a:e5:81:90:1f:24:86:61:46:1e:3b:9c:c4:5f:f5:3a:1b\n# SHA256 Fingerprint: 42:00:f5:04:3a:c8:59:0e:bb:52:7d:20:9e:d1:50:30:29:fb:cb:d4:1c:a1:b5:06:ec:27:f1:5a:de:7d:ac:69\n-----BEGIN CERTIFICATE-----\nMIIDvDCCAqSgAwIBAgIQB1YipOjUiolN9BPI8PjqpTANBgkqhkiG9w0BAQUFADBK\nMQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3QgQ29ycG9yYXRpb24x\nGTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwgQ0EwHhcNMDYxMTA3MTk0MjI4WhcNMjkx\nMjMxMTk1MjA2WjBKMQswCQYDVQQGEwJVUzEgMB4GA1UEChMXU2VjdXJlVHJ1c3Qg\nQ29ycG9yYXRpb24xGTAXBgNVBAMTEFNlY3VyZSBHbG9iYWwgQ0EwggEiMA0GCSqG\nSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvNS7YrGxVaQZx5RNoJLNP2MwhR/jxYDiJ\niQPpvepeRlMJ3Fz1Wuj3RSoC6zFh1ykzTM7HfAo3fg+6MpjhHZevj8fcyTiW89sa\n/FHtaMbQbqR8JNGuQsiWUGMu4P51/pinX0kuleM5M2SOHqRfkNJnPLLZ/kG5VacJ\njnIFHovdRIWCQtBJwB1g8NEXLJXr9qXBkqPFwqcIYA1gBBCWeZ4WNOaptvolRTnI\nHmX5k/Wq8VLcmZg9pYYaDDUz+kulBAYVHDGA76oYa8J719rO+TMg1fW9ajMtgQT7\nsFzUnKPiXB3jqUJ1XnvUd+85VLrJChgbEplJL4hL/VBi0XPnj3pDAgMBAAGjgZ0w\ngZowEwYJKwYBBAGCNxQCBAYeBABDAEEwCwYDVR0PBAQDAgGGMA8GA1UdEwEB/wQF\nMAMBAf8wHQYDVR0OBBYEFK9EBMJBfkiD2045AuzshHrmzsmkMDQGA1UdHwQtMCsw\nKaAnoCWGI2h0dHA6Ly9jcmwuc2VjdXJldHJ1c3QuY29tL1NHQ0EuY3JsMBAGCSsG\nAQQBgjcVAQQDAgEAMA0GCSqGSIb3DQEBBQUAA4IBAQBjGghAfaReUw132HquHw0L\nURYD7xh8yOOvaliTFGCRsoTciE6+OYo68+aCiV0BN7OrJKQVDpI1WkpEXk5X+nXO\nH0jOZvQ8QCaSmGwb7iRGDBezUqXbpZGRzzfTb+cnCDpOGR86p1hcF895P4vkp9Mm\nI50mD1hp/Ed+stCNi5O/KU9DaXR2Z0vPB4zmAve14bRDtUstFJ/53CYNv6ZHdAbY\niNE6KTCEztI5gGIbqMdXSbxqVVFnFUq+NQfk1XWYN3kwFNspnWzFacxHVaIw98xc\nf8LDmBxrThaA63p4ZUWiABqvDA1VZDRIuJK58bRQKfJPIx/abKwfROHdI3hRW8cW\n-----END CERTIFICATE-----\n\n# Issuer: CN=COMODO Certification Authority O=COMODO CA Limited\n# Subject: CN=COMODO Certification Authority O=COMODO CA Limited\n# Label: \"COMODO Certification Authority\"\n# Serial: 104350513648249232941998508985834464573\n# MD5 Fingerprint: 5c:48:dc:f7:42:72:ec:56:94:6d:1c:cc:71:35:80:75\n# SHA1 Fingerprint: 66:31:bf:9e:f7:4f:9e:b6:c9:d5:a6:0c:ba:6a:be:d1:f7:bd:ef:7b\n# SHA256 Fingerprint: 0c:2c:d6:3d:f7:80:6f:a3:99:ed:e8:09:11:6b:57:5b:f8:79:89:f0:65:18:f9:80:8c:86:05:03:17:8b:af:66\n-----BEGIN CERTIFICATE-----\nMIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCB\ngTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G\nA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNV\nBAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEyMDEwMDAw\nMDBaFw0yOTEyMzEyMzU5NTlaMIGBMQswCQYDVQQGEwJHQjEbMBkGA1UECBMSR3Jl\nYXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFDT01P\nRE8gQ0EgTGltaXRlZDEnMCUGA1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0\naG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ECLi3LjkRv3\nUcEbVASY06m/weaKXTuH+7uIzg3jLz8GlvCiKVCZrts7oVewdFFxze1CkU1B/qnI\n2GqGd0S7WWaXUF601CxwRM/aN5VCaTwwxHGzUvAhTaHYujl8HJ6jJJ3ygxaYqhZ8\nQ5sVW7euNJH+1GImGEaaP+vB+fGQV+useg2L23IwambV4EajcNxo2f8ESIl33rXp\n+2dtQem8Ob0y2WIC8bGoPW43nOIv4tOiJovGuFVDiOEjPqXSJDlqR6sA1KGzqSX+\nDT+nHbrTUcELpNqsOO9VUCQFZUaTNE8tja3G1CEZ0o7KBWFxB3NH5YoZEr0ETc5O\nnKVIrLsm9wIDAQABo4GOMIGLMB0GA1UdDgQWBBQLWOWLxkwVN6RAqTCpIb5HNlpW\n/zAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zBJBgNVHR8EQjBAMD6g\nPKA6hjhodHRwOi8vY3JsLmNvbW9kb2NhLmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9u\nQXV0aG9yaXR5LmNybDANBgkqhkiG9w0BAQUFAAOCAQEAPpiem/Yb6dc5t3iuHXIY\nSdOH5EOC6z/JqvWote9VfCFSZfnVDeFs9D6Mk3ORLgLETgdxb8CPOGEIqB6BCsAv\nIC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/\nRxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4\nzJVSk/BwJVmcIGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5dd\nBA6+C4OmF4O5MBKgxTMVBbkN+8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IB\nZQ==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Network Solutions Certificate Authority O=Network Solutions L.L.C.\n# Subject: CN=Network Solutions Certificate Authority O=Network Solutions L.L.C.\n# Label: \"Network Solutions Certificate Authority\"\n# Serial: 116697915152937497490437556386812487904\n# MD5 Fingerprint: d3:f3:a6:16:c0:fa:6b:1d:59:b1:2d:96:4d:0e:11:2e\n# SHA1 Fingerprint: 74:f8:a3:c3:ef:e7:b3:90:06:4b:83:90:3c:21:64:60:20:e5:df:ce\n# SHA256 Fingerprint: 15:f0:ba:00:a3:ac:7a:f3:ac:88:4c:07:2b:10:11:a0:77:bd:77:c0:97:f4:01:64:b2:f8:59:8a:bd:83:86:0c\n-----BEGIN CERTIFICATE-----\nMIID5jCCAs6gAwIBAgIQV8szb8JcFuZHFhfjkDFo4DANBgkqhkiG9w0BAQUFADBi\nMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMu\nMTAwLgYDVQQDEydOZXR3b3JrIFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3Jp\ndHkwHhcNMDYxMjAxMDAwMDAwWhcNMjkxMjMxMjM1OTU5WjBiMQswCQYDVQQGEwJV\nUzEhMB8GA1UEChMYTmV0d29yayBTb2x1dGlvbnMgTC5MLkMuMTAwLgYDVQQDEydO\nZXR3b3JrIFNvbHV0aW9ucyBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkwggEiMA0GCSqG\nSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDkvH6SMG3G2I4rC7xGzuAnlt7e+foS0zwz\nc7MEL7xxjOWftiJgPl9dzgn/ggwbmlFQGiaJ3dVhXRncEg8tCqJDXRfQNJIg6nPP\nOCwGJgl6cvf6UDL4wpPTaaIjzkGxzOTVHzbRijr4jGPiFFlp7Q3Tf2vouAPlT2rl\nmGNpSAW+Lv8ztumXWWn4Zxmuk2GWRBXTcrA/vGp97Eh/jcOrqnErU2lBUzS1sLnF\nBgrEsEX1QV1uiUV7PTsmjHTC5dLRfbIR1PtYMiKagMnc/Qzpf14Dl847ABSHJ3A4\nqY5usyd2mFHgBeMhqxrVhSI8KbWaFsWAqPS7azCPL0YCorEMIuDTAgMBAAGjgZcw\ngZQwHQYDVR0OBBYEFCEwyfsA106Y2oeqKtCnLrFAMadMMA4GA1UdDwEB/wQEAwIB\nBjAPBgNVHRMBAf8EBTADAQH/MFIGA1UdHwRLMEkwR6BFoEOGQWh0dHA6Ly9jcmwu\nbmV0c29sc3NsLmNvbS9OZXR3b3JrU29sdXRpb25zQ2VydGlmaWNhdGVBdXRob3Jp\ndHkuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQC7rkvnt1frf6ott3NHhWrB5KUd5Oc8\n6fRZZXe1eltajSU24HqXLjjAV2CDmAaDn7l2em5Q4LqILPxFzBiwmZVRDuwduIj/\nh1AcgsLj4DKAv6ALR8jDMe+ZZzKATxcheQxpXN5eNK4CtSbqUN9/GGUsyfJj4akH\n/nxxH2szJGoeBfcFaMBqEssuXmHLrijTfsK0ZpEmXzwuJF/LWA/rKOyvEZbz3Htv\nwKeI8lN3s2Berq4o2jUsbzRF0ybh3uxbTydrFny9RAQYgrOJeRcQcT16ohZO9QHN\npGxlaKFJdlxDydi8NmdspZS11My5vWo1ViHe2MPr+8ukYEywVaCge1ey\n-----END CERTIFICATE-----\n\n# Issuer: CN=COMODO ECC Certification Authority O=COMODO CA Limited\n# Subject: CN=COMODO ECC Certification Authority O=COMODO CA Limited\n# Label: \"COMODO ECC Certification Authority\"\n# Serial: 41578283867086692638256921589707938090\n# MD5 Fingerprint: 7c:62:ff:74:9d:31:53:5e:68:4a:d5:78:aa:1e:bf:23\n# SHA1 Fingerprint: 9f:74:4e:9f:2b:4d:ba:ec:0f:31:2c:50:b6:56:3b:8e:2d:93:c3:11\n# SHA256 Fingerprint: 17:93:92:7a:06:14:54:97:89:ad:ce:2f:8f:34:f7:f0:b6:6d:0f:3a:e3:a3:b8:4d:21:ec:15:db:ba:4f:ad:c7\n-----BEGIN CERTIFICATE-----\nMIICiTCCAg+gAwIBAgIQH0evqmIAcFBUTAGem2OZKjAKBggqhkjOPQQDAzCBhTEL\nMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UE\nBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMT\nIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwMzA2MDAw\nMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdy\nZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09N\nT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBFQ0MgQ2VydGlmaWNhdGlv\nbiBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQDR3svdcmCFYX7deSR\nFtSrYpn1PlILBs5BAH+X4QokPB0BBO490o0JlwzgdeT6+3eKKvUDYEs2ixYjFq0J\ncfRK9ChQtP6IHG4/bC8vCVlbpVsLM5niwz2J+Wos77LTBumjQjBAMB0GA1UdDgQW\nBBR1cacZSBm8nZ3qQUfflMRId5nTeTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/\nBAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjEA7wNbeqy3eApyt4jf/7VGFAkK+qDm\nfQjGGoe9GKhzvSbKYAydzpmfz1wPMOG+FDHqAjAU9JM8SaczepBGR7NjfRObTrdv\nGDeAU/7dIOA1mjbRxwG55tzd8/8dLDoWV9mSOdY=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certigna O=Dhimyotis\n# Subject: CN=Certigna O=Dhimyotis\n# Label: \"Certigna\"\n# Serial: 18364802974209362175\n# MD5 Fingerprint: ab:57:a6:5b:7d:42:82:19:b5:d8:58:26:28:5e:fd:ff\n# SHA1 Fingerprint: b1:2e:13:63:45:86:a4:6f:1a:b2:60:68:37:58:2d:c4:ac:fd:94:97\n# SHA256 Fingerprint: e3:b6:a2:db:2e:d7:ce:48:84:2f:7a:c5:32:41:c7:b7:1d:54:14:4b:fb:40:c1:1f:3f:1d:0b:42:f5:ee:a1:2d\n-----BEGIN CERTIFICATE-----\nMIIDqDCCApCgAwIBAgIJAP7c4wEPyUj/MA0GCSqGSIb3DQEBBQUAMDQxCzAJBgNV\nBAYTAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hMB4X\nDTA3MDYyOTE1MTMwNVoXDTI3MDYyOTE1MTMwNVowNDELMAkGA1UEBhMCRlIxEjAQ\nBgNVBAoMCURoaW15b3RpczERMA8GA1UEAwwIQ2VydGlnbmEwggEiMA0GCSqGSIb3\nDQEBAQUAA4IBDwAwggEKAoIBAQDIaPHJ1tazNHUmgh7stL7qXOEm7RFHYeGifBZ4\nQCHkYJ5ayGPhxLGWkv8YbWkj4Sti993iNi+RB7lIzw7sebYs5zRLcAglozyHGxny\ngQcPOJAZ0xH+hrTy0V4eHpbNgGzOOzGTtvKg0KmVEn2lmsxryIRWijOp5yIVUxbw\nzBfsV1/pogqYCd7jX5xv3EjjhQsVWqa6n6xI4wmy9/Qy3l40vhx4XUJbzg4ij02Q\n130yGLMLLGq/jj8UEYkgDncUtT2UCIf3JR7VsmAA7G8qKCVuKj4YYxclPz5EIBb2\nJsglrgVKtOdjLPOMFlN+XPsRGgjBRmKfIrjxwo1p3Po6WAbfAgMBAAGjgbwwgbkw\nDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUGu3+QTmQtCRZvgHyUtVF9lo53BEw\nZAYDVR0jBF0wW4AUGu3+QTmQtCRZvgHyUtVF9lo53BGhOKQ2MDQxCzAJBgNVBAYT\nAkZSMRIwEAYDVQQKDAlEaGlteW90aXMxETAPBgNVBAMMCENlcnRpZ25hggkA/tzj\nAQ/JSP8wDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIBAQQEAwIABzANBgkqhkiG\n9w0BAQUFAAOCAQEAhQMeknH2Qq/ho2Ge6/PAD/Kl1NqV5ta+aDY9fm4fTIrv0Q8h\nbV6lUmPOEvjvKtpv6zf+EwLHyzs+ImvaYS5/1HI93TDhHkxAGYwP15zRgzB7mFnc\nfca5DClMoTOi62c6ZYTTluLtdkVwj7Ur3vkj1kluPBS1xp81HlDQwY9qcEQCYsuu\nHWhBp6pX6FOqB9IG9tUUBguRA3UsbHK1YZWaDYu5Def131TN3ubY1gkIl2PlwS6w\nt0QmwCbAr1UwnjvVNioZBPRcHv/PLLf/0P2HQBHVESO7SMAhqaQoLf0V+LBOK/Qw\nWyH8EZE0vkHve52Xdf+XlcCWWC/qu0bXu+TZLg==\n-----END CERTIFICATE-----\n\n# Issuer: O=Chunghwa Telecom Co., Ltd. OU=ePKI Root Certification Authority\n# Subject: O=Chunghwa Telecom Co., Ltd. OU=ePKI Root Certification Authority\n# Label: \"ePKI Root Certification Authority\"\n# Serial: 28956088682735189655030529057352760477\n# MD5 Fingerprint: 1b:2e:00:ca:26:06:90:3d:ad:fe:6f:15:68:d3:6b:b3\n# SHA1 Fingerprint: 67:65:0d:f1:7e:8e:7e:5b:82:40:a4:f4:56:4b:cf:e2:3d:69:c6:f0\n# SHA256 Fingerprint: c0:a6:f4:dc:63:a2:4b:fd:cf:54:ef:2a:6a:08:2a:0a:72:de:35:80:3e:2f:f5:ff:52:7a:e5:d8:72:06:df:d5\n-----BEGIN CERTIFICATE-----\nMIIFsDCCA5igAwIBAgIQFci9ZUdcr7iXAF7kBtK8nTANBgkqhkiG9w0BAQUFADBe\nMQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0\nZC4xKjAoBgNVBAsMIWVQS0kgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAe\nFw0wNDEyMjAwMjMxMjdaFw0zNDEyMjAwMjMxMjdaMF4xCzAJBgNVBAYTAlRXMSMw\nIQYDVQQKDBpDaHVuZ2h3YSBUZWxlY29tIENvLiwgTHRkLjEqMCgGA1UECwwhZVBL\nSSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0BAQEF\nAAOCAg8AMIICCgKCAgEA4SUP7o3biDN1Z82tH306Tm2d0y8U82N0ywEhajfqhFAH\nSyZbCUNsIZ5qyNUD9WBpj8zwIuQf5/dqIjG3LBXy4P4AakP/h2XGtRrBp0xtInAh\nijHyl3SJCRImHJ7K2RKilTza6We/CKBk49ZCt0Xvl/T29de1ShUCWH2YWEtgvM3X\nDZoTM1PRYfl61dd4s5oz9wCGzh1NlDivqOx4UXCKXBCDUSH3ET00hl7lSM2XgYI1\nTBnsZfZrxQWh7kcT1rMhJ5QQCtkkO7q+RBNGMD+XPNjX12ruOzjjK9SXDrkb5wdJ\nfzcq+Xd4z1TtW0ado4AOkUPB1ltfFLqfpo0kR0BZv3I4sjZsN/+Z0V0OWQqraffA\nsgRFelQArr5T9rXn4fg8ozHSqf4hUmTFpmfwdQcGlBSBVcYn5AGPF8Fqcde+S/uU\nWH1+ETOxQvdibBjWzwloPn9s9h6PYq2lY9sJpx8iQkEeb5mKPtf5P0B6ebClAZLS\nnT0IFaUQAS2zMnaolQ2zepr7BxB4EW/hj8e6DyUadCrlHJhBmd8hh+iVBmoKs2pH\ndmX2Os+PYhcZewoozRrSgx4hxyy/vv9haLdnG7t4TY3OZ+XkwY63I2binZB1NJip\nNiuKmpS5nezMirH4JYlcWrYvjB9teSSnUmjDhDXiZo1jDiVN1Rmy5nk3pyKdVDEC\nAwEAAaNqMGgwHQYDVR0OBBYEFB4M97Zn8uGSJglFwFU5Lnc/QkqiMAwGA1UdEwQF\nMAMBAf8wOQYEZyoHAAQxMC8wLQIBADAJBgUrDgMCGgUAMAcGBWcqAwAABBRFsMLH\nClZ87lt4DJX5GFPBphzYEDANBgkqhkiG9w0BAQUFAAOCAgEACbODU1kBPpVJufGB\nuvl2ICO1J2B01GqZNF5sAFPZn/KmsSQHRGoqxqWOeBLoR9lYGxMqXnmbnwoqZ6Yl\nPwZpVnPDimZI+ymBV3QGypzqKOg4ZyYr8dW1P2WT+DZdjo2NQCCHGervJ8A9tDkP\nJXtoUHRVnAxZfVo9QZQlUgjgRywVMRnVvwdVxrsStZf0X4OFunHB2WyBEXYKCrC/\ngpf36j36+uwtqSiUO1bd0lEursC9CBWMd1I0ltabrNMdjmEPNXubrjlpC2JgQCA2\nj6/7Nu4tCEoduL+bXPjqpRugc6bY+G7gMwRfaKonh+3ZwZCc7b3jajWvY9+rGNm6\n5ulK6lCKD2GTHuItGeIwlDWSXQ62B68ZgI9HkFFLLk3dheLSClIKF5r8GrBQAuUB\no2M3IUxExJtRmREOc5wGj1QupyheRDmHVi03vYVElOEMSyycw5KFNGHLD7ibSkNS\n/jQ6fbjpKdx2qcgw+BRxgMYeNkh0IkFch4LoGHGLQYlE535YW6i4jRPpp2zDR+2z\nGp1iro2C6pSe3VkQw63d4k3jMdXH7OjysP6SHhYKGvzZ8/gntsm+HbRsZJB/9OTE\nW9c3rkIO3aQab3yIVMUWbuF6aC74Or8NpDyJO3inTmODBCEIZ43ygknQW/2xzQ+D\nhNQ+IIX3Sj0rnP0qCglN6oH4EZw=\n-----END CERTIFICATE-----\n\n# Issuer: O=certSIGN OU=certSIGN ROOT CA\n# Subject: O=certSIGN OU=certSIGN ROOT CA\n# Label: \"certSIGN ROOT CA\"\n# Serial: 35210227249154\n# MD5 Fingerprint: 18:98:c0:d6:e9:3a:fc:f9:b0:f5:0c:f7:4b:01:44:17\n# SHA1 Fingerprint: fa:b7:ee:36:97:26:62:fb:2d:b0:2a:f6:bf:03:fd:e8:7c:4b:2f:9b\n# SHA256 Fingerprint: ea:a9:62:c4:fa:4a:6b:af:eb:e4:15:19:6d:35:1c:cd:88:8d:4f:53:f3:fa:8a:e6:d7:c4:66:a9:4e:60:42:bb\n-----BEGIN CERTIFICATE-----\nMIIDODCCAiCgAwIBAgIGIAYFFnACMA0GCSqGSIb3DQEBBQUAMDsxCzAJBgNVBAYT\nAlJPMREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBD\nQTAeFw0wNjA3MDQxNzIwMDRaFw0zMTA3MDQxNzIwMDRaMDsxCzAJBgNVBAYTAlJP\nMREwDwYDVQQKEwhjZXJ0U0lHTjEZMBcGA1UECxMQY2VydFNJR04gUk9PVCBDQTCC\nASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALczuX7IJUqOtdu0KBuqV5Do\n0SLTZLrTk+jUrIZhQGpgV2hUhE28alQCBf/fm5oqrl0Hj0rDKH/v+yv6efHHrfAQ\nUySQi2bJqIirr1qjAOm+ukbuW3N7LBeCgV5iLKECZbO9xSsAfsT8AzNXDe3i+s5d\nRdY4zTW2ssHQnIFKquSyAVwdj1+ZxLGt24gh65AIgoDzMKND5pCCrlUoSe1b16kQ\nOA7+j0xbm0bqQfWwCHTD0IgztnzXdN/chNFDDnU5oSVAKOp4yw4sLjmdjItuFhwv\nJoIQ4uNllAoEwF73XVv4EOLQunpL+943AAAaWyjj0pxzPjKHmKHJUS/X3qwzs08C\nAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAcYwHQYDVR0O\nBBYEFOCMm9slSbPxfIbWskKHC9BroNnkMA0GCSqGSIb3DQEBBQUAA4IBAQA+0hyJ\nLjX8+HXd5n9liPRyTMks1zJO890ZeUe9jjtbkw9QSSQTaxQGcu8J06Gh40CEyecY\nMnQ8SG4Pn0vU9x7Tk4ZkVJdjclDVVc/6IJMCopvDI5NOFlV2oHB5bc0hH88vLbwZ\n44gx+FkagQnIl6Z0x2DEW8xXjrJ1/RsCCdtZb3KTafcxQdaIOL+Hsr0Wefmq5L6I\nJd1hJyMctTEHBDa0GpC9oHRxUIltvBTjD4au8as+x6AJzKNI0eDbZOeStc+vckNw\ni/nDhDwTqn6Sm1dTk/pwwpEOMfmbZ13pljheX7NzTogVZ96edhBiIL5VaZVDADlN\n9u6wWk5JRFRYX0KD\n-----END CERTIFICATE-----\n\n# Issuer: CN=NetLock Arany (Class Gold) F\\u0151tan\\xfas\\xedtv\\xe1ny O=NetLock Kft. OU=Tan\\xfas\\xedtv\\xe1nykiad\\xf3k (Certification Services)\n# Subject: CN=NetLock Arany (Class Gold) F\\u0151tan\\xfas\\xedtv\\xe1ny O=NetLock Kft. OU=Tan\\xfas\\xedtv\\xe1nykiad\\xf3k (Certification Services)\n# Label: \"NetLock Arany (Class Gold) F\\u0151tan\\xfas\\xedtv\\xe1ny\"\n# Serial: 80544274841616\n# MD5 Fingerprint: c5:a1:b7:ff:73:dd:d6:d7:34:32:18:df:fc:3c:ad:88\n# SHA1 Fingerprint: 06:08:3f:59:3f:15:a1:04:a0:69:a4:6b:a9:03:d0:06:b7:97:09:91\n# SHA256 Fingerprint: 6c:61:da:c3:a2:de:f0:31:50:6b:e0:36:d2:a6:fe:40:19:94:fb:d1:3d:f9:c8:d4:66:59:92:74:c4:46:ec:98\n-----BEGIN CERTIFICATE-----\nMIIEFTCCAv2gAwIBAgIGSUEs5AAQMA0GCSqGSIb3DQEBCwUAMIGnMQswCQYDVQQG\nEwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFTATBgNVBAoMDE5ldExvY2sgS2Z0LjE3\nMDUGA1UECwwuVGFuw7pzw610dsOhbnlraWFkw7NrIChDZXJ0aWZpY2F0aW9uIFNl\ncnZpY2VzKTE1MDMGA1UEAwwsTmV0TG9jayBBcmFueSAoQ2xhc3MgR29sZCkgRsWR\ndGFuw7pzw610dsOhbnkwHhcNMDgxMjExMTUwODIxWhcNMjgxMjA2MTUwODIxWjCB\npzELMAkGA1UEBhMCSFUxETAPBgNVBAcMCEJ1ZGFwZXN0MRUwEwYDVQQKDAxOZXRM\nb2NrIEtmdC4xNzA1BgNVBAsMLlRhbsO6c8OtdHbDoW55a2lhZMOzayAoQ2VydGlm\naWNhdGlvbiBTZXJ2aWNlcykxNTAzBgNVBAMMLE5ldExvY2sgQXJhbnkgKENsYXNz\nIEdvbGQpIEbFkXRhbsO6c8OtdHbDoW55MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A\nMIIBCgKCAQEAxCRec75LbRTDofTjl5Bu0jBFHjzuZ9lk4BqKf8owyoPjIMHj9DrT\nlF8afFttvzBPhCf2nx9JvMaZCpDyD/V/Q4Q3Y1GLeqVw/HpYzY6b7cNGbIRwXdrz\nAZAj/E4wqX7hJ2Pn7WQ8oLjJM2P+FpD/sLj916jAwJRDC7bVWaaeVtAkH3B5r9s5\nVA1lddkVQZQBr17s9o3x/61k/iCa11zr/qYfCGSji3ZVrR47KGAuhyXoqq8fxmRG\nILdwfzzeSNuWU7c5d+Qa4scWhHaXWy+7GRWF+GmF9ZmnqfI0p6m2pgP8b4Y9VHx2\nBJtr+UBdADTHLpl1neWIA6pN+APSQnbAGwIDAKiLo0UwQzASBgNVHRMBAf8ECDAG\nAQH/AgEEMA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUzPpnk/C2uNClwB7zU/2M\nU9+D15YwDQYJKoZIhvcNAQELBQADggEBAKt/7hwWqZw8UQCgwBEIBaeZ5m8BiFRh\nbvG5GK1Krf6BQCOUL/t1fC8oS2IkgYIL9WHxHG64YTjrgfpioTtaYtOUZcTh5m2C\n+C8lcLIhJsFyUR+MLMOEkMNaj7rP9KdlpeuY0fsFskZ1FSNqb4VjMIDw1Z4fKRzC\nbLBQWV2QWzuoDTDPv31/zvGdg73JRm4gpvlhUbohL3u+pRVjodSVh/GeufOJ8z2F\nuLjbvrW5KfnaNwUASZQDhETnv0Mxz3WLJdH0pmT1kvarBes96aULNmLazAZfNou2\nXjG4Kvte9nHfRCaexOYNkbQudZWAUWpLMKawYqGT8ZvYzsRjdT9ZR7E=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Hongkong Post Root CA 1 O=Hongkong Post\n# Subject: CN=Hongkong Post Root CA 1 O=Hongkong Post\n# Label: \"Hongkong Post Root CA 1\"\n# Serial: 1000\n# MD5 Fingerprint: a8:0d:6f:39:78:b9:43:6d:77:42:6d:98:5a:cc:23:ca\n# SHA1 Fingerprint: d6:da:a8:20:8d:09:d2:15:4d:24:b5:2f:cb:34:6e:b2:58:b2:8a:58\n# SHA256 Fingerprint: f9:e6:7d:33:6c:51:00:2a:c0:54:c6:32:02:2d:66:dd:a2:e7:e3:ff:f1:0a:d0:61:ed:31:d8:bb:b4:10:cf:b2\n-----BEGIN CERTIFICATE-----\nMIIDMDCCAhigAwIBAgICA+gwDQYJKoZIhvcNAQEFBQAwRzELMAkGA1UEBhMCSEsx\nFjAUBgNVBAoTDUhvbmdrb25nIFBvc3QxIDAeBgNVBAMTF0hvbmdrb25nIFBvc3Qg\nUm9vdCBDQSAxMB4XDTAzMDUxNTA1MTMxNFoXDTIzMDUxNTA0NTIyOVowRzELMAkG\nA1UEBhMCSEsxFjAUBgNVBAoTDUhvbmdrb25nIFBvc3QxIDAeBgNVBAMTF0hvbmdr\nb25nIFBvc3QgUm9vdCBDQSAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC\nAQEArP84tulmAknjorThkPlAj3n54r15/gK97iSSHSL22oVyaf7XPwnU3ZG1ApzQ\njVrhVcNQhrkpJsLj2aDxaQMoIIBFIi1WpztUlVYiWR8o3x8gPW2iNr4joLFutbEn\nPzlTCeqrauh0ssJlXI6/fMN4hM2eFvz1Lk8gKgifd/PFHsSaUmYeSF7jEAaPIpjh\nZY4bXSNmO7ilMlHIhqqhqZ5/dpTCpmy3QfDVyAY45tQM4vM7TG1QjMSDJ8EThFk9\nnnV0ttgCXjqQesBCNnLsak3c78QA3xMYV18meMjWCnl3v/evt3a5pQuEF10Q6m/h\nq5URX208o1xNg1vysxmKgIsLhwIDAQABoyYwJDASBgNVHRMBAf8ECDAGAQH/AgED\nMA4GA1UdDwEB/wQEAwIBxjANBgkqhkiG9w0BAQUFAAOCAQEADkbVPK7ih9legYsC\nmEEIjEy82tvuJxuC52pF7BaLT4Wg87JwvVqWuspube5Gi27nKi6Wsxkz67SfqLI3\n7piol7Yutmcn1KZJ/RyTZXaeQi/cImyaT/JaFTmxcdcrUehtHJjA2Sr0oYJ71clB\noiMBdDhViw+5LmeiIAQ32pwL0xch4I+XeTRvhEgCIDMb5jREn5Fw9IBehEPCKdJs\nEhTkYY2sEJCehFC78JZvRZ+K88psT/oROhUVRsPNH4NbLUES7VBnQRM9IauUiqpO\nfMGx+6fWtScvl6tu4B3i0RwsH0Ti/L6RoZz71ilTc4afU9hDDl3WY4JxHYB0yvbi\nAmvZWg==\n-----END CERTIFICATE-----\n\n# Issuer: CN=SecureSign RootCA11 O=Japan Certification Services, Inc.\n# Subject: CN=SecureSign RootCA11 O=Japan Certification Services, Inc.\n# Label: \"SecureSign RootCA11\"\n# Serial: 1\n# MD5 Fingerprint: b7:52:74:e2:92:b4:80:93:f2:75:e4:cc:d7:f2:ea:26\n# SHA1 Fingerprint: 3b:c4:9f:48:f8:f3:73:a0:9c:1e:bd:f8:5b:b1:c3:65:c7:d8:11:b3\n# SHA256 Fingerprint: bf:0f:ee:fb:9e:3a:58:1a:d5:f9:e9:db:75:89:98:57:43:d2:61:08:5c:4d:31:4f:6f:5d:72:59:aa:42:16:12\n-----BEGIN CERTIFICATE-----\nMIIDbTCCAlWgAwIBAgIBATANBgkqhkiG9w0BAQUFADBYMQswCQYDVQQGEwJKUDEr\nMCkGA1UEChMiSmFwYW4gQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcywgSW5jLjEcMBoG\nA1UEAxMTU2VjdXJlU2lnbiBSb290Q0ExMTAeFw0wOTA0MDgwNDU2NDdaFw0yOTA0\nMDgwNDU2NDdaMFgxCzAJBgNVBAYTAkpQMSswKQYDVQQKEyJKYXBhbiBDZXJ0aWZp\nY2F0aW9uIFNlcnZpY2VzLCBJbmMuMRwwGgYDVQQDExNTZWN1cmVTaWduIFJvb3RD\nQTExMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA/XeqpRyQBTvLTJsz\ni1oURaTnkBbR31fSIRCkF/3frNYfp+TbfPfs37gD2pRY/V1yfIw/XwFndBWW4wI8\nh9uuywGOwvNmxoVF9ALGOrVisq/6nL+k5tSAMJjzDbaTj6nU2DbysPyKyiyhFTOV\nMdrAG/LuYpmGYz+/3ZMqg6h2uRMft85OQoWPIucuGvKVCbIFtUROd6EgvanyTgp9\nUK31BQ1FT0Zx/Sg+U/sE2C3XZR1KG/rPO7AxmjVuyIsG0wCR8pQIZUyxNAYAeoni\n8McDWc/V1uinMrPmmECGxc0nEovMe863ETxiYAcjPitAbpSACW22s293bzUIUPsC\nh8U+iQIDAQABo0IwQDAdBgNVHQ4EFgQUW/hNT7KlhtQ60vFjmqC+CfZXt94wDgYD\nVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEFBQADggEB\nAKChOBZmLqdWHyGcBvod7bkixTgm2E5P7KN/ed5GIaGHd48HCJqypMWvDzKYC3xm\nKbabfSVSSUOrTC4rbnpwrxYO4wJs+0LmGJ1F2FXI6Dvd5+H0LgscNFxsWEr7jIhQ\nX5Ucv+2rIrVls4W6ng+4reV6G4pQOh29Dbx7VFALuUKvVaAYga1lme++5Jy/xIWr\nQbJUb9wlze144o4MjQlJ3WN7WmmWAiGovVJZ6X01y8hSyn+B/tlr0/cR7SXf+Of5\npPpyl4RTDaXQMhhRdlkUbA/r7F+AjHVDg8OFmP9Mni0N5HeDk061lgeLKBObjBmN\nQSdJQO7e5iNEOdyhIta6A/I=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Microsec e-Szigno Root CA 2009 O=Microsec Ltd.\n# Subject: CN=Microsec e-Szigno Root CA 2009 O=Microsec Ltd.\n# Label: \"Microsec e-Szigno Root CA 2009\"\n# Serial: 14014712776195784473\n# MD5 Fingerprint: f8:49:f4:03:bc:44:2d:83:be:48:69:7d:29:64:fc:b1\n# SHA1 Fingerprint: 89:df:74:fe:5c:f4:0f:4a:80:f9:e3:37:7d:54:da:91:e1:01:31:8e\n# SHA256 Fingerprint: 3c:5f:81:fe:a5:fa:b8:2c:64:bf:a2:ea:ec:af:cd:e8:e0:77:fc:86:20:a7:ca:e5:37:16:3d:f3:6e:db:f3:78\n-----BEGIN CERTIFICATE-----\nMIIECjCCAvKgAwIBAgIJAMJ+QwRORz8ZMA0GCSqGSIb3DQEBCwUAMIGCMQswCQYD\nVQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3QxFjAUBgNVBAoMDU1pY3Jvc2VjIEx0\nZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3ppZ25vIFJvb3QgQ0EgMjAwOTEfMB0G\nCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5odTAeFw0wOTA2MTYxMTMwMThaFw0y\nOTEyMzAxMTMwMThaMIGCMQswCQYDVQQGEwJIVTERMA8GA1UEBwwIQnVkYXBlc3Qx\nFjAUBgNVBAoMDU1pY3Jvc2VjIEx0ZC4xJzAlBgNVBAMMHk1pY3Jvc2VjIGUtU3pp\nZ25vIFJvb3QgQ0EgMjAwOTEfMB0GCSqGSIb3DQEJARYQaW5mb0BlLXN6aWduby5o\ndTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOn4j/NjrdqG2KfgQvvP\nkd6mJviZpWNwrZuuyjNAfW2WbqEORO7hE52UQlKavXWFdCyoDh2Tthi3jCyoz/tc\ncbna7P7ofo/kLx2yqHWH2Leh5TvPmUpG0IMZfcChEhyVbUr02MelTTMuhTlAdX4U\nfIASmFDHQWe4oIBhVKZsTh/gnQ4H6cm6M+f+wFUoLAKApxn1ntxVUwOXewdI/5n7\nN4okxFnMUBBjjqqpGrCEGob5X7uxUG6k0QrM1XF+H6cbfPVTbiJfyyvm1HxdrtbC\nxkzlBQHZ7Vf8wSN5/PrIJIOV87VqUQHQd9bpEqH5GoP7ghu5sJf0dgYzQ0mg/wu1\n+rUCAwEAAaOBgDB+MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G\nA1UdDgQWBBTLD8bfQkPMPcu1SCOhGnqmKrs0aDAfBgNVHSMEGDAWgBTLD8bfQkPM\nPcu1SCOhGnqmKrs0aDAbBgNVHREEFDASgRBpbmZvQGUtc3ppZ25vLmh1MA0GCSqG\nSIb3DQEBCwUAA4IBAQDJ0Q5eLtXMs3w+y/w9/w0olZMEyL/azXm4Q5DwpL7v8u8h\nmLzU1F0G9u5C7DBsoKqpyvGvivo/C3NqPuouQH4frlRheesuCDfXI/OMn74dseGk\nddug4lQUsbocKaQY9hK6ohQU4zE1yED/t+AFdlfBHFny+L/k7SViXITwfn4fs775\ntyERzAMBVnCnEJIeGzSBHq2cGsMEPO0CYdYeBvNfOofyK/FFh+U9rNHHV4S9a67c\n2Pm2G2JwCz02yULyMtd6YebS2z3PyKnJm9zbWETXbzivf3jTo60adbocwTZ8jx5t\nHMN1Rq41Bab2XD0h7lbwyYIiLXpUq3DDfSJlgnCW\n-----END CERTIFICATE-----\n\n# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3\n# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R3\n# Label: \"GlobalSign Root CA - R3\"\n# Serial: 4835703278459759426209954\n# MD5 Fingerprint: c5:df:b8:49:ca:05:13:55:ee:2d:ba:1a:c3:3e:b0:28\n# SHA1 Fingerprint: d6:9b:56:11:48:f0:1c:77:c5:45:78:c1:09:26:df:5b:85:69:76:ad\n# SHA256 Fingerprint: cb:b5:22:d7:b7:f1:27:ad:6a:01:13:86:5b:df:1c:d4:10:2e:7d:07:59:af:63:5a:7c:f4:72:0d:c9:63:c5:3b\n-----BEGIN CERTIFICATE-----\nMIIDXzCCAkegAwIBAgILBAAAAAABIVhTCKIwDQYJKoZIhvcNAQELBQAwTDEgMB4G\nA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjMxEzARBgNVBAoTCkdsb2JhbFNp\nZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMDkwMzE4MTAwMDAwWhcNMjkwMzE4\nMTAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSMzETMBEG\nA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCASIwDQYJKoZI\nhvcNAQEBBQADggEPADCCAQoCggEBAMwldpB5BngiFvXAg7aEyiie/QV2EcWtiHL8\nRgJDx7KKnQRfJMsuS+FggkbhUqsMgUdwbN1k0ev1LKMPgj0MK66X17YUhhB5uzsT\ngHeMCOFJ0mpiLx9e+pZo34knlTifBtc+ycsmWQ1z3rDI6SYOgxXG71uL0gRgykmm\nKPZpO/bLyCiR5Z2KYVc3rHQU3HTgOu5yLy6c+9C7v/U9AOEGM+iCK65TpjoWc4zd\nQQ4gOsC0p6Hpsk+QLjJg6VfLuQSSaGjlOCZgdbKfd/+RFO+uIEn8rUAVSNECMWEZ\nXriX7613t2Saer9fwRPvm2L7DWzgVGkWqQPabumDk3F2xmmFghcCAwEAAaNCMEAw\nDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI/wS3+o\nLkUkrk1Q+mOai97i3Ru8MA0GCSqGSIb3DQEBCwUAA4IBAQBLQNvAUKr+yAzv95ZU\nRUm7lgAJQayzE4aGKAczymvmdLm6AC2upArT9fHxD4q/c2dKg8dEe3jgr25sbwMp\njjM5RcOO5LlXbKr8EpbsU8Yt5CRsuZRj+9xTaGdWPoO4zzUhw8lo/s7awlOqzJCK\n6fBdRoyV3XpYKBovHd7NADdBj+1EbddTKJd+82cEHhXXipa0095MJ6RMG3NzdvQX\nmcIfeg7jLQitChws/zyrVQ4PkX4268NXSb7hLi18YIvDQVETI53O9zJrlAGomecs\nMx86OyXShkDOOyyGeMlhLxS67ttVb9+E7gUJTb0o2HLO02JQZR7rkpeDMdmztcpH\nWD9f\n-----END CERTIFICATE-----\n\n# Issuer: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068\n# Subject: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068\n# Label: \"Autoridad de Certificacion Firmaprofesional CIF A62634068\"\n# Serial: 6047274297262753887\n# MD5 Fingerprint: 73:3a:74:7a:ec:bb:a3:96:a6:c2:e4:e2:c8:9b:c0:c3\n# SHA1 Fingerprint: ae:c5:fb:3f:c8:e1:bf:c4:e5:4f:03:07:5a:9a:e8:00:b7:f7:b6:fa\n# SHA256 Fingerprint: 04:04:80:28:bf:1f:28:64:d4:8f:9a:d4:d8:32:94:36:6a:82:88:56:55:3f:3b:14:30:3f:90:14:7f:5d:40:ef\n-----BEGIN CERTIFICATE-----\nMIIGFDCCA/ygAwIBAgIIU+w77vuySF8wDQYJKoZIhvcNAQEFBQAwUTELMAkGA1UE\nBhMCRVMxQjBABgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1h\ncHJvZmVzaW9uYWwgQ0lGIEE2MjYzNDA2ODAeFw0wOTA1MjAwODM4MTVaFw0zMDEy\nMzEwODM4MTVaMFExCzAJBgNVBAYTAkVTMUIwQAYDVQQDDDlBdXRvcmlkYWQgZGUg\nQ2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBBNjI2MzQwNjgwggIi\nMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDDUtd9\nthDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQM\ncas9UX4PB99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefG\nL9ItWY16Ck6WaVICqjaY7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15i\nNA9wBj4gGFrO93IbJWyTdBSTo3OxDqqHECNZXyAFGUftaI6SEspd/NYrspI8IM/h\nX68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyIplD9amML9ZMWGxmPsu2b\nm8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctXMbScyJCy\nZ/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirja\nEbsXLZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/T\nKI8xWVvTyQKmtFLKbpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF\n6NkBiDkal4ZkQdU7hwxu+g/GvUgUvzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVh\nOSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMBIGA1UdEwEB/wQIMAYBAf8CAQEwDgYD\nVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBRlzeurNR4APn7VdMActHNHDhpkLzCBpgYD\nVR0gBIGeMIGbMIGYBgRVHSAAMIGPMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmZp\ncm1hcHJvZmVzaW9uYWwuY29tL2NwczBcBggrBgEFBQcCAjBQHk4AUABhAHMAZQBv\nACAAZABlACAAbABhACAAQgBvAG4AYQBuAG8AdgBhACAANAA3ACAAQgBhAHIAYwBl\nAGwAbwBuAGEAIAAwADgAMAAxADcwDQYJKoZIhvcNAQEFBQADggIBABd9oPm03cXF\n661LJLWhAqvdpYhKsg9VSytXjDvlMd3+xDLx51tkljYyGOylMnfX40S2wBEqgLk9\nam58m9Ot/MPWo+ZkKXzR4Tgegiv/J2Wv+xYVxC5xhOW1//qkR71kMrv2JYSiJ0L1\nILDCExARzRAVukKQKtJE4ZYm6zFIEv0q2skGz3QeqUvVhyj5eTSSPi5E6PaPT481\nPyWzOdxjKpBrIF/EUhJOlywqrJ2X3kjyo2bbwtKDlaZmp54lD+kLM5FlClrD2VQS\n3a/DTg4fJl4N3LON7NWBcN7STyQF82xO9UxJZo3R/9ILJUFI/lGExkKvgATP0H5k\nSeTy36LssUzAKh3ntLFlosS88Zj0qnAHY7S42jtM+kAiMFsRpvAFDsYCA0irhpuF\n3dvd6qJ2gHN99ZwExEWN57kci57q13XRcrHedUTnQn3iV2t93Jm8PYMo6oCTjcVM\nZcFwgbg4/EMxsvYDNEeyrPsiBsse3RdHHF9mudMaotoRsaS8I8nkvof/uZS2+F0g\nStRf571oe2XyFR7SOqkt6dhrJKyXWERHrVkY8SFlcN7ONGCoQPHzPKTDKCOM/icz\nQ0CgFzzr6juwcqajuUpLXhZI9LK8yIySxZ2frHI2vDSANGupi5LAuBft7HZT9SQB\njLMi6Et8Vcad+qMUu2WFbm5PEn4KPJ2V\n-----END CERTIFICATE-----\n\n# Issuer: CN=Izenpe.com O=IZENPE S.A.\n# Subject: CN=Izenpe.com O=IZENPE S.A.\n# Label: \"Izenpe.com\"\n# Serial: 917563065490389241595536686991402621\n# MD5 Fingerprint: a6:b0:cd:85:80:da:5c:50:34:a3:39:90:2f:55:67:73\n# SHA1 Fingerprint: 2f:78:3d:25:52:18:a7:4a:65:39:71:b5:2c:a2:9c:45:15:6f:e9:19\n# SHA256 Fingerprint: 25:30:cc:8e:98:32:15:02:ba:d9:6f:9b:1f:ba:1b:09:9e:2d:29:9e:0f:45:48:bb:91:4f:36:3b:c0:d4:53:1f\n-----BEGIN CERTIFICATE-----\nMIIF8TCCA9mgAwIBAgIQALC3WhZIX7/hy/WL1xnmfTANBgkqhkiG9w0BAQsFADA4\nMQswCQYDVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6\nZW5wZS5jb20wHhcNMDcxMjEzMTMwODI4WhcNMzcxMjEzMDgyNzI1WjA4MQswCQYD\nVQQGEwJFUzEUMBIGA1UECgwLSVpFTlBFIFMuQS4xEzARBgNVBAMMCkl6ZW5wZS5j\nb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDJ03rKDx6sp4boFmVq\nscIbRTJxldn+EFvMr+eleQGPicPK8lVx93e+d5TzcqQsRNiekpsUOqHnJJAKClaO\nxdgmlOHZSOEtPtoKct2jmRXagaKH9HtuJneJWK3W6wyyQXpzbm3benhB6QiIEn6H\nLmYRY2xU+zydcsC8Lv/Ct90NduM61/e0aL6i9eOBbsFGb12N4E3GVFWJGjMxCrFX\nuaOKmMPsOzTFlUFpfnXCPCDFYbpRR6AgkJOhkEvzTnyFRVSa0QUmQbC1TR0zvsQD\nyCV8wXDbO/QJLVQnSKwv4cSsPsjLkkxTOTcj7NMB+eAJRE1NZMDhDVqHIrytG6P+\nJrUV86f8hBnp7KGItERphIPzidF0BqnMC9bC3ieFUCbKF7jJeodWLBoBHmy+E60Q\nrLUk9TiRodZL2vG70t5HtfG8gfZZa88ZU+mNFctKy6lvROUbQc/hhqfK0GqfvEyN\nBjNaooXlkDWgYlwWTvDjovoDGrQscbNYLN57C9saD+veIR8GdwYDsMnvmfzAuU8L\nhij+0rnq49qlw0dpEuDb8PYZi+17cNcC1u2HGCgsBCRMd+RIihrGO5rUD8r6ddIB\nQFqNeb+Lz0vPqhbBleStTIo+F5HUsWLlguWABKQDfo2/2n+iD5dPDNMN+9fR5XJ+\nHMh3/1uaD7euBUbl8agW7EekFwIDAQABo4H2MIHzMIGwBgNVHREEgagwgaWBD2lu\nZm9AaXplbnBlLmNvbaSBkTCBjjFHMEUGA1UECgw+SVpFTlBFIFMuQS4gLSBDSUYg\nQTAxMzM3MjYwLVJNZXJjLlZpdG9yaWEtR2FzdGVpeiBUMTA1NSBGNjIgUzgxQzBB\nBgNVBAkMOkF2ZGEgZGVsIE1lZGl0ZXJyYW5lbyBFdG9yYmlkZWEgMTQgLSAwMTAx\nMCBWaXRvcmlhLUdhc3RlaXowDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\nAQYwHQYDVR0OBBYEFB0cZQ6o8iV7tJHP5LGx5r1VdGwFMA0GCSqGSIb3DQEBCwUA\nA4ICAQB4pgwWSp9MiDrAyw6lFn2fuUhfGI8NYjb2zRlrrKvV9pF9rnHzP7MOeIWb\nlaQnIUdCSnxIOvVFfLMMjlF4rJUT3sb9fbgakEyrkgPH7UIBzg/YsfqikuFgba56\nawmqxinuaElnMIAkejEWOVt+8Rwu3WwJrfIxwYJOubv5vr8qhT/AQKM6WfxZSzwo\nJNu0FXWuDYi6LnPAvViH5ULy617uHjAimcs30cQhbIHsvm0m5hzkQiCeR7Csg1lw\nLDXWrzY0tM07+DKo7+N4ifuNRSzanLh+QBxh5z6ikixL8s36mLYp//Pye6kfLqCT\nVyvehQP5aTfLnnhqBbTFMXiJ7HqnheG5ezzevh55hM6fcA5ZwjUukCox2eRFekGk\nLhObNA5me0mrZJfQRsN5nXJQY6aYWwa9SG3YOYNw6DXwBdGqvOPbyALqfP2C2sJb\nUjWumDqtujWTI6cfSN01RpiyEGjkpTHCClguGYEQyVB1/OpaFs4R1+7vUIgtYf8/\nQnMFlEPVjjxOAToZpR9GTnfQXeWBIiGH/pR9hNiTrdZoQ0iy2+tzJOeRf1SktoA+\nnaM8THLCV8Sg1Mw4J87VBp6iSNnpn86CcDaTmjvfliHjWbcM2pE38P1ZWrOZyGls\nQyYBNWNgVYkDOnXYukrZVP/u3oDYLdE41V4tC5h9Pmzb/CaIxw==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc.\n# Subject: CN=Go Daddy Root Certificate Authority - G2 O=GoDaddy.com, Inc.\n# Label: \"Go Daddy Root Certificate Authority - G2\"\n# Serial: 0\n# MD5 Fingerprint: 80:3a:bc:22:c1:e6:fb:8d:9b:3b:27:4a:32:1b:9a:01\n# SHA1 Fingerprint: 47:be:ab:c9:22:ea:e8:0e:78:78:34:62:a7:9f:45:c2:54:fd:e6:8b\n# SHA256 Fingerprint: 45:14:0b:32:47:eb:9c:c8:c5:b4:f0:d7:b5:30:91:f7:32:92:08:9e:6e:5a:63:e2:74:9d:d3:ac:a9:19:8e:da\n-----BEGIN CERTIFICATE-----\nMIIDxTCCAq2gAwIBAgIBADANBgkqhkiG9w0BAQsFADCBgzELMAkGA1UEBhMCVVMx\nEDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAYBgNVBAoT\nEUdvRGFkZHkuY29tLCBJbmMuMTEwLwYDVQQDEyhHbyBEYWRkeSBSb290IENlcnRp\nZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAwMFoXDTM3MTIzMTIz\nNTk1OVowgYMxCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQH\nEwpTY290dHNkYWxlMRowGAYDVQQKExFHb0RhZGR5LmNvbSwgSW5jLjExMC8GA1UE\nAxMoR28gRGFkZHkgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIw\nDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9xYgjx+lk09xvJGKP3gElY6SKD\nE6bFIEMBO4Tx5oVJnyfq9oQbTqC023CYxzIBsQU+B07u9PpPL1kwIuerGVZr4oAH\n/PMWdYA5UXvl+TW2dE6pjYIT5LY/qQOD+qK+ihVqf94Lw7YZFAXK6sOoBJQ7Rnwy\nDfMAZiLIjWltNowRGLfTshxgtDj6AozO091GB94KPutdfMh8+7ArU6SSYmlRJQVh\nGkSBjCypQ5Yj36w6gZoOKcUcqeldHraenjAKOc7xiID7S13MMuyFYkMlNAJWJwGR\ntDtwKj9useiciAF9n9T521NtYJ2/LOdYq7hfRvzOxBsDPAnrSTFcaUaz4EcCAwEA\nAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE\nFDqahQcQZyi27/a9BUFuIMGU2g/eMA0GCSqGSIb3DQEBCwUAA4IBAQCZ21151fmX\nWWcDYfF+OwYxdS2hII5PZYe096acvNjpL9DbWu7PdIxztDhC2gV7+AJ1uP2lsdeu\n9tfeE8tTEH6KRtGX+rcuKxGrkLAngPnon1rpN5+r5N9ss4UXnT3ZJE95kTXWXwTr\ngIOrmgIttRD02JDHBHNA7XIloKmf7J6raBKZV8aPEjoJpL1E/QYVN8Gb5DKj7Tjo\n2GTzLH4U/ALqn83/B2gX2yKQOC16jdFU8WnjXzPKej17CuPKf1855eJ1usV2GDPO\nLPAvTK33sefOT6jEm0pUBsV/fdUID+Ic/n4XuKxe9tQWskMJDE32p2u0mYRlynqI\n4uJEvlz36hz1\n-----END CERTIFICATE-----\n\n# Issuer: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc.\n# Subject: CN=Starfield Root Certificate Authority - G2 O=Starfield Technologies, Inc.\n# Label: \"Starfield Root Certificate Authority - G2\"\n# Serial: 0\n# MD5 Fingerprint: d6:39:81:c6:52:7e:96:69:fc:fc:ca:66:ed:05:f2:96\n# SHA1 Fingerprint: b5:1c:06:7c:ee:2b:0c:3d:f8:55:ab:2d:92:f4:fe:39:d4:e7:0f:0e\n# SHA256 Fingerprint: 2c:e1:cb:0b:f9:d2:f9:e1:02:99:3f:be:21:51:52:c3:b2:dd:0c:ab:de:1c:68:e5:31:9b:83:91:54:db:b7:f5\n-----BEGIN CERTIFICATE-----\nMIID3TCCAsWgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBjzELMAkGA1UEBhMCVVMx\nEDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT\nHFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xMjAwBgNVBAMTKVN0YXJmaWVs\nZCBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5MDkwMTAwMDAw\nMFoXDTM3MTIzMTIzNTk1OVowgY8xCzAJBgNVBAYTAlVTMRAwDgYDVQQIEwdBcml6\nb25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFyZmllbGQgVGVj\naG5vbG9naWVzLCBJbmMuMTIwMAYDVQQDEylTdGFyZmllbGQgUm9vdCBDZXJ0aWZp\nY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\nggEBAL3twQP89o/8ArFvW59I2Z154qK3A2FWGMNHttfKPTUuiUP3oWmb3ooa/RMg\nnLRJdzIpVv257IzdIvpy3Cdhl+72WoTsbhm5iSzchFvVdPtrX8WJpRBSiUZV9Lh1\nHOZ/5FSuS/hVclcCGfgXcVnrHigHdMWdSL5stPSksPNkN3mSwOxGXn/hbVNMYq/N\nHwtjuzqd+/x5AJhhdM8mgkBj87JyahkNmcrUDnXMN/uLicFZ8WJ/X7NfZTD4p7dN\ndloedl40wOiWVpmKs/B/pM293DIxfJHP4F8R+GuqSVzRmZTRouNjWwl2tVZi4Ut0\nHZbUJtQIBFnQmA4O5t78w+wfkPECAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAO\nBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFHwMMh+n2TB/xH1oo2Kooc6rB1snMA0G\nCSqGSIb3DQEBCwUAA4IBAQARWfolTwNvlJk7mh+ChTnUdgWUXuEok21iXQnCoKjU\nsHU48TRqneSfioYmUeYs0cYtbpUgSpIB7LiKZ3sx4mcujJUDJi5DnUox9g61DLu3\n4jd/IroAow57UvtruzvE03lRTs2Q9GcHGcg8RnoNAX3FWOdt5oUwF5okxBDgBPfg\n8n/Uqgr/Qh037ZTlZFkSIHc40zI+OIF1lnP6aI+xy84fxez6nH7PfrHxBy22/L/K\npL/QlwVKvOoYKAKQvVR4CSFx09F9HdkWsKlhPdAKACL8x3vLCWRFCztAgfd9fDL1\nmMpYjn0q7pBZc2T5NnReJaH1ZgUufzkVqSr7UIuOhWn0\n-----END CERTIFICATE-----\n\n# Issuer: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc.\n# Subject: CN=Starfield Services Root Certificate Authority - G2 O=Starfield Technologies, Inc.\n# Label: \"Starfield Services Root Certificate Authority - G2\"\n# Serial: 0\n# MD5 Fingerprint: 17:35:74:af:7b:61:1c:eb:f4:f9:3c:e2:ee:40:f9:a2\n# SHA1 Fingerprint: 92:5a:8f:8d:2c:6d:04:e0:66:5f:59:6a:ff:22:d8:63:e8:25:6f:3f\n# SHA256 Fingerprint: 56:8d:69:05:a2:c8:87:08:a4:b3:02:51:90:ed:cf:ed:b1:97:4a:60:6a:13:c6:e5:29:0f:cb:2a:e6:3e:da:b5\n-----BEGIN CERTIFICATE-----\nMIID7zCCAtegAwIBAgIBADANBgkqhkiG9w0BAQsFADCBmDELMAkGA1UEBhMCVVMx\nEDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxJTAjBgNVBAoT\nHFN0YXJmaWVsZCBUZWNobm9sb2dpZXMsIEluYy4xOzA5BgNVBAMTMlN0YXJmaWVs\nZCBTZXJ2aWNlcyBSb290IENlcnRpZmljYXRlIEF1dGhvcml0eSAtIEcyMB4XDTA5\nMDkwMTAwMDAwMFoXDTM3MTIzMTIzNTk1OVowgZgxCzAJBgNVBAYTAlVTMRAwDgYD\nVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMSUwIwYDVQQKExxTdGFy\nZmllbGQgVGVjaG5vbG9naWVzLCBJbmMuMTswOQYDVQQDEzJTdGFyZmllbGQgU2Vy\ndmljZXMgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkgLSBHMjCCASIwDQYJKoZI\nhvcNAQEBBQADggEPADCCAQoCggEBANUMOsQq+U7i9b4Zl1+OiFOxHz/Lz58gE20p\nOsgPfTz3a3Y4Y9k2YKibXlwAgLIvWX/2h/klQ4bnaRtSmpDhcePYLQ1Ob/bISdm2\n8xpWriu2dBTrz/sm4xq6HZYuajtYlIlHVv8loJNwU4PahHQUw2eeBGg6345AWh1K\nTs9DkTvnVtYAcMtS7nt9rjrnvDH5RfbCYM8TWQIrgMw0R9+53pBlbQLPLJGmpufe\nhRhJfGZOozptqbXuNC66DQO4M99H67FrjSXZm86B0UVGMpZwh94CDklDhbZsc7tk\n6mFBrMnUVN+HL8cisibMn1lUaJ/8viovxFUcdUBgF4UCVTmLfwUCAwEAAaNCMEAw\nDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFJxfAN+q\nAdcwKziIorhtSpzyEZGDMA0GCSqGSIb3DQEBCwUAA4IBAQBLNqaEd2ndOxmfZyMI\nbw5hyf2E3F/YNoHN2BtBLZ9g3ccaaNnRbobhiCPPE95Dz+I0swSdHynVv/heyNXB\nve6SbzJ08pGCL72CQnqtKrcgfU28elUSwhXqvfdqlS5sdJ/PHLTyxQGjhdByPq1z\nqwubdQxtRbeOlKyWN7Wg0I8VRw7j6IPdj/3vQQF3zCepYoUz8jcI73HPdwbeyBkd\niEDPfUYd/x7H4c7/I9vG+o1VTqkC50cRRj70/b17KSa7qWFiNyi2LSr2EIZkyXCn\n0q23KXB56jzaYyWf/Wi3MOxw+3WKt21gZ7IeyLnp2KhvAotnDU0mV3HaIPzBSlCN\nsSi6\n-----END CERTIFICATE-----\n\n# Issuer: CN=AffirmTrust Commercial O=AffirmTrust\n# Subject: CN=AffirmTrust Commercial O=AffirmTrust\n# Label: \"AffirmTrust Commercial\"\n# Serial: 8608355977964138876\n# MD5 Fingerprint: 82:92:ba:5b:ef:cd:8a:6f:a6:3d:55:f9:84:f6:d6:b7\n# SHA1 Fingerprint: f9:b5:b6:32:45:5f:9c:be:ec:57:5f:80:dc:e9:6e:2c:c7:b2:78:b7\n# SHA256 Fingerprint: 03:76:ab:1d:54:c5:f9:80:3c:e4:b2:e2:01:a0:ee:7e:ef:7b:57:b6:36:e8:a9:3c:9b:8d:48:60:c9:6f:5f:a7\n-----BEGIN CERTIFICATE-----\nMIIDTDCCAjSgAwIBAgIId3cGJyapsXwwDQYJKoZIhvcNAQELBQAwRDELMAkGA1UE\nBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVz\ndCBDb21tZXJjaWFsMB4XDTEwMDEyOTE0MDYwNloXDTMwMTIzMTE0MDYwNlowRDEL\nMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZp\ncm1UcnVzdCBDb21tZXJjaWFsMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC\nAQEA9htPZwcroRX1BiLLHwGy43NFBkRJLLtJJRTWzsO3qyxPxkEylFf6EqdbDuKP\nHx6GGaeqtS25Xw2Kwq+FNXkyLbscYjfysVtKPcrNcV/pQr6U6Mje+SJIZMblq8Yr\nba0F8PrVC8+a5fBQpIs7R6UjW3p6+DM/uO+Zl+MgwdYoic+U+7lF7eNAFxHUdPAL\nMeIrJmqbTFeurCA+ukV6BfO9m2kVrn1OIGPENXY6BwLJN/3HR+7o8XYdcxXyl6S1\nyHp52UKqK39c/s4mT6NmgTWvRLpUHhwwMmWd5jyTXlBOeuM61G7MGvv50jeuJCqr\nVwMiKA1JdX+3KNp1v47j3A55MQIDAQABo0IwQDAdBgNVHQ4EFgQUnZPGU4teyq8/\nnx4P5ZmVvCT2lI8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwDQYJ\nKoZIhvcNAQELBQADggEBAFis9AQOzcAN/wr91LoWXym9e2iZWEnStB03TX8nfUYG\nXUPGhi4+c7ImfU+TqbbEKpqrIZcUsd6M06uJFdhrJNTxFq7YpFzUf1GO7RgBsZNj\nvbz4YYCanrHOQnDiqX0GJX0nof5v7LMeJNrjS1UaADs1tDvZ110w/YETifLCBivt\nZ8SOyUOyXGsViQK8YvxO8rUzqrJv0wqiUOP2O+guRMLbZjipM1ZI8W0bM40NjD9g\nN53Tym1+NH4Nn3J2ixufcv1SNUFFApYvHLKac0khsUlHRUe072o0EclNmsxZt9YC\nnlpOZbWUrhvfKbAW8b8Angc6F2S1BLUjIZkKlTuXfO8=\n-----END CERTIFICATE-----\n\n# Issuer: CN=AffirmTrust Networking O=AffirmTrust\n# Subject: CN=AffirmTrust Networking O=AffirmTrust\n# Label: \"AffirmTrust Networking\"\n# Serial: 8957382827206547757\n# MD5 Fingerprint: 42:65:ca:be:01:9a:9a:4c:a9:8c:41:49:cd:c0:d5:7f\n# SHA1 Fingerprint: 29:36:21:02:8b:20:ed:02:f5:66:c5:32:d1:d6:ed:90:9f:45:00:2f\n# SHA256 Fingerprint: 0a:81:ec:5a:92:97:77:f1:45:90:4a:f3:8d:5d:50:9f:66:b5:e2:c5:8f:cd:b5:31:05:8b:0e:17:f3:f0:b4:1b\n-----BEGIN CERTIFICATE-----\nMIIDTDCCAjSgAwIBAgIIfE8EORzUmS0wDQYJKoZIhvcNAQEFBQAwRDELMAkGA1UE\nBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZpcm1UcnVz\ndCBOZXR3b3JraW5nMB4XDTEwMDEyOTE0MDgyNFoXDTMwMTIzMTE0MDgyNFowRDEL\nMAkGA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MR8wHQYDVQQDDBZBZmZp\ncm1UcnVzdCBOZXR3b3JraW5nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC\nAQEAtITMMxcua5Rsa2FSoOujz3mUTOWUgJnLVWREZY9nZOIG41w3SfYvm4SEHi3y\nYJ0wTsyEheIszx6e/jarM3c1RNg1lho9Nuh6DtjVR6FqaYvZ/Ls6rnla1fTWcbua\nkCNrmreIdIcMHl+5ni36q1Mr3Lt2PpNMCAiMHqIjHNRqrSK6mQEubWXLviRmVSRL\nQESxG9fhwoXA3hA/Pe24/PHxI1Pcv2WXb9n5QHGNfb2V1M6+oF4nI979ptAmDgAp\n6zxG8D1gvz9Q0twmQVGeFDdCBKNwV6gbh+0t+nvujArjqWaJGctB+d1ENmHP4ndG\nyH329JKBNv3bNPFyfvMMFr20FQIDAQABo0IwQDAdBgNVHQ4EFgQUBx/S55zawm6i\nQLSwelAQUHTEyL0wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwDQYJ\nKoZIhvcNAQEFBQADggEBAIlXshZ6qML91tmbmzTCnLQyFE2npN/svqe++EPbkTfO\ntDIuUFUaNU52Q3Eg75N3ThVwLofDwR1t3Mu1J9QsVtFSUzpE0nPIxBsFZVpikpzu\nQY0x2+c06lkh1QF612S4ZDnNye2v7UsDSKegmQGA3GWjNq5lWUhPgkvIZfFXHeVZ\nLgo/bNjR9eUJtGxUAArgFU2HdW23WJZa3W3SAKD0m0i+wzekujbgfIeFlxoVot4u\nolu9rxj5kFDNcFn4J2dHy8egBzp90SxdbBk6ZrV9/ZFvgrG+CJPbFEfxojfHRZ48\nx3evZKiT3/Zpg4Jg8klCNO1aAFSFHBY2kgxc+qatv9s=\n-----END CERTIFICATE-----\n\n# Issuer: CN=AffirmTrust Premium O=AffirmTrust\n# Subject: CN=AffirmTrust Premium O=AffirmTrust\n# Label: \"AffirmTrust Premium\"\n# Serial: 7893706540734352110\n# MD5 Fingerprint: c4:5d:0e:48:b6:ac:28:30:4e:0a:bc:f9:38:16:87:57\n# SHA1 Fingerprint: d8:a6:33:2c:e0:03:6f:b1:85:f6:63:4f:7d:6a:06:65:26:32:28:27\n# SHA256 Fingerprint: 70:a7:3f:7f:37:6b:60:07:42:48:90:45:34:b1:14:82:d5:bf:0e:69:8e:cc:49:8d:f5:25:77:eb:f2:e9:3b:9a\n-----BEGIN CERTIFICATE-----\nMIIFRjCCAy6gAwIBAgIIbYwURrGmCu4wDQYJKoZIhvcNAQEMBQAwQTELMAkGA1UE\nBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1UcnVz\ndCBQcmVtaXVtMB4XDTEwMDEyOTE0MTAzNloXDTQwMTIzMTE0MTAzNlowQTELMAkG\nA1UEBhMCVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MRwwGgYDVQQDDBNBZmZpcm1U\ncnVzdCBQcmVtaXVtMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxBLf\nqV/+Qd3d9Z+K4/as4Tx4mrzY8H96oDMq3I0gW64tb+eT2TZwamjPjlGjhVtnBKAQ\nJG9dKILBl1fYSCkTtuG+kU3fhQxTGJoeJKJPj/CihQvL9Cl/0qRY7iZNyaqoe5rZ\n+jjeRFcV5fiMyNlI4g0WJx0eyIOFJbe6qlVBzAMiSy2RjYvmia9mx+n/K+k8rNrS\ns8PhaJyJ+HoAVt70VZVs+7pk3WKL3wt3MutizCaam7uqYoNMtAZ6MMgpv+0GTZe5\nHMQxK9VfvFMSF5yZVylmd2EhMQcuJUmdGPLu8ytxjLW6OQdJd/zvLpKQBY0tL3d7\n70O/Nbua2Plzpyzy0FfuKE4mX4+QaAkvuPjcBukumj5Rp9EixAqnOEhss/n/fauG\nV+O61oV4d7pD6kh/9ti+I20ev9E2bFhc8e6kGVQa9QPSdubhjL08s9NIS+LI+H+S\nqHZGnEJlPqQewQcDWkYtuJfzt9WyVSHvutxMAJf7FJUnM7/oQ0dG0giZFmA7mn7S\n5u046uwBHjxIVkkJx0w3AJ6IDsBz4W9m6XJHMD4Q5QsDyZpCAGzFlH5hxIrff4Ia\nC1nEWTJ3s7xgaVY5/bQGeyzWZDbZvUjthB9+pSKPKrhC9IK31FOQeE4tGv2Bb0TX\nOwF0lkLgAOIua+rF7nKsu7/+6qqo+Nz2snmKtmcCAwEAAaNCMEAwHQYDVR0OBBYE\nFJ3AZ6YMItkm9UWrpmVSESfYRaxjMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/\nBAQDAgEGMA0GCSqGSIb3DQEBDAUAA4ICAQCzV00QYk465KzquByvMiPIs0laUZx2\nKI15qldGF9X1Uva3ROgIRL8YhNILgM3FEv0AVQVhh0HctSSePMTYyPtwni94loMg\nNt58D2kTiKV1NpgIpsbfrM7jWNa3Pt668+s0QNiigfV4Py/VpfzZotReBA4Xrf5B\n8OWycvpEgjNC6C1Y91aMYj+6QrCcDFx+LmUmXFNPALJ4fqENmS2NuB2OosSw/WDQ\nMKSOyARiqcTtNd56l+0OOF6SL5Nwpamcb6d9Ex1+xghIsV5n61EIJenmJWtSKZGc\n0jlzCFfemQa0W50QBuHCAKi4HEoCChTQwUHK+4w1IX2COPKpVJEZNZOUbWo6xbLQ\nu4mGk+ibyQ86p3q4ofB4Rvr8Ny/lioTz3/4E2aFooC8k4gmVBtWVyuEklut89pMF\nu+1z6S3RdTnX5yTb2E5fQ4+e0BQ5v1VwSJlXMbSc7kqYA5YwH2AG7hsj/oFgIxpH\nYoWlzBk0gG+zrBrjn/B7SK3VAdlntqlyk+otZrWyuOQ9PLLvTIzq6we/qzWaVYa8\nGKa1qF60g2xraUDTn9zxw2lrueFtCfTxqlB2Cnp9ehehVZZCmTEJ3WARjQUwfuaO\nRtGdFNrHF+QFlozEJLUbzxQHskD4o55BhrwE0GuWyCqANP2/7waj3VjFhT0+j/6e\nKeC2uAloGRwYQw==\n-----END CERTIFICATE-----\n\n# Issuer: CN=AffirmTrust Premium ECC O=AffirmTrust\n# Subject: CN=AffirmTrust Premium ECC O=AffirmTrust\n# Label: \"AffirmTrust Premium ECC\"\n# Serial: 8401224907861490260\n# MD5 Fingerprint: 64:b0:09:55:cf:b1:d5:99:e2:be:13:ab:a6:5d:ea:4d\n# SHA1 Fingerprint: b8:23:6b:00:2f:1d:16:86:53:01:55:6c:11:a4:37:ca:eb:ff:c3:bb\n# SHA256 Fingerprint: bd:71:fd:f6:da:97:e4:cf:62:d1:64:7a:dd:25:81:b0:7d:79:ad:f8:39:7e:b4:ec:ba:9c:5e:84:88:82:14:23\n-----BEGIN CERTIFICATE-----\nMIIB/jCCAYWgAwIBAgIIdJclisc/elQwCgYIKoZIzj0EAwMwRTELMAkGA1UEBhMC\nVVMxFDASBgNVBAoMC0FmZmlybVRydXN0MSAwHgYDVQQDDBdBZmZpcm1UcnVzdCBQ\ncmVtaXVtIEVDQzAeFw0xMDAxMjkxNDIwMjRaFw00MDEyMzExNDIwMjRaMEUxCzAJ\nBgNVBAYTAlVTMRQwEgYDVQQKDAtBZmZpcm1UcnVzdDEgMB4GA1UEAwwXQWZmaXJt\nVHJ1c3QgUHJlbWl1bSBFQ0MwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQNMF4bFZ0D\n0KF5Nbc6PJJ6yhUczWLznCZcBz3lVPqj1swS6vQUX+iOGasvLkjmrBhDeKzQN8O9\nss0s5kfiGuZjuD0uL3jET9v0D6RoTFVya5UdThhClXjMNzyR4ptlKymjQjBAMB0G\nA1UdDgQWBBSaryl6wBE1NSZRMADDav5A1a7WPDAPBgNVHRMBAf8EBTADAQH/MA4G\nA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAwNnADBkAjAXCfOHiFBar8jAQr9HX/Vs\naobgxCd05DhT1wV/GzTjxi+zygk8N53X57hG8f2h4nECMEJZh0PUUd+60wkyWs6I\nflc9nF9Ca/UHLbXwgpP5WW+uZPpY5Yse42O+tYHNbwKMeQ==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certum Trusted Network CA O=Unizeto Technologies S.A. OU=Certum Certification Authority\n# Subject: CN=Certum Trusted Network CA O=Unizeto Technologies S.A. OU=Certum Certification Authority\n# Label: \"Certum Trusted Network CA\"\n# Serial: 279744\n# MD5 Fingerprint: d5:e9:81:40:c5:18:69:fc:46:2c:89:75:62:0f:aa:78\n# SHA1 Fingerprint: 07:e0:32:e0:20:b7:2c:3f:19:2f:06:28:a2:59:3a:19:a7:0f:06:9e\n# SHA256 Fingerprint: 5c:58:46:8d:55:f5:8e:49:7e:74:39:82:d2:b5:00:10:b6:d1:65:37:4a:cf:83:a7:d4:a3:2d:b7:68:c4:40:8e\n-----BEGIN CERTIFICATE-----\nMIIDuzCCAqOgAwIBAgIDBETAMA0GCSqGSIb3DQEBBQUAMH4xCzAJBgNVBAYTAlBM\nMSIwIAYDVQQKExlVbml6ZXRvIFRlY2hub2xvZ2llcyBTLkEuMScwJQYDVQQLEx5D\nZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxIjAgBgNVBAMTGUNlcnR1bSBU\ncnVzdGVkIE5ldHdvcmsgQ0EwHhcNMDgxMDIyMTIwNzM3WhcNMjkxMjMxMTIwNzM3\nWjB+MQswCQYDVQQGEwJQTDEiMCAGA1UEChMZVW5pemV0byBUZWNobm9sb2dpZXMg\nUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MSIw\nIAYDVQQDExlDZXJ0dW0gVHJ1c3RlZCBOZXR3b3JrIENBMIIBIjANBgkqhkiG9w0B\nAQEFAAOCAQ8AMIIBCgKCAQEA4/t9o3K6wvDJFIf1awFO4W5AB7ptJ11/91sts1rH\nUV+rpDKmYYe2bg+G0jACl/jXaVehGDldamR5xgFZrDwxSjh80gTSSyjoIF87B6LM\nTXPb865Px1bVWqeWifrzq2jUI4ZZJ88JJ7ysbnKDHDBy3+Ci6dLhdHUZvSqeexVU\nBBvXQzmtVSjF4hq79MDkrjhJM8x2hZ85RdKknvISjFH4fOQtf/WsX+sWn7Et0brM\nkUJ3TCXJkDhv2/DM+44el1k+1WBO5gUo7Ul5E0u6SNsv+XLTOcr+H9g0cvW0QM8x\nAcPs3hEtF10fuFDRXhmnad4HMyjKUJX5p1TLVIZQRan5SQIDAQABo0IwQDAPBgNV\nHRMBAf8EBTADAQH/MB0GA1UdDgQWBBQIds3LB/8k9sXN7buQvOKEN0Z19zAOBgNV\nHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQEFBQADggEBAKaorSLOAT2mo/9i0Eidi15y\nsHhE49wcrwn9I0j6vSrEuVUEtRCjjSfeC4Jj0O7eDDd5QVsisrCaQVymcODU0HfL\nI9MA4GxWL+FpDQ3Zqr8hgVDZBqWo/5U30Kr+4rP1mS1FhIrlQgnXdAIv94nYmem8\nJ9RHjboNRhx3zxSkHLmkMcScKHQDNP8zGSal6Q10tz6XxnboJ5ajZt3hrvJBW8qY\nVoNzcOSGGtIxQbovvi0TWnZvTuhOgQ4/WwMioBK+ZlgRSssDxLQqKi2WF+A5VLxI\n03YnnZotBqbJ7DnSq9ufmgsnAjUpsUCV5/nonFWIGUbWtzT1fs45mtk48VH3Tyw=\n-----END CERTIFICATE-----\n\n# Issuer: CN=TWCA Root Certification Authority O=TAIWAN-CA OU=Root CA\n# Subject: CN=TWCA Root Certification Authority O=TAIWAN-CA OU=Root CA\n# Label: \"TWCA Root Certification Authority\"\n# Serial: 1\n# MD5 Fingerprint: aa:08:8f:f6:f9:7b:b7:f2:b1:a7:1e:9b:ea:ea:bd:79\n# SHA1 Fingerprint: cf:9e:87:6d:d3:eb:fc:42:26:97:a3:b5:a3:7a:a0:76:a9:06:23:48\n# SHA256 Fingerprint: bf:d8:8f:e1:10:1c:41:ae:3e:80:1b:f8:be:56:35:0e:e9:ba:d1:a6:b9:bd:51:5e:dc:5c:6d:5b:87:11:ac:44\n-----BEGIN CERTIFICATE-----\nMIIDezCCAmOgAwIBAgIBATANBgkqhkiG9w0BAQUFADBfMQswCQYDVQQGEwJUVzES\nMBAGA1UECgwJVEFJV0FOLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFU\nV0NBIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMDgwODI4MDcyNDMz\nWhcNMzAxMjMxMTU1OTU5WjBfMQswCQYDVQQGEwJUVzESMBAGA1UECgwJVEFJV0FO\nLUNBMRAwDgYDVQQLDAdSb290IENBMSowKAYDVQQDDCFUV0NBIFJvb3QgQ2VydGlm\naWNhdGlvbiBBdXRob3JpdHkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\nAQCwfnK4pAOU5qfeCTiRShFAh6d8WWQUe7UREN3+v9XAu1bihSX0NXIP+FPQQeFE\nAcK0HMMxQhZHhTMidrIKbw/lJVBPhYa+v5guEGcevhEFhgWQxFnQfHgQsIBct+HH\nK3XLfJ+utdGdIzdjp9xCoi2SBBtQwXu4PhvJVgSLL1KbralW6cH/ralYhzC2gfeX\nRfwZVzsrb+RH9JlF/h3x+JejiB03HFyP4HYlmlD4oFT/RJB2I9IyxsOrBr/8+7/z\nrX2SYgJbKdM1o5OaQ2RgXbL6Mv87BK9NQGr5x+PvI/1ry+UPizgN7gr8/g+YnzAx\n3WxSZfmLgb4i4RxYA7qRG4kHAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\nHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqOFsmjd6LWvJPelSDGRjjCDWmujANBgkq\nhkiG9w0BAQUFAAOCAQEAPNV3PdrfibqHDAhUaiBQkr6wQT25JmSDCi/oQMCXKCeC\nMErJk/9q56YAf4lCmtYR5VPOL8zy2gXE/uJQxDqGfczafhAJO5I1KlOy/usrBdls\nXebQ79NqZp4VKIV66IIArB6nCWlWQtNoURi+VJq/REG6Sb4gumlc7rh3zc5sH62D\nlhh9DrUUOYTxKOkto557HnpyWoOzeW/vtPzQCqVYT0bf+215WfKEIlKuD8z7fDvn\naspHYcN6+NOSBB+4IIThNlQWx0DeO4pz3N/GCUzf7Nr/1FNCocnyYh0igzyXxfkZ\nYiesZSLX0zzG5Y6yU8xJzrww/nsOM5D77dIUkR8Hrw==\n-----END CERTIFICATE-----\n\n# Issuer: O=SECOM Trust Systems CO.,LTD. OU=Security Communication RootCA2\n# Subject: O=SECOM Trust Systems CO.,LTD. OU=Security Communication RootCA2\n# Label: \"Security Communication RootCA2\"\n# Serial: 0\n# MD5 Fingerprint: 6c:39:7d:a4:0e:55:59:b2:3f:d6:41:b1:12:50:de:43\n# SHA1 Fingerprint: 5f:3b:8c:f2:f8:10:b3:7d:78:b4:ce:ec:19:19:c3:73:34:b9:c7:74\n# SHA256 Fingerprint: 51:3b:2c:ec:b8:10:d4:cd:e5:dd:85:39:1a:df:c6:c2:dd:60:d8:7b:b7:36:d2:b5:21:48:4a:a4:7a:0e:be:f6\n-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDEl\nMCMGA1UEChMcU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMe\nU2VjdXJpdHkgQ29tbXVuaWNhdGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoX\nDTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRy\ndXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3VyaXR5IENvbW11bmlj\nYXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAV\nOVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGr\nzbl+dp+++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVM\nVAX3NuRFg3sUZdbcDE3R3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQ\nhNBqyjoGADdH5H5XTz+L62e4iKrFvlNVspHEfbmwhRkGeC7bYRr6hfVKkaHnFtWO\nojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1KEOtOghY6rCcMU/Gt1SSw\nawNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8QIH4D5cs\nOPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3\nDQEBCwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpF\ncoJxDjrSzG+ntKEju/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXc\nokgfGT+Ok+vx+hfuzU7jBBJV1uXk3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8\nt/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6qtnRGEmyR7jTV7JqR50S+kDFy\n1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29mvVXIwAHIRc/\nSjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03\n-----END CERTIFICATE-----\n\n# Issuer: CN=Actalis Authentication Root CA O=Actalis S.p.A./03358520967\n# Subject: CN=Actalis Authentication Root CA O=Actalis S.p.A./03358520967\n# Label: \"Actalis Authentication Root CA\"\n# Serial: 6271844772424770508\n# MD5 Fingerprint: 69:c1:0d:4f:07:a3:1b:c3:fe:56:3d:04:bc:11:f6:a6\n# SHA1 Fingerprint: f3:73:b3:87:06:5a:28:84:8a:f2:f3:4a:ce:19:2b:dd:c7:8e:9c:ac\n# SHA256 Fingerprint: 55:92:60:84:ec:96:3a:64:b9:6e:2a:be:01:ce:0b:a8:6a:64:fb:fe:bc:c7:aa:b5:af:c1:55:b3:7f:d7:60:66\n-----BEGIN CERTIFICATE-----\nMIIFuzCCA6OgAwIBAgIIVwoRl0LE48wwDQYJKoZIhvcNAQELBQAwazELMAkGA1UE\nBhMCSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8w\nMzM1ODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290\nIENBMB4XDTExMDkyMjExMjIwMloXDTMwMDkyMjExMjIwMlowazELMAkGA1UEBhMC\nSVQxDjAMBgNVBAcMBU1pbGFuMSMwIQYDVQQKDBpBY3RhbGlzIFMucC5BLi8wMzM1\nODUyMDk2NzEnMCUGA1UEAwweQWN0YWxpcyBBdXRoZW50aWNhdGlvbiBSb290IENB\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAp8bEpSmkLO/lGMWwUKNv\nUTufClrJwkg4CsIcoBh/kbWHuUA/3R1oHwiD1S0eiKD4j1aPbZkCkpAW1V8IbInX\n4ay8IMKx4INRimlNAJZaby/ARH6jDuSRzVju3PvHHkVH3Se5CAGfpiEd9UEtL0z9\nKK3giq0itFZljoZUj5NDKd45RnijMCO6zfB9E1fAXdKDa0hMxKufgFpbOr3JpyI/\ngCczWw63igxdBzcIy2zSekciRDXFzMwujt0q7bd9Zg1fYVEiVRvjRuPjPdA1Yprb\nrxTIW6HMiRvhMCb8oJsfgadHHwTrozmSBp+Z07/T6k9QnBn+locePGX2oxgkg4YQ\n51Q+qDp2JE+BIcXjDwL4k5RHILv+1A7TaLndxHqEguNTVHnd25zS8gebLra8Pu2F\nbe8lEfKXGkJh90qX6IuxEAf6ZYGyojnP9zz/GPvG8VqLWeICrHuS0E4UT1lF9gxe\nKF+w6D9Fz8+vm2/7hNN3WpVvrJSEnu68wEqPSpP4RCHiMUVhUE4Q2OM1fEwZtN4F\nv6MGn8i1zeQf1xcGDXqVdFUNaBr8EBtiZJ1t4JWgw5QHVw0U5r0F+7if5t+L4sbn\nfpb2U8WANFAoWPASUHEXMLrmeGO89LKtmyuy/uE5jF66CyCU3nuDuP/jVo23Eek7\njPKxwV2dpAtMK9myGPW1n0sCAwEAAaNjMGEwHQYDVR0OBBYEFFLYiDrIn3hm7Ynz\nezhwlMkCAjbQMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUUtiIOsifeGbt\nifN7OHCUyQICNtAwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQAL\ne3KHwGCmSUyIWOYdiPcUZEim2FgKDk8TNd81HdTtBjHIgT5q1d07GjLukD0R0i70\njsNjLiNmsGe+b7bAEzlgqqI0JZN1Ut6nna0Oh4lScWoWPBkdg/iaKWW+9D+a2fDz\nWochcYBNy+A4mz+7+uAwTc+G02UQGRjRlwKxK3JCaKygvU5a2hi/a5iB0P2avl4V\nSM0RFbnAKVy06Ij3Pjaut2L9HmLecHgQHEhb2rykOLpn7VU+Xlff1ANATIGk0k9j\npwlCCRT8AKnCgHNPLsBA2RF7SOp6AsDT6ygBJlh0wcBzIm2Tlf05fbsq4/aC4yyX\nX04fkZT6/iyj2HYauE2yOE+b+h1IYHkm4vP9qdCa6HCPSXrW5b0KDtst842/6+Ok\nfcvHlXHo2qN8xcL4dJIEG4aspCJTQLas/kx2z/uUMsA1n3Y/buWQbqCmJqK4LL7R\nK4X9p2jIugErsWx0Hbhzlefut8cl8ABMALJ+tguLHPPAUJ4lueAI3jZm/zel0btU\nZCzJJ7VLkn5l/9Mt4blOvH+kQSGQQXemOR/qnuOf0GZvBeyqdn6/axag67XH/JJU\nLysRJyU3eExRarDzzFhdFPFqSBX/wge2sY0PjlxQRrM9vwGYT7JZVEc+NHt4bVaT\nLnPqZih4zR0Uv6CPLy64Lo7yFIrM6bV8+2ydDKXhlg==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Buypass Class 2 Root CA O=Buypass AS-983163327\n# Subject: CN=Buypass Class 2 Root CA O=Buypass AS-983163327\n# Label: \"Buypass Class 2 Root CA\"\n# Serial: 2\n# MD5 Fingerprint: 46:a7:d2:fe:45:fb:64:5a:a8:59:90:9b:78:44:9b:29\n# SHA1 Fingerprint: 49:0a:75:74:de:87:0a:47:fe:58:ee:f6:c7:6b:eb:c6:0b:12:40:99\n# SHA256 Fingerprint: 9a:11:40:25:19:7c:5b:b9:5d:94:e6:3d:55:cd:43:79:08:47:b6:46:b2:3c:df:11:ad:a4:a0:0e:ff:15:fb:48\n-----BEGIN CERTIFICATE-----\nMIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd\nMBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg\nQ2xhc3MgMiBSb290IENBMB4XDTEwMTAyNjA4MzgwM1oXDTQwMTAyNjA4MzgwM1ow\nTjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw\nHgYDVQQDDBdCdXlwYXNzIENsYXNzIDIgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB\nBQADggIPADCCAgoCggIBANfHXvfBB9R3+0Mh9PT1aeTuMgHbo4Yf5FkNuud1g1Lr\n6hxhFUi7HQfKjK6w3Jad6sNgkoaCKHOcVgb/S2TwDCo3SbXlzwx87vFKu3MwZfPV\nL4O2fuPn9Z6rYPnT8Z2SdIrkHJasW4DptfQxh6NR/Md+oW+OU3fUl8FVM5I+GC91\n1K2GScuVr1QGbNgGE41b/+EmGVnAJLqBcXmQRFBoJJRfuLMR8SlBYaNByyM21cHx\nMlAQTn/0hpPshNOOvEu/XAFOBz3cFIqUCqTqc/sLUegTBxj6DvEr0VQVfTzh97QZ\nQmdiXnfgolXsttlpF9U6r0TtSsWe5HonfOV116rLJeffawrbD02TTqigzXsu8lkB\narcNuAeBfos4GzjmCleZPe4h6KP1DBbdi+w0jpwqHAAVF41og9JwnxgIzRFo1clr\nUs3ERo/ctfPYV3Me6ZQ5BL/T3jjetFPsaRyifsSP5BtwrfKi+fv3FmRmaZ9JUaLi\nFRhnBkp/1Wy1TbMz4GHrXb7pmA8y1x1LPC5aAVKRCfLf6o3YBkBjqhHk/sM3nhRS\nP/TizPJhk9H9Z2vXUq6/aKtAQ6BXNVN48FP4YUIHZMbXb5tMOA1jrGKvNouicwoN\n9SG9dKpN6nIDSdvHXx1iY8f93ZHsM+71bbRuMGjeyNYmsHVee7QHIJihdjK4TWxP\nAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFMmAd+BikoL1Rpzz\nuvdMw964o605MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAU18h\n9bqwOlI5LJKwbADJ784g7wbylp7ppHR/ehb8t/W2+xUbP6umwHJdELFx7rxP462s\nA20ucS6vxOOto70MEae0/0qyexAQH6dXQbLArvQsWdZHEIjzIVEpMMpghq9Gqx3t\nOluwlN5E40EIosHsHdb9T7bWR9AUC8rmyrV7d35BH16Dx7aMOZawP5aBQW9gkOLo\n+fsicdl9sz1Gv7SEr5AcD48Saq/v7h56rgJKihcrdv6sVIkkLE8/trKnToyokZf7\nKcZ7XC25y2a2t6hbElGFtQl+Ynhw/qlqYLYdDnkM/crqJIByw5c/8nerQyIKx+u2\nDISCLIBrQYoIwOula9+ZEsuK1V6ADJHgJgg2SMX6OBE1/yWDLfJ6v9r9jv6ly0Us\nH8SIU653DtmadsWOLB2jutXsMq7Aqqz30XpN69QH4kj3Io6wpJ9qzo6ysmD0oyLQ\nI+uUWnpp3Q+/QFesa1lQ2aOZ4W7+jQF5JyMV3pKdewlNWudLSDBaGOYKbeaP4NK7\n5t98biGCwWg5TbSYWGZizEqQXsP6JwSxeRV0mcy+rSDeJmAc61ZRpqPq5KM/p/9h\n3PFaTWwyI0PurKju7koSCTxdccK+efrCh2gdC/1cacwG0Jp9VJkqyTkaGa9LKkPz\nY11aWOIv4x3kqdbQCtCev9eBCfHJxyYNrJgWVqA=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Buypass Class 3 Root CA O=Buypass AS-983163327\n# Subject: CN=Buypass Class 3 Root CA O=Buypass AS-983163327\n# Label: \"Buypass Class 3 Root CA\"\n# Serial: 2\n# MD5 Fingerprint: 3d:3b:18:9e:2c:64:5a:e8:d5:88:ce:0e:f9:37:c2:ec\n# SHA1 Fingerprint: da:fa:f7:fa:66:84:ec:06:8f:14:50:bd:c7:c2:81:a5:bc:a9:64:57\n# SHA256 Fingerprint: ed:f7:eb:bc:a2:7a:2a:38:4d:38:7b:7d:40:10:c6:66:e2:ed:b4:84:3e:4c:29:b4:ae:1d:5b:93:32:e6:b2:4d\n-----BEGIN CERTIFICATE-----\nMIIFWTCCA0GgAwIBAgIBAjANBgkqhkiG9w0BAQsFADBOMQswCQYDVQQGEwJOTzEd\nMBsGA1UECgwUQnV5cGFzcyBBUy05ODMxNjMzMjcxIDAeBgNVBAMMF0J1eXBhc3Mg\nQ2xhc3MgMyBSb290IENBMB4XDTEwMTAyNjA4Mjg1OFoXDTQwMTAyNjA4Mjg1OFow\nTjELMAkGA1UEBhMCTk8xHTAbBgNVBAoMFEJ1eXBhc3MgQVMtOTgzMTYzMzI3MSAw\nHgYDVQQDDBdCdXlwYXNzIENsYXNzIDMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEB\nBQADggIPADCCAgoCggIBAKXaCpUWUOOV8l6ddjEGMnqb8RB2uACatVI2zSRHsJ8Y\nZLya9vrVediQYkwiL944PdbgqOkcLNt4EemOaFEVcsfzM4fkoF0LXOBXByow9c3E\nN3coTRiR5r/VUv1xLXA+58bEiuPwKAv0dpihi4dVsjoT/Lc+JzeOIuOoTyrvYLs9\ntznDDgFHmV0ST9tD+leh7fmdvhFHJlsTmKtdFoqwNxxXnUX/iJY2v7vKB3tvh2PX\n0DJq1l1sDPGzbjniazEuOQAnFN44wOwZZoYS6J1yFhNkUsepNxz9gjDthBgd9K5c\n/3ATAOux9TN6S9ZV+AWNS2mw9bMoNlwUxFFzTWsL8TQH2xc519woe2v1n/MuwU8X\nKhDzzMro6/1rqy6any2CbgTUUgGTLT2G/H783+9CHaZr77kgxve9oKeV/afmiSTY\nzIw0bOIjL9kSGiG5VZFvC5F5GQytQIgLcOJ60g7YaEi7ghM5EFjp2CoHxhLbWNvS\nO1UQRwUVZ2J+GGOmRj8JDlQyXr8NYnon74Do29lLBlo3WiXQCBJ31G8JUJc9yB3D\n34xFMFbG02SrZvPAXpacw8Tvw3xrizp5f7NJzz3iiZ+gMEuFuZyUJHmPfWupRWgP\nK9Dx2hzLabjKSWJtyNBjYt1gD1iqj6G8BaVmos8bdrKEZLFMOVLAMLrwjEsCsLa3\nAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFEe4zf/lb+74suwv\nTg75JbCOPGvDMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAACAj\nQTUEkMJAYmDv4jVM1z+s4jSQuKFvdvoWFqRINyzpkMLyPPgKn9iB5btb2iUspKdV\ncSQy9sgL8rxq+JOssgfCX5/bzMiKqr5qb+FJEMwx14C7u8jYog5kV+qi9cKpMRXS\nIGrs/CIBKM+GuIAeqcwRpTzyFrNHnfzSgCHEy9BHcEGhyoMZCCxt8l13nIoUE9Q2\nHJLw5QY33KbmkJs4j1xrG0aGQ0JfPgEHU1RdZX33inOhmlRaHylDFCfChQ+1iHsa\nO5S3HWCntZznKWlXWpuTekMwGwPXYshApqr8ZORK15FTAaggiG6cX0S5y2CBNOxv\n033aSF/rtJC8LakcC6wc1aJoIIAE1vyxjy+7SjENSoYc6+I2KSb12tjE8nVhz36u\ndmNKekBlk4f4HoCMhuWG1o8O/FMsYOgWYRqiPkN7zTlgVGr18okmAWiDSKIz6MkE\nkbIRNBE+6tBDGR8Dk5AM/1E9V/RBbuHLoL7ryWPNbczk+DaqaJ3tvV2XcEQNtg41\n3OEMXbugUZTLfhbrES+jkkXITHHZvMmZUldGL1DPvTVp9D0VzgalLA8+9oG6lLvD\nu79leNKGef9JOxqDDPDeeOzI8k1MGt6CKfjBWtrt7uYnXuhF0J0cUahoq0Tj0Itq\n4/g7u9xN12TyUb7mqqta6THuBrxzvxNiCp/HuZc=\n-----END CERTIFICATE-----\n\n# Issuer: CN=T-TeleSec GlobalRoot Class 3 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center\n# Subject: CN=T-TeleSec GlobalRoot Class 3 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center\n# Label: \"T-TeleSec GlobalRoot Class 3\"\n# Serial: 1\n# MD5 Fingerprint: ca:fb:40:a8:4e:39:92:8a:1d:fe:8e:2f:c4:27:ea:ef\n# SHA1 Fingerprint: 55:a6:72:3e:cb:f2:ec:cd:c3:23:74:70:19:9d:2a:be:11:e3:81:d1\n# SHA256 Fingerprint: fd:73:da:d3:1c:64:4f:f1:b4:3b:ef:0c:cd:da:96:71:0b:9c:d9:87:5e:ca:7e:31:70:7a:f3:e9:6d:52:2b:bd\n-----BEGIN CERTIFICATE-----\nMIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx\nKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd\nBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl\nYyBHbG9iYWxSb290IENsYXNzIDMwHhcNMDgxMDAxMTAyOTU2WhcNMzMxMDAxMjM1\nOTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy\naXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50\nZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDMwggEiMA0G\nCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC9dZPwYiJvJK7genasfb3ZJNW4t/zN\n8ELg63iIVl6bmlQdTQyK9tPPcPRStdiTBONGhnFBSivwKixVA9ZIw+A5OO3yXDw/\nRLyTPWGrTs0NvvAgJ1gORH8EGoel15YUNpDQSXuhdfsaa3Ox+M6pCSzyU9XDFES4\nhqX2iys52qMzVNn6chr3IhUciJFrf2blw2qAsCTz34ZFiP0Zf3WHHx+xGwpzJFu5\nZeAsVMhg02YXP+HMVDNzkQI6pn97djmiH5a2OK61yJN0HZ65tOVgnS9W0eDrXltM\nEnAMbEQgqxHY9Bn20pxSN+f6tsIxO0rUFJmtxxr1XV/6B7h8DR/Wgx6zAgMBAAGj\nQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS1\nA/d2O2GCahKqGFPrAyGUv/7OyjANBgkqhkiG9w0BAQsFAAOCAQEAVj3vlNW92nOy\nWL6ukK2YJ5f+AbGwUgC4TeQbIXQbfsDuXmkqJa9c1h3a0nnJ85cp4IaH3gRZD/FZ\n1GSFS5mvJQQeyUapl96Cshtwn5z2r3Ex3XsFpSzTucpH9sry9uetuUg/vBa3wW30\n6gmv7PO15wWeph6KU1HWk4HMdJP2udqmJQV0eVp+QD6CSyYRMG7hP0HHRwA11fXT\n91Q+gT3aSWqas+8QPebrb9HIIkfLzM8BMZLZGOMivgkeGj5asuRrDFR6fUNOuIml\ne9eiPZaGzPImNC1qkp2aGtAw4l1OBLBfiyB+d8E9lYLRRpo7PHi4b6HQDWSieB4p\nTpPDpFQUWw==\n-----END CERTIFICATE-----\n\n# Issuer: CN=D-TRUST Root Class 3 CA 2 2009 O=D-Trust GmbH\n# Subject: CN=D-TRUST Root Class 3 CA 2 2009 O=D-Trust GmbH\n# Label: \"D-TRUST Root Class 3 CA 2 2009\"\n# Serial: 623603\n# MD5 Fingerprint: cd:e0:25:69:8d:47:ac:9c:89:35:90:f7:fd:51:3d:2f\n# SHA1 Fingerprint: 58:e8:ab:b0:36:15:33:fb:80:f7:9b:1b:6d:29:d3:ff:8d:5f:00:f0\n# SHA256 Fingerprint: 49:e7:a4:42:ac:f0:ea:62:87:05:00:54:b5:25:64:b6:50:e4:f4:9e:42:e3:48:d6:aa:38:e0:39:e9:57:b1:c1\n-----BEGIN CERTIFICATE-----\nMIIEMzCCAxugAwIBAgIDCYPzMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNVBAYTAkRF\nMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMMHkQtVFJVU1QgUm9vdCBD\nbGFzcyAzIENBIDIgMjAwOTAeFw0wOTExMDUwODM1NThaFw0yOTExMDUwODM1NTha\nME0xCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxJzAlBgNVBAMM\nHkQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgMjAwOTCCASIwDQYJKoZIhvcNAQEB\nBQADggEPADCCAQoCggEBANOySs96R+91myP6Oi/WUEWJNTrGa9v+2wBoqOADER03\nUAifTUpolDWzU9GUY6cgVq/eUXjsKj3zSEhQPgrfRlWLJ23DEE0NkVJD2IfgXU42\ntSHKXzlABF9bfsyjxiupQB7ZNoTWSPOSHjRGICTBpFGOShrvUD9pXRl/RcPHAY9R\nySPocq60vFYJfxLLHLGvKZAKyVXMD9O0Gu1HNVpK7ZxzBCHQqr0ME7UAyiZsxGsM\nlFqVlNpQmvH/pStmMaTJOKDfHR+4CS7zp+hnUquVH+BGPtikw8paxTGA6Eian5Rp\n/hnd2HN8gcqW3o7tszIFZYQ05ub9VxC1X3a/L7AQDcUCAwEAAaOCARowggEWMA8G\nA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFP3aFMSfMN4hvR5COfyrYyNJ4PGEMA4G\nA1UdDwEB/wQEAwIBBjCB0wYDVR0fBIHLMIHIMIGAoH6gfIZ6bGRhcDovL2RpcmVj\ndG9yeS5kLXRydXN0Lm5ldC9DTj1ELVRSVVNUJTIwUm9vdCUyMENsYXNzJTIwMyUy\nMENBJTIwMiUyMDIwMDksTz1ELVRydXN0JTIwR21iSCxDPURFP2NlcnRpZmljYXRl\ncmV2b2NhdGlvbmxpc3QwQ6BBoD+GPWh0dHA6Ly93d3cuZC10cnVzdC5uZXQvY3Js\nL2QtdHJ1c3Rfcm9vdF9jbGFzc18zX2NhXzJfMjAwOS5jcmwwDQYJKoZIhvcNAQEL\nBQADggEBAH+X2zDI36ScfSF6gHDOFBJpiBSVYEQBrLLpME+bUMJm2H6NMLVwMeni\nacfzcNsgFYbQDfC+rAF1hM5+n02/t2A7nPPKHeJeaNijnZflQGDSNiH+0LS4F9p0\no3/U37CYAqxva2ssJSRyoWXuJVrl5jLn8t+rSfrzkGkj2wTZ51xY/GXUl77M/C4K\nzCUqNQT4YJEVdT1B/yMfGchs64JTBKbkTCJNjYy6zltz7GRUUG3RnFX7acM2w4y8\nPIWmawomDeCTmGCufsYkl4phX5GOZpIJhzbNi5stPvZR1FDUWSi9g/LMKHtThm3Y\nJohw1+qRzT65ysCQblrGXnRl11z+o+I=\n-----END CERTIFICATE-----\n\n# Issuer: CN=D-TRUST Root Class 3 CA 2 EV 2009 O=D-Trust GmbH\n# Subject: CN=D-TRUST Root Class 3 CA 2 EV 2009 O=D-Trust GmbH\n# Label: \"D-TRUST Root Class 3 CA 2 EV 2009\"\n# Serial: 623604\n# MD5 Fingerprint: aa:c6:43:2c:5e:2d:cd:c4:34:c0:50:4f:11:02:4f:b6\n# SHA1 Fingerprint: 96:c9:1b:0b:95:b4:10:98:42:fa:d0:d8:22:79:fe:60:fa:b9:16:83\n# SHA256 Fingerprint: ee:c5:49:6b:98:8c:e9:86:25:b9:34:09:2e:ec:29:08:be:d0:b0:f3:16:c2:d4:73:0c:84:ea:f1:f3:d3:48:81\n-----BEGIN CERTIFICATE-----\nMIIEQzCCAyugAwIBAgIDCYP0MA0GCSqGSIb3DQEBCwUAMFAxCzAJBgNVBAYTAkRF\nMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNVBAMMIUQtVFJVU1QgUm9vdCBD\nbGFzcyAzIENBIDIgRVYgMjAwOTAeFw0wOTExMDUwODUwNDZaFw0yOTExMDUwODUw\nNDZaMFAxCzAJBgNVBAYTAkRFMRUwEwYDVQQKDAxELVRydXN0IEdtYkgxKjAoBgNV\nBAMMIUQtVFJVU1QgUm9vdCBDbGFzcyAzIENBIDIgRVYgMjAwOTCCASIwDQYJKoZI\nhvcNAQEBBQADggEPADCCAQoCggEBAJnxhDRwui+3MKCOvXwEz75ivJn9gpfSegpn\nljgJ9hBOlSJzmY3aFS3nBfwZcyK3jpgAvDw9rKFs+9Z5JUut8Mxk2og+KbgPCdM0\n3TP1YtHhzRnp7hhPTFiu4h7WDFsVWtg6uMQYZB7jM7K1iXdODL/ZlGsTl28So/6Z\nqQTMFexgaDbtCHu39b+T7WYxg4zGcTSHThfqr4uRjRxWQa4iN1438h3Z0S0NL2lR\np75mpoo6Kr3HGrHhFPC+Oh25z1uxav60sUYgovseO3Dvk5h9jHOW8sXvhXCtKSb8\nHgQ+HKDYD8tSg2J87otTlZCpV6LqYQXY+U3EJ/pure3511H3a6UCAwEAAaOCASQw\nggEgMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFNOUikxiEyoZLsyvcop9Ntea\nHNxnMA4GA1UdDwEB/wQEAwIBBjCB3QYDVR0fBIHVMIHSMIGHoIGEoIGBhn9sZGFw\nOi8vZGlyZWN0b3J5LmQtdHJ1c3QubmV0L0NOPUQtVFJVU1QlMjBSb290JTIwQ2xh\nc3MlMjAzJTIwQ0ElMjAyJTIwRVYlMjAyMDA5LE89RC1UcnVzdCUyMEdtYkgsQz1E\nRT9jZXJ0aWZpY2F0ZXJldm9jYXRpb25saXN0MEagRKBChkBodHRwOi8vd3d3LmQt\ndHJ1c3QubmV0L2NybC9kLXRydXN0X3Jvb3RfY2xhc3NfM19jYV8yX2V2XzIwMDku\nY3JsMA0GCSqGSIb3DQEBCwUAA4IBAQA07XtaPKSUiO8aEXUHL7P+PPoeUSbrh/Yp\n3uDx1MYkCenBz1UbtDDZzhr+BlGmFaQt77JLvyAoJUnRpjZ3NOhk31KxEcdzes05\nnsKtjHEh8lprr988TlWvsoRlFIm5d8sqMb7Po23Pb0iUMkZv53GMoKaEGTcH8gNF\nCSuGdXzfX2lXANtu2KZyIktQ1HWYVt+3GP9DQ1CuekR78HlR10M9p9OB0/DJT7na\nxpeG0ILD5EJt/rDiZE4OJudANCa1CInXCGNjOCd1HjPqbqjdn5lPdE2BiYBL3ZqX\nKVwvvoFBuYz/6n1gBp7N1z3TLqMVvKjmJuVvw9y4AyHqnxbxLFS1\n-----END CERTIFICATE-----\n\n# Issuer: CN=CA Disig Root R2 O=Disig a.s.\n# Subject: CN=CA Disig Root R2 O=Disig a.s.\n# Label: \"CA Disig Root R2\"\n# Serial: 10572350602393338211\n# MD5 Fingerprint: 26:01:fb:d8:27:a7:17:9a:45:54:38:1a:43:01:3b:03\n# SHA1 Fingerprint: b5:61:eb:ea:a4:de:e4:25:4b:69:1a:98:a5:57:47:c2:34:c7:d9:71\n# SHA256 Fingerprint: e2:3d:4a:03:6d:7b:70:e9:f5:95:b1:42:20:79:d2:b9:1e:df:bb:1f:b6:51:a0:63:3e:aa:8a:9d:c5:f8:07:03\n-----BEGIN CERTIFICATE-----\nMIIFaTCCA1GgAwIBAgIJAJK4iNuwisFjMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNV\nBAYTAlNLMRMwEQYDVQQHEwpCcmF0aXNsYXZhMRMwEQYDVQQKEwpEaXNpZyBhLnMu\nMRkwFwYDVQQDExBDQSBEaXNpZyBSb290IFIyMB4XDTEyMDcxOTA5MTUzMFoXDTQy\nMDcxOTA5MTUzMFowUjELMAkGA1UEBhMCU0sxEzARBgNVBAcTCkJyYXRpc2xhdmEx\nEzARBgNVBAoTCkRpc2lnIGEucy4xGTAXBgNVBAMTEENBIERpc2lnIFJvb3QgUjIw\nggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCio8QACdaFXS1tFPbCw3Oe\nNcJxVX6B+6tGUODBfEl45qt5WDza/3wcn9iXAng+a0EE6UG9vgMsRfYvZNSrXaNH\nPWSb6WiaxswbP7q+sos0Ai6YVRn8jG+qX9pMzk0DIaPY0jSTVpbLTAwAFjxfGs3I\nx2ymrdMxp7zo5eFm1tL7A7RBZckQrg4FY8aAamkw/dLukO8NJ9+flXP04SXabBbe\nQTg06ov80egEFGEtQX6sx3dOy1FU+16SGBsEWmjGycT6txOgmLcRK7fWV8x8nhfR\nyyX+hk4kLlYMeE2eARKmK6cBZW58Yh2EhN/qwGu1pSqVg8NTEQxzHQuyRpDRQjrO\nQG6Vrf/GlK1ul4SOfW+eioANSW1z4nuSHsPzwfPrLgVv2RvPN3YEyLRa5Beny912\nH9AZdugsBbPWnDTYltxhh5EF5EQIM8HauQhl1K6yNg3ruji6DOWbnuuNZt2Zz9aJ\nQfYEkoopKW1rOhzndX0CcQ7zwOe9yxndnWCywmZgtrEE7snmhrmaZkCo5xHtgUUD\ni/ZnWejBBhG93c+AAk9lQHhcR1DIm+YfgXvkRKhbhZri3lrVx/k6RGZL5DJUfORs\nnLMOPReisjQS1n6yqEm70XooQL6iFh/f5DcfEXP7kAplQ6INfPgGAVUzfbANuPT1\nrqVCV3w2EYx7XsQDnYx5nQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1Ud\nDwEB/wQEAwIBBjAdBgNVHQ4EFgQUtZn4r7CU9eMg1gqtzk5WpC5uQu0wDQYJKoZI\nhvcNAQELBQADggIBACYGXnDnZTPIgm7ZnBc6G3pmsgH2eDtpXi/q/075KMOYKmFM\ntCQSin1tERT3nLXK5ryeJ45MGcipvXrA1zYObYVybqjGom32+nNjf7xueQgcnYqf\nGopTpti72TVVsRHFqQOzVju5hJMiXn7B9hJSi+osZ7z+Nkz1uM/Rs0mSO9MpDpkb\nlvdhuDvEK7Z4bLQjb/D907JedR+Zlais9trhxTF7+9FGs9K8Z7RiVLoJ92Owk6Ka\n+elSLotgEqv89WBW7xBci8QaQtyDW2QOy7W81k/BfDxujRNt+3vrMNDcTa/F1bal\nTFtxyegxvug4BkihGuLq0t4SOVga/4AOgnXmt8kHbA7v/zjxmHHEt38OFdAlab0i\nnSvtBfZGR6ztwPDUO+Ls7pZbkBNOHlY667DvlruWIxG68kOGdGSVyCh13x01utI3\ngzhTODY7z2zp+WsO0PsE6E9312UBeIYMej4hYvF/Y3EMyZ9E26gnonW+boE+18Dr\nG5gPcFw0sorMwIUY6256s/daoQe/qUKS82Ail+QUoQebTnbAjn39pCXHR+3/H3Os\nzMOl6W8KjptlwlCFtaOgUxLMVYdh84GuEEZhvUQhuMI9dM9+JDX6HAcOmz0iyu8x\nL4ysEr3vQCj8KWefshNPZiTEUxnpHikV7+ZtsH8tZ/3zbBt1RqPlShfppNcL\n-----END CERTIFICATE-----\n\n# Issuer: CN=ACCVRAIZ1 O=ACCV OU=PKIACCV\n# Subject: CN=ACCVRAIZ1 O=ACCV OU=PKIACCV\n# Label: \"ACCVRAIZ1\"\n# Serial: 6828503384748696800\n# MD5 Fingerprint: d0:a0:5a:ee:05:b6:09:94:21:a1:7d:f1:b2:29:82:02\n# SHA1 Fingerprint: 93:05:7a:88:15:c6:4f:ce:88:2f:fa:91:16:52:28:78:bc:53:64:17\n# SHA256 Fingerprint: 9a:6e:c0:12:e1:a7:da:9d:be:34:19:4d:47:8a:d7:c0:db:18:22:fb:07:1d:f1:29:81:49:6e:d1:04:38:41:13\n-----BEGIN CERTIFICATE-----\nMIIH0zCCBbugAwIBAgIIXsO3pkN/pOAwDQYJKoZIhvcNAQEFBQAwQjESMBAGA1UE\nAwwJQUNDVlJBSVoxMRAwDgYDVQQLDAdQS0lBQ0NWMQ0wCwYDVQQKDARBQ0NWMQsw\nCQYDVQQGEwJFUzAeFw0xMTA1MDUwOTM3MzdaFw0zMDEyMzEwOTM3MzdaMEIxEjAQ\nBgNVBAMMCUFDQ1ZSQUlaMTEQMA4GA1UECwwHUEtJQUNDVjENMAsGA1UECgwEQUND\nVjELMAkGA1UEBhMCRVMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCb\nqau/YUqXry+XZpp0X9DZlv3P4uRm7x8fRzPCRKPfmt4ftVTdFXxpNRFvu8gMjmoY\nHtiP2Ra8EEg2XPBjs5BaXCQ316PWywlxufEBcoSwfdtNgM3802/J+Nq2DoLSRYWo\nG2ioPej0RGy9ocLLA76MPhMAhN9KSMDjIgro6TenGEyxCQ0jVn8ETdkXhBilyNpA\nlHPrzg5XPAOBOp0KoVdDaaxXbXmQeOW1tDvYvEyNKKGno6e6Ak4l0Squ7a4DIrhr\nIA8wKFSVf+DuzgpmndFALW4ir50awQUZ0m/A8p/4e7MCQvtQqR0tkw8jq8bBD5L/\n0KIV9VMJcRz/RROE5iZe+OCIHAr8Fraocwa48GOEAqDGWuzndN9wrqODJerWx5eH\nk6fGioozl2A3ED6XPm4pFdahD9GILBKfb6qkxkLrQaLjlUPTAYVtjrs78yM2x/47\n4KElB0iryYl0/wiPgL/AlmXz7uxLaL2diMMxs0Dx6M/2OLuc5NF/1OVYm3z61PMO\nm3WR5LpSLhl+0fXNWhn8ugb2+1KoS5kE3fj5tItQo05iifCHJPqDQsGH+tUtKSpa\ncXpkatcnYGMN285J9Y0fkIkyF/hzQ7jSWpOGYdbhdQrqeWZ2iE9x6wQl1gpaepPl\nuUsXQA+xtrn13k/c4LOsOxFwYIRKQ26ZIMApcQrAZQIDAQABo4ICyzCCAscwfQYI\nKwYBBQUHAQEEcTBvMEwGCCsGAQUFBzAChkBodHRwOi8vd3d3LmFjY3YuZXMvZmls\nZWFkbWluL0FyY2hpdm9zL2NlcnRpZmljYWRvcy9yYWl6YWNjdjEuY3J0MB8GCCsG\nAQUFBzABhhNodHRwOi8vb2NzcC5hY2N2LmVzMB0GA1UdDgQWBBTSh7Tj3zcnk1X2\nVuqB5TbMjB4/vTAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFNKHtOPfNyeT\nVfZW6oHlNsyMHj+9MIIBcwYDVR0gBIIBajCCAWYwggFiBgRVHSAAMIIBWDCCASIG\nCCsGAQUFBwICMIIBFB6CARAAQQB1AHQAbwByAGkAZABhAGQAIABkAGUAIABDAGUA\ncgB0AGkAZgBpAGMAYQBjAGkA8wBuACAAUgBhAO0AegAgAGQAZQAgAGwAYQAgAEEA\nQwBDAFYAIAAoAEEAZwBlAG4AYwBpAGEAIABkAGUAIABUAGUAYwBuAG8AbABvAGcA\n7QBhACAAeQAgAEMAZQByAHQAaQBmAGkAYwBhAGMAaQDzAG4AIABFAGwAZQBjAHQA\ncgDzAG4AaQBjAGEALAAgAEMASQBGACAAUQA0ADYAMAAxADEANQA2AEUAKQAuACAA\nQwBQAFMAIABlAG4AIABoAHQAdABwADoALwAvAHcAdwB3AC4AYQBjAGMAdgAuAGUA\nczAwBggrBgEFBQcCARYkaHR0cDovL3d3dy5hY2N2LmVzL2xlZ2lzbGFjaW9uX2Mu\naHRtMFUGA1UdHwROMEwwSqBIoEaGRGh0dHA6Ly93d3cuYWNjdi5lcy9maWxlYWRt\naW4vQXJjaGl2b3MvY2VydGlmaWNhZG9zL3JhaXphY2N2MV9kZXIuY3JsMA4GA1Ud\nDwEB/wQEAwIBBjAXBgNVHREEEDAOgQxhY2N2QGFjY3YuZXMwDQYJKoZIhvcNAQEF\nBQADggIBAJcxAp/n/UNnSEQU5CmH7UwoZtCPNdpNYbdKl02125DgBS4OxnnQ8pdp\nD70ER9m+27Up2pvZrqmZ1dM8MJP1jaGo/AaNRPTKFpV8M9xii6g3+CfYCS0b78gU\nJyCpZET/LtZ1qmxNYEAZSUNUY9rizLpm5U9EelvZaoErQNV/+QEnWCzI7UiRfD+m\nAM/EKXMRNt6GGT6d7hmKG9Ww7Y49nCrADdg9ZuM8Db3VlFzi4qc1GwQA9j9ajepD\nvV+JHanBsMyZ4k0ACtrJJ1vnE5Bc5PUzolVt3OAJTS+xJlsndQAJxGJ3KQhfnlms\ntn6tn1QwIgPBHnFk/vk4CpYY3QIUrCPLBhwepH2NDd4nQeit2hW3sCPdK6jT2iWH\n7ehVRE2I9DZ+hJp4rPcOVkkO1jMl1oRQQmwgEh0q1b688nCBpHBgvgW1m54ERL5h\nI6zppSSMEYCUWqKiuUnSwdzRp+0xESyeGabu4VXhwOrPDYTkF7eifKXeVSUG7szA\nh1xA2syVP1XgNce4hL60Xc16gwFy7ofmXx2utYXGJt/mwZrpHgJHnyqobalbz+xF\nd3+YJ5oyXSrjhO7FmGYvliAd3djDJ9ew+f7Zfc3Qn48LFFhRny+Lwzgt3uiP1o2H\npPVWQxaZLPSkVrQ0uGE3ycJYgBugl6H8WY3pEfbRD0tVNEYqi4Y7\n-----END CERTIFICATE-----\n\n# Issuer: CN=TWCA Global Root CA O=TAIWAN-CA OU=Root CA\n# Subject: CN=TWCA Global Root CA O=TAIWAN-CA OU=Root CA\n# Label: \"TWCA Global Root CA\"\n# Serial: 3262\n# MD5 Fingerprint: f9:03:7e:cf:e6:9e:3c:73:7a:2a:90:07:69:ff:2b:96\n# SHA1 Fingerprint: 9c:bb:48:53:f6:a4:f6:d3:52:a4:e8:32:52:55:60:13:f5:ad:af:65\n# SHA256 Fingerprint: 59:76:90:07:f7:68:5d:0f:cd:50:87:2f:9f:95:d5:75:5a:5b:2b:45:7d:81:f3:69:2b:61:0a:98:67:2f:0e:1b\n-----BEGIN CERTIFICATE-----\nMIIFQTCCAymgAwIBAgICDL4wDQYJKoZIhvcNAQELBQAwUTELMAkGA1UEBhMCVFcx\nEjAQBgNVBAoTCVRBSVdBTi1DQTEQMA4GA1UECxMHUm9vdCBDQTEcMBoGA1UEAxMT\nVFdDQSBHbG9iYWwgUm9vdCBDQTAeFw0xMjA2MjcwNjI4MzNaFw0zMDEyMzExNTU5\nNTlaMFExCzAJBgNVBAYTAlRXMRIwEAYDVQQKEwlUQUlXQU4tQ0ExEDAOBgNVBAsT\nB1Jvb3QgQ0ExHDAaBgNVBAMTE1RXQ0EgR2xvYmFsIFJvb3QgQ0EwggIiMA0GCSqG\nSIb3DQEBAQUAA4ICDwAwggIKAoICAQCwBdvI64zEbooh745NnHEKH1Jw7W2CnJfF\n10xORUnLQEK1EjRsGcJ0pDFfhQKX7EMzClPSnIyOt7h52yvVavKOZsTuKwEHktSz\n0ALfUPZVr2YOy+BHYC8rMjk1Ujoog/h7FsYYuGLWRyWRzvAZEk2tY/XTP3VfKfCh\nMBwqoJimFb3u/Rk28OKRQ4/6ytYQJ0lM793B8YVwm8rqqFpD/G2Gb3PpN0Wp8DbH\nzIh1HrtsBv+baz4X7GGqcXzGHaL3SekVtTzWoWH1EfcFbx39Eb7QMAfCKbAJTibc\n46KokWofwpFFiFzlmLhxpRUZyXx1EcxwdE8tmx2RRP1WKKD+u4ZqyPpcC1jcxkt2\nyKsi2XMPpfRaAok/T54igu6idFMqPVMnaR1sjjIsZAAmY2E2TqNGtz99sy2sbZCi\nlaLOz9qC5wc0GZbpuCGqKX6mOL6OKUohZnkfs8O1CWfe1tQHRvMq2uYiN2DLgbYP\noA/pyJV/v1WRBXrPPRXAb94JlAGD1zQbzECl8LibZ9WYkTunhHiVJqRaCPgrdLQA\nBDzfuBSO6N+pjWxnkjMdwLfS7JLIvgm/LCkFbwJrnu+8vyq8W8BQj0FwcYeyTbcE\nqYSjMq+u7msXi7Kx/mzhkIyIqJdIzshNy/MGz19qCkKxHh53L46g5pIOBvwFItIm\n4TFRfTLcDwIDAQABoyMwITAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB\n/zANBgkqhkiG9w0BAQsFAAOCAgEAXzSBdu+WHdXltdkCY4QWwa6gcFGn90xHNcgL\n1yg9iXHZqjNB6hQbbCEAwGxCGX6faVsgQt+i0trEfJdLjbDorMjupWkEmQqSpqsn\nLhpNgb+E1HAerUf+/UqdM+DyucRFCCEK2mlpc3INvjT+lIutwx4116KD7+U4x6WF\nH6vPNOw/KP4M8VeGTslV9xzU2KV9Bnpv1d8Q34FOIWWxtuEXeZVFBs5fzNxGiWNo\nRI2T9GRwoD2dKAXDOXC4Ynsg/eTb6QihuJ49CcdP+yz4k3ZB3lLg4VfSnQO8d57+\nnile98FRYB/e2guyLXW3Q0iT5/Z5xoRdgFlglPx4mI88k1HtQJAH32RjJMtOcQWh\n15QaiDLxInQirqWm2BJpTGCjAu4r7NRjkgtevi92a6O2JryPA9gK8kxkRr05YuWW\n6zRjESjMlfGt7+/cgFhI6Uu46mWs6fyAtbXIRfmswZ/ZuepiiI7E8UuDEq3mi4TW\nnsLrgxifarsbJGAzcMzs9zLzXNl5fe+epP7JI8Mk7hWSsT2RTyaGvWZzJBPqpK5j\nwa19hAM8EHiGG3njxPPyBJUgriOCxLM6AGK/5jYk4Ve6xx6QddVfP5VhK8E7zeWz\naGHQRiapIVJpLesux+t3zqY6tQMzT3bR51xUAV3LePTJDL/PEo4XLSNolOer/qmy\nKwbQBM0=\n-----END CERTIFICATE-----\n\n# Issuer: CN=TeliaSonera Root CA v1 O=TeliaSonera\n# Subject: CN=TeliaSonera Root CA v1 O=TeliaSonera\n# Label: \"TeliaSonera Root CA v1\"\n# Serial: 199041966741090107964904287217786801558\n# MD5 Fingerprint: 37:41:49:1b:18:56:9a:26:f5:ad:c2:66:fb:40:a5:4c\n# SHA1 Fingerprint: 43:13:bb:96:f1:d5:86:9b:c1:4e:6a:92:f6:cf:f6:34:69:87:82:37\n# SHA256 Fingerprint: dd:69:36:fe:21:f8:f0:77:c1:23:a1:a5:21:c1:22:24:f7:22:55:b7:3e:03:a7:26:06:93:e8:a2:4b:0f:a3:89\n-----BEGIN CERTIFICATE-----\nMIIFODCCAyCgAwIBAgIRAJW+FqD3LkbxezmCcvqLzZYwDQYJKoZIhvcNAQEFBQAw\nNzEUMBIGA1UECgwLVGVsaWFTb25lcmExHzAdBgNVBAMMFlRlbGlhU29uZXJhIFJv\nb3QgQ0EgdjEwHhcNMDcxMDE4MTIwMDUwWhcNMzIxMDE4MTIwMDUwWjA3MRQwEgYD\nVQQKDAtUZWxpYVNvbmVyYTEfMB0GA1UEAwwWVGVsaWFTb25lcmEgUm9vdCBDQSB2\nMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMK+6yfwIaPzaSZVfp3F\nVRaRXP3vIb9TgHot0pGMYzHw7CTww6XScnwQbfQ3t+XmfHnqjLWCi65ItqwA3GV1\n7CpNX8GH9SBlK4GoRz6JI5UwFpB/6FcHSOcZrr9FZ7E3GwYq/t75rH2D+1665I+X\nZ75Ljo1kB1c4VWk0Nj0TSO9P4tNmHqTPGrdeNjPUtAa9GAH9d4RQAEX1jF3oI7x+\n/jXh7VB7qTCNGdMJjmhnXb88lxhTuylixcpecsHHltTbLaC0H2kD7OriUPEMPPCs\n81Mt8Bz17Ww5OXOAFshSsCPN4D7c3TxHoLs1iuKYaIu+5b9y7tL6pe0S7fyYGKkm\ndtwoSxAgHNN/Fnct7W+A90m7UwW7XWjH1Mh1Fj+JWov3F0fUTPHSiXk+TT2YqGHe\nOh7S+F4D4MHJHIzTjU3TlTazN19jY5szFPAtJmtTfImMMsJu7D0hADnJoWjiUIMu\nsDor8zagrC/kb2HCUQk5PotTubtn2txTuXZZNp1D5SDgPTJghSJRt8czu90VL6R4\npgd7gUY2BIbdeTXHlSw7sKMXNeVzH7RcWe/a6hBle3rQf5+ztCo3O3CLm1u5K7fs\nslESl1MpWtTwEhDcTwK7EpIvYtQ/aUN8Ddb8WHUBiJ1YFkveupD/RwGJBmr2X7KQ\narMCpgKIv7NHfirZ1fpoeDVNAgMBAAGjPzA9MA8GA1UdEwEB/wQFMAMBAf8wCwYD\nVR0PBAQDAgEGMB0GA1UdDgQWBBTwj1k4ALP1j5qWDNXr+nuqF+gTEjANBgkqhkiG\n9w0BAQUFAAOCAgEAvuRcYk4k9AwI//DTDGjkk0kiP0Qnb7tt3oNmzqjMDfz1mgbl\ndxSR651Be5kqhOX//CHBXfDkH1e3damhXwIm/9fH907eT/j3HEbAek9ALCI18Bmx\n0GtnLLCo4MBANzX2hFxc469CeP6nyQ1Q6g2EdvZR74NTxnr/DlZJLo961gzmJ1Tj\nTQpgcmLNkQfWpb/ImWvtxBnmq0wROMVvMeJuScg/doAmAyYp4Db29iBT4xdwNBed\nY2gea+zDTYa4EzAvXUYNR0PVG6pZDrlcjQZIrXSHX8f8MVRBE+LHIQ6e4B4N4cB7\nQ4WQxYpYxmUKeFfyxiMPAdkgS94P+5KFdSpcc41teyWRyu5FrgZLAMzTsVlQ2jqI\nOylDRl6XK1TOU2+NSueW+r9xDkKLfP0ooNBIytrEgUy7onOTJsjrDNYmiLbAJM+7\nvVvrdX3pCI6GMyx5dwlppYn8s3CQh3aP0yK7Qs69cwsgJirQmz1wHiRszYd2qReW\nt88NkvuOGKmYSdGe/mBEciG5Ge3C9THxOUiIkCR1VBatzvT4aRRkOfujuLpwQMcn\nHL/EVlP6Y2XQ8xwOFvVrhlhNGNTkDY6lnVuR3HYkUD/GKvvZt5y11ubQ2egZixVx\nSK236thZiNSQvxaz2emsWWFUyBy6ysHK4bkgTI86k4mloMy/0/Z1pHWWbVY=\n-----END CERTIFICATE-----\n\n# Issuer: CN=E-Tugra Certification Authority O=E-Tu\\u011fra EBG Bili\\u015fim Teknolojileri ve Hizmetleri A.\\u015e. OU=E-Tugra Sertifikasyon Merkezi\n# Subject: CN=E-Tugra Certification Authority O=E-Tu\\u011fra EBG Bili\\u015fim Teknolojileri ve Hizmetleri A.\\u015e. OU=E-Tugra Sertifikasyon Merkezi\n# Label: \"E-Tugra Certification Authority\"\n# Serial: 7667447206703254355\n# MD5 Fingerprint: b8:a1:03:63:b0:bd:21:71:70:8a:6f:13:3a:bb:79:49\n# SHA1 Fingerprint: 51:c6:e7:08:49:06:6e:f3:92:d4:5c:a0:0d:6d:a3:62:8f:c3:52:39\n# SHA256 Fingerprint: b0:bf:d5:2b:b0:d7:d9:bd:92:bf:5d:4d:c1:3d:a2:55:c0:2c:54:2f:37:83:65:ea:89:39:11:f5:5e:55:f2:3c\n-----BEGIN CERTIFICATE-----\nMIIGSzCCBDOgAwIBAgIIamg+nFGby1MwDQYJKoZIhvcNAQELBQAwgbIxCzAJBgNV\nBAYTAlRSMQ8wDQYDVQQHDAZBbmthcmExQDA+BgNVBAoMN0UtVHXEn3JhIEVCRyBC\naWxpxZ9pbSBUZWtub2xvamlsZXJpIHZlIEhpem1ldGxlcmkgQS7Fni4xJjAkBgNV\nBAsMHUUtVHVncmEgU2VydGlmaWthc3lvbiBNZXJrZXppMSgwJgYDVQQDDB9FLVR1\nZ3JhIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTEzMDMwNTEyMDk0OFoXDTIz\nMDMwMzEyMDk0OFowgbIxCzAJBgNVBAYTAlRSMQ8wDQYDVQQHDAZBbmthcmExQDA+\nBgNVBAoMN0UtVHXEn3JhIEVCRyBCaWxpxZ9pbSBUZWtub2xvamlsZXJpIHZlIEhp\nem1ldGxlcmkgQS7Fni4xJjAkBgNVBAsMHUUtVHVncmEgU2VydGlmaWthc3lvbiBN\nZXJrZXppMSgwJgYDVQQDDB9FLVR1Z3JhIENlcnRpZmljYXRpb24gQXV0aG9yaXR5\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA4vU/kwVRHoViVF56C/UY\nB4Oufq9899SKa6VjQzm5S/fDxmSJPZQuVIBSOTkHS0vdhQd2h8y/L5VMzH2nPbxH\nD5hw+IyFHnSOkm0bQNGZDbt1bsipa5rAhDGvykPL6ys06I+XawGb1Q5KCKpbknSF\nQ9OArqGIW66z6l7LFpp3RMih9lRozt6Plyu6W0ACDGQXwLWTzeHxE2bODHnv0ZEo\nq1+gElIwcxmOj+GMB6LDu0rw6h8VqO4lzKRG+Bsi77MOQ7osJLjFLFzUHPhdZL3D\nk14opz8n8Y4e0ypQBaNV2cvnOVPAmJ6MVGKLJrD3fY185MaeZkJVgkfnsliNZvcH\nfC425lAcP9tDJMW/hkd5s3kc91r0E+xs+D/iWR+V7kI+ua2oMoVJl0b+SzGPWsut\ndEcf6ZG33ygEIqDUD13ieU/qbIWGvaimzuT6w+Gzrt48Ue7LE3wBf4QOXVGUnhMM\nti6lTPk5cDZvlsouDERVxcr6XQKj39ZkjFqzAQqptQpHF//vkUAqjqFGOjGY5RH8\nzLtJVor8udBhmm9lbObDyz51Sf6Pp+KJxWfXnUYTTjF2OySznhFlhqt/7x3U+Lzn\nrFpct1pHXFXOVbQicVtbC/DP3KBhZOqp12gKY6fgDT+gr9Oq0n7vUaDmUStVkhUX\nU8u3Zg5mTPj5dUyQ5xJwx0UCAwEAAaNjMGEwHQYDVR0OBBYEFC7j27JJ0JxUeVz6\nJyr+zE7S6E5UMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAULuPbsknQnFR5\nXPonKv7MTtLoTlQwDgYDVR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBCwUAA4ICAQAF\nNzr0TbdF4kV1JI+2d1LoHNgQk2Xz8lkGpD4eKexd0dCrfOAKkEh47U6YA5n+KGCR\nHTAduGN8qOY1tfrTYXbm1gdLymmasoR6d5NFFxWfJNCYExL/u6Au/U5Mh/jOXKqY\nGwXgAEZKgoClM4so3O0409/lPun++1ndYYRP0lSWE2ETPo+Aab6TR7U1Q9Jauz1c\n77NCR807VRMGsAnb/WP2OogKmW9+4c4bU2pEZiNRCHu8W1Ki/QY3OEBhj0qWuJA3\n+GbHeJAAFS6LrVE1Uweoa2iu+U48BybNCAVwzDk/dr2l02cmAYamU9JgO3xDf1WK\nvJUawSg5TB9D0pH0clmKuVb8P7Sd2nCcdlqMQ1DujjByTd//SffGqWfZbawCEeI6\nFiWnWAjLb1NBnEg4R2gz0dfHj9R0IdTDBZB6/86WiLEVKV0jq9BgoRJP3vQXzTLl\nyb/IQ639Lo7xr+L0mPoSHyDYwKcMhcWQ9DstliaxLL5Mq+ux0orJ23gTDx4JnW2P\nAJ8C2sH6H3p6CcRK5ogql5+Ji/03X186zjhZhkuvcQu02PJwT58yE+Owp1fl2tpD\ny4Q08ijE6m30Ku/Ba3ba+367hTzSU8JNvnHhRdH9I2cNE3X7z2VnIp2usAnRCf8d\nNL/+I5c30jn6PQ0GC7TbO6Orb1wdtn7os4I07QZcJA==\n-----END CERTIFICATE-----\n\n# Issuer: CN=T-TeleSec GlobalRoot Class 2 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center\n# Subject: CN=T-TeleSec GlobalRoot Class 2 O=T-Systems Enterprise Services GmbH OU=T-Systems Trust Center\n# Label: \"T-TeleSec GlobalRoot Class 2\"\n# Serial: 1\n# MD5 Fingerprint: 2b:9b:9e:e4:7b:6c:1f:00:72:1a:cc:c1:77:79:df:6a\n# SHA1 Fingerprint: 59:0d:2d:7d:88:4f:40:2e:61:7e:a5:62:32:17:65:cf:17:d8:94:e9\n# SHA256 Fingerprint: 91:e2:f5:78:8d:58:10:eb:a7:ba:58:73:7d:e1:54:8a:8e:ca:cd:01:45:98:bc:0b:14:3e:04:1b:17:05:25:52\n-----BEGIN CERTIFICATE-----\nMIIDwzCCAqugAwIBAgIBATANBgkqhkiG9w0BAQsFADCBgjELMAkGA1UEBhMCREUx\nKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnByaXNlIFNlcnZpY2VzIEdtYkgxHzAd\nBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50ZXIxJTAjBgNVBAMMHFQtVGVsZVNl\nYyBHbG9iYWxSb290IENsYXNzIDIwHhcNMDgxMDAxMTA0MDE0WhcNMzMxMDAxMjM1\nOTU5WjCBgjELMAkGA1UEBhMCREUxKzApBgNVBAoMIlQtU3lzdGVtcyBFbnRlcnBy\naXNlIFNlcnZpY2VzIEdtYkgxHzAdBgNVBAsMFlQtU3lzdGVtcyBUcnVzdCBDZW50\nZXIxJTAjBgNVBAMMHFQtVGVsZVNlYyBHbG9iYWxSb290IENsYXNzIDIwggEiMA0G\nCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCqX9obX+hzkeXaXPSi5kfl82hVYAUd\nAqSzm1nzHoqvNK38DcLZSBnuaY/JIPwhqgcZ7bBcrGXHX+0CfHt8LRvWurmAwhiC\nFoT6ZrAIxlQjgeTNuUk/9k9uN0goOA/FvudocP05l03Sx5iRUKrERLMjfTlH6VJi\n1hKTXrcxlkIF+3anHqP1wvzpesVsqXFP6st4vGCvx9702cu+fjOlbpSD8DT6Iavq\njnKgP6TeMFvvhk1qlVtDRKgQFRzlAVfFmPHmBiiRqiDFt1MmUUOyCxGVWOHAD3bZ\nwI18gfNycJ5v/hqO2V81xrJvNHy+SE/iWjnX2J14np+GPgNeGYtEotXHAgMBAAGj\nQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBS/\nWSA2AHmgoCJrjNXyYdK4LMuCSjANBgkqhkiG9w0BAQsFAAOCAQEAMQOiYQsfdOhy\nNsZt+U2e+iKo4YFWz827n+qrkRk4r6p8FU3ztqONpfSO9kSpp+ghla0+AGIWiPAC\nuvxhI+YzmzB6azZie60EI4RYZeLbK4rnJVM3YlNfvNoBYimipidx5joifsFvHZVw\nIEoHNN/q/xWA5brXethbdXwFeilHfkCoMRN3zUA7tFFHei4R40cR3p1m0IvVVGb6\ng1XqfMIpiRvpb7PO4gWEyS8+eIVibslfwXhjdFjASBgMmTnrpMwatXlajRWc2BQN\n9noHV8cigwUtPJslJj0Ys6lDfMjIq2SPDqO/nBudMNva0Bkuqjzx+zOAduTNrRlP\nBSeOE6Fuwg==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Atos TrustedRoot 2011 O=Atos\n# Subject: CN=Atos TrustedRoot 2011 O=Atos\n# Label: \"Atos TrustedRoot 2011\"\n# Serial: 6643877497813316402\n# MD5 Fingerprint: ae:b9:c4:32:4b:ac:7f:5d:66:cc:77:94:bb:2a:77:56\n# SHA1 Fingerprint: 2b:b1:f5:3e:55:0c:1d:c5:f1:d4:e6:b7:6a:46:4b:55:06:02:ac:21\n# SHA256 Fingerprint: f3:56:be:a2:44:b7:a9:1e:b3:5d:53:ca:9a:d7:86:4a:ce:01:8e:2d:35:d5:f8:f9:6d:df:68:a6:f4:1a:a4:74\n-----BEGIN CERTIFICATE-----\nMIIDdzCCAl+gAwIBAgIIXDPLYixfszIwDQYJKoZIhvcNAQELBQAwPDEeMBwGA1UE\nAwwVQXRvcyBUcnVzdGVkUm9vdCAyMDExMQ0wCwYDVQQKDARBdG9zMQswCQYDVQQG\nEwJERTAeFw0xMTA3MDcxNDU4MzBaFw0zMDEyMzEyMzU5NTlaMDwxHjAcBgNVBAMM\nFUF0b3MgVHJ1c3RlZFJvb3QgMjAxMTENMAsGA1UECgwEQXRvczELMAkGA1UEBhMC\nREUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCVhTuXbyo7LjvPpvMp\nNb7PGKw+qtn4TaA+Gke5vJrf8v7MPkfoepbCJI419KkM/IL9bcFyYie96mvr54rM\nVD6QUM+A1JX76LWC1BTFtqlVJVfbsVD2sGBkWXppzwO3bw2+yj5vdHLqqjAqc2K+\nSZFhyBH+DgMq92og3AIVDV4VavzjgsG1xZ1kCWyjWZgHJ8cblithdHFsQ/H3NYkQ\n4J7sVaE3IqKHBAUsR320HLliKWYoyrfhk/WklAOZuXCFteZI6o1Q/NnezG8HDt0L\ncp2AMBYHlT8oDv3FdU9T1nSatCQujgKRz3bFmx5VdJx4IbHwLfELn8LVlhgf8FQi\neowHAgMBAAGjfTB7MB0GA1UdDgQWBBSnpQaxLKYJYO7Rl+lwrrw7GWzbITAPBgNV\nHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFKelBrEspglg7tGX6XCuvDsZbNshMBgG\nA1UdIAQRMA8wDQYLKwYBBAGwLQMEAQEwDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3\nDQEBCwUAA4IBAQAmdzTblEiGKkGdLD4GkGDEjKwLVLgfuXvTBznk+j57sj1O7Z8j\nvZfza1zv7v1Apt+hk6EKhqzvINB5Ab149xnYJDE0BAGmuhWawyfc2E8PzBhj/5kP\nDpFrdRbhIfzYJsdHt6bPWHJxfrrhTZVHO8mvbaG0weyJ9rQPOLXiZNwlz6bb65pc\nmaHFCN795trV1lpFDMS3wrUU77QR/w4VtfX128a961qn8FYiqTxlVMYVqL2Gns2D\nlmh6cYGJ4Qvh6hEbaAjMaZ7snkGeRDImeuKHCnE96+RapNLbxc3G3mB/ufNPRJLv\nKrcYPqcZ2Qt9sTdBQrC6YB3y/gkRsPCHe6ed\n-----END CERTIFICATE-----\n\n# Issuer: CN=QuoVadis Root CA 1 G3 O=QuoVadis Limited\n# Subject: CN=QuoVadis Root CA 1 G3 O=QuoVadis Limited\n# Label: \"QuoVadis Root CA 1 G3\"\n# Serial: 687049649626669250736271037606554624078720034195\n# MD5 Fingerprint: a4:bc:5b:3f:fe:37:9a:fa:64:f0:e2:fa:05:3d:0b:ab\n# SHA1 Fingerprint: 1b:8e:ea:57:96:29:1a:c9:39:ea:b8:0a:81:1a:73:73:c0:93:79:67\n# SHA256 Fingerprint: 8a:86:6f:d1:b2:76:b5:7e:57:8e:92:1c:65:82:8a:2b:ed:58:e9:f2:f2:88:05:41:34:b7:f1:f4:bf:c9:cc:74\n-----BEGIN CERTIFICATE-----\nMIIFYDCCA0igAwIBAgIUeFhfLq0sGUvjNwc1NBMotZbUZZMwDQYJKoZIhvcNAQEL\nBQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc\nBgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMSBHMzAeFw0xMjAxMTIxNzI3NDRaFw00\nMjAxMTIxNzI3NDRaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM\naW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDEgRzMwggIiMA0GCSqG\nSIb3DQEBAQUAA4ICDwAwggIKAoICAQCgvlAQjunybEC0BJyFuTHK3C3kEakEPBtV\nwedYMB0ktMPvhd6MLOHBPd+C5k+tR4ds7FtJwUrVu4/sh6x/gpqG7D0DmVIB0jWe\nrNrwU8lmPNSsAgHaJNM7qAJGr6Qc4/hzWHa39g6QDbXwz8z6+cZM5cOGMAqNF341\n68Xfuw6cwI2H44g4hWf6Pser4BOcBRiYz5P1sZK0/CPTz9XEJ0ngnjybCKOLXSoh\n4Pw5qlPafX7PGglTvF0FBM+hSo+LdoINofjSxxR3W5A2B4GbPgb6Ul5jxaYA/qXp\nUhtStZI5cgMJYr2wYBZupt0lwgNm3fME0UDiTouG9G/lg6AnhF4EwfWQvTA9xO+o\nabw4m6SkltFi2mnAAZauy8RRNOoMqv8hjlmPSlzkYZqn0ukqeI1RPToV7qJZjqlc\n3sX5kCLliEVx3ZGZbHqfPT2YfF72vhZooF6uCyP8Wg+qInYtyaEQHeTTRCOQiJ/G\nKubX9ZqzWB4vMIkIG1SitZgj7Ah3HJVdYdHLiZxfokqRmu8hqkkWCKi9YSgxyXSt\nhfbZxbGL0eUQMk1fiyA6PEkfM4VZDdvLCXVDaXP7a3F98N/ETH3Goy7IlXnLc6KO\nTk0k+17kBL5yG6YnLUlamXrXXAkgt3+UuU/xDRxeiEIbEbfnkduebPRq34wGmAOt\nzCjvpUfzUwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB\nBjAdBgNVHQ4EFgQUo5fW816iEOGrRZ88F2Q87gFwnMwwDQYJKoZIhvcNAQELBQAD\nggIBABj6W3X8PnrHX3fHyt/PX8MSxEBd1DKquGrX1RUVRpgjpeaQWxiZTOOtQqOC\nMTaIzen7xASWSIsBx40Bz1szBpZGZnQdT+3Btrm0DWHMY37XLneMlhwqI2hrhVd2\ncDMT/uFPpiN3GPoajOi9ZcnPP/TJF9zrx7zABC4tRi9pZsMbj/7sPtPKlL92CiUN\nqXsCHKnQO18LwIE6PWThv6ctTr1NxNgpxiIY0MWscgKCP6o6ojoilzHdCGPDdRS5\nYCgtW2jgFqlmgiNR9etT2DGbe+m3nUvriBbP+V04ikkwj+3x6xn0dxoxGE1nVGwv\nb2X52z3sIexe9PSLymBlVNFxZPT5pqOBMzYzcfCkeF9OrYMh3jRJjehZrJ3ydlo2\n8hP0r+AJx2EqbPfgna67hkooby7utHnNkDPDs3b69fBsnQGQ+p6Q9pxyz0fawx/k\nNSBT8lTR32GDpgLiJTjehTItXnOQUl1CxM49S+H5GYQd1aJQzEH7QRTDvdbJWqNj\nZgKAvQU6O0ec7AAmTPWIUb+oI38YB7AL7YsmoWTTYUrrXJ/es69nA7Mf3W1daWhp\nq1467HxpvMc7hU6eFbm0FU/DlXpY18ls6Wy58yljXrQs8C097Vpl4KlbQMJImYFt\nnh8GKjwStIsPm6Ik8KaN1nrgS7ZklmOVhMJKzRwuJIczYOXD\n-----END CERTIFICATE-----\n\n# Issuer: CN=QuoVadis Root CA 2 G3 O=QuoVadis Limited\n# Subject: CN=QuoVadis Root CA 2 G3 O=QuoVadis Limited\n# Label: \"QuoVadis Root CA 2 G3\"\n# Serial: 390156079458959257446133169266079962026824725800\n# MD5 Fingerprint: af:0c:86:6e:bf:40:2d:7f:0b:3e:12:50:ba:12:3d:06\n# SHA1 Fingerprint: 09:3c:61:f3:8b:8b:dc:7d:55:df:75:38:02:05:00:e1:25:f5:c8:36\n# SHA256 Fingerprint: 8f:e4:fb:0a:f9:3a:4d:0d:67:db:0b:eb:b2:3e:37:c7:1b:f3:25:dc:bc:dd:24:0e:a0:4d:af:58:b4:7e:18:40\n-----BEGIN CERTIFICATE-----\nMIIFYDCCA0igAwIBAgIURFc0JFuBiZs18s64KztbpybwdSgwDQYJKoZIhvcNAQEL\nBQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc\nBgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMiBHMzAeFw0xMjAxMTIxODU5MzJaFw00\nMjAxMTIxODU5MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM\naW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDIgRzMwggIiMA0GCSqG\nSIb3DQEBAQUAA4ICDwAwggIKAoICAQChriWyARjcV4g/Ruv5r+LrI3HimtFhZiFf\nqq8nUeVuGxbULX1QsFN3vXg6YOJkApt8hpvWGo6t/x8Vf9WVHhLL5hSEBMHfNrMW\nn4rjyduYNM7YMxcoRvynyfDStNVNCXJJ+fKH46nafaF9a7I6JaltUkSs+L5u+9ym\nc5GQYaYDFCDy54ejiK2toIz/pgslUiXnFgHVy7g1gQyjO/Dh4fxaXc6AcW34Sas+\nO7q414AB+6XrW7PFXmAqMaCvN+ggOp+oMiwMzAkd056OXbxMmO7FGmh77FOm6RQ1\no9/NgJ8MSPsc9PG/Srj61YxxSscfrf5BmrODXfKEVu+lV0POKa2Mq1W/xPtbAd0j\nIaFYAI7D0GoT7RPjEiuA3GfmlbLNHiJuKvhB1PLKFAeNilUSxmn1uIZoL1NesNKq\nIcGY5jDjZ1XHm26sGahVpkUG0CM62+tlXSoREfA7T8pt9DTEceT/AFr2XK4jYIVz\n8eQQsSWu1ZK7E8EM4DnatDlXtas1qnIhO4M15zHfeiFuuDIIfR0ykRVKYnLP43eh\nvNURG3YBZwjgQQvD6xVu+KQZ2aKrr+InUlYrAoosFCT5v0ICvybIxo/gbjh9Uy3l\n7ZizlWNof/k19N+IxWA1ksB8aRxhlRbQ694Lrz4EEEVlWFA4r0jyWbYW8jwNkALG\ncC4BrTwV1wIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB\nBjAdBgNVHQ4EFgQU7edvdlq/YOxJW8ald7tyFnGbxD0wDQYJKoZIhvcNAQELBQAD\nggIBAJHfgD9DCX5xwvfrs4iP4VGyvD11+ShdyLyZm3tdquXK4Qr36LLTn91nMX66\nAarHakE7kNQIXLJgapDwyM4DYvmL7ftuKtwGTTwpD4kWilhMSA/ohGHqPHKmd+RC\nroijQ1h5fq7KpVMNqT1wvSAZYaRsOPxDMuHBR//47PERIjKWnML2W2mWeyAMQ0Ga\nW/ZZGYjeVYg3UQt4XAoeo0L9x52ID8DyeAIkVJOviYeIyUqAHerQbj5hLja7NQ4n\nlv1mNDthcnPxFlxHBlRJAHpYErAK74X9sbgzdWqTHBLmYF5vHX/JHyPLhGGfHoJE\n+V+tYlUkmlKY7VHnoX6XOuYvHxHaU4AshZ6rNRDbIl9qxV6XU/IyAgkwo1jwDQHV\ncsaxfGl7w/U2Rcxhbl5MlMVerugOXou/983g7aEOGzPuVBj+D77vfoRrQ+NwmNtd\ndbINWQeFFSM51vHfqSYP1kjHs6Yi9TM3WpVHn3u6GBVv/9YUZINJ0gpnIdsPNWNg\nKCLjsZWDzYWm3S8P52dSbrsvhXz1SnPnxT7AvSESBT/8twNJAlvIJebiVDj1eYeM\nHVOyToV7BjjHLPj4sHKNJeV3UvQDHEimUF+IIDBu8oJDqz2XhOdT+yHBTw8imoa4\nWSr2Rz0ZiC3oheGe7IUIarFsNMkd7EgrO3jtZsSOeWmD3n+M\n-----END CERTIFICATE-----\n\n# Issuer: CN=QuoVadis Root CA 3 G3 O=QuoVadis Limited\n# Subject: CN=QuoVadis Root CA 3 G3 O=QuoVadis Limited\n# Label: \"QuoVadis Root CA 3 G3\"\n# Serial: 268090761170461462463995952157327242137089239581\n# MD5 Fingerprint: df:7d:b9:ad:54:6f:68:a1:df:89:57:03:97:43:b0:d7\n# SHA1 Fingerprint: 48:12:bd:92:3c:a8:c4:39:06:e7:30:6d:27:96:e6:a4:cf:22:2e:7d\n# SHA256 Fingerprint: 88:ef:81:de:20:2e:b0:18:45:2e:43:f8:64:72:5c:ea:5f:bd:1f:c2:d9:d2:05:73:07:09:c5:d8:b8:69:0f:46\n-----BEGIN CERTIFICATE-----\nMIIFYDCCA0igAwIBAgIULvWbAiin23r/1aOp7r0DoM8Sah0wDQYJKoZIhvcNAQEL\nBQAwSDELMAkGA1UEBhMCQk0xGTAXBgNVBAoTEFF1b1ZhZGlzIExpbWl0ZWQxHjAc\nBgNVBAMTFVF1b1ZhZGlzIFJvb3QgQ0EgMyBHMzAeFw0xMjAxMTIyMDI2MzJaFw00\nMjAxMTIyMDI2MzJaMEgxCzAJBgNVBAYTAkJNMRkwFwYDVQQKExBRdW9WYWRpcyBM\naW1pdGVkMR4wHAYDVQQDExVRdW9WYWRpcyBSb290IENBIDMgRzMwggIiMA0GCSqG\nSIb3DQEBAQUAA4ICDwAwggIKAoICAQCzyw4QZ47qFJenMioKVjZ/aEzHs286IxSR\n/xl/pcqs7rN2nXrpixurazHb+gtTTK/FpRp5PIpM/6zfJd5O2YIyC0TeytuMrKNu\nFoM7pmRLMon7FhY4futD4tN0SsJiCnMK3UmzV9KwCoWdcTzeo8vAMvMBOSBDGzXR\nU7Ox7sWTaYI+FrUoRqHe6okJ7UO4BUaKhvVZR74bbwEhELn9qdIoyhA5CcoTNs+c\nra1AdHkrAj80//ogaX3T7mH1urPnMNA3I4ZyYUUpSFlob3emLoG+B01vr87ERROR\nFHAGjx+f+IdpsQ7vw4kZ6+ocYfx6bIrc1gMLnia6Et3UVDmrJqMz6nWB2i3ND0/k\nA9HvFZcba5DFApCTZgIhsUfei5pKgLlVj7WiL8DWM2fafsSntARE60f75li59wzw\neyuxwHApw0BiLTtIadwjPEjrewl5qW3aqDCYz4ByA4imW0aucnl8CAMhZa634Ryl\nsSqiMd5mBPfAdOhx3v89WcyWJhKLhZVXGqtrdQtEPREoPHtht+KPZ0/l7DxMYIBp\nVzgeAVuNVejH38DMdyM0SXV89pgR6y3e7UEuFAUCf+D+IOs15xGsIs5XPd7JMG0Q\nA4XN8f+MFrXBsj6IbGB/kE+V9/YtrQE5BwT6dYB9v0lQ7e/JxHwc64B+27bQ3RP+\nydOc17KXqQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB\nBjAdBgNVHQ4EFgQUxhfQvKjqAkPyGwaZXSuQILnXnOQwDQYJKoZIhvcNAQELBQAD\nggIBADRh2Va1EodVTd2jNTFGu6QHcrxfYWLopfsLN7E8trP6KZ1/AvWkyaiTt3px\nKGmPc+FSkNrVvjrlt3ZqVoAh313m6Tqe5T72omnHKgqwGEfcIHB9UqM+WXzBusnI\nFUBhynLWcKzSt/Ac5IYp8M7vaGPQtSCKFWGafoaYtMnCdvvMujAWzKNhxnQT5Wvv\noxXqA/4Ti2Tk08HS6IT7SdEQTXlm66r99I0xHnAUrdzeZxNMgRVhvLfZkXdxGYFg\nu/BYpbWcC/ePIlUnwEsBbTuZDdQdm2NnL9DuDcpmvJRPpq3t/O5jrFc/ZSXPsoaP\n0Aj/uHYUbt7lJ+yreLVTubY/6CD50qi+YUbKh4yE8/nxoGibIh6BJpsQBJFxwAYf\n3KDTuVan45gtf4Od34wrnDKOMpTwATwiKp9Dwi7DmDkHOHv8XgBCH/MyJnmDhPbl\n8MFREsALHgQjDFSlTC9JxUrRtm5gDWv8a4uFJGS3iQ6rJUdbPM9+Sb3H6QrG2vd+\nDhcI00iX0HGS8A85PjRqHH3Y8iKuu2n0M7SmSFXRDw4m6Oy2Cy2nhTXN/VnIn9HN\nPlopNLk9hM6xZdRZkZFWdSHBd575euFgndOtBBj0fOtek49TSiIp+EgrPk2GrFt/\nywaZWWDYWGWVjUTR939+J399roD1B0y2PpxxVJkES/1Y+Zj0\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert Assured ID Root G2 O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert Assured ID Root G2 O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert Assured ID Root G2\"\n# Serial: 15385348160840213938643033620894905419\n# MD5 Fingerprint: 92:38:b9:f8:63:24:82:65:2c:57:33:e6:fe:81:8f:9d\n# SHA1 Fingerprint: a1:4b:48:d9:43:ee:0a:0e:40:90:4f:3c:e0:a4:c0:91:93:51:5d:3f\n# SHA256 Fingerprint: 7d:05:eb:b6:82:33:9f:8c:94:51:ee:09:4e:eb:fe:fa:79:53:a1:14:ed:b2:f4:49:49:45:2f:ab:7d:2f:c1:85\n-----BEGIN CERTIFICATE-----\nMIIDljCCAn6gAwIBAgIQC5McOtY5Z+pnI7/Dr5r0SzANBgkqhkiG9w0BAQsFADBl\nMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\nd3cuZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJv\nb3QgRzIwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQG\nEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNl\ncnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzIwggEi\nMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDZ5ygvUj82ckmIkzTz+GoeMVSA\nn61UQbVH35ao1K+ALbkKz3X9iaV9JPrjIgwrvJUXCzO/GU1BBpAAvQxNEP4Htecc\nbiJVMWWXvdMX0h5i89vqbFCMP4QMls+3ywPgym2hFEwbid3tALBSfK+RbLE4E9Hp\nEgjAALAcKxHad3A2m67OeYfcgnDmCXRwVWmvo2ifv922ebPynXApVfSr/5Vh88lA\nbx3RvpO704gqu52/clpWcTs/1PPRCv4o76Pu2ZmvA9OPYLfykqGxvYmJHzDNw6Yu\nYjOuFgJ3RFrngQo8p0Quebg/BLxcoIfhG69Rjs3sLPr4/m3wOnyqi+RnlTGNAgMB\nAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQW\nBBTOw0q5mVXyuNtgv6l+vVa1lzan1jANBgkqhkiG9w0BAQsFAAOCAQEAyqVVjOPI\nQW5pJ6d1Ee88hjZv0p3GeDgdaZaikmkuOGybfQTUiaWxMTeKySHMq2zNixya1r9I\n0jJmwYrA8y8678Dj1JGG0VDjA9tzd29KOVPt3ibHtX2vK0LRdWLjSisCx1BL4Gni\nlmwORGYQRI+tBev4eaymG+g3NJ1TyWGqolKvSnAWhsI6yLETcDbYz+70CjTVW0z9\nB5yiutkBclzzTcHdDrEcDcRjvq30FPuJ7KJBDkzMyFdA0G4Dqs0MjomZmWzwPDCv\nON9vvKO+KSAnq3T/EyJ43pdSVR6DtVQgA+6uwE9W3jfMw3+qBCe703e4YtsXfJwo\nIhNzbM8m9Yop5w==\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert Assured ID Root G3 O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert Assured ID Root G3 O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert Assured ID Root G3\"\n# Serial: 15459312981008553731928384953135426796\n# MD5 Fingerprint: 7c:7f:65:31:0c:81:df:8d:ba:3e:99:e2:5c:ad:6e:fb\n# SHA1 Fingerprint: f5:17:a2:4f:9a:48:c6:c9:f8:a2:00:26:9f:dc:0f:48:2c:ab:30:89\n# SHA256 Fingerprint: 7e:37:cb:8b:4c:47:09:0c:ab:36:55:1b:a6:f4:5d:b8:40:68:0f:ba:16:6a:95:2d:b1:00:71:7f:43:05:3f:c2\n-----BEGIN CERTIFICATE-----\nMIICRjCCAc2gAwIBAgIQC6Fa+h3foLVJRK/NJKBs7DAKBggqhkjOPQQDAzBlMQsw\nCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu\nZGlnaWNlcnQuY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3Qg\nRzMwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBlMQswCQYDVQQGEwJV\nUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu\nY29tMSQwIgYDVQQDExtEaWdpQ2VydCBBc3N1cmVkIElEIFJvb3QgRzMwdjAQBgcq\nhkjOPQIBBgUrgQQAIgNiAAQZ57ysRGXtzbg/WPuNsVepRC0FFfLvC/8QdJ+1YlJf\nZn4f5dwbRXkLzMZTCp2NXQLZqVneAlr2lSoOjThKiknGvMYDOAdfVdp+CW7if17Q\nRSAPWXYQ1qAk8C3eNvJsKTmjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/\nBAQDAgGGMB0GA1UdDgQWBBTL0L2p4ZgFUaFNN6KDec6NHSrkhDAKBggqhkjOPQQD\nAwNnADBkAjAlpIFFAmsSS3V0T8gj43DydXLefInwz5FyYZ5eEJJZVrmDxxDnOOlY\nJjZ91eQ0hjkCMHw2U/Aw5WJjOpnitqM7mzT6HtoQknFekROn3aRukswy1vUhZscv\n6pZjamVFkpUBtA==\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert Global Root G2 O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert Global Root G2 O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert Global Root G2\"\n# Serial: 4293743540046975378534879503202253541\n# MD5 Fingerprint: e4:a6:8a:c8:54:ac:52:42:46:0a:fd:72:48:1b:2a:44\n# SHA1 Fingerprint: df:3c:24:f9:bf:d6:66:76:1b:26:80:73:fe:06:d1:cc:8d:4f:82:a4\n# SHA256 Fingerprint: cb:3c:cb:b7:60:31:e5:e0:13:8f:8d:d3:9a:23:f9:de:47:ff:c3:5e:43:c1:14:4c:ea:27:d4:6a:5a:b1:cb:5f\n-----BEGIN CERTIFICATE-----\nMIIDjjCCAnagAwIBAgIQAzrx5qcRqaC7KGSxHQn65TANBgkqhkiG9w0BAQsFADBh\nMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\nd3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBH\nMjAeFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVT\nMRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\nb20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEcyMIIBIjANBgkqhkiG\n9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzfNNNx7a8myaJCtSnX/RrohCgiN9RlUyfuI\n2/Ou8jqJkTx65qsGGmvPrC3oXgkkRLpimn7Wo6h+4FR1IAWsULecYxpsMNzaHxmx\n1x7e/dfgy5SDN67sH0NO3Xss0r0upS/kqbitOtSZpLYl6ZtrAGCSYP9PIUkY92eQ\nq2EGnI/yuum06ZIya7XzV+hdG82MHauVBJVJ8zUtluNJbd134/tJS7SsVQepj5Wz\ntCO7TG1F8PapspUwtP1MVYwnSlcUfIKdzXOS0xZKBgyMUNGPHgm+F6HmIcr9g+UQ\nvIOlCsRnKPZzFBQ9RnbDhxSJITRNrw9FDKZJobq7nMWxM4MphQIDAQABo0IwQDAP\nBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQUTiJUIBiV\n5uNu5g/6+rkS7QYXjzkwDQYJKoZIhvcNAQELBQADggEBAGBnKJRvDkhj6zHd6mcY\n1Yl9PMWLSn/pvtsrF9+wX3N3KjITOYFnQoQj8kVnNeyIv/iPsGEMNKSuIEyExtv4\nNeF22d+mQrvHRAiGfzZ0JFrabA0UWTW98kndth/Jsw1HKj2ZL7tcu7XUIOGZX1NG\nFdtom/DzMNU+MeKNhJ7jitralj41E6Vf8PlwUHBHQRFXGU7Aj64GxJUTFy8bJZ91\n8rGOmaFvE7FBcf6IKshPECBV1/MUReXgRPTqh5Uykw7+U0b6LJ3/iyK5S9kJRaTe\npLiaWN0bfVKfjllDiIGknibVb63dDcY3fe0Dkhvld1927jyNxF1WW6LZZm6zNTfl\nMrY=\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert Global Root G3 O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert Global Root G3 O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert Global Root G3\"\n# Serial: 7089244469030293291760083333884364146\n# MD5 Fingerprint: f5:5d:a4:50:a5:fb:28:7e:1e:0f:0d:cc:96:57:56:ca\n# SHA1 Fingerprint: 7e:04:de:89:6a:3e:66:6d:00:e6:87:d3:3f:fa:d9:3b:e8:3d:34:9e\n# SHA256 Fingerprint: 31:ad:66:48:f8:10:41:38:c7:38:f3:9e:a4:32:01:33:39:3e:3a:18:cc:02:29:6e:f9:7c:2a:c9:ef:67:31:d0\n-----BEGIN CERTIFICATE-----\nMIICPzCCAcWgAwIBAgIQBVVWvPJepDU1w6QP1atFcjAKBggqhkjOPQQDAzBhMQsw\nCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cu\nZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBHMzAe\nFw0xMzA4MDExMjAwMDBaFw0zODAxMTUxMjAwMDBaMGExCzAJBgNVBAYTAlVTMRUw\nEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20x\nIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IEczMHYwEAYHKoZIzj0CAQYF\nK4EEACIDYgAE3afZu4q4C/sLfyHS8L6+c/MzXRq8NOrexpu80JX28MzQC7phW1FG\nfp4tn+6OYwwX7Adw9c+ELkCDnOg/QW07rdOkFFk2eJ0DQ+4QE2xy3q6Ip6FrtUPO\nZ9wj/wMco+I+o0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAd\nBgNVHQ4EFgQUs9tIpPmhxdiuNkHMEWNpYim8S8YwCgYIKoZIzj0EAwMDaAAwZQIx\nAK288mw/EkrRLTnDCgmXc/SINoyIJ7vmiI1Qhadj+Z4y3maTD/HMsQmP3Wyr+mt/\noAIwOWZbwmSNuJ5Q3KjVSaLtx9zRSX8XAbjIho9OjIgrqJqpisXRAL34VOKa5Vt8\nsycX\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert Trusted Root G4 O=DigiCert Inc OU=www.digicert.com\n# Subject: CN=DigiCert Trusted Root G4 O=DigiCert Inc OU=www.digicert.com\n# Label: \"DigiCert Trusted Root G4\"\n# Serial: 7451500558977370777930084869016614236\n# MD5 Fingerprint: 78:f2:fc:aa:60:1f:2f:b4:eb:c9:37:ba:53:2e:75:49\n# SHA1 Fingerprint: dd:fb:16:cd:49:31:c9:73:a2:03:7d:3f:c8:3a:4d:7d:77:5d:05:e4\n# SHA256 Fingerprint: 55:2f:7b:dc:f1:a7:af:9e:6c:e6:72:01:7f:4f:12:ab:f7:72:40:c7:8e:76:1a:c2:03:d1:d9:d2:0a:c8:99:88\n-----BEGIN CERTIFICATE-----\nMIIFkDCCA3igAwIBAgIQBZsbV56OITLiOQe9p3d1XDANBgkqhkiG9w0BAQwFADBi\nMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\nd3cuZGlnaWNlcnQuY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3Qg\nRzQwHhcNMTMwODAxMTIwMDAwWhcNMzgwMTE1MTIwMDAwWjBiMQswCQYDVQQGEwJV\nUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQu\nY29tMSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwggIiMA0GCSqG\nSIb3DQEBAQUAA4ICDwAwggIKAoICAQC/5pBzaN675F1KPDAiMGkz7MKnJS7JIT3y\nithZwuEppz1Yq3aaza57G4QNxDAf8xukOBbrVsaXbR2rsnnyyhHS5F/WBTxSD1If\nxp4VpX6+n6lXFllVcq9ok3DCsrp1mWpzMpTREEQQLt+C8weE5nQ7bXHiLQwb7iDV\nySAdYyktzuxeTsiT+CFhmzTrBcZe7FsavOvJz82sNEBfsXpm7nfISKhmV1efVFiO\nDCu3T6cw2Vbuyntd463JT17lNecxy9qTXtyOj4DatpGYQJB5w3jHtrHEtWoYOAMQ\njdjUN6QuBX2I9YI+EJFwq1WCQTLX2wRzKm6RAXwhTNS8rhsDdV14Ztk6MUSaM0C/\nCNdaSaTC5qmgZ92kJ7yhTzm1EVgX9yRcRo9k98FpiHaYdj1ZXUJ2h4mXaXpI8OCi\nEhtmmnTK3kse5w5jrubU75KSOp493ADkRSWJtppEGSt+wJS00mFt6zPZxd9LBADM\nfRyVw4/3IbKyEbe7f/LVjHAsQWCqsWMYRJUadmJ+9oCw++hkpjPRiQfhvbfmQ6QY\nuKZ3AeEPlAwhHbJUKSWJbOUOUlFHdL4mrLZBdd56rF+NP8m800ERElvlEFDrMcXK\nchYiCd98THU/Y+whX8QgUWtvsauGi0/C1kVfnSD8oR7FwI+isX4KJpn15GkvmB0t\n9dmpsh3lGwIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIB\nhjAdBgNVHQ4EFgQU7NfjgtJxXWRM3y5nP+e6mK4cD08wDQYJKoZIhvcNAQEMBQAD\nggIBALth2X2pbL4XxJEbw6GiAI3jZGgPVs93rnD5/ZpKmbnJeFwMDF/k5hQpVgs2\nSV1EY+CtnJYYZhsjDT156W1r1lT40jzBQ0CuHVD1UvyQO7uYmWlrx8GnqGikJ9yd\n+SeuMIW59mdNOj6PWTkiU0TryF0Dyu1Qen1iIQqAyHNm0aAFYF/opbSnr6j3bTWc\nfFqK1qI4mfN4i/RN0iAL3gTujJtHgXINwBQy7zBZLq7gcfJW5GqXb5JQbZaNaHqa\nsjYUegbyJLkJEVDXCLG4iXqEI2FCKeWjzaIgQdfRnGTZ6iahixTXTBmyUEFxPT9N\ncCOGDErcgdLMMpSEDQgJlxxPwO5rIHQw0uA5NBCFIRUBCOhVMt5xSdkoF1BN5r5N\n0XWs0Mr7QbhDparTwwVETyw2m+L64kW4I1NsBm9nVX9GtUw/bihaeSbSpKhil9Ie\n4u1Ki7wb/UdKDd9nZn6yW0HQO+T0O/QEY+nvwlQAUaCKKsnOeMzV6ocEGLPOr0mI\nr/OSmbaz5mEP0oUA51Aa5BuVnRmhuZyxm7EAHu/QD09CbMkKvO5D+jpxpchNJqU1\n/YldvIViHTLSoCtU7ZpXwdv6EM8Zt4tKG48BtieVU+i2iW1bvGjUI+iLUaJW+fCm\ngKDWHrO8Dw9TdSmq6hN35N6MgSGtBxBHEa2HPQfRdbzP82Z+\n-----END CERTIFICATE-----\n\n# Issuer: CN=COMODO RSA Certification Authority O=COMODO CA Limited\n# Subject: CN=COMODO RSA Certification Authority O=COMODO CA Limited\n# Label: \"COMODO RSA Certification Authority\"\n# Serial: 101909084537582093308941363524873193117\n# MD5 Fingerprint: 1b:31:b0:71:40:36:cc:14:36:91:ad:c4:3e:fd:ec:18\n# SHA1 Fingerprint: af:e5:d2:44:a8:d1:19:42:30:ff:47:9f:e2:f8:97:bb:cd:7a:8c:b4\n# SHA256 Fingerprint: 52:f0:e1:c4:e5:8e:c6:29:29:1b:60:31:7f:07:46:71:b8:5d:7e:a8:0d:5b:07:27:34:63:53:4b:32:b4:02:34\n-----BEGIN CERTIFICATE-----\nMIIF2DCCA8CgAwIBAgIQTKr5yttjb+Af907YWwOGnTANBgkqhkiG9w0BAQwFADCB\nhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G\nA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV\nBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMTE5\nMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBhTELMAkGA1UEBhMCR0IxGzAZBgNVBAgT\nEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR\nQ09NT0RPIENBIExpbWl0ZWQxKzApBgNVBAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNh\ndGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCR\n6FSS0gpWsawNJN3Fz0RndJkrN6N9I3AAcbxT38T6KhKPS38QVr2fcHK3YX/JSw8X\npz3jsARh7v8Rl8f0hj4K+j5c+ZPmNHrZFGvnnLOFoIJ6dq9xkNfs/Q36nGz637CC\n9BR++b7Epi9Pf5l/tfxnQ3K9DADWietrLNPtj5gcFKt+5eNu/Nio5JIk2kNrYrhV\n/erBvGy2i/MOjZrkm2xpmfh4SDBF1a3hDTxFYPwyllEnvGfDyi62a+pGx8cgoLEf\nZd5ICLqkTqnyg0Y3hOvozIFIQ2dOciqbXL1MGyiKXCJ7tKuY2e7gUYPDCUZObT6Z\n+pUX2nwzV0E8jVHtC7ZcryxjGt9XyD+86V3Em69FmeKjWiS0uqlWPc9vqv9JWL7w\nqP/0uK3pN/u6uPQLOvnoQ0IeidiEyxPx2bvhiWC4jChWrBQdnArncevPDt09qZah\nSL0896+1DSJMwBGB7FY79tOi4lu3sgQiUpWAk2nojkxl8ZEDLXB0AuqLZxUpaVIC\nu9ffUGpVRr+goyhhf3DQw6KqLCGqR84onAZFdr+CGCe01a60y1Dma/RMhnEw6abf\nFobg2P9A3fvQQoh/ozM6LlweQRGBY84YcWsr7KaKtzFcOmpH4MN5WdYgGq/yapiq\ncrxXStJLnbsQ/LBMQeXtHT1eKJ2czL+zUdqnR+WEUwIDAQABo0IwQDAdBgNVHQ4E\nFgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB\n/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAArx1UaEt65Ru2yyTUEUAJNMnMvl\nwFTPoCWOAvn9sKIN9SCYPBMtrFaisNZ+EZLpLrqeLppysb0ZRGxhNaKatBYSaVqM\n4dc+pBroLwP0rmEdEBsqpIt6xf4FpuHA1sj+nq6PK7o9mfjYcwlYRm6mnPTXJ9OV\n2jeDchzTc+CiR5kDOF3VSXkAKRzH7JsgHAckaVd4sjn8OoSgtZx8jb8uk2Intzna\nFxiuvTwJaP+EmzzV1gsD41eeFPfR60/IvYcjt7ZJQ3mFXLrrkguhxuhoqEwWsRqZ\nCuhTLJK7oQkYdQxlqHvLI7cawiiFwxv/0Cti76R7CZGYZ4wUAc1oBmpjIXUDgIiK\nboHGhfKppC3n9KUkEEeDys30jXlYsQab5xoq2Z0B15R97QNKyvDb6KkBPvVWmcke\njkk9u+UJueBPSZI9FoJAzMxZxuY67RIuaTxslbH9qh17f4a+Hg4yRvv7E491f0yL\nS0Zj/gA0QHDBw7mh3aZw4gSzQbzpgJHqZJx64SIDqZxubw5lT2yHh17zbqD5daWb\nQOhTsiedSrnAdyGN/4fy3ryM7xfft0kL0fJuMAsaDk527RH89elWsn2/x20Kk4yl\n0MC2Hb46TpSi125sC8KKfPog88Tk5c0NqMuRkrF8hey1FGlmDoLnzc7ILaZRfyHB\nNVOFBkpdn627G190\n-----END CERTIFICATE-----\n\n# Issuer: CN=USERTrust RSA Certification Authority O=The USERTRUST Network\n# Subject: CN=USERTrust RSA Certification Authority O=The USERTRUST Network\n# Label: \"USERTrust RSA Certification Authority\"\n# Serial: 2645093764781058787591871645665788717\n# MD5 Fingerprint: 1b:fe:69:d1:91:b7:19:33:a3:72:a8:0f:e1:55:e5:b5\n# SHA1 Fingerprint: 2b:8f:1b:57:33:0d:bb:a2:d0:7a:6c:51:f7:0e:e9:0d:da:b9:ad:8e\n# SHA256 Fingerprint: e7:93:c9:b0:2f:d8:aa:13:e2:1c:31:22:8a:cc:b0:81:19:64:3b:74:9c:89:89:64:b1:74:6d:46:c3:d4:cb:d2\n-----BEGIN CERTIFICATE-----\nMIIF3jCCA8agAwIBAgIQAf1tMPyjylGoG7xkDjUDLTANBgkqhkiG9w0BAQwFADCB\niDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl\ncnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV\nBAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAw\nMjAxMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNV\nBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVU\naGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBSU0EgQ2Vy\ndGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK\nAoICAQCAEmUXNg7D2wiz0KxXDXbtzSfTTK1Qg2HiqiBNCS1kCdzOiZ/MPans9s/B\n3PHTsdZ7NygRK0faOca8Ohm0X6a9fZ2jY0K2dvKpOyuR+OJv0OwWIJAJPuLodMkY\ntJHUYmTbf6MG8YgYapAiPLz+E/CHFHv25B+O1ORRxhFnRghRy4YUVD+8M/5+bJz/\nFp0YvVGONaanZshyZ9shZrHUm3gDwFA66Mzw3LyeTP6vBZY1H1dat//O+T23LLb2\nVN3I5xI6Ta5MirdcmrS3ID3KfyI0rn47aGYBROcBTkZTmzNg95S+UzeQc0PzMsNT\n79uq/nROacdrjGCT3sTHDN/hMq7MkztReJVni+49Vv4M0GkPGw/zJSZrM233bkf6\nc0Plfg6lZrEpfDKEY1WJxA3Bk1QwGROs0303p+tdOmw1XNtB1xLaqUkL39iAigmT\nYo61Zs8liM2EuLE/pDkP2QKe6xJMlXzzawWpXhaDzLhn4ugTncxbgtNMs+1b/97l\nc6wjOy0AvzVVdAlJ2ElYGn+SNuZRkg7zJn0cTRe8yexDJtC/QV9AqURE9JnnV4ee\nUB9XVKg+/XRjL7FQZQnmWEIuQxpMtPAlR1n6BB6T1CZGSlCBst6+eLf8ZxXhyVeE\nHg9j1uliutZfVS7qXMYoCAQlObgOK6nyTJccBz8NUvXt7y+CDwIDAQABo0IwQDAd\nBgNVHQ4EFgQUU3m/WqorSs9UgOHYm8Cd8rIDZsswDgYDVR0PAQH/BAQDAgEGMA8G\nA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEMBQADggIBAFzUfA3P9wF9QZllDHPF\nUp/L+M+ZBn8b2kMVn54CVVeWFPFSPCeHlCjtHzoBN6J2/FNQwISbxmtOuowhT6KO\nVWKR82kV2LyI48SqC/3vqOlLVSoGIG1VeCkZ7l8wXEskEVX/JJpuXior7gtNn3/3\nATiUFJVDBwn7YKnuHKsSjKCaXqeYalltiz8I+8jRRa8YFWSQEg9zKC7F4iRO/Fjs\n8PRF/iKz6y+O0tlFYQXBl2+odnKPi4w2r78NBc5xjeambx9spnFixdjQg3IM8WcR\niQycE0xyNN+81XHfqnHd4blsjDwSXWXavVcStkNr/+XeTWYRUc+ZruwXtuhxkYze\nSf7dNXGiFSeUHM9h4ya7b6NnJSFd5t0dCy5oGzuCr+yDZ4XUmFF0sbmZgIn/f3gZ\nXHlKYC6SQK5MNyosycdiyA5d9zZbyuAlJQG03RoHnHcAP9Dc1ew91Pq7P8yF1m9/\nqS3fuQL39ZeatTXaw2ewh0qpKJ4jjv9cJ2vhsE/zB+4ALtRZh8tSQZXq9EfX7mRB\nVXyNWQKV3WKdwrnuWih0hKWbt5DHDAff9Yk2dDLWKMGwsAvgnEzDHNb842m1R0aB\nL6KCq9NjRHDEjf8tM7qtj3u1cIiuPhnPQCjY/MiQu12ZIvVS5ljFH4gxQ+6IHdfG\njjxDah2nGN59PRbxYvnKkKj9\n-----END CERTIFICATE-----\n\n# Issuer: CN=USERTrust ECC Certification Authority O=The USERTRUST Network\n# Subject: CN=USERTrust ECC Certification Authority O=The USERTRUST Network\n# Label: \"USERTrust ECC Certification Authority\"\n# Serial: 123013823720199481456569720443997572134\n# MD5 Fingerprint: fa:68:bc:d9:b5:7f:ad:fd:c9:1d:06:83:28:cc:24:c1\n# SHA1 Fingerprint: d1:cb:ca:5d:b2:d5:2a:7f:69:3b:67:4d:e5:f0:5a:1d:0c:95:7d:f0\n# SHA256 Fingerprint: 4f:f4:60:d5:4b:9c:86:da:bf:bc:fc:57:12:e0:40:0d:2b:ed:3f:bc:4d:4f:bd:aa:86:e0:6a:dc:d2:a9:ad:7a\n-----BEGIN CERTIFICATE-----\nMIICjzCCAhWgAwIBAgIQXIuZxVqUxdJxVt7NiYDMJjAKBggqhkjOPQQDAzCBiDEL\nMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNl\neSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMT\nJVVTRVJUcnVzdCBFQ0MgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTAwMjAx\nMDAwMDAwWhcNMzgwMTE4MjM1OTU5WjCBiDELMAkGA1UEBhMCVVMxEzARBgNVBAgT\nCk5ldyBKZXJzZXkxFDASBgNVBAcTC0plcnNleSBDaXR5MR4wHAYDVQQKExVUaGUg\nVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNVBAMTJVVTRVJUcnVzdCBFQ0MgQ2VydGlm\naWNhdGlvbiBBdXRob3JpdHkwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQarFRaqflo\nI+d61SRvU8Za2EurxtW20eZzca7dnNYMYf3boIkDuAUU7FfO7l0/4iGzzvfUinng\no4N+LZfQYcTxmdwlkWOrfzCjtHDix6EznPO/LlxTsV+zfTJ/ijTjeXmjQjBAMB0G\nA1UdDgQWBBQ64QmG1M8ZwpZ2dEl23OA1xmNjmjAOBgNVHQ8BAf8EBAMCAQYwDwYD\nVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjA2Z6EWCNzklwBBHU6+4WMB\nzzuqQhFkoJ2UOQIReVx7Hfpkue4WQrO/isIJxOzksU0CMQDpKmFHjFJKS04YcPbW\nRNZu9YO6bVi9JNlWSOrvxKJGgYhqOkbRqZtNyWHa0V1Xahg=\n-----END CERTIFICATE-----\n\n# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R5\n# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R5\n# Label: \"GlobalSign ECC Root CA - R5\"\n# Serial: 32785792099990507226680698011560947931244\n# MD5 Fingerprint: 9f:ad:3b:1c:02:1e:8a:ba:17:74:38:81:0c:a2:bc:08\n# SHA1 Fingerprint: 1f:24:c6:30:cd:a4:18:ef:20:69:ff:ad:4f:dd:5f:46:3a:1b:69:aa\n# SHA256 Fingerprint: 17:9f:bc:14:8a:3d:d0:0f:d2:4e:a1:34:58:cc:43:bf:a7:f5:9c:81:82:d7:83:a5:13:f6:eb:ec:10:0c:89:24\n-----BEGIN CERTIFICATE-----\nMIICHjCCAaSgAwIBAgIRYFlJ4CYuu1X5CneKcflK2GwwCgYIKoZIzj0EAwMwUDEk\nMCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBDQSAtIFI1MRMwEQYDVQQKEwpH\nbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWduMB4XDTEyMTExMzAwMDAwMFoX\nDTM4MDExOTAzMTQwN1owUDEkMCIGA1UECxMbR2xvYmFsU2lnbiBFQ0MgUm9vdCBD\nQSAtIFI1MRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpHbG9iYWxTaWdu\nMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAER0UOlvt9Xb/pOdEh+J8LttV7HpI6SFkc\n8GIxLcB6KP4ap1yztsyX50XUWPrRd21DosCHZTQKH3rd6zwzocWdTaRvQZU4f8ke\nhOvRnkmSh5SHDDqFSmafnVmTTZdhBoZKo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYD\nVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUPeYpSJvqB8ohREom3m7e0oPQn1kwCgYI\nKoZIzj0EAwMDaAAwZQIxAOVpEslu28YxuglB4Zf4+/2a4n0Sye18ZNPLBSWLVtmg\n515dTguDnFt2KaAJJiFqYgIwcdK1j1zqO+F4CYWodZI7yFz9SO8NdCKoCOJuxUnO\nxwy8p2Fp8fc74SrL+SvzZpA3\n-----END CERTIFICATE-----\n\n# Issuer: CN=Staat der Nederlanden EV Root CA O=Staat der Nederlanden\n# Subject: CN=Staat der Nederlanden EV Root CA O=Staat der Nederlanden\n# Label: \"Staat der Nederlanden EV Root CA\"\n# Serial: 10000013\n# MD5 Fingerprint: fc:06:af:7b:e8:1a:f1:9a:b4:e8:d2:70:1f:c0:f5:ba\n# SHA1 Fingerprint: 76:e2:7e:c1:4f:db:82:c1:c0:a6:75:b5:05:be:3d:29:b4:ed:db:bb\n# SHA256 Fingerprint: 4d:24:91:41:4c:fe:95:67:46:ec:4c:ef:a6:cf:6f:72:e2:8a:13:29:43:2f:9d:8a:90:7a:c4:cb:5d:ad:c1:5a\n-----BEGIN CERTIFICATE-----\nMIIFcDCCA1igAwIBAgIEAJiWjTANBgkqhkiG9w0BAQsFADBYMQswCQYDVQQGEwJO\nTDEeMBwGA1UECgwVU3RhYXQgZGVyIE5lZGVybGFuZGVuMSkwJwYDVQQDDCBTdGFh\ndCBkZXIgTmVkZXJsYW5kZW4gRVYgUm9vdCBDQTAeFw0xMDEyMDgxMTE5MjlaFw0y\nMjEyMDgxMTEwMjhaMFgxCzAJBgNVBAYTAk5MMR4wHAYDVQQKDBVTdGFhdCBkZXIg\nTmVkZXJsYW5kZW4xKTAnBgNVBAMMIFN0YWF0IGRlciBOZWRlcmxhbmRlbiBFViBS\nb290IENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA48d+ifkkSzrS\nM4M1LGns3Amk41GoJSt5uAg94JG6hIXGhaTK5skuU6TJJB79VWZxXSzFYGgEt9nC\nUiY4iKTWO0Cmws0/zZiTs1QUWJZV1VD+hq2kY39ch/aO5ieSZxeSAgMs3NZmdO3d\nZ//BYY1jTw+bbRcwJu+r0h8QoPnFfxZpgQNH7R5ojXKhTbImxrpsX23Wr9GxE46p\nrfNeaXUmGD5BKyF/7otdBwadQ8QpCiv8Kj6GyzyDOvnJDdrFmeK8eEEzduG/L13l\npJhQDBXd4Pqcfzho0LKmeqfRMb1+ilgnQ7O6M5HTp5gVXJrm0w912fxBmJc+qiXb\nj5IusHsMX/FjqTf5m3VpTCgmJdrV8hJwRVXj33NeN/UhbJCONVrJ0yPr08C+eKxC\nKFhmpUZtcALXEPlLVPxdhkqHz3/KRawRWrUgUY0viEeXOcDPusBCAUCZSCELa6fS\n/ZbV0b5GnUngC6agIk440ME8MLxwjyx1zNDFjFE7PZQIZCZhfbnDZY8UnCHQqv0X\ncgOPvZuM5l5Tnrmd74K74bzickFbIZTTRTeU0d8JOV3nI6qaHcptqAqGhYqCvkIH\n1vI4gnPah1vlPNOePqc7nvQDs/nxfRN0Av+7oeX6AHkcpmZBiFxgV6YuCcS6/ZrP\npx9Aw7vMWgpVSzs4dlG4Y4uElBbmVvMCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB\n/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFP6rAJCYniT8qcwaivsnuL8wbqg7\nMA0GCSqGSIb3DQEBCwUAA4ICAQDPdyxuVr5Os7aEAJSrR8kN0nbHhp8dB9O2tLsI\neK9p0gtJ3jPFrK3CiAJ9Brc1AsFgyb/E6JTe1NOpEyVa/m6irn0F3H3zbPB+po3u\n2dfOWBfoqSmuc0iH55vKbimhZF8ZE/euBhD/UcabTVUlT5OZEAFTdfETzsemQUHS\nv4ilf0X8rLiltTMMgsT7B/Zq5SWEXwbKwYY5EdtYzXc7LMJMD16a4/CrPmEbUCTC\nwPTxGfARKbalGAKb12NMcIxHowNDXLldRqANb/9Zjr7dn3LDWyvfjFvO5QxGbJKy\nCqNMVEIYFRIYvdr8unRu/8G2oGTYqV9Vrp9canaW2HNnh/tNf1zuacpzEPuKqf2e\nvTY4SUmH9A4U8OmHuD+nT3pajnnUk+S7aFKErGzp85hwVXIy+TSrK0m1zSBi5Dp6\nZ2Orltxtrpfs/J92VoguZs9btsmksNcFuuEnL5O7Jiqik7Ab846+HUCjuTaPPoIa\nGl6I6lD4WeKDRikL40Rc4ZW2aZCaFG+XroHPaO+Zmr615+F/+PoTRxZMzG0IQOeL\neG9QgkRQP2YGiqtDhFZKDyAthg710tvSeopLzaXoTvFeJiUBWSOgftL2fiFX1ye8\nFVdMpEbB4IMeDExNH08GGeL5qPQ6gqGyeUN51q1veieQA6TqJIc/2b3Z6fJfUEkc\n7uzXLg==\n-----END CERTIFICATE-----\n\n# Issuer: CN=IdenTrust Commercial Root CA 1 O=IdenTrust\n# Subject: CN=IdenTrust Commercial Root CA 1 O=IdenTrust\n# Label: \"IdenTrust Commercial Root CA 1\"\n# Serial: 13298821034946342390520003877796839426\n# MD5 Fingerprint: b3:3e:77:73:75:ee:a0:d3:e3:7e:49:63:49:59:bb:c7\n# SHA1 Fingerprint: df:71:7e:aa:4a:d9:4e:c9:55:84:99:60:2d:48:de:5f:bc:f0:3a:25\n# SHA256 Fingerprint: 5d:56:49:9b:e4:d2:e0:8b:cf:ca:d0:8a:3e:38:72:3d:50:50:3b:de:70:69:48:e4:2f:55:60:30:19:e5:28:ae\n-----BEGIN CERTIFICATE-----\nMIIFYDCCA0igAwIBAgIQCgFCgAAAAUUjyES1AAAAAjANBgkqhkiG9w0BAQsFADBK\nMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScwJQYDVQQDEx5JZGVu\nVHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwHhcNMTQwMTE2MTgxMjIzWhcNMzQw\nMTE2MTgxMjIzWjBKMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MScw\nJQYDVQQDEx5JZGVuVHJ1c3QgQ29tbWVyY2lhbCBSb290IENBIDEwggIiMA0GCSqG\nSIb3DQEBAQUAA4ICDwAwggIKAoICAQCnUBneP5k91DNG8W9RYYKyqU+PZ4ldhNlT\n3Qwo2dfw/66VQ3KZ+bVdfIrBQuExUHTRgQ18zZshq0PirK1ehm7zCYofWjK9ouuU\n+ehcCuz/mNKvcbO0U59Oh++SvL3sTzIwiEsXXlfEU8L2ApeN2WIrvyQfYo3fw7gp\nS0l4PJNgiCL8mdo2yMKi1CxUAGc1bnO/AljwpN3lsKImesrgNqUZFvX9t++uP0D1\nbVoE/c40yiTcdCMbXTMTEl3EASX2MN0CXZ/g1Ue9tOsbobtJSdifWwLziuQkkORi\nT0/Br4sOdBeo0XKIanoBScy0RnnGF7HamB4HWfp1IYVl3ZBWzvurpWCdxJ35UrCL\nvYf5jysjCiN2O/cz4ckA82n5S6LgTrx+kzmEB/dEcH7+B1rlsazRGMzyNeVJSQjK\nVsk9+w8YfYs7wRPCTY/JTw436R+hDmrfYi7LNQZReSzIJTj0+kuniVyc0uMNOYZK\ndHzVWYfCP04MXFL0PfdSgvHqo6z9STQaKPNBiDoT7uje/5kdX7rL6B7yuVBgwDHT\nc+XvvqDtMwt0viAgxGds8AgDelWAf0ZOlqf0Hj7h9tgJ4TNkK2PXMl6f+cB7D3hv\nl7yTmvmcEpB4eoCHFddydJxVdHixuuFucAS6T6C6aMN7/zHwcz09lCqxC0EOoP5N\niGVreTO01wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB\n/zAdBgNVHQ4EFgQU7UQZwNPwBovupHu+QucmVMiONnYwDQYJKoZIhvcNAQELBQAD\nggIBAA2ukDL2pkt8RHYZYR4nKM1eVO8lvOMIkPkp165oCOGUAFjvLi5+U1KMtlwH\n6oi6mYtQlNeCgN9hCQCTrQ0U5s7B8jeUeLBfnLOic7iPBZM4zY0+sLj7wM+x8uwt\nLRvM7Kqas6pgghstO8OEPVeKlh6cdbjTMM1gCIOQ045U8U1mwF10A0Cj7oV+wh93\nnAbowacYXVKV7cndJZ5t+qntozo00Fl72u1Q8zW/7esUTTHHYPTa8Yec4kjixsU3\n+wYQ+nVZZjFHKdp2mhzpgq7vmrlR94gjmmmVYjzlVYA211QC//G5Xc7UI2/YRYRK\nW2XviQzdFKcgyxilJbQN+QHwotL0AMh0jqEqSI5l2xPE4iUXfeu+h1sXIFRRk0pT\nAwvsXcoz7WL9RccvW9xYoIA55vrX/hMUpu09lEpCdNTDd1lzzY9GvlU47/rokTLq\nl1gEIt44w8y8bckzOmoKaT+gyOpyj4xjhiO9bTyWnpXgSUyqorkqG5w2gXjtw+hG\n4iZZRHUe2XWJUc0QhJ1hYMtd+ZciTY6Y5uN/9lu7rs3KSoFrXgvzUeF0K+l+J6fZ\nmUlO+KWA2yUPHGNiiskzZ2s8EIPGrd6ozRaOjfAHN3Gf8qv8QfXBi+wAN10J5U6A\n7/qxXDgGpRtK4dw4LTzcqx+QGtVKnO7RcGzM7vRX+Bi6hG6H\n-----END CERTIFICATE-----\n\n# Issuer: CN=IdenTrust Public Sector Root CA 1 O=IdenTrust\n# Subject: CN=IdenTrust Public Sector Root CA 1 O=IdenTrust\n# Label: \"IdenTrust Public Sector Root CA 1\"\n# Serial: 13298821034946342390521976156843933698\n# MD5 Fingerprint: 37:06:a5:b0:fc:89:9d:ba:f4:6b:8c:1a:64:cd:d5:ba\n# SHA1 Fingerprint: ba:29:41:60:77:98:3f:f4:f3:ef:f2:31:05:3b:2e:ea:6d:4d:45:fd\n# SHA256 Fingerprint: 30:d0:89:5a:9a:44:8a:26:20:91:63:55:22:d1:f5:20:10:b5:86:7a:ca:e1:2c:78:ef:95:8f:d4:f4:38:9f:2f\n-----BEGIN CERTIFICATE-----\nMIIFZjCCA06gAwIBAgIQCgFCgAAAAUUjz0Z8AAAAAjANBgkqhkiG9w0BAQsFADBN\nMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0MSowKAYDVQQDEyFJZGVu\nVHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwHhcNMTQwMTE2MTc1MzMyWhcN\nMzQwMTE2MTc1MzMyWjBNMQswCQYDVQQGEwJVUzESMBAGA1UEChMJSWRlblRydXN0\nMSowKAYDVQQDEyFJZGVuVHJ1c3QgUHVibGljIFNlY3RvciBSb290IENBIDEwggIi\nMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC2IpT8pEiv6EdrCvsnduTyP4o7\nekosMSqMjbCpwzFrqHd2hCa2rIFCDQjrVVi7evi8ZX3yoG2LqEfpYnYeEe4IFNGy\nRBb06tD6Hi9e28tzQa68ALBKK0CyrOE7S8ItneShm+waOh7wCLPQ5CQ1B5+ctMlS\nbdsHyo+1W/CD80/HLaXIrcuVIKQxKFdYWuSNG5qrng0M8gozOSI5Cpcu81N3uURF\n/YTLNiCBWS2ab21ISGHKTN9T0a9SvESfqy9rg3LvdYDaBjMbXcjaY8ZNzaxmMc3R\n3j6HEDbhuaR672BQssvKplbgN6+rNBM5Jeg5ZuSYeqoSmJxZZoY+rfGwyj4GD3vw\nEUs3oERte8uojHH01bWRNszwFcYr3lEXsZdMUD2xlVl8BX0tIdUAvwFnol57plzy\n9yLxkA2T26pEUWbMfXYD62qoKjgZl3YNa4ph+bz27nb9cCvdKTz4Ch5bQhyLVi9V\nGxyhLrXHFub4qjySjmm2AcG1hp2JDws4lFTo6tyePSW8Uybt1as5qsVATFSrsrTZ\n2fjXctscvG29ZV/viDUqZi/u9rNl8DONfJhBaUYPQxxp+pu10GFqzcpL2UyQRqsV\nWaFHVCkugyhfHMKiq3IXAAaOReyL4jM9f9oZRORicsPfIsbyVtTdX5Vy7W1f90gD\nW/3FKqD2cyOEEBsB5wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/\nBAUwAwEB/zAdBgNVHQ4EFgQU43HgntinQtnbcZFrlJPrw6PRFKMwDQYJKoZIhvcN\nAQELBQADggIBAEf63QqwEZE4rU1d9+UOl1QZgkiHVIyqZJnYWv6IAcVYpZmxI1Qj\nt2odIFflAWJBF9MJ23XLblSQdf4an4EKwt3X9wnQW3IV5B4Jaj0z8yGa5hV+rVHV\nDRDtfULAj+7AmgjVQdZcDiFpboBhDhXAuM/FSRJSzL46zNQuOAXeNf0fb7iAaJg9\nTaDKQGXSc3z1i9kKlT/YPyNtGtEqJBnZhbMX73huqVjRI9PHE+1yJX9dsXNw0H8G\nlwmEKYBhHfpe/3OsoOOJuBxxFcbeMX8S3OFtm6/n6J91eEyrRjuazr8FGF1NFTwW\nmhlQBJqymm9li1JfPFgEKCXAZmExfrngdbkaqIHWchezxQMxNRF4eKLg6TCMf4Df\nWN88uieW4oA0beOY02QnrEh+KHdcxiVhJfiFDGX6xDIvpZgF5PgLZxYWxoK4Mhn5\n+bl53B/N66+rDt0b20XkeucC4pVd/GnwU2lhlXV5C15V5jgclKlZM57IcXR5f1GJ\ntshquDDIajjDbp7hNxbqBWJMWxJH7ae0s1hWx0nzfxJoCTFx8G34Tkf71oXuxVhA\nGaQdp/lLQzfcaFpPz+vCZHTetBXZ9FRUGi8c15dxVJCO2SCdUyt/q4/i6jC8UDfv\n8Ue1fXwsBOxonbRJRBD0ckscZOf85muQ3Wl9af0AVqW3rLatt8o+Ae+c\n-----END CERTIFICATE-----\n\n# Issuer: CN=Entrust Root Certification Authority - G2 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2009 Entrust, Inc. - for authorized use only\n# Subject: CN=Entrust Root Certification Authority - G2 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2009 Entrust, Inc. - for authorized use only\n# Label: \"Entrust Root Certification Authority - G2\"\n# Serial: 1246989352\n# MD5 Fingerprint: 4b:e2:c9:91:96:65:0c:f4:0e:5a:93:92:a0:0a:fe:b2\n# SHA1 Fingerprint: 8c:f4:27:fd:79:0c:3a:d1:66:06:8d:e8:1e:57:ef:bb:93:22:72:d4\n# SHA256 Fingerprint: 43:df:57:74:b0:3e:7f:ef:5f:e4:0d:93:1a:7b:ed:f1:bb:2e:6b:42:73:8c:4e:6d:38:41:10:3d:3a:a7:f3:39\n-----BEGIN CERTIFICATE-----\nMIIEPjCCAyagAwIBAgIESlOMKDANBgkqhkiG9w0BAQsFADCBvjELMAkGA1UEBhMC\nVVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50\ncnVzdC5uZXQvbGVnYWwtdGVybXMxOTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3Qs\nIEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ugb25seTEyMDAGA1UEAxMpRW50cnVz\ndCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzIwHhcNMDkwNzA3MTcy\nNTU0WhcNMzAxMjA3MTc1NTU0WjCBvjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUVu\ndHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3d3cuZW50cnVzdC5uZXQvbGVnYWwt\ndGVybXMxOTA3BgNVBAsTMChjKSAyMDA5IEVudHJ1c3QsIEluYy4gLSBmb3IgYXV0\naG9yaXplZCB1c2Ugb25seTEyMDAGA1UEAxMpRW50cnVzdCBSb290IENlcnRpZmlj\nYXRpb24gQXV0aG9yaXR5IC0gRzIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK\nAoIBAQC6hLZy254Ma+KZ6TABp3bqMriVQRrJ2mFOWHLP/vaCeb9zYQYKpSfYs1/T\nRU4cctZOMvJyig/3gxnQaoCAAEUesMfnmr8SVycco2gvCoe9amsOXmXzHHfV1IWN\ncCG0szLni6LVhjkCsbjSR87kyUnEO6fe+1R9V77w6G7CebI6C1XiUJgWMhNcL3hW\nwcKUs/Ja5CeanyTXxuzQmyWC48zCxEXFjJd6BmsqEZ+pCm5IO2/b1BEZQvePB7/1\nU1+cPvQXLOZprE4yTGJ36rfo5bs0vBmLrpxR57d+tVOxMyLlbc9wPBr64ptntoP0\njaWvYkxN4FisZDQSA/i2jZRjJKRxAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAP\nBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRqciZ60B7vfec7aVHUbI2fkBJmqzAN\nBgkqhkiG9w0BAQsFAAOCAQEAeZ8dlsa2eT8ijYfThwMEYGprmi5ZiXMRrEPR9RP/\njTkrwPK9T3CMqS/qF8QLVJ7UG5aYMzyorWKiAHarWWluBh1+xLlEjZivEtRh2woZ\nRkfz6/djwUAFQKXSt/S1mja/qYh2iARVBCuch38aNzx+LaUa2NSJXsq9rD1s2G2v\n1fN2D807iDginWyTmsQ9v4IbZT+mD12q/OWyFcq1rca8PdCE6OoGcrBNOTJ4vz4R\nnAuknZoh8/CbCzB428Hch0P+vGOaysXCHMnHjf87ElgI5rY97HosTvuDls4MPGmH\nVHOkc8KT/1EQrBVUAdj8BbGJoX90g5pJ19xOe4pIb4tF9g==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Entrust Root Certification Authority - EC1 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2012 Entrust, Inc. - for authorized use only\n# Subject: CN=Entrust Root Certification Authority - EC1 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2012 Entrust, Inc. - for authorized use only\n# Label: \"Entrust Root Certification Authority - EC1\"\n# Serial: 51543124481930649114116133369\n# MD5 Fingerprint: b6:7e:1d:f0:58:c5:49:6c:24:3b:3d:ed:98:18:ed:bc\n# SHA1 Fingerprint: 20:d8:06:40:df:9b:25:f5:12:25:3a:11:ea:f7:59:8a:eb:14:b5:47\n# SHA256 Fingerprint: 02:ed:0e:b2:8c:14:da:45:16:5c:56:67:91:70:0d:64:51:d7:fb:56:f0:b2:ab:1d:3b:8e:b0:70:e5:6e:df:f5\n-----BEGIN CERTIFICATE-----\nMIIC+TCCAoCgAwIBAgINAKaLeSkAAAAAUNCR+TAKBggqhkjOPQQDAzCBvzELMAkG\nA1UEBhMCVVMxFjAUBgNVBAoTDUVudHJ1c3QsIEluYy4xKDAmBgNVBAsTH1NlZSB3\nd3cuZW50cnVzdC5uZXQvbGVnYWwtdGVybXMxOTA3BgNVBAsTMChjKSAyMDEyIEVu\ndHJ1c3QsIEluYy4gLSBmb3IgYXV0aG9yaXplZCB1c2Ugb25seTEzMDEGA1UEAxMq\nRW50cnVzdCBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRUMxMB4XDTEy\nMTIxODE1MjUzNloXDTM3MTIxODE1NTUzNlowgb8xCzAJBgNVBAYTAlVTMRYwFAYD\nVQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQLEx9TZWUgd3d3LmVudHJ1c3QubmV0\nL2xlZ2FsLXRlcm1zMTkwNwYDVQQLEzAoYykgMjAxMiBFbnRydXN0LCBJbmMuIC0g\nZm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxMzAxBgNVBAMTKkVudHJ1c3QgUm9vdCBD\nZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEVDMTB2MBAGByqGSM49AgEGBSuBBAAi\nA2IABIQTydC6bUF74mzQ61VfZgIaJPRbiWlH47jCffHyAsWfoPZb1YsGGYZPUxBt\nByQnoaD41UcZYUx9ypMn6nQM72+WCf5j7HBdNq1nd67JnXxVRDqiY1Ef9eNi1KlH\nBz7MIKNCMEAwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0O\nBBYEFLdj5xrdjekIplWDpOBqUEFlEUJJMAoGCCqGSM49BAMDA2cAMGQCMGF52OVC\nR98crlOZF7ZvHH3hvxGU0QOIdeSNiaSKd0bebWHvAvX7td/M/k7//qnmpwIwW5nX\nhTcGtXsI/esni0qU+eH6p44mCOh8kmhtc9hvJqwhAriZtyZBWyVgrtBIGu4G\n-----END CERTIFICATE-----\n\n# Issuer: CN=CFCA EV ROOT O=China Financial Certification Authority\n# Subject: CN=CFCA EV ROOT O=China Financial Certification Authority\n# Label: \"CFCA EV ROOT\"\n# Serial: 407555286\n# MD5 Fingerprint: 74:e1:b6:ed:26:7a:7a:44:30:33:94:ab:7b:27:81:30\n# SHA1 Fingerprint: e2:b8:29:4b:55:84:ab:6b:58:c2:90:46:6c:ac:3f:b8:39:8f:84:83\n# SHA256 Fingerprint: 5c:c3:d7:8e:4e:1d:5e:45:54:7a:04:e6:87:3e:64:f9:0c:f9:53:6d:1c:cc:2e:f8:00:f3:55:c4:c5:fd:70:fd\n-----BEGIN CERTIFICATE-----\nMIIFjTCCA3WgAwIBAgIEGErM1jANBgkqhkiG9w0BAQsFADBWMQswCQYDVQQGEwJD\nTjEwMC4GA1UECgwnQ2hpbmEgRmluYW5jaWFsIENlcnRpZmljYXRpb24gQXV0aG9y\naXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJPT1QwHhcNMTIwODA4MDMwNzAxWhcNMjkx\nMjMxMDMwNzAxWjBWMQswCQYDVQQGEwJDTjEwMC4GA1UECgwnQ2hpbmEgRmluYW5j\naWFsIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MRUwEwYDVQQDDAxDRkNBIEVWIFJP\nT1QwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDXXWvNED8fBVnVBU03\nsQ7smCuOFR36k0sXgiFxEFLXUWRwFsJVaU2OFW2fvwwbwuCjZ9YMrM8irq93VCpL\nTIpTUnrD7i7es3ElweldPe6hL6P3KjzJIx1qqx2hp/Hz7KDVRM8Vz3IvHWOX6Jn5\n/ZOkVIBMUtRSqy5J35DNuF++P96hyk0g1CXohClTt7GIH//62pCfCqktQT+x8Rgp\n7hZZLDRJGqgG16iI0gNyejLi6mhNbiyWZXvKWfry4t3uMCz7zEasxGPrb382KzRz\nEpR/38wmnvFyXVBlWY9ps4deMm/DGIq1lY+wejfeWkU7xzbh72fROdOXW3NiGUgt\nhxwG+3SYIElz8AXSG7Ggo7cbcNOIabla1jj0Ytwli3i/+Oh+uFzJlU9fpy25IGvP\na931DfSCt/SyZi4QKPaXWnuWFo8BGS1sbn85WAZkgwGDg8NNkt0yxoekN+kWzqot\naK8KgWU6cMGbrU1tVMoqLUuFG7OA5nBFDWteNfB/O7ic5ARwiRIlk9oKmSJgamNg\nTnYGmE69g60dWIolhdLHZR4tjsbftsbhf4oEIRUpdPA+nJCdDC7xij5aqgwJHsfV\nPKPtl8MeNPo4+QgO48BdK4PRVmrJtqhUUy54Mmc9gn900PvhtgVguXDbjgv5E1hv\ncWAQUhC5wUEJ73IfZzF4/5YFjQIDAQABo2MwYTAfBgNVHSMEGDAWgBTj/i39KNAL\ntbq2osS/BqoFjJP7LzAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAd\nBgNVHQ4EFgQU4/4t/SjQC7W6tqLEvwaqBYyT+y8wDQYJKoZIhvcNAQELBQADggIB\nACXGumvrh8vegjmWPfBEp2uEcwPenStPuiB/vHiyz5ewG5zz13ku9Ui20vsXiObT\nej/tUxPQ4i9qecsAIyjmHjdXNYmEwnZPNDatZ8POQQaIxffu2Bq41gt/UP+TqhdL\njOztUmCypAbqTuv0axn96/Ua4CUqmtzHQTb3yHQFhDmVOdYLO6Qn+gjYXB74BGBS\nESgoA//vU2YApUo0FmZ8/Qmkrp5nGm9BC2sGE5uPhnEFtC+NiWYzKXZUmhH4J/qy\nP5Hgzg0b8zAarb8iXRvTvyUFTeGSGn+ZnzxEk8rUQElsgIfXBDrDMlI1Dlb4pd19\nxIsNER9Tyx6yF7Zod1rg1MvIB671Oi6ON7fQAUtDKXeMOZePglr4UeWJoBjnaH9d\nCi77o0cOPaYjesYBx4/IXr9tgFa+iiS6M+qf4TIRnvHST4D2G0CvOJ4RUHlzEhLN\n5mydLIhyPDCBBpEi6lmt2hkuIsKNuYyH4Ga8cyNfIWRjgEj1oDwYPZTISEEdQLpe\n/v5WOaHIz16eGWRGENoXkbcFgKyLmZJ956LYBws2J+dIeWCKw9cTXPhyQN9Ky8+Z\nAAoACxGV2lZFA4gKn2fQ1XmxqI1AbQ3CekD6819kR5LLU7m7Wc5P/dAVUwHY3+vZ\n5nbv0CO7O6l5s9UCKc2Jo5YPSjXnTkLAdc0Hz+Ys63su\n-----END CERTIFICATE-----\n\n# Issuer: CN=OISTE WISeKey Global Root GB CA O=WISeKey OU=OISTE Foundation Endorsed\n# Subject: CN=OISTE WISeKey Global Root GB CA O=WISeKey OU=OISTE Foundation Endorsed\n# Label: \"OISTE WISeKey Global Root GB CA\"\n# Serial: 157768595616588414422159278966750757568\n# MD5 Fingerprint: a4:eb:b9:61:28:2e:b7:2f:98:b0:35:26:90:99:51:1d\n# SHA1 Fingerprint: 0f:f9:40:76:18:d3:d7:6a:4b:98:f0:a8:35:9e:0c:fd:27:ac:cc:ed\n# SHA256 Fingerprint: 6b:9c:08:e8:6e:b0:f7:67:cf:ad:65:cd:98:b6:21:49:e5:49:4a:67:f5:84:5e:7b:d1:ed:01:9f:27:b8:6b:d6\n-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIQdrEgUnTwhYdGs/gjGvbCwDANBgkqhkiG9w0BAQsFADBt\nMQswCQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUg\nRm91bmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9i\nYWwgUm9vdCBHQiBDQTAeFw0xNDEyMDExNTAwMzJaFw0zOTEyMDExNTEwMzFaMG0x\nCzAJBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBG\nb3VuZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2Jh\nbCBSb290IEdCIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2Be3\nHEokKtaXscriHvt9OO+Y9bI5mE4nuBFde9IllIiCFSZqGzG7qFshISvYD06fWvGx\nWuR51jIjK+FTzJlFXHtPrby/h0oLS5daqPZI7H17Dc0hBt+eFf1Biki3IPShehtX\n1F1Q/7pn2COZH8g/497/b1t3sWtuuMlk9+HKQUYOKXHQuSP8yYFfTvdv37+ErXNk\nu7dCjmn21HYdfp2nuFeKUWdy19SouJVUQHMD9ur06/4oQnc/nSMbsrY9gBQHTC5P\n99UKFg29ZkM3fiNDecNAhvVMKdqOmq0NpQSHiB6F4+lT1ZvIiwNjeOvgGUpuuy9r\nM2RYk61pv48b74JIxwIDAQABo1EwTzALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUw\nAwEB/zAdBgNVHQ4EFgQUNQ/INmNe4qPs+TtmFc5RUuORmj0wEAYJKwYBBAGCNxUB\nBAMCAQAwDQYJKoZIhvcNAQELBQADggEBAEBM+4eymYGQfp3FsLAmzYh7KzKNbrgh\ncViXfa43FK8+5/ea4n32cZiZBKpDdHij40lhPnOMTZTg+XHEthYOU3gf1qKHLwI5\ngSk8rxWYITD+KJAAjNHhy/peyP34EEY7onhCkRd0VQreUGdNZtGn//3ZwLWoo4rO\nZvUPQ82nK1d7Y0Zqqi5S2PTt4W2tKZB4SLrhI6qjiey1q5bAtEuiHZeeevJuQHHf\naPFlTc58Bd9TZaml8LGXBHAVRgOY1NK/VLSgWH1Sb9pWJmLU2NuJMW8c8CLC02Ic\nNc1MaRVUGpCY3useX8p3x8uOPUNpnJpY0CQ73xtAln41rYHHTnG6iBM=\n-----END CERTIFICATE-----\n\n# Issuer: CN=SZAFIR ROOT CA2 O=Krajowa Izba Rozliczeniowa S.A.\n# Subject: CN=SZAFIR ROOT CA2 O=Krajowa Izba Rozliczeniowa S.A.\n# Label: \"SZAFIR ROOT CA2\"\n# Serial: 357043034767186914217277344587386743377558296292\n# MD5 Fingerprint: 11:64:c1:89:b0:24:b1:8c:b1:07:7e:89:9e:51:9e:99\n# SHA1 Fingerprint: e2:52:fa:95:3f:ed:db:24:60:bd:6e:28:f3:9c:cc:cf:5e:b3:3f:de\n# SHA256 Fingerprint: a1:33:9d:33:28:1a:0b:56:e5:57:d3:d3:2b:1c:e7:f9:36:7e:b0:94:bd:5f:a7:2a:7e:50:04:c8:de:d7:ca:fe\n-----BEGIN CERTIFICATE-----\nMIIDcjCCAlqgAwIBAgIUPopdB+xV0jLVt+O2XwHrLdzk1uQwDQYJKoZIhvcNAQEL\nBQAwUTELMAkGA1UEBhMCUEwxKDAmBgNVBAoMH0tyYWpvd2EgSXpiYSBSb3psaWN6\nZW5pb3dhIFMuQS4xGDAWBgNVBAMMD1NaQUZJUiBST09UIENBMjAeFw0xNTEwMTkw\nNzQzMzBaFw0zNTEwMTkwNzQzMzBaMFExCzAJBgNVBAYTAlBMMSgwJgYDVQQKDB9L\ncmFqb3dhIEl6YmEgUm96bGljemVuaW93YSBTLkEuMRgwFgYDVQQDDA9TWkFGSVIg\nUk9PVCBDQTIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC3vD5QqEvN\nQLXOYeeWyrSh2gwisPq1e3YAd4wLz32ohswmUeQgPYUM1ljj5/QqGJ3a0a4m7utT\n3PSQ1hNKDJA8w/Ta0o4NkjrcsbH/ON7Dui1fgLkCvUqdGw+0w8LBZwPd3BucPbOw\n3gAeqDRHu5rr/gsUvTaE2g0gv/pby6kWIK05YO4vdbbnl5z5Pv1+TW9NL++IDWr6\n3fE9biCloBK0TXC5ztdyO4mTp4CEHCdJckm1/zuVnsHMyAHs6A6KCpbns6aH5db5\nBSsNl0BwPLqsdVqc1U2dAgrSS5tmS0YHF2Wtn2yIANwiieDhZNRnvDF5YTy7ykHN\nXGoAyDw4jlivAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD\nAgEGMB0GA1UdDgQWBBQuFqlKGLXLzPVvUPMjX/hd56zwyDANBgkqhkiG9w0BAQsF\nAAOCAQEAtXP4A9xZWx126aMqe5Aosk3AM0+qmrHUuOQn/6mWmc5G4G18TKI4pAZw\n8PRBEew/R40/cof5O/2kbytTAOD/OblqBw7rHRz2onKQy4I9EYKL0rufKq8h5mOG\nnXkZ7/e7DDWQw4rtTw/1zBLZpD67oPwglV9PJi8RI4NOdQcPv5vRtB3pEAT+ymCP\noky4rc/hkA/NrgrHXXu3UNLUYfrVFdvXn4dRVOul4+vJhaAlIDf7js4MNIThPIGy\nd05DpYhfhmehPea0XGG2Ptv+tyjFogeutcrKjSoS75ftwjCkySp6+/NNIxuZMzSg\nLvWpCz/UXeHPhJ/iGcJfitYgHuNztw==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certum Trusted Network CA 2 O=Unizeto Technologies S.A. OU=Certum Certification Authority\n# Subject: CN=Certum Trusted Network CA 2 O=Unizeto Technologies S.A. OU=Certum Certification Authority\n# Label: \"Certum Trusted Network CA 2\"\n# Serial: 44979900017204383099463764357512596969\n# MD5 Fingerprint: 6d:46:9e:d9:25:6d:08:23:5b:5e:74:7d:1e:27:db:f2\n# SHA1 Fingerprint: d3:dd:48:3e:2b:bf:4c:05:e8:af:10:f5:fa:76:26:cf:d3:dc:30:92\n# SHA256 Fingerprint: b6:76:f2:ed:da:e8:77:5c:d3:6c:b0:f6:3c:d1:d4:60:39:61:f4:9e:62:65:ba:01:3a:2f:03:07:b6:d0:b8:04\n-----BEGIN CERTIFICATE-----\nMIIF0jCCA7qgAwIBAgIQIdbQSk8lD8kyN/yqXhKN6TANBgkqhkiG9w0BAQ0FADCB\ngDELMAkGA1UEBhMCUEwxIjAgBgNVBAoTGVVuaXpldG8gVGVjaG5vbG9naWVzIFMu\nQS4xJzAlBgNVBAsTHkNlcnR1bSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEkMCIG\nA1UEAxMbQ2VydHVtIFRydXN0ZWQgTmV0d29yayBDQSAyMCIYDzIwMTExMDA2MDgz\nOTU2WhgPMjA0NjEwMDYwODM5NTZaMIGAMQswCQYDVQQGEwJQTDEiMCAGA1UEChMZ\nVW5pemV0byBUZWNobm9sb2dpZXMgUy5BLjEnMCUGA1UECxMeQ2VydHVtIENlcnRp\nZmljYXRpb24gQXV0aG9yaXR5MSQwIgYDVQQDExtDZXJ0dW0gVHJ1c3RlZCBOZXR3\nb3JrIENBIDIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC9+Xj45tWA\nDGSdhhuWZGc/IjoedQF97/tcZ4zJzFxrqZHmuULlIEub2pt7uZld2ZuAS9eEQCsn\n0+i6MLs+CRqnSZXvK0AkwpfHp+6bJe+oCgCXhVqqndwpyeI1B+twTUrWwbNWuKFB\nOJvR+zF/j+Bf4bE/D44WSWDXBo0Y+aomEKsq09DRZ40bRr5HMNUuctHFY9rnY3lE\nfktjJImGLjQ/KUxSiyqnwOKRKIm5wFv5HdnnJ63/mgKXwcZQkpsCLL2puTRZCr+E\nSv/f/rOf69me4Jgj7KZrdxYq28ytOxykh9xGc14ZYmhFV+SQgkK7QtbwYeDBoz1m\no130GO6IyY0XRSmZMnUCMe4pJshrAua1YkV/NxVaI2iJ1D7eTiew8EAMvE0Xy02i\nsx7QBlrd9pPPV3WZ9fqGGmd4s7+W/jTcvedSVuWz5XV710GRBdxdaeOVDUO5/IOW\nOZV7bIBaTxNyxtd9KXpEulKkKtVBRgkg/iKgtlswjbyJDNXXcPiHUv3a76xRLgez\nTv7QCdpw75j6VuZt27VXS9zlLCUVyJ4ueE742pyehizKV/Ma5ciSixqClnrDvFAS\nadgOWkaLOusm+iPJtrCBvkIApPjW/jAux9JG9uWOdf3yzLnQh1vMBhBgu4M1t15n\n3kfsmUjxpKEV/q2MYo45VU85FrmxY53/twIDAQABo0IwQDAPBgNVHRMBAf8EBTAD\nAQH/MB0GA1UdDgQWBBS2oVQ5AsOgP46KvPrU+Bym0ToO/TAOBgNVHQ8BAf8EBAMC\nAQYwDQYJKoZIhvcNAQENBQADggIBAHGlDs7k6b8/ONWJWsQCYftMxRQXLYtPU2sQ\nF/xlhMcQSZDe28cmk4gmb3DWAl45oPePq5a1pRNcgRRtDoGCERuKTsZPpd1iHkTf\nCVn0W3cLN+mLIMb4Ck4uWBzrM9DPhmDJ2vuAL55MYIR4PSFk1vtBHxgP58l1cb29\nXN40hz5BsA72udY/CROWFC/emh1auVbONTqwX3BNXuMp8SMoclm2q8KMZiYcdywm\ndjWLKKdpoPk79SPdhRB0yZADVpHnr7pH1BKXESLjokmUbOe3lEu6LaTaM4tMpkT/\nWjzGHWTYtTHkpjx6qFcL2+1hGsvxznN3Y6SHb0xRONbkX8eftoEq5IVIeVheO/jb\nAoJnwTnbw3RLPTYe+SmTiGhbqEQZIfCn6IENLOiTNrQ3ssqwGyZ6miUfmpqAnksq\nP/ujmv5zMnHCnsZy4YpoJ/HkD7TETKVhk/iXEAcqMCWpuchxuO9ozC1+9eB+D4Ko\nb7a6bINDd82Kkhehnlt4Fj1F4jNy3eFmypnTycUm/Q1oBEauttmbjL4ZvrHG8hnj\nXALKLNhvSgfZyTXaQHXyxKcZb55CEJh15pWLYLztxRLXis7VmFxWlgPF7ncGNf/P\n5O4/E2Hu29othfDNrp2yGAlFw5Khchf8R7agCyzxxN5DaAhqXzvwdmP7zAYspsbi\nDrW5viSP\n-----END CERTIFICATE-----\n\n# Issuer: CN=Hellenic Academic and Research Institutions RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority\n# Subject: CN=Hellenic Academic and Research Institutions RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority\n# Label: \"Hellenic Academic and Research Institutions RootCA 2015\"\n# Serial: 0\n# MD5 Fingerprint: ca:ff:e2:db:03:d9:cb:4b:e9:0f:ad:84:fd:7b:18:ce\n# SHA1 Fingerprint: 01:0c:06:95:a6:98:19:14:ff:bf:5f:c6:b0:b6:95:ea:29:e9:12:a6\n# SHA256 Fingerprint: a0:40:92:9a:02:ce:53:b4:ac:f4:f2:ff:c6:98:1c:e4:49:6f:75:5e:6d:45:fe:0b:2a:69:2b:cd:52:52:3f:36\n-----BEGIN CERTIFICATE-----\nMIIGCzCCA/OgAwIBAgIBADANBgkqhkiG9w0BAQsFADCBpjELMAkGA1UEBhMCR1Ix\nDzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5k\nIFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxQDA+BgNVBAMT\nN0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgUm9v\ndENBIDIwMTUwHhcNMTUwNzA3MTAxMTIxWhcNNDAwNjMwMTAxMTIxWjCBpjELMAkG\nA1UEBhMCR1IxDzANBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNh\nZGVtaWMgYW5kIFJlc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkx\nQDA+BgNVBAMTN0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1\ndGlvbnMgUm9vdENBIDIwMTUwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoIC\nAQDC+Kk/G4n8PDwEXT2QNrCROnk8ZlrvbTkBSRq0t89/TSNTt5AA4xMqKKYx8ZEA\n4yjsriFBzh/a/X0SWwGDD7mwX5nh8hKDgE0GPt+sr+ehiGsxr/CL0BgzuNtFajT0\nAoAkKAoCFZVedioNmToUW/bLy1O8E00BiDeUJRtCvCLYjqOWXjrZMts+6PAQZe10\n4S+nfK8nNLspfZu2zwnI5dMK/IhlZXQK3HMcXM1AsRzUtoSMTFDPaI6oWa7CJ06C\nojXdFPQf/7J31Ycvqm59JCfnxssm5uX+Zwdj2EUN3TpZZTlYepKZcj2chF6IIbjV\n9Cz82XBST3i4vTwri5WY9bPRaM8gFH5MXF/ni+X1NYEZN9cRCLdmvtNKzoNXADrD\ngfgXy5I2XdGj2HUb4Ysn6npIQf1FGQatJ5lOwXBH3bWfgVMS5bGMSF0xQxfjjMZ6\nY5ZLKTBOhE5iGV48zpeQpX8B653g+IuJ3SWYPZK2fu/Z8VFRfS0myGlZYeCsargq\nNhEEelC9MoS+L9xy1dcdFkfkR2YgP/SWxa+OAXqlD3pk9Q0Yh9muiNX6hME6wGko\nLfINaFGq46V3xqSQDqE3izEjR8EJCOtu93ib14L8hCCZSRm2Ekax+0VVFqmjZayc\nBw/qa9wfLgZy7IaIEuQt218FL+TwA9MmM+eAws1CoRc0CwIDAQABo0IwQDAPBgNV\nHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUcRVnyMjJvXVd\nctA4GGqd83EkVAswDQYJKoZIhvcNAQELBQADggIBAHW7bVRLqhBYRjTyYtcWNl0I\nXtVsyIe9tC5G8jH4fOpCtZMWVdyhDBKg2mF+D1hYc2Ryx+hFjtyp8iY/xnmMsVMI\nM4GwVhO+5lFc2JsKT0ucVlMC6U/2DWDqTUJV6HwbISHTGzrMd/K4kPFox/la/vot\n9L/J9UUbzjgQKjeKeaO04wlshYaT/4mWJ3iBj2fjRnRUjtkNaeJK9E10A/+yd+2V\nZ5fkscWrv2oj6NSU4kQoYsRL4vDY4ilrGnB+JGGTe08DMiUNRSQrlrRGar9KC/ea\nj8GsGsVn82800vpzY4zvFrCopEYq+OsS7HK07/grfoxSwIuEVPkvPuNVqNxmsdnh\nX9izjFk0WaSrT2y7HxjbdavYy5LNlDhhDgcGH0tGEPEVvo2FXDtKK4F5D7Rpn0lQ\nl033DlZdwJVqwjbDG2jJ9SrcR5q+ss7FJej6A7na+RZukYT1HCjI/CbM1xyQVqdf\nbzoEvM14iQuODy+jqk+iGxI9FghAD/FGTNeqewjBCvVtJ94Cj8rDtSvK6evIIVM4\npcw72Hc3MKJP2W/R8kCtQXoXxdZKNYm3QdV8hn9VTYNKpXMgwDqvkPGaJI7ZjnHK\ne7iG2rKPmT4dEw0SEe7Uq/DpFXYC5ODfqiAeW2GFZECpkJcNrVPSWh2HagCXZWK0\nvm9qp/UsQu0yrbYhnr68\n-----END CERTIFICATE-----\n\n# Issuer: CN=Hellenic Academic and Research Institutions ECC RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority\n# Subject: CN=Hellenic Academic and Research Institutions ECC RootCA 2015 O=Hellenic Academic and Research Institutions Cert. Authority\n# Label: \"Hellenic Academic and Research Institutions ECC RootCA 2015\"\n# Serial: 0\n# MD5 Fingerprint: 81:e5:b4:17:eb:c2:f5:e1:4b:0d:41:7b:49:92:fe:ef\n# SHA1 Fingerprint: 9f:f1:71:8d:92:d5:9a:f3:7d:74:97:b4:bc:6f:84:68:0b:ba:b6:66\n# SHA256 Fingerprint: 44:b5:45:aa:8a:25:e6:5a:73:ca:15:dc:27:fc:36:d2:4c:1c:b9:95:3a:06:65:39:b1:15:82:dc:48:7b:48:33\n-----BEGIN CERTIFICATE-----\nMIICwzCCAkqgAwIBAgIBADAKBggqhkjOPQQDAjCBqjELMAkGA1UEBhMCR1IxDzAN\nBgNVBAcTBkF0aGVuczFEMEIGA1UEChM7SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl\nc2VhcmNoIEluc3RpdHV0aW9ucyBDZXJ0LiBBdXRob3JpdHkxRDBCBgNVBAMTO0hl\nbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgRUNDIFJv\nb3RDQSAyMDE1MB4XDTE1MDcwNzEwMzcxMloXDTQwMDYzMDEwMzcxMlowgaoxCzAJ\nBgNVBAYTAkdSMQ8wDQYDVQQHEwZBdGhlbnMxRDBCBgNVBAoTO0hlbGxlbmljIEFj\nYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1dGlvbnMgQ2VydC4gQXV0aG9yaXR5\nMUQwQgYDVQQDEztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0\ndXRpb25zIEVDQyBSb290Q0EgMjAxNTB2MBAGByqGSM49AgEGBSuBBAAiA2IABJKg\nQehLgoRc4vgxEZmGZE4JJS+dQS8KrjVPdJWyUWRrjWvmP3CV8AVER6ZyOFB2lQJa\njq4onvktTpnvLEhvTCUp6NFxW98dwXU3tNf6e3pCnGoKVlp8aQuqgAkkbH7BRqNC\nMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFLQi\nC4KZJAEOnLvkDv2/+5cgk5kqMAoGCCqGSM49BAMCA2cAMGQCMGfOFmI4oqxiRaep\nlSTAGiecMjvAwNW6qef4BENThe5SId6d9SWDPp5YSy/XZxMOIQIwBeF1Ad5o7Sof\nTUwJCA3sS61kFyjndc5FZXIhF8siQQ6ME5g4mlRtm8rifOoCWCKR\n-----END CERTIFICATE-----\n\n# Issuer: CN=ISRG Root X1 O=Internet Security Research Group\n# Subject: CN=ISRG Root X1 O=Internet Security Research Group\n# Label: \"ISRG Root X1\"\n# Serial: 172886928669790476064670243504169061120\n# MD5 Fingerprint: 0c:d2:f9:e0:da:17:73:e9:ed:86:4d:a5:e3:70:e7:4e\n# SHA1 Fingerprint: ca:bd:2a:79:a1:07:6a:31:f2:1d:25:36:35:cb:03:9d:43:29:a5:e8\n# SHA256 Fingerprint: 96:bc:ec:06:26:49:76:f3:74:60:77:9a:cf:28:c5:a7:cf:e8:a3:c0:aa:e1:1a:8f:fc:ee:05:c0:bd:df:08:c6\n-----BEGIN CERTIFICATE-----\nMIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\nTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\ncmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\nWhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\nZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\nMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\nh77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\nA5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\nT8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\nB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\nB5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\nKBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\nOlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\njh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\nqHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\nrU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\nHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\nhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\nubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\nNFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\nORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\nTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\njNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\noyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\nmRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\nemyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n-----END CERTIFICATE-----\n\n# Issuer: O=FNMT-RCM OU=AC RAIZ FNMT-RCM\n# Subject: O=FNMT-RCM OU=AC RAIZ FNMT-RCM\n# Label: \"AC RAIZ FNMT-RCM\"\n# Serial: 485876308206448804701554682760554759\n# MD5 Fingerprint: e2:09:04:b4:d3:bd:d1:a0:14:fd:1a:d2:47:c4:57:1d\n# SHA1 Fingerprint: ec:50:35:07:b2:15:c4:95:62:19:e2:a8:9a:5b:42:99:2c:4c:2c:20\n# SHA256 Fingerprint: eb:c5:57:0c:29:01:8c:4d:67:b1:aa:12:7b:af:12:f7:03:b4:61:1e:bc:17:b7:da:b5:57:38:94:17:9b:93:fa\n-----BEGIN CERTIFICATE-----\nMIIFgzCCA2ugAwIBAgIPXZONMGc2yAYdGsdUhGkHMA0GCSqGSIb3DQEBCwUAMDsx\nCzAJBgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJ\nWiBGTk1ULVJDTTAeFw0wODEwMjkxNTU5NTZaFw0zMDAxMDEwMDAwMDBaMDsxCzAJ\nBgNVBAYTAkVTMREwDwYDVQQKDAhGTk1ULVJDTTEZMBcGA1UECwwQQUMgUkFJWiBG\nTk1ULVJDTTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALpxgHpMhm5/\nyBNtwMZ9HACXjywMI7sQmkCpGreHiPibVmr75nuOi5KOpyVdWRHbNi63URcfqQgf\nBBckWKo3Shjf5TnUV/3XwSyRAZHiItQDwFj8d0fsjz50Q7qsNI1NOHZnjrDIbzAz\nWHFctPVrbtQBULgTfmxKo0nRIBnuvMApGGWn3v7v3QqQIecaZ5JCEJhfTzC8PhxF\ntBDXaEAUwED653cXeuYLj2VbPNmaUtu1vZ5Gzz3rkQUCwJaydkxNEJY7kvqcfw+Z\n374jNUUeAlz+taibmSXaXvMiwzn15Cou08YfxGyqxRxqAQVKL9LFwag0Jl1mpdIC\nIfkYtwb1TplvqKtMUejPUBjFd8g5CSxJkjKZqLsXF3mwWsXmo8RZZUc1g16p6DUL\nmbvkzSDGm0oGObVo/CK67lWMK07q87Hj/LaZmtVC+nFNCM+HHmpxffnTtOmlcYF7\nwk5HlqX2doWjKI/pgG6BU6VtX7hI+cL5NqYuSf+4lsKMB7ObiFj86xsc3i1w4peS\nMKGJ47xVqCfWS+2QrYv6YyVZLag13cqXM7zlzced0ezvXg5KkAYmY6252TUtB7p2\nZSysV4999AeU14ECll2jB0nVetBX+RvnU0Z1qrB5QstocQjpYL05ac70r8NWQMet\nUqIJ5G+GR4of6ygnXYMgrwTJbFaai0b1AgMBAAGjgYMwgYAwDwYDVR0TAQH/BAUw\nAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYEFPd9xf3E6Jobd2Sn9R2gzL+H\nYJptMD4GA1UdIAQ3MDUwMwYEVR0gADArMCkGCCsGAQUFBwIBFh1odHRwOi8vd3d3\nLmNlcnQuZm5tdC5lcy9kcGNzLzANBgkqhkiG9w0BAQsFAAOCAgEAB5BK3/MjTvDD\nnFFlm5wioooMhfNzKWtN/gHiqQxjAb8EZ6WdmF/9ARP67Jpi6Yb+tmLSbkyU+8B1\nRXxlDPiyN8+sD8+Nb/kZ94/sHvJwnvDKuO+3/3Y3dlv2bojzr2IyIpMNOmqOFGYM\nLVN0V2Ue1bLdI4E7pWYjJ2cJj+F3qkPNZVEI7VFY/uY5+ctHhKQV8Xa7pO6kO8Rf\n77IzlhEYt8llvhjho6Tc+hj507wTmzl6NLrTQfv6MooqtyuGC2mDOL7Nii4LcK2N\nJpLuHvUBKwrZ1pebbuCoGRw6IYsMHkCtA+fdZn71uSANA+iW+YJF1DngoABd15jm\nfZ5nc8OaKveri6E6FO80vFIOiZiaBECEHX5FaZNXzuvO+FB8TxxuBEOb+dY7Ixjp\n6o7RTUaN8Tvkasq6+yO3m/qZASlaWFot4/nUbQ4mrcFuNLwy+AwF+mWj2zs3gyLp\n1txyM/1d8iC9djwj2ij3+RvrWWTV3F9yfiD8zYm1kGdNYno/Tq0dwzn+evQoFt9B\n9kiABdcPUXmsEKvU7ANm5mqwujGSQkBqvjrTcuFqN1W8rB2Vt2lh8kORdOag0wok\nRqEIr9baRRmW1FMdW4R58MD3R++Lj8UGrp1MYp3/RgT408m2ECVAdf4WqslKYIYv\nuu8wd+RU4riEmViAqhOLUTpPSPaLtrM=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Amazon Root CA 1 O=Amazon\n# Subject: CN=Amazon Root CA 1 O=Amazon\n# Label: \"Amazon Root CA 1\"\n# Serial: 143266978916655856878034712317230054538369994\n# MD5 Fingerprint: 43:c6:bf:ae:ec:fe:ad:2f:18:c6:88:68:30:fc:c8:e6\n# SHA1 Fingerprint: 8d:a7:f9:65:ec:5e:fc:37:91:0f:1c:6e:59:fd:c1:cc:6a:6e:de:16\n# SHA256 Fingerprint: 8e:cd:e6:88:4f:3d:87:b1:12:5b:a3:1a:c3:fc:b1:3d:70:16:de:7f:57:cc:90:4f:e1:cb:97:c6:ae:98:19:6e\n-----BEGIN CERTIFICATE-----\nMIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\nADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\nb24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\nMAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\nb3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\nca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\nIFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\nVOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\njgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\nAYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\nA4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\nU5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\nN+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\no/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\nrqXRfboQnoZsG4q5WTP468SQvvG5\n-----END CERTIFICATE-----\n\n# Issuer: CN=Amazon Root CA 2 O=Amazon\n# Subject: CN=Amazon Root CA 2 O=Amazon\n# Label: \"Amazon Root CA 2\"\n# Serial: 143266982885963551818349160658925006970653239\n# MD5 Fingerprint: c8:e5:8d:ce:a8:42:e2:7a:c0:2a:5c:7c:9e:26:bf:66\n# SHA1 Fingerprint: 5a:8c:ef:45:d7:a6:98:59:76:7a:8c:8b:44:96:b5:78:cf:47:4b:1a\n# SHA256 Fingerprint: 1b:a5:b2:aa:8c:65:40:1a:82:96:01:18:f8:0b:ec:4f:62:30:4d:83:ce:c4:71:3a:19:c3:9c:01:1e:a4:6d:b4\n-----BEGIN CERTIFICATE-----\nMIIFQTCCAymgAwIBAgITBmyf0pY1hp8KD+WGePhbJruKNzANBgkqhkiG9w0BAQwF\nADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\nb24gUm9vdCBDQSAyMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTEL\nMAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\nb3QgQ0EgMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK2Wny2cSkxK\ngXlRmeyKy2tgURO8TW0G/LAIjd0ZEGrHJgw12MBvIITplLGbhQPDW9tK6Mj4kHbZ\nW0/jTOgGNk3Mmqw9DJArktQGGWCsN0R5hYGCrVo34A3MnaZMUnbqQ523BNFQ9lXg\n1dKmSYXpN+nKfq5clU1Imj+uIFptiJXZNLhSGkOQsL9sBbm2eLfq0OQ6PBJTYv9K\n8nu+NQWpEjTj82R0Yiw9AElaKP4yRLuH3WUnAnE72kr3H9rN9yFVkE8P7K6C4Z9r\n2UXTu/Bfh+08LDmG2j/e7HJV63mjrdvdfLC6HM783k81ds8P+HgfajZRRidhW+me\nz/CiVX18JYpvL7TFz4QuK/0NURBs+18bvBt+xa47mAExkv8LV/SasrlX6avvDXbR\n8O70zoan4G7ptGmh32n2M8ZpLpcTnqWHsFcQgTfJU7O7f/aS0ZzQGPSSbtqDT6Zj\nmUyl+17vIWR6IF9sZIUVyzfpYgwLKhbcAS4y2j5L9Z469hdAlO+ekQiG+r5jqFoz\n7Mt0Q5X5bGlSNscpb/xVA1wf+5+9R+vnSUeVC06JIglJ4PVhHvG/LopyboBZ/1c6\n+XUyo05f7O0oYtlNc/LMgRdg7c3r3NunysV+Ar3yVAhU/bQtCSwXVEqY0VThUWcI\n0u1ufm8/0i2BWSlmy5A5lREedCf+3euvAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMB\nAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSwDPBMMPQFWAJI/TPlUq9LhONm\nUjANBgkqhkiG9w0BAQwFAAOCAgEAqqiAjw54o+Ci1M3m9Zh6O+oAA7CXDpO8Wqj2\nLIxyh6mx/H9z/WNxeKWHWc8w4Q0QshNabYL1auaAn6AFC2jkR2vHat+2/XcycuUY\n+gn0oJMsXdKMdYV2ZZAMA3m3MSNjrXiDCYZohMr/+c8mmpJ5581LxedhpxfL86kS\nk5Nrp+gvU5LEYFiwzAJRGFuFjWJZY7attN6a+yb3ACfAXVU3dJnJUH/jWS5E4ywl\n7uxMMne0nxrpS10gxdr9HIcWxkPo1LsmmkVwXqkLN1PiRnsn/eBG8om3zEK2yygm\nbtmlyTrIQRNg91CMFa6ybRoVGld45pIq2WWQgj9sAq+uEjonljYE1x2igGOpm/Hl\nurR8FLBOybEfdF849lHqm/osohHUqS0nGkWxr7JOcQ3AWEbWaQbLU8uz/mtBzUF+\nfUwPfHJ5elnNXkoOrJupmHN5fLT0zLm4BwyydFy4x2+IoZCn9Kr5v2c69BoVYh63\nn749sSmvZ6ES8lgQGVMDMBu4Gon2nL2XA46jCfMdiyHxtN/kHNGfZQIG6lzWE7OE\n76KlXIx3KadowGuuQNKotOrN8I1LOJwZmhsoVLiJkO/KdYE+HvJkJMcYr07/R54H\n9jVlpNMKVv/1F2Rs76giJUmTtt8AF9pYfl3uxRuw0dFfIRDH+fO6AgonB8Xx1sfT\n4PsJYGw=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Amazon Root CA 3 O=Amazon\n# Subject: CN=Amazon Root CA 3 O=Amazon\n# Label: \"Amazon Root CA 3\"\n# Serial: 143266986699090766294700635381230934788665930\n# MD5 Fingerprint: a0:d4:ef:0b:f7:b5:d8:49:95:2a:ec:f5:c4:fc:81:87\n# SHA1 Fingerprint: 0d:44:dd:8c:3c:8c:1a:1a:58:75:64:81:e9:0f:2e:2a:ff:b3:d2:6e\n# SHA256 Fingerprint: 18:ce:6c:fe:7b:f1:4e:60:b2:e3:47:b8:df:e8:68:cb:31:d0:2e:bb:3a:da:27:15:69:f5:03:43:b4:6d:b3:a4\n-----BEGIN CERTIFICATE-----\nMIIBtjCCAVugAwIBAgITBmyf1XSXNmY/Owua2eiedgPySjAKBggqhkjOPQQDAjA5\nMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g\nUm9vdCBDQSAzMB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG\nA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg\nQ0EgMzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABCmXp8ZBf8ANm+gBG1bG8lKl\nui2yEujSLtf6ycXYqm0fc4E7O5hrOXwzpcVOho6AF2hiRVd9RFgdszflZwjrZt6j\nQjBAMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMB0GA1UdDgQWBBSr\nttvXBp43rDCGB5Fwx5zEGbF4wDAKBggqhkjOPQQDAgNJADBGAiEA4IWSoxe3jfkr\nBqWTrBqYaGFy+uGh0PsceGCmQ5nFuMQCIQCcAu/xlJyzlvnrxir4tiz+OpAUFteM\nYyRIHN8wfdVoOw==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Amazon Root CA 4 O=Amazon\n# Subject: CN=Amazon Root CA 4 O=Amazon\n# Label: \"Amazon Root CA 4\"\n# Serial: 143266989758080763974105200630763877849284878\n# MD5 Fingerprint: 89:bc:27:d5:eb:17:8d:06:6a:69:d5:fd:89:47:b4:cd\n# SHA1 Fingerprint: f6:10:84:07:d6:f8:bb:67:98:0c:c2:e2:44:c2:eb:ae:1c:ef:63:be\n# SHA256 Fingerprint: e3:5d:28:41:9e:d0:20:25:cf:a6:90:38:cd:62:39:62:45:8d:a5:c6:95:fb:de:a3:c2:2b:0b:fb:25:89:70:92\n-----BEGIN CERTIFICATE-----\nMIIB8jCCAXigAwIBAgITBmyf18G7EEwpQ+Vxe3ssyBrBDjAKBggqhkjOPQQDAzA5\nMQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6b24g\nUm9vdCBDQSA0MB4XDTE1MDUyNjAwMDAwMFoXDTQwMDUyNjAwMDAwMFowOTELMAkG\nA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJvb3Qg\nQ0EgNDB2MBAGByqGSM49AgEGBSuBBAAiA2IABNKrijdPo1MN/sGKe0uoe0ZLY7Bi\n9i0b2whxIdIA6GO9mif78DluXeo9pcmBqqNbIJhFXRbb/egQbeOc4OO9X4Ri83Bk\nM6DLJC9wuoihKqB1+IGuYgbEgds5bimwHvouXKNCMEAwDwYDVR0TAQH/BAUwAwEB\n/zAOBgNVHQ8BAf8EBAMCAYYwHQYDVR0OBBYEFNPsxzplbszh2naaVvuc84ZtV+WB\nMAoGCCqGSM49BAMDA2gAMGUCMDqLIfG9fhGt0O9Yli/W651+kI0rz2ZVwyzjKKlw\nCkcO8DdZEv8tmZQoTipPNU0zWgIxAOp1AE47xDqUEpHJWEadIRNyp4iciuRMStuW\n1KyLa2tJElMzrdfkviT8tQp21KW8EA==\n-----END CERTIFICATE-----\n\n# Issuer: CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK OU=Kamu Sertifikasyon Merkezi - Kamu SM\n# Subject: CN=TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1 O=Turkiye Bilimsel ve Teknolojik Arastirma Kurumu - TUBITAK OU=Kamu Sertifikasyon Merkezi - Kamu SM\n# Label: \"TUBITAK Kamu SM SSL Kok Sertifikasi - Surum 1\"\n# Serial: 1\n# MD5 Fingerprint: dc:00:81:dc:69:2f:3e:2f:b0:3b:f6:3d:5a:91:8e:49\n# SHA1 Fingerprint: 31:43:64:9b:ec:ce:27:ec:ed:3a:3f:0b:8f:0d:e4:e8:91:dd:ee:ca\n# SHA256 Fingerprint: 46:ed:c3:68:90:46:d5:3a:45:3f:b3:10:4a:b8:0d:ca:ec:65:8b:26:60:ea:16:29:dd:7e:86:79:90:64:87:16\n-----BEGIN CERTIFICATE-----\nMIIEYzCCA0ugAwIBAgIBATANBgkqhkiG9w0BAQsFADCB0jELMAkGA1UEBhMCVFIx\nGDAWBgNVBAcTD0dlYnplIC0gS29jYWVsaTFCMEAGA1UEChM5VHVya2l5ZSBCaWxp\nbXNlbCB2ZSBUZWtub2xvamlrIEFyYXN0aXJtYSBLdXJ1bXUgLSBUVUJJVEFLMS0w\nKwYDVQQLEyRLYW11IFNlcnRpZmlrYXN5b24gTWVya2V6aSAtIEthbXUgU00xNjA0\nBgNVBAMTLVRVQklUQUsgS2FtdSBTTSBTU0wgS29rIFNlcnRpZmlrYXNpIC0gU3Vy\ndW0gMTAeFw0xMzExMjUwODI1NTVaFw00MzEwMjUwODI1NTVaMIHSMQswCQYDVQQG\nEwJUUjEYMBYGA1UEBxMPR2ViemUgLSBLb2NhZWxpMUIwQAYDVQQKEzlUdXJraXll\nIEJpbGltc2VsIHZlIFRla25vbG9qaWsgQXJhc3Rpcm1hIEt1cnVtdSAtIFRVQklU\nQUsxLTArBgNVBAsTJEthbXUgU2VydGlmaWthc3lvbiBNZXJrZXppIC0gS2FtdSBT\nTTE2MDQGA1UEAxMtVFVCSVRBSyBLYW11IFNNIFNTTCBLb2sgU2VydGlmaWthc2kg\nLSBTdXJ1bSAxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr3UwM6q7\na9OZLBI3hNmNe5eA027n/5tQlT6QlVZC1xl8JoSNkvoBHToP4mQ4t4y86Ij5iySr\nLqP1N+RAjhgleYN1Hzv/bKjFxlb4tO2KRKOrbEz8HdDc72i9z+SqzvBV96I01INr\nN3wcwv61A+xXzry0tcXtAA9TNypN9E8Mg/uGz8v+jE69h/mniyFXnHrfA2eJLJ2X\nYacQuFWQfw4tJzh03+f92k4S400VIgLI4OD8D62K18lUUMw7D8oWgITQUVbDjlZ/\niSIzL+aFCr2lqBs23tPcLG07xxO9WSMs5uWk99gL7eqQQESolbuT1dCANLZGeA4f\nAJNG4e7p+exPFwIDAQABo0IwQDAdBgNVHQ4EFgQUZT/HiobGPN08VFw1+DrtUgxH\nV8gwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL\nBQADggEBACo/4fEyjq7hmFxLXs9rHmoJ0iKpEsdeV31zVmSAhHqT5Am5EM2fKifh\nAHe+SMg1qIGf5LgsyX8OsNJLN13qudULXjS99HMpw+0mFZx+CFOKWI3QSyjfwbPf\nIPP54+M638yclNhOT8NrF7f3cuitZjO1JVOr4PhMqZ398g26rrnZqsZr+ZO7rqu4\nlzwDGrpDxpa5RXI4s6ehlj2Re37AIVNMh+3yC1SVUZPVIqUNivGTDj5UDrDYyU7c\n8jEyVupk+eq1nRZmQnLzf9OxMUP8pI4X8W0jq5Rm+K37DwhuJi1/FwcJsoz7UMCf\nlo3Ptv0AnVoUmr8CRPXBwp8iXqIPoeM=\n-----END CERTIFICATE-----\n\n# Issuer: CN=GDCA TrustAUTH R5 ROOT O=GUANG DONG CERTIFICATE AUTHORITY CO.,LTD.\n# Subject: CN=GDCA TrustAUTH R5 ROOT O=GUANG DONG CERTIFICATE AUTHORITY CO.,LTD.\n# Label: \"GDCA TrustAUTH R5 ROOT\"\n# Serial: 9009899650740120186\n# MD5 Fingerprint: 63:cc:d9:3d:34:35:5c:6f:53:a3:e2:08:70:48:1f:b4\n# SHA1 Fingerprint: 0f:36:38:5b:81:1a:25:c3:9b:31:4e:83:ca:e9:34:66:70:cc:74:b4\n# SHA256 Fingerprint: bf:ff:8f:d0:44:33:48:7d:6a:8a:a6:0c:1a:29:76:7a:9f:c2:bb:b0:5e:42:0f:71:3a:13:b9:92:89:1d:38:93\n-----BEGIN CERTIFICATE-----\nMIIFiDCCA3CgAwIBAgIIfQmX/vBH6nowDQYJKoZIhvcNAQELBQAwYjELMAkGA1UE\nBhMCQ04xMjAwBgNVBAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZ\nIENPLixMVEQuMR8wHQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMB4XDTE0\nMTEyNjA1MTMxNVoXDTQwMTIzMTE1NTk1OVowYjELMAkGA1UEBhMCQ04xMjAwBgNV\nBAoMKUdVQU5HIERPTkcgQ0VSVElGSUNBVEUgQVVUSE9SSVRZIENPLixMVEQuMR8w\nHQYDVQQDDBZHRENBIFRydXN0QVVUSCBSNSBST09UMIICIjANBgkqhkiG9w0BAQEF\nAAOCAg8AMIICCgKCAgEA2aMW8Mh0dHeb7zMNOwZ+Vfy1YI92hhJCfVZmPoiC7XJj\nDp6L3TQsAlFRwxn9WVSEyfFrs0yw6ehGXTjGoqcuEVe6ghWinI9tsJlKCvLriXBj\nTnnEt1u9ol2x8kECK62pOqPseQrsXzrj/e+APK00mxqriCZ7VqKChh/rNYmDf1+u\nKU49tm7srsHwJ5uu4/Ts765/94Y9cnrrpftZTqfrlYwiOXnhLQiPzLyRuEH3FMEj\nqcOtmkVEs7LXLM3GKeJQEK5cy4KOFxg2fZfmiJqwTTQJ9Cy5WmYqsBebnh52nUpm\nMUHfP/vFBu8btn4aRjb3ZGM74zkYI+dndRTVdVeSN72+ahsmUPI2JgaQxXABZG12\nZuGR224HwGGALrIuL4xwp9E7PLOR5G62xDtw8mySlwnNR30YwPO7ng/Wi64HtloP\nzgsMR6flPri9fcebNaBhlzpBdRfMK5Z3KpIhHtmVdiBnaM8Nvd/WHwlqmuLMc3Gk\nL30SgLdTMEZeS1SZD2fJpcjyIMGC7J0R38IC+xo70e0gmu9lZJIQDSri3nDxGGeC\njGHeuLzRL5z7D9Ar7Rt2ueQ5Vfj4oR24qoAATILnsn8JuLwwoC8N9VKejveSswoA\nHQBUlwbgsQfZxw9cZX08bVlX5O2ljelAU58VS6Bx9hoh49pwBiFYFIeFd3mqgnkC\nAwEAAaNCMEAwHQYDVR0OBBYEFOLJQJ9NzuiaoXzPDj9lxSmIahlRMA8GA1UdEwEB\n/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQDRSVfg\np8xoWLoBDysZzY2wYUWsEe1jUGn4H3++Fo/9nesLqjJHdtJnJO29fDMylyrHBYZm\nDRd9FBUb1Ov9H5r2XpdptxolpAqzkT9fNqyL7FeoPueBihhXOYV0GkLH6VsTX4/5\nCOmSdI31R9KrO9b7eGZONn356ZLpBN79SWP8bfsUcZNnL0dKt7n/HipzcEYwv1ry\nL3ml4Y0M2fmyYzeMN2WFcGpcWwlyua1jPLHd+PwyvzeG5LuOmCd+uh8W4XAR8gPf\nJWIyJyYYMoSf/wA6E7qaTfRPuBRwIrHKK5DOKcFw9C+df/KQHtZa37dG/OaG+svg\nIHZ6uqbL9XzeYqWxi+7egmaKTjowHz+Ay60nugxe19CxVsp3cbK1daFQqUBDF8Io\n2c9Si1vIY9RCPqAzekYu9wogRlR+ak8x8YF+QnQ4ZXMn7sZ8uI7XpTrXmKGcjBBV\n09tL7ECQ8s1uV9JiDnxXk7Gnbc2dg7sq5+W2O3FYrf3RRbxake5TFW/TRQl1brqQ\nXR4EzzffHqhmsYzmIGrv/EhOdJhCrylvLmrH+33RZjEizIYAfmaDDEL0vTSSwxrq\nT8p+ck0LcIymSLumoRT2+1hEmRSuqguTaaApJUqlyyvdimYHFngVV3Eb7PVHhPOe\nMTd61X8kreS8/f3MboPoDKi3QWwH3b08hpcv0g==\n-----END CERTIFICATE-----\n\n# Issuer: CN=TrustCor RootCert CA-1 O=TrustCor Systems S. de R.L. OU=TrustCor Certificate Authority\n# Subject: CN=TrustCor RootCert CA-1 O=TrustCor Systems S. de R.L. OU=TrustCor Certificate Authority\n# Label: \"TrustCor RootCert CA-1\"\n# Serial: 15752444095811006489\n# MD5 Fingerprint: 6e:85:f1:dc:1a:00:d3:22:d5:b2:b2:ac:6b:37:05:45\n# SHA1 Fingerprint: ff:bd:cd:e7:82:c8:43:5e:3c:6f:26:86:5c:ca:a8:3a:45:5b:c3:0a\n# SHA256 Fingerprint: d4:0e:9c:86:cd:8f:e4:68:c1:77:69:59:f4:9e:a7:74:fa:54:86:84:b6:c4:06:f3:90:92:61:f4:dc:e2:57:5c\n-----BEGIN CERTIFICATE-----\nMIIEMDCCAxigAwIBAgIJANqb7HHzA7AZMA0GCSqGSIb3DQEBCwUAMIGkMQswCQYD\nVQQGEwJQQTEPMA0GA1UECAwGUGFuYW1hMRQwEgYDVQQHDAtQYW5hbWEgQ2l0eTEk\nMCIGA1UECgwbVHJ1c3RDb3IgU3lzdGVtcyBTLiBkZSBSLkwuMScwJQYDVQQLDB5U\ncnVzdENvciBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkxHzAdBgNVBAMMFlRydXN0Q29y\nIFJvb3RDZXJ0IENBLTEwHhcNMTYwMjA0MTIzMjE2WhcNMjkxMjMxMTcyMzE2WjCB\npDELMAkGA1UEBhMCUEExDzANBgNVBAgMBlBhbmFtYTEUMBIGA1UEBwwLUGFuYW1h\nIENpdHkxJDAiBgNVBAoMG1RydXN0Q29yIFN5c3RlbXMgUy4gZGUgUi5MLjEnMCUG\nA1UECwweVHJ1c3RDb3IgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MR8wHQYDVQQDDBZU\ncnVzdENvciBSb290Q2VydCBDQS0xMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\nCgKCAQEAv463leLCJhJrMxnHQFgKq1mqjQCj/IDHUHuO1CAmujIS2CNUSSUQIpid\nRtLByZ5OGy4sDjjzGiVoHKZaBeYei0i/mJZ0PmnK6bV4pQa81QBeCQryJ3pS/C3V\nseq0iWEk8xoT26nPUu0MJLq5nux+AHT6k61sKZKuUbS701e/s/OojZz0JEsq1pme\n9J7+wH5COucLlVPat2gOkEz7cD+PSiyU8ybdY2mplNgQTsVHCJCZGxdNuWxu72CV\nEY4hgLW9oHPY0LJ3xEXqWib7ZnZ2+AYfYW0PVcWDtxBWcgYHpfOxGgMFZA6dWorW\nhnAbJN7+KIor0Gqw/Hqi3LJ5DotlDwIDAQABo2MwYTAdBgNVHQ4EFgQU7mtJPHo/\nDeOxCbeKyKsZn3MzUOcwHwYDVR0jBBgwFoAU7mtJPHo/DeOxCbeKyKsZn3MzUOcw\nDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQAD\nggEBACUY1JGPE+6PHh0RU9otRCkZoB5rMZ5NDp6tPVxBb5UrJKF5mDo4Nvu7Zp5I\n/5CQ7z3UuJu0h3U/IJvOcs+hVcFNZKIZBqEHMwwLKeXx6quj7LUKdJDHfXLy11yf\nke+Ri7fc7Waiz45mO7yfOgLgJ90WmMCV1Aqk5IGadZQ1nJBfiDcGrVmVCrDRZ9MZ\nyonnMlo2HD6CqFqTvsbQZJG2z9m2GM/bftJlo6bEjhcxwft+dtvTheNYsnd6djts\nL1Ac59v2Z3kf9YKVmgenFK+P3CghZwnS1k1aHBkcjndcw5QkPTJrS37UeJSDvjdN\nzl/HHk484IkzlQsPpTLWPFp5LBk=\n-----END CERTIFICATE-----\n\n# Issuer: CN=TrustCor RootCert CA-2 O=TrustCor Systems S. de R.L. OU=TrustCor Certificate Authority\n# Subject: CN=TrustCor RootCert CA-2 O=TrustCor Systems S. de R.L. OU=TrustCor Certificate Authority\n# Label: \"TrustCor RootCert CA-2\"\n# Serial: 2711694510199101698\n# MD5 Fingerprint: a2:e1:f8:18:0b:ba:45:d5:c7:41:2a:bb:37:52:45:64\n# SHA1 Fingerprint: b8:be:6d:cb:56:f1:55:b9:63:d4:12:ca:4e:06:34:c7:94:b2:1c:c0\n# SHA256 Fingerprint: 07:53:e9:40:37:8c:1b:d5:e3:83:6e:39:5d:ae:a5:cb:83:9e:50:46:f1:bd:0e:ae:19:51:cf:10:fe:c7:c9:65\n-----BEGIN CERTIFICATE-----\nMIIGLzCCBBegAwIBAgIIJaHfyjPLWQIwDQYJKoZIhvcNAQELBQAwgaQxCzAJBgNV\nBAYTAlBBMQ8wDQYDVQQIDAZQYW5hbWExFDASBgNVBAcMC1BhbmFtYSBDaXR5MSQw\nIgYDVQQKDBtUcnVzdENvciBTeXN0ZW1zIFMuIGRlIFIuTC4xJzAlBgNVBAsMHlRy\ndXN0Q29yIENlcnRpZmljYXRlIEF1dGhvcml0eTEfMB0GA1UEAwwWVHJ1c3RDb3Ig\nUm9vdENlcnQgQ0EtMjAeFw0xNjAyMDQxMjMyMjNaFw0zNDEyMzExNzI2MzlaMIGk\nMQswCQYDVQQGEwJQQTEPMA0GA1UECAwGUGFuYW1hMRQwEgYDVQQHDAtQYW5hbWEg\nQ2l0eTEkMCIGA1UECgwbVHJ1c3RDb3IgU3lzdGVtcyBTLiBkZSBSLkwuMScwJQYD\nVQQLDB5UcnVzdENvciBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkxHzAdBgNVBAMMFlRy\ndXN0Q29yIFJvb3RDZXJ0IENBLTIwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK\nAoICAQCnIG7CKqJiJJWQdsg4foDSq8GbZQWU9MEKENUCrO2fk8eHyLAnK0IMPQo+\nQVqedd2NyuCb7GgypGmSaIwLgQ5WoD4a3SwlFIIvl9NkRvRUqdw6VC0xK5mC8tkq\n1+9xALgxpL56JAfDQiDyitSSBBtlVkxs1Pu2YVpHI7TYabS3OtB0PAx1oYxOdqHp\n2yqlO/rOsP9+aij9JxzIsekp8VduZLTQwRVtDr4uDkbIXvRR/u8OYzo7cbrPb1nK\nDOObXUm4TOJXsZiKQlecdu/vvdFoqNL0Cbt3Nb4lggjEFixEIFapRBF37120Hape\naz6LMvYHL1cEksr1/p3C6eizjkxLAjHZ5DxIgif3GIJ2SDpxsROhOdUuxTTCHWKF\n3wP+TfSvPd9cW436cOGlfifHhi5qjxLGhF5DUVCcGZt45vz27Ud+ez1m7xMTiF88\noWP7+ayHNZ/zgp6kPwqcMWmLmaSISo5uZk3vFsQPeSghYA2FFn3XVDjxklb9tTNM\ng9zXEJ9L/cb4Qr26fHMC4P99zVvh1Kxhe1fVSntb1IVYJ12/+CtgrKAmrhQhJ8Z3\nmjOAPF5GP/fDsaOGM8boXg25NSyqRsGFAnWAoOsk+xWq5Gd/bnc/9ASKL3x74xdh\n8N0JqSDIvgmk0H5Ew7IwSjiqqewYmgeCK9u4nBit2uBGF6zPXQIDAQABo2MwYTAd\nBgNVHQ4EFgQU2f4hQG6UnrybPZx9mCAZ5YwwYrIwHwYDVR0jBBgwFoAU2f4hQG6U\nnrybPZx9mCAZ5YwwYrIwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYw\nDQYJKoZIhvcNAQELBQADggIBAJ5Fngw7tu/hOsh80QA9z+LqBrWyOrsGS2h60COX\ndKcs8AjYeVrXWoSK2BKaG9l9XE1wxaX5q+WjiYndAfrs3fnpkpfbsEZC89NiqpX+\nMWcUaViQCqoL7jcjx1BRtPV+nuN79+TMQjItSQzL/0kMmx40/W5ulop5A7Zv2wnL\n/V9lFDfhOPXzYRZY5LVtDQsEGz9QLX+zx3oaFoBg+Iof6Rsqxvm6ARppv9JYx1RX\nCI/hOWB3S6xZhBqI8d3LT3jX5+EzLfzuQfogsL7L9ziUwOHQhQ+77Sxzq+3+knYa\nZH9bDTMJBzN7Bj8RpFxwPIXAz+OQqIN3+tvmxYxoZxBnpVIt8MSZj3+/0WvitUfW\n2dCFmU2Umw9Lje4AWkcdEQOsQRivh7dvDDqPys/cA8GiCcjl/YBeyGBCARsaU1q7\nN6a3vLqE6R5sGtRk2tRD/pOLS/IseRYQ1JMLiI+h2IYURpFHmygk71dSTlxCnKr3\nSewn6EAes6aJInKc9Q0ztFijMDvd1GpUk74aTfOTlPf8hAs/hCBcNANExdqtvArB\nAs8e5ZTZ845b2EzwnexhF7sUMlQMAimTHpKG9n/v55IFDlndmQguLvqcAFLTxWYp\n5KeXRKQOKIETNcX2b2TmQcTVL8w0RSXPQQCWPUouwpaYT05KnJe32x+SMsj/D1Fu\n1uwJ\n-----END CERTIFICATE-----\n\n# Issuer: CN=TrustCor ECA-1 O=TrustCor Systems S. de R.L. OU=TrustCor Certificate Authority\n# Subject: CN=TrustCor ECA-1 O=TrustCor Systems S. de R.L. OU=TrustCor Certificate Authority\n# Label: \"TrustCor ECA-1\"\n# Serial: 9548242946988625984\n# MD5 Fingerprint: 27:92:23:1d:0a:f5:40:7c:e9:e6:6b:9d:d8:f5:e7:6c\n# SHA1 Fingerprint: 58:d1:df:95:95:67:6b:63:c0:f0:5b:1c:17:4d:8b:84:0b:c8:78:bd\n# SHA256 Fingerprint: 5a:88:5d:b1:9c:01:d9:12:c5:75:93:88:93:8c:af:bb:df:03:1a:b2:d4:8e:91:ee:15:58:9b:42:97:1d:03:9c\n-----BEGIN CERTIFICATE-----\nMIIEIDCCAwigAwIBAgIJAISCLF8cYtBAMA0GCSqGSIb3DQEBCwUAMIGcMQswCQYD\nVQQGEwJQQTEPMA0GA1UECAwGUGFuYW1hMRQwEgYDVQQHDAtQYW5hbWEgQ2l0eTEk\nMCIGA1UECgwbVHJ1c3RDb3IgU3lzdGVtcyBTLiBkZSBSLkwuMScwJQYDVQQLDB5U\ncnVzdENvciBDZXJ0aWZpY2F0ZSBBdXRob3JpdHkxFzAVBgNVBAMMDlRydXN0Q29y\nIEVDQS0xMB4XDTE2MDIwNDEyMzIzM1oXDTI5MTIzMTE3MjgwN1owgZwxCzAJBgNV\nBAYTAlBBMQ8wDQYDVQQIDAZQYW5hbWExFDASBgNVBAcMC1BhbmFtYSBDaXR5MSQw\nIgYDVQQKDBtUcnVzdENvciBTeXN0ZW1zIFMuIGRlIFIuTC4xJzAlBgNVBAsMHlRy\ndXN0Q29yIENlcnRpZmljYXRlIEF1dGhvcml0eTEXMBUGA1UEAwwOVHJ1c3RDb3Ig\nRUNBLTEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDPj+ARtZ+odnbb\n3w9U73NjKYKtR8aja+3+XzP4Q1HpGjORMRegdMTUpwHmspI+ap3tDvl0mEDTPwOA\nBoJA6LHip1GnHYMma6ve+heRK9jGrB6xnhkB1Zem6g23xFUfJ3zSCNV2HykVh0A5\n3ThFEXXQmqc04L/NyFIduUd+Dbi7xgz2c1cWWn5DkR9VOsZtRASqnKmcp0yJF4Ou\nowReUoCLHhIlERnXDH19MURB6tuvsBzvgdAsxZohmz3tQjtQJvLsznFhBmIhVE5/\nwZ0+fyCMgMsq2JdiyIMzkX2woloPV+g7zPIlstR8L+xNxqE6FXrntl019fZISjZF\nZtS6mFjBAgMBAAGjYzBhMB0GA1UdDgQWBBREnkj1zG1I1KBLf/5ZJC+Dl5mahjAf\nBgNVHSMEGDAWgBREnkj1zG1I1KBLf/5ZJC+Dl5mahjAPBgNVHRMBAf8EBTADAQH/\nMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAQEABT41XBVwm8nHc2Fv\ncivUwo/yQ10CzsSUuZQRg2dd4mdsdXa/uwyqNsatR5Nj3B5+1t4u/ukZMjgDfxT2\nAHMsWbEhBuH7rBiVDKP/mZb3Kyeb1STMHd3BOuCYRLDE5D53sXOpZCz2HAF8P11F\nhcCF5yWPldwX8zyfGm6wyuMdKulMY/okYWLW2n62HGz1Ah3UKt1VkOsqEUc8Ll50\nsoIipX1TH0XsJ5F95yIW6MBoNtjG8U+ARDL54dHRHareqKucBK+tIA5kmE2la8BI\nWJZpTdwHjFGTot+fDz2LYLSCjaoITmJF4PkL0uDgPFveXHEnJcLmA4GLEFPjx1Wi\ntJ/X5g==\n-----END CERTIFICATE-----\n\n# Issuer: CN=SSL.com Root Certification Authority RSA O=SSL Corporation\n# Subject: CN=SSL.com Root Certification Authority RSA O=SSL Corporation\n# Label: \"SSL.com Root Certification Authority RSA\"\n# Serial: 8875640296558310041\n# MD5 Fingerprint: 86:69:12:c0:70:f1:ec:ac:ac:c2:d5:bc:a5:5b:a1:29\n# SHA1 Fingerprint: b7:ab:33:08:d1:ea:44:77:ba:14:80:12:5a:6f:bd:a9:36:49:0c:bb\n# SHA256 Fingerprint: 85:66:6a:56:2e:e0:be:5c:e9:25:c1:d8:89:0a:6f:76:a8:7e:c1:6d:4d:7d:5f:29:ea:74:19:cf:20:12:3b:69\n-----BEGIN CERTIFICATE-----\nMIIF3TCCA8WgAwIBAgIIeyyb0xaAMpkwDQYJKoZIhvcNAQELBQAwfDELMAkGA1UE\nBhMCVVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQK\nDA9TU0wgQ29ycG9yYXRpb24xMTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZp\nY2F0aW9uIEF1dGhvcml0eSBSU0EwHhcNMTYwMjEyMTczOTM5WhcNNDEwMjEyMTcz\nOTM5WjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hv\ndXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNv\nbSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFJTQTCCAiIwDQYJKoZIhvcN\nAQEBBQADggIPADCCAgoCggIBAPkP3aMrfcvQKv7sZ4Wm5y4bunfh4/WvpOz6Sl2R\nxFdHaxh3a3by/ZPkPQ/CFp4LZsNWlJ4Xg4XOVu/yFv0AYvUiCVToZRdOQbngT0aX\nqhvIuG5iXmmxX9sqAn78bMrzQdjt0Oj8P2FI7bADFB0QDksZ4LtO7IZl/zbzXmcC\nC52GVWH9ejjt/uIZALdvoVBidXQ8oPrIJZK0bnoix/geoeOy3ZExqysdBP+lSgQ3\n6YWkMyv94tZVNHwZpEpox7Ko07fKoZOI68GXvIz5HdkihCR0xwQ9aqkpk8zruFvh\n/l8lqjRYyMEjVJ0bmBHDOJx+PYZspQ9AhnwC9FwCTyjLrnGfDzrIM/4RJTXq/LrF\nYD3ZfBjVsqnTdXgDciLKOsMf7yzlLqn6niy2UUb9rwPW6mBo6oUWNmuF6R7As93E\nJNyAKoFBbZQ+yODJgUEAnl6/f8UImKIYLEJAs/lvOCdLToD0PYFH4Ih86hzOtXVc\nUS4cK38acijnALXRdMbX5J+tB5O2UzU1/Dfkw/ZdFr4hc96SCvigY2q8lpJqPvi8\nZVWb3vUNiSYE/CUapiVpy8JtynziWV+XrOvvLsi81xtZPCvM8hnIk2snYxnP/Okm\n+Mpxm3+T/jRnhE6Z6/yzeAkzcLpmpnbtG3PrGqUNxCITIJRWCk4sbE6x/c+cCbqi\nM+2HAgMBAAGjYzBhMB0GA1UdDgQWBBTdBAkHovV6fVJTEpKV7jiAJQ2mWTAPBgNV\nHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFN0ECQei9Xp9UlMSkpXuOIAlDaZZMA4G\nA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAIBgRlCn7Jp0cHh5wYfGV\ncpNxJK1ok1iOMq8bs3AD/CUrdIWQPXhq9LmLpZc7tRiRux6n+UBbkflVma8eEdBc\nHadm47GUBwwyOabqG7B52B2ccETjit3E+ZUfijhDPwGFpUenPUayvOUiaPd7nNgs\nPgohyC0zrL/FgZkxdMF1ccW+sfAjRfSda/wZY52jvATGGAslu1OJD7OAUN5F7kR/\nq5R4ZJjT9ijdh9hwZXT7DrkT66cPYakylszeu+1jTBi7qUD3oFRuIIhxdRjqerQ0\ncuAjJ3dctpDqhiVAq+8zD8ufgr6iIPv2tS0a5sKFsXQP+8hlAqRSAUfdSSLBv9jr\na6x+3uxjMxW3IwiPxg+NQVrdjsW5j+VFP3jbutIbQLH+cU0/4IGiul607BXgk90I\nH37hVZkLId6Tngr75qNJvTYw/ud3sqB1l7UtgYgXZSD32pAAn8lSzDLKNXz1PQ/Y\nK9f1JmzJBjSWFupwWRoyeXkLtoh/D1JIPb9s2KJELtFOt3JY04kTlf5Eq/jXixtu\nnLwsoFvVagCvXzfh1foQC5ichucmj87w7G6KVwuA406ywKBjYZC6VWg3dGq2ktuf\noYYitmUnDuy2n0Jg5GfCtdpBC8TTi2EbvPofkSvXRAdeuims2cXp71NIWuuA8ShY\nIc2wBlX7Jz9TkHCpBB5XJ7k=\n-----END CERTIFICATE-----\n\n# Issuer: CN=SSL.com Root Certification Authority ECC O=SSL Corporation\n# Subject: CN=SSL.com Root Certification Authority ECC O=SSL Corporation\n# Label: \"SSL.com Root Certification Authority ECC\"\n# Serial: 8495723813297216424\n# MD5 Fingerprint: 2e:da:e4:39:7f:9c:8f:37:d1:70:9f:26:17:51:3a:8e\n# SHA1 Fingerprint: c3:19:7c:39:24:e6:54:af:1b:c4:ab:20:95:7a:e2:c3:0e:13:02:6a\n# SHA256 Fingerprint: 34:17:bb:06:cc:60:07:da:1b:96:1c:92:0b:8a:b4:ce:3f:ad:82:0e:4a:a3:0b:9a:cb:c4:a7:4e:bd:ce:bc:65\n-----BEGIN CERTIFICATE-----\nMIICjTCCAhSgAwIBAgIIdebfy8FoW6gwCgYIKoZIzj0EAwIwfDELMAkGA1UEBhMC\nVVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9T\nU0wgQ29ycG9yYXRpb24xMTAvBgNVBAMMKFNTTC5jb20gUm9vdCBDZXJ0aWZpY2F0\naW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEyMTgxNDAzWhcNNDEwMjEyMTgxNDAz\nWjB8MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hvdXN0\nb24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjExMC8GA1UEAwwoU1NMLmNvbSBS\nb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49AgEGBSuB\nBAAiA2IABEVuqVDEpiM2nl8ojRfLliJkP9x6jh3MCLOicSS6jkm5BBtHllirLZXI\n7Z4INcgn64mMU1jrYor+8FsPazFSY0E7ic3s7LaNGdM0B9y7xgZ/wkWV7Mt/qCPg\nCemB+vNH06NjMGEwHQYDVR0OBBYEFILRhXMw5zUE044CkvvlpNHEIejNMA8GA1Ud\nEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUgtGFczDnNQTTjgKS++Wk0cQh6M0wDgYD\nVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2cAMGQCMG/n61kRpGDPYbCWe+0F+S8T\nkdzt5fxQaxFGRrMcIQBiu77D5+jNB5n5DQtdcj7EqgIwH7y6C+IwJPt8bYBVCpk+\ngA0z5Wajs6O7pdWLjwkspl1+4vAHCGht0nxpbl/f5Wpl\n-----END CERTIFICATE-----\n\n# Issuer: CN=SSL.com EV Root Certification Authority RSA R2 O=SSL Corporation\n# Subject: CN=SSL.com EV Root Certification Authority RSA R2 O=SSL Corporation\n# Label: \"SSL.com EV Root Certification Authority RSA R2\"\n# Serial: 6248227494352943350\n# MD5 Fingerprint: e1:1e:31:58:1a:ae:54:53:02:f6:17:6a:11:7b:4d:95\n# SHA1 Fingerprint: 74:3a:f0:52:9b:d0:32:a0:f4:4a:83:cd:d4:ba:a9:7b:7c:2e:c4:9a\n# SHA256 Fingerprint: 2e:7b:f1:6c:c2:24:85:a7:bb:e2:aa:86:96:75:07:61:b0:ae:39:be:3b:2f:e9:d0:cc:6d:4e:f7:34:91:42:5c\n-----BEGIN CERTIFICATE-----\nMIIF6zCCA9OgAwIBAgIIVrYpzTS8ePYwDQYJKoZIhvcNAQELBQAwgYIxCzAJBgNV\nBAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4GA1UEBwwHSG91c3RvbjEYMBYGA1UE\nCgwPU1NMIENvcnBvcmF0aW9uMTcwNQYDVQQDDC5TU0wuY29tIEVWIFJvb3QgQ2Vy\ndGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIyMB4XDTE3MDUzMTE4MTQzN1oXDTQy\nMDUzMDE4MTQzN1owgYIxCzAJBgNVBAYTAlVTMQ4wDAYDVQQIDAVUZXhhczEQMA4G\nA1UEBwwHSG91c3RvbjEYMBYGA1UECgwPU1NMIENvcnBvcmF0aW9uMTcwNQYDVQQD\nDC5TU0wuY29tIEVWIFJvb3QgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUlNBIFIy\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAjzZlQOHWTcDXtOlG2mvq\nM0fNTPl9fb69LT3w23jhhqXZuglXaO1XPqDQCEGD5yhBJB/jchXQARr7XnAjssuf\nOePPxU7Gkm0mxnu7s9onnQqG6YE3Bf7wcXHswxzpY6IXFJ3vG2fThVUCAtZJycxa\n4bH3bzKfydQ7iEGonL3Lq9ttewkfokxykNorCPzPPFTOZw+oz12WGQvE43LrrdF9\nHSfvkusQv1vrO6/PgN3B0pYEW3p+pKk8OHakYo6gOV7qd89dAFmPZiw+B6KjBSYR\naZfqhbcPlgtLyEDhULouisv3D5oi53+aNxPN8k0TayHRwMwi8qFG9kRpnMphNQcA\nb9ZhCBHqurj26bNg5U257J8UZslXWNvNh2n4ioYSA0e/ZhN2rHd9NCSFg83XqpyQ\nGp8hLH94t2S42Oim9HizVcuE0jLEeK6jj2HdzghTreyI/BXkmg3mnxp3zkyPuBQV\nPWKchjgGAGYS5Fl2WlPAApiiECtoRHuOec4zSnaqW4EWG7WK2NAAe15itAnWhmMO\npgWVSbooi4iTsjQc2KRVbrcc0N6ZVTsj9CLg+SlmJuwgUHfbSguPvuUCYHBBXtSu\nUDkiFCbLsjtzdFVHB3mBOagwE0TlBIqulhMlQg+5U8Sb/M3kHN48+qvWBkofZ6aY\nMBzdLNvcGJVXZsb/XItW9XcCAwEAAaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAfBgNV\nHSMEGDAWgBT5YLvU49U09rj1BoAlp3PbRmmonjAdBgNVHQ4EFgQU+WC71OPVNPa4\n9QaAJadz20ZpqJ4wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEBCwUAA4ICAQBW\ns47LCp1Jjr+kxJG7ZhcFUZh1++VQLHqe8RT6q9OKPv+RKY9ji9i0qVQBDb6Thi/5\nSm3HXvVX+cpVHBK+Rw82xd9qt9t1wkclf7nxY/hoLVUE0fKNsKTPvDxeH3jnpaAg\ncLAExbf3cqfeIg29MyVGjGSSJuM+LmOW2puMPfgYCdcDzH2GguDKBAdRUNf/ktUM\n79qGn5nX67evaOI5JpS6aLe/g9Pqemc9YmeuJeVy6OLk7K4S9ksrPJ/psEDzOFSz\n/bdoyNrGj1E8svuR3Bznm53htw1yj+KkxKl4+esUrMZDBcJlOSgYAsOCsp0FvmXt\nll9ldDz7CTUue5wT/RsPXcdtgTpWD8w74a8CLyKsRspGPKAcTNZEtF4uXBVmCeEm\nKf7GUmG6sXP/wwyc5WxqlD8UykAWlYTzWamsX0xhk23RO8yilQwipmdnRC652dKK\nQbNmC1r7fSOl8hqw/96bg5Qu0T/fkreRrwU7ZcegbLHNYhLDkBvjJc40vG93drEQ\nw/cFGsDWr3RiSBd3kmmQYRzelYB0VI8YHMPzA9C/pEN1hlMYegouCRw2n5H9gooi\nS9EOUCXdywMMF8mDAAhONU2Ki+3wApRmLER/y5UnlhetCTCstnEXbosX9hwJ1C07\nmKVx01QT2WDz9UtmT/rx7iASjbSsV7FFY6GsdqnC+w==\n-----END CERTIFICATE-----\n\n# Issuer: CN=SSL.com EV Root Certification Authority ECC O=SSL Corporation\n# Subject: CN=SSL.com EV Root Certification Authority ECC O=SSL Corporation\n# Label: \"SSL.com EV Root Certification Authority ECC\"\n# Serial: 3182246526754555285\n# MD5 Fingerprint: 59:53:22:65:83:42:01:54:c0:ce:42:b9:5a:7c:f2:90\n# SHA1 Fingerprint: 4c:dd:51:a3:d1:f5:20:32:14:b0:c6:c5:32:23:03:91:c7:46:42:6d\n# SHA256 Fingerprint: 22:a2:c1:f7:bd:ed:70:4c:c1:e7:01:b5:f4:08:c3:10:88:0f:e9:56:b5:de:2a:4a:44:f9:9c:87:3a:25:a7:c8\n-----BEGIN CERTIFICATE-----\nMIIClDCCAhqgAwIBAgIILCmcWxbtBZUwCgYIKoZIzj0EAwIwfzELMAkGA1UEBhMC\nVVMxDjAMBgNVBAgMBVRleGFzMRAwDgYDVQQHDAdIb3VzdG9uMRgwFgYDVQQKDA9T\nU0wgQ29ycG9yYXRpb24xNDAyBgNVBAMMK1NTTC5jb20gRVYgUm9vdCBDZXJ0aWZp\nY2F0aW9uIEF1dGhvcml0eSBFQ0MwHhcNMTYwMjEyMTgxNTIzWhcNNDEwMjEyMTgx\nNTIzWjB/MQswCQYDVQQGEwJVUzEOMAwGA1UECAwFVGV4YXMxEDAOBgNVBAcMB0hv\ndXN0b24xGDAWBgNVBAoMD1NTTCBDb3Jwb3JhdGlvbjE0MDIGA1UEAwwrU1NMLmNv\nbSBFViBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IEVDQzB2MBAGByqGSM49\nAgEGBSuBBAAiA2IABKoSR5CYG/vvw0AHgyBO8TCCogbR8pKGYfL2IWjKAMTH6kMA\nVIbc/R/fALhBYlzccBYy3h+Z1MzFB8gIH2EWB1E9fVwHU+M1OIzfzZ/ZLg1Kthku\nWnBaBu2+8KGwytAJKaNjMGEwHQYDVR0OBBYEFFvKXuXe0oGqzagtZFG22XKbl+ZP\nMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUW8pe5d7SgarNqC1kUbbZcpuX\n5k8wDgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMCA2gAMGUCMQCK5kCJN+vp1RPZ\nytRrJPOwPYdGWBrssd9v+1a6cGvHOMzosYxPD/fxZ3YOg9AeUY8CMD32IygmTMZg\nh5Mmm7I1HrrW9zzRHM76JTymGoEVW/MSD2zuZYrJh6j5B+BimoxcSg==\n-----END CERTIFICATE-----\n\n# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R6\n# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign Root CA - R6\n# Label: \"GlobalSign Root CA - R6\"\n# Serial: 1417766617973444989252670301619537\n# MD5 Fingerprint: 4f:dd:07:e4:d4:22:64:39:1e:0c:37:42:ea:d1:c6:ae\n# SHA1 Fingerprint: 80:94:64:0e:b5:a7:a1:ca:11:9c:1f:dd:d5:9f:81:02:63:a7:fb:d1\n# SHA256 Fingerprint: 2c:ab:ea:fe:37:d0:6c:a2:2a:ba:73:91:c0:03:3d:25:98:29:52:c4:53:64:73:49:76:3a:3a:b5:ad:6c:cf:69\n-----BEGIN CERTIFICATE-----\nMIIFgzCCA2ugAwIBAgIORea7A4Mzw4VlSOb/RVEwDQYJKoZIhvcNAQEMBQAwTDEg\nMB4GA1UECxMXR2xvYmFsU2lnbiBSb290IENBIC0gUjYxEzARBgNVBAoTCkdsb2Jh\nbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTQxMjEwMDAwMDAwWhcNMzQx\nMjEwMDAwMDAwWjBMMSAwHgYDVQQLExdHbG9iYWxTaWduIFJvb3QgQ0EgLSBSNjET\nMBEGA1UEChMKR2xvYmFsU2lnbjETMBEGA1UEAxMKR2xvYmFsU2lnbjCCAiIwDQYJ\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBAJUH6HPKZvnsFMp7PPcNCPG0RQssgrRI\nxutbPK6DuEGSMxSkb3/pKszGsIhrxbaJ0cay/xTOURQh7ErdG1rG1ofuTToVBu1k\nZguSgMpE3nOUTvOniX9PeGMIyBJQbUJmL025eShNUhqKGoC3GYEOfsSKvGRMIRxD\naNc9PIrFsmbVkJq3MQbFvuJtMgamHvm566qjuL++gmNQ0PAYid/kD3n16qIfKtJw\nLnvnvJO7bVPiSHyMEAc4/2ayd2F+4OqMPKq0pPbzlUoSB239jLKJz9CgYXfIWHSw\n1CM69106yqLbnQneXUQtkPGBzVeS+n68UARjNN9rkxi+azayOeSsJDa38O+2HBNX\nk7besvjihbdzorg1qkXy4J02oW9UivFyVm4uiMVRQkQVlO6jxTiWm05OWgtH8wY2\nSXcwvHE35absIQh1/OZhFj931dmRl4QKbNQCTXTAFO39OfuD8l4UoQSwC+n+7o/h\nbguyCLNhZglqsQY6ZZZZwPA1/cnaKI0aEYdwgQqomnUdnjqGBQCe24DWJfncBZ4n\nWUx2OVvq+aWh2IMP0f/fMBH5hc8zSPXKbWQULHpYT9NLCEnFlWQaYw55PfWzjMpY\nrZxCRXluDocZXFSxZba/jJvcE+kNb7gu3GduyYsRtYQUigAZcIN5kZeR1Bonvzce\nMgfYFGM8KEyvAgMBAAGjYzBhMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTAD\nAQH/MB0GA1UdDgQWBBSubAWjkxPioufi1xzWx/B/yGdToDAfBgNVHSMEGDAWgBSu\nbAWjkxPioufi1xzWx/B/yGdToDANBgkqhkiG9w0BAQwFAAOCAgEAgyXt6NH9lVLN\nnsAEoJFp5lzQhN7craJP6Ed41mWYqVuoPId8AorRbrcWc+ZfwFSY1XS+wc3iEZGt\nIxg93eFyRJa0lV7Ae46ZeBZDE1ZXs6KzO7V33EByrKPrmzU+sQghoefEQzd5Mr61\n55wsTLxDKZmOMNOsIeDjHfrYBzN2VAAiKrlNIC5waNrlU/yDXNOd8v9EDERm8tLj\nvUYAGm0CuiVdjaExUd1URhxN25mW7xocBFymFe944Hn+Xds+qkxV/ZoVqW/hpvvf\ncDDpw+5CRu3CkwWJ+n1jez/QcYF8AOiYrg54NMMl+68KnyBr3TsTjxKM4kEaSHpz\noHdpx7Zcf4LIHv5YGygrqGytXm3ABdJ7t+uA/iU3/gKbaKxCXcPu9czc8FB10jZp\nnOZ7BN9uBmm23goJSFmH63sUYHpkqmlD75HHTOwY3WzvUy2MmeFe8nI+z1TIvWfs\npA9MRf/TuTAjB0yPEL+GltmZWrSZVxykzLsViVO6LAUP5MSeGbEYNNVMnbrt9x+v\nJJUEeKgDu+6B5dpffItKoZB0JaezPkvILFa9x8jvOOJckvB595yEunQtYQEgfn7R\n8k8HWV+LLUNS60YMlOH1Zkd5d9VUWx+tJDfLRVpOoERIyNiwmcUVhAn21klJwGW4\n5hpxbqCo8YLoRT5s1gLXCmeDBVrJpBA=\n-----END CERTIFICATE-----\n\n# Issuer: CN=OISTE WISeKey Global Root GC CA O=WISeKey OU=OISTE Foundation Endorsed\n# Subject: CN=OISTE WISeKey Global Root GC CA O=WISeKey OU=OISTE Foundation Endorsed\n# Label: \"OISTE WISeKey Global Root GC CA\"\n# Serial: 44084345621038548146064804565436152554\n# MD5 Fingerprint: a9:d6:b9:2d:2f:93:64:f8:a5:69:ca:91:e9:68:07:23\n# SHA1 Fingerprint: e0:11:84:5e:34:de:be:88:81:b9:9c:f6:16:26:d1:96:1f:c3:b9:31\n# SHA256 Fingerprint: 85:60:f9:1c:36:24:da:ba:95:70:b5:fe:a0:db:e3:6f:f1:1a:83:23:be:94:86:85:4f:b3:f3:4a:55:71:19:8d\n-----BEGIN CERTIFICATE-----\nMIICaTCCAe+gAwIBAgIQISpWDK7aDKtARb8roi066jAKBggqhkjOPQQDAzBtMQsw\nCQYDVQQGEwJDSDEQMA4GA1UEChMHV0lTZUtleTEiMCAGA1UECxMZT0lTVEUgRm91\nbmRhdGlvbiBFbmRvcnNlZDEoMCYGA1UEAxMfT0lTVEUgV0lTZUtleSBHbG9iYWwg\nUm9vdCBHQyBDQTAeFw0xNzA1MDkwOTQ4MzRaFw00MjA1MDkwOTU4MzNaMG0xCzAJ\nBgNVBAYTAkNIMRAwDgYDVQQKEwdXSVNlS2V5MSIwIAYDVQQLExlPSVNURSBGb3Vu\nZGF0aW9uIEVuZG9yc2VkMSgwJgYDVQQDEx9PSVNURSBXSVNlS2V5IEdsb2JhbCBS\nb290IEdDIENBMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAETOlQwMYPchi82PG6s4ni\neUqjFqdrVCTbUf/q9Akkwwsin8tqJ4KBDdLArzHkdIJuyiXZjHWd8dvQmqJLIX4W\np2OQ0jnUsYd4XxiWD1AbNTcPasbc2RNNpI6QN+a9WzGRo1QwUjAOBgNVHQ8BAf8E\nBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUSIcUrOPDnpBgOtfKie7T\nrYy0UGYwEAYJKwYBBAGCNxUBBAMCAQAwCgYIKoZIzj0EAwMDaAAwZQIwJsdpW9zV\n57LnyAyMjMPdeYwbY9XJUpROTYJKcx6ygISpJcBMWm1JKWB4E+J+SOtkAjEA2zQg\nMgj/mkkCtojeFK9dbJlxjRo/i9fgojaGHAeCOnZT/cKi7e97sIBPWA9LUzm9\n-----END CERTIFICATE-----\n\n# Issuer: CN=UCA Global G2 Root O=UniTrust\n# Subject: CN=UCA Global G2 Root O=UniTrust\n# Label: \"UCA Global G2 Root\"\n# Serial: 124779693093741543919145257850076631279\n# MD5 Fingerprint: 80:fe:f0:c4:4a:f0:5c:62:32:9f:1c:ba:78:a9:50:f8\n# SHA1 Fingerprint: 28:f9:78:16:19:7a:ff:18:25:18:aa:44:fe:c1:a0:ce:5c:b6:4c:8a\n# SHA256 Fingerprint: 9b:ea:11:c9:76:fe:01:47:64:c1:be:56:a6:f9:14:b5:a5:60:31:7a:bd:99:88:39:33:82:e5:16:1a:a0:49:3c\n-----BEGIN CERTIFICATE-----\nMIIFRjCCAy6gAwIBAgIQXd+x2lqj7V2+WmUgZQOQ7zANBgkqhkiG9w0BAQsFADA9\nMQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxGzAZBgNVBAMMElVDQSBH\nbG9iYWwgRzIgUm9vdDAeFw0xNjAzMTEwMDAwMDBaFw00MDEyMzEwMDAwMDBaMD0x\nCzAJBgNVBAYTAkNOMREwDwYDVQQKDAhVbmlUcnVzdDEbMBkGA1UEAwwSVUNBIEds\nb2JhbCBHMiBSb290MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxeYr\nb3zvJgUno4Ek2m/LAfmZmqkywiKHYUGRO8vDaBsGxUypK8FnFyIdK+35KYmToni9\nkmugow2ifsqTs6bRjDXVdfkX9s9FxeV67HeToI8jrg4aA3++1NDtLnurRiNb/yzm\nVHqUwCoV8MmNsHo7JOHXaOIxPAYzRrZUEaalLyJUKlgNAQLx+hVRZ2zA+te2G3/R\nVogvGjqNO7uCEeBHANBSh6v7hn4PJGtAnTRnvI3HLYZveT6OqTwXS3+wmeOwcWDc\nC/Vkw85DvG1xudLeJ1uK6NjGruFZfc8oLTW4lVYa8bJYS7cSN8h8s+1LgOGN+jIj\ntm+3SJUIsUROhYw6AlQgL9+/V087OpAh18EmNVQg7Mc/R+zvWr9LesGtOxdQXGLY\nD0tK3Cv6brxzks3sx1DoQZbXqX5t2Okdj4q1uViSukqSKwxW/YDrCPBeKW4bHAyv\nj5OJrdu9o54hyokZ7N+1wxrrFv54NkzWbtA+FxyQF2smuvt6L78RHBgOLXMDj6Dl\nNaBa4kx1HXHhOThTeEDMg5PXCp6dW4+K5OXgSORIskfNTip1KnvyIvbJvgmRlld6\niIis7nCs+dwp4wwcOxJORNanTrAmyPPZGpeRaOrvjUYG0lZFWJo8DA+DuAUlwznP\nO6Q0ibd5Ei9Hxeepl2n8pndntd978XplFeRhVmUCAwEAAaNCMEAwDgYDVR0PAQH/\nBAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFIHEjMz15DD/pQwIX4wV\nZyF0Ad/fMA0GCSqGSIb3DQEBCwUAA4ICAQATZSL1jiutROTL/7lo5sOASD0Ee/oj\nL3rtNtqyzm325p7lX1iPyzcyochltq44PTUbPrw7tgTQvPlJ9Zv3hcU2tsu8+Mg5\n1eRfB70VVJd0ysrtT7q6ZHafgbiERUlMjW+i67HM0cOU2kTC5uLqGOiiHycFutfl\n1qnN3e92mI0ADs0b+gO3joBYDic/UvuUospeZcnWhNq5NXHzJsBPd+aBJ9J3O5oU\nb3n09tDh05S60FdRvScFDcH9yBIw7m+NESsIndTUv4BFFJqIRNow6rSn4+7vW4LV\nPtateJLbXDzz2K36uGt/xDYotgIVilQsnLAXc47QN6MUPJiVAAwpBVueSUmxX8fj\ny88nZY41F7dXyDDZQVu5FLbowg+UMaeUmMxq67XhJ/UQqAHojhJi6IjMtX9Gl8Cb\nEGY4GjZGXyJoPd/JxhMnq1MGrKI8hgZlb7F+sSlEmqO6SWkoaY/X5V+tBIZkbxqg\nDMUIYs6Ao9Dz7GjevjPHF1t/gMRMTLGmhIrDO7gJzRSBuhjjVFc2/tsvfEehOjPI\n+Vg7RE+xygKJBJYoaMVLuCaJu9YzL1DV/pqJuhgyklTGW+Cd+V7lDSKb9triyCGy\nYiGqhkCyLmTTX8jjfhFnRR8F/uOi77Oos/N9j/gMHyIfLXC0uAE0djAA5SN4p1bX\nUB+K+wb1whnw0A==\n-----END CERTIFICATE-----\n\n# Issuer: CN=UCA Extended Validation Root O=UniTrust\n# Subject: CN=UCA Extended Validation Root O=UniTrust\n# Label: \"UCA Extended Validation Root\"\n# Serial: 106100277556486529736699587978573607008\n# MD5 Fingerprint: a1:f3:5f:43:c6:34:9b:da:bf:8c:7e:05:53:ad:96:e2\n# SHA1 Fingerprint: a3:a1:b0:6f:24:61:23:4a:e3:36:a5:c2:37:fc:a6:ff:dd:f0:d7:3a\n# SHA256 Fingerprint: d4:3a:f9:b3:54:73:75:5c:96:84:fc:06:d7:d8:cb:70:ee:5c:28:e7:73:fb:29:4e:b4:1e:e7:17:22:92:4d:24\n-----BEGIN CERTIFICATE-----\nMIIFWjCCA0KgAwIBAgIQT9Irj/VkyDOeTzRYZiNwYDANBgkqhkiG9w0BAQsFADBH\nMQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNVBAMMHFVDQSBF\neHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwHhcNMTUwMzEzMDAwMDAwWhcNMzgxMjMx\nMDAwMDAwWjBHMQswCQYDVQQGEwJDTjERMA8GA1UECgwIVW5pVHJ1c3QxJTAjBgNV\nBAMMHFVDQSBFeHRlbmRlZCBWYWxpZGF0aW9uIFJvb3QwggIiMA0GCSqGSIb3DQEB\nAQUAA4ICDwAwggIKAoICAQCpCQcoEwKwmeBkqh5DFnpzsZGgdT6o+uM4AHrsiWog\nD4vFsJszA1qGxliG1cGFu0/GnEBNyr7uaZa4rYEwmnySBesFK5pI0Lh2PpbIILvS\nsPGP2KxFRv+qZ2C0d35qHzwaUnoEPQc8hQ2E0B92CvdqFN9y4zR8V05WAT558aop\nO2z6+I9tTcg1367r3CTueUWnhbYFiN6IXSV8l2RnCdm/WhUFhvMJHuxYMjMR83dk\nsHYf5BA1FxvyDrFspCqjc/wJHx4yGVMR59mzLC52LqGj3n5qiAno8geK+LLNEOfi\nc0CTuwjRP+H8C5SzJe98ptfRr5//lpr1kXuYC3fUfugH0mK1lTnj8/FtDw5lhIpj\nVMWAtuCeS31HJqcBCF3RiJ7XwzJE+oJKCmhUfzhTA8ykADNkUVkLo4KRel7sFsLz\nKuZi2irbWWIQJUoqgQtHB0MGcIfS+pMRKXpITeuUx3BNr2fVUbGAIAEBtHoIppB/\nTuDvB0GHr2qlXov7z1CymlSvw4m6WC31MJixNnI5fkkE/SmnTHnkBVfblLkWU41G\nsx2VYVdWf6/wFlthWG82UBEL2KwrlRYaDh8IzTY0ZRBiZtWAXxQgXy0MoHgKaNYs\n1+lvK9JKBZP8nm9rZ/+I8U6laUpSNwXqxhaN0sSZ0YIrO7o1dfdRUVjzyAfd5LQD\nfwIDAQABo0IwQDAdBgNVHQ4EFgQU2XQ65DA9DfcS3H5aBZ8eNJr34RQwDwYDVR0T\nAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQADggIBADaN\nl8xCFWQpN5smLNb7rhVpLGsaGvdftvkHTFnq88nIua7Mui563MD1sC3AO6+fcAUR\nap8lTwEpcOPlDOHqWnzcSbvBHiqB9RZLcpHIojG5qtr8nR/zXUACE/xOHAbKsxSQ\nVBcZEhrxH9cMaVr2cXj0lH2RC47skFSOvG+hTKv8dGT9cZr4QQehzZHkPJrgmzI5\nc6sq1WnIeJEmMX3ixzDx/BR4dxIOE/TdFpS/S2d7cFOFyrC78zhNLJA5wA3CXWvp\n4uXViI3WLL+rG761KIcSF3Ru/H38j9CHJrAb+7lsq+KePRXBOy5nAliRn+/4Qh8s\nt2j1da3Ptfb/EX3C8CSlrdP6oDyp+l3cpaDvRKS+1ujl5BOWF3sGPjLtx7dCvHaj\n2GU4Kzg1USEODm8uNBNA4StnDG1KQTAYI1oyVZnJF+A83vbsea0rWBmirSwiGpWO\nvpaQXUJXxPkUAzUrHC1RVwinOt4/5Mi0A3PCwSaAuwtCH60NryZy2sy+s6ODWA2C\nxR9GUeOcGMyNm43sSet1UNWMKFnKdDTajAshqx7qG+XH/RU+wBeq+yNuJkbL+vmx\ncmtpzyKEC2IPrNkZAJSidjzULZrtBJ4tBmIQN1IchXIbJ+XMxjHsN+xjWZsLHXbM\nfjKaiJUINlK73nZfdklJrX+9ZSCyycErdhh2n1ax\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certigna Root CA O=Dhimyotis OU=0002 48146308100036\n# Subject: CN=Certigna Root CA O=Dhimyotis OU=0002 48146308100036\n# Label: \"Certigna Root CA\"\n# Serial: 269714418870597844693661054334862075617\n# MD5 Fingerprint: 0e:5c:30:62:27:eb:5b:bc:d7:ae:62:ba:e9:d5:df:77\n# SHA1 Fingerprint: 2d:0d:52:14:ff:9e:ad:99:24:01:74:20:47:6e:6c:85:27:27:f5:43\n# SHA256 Fingerprint: d4:8d:3d:23:ee:db:50:a4:59:e5:51:97:60:1c:27:77:4b:9d:7b:18:c9:4d:5a:05:95:11:a1:02:50:b9:31:68\n-----BEGIN CERTIFICATE-----\nMIIGWzCCBEOgAwIBAgIRAMrpG4nxVQMNo+ZBbcTjpuEwDQYJKoZIhvcNAQELBQAw\nWjELMAkGA1UEBhMCRlIxEjAQBgNVBAoMCURoaW15b3RpczEcMBoGA1UECwwTMDAw\nMiA0ODE0NjMwODEwMDAzNjEZMBcGA1UEAwwQQ2VydGlnbmEgUm9vdCBDQTAeFw0x\nMzEwMDEwODMyMjdaFw0zMzEwMDEwODMyMjdaMFoxCzAJBgNVBAYTAkZSMRIwEAYD\nVQQKDAlEaGlteW90aXMxHDAaBgNVBAsMEzAwMDIgNDgxNDYzMDgxMDAwMzYxGTAX\nBgNVBAMMEENlcnRpZ25hIFJvb3QgQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw\nggIKAoICAQDNGDllGlmx6mQWDoyUJJV8g9PFOSbcDO8WV43X2KyjQn+Cyu3NW9sO\nty3tRQgXstmzy9YXUnIo245Onoq2C/mehJpNdt4iKVzSs9IGPjA5qXSjklYcoW9M\nCiBtnyN6tMbaLOQdLNyzKNAT8kxOAkmhVECe5uUFoC2EyP+YbNDrihqECB63aCPu\nI9Vwzm1RaRDuoXrC0SIxwoKF0vJVdlB8JXrJhFwLrN1CTivngqIkicuQstDuI7pm\nTLtipPlTWmR7fJj6o0ieD5Wupxj0auwuA0Wv8HT4Ks16XdG+RCYyKfHx9WzMfgIh\nC59vpD++nVPiz32pLHxYGpfhPTc3GGYo0kDFUYqMwy3OU4gkWGQwFsWq4NYKpkDf\nePb1BHxpE4S80dGnBs8B92jAqFe7OmGtBIyT46388NtEbVncSVmurJqZNjBBe3Yz\nIoejwpKGbvlw7q6Hh5UbxHq9MfPU0uWZ/75I7HX1eBYdpnDBfzwboZL7z8g81sWT\nCo/1VTp2lc5ZmIoJlXcymoO6LAQ6l73UL77XbJuiyn1tJslV1c/DeVIICZkHJC1k\nJWumIWmbat10TWuXekG9qxf5kBdIjzb5LdXF2+6qhUVB+s06RbFo5jZMm5BX7CO5\nhwjCxAnxl4YqKE3idMDaxIzb3+KhF1nOJFl0Mdp//TBt2dzhauH8XwIDAQABo4IB\nGjCCARYwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE\nFBiHVuBud+4kNTxOc5of1uHieX4rMB8GA1UdIwQYMBaAFBiHVuBud+4kNTxOc5of\n1uHieX4rMEQGA1UdIAQ9MDswOQYEVR0gADAxMC8GCCsGAQUFBwIBFiNodHRwczov\nL3d3d3cuY2VydGlnbmEuZnIvYXV0b3JpdGVzLzBtBgNVHR8EZjBkMC+gLaArhilo\ndHRwOi8vY3JsLmNlcnRpZ25hLmZyL2NlcnRpZ25hcm9vdGNhLmNybDAxoC+gLYYr\naHR0cDovL2NybC5kaGlteW90aXMuY29tL2NlcnRpZ25hcm9vdGNhLmNybDANBgkq\nhkiG9w0BAQsFAAOCAgEAlLieT/DjlQgi581oQfccVdV8AOItOoldaDgvUSILSo3L\n6btdPrtcPbEo/uRTVRPPoZAbAh1fZkYJMyjhDSSXcNMQH+pkV5a7XdrnxIxPTGRG\nHVyH41neQtGbqH6mid2PHMkwgu07nM3A6RngatgCdTer9zQoKJHyBApPNeNgJgH6\n0BGM+RFq7q89w1DTj18zeTyGqHNFkIwgtnJzFyO+B2XleJINugHA64wcZr+shncB\nlA2c5uk5jR+mUYyZDDl34bSb+hxnV29qao6pK0xXeXpXIs/NX2NGjVxZOob4Mkdi\no2cNGJHc+6Zr9UhhcyNZjgKnvETq9Emd8VRY+WCv2hikLyhF3HqgiIZd8zvn/yk1\ngPxkQ5Tm4xxvvq0OKmOZK8l+hfZx6AYDlf7ej0gcWtSS6Cvu5zHbugRqh5jnxV/v\nfaci9wHYTfmJ0A6aBVmknpjZbyvKcL5kwlWj9Omvw5Ip3IgWJJk8jSaYtlu3zM63\nNwf9JtmYhST/WSMDmu2dnajkXjjO11INb9I/bbEFa0nOipFGc/T2L/Coc3cOZayh\njWZSaX5LaAzHHjcng6WMxwLkFM1JAbBzs/3GkDpv0mztO+7skb6iQ12LAEpmJURw\n3kAP+HwV96LOPNdeE4yBFxgX0b3xdxA61GU5wSesVywlVP+i2k+KYTlerj1KjL0=\n-----END CERTIFICATE-----\n\n# Issuer: CN=emSign Root CA - G1 O=eMudhra Technologies Limited OU=emSign PKI\n# Subject: CN=emSign Root CA - G1 O=eMudhra Technologies Limited OU=emSign PKI\n# Label: \"emSign Root CA - G1\"\n# Serial: 235931866688319308814040\n# MD5 Fingerprint: 9c:42:84:57:dd:cb:0b:a7:2e:95:ad:b6:f3:da:bc:ac\n# SHA1 Fingerprint: 8a:c7:ad:8f:73:ac:4e:c1:b5:75:4d:a5:40:f4:fc:cf:7c:b5:8e:8c\n# SHA256 Fingerprint: 40:f6:af:03:46:a9:9a:a1:cd:1d:55:5a:4e:9c:ce:62:c7:f9:63:46:03:ee:40:66:15:83:3d:c8:c8:d0:03:67\n-----BEGIN CERTIFICATE-----\nMIIDlDCCAnygAwIBAgIKMfXkYgxsWO3W2DANBgkqhkiG9w0BAQsFADBnMQswCQYD\nVQQGEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBU\nZWNobm9sb2dpZXMgTGltaXRlZDEcMBoGA1UEAxMTZW1TaWduIFJvb3QgQ0EgLSBH\nMTAeFw0xODAyMTgxODMwMDBaFw00MzAyMTgxODMwMDBaMGcxCzAJBgNVBAYTAklO\nMRMwEQYDVQQLEwplbVNpZ24gUEtJMSUwIwYDVQQKExxlTXVkaHJhIFRlY2hub2xv\nZ2llcyBMaW1pdGVkMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEcxMIIBIjAN\nBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAk0u76WaK7p1b1TST0Bsew+eeuGQz\nf2N4aLTNLnF115sgxk0pvLZoYIr3IZpWNVrzdr3YzZr/k1ZLpVkGoZM0Kd0WNHVO\n8oG0x5ZOrRkVUkr+PHB1cM2vK6sVmjM8qrOLqs1D/fXqcP/tzxE7lM5OMhbTI0Aq\nd7OvPAEsbO2ZLIvZTmmYsvePQbAyeGHWDV/D+qJAkh1cF+ZwPjXnorfCYuKrpDhM\ntTk1b+oDafo6VGiFbdbyL0NVHpENDtjVaqSW0RM8LHhQ6DqS0hdW5TUaQBw+jSzt\nOd9C4INBdN+jzcKGYEho42kLVACL5HZpIQ15TjQIXhTCzLG3rdd8cIrHhQIDAQAB\no0IwQDAdBgNVHQ4EFgQU++8Nhp6w492pufEhF38+/PB3KxowDgYDVR0PAQH/BAQD\nAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAFn/8oz1h31x\nPaOfG1vR2vjTnGs2vZupYeveFix0PZ7mddrXuqe8QhfnPZHr5X3dPpzxz5KsbEjM\nwiI/aTvFthUvozXGaCocV685743QNcMYDHsAVhzNixl03r4PEuDQqqE/AjSxcM6d\nGNYIAwlG7mDgfrbESQRRfXBgvKqy/3lyeqYdPV8q+Mri/Tm3R7nrft8EI6/6nAYH\n6ftjk4BAtcZsCjEozgyfz7MjNYBBjWzEN3uBL4ChQEKF6dk4jeihU80Bv2noWgby\nRQuQ+q7hv53yrlc8pa6yVvSLZUDp/TGBLPQ5Cdjua6e0ph0VpZj3AYHYhX3zUVxx\niN66zB+Afko=\n-----END CERTIFICATE-----\n\n# Issuer: CN=emSign ECC Root CA - G3 O=eMudhra Technologies Limited OU=emSign PKI\n# Subject: CN=emSign ECC Root CA - G3 O=eMudhra Technologies Limited OU=emSign PKI\n# Label: \"emSign ECC Root CA - G3\"\n# Serial: 287880440101571086945156\n# MD5 Fingerprint: ce:0b:72:d1:9f:88:8e:d0:50:03:e8:e3:b8:8b:67:40\n# SHA1 Fingerprint: 30:43:fa:4f:f2:57:dc:a0:c3:80:ee:2e:58:ea:78:b2:3f:e6:bb:c1\n# SHA256 Fingerprint: 86:a1:ec:ba:08:9c:4a:8d:3b:be:27:34:c6:12:ba:34:1d:81:3e:04:3c:f9:e8:a8:62:cd:5c:57:a3:6b:be:6b\n-----BEGIN CERTIFICATE-----\nMIICTjCCAdOgAwIBAgIKPPYHqWhwDtqLhDAKBggqhkjOPQQDAzBrMQswCQYDVQQG\nEwJJTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNo\nbm9sb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0g\nRzMwHhcNMTgwMjE4MTgzMDAwWhcNNDMwMjE4MTgzMDAwWjBrMQswCQYDVQQGEwJJ\nTjETMBEGA1UECxMKZW1TaWduIFBLSTElMCMGA1UEChMcZU11ZGhyYSBUZWNobm9s\nb2dpZXMgTGltaXRlZDEgMB4GA1UEAxMXZW1TaWduIEVDQyBSb290IENBIC0gRzMw\ndjAQBgcqhkjOPQIBBgUrgQQAIgNiAAQjpQy4LRL1KPOxst3iAhKAnjlfSU2fySU0\nWXTsuwYc58Byr+iuL+FBVIcUqEqy6HyC5ltqtdyzdc6LBtCGI79G1Y4PPwT01xyS\nfvalY8L1X44uT6EYGQIrMgqCZH0Wk9GjQjBAMB0GA1UdDgQWBBR8XQKEE9TMipuB\nzhccLikenEhjQjAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggq\nhkjOPQQDAwNpADBmAjEAvvNhzwIQHWSVB7gYboiFBS+DCBeQyh+KTOgNG3qxrdWB\nCUfvO6wIBHxcmbHtRwfSAjEAnbpV/KlK6O3t5nYBQnvI+GDZjVGLVTv7jHvrZQnD\n+JbNR6iC8hZVdyR+EhCVBCyj\n-----END CERTIFICATE-----\n\n# Issuer: CN=emSign Root CA - C1 O=eMudhra Inc OU=emSign PKI\n# Subject: CN=emSign Root CA - C1 O=eMudhra Inc OU=emSign PKI\n# Label: \"emSign Root CA - C1\"\n# Serial: 825510296613316004955058\n# MD5 Fingerprint: d8:e3:5d:01:21:fa:78:5a:b0:df:ba:d2:ee:2a:5f:68\n# SHA1 Fingerprint: e7:2e:f1:df:fc:b2:09:28:cf:5d:d4:d5:67:37:b1:51:cb:86:4f:01\n# SHA256 Fingerprint: 12:56:09:aa:30:1d:a0:a2:49:b9:7a:82:39:cb:6a:34:21:6f:44:dc:ac:9f:39:54:b1:42:92:f2:e8:c8:60:8f\n-----BEGIN CERTIFICATE-----\nMIIDczCCAlugAwIBAgILAK7PALrEzzL4Q7IwDQYJKoZIhvcNAQELBQAwVjELMAkG\nA1UEBhMCVVMxEzARBgNVBAsTCmVtU2lnbiBQS0kxFDASBgNVBAoTC2VNdWRocmEg\nSW5jMRwwGgYDVQQDExNlbVNpZ24gUm9vdCBDQSAtIEMxMB4XDTE4MDIxODE4MzAw\nMFoXDTQzMDIxODE4MzAwMFowVjELMAkGA1UEBhMCVVMxEzARBgNVBAsTCmVtU2ln\nbiBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMRwwGgYDVQQDExNlbVNpZ24gUm9v\ndCBDQSAtIEMxMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz+upufGZ\nBczYKCFK83M0UYRWEPWgTywS4/oTmifQz/l5GnRfHXk5/Fv4cI7gklL35CX5VIPZ\nHdPIWoU/Xse2B+4+wM6ar6xWQio5JXDWv7V7Nq2s9nPczdcdioOl+yuQFTdrHCZH\n3DspVpNqs8FqOp099cGXOFgFixwR4+S0uF2FHYP+eF8LRWgYSKVGczQ7/g/IdrvH\nGPMF0Ybzhe3nudkyrVWIzqa2kbBPrH4VI5b2P/AgNBbeCsbEBEV5f6f9vtKppa+c\nxSMq9zwhbL2vj07FOrLzNBL834AaSaTUqZX3noleoomslMuoaJuvimUnzYnu3Yy1\naylwQ6BpC+S5DwIDAQABo0IwQDAdBgNVHQ4EFgQU/qHgcB4qAzlSWkK+XJGFehiq\nTbUwDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL\nBQADggEBAMJKVvoVIXsoounlHfv4LcQ5lkFMOycsxGwYFYDGrK9HWS8mC+M2sO87\n/kOXSTKZEhVb3xEp/6tT+LvBeA+snFOvV71ojD1pM/CjoCNjO2RnIkSt1XHLVip4\nkqNPEjE2NuLe/gDEo2APJ62gsIq1NnpSob0n9CAnYuhNlCQT5AoE6TyrLshDCUrG\nYQTlSTR+08TI9Q/Aqum6VF7zYytPT1DU/rl7mYw9wC68AivTxEDkigcxHpvOJpkT\n+xHqmiIMERnHXhuBUDDIlhJu58tBf5E7oke3VIAb3ADMmpDqw8NQBmIMMMAVSKeo\nWXzhriKi4gp6D/piq1JM4fHfyr6DDUI=\n-----END CERTIFICATE-----\n\n# Issuer: CN=emSign ECC Root CA - C3 O=eMudhra Inc OU=emSign PKI\n# Subject: CN=emSign ECC Root CA - C3 O=eMudhra Inc OU=emSign PKI\n# Label: \"emSign ECC Root CA - C3\"\n# Serial: 582948710642506000014504\n# MD5 Fingerprint: 3e:53:b3:a3:81:ee:d7:10:f8:d3:b0:1d:17:92:f5:d5\n# SHA1 Fingerprint: b6:af:43:c2:9b:81:53:7d:f6:ef:6b:c3:1f:1f:60:15:0c:ee:48:66\n# SHA256 Fingerprint: bc:4d:80:9b:15:18:9d:78:db:3e:1d:8c:f4:f9:72:6a:79:5d:a1:64:3c:a5:f1:35:8e:1d:db:0e:dc:0d:7e:b3\n-----BEGIN CERTIFICATE-----\nMIICKzCCAbGgAwIBAgIKe3G2gla4EnycqDAKBggqhkjOPQQDAzBaMQswCQYDVQQG\nEwJVUzETMBEGA1UECxMKZW1TaWduIFBLSTEUMBIGA1UEChMLZU11ZGhyYSBJbmMx\nIDAeBgNVBAMTF2VtU2lnbiBFQ0MgUm9vdCBDQSAtIEMzMB4XDTE4MDIxODE4MzAw\nMFoXDTQzMDIxODE4MzAwMFowWjELMAkGA1UEBhMCVVMxEzARBgNVBAsTCmVtU2ln\nbiBQS0kxFDASBgNVBAoTC2VNdWRocmEgSW5jMSAwHgYDVQQDExdlbVNpZ24gRUND\nIFJvb3QgQ0EgLSBDMzB2MBAGByqGSM49AgEGBSuBBAAiA2IABP2lYa57JhAd6bci\nMK4G9IGzsUJxlTm801Ljr6/58pc1kjZGDoeVjbk5Wum739D+yAdBPLtVb4Ojavti\nsIGJAnB9SMVK4+kiVCJNk7tCDK93nCOmfddhEc5lx/h//vXyqaNCMEAwHQYDVR0O\nBBYEFPtaSNCAIEDyqOkAB2kZd6fmw/TPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMB\nAf8EBTADAQH/MAoGCCqGSM49BAMDA2gAMGUCMQC02C8Cif22TGK6Q04ThHK1rt0c\n3ta13FaPWEBaLd4gTCKDypOofu4SQMfWh0/434UCMBwUZOR8loMRnLDRWmFLpg9J\n0wD8ofzkpf9/rdcw0Md3f76BB1UwUCAU9Vc4CqgxUQ==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Hongkong Post Root CA 3 O=Hongkong Post\n# Subject: CN=Hongkong Post Root CA 3 O=Hongkong Post\n# Label: \"Hongkong Post Root CA 3\"\n# Serial: 46170865288971385588281144162979347873371282084\n# MD5 Fingerprint: 11:fc:9f:bd:73:30:02:8a:fd:3f:f3:58:b9:cb:20:f0\n# SHA1 Fingerprint: 58:a2:d0:ec:20:52:81:5b:c1:f3:f8:64:02:24:4e:c2:8e:02:4b:02\n# SHA256 Fingerprint: 5a:2f:c0:3f:0c:83:b0:90:bb:fa:40:60:4b:09:88:44:6c:76:36:18:3d:f9:84:6e:17:10:1a:44:7f:b8:ef:d6\n-----BEGIN CERTIFICATE-----\nMIIFzzCCA7egAwIBAgIUCBZfikyl7ADJk0DfxMauI7gcWqQwDQYJKoZIhvcNAQEL\nBQAwbzELMAkGA1UEBhMCSEsxEjAQBgNVBAgTCUhvbmcgS29uZzESMBAGA1UEBxMJ\nSG9uZyBLb25nMRYwFAYDVQQKEw1Ib25na29uZyBQb3N0MSAwHgYDVQQDExdIb25n\na29uZyBQb3N0IFJvb3QgQ0EgMzAeFw0xNzA2MDMwMjI5NDZaFw00MjA2MDMwMjI5\nNDZaMG8xCzAJBgNVBAYTAkhLMRIwEAYDVQQIEwlIb25nIEtvbmcxEjAQBgNVBAcT\nCUhvbmcgS29uZzEWMBQGA1UEChMNSG9uZ2tvbmcgUG9zdDEgMB4GA1UEAxMXSG9u\nZ2tvbmcgUG9zdCBSb290IENBIDMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK\nAoICAQCziNfqzg8gTr7m1gNt7ln8wlffKWihgw4+aMdoWJwcYEuJQwy51BWy7sFO\ndem1p+/l6TWZ5Mwc50tfjTMwIDNT2aa71T4Tjukfh0mtUC1Qyhi+AViiE3CWu4mI\nVoBc+L0sPOFMV4i707mV78vH9toxdCim5lSJ9UExyuUmGs2C4HDaOym71QP1mbpV\n9WTRYA6ziUm4ii8F0oRFKHyPaFASePwLtVPLwpgchKOesL4jpNrcyCse2m5FHomY\n2vkALgbpDDtw1VAliJnLzXNg99X/NWfFobxeq81KuEXryGgeDQ0URhLj0mRiikKY\nvLTGCAj4/ahMZJx2Ab0vqWwzD9g/KLg8aQFChn5pwckGyuV6RmXpwtZQQS4/t+Tt\nbNe/JgERohYpSms0BpDsE9K2+2p20jzt8NYt3eEV7KObLyzJPivkaTv/ciWxNoZb\nx39ri1UbSsUgYT2uy1DhCDq+sI9jQVMwCFk8mB13umOResoQUGC/8Ne8lYePl8X+\nl2oBlKN8W4UdKjk60FSh0Tlxnf0h+bV78OLgAo9uliQlLKAeLKjEiafv7ZkGL7YK\nTE/bosw3Gq9HhS2KX8Q0NEwA/RiTZxPRN+ZItIsGxVd7GYYKecsAyVKvQv83j+Gj\nHno9UKtjBucVtT+2RTeUN7F+8kjDf8V1/peNRY8apxpyKBpADwIDAQABo2MwYTAP\nBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAfBgNVHSMEGDAWgBQXnc0e\ni9Y5K3DTXNSguB+wAPzFYTAdBgNVHQ4EFgQUF53NHovWOStw01zUoLgfsAD8xWEw\nDQYJKoZIhvcNAQELBQADggIBAFbVe27mIgHSQpsY1Q7XZiNc4/6gx5LS6ZStS6LG\n7BJ8dNVI0lkUmcDrudHr9EgwW62nV3OZqdPlt9EuWSRY3GguLmLYauRwCy0gUCCk\nMpXRAJi70/33MvJJrsZ64Ee+bs7Lo3I6LWldy8joRTnU+kLBEUx3XZL7av9YROXr\ngZ6voJmtvqkBZss4HTzfQx/0TW60uhdG/H39h4F5ag0zD/ov+BS5gLNdTaqX4fnk\nGMX41TiMJjz98iji7lpJiCzfeT2OnpA8vUFKOt1b9pq0zj8lMH8yfaIDlNDceqFS\n3m6TjRgm/VWsvY+b0s+v54Ysyx8Jb6NvqYTUc79NoXQbTiNg8swOqn+knEwlqLJm\nOzj/2ZQw9nKEvmhVEA/GcywWaZMH/rFF7buiVWqw2rVKAiUnhde3t4ZEFolsgCs+\nl6mc1X5VTMbeRRAc6uk7nwNT7u56AQIWeNTowr5GdogTPyK7SBIdUgC0An4hGh6c\nJfTzPV4e0hz5sy229zdcxsshTrD3mUcYhcErulWuBurQB7Lcq9CClnXO0lD+mefP\nL5/ndtFhKvshuzHQqp9HpLIiyhY6UFfEW0NnxWViA0kB60PZ2Pierc+xYw5F9KBa\nLJstxabArahH9CdMOA0uG0k7UvToiIMrVCjU8jVStDKDYmlkDJGcn5fqdBb9HxEG\nmpv0\n-----END CERTIFICATE-----\n\n# Issuer: CN=Entrust Root Certification Authority - G4 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2015 Entrust, Inc. - for authorized use only\n# Subject: CN=Entrust Root Certification Authority - G4 O=Entrust, Inc. OU=See www.entrust.net/legal-terms/(c) 2015 Entrust, Inc. - for authorized use only\n# Label: \"Entrust Root Certification Authority - G4\"\n# Serial: 289383649854506086828220374796556676440\n# MD5 Fingerprint: 89:53:f1:83:23:b7:7c:8e:05:f1:8c:71:38:4e:1f:88\n# SHA1 Fingerprint: 14:88:4e:86:26:37:b0:26:af:59:62:5c:40:77:ec:35:29:ba:96:01\n# SHA256 Fingerprint: db:35:17:d1:f6:73:2a:2d:5a:b9:7c:53:3e:c7:07:79:ee:32:70:a6:2f:b4:ac:42:38:37:24:60:e6:f0:1e:88\n-----BEGIN CERTIFICATE-----\nMIIGSzCCBDOgAwIBAgIRANm1Q3+vqTkPAAAAAFVlrVgwDQYJKoZIhvcNAQELBQAw\ngb4xCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQL\nEx9TZWUgd3d3LmVudHJ1c3QubmV0L2xlZ2FsLXRlcm1zMTkwNwYDVQQLEzAoYykg\nMjAxNSBFbnRydXN0LCBJbmMuIC0gZm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxMjAw\nBgNVBAMTKUVudHJ1c3QgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEc0\nMB4XDTE1MDUyNzExMTExNloXDTM3MTIyNzExNDExNlowgb4xCzAJBgNVBAYTAlVT\nMRYwFAYDVQQKEw1FbnRydXN0LCBJbmMuMSgwJgYDVQQLEx9TZWUgd3d3LmVudHJ1\nc3QubmV0L2xlZ2FsLXRlcm1zMTkwNwYDVQQLEzAoYykgMjAxNSBFbnRydXN0LCBJ\nbmMuIC0gZm9yIGF1dGhvcml6ZWQgdXNlIG9ubHkxMjAwBgNVBAMTKUVudHJ1c3Qg\nUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eSAtIEc0MIICIjANBgkqhkiG9w0B\nAQEFAAOCAg8AMIICCgKCAgEAsewsQu7i0TD/pZJH4i3DumSXbcr3DbVZwbPLqGgZ\n2K+EbTBwXX7zLtJTmeH+H17ZSK9dE43b/2MzTdMAArzE+NEGCJR5WIoV3imz/f3E\nT+iq4qA7ec2/a0My3dl0ELn39GjUu9CH1apLiipvKgS1sqbHoHrmSKvS0VnM1n4j\n5pds8ELl3FFLFUHtSUrJ3hCX1nbB76W1NhSXNdh4IjVS70O92yfbYVaCNNzLiGAM\nC1rlLAHGVK/XqsEQe9IFWrhAnoanw5CGAlZSCXqc0ieCU0plUmr1POeo8pyvi73T\nDtTUXm6Hnmo9RR3RXRv06QqsYJn7ibT/mCzPfB3pAqoEmh643IhuJbNsZvc8kPNX\nwbMv9W3y+8qh+CmdRouzavbmZwe+LGcKKh9asj5XxNMhIWNlUpEbsZmOeX7m640A\n2Vqq6nPopIICR5b+W45UYaPrL0swsIsjdXJ8ITzI9vF01Bx7owVV7rtNOzK+mndm\nnqxpkCIHH2E6lr7lmk/MBTwoWdPBDFSoWWG9yHJM6Nyfh3+9nEg2XpWjDrk4JFX8\ndWbrAuMINClKxuMrLzOg2qOGpRKX/YAr2hRC45K9PvJdXmd0LhyIRyk0X+IyqJwl\nN4y6mACXi0mWHv0liqzc2thddG5msP9E36EYxr5ILzeUePiVSj9/E15dWf10hkNj\nc0kCAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD\nVR0OBBYEFJ84xFYjwznooHFs6FRM5Og6sb9nMA0GCSqGSIb3DQEBCwUAA4ICAQAS\n5UKme4sPDORGpbZgQIeMJX6tuGguW8ZAdjwD+MlZ9POrYs4QjbRaZIxowLByQzTS\nGwv2LFPSypBLhmb8qoMi9IsabyZIrHZ3CL/FmFz0Jomee8O5ZDIBf9PD3Vht7LGr\nhFV0d4QEJ1JrhkzO3bll/9bGXp+aEJlLdWr+aumXIOTkdnrG0CSqkM0gkLpHZPt/\nB7NTeLUKYvJzQ85BK4FqLoUWlFPUa19yIqtRLULVAJyZv967lDtX/Zr1hstWO1uI\nAeV8KEsD+UmDfLJ/fOPtjqF/YFOOVZ1QNBIPt5d7bIdKROf1beyAN/BYGW5KaHbw\nH5Lk6rWS02FREAutp9lfx1/cH6NcjKF+m7ee01ZvZl4HliDtC3T7Zk6LERXpgUl+\nb7DUUH8i119lAg2m9IUe2K4GS0qn0jFmwvjO5QimpAKWRGhXxNUzzxkvFMSUHHuk\n2fCfDrGA4tGeEWSpiBE6doLlYsKA2KSD7ZPvfC+QsDJMlhVoSFLUmQjAJOgc47Ol\nIQ6SwJAfzyBfyjs4x7dtOvPmRLgOMWuIjnDrnBdSqEGULoe256YSxXXfW8AKbnuk\n5F6G+TaU33fD6Q3AOfF5u0aOq0NZJ7cguyPpVkAh7DE9ZapD8j3fcEThuk0mEDuY\nn/PIjhs4ViFqUZPTkcpG2om3PVODLAgfi49T3f+sHw==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Microsoft ECC Root Certificate Authority 2017 O=Microsoft Corporation\n# Subject: CN=Microsoft ECC Root Certificate Authority 2017 O=Microsoft Corporation\n# Label: \"Microsoft ECC Root Certificate Authority 2017\"\n# Serial: 136839042543790627607696632466672567020\n# MD5 Fingerprint: dd:a1:03:e6:4a:93:10:d1:bf:f0:19:42:cb:fe:ed:67\n# SHA1 Fingerprint: 99:9a:64:c3:7f:f4:7d:9f:ab:95:f1:47:69:89:14:60:ee:c4:c3:c5\n# SHA256 Fingerprint: 35:8d:f3:9d:76:4a:f9:e1:b7:66:e9:c9:72:df:35:2e:e1:5c:fa:c2:27:af:6a:d1:d7:0e:8e:4a:6e:dc:ba:02\n-----BEGIN CERTIFICATE-----\nMIICWTCCAd+gAwIBAgIQZvI9r4fei7FK6gxXMQHC7DAKBggqhkjOPQQDAzBlMQsw\nCQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYD\nVQQDEy1NaWNyb3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIw\nMTcwHhcNMTkxMjE4MjMwNjQ1WhcNNDIwNzE4MjMxNjA0WjBlMQswCQYDVQQGEwJV\nUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1NaWNy\nb3NvZnQgRUNDIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwdjAQBgcq\nhkjOPQIBBgUrgQQAIgNiAATUvD0CQnVBEyPNgASGAlEvaqiBYgtlzPbKnR5vSmZR\nogPZnZH6thaxjG7efM3beaYvzrvOcS/lpaso7GMEZpn4+vKTEAXhgShC48Zo9OYb\nhGBKia/teQ87zvH2RPUBeMCjVDBSMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8E\nBTADAQH/MB0GA1UdDgQWBBTIy5lycFIM+Oa+sgRXKSrPQhDtNTAQBgkrBgEEAYI3\nFQEEAwIBADAKBggqhkjOPQQDAwNoADBlAjBY8k3qDPlfXu5gKcs68tvWMoQZP3zV\nL8KxzJOuULsJMsbG7X7JNpQS5GiFBqIb0C8CMQCZ6Ra0DvpWSNSkMBaReNtUjGUB\niudQZsIxtzm6uBoiB078a1QWIP8rtedMDE2mT3M=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Microsoft RSA Root Certificate Authority 2017 O=Microsoft Corporation\n# Subject: CN=Microsoft RSA Root Certificate Authority 2017 O=Microsoft Corporation\n# Label: \"Microsoft RSA Root Certificate Authority 2017\"\n# Serial: 40975477897264996090493496164228220339\n# MD5 Fingerprint: 10:ff:00:ff:cf:c9:f8:c7:7a:c0:ee:35:8e:c9:0f:47\n# SHA1 Fingerprint: 73:a5:e6:4a:3b:ff:83:16:ff:0e:dc:cc:61:8a:90:6e:4e:ae:4d:74\n# SHA256 Fingerprint: c7:41:f7:0f:4b:2a:8d:88:bf:2e:71:c1:41:22:ef:53:ef:10:eb:a0:cf:a5:e6:4c:fa:20:f4:18:85:30:73:e0\n-----BEGIN CERTIFICATE-----\nMIIFqDCCA5CgAwIBAgIQHtOXCV/YtLNHcB6qvn9FszANBgkqhkiG9w0BAQwFADBl\nMQswCQYDVQQGEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYw\nNAYDVQQDEy1NaWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5\nIDIwMTcwHhcNMTkxMjE4MjI1MTIyWhcNNDIwNzE4MjMwMDIzWjBlMQswCQYDVQQG\nEwJVUzEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMTYwNAYDVQQDEy1N\naWNyb3NvZnQgUlNBIFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTcwggIi\nMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKW76UM4wplZEWCpW9R2LBifOZ\nNt9GkMml7Xhqb0eRaPgnZ1AzHaGm++DlQ6OEAlcBXZxIQIJTELy/xztokLaCLeX0\nZdDMbRnMlfl7rEqUrQ7eS0MdhweSE5CAg2Q1OQT85elss7YfUJQ4ZVBcF0a5toW1\nHLUX6NZFndiyJrDKxHBKrmCk3bPZ7Pw71VdyvD/IybLeS2v4I2wDwAW9lcfNcztm\ngGTjGqwu+UcF8ga2m3P1eDNbx6H7JyqhtJqRjJHTOoI+dkC0zVJhUXAoP8XFWvLJ\njEm7FFtNyP9nTUwSlq31/niol4fX/V4ggNyhSyL71Imtus5Hl0dVe49FyGcohJUc\naDDv70ngNXtk55iwlNpNhTs+VcQor1fznhPbRiefHqJeRIOkpcrVE7NLP8TjwuaG\nYaRSMLl6IE9vDzhTyzMMEyuP1pq9KsgtsRx9S1HKR9FIJ3Jdh+vVReZIZZ2vUpC6\nW6IYZVcSn2i51BVrlMRpIpj0M+Dt+VGOQVDJNE92kKz8OMHY4Xu54+OU4UZpyw4K\nUGsTuqwPN1q3ErWQgR5WrlcihtnJ0tHXUeOrO8ZV/R4O03QK0dqq6mm4lyiPSMQH\n+FJDOvTKVTUssKZqwJz58oHhEmrARdlns87/I6KJClTUFLkqqNfs+avNJVgyeY+Q\nW5g5xAgGwax/Dj0ApQIDAQABo1QwUjAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/\nBAUwAwEB/zAdBgNVHQ4EFgQUCctZf4aycI8awznjwNnpv7tNsiMwEAYJKwYBBAGC\nNxUBBAMCAQAwDQYJKoZIhvcNAQEMBQADggIBAKyvPl3CEZaJjqPnktaXFbgToqZC\nLgLNFgVZJ8og6Lq46BrsTaiXVq5lQ7GPAJtSzVXNUzltYkyLDVt8LkS/gxCP81OC\ngMNPOsduET/m4xaRhPtthH80dK2Jp86519efhGSSvpWhrQlTM93uCupKUY5vVau6\ntZRGrox/2KJQJWVggEbbMwSubLWYdFQl3JPk+ONVFT24bcMKpBLBaYVu32TxU5nh\nSnUgnZUP5NbcA/FZGOhHibJXWpS2qdgXKxdJ5XbLwVaZOjex/2kskZGT4d9Mozd2\nTaGf+G0eHdP67Pv0RR0Tbc/3WeUiJ3IrhvNXuzDtJE3cfVa7o7P4NHmJweDyAmH3\npvwPuxwXC65B2Xy9J6P9LjrRk5Sxcx0ki69bIImtt2dmefU6xqaWM/5TkshGsRGR\nxpl/j8nWZjEgQRCHLQzWwa80mMpkg/sTV9HB8Dx6jKXB/ZUhoHHBk2dxEuqPiApp\nGWSZI1b7rCoucL5mxAyE7+WL85MB+GqQk2dLsmijtWKP6T+MejteD+eMuMZ87zf9\ndOLITzNy4ZQ5bb0Sr74MTnB8G2+NszKTc0QWbej09+CVgI+WXTik9KveCjCHk9hN\nAHFiRSdLOkKEW39lt2c0Ui2cFmuqqNh7o0JMcccMyj6D5KbvtwEwXlGjefVwaaZB\nRA+GsCyRxj3qrg+E\n-----END CERTIFICATE-----\n\n# Issuer: CN=e-Szigno Root CA 2017 O=Microsec Ltd.\n# Subject: CN=e-Szigno Root CA 2017 O=Microsec Ltd.\n# Label: \"e-Szigno Root CA 2017\"\n# Serial: 411379200276854331539784714\n# MD5 Fingerprint: de:1f:f6:9e:84:ae:a7:b4:21:ce:1e:58:7d:d1:84:98\n# SHA1 Fingerprint: 89:d4:83:03:4f:9e:9a:48:80:5f:72:37:d4:a9:a6:ef:cb:7c:1f:d1\n# SHA256 Fingerprint: be:b0:0b:30:83:9b:9b:c3:2c:32:e4:44:79:05:95:06:41:f2:64:21:b1:5e:d0:89:19:8b:51:8a:e2:ea:1b:99\n-----BEGIN CERTIFICATE-----\nMIICQDCCAeWgAwIBAgIMAVRI7yH9l1kN9QQKMAoGCCqGSM49BAMCMHExCzAJBgNV\nBAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDEWMBQGA1UECgwNTWljcm9zZWMgTHRk\nLjEXMBUGA1UEYQwOVkFUSFUtMjM1ODQ0OTcxHjAcBgNVBAMMFWUtU3ppZ25vIFJv\nb3QgQ0EgMjAxNzAeFw0xNzA4MjIxMjA3MDZaFw00MjA4MjIxMjA3MDZaMHExCzAJ\nBgNVBAYTAkhVMREwDwYDVQQHDAhCdWRhcGVzdDEWMBQGA1UECgwNTWljcm9zZWMg\nTHRkLjEXMBUGA1UEYQwOVkFUSFUtMjM1ODQ0OTcxHjAcBgNVBAMMFWUtU3ppZ25v\nIFJvb3QgQ0EgMjAxNzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABJbcPYrYsHtv\nxie+RJCxs1YVe45DJH0ahFnuY2iyxl6H0BVIHqiQrb1TotreOpCmYF9oMrWGQd+H\nWyx7xf58etqjYzBhMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0G\nA1UdDgQWBBSHERUI0arBeAyxr87GyZDvvzAEwDAfBgNVHSMEGDAWgBSHERUI0arB\neAyxr87GyZDvvzAEwDAKBggqhkjOPQQDAgNJADBGAiEAtVfd14pVCzbhhkT61Nlo\njbjcI4qKDdQvfepz7L9NbKgCIQDLpbQS+ue16M9+k/zzNY9vTlp8tLxOsvxyqltZ\n+efcMQ==\n-----END CERTIFICATE-----\n\n# Issuer: O=CERTSIGN SA OU=certSIGN ROOT CA G2\n# Subject: O=CERTSIGN SA OU=certSIGN ROOT CA G2\n# Label: \"certSIGN Root CA G2\"\n# Serial: 313609486401300475190\n# MD5 Fingerprint: 8c:f1:75:8a:c6:19:cf:94:b7:f7:65:20:87:c3:97:c7\n# SHA1 Fingerprint: 26:f9:93:b4:ed:3d:28:27:b0:b9:4b:a7:e9:15:1d:a3:8d:92:e5:32\n# SHA256 Fingerprint: 65:7c:fe:2f:a7:3f:aa:38:46:25:71:f3:32:a2:36:3a:46:fc:e7:02:09:51:71:07:02:cd:fb:b6:ee:da:33:05\n-----BEGIN CERTIFICATE-----\nMIIFRzCCAy+gAwIBAgIJEQA0tk7GNi02MA0GCSqGSIb3DQEBCwUAMEExCzAJBgNV\nBAYTAlJPMRQwEgYDVQQKEwtDRVJUU0lHTiBTQTEcMBoGA1UECxMTY2VydFNJR04g\nUk9PVCBDQSBHMjAeFw0xNzAyMDYwOTI3MzVaFw00MjAyMDYwOTI3MzVaMEExCzAJ\nBgNVBAYTAlJPMRQwEgYDVQQKEwtDRVJUU0lHTiBTQTEcMBoGA1UECxMTY2VydFNJ\nR04gUk9PVCBDQSBHMjCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMDF\ndRmRfUR0dIf+DjuW3NgBFszuY5HnC2/OOwppGnzC46+CjobXXo9X69MhWf05N0Iw\nvlDqtg+piNguLWkh59E3GE59kdUWX2tbAMI5Qw02hVK5U2UPHULlj88F0+7cDBrZ\nuIt4ImfkabBoxTzkbFpG583H+u/E7Eu9aqSs/cwoUe+StCmrqzWaTOTECMYmzPhp\nn+Sc8CnTXPnGFiWeI8MgwT0PPzhAsP6CRDiqWhqKa2NYOLQV07YRaXseVO6MGiKs\ncpc/I1mbySKEwQdPzH/iV8oScLumZfNpdWO9lfsbl83kqK/20U6o2YpxJM02PbyW\nxPFsqa7lzw1uKA2wDrXKUXt4FMMgL3/7FFXhEZn91QqhngLjYl/rNUssuHLoPj1P\nrCy7Lobio3aP5ZMqz6WryFyNSwb/EkaseMsUBzXgqd+L6a8VTxaJW732jcZZroiF\nDsGJ6x9nxUWO/203Nit4ZoORUSs9/1F3dmKh7Gc+PoGD4FapUB8fepmrY7+EF3fx\nDTvf95xhszWYijqy7DwaNz9+j5LP2RIUZNoQAhVB/0/E6xyjyfqZ90bp4RjZsbgy\nLcsUDFDYg2WD7rlcz8sFWkz6GZdr1l0T08JcVLwyc6B49fFtHsufpaafItzRUZ6C\neWRgKRM+o/1Pcmqr4tTluCRVLERLiohEnMqE0yo7AgMBAAGjQjBAMA8GA1UdEwEB\n/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBSCIS1mxteg4BXrzkwJ\nd8RgnlRuAzANBgkqhkiG9w0BAQsFAAOCAgEAYN4auOfyYILVAzOBywaK8SJJ6ejq\nkX/GM15oGQOGO0MBzwdw5AgeZYWR5hEit/UCI46uuR59H35s5r0l1ZUa8gWmr4UC\nb6741jH/JclKyMeKqdmfS0mbEVeZkkMR3rYzpMzXjWR91M08KCy0mpbqTfXERMQl\nqiCA2ClV9+BB/AYm/7k29UMUA2Z44RGx2iBfRgB4ACGlHgAoYXhvqAEBj500mv/0\nOJD7uNGzcgbJceaBxXntC6Z58hMLnPddDnskk7RI24Zf3lCGeOdA5jGokHZwYa+c\nNywRtYK3qq4kNFtyDGkNzVmf9nGvnAvRCjj5BiKDUyUM/FHE5r7iOZULJK2v0ZXk\nltd0ZGtxTgI8qoXzIKNDOXZbbFD+mpwUHmUUihW9o4JFWklWatKcsWMy5WHgUyIO\npwpJ6st+H6jiYoD2EEVSmAYY3qXNL3+q1Ok+CHLsIwMCPKaq2LxndD0UF/tUSxfj\n03k9bWtJySgOLnRQvwzZRjoQhsmnP+mg7H/rpXdYaXHmgwo38oZJar55CJD2AhZk\nPuXaTH4MNMn5X7azKFGnpyuqSfqNZSlO42sTp5SjLVFteAxEy9/eCG/Oo2Sr05WE\n1LlSVHJ7liXMvGnjSG4N0MedJ5qq+BOS3R7fY581qRY27Iy4g/Q9iY/NtBde17MX\nQRBdJ3NghVdJIgc=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Trustwave Global Certification Authority O=Trustwave Holdings, Inc.\n# Subject: CN=Trustwave Global Certification Authority O=Trustwave Holdings, Inc.\n# Label: \"Trustwave Global Certification Authority\"\n# Serial: 1846098327275375458322922162\n# MD5 Fingerprint: f8:1c:18:2d:2f:ba:5f:6d:a1:6c:bc:c7:ab:91:c7:0e\n# SHA1 Fingerprint: 2f:8f:36:4f:e1:58:97:44:21:59:87:a5:2a:9a:d0:69:95:26:7f:b5\n# SHA256 Fingerprint: 97:55:20:15:f5:dd:fc:3c:87:88:c0:06:94:45:55:40:88:94:45:00:84:f1:00:86:70:86:bc:1a:2b:b5:8d:c8\n-----BEGIN CERTIFICATE-----\nMIIF2jCCA8KgAwIBAgIMBfcOhtpJ80Y1LrqyMA0GCSqGSIb3DQEBCwUAMIGIMQsw\nCQYDVQQGEwJVUzERMA8GA1UECAwISWxsaW5vaXMxEDAOBgNVBAcMB0NoaWNhZ28x\nITAfBgNVBAoMGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjExMC8GA1UEAwwoVHJ1\nc3R3YXZlIEdsb2JhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0xNzA4MjMx\nOTM0MTJaFw00MjA4MjMxOTM0MTJaMIGIMQswCQYDVQQGEwJVUzERMA8GA1UECAwI\nSWxsaW5vaXMxEDAOBgNVBAcMB0NoaWNhZ28xITAfBgNVBAoMGFRydXN0d2F2ZSBI\nb2xkaW5ncywgSW5jLjExMC8GA1UEAwwoVHJ1c3R3YXZlIEdsb2JhbCBDZXJ0aWZp\nY2F0aW9uIEF1dGhvcml0eTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIB\nALldUShLPDeS0YLOvR29zd24q88KPuFd5dyqCblXAj7mY2Hf8g+CY66j96xz0Xzn\nswuvCAAJWX/NKSqIk4cXGIDtiLK0thAfLdZfVaITXdHG6wZWiYj+rDKd/VzDBcdu\n7oaJuogDnXIhhpCujwOl3J+IKMujkkkP7NAP4m1ET4BqstTnoApTAbqOl5F2brz8\n1Ws25kCI1nsvXwXoLG0R8+eyvpJETNKXpP7ScoFDB5zpET71ixpZfR9oWN0EACyW\n80OzfpgZdNmcc9kYvkHHNHnZ9GLCQ7mzJ7Aiy/k9UscwR7PJPrhq4ufogXBeQotP\nJqX+OsIgbrv4Fo7NDKm0G2x2EOFYeUY+VM6AqFcJNykbmROPDMjWLBz7BegIlT1l\nRtzuzWniTY+HKE40Cz7PFNm73bZQmq131BnW2hqIyE4bJ3XYsgjxroMwuREOzYfw\nhI0Vcnyh78zyiGG69Gm7DIwLdVcEuE4qFC49DxweMqZiNu5m4iK4BUBjECLzMx10\ncoos9TkpoNPnG4CELcU9402x/RpvumUHO1jsQkUm+9jaJXLE9gCxInm943xZYkqc\nBW89zubWR2OZxiRvchLIrH+QtAuRcOi35hYQcRfO3gZPSEF9NUqjifLJS3tBEW1n\ntwiYTOURGa5CgNz7kAXU+FDKvuStx8KU1xad5hePrzb7AgMBAAGjQjBAMA8GA1Ud\nEwEB/wQFMAMBAf8wHQYDVR0OBBYEFJngGWcNYtt2s9o9uFvo/ULSMQ6HMA4GA1Ud\nDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAmHNw4rDT7TnsTGDZqRKGFx6W\n0OhUKDtkLSGm+J1WE2pIPU/HPinbbViDVD2HfSMF1OQc3Og4ZYbFdada2zUFvXfe\nuyk3QAUHw5RSn8pk3fEbK9xGChACMf1KaA0HZJDmHvUqoai7PF35owgLEQzxPy0Q\nlG/+4jSHg9bP5Rs1bdID4bANqKCqRieCNqcVtgimQlRXtpla4gt5kNdXElE1GYhB\naCXUNxeEFfsBctyV3lImIJgm4nb1J2/6ADtKYdkNy1GTKv0WBpanI5ojSP5RvbbE\nsLFUzt5sQa0WZ37b/TjNuThOssFgy50X31ieemKyJo90lZvkWx3SD92YHJtZuSPT\nMaCm/zjdzyBP6VhWOmfD0faZmZ26NraAL4hHT4a/RDqA5Dccprrql5gR0IRiR2Qe\nqu5AvzSxnI9O4fKSTx+O856X3vOmeWqJcU9LJxdI/uz0UA9PSX3MReO9ekDFQdxh\nVicGaeVyQYHTtgGJoC86cnn+OjC/QezHYj6RS8fZMXZC+fc8Y+wmjHMMfRod6qh8\nh6jCJ3zhM0EPz8/8AKAigJ5Kp28AsEFFtyLKaEjFQqKu3R3y4G5OBVixwJAWKqQ9\nEEC+j2Jjg6mcgn0tAumDMHzLJ8n9HmYAsC7TIS+OMxZsmO0QqAfWzJPP29FpHOTK\nyeC2nOnOcXHebD8WpHk=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Trustwave Global ECC P256 Certification Authority O=Trustwave Holdings, Inc.\n# Subject: CN=Trustwave Global ECC P256 Certification Authority O=Trustwave Holdings, Inc.\n# Label: \"Trustwave Global ECC P256 Certification Authority\"\n# Serial: 4151900041497450638097112925\n# MD5 Fingerprint: 5b:44:e3:8d:5d:36:86:26:e8:0d:05:d2:59:a7:83:54\n# SHA1 Fingerprint: b4:90:82:dd:45:0c:be:8b:5b:b1:66:d3:e2:a4:08:26:cd:ed:42:cf\n# SHA256 Fingerprint: 94:5b:bc:82:5e:a5:54:f4:89:d1:fd:51:a7:3d:df:2e:a6:24:ac:70:19:a0:52:05:22:5c:22:a7:8c:cf:a8:b4\n-----BEGIN CERTIFICATE-----\nMIICYDCCAgegAwIBAgIMDWpfCD8oXD5Rld9dMAoGCCqGSM49BAMCMIGRMQswCQYD\nVQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAf\nBgNVBAoTGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3\nYXZlIEdsb2JhbCBFQ0MgUDI1NiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0x\nNzA4MjMxOTM1MTBaFw00MjA4MjMxOTM1MTBaMIGRMQswCQYDVQQGEwJVUzERMA8G\nA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAfBgNVBAoTGFRydXN0\nd2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3YXZlIEdsb2JhbCBF\nQ0MgUDI1NiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTBZMBMGByqGSM49AgEGCCqG\nSM49AwEHA0IABH77bOYj43MyCMpg5lOcunSNGLB4kFKA3TjASh3RqMyTpJcGOMoN\nFWLGjgEqZZ2q3zSRLoHB5DOSMcT9CTqmP62jQzBBMA8GA1UdEwEB/wQFMAMBAf8w\nDwYDVR0PAQH/BAUDAwcGADAdBgNVHQ4EFgQUo0EGrJBt0UrrdaVKEJmzsaGLSvcw\nCgYIKoZIzj0EAwIDRwAwRAIgB+ZU2g6gWrKuEZ+Hxbb/ad4lvvigtwjzRM4q3wgh\nDDcCIC0mA6AFvWvR9lz4ZcyGbbOcNEhjhAnFjXca4syc4XR7\n-----END CERTIFICATE-----\n\n# Issuer: CN=Trustwave Global ECC P384 Certification Authority O=Trustwave Holdings, Inc.\n# Subject: CN=Trustwave Global ECC P384 Certification Authority O=Trustwave Holdings, Inc.\n# Label: \"Trustwave Global ECC P384 Certification Authority\"\n# Serial: 2704997926503831671788816187\n# MD5 Fingerprint: ea:cf:60:c4:3b:b9:15:29:40:a1:97:ed:78:27:93:d6\n# SHA1 Fingerprint: e7:f3:a3:c8:cf:6f:c3:04:2e:6d:0e:67:32:c5:9e:68:95:0d:5e:d2\n# SHA256 Fingerprint: 55:90:38:59:c8:c0:c3:eb:b8:75:9e:ce:4e:25:57:22:5f:f5:75:8b:bd:38:eb:d4:82:76:60:1e:1b:d5:80:97\n-----BEGIN CERTIFICATE-----\nMIICnTCCAiSgAwIBAgIMCL2Fl2yZJ6SAaEc7MAoGCCqGSM49BAMDMIGRMQswCQYD\nVQQGEwJVUzERMA8GA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAf\nBgNVBAoTGFRydXN0d2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3\nYXZlIEdsb2JhbCBFQ0MgUDM4NCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0x\nNzA4MjMxOTM2NDNaFw00MjA4MjMxOTM2NDNaMIGRMQswCQYDVQQGEwJVUzERMA8G\nA1UECBMISWxsaW5vaXMxEDAOBgNVBAcTB0NoaWNhZ28xITAfBgNVBAoTGFRydXN0\nd2F2ZSBIb2xkaW5ncywgSW5jLjE6MDgGA1UEAxMxVHJ1c3R3YXZlIEdsb2JhbCBF\nQ0MgUDM4NCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTB2MBAGByqGSM49AgEGBSuB\nBAAiA2IABGvaDXU1CDFHBa5FmVXxERMuSvgQMSOjfoPTfygIOiYaOs+Xgh+AtycJ\nj9GOMMQKmw6sWASr9zZ9lCOkmwqKi6vr/TklZvFe/oyujUF5nQlgziip04pt89ZF\n1PKYhDhloKNDMEEwDwYDVR0TAQH/BAUwAwEB/zAPBgNVHQ8BAf8EBQMDBwYAMB0G\nA1UdDgQWBBRVqYSJ0sEyvRjLbKYHTsjnnb6CkDAKBggqhkjOPQQDAwNnADBkAjA3\nAZKXRRJ+oPM+rRk6ct30UJMDEr5E0k9BpIycnR+j9sKS50gU/k6bpZFXrsY3crsC\nMGclCrEMXu6pY5Jv5ZAL/mYiykf9ijH3g/56vxC+GCsej/YpHpRZ744hN8tRmKVu\nSw==\n-----END CERTIFICATE-----\n\n# Issuer: CN=NAVER Global Root Certification Authority O=NAVER BUSINESS PLATFORM Corp.\n# Subject: CN=NAVER Global Root Certification Authority O=NAVER BUSINESS PLATFORM Corp.\n# Label: \"NAVER Global Root Certification Authority\"\n# Serial: 9013692873798656336226253319739695165984492813\n# MD5 Fingerprint: c8:7e:41:f6:25:3b:f5:09:b3:17:e8:46:3d:bf:d0:9b\n# SHA1 Fingerprint: 8f:6b:f2:a9:27:4a:da:14:a0:c4:f4:8e:61:27:f9:c0:1e:78:5d:d1\n# SHA256 Fingerprint: 88:f4:38:dc:f8:ff:d1:fa:8f:42:91:15:ff:e5:f8:2a:e1:e0:6e:0c:70:c3:75:fa:ad:71:7b:34:a4:9e:72:65\n-----BEGIN CERTIFICATE-----\nMIIFojCCA4qgAwIBAgIUAZQwHqIL3fXFMyqxQ0Rx+NZQTQ0wDQYJKoZIhvcNAQEM\nBQAwaTELMAkGA1UEBhMCS1IxJjAkBgNVBAoMHU5BVkVSIEJVU0lORVNTIFBMQVRG\nT1JNIENvcnAuMTIwMAYDVQQDDClOQVZFUiBHbG9iYWwgUm9vdCBDZXJ0aWZpY2F0\naW9uIEF1dGhvcml0eTAeFw0xNzA4MTgwODU4NDJaFw0zNzA4MTgyMzU5NTlaMGkx\nCzAJBgNVBAYTAktSMSYwJAYDVQQKDB1OQVZFUiBCVVNJTkVTUyBQTEFURk9STSBD\nb3JwLjEyMDAGA1UEAwwpTkFWRVIgR2xvYmFsIFJvb3QgQ2VydGlmaWNhdGlvbiBB\ndXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC21PGTXLVA\niQqrDZBbUGOukJR0F0Vy1ntlWilLp1agS7gvQnXp2XskWjFlqxcX0TM62RHcQDaH\n38dq6SZeWYp34+hInDEW+j6RscrJo+KfziFTowI2MMtSAuXaMl3Dxeb57hHHi8lE\nHoSTGEq0n+USZGnQJoViAbbJAh2+g1G7XNr4rRVqmfeSVPc0W+m/6imBEtRTkZaz\nkVrd/pBzKPswRrXKCAfHcXLJZtM0l/aM9BhK4dA9WkW2aacp+yPOiNgSnABIqKYP\nszuSjXEOdMWLyEz59JuOuDxp7W87UC9Y7cSw0BwbagzivESq2M0UXZR4Yb8Obtoq\nvC8MC3GmsxY/nOb5zJ9TNeIDoKAYv7vxvvTWjIcNQvcGufFt7QSUqP620wbGQGHf\nnZ3zVHbOUzoBppJB7ASjjw2i1QnK1sua8e9DXcCrpUHPXFNwcMmIpi3Ua2FzUCaG\nYQ5fG8Ir4ozVu53BA0K6lNpfqbDKzE0K70dpAy8i+/Eozr9dUGWokG2zdLAIx6yo\n0es+nPxdGoMuK8u180SdOqcXYZaicdNwlhVNt0xz7hlcxVs+Qf6sdWA7G2POAN3a\nCJBitOUt7kinaxeZVL6HSuOpXgRM6xBtVNbv8ejyYhbLgGvtPe31HzClrkvJE+2K\nAQHJuFFYwGY6sWZLxNUxAmLpdIQM201GLQIDAQABo0IwQDAdBgNVHQ4EFgQU0p+I\n36HNLL3s9TsBAZMzJ7LrYEswDgYDVR0PAQH/BAQDAgEGMA8GA1UdEwEB/wQFMAMB\nAf8wDQYJKoZIhvcNAQEMBQADggIBADLKgLOdPVQG3dLSLvCkASELZ0jKbY7gyKoN\nqo0hV4/GPnrK21HUUrPUloSlWGB/5QuOH/XcChWB5Tu2tyIvCZwTFrFsDDUIbatj\ncu3cvuzHV+YwIHHW1xDBE1UBjCpD5EHxzzp6U5LOogMFDTjfArsQLtk70pt6wKGm\n+LUx5vR1yblTmXVHIloUFcd4G7ad6Qz4G3bxhYTeodoS76TiEJd6eN4MUZeoIUCL\nhr0N8F5OSza7OyAfikJW4Qsav3vQIkMsRIz75Sq0bBwcupTgE34h5prCy8VCZLQe\nlHsIJchxzIdFV4XTnyliIoNRlwAYl3dqmJLJfGBs32x9SuRwTMKeuB330DTHD8z7\np/8Dvq1wkNoL3chtl1+afwkyQf3NosxabUzyqkn+Zvjp2DXrDige7kgvOtB5CTh8\npiKCk5XQA76+AqAF3SAi428diDRgxuYKuQl1C/AH6GmWNcf7I4GOODm4RStDeKLR\nLBT/DShycpWbXgnbiUSYqqFJu3FS8r/2/yehNq+4tneI3TqkbZs0kNwUXTC/t+sX\n5Ie3cdCh13cV1ELX8vMxmV2b3RZtP+oGI/hGoiLtk/bdmuYqh7GYVPEi92tF4+KO\ndh2ajcQGjTa3FPOdVGm3jjzVpG2Tgbet9r1ke8LJaDmgkpzNNIaRkPpkUZ3+/uul\n9XXeifdy\n-----END CERTIFICATE-----\n\n# Issuer: CN=AC RAIZ FNMT-RCM SERVIDORES SEGUROS O=FNMT-RCM OU=Ceres\n# Subject: CN=AC RAIZ FNMT-RCM SERVIDORES SEGUROS O=FNMT-RCM OU=Ceres\n# Label: \"AC RAIZ FNMT-RCM SERVIDORES SEGUROS\"\n# Serial: 131542671362353147877283741781055151509\n# MD5 Fingerprint: 19:36:9c:52:03:2f:d2:d1:bb:23:cc:dd:1e:12:55:bb\n# SHA1 Fingerprint: 62:ff:d9:9e:c0:65:0d:03:ce:75:93:d2:ed:3f:2d:32:c9:e3:e5:4a\n# SHA256 Fingerprint: 55:41:53:b1:3d:2c:f9:dd:b7:53:bf:be:1a:4e:0a:e0:8d:0a:a4:18:70:58:fe:60:a2:b8:62:b2:e4:b8:7b:cb\n-----BEGIN CERTIFICATE-----\nMIICbjCCAfOgAwIBAgIQYvYybOXE42hcG2LdnC6dlTAKBggqhkjOPQQDAzB4MQsw\nCQYDVQQGEwJFUzERMA8GA1UECgwIRk5NVC1SQ00xDjAMBgNVBAsMBUNlcmVzMRgw\nFgYDVQRhDA9WQVRFUy1RMjgyNjAwNEoxLDAqBgNVBAMMI0FDIFJBSVogRk5NVC1S\nQ00gU0VSVklET1JFUyBTRUdVUk9TMB4XDTE4MTIyMDA5MzczM1oXDTQzMTIyMDA5\nMzczM1oweDELMAkGA1UEBhMCRVMxETAPBgNVBAoMCEZOTVQtUkNNMQ4wDAYDVQQL\nDAVDZXJlczEYMBYGA1UEYQwPVkFURVMtUTI4MjYwMDRKMSwwKgYDVQQDDCNBQyBS\nQUlaIEZOTVQtUkNNIFNFUlZJRE9SRVMgU0VHVVJPUzB2MBAGByqGSM49AgEGBSuB\nBAAiA2IABPa6V1PIyqvfNkpSIeSX0oNnnvBlUdBeh8dHsVnyV0ebAAKTRBdp20LH\nsbI6GA60XYyzZl2hNPk2LEnb80b8s0RpRBNm/dfF/a82Tc4DTQdxz69qBdKiQ1oK\nUm8BA06Oi6NCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD\nVR0OBBYEFAG5L++/EYZg8k/QQW6rcx/n0m5JMAoGCCqGSM49BAMDA2kAMGYCMQCu\nSuMrQMN0EfKVrRYj3k4MGuZdpSRea0R7/DjiT8ucRRcRTBQnJlU5dUoDzBOQn5IC\nMQD6SmxgiHPz7riYYqnOK8LZiqZwMR2vsJRM60/G49HzYqc8/5MuB1xJAWdpEgJy\nv+c=\n-----END CERTIFICATE-----\n\n# Issuer: CN=GlobalSign Root R46 O=GlobalSign nv-sa\n# Subject: CN=GlobalSign Root R46 O=GlobalSign nv-sa\n# Label: \"GlobalSign Root R46\"\n# Serial: 1552617688466950547958867513931858518042577\n# MD5 Fingerprint: c4:14:30:e4:fa:66:43:94:2a:6a:1b:24:5f:19:d0:ef\n# SHA1 Fingerprint: 53:a2:b0:4b:ca:6b:d6:45:e6:39:8a:8e:c4:0d:d2:bf:77:c3:a2:90\n# SHA256 Fingerprint: 4f:a3:12:6d:8d:3a:11:d1:c4:85:5a:4f:80:7c:ba:d6:cf:91:9d:3a:5a:88:b0:3b:ea:2c:63:72:d9:3c:40:c9\n-----BEGIN CERTIFICATE-----\nMIIFWjCCA0KgAwIBAgISEdK7udcjGJ5AXwqdLdDfJWfRMA0GCSqGSIb3DQEBDAUA\nMEYxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYD\nVQQDExNHbG9iYWxTaWduIFJvb3QgUjQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMy\nMDAwMDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYt\nc2ExHDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBSNDYwggIiMA0GCSqGSIb3DQEB\nAQUAA4ICDwAwggIKAoICAQCsrHQy6LNl5brtQyYdpokNRbopiLKkHWPd08EsCVeJ\nOaFV6Wc0dwxu5FUdUiXSE2te4R2pt32JMl8Nnp8semNgQB+msLZ4j5lUlghYruQG\nvGIFAha/r6gjA7aUD7xubMLL1aa7DOn2wQL7Id5m3RerdELv8HQvJfTqa1VbkNud\n316HCkD7rRlr+/fKYIje2sGP1q7Vf9Q8g+7XFkyDRTNrJ9CG0Bwta/OrffGFqfUo\n0q3v84RLHIf8E6M6cqJaESvWJ3En7YEtbWaBkoe0G1h6zD8K+kZPTXhc+CtI4wSE\ny132tGqzZfxCnlEmIyDLPRT5ge1lFgBPGmSXZgjPjHvjK8Cd+RTyG/FWaha/LIWF\nzXg4mutCagI0GIMXTpRW+LaCtfOW3T3zvn8gdz57GSNrLNRyc0NXfeD412lPFzYE\n+cCQYDdF3uYM2HSNrpyibXRdQr4G9dlkbgIQrImwTDsHTUB+JMWKmIJ5jqSngiCN\nI/onccnfxkF0oE32kRbcRoxfKWMxWXEM2G/CtjJ9++ZdU6Z+Ffy7dXxd7Pj2Fxzs\nx2sZy/N78CsHpdlseVR2bJ0cpm4O6XkMqCNqo98bMDGfsVR7/mrLZqrcZdCinkqa\nByFrgY/bxFn63iLABJzjqls2k+g9vXqhnQt2sQvHnf3PmKgGwvgqo6GDoLclcqUC\n4wIDAQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNV\nHQ4EFgQUA1yrc4GHqMywptWU4jaWSf8FmSwwDQYJKoZIhvcNAQEMBQADggIBAHx4\n7PYCLLtbfpIrXTncvtgdokIzTfnvpCo7RGkerNlFo048p9gkUbJUHJNOxO97k4Vg\nJuoJSOD1u8fpaNK7ajFxzHmuEajwmf3lH7wvqMxX63bEIaZHU1VNaL8FpO7XJqti\n2kM3S+LGteWygxk6x9PbTZ4IevPuzz5i+6zoYMzRx6Fcg0XERczzF2sUyQQCPtIk\npnnpHs6i58FZFZ8d4kuaPp92CC1r2LpXFNqD6v6MVenQTqnMdzGxRBF6XLE+0xRF\nFRhiJBPSy03OXIPBNvIQtQ6IbbjhVp+J3pZmOUdkLG5NrmJ7v2B0GbhWrJKsFjLt\nrWhV/pi60zTe9Mlhww6G9kuEYO4Ne7UyWHmRVSyBQ7N0H3qqJZ4d16GLuc1CLgSk\nZoNNiTW2bKg2SnkheCLQQrzRQDGQob4Ez8pn7fXwgNNgyYMqIgXQBztSvwyeqiv5\nu+YfjyW6hY0XHgL+XVAEV8/+LbzvXMAaq7afJMbfc2hIkCwU9D9SGuTSyxTDYWnP\n4vkYxboznxSjBF25cfe1lNj2M8FawTSLfJvdkzrnE6JwYZ+vj+vYxXX4M2bUdGc6\nN3ec592kD3ZDZopD8p/7DEJ4Y9HiD2971KE9dJeFt0g5QdYg/NA6s/rob8SKunE3\nvouXsXgxT7PntgMTzlSdriVZzH81Xwj3QEUxeCp6\n-----END CERTIFICATE-----\n\n# Issuer: CN=GlobalSign Root E46 O=GlobalSign nv-sa\n# Subject: CN=GlobalSign Root E46 O=GlobalSign nv-sa\n# Label: \"GlobalSign Root E46\"\n# Serial: 1552617690338932563915843282459653771421763\n# MD5 Fingerprint: b5:b8:66:ed:de:08:83:e3:c9:e2:01:34:06:ac:51:6f\n# SHA1 Fingerprint: 39:b4:6c:d5:fe:80:06:eb:e2:2f:4a:bb:08:33:a0:af:db:b9:dd:84\n# SHA256 Fingerprint: cb:b9:c4:4d:84:b8:04:3e:10:50:ea:31:a6:9f:51:49:55:d7:bf:d2:e2:c6:b4:93:01:01:9a:d6:1d:9f:50:58\n-----BEGIN CERTIFICATE-----\nMIICCzCCAZGgAwIBAgISEdK7ujNu1LzmJGjFDYQdmOhDMAoGCCqGSM49BAMDMEYx\nCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRwwGgYDVQQD\nExNHbG9iYWxTaWduIFJvb3QgRTQ2MB4XDTE5MDMyMDAwMDAwMFoXDTQ2MDMyMDAw\nMDAwMFowRjELMAkGA1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2Ex\nHDAaBgNVBAMTE0dsb2JhbFNpZ24gUm9vdCBFNDYwdjAQBgcqhkjOPQIBBgUrgQQA\nIgNiAAScDrHPt+ieUnd1NPqlRqetMhkytAepJ8qUuwzSChDH2omwlwxwEwkBjtjq\nR+q+soArzfwoDdusvKSGN+1wCAB16pMLey5SnCNoIwZD7JIvU4Tb+0cUB+hflGdd\nyXqBPCCjQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud\nDgQWBBQxCpCPtsad0kRLgLWi5h+xEk8blTAKBggqhkjOPQQDAwNoADBlAjEA31SQ\n7Zvvi5QCkxeCmb6zniz2C5GMn0oUsfZkvLtoURMMA/cVi4RguYv/Uo7njLwcAjA8\n+RHUjE7AwWHCFUyqqx0LMV87HOIAl0Qx5v5zli/altP+CAezNIm8BZ/3Hobui3A=\n-----END CERTIFICATE-----\n\n# Issuer: CN=GLOBALTRUST 2020 O=e-commerce monitoring GmbH\n# Subject: CN=GLOBALTRUST 2020 O=e-commerce monitoring GmbH\n# Label: \"GLOBALTRUST 2020\"\n# Serial: 109160994242082918454945253\n# MD5 Fingerprint: 8a:c7:6f:cb:6d:e3:cc:a2:f1:7c:83:fa:0e:78:d7:e8\n# SHA1 Fingerprint: d0:67:c1:13:51:01:0c:aa:d0:c7:6a:65:37:31:16:26:4f:53:71:a2\n# SHA256 Fingerprint: 9a:29:6a:51:82:d1:d4:51:a2:e3:7f:43:9b:74:da:af:a2:67:52:33:29:f9:0f:9a:0d:20:07:c3:34:e2:3c:9a\n-----BEGIN CERTIFICATE-----\nMIIFgjCCA2qgAwIBAgILWku9WvtPilv6ZeUwDQYJKoZIhvcNAQELBQAwTTELMAkG\nA1UEBhMCQVQxIzAhBgNVBAoTGmUtY29tbWVyY2UgbW9uaXRvcmluZyBHbWJIMRkw\nFwYDVQQDExBHTE9CQUxUUlVTVCAyMDIwMB4XDTIwMDIxMDAwMDAwMFoXDTQwMDYx\nMDAwMDAwMFowTTELMAkGA1UEBhMCQVQxIzAhBgNVBAoTGmUtY29tbWVyY2UgbW9u\naXRvcmluZyBHbWJIMRkwFwYDVQQDExBHTE9CQUxUUlVTVCAyMDIwMIICIjANBgkq\nhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAri5WrRsc7/aVj6B3GyvTY4+ETUWiD59b\nRatZe1E0+eyLinjF3WuvvcTfk0Uev5E4C64OFudBc/jbu9G4UeDLgztzOG53ig9Z\nYybNpyrOVPu44sB8R85gfD+yc/LAGbaKkoc1DZAoouQVBGM+uq/ufF7MpotQsjj3\nQWPKzv9pj2gOlTblzLmMCcpL3TGQlsjMH/1WljTbjhzqLL6FLmPdqqmV0/0plRPw\nyJiT2S0WR5ARg6I6IqIoV6Lr/sCMKKCmfecqQjuCgGOlYx8ZzHyyZqjC0203b+J+\nBlHZRYQfEs4kUmSFC0iAToexIiIwquuuvuAC4EDosEKAA1GqtH6qRNdDYfOiaxaJ\nSaSjpCuKAsR49GiKweR6NrFvG5Ybd0mN1MkGco/PU+PcF4UgStyYJ9ORJitHHmkH\nr96i5OTUawuzXnzUJIBHKWk7buis/UDr2O1xcSvy6Fgd60GXIsUf1DnQJ4+H4xj0\n4KlGDfV0OoIu0G4skaMxXDtG6nsEEFZegB31pWXogvziB4xiRfUg3kZwhqG8k9Me\ndKZssCz3AwyIDMvUclOGvGBG85hqwvG/Q/lwIHfKN0F5VVJjjVsSn8VoxIidrPIw\nq7ejMZdnrY8XD2zHc+0klGvIg5rQmjdJBKuxFshsSUktq6HQjJLyQUp5ISXbY9e2\nnKd+Qmn7OmMCAwEAAaNjMGEwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\nAQYwHQYDVR0OBBYEFNwuH9FhN3nkq9XVsxJxaD1qaJwiMB8GA1UdIwQYMBaAFNwu\nH9FhN3nkq9XVsxJxaD1qaJwiMA0GCSqGSIb3DQEBCwUAA4ICAQCR8EICaEDuw2jA\nVC/f7GLDw56KoDEoqoOOpFaWEhCGVrqXctJUMHytGdUdaG/7FELYjQ7ztdGl4wJC\nXtzoRlgHNQIw4Lx0SsFDKv/bGtCwr2zD/cuz9X9tAy5ZVp0tLTWMstZDFyySCstd\n6IwPS3BD0IL/qMy/pJTAvoe9iuOTe8aPmxadJ2W8esVCgmxcB9CpwYhgROmYhRZf\n+I/KARDOJcP5YBugxZfD0yyIMaK9MOzQ0MAS8cE54+X1+NZK3TTN+2/BT+MAi1bi\nkvcoskJ3ciNnxz8RFbLEAwW+uxF7Cr+obuf/WEPPm2eggAe2HcqtbepBEX4tdJP7\nwry+UUTF72glJ4DjyKDUEuzZpTcdN3y0kcra1LGWge9oXHYQSa9+pTeAsRxSvTOB\nTI/53WXZFM2KJVj04sWDpQmQ1GwUY7VA3+vA/MRYfg0UFodUJ25W5HCEuGwyEn6C\nMUO+1918oa2u1qsgEu8KwxCMSZY13At1XrFP1U80DhEgB3VDRemjEdqso5nCtnkn\n4rnvyOL2NSl6dPrFf4IFYqYK6miyeUcGbvJXqBUzxvd4Sj1Ce2t+/vdG6tHrju+I\naFvowdlxfv1k7/9nR4hYJS8+hge9+6jlgqispdNpQ80xiEmEU5LAsTkbOYMBMMTy\nqfrQA71yN2BWHzZ8vTmR9W0Nv3vXkg==\n-----END CERTIFICATE-----\n\n# Issuer: CN=ANF Secure Server Root CA O=ANF Autoridad de Certificacion OU=ANF CA Raiz\n# Subject: CN=ANF Secure Server Root CA O=ANF Autoridad de Certificacion OU=ANF CA Raiz\n# Label: \"ANF Secure Server Root CA\"\n# Serial: 996390341000653745\n# MD5 Fingerprint: 26:a6:44:5a:d9:af:4e:2f:b2:1d:b6:65:b0:4e:e8:96\n# SHA1 Fingerprint: 5b:6e:68:d0:cc:15:b6:a0:5f:1e:c1:5f:ae:02:fc:6b:2f:5d:6f:74\n# SHA256 Fingerprint: fb:8f:ec:75:91:69:b9:10:6b:1e:51:16:44:c6:18:c5:13:04:37:3f:6c:06:43:08:8d:8b:ef:fd:1b:99:75:99\n-----BEGIN CERTIFICATE-----\nMIIF7zCCA9egAwIBAgIIDdPjvGz5a7EwDQYJKoZIhvcNAQELBQAwgYQxEjAQBgNV\nBAUTCUc2MzI4NzUxMDELMAkGA1UEBhMCRVMxJzAlBgNVBAoTHkFORiBBdXRvcmlk\nYWQgZGUgQ2VydGlmaWNhY2lvbjEUMBIGA1UECxMLQU5GIENBIFJhaXoxIjAgBgNV\nBAMTGUFORiBTZWN1cmUgU2VydmVyIFJvb3QgQ0EwHhcNMTkwOTA0MTAwMDM4WhcN\nMzkwODMwMTAwMDM4WjCBhDESMBAGA1UEBRMJRzYzMjg3NTEwMQswCQYDVQQGEwJF\nUzEnMCUGA1UEChMeQU5GIEF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uMRQwEgYD\nVQQLEwtBTkYgQ0EgUmFpejEiMCAGA1UEAxMZQU5GIFNlY3VyZSBTZXJ2ZXIgUm9v\ndCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANvrayvmZFSVgpCj\ncqQZAZ2cC4Ffc0m6p6zzBE57lgvsEeBbphzOG9INgxwruJ4dfkUyYA8H6XdYfp9q\nyGFOtibBTI3/TO80sh9l2Ll49a2pcbnvT1gdpd50IJeh7WhM3pIXS7yr/2WanvtH\n2Vdy8wmhrnZEE26cLUQ5vPnHO6RYPUG9tMJJo8gN0pcvB2VSAKduyK9o7PQUlrZX\nH1bDOZ8rbeTzPvY1ZNoMHKGESy9LS+IsJJ1tk0DrtSOOMspvRdOoiXsezx76W0OL\nzc2oD2rKDF65nkeP8Nm2CgtYZRczuSPkdxl9y0oukntPLxB3sY0vaJxizOBQ+OyR\np1RMVwnVdmPF6GUe7m1qzwmd+nxPrWAI/VaZDxUse6mAq4xhj0oHdkLePfTdsiQz\nW7i1o0TJrH93PB0j7IKppuLIBkwC/qxcmZkLLxCKpvR/1Yd0DVlJRfbwcVw5Kda/\nSiOL9V8BY9KHcyi1Swr1+KuCLH5zJTIdC2MKF4EA/7Z2Xue0sUDKIbvVgFHlSFJn\nLNJhiQcND85Cd8BEc5xEUKDbEAotlRyBr+Qc5RQe8TZBAQIvfXOn3kLMTOmJDVb3\nn5HUA8ZsyY/b2BzgQJhdZpmYgG4t/wHFzstGH6wCxkPmrqKEPMVOHj1tyRRM4y5B\nu8o5vzY8KhmqQYdOpc5LMnndkEl/AgMBAAGjYzBhMB8GA1UdIwQYMBaAFJxf0Gxj\no1+TypOYCK2Mh6UsXME3MB0GA1UdDgQWBBScX9BsY6Nfk8qTmAitjIelLFzBNzAO\nBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\nAgEATh65isagmD9uw2nAalxJUqzLK114OMHVVISfk/CHGT0sZonrDUL8zPB1hT+L\n9IBdeeUXZ701guLyPI59WzbLWoAAKfLOKyzxj6ptBZNscsdW699QIyjlRRA96Gej\nrw5VD5AJYu9LWaL2U/HANeQvwSS9eS9OICI7/RogsKQOLHDtdD+4E5UGUcjohybK\npFtqFiGS3XNgnhAY3jyB6ugYw3yJ8otQPr0R4hUDqDZ9MwFsSBXXiJCZBMXM5gf0\nvPSQ7RPi6ovDj6MzD8EpTBNO2hVWcXNyglD2mjN8orGoGjR0ZVzO0eurU+AagNjq\nOknkJjCb5RyKqKkVMoaZkgoQI1YS4PbOTOK7vtuNknMBZi9iPrJyJ0U27U1W45eZ\n/zo1PqVUSlJZS2Db7v54EX9K3BR5YLZrZAPbFYPhor72I5dQ8AkzNqdxliXzuUJ9\n2zg/LFis6ELhDtjTO0wugumDLmsx2d1Hhk9tl5EuT+IocTUW0fJz/iUrB0ckYyfI\n+PbZa/wSMVYIwFNCr5zQM378BvAxRAMU8Vjq8moNqRGyg77FGr8H6lnco4g175x2\nMjxNBiLOFeXdntiP2t7SxDnlF4HPOEfrf4htWRvfn0IUrn7PqLBmZdo3r5+qPeoo\ntt7VMVgWglvquxl1AnMaykgaIZOQCo6ThKd9OyMYkomgjaw=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certum EC-384 CA O=Asseco Data Systems S.A. OU=Certum Certification Authority\n# Subject: CN=Certum EC-384 CA O=Asseco Data Systems S.A. OU=Certum Certification Authority\n# Label: \"Certum EC-384 CA\"\n# Serial: 160250656287871593594747141429395092468\n# MD5 Fingerprint: b6:65:b3:96:60:97:12:a1:ec:4e:e1:3d:a3:c6:c9:f1\n# SHA1 Fingerprint: f3:3e:78:3c:ac:df:f4:a2:cc:ac:67:55:69:56:d7:e5:16:3c:e1:ed\n# SHA256 Fingerprint: 6b:32:80:85:62:53:18:aa:50:d1:73:c9:8d:8b:da:09:d5:7e:27:41:3d:11:4c:f7:87:a0:f5:d0:6c:03:0c:f6\n-----BEGIN CERTIFICATE-----\nMIICZTCCAeugAwIBAgIQeI8nXIESUiClBNAt3bpz9DAKBggqhkjOPQQDAzB0MQsw\nCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBTLkEuMScw\nJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxGTAXBgNVBAMT\nEENlcnR1bSBFQy0zODQgQ0EwHhcNMTgwMzI2MDcyNDU0WhcNNDMwMzI2MDcyNDU0\nWjB0MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBT\nLkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxGTAX\nBgNVBAMTEENlcnR1bSBFQy0zODQgQ0EwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAATE\nKI6rGFtqvm5kN2PkzeyrOvfMobgOgknXhimfoZTy42B4mIF4Bk3y7JoOV2CDn7Tm\nFy8as10CW4kjPMIRBSqniBMY81CE1700LCeJVf/OTOffph8oxPBUw7l8t1Ot68Kj\nQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFI0GZnQkdjrzife81r1HfS+8\nEF9LMA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAwNoADBlAjADVS2m5hjEfO/J\nUG7BJw+ch69u1RsIGL2SKcHvlJF40jocVYli5RsJHrpka/F2tNQCMQC0QoSZ/6vn\nnvuRlydd3LBbMHHOXjgaatkl5+r3YZJW+OraNsKHZZYuciUvf9/DE8k=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certum Trusted Root CA O=Asseco Data Systems S.A. OU=Certum Certification Authority\n# Subject: CN=Certum Trusted Root CA O=Asseco Data Systems S.A. OU=Certum Certification Authority\n# Label: \"Certum Trusted Root CA\"\n# Serial: 40870380103424195783807378461123655149\n# MD5 Fingerprint: 51:e1:c2:e7:fe:4c:84:af:59:0e:2f:f4:54:6f:ea:29\n# SHA1 Fingerprint: c8:83:44:c0:18:ae:9f:cc:f1:87:b7:8f:22:d1:c5:d7:45:84:ba:e5\n# SHA256 Fingerprint: fe:76:96:57:38:55:77:3e:37:a9:5e:7a:d4:d9:cc:96:c3:01:57:c1:5d:31:76:5b:a9:b1:57:04:e1:ae:78:fd\n-----BEGIN CERTIFICATE-----\nMIIFwDCCA6igAwIBAgIQHr9ZULjJgDdMBvfrVU+17TANBgkqhkiG9w0BAQ0FADB6\nMQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEgU3lzdGVtcyBTLkEu\nMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkxHzAdBgNV\nBAMTFkNlcnR1bSBUcnVzdGVkIFJvb3QgQ0EwHhcNMTgwMzE2MTIxMDEzWhcNNDMw\nMzE2MTIxMDEzWjB6MQswCQYDVQQGEwJQTDEhMB8GA1UEChMYQXNzZWNvIERhdGEg\nU3lzdGVtcyBTLkEuMScwJQYDVQQLEx5DZXJ0dW0gQ2VydGlmaWNhdGlvbiBBdXRo\nb3JpdHkxHzAdBgNVBAMTFkNlcnR1bSBUcnVzdGVkIFJvb3QgQ0EwggIiMA0GCSqG\nSIb3DQEBAQUAA4ICDwAwggIKAoICAQDRLY67tzbqbTeRn06TpwXkKQMlzhyC93yZ\nn0EGze2jusDbCSzBfN8pfktlL5On1AFrAygYo9idBcEq2EXxkd7fO9CAAozPOA/q\np1x4EaTByIVcJdPTsuclzxFUl6s1wB52HO8AU5853BSlLCIls3Jy/I2z5T4IHhQq\nNwuIPMqw9MjCoa68wb4pZ1Xi/K1ZXP69VyywkI3C7Te2fJmItdUDmj0VDT06qKhF\n8JVOJVkdzZhpu9PMMsmN74H+rX2Ju7pgE8pllWeg8xn2A1bUatMn4qGtg/BKEiJ3\nHAVz4hlxQsDsdUaakFjgao4rpUYwBI4Zshfjvqm6f1bxJAPXsiEodg42MEx51UGa\nmqi4NboMOvJEGyCI98Ul1z3G4z5D3Yf+xOr1Uz5MZf87Sst4WmsXXw3Hw09Omiqi\n7VdNIuJGmj8PkTQkfVXjjJU30xrwCSss0smNtA0Aq2cpKNgB9RkEth2+dv5yXMSF\nytKAQd8FqKPVhJBPC/PgP5sZ0jeJP/J7UhyM9uH3PAeXjA6iWYEMspA90+NZRu0P\nqafegGtaqge2Gcu8V/OXIXoMsSt0Puvap2ctTMSYnjYJdmZm/Bo/6khUHL4wvYBQ\nv3y1zgD2DGHZ5yQD4OMBgQ692IU0iL2yNqh7XAjlRICMb/gv1SHKHRzQ+8S1h9E6\nTsd2tTVItQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSM+xx1\nvALTn04uSNn5YFSqxLNP+jAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQENBQAD\nggIBAEii1QALLtA/vBzVtVRJHlpr9OTy4EA34MwUe7nJ+jW1dReTagVphZzNTxl4\nWxmB82M+w85bj/UvXgF2Ez8sALnNllI5SW0ETsXpD4YN4fqzX4IS8TrOZgYkNCvo\nzMrnadyHncI013nR03e4qllY/p0m+jiGPp2Kh2RX5Rc64vmNueMzeMGQ2Ljdt4NR\n5MTMI9UGfOZR0800McD2RrsLrfw9EAUqO0qRJe6M1ISHgCq8CYyqOhNf6DR5UMEQ\nGfnTKB7U0VEwKbOukGfWHwpjscWpxkIxYxeU72nLL/qMFH3EQxiJ2fAyQOaA4kZf\n5ePBAFmo+eggvIksDkc0C+pXwlM2/KfUrzHN/gLldfq5Jwn58/U7yn2fqSLLiMmq\n0Uc9NneoWWRrJ8/vJ8HjJLWG965+Mk2weWjROeiQWMODvA8s1pfrzgzhIMfatz7D\nP78v3DSk+yshzWePS/Tj6tQ/50+6uaWTRRxmHyH6ZF5v4HaUMst19W7l9o/HuKTM\nqJZ9ZPskWkoDbGs4xugDQ5r3V7mzKWmTOPQD8rv7gmsHINFSH5pkAnuYZttcTVoP\n0ISVoDwUQwbKytu4QTbaakRnh6+v40URFWkIsr4WOZckbxJF0WddCajJFdr60qZf\nE2Efv4WstK2tBZQIgx51F9NxO5NQI1mg7TyRVJ12AMXDuDjb\n-----END CERTIFICATE-----\n\n# Issuer: CN=TunTrust Root CA O=Agence Nationale de Certification Electronique\n# Subject: CN=TunTrust Root CA O=Agence Nationale de Certification Electronique\n# Label: \"TunTrust Root CA\"\n# Serial: 108534058042236574382096126452369648152337120275\n# MD5 Fingerprint: 85:13:b9:90:5b:36:5c:b6:5e:b8:5a:f8:e0:31:57:b4\n# SHA1 Fingerprint: cf:e9:70:84:0f:e0:73:0f:9d:f6:0c:7f:2c:4b:ee:20:46:34:9c:bb\n# SHA256 Fingerprint: 2e:44:10:2a:b5:8c:b8:54:19:45:1c:8e:19:d9:ac:f3:66:2c:af:bc:61:4b:6a:53:96:0a:30:f7:d0:e2:eb:41\n-----BEGIN CERTIFICATE-----\nMIIFszCCA5ugAwIBAgIUEwLV4kBMkkaGFmddtLu7sms+/BMwDQYJKoZIhvcNAQEL\nBQAwYTELMAkGA1UEBhMCVE4xNzA1BgNVBAoMLkFnZW5jZSBOYXRpb25hbGUgZGUg\nQ2VydGlmaWNhdGlvbiBFbGVjdHJvbmlxdWUxGTAXBgNVBAMMEFR1blRydXN0IFJv\nb3QgQ0EwHhcNMTkwNDI2MDg1NzU2WhcNNDQwNDI2MDg1NzU2WjBhMQswCQYDVQQG\nEwJUTjE3MDUGA1UECgwuQWdlbmNlIE5hdGlvbmFsZSBkZSBDZXJ0aWZpY2F0aW9u\nIEVsZWN0cm9uaXF1ZTEZMBcGA1UEAwwQVHVuVHJ1c3QgUm9vdCBDQTCCAiIwDQYJ\nKoZIhvcNAQEBBQADggIPADCCAgoCggIBAMPN0/y9BFPdDCA61YguBUtB9YOCfvdZ\nn56eY+hz2vYGqU8ftPkLHzmMmiDQfgbU7DTZhrx1W4eI8NLZ1KMKsmwb60ksPqxd\n2JQDoOw05TDENX37Jk0bbjBU2PWARZw5rZzJJQRNmpA+TkBuimvNKWfGzC3gdOgF\nVwpIUPp6Q9p+7FuaDmJ2/uqdHYVy7BG7NegfJ7/Boce7SBbdVtfMTqDhuazb1YMZ\nGoXRlJfXyqNlC/M4+QKu3fZnz8k/9YosRxqZbwUN/dAdgjH8KcwAWJeRTIAAHDOF\nli/LQcKLEITDCSSJH7UP2dl3RxiSlGBcx5kDPP73lad9UKGAwqmDrViWVSHbhlnU\nr8a83YFuB9tgYv7sEG7aaAH0gxupPqJbI9dkxt/con3YS7qC0lH4Zr8GRuR5KiY2\neY8fTpkdso8MDhz/yV3A/ZAQprE38806JG60hZC/gLkMjNWb1sjxVj8agIl6qeIb\nMlEsPvLfe/ZdeikZjuXIvTZxi11Mwh0/rViizz1wTaZQmCXcI/m4WEEIcb9PuISg\njwBUFfyRbVinljvrS5YnzWuioYasDXxU5mZMZl+QviGaAkYt5IPCgLnPSz7ofzwB\n7I9ezX/SKEIBlYrilz0QIX32nRzFNKHsLA4KUiwSVXAkPcvCFDVDXSdOvsC9qnyW\n5/yeYa1E0wCXAgMBAAGjYzBhMB0GA1UdDgQWBBQGmpsfU33x9aTI04Y+oXNZtPdE\nITAPBgNVHRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFAaamx9TffH1pMjThj6hc1m0\n90QhMA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAqgVutt0Vyb+z\nxiD2BkewhpMl0425yAA/l/VSJ4hxyXT968pk21vvHl26v9Hr7lxpuhbI87mP0zYu\nQEkHDVneixCwSQXi/5E/S7fdAo74gShczNxtr18UnH1YeA32gAm56Q6XKRm4t+v4\nFstVEuTGfbvE7Pi1HE4+Z7/FXxttbUcoqgRYYdZ2vyJ/0Adqp2RT8JeNnYA/u8EH\n22Wv5psymsNUk8QcCMNE+3tjEUPRahphanltkE8pjkcFwRJpadbGNjHh/PqAulxP\nxOu3Mqz4dWEX1xAZufHSCe96Qp1bWgvUxpVOKs7/B9dPfhgGiPEZtdmYu65xxBzn\ndFlY7wyJz4sfdZMaBBSSSFCp61cpABbjNhzI+L/wM9VBD8TMPN3pM0MBkRArHtG5\nXc0yGYuPjCB31yLEQtyEFpslbei0VXF/sHyz03FJuc9SpAQ/3D2gu68zngowYI7b\nnV2UqL1g52KAdoGDDIzMMEZJ4gzSqK/rYXHv5yJiqfdcZGyfFoxnNidF9Ql7v/YQ\nCvGwjVRDjAS6oz/v4jXH+XTgbzRB0L9zZVcg+ZtnemZoJE6AZb0QmQZZ8mWvuMZH\nu/2QeItBcy6vVR/cO5JyboTT0GFMDcx2V+IthSIVNg3rAZ3r2OvEhJn7wAzMMujj\nd9qDRIueVSjAi1jTkD5OGwDxFa2DK5o=\n-----END CERTIFICATE-----\n\n# Issuer: CN=HARICA TLS RSA Root CA 2021 O=Hellenic Academic and Research Institutions CA\n# Subject: CN=HARICA TLS RSA Root CA 2021 O=Hellenic Academic and Research Institutions CA\n# Label: \"HARICA TLS RSA Root CA 2021\"\n# Serial: 76817823531813593706434026085292783742\n# MD5 Fingerprint: 65:47:9b:58:86:dd:2c:f0:fc:a2:84:1f:1e:96:c4:91\n# SHA1 Fingerprint: 02:2d:05:82:fa:88:ce:14:0c:06:79:de:7f:14:10:e9:45:d7:a5:6d\n# SHA256 Fingerprint: d9:5d:0e:8e:da:79:52:5b:f9:be:b1:1b:14:d2:10:0d:32:94:98:5f:0c:62:d9:fa:bd:9c:d9:99:ec:cb:7b:1d\n-----BEGIN CERTIFICATE-----\nMIIFpDCCA4ygAwIBAgIQOcqTHO9D88aOk8f0ZIk4fjANBgkqhkiG9w0BAQsFADBs\nMQswCQYDVQQGEwJHUjE3MDUGA1UECgwuSGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl\nc2VhcmNoIEluc3RpdHV0aW9ucyBDQTEkMCIGA1UEAwwbSEFSSUNBIFRMUyBSU0Eg\nUm9vdCBDQSAyMDIxMB4XDTIxMDIxOTEwNTUzOFoXDTQ1MDIxMzEwNTUzN1owbDEL\nMAkGA1UEBhMCR1IxNzA1BgNVBAoMLkhlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNl\nYXJjaCBJbnN0aXR1dGlvbnMgQ0ExJDAiBgNVBAMMG0hBUklDQSBUTFMgUlNBIFJv\nb3QgQ0EgMjAyMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAIvC569l\nmwVnlskNJLnQDmT8zuIkGCyEf3dRywQRNrhe7Wlxp57kJQmXZ8FHws+RFjZiPTgE\n4VGC/6zStGndLuwRo0Xua2s7TL+MjaQenRG56Tj5eg4MmOIjHdFOY9TnuEFE+2uv\na9of08WRiFukiZLRgeaMOVig1mlDqa2YUlhu2wr7a89o+uOkXjpFc5gH6l8Cct4M\npbOfrqkdtx2z/IpZ525yZa31MJQjB/OCFks1mJxTuy/K5FrZx40d/JiZ+yykgmvw\nKh+OC19xXFyuQnspiYHLA6OZyoieC0AJQTPb5lh6/a6ZcMBaD9YThnEvdmn8kN3b\nLW7R8pv1GmuebxWMevBLKKAiOIAkbDakO/IwkfN4E8/BPzWr8R0RI7VDIp4BkrcY\nAuUR0YLbFQDMYTfBKnya4dC6s1BG7oKsnTH4+yPiAwBIcKMJJnkVU2DzOFytOOqB\nAGMUuTNe3QvboEUHGjMJ+E20pwKmafTCWQWIZYVWrkvL4N48fS0ayOn7H6NhStYq\nE613TBoYm5EPWNgGVMWX+Ko/IIqmhaZ39qb8HOLubpQzKoNQhArlT4b4UEV4AIHr\nW2jjJo3Me1xR9BQsQL4aYB16cmEdH2MtiKrOokWQCPxrvrNQKlr9qEgYRtaQQJKQ\nCoReaDH46+0N0x3GfZkYVVYnZS6NRcUk7M7jAgMBAAGjQjBAMA8GA1UdEwEB/wQF\nMAMBAf8wHQYDVR0OBBYEFApII6ZgpJIKM+qTW8VX6iVNvRLuMA4GA1UdDwEB/wQE\nAwIBhjANBgkqhkiG9w0BAQsFAAOCAgEAPpBIqm5iFSVmewzVjIuJndftTgfvnNAU\nX15QvWiWkKQUEapobQk1OUAJ2vQJLDSle1mESSmXdMgHHkdt8s4cUCbjnj1AUz/3\nf5Z2EMVGpdAgS1D0NTsY9FVqQRtHBmg8uwkIYtlfVUKqrFOFrJVWNlar5AWMxaja\nH6NpvVMPxP/cyuN+8kyIhkdGGvMA9YCRotxDQpSbIPDRzbLrLFPCU3hKTwSUQZqP\nJzLB5UkZv/HywouoCjkxKLR9YjYsTewfM7Z+d21+UPCfDtcRj88YxeMn/ibvBZ3P\nzzfF0HvaO7AWhAw6k9a+F9sPPg4ZeAnHqQJyIkv3N3a6dcSFA1pj1bF1BcK5vZSt\njBWZp5N99sXzqnTPBIWUmAD04vnKJGW/4GKvyMX6ssmeVkjaef2WdhW+o45WxLM0\n/L5H9MG0qPzVMIho7suuyWPEdr6sOBjhXlzPrjoiUevRi7PzKzMHVIf6tLITe7pT\nBGIBnfHAT+7hOtSLIBD6Alfm78ELt5BGnBkpjNxvoEppaZS3JGWg/6w/zgH7IS79\naPib8qXPMThcFarmlwDB31qlpzmq6YR/PFGoOtmUW4y/Twhx5duoXNTSpv4Ao8YW\nxw/ogM4cKGR0GQjTQuPOAF1/sdwTsOEFy9EgqoZ0njnnkf3/W9b3raYvAwtt41dU\n63ZTGI0RmLo=\n-----END CERTIFICATE-----\n\n# Issuer: CN=HARICA TLS ECC Root CA 2021 O=Hellenic Academic and Research Institutions CA\n# Subject: CN=HARICA TLS ECC Root CA 2021 O=Hellenic Academic and Research Institutions CA\n# Label: \"HARICA TLS ECC Root CA 2021\"\n# Serial: 137515985548005187474074462014555733966\n# MD5 Fingerprint: ae:f7:4c:e5:66:35:d1:b7:9b:8c:22:93:74:d3:4b:b0\n# SHA1 Fingerprint: bc:b0:c1:9d:e9:98:92:70:19:38:57:e9:8d:a7:b4:5d:6e:ee:01:48\n# SHA256 Fingerprint: 3f:99:cc:47:4a:cf:ce:4d:fe:d5:87:94:66:5e:47:8d:15:47:73:9f:2e:78:0f:1b:b4:ca:9b:13:30:97:d4:01\n-----BEGIN CERTIFICATE-----\nMIICVDCCAdugAwIBAgIQZ3SdjXfYO2rbIvT/WeK/zjAKBggqhkjOPQQDAzBsMQsw\nCQYDVQQGEwJHUjE3MDUGA1UECgwuSGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJlc2Vh\ncmNoIEluc3RpdHV0aW9ucyBDQTEkMCIGA1UEAwwbSEFSSUNBIFRMUyBFQ0MgUm9v\ndCBDQSAyMDIxMB4XDTIxMDIxOTExMDExMFoXDTQ1MDIxMzExMDEwOVowbDELMAkG\nA1UEBhMCR1IxNzA1BgNVBAoMLkhlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJj\naCBJbnN0aXR1dGlvbnMgQ0ExJDAiBgNVBAMMG0hBUklDQSBUTFMgRUNDIFJvb3Qg\nQ0EgMjAyMTB2MBAGByqGSM49AgEGBSuBBAAiA2IABDgI/rGgltJ6rK9JOtDA4MM7\nKKrxcm1lAEeIhPyaJmuqS7psBAqIXhfyVYf8MLA04jRYVxqEU+kw2anylnTDUR9Y\nSTHMmE5gEYd103KUkE+bECUqqHgtvpBBWJAVcqeht6NCMEAwDwYDVR0TAQH/BAUw\nAwEB/zAdBgNVHQ4EFgQUyRtTgRL+BNUW0aq8mm+3oJUZbsowDgYDVR0PAQH/BAQD\nAgGGMAoGCCqGSM49BAMDA2cAMGQCMBHervjcToiwqfAircJRQO9gcS3ujwLEXQNw\nSaSS6sUUiHCm0w2wqsosQJz76YJumgIwK0eaB8bRwoF8yguWGEEbo/QwCZ61IygN\nnxS2PFOiTAZpffpskcYqSUXm7LcT4Tps\n-----END CERTIFICATE-----\n\n# Issuer: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068\n# Subject: CN=Autoridad de Certificacion Firmaprofesional CIF A62634068\n# Label: \"Autoridad de Certificacion Firmaprofesional CIF A62634068\"\n# Serial: 1977337328857672817\n# MD5 Fingerprint: 4e:6e:9b:54:4c:ca:b7:fa:48:e4:90:b1:15:4b:1c:a3\n# SHA1 Fingerprint: 0b:be:c2:27:22:49:cb:39:aa:db:35:5c:53:e3:8c:ae:78:ff:b6:fe\n# SHA256 Fingerprint: 57:de:05:83:ef:d2:b2:6e:03:61:da:99:da:9d:f4:64:8d:ef:7e:e8:44:1c:3b:72:8a:fa:9b:cd:e0:f9:b2:6a\n-----BEGIN CERTIFICATE-----\nMIIGFDCCA/ygAwIBAgIIG3Dp0v+ubHEwDQYJKoZIhvcNAQELBQAwUTELMAkGA1UE\nBhMCRVMxQjBABgNVBAMMOUF1dG9yaWRhZCBkZSBDZXJ0aWZpY2FjaW9uIEZpcm1h\ncHJvZmVzaW9uYWwgQ0lGIEE2MjYzNDA2ODAeFw0xNDA5MjMxNTIyMDdaFw0zNjA1\nMDUxNTIyMDdaMFExCzAJBgNVBAYTAkVTMUIwQAYDVQQDDDlBdXRvcmlkYWQgZGUg\nQ2VydGlmaWNhY2lvbiBGaXJtYXByb2Zlc2lvbmFsIENJRiBBNjI2MzQwNjgwggIi\nMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDKlmuO6vj78aI14H9M2uDDUtd9\nthDIAl6zQyrET2qyyhxdKJp4ERppWVevtSBC5IsP5t9bpgOSL/UR5GLXMnE42QQM\ncas9UX4PB99jBVzpv5RvwSmCwLTaUbDBPLutN0pcyvFLNg4kq7/DhHf9qFD0sefG\nL9ItWY16Ck6WaVICqjaY7Pz6FIMMNx/Jkjd/14Et5cS54D40/mf0PmbR0/RAz15i\nNA9wBj4gGFrO93IbJWyTdBSTo3OxDqqHECNZXyAFGUftaI6SEspd/NYrspI8IM/h\nX68gvqB2f3bl7BqGYTM+53u0P6APjqK5am+5hyZvQWyIplD9amML9ZMWGxmPsu2b\nm8mQ9QEM3xk9Dz44I8kvjwzRAv4bVdZO0I08r0+k8/6vKtMFnXkIoctXMbScyJCy\nZ/QYFpM6/EfY0XiWMR+6KwxfXZmtY4laJCB22N/9q06mIqqdXuYnin1oKaPnirja\nEbsXLZmdEyRG98Xi2J+Of8ePdG1asuhy9azuJBCtLxTa/y2aRnFHvkLfuwHb9H/T\nKI8xWVvTyQKmtFLKbpf7Q8UIJm+K9Lv9nyiqDdVF8xM6HdjAeI9BZzwelGSuewvF\n6NkBiDkal4ZkQdU7hwxu+g/GvUgUvzlN1J5Bto+WHWOWk9mVBngxaJ43BjuAiUVh\nOSPHG0SjFeUc+JIwuwIDAQABo4HvMIHsMB0GA1UdDgQWBBRlzeurNR4APn7VdMAc\ntHNHDhpkLzASBgNVHRMBAf8ECDAGAQH/AgEBMIGmBgNVHSAEgZ4wgZswgZgGBFUd\nIAAwgY8wLwYIKwYBBQUHAgEWI2h0dHA6Ly93d3cuZmlybWFwcm9mZXNpb25hbC5j\nb20vY3BzMFwGCCsGAQUFBwICMFAeTgBQAGEAcwBlAG8AIABkAGUAIABsAGEAIABC\nAG8AbgBhAG4AbwB2AGEAIAA0ADcAIABCAGEAcgBjAGUAbABvAG4AYQAgADAAOAAw\nADEANzAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQELBQADggIBAHSHKAIrdx9m\niWTtj3QuRhy7qPj4Cx2Dtjqn6EWKB7fgPiDL4QjbEwj4KKE1soCzC1HA01aajTNF\nSa9J8OA9B3pFE1r/yJfY0xgsfZb43aJlQ3CTkBW6kN/oGbDbLIpgD7dvlAceHabJ\nhfa9NPhAeGIQcDq+fUs5gakQ1JZBu/hfHAsdCPKxsIl68veg4MSPi3i1O1ilI45P\nVf42O+AMt8oqMEEgtIDNrvx2ZnOorm7hfNoD6JQg5iKj0B+QXSBTFCZX2lSX3xZE\nEAEeiGaPcjiT3SC3NL7X8e5jjkd5KAb881lFJWAiMxujX6i6KtoaPc1A6ozuBRWV\n1aUsIC+nmCjuRfzxuIgALI9C2lHVnOUTaHFFQ4ueCyE8S1wF3BqfmI7avSKecs2t\nCsvMo2ebKHTEm9caPARYpoKdrcd7b/+Alun4jWq9GJAd/0kakFI3ky88Al2CdgtR\n5xbHV/g4+afNmyJU72OwFW1TZQNKXkqgsqeOSQBZONXH9IBk9W6VULgRfhVwOEqw\nf9DEMnDAGf/JOC0ULGb0QkTmVXYbgBVX/8Cnp6o5qtjTcNAuuuuUavpfNIbnYrX9\nivAwhZTJryQCL2/W3Wf+47BVTwSYT6RBVuKT0Gro1vP7ZeDOdcQxWQzugsgMYDNK\nGbqEZycPvEJdvSRUDewdcAZfpLz6IHxV\n-----END CERTIFICATE-----\n\n# Issuer: CN=vTrus ECC Root CA O=iTrusChina Co.,Ltd.\n# Subject: CN=vTrus ECC Root CA O=iTrusChina Co.,Ltd.\n# Label: \"vTrus ECC Root CA\"\n# Serial: 630369271402956006249506845124680065938238527194\n# MD5 Fingerprint: de:4b:c1:f5:52:8c:9b:43:e1:3e:8f:55:54:17:8d:85\n# SHA1 Fingerprint: f6:9c:db:b0:fc:f6:02:13:b6:52:32:a6:a3:91:3f:16:70:da:c3:e1\n# SHA256 Fingerprint: 30:fb:ba:2c:32:23:8e:2a:98:54:7a:f9:79:31:e5:50:42:8b:9b:3f:1c:8e:eb:66:33:dc:fa:86:c5:b2:7d:d3\n-----BEGIN CERTIFICATE-----\nMIICDzCCAZWgAwIBAgIUbmq8WapTvpg5Z6LSa6Q75m0c1towCgYIKoZIzj0EAwMw\nRzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28uLEx0ZC4xGjAY\nBgNVBAMTEXZUcnVzIEVDQyBSb290IENBMB4XDTE4MDczMTA3MjY0NFoXDTQzMDcz\nMTA3MjY0NFowRzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28u\nLEx0ZC4xGjAYBgNVBAMTEXZUcnVzIEVDQyBSb290IENBMHYwEAYHKoZIzj0CAQYF\nK4EEACIDYgAEZVBKrox5lkqqHAjDo6LN/llWQXf9JpRCux3NCNtzslt188+cToL0\nv/hhJoVs1oVbcnDS/dtitN9Ti72xRFhiQgnH+n9bEOf+QP3A2MMrMudwpremIFUd\ne4BdS49nTPEQo0IwQDAdBgNVHQ4EFgQUmDnNvtiyjPeyq+GtJK97fKHbH88wDwYD\nVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwCgYIKoZIzj0EAwMDaAAwZQIw\nV53dVvHH4+m4SVBrm2nDb+zDfSXkV5UTQJtS0zvzQBm8JsctBp61ezaf9SXUY2sA\nAjEA6dPGnlaaKsyh2j/IZivTWJwghfqrkYpwcBE4YGQLYgmRWAD5Tfs0aNoJrSEG\nGJTO\n-----END CERTIFICATE-----\n\n# Issuer: CN=vTrus Root CA O=iTrusChina Co.,Ltd.\n# Subject: CN=vTrus Root CA O=iTrusChina Co.,Ltd.\n# Label: \"vTrus Root CA\"\n# Serial: 387574501246983434957692974888460947164905180485\n# MD5 Fingerprint: b8:c9:37:df:fa:6b:31:84:64:c5:ea:11:6a:1b:75:fc\n# SHA1 Fingerprint: 84:1a:69:fb:f5:cd:1a:25:34:13:3d:e3:f8:fc:b8:99:d0:c9:14:b7\n# SHA256 Fingerprint: 8a:71:de:65:59:33:6f:42:6c:26:e5:38:80:d0:0d:88:a1:8d:a4:c6:a9:1f:0d:cb:61:94:e2:06:c5:c9:63:87\n-----BEGIN CERTIFICATE-----\nMIIFVjCCAz6gAwIBAgIUQ+NxE9izWRRdt86M/TX9b7wFjUUwDQYJKoZIhvcNAQEL\nBQAwQzELMAkGA1UEBhMCQ04xHDAaBgNVBAoTE2lUcnVzQ2hpbmEgQ28uLEx0ZC4x\nFjAUBgNVBAMTDXZUcnVzIFJvb3QgQ0EwHhcNMTgwNzMxMDcyNDA1WhcNNDMwNzMx\nMDcyNDA1WjBDMQswCQYDVQQGEwJDTjEcMBoGA1UEChMTaVRydXNDaGluYSBDby4s\nTHRkLjEWMBQGA1UEAxMNdlRydXMgUm9vdCBDQTCCAiIwDQYJKoZIhvcNAQEBBQAD\nggIPADCCAgoCggIBAL1VfGHTuB0EYgWgrmy3cLRB6ksDXhA/kFocizuwZotsSKYc\nIrrVQJLuM7IjWcmOvFjai57QGfIvWcaMY1q6n6MLsLOaXLoRuBLpDLvPbmyAhykU\nAyyNJJrIZIO1aqwTLDPxn9wsYTwaP3BVm60AUn/PBLn+NvqcwBauYv6WTEN+VRS+\nGrPSbcKvdmaVayqwlHeFXgQPYh1jdfdr58tbmnDsPmcF8P4HCIDPKNsFxhQnL4Z9\n8Cfe/+Z+M0jnCx5Y0ScrUw5XSmXX+6KAYPxMvDVTAWqXcoKv8R1w6Jz1717CbMdH\nflqUhSZNO7rrTOiwCcJlwp2dCZtOtZcFrPUGoPc2BX70kLJrxLT5ZOrpGgrIDajt\nJ8nU57O5q4IikCc9Kuh8kO+8T/3iCiSn3mUkpF3qwHYw03dQ+A0Em5Q2AXPKBlim\n0zvc+gRGE1WKyURHuFE5Gi7oNOJ5y1lKCn+8pu8fA2dqWSslYpPZUxlmPCdiKYZN\npGvu/9ROutW04o5IWgAZCfEF2c6Rsffr6TlP9m8EQ5pV9T4FFL2/s1m02I4zhKOQ\nUqqzApVg+QxMaPnu1RcN+HFXtSXkKe5lXa/R7jwXC1pDxaWG6iSe4gUH3DRCEpHW\nOXSuTEGC2/KmSNGzm/MzqvOmwMVO9fSddmPmAsYiS8GVP1BkLFTltvA8Kc9XAgMB\nAAGjQjBAMB0GA1UdDgQWBBRUYnBj8XWEQ1iO0RYgscasGrz2iTAPBgNVHRMBAf8E\nBTADAQH/MA4GA1UdDwEB/wQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAgEAKbqSSaet\n8PFww+SX8J+pJdVrnjT+5hpk9jprUrIQeBqfTNqK2uwcN1LgQkv7bHbKJAs5EhWd\nnxEt/Hlk3ODg9d3gV8mlsnZwUKT+twpw1aA08XXXTUm6EdGz2OyC/+sOxL9kLX1j\nbhd47F18iMjrjld22VkE+rxSH0Ws8HqA7Oxvdq6R2xCOBNyS36D25q5J08FsEhvM\nKar5CKXiNxTKsbhm7xqC5PD48acWabfbqWE8n/Uxy+QARsIvdLGx14HuqCaVvIiv\nTDUHKgLKeBRtRytAVunLKmChZwOgzoy8sHJnxDHO2zTlJQNgJXtxmOTAGytfdELS\nS8VZCAeHvsXDf+eW2eHcKJfWjwXj9ZtOyh1QRwVTsMo554WgicEFOwE30z9J4nfr\nI8iIZjs9OXYhRvHsXyO466JmdXTBQPfYaJqT4i2pLr0cox7IdMakLXogqzu4sEb9\nb91fUlV1YvCXoHzXOP0l382gmxDPi7g4Xl7FtKYCNqEeXxzP4padKar9mK5S4fNB\nUvupLnKWnyfjqnN9+BojZns7q2WwMgFLFT49ok8MKzWixtlnEjUwzXYuFrOZnk1P\nTi07NEPhmg4NpGaXutIcSkwsKouLgU9xGqndXHt7CMUADTdA43x7VF8vhV929ven\nsBxXVsFy6K2ir40zSbofitzmdHxghm+Hl3s=\n-----END CERTIFICATE-----\n\n# Issuer: CN=ISRG Root X2 O=Internet Security Research Group\n# Subject: CN=ISRG Root X2 O=Internet Security Research Group\n# Label: \"ISRG Root X2\"\n# Serial: 87493402998870891108772069816698636114\n# MD5 Fingerprint: d3:9e:c4:1e:23:3c:a6:df:cf:a3:7e:6d:e0:14:e6:e5\n# SHA1 Fingerprint: bd:b1:b9:3c:d5:97:8d:45:c6:26:14:55:f8:db:95:c7:5a:d1:53:af\n# SHA256 Fingerprint: 69:72:9b:8e:15:a8:6e:fc:17:7a:57:af:b7:17:1d:fc:64:ad:d2:8c:2f:ca:8c:f1:50:7e:34:45:3c:cb:14:70\n-----BEGIN CERTIFICATE-----\nMIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw\nCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg\nR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00\nMDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT\nZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw\nEAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW\n+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9\nItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T\nAQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI\nzj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW\ntL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1\n/q4AaOeMSQ+2b1tbFfLn\n-----END CERTIFICATE-----\n\n# Issuer: CN=HiPKI Root CA - G1 O=Chunghwa Telecom Co., Ltd.\n# Subject: CN=HiPKI Root CA - G1 O=Chunghwa Telecom Co., Ltd.\n# Label: \"HiPKI Root CA - G1\"\n# Serial: 60966262342023497858655262305426234976\n# MD5 Fingerprint: 69:45:df:16:65:4b:e8:68:9a:8f:76:5f:ff:80:9e:d3\n# SHA1 Fingerprint: 6a:92:e4:a8:ee:1b:ec:96:45:37:e3:29:57:49:cd:96:e3:e5:d2:60\n# SHA256 Fingerprint: f0:15:ce:3c:c2:39:bf:ef:06:4b:e9:f1:d2:c4:17:e1:a0:26:4a:0a:94:be:1f:0c:8d:12:18:64:eb:69:49:cc\n-----BEGIN CERTIFICATE-----\nMIIFajCCA1KgAwIBAgIQLd2szmKXlKFD6LDNdmpeYDANBgkqhkiG9w0BAQsFADBP\nMQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0\nZC4xGzAZBgNVBAMMEkhpUEtJIFJvb3QgQ0EgLSBHMTAeFw0xOTAyMjIwOTQ2MDRa\nFw0zNzEyMzExNTU5NTlaME8xCzAJBgNVBAYTAlRXMSMwIQYDVQQKDBpDaHVuZ2h3\nYSBUZWxlY29tIENvLiwgTHRkLjEbMBkGA1UEAwwSSGlQS0kgUm9vdCBDQSAtIEcx\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA9B5/UnMyDHPkvRN0o9Qw\nqNCuS9i233VHZvR85zkEHmpwINJaR3JnVfSl6J3VHiGh8Ge6zCFovkRTv4354twv\nVcg3Px+kwJyz5HdcoEb+d/oaoDjq7Zpy3iu9lFc6uux55199QmQ5eiY29yTw1S+6\nlZgRZq2XNdZ1AYDgr/SEYYwNHl98h5ZeQa/rh+r4XfEuiAU+TCK72h8q3VJGZDnz\nQs7ZngyzsHeXZJzA9KMuH5UHsBffMNsAGJZMoYFL3QRtU6M9/Aes1MU3guvklQgZ\nKILSQjqj2FPseYlgSGDIcpJQ3AOPgz+yQlda22rpEZfdhSi8MEyr48KxRURHH+CK\nFgeW0iEPU8DtqX7UTuybCeyvQqww1r/REEXgphaypcXTT3OUM3ECoWqj1jOXTyFj\nHluP2cFeRXF3D4FdXyGarYPM+l7WjSNfGz1BryB1ZlpK9p/7qxj3ccC2HTHsOyDr\ny+K49a6SsvfhhEvyovKTmiKe0xRvNlS9H15ZFblzqMF8b3ti6RZsR1pl8w4Rm0bZ\n/W3c1pzAtH2lsN0/Vm+h+fbkEkj9Bn8SV7apI09bA8PgcSojt/ewsTu8mL3WmKgM\na/aOEmem8rJY5AIJEzypuxC00jBF8ez3ABHfZfjcK0NVvxaXxA/VLGGEqnKG/uY6\nfsI/fe78LxQ+5oXdUG+3Se0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNV\nHQ4EFgQU8ncX+l6o/vY9cdVouslGDDjYr7AwDgYDVR0PAQH/BAQDAgGGMA0GCSqG\nSIb3DQEBCwUAA4ICAQBQUfB13HAE4/+qddRxosuej6ip0691x1TPOhwEmSKsxBHi\n7zNKpiMdDg1H2DfHb680f0+BazVP6XKlMeJ45/dOlBhbQH3PayFUhuaVevvGyuqc\nSE5XCV0vrPSltJczWNWseanMX/mF+lLFjfiRFOs6DRfQUsJ748JzjkZ4Bjgs6Fza\nZsT0pPBWGTMpWmWSBUdGSquEwx4noR8RkpkndZMPvDY7l1ePJlsMu5wP1G4wB9Tc\nXzZoZjmDlicmisjEOf6aIW/Vcobpf2Lll07QJNBAsNB1CI69aO4I1258EHBGG3zg\niLKecoaZAeO/n0kZtCW+VmWuF2PlHt/o/0elv+EmBYTksMCv5wiZqAxeJoBF1Pho\nL5aPruJKHJwWDBNvOIf2u8g0X5IDUXlwpt/L9ZlNec1OvFefQ05rLisY+GpzjLrF\nNe85akEez3GoorKGB1s6yeHvP2UEgEcyRHCVTjFnanRbEEV16rCf0OY1/k6fi8wr\nkkVbbiVghUbN0aqwdmaTd5a+g744tiROJgvM7XpWGuDpWsZkrUx6AEhEL7lAuxM+\nvhV4nYWBSipX3tUZQ9rbyltHhoMLP7YNdnhzeSJesYAfz77RP1YQmCuVh6EfnWQU\nYDksswBVLuT1sw5XxJFBAJw/6KXf6vb/yPCtbVKoF6ubYfwSUTXkJf2vqmqGOQ==\n-----END CERTIFICATE-----\n\n# Issuer: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R4\n# Subject: CN=GlobalSign O=GlobalSign OU=GlobalSign ECC Root CA - R4\n# Label: \"GlobalSign ECC Root CA - R4\"\n# Serial: 159662223612894884239637590694\n# MD5 Fingerprint: 26:29:f8:6d:e1:88:bf:a2:65:7f:aa:c4:cd:0f:7f:fc\n# SHA1 Fingerprint: 6b:a0:b0:98:e1:71:ef:5a:ad:fe:48:15:80:77:10:f4:bd:6f:0b:28\n# SHA256 Fingerprint: b0:85:d7:0b:96:4f:19:1a:73:e4:af:0d:54:ae:7a:0e:07:aa:fd:af:9b:71:dd:08:62:13:8a:b7:32:5a:24:a2\n-----BEGIN CERTIFICATE-----\nMIIB3DCCAYOgAwIBAgINAgPlfvU/k/2lCSGypjAKBggqhkjOPQQDAjBQMSQwIgYD\nVQQLExtHbG9iYWxTaWduIEVDQyBSb290IENBIC0gUjQxEzARBgNVBAoTCkdsb2Jh\nbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wHhcNMTIxMTEzMDAwMDAwWhcNMzgw\nMTE5MDMxNDA3WjBQMSQwIgYDVQQLExtHbG9iYWxTaWduIEVDQyBSb290IENBIC0g\nUjQxEzARBgNVBAoTCkdsb2JhbFNpZ24xEzARBgNVBAMTCkdsb2JhbFNpZ24wWTAT\nBgcqhkjOPQIBBggqhkjOPQMBBwNCAAS4xnnTj2wlDp8uORkcA6SumuU5BwkWymOx\nuYb4ilfBV85C+nOh92VC/x7BALJucw7/xyHlGKSq2XE/qNS5zowdo0IwQDAOBgNV\nHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUVLB7rUW44kB/\n+wpu+74zyTyjhNUwCgYIKoZIzj0EAwIDRwAwRAIgIk90crlgr/HmnKAWBVBfw147\nbmF0774BxL4YSFlhgjICICadVGNA3jdgUM/I2O2dgq43mLyjj0xMqTQrbO/7lZsm\n-----END CERTIFICATE-----\n\n# Issuer: CN=GTS Root R1 O=Google Trust Services LLC\n# Subject: CN=GTS Root R1 O=Google Trust Services LLC\n# Label: \"GTS Root R1\"\n# Serial: 159662320309726417404178440727\n# MD5 Fingerprint: 05:fe:d0:bf:71:a8:a3:76:63:da:01:e0:d8:52:dc:40\n# SHA1 Fingerprint: e5:8c:1c:c4:91:3b:38:63:4b:e9:10:6e:e3:ad:8e:6b:9d:d9:81:4a\n# SHA256 Fingerprint: d9:47:43:2a:bd:e7:b7:fa:90:fc:2e:6b:59:10:1b:12:80:e0:e1:c7:e4:e4:0f:a3:c6:88:7f:ff:57:a7:f4:cf\n-----BEGIN CERTIFICATE-----\nMIIFVzCCAz+gAwIBAgINAgPlk28xsBNJiGuiFzANBgkqhkiG9w0BAQwFADBHMQsw\nCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU\nMBIGA1UEAxMLR1RTIFJvb3QgUjEwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw\nMDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp\nY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjEwggIiMA0GCSqGSIb3DQEBAQUA\nA4ICDwAwggIKAoICAQC2EQKLHuOhd5s73L+UPreVp0A8of2C+X0yBoJx9vaMf/vo\n27xqLpeXo4xL+Sv2sfnOhB2x+cWX3u+58qPpvBKJXqeqUqv4IyfLpLGcY9vXmX7w\nCl7raKb0xlpHDU0QM+NOsROjyBhsS+z8CZDfnWQpJSMHobTSPS5g4M/SCYe7zUjw\nTcLCeoiKu7rPWRnWr4+wB7CeMfGCwcDfLqZtbBkOtdh+JhpFAz2weaSUKK0Pfybl\nqAj+lug8aJRT7oM6iCsVlgmy4HqMLnXWnOunVmSPlk9orj2XwoSPwLxAwAtcvfaH\nszVsrBhQf4TgTM2S0yDpM7xSma8ytSmzJSq0SPly4cpk9+aCEI3oncKKiPo4Zor8\nY/kB+Xj9e1x3+naH+uzfsQ55lVe0vSbv1gHR6xYKu44LtcXFilWr06zqkUspzBmk\nMiVOKvFlRNACzqrOSbTqn3yDsEB750Orp2yjj32JgfpMpf/VjsPOS+C12LOORc92\nwO1AK/1TD7Cn1TsNsYqiA94xrcx36m97PtbfkSIS5r762DL8EGMUUXLeXdYWk70p\naDPvOmbsB4om3xPXV2V4J95eSRQAogB/mqghtqmxlbCluQ0WEdrHbEg8QOB+DVrN\nVjzRlwW5y0vtOUucxD/SVRNuJLDWcfr0wbrM7Rv1/oFB2ACYPTrIrnqYNxgFlQID\nAQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E\nFgQU5K8rJnEaK0gnhS9SZizv8IkTcT4wDQYJKoZIhvcNAQEMBQADggIBAJ+qQibb\nC5u+/x6Wki4+omVKapi6Ist9wTrYggoGxval3sBOh2Z5ofmmWJyq+bXmYOfg6LEe\nQkEzCzc9zolwFcq1JKjPa7XSQCGYzyI0zzvFIoTgxQ6KfF2I5DUkzps+GlQebtuy\nh6f88/qBVRRiClmpIgUxPoLW7ttXNLwzldMXG+gnoot7TiYaelpkttGsN/H9oPM4\n7HLwEXWdyzRSjeZ2axfG34arJ45JK3VmgRAhpuo+9K4l/3wV3s6MJT/KYnAK9y8J\nZgfIPxz88NtFMN9iiMG1D53Dn0reWVlHxYciNuaCp+0KueIHoI17eko8cdLiA6Ef\nMgfdG+RCzgwARWGAtQsgWSl4vflVy2PFPEz0tv/bal8xa5meLMFrUKTX5hgUvYU/\nZ6tGn6D/Qqc6f1zLXbBwHSs09dR2CQzreExZBfMzQsNhFRAbd03OIozUhfJFfbdT\n6u9AWpQKXCBfTkBdYiJ23//OYb2MI3jSNwLgjt7RETeJ9r/tSQdirpLsQBqvFAnZ\n0E6yove+7u7Y/9waLd64NnHi/Hm3lCXRSHNboTXns5lndcEZOitHTtNCjv0xyBZm\n2tIMPNuzjsmhDYAPexZ3FL//2wmUspO8IFgV6dtxQ/PeEMMA3KgqlbbC1j+Qa3bb\nbP6MvPJwNQzcmRk13NfIRmPVNnGuV/u3gm3c\n-----END CERTIFICATE-----\n\n# Issuer: CN=GTS Root R2 O=Google Trust Services LLC\n# Subject: CN=GTS Root R2 O=Google Trust Services LLC\n# Label: \"GTS Root R2\"\n# Serial: 159662449406622349769042896298\n# MD5 Fingerprint: 1e:39:c0:53:e6:1e:29:82:0b:ca:52:55:36:5d:57:dc\n# SHA1 Fingerprint: 9a:44:49:76:32:db:de:fa:d0:bc:fb:5a:7b:17:bd:9e:56:09:24:94\n# SHA256 Fingerprint: 8d:25:cd:97:22:9d:bf:70:35:6b:da:4e:b3:cc:73:40:31:e2:4c:f0:0f:af:cf:d3:2d:c7:6e:b5:84:1c:7e:a8\n-----BEGIN CERTIFICATE-----\nMIIFVzCCAz+gAwIBAgINAgPlrsWNBCUaqxElqjANBgkqhkiG9w0BAQwFADBHMQsw\nCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU\nMBIGA1UEAxMLR1RTIFJvb3QgUjIwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw\nMDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp\nY2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjIwggIiMA0GCSqGSIb3DQEBAQUA\nA4ICDwAwggIKAoICAQDO3v2m++zsFDQ8BwZabFn3GTXd98GdVarTzTukk3LvCvpt\nnfbwhYBboUhSnznFt+4orO/LdmgUud+tAWyZH8QiHZ/+cnfgLFuv5AS/T3KgGjSY\n6Dlo7JUle3ah5mm5hRm9iYz+re026nO8/4Piy33B0s5Ks40FnotJk9/BW9BuXvAu\nMC6C/Pq8tBcKSOWIm8Wba96wyrQD8Nr0kLhlZPdcTK3ofmZemde4wj7I0BOdre7k\nRXuJVfeKH2JShBKzwkCX44ofR5GmdFrS+LFjKBC4swm4VndAoiaYecb+3yXuPuWg\nf9RhD1FLPD+M2uFwdNjCaKH5wQzpoeJ/u1U8dgbuak7MkogwTZq9TwtImoS1mKPV\n+3PBV2HdKFZ1E66HjucMUQkQdYhMvI35ezzUIkgfKtzra7tEscszcTJGr61K8Yzo\ndDqs5xoic4DSMPclQsciOzsSrZYuxsN2B6ogtzVJV+mSSeh2FnIxZyuWfoqjx5RW\nIr9qS34BIbIjMt/kmkRtWVtd9QCgHJvGeJeNkP+byKq0rxFROV7Z+2et1VsRnTKa\nG73VululycslaVNVJ1zgyjbLiGH7HrfQy+4W+9OmTN6SpdTi3/UGVN4unUu0kzCq\ngc7dGtxRcw1PcOnlthYhGXmy5okLdWTK1au8CcEYof/UVKGFPP0UJAOyh9OktwID\nAQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E\nFgQUu//KjiOfT5nK2+JopqUVJxce2Q4wDQYJKoZIhvcNAQEMBQADggIBAB/Kzt3H\nvqGf2SdMC9wXmBFqiN495nFWcrKeGk6c1SuYJF2ba3uwM4IJvd8lRuqYnrYb/oM8\n0mJhwQTtzuDFycgTE1XnqGOtjHsB/ncw4c5omwX4Eu55MaBBRTUoCnGkJE+M3DyC\nB19m3H0Q/gxhswWV7uGugQ+o+MePTagjAiZrHYNSVc61LwDKgEDg4XSsYPWHgJ2u\nNmSRXbBoGOqKYcl3qJfEycel/FVL8/B/uWU9J2jQzGv6U53hkRrJXRqWbTKH7QMg\nyALOWr7Z6v2yTcQvG99fevX4i8buMTolUVVnjWQye+mew4K6Ki3pHrTgSAai/Gev\nHyICc/sgCq+dVEuhzf9gR7A/Xe8bVr2XIZYtCtFenTgCR2y59PYjJbigapordwj6\nxLEokCZYCDzifqrXPW+6MYgKBesntaFJ7qBFVHvmJ2WZICGoo7z7GJa7Um8M7YNR\nTOlZ4iBgxcJlkoKM8xAfDoqXvneCbT+PHV28SSe9zE8P4c52hgQjxcCMElv924Sg\nJPFI/2R80L5cFtHvma3AH/vLrrw4IgYmZNralw4/KBVEqE8AyvCazM90arQ+POuV\n7LXTWtiBmelDGDfrs7vRWGJB82bSj6p4lVQgw1oudCvV0b4YacCs1aTPObpRhANl\n6WLAYv7YTVWW4tAR+kg0Eeye7QUd5MjWHYbL\n-----END CERTIFICATE-----\n\n# Issuer: CN=GTS Root R3 O=Google Trust Services LLC\n# Subject: CN=GTS Root R3 O=Google Trust Services LLC\n# Label: \"GTS Root R3\"\n# Serial: 159662495401136852707857743206\n# MD5 Fingerprint: 3e:e7:9d:58:02:94:46:51:94:e5:e0:22:4a:8b:e7:73\n# SHA1 Fingerprint: ed:e5:71:80:2b:c8:92:b9:5b:83:3c:d2:32:68:3f:09:cd:a0:1e:46\n# SHA256 Fingerprint: 34:d8:a7:3e:e2:08:d9:bc:db:0d:95:65:20:93:4b:4e:40:e6:94:82:59:6e:8b:6f:73:c8:42:6b:01:0a:6f:48\n-----BEGIN CERTIFICATE-----\nMIICCTCCAY6gAwIBAgINAgPluILrIPglJ209ZjAKBggqhkjOPQQDAzBHMQswCQYD\nVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIG\nA1UEAxMLR1RTIFJvb3QgUjMwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAw\nWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2Vz\nIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjMwdjAQBgcqhkjOPQIBBgUrgQQAIgNi\nAAQfTzOHMymKoYTey8chWEGJ6ladK0uFxh1MJ7x/JlFyb+Kf1qPKzEUURout736G\njOyxfi//qXGdGIRFBEFVbivqJn+7kAHjSxm65FSWRQmx1WyRRK2EE46ajA2ADDL2\n4CejQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW\nBBTB8Sa6oC2uhYHP0/EqEr24Cmf9vDAKBggqhkjOPQQDAwNpADBmAjEA9uEglRR7\nVKOQFhG/hMjqb2sXnh5GmCCbn9MN2azTL818+FsuVbu/3ZL3pAzcMeGiAjEA/Jdm\nZuVDFhOD3cffL74UOO0BzrEXGhF16b0DjyZ+hOXJYKaV11RZt+cRLInUue4X\n-----END CERTIFICATE-----\n\n# Issuer: CN=GTS Root R4 O=Google Trust Services LLC\n# Subject: CN=GTS Root R4 O=Google Trust Services LLC\n# Label: \"GTS Root R4\"\n# Serial: 159662532700760215368942768210\n# MD5 Fingerprint: 43:96:83:77:19:4d:76:b3:9d:65:52:e4:1d:22:a5:e8\n# SHA1 Fingerprint: 77:d3:03:67:b5:e0:0c:15:f6:0c:38:61:df:7c:e1:3b:92:46:4d:47\n# SHA256 Fingerprint: 34:9d:fa:40:58:c5:e2:63:12:3b:39:8a:e7:95:57:3c:4e:13:13:c8:3f:e6:8f:93:55:6c:d5:e8:03:1b:3c:7d\n-----BEGIN CERTIFICATE-----\nMIICCTCCAY6gAwIBAgINAgPlwGjvYxqccpBQUjAKBggqhkjOPQQDAzBHMQswCQYD\nVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEUMBIG\nA1UEAxMLR1RTIFJvb3QgUjQwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAwMDAw\nWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2Vz\nIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjQwdjAQBgcqhkjOPQIBBgUrgQQAIgNi\nAATzdHOnaItgrkO4NcWBMHtLSZ37wWHO5t5GvWvVYRg1rkDdc/eJkTBa6zzuhXyi\nQHY7qca4R9gq55KRanPpsXI5nymfopjTX15YhmUPoYRlBtHci8nHc8iMai/lxKvR\nHYqjQjBAMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQW\nBBSATNbrdP9JNqPV2Py1PsVq8JQdjDAKBggqhkjOPQQDAwNpADBmAjEA6ED/g94D\n9J+uHXqnLrmvT/aDHQ4thQEd0dlq7A/Cr8deVl5c1RxYIigL9zC2L7F8AjEA8GE8\np/SgguMh1YQdc4acLa/KNJvxn7kjNuK8YAOdgLOaVsjh4rsUecrNIdSUtUlD\n-----END CERTIFICATE-----\n\n# Issuer: CN=Telia Root CA v2 O=Telia Finland Oyj\n# Subject: CN=Telia Root CA v2 O=Telia Finland Oyj\n# Label: \"Telia Root CA v2\"\n# Serial: 7288924052977061235122729490515358\n# MD5 Fingerprint: 0e:8f:ac:aa:82:df:85:b1:f4:dc:10:1c:fc:99:d9:48\n# SHA1 Fingerprint: b9:99:cd:d1:73:50:8a:c4:47:05:08:9c:8c:88:fb:be:a0:2b:40:cd\n# SHA256 Fingerprint: 24:2b:69:74:2f:cb:1e:5b:2a:bf:98:89:8b:94:57:21:87:54:4e:5b:4d:99:11:78:65:73:62:1f:6a:74:b8:2c\n-----BEGIN CERTIFICATE-----\nMIIFdDCCA1ygAwIBAgIPAWdfJ9b+euPkrL4JWwWeMA0GCSqGSIb3DQEBCwUAMEQx\nCzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZMBcGA1UE\nAwwQVGVsaWEgUm9vdCBDQSB2MjAeFw0xODExMjkxMTU1NTRaFw00MzExMjkxMTU1\nNTRaMEQxCzAJBgNVBAYTAkZJMRowGAYDVQQKDBFUZWxpYSBGaW5sYW5kIE95ajEZ\nMBcGA1UEAwwQVGVsaWEgUm9vdCBDQSB2MjCCAiIwDQYJKoZIhvcNAQEBBQADggIP\nADCCAgoCggIBALLQPwe84nvQa5n44ndp586dpAO8gm2h/oFlH0wnrI4AuhZ76zBq\nAMCzdGh+sq/H1WKzej9Qyow2RCRj0jbpDIX2Q3bVTKFgcmfiKDOlyzG4OiIjNLh9\nvVYiQJ3q9HsDrWj8soFPmNB06o3lfc1jw6P23pLCWBnglrvFxKk9pXSW/q/5iaq9\nlRdU2HhE8Qx3FZLgmEKnpNaqIJLNwaCzlrI6hEKNfdWV5Nbb6WLEWLN5xYzTNTOD\nn3WhUidhOPFZPY5Q4L15POdslv5e2QJltI5c0BE0312/UqeBAMN/mUWZFdUXyApT\n7GPzmX3MaRKGwhfwAZ6/hLzRUssbkmbOpFPlob/E2wnW5olWK8jjfN7j/4nlNW4o\n6GwLI1GpJQXrSPjdscr6bAhR77cYbETKJuFzxokGgeWKrLDiKca5JLNrRBH0pUPC\nTEPlcDaMtjNXepUugqD0XBCzYYP2AgWGLnwtbNwDRm41k9V6lS/eINhbfpSQBGq6\nWT0EBXWdN6IOLj3rwaRSg/7Qa9RmjtzG6RJOHSpXqhC8fF6CfaamyfItufUXJ63R\nDolUK5X6wK0dmBR4M0KGCqlztft0DbcbMBnEWg4cJ7faGND/isgFuvGqHKI3t+ZI\npEYslOqodmJHixBTB0hXbOKSTbauBcvcwUpej6w9GU7C7WB1K9vBykLVAgMBAAGj\nYzBhMB8GA1UdIwQYMBaAFHKs5DN5qkWH9v2sHZ7Wxy+G2CQ5MB0GA1UdDgQWBBRy\nrOQzeapFh/b9rB2e1scvhtgkOTAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUw\nAwEB/zANBgkqhkiG9w0BAQsFAAOCAgEAoDtZpwmUPjaE0n4vOaWWl/oRrfxn83EJ\n8rKJhGdEr7nv7ZbsnGTbMjBvZ5qsfl+yqwE2foH65IRe0qw24GtixX1LDoJt0nZi\n0f6X+J8wfBj5tFJ3gh1229MdqfDBmgC9bXXYfef6xzijnHDoRnkDry5023X4blMM\nA8iZGok1GTzTyVR8qPAs5m4HeW9q4ebqkYJpCh3DflminmtGFZhb069GHWLIzoBS\nSRE/yQQSwxN8PzuKlts8oB4KtItUsiRnDe+Cy748fdHif64W1lZYudogsYMVoe+K\nTTJvQS8TUoKU1xrBeKJR3Stwbbca+few4GeXVtt8YVMJAygCQMez2P2ccGrGKMOF\n6eLtGpOg3kuYooQ+BXcBlj37tCAPnHICehIv1aO6UXivKitEZU61/Qrowc15h2Er\n3oBXRb9n8ZuRXqWk7FlIEA04x7D6w0RtBPV4UBySllva9bguulvP5fBqnUsvWHMt\nTy3EHD70sz+rFQ47GUGKpMFXEmZxTPpT41frYpUJnlTd0cI8Vzy9OK2YZLe4A5pT\nVmBds9hCG1xLEooc6+t9xnppxyd/pPiL8uSUZodL6ZQHCRJ5irLrdATczvREWeAW\nysUsWNc8e89ihmpQfTU2Zqf7N+cox9jQraVplI/owd8k+BsHMYeB2F326CjYSlKA\nrBPuUBQemMc=\n-----END CERTIFICATE-----\n\n# Issuer: CN=D-TRUST BR Root CA 1 2020 O=D-Trust GmbH\n# Subject: CN=D-TRUST BR Root CA 1 2020 O=D-Trust GmbH\n# Label: \"D-TRUST BR Root CA 1 2020\"\n# Serial: 165870826978392376648679885835942448534\n# MD5 Fingerprint: b5:aa:4b:d5:ed:f7:e3:55:2e:8f:72:0a:f3:75:b8:ed\n# SHA1 Fingerprint: 1f:5b:98:f0:e3:b5:f7:74:3c:ed:e6:b0:36:7d:32:cd:f4:09:41:67\n# SHA256 Fingerprint: e5:9a:aa:81:60:09:c2:2b:ff:5b:25:ba:d3:7d:f3:06:f0:49:79:7c:1f:81:d8:5a:b0:89:e6:57:bd:8f:00:44\n-----BEGIN CERTIFICATE-----\nMIIC2zCCAmCgAwIBAgIQfMmPK4TX3+oPyWWa00tNljAKBggqhkjOPQQDAzBIMQsw\nCQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlELVRS\nVVNUIEJSIFJvb3QgQ0EgMSAyMDIwMB4XDTIwMDIxMTA5NDUwMFoXDTM1MDIxMTA5\nNDQ1OVowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEiMCAG\nA1UEAxMZRC1UUlVTVCBCUiBSb290IENBIDEgMjAyMDB2MBAGByqGSM49AgEGBSuB\nBAAiA2IABMbLxyjR+4T1mu9CFCDhQ2tuda38KwOE1HaTJddZO0Flax7mNCq7dPYS\nzuht56vkPE4/RAiLzRZxy7+SmfSk1zxQVFKQhYN4lGdnoxwJGT11NIXe7WB9xwy0\nQVK5buXuQqOCAQ0wggEJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFHOREKv/\nVbNafAkl1bK6CKBrqx9tMA4GA1UdDwEB/wQEAwIBBjCBxgYDVR0fBIG+MIG7MD6g\nPKA6hjhodHRwOi8vY3JsLmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X2JyX3Jvb3Rf\nY2FfMV8yMDIwLmNybDB5oHegdYZzbGRhcDovL2RpcmVjdG9yeS5kLXRydXN0Lm5l\ndC9DTj1ELVRSVVNUJTIwQlIlMjBSb290JTIwQ0ElMjAxJTIwMjAyMCxPPUQtVHJ1\nc3QlMjBHbWJILEM9REU/Y2VydGlmaWNhdGVyZXZvY2F0aW9ubGlzdDAKBggqhkjO\nPQQDAwNpADBmAjEAlJAtE/rhY/hhY+ithXhUkZy4kzg+GkHaQBZTQgjKL47xPoFW\nwKrY7RjEsK70PvomAjEA8yjixtsrmfu3Ubgko6SUeho/5jbiA1czijDLgsfWFBHV\ndWNbFJWcHwHP2NVypw87\n-----END CERTIFICATE-----\n\n# Issuer: CN=D-TRUST EV Root CA 1 2020 O=D-Trust GmbH\n# Subject: CN=D-TRUST EV Root CA 1 2020 O=D-Trust GmbH\n# Label: \"D-TRUST EV Root CA 1 2020\"\n# Serial: 126288379621884218666039612629459926992\n# MD5 Fingerprint: 8c:2d:9d:70:9f:48:99:11:06:11:fb:e9:cb:30:c0:6e\n# SHA1 Fingerprint: 61:db:8c:21:59:69:03:90:d8:7c:9c:12:86:54:cf:9d:3d:f4:dd:07\n# SHA256 Fingerprint: 08:17:0d:1a:a3:64:53:90:1a:2f:95:92:45:e3:47:db:0c:8d:37:ab:aa:bc:56:b8:1a:a1:00:dc:95:89:70:db\n-----BEGIN CERTIFICATE-----\nMIIC2zCCAmCgAwIBAgIQXwJB13qHfEwDo6yWjfv/0DAKBggqhkjOPQQDAzBIMQsw\nCQYDVQQGEwJERTEVMBMGA1UEChMMRC1UcnVzdCBHbWJIMSIwIAYDVQQDExlELVRS\nVVNUIEVWIFJvb3QgQ0EgMSAyMDIwMB4XDTIwMDIxMTEwMDAwMFoXDTM1MDIxMTA5\nNTk1OVowSDELMAkGA1UEBhMCREUxFTATBgNVBAoTDEQtVHJ1c3QgR21iSDEiMCAG\nA1UEAxMZRC1UUlVTVCBFViBSb290IENBIDEgMjAyMDB2MBAGByqGSM49AgEGBSuB\nBAAiA2IABPEL3YZDIBnfl4XoIkqbz52Yv7QFJsnL46bSj8WeeHsxiamJrSc8ZRCC\n/N/DnU7wMyPE0jL1HLDfMxddxfCxivnvubcUyilKwg+pf3VlSSowZ/Rk99Yad9rD\nwpdhQntJraOCAQ0wggEJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFH8QARY3\nOqQo5FD4pPfsazK2/umLMA4GA1UdDwEB/wQEAwIBBjCBxgYDVR0fBIG+MIG7MD6g\nPKA6hjhodHRwOi8vY3JsLmQtdHJ1c3QubmV0L2NybC9kLXRydXN0X2V2X3Jvb3Rf\nY2FfMV8yMDIwLmNybDB5oHegdYZzbGRhcDovL2RpcmVjdG9yeS5kLXRydXN0Lm5l\ndC9DTj1ELVRSVVNUJTIwRVYlMjBSb290JTIwQ0ElMjAxJTIwMjAyMCxPPUQtVHJ1\nc3QlMjBHbWJILEM9REU/Y2VydGlmaWNhdGVyZXZvY2F0aW9ubGlzdDAKBggqhkjO\nPQQDAwNpADBmAjEAyjzGKnXCXnViOTYAYFqLwZOZzNnbQTs7h5kXO9XMT8oi96CA\ny/m0sRtW9XLS/BnRAjEAkfcwkz8QRitxpNA7RJvAKQIFskF3UfN5Wp6OFKBOQtJb\ngfM0agPnIjhQW+0ZT0MW\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert TLS ECC P384 Root G5 O=DigiCert, Inc.\n# Subject: CN=DigiCert TLS ECC P384 Root G5 O=DigiCert, Inc.\n# Label: \"DigiCert TLS ECC P384 Root G5\"\n# Serial: 13129116028163249804115411775095713523\n# MD5 Fingerprint: d3:71:04:6a:43:1c:db:a6:59:e1:a8:a3:aa:c5:71:ed\n# SHA1 Fingerprint: 17:f3:de:5e:9f:0f:19:e9:8e:f6:1f:32:26:6e:20:c4:07:ae:30:ee\n# SHA256 Fingerprint: 01:8e:13:f0:77:25:32:cf:80:9b:d1:b1:72:81:86:72:83:fc:48:c6:e1:3b:e9:c6:98:12:85:4a:49:0c:1b:05\n-----BEGIN CERTIFICATE-----\nMIICGTCCAZ+gAwIBAgIQCeCTZaz32ci5PhwLBCou8zAKBggqhkjOPQQDAzBOMQsw\nCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJjAkBgNVBAMTHURp\nZ2lDZXJ0IFRMUyBFQ0MgUDM4NCBSb290IEc1MB4XDTIxMDExNTAwMDAwMFoXDTQ2\nMDExNDIzNTk1OVowTjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lDZXJ0LCBJ\nbmMuMSYwJAYDVQQDEx1EaWdpQ2VydCBUTFMgRUNDIFAzODQgUm9vdCBHNTB2MBAG\nByqGSM49AgEGBSuBBAAiA2IABMFEoc8Rl1Ca3iOCNQfN0MsYndLxf3c1TzvdlHJS\n7cI7+Oz6e2tYIOyZrsn8aLN1udsJ7MgT9U7GCh1mMEy7H0cKPGEQQil8pQgO4CLp\n0zVozptjn4S1mU1YoI71VOeVyaNCMEAwHQYDVR0OBBYEFMFRRVBZqz7nLFr6ICIS\nB4CIfBFqMA4GA1UdDwEB/wQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49\nBAMDA2gAMGUCMQCJao1H5+z8blUD2WdsJk6Dxv3J+ysTvLd6jLRl0mlpYxNjOyZQ\nLgGheQaRnUi/wr4CMEfDFXuxoJGZSZOoPHzoRgaLLPIxAJSdYsiJvRmEFOml+wG4\nDXZDjC5Ty3zfDBeWUA==\n-----END CERTIFICATE-----\n\n# Issuer: CN=DigiCert TLS RSA4096 Root G5 O=DigiCert, Inc.\n# Subject: CN=DigiCert TLS RSA4096 Root G5 O=DigiCert, Inc.\n# Label: \"DigiCert TLS RSA4096 Root G5\"\n# Serial: 11930366277458970227240571539258396554\n# MD5 Fingerprint: ac:fe:f7:34:96:a9:f2:b3:b4:12:4b:e4:27:41:6f:e1\n# SHA1 Fingerprint: a7:88:49:dc:5d:7c:75:8c:8c:de:39:98:56:b3:aa:d0:b2:a5:71:35\n# SHA256 Fingerprint: 37:1a:00:dc:05:33:b3:72:1a:7e:eb:40:e8:41:9e:70:79:9d:2b:0a:0f:2c:1d:80:69:31:65:f7:ce:c4:ad:75\n-----BEGIN CERTIFICATE-----\nMIIFZjCCA06gAwIBAgIQCPm0eKj6ftpqMzeJ3nzPijANBgkqhkiG9w0BAQwFADBN\nMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQsIEluYy4xJTAjBgNVBAMT\nHERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwHhcNMjEwMTE1MDAwMDAwWhcN\nNDYwMTE0MjM1OTU5WjBNMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGlnaUNlcnQs\nIEluYy4xJTAjBgNVBAMTHERpZ2lDZXJ0IFRMUyBSU0E0MDk2IFJvb3QgRzUwggIi\nMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCz0PTJeRGd/fxmgefM1eS87IE+\najWOLrfn3q/5B03PMJ3qCQuZvWxX2hhKuHisOjmopkisLnLlvevxGs3npAOpPxG0\n2C+JFvuUAT27L/gTBaF4HI4o4EXgg/RZG5Wzrn4DReW+wkL+7vI8toUTmDKdFqgp\nwgscONyfMXdcvyej/Cestyu9dJsXLfKB2l2w4SMXPohKEiPQ6s+d3gMXsUJKoBZM\npG2T6T867jp8nVid9E6P/DsjyG244gXazOvswzH016cpVIDPRFtMbzCe88zdH5RD\nnU1/cHAN1DrRN/BsnZvAFJNY781BOHW8EwOVfH/jXOnVDdXifBBiqmvwPXbzP6Po\nsMH976pXTayGpxi0KcEsDr9kvimM2AItzVwv8n/vFfQMFawKsPHTDU9qTXeXAaDx\nZre3zu/O7Oyldcqs4+Fj97ihBMi8ez9dLRYiVu1ISf6nL3kwJZu6ay0/nTvEF+cd\nLvvyz6b84xQslpghjLSR6Rlgg/IwKwZzUNWYOwbpx4oMYIwo+FKbbuH2TbsGJJvX\nKyY//SovcfXWJL5/MZ4PbeiPT02jP/816t9JXkGPhvnxd3lLG7SjXi/7RgLQZhNe\nXoVPzthwiHvOAbWWl9fNff2C+MIkwcoBOU+NosEUQB+cZtUMCUbW8tDRSHZWOkPL\ntgoRObqME2wGtZ7P6wIDAQABo0IwQDAdBgNVHQ4EFgQUUTMc7TZArxfTJc1paPKv\nTiM+s0EwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN\nAQEMBQADggIBAGCmr1tfV9qJ20tQqcQjNSH/0GEwhJG3PxDPJY7Jv0Y02cEhJhxw\nGXIeo8mH/qlDZJY6yFMECrZBu8RHANmfGBg7sg7zNOok992vIGCukihfNudd5N7H\nPNtQOa27PShNlnx2xlv0wdsUpasZYgcYQF+Xkdycx6u1UQ3maVNVzDl92sURVXLF\nO4uJ+DQtpBflF+aZfTCIITfNMBc9uPK8qHWgQ9w+iUuQrm0D4ByjoJYJu32jtyoQ\nREtGBzRj7TG5BO6jm5qu5jF49OokYTurWGT/u4cnYiWB39yhL/btp/96j1EuMPik\nAdKFOV8BmZZvWltwGUb+hmA+rYAQCd05JS9Yf7vSdPD3Rh9GOUrYU9DzLjtxpdRv\n/PNn5AeP3SYZ4Y1b+qOTEZvpyDrDVWiakuFSdjjo4bq9+0/V77PnSIMx8IIh47a+\np6tv75/fTM8BuGJqIz3nCU2AG3swpMPdB380vqQmsvZB6Akd4yCYqjdP//fx4ilw\nMUc/dNAUFvohigLVigmUdy7yWSiLfFCSCmZ4OIN1xLVaqBHG5cGdZlXPU8Sv13WF\nqUITVuwhd4GTWgzqltlJyqEI8pc7bZsEGCREjnwB8twl2F6GmrE52/WRMmrRpnCK\novfepEWFJqgejF0pW8hL2JpqA15w8oVPbEtoL8pU9ozaMv7Da4M/OMZ+\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certainly Root R1 O=Certainly\n# Subject: CN=Certainly Root R1 O=Certainly\n# Label: \"Certainly Root R1\"\n# Serial: 188833316161142517227353805653483829216\n# MD5 Fingerprint: 07:70:d4:3e:82:87:a0:fa:33:36:13:f4:fa:33:e7:12\n# SHA1 Fingerprint: a0:50:ee:0f:28:71:f4:27:b2:12:6d:6f:50:96:25:ba:cc:86:42:af\n# SHA256 Fingerprint: 77:b8:2c:d8:64:4c:43:05:f7:ac:c5:cb:15:6b:45:67:50:04:03:3d:51:c6:0c:62:02:a8:e0:c3:34:67:d3:a0\n-----BEGIN CERTIFICATE-----\nMIIFRzCCAy+gAwIBAgIRAI4P+UuQcWhlM1T01EQ5t+AwDQYJKoZIhvcNAQELBQAw\nPTELMAkGA1UEBhMCVVMxEjAQBgNVBAoTCUNlcnRhaW5seTEaMBgGA1UEAxMRQ2Vy\ndGFpbmx5IFJvb3QgUjEwHhcNMjEwNDAxMDAwMDAwWhcNNDYwNDAxMDAwMDAwWjA9\nMQswCQYDVQQGEwJVUzESMBAGA1UEChMJQ2VydGFpbmx5MRowGAYDVQQDExFDZXJ0\nYWlubHkgUm9vdCBSMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANA2\n1B/q3avk0bbm+yLA3RMNansiExyXPGhjZjKcA7WNpIGD2ngwEc/csiu+kr+O5MQT\nvqRoTNoCaBZ0vrLdBORrKt03H2As2/X3oXyVtwxwhi7xOu9S98zTm/mLvg7fMbed\naFySpvXl8wo0tf97ouSHocavFwDvA5HtqRxOcT3Si2yJ9HiG5mpJoM610rCrm/b0\n1C7jcvk2xusVtyWMOvwlDbMicyF0yEqWYZL1LwsYpfSt4u5BvQF5+paMjRcCMLT5\nr3gajLQ2EBAHBXDQ9DGQilHFhiZ5shGIXsXwClTNSaa/ApzSRKft43jvRl5tcdF5\ncBxGX1HpyTfcX35pe0HfNEXgO4T0oYoKNp43zGJS4YkNKPl6I7ENPT2a/Z2B7yyQ\nwHtETrtJ4A5KVpK8y7XdeReJkd5hiXSSqOMyhb5OhaRLWcsrxXiOcVTQAjeZjOVJ\n6uBUcqQRBi8LjMFbvrWhsFNunLhgkR9Za/kt9JQKl7XsxXYDVBtlUrpMklZRNaBA\n2CnbrlJ2Oy0wQJuK0EJWtLeIAaSHO1OWzaMWj/Nmqhexx2DgwUMFDO6bW2BvBlyH\nWyf5QBGenDPBt+U1VwV/J84XIIwc/PH72jEpSe31C4SnT8H2TsIonPru4K8H+zMR\neiFPCyEQtkA6qyI6BJyLm4SGcprSp6XEtHWRqSsjAgMBAAGjQjBAMA4GA1UdDwEB\n/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTgqj8ljZ9EXME66C6u\nd0yEPmcM9DANBgkqhkiG9w0BAQsFAAOCAgEAuVevuBLaV4OPaAszHQNTVfSVcOQr\nPbA56/qJYv331hgELyE03fFo8NWWWt7CgKPBjcZq91l3rhVkz1t5BXdm6ozTaw3d\n8VkswTOlMIAVRQdFGjEitpIAq5lNOo93r6kiyi9jyhXWx8bwPWz8HA2YEGGeEaIi\n1wrykXprOQ4vMMM2SZ/g6Q8CRFA3lFV96p/2O7qUpUzpvD5RtOjKkjZUbVwlKNrd\nrRT90+7iIgXr0PK3aBLXWopBGsaSpVo7Y0VPv+E6dyIvXL9G+VoDhRNCX8reU9di\ntaY1BMJH/5n9hN9czulegChB8n3nHpDYT3Y+gjwN/KUD+nsa2UUeYNrEjvn8K8l7\nlcUq/6qJ34IxD3L/DCfXCh5WAFAeDJDBlrXYFIW7pw0WwfgHJBu6haEaBQmAupVj\nyTrsJZ9/nbqkRxWbRHDxakvWOF5D8xh+UG7pWijmZeZ3Gzr9Hb4DJqPb1OG7fpYn\nKx3upPvaJVQTA945xsMfTZDsjxtK0hzthZU4UHlG1sGQUDGpXJpuHfUzVounmdLy\nyCwzk5Iwx06MZTMQZBf9JBeW0Y3COmor6xOLRPIh80oat3df1+2IpHLlOR+Vnb5n\nwXARPbv0+Em34yaXOp/SX3z7wJl8OSngex2/DaeP0ik0biQVy96QXr8axGbqwua6\nOV+KmalBWQewLK8=\n-----END CERTIFICATE-----\n\n# Issuer: CN=Certainly Root E1 O=Certainly\n# Subject: CN=Certainly Root E1 O=Certainly\n# Label: \"Certainly Root E1\"\n# Serial: 8168531406727139161245376702891150584\n# MD5 Fingerprint: 0a:9e:ca:cd:3e:52:50:c6:36:f3:4b:a3:ed:a7:53:e9\n# SHA1 Fingerprint: f9:e1:6d:dc:01:89:cf:d5:82:45:63:3e:c5:37:7d:c2:eb:93:6f:2b\n# SHA256 Fingerprint: b4:58:5f:22:e4:ac:75:6a:4e:86:12:a1:36:1c:5d:9d:03:1a:93:fd:84:fe:bb:77:8f:a3:06:8b:0f:c4:2d:c2\n-----BEGIN CERTIFICATE-----\nMIIB9zCCAX2gAwIBAgIQBiUzsUcDMydc+Y2aub/M+DAKBggqhkjOPQQDAzA9MQsw\nCQYDVQQGEwJVUzESMBAGA1UEChMJQ2VydGFpbmx5MRowGAYDVQQDExFDZXJ0YWlu\nbHkgUm9vdCBFMTAeFw0yMTA0MDEwMDAwMDBaFw00NjA0MDEwMDAwMDBaMD0xCzAJ\nBgNVBAYTAlVTMRIwEAYDVQQKEwlDZXJ0YWlubHkxGjAYBgNVBAMTEUNlcnRhaW5s\neSBSb290IEUxMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE3m/4fxzf7flHh4axpMCK\n+IKXgOqPyEpeKn2IaKcBYhSRJHpcnqMXfYqGITQYUBsQ3tA3SybHGWCA6TS9YBk2\nQNYphwk8kXr2vBMj3VlOBF7PyAIcGFPBMdjaIOlEjeR2o0IwQDAOBgNVHQ8BAf8E\nBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQU8ygYy2R17ikq6+2uI1g4\nhevIIgcwCgYIKoZIzj0EAwMDaAAwZQIxALGOWiDDshliTd6wT99u0nCK8Z9+aozm\nut6Dacpps6kFtZaSF4fC0urQe87YQVt8rgIwRt7qy12a7DLCZRawTDBcMPPaTnOG\nBtjOiQRINzf43TNRnXCve1XYAS59BWQOhriR\n-----END CERTIFICATE-----\n\n# Issuer: CN=E-Tugra Global Root CA RSA v3 O=E-Tugra EBG A.S. OU=E-Tugra Trust Center\n# Subject: CN=E-Tugra Global Root CA RSA v3 O=E-Tugra EBG A.S. OU=E-Tugra Trust Center\n# Label: \"E-Tugra Global Root CA RSA v3\"\n# Serial: 75951268308633135324246244059508261641472512052\n# MD5 Fingerprint: 22:be:10:f6:c2:f8:03:88:73:5f:33:29:47:28:47:a4\n# SHA1 Fingerprint: e9:a8:5d:22:14:52:1c:5b:aa:0a:b4:be:24:6a:23:8a:c9:ba:e2:a9\n# SHA256 Fingerprint: ef:66:b0:b1:0a:3c:db:9f:2e:36:48:c7:6b:d2:af:18:ea:d2:bf:e6:f1:17:65:5e:28:c4:06:0d:a1:a3:f4:c2\n-----BEGIN CERTIFICATE-----\nMIIF8zCCA9ugAwIBAgIUDU3FzRYilZYIfrgLfxUGNPt5EDQwDQYJKoZIhvcNAQEL\nBQAwgYAxCzAJBgNVBAYTAlRSMQ8wDQYDVQQHEwZBbmthcmExGTAXBgNVBAoTEEUt\nVHVncmEgRUJHIEEuUy4xHTAbBgNVBAsTFEUtVHVncmEgVHJ1c3QgQ2VudGVyMSYw\nJAYDVQQDEx1FLVR1Z3JhIEdsb2JhbCBSb290IENBIFJTQSB2MzAeFw0yMDAzMTgw\nOTA3MTdaFw00NTAzMTIwOTA3MTdaMIGAMQswCQYDVQQGEwJUUjEPMA0GA1UEBxMG\nQW5rYXJhMRkwFwYDVQQKExBFLVR1Z3JhIEVCRyBBLlMuMR0wGwYDVQQLExRFLVR1\nZ3JhIFRydXN0IENlbnRlcjEmMCQGA1UEAxMdRS1UdWdyYSBHbG9iYWwgUm9vdCBD\nQSBSU0EgdjMwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQCiZvCJt3J7\n7gnJY9LTQ91ew6aEOErxjYG7FL1H6EAX8z3DeEVypi6Q3po61CBxyryfHUuXCscx\nuj7X/iWpKo429NEvx7epXTPcMHD4QGxLsqYxYdE0PD0xesevxKenhOGXpOhL9hd8\n7jwH7eKKV9y2+/hDJVDqJ4GohryPUkqWOmAalrv9c/SF/YP9f4RtNGx/ardLAQO/\nrWm31zLZ9Vdq6YaCPqVmMbMWPcLzJmAy01IesGykNz709a/r4d+ABs8qQedmCeFL\nl+d3vSFtKbZnwy1+7dZ5ZdHPOrbRsV5WYVB6Ws5OUDGAA5hH5+QYfERaxqSzO8bG\nwzrwbMOLyKSRBfP12baqBqG3q+Sx6iEUXIOk/P+2UNOMEiaZdnDpwA+mdPy70Bt4\nznKS4iicvObpCdg604nmvi533wEKb5b25Y08TVJ2Glbhc34XrD2tbKNSEhhw5oBO\nM/J+JjKsBY04pOZ2PJ8QaQ5tndLBeSBrW88zjdGUdjXnXVXHt6woq0bM5zshtQoK\n5EpZ3IE1S0SVEgpnpaH/WwAH0sDM+T/8nzPyAPiMbIedBi3x7+PmBvrFZhNb/FAH\nnnGGstpvdDDPk1Po3CLW3iAfYY2jLqN4MpBs3KwytQXk9TwzDdbgh3cXTJ2w2Amo\nDVf3RIXwyAS+XF1a4xeOVGNpf0l0ZAWMowIDAQABo2MwYTAPBgNVHRMBAf8EBTAD\nAQH/MB8GA1UdIwQYMBaAFLK0ruYt9ybVqnUtdkvAG1Mh0EjvMB0GA1UdDgQWBBSy\ntK7mLfcm1ap1LXZLwBtTIdBI7zAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQEL\nBQADggIBAImocn+M684uGMQQgC0QDP/7FM0E4BQ8Tpr7nym/Ip5XuYJzEmMmtcyQ\n6dIqKe6cLcwsmb5FJ+Sxce3kOJUxQfJ9emN438o2Fi+CiJ+8EUdPdk3ILY7r3y18\nTjvarvbj2l0Upq7ohUSdBm6O++96SmotKygY/r+QLHUWnw/qln0F7psTpURs+APQ\n3SPh/QMSEgj0GDSz4DcLdxEBSL9htLX4GdnLTeqjjO/98Aa1bZL0SmFQhO3sSdPk\nvmjmLuMxC1QLGpLWgti2omU8ZgT5Vdps+9u1FGZNlIM7zR6mK7L+d0CGq+ffCsn9\n9t2HVhjYsCxVYJb6CH5SkPVLpi6HfMsg2wY+oF0Dd32iPBMbKaITVaA9FCKvb7jQ\nmhty3QUBjYZgv6Rn7rWlDdF/5horYmbDB7rnoEgcOMPpRfunf/ztAmgayncSd6YA\nVSgU7NbHEqIbZULpkejLPoeJVF3Zr52XnGnnCv8PWniLYypMfUeUP95L6VPQMPHF\n9p5J3zugkaOj/s1YzOrfr28oO6Bpm4/srK4rVJ2bBLFHIK+WEj5jlB0E5y67hscM\nmoi/dkfv97ALl2bSRM9gUgfh1SxKOidhd8rXj+eHDjD/DLsE4mHDosiXYY60MGo8\nbcIHX0pzLz/5FooBZu+6kcpSV3uu1OYP3Qt6f4ueJiDPO++BcYNZ\n-----END CERTIFICATE-----\n\n# Issuer: CN=E-Tugra Global Root CA ECC v3 O=E-Tugra EBG A.S. OU=E-Tugra Trust Center\n# Subject: CN=E-Tugra Global Root CA ECC v3 O=E-Tugra EBG A.S. OU=E-Tugra Trust Center\n# Label: \"E-Tugra Global Root CA ECC v3\"\n# Serial: 218504919822255052842371958738296604628416471745\n# MD5 Fingerprint: 46:bc:81:bb:f1:b5:1e:f7:4b:96:bc:14:e2:e7:27:64\n# SHA1 Fingerprint: 8a:2f:af:57:53:b1:b0:e6:a1:04:ec:5b:6a:69:71:6d:f6:1c:e2:84\n# SHA256 Fingerprint: 87:3f:46:85:fa:7f:56:36:25:25:2e:6d:36:bc:d7:f1:6f:c2:49:51:f2:64:e4:7e:1b:95:4f:49:08:cd:ca:13\n-----BEGIN CERTIFICATE-----\nMIICpTCCAiqgAwIBAgIUJkYZdzHhT28oNt45UYbm1JeIIsEwCgYIKoZIzj0EAwMw\ngYAxCzAJBgNVBAYTAlRSMQ8wDQYDVQQHEwZBbmthcmExGTAXBgNVBAoTEEUtVHVn\ncmEgRUJHIEEuUy4xHTAbBgNVBAsTFEUtVHVncmEgVHJ1c3QgQ2VudGVyMSYwJAYD\nVQQDEx1FLVR1Z3JhIEdsb2JhbCBSb290IENBIEVDQyB2MzAeFw0yMDAzMTgwOTQ2\nNThaFw00NTAzMTIwOTQ2NThaMIGAMQswCQYDVQQGEwJUUjEPMA0GA1UEBxMGQW5r\nYXJhMRkwFwYDVQQKExBFLVR1Z3JhIEVCRyBBLlMuMR0wGwYDVQQLExRFLVR1Z3Jh\nIFRydXN0IENlbnRlcjEmMCQGA1UEAxMdRS1UdWdyYSBHbG9iYWwgUm9vdCBDQSBF\nQ0MgdjMwdjAQBgcqhkjOPQIBBgUrgQQAIgNiAASOmCm/xxAeJ9urA8woLNheSBkQ\nKczLWYHMjLiSF4mDKpL2w6QdTGLVn9agRtwcvHbB40fQWxPa56WzZkjnIZpKT4YK\nfWzqTTKACrJ6CZtpS5iB4i7sAnCWH/31Rs7K3IKjYzBhMA8GA1UdEwEB/wQFMAMB\nAf8wHwYDVR0jBBgwFoAU/4Ixcj75xGZsrTie0bBRiKWQzPUwHQYDVR0OBBYEFP+C\nMXI++cRmbK04ntGwUYilkMz1MA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAwNp\nADBmAjEA5gVYaWHlLcoNy/EZCL3W/VGSGn5jVASQkZo1kTmZ+gepZpO6yGjUij/6\n7W4WAie3AjEA3VoXK3YdZUKWpqxdinlW2Iob35reX8dQj7FbcQwm32pAAOwzkSFx\nvmjkI6TZraE3\n-----END CERTIFICATE-----\n\n# Issuer: CN=Security Communication RootCA3 O=SECOM Trust Systems CO.,LTD.\n# Subject: CN=Security Communication RootCA3 O=SECOM Trust Systems CO.,LTD.\n# Label: \"Security Communication RootCA3\"\n# Serial: 16247922307909811815\n# MD5 Fingerprint: 1c:9a:16:ff:9e:5c:e0:4d:8a:14:01:f4:35:5d:29:26\n# SHA1 Fingerprint: c3:03:c8:22:74:92:e5:61:a2:9c:5f:79:91:2b:1e:44:13:91:30:3a\n# SHA256 Fingerprint: 24:a5:5c:2a:b0:51:44:2d:06:17:76:65:41:23:9a:4a:d0:32:d7:c5:51:75:aa:34:ff:de:2f:bc:4f:5c:52:94\n-----BEGIN CERTIFICATE-----\nMIIFfzCCA2egAwIBAgIJAOF8N0D9G/5nMA0GCSqGSIb3DQEBDAUAMF0xCzAJBgNV\nBAYTAkpQMSUwIwYDVQQKExxTRUNPTSBUcnVzdCBTeXN0ZW1zIENPLixMVEQuMScw\nJQYDVQQDEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTMwHhcNMTYwNjE2\nMDYxNzE2WhcNMzgwMTE4MDYxNzE2WjBdMQswCQYDVQQGEwJKUDElMCMGA1UEChMc\nU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UEAxMeU2VjdXJpdHkg\nQ29tbXVuaWNhdGlvbiBSb290Q0EzMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC\nCgKCAgEA48lySfcw3gl8qUCBWNO0Ot26YQ+TUG5pPDXC7ltzkBtnTCHsXzW7OT4r\nCmDvu20rhvtxosis5FaU+cmvsXLUIKx00rgVrVH+hXShuRD+BYD5UpOzQD11EKzA\nlrenfna84xtSGc4RHwsENPXY9Wk8d/Nk9A2qhd7gCVAEF5aEt8iKvE1y/By7z/MG\nTfmfZPd+pmaGNXHIEYBMwXFAWB6+oHP2/D5Q4eAvJj1+XCO1eXDe+uDRpdYMQXF7\n9+qMHIjH7Iv10S9VlkZ8WjtYO/u62C21Jdp6Ts9EriGmnpjKIG58u4iFW/vAEGK7\n8vknR+/RiTlDxN/e4UG/VHMgly1s2vPUB6PmudhvrvyMGS7TZ2crldtYXLVqAvO4\ng160a75BflcJdURQVc1aEWEhCmHCqYj9E7wtiS/NYeCVvsq1e+F7NGcLH7YMx3we\nGVPKp7FKFSBWFHA9K4IsD50VHUeAR/94mQ4xr28+j+2GaR57GIgUssL8gjMunEst\n+3A7caoreyYn8xrC3PsXuKHqy6C0rtOUfnrQq8PsOC0RLoi/1D+tEjtCrI8Cbn3M\n0V9hvqG8OmpI6iZVIhZdXw3/JzOfGAN0iltSIEdrRU0id4xVJ/CvHozJgyJUt5rQ\nT9nO/NkuHJYosQLTA70lUhw0Zk8jq/R3gpYd0VcwCBEF/VfR2ccCAwEAAaNCMEAw\nHQYDVR0OBBYEFGQUfPxYchamCik0FW8qy7z8r6irMA4GA1UdDwEB/wQEAwIBBjAP\nBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBDAUAA4ICAQDcAiMI4u8hOscNtybS\nYpOnpSNyByCCYN8Y11StaSWSntkUz5m5UoHPrmyKO1o5yGwBQ8IibQLwYs1OY0PA\nFNr0Y/Dq9HHuTofjcan0yVflLl8cebsjqodEV+m9NU1Bu0soo5iyG9kLFwfl9+qd\n9XbXv8S2gVj/yP9kaWJ5rW4OH3/uHWnlt3Jxs/6lATWUVCvAUm2PVcTJ0rjLyjQI\nUYWg9by0F1jqClx6vWPGOi//lkkZhOpn2ASxYfQAW0q3nHE3GYV5v4GwxxMOdnE+\nOoAGrgYWp421wsTL/0ClXI2lyTrtcoHKXJg80jQDdwj98ClZXSEIx2C/pHF7uNke\ngr4Jr2VvKKu/S7XuPghHJ6APbw+LP6yVGPO5DtxnVW5inkYO0QR4ynKudtml+LLf\niAlhi+8kTtFZP1rUPcmTPCtk9YENFpb3ksP+MW/oKjJ0DvRMmEoYDjBU1cXrvMUV\nnuiZIesnKwkK2/HmcBhWuwzkvvnoEKQTkrgc4NtnHVMDpCKn3F2SEDzq//wbEBrD\n2NCcnWXL0CsnMQMeNuE9dnUM/0Umud1RvCPHX9jYhxBAEg09ODfnRDwYwFMJZI//\n1ZqmfHAuc1Uh6N//g7kdPjIe1qZ9LPFm6Vwdp6POXiUyK+OVrCoHzrQoeIY8Laad\nTdJ0MN1kURXbg4NR16/9M51NZg==\n-----END CERTIFICATE-----\n\n# Issuer: CN=Security Communication ECC RootCA1 O=SECOM Trust Systems CO.,LTD.\n# Subject: CN=Security Communication ECC RootCA1 O=SECOM Trust Systems CO.,LTD.\n# Label: \"Security Communication ECC RootCA1\"\n# Serial: 15446673492073852651\n# MD5 Fingerprint: 7e:43:b0:92:68:ec:05:43:4c:98:ab:5d:35:2e:7e:86\n# SHA1 Fingerprint: b8:0e:26:a9:bf:d2:b2:3b:c0:ef:46:c9:ba:c7:bb:f6:1d:0d:41:41\n# SHA256 Fingerprint: e7:4f:bd:a5:5b:d5:64:c4:73:a3:6b:44:1a:a7:99:c8:a6:8e:07:74:40:e8:28:8b:9f:a1:e5:0e:4b:ba:ca:11\n-----BEGIN CERTIFICATE-----\nMIICODCCAb6gAwIBAgIJANZdm7N4gS7rMAoGCCqGSM49BAMDMGExCzAJBgNVBAYT\nAkpQMSUwIwYDVQQKExxTRUNPTSBUcnVzdCBTeXN0ZW1zIENPLixMVEQuMSswKQYD\nVQQDEyJTZWN1cml0eSBDb21tdW5pY2F0aW9uIEVDQyBSb290Q0ExMB4XDTE2MDYx\nNjA1MTUyOFoXDTM4MDExODA1MTUyOFowYTELMAkGA1UEBhMCSlAxJTAjBgNVBAoT\nHFNFQ09NIFRydXN0IFN5c3RlbXMgQ08uLExURC4xKzApBgNVBAMTIlNlY3VyaXR5\nIENvbW11bmljYXRpb24gRUNDIFJvb3RDQTEwdjAQBgcqhkjOPQIBBgUrgQQAIgNi\nAASkpW9gAwPDvTH00xecK4R1rOX9PVdu12O/5gSJko6BnOPpR27KkBLIE+Cnnfdl\ndB9sELLo5OnvbYUymUSxXv3MdhDYW72ixvnWQuRXdtyQwjWpS4g8EkdtXP9JTxpK\nULGjQjBAMB0GA1UdDgQWBBSGHOf+LaVKiwj+KBH6vqNm+GBZLzAOBgNVHQ8BAf8E\nBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zAKBggqhkjOPQQDAwNoADBlAjAVXUI9/Lbu\n9zuxNuie9sRGKEkz0FhDKmMpzE2xtHqiuQ04pV1IKv3LsnNdo4gIxwwCMQDAqy0O\nbe0YottT6SXbVQjgUMzfRGEWgqtJsLKB7HOHeLRMsmIbEvoWTSVLY70eN9k=\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/certifi/core.py",
    "content": "\"\"\"\ncertifi.py\n~~~~~~~~~~\n\nThis module returns the installation location of cacert.pem or its contents.\n\"\"\"\nimport sys\n\n\nif sys.version_info >= (3, 11):\n\n    from importlib.resources import as_file, files\n\n    _CACERT_CTX = None\n    _CACERT_PATH = None\n\n    def where() -> str:\n        # This is slightly terrible, but we want to delay extracting the file\n        # in cases where we're inside of a zipimport situation until someone\n        # actually calls where(), but we don't want to re-extract the file\n        # on every call of where(), so we'll do it once then store it in a\n        # global variable.\n        global _CACERT_CTX\n        global _CACERT_PATH\n        if _CACERT_PATH is None:\n            # This is slightly janky, the importlib.resources API wants you to\n            # manage the cleanup of this file, so it doesn't actually return a\n            # path, it returns a context manager that will give you the path\n            # when you enter it and will do any cleanup when you leave it. In\n            # the common case of not needing a temporary file, it will just\n            # return the file system location and the __exit__() is a no-op.\n            #\n            # We also have to hold onto the actual context manager, because\n            # it will do the cleanup whenever it gets garbage collected, so\n            # we will also store that at the global level as well.\n            _CACERT_CTX = as_file(files(\"pip._vendor.certifi\").joinpath(\"cacert.pem\"))\n            _CACERT_PATH = str(_CACERT_CTX.__enter__())\n\n        return _CACERT_PATH\n\n    def contents() -> str:\n        return files(\"pip._vendor.certifi\").joinpath(\"cacert.pem\").read_text(encoding=\"ascii\")\n\nelif sys.version_info >= (3, 7):\n\n    from importlib.resources import path as get_path, read_text\n\n    _CACERT_CTX = None\n    _CACERT_PATH = None\n\n    def where() -> str:\n        # This is slightly terrible, but we want to delay extracting the\n        # file in cases where we're inside of a zipimport situation until\n        # someone actually calls where(), but we don't want to re-extract\n        # the file on every call of where(), so we'll do it once then store\n        # it in a global variable.\n        global _CACERT_CTX\n        global _CACERT_PATH\n        if _CACERT_PATH is None:\n            # This is slightly janky, the importlib.resources API wants you\n            # to manage the cleanup of this file, so it doesn't actually\n            # return a path, it returns a context manager that will give\n            # you the path when you enter it and will do any cleanup when\n            # you leave it. In the common case of not needing a temporary\n            # file, it will just return the file system location and the\n            # __exit__() is a no-op.\n            #\n            # We also have to hold onto the actual context manager, because\n            # it will do the cleanup whenever it gets garbage collected, so\n            # we will also store that at the global level as well.\n            _CACERT_CTX = get_path(\"pip._vendor.certifi\", \"cacert.pem\")\n            _CACERT_PATH = str(_CACERT_CTX.__enter__())\n\n        return _CACERT_PATH\n\n    def contents() -> str:\n        return read_text(\"pip._vendor.certifi\", \"cacert.pem\", encoding=\"ascii\")\n\nelse:\n    import os\n    import types\n    from typing import Union\n\n    Package = Union[types.ModuleType, str]\n    Resource = Union[str, \"os.PathLike\"]\n\n    # This fallback will work for Python versions prior to 3.7 that lack the\n    # importlib.resources module but relies on the existing `where` function\n    # so won't address issues with environments like PyOxidizer that don't set\n    # __file__ on modules.\n    def read_text(\n        package: Package,\n        resource: Resource,\n        encoding: str = 'utf-8',\n        errors: str = 'strict'\n    ) -> str:\n        with open(where(), encoding=encoding) as data:\n            return data.read()\n\n    # If we don't have importlib.resources, then we will just do the old logic\n    # of assuming we're on the filesystem and munge the path directly.\n    def where() -> str:\n        f = os.path.dirname(__file__)\n\n        return os.path.join(f, \"cacert.pem\")\n\n    def contents() -> str:\n        return read_text(\"pip._vendor.certifi\", \"cacert.pem\", encoding=\"ascii\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/__init__.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .enums import InputState\nfrom .universaldetector import UniversalDetector\nfrom .version import VERSION, __version__\n\n__all__ = [\"UniversalDetector\", \"detect\", \"detect_all\", \"__version__\", \"VERSION\"]\n\n\ndef detect(byte_str):\n    \"\"\"\n    Detect the encoding of the given byte string.\n\n    :param byte_str:     The byte sequence to examine.\n    :type byte_str:      ``bytes`` or ``bytearray``\n    \"\"\"\n    if not isinstance(byte_str, bytearray):\n        if not isinstance(byte_str, bytes):\n            raise TypeError(\n                f\"Expected object of type bytes or bytearray, got: {type(byte_str)}\"\n            )\n        byte_str = bytearray(byte_str)\n    detector = UniversalDetector()\n    detector.feed(byte_str)\n    return detector.close()\n\n\ndef detect_all(byte_str, ignore_threshold=False):\n    \"\"\"\n    Detect all the possible encodings of the given byte string.\n\n    :param byte_str:          The byte sequence to examine.\n    :type byte_str:           ``bytes`` or ``bytearray``\n    :param ignore_threshold:  Include encodings that are below\n                              ``UniversalDetector.MINIMUM_THRESHOLD``\n                              in results.\n    :type ignore_threshold:   ``bool``\n    \"\"\"\n    if not isinstance(byte_str, bytearray):\n        if not isinstance(byte_str, bytes):\n            raise TypeError(\n                f\"Expected object of type bytes or bytearray, got: {type(byte_str)}\"\n            )\n        byte_str = bytearray(byte_str)\n\n    detector = UniversalDetector()\n    detector.feed(byte_str)\n    detector.close()\n\n    if detector.input_state == InputState.HIGH_BYTE:\n        results = []\n        probers = []\n        for prober in detector.charset_probers:\n            if hasattr(prober, \"probers\"):\n                probers.extend(p for p in prober.probers)\n            else:\n                probers.append(prober)\n        for prober in probers:\n            if ignore_threshold or prober.get_confidence() > detector.MINIMUM_THRESHOLD:\n                charset_name = prober.charset_name or \"\"\n                lower_charset_name = charset_name.lower()\n                # Use Windows encoding name instead of ISO-8859 if we saw any\n                # extra Windows-specific bytes\n                if lower_charset_name.startswith(\"iso-8859\") and detector.has_win_bytes:\n                    charset_name = detector.ISO_WIN_MAP.get(\n                        lower_charset_name, charset_name\n                    )\n                results.append(\n                    {\n                        \"encoding\": charset_name,\n                        \"confidence\": prober.get_confidence(),\n                        \"language\": prober.language,\n                    }\n                )\n        if len(results) > 0:\n            return sorted(results, key=lambda result: -result[\"confidence\"])\n\n    return [detector.result]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/big5freq.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Communicator client code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\n# Big5 frequency table\n# by Taiwan's Mandarin Promotion Council\n# <http://www.edu.tw:81/mandr/>\n#\n# 128  --> 0.42261\n# 256  --> 0.57851\n# 512  --> 0.74851\n# 1024 --> 0.89384\n# 2048 --> 0.97583\n#\n# Ideal Distribution Ratio = 0.74851/(1-0.74851) =2.98\n# Random Distribution Ration = 512/(5401-512)=0.105\n#\n# Typical Distribution Ratio about 25% of Ideal one, still much higher than RDR\n\nBIG5_TYPICAL_DISTRIBUTION_RATIO = 0.75\n\n# Char to FreqOrder table\nBIG5_TABLE_SIZE = 5376\n# fmt: off\nBIG5_CHAR_TO_FREQ_ORDER = (\n   1,1801,1506, 255,1431, 198,   9,  82,   6,5008, 177, 202,3681,1256,2821, 110, #   16\n3814,  33,3274, 261,  76,  44,2114,  16,2946,2187,1176, 659,3971,  26,3451,2653, #   32\n1198,3972,3350,4202, 410,2215, 302, 590, 361,1964,   8, 204,  58,4510,5009,1932, #   48\n  63,5010,5011, 317,1614,  75, 222, 159,4203,2417,1480,5012,3555,3091, 224,2822, #   64\n3682,   3,  10,3973,1471,  29,2787,1135,2866,1940, 873, 130,3275,1123, 312,5013, #   80\n4511,2052, 507, 252, 682,5014, 142,1915, 124, 206,2947,  34,3556,3204,  64, 604, #   96\n5015,2501,1977,1978, 155,1991, 645, 641,1606,5016,3452, 337,  72, 406,5017,  80, #  112\n 630, 238,3205,1509, 263, 939,1092,2654, 756,1440,1094,3453, 449,  69,2987, 591, #  128\n 179,2096, 471, 115,2035,1844,  60,  50,2988, 134, 806,1869, 734,2036,3454, 180, #  144\n 995,1607, 156, 537,2907, 688,5018, 319,1305, 779,2145, 514,2379, 298,4512, 359, #  160\n2502,  90,2716,1338, 663,  11, 906,1099,2553,  20,2441, 182, 532,1716,5019, 732, #  176\n1376,4204,1311,1420,3206,  25,2317,1056, 113, 399, 382,1950, 242,3455,2474, 529, #  192\n3276, 475,1447,3683,5020, 117,  21, 656, 810,1297,2300,2334,3557,5021, 126,4205, #  208\n 706, 456, 150, 613,4513,  71,1118,2037,4206, 145,3092,  85, 835, 486,2115,1246, #  224\n1426, 428, 727,1285,1015, 800, 106, 623, 303,1281,5022,2128,2359, 347,3815, 221, #  240\n3558,3135,5023,1956,1153,4207,  83, 296,1199,3093, 192, 624,  93,5024, 822,1898, #  256\n2823,3136, 795,2065, 991,1554,1542,1592,  27,  43,2867, 859, 139,1456, 860,4514, #  272\n 437, 712,3974, 164,2397,3137, 695, 211,3037,2097, 195,3975,1608,3559,3560,3684, #  288\n3976, 234, 811,2989,2098,3977,2233,1441,3561,1615,2380, 668,2077,1638, 305, 228, #  304\n1664,4515, 467, 415,5025, 262,2099,1593, 239, 108, 300, 200,1033, 512,1247,2078, #  320\n5026,5027,2176,3207,3685,2682, 593, 845,1062,3277,  88,1723,2038,3978,1951, 212, #  336\n 266, 152, 149, 468,1899,4208,4516,  77, 187,5028,3038,  37,   5,2990,5029,3979, #  352\n5030,5031,  39,2524,4517,2908,3208,2079,  55, 148,  74,4518, 545, 483,1474,1029, #  368\n1665, 217,1870,1531,3138,1104,2655,4209,  24, 172,3562, 900,3980,3563,3564,4519, #  384\n  32,1408,2824,1312, 329, 487,2360,2251,2717, 784,2683,   4,3039,3351,1427,1789, #  400\n 188, 109, 499,5032,3686,1717,1790, 888,1217,3040,4520,5033,3565,5034,3352,1520, #  416\n3687,3981, 196,1034, 775,5035,5036, 929,1816, 249, 439,  38,5037,1063,5038, 794, #  432\n3982,1435,2301,  46, 178,3278,2066,5039,2381,5040, 214,1709,4521, 804,  35, 707, #  448\n 324,3688,1601,2554, 140, 459,4210,5041,5042,1365, 839, 272, 978,2262,2580,3456, #  464\n2129,1363,3689,1423, 697, 100,3094,  48,  70,1231, 495,3139,2196,5043,1294,5044, #  480\n2080, 462, 586,1042,3279, 853, 256, 988, 185,2382,3457,1698, 434,1084,5045,3458, #  496\n 314,2625,2788,4522,2335,2336, 569,2285, 637,1817,2525, 757,1162,1879,1616,3459, #  512\n 287,1577,2116, 768,4523,1671,2868,3566,2526,1321,3816, 909,2418,5046,4211, 933, #  528\n3817,4212,2053,2361,1222,4524, 765,2419,1322, 786,4525,5047,1920,1462,1677,2909, #  544\n1699,5048,4526,1424,2442,3140,3690,2600,3353,1775,1941,3460,3983,4213, 309,1369, #  560\n1130,2825, 364,2234,1653,1299,3984,3567,3985,3986,2656, 525,1085,3041, 902,2001, #  576\n1475, 964,4527, 421,1845,1415,1057,2286, 940,1364,3141, 376,4528,4529,1381,   7, #  592\n2527, 983,2383, 336,1710,2684,1846, 321,3461, 559,1131,3042,2752,1809,1132,1313, #  608\n 265,1481,1858,5049, 352,1203,2826,3280, 167,1089, 420,2827, 776, 792,1724,3568, #  624\n4214,2443,3281,5050,4215,5051, 446, 229, 333,2753, 901,3818,1200,1557,4530,2657, #  640\n1921, 395,2754,2685,3819,4216,1836, 125, 916,3209,2626,4531,5052,5053,3820,5054, #  656\n5055,5056,4532,3142,3691,1133,2555,1757,3462,1510,2318,1409,3569,5057,2146, 438, #  672\n2601,2910,2384,3354,1068, 958,3043, 461, 311,2869,2686,4217,1916,3210,4218,1979, #  688\n 383, 750,2755,2627,4219, 274, 539, 385,1278,1442,5058,1154,1965, 384, 561, 210, #  704\n  98,1295,2556,3570,5059,1711,2420,1482,3463,3987,2911,1257, 129,5060,3821, 642, #  720\n 523,2789,2790,2658,5061, 141,2235,1333,  68, 176, 441, 876, 907,4220, 603,2602, #  736\n 710, 171,3464, 404, 549,  18,3143,2398,1410,3692,1666,5062,3571,4533,2912,4534, #  752\n5063,2991, 368,5064, 146, 366,  99, 871,3693,1543, 748, 807,1586,1185,  22,2263, #  768\n 379,3822,3211,5065,3212, 505,1942,2628,1992,1382,2319,5066, 380,2362, 218, 702, #  784\n1818,1248,3465,3044,3572,3355,3282,5067,2992,3694, 930,3283,3823,5068,  59,5069, #  800\n 585, 601,4221, 497,3466,1112,1314,4535,1802,5070,1223,1472,2177,5071, 749,1837, #  816\n 690,1900,3824,1773,3988,1476, 429,1043,1791,2236,2117, 917,4222, 447,1086,1629, #  832\n5072, 556,5073,5074,2021,1654, 844,1090, 105, 550, 966,1758,2828,1008,1783, 686, #  848\n1095,5075,2287, 793,1602,5076,3573,2603,4536,4223,2948,2302,4537,3825, 980,2503, #  864\n 544, 353, 527,4538, 908,2687,2913,5077, 381,2629,1943,1348,5078,1341,1252, 560, #  880\n3095,5079,3467,2870,5080,2054, 973, 886,2081, 143,4539,5081,5082, 157,3989, 496, #  896\n4224,  57, 840, 540,2039,4540,4541,3468,2118,1445, 970,2264,1748,1966,2082,4225, #  912\n3144,1234,1776,3284,2829,3695, 773,1206,2130,1066,2040,1326,3990,1738,1725,4226, #  928\n 279,3145,  51,1544,2604, 423,1578,2131,2067, 173,4542,1880,5083,5084,1583, 264, #  944\n 610,3696,4543,2444, 280, 154,5085,5086,5087,1739, 338,1282,3096, 693,2871,1411, #  960\n1074,3826,2445,5088,4544,5089,5090,1240, 952,2399,5091,2914,1538,2688, 685,1483, #  976\n4227,2475,1436, 953,4228,2055,4545, 671,2400,  79,4229,2446,3285, 608, 567,2689, #  992\n3469,4230,4231,1691, 393,1261,1792,2401,5092,4546,5093,5094,5095,5096,1383,1672, # 1008\n3827,3213,1464, 522,1119, 661,1150, 216, 675,4547,3991,1432,3574, 609,4548,2690, # 1024\n2402,5097,5098,5099,4232,3045,   0,5100,2476, 315, 231,2447, 301,3356,4549,2385, # 1040\n5101, 233,4233,3697,1819,4550,4551,5102,  96,1777,1315,2083,5103, 257,5104,1810, # 1056\n3698,2718,1139,1820,4234,2022,1124,2164,2791,1778,2659,5105,3097, 363,1655,3214, # 1072\n5106,2993,5107,5108,5109,3992,1567,3993, 718, 103,3215, 849,1443, 341,3357,2949, # 1088\n1484,5110,1712, 127,  67, 339,4235,2403, 679,1412, 821,5111,5112, 834, 738, 351, # 1104\n2994,2147, 846, 235,1497,1881, 418,1993,3828,2719, 186,1100,2148,2756,3575,1545, # 1120\n1355,2950,2872,1377, 583,3994,4236,2581,2995,5113,1298,3699,1078,2557,3700,2363, # 1136\n  78,3829,3830, 267,1289,2100,2002,1594,4237, 348, 369,1274,2197,2178,1838,4552, # 1152\n1821,2830,3701,2757,2288,2003,4553,2951,2758, 144,3358, 882,4554,3995,2759,3470, # 1168\n4555,2915,5114,4238,1726, 320,5115,3996,3046, 788,2996,5116,2831,1774,1327,2873, # 1184\n3997,2832,5117,1306,4556,2004,1700,3831,3576,2364,2660, 787,2023, 506, 824,3702, # 1200\n 534, 323,4557,1044,3359,2024,1901, 946,3471,5118,1779,1500,1678,5119,1882,4558, # 1216\n 165, 243,4559,3703,2528, 123, 683,4239, 764,4560,  36,3998,1793, 589,2916, 816, # 1232\n 626,1667,3047,2237,1639,1555,1622,3832,3999,5120,4000,2874,1370,1228,1933, 891, # 1248\n2084,2917, 304,4240,5121, 292,2997,2720,3577, 691,2101,4241,1115,4561, 118, 662, # 1264\n5122, 611,1156, 854,2386,1316,2875,   2, 386, 515,2918,5123,5124,3286, 868,2238, # 1280\n1486, 855,2661, 785,2216,3048,5125,1040,3216,3578,5126,3146, 448,5127,1525,5128, # 1296\n2165,4562,5129,3833,5130,4242,2833,3579,3147, 503, 818,4001,3148,1568, 814, 676, # 1312\n1444, 306,1749,5131,3834,1416,1030, 197,1428, 805,2834,1501,4563,5132,5133,5134, # 1328\n1994,5135,4564,5136,5137,2198,  13,2792,3704,2998,3149,1229,1917,5138,3835,2132, # 1344\n5139,4243,4565,2404,3580,5140,2217,1511,1727,1120,5141,5142, 646,3836,2448, 307, # 1360\n5143,5144,1595,3217,5145,5146,5147,3705,1113,1356,4002,1465,2529,2530,5148, 519, # 1376\n5149, 128,2133,  92,2289,1980,5150,4003,1512, 342,3150,2199,5151,2793,2218,1981, # 1392\n3360,4244, 290,1656,1317, 789, 827,2365,5152,3837,4566, 562, 581,4004,5153, 401, # 1408\n4567,2252,  94,4568,5154,1399,2794,5155,1463,2025,4569,3218,1944,5156, 828,1105, # 1424\n4245,1262,1394,5157,4246, 605,4570,5158,1784,2876,5159,2835, 819,2102, 578,2200, # 1440\n2952,5160,1502, 436,3287,4247,3288,2836,4005,2919,3472,3473,5161,2721,2320,5162, # 1456\n5163,2337,2068,  23,4571, 193, 826,3838,2103, 699,1630,4248,3098, 390,1794,1064, # 1472\n3581,5164,1579,3099,3100,1400,5165,4249,1839,1640,2877,5166,4572,4573, 137,4250, # 1488\n 598,3101,1967, 780, 104, 974,2953,5167, 278, 899, 253, 402, 572, 504, 493,1339, # 1504\n5168,4006,1275,4574,2582,2558,5169,3706,3049,3102,2253, 565,1334,2722, 863,  41, # 1520\n5170,5171,4575,5172,1657,2338,  19, 463,2760,4251, 606,5173,2999,3289,1087,2085, # 1536\n1323,2662,3000,5174,1631,1623,1750,4252,2691,5175,2878, 791,2723,2663,2339, 232, # 1552\n2421,5176,3001,1498,5177,2664,2630, 755,1366,3707,3290,3151,2026,1609, 119,1918, # 1568\n3474, 862,1026,4253,5178,4007,3839,4576,4008,4577,2265,1952,2477,5179,1125, 817, # 1584\n4254,4255,4009,1513,1766,2041,1487,4256,3050,3291,2837,3840,3152,5180,5181,1507, # 1600\n5182,2692, 733,  40,1632,1106,2879, 345,4257, 841,2531, 230,4578,3002,1847,3292, # 1616\n3475,5183,1263, 986,3476,5184, 735, 879, 254,1137, 857, 622,1300,1180,1388,1562, # 1632\n4010,4011,2954, 967,2761,2665,1349, 592,2134,1692,3361,3003,1995,4258,1679,4012, # 1648\n1902,2188,5185, 739,3708,2724,1296,1290,5186,4259,2201,2202,1922,1563,2605,2559, # 1664\n1871,2762,3004,5187, 435,5188, 343,1108, 596,  17,1751,4579,2239,3477,3709,5189, # 1680\n4580, 294,3582,2955,1693, 477, 979, 281,2042,3583, 643,2043,3710,2631,2795,2266, # 1696\n1031,2340,2135,2303,3584,4581, 367,1249,2560,5190,3585,5191,4582,1283,3362,2005, # 1712\n 240,1762,3363,4583,4584, 836,1069,3153, 474,5192,2149,2532, 268,3586,5193,3219, # 1728\n1521,1284,5194,1658,1546,4260,5195,3587,3588,5196,4261,3364,2693,1685,4262, 961, # 1744\n1673,2632, 190,2006,2203,3841,4585,4586,5197, 570,2504,3711,1490,5198,4587,2633, # 1760\n3293,1957,4588, 584,1514, 396,1045,1945,5199,4589,1968,2449,5200,5201,4590,4013, # 1776\n 619,5202,3154,3294, 215,2007,2796,2561,3220,4591,3221,4592, 763,4263,3842,4593, # 1792\n5203,5204,1958,1767,2956,3365,3712,1174, 452,1477,4594,3366,3155,5205,2838,1253, # 1808\n2387,2189,1091,2290,4264, 492,5206, 638,1169,1825,2136,1752,4014, 648, 926,1021, # 1824\n1324,4595, 520,4596, 997, 847,1007, 892,4597,3843,2267,1872,3713,2405,1785,4598, # 1840\n1953,2957,3103,3222,1728,4265,2044,3714,4599,2008,1701,3156,1551,  30,2268,4266, # 1856\n5207,2027,4600,3589,5208, 501,5209,4267, 594,3478,2166,1822,3590,3479,3591,3223, # 1872\n 829,2839,4268,5210,1680,3157,1225,4269,5211,3295,4601,4270,3158,2341,5212,4602, # 1888\n4271,5213,4015,4016,5214,1848,2388,2606,3367,5215,4603, 374,4017, 652,4272,4273, # 1904\n 375,1140, 798,5216,5217,5218,2366,4604,2269, 546,1659, 138,3051,2450,4605,5219, # 1920\n2254, 612,1849, 910, 796,3844,1740,1371, 825,3845,3846,5220,2920,2562,5221, 692, # 1936\n 444,3052,2634, 801,4606,4274,5222,1491, 244,1053,3053,4275,4276, 340,5223,4018, # 1952\n1041,3005, 293,1168,  87,1357,5224,1539, 959,5225,2240, 721, 694,4277,3847, 219, # 1968\n1478, 644,1417,3368,2666,1413,1401,1335,1389,4019,5226,5227,3006,2367,3159,1826, # 1984\n 730,1515, 184,2840,  66,4607,5228,1660,2958, 246,3369, 378,1457, 226,3480, 975, # 2000\n4020,2959,1264,3592, 674, 696,5229, 163,5230,1141,2422,2167, 713,3593,3370,4608, # 2016\n4021,5231,5232,1186,  15,5233,1079,1070,5234,1522,3224,3594, 276,1050,2725, 758, # 2032\n1126, 653,2960,3296,5235,2342, 889,3595,4022,3104,3007, 903,1250,4609,4023,3481, # 2048\n3596,1342,1681,1718, 766,3297, 286,  89,2961,3715,5236,1713,5237,2607,3371,3008, # 2064\n5238,2962,2219,3225,2880,5239,4610,2505,2533, 181, 387,1075,4024, 731,2190,3372, # 2080\n5240,3298, 310, 313,3482,2304, 770,4278,  54,3054, 189,4611,3105,3848,4025,5241, # 2096\n1230,1617,1850, 355,3597,4279,4612,3373, 111,4280,3716,1350,3160,3483,3055,4281, # 2112\n2150,3299,3598,5242,2797,4026,4027,3009, 722,2009,5243,1071, 247,1207,2343,2478, # 2128\n1378,4613,2010, 864,1437,1214,4614, 373,3849,1142,2220, 667,4615, 442,2763,2563, # 2144\n3850,4028,1969,4282,3300,1840, 837, 170,1107, 934,1336,1883,5244,5245,2119,4283, # 2160\n2841, 743,1569,5246,4616,4284, 582,2389,1418,3484,5247,1803,5248, 357,1395,1729, # 2176\n3717,3301,2423,1564,2241,5249,3106,3851,1633,4617,1114,2086,4285,1532,5250, 482, # 2192\n2451,4618,5251,5252,1492, 833,1466,5253,2726,3599,1641,2842,5254,1526,1272,3718, # 2208\n4286,1686,1795, 416,2564,1903,1954,1804,5255,3852,2798,3853,1159,2321,5256,2881, # 2224\n4619,1610,1584,3056,2424,2764, 443,3302,1163,3161,5257,5258,4029,5259,4287,2506, # 2240\n3057,4620,4030,3162,2104,1647,3600,2011,1873,4288,5260,4289, 431,3485,5261, 250, # 2256\n  97,  81,4290,5262,1648,1851,1558, 160, 848,5263, 866, 740,1694,5264,2204,2843, # 2272\n3226,4291,4621,3719,1687, 950,2479, 426, 469,3227,3720,3721,4031,5265,5266,1188, # 2288\n 424,1996, 861,3601,4292,3854,2205,2694, 168,1235,3602,4293,5267,2087,1674,4622, # 2304\n3374,3303, 220,2565,1009,5268,3855, 670,3010, 332,1208, 717,5269,5270,3603,2452, # 2320\n4032,3375,5271, 513,5272,1209,2882,3376,3163,4623,1080,5273,5274,5275,5276,2534, # 2336\n3722,3604, 815,1587,4033,4034,5277,3605,3486,3856,1254,4624,1328,3058,1390,4035, # 2352\n1741,4036,3857,4037,5278, 236,3858,2453,3304,5279,5280,3723,3859,1273,3860,4625, # 2368\n5281, 308,5282,4626, 245,4627,1852,2480,1307,2583, 430, 715,2137,2454,5283, 270, # 2384\n 199,2883,4038,5284,3606,2727,1753, 761,1754, 725,1661,1841,4628,3487,3724,5285, # 2400\n5286, 587,  14,3305, 227,2608, 326, 480,2270, 943,2765,3607, 291, 650,1884,5287, # 2416\n1702,1226, 102,1547,  62,3488, 904,4629,3489,1164,4294,5288,5289,1224,1548,2766, # 2432\n 391, 498,1493,5290,1386,1419,5291,2056,1177,4630, 813, 880,1081,2368, 566,1145, # 2448\n4631,2291,1001,1035,2566,2609,2242, 394,1286,5292,5293,2069,5294,  86,1494,1730, # 2464\n4039, 491,1588, 745, 897,2963, 843,3377,4040,2767,2884,3306,1768, 998,2221,2070, # 2480\n 397,1827,1195,1970,3725,3011,3378, 284,5295,3861,2507,2138,2120,1904,5296,4041, # 2496\n2151,4042,4295,1036,3490,1905, 114,2567,4296, 209,1527,5297,5298,2964,2844,2635, # 2512\n2390,2728,3164, 812,2568,5299,3307,5300,1559, 737,1885,3726,1210, 885,  28,2695, # 2528\n3608,3862,5301,4297,1004,1780,4632,5302, 346,1982,2222,2696,4633,3863,1742, 797, # 2544\n1642,4043,1934,1072,1384,2152, 896,4044,3308,3727,3228,2885,3609,5303,2569,1959, # 2560\n4634,2455,1786,5304,5305,5306,4045,4298,1005,1308,3728,4299,2729,4635,4636,1528, # 2576\n2610, 161,1178,4300,1983, 987,4637,1101,4301, 631,4046,1157,3229,2425,1343,1241, # 2592\n1016,2243,2570, 372, 877,2344,2508,1160, 555,1935, 911,4047,5307, 466,1170, 169, # 2608\n1051,2921,2697,3729,2481,3012,1182,2012,2571,1251,2636,5308, 992,2345,3491,1540, # 2624\n2730,1201,2071,2406,1997,2482,5309,4638, 528,1923,2191,1503,1874,1570,2369,3379, # 2640\n3309,5310, 557,1073,5311,1828,3492,2088,2271,3165,3059,3107, 767,3108,2799,4639, # 2656\n1006,4302,4640,2346,1267,2179,3730,3230, 778,4048,3231,2731,1597,2667,5312,4641, # 2672\n5313,3493,5314,5315,5316,3310,2698,1433,3311, 131,  95,1504,4049, 723,4303,3166, # 2688\n1842,3610,2768,2192,4050,2028,2105,3731,5317,3013,4051,1218,5318,3380,3232,4052, # 2704\n4304,2584, 248,1634,3864, 912,5319,2845,3732,3060,3865, 654,  53,5320,3014,5321, # 2720\n1688,4642, 777,3494,1032,4053,1425,5322, 191, 820,2121,2846, 971,4643, 931,3233, # 2736\n 135, 664, 783,3866,1998, 772,2922,1936,4054,3867,4644,2923,3234, 282,2732, 640, # 2752\n1372,3495,1127, 922, 325,3381,5323,5324, 711,2045,5325,5326,4055,2223,2800,1937, # 2768\n4056,3382,2224,2255,3868,2305,5327,4645,3869,1258,3312,4057,3235,2139,2965,4058, # 2784\n4059,5328,2225, 258,3236,4646, 101,1227,5329,3313,1755,5330,1391,3314,5331,2924, # 2800\n2057, 893,5332,5333,5334,1402,4305,2347,5335,5336,3237,3611,5337,5338, 878,1325, # 2816\n1781,2801,4647, 259,1385,2585, 744,1183,2272,4648,5339,4060,2509,5340, 684,1024, # 2832\n4306,5341, 472,3612,3496,1165,3315,4061,4062, 322,2153, 881, 455,1695,1152,1340, # 2848\n 660, 554,2154,4649,1058,4650,4307, 830,1065,3383,4063,4651,1924,5342,1703,1919, # 2864\n5343, 932,2273, 122,5344,4652, 947, 677,5345,3870,2637, 297,1906,1925,2274,4653, # 2880\n2322,3316,5346,5347,4308,5348,4309,  84,4310, 112, 989,5349, 547,1059,4064, 701, # 2896\n3613,1019,5350,4311,5351,3497, 942, 639, 457,2306,2456, 993,2966, 407, 851, 494, # 2912\n4654,3384, 927,5352,1237,5353,2426,3385, 573,4312, 680, 921,2925,1279,1875, 285, # 2928\n 790,1448,1984, 719,2168,5354,5355,4655,4065,4066,1649,5356,1541, 563,5357,1077, # 2944\n5358,3386,3061,3498, 511,3015,4067,4068,3733,4069,1268,2572,3387,3238,4656,4657, # 2960\n5359, 535,1048,1276,1189,2926,2029,3167,1438,1373,2847,2967,1134,2013,5360,4313, # 2976\n1238,2586,3109,1259,5361, 700,5362,2968,3168,3734,4314,5363,4315,1146,1876,1907, # 2992\n4658,2611,4070, 781,2427, 132,1589, 203, 147, 273,2802,2407, 898,1787,2155,4071, # 3008\n4072,5364,3871,2803,5365,5366,4659,4660,5367,3239,5368,1635,3872, 965,5369,1805, # 3024\n2699,1516,3614,1121,1082,1329,3317,4073,1449,3873,  65,1128,2848,2927,2769,1590, # 3040\n3874,5370,5371,  12,2668,  45, 976,2587,3169,4661, 517,2535,1013,1037,3240,5372, # 3056\n3875,2849,5373,3876,5374,3499,5375,2612, 614,1999,2323,3877,3110,2733,2638,5376, # 3072\n2588,4316, 599,1269,5377,1811,3735,5378,2700,3111, 759,1060, 489,1806,3388,3318, # 3088\n1358,5379,5380,2391,1387,1215,2639,2256, 490,5381,5382,4317,1759,2392,2348,5383, # 3104\n4662,3878,1908,4074,2640,1807,3241,4663,3500,3319,2770,2349, 874,5384,5385,3501, # 3120\n3736,1859,  91,2928,3737,3062,3879,4664,5386,3170,4075,2669,5387,3502,1202,1403, # 3136\n3880,2969,2536,1517,2510,4665,3503,2511,5388,4666,5389,2701,1886,1495,1731,4076, # 3152\n2370,4667,5390,2030,5391,5392,4077,2702,1216, 237,2589,4318,2324,4078,3881,4668, # 3168\n4669,2703,3615,3504, 445,4670,5393,5394,5395,5396,2771,  61,4079,3738,1823,4080, # 3184\n5397, 687,2046, 935, 925, 405,2670, 703,1096,1860,2734,4671,4081,1877,1367,2704, # 3200\n3389, 918,2106,1782,2483, 334,3320,1611,1093,4672, 564,3171,3505,3739,3390, 945, # 3216\n2641,2058,4673,5398,1926, 872,4319,5399,3506,2705,3112, 349,4320,3740,4082,4674, # 3232\n3882,4321,3741,2156,4083,4675,4676,4322,4677,2408,2047, 782,4084, 400, 251,4323, # 3248\n1624,5400,5401, 277,3742, 299,1265, 476,1191,3883,2122,4324,4325,1109, 205,5402, # 3264\n2590,1000,2157,3616,1861,5403,5404,5405,4678,5406,4679,2573, 107,2484,2158,4085, # 3280\n3507,3172,5407,1533, 541,1301, 158, 753,4326,2886,3617,5408,1696, 370,1088,4327, # 3296\n4680,3618, 579, 327, 440, 162,2244, 269,1938,1374,3508, 968,3063,  56,1396,3113, # 3312\n2107,3321,3391,5409,1927,2159,4681,3016,5410,3619,5411,5412,3743,4682,2485,5413, # 3328\n2804,5414,1650,4683,5415,2613,5416,5417,4086,2671,3392,1149,3393,4087,3884,4088, # 3344\n5418,1076,  49,5419, 951,3242,3322,3323, 450,2850, 920,5420,1812,2805,2371,4328, # 3360\n1909,1138,2372,3885,3509,5421,3243,4684,1910,1147,1518,2428,4685,3886,5422,4686, # 3376\n2393,2614, 260,1796,3244,5423,5424,3887,3324, 708,5425,3620,1704,5426,3621,1351, # 3392\n1618,3394,3017,1887, 944,4329,3395,4330,3064,3396,4331,5427,3744, 422, 413,1714, # 3408\n3325, 500,2059,2350,4332,2486,5428,1344,1911, 954,5429,1668,5430,5431,4089,2409, # 3424\n4333,3622,3888,4334,5432,2307,1318,2512,3114, 133,3115,2887,4687, 629,  31,2851, # 3440\n2706,3889,4688, 850, 949,4689,4090,2970,1732,2089,4335,1496,1853,5433,4091, 620, # 3456\n3245, 981,1242,3745,3397,1619,3746,1643,3326,2140,2457,1971,1719,3510,2169,5434, # 3472\n3246,5435,5436,3398,1829,5437,1277,4690,1565,2048,5438,1636,3623,3116,5439, 869, # 3488\n2852, 655,3890,3891,3117,4092,3018,3892,1310,3624,4691,5440,5441,5442,1733, 558, # 3504\n4692,3747, 335,1549,3065,1756,4336,3748,1946,3511,1830,1291,1192, 470,2735,2108, # 3520\n2806, 913,1054,4093,5443,1027,5444,3066,4094,4693, 982,2672,3399,3173,3512,3247, # 3536\n3248,1947,2807,5445, 571,4694,5446,1831,5447,3625,2591,1523,2429,5448,2090, 984, # 3552\n4695,3749,1960,5449,3750, 852, 923,2808,3513,3751, 969,1519, 999,2049,2325,1705, # 3568\n5450,3118, 615,1662, 151, 597,4095,2410,2326,1049, 275,4696,3752,4337, 568,3753, # 3584\n3626,2487,4338,3754,5451,2430,2275, 409,3249,5452,1566,2888,3514,1002, 769,2853, # 3600\n 194,2091,3174,3755,2226,3327,4339, 628,1505,5453,5454,1763,2180,3019,4096, 521, # 3616\n1161,2592,1788,2206,2411,4697,4097,1625,4340,4341, 412,  42,3119, 464,5455,2642, # 3632\n4698,3400,1760,1571,2889,3515,2537,1219,2207,3893,2643,2141,2373,4699,4700,3328, # 3648\n1651,3401,3627,5456,5457,3628,2488,3516,5458,3756,5459,5460,2276,2092, 460,5461, # 3664\n4701,5462,3020, 962, 588,3629, 289,3250,2644,1116,  52,5463,3067,1797,5464,5465, # 3680\n5466,1467,5467,1598,1143,3757,4342,1985,1734,1067,4702,1280,3402, 465,4703,1572, # 3696\n 510,5468,1928,2245,1813,1644,3630,5469,4704,3758,5470,5471,2673,1573,1534,5472, # 3712\n5473, 536,1808,1761,3517,3894,3175,2645,5474,5475,5476,4705,3518,2929,1912,2809, # 3728\n5477,3329,1122, 377,3251,5478, 360,5479,5480,4343,1529, 551,5481,2060,3759,1769, # 3744\n2431,5482,2930,4344,3330,3120,2327,2109,2031,4706,1404, 136,1468,1479, 672,1171, # 3760\n3252,2308, 271,3176,5483,2772,5484,2050, 678,2736, 865,1948,4707,5485,2014,4098, # 3776\n2971,5486,2737,2227,1397,3068,3760,4708,4709,1735,2931,3403,3631,5487,3895, 509, # 3792\n2854,2458,2890,3896,5488,5489,3177,3178,4710,4345,2538,4711,2309,1166,1010, 552, # 3808\n 681,1888,5490,5491,2972,2973,4099,1287,1596,1862,3179, 358, 453, 736, 175, 478, # 3824\n1117, 905,1167,1097,5492,1854,1530,5493,1706,5494,2181,3519,2292,3761,3520,3632, # 3840\n4346,2093,4347,5495,3404,1193,2489,4348,1458,2193,2208,1863,1889,1421,3331,2932, # 3856\n3069,2182,3521, 595,2123,5496,4100,5497,5498,4349,1707,2646, 223,3762,1359, 751, # 3872\n3121, 183,3522,5499,2810,3021, 419,2374, 633, 704,3897,2394, 241,5500,5501,5502, # 3888\n 838,3022,3763,2277,2773,2459,3898,1939,2051,4101,1309,3122,2246,1181,5503,1136, # 3904\n2209,3899,2375,1446,4350,2310,4712,5504,5505,4351,1055,2615, 484,3764,5506,4102, # 3920\n 625,4352,2278,3405,1499,4353,4103,5507,4104,4354,3253,2279,2280,3523,5508,5509, # 3936\n2774, 808,2616,3765,3406,4105,4355,3123,2539, 526,3407,3900,4356, 955,5510,1620, # 3952\n4357,2647,2432,5511,1429,3766,1669,1832, 994, 928,5512,3633,1260,5513,5514,5515, # 3968\n1949,2293, 741,2933,1626,4358,2738,2460, 867,1184, 362,3408,1392,5516,5517,4106, # 3984\n4359,1770,1736,3254,2934,4713,4714,1929,2707,1459,1158,5518,3070,3409,2891,1292, # 4000\n1930,2513,2855,3767,1986,1187,2072,2015,2617,4360,5519,2574,2514,2170,3768,2490, # 4016\n3332,5520,3769,4715,5521,5522, 666,1003,3023,1022,3634,4361,5523,4716,1814,2257, # 4032\n 574,3901,1603, 295,1535, 705,3902,4362, 283, 858, 417,5524,5525,3255,4717,4718, # 4048\n3071,1220,1890,1046,2281,2461,4107,1393,1599, 689,2575, 388,4363,5526,2491, 802, # 4064\n5527,2811,3903,2061,1405,2258,5528,4719,3904,2110,1052,1345,3256,1585,5529, 809, # 4080\n5530,5531,5532, 575,2739,3524, 956,1552,1469,1144,2328,5533,2329,1560,2462,3635, # 4096\n3257,4108, 616,2210,4364,3180,2183,2294,5534,1833,5535,3525,4720,5536,1319,3770, # 4112\n3771,1211,3636,1023,3258,1293,2812,5537,5538,5539,3905, 607,2311,3906, 762,2892, # 4128\n1439,4365,1360,4721,1485,3072,5540,4722,1038,4366,1450,2062,2648,4367,1379,4723, # 4144\n2593,5541,5542,4368,1352,1414,2330,2935,1172,5543,5544,3907,3908,4724,1798,1451, # 4160\n5545,5546,5547,5548,2936,4109,4110,2492,2351, 411,4111,4112,3637,3333,3124,4725, # 4176\n1561,2674,1452,4113,1375,5549,5550,  47,2974, 316,5551,1406,1591,2937,3181,5552, # 4192\n1025,2142,3125,3182, 354,2740, 884,2228,4369,2412, 508,3772, 726,3638, 996,2433, # 4208\n3639, 729,5553, 392,2194,1453,4114,4726,3773,5554,5555,2463,3640,2618,1675,2813, # 4224\n 919,2352,2975,2353,1270,4727,4115,  73,5556,5557, 647,5558,3259,2856,2259,1550, # 4240\n1346,3024,5559,1332, 883,3526,5560,5561,5562,5563,3334,2775,5564,1212, 831,1347, # 4256\n4370,4728,2331,3909,1864,3073, 720,3910,4729,4730,3911,5565,4371,5566,5567,4731, # 4272\n5568,5569,1799,4732,3774,2619,4733,3641,1645,2376,4734,5570,2938, 669,2211,2675, # 4288\n2434,5571,2893,5572,5573,1028,3260,5574,4372,2413,5575,2260,1353,5576,5577,4735, # 4304\n3183, 518,5578,4116,5579,4373,1961,5580,2143,4374,5581,5582,3025,2354,2355,3912, # 4320\n 516,1834,1454,4117,2708,4375,4736,2229,2620,1972,1129,3642,5583,2776,5584,2976, # 4336\n1422, 577,1470,3026,1524,3410,5585,5586, 432,4376,3074,3527,5587,2594,1455,2515, # 4352\n2230,1973,1175,5588,1020,2741,4118,3528,4737,5589,2742,5590,1743,1361,3075,3529, # 4368\n2649,4119,4377,4738,2295, 895, 924,4378,2171, 331,2247,3076, 166,1627,3077,1098, # 4384\n5591,1232,2894,2231,3411,4739, 657, 403,1196,2377, 542,3775,3412,1600,4379,3530, # 4400\n5592,4740,2777,3261, 576, 530,1362,4741,4742,2540,2676,3776,4120,5593, 842,3913, # 4416\n5594,2814,2032,1014,4121, 213,2709,3413, 665, 621,4380,5595,3777,2939,2435,5596, # 4432\n2436,3335,3643,3414,4743,4381,2541,4382,4744,3644,1682,4383,3531,1380,5597, 724, # 4448\n2282, 600,1670,5598,1337,1233,4745,3126,2248,5599,1621,4746,5600, 651,4384,5601, # 4464\n1612,4385,2621,5602,2857,5603,2743,2312,3078,5604, 716,2464,3079, 174,1255,2710, # 4480\n4122,3645, 548,1320,1398, 728,4123,1574,5605,1891,1197,3080,4124,5606,3081,3082, # 4496\n3778,3646,3779, 747,5607, 635,4386,4747,5608,5609,5610,4387,5611,5612,4748,5613, # 4512\n3415,4749,2437, 451,5614,3780,2542,2073,4388,2744,4389,4125,5615,1764,4750,5616, # 4528\n4390, 350,4751,2283,2395,2493,5617,4391,4126,2249,1434,4127, 488,4752, 458,4392, # 4544\n4128,3781, 771,1330,2396,3914,2576,3184,2160,2414,1553,2677,3185,4393,5618,2494, # 4560\n2895,2622,1720,2711,4394,3416,4753,5619,2543,4395,5620,3262,4396,2778,5621,2016, # 4576\n2745,5622,1155,1017,3782,3915,5623,3336,2313, 201,1865,4397,1430,5624,4129,5625, # 4592\n5626,5627,5628,5629,4398,1604,5630, 414,1866, 371,2595,4754,4755,3532,2017,3127, # 4608\n4756,1708, 960,4399, 887, 389,2172,1536,1663,1721,5631,2232,4130,2356,2940,1580, # 4624\n5632,5633,1744,4757,2544,4758,4759,5634,4760,5635,2074,5636,4761,3647,3417,2896, # 4640\n4400,5637,4401,2650,3418,2815, 673,2712,2465, 709,3533,4131,3648,4402,5638,1148, # 4656\n 502, 634,5639,5640,1204,4762,3649,1575,4763,2623,3783,5641,3784,3128, 948,3263, # 4672\n 121,1745,3916,1110,5642,4403,3083,2516,3027,4132,3785,1151,1771,3917,1488,4133, # 4688\n1987,5643,2438,3534,5644,5645,2094,5646,4404,3918,1213,1407,2816, 531,2746,2545, # 4704\n3264,1011,1537,4764,2779,4405,3129,1061,5647,3786,3787,1867,2897,5648,2018, 120, # 4720\n4406,4407,2063,3650,3265,2314,3919,2678,3419,1955,4765,4134,5649,3535,1047,2713, # 4736\n1266,5650,1368,4766,2858, 649,3420,3920,2546,2747,1102,2859,2679,5651,5652,2000, # 4752\n5653,1111,3651,2977,5654,2495,3921,3652,2817,1855,3421,3788,5655,5656,3422,2415, # 4768\n2898,3337,3266,3653,5657,2577,5658,3654,2818,4135,1460, 856,5659,3655,5660,2899, # 4784\n2978,5661,2900,3922,5662,4408, 632,2517, 875,3923,1697,3924,2296,5663,5664,4767, # 4800\n3028,1239, 580,4768,4409,5665, 914, 936,2075,1190,4136,1039,2124,5666,5667,5668, # 4816\n5669,3423,1473,5670,1354,4410,3925,4769,2173,3084,4137, 915,3338,4411,4412,3339, # 4832\n1605,1835,5671,2748, 398,3656,4413,3926,4138, 328,1913,2860,4139,3927,1331,4414, # 4848\n3029, 937,4415,5672,3657,4140,4141,3424,2161,4770,3425, 524, 742, 538,3085,1012, # 4864\n5673,5674,3928,2466,5675, 658,1103, 225,3929,5676,5677,4771,5678,4772,5679,3267, # 4880\n1243,5680,4142, 963,2250,4773,5681,2714,3658,3186,5682,5683,2596,2332,5684,4774, # 4896\n5685,5686,5687,3536, 957,3426,2547,2033,1931,2941,2467, 870,2019,3659,1746,2780, # 4912\n2781,2439,2468,5688,3930,5689,3789,3130,3790,3537,3427,3791,5690,1179,3086,5691, # 4928\n3187,2378,4416,3792,2548,3188,3131,2749,4143,5692,3428,1556,2549,2297, 977,2901, # 4944\n2034,4144,1205,3429,5693,1765,3430,3189,2125,1271, 714,1689,4775,3538,5694,2333, # 4960\n3931, 533,4417,3660,2184, 617,5695,2469,3340,3539,2315,5696,5697,3190,5698,5699, # 4976\n3932,1988, 618, 427,2651,3540,3431,5700,5701,1244,1690,5702,2819,4418,4776,5703, # 4992\n3541,4777,5704,2284,1576, 473,3661,4419,3432, 972,5705,3662,5706,3087,5707,5708, # 5008\n4778,4779,5709,3793,4145,4146,5710, 153,4780, 356,5711,1892,2902,4420,2144, 408, # 5024\n 803,2357,5712,3933,5713,4421,1646,2578,2518,4781,4782,3934,5714,3935,4422,5715, # 5040\n2416,3433, 752,5716,5717,1962,3341,2979,5718, 746,3030,2470,4783,4423,3794, 698, # 5056\n4784,1893,4424,3663,2550,4785,3664,3936,5719,3191,3434,5720,1824,1302,4147,2715, # 5072\n3937,1974,4425,5721,4426,3192, 823,1303,1288,1236,2861,3542,4148,3435, 774,3938, # 5088\n5722,1581,4786,1304,2862,3939,4787,5723,2440,2162,1083,3268,4427,4149,4428, 344, # 5104\n1173, 288,2316, 454,1683,5724,5725,1461,4788,4150,2597,5726,5727,4789, 985, 894, # 5120\n5728,3436,3193,5729,1914,2942,3795,1989,5730,2111,1975,5731,4151,5732,2579,1194, # 5136\n 425,5733,4790,3194,1245,3796,4429,5734,5735,2863,5736, 636,4791,1856,3940, 760, # 5152\n1800,5737,4430,2212,1508,4792,4152,1894,1684,2298,5738,5739,4793,4431,4432,2213, # 5168\n 479,5740,5741, 832,5742,4153,2496,5743,2980,2497,3797, 990,3132, 627,1815,2652, # 5184\n4433,1582,4434,2126,2112,3543,4794,5744, 799,4435,3195,5745,4795,2113,1737,3031, # 5200\n1018, 543, 754,4436,3342,1676,4796,4797,4154,4798,1489,5746,3544,5747,2624,2903, # 5216\n4155,5748,5749,2981,5750,5751,5752,5753,3196,4799,4800,2185,1722,5754,3269,3270, # 5232\n1843,3665,1715, 481, 365,1976,1857,5755,5756,1963,2498,4801,5757,2127,3666,3271, # 5248\n 433,1895,2064,2076,5758, 602,2750,5759,5760,5761,5762,5763,3032,1628,3437,5764, # 5264\n3197,4802,4156,2904,4803,2519,5765,2551,2782,5766,5767,5768,3343,4804,2905,5769, # 5280\n4805,5770,2864,4806,4807,1221,2982,4157,2520,5771,5772,5773,1868,1990,5774,5775, # 5296\n5776,1896,5777,5778,4808,1897,4158, 318,5779,2095,4159,4437,5780,5781, 485,5782, # 5312\n 938,3941, 553,2680, 116,5783,3942,3667,5784,3545,2681,2783,3438,3344,2820,5785, # 5328\n3668,2943,4160,1747,2944,2983,5786,5787, 207,5788,4809,5789,4810,2521,5790,3033, # 5344\n 890,3669,3943,5791,1878,3798,3439,5792,2186,2358,3440,1652,5793,5794,5795, 941, # 5360\n2299, 208,3546,4161,2020, 330,4438,3944,2906,2499,3799,4439,4811,5796,5797,5798, # 5376\n)\n# fmt: on\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/big5prober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Communicator client code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .chardistribution import Big5DistributionAnalysis\nfrom .codingstatemachine import CodingStateMachine\nfrom .mbcharsetprober import MultiByteCharSetProber\nfrom .mbcssm import BIG5_SM_MODEL\n\n\nclass Big5Prober(MultiByteCharSetProber):\n    def __init__(self):\n        super().__init__()\n        self.coding_sm = CodingStateMachine(BIG5_SM_MODEL)\n        self.distribution_analyzer = Big5DistributionAnalysis()\n        self.reset()\n\n    @property\n    def charset_name(self):\n        return \"Big5\"\n\n    @property\n    def language(self):\n        return \"Chinese\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/chardistribution.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Communicator client code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .big5freq import (\n    BIG5_CHAR_TO_FREQ_ORDER,\n    BIG5_TABLE_SIZE,\n    BIG5_TYPICAL_DISTRIBUTION_RATIO,\n)\nfrom .euckrfreq import (\n    EUCKR_CHAR_TO_FREQ_ORDER,\n    EUCKR_TABLE_SIZE,\n    EUCKR_TYPICAL_DISTRIBUTION_RATIO,\n)\nfrom .euctwfreq import (\n    EUCTW_CHAR_TO_FREQ_ORDER,\n    EUCTW_TABLE_SIZE,\n    EUCTW_TYPICAL_DISTRIBUTION_RATIO,\n)\nfrom .gb2312freq import (\n    GB2312_CHAR_TO_FREQ_ORDER,\n    GB2312_TABLE_SIZE,\n    GB2312_TYPICAL_DISTRIBUTION_RATIO,\n)\nfrom .jisfreq import (\n    JIS_CHAR_TO_FREQ_ORDER,\n    JIS_TABLE_SIZE,\n    JIS_TYPICAL_DISTRIBUTION_RATIO,\n)\nfrom .johabfreq import JOHAB_TO_EUCKR_ORDER_TABLE\n\n\nclass CharDistributionAnalysis:\n    ENOUGH_DATA_THRESHOLD = 1024\n    SURE_YES = 0.99\n    SURE_NO = 0.01\n    MINIMUM_DATA_THRESHOLD = 3\n\n    def __init__(self):\n        # Mapping table to get frequency order from char order (get from\n        # GetOrder())\n        self._char_to_freq_order = tuple()\n        self._table_size = None  # Size of above table\n        # This is a constant value which varies from language to language,\n        # used in calculating confidence.  See\n        # http://www.mozilla.org/projects/intl/UniversalCharsetDetection.html\n        # for further detail.\n        self.typical_distribution_ratio = None\n        self._done = None\n        self._total_chars = None\n        self._freq_chars = None\n        self.reset()\n\n    def reset(self):\n        \"\"\"reset analyser, clear any state\"\"\"\n        # If this flag is set to True, detection is done and conclusion has\n        # been made\n        self._done = False\n        self._total_chars = 0  # Total characters encountered\n        # The number of characters whose frequency order is less than 512\n        self._freq_chars = 0\n\n    def feed(self, char, char_len):\n        \"\"\"feed a character with known length\"\"\"\n        if char_len == 2:\n            # we only care about 2-bytes character in our distribution analysis\n            order = self.get_order(char)\n        else:\n            order = -1\n        if order >= 0:\n            self._total_chars += 1\n            # order is valid\n            if order < self._table_size:\n                if 512 > self._char_to_freq_order[order]:\n                    self._freq_chars += 1\n\n    def get_confidence(self):\n        \"\"\"return confidence based on existing data\"\"\"\n        # if we didn't receive any character in our consideration range,\n        # return negative answer\n        if self._total_chars <= 0 or self._freq_chars <= self.MINIMUM_DATA_THRESHOLD:\n            return self.SURE_NO\n\n        if self._total_chars != self._freq_chars:\n            r = self._freq_chars / (\n                (self._total_chars - self._freq_chars) * self.typical_distribution_ratio\n            )\n            if r < self.SURE_YES:\n                return r\n\n        # normalize confidence (we don't want to be 100% sure)\n        return self.SURE_YES\n\n    def got_enough_data(self):\n        # It is not necessary to receive all data to draw conclusion.\n        # For charset detection, certain amount of data is enough\n        return self._total_chars > self.ENOUGH_DATA_THRESHOLD\n\n    def get_order(self, _):\n        # We do not handle characters based on the original encoding string,\n        # but convert this encoding string to a number, here called order.\n        # This allows multiple encodings of a language to share one frequency\n        # table.\n        return -1\n\n\nclass EUCTWDistributionAnalysis(CharDistributionAnalysis):\n    def __init__(self):\n        super().__init__()\n        self._char_to_freq_order = EUCTW_CHAR_TO_FREQ_ORDER\n        self._table_size = EUCTW_TABLE_SIZE\n        self.typical_distribution_ratio = EUCTW_TYPICAL_DISTRIBUTION_RATIO\n\n    def get_order(self, byte_str):\n        # for euc-TW encoding, we are interested\n        #   first  byte range: 0xc4 -- 0xfe\n        #   second byte range: 0xa1 -- 0xfe\n        # no validation needed here. State machine has done that\n        first_char = byte_str[0]\n        if first_char >= 0xC4:\n            return 94 * (first_char - 0xC4) + byte_str[1] - 0xA1\n        return -1\n\n\nclass EUCKRDistributionAnalysis(CharDistributionAnalysis):\n    def __init__(self):\n        super().__init__()\n        self._char_to_freq_order = EUCKR_CHAR_TO_FREQ_ORDER\n        self._table_size = EUCKR_TABLE_SIZE\n        self.typical_distribution_ratio = EUCKR_TYPICAL_DISTRIBUTION_RATIO\n\n    def get_order(self, byte_str):\n        # for euc-KR encoding, we are interested\n        #   first  byte range: 0xb0 -- 0xfe\n        #   second byte range: 0xa1 -- 0xfe\n        # no validation needed here. State machine has done that\n        first_char = byte_str[0]\n        if first_char >= 0xB0:\n            return 94 * (first_char - 0xB0) + byte_str[1] - 0xA1\n        return -1\n\n\nclass JOHABDistributionAnalysis(CharDistributionAnalysis):\n    def __init__(self):\n        super().__init__()\n        self._char_to_freq_order = EUCKR_CHAR_TO_FREQ_ORDER\n        self._table_size = EUCKR_TABLE_SIZE\n        self.typical_distribution_ratio = EUCKR_TYPICAL_DISTRIBUTION_RATIO\n\n    def get_order(self, byte_str):\n        first_char = byte_str[0]\n        if 0x88 <= first_char < 0xD4:\n            code = first_char * 256 + byte_str[1]\n            return JOHAB_TO_EUCKR_ORDER_TABLE.get(code, -1)\n        return -1\n\n\nclass GB2312DistributionAnalysis(CharDistributionAnalysis):\n    def __init__(self):\n        super().__init__()\n        self._char_to_freq_order = GB2312_CHAR_TO_FREQ_ORDER\n        self._table_size = GB2312_TABLE_SIZE\n        self.typical_distribution_ratio = GB2312_TYPICAL_DISTRIBUTION_RATIO\n\n    def get_order(self, byte_str):\n        # for GB2312 encoding, we are interested\n        #  first  byte range: 0xb0 -- 0xfe\n        #  second byte range: 0xa1 -- 0xfe\n        # no validation needed here. State machine has done that\n        first_char, second_char = byte_str[0], byte_str[1]\n        if (first_char >= 0xB0) and (second_char >= 0xA1):\n            return 94 * (first_char - 0xB0) + second_char - 0xA1\n        return -1\n\n\nclass Big5DistributionAnalysis(CharDistributionAnalysis):\n    def __init__(self):\n        super().__init__()\n        self._char_to_freq_order = BIG5_CHAR_TO_FREQ_ORDER\n        self._table_size = BIG5_TABLE_SIZE\n        self.typical_distribution_ratio = BIG5_TYPICAL_DISTRIBUTION_RATIO\n\n    def get_order(self, byte_str):\n        # for big5 encoding, we are interested\n        #   first  byte range: 0xa4 -- 0xfe\n        #   second byte range: 0x40 -- 0x7e , 0xa1 -- 0xfe\n        # no validation needed here. State machine has done that\n        first_char, second_char = byte_str[0], byte_str[1]\n        if first_char >= 0xA4:\n            if second_char >= 0xA1:\n                return 157 * (first_char - 0xA4) + second_char - 0xA1 + 63\n            return 157 * (first_char - 0xA4) + second_char - 0x40\n        return -1\n\n\nclass SJISDistributionAnalysis(CharDistributionAnalysis):\n    def __init__(self):\n        super().__init__()\n        self._char_to_freq_order = JIS_CHAR_TO_FREQ_ORDER\n        self._table_size = JIS_TABLE_SIZE\n        self.typical_distribution_ratio = JIS_TYPICAL_DISTRIBUTION_RATIO\n\n    def get_order(self, byte_str):\n        # for sjis encoding, we are interested\n        #   first  byte range: 0x81 -- 0x9f , 0xe0 -- 0xfe\n        #   second byte range: 0x40 -- 0x7e,  0x81 -- oxfe\n        # no validation needed here. State machine has done that\n        first_char, second_char = byte_str[0], byte_str[1]\n        if 0x81 <= first_char <= 0x9F:\n            order = 188 * (first_char - 0x81)\n        elif 0xE0 <= first_char <= 0xEF:\n            order = 188 * (first_char - 0xE0 + 31)\n        else:\n            return -1\n        order = order + second_char - 0x40\n        if second_char > 0x7F:\n            order = -1\n        return order\n\n\nclass EUCJPDistributionAnalysis(CharDistributionAnalysis):\n    def __init__(self):\n        super().__init__()\n        self._char_to_freq_order = JIS_CHAR_TO_FREQ_ORDER\n        self._table_size = JIS_TABLE_SIZE\n        self.typical_distribution_ratio = JIS_TYPICAL_DISTRIBUTION_RATIO\n\n    def get_order(self, byte_str):\n        # for euc-JP encoding, we are interested\n        #   first  byte range: 0xa0 -- 0xfe\n        #   second byte range: 0xa1 -- 0xfe\n        # no validation needed here. State machine has done that\n        char = byte_str[0]\n        if char >= 0xA0:\n            return 94 * (char - 0xA1) + byte_str[1] - 0xA1\n        return -1\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/charsetgroupprober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Communicator client code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .charsetprober import CharSetProber\nfrom .enums import ProbingState\n\n\nclass CharSetGroupProber(CharSetProber):\n    def __init__(self, lang_filter=None):\n        super().__init__(lang_filter=lang_filter)\n        self._active_num = 0\n        self.probers = []\n        self._best_guess_prober = None\n\n    def reset(self):\n        super().reset()\n        self._active_num = 0\n        for prober in self.probers:\n            if prober:\n                prober.reset()\n                prober.active = True\n                self._active_num += 1\n        self._best_guess_prober = None\n\n    @property\n    def charset_name(self):\n        if not self._best_guess_prober:\n            self.get_confidence()\n            if not self._best_guess_prober:\n                return None\n        return self._best_guess_prober.charset_name\n\n    @property\n    def language(self):\n        if not self._best_guess_prober:\n            self.get_confidence()\n            if not self._best_guess_prober:\n                return None\n        return self._best_guess_prober.language\n\n    def feed(self, byte_str):\n        for prober in self.probers:\n            if not prober:\n                continue\n            if not prober.active:\n                continue\n            state = prober.feed(byte_str)\n            if not state:\n                continue\n            if state == ProbingState.FOUND_IT:\n                self._best_guess_prober = prober\n                self._state = ProbingState.FOUND_IT\n                return self.state\n            if state == ProbingState.NOT_ME:\n                prober.active = False\n                self._active_num -= 1\n                if self._active_num <= 0:\n                    self._state = ProbingState.NOT_ME\n                    return self.state\n        return self.state\n\n    def get_confidence(self):\n        state = self.state\n        if state == ProbingState.FOUND_IT:\n            return 0.99\n        if state == ProbingState.NOT_ME:\n            return 0.01\n        best_conf = 0.0\n        self._best_guess_prober = None\n        for prober in self.probers:\n            if not prober:\n                continue\n            if not prober.active:\n                self.logger.debug(\"%s not active\", prober.charset_name)\n                continue\n            conf = prober.get_confidence()\n            self.logger.debug(\n                \"%s %s confidence = %s\", prober.charset_name, prober.language, conf\n            )\n            if best_conf < conf:\n                best_conf = conf\n                self._best_guess_prober = prober\n        if not self._best_guess_prober:\n            return 0.0\n        return best_conf\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/charsetprober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Universal charset detector code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 2001\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#   Shy Shalom - original C code\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nimport logging\nimport re\n\nfrom .enums import ProbingState\n\nINTERNATIONAL_WORDS_PATTERN = re.compile(\n    b\"[a-zA-Z]*[\\x80-\\xFF]+[a-zA-Z]*[^a-zA-Z\\x80-\\xFF]?\"\n)\n\n\nclass CharSetProber:\n\n    SHORTCUT_THRESHOLD = 0.95\n\n    def __init__(self, lang_filter=None):\n        self._state = None\n        self.lang_filter = lang_filter\n        self.logger = logging.getLogger(__name__)\n\n    def reset(self):\n        self._state = ProbingState.DETECTING\n\n    @property\n    def charset_name(self):\n        return None\n\n    def feed(self, byte_str):\n        raise NotImplementedError\n\n    @property\n    def state(self):\n        return self._state\n\n    def get_confidence(self):\n        return 0.0\n\n    @staticmethod\n    def filter_high_byte_only(buf):\n        buf = re.sub(b\"([\\x00-\\x7F])+\", b\" \", buf)\n        return buf\n\n    @staticmethod\n    def filter_international_words(buf):\n        \"\"\"\n        We define three types of bytes:\n        alphabet: english alphabets [a-zA-Z]\n        international: international characters [\\x80-\\xFF]\n        marker: everything else [^a-zA-Z\\x80-\\xFF]\n        The input buffer can be thought to contain a series of words delimited\n        by markers. This function works to filter all words that contain at\n        least one international character. All contiguous sequences of markers\n        are replaced by a single space ascii character.\n        This filter applies to all scripts which do not use English characters.\n        \"\"\"\n        filtered = bytearray()\n\n        # This regex expression filters out only words that have at-least one\n        # international character. The word may include one marker character at\n        # the end.\n        words = INTERNATIONAL_WORDS_PATTERN.findall(buf)\n\n        for word in words:\n            filtered.extend(word[:-1])\n\n            # If the last character in the word is a marker, replace it with a\n            # space as markers shouldn't affect our analysis (they are used\n            # similarly across all languages and may thus have similar\n            # frequencies).\n            last_char = word[-1:]\n            if not last_char.isalpha() and last_char < b\"\\x80\":\n                last_char = b\" \"\n            filtered.extend(last_char)\n\n        return filtered\n\n    @staticmethod\n    def remove_xml_tags(buf):\n        \"\"\"\n        Returns a copy of ``buf`` that retains only the sequences of English\n        alphabet and high byte characters that are not between <> characters.\n        This filter can be applied to all scripts which contain both English\n        characters and extended ASCII characters, but is currently only used by\n        ``Latin1Prober``.\n        \"\"\"\n        filtered = bytearray()\n        in_tag = False\n        prev = 0\n        buf = memoryview(buf).cast(\"c\")\n\n        for curr, buf_char in enumerate(buf):\n            # Check if we're coming out of or entering an XML tag\n            if buf_char == b\">\":\n                prev = curr + 1\n                in_tag = False\n            elif buf_char == b\"<\":\n                if curr > prev and not in_tag:\n                    # Keep everything after last non-extended-ASCII,\n                    # non-alphabetic character\n                    filtered.extend(buf[prev:curr])\n                    # Output a space to delimit stretch we kept\n                    filtered.extend(b\" \")\n                in_tag = True\n\n        # If we're not in a tag...\n        if not in_tag:\n            # Keep everything after last non-extended-ASCII, non-alphabetic\n            # character\n            filtered.extend(buf[prev:])\n\n        return filtered\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/cli/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/cli/chardetect.py",
    "content": "\"\"\"\nScript which takes one or more file paths and reports on their detected\nencodings\n\nExample::\n\n    % chardetect somefile someotherfile\n    somefile: windows-1252 with confidence 0.5\n    someotherfile: ascii with confidence 1.0\n\nIf no paths are provided, it takes its input from stdin.\n\n\"\"\"\n\n\nimport argparse\nimport sys\n\nfrom .. import __version__\nfrom ..universaldetector import UniversalDetector\n\n\ndef description_of(lines, name=\"stdin\"):\n    \"\"\"\n    Return a string describing the probable encoding of a file or\n    list of strings.\n\n    :param lines: The lines to get the encoding of.\n    :type lines: Iterable of bytes\n    :param name: Name of file or collection of lines\n    :type name: str\n    \"\"\"\n    u = UniversalDetector()\n    for line in lines:\n        line = bytearray(line)\n        u.feed(line)\n        # shortcut out of the loop to save reading further - particularly useful if we read a BOM.\n        if u.done:\n            break\n    u.close()\n    result = u.result\n    if result[\"encoding\"]:\n        return f'{name}: {result[\"encoding\"]} with confidence {result[\"confidence\"]}'\n    return f\"{name}: no result\"\n\n\ndef main(argv=None):\n    \"\"\"\n    Handles command line arguments and gets things started.\n\n    :param argv: List of arguments, as if specified on the command-line.\n                 If None, ``sys.argv[1:]`` is used instead.\n    :type argv: list of str\n    \"\"\"\n    # Get command line arguments\n    parser = argparse.ArgumentParser(\n        description=\"Takes one or more file paths and reports their detected \\\n                     encodings\"\n    )\n    parser.add_argument(\n        \"input\",\n        help=\"File whose encoding we would like to determine. \\\n                              (default: stdin)\",\n        type=argparse.FileType(\"rb\"),\n        nargs=\"*\",\n        default=[sys.stdin.buffer],\n    )\n    parser.add_argument(\n        \"--version\", action=\"version\", version=f\"%(prog)s {__version__}\"\n    )\n    args = parser.parse_args(argv)\n\n    for f in args.input:\n        if f.isatty():\n            print(\n                \"You are running chardetect interactively. Press \"\n                \"CTRL-D twice at the start of a blank line to signal the \"\n                \"end of your input. If you want help, run chardetect \"\n                \"--help\\n\",\n                file=sys.stderr,\n            )\n        print(description_of(f, f.name))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/codingstatemachine.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is mozilla.org code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nimport logging\n\nfrom .enums import MachineState\n\n\nclass CodingStateMachine:\n    \"\"\"\n    A state machine to verify a byte sequence for a particular encoding. For\n    each byte the detector receives, it will feed that byte to every active\n    state machine available, one byte at a time. The state machine changes its\n    state based on its previous state and the byte it receives. There are 3\n    states in a state machine that are of interest to an auto-detector:\n\n    START state: This is the state to start with, or a legal byte sequence\n                 (i.e. a valid code point) for character has been identified.\n\n    ME state:  This indicates that the state machine identified a byte sequence\n               that is specific to the charset it is designed for and that\n               there is no other possible encoding which can contain this byte\n               sequence. This will to lead to an immediate positive answer for\n               the detector.\n\n    ERROR state: This indicates the state machine identified an illegal byte\n                 sequence for that encoding. This will lead to an immediate\n                 negative answer for this encoding. Detector will exclude this\n                 encoding from consideration from here on.\n    \"\"\"\n\n    def __init__(self, sm):\n        self._model = sm\n        self._curr_byte_pos = 0\n        self._curr_char_len = 0\n        self._curr_state = None\n        self.logger = logging.getLogger(__name__)\n        self.reset()\n\n    def reset(self):\n        self._curr_state = MachineState.START\n\n    def next_state(self, c):\n        # for each byte we get its class\n        # if it is first byte, we also get byte length\n        byte_class = self._model[\"class_table\"][c]\n        if self._curr_state == MachineState.START:\n            self._curr_byte_pos = 0\n            self._curr_char_len = self._model[\"char_len_table\"][byte_class]\n        # from byte's class and state_table, we get its next state\n        curr_state = self._curr_state * self._model[\"class_factor\"] + byte_class\n        self._curr_state = self._model[\"state_table\"][curr_state]\n        self._curr_byte_pos += 1\n        return self._curr_state\n\n    def get_current_charlen(self):\n        return self._curr_char_len\n\n    def get_coding_state_machine(self):\n        return self._model[\"name\"]\n\n    @property\n    def language(self):\n        return self._model[\"language\"]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/cp949prober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is mozilla.org code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .chardistribution import EUCKRDistributionAnalysis\nfrom .codingstatemachine import CodingStateMachine\nfrom .mbcharsetprober import MultiByteCharSetProber\nfrom .mbcssm import CP949_SM_MODEL\n\n\nclass CP949Prober(MultiByteCharSetProber):\n    def __init__(self):\n        super().__init__()\n        self.coding_sm = CodingStateMachine(CP949_SM_MODEL)\n        # NOTE: CP949 is a superset of EUC-KR, so the distribution should be\n        #       not different.\n        self.distribution_analyzer = EUCKRDistributionAnalysis()\n        self.reset()\n\n    @property\n    def charset_name(self):\n        return \"CP949\"\n\n    @property\n    def language(self):\n        return \"Korean\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/enums.py",
    "content": "\"\"\"\nAll of the Enums that are used throughout the chardet package.\n\n:author: Dan Blanchard (dan.blanchard@gmail.com)\n\"\"\"\n\n\nclass InputState:\n    \"\"\"\n    This enum represents the different states a universal detector can be in.\n    \"\"\"\n\n    PURE_ASCII = 0\n    ESC_ASCII = 1\n    HIGH_BYTE = 2\n\n\nclass LanguageFilter:\n    \"\"\"\n    This enum represents the different language filters we can apply to a\n    ``UniversalDetector``.\n    \"\"\"\n\n    CHINESE_SIMPLIFIED = 0x01\n    CHINESE_TRADITIONAL = 0x02\n    JAPANESE = 0x04\n    KOREAN = 0x08\n    NON_CJK = 0x10\n    ALL = 0x1F\n    CHINESE = CHINESE_SIMPLIFIED | CHINESE_TRADITIONAL\n    CJK = CHINESE | JAPANESE | KOREAN\n\n\nclass ProbingState:\n    \"\"\"\n    This enum represents the different states a prober can be in.\n    \"\"\"\n\n    DETECTING = 0\n    FOUND_IT = 1\n    NOT_ME = 2\n\n\nclass MachineState:\n    \"\"\"\n    This enum represents the different states a state machine can be in.\n    \"\"\"\n\n    START = 0\n    ERROR = 1\n    ITS_ME = 2\n\n\nclass SequenceLikelihood:\n    \"\"\"\n    This enum represents the likelihood of a character following the previous one.\n    \"\"\"\n\n    NEGATIVE = 0\n    UNLIKELY = 1\n    LIKELY = 2\n    POSITIVE = 3\n\n    @classmethod\n    def get_num_categories(cls):\n        \"\"\":returns: The number of likelihood categories in the enum.\"\"\"\n        return 4\n\n\nclass CharacterCategory:\n    \"\"\"\n    This enum represents the different categories language models for\n    ``SingleByteCharsetProber`` put characters into.\n\n    Anything less than CONTROL is considered a letter.\n    \"\"\"\n\n    UNDEFINED = 255\n    LINE_BREAK = 254\n    SYMBOL = 253\n    DIGIT = 252\n    CONTROL = 251\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/escprober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is mozilla.org code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .charsetprober import CharSetProber\nfrom .codingstatemachine import CodingStateMachine\nfrom .enums import LanguageFilter, MachineState, ProbingState\nfrom .escsm import (\n    HZ_SM_MODEL,\n    ISO2022CN_SM_MODEL,\n    ISO2022JP_SM_MODEL,\n    ISO2022KR_SM_MODEL,\n)\n\n\nclass EscCharSetProber(CharSetProber):\n    \"\"\"\n    This CharSetProber uses a \"code scheme\" approach for detecting encodings,\n    whereby easily recognizable escape or shift sequences are relied on to\n    identify these encodings.\n    \"\"\"\n\n    def __init__(self, lang_filter=None):\n        super().__init__(lang_filter=lang_filter)\n        self.coding_sm = []\n        if self.lang_filter & LanguageFilter.CHINESE_SIMPLIFIED:\n            self.coding_sm.append(CodingStateMachine(HZ_SM_MODEL))\n            self.coding_sm.append(CodingStateMachine(ISO2022CN_SM_MODEL))\n        if self.lang_filter & LanguageFilter.JAPANESE:\n            self.coding_sm.append(CodingStateMachine(ISO2022JP_SM_MODEL))\n        if self.lang_filter & LanguageFilter.KOREAN:\n            self.coding_sm.append(CodingStateMachine(ISO2022KR_SM_MODEL))\n        self.active_sm_count = None\n        self._detected_charset = None\n        self._detected_language = None\n        self._state = None\n        self.reset()\n\n    def reset(self):\n        super().reset()\n        for coding_sm in self.coding_sm:\n            if not coding_sm:\n                continue\n            coding_sm.active = True\n            coding_sm.reset()\n        self.active_sm_count = len(self.coding_sm)\n        self._detected_charset = None\n        self._detected_language = None\n\n    @property\n    def charset_name(self):\n        return self._detected_charset\n\n    @property\n    def language(self):\n        return self._detected_language\n\n    def get_confidence(self):\n        return 0.99 if self._detected_charset else 0.00\n\n    def feed(self, byte_str):\n        for c in byte_str:\n            for coding_sm in self.coding_sm:\n                if not coding_sm or not coding_sm.active:\n                    continue\n                coding_state = coding_sm.next_state(c)\n                if coding_state == MachineState.ERROR:\n                    coding_sm.active = False\n                    self.active_sm_count -= 1\n                    if self.active_sm_count <= 0:\n                        self._state = ProbingState.NOT_ME\n                        return self.state\n                elif coding_state == MachineState.ITS_ME:\n                    self._state = ProbingState.FOUND_IT\n                    self._detected_charset = coding_sm.get_coding_state_machine()\n                    self._detected_language = coding_sm.language\n                    return self.state\n\n        return self.state\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/escsm.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is mozilla.org code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License,  or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not,  write to the Free Software\n# Foundation,  Inc.,  51 Franklin St,  Fifth Floor,  Boston,  MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .enums import MachineState\n\n# fmt: off\nHZ_CLS = (\n    1, 0, 0, 0, 0, 0, 0, 0,  # 00 - 07\n    0, 0, 0, 0, 0, 0, 0, 0,  # 08 - 0f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 10 - 17\n    0, 0, 0, 1, 0, 0, 0, 0,  # 18 - 1f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 20 - 27\n    0, 0, 0, 0, 0, 0, 0, 0,  # 28 - 2f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 30 - 37\n    0, 0, 0, 0, 0, 0, 0, 0,  # 38 - 3f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 40 - 47\n    0, 0, 0, 0, 0, 0, 0, 0,  # 48 - 4f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 50 - 57\n    0, 0, 0, 0, 0, 0, 0, 0,  # 58 - 5f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 60 - 67\n    0, 0, 0, 0, 0, 0, 0, 0,  # 68 - 6f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 70 - 77\n    0, 0, 0, 4, 0, 5, 2, 0,  # 78 - 7f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 80 - 87\n    1, 1, 1, 1, 1, 1, 1, 1,  # 88 - 8f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 90 - 97\n    1, 1, 1, 1, 1, 1, 1, 1,  # 98 - 9f\n    1, 1, 1, 1, 1, 1, 1, 1,  # a0 - a7\n    1, 1, 1, 1, 1, 1, 1, 1,  # a8 - af\n    1, 1, 1, 1, 1, 1, 1, 1,  # b0 - b7\n    1, 1, 1, 1, 1, 1, 1, 1,  # b8 - bf\n    1, 1, 1, 1, 1, 1, 1, 1,  # c0 - c7\n    1, 1, 1, 1, 1, 1, 1, 1,  # c8 - cf\n    1, 1, 1, 1, 1, 1, 1, 1,  # d0 - d7\n    1, 1, 1, 1, 1, 1, 1, 1,  # d8 - df\n    1, 1, 1, 1, 1, 1, 1, 1,  # e0 - e7\n    1, 1, 1, 1, 1, 1, 1, 1,  # e8 - ef\n    1, 1, 1, 1, 1, 1, 1, 1,  # f0 - f7\n    1, 1, 1, 1, 1, 1, 1, 1,  # f8 - ff\n)\n\nHZ_ST = (\nMachineState.START, MachineState.ERROR,      3, MachineState.START, MachineState.START, MachineState.START, MachineState.ERROR, MachineState.ERROR, # 00-07\nMachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, # 08-0f\nMachineState.ITS_ME, MachineState.ITS_ME, MachineState.ERROR, MachineState.ERROR, MachineState.START, MachineState.START,      4, MachineState.ERROR, # 10-17\n     5, MachineState.ERROR,      6, MachineState.ERROR,      5,      5,      4, MachineState.ERROR, # 18-1f\n     4, MachineState.ERROR,      4,      4,      4, MachineState.ERROR,      4, MachineState.ERROR, # 20-27\n     4, MachineState.ITS_ME, MachineState.START, MachineState.START, MachineState.START, MachineState.START, MachineState.START, MachineState.START, # 28-2f\n)\n# fmt: on\n\nHZ_CHAR_LEN_TABLE = (0, 0, 0, 0, 0, 0)\n\nHZ_SM_MODEL = {\n    \"class_table\": HZ_CLS,\n    \"class_factor\": 6,\n    \"state_table\": HZ_ST,\n    \"char_len_table\": HZ_CHAR_LEN_TABLE,\n    \"name\": \"HZ-GB-2312\",\n    \"language\": \"Chinese\",\n}\n\n# fmt: off\nISO2022CN_CLS = (\n    2, 0, 0, 0, 0, 0, 0, 0,  # 00 - 07\n    0, 0, 0, 0, 0, 0, 0, 0,  # 08 - 0f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 10 - 17\n    0, 0, 0, 1, 0, 0, 0, 0,  # 18 - 1f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 20 - 27\n    0, 3, 0, 0, 0, 0, 0, 0,  # 28 - 2f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 30 - 37\n    0, 0, 0, 0, 0, 0, 0, 0,  # 38 - 3f\n    0, 0, 0, 4, 0, 0, 0, 0,  # 40 - 47\n    0, 0, 0, 0, 0, 0, 0, 0,  # 48 - 4f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 50 - 57\n    0, 0, 0, 0, 0, 0, 0, 0,  # 58 - 5f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 60 - 67\n    0, 0, 0, 0, 0, 0, 0, 0,  # 68 - 6f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 70 - 77\n    0, 0, 0, 0, 0, 0, 0, 0,  # 78 - 7f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 80 - 87\n    2, 2, 2, 2, 2, 2, 2, 2,  # 88 - 8f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 90 - 97\n    2, 2, 2, 2, 2, 2, 2, 2,  # 98 - 9f\n    2, 2, 2, 2, 2, 2, 2, 2,  # a0 - a7\n    2, 2, 2, 2, 2, 2, 2, 2,  # a8 - af\n    2, 2, 2, 2, 2, 2, 2, 2,  # b0 - b7\n    2, 2, 2, 2, 2, 2, 2, 2,  # b8 - bf\n    2, 2, 2, 2, 2, 2, 2, 2,  # c0 - c7\n    2, 2, 2, 2, 2, 2, 2, 2,  # c8 - cf\n    2, 2, 2, 2, 2, 2, 2, 2,  # d0 - d7\n    2, 2, 2, 2, 2, 2, 2, 2,  # d8 - df\n    2, 2, 2, 2, 2, 2, 2, 2,  # e0 - e7\n    2, 2, 2, 2, 2, 2, 2, 2,  # e8 - ef\n    2, 2, 2, 2, 2, 2, 2, 2,  # f0 - f7\n    2, 2, 2, 2, 2, 2, 2, 2,  # f8 - ff\n)\n\nISO2022CN_ST = (\n    MachineState.START,      3, MachineState.ERROR, MachineState.START, MachineState.START, MachineState.START, MachineState.START, MachineState.START, # 00-07\n    MachineState.START, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, # 08-0f\n    MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, # 10-17\n    MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR,      4, MachineState.ERROR, # 18-1f\n    MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, # 20-27\n        5,      6, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, # 28-2f\n    MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, # 30-37\n    MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ERROR, MachineState.START, # 38-3f\n)\n# fmt: on\n\nISO2022CN_CHAR_LEN_TABLE = (0, 0, 0, 0, 0, 0, 0, 0, 0)\n\nISO2022CN_SM_MODEL = {\n    \"class_table\": ISO2022CN_CLS,\n    \"class_factor\": 9,\n    \"state_table\": ISO2022CN_ST,\n    \"char_len_table\": ISO2022CN_CHAR_LEN_TABLE,\n    \"name\": \"ISO-2022-CN\",\n    \"language\": \"Chinese\",\n}\n\n# fmt: off\nISO2022JP_CLS = (\n    2, 0, 0, 0, 0, 0, 0, 0,  # 00 - 07\n    0, 0, 0, 0, 0, 0, 2, 2,  # 08 - 0f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 10 - 17\n    0, 0, 0, 1, 0, 0, 0, 0,  # 18 - 1f\n    0, 0, 0, 0, 7, 0, 0, 0,  # 20 - 27\n    3, 0, 0, 0, 0, 0, 0, 0,  # 28 - 2f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 30 - 37\n    0, 0, 0, 0, 0, 0, 0, 0,  # 38 - 3f\n    6, 0, 4, 0, 8, 0, 0, 0,  # 40 - 47\n    0, 9, 5, 0, 0, 0, 0, 0,  # 48 - 4f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 50 - 57\n    0, 0, 0, 0, 0, 0, 0, 0,  # 58 - 5f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 60 - 67\n    0, 0, 0, 0, 0, 0, 0, 0,  # 68 - 6f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 70 - 77\n    0, 0, 0, 0, 0, 0, 0, 0,  # 78 - 7f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 80 - 87\n    2, 2, 2, 2, 2, 2, 2, 2,  # 88 - 8f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 90 - 97\n    2, 2, 2, 2, 2, 2, 2, 2,  # 98 - 9f\n    2, 2, 2, 2, 2, 2, 2, 2,  # a0 - a7\n    2, 2, 2, 2, 2, 2, 2, 2,  # a8 - af\n    2, 2, 2, 2, 2, 2, 2, 2,  # b0 - b7\n    2, 2, 2, 2, 2, 2, 2, 2,  # b8 - bf\n    2, 2, 2, 2, 2, 2, 2, 2,  # c0 - c7\n    2, 2, 2, 2, 2, 2, 2, 2,  # c8 - cf\n    2, 2, 2, 2, 2, 2, 2, 2,  # d0 - d7\n    2, 2, 2, 2, 2, 2, 2, 2,  # d8 - df\n    2, 2, 2, 2, 2, 2, 2, 2,  # e0 - e7\n    2, 2, 2, 2, 2, 2, 2, 2,  # e8 - ef\n    2, 2, 2, 2, 2, 2, 2, 2,  # f0 - f7\n    2, 2, 2, 2, 2, 2, 2, 2,  # f8 - ff\n)\n\nISO2022JP_ST = (\n    MachineState.START,      3, MachineState.ERROR, MachineState.START, MachineState.START, MachineState.START, MachineState.START, MachineState.START, # 00-07\n    MachineState.START, MachineState.START, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, # 08-0f\n    MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, # 10-17\n    MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ERROR, MachineState.ERROR, # 18-1f\n    MachineState.ERROR,      5, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR,      4, MachineState.ERROR, MachineState.ERROR, # 20-27\n    MachineState.ERROR, MachineState.ERROR, MachineState.ERROR,      6, MachineState.ITS_ME, MachineState.ERROR, MachineState.ITS_ME, MachineState.ERROR, # 28-2f\n    MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ITS_ME, # 30-37\n    MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, # 38-3f\n    MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ERROR, MachineState.START, MachineState.START, # 40-47\n)\n# fmt: on\n\nISO2022JP_CHAR_LEN_TABLE = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)\n\nISO2022JP_SM_MODEL = {\n    \"class_table\": ISO2022JP_CLS,\n    \"class_factor\": 10,\n    \"state_table\": ISO2022JP_ST,\n    \"char_len_table\": ISO2022JP_CHAR_LEN_TABLE,\n    \"name\": \"ISO-2022-JP\",\n    \"language\": \"Japanese\",\n}\n\n# fmt: off\nISO2022KR_CLS = (\n    2, 0, 0, 0, 0, 0, 0, 0,  # 00 - 07\n    0, 0, 0, 0, 0, 0, 0, 0,  # 08 - 0f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 10 - 17\n    0, 0, 0, 1, 0, 0, 0, 0,  # 18 - 1f\n    0, 0, 0, 0, 3, 0, 0, 0,  # 20 - 27\n    0, 4, 0, 0, 0, 0, 0, 0,  # 28 - 2f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 30 - 37\n    0, 0, 0, 0, 0, 0, 0, 0,  # 38 - 3f\n    0, 0, 0, 5, 0, 0, 0, 0,  # 40 - 47\n    0, 0, 0, 0, 0, 0, 0, 0,  # 48 - 4f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 50 - 57\n    0, 0, 0, 0, 0, 0, 0, 0,  # 58 - 5f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 60 - 67\n    0, 0, 0, 0, 0, 0, 0, 0,  # 68 - 6f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 70 - 77\n    0, 0, 0, 0, 0, 0, 0, 0,  # 78 - 7f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 80 - 87\n    2, 2, 2, 2, 2, 2, 2, 2,  # 88 - 8f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 90 - 97\n    2, 2, 2, 2, 2, 2, 2, 2,  # 98 - 9f\n    2, 2, 2, 2, 2, 2, 2, 2,  # a0 - a7\n    2, 2, 2, 2, 2, 2, 2, 2,  # a8 - af\n    2, 2, 2, 2, 2, 2, 2, 2,  # b0 - b7\n    2, 2, 2, 2, 2, 2, 2, 2,  # b8 - bf\n    2, 2, 2, 2, 2, 2, 2, 2,  # c0 - c7\n    2, 2, 2, 2, 2, 2, 2, 2,  # c8 - cf\n    2, 2, 2, 2, 2, 2, 2, 2,  # d0 - d7\n    2, 2, 2, 2, 2, 2, 2, 2,  # d8 - df\n    2, 2, 2, 2, 2, 2, 2, 2,  # e0 - e7\n    2, 2, 2, 2, 2, 2, 2, 2,  # e8 - ef\n    2, 2, 2, 2, 2, 2, 2, 2,  # f0 - f7\n    2, 2, 2, 2, 2, 2, 2, 2,  # f8 - ff\n)\n\nISO2022KR_ST = (\n    MachineState.START,      3, MachineState.ERROR, MachineState.START, MachineState.START, MachineState.START, MachineState.ERROR, MachineState.ERROR, # 00-07\n    MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ITS_ME, # 08-0f\n    MachineState.ITS_ME, MachineState.ITS_ME, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR,      4, MachineState.ERROR, MachineState.ERROR, # 10-17\n    MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR,      5, MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, # 18-1f\n    MachineState.ERROR, MachineState.ERROR, MachineState.ERROR, MachineState.ITS_ME, MachineState.START, MachineState.START, MachineState.START, MachineState.START, # 20-27\n)\n# fmt: on\n\nISO2022KR_CHAR_LEN_TABLE = (0, 0, 0, 0, 0, 0)\n\nISO2022KR_SM_MODEL = {\n    \"class_table\": ISO2022KR_CLS,\n    \"class_factor\": 6,\n    \"state_table\": ISO2022KR_ST,\n    \"char_len_table\": ISO2022KR_CHAR_LEN_TABLE,\n    \"name\": \"ISO-2022-KR\",\n    \"language\": \"Korean\",\n}\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/eucjpprober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is mozilla.org code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .chardistribution import EUCJPDistributionAnalysis\nfrom .codingstatemachine import CodingStateMachine\nfrom .enums import MachineState, ProbingState\nfrom .jpcntx import EUCJPContextAnalysis\nfrom .mbcharsetprober import MultiByteCharSetProber\nfrom .mbcssm import EUCJP_SM_MODEL\n\n\nclass EUCJPProber(MultiByteCharSetProber):\n    def __init__(self):\n        super().__init__()\n        self.coding_sm = CodingStateMachine(EUCJP_SM_MODEL)\n        self.distribution_analyzer = EUCJPDistributionAnalysis()\n        self.context_analyzer = EUCJPContextAnalysis()\n        self.reset()\n\n    def reset(self):\n        super().reset()\n        self.context_analyzer.reset()\n\n    @property\n    def charset_name(self):\n        return \"EUC-JP\"\n\n    @property\n    def language(self):\n        return \"Japanese\"\n\n    def feed(self, byte_str):\n        for i, byte in enumerate(byte_str):\n            # PY3K: byte_str is a byte array, so byte is an int, not a byte\n            coding_state = self.coding_sm.next_state(byte)\n            if coding_state == MachineState.ERROR:\n                self.logger.debug(\n                    \"%s %s prober hit error at byte %s\",\n                    self.charset_name,\n                    self.language,\n                    i,\n                )\n                self._state = ProbingState.NOT_ME\n                break\n            if coding_state == MachineState.ITS_ME:\n                self._state = ProbingState.FOUND_IT\n                break\n            if coding_state == MachineState.START:\n                char_len = self.coding_sm.get_current_charlen()\n                if i == 0:\n                    self._last_char[1] = byte\n                    self.context_analyzer.feed(self._last_char, char_len)\n                    self.distribution_analyzer.feed(self._last_char, char_len)\n                else:\n                    self.context_analyzer.feed(byte_str[i - 1 : i + 1], char_len)\n                    self.distribution_analyzer.feed(byte_str[i - 1 : i + 1], char_len)\n\n        self._last_char[0] = byte_str[-1]\n\n        if self.state == ProbingState.DETECTING:\n            if self.context_analyzer.got_enough_data() and (\n                self.get_confidence() > self.SHORTCUT_THRESHOLD\n            ):\n                self._state = ProbingState.FOUND_IT\n\n        return self.state\n\n    def get_confidence(self):\n        context_conf = self.context_analyzer.get_confidence()\n        distrib_conf = self.distribution_analyzer.get_confidence()\n        return max(context_conf, distrib_conf)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/euckrfreq.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Communicator client code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\n# Sampling from about 20M text materials include literature and computer technology\n\n# 128  --> 0.79\n# 256  --> 0.92\n# 512  --> 0.986\n# 1024 --> 0.99944\n# 2048 --> 0.99999\n#\n# Idea Distribution Ratio = 0.98653 / (1-0.98653) = 73.24\n# Random Distribution Ration = 512 / (2350-512) = 0.279.\n#\n# Typical Distribution Ratio\n\nEUCKR_TYPICAL_DISTRIBUTION_RATIO = 6.0\n\nEUCKR_TABLE_SIZE = 2352\n\n# Char to FreqOrder table ,\n# fmt: off\nEUCKR_CHAR_TO_FREQ_ORDER = (\n  13, 130, 120,1396, 481,1719,1720, 328, 609, 212,1721, 707, 400, 299,1722,  87,\n1397,1723, 104, 536,1117,1203,1724,1267, 685,1268, 508,1725,1726,1727,1728,1398,\n1399,1729,1730,1731, 141, 621, 326,1057, 368,1732, 267, 488,  20,1733,1269,1734,\n 945,1400,1735,  47, 904,1270,1736,1737, 773, 248,1738, 409, 313, 786, 429,1739,\n 116, 987, 813,1401, 683,  75,1204, 145,1740,1741,1742,1743,  16, 847, 667, 622,\n 708,1744,1745,1746, 966, 787, 304, 129,1747,  60, 820, 123, 676,1748,1749,1750,\n1751, 617,1752, 626,1753,1754,1755,1756, 653,1757,1758,1759,1760,1761,1762, 856,\n 344,1763,1764,1765,1766,  89, 401, 418, 806, 905, 848,1767,1768,1769, 946,1205,\n 709,1770,1118,1771, 241,1772,1773,1774,1271,1775, 569,1776, 999,1777,1778,1779,\n1780, 337, 751,1058,  28, 628, 254,1781, 177, 906, 270, 349, 891,1079,1782,  19,\n1783, 379,1784, 315,1785, 629, 754,1402, 559,1786, 636, 203,1206,1787, 710, 567,\n1788, 935, 814,1789,1790,1207, 766, 528,1791,1792,1208,1793,1794,1795,1796,1797,\n1403,1798,1799, 533,1059,1404,1405,1156,1406, 936, 884,1080,1800, 351,1801,1802,\n1803,1804,1805, 801,1806,1807,1808,1119,1809,1157, 714, 474,1407,1810, 298, 899,\n 885,1811,1120, 802,1158,1812, 892,1813,1814,1408, 659,1815,1816,1121,1817,1818,\n1819,1820,1821,1822, 319,1823, 594, 545,1824, 815, 937,1209,1825,1826, 573,1409,\n1022,1827,1210,1828,1829,1830,1831,1832,1833, 556, 722, 807,1122,1060,1834, 697,\n1835, 900, 557, 715,1836,1410, 540,1411, 752,1159, 294, 597,1211, 976, 803, 770,\n1412,1837,1838,  39, 794,1413, 358,1839, 371, 925,1840, 453, 661, 788, 531, 723,\n 544,1023,1081, 869,  91,1841, 392, 430, 790, 602,1414, 677,1082, 457,1415,1416,\n1842,1843, 475, 327,1024,1417, 795, 121,1844, 733, 403,1418,1845,1846,1847, 300,\n 119, 711,1212, 627,1848,1272, 207,1849,1850, 796,1213, 382,1851, 519,1852,1083,\n 893,1853,1854,1855, 367, 809, 487, 671,1856, 663,1857,1858, 956, 471, 306, 857,\n1859,1860,1160,1084,1861,1862,1863,1864,1865,1061,1866,1867,1868,1869,1870,1871,\n 282,  96, 574,1872, 502,1085,1873,1214,1874, 907,1875,1876, 827, 977,1419,1420,\n1421, 268,1877,1422,1878,1879,1880, 308,1881,   2, 537,1882,1883,1215,1884,1885,\n 127, 791,1886,1273,1423,1887,  34, 336, 404, 643,1888, 571, 654, 894, 840,1889,\n   0, 886,1274, 122, 575, 260, 908, 938,1890,1275, 410, 316,1891,1892, 100,1893,\n1894,1123,  48,1161,1124,1025,1895, 633, 901,1276,1896,1897, 115, 816,1898, 317,\n1899, 694,1900, 909, 734,1424, 572, 866,1425, 691,  85, 524,1010, 543, 394, 841,\n1901,1902,1903,1026,1904,1905,1906,1907,1908,1909,  30, 451, 651, 988, 310,1910,\n1911,1426, 810,1216,  93,1912,1913,1277,1217,1914, 858, 759,  45,  58, 181, 610,\n 269,1915,1916, 131,1062, 551, 443,1000, 821,1427, 957, 895,1086,1917,1918, 375,\n1919, 359,1920, 687,1921, 822,1922, 293,1923,1924,  40, 662, 118, 692,  29, 939,\n 887, 640, 482, 174,1925,  69,1162, 728,1428, 910,1926,1278,1218,1279, 386, 870,\n 217, 854,1163, 823,1927,1928,1929,1930, 834,1931,  78,1932, 859,1933,1063,1934,\n1935,1936,1937, 438,1164, 208, 595,1938,1939,1940,1941,1219,1125,1942, 280, 888,\n1429,1430,1220,1431,1943,1944,1945,1946,1947,1280, 150, 510,1432,1948,1949,1950,\n1951,1952,1953,1954,1011,1087,1955,1433,1043,1956, 881,1957, 614, 958,1064,1065,\n1221,1958, 638,1001, 860, 967, 896,1434, 989, 492, 553,1281,1165,1959,1282,1002,\n1283,1222,1960,1961,1962,1963,  36, 383, 228, 753, 247, 454,1964, 876, 678,1965,\n1966,1284, 126, 464, 490, 835, 136, 672, 529, 940,1088,1435, 473,1967,1968, 467,\n  50, 390, 227, 587, 279, 378, 598, 792, 968, 240, 151, 160, 849, 882,1126,1285,\n 639,1044, 133, 140, 288, 360, 811, 563,1027, 561, 142, 523,1969,1970,1971,   7,\n 103, 296, 439, 407, 506, 634, 990,1972,1973,1974,1975, 645,1976,1977,1978,1979,\n1980,1981, 236,1982,1436,1983,1984,1089, 192, 828, 618, 518,1166, 333,1127,1985,\n 818,1223,1986,1987,1988,1989,1990,1991,1992,1993, 342,1128,1286, 746, 842,1994,\n1995, 560, 223,1287,  98,   8, 189, 650, 978,1288,1996,1437,1997,  17, 345, 250,\n 423, 277, 234, 512, 226,  97, 289,  42, 167,1998, 201,1999,2000, 843, 836, 824,\n 532, 338, 783,1090, 182, 576, 436,1438,1439, 527, 500,2001, 947, 889,2002,2003,\n2004,2005, 262, 600, 314, 447,2006, 547,2007, 693, 738,1129,2008,  71,1440, 745,\n 619, 688,2009, 829,2010,2011, 147,2012,  33, 948,2013,2014,  74, 224,2015,  61,\n 191, 918, 399, 637,2016,1028,1130, 257, 902,2017,2018,2019,2020,2021,2022,2023,\n2024,2025,2026, 837,2027,2028,2029,2030, 179, 874, 591,  52, 724, 246,2031,2032,\n2033,2034,1167, 969,2035,1289, 630, 605, 911,1091,1168,2036,2037,2038,1441, 912,\n2039, 623,2040,2041, 253,1169,1290,2042,1442, 146, 620, 611, 577, 433,2043,1224,\n 719,1170, 959, 440, 437, 534,  84, 388, 480,1131, 159, 220, 198, 679,2044,1012,\n 819,1066,1443, 113,1225, 194, 318,1003,1029,2045,2046,2047,2048,1067,2049,2050,\n2051,2052,2053,  59, 913, 112,2054, 632,2055, 455, 144, 739,1291,2056, 273, 681,\n 499,2057, 448,2058,2059, 760,2060,2061, 970, 384, 169, 245,1132,2062,2063, 414,\n1444,2064,2065,  41, 235,2066, 157, 252, 877, 568, 919, 789, 580,2067, 725,2068,\n2069,1292,2070,2071,1445,2072,1446,2073,2074,  55, 588,  66,1447, 271,1092,2075,\n1226,2076, 960,1013, 372,2077,2078,2079,2080,2081,1293,2082,2083,2084,2085, 850,\n2086,2087,2088,2089,2090, 186,2091,1068, 180,2092,2093,2094, 109,1227, 522, 606,\n2095, 867,1448,1093, 991,1171, 926, 353,1133,2096, 581,2097,2098,2099,1294,1449,\n1450,2100, 596,1172,1014,1228,2101,1451,1295,1173,1229,2102,2103,1296,1134,1452,\n 949,1135,2104,2105,1094,1453,1454,1455,2106,1095,2107,2108,2109,2110,2111,2112,\n2113,2114,2115,2116,2117, 804,2118,2119,1230,1231, 805,1456, 405,1136,2120,2121,\n2122,2123,2124, 720, 701,1297, 992,1457, 927,1004,2125,2126,2127,2128,2129,2130,\n  22, 417,2131, 303,2132, 385,2133, 971, 520, 513,2134,1174,  73,1096, 231, 274,\n 962,1458, 673,2135,1459,2136, 152,1137,2137,2138,2139,2140,1005,1138,1460,1139,\n2141,2142,2143,2144,  11, 374, 844,2145, 154,1232,  46,1461,2146, 838, 830, 721,\n1233, 106,2147,  90, 428, 462, 578, 566,1175, 352,2148,2149, 538,1234, 124,1298,\n2150,1462, 761, 565,2151, 686,2152, 649,2153,  72, 173,2154, 460, 415,2155,1463,\n2156,1235, 305,2157,2158,2159,2160,2161,2162, 579,2163,2164,2165,2166,2167, 747,\n2168,2169,2170,2171,1464, 669,2172,2173,2174,2175,2176,1465,2177,  23, 530, 285,\n2178, 335, 729,2179, 397,2180,2181,2182,1030,2183,2184, 698,2185,2186, 325,2187,\n2188, 369,2189, 799,1097,1015, 348,2190,1069, 680,2191, 851,1466,2192,2193,  10,\n2194, 613, 424,2195, 979, 108, 449, 589,  27, 172,  81,1031,  80, 774, 281, 350,\n1032, 525, 301, 582,1176,2196, 674,1045,2197,2198,1467, 730, 762,2199,2200,2201,\n2202,1468,2203, 993,2204,2205, 266,1070, 963,1140,2206,2207,2208, 664,1098, 972,\n2209,2210,2211,1177,1469,1470, 871,2212,2213,2214,2215,2216,1471,2217,2218,2219,\n2220,2221,2222,2223,2224,2225,2226,2227,1472,1236,2228,2229,2230,2231,2232,2233,\n2234,2235,1299,2236,2237, 200,2238, 477, 373,2239,2240, 731, 825, 777,2241,2242,\n2243, 521, 486, 548,2244,2245,2246,1473,1300,  53, 549, 137, 875,  76, 158,2247,\n1301,1474, 469, 396,1016, 278, 712,2248, 321, 442, 503, 767, 744, 941,1237,1178,\n1475,2249,  82, 178,1141,1179, 973,2250,1302,2251, 297,2252,2253, 570,2254,2255,\n2256,  18, 450, 206,2257, 290, 292,1142,2258, 511, 162,  99, 346, 164, 735,2259,\n1476,1477,   4, 554, 343, 798,1099,2260,1100,2261,  43, 171,1303, 139, 215,2262,\n2263, 717, 775,2264,1033, 322, 216,2265, 831,2266, 149,2267,1304,2268,2269, 702,\n1238, 135, 845, 347, 309,2270, 484,2271, 878, 655, 238,1006,1478,2272,  67,2273,\n 295,2274,2275, 461,2276, 478, 942, 412,2277,1034,2278,2279,2280, 265,2281, 541,\n2282,2283,2284,2285,2286,  70, 852,1071,2287,2288,2289,2290,  21,  56, 509, 117,\n 432,2291,2292, 331, 980, 552,1101, 148, 284, 105, 393,1180,1239, 755,2293, 187,\n2294,1046,1479,2295, 340,2296,  63,1047, 230,2297,2298,1305, 763,1306, 101, 800,\n 808, 494,2299,2300,2301, 903,2302,  37,1072,  14,   5,2303,  79, 675,2304, 312,\n2305,2306,2307,2308,2309,1480,   6,1307,2310,2311,2312,   1, 470,  35,  24, 229,\n2313, 695, 210,  86, 778,  15, 784, 592, 779,  32,  77, 855, 964,2314, 259,2315,\n 501, 380,2316,2317,  83, 981, 153, 689,1308,1481,1482,1483,2318,2319, 716,1484,\n2320,2321,2322,2323,2324,2325,1485,2326,2327, 128,  57,  68, 261,1048, 211, 170,\n1240,  31,2328,  51, 435, 742,2329,2330,2331, 635,2332, 264, 456,2333,2334,2335,\n 425,2336,1486, 143, 507, 263, 943,2337, 363, 920,1487, 256,1488,1102, 243, 601,\n1489,2338,2339,2340,2341,2342,2343,2344, 861,2345,2346,2347,2348,2349,2350, 395,\n2351,1490,1491,  62, 535, 166, 225,2352,2353, 668, 419,1241, 138, 604, 928,2354,\n1181,2355,1492,1493,2356,2357,2358,1143,2359, 696,2360, 387, 307,1309, 682, 476,\n2361,2362, 332,  12, 222, 156,2363, 232,2364, 641, 276, 656, 517,1494,1495,1035,\n 416, 736,1496,2365,1017, 586,2366,2367,2368,1497,2369, 242,2370,2371,2372,1498,\n2373, 965, 713,2374,2375,2376,2377, 740, 982,1499, 944,1500,1007,2378,2379,1310,\n1501,2380,2381,2382, 785, 329,2383,2384,1502,2385,2386,2387, 932,2388,1503,2389,\n2390,2391,2392,1242,2393,2394,2395,2396,2397, 994, 950,2398,2399,2400,2401,1504,\n1311,2402,2403,2404,2405,1049, 749,2406,2407, 853, 718,1144,1312,2408,1182,1505,\n2409,2410, 255, 516, 479, 564, 550, 214,1506,1507,1313, 413, 239, 444, 339,1145,\n1036,1508,1509,1314,1037,1510,1315,2411,1511,2412,2413,2414, 176, 703, 497, 624,\n 593, 921, 302,2415, 341, 165,1103,1512,2416,1513,2417,2418,2419, 376,2420, 700,\n2421,2422,2423, 258, 768,1316,2424,1183,2425, 995, 608,2426,2427,2428,2429, 221,\n2430,2431,2432,2433,2434,2435,2436,2437, 195, 323, 726, 188, 897, 983,1317, 377,\n 644,1050, 879,2438, 452,2439,2440,2441,2442,2443,2444, 914,2445,2446,2447,2448,\n 915, 489,2449,1514,1184,2450,2451, 515,  64, 427, 495,2452, 583,2453, 483, 485,\n1038, 562, 213,1515, 748, 666,2454,2455,2456,2457, 334,2458, 780, 996,1008, 705,\n1243,2459,2460,2461,2462,2463, 114,2464, 493,1146, 366, 163,1516, 961,1104,2465,\n 291,2466,1318,1105,2467,1517, 365,2468, 355, 951,1244,2469,1319,2470, 631,2471,\n2472, 218,1320, 364, 320, 756,1518,1519,1321,1520,1322,2473,2474,2475,2476, 997,\n2477,2478,2479,2480, 665,1185,2481, 916,1521,2482,2483,2484, 584, 684,2485,2486,\n 797,2487,1051,1186,2488,2489,2490,1522,2491,2492, 370,2493,1039,1187,  65,2494,\n 434, 205, 463,1188,2495, 125, 812, 391, 402, 826, 699, 286, 398, 155, 781, 771,\n 585,2496, 590, 505,1073,2497, 599, 244, 219, 917,1018, 952, 646,1523,2498,1323,\n2499,2500,  49, 984, 354, 741,2501, 625,2502,1324,2503,1019, 190, 357, 757, 491,\n  95, 782, 868,2504,2505,2506,2507,2508,2509, 134,1524,1074, 422,1525, 898,2510,\n 161,2511,2512,2513,2514, 769,2515,1526,2516,2517, 411,1325,2518, 472,1527,2519,\n2520,2521,2522,2523,2524, 985,2525,2526,2527,2528,2529,2530, 764,2531,1245,2532,\n2533,  25, 204, 311,2534, 496,2535,1052,2536,2537,2538,2539,2540,2541,2542, 199,\n 704, 504, 468, 758, 657,1528, 196,  44, 839,1246, 272, 750,2543, 765, 862,2544,\n2545,1326,2546, 132, 615, 933,2547, 732,2548,2549,2550,1189,1529,2551, 283,1247,\n1053, 607, 929,2552,2553,2554, 930, 183, 872, 616,1040,1147,2555,1148,1020, 441,\n 249,1075,2556,2557,2558, 466, 743,2559,2560,2561,  92, 514, 426, 420, 526,2562,\n2563,2564,2565,2566,2567,2568, 185,2569,2570,2571,2572, 776,1530, 658,2573, 362,\n2574, 361, 922,1076, 793,2575,2576,2577,2578,2579,2580,1531, 251,2581,2582,2583,\n2584,1532,  54, 612, 237,1327,2585,2586, 275, 408, 647, 111,2587,1533,1106, 465,\n   3, 458,   9,  38,2588, 107, 110, 890, 209,  26, 737, 498,2589,1534,2590, 431,\n 202,  88,1535, 356, 287,1107, 660,1149,2591, 381,1536, 986,1150, 445,1248,1151,\n 974,2592,2593, 846,2594, 446, 953, 184,1249,1250, 727,2595, 923, 193, 883,2596,\n2597,2598, 102, 324, 539, 817,2599, 421,1041,2600, 832,2601,  94, 175, 197, 406,\n2602, 459,2603,2604,2605,2606,2607, 330, 555,2608,2609,2610, 706,1108, 389,2611,\n2612,2613,2614, 233,2615, 833, 558, 931, 954,1251,2616,2617,1537, 546,2618,2619,\n1009,2620,2621,2622,1538, 690,1328,2623, 955,2624,1539,2625,2626, 772,2627,2628,\n2629,2630,2631, 924, 648, 863, 603,2632,2633, 934,1540, 864, 865,2634, 642,1042,\n 670,1190,2635,2636,2637,2638, 168,2639, 652, 873, 542,1054,1541,2640,2641,2642,  # 512, 256\n)\n# fmt: on\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/euckrprober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is mozilla.org code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .chardistribution import EUCKRDistributionAnalysis\nfrom .codingstatemachine import CodingStateMachine\nfrom .mbcharsetprober import MultiByteCharSetProber\nfrom .mbcssm import EUCKR_SM_MODEL\n\n\nclass EUCKRProber(MultiByteCharSetProber):\n    def __init__(self):\n        super().__init__()\n        self.coding_sm = CodingStateMachine(EUCKR_SM_MODEL)\n        self.distribution_analyzer = EUCKRDistributionAnalysis()\n        self.reset()\n\n    @property\n    def charset_name(self):\n        return \"EUC-KR\"\n\n    @property\n    def language(self):\n        return \"Korean\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/euctwfreq.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Communicator client code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\n# EUCTW frequency table\n# Converted from big5 work\n# by Taiwan's Mandarin Promotion Council\n# <http:#www.edu.tw:81/mandr/>\n\n# 128  --> 0.42261\n# 256  --> 0.57851\n# 512  --> 0.74851\n# 1024 --> 0.89384\n# 2048 --> 0.97583\n#\n# Idea Distribution Ratio = 0.74851/(1-0.74851) =2.98\n# Random Distribution Ration = 512/(5401-512)=0.105\n#\n# Typical Distribution Ratio about 25% of Ideal one, still much higher than RDR\n\nEUCTW_TYPICAL_DISTRIBUTION_RATIO = 0.75\n\n# Char to FreqOrder table\nEUCTW_TABLE_SIZE = 5376\n\n# fmt: off\nEUCTW_CHAR_TO_FREQ_ORDER = (\n    1, 1800, 1506, 255, 1431, 198, 9, 82, 6, 7310, 177, 202, 3615, 1256, 2808, 110,  # 2742\n    3735, 33, 3241, 261, 76, 44, 2113, 16, 2931, 2184, 1176, 659, 3868, 26, 3404, 2643,  # 2758\n    1198, 3869, 3313, 4060, 410, 2211, 302, 590, 361, 1963, 8, 204, 58, 4296, 7311, 1931,  # 2774\n    63, 7312, 7313, 317, 1614, 75, 222, 159, 4061, 2412, 1480, 7314, 3500, 3068, 224, 2809,  # 2790\n    3616, 3, 10, 3870, 1471, 29, 2774, 1135, 2852, 1939, 873, 130, 3242, 1123, 312, 7315,  # 2806\n    4297, 2051, 507, 252, 682, 7316, 142, 1914, 124, 206, 2932, 34, 3501, 3173, 64, 604,  # 2822\n    7317, 2494, 1976, 1977, 155, 1990, 645, 641, 1606, 7318, 3405, 337, 72, 406, 7319, 80,  # 2838\n    630, 238, 3174, 1509, 263, 939, 1092, 2644, 756, 1440, 1094, 3406, 449, 69, 2969, 591,  # 2854\n    179, 2095, 471, 115, 2034, 1843, 60, 50, 2970, 134, 806, 1868, 734, 2035, 3407, 180,  # 2870\n    995, 1607, 156, 537, 2893, 688, 7320, 319, 1305, 779, 2144, 514, 2374, 298, 4298, 359,  # 2886\n    2495, 90, 2707, 1338, 663, 11, 906, 1099, 2545, 20, 2436, 182, 532, 1716, 7321, 732,  # 2902\n    1376, 4062, 1311, 1420, 3175, 25, 2312, 1056, 113, 399, 382, 1949, 242, 3408, 2467, 529,  # 2918\n    3243, 475, 1447, 3617, 7322, 117, 21, 656, 810, 1297, 2295, 2329, 3502, 7323, 126, 4063,  # 2934\n    706, 456, 150, 613, 4299, 71, 1118, 2036, 4064, 145, 3069, 85, 835, 486, 2114, 1246,  # 2950\n    1426, 428, 727, 1285, 1015, 800, 106, 623, 303, 1281, 7324, 2127, 2354, 347, 3736, 221,  # 2966\n    3503, 3110, 7325, 1955, 1153, 4065, 83, 296, 1199, 3070, 192, 624, 93, 7326, 822, 1897,  # 2982\n    2810, 3111, 795, 2064, 991, 1554, 1542, 1592, 27, 43, 2853, 859, 139, 1456, 860, 4300,  # 2998\n    437, 712, 3871, 164, 2392, 3112, 695, 211, 3017, 2096, 195, 3872, 1608, 3504, 3505, 3618,  # 3014\n    3873, 234, 811, 2971, 2097, 3874, 2229, 1441, 3506, 1615, 2375, 668, 2076, 1638, 305, 228,  # 3030\n    1664, 4301, 467, 415, 7327, 262, 2098, 1593, 239, 108, 300, 200, 1033, 512, 1247, 2077,  # 3046\n    7328, 7329, 2173, 3176, 3619, 2673, 593, 845, 1062, 3244, 88, 1723, 2037, 3875, 1950, 212,  # 3062\n    266, 152, 149, 468, 1898, 4066, 4302, 77, 187, 7330, 3018, 37, 5, 2972, 7331, 3876,  # 3078\n    7332, 7333, 39, 2517, 4303, 2894, 3177, 2078, 55, 148, 74, 4304, 545, 483, 1474, 1029,  # 3094\n    1665, 217, 1869, 1531, 3113, 1104, 2645, 4067, 24, 172, 3507, 900, 3877, 3508, 3509, 4305,  # 3110\n    32, 1408, 2811, 1312, 329, 487, 2355, 2247, 2708, 784, 2674, 4, 3019, 3314, 1427, 1788,  # 3126\n    188, 109, 499, 7334, 3620, 1717, 1789, 888, 1217, 3020, 4306, 7335, 3510, 7336, 3315, 1520,  # 3142\n    3621, 3878, 196, 1034, 775, 7337, 7338, 929, 1815, 249, 439, 38, 7339, 1063, 7340, 794,  # 3158\n    3879, 1435, 2296, 46, 178, 3245, 2065, 7341, 2376, 7342, 214, 1709, 4307, 804, 35, 707,  # 3174\n    324, 3622, 1601, 2546, 140, 459, 4068, 7343, 7344, 1365, 839, 272, 978, 2257, 2572, 3409,  # 3190\n    2128, 1363, 3623, 1423, 697, 100, 3071, 48, 70, 1231, 495, 3114, 2193, 7345, 1294, 7346,  # 3206\n    2079, 462, 586, 1042, 3246, 853, 256, 988, 185, 2377, 3410, 1698, 434, 1084, 7347, 3411,  # 3222\n    314, 2615, 2775, 4308, 2330, 2331, 569, 2280, 637, 1816, 2518, 757, 1162, 1878, 1616, 3412,  # 3238\n    287, 1577, 2115, 768, 4309, 1671, 2854, 3511, 2519, 1321, 3737, 909, 2413, 7348, 4069, 933,  # 3254\n    3738, 7349, 2052, 2356, 1222, 4310, 765, 2414, 1322, 786, 4311, 7350, 1919, 1462, 1677, 2895,  # 3270\n    1699, 7351, 4312, 1424, 2437, 3115, 3624, 2590, 3316, 1774, 1940, 3413, 3880, 4070, 309, 1369,  # 3286\n    1130, 2812, 364, 2230, 1653, 1299, 3881, 3512, 3882, 3883, 2646, 525, 1085, 3021, 902, 2000,  # 3302\n    1475, 964, 4313, 421, 1844, 1415, 1057, 2281, 940, 1364, 3116, 376, 4314, 4315, 1381, 7,  # 3318\n    2520, 983, 2378, 336, 1710, 2675, 1845, 321, 3414, 559, 1131, 3022, 2742, 1808, 1132, 1313,  # 3334\n    265, 1481, 1857, 7352, 352, 1203, 2813, 3247, 167, 1089, 420, 2814, 776, 792, 1724, 3513,  # 3350\n    4071, 2438, 3248, 7353, 4072, 7354, 446, 229, 333, 2743, 901, 3739, 1200, 1557, 4316, 2647,  # 3366\n    1920, 395, 2744, 2676, 3740, 4073, 1835, 125, 916, 3178, 2616, 4317, 7355, 7356, 3741, 7357,  # 3382\n    7358, 7359, 4318, 3117, 3625, 1133, 2547, 1757, 3415, 1510, 2313, 1409, 3514, 7360, 2145, 438,  # 3398\n    2591, 2896, 2379, 3317, 1068, 958, 3023, 461, 311, 2855, 2677, 4074, 1915, 3179, 4075, 1978,  # 3414\n    383, 750, 2745, 2617, 4076, 274, 539, 385, 1278, 1442, 7361, 1154, 1964, 384, 561, 210,  # 3430\n    98, 1295, 2548, 3515, 7362, 1711, 2415, 1482, 3416, 3884, 2897, 1257, 129, 7363, 3742, 642,  # 3446\n    523, 2776, 2777, 2648, 7364, 141, 2231, 1333, 68, 176, 441, 876, 907, 4077, 603, 2592,  # 3462\n    710, 171, 3417, 404, 549, 18, 3118, 2393, 1410, 3626, 1666, 7365, 3516, 4319, 2898, 4320,  # 3478\n    7366, 2973, 368, 7367, 146, 366, 99, 871, 3627, 1543, 748, 807, 1586, 1185, 22, 2258,  # 3494\n    379, 3743, 3180, 7368, 3181, 505, 1941, 2618, 1991, 1382, 2314, 7369, 380, 2357, 218, 702,  # 3510\n    1817, 1248, 3418, 3024, 3517, 3318, 3249, 7370, 2974, 3628, 930, 3250, 3744, 7371, 59, 7372,  # 3526\n    585, 601, 4078, 497, 3419, 1112, 1314, 4321, 1801, 7373, 1223, 1472, 2174, 7374, 749, 1836,  # 3542\n    690, 1899, 3745, 1772, 3885, 1476, 429, 1043, 1790, 2232, 2116, 917, 4079, 447, 1086, 1629,  # 3558\n    7375, 556, 7376, 7377, 2020, 1654, 844, 1090, 105, 550, 966, 1758, 2815, 1008, 1782, 686,  # 3574\n    1095, 7378, 2282, 793, 1602, 7379, 3518, 2593, 4322, 4080, 2933, 2297, 4323, 3746, 980, 2496,  # 3590\n    544, 353, 527, 4324, 908, 2678, 2899, 7380, 381, 2619, 1942, 1348, 7381, 1341, 1252, 560,  # 3606\n    3072, 7382, 3420, 2856, 7383, 2053, 973, 886, 2080, 143, 4325, 7384, 7385, 157, 3886, 496,  # 3622\n    4081, 57, 840, 540, 2038, 4326, 4327, 3421, 2117, 1445, 970, 2259, 1748, 1965, 2081, 4082,  # 3638\n    3119, 1234, 1775, 3251, 2816, 3629, 773, 1206, 2129, 1066, 2039, 1326, 3887, 1738, 1725, 4083,  # 3654\n    279, 3120, 51, 1544, 2594, 423, 1578, 2130, 2066, 173, 4328, 1879, 7386, 7387, 1583, 264,  # 3670\n    610, 3630, 4329, 2439, 280, 154, 7388, 7389, 7390, 1739, 338, 1282, 3073, 693, 2857, 1411,  # 3686\n    1074, 3747, 2440, 7391, 4330, 7392, 7393, 1240, 952, 2394, 7394, 2900, 1538, 2679, 685, 1483,  # 3702\n    4084, 2468, 1436, 953, 4085, 2054, 4331, 671, 2395, 79, 4086, 2441, 3252, 608, 567, 2680,  # 3718\n    3422, 4087, 4088, 1691, 393, 1261, 1791, 2396, 7395, 4332, 7396, 7397, 7398, 7399, 1383, 1672,  # 3734\n    3748, 3182, 1464, 522, 1119, 661, 1150, 216, 675, 4333, 3888, 1432, 3519, 609, 4334, 2681,  # 3750\n    2397, 7400, 7401, 7402, 4089, 3025, 0, 7403, 2469, 315, 231, 2442, 301, 3319, 4335, 2380,  # 3766\n    7404, 233, 4090, 3631, 1818, 4336, 4337, 7405, 96, 1776, 1315, 2082, 7406, 257, 7407, 1809,  # 3782\n    3632, 2709, 1139, 1819, 4091, 2021, 1124, 2163, 2778, 1777, 2649, 7408, 3074, 363, 1655, 3183,  # 3798\n    7409, 2975, 7410, 7411, 7412, 3889, 1567, 3890, 718, 103, 3184, 849, 1443, 341, 3320, 2934,  # 3814\n    1484, 7413, 1712, 127, 67, 339, 4092, 2398, 679, 1412, 821, 7414, 7415, 834, 738, 351,  # 3830\n    2976, 2146, 846, 235, 1497, 1880, 418, 1992, 3749, 2710, 186, 1100, 2147, 2746, 3520, 1545,  # 3846\n    1355, 2935, 2858, 1377, 583, 3891, 4093, 2573, 2977, 7416, 1298, 3633, 1078, 2549, 3634, 2358,  # 3862\n    78, 3750, 3751, 267, 1289, 2099, 2001, 1594, 4094, 348, 369, 1274, 2194, 2175, 1837, 4338,  # 3878\n    1820, 2817, 3635, 2747, 2283, 2002, 4339, 2936, 2748, 144, 3321, 882, 4340, 3892, 2749, 3423,  # 3894\n    4341, 2901, 7417, 4095, 1726, 320, 7418, 3893, 3026, 788, 2978, 7419, 2818, 1773, 1327, 2859,  # 3910\n    3894, 2819, 7420, 1306, 4342, 2003, 1700, 3752, 3521, 2359, 2650, 787, 2022, 506, 824, 3636,  # 3926\n    534, 323, 4343, 1044, 3322, 2023, 1900, 946, 3424, 7421, 1778, 1500, 1678, 7422, 1881, 4344,  # 3942\n    165, 243, 4345, 3637, 2521, 123, 683, 4096, 764, 4346, 36, 3895, 1792, 589, 2902, 816,  # 3958\n    626, 1667, 3027, 2233, 1639, 1555, 1622, 3753, 3896, 7423, 3897, 2860, 1370, 1228, 1932, 891,  # 3974\n    2083, 2903, 304, 4097, 7424, 292, 2979, 2711, 3522, 691, 2100, 4098, 1115, 4347, 118, 662,  # 3990\n    7425, 611, 1156, 854, 2381, 1316, 2861, 2, 386, 515, 2904, 7426, 7427, 3253, 868, 2234,  # 4006\n    1486, 855, 2651, 785, 2212, 3028, 7428, 1040, 3185, 3523, 7429, 3121, 448, 7430, 1525, 7431,  # 4022\n    2164, 4348, 7432, 3754, 7433, 4099, 2820, 3524, 3122, 503, 818, 3898, 3123, 1568, 814, 676,  # 4038\n    1444, 306, 1749, 7434, 3755, 1416, 1030, 197, 1428, 805, 2821, 1501, 4349, 7435, 7436, 7437,  # 4054\n    1993, 7438, 4350, 7439, 7440, 2195, 13, 2779, 3638, 2980, 3124, 1229, 1916, 7441, 3756, 2131,  # 4070\n    7442, 4100, 4351, 2399, 3525, 7443, 2213, 1511, 1727, 1120, 7444, 7445, 646, 3757, 2443, 307,  # 4086\n    7446, 7447, 1595, 3186, 7448, 7449, 7450, 3639, 1113, 1356, 3899, 1465, 2522, 2523, 7451, 519,  # 4102\n    7452, 128, 2132, 92, 2284, 1979, 7453, 3900, 1512, 342, 3125, 2196, 7454, 2780, 2214, 1980,  # 4118\n    3323, 7455, 290, 1656, 1317, 789, 827, 2360, 7456, 3758, 4352, 562, 581, 3901, 7457, 401,  # 4134\n    4353, 2248, 94, 4354, 1399, 2781, 7458, 1463, 2024, 4355, 3187, 1943, 7459, 828, 1105, 4101,  # 4150\n    1262, 1394, 7460, 4102, 605, 4356, 7461, 1783, 2862, 7462, 2822, 819, 2101, 578, 2197, 2937,  # 4166\n    7463, 1502, 436, 3254, 4103, 3255, 2823, 3902, 2905, 3425, 3426, 7464, 2712, 2315, 7465, 7466,  # 4182\n    2332, 2067, 23, 4357, 193, 826, 3759, 2102, 699, 1630, 4104, 3075, 390, 1793, 1064, 3526,  # 4198\n    7467, 1579, 3076, 3077, 1400, 7468, 4105, 1838, 1640, 2863, 7469, 4358, 4359, 137, 4106, 598,  # 4214\n    3078, 1966, 780, 104, 974, 2938, 7470, 278, 899, 253, 402, 572, 504, 493, 1339, 7471,  # 4230\n    3903, 1275, 4360, 2574, 2550, 7472, 3640, 3029, 3079, 2249, 565, 1334, 2713, 863, 41, 7473,  # 4246\n    7474, 4361, 7475, 1657, 2333, 19, 463, 2750, 4107, 606, 7476, 2981, 3256, 1087, 2084, 1323,  # 4262\n    2652, 2982, 7477, 1631, 1623, 1750, 4108, 2682, 7478, 2864, 791, 2714, 2653, 2334, 232, 2416,  # 4278\n    7479, 2983, 1498, 7480, 2654, 2620, 755, 1366, 3641, 3257, 3126, 2025, 1609, 119, 1917, 3427,  # 4294\n    862, 1026, 4109, 7481, 3904, 3760, 4362, 3905, 4363, 2260, 1951, 2470, 7482, 1125, 817, 4110,  # 4310\n    4111, 3906, 1513, 1766, 2040, 1487, 4112, 3030, 3258, 2824, 3761, 3127, 7483, 7484, 1507, 7485,  # 4326\n    2683, 733, 40, 1632, 1106, 2865, 345, 4113, 841, 2524, 230, 4364, 2984, 1846, 3259, 3428,  # 4342\n    7486, 1263, 986, 3429, 7487, 735, 879, 254, 1137, 857, 622, 1300, 1180, 1388, 1562, 3907,  # 4358\n    3908, 2939, 967, 2751, 2655, 1349, 592, 2133, 1692, 3324, 2985, 1994, 4114, 1679, 3909, 1901,  # 4374\n    2185, 7488, 739, 3642, 2715, 1296, 1290, 7489, 4115, 2198, 2199, 1921, 1563, 2595, 2551, 1870,  # 4390\n    2752, 2986, 7490, 435, 7491, 343, 1108, 596, 17, 1751, 4365, 2235, 3430, 3643, 7492, 4366,  # 4406\n    294, 3527, 2940, 1693, 477, 979, 281, 2041, 3528, 643, 2042, 3644, 2621, 2782, 2261, 1031,  # 4422\n    2335, 2134, 2298, 3529, 4367, 367, 1249, 2552, 7493, 3530, 7494, 4368, 1283, 3325, 2004, 240,  # 4438\n    1762, 3326, 4369, 4370, 836, 1069, 3128, 474, 7495, 2148, 2525, 268, 3531, 7496, 3188, 1521,  # 4454\n    1284, 7497, 1658, 1546, 4116, 7498, 3532, 3533, 7499, 4117, 3327, 2684, 1685, 4118, 961, 1673,  # 4470\n    2622, 190, 2005, 2200, 3762, 4371, 4372, 7500, 570, 2497, 3645, 1490, 7501, 4373, 2623, 3260,  # 4486\n    1956, 4374, 584, 1514, 396, 1045, 1944, 7502, 4375, 1967, 2444, 7503, 7504, 4376, 3910, 619,  # 4502\n    7505, 3129, 3261, 215, 2006, 2783, 2553, 3189, 4377, 3190, 4378, 763, 4119, 3763, 4379, 7506,  # 4518\n    7507, 1957, 1767, 2941, 3328, 3646, 1174, 452, 1477, 4380, 3329, 3130, 7508, 2825, 1253, 2382,  # 4534\n    2186, 1091, 2285, 4120, 492, 7509, 638, 1169, 1824, 2135, 1752, 3911, 648, 926, 1021, 1324,  # 4550\n    4381, 520, 4382, 997, 847, 1007, 892, 4383, 3764, 2262, 1871, 3647, 7510, 2400, 1784, 4384,  # 4566\n    1952, 2942, 3080, 3191, 1728, 4121, 2043, 3648, 4385, 2007, 1701, 3131, 1551, 30, 2263, 4122,  # 4582\n    7511, 2026, 4386, 3534, 7512, 501, 7513, 4123, 594, 3431, 2165, 1821, 3535, 3432, 3536, 3192,  # 4598\n    829, 2826, 4124, 7514, 1680, 3132, 1225, 4125, 7515, 3262, 4387, 4126, 3133, 2336, 7516, 4388,  # 4614\n    4127, 7517, 3912, 3913, 7518, 1847, 2383, 2596, 3330, 7519, 4389, 374, 3914, 652, 4128, 4129,  # 4630\n    375, 1140, 798, 7520, 7521, 7522, 2361, 4390, 2264, 546, 1659, 138, 3031, 2445, 4391, 7523,  # 4646\n    2250, 612, 1848, 910, 796, 3765, 1740, 1371, 825, 3766, 3767, 7524, 2906, 2554, 7525, 692,  # 4662\n    444, 3032, 2624, 801, 4392, 4130, 7526, 1491, 244, 1053, 3033, 4131, 4132, 340, 7527, 3915,  # 4678\n    1041, 2987, 293, 1168, 87, 1357, 7528, 1539, 959, 7529, 2236, 721, 694, 4133, 3768, 219,  # 4694\n    1478, 644, 1417, 3331, 2656, 1413, 1401, 1335, 1389, 3916, 7530, 7531, 2988, 2362, 3134, 1825,  # 4710\n    730, 1515, 184, 2827, 66, 4393, 7532, 1660, 2943, 246, 3332, 378, 1457, 226, 3433, 975,  # 4726\n    3917, 2944, 1264, 3537, 674, 696, 7533, 163, 7534, 1141, 2417, 2166, 713, 3538, 3333, 4394,  # 4742\n    3918, 7535, 7536, 1186, 15, 7537, 1079, 1070, 7538, 1522, 3193, 3539, 276, 1050, 2716, 758,  # 4758\n    1126, 653, 2945, 3263, 7539, 2337, 889, 3540, 3919, 3081, 2989, 903, 1250, 4395, 3920, 3434,  # 4774\n    3541, 1342, 1681, 1718, 766, 3264, 286, 89, 2946, 3649, 7540, 1713, 7541, 2597, 3334, 2990,  # 4790\n    7542, 2947, 2215, 3194, 2866, 7543, 4396, 2498, 2526, 181, 387, 1075, 3921, 731, 2187, 3335,  # 4806\n    7544, 3265, 310, 313, 3435, 2299, 770, 4134, 54, 3034, 189, 4397, 3082, 3769, 3922, 7545,  # 4822\n    1230, 1617, 1849, 355, 3542, 4135, 4398, 3336, 111, 4136, 3650, 1350, 3135, 3436, 3035, 4137,  # 4838\n    2149, 3266, 3543, 7546, 2784, 3923, 3924, 2991, 722, 2008, 7547, 1071, 247, 1207, 2338, 2471,  # 4854\n    1378, 4399, 2009, 864, 1437, 1214, 4400, 373, 3770, 1142, 2216, 667, 4401, 442, 2753, 2555,  # 4870\n    3771, 3925, 1968, 4138, 3267, 1839, 837, 170, 1107, 934, 1336, 1882, 7548, 7549, 2118, 4139,  # 4886\n    2828, 743, 1569, 7550, 4402, 4140, 582, 2384, 1418, 3437, 7551, 1802, 7552, 357, 1395, 1729,  # 4902\n    3651, 3268, 2418, 1564, 2237, 7553, 3083, 3772, 1633, 4403, 1114, 2085, 4141, 1532, 7554, 482,  # 4918\n    2446, 4404, 7555, 7556, 1492, 833, 1466, 7557, 2717, 3544, 1641, 2829, 7558, 1526, 1272, 3652,  # 4934\n    4142, 1686, 1794, 416, 2556, 1902, 1953, 1803, 7559, 3773, 2785, 3774, 1159, 2316, 7560, 2867,  # 4950\n    4405, 1610, 1584, 3036, 2419, 2754, 443, 3269, 1163, 3136, 7561, 7562, 3926, 7563, 4143, 2499,  # 4966\n    3037, 4406, 3927, 3137, 2103, 1647, 3545, 2010, 1872, 4144, 7564, 4145, 431, 3438, 7565, 250,  # 4982\n    97, 81, 4146, 7566, 1648, 1850, 1558, 160, 848, 7567, 866, 740, 1694, 7568, 2201, 2830,  # 4998\n    3195, 4147, 4407, 3653, 1687, 950, 2472, 426, 469, 3196, 3654, 3655, 3928, 7569, 7570, 1188,  # 5014\n    424, 1995, 861, 3546, 4148, 3775, 2202, 2685, 168, 1235, 3547, 4149, 7571, 2086, 1674, 4408,  # 5030\n    3337, 3270, 220, 2557, 1009, 7572, 3776, 670, 2992, 332, 1208, 717, 7573, 7574, 3548, 2447,  # 5046\n    3929, 3338, 7575, 513, 7576, 1209, 2868, 3339, 3138, 4409, 1080, 7577, 7578, 7579, 7580, 2527,  # 5062\n    3656, 3549, 815, 1587, 3930, 3931, 7581, 3550, 3439, 3777, 1254, 4410, 1328, 3038, 1390, 3932,  # 5078\n    1741, 3933, 3778, 3934, 7582, 236, 3779, 2448, 3271, 7583, 7584, 3657, 3780, 1273, 3781, 4411,  # 5094\n    7585, 308, 7586, 4412, 245, 4413, 1851, 2473, 1307, 2575, 430, 715, 2136, 2449, 7587, 270,  # 5110\n    199, 2869, 3935, 7588, 3551, 2718, 1753, 761, 1754, 725, 1661, 1840, 4414, 3440, 3658, 7589,  # 5126\n    7590, 587, 14, 3272, 227, 2598, 326, 480, 2265, 943, 2755, 3552, 291, 650, 1883, 7591,  # 5142\n    1702, 1226, 102, 1547, 62, 3441, 904, 4415, 3442, 1164, 4150, 7592, 7593, 1224, 1548, 2756,  # 5158\n    391, 498, 1493, 7594, 1386, 1419, 7595, 2055, 1177, 4416, 813, 880, 1081, 2363, 566, 1145,  # 5174\n    4417, 2286, 1001, 1035, 2558, 2599, 2238, 394, 1286, 7596, 7597, 2068, 7598, 86, 1494, 1730,  # 5190\n    3936, 491, 1588, 745, 897, 2948, 843, 3340, 3937, 2757, 2870, 3273, 1768, 998, 2217, 2069,  # 5206\n    397, 1826, 1195, 1969, 3659, 2993, 3341, 284, 7599, 3782, 2500, 2137, 2119, 1903, 7600, 3938,  # 5222\n    2150, 3939, 4151, 1036, 3443, 1904, 114, 2559, 4152, 209, 1527, 7601, 7602, 2949, 2831, 2625,  # 5238\n    2385, 2719, 3139, 812, 2560, 7603, 3274, 7604, 1559, 737, 1884, 3660, 1210, 885, 28, 2686,  # 5254\n    3553, 3783, 7605, 4153, 1004, 1779, 4418, 7606, 346, 1981, 2218, 2687, 4419, 3784, 1742, 797,  # 5270\n    1642, 3940, 1933, 1072, 1384, 2151, 896, 3941, 3275, 3661, 3197, 2871, 3554, 7607, 2561, 1958,  # 5286\n    4420, 2450, 1785, 7608, 7609, 7610, 3942, 4154, 1005, 1308, 3662, 4155, 2720, 4421, 4422, 1528,  # 5302\n    2600, 161, 1178, 4156, 1982, 987, 4423, 1101, 4157, 631, 3943, 1157, 3198, 2420, 1343, 1241,  # 5318\n    1016, 2239, 2562, 372, 877, 2339, 2501, 1160, 555, 1934, 911, 3944, 7611, 466, 1170, 169,  # 5334\n    1051, 2907, 2688, 3663, 2474, 2994, 1182, 2011, 2563, 1251, 2626, 7612, 992, 2340, 3444, 1540,  # 5350\n    2721, 1201, 2070, 2401, 1996, 2475, 7613, 4424, 528, 1922, 2188, 1503, 1873, 1570, 2364, 3342,  # 5366\n    3276, 7614, 557, 1073, 7615, 1827, 3445, 2087, 2266, 3140, 3039, 3084, 767, 3085, 2786, 4425,  # 5382\n    1006, 4158, 4426, 2341, 1267, 2176, 3664, 3199, 778, 3945, 3200, 2722, 1597, 2657, 7616, 4427,  # 5398\n    7617, 3446, 7618, 7619, 7620, 3277, 2689, 1433, 3278, 131, 95, 1504, 3946, 723, 4159, 3141,  # 5414\n    1841, 3555, 2758, 2189, 3947, 2027, 2104, 3665, 7621, 2995, 3948, 1218, 7622, 3343, 3201, 3949,  # 5430\n    4160, 2576, 248, 1634, 3785, 912, 7623, 2832, 3666, 3040, 3786, 654, 53, 7624, 2996, 7625,  # 5446\n    1688, 4428, 777, 3447, 1032, 3950, 1425, 7626, 191, 820, 2120, 2833, 971, 4429, 931, 3202,  # 5462\n    135, 664, 783, 3787, 1997, 772, 2908, 1935, 3951, 3788, 4430, 2909, 3203, 282, 2723, 640,  # 5478\n    1372, 3448, 1127, 922, 325, 3344, 7627, 7628, 711, 2044, 7629, 7630, 3952, 2219, 2787, 1936,  # 5494\n    3953, 3345, 2220, 2251, 3789, 2300, 7631, 4431, 3790, 1258, 3279, 3954, 3204, 2138, 2950, 3955,  # 5510\n    3956, 7632, 2221, 258, 3205, 4432, 101, 1227, 7633, 3280, 1755, 7634, 1391, 3281, 7635, 2910,  # 5526\n    2056, 893, 7636, 7637, 7638, 1402, 4161, 2342, 7639, 7640, 3206, 3556, 7641, 7642, 878, 1325,  # 5542\n    1780, 2788, 4433, 259, 1385, 2577, 744, 1183, 2267, 4434, 7643, 3957, 2502, 7644, 684, 1024,  # 5558\n    4162, 7645, 472, 3557, 3449, 1165, 3282, 3958, 3959, 322, 2152, 881, 455, 1695, 1152, 1340,  # 5574\n    660, 554, 2153, 4435, 1058, 4436, 4163, 830, 1065, 3346, 3960, 4437, 1923, 7646, 1703, 1918,  # 5590\n    7647, 932, 2268, 122, 7648, 4438, 947, 677, 7649, 3791, 2627, 297, 1905, 1924, 2269, 4439,  # 5606\n    2317, 3283, 7650, 7651, 4164, 7652, 4165, 84, 4166, 112, 989, 7653, 547, 1059, 3961, 701,  # 5622\n    3558, 1019, 7654, 4167, 7655, 3450, 942, 639, 457, 2301, 2451, 993, 2951, 407, 851, 494,  # 5638\n    4440, 3347, 927, 7656, 1237, 7657, 2421, 3348, 573, 4168, 680, 921, 2911, 1279, 1874, 285,  # 5654\n    790, 1448, 1983, 719, 2167, 7658, 7659, 4441, 3962, 3963, 1649, 7660, 1541, 563, 7661, 1077,  # 5670\n    7662, 3349, 3041, 3451, 511, 2997, 3964, 3965, 3667, 3966, 1268, 2564, 3350, 3207, 4442, 4443,  # 5686\n    7663, 535, 1048, 1276, 1189, 2912, 2028, 3142, 1438, 1373, 2834, 2952, 1134, 2012, 7664, 4169,  # 5702\n    1238, 2578, 3086, 1259, 7665, 700, 7666, 2953, 3143, 3668, 4170, 7667, 4171, 1146, 1875, 1906,  # 5718\n    4444, 2601, 3967, 781, 2422, 132, 1589, 203, 147, 273, 2789, 2402, 898, 1786, 2154, 3968,  # 5734\n    3969, 7668, 3792, 2790, 7669, 7670, 4445, 4446, 7671, 3208, 7672, 1635, 3793, 965, 7673, 1804,  # 5750\n    2690, 1516, 3559, 1121, 1082, 1329, 3284, 3970, 1449, 3794, 65, 1128, 2835, 2913, 2759, 1590,  # 5766\n    3795, 7674, 7675, 12, 2658, 45, 976, 2579, 3144, 4447, 517, 2528, 1013, 1037, 3209, 7676,  # 5782\n    3796, 2836, 7677, 3797, 7678, 3452, 7679, 2602, 614, 1998, 2318, 3798, 3087, 2724, 2628, 7680,  # 5798\n    2580, 4172, 599, 1269, 7681, 1810, 3669, 7682, 2691, 3088, 759, 1060, 489, 1805, 3351, 3285,  # 5814\n    1358, 7683, 7684, 2386, 1387, 1215, 2629, 2252, 490, 7685, 7686, 4173, 1759, 2387, 2343, 7687,  # 5830\n    4448, 3799, 1907, 3971, 2630, 1806, 3210, 4449, 3453, 3286, 2760, 2344, 874, 7688, 7689, 3454,  # 5846\n    3670, 1858, 91, 2914, 3671, 3042, 3800, 4450, 7690, 3145, 3972, 2659, 7691, 3455, 1202, 1403,  # 5862\n    3801, 2954, 2529, 1517, 2503, 4451, 3456, 2504, 7692, 4452, 7693, 2692, 1885, 1495, 1731, 3973,  # 5878\n    2365, 4453, 7694, 2029, 7695, 7696, 3974, 2693, 1216, 237, 2581, 4174, 2319, 3975, 3802, 4454,  # 5894\n    4455, 2694, 3560, 3457, 445, 4456, 7697, 7698, 7699, 7700, 2761, 61, 3976, 3672, 1822, 3977,  # 5910\n    7701, 687, 2045, 935, 925, 405, 2660, 703, 1096, 1859, 2725, 4457, 3978, 1876, 1367, 2695,  # 5926\n    3352, 918, 2105, 1781, 2476, 334, 3287, 1611, 1093, 4458, 564, 3146, 3458, 3673, 3353, 945,  # 5942\n    2631, 2057, 4459, 7702, 1925, 872, 4175, 7703, 3459, 2696, 3089, 349, 4176, 3674, 3979, 4460,  # 5958\n    3803, 4177, 3675, 2155, 3980, 4461, 4462, 4178, 4463, 2403, 2046, 782, 3981, 400, 251, 4179,  # 5974\n    1624, 7704, 7705, 277, 3676, 299, 1265, 476, 1191, 3804, 2121, 4180, 4181, 1109, 205, 7706,  # 5990\n    2582, 1000, 2156, 3561, 1860, 7707, 7708, 7709, 4464, 7710, 4465, 2565, 107, 2477, 2157, 3982,  # 6006\n    3460, 3147, 7711, 1533, 541, 1301, 158, 753, 4182, 2872, 3562, 7712, 1696, 370, 1088, 4183,  # 6022\n    4466, 3563, 579, 327, 440, 162, 2240, 269, 1937, 1374, 3461, 968, 3043, 56, 1396, 3090,  # 6038\n    2106, 3288, 3354, 7713, 1926, 2158, 4467, 2998, 7714, 3564, 7715, 7716, 3677, 4468, 2478, 7717,  # 6054\n    2791, 7718, 1650, 4469, 7719, 2603, 7720, 7721, 3983, 2661, 3355, 1149, 3356, 3984, 3805, 3985,  # 6070\n    7722, 1076, 49, 7723, 951, 3211, 3289, 3290, 450, 2837, 920, 7724, 1811, 2792, 2366, 4184,  # 6086\n    1908, 1138, 2367, 3806, 3462, 7725, 3212, 4470, 1909, 1147, 1518, 2423, 4471, 3807, 7726, 4472,  # 6102\n    2388, 2604, 260, 1795, 3213, 7727, 7728, 3808, 3291, 708, 7729, 3565, 1704, 7730, 3566, 1351,  # 6118\n    1618, 3357, 2999, 1886, 944, 4185, 3358, 4186, 3044, 3359, 4187, 7731, 3678, 422, 413, 1714,  # 6134\n    3292, 500, 2058, 2345, 4188, 2479, 7732, 1344, 1910, 954, 7733, 1668, 7734, 7735, 3986, 2404,  # 6150\n    4189, 3567, 3809, 4190, 7736, 2302, 1318, 2505, 3091, 133, 3092, 2873, 4473, 629, 31, 2838,  # 6166\n    2697, 3810, 4474, 850, 949, 4475, 3987, 2955, 1732, 2088, 4191, 1496, 1852, 7737, 3988, 620,  # 6182\n    3214, 981, 1242, 3679, 3360, 1619, 3680, 1643, 3293, 2139, 2452, 1970, 1719, 3463, 2168, 7738,  # 6198\n    3215, 7739, 7740, 3361, 1828, 7741, 1277, 4476, 1565, 2047, 7742, 1636, 3568, 3093, 7743, 869,  # 6214\n    2839, 655, 3811, 3812, 3094, 3989, 3000, 3813, 1310, 3569, 4477, 7744, 7745, 7746, 1733, 558,  # 6230\n    4478, 3681, 335, 1549, 3045, 1756, 4192, 3682, 1945, 3464, 1829, 1291, 1192, 470, 2726, 2107,  # 6246\n    2793, 913, 1054, 3990, 7747, 1027, 7748, 3046, 3991, 4479, 982, 2662, 3362, 3148, 3465, 3216,  # 6262\n    3217, 1946, 2794, 7749, 571, 4480, 7750, 1830, 7751, 3570, 2583, 1523, 2424, 7752, 2089, 984,  # 6278\n    4481, 3683, 1959, 7753, 3684, 852, 923, 2795, 3466, 3685, 969, 1519, 999, 2048, 2320, 1705,  # 6294\n    7754, 3095, 615, 1662, 151, 597, 3992, 2405, 2321, 1049, 275, 4482, 3686, 4193, 568, 3687,  # 6310\n    3571, 2480, 4194, 3688, 7755, 2425, 2270, 409, 3218, 7756, 1566, 2874, 3467, 1002, 769, 2840,  # 6326\n    194, 2090, 3149, 3689, 2222, 3294, 4195, 628, 1505, 7757, 7758, 1763, 2177, 3001, 3993, 521,  # 6342\n    1161, 2584, 1787, 2203, 2406, 4483, 3994, 1625, 4196, 4197, 412, 42, 3096, 464, 7759, 2632,  # 6358\n    4484, 3363, 1760, 1571, 2875, 3468, 2530, 1219, 2204, 3814, 2633, 2140, 2368, 4485, 4486, 3295,  # 6374\n    1651, 3364, 3572, 7760, 7761, 3573, 2481, 3469, 7762, 3690, 7763, 7764, 2271, 2091, 460, 7765,  # 6390\n    4487, 7766, 3002, 962, 588, 3574, 289, 3219, 2634, 1116, 52, 7767, 3047, 1796, 7768, 7769,  # 6406\n    7770, 1467, 7771, 1598, 1143, 3691, 4198, 1984, 1734, 1067, 4488, 1280, 3365, 465, 4489, 1572,  # 6422\n    510, 7772, 1927, 2241, 1812, 1644, 3575, 7773, 4490, 3692, 7774, 7775, 2663, 1573, 1534, 7776,  # 6438\n    7777, 4199, 536, 1807, 1761, 3470, 3815, 3150, 2635, 7778, 7779, 7780, 4491, 3471, 2915, 1911,  # 6454\n    2796, 7781, 3296, 1122, 377, 3220, 7782, 360, 7783, 7784, 4200, 1529, 551, 7785, 2059, 3693,  # 6470\n    1769, 2426, 7786, 2916, 4201, 3297, 3097, 2322, 2108, 2030, 4492, 1404, 136, 1468, 1479, 672,  # 6486\n    1171, 3221, 2303, 271, 3151, 7787, 2762, 7788, 2049, 678, 2727, 865, 1947, 4493, 7789, 2013,  # 6502\n    3995, 2956, 7790, 2728, 2223, 1397, 3048, 3694, 4494, 4495, 1735, 2917, 3366, 3576, 7791, 3816,  # 6518\n    509, 2841, 2453, 2876, 3817, 7792, 7793, 3152, 3153, 4496, 4202, 2531, 4497, 2304, 1166, 1010,  # 6534\n    552, 681, 1887, 7794, 7795, 2957, 2958, 3996, 1287, 1596, 1861, 3154, 358, 453, 736, 175,  # 6550\n    478, 1117, 905, 1167, 1097, 7796, 1853, 1530, 7797, 1706, 7798, 2178, 3472, 2287, 3695, 3473,  # 6566\n    3577, 4203, 2092, 4204, 7799, 3367, 1193, 2482, 4205, 1458, 2190, 2205, 1862, 1888, 1421, 3298,  # 6582\n    2918, 3049, 2179, 3474, 595, 2122, 7800, 3997, 7801, 7802, 4206, 1707, 2636, 223, 3696, 1359,  # 6598\n    751, 3098, 183, 3475, 7803, 2797, 3003, 419, 2369, 633, 704, 3818, 2389, 241, 7804, 7805,  # 6614\n    7806, 838, 3004, 3697, 2272, 2763, 2454, 3819, 1938, 2050, 3998, 1309, 3099, 2242, 1181, 7807,  # 6630\n    1136, 2206, 3820, 2370, 1446, 4207, 2305, 4498, 7808, 7809, 4208, 1055, 2605, 484, 3698, 7810,  # 6646\n    3999, 625, 4209, 2273, 3368, 1499, 4210, 4000, 7811, 4001, 4211, 3222, 2274, 2275, 3476, 7812,  # 6662\n    7813, 2764, 808, 2606, 3699, 3369, 4002, 4212, 3100, 2532, 526, 3370, 3821, 4213, 955, 7814,  # 6678\n    1620, 4214, 2637, 2427, 7815, 1429, 3700, 1669, 1831, 994, 928, 7816, 3578, 1260, 7817, 7818,  # 6694\n    7819, 1948, 2288, 741, 2919, 1626, 4215, 2729, 2455, 867, 1184, 362, 3371, 1392, 7820, 7821,  # 6710\n    4003, 4216, 1770, 1736, 3223, 2920, 4499, 4500, 1928, 2698, 1459, 1158, 7822, 3050, 3372, 2877,  # 6726\n    1292, 1929, 2506, 2842, 3701, 1985, 1187, 2071, 2014, 2607, 4217, 7823, 2566, 2507, 2169, 3702,  # 6742\n    2483, 3299, 7824, 3703, 4501, 7825, 7826, 666, 1003, 3005, 1022, 3579, 4218, 7827, 4502, 1813,  # 6758\n    2253, 574, 3822, 1603, 295, 1535, 705, 3823, 4219, 283, 858, 417, 7828, 7829, 3224, 4503,  # 6774\n    4504, 3051, 1220, 1889, 1046, 2276, 2456, 4004, 1393, 1599, 689, 2567, 388, 4220, 7830, 2484,  # 6790\n    802, 7831, 2798, 3824, 2060, 1405, 2254, 7832, 4505, 3825, 2109, 1052, 1345, 3225, 1585, 7833,  # 6806\n    809, 7834, 7835, 7836, 575, 2730, 3477, 956, 1552, 1469, 1144, 2323, 7837, 2324, 1560, 2457,  # 6822\n    3580, 3226, 4005, 616, 2207, 3155, 2180, 2289, 7838, 1832, 7839, 3478, 4506, 7840, 1319, 3704,  # 6838\n    3705, 1211, 3581, 1023, 3227, 1293, 2799, 7841, 7842, 7843, 3826, 607, 2306, 3827, 762, 2878,  # 6854\n    1439, 4221, 1360, 7844, 1485, 3052, 7845, 4507, 1038, 4222, 1450, 2061, 2638, 4223, 1379, 4508,  # 6870\n    2585, 7846, 7847, 4224, 1352, 1414, 2325, 2921, 1172, 7848, 7849, 3828, 3829, 7850, 1797, 1451,  # 6886\n    7851, 7852, 7853, 7854, 2922, 4006, 4007, 2485, 2346, 411, 4008, 4009, 3582, 3300, 3101, 4509,  # 6902\n    1561, 2664, 1452, 4010, 1375, 7855, 7856, 47, 2959, 316, 7857, 1406, 1591, 2923, 3156, 7858,  # 6918\n    1025, 2141, 3102, 3157, 354, 2731, 884, 2224, 4225, 2407, 508, 3706, 726, 3583, 996, 2428,  # 6934\n    3584, 729, 7859, 392, 2191, 1453, 4011, 4510, 3707, 7860, 7861, 2458, 3585, 2608, 1675, 2800,  # 6950\n    919, 2347, 2960, 2348, 1270, 4511, 4012, 73, 7862, 7863, 647, 7864, 3228, 2843, 2255, 1550,  # 6966\n    1346, 3006, 7865, 1332, 883, 3479, 7866, 7867, 7868, 7869, 3301, 2765, 7870, 1212, 831, 1347,  # 6982\n    4226, 4512, 2326, 3830, 1863, 3053, 720, 3831, 4513, 4514, 3832, 7871, 4227, 7872, 7873, 4515,  # 6998\n    7874, 7875, 1798, 4516, 3708, 2609, 4517, 3586, 1645, 2371, 7876, 7877, 2924, 669, 2208, 2665,  # 7014\n    2429, 7878, 2879, 7879, 7880, 1028, 3229, 7881, 4228, 2408, 7882, 2256, 1353, 7883, 7884, 4518,  # 7030\n    3158, 518, 7885, 4013, 7886, 4229, 1960, 7887, 2142, 4230, 7888, 7889, 3007, 2349, 2350, 3833,  # 7046\n    516, 1833, 1454, 4014, 2699, 4231, 4519, 2225, 2610, 1971, 1129, 3587, 7890, 2766, 7891, 2961,  # 7062\n    1422, 577, 1470, 3008, 1524, 3373, 7892, 7893, 432, 4232, 3054, 3480, 7894, 2586, 1455, 2508,  # 7078\n    2226, 1972, 1175, 7895, 1020, 2732, 4015, 3481, 4520, 7896, 2733, 7897, 1743, 1361, 3055, 3482,  # 7094\n    2639, 4016, 4233, 4521, 2290, 895, 924, 4234, 2170, 331, 2243, 3056, 166, 1627, 3057, 1098,  # 7110\n    7898, 1232, 2880, 2227, 3374, 4522, 657, 403, 1196, 2372, 542, 3709, 3375, 1600, 4235, 3483,  # 7126\n    7899, 4523, 2767, 3230, 576, 530, 1362, 7900, 4524, 2533, 2666, 3710, 4017, 7901, 842, 3834,  # 7142\n    7902, 2801, 2031, 1014, 4018, 213, 2700, 3376, 665, 621, 4236, 7903, 3711, 2925, 2430, 7904,  # 7158\n    2431, 3302, 3588, 3377, 7905, 4237, 2534, 4238, 4525, 3589, 1682, 4239, 3484, 1380, 7906, 724,  # 7174\n    2277, 600, 1670, 7907, 1337, 1233, 4526, 3103, 2244, 7908, 1621, 4527, 7909, 651, 4240, 7910,  # 7190\n    1612, 4241, 2611, 7911, 2844, 7912, 2734, 2307, 3058, 7913, 716, 2459, 3059, 174, 1255, 2701,  # 7206\n    4019, 3590, 548, 1320, 1398, 728, 4020, 1574, 7914, 1890, 1197, 3060, 4021, 7915, 3061, 3062,  # 7222\n    3712, 3591, 3713, 747, 7916, 635, 4242, 4528, 7917, 7918, 7919, 4243, 7920, 7921, 4529, 7922,  # 7238\n    3378, 4530, 2432, 451, 7923, 3714, 2535, 2072, 4244, 2735, 4245, 4022, 7924, 1764, 4531, 7925,  # 7254\n    4246, 350, 7926, 2278, 2390, 2486, 7927, 4247, 4023, 2245, 1434, 4024, 488, 4532, 458, 4248,  # 7270\n    4025, 3715, 771, 1330, 2391, 3835, 2568, 3159, 2159, 2409, 1553, 2667, 3160, 4249, 7928, 2487,  # 7286\n    2881, 2612, 1720, 2702, 4250, 3379, 4533, 7929, 2536, 4251, 7930, 3231, 4252, 2768, 7931, 2015,  # 7302\n    2736, 7932, 1155, 1017, 3716, 3836, 7933, 3303, 2308, 201, 1864, 4253, 1430, 7934, 4026, 7935,  # 7318\n    7936, 7937, 7938, 7939, 4254, 1604, 7940, 414, 1865, 371, 2587, 4534, 4535, 3485, 2016, 3104,  # 7334\n    4536, 1708, 960, 4255, 887, 389, 2171, 1536, 1663, 1721, 7941, 2228, 4027, 2351, 2926, 1580,  # 7350\n    7942, 7943, 7944, 1744, 7945, 2537, 4537, 4538, 7946, 4539, 7947, 2073, 7948, 7949, 3592, 3380,  # 7366\n    2882, 4256, 7950, 4257, 2640, 3381, 2802, 673, 2703, 2460, 709, 3486, 4028, 3593, 4258, 7951,  # 7382\n    1148, 502, 634, 7952, 7953, 1204, 4540, 3594, 1575, 4541, 2613, 3717, 7954, 3718, 3105, 948,  # 7398\n    3232, 121, 1745, 3837, 1110, 7955, 4259, 3063, 2509, 3009, 4029, 3719, 1151, 1771, 3838, 1488,  # 7414\n    4030, 1986, 7956, 2433, 3487, 7957, 7958, 2093, 7959, 4260, 3839, 1213, 1407, 2803, 531, 2737,  # 7430\n    2538, 3233, 1011, 1537, 7960, 2769, 4261, 3106, 1061, 7961, 3720, 3721, 1866, 2883, 7962, 2017,  # 7446\n    120, 4262, 4263, 2062, 3595, 3234, 2309, 3840, 2668, 3382, 1954, 4542, 7963, 7964, 3488, 1047,  # 7462\n    2704, 1266, 7965, 1368, 4543, 2845, 649, 3383, 3841, 2539, 2738, 1102, 2846, 2669, 7966, 7967,  # 7478\n    1999, 7968, 1111, 3596, 2962, 7969, 2488, 3842, 3597, 2804, 1854, 3384, 3722, 7970, 7971, 3385,  # 7494\n    2410, 2884, 3304, 3235, 3598, 7972, 2569, 7973, 3599, 2805, 4031, 1460, 856, 7974, 3600, 7975,  # 7510\n    2885, 2963, 7976, 2886, 3843, 7977, 4264, 632, 2510, 875, 3844, 1697, 3845, 2291, 7978, 7979,  # 7526\n    4544, 3010, 1239, 580, 4545, 4265, 7980, 914, 936, 2074, 1190, 4032, 1039, 2123, 7981, 7982,  # 7542\n    7983, 3386, 1473, 7984, 1354, 4266, 3846, 7985, 2172, 3064, 4033, 915, 3305, 4267, 4268, 3306,  # 7558\n    1605, 1834, 7986, 2739, 398, 3601, 4269, 3847, 4034, 328, 1912, 2847, 4035, 3848, 1331, 4270,  # 7574\n    3011, 937, 4271, 7987, 3602, 4036, 4037, 3387, 2160, 4546, 3388, 524, 742, 538, 3065, 1012,  # 7590\n    7988, 7989, 3849, 2461, 7990, 658, 1103, 225, 3850, 7991, 7992, 4547, 7993, 4548, 7994, 3236,  # 7606\n    1243, 7995, 4038, 963, 2246, 4549, 7996, 2705, 3603, 3161, 7997, 7998, 2588, 2327, 7999, 4550,  # 7622\n    8000, 8001, 8002, 3489, 3307, 957, 3389, 2540, 2032, 1930, 2927, 2462, 870, 2018, 3604, 1746,  # 7638\n    2770, 2771, 2434, 2463, 8003, 3851, 8004, 3723, 3107, 3724, 3490, 3390, 3725, 8005, 1179, 3066,  # 7654\n    8006, 3162, 2373, 4272, 3726, 2541, 3163, 3108, 2740, 4039, 8007, 3391, 1556, 2542, 2292, 977,  # 7670\n    2887, 2033, 4040, 1205, 3392, 8008, 1765, 3393, 3164, 2124, 1271, 1689, 714, 4551, 3491, 8009,  # 7686\n    2328, 3852, 533, 4273, 3605, 2181, 617, 8010, 2464, 3308, 3492, 2310, 8011, 8012, 3165, 8013,  # 7702\n    8014, 3853, 1987, 618, 427, 2641, 3493, 3394, 8015, 8016, 1244, 1690, 8017, 2806, 4274, 4552,  # 7718\n    8018, 3494, 8019, 8020, 2279, 1576, 473, 3606, 4275, 3395, 972, 8021, 3607, 8022, 3067, 8023,  # 7734\n    8024, 4553, 4554, 8025, 3727, 4041, 4042, 8026, 153, 4555, 356, 8027, 1891, 2888, 4276, 2143,  # 7750\n    408, 803, 2352, 8028, 3854, 8029, 4277, 1646, 2570, 2511, 4556, 4557, 3855, 8030, 3856, 4278,  # 7766\n    8031, 2411, 3396, 752, 8032, 8033, 1961, 2964, 8034, 746, 3012, 2465, 8035, 4279, 3728, 698,  # 7782\n    4558, 1892, 4280, 3608, 2543, 4559, 3609, 3857, 8036, 3166, 3397, 8037, 1823, 1302, 4043, 2706,  # 7798\n    3858, 1973, 4281, 8038, 4282, 3167, 823, 1303, 1288, 1236, 2848, 3495, 4044, 3398, 774, 3859,  # 7814\n    8039, 1581, 4560, 1304, 2849, 3860, 4561, 8040, 2435, 2161, 1083, 3237, 4283, 4045, 4284, 344,  # 7830\n    1173, 288, 2311, 454, 1683, 8041, 8042, 1461, 4562, 4046, 2589, 8043, 8044, 4563, 985, 894,  # 7846\n    8045, 3399, 3168, 8046, 1913, 2928, 3729, 1988, 8047, 2110, 1974, 8048, 4047, 8049, 2571, 1194,  # 7862\n    425, 8050, 4564, 3169, 1245, 3730, 4285, 8051, 8052, 2850, 8053, 636, 4565, 1855, 3861, 760,  # 7878\n    1799, 8054, 4286, 2209, 1508, 4566, 4048, 1893, 1684, 2293, 8055, 8056, 8057, 4287, 4288, 2210,  # 7894\n    479, 8058, 8059, 832, 8060, 4049, 2489, 8061, 2965, 2490, 3731, 990, 3109, 627, 1814, 2642,  # 7910\n    4289, 1582, 4290, 2125, 2111, 3496, 4567, 8062, 799, 4291, 3170, 8063, 4568, 2112, 1737, 3013,  # 7926\n    1018, 543, 754, 4292, 3309, 1676, 4569, 4570, 4050, 8064, 1489, 8065, 3497, 8066, 2614, 2889,  # 7942\n    4051, 8067, 8068, 2966, 8069, 8070, 8071, 8072, 3171, 4571, 4572, 2182, 1722, 8073, 3238, 3239,  # 7958\n    1842, 3610, 1715, 481, 365, 1975, 1856, 8074, 8075, 1962, 2491, 4573, 8076, 2126, 3611, 3240,  # 7974\n    433, 1894, 2063, 2075, 8077, 602, 2741, 8078, 8079, 8080, 8081, 8082, 3014, 1628, 3400, 8083,  # 7990\n    3172, 4574, 4052, 2890, 4575, 2512, 8084, 2544, 2772, 8085, 8086, 8087, 3310, 4576, 2891, 8088,  # 8006\n    4577, 8089, 2851, 4578, 4579, 1221, 2967, 4053, 2513, 8090, 8091, 8092, 1867, 1989, 8093, 8094,  # 8022\n    8095, 1895, 8096, 8097, 4580, 1896, 4054, 318, 8098, 2094, 4055, 4293, 8099, 8100, 485, 8101,  # 8038\n    938, 3862, 553, 2670, 116, 8102, 3863, 3612, 8103, 3498, 2671, 2773, 3401, 3311, 2807, 8104,  # 8054\n    3613, 2929, 4056, 1747, 2930, 2968, 8105, 8106, 207, 8107, 8108, 2672, 4581, 2514, 8109, 3015,  # 8070\n    890, 3614, 3864, 8110, 1877, 3732, 3402, 8111, 2183, 2353, 3403, 1652, 8112, 8113, 8114, 941,  # 8086\n    2294, 208, 3499, 4057, 2019, 330, 4294, 3865, 2892, 2492, 3733, 4295, 8115, 8116, 8117, 8118,  # 8102\n)\n# fmt: on\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/euctwprober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is mozilla.org code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .chardistribution import EUCTWDistributionAnalysis\nfrom .codingstatemachine import CodingStateMachine\nfrom .mbcharsetprober import MultiByteCharSetProber\nfrom .mbcssm import EUCTW_SM_MODEL\n\n\nclass EUCTWProber(MultiByteCharSetProber):\n    def __init__(self):\n        super().__init__()\n        self.coding_sm = CodingStateMachine(EUCTW_SM_MODEL)\n        self.distribution_analyzer = EUCTWDistributionAnalysis()\n        self.reset()\n\n    @property\n    def charset_name(self):\n        return \"EUC-TW\"\n\n    @property\n    def language(self):\n        return \"Taiwan\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/gb2312freq.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Communicator client code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\n# GB2312 most frequently used character table\n#\n# Char to FreqOrder table , from hz6763\n\n# 512  --> 0.79  -- 0.79\n# 1024 --> 0.92  -- 0.13\n# 2048 --> 0.98  -- 0.06\n# 6768 --> 1.00  -- 0.02\n#\n# Ideal Distribution Ratio = 0.79135/(1-0.79135) = 3.79\n# Random Distribution Ration = 512 / (3755 - 512) = 0.157\n#\n# Typical Distribution Ratio about 25% of Ideal one, still much higher that RDR\n\nGB2312_TYPICAL_DISTRIBUTION_RATIO = 0.9\n\nGB2312_TABLE_SIZE = 3760\n\n# fmt: off\nGB2312_CHAR_TO_FREQ_ORDER = (\n1671, 749,1443,2364,3924,3807,2330,3921,1704,3463,2691,1511,1515, 572,3191,2205,\n2361, 224,2558, 479,1711, 963,3162, 440,4060,1905,2966,2947,3580,2647,3961,3842,\n2204, 869,4207, 970,2678,5626,2944,2956,1479,4048, 514,3595, 588,1346,2820,3409,\n 249,4088,1746,1873,2047,1774, 581,1813, 358,1174,3590,1014,1561,4844,2245, 670,\n1636,3112, 889,1286, 953, 556,2327,3060,1290,3141, 613, 185,3477,1367, 850,3820,\n1715,2428,2642,2303,2732,3041,2562,2648,3566,3946,1349, 388,3098,2091,1360,3585,\n 152,1687,1539, 738,1559,  59,1232,2925,2267,1388,1249,1741,1679,2960, 151,1566,\n1125,1352,4271, 924,4296, 385,3166,4459, 310,1245,2850,  70,3285,2729,3534,3575,\n2398,3298,3466,1960,2265, 217,3647, 864,1909,2084,4401,2773,1010,3269,5152, 853,\n3051,3121,1244,4251,1895, 364,1499,1540,2313,1180,3655,2268, 562, 715,2417,3061,\n 544, 336,3768,2380,1752,4075, 950, 280,2425,4382, 183,2759,3272, 333,4297,2155,\n1688,2356,1444,1039,4540, 736,1177,3349,2443,2368,2144,2225, 565, 196,1482,3406,\n 927,1335,4147, 692, 878,1311,1653,3911,3622,1378,4200,1840,2969,3149,2126,1816,\n2534,1546,2393,2760, 737,2494,  13, 447, 245,2747,  38,2765,2129,2589,1079, 606,\n 360, 471,3755,2890, 404, 848, 699,1785,1236, 370,2221,1023,3746,2074,2026,2023,\n2388,1581,2119, 812,1141,3091,2536,1519, 804,2053, 406,1596,1090, 784, 548,4414,\n1806,2264,2936,1100, 343,4114,5096, 622,3358, 743,3668,1510,1626,5020,3567,2513,\n3195,4115,5627,2489,2991,  24,2065,2697,1087,2719,  48,1634, 315,  68, 985,2052,\n 198,2239,1347,1107,1439, 597,2366,2172, 871,3307, 919,2487,2790,1867, 236,2570,\n1413,3794, 906,3365,3381,1701,1982,1818,1524,2924,1205, 616,2586,2072,2004, 575,\n 253,3099,  32,1365,1182, 197,1714,2454,1201, 554,3388,3224,2748, 756,2587, 250,\n2567,1507,1517,3529,1922,2761,2337,3416,1961,1677,2452,2238,3153, 615, 911,1506,\n1474,2495,1265,1906,2749,3756,3280,2161, 898,2714,1759,3450,2243,2444, 563,  26,\n3286,2266,3769,3344,2707,3677, 611,1402, 531,1028,2871,4548,1375, 261,2948, 835,\n1190,4134, 353, 840,2684,1900,3082,1435,2109,1207,1674, 329,1872,2781,4055,2686,\n2104, 608,3318,2423,2957,2768,1108,3739,3512,3271,3985,2203,1771,3520,1418,2054,\n1681,1153, 225,1627,2929, 162,2050,2511,3687,1954, 124,1859,2431,1684,3032,2894,\n 585,4805,3969,2869,2704,2088,2032,2095,3656,2635,4362,2209, 256, 518,2042,2105,\n3777,3657, 643,2298,1148,1779, 190, 989,3544, 414,  11,2135,2063,2979,1471, 403,\n3678, 126, 770,1563, 671,2499,3216,2877, 600,1179, 307,2805,4937,1268,1297,2694,\n 252,4032,1448,1494,1331,1394, 127,2256, 222,1647,1035,1481,3056,1915,1048, 873,\n3651, 210,  33,1608,2516, 200,1520, 415, 102,   0,3389,1287, 817,  91,3299,2940,\n 836,1814, 549,2197,1396,1669,2987,3582,2297,2848,4528,1070, 687,  20,1819, 121,\n1552,1364,1461,1968,2617,3540,2824,2083, 177, 948,4938,2291, 110,4549,2066, 648,\n3359,1755,2110,2114,4642,4845,1693,3937,3308,1257,1869,2123, 208,1804,3159,2992,\n2531,2549,3361,2418,1350,2347,2800,2568,1291,2036,2680,  72, 842,1990, 212,1233,\n1154,1586,  75,2027,3410,4900,1823,1337,2710,2676, 728,2810,1522,3026,4995, 157,\n 755,1050,4022, 710, 785,1936,2194,2085,1406,2777,2400, 150,1250,4049,1206, 807,\n1910, 534, 529,3309,1721,1660, 274,  39,2827, 661,2670,1578, 925,3248,3815,1094,\n4278,4901,4252,  41,1150,3747,2572,2227,4501,3658,4902,3813,3357,3617,2884,2258,\n 887, 538,4187,3199,1294,2439,3042,2329,2343,2497,1255, 107, 543,1527, 521,3478,\n3568, 194,5062,  15, 961,3870,1241,1192,2664,  66,5215,3260,2111,1295,1127,2152,\n3805,4135, 901,1164,1976, 398,1278, 530,1460, 748, 904,1054,1966,1426,  53,2909,\n 509, 523,2279,1534, 536,1019, 239,1685, 460,2353, 673,1065,2401,3600,4298,2272,\n1272,2363, 284,1753,3679,4064,1695,  81, 815,2677,2757,2731,1386, 859, 500,4221,\n2190,2566, 757,1006,2519,2068,1166,1455, 337,2654,3203,1863,1682,1914,3025,1252,\n1409,1366, 847, 714,2834,2038,3209, 964,2970,1901, 885,2553,1078,1756,3049, 301,\n1572,3326, 688,2130,1996,2429,1805,1648,2930,3421,2750,3652,3088, 262,1158,1254,\n 389,1641,1812, 526,1719, 923,2073,1073,1902, 468, 489,4625,1140, 857,2375,3070,\n3319,2863, 380, 116,1328,2693,1161,2244, 273,1212,1884,2769,3011,1775,1142, 461,\n3066,1200,2147,2212, 790, 702,2695,4222,1601,1058, 434,2338,5153,3640,  67,2360,\n4099,2502, 618,3472,1329, 416,1132, 830,2782,1807,2653,3211,3510,1662, 192,2124,\n 296,3979,1739,1611,3684,  23, 118, 324, 446,1239,1225, 293,2520,3814,3795,2535,\n3116,  17,1074, 467,2692,2201, 387,2922,  45,1326,3055,1645,3659,2817, 958, 243,\n1903,2320,1339,2825,1784,3289, 356, 576, 865,2315,2381,3377,3916,1088,3122,1713,\n1655, 935, 628,4689,1034,1327, 441, 800, 720, 894,1979,2183,1528,5289,2702,1071,\n4046,3572,2399,1571,3281,  79, 761,1103, 327, 134, 758,1899,1371,1615, 879, 442,\n 215,2605,2579, 173,2048,2485,1057,2975,3317,1097,2253,3801,4263,1403,1650,2946,\n 814,4968,3487,1548,2644,1567,1285,   2, 295,2636,  97, 946,3576, 832, 141,4257,\n3273, 760,3821,3521,3156,2607, 949,1024,1733,1516,1803,1920,2125,2283,2665,3180,\n1501,2064,3560,2171,1592, 803,3518,1416, 732,3897,4258,1363,1362,2458, 119,1427,\n 602,1525,2608,1605,1639,3175, 694,3064,  10, 465,  76,2000,4846,4208, 444,3781,\n1619,3353,2206,1273,3796, 740,2483, 320,1723,2377,3660,2619,1359,1137,1762,1724,\n2345,2842,1850,1862, 912, 821,1866, 612,2625,1735,2573,3369,1093, 844,  89, 937,\n 930,1424,3564,2413,2972,1004,3046,3019,2011, 711,3171,1452,4178, 428, 801,1943,\n 432, 445,2811, 206,4136,1472, 730, 349,  73, 397,2802,2547, 998,1637,1167, 789,\n 396,3217, 154,1218, 716,1120,1780,2819,4826,1931,3334,3762,2139,1215,2627, 552,\n3664,3628,3232,1405,2383,3111,1356,2652,3577,3320,3101,1703, 640,1045,1370,1246,\n4996, 371,1575,2436,1621,2210, 984,4033,1734,2638,  16,4529, 663,2755,3255,1451,\n3917,2257,1253,1955,2234,1263,2951, 214,1229, 617, 485, 359,1831,1969, 473,2310,\n 750,2058, 165,  80,2864,2419, 361,4344,2416,2479,1134, 796,3726,1266,2943, 860,\n2715, 938, 390,2734,1313,1384, 248, 202, 877,1064,2854, 522,3907, 279,1602, 297,\n2357, 395,3740, 137,2075, 944,4089,2584,1267,3802,  62,1533,2285, 178, 176, 780,\n2440, 201,3707, 590, 478,1560,4354,2117,1075,  30,  74,4643,4004,1635,1441,2745,\n 776,2596, 238,1077,1692,1912,2844, 605, 499,1742,3947, 241,3053, 980,1749, 936,\n2640,4511,2582, 515,1543,2162,5322,2892,2993, 890,2148,1924, 665,1827,3581,1032,\n 968,3163, 339,1044,1896, 270, 583,1791,1720,4367,1194,3488,3669,  43,2523,1657,\n 163,2167, 290,1209,1622,3378, 550, 634,2508,2510, 695,2634,2384,2512,1476,1414,\n 220,1469,2341,2138,2852,3183,2900,4939,2865,3502,1211,3680, 854,3227,1299,2976,\n3172, 186,2998,1459, 443,1067,3251,1495, 321,1932,3054, 909, 753,1410,1828, 436,\n2441,1119,1587,3164,2186,1258, 227, 231,1425,1890,3200,3942, 247, 959, 725,5254,\n2741, 577,2158,2079, 929, 120, 174, 838,2813, 591,1115, 417,2024,  40,3240,1536,\n1037, 291,4151,2354, 632,1298,2406,2500,3535,1825,1846,3451, 205,1171, 345,4238,\n  18,1163, 811, 685,2208,1217, 425,1312,1508,1175,4308,2552,1033, 587,1381,3059,\n2984,3482, 340,1316,4023,3972, 792,3176, 519, 777,4690, 918, 933,4130,2981,3741,\n  90,3360,2911,2200,5184,4550, 609,3079,2030, 272,3379,2736, 363,3881,1130,1447,\n 286, 779, 357,1169,3350,3137,1630,1220,2687,2391, 747,1277,3688,2618,2682,2601,\n1156,3196,5290,4034,3102,1689,3596,3128, 874, 219,2783, 798, 508,1843,2461, 269,\n1658,1776,1392,1913,2983,3287,2866,2159,2372, 829,4076,  46,4253,2873,1889,1894,\n 915,1834,1631,2181,2318, 298, 664,2818,3555,2735, 954,3228,3117, 527,3511,2173,\n 681,2712,3033,2247,2346,3467,1652, 155,2164,3382, 113,1994, 450, 899, 494, 994,\n1237,2958,1875,2336,1926,3727, 545,1577,1550, 633,3473, 204,1305,3072,2410,1956,\n2471, 707,2134, 841,2195,2196,2663,3843,1026,4940, 990,3252,4997, 368,1092, 437,\n3212,3258,1933,1829, 675,2977,2893, 412, 943,3723,4644,3294,3283,2230,2373,5154,\n2389,2241,2661,2323,1404,2524, 593, 787, 677,3008,1275,2059, 438,2709,2609,2240,\n2269,2246,1446,  36,1568,1373,3892,1574,2301,1456,3962, 693,2276,5216,2035,1143,\n2720,1919,1797,1811,2763,4137,2597,1830,1699,1488,1198,2090, 424,1694, 312,3634,\n3390,4179,3335,2252,1214, 561,1059,3243,2295,2561, 975,5155,2321,2751,3772, 472,\n1537,3282,3398,1047,2077,2348,2878,1323,3340,3076, 690,2906,  51, 369, 170,3541,\n1060,2187,2688,3670,2541,1083,1683, 928,3918, 459, 109,4427, 599,3744,4286, 143,\n2101,2730,2490,  82,1588,3036,2121, 281,1860, 477,4035,1238,2812,3020,2716,3312,\n1530,2188,2055,1317, 843, 636,1808,1173,3495, 649, 181,1002, 147,3641,1159,2414,\n3750,2289,2795, 813,3123,2610,1136,4368,   5,3391,4541,2174, 420, 429,1728, 754,\n1228,2115,2219, 347,2223,2733, 735,1518,3003,2355,3134,1764,3948,3329,1888,2424,\n1001,1234,1972,3321,3363,1672,1021,1450,1584, 226, 765, 655,2526,3404,3244,2302,\n3665, 731, 594,2184, 319,1576, 621, 658,2656,4299,2099,3864,1279,2071,2598,2739,\n 795,3086,3699,3908,1707,2352,2402,1382,3136,2475,1465,4847,3496,3865,1085,3004,\n2591,1084, 213,2287,1963,3565,2250, 822, 793,4574,3187,1772,1789,3050, 595,1484,\n1959,2770,1080,2650, 456, 422,2996, 940,3322,4328,4345,3092,2742, 965,2784, 739,\n4124, 952,1358,2498,2949,2565, 332,2698,2378, 660,2260,2473,4194,3856,2919, 535,\n1260,2651,1208,1428,1300,1949,1303,2942, 433,2455,2450,1251,1946, 614,1269, 641,\n1306,1810,2737,3078,2912, 564,2365,1419,1415,1497,4460,2367,2185,1379,3005,1307,\n3218,2175,1897,3063, 682,1157,4040,4005,1712,1160,1941,1399, 394, 402,2952,1573,\n1151,2986,2404, 862, 299,2033,1489,3006, 346, 171,2886,3401,1726,2932, 168,2533,\n  47,2507,1030,3735,1145,3370,1395,1318,1579,3609,4560,2857,4116,1457,2529,1965,\n 504,1036,2690,2988,2405, 745,5871, 849,2397,2056,3081, 863,2359,3857,2096,  99,\n1397,1769,2300,4428,1643,3455,1978,1757,3718,1440,  35,4879,3742,1296,4228,2280,\n 160,5063,1599,2013, 166, 520,3479,1646,3345,3012, 490,1937,1545,1264,2182,2505,\n1096,1188,1369,1436,2421,1667,2792,2460,1270,2122, 727,3167,2143, 806,1706,1012,\n1800,3037, 960,2218,1882, 805, 139,2456,1139,1521, 851,1052,3093,3089, 342,2039,\n 744,5097,1468,1502,1585,2087, 223, 939, 326,2140,2577, 892,2481,1623,4077, 982,\n3708, 135,2131,  87,2503,3114,2326,1106, 876,1616, 547,2997,2831,2093,3441,4530,\n4314,   9,3256,4229,4148, 659,1462,1986,1710,2046,2913,2231,4090,4880,5255,3392,\n3274,1368,3689,4645,1477, 705,3384,3635,1068,1529,2941,1458,3782,1509, 100,1656,\n2548, 718,2339, 408,1590,2780,3548,1838,4117,3719,1345,3530, 717,3442,2778,3220,\n2898,1892,4590,3614,3371,2043,1998,1224,3483, 891, 635, 584,2559,3355, 733,1766,\n1729,1172,3789,1891,2307, 781,2982,2271,1957,1580,5773,2633,2005,4195,3097,1535,\n3213,1189,1934,5693,3262, 586,3118,1324,1598, 517,1564,2217,1868,1893,4445,3728,\n2703,3139,1526,1787,1992,3882,2875,1549,1199,1056,2224,1904,2711,5098,4287, 338,\n1993,3129,3489,2689,1809,2815,1997, 957,1855,3898,2550,3275,3057,1105,1319, 627,\n1505,1911,1883,3526, 698,3629,3456,1833,1431, 746,  77,1261,2017,2296,1977,1885,\n 125,1334,1600, 525,1798,1109,2222,1470,1945, 559,2236,1186,3443,2476,1929,1411,\n2411,3135,1777,3372,2621,1841,1613,3229, 668,1430,1839,2643,2916, 195,1989,2671,\n2358,1387, 629,3205,2293,5256,4439, 123,1310, 888,1879,4300,3021,3605,1003,1162,\n3192,2910,2010, 140,2395,2859,  55,1082,2012,2901, 662, 419,2081,1438, 680,2774,\n4654,3912,1620,1731,1625,5035,4065,2328, 512,1344, 802,5443,2163,2311,2537, 524,\n3399,  98,1155,2103,1918,2606,3925,2816,1393,2465,1504,3773,2177,3963,1478,4346,\n 180,1113,4655,3461,2028,1698, 833,2696,1235,1322,1594,4408,3623,3013,3225,2040,\n3022, 541,2881, 607,3632,2029,1665,1219, 639,1385,1686,1099,2803,3231,1938,3188,\n2858, 427, 676,2772,1168,2025, 454,3253,2486,3556, 230,1950, 580, 791,1991,1280,\n1086,1974,2034, 630, 257,3338,2788,4903,1017,  86,4790, 966,2789,1995,1696,1131,\n 259,3095,4188,1308, 179,1463,5257, 289,4107,1248,  42,3413,1725,2288, 896,1947,\n 774,4474,4254, 604,3430,4264, 392,2514,2588, 452, 237,1408,3018, 988,4531,1970,\n3034,3310, 540,2370,1562,1288,2990, 502,4765,1147,   4,1853,2708, 207, 294,2814,\n4078,2902,2509, 684,  34,3105,3532,2551, 644, 709,2801,2344, 573,1727,3573,3557,\n2021,1081,3100,4315,2100,3681, 199,2263,1837,2385, 146,3484,1195,2776,3949, 997,\n1939,3973,1008,1091,1202,1962,1847,1149,4209,5444,1076, 493, 117,5400,2521, 972,\n1490,2934,1796,4542,2374,1512,2933,2657, 413,2888,1135,2762,2314,2156,1355,2369,\n 766,2007,2527,2170,3124,2491,2593,2632,4757,2437, 234,3125,3591,1898,1750,1376,\n1942,3468,3138, 570,2127,2145,3276,4131, 962, 132,1445,4196,  19, 941,3624,3480,\n3366,1973,1374,4461,3431,2629, 283,2415,2275, 808,2887,3620,2112,2563,1353,3610,\n 955,1089,3103,1053,  96,  88,4097, 823,3808,1583, 399, 292,4091,3313, 421,1128,\n 642,4006, 903,2539,1877,2082, 596,  29,4066,1790, 722,2157, 130, 995,1569, 769,\n1485, 464, 513,2213, 288,1923,1101,2453,4316, 133, 486,2445,  50, 625, 487,2207,\n  57, 423, 481,2962, 159,3729,1558, 491, 303, 482, 501, 240,2837, 112,3648,2392,\n1783, 362,   8,3433,3422, 610,2793,3277,1390,1284,1654,  21,3823, 734, 367, 623,\n 193, 287, 374,1009,1483, 816, 476, 313,2255,2340,1262,2150,2899,1146,2581, 782,\n2116,1659,2018,1880, 255,3586,3314,1110,2867,2137,2564, 986,2767,5185,2006, 650,\n 158, 926, 762, 881,3157,2717,2362,3587, 306,3690,3245,1542,3077,2427,1691,2478,\n2118,2985,3490,2438, 539,2305, 983, 129,1754, 355,4201,2386, 827,2923, 104,1773,\n2838,2771, 411,2905,3919, 376, 767, 122,1114, 828,2422,1817,3506, 266,3460,1007,\n1609,4998, 945,2612,4429,2274, 726,1247,1964,2914,2199,2070,4002,4108, 657,3323,\n1422, 579, 455,2764,4737,1222,2895,1670, 824,1223,1487,2525, 558, 861,3080, 598,\n2659,2515,1967, 752,2583,2376,2214,4180, 977, 704,2464,4999,2622,4109,1210,2961,\n 819,1541, 142,2284,  44, 418, 457,1126,3730,4347,4626,1644,1876,3671,1864, 302,\n1063,5694, 624, 723,1984,3745,1314,1676,2488,1610,1449,3558,3569,2166,2098, 409,\n1011,2325,3704,2306, 818,1732,1383,1824,1844,3757, 999,2705,3497,1216,1423,2683,\n2426,2954,2501,2726,2229,1475,2554,5064,1971,1794,1666,2014,1343, 783, 724, 191,\n2434,1354,2220,5065,1763,2752,2472,4152, 131, 175,2885,3434,  92,1466,4920,2616,\n3871,3872,3866, 128,1551,1632, 669,1854,3682,4691,4125,1230, 188,2973,3290,1302,\n1213, 560,3266, 917, 763,3909,3249,1760, 868,1958, 764,1782,2097, 145,2277,3774,\n4462,  64,1491,3062, 971,2132,3606,2442, 221,1226,1617, 218, 323,1185,3207,3147,\n 571, 619,1473,1005,1744,2281, 449,1887,2396,3685, 275, 375,3816,1743,3844,3731,\n 845,1983,2350,4210,1377, 773, 967,3499,3052,3743,2725,4007,1697,1022,3943,1464,\n3264,2855,2722,1952,1029,2839,2467,  84,4383,2215, 820,1391,2015,2448,3672, 377,\n1948,2168, 797,2545,3536,2578,2645,  94,2874,1678, 405,1259,3071, 771, 546,1315,\n 470,1243,3083, 895,2468, 981, 969,2037, 846,4181, 653,1276,2928,  14,2594, 557,\n3007,2474, 156, 902,1338,1740,2574, 537,2518, 973,2282,2216,2433,1928, 138,2903,\n1293,2631,1612, 646,3457, 839,2935, 111, 496,2191,2847, 589,3186, 149,3994,2060,\n4031,2641,4067,3145,1870,  37,3597,2136,1025,2051,3009,3383,3549,1121,1016,3261,\n1301, 251,2446,2599,2153, 872,3246, 637, 334,3705, 831, 884, 921,3065,3140,4092,\n2198,1944, 246,2964, 108,2045,1152,1921,2308,1031, 203,3173,4170,1907,3890, 810,\n1401,2003,1690, 506, 647,1242,2828,1761,1649,3208,2249,1589,3709,2931,5156,1708,\n 498, 666,2613, 834,3817,1231, 184,2851,1124, 883,3197,2261,3710,1765,1553,2658,\n1178,2639,2351,  93,1193, 942,2538,2141,4402, 235,1821, 870,1591,2192,1709,1871,\n3341,1618,4126,2595,2334, 603, 651,  69, 701, 268,2662,3411,2555,1380,1606, 503,\n 448, 254,2371,2646, 574,1187,2309,1770, 322,2235,1292,1801, 305, 566,1133, 229,\n2067,2057, 706, 167, 483,2002,2672,3295,1820,3561,3067, 316, 378,2746,3452,1112,\n 136,1981, 507,1651,2917,1117, 285,4591, 182,2580,3522,1304, 335,3303,1835,2504,\n1795,1792,2248, 674,1018,2106,2449,1857,2292,2845, 976,3047,1781,2600,2727,1389,\n1281,  52,3152, 153, 265,3950, 672,3485,3951,4463, 430,1183, 365, 278,2169,  27,\n1407,1336,2304, 209,1340,1730,2202,1852,2403,2883, 979,1737,1062, 631,2829,2542,\n3876,2592, 825,2086,2226,3048,3625, 352,1417,3724, 542, 991, 431,1351,3938,1861,\n2294, 826,1361,2927,3142,3503,1738, 463,2462,2723, 582,1916,1595,2808, 400,3845,\n3891,2868,3621,2254,  58,2492,1123, 910,2160,2614,1372,1603,1196,1072,3385,1700,\n3267,1980, 696, 480,2430, 920, 799,1570,2920,1951,2041,4047,2540,1321,4223,2469,\n3562,2228,1271,2602, 401,2833,3351,2575,5157, 907,2312,1256, 410, 263,3507,1582,\n 996, 678,1849,2316,1480, 908,3545,2237, 703,2322, 667,1826,2849,1531,2604,2999,\n2407,3146,2151,2630,1786,3711, 469,3542, 497,3899,2409, 858, 837,4446,3393,1274,\n 786, 620,1845,2001,3311, 484, 308,3367,1204,1815,3691,2332,1532,2557,1842,2020,\n2724,1927,2333,4440, 567,  22,1673,2728,4475,1987,1858,1144,1597, 101,1832,3601,\n  12, 974,3783,4391, 951,1412,   1,3720, 453,4608,4041, 528,1041,1027,3230,2628,\n1129, 875,1051,3291,1203,2262,1069,2860,2799,2149,2615,3278, 144,1758,3040,  31,\n 475,1680, 366,2685,3184, 311,1642,4008,2466,5036,1593,1493,2809, 216,1420,1668,\n 233, 304,2128,3284, 232,1429,1768,1040,2008,3407,2740,2967,2543, 242,2133, 778,\n1565,2022,2620, 505,2189,2756,1098,2273, 372,1614, 708, 553,2846,2094,2278, 169,\n3626,2835,4161, 228,2674,3165, 809,1454,1309, 466,1705,1095, 900,3423, 880,2667,\n3751,5258,2317,3109,2571,4317,2766,1503,1342, 866,4447,1118,  63,2076, 314,1881,\n1348,1061, 172, 978,3515,1747, 532, 511,3970,   6, 601, 905,2699,3300,1751, 276,\n1467,3725,2668,  65,4239,2544,2779,2556,1604, 578,2451,1802, 992,2331,2624,1320,\n3446, 713,1513,1013, 103,2786,2447,1661, 886,1702, 916, 654,3574,2031,1556, 751,\n2178,2821,2179,1498,1538,2176, 271, 914,2251,2080,1325, 638,1953,2937,3877,2432,\n2754,  95,3265,1716, 260,1227,4083, 775, 106,1357,3254, 426,1607, 555,2480, 772,\n1985, 244,2546, 474, 495,1046,2611,1851,2061,  71,2089,1675,2590, 742,3758,2843,\n3222,1433, 267,2180,2576,2826,2233,2092,3913,2435, 956,1745,3075, 856,2113,1116,\n 451,   3,1988,2896,1398, 993,2463,1878,2049,1341,2718,2721,2870,2108, 712,2904,\n4363,2753,2324, 277,2872,2349,2649, 384, 987, 435, 691,3000, 922, 164,3939, 652,\n1500,1184,4153,2482,3373,2165,4848,2335,3775,3508,3154,2806,2830,1554,2102,1664,\n2530,1434,2408, 893,1547,2623,3447,2832,2242,2532,3169,2856,3223,2078,  49,3770,\n3469, 462, 318, 656,2259,3250,3069, 679,1629,2758, 344,1138,1104,3120,1836,1283,\n3115,2154,1437,4448, 934, 759,1999, 794,2862,1038, 533,2560,1722,2342, 855,2626,\n1197,1663,4476,3127,  85,4240,2528,  25,1111,1181,3673, 407,3470,4561,2679,2713,\n 768,1925,2841,3986,1544,1165, 932, 373,1240,2146,1930,2673, 721,4766, 354,4333,\n 391,2963, 187,  61,3364,1442,1102, 330,1940,1767, 341,3809,4118, 393,2496,2062,\n2211, 105, 331, 300, 439, 913,1332, 626, 379,3304,1557, 328, 689,3952, 309,1555,\n 931, 317,2517,3027, 325, 569, 686,2107,3084,  60,1042,1333,2794, 264,3177,4014,\n1628, 258,3712,   7,4464,1176,1043,1778, 683, 114,1975,  78,1492, 383,1886, 510,\n 386, 645,5291,2891,2069,3305,4138,3867,2939,2603,2493,1935,1066,1848,3588,1015,\n1282,1289,4609, 697,1453,3044,2666,3611,1856,2412,  54, 719,1330, 568,3778,2459,\n1748, 788, 492, 551,1191,1000, 488,3394,3763, 282,1799, 348,2016,1523,3155,2390,\n1049, 382,2019,1788,1170, 729,2968,3523, 897,3926,2785,2938,3292, 350,2319,3238,\n1718,1717,2655,3453,3143,4465, 161,2889,2980,2009,1421,  56,1908,1640,2387,2232,\n1917,1874,2477,4921, 148,  83,3438, 592,4245,2882,1822,1055, 741, 115,1496,1624,\n 381,1638,4592,1020, 516,3214, 458, 947,4575,1432, 211,1514,2926,1865,2142, 189,\n 852,1221,1400,1486, 882,2299,4036, 351,  28,1122, 700,6479,6480,6481,6482,6483,  #last 512\n)\n# fmt: on\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/gb2312prober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is mozilla.org code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .chardistribution import GB2312DistributionAnalysis\nfrom .codingstatemachine import CodingStateMachine\nfrom .mbcharsetprober import MultiByteCharSetProber\nfrom .mbcssm import GB2312_SM_MODEL\n\n\nclass GB2312Prober(MultiByteCharSetProber):\n    def __init__(self):\n        super().__init__()\n        self.coding_sm = CodingStateMachine(GB2312_SM_MODEL)\n        self.distribution_analyzer = GB2312DistributionAnalysis()\n        self.reset()\n\n    @property\n    def charset_name(self):\n        return \"GB2312\"\n\n    @property\n    def language(self):\n        return \"Chinese\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/hebrewprober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Universal charset detector code.\n#\n# The Initial Developer of the Original Code is\n#          Shy Shalom\n# Portions created by the Initial Developer are Copyright (C) 2005\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .charsetprober import CharSetProber\nfrom .enums import ProbingState\n\n# This prober doesn't actually recognize a language or a charset.\n# It is a helper prober for the use of the Hebrew model probers\n\n### General ideas of the Hebrew charset recognition ###\n#\n# Four main charsets exist in Hebrew:\n# \"ISO-8859-8\" - Visual Hebrew\n# \"windows-1255\" - Logical Hebrew\n# \"ISO-8859-8-I\" - Logical Hebrew\n# \"x-mac-hebrew\" - ?? Logical Hebrew ??\n#\n# Both \"ISO\" charsets use a completely identical set of code points, whereas\n# \"windows-1255\" and \"x-mac-hebrew\" are two different proper supersets of\n# these code points. windows-1255 defines additional characters in the range\n# 0x80-0x9F as some misc punctuation marks as well as some Hebrew-specific\n# diacritics and additional 'Yiddish' ligature letters in the range 0xc0-0xd6.\n# x-mac-hebrew defines similar additional code points but with a different\n# mapping.\n#\n# As far as an average Hebrew text with no diacritics is concerned, all four\n# charsets are identical with respect to code points. Meaning that for the\n# main Hebrew alphabet, all four map the same values to all 27 Hebrew letters\n# (including final letters).\n#\n# The dominant difference between these charsets is their directionality.\n# \"Visual\" directionality means that the text is ordered as if the renderer is\n# not aware of a BIDI rendering algorithm. The renderer sees the text and\n# draws it from left to right. The text itself when ordered naturally is read\n# backwards. A buffer of Visual Hebrew generally looks like so:\n# \"[last word of first line spelled backwards] [whole line ordered backwards\n# and spelled backwards] [first word of first line spelled backwards]\n# [end of line] [last word of second line] ... etc' \"\n# adding punctuation marks, numbers and English text to visual text is\n# naturally also \"visual\" and from left to right.\n#\n# \"Logical\" directionality means the text is ordered \"naturally\" according to\n# the order it is read. It is the responsibility of the renderer to display\n# the text from right to left. A BIDI algorithm is used to place general\n# punctuation marks, numbers and English text in the text.\n#\n# Texts in x-mac-hebrew are almost impossible to find on the Internet. From\n# what little evidence I could find, it seems that its general directionality\n# is Logical.\n#\n# To sum up all of the above, the Hebrew probing mechanism knows about two\n# charsets:\n# Visual Hebrew - \"ISO-8859-8\" - backwards text - Words and sentences are\n#    backwards while line order is natural. For charset recognition purposes\n#    the line order is unimportant (In fact, for this implementation, even\n#    word order is unimportant).\n# Logical Hebrew - \"windows-1255\" - normal, naturally ordered text.\n#\n# \"ISO-8859-8-I\" is a subset of windows-1255 and doesn't need to be\n#    specifically identified.\n# \"x-mac-hebrew\" is also identified as windows-1255. A text in x-mac-hebrew\n#    that contain special punctuation marks or diacritics is displayed with\n#    some unconverted characters showing as question marks. This problem might\n#    be corrected using another model prober for x-mac-hebrew. Due to the fact\n#    that x-mac-hebrew texts are so rare, writing another model prober isn't\n#    worth the effort and performance hit.\n#\n#### The Prober ####\n#\n# The prober is divided between two SBCharSetProbers and a HebrewProber,\n# all of which are managed, created, fed data, inquired and deleted by the\n# SBCSGroupProber. The two SBCharSetProbers identify that the text is in\n# fact some kind of Hebrew, Logical or Visual. The final decision about which\n# one is it is made by the HebrewProber by combining final-letter scores\n# with the scores of the two SBCharSetProbers to produce a final answer.\n#\n# The SBCSGroupProber is responsible for stripping the original text of HTML\n# tags, English characters, numbers, low-ASCII punctuation characters, spaces\n# and new lines. It reduces any sequence of such characters to a single space.\n# The buffer fed to each prober in the SBCS group prober is pure text in\n# high-ASCII.\n# The two SBCharSetProbers (model probers) share the same language model:\n# Win1255Model.\n# The first SBCharSetProber uses the model normally as any other\n# SBCharSetProber does, to recognize windows-1255, upon which this model was\n# built. The second SBCharSetProber is told to make the pair-of-letter\n# lookup in the language model backwards. This in practice exactly simulates\n# a visual Hebrew model using the windows-1255 logical Hebrew model.\n#\n# The HebrewProber is not using any language model. All it does is look for\n# final-letter evidence suggesting the text is either logical Hebrew or visual\n# Hebrew. Disjointed from the model probers, the results of the HebrewProber\n# alone are meaningless. HebrewProber always returns 0.00 as confidence\n# since it never identifies a charset by itself. Instead, the pointer to the\n# HebrewProber is passed to the model probers as a helper \"Name Prober\".\n# When the Group prober receives a positive identification from any prober,\n# it asks for the name of the charset identified. If the prober queried is a\n# Hebrew model prober, the model prober forwards the call to the\n# HebrewProber to make the final decision. In the HebrewProber, the\n# decision is made according to the final-letters scores maintained and Both\n# model probers scores. The answer is returned in the form of the name of the\n# charset identified, either \"windows-1255\" or \"ISO-8859-8\".\n\n\nclass HebrewProber(CharSetProber):\n    # windows-1255 / ISO-8859-8 code points of interest\n    FINAL_KAF = 0xEA\n    NORMAL_KAF = 0xEB\n    FINAL_MEM = 0xED\n    NORMAL_MEM = 0xEE\n    FINAL_NUN = 0xEF\n    NORMAL_NUN = 0xF0\n    FINAL_PE = 0xF3\n    NORMAL_PE = 0xF4\n    FINAL_TSADI = 0xF5\n    NORMAL_TSADI = 0xF6\n\n    # Minimum Visual vs Logical final letter score difference.\n    # If the difference is below this, don't rely solely on the final letter score\n    # distance.\n    MIN_FINAL_CHAR_DISTANCE = 5\n\n    # Minimum Visual vs Logical model score difference.\n    # If the difference is below this, don't rely at all on the model score\n    # distance.\n    MIN_MODEL_DISTANCE = 0.01\n\n    VISUAL_HEBREW_NAME = \"ISO-8859-8\"\n    LOGICAL_HEBREW_NAME = \"windows-1255\"\n\n    def __init__(self):\n        super().__init__()\n        self._final_char_logical_score = None\n        self._final_char_visual_score = None\n        self._prev = None\n        self._before_prev = None\n        self._logical_prober = None\n        self._visual_prober = None\n        self.reset()\n\n    def reset(self):\n        self._final_char_logical_score = 0\n        self._final_char_visual_score = 0\n        # The two last characters seen in the previous buffer,\n        # mPrev and mBeforePrev are initialized to space in order to simulate\n        # a word delimiter at the beginning of the data\n        self._prev = \" \"\n        self._before_prev = \" \"\n        # These probers are owned by the group prober.\n\n    def set_model_probers(self, logical_prober, visual_prober):\n        self._logical_prober = logical_prober\n        self._visual_prober = visual_prober\n\n    def is_final(self, c):\n        return c in [\n            self.FINAL_KAF,\n            self.FINAL_MEM,\n            self.FINAL_NUN,\n            self.FINAL_PE,\n            self.FINAL_TSADI,\n        ]\n\n    def is_non_final(self, c):\n        # The normal Tsadi is not a good Non-Final letter due to words like\n        # 'lechotet' (to chat) containing an apostrophe after the tsadi. This\n        # apostrophe is converted to a space in FilterWithoutEnglishLetters\n        # causing the Non-Final tsadi to appear at an end of a word even\n        # though this is not the case in the original text.\n        # The letters Pe and Kaf rarely display a related behavior of not being\n        # a good Non-Final letter. Words like 'Pop', 'Winamp' and 'Mubarak'\n        # for example legally end with a Non-Final Pe or Kaf. However, the\n        # benefit of these letters as Non-Final letters outweighs the damage\n        # since these words are quite rare.\n        return c in [self.NORMAL_KAF, self.NORMAL_MEM, self.NORMAL_NUN, self.NORMAL_PE]\n\n    def feed(self, byte_str):\n        # Final letter analysis for logical-visual decision.\n        # Look for evidence that the received buffer is either logical Hebrew\n        # or visual Hebrew.\n        # The following cases are checked:\n        # 1) A word longer than 1 letter, ending with a final letter. This is\n        #    an indication that the text is laid out \"naturally\" since the\n        #    final letter really appears at the end. +1 for logical score.\n        # 2) A word longer than 1 letter, ending with a Non-Final letter. In\n        #    normal Hebrew, words ending with Kaf, Mem, Nun, Pe or Tsadi,\n        #    should not end with the Non-Final form of that letter. Exceptions\n        #    to this rule are mentioned above in isNonFinal(). This is an\n        #    indication that the text is laid out backwards. +1 for visual\n        #    score\n        # 3) A word longer than 1 letter, starting with a final letter. Final\n        #    letters should not appear at the beginning of a word. This is an\n        #    indication that the text is laid out backwards. +1 for visual\n        #    score.\n        #\n        # The visual score and logical score are accumulated throughout the\n        # text and are finally checked against each other in GetCharSetName().\n        # No checking for final letters in the middle of words is done since\n        # that case is not an indication for either Logical or Visual text.\n        #\n        # We automatically filter out all 7-bit characters (replace them with\n        # spaces) so the word boundary detection works properly. [MAP]\n\n        if self.state == ProbingState.NOT_ME:\n            # Both model probers say it's not them. No reason to continue.\n            return ProbingState.NOT_ME\n\n        byte_str = self.filter_high_byte_only(byte_str)\n\n        for cur in byte_str:\n            if cur == \" \":\n                # We stand on a space - a word just ended\n                if self._before_prev != \" \":\n                    # next-to-last char was not a space so self._prev is not a\n                    # 1 letter word\n                    if self.is_final(self._prev):\n                        # case (1) [-2:not space][-1:final letter][cur:space]\n                        self._final_char_logical_score += 1\n                    elif self.is_non_final(self._prev):\n                        # case (2) [-2:not space][-1:Non-Final letter][\n                        #  cur:space]\n                        self._final_char_visual_score += 1\n            else:\n                # Not standing on a space\n                if (\n                    (self._before_prev == \" \")\n                    and (self.is_final(self._prev))\n                    and (cur != \" \")\n                ):\n                    # case (3) [-2:space][-1:final letter][cur:not space]\n                    self._final_char_visual_score += 1\n            self._before_prev = self._prev\n            self._prev = cur\n\n        # Forever detecting, till the end or until both model probers return\n        # ProbingState.NOT_ME (handled above)\n        return ProbingState.DETECTING\n\n    @property\n    def charset_name(self):\n        # Make the decision: is it Logical or Visual?\n        # If the final letter score distance is dominant enough, rely on it.\n        finalsub = self._final_char_logical_score - self._final_char_visual_score\n        if finalsub >= self.MIN_FINAL_CHAR_DISTANCE:\n            return self.LOGICAL_HEBREW_NAME\n        if finalsub <= -self.MIN_FINAL_CHAR_DISTANCE:\n            return self.VISUAL_HEBREW_NAME\n\n        # It's not dominant enough, try to rely on the model scores instead.\n        modelsub = (\n            self._logical_prober.get_confidence() - self._visual_prober.get_confidence()\n        )\n        if modelsub > self.MIN_MODEL_DISTANCE:\n            return self.LOGICAL_HEBREW_NAME\n        if modelsub < -self.MIN_MODEL_DISTANCE:\n            return self.VISUAL_HEBREW_NAME\n\n        # Still no good, back to final letter distance, maybe it'll save the\n        # day.\n        if finalsub < 0.0:\n            return self.VISUAL_HEBREW_NAME\n\n        # (finalsub > 0 - Logical) or (don't know what to do) default to\n        # Logical.\n        return self.LOGICAL_HEBREW_NAME\n\n    @property\n    def language(self):\n        return \"Hebrew\"\n\n    @property\n    def state(self):\n        # Remain active as long as any of the model probers are active.\n        if (self._logical_prober.state == ProbingState.NOT_ME) and (\n            self._visual_prober.state == ProbingState.NOT_ME\n        ):\n            return ProbingState.NOT_ME\n        return ProbingState.DETECTING\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/jisfreq.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Communicator client code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\n# Sampling from about 20M text materials include literature and computer technology\n#\n# Japanese frequency table, applied to both S-JIS and EUC-JP\n# They are sorted in order.\n\n# 128  --> 0.77094\n# 256  --> 0.85710\n# 512  --> 0.92635\n# 1024 --> 0.97130\n# 2048 --> 0.99431\n#\n# Ideal Distribution Ratio = 0.92635 / (1-0.92635) = 12.58\n# Random Distribution Ration = 512 / (2965+62+83+86-512) = 0.191\n#\n# Typical Distribution Ratio, 25% of IDR\n\nJIS_TYPICAL_DISTRIBUTION_RATIO = 3.0\n\n# Char to FreqOrder table ,\nJIS_TABLE_SIZE = 4368\n\n# fmt: off\nJIS_CHAR_TO_FREQ_ORDER = (\n  40,   1,   6, 182, 152, 180, 295,2127, 285, 381,3295,4304,3068,4606,3165,3510, #   16\n3511,1822,2785,4607,1193,2226,5070,4608, 171,2996,1247,  18, 179,5071, 856,1661, #   32\n1262,5072, 619, 127,3431,3512,3230,1899,1700, 232, 228,1294,1298, 284, 283,2041, #   48\n2042,1061,1062,  48,  49,  44,  45, 433, 434,1040,1041, 996, 787,2997,1255,4305, #   64\n2108,4609,1684,1648,5073,5074,5075,5076,5077,5078,3687,5079,4610,5080,3927,3928, #   80\n5081,3296,3432, 290,2285,1471,2187,5082,2580,2825,1303,2140,1739,1445,2691,3375, #   96\n1691,3297,4306,4307,4611, 452,3376,1182,2713,3688,3069,4308,5083,5084,5085,5086, #  112\n5087,5088,5089,5090,5091,5092,5093,5094,5095,5096,5097,5098,5099,5100,5101,5102, #  128\n5103,5104,5105,5106,5107,5108,5109,5110,5111,5112,4097,5113,5114,5115,5116,5117, #  144\n5118,5119,5120,5121,5122,5123,5124,5125,5126,5127,5128,5129,5130,5131,5132,5133, #  160\n5134,5135,5136,5137,5138,5139,5140,5141,5142,5143,5144,5145,5146,5147,5148,5149, #  176\n5150,5151,5152,4612,5153,5154,5155,5156,5157,5158,5159,5160,5161,5162,5163,5164, #  192\n5165,5166,5167,5168,5169,5170,5171,5172,5173,5174,5175,1472, 598, 618, 820,1205, #  208\n1309,1412,1858,1307,1692,5176,5177,5178,5179,5180,5181,5182,1142,1452,1234,1172, #  224\n1875,2043,2149,1793,1382,2973, 925,2404,1067,1241, 960,1377,2935,1491, 919,1217, #  240\n1865,2030,1406,1499,2749,4098,5183,5184,5185,5186,5187,5188,2561,4099,3117,1804, #  256\n2049,3689,4309,3513,1663,5189,3166,3118,3298,1587,1561,3433,5190,3119,1625,2998, #  272\n3299,4613,1766,3690,2786,4614,5191,5192,5193,5194,2161,  26,3377,   2,3929,  20, #  288\n3691,  47,4100,  50,  17,  16,  35, 268,  27, 243,  42, 155,  24, 154,  29, 184, #  304\n   4,  91,  14,  92,  53, 396,  33, 289,   9,  37,  64, 620,  21,  39, 321,   5, #  320\n  12,  11,  52,  13,   3, 208, 138,   0,   7,  60, 526, 141, 151,1069, 181, 275, #  336\n1591,  83, 132,1475, 126, 331, 829,  15,  69, 160,  59,  22, 157,  55,1079, 312, #  352\n 109,  38,  23,  25,  10,  19,  79,5195,  61, 382,1124,   8,  30,5196,5197,5198, #  368\n5199,5200,5201,5202,5203,5204,5205,5206,  89,  62,  74,  34,2416, 112, 139, 196, #  384\n 271, 149,  84, 607, 131, 765,  46,  88, 153, 683,  76, 874, 101, 258,  57,  80, #  400\n  32, 364, 121,1508, 169,1547,  68, 235, 145,2999,  41, 360,3027,  70,  63,  31, #  416\n  43, 259, 262,1383,  99, 533, 194,  66,  93, 846, 217, 192,  56, 106,  58, 565, #  432\n 280, 272, 311, 256, 146,  82, 308,  71, 100, 128, 214, 655, 110, 261, 104,1140, #  448\n  54,  51,  36,  87,  67,3070, 185,2618,2936,2020,  28,1066,2390,2059,5207,5208, #  464\n5209,5210,5211,5212,5213,5214,5215,5216,4615,5217,5218,5219,5220,5221,5222,5223, #  480\n5224,5225,5226,5227,5228,5229,5230,5231,5232,5233,5234,5235,5236,3514,5237,5238, #  496\n5239,5240,5241,5242,5243,5244,2297,2031,4616,4310,3692,5245,3071,5246,3598,5247, #  512\n4617,3231,3515,5248,4101,4311,4618,3808,4312,4102,5249,4103,4104,3599,5250,5251, #  528\n5252,5253,5254,5255,5256,5257,5258,5259,5260,5261,5262,5263,5264,5265,5266,5267, #  544\n5268,5269,5270,5271,5272,5273,5274,5275,5276,5277,5278,5279,5280,5281,5282,5283, #  560\n5284,5285,5286,5287,5288,5289,5290,5291,5292,5293,5294,5295,5296,5297,5298,5299, #  576\n5300,5301,5302,5303,5304,5305,5306,5307,5308,5309,5310,5311,5312,5313,5314,5315, #  592\n5316,5317,5318,5319,5320,5321,5322,5323,5324,5325,5326,5327,5328,5329,5330,5331, #  608\n5332,5333,5334,5335,5336,5337,5338,5339,5340,5341,5342,5343,5344,5345,5346,5347, #  624\n5348,5349,5350,5351,5352,5353,5354,5355,5356,5357,5358,5359,5360,5361,5362,5363, #  640\n5364,5365,5366,5367,5368,5369,5370,5371,5372,5373,5374,5375,5376,5377,5378,5379, #  656\n5380,5381, 363, 642,2787,2878,2788,2789,2316,3232,2317,3434,2011, 165,1942,3930, #  672\n3931,3932,3933,5382,4619,5383,4620,5384,5385,5386,5387,5388,5389,5390,5391,5392, #  688\n5393,5394,5395,5396,5397,5398,5399,5400,5401,5402,5403,5404,5405,5406,5407,5408, #  704\n5409,5410,5411,5412,5413,5414,5415,5416,5417,5418,5419,5420,5421,5422,5423,5424, #  720\n5425,5426,5427,5428,5429,5430,5431,5432,5433,5434,5435,5436,5437,5438,5439,5440, #  736\n5441,5442,5443,5444,5445,5446,5447,5448,5449,5450,5451,5452,5453,5454,5455,5456, #  752\n5457,5458,5459,5460,5461,5462,5463,5464,5465,5466,5467,5468,5469,5470,5471,5472, #  768\n5473,5474,5475,5476,5477,5478,5479,5480,5481,5482,5483,5484,5485,5486,5487,5488, #  784\n5489,5490,5491,5492,5493,5494,5495,5496,5497,5498,5499,5500,5501,5502,5503,5504, #  800\n5505,5506,5507,5508,5509,5510,5511,5512,5513,5514,5515,5516,5517,5518,5519,5520, #  816\n5521,5522,5523,5524,5525,5526,5527,5528,5529,5530,5531,5532,5533,5534,5535,5536, #  832\n5537,5538,5539,5540,5541,5542,5543,5544,5545,5546,5547,5548,5549,5550,5551,5552, #  848\n5553,5554,5555,5556,5557,5558,5559,5560,5561,5562,5563,5564,5565,5566,5567,5568, #  864\n5569,5570,5571,5572,5573,5574,5575,5576,5577,5578,5579,5580,5581,5582,5583,5584, #  880\n5585,5586,5587,5588,5589,5590,5591,5592,5593,5594,5595,5596,5597,5598,5599,5600, #  896\n5601,5602,5603,5604,5605,5606,5607,5608,5609,5610,5611,5612,5613,5614,5615,5616, #  912\n5617,5618,5619,5620,5621,5622,5623,5624,5625,5626,5627,5628,5629,5630,5631,5632, #  928\n5633,5634,5635,5636,5637,5638,5639,5640,5641,5642,5643,5644,5645,5646,5647,5648, #  944\n5649,5650,5651,5652,5653,5654,5655,5656,5657,5658,5659,5660,5661,5662,5663,5664, #  960\n5665,5666,5667,5668,5669,5670,5671,5672,5673,5674,5675,5676,5677,5678,5679,5680, #  976\n5681,5682,5683,5684,5685,5686,5687,5688,5689,5690,5691,5692,5693,5694,5695,5696, #  992\n5697,5698,5699,5700,5701,5702,5703,5704,5705,5706,5707,5708,5709,5710,5711,5712, # 1008\n5713,5714,5715,5716,5717,5718,5719,5720,5721,5722,5723,5724,5725,5726,5727,5728, # 1024\n5729,5730,5731,5732,5733,5734,5735,5736,5737,5738,5739,5740,5741,5742,5743,5744, # 1040\n5745,5746,5747,5748,5749,5750,5751,5752,5753,5754,5755,5756,5757,5758,5759,5760, # 1056\n5761,5762,5763,5764,5765,5766,5767,5768,5769,5770,5771,5772,5773,5774,5775,5776, # 1072\n5777,5778,5779,5780,5781,5782,5783,5784,5785,5786,5787,5788,5789,5790,5791,5792, # 1088\n5793,5794,5795,5796,5797,5798,5799,5800,5801,5802,5803,5804,5805,5806,5807,5808, # 1104\n5809,5810,5811,5812,5813,5814,5815,5816,5817,5818,5819,5820,5821,5822,5823,5824, # 1120\n5825,5826,5827,5828,5829,5830,5831,5832,5833,5834,5835,5836,5837,5838,5839,5840, # 1136\n5841,5842,5843,5844,5845,5846,5847,5848,5849,5850,5851,5852,5853,5854,5855,5856, # 1152\n5857,5858,5859,5860,5861,5862,5863,5864,5865,5866,5867,5868,5869,5870,5871,5872, # 1168\n5873,5874,5875,5876,5877,5878,5879,5880,5881,5882,5883,5884,5885,5886,5887,5888, # 1184\n5889,5890,5891,5892,5893,5894,5895,5896,5897,5898,5899,5900,5901,5902,5903,5904, # 1200\n5905,5906,5907,5908,5909,5910,5911,5912,5913,5914,5915,5916,5917,5918,5919,5920, # 1216\n5921,5922,5923,5924,5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,5936, # 1232\n5937,5938,5939,5940,5941,5942,5943,5944,5945,5946,5947,5948,5949,5950,5951,5952, # 1248\n5953,5954,5955,5956,5957,5958,5959,5960,5961,5962,5963,5964,5965,5966,5967,5968, # 1264\n5969,5970,5971,5972,5973,5974,5975,5976,5977,5978,5979,5980,5981,5982,5983,5984, # 1280\n5985,5986,5987,5988,5989,5990,5991,5992,5993,5994,5995,5996,5997,5998,5999,6000, # 1296\n6001,6002,6003,6004,6005,6006,6007,6008,6009,6010,6011,6012,6013,6014,6015,6016, # 1312\n6017,6018,6019,6020,6021,6022,6023,6024,6025,6026,6027,6028,6029,6030,6031,6032, # 1328\n6033,6034,6035,6036,6037,6038,6039,6040,6041,6042,6043,6044,6045,6046,6047,6048, # 1344\n6049,6050,6051,6052,6053,6054,6055,6056,6057,6058,6059,6060,6061,6062,6063,6064, # 1360\n6065,6066,6067,6068,6069,6070,6071,6072,6073,6074,6075,6076,6077,6078,6079,6080, # 1376\n6081,6082,6083,6084,6085,6086,6087,6088,6089,6090,6091,6092,6093,6094,6095,6096, # 1392\n6097,6098,6099,6100,6101,6102,6103,6104,6105,6106,6107,6108,6109,6110,6111,6112, # 1408\n6113,6114,2044,2060,4621, 997,1235, 473,1186,4622, 920,3378,6115,6116, 379,1108, # 1424\n4313,2657,2735,3934,6117,3809, 636,3233, 573,1026,3693,3435,2974,3300,2298,4105, # 1440\n 854,2937,2463, 393,2581,2417, 539, 752,1280,2750,2480, 140,1161, 440, 708,1569, # 1456\n 665,2497,1746,1291,1523,3000, 164,1603, 847,1331, 537,1997, 486, 508,1693,2418, # 1472\n1970,2227, 878,1220, 299,1030, 969, 652,2751, 624,1137,3301,2619,  65,3302,2045, # 1488\n1761,1859,3120,1930,3694,3516, 663,1767, 852, 835,3695, 269, 767,2826,2339,1305, # 1504\n 896,1150, 770,1616,6118, 506,1502,2075,1012,2519, 775,2520,2975,2340,2938,4314, # 1520\n3028,2086,1224,1943,2286,6119,3072,4315,2240,1273,1987,3935,1557, 175, 597, 985, # 1536\n3517,2419,2521,1416,3029, 585, 938,1931,1007,1052,1932,1685,6120,3379,4316,4623, # 1552\n 804, 599,3121,1333,2128,2539,1159,1554,2032,3810, 687,2033,2904, 952, 675,1467, # 1568\n3436,6121,2241,1096,1786,2440,1543,1924, 980,1813,2228, 781,2692,1879, 728,1918, # 1584\n3696,4624, 548,1950,4625,1809,1088,1356,3303,2522,1944, 502, 972, 373, 513,2827, # 1600\n 586,2377,2391,1003,1976,1631,6122,2464,1084, 648,1776,4626,2141, 324, 962,2012, # 1616\n2177,2076,1384, 742,2178,1448,1173,1810, 222, 102, 301, 445, 125,2420, 662,2498, # 1632\n 277, 200,1476,1165,1068, 224,2562,1378,1446, 450,1880, 659, 791, 582,4627,2939, # 1648\n3936,1516,1274, 555,2099,3697,1020,1389,1526,3380,1762,1723,1787,2229, 412,2114, # 1664\n1900,2392,3518, 512,2597, 427,1925,2341,3122,1653,1686,2465,2499, 697, 330, 273, # 1680\n 380,2162, 951, 832, 780, 991,1301,3073, 965,2270,3519, 668,2523,2636,1286, 535, # 1696\n1407, 518, 671, 957,2658,2378, 267, 611,2197,3030,6123, 248,2299, 967,1799,2356, # 1712\n 850,1418,3437,1876,1256,1480,2828,1718,6124,6125,1755,1664,2405,6126,4628,2879, # 1728\n2829, 499,2179, 676,4629, 557,2329,2214,2090, 325,3234, 464, 811,3001, 992,2342, # 1744\n2481,1232,1469, 303,2242, 466,1070,2163, 603,1777,2091,4630,2752,4631,2714, 322, # 1760\n2659,1964,1768, 481,2188,1463,2330,2857,3600,2092,3031,2421,4632,2318,2070,1849, # 1776\n2598,4633,1302,2254,1668,1701,2422,3811,2905,3032,3123,2046,4106,1763,1694,4634, # 1792\n1604, 943,1724,1454, 917, 868,2215,1169,2940, 552,1145,1800,1228,1823,1955, 316, # 1808\n1080,2510, 361,1807,2830,4107,2660,3381,1346,1423,1134,4108,6127, 541,1263,1229, # 1824\n1148,2540, 545, 465,1833,2880,3438,1901,3074,2482, 816,3937, 713,1788,2500, 122, # 1840\n1575, 195,1451,2501,1111,6128, 859, 374,1225,2243,2483,4317, 390,1033,3439,3075, # 1856\n2524,1687, 266, 793,1440,2599, 946, 779, 802, 507, 897,1081, 528,2189,1292, 711, # 1872\n1866,1725,1167,1640, 753, 398,2661,1053, 246, 348,4318, 137,1024,3440,1600,2077, # 1888\n2129, 825,4319, 698, 238, 521, 187,2300,1157,2423,1641,1605,1464,1610,1097,2541, # 1904\n1260,1436, 759,2255,1814,2150, 705,3235, 409,2563,3304, 561,3033,2005,2564, 726, # 1920\n1956,2343,3698,4109, 949,3812,3813,3520,1669, 653,1379,2525, 881,2198, 632,2256, # 1936\n1027, 778,1074, 733,1957, 514,1481,2466, 554,2180, 702,3938,1606,1017,1398,6129, # 1952\n1380,3521, 921, 993,1313, 594, 449,1489,1617,1166, 768,1426,1360, 495,1794,3601, # 1968\n1177,3602,1170,4320,2344, 476, 425,3167,4635,3168,1424, 401,2662,1171,3382,1998, # 1984\n1089,4110, 477,3169, 474,6130,1909, 596,2831,1842, 494, 693,1051,1028,1207,3076, # 2000\n 606,2115, 727,2790,1473,1115, 743,3522, 630, 805,1532,4321,2021, 366,1057, 838, # 2016\n 684,1114,2142,4322,2050,1492,1892,1808,2271,3814,2424,1971,1447,1373,3305,1090, # 2032\n1536,3939,3523,3306,1455,2199, 336, 369,2331,1035, 584,2393, 902, 718,2600,6131, # 2048\n2753, 463,2151,1149,1611,2467, 715,1308,3124,1268, 343,1413,3236,1517,1347,2663, # 2064\n2093,3940,2022,1131,1553,2100,2941,1427,3441,2942,1323,2484,6132,1980, 872,2368, # 2080\n2441,2943, 320,2369,2116,1082, 679,1933,3941,2791,3815, 625,1143,2023, 422,2200, # 2096\n3816,6133, 730,1695, 356,2257,1626,2301,2858,2637,1627,1778, 937, 883,2906,2693, # 2112\n3002,1769,1086, 400,1063,1325,3307,2792,4111,3077, 456,2345,1046, 747,6134,1524, # 2128\n 884,1094,3383,1474,2164,1059, 974,1688,2181,2258,1047, 345,1665,1187, 358, 875, # 2144\n3170, 305, 660,3524,2190,1334,1135,3171,1540,1649,2542,1527, 927, 968,2793, 885, # 2160\n1972,1850, 482, 500,2638,1218,1109,1085,2543,1654,2034, 876,  78,2287,1482,1277, # 2176\n 861,1675,1083,1779, 724,2754, 454, 397,1132,1612,2332, 893, 672,1237, 257,2259, # 2192\n2370, 135,3384, 337,2244, 547, 352, 340, 709,2485,1400, 788,1138,2511, 540, 772, # 2208\n1682,2260,2272,2544,2013,1843,1902,4636,1999,1562,2288,4637,2201,1403,1533, 407, # 2224\n 576,3308,1254,2071, 978,3385, 170, 136,1201,3125,2664,3172,2394, 213, 912, 873, # 2240\n3603,1713,2202, 699,3604,3699, 813,3442, 493, 531,1054, 468,2907,1483, 304, 281, # 2256\n4112,1726,1252,2094, 339,2319,2130,2639, 756,1563,2944, 748, 571,2976,1588,2425, # 2272\n2715,1851,1460,2426,1528,1392,1973,3237, 288,3309, 685,3386, 296, 892,2716,2216, # 2288\n1570,2245, 722,1747,2217, 905,3238,1103,6135,1893,1441,1965, 251,1805,2371,3700, # 2304\n2601,1919,1078,  75,2182,1509,1592,1270,2640,4638,2152,6136,3310,3817, 524, 706, # 2320\n1075, 292,3818,1756,2602, 317,  98,3173,3605,3525,1844,2218,3819,2502, 814, 567, # 2336\n 385,2908,1534,6137, 534,1642,3239, 797,6138,1670,1529, 953,4323, 188,1071, 538, # 2352\n 178, 729,3240,2109,1226,1374,2000,2357,2977, 731,2468,1116,2014,2051,6139,1261, # 2368\n1593, 803,2859,2736,3443, 556, 682, 823,1541,6140,1369,2289,1706,2794, 845, 462, # 2384\n2603,2665,1361, 387, 162,2358,1740, 739,1770,1720,1304,1401,3241,1049, 627,1571, # 2400\n2427,3526,1877,3942,1852,1500, 431,1910,1503, 677, 297,2795, 286,1433,1038,1198, # 2416\n2290,1133,1596,4113,4639,2469,1510,1484,3943,6141,2442, 108, 712,4640,2372, 866, # 2432\n3701,2755,3242,1348, 834,1945,1408,3527,2395,3243,1811, 824, 994,1179,2110,1548, # 2448\n1453, 790,3003, 690,4324,4325,2832,2909,3820,1860,3821, 225,1748, 310, 346,1780, # 2464\n2470, 821,1993,2717,2796, 828, 877,3528,2860,2471,1702,2165,2910,2486,1789, 453, # 2480\n 359,2291,1676,  73,1164,1461,1127,3311, 421, 604, 314,1037, 589, 116,2487, 737, # 2496\n 837,1180, 111, 244, 735,6142,2261,1861,1362, 986, 523, 418, 581,2666,3822, 103, # 2512\n 855, 503,1414,1867,2488,1091, 657,1597, 979, 605,1316,4641,1021,2443,2078,2001, # 2528\n1209,  96, 587,2166,1032, 260,1072,2153, 173,  94, 226,3244, 819,2006,4642,4114, # 2544\n2203, 231,1744, 782,  97,2667, 786,3387, 887, 391, 442,2219,4326,1425,6143,2694, # 2560\n 633,1544,1202, 483,2015, 592,2052,1958,2472,1655, 419, 129,4327,3444,3312,1714, # 2576\n1257,3078,4328,1518,1098, 865,1310,1019,1885,1512,1734, 469,2444, 148, 773, 436, # 2592\n1815,1868,1128,1055,4329,1245,2756,3445,2154,1934,1039,4643, 579,1238, 932,2320, # 2608\n 353, 205, 801, 115,2428, 944,2321,1881, 399,2565,1211, 678, 766,3944, 335,2101, # 2624\n1459,1781,1402,3945,2737,2131,1010, 844, 981,1326,1013, 550,1816,1545,2620,1335, # 2640\n1008, 371,2881, 936,1419,1613,3529,1456,1395,2273,1834,2604,1317,2738,2503, 416, # 2656\n1643,4330, 806,1126, 229, 591,3946,1314,1981,1576,1837,1666, 347,1790, 977,3313, # 2672\n 764,2861,1853, 688,2429,1920,1462,  77, 595, 415,2002,3034, 798,1192,4115,6144, # 2688\n2978,4331,3035,2695,2582,2072,2566, 430,2430,1727, 842,1396,3947,3702, 613, 377, # 2704\n 278, 236,1417,3388,3314,3174, 757,1869, 107,3530,6145,1194, 623,2262, 207,1253, # 2720\n2167,3446,3948, 492,1117,1935, 536,1838,2757,1246,4332, 696,2095,2406,1393,1572, # 2736\n3175,1782, 583, 190, 253,1390,2230, 830,3126,3389, 934,3245,1703,1749,2979,1870, # 2752\n2545,1656,2204, 869,2346,4116,3176,1817, 496,1764,4644, 942,1504, 404,1903,1122, # 2768\n1580,3606,2945,1022, 515, 372,1735, 955,2431,3036,6146,2797,1110,2302,2798, 617, # 2784\n6147, 441, 762,1771,3447,3607,3608,1904, 840,3037,  86, 939,1385, 572,1370,2445, # 2800\n1336, 114,3703, 898, 294, 203,3315, 703,1583,2274, 429, 961,4333,1854,1951,3390, # 2816\n2373,3704,4334,1318,1381, 966,1911,2322,1006,1155, 309, 989, 458,2718,1795,1372, # 2832\n1203, 252,1689,1363,3177, 517,1936, 168,1490, 562, 193,3823,1042,4117,1835, 551, # 2848\n 470,4645, 395, 489,3448,1871,1465,2583,2641, 417,1493, 279,1295, 511,1236,1119, # 2864\n  72,1231,1982,1812,3004, 871,1564, 984,3449,1667,2696,2096,4646,2347,2833,1673, # 2880\n3609, 695,3246,2668, 807,1183,4647, 890, 388,2333,1801,1457,2911,1765,1477,1031, # 2896\n3316,3317,1278,3391,2799,2292,2526, 163,3450,4335,2669,1404,1802,6148,2323,2407, # 2912\n1584,1728,1494,1824,1269, 298, 909,3318,1034,1632, 375, 776,1683,2061, 291, 210, # 2928\n1123, 809,1249,1002,2642,3038, 206,1011,2132, 144, 975, 882,1565, 342, 667, 754, # 2944\n1442,2143,1299,2303,2062, 447, 626,2205,1221,2739,2912,1144,1214,2206,2584, 760, # 2960\n1715, 614, 950,1281,2670,2621, 810, 577,1287,2546,4648, 242,2168, 250,2643, 691, # 2976\n 123,2644, 647, 313,1029, 689,1357,2946,1650, 216, 771,1339,1306, 808,2063, 549, # 2992\n 913,1371,2913,2914,6149,1466,1092,1174,1196,1311,2605,2396,1783,1796,3079, 406, # 3008\n2671,2117,3949,4649, 487,1825,2220,6150,2915, 448,2348,1073,6151,2397,1707, 130, # 3024\n 900,1598, 329, 176,1959,2527,1620,6152,2275,4336,3319,1983,2191,3705,3610,2155, # 3040\n3706,1912,1513,1614,6153,1988, 646, 392,2304,1589,3320,3039,1826,1239,1352,1340, # 3056\n2916, 505,2567,1709,1437,2408,2547, 906,6154,2672, 384,1458,1594,1100,1329, 710, # 3072\n 423,3531,2064,2231,2622,1989,2673,1087,1882, 333, 841,3005,1296,2882,2379, 580, # 3088\n1937,1827,1293,2585, 601, 574, 249,1772,4118,2079,1120, 645, 901,1176,1690, 795, # 3104\n2207, 478,1434, 516,1190,1530, 761,2080, 930,1264, 355, 435,1552, 644,1791, 987, # 3120\n 220,1364,1163,1121,1538, 306,2169,1327,1222, 546,2645, 218, 241, 610,1704,3321, # 3136\n1984,1839,1966,2528, 451,6155,2586,3707,2568, 907,3178, 254,2947, 186,1845,4650, # 3152\n 745, 432,1757, 428,1633, 888,2246,2221,2489,3611,2118,1258,1265, 956,3127,1784, # 3168\n4337,2490, 319, 510, 119, 457,3612, 274,2035,2007,4651,1409,3128, 970,2758, 590, # 3184\n2800, 661,2247,4652,2008,3950,1420,1549,3080,3322,3951,1651,1375,2111, 485,2491, # 3200\n1429,1156,6156,2548,2183,1495, 831,1840,2529,2446, 501,1657, 307,1894,3247,1341, # 3216\n 666, 899,2156,1539,2549,1559, 886, 349,2208,3081,2305,1736,3824,2170,2759,1014, # 3232\n1913,1386, 542,1397,2948, 490, 368, 716, 362, 159, 282,2569,1129,1658,1288,1750, # 3248\n2674, 276, 649,2016, 751,1496, 658,1818,1284,1862,2209,2087,2512,3451, 622,2834, # 3264\n 376, 117,1060,2053,1208,1721,1101,1443, 247,1250,3179,1792,3952,2760,2398,3953, # 3280\n6157,2144,3708, 446,2432,1151,2570,3452,2447,2761,2835,1210,2448,3082, 424,2222, # 3296\n1251,2449,2119,2836, 504,1581,4338, 602, 817, 857,3825,2349,2306, 357,3826,1470, # 3312\n1883,2883, 255, 958, 929,2917,3248, 302,4653,1050,1271,1751,2307,1952,1430,2697, # 3328\n2719,2359, 354,3180, 777, 158,2036,4339,1659,4340,4654,2308,2949,2248,1146,2232, # 3344\n3532,2720,1696,2623,3827,6158,3129,1550,2698,1485,1297,1428, 637, 931,2721,2145, # 3360\n 914,2550,2587,  81,2450, 612, 827,2646,1242,4655,1118,2884, 472,1855,3181,3533, # 3376\n3534, 569,1353,2699,1244,1758,2588,4119,2009,2762,2171,3709,1312,1531,6159,1152, # 3392\n1938, 134,1830, 471,3710,2276,1112,1535,3323,3453,3535, 982,1337,2950, 488, 826, # 3408\n 674,1058,1628,4120,2017, 522,2399, 211, 568,1367,3454, 350, 293,1872,1139,3249, # 3424\n1399,1946,3006,1300,2360,3324, 588, 736,6160,2606, 744, 669,3536,3828,6161,1358, # 3440\n 199, 723, 848, 933, 851,1939,1505,1514,1338,1618,1831,4656,1634,3613, 443,2740, # 3456\n3829, 717,1947, 491,1914,6162,2551,1542,4121,1025,6163,1099,1223, 198,3040,2722, # 3472\n 370, 410,1905,2589, 998,1248,3182,2380, 519,1449,4122,1710, 947, 928,1153,4341, # 3488\n2277, 344,2624,1511, 615, 105, 161,1212,1076,1960,3130,2054,1926,1175,1906,2473, # 3504\n 414,1873,2801,6164,2309, 315,1319,3325, 318,2018,2146,2157, 963, 631, 223,4342, # 3520\n4343,2675, 479,3711,1197,2625,3712,2676,2361,6165,4344,4123,6166,2451,3183,1886, # 3536\n2184,1674,1330,1711,1635,1506, 799, 219,3250,3083,3954,1677,3713,3326,2081,3614, # 3552\n1652,2073,4657,1147,3041,1752, 643,1961, 147,1974,3955,6167,1716,2037, 918,3007, # 3568\n1994, 120,1537, 118, 609,3184,4345, 740,3455,1219, 332,1615,3830,6168,1621,2980, # 3584\n1582, 783, 212, 553,2350,3714,1349,2433,2082,4124, 889,6169,2310,1275,1410, 973, # 3600\n 166,1320,3456,1797,1215,3185,2885,1846,2590,2763,4658, 629, 822,3008, 763, 940, # 3616\n1990,2862, 439,2409,1566,1240,1622, 926,1282,1907,2764, 654,2210,1607, 327,1130, # 3632\n3956,1678,1623,6170,2434,2192, 686, 608,3831,3715, 903,3957,3042,6171,2741,1522, # 3648\n1915,1105,1555,2552,1359, 323,3251,4346,3457, 738,1354,2553,2311,2334,1828,2003, # 3664\n3832,1753,2351,1227,6172,1887,4125,1478,6173,2410,1874,1712,1847, 520,1204,2607, # 3680\n 264,4659, 836,2677,2102, 600,4660,3833,2278,3084,6174,4347,3615,1342, 640, 532, # 3696\n 543,2608,1888,2400,2591,1009,4348,1497, 341,1737,3616,2723,1394, 529,3252,1321, # 3712\n 983,4661,1515,2120, 971,2592, 924, 287,1662,3186,4349,2700,4350,1519, 908,1948, # 3728\n2452, 156, 796,1629,1486,2223,2055, 694,4126,1259,1036,3392,1213,2249,2742,1889, # 3744\n1230,3958,1015, 910, 408, 559,3617,4662, 746, 725, 935,4663,3959,3009,1289, 563, # 3760\n 867,4664,3960,1567,2981,2038,2626, 988,2263,2381,4351, 143,2374, 704,1895,6175, # 3776\n1188,3716,2088, 673,3085,2362,4352, 484,1608,1921,2765,2918, 215, 904,3618,3537, # 3792\n 894, 509, 976,3043,2701,3961,4353,2837,2982, 498,6176,6177,1102,3538,1332,3393, # 3808\n1487,1636,1637, 233, 245,3962, 383, 650, 995,3044, 460,1520,1206,2352, 749,3327, # 3824\n 530, 700, 389,1438,1560,1773,3963,2264, 719,2951,2724,3834, 870,1832,1644,1000, # 3840\n 839,2474,3717, 197,1630,3394, 365,2886,3964,1285,2133, 734, 922, 818,1106, 732, # 3856\n 480,2083,1774,3458, 923,2279,1350, 221,3086,  85,2233,2234,3835,1585,3010,2147, # 3872\n1387,1705,2382,1619,2475, 133, 239,2802,1991,1016,2084,2383, 411,2838,1113, 651, # 3888\n1985,1160,3328, 990,1863,3087,1048,1276,2647, 265,2627,1599,3253,2056, 150, 638, # 3904\n2019, 656, 853, 326,1479, 680,1439,4354,1001,1759, 413,3459,3395,2492,1431, 459, # 3920\n4355,1125,3329,2265,1953,1450,2065,2863, 849, 351,2678,3131,3254,3255,1104,1577, # 3936\n 227,1351,1645,2453,2193,1421,2887, 812,2121, 634,  95,2435, 201,2312,4665,1646, # 3952\n1671,2743,1601,2554,2702,2648,2280,1315,1366,2089,3132,1573,3718,3965,1729,1189, # 3968\n 328,2679,1077,1940,1136, 558,1283, 964,1195, 621,2074,1199,1743,3460,3619,1896, # 3984\n1916,1890,3836,2952,1154,2112,1064, 862, 378,3011,2066,2113,2803,1568,2839,6178, # 4000\n3088,2919,1941,1660,2004,1992,2194, 142, 707,1590,1708,1624,1922,1023,1836,1233, # 4016\n1004,2313, 789, 741,3620,6179,1609,2411,1200,4127,3719,3720,4666,2057,3721, 593, # 4032\n2840, 367,2920,1878,6180,3461,1521, 628,1168, 692,2211,2649, 300, 720,2067,2571, # 4048\n2953,3396, 959,2504,3966,3539,3462,1977, 701,6181, 954,1043, 800, 681, 183,3722, # 4064\n1803,1730,3540,4128,2103, 815,2314, 174, 467, 230,2454,1093,2134, 755,3541,3397, # 4080\n1141,1162,6182,1738,2039, 270,3256,2513,1005,1647,2185,3837, 858,1679,1897,1719, # 4096\n2954,2324,1806, 402, 670, 167,4129,1498,2158,2104, 750,6183, 915, 189,1680,1551, # 4112\n 455,4356,1501,2455, 405,1095,2955, 338,1586,1266,1819, 570, 641,1324, 237,1556, # 4128\n2650,1388,3723,6184,1368,2384,1343,1978,3089,2436, 879,3724, 792,1191, 758,3012, # 4144\n1411,2135,1322,4357, 240,4667,1848,3725,1574,6185, 420,3045,1546,1391, 714,4358, # 4160\n1967, 941,1864, 863, 664, 426, 560,1731,2680,1785,2864,1949,2363, 403,3330,1415, # 4176\n1279,2136,1697,2335, 204, 721,2097,3838,  90,6186,2085,2505, 191,3967, 124,2148, # 4192\n1376,1798,1178,1107,1898,1405, 860,4359,1243,1272,2375,2983,1558,2456,1638, 113, # 4208\n3621, 578,1923,2609, 880, 386,4130, 784,2186,2266,1422,2956,2172,1722, 497, 263, # 4224\n2514,1267,2412,2610, 177,2703,3542, 774,1927,1344, 616,1432,1595,1018, 172,4360, # 4240\n2325, 911,4361, 438,1468,3622, 794,3968,2024,2173,1681,1829,2957, 945, 895,3090, # 4256\n 575,2212,2476, 475,2401,2681, 785,2744,1745,2293,2555,1975,3133,2865, 394,4668, # 4272\n3839, 635,4131, 639, 202,1507,2195,2766,1345,1435,2572,3726,1908,1184,1181,2457, # 4288\n3727,3134,4362, 843,2611, 437, 916,4669, 234, 769,1884,3046,3047,3623, 833,6187, # 4304\n1639,2250,2402,1355,1185,2010,2047, 999, 525,1732,1290,1488,2612, 948,1578,3728, # 4320\n2413,2477,1216,2725,2159, 334,3840,1328,3624,2921,1525,4132, 564,1056, 891,4363, # 4336\n1444,1698,2385,2251,3729,1365,2281,2235,1717,6188, 864,3841,2515, 444, 527,2767, # 4352\n2922,3625, 544, 461,6189, 566, 209,2437,3398,2098,1065,2068,3331,3626,3257,2137, # 4368  #last 512\n)\n# fmt: on\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/johabfreq.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Communicator client code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\n# The frequency data itself is the same as euc-kr.\n# This is just a mapping table to euc-kr.\n\nJOHAB_TO_EUCKR_ORDER_TABLE = {\n    0x8861: 0,\n    0x8862: 1,\n    0x8865: 2,\n    0x8868: 3,\n    0x8869: 4,\n    0x886A: 5,\n    0x886B: 6,\n    0x8871: 7,\n    0x8873: 8,\n    0x8874: 9,\n    0x8875: 10,\n    0x8876: 11,\n    0x8877: 12,\n    0x8878: 13,\n    0x8879: 14,\n    0x887B: 15,\n    0x887C: 16,\n    0x887D: 17,\n    0x8881: 18,\n    0x8882: 19,\n    0x8885: 20,\n    0x8889: 21,\n    0x8891: 22,\n    0x8893: 23,\n    0x8895: 24,\n    0x8896: 25,\n    0x8897: 26,\n    0x88A1: 27,\n    0x88A2: 28,\n    0x88A5: 29,\n    0x88A9: 30,\n    0x88B5: 31,\n    0x88B7: 32,\n    0x88C1: 33,\n    0x88C5: 34,\n    0x88C9: 35,\n    0x88E1: 36,\n    0x88E2: 37,\n    0x88E5: 38,\n    0x88E8: 39,\n    0x88E9: 40,\n    0x88EB: 41,\n    0x88F1: 42,\n    0x88F3: 43,\n    0x88F5: 44,\n    0x88F6: 45,\n    0x88F7: 46,\n    0x88F8: 47,\n    0x88FB: 48,\n    0x88FC: 49,\n    0x88FD: 50,\n    0x8941: 51,\n    0x8945: 52,\n    0x8949: 53,\n    0x8951: 54,\n    0x8953: 55,\n    0x8955: 56,\n    0x8956: 57,\n    0x8957: 58,\n    0x8961: 59,\n    0x8962: 60,\n    0x8963: 61,\n    0x8965: 62,\n    0x8968: 63,\n    0x8969: 64,\n    0x8971: 65,\n    0x8973: 66,\n    0x8975: 67,\n    0x8976: 68,\n    0x8977: 69,\n    0x897B: 70,\n    0x8981: 71,\n    0x8985: 72,\n    0x8989: 73,\n    0x8993: 74,\n    0x8995: 75,\n    0x89A1: 76,\n    0x89A2: 77,\n    0x89A5: 78,\n    0x89A8: 79,\n    0x89A9: 80,\n    0x89AB: 81,\n    0x89AD: 82,\n    0x89B0: 83,\n    0x89B1: 84,\n    0x89B3: 85,\n    0x89B5: 86,\n    0x89B7: 87,\n    0x89B8: 88,\n    0x89C1: 89,\n    0x89C2: 90,\n    0x89C5: 91,\n    0x89C9: 92,\n    0x89CB: 93,\n    0x89D1: 94,\n    0x89D3: 95,\n    0x89D5: 96,\n    0x89D7: 97,\n    0x89E1: 98,\n    0x89E5: 99,\n    0x89E9: 100,\n    0x89F3: 101,\n    0x89F6: 102,\n    0x89F7: 103,\n    0x8A41: 104,\n    0x8A42: 105,\n    0x8A45: 106,\n    0x8A49: 107,\n    0x8A51: 108,\n    0x8A53: 109,\n    0x8A55: 110,\n    0x8A57: 111,\n    0x8A61: 112,\n    0x8A65: 113,\n    0x8A69: 114,\n    0x8A73: 115,\n    0x8A75: 116,\n    0x8A81: 117,\n    0x8A82: 118,\n    0x8A85: 119,\n    0x8A88: 120,\n    0x8A89: 121,\n    0x8A8A: 122,\n    0x8A8B: 123,\n    0x8A90: 124,\n    0x8A91: 125,\n    0x8A93: 126,\n    0x8A95: 127,\n    0x8A97: 128,\n    0x8A98: 129,\n    0x8AA1: 130,\n    0x8AA2: 131,\n    0x8AA5: 132,\n    0x8AA9: 133,\n    0x8AB6: 134,\n    0x8AB7: 135,\n    0x8AC1: 136,\n    0x8AD5: 137,\n    0x8AE1: 138,\n    0x8AE2: 139,\n    0x8AE5: 140,\n    0x8AE9: 141,\n    0x8AF1: 142,\n    0x8AF3: 143,\n    0x8AF5: 144,\n    0x8B41: 145,\n    0x8B45: 146,\n    0x8B49: 147,\n    0x8B61: 148,\n    0x8B62: 149,\n    0x8B65: 150,\n    0x8B68: 151,\n    0x8B69: 152,\n    0x8B6A: 153,\n    0x8B71: 154,\n    0x8B73: 155,\n    0x8B75: 156,\n    0x8B77: 157,\n    0x8B81: 158,\n    0x8BA1: 159,\n    0x8BA2: 160,\n    0x8BA5: 161,\n    0x8BA8: 162,\n    0x8BA9: 163,\n    0x8BAB: 164,\n    0x8BB1: 165,\n    0x8BB3: 166,\n    0x8BB5: 167,\n    0x8BB7: 168,\n    0x8BB8: 169,\n    0x8BBC: 170,\n    0x8C61: 171,\n    0x8C62: 172,\n    0x8C63: 173,\n    0x8C65: 174,\n    0x8C69: 175,\n    0x8C6B: 176,\n    0x8C71: 177,\n    0x8C73: 178,\n    0x8C75: 179,\n    0x8C76: 180,\n    0x8C77: 181,\n    0x8C7B: 182,\n    0x8C81: 183,\n    0x8C82: 184,\n    0x8C85: 185,\n    0x8C89: 186,\n    0x8C91: 187,\n    0x8C93: 188,\n    0x8C95: 189,\n    0x8C96: 190,\n    0x8C97: 191,\n    0x8CA1: 192,\n    0x8CA2: 193,\n    0x8CA9: 194,\n    0x8CE1: 195,\n    0x8CE2: 196,\n    0x8CE3: 197,\n    0x8CE5: 198,\n    0x8CE9: 199,\n    0x8CF1: 200,\n    0x8CF3: 201,\n    0x8CF5: 202,\n    0x8CF6: 203,\n    0x8CF7: 204,\n    0x8D41: 205,\n    0x8D42: 206,\n    0x8D45: 207,\n    0x8D51: 208,\n    0x8D55: 209,\n    0x8D57: 210,\n    0x8D61: 211,\n    0x8D65: 212,\n    0x8D69: 213,\n    0x8D75: 214,\n    0x8D76: 215,\n    0x8D7B: 216,\n    0x8D81: 217,\n    0x8DA1: 218,\n    0x8DA2: 219,\n    0x8DA5: 220,\n    0x8DA7: 221,\n    0x8DA9: 222,\n    0x8DB1: 223,\n    0x8DB3: 224,\n    0x8DB5: 225,\n    0x8DB7: 226,\n    0x8DB8: 227,\n    0x8DB9: 228,\n    0x8DC1: 229,\n    0x8DC2: 230,\n    0x8DC9: 231,\n    0x8DD6: 232,\n    0x8DD7: 233,\n    0x8DE1: 234,\n    0x8DE2: 235,\n    0x8DF7: 236,\n    0x8E41: 237,\n    0x8E45: 238,\n    0x8E49: 239,\n    0x8E51: 240,\n    0x8E53: 241,\n    0x8E57: 242,\n    0x8E61: 243,\n    0x8E81: 244,\n    0x8E82: 245,\n    0x8E85: 246,\n    0x8E89: 247,\n    0x8E90: 248,\n    0x8E91: 249,\n    0x8E93: 250,\n    0x8E95: 251,\n    0x8E97: 252,\n    0x8E98: 253,\n    0x8EA1: 254,\n    0x8EA9: 255,\n    0x8EB6: 256,\n    0x8EB7: 257,\n    0x8EC1: 258,\n    0x8EC2: 259,\n    0x8EC5: 260,\n    0x8EC9: 261,\n    0x8ED1: 262,\n    0x8ED3: 263,\n    0x8ED6: 264,\n    0x8EE1: 265,\n    0x8EE5: 266,\n    0x8EE9: 267,\n    0x8EF1: 268,\n    0x8EF3: 269,\n    0x8F41: 270,\n    0x8F61: 271,\n    0x8F62: 272,\n    0x8F65: 273,\n    0x8F67: 274,\n    0x8F69: 275,\n    0x8F6B: 276,\n    0x8F70: 277,\n    0x8F71: 278,\n    0x8F73: 279,\n    0x8F75: 280,\n    0x8F77: 281,\n    0x8F7B: 282,\n    0x8FA1: 283,\n    0x8FA2: 284,\n    0x8FA5: 285,\n    0x8FA9: 286,\n    0x8FB1: 287,\n    0x8FB3: 288,\n    0x8FB5: 289,\n    0x8FB7: 290,\n    0x9061: 291,\n    0x9062: 292,\n    0x9063: 293,\n    0x9065: 294,\n    0x9068: 295,\n    0x9069: 296,\n    0x906A: 297,\n    0x906B: 298,\n    0x9071: 299,\n    0x9073: 300,\n    0x9075: 301,\n    0x9076: 302,\n    0x9077: 303,\n    0x9078: 304,\n    0x9079: 305,\n    0x907B: 306,\n    0x907D: 307,\n    0x9081: 308,\n    0x9082: 309,\n    0x9085: 310,\n    0x9089: 311,\n    0x9091: 312,\n    0x9093: 313,\n    0x9095: 314,\n    0x9096: 315,\n    0x9097: 316,\n    0x90A1: 317,\n    0x90A2: 318,\n    0x90A5: 319,\n    0x90A9: 320,\n    0x90B1: 321,\n    0x90B7: 322,\n    0x90E1: 323,\n    0x90E2: 324,\n    0x90E4: 325,\n    0x90E5: 326,\n    0x90E9: 327,\n    0x90EB: 328,\n    0x90EC: 329,\n    0x90F1: 330,\n    0x90F3: 331,\n    0x90F5: 332,\n    0x90F6: 333,\n    0x90F7: 334,\n    0x90FD: 335,\n    0x9141: 336,\n    0x9142: 337,\n    0x9145: 338,\n    0x9149: 339,\n    0x9151: 340,\n    0x9153: 341,\n    0x9155: 342,\n    0x9156: 343,\n    0x9157: 344,\n    0x9161: 345,\n    0x9162: 346,\n    0x9165: 347,\n    0x9169: 348,\n    0x9171: 349,\n    0x9173: 350,\n    0x9176: 351,\n    0x9177: 352,\n    0x917A: 353,\n    0x9181: 354,\n    0x9185: 355,\n    0x91A1: 356,\n    0x91A2: 357,\n    0x91A5: 358,\n    0x91A9: 359,\n    0x91AB: 360,\n    0x91B1: 361,\n    0x91B3: 362,\n    0x91B5: 363,\n    0x91B7: 364,\n    0x91BC: 365,\n    0x91BD: 366,\n    0x91C1: 367,\n    0x91C5: 368,\n    0x91C9: 369,\n    0x91D6: 370,\n    0x9241: 371,\n    0x9245: 372,\n    0x9249: 373,\n    0x9251: 374,\n    0x9253: 375,\n    0x9255: 376,\n    0x9261: 377,\n    0x9262: 378,\n    0x9265: 379,\n    0x9269: 380,\n    0x9273: 381,\n    0x9275: 382,\n    0x9277: 383,\n    0x9281: 384,\n    0x9282: 385,\n    0x9285: 386,\n    0x9288: 387,\n    0x9289: 388,\n    0x9291: 389,\n    0x9293: 390,\n    0x9295: 391,\n    0x9297: 392,\n    0x92A1: 393,\n    0x92B6: 394,\n    0x92C1: 395,\n    0x92E1: 396,\n    0x92E5: 397,\n    0x92E9: 398,\n    0x92F1: 399,\n    0x92F3: 400,\n    0x9341: 401,\n    0x9342: 402,\n    0x9349: 403,\n    0x9351: 404,\n    0x9353: 405,\n    0x9357: 406,\n    0x9361: 407,\n    0x9362: 408,\n    0x9365: 409,\n    0x9369: 410,\n    0x936A: 411,\n    0x936B: 412,\n    0x9371: 413,\n    0x9373: 414,\n    0x9375: 415,\n    0x9377: 416,\n    0x9378: 417,\n    0x937C: 418,\n    0x9381: 419,\n    0x9385: 420,\n    0x9389: 421,\n    0x93A1: 422,\n    0x93A2: 423,\n    0x93A5: 424,\n    0x93A9: 425,\n    0x93AB: 426,\n    0x93B1: 427,\n    0x93B3: 428,\n    0x93B5: 429,\n    0x93B7: 430,\n    0x93BC: 431,\n    0x9461: 432,\n    0x9462: 433,\n    0x9463: 434,\n    0x9465: 435,\n    0x9468: 436,\n    0x9469: 437,\n    0x946A: 438,\n    0x946B: 439,\n    0x946C: 440,\n    0x9470: 441,\n    0x9471: 442,\n    0x9473: 443,\n    0x9475: 444,\n    0x9476: 445,\n    0x9477: 446,\n    0x9478: 447,\n    0x9479: 448,\n    0x947D: 449,\n    0x9481: 450,\n    0x9482: 451,\n    0x9485: 452,\n    0x9489: 453,\n    0x9491: 454,\n    0x9493: 455,\n    0x9495: 456,\n    0x9496: 457,\n    0x9497: 458,\n    0x94A1: 459,\n    0x94E1: 460,\n    0x94E2: 461,\n    0x94E3: 462,\n    0x94E5: 463,\n    0x94E8: 464,\n    0x94E9: 465,\n    0x94EB: 466,\n    0x94EC: 467,\n    0x94F1: 468,\n    0x94F3: 469,\n    0x94F5: 470,\n    0x94F7: 471,\n    0x94F9: 472,\n    0x94FC: 473,\n    0x9541: 474,\n    0x9542: 475,\n    0x9545: 476,\n    0x9549: 477,\n    0x9551: 478,\n    0x9553: 479,\n    0x9555: 480,\n    0x9556: 481,\n    0x9557: 482,\n    0x9561: 483,\n    0x9565: 484,\n    0x9569: 485,\n    0x9576: 486,\n    0x9577: 487,\n    0x9581: 488,\n    0x9585: 489,\n    0x95A1: 490,\n    0x95A2: 491,\n    0x95A5: 492,\n    0x95A8: 493,\n    0x95A9: 494,\n    0x95AB: 495,\n    0x95AD: 496,\n    0x95B1: 497,\n    0x95B3: 498,\n    0x95B5: 499,\n    0x95B7: 500,\n    0x95B9: 501,\n    0x95BB: 502,\n    0x95C1: 503,\n    0x95C5: 504,\n    0x95C9: 505,\n    0x95E1: 506,\n    0x95F6: 507,\n    0x9641: 508,\n    0x9645: 509,\n    0x9649: 510,\n    0x9651: 511,\n    0x9653: 512,\n    0x9655: 513,\n    0x9661: 514,\n    0x9681: 515,\n    0x9682: 516,\n    0x9685: 517,\n    0x9689: 518,\n    0x9691: 519,\n    0x9693: 520,\n    0x9695: 521,\n    0x9697: 522,\n    0x96A1: 523,\n    0x96B6: 524,\n    0x96C1: 525,\n    0x96D7: 526,\n    0x96E1: 527,\n    0x96E5: 528,\n    0x96E9: 529,\n    0x96F3: 530,\n    0x96F5: 531,\n    0x96F7: 532,\n    0x9741: 533,\n    0x9745: 534,\n    0x9749: 535,\n    0x9751: 536,\n    0x9757: 537,\n    0x9761: 538,\n    0x9762: 539,\n    0x9765: 540,\n    0x9768: 541,\n    0x9769: 542,\n    0x976B: 543,\n    0x9771: 544,\n    0x9773: 545,\n    0x9775: 546,\n    0x9777: 547,\n    0x9781: 548,\n    0x97A1: 549,\n    0x97A2: 550,\n    0x97A5: 551,\n    0x97A8: 552,\n    0x97A9: 553,\n    0x97B1: 554,\n    0x97B3: 555,\n    0x97B5: 556,\n    0x97B6: 557,\n    0x97B7: 558,\n    0x97B8: 559,\n    0x9861: 560,\n    0x9862: 561,\n    0x9865: 562,\n    0x9869: 563,\n    0x9871: 564,\n    0x9873: 565,\n    0x9875: 566,\n    0x9876: 567,\n    0x9877: 568,\n    0x987D: 569,\n    0x9881: 570,\n    0x9882: 571,\n    0x9885: 572,\n    0x9889: 573,\n    0x9891: 574,\n    0x9893: 575,\n    0x9895: 576,\n    0x9896: 577,\n    0x9897: 578,\n    0x98E1: 579,\n    0x98E2: 580,\n    0x98E5: 581,\n    0x98E9: 582,\n    0x98EB: 583,\n    0x98EC: 584,\n    0x98F1: 585,\n    0x98F3: 586,\n    0x98F5: 587,\n    0x98F6: 588,\n    0x98F7: 589,\n    0x98FD: 590,\n    0x9941: 591,\n    0x9942: 592,\n    0x9945: 593,\n    0x9949: 594,\n    0x9951: 595,\n    0x9953: 596,\n    0x9955: 597,\n    0x9956: 598,\n    0x9957: 599,\n    0x9961: 600,\n    0x9976: 601,\n    0x99A1: 602,\n    0x99A2: 603,\n    0x99A5: 604,\n    0x99A9: 605,\n    0x99B7: 606,\n    0x99C1: 607,\n    0x99C9: 608,\n    0x99E1: 609,\n    0x9A41: 610,\n    0x9A45: 611,\n    0x9A81: 612,\n    0x9A82: 613,\n    0x9A85: 614,\n    0x9A89: 615,\n    0x9A90: 616,\n    0x9A91: 617,\n    0x9A97: 618,\n    0x9AC1: 619,\n    0x9AE1: 620,\n    0x9AE5: 621,\n    0x9AE9: 622,\n    0x9AF1: 623,\n    0x9AF3: 624,\n    0x9AF7: 625,\n    0x9B61: 626,\n    0x9B62: 627,\n    0x9B65: 628,\n    0x9B68: 629,\n    0x9B69: 630,\n    0x9B71: 631,\n    0x9B73: 632,\n    0x9B75: 633,\n    0x9B81: 634,\n    0x9B85: 635,\n    0x9B89: 636,\n    0x9B91: 637,\n    0x9B93: 638,\n    0x9BA1: 639,\n    0x9BA5: 640,\n    0x9BA9: 641,\n    0x9BB1: 642,\n    0x9BB3: 643,\n    0x9BB5: 644,\n    0x9BB7: 645,\n    0x9C61: 646,\n    0x9C62: 647,\n    0x9C65: 648,\n    0x9C69: 649,\n    0x9C71: 650,\n    0x9C73: 651,\n    0x9C75: 652,\n    0x9C76: 653,\n    0x9C77: 654,\n    0x9C78: 655,\n    0x9C7C: 656,\n    0x9C7D: 657,\n    0x9C81: 658,\n    0x9C82: 659,\n    0x9C85: 660,\n    0x9C89: 661,\n    0x9C91: 662,\n    0x9C93: 663,\n    0x9C95: 664,\n    0x9C96: 665,\n    0x9C97: 666,\n    0x9CA1: 667,\n    0x9CA2: 668,\n    0x9CA5: 669,\n    0x9CB5: 670,\n    0x9CB7: 671,\n    0x9CE1: 672,\n    0x9CE2: 673,\n    0x9CE5: 674,\n    0x9CE9: 675,\n    0x9CF1: 676,\n    0x9CF3: 677,\n    0x9CF5: 678,\n    0x9CF6: 679,\n    0x9CF7: 680,\n    0x9CFD: 681,\n    0x9D41: 682,\n    0x9D42: 683,\n    0x9D45: 684,\n    0x9D49: 685,\n    0x9D51: 686,\n    0x9D53: 687,\n    0x9D55: 688,\n    0x9D57: 689,\n    0x9D61: 690,\n    0x9D62: 691,\n    0x9D65: 692,\n    0x9D69: 693,\n    0x9D71: 694,\n    0x9D73: 695,\n    0x9D75: 696,\n    0x9D76: 697,\n    0x9D77: 698,\n    0x9D81: 699,\n    0x9D85: 700,\n    0x9D93: 701,\n    0x9D95: 702,\n    0x9DA1: 703,\n    0x9DA2: 704,\n    0x9DA5: 705,\n    0x9DA9: 706,\n    0x9DB1: 707,\n    0x9DB3: 708,\n    0x9DB5: 709,\n    0x9DB7: 710,\n    0x9DC1: 711,\n    0x9DC5: 712,\n    0x9DD7: 713,\n    0x9DF6: 714,\n    0x9E41: 715,\n    0x9E45: 716,\n    0x9E49: 717,\n    0x9E51: 718,\n    0x9E53: 719,\n    0x9E55: 720,\n    0x9E57: 721,\n    0x9E61: 722,\n    0x9E65: 723,\n    0x9E69: 724,\n    0x9E73: 725,\n    0x9E75: 726,\n    0x9E77: 727,\n    0x9E81: 728,\n    0x9E82: 729,\n    0x9E85: 730,\n    0x9E89: 731,\n    0x9E91: 732,\n    0x9E93: 733,\n    0x9E95: 734,\n    0x9E97: 735,\n    0x9EA1: 736,\n    0x9EB6: 737,\n    0x9EC1: 738,\n    0x9EE1: 739,\n    0x9EE2: 740,\n    0x9EE5: 741,\n    0x9EE9: 742,\n    0x9EF1: 743,\n    0x9EF5: 744,\n    0x9EF7: 745,\n    0x9F41: 746,\n    0x9F42: 747,\n    0x9F45: 748,\n    0x9F49: 749,\n    0x9F51: 750,\n    0x9F53: 751,\n    0x9F55: 752,\n    0x9F57: 753,\n    0x9F61: 754,\n    0x9F62: 755,\n    0x9F65: 756,\n    0x9F69: 757,\n    0x9F71: 758,\n    0x9F73: 759,\n    0x9F75: 760,\n    0x9F77: 761,\n    0x9F78: 762,\n    0x9F7B: 763,\n    0x9F7C: 764,\n    0x9FA1: 765,\n    0x9FA2: 766,\n    0x9FA5: 767,\n    0x9FA9: 768,\n    0x9FB1: 769,\n    0x9FB3: 770,\n    0x9FB5: 771,\n    0x9FB7: 772,\n    0xA061: 773,\n    0xA062: 774,\n    0xA065: 775,\n    0xA067: 776,\n    0xA068: 777,\n    0xA069: 778,\n    0xA06A: 779,\n    0xA06B: 780,\n    0xA071: 781,\n    0xA073: 782,\n    0xA075: 783,\n    0xA077: 784,\n    0xA078: 785,\n    0xA07B: 786,\n    0xA07D: 787,\n    0xA081: 788,\n    0xA082: 789,\n    0xA085: 790,\n    0xA089: 791,\n    0xA091: 792,\n    0xA093: 793,\n    0xA095: 794,\n    0xA096: 795,\n    0xA097: 796,\n    0xA098: 797,\n    0xA0A1: 798,\n    0xA0A2: 799,\n    0xA0A9: 800,\n    0xA0B7: 801,\n    0xA0E1: 802,\n    0xA0E2: 803,\n    0xA0E5: 804,\n    0xA0E9: 805,\n    0xA0EB: 806,\n    0xA0F1: 807,\n    0xA0F3: 808,\n    0xA0F5: 809,\n    0xA0F7: 810,\n    0xA0F8: 811,\n    0xA0FD: 812,\n    0xA141: 813,\n    0xA142: 814,\n    0xA145: 815,\n    0xA149: 816,\n    0xA151: 817,\n    0xA153: 818,\n    0xA155: 819,\n    0xA156: 820,\n    0xA157: 821,\n    0xA161: 822,\n    0xA162: 823,\n    0xA165: 824,\n    0xA169: 825,\n    0xA175: 826,\n    0xA176: 827,\n    0xA177: 828,\n    0xA179: 829,\n    0xA181: 830,\n    0xA1A1: 831,\n    0xA1A2: 832,\n    0xA1A4: 833,\n    0xA1A5: 834,\n    0xA1A9: 835,\n    0xA1AB: 836,\n    0xA1B1: 837,\n    0xA1B3: 838,\n    0xA1B5: 839,\n    0xA1B7: 840,\n    0xA1C1: 841,\n    0xA1C5: 842,\n    0xA1D6: 843,\n    0xA1D7: 844,\n    0xA241: 845,\n    0xA245: 846,\n    0xA249: 847,\n    0xA253: 848,\n    0xA255: 849,\n    0xA257: 850,\n    0xA261: 851,\n    0xA265: 852,\n    0xA269: 853,\n    0xA273: 854,\n    0xA275: 855,\n    0xA281: 856,\n    0xA282: 857,\n    0xA283: 858,\n    0xA285: 859,\n    0xA288: 860,\n    0xA289: 861,\n    0xA28A: 862,\n    0xA28B: 863,\n    0xA291: 864,\n    0xA293: 865,\n    0xA295: 866,\n    0xA297: 867,\n    0xA29B: 868,\n    0xA29D: 869,\n    0xA2A1: 870,\n    0xA2A5: 871,\n    0xA2A9: 872,\n    0xA2B3: 873,\n    0xA2B5: 874,\n    0xA2C1: 875,\n    0xA2E1: 876,\n    0xA2E5: 877,\n    0xA2E9: 878,\n    0xA341: 879,\n    0xA345: 880,\n    0xA349: 881,\n    0xA351: 882,\n    0xA355: 883,\n    0xA361: 884,\n    0xA365: 885,\n    0xA369: 886,\n    0xA371: 887,\n    0xA375: 888,\n    0xA3A1: 889,\n    0xA3A2: 890,\n    0xA3A5: 891,\n    0xA3A8: 892,\n    0xA3A9: 893,\n    0xA3AB: 894,\n    0xA3B1: 895,\n    0xA3B3: 896,\n    0xA3B5: 897,\n    0xA3B6: 898,\n    0xA3B7: 899,\n    0xA3B9: 900,\n    0xA3BB: 901,\n    0xA461: 902,\n    0xA462: 903,\n    0xA463: 904,\n    0xA464: 905,\n    0xA465: 906,\n    0xA468: 907,\n    0xA469: 908,\n    0xA46A: 909,\n    0xA46B: 910,\n    0xA46C: 911,\n    0xA471: 912,\n    0xA473: 913,\n    0xA475: 914,\n    0xA477: 915,\n    0xA47B: 916,\n    0xA481: 917,\n    0xA482: 918,\n    0xA485: 919,\n    0xA489: 920,\n    0xA491: 921,\n    0xA493: 922,\n    0xA495: 923,\n    0xA496: 924,\n    0xA497: 925,\n    0xA49B: 926,\n    0xA4A1: 927,\n    0xA4A2: 928,\n    0xA4A5: 929,\n    0xA4B3: 930,\n    0xA4E1: 931,\n    0xA4E2: 932,\n    0xA4E5: 933,\n    0xA4E8: 934,\n    0xA4E9: 935,\n    0xA4EB: 936,\n    0xA4F1: 937,\n    0xA4F3: 938,\n    0xA4F5: 939,\n    0xA4F7: 940,\n    0xA4F8: 941,\n    0xA541: 942,\n    0xA542: 943,\n    0xA545: 944,\n    0xA548: 945,\n    0xA549: 946,\n    0xA551: 947,\n    0xA553: 948,\n    0xA555: 949,\n    0xA556: 950,\n    0xA557: 951,\n    0xA561: 952,\n    0xA562: 953,\n    0xA565: 954,\n    0xA569: 955,\n    0xA573: 956,\n    0xA575: 957,\n    0xA576: 958,\n    0xA577: 959,\n    0xA57B: 960,\n    0xA581: 961,\n    0xA585: 962,\n    0xA5A1: 963,\n    0xA5A2: 964,\n    0xA5A3: 965,\n    0xA5A5: 966,\n    0xA5A9: 967,\n    0xA5B1: 968,\n    0xA5B3: 969,\n    0xA5B5: 970,\n    0xA5B7: 971,\n    0xA5C1: 972,\n    0xA5C5: 973,\n    0xA5D6: 974,\n    0xA5E1: 975,\n    0xA5F6: 976,\n    0xA641: 977,\n    0xA642: 978,\n    0xA645: 979,\n    0xA649: 980,\n    0xA651: 981,\n    0xA653: 982,\n    0xA661: 983,\n    0xA665: 984,\n    0xA681: 985,\n    0xA682: 986,\n    0xA685: 987,\n    0xA688: 988,\n    0xA689: 989,\n    0xA68A: 990,\n    0xA68B: 991,\n    0xA691: 992,\n    0xA693: 993,\n    0xA695: 994,\n    0xA697: 995,\n    0xA69B: 996,\n    0xA69C: 997,\n    0xA6A1: 998,\n    0xA6A9: 999,\n    0xA6B6: 1000,\n    0xA6C1: 1001,\n    0xA6E1: 1002,\n    0xA6E2: 1003,\n    0xA6E5: 1004,\n    0xA6E9: 1005,\n    0xA6F7: 1006,\n    0xA741: 1007,\n    0xA745: 1008,\n    0xA749: 1009,\n    0xA751: 1010,\n    0xA755: 1011,\n    0xA757: 1012,\n    0xA761: 1013,\n    0xA762: 1014,\n    0xA765: 1015,\n    0xA769: 1016,\n    0xA771: 1017,\n    0xA773: 1018,\n    0xA775: 1019,\n    0xA7A1: 1020,\n    0xA7A2: 1021,\n    0xA7A5: 1022,\n    0xA7A9: 1023,\n    0xA7AB: 1024,\n    0xA7B1: 1025,\n    0xA7B3: 1026,\n    0xA7B5: 1027,\n    0xA7B7: 1028,\n    0xA7B8: 1029,\n    0xA7B9: 1030,\n    0xA861: 1031,\n    0xA862: 1032,\n    0xA865: 1033,\n    0xA869: 1034,\n    0xA86B: 1035,\n    0xA871: 1036,\n    0xA873: 1037,\n    0xA875: 1038,\n    0xA876: 1039,\n    0xA877: 1040,\n    0xA87D: 1041,\n    0xA881: 1042,\n    0xA882: 1043,\n    0xA885: 1044,\n    0xA889: 1045,\n    0xA891: 1046,\n    0xA893: 1047,\n    0xA895: 1048,\n    0xA896: 1049,\n    0xA897: 1050,\n    0xA8A1: 1051,\n    0xA8A2: 1052,\n    0xA8B1: 1053,\n    0xA8E1: 1054,\n    0xA8E2: 1055,\n    0xA8E5: 1056,\n    0xA8E8: 1057,\n    0xA8E9: 1058,\n    0xA8F1: 1059,\n    0xA8F5: 1060,\n    0xA8F6: 1061,\n    0xA8F7: 1062,\n    0xA941: 1063,\n    0xA957: 1064,\n    0xA961: 1065,\n    0xA962: 1066,\n    0xA971: 1067,\n    0xA973: 1068,\n    0xA975: 1069,\n    0xA976: 1070,\n    0xA977: 1071,\n    0xA9A1: 1072,\n    0xA9A2: 1073,\n    0xA9A5: 1074,\n    0xA9A9: 1075,\n    0xA9B1: 1076,\n    0xA9B3: 1077,\n    0xA9B7: 1078,\n    0xAA41: 1079,\n    0xAA61: 1080,\n    0xAA77: 1081,\n    0xAA81: 1082,\n    0xAA82: 1083,\n    0xAA85: 1084,\n    0xAA89: 1085,\n    0xAA91: 1086,\n    0xAA95: 1087,\n    0xAA97: 1088,\n    0xAB41: 1089,\n    0xAB57: 1090,\n    0xAB61: 1091,\n    0xAB65: 1092,\n    0xAB69: 1093,\n    0xAB71: 1094,\n    0xAB73: 1095,\n    0xABA1: 1096,\n    0xABA2: 1097,\n    0xABA5: 1098,\n    0xABA9: 1099,\n    0xABB1: 1100,\n    0xABB3: 1101,\n    0xABB5: 1102,\n    0xABB7: 1103,\n    0xAC61: 1104,\n    0xAC62: 1105,\n    0xAC64: 1106,\n    0xAC65: 1107,\n    0xAC68: 1108,\n    0xAC69: 1109,\n    0xAC6A: 1110,\n    0xAC6B: 1111,\n    0xAC71: 1112,\n    0xAC73: 1113,\n    0xAC75: 1114,\n    0xAC76: 1115,\n    0xAC77: 1116,\n    0xAC7B: 1117,\n    0xAC81: 1118,\n    0xAC82: 1119,\n    0xAC85: 1120,\n    0xAC89: 1121,\n    0xAC91: 1122,\n    0xAC93: 1123,\n    0xAC95: 1124,\n    0xAC96: 1125,\n    0xAC97: 1126,\n    0xACA1: 1127,\n    0xACA2: 1128,\n    0xACA5: 1129,\n    0xACA9: 1130,\n    0xACB1: 1131,\n    0xACB3: 1132,\n    0xACB5: 1133,\n    0xACB7: 1134,\n    0xACC1: 1135,\n    0xACC5: 1136,\n    0xACC9: 1137,\n    0xACD1: 1138,\n    0xACD7: 1139,\n    0xACE1: 1140,\n    0xACE2: 1141,\n    0xACE3: 1142,\n    0xACE4: 1143,\n    0xACE5: 1144,\n    0xACE8: 1145,\n    0xACE9: 1146,\n    0xACEB: 1147,\n    0xACEC: 1148,\n    0xACF1: 1149,\n    0xACF3: 1150,\n    0xACF5: 1151,\n    0xACF6: 1152,\n    0xACF7: 1153,\n    0xACFC: 1154,\n    0xAD41: 1155,\n    0xAD42: 1156,\n    0xAD45: 1157,\n    0xAD49: 1158,\n    0xAD51: 1159,\n    0xAD53: 1160,\n    0xAD55: 1161,\n    0xAD56: 1162,\n    0xAD57: 1163,\n    0xAD61: 1164,\n    0xAD62: 1165,\n    0xAD65: 1166,\n    0xAD69: 1167,\n    0xAD71: 1168,\n    0xAD73: 1169,\n    0xAD75: 1170,\n    0xAD76: 1171,\n    0xAD77: 1172,\n    0xAD81: 1173,\n    0xAD85: 1174,\n    0xAD89: 1175,\n    0xAD97: 1176,\n    0xADA1: 1177,\n    0xADA2: 1178,\n    0xADA3: 1179,\n    0xADA5: 1180,\n    0xADA9: 1181,\n    0xADAB: 1182,\n    0xADB1: 1183,\n    0xADB3: 1184,\n    0xADB5: 1185,\n    0xADB7: 1186,\n    0xADBB: 1187,\n    0xADC1: 1188,\n    0xADC2: 1189,\n    0xADC5: 1190,\n    0xADC9: 1191,\n    0xADD7: 1192,\n    0xADE1: 1193,\n    0xADE5: 1194,\n    0xADE9: 1195,\n    0xADF1: 1196,\n    0xADF5: 1197,\n    0xADF6: 1198,\n    0xAE41: 1199,\n    0xAE45: 1200,\n    0xAE49: 1201,\n    0xAE51: 1202,\n    0xAE53: 1203,\n    0xAE55: 1204,\n    0xAE61: 1205,\n    0xAE62: 1206,\n    0xAE65: 1207,\n    0xAE69: 1208,\n    0xAE71: 1209,\n    0xAE73: 1210,\n    0xAE75: 1211,\n    0xAE77: 1212,\n    0xAE81: 1213,\n    0xAE82: 1214,\n    0xAE85: 1215,\n    0xAE88: 1216,\n    0xAE89: 1217,\n    0xAE91: 1218,\n    0xAE93: 1219,\n    0xAE95: 1220,\n    0xAE97: 1221,\n    0xAE99: 1222,\n    0xAE9B: 1223,\n    0xAE9C: 1224,\n    0xAEA1: 1225,\n    0xAEB6: 1226,\n    0xAEC1: 1227,\n    0xAEC2: 1228,\n    0xAEC5: 1229,\n    0xAEC9: 1230,\n    0xAED1: 1231,\n    0xAED7: 1232,\n    0xAEE1: 1233,\n    0xAEE2: 1234,\n    0xAEE5: 1235,\n    0xAEE9: 1236,\n    0xAEF1: 1237,\n    0xAEF3: 1238,\n    0xAEF5: 1239,\n    0xAEF7: 1240,\n    0xAF41: 1241,\n    0xAF42: 1242,\n    0xAF49: 1243,\n    0xAF51: 1244,\n    0xAF55: 1245,\n    0xAF57: 1246,\n    0xAF61: 1247,\n    0xAF62: 1248,\n    0xAF65: 1249,\n    0xAF69: 1250,\n    0xAF6A: 1251,\n    0xAF71: 1252,\n    0xAF73: 1253,\n    0xAF75: 1254,\n    0xAF77: 1255,\n    0xAFA1: 1256,\n    0xAFA2: 1257,\n    0xAFA5: 1258,\n    0xAFA8: 1259,\n    0xAFA9: 1260,\n    0xAFB0: 1261,\n    0xAFB1: 1262,\n    0xAFB3: 1263,\n    0xAFB5: 1264,\n    0xAFB7: 1265,\n    0xAFBC: 1266,\n    0xB061: 1267,\n    0xB062: 1268,\n    0xB064: 1269,\n    0xB065: 1270,\n    0xB069: 1271,\n    0xB071: 1272,\n    0xB073: 1273,\n    0xB076: 1274,\n    0xB077: 1275,\n    0xB07D: 1276,\n    0xB081: 1277,\n    0xB082: 1278,\n    0xB085: 1279,\n    0xB089: 1280,\n    0xB091: 1281,\n    0xB093: 1282,\n    0xB096: 1283,\n    0xB097: 1284,\n    0xB0B7: 1285,\n    0xB0E1: 1286,\n    0xB0E2: 1287,\n    0xB0E5: 1288,\n    0xB0E9: 1289,\n    0xB0EB: 1290,\n    0xB0F1: 1291,\n    0xB0F3: 1292,\n    0xB0F6: 1293,\n    0xB0F7: 1294,\n    0xB141: 1295,\n    0xB145: 1296,\n    0xB149: 1297,\n    0xB185: 1298,\n    0xB1A1: 1299,\n    0xB1A2: 1300,\n    0xB1A5: 1301,\n    0xB1A8: 1302,\n    0xB1A9: 1303,\n    0xB1AB: 1304,\n    0xB1B1: 1305,\n    0xB1B3: 1306,\n    0xB1B7: 1307,\n    0xB1C1: 1308,\n    0xB1C2: 1309,\n    0xB1C5: 1310,\n    0xB1D6: 1311,\n    0xB1E1: 1312,\n    0xB1F6: 1313,\n    0xB241: 1314,\n    0xB245: 1315,\n    0xB249: 1316,\n    0xB251: 1317,\n    0xB253: 1318,\n    0xB261: 1319,\n    0xB281: 1320,\n    0xB282: 1321,\n    0xB285: 1322,\n    0xB289: 1323,\n    0xB291: 1324,\n    0xB293: 1325,\n    0xB297: 1326,\n    0xB2A1: 1327,\n    0xB2B6: 1328,\n    0xB2C1: 1329,\n    0xB2E1: 1330,\n    0xB2E5: 1331,\n    0xB357: 1332,\n    0xB361: 1333,\n    0xB362: 1334,\n    0xB365: 1335,\n    0xB369: 1336,\n    0xB36B: 1337,\n    0xB370: 1338,\n    0xB371: 1339,\n    0xB373: 1340,\n    0xB381: 1341,\n    0xB385: 1342,\n    0xB389: 1343,\n    0xB391: 1344,\n    0xB3A1: 1345,\n    0xB3A2: 1346,\n    0xB3A5: 1347,\n    0xB3A9: 1348,\n    0xB3B1: 1349,\n    0xB3B3: 1350,\n    0xB3B5: 1351,\n    0xB3B7: 1352,\n    0xB461: 1353,\n    0xB462: 1354,\n    0xB465: 1355,\n    0xB466: 1356,\n    0xB467: 1357,\n    0xB469: 1358,\n    0xB46A: 1359,\n    0xB46B: 1360,\n    0xB470: 1361,\n    0xB471: 1362,\n    0xB473: 1363,\n    0xB475: 1364,\n    0xB476: 1365,\n    0xB477: 1366,\n    0xB47B: 1367,\n    0xB47C: 1368,\n    0xB481: 1369,\n    0xB482: 1370,\n    0xB485: 1371,\n    0xB489: 1372,\n    0xB491: 1373,\n    0xB493: 1374,\n    0xB495: 1375,\n    0xB496: 1376,\n    0xB497: 1377,\n    0xB4A1: 1378,\n    0xB4A2: 1379,\n    0xB4A5: 1380,\n    0xB4A9: 1381,\n    0xB4AC: 1382,\n    0xB4B1: 1383,\n    0xB4B3: 1384,\n    0xB4B5: 1385,\n    0xB4B7: 1386,\n    0xB4BB: 1387,\n    0xB4BD: 1388,\n    0xB4C1: 1389,\n    0xB4C5: 1390,\n    0xB4C9: 1391,\n    0xB4D3: 1392,\n    0xB4E1: 1393,\n    0xB4E2: 1394,\n    0xB4E5: 1395,\n    0xB4E6: 1396,\n    0xB4E8: 1397,\n    0xB4E9: 1398,\n    0xB4EA: 1399,\n    0xB4EB: 1400,\n    0xB4F1: 1401,\n    0xB4F3: 1402,\n    0xB4F4: 1403,\n    0xB4F5: 1404,\n    0xB4F6: 1405,\n    0xB4F7: 1406,\n    0xB4F8: 1407,\n    0xB4FA: 1408,\n    0xB4FC: 1409,\n    0xB541: 1410,\n    0xB542: 1411,\n    0xB545: 1412,\n    0xB549: 1413,\n    0xB551: 1414,\n    0xB553: 1415,\n    0xB555: 1416,\n    0xB557: 1417,\n    0xB561: 1418,\n    0xB562: 1419,\n    0xB563: 1420,\n    0xB565: 1421,\n    0xB569: 1422,\n    0xB56B: 1423,\n    0xB56C: 1424,\n    0xB571: 1425,\n    0xB573: 1426,\n    0xB574: 1427,\n    0xB575: 1428,\n    0xB576: 1429,\n    0xB577: 1430,\n    0xB57B: 1431,\n    0xB57C: 1432,\n    0xB57D: 1433,\n    0xB581: 1434,\n    0xB585: 1435,\n    0xB589: 1436,\n    0xB591: 1437,\n    0xB593: 1438,\n    0xB595: 1439,\n    0xB596: 1440,\n    0xB5A1: 1441,\n    0xB5A2: 1442,\n    0xB5A5: 1443,\n    0xB5A9: 1444,\n    0xB5AA: 1445,\n    0xB5AB: 1446,\n    0xB5AD: 1447,\n    0xB5B0: 1448,\n    0xB5B1: 1449,\n    0xB5B3: 1450,\n    0xB5B5: 1451,\n    0xB5B7: 1452,\n    0xB5B9: 1453,\n    0xB5C1: 1454,\n    0xB5C2: 1455,\n    0xB5C5: 1456,\n    0xB5C9: 1457,\n    0xB5D1: 1458,\n    0xB5D3: 1459,\n    0xB5D5: 1460,\n    0xB5D6: 1461,\n    0xB5D7: 1462,\n    0xB5E1: 1463,\n    0xB5E2: 1464,\n    0xB5E5: 1465,\n    0xB5F1: 1466,\n    0xB5F5: 1467,\n    0xB5F7: 1468,\n    0xB641: 1469,\n    0xB642: 1470,\n    0xB645: 1471,\n    0xB649: 1472,\n    0xB651: 1473,\n    0xB653: 1474,\n    0xB655: 1475,\n    0xB657: 1476,\n    0xB661: 1477,\n    0xB662: 1478,\n    0xB665: 1479,\n    0xB669: 1480,\n    0xB671: 1481,\n    0xB673: 1482,\n    0xB675: 1483,\n    0xB677: 1484,\n    0xB681: 1485,\n    0xB682: 1486,\n    0xB685: 1487,\n    0xB689: 1488,\n    0xB68A: 1489,\n    0xB68B: 1490,\n    0xB691: 1491,\n    0xB693: 1492,\n    0xB695: 1493,\n    0xB697: 1494,\n    0xB6A1: 1495,\n    0xB6A2: 1496,\n    0xB6A5: 1497,\n    0xB6A9: 1498,\n    0xB6B1: 1499,\n    0xB6B3: 1500,\n    0xB6B6: 1501,\n    0xB6B7: 1502,\n    0xB6C1: 1503,\n    0xB6C2: 1504,\n    0xB6C5: 1505,\n    0xB6C9: 1506,\n    0xB6D1: 1507,\n    0xB6D3: 1508,\n    0xB6D7: 1509,\n    0xB6E1: 1510,\n    0xB6E2: 1511,\n    0xB6E5: 1512,\n    0xB6E9: 1513,\n    0xB6F1: 1514,\n    0xB6F3: 1515,\n    0xB6F5: 1516,\n    0xB6F7: 1517,\n    0xB741: 1518,\n    0xB742: 1519,\n    0xB745: 1520,\n    0xB749: 1521,\n    0xB751: 1522,\n    0xB753: 1523,\n    0xB755: 1524,\n    0xB757: 1525,\n    0xB759: 1526,\n    0xB761: 1527,\n    0xB762: 1528,\n    0xB765: 1529,\n    0xB769: 1530,\n    0xB76F: 1531,\n    0xB771: 1532,\n    0xB773: 1533,\n    0xB775: 1534,\n    0xB777: 1535,\n    0xB778: 1536,\n    0xB779: 1537,\n    0xB77A: 1538,\n    0xB77B: 1539,\n    0xB77C: 1540,\n    0xB77D: 1541,\n    0xB781: 1542,\n    0xB785: 1543,\n    0xB789: 1544,\n    0xB791: 1545,\n    0xB795: 1546,\n    0xB7A1: 1547,\n    0xB7A2: 1548,\n    0xB7A5: 1549,\n    0xB7A9: 1550,\n    0xB7AA: 1551,\n    0xB7AB: 1552,\n    0xB7B0: 1553,\n    0xB7B1: 1554,\n    0xB7B3: 1555,\n    0xB7B5: 1556,\n    0xB7B6: 1557,\n    0xB7B7: 1558,\n    0xB7B8: 1559,\n    0xB7BC: 1560,\n    0xB861: 1561,\n    0xB862: 1562,\n    0xB865: 1563,\n    0xB867: 1564,\n    0xB868: 1565,\n    0xB869: 1566,\n    0xB86B: 1567,\n    0xB871: 1568,\n    0xB873: 1569,\n    0xB875: 1570,\n    0xB876: 1571,\n    0xB877: 1572,\n    0xB878: 1573,\n    0xB881: 1574,\n    0xB882: 1575,\n    0xB885: 1576,\n    0xB889: 1577,\n    0xB891: 1578,\n    0xB893: 1579,\n    0xB895: 1580,\n    0xB896: 1581,\n    0xB897: 1582,\n    0xB8A1: 1583,\n    0xB8A2: 1584,\n    0xB8A5: 1585,\n    0xB8A7: 1586,\n    0xB8A9: 1587,\n    0xB8B1: 1588,\n    0xB8B7: 1589,\n    0xB8C1: 1590,\n    0xB8C5: 1591,\n    0xB8C9: 1592,\n    0xB8E1: 1593,\n    0xB8E2: 1594,\n    0xB8E5: 1595,\n    0xB8E9: 1596,\n    0xB8EB: 1597,\n    0xB8F1: 1598,\n    0xB8F3: 1599,\n    0xB8F5: 1600,\n    0xB8F7: 1601,\n    0xB8F8: 1602,\n    0xB941: 1603,\n    0xB942: 1604,\n    0xB945: 1605,\n    0xB949: 1606,\n    0xB951: 1607,\n    0xB953: 1608,\n    0xB955: 1609,\n    0xB957: 1610,\n    0xB961: 1611,\n    0xB965: 1612,\n    0xB969: 1613,\n    0xB971: 1614,\n    0xB973: 1615,\n    0xB976: 1616,\n    0xB977: 1617,\n    0xB981: 1618,\n    0xB9A1: 1619,\n    0xB9A2: 1620,\n    0xB9A5: 1621,\n    0xB9A9: 1622,\n    0xB9AB: 1623,\n    0xB9B1: 1624,\n    0xB9B3: 1625,\n    0xB9B5: 1626,\n    0xB9B7: 1627,\n    0xB9B8: 1628,\n    0xB9B9: 1629,\n    0xB9BD: 1630,\n    0xB9C1: 1631,\n    0xB9C2: 1632,\n    0xB9C9: 1633,\n    0xB9D3: 1634,\n    0xB9D5: 1635,\n    0xB9D7: 1636,\n    0xB9E1: 1637,\n    0xB9F6: 1638,\n    0xB9F7: 1639,\n    0xBA41: 1640,\n    0xBA45: 1641,\n    0xBA49: 1642,\n    0xBA51: 1643,\n    0xBA53: 1644,\n    0xBA55: 1645,\n    0xBA57: 1646,\n    0xBA61: 1647,\n    0xBA62: 1648,\n    0xBA65: 1649,\n    0xBA77: 1650,\n    0xBA81: 1651,\n    0xBA82: 1652,\n    0xBA85: 1653,\n    0xBA89: 1654,\n    0xBA8A: 1655,\n    0xBA8B: 1656,\n    0xBA91: 1657,\n    0xBA93: 1658,\n    0xBA95: 1659,\n    0xBA97: 1660,\n    0xBAA1: 1661,\n    0xBAB6: 1662,\n    0xBAC1: 1663,\n    0xBAE1: 1664,\n    0xBAE2: 1665,\n    0xBAE5: 1666,\n    0xBAE9: 1667,\n    0xBAF1: 1668,\n    0xBAF3: 1669,\n    0xBAF5: 1670,\n    0xBB41: 1671,\n    0xBB45: 1672,\n    0xBB49: 1673,\n    0xBB51: 1674,\n    0xBB61: 1675,\n    0xBB62: 1676,\n    0xBB65: 1677,\n    0xBB69: 1678,\n    0xBB71: 1679,\n    0xBB73: 1680,\n    0xBB75: 1681,\n    0xBB77: 1682,\n    0xBBA1: 1683,\n    0xBBA2: 1684,\n    0xBBA5: 1685,\n    0xBBA8: 1686,\n    0xBBA9: 1687,\n    0xBBAB: 1688,\n    0xBBB1: 1689,\n    0xBBB3: 1690,\n    0xBBB5: 1691,\n    0xBBB7: 1692,\n    0xBBB8: 1693,\n    0xBBBB: 1694,\n    0xBBBC: 1695,\n    0xBC61: 1696,\n    0xBC62: 1697,\n    0xBC65: 1698,\n    0xBC67: 1699,\n    0xBC69: 1700,\n    0xBC6C: 1701,\n    0xBC71: 1702,\n    0xBC73: 1703,\n    0xBC75: 1704,\n    0xBC76: 1705,\n    0xBC77: 1706,\n    0xBC81: 1707,\n    0xBC82: 1708,\n    0xBC85: 1709,\n    0xBC89: 1710,\n    0xBC91: 1711,\n    0xBC93: 1712,\n    0xBC95: 1713,\n    0xBC96: 1714,\n    0xBC97: 1715,\n    0xBCA1: 1716,\n    0xBCA5: 1717,\n    0xBCB7: 1718,\n    0xBCE1: 1719,\n    0xBCE2: 1720,\n    0xBCE5: 1721,\n    0xBCE9: 1722,\n    0xBCF1: 1723,\n    0xBCF3: 1724,\n    0xBCF5: 1725,\n    0xBCF6: 1726,\n    0xBCF7: 1727,\n    0xBD41: 1728,\n    0xBD57: 1729,\n    0xBD61: 1730,\n    0xBD76: 1731,\n    0xBDA1: 1732,\n    0xBDA2: 1733,\n    0xBDA5: 1734,\n    0xBDA9: 1735,\n    0xBDB1: 1736,\n    0xBDB3: 1737,\n    0xBDB5: 1738,\n    0xBDB7: 1739,\n    0xBDB9: 1740,\n    0xBDC1: 1741,\n    0xBDC2: 1742,\n    0xBDC9: 1743,\n    0xBDD6: 1744,\n    0xBDE1: 1745,\n    0xBDF6: 1746,\n    0xBE41: 1747,\n    0xBE45: 1748,\n    0xBE49: 1749,\n    0xBE51: 1750,\n    0xBE53: 1751,\n    0xBE77: 1752,\n    0xBE81: 1753,\n    0xBE82: 1754,\n    0xBE85: 1755,\n    0xBE89: 1756,\n    0xBE91: 1757,\n    0xBE93: 1758,\n    0xBE97: 1759,\n    0xBEA1: 1760,\n    0xBEB6: 1761,\n    0xBEB7: 1762,\n    0xBEE1: 1763,\n    0xBF41: 1764,\n    0xBF61: 1765,\n    0xBF71: 1766,\n    0xBF75: 1767,\n    0xBF77: 1768,\n    0xBFA1: 1769,\n    0xBFA2: 1770,\n    0xBFA5: 1771,\n    0xBFA9: 1772,\n    0xBFB1: 1773,\n    0xBFB3: 1774,\n    0xBFB7: 1775,\n    0xBFB8: 1776,\n    0xBFBD: 1777,\n    0xC061: 1778,\n    0xC062: 1779,\n    0xC065: 1780,\n    0xC067: 1781,\n    0xC069: 1782,\n    0xC071: 1783,\n    0xC073: 1784,\n    0xC075: 1785,\n    0xC076: 1786,\n    0xC077: 1787,\n    0xC078: 1788,\n    0xC081: 1789,\n    0xC082: 1790,\n    0xC085: 1791,\n    0xC089: 1792,\n    0xC091: 1793,\n    0xC093: 1794,\n    0xC095: 1795,\n    0xC096: 1796,\n    0xC097: 1797,\n    0xC0A1: 1798,\n    0xC0A5: 1799,\n    0xC0A7: 1800,\n    0xC0A9: 1801,\n    0xC0B1: 1802,\n    0xC0B7: 1803,\n    0xC0E1: 1804,\n    0xC0E2: 1805,\n    0xC0E5: 1806,\n    0xC0E9: 1807,\n    0xC0F1: 1808,\n    0xC0F3: 1809,\n    0xC0F5: 1810,\n    0xC0F6: 1811,\n    0xC0F7: 1812,\n    0xC141: 1813,\n    0xC142: 1814,\n    0xC145: 1815,\n    0xC149: 1816,\n    0xC151: 1817,\n    0xC153: 1818,\n    0xC155: 1819,\n    0xC157: 1820,\n    0xC161: 1821,\n    0xC165: 1822,\n    0xC176: 1823,\n    0xC181: 1824,\n    0xC185: 1825,\n    0xC197: 1826,\n    0xC1A1: 1827,\n    0xC1A2: 1828,\n    0xC1A5: 1829,\n    0xC1A9: 1830,\n    0xC1B1: 1831,\n    0xC1B3: 1832,\n    0xC1B5: 1833,\n    0xC1B7: 1834,\n    0xC1C1: 1835,\n    0xC1C5: 1836,\n    0xC1C9: 1837,\n    0xC1D7: 1838,\n    0xC241: 1839,\n    0xC245: 1840,\n    0xC249: 1841,\n    0xC251: 1842,\n    0xC253: 1843,\n    0xC255: 1844,\n    0xC257: 1845,\n    0xC261: 1846,\n    0xC271: 1847,\n    0xC281: 1848,\n    0xC282: 1849,\n    0xC285: 1850,\n    0xC289: 1851,\n    0xC291: 1852,\n    0xC293: 1853,\n    0xC295: 1854,\n    0xC297: 1855,\n    0xC2A1: 1856,\n    0xC2B6: 1857,\n    0xC2C1: 1858,\n    0xC2C5: 1859,\n    0xC2E1: 1860,\n    0xC2E5: 1861,\n    0xC2E9: 1862,\n    0xC2F1: 1863,\n    0xC2F3: 1864,\n    0xC2F5: 1865,\n    0xC2F7: 1866,\n    0xC341: 1867,\n    0xC345: 1868,\n    0xC349: 1869,\n    0xC351: 1870,\n    0xC357: 1871,\n    0xC361: 1872,\n    0xC362: 1873,\n    0xC365: 1874,\n    0xC369: 1875,\n    0xC371: 1876,\n    0xC373: 1877,\n    0xC375: 1878,\n    0xC377: 1879,\n    0xC3A1: 1880,\n    0xC3A2: 1881,\n    0xC3A5: 1882,\n    0xC3A8: 1883,\n    0xC3A9: 1884,\n    0xC3AA: 1885,\n    0xC3B1: 1886,\n    0xC3B3: 1887,\n    0xC3B5: 1888,\n    0xC3B7: 1889,\n    0xC461: 1890,\n    0xC462: 1891,\n    0xC465: 1892,\n    0xC469: 1893,\n    0xC471: 1894,\n    0xC473: 1895,\n    0xC475: 1896,\n    0xC477: 1897,\n    0xC481: 1898,\n    0xC482: 1899,\n    0xC485: 1900,\n    0xC489: 1901,\n    0xC491: 1902,\n    0xC493: 1903,\n    0xC495: 1904,\n    0xC496: 1905,\n    0xC497: 1906,\n    0xC4A1: 1907,\n    0xC4A2: 1908,\n    0xC4B7: 1909,\n    0xC4E1: 1910,\n    0xC4E2: 1911,\n    0xC4E5: 1912,\n    0xC4E8: 1913,\n    0xC4E9: 1914,\n    0xC4F1: 1915,\n    0xC4F3: 1916,\n    0xC4F5: 1917,\n    0xC4F6: 1918,\n    0xC4F7: 1919,\n    0xC541: 1920,\n    0xC542: 1921,\n    0xC545: 1922,\n    0xC549: 1923,\n    0xC551: 1924,\n    0xC553: 1925,\n    0xC555: 1926,\n    0xC557: 1927,\n    0xC561: 1928,\n    0xC565: 1929,\n    0xC569: 1930,\n    0xC571: 1931,\n    0xC573: 1932,\n    0xC575: 1933,\n    0xC576: 1934,\n    0xC577: 1935,\n    0xC581: 1936,\n    0xC5A1: 1937,\n    0xC5A2: 1938,\n    0xC5A5: 1939,\n    0xC5A9: 1940,\n    0xC5B1: 1941,\n    0xC5B3: 1942,\n    0xC5B5: 1943,\n    0xC5B7: 1944,\n    0xC5C1: 1945,\n    0xC5C2: 1946,\n    0xC5C5: 1947,\n    0xC5C9: 1948,\n    0xC5D1: 1949,\n    0xC5D7: 1950,\n    0xC5E1: 1951,\n    0xC5F7: 1952,\n    0xC641: 1953,\n    0xC649: 1954,\n    0xC661: 1955,\n    0xC681: 1956,\n    0xC682: 1957,\n    0xC685: 1958,\n    0xC689: 1959,\n    0xC691: 1960,\n    0xC693: 1961,\n    0xC695: 1962,\n    0xC697: 1963,\n    0xC6A1: 1964,\n    0xC6A5: 1965,\n    0xC6A9: 1966,\n    0xC6B7: 1967,\n    0xC6C1: 1968,\n    0xC6D7: 1969,\n    0xC6E1: 1970,\n    0xC6E2: 1971,\n    0xC6E5: 1972,\n    0xC6E9: 1973,\n    0xC6F1: 1974,\n    0xC6F3: 1975,\n    0xC6F5: 1976,\n    0xC6F7: 1977,\n    0xC741: 1978,\n    0xC745: 1979,\n    0xC749: 1980,\n    0xC751: 1981,\n    0xC761: 1982,\n    0xC762: 1983,\n    0xC765: 1984,\n    0xC769: 1985,\n    0xC771: 1986,\n    0xC773: 1987,\n    0xC777: 1988,\n    0xC7A1: 1989,\n    0xC7A2: 1990,\n    0xC7A5: 1991,\n    0xC7A9: 1992,\n    0xC7B1: 1993,\n    0xC7B3: 1994,\n    0xC7B5: 1995,\n    0xC7B7: 1996,\n    0xC861: 1997,\n    0xC862: 1998,\n    0xC865: 1999,\n    0xC869: 2000,\n    0xC86A: 2001,\n    0xC871: 2002,\n    0xC873: 2003,\n    0xC875: 2004,\n    0xC876: 2005,\n    0xC877: 2006,\n    0xC881: 2007,\n    0xC882: 2008,\n    0xC885: 2009,\n    0xC889: 2010,\n    0xC891: 2011,\n    0xC893: 2012,\n    0xC895: 2013,\n    0xC896: 2014,\n    0xC897: 2015,\n    0xC8A1: 2016,\n    0xC8B7: 2017,\n    0xC8E1: 2018,\n    0xC8E2: 2019,\n    0xC8E5: 2020,\n    0xC8E9: 2021,\n    0xC8EB: 2022,\n    0xC8F1: 2023,\n    0xC8F3: 2024,\n    0xC8F5: 2025,\n    0xC8F6: 2026,\n    0xC8F7: 2027,\n    0xC941: 2028,\n    0xC942: 2029,\n    0xC945: 2030,\n    0xC949: 2031,\n    0xC951: 2032,\n    0xC953: 2033,\n    0xC955: 2034,\n    0xC957: 2035,\n    0xC961: 2036,\n    0xC965: 2037,\n    0xC976: 2038,\n    0xC981: 2039,\n    0xC985: 2040,\n    0xC9A1: 2041,\n    0xC9A2: 2042,\n    0xC9A5: 2043,\n    0xC9A9: 2044,\n    0xC9B1: 2045,\n    0xC9B3: 2046,\n    0xC9B5: 2047,\n    0xC9B7: 2048,\n    0xC9BC: 2049,\n    0xC9C1: 2050,\n    0xC9C5: 2051,\n    0xC9E1: 2052,\n    0xCA41: 2053,\n    0xCA45: 2054,\n    0xCA55: 2055,\n    0xCA57: 2056,\n    0xCA61: 2057,\n    0xCA81: 2058,\n    0xCA82: 2059,\n    0xCA85: 2060,\n    0xCA89: 2061,\n    0xCA91: 2062,\n    0xCA93: 2063,\n    0xCA95: 2064,\n    0xCA97: 2065,\n    0xCAA1: 2066,\n    0xCAB6: 2067,\n    0xCAC1: 2068,\n    0xCAE1: 2069,\n    0xCAE2: 2070,\n    0xCAE5: 2071,\n    0xCAE9: 2072,\n    0xCAF1: 2073,\n    0xCAF3: 2074,\n    0xCAF7: 2075,\n    0xCB41: 2076,\n    0xCB45: 2077,\n    0xCB49: 2078,\n    0xCB51: 2079,\n    0xCB57: 2080,\n    0xCB61: 2081,\n    0xCB62: 2082,\n    0xCB65: 2083,\n    0xCB68: 2084,\n    0xCB69: 2085,\n    0xCB6B: 2086,\n    0xCB71: 2087,\n    0xCB73: 2088,\n    0xCB75: 2089,\n    0xCB81: 2090,\n    0xCB85: 2091,\n    0xCB89: 2092,\n    0xCB91: 2093,\n    0xCB93: 2094,\n    0xCBA1: 2095,\n    0xCBA2: 2096,\n    0xCBA5: 2097,\n    0xCBA9: 2098,\n    0xCBB1: 2099,\n    0xCBB3: 2100,\n    0xCBB5: 2101,\n    0xCBB7: 2102,\n    0xCC61: 2103,\n    0xCC62: 2104,\n    0xCC63: 2105,\n    0xCC65: 2106,\n    0xCC69: 2107,\n    0xCC6B: 2108,\n    0xCC71: 2109,\n    0xCC73: 2110,\n    0xCC75: 2111,\n    0xCC76: 2112,\n    0xCC77: 2113,\n    0xCC7B: 2114,\n    0xCC81: 2115,\n    0xCC82: 2116,\n    0xCC85: 2117,\n    0xCC89: 2118,\n    0xCC91: 2119,\n    0xCC93: 2120,\n    0xCC95: 2121,\n    0xCC96: 2122,\n    0xCC97: 2123,\n    0xCCA1: 2124,\n    0xCCA2: 2125,\n    0xCCE1: 2126,\n    0xCCE2: 2127,\n    0xCCE5: 2128,\n    0xCCE9: 2129,\n    0xCCF1: 2130,\n    0xCCF3: 2131,\n    0xCCF5: 2132,\n    0xCCF6: 2133,\n    0xCCF7: 2134,\n    0xCD41: 2135,\n    0xCD42: 2136,\n    0xCD45: 2137,\n    0xCD49: 2138,\n    0xCD51: 2139,\n    0xCD53: 2140,\n    0xCD55: 2141,\n    0xCD57: 2142,\n    0xCD61: 2143,\n    0xCD65: 2144,\n    0xCD69: 2145,\n    0xCD71: 2146,\n    0xCD73: 2147,\n    0xCD76: 2148,\n    0xCD77: 2149,\n    0xCD81: 2150,\n    0xCD89: 2151,\n    0xCD93: 2152,\n    0xCD95: 2153,\n    0xCDA1: 2154,\n    0xCDA2: 2155,\n    0xCDA5: 2156,\n    0xCDA9: 2157,\n    0xCDB1: 2158,\n    0xCDB3: 2159,\n    0xCDB5: 2160,\n    0xCDB7: 2161,\n    0xCDC1: 2162,\n    0xCDD7: 2163,\n    0xCE41: 2164,\n    0xCE45: 2165,\n    0xCE61: 2166,\n    0xCE65: 2167,\n    0xCE69: 2168,\n    0xCE73: 2169,\n    0xCE75: 2170,\n    0xCE81: 2171,\n    0xCE82: 2172,\n    0xCE85: 2173,\n    0xCE88: 2174,\n    0xCE89: 2175,\n    0xCE8B: 2176,\n    0xCE91: 2177,\n    0xCE93: 2178,\n    0xCE95: 2179,\n    0xCE97: 2180,\n    0xCEA1: 2181,\n    0xCEB7: 2182,\n    0xCEE1: 2183,\n    0xCEE5: 2184,\n    0xCEE9: 2185,\n    0xCEF1: 2186,\n    0xCEF5: 2187,\n    0xCF41: 2188,\n    0xCF45: 2189,\n    0xCF49: 2190,\n    0xCF51: 2191,\n    0xCF55: 2192,\n    0xCF57: 2193,\n    0xCF61: 2194,\n    0xCF65: 2195,\n    0xCF69: 2196,\n    0xCF71: 2197,\n    0xCF73: 2198,\n    0xCF75: 2199,\n    0xCFA1: 2200,\n    0xCFA2: 2201,\n    0xCFA5: 2202,\n    0xCFA9: 2203,\n    0xCFB1: 2204,\n    0xCFB3: 2205,\n    0xCFB5: 2206,\n    0xCFB7: 2207,\n    0xD061: 2208,\n    0xD062: 2209,\n    0xD065: 2210,\n    0xD069: 2211,\n    0xD06E: 2212,\n    0xD071: 2213,\n    0xD073: 2214,\n    0xD075: 2215,\n    0xD077: 2216,\n    0xD081: 2217,\n    0xD082: 2218,\n    0xD085: 2219,\n    0xD089: 2220,\n    0xD091: 2221,\n    0xD093: 2222,\n    0xD095: 2223,\n    0xD096: 2224,\n    0xD097: 2225,\n    0xD0A1: 2226,\n    0xD0B7: 2227,\n    0xD0E1: 2228,\n    0xD0E2: 2229,\n    0xD0E5: 2230,\n    0xD0E9: 2231,\n    0xD0EB: 2232,\n    0xD0F1: 2233,\n    0xD0F3: 2234,\n    0xD0F5: 2235,\n    0xD0F7: 2236,\n    0xD141: 2237,\n    0xD142: 2238,\n    0xD145: 2239,\n    0xD149: 2240,\n    0xD151: 2241,\n    0xD153: 2242,\n    0xD155: 2243,\n    0xD157: 2244,\n    0xD161: 2245,\n    0xD162: 2246,\n    0xD165: 2247,\n    0xD169: 2248,\n    0xD171: 2249,\n    0xD173: 2250,\n    0xD175: 2251,\n    0xD176: 2252,\n    0xD177: 2253,\n    0xD181: 2254,\n    0xD185: 2255,\n    0xD189: 2256,\n    0xD193: 2257,\n    0xD1A1: 2258,\n    0xD1A2: 2259,\n    0xD1A5: 2260,\n    0xD1A9: 2261,\n    0xD1AE: 2262,\n    0xD1B1: 2263,\n    0xD1B3: 2264,\n    0xD1B5: 2265,\n    0xD1B7: 2266,\n    0xD1BB: 2267,\n    0xD1C1: 2268,\n    0xD1C2: 2269,\n    0xD1C5: 2270,\n    0xD1C9: 2271,\n    0xD1D5: 2272,\n    0xD1D7: 2273,\n    0xD1E1: 2274,\n    0xD1E2: 2275,\n    0xD1E5: 2276,\n    0xD1F5: 2277,\n    0xD1F7: 2278,\n    0xD241: 2279,\n    0xD242: 2280,\n    0xD245: 2281,\n    0xD249: 2282,\n    0xD253: 2283,\n    0xD255: 2284,\n    0xD257: 2285,\n    0xD261: 2286,\n    0xD265: 2287,\n    0xD269: 2288,\n    0xD273: 2289,\n    0xD275: 2290,\n    0xD281: 2291,\n    0xD282: 2292,\n    0xD285: 2293,\n    0xD289: 2294,\n    0xD28E: 2295,\n    0xD291: 2296,\n    0xD295: 2297,\n    0xD297: 2298,\n    0xD2A1: 2299,\n    0xD2A5: 2300,\n    0xD2A9: 2301,\n    0xD2B1: 2302,\n    0xD2B7: 2303,\n    0xD2C1: 2304,\n    0xD2C2: 2305,\n    0xD2C5: 2306,\n    0xD2C9: 2307,\n    0xD2D7: 2308,\n    0xD2E1: 2309,\n    0xD2E2: 2310,\n    0xD2E5: 2311,\n    0xD2E9: 2312,\n    0xD2F1: 2313,\n    0xD2F3: 2314,\n    0xD2F5: 2315,\n    0xD2F7: 2316,\n    0xD341: 2317,\n    0xD342: 2318,\n    0xD345: 2319,\n    0xD349: 2320,\n    0xD351: 2321,\n    0xD355: 2322,\n    0xD357: 2323,\n    0xD361: 2324,\n    0xD362: 2325,\n    0xD365: 2326,\n    0xD367: 2327,\n    0xD368: 2328,\n    0xD369: 2329,\n    0xD36A: 2330,\n    0xD371: 2331,\n    0xD373: 2332,\n    0xD375: 2333,\n    0xD377: 2334,\n    0xD37B: 2335,\n    0xD381: 2336,\n    0xD385: 2337,\n    0xD389: 2338,\n    0xD391: 2339,\n    0xD393: 2340,\n    0xD397: 2341,\n    0xD3A1: 2342,\n    0xD3A2: 2343,\n    0xD3A5: 2344,\n    0xD3A9: 2345,\n    0xD3B1: 2346,\n    0xD3B3: 2347,\n    0xD3B5: 2348,\n    0xD3B7: 2349,\n}\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/johabprober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is mozilla.org code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .chardistribution import JOHABDistributionAnalysis\nfrom .codingstatemachine import CodingStateMachine\nfrom .mbcharsetprober import MultiByteCharSetProber\nfrom .mbcssm import JOHAB_SM_MODEL\n\n\nclass JOHABProber(MultiByteCharSetProber):\n    def __init__(self):\n        super().__init__()\n        self.coding_sm = CodingStateMachine(JOHAB_SM_MODEL)\n        self.distribution_analyzer = JOHABDistributionAnalysis()\n        self.reset()\n\n    @property\n    def charset_name(self):\n        return \"Johab\"\n\n    @property\n    def language(self):\n        return \"Korean\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/jpcntx.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Communicator client code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\n\n# This is hiragana 2-char sequence table, the number in each cell represents its frequency category\n# fmt: off\njp2_char_context = (\n    (0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1),\n    (2, 4, 0, 4, 0, 3, 0, 4, 0, 3, 4, 4, 4, 2, 4, 3, 3, 4, 3, 2, 3, 3, 4, 2, 3, 3, 3, 2, 4, 1, 4, 3, 3, 1, 5, 4, 3, 4, 3, 4, 3, 5, 3, 0, 3, 5, 4, 2, 0, 3, 1, 0, 3, 3, 0, 3, 3, 0, 1, 1, 0, 4, 3, 0, 3, 3, 0, 4, 0, 2, 0, 3, 5, 5, 5, 5, 4, 0, 4, 1, 0, 3, 4),\n    (0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2),\n    (0, 4, 0, 5, 0, 5, 0, 4, 0, 4, 5, 4, 4, 3, 5, 3, 5, 1, 5, 3, 4, 3, 4, 4, 3, 4, 3, 3, 4, 3, 5, 4, 4, 3, 5, 5, 3, 5, 5, 5, 3, 5, 5, 3, 4, 5, 5, 3, 1, 3, 2, 0, 3, 4, 0, 4, 2, 0, 4, 2, 1, 5, 3, 2, 3, 5, 0, 4, 0, 2, 0, 5, 4, 4, 5, 4, 5, 0, 4, 0, 0, 4, 4),\n    (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),\n    (0, 3, 0, 4, 0, 3, 0, 3, 0, 4, 5, 4, 3, 3, 3, 3, 4, 3, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 4, 4, 4, 4, 5, 3, 4, 4, 3, 4, 5, 5, 4, 5, 5, 1, 4, 5, 4, 3, 0, 3, 3, 1, 3, 3, 0, 4, 4, 0, 3, 3, 1, 5, 3, 3, 3, 5, 0, 4, 0, 3, 0, 4, 4, 3, 4, 3, 3, 0, 4, 1, 1, 3, 4),\n    (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),\n    (0, 4, 0, 3, 0, 3, 0, 4, 0, 3, 4, 4, 3, 2, 2, 1, 2, 1, 3, 1, 3, 3, 3, 3, 3, 4, 3, 1, 3, 3, 5, 3, 3, 0, 4, 3, 0, 5, 4, 3, 3, 5, 4, 4, 3, 4, 4, 5, 0, 1, 2, 0, 1, 2, 0, 2, 2, 0, 1, 0, 0, 5, 2, 2, 1, 4, 0, 3, 0, 1, 0, 4, 4, 3, 5, 4, 3, 0, 2, 1, 0, 4, 3),\n    (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),\n    (0, 3, 0, 5, 0, 4, 0, 2, 1, 4, 4, 2, 4, 1, 4, 2, 4, 2, 4, 3, 3, 3, 4, 3, 3, 3, 3, 1, 4, 2, 3, 3, 3, 1, 4, 4, 1, 1, 1, 4, 3, 3, 2, 0, 2, 4, 3, 2, 0, 3, 3, 0, 3, 1, 1, 0, 0, 0, 3, 3, 0, 4, 2, 2, 3, 4, 0, 4, 0, 3, 0, 4, 4, 5, 3, 4, 4, 0, 3, 0, 0, 1, 4),\n    (1, 4, 0, 4, 0, 4, 0, 4, 0, 3, 5, 4, 4, 3, 4, 3, 5, 4, 3, 3, 4, 3, 5, 4, 4, 4, 4, 3, 4, 2, 4, 3, 3, 1, 5, 4, 3, 2, 4, 5, 4, 5, 5, 4, 4, 5, 4, 4, 0, 3, 2, 2, 3, 3, 0, 4, 3, 1, 3, 2, 1, 4, 3, 3, 4, 5, 0, 3, 0, 2, 0, 4, 5, 5, 4, 5, 4, 0, 4, 0, 0, 5, 4),\n    (0, 5, 0, 5, 0, 4, 0, 3, 0, 4, 4, 3, 4, 3, 3, 3, 4, 0, 4, 4, 4, 3, 4, 3, 4, 3, 3, 1, 4, 2, 4, 3, 4, 0, 5, 4, 1, 4, 5, 4, 4, 5, 3, 2, 4, 3, 4, 3, 2, 4, 1, 3, 3, 3, 2, 3, 2, 0, 4, 3, 3, 4, 3, 3, 3, 4, 0, 4, 0, 3, 0, 4, 5, 4, 4, 4, 3, 0, 4, 1, 0, 1, 3),\n    (0, 3, 1, 4, 0, 3, 0, 2, 0, 3, 4, 4, 3, 1, 4, 2, 3, 3, 4, 3, 4, 3, 4, 3, 4, 4, 3, 2, 3, 1, 5, 4, 4, 1, 4, 4, 3, 5, 4, 4, 3, 5, 5, 4, 3, 4, 4, 3, 1, 2, 3, 1, 2, 2, 0, 3, 2, 0, 3, 1, 0, 5, 3, 3, 3, 4, 3, 3, 3, 3, 4, 4, 4, 4, 5, 4, 2, 0, 3, 3, 2, 4, 3),\n    (0, 2, 0, 3, 0, 1, 0, 1, 0, 0, 3, 2, 0, 0, 2, 0, 1, 0, 2, 1, 3, 3, 3, 1, 2, 3, 1, 0, 1, 0, 4, 2, 1, 1, 3, 3, 0, 4, 3, 3, 1, 4, 3, 3, 0, 3, 3, 2, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 4, 1, 0, 2, 3, 2, 2, 2, 1, 3, 3, 3, 4, 4, 3, 2, 0, 3, 1, 0, 3, 3),\n    (0, 4, 0, 4, 0, 3, 0, 3, 0, 4, 4, 4, 3, 3, 3, 3, 3, 3, 4, 3, 4, 2, 4, 3, 4, 3, 3, 2, 4, 3, 4, 5, 4, 1, 4, 5, 3, 5, 4, 5, 3, 5, 4, 0, 3, 5, 5, 3, 1, 3, 3, 2, 2, 3, 0, 3, 4, 1, 3, 3, 2, 4, 3, 3, 3, 4, 0, 4, 0, 3, 0, 4, 5, 4, 4, 5, 3, 0, 4, 1, 0, 3, 4),\n    (0, 2, 0, 3, 0, 3, 0, 0, 0, 2, 2, 2, 1, 0, 1, 0, 0, 0, 3, 0, 3, 0, 3, 0, 1, 3, 1, 0, 3, 1, 3, 3, 3, 1, 3, 3, 3, 0, 1, 3, 1, 3, 4, 0, 0, 3, 1, 1, 0, 3, 2, 0, 0, 0, 0, 1, 3, 0, 1, 0, 0, 3, 3, 2, 0, 3, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 3, 0, 3, 0, 0, 2, 3),\n    (2, 3, 0, 3, 0, 2, 0, 1, 0, 3, 3, 4, 3, 1, 3, 1, 1, 1, 3, 1, 4, 3, 4, 3, 3, 3, 0, 0, 3, 1, 5, 4, 3, 1, 4, 3, 2, 5, 5, 4, 4, 4, 4, 3, 3, 4, 4, 4, 0, 2, 1, 1, 3, 2, 0, 1, 2, 0, 0, 1, 0, 4, 1, 3, 3, 3, 0, 3, 0, 1, 0, 4, 4, 4, 5, 5, 3, 0, 2, 0, 0, 4, 4),\n    (0, 2, 0, 1, 0, 3, 1, 3, 0, 2, 3, 3, 3, 0, 3, 1, 0, 0, 3, 0, 3, 2, 3, 1, 3, 2, 1, 1, 0, 0, 4, 2, 1, 0, 2, 3, 1, 4, 3, 2, 0, 4, 4, 3, 1, 3, 1, 3, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 4, 1, 1, 1, 2, 0, 3, 0, 0, 0, 3, 4, 2, 4, 3, 2, 0, 1, 0, 0, 3, 3),\n    (0, 1, 0, 4, 0, 5, 0, 4, 0, 2, 4, 4, 2, 3, 3, 2, 3, 3, 5, 3, 3, 3, 4, 3, 4, 2, 3, 0, 4, 3, 3, 3, 4, 1, 4, 3, 2, 1, 5, 5, 3, 4, 5, 1, 3, 5, 4, 2, 0, 3, 3, 0, 1, 3, 0, 4, 2, 0, 1, 3, 1, 4, 3, 3, 3, 3, 0, 3, 0, 1, 0, 3, 4, 4, 4, 5, 5, 0, 3, 0, 1, 4, 5),\n    (0, 2, 0, 3, 0, 3, 0, 0, 0, 2, 3, 1, 3, 0, 4, 0, 1, 1, 3, 0, 3, 4, 3, 2, 3, 1, 0, 3, 3, 2, 3, 1, 3, 0, 2, 3, 0, 2, 1, 4, 1, 2, 2, 0, 0, 3, 3, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 2, 2, 0, 3, 2, 1, 3, 3, 0, 2, 0, 2, 0, 0, 3, 3, 1, 2, 4, 0, 3, 0, 2, 2, 3),\n    (2, 4, 0, 5, 0, 4, 0, 4, 0, 2, 4, 4, 4, 3, 4, 3, 3, 3, 1, 2, 4, 3, 4, 3, 4, 4, 5, 0, 3, 3, 3, 3, 2, 0, 4, 3, 1, 4, 3, 4, 1, 4, 4, 3, 3, 4, 4, 3, 1, 2, 3, 0, 4, 2, 0, 4, 1, 0, 3, 3, 0, 4, 3, 3, 3, 4, 0, 4, 0, 2, 0, 3, 5, 3, 4, 5, 2, 0, 3, 0, 0, 4, 5),\n    (0, 3, 0, 4, 0, 1, 0, 1, 0, 1, 3, 2, 2, 1, 3, 0, 3, 0, 2, 0, 2, 0, 3, 0, 2, 0, 0, 0, 1, 0, 1, 1, 0, 0, 3, 1, 0, 0, 0, 4, 0, 3, 1, 0, 2, 1, 3, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 2, 2, 3, 1, 0, 3, 0, 0, 0, 1, 4, 4, 4, 3, 0, 0, 4, 0, 0, 1, 4),\n    (1, 4, 1, 5, 0, 3, 0, 3, 0, 4, 5, 4, 4, 3, 5, 3, 3, 4, 4, 3, 4, 1, 3, 3, 3, 3, 2, 1, 4, 1, 5, 4, 3, 1, 4, 4, 3, 5, 4, 4, 3, 5, 4, 3, 3, 4, 4, 4, 0, 3, 3, 1, 2, 3, 0, 3, 1, 0, 3, 3, 0, 5, 4, 4, 4, 4, 4, 4, 3, 3, 5, 4, 4, 3, 3, 5, 4, 0, 3, 2, 0, 4, 4),\n    (0, 2, 0, 3, 0, 1, 0, 0, 0, 1, 3, 3, 3, 2, 4, 1, 3, 0, 3, 1, 3, 0, 2, 2, 1, 1, 0, 0, 2, 0, 4, 3, 1, 0, 4, 3, 0, 4, 4, 4, 1, 4, 3, 1, 1, 3, 3, 1, 0, 2, 0, 0, 1, 3, 0, 0, 0, 0, 2, 0, 0, 4, 3, 2, 4, 3, 5, 4, 3, 3, 3, 4, 3, 3, 4, 3, 3, 0, 2, 1, 0, 3, 3),\n    (0, 2, 0, 4, 0, 3, 0, 2, 0, 2, 5, 5, 3, 4, 4, 4, 4, 1, 4, 3, 3, 0, 4, 3, 4, 3, 1, 3, 3, 2, 4, 3, 0, 3, 4, 3, 0, 3, 4, 4, 2, 4, 4, 0, 4, 5, 3, 3, 2, 2, 1, 1, 1, 2, 0, 1, 5, 0, 3, 3, 2, 4, 3, 3, 3, 4, 0, 3, 0, 2, 0, 4, 4, 3, 5, 5, 0, 0, 3, 0, 2, 3, 3),\n    (0, 3, 0, 4, 0, 3, 0, 1, 0, 3, 4, 3, 3, 1, 3, 3, 3, 0, 3, 1, 3, 0, 4, 3, 3, 1, 1, 0, 3, 0, 3, 3, 0, 0, 4, 4, 0, 1, 5, 4, 3, 3, 5, 0, 3, 3, 4, 3, 0, 2, 0, 1, 1, 1, 0, 1, 3, 0, 1, 2, 1, 3, 3, 2, 3, 3, 0, 3, 0, 1, 0, 1, 3, 3, 4, 4, 1, 0, 1, 2, 2, 1, 3),\n    (0, 1, 0, 4, 0, 4, 0, 3, 0, 1, 3, 3, 3, 2, 3, 1, 1, 0, 3, 0, 3, 3, 4, 3, 2, 4, 2, 0, 1, 0, 4, 3, 2, 0, 4, 3, 0, 5, 3, 3, 2, 4, 4, 4, 3, 3, 3, 4, 0, 1, 3, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 4, 2, 3, 3, 3, 0, 3, 0, 0, 0, 4, 4, 4, 5, 3, 2, 0, 3, 3, 0, 3, 5),\n    (0, 2, 0, 3, 0, 0, 0, 3, 0, 1, 3, 0, 2, 0, 0, 0, 1, 0, 3, 1, 1, 3, 3, 0, 0, 3, 0, 0, 3, 0, 2, 3, 1, 0, 3, 1, 0, 3, 3, 2, 0, 4, 2, 2, 0, 2, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 2, 0, 1, 0, 1, 0, 0, 0, 1, 3, 1, 2, 0, 0, 0, 1, 0, 0, 1, 4),\n    (0, 3, 0, 3, 0, 5, 0, 1, 0, 2, 4, 3, 1, 3, 3, 2, 1, 1, 5, 2, 1, 0, 5, 1, 2, 0, 0, 0, 3, 3, 2, 2, 3, 2, 4, 3, 0, 0, 3, 3, 1, 3, 3, 0, 2, 5, 3, 4, 0, 3, 3, 0, 1, 2, 0, 2, 2, 0, 3, 2, 0, 2, 2, 3, 3, 3, 0, 2, 0, 1, 0, 3, 4, 4, 2, 5, 4, 0, 3, 0, 0, 3, 5),\n    (0, 3, 0, 3, 0, 3, 0, 1, 0, 3, 3, 3, 3, 0, 3, 0, 2, 0, 2, 1, 1, 0, 2, 0, 1, 0, 0, 0, 2, 1, 0, 0, 1, 0, 3, 2, 0, 0, 3, 3, 1, 2, 3, 1, 0, 3, 3, 0, 0, 1, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 3, 1, 2, 3, 0, 3, 0, 1, 0, 3, 2, 1, 0, 4, 3, 0, 1, 1, 0, 3, 3),\n    (0, 4, 0, 5, 0, 3, 0, 3, 0, 4, 5, 5, 4, 3, 5, 3, 4, 3, 5, 3, 3, 2, 5, 3, 4, 4, 4, 3, 4, 3, 4, 5, 5, 3, 4, 4, 3, 4, 4, 5, 4, 4, 4, 3, 4, 5, 5, 4, 2, 3, 4, 2, 3, 4, 0, 3, 3, 1, 4, 3, 2, 4, 3, 3, 5, 5, 0, 3, 0, 3, 0, 5, 5, 5, 5, 4, 4, 0, 4, 0, 1, 4, 4),\n    (0, 4, 0, 4, 0, 3, 0, 3, 0, 3, 5, 4, 4, 2, 3, 2, 5, 1, 3, 2, 5, 1, 4, 2, 3, 2, 3, 3, 4, 3, 3, 3, 3, 2, 5, 4, 1, 3, 3, 5, 3, 4, 4, 0, 4, 4, 3, 1, 1, 3, 1, 0, 2, 3, 0, 2, 3, 0, 3, 0, 0, 4, 3, 1, 3, 4, 0, 3, 0, 2, 0, 4, 4, 4, 3, 4, 5, 0, 4, 0, 0, 3, 4),\n    (0, 3, 0, 3, 0, 3, 1, 2, 0, 3, 4, 4, 3, 3, 3, 0, 2, 2, 4, 3, 3, 1, 3, 3, 3, 1, 1, 0, 3, 1, 4, 3, 2, 3, 4, 4, 2, 4, 4, 4, 3, 4, 4, 3, 2, 4, 4, 3, 1, 3, 3, 1, 3, 3, 0, 4, 1, 0, 2, 2, 1, 4, 3, 2, 3, 3, 5, 4, 3, 3, 5, 4, 4, 3, 3, 0, 4, 0, 3, 2, 2, 4, 4),\n    (0, 2, 0, 1, 0, 0, 0, 0, 0, 1, 2, 1, 3, 0, 0, 0, 0, 0, 2, 0, 1, 2, 1, 0, 0, 1, 0, 0, 0, 0, 3, 0, 0, 1, 0, 1, 1, 3, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 0, 3, 4, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1),\n    (0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 4, 0, 4, 1, 4, 0, 3, 0, 4, 0, 3, 0, 4, 0, 3, 0, 3, 0, 4, 1, 5, 1, 4, 0, 0, 3, 0, 5, 0, 5, 2, 0, 1, 0, 0, 0, 2, 1, 4, 0, 1, 3, 0, 0, 3, 0, 0, 3, 1, 1, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0),\n    (1, 4, 0, 5, 0, 3, 0, 2, 0, 3, 5, 4, 4, 3, 4, 3, 5, 3, 4, 3, 3, 0, 4, 3, 3, 3, 3, 3, 3, 2, 4, 4, 3, 1, 3, 4, 4, 5, 4, 4, 3, 4, 4, 1, 3, 5, 4, 3, 3, 3, 1, 2, 2, 3, 3, 1, 3, 1, 3, 3, 3, 5, 3, 3, 4, 5, 0, 3, 0, 3, 0, 3, 4, 3, 4, 4, 3, 0, 3, 0, 2, 4, 3),\n    (0, 1, 0, 4, 0, 0, 0, 0, 0, 1, 4, 0, 4, 1, 4, 2, 4, 0, 3, 0, 1, 0, 1, 0, 0, 0, 0, 0, 2, 0, 3, 1, 1, 1, 0, 3, 0, 0, 0, 1, 2, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 3, 0, 0, 0, 0, 3, 2, 0, 2, 2, 0, 1, 0, 0, 0, 2, 3, 2, 3, 3, 0, 0, 0, 0, 2, 1, 0),\n    (0, 5, 1, 5, 0, 3, 0, 3, 0, 5, 4, 4, 5, 1, 5, 3, 3, 0, 4, 3, 4, 3, 5, 3, 4, 3, 3, 2, 4, 3, 4, 3, 3, 0, 3, 3, 1, 4, 4, 3, 4, 4, 4, 3, 4, 5, 5, 3, 2, 3, 1, 1, 3, 3, 1, 3, 1, 1, 3, 3, 2, 4, 5, 3, 3, 5, 0, 4, 0, 3, 0, 4, 4, 3, 5, 3, 3, 0, 3, 4, 0, 4, 3),\n    (0, 5, 0, 5, 0, 3, 0, 2, 0, 4, 4, 3, 5, 2, 4, 3, 3, 3, 4, 4, 4, 3, 5, 3, 5, 3, 3, 1, 4, 0, 4, 3, 3, 0, 3, 3, 0, 4, 4, 4, 4, 5, 4, 3, 3, 5, 5, 3, 2, 3, 1, 2, 3, 2, 0, 1, 0, 0, 3, 2, 2, 4, 4, 3, 1, 5, 0, 4, 0, 3, 0, 4, 3, 1, 3, 2, 1, 0, 3, 3, 0, 3, 3),\n    (0, 4, 0, 5, 0, 5, 0, 4, 0, 4, 5, 5, 5, 3, 4, 3, 3, 2, 5, 4, 4, 3, 5, 3, 5, 3, 4, 0, 4, 3, 4, 4, 3, 2, 4, 4, 3, 4, 5, 4, 4, 5, 5, 0, 3, 5, 5, 4, 1, 3, 3, 2, 3, 3, 1, 3, 1, 0, 4, 3, 1, 4, 4, 3, 4, 5, 0, 4, 0, 2, 0, 4, 3, 4, 4, 3, 3, 0, 4, 0, 0, 5, 5),\n    (0, 4, 0, 4, 0, 5, 0, 1, 1, 3, 3, 4, 4, 3, 4, 1, 3, 0, 5, 1, 3, 0, 3, 1, 3, 1, 1, 0, 3, 0, 3, 3, 4, 0, 4, 3, 0, 4, 4, 4, 3, 4, 4, 0, 3, 5, 4, 1, 0, 3, 0, 0, 2, 3, 0, 3, 1, 0, 3, 1, 0, 3, 2, 1, 3, 5, 0, 3, 0, 1, 0, 3, 2, 3, 3, 4, 4, 0, 2, 2, 0, 4, 4),\n    (2, 4, 0, 5, 0, 4, 0, 3, 0, 4, 5, 5, 4, 3, 5, 3, 5, 3, 5, 3, 5, 2, 5, 3, 4, 3, 3, 4, 3, 4, 5, 3, 2, 1, 5, 4, 3, 2, 3, 4, 5, 3, 4, 1, 2, 5, 4, 3, 0, 3, 3, 0, 3, 2, 0, 2, 3, 0, 4, 1, 0, 3, 4, 3, 3, 5, 0, 3, 0, 1, 0, 4, 5, 5, 5, 4, 3, 0, 4, 2, 0, 3, 5),\n    (0, 5, 0, 4, 0, 4, 0, 2, 0, 5, 4, 3, 4, 3, 4, 3, 3, 3, 4, 3, 4, 2, 5, 3, 5, 3, 4, 1, 4, 3, 4, 4, 4, 0, 3, 5, 0, 4, 4, 4, 4, 5, 3, 1, 3, 4, 5, 3, 3, 3, 3, 3, 3, 3, 0, 2, 2, 0, 3, 3, 2, 4, 3, 3, 3, 5, 3, 4, 1, 3, 3, 5, 3, 2, 0, 0, 0, 0, 4, 3, 1, 3, 3),\n    (0, 1, 0, 3, 0, 3, 0, 1, 0, 1, 3, 3, 3, 2, 3, 3, 3, 0, 3, 0, 0, 0, 3, 1, 3, 0, 0, 0, 2, 2, 2, 3, 0, 0, 3, 2, 0, 1, 2, 4, 1, 3, 3, 0, 0, 3, 3, 3, 0, 1, 0, 0, 2, 1, 0, 0, 3, 0, 3, 1, 0, 3, 0, 0, 1, 3, 0, 2, 0, 1, 0, 3, 3, 1, 3, 3, 0, 0, 1, 1, 0, 3, 3),\n    (0, 2, 0, 3, 0, 2, 1, 4, 0, 2, 2, 3, 1, 1, 3, 1, 1, 0, 2, 0, 3, 1, 2, 3, 1, 3, 0, 0, 1, 0, 4, 3, 2, 3, 3, 3, 1, 4, 2, 3, 3, 3, 3, 1, 0, 3, 1, 4, 0, 1, 1, 0, 1, 2, 0, 1, 1, 0, 1, 1, 0, 3, 1, 3, 2, 2, 0, 1, 0, 0, 0, 2, 3, 3, 3, 1, 0, 0, 0, 0, 0, 2, 3),\n    (0, 5, 0, 4, 0, 5, 0, 2, 0, 4, 5, 5, 3, 3, 4, 3, 3, 1, 5, 4, 4, 2, 4, 4, 4, 3, 4, 2, 4, 3, 5, 5, 4, 3, 3, 4, 3, 3, 5, 5, 4, 5, 5, 1, 3, 4, 5, 3, 1, 4, 3, 1, 3, 3, 0, 3, 3, 1, 4, 3, 1, 4, 5, 3, 3, 5, 0, 4, 0, 3, 0, 5, 3, 3, 1, 4, 3, 0, 4, 0, 1, 5, 3),\n    (0, 5, 0, 5, 0, 4, 0, 2, 0, 4, 4, 3, 4, 3, 3, 3, 3, 3, 5, 4, 4, 4, 4, 4, 4, 5, 3, 3, 5, 2, 4, 4, 4, 3, 4, 4, 3, 3, 4, 4, 5, 5, 3, 3, 4, 3, 4, 3, 3, 4, 3, 3, 3, 3, 1, 2, 2, 1, 4, 3, 3, 5, 4, 4, 3, 4, 0, 4, 0, 3, 0, 4, 4, 4, 4, 4, 1, 0, 4, 2, 0, 2, 4),\n    (0, 4, 0, 4, 0, 3, 0, 1, 0, 3, 5, 2, 3, 0, 3, 0, 2, 1, 4, 2, 3, 3, 4, 1, 4, 3, 3, 2, 4, 1, 3, 3, 3, 0, 3, 3, 0, 0, 3, 3, 3, 5, 3, 3, 3, 3, 3, 2, 0, 2, 0, 0, 2, 0, 0, 2, 0, 0, 1, 0, 0, 3, 1, 2, 2, 3, 0, 3, 0, 2, 0, 4, 4, 3, 3, 4, 1, 0, 3, 0, 0, 2, 4),\n    (0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 2, 0, 0, 0, 0, 0, 1, 0, 2, 0, 1, 0, 0, 0, 0, 0, 3, 1, 3, 0, 3, 2, 0, 0, 0, 1, 0, 3, 2, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 0, 2, 0, 0, 0, 0, 0, 0, 2),\n    (0, 2, 1, 3, 0, 2, 0, 2, 0, 3, 3, 3, 3, 1, 3, 1, 3, 3, 3, 3, 3, 3, 4, 2, 2, 1, 2, 1, 4, 0, 4, 3, 1, 3, 3, 3, 2, 4, 3, 5, 4, 3, 3, 3, 3, 3, 3, 3, 0, 1, 3, 0, 2, 0, 0, 1, 0, 0, 1, 0, 0, 4, 2, 0, 2, 3, 0, 3, 3, 0, 3, 3, 4, 2, 3, 1, 4, 0, 1, 2, 0, 2, 3),\n    (0, 3, 0, 3, 0, 1, 0, 3, 0, 2, 3, 3, 3, 0, 3, 1, 2, 0, 3, 3, 2, 3, 3, 2, 3, 2, 3, 1, 3, 0, 4, 3, 2, 0, 3, 3, 1, 4, 3, 3, 2, 3, 4, 3, 1, 3, 3, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 4, 1, 1, 0, 3, 0, 3, 1, 0, 2, 3, 3, 3, 3, 3, 1, 0, 0, 2, 0, 3, 3),\n    (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 2, 0, 3, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 3, 0, 3, 0, 3, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 3),\n    (0, 2, 0, 3, 1, 3, 0, 3, 0, 2, 3, 3, 3, 1, 3, 1, 3, 1, 3, 1, 3, 3, 3, 1, 3, 0, 2, 3, 1, 1, 4, 3, 3, 2, 3, 3, 1, 2, 2, 4, 1, 3, 3, 0, 1, 4, 2, 3, 0, 1, 3, 0, 3, 0, 0, 1, 3, 0, 2, 0, 0, 3, 3, 2, 1, 3, 0, 3, 0, 2, 0, 3, 4, 4, 4, 3, 1, 0, 3, 0, 0, 3, 3),\n    (0, 2, 0, 1, 0, 2, 0, 0, 0, 1, 3, 2, 2, 1, 3, 0, 1, 1, 3, 0, 3, 2, 3, 1, 2, 0, 2, 0, 1, 1, 3, 3, 3, 0, 3, 3, 1, 1, 2, 3, 2, 3, 3, 1, 2, 3, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 3, 0, 1, 0, 0, 2, 1, 2, 1, 3, 0, 3, 0, 0, 0, 3, 4, 4, 4, 3, 2, 0, 2, 0, 0, 2, 4),\n    (0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 3, 1, 0, 0, 0, 0, 0, 0, 0, 3),\n    (0, 3, 0, 3, 0, 2, 0, 3, 0, 3, 3, 3, 2, 3, 2, 2, 2, 0, 3, 1, 3, 3, 3, 2, 3, 3, 0, 0, 3, 0, 3, 2, 2, 0, 2, 3, 1, 4, 3, 4, 3, 3, 2, 3, 1, 5, 4, 4, 0, 3, 1, 2, 1, 3, 0, 3, 1, 1, 2, 0, 2, 3, 1, 3, 1, 3, 0, 3, 0, 1, 0, 3, 3, 4, 4, 2, 1, 0, 2, 1, 0, 2, 4),\n    (0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 4, 2, 5, 1, 4, 0, 2, 0, 2, 1, 3, 1, 4, 0, 2, 1, 0, 0, 2, 1, 4, 1, 1, 0, 3, 3, 0, 5, 1, 3, 2, 3, 3, 1, 0, 3, 2, 3, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 4, 0, 1, 0, 3, 0, 2, 0, 1, 0, 3, 3, 3, 4, 3, 3, 0, 0, 0, 0, 2, 3),\n    (0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 1, 0, 0, 0, 0, 0, 3),\n    (0, 1, 0, 3, 0, 4, 0, 3, 0, 2, 4, 3, 1, 0, 3, 2, 2, 1, 3, 1, 2, 2, 3, 1, 1, 1, 2, 1, 3, 0, 1, 2, 0, 1, 3, 2, 1, 3, 0, 5, 5, 1, 0, 0, 1, 3, 2, 1, 0, 3, 0, 0, 1, 0, 0, 0, 0, 0, 3, 4, 0, 1, 1, 1, 3, 2, 0, 2, 0, 1, 0, 2, 3, 3, 1, 2, 3, 0, 1, 0, 1, 0, 4),\n    (0, 0, 0, 1, 0, 3, 0, 3, 0, 2, 2, 1, 0, 0, 4, 0, 3, 0, 3, 1, 3, 0, 3, 0, 3, 0, 1, 0, 3, 0, 3, 1, 3, 0, 3, 3, 0, 0, 1, 2, 1, 1, 1, 0, 1, 2, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 1, 2, 0, 0, 2, 0, 0, 0, 0, 2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 4),\n    (0, 0, 0, 3, 0, 3, 0, 0, 0, 0, 3, 1, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 3, 0, 2, 0, 2, 3, 0, 0, 2, 2, 3, 1, 2, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 2, 0, 0, 0, 0, 2, 3),\n    (2, 4, 0, 5, 0, 5, 0, 4, 0, 3, 4, 3, 3, 3, 4, 3, 3, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 2, 3, 0, 5, 5, 4, 1, 5, 4, 3, 1, 5, 4, 3, 4, 4, 3, 3, 4, 3, 3, 0, 3, 2, 0, 2, 3, 0, 3, 0, 0, 3, 3, 0, 5, 3, 2, 3, 3, 0, 3, 0, 3, 0, 3, 4, 5, 4, 5, 3, 0, 4, 3, 0, 3, 4),\n    (0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 3, 4, 3, 2, 3, 2, 3, 0, 4, 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 2, 4, 3, 3, 1, 3, 4, 3, 4, 4, 4, 3, 4, 4, 3, 2, 4, 4, 1, 0, 2, 0, 0, 1, 1, 0, 2, 0, 0, 3, 1, 0, 5, 3, 2, 1, 3, 0, 3, 0, 1, 2, 4, 3, 2, 4, 3, 3, 0, 3, 2, 0, 4, 4),\n    (0, 3, 0, 3, 0, 1, 0, 0, 0, 1, 4, 3, 3, 2, 3, 1, 3, 1, 4, 2, 3, 2, 4, 2, 3, 4, 3, 0, 2, 2, 3, 3, 3, 0, 3, 3, 3, 0, 3, 4, 1, 3, 3, 0, 3, 4, 3, 3, 0, 1, 1, 0, 1, 0, 0, 0, 4, 0, 3, 0, 0, 3, 1, 2, 1, 3, 0, 4, 0, 1, 0, 4, 3, 3, 4, 3, 3, 0, 2, 0, 0, 3, 3),\n    (0, 3, 0, 4, 0, 1, 0, 3, 0, 3, 4, 3, 3, 0, 3, 3, 3, 1, 3, 1, 3, 3, 4, 3, 3, 3, 0, 0, 3, 1, 5, 3, 3, 1, 3, 3, 2, 5, 4, 3, 3, 4, 5, 3, 2, 5, 3, 4, 0, 1, 0, 0, 0, 0, 0, 2, 0, 0, 1, 1, 0, 4, 2, 2, 1, 3, 0, 3, 0, 2, 0, 4, 4, 3, 5, 3, 2, 0, 1, 1, 0, 3, 4),\n    (0, 5, 0, 4, 0, 5, 0, 2, 0, 4, 4, 3, 3, 2, 3, 3, 3, 1, 4, 3, 4, 1, 5, 3, 4, 3, 4, 0, 4, 2, 4, 3, 4, 1, 5, 4, 0, 4, 4, 4, 4, 5, 4, 1, 3, 5, 4, 2, 1, 4, 1, 1, 3, 2, 0, 3, 1, 0, 3, 2, 1, 4, 3, 3, 3, 4, 0, 4, 0, 3, 0, 4, 4, 4, 3, 3, 3, 0, 4, 2, 0, 3, 4),\n    (1, 4, 0, 4, 0, 3, 0, 1, 0, 3, 3, 3, 1, 1, 3, 3, 2, 2, 3, 3, 1, 0, 3, 2, 2, 1, 2, 0, 3, 1, 2, 1, 2, 0, 3, 2, 0, 2, 2, 3, 3, 4, 3, 0, 3, 3, 1, 2, 0, 1, 1, 3, 1, 2, 0, 0, 3, 0, 1, 1, 0, 3, 2, 2, 3, 3, 0, 3, 0, 0, 0, 2, 3, 3, 4, 3, 3, 0, 1, 0, 0, 1, 4),\n    (0, 4, 0, 4, 0, 4, 0, 0, 0, 3, 4, 4, 3, 1, 4, 2, 3, 2, 3, 3, 3, 1, 4, 3, 4, 0, 3, 0, 4, 2, 3, 3, 2, 2, 5, 4, 2, 1, 3, 4, 3, 4, 3, 1, 3, 3, 4, 2, 0, 2, 1, 0, 3, 3, 0, 0, 2, 0, 3, 1, 0, 4, 4, 3, 4, 3, 0, 4, 0, 1, 0, 2, 4, 4, 4, 4, 4, 0, 3, 2, 0, 3, 3),\n    (0, 0, 0, 1, 0, 4, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 3, 2, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 2),\n    (0, 2, 0, 3, 0, 4, 0, 4, 0, 1, 3, 3, 3, 0, 4, 0, 2, 1, 2, 1, 1, 1, 2, 0, 3, 1, 1, 0, 1, 0, 3, 1, 0, 0, 3, 3, 2, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 2, 0, 2, 2, 0, 3, 1, 0, 0, 1, 0, 1, 1, 0, 1, 2, 0, 3, 0, 0, 0, 0, 1, 0, 0, 3, 3, 4, 3, 1, 0, 1, 0, 3, 0, 2),\n    (0, 0, 0, 3, 0, 5, 0, 0, 0, 0, 1, 0, 2, 0, 3, 1, 0, 1, 3, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 4, 0, 0, 0, 2, 3, 0, 1, 4, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 3, 0, 0, 0, 0, 0, 3),\n    (0, 2, 0, 5, 0, 5, 0, 1, 0, 2, 4, 3, 3, 2, 5, 1, 3, 2, 3, 3, 3, 0, 4, 1, 2, 0, 3, 0, 4, 0, 2, 2, 1, 1, 5, 3, 0, 0, 1, 4, 2, 3, 2, 0, 3, 3, 3, 2, 0, 2, 4, 1, 1, 2, 0, 1, 1, 0, 3, 1, 0, 1, 3, 1, 2, 3, 0, 2, 0, 0, 0, 1, 3, 5, 4, 4, 4, 0, 3, 0, 0, 1, 3),\n    (0, 4, 0, 5, 0, 4, 0, 4, 0, 4, 5, 4, 3, 3, 4, 3, 3, 3, 4, 3, 4, 4, 5, 3, 4, 5, 4, 2, 4, 2, 3, 4, 3, 1, 4, 4, 1, 3, 5, 4, 4, 5, 5, 4, 4, 5, 5, 5, 2, 3, 3, 1, 4, 3, 1, 3, 3, 0, 3, 3, 1, 4, 3, 4, 4, 4, 0, 3, 0, 4, 0, 3, 3, 4, 4, 5, 0, 0, 4, 3, 0, 4, 5),\n    (0, 4, 0, 4, 0, 3, 0, 3, 0, 3, 4, 4, 4, 3, 3, 2, 4, 3, 4, 3, 4, 3, 5, 3, 4, 3, 2, 1, 4, 2, 4, 4, 3, 1, 3, 4, 2, 4, 5, 5, 3, 4, 5, 4, 1, 5, 4, 3, 0, 3, 2, 2, 3, 2, 1, 3, 1, 0, 3, 3, 3, 5, 3, 3, 3, 5, 4, 4, 2, 3, 3, 4, 3, 3, 3, 2, 1, 0, 3, 2, 1, 4, 3),\n    (0, 4, 0, 5, 0, 4, 0, 3, 0, 3, 5, 5, 3, 2, 4, 3, 4, 0, 5, 4, 4, 1, 4, 4, 4, 3, 3, 3, 4, 3, 5, 5, 2, 3, 3, 4, 1, 2, 5, 5, 3, 5, 5, 2, 3, 5, 5, 4, 0, 3, 2, 0, 3, 3, 1, 1, 5, 1, 4, 1, 0, 4, 3, 2, 3, 5, 0, 4, 0, 3, 0, 5, 4, 3, 4, 3, 0, 0, 4, 1, 0, 4, 4),\n    (1, 3, 0, 4, 0, 2, 0, 2, 0, 2, 5, 5, 3, 3, 3, 3, 3, 0, 4, 2, 3, 4, 4, 4, 3, 4, 0, 0, 3, 4, 5, 4, 3, 3, 3, 3, 2, 5, 5, 4, 5, 5, 5, 4, 3, 5, 5, 5, 1, 3, 1, 0, 1, 0, 0, 3, 2, 0, 4, 2, 0, 5, 2, 3, 2, 4, 1, 3, 0, 3, 0, 4, 5, 4, 5, 4, 3, 0, 4, 2, 0, 5, 4),\n    (0, 3, 0, 4, 0, 5, 0, 3, 0, 3, 4, 4, 3, 2, 3, 2, 3, 3, 3, 3, 3, 2, 4, 3, 3, 2, 2, 0, 3, 3, 3, 3, 3, 1, 3, 3, 3, 0, 4, 4, 3, 4, 4, 1, 1, 4, 4, 2, 0, 3, 1, 0, 1, 1, 0, 4, 1, 0, 2, 3, 1, 3, 3, 1, 3, 4, 0, 3, 0, 1, 0, 3, 1, 3, 0, 0, 1, 0, 2, 0, 0, 4, 4),\n    (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),\n    (0, 3, 0, 3, 0, 2, 0, 3, 0, 1, 5, 4, 3, 3, 3, 1, 4, 2, 1, 2, 3, 4, 4, 2, 4, 4, 5, 0, 3, 1, 4, 3, 4, 0, 4, 3, 3, 3, 2, 3, 2, 5, 3, 4, 3, 2, 2, 3, 0, 0, 3, 0, 2, 1, 0, 1, 2, 0, 0, 0, 0, 2, 1, 1, 3, 1, 0, 2, 0, 4, 0, 3, 4, 4, 4, 5, 2, 0, 2, 0, 0, 1, 3),\n    (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 4, 2, 1, 1, 0, 1, 0, 3, 2, 0, 0, 3, 1, 1, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1, 4, 0, 4, 2, 1, 0, 0, 0, 0, 0, 1),\n    (0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 3, 1, 0, 0, 0, 2, 0, 2, 1, 0, 0, 1, 2, 1, 0, 1, 1, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 0, 0, 0, 0, 0, 1, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2),\n    (0, 4, 0, 4, 0, 4, 0, 3, 0, 4, 4, 3, 4, 2, 4, 3, 2, 0, 4, 4, 4, 3, 5, 3, 5, 3, 3, 2, 4, 2, 4, 3, 4, 3, 1, 4, 0, 2, 3, 4, 4, 4, 3, 3, 3, 4, 4, 4, 3, 4, 1, 3, 4, 3, 2, 1, 2, 1, 3, 3, 3, 4, 4, 3, 3, 5, 0, 4, 0, 3, 0, 4, 3, 3, 3, 2, 1, 0, 3, 0, 0, 3, 3),\n    (0, 4, 0, 3, 0, 3, 0, 3, 0, 3, 5, 5, 3, 3, 3, 3, 4, 3, 4, 3, 3, 3, 4, 4, 4, 3, 3, 3, 3, 4, 3, 5, 3, 3, 1, 3, 2, 4, 5, 5, 5, 5, 4, 3, 4, 5, 5, 3, 2, 2, 3, 3, 3, 3, 2, 3, 3, 1, 2, 3, 2, 4, 3, 3, 3, 4, 0, 4, 0, 2, 0, 4, 3, 2, 2, 1, 2, 0, 3, 0, 0, 4, 1),\n)\n# fmt: on\n\n\nclass JapaneseContextAnalysis:\n    NUM_OF_CATEGORY = 6\n    DONT_KNOW = -1\n    ENOUGH_REL_THRESHOLD = 100\n    MAX_REL_THRESHOLD = 1000\n    MINIMUM_DATA_THRESHOLD = 4\n\n    def __init__(self):\n        self._total_rel = None\n        self._rel_sample = None\n        self._need_to_skip_char_num = None\n        self._last_char_order = None\n        self._done = None\n        self.reset()\n\n    def reset(self):\n        self._total_rel = 0  # total sequence received\n        # category counters, each integer counts sequence in its category\n        self._rel_sample = [0] * self.NUM_OF_CATEGORY\n        # if last byte in current buffer is not the last byte of a character,\n        # we need to know how many bytes to skip in next buffer\n        self._need_to_skip_char_num = 0\n        self._last_char_order = -1  # The order of previous char\n        # If this flag is set to True, detection is done and conclusion has\n        # been made\n        self._done = False\n\n    def feed(self, byte_str, num_bytes):\n        if self._done:\n            return\n\n        # The buffer we got is byte oriented, and a character may span in more than one\n        # buffers. In case the last one or two byte in last buffer is not\n        # complete, we record how many byte needed to complete that character\n        # and skip these bytes here.  We can choose to record those bytes as\n        # well and analyse the character once it is complete, but since a\n        # character will not make much difference, by simply skipping\n        # this character will simply our logic and improve performance.\n        i = self._need_to_skip_char_num\n        while i < num_bytes:\n            order, char_len = self.get_order(byte_str[i : i + 2])\n            i += char_len\n            if i > num_bytes:\n                self._need_to_skip_char_num = i - num_bytes\n                self._last_char_order = -1\n            else:\n                if (order != -1) and (self._last_char_order != -1):\n                    self._total_rel += 1\n                    if self._total_rel > self.MAX_REL_THRESHOLD:\n                        self._done = True\n                        break\n                    self._rel_sample[\n                        jp2_char_context[self._last_char_order][order]\n                    ] += 1\n                self._last_char_order = order\n\n    def got_enough_data(self):\n        return self._total_rel > self.ENOUGH_REL_THRESHOLD\n\n    def get_confidence(self):\n        # This is just one way to calculate confidence. It works well for me.\n        if self._total_rel > self.MINIMUM_DATA_THRESHOLD:\n            return (self._total_rel - self._rel_sample[0]) / self._total_rel\n        return self.DONT_KNOW\n\n    def get_order(self, _):\n        return -1, 1\n\n\nclass SJISContextAnalysis(JapaneseContextAnalysis):\n    def __init__(self):\n        super().__init__()\n        self._charset_name = \"SHIFT_JIS\"\n\n    @property\n    def charset_name(self):\n        return self._charset_name\n\n    def get_order(self, byte_str):\n        if not byte_str:\n            return -1, 1\n        # find out current char's byte length\n        first_char = byte_str[0]\n        if (0x81 <= first_char <= 0x9F) or (0xE0 <= first_char <= 0xFC):\n            char_len = 2\n            if (first_char == 0x87) or (0xFA <= first_char <= 0xFC):\n                self._charset_name = \"CP932\"\n        else:\n            char_len = 1\n\n        # return its order if it is hiragana\n        if len(byte_str) > 1:\n            second_char = byte_str[1]\n            if (first_char == 202) and (0x9F <= second_char <= 0xF1):\n                return second_char - 0x9F, char_len\n\n        return -1, char_len\n\n\nclass EUCJPContextAnalysis(JapaneseContextAnalysis):\n    def get_order(self, byte_str):\n        if not byte_str:\n            return -1, 1\n        # find out current char's byte length\n        first_char = byte_str[0]\n        if (first_char == 0x8E) or (0xA1 <= first_char <= 0xFE):\n            char_len = 2\n        elif first_char == 0x8F:\n            char_len = 3\n        else:\n            char_len = 1\n\n        # return its order if it is hiragana\n        if len(byte_str) > 1:\n            second_char = byte_str[1]\n            if (first_char == 0xA4) and (0xA1 <= second_char <= 0xF3):\n                return second_char - 0xA1, char_len\n\n        return -1, char_len\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/langbulgarianmodel.py",
    "content": "from pip._vendor.chardet.sbcharsetprober import SingleByteCharSetModel\n\n# 3: Positive\n# 2: Likely\n# 1: Unlikely\n# 0: Negative\n\nBULGARIAN_LANG_MODEL = {\n    63: {  # 'e'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 0,  # 'а'\n        18: 1,  # 'б'\n        9: 1,  # 'в'\n        20: 1,  # 'г'\n        11: 1,  # 'д'\n        3: 1,  # 'е'\n        23: 1,  # 'ж'\n        15: 1,  # 'з'\n        2: 0,  # 'и'\n        26: 1,  # 'й'\n        12: 1,  # 'к'\n        10: 1,  # 'л'\n        14: 1,  # 'м'\n        6: 1,  # 'н'\n        4: 1,  # 'о'\n        13: 1,  # 'п'\n        7: 1,  # 'р'\n        8: 1,  # 'с'\n        5: 1,  # 'т'\n        19: 0,  # 'у'\n        29: 1,  # 'ф'\n        25: 1,  # 'х'\n        22: 0,  # 'ц'\n        21: 1,  # 'ч'\n        27: 1,  # 'ш'\n        24: 1,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    45: {  # '\\xad'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 1,  # 'Б'\n        35: 1,  # 'В'\n        43: 0,  # 'Г'\n        37: 1,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 1,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 0,  # 'Л'\n        38: 1,  # 'М'\n        36: 0,  # 'Н'\n        41: 1,  # 'О'\n        30: 1,  # 'П'\n        39: 1,  # 'Р'\n        28: 1,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 1,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 0,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 0,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 0,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 0,  # 'л'\n        14: 0,  # 'м'\n        6: 0,  # 'н'\n        4: 0,  # 'о'\n        13: 0,  # 'п'\n        7: 0,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 0,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    31: {  # 'А'\n        63: 0,  # 'e'\n        45: 1,  # '\\xad'\n        31: 1,  # 'А'\n        32: 1,  # 'Б'\n        35: 2,  # 'В'\n        43: 1,  # 'Г'\n        37: 2,  # 'Д'\n        44: 2,  # 'Е'\n        55: 1,  # 'Ж'\n        47: 2,  # 'З'\n        40: 1,  # 'И'\n        59: 1,  # 'Й'\n        33: 1,  # 'К'\n        46: 2,  # 'Л'\n        38: 1,  # 'М'\n        36: 2,  # 'Н'\n        41: 1,  # 'О'\n        30: 2,  # 'П'\n        39: 2,  # 'Р'\n        28: 2,  # 'С'\n        34: 2,  # 'Т'\n        51: 1,  # 'У'\n        48: 2,  # 'Ф'\n        49: 1,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        54: 1,  # 'Ш'\n        57: 2,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 1,  # 'Я'\n        1: 1,  # 'а'\n        18: 2,  # 'б'\n        9: 2,  # 'в'\n        20: 2,  # 'г'\n        11: 2,  # 'д'\n        3: 1,  # 'е'\n        23: 1,  # 'ж'\n        15: 2,  # 'з'\n        2: 0,  # 'и'\n        26: 2,  # 'й'\n        12: 2,  # 'к'\n        10: 3,  # 'л'\n        14: 2,  # 'м'\n        6: 3,  # 'н'\n        4: 0,  # 'о'\n        13: 2,  # 'п'\n        7: 2,  # 'р'\n        8: 2,  # 'с'\n        5: 2,  # 'т'\n        19: 1,  # 'у'\n        29: 2,  # 'ф'\n        25: 1,  # 'х'\n        22: 1,  # 'ц'\n        21: 1,  # 'ч'\n        27: 1,  # 'ш'\n        24: 0,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    32: {  # 'Б'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 2,  # 'А'\n        32: 2,  # 'Б'\n        35: 1,  # 'В'\n        43: 1,  # 'Г'\n        37: 2,  # 'Д'\n        44: 1,  # 'Е'\n        55: 1,  # 'Ж'\n        47: 2,  # 'З'\n        40: 1,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 1,  # 'М'\n        36: 2,  # 'Н'\n        41: 2,  # 'О'\n        30: 1,  # 'П'\n        39: 1,  # 'Р'\n        28: 2,  # 'С'\n        34: 2,  # 'Т'\n        51: 1,  # 'У'\n        48: 2,  # 'Ф'\n        49: 1,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 1,  # 'Щ'\n        61: 2,  # 'Ъ'\n        60: 1,  # 'Ю'\n        56: 1,  # 'Я'\n        1: 3,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 1,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 2,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 2,  # 'л'\n        14: 0,  # 'м'\n        6: 0,  # 'н'\n        4: 3,  # 'о'\n        13: 0,  # 'п'\n        7: 2,  # 'р'\n        8: 1,  # 'с'\n        5: 0,  # 'т'\n        19: 2,  # 'у'\n        29: 0,  # 'ф'\n        25: 1,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 3,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 1,  # 'ю'\n        16: 2,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    35: {  # 'В'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 2,  # 'А'\n        32: 1,  # 'Б'\n        35: 1,  # 'В'\n        43: 0,  # 'Г'\n        37: 1,  # 'Д'\n        44: 2,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 2,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 1,  # 'М'\n        36: 1,  # 'Н'\n        41: 1,  # 'О'\n        30: 1,  # 'П'\n        39: 2,  # 'Р'\n        28: 2,  # 'С'\n        34: 1,  # 'Т'\n        51: 1,  # 'У'\n        48: 2,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 1,  # 'Ъ'\n        60: 1,  # 'Ю'\n        56: 2,  # 'Я'\n        1: 3,  # 'а'\n        18: 1,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 1,  # 'д'\n        3: 3,  # 'е'\n        23: 1,  # 'ж'\n        15: 2,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 1,  # 'к'\n        10: 2,  # 'л'\n        14: 1,  # 'м'\n        6: 2,  # 'н'\n        4: 2,  # 'о'\n        13: 1,  # 'п'\n        7: 2,  # 'р'\n        8: 2,  # 'с'\n        5: 2,  # 'т'\n        19: 1,  # 'у'\n        29: 0,  # 'ф'\n        25: 1,  # 'х'\n        22: 0,  # 'ц'\n        21: 2,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 1,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    43: {  # 'Г'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 2,  # 'А'\n        32: 1,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 1,  # 'Д'\n        44: 2,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 1,  # 'З'\n        40: 1,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 0,  # 'М'\n        36: 1,  # 'Н'\n        41: 1,  # 'О'\n        30: 0,  # 'П'\n        39: 1,  # 'Р'\n        28: 1,  # 'С'\n        34: 0,  # 'Т'\n        51: 1,  # 'У'\n        48: 1,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 1,  # 'Щ'\n        61: 1,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 2,  # 'а'\n        18: 1,  # 'б'\n        9: 1,  # 'в'\n        20: 0,  # 'г'\n        11: 1,  # 'д'\n        3: 3,  # 'е'\n        23: 1,  # 'ж'\n        15: 0,  # 'з'\n        2: 2,  # 'и'\n        26: 0,  # 'й'\n        12: 1,  # 'к'\n        10: 2,  # 'л'\n        14: 1,  # 'м'\n        6: 1,  # 'н'\n        4: 2,  # 'о'\n        13: 0,  # 'п'\n        7: 2,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 2,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 1,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 1,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    37: {  # 'Д'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 2,  # 'А'\n        32: 1,  # 'Б'\n        35: 2,  # 'В'\n        43: 1,  # 'Г'\n        37: 2,  # 'Д'\n        44: 2,  # 'Е'\n        55: 2,  # 'Ж'\n        47: 1,  # 'З'\n        40: 2,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 1,  # 'М'\n        36: 1,  # 'Н'\n        41: 2,  # 'О'\n        30: 2,  # 'П'\n        39: 1,  # 'Р'\n        28: 2,  # 'С'\n        34: 1,  # 'Т'\n        51: 1,  # 'У'\n        48: 1,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 1,  # 'Ъ'\n        60: 1,  # 'Ю'\n        56: 1,  # 'Я'\n        1: 3,  # 'а'\n        18: 0,  # 'б'\n        9: 2,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 3,  # 'е'\n        23: 3,  # 'ж'\n        15: 1,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 1,  # 'л'\n        14: 1,  # 'м'\n        6: 2,  # 'н'\n        4: 3,  # 'о'\n        13: 0,  # 'п'\n        7: 2,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 2,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 2,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    44: {  # 'Е'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 1,  # 'А'\n        32: 1,  # 'Б'\n        35: 2,  # 'В'\n        43: 1,  # 'Г'\n        37: 1,  # 'Д'\n        44: 1,  # 'Е'\n        55: 1,  # 'Ж'\n        47: 1,  # 'З'\n        40: 1,  # 'И'\n        59: 1,  # 'Й'\n        33: 2,  # 'К'\n        46: 2,  # 'Л'\n        38: 1,  # 'М'\n        36: 2,  # 'Н'\n        41: 2,  # 'О'\n        30: 1,  # 'П'\n        39: 2,  # 'Р'\n        28: 2,  # 'С'\n        34: 2,  # 'Т'\n        51: 1,  # 'У'\n        48: 2,  # 'Ф'\n        49: 1,  # 'Х'\n        53: 2,  # 'Ц'\n        50: 1,  # 'Ч'\n        54: 1,  # 'Ш'\n        57: 1,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 1,  # 'Я'\n        1: 0,  # 'а'\n        18: 1,  # 'б'\n        9: 2,  # 'в'\n        20: 1,  # 'г'\n        11: 2,  # 'д'\n        3: 0,  # 'е'\n        23: 1,  # 'ж'\n        15: 1,  # 'з'\n        2: 0,  # 'и'\n        26: 1,  # 'й'\n        12: 2,  # 'к'\n        10: 2,  # 'л'\n        14: 2,  # 'м'\n        6: 2,  # 'н'\n        4: 0,  # 'о'\n        13: 1,  # 'п'\n        7: 2,  # 'р'\n        8: 2,  # 'с'\n        5: 1,  # 'т'\n        19: 1,  # 'у'\n        29: 1,  # 'ф'\n        25: 1,  # 'х'\n        22: 0,  # 'ц'\n        21: 1,  # 'ч'\n        27: 1,  # 'ш'\n        24: 1,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 1,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    55: {  # 'Ж'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 1,  # 'А'\n        32: 0,  # 'Б'\n        35: 1,  # 'В'\n        43: 0,  # 'Г'\n        37: 1,  # 'Д'\n        44: 1,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 1,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 1,  # 'Н'\n        41: 1,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 1,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 2,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 1,  # 'д'\n        3: 2,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 2,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 0,  # 'л'\n        14: 0,  # 'м'\n        6: 0,  # 'н'\n        4: 2,  # 'о'\n        13: 1,  # 'п'\n        7: 1,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 1,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 1,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    47: {  # 'З'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 2,  # 'А'\n        32: 1,  # 'Б'\n        35: 1,  # 'В'\n        43: 1,  # 'Г'\n        37: 1,  # 'Д'\n        44: 1,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 1,  # 'З'\n        40: 1,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 1,  # 'М'\n        36: 2,  # 'Н'\n        41: 1,  # 'О'\n        30: 1,  # 'П'\n        39: 1,  # 'Р'\n        28: 1,  # 'С'\n        34: 1,  # 'Т'\n        51: 1,  # 'У'\n        48: 0,  # 'Ф'\n        49: 1,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 1,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 1,  # 'Я'\n        1: 3,  # 'а'\n        18: 1,  # 'б'\n        9: 2,  # 'в'\n        20: 1,  # 'г'\n        11: 2,  # 'д'\n        3: 2,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 1,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 2,  # 'л'\n        14: 1,  # 'м'\n        6: 1,  # 'н'\n        4: 1,  # 'о'\n        13: 0,  # 'п'\n        7: 1,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 1,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 1,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    40: {  # 'И'\n        63: 0,  # 'e'\n        45: 1,  # '\\xad'\n        31: 1,  # 'А'\n        32: 1,  # 'Б'\n        35: 1,  # 'В'\n        43: 1,  # 'Г'\n        37: 1,  # 'Д'\n        44: 2,  # 'Е'\n        55: 1,  # 'Ж'\n        47: 2,  # 'З'\n        40: 1,  # 'И'\n        59: 1,  # 'Й'\n        33: 2,  # 'К'\n        46: 2,  # 'Л'\n        38: 2,  # 'М'\n        36: 2,  # 'Н'\n        41: 1,  # 'О'\n        30: 1,  # 'П'\n        39: 2,  # 'Р'\n        28: 2,  # 'С'\n        34: 2,  # 'Т'\n        51: 0,  # 'У'\n        48: 1,  # 'Ф'\n        49: 1,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        54: 1,  # 'Ш'\n        57: 1,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 2,  # 'Я'\n        1: 1,  # 'а'\n        18: 1,  # 'б'\n        9: 3,  # 'в'\n        20: 2,  # 'г'\n        11: 1,  # 'д'\n        3: 1,  # 'е'\n        23: 0,  # 'ж'\n        15: 3,  # 'з'\n        2: 0,  # 'и'\n        26: 1,  # 'й'\n        12: 1,  # 'к'\n        10: 2,  # 'л'\n        14: 2,  # 'м'\n        6: 2,  # 'н'\n        4: 0,  # 'о'\n        13: 1,  # 'п'\n        7: 2,  # 'р'\n        8: 2,  # 'с'\n        5: 2,  # 'т'\n        19: 0,  # 'у'\n        29: 1,  # 'ф'\n        25: 1,  # 'х'\n        22: 1,  # 'ц'\n        21: 1,  # 'ч'\n        27: 1,  # 'ш'\n        24: 1,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    59: {  # 'Й'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 1,  # 'Д'\n        44: 1,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 1,  # 'М'\n        36: 1,  # 'Н'\n        41: 1,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 1,  # 'С'\n        34: 1,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 1,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 1,  # 'Я'\n        1: 0,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 1,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 0,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 0,  # 'л'\n        14: 0,  # 'м'\n        6: 0,  # 'н'\n        4: 2,  # 'о'\n        13: 0,  # 'п'\n        7: 0,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 0,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    33: {  # 'К'\n        63: 0,  # 'e'\n        45: 1,  # '\\xad'\n        31: 2,  # 'А'\n        32: 1,  # 'Б'\n        35: 1,  # 'В'\n        43: 1,  # 'Г'\n        37: 1,  # 'Д'\n        44: 1,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 1,  # 'З'\n        40: 2,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 0,  # 'М'\n        36: 2,  # 'Н'\n        41: 2,  # 'О'\n        30: 2,  # 'П'\n        39: 1,  # 'Р'\n        28: 2,  # 'С'\n        34: 1,  # 'Т'\n        51: 1,  # 'У'\n        48: 1,  # 'Ф'\n        49: 1,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 1,  # 'Ъ'\n        60: 1,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 0,  # 'б'\n        9: 1,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 2,  # 'е'\n        23: 1,  # 'ж'\n        15: 0,  # 'з'\n        2: 2,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 2,  # 'л'\n        14: 1,  # 'м'\n        6: 2,  # 'н'\n        4: 3,  # 'о'\n        13: 0,  # 'п'\n        7: 3,  # 'р'\n        8: 1,  # 'с'\n        5: 0,  # 'т'\n        19: 2,  # 'у'\n        29: 0,  # 'ф'\n        25: 1,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 1,  # 'ш'\n        24: 0,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 2,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    46: {  # 'Л'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 2,  # 'А'\n        32: 1,  # 'Б'\n        35: 1,  # 'В'\n        43: 2,  # 'Г'\n        37: 1,  # 'Д'\n        44: 2,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 1,  # 'З'\n        40: 2,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 0,  # 'М'\n        36: 1,  # 'Н'\n        41: 2,  # 'О'\n        30: 1,  # 'П'\n        39: 0,  # 'Р'\n        28: 1,  # 'С'\n        34: 1,  # 'Т'\n        51: 1,  # 'У'\n        48: 0,  # 'Ф'\n        49: 1,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 1,  # 'Ъ'\n        60: 1,  # 'Ю'\n        56: 1,  # 'Я'\n        1: 2,  # 'а'\n        18: 0,  # 'б'\n        9: 1,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 2,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 0,  # 'л'\n        14: 0,  # 'м'\n        6: 0,  # 'н'\n        4: 2,  # 'о'\n        13: 0,  # 'п'\n        7: 0,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 2,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 2,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    38: {  # 'М'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 2,  # 'А'\n        32: 1,  # 'Б'\n        35: 2,  # 'В'\n        43: 0,  # 'Г'\n        37: 1,  # 'Д'\n        44: 1,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 1,  # 'З'\n        40: 2,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 1,  # 'М'\n        36: 1,  # 'Н'\n        41: 2,  # 'О'\n        30: 1,  # 'П'\n        39: 1,  # 'Р'\n        28: 2,  # 'С'\n        34: 1,  # 'Т'\n        51: 1,  # 'У'\n        48: 1,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 1,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 1,  # 'Я'\n        1: 3,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 2,  # 'л'\n        14: 0,  # 'м'\n        6: 2,  # 'н'\n        4: 3,  # 'о'\n        13: 0,  # 'п'\n        7: 1,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 2,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 2,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    36: {  # 'Н'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 2,  # 'А'\n        32: 2,  # 'Б'\n        35: 1,  # 'В'\n        43: 1,  # 'Г'\n        37: 2,  # 'Д'\n        44: 2,  # 'Е'\n        55: 1,  # 'Ж'\n        47: 1,  # 'З'\n        40: 2,  # 'И'\n        59: 1,  # 'Й'\n        33: 2,  # 'К'\n        46: 1,  # 'Л'\n        38: 1,  # 'М'\n        36: 1,  # 'Н'\n        41: 2,  # 'О'\n        30: 1,  # 'П'\n        39: 1,  # 'Р'\n        28: 2,  # 'С'\n        34: 2,  # 'Т'\n        51: 1,  # 'У'\n        48: 1,  # 'Ф'\n        49: 1,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        54: 1,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 1,  # 'Ъ'\n        60: 1,  # 'Ю'\n        56: 1,  # 'Я'\n        1: 3,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 1,  # 'г'\n        11: 0,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 0,  # 'л'\n        14: 0,  # 'м'\n        6: 0,  # 'н'\n        4: 3,  # 'о'\n        13: 0,  # 'п'\n        7: 0,  # 'р'\n        8: 0,  # 'с'\n        5: 1,  # 'т'\n        19: 1,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 1,  # 'ш'\n        24: 0,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 2,  # 'ю'\n        16: 2,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    41: {  # 'О'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 1,  # 'А'\n        32: 1,  # 'Б'\n        35: 2,  # 'В'\n        43: 1,  # 'Г'\n        37: 2,  # 'Д'\n        44: 1,  # 'Е'\n        55: 1,  # 'Ж'\n        47: 1,  # 'З'\n        40: 1,  # 'И'\n        59: 1,  # 'Й'\n        33: 2,  # 'К'\n        46: 2,  # 'Л'\n        38: 2,  # 'М'\n        36: 2,  # 'Н'\n        41: 2,  # 'О'\n        30: 1,  # 'П'\n        39: 2,  # 'Р'\n        28: 2,  # 'С'\n        34: 2,  # 'Т'\n        51: 1,  # 'У'\n        48: 1,  # 'Ф'\n        49: 1,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 1,  # 'Ч'\n        54: 1,  # 'Ш'\n        57: 1,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 1,  # 'Я'\n        1: 1,  # 'а'\n        18: 2,  # 'б'\n        9: 2,  # 'в'\n        20: 2,  # 'г'\n        11: 1,  # 'д'\n        3: 1,  # 'е'\n        23: 1,  # 'ж'\n        15: 1,  # 'з'\n        2: 0,  # 'и'\n        26: 1,  # 'й'\n        12: 2,  # 'к'\n        10: 2,  # 'л'\n        14: 1,  # 'м'\n        6: 1,  # 'н'\n        4: 0,  # 'о'\n        13: 2,  # 'п'\n        7: 2,  # 'р'\n        8: 2,  # 'с'\n        5: 3,  # 'т'\n        19: 1,  # 'у'\n        29: 1,  # 'ф'\n        25: 1,  # 'х'\n        22: 1,  # 'ц'\n        21: 2,  # 'ч'\n        27: 0,  # 'ш'\n        24: 2,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    30: {  # 'П'\n        63: 0,  # 'e'\n        45: 1,  # '\\xad'\n        31: 2,  # 'А'\n        32: 1,  # 'Б'\n        35: 1,  # 'В'\n        43: 1,  # 'Г'\n        37: 1,  # 'Д'\n        44: 1,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 1,  # 'З'\n        40: 2,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 1,  # 'М'\n        36: 1,  # 'Н'\n        41: 2,  # 'О'\n        30: 2,  # 'П'\n        39: 2,  # 'Р'\n        28: 2,  # 'С'\n        34: 1,  # 'Т'\n        51: 2,  # 'У'\n        48: 1,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        54: 1,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 1,  # 'Ъ'\n        60: 1,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 2,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 2,  # 'и'\n        26: 0,  # 'й'\n        12: 1,  # 'к'\n        10: 3,  # 'л'\n        14: 0,  # 'м'\n        6: 1,  # 'н'\n        4: 3,  # 'о'\n        13: 0,  # 'п'\n        7: 3,  # 'р'\n        8: 1,  # 'с'\n        5: 1,  # 'т'\n        19: 2,  # 'у'\n        29: 1,  # 'ф'\n        25: 1,  # 'х'\n        22: 0,  # 'ц'\n        21: 1,  # 'ч'\n        27: 1,  # 'ш'\n        24: 0,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 1,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    39: {  # 'Р'\n        63: 0,  # 'e'\n        45: 1,  # '\\xad'\n        31: 2,  # 'А'\n        32: 1,  # 'Б'\n        35: 1,  # 'В'\n        43: 2,  # 'Г'\n        37: 2,  # 'Д'\n        44: 2,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 1,  # 'З'\n        40: 2,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 0,  # 'Л'\n        38: 1,  # 'М'\n        36: 1,  # 'Н'\n        41: 2,  # 'О'\n        30: 2,  # 'П'\n        39: 1,  # 'Р'\n        28: 1,  # 'С'\n        34: 1,  # 'Т'\n        51: 1,  # 'У'\n        48: 1,  # 'Ф'\n        49: 1,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 1,  # 'Ъ'\n        60: 1,  # 'Ю'\n        56: 1,  # 'Я'\n        1: 3,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 2,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 2,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 0,  # 'л'\n        14: 0,  # 'м'\n        6: 1,  # 'н'\n        4: 3,  # 'о'\n        13: 0,  # 'п'\n        7: 0,  # 'р'\n        8: 1,  # 'с'\n        5: 0,  # 'т'\n        19: 3,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 1,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    28: {  # 'С'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 3,  # 'А'\n        32: 2,  # 'Б'\n        35: 2,  # 'В'\n        43: 1,  # 'Г'\n        37: 2,  # 'Д'\n        44: 2,  # 'Е'\n        55: 1,  # 'Ж'\n        47: 1,  # 'З'\n        40: 2,  # 'И'\n        59: 0,  # 'Й'\n        33: 2,  # 'К'\n        46: 1,  # 'Л'\n        38: 1,  # 'М'\n        36: 1,  # 'Н'\n        41: 2,  # 'О'\n        30: 2,  # 'П'\n        39: 1,  # 'Р'\n        28: 2,  # 'С'\n        34: 2,  # 'Т'\n        51: 1,  # 'У'\n        48: 1,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 1,  # 'Ъ'\n        60: 1,  # 'Ю'\n        56: 1,  # 'Я'\n        1: 3,  # 'а'\n        18: 1,  # 'б'\n        9: 2,  # 'в'\n        20: 1,  # 'г'\n        11: 1,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 2,  # 'к'\n        10: 3,  # 'л'\n        14: 2,  # 'м'\n        6: 1,  # 'н'\n        4: 3,  # 'о'\n        13: 3,  # 'п'\n        7: 2,  # 'р'\n        8: 0,  # 'с'\n        5: 3,  # 'т'\n        19: 2,  # 'у'\n        29: 2,  # 'ф'\n        25: 1,  # 'х'\n        22: 1,  # 'ц'\n        21: 1,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 3,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 1,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    34: {  # 'Т'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 2,  # 'А'\n        32: 2,  # 'Б'\n        35: 1,  # 'В'\n        43: 0,  # 'Г'\n        37: 1,  # 'Д'\n        44: 2,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 2,  # 'И'\n        59: 0,  # 'Й'\n        33: 2,  # 'К'\n        46: 1,  # 'Л'\n        38: 1,  # 'М'\n        36: 1,  # 'Н'\n        41: 2,  # 'О'\n        30: 1,  # 'П'\n        39: 2,  # 'Р'\n        28: 2,  # 'С'\n        34: 1,  # 'Т'\n        51: 1,  # 'У'\n        48: 1,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 1,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 1,  # 'Я'\n        1: 3,  # 'а'\n        18: 1,  # 'б'\n        9: 1,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 2,  # 'и'\n        26: 0,  # 'й'\n        12: 1,  # 'к'\n        10: 1,  # 'л'\n        14: 0,  # 'м'\n        6: 0,  # 'н'\n        4: 3,  # 'о'\n        13: 0,  # 'п'\n        7: 3,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 2,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 1,  # 'ю'\n        16: 2,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    51: {  # 'У'\n        63: 0,  # 'e'\n        45: 1,  # '\\xad'\n        31: 1,  # 'А'\n        32: 1,  # 'Б'\n        35: 1,  # 'В'\n        43: 1,  # 'Г'\n        37: 1,  # 'Д'\n        44: 2,  # 'Е'\n        55: 1,  # 'Ж'\n        47: 1,  # 'З'\n        40: 1,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 1,  # 'М'\n        36: 1,  # 'Н'\n        41: 0,  # 'О'\n        30: 1,  # 'П'\n        39: 1,  # 'Р'\n        28: 1,  # 'С'\n        34: 2,  # 'Т'\n        51: 0,  # 'У'\n        48: 1,  # 'Ф'\n        49: 1,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        54: 1,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 1,  # 'а'\n        18: 1,  # 'б'\n        9: 2,  # 'в'\n        20: 1,  # 'г'\n        11: 1,  # 'д'\n        3: 2,  # 'е'\n        23: 1,  # 'ж'\n        15: 1,  # 'з'\n        2: 2,  # 'и'\n        26: 1,  # 'й'\n        12: 2,  # 'к'\n        10: 1,  # 'л'\n        14: 1,  # 'м'\n        6: 2,  # 'н'\n        4: 2,  # 'о'\n        13: 1,  # 'п'\n        7: 1,  # 'р'\n        8: 2,  # 'с'\n        5: 1,  # 'т'\n        19: 1,  # 'у'\n        29: 0,  # 'ф'\n        25: 1,  # 'х'\n        22: 0,  # 'ц'\n        21: 2,  # 'ч'\n        27: 1,  # 'ш'\n        24: 0,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    48: {  # 'Ф'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 2,  # 'А'\n        32: 1,  # 'Б'\n        35: 1,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 1,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 2,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 0,  # 'М'\n        36: 1,  # 'Н'\n        41: 1,  # 'О'\n        30: 2,  # 'П'\n        39: 1,  # 'Р'\n        28: 2,  # 'С'\n        34: 1,  # 'Т'\n        51: 1,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 2,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 2,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 2,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 2,  # 'л'\n        14: 0,  # 'м'\n        6: 0,  # 'н'\n        4: 2,  # 'о'\n        13: 0,  # 'п'\n        7: 2,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 1,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 1,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    49: {  # 'Х'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 1,  # 'А'\n        32: 0,  # 'Б'\n        35: 1,  # 'В'\n        43: 1,  # 'Г'\n        37: 1,  # 'Д'\n        44: 1,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 1,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 1,  # 'Л'\n        38: 1,  # 'М'\n        36: 1,  # 'Н'\n        41: 1,  # 'О'\n        30: 1,  # 'П'\n        39: 1,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 1,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 2,  # 'а'\n        18: 0,  # 'б'\n        9: 1,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 2,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 2,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 1,  # 'л'\n        14: 1,  # 'м'\n        6: 0,  # 'н'\n        4: 2,  # 'о'\n        13: 0,  # 'п'\n        7: 2,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 2,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 1,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    53: {  # 'Ц'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 1,  # 'А'\n        32: 0,  # 'Б'\n        35: 1,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 1,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 2,  # 'И'\n        59: 0,  # 'Й'\n        33: 2,  # 'К'\n        46: 1,  # 'Л'\n        38: 1,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 1,  # 'Р'\n        28: 2,  # 'С'\n        34: 0,  # 'Т'\n        51: 1,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 2,  # 'а'\n        18: 0,  # 'б'\n        9: 2,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 2,  # 'е'\n        23: 0,  # 'ж'\n        15: 1,  # 'з'\n        2: 2,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 0,  # 'л'\n        14: 0,  # 'м'\n        6: 0,  # 'н'\n        4: 1,  # 'о'\n        13: 0,  # 'п'\n        7: 1,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 1,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 1,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    50: {  # 'Ч'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 2,  # 'А'\n        32: 1,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 1,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 1,  # 'З'\n        40: 1,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 0,  # 'М'\n        36: 1,  # 'Н'\n        41: 1,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 1,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 2,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 3,  # 'е'\n        23: 1,  # 'ж'\n        15: 0,  # 'з'\n        2: 2,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 1,  # 'л'\n        14: 0,  # 'м'\n        6: 0,  # 'н'\n        4: 2,  # 'о'\n        13: 0,  # 'п'\n        7: 1,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 2,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 0,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    54: {  # 'Ш'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 1,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 1,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 1,  # 'З'\n        40: 1,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 1,  # 'Н'\n        41: 1,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 1,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 2,  # 'а'\n        18: 0,  # 'б'\n        9: 2,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 2,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 2,  # 'и'\n        26: 0,  # 'й'\n        12: 1,  # 'к'\n        10: 1,  # 'л'\n        14: 1,  # 'м'\n        6: 1,  # 'н'\n        4: 2,  # 'о'\n        13: 1,  # 'п'\n        7: 1,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 2,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 1,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 0,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    57: {  # 'Щ'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 1,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 1,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 1,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 1,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 2,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 2,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 1,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 0,  # 'л'\n        14: 0,  # 'м'\n        6: 0,  # 'н'\n        4: 1,  # 'о'\n        13: 0,  # 'п'\n        7: 1,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 1,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    61: {  # 'Ъ'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 1,  # 'Б'\n        35: 1,  # 'В'\n        43: 0,  # 'Г'\n        37: 1,  # 'Д'\n        44: 0,  # 'Е'\n        55: 1,  # 'Ж'\n        47: 1,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 2,  # 'Л'\n        38: 1,  # 'М'\n        36: 1,  # 'Н'\n        41: 0,  # 'О'\n        30: 1,  # 'П'\n        39: 2,  # 'Р'\n        28: 1,  # 'С'\n        34: 1,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 1,  # 'Х'\n        53: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        54: 1,  # 'Ш'\n        57: 1,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 0,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 0,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 0,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 1,  # 'л'\n        14: 0,  # 'м'\n        6: 1,  # 'н'\n        4: 0,  # 'о'\n        13: 0,  # 'п'\n        7: 1,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 0,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    60: {  # 'Ю'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 1,  # 'А'\n        32: 1,  # 'Б'\n        35: 0,  # 'В'\n        43: 1,  # 'Г'\n        37: 1,  # 'Д'\n        44: 0,  # 'Е'\n        55: 1,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 0,  # 'М'\n        36: 1,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 1,  # 'Р'\n        28: 1,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 0,  # 'а'\n        18: 1,  # 'б'\n        9: 1,  # 'в'\n        20: 2,  # 'г'\n        11: 1,  # 'д'\n        3: 0,  # 'е'\n        23: 2,  # 'ж'\n        15: 1,  # 'з'\n        2: 1,  # 'и'\n        26: 0,  # 'й'\n        12: 1,  # 'к'\n        10: 1,  # 'л'\n        14: 1,  # 'м'\n        6: 1,  # 'н'\n        4: 0,  # 'о'\n        13: 1,  # 'п'\n        7: 1,  # 'р'\n        8: 1,  # 'с'\n        5: 1,  # 'т'\n        19: 0,  # 'у'\n        29: 0,  # 'ф'\n        25: 1,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    56: {  # 'Я'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 1,  # 'Б'\n        35: 1,  # 'В'\n        43: 1,  # 'Г'\n        37: 1,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 1,  # 'Л'\n        38: 1,  # 'М'\n        36: 1,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 1,  # 'С'\n        34: 2,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 0,  # 'а'\n        18: 1,  # 'б'\n        9: 1,  # 'в'\n        20: 1,  # 'г'\n        11: 1,  # 'д'\n        3: 0,  # 'е'\n        23: 0,  # 'ж'\n        15: 1,  # 'з'\n        2: 1,  # 'и'\n        26: 1,  # 'й'\n        12: 1,  # 'к'\n        10: 1,  # 'л'\n        14: 2,  # 'м'\n        6: 2,  # 'н'\n        4: 0,  # 'о'\n        13: 2,  # 'п'\n        7: 1,  # 'р'\n        8: 1,  # 'с'\n        5: 1,  # 'т'\n        19: 0,  # 'у'\n        29: 0,  # 'ф'\n        25: 1,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 1,  # 'ш'\n        24: 0,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 1,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    1: {  # 'а'\n        63: 1,  # 'e'\n        45: 1,  # '\\xad'\n        31: 1,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 1,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 1,  # 'а'\n        18: 3,  # 'б'\n        9: 3,  # 'в'\n        20: 3,  # 'г'\n        11: 3,  # 'д'\n        3: 3,  # 'е'\n        23: 3,  # 'ж'\n        15: 3,  # 'з'\n        2: 3,  # 'и'\n        26: 3,  # 'й'\n        12: 3,  # 'к'\n        10: 3,  # 'л'\n        14: 3,  # 'м'\n        6: 3,  # 'н'\n        4: 2,  # 'о'\n        13: 3,  # 'п'\n        7: 3,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 3,  # 'у'\n        29: 3,  # 'ф'\n        25: 3,  # 'х'\n        22: 3,  # 'ц'\n        21: 3,  # 'ч'\n        27: 3,  # 'ш'\n        24: 3,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 1,  # 'ю'\n        16: 3,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    18: {  # 'б'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 0,  # 'б'\n        9: 3,  # 'в'\n        20: 1,  # 'г'\n        11: 2,  # 'д'\n        3: 3,  # 'е'\n        23: 1,  # 'ж'\n        15: 1,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 1,  # 'к'\n        10: 3,  # 'л'\n        14: 2,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 1,  # 'п'\n        7: 3,  # 'р'\n        8: 3,  # 'с'\n        5: 0,  # 'т'\n        19: 3,  # 'у'\n        29: 0,  # 'ф'\n        25: 2,  # 'х'\n        22: 1,  # 'ц'\n        21: 1,  # 'ч'\n        27: 1,  # 'ш'\n        24: 3,  # 'щ'\n        17: 3,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 2,  # 'ю'\n        16: 3,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    9: {  # 'в'\n        63: 1,  # 'e'\n        45: 1,  # '\\xad'\n        31: 0,  # 'А'\n        32: 1,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 1,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 1,  # 'б'\n        9: 0,  # 'в'\n        20: 2,  # 'г'\n        11: 3,  # 'д'\n        3: 3,  # 'е'\n        23: 1,  # 'ж'\n        15: 3,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 3,  # 'к'\n        10: 3,  # 'л'\n        14: 2,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 2,  # 'п'\n        7: 3,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 2,  # 'у'\n        29: 0,  # 'ф'\n        25: 2,  # 'х'\n        22: 2,  # 'ц'\n        21: 3,  # 'ч'\n        27: 2,  # 'ш'\n        24: 1,  # 'щ'\n        17: 3,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 2,  # 'ю'\n        16: 3,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    20: {  # 'г'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 1,  # 'б'\n        9: 2,  # 'в'\n        20: 1,  # 'г'\n        11: 2,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 1,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 1,  # 'к'\n        10: 3,  # 'л'\n        14: 1,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 1,  # 'п'\n        7: 3,  # 'р'\n        8: 2,  # 'с'\n        5: 2,  # 'т'\n        19: 3,  # 'у'\n        29: 1,  # 'ф'\n        25: 1,  # 'х'\n        22: 0,  # 'ц'\n        21: 1,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 3,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 1,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    11: {  # 'д'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 2,  # 'б'\n        9: 3,  # 'в'\n        20: 2,  # 'г'\n        11: 2,  # 'д'\n        3: 3,  # 'е'\n        23: 3,  # 'ж'\n        15: 2,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 3,  # 'к'\n        10: 3,  # 'л'\n        14: 3,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 3,  # 'п'\n        7: 3,  # 'р'\n        8: 3,  # 'с'\n        5: 1,  # 'т'\n        19: 3,  # 'у'\n        29: 1,  # 'ф'\n        25: 2,  # 'х'\n        22: 2,  # 'ц'\n        21: 2,  # 'ч'\n        27: 1,  # 'ш'\n        24: 1,  # 'щ'\n        17: 3,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 1,  # 'ю'\n        16: 3,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    3: {  # 'е'\n        63: 0,  # 'e'\n        45: 1,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 2,  # 'а'\n        18: 3,  # 'б'\n        9: 3,  # 'в'\n        20: 3,  # 'г'\n        11: 3,  # 'д'\n        3: 2,  # 'е'\n        23: 3,  # 'ж'\n        15: 3,  # 'з'\n        2: 2,  # 'и'\n        26: 3,  # 'й'\n        12: 3,  # 'к'\n        10: 3,  # 'л'\n        14: 3,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 3,  # 'п'\n        7: 3,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 2,  # 'у'\n        29: 3,  # 'ф'\n        25: 3,  # 'х'\n        22: 3,  # 'ц'\n        21: 3,  # 'ч'\n        27: 3,  # 'ш'\n        24: 3,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 1,  # 'ю'\n        16: 3,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    23: {  # 'ж'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 3,  # 'б'\n        9: 2,  # 'в'\n        20: 1,  # 'г'\n        11: 3,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 2,  # 'к'\n        10: 1,  # 'л'\n        14: 1,  # 'м'\n        6: 3,  # 'н'\n        4: 2,  # 'о'\n        13: 1,  # 'п'\n        7: 1,  # 'р'\n        8: 1,  # 'с'\n        5: 1,  # 'т'\n        19: 2,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 1,  # 'ц'\n        21: 1,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    15: {  # 'з'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 3,  # 'б'\n        9: 3,  # 'в'\n        20: 3,  # 'г'\n        11: 3,  # 'д'\n        3: 3,  # 'е'\n        23: 1,  # 'ж'\n        15: 1,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 3,  # 'к'\n        10: 3,  # 'л'\n        14: 3,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 3,  # 'п'\n        7: 3,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 3,  # 'у'\n        29: 1,  # 'ф'\n        25: 2,  # 'х'\n        22: 2,  # 'ц'\n        21: 2,  # 'ч'\n        27: 2,  # 'ш'\n        24: 1,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 1,  # 'ю'\n        16: 2,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    2: {  # 'и'\n        63: 1,  # 'e'\n        45: 1,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 1,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 1,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 1,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 1,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 3,  # 'б'\n        9: 3,  # 'в'\n        20: 3,  # 'г'\n        11: 3,  # 'д'\n        3: 3,  # 'е'\n        23: 3,  # 'ж'\n        15: 3,  # 'з'\n        2: 3,  # 'и'\n        26: 3,  # 'й'\n        12: 3,  # 'к'\n        10: 3,  # 'л'\n        14: 3,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 3,  # 'п'\n        7: 3,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 2,  # 'у'\n        29: 3,  # 'ф'\n        25: 3,  # 'х'\n        22: 3,  # 'ц'\n        21: 3,  # 'ч'\n        27: 3,  # 'ш'\n        24: 3,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 1,  # 'ю'\n        16: 3,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    26: {  # 'й'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 1,  # 'а'\n        18: 2,  # 'б'\n        9: 2,  # 'в'\n        20: 1,  # 'г'\n        11: 2,  # 'д'\n        3: 2,  # 'е'\n        23: 0,  # 'ж'\n        15: 2,  # 'з'\n        2: 1,  # 'и'\n        26: 0,  # 'й'\n        12: 3,  # 'к'\n        10: 2,  # 'л'\n        14: 2,  # 'м'\n        6: 3,  # 'н'\n        4: 2,  # 'о'\n        13: 1,  # 'п'\n        7: 2,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 1,  # 'у'\n        29: 2,  # 'ф'\n        25: 1,  # 'х'\n        22: 2,  # 'ц'\n        21: 2,  # 'ч'\n        27: 1,  # 'ш'\n        24: 1,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    12: {  # 'к'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 1,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 1,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 1,  # 'б'\n        9: 3,  # 'в'\n        20: 2,  # 'г'\n        11: 1,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 2,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 1,  # 'к'\n        10: 3,  # 'л'\n        14: 2,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 1,  # 'п'\n        7: 3,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 3,  # 'у'\n        29: 1,  # 'ф'\n        25: 1,  # 'х'\n        22: 3,  # 'ц'\n        21: 2,  # 'ч'\n        27: 1,  # 'ш'\n        24: 0,  # 'щ'\n        17: 3,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 2,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    10: {  # 'л'\n        63: 1,  # 'e'\n        45: 1,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 1,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 3,  # 'б'\n        9: 3,  # 'в'\n        20: 3,  # 'г'\n        11: 2,  # 'д'\n        3: 3,  # 'е'\n        23: 3,  # 'ж'\n        15: 2,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 3,  # 'к'\n        10: 1,  # 'л'\n        14: 2,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 2,  # 'п'\n        7: 2,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 3,  # 'у'\n        29: 2,  # 'ф'\n        25: 2,  # 'х'\n        22: 2,  # 'ц'\n        21: 2,  # 'ч'\n        27: 2,  # 'ш'\n        24: 1,  # 'щ'\n        17: 3,  # 'ъ'\n        52: 2,  # 'ь'\n        42: 3,  # 'ю'\n        16: 3,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    14: {  # 'м'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 1,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 3,  # 'б'\n        9: 3,  # 'в'\n        20: 1,  # 'г'\n        11: 1,  # 'д'\n        3: 3,  # 'е'\n        23: 1,  # 'ж'\n        15: 1,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 2,  # 'к'\n        10: 3,  # 'л'\n        14: 1,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 3,  # 'п'\n        7: 2,  # 'р'\n        8: 2,  # 'с'\n        5: 1,  # 'т'\n        19: 3,  # 'у'\n        29: 2,  # 'ф'\n        25: 1,  # 'х'\n        22: 2,  # 'ц'\n        21: 2,  # 'ч'\n        27: 2,  # 'ш'\n        24: 1,  # 'щ'\n        17: 3,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 2,  # 'ю'\n        16: 3,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    6: {  # 'н'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 1,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 2,  # 'б'\n        9: 2,  # 'в'\n        20: 3,  # 'г'\n        11: 3,  # 'д'\n        3: 3,  # 'е'\n        23: 2,  # 'ж'\n        15: 2,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 3,  # 'к'\n        10: 2,  # 'л'\n        14: 1,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 1,  # 'п'\n        7: 2,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 3,  # 'у'\n        29: 3,  # 'ф'\n        25: 2,  # 'х'\n        22: 3,  # 'ц'\n        21: 3,  # 'ч'\n        27: 2,  # 'ш'\n        24: 1,  # 'щ'\n        17: 3,  # 'ъ'\n        52: 2,  # 'ь'\n        42: 2,  # 'ю'\n        16: 3,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    4: {  # 'о'\n        63: 0,  # 'e'\n        45: 1,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 2,  # 'а'\n        18: 3,  # 'б'\n        9: 3,  # 'в'\n        20: 3,  # 'г'\n        11: 3,  # 'д'\n        3: 3,  # 'е'\n        23: 3,  # 'ж'\n        15: 3,  # 'з'\n        2: 3,  # 'и'\n        26: 3,  # 'й'\n        12: 3,  # 'к'\n        10: 3,  # 'л'\n        14: 3,  # 'м'\n        6: 3,  # 'н'\n        4: 2,  # 'о'\n        13: 3,  # 'п'\n        7: 3,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 2,  # 'у'\n        29: 3,  # 'ф'\n        25: 3,  # 'х'\n        22: 3,  # 'ц'\n        21: 3,  # 'ч'\n        27: 3,  # 'ш'\n        24: 3,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 1,  # 'ю'\n        16: 3,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    13: {  # 'п'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 1,  # 'б'\n        9: 2,  # 'в'\n        20: 1,  # 'г'\n        11: 1,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 1,  # 'з'\n        2: 3,  # 'и'\n        26: 1,  # 'й'\n        12: 2,  # 'к'\n        10: 3,  # 'л'\n        14: 1,  # 'м'\n        6: 2,  # 'н'\n        4: 3,  # 'о'\n        13: 1,  # 'п'\n        7: 3,  # 'р'\n        8: 2,  # 'с'\n        5: 2,  # 'т'\n        19: 3,  # 'у'\n        29: 1,  # 'ф'\n        25: 1,  # 'х'\n        22: 2,  # 'ц'\n        21: 2,  # 'ч'\n        27: 1,  # 'ш'\n        24: 1,  # 'щ'\n        17: 3,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 2,  # 'ю'\n        16: 2,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    7: {  # 'р'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 3,  # 'б'\n        9: 3,  # 'в'\n        20: 3,  # 'г'\n        11: 3,  # 'д'\n        3: 3,  # 'е'\n        23: 3,  # 'ж'\n        15: 2,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 3,  # 'к'\n        10: 3,  # 'л'\n        14: 3,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 2,  # 'п'\n        7: 1,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 3,  # 'у'\n        29: 2,  # 'ф'\n        25: 3,  # 'х'\n        22: 3,  # 'ц'\n        21: 2,  # 'ч'\n        27: 3,  # 'ш'\n        24: 1,  # 'щ'\n        17: 3,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 2,  # 'ю'\n        16: 3,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    8: {  # 'с'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 2,  # 'б'\n        9: 3,  # 'в'\n        20: 2,  # 'г'\n        11: 2,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 1,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 3,  # 'к'\n        10: 3,  # 'л'\n        14: 3,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 3,  # 'п'\n        7: 3,  # 'р'\n        8: 1,  # 'с'\n        5: 3,  # 'т'\n        19: 3,  # 'у'\n        29: 2,  # 'ф'\n        25: 2,  # 'х'\n        22: 2,  # 'ц'\n        21: 2,  # 'ч'\n        27: 2,  # 'ш'\n        24: 0,  # 'щ'\n        17: 3,  # 'ъ'\n        52: 2,  # 'ь'\n        42: 2,  # 'ю'\n        16: 3,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    5: {  # 'т'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 3,  # 'б'\n        9: 3,  # 'в'\n        20: 2,  # 'г'\n        11: 2,  # 'д'\n        3: 3,  # 'е'\n        23: 1,  # 'ж'\n        15: 1,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 3,  # 'к'\n        10: 3,  # 'л'\n        14: 2,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 2,  # 'п'\n        7: 3,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 3,  # 'у'\n        29: 1,  # 'ф'\n        25: 2,  # 'х'\n        22: 2,  # 'ц'\n        21: 2,  # 'ч'\n        27: 1,  # 'ш'\n        24: 1,  # 'щ'\n        17: 3,  # 'ъ'\n        52: 2,  # 'ь'\n        42: 2,  # 'ю'\n        16: 3,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    19: {  # 'у'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 3,  # 'б'\n        9: 3,  # 'в'\n        20: 3,  # 'г'\n        11: 3,  # 'д'\n        3: 2,  # 'е'\n        23: 3,  # 'ж'\n        15: 3,  # 'з'\n        2: 2,  # 'и'\n        26: 2,  # 'й'\n        12: 3,  # 'к'\n        10: 3,  # 'л'\n        14: 3,  # 'м'\n        6: 3,  # 'н'\n        4: 2,  # 'о'\n        13: 3,  # 'п'\n        7: 3,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 1,  # 'у'\n        29: 2,  # 'ф'\n        25: 2,  # 'х'\n        22: 2,  # 'ц'\n        21: 3,  # 'ч'\n        27: 3,  # 'ш'\n        24: 2,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 1,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    29: {  # 'ф'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 1,  # 'б'\n        9: 1,  # 'в'\n        20: 1,  # 'г'\n        11: 0,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 2,  # 'к'\n        10: 2,  # 'л'\n        14: 1,  # 'м'\n        6: 1,  # 'н'\n        4: 3,  # 'о'\n        13: 0,  # 'п'\n        7: 2,  # 'р'\n        8: 2,  # 'с'\n        5: 2,  # 'т'\n        19: 2,  # 'у'\n        29: 0,  # 'ф'\n        25: 1,  # 'х'\n        22: 0,  # 'ц'\n        21: 1,  # 'ч'\n        27: 1,  # 'ш'\n        24: 0,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 2,  # 'ь'\n        42: 1,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    25: {  # 'х'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 1,  # 'б'\n        9: 3,  # 'в'\n        20: 0,  # 'г'\n        11: 1,  # 'д'\n        3: 2,  # 'е'\n        23: 0,  # 'ж'\n        15: 1,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 1,  # 'к'\n        10: 2,  # 'л'\n        14: 2,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 1,  # 'п'\n        7: 3,  # 'р'\n        8: 1,  # 'с'\n        5: 2,  # 'т'\n        19: 3,  # 'у'\n        29: 0,  # 'ф'\n        25: 1,  # 'х'\n        22: 0,  # 'ц'\n        21: 1,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 1,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    22: {  # 'ц'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 1,  # 'б'\n        9: 2,  # 'в'\n        20: 1,  # 'г'\n        11: 1,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 1,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 2,  # 'к'\n        10: 1,  # 'л'\n        14: 1,  # 'м'\n        6: 1,  # 'н'\n        4: 2,  # 'о'\n        13: 1,  # 'п'\n        7: 1,  # 'р'\n        8: 1,  # 'с'\n        5: 1,  # 'т'\n        19: 2,  # 'у'\n        29: 1,  # 'ф'\n        25: 1,  # 'х'\n        22: 1,  # 'ц'\n        21: 1,  # 'ч'\n        27: 1,  # 'ш'\n        24: 1,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 0,  # 'ю'\n        16: 2,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    21: {  # 'ч'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 1,  # 'б'\n        9: 3,  # 'в'\n        20: 1,  # 'г'\n        11: 0,  # 'д'\n        3: 3,  # 'е'\n        23: 1,  # 'ж'\n        15: 0,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 3,  # 'к'\n        10: 2,  # 'л'\n        14: 2,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 0,  # 'п'\n        7: 2,  # 'р'\n        8: 0,  # 'с'\n        5: 2,  # 'т'\n        19: 3,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 1,  # 'ш'\n        24: 0,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 1,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    27: {  # 'ш'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 0,  # 'б'\n        9: 2,  # 'в'\n        20: 0,  # 'г'\n        11: 1,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 3,  # 'к'\n        10: 2,  # 'л'\n        14: 1,  # 'м'\n        6: 3,  # 'н'\n        4: 2,  # 'о'\n        13: 2,  # 'п'\n        7: 1,  # 'р'\n        8: 0,  # 'с'\n        5: 1,  # 'т'\n        19: 2,  # 'у'\n        29: 1,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 1,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 2,  # 'ъ'\n        52: 1,  # 'ь'\n        42: 1,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    24: {  # 'щ'\n        63: 1,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 3,  # 'а'\n        18: 0,  # 'б'\n        9: 1,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 3,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 3,  # 'и'\n        26: 0,  # 'й'\n        12: 1,  # 'к'\n        10: 0,  # 'л'\n        14: 0,  # 'м'\n        6: 2,  # 'н'\n        4: 3,  # 'о'\n        13: 0,  # 'п'\n        7: 1,  # 'р'\n        8: 0,  # 'с'\n        5: 2,  # 'т'\n        19: 3,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 1,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 2,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    17: {  # 'ъ'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 1,  # 'а'\n        18: 3,  # 'б'\n        9: 3,  # 'в'\n        20: 3,  # 'г'\n        11: 3,  # 'д'\n        3: 2,  # 'е'\n        23: 3,  # 'ж'\n        15: 3,  # 'з'\n        2: 1,  # 'и'\n        26: 2,  # 'й'\n        12: 3,  # 'к'\n        10: 3,  # 'л'\n        14: 3,  # 'м'\n        6: 3,  # 'н'\n        4: 3,  # 'о'\n        13: 3,  # 'п'\n        7: 3,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 1,  # 'у'\n        29: 1,  # 'ф'\n        25: 2,  # 'х'\n        22: 2,  # 'ц'\n        21: 3,  # 'ч'\n        27: 2,  # 'ш'\n        24: 3,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 2,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    52: {  # 'ь'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 0,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 1,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 0,  # 'и'\n        26: 0,  # 'й'\n        12: 1,  # 'к'\n        10: 0,  # 'л'\n        14: 0,  # 'м'\n        6: 1,  # 'н'\n        4: 3,  # 'о'\n        13: 0,  # 'п'\n        7: 0,  # 'р'\n        8: 0,  # 'с'\n        5: 1,  # 'т'\n        19: 0,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 1,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 1,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    42: {  # 'ю'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 1,  # 'а'\n        18: 2,  # 'б'\n        9: 1,  # 'в'\n        20: 2,  # 'г'\n        11: 2,  # 'д'\n        3: 1,  # 'е'\n        23: 2,  # 'ж'\n        15: 2,  # 'з'\n        2: 1,  # 'и'\n        26: 1,  # 'й'\n        12: 2,  # 'к'\n        10: 2,  # 'л'\n        14: 2,  # 'м'\n        6: 2,  # 'н'\n        4: 1,  # 'о'\n        13: 1,  # 'п'\n        7: 2,  # 'р'\n        8: 2,  # 'с'\n        5: 2,  # 'т'\n        19: 1,  # 'у'\n        29: 1,  # 'ф'\n        25: 1,  # 'х'\n        22: 2,  # 'ц'\n        21: 3,  # 'ч'\n        27: 1,  # 'ш'\n        24: 1,  # 'щ'\n        17: 1,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    16: {  # 'я'\n        63: 0,  # 'e'\n        45: 1,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 0,  # 'а'\n        18: 3,  # 'б'\n        9: 3,  # 'в'\n        20: 2,  # 'г'\n        11: 3,  # 'д'\n        3: 2,  # 'е'\n        23: 1,  # 'ж'\n        15: 2,  # 'з'\n        2: 1,  # 'и'\n        26: 2,  # 'й'\n        12: 3,  # 'к'\n        10: 3,  # 'л'\n        14: 3,  # 'м'\n        6: 3,  # 'н'\n        4: 1,  # 'о'\n        13: 2,  # 'п'\n        7: 2,  # 'р'\n        8: 3,  # 'с'\n        5: 3,  # 'т'\n        19: 1,  # 'у'\n        29: 1,  # 'ф'\n        25: 3,  # 'х'\n        22: 2,  # 'ц'\n        21: 1,  # 'ч'\n        27: 1,  # 'ш'\n        24: 2,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 1,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    58: {  # 'є'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 0,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 0,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 0,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 0,  # 'л'\n        14: 0,  # 'м'\n        6: 0,  # 'н'\n        4: 0,  # 'о'\n        13: 0,  # 'п'\n        7: 0,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 0,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n    62: {  # '№'\n        63: 0,  # 'e'\n        45: 0,  # '\\xad'\n        31: 0,  # 'А'\n        32: 0,  # 'Б'\n        35: 0,  # 'В'\n        43: 0,  # 'Г'\n        37: 0,  # 'Д'\n        44: 0,  # 'Е'\n        55: 0,  # 'Ж'\n        47: 0,  # 'З'\n        40: 0,  # 'И'\n        59: 0,  # 'Й'\n        33: 0,  # 'К'\n        46: 0,  # 'Л'\n        38: 0,  # 'М'\n        36: 0,  # 'Н'\n        41: 0,  # 'О'\n        30: 0,  # 'П'\n        39: 0,  # 'Р'\n        28: 0,  # 'С'\n        34: 0,  # 'Т'\n        51: 0,  # 'У'\n        48: 0,  # 'Ф'\n        49: 0,  # 'Х'\n        53: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        54: 0,  # 'Ш'\n        57: 0,  # 'Щ'\n        61: 0,  # 'Ъ'\n        60: 0,  # 'Ю'\n        56: 0,  # 'Я'\n        1: 0,  # 'а'\n        18: 0,  # 'б'\n        9: 0,  # 'в'\n        20: 0,  # 'г'\n        11: 0,  # 'д'\n        3: 0,  # 'е'\n        23: 0,  # 'ж'\n        15: 0,  # 'з'\n        2: 0,  # 'и'\n        26: 0,  # 'й'\n        12: 0,  # 'к'\n        10: 0,  # 'л'\n        14: 0,  # 'м'\n        6: 0,  # 'н'\n        4: 0,  # 'о'\n        13: 0,  # 'п'\n        7: 0,  # 'р'\n        8: 0,  # 'с'\n        5: 0,  # 'т'\n        19: 0,  # 'у'\n        29: 0,  # 'ф'\n        25: 0,  # 'х'\n        22: 0,  # 'ц'\n        21: 0,  # 'ч'\n        27: 0,  # 'ш'\n        24: 0,  # 'щ'\n        17: 0,  # 'ъ'\n        52: 0,  # 'ь'\n        42: 0,  # 'ю'\n        16: 0,  # 'я'\n        58: 0,  # 'є'\n        62: 0,  # '№'\n    },\n}\n\n# 255: Undefined characters that did not exist in training text\n# 254: Carriage/Return\n# 253: symbol (punctuation) that does not belong to word\n# 252: 0 - 9\n# 251: Control characters\n\n# Character Mapping Table(s):\nISO_8859_5_BULGARIAN_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 254,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 254,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 253,  # ' '\n    33: 253,  # '!'\n    34: 253,  # '\"'\n    35: 253,  # '#'\n    36: 253,  # '$'\n    37: 253,  # '%'\n    38: 253,  # '&'\n    39: 253,  # \"'\"\n    40: 253,  # '('\n    41: 253,  # ')'\n    42: 253,  # '*'\n    43: 253,  # '+'\n    44: 253,  # ','\n    45: 253,  # '-'\n    46: 253,  # '.'\n    47: 253,  # '/'\n    48: 252,  # '0'\n    49: 252,  # '1'\n    50: 252,  # '2'\n    51: 252,  # '3'\n    52: 252,  # '4'\n    53: 252,  # '5'\n    54: 252,  # '6'\n    55: 252,  # '7'\n    56: 252,  # '8'\n    57: 252,  # '9'\n    58: 253,  # ':'\n    59: 253,  # ';'\n    60: 253,  # '<'\n    61: 253,  # '='\n    62: 253,  # '>'\n    63: 253,  # '?'\n    64: 253,  # '@'\n    65: 77,  # 'A'\n    66: 90,  # 'B'\n    67: 99,  # 'C'\n    68: 100,  # 'D'\n    69: 72,  # 'E'\n    70: 109,  # 'F'\n    71: 107,  # 'G'\n    72: 101,  # 'H'\n    73: 79,  # 'I'\n    74: 185,  # 'J'\n    75: 81,  # 'K'\n    76: 102,  # 'L'\n    77: 76,  # 'M'\n    78: 94,  # 'N'\n    79: 82,  # 'O'\n    80: 110,  # 'P'\n    81: 186,  # 'Q'\n    82: 108,  # 'R'\n    83: 91,  # 'S'\n    84: 74,  # 'T'\n    85: 119,  # 'U'\n    86: 84,  # 'V'\n    87: 96,  # 'W'\n    88: 111,  # 'X'\n    89: 187,  # 'Y'\n    90: 115,  # 'Z'\n    91: 253,  # '['\n    92: 253,  # '\\\\'\n    93: 253,  # ']'\n    94: 253,  # '^'\n    95: 253,  # '_'\n    96: 253,  # '`'\n    97: 65,  # 'a'\n    98: 69,  # 'b'\n    99: 70,  # 'c'\n    100: 66,  # 'd'\n    101: 63,  # 'e'\n    102: 68,  # 'f'\n    103: 112,  # 'g'\n    104: 103,  # 'h'\n    105: 92,  # 'i'\n    106: 194,  # 'j'\n    107: 104,  # 'k'\n    108: 95,  # 'l'\n    109: 86,  # 'm'\n    110: 87,  # 'n'\n    111: 71,  # 'o'\n    112: 116,  # 'p'\n    113: 195,  # 'q'\n    114: 85,  # 'r'\n    115: 93,  # 's'\n    116: 97,  # 't'\n    117: 113,  # 'u'\n    118: 196,  # 'v'\n    119: 197,  # 'w'\n    120: 198,  # 'x'\n    121: 199,  # 'y'\n    122: 200,  # 'z'\n    123: 253,  # '{'\n    124: 253,  # '|'\n    125: 253,  # '}'\n    126: 253,  # '~'\n    127: 253,  # '\\x7f'\n    128: 194,  # '\\x80'\n    129: 195,  # '\\x81'\n    130: 196,  # '\\x82'\n    131: 197,  # '\\x83'\n    132: 198,  # '\\x84'\n    133: 199,  # '\\x85'\n    134: 200,  # '\\x86'\n    135: 201,  # '\\x87'\n    136: 202,  # '\\x88'\n    137: 203,  # '\\x89'\n    138: 204,  # '\\x8a'\n    139: 205,  # '\\x8b'\n    140: 206,  # '\\x8c'\n    141: 207,  # '\\x8d'\n    142: 208,  # '\\x8e'\n    143: 209,  # '\\x8f'\n    144: 210,  # '\\x90'\n    145: 211,  # '\\x91'\n    146: 212,  # '\\x92'\n    147: 213,  # '\\x93'\n    148: 214,  # '\\x94'\n    149: 215,  # '\\x95'\n    150: 216,  # '\\x96'\n    151: 217,  # '\\x97'\n    152: 218,  # '\\x98'\n    153: 219,  # '\\x99'\n    154: 220,  # '\\x9a'\n    155: 221,  # '\\x9b'\n    156: 222,  # '\\x9c'\n    157: 223,  # '\\x9d'\n    158: 224,  # '\\x9e'\n    159: 225,  # '\\x9f'\n    160: 81,  # '\\xa0'\n    161: 226,  # 'Ё'\n    162: 227,  # 'Ђ'\n    163: 228,  # 'Ѓ'\n    164: 229,  # 'Є'\n    165: 230,  # 'Ѕ'\n    166: 105,  # 'І'\n    167: 231,  # 'Ї'\n    168: 232,  # 'Ј'\n    169: 233,  # 'Љ'\n    170: 234,  # 'Њ'\n    171: 235,  # 'Ћ'\n    172: 236,  # 'Ќ'\n    173: 45,  # '\\xad'\n    174: 237,  # 'Ў'\n    175: 238,  # 'Џ'\n    176: 31,  # 'А'\n    177: 32,  # 'Б'\n    178: 35,  # 'В'\n    179: 43,  # 'Г'\n    180: 37,  # 'Д'\n    181: 44,  # 'Е'\n    182: 55,  # 'Ж'\n    183: 47,  # 'З'\n    184: 40,  # 'И'\n    185: 59,  # 'Й'\n    186: 33,  # 'К'\n    187: 46,  # 'Л'\n    188: 38,  # 'М'\n    189: 36,  # 'Н'\n    190: 41,  # 'О'\n    191: 30,  # 'П'\n    192: 39,  # 'Р'\n    193: 28,  # 'С'\n    194: 34,  # 'Т'\n    195: 51,  # 'У'\n    196: 48,  # 'Ф'\n    197: 49,  # 'Х'\n    198: 53,  # 'Ц'\n    199: 50,  # 'Ч'\n    200: 54,  # 'Ш'\n    201: 57,  # 'Щ'\n    202: 61,  # 'Ъ'\n    203: 239,  # 'Ы'\n    204: 67,  # 'Ь'\n    205: 240,  # 'Э'\n    206: 60,  # 'Ю'\n    207: 56,  # 'Я'\n    208: 1,  # 'а'\n    209: 18,  # 'б'\n    210: 9,  # 'в'\n    211: 20,  # 'г'\n    212: 11,  # 'д'\n    213: 3,  # 'е'\n    214: 23,  # 'ж'\n    215: 15,  # 'з'\n    216: 2,  # 'и'\n    217: 26,  # 'й'\n    218: 12,  # 'к'\n    219: 10,  # 'л'\n    220: 14,  # 'м'\n    221: 6,  # 'н'\n    222: 4,  # 'о'\n    223: 13,  # 'п'\n    224: 7,  # 'р'\n    225: 8,  # 'с'\n    226: 5,  # 'т'\n    227: 19,  # 'у'\n    228: 29,  # 'ф'\n    229: 25,  # 'х'\n    230: 22,  # 'ц'\n    231: 21,  # 'ч'\n    232: 27,  # 'ш'\n    233: 24,  # 'щ'\n    234: 17,  # 'ъ'\n    235: 75,  # 'ы'\n    236: 52,  # 'ь'\n    237: 241,  # 'э'\n    238: 42,  # 'ю'\n    239: 16,  # 'я'\n    240: 62,  # '№'\n    241: 242,  # 'ё'\n    242: 243,  # 'ђ'\n    243: 244,  # 'ѓ'\n    244: 58,  # 'є'\n    245: 245,  # 'ѕ'\n    246: 98,  # 'і'\n    247: 246,  # 'ї'\n    248: 247,  # 'ј'\n    249: 248,  # 'љ'\n    250: 249,  # 'њ'\n    251: 250,  # 'ћ'\n    252: 251,  # 'ќ'\n    253: 91,  # '§'\n    254: 252,  # 'ў'\n    255: 253,  # 'џ'\n}\n\nISO_8859_5_BULGARIAN_MODEL = SingleByteCharSetModel(\n    charset_name=\"ISO-8859-5\",\n    language=\"Bulgarian\",\n    char_to_order_map=ISO_8859_5_BULGARIAN_CHAR_TO_ORDER,\n    language_model=BULGARIAN_LANG_MODEL,\n    typical_positive_ratio=0.969392,\n    keep_ascii_letters=False,\n    alphabet=\"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЬЮЯабвгдежзийклмнопрстуфхцчшщъьюя\",\n)\n\nWINDOWS_1251_BULGARIAN_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 254,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 254,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 253,  # ' '\n    33: 253,  # '!'\n    34: 253,  # '\"'\n    35: 253,  # '#'\n    36: 253,  # '$'\n    37: 253,  # '%'\n    38: 253,  # '&'\n    39: 253,  # \"'\"\n    40: 253,  # '('\n    41: 253,  # ')'\n    42: 253,  # '*'\n    43: 253,  # '+'\n    44: 253,  # ','\n    45: 253,  # '-'\n    46: 253,  # '.'\n    47: 253,  # '/'\n    48: 252,  # '0'\n    49: 252,  # '1'\n    50: 252,  # '2'\n    51: 252,  # '3'\n    52: 252,  # '4'\n    53: 252,  # '5'\n    54: 252,  # '6'\n    55: 252,  # '7'\n    56: 252,  # '8'\n    57: 252,  # '9'\n    58: 253,  # ':'\n    59: 253,  # ';'\n    60: 253,  # '<'\n    61: 253,  # '='\n    62: 253,  # '>'\n    63: 253,  # '?'\n    64: 253,  # '@'\n    65: 77,  # 'A'\n    66: 90,  # 'B'\n    67: 99,  # 'C'\n    68: 100,  # 'D'\n    69: 72,  # 'E'\n    70: 109,  # 'F'\n    71: 107,  # 'G'\n    72: 101,  # 'H'\n    73: 79,  # 'I'\n    74: 185,  # 'J'\n    75: 81,  # 'K'\n    76: 102,  # 'L'\n    77: 76,  # 'M'\n    78: 94,  # 'N'\n    79: 82,  # 'O'\n    80: 110,  # 'P'\n    81: 186,  # 'Q'\n    82: 108,  # 'R'\n    83: 91,  # 'S'\n    84: 74,  # 'T'\n    85: 119,  # 'U'\n    86: 84,  # 'V'\n    87: 96,  # 'W'\n    88: 111,  # 'X'\n    89: 187,  # 'Y'\n    90: 115,  # 'Z'\n    91: 253,  # '['\n    92: 253,  # '\\\\'\n    93: 253,  # ']'\n    94: 253,  # '^'\n    95: 253,  # '_'\n    96: 253,  # '`'\n    97: 65,  # 'a'\n    98: 69,  # 'b'\n    99: 70,  # 'c'\n    100: 66,  # 'd'\n    101: 63,  # 'e'\n    102: 68,  # 'f'\n    103: 112,  # 'g'\n    104: 103,  # 'h'\n    105: 92,  # 'i'\n    106: 194,  # 'j'\n    107: 104,  # 'k'\n    108: 95,  # 'l'\n    109: 86,  # 'm'\n    110: 87,  # 'n'\n    111: 71,  # 'o'\n    112: 116,  # 'p'\n    113: 195,  # 'q'\n    114: 85,  # 'r'\n    115: 93,  # 's'\n    116: 97,  # 't'\n    117: 113,  # 'u'\n    118: 196,  # 'v'\n    119: 197,  # 'w'\n    120: 198,  # 'x'\n    121: 199,  # 'y'\n    122: 200,  # 'z'\n    123: 253,  # '{'\n    124: 253,  # '|'\n    125: 253,  # '}'\n    126: 253,  # '~'\n    127: 253,  # '\\x7f'\n    128: 206,  # 'Ђ'\n    129: 207,  # 'Ѓ'\n    130: 208,  # '‚'\n    131: 209,  # 'ѓ'\n    132: 210,  # '„'\n    133: 211,  # '…'\n    134: 212,  # '†'\n    135: 213,  # '‡'\n    136: 120,  # '€'\n    137: 214,  # '‰'\n    138: 215,  # 'Љ'\n    139: 216,  # '‹'\n    140: 217,  # 'Њ'\n    141: 218,  # 'Ќ'\n    142: 219,  # 'Ћ'\n    143: 220,  # 'Џ'\n    144: 221,  # 'ђ'\n    145: 78,  # '‘'\n    146: 64,  # '’'\n    147: 83,  # '“'\n    148: 121,  # '”'\n    149: 98,  # '•'\n    150: 117,  # '–'\n    151: 105,  # '—'\n    152: 222,  # None\n    153: 223,  # '™'\n    154: 224,  # 'љ'\n    155: 225,  # '›'\n    156: 226,  # 'њ'\n    157: 227,  # 'ќ'\n    158: 228,  # 'ћ'\n    159: 229,  # 'џ'\n    160: 88,  # '\\xa0'\n    161: 230,  # 'Ў'\n    162: 231,  # 'ў'\n    163: 232,  # 'Ј'\n    164: 233,  # '¤'\n    165: 122,  # 'Ґ'\n    166: 89,  # '¦'\n    167: 106,  # '§'\n    168: 234,  # 'Ё'\n    169: 235,  # '©'\n    170: 236,  # 'Є'\n    171: 237,  # '«'\n    172: 238,  # '¬'\n    173: 45,  # '\\xad'\n    174: 239,  # '®'\n    175: 240,  # 'Ї'\n    176: 73,  # '°'\n    177: 80,  # '±'\n    178: 118,  # 'І'\n    179: 114,  # 'і'\n    180: 241,  # 'ґ'\n    181: 242,  # 'µ'\n    182: 243,  # '¶'\n    183: 244,  # '·'\n    184: 245,  # 'ё'\n    185: 62,  # '№'\n    186: 58,  # 'є'\n    187: 246,  # '»'\n    188: 247,  # 'ј'\n    189: 248,  # 'Ѕ'\n    190: 249,  # 'ѕ'\n    191: 250,  # 'ї'\n    192: 31,  # 'А'\n    193: 32,  # 'Б'\n    194: 35,  # 'В'\n    195: 43,  # 'Г'\n    196: 37,  # 'Д'\n    197: 44,  # 'Е'\n    198: 55,  # 'Ж'\n    199: 47,  # 'З'\n    200: 40,  # 'И'\n    201: 59,  # 'Й'\n    202: 33,  # 'К'\n    203: 46,  # 'Л'\n    204: 38,  # 'М'\n    205: 36,  # 'Н'\n    206: 41,  # 'О'\n    207: 30,  # 'П'\n    208: 39,  # 'Р'\n    209: 28,  # 'С'\n    210: 34,  # 'Т'\n    211: 51,  # 'У'\n    212: 48,  # 'Ф'\n    213: 49,  # 'Х'\n    214: 53,  # 'Ц'\n    215: 50,  # 'Ч'\n    216: 54,  # 'Ш'\n    217: 57,  # 'Щ'\n    218: 61,  # 'Ъ'\n    219: 251,  # 'Ы'\n    220: 67,  # 'Ь'\n    221: 252,  # 'Э'\n    222: 60,  # 'Ю'\n    223: 56,  # 'Я'\n    224: 1,  # 'а'\n    225: 18,  # 'б'\n    226: 9,  # 'в'\n    227: 20,  # 'г'\n    228: 11,  # 'д'\n    229: 3,  # 'е'\n    230: 23,  # 'ж'\n    231: 15,  # 'з'\n    232: 2,  # 'и'\n    233: 26,  # 'й'\n    234: 12,  # 'к'\n    235: 10,  # 'л'\n    236: 14,  # 'м'\n    237: 6,  # 'н'\n    238: 4,  # 'о'\n    239: 13,  # 'п'\n    240: 7,  # 'р'\n    241: 8,  # 'с'\n    242: 5,  # 'т'\n    243: 19,  # 'у'\n    244: 29,  # 'ф'\n    245: 25,  # 'х'\n    246: 22,  # 'ц'\n    247: 21,  # 'ч'\n    248: 27,  # 'ш'\n    249: 24,  # 'щ'\n    250: 17,  # 'ъ'\n    251: 75,  # 'ы'\n    252: 52,  # 'ь'\n    253: 253,  # 'э'\n    254: 42,  # 'ю'\n    255: 16,  # 'я'\n}\n\nWINDOWS_1251_BULGARIAN_MODEL = SingleByteCharSetModel(\n    charset_name=\"windows-1251\",\n    language=\"Bulgarian\",\n    char_to_order_map=WINDOWS_1251_BULGARIAN_CHAR_TO_ORDER,\n    language_model=BULGARIAN_LANG_MODEL,\n    typical_positive_ratio=0.969392,\n    keep_ascii_letters=False,\n    alphabet=\"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЬЮЯабвгдежзийклмнопрстуфхцчшщъьюя\",\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/langgreekmodel.py",
    "content": "from pip._vendor.chardet.sbcharsetprober import SingleByteCharSetModel\n\n# 3: Positive\n# 2: Likely\n# 1: Unlikely\n# 0: Negative\n\nGREEK_LANG_MODEL = {\n    60: {  # 'e'\n        60: 2,  # 'e'\n        55: 1,  # 'o'\n        58: 2,  # 't'\n        36: 1,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 1,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    55: {  # 'o'\n        60: 0,  # 'e'\n        55: 2,  # 'o'\n        58: 2,  # 't'\n        36: 1,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 1,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 1,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    58: {  # 't'\n        60: 2,  # 'e'\n        55: 1,  # 'o'\n        58: 1,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 2,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 1,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    36: {  # '·'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    61: {  # 'Ά'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 1,  # 'γ'\n        21: 2,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 2,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 1,  # 'π'\n        8: 2,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    46: {  # 'Έ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 2,  # 'β'\n        20: 2,  # 'γ'\n        21: 0,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 2,  # 'κ'\n        16: 2,  # 'λ'\n        10: 0,  # 'μ'\n        6: 3,  # 'ν'\n        30: 2,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 2,  # 'π'\n        8: 2,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 1,  # 'σ'\n        2: 2,  # 'τ'\n        12: 0,  # 'υ'\n        28: 2,  # 'φ'\n        23: 3,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    54: {  # 'Ό'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 2,  # 'λ'\n        10: 2,  # 'μ'\n        6: 2,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 2,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 2,  # 'σ'\n        2: 3,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 2,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    31: {  # 'Α'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 2,  # 'Β'\n        43: 2,  # 'Γ'\n        41: 1,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 2,  # 'Θ'\n        47: 2,  # 'Ι'\n        44: 2,  # 'Κ'\n        53: 2,  # 'Λ'\n        38: 2,  # 'Μ'\n        49: 2,  # 'Ν'\n        59: 1,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 2,  # 'Π'\n        48: 2,  # 'Ρ'\n        37: 2,  # 'Σ'\n        33: 2,  # 'Τ'\n        45: 2,  # 'Υ'\n        56: 2,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 2,  # 'γ'\n        21: 0,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 1,  # 'θ'\n        5: 0,  # 'ι'\n        11: 2,  # 'κ'\n        16: 3,  # 'λ'\n        10: 2,  # 'μ'\n        6: 3,  # 'ν'\n        30: 2,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 3,  # 'π'\n        8: 3,  # 'ρ'\n        14: 2,  # 'ς'\n        7: 2,  # 'σ'\n        2: 0,  # 'τ'\n        12: 3,  # 'υ'\n        28: 2,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    51: {  # 'Β'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 2,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 1,  # 'Ε'\n        40: 1,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 1,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 1,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 2,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 2,  # 'ά'\n        18: 2,  # 'έ'\n        22: 2,  # 'ή'\n        15: 0,  # 'ί'\n        1: 2,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 2,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 2,  # 'ι'\n        11: 0,  # 'κ'\n        16: 2,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 0,  # 'π'\n        8: 2,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    43: {  # 'Γ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 1,  # 'Α'\n        51: 0,  # 'Β'\n        43: 2,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 2,  # 'Ε'\n        40: 1,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 2,  # 'Ι'\n        44: 1,  # 'Κ'\n        53: 1,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 1,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 2,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 2,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 1,  # 'Χ'\n        57: 2,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 2,  # 'ί'\n        1: 2,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 2,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 3,  # 'ι'\n        11: 0,  # 'κ'\n        16: 2,  # 'λ'\n        10: 0,  # 'μ'\n        6: 2,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 0,  # 'π'\n        8: 2,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    41: {  # 'Δ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 2,  # 'Ε'\n        40: 2,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 2,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 2,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 2,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 2,  # 'ή'\n        15: 2,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 2,  # 'η'\n        25: 0,  # 'θ'\n        5: 3,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 0,  # 'π'\n        8: 2,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 2,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 2,  # 'ω'\n        19: 1,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 2,  # 'ώ'\n    },\n    34: {  # 'Ε'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 2,  # 'Α'\n        51: 0,  # 'Β'\n        43: 2,  # 'Γ'\n        41: 2,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 2,  # 'Ι'\n        44: 2,  # 'Κ'\n        53: 2,  # 'Λ'\n        38: 2,  # 'Μ'\n        49: 2,  # 'Ν'\n        59: 1,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 2,  # 'Π'\n        48: 2,  # 'Ρ'\n        37: 2,  # 'Σ'\n        33: 2,  # 'Τ'\n        45: 2,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 2,  # 'Χ'\n        57: 2,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 3,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 3,  # 'γ'\n        21: 2,  # 'δ'\n        3: 1,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 1,  # 'θ'\n        5: 2,  # 'ι'\n        11: 3,  # 'κ'\n        16: 3,  # 'λ'\n        10: 2,  # 'μ'\n        6: 3,  # 'ν'\n        30: 2,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 3,  # 'π'\n        8: 2,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 2,  # 'σ'\n        2: 2,  # 'τ'\n        12: 2,  # 'υ'\n        28: 2,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 1,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    40: {  # 'Η'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 1,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 2,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 2,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 2,  # 'Μ'\n        49: 2,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 2,  # 'Π'\n        48: 2,  # 'Ρ'\n        37: 2,  # 'Σ'\n        33: 2,  # 'Τ'\n        45: 1,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 2,  # 'λ'\n        10: 0,  # 'μ'\n        6: 1,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 1,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    52: {  # 'Θ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 2,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 2,  # 'Ε'\n        40: 2,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 2,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 1,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 1,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 2,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 2,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 2,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    47: {  # 'Ι'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 2,  # 'Α'\n        51: 1,  # 'Β'\n        43: 1,  # 'Γ'\n        41: 2,  # 'Δ'\n        34: 2,  # 'Ε'\n        40: 2,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 2,  # 'Κ'\n        53: 2,  # 'Λ'\n        38: 2,  # 'Μ'\n        49: 2,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 2,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 2,  # 'Ρ'\n        37: 2,  # 'Σ'\n        33: 2,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 2,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 2,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 2,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 2,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 1,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 2,  # 'σ'\n        2: 1,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 1,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    44: {  # 'Κ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 2,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 1,  # 'Δ'\n        34: 2,  # 'Ε'\n        40: 2,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 1,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 2,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 2,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 1,  # 'Τ'\n        45: 2,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 1,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 2,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 2,  # 'ι'\n        11: 0,  # 'κ'\n        16: 2,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 0,  # 'π'\n        8: 2,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 2,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 2,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 2,  # 'ώ'\n    },\n    53: {  # 'Λ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 2,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 2,  # 'Ε'\n        40: 2,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 2,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 2,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 2,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 2,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 2,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 2,  # 'Ω'\n        17: 2,  # 'ά'\n        18: 2,  # 'έ'\n        22: 0,  # 'ή'\n        15: 2,  # 'ί'\n        1: 2,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 2,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 1,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 2,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 2,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    38: {  # 'Μ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 2,  # 'Α'\n        51: 2,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 2,  # 'Ε'\n        40: 2,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 2,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 2,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 2,  # 'Ο'\n        35: 2,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 2,  # 'ά'\n        18: 2,  # 'έ'\n        22: 2,  # 'ή'\n        15: 2,  # 'ί'\n        1: 2,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 2,  # 'η'\n        25: 0,  # 'θ'\n        5: 3,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 3,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 2,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 2,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    49: {  # 'Ν'\n        60: 2,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 2,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 2,  # 'Ε'\n        40: 2,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 2,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 2,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 2,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 2,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 2,  # 'έ'\n        22: 0,  # 'ή'\n        15: 2,  # 'ί'\n        1: 2,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 1,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 1,  # 'ω'\n        19: 2,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    59: {  # 'Ξ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 1,  # 'Ε'\n        40: 1,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 1,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 2,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 2,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 2,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    39: {  # 'Ο'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 1,  # 'Β'\n        43: 2,  # 'Γ'\n        41: 2,  # 'Δ'\n        34: 2,  # 'Ε'\n        40: 1,  # 'Η'\n        52: 2,  # 'Θ'\n        47: 2,  # 'Ι'\n        44: 2,  # 'Κ'\n        53: 2,  # 'Λ'\n        38: 2,  # 'Μ'\n        49: 2,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 2,  # 'Π'\n        48: 2,  # 'Ρ'\n        37: 2,  # 'Σ'\n        33: 2,  # 'Τ'\n        45: 2,  # 'Υ'\n        56: 2,  # 'Φ'\n        50: 2,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 2,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 3,  # 'ι'\n        11: 2,  # 'κ'\n        16: 2,  # 'λ'\n        10: 2,  # 'μ'\n        6: 2,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 2,  # 'π'\n        8: 2,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 2,  # 'τ'\n        12: 2,  # 'υ'\n        28: 1,  # 'φ'\n        23: 1,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    35: {  # 'Π'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 2,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 2,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 2,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 2,  # 'Λ'\n        38: 1,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 2,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 2,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 1,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 1,  # 'Χ'\n        57: 2,  # 'Ω'\n        17: 2,  # 'ά'\n        18: 1,  # 'έ'\n        22: 1,  # 'ή'\n        15: 2,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 2,  # 'η'\n        25: 0,  # 'θ'\n        5: 2,  # 'ι'\n        11: 0,  # 'κ'\n        16: 2,  # 'λ'\n        10: 0,  # 'μ'\n        6: 2,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 0,  # 'π'\n        8: 3,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 2,  # 'υ'\n        28: 0,  # 'φ'\n        23: 2,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 2,  # 'ω'\n        19: 2,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 3,  # 'ώ'\n    },\n    48: {  # 'Ρ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 2,  # 'Α'\n        51: 0,  # 'Β'\n        43: 1,  # 'Γ'\n        41: 1,  # 'Δ'\n        34: 2,  # 'Ε'\n        40: 2,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 2,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 2,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 2,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 2,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 1,  # 'Τ'\n        45: 1,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 1,  # 'Χ'\n        57: 1,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 2,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 1,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 3,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 2,  # 'ω'\n        19: 0,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    37: {  # 'Σ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 2,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 1,  # 'Δ'\n        34: 2,  # 'Ε'\n        40: 2,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 2,  # 'Ι'\n        44: 2,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 2,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 2,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 2,  # 'Σ'\n        33: 2,  # 'Τ'\n        45: 2,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 2,  # 'Χ'\n        57: 2,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 2,  # 'ή'\n        15: 2,  # 'ί'\n        1: 2,  # 'α'\n        29: 2,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 3,  # 'η'\n        25: 0,  # 'θ'\n        5: 2,  # 'ι'\n        11: 2,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 2,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 3,  # 'τ'\n        12: 3,  # 'υ'\n        28: 0,  # 'φ'\n        23: 2,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 2,  # 'ω'\n        19: 0,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 2,  # 'ώ'\n    },\n    33: {  # 'Τ'\n        60: 0,  # 'e'\n        55: 1,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 2,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 2,  # 'Ε'\n        40: 2,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 2,  # 'Ι'\n        44: 2,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 2,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 2,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 1,  # 'Τ'\n        45: 1,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 2,  # 'Ω'\n        17: 2,  # 'ά'\n        18: 2,  # 'έ'\n        22: 0,  # 'ή'\n        15: 2,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 2,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 2,  # 'η'\n        25: 0,  # 'θ'\n        5: 2,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 2,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 0,  # 'π'\n        8: 2,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 2,  # 'σ'\n        2: 0,  # 'τ'\n        12: 2,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 2,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 3,  # 'ώ'\n    },\n    45: {  # 'Υ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 2,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 1,  # 'Ε'\n        40: 2,  # 'Η'\n        52: 2,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 1,  # 'Λ'\n        38: 2,  # 'Μ'\n        49: 2,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 2,  # 'Π'\n        48: 1,  # 'Ρ'\n        37: 2,  # 'Σ'\n        33: 2,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 1,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 2,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 3,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    56: {  # 'Φ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 1,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 1,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 2,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 2,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 2,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 2,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 2,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 2,  # 'τ'\n        12: 2,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 1,  # 'ύ'\n        27: 1,  # 'ώ'\n    },\n    50: {  # 'Χ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 1,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 2,  # 'Ε'\n        40: 2,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 2,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 1,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 1,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 2,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 1,  # 'Χ'\n        57: 1,  # 'Ω'\n        17: 2,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 2,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 2,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 0,  # 'π'\n        8: 3,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 2,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 2,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    57: {  # 'Ω'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 1,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 1,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 2,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 2,  # 'Ρ'\n        37: 2,  # 'Σ'\n        33: 2,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 0,  # 'π'\n        8: 2,  # 'ρ'\n        14: 2,  # 'ς'\n        7: 2,  # 'σ'\n        2: 0,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 1,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    17: {  # 'ά'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 2,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 3,  # 'β'\n        20: 3,  # 'γ'\n        21: 3,  # 'δ'\n        3: 3,  # 'ε'\n        32: 3,  # 'ζ'\n        13: 0,  # 'η'\n        25: 3,  # 'θ'\n        5: 2,  # 'ι'\n        11: 3,  # 'κ'\n        16: 3,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 3,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 3,  # 'π'\n        8: 3,  # 'ρ'\n        14: 3,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 0,  # 'υ'\n        28: 3,  # 'φ'\n        23: 3,  # 'χ'\n        42: 3,  # 'ψ'\n        24: 2,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    18: {  # 'έ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 3,  # 'α'\n        29: 2,  # 'β'\n        20: 3,  # 'γ'\n        21: 2,  # 'δ'\n        3: 3,  # 'ε'\n        32: 2,  # 'ζ'\n        13: 0,  # 'η'\n        25: 3,  # 'θ'\n        5: 0,  # 'ι'\n        11: 3,  # 'κ'\n        16: 3,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 3,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 3,  # 'π'\n        8: 3,  # 'ρ'\n        14: 3,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 0,  # 'υ'\n        28: 3,  # 'φ'\n        23: 3,  # 'χ'\n        42: 3,  # 'ψ'\n        24: 2,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    22: {  # 'ή'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 1,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 3,  # 'γ'\n        21: 3,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 3,  # 'θ'\n        5: 0,  # 'ι'\n        11: 3,  # 'κ'\n        16: 2,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 2,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 3,  # 'π'\n        8: 3,  # 'ρ'\n        14: 3,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 0,  # 'υ'\n        28: 2,  # 'φ'\n        23: 3,  # 'χ'\n        42: 2,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    15: {  # 'ί'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 3,  # 'α'\n        29: 2,  # 'β'\n        20: 3,  # 'γ'\n        21: 3,  # 'δ'\n        3: 3,  # 'ε'\n        32: 3,  # 'ζ'\n        13: 3,  # 'η'\n        25: 3,  # 'θ'\n        5: 0,  # 'ι'\n        11: 3,  # 'κ'\n        16: 3,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 3,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 3,  # 'π'\n        8: 3,  # 'ρ'\n        14: 3,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 0,  # 'υ'\n        28: 1,  # 'φ'\n        23: 3,  # 'χ'\n        42: 2,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    1: {  # 'α'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 2,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 2,  # 'έ'\n        22: 0,  # 'ή'\n        15: 3,  # 'ί'\n        1: 0,  # 'α'\n        29: 3,  # 'β'\n        20: 3,  # 'γ'\n        21: 3,  # 'δ'\n        3: 2,  # 'ε'\n        32: 3,  # 'ζ'\n        13: 1,  # 'η'\n        25: 3,  # 'θ'\n        5: 3,  # 'ι'\n        11: 3,  # 'κ'\n        16: 3,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 3,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 3,  # 'π'\n        8: 3,  # 'ρ'\n        14: 3,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 3,  # 'υ'\n        28: 3,  # 'φ'\n        23: 3,  # 'χ'\n        42: 2,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 2,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    29: {  # 'β'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 2,  # 'έ'\n        22: 3,  # 'ή'\n        15: 2,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 2,  # 'γ'\n        21: 2,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 2,  # 'η'\n        25: 0,  # 'θ'\n        5: 3,  # 'ι'\n        11: 0,  # 'κ'\n        16: 3,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 0,  # 'π'\n        8: 3,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 2,  # 'ω'\n        19: 2,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 2,  # 'ώ'\n    },\n    20: {  # 'γ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 3,  # 'έ'\n        22: 3,  # 'ή'\n        15: 3,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 3,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 3,  # 'η'\n        25: 0,  # 'θ'\n        5: 3,  # 'ι'\n        11: 3,  # 'κ'\n        16: 3,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 3,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 0,  # 'π'\n        8: 3,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 2,  # 'υ'\n        28: 0,  # 'φ'\n        23: 3,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 3,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 3,  # 'ώ'\n    },\n    21: {  # 'δ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 2,  # 'ά'\n        18: 3,  # 'έ'\n        22: 3,  # 'ή'\n        15: 3,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 3,  # 'η'\n        25: 0,  # 'θ'\n        5: 3,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 0,  # 'π'\n        8: 3,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 3,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 3,  # 'ό'\n        26: 3,  # 'ύ'\n        27: 3,  # 'ώ'\n    },\n    3: {  # 'ε'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 2,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 3,  # 'ί'\n        1: 2,  # 'α'\n        29: 3,  # 'β'\n        20: 3,  # 'γ'\n        21: 3,  # 'δ'\n        3: 2,  # 'ε'\n        32: 2,  # 'ζ'\n        13: 0,  # 'η'\n        25: 3,  # 'θ'\n        5: 3,  # 'ι'\n        11: 3,  # 'κ'\n        16: 3,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 3,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 3,  # 'π'\n        8: 3,  # 'ρ'\n        14: 3,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 3,  # 'υ'\n        28: 3,  # 'φ'\n        23: 3,  # 'χ'\n        42: 2,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 2,  # 'ό'\n        26: 3,  # 'ύ'\n        27: 2,  # 'ώ'\n    },\n    32: {  # 'ζ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 2,  # 'ά'\n        18: 2,  # 'έ'\n        22: 2,  # 'ή'\n        15: 2,  # 'ί'\n        1: 2,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 3,  # 'η'\n        25: 0,  # 'θ'\n        5: 2,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 1,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 2,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 2,  # 'ώ'\n    },\n    13: {  # 'η'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 2,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 3,  # 'γ'\n        21: 2,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 3,  # 'θ'\n        5: 0,  # 'ι'\n        11: 3,  # 'κ'\n        16: 3,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 2,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 2,  # 'π'\n        8: 3,  # 'ρ'\n        14: 3,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 0,  # 'υ'\n        28: 2,  # 'φ'\n        23: 3,  # 'χ'\n        42: 2,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    25: {  # 'θ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 2,  # 'ά'\n        18: 3,  # 'έ'\n        22: 3,  # 'ή'\n        15: 2,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 3,  # 'η'\n        25: 0,  # 'θ'\n        5: 3,  # 'ι'\n        11: 0,  # 'κ'\n        16: 1,  # 'λ'\n        10: 3,  # 'μ'\n        6: 2,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 0,  # 'π'\n        8: 3,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 3,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 3,  # 'ό'\n        26: 3,  # 'ύ'\n        27: 3,  # 'ώ'\n    },\n    5: {  # 'ι'\n        60: 0,  # 'e'\n        55: 1,  # 'o'\n        58: 0,  # 't'\n        36: 2,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 1,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 3,  # 'έ'\n        22: 3,  # 'ή'\n        15: 0,  # 'ί'\n        1: 3,  # 'α'\n        29: 3,  # 'β'\n        20: 3,  # 'γ'\n        21: 3,  # 'δ'\n        3: 3,  # 'ε'\n        32: 2,  # 'ζ'\n        13: 3,  # 'η'\n        25: 3,  # 'θ'\n        5: 0,  # 'ι'\n        11: 3,  # 'κ'\n        16: 3,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 3,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 3,  # 'π'\n        8: 3,  # 'ρ'\n        14: 3,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 0,  # 'υ'\n        28: 2,  # 'φ'\n        23: 3,  # 'χ'\n        42: 2,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 3,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 3,  # 'ώ'\n    },\n    11: {  # 'κ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 3,  # 'έ'\n        22: 3,  # 'ή'\n        15: 3,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 3,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 3,  # 'η'\n        25: 2,  # 'θ'\n        5: 3,  # 'ι'\n        11: 3,  # 'κ'\n        16: 3,  # 'λ'\n        10: 3,  # 'μ'\n        6: 2,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 2,  # 'π'\n        8: 3,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 3,  # 'τ'\n        12: 3,  # 'υ'\n        28: 2,  # 'φ'\n        23: 2,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 3,  # 'ό'\n        26: 3,  # 'ύ'\n        27: 3,  # 'ώ'\n    },\n    16: {  # 'λ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 3,  # 'έ'\n        22: 3,  # 'ή'\n        15: 3,  # 'ί'\n        1: 3,  # 'α'\n        29: 1,  # 'β'\n        20: 2,  # 'γ'\n        21: 1,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 3,  # 'η'\n        25: 2,  # 'θ'\n        5: 3,  # 'ι'\n        11: 2,  # 'κ'\n        16: 3,  # 'λ'\n        10: 2,  # 'μ'\n        6: 2,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 3,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 3,  # 'τ'\n        12: 3,  # 'υ'\n        28: 2,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 3,  # 'ό'\n        26: 3,  # 'ύ'\n        27: 3,  # 'ώ'\n    },\n    10: {  # 'μ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 1,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 3,  # 'έ'\n        22: 3,  # 'ή'\n        15: 3,  # 'ί'\n        1: 3,  # 'α'\n        29: 3,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 3,  # 'η'\n        25: 0,  # 'θ'\n        5: 3,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 3,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 2,  # 'υ'\n        28: 3,  # 'φ'\n        23: 0,  # 'χ'\n        42: 2,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 3,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 2,  # 'ώ'\n    },\n    6: {  # 'ν'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 2,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 3,  # 'έ'\n        22: 3,  # 'ή'\n        15: 3,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 3,  # 'δ'\n        3: 3,  # 'ε'\n        32: 2,  # 'ζ'\n        13: 3,  # 'η'\n        25: 3,  # 'θ'\n        5: 3,  # 'ι'\n        11: 0,  # 'κ'\n        16: 1,  # 'λ'\n        10: 0,  # 'μ'\n        6: 2,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 3,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 3,  # 'ό'\n        26: 3,  # 'ύ'\n        27: 3,  # 'ώ'\n    },\n    30: {  # 'ξ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 2,  # 'ά'\n        18: 3,  # 'έ'\n        22: 3,  # 'ή'\n        15: 2,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 3,  # 'η'\n        25: 0,  # 'θ'\n        5: 2,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 3,  # 'τ'\n        12: 2,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 2,  # 'ό'\n        26: 3,  # 'ύ'\n        27: 1,  # 'ώ'\n    },\n    4: {  # 'ο'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 2,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 2,  # 'έ'\n        22: 3,  # 'ή'\n        15: 3,  # 'ί'\n        1: 2,  # 'α'\n        29: 3,  # 'β'\n        20: 3,  # 'γ'\n        21: 3,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 3,  # 'η'\n        25: 3,  # 'θ'\n        5: 3,  # 'ι'\n        11: 3,  # 'κ'\n        16: 3,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 2,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 3,  # 'π'\n        8: 3,  # 'ρ'\n        14: 3,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 3,  # 'υ'\n        28: 3,  # 'φ'\n        23: 3,  # 'χ'\n        42: 2,  # 'ψ'\n        24: 2,  # 'ω'\n        19: 1,  # 'ό'\n        26: 3,  # 'ύ'\n        27: 2,  # 'ώ'\n    },\n    9: {  # 'π'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 3,  # 'έ'\n        22: 3,  # 'ή'\n        15: 3,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 3,  # 'η'\n        25: 0,  # 'θ'\n        5: 3,  # 'ι'\n        11: 0,  # 'κ'\n        16: 3,  # 'λ'\n        10: 0,  # 'μ'\n        6: 2,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 0,  # 'π'\n        8: 3,  # 'ρ'\n        14: 2,  # 'ς'\n        7: 0,  # 'σ'\n        2: 3,  # 'τ'\n        12: 3,  # 'υ'\n        28: 0,  # 'φ'\n        23: 2,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 3,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 3,  # 'ώ'\n    },\n    8: {  # 'ρ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 3,  # 'έ'\n        22: 3,  # 'ή'\n        15: 3,  # 'ί'\n        1: 3,  # 'α'\n        29: 2,  # 'β'\n        20: 3,  # 'γ'\n        21: 2,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 3,  # 'η'\n        25: 3,  # 'θ'\n        5: 3,  # 'ι'\n        11: 3,  # 'κ'\n        16: 1,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 2,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 2,  # 'π'\n        8: 2,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 2,  # 'σ'\n        2: 3,  # 'τ'\n        12: 3,  # 'υ'\n        28: 3,  # 'φ'\n        23: 3,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 3,  # 'ό'\n        26: 3,  # 'ύ'\n        27: 3,  # 'ώ'\n    },\n    14: {  # 'ς'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 2,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 0,  # 'θ'\n        5: 0,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 0,  # 'τ'\n        12: 0,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    7: {  # 'σ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 2,  # 'ά'\n        18: 2,  # 'έ'\n        22: 3,  # 'ή'\n        15: 3,  # 'ί'\n        1: 3,  # 'α'\n        29: 3,  # 'β'\n        20: 0,  # 'γ'\n        21: 2,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 3,  # 'η'\n        25: 3,  # 'θ'\n        5: 3,  # 'ι'\n        11: 3,  # 'κ'\n        16: 2,  # 'λ'\n        10: 3,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 3,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 3,  # 'υ'\n        28: 3,  # 'φ'\n        23: 3,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 3,  # 'ό'\n        26: 3,  # 'ύ'\n        27: 2,  # 'ώ'\n    },\n    2: {  # 'τ'\n        60: 0,  # 'e'\n        55: 2,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 3,  # 'έ'\n        22: 3,  # 'ή'\n        15: 3,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 2,  # 'ζ'\n        13: 3,  # 'η'\n        25: 0,  # 'θ'\n        5: 3,  # 'ι'\n        11: 2,  # 'κ'\n        16: 2,  # 'λ'\n        10: 3,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 0,  # 'π'\n        8: 3,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 3,  # 'υ'\n        28: 2,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 3,  # 'ό'\n        26: 3,  # 'ύ'\n        27: 3,  # 'ώ'\n    },\n    12: {  # 'υ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 2,  # 'ά'\n        18: 2,  # 'έ'\n        22: 3,  # 'ή'\n        15: 2,  # 'ί'\n        1: 3,  # 'α'\n        29: 2,  # 'β'\n        20: 3,  # 'γ'\n        21: 2,  # 'δ'\n        3: 2,  # 'ε'\n        32: 2,  # 'ζ'\n        13: 2,  # 'η'\n        25: 3,  # 'θ'\n        5: 2,  # 'ι'\n        11: 3,  # 'κ'\n        16: 3,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 3,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 3,  # 'π'\n        8: 3,  # 'ρ'\n        14: 3,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 0,  # 'υ'\n        28: 2,  # 'φ'\n        23: 3,  # 'χ'\n        42: 2,  # 'ψ'\n        24: 2,  # 'ω'\n        19: 2,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 2,  # 'ώ'\n    },\n    28: {  # 'φ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 3,  # 'έ'\n        22: 3,  # 'ή'\n        15: 3,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 2,  # 'η'\n        25: 2,  # 'θ'\n        5: 3,  # 'ι'\n        11: 0,  # 'κ'\n        16: 2,  # 'λ'\n        10: 0,  # 'μ'\n        6: 1,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 0,  # 'π'\n        8: 3,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 3,  # 'τ'\n        12: 3,  # 'υ'\n        28: 1,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 3,  # 'ό'\n        26: 2,  # 'ύ'\n        27: 2,  # 'ώ'\n    },\n    23: {  # 'χ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 3,  # 'ά'\n        18: 2,  # 'έ'\n        22: 3,  # 'ή'\n        15: 3,  # 'ί'\n        1: 3,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 2,  # 'η'\n        25: 2,  # 'θ'\n        5: 3,  # 'ι'\n        11: 0,  # 'κ'\n        16: 2,  # 'λ'\n        10: 2,  # 'μ'\n        6: 3,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 0,  # 'π'\n        8: 3,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 3,  # 'τ'\n        12: 3,  # 'υ'\n        28: 0,  # 'φ'\n        23: 2,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 3,  # 'ω'\n        19: 3,  # 'ό'\n        26: 3,  # 'ύ'\n        27: 3,  # 'ώ'\n    },\n    42: {  # 'ψ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 2,  # 'ά'\n        18: 2,  # 'έ'\n        22: 1,  # 'ή'\n        15: 2,  # 'ί'\n        1: 2,  # 'α'\n        29: 0,  # 'β'\n        20: 0,  # 'γ'\n        21: 0,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 3,  # 'η'\n        25: 0,  # 'θ'\n        5: 2,  # 'ι'\n        11: 0,  # 'κ'\n        16: 0,  # 'λ'\n        10: 0,  # 'μ'\n        6: 0,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 0,  # 'π'\n        8: 0,  # 'ρ'\n        14: 0,  # 'ς'\n        7: 0,  # 'σ'\n        2: 2,  # 'τ'\n        12: 1,  # 'υ'\n        28: 0,  # 'φ'\n        23: 0,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 2,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    24: {  # 'ω'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 1,  # 'ά'\n        18: 0,  # 'έ'\n        22: 2,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 2,  # 'β'\n        20: 3,  # 'γ'\n        21: 2,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 0,  # 'η'\n        25: 3,  # 'θ'\n        5: 2,  # 'ι'\n        11: 0,  # 'κ'\n        16: 2,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 0,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 3,  # 'π'\n        8: 3,  # 'ρ'\n        14: 3,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 0,  # 'υ'\n        28: 2,  # 'φ'\n        23: 2,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    19: {  # 'ό'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 3,  # 'β'\n        20: 3,  # 'γ'\n        21: 3,  # 'δ'\n        3: 1,  # 'ε'\n        32: 2,  # 'ζ'\n        13: 2,  # 'η'\n        25: 2,  # 'θ'\n        5: 2,  # 'ι'\n        11: 3,  # 'κ'\n        16: 3,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 1,  # 'ξ'\n        4: 2,  # 'ο'\n        9: 3,  # 'π'\n        8: 3,  # 'ρ'\n        14: 3,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 0,  # 'υ'\n        28: 2,  # 'φ'\n        23: 3,  # 'χ'\n        42: 2,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    26: {  # 'ύ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 2,  # 'α'\n        29: 2,  # 'β'\n        20: 2,  # 'γ'\n        21: 1,  # 'δ'\n        3: 3,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 2,  # 'η'\n        25: 3,  # 'θ'\n        5: 0,  # 'ι'\n        11: 3,  # 'κ'\n        16: 3,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 2,  # 'ξ'\n        4: 3,  # 'ο'\n        9: 3,  # 'π'\n        8: 3,  # 'ρ'\n        14: 3,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 0,  # 'υ'\n        28: 2,  # 'φ'\n        23: 2,  # 'χ'\n        42: 2,  # 'ψ'\n        24: 2,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n    27: {  # 'ώ'\n        60: 0,  # 'e'\n        55: 0,  # 'o'\n        58: 0,  # 't'\n        36: 0,  # '·'\n        61: 0,  # 'Ά'\n        46: 0,  # 'Έ'\n        54: 0,  # 'Ό'\n        31: 0,  # 'Α'\n        51: 0,  # 'Β'\n        43: 0,  # 'Γ'\n        41: 0,  # 'Δ'\n        34: 0,  # 'Ε'\n        40: 0,  # 'Η'\n        52: 0,  # 'Θ'\n        47: 0,  # 'Ι'\n        44: 0,  # 'Κ'\n        53: 0,  # 'Λ'\n        38: 0,  # 'Μ'\n        49: 0,  # 'Ν'\n        59: 0,  # 'Ξ'\n        39: 0,  # 'Ο'\n        35: 0,  # 'Π'\n        48: 0,  # 'Ρ'\n        37: 0,  # 'Σ'\n        33: 0,  # 'Τ'\n        45: 0,  # 'Υ'\n        56: 0,  # 'Φ'\n        50: 0,  # 'Χ'\n        57: 0,  # 'Ω'\n        17: 0,  # 'ά'\n        18: 0,  # 'έ'\n        22: 0,  # 'ή'\n        15: 0,  # 'ί'\n        1: 0,  # 'α'\n        29: 1,  # 'β'\n        20: 0,  # 'γ'\n        21: 3,  # 'δ'\n        3: 0,  # 'ε'\n        32: 0,  # 'ζ'\n        13: 1,  # 'η'\n        25: 2,  # 'θ'\n        5: 2,  # 'ι'\n        11: 0,  # 'κ'\n        16: 2,  # 'λ'\n        10: 3,  # 'μ'\n        6: 3,  # 'ν'\n        30: 1,  # 'ξ'\n        4: 0,  # 'ο'\n        9: 2,  # 'π'\n        8: 3,  # 'ρ'\n        14: 3,  # 'ς'\n        7: 3,  # 'σ'\n        2: 3,  # 'τ'\n        12: 0,  # 'υ'\n        28: 1,  # 'φ'\n        23: 1,  # 'χ'\n        42: 0,  # 'ψ'\n        24: 0,  # 'ω'\n        19: 0,  # 'ό'\n        26: 0,  # 'ύ'\n        27: 0,  # 'ώ'\n    },\n}\n\n# 255: Undefined characters that did not exist in training text\n# 254: Carriage/Return\n# 253: symbol (punctuation) that does not belong to word\n# 252: 0 - 9\n# 251: Control characters\n\n# Character Mapping Table(s):\nWINDOWS_1253_GREEK_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 254,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 254,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 253,  # ' '\n    33: 253,  # '!'\n    34: 253,  # '\"'\n    35: 253,  # '#'\n    36: 253,  # '$'\n    37: 253,  # '%'\n    38: 253,  # '&'\n    39: 253,  # \"'\"\n    40: 253,  # '('\n    41: 253,  # ')'\n    42: 253,  # '*'\n    43: 253,  # '+'\n    44: 253,  # ','\n    45: 253,  # '-'\n    46: 253,  # '.'\n    47: 253,  # '/'\n    48: 252,  # '0'\n    49: 252,  # '1'\n    50: 252,  # '2'\n    51: 252,  # '3'\n    52: 252,  # '4'\n    53: 252,  # '5'\n    54: 252,  # '6'\n    55: 252,  # '7'\n    56: 252,  # '8'\n    57: 252,  # '9'\n    58: 253,  # ':'\n    59: 253,  # ';'\n    60: 253,  # '<'\n    61: 253,  # '='\n    62: 253,  # '>'\n    63: 253,  # '?'\n    64: 253,  # '@'\n    65: 82,  # 'A'\n    66: 100,  # 'B'\n    67: 104,  # 'C'\n    68: 94,  # 'D'\n    69: 98,  # 'E'\n    70: 101,  # 'F'\n    71: 116,  # 'G'\n    72: 102,  # 'H'\n    73: 111,  # 'I'\n    74: 187,  # 'J'\n    75: 117,  # 'K'\n    76: 92,  # 'L'\n    77: 88,  # 'M'\n    78: 113,  # 'N'\n    79: 85,  # 'O'\n    80: 79,  # 'P'\n    81: 118,  # 'Q'\n    82: 105,  # 'R'\n    83: 83,  # 'S'\n    84: 67,  # 'T'\n    85: 114,  # 'U'\n    86: 119,  # 'V'\n    87: 95,  # 'W'\n    88: 99,  # 'X'\n    89: 109,  # 'Y'\n    90: 188,  # 'Z'\n    91: 253,  # '['\n    92: 253,  # '\\\\'\n    93: 253,  # ']'\n    94: 253,  # '^'\n    95: 253,  # '_'\n    96: 253,  # '`'\n    97: 72,  # 'a'\n    98: 70,  # 'b'\n    99: 80,  # 'c'\n    100: 81,  # 'd'\n    101: 60,  # 'e'\n    102: 96,  # 'f'\n    103: 93,  # 'g'\n    104: 89,  # 'h'\n    105: 68,  # 'i'\n    106: 120,  # 'j'\n    107: 97,  # 'k'\n    108: 77,  # 'l'\n    109: 86,  # 'm'\n    110: 69,  # 'n'\n    111: 55,  # 'o'\n    112: 78,  # 'p'\n    113: 115,  # 'q'\n    114: 65,  # 'r'\n    115: 66,  # 's'\n    116: 58,  # 't'\n    117: 76,  # 'u'\n    118: 106,  # 'v'\n    119: 103,  # 'w'\n    120: 87,  # 'x'\n    121: 107,  # 'y'\n    122: 112,  # 'z'\n    123: 253,  # '{'\n    124: 253,  # '|'\n    125: 253,  # '}'\n    126: 253,  # '~'\n    127: 253,  # '\\x7f'\n    128: 255,  # '€'\n    129: 255,  # None\n    130: 255,  # '‚'\n    131: 255,  # 'ƒ'\n    132: 255,  # '„'\n    133: 255,  # '…'\n    134: 255,  # '†'\n    135: 255,  # '‡'\n    136: 255,  # None\n    137: 255,  # '‰'\n    138: 255,  # None\n    139: 255,  # '‹'\n    140: 255,  # None\n    141: 255,  # None\n    142: 255,  # None\n    143: 255,  # None\n    144: 255,  # None\n    145: 255,  # '‘'\n    146: 255,  # '’'\n    147: 255,  # '“'\n    148: 255,  # '”'\n    149: 255,  # '•'\n    150: 255,  # '–'\n    151: 255,  # '—'\n    152: 255,  # None\n    153: 255,  # '™'\n    154: 255,  # None\n    155: 255,  # '›'\n    156: 255,  # None\n    157: 255,  # None\n    158: 255,  # None\n    159: 255,  # None\n    160: 253,  # '\\xa0'\n    161: 233,  # '΅'\n    162: 61,  # 'Ά'\n    163: 253,  # '£'\n    164: 253,  # '¤'\n    165: 253,  # '¥'\n    166: 253,  # '¦'\n    167: 253,  # '§'\n    168: 253,  # '¨'\n    169: 253,  # '©'\n    170: 253,  # None\n    171: 253,  # '«'\n    172: 253,  # '¬'\n    173: 74,  # '\\xad'\n    174: 253,  # '®'\n    175: 253,  # '―'\n    176: 253,  # '°'\n    177: 253,  # '±'\n    178: 253,  # '²'\n    179: 253,  # '³'\n    180: 247,  # '΄'\n    181: 253,  # 'µ'\n    182: 253,  # '¶'\n    183: 36,  # '·'\n    184: 46,  # 'Έ'\n    185: 71,  # 'Ή'\n    186: 73,  # 'Ί'\n    187: 253,  # '»'\n    188: 54,  # 'Ό'\n    189: 253,  # '½'\n    190: 108,  # 'Ύ'\n    191: 123,  # 'Ώ'\n    192: 110,  # 'ΐ'\n    193: 31,  # 'Α'\n    194: 51,  # 'Β'\n    195: 43,  # 'Γ'\n    196: 41,  # 'Δ'\n    197: 34,  # 'Ε'\n    198: 91,  # 'Ζ'\n    199: 40,  # 'Η'\n    200: 52,  # 'Θ'\n    201: 47,  # 'Ι'\n    202: 44,  # 'Κ'\n    203: 53,  # 'Λ'\n    204: 38,  # 'Μ'\n    205: 49,  # 'Ν'\n    206: 59,  # 'Ξ'\n    207: 39,  # 'Ο'\n    208: 35,  # 'Π'\n    209: 48,  # 'Ρ'\n    210: 250,  # None\n    211: 37,  # 'Σ'\n    212: 33,  # 'Τ'\n    213: 45,  # 'Υ'\n    214: 56,  # 'Φ'\n    215: 50,  # 'Χ'\n    216: 84,  # 'Ψ'\n    217: 57,  # 'Ω'\n    218: 120,  # 'Ϊ'\n    219: 121,  # 'Ϋ'\n    220: 17,  # 'ά'\n    221: 18,  # 'έ'\n    222: 22,  # 'ή'\n    223: 15,  # 'ί'\n    224: 124,  # 'ΰ'\n    225: 1,  # 'α'\n    226: 29,  # 'β'\n    227: 20,  # 'γ'\n    228: 21,  # 'δ'\n    229: 3,  # 'ε'\n    230: 32,  # 'ζ'\n    231: 13,  # 'η'\n    232: 25,  # 'θ'\n    233: 5,  # 'ι'\n    234: 11,  # 'κ'\n    235: 16,  # 'λ'\n    236: 10,  # 'μ'\n    237: 6,  # 'ν'\n    238: 30,  # 'ξ'\n    239: 4,  # 'ο'\n    240: 9,  # 'π'\n    241: 8,  # 'ρ'\n    242: 14,  # 'ς'\n    243: 7,  # 'σ'\n    244: 2,  # 'τ'\n    245: 12,  # 'υ'\n    246: 28,  # 'φ'\n    247: 23,  # 'χ'\n    248: 42,  # 'ψ'\n    249: 24,  # 'ω'\n    250: 64,  # 'ϊ'\n    251: 75,  # 'ϋ'\n    252: 19,  # 'ό'\n    253: 26,  # 'ύ'\n    254: 27,  # 'ώ'\n    255: 253,  # None\n}\n\nWINDOWS_1253_GREEK_MODEL = SingleByteCharSetModel(\n    charset_name=\"windows-1253\",\n    language=\"Greek\",\n    char_to_order_map=WINDOWS_1253_GREEK_CHAR_TO_ORDER,\n    language_model=GREEK_LANG_MODEL,\n    typical_positive_ratio=0.982851,\n    keep_ascii_letters=False,\n    alphabet=\"ΆΈΉΊΌΎΏΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩάέήίαβγδεζηθικλμνξοπρςστυφχψωόύώ\",\n)\n\nISO_8859_7_GREEK_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 254,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 254,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 253,  # ' '\n    33: 253,  # '!'\n    34: 253,  # '\"'\n    35: 253,  # '#'\n    36: 253,  # '$'\n    37: 253,  # '%'\n    38: 253,  # '&'\n    39: 253,  # \"'\"\n    40: 253,  # '('\n    41: 253,  # ')'\n    42: 253,  # '*'\n    43: 253,  # '+'\n    44: 253,  # ','\n    45: 253,  # '-'\n    46: 253,  # '.'\n    47: 253,  # '/'\n    48: 252,  # '0'\n    49: 252,  # '1'\n    50: 252,  # '2'\n    51: 252,  # '3'\n    52: 252,  # '4'\n    53: 252,  # '5'\n    54: 252,  # '6'\n    55: 252,  # '7'\n    56: 252,  # '8'\n    57: 252,  # '9'\n    58: 253,  # ':'\n    59: 253,  # ';'\n    60: 253,  # '<'\n    61: 253,  # '='\n    62: 253,  # '>'\n    63: 253,  # '?'\n    64: 253,  # '@'\n    65: 82,  # 'A'\n    66: 100,  # 'B'\n    67: 104,  # 'C'\n    68: 94,  # 'D'\n    69: 98,  # 'E'\n    70: 101,  # 'F'\n    71: 116,  # 'G'\n    72: 102,  # 'H'\n    73: 111,  # 'I'\n    74: 187,  # 'J'\n    75: 117,  # 'K'\n    76: 92,  # 'L'\n    77: 88,  # 'M'\n    78: 113,  # 'N'\n    79: 85,  # 'O'\n    80: 79,  # 'P'\n    81: 118,  # 'Q'\n    82: 105,  # 'R'\n    83: 83,  # 'S'\n    84: 67,  # 'T'\n    85: 114,  # 'U'\n    86: 119,  # 'V'\n    87: 95,  # 'W'\n    88: 99,  # 'X'\n    89: 109,  # 'Y'\n    90: 188,  # 'Z'\n    91: 253,  # '['\n    92: 253,  # '\\\\'\n    93: 253,  # ']'\n    94: 253,  # '^'\n    95: 253,  # '_'\n    96: 253,  # '`'\n    97: 72,  # 'a'\n    98: 70,  # 'b'\n    99: 80,  # 'c'\n    100: 81,  # 'd'\n    101: 60,  # 'e'\n    102: 96,  # 'f'\n    103: 93,  # 'g'\n    104: 89,  # 'h'\n    105: 68,  # 'i'\n    106: 120,  # 'j'\n    107: 97,  # 'k'\n    108: 77,  # 'l'\n    109: 86,  # 'm'\n    110: 69,  # 'n'\n    111: 55,  # 'o'\n    112: 78,  # 'p'\n    113: 115,  # 'q'\n    114: 65,  # 'r'\n    115: 66,  # 's'\n    116: 58,  # 't'\n    117: 76,  # 'u'\n    118: 106,  # 'v'\n    119: 103,  # 'w'\n    120: 87,  # 'x'\n    121: 107,  # 'y'\n    122: 112,  # 'z'\n    123: 253,  # '{'\n    124: 253,  # '|'\n    125: 253,  # '}'\n    126: 253,  # '~'\n    127: 253,  # '\\x7f'\n    128: 255,  # '\\x80'\n    129: 255,  # '\\x81'\n    130: 255,  # '\\x82'\n    131: 255,  # '\\x83'\n    132: 255,  # '\\x84'\n    133: 255,  # '\\x85'\n    134: 255,  # '\\x86'\n    135: 255,  # '\\x87'\n    136: 255,  # '\\x88'\n    137: 255,  # '\\x89'\n    138: 255,  # '\\x8a'\n    139: 255,  # '\\x8b'\n    140: 255,  # '\\x8c'\n    141: 255,  # '\\x8d'\n    142: 255,  # '\\x8e'\n    143: 255,  # '\\x8f'\n    144: 255,  # '\\x90'\n    145: 255,  # '\\x91'\n    146: 255,  # '\\x92'\n    147: 255,  # '\\x93'\n    148: 255,  # '\\x94'\n    149: 255,  # '\\x95'\n    150: 255,  # '\\x96'\n    151: 255,  # '\\x97'\n    152: 255,  # '\\x98'\n    153: 255,  # '\\x99'\n    154: 255,  # '\\x9a'\n    155: 255,  # '\\x9b'\n    156: 255,  # '\\x9c'\n    157: 255,  # '\\x9d'\n    158: 255,  # '\\x9e'\n    159: 255,  # '\\x9f'\n    160: 253,  # '\\xa0'\n    161: 233,  # '‘'\n    162: 90,  # '’'\n    163: 253,  # '£'\n    164: 253,  # '€'\n    165: 253,  # '₯'\n    166: 253,  # '¦'\n    167: 253,  # '§'\n    168: 253,  # '¨'\n    169: 253,  # '©'\n    170: 253,  # 'ͺ'\n    171: 253,  # '«'\n    172: 253,  # '¬'\n    173: 74,  # '\\xad'\n    174: 253,  # None\n    175: 253,  # '―'\n    176: 253,  # '°'\n    177: 253,  # '±'\n    178: 253,  # '²'\n    179: 253,  # '³'\n    180: 247,  # '΄'\n    181: 248,  # '΅'\n    182: 61,  # 'Ά'\n    183: 36,  # '·'\n    184: 46,  # 'Έ'\n    185: 71,  # 'Ή'\n    186: 73,  # 'Ί'\n    187: 253,  # '»'\n    188: 54,  # 'Ό'\n    189: 253,  # '½'\n    190: 108,  # 'Ύ'\n    191: 123,  # 'Ώ'\n    192: 110,  # 'ΐ'\n    193: 31,  # 'Α'\n    194: 51,  # 'Β'\n    195: 43,  # 'Γ'\n    196: 41,  # 'Δ'\n    197: 34,  # 'Ε'\n    198: 91,  # 'Ζ'\n    199: 40,  # 'Η'\n    200: 52,  # 'Θ'\n    201: 47,  # 'Ι'\n    202: 44,  # 'Κ'\n    203: 53,  # 'Λ'\n    204: 38,  # 'Μ'\n    205: 49,  # 'Ν'\n    206: 59,  # 'Ξ'\n    207: 39,  # 'Ο'\n    208: 35,  # 'Π'\n    209: 48,  # 'Ρ'\n    210: 250,  # None\n    211: 37,  # 'Σ'\n    212: 33,  # 'Τ'\n    213: 45,  # 'Υ'\n    214: 56,  # 'Φ'\n    215: 50,  # 'Χ'\n    216: 84,  # 'Ψ'\n    217: 57,  # 'Ω'\n    218: 120,  # 'Ϊ'\n    219: 121,  # 'Ϋ'\n    220: 17,  # 'ά'\n    221: 18,  # 'έ'\n    222: 22,  # 'ή'\n    223: 15,  # 'ί'\n    224: 124,  # 'ΰ'\n    225: 1,  # 'α'\n    226: 29,  # 'β'\n    227: 20,  # 'γ'\n    228: 21,  # 'δ'\n    229: 3,  # 'ε'\n    230: 32,  # 'ζ'\n    231: 13,  # 'η'\n    232: 25,  # 'θ'\n    233: 5,  # 'ι'\n    234: 11,  # 'κ'\n    235: 16,  # 'λ'\n    236: 10,  # 'μ'\n    237: 6,  # 'ν'\n    238: 30,  # 'ξ'\n    239: 4,  # 'ο'\n    240: 9,  # 'π'\n    241: 8,  # 'ρ'\n    242: 14,  # 'ς'\n    243: 7,  # 'σ'\n    244: 2,  # 'τ'\n    245: 12,  # 'υ'\n    246: 28,  # 'φ'\n    247: 23,  # 'χ'\n    248: 42,  # 'ψ'\n    249: 24,  # 'ω'\n    250: 64,  # 'ϊ'\n    251: 75,  # 'ϋ'\n    252: 19,  # 'ό'\n    253: 26,  # 'ύ'\n    254: 27,  # 'ώ'\n    255: 253,  # None\n}\n\nISO_8859_7_GREEK_MODEL = SingleByteCharSetModel(\n    charset_name=\"ISO-8859-7\",\n    language=\"Greek\",\n    char_to_order_map=ISO_8859_7_GREEK_CHAR_TO_ORDER,\n    language_model=GREEK_LANG_MODEL,\n    typical_positive_ratio=0.982851,\n    keep_ascii_letters=False,\n    alphabet=\"ΆΈΉΊΌΎΏΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩάέήίαβγδεζηθικλμνξοπρςστυφχψωόύώ\",\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/langhebrewmodel.py",
    "content": "from pip._vendor.chardet.sbcharsetprober import SingleByteCharSetModel\n\n# 3: Positive\n# 2: Likely\n# 1: Unlikely\n# 0: Negative\n\nHEBREW_LANG_MODEL = {\n    50: {  # 'a'\n        50: 0,  # 'a'\n        60: 1,  # 'c'\n        61: 1,  # 'd'\n        42: 1,  # 'e'\n        53: 1,  # 'i'\n        56: 2,  # 'l'\n        54: 2,  # 'n'\n        49: 0,  # 'o'\n        51: 2,  # 'r'\n        43: 1,  # 's'\n        44: 2,  # 't'\n        63: 1,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 1,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 1,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 1,  # 'ק'\n        7: 0,  # 'ר'\n        10: 1,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 1,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    60: {  # 'c'\n        50: 1,  # 'a'\n        60: 1,  # 'c'\n        61: 0,  # 'd'\n        42: 1,  # 'e'\n        53: 1,  # 'i'\n        56: 1,  # 'l'\n        54: 0,  # 'n'\n        49: 1,  # 'o'\n        51: 1,  # 'r'\n        43: 1,  # 's'\n        44: 2,  # 't'\n        63: 1,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 1,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 1,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 1,  # 'מ'\n        23: 0,  # 'ן'\n        12: 1,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    61: {  # 'd'\n        50: 1,  # 'a'\n        60: 0,  # 'c'\n        61: 1,  # 'd'\n        42: 1,  # 'e'\n        53: 1,  # 'i'\n        56: 1,  # 'l'\n        54: 1,  # 'n'\n        49: 2,  # 'o'\n        51: 1,  # 'r'\n        43: 1,  # 's'\n        44: 0,  # 't'\n        63: 1,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 1,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 1,  # '–'\n        52: 1,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    42: {  # 'e'\n        50: 1,  # 'a'\n        60: 1,  # 'c'\n        61: 2,  # 'd'\n        42: 1,  # 'e'\n        53: 1,  # 'i'\n        56: 2,  # 'l'\n        54: 2,  # 'n'\n        49: 1,  # 'o'\n        51: 2,  # 'r'\n        43: 2,  # 's'\n        44: 2,  # 't'\n        63: 1,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 1,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 1,  # '–'\n        52: 2,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    53: {  # 'i'\n        50: 1,  # 'a'\n        60: 2,  # 'c'\n        61: 1,  # 'd'\n        42: 1,  # 'e'\n        53: 0,  # 'i'\n        56: 1,  # 'l'\n        54: 2,  # 'n'\n        49: 2,  # 'o'\n        51: 1,  # 'r'\n        43: 2,  # 's'\n        44: 2,  # 't'\n        63: 1,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 1,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 1,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    56: {  # 'l'\n        50: 1,  # 'a'\n        60: 1,  # 'c'\n        61: 1,  # 'd'\n        42: 2,  # 'e'\n        53: 2,  # 'i'\n        56: 2,  # 'l'\n        54: 1,  # 'n'\n        49: 1,  # 'o'\n        51: 0,  # 'r'\n        43: 1,  # 's'\n        44: 1,  # 't'\n        63: 1,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 1,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    54: {  # 'n'\n        50: 1,  # 'a'\n        60: 1,  # 'c'\n        61: 1,  # 'd'\n        42: 1,  # 'e'\n        53: 1,  # 'i'\n        56: 1,  # 'l'\n        54: 1,  # 'n'\n        49: 1,  # 'o'\n        51: 0,  # 'r'\n        43: 1,  # 's'\n        44: 2,  # 't'\n        63: 1,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 1,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 2,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    49: {  # 'o'\n        50: 1,  # 'a'\n        60: 1,  # 'c'\n        61: 1,  # 'd'\n        42: 1,  # 'e'\n        53: 1,  # 'i'\n        56: 1,  # 'l'\n        54: 2,  # 'n'\n        49: 1,  # 'o'\n        51: 2,  # 'r'\n        43: 1,  # 's'\n        44: 1,  # 't'\n        63: 1,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 1,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    51: {  # 'r'\n        50: 2,  # 'a'\n        60: 1,  # 'c'\n        61: 1,  # 'd'\n        42: 2,  # 'e'\n        53: 1,  # 'i'\n        56: 1,  # 'l'\n        54: 1,  # 'n'\n        49: 2,  # 'o'\n        51: 1,  # 'r'\n        43: 1,  # 's'\n        44: 1,  # 't'\n        63: 1,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 2,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    43: {  # 's'\n        50: 1,  # 'a'\n        60: 1,  # 'c'\n        61: 0,  # 'd'\n        42: 2,  # 'e'\n        53: 1,  # 'i'\n        56: 1,  # 'l'\n        54: 1,  # 'n'\n        49: 1,  # 'o'\n        51: 1,  # 'r'\n        43: 1,  # 's'\n        44: 2,  # 't'\n        63: 1,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 1,  # '’'\n        47: 0,  # '“'\n        46: 2,  # '”'\n        58: 0,  # '†'\n        40: 2,  # '…'\n    },\n    44: {  # 't'\n        50: 1,  # 'a'\n        60: 1,  # 'c'\n        61: 0,  # 'd'\n        42: 2,  # 'e'\n        53: 2,  # 'i'\n        56: 1,  # 'l'\n        54: 0,  # 'n'\n        49: 1,  # 'o'\n        51: 1,  # 'r'\n        43: 1,  # 's'\n        44: 1,  # 't'\n        63: 1,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 2,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    63: {  # 'u'\n        50: 1,  # 'a'\n        60: 1,  # 'c'\n        61: 1,  # 'd'\n        42: 1,  # 'e'\n        53: 1,  # 'i'\n        56: 1,  # 'l'\n        54: 1,  # 'n'\n        49: 0,  # 'o'\n        51: 1,  # 'r'\n        43: 2,  # 's'\n        44: 1,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 1,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    34: {  # '\\xa0'\n        50: 1,  # 'a'\n        60: 0,  # 'c'\n        61: 1,  # 'd'\n        42: 0,  # 'e'\n        53: 1,  # 'i'\n        56: 0,  # 'l'\n        54: 1,  # 'n'\n        49: 1,  # 'o'\n        51: 0,  # 'r'\n        43: 1,  # 's'\n        44: 1,  # 't'\n        63: 0,  # 'u'\n        34: 2,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 2,  # 'א'\n        8: 1,  # 'ב'\n        20: 1,  # 'ג'\n        16: 1,  # 'ד'\n        3: 1,  # 'ה'\n        2: 1,  # 'ו'\n        24: 1,  # 'ז'\n        14: 1,  # 'ח'\n        22: 1,  # 'ט'\n        1: 2,  # 'י'\n        25: 0,  # 'ך'\n        15: 1,  # 'כ'\n        4: 1,  # 'ל'\n        11: 0,  # 'ם'\n        6: 2,  # 'מ'\n        23: 0,  # 'ן'\n        12: 1,  # 'נ'\n        19: 1,  # 'ס'\n        13: 1,  # 'ע'\n        26: 0,  # 'ף'\n        18: 1,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 1,  # 'צ'\n        17: 1,  # 'ק'\n        7: 1,  # 'ר'\n        10: 1,  # 'ש'\n        5: 1,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    55: {  # '´'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 1,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 1,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 1,  # 'ה'\n        2: 1,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 2,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 1,  # 'ל'\n        11: 0,  # 'ם'\n        6: 1,  # 'מ'\n        23: 1,  # 'ן'\n        12: 1,  # 'נ'\n        19: 1,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 1,  # 'ר'\n        10: 1,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    48: {  # '¼'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 1,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 1,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 1,  # 'כ'\n        4: 1,  # 'ל'\n        11: 0,  # 'ם'\n        6: 1,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    39: {  # '½'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 1,  # 'כ'\n        4: 1,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 1,  # 'צ'\n        17: 1,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    57: {  # '¾'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    30: {  # 'ְ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 1,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 2,  # 'א'\n        8: 2,  # 'ב'\n        20: 2,  # 'ג'\n        16: 2,  # 'ד'\n        3: 2,  # 'ה'\n        2: 2,  # 'ו'\n        24: 2,  # 'ז'\n        14: 2,  # 'ח'\n        22: 2,  # 'ט'\n        1: 2,  # 'י'\n        25: 2,  # 'ך'\n        15: 2,  # 'כ'\n        4: 2,  # 'ל'\n        11: 1,  # 'ם'\n        6: 2,  # 'מ'\n        23: 0,  # 'ן'\n        12: 2,  # 'נ'\n        19: 2,  # 'ס'\n        13: 2,  # 'ע'\n        26: 0,  # 'ף'\n        18: 2,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 2,  # 'צ'\n        17: 2,  # 'ק'\n        7: 2,  # 'ר'\n        10: 2,  # 'ש'\n        5: 2,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    59: {  # 'ֱ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 1,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 1,  # 'ב'\n        20: 1,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 0,  # 'ו'\n        24: 1,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 1,  # 'י'\n        25: 0,  # 'ך'\n        15: 1,  # 'כ'\n        4: 2,  # 'ל'\n        11: 0,  # 'ם'\n        6: 2,  # 'מ'\n        23: 0,  # 'ן'\n        12: 1,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 1,  # 'ר'\n        10: 1,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    41: {  # 'ֲ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 2,  # 'ב'\n        20: 1,  # 'ג'\n        16: 2,  # 'ד'\n        3: 1,  # 'ה'\n        2: 1,  # 'ו'\n        24: 1,  # 'ז'\n        14: 1,  # 'ח'\n        22: 1,  # 'ט'\n        1: 1,  # 'י'\n        25: 1,  # 'ך'\n        15: 1,  # 'כ'\n        4: 2,  # 'ל'\n        11: 0,  # 'ם'\n        6: 2,  # 'מ'\n        23: 0,  # 'ן'\n        12: 2,  # 'נ'\n        19: 1,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 1,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 2,  # 'צ'\n        17: 1,  # 'ק'\n        7: 2,  # 'ר'\n        10: 2,  # 'ש'\n        5: 1,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    33: {  # 'ִ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 1,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 1,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 1,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 1,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 1,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 1,  # 'א'\n        8: 2,  # 'ב'\n        20: 2,  # 'ג'\n        16: 2,  # 'ד'\n        3: 1,  # 'ה'\n        2: 1,  # 'ו'\n        24: 2,  # 'ז'\n        14: 1,  # 'ח'\n        22: 1,  # 'ט'\n        1: 3,  # 'י'\n        25: 1,  # 'ך'\n        15: 2,  # 'כ'\n        4: 2,  # 'ל'\n        11: 2,  # 'ם'\n        6: 2,  # 'מ'\n        23: 2,  # 'ן'\n        12: 2,  # 'נ'\n        19: 2,  # 'ס'\n        13: 1,  # 'ע'\n        26: 0,  # 'ף'\n        18: 2,  # 'פ'\n        27: 1,  # 'ץ'\n        21: 2,  # 'צ'\n        17: 2,  # 'ק'\n        7: 2,  # 'ר'\n        10: 2,  # 'ש'\n        5: 2,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    37: {  # 'ֵ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 1,  # 'ֶ'\n        31: 1,  # 'ַ'\n        29: 1,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 2,  # 'א'\n        8: 2,  # 'ב'\n        20: 1,  # 'ג'\n        16: 2,  # 'ד'\n        3: 2,  # 'ה'\n        2: 1,  # 'ו'\n        24: 1,  # 'ז'\n        14: 2,  # 'ח'\n        22: 1,  # 'ט'\n        1: 3,  # 'י'\n        25: 2,  # 'ך'\n        15: 1,  # 'כ'\n        4: 2,  # 'ל'\n        11: 2,  # 'ם'\n        6: 1,  # 'מ'\n        23: 2,  # 'ן'\n        12: 2,  # 'נ'\n        19: 1,  # 'ס'\n        13: 2,  # 'ע'\n        26: 1,  # 'ף'\n        18: 1,  # 'פ'\n        27: 1,  # 'ץ'\n        21: 1,  # 'צ'\n        17: 1,  # 'ק'\n        7: 2,  # 'ר'\n        10: 2,  # 'ש'\n        5: 2,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    36: {  # 'ֶ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 1,  # 'ֶ'\n        31: 1,  # 'ַ'\n        29: 1,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 2,  # 'א'\n        8: 2,  # 'ב'\n        20: 1,  # 'ג'\n        16: 2,  # 'ד'\n        3: 2,  # 'ה'\n        2: 1,  # 'ו'\n        24: 1,  # 'ז'\n        14: 2,  # 'ח'\n        22: 1,  # 'ט'\n        1: 2,  # 'י'\n        25: 2,  # 'ך'\n        15: 1,  # 'כ'\n        4: 2,  # 'ל'\n        11: 2,  # 'ם'\n        6: 2,  # 'מ'\n        23: 2,  # 'ן'\n        12: 2,  # 'נ'\n        19: 2,  # 'ס'\n        13: 1,  # 'ע'\n        26: 1,  # 'ף'\n        18: 1,  # 'פ'\n        27: 2,  # 'ץ'\n        21: 1,  # 'צ'\n        17: 1,  # 'ק'\n        7: 2,  # 'ר'\n        10: 2,  # 'ש'\n        5: 2,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    31: {  # 'ַ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 1,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 1,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 2,  # 'א'\n        8: 2,  # 'ב'\n        20: 2,  # 'ג'\n        16: 2,  # 'ד'\n        3: 2,  # 'ה'\n        2: 1,  # 'ו'\n        24: 2,  # 'ז'\n        14: 2,  # 'ח'\n        22: 2,  # 'ט'\n        1: 3,  # 'י'\n        25: 1,  # 'ך'\n        15: 2,  # 'כ'\n        4: 2,  # 'ל'\n        11: 2,  # 'ם'\n        6: 2,  # 'מ'\n        23: 2,  # 'ן'\n        12: 2,  # 'נ'\n        19: 2,  # 'ס'\n        13: 2,  # 'ע'\n        26: 2,  # 'ף'\n        18: 2,  # 'פ'\n        27: 1,  # 'ץ'\n        21: 2,  # 'צ'\n        17: 2,  # 'ק'\n        7: 2,  # 'ר'\n        10: 2,  # 'ש'\n        5: 2,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    29: {  # 'ָ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 1,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 1,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 2,  # 'א'\n        8: 2,  # 'ב'\n        20: 2,  # 'ג'\n        16: 2,  # 'ד'\n        3: 3,  # 'ה'\n        2: 2,  # 'ו'\n        24: 2,  # 'ז'\n        14: 2,  # 'ח'\n        22: 1,  # 'ט'\n        1: 2,  # 'י'\n        25: 2,  # 'ך'\n        15: 2,  # 'כ'\n        4: 2,  # 'ל'\n        11: 2,  # 'ם'\n        6: 2,  # 'מ'\n        23: 2,  # 'ן'\n        12: 2,  # 'נ'\n        19: 1,  # 'ס'\n        13: 2,  # 'ע'\n        26: 1,  # 'ף'\n        18: 2,  # 'פ'\n        27: 1,  # 'ץ'\n        21: 2,  # 'צ'\n        17: 2,  # 'ק'\n        7: 2,  # 'ר'\n        10: 2,  # 'ש'\n        5: 2,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    35: {  # 'ֹ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 2,  # 'א'\n        8: 2,  # 'ב'\n        20: 1,  # 'ג'\n        16: 2,  # 'ד'\n        3: 2,  # 'ה'\n        2: 1,  # 'ו'\n        24: 1,  # 'ז'\n        14: 1,  # 'ח'\n        22: 1,  # 'ט'\n        1: 1,  # 'י'\n        25: 1,  # 'ך'\n        15: 2,  # 'כ'\n        4: 2,  # 'ל'\n        11: 2,  # 'ם'\n        6: 2,  # 'מ'\n        23: 2,  # 'ן'\n        12: 2,  # 'נ'\n        19: 2,  # 'ס'\n        13: 2,  # 'ע'\n        26: 1,  # 'ף'\n        18: 2,  # 'פ'\n        27: 1,  # 'ץ'\n        21: 2,  # 'צ'\n        17: 2,  # 'ק'\n        7: 2,  # 'ר'\n        10: 2,  # 'ש'\n        5: 2,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    62: {  # 'ֻ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 1,  # 'ב'\n        20: 1,  # 'ג'\n        16: 1,  # 'ד'\n        3: 1,  # 'ה'\n        2: 1,  # 'ו'\n        24: 1,  # 'ז'\n        14: 1,  # 'ח'\n        22: 0,  # 'ט'\n        1: 1,  # 'י'\n        25: 0,  # 'ך'\n        15: 1,  # 'כ'\n        4: 2,  # 'ל'\n        11: 1,  # 'ם'\n        6: 1,  # 'מ'\n        23: 1,  # 'ן'\n        12: 1,  # 'נ'\n        19: 1,  # 'ס'\n        13: 1,  # 'ע'\n        26: 0,  # 'ף'\n        18: 1,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 1,  # 'צ'\n        17: 1,  # 'ק'\n        7: 1,  # 'ר'\n        10: 1,  # 'ש'\n        5: 1,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    28: {  # 'ּ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 3,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 1,  # 'ֲ'\n        33: 3,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 3,  # 'ַ'\n        29: 3,  # 'ָ'\n        35: 2,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 2,  # 'ׁ'\n        45: 1,  # 'ׂ'\n        9: 2,  # 'א'\n        8: 2,  # 'ב'\n        20: 1,  # 'ג'\n        16: 2,  # 'ד'\n        3: 1,  # 'ה'\n        2: 2,  # 'ו'\n        24: 1,  # 'ז'\n        14: 1,  # 'ח'\n        22: 1,  # 'ט'\n        1: 2,  # 'י'\n        25: 2,  # 'ך'\n        15: 2,  # 'כ'\n        4: 2,  # 'ל'\n        11: 1,  # 'ם'\n        6: 2,  # 'מ'\n        23: 1,  # 'ן'\n        12: 2,  # 'נ'\n        19: 1,  # 'ס'\n        13: 2,  # 'ע'\n        26: 1,  # 'ף'\n        18: 1,  # 'פ'\n        27: 1,  # 'ץ'\n        21: 1,  # 'צ'\n        17: 1,  # 'ק'\n        7: 2,  # 'ר'\n        10: 2,  # 'ש'\n        5: 2,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    38: {  # 'ׁ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 2,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 1,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 1,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    45: {  # 'ׂ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 1,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 1,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 1,  # 'א'\n        8: 0,  # 'ב'\n        20: 1,  # 'ג'\n        16: 0,  # 'ד'\n        3: 1,  # 'ה'\n        2: 2,  # 'ו'\n        24: 0,  # 'ז'\n        14: 1,  # 'ח'\n        22: 0,  # 'ט'\n        1: 1,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 1,  # 'ם'\n        6: 1,  # 'מ'\n        23: 0,  # 'ן'\n        12: 1,  # 'נ'\n        19: 0,  # 'ס'\n        13: 1,  # 'ע'\n        26: 0,  # 'ף'\n        18: 1,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 1,  # 'ר'\n        10: 0,  # 'ש'\n        5: 1,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    9: {  # 'א'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 1,  # '´'\n        48: 1,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 2,  # 'ֱ'\n        41: 2,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 2,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 2,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 3,  # 'ז'\n        14: 3,  # 'ח'\n        22: 3,  # 'ט'\n        1: 3,  # 'י'\n        25: 3,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 3,  # 'ן'\n        12: 3,  # 'נ'\n        19: 3,  # 'ס'\n        13: 2,  # 'ע'\n        26: 3,  # 'ף'\n        18: 3,  # 'פ'\n        27: 1,  # 'ץ'\n        21: 3,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    8: {  # 'ב'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 1,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 1,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 2,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 3,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 3,  # 'ז'\n        14: 3,  # 'ח'\n        22: 3,  # 'ט'\n        1: 3,  # 'י'\n        25: 2,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 2,  # 'ם'\n        6: 3,  # 'מ'\n        23: 3,  # 'ן'\n        12: 3,  # 'נ'\n        19: 3,  # 'ס'\n        13: 3,  # 'ע'\n        26: 1,  # 'ף'\n        18: 3,  # 'פ'\n        27: 2,  # 'ץ'\n        21: 3,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 1,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    20: {  # 'ג'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 2,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 1,  # 'ִ'\n        37: 1,  # 'ֵ'\n        36: 1,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 2,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 2,  # 'א'\n        8: 3,  # 'ב'\n        20: 2,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 3,  # 'ז'\n        14: 2,  # 'ח'\n        22: 2,  # 'ט'\n        1: 3,  # 'י'\n        25: 1,  # 'ך'\n        15: 1,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 3,  # 'ן'\n        12: 3,  # 'נ'\n        19: 2,  # 'ס'\n        13: 3,  # 'ע'\n        26: 2,  # 'ף'\n        18: 2,  # 'פ'\n        27: 1,  # 'ץ'\n        21: 1,  # 'צ'\n        17: 1,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 1,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    16: {  # 'ד'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 2,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 2,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 1,  # 'ז'\n        14: 2,  # 'ח'\n        22: 2,  # 'ט'\n        1: 3,  # 'י'\n        25: 2,  # 'ך'\n        15: 2,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 2,  # 'ן'\n        12: 3,  # 'נ'\n        19: 2,  # 'ס'\n        13: 3,  # 'ע'\n        26: 2,  # 'ף'\n        18: 3,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 2,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    3: {  # 'ה'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 1,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 0,  # '´'\n        48: 1,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 1,  # 'ְ'\n        59: 1,  # 'ֱ'\n        41: 2,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 3,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 2,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 3,  # 'ז'\n        14: 3,  # 'ח'\n        22: 3,  # 'ט'\n        1: 3,  # 'י'\n        25: 1,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 3,  # 'ן'\n        12: 3,  # 'נ'\n        19: 3,  # 'ס'\n        13: 3,  # 'ע'\n        26: 0,  # 'ף'\n        18: 3,  # 'פ'\n        27: 1,  # 'ץ'\n        21: 3,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 1,  # '–'\n        52: 1,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 2,  # '…'\n    },\n    2: {  # 'ו'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 1,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 1,  # '´'\n        48: 1,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 1,  # 'ֵ'\n        36: 1,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 3,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 3,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 3,  # 'ז'\n        14: 3,  # 'ח'\n        22: 3,  # 'ט'\n        1: 3,  # 'י'\n        25: 3,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 3,  # 'ן'\n        12: 3,  # 'נ'\n        19: 3,  # 'ס'\n        13: 3,  # 'ע'\n        26: 3,  # 'ף'\n        18: 3,  # 'פ'\n        27: 3,  # 'ץ'\n        21: 3,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 1,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 2,  # '…'\n    },\n    24: {  # 'ז'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 1,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 1,  # 'ֲ'\n        33: 1,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 2,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 2,  # 'ב'\n        20: 2,  # 'ג'\n        16: 2,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 2,  # 'ז'\n        14: 2,  # 'ח'\n        22: 1,  # 'ט'\n        1: 3,  # 'י'\n        25: 1,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 2,  # 'ם'\n        6: 3,  # 'מ'\n        23: 2,  # 'ן'\n        12: 2,  # 'נ'\n        19: 1,  # 'ס'\n        13: 2,  # 'ע'\n        26: 1,  # 'ף'\n        18: 1,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 2,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 1,  # 'ש'\n        5: 2,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    14: {  # 'ח'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 1,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 1,  # 'ֱ'\n        41: 2,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 2,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 2,  # 'א'\n        8: 3,  # 'ב'\n        20: 2,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 3,  # 'ז'\n        14: 2,  # 'ח'\n        22: 2,  # 'ט'\n        1: 3,  # 'י'\n        25: 1,  # 'ך'\n        15: 2,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 2,  # 'ן'\n        12: 3,  # 'נ'\n        19: 3,  # 'ס'\n        13: 1,  # 'ע'\n        26: 2,  # 'ף'\n        18: 2,  # 'פ'\n        27: 2,  # 'ץ'\n        21: 3,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 1,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    22: {  # 'ט'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 1,  # 'ֵ'\n        36: 1,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 1,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 1,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 1,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 2,  # 'ז'\n        14: 3,  # 'ח'\n        22: 2,  # 'ט'\n        1: 3,  # 'י'\n        25: 1,  # 'ך'\n        15: 2,  # 'כ'\n        4: 3,  # 'ל'\n        11: 2,  # 'ם'\n        6: 2,  # 'מ'\n        23: 2,  # 'ן'\n        12: 3,  # 'נ'\n        19: 2,  # 'ס'\n        13: 3,  # 'ע'\n        26: 2,  # 'ף'\n        18: 3,  # 'פ'\n        27: 1,  # 'ץ'\n        21: 2,  # 'צ'\n        17: 2,  # 'ק'\n        7: 3,  # 'ר'\n        10: 2,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    1: {  # 'י'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 1,  # '´'\n        48: 1,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 1,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 2,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 2,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 3,  # 'ז'\n        14: 3,  # 'ח'\n        22: 3,  # 'ט'\n        1: 3,  # 'י'\n        25: 3,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 3,  # 'ן'\n        12: 3,  # 'נ'\n        19: 3,  # 'ס'\n        13: 3,  # 'ע'\n        26: 3,  # 'ף'\n        18: 3,  # 'פ'\n        27: 3,  # 'ץ'\n        21: 3,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 1,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 2,  # '…'\n    },\n    25: {  # 'ך'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 1,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 1,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 1,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 1,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 1,  # 'ל'\n        11: 0,  # 'ם'\n        6: 1,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 1,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    15: {  # 'כ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 3,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 2,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 3,  # 'ז'\n        14: 3,  # 'ח'\n        22: 2,  # 'ט'\n        1: 3,  # 'י'\n        25: 3,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 3,  # 'ן'\n        12: 3,  # 'נ'\n        19: 3,  # 'ס'\n        13: 2,  # 'ע'\n        26: 3,  # 'ף'\n        18: 3,  # 'פ'\n        27: 1,  # 'ץ'\n        21: 2,  # 'צ'\n        17: 2,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    4: {  # 'ל'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 1,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 3,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 2,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 2,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 3,  # 'ז'\n        14: 3,  # 'ח'\n        22: 3,  # 'ט'\n        1: 3,  # 'י'\n        25: 3,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 2,  # 'ן'\n        12: 3,  # 'נ'\n        19: 3,  # 'ס'\n        13: 3,  # 'ע'\n        26: 2,  # 'ף'\n        18: 3,  # 'פ'\n        27: 2,  # 'ץ'\n        21: 3,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 1,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    11: {  # 'ם'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 1,  # 'א'\n        8: 1,  # 'ב'\n        20: 1,  # 'ג'\n        16: 0,  # 'ד'\n        3: 1,  # 'ה'\n        2: 1,  # 'ו'\n        24: 1,  # 'ז'\n        14: 1,  # 'ח'\n        22: 0,  # 'ט'\n        1: 1,  # 'י'\n        25: 0,  # 'ך'\n        15: 1,  # 'כ'\n        4: 1,  # 'ל'\n        11: 1,  # 'ם'\n        6: 1,  # 'מ'\n        23: 0,  # 'ן'\n        12: 1,  # 'נ'\n        19: 0,  # 'ס'\n        13: 1,  # 'ע'\n        26: 0,  # 'ף'\n        18: 1,  # 'פ'\n        27: 1,  # 'ץ'\n        21: 1,  # 'צ'\n        17: 1,  # 'ק'\n        7: 1,  # 'ר'\n        10: 1,  # 'ש'\n        5: 1,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 2,  # '…'\n    },\n    6: {  # 'מ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 1,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 2,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 2,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 3,  # 'ז'\n        14: 3,  # 'ח'\n        22: 3,  # 'ט'\n        1: 3,  # 'י'\n        25: 2,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 3,  # 'ן'\n        12: 3,  # 'נ'\n        19: 3,  # 'ס'\n        13: 3,  # 'ע'\n        26: 0,  # 'ף'\n        18: 3,  # 'פ'\n        27: 2,  # 'ץ'\n        21: 3,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    23: {  # 'ן'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 0,  # '´'\n        48: 1,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 1,  # 'א'\n        8: 1,  # 'ב'\n        20: 1,  # 'ג'\n        16: 1,  # 'ד'\n        3: 1,  # 'ה'\n        2: 1,  # 'ו'\n        24: 0,  # 'ז'\n        14: 1,  # 'ח'\n        22: 1,  # 'ט'\n        1: 1,  # 'י'\n        25: 0,  # 'ך'\n        15: 1,  # 'כ'\n        4: 1,  # 'ל'\n        11: 1,  # 'ם'\n        6: 1,  # 'מ'\n        23: 0,  # 'ן'\n        12: 1,  # 'נ'\n        19: 1,  # 'ס'\n        13: 1,  # 'ע'\n        26: 1,  # 'ף'\n        18: 1,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 1,  # 'ק'\n        7: 1,  # 'ר'\n        10: 1,  # 'ש'\n        5: 1,  # 'ת'\n        32: 1,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 2,  # '…'\n    },\n    12: {  # 'נ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 2,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 3,  # 'ז'\n        14: 3,  # 'ח'\n        22: 3,  # 'ט'\n        1: 3,  # 'י'\n        25: 2,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 3,  # 'ן'\n        12: 3,  # 'נ'\n        19: 3,  # 'ס'\n        13: 3,  # 'ע'\n        26: 2,  # 'ף'\n        18: 3,  # 'פ'\n        27: 2,  # 'ץ'\n        21: 3,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    19: {  # 'ס'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 1,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 1,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 1,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 2,  # 'ֻ'\n        28: 2,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 2,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 1,  # 'ז'\n        14: 3,  # 'ח'\n        22: 3,  # 'ט'\n        1: 3,  # 'י'\n        25: 2,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 2,  # 'ם'\n        6: 3,  # 'מ'\n        23: 2,  # 'ן'\n        12: 3,  # 'נ'\n        19: 2,  # 'ס'\n        13: 3,  # 'ע'\n        26: 3,  # 'ף'\n        18: 3,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 2,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 1,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    13: {  # 'ע'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 1,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 1,  # 'ְ'\n        59: 1,  # 'ֱ'\n        41: 2,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 2,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 2,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 3,  # 'ז'\n        14: 1,  # 'ח'\n        22: 3,  # 'ט'\n        1: 3,  # 'י'\n        25: 2,  # 'ך'\n        15: 2,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 2,  # 'ן'\n        12: 3,  # 'נ'\n        19: 3,  # 'ס'\n        13: 2,  # 'ע'\n        26: 1,  # 'ף'\n        18: 2,  # 'פ'\n        27: 2,  # 'ץ'\n        21: 3,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    26: {  # 'ף'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 1,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 1,  # 'ו'\n        24: 0,  # 'ז'\n        14: 1,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 1,  # 'כ'\n        4: 1,  # 'ל'\n        11: 0,  # 'ם'\n        6: 1,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 1,  # 'ס'\n        13: 0,  # 'ע'\n        26: 1,  # 'ף'\n        18: 1,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 1,  # 'ק'\n        7: 1,  # 'ר'\n        10: 1,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    18: {  # 'פ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 1,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 1,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 1,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 2,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 2,  # 'ב'\n        20: 3,  # 'ג'\n        16: 2,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 2,  # 'ז'\n        14: 3,  # 'ח'\n        22: 3,  # 'ט'\n        1: 3,  # 'י'\n        25: 2,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 2,  # 'ם'\n        6: 2,  # 'מ'\n        23: 3,  # 'ן'\n        12: 3,  # 'נ'\n        19: 3,  # 'ס'\n        13: 3,  # 'ע'\n        26: 2,  # 'ף'\n        18: 2,  # 'פ'\n        27: 2,  # 'ץ'\n        21: 3,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    27: {  # 'ץ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 1,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 1,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 1,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 1,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 1,  # 'ר'\n        10: 0,  # 'ש'\n        5: 1,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    21: {  # 'צ'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 1,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 1,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 2,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 2,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 1,  # 'ז'\n        14: 3,  # 'ח'\n        22: 2,  # 'ט'\n        1: 3,  # 'י'\n        25: 1,  # 'ך'\n        15: 1,  # 'כ'\n        4: 3,  # 'ל'\n        11: 2,  # 'ם'\n        6: 3,  # 'מ'\n        23: 2,  # 'ן'\n        12: 3,  # 'נ'\n        19: 1,  # 'ס'\n        13: 3,  # 'ע'\n        26: 2,  # 'ף'\n        18: 3,  # 'פ'\n        27: 2,  # 'ץ'\n        21: 2,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 0,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    17: {  # 'ק'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 1,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 1,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 2,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 2,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 2,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 2,  # 'ז'\n        14: 3,  # 'ח'\n        22: 3,  # 'ט'\n        1: 3,  # 'י'\n        25: 1,  # 'ך'\n        15: 1,  # 'כ'\n        4: 3,  # 'ל'\n        11: 2,  # 'ם'\n        6: 3,  # 'מ'\n        23: 2,  # 'ן'\n        12: 3,  # 'נ'\n        19: 3,  # 'ס'\n        13: 3,  # 'ע'\n        26: 2,  # 'ף'\n        18: 3,  # 'פ'\n        27: 2,  # 'ץ'\n        21: 3,  # 'צ'\n        17: 2,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 1,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    7: {  # 'ר'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 2,  # '´'\n        48: 1,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 1,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 2,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 3,  # 'ז'\n        14: 3,  # 'ח'\n        22: 3,  # 'ט'\n        1: 3,  # 'י'\n        25: 3,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 3,  # 'ן'\n        12: 3,  # 'נ'\n        19: 3,  # 'ס'\n        13: 3,  # 'ע'\n        26: 2,  # 'ף'\n        18: 3,  # 'פ'\n        27: 3,  # 'ץ'\n        21: 3,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 2,  # '…'\n    },\n    10: {  # 'ש'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 1,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 1,  # 'ִ'\n        37: 1,  # 'ֵ'\n        36: 1,  # 'ֶ'\n        31: 1,  # 'ַ'\n        29: 1,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 2,  # 'ּ'\n        38: 3,  # 'ׁ'\n        45: 2,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 3,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 2,  # 'ז'\n        14: 3,  # 'ח'\n        22: 3,  # 'ט'\n        1: 3,  # 'י'\n        25: 3,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 2,  # 'ן'\n        12: 3,  # 'נ'\n        19: 2,  # 'ס'\n        13: 3,  # 'ע'\n        26: 2,  # 'ף'\n        18: 3,  # 'פ'\n        27: 1,  # 'ץ'\n        21: 2,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 1,  # '…'\n    },\n    5: {  # 'ת'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 1,  # '\\xa0'\n        55: 0,  # '´'\n        48: 1,  # '¼'\n        39: 1,  # '½'\n        57: 0,  # '¾'\n        30: 2,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 2,  # 'ִ'\n        37: 2,  # 'ֵ'\n        36: 2,  # 'ֶ'\n        31: 2,  # 'ַ'\n        29: 2,  # 'ָ'\n        35: 1,  # 'ֹ'\n        62: 1,  # 'ֻ'\n        28: 2,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 3,  # 'א'\n        8: 3,  # 'ב'\n        20: 3,  # 'ג'\n        16: 2,  # 'ד'\n        3: 3,  # 'ה'\n        2: 3,  # 'ו'\n        24: 2,  # 'ז'\n        14: 3,  # 'ח'\n        22: 2,  # 'ט'\n        1: 3,  # 'י'\n        25: 2,  # 'ך'\n        15: 3,  # 'כ'\n        4: 3,  # 'ל'\n        11: 3,  # 'ם'\n        6: 3,  # 'מ'\n        23: 3,  # 'ן'\n        12: 3,  # 'נ'\n        19: 2,  # 'ס'\n        13: 3,  # 'ע'\n        26: 2,  # 'ף'\n        18: 3,  # 'פ'\n        27: 1,  # 'ץ'\n        21: 2,  # 'צ'\n        17: 3,  # 'ק'\n        7: 3,  # 'ר'\n        10: 3,  # 'ש'\n        5: 3,  # 'ת'\n        32: 1,  # '–'\n        52: 1,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 2,  # '…'\n    },\n    32: {  # '–'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 1,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 1,  # 'א'\n        8: 1,  # 'ב'\n        20: 1,  # 'ג'\n        16: 1,  # 'ד'\n        3: 1,  # 'ה'\n        2: 1,  # 'ו'\n        24: 0,  # 'ז'\n        14: 1,  # 'ח'\n        22: 0,  # 'ט'\n        1: 1,  # 'י'\n        25: 0,  # 'ך'\n        15: 1,  # 'כ'\n        4: 1,  # 'ל'\n        11: 0,  # 'ם'\n        6: 1,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 1,  # 'ס'\n        13: 1,  # 'ע'\n        26: 0,  # 'ף'\n        18: 1,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 1,  # 'צ'\n        17: 0,  # 'ק'\n        7: 1,  # 'ר'\n        10: 1,  # 'ש'\n        5: 1,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    52: {  # '’'\n        50: 1,  # 'a'\n        60: 0,  # 'c'\n        61: 1,  # 'd'\n        42: 1,  # 'e'\n        53: 1,  # 'i'\n        56: 1,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 1,  # 'r'\n        43: 2,  # 's'\n        44: 2,  # 't'\n        63: 1,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 1,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 1,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 1,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    47: {  # '“'\n        50: 1,  # 'a'\n        60: 1,  # 'c'\n        61: 1,  # 'd'\n        42: 1,  # 'e'\n        53: 1,  # 'i'\n        56: 1,  # 'l'\n        54: 1,  # 'n'\n        49: 1,  # 'o'\n        51: 1,  # 'r'\n        43: 1,  # 's'\n        44: 1,  # 't'\n        63: 1,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 2,  # 'א'\n        8: 1,  # 'ב'\n        20: 1,  # 'ג'\n        16: 1,  # 'ד'\n        3: 1,  # 'ה'\n        2: 1,  # 'ו'\n        24: 1,  # 'ז'\n        14: 1,  # 'ח'\n        22: 1,  # 'ט'\n        1: 1,  # 'י'\n        25: 0,  # 'ך'\n        15: 1,  # 'כ'\n        4: 1,  # 'ל'\n        11: 0,  # 'ם'\n        6: 1,  # 'מ'\n        23: 0,  # 'ן'\n        12: 1,  # 'נ'\n        19: 1,  # 'ס'\n        13: 1,  # 'ע'\n        26: 0,  # 'ף'\n        18: 1,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 1,  # 'צ'\n        17: 1,  # 'ק'\n        7: 1,  # 'ר'\n        10: 1,  # 'ש'\n        5: 1,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    46: {  # '”'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 1,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 1,  # 'א'\n        8: 1,  # 'ב'\n        20: 1,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 1,  # 'י'\n        25: 0,  # 'ך'\n        15: 1,  # 'כ'\n        4: 1,  # 'ל'\n        11: 0,  # 'ם'\n        6: 1,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 1,  # 'צ'\n        17: 0,  # 'ק'\n        7: 1,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 0,  # '†'\n        40: 0,  # '…'\n    },\n    58: {  # '†'\n        50: 0,  # 'a'\n        60: 0,  # 'c'\n        61: 0,  # 'd'\n        42: 0,  # 'e'\n        53: 0,  # 'i'\n        56: 0,  # 'l'\n        54: 0,  # 'n'\n        49: 0,  # 'o'\n        51: 0,  # 'r'\n        43: 0,  # 's'\n        44: 0,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 0,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 0,  # 'ה'\n        2: 0,  # 'ו'\n        24: 0,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 0,  # 'י'\n        25: 0,  # 'ך'\n        15: 0,  # 'כ'\n        4: 0,  # 'ל'\n        11: 0,  # 'ם'\n        6: 0,  # 'מ'\n        23: 0,  # 'ן'\n        12: 0,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 0,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 0,  # 'ר'\n        10: 0,  # 'ש'\n        5: 0,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 0,  # '”'\n        58: 2,  # '†'\n        40: 0,  # '…'\n    },\n    40: {  # '…'\n        50: 1,  # 'a'\n        60: 1,  # 'c'\n        61: 1,  # 'd'\n        42: 1,  # 'e'\n        53: 1,  # 'i'\n        56: 0,  # 'l'\n        54: 1,  # 'n'\n        49: 0,  # 'o'\n        51: 1,  # 'r'\n        43: 1,  # 's'\n        44: 1,  # 't'\n        63: 0,  # 'u'\n        34: 0,  # '\\xa0'\n        55: 0,  # '´'\n        48: 0,  # '¼'\n        39: 0,  # '½'\n        57: 0,  # '¾'\n        30: 0,  # 'ְ'\n        59: 0,  # 'ֱ'\n        41: 0,  # 'ֲ'\n        33: 0,  # 'ִ'\n        37: 0,  # 'ֵ'\n        36: 0,  # 'ֶ'\n        31: 0,  # 'ַ'\n        29: 0,  # 'ָ'\n        35: 0,  # 'ֹ'\n        62: 0,  # 'ֻ'\n        28: 0,  # 'ּ'\n        38: 0,  # 'ׁ'\n        45: 0,  # 'ׂ'\n        9: 1,  # 'א'\n        8: 0,  # 'ב'\n        20: 0,  # 'ג'\n        16: 0,  # 'ד'\n        3: 1,  # 'ה'\n        2: 1,  # 'ו'\n        24: 1,  # 'ז'\n        14: 0,  # 'ח'\n        22: 0,  # 'ט'\n        1: 1,  # 'י'\n        25: 0,  # 'ך'\n        15: 1,  # 'כ'\n        4: 1,  # 'ל'\n        11: 0,  # 'ם'\n        6: 1,  # 'מ'\n        23: 0,  # 'ן'\n        12: 1,  # 'נ'\n        19: 0,  # 'ס'\n        13: 0,  # 'ע'\n        26: 0,  # 'ף'\n        18: 1,  # 'פ'\n        27: 0,  # 'ץ'\n        21: 0,  # 'צ'\n        17: 0,  # 'ק'\n        7: 1,  # 'ר'\n        10: 1,  # 'ש'\n        5: 1,  # 'ת'\n        32: 0,  # '–'\n        52: 0,  # '’'\n        47: 0,  # '“'\n        46: 1,  # '”'\n        58: 0,  # '†'\n        40: 2,  # '…'\n    },\n}\n\n# 255: Undefined characters that did not exist in training text\n# 254: Carriage/Return\n# 253: symbol (punctuation) that does not belong to word\n# 252: 0 - 9\n# 251: Control characters\n\n# Character Mapping Table(s):\nWINDOWS_1255_HEBREW_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 254,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 254,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 253,  # ' '\n    33: 253,  # '!'\n    34: 253,  # '\"'\n    35: 253,  # '#'\n    36: 253,  # '$'\n    37: 253,  # '%'\n    38: 253,  # '&'\n    39: 253,  # \"'\"\n    40: 253,  # '('\n    41: 253,  # ')'\n    42: 253,  # '*'\n    43: 253,  # '+'\n    44: 253,  # ','\n    45: 253,  # '-'\n    46: 253,  # '.'\n    47: 253,  # '/'\n    48: 252,  # '0'\n    49: 252,  # '1'\n    50: 252,  # '2'\n    51: 252,  # '3'\n    52: 252,  # '4'\n    53: 252,  # '5'\n    54: 252,  # '6'\n    55: 252,  # '7'\n    56: 252,  # '8'\n    57: 252,  # '9'\n    58: 253,  # ':'\n    59: 253,  # ';'\n    60: 253,  # '<'\n    61: 253,  # '='\n    62: 253,  # '>'\n    63: 253,  # '?'\n    64: 253,  # '@'\n    65: 69,  # 'A'\n    66: 91,  # 'B'\n    67: 79,  # 'C'\n    68: 80,  # 'D'\n    69: 92,  # 'E'\n    70: 89,  # 'F'\n    71: 97,  # 'G'\n    72: 90,  # 'H'\n    73: 68,  # 'I'\n    74: 111,  # 'J'\n    75: 112,  # 'K'\n    76: 82,  # 'L'\n    77: 73,  # 'M'\n    78: 95,  # 'N'\n    79: 85,  # 'O'\n    80: 78,  # 'P'\n    81: 121,  # 'Q'\n    82: 86,  # 'R'\n    83: 71,  # 'S'\n    84: 67,  # 'T'\n    85: 102,  # 'U'\n    86: 107,  # 'V'\n    87: 84,  # 'W'\n    88: 114,  # 'X'\n    89: 103,  # 'Y'\n    90: 115,  # 'Z'\n    91: 253,  # '['\n    92: 253,  # '\\\\'\n    93: 253,  # ']'\n    94: 253,  # '^'\n    95: 253,  # '_'\n    96: 253,  # '`'\n    97: 50,  # 'a'\n    98: 74,  # 'b'\n    99: 60,  # 'c'\n    100: 61,  # 'd'\n    101: 42,  # 'e'\n    102: 76,  # 'f'\n    103: 70,  # 'g'\n    104: 64,  # 'h'\n    105: 53,  # 'i'\n    106: 105,  # 'j'\n    107: 93,  # 'k'\n    108: 56,  # 'l'\n    109: 65,  # 'm'\n    110: 54,  # 'n'\n    111: 49,  # 'o'\n    112: 66,  # 'p'\n    113: 110,  # 'q'\n    114: 51,  # 'r'\n    115: 43,  # 's'\n    116: 44,  # 't'\n    117: 63,  # 'u'\n    118: 81,  # 'v'\n    119: 77,  # 'w'\n    120: 98,  # 'x'\n    121: 75,  # 'y'\n    122: 108,  # 'z'\n    123: 253,  # '{'\n    124: 253,  # '|'\n    125: 253,  # '}'\n    126: 253,  # '~'\n    127: 253,  # '\\x7f'\n    128: 124,  # '€'\n    129: 202,  # None\n    130: 203,  # '‚'\n    131: 204,  # 'ƒ'\n    132: 205,  # '„'\n    133: 40,  # '…'\n    134: 58,  # '†'\n    135: 206,  # '‡'\n    136: 207,  # 'ˆ'\n    137: 208,  # '‰'\n    138: 209,  # None\n    139: 210,  # '‹'\n    140: 211,  # None\n    141: 212,  # None\n    142: 213,  # None\n    143: 214,  # None\n    144: 215,  # None\n    145: 83,  # '‘'\n    146: 52,  # '’'\n    147: 47,  # '“'\n    148: 46,  # '”'\n    149: 72,  # '•'\n    150: 32,  # '–'\n    151: 94,  # '—'\n    152: 216,  # '˜'\n    153: 113,  # '™'\n    154: 217,  # None\n    155: 109,  # '›'\n    156: 218,  # None\n    157: 219,  # None\n    158: 220,  # None\n    159: 221,  # None\n    160: 34,  # '\\xa0'\n    161: 116,  # '¡'\n    162: 222,  # '¢'\n    163: 118,  # '£'\n    164: 100,  # '₪'\n    165: 223,  # '¥'\n    166: 224,  # '¦'\n    167: 117,  # '§'\n    168: 119,  # '¨'\n    169: 104,  # '©'\n    170: 125,  # '×'\n    171: 225,  # '«'\n    172: 226,  # '¬'\n    173: 87,  # '\\xad'\n    174: 99,  # '®'\n    175: 227,  # '¯'\n    176: 106,  # '°'\n    177: 122,  # '±'\n    178: 123,  # '²'\n    179: 228,  # '³'\n    180: 55,  # '´'\n    181: 229,  # 'µ'\n    182: 230,  # '¶'\n    183: 101,  # '·'\n    184: 231,  # '¸'\n    185: 232,  # '¹'\n    186: 120,  # '÷'\n    187: 233,  # '»'\n    188: 48,  # '¼'\n    189: 39,  # '½'\n    190: 57,  # '¾'\n    191: 234,  # '¿'\n    192: 30,  # 'ְ'\n    193: 59,  # 'ֱ'\n    194: 41,  # 'ֲ'\n    195: 88,  # 'ֳ'\n    196: 33,  # 'ִ'\n    197: 37,  # 'ֵ'\n    198: 36,  # 'ֶ'\n    199: 31,  # 'ַ'\n    200: 29,  # 'ָ'\n    201: 35,  # 'ֹ'\n    202: 235,  # None\n    203: 62,  # 'ֻ'\n    204: 28,  # 'ּ'\n    205: 236,  # 'ֽ'\n    206: 126,  # '־'\n    207: 237,  # 'ֿ'\n    208: 238,  # '׀'\n    209: 38,  # 'ׁ'\n    210: 45,  # 'ׂ'\n    211: 239,  # '׃'\n    212: 240,  # 'װ'\n    213: 241,  # 'ױ'\n    214: 242,  # 'ײ'\n    215: 243,  # '׳'\n    216: 127,  # '״'\n    217: 244,  # None\n    218: 245,  # None\n    219: 246,  # None\n    220: 247,  # None\n    221: 248,  # None\n    222: 249,  # None\n    223: 250,  # None\n    224: 9,  # 'א'\n    225: 8,  # 'ב'\n    226: 20,  # 'ג'\n    227: 16,  # 'ד'\n    228: 3,  # 'ה'\n    229: 2,  # 'ו'\n    230: 24,  # 'ז'\n    231: 14,  # 'ח'\n    232: 22,  # 'ט'\n    233: 1,  # 'י'\n    234: 25,  # 'ך'\n    235: 15,  # 'כ'\n    236: 4,  # 'ל'\n    237: 11,  # 'ם'\n    238: 6,  # 'מ'\n    239: 23,  # 'ן'\n    240: 12,  # 'נ'\n    241: 19,  # 'ס'\n    242: 13,  # 'ע'\n    243: 26,  # 'ף'\n    244: 18,  # 'פ'\n    245: 27,  # 'ץ'\n    246: 21,  # 'צ'\n    247: 17,  # 'ק'\n    248: 7,  # 'ר'\n    249: 10,  # 'ש'\n    250: 5,  # 'ת'\n    251: 251,  # None\n    252: 252,  # None\n    253: 128,  # '\\u200e'\n    254: 96,  # '\\u200f'\n    255: 253,  # None\n}\n\nWINDOWS_1255_HEBREW_MODEL = SingleByteCharSetModel(\n    charset_name=\"windows-1255\",\n    language=\"Hebrew\",\n    char_to_order_map=WINDOWS_1255_HEBREW_CHAR_TO_ORDER,\n    language_model=HEBREW_LANG_MODEL,\n    typical_positive_ratio=0.984004,\n    keep_ascii_letters=False,\n    alphabet=\"אבגדהוזחטיךכלםמןנסעףפץצקרשתװױײ\",\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/langhungarianmodel.py",
    "content": "from pip._vendor.chardet.sbcharsetprober import SingleByteCharSetModel\n\n# 3: Positive\n# 2: Likely\n# 1: Unlikely\n# 0: Negative\n\nHUNGARIAN_LANG_MODEL = {\n    28: {  # 'A'\n        28: 0,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 2,  # 'D'\n        32: 1,  # 'E'\n        50: 1,  # 'F'\n        49: 2,  # 'G'\n        38: 1,  # 'H'\n        39: 2,  # 'I'\n        53: 1,  # 'J'\n        36: 2,  # 'K'\n        41: 2,  # 'L'\n        34: 1,  # 'M'\n        35: 2,  # 'N'\n        47: 1,  # 'O'\n        46: 2,  # 'P'\n        43: 2,  # 'R'\n        33: 2,  # 'S'\n        37: 2,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 1,  # 'Y'\n        52: 2,  # 'Z'\n        2: 0,  # 'a'\n        18: 1,  # 'b'\n        26: 1,  # 'c'\n        17: 2,  # 'd'\n        1: 1,  # 'e'\n        27: 1,  # 'f'\n        12: 1,  # 'g'\n        20: 1,  # 'h'\n        9: 1,  # 'i'\n        22: 1,  # 'j'\n        7: 2,  # 'k'\n        6: 2,  # 'l'\n        13: 2,  # 'm'\n        4: 2,  # 'n'\n        8: 0,  # 'o'\n        23: 2,  # 'p'\n        10: 2,  # 'r'\n        5: 1,  # 's'\n        3: 1,  # 't'\n        21: 1,  # 'u'\n        19: 1,  # 'v'\n        62: 1,  # 'x'\n        16: 0,  # 'y'\n        11: 3,  # 'z'\n        51: 1,  # 'Á'\n        44: 0,  # 'É'\n        61: 1,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    40: {  # 'B'\n        28: 2,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 2,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 1,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 0,  # 'M'\n        35: 1,  # 'N'\n        47: 2,  # 'O'\n        46: 0,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 2,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 3,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 0,  # 'h'\n        9: 2,  # 'i'\n        22: 1,  # 'j'\n        7: 0,  # 'k'\n        6: 1,  # 'l'\n        13: 0,  # 'm'\n        4: 0,  # 'n'\n        8: 2,  # 'o'\n        23: 1,  # 'p'\n        10: 2,  # 'r'\n        5: 0,  # 's'\n        3: 0,  # 't'\n        21: 3,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 0,  # 'z'\n        51: 1,  # 'Á'\n        44: 1,  # 'É'\n        61: 1,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 2,  # 'á'\n        15: 2,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 1,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 1,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    54: {  # 'C'\n        28: 1,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 1,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 1,  # 'H'\n        39: 2,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 0,  # 'N'\n        47: 1,  # 'O'\n        46: 1,  # 'P'\n        43: 1,  # 'R'\n        33: 2,  # 'S'\n        37: 1,  # 'T'\n        57: 1,  # 'U'\n        48: 0,  # 'V'\n        55: 1,  # 'Y'\n        52: 1,  # 'Z'\n        2: 2,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 1,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 1,  # 'h'\n        9: 1,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 1,  # 'l'\n        13: 0,  # 'm'\n        4: 0,  # 'n'\n        8: 2,  # 'o'\n        23: 0,  # 'p'\n        10: 1,  # 'r'\n        5: 3,  # 's'\n        3: 0,  # 't'\n        21: 1,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 1,  # 'z'\n        51: 1,  # 'Á'\n        44: 1,  # 'É'\n        61: 1,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 1,  # 'á'\n        15: 1,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    45: {  # 'D'\n        28: 2,  # 'A'\n        40: 1,  # 'B'\n        54: 0,  # 'C'\n        45: 1,  # 'D'\n        32: 2,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 2,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 0,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 2,  # 'O'\n        46: 0,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 1,  # 'Y'\n        52: 1,  # 'Z'\n        2: 2,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 3,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 0,  # 'h'\n        9: 1,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 0,  # 'n'\n        8: 1,  # 'o'\n        23: 0,  # 'p'\n        10: 2,  # 'r'\n        5: 0,  # 's'\n        3: 0,  # 't'\n        21: 2,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 1,  # 'z'\n        51: 1,  # 'Á'\n        44: 1,  # 'É'\n        61: 1,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 1,  # 'á'\n        15: 1,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 1,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 1,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    32: {  # 'E'\n        28: 1,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 1,  # 'E'\n        50: 1,  # 'F'\n        49: 2,  # 'G'\n        38: 1,  # 'H'\n        39: 1,  # 'I'\n        53: 1,  # 'J'\n        36: 2,  # 'K'\n        41: 2,  # 'L'\n        34: 2,  # 'M'\n        35: 2,  # 'N'\n        47: 1,  # 'O'\n        46: 1,  # 'P'\n        43: 2,  # 'R'\n        33: 2,  # 'S'\n        37: 2,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 1,  # 'Y'\n        52: 1,  # 'Z'\n        2: 1,  # 'a'\n        18: 1,  # 'b'\n        26: 1,  # 'c'\n        17: 2,  # 'd'\n        1: 1,  # 'e'\n        27: 1,  # 'f'\n        12: 3,  # 'g'\n        20: 1,  # 'h'\n        9: 1,  # 'i'\n        22: 1,  # 'j'\n        7: 1,  # 'k'\n        6: 2,  # 'l'\n        13: 2,  # 'm'\n        4: 2,  # 'n'\n        8: 0,  # 'o'\n        23: 1,  # 'p'\n        10: 2,  # 'r'\n        5: 2,  # 's'\n        3: 1,  # 't'\n        21: 2,  # 'u'\n        19: 1,  # 'v'\n        62: 1,  # 'x'\n        16: 0,  # 'y'\n        11: 3,  # 'z'\n        51: 1,  # 'Á'\n        44: 1,  # 'É'\n        61: 0,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 1,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    50: {  # 'F'\n        28: 1,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 1,  # 'E'\n        50: 1,  # 'F'\n        49: 0,  # 'G'\n        38: 1,  # 'H'\n        39: 1,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 1,  # 'O'\n        46: 0,  # 'P'\n        43: 1,  # 'R'\n        33: 0,  # 'S'\n        37: 1,  # 'T'\n        57: 1,  # 'U'\n        48: 0,  # 'V'\n        55: 1,  # 'Y'\n        52: 0,  # 'Z'\n        2: 2,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 2,  # 'e'\n        27: 1,  # 'f'\n        12: 0,  # 'g'\n        20: 0,  # 'h'\n        9: 2,  # 'i'\n        22: 1,  # 'j'\n        7: 0,  # 'k'\n        6: 1,  # 'l'\n        13: 0,  # 'm'\n        4: 0,  # 'n'\n        8: 2,  # 'o'\n        23: 0,  # 'p'\n        10: 2,  # 'r'\n        5: 0,  # 's'\n        3: 0,  # 't'\n        21: 1,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 0,  # 'z'\n        51: 1,  # 'Á'\n        44: 1,  # 'É'\n        61: 0,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 1,  # 'á'\n        15: 1,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 2,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 1,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    49: {  # 'G'\n        28: 2,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 2,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 1,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 1,  # 'O'\n        46: 1,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 2,  # 'Y'\n        52: 1,  # 'Z'\n        2: 2,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 2,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 0,  # 'h'\n        9: 1,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 1,  # 'l'\n        13: 0,  # 'm'\n        4: 0,  # 'n'\n        8: 2,  # 'o'\n        23: 0,  # 'p'\n        10: 2,  # 'r'\n        5: 0,  # 's'\n        3: 0,  # 't'\n        21: 1,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 2,  # 'y'\n        11: 0,  # 'z'\n        51: 1,  # 'Á'\n        44: 1,  # 'É'\n        61: 1,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 1,  # 'á'\n        15: 1,  # 'é'\n        30: 0,  # 'í'\n        25: 1,  # 'ó'\n        24: 1,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 1,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    38: {  # 'H'\n        28: 2,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 0,  # 'D'\n        32: 1,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 1,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 1,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 1,  # 'O'\n        46: 0,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 1,  # 'U'\n        48: 0,  # 'V'\n        55: 1,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 2,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 0,  # 'h'\n        9: 2,  # 'i'\n        22: 1,  # 'j'\n        7: 0,  # 'k'\n        6: 1,  # 'l'\n        13: 1,  # 'm'\n        4: 0,  # 'n'\n        8: 3,  # 'o'\n        23: 0,  # 'p'\n        10: 1,  # 'r'\n        5: 0,  # 's'\n        3: 0,  # 't'\n        21: 2,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 0,  # 'z'\n        51: 2,  # 'Á'\n        44: 2,  # 'É'\n        61: 1,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 2,  # 'á'\n        15: 1,  # 'é'\n        30: 2,  # 'í'\n        25: 1,  # 'ó'\n        24: 1,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 1,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    39: {  # 'I'\n        28: 2,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 1,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 2,  # 'I'\n        53: 1,  # 'J'\n        36: 2,  # 'K'\n        41: 2,  # 'L'\n        34: 1,  # 'M'\n        35: 2,  # 'N'\n        47: 1,  # 'O'\n        46: 1,  # 'P'\n        43: 1,  # 'R'\n        33: 2,  # 'S'\n        37: 1,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 0,  # 'Y'\n        52: 2,  # 'Z'\n        2: 0,  # 'a'\n        18: 1,  # 'b'\n        26: 1,  # 'c'\n        17: 2,  # 'd'\n        1: 0,  # 'e'\n        27: 1,  # 'f'\n        12: 2,  # 'g'\n        20: 1,  # 'h'\n        9: 0,  # 'i'\n        22: 1,  # 'j'\n        7: 1,  # 'k'\n        6: 2,  # 'l'\n        13: 2,  # 'm'\n        4: 1,  # 'n'\n        8: 0,  # 'o'\n        23: 1,  # 'p'\n        10: 2,  # 'r'\n        5: 2,  # 's'\n        3: 2,  # 't'\n        21: 0,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 1,  # 'z'\n        51: 1,  # 'Á'\n        44: 1,  # 'É'\n        61: 0,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    53: {  # 'J'\n        28: 2,  # 'A'\n        40: 0,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 2,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 1,  # 'H'\n        39: 1,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 1,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 1,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 1,  # 'Z'\n        2: 2,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 2,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 0,  # 'h'\n        9: 1,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 0,  # 'n'\n        8: 1,  # 'o'\n        23: 0,  # 'p'\n        10: 0,  # 'r'\n        5: 0,  # 's'\n        3: 0,  # 't'\n        21: 2,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 0,  # 'z'\n        51: 1,  # 'Á'\n        44: 1,  # 'É'\n        61: 0,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 2,  # 'á'\n        15: 1,  # 'é'\n        30: 0,  # 'í'\n        25: 2,  # 'ó'\n        24: 2,  # 'ö'\n        31: 1,  # 'ú'\n        29: 0,  # 'ü'\n        42: 1,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    36: {  # 'K'\n        28: 2,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 2,  # 'E'\n        50: 1,  # 'F'\n        49: 0,  # 'G'\n        38: 1,  # 'H'\n        39: 2,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 2,  # 'O'\n        46: 0,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 1,  # 'Y'\n        52: 0,  # 'Z'\n        2: 2,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 2,  # 'e'\n        27: 1,  # 'f'\n        12: 0,  # 'g'\n        20: 1,  # 'h'\n        9: 3,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 1,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        8: 2,  # 'o'\n        23: 0,  # 'p'\n        10: 2,  # 'r'\n        5: 0,  # 's'\n        3: 0,  # 't'\n        21: 1,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 0,  # 'z'\n        51: 1,  # 'Á'\n        44: 1,  # 'É'\n        61: 1,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 2,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 2,  # 'á'\n        15: 2,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 2,  # 'ö'\n        31: 1,  # 'ú'\n        29: 2,  # 'ü'\n        42: 1,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    41: {  # 'L'\n        28: 2,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 2,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 2,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 2,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 2,  # 'O'\n        46: 0,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 2,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 1,  # 'Y'\n        52: 1,  # 'Z'\n        2: 2,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 3,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 0,  # 'h'\n        9: 2,  # 'i'\n        22: 1,  # 'j'\n        7: 0,  # 'k'\n        6: 1,  # 'l'\n        13: 0,  # 'm'\n        4: 0,  # 'n'\n        8: 2,  # 'o'\n        23: 0,  # 'p'\n        10: 0,  # 'r'\n        5: 0,  # 's'\n        3: 0,  # 't'\n        21: 2,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 0,  # 'z'\n        51: 2,  # 'Á'\n        44: 1,  # 'É'\n        61: 1,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 2,  # 'á'\n        15: 1,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 1,  # 'ö'\n        31: 0,  # 'ú'\n        29: 1,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    34: {  # 'M'\n        28: 2,  # 'A'\n        40: 1,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 2,  # 'E'\n        50: 1,  # 'F'\n        49: 0,  # 'G'\n        38: 1,  # 'H'\n        39: 2,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 1,  # 'O'\n        46: 1,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 1,  # 'Y'\n        52: 1,  # 'Z'\n        2: 3,  # 'a'\n        18: 0,  # 'b'\n        26: 1,  # 'c'\n        17: 0,  # 'd'\n        1: 3,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 0,  # 'h'\n        9: 3,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 0,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        8: 3,  # 'o'\n        23: 0,  # 'p'\n        10: 1,  # 'r'\n        5: 0,  # 's'\n        3: 0,  # 't'\n        21: 2,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 0,  # 'z'\n        51: 2,  # 'Á'\n        44: 1,  # 'É'\n        61: 1,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 2,  # 'á'\n        15: 2,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 1,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 0,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    35: {  # 'N'\n        28: 2,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 2,  # 'D'\n        32: 2,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 1,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 1,  # 'O'\n        46: 1,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 2,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 2,  # 'Y'\n        52: 1,  # 'Z'\n        2: 3,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 3,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 0,  # 'h'\n        9: 2,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 1,  # 'n'\n        8: 2,  # 'o'\n        23: 0,  # 'p'\n        10: 0,  # 'r'\n        5: 0,  # 's'\n        3: 0,  # 't'\n        21: 1,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 2,  # 'y'\n        11: 0,  # 'z'\n        51: 1,  # 'Á'\n        44: 1,  # 'É'\n        61: 1,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 1,  # 'á'\n        15: 2,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 1,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 1,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    47: {  # 'O'\n        28: 1,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 1,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 1,  # 'I'\n        53: 1,  # 'J'\n        36: 2,  # 'K'\n        41: 2,  # 'L'\n        34: 2,  # 'M'\n        35: 2,  # 'N'\n        47: 1,  # 'O'\n        46: 1,  # 'P'\n        43: 2,  # 'R'\n        33: 2,  # 'S'\n        37: 2,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 1,  # 'Y'\n        52: 1,  # 'Z'\n        2: 0,  # 'a'\n        18: 1,  # 'b'\n        26: 1,  # 'c'\n        17: 1,  # 'd'\n        1: 1,  # 'e'\n        27: 1,  # 'f'\n        12: 1,  # 'g'\n        20: 1,  # 'h'\n        9: 1,  # 'i'\n        22: 1,  # 'j'\n        7: 2,  # 'k'\n        6: 2,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        8: 1,  # 'o'\n        23: 1,  # 'p'\n        10: 2,  # 'r'\n        5: 1,  # 's'\n        3: 2,  # 't'\n        21: 1,  # 'u'\n        19: 0,  # 'v'\n        62: 1,  # 'x'\n        16: 0,  # 'y'\n        11: 1,  # 'z'\n        51: 1,  # 'Á'\n        44: 1,  # 'É'\n        61: 0,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    46: {  # 'P'\n        28: 1,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 1,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 1,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 0,  # 'M'\n        35: 1,  # 'N'\n        47: 1,  # 'O'\n        46: 1,  # 'P'\n        43: 2,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 0,  # 'Y'\n        52: 1,  # 'Z'\n        2: 2,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 2,  # 'e'\n        27: 1,  # 'f'\n        12: 0,  # 'g'\n        20: 1,  # 'h'\n        9: 2,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 1,  # 'l'\n        13: 0,  # 'm'\n        4: 1,  # 'n'\n        8: 2,  # 'o'\n        23: 0,  # 'p'\n        10: 2,  # 'r'\n        5: 1,  # 's'\n        3: 0,  # 't'\n        21: 1,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 0,  # 'z'\n        51: 2,  # 'Á'\n        44: 1,  # 'É'\n        61: 1,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 3,  # 'á'\n        15: 2,  # 'é'\n        30: 0,  # 'í'\n        25: 1,  # 'ó'\n        24: 1,  # 'ö'\n        31: 0,  # 'ú'\n        29: 1,  # 'ü'\n        42: 1,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    43: {  # 'R'\n        28: 2,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 2,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 2,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 2,  # 'O'\n        46: 1,  # 'P'\n        43: 1,  # 'R'\n        33: 2,  # 'S'\n        37: 2,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 1,  # 'Y'\n        52: 1,  # 'Z'\n        2: 2,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 2,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 1,  # 'h'\n        9: 2,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 0,  # 'n'\n        8: 2,  # 'o'\n        23: 0,  # 'p'\n        10: 0,  # 'r'\n        5: 0,  # 's'\n        3: 0,  # 't'\n        21: 1,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 0,  # 'z'\n        51: 2,  # 'Á'\n        44: 1,  # 'É'\n        61: 1,  # 'Í'\n        58: 2,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 2,  # 'á'\n        15: 2,  # 'é'\n        30: 1,  # 'í'\n        25: 2,  # 'ó'\n        24: 1,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    33: {  # 'S'\n        28: 2,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 2,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 2,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 2,  # 'O'\n        46: 1,  # 'P'\n        43: 1,  # 'R'\n        33: 2,  # 'S'\n        37: 2,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 1,  # 'Y'\n        52: 3,  # 'Z'\n        2: 2,  # 'a'\n        18: 0,  # 'b'\n        26: 1,  # 'c'\n        17: 0,  # 'd'\n        1: 2,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 1,  # 'h'\n        9: 2,  # 'i'\n        22: 0,  # 'j'\n        7: 1,  # 'k'\n        6: 1,  # 'l'\n        13: 1,  # 'm'\n        4: 0,  # 'n'\n        8: 2,  # 'o'\n        23: 1,  # 'p'\n        10: 0,  # 'r'\n        5: 0,  # 's'\n        3: 1,  # 't'\n        21: 1,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 3,  # 'z'\n        51: 2,  # 'Á'\n        44: 1,  # 'É'\n        61: 1,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 2,  # 'á'\n        15: 1,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 1,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 1,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    37: {  # 'T'\n        28: 2,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 2,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 2,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 2,  # 'O'\n        46: 1,  # 'P'\n        43: 2,  # 'R'\n        33: 1,  # 'S'\n        37: 2,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 1,  # 'Y'\n        52: 1,  # 'Z'\n        2: 2,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 2,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 1,  # 'h'\n        9: 2,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 0,  # 'n'\n        8: 2,  # 'o'\n        23: 0,  # 'p'\n        10: 1,  # 'r'\n        5: 1,  # 's'\n        3: 0,  # 't'\n        21: 2,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 1,  # 'z'\n        51: 2,  # 'Á'\n        44: 2,  # 'É'\n        61: 1,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 2,  # 'á'\n        15: 1,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 2,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 1,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    57: {  # 'U'\n        28: 1,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 1,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 1,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 1,  # 'O'\n        46: 1,  # 'P'\n        43: 1,  # 'R'\n        33: 2,  # 'S'\n        37: 1,  # 'T'\n        57: 0,  # 'U'\n        48: 1,  # 'V'\n        55: 0,  # 'Y'\n        52: 1,  # 'Z'\n        2: 0,  # 'a'\n        18: 1,  # 'b'\n        26: 1,  # 'c'\n        17: 1,  # 'd'\n        1: 1,  # 'e'\n        27: 0,  # 'f'\n        12: 2,  # 'g'\n        20: 0,  # 'h'\n        9: 0,  # 'i'\n        22: 1,  # 'j'\n        7: 1,  # 'k'\n        6: 1,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        8: 0,  # 'o'\n        23: 1,  # 'p'\n        10: 1,  # 'r'\n        5: 1,  # 's'\n        3: 1,  # 't'\n        21: 0,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 1,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 1,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    48: {  # 'V'\n        28: 2,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 1,  # 'D'\n        32: 2,  # 'E'\n        50: 1,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 2,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 0,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 1,  # 'O'\n        46: 1,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 1,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 2,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 0,  # 'h'\n        9: 2,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 1,  # 'l'\n        13: 0,  # 'm'\n        4: 0,  # 'n'\n        8: 2,  # 'o'\n        23: 0,  # 'p'\n        10: 0,  # 'r'\n        5: 0,  # 's'\n        3: 0,  # 't'\n        21: 1,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 0,  # 'z'\n        51: 2,  # 'Á'\n        44: 2,  # 'É'\n        61: 1,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 2,  # 'á'\n        15: 2,  # 'é'\n        30: 1,  # 'í'\n        25: 0,  # 'ó'\n        24: 1,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    55: {  # 'Y'\n        28: 2,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 2,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 1,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 1,  # 'O'\n        46: 1,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 0,  # 'Y'\n        52: 2,  # 'Z'\n        2: 1,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 1,  # 'd'\n        1: 1,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 0,  # 'h'\n        9: 0,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 0,  # 'n'\n        8: 1,  # 'o'\n        23: 1,  # 'p'\n        10: 0,  # 'r'\n        5: 0,  # 's'\n        3: 0,  # 't'\n        21: 0,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 0,  # 'z'\n        51: 1,  # 'Á'\n        44: 1,  # 'É'\n        61: 1,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    52: {  # 'Z'\n        28: 2,  # 'A'\n        40: 1,  # 'B'\n        54: 0,  # 'C'\n        45: 1,  # 'D'\n        32: 2,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 2,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 2,  # 'O'\n        46: 1,  # 'P'\n        43: 1,  # 'R'\n        33: 2,  # 'S'\n        37: 1,  # 'T'\n        57: 1,  # 'U'\n        48: 1,  # 'V'\n        55: 1,  # 'Y'\n        52: 1,  # 'Z'\n        2: 1,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 1,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 0,  # 'h'\n        9: 1,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 1,  # 'n'\n        8: 1,  # 'o'\n        23: 0,  # 'p'\n        10: 1,  # 'r'\n        5: 2,  # 's'\n        3: 0,  # 't'\n        21: 1,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 0,  # 'z'\n        51: 2,  # 'Á'\n        44: 1,  # 'É'\n        61: 1,  # 'Í'\n        58: 1,  # 'Ó'\n        59: 1,  # 'Ö'\n        60: 1,  # 'Ú'\n        63: 1,  # 'Ü'\n        14: 1,  # 'á'\n        15: 1,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 1,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    2: {  # 'a'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 1,  # 'a'\n        18: 3,  # 'b'\n        26: 3,  # 'c'\n        17: 3,  # 'd'\n        1: 2,  # 'e'\n        27: 2,  # 'f'\n        12: 3,  # 'g'\n        20: 3,  # 'h'\n        9: 3,  # 'i'\n        22: 3,  # 'j'\n        7: 3,  # 'k'\n        6: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        8: 2,  # 'o'\n        23: 3,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 3,  # 'u'\n        19: 3,  # 'v'\n        62: 1,  # 'x'\n        16: 2,  # 'y'\n        11: 3,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 1,  # 'á'\n        15: 1,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 1,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    18: {  # 'b'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 3,  # 'b'\n        26: 1,  # 'c'\n        17: 1,  # 'd'\n        1: 3,  # 'e'\n        27: 1,  # 'f'\n        12: 1,  # 'g'\n        20: 1,  # 'h'\n        9: 3,  # 'i'\n        22: 2,  # 'j'\n        7: 2,  # 'k'\n        6: 2,  # 'l'\n        13: 1,  # 'm'\n        4: 2,  # 'n'\n        8: 3,  # 'o'\n        23: 1,  # 'p'\n        10: 3,  # 'r'\n        5: 2,  # 's'\n        3: 1,  # 't'\n        21: 3,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 1,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 2,  # 'í'\n        25: 3,  # 'ó'\n        24: 2,  # 'ö'\n        31: 2,  # 'ú'\n        29: 2,  # 'ü'\n        42: 2,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    26: {  # 'c'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 1,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 1,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 2,  # 'a'\n        18: 1,  # 'b'\n        26: 2,  # 'c'\n        17: 1,  # 'd'\n        1: 3,  # 'e'\n        27: 1,  # 'f'\n        12: 1,  # 'g'\n        20: 3,  # 'h'\n        9: 3,  # 'i'\n        22: 1,  # 'j'\n        7: 2,  # 'k'\n        6: 1,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        8: 3,  # 'o'\n        23: 1,  # 'p'\n        10: 2,  # 'r'\n        5: 3,  # 's'\n        3: 2,  # 't'\n        21: 2,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 2,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 2,  # 'á'\n        15: 2,  # 'é'\n        30: 2,  # 'í'\n        25: 1,  # 'ó'\n        24: 1,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    17: {  # 'd'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 2,  # 'b'\n        26: 1,  # 'c'\n        17: 2,  # 'd'\n        1: 3,  # 'e'\n        27: 1,  # 'f'\n        12: 1,  # 'g'\n        20: 2,  # 'h'\n        9: 3,  # 'i'\n        22: 3,  # 'j'\n        7: 2,  # 'k'\n        6: 1,  # 'l'\n        13: 2,  # 'm'\n        4: 3,  # 'n'\n        8: 3,  # 'o'\n        23: 1,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 3,  # 'u'\n        19: 3,  # 'v'\n        62: 0,  # 'x'\n        16: 2,  # 'y'\n        11: 2,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 3,  # 'í'\n        25: 3,  # 'ó'\n        24: 3,  # 'ö'\n        31: 2,  # 'ú'\n        29: 2,  # 'ü'\n        42: 2,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    1: {  # 'e'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 2,  # 'a'\n        18: 3,  # 'b'\n        26: 3,  # 'c'\n        17: 3,  # 'd'\n        1: 2,  # 'e'\n        27: 3,  # 'f'\n        12: 3,  # 'g'\n        20: 3,  # 'h'\n        9: 3,  # 'i'\n        22: 3,  # 'j'\n        7: 3,  # 'k'\n        6: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        8: 2,  # 'o'\n        23: 3,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 2,  # 'u'\n        19: 3,  # 'v'\n        62: 2,  # 'x'\n        16: 2,  # 'y'\n        11: 3,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 1,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 1,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    27: {  # 'f'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 1,  # 'b'\n        26: 1,  # 'c'\n        17: 1,  # 'd'\n        1: 3,  # 'e'\n        27: 2,  # 'f'\n        12: 1,  # 'g'\n        20: 1,  # 'h'\n        9: 3,  # 'i'\n        22: 2,  # 'j'\n        7: 1,  # 'k'\n        6: 1,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        8: 3,  # 'o'\n        23: 0,  # 'p'\n        10: 3,  # 'r'\n        5: 1,  # 's'\n        3: 1,  # 't'\n        21: 2,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 0,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 3,  # 'ö'\n        31: 1,  # 'ú'\n        29: 2,  # 'ü'\n        42: 1,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    12: {  # 'g'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 3,  # 'b'\n        26: 2,  # 'c'\n        17: 2,  # 'd'\n        1: 3,  # 'e'\n        27: 2,  # 'f'\n        12: 3,  # 'g'\n        20: 3,  # 'h'\n        9: 3,  # 'i'\n        22: 3,  # 'j'\n        7: 2,  # 'k'\n        6: 3,  # 'l'\n        13: 2,  # 'm'\n        4: 3,  # 'n'\n        8: 3,  # 'o'\n        23: 1,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 3,  # 'u'\n        19: 3,  # 'v'\n        62: 0,  # 'x'\n        16: 3,  # 'y'\n        11: 2,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 2,  # 'í'\n        25: 3,  # 'ó'\n        24: 2,  # 'ö'\n        31: 2,  # 'ú'\n        29: 2,  # 'ü'\n        42: 2,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    20: {  # 'h'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 1,  # 'b'\n        26: 1,  # 'c'\n        17: 0,  # 'd'\n        1: 3,  # 'e'\n        27: 0,  # 'f'\n        12: 1,  # 'g'\n        20: 2,  # 'h'\n        9: 3,  # 'i'\n        22: 1,  # 'j'\n        7: 1,  # 'k'\n        6: 1,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        8: 3,  # 'o'\n        23: 0,  # 'p'\n        10: 1,  # 'r'\n        5: 2,  # 's'\n        3: 1,  # 't'\n        21: 3,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 2,  # 'y'\n        11: 0,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 3,  # 'í'\n        25: 2,  # 'ó'\n        24: 2,  # 'ö'\n        31: 2,  # 'ú'\n        29: 1,  # 'ü'\n        42: 1,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    9: {  # 'i'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 3,  # 'b'\n        26: 3,  # 'c'\n        17: 3,  # 'd'\n        1: 3,  # 'e'\n        27: 3,  # 'f'\n        12: 3,  # 'g'\n        20: 3,  # 'h'\n        9: 2,  # 'i'\n        22: 2,  # 'j'\n        7: 3,  # 'k'\n        6: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        8: 2,  # 'o'\n        23: 2,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 3,  # 'u'\n        19: 3,  # 'v'\n        62: 1,  # 'x'\n        16: 1,  # 'y'\n        11: 3,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 2,  # 'é'\n        30: 1,  # 'í'\n        25: 3,  # 'ó'\n        24: 1,  # 'ö'\n        31: 2,  # 'ú'\n        29: 1,  # 'ü'\n        42: 0,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    22: {  # 'j'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 2,  # 'b'\n        26: 1,  # 'c'\n        17: 3,  # 'd'\n        1: 3,  # 'e'\n        27: 1,  # 'f'\n        12: 1,  # 'g'\n        20: 2,  # 'h'\n        9: 1,  # 'i'\n        22: 2,  # 'j'\n        7: 2,  # 'k'\n        6: 2,  # 'l'\n        13: 1,  # 'm'\n        4: 2,  # 'n'\n        8: 3,  # 'o'\n        23: 1,  # 'p'\n        10: 2,  # 'r'\n        5: 2,  # 's'\n        3: 3,  # 't'\n        21: 3,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 2,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 1,  # 'í'\n        25: 3,  # 'ó'\n        24: 3,  # 'ö'\n        31: 3,  # 'ú'\n        29: 2,  # 'ü'\n        42: 1,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    7: {  # 'k'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 3,  # 'b'\n        26: 2,  # 'c'\n        17: 1,  # 'd'\n        1: 3,  # 'e'\n        27: 1,  # 'f'\n        12: 1,  # 'g'\n        20: 2,  # 'h'\n        9: 3,  # 'i'\n        22: 2,  # 'j'\n        7: 3,  # 'k'\n        6: 3,  # 'l'\n        13: 1,  # 'm'\n        4: 3,  # 'n'\n        8: 3,  # 'o'\n        23: 1,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 3,  # 'u'\n        19: 2,  # 'v'\n        62: 0,  # 'x'\n        16: 2,  # 'y'\n        11: 1,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 3,  # 'í'\n        25: 2,  # 'ó'\n        24: 3,  # 'ö'\n        31: 1,  # 'ú'\n        29: 3,  # 'ü'\n        42: 1,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    6: {  # 'l'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 1,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 1,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 2,  # 'b'\n        26: 3,  # 'c'\n        17: 3,  # 'd'\n        1: 3,  # 'e'\n        27: 3,  # 'f'\n        12: 3,  # 'g'\n        20: 3,  # 'h'\n        9: 3,  # 'i'\n        22: 3,  # 'j'\n        7: 3,  # 'k'\n        6: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        8: 3,  # 'o'\n        23: 2,  # 'p'\n        10: 2,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 3,  # 'u'\n        19: 3,  # 'v'\n        62: 0,  # 'x'\n        16: 3,  # 'y'\n        11: 2,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 3,  # 'í'\n        25: 3,  # 'ó'\n        24: 3,  # 'ö'\n        31: 2,  # 'ú'\n        29: 2,  # 'ü'\n        42: 3,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    13: {  # 'm'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 3,  # 'b'\n        26: 2,  # 'c'\n        17: 1,  # 'd'\n        1: 3,  # 'e'\n        27: 1,  # 'f'\n        12: 1,  # 'g'\n        20: 2,  # 'h'\n        9: 3,  # 'i'\n        22: 2,  # 'j'\n        7: 1,  # 'k'\n        6: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 2,  # 'n'\n        8: 3,  # 'o'\n        23: 3,  # 'p'\n        10: 2,  # 'r'\n        5: 2,  # 's'\n        3: 2,  # 't'\n        21: 3,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 2,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 2,  # 'í'\n        25: 2,  # 'ó'\n        24: 2,  # 'ö'\n        31: 2,  # 'ú'\n        29: 2,  # 'ü'\n        42: 1,  # 'ő'\n        56: 2,  # 'ű'\n    },\n    4: {  # 'n'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 3,  # 'b'\n        26: 3,  # 'c'\n        17: 3,  # 'd'\n        1: 3,  # 'e'\n        27: 2,  # 'f'\n        12: 3,  # 'g'\n        20: 3,  # 'h'\n        9: 3,  # 'i'\n        22: 2,  # 'j'\n        7: 3,  # 'k'\n        6: 2,  # 'l'\n        13: 2,  # 'm'\n        4: 3,  # 'n'\n        8: 3,  # 'o'\n        23: 2,  # 'p'\n        10: 2,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 3,  # 'u'\n        19: 2,  # 'v'\n        62: 1,  # 'x'\n        16: 3,  # 'y'\n        11: 3,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 2,  # 'í'\n        25: 2,  # 'ó'\n        24: 3,  # 'ö'\n        31: 2,  # 'ú'\n        29: 3,  # 'ü'\n        42: 2,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    8: {  # 'o'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 1,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 2,  # 'a'\n        18: 3,  # 'b'\n        26: 3,  # 'c'\n        17: 3,  # 'd'\n        1: 2,  # 'e'\n        27: 2,  # 'f'\n        12: 3,  # 'g'\n        20: 3,  # 'h'\n        9: 2,  # 'i'\n        22: 2,  # 'j'\n        7: 3,  # 'k'\n        6: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        8: 1,  # 'o'\n        23: 3,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 2,  # 'u'\n        19: 3,  # 'v'\n        62: 1,  # 'x'\n        16: 1,  # 'y'\n        11: 3,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 1,  # 'á'\n        15: 2,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 1,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    23: {  # 'p'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 1,  # 'b'\n        26: 2,  # 'c'\n        17: 1,  # 'd'\n        1: 3,  # 'e'\n        27: 1,  # 'f'\n        12: 1,  # 'g'\n        20: 2,  # 'h'\n        9: 3,  # 'i'\n        22: 2,  # 'j'\n        7: 2,  # 'k'\n        6: 3,  # 'l'\n        13: 1,  # 'm'\n        4: 2,  # 'n'\n        8: 3,  # 'o'\n        23: 3,  # 'p'\n        10: 3,  # 'r'\n        5: 2,  # 's'\n        3: 2,  # 't'\n        21: 3,  # 'u'\n        19: 2,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 2,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 2,  # 'í'\n        25: 2,  # 'ó'\n        24: 2,  # 'ö'\n        31: 1,  # 'ú'\n        29: 2,  # 'ü'\n        42: 1,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    10: {  # 'r'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 3,  # 'b'\n        26: 3,  # 'c'\n        17: 3,  # 'd'\n        1: 3,  # 'e'\n        27: 2,  # 'f'\n        12: 3,  # 'g'\n        20: 2,  # 'h'\n        9: 3,  # 'i'\n        22: 3,  # 'j'\n        7: 3,  # 'k'\n        6: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        8: 3,  # 'o'\n        23: 2,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 3,  # 'u'\n        19: 3,  # 'v'\n        62: 1,  # 'x'\n        16: 2,  # 'y'\n        11: 3,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 2,  # 'í'\n        25: 3,  # 'ó'\n        24: 3,  # 'ö'\n        31: 3,  # 'ú'\n        29: 3,  # 'ü'\n        42: 2,  # 'ő'\n        56: 2,  # 'ű'\n    },\n    5: {  # 's'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 3,  # 'b'\n        26: 2,  # 'c'\n        17: 2,  # 'd'\n        1: 3,  # 'e'\n        27: 2,  # 'f'\n        12: 2,  # 'g'\n        20: 2,  # 'h'\n        9: 3,  # 'i'\n        22: 1,  # 'j'\n        7: 3,  # 'k'\n        6: 2,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        8: 3,  # 'o'\n        23: 2,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 3,  # 'u'\n        19: 2,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 3,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 3,  # 'í'\n        25: 3,  # 'ó'\n        24: 3,  # 'ö'\n        31: 3,  # 'ú'\n        29: 3,  # 'ü'\n        42: 2,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    3: {  # 't'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 3,  # 'b'\n        26: 2,  # 'c'\n        17: 1,  # 'd'\n        1: 3,  # 'e'\n        27: 2,  # 'f'\n        12: 1,  # 'g'\n        20: 3,  # 'h'\n        9: 3,  # 'i'\n        22: 3,  # 'j'\n        7: 3,  # 'k'\n        6: 3,  # 'l'\n        13: 2,  # 'm'\n        4: 3,  # 'n'\n        8: 3,  # 'o'\n        23: 1,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 3,  # 'u'\n        19: 3,  # 'v'\n        62: 0,  # 'x'\n        16: 3,  # 'y'\n        11: 1,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 2,  # 'í'\n        25: 3,  # 'ó'\n        24: 3,  # 'ö'\n        31: 3,  # 'ú'\n        29: 3,  # 'ü'\n        42: 3,  # 'ő'\n        56: 2,  # 'ű'\n    },\n    21: {  # 'u'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 1,  # 'a'\n        18: 2,  # 'b'\n        26: 2,  # 'c'\n        17: 3,  # 'd'\n        1: 2,  # 'e'\n        27: 1,  # 'f'\n        12: 3,  # 'g'\n        20: 2,  # 'h'\n        9: 2,  # 'i'\n        22: 2,  # 'j'\n        7: 3,  # 'k'\n        6: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        8: 1,  # 'o'\n        23: 2,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 1,  # 'u'\n        19: 3,  # 'v'\n        62: 1,  # 'x'\n        16: 1,  # 'y'\n        11: 2,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 2,  # 'á'\n        15: 1,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 0,  # 'ö'\n        31: 1,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    19: {  # 'v'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 2,  # 'b'\n        26: 1,  # 'c'\n        17: 1,  # 'd'\n        1: 3,  # 'e'\n        27: 1,  # 'f'\n        12: 1,  # 'g'\n        20: 1,  # 'h'\n        9: 3,  # 'i'\n        22: 1,  # 'j'\n        7: 1,  # 'k'\n        6: 1,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        8: 3,  # 'o'\n        23: 1,  # 'p'\n        10: 1,  # 'r'\n        5: 2,  # 's'\n        3: 2,  # 't'\n        21: 2,  # 'u'\n        19: 2,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 1,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 2,  # 'í'\n        25: 2,  # 'ó'\n        24: 2,  # 'ö'\n        31: 1,  # 'ú'\n        29: 2,  # 'ü'\n        42: 1,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    62: {  # 'x'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 1,  # 'a'\n        18: 1,  # 'b'\n        26: 1,  # 'c'\n        17: 0,  # 'd'\n        1: 1,  # 'e'\n        27: 1,  # 'f'\n        12: 0,  # 'g'\n        20: 0,  # 'h'\n        9: 1,  # 'i'\n        22: 0,  # 'j'\n        7: 1,  # 'k'\n        6: 1,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        8: 1,  # 'o'\n        23: 1,  # 'p'\n        10: 1,  # 'r'\n        5: 1,  # 's'\n        3: 1,  # 't'\n        21: 1,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 0,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 1,  # 'á'\n        15: 1,  # 'é'\n        30: 1,  # 'í'\n        25: 1,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    16: {  # 'y'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 2,  # 'b'\n        26: 1,  # 'c'\n        17: 1,  # 'd'\n        1: 3,  # 'e'\n        27: 2,  # 'f'\n        12: 2,  # 'g'\n        20: 2,  # 'h'\n        9: 3,  # 'i'\n        22: 2,  # 'j'\n        7: 2,  # 'k'\n        6: 2,  # 'l'\n        13: 2,  # 'm'\n        4: 3,  # 'n'\n        8: 3,  # 'o'\n        23: 2,  # 'p'\n        10: 2,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 3,  # 'u'\n        19: 3,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 2,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 2,  # 'í'\n        25: 2,  # 'ó'\n        24: 3,  # 'ö'\n        31: 2,  # 'ú'\n        29: 2,  # 'ü'\n        42: 1,  # 'ő'\n        56: 2,  # 'ű'\n    },\n    11: {  # 'z'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 3,  # 'a'\n        18: 2,  # 'b'\n        26: 1,  # 'c'\n        17: 3,  # 'd'\n        1: 3,  # 'e'\n        27: 1,  # 'f'\n        12: 2,  # 'g'\n        20: 2,  # 'h'\n        9: 3,  # 'i'\n        22: 1,  # 'j'\n        7: 3,  # 'k'\n        6: 2,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        8: 3,  # 'o'\n        23: 1,  # 'p'\n        10: 2,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 3,  # 'u'\n        19: 2,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 3,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 3,  # 'á'\n        15: 3,  # 'é'\n        30: 3,  # 'í'\n        25: 3,  # 'ó'\n        24: 3,  # 'ö'\n        31: 2,  # 'ú'\n        29: 3,  # 'ü'\n        42: 2,  # 'ő'\n        56: 1,  # 'ű'\n    },\n    51: {  # 'Á'\n        28: 0,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 0,  # 'E'\n        50: 1,  # 'F'\n        49: 2,  # 'G'\n        38: 1,  # 'H'\n        39: 1,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 2,  # 'L'\n        34: 1,  # 'M'\n        35: 2,  # 'N'\n        47: 0,  # 'O'\n        46: 1,  # 'P'\n        43: 2,  # 'R'\n        33: 2,  # 'S'\n        37: 1,  # 'T'\n        57: 0,  # 'U'\n        48: 1,  # 'V'\n        55: 0,  # 'Y'\n        52: 1,  # 'Z'\n        2: 0,  # 'a'\n        18: 1,  # 'b'\n        26: 1,  # 'c'\n        17: 1,  # 'd'\n        1: 0,  # 'e'\n        27: 0,  # 'f'\n        12: 1,  # 'g'\n        20: 1,  # 'h'\n        9: 0,  # 'i'\n        22: 1,  # 'j'\n        7: 1,  # 'k'\n        6: 2,  # 'l'\n        13: 2,  # 'm'\n        4: 0,  # 'n'\n        8: 0,  # 'o'\n        23: 1,  # 'p'\n        10: 1,  # 'r'\n        5: 1,  # 's'\n        3: 1,  # 't'\n        21: 0,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 1,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 1,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    44: {  # 'É'\n        28: 0,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 1,  # 'E'\n        50: 0,  # 'F'\n        49: 2,  # 'G'\n        38: 1,  # 'H'\n        39: 1,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 2,  # 'L'\n        34: 1,  # 'M'\n        35: 2,  # 'N'\n        47: 0,  # 'O'\n        46: 1,  # 'P'\n        43: 2,  # 'R'\n        33: 2,  # 'S'\n        37: 2,  # 'T'\n        57: 0,  # 'U'\n        48: 1,  # 'V'\n        55: 0,  # 'Y'\n        52: 1,  # 'Z'\n        2: 0,  # 'a'\n        18: 1,  # 'b'\n        26: 1,  # 'c'\n        17: 1,  # 'd'\n        1: 0,  # 'e'\n        27: 0,  # 'f'\n        12: 1,  # 'g'\n        20: 1,  # 'h'\n        9: 0,  # 'i'\n        22: 1,  # 'j'\n        7: 1,  # 'k'\n        6: 2,  # 'l'\n        13: 1,  # 'm'\n        4: 2,  # 'n'\n        8: 0,  # 'o'\n        23: 1,  # 'p'\n        10: 2,  # 'r'\n        5: 3,  # 's'\n        3: 1,  # 't'\n        21: 0,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 0,  # 'z'\n        51: 0,  # 'Á'\n        44: 1,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    61: {  # 'Í'\n        28: 0,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 0,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 1,  # 'J'\n        36: 0,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 0,  # 'O'\n        46: 1,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 0,  # 'U'\n        48: 1,  # 'V'\n        55: 0,  # 'Y'\n        52: 1,  # 'Z'\n        2: 0,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 0,  # 'e'\n        27: 0,  # 'f'\n        12: 2,  # 'g'\n        20: 0,  # 'h'\n        9: 0,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 0,  # 'l'\n        13: 1,  # 'm'\n        4: 0,  # 'n'\n        8: 0,  # 'o'\n        23: 0,  # 'p'\n        10: 1,  # 'r'\n        5: 0,  # 's'\n        3: 1,  # 't'\n        21: 0,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 1,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    58: {  # 'Ó'\n        28: 1,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 0,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 1,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 2,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 0,  # 'O'\n        46: 1,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 0,  # 'U'\n        48: 1,  # 'V'\n        55: 0,  # 'Y'\n        52: 1,  # 'Z'\n        2: 0,  # 'a'\n        18: 1,  # 'b'\n        26: 1,  # 'c'\n        17: 1,  # 'd'\n        1: 0,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 2,  # 'h'\n        9: 0,  # 'i'\n        22: 0,  # 'j'\n        7: 1,  # 'k'\n        6: 1,  # 'l'\n        13: 0,  # 'm'\n        4: 1,  # 'n'\n        8: 0,  # 'o'\n        23: 1,  # 'p'\n        10: 1,  # 'r'\n        5: 1,  # 's'\n        3: 0,  # 't'\n        21: 0,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 1,  # 'z'\n        51: 0,  # 'Á'\n        44: 1,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    59: {  # 'Ö'\n        28: 0,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 0,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 0,  # 'O'\n        46: 1,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 0,  # 'U'\n        48: 1,  # 'V'\n        55: 0,  # 'Y'\n        52: 1,  # 'Z'\n        2: 0,  # 'a'\n        18: 0,  # 'b'\n        26: 1,  # 'c'\n        17: 1,  # 'd'\n        1: 0,  # 'e'\n        27: 0,  # 'f'\n        12: 0,  # 'g'\n        20: 0,  # 'h'\n        9: 0,  # 'i'\n        22: 0,  # 'j'\n        7: 1,  # 'k'\n        6: 1,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        8: 0,  # 'o'\n        23: 0,  # 'p'\n        10: 2,  # 'r'\n        5: 1,  # 's'\n        3: 1,  # 't'\n        21: 0,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 1,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    60: {  # 'Ú'\n        28: 0,  # 'A'\n        40: 1,  # 'B'\n        54: 1,  # 'C'\n        45: 1,  # 'D'\n        32: 0,  # 'E'\n        50: 1,  # 'F'\n        49: 1,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 0,  # 'U'\n        48: 1,  # 'V'\n        55: 0,  # 'Y'\n        52: 1,  # 'Z'\n        2: 0,  # 'a'\n        18: 0,  # 'b'\n        26: 0,  # 'c'\n        17: 0,  # 'd'\n        1: 0,  # 'e'\n        27: 0,  # 'f'\n        12: 2,  # 'g'\n        20: 0,  # 'h'\n        9: 0,  # 'i'\n        22: 2,  # 'j'\n        7: 0,  # 'k'\n        6: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 1,  # 'n'\n        8: 0,  # 'o'\n        23: 0,  # 'p'\n        10: 1,  # 'r'\n        5: 1,  # 's'\n        3: 1,  # 't'\n        21: 0,  # 'u'\n        19: 0,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 0,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    63: {  # 'Ü'\n        28: 0,  # 'A'\n        40: 1,  # 'B'\n        54: 0,  # 'C'\n        45: 1,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 1,  # 'G'\n        38: 1,  # 'H'\n        39: 0,  # 'I'\n        53: 1,  # 'J'\n        36: 1,  # 'K'\n        41: 1,  # 'L'\n        34: 1,  # 'M'\n        35: 1,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 1,  # 'R'\n        33: 1,  # 'S'\n        37: 1,  # 'T'\n        57: 0,  # 'U'\n        48: 1,  # 'V'\n        55: 0,  # 'Y'\n        52: 1,  # 'Z'\n        2: 0,  # 'a'\n        18: 1,  # 'b'\n        26: 0,  # 'c'\n        17: 1,  # 'd'\n        1: 0,  # 'e'\n        27: 0,  # 'f'\n        12: 1,  # 'g'\n        20: 0,  # 'h'\n        9: 0,  # 'i'\n        22: 0,  # 'j'\n        7: 0,  # 'k'\n        6: 1,  # 'l'\n        13: 0,  # 'm'\n        4: 1,  # 'n'\n        8: 0,  # 'o'\n        23: 0,  # 'p'\n        10: 1,  # 'r'\n        5: 1,  # 's'\n        3: 1,  # 't'\n        21: 0,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 1,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    14: {  # 'á'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 1,  # 'a'\n        18: 3,  # 'b'\n        26: 3,  # 'c'\n        17: 3,  # 'd'\n        1: 1,  # 'e'\n        27: 2,  # 'f'\n        12: 3,  # 'g'\n        20: 2,  # 'h'\n        9: 2,  # 'i'\n        22: 3,  # 'j'\n        7: 3,  # 'k'\n        6: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        8: 1,  # 'o'\n        23: 2,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 2,  # 'u'\n        19: 3,  # 'v'\n        62: 0,  # 'x'\n        16: 1,  # 'y'\n        11: 3,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 1,  # 'á'\n        15: 2,  # 'é'\n        30: 1,  # 'í'\n        25: 0,  # 'ó'\n        24: 1,  # 'ö'\n        31: 0,  # 'ú'\n        29: 1,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    15: {  # 'é'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 1,  # 'a'\n        18: 3,  # 'b'\n        26: 2,  # 'c'\n        17: 3,  # 'd'\n        1: 1,  # 'e'\n        27: 1,  # 'f'\n        12: 3,  # 'g'\n        20: 3,  # 'h'\n        9: 2,  # 'i'\n        22: 2,  # 'j'\n        7: 3,  # 'k'\n        6: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        8: 1,  # 'o'\n        23: 3,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 0,  # 'u'\n        19: 3,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 3,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 1,  # 'á'\n        15: 1,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 1,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    30: {  # 'í'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 0,  # 'a'\n        18: 1,  # 'b'\n        26: 2,  # 'c'\n        17: 1,  # 'd'\n        1: 0,  # 'e'\n        27: 1,  # 'f'\n        12: 3,  # 'g'\n        20: 0,  # 'h'\n        9: 0,  # 'i'\n        22: 1,  # 'j'\n        7: 1,  # 'k'\n        6: 2,  # 'l'\n        13: 2,  # 'm'\n        4: 3,  # 'n'\n        8: 0,  # 'o'\n        23: 1,  # 'p'\n        10: 3,  # 'r'\n        5: 2,  # 's'\n        3: 3,  # 't'\n        21: 0,  # 'u'\n        19: 3,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 2,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    25: {  # 'ó'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 2,  # 'a'\n        18: 3,  # 'b'\n        26: 2,  # 'c'\n        17: 3,  # 'd'\n        1: 1,  # 'e'\n        27: 2,  # 'f'\n        12: 2,  # 'g'\n        20: 2,  # 'h'\n        9: 2,  # 'i'\n        22: 2,  # 'j'\n        7: 3,  # 'k'\n        6: 3,  # 'l'\n        13: 2,  # 'm'\n        4: 3,  # 'n'\n        8: 1,  # 'o'\n        23: 2,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 1,  # 'u'\n        19: 2,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 3,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 1,  # 'á'\n        15: 1,  # 'é'\n        30: 1,  # 'í'\n        25: 0,  # 'ó'\n        24: 1,  # 'ö'\n        31: 1,  # 'ú'\n        29: 1,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    24: {  # 'ö'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 0,  # 'a'\n        18: 3,  # 'b'\n        26: 1,  # 'c'\n        17: 2,  # 'd'\n        1: 0,  # 'e'\n        27: 1,  # 'f'\n        12: 2,  # 'g'\n        20: 1,  # 'h'\n        9: 0,  # 'i'\n        22: 1,  # 'j'\n        7: 3,  # 'k'\n        6: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        8: 0,  # 'o'\n        23: 2,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 3,  # 't'\n        21: 0,  # 'u'\n        19: 3,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 3,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    31: {  # 'ú'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 1,  # 'a'\n        18: 1,  # 'b'\n        26: 2,  # 'c'\n        17: 1,  # 'd'\n        1: 1,  # 'e'\n        27: 2,  # 'f'\n        12: 3,  # 'g'\n        20: 1,  # 'h'\n        9: 1,  # 'i'\n        22: 3,  # 'j'\n        7: 1,  # 'k'\n        6: 3,  # 'l'\n        13: 1,  # 'm'\n        4: 2,  # 'n'\n        8: 0,  # 'o'\n        23: 1,  # 'p'\n        10: 3,  # 'r'\n        5: 3,  # 's'\n        3: 2,  # 't'\n        21: 1,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 2,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 1,  # 'á'\n        15: 1,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    29: {  # 'ü'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 1,  # 'a'\n        18: 1,  # 'b'\n        26: 1,  # 'c'\n        17: 2,  # 'd'\n        1: 1,  # 'e'\n        27: 1,  # 'f'\n        12: 3,  # 'g'\n        20: 2,  # 'h'\n        9: 1,  # 'i'\n        22: 1,  # 'j'\n        7: 3,  # 'k'\n        6: 3,  # 'l'\n        13: 1,  # 'm'\n        4: 3,  # 'n'\n        8: 0,  # 'o'\n        23: 1,  # 'p'\n        10: 2,  # 'r'\n        5: 2,  # 's'\n        3: 2,  # 't'\n        21: 0,  # 'u'\n        19: 2,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 2,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 1,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    42: {  # 'ő'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 1,  # 'a'\n        18: 2,  # 'b'\n        26: 1,  # 'c'\n        17: 2,  # 'd'\n        1: 1,  # 'e'\n        27: 1,  # 'f'\n        12: 1,  # 'g'\n        20: 1,  # 'h'\n        9: 1,  # 'i'\n        22: 1,  # 'j'\n        7: 2,  # 'k'\n        6: 3,  # 'l'\n        13: 1,  # 'm'\n        4: 2,  # 'n'\n        8: 1,  # 'o'\n        23: 1,  # 'p'\n        10: 2,  # 'r'\n        5: 2,  # 's'\n        3: 2,  # 't'\n        21: 1,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 2,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 1,  # 'é'\n        30: 1,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 1,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n    56: {  # 'ű'\n        28: 0,  # 'A'\n        40: 0,  # 'B'\n        54: 0,  # 'C'\n        45: 0,  # 'D'\n        32: 0,  # 'E'\n        50: 0,  # 'F'\n        49: 0,  # 'G'\n        38: 0,  # 'H'\n        39: 0,  # 'I'\n        53: 0,  # 'J'\n        36: 0,  # 'K'\n        41: 0,  # 'L'\n        34: 0,  # 'M'\n        35: 0,  # 'N'\n        47: 0,  # 'O'\n        46: 0,  # 'P'\n        43: 0,  # 'R'\n        33: 0,  # 'S'\n        37: 0,  # 'T'\n        57: 0,  # 'U'\n        48: 0,  # 'V'\n        55: 0,  # 'Y'\n        52: 0,  # 'Z'\n        2: 1,  # 'a'\n        18: 1,  # 'b'\n        26: 0,  # 'c'\n        17: 1,  # 'd'\n        1: 1,  # 'e'\n        27: 1,  # 'f'\n        12: 1,  # 'g'\n        20: 1,  # 'h'\n        9: 1,  # 'i'\n        22: 1,  # 'j'\n        7: 1,  # 'k'\n        6: 1,  # 'l'\n        13: 0,  # 'm'\n        4: 2,  # 'n'\n        8: 0,  # 'o'\n        23: 0,  # 'p'\n        10: 1,  # 'r'\n        5: 1,  # 's'\n        3: 1,  # 't'\n        21: 0,  # 'u'\n        19: 1,  # 'v'\n        62: 0,  # 'x'\n        16: 0,  # 'y'\n        11: 2,  # 'z'\n        51: 0,  # 'Á'\n        44: 0,  # 'É'\n        61: 0,  # 'Í'\n        58: 0,  # 'Ó'\n        59: 0,  # 'Ö'\n        60: 0,  # 'Ú'\n        63: 0,  # 'Ü'\n        14: 0,  # 'á'\n        15: 0,  # 'é'\n        30: 0,  # 'í'\n        25: 0,  # 'ó'\n        24: 0,  # 'ö'\n        31: 0,  # 'ú'\n        29: 0,  # 'ü'\n        42: 0,  # 'ő'\n        56: 0,  # 'ű'\n    },\n}\n\n# 255: Undefined characters that did not exist in training text\n# 254: Carriage/Return\n# 253: symbol (punctuation) that does not belong to word\n# 252: 0 - 9\n# 251: Control characters\n\n# Character Mapping Table(s):\nWINDOWS_1250_HUNGARIAN_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 254,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 254,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 253,  # ' '\n    33: 253,  # '!'\n    34: 253,  # '\"'\n    35: 253,  # '#'\n    36: 253,  # '$'\n    37: 253,  # '%'\n    38: 253,  # '&'\n    39: 253,  # \"'\"\n    40: 253,  # '('\n    41: 253,  # ')'\n    42: 253,  # '*'\n    43: 253,  # '+'\n    44: 253,  # ','\n    45: 253,  # '-'\n    46: 253,  # '.'\n    47: 253,  # '/'\n    48: 252,  # '0'\n    49: 252,  # '1'\n    50: 252,  # '2'\n    51: 252,  # '3'\n    52: 252,  # '4'\n    53: 252,  # '5'\n    54: 252,  # '6'\n    55: 252,  # '7'\n    56: 252,  # '8'\n    57: 252,  # '9'\n    58: 253,  # ':'\n    59: 253,  # ';'\n    60: 253,  # '<'\n    61: 253,  # '='\n    62: 253,  # '>'\n    63: 253,  # '?'\n    64: 253,  # '@'\n    65: 28,  # 'A'\n    66: 40,  # 'B'\n    67: 54,  # 'C'\n    68: 45,  # 'D'\n    69: 32,  # 'E'\n    70: 50,  # 'F'\n    71: 49,  # 'G'\n    72: 38,  # 'H'\n    73: 39,  # 'I'\n    74: 53,  # 'J'\n    75: 36,  # 'K'\n    76: 41,  # 'L'\n    77: 34,  # 'M'\n    78: 35,  # 'N'\n    79: 47,  # 'O'\n    80: 46,  # 'P'\n    81: 72,  # 'Q'\n    82: 43,  # 'R'\n    83: 33,  # 'S'\n    84: 37,  # 'T'\n    85: 57,  # 'U'\n    86: 48,  # 'V'\n    87: 64,  # 'W'\n    88: 68,  # 'X'\n    89: 55,  # 'Y'\n    90: 52,  # 'Z'\n    91: 253,  # '['\n    92: 253,  # '\\\\'\n    93: 253,  # ']'\n    94: 253,  # '^'\n    95: 253,  # '_'\n    96: 253,  # '`'\n    97: 2,  # 'a'\n    98: 18,  # 'b'\n    99: 26,  # 'c'\n    100: 17,  # 'd'\n    101: 1,  # 'e'\n    102: 27,  # 'f'\n    103: 12,  # 'g'\n    104: 20,  # 'h'\n    105: 9,  # 'i'\n    106: 22,  # 'j'\n    107: 7,  # 'k'\n    108: 6,  # 'l'\n    109: 13,  # 'm'\n    110: 4,  # 'n'\n    111: 8,  # 'o'\n    112: 23,  # 'p'\n    113: 67,  # 'q'\n    114: 10,  # 'r'\n    115: 5,  # 's'\n    116: 3,  # 't'\n    117: 21,  # 'u'\n    118: 19,  # 'v'\n    119: 65,  # 'w'\n    120: 62,  # 'x'\n    121: 16,  # 'y'\n    122: 11,  # 'z'\n    123: 253,  # '{'\n    124: 253,  # '|'\n    125: 253,  # '}'\n    126: 253,  # '~'\n    127: 253,  # '\\x7f'\n    128: 161,  # '€'\n    129: 162,  # None\n    130: 163,  # '‚'\n    131: 164,  # None\n    132: 165,  # '„'\n    133: 166,  # '…'\n    134: 167,  # '†'\n    135: 168,  # '‡'\n    136: 169,  # None\n    137: 170,  # '‰'\n    138: 171,  # 'Š'\n    139: 172,  # '‹'\n    140: 173,  # 'Ś'\n    141: 174,  # 'Ť'\n    142: 175,  # 'Ž'\n    143: 176,  # 'Ź'\n    144: 177,  # None\n    145: 178,  # '‘'\n    146: 179,  # '’'\n    147: 180,  # '“'\n    148: 78,  # '”'\n    149: 181,  # '•'\n    150: 69,  # '–'\n    151: 182,  # '—'\n    152: 183,  # None\n    153: 184,  # '™'\n    154: 185,  # 'š'\n    155: 186,  # '›'\n    156: 187,  # 'ś'\n    157: 188,  # 'ť'\n    158: 189,  # 'ž'\n    159: 190,  # 'ź'\n    160: 191,  # '\\xa0'\n    161: 192,  # 'ˇ'\n    162: 193,  # '˘'\n    163: 194,  # 'Ł'\n    164: 195,  # '¤'\n    165: 196,  # 'Ą'\n    166: 197,  # '¦'\n    167: 76,  # '§'\n    168: 198,  # '¨'\n    169: 199,  # '©'\n    170: 200,  # 'Ş'\n    171: 201,  # '«'\n    172: 202,  # '¬'\n    173: 203,  # '\\xad'\n    174: 204,  # '®'\n    175: 205,  # 'Ż'\n    176: 81,  # '°'\n    177: 206,  # '±'\n    178: 207,  # '˛'\n    179: 208,  # 'ł'\n    180: 209,  # '´'\n    181: 210,  # 'µ'\n    182: 211,  # '¶'\n    183: 212,  # '·'\n    184: 213,  # '¸'\n    185: 214,  # 'ą'\n    186: 215,  # 'ş'\n    187: 216,  # '»'\n    188: 217,  # 'Ľ'\n    189: 218,  # '˝'\n    190: 219,  # 'ľ'\n    191: 220,  # 'ż'\n    192: 221,  # 'Ŕ'\n    193: 51,  # 'Á'\n    194: 83,  # 'Â'\n    195: 222,  # 'Ă'\n    196: 80,  # 'Ä'\n    197: 223,  # 'Ĺ'\n    198: 224,  # 'Ć'\n    199: 225,  # 'Ç'\n    200: 226,  # 'Č'\n    201: 44,  # 'É'\n    202: 227,  # 'Ę'\n    203: 228,  # 'Ë'\n    204: 229,  # 'Ě'\n    205: 61,  # 'Í'\n    206: 230,  # 'Î'\n    207: 231,  # 'Ď'\n    208: 232,  # 'Đ'\n    209: 233,  # 'Ń'\n    210: 234,  # 'Ň'\n    211: 58,  # 'Ó'\n    212: 235,  # 'Ô'\n    213: 66,  # 'Ő'\n    214: 59,  # 'Ö'\n    215: 236,  # '×'\n    216: 237,  # 'Ř'\n    217: 238,  # 'Ů'\n    218: 60,  # 'Ú'\n    219: 70,  # 'Ű'\n    220: 63,  # 'Ü'\n    221: 239,  # 'Ý'\n    222: 240,  # 'Ţ'\n    223: 241,  # 'ß'\n    224: 84,  # 'ŕ'\n    225: 14,  # 'á'\n    226: 75,  # 'â'\n    227: 242,  # 'ă'\n    228: 71,  # 'ä'\n    229: 82,  # 'ĺ'\n    230: 243,  # 'ć'\n    231: 73,  # 'ç'\n    232: 244,  # 'č'\n    233: 15,  # 'é'\n    234: 85,  # 'ę'\n    235: 79,  # 'ë'\n    236: 86,  # 'ě'\n    237: 30,  # 'í'\n    238: 77,  # 'î'\n    239: 87,  # 'ď'\n    240: 245,  # 'đ'\n    241: 246,  # 'ń'\n    242: 247,  # 'ň'\n    243: 25,  # 'ó'\n    244: 74,  # 'ô'\n    245: 42,  # 'ő'\n    246: 24,  # 'ö'\n    247: 248,  # '÷'\n    248: 249,  # 'ř'\n    249: 250,  # 'ů'\n    250: 31,  # 'ú'\n    251: 56,  # 'ű'\n    252: 29,  # 'ü'\n    253: 251,  # 'ý'\n    254: 252,  # 'ţ'\n    255: 253,  # '˙'\n}\n\nWINDOWS_1250_HUNGARIAN_MODEL = SingleByteCharSetModel(\n    charset_name=\"windows-1250\",\n    language=\"Hungarian\",\n    char_to_order_map=WINDOWS_1250_HUNGARIAN_CHAR_TO_ORDER,\n    language_model=HUNGARIAN_LANG_MODEL,\n    typical_positive_ratio=0.947368,\n    keep_ascii_letters=True,\n    alphabet=\"ABCDEFGHIJKLMNOPRSTUVZabcdefghijklmnoprstuvzÁÉÍÓÖÚÜáéíóöúüŐőŰű\",\n)\n\nISO_8859_2_HUNGARIAN_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 254,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 254,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 253,  # ' '\n    33: 253,  # '!'\n    34: 253,  # '\"'\n    35: 253,  # '#'\n    36: 253,  # '$'\n    37: 253,  # '%'\n    38: 253,  # '&'\n    39: 253,  # \"'\"\n    40: 253,  # '('\n    41: 253,  # ')'\n    42: 253,  # '*'\n    43: 253,  # '+'\n    44: 253,  # ','\n    45: 253,  # '-'\n    46: 253,  # '.'\n    47: 253,  # '/'\n    48: 252,  # '0'\n    49: 252,  # '1'\n    50: 252,  # '2'\n    51: 252,  # '3'\n    52: 252,  # '4'\n    53: 252,  # '5'\n    54: 252,  # '6'\n    55: 252,  # '7'\n    56: 252,  # '8'\n    57: 252,  # '9'\n    58: 253,  # ':'\n    59: 253,  # ';'\n    60: 253,  # '<'\n    61: 253,  # '='\n    62: 253,  # '>'\n    63: 253,  # '?'\n    64: 253,  # '@'\n    65: 28,  # 'A'\n    66: 40,  # 'B'\n    67: 54,  # 'C'\n    68: 45,  # 'D'\n    69: 32,  # 'E'\n    70: 50,  # 'F'\n    71: 49,  # 'G'\n    72: 38,  # 'H'\n    73: 39,  # 'I'\n    74: 53,  # 'J'\n    75: 36,  # 'K'\n    76: 41,  # 'L'\n    77: 34,  # 'M'\n    78: 35,  # 'N'\n    79: 47,  # 'O'\n    80: 46,  # 'P'\n    81: 71,  # 'Q'\n    82: 43,  # 'R'\n    83: 33,  # 'S'\n    84: 37,  # 'T'\n    85: 57,  # 'U'\n    86: 48,  # 'V'\n    87: 64,  # 'W'\n    88: 68,  # 'X'\n    89: 55,  # 'Y'\n    90: 52,  # 'Z'\n    91: 253,  # '['\n    92: 253,  # '\\\\'\n    93: 253,  # ']'\n    94: 253,  # '^'\n    95: 253,  # '_'\n    96: 253,  # '`'\n    97: 2,  # 'a'\n    98: 18,  # 'b'\n    99: 26,  # 'c'\n    100: 17,  # 'd'\n    101: 1,  # 'e'\n    102: 27,  # 'f'\n    103: 12,  # 'g'\n    104: 20,  # 'h'\n    105: 9,  # 'i'\n    106: 22,  # 'j'\n    107: 7,  # 'k'\n    108: 6,  # 'l'\n    109: 13,  # 'm'\n    110: 4,  # 'n'\n    111: 8,  # 'o'\n    112: 23,  # 'p'\n    113: 67,  # 'q'\n    114: 10,  # 'r'\n    115: 5,  # 's'\n    116: 3,  # 't'\n    117: 21,  # 'u'\n    118: 19,  # 'v'\n    119: 65,  # 'w'\n    120: 62,  # 'x'\n    121: 16,  # 'y'\n    122: 11,  # 'z'\n    123: 253,  # '{'\n    124: 253,  # '|'\n    125: 253,  # '}'\n    126: 253,  # '~'\n    127: 253,  # '\\x7f'\n    128: 159,  # '\\x80'\n    129: 160,  # '\\x81'\n    130: 161,  # '\\x82'\n    131: 162,  # '\\x83'\n    132: 163,  # '\\x84'\n    133: 164,  # '\\x85'\n    134: 165,  # '\\x86'\n    135: 166,  # '\\x87'\n    136: 167,  # '\\x88'\n    137: 168,  # '\\x89'\n    138: 169,  # '\\x8a'\n    139: 170,  # '\\x8b'\n    140: 171,  # '\\x8c'\n    141: 172,  # '\\x8d'\n    142: 173,  # '\\x8e'\n    143: 174,  # '\\x8f'\n    144: 175,  # '\\x90'\n    145: 176,  # '\\x91'\n    146: 177,  # '\\x92'\n    147: 178,  # '\\x93'\n    148: 179,  # '\\x94'\n    149: 180,  # '\\x95'\n    150: 181,  # '\\x96'\n    151: 182,  # '\\x97'\n    152: 183,  # '\\x98'\n    153: 184,  # '\\x99'\n    154: 185,  # '\\x9a'\n    155: 186,  # '\\x9b'\n    156: 187,  # '\\x9c'\n    157: 188,  # '\\x9d'\n    158: 189,  # '\\x9e'\n    159: 190,  # '\\x9f'\n    160: 191,  # '\\xa0'\n    161: 192,  # 'Ą'\n    162: 193,  # '˘'\n    163: 194,  # 'Ł'\n    164: 195,  # '¤'\n    165: 196,  # 'Ľ'\n    166: 197,  # 'Ś'\n    167: 75,  # '§'\n    168: 198,  # '¨'\n    169: 199,  # 'Š'\n    170: 200,  # 'Ş'\n    171: 201,  # 'Ť'\n    172: 202,  # 'Ź'\n    173: 203,  # '\\xad'\n    174: 204,  # 'Ž'\n    175: 205,  # 'Ż'\n    176: 79,  # '°'\n    177: 206,  # 'ą'\n    178: 207,  # '˛'\n    179: 208,  # 'ł'\n    180: 209,  # '´'\n    181: 210,  # 'ľ'\n    182: 211,  # 'ś'\n    183: 212,  # 'ˇ'\n    184: 213,  # '¸'\n    185: 214,  # 'š'\n    186: 215,  # 'ş'\n    187: 216,  # 'ť'\n    188: 217,  # 'ź'\n    189: 218,  # '˝'\n    190: 219,  # 'ž'\n    191: 220,  # 'ż'\n    192: 221,  # 'Ŕ'\n    193: 51,  # 'Á'\n    194: 81,  # 'Â'\n    195: 222,  # 'Ă'\n    196: 78,  # 'Ä'\n    197: 223,  # 'Ĺ'\n    198: 224,  # 'Ć'\n    199: 225,  # 'Ç'\n    200: 226,  # 'Č'\n    201: 44,  # 'É'\n    202: 227,  # 'Ę'\n    203: 228,  # 'Ë'\n    204: 229,  # 'Ě'\n    205: 61,  # 'Í'\n    206: 230,  # 'Î'\n    207: 231,  # 'Ď'\n    208: 232,  # 'Đ'\n    209: 233,  # 'Ń'\n    210: 234,  # 'Ň'\n    211: 58,  # 'Ó'\n    212: 235,  # 'Ô'\n    213: 66,  # 'Ő'\n    214: 59,  # 'Ö'\n    215: 236,  # '×'\n    216: 237,  # 'Ř'\n    217: 238,  # 'Ů'\n    218: 60,  # 'Ú'\n    219: 69,  # 'Ű'\n    220: 63,  # 'Ü'\n    221: 239,  # 'Ý'\n    222: 240,  # 'Ţ'\n    223: 241,  # 'ß'\n    224: 82,  # 'ŕ'\n    225: 14,  # 'á'\n    226: 74,  # 'â'\n    227: 242,  # 'ă'\n    228: 70,  # 'ä'\n    229: 80,  # 'ĺ'\n    230: 243,  # 'ć'\n    231: 72,  # 'ç'\n    232: 244,  # 'č'\n    233: 15,  # 'é'\n    234: 83,  # 'ę'\n    235: 77,  # 'ë'\n    236: 84,  # 'ě'\n    237: 30,  # 'í'\n    238: 76,  # 'î'\n    239: 85,  # 'ď'\n    240: 245,  # 'đ'\n    241: 246,  # 'ń'\n    242: 247,  # 'ň'\n    243: 25,  # 'ó'\n    244: 73,  # 'ô'\n    245: 42,  # 'ő'\n    246: 24,  # 'ö'\n    247: 248,  # '÷'\n    248: 249,  # 'ř'\n    249: 250,  # 'ů'\n    250: 31,  # 'ú'\n    251: 56,  # 'ű'\n    252: 29,  # 'ü'\n    253: 251,  # 'ý'\n    254: 252,  # 'ţ'\n    255: 253,  # '˙'\n}\n\nISO_8859_2_HUNGARIAN_MODEL = SingleByteCharSetModel(\n    charset_name=\"ISO-8859-2\",\n    language=\"Hungarian\",\n    char_to_order_map=ISO_8859_2_HUNGARIAN_CHAR_TO_ORDER,\n    language_model=HUNGARIAN_LANG_MODEL,\n    typical_positive_ratio=0.947368,\n    keep_ascii_letters=True,\n    alphabet=\"ABCDEFGHIJKLMNOPRSTUVZabcdefghijklmnoprstuvzÁÉÍÓÖÚÜáéíóöúüŐőŰű\",\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/langrussianmodel.py",
    "content": "from pip._vendor.chardet.sbcharsetprober import SingleByteCharSetModel\n\n# 3: Positive\n# 2: Likely\n# 1: Unlikely\n# 0: Negative\n\nRUSSIAN_LANG_MODEL = {\n    37: {  # 'А'\n        37: 0,  # 'А'\n        44: 1,  # 'Б'\n        33: 1,  # 'В'\n        46: 1,  # 'Г'\n        41: 1,  # 'Д'\n        48: 1,  # 'Е'\n        56: 1,  # 'Ж'\n        51: 1,  # 'З'\n        42: 1,  # 'И'\n        60: 1,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 2,  # 'Н'\n        34: 1,  # 'О'\n        35: 1,  # 'П'\n        45: 1,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 1,  # 'У'\n        53: 1,  # 'Ф'\n        55: 1,  # 'Х'\n        58: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        57: 1,  # 'Ш'\n        63: 1,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 1,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 1,  # 'а'\n        21: 2,  # 'б'\n        10: 2,  # 'в'\n        19: 2,  # 'г'\n        13: 2,  # 'д'\n        2: 0,  # 'е'\n        24: 1,  # 'ж'\n        20: 1,  # 'з'\n        4: 0,  # 'и'\n        23: 1,  # 'й'\n        11: 2,  # 'к'\n        8: 3,  # 'л'\n        12: 2,  # 'м'\n        5: 2,  # 'н'\n        1: 0,  # 'о'\n        15: 2,  # 'п'\n        9: 2,  # 'р'\n        7: 2,  # 'с'\n        6: 2,  # 'т'\n        14: 2,  # 'у'\n        39: 2,  # 'ф'\n        26: 2,  # 'х'\n        28: 0,  # 'ц'\n        22: 1,  # 'ч'\n        25: 2,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 1,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    44: {  # 'Б'\n        37: 1,  # 'А'\n        44: 0,  # 'Б'\n        33: 1,  # 'В'\n        46: 1,  # 'Г'\n        41: 0,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 0,  # 'П'\n        45: 1,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 1,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 2,  # 'а'\n        21: 0,  # 'б'\n        10: 0,  # 'в'\n        19: 0,  # 'г'\n        13: 1,  # 'д'\n        2: 3,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 2,  # 'л'\n        12: 0,  # 'м'\n        5: 0,  # 'н'\n        1: 3,  # 'о'\n        15: 0,  # 'п'\n        9: 2,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 2,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 2,  # 'ы'\n        17: 1,  # 'ь'\n        30: 2,  # 'э'\n        27: 1,  # 'ю'\n        16: 1,  # 'я'\n    },\n    33: {  # 'В'\n        37: 2,  # 'А'\n        44: 0,  # 'Б'\n        33: 1,  # 'В'\n        46: 0,  # 'Г'\n        41: 1,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 1,  # 'П'\n        45: 1,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 1,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 1,  # 'Ы'\n        61: 1,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 2,  # 'а'\n        21: 1,  # 'б'\n        10: 1,  # 'в'\n        19: 1,  # 'г'\n        13: 2,  # 'д'\n        2: 3,  # 'е'\n        24: 0,  # 'ж'\n        20: 2,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 1,  # 'к'\n        8: 2,  # 'л'\n        12: 2,  # 'м'\n        5: 2,  # 'н'\n        1: 3,  # 'о'\n        15: 2,  # 'п'\n        9: 2,  # 'р'\n        7: 3,  # 'с'\n        6: 2,  # 'т'\n        14: 2,  # 'у'\n        39: 0,  # 'ф'\n        26: 1,  # 'х'\n        28: 1,  # 'ц'\n        22: 2,  # 'ч'\n        25: 1,  # 'ш'\n        29: 0,  # 'щ'\n        54: 1,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 1,  # 'ь'\n        30: 2,  # 'э'\n        27: 0,  # 'ю'\n        16: 1,  # 'я'\n    },\n    46: {  # 'Г'\n        37: 1,  # 'А'\n        44: 1,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 1,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 1,  # 'П'\n        45: 1,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 2,  # 'а'\n        21: 0,  # 'б'\n        10: 1,  # 'в'\n        19: 0,  # 'г'\n        13: 2,  # 'д'\n        2: 2,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 2,  # 'л'\n        12: 1,  # 'м'\n        5: 1,  # 'н'\n        1: 3,  # 'о'\n        15: 0,  # 'п'\n        9: 2,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 2,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 1,  # 'ь'\n        30: 1,  # 'э'\n        27: 1,  # 'ю'\n        16: 0,  # 'я'\n    },\n    41: {  # 'Д'\n        37: 1,  # 'А'\n        44: 0,  # 'Б'\n        33: 1,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 2,  # 'Е'\n        56: 1,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 0,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 0,  # 'П'\n        45: 1,  # 'Р'\n        32: 1,  # 'С'\n        40: 0,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 1,  # 'Ы'\n        61: 1,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 3,  # 'а'\n        21: 0,  # 'б'\n        10: 2,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 2,  # 'е'\n        24: 3,  # 'ж'\n        20: 1,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 2,  # 'л'\n        12: 1,  # 'м'\n        5: 1,  # 'н'\n        1: 3,  # 'о'\n        15: 0,  # 'п'\n        9: 2,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 2,  # 'у'\n        39: 0,  # 'ф'\n        26: 1,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 1,  # 'ы'\n        17: 1,  # 'ь'\n        30: 2,  # 'э'\n        27: 1,  # 'ю'\n        16: 1,  # 'я'\n    },\n    48: {  # 'Е'\n        37: 1,  # 'А'\n        44: 1,  # 'Б'\n        33: 1,  # 'В'\n        46: 1,  # 'Г'\n        41: 1,  # 'Д'\n        48: 1,  # 'Е'\n        56: 1,  # 'Ж'\n        51: 1,  # 'З'\n        42: 1,  # 'И'\n        60: 1,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 2,  # 'Н'\n        34: 1,  # 'О'\n        35: 1,  # 'П'\n        45: 2,  # 'Р'\n        32: 2,  # 'С'\n        40: 1,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 1,  # 'Х'\n        58: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        57: 1,  # 'Ш'\n        63: 1,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 0,  # 'а'\n        21: 0,  # 'б'\n        10: 2,  # 'в'\n        19: 2,  # 'г'\n        13: 2,  # 'д'\n        2: 2,  # 'е'\n        24: 1,  # 'ж'\n        20: 1,  # 'з'\n        4: 0,  # 'и'\n        23: 2,  # 'й'\n        11: 1,  # 'к'\n        8: 2,  # 'л'\n        12: 2,  # 'м'\n        5: 1,  # 'н'\n        1: 0,  # 'о'\n        15: 1,  # 'п'\n        9: 1,  # 'р'\n        7: 3,  # 'с'\n        6: 0,  # 'т'\n        14: 0,  # 'у'\n        39: 1,  # 'ф'\n        26: 1,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 1,  # 'ш'\n        29: 2,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 1,  # 'ю'\n        16: 0,  # 'я'\n    },\n    56: {  # 'Ж'\n        37: 1,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 1,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 1,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 2,  # 'а'\n        21: 1,  # 'б'\n        10: 0,  # 'в'\n        19: 1,  # 'г'\n        13: 1,  # 'д'\n        2: 2,  # 'е'\n        24: 1,  # 'ж'\n        20: 0,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 0,  # 'л'\n        12: 1,  # 'м'\n        5: 0,  # 'н'\n        1: 2,  # 'о'\n        15: 0,  # 'п'\n        9: 1,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 2,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 2,  # 'ю'\n        16: 0,  # 'я'\n    },\n    51: {  # 'З'\n        37: 1,  # 'А'\n        44: 0,  # 'Б'\n        33: 1,  # 'В'\n        46: 1,  # 'Г'\n        41: 1,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 0,  # 'П'\n        45: 1,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 1,  # 'Ы'\n        61: 1,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 1,  # 'б'\n        10: 2,  # 'в'\n        19: 0,  # 'г'\n        13: 2,  # 'д'\n        2: 2,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 1,  # 'л'\n        12: 1,  # 'м'\n        5: 2,  # 'н'\n        1: 2,  # 'о'\n        15: 0,  # 'п'\n        9: 1,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 1,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 1,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 0,  # 'ю'\n        16: 1,  # 'я'\n    },\n    42: {  # 'И'\n        37: 1,  # 'А'\n        44: 1,  # 'Б'\n        33: 1,  # 'В'\n        46: 1,  # 'Г'\n        41: 1,  # 'Д'\n        48: 2,  # 'Е'\n        56: 1,  # 'Ж'\n        51: 1,  # 'З'\n        42: 1,  # 'И'\n        60: 1,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 1,  # 'П'\n        45: 1,  # 'Р'\n        32: 2,  # 'С'\n        40: 1,  # 'Т'\n        52: 0,  # 'У'\n        53: 1,  # 'Ф'\n        55: 1,  # 'Х'\n        58: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 1,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 1,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 1,  # 'а'\n        21: 2,  # 'б'\n        10: 2,  # 'в'\n        19: 2,  # 'г'\n        13: 2,  # 'д'\n        2: 2,  # 'е'\n        24: 0,  # 'ж'\n        20: 2,  # 'з'\n        4: 1,  # 'и'\n        23: 0,  # 'й'\n        11: 1,  # 'к'\n        8: 2,  # 'л'\n        12: 2,  # 'м'\n        5: 2,  # 'н'\n        1: 1,  # 'о'\n        15: 1,  # 'п'\n        9: 2,  # 'р'\n        7: 2,  # 'с'\n        6: 2,  # 'т'\n        14: 1,  # 'у'\n        39: 1,  # 'ф'\n        26: 2,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 1,  # 'ш'\n        29: 1,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 1,  # 'ю'\n        16: 0,  # 'я'\n    },\n    60: {  # 'Й'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 1,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 0,  # 'М'\n        31: 1,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 1,  # 'Х'\n        58: 1,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 0,  # 'а'\n        21: 0,  # 'б'\n        10: 0,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 1,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 0,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 0,  # 'л'\n        12: 0,  # 'м'\n        5: 0,  # 'н'\n        1: 2,  # 'о'\n        15: 0,  # 'п'\n        9: 0,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 0,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    36: {  # 'К'\n        37: 2,  # 'А'\n        44: 0,  # 'Б'\n        33: 1,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 1,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 1,  # 'Л'\n        38: 0,  # 'М'\n        31: 1,  # 'Н'\n        34: 2,  # 'О'\n        35: 1,  # 'П'\n        45: 1,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 1,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 0,  # 'б'\n        10: 1,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 2,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 2,  # 'л'\n        12: 0,  # 'м'\n        5: 1,  # 'н'\n        1: 3,  # 'о'\n        15: 0,  # 'п'\n        9: 2,  # 'р'\n        7: 2,  # 'с'\n        6: 2,  # 'т'\n        14: 2,  # 'у'\n        39: 0,  # 'ф'\n        26: 1,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 1,  # 'ы'\n        17: 1,  # 'ь'\n        30: 2,  # 'э'\n        27: 1,  # 'ю'\n        16: 0,  # 'я'\n    },\n    49: {  # 'Л'\n        37: 2,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 1,  # 'Г'\n        41: 0,  # 'Д'\n        48: 1,  # 'Е'\n        56: 1,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 0,  # 'Н'\n        34: 1,  # 'О'\n        35: 1,  # 'П'\n        45: 0,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 1,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 1,  # 'Ы'\n        61: 1,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 1,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 2,  # 'а'\n        21: 0,  # 'б'\n        10: 0,  # 'в'\n        19: 1,  # 'г'\n        13: 0,  # 'д'\n        2: 2,  # 'е'\n        24: 1,  # 'ж'\n        20: 0,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 1,  # 'л'\n        12: 0,  # 'м'\n        5: 1,  # 'н'\n        1: 2,  # 'о'\n        15: 0,  # 'п'\n        9: 0,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 2,  # 'у'\n        39: 0,  # 'ф'\n        26: 1,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 1,  # 'ы'\n        17: 1,  # 'ь'\n        30: 2,  # 'э'\n        27: 2,  # 'ю'\n        16: 1,  # 'я'\n    },\n    38: {  # 'М'\n        37: 1,  # 'А'\n        44: 1,  # 'Б'\n        33: 1,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 1,  # 'П'\n        45: 1,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 1,  # 'У'\n        53: 1,  # 'Ф'\n        55: 1,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 1,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 1,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 3,  # 'а'\n        21: 0,  # 'б'\n        10: 0,  # 'в'\n        19: 1,  # 'г'\n        13: 0,  # 'д'\n        2: 2,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 1,  # 'л'\n        12: 1,  # 'м'\n        5: 2,  # 'н'\n        1: 3,  # 'о'\n        15: 0,  # 'п'\n        9: 1,  # 'р'\n        7: 1,  # 'с'\n        6: 0,  # 'т'\n        14: 2,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 1,  # 'ь'\n        30: 2,  # 'э'\n        27: 1,  # 'ю'\n        16: 1,  # 'я'\n    },\n    31: {  # 'Н'\n        37: 2,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 1,  # 'Г'\n        41: 1,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 1,  # 'З'\n        42: 2,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 0,  # 'П'\n        45: 1,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 1,  # 'У'\n        53: 1,  # 'Ф'\n        55: 1,  # 'Х'\n        58: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 1,  # 'Ы'\n        61: 1,  # 'Ь'\n        47: 1,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 3,  # 'а'\n        21: 0,  # 'б'\n        10: 0,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 3,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 0,  # 'л'\n        12: 0,  # 'м'\n        5: 0,  # 'н'\n        1: 3,  # 'о'\n        15: 0,  # 'п'\n        9: 1,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 3,  # 'у'\n        39: 0,  # 'ф'\n        26: 1,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 1,  # 'ы'\n        17: 2,  # 'ь'\n        30: 1,  # 'э'\n        27: 1,  # 'ю'\n        16: 1,  # 'я'\n    },\n    34: {  # 'О'\n        37: 0,  # 'А'\n        44: 1,  # 'Б'\n        33: 1,  # 'В'\n        46: 1,  # 'Г'\n        41: 2,  # 'Д'\n        48: 1,  # 'Е'\n        56: 1,  # 'Ж'\n        51: 1,  # 'З'\n        42: 1,  # 'И'\n        60: 1,  # 'Й'\n        36: 1,  # 'К'\n        49: 2,  # 'Л'\n        38: 1,  # 'М'\n        31: 2,  # 'Н'\n        34: 1,  # 'О'\n        35: 1,  # 'П'\n        45: 2,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 1,  # 'У'\n        53: 1,  # 'Ф'\n        55: 1,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 1,  # 'Ч'\n        57: 1,  # 'Ш'\n        63: 1,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 1,  # 'а'\n        21: 2,  # 'б'\n        10: 1,  # 'в'\n        19: 2,  # 'г'\n        13: 2,  # 'д'\n        2: 0,  # 'е'\n        24: 1,  # 'ж'\n        20: 1,  # 'з'\n        4: 0,  # 'и'\n        23: 1,  # 'й'\n        11: 2,  # 'к'\n        8: 2,  # 'л'\n        12: 1,  # 'м'\n        5: 3,  # 'н'\n        1: 0,  # 'о'\n        15: 2,  # 'п'\n        9: 2,  # 'р'\n        7: 2,  # 'с'\n        6: 2,  # 'т'\n        14: 1,  # 'у'\n        39: 1,  # 'ф'\n        26: 2,  # 'х'\n        28: 1,  # 'ц'\n        22: 2,  # 'ч'\n        25: 2,  # 'ш'\n        29: 1,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    35: {  # 'П'\n        37: 1,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 1,  # 'Л'\n        38: 0,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 1,  # 'П'\n        45: 2,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 1,  # 'Ы'\n        61: 1,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 2,  # 'а'\n        21: 0,  # 'б'\n        10: 0,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 2,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 2,  # 'л'\n        12: 0,  # 'м'\n        5: 1,  # 'н'\n        1: 3,  # 'о'\n        15: 0,  # 'п'\n        9: 3,  # 'р'\n        7: 1,  # 'с'\n        6: 1,  # 'т'\n        14: 2,  # 'у'\n        39: 1,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 1,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 1,  # 'ы'\n        17: 2,  # 'ь'\n        30: 1,  # 'э'\n        27: 0,  # 'ю'\n        16: 2,  # 'я'\n    },\n    45: {  # 'Р'\n        37: 2,  # 'А'\n        44: 1,  # 'Б'\n        33: 1,  # 'В'\n        46: 1,  # 'Г'\n        41: 1,  # 'Д'\n        48: 2,  # 'Е'\n        56: 1,  # 'Ж'\n        51: 0,  # 'З'\n        42: 2,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 2,  # 'О'\n        35: 0,  # 'П'\n        45: 1,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 1,  # 'Х'\n        58: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        57: 1,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 1,  # 'Ы'\n        61: 1,  # 'Ь'\n        47: 1,  # 'Э'\n        59: 1,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 3,  # 'а'\n        21: 0,  # 'б'\n        10: 1,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 2,  # 'е'\n        24: 1,  # 'ж'\n        20: 0,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 0,  # 'л'\n        12: 0,  # 'м'\n        5: 0,  # 'н'\n        1: 3,  # 'о'\n        15: 0,  # 'п'\n        9: 1,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 2,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 2,  # 'ы'\n        17: 0,  # 'ь'\n        30: 1,  # 'э'\n        27: 1,  # 'ю'\n        16: 2,  # 'я'\n    },\n    32: {  # 'С'\n        37: 1,  # 'А'\n        44: 1,  # 'Б'\n        33: 1,  # 'В'\n        46: 1,  # 'Г'\n        41: 1,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 1,  # 'П'\n        45: 1,  # 'Р'\n        32: 1,  # 'С'\n        40: 2,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 1,  # 'Х'\n        58: 1,  # 'Ц'\n        50: 1,  # 'Ч'\n        57: 1,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 1,  # 'Ы'\n        61: 1,  # 'Ь'\n        47: 1,  # 'Э'\n        59: 1,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 2,  # 'а'\n        21: 1,  # 'б'\n        10: 2,  # 'в'\n        19: 1,  # 'г'\n        13: 2,  # 'д'\n        2: 3,  # 'е'\n        24: 1,  # 'ж'\n        20: 1,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 2,  # 'к'\n        8: 2,  # 'л'\n        12: 2,  # 'м'\n        5: 2,  # 'н'\n        1: 2,  # 'о'\n        15: 2,  # 'п'\n        9: 2,  # 'р'\n        7: 1,  # 'с'\n        6: 3,  # 'т'\n        14: 2,  # 'у'\n        39: 1,  # 'ф'\n        26: 1,  # 'х'\n        28: 1,  # 'ц'\n        22: 1,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 1,  # 'ъ'\n        18: 1,  # 'ы'\n        17: 1,  # 'ь'\n        30: 2,  # 'э'\n        27: 1,  # 'ю'\n        16: 1,  # 'я'\n    },\n    40: {  # 'Т'\n        37: 1,  # 'А'\n        44: 0,  # 'Б'\n        33: 1,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 2,  # 'О'\n        35: 0,  # 'П'\n        45: 1,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 1,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 1,  # 'Ы'\n        61: 1,  # 'Ь'\n        47: 1,  # 'Э'\n        59: 1,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 3,  # 'а'\n        21: 1,  # 'б'\n        10: 2,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 3,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 1,  # 'к'\n        8: 1,  # 'л'\n        12: 0,  # 'м'\n        5: 0,  # 'н'\n        1: 3,  # 'о'\n        15: 0,  # 'п'\n        9: 2,  # 'р'\n        7: 1,  # 'с'\n        6: 0,  # 'т'\n        14: 2,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 1,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 1,  # 'ь'\n        30: 2,  # 'э'\n        27: 1,  # 'ю'\n        16: 1,  # 'я'\n    },\n    52: {  # 'У'\n        37: 1,  # 'А'\n        44: 1,  # 'Б'\n        33: 1,  # 'В'\n        46: 1,  # 'Г'\n        41: 1,  # 'Д'\n        48: 1,  # 'Е'\n        56: 1,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 1,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 1,  # 'П'\n        45: 1,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 1,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 1,  # 'Ч'\n        57: 1,  # 'Ш'\n        63: 1,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 1,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 1,  # 'а'\n        21: 2,  # 'б'\n        10: 2,  # 'в'\n        19: 1,  # 'г'\n        13: 2,  # 'д'\n        2: 1,  # 'е'\n        24: 2,  # 'ж'\n        20: 2,  # 'з'\n        4: 2,  # 'и'\n        23: 1,  # 'й'\n        11: 1,  # 'к'\n        8: 2,  # 'л'\n        12: 2,  # 'м'\n        5: 1,  # 'н'\n        1: 2,  # 'о'\n        15: 1,  # 'п'\n        9: 2,  # 'р'\n        7: 2,  # 'с'\n        6: 2,  # 'т'\n        14: 0,  # 'у'\n        39: 1,  # 'ф'\n        26: 1,  # 'х'\n        28: 1,  # 'ц'\n        22: 2,  # 'ч'\n        25: 1,  # 'ш'\n        29: 1,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 2,  # 'э'\n        27: 1,  # 'ю'\n        16: 0,  # 'я'\n    },\n    53: {  # 'Ф'\n        37: 1,  # 'А'\n        44: 1,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 1,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 1,  # 'О'\n        35: 0,  # 'П'\n        45: 1,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 2,  # 'а'\n        21: 0,  # 'б'\n        10: 0,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 2,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 2,  # 'л'\n        12: 0,  # 'м'\n        5: 0,  # 'н'\n        1: 2,  # 'о'\n        15: 0,  # 'п'\n        9: 2,  # 'р'\n        7: 0,  # 'с'\n        6: 1,  # 'т'\n        14: 2,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 1,  # 'ь'\n        30: 2,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    55: {  # 'Х'\n        37: 1,  # 'А'\n        44: 0,  # 'Б'\n        33: 1,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 2,  # 'а'\n        21: 0,  # 'б'\n        10: 2,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 2,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 2,  # 'л'\n        12: 1,  # 'м'\n        5: 0,  # 'н'\n        1: 2,  # 'о'\n        15: 0,  # 'п'\n        9: 2,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 1,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 1,  # 'ь'\n        30: 1,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    58: {  # 'Ц'\n        37: 1,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 1,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 1,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 1,  # 'а'\n        21: 0,  # 'б'\n        10: 1,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 2,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 0,  # 'л'\n        12: 0,  # 'м'\n        5: 0,  # 'н'\n        1: 0,  # 'о'\n        15: 0,  # 'п'\n        9: 0,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 1,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 1,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 1,  # 'ю'\n        16: 0,  # 'я'\n    },\n    50: {  # 'Ч'\n        37: 1,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 1,  # 'Н'\n        34: 0,  # 'О'\n        35: 1,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 1,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 1,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 2,  # 'а'\n        21: 0,  # 'б'\n        10: 0,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 2,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 1,  # 'л'\n        12: 0,  # 'м'\n        5: 0,  # 'н'\n        1: 1,  # 'о'\n        15: 0,  # 'п'\n        9: 1,  # 'р'\n        7: 0,  # 'с'\n        6: 3,  # 'т'\n        14: 2,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 1,  # 'ь'\n        30: 0,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    57: {  # 'Ш'\n        37: 1,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 0,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 1,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 2,  # 'а'\n        21: 0,  # 'б'\n        10: 1,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 2,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 1,  # 'и'\n        23: 0,  # 'й'\n        11: 1,  # 'к'\n        8: 2,  # 'л'\n        12: 1,  # 'м'\n        5: 1,  # 'н'\n        1: 2,  # 'о'\n        15: 2,  # 'п'\n        9: 1,  # 'р'\n        7: 0,  # 'с'\n        6: 2,  # 'т'\n        14: 2,  # 'у'\n        39: 0,  # 'ф'\n        26: 1,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 1,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 1,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    63: {  # 'Щ'\n        37: 1,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 1,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 1,  # 'а'\n        21: 0,  # 'б'\n        10: 0,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 1,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 1,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 0,  # 'л'\n        12: 0,  # 'м'\n        5: 0,  # 'н'\n        1: 1,  # 'о'\n        15: 0,  # 'п'\n        9: 0,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 1,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    62: {  # 'Ы'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 1,  # 'В'\n        46: 1,  # 'Г'\n        41: 0,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 1,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 0,  # 'О'\n        35: 1,  # 'П'\n        45: 1,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 1,  # 'Х'\n        58: 1,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 1,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 0,  # 'а'\n        21: 0,  # 'б'\n        10: 0,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 0,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 0,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 0,  # 'л'\n        12: 0,  # 'м'\n        5: 0,  # 'н'\n        1: 0,  # 'о'\n        15: 0,  # 'п'\n        9: 0,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 0,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    61: {  # 'Ь'\n        37: 0,  # 'А'\n        44: 1,  # 'Б'\n        33: 1,  # 'В'\n        46: 0,  # 'Г'\n        41: 1,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 0,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 1,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 1,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 1,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 1,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 1,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 0,  # 'а'\n        21: 0,  # 'б'\n        10: 0,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 0,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 0,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 0,  # 'л'\n        12: 0,  # 'м'\n        5: 0,  # 'н'\n        1: 0,  # 'о'\n        15: 0,  # 'п'\n        9: 0,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 0,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    47: {  # 'Э'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 1,  # 'В'\n        46: 0,  # 'Г'\n        41: 1,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 1,  # 'Й'\n        36: 1,  # 'К'\n        49: 1,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 0,  # 'О'\n        35: 1,  # 'П'\n        45: 1,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 1,  # 'а'\n        21: 1,  # 'б'\n        10: 2,  # 'в'\n        19: 1,  # 'г'\n        13: 2,  # 'д'\n        2: 0,  # 'е'\n        24: 1,  # 'ж'\n        20: 0,  # 'з'\n        4: 0,  # 'и'\n        23: 2,  # 'й'\n        11: 2,  # 'к'\n        8: 2,  # 'л'\n        12: 2,  # 'м'\n        5: 2,  # 'н'\n        1: 0,  # 'о'\n        15: 1,  # 'п'\n        9: 2,  # 'р'\n        7: 1,  # 'с'\n        6: 3,  # 'т'\n        14: 1,  # 'у'\n        39: 1,  # 'ф'\n        26: 1,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 1,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    59: {  # 'Ю'\n        37: 1,  # 'А'\n        44: 1,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 1,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 1,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 1,  # 'Р'\n        32: 0,  # 'С'\n        40: 1,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 1,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 1,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 0,  # 'а'\n        21: 1,  # 'б'\n        10: 0,  # 'в'\n        19: 1,  # 'г'\n        13: 1,  # 'д'\n        2: 0,  # 'е'\n        24: 1,  # 'ж'\n        20: 0,  # 'з'\n        4: 0,  # 'и'\n        23: 0,  # 'й'\n        11: 1,  # 'к'\n        8: 2,  # 'л'\n        12: 1,  # 'м'\n        5: 2,  # 'н'\n        1: 0,  # 'о'\n        15: 1,  # 'п'\n        9: 1,  # 'р'\n        7: 1,  # 'с'\n        6: 0,  # 'т'\n        14: 0,  # 'у'\n        39: 0,  # 'ф'\n        26: 1,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    43: {  # 'Я'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 1,  # 'В'\n        46: 1,  # 'Г'\n        41: 0,  # 'Д'\n        48: 1,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 1,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 1,  # 'С'\n        40: 1,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 1,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 1,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 1,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 1,  # 'Ю'\n        43: 1,  # 'Я'\n        3: 0,  # 'а'\n        21: 1,  # 'б'\n        10: 1,  # 'в'\n        19: 1,  # 'г'\n        13: 1,  # 'д'\n        2: 0,  # 'е'\n        24: 0,  # 'ж'\n        20: 1,  # 'з'\n        4: 0,  # 'и'\n        23: 1,  # 'й'\n        11: 1,  # 'к'\n        8: 1,  # 'л'\n        12: 1,  # 'м'\n        5: 2,  # 'н'\n        1: 0,  # 'о'\n        15: 1,  # 'п'\n        9: 1,  # 'р'\n        7: 1,  # 'с'\n        6: 0,  # 'т'\n        14: 0,  # 'у'\n        39: 0,  # 'ф'\n        26: 1,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 1,  # 'ш'\n        29: 1,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    3: {  # 'а'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 1,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 1,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 2,  # 'а'\n        21: 3,  # 'б'\n        10: 3,  # 'в'\n        19: 3,  # 'г'\n        13: 3,  # 'д'\n        2: 3,  # 'е'\n        24: 3,  # 'ж'\n        20: 3,  # 'з'\n        4: 3,  # 'и'\n        23: 3,  # 'й'\n        11: 3,  # 'к'\n        8: 3,  # 'л'\n        12: 3,  # 'м'\n        5: 3,  # 'н'\n        1: 2,  # 'о'\n        15: 3,  # 'п'\n        9: 3,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 3,  # 'у'\n        39: 2,  # 'ф'\n        26: 3,  # 'х'\n        28: 3,  # 'ц'\n        22: 3,  # 'ч'\n        25: 3,  # 'ш'\n        29: 3,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 2,  # 'э'\n        27: 3,  # 'ю'\n        16: 3,  # 'я'\n    },\n    21: {  # 'б'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 1,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 2,  # 'б'\n        10: 2,  # 'в'\n        19: 1,  # 'г'\n        13: 2,  # 'д'\n        2: 3,  # 'е'\n        24: 2,  # 'ж'\n        20: 1,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 2,  # 'к'\n        8: 3,  # 'л'\n        12: 2,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 1,  # 'п'\n        9: 3,  # 'р'\n        7: 3,  # 'с'\n        6: 2,  # 'т'\n        14: 3,  # 'у'\n        39: 0,  # 'ф'\n        26: 2,  # 'х'\n        28: 1,  # 'ц'\n        22: 1,  # 'ч'\n        25: 2,  # 'ш'\n        29: 3,  # 'щ'\n        54: 2,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 2,  # 'ь'\n        30: 1,  # 'э'\n        27: 2,  # 'ю'\n        16: 3,  # 'я'\n    },\n    10: {  # 'в'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 2,  # 'б'\n        10: 2,  # 'в'\n        19: 2,  # 'г'\n        13: 3,  # 'д'\n        2: 3,  # 'е'\n        24: 1,  # 'ж'\n        20: 3,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 3,  # 'к'\n        8: 3,  # 'л'\n        12: 2,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 3,  # 'п'\n        9: 3,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 3,  # 'у'\n        39: 1,  # 'ф'\n        26: 2,  # 'х'\n        28: 2,  # 'ц'\n        22: 2,  # 'ч'\n        25: 3,  # 'ш'\n        29: 2,  # 'щ'\n        54: 2,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 3,  # 'ь'\n        30: 1,  # 'э'\n        27: 1,  # 'ю'\n        16: 3,  # 'я'\n    },\n    19: {  # 'г'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 1,  # 'б'\n        10: 2,  # 'в'\n        19: 1,  # 'г'\n        13: 3,  # 'д'\n        2: 3,  # 'е'\n        24: 0,  # 'ж'\n        20: 1,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 2,  # 'к'\n        8: 3,  # 'л'\n        12: 2,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 0,  # 'п'\n        9: 3,  # 'р'\n        7: 2,  # 'с'\n        6: 2,  # 'т'\n        14: 3,  # 'у'\n        39: 1,  # 'ф'\n        26: 1,  # 'х'\n        28: 1,  # 'ц'\n        22: 2,  # 'ч'\n        25: 1,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 1,  # 'ы'\n        17: 1,  # 'ь'\n        30: 1,  # 'э'\n        27: 1,  # 'ю'\n        16: 0,  # 'я'\n    },\n    13: {  # 'д'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 2,  # 'б'\n        10: 3,  # 'в'\n        19: 2,  # 'г'\n        13: 2,  # 'д'\n        2: 3,  # 'е'\n        24: 2,  # 'ж'\n        20: 2,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 3,  # 'к'\n        8: 3,  # 'л'\n        12: 2,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 2,  # 'п'\n        9: 3,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 3,  # 'у'\n        39: 1,  # 'ф'\n        26: 2,  # 'х'\n        28: 3,  # 'ц'\n        22: 2,  # 'ч'\n        25: 2,  # 'ш'\n        29: 1,  # 'щ'\n        54: 2,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 3,  # 'ь'\n        30: 1,  # 'э'\n        27: 2,  # 'ю'\n        16: 3,  # 'я'\n    },\n    2: {  # 'е'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 2,  # 'а'\n        21: 3,  # 'б'\n        10: 3,  # 'в'\n        19: 3,  # 'г'\n        13: 3,  # 'д'\n        2: 3,  # 'е'\n        24: 3,  # 'ж'\n        20: 3,  # 'з'\n        4: 2,  # 'и'\n        23: 3,  # 'й'\n        11: 3,  # 'к'\n        8: 3,  # 'л'\n        12: 3,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 3,  # 'п'\n        9: 3,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 2,  # 'у'\n        39: 2,  # 'ф'\n        26: 3,  # 'х'\n        28: 3,  # 'ц'\n        22: 3,  # 'ч'\n        25: 3,  # 'ш'\n        29: 3,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 1,  # 'э'\n        27: 2,  # 'ю'\n        16: 3,  # 'я'\n    },\n    24: {  # 'ж'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 2,  # 'б'\n        10: 1,  # 'в'\n        19: 2,  # 'г'\n        13: 3,  # 'д'\n        2: 3,  # 'е'\n        24: 2,  # 'ж'\n        20: 1,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 2,  # 'к'\n        8: 2,  # 'л'\n        12: 1,  # 'м'\n        5: 3,  # 'н'\n        1: 2,  # 'о'\n        15: 1,  # 'п'\n        9: 2,  # 'р'\n        7: 2,  # 'с'\n        6: 1,  # 'т'\n        14: 3,  # 'у'\n        39: 1,  # 'ф'\n        26: 0,  # 'х'\n        28: 1,  # 'ц'\n        22: 2,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 1,  # 'ы'\n        17: 2,  # 'ь'\n        30: 1,  # 'э'\n        27: 1,  # 'ю'\n        16: 1,  # 'я'\n    },\n    20: {  # 'з'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 3,  # 'б'\n        10: 3,  # 'в'\n        19: 3,  # 'г'\n        13: 3,  # 'д'\n        2: 3,  # 'е'\n        24: 2,  # 'ж'\n        20: 2,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 3,  # 'к'\n        8: 3,  # 'л'\n        12: 3,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 0,  # 'п'\n        9: 3,  # 'р'\n        7: 2,  # 'с'\n        6: 2,  # 'т'\n        14: 3,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 1,  # 'ц'\n        22: 2,  # 'ч'\n        25: 1,  # 'ш'\n        29: 0,  # 'щ'\n        54: 2,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 2,  # 'ь'\n        30: 1,  # 'э'\n        27: 1,  # 'ю'\n        16: 3,  # 'я'\n    },\n    4: {  # 'и'\n        37: 1,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 1,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 3,  # 'б'\n        10: 3,  # 'в'\n        19: 3,  # 'г'\n        13: 3,  # 'д'\n        2: 3,  # 'е'\n        24: 3,  # 'ж'\n        20: 3,  # 'з'\n        4: 3,  # 'и'\n        23: 3,  # 'й'\n        11: 3,  # 'к'\n        8: 3,  # 'л'\n        12: 3,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 3,  # 'п'\n        9: 3,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 2,  # 'у'\n        39: 2,  # 'ф'\n        26: 3,  # 'х'\n        28: 3,  # 'ц'\n        22: 3,  # 'ч'\n        25: 3,  # 'ш'\n        29: 3,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 2,  # 'э'\n        27: 3,  # 'ю'\n        16: 3,  # 'я'\n    },\n    23: {  # 'й'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 1,  # 'а'\n        21: 1,  # 'б'\n        10: 1,  # 'в'\n        19: 2,  # 'г'\n        13: 3,  # 'д'\n        2: 2,  # 'е'\n        24: 0,  # 'ж'\n        20: 2,  # 'з'\n        4: 1,  # 'и'\n        23: 0,  # 'й'\n        11: 2,  # 'к'\n        8: 2,  # 'л'\n        12: 2,  # 'м'\n        5: 3,  # 'н'\n        1: 2,  # 'о'\n        15: 1,  # 'п'\n        9: 2,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 1,  # 'у'\n        39: 2,  # 'ф'\n        26: 1,  # 'х'\n        28: 2,  # 'ц'\n        22: 3,  # 'ч'\n        25: 2,  # 'ш'\n        29: 1,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 1,  # 'э'\n        27: 1,  # 'ю'\n        16: 2,  # 'я'\n    },\n    11: {  # 'к'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 1,  # 'б'\n        10: 3,  # 'в'\n        19: 1,  # 'г'\n        13: 1,  # 'д'\n        2: 3,  # 'е'\n        24: 2,  # 'ж'\n        20: 2,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 2,  # 'к'\n        8: 3,  # 'л'\n        12: 1,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 0,  # 'п'\n        9: 3,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 3,  # 'у'\n        39: 1,  # 'ф'\n        26: 2,  # 'х'\n        28: 2,  # 'ц'\n        22: 1,  # 'ч'\n        25: 2,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 1,  # 'ы'\n        17: 1,  # 'ь'\n        30: 1,  # 'э'\n        27: 1,  # 'ю'\n        16: 1,  # 'я'\n    },\n    8: {  # 'л'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 2,  # 'б'\n        10: 2,  # 'в'\n        19: 3,  # 'г'\n        13: 2,  # 'д'\n        2: 3,  # 'е'\n        24: 3,  # 'ж'\n        20: 2,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 3,  # 'к'\n        8: 3,  # 'л'\n        12: 2,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 2,  # 'п'\n        9: 1,  # 'р'\n        7: 3,  # 'с'\n        6: 2,  # 'т'\n        14: 3,  # 'у'\n        39: 2,  # 'ф'\n        26: 2,  # 'х'\n        28: 1,  # 'ц'\n        22: 3,  # 'ч'\n        25: 2,  # 'ш'\n        29: 1,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 3,  # 'ь'\n        30: 1,  # 'э'\n        27: 3,  # 'ю'\n        16: 3,  # 'я'\n    },\n    12: {  # 'м'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 2,  # 'б'\n        10: 2,  # 'в'\n        19: 2,  # 'г'\n        13: 1,  # 'д'\n        2: 3,  # 'е'\n        24: 1,  # 'ж'\n        20: 1,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 2,  # 'к'\n        8: 3,  # 'л'\n        12: 2,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 2,  # 'п'\n        9: 2,  # 'р'\n        7: 3,  # 'с'\n        6: 2,  # 'т'\n        14: 3,  # 'у'\n        39: 2,  # 'ф'\n        26: 2,  # 'х'\n        28: 2,  # 'ц'\n        22: 2,  # 'ч'\n        25: 1,  # 'ш'\n        29: 1,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 2,  # 'ь'\n        30: 2,  # 'э'\n        27: 1,  # 'ю'\n        16: 3,  # 'я'\n    },\n    5: {  # 'н'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 2,  # 'б'\n        10: 2,  # 'в'\n        19: 3,  # 'г'\n        13: 3,  # 'д'\n        2: 3,  # 'е'\n        24: 2,  # 'ж'\n        20: 2,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 3,  # 'к'\n        8: 2,  # 'л'\n        12: 1,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 1,  # 'п'\n        9: 2,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 3,  # 'у'\n        39: 2,  # 'ф'\n        26: 2,  # 'х'\n        28: 3,  # 'ц'\n        22: 3,  # 'ч'\n        25: 2,  # 'ш'\n        29: 2,  # 'щ'\n        54: 1,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 3,  # 'ь'\n        30: 1,  # 'э'\n        27: 3,  # 'ю'\n        16: 3,  # 'я'\n    },\n    1: {  # 'о'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 2,  # 'а'\n        21: 3,  # 'б'\n        10: 3,  # 'в'\n        19: 3,  # 'г'\n        13: 3,  # 'д'\n        2: 3,  # 'е'\n        24: 3,  # 'ж'\n        20: 3,  # 'з'\n        4: 3,  # 'и'\n        23: 3,  # 'й'\n        11: 3,  # 'к'\n        8: 3,  # 'л'\n        12: 3,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 3,  # 'п'\n        9: 3,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 2,  # 'у'\n        39: 2,  # 'ф'\n        26: 3,  # 'х'\n        28: 2,  # 'ц'\n        22: 3,  # 'ч'\n        25: 3,  # 'ш'\n        29: 3,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 2,  # 'э'\n        27: 3,  # 'ю'\n        16: 3,  # 'я'\n    },\n    15: {  # 'п'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 1,  # 'б'\n        10: 0,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 3,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 2,  # 'к'\n        8: 3,  # 'л'\n        12: 1,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 2,  # 'п'\n        9: 3,  # 'р'\n        7: 2,  # 'с'\n        6: 2,  # 'т'\n        14: 3,  # 'у'\n        39: 1,  # 'ф'\n        26: 0,  # 'х'\n        28: 2,  # 'ц'\n        22: 2,  # 'ч'\n        25: 1,  # 'ш'\n        29: 1,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 2,  # 'ь'\n        30: 1,  # 'э'\n        27: 1,  # 'ю'\n        16: 3,  # 'я'\n    },\n    9: {  # 'р'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 2,  # 'б'\n        10: 3,  # 'в'\n        19: 3,  # 'г'\n        13: 3,  # 'д'\n        2: 3,  # 'е'\n        24: 3,  # 'ж'\n        20: 2,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 3,  # 'к'\n        8: 2,  # 'л'\n        12: 3,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 2,  # 'п'\n        9: 2,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 3,  # 'у'\n        39: 2,  # 'ф'\n        26: 3,  # 'х'\n        28: 2,  # 'ц'\n        22: 2,  # 'ч'\n        25: 3,  # 'ш'\n        29: 2,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 3,  # 'ь'\n        30: 2,  # 'э'\n        27: 2,  # 'ю'\n        16: 3,  # 'я'\n    },\n    7: {  # 'с'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 1,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 2,  # 'б'\n        10: 3,  # 'в'\n        19: 2,  # 'г'\n        13: 3,  # 'д'\n        2: 3,  # 'е'\n        24: 2,  # 'ж'\n        20: 2,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 3,  # 'к'\n        8: 3,  # 'л'\n        12: 3,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 3,  # 'п'\n        9: 3,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 3,  # 'у'\n        39: 2,  # 'ф'\n        26: 3,  # 'х'\n        28: 2,  # 'ц'\n        22: 3,  # 'ч'\n        25: 2,  # 'ш'\n        29: 1,  # 'щ'\n        54: 2,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 3,  # 'ь'\n        30: 2,  # 'э'\n        27: 3,  # 'ю'\n        16: 3,  # 'я'\n    },\n    6: {  # 'т'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 2,  # 'б'\n        10: 3,  # 'в'\n        19: 2,  # 'г'\n        13: 2,  # 'д'\n        2: 3,  # 'е'\n        24: 1,  # 'ж'\n        20: 1,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 3,  # 'к'\n        8: 3,  # 'л'\n        12: 2,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 2,  # 'п'\n        9: 3,  # 'р'\n        7: 3,  # 'с'\n        6: 2,  # 'т'\n        14: 3,  # 'у'\n        39: 2,  # 'ф'\n        26: 2,  # 'х'\n        28: 2,  # 'ц'\n        22: 2,  # 'ч'\n        25: 2,  # 'ш'\n        29: 2,  # 'щ'\n        54: 2,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 3,  # 'ь'\n        30: 2,  # 'э'\n        27: 2,  # 'ю'\n        16: 3,  # 'я'\n    },\n    14: {  # 'у'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 2,  # 'а'\n        21: 3,  # 'б'\n        10: 3,  # 'в'\n        19: 3,  # 'г'\n        13: 3,  # 'д'\n        2: 3,  # 'е'\n        24: 3,  # 'ж'\n        20: 3,  # 'з'\n        4: 2,  # 'и'\n        23: 2,  # 'й'\n        11: 3,  # 'к'\n        8: 3,  # 'л'\n        12: 3,  # 'м'\n        5: 3,  # 'н'\n        1: 2,  # 'о'\n        15: 3,  # 'п'\n        9: 3,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 1,  # 'у'\n        39: 2,  # 'ф'\n        26: 3,  # 'х'\n        28: 2,  # 'ц'\n        22: 3,  # 'ч'\n        25: 3,  # 'ш'\n        29: 3,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 2,  # 'э'\n        27: 3,  # 'ю'\n        16: 2,  # 'я'\n    },\n    39: {  # 'ф'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 1,  # 'б'\n        10: 0,  # 'в'\n        19: 1,  # 'г'\n        13: 0,  # 'д'\n        2: 3,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 1,  # 'к'\n        8: 2,  # 'л'\n        12: 1,  # 'м'\n        5: 1,  # 'н'\n        1: 3,  # 'о'\n        15: 1,  # 'п'\n        9: 2,  # 'р'\n        7: 2,  # 'с'\n        6: 2,  # 'т'\n        14: 2,  # 'у'\n        39: 2,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 1,  # 'ч'\n        25: 1,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 2,  # 'ы'\n        17: 1,  # 'ь'\n        30: 2,  # 'э'\n        27: 1,  # 'ю'\n        16: 1,  # 'я'\n    },\n    26: {  # 'х'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 0,  # 'б'\n        10: 3,  # 'в'\n        19: 1,  # 'г'\n        13: 1,  # 'д'\n        2: 2,  # 'е'\n        24: 0,  # 'ж'\n        20: 1,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 1,  # 'к'\n        8: 2,  # 'л'\n        12: 2,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 1,  # 'п'\n        9: 3,  # 'р'\n        7: 2,  # 'с'\n        6: 2,  # 'т'\n        14: 2,  # 'у'\n        39: 1,  # 'ф'\n        26: 1,  # 'х'\n        28: 1,  # 'ц'\n        22: 1,  # 'ч'\n        25: 2,  # 'ш'\n        29: 0,  # 'щ'\n        54: 1,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 1,  # 'ь'\n        30: 1,  # 'э'\n        27: 1,  # 'ю'\n        16: 0,  # 'я'\n    },\n    28: {  # 'ц'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 1,  # 'б'\n        10: 2,  # 'в'\n        19: 1,  # 'г'\n        13: 1,  # 'д'\n        2: 3,  # 'е'\n        24: 0,  # 'ж'\n        20: 1,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 2,  # 'к'\n        8: 1,  # 'л'\n        12: 1,  # 'м'\n        5: 1,  # 'н'\n        1: 3,  # 'о'\n        15: 0,  # 'п'\n        9: 1,  # 'р'\n        7: 0,  # 'с'\n        6: 1,  # 'т'\n        14: 3,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 1,  # 'ц'\n        22: 0,  # 'ч'\n        25: 1,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 3,  # 'ы'\n        17: 1,  # 'ь'\n        30: 0,  # 'э'\n        27: 1,  # 'ю'\n        16: 0,  # 'я'\n    },\n    22: {  # 'ч'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 1,  # 'б'\n        10: 1,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 3,  # 'е'\n        24: 1,  # 'ж'\n        20: 0,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 3,  # 'к'\n        8: 2,  # 'л'\n        12: 1,  # 'м'\n        5: 3,  # 'н'\n        1: 2,  # 'о'\n        15: 0,  # 'п'\n        9: 2,  # 'р'\n        7: 1,  # 'с'\n        6: 3,  # 'т'\n        14: 3,  # 'у'\n        39: 1,  # 'ф'\n        26: 1,  # 'х'\n        28: 0,  # 'ц'\n        22: 1,  # 'ч'\n        25: 2,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 3,  # 'ь'\n        30: 0,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    25: {  # 'ш'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 1,  # 'б'\n        10: 2,  # 'в'\n        19: 1,  # 'г'\n        13: 0,  # 'д'\n        2: 3,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 3,  # 'к'\n        8: 3,  # 'л'\n        12: 2,  # 'м'\n        5: 3,  # 'н'\n        1: 3,  # 'о'\n        15: 2,  # 'п'\n        9: 2,  # 'р'\n        7: 1,  # 'с'\n        6: 2,  # 'т'\n        14: 3,  # 'у'\n        39: 2,  # 'ф'\n        26: 1,  # 'х'\n        28: 1,  # 'ц'\n        22: 1,  # 'ч'\n        25: 1,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 3,  # 'ь'\n        30: 1,  # 'э'\n        27: 1,  # 'ю'\n        16: 0,  # 'я'\n    },\n    29: {  # 'щ'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 3,  # 'а'\n        21: 0,  # 'б'\n        10: 1,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 3,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 3,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 0,  # 'л'\n        12: 1,  # 'м'\n        5: 2,  # 'н'\n        1: 1,  # 'о'\n        15: 0,  # 'п'\n        9: 2,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 2,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 2,  # 'ь'\n        30: 0,  # 'э'\n        27: 0,  # 'ю'\n        16: 0,  # 'я'\n    },\n    54: {  # 'ъ'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 0,  # 'а'\n        21: 0,  # 'б'\n        10: 0,  # 'в'\n        19: 0,  # 'г'\n        13: 0,  # 'д'\n        2: 2,  # 'е'\n        24: 0,  # 'ж'\n        20: 0,  # 'з'\n        4: 0,  # 'и'\n        23: 0,  # 'й'\n        11: 0,  # 'к'\n        8: 0,  # 'л'\n        12: 0,  # 'м'\n        5: 0,  # 'н'\n        1: 0,  # 'о'\n        15: 0,  # 'п'\n        9: 0,  # 'р'\n        7: 0,  # 'с'\n        6: 0,  # 'т'\n        14: 0,  # 'у'\n        39: 0,  # 'ф'\n        26: 0,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 0,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 1,  # 'ю'\n        16: 2,  # 'я'\n    },\n    18: {  # 'ы'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 0,  # 'а'\n        21: 3,  # 'б'\n        10: 3,  # 'в'\n        19: 2,  # 'г'\n        13: 2,  # 'д'\n        2: 3,  # 'е'\n        24: 2,  # 'ж'\n        20: 2,  # 'з'\n        4: 2,  # 'и'\n        23: 3,  # 'й'\n        11: 3,  # 'к'\n        8: 3,  # 'л'\n        12: 3,  # 'м'\n        5: 3,  # 'н'\n        1: 1,  # 'о'\n        15: 3,  # 'п'\n        9: 3,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 1,  # 'у'\n        39: 0,  # 'ф'\n        26: 3,  # 'х'\n        28: 2,  # 'ц'\n        22: 3,  # 'ч'\n        25: 3,  # 'ш'\n        29: 2,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 0,  # 'ю'\n        16: 2,  # 'я'\n    },\n    17: {  # 'ь'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 0,  # 'а'\n        21: 2,  # 'б'\n        10: 2,  # 'в'\n        19: 2,  # 'г'\n        13: 2,  # 'д'\n        2: 3,  # 'е'\n        24: 1,  # 'ж'\n        20: 3,  # 'з'\n        4: 2,  # 'и'\n        23: 0,  # 'й'\n        11: 3,  # 'к'\n        8: 0,  # 'л'\n        12: 3,  # 'м'\n        5: 3,  # 'н'\n        1: 2,  # 'о'\n        15: 2,  # 'п'\n        9: 1,  # 'р'\n        7: 3,  # 'с'\n        6: 2,  # 'т'\n        14: 0,  # 'у'\n        39: 2,  # 'ф'\n        26: 1,  # 'х'\n        28: 2,  # 'ц'\n        22: 2,  # 'ч'\n        25: 3,  # 'ш'\n        29: 2,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 1,  # 'э'\n        27: 3,  # 'ю'\n        16: 3,  # 'я'\n    },\n    30: {  # 'э'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 1,  # 'М'\n        31: 1,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 1,  # 'Р'\n        32: 1,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 1,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 0,  # 'а'\n        21: 1,  # 'б'\n        10: 1,  # 'в'\n        19: 1,  # 'г'\n        13: 2,  # 'д'\n        2: 1,  # 'е'\n        24: 0,  # 'ж'\n        20: 1,  # 'з'\n        4: 0,  # 'и'\n        23: 2,  # 'й'\n        11: 2,  # 'к'\n        8: 2,  # 'л'\n        12: 2,  # 'м'\n        5: 2,  # 'н'\n        1: 0,  # 'о'\n        15: 2,  # 'п'\n        9: 2,  # 'р'\n        7: 2,  # 'с'\n        6: 3,  # 'т'\n        14: 1,  # 'у'\n        39: 2,  # 'ф'\n        26: 1,  # 'х'\n        28: 0,  # 'ц'\n        22: 0,  # 'ч'\n        25: 1,  # 'ш'\n        29: 0,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 1,  # 'э'\n        27: 1,  # 'ю'\n        16: 1,  # 'я'\n    },\n    27: {  # 'ю'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 2,  # 'а'\n        21: 3,  # 'б'\n        10: 1,  # 'в'\n        19: 2,  # 'г'\n        13: 3,  # 'д'\n        2: 1,  # 'е'\n        24: 2,  # 'ж'\n        20: 2,  # 'з'\n        4: 1,  # 'и'\n        23: 1,  # 'й'\n        11: 2,  # 'к'\n        8: 2,  # 'л'\n        12: 2,  # 'м'\n        5: 2,  # 'н'\n        1: 1,  # 'о'\n        15: 2,  # 'п'\n        9: 2,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 0,  # 'у'\n        39: 1,  # 'ф'\n        26: 2,  # 'х'\n        28: 2,  # 'ц'\n        22: 2,  # 'ч'\n        25: 2,  # 'ш'\n        29: 3,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 1,  # 'э'\n        27: 2,  # 'ю'\n        16: 1,  # 'я'\n    },\n    16: {  # 'я'\n        37: 0,  # 'А'\n        44: 0,  # 'Б'\n        33: 0,  # 'В'\n        46: 0,  # 'Г'\n        41: 0,  # 'Д'\n        48: 0,  # 'Е'\n        56: 0,  # 'Ж'\n        51: 0,  # 'З'\n        42: 0,  # 'И'\n        60: 0,  # 'Й'\n        36: 0,  # 'К'\n        49: 0,  # 'Л'\n        38: 0,  # 'М'\n        31: 0,  # 'Н'\n        34: 0,  # 'О'\n        35: 0,  # 'П'\n        45: 0,  # 'Р'\n        32: 0,  # 'С'\n        40: 0,  # 'Т'\n        52: 0,  # 'У'\n        53: 0,  # 'Ф'\n        55: 0,  # 'Х'\n        58: 0,  # 'Ц'\n        50: 0,  # 'Ч'\n        57: 0,  # 'Ш'\n        63: 0,  # 'Щ'\n        62: 0,  # 'Ы'\n        61: 0,  # 'Ь'\n        47: 0,  # 'Э'\n        59: 0,  # 'Ю'\n        43: 0,  # 'Я'\n        3: 0,  # 'а'\n        21: 2,  # 'б'\n        10: 3,  # 'в'\n        19: 2,  # 'г'\n        13: 3,  # 'д'\n        2: 3,  # 'е'\n        24: 3,  # 'ж'\n        20: 3,  # 'з'\n        4: 2,  # 'и'\n        23: 2,  # 'й'\n        11: 3,  # 'к'\n        8: 3,  # 'л'\n        12: 3,  # 'м'\n        5: 3,  # 'н'\n        1: 0,  # 'о'\n        15: 2,  # 'п'\n        9: 2,  # 'р'\n        7: 3,  # 'с'\n        6: 3,  # 'т'\n        14: 1,  # 'у'\n        39: 1,  # 'ф'\n        26: 3,  # 'х'\n        28: 2,  # 'ц'\n        22: 2,  # 'ч'\n        25: 2,  # 'ш'\n        29: 3,  # 'щ'\n        54: 0,  # 'ъ'\n        18: 0,  # 'ы'\n        17: 0,  # 'ь'\n        30: 0,  # 'э'\n        27: 2,  # 'ю'\n        16: 2,  # 'я'\n    },\n}\n\n# 255: Undefined characters that did not exist in training text\n# 254: Carriage/Return\n# 253: symbol (punctuation) that does not belong to word\n# 252: 0 - 9\n# 251: Control characters\n\n# Character Mapping Table(s):\nIBM866_RUSSIAN_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 254,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 254,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 253,  # ' '\n    33: 253,  # '!'\n    34: 253,  # '\"'\n    35: 253,  # '#'\n    36: 253,  # '$'\n    37: 253,  # '%'\n    38: 253,  # '&'\n    39: 253,  # \"'\"\n    40: 253,  # '('\n    41: 253,  # ')'\n    42: 253,  # '*'\n    43: 253,  # '+'\n    44: 253,  # ','\n    45: 253,  # '-'\n    46: 253,  # '.'\n    47: 253,  # '/'\n    48: 252,  # '0'\n    49: 252,  # '1'\n    50: 252,  # '2'\n    51: 252,  # '3'\n    52: 252,  # '4'\n    53: 252,  # '5'\n    54: 252,  # '6'\n    55: 252,  # '7'\n    56: 252,  # '8'\n    57: 252,  # '9'\n    58: 253,  # ':'\n    59: 253,  # ';'\n    60: 253,  # '<'\n    61: 253,  # '='\n    62: 253,  # '>'\n    63: 253,  # '?'\n    64: 253,  # '@'\n    65: 142,  # 'A'\n    66: 143,  # 'B'\n    67: 144,  # 'C'\n    68: 145,  # 'D'\n    69: 146,  # 'E'\n    70: 147,  # 'F'\n    71: 148,  # 'G'\n    72: 149,  # 'H'\n    73: 150,  # 'I'\n    74: 151,  # 'J'\n    75: 152,  # 'K'\n    76: 74,  # 'L'\n    77: 153,  # 'M'\n    78: 75,  # 'N'\n    79: 154,  # 'O'\n    80: 155,  # 'P'\n    81: 156,  # 'Q'\n    82: 157,  # 'R'\n    83: 158,  # 'S'\n    84: 159,  # 'T'\n    85: 160,  # 'U'\n    86: 161,  # 'V'\n    87: 162,  # 'W'\n    88: 163,  # 'X'\n    89: 164,  # 'Y'\n    90: 165,  # 'Z'\n    91: 253,  # '['\n    92: 253,  # '\\\\'\n    93: 253,  # ']'\n    94: 253,  # '^'\n    95: 253,  # '_'\n    96: 253,  # '`'\n    97: 71,  # 'a'\n    98: 172,  # 'b'\n    99: 66,  # 'c'\n    100: 173,  # 'd'\n    101: 65,  # 'e'\n    102: 174,  # 'f'\n    103: 76,  # 'g'\n    104: 175,  # 'h'\n    105: 64,  # 'i'\n    106: 176,  # 'j'\n    107: 177,  # 'k'\n    108: 77,  # 'l'\n    109: 72,  # 'm'\n    110: 178,  # 'n'\n    111: 69,  # 'o'\n    112: 67,  # 'p'\n    113: 179,  # 'q'\n    114: 78,  # 'r'\n    115: 73,  # 's'\n    116: 180,  # 't'\n    117: 181,  # 'u'\n    118: 79,  # 'v'\n    119: 182,  # 'w'\n    120: 183,  # 'x'\n    121: 184,  # 'y'\n    122: 185,  # 'z'\n    123: 253,  # '{'\n    124: 253,  # '|'\n    125: 253,  # '}'\n    126: 253,  # '~'\n    127: 253,  # '\\x7f'\n    128: 37,  # 'А'\n    129: 44,  # 'Б'\n    130: 33,  # 'В'\n    131: 46,  # 'Г'\n    132: 41,  # 'Д'\n    133: 48,  # 'Е'\n    134: 56,  # 'Ж'\n    135: 51,  # 'З'\n    136: 42,  # 'И'\n    137: 60,  # 'Й'\n    138: 36,  # 'К'\n    139: 49,  # 'Л'\n    140: 38,  # 'М'\n    141: 31,  # 'Н'\n    142: 34,  # 'О'\n    143: 35,  # 'П'\n    144: 45,  # 'Р'\n    145: 32,  # 'С'\n    146: 40,  # 'Т'\n    147: 52,  # 'У'\n    148: 53,  # 'Ф'\n    149: 55,  # 'Х'\n    150: 58,  # 'Ц'\n    151: 50,  # 'Ч'\n    152: 57,  # 'Ш'\n    153: 63,  # 'Щ'\n    154: 70,  # 'Ъ'\n    155: 62,  # 'Ы'\n    156: 61,  # 'Ь'\n    157: 47,  # 'Э'\n    158: 59,  # 'Ю'\n    159: 43,  # 'Я'\n    160: 3,  # 'а'\n    161: 21,  # 'б'\n    162: 10,  # 'в'\n    163: 19,  # 'г'\n    164: 13,  # 'д'\n    165: 2,  # 'е'\n    166: 24,  # 'ж'\n    167: 20,  # 'з'\n    168: 4,  # 'и'\n    169: 23,  # 'й'\n    170: 11,  # 'к'\n    171: 8,  # 'л'\n    172: 12,  # 'м'\n    173: 5,  # 'н'\n    174: 1,  # 'о'\n    175: 15,  # 'п'\n    176: 191,  # '░'\n    177: 192,  # '▒'\n    178: 193,  # '▓'\n    179: 194,  # '│'\n    180: 195,  # '┤'\n    181: 196,  # '╡'\n    182: 197,  # '╢'\n    183: 198,  # '╖'\n    184: 199,  # '╕'\n    185: 200,  # '╣'\n    186: 201,  # '║'\n    187: 202,  # '╗'\n    188: 203,  # '╝'\n    189: 204,  # '╜'\n    190: 205,  # '╛'\n    191: 206,  # '┐'\n    192: 207,  # '└'\n    193: 208,  # '┴'\n    194: 209,  # '┬'\n    195: 210,  # '├'\n    196: 211,  # '─'\n    197: 212,  # '┼'\n    198: 213,  # '╞'\n    199: 214,  # '╟'\n    200: 215,  # '╚'\n    201: 216,  # '╔'\n    202: 217,  # '╩'\n    203: 218,  # '╦'\n    204: 219,  # '╠'\n    205: 220,  # '═'\n    206: 221,  # '╬'\n    207: 222,  # '╧'\n    208: 223,  # '╨'\n    209: 224,  # '╤'\n    210: 225,  # '╥'\n    211: 226,  # '╙'\n    212: 227,  # '╘'\n    213: 228,  # '╒'\n    214: 229,  # '╓'\n    215: 230,  # '╫'\n    216: 231,  # '╪'\n    217: 232,  # '┘'\n    218: 233,  # '┌'\n    219: 234,  # '█'\n    220: 235,  # '▄'\n    221: 236,  # '▌'\n    222: 237,  # '▐'\n    223: 238,  # '▀'\n    224: 9,  # 'р'\n    225: 7,  # 'с'\n    226: 6,  # 'т'\n    227: 14,  # 'у'\n    228: 39,  # 'ф'\n    229: 26,  # 'х'\n    230: 28,  # 'ц'\n    231: 22,  # 'ч'\n    232: 25,  # 'ш'\n    233: 29,  # 'щ'\n    234: 54,  # 'ъ'\n    235: 18,  # 'ы'\n    236: 17,  # 'ь'\n    237: 30,  # 'э'\n    238: 27,  # 'ю'\n    239: 16,  # 'я'\n    240: 239,  # 'Ё'\n    241: 68,  # 'ё'\n    242: 240,  # 'Є'\n    243: 241,  # 'є'\n    244: 242,  # 'Ї'\n    245: 243,  # 'ї'\n    246: 244,  # 'Ў'\n    247: 245,  # 'ў'\n    248: 246,  # '°'\n    249: 247,  # '∙'\n    250: 248,  # '·'\n    251: 249,  # '√'\n    252: 250,  # '№'\n    253: 251,  # '¤'\n    254: 252,  # '■'\n    255: 255,  # '\\xa0'\n}\n\nIBM866_RUSSIAN_MODEL = SingleByteCharSetModel(\n    charset_name=\"IBM866\",\n    language=\"Russian\",\n    char_to_order_map=IBM866_RUSSIAN_CHAR_TO_ORDER,\n    language_model=RUSSIAN_LANG_MODEL,\n    typical_positive_ratio=0.976601,\n    keep_ascii_letters=False,\n    alphabet=\"ЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяё\",\n)\n\nWINDOWS_1251_RUSSIAN_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 254,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 254,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 253,  # ' '\n    33: 253,  # '!'\n    34: 253,  # '\"'\n    35: 253,  # '#'\n    36: 253,  # '$'\n    37: 253,  # '%'\n    38: 253,  # '&'\n    39: 253,  # \"'\"\n    40: 253,  # '('\n    41: 253,  # ')'\n    42: 253,  # '*'\n    43: 253,  # '+'\n    44: 253,  # ','\n    45: 253,  # '-'\n    46: 253,  # '.'\n    47: 253,  # '/'\n    48: 252,  # '0'\n    49: 252,  # '1'\n    50: 252,  # '2'\n    51: 252,  # '3'\n    52: 252,  # '4'\n    53: 252,  # '5'\n    54: 252,  # '6'\n    55: 252,  # '7'\n    56: 252,  # '8'\n    57: 252,  # '9'\n    58: 253,  # ':'\n    59: 253,  # ';'\n    60: 253,  # '<'\n    61: 253,  # '='\n    62: 253,  # '>'\n    63: 253,  # '?'\n    64: 253,  # '@'\n    65: 142,  # 'A'\n    66: 143,  # 'B'\n    67: 144,  # 'C'\n    68: 145,  # 'D'\n    69: 146,  # 'E'\n    70: 147,  # 'F'\n    71: 148,  # 'G'\n    72: 149,  # 'H'\n    73: 150,  # 'I'\n    74: 151,  # 'J'\n    75: 152,  # 'K'\n    76: 74,  # 'L'\n    77: 153,  # 'M'\n    78: 75,  # 'N'\n    79: 154,  # 'O'\n    80: 155,  # 'P'\n    81: 156,  # 'Q'\n    82: 157,  # 'R'\n    83: 158,  # 'S'\n    84: 159,  # 'T'\n    85: 160,  # 'U'\n    86: 161,  # 'V'\n    87: 162,  # 'W'\n    88: 163,  # 'X'\n    89: 164,  # 'Y'\n    90: 165,  # 'Z'\n    91: 253,  # '['\n    92: 253,  # '\\\\'\n    93: 253,  # ']'\n    94: 253,  # '^'\n    95: 253,  # '_'\n    96: 253,  # '`'\n    97: 71,  # 'a'\n    98: 172,  # 'b'\n    99: 66,  # 'c'\n    100: 173,  # 'd'\n    101: 65,  # 'e'\n    102: 174,  # 'f'\n    103: 76,  # 'g'\n    104: 175,  # 'h'\n    105: 64,  # 'i'\n    106: 176,  # 'j'\n    107: 177,  # 'k'\n    108: 77,  # 'l'\n    109: 72,  # 'm'\n    110: 178,  # 'n'\n    111: 69,  # 'o'\n    112: 67,  # 'p'\n    113: 179,  # 'q'\n    114: 78,  # 'r'\n    115: 73,  # 's'\n    116: 180,  # 't'\n    117: 181,  # 'u'\n    118: 79,  # 'v'\n    119: 182,  # 'w'\n    120: 183,  # 'x'\n    121: 184,  # 'y'\n    122: 185,  # 'z'\n    123: 253,  # '{'\n    124: 253,  # '|'\n    125: 253,  # '}'\n    126: 253,  # '~'\n    127: 253,  # '\\x7f'\n    128: 191,  # 'Ђ'\n    129: 192,  # 'Ѓ'\n    130: 193,  # '‚'\n    131: 194,  # 'ѓ'\n    132: 195,  # '„'\n    133: 196,  # '…'\n    134: 197,  # '†'\n    135: 198,  # '‡'\n    136: 199,  # '€'\n    137: 200,  # '‰'\n    138: 201,  # 'Љ'\n    139: 202,  # '‹'\n    140: 203,  # 'Њ'\n    141: 204,  # 'Ќ'\n    142: 205,  # 'Ћ'\n    143: 206,  # 'Џ'\n    144: 207,  # 'ђ'\n    145: 208,  # '‘'\n    146: 209,  # '’'\n    147: 210,  # '“'\n    148: 211,  # '”'\n    149: 212,  # '•'\n    150: 213,  # '–'\n    151: 214,  # '—'\n    152: 215,  # None\n    153: 216,  # '™'\n    154: 217,  # 'љ'\n    155: 218,  # '›'\n    156: 219,  # 'њ'\n    157: 220,  # 'ќ'\n    158: 221,  # 'ћ'\n    159: 222,  # 'џ'\n    160: 223,  # '\\xa0'\n    161: 224,  # 'Ў'\n    162: 225,  # 'ў'\n    163: 226,  # 'Ј'\n    164: 227,  # '¤'\n    165: 228,  # 'Ґ'\n    166: 229,  # '¦'\n    167: 230,  # '§'\n    168: 231,  # 'Ё'\n    169: 232,  # '©'\n    170: 233,  # 'Є'\n    171: 234,  # '«'\n    172: 235,  # '¬'\n    173: 236,  # '\\xad'\n    174: 237,  # '®'\n    175: 238,  # 'Ї'\n    176: 239,  # '°'\n    177: 240,  # '±'\n    178: 241,  # 'І'\n    179: 242,  # 'і'\n    180: 243,  # 'ґ'\n    181: 244,  # 'µ'\n    182: 245,  # '¶'\n    183: 246,  # '·'\n    184: 68,  # 'ё'\n    185: 247,  # '№'\n    186: 248,  # 'є'\n    187: 249,  # '»'\n    188: 250,  # 'ј'\n    189: 251,  # 'Ѕ'\n    190: 252,  # 'ѕ'\n    191: 253,  # 'ї'\n    192: 37,  # 'А'\n    193: 44,  # 'Б'\n    194: 33,  # 'В'\n    195: 46,  # 'Г'\n    196: 41,  # 'Д'\n    197: 48,  # 'Е'\n    198: 56,  # 'Ж'\n    199: 51,  # 'З'\n    200: 42,  # 'И'\n    201: 60,  # 'Й'\n    202: 36,  # 'К'\n    203: 49,  # 'Л'\n    204: 38,  # 'М'\n    205: 31,  # 'Н'\n    206: 34,  # 'О'\n    207: 35,  # 'П'\n    208: 45,  # 'Р'\n    209: 32,  # 'С'\n    210: 40,  # 'Т'\n    211: 52,  # 'У'\n    212: 53,  # 'Ф'\n    213: 55,  # 'Х'\n    214: 58,  # 'Ц'\n    215: 50,  # 'Ч'\n    216: 57,  # 'Ш'\n    217: 63,  # 'Щ'\n    218: 70,  # 'Ъ'\n    219: 62,  # 'Ы'\n    220: 61,  # 'Ь'\n    221: 47,  # 'Э'\n    222: 59,  # 'Ю'\n    223: 43,  # 'Я'\n    224: 3,  # 'а'\n    225: 21,  # 'б'\n    226: 10,  # 'в'\n    227: 19,  # 'г'\n    228: 13,  # 'д'\n    229: 2,  # 'е'\n    230: 24,  # 'ж'\n    231: 20,  # 'з'\n    232: 4,  # 'и'\n    233: 23,  # 'й'\n    234: 11,  # 'к'\n    235: 8,  # 'л'\n    236: 12,  # 'м'\n    237: 5,  # 'н'\n    238: 1,  # 'о'\n    239: 15,  # 'п'\n    240: 9,  # 'р'\n    241: 7,  # 'с'\n    242: 6,  # 'т'\n    243: 14,  # 'у'\n    244: 39,  # 'ф'\n    245: 26,  # 'х'\n    246: 28,  # 'ц'\n    247: 22,  # 'ч'\n    248: 25,  # 'ш'\n    249: 29,  # 'щ'\n    250: 54,  # 'ъ'\n    251: 18,  # 'ы'\n    252: 17,  # 'ь'\n    253: 30,  # 'э'\n    254: 27,  # 'ю'\n    255: 16,  # 'я'\n}\n\nWINDOWS_1251_RUSSIAN_MODEL = SingleByteCharSetModel(\n    charset_name=\"windows-1251\",\n    language=\"Russian\",\n    char_to_order_map=WINDOWS_1251_RUSSIAN_CHAR_TO_ORDER,\n    language_model=RUSSIAN_LANG_MODEL,\n    typical_positive_ratio=0.976601,\n    keep_ascii_letters=False,\n    alphabet=\"ЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяё\",\n)\n\nIBM855_RUSSIAN_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 254,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 254,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 253,  # ' '\n    33: 253,  # '!'\n    34: 253,  # '\"'\n    35: 253,  # '#'\n    36: 253,  # '$'\n    37: 253,  # '%'\n    38: 253,  # '&'\n    39: 253,  # \"'\"\n    40: 253,  # '('\n    41: 253,  # ')'\n    42: 253,  # '*'\n    43: 253,  # '+'\n    44: 253,  # ','\n    45: 253,  # '-'\n    46: 253,  # '.'\n    47: 253,  # '/'\n    48: 252,  # '0'\n    49: 252,  # '1'\n    50: 252,  # '2'\n    51: 252,  # '3'\n    52: 252,  # '4'\n    53: 252,  # '5'\n    54: 252,  # '6'\n    55: 252,  # '7'\n    56: 252,  # '8'\n    57: 252,  # '9'\n    58: 253,  # ':'\n    59: 253,  # ';'\n    60: 253,  # '<'\n    61: 253,  # '='\n    62: 253,  # '>'\n    63: 253,  # '?'\n    64: 253,  # '@'\n    65: 142,  # 'A'\n    66: 143,  # 'B'\n    67: 144,  # 'C'\n    68: 145,  # 'D'\n    69: 146,  # 'E'\n    70: 147,  # 'F'\n    71: 148,  # 'G'\n    72: 149,  # 'H'\n    73: 150,  # 'I'\n    74: 151,  # 'J'\n    75: 152,  # 'K'\n    76: 74,  # 'L'\n    77: 153,  # 'M'\n    78: 75,  # 'N'\n    79: 154,  # 'O'\n    80: 155,  # 'P'\n    81: 156,  # 'Q'\n    82: 157,  # 'R'\n    83: 158,  # 'S'\n    84: 159,  # 'T'\n    85: 160,  # 'U'\n    86: 161,  # 'V'\n    87: 162,  # 'W'\n    88: 163,  # 'X'\n    89: 164,  # 'Y'\n    90: 165,  # 'Z'\n    91: 253,  # '['\n    92: 253,  # '\\\\'\n    93: 253,  # ']'\n    94: 253,  # '^'\n    95: 253,  # '_'\n    96: 253,  # '`'\n    97: 71,  # 'a'\n    98: 172,  # 'b'\n    99: 66,  # 'c'\n    100: 173,  # 'd'\n    101: 65,  # 'e'\n    102: 174,  # 'f'\n    103: 76,  # 'g'\n    104: 175,  # 'h'\n    105: 64,  # 'i'\n    106: 176,  # 'j'\n    107: 177,  # 'k'\n    108: 77,  # 'l'\n    109: 72,  # 'm'\n    110: 178,  # 'n'\n    111: 69,  # 'o'\n    112: 67,  # 'p'\n    113: 179,  # 'q'\n    114: 78,  # 'r'\n    115: 73,  # 's'\n    116: 180,  # 't'\n    117: 181,  # 'u'\n    118: 79,  # 'v'\n    119: 182,  # 'w'\n    120: 183,  # 'x'\n    121: 184,  # 'y'\n    122: 185,  # 'z'\n    123: 253,  # '{'\n    124: 253,  # '|'\n    125: 253,  # '}'\n    126: 253,  # '~'\n    127: 253,  # '\\x7f'\n    128: 191,  # 'ђ'\n    129: 192,  # 'Ђ'\n    130: 193,  # 'ѓ'\n    131: 194,  # 'Ѓ'\n    132: 68,  # 'ё'\n    133: 195,  # 'Ё'\n    134: 196,  # 'є'\n    135: 197,  # 'Є'\n    136: 198,  # 'ѕ'\n    137: 199,  # 'Ѕ'\n    138: 200,  # 'і'\n    139: 201,  # 'І'\n    140: 202,  # 'ї'\n    141: 203,  # 'Ї'\n    142: 204,  # 'ј'\n    143: 205,  # 'Ј'\n    144: 206,  # 'љ'\n    145: 207,  # 'Љ'\n    146: 208,  # 'њ'\n    147: 209,  # 'Њ'\n    148: 210,  # 'ћ'\n    149: 211,  # 'Ћ'\n    150: 212,  # 'ќ'\n    151: 213,  # 'Ќ'\n    152: 214,  # 'ў'\n    153: 215,  # 'Ў'\n    154: 216,  # 'џ'\n    155: 217,  # 'Џ'\n    156: 27,  # 'ю'\n    157: 59,  # 'Ю'\n    158: 54,  # 'ъ'\n    159: 70,  # 'Ъ'\n    160: 3,  # 'а'\n    161: 37,  # 'А'\n    162: 21,  # 'б'\n    163: 44,  # 'Б'\n    164: 28,  # 'ц'\n    165: 58,  # 'Ц'\n    166: 13,  # 'д'\n    167: 41,  # 'Д'\n    168: 2,  # 'е'\n    169: 48,  # 'Е'\n    170: 39,  # 'ф'\n    171: 53,  # 'Ф'\n    172: 19,  # 'г'\n    173: 46,  # 'Г'\n    174: 218,  # '«'\n    175: 219,  # '»'\n    176: 220,  # '░'\n    177: 221,  # '▒'\n    178: 222,  # '▓'\n    179: 223,  # '│'\n    180: 224,  # '┤'\n    181: 26,  # 'х'\n    182: 55,  # 'Х'\n    183: 4,  # 'и'\n    184: 42,  # 'И'\n    185: 225,  # '╣'\n    186: 226,  # '║'\n    187: 227,  # '╗'\n    188: 228,  # '╝'\n    189: 23,  # 'й'\n    190: 60,  # 'Й'\n    191: 229,  # '┐'\n    192: 230,  # '└'\n    193: 231,  # '┴'\n    194: 232,  # '┬'\n    195: 233,  # '├'\n    196: 234,  # '─'\n    197: 235,  # '┼'\n    198: 11,  # 'к'\n    199: 36,  # 'К'\n    200: 236,  # '╚'\n    201: 237,  # '╔'\n    202: 238,  # '╩'\n    203: 239,  # '╦'\n    204: 240,  # '╠'\n    205: 241,  # '═'\n    206: 242,  # '╬'\n    207: 243,  # '¤'\n    208: 8,  # 'л'\n    209: 49,  # 'Л'\n    210: 12,  # 'м'\n    211: 38,  # 'М'\n    212: 5,  # 'н'\n    213: 31,  # 'Н'\n    214: 1,  # 'о'\n    215: 34,  # 'О'\n    216: 15,  # 'п'\n    217: 244,  # '┘'\n    218: 245,  # '┌'\n    219: 246,  # '█'\n    220: 247,  # '▄'\n    221: 35,  # 'П'\n    222: 16,  # 'я'\n    223: 248,  # '▀'\n    224: 43,  # 'Я'\n    225: 9,  # 'р'\n    226: 45,  # 'Р'\n    227: 7,  # 'с'\n    228: 32,  # 'С'\n    229: 6,  # 'т'\n    230: 40,  # 'Т'\n    231: 14,  # 'у'\n    232: 52,  # 'У'\n    233: 24,  # 'ж'\n    234: 56,  # 'Ж'\n    235: 10,  # 'в'\n    236: 33,  # 'В'\n    237: 17,  # 'ь'\n    238: 61,  # 'Ь'\n    239: 249,  # '№'\n    240: 250,  # '\\xad'\n    241: 18,  # 'ы'\n    242: 62,  # 'Ы'\n    243: 20,  # 'з'\n    244: 51,  # 'З'\n    245: 25,  # 'ш'\n    246: 57,  # 'Ш'\n    247: 30,  # 'э'\n    248: 47,  # 'Э'\n    249: 29,  # 'щ'\n    250: 63,  # 'Щ'\n    251: 22,  # 'ч'\n    252: 50,  # 'Ч'\n    253: 251,  # '§'\n    254: 252,  # '■'\n    255: 255,  # '\\xa0'\n}\n\nIBM855_RUSSIAN_MODEL = SingleByteCharSetModel(\n    charset_name=\"IBM855\",\n    language=\"Russian\",\n    char_to_order_map=IBM855_RUSSIAN_CHAR_TO_ORDER,\n    language_model=RUSSIAN_LANG_MODEL,\n    typical_positive_ratio=0.976601,\n    keep_ascii_letters=False,\n    alphabet=\"ЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяё\",\n)\n\nKOI8_R_RUSSIAN_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 254,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 254,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 253,  # ' '\n    33: 253,  # '!'\n    34: 253,  # '\"'\n    35: 253,  # '#'\n    36: 253,  # '$'\n    37: 253,  # '%'\n    38: 253,  # '&'\n    39: 253,  # \"'\"\n    40: 253,  # '('\n    41: 253,  # ')'\n    42: 253,  # '*'\n    43: 253,  # '+'\n    44: 253,  # ','\n    45: 253,  # '-'\n    46: 253,  # '.'\n    47: 253,  # '/'\n    48: 252,  # '0'\n    49: 252,  # '1'\n    50: 252,  # '2'\n    51: 252,  # '3'\n    52: 252,  # '4'\n    53: 252,  # '5'\n    54: 252,  # '6'\n    55: 252,  # '7'\n    56: 252,  # '8'\n    57: 252,  # '9'\n    58: 253,  # ':'\n    59: 253,  # ';'\n    60: 253,  # '<'\n    61: 253,  # '='\n    62: 253,  # '>'\n    63: 253,  # '?'\n    64: 253,  # '@'\n    65: 142,  # 'A'\n    66: 143,  # 'B'\n    67: 144,  # 'C'\n    68: 145,  # 'D'\n    69: 146,  # 'E'\n    70: 147,  # 'F'\n    71: 148,  # 'G'\n    72: 149,  # 'H'\n    73: 150,  # 'I'\n    74: 151,  # 'J'\n    75: 152,  # 'K'\n    76: 74,  # 'L'\n    77: 153,  # 'M'\n    78: 75,  # 'N'\n    79: 154,  # 'O'\n    80: 155,  # 'P'\n    81: 156,  # 'Q'\n    82: 157,  # 'R'\n    83: 158,  # 'S'\n    84: 159,  # 'T'\n    85: 160,  # 'U'\n    86: 161,  # 'V'\n    87: 162,  # 'W'\n    88: 163,  # 'X'\n    89: 164,  # 'Y'\n    90: 165,  # 'Z'\n    91: 253,  # '['\n    92: 253,  # '\\\\'\n    93: 253,  # ']'\n    94: 253,  # '^'\n    95: 253,  # '_'\n    96: 253,  # '`'\n    97: 71,  # 'a'\n    98: 172,  # 'b'\n    99: 66,  # 'c'\n    100: 173,  # 'd'\n    101: 65,  # 'e'\n    102: 174,  # 'f'\n    103: 76,  # 'g'\n    104: 175,  # 'h'\n    105: 64,  # 'i'\n    106: 176,  # 'j'\n    107: 177,  # 'k'\n    108: 77,  # 'l'\n    109: 72,  # 'm'\n    110: 178,  # 'n'\n    111: 69,  # 'o'\n    112: 67,  # 'p'\n    113: 179,  # 'q'\n    114: 78,  # 'r'\n    115: 73,  # 's'\n    116: 180,  # 't'\n    117: 181,  # 'u'\n    118: 79,  # 'v'\n    119: 182,  # 'w'\n    120: 183,  # 'x'\n    121: 184,  # 'y'\n    122: 185,  # 'z'\n    123: 253,  # '{'\n    124: 253,  # '|'\n    125: 253,  # '}'\n    126: 253,  # '~'\n    127: 253,  # '\\x7f'\n    128: 191,  # '─'\n    129: 192,  # '│'\n    130: 193,  # '┌'\n    131: 194,  # '┐'\n    132: 195,  # '└'\n    133: 196,  # '┘'\n    134: 197,  # '├'\n    135: 198,  # '┤'\n    136: 199,  # '┬'\n    137: 200,  # '┴'\n    138: 201,  # '┼'\n    139: 202,  # '▀'\n    140: 203,  # '▄'\n    141: 204,  # '█'\n    142: 205,  # '▌'\n    143: 206,  # '▐'\n    144: 207,  # '░'\n    145: 208,  # '▒'\n    146: 209,  # '▓'\n    147: 210,  # '⌠'\n    148: 211,  # '■'\n    149: 212,  # '∙'\n    150: 213,  # '√'\n    151: 214,  # '≈'\n    152: 215,  # '≤'\n    153: 216,  # '≥'\n    154: 217,  # '\\xa0'\n    155: 218,  # '⌡'\n    156: 219,  # '°'\n    157: 220,  # '²'\n    158: 221,  # '·'\n    159: 222,  # '÷'\n    160: 223,  # '═'\n    161: 224,  # '║'\n    162: 225,  # '╒'\n    163: 68,  # 'ё'\n    164: 226,  # '╓'\n    165: 227,  # '╔'\n    166: 228,  # '╕'\n    167: 229,  # '╖'\n    168: 230,  # '╗'\n    169: 231,  # '╘'\n    170: 232,  # '╙'\n    171: 233,  # '╚'\n    172: 234,  # '╛'\n    173: 235,  # '╜'\n    174: 236,  # '╝'\n    175: 237,  # '╞'\n    176: 238,  # '╟'\n    177: 239,  # '╠'\n    178: 240,  # '╡'\n    179: 241,  # 'Ё'\n    180: 242,  # '╢'\n    181: 243,  # '╣'\n    182: 244,  # '╤'\n    183: 245,  # '╥'\n    184: 246,  # '╦'\n    185: 247,  # '╧'\n    186: 248,  # '╨'\n    187: 249,  # '╩'\n    188: 250,  # '╪'\n    189: 251,  # '╫'\n    190: 252,  # '╬'\n    191: 253,  # '©'\n    192: 27,  # 'ю'\n    193: 3,  # 'а'\n    194: 21,  # 'б'\n    195: 28,  # 'ц'\n    196: 13,  # 'д'\n    197: 2,  # 'е'\n    198: 39,  # 'ф'\n    199: 19,  # 'г'\n    200: 26,  # 'х'\n    201: 4,  # 'и'\n    202: 23,  # 'й'\n    203: 11,  # 'к'\n    204: 8,  # 'л'\n    205: 12,  # 'м'\n    206: 5,  # 'н'\n    207: 1,  # 'о'\n    208: 15,  # 'п'\n    209: 16,  # 'я'\n    210: 9,  # 'р'\n    211: 7,  # 'с'\n    212: 6,  # 'т'\n    213: 14,  # 'у'\n    214: 24,  # 'ж'\n    215: 10,  # 'в'\n    216: 17,  # 'ь'\n    217: 18,  # 'ы'\n    218: 20,  # 'з'\n    219: 25,  # 'ш'\n    220: 30,  # 'э'\n    221: 29,  # 'щ'\n    222: 22,  # 'ч'\n    223: 54,  # 'ъ'\n    224: 59,  # 'Ю'\n    225: 37,  # 'А'\n    226: 44,  # 'Б'\n    227: 58,  # 'Ц'\n    228: 41,  # 'Д'\n    229: 48,  # 'Е'\n    230: 53,  # 'Ф'\n    231: 46,  # 'Г'\n    232: 55,  # 'Х'\n    233: 42,  # 'И'\n    234: 60,  # 'Й'\n    235: 36,  # 'К'\n    236: 49,  # 'Л'\n    237: 38,  # 'М'\n    238: 31,  # 'Н'\n    239: 34,  # 'О'\n    240: 35,  # 'П'\n    241: 43,  # 'Я'\n    242: 45,  # 'Р'\n    243: 32,  # 'С'\n    244: 40,  # 'Т'\n    245: 52,  # 'У'\n    246: 56,  # 'Ж'\n    247: 33,  # 'В'\n    248: 61,  # 'Ь'\n    249: 62,  # 'Ы'\n    250: 51,  # 'З'\n    251: 57,  # 'Ш'\n    252: 47,  # 'Э'\n    253: 63,  # 'Щ'\n    254: 50,  # 'Ч'\n    255: 70,  # 'Ъ'\n}\n\nKOI8_R_RUSSIAN_MODEL = SingleByteCharSetModel(\n    charset_name=\"KOI8-R\",\n    language=\"Russian\",\n    char_to_order_map=KOI8_R_RUSSIAN_CHAR_TO_ORDER,\n    language_model=RUSSIAN_LANG_MODEL,\n    typical_positive_ratio=0.976601,\n    keep_ascii_letters=False,\n    alphabet=\"ЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяё\",\n)\n\nMACCYRILLIC_RUSSIAN_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 254,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 254,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 253,  # ' '\n    33: 253,  # '!'\n    34: 253,  # '\"'\n    35: 253,  # '#'\n    36: 253,  # '$'\n    37: 253,  # '%'\n    38: 253,  # '&'\n    39: 253,  # \"'\"\n    40: 253,  # '('\n    41: 253,  # ')'\n    42: 253,  # '*'\n    43: 253,  # '+'\n    44: 253,  # ','\n    45: 253,  # '-'\n    46: 253,  # '.'\n    47: 253,  # '/'\n    48: 252,  # '0'\n    49: 252,  # '1'\n    50: 252,  # '2'\n    51: 252,  # '3'\n    52: 252,  # '4'\n    53: 252,  # '5'\n    54: 252,  # '6'\n    55: 252,  # '7'\n    56: 252,  # '8'\n    57: 252,  # '9'\n    58: 253,  # ':'\n    59: 253,  # ';'\n    60: 253,  # '<'\n    61: 253,  # '='\n    62: 253,  # '>'\n    63: 253,  # '?'\n    64: 253,  # '@'\n    65: 142,  # 'A'\n    66: 143,  # 'B'\n    67: 144,  # 'C'\n    68: 145,  # 'D'\n    69: 146,  # 'E'\n    70: 147,  # 'F'\n    71: 148,  # 'G'\n    72: 149,  # 'H'\n    73: 150,  # 'I'\n    74: 151,  # 'J'\n    75: 152,  # 'K'\n    76: 74,  # 'L'\n    77: 153,  # 'M'\n    78: 75,  # 'N'\n    79: 154,  # 'O'\n    80: 155,  # 'P'\n    81: 156,  # 'Q'\n    82: 157,  # 'R'\n    83: 158,  # 'S'\n    84: 159,  # 'T'\n    85: 160,  # 'U'\n    86: 161,  # 'V'\n    87: 162,  # 'W'\n    88: 163,  # 'X'\n    89: 164,  # 'Y'\n    90: 165,  # 'Z'\n    91: 253,  # '['\n    92: 253,  # '\\\\'\n    93: 253,  # ']'\n    94: 253,  # '^'\n    95: 253,  # '_'\n    96: 253,  # '`'\n    97: 71,  # 'a'\n    98: 172,  # 'b'\n    99: 66,  # 'c'\n    100: 173,  # 'd'\n    101: 65,  # 'e'\n    102: 174,  # 'f'\n    103: 76,  # 'g'\n    104: 175,  # 'h'\n    105: 64,  # 'i'\n    106: 176,  # 'j'\n    107: 177,  # 'k'\n    108: 77,  # 'l'\n    109: 72,  # 'm'\n    110: 178,  # 'n'\n    111: 69,  # 'o'\n    112: 67,  # 'p'\n    113: 179,  # 'q'\n    114: 78,  # 'r'\n    115: 73,  # 's'\n    116: 180,  # 't'\n    117: 181,  # 'u'\n    118: 79,  # 'v'\n    119: 182,  # 'w'\n    120: 183,  # 'x'\n    121: 184,  # 'y'\n    122: 185,  # 'z'\n    123: 253,  # '{'\n    124: 253,  # '|'\n    125: 253,  # '}'\n    126: 253,  # '~'\n    127: 253,  # '\\x7f'\n    128: 37,  # 'А'\n    129: 44,  # 'Б'\n    130: 33,  # 'В'\n    131: 46,  # 'Г'\n    132: 41,  # 'Д'\n    133: 48,  # 'Е'\n    134: 56,  # 'Ж'\n    135: 51,  # 'З'\n    136: 42,  # 'И'\n    137: 60,  # 'Й'\n    138: 36,  # 'К'\n    139: 49,  # 'Л'\n    140: 38,  # 'М'\n    141: 31,  # 'Н'\n    142: 34,  # 'О'\n    143: 35,  # 'П'\n    144: 45,  # 'Р'\n    145: 32,  # 'С'\n    146: 40,  # 'Т'\n    147: 52,  # 'У'\n    148: 53,  # 'Ф'\n    149: 55,  # 'Х'\n    150: 58,  # 'Ц'\n    151: 50,  # 'Ч'\n    152: 57,  # 'Ш'\n    153: 63,  # 'Щ'\n    154: 70,  # 'Ъ'\n    155: 62,  # 'Ы'\n    156: 61,  # 'Ь'\n    157: 47,  # 'Э'\n    158: 59,  # 'Ю'\n    159: 43,  # 'Я'\n    160: 191,  # '†'\n    161: 192,  # '°'\n    162: 193,  # 'Ґ'\n    163: 194,  # '£'\n    164: 195,  # '§'\n    165: 196,  # '•'\n    166: 197,  # '¶'\n    167: 198,  # 'І'\n    168: 199,  # '®'\n    169: 200,  # '©'\n    170: 201,  # '™'\n    171: 202,  # 'Ђ'\n    172: 203,  # 'ђ'\n    173: 204,  # '≠'\n    174: 205,  # 'Ѓ'\n    175: 206,  # 'ѓ'\n    176: 207,  # '∞'\n    177: 208,  # '±'\n    178: 209,  # '≤'\n    179: 210,  # '≥'\n    180: 211,  # 'і'\n    181: 212,  # 'µ'\n    182: 213,  # 'ґ'\n    183: 214,  # 'Ј'\n    184: 215,  # 'Є'\n    185: 216,  # 'є'\n    186: 217,  # 'Ї'\n    187: 218,  # 'ї'\n    188: 219,  # 'Љ'\n    189: 220,  # 'љ'\n    190: 221,  # 'Њ'\n    191: 222,  # 'њ'\n    192: 223,  # 'ј'\n    193: 224,  # 'Ѕ'\n    194: 225,  # '¬'\n    195: 226,  # '√'\n    196: 227,  # 'ƒ'\n    197: 228,  # '≈'\n    198: 229,  # '∆'\n    199: 230,  # '«'\n    200: 231,  # '»'\n    201: 232,  # '…'\n    202: 233,  # '\\xa0'\n    203: 234,  # 'Ћ'\n    204: 235,  # 'ћ'\n    205: 236,  # 'Ќ'\n    206: 237,  # 'ќ'\n    207: 238,  # 'ѕ'\n    208: 239,  # '–'\n    209: 240,  # '—'\n    210: 241,  # '“'\n    211: 242,  # '”'\n    212: 243,  # '‘'\n    213: 244,  # '’'\n    214: 245,  # '÷'\n    215: 246,  # '„'\n    216: 247,  # 'Ў'\n    217: 248,  # 'ў'\n    218: 249,  # 'Џ'\n    219: 250,  # 'џ'\n    220: 251,  # '№'\n    221: 252,  # 'Ё'\n    222: 68,  # 'ё'\n    223: 16,  # 'я'\n    224: 3,  # 'а'\n    225: 21,  # 'б'\n    226: 10,  # 'в'\n    227: 19,  # 'г'\n    228: 13,  # 'д'\n    229: 2,  # 'е'\n    230: 24,  # 'ж'\n    231: 20,  # 'з'\n    232: 4,  # 'и'\n    233: 23,  # 'й'\n    234: 11,  # 'к'\n    235: 8,  # 'л'\n    236: 12,  # 'м'\n    237: 5,  # 'н'\n    238: 1,  # 'о'\n    239: 15,  # 'п'\n    240: 9,  # 'р'\n    241: 7,  # 'с'\n    242: 6,  # 'т'\n    243: 14,  # 'у'\n    244: 39,  # 'ф'\n    245: 26,  # 'х'\n    246: 28,  # 'ц'\n    247: 22,  # 'ч'\n    248: 25,  # 'ш'\n    249: 29,  # 'щ'\n    250: 54,  # 'ъ'\n    251: 18,  # 'ы'\n    252: 17,  # 'ь'\n    253: 30,  # 'э'\n    254: 27,  # 'ю'\n    255: 255,  # '€'\n}\n\nMACCYRILLIC_RUSSIAN_MODEL = SingleByteCharSetModel(\n    charset_name=\"MacCyrillic\",\n    language=\"Russian\",\n    char_to_order_map=MACCYRILLIC_RUSSIAN_CHAR_TO_ORDER,\n    language_model=RUSSIAN_LANG_MODEL,\n    typical_positive_ratio=0.976601,\n    keep_ascii_letters=False,\n    alphabet=\"ЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяё\",\n)\n\nISO_8859_5_RUSSIAN_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 254,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 254,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 253,  # ' '\n    33: 253,  # '!'\n    34: 253,  # '\"'\n    35: 253,  # '#'\n    36: 253,  # '$'\n    37: 253,  # '%'\n    38: 253,  # '&'\n    39: 253,  # \"'\"\n    40: 253,  # '('\n    41: 253,  # ')'\n    42: 253,  # '*'\n    43: 253,  # '+'\n    44: 253,  # ','\n    45: 253,  # '-'\n    46: 253,  # '.'\n    47: 253,  # '/'\n    48: 252,  # '0'\n    49: 252,  # '1'\n    50: 252,  # '2'\n    51: 252,  # '3'\n    52: 252,  # '4'\n    53: 252,  # '5'\n    54: 252,  # '6'\n    55: 252,  # '7'\n    56: 252,  # '8'\n    57: 252,  # '9'\n    58: 253,  # ':'\n    59: 253,  # ';'\n    60: 253,  # '<'\n    61: 253,  # '='\n    62: 253,  # '>'\n    63: 253,  # '?'\n    64: 253,  # '@'\n    65: 142,  # 'A'\n    66: 143,  # 'B'\n    67: 144,  # 'C'\n    68: 145,  # 'D'\n    69: 146,  # 'E'\n    70: 147,  # 'F'\n    71: 148,  # 'G'\n    72: 149,  # 'H'\n    73: 150,  # 'I'\n    74: 151,  # 'J'\n    75: 152,  # 'K'\n    76: 74,  # 'L'\n    77: 153,  # 'M'\n    78: 75,  # 'N'\n    79: 154,  # 'O'\n    80: 155,  # 'P'\n    81: 156,  # 'Q'\n    82: 157,  # 'R'\n    83: 158,  # 'S'\n    84: 159,  # 'T'\n    85: 160,  # 'U'\n    86: 161,  # 'V'\n    87: 162,  # 'W'\n    88: 163,  # 'X'\n    89: 164,  # 'Y'\n    90: 165,  # 'Z'\n    91: 253,  # '['\n    92: 253,  # '\\\\'\n    93: 253,  # ']'\n    94: 253,  # '^'\n    95: 253,  # '_'\n    96: 253,  # '`'\n    97: 71,  # 'a'\n    98: 172,  # 'b'\n    99: 66,  # 'c'\n    100: 173,  # 'd'\n    101: 65,  # 'e'\n    102: 174,  # 'f'\n    103: 76,  # 'g'\n    104: 175,  # 'h'\n    105: 64,  # 'i'\n    106: 176,  # 'j'\n    107: 177,  # 'k'\n    108: 77,  # 'l'\n    109: 72,  # 'm'\n    110: 178,  # 'n'\n    111: 69,  # 'o'\n    112: 67,  # 'p'\n    113: 179,  # 'q'\n    114: 78,  # 'r'\n    115: 73,  # 's'\n    116: 180,  # 't'\n    117: 181,  # 'u'\n    118: 79,  # 'v'\n    119: 182,  # 'w'\n    120: 183,  # 'x'\n    121: 184,  # 'y'\n    122: 185,  # 'z'\n    123: 253,  # '{'\n    124: 253,  # '|'\n    125: 253,  # '}'\n    126: 253,  # '~'\n    127: 253,  # '\\x7f'\n    128: 191,  # '\\x80'\n    129: 192,  # '\\x81'\n    130: 193,  # '\\x82'\n    131: 194,  # '\\x83'\n    132: 195,  # '\\x84'\n    133: 196,  # '\\x85'\n    134: 197,  # '\\x86'\n    135: 198,  # '\\x87'\n    136: 199,  # '\\x88'\n    137: 200,  # '\\x89'\n    138: 201,  # '\\x8a'\n    139: 202,  # '\\x8b'\n    140: 203,  # '\\x8c'\n    141: 204,  # '\\x8d'\n    142: 205,  # '\\x8e'\n    143: 206,  # '\\x8f'\n    144: 207,  # '\\x90'\n    145: 208,  # '\\x91'\n    146: 209,  # '\\x92'\n    147: 210,  # '\\x93'\n    148: 211,  # '\\x94'\n    149: 212,  # '\\x95'\n    150: 213,  # '\\x96'\n    151: 214,  # '\\x97'\n    152: 215,  # '\\x98'\n    153: 216,  # '\\x99'\n    154: 217,  # '\\x9a'\n    155: 218,  # '\\x9b'\n    156: 219,  # '\\x9c'\n    157: 220,  # '\\x9d'\n    158: 221,  # '\\x9e'\n    159: 222,  # '\\x9f'\n    160: 223,  # '\\xa0'\n    161: 224,  # 'Ё'\n    162: 225,  # 'Ђ'\n    163: 226,  # 'Ѓ'\n    164: 227,  # 'Є'\n    165: 228,  # 'Ѕ'\n    166: 229,  # 'І'\n    167: 230,  # 'Ї'\n    168: 231,  # 'Ј'\n    169: 232,  # 'Љ'\n    170: 233,  # 'Њ'\n    171: 234,  # 'Ћ'\n    172: 235,  # 'Ќ'\n    173: 236,  # '\\xad'\n    174: 237,  # 'Ў'\n    175: 238,  # 'Џ'\n    176: 37,  # 'А'\n    177: 44,  # 'Б'\n    178: 33,  # 'В'\n    179: 46,  # 'Г'\n    180: 41,  # 'Д'\n    181: 48,  # 'Е'\n    182: 56,  # 'Ж'\n    183: 51,  # 'З'\n    184: 42,  # 'И'\n    185: 60,  # 'Й'\n    186: 36,  # 'К'\n    187: 49,  # 'Л'\n    188: 38,  # 'М'\n    189: 31,  # 'Н'\n    190: 34,  # 'О'\n    191: 35,  # 'П'\n    192: 45,  # 'Р'\n    193: 32,  # 'С'\n    194: 40,  # 'Т'\n    195: 52,  # 'У'\n    196: 53,  # 'Ф'\n    197: 55,  # 'Х'\n    198: 58,  # 'Ц'\n    199: 50,  # 'Ч'\n    200: 57,  # 'Ш'\n    201: 63,  # 'Щ'\n    202: 70,  # 'Ъ'\n    203: 62,  # 'Ы'\n    204: 61,  # 'Ь'\n    205: 47,  # 'Э'\n    206: 59,  # 'Ю'\n    207: 43,  # 'Я'\n    208: 3,  # 'а'\n    209: 21,  # 'б'\n    210: 10,  # 'в'\n    211: 19,  # 'г'\n    212: 13,  # 'д'\n    213: 2,  # 'е'\n    214: 24,  # 'ж'\n    215: 20,  # 'з'\n    216: 4,  # 'и'\n    217: 23,  # 'й'\n    218: 11,  # 'к'\n    219: 8,  # 'л'\n    220: 12,  # 'м'\n    221: 5,  # 'н'\n    222: 1,  # 'о'\n    223: 15,  # 'п'\n    224: 9,  # 'р'\n    225: 7,  # 'с'\n    226: 6,  # 'т'\n    227: 14,  # 'у'\n    228: 39,  # 'ф'\n    229: 26,  # 'х'\n    230: 28,  # 'ц'\n    231: 22,  # 'ч'\n    232: 25,  # 'ш'\n    233: 29,  # 'щ'\n    234: 54,  # 'ъ'\n    235: 18,  # 'ы'\n    236: 17,  # 'ь'\n    237: 30,  # 'э'\n    238: 27,  # 'ю'\n    239: 16,  # 'я'\n    240: 239,  # '№'\n    241: 68,  # 'ё'\n    242: 240,  # 'ђ'\n    243: 241,  # 'ѓ'\n    244: 242,  # 'є'\n    245: 243,  # 'ѕ'\n    246: 244,  # 'і'\n    247: 245,  # 'ї'\n    248: 246,  # 'ј'\n    249: 247,  # 'љ'\n    250: 248,  # 'њ'\n    251: 249,  # 'ћ'\n    252: 250,  # 'ќ'\n    253: 251,  # '§'\n    254: 252,  # 'ў'\n    255: 255,  # 'џ'\n}\n\nISO_8859_5_RUSSIAN_MODEL = SingleByteCharSetModel(\n    charset_name=\"ISO-8859-5\",\n    language=\"Russian\",\n    char_to_order_map=ISO_8859_5_RUSSIAN_CHAR_TO_ORDER,\n    language_model=RUSSIAN_LANG_MODEL,\n    typical_positive_ratio=0.976601,\n    keep_ascii_letters=False,\n    alphabet=\"ЁАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюяё\",\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/langthaimodel.py",
    "content": "from pip._vendor.chardet.sbcharsetprober import SingleByteCharSetModel\n\n# 3: Positive\n# 2: Likely\n# 1: Unlikely\n# 0: Negative\n\nTHAI_LANG_MODEL = {\n    5: {  # 'ก'\n        5: 2,  # 'ก'\n        30: 2,  # 'ข'\n        24: 2,  # 'ค'\n        8: 2,  # 'ง'\n        26: 2,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 1,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 3,  # 'ฎ'\n        57: 2,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 2,  # 'ณ'\n        20: 2,  # 'ด'\n        19: 3,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 2,  # 'น'\n        17: 1,  # 'บ'\n        25: 2,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 1,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 1,  # 'ย'\n        2: 3,  # 'ร'\n        61: 2,  # 'ฤ'\n        15: 3,  # 'ล'\n        12: 3,  # 'ว'\n        42: 2,  # 'ศ'\n        46: 3,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 2,  # 'ห'\n        4: 3,  # 'อ'\n        63: 1,  # 'ฯ'\n        22: 2,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 3,  # 'ำ'\n        23: 3,  # 'ิ'\n        13: 3,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 2,  # 'ื'\n        32: 2,  # 'ุ'\n        35: 1,  # 'ู'\n        11: 2,  # 'เ'\n        28: 2,  # 'แ'\n        41: 1,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 2,  # 'ไ'\n        50: 1,  # 'ๆ'\n        37: 3,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 2,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    30: {  # 'ข'\n        5: 1,  # 'ก'\n        30: 0,  # 'ข'\n        24: 1,  # 'ค'\n        8: 1,  # 'ง'\n        26: 1,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 2,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 2,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 2,  # 'น'\n        17: 1,  # 'บ'\n        25: 1,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 2,  # 'ย'\n        2: 1,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 2,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 1,  # 'ห'\n        4: 3,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 2,  # 'ี'\n        40: 3,  # 'ึ'\n        27: 1,  # 'ื'\n        32: 1,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 1,  # '็'\n        6: 2,  # '่'\n        7: 3,  # '้'\n        38: 1,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    24: {  # 'ค'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 2,  # 'ค'\n        8: 2,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 2,  # 'ณ'\n        20: 2,  # 'ด'\n        19: 2,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 0,  # 'บ'\n        25: 1,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 2,  # 'ย'\n        2: 3,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 3,  # 'ล'\n        12: 3,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 0,  # 'ห'\n        4: 2,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 2,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 2,  # 'า'\n        36: 3,  # 'ำ'\n        23: 3,  # 'ิ'\n        13: 2,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 3,  # 'ื'\n        32: 3,  # 'ุ'\n        35: 2,  # 'ู'\n        11: 1,  # 'เ'\n        28: 0,  # 'แ'\n        41: 3,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 1,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 3,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    8: {  # 'ง'\n        5: 3,  # 'ก'\n        30: 2,  # 'ข'\n        24: 3,  # 'ค'\n        8: 2,  # 'ง'\n        26: 2,  # 'จ'\n        52: 1,  # 'ฉ'\n        34: 2,  # 'ช'\n        51: 1,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 2,  # 'ด'\n        19: 2,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 3,  # 'ท'\n        48: 1,  # 'ธ'\n        3: 3,  # 'น'\n        17: 2,  # 'บ'\n        25: 2,  # 'ป'\n        39: 2,  # 'ผ'\n        62: 1,  # 'ฝ'\n        31: 2,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 1,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 2,  # 'ว'\n        42: 2,  # 'ศ'\n        46: 1,  # 'ษ'\n        18: 3,  # 'ส'\n        21: 3,  # 'ห'\n        4: 2,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 1,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 2,  # 'ิ'\n        13: 1,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 1,  # 'ื'\n        32: 1,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 3,  # 'เ'\n        28: 2,  # 'แ'\n        41: 1,  # 'โ'\n        29: 2,  # 'ใ'\n        33: 2,  # 'ไ'\n        50: 3,  # 'ๆ'\n        37: 0,  # '็'\n        6: 2,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    26: {  # 'จ'\n        5: 2,  # 'ก'\n        30: 1,  # 'ข'\n        24: 0,  # 'ค'\n        8: 2,  # 'ง'\n        26: 3,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 2,  # 'ด'\n        19: 1,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 1,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 1,  # 'ย'\n        2: 3,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 1,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 1,  # 'ห'\n        4: 2,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 3,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 3,  # 'ำ'\n        23: 2,  # 'ิ'\n        13: 1,  # 'ี'\n        40: 3,  # 'ึ'\n        27: 1,  # 'ื'\n        32: 3,  # 'ุ'\n        35: 2,  # 'ู'\n        11: 1,  # 'เ'\n        28: 1,  # 'แ'\n        41: 0,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 1,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 2,  # '่'\n        7: 2,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    52: {  # 'ฉ'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 3,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 3,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 1,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 1,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 1,  # 'ะ'\n        10: 1,  # 'ั'\n        1: 1,  # 'า'\n        36: 0,  # 'ำ'\n        23: 1,  # 'ิ'\n        13: 1,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 1,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    34: {  # 'ช'\n        5: 1,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 1,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 1,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 2,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 1,  # 'ย'\n        2: 1,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 1,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 2,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 2,  # 'ั'\n        1: 3,  # 'า'\n        36: 1,  # 'ำ'\n        23: 3,  # 'ิ'\n        13: 2,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 3,  # 'ื'\n        32: 3,  # 'ุ'\n        35: 1,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 1,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    51: {  # 'ซ'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 1,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 1,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 0,  # 'ห'\n        4: 2,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 1,  # 'ั'\n        1: 1,  # 'า'\n        36: 0,  # 'ำ'\n        23: 1,  # 'ิ'\n        13: 2,  # 'ี'\n        40: 3,  # 'ึ'\n        27: 2,  # 'ื'\n        32: 1,  # 'ุ'\n        35: 1,  # 'ู'\n        11: 1,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 1,  # '็'\n        6: 1,  # '่'\n        7: 2,  # '้'\n        38: 1,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    47: {  # 'ญ'\n        5: 1,  # 'ก'\n        30: 1,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 3,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 1,  # 'บ'\n        25: 1,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 1,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 2,  # 'ห'\n        4: 1,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 1,  # 'ะ'\n        10: 2,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 1,  # 'ิ'\n        13: 1,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 1,  # 'เ'\n        28: 1,  # 'แ'\n        41: 0,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 1,  # 'ๆ'\n        37: 0,  # '็'\n        6: 2,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    58: {  # 'ฎ'\n        5: 2,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 1,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 1,  # 'ิ'\n        13: 2,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    57: {  # 'ฏ'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 3,  # 'ิ'\n        13: 1,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    49: {  # 'ฐ'\n        5: 1,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 2,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 1,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 1,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 1,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    53: {  # 'ฑ'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 2,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 3,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    55: {  # 'ฒ'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 1,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    43: {  # 'ณ'\n        5: 1,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 3,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 3,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 1,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 1,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 1,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 3,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 1,  # 'ิ'\n        13: 2,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 1,  # 'เ'\n        28: 1,  # 'แ'\n        41: 0,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 1,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 3,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    20: {  # 'ด'\n        5: 2,  # 'ก'\n        30: 2,  # 'ข'\n        24: 2,  # 'ค'\n        8: 3,  # 'ง'\n        26: 2,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 1,  # 'ด'\n        19: 2,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 1,  # 'น'\n        17: 1,  # 'บ'\n        25: 1,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 3,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 2,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 2,  # 'ห'\n        4: 1,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 2,  # 'า'\n        36: 2,  # 'ำ'\n        23: 3,  # 'ิ'\n        13: 3,  # 'ี'\n        40: 1,  # 'ึ'\n        27: 2,  # 'ื'\n        32: 3,  # 'ุ'\n        35: 2,  # 'ู'\n        11: 2,  # 'เ'\n        28: 2,  # 'แ'\n        41: 1,  # 'โ'\n        29: 2,  # 'ใ'\n        33: 2,  # 'ไ'\n        50: 2,  # 'ๆ'\n        37: 2,  # '็'\n        6: 1,  # '่'\n        7: 3,  # '้'\n        38: 1,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    19: {  # 'ต'\n        5: 2,  # 'ก'\n        30: 1,  # 'ข'\n        24: 1,  # 'ค'\n        8: 0,  # 'ง'\n        26: 1,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 1,  # 'ด'\n        19: 1,  # 'ต'\n        44: 2,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 2,  # 'น'\n        17: 1,  # 'บ'\n        25: 1,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 2,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 1,  # 'ย'\n        2: 3,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 1,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 3,  # 'ส'\n        21: 0,  # 'ห'\n        4: 3,  # 'อ'\n        63: 1,  # 'ฯ'\n        22: 2,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 2,  # 'ำ'\n        23: 3,  # 'ิ'\n        13: 2,  # 'ี'\n        40: 1,  # 'ึ'\n        27: 1,  # 'ื'\n        32: 3,  # 'ุ'\n        35: 2,  # 'ู'\n        11: 1,  # 'เ'\n        28: 1,  # 'แ'\n        41: 1,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 1,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 2,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 2,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    44: {  # 'ถ'\n        5: 1,  # 'ก'\n        30: 0,  # 'ข'\n        24: 1,  # 'ค'\n        8: 0,  # 'ง'\n        26: 1,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 1,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 1,  # 'น'\n        17: 2,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 1,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 1,  # 'ล'\n        12: 1,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 0,  # 'ห'\n        4: 1,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 2,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 2,  # 'ิ'\n        13: 1,  # 'ี'\n        40: 3,  # 'ึ'\n        27: 2,  # 'ื'\n        32: 2,  # 'ุ'\n        35: 3,  # 'ู'\n        11: 1,  # 'เ'\n        28: 1,  # 'แ'\n        41: 0,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 1,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 2,  # '่'\n        7: 3,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    14: {  # 'ท'\n        5: 1,  # 'ก'\n        30: 1,  # 'ข'\n        24: 3,  # 'ค'\n        8: 1,  # 'ง'\n        26: 1,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 2,  # 'ด'\n        19: 1,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 3,  # 'ธ'\n        3: 3,  # 'น'\n        17: 2,  # 'บ'\n        25: 2,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 2,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 3,  # 'ย'\n        2: 3,  # 'ร'\n        61: 1,  # 'ฤ'\n        15: 1,  # 'ล'\n        12: 2,  # 'ว'\n        42: 3,  # 'ศ'\n        46: 1,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 0,  # 'ห'\n        4: 2,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 2,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 3,  # 'ำ'\n        23: 2,  # 'ิ'\n        13: 3,  # 'ี'\n        40: 2,  # 'ึ'\n        27: 1,  # 'ื'\n        32: 3,  # 'ุ'\n        35: 1,  # 'ู'\n        11: 0,  # 'เ'\n        28: 1,  # 'แ'\n        41: 0,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 1,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 2,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    48: {  # 'ธ'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 1,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 1,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 2,  # 'า'\n        36: 0,  # 'ำ'\n        23: 3,  # 'ิ'\n        13: 3,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 2,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 3,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    3: {  # 'น'\n        5: 3,  # 'ก'\n        30: 2,  # 'ข'\n        24: 3,  # 'ค'\n        8: 1,  # 'ง'\n        26: 2,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 1,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 1,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 3,  # 'ด'\n        19: 3,  # 'ต'\n        44: 2,  # 'ถ'\n        14: 3,  # 'ท'\n        48: 3,  # 'ธ'\n        3: 2,  # 'น'\n        17: 2,  # 'บ'\n        25: 2,  # 'ป'\n        39: 2,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 2,  # 'พ'\n        54: 1,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 2,  # 'ย'\n        2: 2,  # 'ร'\n        61: 1,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 3,  # 'ว'\n        42: 1,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 2,  # 'ห'\n        4: 3,  # 'อ'\n        63: 1,  # 'ฯ'\n        22: 2,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 3,  # 'ำ'\n        23: 3,  # 'ิ'\n        13: 3,  # 'ี'\n        40: 3,  # 'ึ'\n        27: 3,  # 'ื'\n        32: 3,  # 'ุ'\n        35: 2,  # 'ู'\n        11: 3,  # 'เ'\n        28: 2,  # 'แ'\n        41: 3,  # 'โ'\n        29: 3,  # 'ใ'\n        33: 3,  # 'ไ'\n        50: 2,  # 'ๆ'\n        37: 1,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 2,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    17: {  # 'บ'\n        5: 3,  # 'ก'\n        30: 2,  # 'ข'\n        24: 2,  # 'ค'\n        8: 1,  # 'ง'\n        26: 1,  # 'จ'\n        52: 1,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 1,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 1,  # 'ด'\n        19: 2,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 3,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 3,  # 'บ'\n        25: 2,  # 'ป'\n        39: 2,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 1,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 0,  # 'ย'\n        2: 3,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 3,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 2,  # 'ห'\n        4: 2,  # 'อ'\n        63: 1,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 2,  # 'ำ'\n        23: 2,  # 'ิ'\n        13: 2,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 2,  # 'ื'\n        32: 3,  # 'ุ'\n        35: 2,  # 'ู'\n        11: 2,  # 'เ'\n        28: 2,  # 'แ'\n        41: 1,  # 'โ'\n        29: 2,  # 'ใ'\n        33: 2,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 1,  # '็'\n        6: 2,  # '่'\n        7: 2,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    25: {  # 'ป'\n        5: 2,  # 'ก'\n        30: 0,  # 'ข'\n        24: 1,  # 'ค'\n        8: 0,  # 'ง'\n        26: 1,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 1,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 1,  # 'ฎ'\n        57: 3,  # 'ฏ'\n        49: 1,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 1,  # 'ด'\n        19: 1,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 2,  # 'น'\n        17: 0,  # 'บ'\n        25: 1,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 1,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 0,  # 'ย'\n        2: 3,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 3,  # 'ล'\n        12: 1,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 1,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 1,  # 'ห'\n        4: 2,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 1,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 1,  # 'า'\n        36: 0,  # 'ำ'\n        23: 2,  # 'ิ'\n        13: 3,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 1,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 1,  # 'เ'\n        28: 2,  # 'แ'\n        41: 0,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 2,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 3,  # '็'\n        6: 1,  # '่'\n        7: 2,  # '้'\n        38: 1,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    39: {  # 'ผ'\n        5: 1,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 1,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 2,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 2,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 3,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 1,  # 'ะ'\n        10: 1,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 2,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 1,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 3,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 3,  # '่'\n        7: 1,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    62: {  # 'ฝ'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 1,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 1,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 1,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 1,  # 'ี'\n        40: 2,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 2,  # '่'\n        7: 1,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    31: {  # 'พ'\n        5: 1,  # 'ก'\n        30: 1,  # 'ข'\n        24: 1,  # 'ค'\n        8: 1,  # 'ง'\n        26: 1,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 1,  # 'ณ'\n        20: 1,  # 'ด'\n        19: 1,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 1,  # 'ธ'\n        3: 3,  # 'น'\n        17: 2,  # 'บ'\n        25: 0,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 2,  # 'ย'\n        2: 3,  # 'ร'\n        61: 2,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 2,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 1,  # 'ห'\n        4: 2,  # 'อ'\n        63: 1,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 3,  # 'ิ'\n        13: 2,  # 'ี'\n        40: 1,  # 'ึ'\n        27: 3,  # 'ื'\n        32: 1,  # 'ุ'\n        35: 2,  # 'ู'\n        11: 1,  # 'เ'\n        28: 1,  # 'แ'\n        41: 0,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 1,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 1,  # '็'\n        6: 0,  # '่'\n        7: 1,  # '้'\n        38: 3,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    54: {  # 'ฟ'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 1,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 2,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 1,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 0,  # 'ห'\n        4: 1,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 2,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 1,  # 'ิ'\n        13: 1,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 1,  # 'ื'\n        32: 1,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 1,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 2,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    45: {  # 'ภ'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 1,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 3,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 1,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 1,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 2,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 1,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    9: {  # 'ม'\n        5: 2,  # 'ก'\n        30: 2,  # 'ข'\n        24: 2,  # 'ค'\n        8: 2,  # 'ง'\n        26: 2,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 1,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 1,  # 'ณ'\n        20: 2,  # 'ด'\n        19: 2,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 1,  # 'ธ'\n        3: 3,  # 'น'\n        17: 2,  # 'บ'\n        25: 2,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 3,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 1,  # 'ย'\n        2: 2,  # 'ร'\n        61: 2,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 2,  # 'ว'\n        42: 1,  # 'ศ'\n        46: 1,  # 'ษ'\n        18: 3,  # 'ส'\n        21: 3,  # 'ห'\n        4: 3,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 1,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 3,  # 'ิ'\n        13: 3,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 3,  # 'ื'\n        32: 3,  # 'ุ'\n        35: 3,  # 'ู'\n        11: 2,  # 'เ'\n        28: 2,  # 'แ'\n        41: 2,  # 'โ'\n        29: 2,  # 'ใ'\n        33: 2,  # 'ไ'\n        50: 1,  # 'ๆ'\n        37: 1,  # '็'\n        6: 3,  # '่'\n        7: 2,  # '้'\n        38: 1,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    16: {  # 'ย'\n        5: 3,  # 'ก'\n        30: 1,  # 'ข'\n        24: 2,  # 'ค'\n        8: 3,  # 'ง'\n        26: 2,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 2,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 2,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 2,  # 'ด'\n        19: 2,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 1,  # 'ธ'\n        3: 3,  # 'น'\n        17: 3,  # 'บ'\n        25: 1,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 0,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 1,  # 'ล'\n        12: 3,  # 'ว'\n        42: 1,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 1,  # 'ห'\n        4: 2,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 2,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 2,  # 'ิ'\n        13: 3,  # 'ี'\n        40: 1,  # 'ึ'\n        27: 2,  # 'ื'\n        32: 2,  # 'ุ'\n        35: 3,  # 'ู'\n        11: 2,  # 'เ'\n        28: 1,  # 'แ'\n        41: 1,  # 'โ'\n        29: 2,  # 'ใ'\n        33: 2,  # 'ไ'\n        50: 2,  # 'ๆ'\n        37: 1,  # '็'\n        6: 3,  # '่'\n        7: 2,  # '้'\n        38: 3,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    2: {  # 'ร'\n        5: 3,  # 'ก'\n        30: 2,  # 'ข'\n        24: 2,  # 'ค'\n        8: 3,  # 'ง'\n        26: 2,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 2,  # 'ช'\n        51: 1,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 3,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 3,  # 'ณ'\n        20: 2,  # 'ด'\n        19: 2,  # 'ต'\n        44: 3,  # 'ถ'\n        14: 3,  # 'ท'\n        48: 1,  # 'ธ'\n        3: 2,  # 'น'\n        17: 2,  # 'บ'\n        25: 3,  # 'ป'\n        39: 2,  # 'ผ'\n        62: 1,  # 'ฝ'\n        31: 2,  # 'พ'\n        54: 1,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 3,  # 'ม'\n        16: 2,  # 'ย'\n        2: 3,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 3,  # 'ว'\n        42: 2,  # 'ศ'\n        46: 2,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 2,  # 'ห'\n        4: 3,  # 'อ'\n        63: 1,  # 'ฯ'\n        22: 3,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 3,  # 'ิ'\n        13: 3,  # 'ี'\n        40: 2,  # 'ึ'\n        27: 3,  # 'ื'\n        32: 3,  # 'ุ'\n        35: 3,  # 'ู'\n        11: 3,  # 'เ'\n        28: 3,  # 'แ'\n        41: 1,  # 'โ'\n        29: 2,  # 'ใ'\n        33: 1,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 3,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 3,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    61: {  # 'ฤ'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 2,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 2,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    15: {  # 'ล'\n        5: 2,  # 'ก'\n        30: 3,  # 'ข'\n        24: 1,  # 'ค'\n        8: 3,  # 'ง'\n        26: 1,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 2,  # 'ด'\n        19: 2,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 1,  # 'น'\n        17: 2,  # 'บ'\n        25: 2,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 3,  # 'ย'\n        2: 1,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 1,  # 'ล'\n        12: 1,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 1,  # 'ห'\n        4: 3,  # 'อ'\n        63: 2,  # 'ฯ'\n        22: 3,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 2,  # 'ำ'\n        23: 3,  # 'ิ'\n        13: 3,  # 'ี'\n        40: 2,  # 'ึ'\n        27: 3,  # 'ื'\n        32: 2,  # 'ุ'\n        35: 3,  # 'ู'\n        11: 2,  # 'เ'\n        28: 1,  # 'แ'\n        41: 1,  # 'โ'\n        29: 2,  # 'ใ'\n        33: 1,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 2,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 2,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    12: {  # 'ว'\n        5: 3,  # 'ก'\n        30: 2,  # 'ข'\n        24: 1,  # 'ค'\n        8: 3,  # 'ง'\n        26: 2,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 1,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 1,  # 'ณ'\n        20: 2,  # 'ด'\n        19: 1,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 2,  # 'บ'\n        25: 1,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 1,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 3,  # 'ม'\n        16: 3,  # 'ย'\n        2: 3,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 3,  # 'ล'\n        12: 1,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 2,  # 'ห'\n        4: 2,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 2,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 3,  # 'ิ'\n        13: 2,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 2,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 3,  # 'เ'\n        28: 2,  # 'แ'\n        41: 1,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 2,  # 'ไ'\n        50: 1,  # 'ๆ'\n        37: 0,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 1,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    42: {  # 'ศ'\n        5: 1,  # 'ก'\n        30: 0,  # 'ข'\n        24: 1,  # 'ค'\n        8: 0,  # 'ง'\n        26: 1,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 1,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 1,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 2,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 2,  # 'ว'\n        42: 1,  # 'ศ'\n        46: 2,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 2,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 2,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 3,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 2,  # 'ู'\n        11: 0,  # 'เ'\n        28: 1,  # 'แ'\n        41: 0,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 1,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 1,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    46: {  # 'ษ'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 2,  # 'ฎ'\n        57: 1,  # 'ฏ'\n        49: 2,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 3,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 1,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 2,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 1,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 2,  # 'ะ'\n        10: 2,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 1,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 1,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 2,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    18: {  # 'ส'\n        5: 2,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 2,  # 'ง'\n        26: 1,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 3,  # 'ด'\n        19: 3,  # 'ต'\n        44: 3,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 2,  # 'บ'\n        25: 1,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 2,  # 'ภ'\n        9: 3,  # 'ม'\n        16: 1,  # 'ย'\n        2: 3,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 1,  # 'ล'\n        12: 2,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 2,  # 'ห'\n        4: 3,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 2,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 3,  # 'ำ'\n        23: 3,  # 'ิ'\n        13: 3,  # 'ี'\n        40: 2,  # 'ึ'\n        27: 3,  # 'ื'\n        32: 3,  # 'ุ'\n        35: 3,  # 'ู'\n        11: 2,  # 'เ'\n        28: 0,  # 'แ'\n        41: 1,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 1,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 3,  # '่'\n        7: 1,  # '้'\n        38: 2,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    21: {  # 'ห'\n        5: 3,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 1,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 2,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 1,  # 'ด'\n        19: 3,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 0,  # 'บ'\n        25: 1,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 3,  # 'ม'\n        16: 2,  # 'ย'\n        2: 3,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 3,  # 'ล'\n        12: 2,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 3,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 1,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 0,  # 'ำ'\n        23: 1,  # 'ิ'\n        13: 1,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 1,  # 'ุ'\n        35: 1,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 3,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 2,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    4: {  # 'อ'\n        5: 3,  # 'ก'\n        30: 1,  # 'ข'\n        24: 2,  # 'ค'\n        8: 3,  # 'ง'\n        26: 1,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 3,  # 'ด'\n        19: 2,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 1,  # 'ธ'\n        3: 3,  # 'น'\n        17: 3,  # 'บ'\n        25: 1,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 1,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 3,  # 'ม'\n        16: 3,  # 'ย'\n        2: 3,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 2,  # 'ว'\n        42: 1,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 2,  # 'ห'\n        4: 3,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 2,  # 'ะ'\n        10: 3,  # 'ั'\n        1: 3,  # 'า'\n        36: 2,  # 'ำ'\n        23: 2,  # 'ิ'\n        13: 3,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 3,  # 'ื'\n        32: 3,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 3,  # 'เ'\n        28: 1,  # 'แ'\n        41: 1,  # 'โ'\n        29: 2,  # 'ใ'\n        33: 2,  # 'ไ'\n        50: 1,  # 'ๆ'\n        37: 1,  # '็'\n        6: 2,  # '่'\n        7: 2,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    63: {  # 'ฯ'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    22: {  # 'ะ'\n        5: 3,  # 'ก'\n        30: 1,  # 'ข'\n        24: 2,  # 'ค'\n        8: 1,  # 'ง'\n        26: 2,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 3,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 3,  # 'ด'\n        19: 3,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 3,  # 'ท'\n        48: 1,  # 'ธ'\n        3: 2,  # 'น'\n        17: 3,  # 'บ'\n        25: 2,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 2,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 3,  # 'ม'\n        16: 2,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 2,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 3,  # 'ส'\n        21: 3,  # 'ห'\n        4: 2,  # 'อ'\n        63: 1,  # 'ฯ'\n        22: 1,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 3,  # 'เ'\n        28: 2,  # 'แ'\n        41: 1,  # 'โ'\n        29: 2,  # 'ใ'\n        33: 2,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    10: {  # 'ั'\n        5: 3,  # 'ก'\n        30: 0,  # 'ข'\n        24: 1,  # 'ค'\n        8: 3,  # 'ง'\n        26: 3,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 3,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 2,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 3,  # 'ฒ'\n        43: 3,  # 'ณ'\n        20: 3,  # 'ด'\n        19: 3,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 3,  # 'บ'\n        25: 1,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 2,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 3,  # 'ม'\n        16: 3,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 3,  # 'ว'\n        42: 2,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 3,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    1: {  # 'า'\n        5: 3,  # 'ก'\n        30: 2,  # 'ข'\n        24: 3,  # 'ค'\n        8: 3,  # 'ง'\n        26: 3,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 3,  # 'ช'\n        51: 1,  # 'ซ'\n        47: 2,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 3,  # 'ณ'\n        20: 3,  # 'ด'\n        19: 3,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 3,  # 'ท'\n        48: 2,  # 'ธ'\n        3: 3,  # 'น'\n        17: 3,  # 'บ'\n        25: 2,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 1,  # 'ฝ'\n        31: 3,  # 'พ'\n        54: 1,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 3,  # 'ม'\n        16: 3,  # 'ย'\n        2: 3,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 3,  # 'ล'\n        12: 3,  # 'ว'\n        42: 2,  # 'ศ'\n        46: 3,  # 'ษ'\n        18: 3,  # 'ส'\n        21: 3,  # 'ห'\n        4: 2,  # 'อ'\n        63: 1,  # 'ฯ'\n        22: 3,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 3,  # 'เ'\n        28: 2,  # 'แ'\n        41: 1,  # 'โ'\n        29: 2,  # 'ใ'\n        33: 2,  # 'ไ'\n        50: 1,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    36: {  # 'ำ'\n        5: 2,  # 'ก'\n        30: 1,  # 'ข'\n        24: 3,  # 'ค'\n        8: 2,  # 'ง'\n        26: 1,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 1,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 1,  # 'ด'\n        19: 1,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 1,  # 'บ'\n        25: 1,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 0,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 1,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 3,  # 'ห'\n        4: 1,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 3,  # 'เ'\n        28: 2,  # 'แ'\n        41: 1,  # 'โ'\n        29: 2,  # 'ใ'\n        33: 2,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    23: {  # 'ิ'\n        5: 3,  # 'ก'\n        30: 1,  # 'ข'\n        24: 2,  # 'ค'\n        8: 3,  # 'ง'\n        26: 3,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 3,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 2,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 3,  # 'ด'\n        19: 3,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 3,  # 'ท'\n        48: 3,  # 'ธ'\n        3: 3,  # 'น'\n        17: 3,  # 'บ'\n        25: 2,  # 'ป'\n        39: 2,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 3,  # 'พ'\n        54: 1,  # 'ฟ'\n        45: 2,  # 'ภ'\n        9: 3,  # 'ม'\n        16: 2,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 3,  # 'ว'\n        42: 3,  # 'ศ'\n        46: 2,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 3,  # 'ห'\n        4: 1,  # 'อ'\n        63: 1,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 3,  # 'เ'\n        28: 1,  # 'แ'\n        41: 1,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 3,  # '่'\n        7: 2,  # '้'\n        38: 2,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    13: {  # 'ี'\n        5: 3,  # 'ก'\n        30: 2,  # 'ข'\n        24: 2,  # 'ค'\n        8: 0,  # 'ง'\n        26: 1,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 2,  # 'ด'\n        19: 1,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 1,  # 'น'\n        17: 2,  # 'บ'\n        25: 2,  # 'ป'\n        39: 1,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 2,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 3,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 1,  # 'ล'\n        12: 2,  # 'ว'\n        42: 1,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 1,  # 'ห'\n        4: 2,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 2,  # 'เ'\n        28: 2,  # 'แ'\n        41: 1,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 1,  # 'ไ'\n        50: 1,  # 'ๆ'\n        37: 0,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    40: {  # 'ึ'\n        5: 3,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 3,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 1,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    27: {  # 'ื'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 1,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 2,  # 'น'\n        17: 3,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 3,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    32: {  # 'ุ'\n        5: 3,  # 'ก'\n        30: 2,  # 'ข'\n        24: 3,  # 'ค'\n        8: 3,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 2,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 1,  # 'ฒ'\n        43: 3,  # 'ณ'\n        20: 3,  # 'ด'\n        19: 3,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 1,  # 'ธ'\n        3: 2,  # 'น'\n        17: 2,  # 'บ'\n        25: 2,  # 'ป'\n        39: 2,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 3,  # 'ม'\n        16: 1,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 1,  # 'ว'\n        42: 1,  # 'ศ'\n        46: 2,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 1,  # 'ห'\n        4: 1,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 1,  # 'เ'\n        28: 0,  # 'แ'\n        41: 1,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 1,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 3,  # '่'\n        7: 2,  # '้'\n        38: 1,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    35: {  # 'ู'\n        5: 3,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 2,  # 'ง'\n        26: 1,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 2,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 1,  # 'ณ'\n        20: 2,  # 'ด'\n        19: 2,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 2,  # 'น'\n        17: 0,  # 'บ'\n        25: 3,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 0,  # 'ย'\n        2: 1,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 3,  # 'ล'\n        12: 1,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 1,  # 'เ'\n        28: 1,  # 'แ'\n        41: 1,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 3,  # '่'\n        7: 3,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    11: {  # 'เ'\n        5: 3,  # 'ก'\n        30: 3,  # 'ข'\n        24: 3,  # 'ค'\n        8: 2,  # 'ง'\n        26: 3,  # 'จ'\n        52: 3,  # 'ฉ'\n        34: 3,  # 'ช'\n        51: 2,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 1,  # 'ณ'\n        20: 3,  # 'ด'\n        19: 3,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 3,  # 'ท'\n        48: 1,  # 'ธ'\n        3: 3,  # 'น'\n        17: 3,  # 'บ'\n        25: 3,  # 'ป'\n        39: 2,  # 'ผ'\n        62: 1,  # 'ฝ'\n        31: 3,  # 'พ'\n        54: 1,  # 'ฟ'\n        45: 3,  # 'ภ'\n        9: 3,  # 'ม'\n        16: 2,  # 'ย'\n        2: 3,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 3,  # 'ล'\n        12: 3,  # 'ว'\n        42: 2,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 3,  # 'ส'\n        21: 3,  # 'ห'\n        4: 3,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    28: {  # 'แ'\n        5: 3,  # 'ก'\n        30: 2,  # 'ข'\n        24: 2,  # 'ค'\n        8: 1,  # 'ง'\n        26: 2,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 2,  # 'ด'\n        19: 3,  # 'ต'\n        44: 2,  # 'ถ'\n        14: 3,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 3,  # 'บ'\n        25: 2,  # 'ป'\n        39: 3,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 2,  # 'พ'\n        54: 2,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 2,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 3,  # 'ล'\n        12: 2,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 3,  # 'ส'\n        21: 3,  # 'ห'\n        4: 1,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    41: {  # 'โ'\n        5: 2,  # 'ก'\n        30: 1,  # 'ข'\n        24: 2,  # 'ค'\n        8: 0,  # 'ง'\n        26: 1,  # 'จ'\n        52: 1,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 1,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 3,  # 'ด'\n        19: 2,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 1,  # 'บ'\n        25: 3,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 1,  # 'ฟ'\n        45: 1,  # 'ภ'\n        9: 1,  # 'ม'\n        16: 2,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 3,  # 'ล'\n        12: 0,  # 'ว'\n        42: 1,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 0,  # 'ห'\n        4: 2,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    29: {  # 'ใ'\n        5: 2,  # 'ก'\n        30: 0,  # 'ข'\n        24: 1,  # 'ค'\n        8: 0,  # 'ง'\n        26: 3,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 3,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 3,  # 'ด'\n        19: 1,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 2,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 1,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 3,  # 'ส'\n        21: 3,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    33: {  # 'ไ'\n        5: 1,  # 'ก'\n        30: 2,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 1,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 3,  # 'ด'\n        19: 1,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 3,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 1,  # 'บ'\n        25: 3,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 2,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 3,  # 'ม'\n        16: 0,  # 'ย'\n        2: 3,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 1,  # 'ล'\n        12: 3,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 2,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    50: {  # 'ๆ'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    37: {  # '็'\n        5: 2,  # 'ก'\n        30: 1,  # 'ข'\n        24: 2,  # 'ค'\n        8: 2,  # 'ง'\n        26: 3,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 1,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 1,  # 'ด'\n        19: 2,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 3,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 1,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 2,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 0,  # 'ห'\n        4: 1,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 1,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 1,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    6: {  # '่'\n        5: 2,  # 'ก'\n        30: 1,  # 'ข'\n        24: 2,  # 'ค'\n        8: 3,  # 'ง'\n        26: 2,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 1,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 1,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 1,  # 'ด'\n        19: 2,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 1,  # 'ธ'\n        3: 3,  # 'น'\n        17: 1,  # 'บ'\n        25: 2,  # 'ป'\n        39: 2,  # 'ผ'\n        62: 1,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 3,  # 'ม'\n        16: 3,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 2,  # 'ล'\n        12: 3,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 1,  # 'ห'\n        4: 3,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 1,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 3,  # 'า'\n        36: 2,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 3,  # 'เ'\n        28: 2,  # 'แ'\n        41: 1,  # 'โ'\n        29: 2,  # 'ใ'\n        33: 2,  # 'ไ'\n        50: 1,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    7: {  # '้'\n        5: 2,  # 'ก'\n        30: 1,  # 'ข'\n        24: 2,  # 'ค'\n        8: 3,  # 'ง'\n        26: 2,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 1,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 1,  # 'ด'\n        19: 2,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 2,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 3,  # 'น'\n        17: 2,  # 'บ'\n        25: 2,  # 'ป'\n        39: 2,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 1,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 3,  # 'ม'\n        16: 2,  # 'ย'\n        2: 2,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 1,  # 'ล'\n        12: 3,  # 'ว'\n        42: 1,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 2,  # 'ส'\n        21: 2,  # 'ห'\n        4: 3,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 3,  # 'า'\n        36: 2,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 2,  # 'เ'\n        28: 2,  # 'แ'\n        41: 1,  # 'โ'\n        29: 2,  # 'ใ'\n        33: 2,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    38: {  # '์'\n        5: 2,  # 'ก'\n        30: 1,  # 'ข'\n        24: 1,  # 'ค'\n        8: 0,  # 'ง'\n        26: 1,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 1,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 2,  # 'ด'\n        19: 1,  # 'ต'\n        44: 1,  # 'ถ'\n        14: 1,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 1,  # 'น'\n        17: 1,  # 'บ'\n        25: 1,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 1,  # 'พ'\n        54: 1,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 2,  # 'ม'\n        16: 0,  # 'ย'\n        2: 1,  # 'ร'\n        61: 1,  # 'ฤ'\n        15: 1,  # 'ล'\n        12: 1,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 1,  # 'ส'\n        21: 1,  # 'ห'\n        4: 2,  # 'อ'\n        63: 1,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 2,  # 'เ'\n        28: 2,  # 'แ'\n        41: 1,  # 'โ'\n        29: 1,  # 'ใ'\n        33: 1,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 0,  # '๑'\n        59: 0,  # '๒'\n        60: 0,  # '๕'\n    },\n    56: {  # '๑'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 2,  # '๑'\n        59: 1,  # '๒'\n        60: 1,  # '๕'\n    },\n    59: {  # '๒'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 1,  # '๑'\n        59: 1,  # '๒'\n        60: 3,  # '๕'\n    },\n    60: {  # '๕'\n        5: 0,  # 'ก'\n        30: 0,  # 'ข'\n        24: 0,  # 'ค'\n        8: 0,  # 'ง'\n        26: 0,  # 'จ'\n        52: 0,  # 'ฉ'\n        34: 0,  # 'ช'\n        51: 0,  # 'ซ'\n        47: 0,  # 'ญ'\n        58: 0,  # 'ฎ'\n        57: 0,  # 'ฏ'\n        49: 0,  # 'ฐ'\n        53: 0,  # 'ฑ'\n        55: 0,  # 'ฒ'\n        43: 0,  # 'ณ'\n        20: 0,  # 'ด'\n        19: 0,  # 'ต'\n        44: 0,  # 'ถ'\n        14: 0,  # 'ท'\n        48: 0,  # 'ธ'\n        3: 0,  # 'น'\n        17: 0,  # 'บ'\n        25: 0,  # 'ป'\n        39: 0,  # 'ผ'\n        62: 0,  # 'ฝ'\n        31: 0,  # 'พ'\n        54: 0,  # 'ฟ'\n        45: 0,  # 'ภ'\n        9: 0,  # 'ม'\n        16: 0,  # 'ย'\n        2: 0,  # 'ร'\n        61: 0,  # 'ฤ'\n        15: 0,  # 'ล'\n        12: 0,  # 'ว'\n        42: 0,  # 'ศ'\n        46: 0,  # 'ษ'\n        18: 0,  # 'ส'\n        21: 0,  # 'ห'\n        4: 0,  # 'อ'\n        63: 0,  # 'ฯ'\n        22: 0,  # 'ะ'\n        10: 0,  # 'ั'\n        1: 0,  # 'า'\n        36: 0,  # 'ำ'\n        23: 0,  # 'ิ'\n        13: 0,  # 'ี'\n        40: 0,  # 'ึ'\n        27: 0,  # 'ื'\n        32: 0,  # 'ุ'\n        35: 0,  # 'ู'\n        11: 0,  # 'เ'\n        28: 0,  # 'แ'\n        41: 0,  # 'โ'\n        29: 0,  # 'ใ'\n        33: 0,  # 'ไ'\n        50: 0,  # 'ๆ'\n        37: 0,  # '็'\n        6: 0,  # '่'\n        7: 0,  # '้'\n        38: 0,  # '์'\n        56: 2,  # '๑'\n        59: 1,  # '๒'\n        60: 0,  # '๕'\n    },\n}\n\n# 255: Undefined characters that did not exist in training text\n# 254: Carriage/Return\n# 253: symbol (punctuation) that does not belong to word\n# 252: 0 - 9\n# 251: Control characters\n\n# Character Mapping Table(s):\nTIS_620_THAI_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 254,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 254,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 253,  # ' '\n    33: 253,  # '!'\n    34: 253,  # '\"'\n    35: 253,  # '#'\n    36: 253,  # '$'\n    37: 253,  # '%'\n    38: 253,  # '&'\n    39: 253,  # \"'\"\n    40: 253,  # '('\n    41: 253,  # ')'\n    42: 253,  # '*'\n    43: 253,  # '+'\n    44: 253,  # ','\n    45: 253,  # '-'\n    46: 253,  # '.'\n    47: 253,  # '/'\n    48: 252,  # '0'\n    49: 252,  # '1'\n    50: 252,  # '2'\n    51: 252,  # '3'\n    52: 252,  # '4'\n    53: 252,  # '5'\n    54: 252,  # '6'\n    55: 252,  # '7'\n    56: 252,  # '8'\n    57: 252,  # '9'\n    58: 253,  # ':'\n    59: 253,  # ';'\n    60: 253,  # '<'\n    61: 253,  # '='\n    62: 253,  # '>'\n    63: 253,  # '?'\n    64: 253,  # '@'\n    65: 182,  # 'A'\n    66: 106,  # 'B'\n    67: 107,  # 'C'\n    68: 100,  # 'D'\n    69: 183,  # 'E'\n    70: 184,  # 'F'\n    71: 185,  # 'G'\n    72: 101,  # 'H'\n    73: 94,  # 'I'\n    74: 186,  # 'J'\n    75: 187,  # 'K'\n    76: 108,  # 'L'\n    77: 109,  # 'M'\n    78: 110,  # 'N'\n    79: 111,  # 'O'\n    80: 188,  # 'P'\n    81: 189,  # 'Q'\n    82: 190,  # 'R'\n    83: 89,  # 'S'\n    84: 95,  # 'T'\n    85: 112,  # 'U'\n    86: 113,  # 'V'\n    87: 191,  # 'W'\n    88: 192,  # 'X'\n    89: 193,  # 'Y'\n    90: 194,  # 'Z'\n    91: 253,  # '['\n    92: 253,  # '\\\\'\n    93: 253,  # ']'\n    94: 253,  # '^'\n    95: 253,  # '_'\n    96: 253,  # '`'\n    97: 64,  # 'a'\n    98: 72,  # 'b'\n    99: 73,  # 'c'\n    100: 114,  # 'd'\n    101: 74,  # 'e'\n    102: 115,  # 'f'\n    103: 116,  # 'g'\n    104: 102,  # 'h'\n    105: 81,  # 'i'\n    106: 201,  # 'j'\n    107: 117,  # 'k'\n    108: 90,  # 'l'\n    109: 103,  # 'm'\n    110: 78,  # 'n'\n    111: 82,  # 'o'\n    112: 96,  # 'p'\n    113: 202,  # 'q'\n    114: 91,  # 'r'\n    115: 79,  # 's'\n    116: 84,  # 't'\n    117: 104,  # 'u'\n    118: 105,  # 'v'\n    119: 97,  # 'w'\n    120: 98,  # 'x'\n    121: 92,  # 'y'\n    122: 203,  # 'z'\n    123: 253,  # '{'\n    124: 253,  # '|'\n    125: 253,  # '}'\n    126: 253,  # '~'\n    127: 253,  # '\\x7f'\n    128: 209,  # '\\x80'\n    129: 210,  # '\\x81'\n    130: 211,  # '\\x82'\n    131: 212,  # '\\x83'\n    132: 213,  # '\\x84'\n    133: 88,  # '\\x85'\n    134: 214,  # '\\x86'\n    135: 215,  # '\\x87'\n    136: 216,  # '\\x88'\n    137: 217,  # '\\x89'\n    138: 218,  # '\\x8a'\n    139: 219,  # '\\x8b'\n    140: 220,  # '\\x8c'\n    141: 118,  # '\\x8d'\n    142: 221,  # '\\x8e'\n    143: 222,  # '\\x8f'\n    144: 223,  # '\\x90'\n    145: 224,  # '\\x91'\n    146: 99,  # '\\x92'\n    147: 85,  # '\\x93'\n    148: 83,  # '\\x94'\n    149: 225,  # '\\x95'\n    150: 226,  # '\\x96'\n    151: 227,  # '\\x97'\n    152: 228,  # '\\x98'\n    153: 229,  # '\\x99'\n    154: 230,  # '\\x9a'\n    155: 231,  # '\\x9b'\n    156: 232,  # '\\x9c'\n    157: 233,  # '\\x9d'\n    158: 234,  # '\\x9e'\n    159: 235,  # '\\x9f'\n    160: 236,  # None\n    161: 5,  # 'ก'\n    162: 30,  # 'ข'\n    163: 237,  # 'ฃ'\n    164: 24,  # 'ค'\n    165: 238,  # 'ฅ'\n    166: 75,  # 'ฆ'\n    167: 8,  # 'ง'\n    168: 26,  # 'จ'\n    169: 52,  # 'ฉ'\n    170: 34,  # 'ช'\n    171: 51,  # 'ซ'\n    172: 119,  # 'ฌ'\n    173: 47,  # 'ญ'\n    174: 58,  # 'ฎ'\n    175: 57,  # 'ฏ'\n    176: 49,  # 'ฐ'\n    177: 53,  # 'ฑ'\n    178: 55,  # 'ฒ'\n    179: 43,  # 'ณ'\n    180: 20,  # 'ด'\n    181: 19,  # 'ต'\n    182: 44,  # 'ถ'\n    183: 14,  # 'ท'\n    184: 48,  # 'ธ'\n    185: 3,  # 'น'\n    186: 17,  # 'บ'\n    187: 25,  # 'ป'\n    188: 39,  # 'ผ'\n    189: 62,  # 'ฝ'\n    190: 31,  # 'พ'\n    191: 54,  # 'ฟ'\n    192: 45,  # 'ภ'\n    193: 9,  # 'ม'\n    194: 16,  # 'ย'\n    195: 2,  # 'ร'\n    196: 61,  # 'ฤ'\n    197: 15,  # 'ล'\n    198: 239,  # 'ฦ'\n    199: 12,  # 'ว'\n    200: 42,  # 'ศ'\n    201: 46,  # 'ษ'\n    202: 18,  # 'ส'\n    203: 21,  # 'ห'\n    204: 76,  # 'ฬ'\n    205: 4,  # 'อ'\n    206: 66,  # 'ฮ'\n    207: 63,  # 'ฯ'\n    208: 22,  # 'ะ'\n    209: 10,  # 'ั'\n    210: 1,  # 'า'\n    211: 36,  # 'ำ'\n    212: 23,  # 'ิ'\n    213: 13,  # 'ี'\n    214: 40,  # 'ึ'\n    215: 27,  # 'ื'\n    216: 32,  # 'ุ'\n    217: 35,  # 'ู'\n    218: 86,  # 'ฺ'\n    219: 240,  # None\n    220: 241,  # None\n    221: 242,  # None\n    222: 243,  # None\n    223: 244,  # '฿'\n    224: 11,  # 'เ'\n    225: 28,  # 'แ'\n    226: 41,  # 'โ'\n    227: 29,  # 'ใ'\n    228: 33,  # 'ไ'\n    229: 245,  # 'ๅ'\n    230: 50,  # 'ๆ'\n    231: 37,  # '็'\n    232: 6,  # '่'\n    233: 7,  # '้'\n    234: 67,  # '๊'\n    235: 77,  # '๋'\n    236: 38,  # '์'\n    237: 93,  # 'ํ'\n    238: 246,  # '๎'\n    239: 247,  # '๏'\n    240: 68,  # '๐'\n    241: 56,  # '๑'\n    242: 59,  # '๒'\n    243: 65,  # '๓'\n    244: 69,  # '๔'\n    245: 60,  # '๕'\n    246: 70,  # '๖'\n    247: 80,  # '๗'\n    248: 71,  # '๘'\n    249: 87,  # '๙'\n    250: 248,  # '๚'\n    251: 249,  # '๛'\n    252: 250,  # None\n    253: 251,  # None\n    254: 252,  # None\n    255: 253,  # None\n}\n\nTIS_620_THAI_MODEL = SingleByteCharSetModel(\n    charset_name=\"TIS-620\",\n    language=\"Thai\",\n    char_to_order_map=TIS_620_THAI_CHAR_TO_ORDER,\n    language_model=THAI_LANG_MODEL,\n    typical_positive_ratio=0.926386,\n    keep_ascii_letters=False,\n    alphabet=\"กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛\",\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/langturkishmodel.py",
    "content": "from pip._vendor.chardet.sbcharsetprober import SingleByteCharSetModel\n\n# 3: Positive\n# 2: Likely\n# 1: Unlikely\n# 0: Negative\n\nTURKISH_LANG_MODEL = {\n    23: {  # 'A'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 0,  # 'c'\n        12: 2,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 1,  # 'g'\n        25: 1,  # 'h'\n        3: 1,  # 'i'\n        24: 0,  # 'j'\n        10: 2,  # 'k'\n        5: 1,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        15: 0,  # 'o'\n        26: 0,  # 'p'\n        7: 1,  # 'r'\n        8: 1,  # 's'\n        9: 1,  # 't'\n        14: 1,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 3,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 0,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    37: {  # 'B'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 2,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 2,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 1,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 1,  # 'P'\n        44: 0,  # 'R'\n        35: 1,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 1,  # 'Y'\n        56: 0,  # 'Z'\n        1: 2,  # 'a'\n        21: 0,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 0,  # 'j'\n        10: 0,  # 'k'\n        5: 0,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        15: 0,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 2,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 1,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 1,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 0,  # 'ı'\n        40: 1,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    47: {  # 'C'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 1,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 1,  # 'L'\n        20: 0,  # 'M'\n        46: 1,  # 'N'\n        42: 0,  # 'O'\n        48: 1,  # 'P'\n        44: 1,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 1,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 2,  # 'j'\n        10: 1,  # 'k'\n        5: 2,  # 'l'\n        13: 2,  # 'm'\n        4: 2,  # 'n'\n        15: 1,  # 'o'\n        26: 0,  # 'p'\n        7: 2,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 3,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 1,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    39: {  # 'D'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 1,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 1,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 1,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 2,  # 'a'\n        21: 0,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 2,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 0,  # 'j'\n        10: 0,  # 'k'\n        5: 1,  # 'l'\n        13: 3,  # 'm'\n        4: 0,  # 'n'\n        15: 1,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 1,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 1,  # 'z'\n        63: 0,  # '·'\n        54: 1,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 1,  # 'ı'\n        40: 1,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    29: {  # 'E'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 1,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 1,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 0,  # 'c'\n        12: 2,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 1,  # 'g'\n        25: 0,  # 'h'\n        3: 1,  # 'i'\n        24: 1,  # 'j'\n        10: 0,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 1,  # 's'\n        9: 1,  # 't'\n        14: 1,  # 'u'\n        32: 1,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 2,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    52: {  # 'F'\n        23: 0,  # 'A'\n        37: 1,  # 'B'\n        47: 1,  # 'C'\n        39: 1,  # 'D'\n        29: 1,  # 'E'\n        52: 2,  # 'F'\n        36: 0,  # 'G'\n        45: 2,  # 'H'\n        53: 1,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 1,  # 'M'\n        46: 1,  # 'N'\n        42: 1,  # 'O'\n        48: 2,  # 'P'\n        44: 1,  # 'R'\n        35: 1,  # 'S'\n        31: 1,  # 'T'\n        51: 1,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 2,  # 'Y'\n        56: 0,  # 'Z'\n        1: 0,  # 'a'\n        21: 1,  # 'b'\n        28: 1,  # 'c'\n        12: 1,  # 'd'\n        2: 0,  # 'e'\n        18: 1,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 2,  # 'i'\n        24: 1,  # 'j'\n        10: 0,  # 'k'\n        5: 0,  # 'l'\n        13: 1,  # 'm'\n        4: 2,  # 'n'\n        15: 1,  # 'o'\n        26: 0,  # 'p'\n        7: 2,  # 'r'\n        8: 1,  # 's'\n        9: 1,  # 't'\n        14: 1,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 1,  # 'y'\n        22: 1,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 1,  # 'Ö'\n        55: 2,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 2,  # 'ö'\n        17: 0,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 2,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 2,  # 'ş'\n    },\n    36: {  # 'G'\n        23: 1,  # 'A'\n        37: 0,  # 'B'\n        47: 1,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 1,  # 'F'\n        36: 2,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 2,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 2,  # 'N'\n        42: 1,  # 'O'\n        48: 1,  # 'P'\n        44: 1,  # 'R'\n        35: 1,  # 'S'\n        31: 0,  # 'T'\n        51: 1,  # 'U'\n        38: 2,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 1,  # 'c'\n        12: 0,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 1,  # 'j'\n        10: 1,  # 'k'\n        5: 0,  # 'l'\n        13: 3,  # 'm'\n        4: 2,  # 'n'\n        15: 0,  # 'o'\n        26: 1,  # 'p'\n        7: 0,  # 'r'\n        8: 1,  # 's'\n        9: 1,  # 't'\n        14: 3,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 1,  # 'x'\n        11: 0,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 1,  # 'Ç'\n        50: 2,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 1,  # 'â'\n        33: 2,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 2,  # 'ı'\n        40: 2,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    45: {  # 'H'\n        23: 0,  # 'A'\n        37: 1,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 2,  # 'F'\n        36: 2,  # 'G'\n        45: 1,  # 'H'\n        53: 1,  # 'I'\n        60: 0,  # 'J'\n        16: 2,  # 'K'\n        49: 1,  # 'L'\n        20: 0,  # 'M'\n        46: 1,  # 'N'\n        42: 1,  # 'O'\n        48: 1,  # 'P'\n        44: 0,  # 'R'\n        35: 2,  # 'S'\n        31: 0,  # 'T'\n        51: 1,  # 'U'\n        38: 2,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 2,  # 'i'\n        24: 0,  # 'j'\n        10: 1,  # 'k'\n        5: 0,  # 'l'\n        13: 2,  # 'm'\n        4: 0,  # 'n'\n        15: 1,  # 'o'\n        26: 1,  # 'p'\n        7: 1,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 3,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 1,  # 'Ç'\n        50: 1,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 0,  # 'ü'\n        30: 2,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 0,  # 'ı'\n        40: 2,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    53: {  # 'I'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 1,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 2,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 1,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 2,  # 'a'\n        21: 0,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 2,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 0,  # 'j'\n        10: 0,  # 'k'\n        5: 2,  # 'l'\n        13: 2,  # 'm'\n        4: 0,  # 'n'\n        15: 0,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 2,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 1,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 2,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 0,  # 'ı'\n        40: 1,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    60: {  # 'J'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 1,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 0,  # 'a'\n        21: 1,  # 'b'\n        28: 0,  # 'c'\n        12: 1,  # 'd'\n        2: 0,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 1,  # 'i'\n        24: 0,  # 'j'\n        10: 0,  # 'k'\n        5: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 1,  # 'n'\n        15: 0,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 1,  # 's'\n        9: 0,  # 't'\n        14: 0,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 0,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    16: {  # 'K'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 3,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 2,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 2,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 2,  # 'a'\n        21: 3,  # 'b'\n        28: 0,  # 'c'\n        12: 3,  # 'd'\n        2: 1,  # 'e'\n        18: 3,  # 'f'\n        27: 3,  # 'g'\n        25: 3,  # 'h'\n        3: 3,  # 'i'\n        24: 2,  # 'j'\n        10: 3,  # 'k'\n        5: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 1,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 0,  # 'u'\n        32: 3,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 2,  # 'y'\n        22: 1,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 2,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    49: {  # 'L'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 2,  # 'E'\n        52: 0,  # 'F'\n        36: 1,  # 'G'\n        45: 1,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 1,  # 'M'\n        46: 0,  # 'N'\n        42: 2,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 1,  # 'Y'\n        56: 0,  # 'Z'\n        1: 0,  # 'a'\n        21: 3,  # 'b'\n        28: 0,  # 'c'\n        12: 2,  # 'd'\n        2: 0,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 2,  # 'i'\n        24: 0,  # 'j'\n        10: 1,  # 'k'\n        5: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 2,  # 'n'\n        15: 1,  # 'o'\n        26: 1,  # 'p'\n        7: 1,  # 'r'\n        8: 1,  # 's'\n        9: 1,  # 't'\n        14: 0,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 2,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 2,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 1,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 2,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    20: {  # 'M'\n        23: 1,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 1,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 2,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 1,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 2,  # 'b'\n        28: 0,  # 'c'\n        12: 3,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 1,  # 'g'\n        25: 1,  # 'h'\n        3: 2,  # 'i'\n        24: 2,  # 'j'\n        10: 2,  # 'k'\n        5: 2,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 1,  # 'p'\n        7: 3,  # 'r'\n        8: 0,  # 's'\n        9: 2,  # 't'\n        14: 3,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 2,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 3,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    46: {  # 'N'\n        23: 0,  # 'A'\n        37: 1,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 1,  # 'F'\n        36: 1,  # 'G'\n        45: 1,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 2,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 1,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 1,  # 'R'\n        35: 1,  # 'S'\n        31: 0,  # 'T'\n        51: 1,  # 'U'\n        38: 2,  # 'V'\n        62: 0,  # 'W'\n        43: 1,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 1,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 2,  # 'j'\n        10: 1,  # 'k'\n        5: 1,  # 'l'\n        13: 3,  # 'm'\n        4: 2,  # 'n'\n        15: 1,  # 'o'\n        26: 1,  # 'p'\n        7: 1,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 3,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 1,  # 'x'\n        11: 1,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 1,  # 'Ç'\n        50: 1,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 2,  # 'ı'\n        40: 1,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    42: {  # 'O'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 1,  # 'F'\n        36: 0,  # 'G'\n        45: 1,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 2,  # 'K'\n        49: 1,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 2,  # 'P'\n        44: 1,  # 'R'\n        35: 1,  # 'S'\n        31: 0,  # 'T'\n        51: 1,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 2,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 0,  # 'j'\n        10: 0,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 0,  # 'n'\n        15: 1,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 2,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 2,  # 'Ç'\n        50: 1,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 2,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 0,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 2,  # 'İ'\n        6: 1,  # 'ı'\n        40: 1,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    48: {  # 'P'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 2,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 2,  # 'F'\n        36: 1,  # 'G'\n        45: 1,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 2,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 1,  # 'N'\n        42: 1,  # 'O'\n        48: 1,  # 'P'\n        44: 0,  # 'R'\n        35: 1,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 2,  # 'a'\n        21: 0,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 0,  # 'j'\n        10: 1,  # 'k'\n        5: 0,  # 'l'\n        13: 2,  # 'm'\n        4: 0,  # 'n'\n        15: 2,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 2,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 2,  # 'x'\n        11: 0,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 1,  # 'Ç'\n        50: 2,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 2,  # 'ö'\n        17: 0,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 0,  # 'ı'\n        40: 2,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    44: {  # 'R'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 1,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 1,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 1,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 1,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 1,  # 'b'\n        28: 1,  # 'c'\n        12: 0,  # 'd'\n        2: 2,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 0,  # 'j'\n        10: 1,  # 'k'\n        5: 2,  # 'l'\n        13: 2,  # 'm'\n        4: 0,  # 'n'\n        15: 1,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 2,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 1,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 1,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 1,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 2,  # 'ı'\n        40: 1,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    35: {  # 'S'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 1,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 1,  # 'F'\n        36: 1,  # 'G'\n        45: 1,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 3,  # 'K'\n        49: 1,  # 'L'\n        20: 1,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 1,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 1,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 1,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 0,  # 'j'\n        10: 1,  # 'k'\n        5: 1,  # 'l'\n        13: 2,  # 'm'\n        4: 1,  # 'n'\n        15: 0,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 1,  # 't'\n        14: 2,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 1,  # 'z'\n        63: 0,  # '·'\n        54: 2,  # 'Ç'\n        50: 2,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 3,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 2,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    31: {  # 'T'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 1,  # 'J'\n        16: 2,  # 'K'\n        49: 0,  # 'L'\n        20: 1,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 2,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 2,  # 'b'\n        28: 0,  # 'c'\n        12: 1,  # 'd'\n        2: 3,  # 'e'\n        18: 2,  # 'f'\n        27: 2,  # 'g'\n        25: 0,  # 'h'\n        3: 1,  # 'i'\n        24: 1,  # 'j'\n        10: 2,  # 'k'\n        5: 2,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 2,  # 'p'\n        7: 2,  # 'r'\n        8: 0,  # 's'\n        9: 2,  # 't'\n        14: 2,  # 'u'\n        32: 1,  # 'v'\n        57: 1,  # 'w'\n        58: 1,  # 'x'\n        11: 2,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 1,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    51: {  # 'U'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 1,  # 'F'\n        36: 1,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 1,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 1,  # 'N'\n        42: 0,  # 'O'\n        48: 1,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 1,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 1,  # 'c'\n        12: 0,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 2,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 0,  # 'j'\n        10: 1,  # 'k'\n        5: 1,  # 'l'\n        13: 3,  # 'm'\n        4: 2,  # 'n'\n        15: 0,  # 'o'\n        26: 1,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 2,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 1,  # 'Ç'\n        50: 1,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 2,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    38: {  # 'V'\n        23: 1,  # 'A'\n        37: 1,  # 'B'\n        47: 1,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 2,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 3,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 1,  # 'P'\n        44: 1,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 1,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 0,  # 'j'\n        10: 0,  # 'k'\n        5: 2,  # 'l'\n        13: 2,  # 'm'\n        4: 0,  # 'n'\n        15: 2,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 1,  # 't'\n        14: 3,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 1,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 1,  # 'Ç'\n        50: 1,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 1,  # 'â'\n        33: 2,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 0,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 3,  # 'ı'\n        40: 2,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    62: {  # 'W'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 0,  # 'a'\n        21: 0,  # 'b'\n        28: 0,  # 'c'\n        12: 0,  # 'd'\n        2: 0,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 0,  # 'j'\n        10: 0,  # 'k'\n        5: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 0,  # 'n'\n        15: 0,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 0,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 0,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    43: {  # 'Y'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 1,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 2,  # 'F'\n        36: 0,  # 'G'\n        45: 1,  # 'H'\n        53: 1,  # 'I'\n        60: 0,  # 'J'\n        16: 2,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 2,  # 'N'\n        42: 0,  # 'O'\n        48: 2,  # 'P'\n        44: 1,  # 'R'\n        35: 1,  # 'S'\n        31: 0,  # 'T'\n        51: 1,  # 'U'\n        38: 2,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 2,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 1,  # 'j'\n        10: 1,  # 'k'\n        5: 1,  # 'l'\n        13: 3,  # 'm'\n        4: 0,  # 'n'\n        15: 2,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 3,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 1,  # 'x'\n        11: 0,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 1,  # 'Ç'\n        50: 2,  # 'Ö'\n        55: 1,  # 'Ü'\n        59: 1,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 0,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 0,  # 'ı'\n        40: 2,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    56: {  # 'Z'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 2,  # 'Z'\n        1: 2,  # 'a'\n        21: 1,  # 'b'\n        28: 0,  # 'c'\n        12: 0,  # 'd'\n        2: 2,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 2,  # 'i'\n        24: 1,  # 'j'\n        10: 0,  # 'k'\n        5: 0,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        15: 0,  # 'o'\n        26: 0,  # 'p'\n        7: 1,  # 'r'\n        8: 1,  # 's'\n        9: 0,  # 't'\n        14: 2,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 1,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 1,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    1: {  # 'a'\n        23: 3,  # 'A'\n        37: 0,  # 'B'\n        47: 1,  # 'C'\n        39: 0,  # 'D'\n        29: 3,  # 'E'\n        52: 0,  # 'F'\n        36: 1,  # 'G'\n        45: 1,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 3,  # 'M'\n        46: 1,  # 'N'\n        42: 0,  # 'O'\n        48: 1,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 3,  # 'T'\n        51: 0,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 2,  # 'Z'\n        1: 2,  # 'a'\n        21: 3,  # 'b'\n        28: 0,  # 'c'\n        12: 3,  # 'd'\n        2: 2,  # 'e'\n        18: 3,  # 'f'\n        27: 3,  # 'g'\n        25: 3,  # 'h'\n        3: 3,  # 'i'\n        24: 3,  # 'j'\n        10: 3,  # 'k'\n        5: 0,  # 'l'\n        13: 2,  # 'm'\n        4: 3,  # 'n'\n        15: 1,  # 'o'\n        26: 3,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 3,  # 'u'\n        32: 3,  # 'v'\n        57: 2,  # 'w'\n        58: 0,  # 'x'\n        11: 3,  # 'y'\n        22: 0,  # 'z'\n        63: 1,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 1,  # 'î'\n        34: 1,  # 'ö'\n        17: 3,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    21: {  # 'b'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 1,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 1,  # 'J'\n        16: 2,  # 'K'\n        49: 0,  # 'L'\n        20: 2,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 1,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 1,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 2,  # 'b'\n        28: 0,  # 'c'\n        12: 3,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 3,  # 'g'\n        25: 1,  # 'h'\n        3: 3,  # 'i'\n        24: 2,  # 'j'\n        10: 3,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 3,  # 'p'\n        7: 1,  # 'r'\n        8: 2,  # 's'\n        9: 2,  # 't'\n        14: 2,  # 'u'\n        32: 1,  # 'v'\n        57: 0,  # 'w'\n        58: 1,  # 'x'\n        11: 3,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 2,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    28: {  # 'c'\n        23: 0,  # 'A'\n        37: 1,  # 'B'\n        47: 1,  # 'C'\n        39: 1,  # 'D'\n        29: 2,  # 'E'\n        52: 0,  # 'F'\n        36: 2,  # 'G'\n        45: 2,  # 'H'\n        53: 1,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 2,  # 'M'\n        46: 1,  # 'N'\n        42: 1,  # 'O'\n        48: 2,  # 'P'\n        44: 1,  # 'R'\n        35: 1,  # 'S'\n        31: 2,  # 'T'\n        51: 2,  # 'U'\n        38: 2,  # 'V'\n        62: 0,  # 'W'\n        43: 3,  # 'Y'\n        56: 0,  # 'Z'\n        1: 1,  # 'a'\n        21: 1,  # 'b'\n        28: 2,  # 'c'\n        12: 2,  # 'd'\n        2: 1,  # 'e'\n        18: 1,  # 'f'\n        27: 2,  # 'g'\n        25: 2,  # 'h'\n        3: 3,  # 'i'\n        24: 1,  # 'j'\n        10: 3,  # 'k'\n        5: 0,  # 'l'\n        13: 2,  # 'm'\n        4: 3,  # 'n'\n        15: 2,  # 'o'\n        26: 2,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 1,  # 'u'\n        32: 0,  # 'v'\n        57: 1,  # 'w'\n        58: 0,  # 'x'\n        11: 2,  # 'y'\n        22: 1,  # 'z'\n        63: 1,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 1,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 1,  # 'î'\n        34: 2,  # 'ö'\n        17: 2,  # 'ü'\n        30: 2,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 2,  # 'ş'\n    },\n    12: {  # 'd'\n        23: 1,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 2,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 3,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 1,  # 'S'\n        31: 1,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 2,  # 'b'\n        28: 1,  # 'c'\n        12: 3,  # 'd'\n        2: 3,  # 'e'\n        18: 1,  # 'f'\n        27: 3,  # 'g'\n        25: 3,  # 'h'\n        3: 2,  # 'i'\n        24: 3,  # 'j'\n        10: 2,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 1,  # 'o'\n        26: 2,  # 'p'\n        7: 3,  # 'r'\n        8: 2,  # 's'\n        9: 2,  # 't'\n        14: 3,  # 'u'\n        32: 1,  # 'v'\n        57: 0,  # 'w'\n        58: 1,  # 'x'\n        11: 3,  # 'y'\n        22: 1,  # 'z'\n        63: 1,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 1,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 2,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    2: {  # 'e'\n        23: 2,  # 'A'\n        37: 0,  # 'B'\n        47: 2,  # 'C'\n        39: 0,  # 'D'\n        29: 3,  # 'E'\n        52: 1,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 1,  # 'K'\n        49: 0,  # 'L'\n        20: 3,  # 'M'\n        46: 1,  # 'N'\n        42: 0,  # 'O'\n        48: 1,  # 'P'\n        44: 1,  # 'R'\n        35: 0,  # 'S'\n        31: 3,  # 'T'\n        51: 0,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 1,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 3,  # 'b'\n        28: 0,  # 'c'\n        12: 3,  # 'd'\n        2: 2,  # 'e'\n        18: 3,  # 'f'\n        27: 3,  # 'g'\n        25: 3,  # 'h'\n        3: 3,  # 'i'\n        24: 3,  # 'j'\n        10: 3,  # 'k'\n        5: 0,  # 'l'\n        13: 2,  # 'm'\n        4: 3,  # 'n'\n        15: 1,  # 'o'\n        26: 3,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 3,  # 'u'\n        32: 3,  # 'v'\n        57: 2,  # 'w'\n        58: 0,  # 'x'\n        11: 3,  # 'y'\n        22: 1,  # 'z'\n        63: 1,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 3,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    18: {  # 'f'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 2,  # 'K'\n        49: 0,  # 'L'\n        20: 2,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 2,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 1,  # 'b'\n        28: 0,  # 'c'\n        12: 3,  # 'd'\n        2: 3,  # 'e'\n        18: 2,  # 'f'\n        27: 1,  # 'g'\n        25: 1,  # 'h'\n        3: 1,  # 'i'\n        24: 1,  # 'j'\n        10: 1,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 2,  # 'p'\n        7: 1,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 1,  # 'u'\n        32: 2,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 1,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 1,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 1,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    27: {  # 'g'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 1,  # 'S'\n        31: 1,  # 'T'\n        51: 0,  # 'U'\n        38: 2,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 1,  # 'b'\n        28: 0,  # 'c'\n        12: 1,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 2,  # 'g'\n        25: 1,  # 'h'\n        3: 2,  # 'i'\n        24: 3,  # 'j'\n        10: 2,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 2,  # 'n'\n        15: 0,  # 'o'\n        26: 1,  # 'p'\n        7: 2,  # 'r'\n        8: 2,  # 's'\n        9: 3,  # 't'\n        14: 3,  # 'u'\n        32: 1,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 1,  # 'y'\n        22: 0,  # 'z'\n        63: 1,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 2,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    25: {  # 'h'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 2,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 0,  # 'c'\n        12: 2,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 1,  # 'g'\n        25: 2,  # 'h'\n        3: 2,  # 'i'\n        24: 3,  # 'j'\n        10: 3,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 1,  # 'o'\n        26: 1,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 2,  # 't'\n        14: 3,  # 'u'\n        32: 2,  # 'v'\n        57: 1,  # 'w'\n        58: 0,  # 'x'\n        11: 1,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    3: {  # 'i'\n        23: 2,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 1,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 3,  # 'M'\n        46: 0,  # 'N'\n        42: 1,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 1,  # 'S'\n        31: 2,  # 'T'\n        51: 0,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 2,  # 'b'\n        28: 0,  # 'c'\n        12: 3,  # 'd'\n        2: 3,  # 'e'\n        18: 2,  # 'f'\n        27: 3,  # 'g'\n        25: 1,  # 'h'\n        3: 3,  # 'i'\n        24: 2,  # 'j'\n        10: 3,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 1,  # 'o'\n        26: 3,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 3,  # 'u'\n        32: 2,  # 'v'\n        57: 1,  # 'w'\n        58: 1,  # 'x'\n        11: 3,  # 'y'\n        22: 1,  # 'z'\n        63: 1,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 1,  # 'Ü'\n        59: 0,  # 'â'\n        33: 2,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 3,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 2,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    24: {  # 'j'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 1,  # 'J'\n        16: 2,  # 'K'\n        49: 0,  # 'L'\n        20: 2,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 1,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 1,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 1,  # 'Z'\n        1: 3,  # 'a'\n        21: 1,  # 'b'\n        28: 1,  # 'c'\n        12: 3,  # 'd'\n        2: 3,  # 'e'\n        18: 2,  # 'f'\n        27: 1,  # 'g'\n        25: 1,  # 'h'\n        3: 2,  # 'i'\n        24: 1,  # 'j'\n        10: 2,  # 'k'\n        5: 2,  # 'l'\n        13: 3,  # 'm'\n        4: 2,  # 'n'\n        15: 0,  # 'o'\n        26: 1,  # 'p'\n        7: 2,  # 'r'\n        8: 3,  # 's'\n        9: 2,  # 't'\n        14: 3,  # 'u'\n        32: 2,  # 'v'\n        57: 0,  # 'w'\n        58: 2,  # 'x'\n        11: 1,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 1,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    10: {  # 'k'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 2,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 3,  # 'T'\n        51: 0,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 1,  # 'Z'\n        1: 3,  # 'a'\n        21: 2,  # 'b'\n        28: 0,  # 'c'\n        12: 2,  # 'd'\n        2: 3,  # 'e'\n        18: 1,  # 'f'\n        27: 2,  # 'g'\n        25: 2,  # 'h'\n        3: 3,  # 'i'\n        24: 2,  # 'j'\n        10: 2,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 3,  # 'p'\n        7: 2,  # 'r'\n        8: 2,  # 's'\n        9: 2,  # 't'\n        14: 3,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 1,  # 'x'\n        11: 3,  # 'y'\n        22: 0,  # 'z'\n        63: 1,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 3,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 3,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    5: {  # 'l'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 3,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 2,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 1,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 0,  # 'a'\n        21: 3,  # 'b'\n        28: 0,  # 'c'\n        12: 3,  # 'd'\n        2: 1,  # 'e'\n        18: 3,  # 'f'\n        27: 3,  # 'g'\n        25: 2,  # 'h'\n        3: 3,  # 'i'\n        24: 2,  # 'j'\n        10: 3,  # 'k'\n        5: 1,  # 'l'\n        13: 1,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 2,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 2,  # 'u'\n        32: 2,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 3,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 2,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    13: {  # 'm'\n        23: 1,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 3,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 3,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 3,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 1,  # 'Y'\n        56: 0,  # 'Z'\n        1: 2,  # 'a'\n        21: 3,  # 'b'\n        28: 0,  # 'c'\n        12: 3,  # 'd'\n        2: 2,  # 'e'\n        18: 3,  # 'f'\n        27: 3,  # 'g'\n        25: 3,  # 'h'\n        3: 3,  # 'i'\n        24: 3,  # 'j'\n        10: 3,  # 'k'\n        5: 0,  # 'l'\n        13: 2,  # 'm'\n        4: 3,  # 'n'\n        15: 1,  # 'o'\n        26: 2,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 2,  # 'u'\n        32: 2,  # 'v'\n        57: 1,  # 'w'\n        58: 0,  # 'x'\n        11: 3,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 3,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    4: {  # 'n'\n        23: 1,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 1,  # 'H'\n        53: 0,  # 'I'\n        60: 2,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 3,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 2,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 2,  # 'b'\n        28: 1,  # 'c'\n        12: 3,  # 'd'\n        2: 3,  # 'e'\n        18: 1,  # 'f'\n        27: 2,  # 'g'\n        25: 3,  # 'h'\n        3: 2,  # 'i'\n        24: 2,  # 'j'\n        10: 3,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 1,  # 'o'\n        26: 3,  # 'p'\n        7: 2,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 3,  # 'u'\n        32: 2,  # 'v'\n        57: 0,  # 'w'\n        58: 2,  # 'x'\n        11: 3,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 2,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 1,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    15: {  # 'o'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 1,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 2,  # 'F'\n        36: 1,  # 'G'\n        45: 1,  # 'H'\n        53: 1,  # 'I'\n        60: 0,  # 'J'\n        16: 3,  # 'K'\n        49: 2,  # 'L'\n        20: 0,  # 'M'\n        46: 2,  # 'N'\n        42: 1,  # 'O'\n        48: 2,  # 'P'\n        44: 1,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 1,  # 'i'\n        24: 2,  # 'j'\n        10: 1,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 2,  # 'n'\n        15: 2,  # 'o'\n        26: 0,  # 'p'\n        7: 1,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 3,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 2,  # 'x'\n        11: 0,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 1,  # 'Ç'\n        50: 2,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 3,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 0,  # 'ü'\n        30: 2,  # 'ğ'\n        41: 2,  # 'İ'\n        6: 3,  # 'ı'\n        40: 2,  # 'Ş'\n        19: 2,  # 'ş'\n    },\n    26: {  # 'p'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 1,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 1,  # 'b'\n        28: 0,  # 'c'\n        12: 1,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 1,  # 'g'\n        25: 1,  # 'h'\n        3: 2,  # 'i'\n        24: 3,  # 'j'\n        10: 1,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 2,  # 'n'\n        15: 0,  # 'o'\n        26: 2,  # 'p'\n        7: 2,  # 'r'\n        8: 1,  # 's'\n        9: 1,  # 't'\n        14: 3,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 1,  # 'x'\n        11: 1,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 3,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 1,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    7: {  # 'r'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 1,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 2,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 2,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 2,  # 'T'\n        51: 1,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 1,  # 'Z'\n        1: 3,  # 'a'\n        21: 1,  # 'b'\n        28: 0,  # 'c'\n        12: 3,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 2,  # 'g'\n        25: 3,  # 'h'\n        3: 2,  # 'i'\n        24: 2,  # 'j'\n        10: 3,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 2,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 3,  # 'u'\n        32: 2,  # 'v'\n        57: 0,  # 'w'\n        58: 1,  # 'x'\n        11: 2,  # 'y'\n        22: 0,  # 'z'\n        63: 1,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 2,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 3,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 2,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    8: {  # 's'\n        23: 1,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 1,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 3,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 2,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 1,  # 'Z'\n        1: 3,  # 'a'\n        21: 2,  # 'b'\n        28: 1,  # 'c'\n        12: 3,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 2,  # 'g'\n        25: 2,  # 'h'\n        3: 2,  # 'i'\n        24: 3,  # 'j'\n        10: 3,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 3,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 3,  # 'u'\n        32: 2,  # 'v'\n        57: 0,  # 'w'\n        58: 1,  # 'x'\n        11: 2,  # 'y'\n        22: 1,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 2,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 2,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    9: {  # 't'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 1,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 2,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 2,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 1,  # 'Z'\n        1: 3,  # 'a'\n        21: 3,  # 'b'\n        28: 0,  # 'c'\n        12: 3,  # 'd'\n        2: 3,  # 'e'\n        18: 2,  # 'f'\n        27: 2,  # 'g'\n        25: 2,  # 'h'\n        3: 2,  # 'i'\n        24: 2,  # 'j'\n        10: 3,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 2,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 3,  # 'u'\n        32: 3,  # 'v'\n        57: 0,  # 'w'\n        58: 2,  # 'x'\n        11: 2,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 3,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 2,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    14: {  # 'u'\n        23: 3,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 3,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 1,  # 'H'\n        53: 0,  # 'I'\n        60: 1,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 3,  # 'M'\n        46: 2,  # 'N'\n        42: 0,  # 'O'\n        48: 1,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 3,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 1,  # 'Y'\n        56: 2,  # 'Z'\n        1: 2,  # 'a'\n        21: 3,  # 'b'\n        28: 0,  # 'c'\n        12: 3,  # 'd'\n        2: 2,  # 'e'\n        18: 2,  # 'f'\n        27: 3,  # 'g'\n        25: 3,  # 'h'\n        3: 3,  # 'i'\n        24: 2,  # 'j'\n        10: 3,  # 'k'\n        5: 0,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 3,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 3,  # 'u'\n        32: 2,  # 'v'\n        57: 2,  # 'w'\n        58: 0,  # 'x'\n        11: 3,  # 'y'\n        22: 0,  # 'z'\n        63: 1,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 3,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    32: {  # 'v'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 1,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 0,  # 'c'\n        12: 3,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 1,  # 'j'\n        10: 1,  # 'k'\n        5: 3,  # 'l'\n        13: 2,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 1,  # 'p'\n        7: 1,  # 'r'\n        8: 2,  # 's'\n        9: 3,  # 't'\n        14: 3,  # 'u'\n        32: 1,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 2,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 1,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    57: {  # 'w'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 1,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 1,  # 'a'\n        21: 0,  # 'b'\n        28: 0,  # 'c'\n        12: 0,  # 'd'\n        2: 2,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 1,  # 'h'\n        3: 0,  # 'i'\n        24: 0,  # 'j'\n        10: 1,  # 'k'\n        5: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 1,  # 'n'\n        15: 0,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 1,  # 's'\n        9: 0,  # 't'\n        14: 1,  # 'u'\n        32: 0,  # 'v'\n        57: 2,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 0,  # 'z'\n        63: 1,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 1,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 0,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    58: {  # 'x'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 1,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 1,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 1,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 0,  # 'a'\n        21: 1,  # 'b'\n        28: 0,  # 'c'\n        12: 2,  # 'd'\n        2: 1,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 2,  # 'i'\n        24: 2,  # 'j'\n        10: 1,  # 'k'\n        5: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 2,  # 'n'\n        15: 0,  # 'o'\n        26: 0,  # 'p'\n        7: 1,  # 'r'\n        8: 2,  # 's'\n        9: 1,  # 't'\n        14: 0,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 2,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 1,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 2,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    11: {  # 'y'\n        23: 1,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 1,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 1,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 1,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 1,  # 'Y'\n        56: 1,  # 'Z'\n        1: 3,  # 'a'\n        21: 1,  # 'b'\n        28: 0,  # 'c'\n        12: 2,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 2,  # 'g'\n        25: 2,  # 'h'\n        3: 2,  # 'i'\n        24: 1,  # 'j'\n        10: 2,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 1,  # 'p'\n        7: 2,  # 'r'\n        8: 1,  # 's'\n        9: 2,  # 't'\n        14: 3,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 1,  # 'x'\n        11: 3,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 3,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 2,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    22: {  # 'z'\n        23: 2,  # 'A'\n        37: 2,  # 'B'\n        47: 1,  # 'C'\n        39: 2,  # 'D'\n        29: 3,  # 'E'\n        52: 1,  # 'F'\n        36: 2,  # 'G'\n        45: 2,  # 'H'\n        53: 1,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 3,  # 'M'\n        46: 2,  # 'N'\n        42: 2,  # 'O'\n        48: 2,  # 'P'\n        44: 1,  # 'R'\n        35: 1,  # 'S'\n        31: 3,  # 'T'\n        51: 2,  # 'U'\n        38: 2,  # 'V'\n        62: 0,  # 'W'\n        43: 2,  # 'Y'\n        56: 1,  # 'Z'\n        1: 1,  # 'a'\n        21: 2,  # 'b'\n        28: 1,  # 'c'\n        12: 2,  # 'd'\n        2: 2,  # 'e'\n        18: 3,  # 'f'\n        27: 2,  # 'g'\n        25: 2,  # 'h'\n        3: 3,  # 'i'\n        24: 2,  # 'j'\n        10: 3,  # 'k'\n        5: 0,  # 'l'\n        13: 2,  # 'm'\n        4: 3,  # 'n'\n        15: 2,  # 'o'\n        26: 2,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 0,  # 'u'\n        32: 2,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 3,  # 'y'\n        22: 2,  # 'z'\n        63: 1,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 2,  # 'Ü'\n        59: 1,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 2,  # 'ö'\n        17: 2,  # 'ü'\n        30: 2,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 3,  # 'ı'\n        40: 1,  # 'Ş'\n        19: 2,  # 'ş'\n    },\n    63: {  # '·'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 0,  # 'a'\n        21: 0,  # 'b'\n        28: 0,  # 'c'\n        12: 0,  # 'd'\n        2: 1,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 0,  # 'j'\n        10: 0,  # 'k'\n        5: 0,  # 'l'\n        13: 2,  # 'm'\n        4: 0,  # 'n'\n        15: 0,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 2,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 0,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    54: {  # 'Ç'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 1,  # 'C'\n        39: 1,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 1,  # 'G'\n        45: 1,  # 'H'\n        53: 1,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 1,  # 'O'\n        48: 1,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 1,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 2,  # 'Y'\n        56: 0,  # 'Z'\n        1: 0,  # 'a'\n        21: 1,  # 'b'\n        28: 0,  # 'c'\n        12: 1,  # 'd'\n        2: 0,  # 'e'\n        18: 0,  # 'f'\n        27: 1,  # 'g'\n        25: 0,  # 'h'\n        3: 3,  # 'i'\n        24: 0,  # 'j'\n        10: 1,  # 'k'\n        5: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 2,  # 'n'\n        15: 1,  # 'o'\n        26: 0,  # 'p'\n        7: 2,  # 'r'\n        8: 0,  # 's'\n        9: 1,  # 't'\n        14: 0,  # 'u'\n        32: 2,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 2,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 2,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    50: {  # 'Ö'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 1,  # 'C'\n        39: 1,  # 'D'\n        29: 2,  # 'E'\n        52: 0,  # 'F'\n        36: 1,  # 'G'\n        45: 2,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 1,  # 'M'\n        46: 1,  # 'N'\n        42: 2,  # 'O'\n        48: 2,  # 'P'\n        44: 1,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 1,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 2,  # 'Y'\n        56: 0,  # 'Z'\n        1: 0,  # 'a'\n        21: 2,  # 'b'\n        28: 1,  # 'c'\n        12: 2,  # 'd'\n        2: 0,  # 'e'\n        18: 1,  # 'f'\n        27: 1,  # 'g'\n        25: 1,  # 'h'\n        3: 2,  # 'i'\n        24: 0,  # 'j'\n        10: 2,  # 'k'\n        5: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 3,  # 'n'\n        15: 2,  # 'o'\n        26: 2,  # 'p'\n        7: 3,  # 'r'\n        8: 1,  # 's'\n        9: 2,  # 't'\n        14: 0,  # 'u'\n        32: 1,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 1,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 2,  # 'ö'\n        17: 2,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 2,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    55: {  # 'Ü'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 2,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 1,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 1,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 2,  # 'a'\n        21: 0,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 2,  # 'e'\n        18: 0,  # 'f'\n        27: 1,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 0,  # 'j'\n        10: 0,  # 'k'\n        5: 1,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        15: 0,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 1,  # 't'\n        14: 2,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 1,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 1,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 0,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 0,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    59: {  # 'â'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 1,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 1,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 2,  # 'a'\n        21: 0,  # 'b'\n        28: 0,  # 'c'\n        12: 0,  # 'd'\n        2: 2,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 0,  # 'j'\n        10: 0,  # 'k'\n        5: 0,  # 'l'\n        13: 2,  # 'm'\n        4: 0,  # 'n'\n        15: 1,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 2,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 1,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 1,  # 'ı'\n        40: 1,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    33: {  # 'ç'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 3,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 1,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 2,  # 'T'\n        51: 0,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 0,  # 'Z'\n        1: 0,  # 'a'\n        21: 3,  # 'b'\n        28: 0,  # 'c'\n        12: 2,  # 'd'\n        2: 0,  # 'e'\n        18: 2,  # 'f'\n        27: 1,  # 'g'\n        25: 3,  # 'h'\n        3: 3,  # 'i'\n        24: 0,  # 'j'\n        10: 3,  # 'k'\n        5: 0,  # 'l'\n        13: 0,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 1,  # 'p'\n        7: 3,  # 'r'\n        8: 2,  # 's'\n        9: 3,  # 't'\n        14: 0,  # 'u'\n        32: 2,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 2,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 1,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    61: {  # 'î'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 0,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 0,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 1,  # 'Z'\n        1: 2,  # 'a'\n        21: 0,  # 'b'\n        28: 0,  # 'c'\n        12: 0,  # 'd'\n        2: 2,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 1,  # 'j'\n        10: 0,  # 'k'\n        5: 0,  # 'l'\n        13: 1,  # 'm'\n        4: 1,  # 'n'\n        15: 0,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 1,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 1,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 1,  # 'î'\n        34: 0,  # 'ö'\n        17: 0,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 1,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    34: {  # 'ö'\n        23: 0,  # 'A'\n        37: 1,  # 'B'\n        47: 1,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 2,  # 'F'\n        36: 1,  # 'G'\n        45: 1,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 3,  # 'K'\n        49: 1,  # 'L'\n        20: 0,  # 'M'\n        46: 1,  # 'N'\n        42: 1,  # 'O'\n        48: 2,  # 'P'\n        44: 1,  # 'R'\n        35: 1,  # 'S'\n        31: 1,  # 'T'\n        51: 1,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 1,  # 'Z'\n        1: 3,  # 'a'\n        21: 1,  # 'b'\n        28: 2,  # 'c'\n        12: 1,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 2,  # 'g'\n        25: 2,  # 'h'\n        3: 1,  # 'i'\n        24: 2,  # 'j'\n        10: 1,  # 'k'\n        5: 2,  # 'l'\n        13: 3,  # 'm'\n        4: 2,  # 'n'\n        15: 2,  # 'o'\n        26: 0,  # 'p'\n        7: 0,  # 'r'\n        8: 3,  # 's'\n        9: 1,  # 't'\n        14: 3,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 1,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 1,  # 'Ç'\n        50: 2,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 2,  # 'ç'\n        61: 0,  # 'î'\n        34: 2,  # 'ö'\n        17: 0,  # 'ü'\n        30: 2,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 1,  # 'ı'\n        40: 2,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    17: {  # 'ü'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 1,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 0,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 1,  # 'J'\n        16: 1,  # 'K'\n        49: 0,  # 'L'\n        20: 1,  # 'M'\n        46: 0,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 1,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 0,  # 'Y'\n        56: 1,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 0,  # 'c'\n        12: 1,  # 'd'\n        2: 3,  # 'e'\n        18: 1,  # 'f'\n        27: 2,  # 'g'\n        25: 0,  # 'h'\n        3: 1,  # 'i'\n        24: 1,  # 'j'\n        10: 2,  # 'k'\n        5: 3,  # 'l'\n        13: 2,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 2,  # 'p'\n        7: 2,  # 'r'\n        8: 3,  # 's'\n        9: 2,  # 't'\n        14: 3,  # 'u'\n        32: 1,  # 'v'\n        57: 1,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 2,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 2,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    30: {  # 'ğ'\n        23: 0,  # 'A'\n        37: 2,  # 'B'\n        47: 1,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 2,  # 'F'\n        36: 1,  # 'G'\n        45: 0,  # 'H'\n        53: 1,  # 'I'\n        60: 0,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 1,  # 'M'\n        46: 2,  # 'N'\n        42: 2,  # 'O'\n        48: 1,  # 'P'\n        44: 1,  # 'R'\n        35: 0,  # 'S'\n        31: 1,  # 'T'\n        51: 0,  # 'U'\n        38: 2,  # 'V'\n        62: 0,  # 'W'\n        43: 2,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 0,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 2,  # 'e'\n        18: 0,  # 'f'\n        27: 0,  # 'g'\n        25: 0,  # 'h'\n        3: 0,  # 'i'\n        24: 3,  # 'j'\n        10: 1,  # 'k'\n        5: 2,  # 'l'\n        13: 3,  # 'm'\n        4: 0,  # 'n'\n        15: 1,  # 'o'\n        26: 0,  # 'p'\n        7: 1,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 3,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 2,  # 'Ç'\n        50: 2,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 0,  # 'î'\n        34: 2,  # 'ö'\n        17: 0,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 2,  # 'İ'\n        6: 2,  # 'ı'\n        40: 2,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    41: {  # 'İ'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 1,  # 'C'\n        39: 1,  # 'D'\n        29: 1,  # 'E'\n        52: 0,  # 'F'\n        36: 2,  # 'G'\n        45: 2,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 2,  # 'M'\n        46: 1,  # 'N'\n        42: 1,  # 'O'\n        48: 2,  # 'P'\n        44: 0,  # 'R'\n        35: 1,  # 'S'\n        31: 1,  # 'T'\n        51: 1,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 2,  # 'Y'\n        56: 0,  # 'Z'\n        1: 1,  # 'a'\n        21: 2,  # 'b'\n        28: 1,  # 'c'\n        12: 2,  # 'd'\n        2: 1,  # 'e'\n        18: 0,  # 'f'\n        27: 3,  # 'g'\n        25: 2,  # 'h'\n        3: 2,  # 'i'\n        24: 2,  # 'j'\n        10: 2,  # 'k'\n        5: 0,  # 'l'\n        13: 1,  # 'm'\n        4: 3,  # 'n'\n        15: 1,  # 'o'\n        26: 1,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 2,  # 't'\n        14: 0,  # 'u'\n        32: 0,  # 'v'\n        57: 1,  # 'w'\n        58: 0,  # 'x'\n        11: 2,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 1,  # 'Ü'\n        59: 1,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 1,  # 'ö'\n        17: 1,  # 'ü'\n        30: 2,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n    6: {  # 'ı'\n        23: 2,  # 'A'\n        37: 0,  # 'B'\n        47: 0,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 0,  # 'F'\n        36: 1,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 2,  # 'J'\n        16: 3,  # 'K'\n        49: 0,  # 'L'\n        20: 3,  # 'M'\n        46: 1,  # 'N'\n        42: 0,  # 'O'\n        48: 0,  # 'P'\n        44: 0,  # 'R'\n        35: 0,  # 'S'\n        31: 2,  # 'T'\n        51: 0,  # 'U'\n        38: 0,  # 'V'\n        62: 0,  # 'W'\n        43: 2,  # 'Y'\n        56: 1,  # 'Z'\n        1: 3,  # 'a'\n        21: 2,  # 'b'\n        28: 1,  # 'c'\n        12: 3,  # 'd'\n        2: 3,  # 'e'\n        18: 3,  # 'f'\n        27: 3,  # 'g'\n        25: 2,  # 'h'\n        3: 3,  # 'i'\n        24: 3,  # 'j'\n        10: 3,  # 'k'\n        5: 3,  # 'l'\n        13: 3,  # 'm'\n        4: 3,  # 'n'\n        15: 0,  # 'o'\n        26: 3,  # 'p'\n        7: 3,  # 'r'\n        8: 3,  # 's'\n        9: 3,  # 't'\n        14: 3,  # 'u'\n        32: 3,  # 'v'\n        57: 1,  # 'w'\n        58: 1,  # 'x'\n        11: 3,  # 'y'\n        22: 0,  # 'z'\n        63: 1,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 2,  # 'ç'\n        61: 0,  # 'î'\n        34: 0,  # 'ö'\n        17: 3,  # 'ü'\n        30: 0,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 3,  # 'ı'\n        40: 0,  # 'Ş'\n        19: 0,  # 'ş'\n    },\n    40: {  # 'Ş'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 1,  # 'C'\n        39: 1,  # 'D'\n        29: 1,  # 'E'\n        52: 0,  # 'F'\n        36: 1,  # 'G'\n        45: 2,  # 'H'\n        53: 1,  # 'I'\n        60: 0,  # 'J'\n        16: 0,  # 'K'\n        49: 0,  # 'L'\n        20: 2,  # 'M'\n        46: 1,  # 'N'\n        42: 1,  # 'O'\n        48: 2,  # 'P'\n        44: 2,  # 'R'\n        35: 1,  # 'S'\n        31: 1,  # 'T'\n        51: 0,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 2,  # 'Y'\n        56: 1,  # 'Z'\n        1: 0,  # 'a'\n        21: 2,  # 'b'\n        28: 0,  # 'c'\n        12: 2,  # 'd'\n        2: 0,  # 'e'\n        18: 3,  # 'f'\n        27: 0,  # 'g'\n        25: 2,  # 'h'\n        3: 3,  # 'i'\n        24: 2,  # 'j'\n        10: 1,  # 'k'\n        5: 0,  # 'l'\n        13: 1,  # 'm'\n        4: 3,  # 'n'\n        15: 2,  # 'o'\n        26: 0,  # 'p'\n        7: 3,  # 'r'\n        8: 2,  # 's'\n        9: 2,  # 't'\n        14: 1,  # 'u'\n        32: 3,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 2,  # 'y'\n        22: 0,  # 'z'\n        63: 0,  # '·'\n        54: 0,  # 'Ç'\n        50: 0,  # 'Ö'\n        55: 1,  # 'Ü'\n        59: 0,  # 'â'\n        33: 0,  # 'ç'\n        61: 0,  # 'î'\n        34: 2,  # 'ö'\n        17: 1,  # 'ü'\n        30: 2,  # 'ğ'\n        41: 0,  # 'İ'\n        6: 2,  # 'ı'\n        40: 1,  # 'Ş'\n        19: 2,  # 'ş'\n    },\n    19: {  # 'ş'\n        23: 0,  # 'A'\n        37: 0,  # 'B'\n        47: 1,  # 'C'\n        39: 0,  # 'D'\n        29: 0,  # 'E'\n        52: 2,  # 'F'\n        36: 1,  # 'G'\n        45: 0,  # 'H'\n        53: 0,  # 'I'\n        60: 0,  # 'J'\n        16: 3,  # 'K'\n        49: 2,  # 'L'\n        20: 0,  # 'M'\n        46: 1,  # 'N'\n        42: 1,  # 'O'\n        48: 1,  # 'P'\n        44: 1,  # 'R'\n        35: 1,  # 'S'\n        31: 0,  # 'T'\n        51: 1,  # 'U'\n        38: 1,  # 'V'\n        62: 0,  # 'W'\n        43: 1,  # 'Y'\n        56: 0,  # 'Z'\n        1: 3,  # 'a'\n        21: 1,  # 'b'\n        28: 2,  # 'c'\n        12: 0,  # 'd'\n        2: 3,  # 'e'\n        18: 0,  # 'f'\n        27: 2,  # 'g'\n        25: 1,  # 'h'\n        3: 1,  # 'i'\n        24: 0,  # 'j'\n        10: 2,  # 'k'\n        5: 2,  # 'l'\n        13: 3,  # 'm'\n        4: 0,  # 'n'\n        15: 0,  # 'o'\n        26: 1,  # 'p'\n        7: 3,  # 'r'\n        8: 0,  # 's'\n        9: 0,  # 't'\n        14: 3,  # 'u'\n        32: 0,  # 'v'\n        57: 0,  # 'w'\n        58: 0,  # 'x'\n        11: 0,  # 'y'\n        22: 2,  # 'z'\n        63: 0,  # '·'\n        54: 1,  # 'Ç'\n        50: 2,  # 'Ö'\n        55: 0,  # 'Ü'\n        59: 0,  # 'â'\n        33: 1,  # 'ç'\n        61: 1,  # 'î'\n        34: 2,  # 'ö'\n        17: 0,  # 'ü'\n        30: 1,  # 'ğ'\n        41: 1,  # 'İ'\n        6: 1,  # 'ı'\n        40: 1,  # 'Ş'\n        19: 1,  # 'ş'\n    },\n}\n\n# 255: Undefined characters that did not exist in training text\n# 254: Carriage/Return\n# 253: symbol (punctuation) that does not belong to word\n# 252: 0 - 9\n# 251: Control characters\n\n# Character Mapping Table(s):\nISO_8859_9_TURKISH_CHAR_TO_ORDER = {\n    0: 255,  # '\\x00'\n    1: 255,  # '\\x01'\n    2: 255,  # '\\x02'\n    3: 255,  # '\\x03'\n    4: 255,  # '\\x04'\n    5: 255,  # '\\x05'\n    6: 255,  # '\\x06'\n    7: 255,  # '\\x07'\n    8: 255,  # '\\x08'\n    9: 255,  # '\\t'\n    10: 255,  # '\\n'\n    11: 255,  # '\\x0b'\n    12: 255,  # '\\x0c'\n    13: 255,  # '\\r'\n    14: 255,  # '\\x0e'\n    15: 255,  # '\\x0f'\n    16: 255,  # '\\x10'\n    17: 255,  # '\\x11'\n    18: 255,  # '\\x12'\n    19: 255,  # '\\x13'\n    20: 255,  # '\\x14'\n    21: 255,  # '\\x15'\n    22: 255,  # '\\x16'\n    23: 255,  # '\\x17'\n    24: 255,  # '\\x18'\n    25: 255,  # '\\x19'\n    26: 255,  # '\\x1a'\n    27: 255,  # '\\x1b'\n    28: 255,  # '\\x1c'\n    29: 255,  # '\\x1d'\n    30: 255,  # '\\x1e'\n    31: 255,  # '\\x1f'\n    32: 255,  # ' '\n    33: 255,  # '!'\n    34: 255,  # '\"'\n    35: 255,  # '#'\n    36: 255,  # '$'\n    37: 255,  # '%'\n    38: 255,  # '&'\n    39: 255,  # \"'\"\n    40: 255,  # '('\n    41: 255,  # ')'\n    42: 255,  # '*'\n    43: 255,  # '+'\n    44: 255,  # ','\n    45: 255,  # '-'\n    46: 255,  # '.'\n    47: 255,  # '/'\n    48: 255,  # '0'\n    49: 255,  # '1'\n    50: 255,  # '2'\n    51: 255,  # '3'\n    52: 255,  # '4'\n    53: 255,  # '5'\n    54: 255,  # '6'\n    55: 255,  # '7'\n    56: 255,  # '8'\n    57: 255,  # '9'\n    58: 255,  # ':'\n    59: 255,  # ';'\n    60: 255,  # '<'\n    61: 255,  # '='\n    62: 255,  # '>'\n    63: 255,  # '?'\n    64: 255,  # '@'\n    65: 23,  # 'A'\n    66: 37,  # 'B'\n    67: 47,  # 'C'\n    68: 39,  # 'D'\n    69: 29,  # 'E'\n    70: 52,  # 'F'\n    71: 36,  # 'G'\n    72: 45,  # 'H'\n    73: 53,  # 'I'\n    74: 60,  # 'J'\n    75: 16,  # 'K'\n    76: 49,  # 'L'\n    77: 20,  # 'M'\n    78: 46,  # 'N'\n    79: 42,  # 'O'\n    80: 48,  # 'P'\n    81: 69,  # 'Q'\n    82: 44,  # 'R'\n    83: 35,  # 'S'\n    84: 31,  # 'T'\n    85: 51,  # 'U'\n    86: 38,  # 'V'\n    87: 62,  # 'W'\n    88: 65,  # 'X'\n    89: 43,  # 'Y'\n    90: 56,  # 'Z'\n    91: 255,  # '['\n    92: 255,  # '\\\\'\n    93: 255,  # ']'\n    94: 255,  # '^'\n    95: 255,  # '_'\n    96: 255,  # '`'\n    97: 1,  # 'a'\n    98: 21,  # 'b'\n    99: 28,  # 'c'\n    100: 12,  # 'd'\n    101: 2,  # 'e'\n    102: 18,  # 'f'\n    103: 27,  # 'g'\n    104: 25,  # 'h'\n    105: 3,  # 'i'\n    106: 24,  # 'j'\n    107: 10,  # 'k'\n    108: 5,  # 'l'\n    109: 13,  # 'm'\n    110: 4,  # 'n'\n    111: 15,  # 'o'\n    112: 26,  # 'p'\n    113: 64,  # 'q'\n    114: 7,  # 'r'\n    115: 8,  # 's'\n    116: 9,  # 't'\n    117: 14,  # 'u'\n    118: 32,  # 'v'\n    119: 57,  # 'w'\n    120: 58,  # 'x'\n    121: 11,  # 'y'\n    122: 22,  # 'z'\n    123: 255,  # '{'\n    124: 255,  # '|'\n    125: 255,  # '}'\n    126: 255,  # '~'\n    127: 255,  # '\\x7f'\n    128: 180,  # '\\x80'\n    129: 179,  # '\\x81'\n    130: 178,  # '\\x82'\n    131: 177,  # '\\x83'\n    132: 176,  # '\\x84'\n    133: 175,  # '\\x85'\n    134: 174,  # '\\x86'\n    135: 173,  # '\\x87'\n    136: 172,  # '\\x88'\n    137: 171,  # '\\x89'\n    138: 170,  # '\\x8a'\n    139: 169,  # '\\x8b'\n    140: 168,  # '\\x8c'\n    141: 167,  # '\\x8d'\n    142: 166,  # '\\x8e'\n    143: 165,  # '\\x8f'\n    144: 164,  # '\\x90'\n    145: 163,  # '\\x91'\n    146: 162,  # '\\x92'\n    147: 161,  # '\\x93'\n    148: 160,  # '\\x94'\n    149: 159,  # '\\x95'\n    150: 101,  # '\\x96'\n    151: 158,  # '\\x97'\n    152: 157,  # '\\x98'\n    153: 156,  # '\\x99'\n    154: 155,  # '\\x9a'\n    155: 154,  # '\\x9b'\n    156: 153,  # '\\x9c'\n    157: 152,  # '\\x9d'\n    158: 151,  # '\\x9e'\n    159: 106,  # '\\x9f'\n    160: 150,  # '\\xa0'\n    161: 149,  # '¡'\n    162: 148,  # '¢'\n    163: 147,  # '£'\n    164: 146,  # '¤'\n    165: 145,  # '¥'\n    166: 144,  # '¦'\n    167: 100,  # '§'\n    168: 143,  # '¨'\n    169: 142,  # '©'\n    170: 141,  # 'ª'\n    171: 140,  # '«'\n    172: 139,  # '¬'\n    173: 138,  # '\\xad'\n    174: 137,  # '®'\n    175: 136,  # '¯'\n    176: 94,  # '°'\n    177: 80,  # '±'\n    178: 93,  # '²'\n    179: 135,  # '³'\n    180: 105,  # '´'\n    181: 134,  # 'µ'\n    182: 133,  # '¶'\n    183: 63,  # '·'\n    184: 132,  # '¸'\n    185: 131,  # '¹'\n    186: 130,  # 'º'\n    187: 129,  # '»'\n    188: 128,  # '¼'\n    189: 127,  # '½'\n    190: 126,  # '¾'\n    191: 125,  # '¿'\n    192: 124,  # 'À'\n    193: 104,  # 'Á'\n    194: 73,  # 'Â'\n    195: 99,  # 'Ã'\n    196: 79,  # 'Ä'\n    197: 85,  # 'Å'\n    198: 123,  # 'Æ'\n    199: 54,  # 'Ç'\n    200: 122,  # 'È'\n    201: 98,  # 'É'\n    202: 92,  # 'Ê'\n    203: 121,  # 'Ë'\n    204: 120,  # 'Ì'\n    205: 91,  # 'Í'\n    206: 103,  # 'Î'\n    207: 119,  # 'Ï'\n    208: 68,  # 'Ğ'\n    209: 118,  # 'Ñ'\n    210: 117,  # 'Ò'\n    211: 97,  # 'Ó'\n    212: 116,  # 'Ô'\n    213: 115,  # 'Õ'\n    214: 50,  # 'Ö'\n    215: 90,  # '×'\n    216: 114,  # 'Ø'\n    217: 113,  # 'Ù'\n    218: 112,  # 'Ú'\n    219: 111,  # 'Û'\n    220: 55,  # 'Ü'\n    221: 41,  # 'İ'\n    222: 40,  # 'Ş'\n    223: 86,  # 'ß'\n    224: 89,  # 'à'\n    225: 70,  # 'á'\n    226: 59,  # 'â'\n    227: 78,  # 'ã'\n    228: 71,  # 'ä'\n    229: 82,  # 'å'\n    230: 88,  # 'æ'\n    231: 33,  # 'ç'\n    232: 77,  # 'è'\n    233: 66,  # 'é'\n    234: 84,  # 'ê'\n    235: 83,  # 'ë'\n    236: 110,  # 'ì'\n    237: 75,  # 'í'\n    238: 61,  # 'î'\n    239: 96,  # 'ï'\n    240: 30,  # 'ğ'\n    241: 67,  # 'ñ'\n    242: 109,  # 'ò'\n    243: 74,  # 'ó'\n    244: 87,  # 'ô'\n    245: 102,  # 'õ'\n    246: 34,  # 'ö'\n    247: 95,  # '÷'\n    248: 81,  # 'ø'\n    249: 108,  # 'ù'\n    250: 76,  # 'ú'\n    251: 72,  # 'û'\n    252: 17,  # 'ü'\n    253: 6,  # 'ı'\n    254: 19,  # 'ş'\n    255: 107,  # 'ÿ'\n}\n\nISO_8859_9_TURKISH_MODEL = SingleByteCharSetModel(\n    charset_name=\"ISO-8859-9\",\n    language=\"Turkish\",\n    char_to_order_map=ISO_8859_9_TURKISH_CHAR_TO_ORDER,\n    language_model=TURKISH_LANG_MODEL,\n    typical_positive_ratio=0.97029,\n    keep_ascii_letters=True,\n    alphabet=\"ABCDEFGHIJKLMNOPRSTUVYZabcdefghijklmnoprstuvyzÂÇÎÖÛÜâçîöûüĞğİıŞş\",\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/latin1prober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Universal charset detector code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 2001\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#   Shy Shalom - original C code\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .charsetprober import CharSetProber\nfrom .enums import ProbingState\n\nFREQ_CAT_NUM = 4\n\nUDF = 0  # undefined\nOTH = 1  # other\nASC = 2  # ascii capital letter\nASS = 3  # ascii small letter\nACV = 4  # accent capital vowel\nACO = 5  # accent capital other\nASV = 6  # accent small vowel\nASO = 7  # accent small other\nCLASS_NUM = 8  # total classes\n\n# fmt: off\nLatin1_CharToClass = (\n    OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH,   # 00 - 07\n    OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH,   # 08 - 0F\n    OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH,   # 10 - 17\n    OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH,   # 18 - 1F\n    OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH,   # 20 - 27\n    OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH,   # 28 - 2F\n    OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH,   # 30 - 37\n    OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH,   # 38 - 3F\n    OTH, ASC, ASC, ASC, ASC, ASC, ASC, ASC,   # 40 - 47\n    ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC,   # 48 - 4F\n    ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC,   # 50 - 57\n    ASC, ASC, ASC, OTH, OTH, OTH, OTH, OTH,   # 58 - 5F\n    OTH, ASS, ASS, ASS, ASS, ASS, ASS, ASS,   # 60 - 67\n    ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS,   # 68 - 6F\n    ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS,   # 70 - 77\n    ASS, ASS, ASS, OTH, OTH, OTH, OTH, OTH,   # 78 - 7F\n    OTH, UDF, OTH, ASO, OTH, OTH, OTH, OTH,   # 80 - 87\n    OTH, OTH, ACO, OTH, ACO, UDF, ACO, UDF,   # 88 - 8F\n    UDF, OTH, OTH, OTH, OTH, OTH, OTH, OTH,   # 90 - 97\n    OTH, OTH, ASO, OTH, ASO, UDF, ASO, ACO,   # 98 - 9F\n    OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH,   # A0 - A7\n    OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH,   # A8 - AF\n    OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH,   # B0 - B7\n    OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH,   # B8 - BF\n    ACV, ACV, ACV, ACV, ACV, ACV, ACO, ACO,   # C0 - C7\n    ACV, ACV, ACV, ACV, ACV, ACV, ACV, ACV,   # C8 - CF\n    ACO, ACO, ACV, ACV, ACV, ACV, ACV, OTH,   # D0 - D7\n    ACV, ACV, ACV, ACV, ACV, ACO, ACO, ACO,   # D8 - DF\n    ASV, ASV, ASV, ASV, ASV, ASV, ASO, ASO,   # E0 - E7\n    ASV, ASV, ASV, ASV, ASV, ASV, ASV, ASV,   # E8 - EF\n    ASO, ASO, ASV, ASV, ASV, ASV, ASV, OTH,   # F0 - F7\n    ASV, ASV, ASV, ASV, ASV, ASO, ASO, ASO,   # F8 - FF\n)\n\n# 0 : illegal\n# 1 : very unlikely\n# 2 : normal\n# 3 : very likely\nLatin1ClassModel = (\n# UDF OTH ASC ASS ACV ACO ASV ASO\n    0,  0,  0,  0,  0,  0,  0,  0,  # UDF\n    0,  3,  3,  3,  3,  3,  3,  3,  # OTH\n    0,  3,  3,  3,  3,  3,  3,  3,  # ASC\n    0,  3,  3,  3,  1,  1,  3,  3,  # ASS\n    0,  3,  3,  3,  1,  2,  1,  2,  # ACV\n    0,  3,  3,  3,  3,  3,  3,  3,  # ACO\n    0,  3,  1,  3,  1,  1,  1,  3,  # ASV\n    0,  3,  1,  3,  1,  1,  3,  3,  # ASO\n)\n# fmt: on\n\n\nclass Latin1Prober(CharSetProber):\n    def __init__(self):\n        super().__init__()\n        self._last_char_class = None\n        self._freq_counter = None\n        self.reset()\n\n    def reset(self):\n        self._last_char_class = OTH\n        self._freq_counter = [0] * FREQ_CAT_NUM\n        super().reset()\n\n    @property\n    def charset_name(self):\n        return \"ISO-8859-1\"\n\n    @property\n    def language(self):\n        return \"\"\n\n    def feed(self, byte_str):\n        byte_str = self.remove_xml_tags(byte_str)\n        for c in byte_str:\n            char_class = Latin1_CharToClass[c]\n            freq = Latin1ClassModel[(self._last_char_class * CLASS_NUM) + char_class]\n            if freq == 0:\n                self._state = ProbingState.NOT_ME\n                break\n            self._freq_counter[freq] += 1\n            self._last_char_class = char_class\n\n        return self.state\n\n    def get_confidence(self):\n        if self.state == ProbingState.NOT_ME:\n            return 0.01\n\n        total = sum(self._freq_counter)\n        confidence = (\n            0.0\n            if total < 0.01\n            else (self._freq_counter[3] - self._freq_counter[1] * 20.0) / total\n        )\n        confidence = max(confidence, 0.0)\n        # lower the confidence of latin1 so that other more accurate\n        # detector can take priority.\n        confidence *= 0.73\n        return confidence\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/mbcharsetprober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Universal charset detector code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 2001\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#   Shy Shalom - original C code\n#   Proofpoint, Inc.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .charsetprober import CharSetProber\nfrom .enums import MachineState, ProbingState\n\n\nclass MultiByteCharSetProber(CharSetProber):\n    \"\"\"\n    MultiByteCharSetProber\n    \"\"\"\n\n    def __init__(self, lang_filter=None):\n        super().__init__(lang_filter=lang_filter)\n        self.distribution_analyzer = None\n        self.coding_sm = None\n        self._last_char = [0, 0]\n\n    def reset(self):\n        super().reset()\n        if self.coding_sm:\n            self.coding_sm.reset()\n        if self.distribution_analyzer:\n            self.distribution_analyzer.reset()\n        self._last_char = [0, 0]\n\n    @property\n    def charset_name(self):\n        raise NotImplementedError\n\n    @property\n    def language(self):\n        raise NotImplementedError\n\n    def feed(self, byte_str):\n        for i, byte in enumerate(byte_str):\n            coding_state = self.coding_sm.next_state(byte)\n            if coding_state == MachineState.ERROR:\n                self.logger.debug(\n                    \"%s %s prober hit error at byte %s\",\n                    self.charset_name,\n                    self.language,\n                    i,\n                )\n                self._state = ProbingState.NOT_ME\n                break\n            if coding_state == MachineState.ITS_ME:\n                self._state = ProbingState.FOUND_IT\n                break\n            if coding_state == MachineState.START:\n                char_len = self.coding_sm.get_current_charlen()\n                if i == 0:\n                    self._last_char[1] = byte\n                    self.distribution_analyzer.feed(self._last_char, char_len)\n                else:\n                    self.distribution_analyzer.feed(byte_str[i - 1 : i + 1], char_len)\n\n        self._last_char[0] = byte_str[-1]\n\n        if self.state == ProbingState.DETECTING:\n            if self.distribution_analyzer.got_enough_data() and (\n                self.get_confidence() > self.SHORTCUT_THRESHOLD\n            ):\n                self._state = ProbingState.FOUND_IT\n\n        return self.state\n\n    def get_confidence(self):\n        return self.distribution_analyzer.get_confidence()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/mbcsgroupprober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Universal charset detector code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 2001\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#   Shy Shalom - original C code\n#   Proofpoint, Inc.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .big5prober import Big5Prober\nfrom .charsetgroupprober import CharSetGroupProber\nfrom .cp949prober import CP949Prober\nfrom .eucjpprober import EUCJPProber\nfrom .euckrprober import EUCKRProber\nfrom .euctwprober import EUCTWProber\nfrom .gb2312prober import GB2312Prober\nfrom .johabprober import JOHABProber\nfrom .sjisprober import SJISProber\nfrom .utf8prober import UTF8Prober\n\n\nclass MBCSGroupProber(CharSetGroupProber):\n    def __init__(self, lang_filter=None):\n        super().__init__(lang_filter=lang_filter)\n        self.probers = [\n            UTF8Prober(),\n            SJISProber(),\n            EUCJPProber(),\n            GB2312Prober(),\n            EUCKRProber(),\n            CP949Prober(),\n            Big5Prober(),\n            EUCTWProber(),\n            JOHABProber(),\n        ]\n        self.reset()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/mbcssm.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is mozilla.org code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .enums import MachineState\n\n# BIG5\n\n# fmt: off\nBIG5_CLS = (\n    1, 1, 1, 1, 1, 1, 1, 1,  # 00 - 07    #allow 0x00 as legal value\n    1, 1, 1, 1, 1, 1, 0, 0,  # 08 - 0f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 10 - 17\n    1, 1, 1, 0, 1, 1, 1, 1,  # 18 - 1f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 20 - 27\n    1, 1, 1, 1, 1, 1, 1, 1,  # 28 - 2f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 30 - 37\n    1, 1, 1, 1, 1, 1, 1, 1,  # 38 - 3f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 40 - 47\n    2, 2, 2, 2, 2, 2, 2, 2,  # 48 - 4f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 50 - 57\n    2, 2, 2, 2, 2, 2, 2, 2,  # 58 - 5f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 60 - 67\n    2, 2, 2, 2, 2, 2, 2, 2,  # 68 - 6f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 70 - 77\n    2, 2, 2, 2, 2, 2, 2, 1,  # 78 - 7f\n    4, 4, 4, 4, 4, 4, 4, 4,  # 80 - 87\n    4, 4, 4, 4, 4, 4, 4, 4,  # 88 - 8f\n    4, 4, 4, 4, 4, 4, 4, 4,  # 90 - 97\n    4, 4, 4, 4, 4, 4, 4, 4,  # 98 - 9f\n    4, 3, 3, 3, 3, 3, 3, 3,  # a0 - a7\n    3, 3, 3, 3, 3, 3, 3, 3,  # a8 - af\n    3, 3, 3, 3, 3, 3, 3, 3,  # b0 - b7\n    3, 3, 3, 3, 3, 3, 3, 3,  # b8 - bf\n    3, 3, 3, 3, 3, 3, 3, 3,  # c0 - c7\n    3, 3, 3, 3, 3, 3, 3, 3,  # c8 - cf\n    3, 3, 3, 3, 3, 3, 3, 3,  # d0 - d7\n    3, 3, 3, 3, 3, 3, 3, 3,  # d8 - df\n    3, 3, 3, 3, 3, 3, 3, 3,  # e0 - e7\n    3, 3, 3, 3, 3, 3, 3, 3,  # e8 - ef\n    3, 3, 3, 3, 3, 3, 3, 3,  # f0 - f7\n    3, 3, 3, 3, 3, 3, 3, 0  # f8 - ff\n)\n\nBIG5_ST = (\n    MachineState.ERROR,MachineState.START,MachineState.START,     3,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#00-07\n    MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ERROR,#08-0f\n    MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START#10-17\n)\n# fmt: on\n\nBIG5_CHAR_LEN_TABLE = (0, 1, 1, 2, 0)\n\nBIG5_SM_MODEL = {\n    \"class_table\": BIG5_CLS,\n    \"class_factor\": 5,\n    \"state_table\": BIG5_ST,\n    \"char_len_table\": BIG5_CHAR_LEN_TABLE,\n    \"name\": \"Big5\",\n}\n\n# CP949\n# fmt: off\nCP949_CLS  = (\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0,  # 00 - 0f\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1,  # 10 - 1f\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  # 20 - 2f\n    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  # 30 - 3f\n    1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,  # 40 - 4f\n    4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 1, 1, 1,  # 50 - 5f\n    1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,  # 60 - 6f\n    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 1, 1, 1,  # 70 - 7f\n    0, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,  # 80 - 8f\n    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,  # 90 - 9f\n    6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,  # a0 - af\n    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,  # b0 - bf\n    7, 7, 7, 7, 7, 7, 9, 2, 2, 3, 2, 2, 2, 2, 2, 2,  # c0 - cf\n    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,  # d0 - df\n    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,  # e0 - ef\n    2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0,  # f0 - ff\n)\n\nCP949_ST = (\n#cls=    0      1      2      3      4      5      6      7      8      9  # previous state =\n    MachineState.ERROR,MachineState.START,     3,MachineState.ERROR,MachineState.START,MachineState.START,     4,     5,MachineState.ERROR,     6, # MachineState.START\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR, # MachineState.ERROR\n    MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME, # MachineState.ITS_ME\n    MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START, # 3\n    MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START, # 4\n    MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START, # 5\n    MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START, # 6\n)\n# fmt: on\n\nCP949_CHAR_LEN_TABLE = (0, 1, 2, 0, 1, 1, 2, 2, 0, 2)\n\nCP949_SM_MODEL = {\n    \"class_table\": CP949_CLS,\n    \"class_factor\": 10,\n    \"state_table\": CP949_ST,\n    \"char_len_table\": CP949_CHAR_LEN_TABLE,\n    \"name\": \"CP949\",\n}\n\n# EUC-JP\n# fmt: off\nEUCJP_CLS = (\n    4, 4, 4, 4, 4, 4, 4, 4,  # 00 - 07\n    4, 4, 4, 4, 4, 4, 5, 5,  # 08 - 0f\n    4, 4, 4, 4, 4, 4, 4, 4,  # 10 - 17\n    4, 4, 4, 5, 4, 4, 4, 4,  # 18 - 1f\n    4, 4, 4, 4, 4, 4, 4, 4,  # 20 - 27\n    4, 4, 4, 4, 4, 4, 4, 4,  # 28 - 2f\n    4, 4, 4, 4, 4, 4, 4, 4,  # 30 - 37\n    4, 4, 4, 4, 4, 4, 4, 4,  # 38 - 3f\n    4, 4, 4, 4, 4, 4, 4, 4,  # 40 - 47\n    4, 4, 4, 4, 4, 4, 4, 4,  # 48 - 4f\n    4, 4, 4, 4, 4, 4, 4, 4,  # 50 - 57\n    4, 4, 4, 4, 4, 4, 4, 4,  # 58 - 5f\n    4, 4, 4, 4, 4, 4, 4, 4,  # 60 - 67\n    4, 4, 4, 4, 4, 4, 4, 4,  # 68 - 6f\n    4, 4, 4, 4, 4, 4, 4, 4,  # 70 - 77\n    4, 4, 4, 4, 4, 4, 4, 4,  # 78 - 7f\n    5, 5, 5, 5, 5, 5, 5, 5,  # 80 - 87\n    5, 5, 5, 5, 5, 5, 1, 3,  # 88 - 8f\n    5, 5, 5, 5, 5, 5, 5, 5,  # 90 - 97\n    5, 5, 5, 5, 5, 5, 5, 5,  # 98 - 9f\n    5, 2, 2, 2, 2, 2, 2, 2,  # a0 - a7\n    2, 2, 2, 2, 2, 2, 2, 2,  # a8 - af\n    2, 2, 2, 2, 2, 2, 2, 2,  # b0 - b7\n    2, 2, 2, 2, 2, 2, 2, 2,  # b8 - bf\n    2, 2, 2, 2, 2, 2, 2, 2,  # c0 - c7\n    2, 2, 2, 2, 2, 2, 2, 2,  # c8 - cf\n    2, 2, 2, 2, 2, 2, 2, 2,  # d0 - d7\n    2, 2, 2, 2, 2, 2, 2, 2,  # d8 - df\n    0, 0, 0, 0, 0, 0, 0, 0,  # e0 - e7\n    0, 0, 0, 0, 0, 0, 0, 0,  # e8 - ef\n    0, 0, 0, 0, 0, 0, 0, 0,  # f0 - f7\n    0, 0, 0, 0, 0, 0, 0, 5  # f8 - ff\n)\n\nEUCJP_ST = (\n          3,     4,     3,     5,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#00-07\n     MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,#08-0f\n     MachineState.ITS_ME,MachineState.ITS_ME,MachineState.START,MachineState.ERROR,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#10-17\n     MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,     3,MachineState.ERROR,#18-1f\n          3,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START#20-27\n)\n# fmt: on\n\nEUCJP_CHAR_LEN_TABLE = (2, 2, 2, 3, 1, 0)\n\nEUCJP_SM_MODEL = {\n    \"class_table\": EUCJP_CLS,\n    \"class_factor\": 6,\n    \"state_table\": EUCJP_ST,\n    \"char_len_table\": EUCJP_CHAR_LEN_TABLE,\n    \"name\": \"EUC-JP\",\n}\n\n# EUC-KR\n# fmt: off\nEUCKR_CLS  = (\n    1, 1, 1, 1, 1, 1, 1, 1,  # 00 - 07\n    1, 1, 1, 1, 1, 1, 0, 0,  # 08 - 0f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 10 - 17\n    1, 1, 1, 0, 1, 1, 1, 1,  # 18 - 1f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 20 - 27\n    1, 1, 1, 1, 1, 1, 1, 1,  # 28 - 2f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 30 - 37\n    1, 1, 1, 1, 1, 1, 1, 1,  # 38 - 3f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 40 - 47\n    1, 1, 1, 1, 1, 1, 1, 1,  # 48 - 4f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 50 - 57\n    1, 1, 1, 1, 1, 1, 1, 1,  # 58 - 5f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 60 - 67\n    1, 1, 1, 1, 1, 1, 1, 1,  # 68 - 6f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 70 - 77\n    1, 1, 1, 1, 1, 1, 1, 1,  # 78 - 7f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 80 - 87\n    0, 0, 0, 0, 0, 0, 0, 0,  # 88 - 8f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 90 - 97\n    0, 0, 0, 0, 0, 0, 0, 0,  # 98 - 9f\n    0, 2, 2, 2, 2, 2, 2, 2,  # a0 - a7\n    2, 2, 2, 2, 2, 3, 3, 3,  # a8 - af\n    2, 2, 2, 2, 2, 2, 2, 2,  # b0 - b7\n    2, 2, 2, 2, 2, 2, 2, 2,  # b8 - bf\n    2, 2, 2, 2, 2, 2, 2, 2,  # c0 - c7\n    2, 3, 2, 2, 2, 2, 2, 2,  # c8 - cf\n    2, 2, 2, 2, 2, 2, 2, 2,  # d0 - d7\n    2, 2, 2, 2, 2, 2, 2, 2,  # d8 - df\n    2, 2, 2, 2, 2, 2, 2, 2,  # e0 - e7\n    2, 2, 2, 2, 2, 2, 2, 2,  # e8 - ef\n    2, 2, 2, 2, 2, 2, 2, 2,  # f0 - f7\n    2, 2, 2, 2, 2, 2, 2, 0   # f8 - ff\n)\n\nEUCKR_ST = (\n    MachineState.ERROR,MachineState.START,     3,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#00-07\n    MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START #08-0f\n)\n# fmt: on\n\nEUCKR_CHAR_LEN_TABLE = (0, 1, 2, 0)\n\nEUCKR_SM_MODEL = {\n    \"class_table\": EUCKR_CLS,\n    \"class_factor\": 4,\n    \"state_table\": EUCKR_ST,\n    \"char_len_table\": EUCKR_CHAR_LEN_TABLE,\n    \"name\": \"EUC-KR\",\n}\n\n# JOHAB\n# fmt: off\nJOHAB_CLS = (\n    4,4,4,4,4,4,4,4,  # 00 - 07\n    4,4,4,4,4,4,0,0,  # 08 - 0f\n    4,4,4,4,4,4,4,4,  # 10 - 17\n    4,4,4,0,4,4,4,4,  # 18 - 1f\n    4,4,4,4,4,4,4,4,  # 20 - 27\n    4,4,4,4,4,4,4,4,  # 28 - 2f\n    4,3,3,3,3,3,3,3,  # 30 - 37\n    3,3,3,3,3,3,3,3,  # 38 - 3f\n    3,1,1,1,1,1,1,1,  # 40 - 47\n    1,1,1,1,1,1,1,1,  # 48 - 4f\n    1,1,1,1,1,1,1,1,  # 50 - 57\n    1,1,1,1,1,1,1,1,  # 58 - 5f\n    1,1,1,1,1,1,1,1,  # 60 - 67\n    1,1,1,1,1,1,1,1,  # 68 - 6f\n    1,1,1,1,1,1,1,1,  # 70 - 77\n    1,1,1,1,1,1,1,2,  # 78 - 7f\n    6,6,6,6,8,8,8,8,  # 80 - 87\n    8,8,8,8,8,8,8,8,  # 88 - 8f\n    8,7,7,7,7,7,7,7,  # 90 - 97\n    7,7,7,7,7,7,7,7,  # 98 - 9f\n    7,7,7,7,7,7,7,7,  # a0 - a7\n    7,7,7,7,7,7,7,7,  # a8 - af\n    7,7,7,7,7,7,7,7,  # b0 - b7\n    7,7,7,7,7,7,7,7,  # b8 - bf\n    7,7,7,7,7,7,7,7,  # c0 - c7\n    7,7,7,7,7,7,7,7,  # c8 - cf\n    7,7,7,7,5,5,5,5,  # d0 - d7\n    5,9,9,9,9,9,9,5,  # d8 - df\n    9,9,9,9,9,9,9,9,  # e0 - e7\n    9,9,9,9,9,9,9,9,  # e8 - ef\n    9,9,9,9,9,9,9,9,  # f0 - f7\n    9,9,5,5,5,5,5,0   # f8 - ff\n)\n\nJOHAB_ST = (\n# cls = 0                   1                   2                   3                   4                   5                   6                   7                   8                   9\n    MachineState.ERROR ,MachineState.START ,MachineState.START ,MachineState.START ,MachineState.START ,MachineState.ERROR ,MachineState.ERROR ,3                  ,3                  ,4                  ,  # MachineState.START\n    MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,  # MachineState.ITS_ME\n    MachineState.ERROR ,MachineState.ERROR ,MachineState.ERROR ,MachineState.ERROR ,MachineState.ERROR ,MachineState.ERROR ,MachineState.ERROR ,MachineState.ERROR ,MachineState.ERROR ,MachineState.ERROR ,  # MachineState.ERROR\n    MachineState.ERROR ,MachineState.START ,MachineState.START ,MachineState.ERROR ,MachineState.ERROR ,MachineState.START ,MachineState.START ,MachineState.START ,MachineState.START ,MachineState.START ,  # 3\n    MachineState.ERROR ,MachineState.START ,MachineState.ERROR ,MachineState.START ,MachineState.ERROR ,MachineState.START ,MachineState.ERROR ,MachineState.START ,MachineState.ERROR ,MachineState.START ,  # 4\n)\n# fmt: on\n\nJOHAB_CHAR_LEN_TABLE = (0, 1, 1, 1, 1, 0, 0, 2, 2, 2)\n\nJOHAB_SM_MODEL = {\n    \"class_table\": JOHAB_CLS,\n    \"class_factor\": 10,\n    \"state_table\": JOHAB_ST,\n    \"char_len_table\": JOHAB_CHAR_LEN_TABLE,\n    \"name\": \"Johab\",\n}\n\n# EUC-TW\n# fmt: off\nEUCTW_CLS = (\n    2, 2, 2, 2, 2, 2, 2, 2,  # 00 - 07\n    2, 2, 2, 2, 2, 2, 0, 0,  # 08 - 0f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 10 - 17\n    2, 2, 2, 0, 2, 2, 2, 2,  # 18 - 1f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 20 - 27\n    2, 2, 2, 2, 2, 2, 2, 2,  # 28 - 2f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 30 - 37\n    2, 2, 2, 2, 2, 2, 2, 2,  # 38 - 3f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 40 - 47\n    2, 2, 2, 2, 2, 2, 2, 2,  # 48 - 4f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 50 - 57\n    2, 2, 2, 2, 2, 2, 2, 2,  # 58 - 5f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 60 - 67\n    2, 2, 2, 2, 2, 2, 2, 2,  # 68 - 6f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 70 - 77\n    2, 2, 2, 2, 2, 2, 2, 2,  # 78 - 7f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 80 - 87\n    0, 0, 0, 0, 0, 0, 6, 0,  # 88 - 8f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 90 - 97\n    0, 0, 0, 0, 0, 0, 0, 0,  # 98 - 9f\n    0, 3, 4, 4, 4, 4, 4, 4,  # a0 - a7\n    5, 5, 1, 1, 1, 1, 1, 1,  # a8 - af\n    1, 1, 1, 1, 1, 1, 1, 1,  # b0 - b7\n    1, 1, 1, 1, 1, 1, 1, 1,  # b8 - bf\n    1, 1, 3, 1, 3, 3, 3, 3,  # c0 - c7\n    3, 3, 3, 3, 3, 3, 3, 3,  # c8 - cf\n    3, 3, 3, 3, 3, 3, 3, 3,  # d0 - d7\n    3, 3, 3, 3, 3, 3, 3, 3,  # d8 - df\n    3, 3, 3, 3, 3, 3, 3, 3,  # e0 - e7\n    3, 3, 3, 3, 3, 3, 3, 3,  # e8 - ef\n    3, 3, 3, 3, 3, 3, 3, 3,  # f0 - f7\n    3, 3, 3, 3, 3, 3, 3, 0   # f8 - ff\n)\n\nEUCTW_ST = (\n    MachineState.ERROR,MachineState.ERROR,MachineState.START,     3,     3,     3,     4,MachineState.ERROR,#00-07\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,#08-0f\n    MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ERROR,MachineState.START,MachineState.ERROR,#10-17\n    MachineState.START,MachineState.START,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#18-1f\n         5,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.ERROR,MachineState.START,MachineState.START,#20-27\n    MachineState.START,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START #28-2f\n)\n# fmt: on\n\nEUCTW_CHAR_LEN_TABLE = (0, 0, 1, 2, 2, 2, 3)\n\nEUCTW_SM_MODEL = {\n    \"class_table\": EUCTW_CLS,\n    \"class_factor\": 7,\n    \"state_table\": EUCTW_ST,\n    \"char_len_table\": EUCTW_CHAR_LEN_TABLE,\n    \"name\": \"x-euc-tw\",\n}\n\n# GB2312\n# fmt: off\nGB2312_CLS = (\n    1, 1, 1, 1, 1, 1, 1, 1,  # 00 - 07\n    1, 1, 1, 1, 1, 1, 0, 0,  # 08 - 0f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 10 - 17\n    1, 1, 1, 0, 1, 1, 1, 1,  # 18 - 1f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 20 - 27\n    1, 1, 1, 1, 1, 1, 1, 1,  # 28 - 2f\n    3, 3, 3, 3, 3, 3, 3, 3,  # 30 - 37\n    3, 3, 1, 1, 1, 1, 1, 1,  # 38 - 3f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 40 - 47\n    2, 2, 2, 2, 2, 2, 2, 2,  # 48 - 4f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 50 - 57\n    2, 2, 2, 2, 2, 2, 2, 2,  # 58 - 5f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 60 - 67\n    2, 2, 2, 2, 2, 2, 2, 2,  # 68 - 6f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 70 - 77\n    2, 2, 2, 2, 2, 2, 2, 4,  # 78 - 7f\n    5, 6, 6, 6, 6, 6, 6, 6,  # 80 - 87\n    6, 6, 6, 6, 6, 6, 6, 6,  # 88 - 8f\n    6, 6, 6, 6, 6, 6, 6, 6,  # 90 - 97\n    6, 6, 6, 6, 6, 6, 6, 6,  # 98 - 9f\n    6, 6, 6, 6, 6, 6, 6, 6,  # a0 - a7\n    6, 6, 6, 6, 6, 6, 6, 6,  # a8 - af\n    6, 6, 6, 6, 6, 6, 6, 6,  # b0 - b7\n    6, 6, 6, 6, 6, 6, 6, 6,  # b8 - bf\n    6, 6, 6, 6, 6, 6, 6, 6,  # c0 - c7\n    6, 6, 6, 6, 6, 6, 6, 6,  # c8 - cf\n    6, 6, 6, 6, 6, 6, 6, 6,  # d0 - d7\n    6, 6, 6, 6, 6, 6, 6, 6,  # d8 - df\n    6, 6, 6, 6, 6, 6, 6, 6,  # e0 - e7\n    6, 6, 6, 6, 6, 6, 6, 6,  # e8 - ef\n    6, 6, 6, 6, 6, 6, 6, 6,  # f0 - f7\n    6, 6, 6, 6, 6, 6, 6, 0   # f8 - ff\n)\n\nGB2312_ST = (\n    MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,     3,MachineState.ERROR,#00-07\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,#08-0f\n    MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ERROR,MachineState.ERROR,MachineState.START,#10-17\n         4,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#18-1f\n    MachineState.ERROR,MachineState.ERROR,     5,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ERROR,#20-27\n    MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.START #28-2f\n)\n# fmt: on\n\n# To be accurate, the length of class 6 can be either 2 or 4.\n# But it is not necessary to discriminate between the two since\n# it is used for frequency analysis only, and we are validating\n# each code range there as well. So it is safe to set it to be\n# 2 here.\nGB2312_CHAR_LEN_TABLE = (0, 1, 1, 1, 1, 1, 2)\n\nGB2312_SM_MODEL = {\n    \"class_table\": GB2312_CLS,\n    \"class_factor\": 7,\n    \"state_table\": GB2312_ST,\n    \"char_len_table\": GB2312_CHAR_LEN_TABLE,\n    \"name\": \"GB2312\",\n}\n\n# Shift_JIS\n# fmt: off\nSJIS_CLS = (\n    1, 1, 1, 1, 1, 1, 1, 1,  # 00 - 07\n    1, 1, 1, 1, 1, 1, 0, 0,  # 08 - 0f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 10 - 17\n    1, 1, 1, 0, 1, 1, 1, 1,  # 18 - 1f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 20 - 27\n    1, 1, 1, 1, 1, 1, 1, 1,  # 28 - 2f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 30 - 37\n    1, 1, 1, 1, 1, 1, 1, 1,  # 38 - 3f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 40 - 47\n    2, 2, 2, 2, 2, 2, 2, 2,  # 48 - 4f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 50 - 57\n    2, 2, 2, 2, 2, 2, 2, 2,  # 58 - 5f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 60 - 67\n    2, 2, 2, 2, 2, 2, 2, 2,  # 68 - 6f\n    2, 2, 2, 2, 2, 2, 2, 2,  # 70 - 77\n    2, 2, 2, 2, 2, 2, 2, 1,  # 78 - 7f\n    3, 3, 3, 3, 3, 2, 2, 3,  # 80 - 87\n    3, 3, 3, 3, 3, 3, 3, 3,  # 88 - 8f\n    3, 3, 3, 3, 3, 3, 3, 3,  # 90 - 97\n    3, 3, 3, 3, 3, 3, 3, 3,  # 98 - 9f\n    #0xa0 is illegal in sjis encoding, but some pages does\n    #contain such byte. We need to be more error forgiven.\n    2, 2, 2, 2, 2, 2, 2, 2,  # a0 - a7\n    2, 2, 2, 2, 2, 2, 2, 2,  # a8 - af\n    2, 2, 2, 2, 2, 2, 2, 2,  # b0 - b7\n    2, 2, 2, 2, 2, 2, 2, 2,  # b8 - bf\n    2, 2, 2, 2, 2, 2, 2, 2,  # c0 - c7\n    2, 2, 2, 2, 2, 2, 2, 2,  # c8 - cf\n    2, 2, 2, 2, 2, 2, 2, 2,  # d0 - d7\n    2, 2, 2, 2, 2, 2, 2, 2,  # d8 - df\n    3, 3, 3, 3, 3, 3, 3, 3,  # e0 - e7\n    3, 3, 3, 3, 3, 4, 4, 4,  # e8 - ef\n    3, 3, 3, 3, 3, 3, 3, 3,  # f0 - f7\n    3, 3, 3, 3, 3, 0, 0, 0,  # f8 - ff\n)\n\nSJIS_ST = (\n    MachineState.ERROR,MachineState.START,MachineState.START,     3,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#00-07\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,#08-0f\n    MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START #10-17\n)\n# fmt: on\n\nSJIS_CHAR_LEN_TABLE = (0, 1, 1, 2, 0, 0)\n\nSJIS_SM_MODEL = {\n    \"class_table\": SJIS_CLS,\n    \"class_factor\": 6,\n    \"state_table\": SJIS_ST,\n    \"char_len_table\": SJIS_CHAR_LEN_TABLE,\n    \"name\": \"Shift_JIS\",\n}\n\n# UCS2-BE\n# fmt: off\nUCS2BE_CLS = (\n    0, 0, 0, 0, 0, 0, 0, 0,  # 00 - 07\n    0, 0, 1, 0, 0, 2, 0, 0,  # 08 - 0f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 10 - 17\n    0, 0, 0, 3, 0, 0, 0, 0,  # 18 - 1f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 20 - 27\n    0, 3, 3, 3, 3, 3, 0, 0,  # 28 - 2f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 30 - 37\n    0, 0, 0, 0, 0, 0, 0, 0,  # 38 - 3f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 40 - 47\n    0, 0, 0, 0, 0, 0, 0, 0,  # 48 - 4f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 50 - 57\n    0, 0, 0, 0, 0, 0, 0, 0,  # 58 - 5f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 60 - 67\n    0, 0, 0, 0, 0, 0, 0, 0,  # 68 - 6f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 70 - 77\n    0, 0, 0, 0, 0, 0, 0, 0,  # 78 - 7f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 80 - 87\n    0, 0, 0, 0, 0, 0, 0, 0,  # 88 - 8f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 90 - 97\n    0, 0, 0, 0, 0, 0, 0, 0,  # 98 - 9f\n    0, 0, 0, 0, 0, 0, 0, 0,  # a0 - a7\n    0, 0, 0, 0, 0, 0, 0, 0,  # a8 - af\n    0, 0, 0, 0, 0, 0, 0, 0,  # b0 - b7\n    0, 0, 0, 0, 0, 0, 0, 0,  # b8 - bf\n    0, 0, 0, 0, 0, 0, 0, 0,  # c0 - c7\n    0, 0, 0, 0, 0, 0, 0, 0,  # c8 - cf\n    0, 0, 0, 0, 0, 0, 0, 0,  # d0 - d7\n    0, 0, 0, 0, 0, 0, 0, 0,  # d8 - df\n    0, 0, 0, 0, 0, 0, 0, 0,  # e0 - e7\n    0, 0, 0, 0, 0, 0, 0, 0,  # e8 - ef\n    0, 0, 0, 0, 0, 0, 0, 0,  # f0 - f7\n    0, 0, 0, 0, 0, 0, 4, 5   # f8 - ff\n)\n\nUCS2BE_ST  = (\n          5,     7,     7,MachineState.ERROR,     4,     3,MachineState.ERROR,MachineState.ERROR,#00-07\n     MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,#08-0f\n     MachineState.ITS_ME,MachineState.ITS_ME,     6,     6,     6,     6,MachineState.ERROR,MachineState.ERROR,#10-17\n          6,     6,     6,     6,     6,MachineState.ITS_ME,     6,     6,#18-1f\n          6,     6,     6,     6,     5,     7,     7,MachineState.ERROR,#20-27\n          5,     8,     6,     6,MachineState.ERROR,     6,     6,     6,#28-2f\n          6,     6,     6,     6,MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START #30-37\n)\n# fmt: on\n\nUCS2BE_CHAR_LEN_TABLE = (2, 2, 2, 0, 2, 2)\n\nUCS2BE_SM_MODEL = {\n    \"class_table\": UCS2BE_CLS,\n    \"class_factor\": 6,\n    \"state_table\": UCS2BE_ST,\n    \"char_len_table\": UCS2BE_CHAR_LEN_TABLE,\n    \"name\": \"UTF-16BE\",\n}\n\n# UCS2-LE\n# fmt: off\nUCS2LE_CLS = (\n    0, 0, 0, 0, 0, 0, 0, 0,  # 00 - 07\n    0, 0, 1, 0, 0, 2, 0, 0,  # 08 - 0f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 10 - 17\n    0, 0, 0, 3, 0, 0, 0, 0,  # 18 - 1f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 20 - 27\n    0, 3, 3, 3, 3, 3, 0, 0,  # 28 - 2f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 30 - 37\n    0, 0, 0, 0, 0, 0, 0, 0,  # 38 - 3f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 40 - 47\n    0, 0, 0, 0, 0, 0, 0, 0,  # 48 - 4f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 50 - 57\n    0, 0, 0, 0, 0, 0, 0, 0,  # 58 - 5f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 60 - 67\n    0, 0, 0, 0, 0, 0, 0, 0,  # 68 - 6f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 70 - 77\n    0, 0, 0, 0, 0, 0, 0, 0,  # 78 - 7f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 80 - 87\n    0, 0, 0, 0, 0, 0, 0, 0,  # 88 - 8f\n    0, 0, 0, 0, 0, 0, 0, 0,  # 90 - 97\n    0, 0, 0, 0, 0, 0, 0, 0,  # 98 - 9f\n    0, 0, 0, 0, 0, 0, 0, 0,  # a0 - a7\n    0, 0, 0, 0, 0, 0, 0, 0,  # a8 - af\n    0, 0, 0, 0, 0, 0, 0, 0,  # b0 - b7\n    0, 0, 0, 0, 0, 0, 0, 0,  # b8 - bf\n    0, 0, 0, 0, 0, 0, 0, 0,  # c0 - c7\n    0, 0, 0, 0, 0, 0, 0, 0,  # c8 - cf\n    0, 0, 0, 0, 0, 0, 0, 0,  # d0 - d7\n    0, 0, 0, 0, 0, 0, 0, 0,  # d8 - df\n    0, 0, 0, 0, 0, 0, 0, 0,  # e0 - e7\n    0, 0, 0, 0, 0, 0, 0, 0,  # e8 - ef\n    0, 0, 0, 0, 0, 0, 0, 0,  # f0 - f7\n    0, 0, 0, 0, 0, 0, 4, 5   # f8 - ff\n)\n\nUCS2LE_ST = (\n          6,     6,     7,     6,     4,     3,MachineState.ERROR,MachineState.ERROR,#00-07\n     MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,#08-0f\n     MachineState.ITS_ME,MachineState.ITS_ME,     5,     5,     5,MachineState.ERROR,MachineState.ITS_ME,MachineState.ERROR,#10-17\n          5,     5,     5,MachineState.ERROR,     5,MachineState.ERROR,     6,     6,#18-1f\n          7,     6,     8,     8,     5,     5,     5,MachineState.ERROR,#20-27\n          5,     5,     5,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,     5,     5,#28-2f\n          5,     5,     5,MachineState.ERROR,     5,MachineState.ERROR,MachineState.START,MachineState.START #30-37\n)\n# fmt: on\n\nUCS2LE_CHAR_LEN_TABLE = (2, 2, 2, 2, 2, 2)\n\nUCS2LE_SM_MODEL = {\n    \"class_table\": UCS2LE_CLS,\n    \"class_factor\": 6,\n    \"state_table\": UCS2LE_ST,\n    \"char_len_table\": UCS2LE_CHAR_LEN_TABLE,\n    \"name\": \"UTF-16LE\",\n}\n\n# UTF-8\n# fmt: off\nUTF8_CLS = (\n    1, 1, 1, 1, 1, 1, 1, 1,  # 00 - 07  #allow 0x00 as a legal value\n    1, 1, 1, 1, 1, 1, 0, 0,  # 08 - 0f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 10 - 17\n    1, 1, 1, 0, 1, 1, 1, 1,  # 18 - 1f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 20 - 27\n    1, 1, 1, 1, 1, 1, 1, 1,  # 28 - 2f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 30 - 37\n    1, 1, 1, 1, 1, 1, 1, 1,  # 38 - 3f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 40 - 47\n    1, 1, 1, 1, 1, 1, 1, 1,  # 48 - 4f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 50 - 57\n    1, 1, 1, 1, 1, 1, 1, 1,  # 58 - 5f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 60 - 67\n    1, 1, 1, 1, 1, 1, 1, 1,  # 68 - 6f\n    1, 1, 1, 1, 1, 1, 1, 1,  # 70 - 77\n    1, 1, 1, 1, 1, 1, 1, 1,  # 78 - 7f\n    2, 2, 2, 2, 3, 3, 3, 3,  # 80 - 87\n    4, 4, 4, 4, 4, 4, 4, 4,  # 88 - 8f\n    4, 4, 4, 4, 4, 4, 4, 4,  # 90 - 97\n    4, 4, 4, 4, 4, 4, 4, 4,  # 98 - 9f\n    5, 5, 5, 5, 5, 5, 5, 5,  # a0 - a7\n    5, 5, 5, 5, 5, 5, 5, 5,  # a8 - af\n    5, 5, 5, 5, 5, 5, 5, 5,  # b0 - b7\n    5, 5, 5, 5, 5, 5, 5, 5,  # b8 - bf\n    0, 0, 6, 6, 6, 6, 6, 6,  # c0 - c7\n    6, 6, 6, 6, 6, 6, 6, 6,  # c8 - cf\n    6, 6, 6, 6, 6, 6, 6, 6,  # d0 - d7\n    6, 6, 6, 6, 6, 6, 6, 6,  # d8 - df\n    7, 8, 8, 8, 8, 8, 8, 8,  # e0 - e7\n    8, 8, 8, 8, 8, 9, 8, 8,  # e8 - ef\n    10, 11, 11, 11, 11, 11, 11, 11,  # f0 - f7\n    12, 13, 13, 13, 14, 15, 0, 0    # f8 - ff\n)\n\nUTF8_ST = (\n    MachineState.ERROR,MachineState.START,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,     12,   10,#00-07\n         9,     11,     8,     7,     6,     5,     4,    3,#08-0f\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#10-17\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#18-1f\n    MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,#20-27\n    MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,MachineState.ITS_ME,#28-2f\n    MachineState.ERROR,MachineState.ERROR,     5,     5,     5,     5,MachineState.ERROR,MachineState.ERROR,#30-37\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#38-3f\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,     5,     5,     5,MachineState.ERROR,MachineState.ERROR,#40-47\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#48-4f\n    MachineState.ERROR,MachineState.ERROR,     7,     7,     7,     7,MachineState.ERROR,MachineState.ERROR,#50-57\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#58-5f\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,     7,     7,MachineState.ERROR,MachineState.ERROR,#60-67\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#68-6f\n    MachineState.ERROR,MachineState.ERROR,     9,     9,     9,     9,MachineState.ERROR,MachineState.ERROR,#70-77\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#78-7f\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,     9,MachineState.ERROR,MachineState.ERROR,#80-87\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#88-8f\n    MachineState.ERROR,MachineState.ERROR,    12,    12,    12,    12,MachineState.ERROR,MachineState.ERROR,#90-97\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#98-9f\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,    12,MachineState.ERROR,MachineState.ERROR,#a0-a7\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#a8-af\n    MachineState.ERROR,MachineState.ERROR,    12,    12,    12,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#b0-b7\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,#b8-bf\n    MachineState.ERROR,MachineState.ERROR,MachineState.START,MachineState.START,MachineState.START,MachineState.START,MachineState.ERROR,MachineState.ERROR,#c0-c7\n    MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR,MachineState.ERROR #c8-cf\n)\n# fmt: on\n\nUTF8_CHAR_LEN_TABLE = (0, 1, 0, 0, 0, 0, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6)\n\nUTF8_SM_MODEL = {\n    \"class_table\": UTF8_CLS,\n    \"class_factor\": 16,\n    \"state_table\": UTF8_ST,\n    \"char_len_table\": UTF8_CHAR_LEN_TABLE,\n    \"name\": \"UTF-8\",\n}\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/metadata/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/metadata/languages.py",
    "content": "\"\"\"\nMetadata about languages used by our model training code for our\nSingleByteCharSetProbers.  Could be used for other things in the future.\n\nThis code is based on the language metadata from the uchardet project.\n\"\"\"\n\nfrom string import ascii_letters\n\n# TODO: Add Ukrainian (KOI8-U)\n\n\nclass Language:\n    \"\"\"Metadata about a language useful for training models\n\n    :ivar name: The human name for the language, in English.\n    :type name: str\n    :ivar iso_code: 2-letter ISO 639-1 if possible, 3-letter ISO code otherwise,\n                    or use another catalog as a last resort.\n    :type iso_code: str\n    :ivar use_ascii: Whether or not ASCII letters should be included in trained\n                     models.\n    :type use_ascii: bool\n    :ivar charsets: The charsets we want to support and create data for.\n    :type charsets: list of str\n    :ivar alphabet: The characters in the language's alphabet. If `use_ascii` is\n                    `True`, you only need to add those not in the ASCII set.\n    :type alphabet: str\n    :ivar wiki_start_pages: The Wikipedia pages to start from if we're crawling\n                            Wikipedia for training data.\n    :type wiki_start_pages: list of str\n    \"\"\"\n\n    def __init__(\n        self,\n        name=None,\n        iso_code=None,\n        use_ascii=True,\n        charsets=None,\n        alphabet=None,\n        wiki_start_pages=None,\n    ):\n        super().__init__()\n        self.name = name\n        self.iso_code = iso_code\n        self.use_ascii = use_ascii\n        self.charsets = charsets\n        if self.use_ascii:\n            if alphabet:\n                alphabet += ascii_letters\n            else:\n                alphabet = ascii_letters\n        elif not alphabet:\n            raise ValueError(\"Must supply alphabet if use_ascii is False\")\n        self.alphabet = \"\".join(sorted(set(alphabet))) if alphabet else None\n        self.wiki_start_pages = wiki_start_pages\n\n    def __repr__(self):\n        param_str = \", \".join(\n            f\"{k}={v!r}\" for k, v in self.__dict__.items() if not k.startswith(\"_\")\n        )\n        return f\"{self.__class__.__name__}({param_str})\"\n\n\nLANGUAGES = {\n    \"Arabic\": Language(\n        name=\"Arabic\",\n        iso_code=\"ar\",\n        use_ascii=False,\n        # We only support encodings that use isolated\n        # forms, because the current recommendation is\n        # that the rendering system handles presentation\n        # forms. This means we purposefully skip IBM864.\n        charsets=[\"ISO-8859-6\", \"WINDOWS-1256\", \"CP720\", \"CP864\"],\n        alphabet=\"ءآأؤإئابةتثجحخدذرزسشصضطظعغػؼؽؾؿـفقكلمنهوىيًٌٍَُِّ\",\n        wiki_start_pages=[\"الصفحة_الرئيسية\"],\n    ),\n    \"Belarusian\": Language(\n        name=\"Belarusian\",\n        iso_code=\"be\",\n        use_ascii=False,\n        charsets=[\"ISO-8859-5\", \"WINDOWS-1251\", \"IBM866\", \"MacCyrillic\"],\n        alphabet=\"АБВГДЕЁЖЗІЙКЛМНОПРСТУЎФХЦЧШЫЬЭЮЯабвгдеёжзійклмнопрстуўфхцчшыьэюяʼ\",\n        wiki_start_pages=[\"Галоўная_старонка\"],\n    ),\n    \"Bulgarian\": Language(\n        name=\"Bulgarian\",\n        iso_code=\"bg\",\n        use_ascii=False,\n        charsets=[\"ISO-8859-5\", \"WINDOWS-1251\", \"IBM855\"],\n        alphabet=\"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЬЮЯабвгдежзийклмнопрстуфхцчшщъьюя\",\n        wiki_start_pages=[\"Начална_страница\"],\n    ),\n    \"Czech\": Language(\n        name=\"Czech\",\n        iso_code=\"cz\",\n        use_ascii=True,\n        charsets=[\"ISO-8859-2\", \"WINDOWS-1250\"],\n        alphabet=\"áčďéěíňóřšťúůýžÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ\",\n        wiki_start_pages=[\"Hlavní_strana\"],\n    ),\n    \"Danish\": Language(\n        name=\"Danish\",\n        iso_code=\"da\",\n        use_ascii=True,\n        charsets=[\"ISO-8859-1\", \"ISO-8859-15\", \"WINDOWS-1252\"],\n        alphabet=\"æøåÆØÅ\",\n        wiki_start_pages=[\"Forside\"],\n    ),\n    \"German\": Language(\n        name=\"German\",\n        iso_code=\"de\",\n        use_ascii=True,\n        charsets=[\"ISO-8859-1\", \"WINDOWS-1252\"],\n        alphabet=\"äöüßÄÖÜ\",\n        wiki_start_pages=[\"Wikipedia:Hauptseite\"],\n    ),\n    \"Greek\": Language(\n        name=\"Greek\",\n        iso_code=\"el\",\n        use_ascii=False,\n        charsets=[\"ISO-8859-7\", \"WINDOWS-1253\"],\n        alphabet=\"αβγδεζηθικλμνξοπρσςτυφχψωάέήίόύώΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΣΤΥΦΧΨΩΆΈΉΊΌΎΏ\",\n        wiki_start_pages=[\"Πύλη:Κύρια\"],\n    ),\n    \"English\": Language(\n        name=\"English\",\n        iso_code=\"en\",\n        use_ascii=True,\n        charsets=[\"ISO-8859-1\", \"WINDOWS-1252\"],\n        wiki_start_pages=[\"Main_Page\"],\n    ),\n    \"Esperanto\": Language(\n        name=\"Esperanto\",\n        iso_code=\"eo\",\n        # Q, W, X, and Y not used at all\n        use_ascii=False,\n        charsets=[\"ISO-8859-3\"],\n        alphabet=\"abcĉdefgĝhĥijĵklmnoprsŝtuŭvzABCĈDEFGĜHĤIJĴKLMNOPRSŜTUŬVZ\",\n        wiki_start_pages=[\"Vikipedio:Ĉefpaĝo\"],\n    ),\n    \"Spanish\": Language(\n        name=\"Spanish\",\n        iso_code=\"es\",\n        use_ascii=True,\n        charsets=[\"ISO-8859-1\", \"ISO-8859-15\", \"WINDOWS-1252\"],\n        alphabet=\"ñáéíóúüÑÁÉÍÓÚÜ\",\n        wiki_start_pages=[\"Wikipedia:Portada\"],\n    ),\n    \"Estonian\": Language(\n        name=\"Estonian\",\n        iso_code=\"et\",\n        use_ascii=False,\n        charsets=[\"ISO-8859-4\", \"ISO-8859-13\", \"WINDOWS-1257\"],\n        # C, F, Š, Q, W, X, Y, Z, Ž are only for\n        # loanwords\n        alphabet=\"ABDEGHIJKLMNOPRSTUVÕÄÖÜabdeghijklmnoprstuvõäöü\",\n        wiki_start_pages=[\"Esileht\"],\n    ),\n    \"Finnish\": Language(\n        name=\"Finnish\",\n        iso_code=\"fi\",\n        use_ascii=True,\n        charsets=[\"ISO-8859-1\", \"ISO-8859-15\", \"WINDOWS-1252\"],\n        alphabet=\"ÅÄÖŠŽåäöšž\",\n        wiki_start_pages=[\"Wikipedia:Etusivu\"],\n    ),\n    \"French\": Language(\n        name=\"French\",\n        iso_code=\"fr\",\n        use_ascii=True,\n        charsets=[\"ISO-8859-1\", \"ISO-8859-15\", \"WINDOWS-1252\"],\n        alphabet=\"œàâçèéîïùûêŒÀÂÇÈÉÎÏÙÛÊ\",\n        wiki_start_pages=[\"Wikipédia:Accueil_principal\", \"Bœuf (animal)\"],\n    ),\n    \"Hebrew\": Language(\n        name=\"Hebrew\",\n        iso_code=\"he\",\n        use_ascii=False,\n        charsets=[\"ISO-8859-8\", \"WINDOWS-1255\"],\n        alphabet=\"אבגדהוזחטיךכלםמןנסעףפץצקרשתװױײ\",\n        wiki_start_pages=[\"עמוד_ראשי\"],\n    ),\n    \"Croatian\": Language(\n        name=\"Croatian\",\n        iso_code=\"hr\",\n        # Q, W, X, Y are only used for foreign words.\n        use_ascii=False,\n        charsets=[\"ISO-8859-2\", \"WINDOWS-1250\"],\n        alphabet=\"abcčćdđefghijklmnoprsštuvzžABCČĆDĐEFGHIJKLMNOPRSŠTUVZŽ\",\n        wiki_start_pages=[\"Glavna_stranica\"],\n    ),\n    \"Hungarian\": Language(\n        name=\"Hungarian\",\n        iso_code=\"hu\",\n        # Q, W, X, Y are only used for foreign words.\n        use_ascii=False,\n        charsets=[\"ISO-8859-2\", \"WINDOWS-1250\"],\n        alphabet=\"abcdefghijklmnoprstuvzáéíóöőúüűABCDEFGHIJKLMNOPRSTUVZÁÉÍÓÖŐÚÜŰ\",\n        wiki_start_pages=[\"Kezdőlap\"],\n    ),\n    \"Italian\": Language(\n        name=\"Italian\",\n        iso_code=\"it\",\n        use_ascii=True,\n        charsets=[\"ISO-8859-1\", \"ISO-8859-15\", \"WINDOWS-1252\"],\n        alphabet=\"ÀÈÉÌÒÓÙàèéìòóù\",\n        wiki_start_pages=[\"Pagina_principale\"],\n    ),\n    \"Lithuanian\": Language(\n        name=\"Lithuanian\",\n        iso_code=\"lt\",\n        use_ascii=False,\n        charsets=[\"ISO-8859-13\", \"WINDOWS-1257\", \"ISO-8859-4\"],\n        # Q, W, and X not used at all\n        alphabet=\"AĄBCČDEĘĖFGHIĮYJKLMNOPRSŠTUŲŪVZŽaąbcčdeęėfghiįyjklmnoprsštuųūvzž\",\n        wiki_start_pages=[\"Pagrindinis_puslapis\"],\n    ),\n    \"Latvian\": Language(\n        name=\"Latvian\",\n        iso_code=\"lv\",\n        use_ascii=False,\n        charsets=[\"ISO-8859-13\", \"WINDOWS-1257\", \"ISO-8859-4\"],\n        # Q, W, X, Y are only for loanwords\n        alphabet=\"AĀBCČDEĒFGĢHIĪJKĶLĻMNŅOPRSŠTUŪVZŽaābcčdeēfgģhiījkķlļmnņoprsštuūvzž\",\n        wiki_start_pages=[\"Sākumlapa\"],\n    ),\n    \"Macedonian\": Language(\n        name=\"Macedonian\",\n        iso_code=\"mk\",\n        use_ascii=False,\n        charsets=[\"ISO-8859-5\", \"WINDOWS-1251\", \"MacCyrillic\", \"IBM855\"],\n        alphabet=\"АБВГДЃЕЖЗЅИЈКЛЉМНЊОПРСТЌУФХЦЧЏШабвгдѓежзѕијклљмнњопрстќуфхцчџш\",\n        wiki_start_pages=[\"Главна_страница\"],\n    ),\n    \"Dutch\": Language(\n        name=\"Dutch\",\n        iso_code=\"nl\",\n        use_ascii=True,\n        charsets=[\"ISO-8859-1\", \"WINDOWS-1252\"],\n        wiki_start_pages=[\"Hoofdpagina\"],\n    ),\n    \"Polish\": Language(\n        name=\"Polish\",\n        iso_code=\"pl\",\n        # Q and X are only used for foreign words.\n        use_ascii=False,\n        charsets=[\"ISO-8859-2\", \"WINDOWS-1250\"],\n        alphabet=\"AĄBCĆDEĘFGHIJKLŁMNŃOÓPRSŚTUWYZŹŻaąbcćdeęfghijklłmnńoóprsśtuwyzźż\",\n        wiki_start_pages=[\"Wikipedia:Strona_główna\"],\n    ),\n    \"Portuguese\": Language(\n        name=\"Portuguese\",\n        iso_code=\"pt\",\n        use_ascii=True,\n        charsets=[\"ISO-8859-1\", \"ISO-8859-15\", \"WINDOWS-1252\"],\n        alphabet=\"ÁÂÃÀÇÉÊÍÓÔÕÚáâãàçéêíóôõú\",\n        wiki_start_pages=[\"Wikipédia:Página_principal\"],\n    ),\n    \"Romanian\": Language(\n        name=\"Romanian\",\n        iso_code=\"ro\",\n        use_ascii=True,\n        charsets=[\"ISO-8859-2\", \"WINDOWS-1250\"],\n        alphabet=\"ăâîșțĂÂÎȘȚ\",\n        wiki_start_pages=[\"Pagina_principală\"],\n    ),\n    \"Russian\": Language(\n        name=\"Russian\",\n        iso_code=\"ru\",\n        use_ascii=False,\n        charsets=[\n            \"ISO-8859-5\",\n            \"WINDOWS-1251\",\n            \"KOI8-R\",\n            \"MacCyrillic\",\n            \"IBM866\",\n            \"IBM855\",\n        ],\n        alphabet=\"абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ\",\n        wiki_start_pages=[\"Заглавная_страница\"],\n    ),\n    \"Slovak\": Language(\n        name=\"Slovak\",\n        iso_code=\"sk\",\n        use_ascii=True,\n        charsets=[\"ISO-8859-2\", \"WINDOWS-1250\"],\n        alphabet=\"áäčďéíĺľňóôŕšťúýžÁÄČĎÉÍĹĽŇÓÔŔŠŤÚÝŽ\",\n        wiki_start_pages=[\"Hlavná_stránka\"],\n    ),\n    \"Slovene\": Language(\n        name=\"Slovene\",\n        iso_code=\"sl\",\n        # Q, W, X, Y are only used for foreign words.\n        use_ascii=False,\n        charsets=[\"ISO-8859-2\", \"WINDOWS-1250\"],\n        alphabet=\"abcčdefghijklmnoprsštuvzžABCČDEFGHIJKLMNOPRSŠTUVZŽ\",\n        wiki_start_pages=[\"Glavna_stran\"],\n    ),\n    # Serbian can be written in both Latin and Cyrillic, but there's no\n    # simple way to get the Latin alphabet pages from Wikipedia through\n    # the API, so for now we just support Cyrillic.\n    \"Serbian\": Language(\n        name=\"Serbian\",\n        iso_code=\"sr\",\n        alphabet=\"АБВГДЂЕЖЗИЈКЛЉМНЊОПРСТЋУФХЦЧЏШабвгдђежзијклљмнњопрстћуфхцчџш\",\n        charsets=[\"ISO-8859-5\", \"WINDOWS-1251\", \"MacCyrillic\", \"IBM855\"],\n        wiki_start_pages=[\"Главна_страна\"],\n    ),\n    \"Thai\": Language(\n        name=\"Thai\",\n        iso_code=\"th\",\n        use_ascii=False,\n        charsets=[\"ISO-8859-11\", \"TIS-620\", \"CP874\"],\n        alphabet=\"กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛\",\n        wiki_start_pages=[\"หน้าหลัก\"],\n    ),\n    \"Turkish\": Language(\n        name=\"Turkish\",\n        iso_code=\"tr\",\n        # Q, W, and X are not used by Turkish\n        use_ascii=False,\n        charsets=[\"ISO-8859-3\", \"ISO-8859-9\", \"WINDOWS-1254\"],\n        alphabet=\"abcçdefgğhıijklmnoöprsştuüvyzâîûABCÇDEFGĞHIİJKLMNOÖPRSŞTUÜVYZÂÎÛ\",\n        wiki_start_pages=[\"Ana_Sayfa\"],\n    ),\n    \"Vietnamese\": Language(\n        name=\"Vietnamese\",\n        iso_code=\"vi\",\n        use_ascii=False,\n        # Windows-1258 is the only common 8-bit\n        # Vietnamese encoding supported by Python.\n        # From Wikipedia:\n        # For systems that lack support for Unicode,\n        # dozens of 8-bit Vietnamese code pages are\n        # available.[1] The most common are VISCII\n        # (TCVN 5712:1993), VPS, and Windows-1258.[3]\n        # Where ASCII is required, such as when\n        # ensuring readability in plain text e-mail,\n        # Vietnamese letters are often encoded\n        # according to Vietnamese Quoted-Readable\n        # (VIQR) or VSCII Mnemonic (VSCII-MNEM),[4]\n        # though usage of either variable-width\n        # scheme has declined dramatically following\n        # the adoption of Unicode on the World Wide\n        # Web.\n        charsets=[\"WINDOWS-1258\"],\n        alphabet=\"aăâbcdđeêghiklmnoôơpqrstuưvxyAĂÂBCDĐEÊGHIKLMNOÔƠPQRSTUƯVXY\",\n        wiki_start_pages=[\"Chữ_Quốc_ngữ\"],\n    ),\n}\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/sbcharsetprober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Universal charset detector code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 2001\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#   Shy Shalom - original C code\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom collections import namedtuple\n\nfrom .charsetprober import CharSetProber\nfrom .enums import CharacterCategory, ProbingState, SequenceLikelihood\n\nSingleByteCharSetModel = namedtuple(\n    \"SingleByteCharSetModel\",\n    [\n        \"charset_name\",\n        \"language\",\n        \"char_to_order_map\",\n        \"language_model\",\n        \"typical_positive_ratio\",\n        \"keep_ascii_letters\",\n        \"alphabet\",\n    ],\n)\n\n\nclass SingleByteCharSetProber(CharSetProber):\n    SAMPLE_SIZE = 64\n    SB_ENOUGH_REL_THRESHOLD = 1024  # 0.25 * SAMPLE_SIZE^2\n    POSITIVE_SHORTCUT_THRESHOLD = 0.95\n    NEGATIVE_SHORTCUT_THRESHOLD = 0.05\n\n    def __init__(self, model, is_reversed=False, name_prober=None):\n        super().__init__()\n        self._model = model\n        # TRUE if we need to reverse every pair in the model lookup\n        self._reversed = is_reversed\n        # Optional auxiliary prober for name decision\n        self._name_prober = name_prober\n        self._last_order = None\n        self._seq_counters = None\n        self._total_seqs = None\n        self._total_char = None\n        self._control_char = None\n        self._freq_char = None\n        self.reset()\n\n    def reset(self):\n        super().reset()\n        # char order of last character\n        self._last_order = 255\n        self._seq_counters = [0] * SequenceLikelihood.get_num_categories()\n        self._total_seqs = 0\n        self._total_char = 0\n        self._control_char = 0\n        # characters that fall in our sampling range\n        self._freq_char = 0\n\n    @property\n    def charset_name(self):\n        if self._name_prober:\n            return self._name_prober.charset_name\n        return self._model.charset_name\n\n    @property\n    def language(self):\n        if self._name_prober:\n            return self._name_prober.language\n        return self._model.language\n\n    def feed(self, byte_str):\n        # TODO: Make filter_international_words keep things in self.alphabet\n        if not self._model.keep_ascii_letters:\n            byte_str = self.filter_international_words(byte_str)\n        else:\n            byte_str = self.remove_xml_tags(byte_str)\n        if not byte_str:\n            return self.state\n        char_to_order_map = self._model.char_to_order_map\n        language_model = self._model.language_model\n        for char in byte_str:\n            order = char_to_order_map.get(char, CharacterCategory.UNDEFINED)\n            # XXX: This was SYMBOL_CAT_ORDER before, with a value of 250, but\n            #      CharacterCategory.SYMBOL is actually 253, so we use CONTROL\n            #      to make it closer to the original intent. The only difference\n            #      is whether or not we count digits and control characters for\n            #      _total_char purposes.\n            if order < CharacterCategory.CONTROL:\n                self._total_char += 1\n            if order < self.SAMPLE_SIZE:\n                self._freq_char += 1\n                if self._last_order < self.SAMPLE_SIZE:\n                    self._total_seqs += 1\n                    if not self._reversed:\n                        lm_cat = language_model[self._last_order][order]\n                    else:\n                        lm_cat = language_model[order][self._last_order]\n                    self._seq_counters[lm_cat] += 1\n            self._last_order = order\n\n        charset_name = self._model.charset_name\n        if self.state == ProbingState.DETECTING:\n            if self._total_seqs > self.SB_ENOUGH_REL_THRESHOLD:\n                confidence = self.get_confidence()\n                if confidence > self.POSITIVE_SHORTCUT_THRESHOLD:\n                    self.logger.debug(\n                        \"%s confidence = %s, we have a winner\", charset_name, confidence\n                    )\n                    self._state = ProbingState.FOUND_IT\n                elif confidence < self.NEGATIVE_SHORTCUT_THRESHOLD:\n                    self.logger.debug(\n                        \"%s confidence = %s, below negative shortcut threshold %s\",\n                        charset_name,\n                        confidence,\n                        self.NEGATIVE_SHORTCUT_THRESHOLD,\n                    )\n                    self._state = ProbingState.NOT_ME\n\n        return self.state\n\n    def get_confidence(self):\n        r = 0.01\n        if self._total_seqs > 0:\n            r = (\n                (\n                    self._seq_counters[SequenceLikelihood.POSITIVE]\n                    + 0.25 * self._seq_counters[SequenceLikelihood.LIKELY]\n                )\n                / self._total_seqs\n                / self._model.typical_positive_ratio\n            )\n            # The more control characters (proportionnaly to the size\n            # of the text), the less confident we become in the current\n            # charset.\n            r = r * (self._total_char - self._control_char) / self._total_char\n            r = r * self._freq_char / self._total_char\n            if r >= 1.0:\n                r = 0.99\n        return r\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/sbcsgroupprober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Universal charset detector code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 2001\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#   Shy Shalom - original C code\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .charsetgroupprober import CharSetGroupProber\nfrom .hebrewprober import HebrewProber\nfrom .langbulgarianmodel import ISO_8859_5_BULGARIAN_MODEL, WINDOWS_1251_BULGARIAN_MODEL\nfrom .langgreekmodel import ISO_8859_7_GREEK_MODEL, WINDOWS_1253_GREEK_MODEL\nfrom .langhebrewmodel import WINDOWS_1255_HEBREW_MODEL\n\n# from .langhungarianmodel import (ISO_8859_2_HUNGARIAN_MODEL,\n#                                  WINDOWS_1250_HUNGARIAN_MODEL)\nfrom .langrussianmodel import (\n    IBM855_RUSSIAN_MODEL,\n    IBM866_RUSSIAN_MODEL,\n    ISO_8859_5_RUSSIAN_MODEL,\n    KOI8_R_RUSSIAN_MODEL,\n    MACCYRILLIC_RUSSIAN_MODEL,\n    WINDOWS_1251_RUSSIAN_MODEL,\n)\nfrom .langthaimodel import TIS_620_THAI_MODEL\nfrom .langturkishmodel import ISO_8859_9_TURKISH_MODEL\nfrom .sbcharsetprober import SingleByteCharSetProber\n\n\nclass SBCSGroupProber(CharSetGroupProber):\n    def __init__(self):\n        super().__init__()\n        hebrew_prober = HebrewProber()\n        logical_hebrew_prober = SingleByteCharSetProber(\n            WINDOWS_1255_HEBREW_MODEL, is_reversed=False, name_prober=hebrew_prober\n        )\n        # TODO: See if using ISO-8859-8 Hebrew model works better here, since\n        #       it's actually the visual one\n        visual_hebrew_prober = SingleByteCharSetProber(\n            WINDOWS_1255_HEBREW_MODEL, is_reversed=True, name_prober=hebrew_prober\n        )\n        hebrew_prober.set_model_probers(logical_hebrew_prober, visual_hebrew_prober)\n        # TODO: ORDER MATTERS HERE. I changed the order vs what was in master\n        #       and several tests failed that did not before. Some thought\n        #       should be put into the ordering, and we should consider making\n        #       order not matter here, because that is very counter-intuitive.\n        self.probers = [\n            SingleByteCharSetProber(WINDOWS_1251_RUSSIAN_MODEL),\n            SingleByteCharSetProber(KOI8_R_RUSSIAN_MODEL),\n            SingleByteCharSetProber(ISO_8859_5_RUSSIAN_MODEL),\n            SingleByteCharSetProber(MACCYRILLIC_RUSSIAN_MODEL),\n            SingleByteCharSetProber(IBM866_RUSSIAN_MODEL),\n            SingleByteCharSetProber(IBM855_RUSSIAN_MODEL),\n            SingleByteCharSetProber(ISO_8859_7_GREEK_MODEL),\n            SingleByteCharSetProber(WINDOWS_1253_GREEK_MODEL),\n            SingleByteCharSetProber(ISO_8859_5_BULGARIAN_MODEL),\n            SingleByteCharSetProber(WINDOWS_1251_BULGARIAN_MODEL),\n            # TODO: Restore Hungarian encodings (iso-8859-2 and windows-1250)\n            #       after we retrain model.\n            # SingleByteCharSetProber(ISO_8859_2_HUNGARIAN_MODEL),\n            # SingleByteCharSetProber(WINDOWS_1250_HUNGARIAN_MODEL),\n            SingleByteCharSetProber(TIS_620_THAI_MODEL),\n            SingleByteCharSetProber(ISO_8859_9_TURKISH_MODEL),\n            hebrew_prober,\n            logical_hebrew_prober,\n            visual_hebrew_prober,\n        ]\n        self.reset()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/sjisprober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is mozilla.org code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .chardistribution import SJISDistributionAnalysis\nfrom .codingstatemachine import CodingStateMachine\nfrom .enums import MachineState, ProbingState\nfrom .jpcntx import SJISContextAnalysis\nfrom .mbcharsetprober import MultiByteCharSetProber\nfrom .mbcssm import SJIS_SM_MODEL\n\n\nclass SJISProber(MultiByteCharSetProber):\n    def __init__(self):\n        super().__init__()\n        self.coding_sm = CodingStateMachine(SJIS_SM_MODEL)\n        self.distribution_analyzer = SJISDistributionAnalysis()\n        self.context_analyzer = SJISContextAnalysis()\n        self.reset()\n\n    def reset(self):\n        super().reset()\n        self.context_analyzer.reset()\n\n    @property\n    def charset_name(self):\n        return self.context_analyzer.charset_name\n\n    @property\n    def language(self):\n        return \"Japanese\"\n\n    def feed(self, byte_str):\n        for i, byte in enumerate(byte_str):\n            coding_state = self.coding_sm.next_state(byte)\n            if coding_state == MachineState.ERROR:\n                self.logger.debug(\n                    \"%s %s prober hit error at byte %s\",\n                    self.charset_name,\n                    self.language,\n                    i,\n                )\n                self._state = ProbingState.NOT_ME\n                break\n            if coding_state == MachineState.ITS_ME:\n                self._state = ProbingState.FOUND_IT\n                break\n            if coding_state == MachineState.START:\n                char_len = self.coding_sm.get_current_charlen()\n                if i == 0:\n                    self._last_char[1] = byte\n                    self.context_analyzer.feed(\n                        self._last_char[2 - char_len :], char_len\n                    )\n                    self.distribution_analyzer.feed(self._last_char, char_len)\n                else:\n                    self.context_analyzer.feed(\n                        byte_str[i + 1 - char_len : i + 3 - char_len], char_len\n                    )\n                    self.distribution_analyzer.feed(byte_str[i - 1 : i + 1], char_len)\n\n        self._last_char[0] = byte_str[-1]\n\n        if self.state == ProbingState.DETECTING:\n            if self.context_analyzer.got_enough_data() and (\n                self.get_confidence() > self.SHORTCUT_THRESHOLD\n            ):\n                self._state = ProbingState.FOUND_IT\n\n        return self.state\n\n    def get_confidence(self):\n        context_conf = self.context_analyzer.get_confidence()\n        distrib_conf = self.distribution_analyzer.get_confidence()\n        return max(context_conf, distrib_conf)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/universaldetector.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is Mozilla Universal charset detector code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 2001\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#   Shy Shalom - original C code\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\"\"\"\nModule containing the UniversalDetector detector class, which is the primary\nclass a user of ``chardet`` should use.\n\n:author: Mark Pilgrim (initial port to Python)\n:author: Shy Shalom (original C code)\n:author: Dan Blanchard (major refactoring for 3.0)\n:author: Ian Cordasco\n\"\"\"\n\n\nimport codecs\nimport logging\nimport re\n\nfrom .charsetgroupprober import CharSetGroupProber\nfrom .enums import InputState, LanguageFilter, ProbingState\nfrom .escprober import EscCharSetProber\nfrom .latin1prober import Latin1Prober\nfrom .mbcsgroupprober import MBCSGroupProber\nfrom .sbcsgroupprober import SBCSGroupProber\nfrom .utf1632prober import UTF1632Prober\n\n\nclass UniversalDetector:\n    \"\"\"\n    The ``UniversalDetector`` class underlies the ``chardet.detect`` function\n    and coordinates all of the different charset probers.\n\n    To get a ``dict`` containing an encoding and its confidence, you can simply\n    run:\n\n    .. code::\n\n            u = UniversalDetector()\n            u.feed(some_bytes)\n            u.close()\n            detected = u.result\n\n    \"\"\"\n\n    MINIMUM_THRESHOLD = 0.20\n    HIGH_BYTE_DETECTOR = re.compile(b\"[\\x80-\\xFF]\")\n    ESC_DETECTOR = re.compile(b\"(\\033|~{)\")\n    WIN_BYTE_DETECTOR = re.compile(b\"[\\x80-\\x9F]\")\n    ISO_WIN_MAP = {\n        \"iso-8859-1\": \"Windows-1252\",\n        \"iso-8859-2\": \"Windows-1250\",\n        \"iso-8859-5\": \"Windows-1251\",\n        \"iso-8859-6\": \"Windows-1256\",\n        \"iso-8859-7\": \"Windows-1253\",\n        \"iso-8859-8\": \"Windows-1255\",\n        \"iso-8859-9\": \"Windows-1254\",\n        \"iso-8859-13\": \"Windows-1257\",\n    }\n\n    def __init__(self, lang_filter=LanguageFilter.ALL):\n        self._esc_charset_prober = None\n        self._utf1632_prober = None\n        self._charset_probers = []\n        self.result = None\n        self.done = None\n        self._got_data = None\n        self._input_state = None\n        self._last_char = None\n        self.lang_filter = lang_filter\n        self.logger = logging.getLogger(__name__)\n        self._has_win_bytes = None\n        self.reset()\n\n    @property\n    def input_state(self):\n        return self._input_state\n\n    @property\n    def has_win_bytes(self):\n        return self._has_win_bytes\n\n    @property\n    def charset_probers(self):\n        return self._charset_probers\n\n    def reset(self):\n        \"\"\"\n        Reset the UniversalDetector and all of its probers back to their\n        initial states.  This is called by ``__init__``, so you only need to\n        call this directly in between analyses of different documents.\n        \"\"\"\n        self.result = {\"encoding\": None, \"confidence\": 0.0, \"language\": None}\n        self.done = False\n        self._got_data = False\n        self._has_win_bytes = False\n        self._input_state = InputState.PURE_ASCII\n        self._last_char = b\"\"\n        if self._esc_charset_prober:\n            self._esc_charset_prober.reset()\n        if self._utf1632_prober:\n            self._utf1632_prober.reset()\n        for prober in self._charset_probers:\n            prober.reset()\n\n    def feed(self, byte_str):\n        \"\"\"\n        Takes a chunk of a document and feeds it through all of the relevant\n        charset probers.\n\n        After calling ``feed``, you can check the value of the ``done``\n        attribute to see if you need to continue feeding the\n        ``UniversalDetector`` more data, or if it has made a prediction\n        (in the ``result`` attribute).\n\n        .. note::\n           You should always call ``close`` when you're done feeding in your\n           document if ``done`` is not already ``True``.\n        \"\"\"\n        if self.done:\n            return\n\n        if not byte_str:\n            return\n\n        if not isinstance(byte_str, bytearray):\n            byte_str = bytearray(byte_str)\n\n        # First check for known BOMs, since these are guaranteed to be correct\n        if not self._got_data:\n            # If the data starts with BOM, we know it is UTF\n            if byte_str.startswith(codecs.BOM_UTF8):\n                # EF BB BF  UTF-8 with BOM\n                self.result = {\n                    \"encoding\": \"UTF-8-SIG\",\n                    \"confidence\": 1.0,\n                    \"language\": \"\",\n                }\n            elif byte_str.startswith((codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)):\n                # FF FE 00 00  UTF-32, little-endian BOM\n                # 00 00 FE FF  UTF-32, big-endian BOM\n                self.result = {\"encoding\": \"UTF-32\", \"confidence\": 1.0, \"language\": \"\"}\n            elif byte_str.startswith(b\"\\xFE\\xFF\\x00\\x00\"):\n                # FE FF 00 00  UCS-4, unusual octet order BOM (3412)\n                self.result = {\n                    \"encoding\": \"X-ISO-10646-UCS-4-3412\",\n                    \"confidence\": 1.0,\n                    \"language\": \"\",\n                }\n            elif byte_str.startswith(b\"\\x00\\x00\\xFF\\xFE\"):\n                # 00 00 FF FE  UCS-4, unusual octet order BOM (2143)\n                self.result = {\n                    \"encoding\": \"X-ISO-10646-UCS-4-2143\",\n                    \"confidence\": 1.0,\n                    \"language\": \"\",\n                }\n            elif byte_str.startswith((codecs.BOM_LE, codecs.BOM_BE)):\n                # FF FE  UTF-16, little endian BOM\n                # FE FF  UTF-16, big endian BOM\n                self.result = {\"encoding\": \"UTF-16\", \"confidence\": 1.0, \"language\": \"\"}\n\n            self._got_data = True\n            if self.result[\"encoding\"] is not None:\n                self.done = True\n                return\n\n        # If none of those matched and we've only see ASCII so far, check\n        # for high bytes and escape sequences\n        if self._input_state == InputState.PURE_ASCII:\n            if self.HIGH_BYTE_DETECTOR.search(byte_str):\n                self._input_state = InputState.HIGH_BYTE\n            elif (\n                self._input_state == InputState.PURE_ASCII\n                and self.ESC_DETECTOR.search(self._last_char + byte_str)\n            ):\n                self._input_state = InputState.ESC_ASCII\n\n        self._last_char = byte_str[-1:]\n\n        # next we will look to see if it is appears to be either a UTF-16 or\n        # UTF-32 encoding\n        if not self._utf1632_prober:\n            self._utf1632_prober = UTF1632Prober()\n\n        if self._utf1632_prober.state == ProbingState.DETECTING:\n            if self._utf1632_prober.feed(byte_str) == ProbingState.FOUND_IT:\n                self.result = {\n                    \"encoding\": self._utf1632_prober.charset_name,\n                    \"confidence\": self._utf1632_prober.get_confidence(),\n                    \"language\": \"\",\n                }\n                self.done = True\n                return\n\n        # If we've seen escape sequences, use the EscCharSetProber, which\n        # uses a simple state machine to check for known escape sequences in\n        # HZ and ISO-2022 encodings, since those are the only encodings that\n        # use such sequences.\n        if self._input_state == InputState.ESC_ASCII:\n            if not self._esc_charset_prober:\n                self._esc_charset_prober = EscCharSetProber(self.lang_filter)\n            if self._esc_charset_prober.feed(byte_str) == ProbingState.FOUND_IT:\n                self.result = {\n                    \"encoding\": self._esc_charset_prober.charset_name,\n                    \"confidence\": self._esc_charset_prober.get_confidence(),\n                    \"language\": self._esc_charset_prober.language,\n                }\n                self.done = True\n        # If we've seen high bytes (i.e., those with values greater than 127),\n        # we need to do more complicated checks using all our multi-byte and\n        # single-byte probers that are left.  The single-byte probers\n        # use character bigram distributions to determine the encoding, whereas\n        # the multi-byte probers use a combination of character unigram and\n        # bigram distributions.\n        elif self._input_state == InputState.HIGH_BYTE:\n            if not self._charset_probers:\n                self._charset_probers = [MBCSGroupProber(self.lang_filter)]\n                # If we're checking non-CJK encodings, use single-byte prober\n                if self.lang_filter & LanguageFilter.NON_CJK:\n                    self._charset_probers.append(SBCSGroupProber())\n                self._charset_probers.append(Latin1Prober())\n            for prober in self._charset_probers:\n                if prober.feed(byte_str) == ProbingState.FOUND_IT:\n                    self.result = {\n                        \"encoding\": prober.charset_name,\n                        \"confidence\": prober.get_confidence(),\n                        \"language\": prober.language,\n                    }\n                    self.done = True\n                    break\n            if self.WIN_BYTE_DETECTOR.search(byte_str):\n                self._has_win_bytes = True\n\n    def close(self):\n        \"\"\"\n        Stop analyzing the current document and come up with a final\n        prediction.\n\n        :returns:  The ``result`` attribute, a ``dict`` with the keys\n                   `encoding`, `confidence`, and `language`.\n        \"\"\"\n        # Don't bother with checks if we're already done\n        if self.done:\n            return self.result\n        self.done = True\n\n        if not self._got_data:\n            self.logger.debug(\"no data received!\")\n\n        # Default to ASCII if it is all we've seen so far\n        elif self._input_state == InputState.PURE_ASCII:\n            self.result = {\"encoding\": \"ascii\", \"confidence\": 1.0, \"language\": \"\"}\n\n        # If we have seen non-ASCII, return the best that met MINIMUM_THRESHOLD\n        elif self._input_state == InputState.HIGH_BYTE:\n            prober_confidence = None\n            max_prober_confidence = 0.0\n            max_prober = None\n            for prober in self._charset_probers:\n                if not prober:\n                    continue\n                prober_confidence = prober.get_confidence()\n                if prober_confidence > max_prober_confidence:\n                    max_prober_confidence = prober_confidence\n                    max_prober = prober\n            if max_prober and (max_prober_confidence > self.MINIMUM_THRESHOLD):\n                charset_name = max_prober.charset_name\n                lower_charset_name = max_prober.charset_name.lower()\n                confidence = max_prober.get_confidence()\n                # Use Windows encoding name instead of ISO-8859 if we saw any\n                # extra Windows-specific bytes\n                if lower_charset_name.startswith(\"iso-8859\"):\n                    if self._has_win_bytes:\n                        charset_name = self.ISO_WIN_MAP.get(\n                            lower_charset_name, charset_name\n                        )\n                self.result = {\n                    \"encoding\": charset_name,\n                    \"confidence\": confidence,\n                    \"language\": max_prober.language,\n                }\n\n        # Log all prober confidences if none met MINIMUM_THRESHOLD\n        if self.logger.getEffectiveLevel() <= logging.DEBUG:\n            if self.result[\"encoding\"] is None:\n                self.logger.debug(\"no probers hit minimum threshold\")\n                for group_prober in self._charset_probers:\n                    if not group_prober:\n                        continue\n                    if isinstance(group_prober, CharSetGroupProber):\n                        for prober in group_prober.probers:\n                            self.logger.debug(\n                                \"%s %s confidence = %s\",\n                                prober.charset_name,\n                                prober.language,\n                                prober.get_confidence(),\n                            )\n                    else:\n                        self.logger.debug(\n                            \"%s %s confidence = %s\",\n                            group_prober.charset_name,\n                            group_prober.language,\n                            group_prober.get_confidence(),\n                        )\n        return self.result\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/utf1632prober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n#\n# Contributor(s):\n#   Jason Zavaglia\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\nfrom .charsetprober import CharSetProber\nfrom .enums import ProbingState\n\n\nclass UTF1632Prober(CharSetProber):\n    \"\"\"\n    This class simply looks for occurrences of zero bytes, and infers\n    whether the file is UTF16 or UTF32 (low-endian or big-endian)\n    For instance, files looking like ( \\0 \\0 \\0 [nonzero] )+\n    have a good probability to be UTF32BE.  Files looking like ( \\0 [nonzero] )+\n    may be guessed to be UTF16BE, and inversely for little-endian varieties.\n    \"\"\"\n\n    # how many logical characters to scan before feeling confident of prediction\n    MIN_CHARS_FOR_DETECTION = 20\n    # a fixed constant ratio of expected zeros or non-zeros in modulo-position.\n    EXPECTED_RATIO = 0.94\n\n    def __init__(self):\n        super().__init__()\n        self.position = 0\n        self.zeros_at_mod = [0] * 4\n        self.nonzeros_at_mod = [0] * 4\n        self._state = ProbingState.DETECTING\n        self.quad = [0, 0, 0, 0]\n        self.invalid_utf16be = False\n        self.invalid_utf16le = False\n        self.invalid_utf32be = False\n        self.invalid_utf32le = False\n        self.first_half_surrogate_pair_detected_16be = False\n        self.first_half_surrogate_pair_detected_16le = False\n        self.reset()\n\n    def reset(self):\n        super().reset()\n        self.position = 0\n        self.zeros_at_mod = [0] * 4\n        self.nonzeros_at_mod = [0] * 4\n        self._state = ProbingState.DETECTING\n        self.invalid_utf16be = False\n        self.invalid_utf16le = False\n        self.invalid_utf32be = False\n        self.invalid_utf32le = False\n        self.first_half_surrogate_pair_detected_16be = False\n        self.first_half_surrogate_pair_detected_16le = False\n        self.quad = [0, 0, 0, 0]\n\n    @property\n    def charset_name(self):\n        if self.is_likely_utf32be():\n            return \"utf-32be\"\n        if self.is_likely_utf32le():\n            return \"utf-32le\"\n        if self.is_likely_utf16be():\n            return \"utf-16be\"\n        if self.is_likely_utf16le():\n            return \"utf-16le\"\n        # default to something valid\n        return \"utf-16\"\n\n    @property\n    def language(self):\n        return \"\"\n\n    def approx_32bit_chars(self):\n        return max(1.0, self.position / 4.0)\n\n    def approx_16bit_chars(self):\n        return max(1.0, self.position / 2.0)\n\n    def is_likely_utf32be(self):\n        approx_chars = self.approx_32bit_chars()\n        return approx_chars >= self.MIN_CHARS_FOR_DETECTION and (\n            self.zeros_at_mod[0] / approx_chars > self.EXPECTED_RATIO\n            and self.zeros_at_mod[1] / approx_chars > self.EXPECTED_RATIO\n            and self.zeros_at_mod[2] / approx_chars > self.EXPECTED_RATIO\n            and self.nonzeros_at_mod[3] / approx_chars > self.EXPECTED_RATIO\n            and not self.invalid_utf32be\n        )\n\n    def is_likely_utf32le(self):\n        approx_chars = self.approx_32bit_chars()\n        return approx_chars >= self.MIN_CHARS_FOR_DETECTION and (\n            self.nonzeros_at_mod[0] / approx_chars > self.EXPECTED_RATIO\n            and self.zeros_at_mod[1] / approx_chars > self.EXPECTED_RATIO\n            and self.zeros_at_mod[2] / approx_chars > self.EXPECTED_RATIO\n            and self.zeros_at_mod[3] / approx_chars > self.EXPECTED_RATIO\n            and not self.invalid_utf32le\n        )\n\n    def is_likely_utf16be(self):\n        approx_chars = self.approx_16bit_chars()\n        return approx_chars >= self.MIN_CHARS_FOR_DETECTION and (\n            (self.nonzeros_at_mod[1] + self.nonzeros_at_mod[3]) / approx_chars\n            > self.EXPECTED_RATIO\n            and (self.zeros_at_mod[0] + self.zeros_at_mod[2]) / approx_chars\n            > self.EXPECTED_RATIO\n            and not self.invalid_utf16be\n        )\n\n    def is_likely_utf16le(self):\n        approx_chars = self.approx_16bit_chars()\n        return approx_chars >= self.MIN_CHARS_FOR_DETECTION and (\n            (self.nonzeros_at_mod[0] + self.nonzeros_at_mod[2]) / approx_chars\n            > self.EXPECTED_RATIO\n            and (self.zeros_at_mod[1] + self.zeros_at_mod[3]) / approx_chars\n            > self.EXPECTED_RATIO\n            and not self.invalid_utf16le\n        )\n\n    def validate_utf32_characters(self, quad):\n        \"\"\"\n        Validate if the quad of bytes is valid UTF-32.\n\n        UTF-32 is valid in the range 0x00000000 - 0x0010FFFF\n        excluding 0x0000D800 - 0x0000DFFF\n\n        https://en.wikipedia.org/wiki/UTF-32\n        \"\"\"\n        if (\n            quad[0] != 0\n            or quad[1] > 0x10\n            or (quad[0] == 0 and quad[1] == 0 and 0xD8 <= quad[2] <= 0xDF)\n        ):\n            self.invalid_utf32be = True\n        if (\n            quad[3] != 0\n            or quad[2] > 0x10\n            or (quad[3] == 0 and quad[2] == 0 and 0xD8 <= quad[1] <= 0xDF)\n        ):\n            self.invalid_utf32le = True\n\n    def validate_utf16_characters(self, pair):\n        \"\"\"\n        Validate if the pair of bytes is  valid UTF-16.\n\n        UTF-16 is valid in the range 0x0000 - 0xFFFF excluding 0xD800 - 0xFFFF\n        with an exception for surrogate pairs, which must be in the range\n        0xD800-0xDBFF followed by 0xDC00-0xDFFF\n\n        https://en.wikipedia.org/wiki/UTF-16\n        \"\"\"\n        if not self.first_half_surrogate_pair_detected_16be:\n            if 0xD8 <= pair[0] <= 0xDB:\n                self.first_half_surrogate_pair_detected_16be = True\n            elif 0xDC <= pair[0] <= 0xDF:\n                self.invalid_utf16be = True\n        else:\n            if 0xDC <= pair[0] <= 0xDF:\n                self.first_half_surrogate_pair_detected_16be = False\n            else:\n                self.invalid_utf16be = True\n\n        if not self.first_half_surrogate_pair_detected_16le:\n            if 0xD8 <= pair[1] <= 0xDB:\n                self.first_half_surrogate_pair_detected_16le = True\n            elif 0xDC <= pair[1] <= 0xDF:\n                self.invalid_utf16le = True\n        else:\n            if 0xDC <= pair[1] <= 0xDF:\n                self.first_half_surrogate_pair_detected_16le = False\n            else:\n                self.invalid_utf16le = True\n\n    def feed(self, byte_str):\n        for c in byte_str:\n            mod4 = self.position % 4\n            self.quad[mod4] = c\n            if mod4 == 3:\n                self.validate_utf32_characters(self.quad)\n                self.validate_utf16_characters(self.quad[0:2])\n                self.validate_utf16_characters(self.quad[2:4])\n            if c == 0:\n                self.zeros_at_mod[mod4] += 1\n            else:\n                self.nonzeros_at_mod[mod4] += 1\n            self.position += 1\n        return self.state\n\n    @property\n    def state(self):\n        if self._state in {ProbingState.NOT_ME, ProbingState.FOUND_IT}:\n            # terminal, decided states\n            return self._state\n        if self.get_confidence() > 0.80:\n            self._state = ProbingState.FOUND_IT\n        elif self.position > 4 * 1024:\n            # if we get to 4kb into the file, and we can't conclude it's UTF,\n            # let's give up\n            self._state = ProbingState.NOT_ME\n        return self._state\n\n    def get_confidence(self):\n        return (\n            0.85\n            if (\n                self.is_likely_utf16le()\n                or self.is_likely_utf16be()\n                or self.is_likely_utf32le()\n                or self.is_likely_utf32be()\n            )\n            else 0.00\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/utf8prober.py",
    "content": "######################## BEGIN LICENSE BLOCK ########################\n# The Original Code is mozilla.org code.\n#\n# The Initial Developer of the Original Code is\n# Netscape Communications Corporation.\n# Portions created by the Initial Developer are Copyright (C) 1998\n# the Initial Developer. All Rights Reserved.\n#\n# Contributor(s):\n#   Mark Pilgrim - port to Python\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA\n# 02110-1301  USA\n######################### END LICENSE BLOCK #########################\n\nfrom .charsetprober import CharSetProber\nfrom .codingstatemachine import CodingStateMachine\nfrom .enums import MachineState, ProbingState\nfrom .mbcssm import UTF8_SM_MODEL\n\n\nclass UTF8Prober(CharSetProber):\n    ONE_CHAR_PROB = 0.5\n\n    def __init__(self):\n        super().__init__()\n        self.coding_sm = CodingStateMachine(UTF8_SM_MODEL)\n        self._num_mb_chars = None\n        self.reset()\n\n    def reset(self):\n        super().reset()\n        self.coding_sm.reset()\n        self._num_mb_chars = 0\n\n    @property\n    def charset_name(self):\n        return \"utf-8\"\n\n    @property\n    def language(self):\n        return \"\"\n\n    def feed(self, byte_str):\n        for c in byte_str:\n            coding_state = self.coding_sm.next_state(c)\n            if coding_state == MachineState.ERROR:\n                self._state = ProbingState.NOT_ME\n                break\n            if coding_state == MachineState.ITS_ME:\n                self._state = ProbingState.FOUND_IT\n                break\n            if coding_state == MachineState.START:\n                if self.coding_sm.get_current_charlen() >= 2:\n                    self._num_mb_chars += 1\n\n        if self.state == ProbingState.DETECTING:\n            if self.get_confidence() > self.SHORTCUT_THRESHOLD:\n                self._state = ProbingState.FOUND_IT\n\n        return self.state\n\n    def get_confidence(self):\n        unlike = 0.99\n        if self._num_mb_chars < 6:\n            unlike *= self.ONE_CHAR_PROB**self._num_mb_chars\n            return 1.0 - unlike\n        return unlike\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/chardet/version.py",
    "content": "\"\"\"\nThis module exists only to simplify retrieving the version number of chardet\nfrom within setup.py and from chardet subpackages.\n\n:author: Dan Blanchard (dan.blanchard@gmail.com)\n\"\"\"\n\n__version__ = \"5.0.0\"\nVERSION = __version__.split(\".\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/colorama/__init__.py",
    "content": "# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.\nfrom .initialise import init, deinit, reinit, colorama_text\nfrom .ansi import Fore, Back, Style, Cursor\nfrom .ansitowin32 import AnsiToWin32\n\n__version__ = '0.4.5'\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/colorama/ansi.py",
    "content": "# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.\n'''\nThis module generates ANSI character codes to printing colors to terminals.\nSee: http://en.wikipedia.org/wiki/ANSI_escape_code\n'''\n\nCSI = '\\033['\nOSC = '\\033]'\nBEL = '\\a'\n\n\ndef code_to_chars(code):\n    return CSI + str(code) + 'm'\n\ndef set_title(title):\n    return OSC + '2;' + title + BEL\n\ndef clear_screen(mode=2):\n    return CSI + str(mode) + 'J'\n\ndef clear_line(mode=2):\n    return CSI + str(mode) + 'K'\n\n\nclass AnsiCodes(object):\n    def __init__(self):\n        # the subclasses declare class attributes which are numbers.\n        # Upon instantiation we define instance attributes, which are the same\n        # as the class attributes but wrapped with the ANSI escape sequence\n        for name in dir(self):\n            if not name.startswith('_'):\n                value = getattr(self, name)\n                setattr(self, name, code_to_chars(value))\n\n\nclass AnsiCursor(object):\n    def UP(self, n=1):\n        return CSI + str(n) + 'A'\n    def DOWN(self, n=1):\n        return CSI + str(n) + 'B'\n    def FORWARD(self, n=1):\n        return CSI + str(n) + 'C'\n    def BACK(self, n=1):\n        return CSI + str(n) + 'D'\n    def POS(self, x=1, y=1):\n        return CSI + str(y) + ';' + str(x) + 'H'\n\n\nclass AnsiFore(AnsiCodes):\n    BLACK           = 30\n    RED             = 31\n    GREEN           = 32\n    YELLOW          = 33\n    BLUE            = 34\n    MAGENTA         = 35\n    CYAN            = 36\n    WHITE           = 37\n    RESET           = 39\n\n    # These are fairly well supported, but not part of the standard.\n    LIGHTBLACK_EX   = 90\n    LIGHTRED_EX     = 91\n    LIGHTGREEN_EX   = 92\n    LIGHTYELLOW_EX  = 93\n    LIGHTBLUE_EX    = 94\n    LIGHTMAGENTA_EX = 95\n    LIGHTCYAN_EX    = 96\n    LIGHTWHITE_EX   = 97\n\n\nclass AnsiBack(AnsiCodes):\n    BLACK           = 40\n    RED             = 41\n    GREEN           = 42\n    YELLOW          = 43\n    BLUE            = 44\n    MAGENTA         = 45\n    CYAN            = 46\n    WHITE           = 47\n    RESET           = 49\n\n    # These are fairly well supported, but not part of the standard.\n    LIGHTBLACK_EX   = 100\n    LIGHTRED_EX     = 101\n    LIGHTGREEN_EX   = 102\n    LIGHTYELLOW_EX  = 103\n    LIGHTBLUE_EX    = 104\n    LIGHTMAGENTA_EX = 105\n    LIGHTCYAN_EX    = 106\n    LIGHTWHITE_EX   = 107\n\n\nclass AnsiStyle(AnsiCodes):\n    BRIGHT    = 1\n    DIM       = 2\n    NORMAL    = 22\n    RESET_ALL = 0\n\nFore   = AnsiFore()\nBack   = AnsiBack()\nStyle  = AnsiStyle()\nCursor = AnsiCursor()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/colorama/ansitowin32.py",
    "content": "# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.\nimport re\nimport sys\nimport os\n\nfrom .ansi import AnsiFore, AnsiBack, AnsiStyle, Style, BEL\nfrom .winterm import WinTerm, WinColor, WinStyle\nfrom .win32 import windll, winapi_test\n\n\nwinterm = None\nif windll is not None:\n    winterm = WinTerm()\n\n\nclass StreamWrapper(object):\n    '''\n    Wraps a stream (such as stdout), acting as a transparent proxy for all\n    attribute access apart from method 'write()', which is delegated to our\n    Converter instance.\n    '''\n    def __init__(self, wrapped, converter):\n        # double-underscore everything to prevent clashes with names of\n        # attributes on the wrapped stream object.\n        self.__wrapped = wrapped\n        self.__convertor = converter\n\n    def __getattr__(self, name):\n        return getattr(self.__wrapped, name)\n\n    def __enter__(self, *args, **kwargs):\n        # special method lookup bypasses __getattr__/__getattribute__, see\n        # https://stackoverflow.com/questions/12632894/why-doesnt-getattr-work-with-exit\n        # thus, contextlib magic methods are not proxied via __getattr__\n        return self.__wrapped.__enter__(*args, **kwargs)\n\n    def __exit__(self, *args, **kwargs):\n        return self.__wrapped.__exit__(*args, **kwargs)\n\n    def __setstate__(self, state):\n        self.__dict__ = state\n\n    def __getstate__(self):\n        return self.__dict__\n\n    def write(self, text):\n        self.__convertor.write(text)\n\n    def isatty(self):\n        stream = self.__wrapped\n        if 'PYCHARM_HOSTED' in os.environ:\n            if stream is not None and (stream is sys.__stdout__ or stream is sys.__stderr__):\n                return True\n        try:\n            stream_isatty = stream.isatty\n        except AttributeError:\n            return False\n        else:\n            return stream_isatty()\n\n    @property\n    def closed(self):\n        stream = self.__wrapped\n        try:\n            return stream.closed\n        # AttributeError in the case that the stream doesn't support being closed\n        # ValueError for the case that the stream has already been detached when atexit runs\n        except (AttributeError, ValueError):\n            return True\n\n\nclass AnsiToWin32(object):\n    '''\n    Implements a 'write()' method which, on Windows, will strip ANSI character\n    sequences from the text, and if outputting to a tty, will convert them into\n    win32 function calls.\n    '''\n    ANSI_CSI_RE = re.compile('\\001?\\033\\\\[((?:\\\\d|;)*)([a-zA-Z])\\002?')   # Control Sequence Introducer\n    ANSI_OSC_RE = re.compile('\\001?\\033\\\\]([^\\a]*)(\\a)\\002?')             # Operating System Command\n\n    def __init__(self, wrapped, convert=None, strip=None, autoreset=False):\n        # The wrapped stream (normally sys.stdout or sys.stderr)\n        self.wrapped = wrapped\n\n        # should we reset colors to defaults after every .write()\n        self.autoreset = autoreset\n\n        # create the proxy wrapping our output stream\n        self.stream = StreamWrapper(wrapped, self)\n\n        on_windows = os.name == 'nt'\n        # We test if the WinAPI works, because even if we are on Windows\n        # we may be using a terminal that doesn't support the WinAPI\n        # (e.g. Cygwin Terminal). In this case it's up to the terminal\n        # to support the ANSI codes.\n        conversion_supported = on_windows and winapi_test()\n\n        # should we strip ANSI sequences from our output?\n        if strip is None:\n            strip = conversion_supported or (not self.stream.closed and not self.stream.isatty())\n        self.strip = strip\n\n        # should we should convert ANSI sequences into win32 calls?\n        if convert is None:\n            convert = conversion_supported and not self.stream.closed and self.stream.isatty()\n        self.convert = convert\n\n        # dict of ansi codes to win32 functions and parameters\n        self.win32_calls = self.get_win32_calls()\n\n        # are we wrapping stderr?\n        self.on_stderr = self.wrapped is sys.stderr\n\n    def should_wrap(self):\n        '''\n        True if this class is actually needed. If false, then the output\n        stream will not be affected, nor will win32 calls be issued, so\n        wrapping stdout is not actually required. This will generally be\n        False on non-Windows platforms, unless optional functionality like\n        autoreset has been requested using kwargs to init()\n        '''\n        return self.convert or self.strip or self.autoreset\n\n    def get_win32_calls(self):\n        if self.convert and winterm:\n            return {\n                AnsiStyle.RESET_ALL: (winterm.reset_all, ),\n                AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT),\n                AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL),\n                AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL),\n                AnsiFore.BLACK: (winterm.fore, WinColor.BLACK),\n                AnsiFore.RED: (winterm.fore, WinColor.RED),\n                AnsiFore.GREEN: (winterm.fore, WinColor.GREEN),\n                AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW),\n                AnsiFore.BLUE: (winterm.fore, WinColor.BLUE),\n                AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA),\n                AnsiFore.CYAN: (winterm.fore, WinColor.CYAN),\n                AnsiFore.WHITE: (winterm.fore, WinColor.GREY),\n                AnsiFore.RESET: (winterm.fore, ),\n                AnsiFore.LIGHTBLACK_EX: (winterm.fore, WinColor.BLACK, True),\n                AnsiFore.LIGHTRED_EX: (winterm.fore, WinColor.RED, True),\n                AnsiFore.LIGHTGREEN_EX: (winterm.fore, WinColor.GREEN, True),\n                AnsiFore.LIGHTYELLOW_EX: (winterm.fore, WinColor.YELLOW, True),\n                AnsiFore.LIGHTBLUE_EX: (winterm.fore, WinColor.BLUE, True),\n                AnsiFore.LIGHTMAGENTA_EX: (winterm.fore, WinColor.MAGENTA, True),\n                AnsiFore.LIGHTCYAN_EX: (winterm.fore, WinColor.CYAN, True),\n                AnsiFore.LIGHTWHITE_EX: (winterm.fore, WinColor.GREY, True),\n                AnsiBack.BLACK: (winterm.back, WinColor.BLACK),\n                AnsiBack.RED: (winterm.back, WinColor.RED),\n                AnsiBack.GREEN: (winterm.back, WinColor.GREEN),\n                AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW),\n                AnsiBack.BLUE: (winterm.back, WinColor.BLUE),\n                AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA),\n                AnsiBack.CYAN: (winterm.back, WinColor.CYAN),\n                AnsiBack.WHITE: (winterm.back, WinColor.GREY),\n                AnsiBack.RESET: (winterm.back, ),\n                AnsiBack.LIGHTBLACK_EX: (winterm.back, WinColor.BLACK, True),\n                AnsiBack.LIGHTRED_EX: (winterm.back, WinColor.RED, True),\n                AnsiBack.LIGHTGREEN_EX: (winterm.back, WinColor.GREEN, True),\n                AnsiBack.LIGHTYELLOW_EX: (winterm.back, WinColor.YELLOW, True),\n                AnsiBack.LIGHTBLUE_EX: (winterm.back, WinColor.BLUE, True),\n                AnsiBack.LIGHTMAGENTA_EX: (winterm.back, WinColor.MAGENTA, True),\n                AnsiBack.LIGHTCYAN_EX: (winterm.back, WinColor.CYAN, True),\n                AnsiBack.LIGHTWHITE_EX: (winterm.back, WinColor.GREY, True),\n            }\n        return dict()\n\n    def write(self, text):\n        if self.strip or self.convert:\n            self.write_and_convert(text)\n        else:\n            self.wrapped.write(text)\n            self.wrapped.flush()\n        if self.autoreset:\n            self.reset_all()\n\n\n    def reset_all(self):\n        if self.convert:\n            self.call_win32('m', (0,))\n        elif not self.strip and not self.stream.closed:\n            self.wrapped.write(Style.RESET_ALL)\n\n\n    def write_and_convert(self, text):\n        '''\n        Write the given text to our wrapped stream, stripping any ANSI\n        sequences from the text, and optionally converting them into win32\n        calls.\n        '''\n        cursor = 0\n        text = self.convert_osc(text)\n        for match in self.ANSI_CSI_RE.finditer(text):\n            start, end = match.span()\n            self.write_plain_text(text, cursor, start)\n            self.convert_ansi(*match.groups())\n            cursor = end\n        self.write_plain_text(text, cursor, len(text))\n\n\n    def write_plain_text(self, text, start, end):\n        if start < end:\n            self.wrapped.write(text[start:end])\n            self.wrapped.flush()\n\n\n    def convert_ansi(self, paramstring, command):\n        if self.convert:\n            params = self.extract_params(command, paramstring)\n            self.call_win32(command, params)\n\n\n    def extract_params(self, command, paramstring):\n        if command in 'Hf':\n            params = tuple(int(p) if len(p) != 0 else 1 for p in paramstring.split(';'))\n            while len(params) < 2:\n                # defaults:\n                params = params + (1,)\n        else:\n            params = tuple(int(p) for p in paramstring.split(';') if len(p) != 0)\n            if len(params) == 0:\n                # defaults:\n                if command in 'JKm':\n                    params = (0,)\n                elif command in 'ABCD':\n                    params = (1,)\n\n        return params\n\n\n    def call_win32(self, command, params):\n        if command == 'm':\n            for param in params:\n                if param in self.win32_calls:\n                    func_args = self.win32_calls[param]\n                    func = func_args[0]\n                    args = func_args[1:]\n                    kwargs = dict(on_stderr=self.on_stderr)\n                    func(*args, **kwargs)\n        elif command in 'J':\n            winterm.erase_screen(params[0], on_stderr=self.on_stderr)\n        elif command in 'K':\n            winterm.erase_line(params[0], on_stderr=self.on_stderr)\n        elif command in 'Hf':     # cursor position - absolute\n            winterm.set_cursor_position(params, on_stderr=self.on_stderr)\n        elif command in 'ABCD':   # cursor position - relative\n            n = params[0]\n            # A - up, B - down, C - forward, D - back\n            x, y = {'A': (0, -n), 'B': (0, n), 'C': (n, 0), 'D': (-n, 0)}[command]\n            winterm.cursor_adjust(x, y, on_stderr=self.on_stderr)\n\n\n    def convert_osc(self, text):\n        for match in self.ANSI_OSC_RE.finditer(text):\n            start, end = match.span()\n            text = text[:start] + text[end:]\n            paramstring, command = match.groups()\n            if command == BEL:\n                if paramstring.count(\";\") == 1:\n                    params = paramstring.split(\";\")\n                    # 0 - change title and icon (we will only change title)\n                    # 1 - change icon (we don't support this)\n                    # 2 - change title\n                    if params[0] in '02':\n                        winterm.set_title(params[1])\n        return text\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/colorama/initialise.py",
    "content": "# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.\nimport atexit\nimport contextlib\nimport sys\n\nfrom .ansitowin32 import AnsiToWin32\n\n\norig_stdout = None\norig_stderr = None\n\nwrapped_stdout = None\nwrapped_stderr = None\n\natexit_done = False\n\n\ndef reset_all():\n    if AnsiToWin32 is not None:    # Issue #74: objects might become None at exit\n        AnsiToWin32(orig_stdout).reset_all()\n\n\ndef init(autoreset=False, convert=None, strip=None, wrap=True):\n\n    if not wrap and any([autoreset, convert, strip]):\n        raise ValueError('wrap=False conflicts with any other arg=True')\n\n    global wrapped_stdout, wrapped_stderr\n    global orig_stdout, orig_stderr\n\n    orig_stdout = sys.stdout\n    orig_stderr = sys.stderr\n\n    if sys.stdout is None:\n        wrapped_stdout = None\n    else:\n        sys.stdout = wrapped_stdout = \\\n            wrap_stream(orig_stdout, convert, strip, autoreset, wrap)\n    if sys.stderr is None:\n        wrapped_stderr = None\n    else:\n        sys.stderr = wrapped_stderr = \\\n            wrap_stream(orig_stderr, convert, strip, autoreset, wrap)\n\n    global atexit_done\n    if not atexit_done:\n        atexit.register(reset_all)\n        atexit_done = True\n\n\ndef deinit():\n    if orig_stdout is not None:\n        sys.stdout = orig_stdout\n    if orig_stderr is not None:\n        sys.stderr = orig_stderr\n\n\n@contextlib.contextmanager\ndef colorama_text(*args, **kwargs):\n    init(*args, **kwargs)\n    try:\n        yield\n    finally:\n        deinit()\n\n\ndef reinit():\n    if wrapped_stdout is not None:\n        sys.stdout = wrapped_stdout\n    if wrapped_stderr is not None:\n        sys.stderr = wrapped_stderr\n\n\ndef wrap_stream(stream, convert, strip, autoreset, wrap):\n    if wrap:\n        wrapper = AnsiToWin32(stream,\n            convert=convert, strip=strip, autoreset=autoreset)\n        if wrapper.should_wrap():\n            stream = wrapper.stream\n    return stream\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/colorama/win32.py",
    "content": "# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.\n\n# from winbase.h\nSTDOUT = -11\nSTDERR = -12\n\ntry:\n    import ctypes\n    from ctypes import LibraryLoader\n    windll = LibraryLoader(ctypes.WinDLL)\n    from ctypes import wintypes\nexcept (AttributeError, ImportError):\n    windll = None\n    SetConsoleTextAttribute = lambda *_: None\n    winapi_test = lambda *_: None\nelse:\n    from ctypes import byref, Structure, c_char, POINTER\n\n    COORD = wintypes._COORD\n\n    class CONSOLE_SCREEN_BUFFER_INFO(Structure):\n        \"\"\"struct in wincon.h.\"\"\"\n        _fields_ = [\n            (\"dwSize\", COORD),\n            (\"dwCursorPosition\", COORD),\n            (\"wAttributes\", wintypes.WORD),\n            (\"srWindow\", wintypes.SMALL_RECT),\n            (\"dwMaximumWindowSize\", COORD),\n        ]\n        def __str__(self):\n            return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % (\n                self.dwSize.Y, self.dwSize.X\n                , self.dwCursorPosition.Y, self.dwCursorPosition.X\n                , self.wAttributes\n                , self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right\n                , self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X\n            )\n\n    _GetStdHandle = windll.kernel32.GetStdHandle\n    _GetStdHandle.argtypes = [\n        wintypes.DWORD,\n    ]\n    _GetStdHandle.restype = wintypes.HANDLE\n\n    _GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo\n    _GetConsoleScreenBufferInfo.argtypes = [\n        wintypes.HANDLE,\n        POINTER(CONSOLE_SCREEN_BUFFER_INFO),\n    ]\n    _GetConsoleScreenBufferInfo.restype = wintypes.BOOL\n\n    _SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute\n    _SetConsoleTextAttribute.argtypes = [\n        wintypes.HANDLE,\n        wintypes.WORD,\n    ]\n    _SetConsoleTextAttribute.restype = wintypes.BOOL\n\n    _SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition\n    _SetConsoleCursorPosition.argtypes = [\n        wintypes.HANDLE,\n        COORD,\n    ]\n    _SetConsoleCursorPosition.restype = wintypes.BOOL\n\n    _FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA\n    _FillConsoleOutputCharacterA.argtypes = [\n        wintypes.HANDLE,\n        c_char,\n        wintypes.DWORD,\n        COORD,\n        POINTER(wintypes.DWORD),\n    ]\n    _FillConsoleOutputCharacterA.restype = wintypes.BOOL\n\n    _FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute\n    _FillConsoleOutputAttribute.argtypes = [\n        wintypes.HANDLE,\n        wintypes.WORD,\n        wintypes.DWORD,\n        COORD,\n        POINTER(wintypes.DWORD),\n    ]\n    _FillConsoleOutputAttribute.restype = wintypes.BOOL\n\n    _SetConsoleTitleW = windll.kernel32.SetConsoleTitleW\n    _SetConsoleTitleW.argtypes = [\n        wintypes.LPCWSTR\n    ]\n    _SetConsoleTitleW.restype = wintypes.BOOL\n\n    def _winapi_test(handle):\n        csbi = CONSOLE_SCREEN_BUFFER_INFO()\n        success = _GetConsoleScreenBufferInfo(\n            handle, byref(csbi))\n        return bool(success)\n\n    def winapi_test():\n        return any(_winapi_test(h) for h in\n                   (_GetStdHandle(STDOUT), _GetStdHandle(STDERR)))\n\n    def GetConsoleScreenBufferInfo(stream_id=STDOUT):\n        handle = _GetStdHandle(stream_id)\n        csbi = CONSOLE_SCREEN_BUFFER_INFO()\n        success = _GetConsoleScreenBufferInfo(\n            handle, byref(csbi))\n        return csbi\n\n    def SetConsoleTextAttribute(stream_id, attrs):\n        handle = _GetStdHandle(stream_id)\n        return _SetConsoleTextAttribute(handle, attrs)\n\n    def SetConsoleCursorPosition(stream_id, position, adjust=True):\n        position = COORD(*position)\n        # If the position is out of range, do nothing.\n        if position.Y <= 0 or position.X <= 0:\n            return\n        # Adjust for Windows' SetConsoleCursorPosition:\n        #    1. being 0-based, while ANSI is 1-based.\n        #    2. expecting (x,y), while ANSI uses (y,x).\n        adjusted_position = COORD(position.Y - 1, position.X - 1)\n        if adjust:\n            # Adjust for viewport's scroll position\n            sr = GetConsoleScreenBufferInfo(STDOUT).srWindow\n            adjusted_position.Y += sr.Top\n            adjusted_position.X += sr.Left\n        # Resume normal processing\n        handle = _GetStdHandle(stream_id)\n        return _SetConsoleCursorPosition(handle, adjusted_position)\n\n    def FillConsoleOutputCharacter(stream_id, char, length, start):\n        handle = _GetStdHandle(stream_id)\n        char = c_char(char.encode())\n        length = wintypes.DWORD(length)\n        num_written = wintypes.DWORD(0)\n        # Note that this is hard-coded for ANSI (vs wide) bytes.\n        success = _FillConsoleOutputCharacterA(\n            handle, char, length, start, byref(num_written))\n        return num_written.value\n\n    def FillConsoleOutputAttribute(stream_id, attr, length, start):\n        ''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )'''\n        handle = _GetStdHandle(stream_id)\n        attribute = wintypes.WORD(attr)\n        length = wintypes.DWORD(length)\n        num_written = wintypes.DWORD(0)\n        # Note that this is hard-coded for ANSI (vs wide) bytes.\n        return _FillConsoleOutputAttribute(\n            handle, attribute, length, start, byref(num_written))\n\n    def SetConsoleTitle(title):\n        return _SetConsoleTitleW(title)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/colorama/winterm.py",
    "content": "# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.\nfrom . import win32\n\n\n# from wincon.h\nclass WinColor(object):\n    BLACK   = 0\n    BLUE    = 1\n    GREEN   = 2\n    CYAN    = 3\n    RED     = 4\n    MAGENTA = 5\n    YELLOW  = 6\n    GREY    = 7\n\n# from wincon.h\nclass WinStyle(object):\n    NORMAL              = 0x00 # dim text, dim background\n    BRIGHT              = 0x08 # bright text, dim background\n    BRIGHT_BACKGROUND   = 0x80 # dim text, bright background\n\nclass WinTerm(object):\n\n    def __init__(self):\n        self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes\n        self.set_attrs(self._default)\n        self._default_fore = self._fore\n        self._default_back = self._back\n        self._default_style = self._style\n        # In order to emulate LIGHT_EX in windows, we borrow the BRIGHT style.\n        # So that LIGHT_EX colors and BRIGHT style do not clobber each other,\n        # we track them separately, since LIGHT_EX is overwritten by Fore/Back\n        # and BRIGHT is overwritten by Style codes.\n        self._light = 0\n\n    def get_attrs(self):\n        return self._fore + self._back * 16 + (self._style | self._light)\n\n    def set_attrs(self, value):\n        self._fore = value & 7\n        self._back = (value >> 4) & 7\n        self._style = value & (WinStyle.BRIGHT | WinStyle.BRIGHT_BACKGROUND)\n\n    def reset_all(self, on_stderr=None):\n        self.set_attrs(self._default)\n        self.set_console(attrs=self._default)\n        self._light = 0\n\n    def fore(self, fore=None, light=False, on_stderr=False):\n        if fore is None:\n            fore = self._default_fore\n        self._fore = fore\n        # Emulate LIGHT_EX with BRIGHT Style\n        if light:\n            self._light |= WinStyle.BRIGHT\n        else:\n            self._light &= ~WinStyle.BRIGHT\n        self.set_console(on_stderr=on_stderr)\n\n    def back(self, back=None, light=False, on_stderr=False):\n        if back is None:\n            back = self._default_back\n        self._back = back\n        # Emulate LIGHT_EX with BRIGHT_BACKGROUND Style\n        if light:\n            self._light |= WinStyle.BRIGHT_BACKGROUND\n        else:\n            self._light &= ~WinStyle.BRIGHT_BACKGROUND\n        self.set_console(on_stderr=on_stderr)\n\n    def style(self, style=None, on_stderr=False):\n        if style is None:\n            style = self._default_style\n        self._style = style\n        self.set_console(on_stderr=on_stderr)\n\n    def set_console(self, attrs=None, on_stderr=False):\n        if attrs is None:\n            attrs = self.get_attrs()\n        handle = win32.STDOUT\n        if on_stderr:\n            handle = win32.STDERR\n        win32.SetConsoleTextAttribute(handle, attrs)\n\n    def get_position(self, handle):\n        position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition\n        # Because Windows coordinates are 0-based,\n        # and win32.SetConsoleCursorPosition expects 1-based.\n        position.X += 1\n        position.Y += 1\n        return position\n\n    def set_cursor_position(self, position=None, on_stderr=False):\n        if position is None:\n            # I'm not currently tracking the position, so there is no default.\n            # position = self.get_position()\n            return\n        handle = win32.STDOUT\n        if on_stderr:\n            handle = win32.STDERR\n        win32.SetConsoleCursorPosition(handle, position)\n\n    def cursor_adjust(self, x, y, on_stderr=False):\n        handle = win32.STDOUT\n        if on_stderr:\n            handle = win32.STDERR\n        position = self.get_position(handle)\n        adjusted_position = (position.Y + y, position.X + x)\n        win32.SetConsoleCursorPosition(handle, adjusted_position, adjust=False)\n\n    def erase_screen(self, mode=0, on_stderr=False):\n        # 0 should clear from the cursor to the end of the screen.\n        # 1 should clear from the cursor to the beginning of the screen.\n        # 2 should clear the entire screen, and move cursor to (1,1)\n        handle = win32.STDOUT\n        if on_stderr:\n            handle = win32.STDERR\n        csbi = win32.GetConsoleScreenBufferInfo(handle)\n        # get the number of character cells in the current buffer\n        cells_in_screen = csbi.dwSize.X * csbi.dwSize.Y\n        # get number of character cells before current cursor position\n        cells_before_cursor = csbi.dwSize.X * csbi.dwCursorPosition.Y + csbi.dwCursorPosition.X\n        if mode == 0:\n            from_coord = csbi.dwCursorPosition\n            cells_to_erase = cells_in_screen - cells_before_cursor\n        elif mode == 1:\n            from_coord = win32.COORD(0, 0)\n            cells_to_erase = cells_before_cursor\n        elif mode == 2:\n            from_coord = win32.COORD(0, 0)\n            cells_to_erase = cells_in_screen\n        else:\n            # invalid mode\n            return\n        # fill the entire screen with blanks\n        win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)\n        # now set the buffer's attributes accordingly\n        win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)\n        if mode == 2:\n            # put the cursor where needed\n            win32.SetConsoleCursorPosition(handle, (1, 1))\n\n    def erase_line(self, mode=0, on_stderr=False):\n        # 0 should clear from the cursor to the end of the line.\n        # 1 should clear from the cursor to the beginning of the line.\n        # 2 should clear the entire line.\n        handle = win32.STDOUT\n        if on_stderr:\n            handle = win32.STDERR\n        csbi = win32.GetConsoleScreenBufferInfo(handle)\n        if mode == 0:\n            from_coord = csbi.dwCursorPosition\n            cells_to_erase = csbi.dwSize.X - csbi.dwCursorPosition.X\n        elif mode == 1:\n            from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)\n            cells_to_erase = csbi.dwCursorPosition.X\n        elif mode == 2:\n            from_coord = win32.COORD(0, csbi.dwCursorPosition.Y)\n            cells_to_erase = csbi.dwSize.X\n        else:\n            # invalid mode\n            return\n        # fill the entire screen with blanks\n        win32.FillConsoleOutputCharacter(handle, ' ', cells_to_erase, from_coord)\n        # now set the buffer's attributes accordingly\n        win32.FillConsoleOutputAttribute(handle, self.get_attrs(), cells_to_erase, from_coord)\n\n    def set_title(self, title):\n        win32.SetConsoleTitle(title)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distlib/__init__.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2012-2022 Vinay Sajip.\n# Licensed to the Python Software Foundation under a contributor agreement.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\nimport logging\n\n__version__ = '0.3.6'\n\nclass DistlibException(Exception):\n    pass\n\ntry:\n    from logging import NullHandler\nexcept ImportError: # pragma: no cover\n    class NullHandler(logging.Handler):\n        def handle(self, record): pass\n        def emit(self, record): pass\n        def createLock(self): self.lock = None\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(NullHandler())\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distlib/compat.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013-2017 Vinay Sajip.\n# Licensed to the Python Software Foundation under a contributor agreement.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\nfrom __future__ import absolute_import\n\nimport os\nimport re\nimport sys\n\ntry:\n    import ssl\nexcept ImportError:  # pragma: no cover\n    ssl = None\n\nif sys.version_info[0] < 3:  # pragma: no cover\n    from StringIO import StringIO\n    string_types = basestring,\n    text_type = unicode\n    from types import FileType as file_type\n    import __builtin__ as builtins\n    import ConfigParser as configparser\n    from urlparse import urlparse, urlunparse, urljoin, urlsplit, urlunsplit\n    from urllib import (urlretrieve, quote as _quote, unquote, url2pathname,\n                        pathname2url, ContentTooShortError, splittype)\n\n    def quote(s):\n        if isinstance(s, unicode):\n            s = s.encode('utf-8')\n        return _quote(s)\n\n    import urllib2\n    from urllib2 import (Request, urlopen, URLError, HTTPError,\n                         HTTPBasicAuthHandler, HTTPPasswordMgr,\n                         HTTPHandler, HTTPRedirectHandler,\n                         build_opener)\n    if ssl:\n        from urllib2 import HTTPSHandler\n    import httplib\n    import xmlrpclib\n    import Queue as queue\n    from HTMLParser import HTMLParser\n    import htmlentitydefs\n    raw_input = raw_input\n    from itertools import ifilter as filter\n    from itertools import ifilterfalse as filterfalse\n\n    # Leaving this around for now, in case it needs resurrecting in some way\n    # _userprog = None\n    # def splituser(host):\n        # \"\"\"splituser('user[:passwd]@host[:port]') --> 'user[:passwd]', 'host[:port]'.\"\"\"\n        # global _userprog\n        # if _userprog is None:\n            # import re\n            # _userprog = re.compile('^(.*)@(.*)$')\n\n        # match = _userprog.match(host)\n        # if match: return match.group(1, 2)\n        # return None, host\n\nelse:  # pragma: no cover\n    from io import StringIO\n    string_types = str,\n    text_type = str\n    from io import TextIOWrapper as file_type\n    import builtins\n    import configparser\n    import shutil\n    from urllib.parse import (urlparse, urlunparse, urljoin, quote,\n                              unquote, urlsplit, urlunsplit, splittype)\n    from urllib.request import (urlopen, urlretrieve, Request, url2pathname,\n                                pathname2url,\n                                HTTPBasicAuthHandler, HTTPPasswordMgr,\n                                HTTPHandler, HTTPRedirectHandler,\n                                build_opener)\n    if ssl:\n        from urllib.request import HTTPSHandler\n    from urllib.error import HTTPError, URLError, ContentTooShortError\n    import http.client as httplib\n    import urllib.request as urllib2\n    import xmlrpc.client as xmlrpclib\n    import queue\n    from html.parser import HTMLParser\n    import html.entities as htmlentitydefs\n    raw_input = input\n    from itertools import filterfalse\n    filter = filter\n\n\ntry:\n    from ssl import match_hostname, CertificateError\nexcept ImportError: # pragma: no cover\n    class CertificateError(ValueError):\n        pass\n\n\n    def _dnsname_match(dn, hostname, max_wildcards=1):\n        \"\"\"Matching according to RFC 6125, section 6.4.3\n\n        http://tools.ietf.org/html/rfc6125#section-6.4.3\n        \"\"\"\n        pats = []\n        if not dn:\n            return False\n\n        parts = dn.split('.')\n        leftmost, remainder = parts[0], parts[1:]\n\n        wildcards = leftmost.count('*')\n        if wildcards > max_wildcards:\n            # Issue #17980: avoid denials of service by refusing more\n            # than one wildcard per fragment.  A survey of established\n            # policy among SSL implementations showed it to be a\n            # reasonable choice.\n            raise CertificateError(\n                \"too many wildcards in certificate DNS name: \" + repr(dn))\n\n        # speed up common case w/o wildcards\n        if not wildcards:\n            return dn.lower() == hostname.lower()\n\n        # RFC 6125, section 6.4.3, subitem 1.\n        # The client SHOULD NOT attempt to match a presented identifier in which\n        # the wildcard character comprises a label other than the left-most label.\n        if leftmost == '*':\n            # When '*' is a fragment by itself, it matches a non-empty dotless\n            # fragment.\n            pats.append('[^.]+')\n        elif leftmost.startswith('xn--') or hostname.startswith('xn--'):\n            # RFC 6125, section 6.4.3, subitem 3.\n            # The client SHOULD NOT attempt to match a presented identifier\n            # where the wildcard character is embedded within an A-label or\n            # U-label of an internationalized domain name.\n            pats.append(re.escape(leftmost))\n        else:\n            # Otherwise, '*' matches any dotless string, e.g. www*\n            pats.append(re.escape(leftmost).replace(r'\\*', '[^.]*'))\n\n        # add the remaining fragments, ignore any wildcards\n        for frag in remainder:\n            pats.append(re.escape(frag))\n\n        pat = re.compile(r'\\A' + r'\\.'.join(pats) + r'\\Z', re.IGNORECASE)\n        return pat.match(hostname)\n\n\n    def match_hostname(cert, hostname):\n        \"\"\"Verify that *cert* (in decoded format as returned by\n        SSLSocket.getpeercert()) matches the *hostname*.  RFC 2818 and RFC 6125\n        rules are followed, but IP addresses are not accepted for *hostname*.\n\n        CertificateError is raised on failure. On success, the function\n        returns nothing.\n        \"\"\"\n        if not cert:\n            raise ValueError(\"empty or no certificate, match_hostname needs a \"\n                             \"SSL socket or SSL context with either \"\n                             \"CERT_OPTIONAL or CERT_REQUIRED\")\n        dnsnames = []\n        san = cert.get('subjectAltName', ())\n        for key, value in san:\n            if key == 'DNS':\n                if _dnsname_match(value, hostname):\n                    return\n                dnsnames.append(value)\n        if not dnsnames:\n            # The subject is only checked when there is no dNSName entry\n            # in subjectAltName\n            for sub in cert.get('subject', ()):\n                for key, value in sub:\n                    # XXX according to RFC 2818, the most specific Common Name\n                    # must be used.\n                    if key == 'commonName':\n                        if _dnsname_match(value, hostname):\n                            return\n                        dnsnames.append(value)\n        if len(dnsnames) > 1:\n            raise CertificateError(\"hostname %r \"\n                \"doesn't match either of %s\"\n                % (hostname, ', '.join(map(repr, dnsnames))))\n        elif len(dnsnames) == 1:\n            raise CertificateError(\"hostname %r \"\n                \"doesn't match %r\"\n                % (hostname, dnsnames[0]))\n        else:\n            raise CertificateError(\"no appropriate commonName or \"\n                \"subjectAltName fields were found\")\n\n\ntry:\n    from types import SimpleNamespace as Container\nexcept ImportError:  # pragma: no cover\n    class Container(object):\n        \"\"\"\n        A generic container for when multiple values need to be returned\n        \"\"\"\n        def __init__(self, **kwargs):\n            self.__dict__.update(kwargs)\n\n\ntry:\n    from shutil import which\nexcept ImportError:  # pragma: no cover\n    # Implementation from Python 3.3\n    def which(cmd, mode=os.F_OK | os.X_OK, path=None):\n        \"\"\"Given a command, mode, and a PATH string, return the path which\n        conforms to the given mode on the PATH, or None if there is no such\n        file.\n\n        `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result\n        of os.environ.get(\"PATH\"), or can be overridden with a custom search\n        path.\n\n        \"\"\"\n        # Check that a given file can be accessed with the correct mode.\n        # Additionally check that `file` is not a directory, as on Windows\n        # directories pass the os.access check.\n        def _access_check(fn, mode):\n            return (os.path.exists(fn) and os.access(fn, mode)\n                    and not os.path.isdir(fn))\n\n        # If we're given a path with a directory part, look it up directly rather\n        # than referring to PATH directories. This includes checking relative to the\n        # current directory, e.g. ./script\n        if os.path.dirname(cmd):\n            if _access_check(cmd, mode):\n                return cmd\n            return None\n\n        if path is None:\n            path = os.environ.get(\"PATH\", os.defpath)\n        if not path:\n            return None\n        path = path.split(os.pathsep)\n\n        if sys.platform == \"win32\":\n            # The current directory takes precedence on Windows.\n            if not os.curdir in path:\n                path.insert(0, os.curdir)\n\n            # PATHEXT is necessary to check on Windows.\n            pathext = os.environ.get(\"PATHEXT\", \"\").split(os.pathsep)\n            # See if the given file matches any of the expected path extensions.\n            # This will allow us to short circuit when given \"python.exe\".\n            # If it does match, only test that one, otherwise we have to try\n            # others.\n            if any(cmd.lower().endswith(ext.lower()) for ext in pathext):\n                files = [cmd]\n            else:\n                files = [cmd + ext for ext in pathext]\n        else:\n            # On other platforms you don't have things like PATHEXT to tell you\n            # what file suffixes are executable, so just pass on cmd as-is.\n            files = [cmd]\n\n        seen = set()\n        for dir in path:\n            normdir = os.path.normcase(dir)\n            if not normdir in seen:\n                seen.add(normdir)\n                for thefile in files:\n                    name = os.path.join(dir, thefile)\n                    if _access_check(name, mode):\n                        return name\n        return None\n\n\n# ZipFile is a context manager in 2.7, but not in 2.6\n\nfrom zipfile import ZipFile as BaseZipFile\n\nif hasattr(BaseZipFile, '__enter__'):  # pragma: no cover\n    ZipFile = BaseZipFile\nelse:  # pragma: no cover\n    from zipfile import ZipExtFile as BaseZipExtFile\n\n    class ZipExtFile(BaseZipExtFile):\n        def __init__(self, base):\n            self.__dict__.update(base.__dict__)\n\n        def __enter__(self):\n            return self\n\n        def __exit__(self, *exc_info):\n            self.close()\n            # return None, so if an exception occurred, it will propagate\n\n    class ZipFile(BaseZipFile):\n        def __enter__(self):\n            return self\n\n        def __exit__(self, *exc_info):\n            self.close()\n            # return None, so if an exception occurred, it will propagate\n\n        def open(self, *args, **kwargs):\n            base = BaseZipFile.open(self, *args, **kwargs)\n            return ZipExtFile(base)\n\ntry:\n    from platform import python_implementation\nexcept ImportError: # pragma: no cover\n    def python_implementation():\n        \"\"\"Return a string identifying the Python implementation.\"\"\"\n        if 'PyPy' in sys.version:\n            return 'PyPy'\n        if os.name == 'java':\n            return 'Jython'\n        if sys.version.startswith('IronPython'):\n            return 'IronPython'\n        return 'CPython'\n\nimport shutil\nimport sysconfig\n\ntry:\n    callable = callable\nexcept NameError:   # pragma: no cover\n    from collections.abc import Callable\n\n    def callable(obj):\n        return isinstance(obj, Callable)\n\n\ntry:\n    fsencode = os.fsencode\n    fsdecode = os.fsdecode\nexcept AttributeError:  # pragma: no cover\n    # Issue #99: on some systems (e.g. containerised),\n    # sys.getfilesystemencoding() returns None, and we need a real value,\n    # so fall back to utf-8. From the CPython 2.7 docs relating to Unix and\n    # sys.getfilesystemencoding(): the return value is \"the user’s preference\n    # according to the result of nl_langinfo(CODESET), or None if the\n    # nl_langinfo(CODESET) failed.\"\n    _fsencoding = sys.getfilesystemencoding() or 'utf-8'\n    if _fsencoding == 'mbcs':\n        _fserrors = 'strict'\n    else:\n        _fserrors = 'surrogateescape'\n\n    def fsencode(filename):\n        if isinstance(filename, bytes):\n            return filename\n        elif isinstance(filename, text_type):\n            return filename.encode(_fsencoding, _fserrors)\n        else:\n            raise TypeError(\"expect bytes or str, not %s\" %\n                            type(filename).__name__)\n\n    def fsdecode(filename):\n        if isinstance(filename, text_type):\n            return filename\n        elif isinstance(filename, bytes):\n            return filename.decode(_fsencoding, _fserrors)\n        else:\n            raise TypeError(\"expect bytes or str, not %s\" %\n                            type(filename).__name__)\n\ntry:\n    from tokenize import detect_encoding\nexcept ImportError: # pragma: no cover\n    from codecs import BOM_UTF8, lookup\n    import re\n\n    cookie_re = re.compile(r\"coding[:=]\\s*([-\\w.]+)\")\n\n    def _get_normal_name(orig_enc):\n        \"\"\"Imitates get_normal_name in tokenizer.c.\"\"\"\n        # Only care about the first 12 characters.\n        enc = orig_enc[:12].lower().replace(\"_\", \"-\")\n        if enc == \"utf-8\" or enc.startswith(\"utf-8-\"):\n            return \"utf-8\"\n        if enc in (\"latin-1\", \"iso-8859-1\", \"iso-latin-1\") or \\\n           enc.startswith((\"latin-1-\", \"iso-8859-1-\", \"iso-latin-1-\")):\n            return \"iso-8859-1\"\n        return orig_enc\n\n    def detect_encoding(readline):\n        \"\"\"\n        The detect_encoding() function is used to detect the encoding that should\n        be used to decode a Python source file.  It requires one argument, readline,\n        in the same way as the tokenize() generator.\n\n        It will call readline a maximum of twice, and return the encoding used\n        (as a string) and a list of any lines (left as bytes) it has read in.\n\n        It detects the encoding from the presence of a utf-8 bom or an encoding\n        cookie as specified in pep-0263.  If both a bom and a cookie are present,\n        but disagree, a SyntaxError will be raised.  If the encoding cookie is an\n        invalid charset, raise a SyntaxError.  Note that if a utf-8 bom is found,\n        'utf-8-sig' is returned.\n\n        If no encoding is specified, then the default of 'utf-8' will be returned.\n        \"\"\"\n        try:\n            filename = readline.__self__.name\n        except AttributeError:\n            filename = None\n        bom_found = False\n        encoding = None\n        default = 'utf-8'\n        def read_or_stop():\n            try:\n                return readline()\n            except StopIteration:\n                return b''\n\n        def find_cookie(line):\n            try:\n                # Decode as UTF-8. Either the line is an encoding declaration,\n                # in which case it should be pure ASCII, or it must be UTF-8\n                # per default encoding.\n                line_string = line.decode('utf-8')\n            except UnicodeDecodeError:\n                msg = \"invalid or missing encoding declaration\"\n                if filename is not None:\n                    msg = '{} for {!r}'.format(msg, filename)\n                raise SyntaxError(msg)\n\n            matches = cookie_re.findall(line_string)\n            if not matches:\n                return None\n            encoding = _get_normal_name(matches[0])\n            try:\n                codec = lookup(encoding)\n            except LookupError:\n                # This behaviour mimics the Python interpreter\n                if filename is None:\n                    msg = \"unknown encoding: \" + encoding\n                else:\n                    msg = \"unknown encoding for {!r}: {}\".format(filename,\n                            encoding)\n                raise SyntaxError(msg)\n\n            if bom_found:\n                if codec.name != 'utf-8':\n                    # This behaviour mimics the Python interpreter\n                    if filename is None:\n                        msg = 'encoding problem: utf-8'\n                    else:\n                        msg = 'encoding problem for {!r}: utf-8'.format(filename)\n                    raise SyntaxError(msg)\n                encoding += '-sig'\n            return encoding\n\n        first = read_or_stop()\n        if first.startswith(BOM_UTF8):\n            bom_found = True\n            first = first[3:]\n            default = 'utf-8-sig'\n        if not first:\n            return default, []\n\n        encoding = find_cookie(first)\n        if encoding:\n            return encoding, [first]\n\n        second = read_or_stop()\n        if not second:\n            return default, [first]\n\n        encoding = find_cookie(second)\n        if encoding:\n            return encoding, [first, second]\n\n        return default, [first, second]\n\n# For converting & <-> &amp; etc.\ntry:\n    from html import escape\nexcept ImportError:\n    from cgi import escape\nif sys.version_info[:2] < (3, 4):\n    unescape = HTMLParser().unescape\nelse:\n    from html import unescape\n\ntry:\n    from collections import ChainMap\nexcept ImportError: # pragma: no cover\n    from collections import MutableMapping\n\n    try:\n        from reprlib import recursive_repr as _recursive_repr\n    except ImportError:\n        def _recursive_repr(fillvalue='...'):\n            '''\n            Decorator to make a repr function return fillvalue for a recursive\n            call\n            '''\n\n            def decorating_function(user_function):\n                repr_running = set()\n\n                def wrapper(self):\n                    key = id(self), get_ident()\n                    if key in repr_running:\n                        return fillvalue\n                    repr_running.add(key)\n                    try:\n                        result = user_function(self)\n                    finally:\n                        repr_running.discard(key)\n                    return result\n\n                # Can't use functools.wraps() here because of bootstrap issues\n                wrapper.__module__ = getattr(user_function, '__module__')\n                wrapper.__doc__ = getattr(user_function, '__doc__')\n                wrapper.__name__ = getattr(user_function, '__name__')\n                wrapper.__annotations__ = getattr(user_function, '__annotations__', {})\n                return wrapper\n\n            return decorating_function\n\n    class ChainMap(MutableMapping):\n        ''' A ChainMap groups multiple dicts (or other mappings) together\n        to create a single, updateable view.\n\n        The underlying mappings are stored in a list.  That list is public and can\n        accessed or updated using the *maps* attribute.  There is no other state.\n\n        Lookups search the underlying mappings successively until a key is found.\n        In contrast, writes, updates, and deletions only operate on the first\n        mapping.\n\n        '''\n\n        def __init__(self, *maps):\n            '''Initialize a ChainMap by setting *maps* to the given mappings.\n            If no mappings are provided, a single empty dictionary is used.\n\n            '''\n            self.maps = list(maps) or [{}]          # always at least one map\n\n        def __missing__(self, key):\n            raise KeyError(key)\n\n        def __getitem__(self, key):\n            for mapping in self.maps:\n                try:\n                    return mapping[key]             # can't use 'key in mapping' with defaultdict\n                except KeyError:\n                    pass\n            return self.__missing__(key)            # support subclasses that define __missing__\n\n        def get(self, key, default=None):\n            return self[key] if key in self else default\n\n        def __len__(self):\n            return len(set().union(*self.maps))     # reuses stored hash values if possible\n\n        def __iter__(self):\n            return iter(set().union(*self.maps))\n\n        def __contains__(self, key):\n            return any(key in m for m in self.maps)\n\n        def __bool__(self):\n            return any(self.maps)\n\n        @_recursive_repr()\n        def __repr__(self):\n            return '{0.__class__.__name__}({1})'.format(\n                self, ', '.join(map(repr, self.maps)))\n\n        @classmethod\n        def fromkeys(cls, iterable, *args):\n            'Create a ChainMap with a single dict created from the iterable.'\n            return cls(dict.fromkeys(iterable, *args))\n\n        def copy(self):\n            'New ChainMap or subclass with a new copy of maps[0] and refs to maps[1:]'\n            return self.__class__(self.maps[0].copy(), *self.maps[1:])\n\n        __copy__ = copy\n\n        def new_child(self):                        # like Django's Context.push()\n            'New ChainMap with a new dict followed by all previous maps.'\n            return self.__class__({}, *self.maps)\n\n        @property\n        def parents(self):                          # like Django's Context.pop()\n            'New ChainMap from maps[1:].'\n            return self.__class__(*self.maps[1:])\n\n        def __setitem__(self, key, value):\n            self.maps[0][key] = value\n\n        def __delitem__(self, key):\n            try:\n                del self.maps[0][key]\n            except KeyError:\n                raise KeyError('Key not found in the first mapping: {!r}'.format(key))\n\n        def popitem(self):\n            'Remove and return an item pair from maps[0]. Raise KeyError is maps[0] is empty.'\n            try:\n                return self.maps[0].popitem()\n            except KeyError:\n                raise KeyError('No keys found in the first mapping.')\n\n        def pop(self, key, *args):\n            'Remove *key* from maps[0] and return its value. Raise KeyError if *key* not in maps[0].'\n            try:\n                return self.maps[0].pop(key, *args)\n            except KeyError:\n                raise KeyError('Key not found in the first mapping: {!r}'.format(key))\n\n        def clear(self):\n            'Clear maps[0], leaving maps[1:] intact.'\n            self.maps[0].clear()\n\ntry:\n    from importlib.util import cache_from_source  # Python >= 3.4\nexcept ImportError:  # pragma: no cover\n    def cache_from_source(path, debug_override=None):\n        assert path.endswith('.py')\n        if debug_override is None:\n            debug_override = __debug__\n        if debug_override:\n            suffix = 'c'\n        else:\n            suffix = 'o'\n        return path + suffix\n\ntry:\n    from collections import OrderedDict\nexcept ImportError: # pragma: no cover\n## {{{ http://code.activestate.com/recipes/576693/ (r9)\n# Backport of OrderedDict() class that runs on Python 2.4, 2.5, 2.6, 2.7 and pypy.\n# Passes Python2.7's test suite and incorporates all the latest updates.\n    try:\n        from thread import get_ident as _get_ident\n    except ImportError:\n        from dummy_thread import get_ident as _get_ident\n\n    try:\n        from _abcoll import KeysView, ValuesView, ItemsView\n    except ImportError:\n        pass\n\n\n    class OrderedDict(dict):\n        'Dictionary that remembers insertion order'\n        # An inherited dict maps keys to values.\n        # The inherited dict provides __getitem__, __len__, __contains__, and get.\n        # The remaining methods are order-aware.\n        # Big-O running times for all methods are the same as for regular dictionaries.\n\n        # The internal self.__map dictionary maps keys to links in a doubly linked list.\n        # The circular doubly linked list starts and ends with a sentinel element.\n        # The sentinel element never gets deleted (this simplifies the algorithm).\n        # Each link is stored as a list of length three:  [PREV, NEXT, KEY].\n\n        def __init__(self, *args, **kwds):\n            '''Initialize an ordered dictionary.  Signature is the same as for\n            regular dictionaries, but keyword arguments are not recommended\n            because their insertion order is arbitrary.\n\n            '''\n            if len(args) > 1:\n                raise TypeError('expected at most 1 arguments, got %d' % len(args))\n            try:\n                self.__root\n            except AttributeError:\n                self.__root = root = []                     # sentinel node\n                root[:] = [root, root, None]\n                self.__map = {}\n            self.__update(*args, **kwds)\n\n        def __setitem__(self, key, value, dict_setitem=dict.__setitem__):\n            'od.__setitem__(i, y) <==> od[i]=y'\n            # Setting a new item creates a new link which goes at the end of the linked\n            # list, and the inherited dictionary is updated with the new key/value pair.\n            if key not in self:\n                root = self.__root\n                last = root[0]\n                last[1] = root[0] = self.__map[key] = [last, root, key]\n            dict_setitem(self, key, value)\n\n        def __delitem__(self, key, dict_delitem=dict.__delitem__):\n            'od.__delitem__(y) <==> del od[y]'\n            # Deleting an existing item uses self.__map to find the link which is\n            # then removed by updating the links in the predecessor and successor nodes.\n            dict_delitem(self, key)\n            link_prev, link_next, key = self.__map.pop(key)\n            link_prev[1] = link_next\n            link_next[0] = link_prev\n\n        def __iter__(self):\n            'od.__iter__() <==> iter(od)'\n            root = self.__root\n            curr = root[1]\n            while curr is not root:\n                yield curr[2]\n                curr = curr[1]\n\n        def __reversed__(self):\n            'od.__reversed__() <==> reversed(od)'\n            root = self.__root\n            curr = root[0]\n            while curr is not root:\n                yield curr[2]\n                curr = curr[0]\n\n        def clear(self):\n            'od.clear() -> None.  Remove all items from od.'\n            try:\n                for node in self.__map.itervalues():\n                    del node[:]\n                root = self.__root\n                root[:] = [root, root, None]\n                self.__map.clear()\n            except AttributeError:\n                pass\n            dict.clear(self)\n\n        def popitem(self, last=True):\n            '''od.popitem() -> (k, v), return and remove a (key, value) pair.\n            Pairs are returned in LIFO order if last is true or FIFO order if false.\n\n            '''\n            if not self:\n                raise KeyError('dictionary is empty')\n            root = self.__root\n            if last:\n                link = root[0]\n                link_prev = link[0]\n                link_prev[1] = root\n                root[0] = link_prev\n            else:\n                link = root[1]\n                link_next = link[1]\n                root[1] = link_next\n                link_next[0] = root\n            key = link[2]\n            del self.__map[key]\n            value = dict.pop(self, key)\n            return key, value\n\n        # -- the following methods do not depend on the internal structure --\n\n        def keys(self):\n            'od.keys() -> list of keys in od'\n            return list(self)\n\n        def values(self):\n            'od.values() -> list of values in od'\n            return [self[key] for key in self]\n\n        def items(self):\n            'od.items() -> list of (key, value) pairs in od'\n            return [(key, self[key]) for key in self]\n\n        def iterkeys(self):\n            'od.iterkeys() -> an iterator over the keys in od'\n            return iter(self)\n\n        def itervalues(self):\n            'od.itervalues -> an iterator over the values in od'\n            for k in self:\n                yield self[k]\n\n        def iteritems(self):\n            'od.iteritems -> an iterator over the (key, value) items in od'\n            for k in self:\n                yield (k, self[k])\n\n        def update(*args, **kwds):\n            '''od.update(E, **F) -> None.  Update od from dict/iterable E and F.\n\n            If E is a dict instance, does:           for k in E: od[k] = E[k]\n            If E has a .keys() method, does:         for k in E.keys(): od[k] = E[k]\n            Or if E is an iterable of items, does:   for k, v in E: od[k] = v\n            In either case, this is followed by:     for k, v in F.items(): od[k] = v\n\n            '''\n            if len(args) > 2:\n                raise TypeError('update() takes at most 2 positional '\n                                'arguments (%d given)' % (len(args),))\n            elif not args:\n                raise TypeError('update() takes at least 1 argument (0 given)')\n            self = args[0]\n            # Make progressively weaker assumptions about \"other\"\n            other = ()\n            if len(args) == 2:\n                other = args[1]\n            if isinstance(other, dict):\n                for key in other:\n                    self[key] = other[key]\n            elif hasattr(other, 'keys'):\n                for key in other.keys():\n                    self[key] = other[key]\n            else:\n                for key, value in other:\n                    self[key] = value\n            for key, value in kwds.items():\n                self[key] = value\n\n        __update = update  # let subclasses override update without breaking __init__\n\n        __marker = object()\n\n        def pop(self, key, default=__marker):\n            '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n            If key is not found, d is returned if given, otherwise KeyError is raised.\n\n            '''\n            if key in self:\n                result = self[key]\n                del self[key]\n                return result\n            if default is self.__marker:\n                raise KeyError(key)\n            return default\n\n        def setdefault(self, key, default=None):\n            'od.setdefault(k[,d]) -> od.get(k,d), also set od[k]=d if k not in od'\n            if key in self:\n                return self[key]\n            self[key] = default\n            return default\n\n        def __repr__(self, _repr_running=None):\n            'od.__repr__() <==> repr(od)'\n            if not _repr_running: _repr_running = {}\n            call_key = id(self), _get_ident()\n            if call_key in _repr_running:\n                return '...'\n            _repr_running[call_key] = 1\n            try:\n                if not self:\n                    return '%s()' % (self.__class__.__name__,)\n                return '%s(%r)' % (self.__class__.__name__, self.items())\n            finally:\n                del _repr_running[call_key]\n\n        def __reduce__(self):\n            'Return state information for pickling'\n            items = [[k, self[k]] for k in self]\n            inst_dict = vars(self).copy()\n            for k in vars(OrderedDict()):\n                inst_dict.pop(k, None)\n            if inst_dict:\n                return (self.__class__, (items,), inst_dict)\n            return self.__class__, (items,)\n\n        def copy(self):\n            'od.copy() -> a shallow copy of od'\n            return self.__class__(self)\n\n        @classmethod\n        def fromkeys(cls, iterable, value=None):\n            '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S\n            and values equal to v (which defaults to None).\n\n            '''\n            d = cls()\n            for key in iterable:\n                d[key] = value\n            return d\n\n        def __eq__(self, other):\n            '''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive\n            while comparison to a regular mapping is order-insensitive.\n\n            '''\n            if isinstance(other, OrderedDict):\n                return len(self)==len(other) and self.items() == other.items()\n            return dict.__eq__(self, other)\n\n        def __ne__(self, other):\n            return not self == other\n\n        # -- the following methods are only used in Python 2.7 --\n\n        def viewkeys(self):\n            \"od.viewkeys() -> a set-like object providing a view on od's keys\"\n            return KeysView(self)\n\n        def viewvalues(self):\n            \"od.viewvalues() -> an object providing a view on od's values\"\n            return ValuesView(self)\n\n        def viewitems(self):\n            \"od.viewitems() -> a set-like object providing a view on od's items\"\n            return ItemsView(self)\n\ntry:\n    from logging.config import BaseConfigurator, valid_ident\nexcept ImportError: # pragma: no cover\n    IDENTIFIER = re.compile('^[a-z_][a-z0-9_]*$', re.I)\n\n\n    def valid_ident(s):\n        m = IDENTIFIER.match(s)\n        if not m:\n            raise ValueError('Not a valid Python identifier: %r' % s)\n        return True\n\n\n    # The ConvertingXXX classes are wrappers around standard Python containers,\n    # and they serve to convert any suitable values in the container. The\n    # conversion converts base dicts, lists and tuples to their wrapped\n    # equivalents, whereas strings which match a conversion format are converted\n    # appropriately.\n    #\n    # Each wrapper should have a configurator attribute holding the actual\n    # configurator to use for conversion.\n\n    class ConvertingDict(dict):\n        \"\"\"A converting dictionary wrapper.\"\"\"\n\n        def __getitem__(self, key):\n            value = dict.__getitem__(self, key)\n            result = self.configurator.convert(value)\n            #If the converted value is different, save for next time\n            if value is not result:\n                self[key] = result\n                if type(result) in (ConvertingDict, ConvertingList,\n                                    ConvertingTuple):\n                    result.parent = self\n                    result.key = key\n            return result\n\n        def get(self, key, default=None):\n            value = dict.get(self, key, default)\n            result = self.configurator.convert(value)\n            #If the converted value is different, save for next time\n            if value is not result:\n                self[key] = result\n                if type(result) in (ConvertingDict, ConvertingList,\n                                    ConvertingTuple):\n                    result.parent = self\n                    result.key = key\n            return result\n\n    def pop(self, key, default=None):\n        value = dict.pop(self, key, default)\n        result = self.configurator.convert(value)\n        if value is not result:\n            if type(result) in (ConvertingDict, ConvertingList,\n                                ConvertingTuple):\n                result.parent = self\n                result.key = key\n        return result\n\n    class ConvertingList(list):\n        \"\"\"A converting list wrapper.\"\"\"\n        def __getitem__(self, key):\n            value = list.__getitem__(self, key)\n            result = self.configurator.convert(value)\n            #If the converted value is different, save for next time\n            if value is not result:\n                self[key] = result\n                if type(result) in (ConvertingDict, ConvertingList,\n                                    ConvertingTuple):\n                    result.parent = self\n                    result.key = key\n            return result\n\n        def pop(self, idx=-1):\n            value = list.pop(self, idx)\n            result = self.configurator.convert(value)\n            if value is not result:\n                if type(result) in (ConvertingDict, ConvertingList,\n                                    ConvertingTuple):\n                    result.parent = self\n            return result\n\n    class ConvertingTuple(tuple):\n        \"\"\"A converting tuple wrapper.\"\"\"\n        def __getitem__(self, key):\n            value = tuple.__getitem__(self, key)\n            result = self.configurator.convert(value)\n            if value is not result:\n                if type(result) in (ConvertingDict, ConvertingList,\n                                    ConvertingTuple):\n                    result.parent = self\n                    result.key = key\n            return result\n\n    class BaseConfigurator(object):\n        \"\"\"\n        The configurator base class which defines some useful defaults.\n        \"\"\"\n\n        CONVERT_PATTERN = re.compile(r'^(?P<prefix>[a-z]+)://(?P<suffix>.*)$')\n\n        WORD_PATTERN = re.compile(r'^\\s*(\\w+)\\s*')\n        DOT_PATTERN = re.compile(r'^\\.\\s*(\\w+)\\s*')\n        INDEX_PATTERN = re.compile(r'^\\[\\s*(\\w+)\\s*\\]\\s*')\n        DIGIT_PATTERN = re.compile(r'^\\d+$')\n\n        value_converters = {\n            'ext' : 'ext_convert',\n            'cfg' : 'cfg_convert',\n        }\n\n        # We might want to use a different one, e.g. importlib\n        importer = staticmethod(__import__)\n\n        def __init__(self, config):\n            self.config = ConvertingDict(config)\n            self.config.configurator = self\n\n        def resolve(self, s):\n            \"\"\"\n            Resolve strings to objects using standard import and attribute\n            syntax.\n            \"\"\"\n            name = s.split('.')\n            used = name.pop(0)\n            try:\n                found = self.importer(used)\n                for frag in name:\n                    used += '.' + frag\n                    try:\n                        found = getattr(found, frag)\n                    except AttributeError:\n                        self.importer(used)\n                        found = getattr(found, frag)\n                return found\n            except ImportError:\n                e, tb = sys.exc_info()[1:]\n                v = ValueError('Cannot resolve %r: %s' % (s, e))\n                v.__cause__, v.__traceback__ = e, tb\n                raise v\n\n        def ext_convert(self, value):\n            \"\"\"Default converter for the ext:// protocol.\"\"\"\n            return self.resolve(value)\n\n        def cfg_convert(self, value):\n            \"\"\"Default converter for the cfg:// protocol.\"\"\"\n            rest = value\n            m = self.WORD_PATTERN.match(rest)\n            if m is None:\n                raise ValueError(\"Unable to convert %r\" % value)\n            else:\n                rest = rest[m.end():]\n                d = self.config[m.groups()[0]]\n                #print d, rest\n                while rest:\n                    m = self.DOT_PATTERN.match(rest)\n                    if m:\n                        d = d[m.groups()[0]]\n                    else:\n                        m = self.INDEX_PATTERN.match(rest)\n                        if m:\n                            idx = m.groups()[0]\n                            if not self.DIGIT_PATTERN.match(idx):\n                                d = d[idx]\n                            else:\n                                try:\n                                    n = int(idx) # try as number first (most likely)\n                                    d = d[n]\n                                except TypeError:\n                                    d = d[idx]\n                    if m:\n                        rest = rest[m.end():]\n                    else:\n                        raise ValueError('Unable to convert '\n                                         '%r at %r' % (value, rest))\n            #rest should be empty\n            return d\n\n        def convert(self, value):\n            \"\"\"\n            Convert values to an appropriate type. dicts, lists and tuples are\n            replaced by their converting alternatives. Strings are checked to\n            see if they have a conversion format and are converted if they do.\n            \"\"\"\n            if not isinstance(value, ConvertingDict) and isinstance(value, dict):\n                value = ConvertingDict(value)\n                value.configurator = self\n            elif not isinstance(value, ConvertingList) and isinstance(value, list):\n                value = ConvertingList(value)\n                value.configurator = self\n            elif not isinstance(value, ConvertingTuple) and\\\n                     isinstance(value, tuple):\n                value = ConvertingTuple(value)\n                value.configurator = self\n            elif isinstance(value, string_types):\n                m = self.CONVERT_PATTERN.match(value)\n                if m:\n                    d = m.groupdict()\n                    prefix = d['prefix']\n                    converter = self.value_converters.get(prefix, None)\n                    if converter:\n                        suffix = d['suffix']\n                        converter = getattr(self, converter)\n                        value = converter(suffix)\n            return value\n\n        def configure_custom(self, config):\n            \"\"\"Configure an object with a user-supplied factory.\"\"\"\n            c = config.pop('()')\n            if not callable(c):\n                c = self.resolve(c)\n            props = config.pop('.', None)\n            # Check for valid identifiers\n            kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])\n            result = c(**kwargs)\n            if props:\n                for name, value in props.items():\n                    setattr(result, name, value)\n            return result\n\n        def as_tuple(self, value):\n            \"\"\"Utility function which converts lists to tuples.\"\"\"\n            if isinstance(value, list):\n                value = tuple(value)\n            return value\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distlib/database.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2012-2017 The Python Software Foundation.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\n\"\"\"PEP 376 implementation.\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport base64\nimport codecs\nimport contextlib\nimport hashlib\nimport logging\nimport os\nimport posixpath\nimport sys\nimport zipimport\n\nfrom . import DistlibException, resources\nfrom .compat import StringIO\nfrom .version import get_scheme, UnsupportedVersionError\nfrom .metadata import (Metadata, METADATA_FILENAME, WHEEL_METADATA_FILENAME,\n                       LEGACY_METADATA_FILENAME)\nfrom .util import (parse_requirement, cached_property, parse_name_and_version,\n                   read_exports, write_exports, CSVReader, CSVWriter)\n\n\n__all__ = ['Distribution', 'BaseInstalledDistribution',\n           'InstalledDistribution', 'EggInfoDistribution',\n           'DistributionPath']\n\n\nlogger = logging.getLogger(__name__)\n\nEXPORTS_FILENAME = 'pydist-exports.json'\nCOMMANDS_FILENAME = 'pydist-commands.json'\n\nDIST_FILES = ('INSTALLER', METADATA_FILENAME, 'RECORD', 'REQUESTED',\n              'RESOURCES', EXPORTS_FILENAME, 'SHARED')\n\nDISTINFO_EXT = '.dist-info'\n\n\nclass _Cache(object):\n    \"\"\"\n    A simple cache mapping names and .dist-info paths to distributions\n    \"\"\"\n    def __init__(self):\n        \"\"\"\n        Initialise an instance. There is normally one for each DistributionPath.\n        \"\"\"\n        self.name = {}\n        self.path = {}\n        self.generated = False\n\n    def clear(self):\n        \"\"\"\n        Clear the cache, setting it to its initial state.\n        \"\"\"\n        self.name.clear()\n        self.path.clear()\n        self.generated = False\n\n    def add(self, dist):\n        \"\"\"\n        Add a distribution to the cache.\n        :param dist: The distribution to add.\n        \"\"\"\n        if dist.path not in self.path:\n            self.path[dist.path] = dist\n            self.name.setdefault(dist.key, []).append(dist)\n\n\nclass DistributionPath(object):\n    \"\"\"\n    Represents a set of distributions installed on a path (typically sys.path).\n    \"\"\"\n    def __init__(self, path=None, include_egg=False):\n        \"\"\"\n        Create an instance from a path, optionally including legacy (distutils/\n        setuptools/distribute) distributions.\n        :param path: The path to use, as a list of directories. If not specified,\n                     sys.path is used.\n        :param include_egg: If True, this instance will look for and return legacy\n                            distributions as well as those based on PEP 376.\n        \"\"\"\n        if path is None:\n            path = sys.path\n        self.path = path\n        self._include_dist = True\n        self._include_egg = include_egg\n\n        self._cache = _Cache()\n        self._cache_egg = _Cache()\n        self._cache_enabled = True\n        self._scheme = get_scheme('default')\n\n    def _get_cache_enabled(self):\n        return self._cache_enabled\n\n    def _set_cache_enabled(self, value):\n        self._cache_enabled = value\n\n    cache_enabled = property(_get_cache_enabled, _set_cache_enabled)\n\n    def clear_cache(self):\n        \"\"\"\n        Clears the internal cache.\n        \"\"\"\n        self._cache.clear()\n        self._cache_egg.clear()\n\n\n    def _yield_distributions(self):\n        \"\"\"\n        Yield .dist-info and/or .egg(-info) distributions.\n        \"\"\"\n        # We need to check if we've seen some resources already, because on\n        # some Linux systems (e.g. some Debian/Ubuntu variants) there are\n        # symlinks which alias other files in the environment.\n        seen = set()\n        for path in self.path:\n            finder = resources.finder_for_path(path)\n            if finder is None:\n                continue\n            r = finder.find('')\n            if not r or not r.is_container:\n                continue\n            rset = sorted(r.resources)\n            for entry in rset:\n                r = finder.find(entry)\n                if not r or r.path in seen:\n                    continue\n                try:\n                    if self._include_dist and entry.endswith(DISTINFO_EXT):\n                        possible_filenames = [METADATA_FILENAME,\n                                              WHEEL_METADATA_FILENAME,\n                                              LEGACY_METADATA_FILENAME]\n                        for metadata_filename in possible_filenames:\n                            metadata_path = posixpath.join(entry, metadata_filename)\n                            pydist = finder.find(metadata_path)\n                            if pydist:\n                                break\n                        else:\n                            continue\n\n                        with contextlib.closing(pydist.as_stream()) as stream:\n                            metadata = Metadata(fileobj=stream, scheme='legacy')\n                        logger.debug('Found %s', r.path)\n                        seen.add(r.path)\n                        yield new_dist_class(r.path, metadata=metadata,\n                                             env=self)\n                    elif self._include_egg and entry.endswith(('.egg-info',\n                                                              '.egg')):\n                        logger.debug('Found %s', r.path)\n                        seen.add(r.path)\n                        yield old_dist_class(r.path, self)\n                except Exception as e:\n                    msg = 'Unable to read distribution at %s, perhaps due to bad metadata: %s'\n                    logger.warning(msg, r.path, e)\n                    import warnings\n                    warnings.warn(msg % (r.path, e), stacklevel=2)\n\n    def _generate_cache(self):\n        \"\"\"\n        Scan the path for distributions and populate the cache with\n        those that are found.\n        \"\"\"\n        gen_dist = not self._cache.generated\n        gen_egg = self._include_egg and not self._cache_egg.generated\n        if gen_dist or gen_egg:\n            for dist in self._yield_distributions():\n                if isinstance(dist, InstalledDistribution):\n                    self._cache.add(dist)\n                else:\n                    self._cache_egg.add(dist)\n\n            if gen_dist:\n                self._cache.generated = True\n            if gen_egg:\n                self._cache_egg.generated = True\n\n    @classmethod\n    def distinfo_dirname(cls, name, version):\n        \"\"\"\n        The *name* and *version* parameters are converted into their\n        filename-escaped form, i.e. any ``'-'`` characters are replaced\n        with ``'_'`` other than the one in ``'dist-info'`` and the one\n        separating the name from the version number.\n\n        :parameter name: is converted to a standard distribution name by replacing\n                         any runs of non- alphanumeric characters with a single\n                         ``'-'``.\n        :type name: string\n        :parameter version: is converted to a standard version string. Spaces\n                            become dots, and all other non-alphanumeric characters\n                            (except dots) become dashes, with runs of multiple\n                            dashes condensed to a single dash.\n        :type version: string\n        :returns: directory name\n        :rtype: string\"\"\"\n        name = name.replace('-', '_')\n        return '-'.join([name, version]) + DISTINFO_EXT\n\n    def get_distributions(self):\n        \"\"\"\n        Provides an iterator that looks for distributions and returns\n        :class:`InstalledDistribution` or\n        :class:`EggInfoDistribution` instances for each one of them.\n\n        :rtype: iterator of :class:`InstalledDistribution` and\n                :class:`EggInfoDistribution` instances\n        \"\"\"\n        if not self._cache_enabled:\n            for dist in self._yield_distributions():\n                yield dist\n        else:\n            self._generate_cache()\n\n            for dist in self._cache.path.values():\n                yield dist\n\n            if self._include_egg:\n                for dist in self._cache_egg.path.values():\n                    yield dist\n\n    def get_distribution(self, name):\n        \"\"\"\n        Looks for a named distribution on the path.\n\n        This function only returns the first result found, as no more than one\n        value is expected. If nothing is found, ``None`` is returned.\n\n        :rtype: :class:`InstalledDistribution`, :class:`EggInfoDistribution`\n                or ``None``\n        \"\"\"\n        result = None\n        name = name.lower()\n        if not self._cache_enabled:\n            for dist in self._yield_distributions():\n                if dist.key == name:\n                    result = dist\n                    break\n        else:\n            self._generate_cache()\n\n            if name in self._cache.name:\n                result = self._cache.name[name][0]\n            elif self._include_egg and name in self._cache_egg.name:\n                result = self._cache_egg.name[name][0]\n        return result\n\n    def provides_distribution(self, name, version=None):\n        \"\"\"\n        Iterates over all distributions to find which distributions provide *name*.\n        If a *version* is provided, it will be used to filter the results.\n\n        This function only returns the first result found, since no more than\n        one values are expected. If the directory is not found, returns ``None``.\n\n        :parameter version: a version specifier that indicates the version\n                            required, conforming to the format in ``PEP-345``\n\n        :type name: string\n        :type version: string\n        \"\"\"\n        matcher = None\n        if version is not None:\n            try:\n                matcher = self._scheme.matcher('%s (%s)' % (name, version))\n            except ValueError:\n                raise DistlibException('invalid name or version: %r, %r' %\n                                      (name, version))\n\n        for dist in self.get_distributions():\n            # We hit a problem on Travis where enum34 was installed and doesn't\n            # have a provides attribute ...\n            if not hasattr(dist, 'provides'):\n                logger.debug('No \"provides\": %s', dist)\n            else:\n                provided = dist.provides\n\n                for p in provided:\n                    p_name, p_ver = parse_name_and_version(p)\n                    if matcher is None:\n                        if p_name == name:\n                            yield dist\n                            break\n                    else:\n                        if p_name == name and matcher.match(p_ver):\n                            yield dist\n                            break\n\n    def get_file_path(self, name, relative_path):\n        \"\"\"\n        Return the path to a resource file.\n        \"\"\"\n        dist = self.get_distribution(name)\n        if dist is None:\n            raise LookupError('no distribution named %r found' % name)\n        return dist.get_resource_path(relative_path)\n\n    def get_exported_entries(self, category, name=None):\n        \"\"\"\n        Return all of the exported entries in a particular category.\n\n        :param category: The category to search for entries.\n        :param name: If specified, only entries with that name are returned.\n        \"\"\"\n        for dist in self.get_distributions():\n            r = dist.exports\n            if category in r:\n                d = r[category]\n                if name is not None:\n                    if name in d:\n                        yield d[name]\n                else:\n                    for v in d.values():\n                        yield v\n\n\nclass Distribution(object):\n    \"\"\"\n    A base class for distributions, whether installed or from indexes.\n    Either way, it must have some metadata, so that's all that's needed\n    for construction.\n    \"\"\"\n\n    build_time_dependency = False\n    \"\"\"\n    Set to True if it's known to be only a build-time dependency (i.e.\n    not needed after installation).\n    \"\"\"\n\n    requested = False\n    \"\"\"A boolean that indicates whether the ``REQUESTED`` metadata file is\n    present (in other words, whether the package was installed by user\n    request or it was installed as a dependency).\"\"\"\n\n    def __init__(self, metadata):\n        \"\"\"\n        Initialise an instance.\n        :param metadata: The instance of :class:`Metadata` describing this\n        distribution.\n        \"\"\"\n        self.metadata = metadata\n        self.name = metadata.name\n        self.key = self.name.lower()    # for case-insensitive comparisons\n        self.version = metadata.version\n        self.locator = None\n        self.digest = None\n        self.extras = None      # additional features requested\n        self.context = None     # environment marker overrides\n        self.download_urls = set()\n        self.digests = {}\n\n    @property\n    def source_url(self):\n        \"\"\"\n        The source archive download URL for this distribution.\n        \"\"\"\n        return self.metadata.source_url\n\n    download_url = source_url   # Backward compatibility\n\n    @property\n    def name_and_version(self):\n        \"\"\"\n        A utility property which displays the name and version in parentheses.\n        \"\"\"\n        return '%s (%s)' % (self.name, self.version)\n\n    @property\n    def provides(self):\n        \"\"\"\n        A set of distribution names and versions provided by this distribution.\n        :return: A set of \"name (version)\" strings.\n        \"\"\"\n        plist = self.metadata.provides\n        s = '%s (%s)' % (self.name, self.version)\n        if s not in plist:\n            plist.append(s)\n        return plist\n\n    def _get_requirements(self, req_attr):\n        md = self.metadata\n        reqts = getattr(md, req_attr)\n        logger.debug('%s: got requirements %r from metadata: %r', self.name, req_attr,\n                     reqts)\n        return set(md.get_requirements(reqts, extras=self.extras,\n                                       env=self.context))\n\n    @property\n    def run_requires(self):\n        return self._get_requirements('run_requires')\n\n    @property\n    def meta_requires(self):\n        return self._get_requirements('meta_requires')\n\n    @property\n    def build_requires(self):\n        return self._get_requirements('build_requires')\n\n    @property\n    def test_requires(self):\n        return self._get_requirements('test_requires')\n\n    @property\n    def dev_requires(self):\n        return self._get_requirements('dev_requires')\n\n    def matches_requirement(self, req):\n        \"\"\"\n        Say if this instance matches (fulfills) a requirement.\n        :param req: The requirement to match.\n        :rtype req: str\n        :return: True if it matches, else False.\n        \"\"\"\n        # Requirement may contain extras - parse to lose those\n        # from what's passed to the matcher\n        r = parse_requirement(req)\n        scheme = get_scheme(self.metadata.scheme)\n        try:\n            matcher = scheme.matcher(r.requirement)\n        except UnsupportedVersionError:\n            # XXX compat-mode if cannot read the version\n            logger.warning('could not read version %r - using name only',\n                           req)\n            name = req.split()[0]\n            matcher = scheme.matcher(name)\n\n        name = matcher.key   # case-insensitive\n\n        result = False\n        for p in self.provides:\n            p_name, p_ver = parse_name_and_version(p)\n            if p_name != name:\n                continue\n            try:\n                result = matcher.match(p_ver)\n                break\n            except UnsupportedVersionError:\n                pass\n        return result\n\n    def __repr__(self):\n        \"\"\"\n        Return a textual representation of this instance,\n        \"\"\"\n        if self.source_url:\n            suffix = ' [%s]' % self.source_url\n        else:\n            suffix = ''\n        return '<Distribution %s (%s)%s>' % (self.name, self.version, suffix)\n\n    def __eq__(self, other):\n        \"\"\"\n        See if this distribution is the same as another.\n        :param other: The distribution to compare with. To be equal to one\n                      another. distributions must have the same type, name,\n                      version and source_url.\n        :return: True if it is the same, else False.\n        \"\"\"\n        if type(other) is not type(self):\n            result = False\n        else:\n            result = (self.name == other.name and\n                      self.version == other.version and\n                      self.source_url == other.source_url)\n        return result\n\n    def __hash__(self):\n        \"\"\"\n        Compute hash in a way which matches the equality test.\n        \"\"\"\n        return hash(self.name) + hash(self.version) + hash(self.source_url)\n\n\nclass BaseInstalledDistribution(Distribution):\n    \"\"\"\n    This is the base class for installed distributions (whether PEP 376 or\n    legacy).\n    \"\"\"\n\n    hasher = None\n\n    def __init__(self, metadata, path, env=None):\n        \"\"\"\n        Initialise an instance.\n        :param metadata: An instance of :class:`Metadata` which describes the\n                         distribution. This will normally have been initialised\n                         from a metadata file in the ``path``.\n        :param path:     The path of the ``.dist-info`` or ``.egg-info``\n                         directory for the distribution.\n        :param env:      This is normally the :class:`DistributionPath`\n                         instance where this distribution was found.\n        \"\"\"\n        super(BaseInstalledDistribution, self).__init__(metadata)\n        self.path = path\n        self.dist_path = env\n\n    def get_hash(self, data, hasher=None):\n        \"\"\"\n        Get the hash of some data, using a particular hash algorithm, if\n        specified.\n\n        :param data: The data to be hashed.\n        :type data: bytes\n        :param hasher: The name of a hash implementation, supported by hashlib,\n                       or ``None``. Examples of valid values are ``'sha1'``,\n                       ``'sha224'``, ``'sha384'``, '``sha256'``, ``'md5'`` and\n                       ``'sha512'``. If no hasher is specified, the ``hasher``\n                       attribute of the :class:`InstalledDistribution` instance\n                       is used. If the hasher is determined to be ``None``, MD5\n                       is used as the hashing algorithm.\n        :returns: The hash of the data. If a hasher was explicitly specified,\n                  the returned hash will be prefixed with the specified hasher\n                  followed by '='.\n        :rtype: str\n        \"\"\"\n        if hasher is None:\n            hasher = self.hasher\n        if hasher is None:\n            hasher = hashlib.md5\n            prefix = ''\n        else:\n            hasher = getattr(hashlib, hasher)\n            prefix = '%s=' % self.hasher\n        digest = hasher(data).digest()\n        digest = base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')\n        return '%s%s' % (prefix, digest)\n\n\nclass InstalledDistribution(BaseInstalledDistribution):\n    \"\"\"\n    Created with the *path* of the ``.dist-info`` directory provided to the\n    constructor. It reads the metadata contained in ``pydist.json`` when it is\n    instantiated., or uses a passed in Metadata instance (useful for when\n    dry-run mode is being used).\n    \"\"\"\n\n    hasher = 'sha256'\n\n    def __init__(self, path, metadata=None, env=None):\n        self.modules = []\n        self.finder = finder = resources.finder_for_path(path)\n        if finder is None:\n            raise ValueError('finder unavailable for %s' % path)\n        if env and env._cache_enabled and path in env._cache.path:\n            metadata = env._cache.path[path].metadata\n        elif metadata is None:\n            r = finder.find(METADATA_FILENAME)\n            # Temporary - for Wheel 0.23 support\n            if r is None:\n                r = finder.find(WHEEL_METADATA_FILENAME)\n            # Temporary - for legacy support\n            if r is None:\n                r = finder.find(LEGACY_METADATA_FILENAME)\n            if r is None:\n                raise ValueError('no %s found in %s' % (METADATA_FILENAME,\n                                                        path))\n            with contextlib.closing(r.as_stream()) as stream:\n                metadata = Metadata(fileobj=stream, scheme='legacy')\n\n        super(InstalledDistribution, self).__init__(metadata, path, env)\n\n        if env and env._cache_enabled:\n            env._cache.add(self)\n\n        r = finder.find('REQUESTED')\n        self.requested = r is not None\n        p  = os.path.join(path, 'top_level.txt')\n        if os.path.exists(p):\n            with open(p, 'rb') as f:\n                data = f.read().decode('utf-8')\n            self.modules = data.splitlines()\n\n    def __repr__(self):\n        return '<InstalledDistribution %r %s at %r>' % (\n            self.name, self.version, self.path)\n\n    def __str__(self):\n        return \"%s %s\" % (self.name, self.version)\n\n    def _get_records(self):\n        \"\"\"\n        Get the list of installed files for the distribution\n        :return: A list of tuples of path, hash and size. Note that hash and\n                 size might be ``None`` for some entries. The path is exactly\n                 as stored in the file (which is as in PEP 376).\n        \"\"\"\n        results = []\n        r = self.get_distinfo_resource('RECORD')\n        with contextlib.closing(r.as_stream()) as stream:\n            with CSVReader(stream=stream) as record_reader:\n                # Base location is parent dir of .dist-info dir\n                #base_location = os.path.dirname(self.path)\n                #base_location = os.path.abspath(base_location)\n                for row in record_reader:\n                    missing = [None for i in range(len(row), 3)]\n                    path, checksum, size = row + missing\n                    #if not os.path.isabs(path):\n                    #    path = path.replace('/', os.sep)\n                    #    path = os.path.join(base_location, path)\n                    results.append((path, checksum, size))\n        return results\n\n    @cached_property\n    def exports(self):\n        \"\"\"\n        Return the information exported by this distribution.\n        :return: A dictionary of exports, mapping an export category to a dict\n                 of :class:`ExportEntry` instances describing the individual\n                 export entries, and keyed by name.\n        \"\"\"\n        result = {}\n        r = self.get_distinfo_resource(EXPORTS_FILENAME)\n        if r:\n            result = self.read_exports()\n        return result\n\n    def read_exports(self):\n        \"\"\"\n        Read exports data from a file in .ini format.\n\n        :return: A dictionary of exports, mapping an export category to a list\n                 of :class:`ExportEntry` instances describing the individual\n                 export entries.\n        \"\"\"\n        result = {}\n        r = self.get_distinfo_resource(EXPORTS_FILENAME)\n        if r:\n            with contextlib.closing(r.as_stream()) as stream:\n                result = read_exports(stream)\n        return result\n\n    def write_exports(self, exports):\n        \"\"\"\n        Write a dictionary of exports to a file in .ini format.\n        :param exports: A dictionary of exports, mapping an export category to\n                        a list of :class:`ExportEntry` instances describing the\n                        individual export entries.\n        \"\"\"\n        rf = self.get_distinfo_file(EXPORTS_FILENAME)\n        with open(rf, 'w') as f:\n            write_exports(exports, f)\n\n    def get_resource_path(self, relative_path):\n        \"\"\"\n        NOTE: This API may change in the future.\n\n        Return the absolute path to a resource file with the given relative\n        path.\n\n        :param relative_path: The path, relative to .dist-info, of the resource\n                              of interest.\n        :return: The absolute path where the resource is to be found.\n        \"\"\"\n        r = self.get_distinfo_resource('RESOURCES')\n        with contextlib.closing(r.as_stream()) as stream:\n            with CSVReader(stream=stream) as resources_reader:\n                for relative, destination in resources_reader:\n                    if relative == relative_path:\n                        return destination\n        raise KeyError('no resource file with relative path %r '\n                       'is installed' % relative_path)\n\n    def list_installed_files(self):\n        \"\"\"\n        Iterates over the ``RECORD`` entries and returns a tuple\n        ``(path, hash, size)`` for each line.\n\n        :returns: iterator of (path, hash, size)\n        \"\"\"\n        for result in self._get_records():\n            yield result\n\n    def write_installed_files(self, paths, prefix, dry_run=False):\n        \"\"\"\n        Writes the ``RECORD`` file, using the ``paths`` iterable passed in. Any\n        existing ``RECORD`` file is silently overwritten.\n\n        prefix is used to determine when to write absolute paths.\n        \"\"\"\n        prefix = os.path.join(prefix, '')\n        base = os.path.dirname(self.path)\n        base_under_prefix = base.startswith(prefix)\n        base = os.path.join(base, '')\n        record_path = self.get_distinfo_file('RECORD')\n        logger.info('creating %s', record_path)\n        if dry_run:\n            return None\n        with CSVWriter(record_path) as writer:\n            for path in paths:\n                if os.path.isdir(path) or path.endswith(('.pyc', '.pyo')):\n                    # do not put size and hash, as in PEP-376\n                    hash_value = size = ''\n                else:\n                    size = '%d' % os.path.getsize(path)\n                    with open(path, 'rb') as fp:\n                        hash_value = self.get_hash(fp.read())\n                if path.startswith(base) or (base_under_prefix and\n                                             path.startswith(prefix)):\n                    path = os.path.relpath(path, base)\n                writer.writerow((path, hash_value, size))\n\n            # add the RECORD file itself\n            if record_path.startswith(base):\n                record_path = os.path.relpath(record_path, base)\n            writer.writerow((record_path, '', ''))\n        return record_path\n\n    def check_installed_files(self):\n        \"\"\"\n        Checks that the hashes and sizes of the files in ``RECORD`` are\n        matched by the files themselves. Returns a (possibly empty) list of\n        mismatches. Each entry in the mismatch list will be a tuple consisting\n        of the path, 'exists', 'size' or 'hash' according to what didn't match\n        (existence is checked first, then size, then hash), the expected\n        value and the actual value.\n        \"\"\"\n        mismatches = []\n        base = os.path.dirname(self.path)\n        record_path = self.get_distinfo_file('RECORD')\n        for path, hash_value, size in self.list_installed_files():\n            if not os.path.isabs(path):\n                path = os.path.join(base, path)\n            if path == record_path:\n                continue\n            if not os.path.exists(path):\n                mismatches.append((path, 'exists', True, False))\n            elif os.path.isfile(path):\n                actual_size = str(os.path.getsize(path))\n                if size and actual_size != size:\n                    mismatches.append((path, 'size', size, actual_size))\n                elif hash_value:\n                    if '=' in hash_value:\n                        hasher = hash_value.split('=', 1)[0]\n                    else:\n                        hasher = None\n\n                    with open(path, 'rb') as f:\n                        actual_hash = self.get_hash(f.read(), hasher)\n                        if actual_hash != hash_value:\n                            mismatches.append((path, 'hash', hash_value, actual_hash))\n        return mismatches\n\n    @cached_property\n    def shared_locations(self):\n        \"\"\"\n        A dictionary of shared locations whose keys are in the set 'prefix',\n        'purelib', 'platlib', 'scripts', 'headers', 'data' and 'namespace'.\n        The corresponding value is the absolute path of that category for\n        this distribution, and takes into account any paths selected by the\n        user at installation time (e.g. via command-line arguments). In the\n        case of the 'namespace' key, this would be a list of absolute paths\n        for the roots of namespace packages in this distribution.\n\n        The first time this property is accessed, the relevant information is\n        read from the SHARED file in the .dist-info directory.\n        \"\"\"\n        result = {}\n        shared_path = os.path.join(self.path, 'SHARED')\n        if os.path.isfile(shared_path):\n            with codecs.open(shared_path, 'r', encoding='utf-8') as f:\n                lines = f.read().splitlines()\n            for line in lines:\n                key, value = line.split('=', 1)\n                if key == 'namespace':\n                    result.setdefault(key, []).append(value)\n                else:\n                    result[key] = value\n        return result\n\n    def write_shared_locations(self, paths, dry_run=False):\n        \"\"\"\n        Write shared location information to the SHARED file in .dist-info.\n        :param paths: A dictionary as described in the documentation for\n        :meth:`shared_locations`.\n        :param dry_run: If True, the action is logged but no file is actually\n                        written.\n        :return: The path of the file written to.\n        \"\"\"\n        shared_path = os.path.join(self.path, 'SHARED')\n        logger.info('creating %s', shared_path)\n        if dry_run:\n            return None\n        lines = []\n        for key in ('prefix', 'lib', 'headers', 'scripts', 'data'):\n            path = paths[key]\n            if os.path.isdir(paths[key]):\n                lines.append('%s=%s' % (key,  path))\n        for ns in paths.get('namespace', ()):\n            lines.append('namespace=%s' % ns)\n\n        with codecs.open(shared_path, 'w', encoding='utf-8') as f:\n            f.write('\\n'.join(lines))\n        return shared_path\n\n    def get_distinfo_resource(self, path):\n        if path not in DIST_FILES:\n            raise DistlibException('invalid path for a dist-info file: '\n                                   '%r at %r' % (path, self.path))\n        finder = resources.finder_for_path(self.path)\n        if finder is None:\n            raise DistlibException('Unable to get a finder for %s' % self.path)\n        return finder.find(path)\n\n    def get_distinfo_file(self, path):\n        \"\"\"\n        Returns a path located under the ``.dist-info`` directory. Returns a\n        string representing the path.\n\n        :parameter path: a ``'/'``-separated path relative to the\n                         ``.dist-info`` directory or an absolute path;\n                         If *path* is an absolute path and doesn't start\n                         with the ``.dist-info`` directory path,\n                         a :class:`DistlibException` is raised\n        :type path: str\n        :rtype: str\n        \"\"\"\n        # Check if it is an absolute path  # XXX use relpath, add tests\n        if path.find(os.sep) >= 0:\n            # it's an absolute path?\n            distinfo_dirname, path = path.split(os.sep)[-2:]\n            if distinfo_dirname != self.path.split(os.sep)[-1]:\n                raise DistlibException(\n                    'dist-info file %r does not belong to the %r %s '\n                    'distribution' % (path, self.name, self.version))\n\n        # The file must be relative\n        if path not in DIST_FILES:\n            raise DistlibException('invalid path for a dist-info file: '\n                                   '%r at %r' % (path, self.path))\n\n        return os.path.join(self.path, path)\n\n    def list_distinfo_files(self):\n        \"\"\"\n        Iterates over the ``RECORD`` entries and returns paths for each line if\n        the path is pointing to a file located in the ``.dist-info`` directory\n        or one of its subdirectories.\n\n        :returns: iterator of paths\n        \"\"\"\n        base = os.path.dirname(self.path)\n        for path, checksum, size in self._get_records():\n            # XXX add separator or use real relpath algo\n            if not os.path.isabs(path):\n                path = os.path.join(base, path)\n            if path.startswith(self.path):\n                yield path\n\n    def __eq__(self, other):\n        return (isinstance(other, InstalledDistribution) and\n                self.path == other.path)\n\n    # See http://docs.python.org/reference/datamodel#object.__hash__\n    __hash__ = object.__hash__\n\n\nclass EggInfoDistribution(BaseInstalledDistribution):\n    \"\"\"Created with the *path* of the ``.egg-info`` directory or file provided\n    to the constructor. It reads the metadata contained in the file itself, or\n    if the given path happens to be a directory, the metadata is read from the\n    file ``PKG-INFO`` under that directory.\"\"\"\n\n    requested = True    # as we have no way of knowing, assume it was\n    shared_locations = {}\n\n    def __init__(self, path, env=None):\n        def set_name_and_version(s, n, v):\n            s.name = n\n            s.key = n.lower()   # for case-insensitive comparisons\n            s.version = v\n\n        self.path = path\n        self.dist_path = env\n        if env and env._cache_enabled and path in env._cache_egg.path:\n            metadata = env._cache_egg.path[path].metadata\n            set_name_and_version(self, metadata.name, metadata.version)\n        else:\n            metadata = self._get_metadata(path)\n\n            # Need to be set before caching\n            set_name_and_version(self, metadata.name, metadata.version)\n\n            if env and env._cache_enabled:\n                env._cache_egg.add(self)\n        super(EggInfoDistribution, self).__init__(metadata, path, env)\n\n    def _get_metadata(self, path):\n        requires = None\n\n        def parse_requires_data(data):\n            \"\"\"Create a list of dependencies from a requires.txt file.\n\n            *data*: the contents of a setuptools-produced requires.txt file.\n            \"\"\"\n            reqs = []\n            lines = data.splitlines()\n            for line in lines:\n                line = line.strip()\n                if line.startswith('['):\n                    logger.warning('Unexpected line: quitting requirement scan: %r',\n                                   line)\n                    break\n                r = parse_requirement(line)\n                if not r:\n                    logger.warning('Not recognised as a requirement: %r', line)\n                    continue\n                if r.extras:\n                    logger.warning('extra requirements in requires.txt are '\n                                   'not supported')\n                if not r.constraints:\n                    reqs.append(r.name)\n                else:\n                    cons = ', '.join('%s%s' % c for c in r.constraints)\n                    reqs.append('%s (%s)' % (r.name, cons))\n            return reqs\n\n        def parse_requires_path(req_path):\n            \"\"\"Create a list of dependencies from a requires.txt file.\n\n            *req_path*: the path to a setuptools-produced requires.txt file.\n            \"\"\"\n\n            reqs = []\n            try:\n                with codecs.open(req_path, 'r', 'utf-8') as fp:\n                    reqs = parse_requires_data(fp.read())\n            except IOError:\n                pass\n            return reqs\n\n        tl_path = tl_data = None\n        if path.endswith('.egg'):\n            if os.path.isdir(path):\n                p = os.path.join(path, 'EGG-INFO')\n                meta_path = os.path.join(p, 'PKG-INFO')\n                metadata = Metadata(path=meta_path, scheme='legacy')\n                req_path = os.path.join(p, 'requires.txt')\n                tl_path = os.path.join(p, 'top_level.txt')\n                requires = parse_requires_path(req_path)\n            else:\n                # FIXME handle the case where zipfile is not available\n                zipf = zipimport.zipimporter(path)\n                fileobj = StringIO(\n                    zipf.get_data('EGG-INFO/PKG-INFO').decode('utf8'))\n                metadata = Metadata(fileobj=fileobj, scheme='legacy')\n                try:\n                    data = zipf.get_data('EGG-INFO/requires.txt')\n                    tl_data = zipf.get_data('EGG-INFO/top_level.txt').decode('utf-8')\n                    requires = parse_requires_data(data.decode('utf-8'))\n                except IOError:\n                    requires = None\n        elif path.endswith('.egg-info'):\n            if os.path.isdir(path):\n                req_path = os.path.join(path, 'requires.txt')\n                requires = parse_requires_path(req_path)\n                path = os.path.join(path, 'PKG-INFO')\n                tl_path = os.path.join(path, 'top_level.txt')\n            metadata = Metadata(path=path, scheme='legacy')\n        else:\n            raise DistlibException('path must end with .egg-info or .egg, '\n                                   'got %r' % path)\n\n        if requires:\n            metadata.add_requirements(requires)\n        # look for top-level modules in top_level.txt, if present\n        if tl_data is None:\n            if tl_path is not None and os.path.exists(tl_path):\n                with open(tl_path, 'rb') as f:\n                    tl_data = f.read().decode('utf-8')\n        if not tl_data:\n            tl_data = []\n        else:\n            tl_data = tl_data.splitlines()\n        self.modules = tl_data\n        return metadata\n\n    def __repr__(self):\n        return '<EggInfoDistribution %r %s at %r>' % (\n            self.name, self.version, self.path)\n\n    def __str__(self):\n        return \"%s %s\" % (self.name, self.version)\n\n    def check_installed_files(self):\n        \"\"\"\n        Checks that the hashes and sizes of the files in ``RECORD`` are\n        matched by the files themselves. Returns a (possibly empty) list of\n        mismatches. Each entry in the mismatch list will be a tuple consisting\n        of the path, 'exists', 'size' or 'hash' according to what didn't match\n        (existence is checked first, then size, then hash), the expected\n        value and the actual value.\n        \"\"\"\n        mismatches = []\n        record_path = os.path.join(self.path, 'installed-files.txt')\n        if os.path.exists(record_path):\n            for path, _, _ in self.list_installed_files():\n                if path == record_path:\n                    continue\n                if not os.path.exists(path):\n                    mismatches.append((path, 'exists', True, False))\n        return mismatches\n\n    def list_installed_files(self):\n        \"\"\"\n        Iterates over the ``installed-files.txt`` entries and returns a tuple\n        ``(path, hash, size)`` for each line.\n\n        :returns: a list of (path, hash, size)\n        \"\"\"\n\n        def _md5(path):\n            f = open(path, 'rb')\n            try:\n                content = f.read()\n            finally:\n                f.close()\n            return hashlib.md5(content).hexdigest()\n\n        def _size(path):\n            return os.stat(path).st_size\n\n        record_path = os.path.join(self.path, 'installed-files.txt')\n        result = []\n        if os.path.exists(record_path):\n            with codecs.open(record_path, 'r', encoding='utf-8') as f:\n                for line in f:\n                    line = line.strip()\n                    p = os.path.normpath(os.path.join(self.path, line))\n                    # \"./\" is present as a marker between installed files\n                    # and installation metadata files\n                    if not os.path.exists(p):\n                        logger.warning('Non-existent file: %s', p)\n                        if p.endswith(('.pyc', '.pyo')):\n                            continue\n                        #otherwise fall through and fail\n                    if not os.path.isdir(p):\n                        result.append((p, _md5(p), _size(p)))\n            result.append((record_path, None, None))\n        return result\n\n    def list_distinfo_files(self, absolute=False):\n        \"\"\"\n        Iterates over the ``installed-files.txt`` entries and returns paths for\n        each line if the path is pointing to a file located in the\n        ``.egg-info`` directory or one of its subdirectories.\n\n        :parameter absolute: If *absolute* is ``True``, each returned path is\n                          transformed into a local absolute path. Otherwise the\n                          raw value from ``installed-files.txt`` is returned.\n        :type absolute: boolean\n        :returns: iterator of paths\n        \"\"\"\n        record_path = os.path.join(self.path, 'installed-files.txt')\n        if os.path.exists(record_path):\n            skip = True\n            with codecs.open(record_path, 'r', encoding='utf-8') as f:\n                for line in f:\n                    line = line.strip()\n                    if line == './':\n                        skip = False\n                        continue\n                    if not skip:\n                        p = os.path.normpath(os.path.join(self.path, line))\n                        if p.startswith(self.path):\n                            if absolute:\n                                yield p\n                            else:\n                                yield line\n\n    def __eq__(self, other):\n        return (isinstance(other, EggInfoDistribution) and\n                self.path == other.path)\n\n    # See http://docs.python.org/reference/datamodel#object.__hash__\n    __hash__ = object.__hash__\n\nnew_dist_class = InstalledDistribution\nold_dist_class = EggInfoDistribution\n\n\nclass DependencyGraph(object):\n    \"\"\"\n    Represents a dependency graph between distributions.\n\n    The dependency relationships are stored in an ``adjacency_list`` that maps\n    distributions to a list of ``(other, label)`` tuples where  ``other``\n    is a distribution and the edge is labeled with ``label`` (i.e. the version\n    specifier, if such was provided). Also, for more efficient traversal, for\n    every distribution ``x``, a list of predecessors is kept in\n    ``reverse_list[x]``. An edge from distribution ``a`` to\n    distribution ``b`` means that ``a`` depends on ``b``. If any missing\n    dependencies are found, they are stored in ``missing``, which is a\n    dictionary that maps distributions to a list of requirements that were not\n    provided by any other distributions.\n    \"\"\"\n\n    def __init__(self):\n        self.adjacency_list = {}\n        self.reverse_list = {}\n        self.missing = {}\n\n    def add_distribution(self, distribution):\n        \"\"\"Add the *distribution* to the graph.\n\n        :type distribution: :class:`distutils2.database.InstalledDistribution`\n                            or :class:`distutils2.database.EggInfoDistribution`\n        \"\"\"\n        self.adjacency_list[distribution] = []\n        self.reverse_list[distribution] = []\n        #self.missing[distribution] = []\n\n    def add_edge(self, x, y, label=None):\n        \"\"\"Add an edge from distribution *x* to distribution *y* with the given\n        *label*.\n\n        :type x: :class:`distutils2.database.InstalledDistribution` or\n                 :class:`distutils2.database.EggInfoDistribution`\n        :type y: :class:`distutils2.database.InstalledDistribution` or\n                 :class:`distutils2.database.EggInfoDistribution`\n        :type label: ``str`` or ``None``\n        \"\"\"\n        self.adjacency_list[x].append((y, label))\n        # multiple edges are allowed, so be careful\n        if x not in self.reverse_list[y]:\n            self.reverse_list[y].append(x)\n\n    def add_missing(self, distribution, requirement):\n        \"\"\"\n        Add a missing *requirement* for the given *distribution*.\n\n        :type distribution: :class:`distutils2.database.InstalledDistribution`\n                            or :class:`distutils2.database.EggInfoDistribution`\n        :type requirement: ``str``\n        \"\"\"\n        logger.debug('%s missing %r', distribution, requirement)\n        self.missing.setdefault(distribution, []).append(requirement)\n\n    def _repr_dist(self, dist):\n        return '%s %s' % (dist.name, dist.version)\n\n    def repr_node(self, dist, level=1):\n        \"\"\"Prints only a subgraph\"\"\"\n        output = [self._repr_dist(dist)]\n        for other, label in self.adjacency_list[dist]:\n            dist = self._repr_dist(other)\n            if label is not None:\n                dist = '%s [%s]' % (dist, label)\n            output.append('    ' * level + str(dist))\n            suboutput = self.repr_node(other, level + 1)\n            subs = suboutput.split('\\n')\n            output.extend(subs[1:])\n        return '\\n'.join(output)\n\n    def to_dot(self, f, skip_disconnected=True):\n        \"\"\"Writes a DOT output for the graph to the provided file *f*.\n\n        If *skip_disconnected* is set to ``True``, then all distributions\n        that are not dependent on any other distribution are skipped.\n\n        :type f: has to support ``file``-like operations\n        :type skip_disconnected: ``bool``\n        \"\"\"\n        disconnected = []\n\n        f.write(\"digraph dependencies {\\n\")\n        for dist, adjs in self.adjacency_list.items():\n            if len(adjs) == 0 and not skip_disconnected:\n                disconnected.append(dist)\n            for other, label in adjs:\n                if not label is None:\n                    f.write('\"%s\" -> \"%s\" [label=\"%s\"]\\n' %\n                            (dist.name, other.name, label))\n                else:\n                    f.write('\"%s\" -> \"%s\"\\n' % (dist.name, other.name))\n        if not skip_disconnected and len(disconnected) > 0:\n            f.write('subgraph disconnected {\\n')\n            f.write('label = \"Disconnected\"\\n')\n            f.write('bgcolor = red\\n')\n\n            for dist in disconnected:\n                f.write('\"%s\"' % dist.name)\n                f.write('\\n')\n            f.write('}\\n')\n        f.write('}\\n')\n\n    def topological_sort(self):\n        \"\"\"\n        Perform a topological sort of the graph.\n        :return: A tuple, the first element of which is a topologically sorted\n                 list of distributions, and the second element of which is a\n                 list of distributions that cannot be sorted because they have\n                 circular dependencies and so form a cycle.\n        \"\"\"\n        result = []\n        # Make a shallow copy of the adjacency list\n        alist = {}\n        for k, v in self.adjacency_list.items():\n            alist[k] = v[:]\n        while True:\n            # See what we can remove in this run\n            to_remove = []\n            for k, v in list(alist.items())[:]:\n                if not v:\n                    to_remove.append(k)\n                    del alist[k]\n            if not to_remove:\n                # What's left in alist (if anything) is a cycle.\n                break\n            # Remove from the adjacency list of others\n            for k, v in alist.items():\n                alist[k] = [(d, r) for d, r in v if d not in to_remove]\n            logger.debug('Moving to result: %s',\n                         ['%s (%s)' % (d.name, d.version) for d in to_remove])\n            result.extend(to_remove)\n        return result, list(alist.keys())\n\n    def __repr__(self):\n        \"\"\"Representation of the graph\"\"\"\n        output = []\n        for dist, adjs in self.adjacency_list.items():\n            output.append(self.repr_node(dist))\n        return '\\n'.join(output)\n\n\ndef make_graph(dists, scheme='default'):\n    \"\"\"Makes a dependency graph from the given distributions.\n\n    :parameter dists: a list of distributions\n    :type dists: list of :class:`distutils2.database.InstalledDistribution` and\n                 :class:`distutils2.database.EggInfoDistribution` instances\n    :rtype: a :class:`DependencyGraph` instance\n    \"\"\"\n    scheme = get_scheme(scheme)\n    graph = DependencyGraph()\n    provided = {}  # maps names to lists of (version, dist) tuples\n\n    # first, build the graph and find out what's provided\n    for dist in dists:\n        graph.add_distribution(dist)\n\n        for p in dist.provides:\n            name, version = parse_name_and_version(p)\n            logger.debug('Add to provided: %s, %s, %s', name, version, dist)\n            provided.setdefault(name, []).append((version, dist))\n\n    # now make the edges\n    for dist in dists:\n        requires = (dist.run_requires | dist.meta_requires |\n                    dist.build_requires | dist.dev_requires)\n        for req in requires:\n            try:\n                matcher = scheme.matcher(req)\n            except UnsupportedVersionError:\n                # XXX compat-mode if cannot read the version\n                logger.warning('could not read version %r - using name only',\n                               req)\n                name = req.split()[0]\n                matcher = scheme.matcher(name)\n\n            name = matcher.key   # case-insensitive\n\n            matched = False\n            if name in provided:\n                for version, provider in provided[name]:\n                    try:\n                        match = matcher.match(version)\n                    except UnsupportedVersionError:\n                        match = False\n\n                    if match:\n                        graph.add_edge(dist, provider, req)\n                        matched = True\n                        break\n            if not matched:\n                graph.add_missing(dist, req)\n    return graph\n\n\ndef get_dependent_dists(dists, dist):\n    \"\"\"Recursively generate a list of distributions from *dists* that are\n    dependent on *dist*.\n\n    :param dists: a list of distributions\n    :param dist: a distribution, member of *dists* for which we are interested\n    \"\"\"\n    if dist not in dists:\n        raise DistlibException('given distribution %r is not a member '\n                               'of the list' % dist.name)\n    graph = make_graph(dists)\n\n    dep = [dist]  # dependent distributions\n    todo = graph.reverse_list[dist]  # list of nodes we should inspect\n\n    while todo:\n        d = todo.pop()\n        dep.append(d)\n        for succ in graph.reverse_list[d]:\n            if succ not in dep:\n                todo.append(succ)\n\n    dep.pop(0)  # remove dist from dep, was there to prevent infinite loops\n    return dep\n\n\ndef get_required_dists(dists, dist):\n    \"\"\"Recursively generate a list of distributions from *dists* that are\n    required by *dist*.\n\n    :param dists: a list of distributions\n    :param dist: a distribution, member of *dists* for which we are interested\n                 in finding the dependencies.\n    \"\"\"\n    if dist not in dists:\n        raise DistlibException('given distribution %r is not a member '\n                               'of the list' % dist.name)\n    graph = make_graph(dists)\n\n    req = set()  # required distributions\n    todo = graph.adjacency_list[dist]  # list of nodes we should inspect\n    seen = set(t[0] for t in todo) # already added to todo\n\n    while todo:\n        d = todo.pop()[0]\n        req.add(d)\n        pred_list = graph.adjacency_list[d]\n        for pred in pred_list:\n            d = pred[0]\n            if d not in req and d not in seen:\n                seen.add(d)\n                todo.append(pred)\n    return req\n\n\ndef make_dist(name, version, **kwargs):\n    \"\"\"\n    A convenience method for making a dist given just a name and version.\n    \"\"\"\n    summary = kwargs.pop('summary', 'Placeholder for summary')\n    md = Metadata(**kwargs)\n    md.name = name\n    md.version = version\n    md.summary = summary or 'Placeholder for summary'\n    return Distribution(md)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distlib/index.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013 Vinay Sajip.\n# Licensed to the Python Software Foundation under a contributor agreement.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\nimport hashlib\nimport logging\nimport os\nimport shutil\nimport subprocess\nimport tempfile\ntry:\n    from threading import Thread\nexcept ImportError:  # pragma: no cover\n    from dummy_threading import Thread\n\nfrom . import DistlibException\nfrom .compat import (HTTPBasicAuthHandler, Request, HTTPPasswordMgr,\n                     urlparse, build_opener, string_types)\nfrom .util import zip_dir, ServerProxy\n\nlogger = logging.getLogger(__name__)\n\nDEFAULT_INDEX = 'https://pypi.org/pypi'\nDEFAULT_REALM = 'pypi'\n\nclass PackageIndex(object):\n    \"\"\"\n    This class represents a package index compatible with PyPI, the Python\n    Package Index.\n    \"\"\"\n\n    boundary = b'----------ThIs_Is_tHe_distlib_index_bouNdaRY_$'\n\n    def __init__(self, url=None):\n        \"\"\"\n        Initialise an instance.\n\n        :param url: The URL of the index. If not specified, the URL for PyPI is\n                    used.\n        \"\"\"\n        self.url = url or DEFAULT_INDEX\n        self.read_configuration()\n        scheme, netloc, path, params, query, frag = urlparse(self.url)\n        if params or query or frag or scheme not in ('http', 'https'):\n            raise DistlibException('invalid repository: %s' % self.url)\n        self.password_handler = None\n        self.ssl_verifier = None\n        self.gpg = None\n        self.gpg_home = None\n        with open(os.devnull, 'w') as sink:\n            # Use gpg by default rather than gpg2, as gpg2 insists on\n            # prompting for passwords\n            for s in ('gpg', 'gpg2'):\n                try:\n                    rc = subprocess.check_call([s, '--version'], stdout=sink,\n                                               stderr=sink)\n                    if rc == 0:\n                        self.gpg = s\n                        break\n                except OSError:\n                    pass\n\n    def _get_pypirc_command(self):\n        \"\"\"\n        Get the distutils command for interacting with PyPI configurations.\n        :return: the command.\n        \"\"\"\n        from .util import _get_pypirc_command as cmd\n        return cmd()\n\n    def read_configuration(self):\n        \"\"\"\n        Read the PyPI access configuration as supported by distutils. This populates\n        ``username``, ``password``, ``realm`` and ``url`` attributes from the\n        configuration.\n        \"\"\"\n        from .util import _load_pypirc\n        cfg = _load_pypirc(self)\n        self.username = cfg.get('username')\n        self.password = cfg.get('password')\n        self.realm = cfg.get('realm', 'pypi')\n        self.url = cfg.get('repository', self.url)\n\n    def save_configuration(self):\n        \"\"\"\n        Save the PyPI access configuration. You must have set ``username`` and\n        ``password`` attributes before calling this method.\n        \"\"\"\n        self.check_credentials()\n        from .util import _store_pypirc\n        _store_pypirc(self)\n\n    def check_credentials(self):\n        \"\"\"\n        Check that ``username`` and ``password`` have been set, and raise an\n        exception if not.\n        \"\"\"\n        if self.username is None or self.password is None:\n            raise DistlibException('username and password must be set')\n        pm = HTTPPasswordMgr()\n        _, netloc, _, _, _, _ = urlparse(self.url)\n        pm.add_password(self.realm, netloc, self.username, self.password)\n        self.password_handler = HTTPBasicAuthHandler(pm)\n\n    def register(self, metadata):  # pragma: no cover\n        \"\"\"\n        Register a distribution on PyPI, using the provided metadata.\n\n        :param metadata: A :class:`Metadata` instance defining at least a name\n                         and version number for the distribution to be\n                         registered.\n        :return: The HTTP response received from PyPI upon submission of the\n                request.\n        \"\"\"\n        self.check_credentials()\n        metadata.validate()\n        d = metadata.todict()\n        d[':action'] = 'verify'\n        request = self.encode_request(d.items(), [])\n        response = self.send_request(request)\n        d[':action'] = 'submit'\n        request = self.encode_request(d.items(), [])\n        return self.send_request(request)\n\n    def _reader(self, name, stream, outbuf):\n        \"\"\"\n        Thread runner for reading lines of from a subprocess into a buffer.\n\n        :param name: The logical name of the stream (used for logging only).\n        :param stream: The stream to read from. This will typically a pipe\n                       connected to the output stream of a subprocess.\n        :param outbuf: The list to append the read lines to.\n        \"\"\"\n        while True:\n            s = stream.readline()\n            if not s:\n                break\n            s = s.decode('utf-8').rstrip()\n            outbuf.append(s)\n            logger.debug('%s: %s' % (name, s))\n        stream.close()\n\n    def get_sign_command(self, filename, signer, sign_password, keystore=None):  # pragma: no cover\n        \"\"\"\n        Return a suitable command for signing a file.\n\n        :param filename: The pathname to the file to be signed.\n        :param signer: The identifier of the signer of the file.\n        :param sign_password: The passphrase for the signer's\n                              private key used for signing.\n        :param keystore: The path to a directory which contains the keys\n                         used in verification. If not specified, the\n                         instance's ``gpg_home`` attribute is used instead.\n        :return: The signing command as a list suitable to be\n                 passed to :class:`subprocess.Popen`.\n        \"\"\"\n        cmd = [self.gpg, '--status-fd', '2', '--no-tty']\n        if keystore is None:\n            keystore = self.gpg_home\n        if keystore:\n            cmd.extend(['--homedir', keystore])\n        if sign_password is not None:\n            cmd.extend(['--batch', '--passphrase-fd', '0'])\n        td = tempfile.mkdtemp()\n        sf = os.path.join(td, os.path.basename(filename) + '.asc')\n        cmd.extend(['--detach-sign', '--armor', '--local-user',\n                    signer, '--output', sf, filename])\n        logger.debug('invoking: %s', ' '.join(cmd))\n        return cmd, sf\n\n    def run_command(self, cmd, input_data=None):\n        \"\"\"\n        Run a command in a child process , passing it any input data specified.\n\n        :param cmd: The command to run.\n        :param input_data: If specified, this must be a byte string containing\n                           data to be sent to the child process.\n        :return: A tuple consisting of the subprocess' exit code, a list of\n                 lines read from the subprocess' ``stdout``, and a list of\n                 lines read from the subprocess' ``stderr``.\n        \"\"\"\n        kwargs = {\n            'stdout': subprocess.PIPE,\n            'stderr': subprocess.PIPE,\n        }\n        if input_data is not None:\n            kwargs['stdin'] = subprocess.PIPE\n        stdout = []\n        stderr = []\n        p = subprocess.Popen(cmd, **kwargs)\n        # We don't use communicate() here because we may need to\n        # get clever with interacting with the command\n        t1 = Thread(target=self._reader, args=('stdout', p.stdout, stdout))\n        t1.start()\n        t2 = Thread(target=self._reader, args=('stderr', p.stderr, stderr))\n        t2.start()\n        if input_data is not None:\n            p.stdin.write(input_data)\n            p.stdin.close()\n\n        p.wait()\n        t1.join()\n        t2.join()\n        return p.returncode, stdout, stderr\n\n    def sign_file(self, filename, signer, sign_password, keystore=None):  # pragma: no cover\n        \"\"\"\n        Sign a file.\n\n        :param filename: The pathname to the file to be signed.\n        :param signer: The identifier of the signer of the file.\n        :param sign_password: The passphrase for the signer's\n                              private key used for signing.\n        :param keystore: The path to a directory which contains the keys\n                         used in signing. If not specified, the instance's\n                         ``gpg_home`` attribute is used instead.\n        :return: The absolute pathname of the file where the signature is\n                 stored.\n        \"\"\"\n        cmd, sig_file = self.get_sign_command(filename, signer, sign_password,\n                                              keystore)\n        rc, stdout, stderr = self.run_command(cmd,\n                                              sign_password.encode('utf-8'))\n        if rc != 0:\n            raise DistlibException('sign command failed with error '\n                                   'code %s' % rc)\n        return sig_file\n\n    def upload_file(self, metadata, filename, signer=None, sign_password=None,\n                    filetype='sdist', pyversion='source', keystore=None):\n        \"\"\"\n        Upload a release file to the index.\n\n        :param metadata: A :class:`Metadata` instance defining at least a name\n                         and version number for the file to be uploaded.\n        :param filename: The pathname of the file to be uploaded.\n        :param signer: The identifier of the signer of the file.\n        :param sign_password: The passphrase for the signer's\n                              private key used for signing.\n        :param filetype: The type of the file being uploaded. This is the\n                        distutils command which produced that file, e.g.\n                        ``sdist`` or ``bdist_wheel``.\n        :param pyversion: The version of Python which the release relates\n                          to. For code compatible with any Python, this would\n                          be ``source``, otherwise it would be e.g. ``3.2``.\n        :param keystore: The path to a directory which contains the keys\n                         used in signing. If not specified, the instance's\n                         ``gpg_home`` attribute is used instead.\n        :return: The HTTP response received from PyPI upon submission of the\n                request.\n        \"\"\"\n        self.check_credentials()\n        if not os.path.exists(filename):\n            raise DistlibException('not found: %s' % filename)\n        metadata.validate()\n        d = metadata.todict()\n        sig_file = None\n        if signer:\n            if not self.gpg:\n                logger.warning('no signing program available - not signed')\n            else:\n                sig_file = self.sign_file(filename, signer, sign_password,\n                                          keystore)\n        with open(filename, 'rb') as f:\n            file_data = f.read()\n        md5_digest = hashlib.md5(file_data).hexdigest()\n        sha256_digest = hashlib.sha256(file_data).hexdigest()\n        d.update({\n            ':action': 'file_upload',\n            'protocol_version': '1',\n            'filetype': filetype,\n            'pyversion': pyversion,\n            'md5_digest': md5_digest,\n            'sha256_digest': sha256_digest,\n        })\n        files = [('content', os.path.basename(filename), file_data)]\n        if sig_file:\n            with open(sig_file, 'rb') as f:\n                sig_data = f.read()\n            files.append(('gpg_signature', os.path.basename(sig_file),\n                         sig_data))\n            shutil.rmtree(os.path.dirname(sig_file))\n        request = self.encode_request(d.items(), files)\n        return self.send_request(request)\n\n    def upload_documentation(self, metadata, doc_dir):  # pragma: no cover\n        \"\"\"\n        Upload documentation to the index.\n\n        :param metadata: A :class:`Metadata` instance defining at least a name\n                         and version number for the documentation to be\n                         uploaded.\n        :param doc_dir: The pathname of the directory which contains the\n                        documentation. This should be the directory that\n                        contains the ``index.html`` for the documentation.\n        :return: The HTTP response received from PyPI upon submission of the\n                request.\n        \"\"\"\n        self.check_credentials()\n        if not os.path.isdir(doc_dir):\n            raise DistlibException('not a directory: %r' % doc_dir)\n        fn = os.path.join(doc_dir, 'index.html')\n        if not os.path.exists(fn):\n            raise DistlibException('not found: %r' % fn)\n        metadata.validate()\n        name, version = metadata.name, metadata.version\n        zip_data = zip_dir(doc_dir).getvalue()\n        fields = [(':action', 'doc_upload'),\n                  ('name', name), ('version', version)]\n        files = [('content', name, zip_data)]\n        request = self.encode_request(fields, files)\n        return self.send_request(request)\n\n    def get_verify_command(self, signature_filename, data_filename,\n                           keystore=None):\n        \"\"\"\n        Return a suitable command for verifying a file.\n\n        :param signature_filename: The pathname to the file containing the\n                                   signature.\n        :param data_filename: The pathname to the file containing the\n                              signed data.\n        :param keystore: The path to a directory which contains the keys\n                         used in verification. If not specified, the\n                         instance's ``gpg_home`` attribute is used instead.\n        :return: The verifying command as a list suitable to be\n                 passed to :class:`subprocess.Popen`.\n        \"\"\"\n        cmd = [self.gpg, '--status-fd', '2', '--no-tty']\n        if keystore is None:\n            keystore = self.gpg_home\n        if keystore:\n            cmd.extend(['--homedir', keystore])\n        cmd.extend(['--verify', signature_filename, data_filename])\n        logger.debug('invoking: %s', ' '.join(cmd))\n        return cmd\n\n    def verify_signature(self, signature_filename, data_filename,\n                         keystore=None):\n        \"\"\"\n        Verify a signature for a file.\n\n        :param signature_filename: The pathname to the file containing the\n                                   signature.\n        :param data_filename: The pathname to the file containing the\n                              signed data.\n        :param keystore: The path to a directory which contains the keys\n                         used in verification. If not specified, the\n                         instance's ``gpg_home`` attribute is used instead.\n        :return: True if the signature was verified, else False.\n        \"\"\"\n        if not self.gpg:\n            raise DistlibException('verification unavailable because gpg '\n                                   'unavailable')\n        cmd = self.get_verify_command(signature_filename, data_filename,\n                                      keystore)\n        rc, stdout, stderr = self.run_command(cmd)\n        if rc not in (0, 1):\n            raise DistlibException('verify command failed with error '\n                             'code %s' % rc)\n        return rc == 0\n\n    def download_file(self, url, destfile, digest=None, reporthook=None):\n        \"\"\"\n        This is a convenience method for downloading a file from an URL.\n        Normally, this will be a file from the index, though currently\n        no check is made for this (i.e. a file can be downloaded from\n        anywhere).\n\n        The method is just like the :func:`urlretrieve` function in the\n        standard library, except that it allows digest computation to be\n        done during download and checking that the downloaded data\n        matched any expected value.\n\n        :param url: The URL of the file to be downloaded (assumed to be\n                    available via an HTTP GET request).\n        :param destfile: The pathname where the downloaded file is to be\n                         saved.\n        :param digest: If specified, this must be a (hasher, value)\n                       tuple, where hasher is the algorithm used (e.g.\n                       ``'md5'``) and ``value`` is the expected value.\n        :param reporthook: The same as for :func:`urlretrieve` in the\n                           standard library.\n        \"\"\"\n        if digest is None:\n            digester = None\n            logger.debug('No digest specified')\n        else:\n            if isinstance(digest, (list, tuple)):\n                hasher, digest = digest\n            else:\n                hasher = 'md5'\n            digester = getattr(hashlib, hasher)()\n            logger.debug('Digest specified: %s' % digest)\n        # The following code is equivalent to urlretrieve.\n        # We need to do it this way so that we can compute the\n        # digest of the file as we go.\n        with open(destfile, 'wb') as dfp:\n            # addinfourl is not a context manager on 2.x\n            # so we have to use try/finally\n            sfp = self.send_request(Request(url))\n            try:\n                headers = sfp.info()\n                blocksize = 8192\n                size = -1\n                read = 0\n                blocknum = 0\n                if \"content-length\" in headers:\n                    size = int(headers[\"Content-Length\"])\n                if reporthook:\n                    reporthook(blocknum, blocksize, size)\n                while True:\n                    block = sfp.read(blocksize)\n                    if not block:\n                        break\n                    read += len(block)\n                    dfp.write(block)\n                    if digester:\n                        digester.update(block)\n                    blocknum += 1\n                    if reporthook:\n                        reporthook(blocknum, blocksize, size)\n            finally:\n                sfp.close()\n\n        # check that we got the whole file, if we can\n        if size >= 0 and read < size:\n            raise DistlibException(\n                'retrieval incomplete: got only %d out of %d bytes'\n                % (read, size))\n        # if we have a digest, it must match.\n        if digester:\n            actual = digester.hexdigest()\n            if digest != actual:\n                raise DistlibException('%s digest mismatch for %s: expected '\n                                       '%s, got %s' % (hasher, destfile,\n                                                       digest, actual))\n            logger.debug('Digest verified: %s', digest)\n\n    def send_request(self, req):\n        \"\"\"\n        Send a standard library :class:`Request` to PyPI and return its\n        response.\n\n        :param req: The request to send.\n        :return: The HTTP response from PyPI (a standard library HTTPResponse).\n        \"\"\"\n        handlers = []\n        if self.password_handler:\n            handlers.append(self.password_handler)\n        if self.ssl_verifier:\n            handlers.append(self.ssl_verifier)\n        opener = build_opener(*handlers)\n        return opener.open(req)\n\n    def encode_request(self, fields, files):\n        \"\"\"\n        Encode fields and files for posting to an HTTP server.\n\n        :param fields: The fields to send as a list of (fieldname, value)\n                       tuples.\n        :param files: The files to send as a list of (fieldname, filename,\n                      file_bytes) tuple.\n        \"\"\"\n        # Adapted from packaging, which in turn was adapted from\n        # http://code.activestate.com/recipes/146306\n\n        parts = []\n        boundary = self.boundary\n        for k, values in fields:\n            if not isinstance(values, (list, tuple)):\n                values = [values]\n\n            for v in values:\n                parts.extend((\n                    b'--' + boundary,\n                    ('Content-Disposition: form-data; name=\"%s\"' %\n                     k).encode('utf-8'),\n                    b'',\n                    v.encode('utf-8')))\n        for key, filename, value in files:\n            parts.extend((\n                b'--' + boundary,\n                ('Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"' %\n                 (key, filename)).encode('utf-8'),\n                b'',\n                value))\n\n        parts.extend((b'--' + boundary + b'--', b''))\n\n        body = b'\\r\\n'.join(parts)\n        ct = b'multipart/form-data; boundary=' + boundary\n        headers = {\n            'Content-type': ct,\n            'Content-length': str(len(body))\n        }\n        return Request(self.url, body, headers)\n\n    def search(self, terms, operator=None):  # pragma: no cover\n        if isinstance(terms, string_types):\n            terms = {'name': terms}\n        rpc_proxy = ServerProxy(self.url, timeout=3.0)\n        try:\n            return rpc_proxy.search(terms, operator or 'and')\n        finally:\n            rpc_proxy('close')()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distlib/locators.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2012-2015 Vinay Sajip.\n# Licensed to the Python Software Foundation under a contributor agreement.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\n\nimport gzip\nfrom io import BytesIO\nimport json\nimport logging\nimport os\nimport posixpath\nimport re\ntry:\n    import threading\nexcept ImportError:  # pragma: no cover\n    import dummy_threading as threading\nimport zlib\n\nfrom . import DistlibException\nfrom .compat import (urljoin, urlparse, urlunparse, url2pathname, pathname2url,\n                     queue, quote, unescape, build_opener,\n                     HTTPRedirectHandler as BaseRedirectHandler, text_type,\n                     Request, HTTPError, URLError)\nfrom .database import Distribution, DistributionPath, make_dist\nfrom .metadata import Metadata, MetadataInvalidError\nfrom .util import (cached_property, ensure_slash, split_filename, get_project_data,\n                   parse_requirement, parse_name_and_version, ServerProxy,\n                   normalize_name)\nfrom .version import get_scheme, UnsupportedVersionError\nfrom .wheel import Wheel, is_compatible\n\nlogger = logging.getLogger(__name__)\n\nHASHER_HASH = re.compile(r'^(\\w+)=([a-f0-9]+)')\nCHARSET = re.compile(r';\\s*charset\\s*=\\s*(.*)\\s*$', re.I)\nHTML_CONTENT_TYPE = re.compile('text/html|application/x(ht)?ml')\nDEFAULT_INDEX = 'https://pypi.org/pypi'\n\ndef get_all_distribution_names(url=None):\n    \"\"\"\n    Return all distribution names known by an index.\n    :param url: The URL of the index.\n    :return: A list of all known distribution names.\n    \"\"\"\n    if url is None:\n        url = DEFAULT_INDEX\n    client = ServerProxy(url, timeout=3.0)\n    try:\n        return client.list_packages()\n    finally:\n        client('close')()\n\nclass RedirectHandler(BaseRedirectHandler):\n    \"\"\"\n    A class to work around a bug in some Python 3.2.x releases.\n    \"\"\"\n    # There's a bug in the base version for some 3.2.x\n    # (e.g. 3.2.2 on Ubuntu Oneiric). If a Location header\n    # returns e.g. /abc, it bails because it says the scheme ''\n    # is bogus, when actually it should use the request's\n    # URL for the scheme. See Python issue #13696.\n    def http_error_302(self, req, fp, code, msg, headers):\n        # Some servers (incorrectly) return multiple Location headers\n        # (so probably same goes for URI).  Use first header.\n        newurl = None\n        for key in ('location', 'uri'):\n            if key in headers:\n                newurl = headers[key]\n                break\n        if newurl is None:  # pragma: no cover\n            return\n        urlparts = urlparse(newurl)\n        if urlparts.scheme == '':\n            newurl = urljoin(req.get_full_url(), newurl)\n            if hasattr(headers, 'replace_header'):\n                headers.replace_header(key, newurl)\n            else:\n                headers[key] = newurl\n        return BaseRedirectHandler.http_error_302(self, req, fp, code, msg,\n                                                  headers)\n\n    http_error_301 = http_error_303 = http_error_307 = http_error_302\n\nclass Locator(object):\n    \"\"\"\n    A base class for locators - things that locate distributions.\n    \"\"\"\n    source_extensions = ('.tar.gz', '.tar.bz2', '.tar', '.zip', '.tgz', '.tbz')\n    binary_extensions = ('.egg', '.exe', '.whl')\n    excluded_extensions = ('.pdf',)\n\n    # A list of tags indicating which wheels you want to match. The default\n    # value of None matches against the tags compatible with the running\n    # Python. If you want to match other values, set wheel_tags on a locator\n    # instance to a list of tuples (pyver, abi, arch) which you want to match.\n    wheel_tags = None\n\n    downloadable_extensions = source_extensions + ('.whl',)\n\n    def __init__(self, scheme='default'):\n        \"\"\"\n        Initialise an instance.\n        :param scheme: Because locators look for most recent versions, they\n                       need to know the version scheme to use. This specifies\n                       the current PEP-recommended scheme - use ``'legacy'``\n                       if you need to support existing distributions on PyPI.\n        \"\"\"\n        self._cache = {}\n        self.scheme = scheme\n        # Because of bugs in some of the handlers on some of the platforms,\n        # we use our own opener rather than just using urlopen.\n        self.opener = build_opener(RedirectHandler())\n        # If get_project() is called from locate(), the matcher instance\n        # is set from the requirement passed to locate(). See issue #18 for\n        # why this can be useful to know.\n        self.matcher = None\n        self.errors = queue.Queue()\n\n    def get_errors(self):\n        \"\"\"\n        Return any errors which have occurred.\n        \"\"\"\n        result = []\n        while not self.errors.empty():  # pragma: no cover\n            try:\n                e = self.errors.get(False)\n                result.append(e)\n            except self.errors.Empty:\n                continue\n            self.errors.task_done()\n        return result\n\n    def clear_errors(self):\n        \"\"\"\n        Clear any errors which may have been logged.\n        \"\"\"\n        # Just get the errors and throw them away\n        self.get_errors()\n\n    def clear_cache(self):\n        self._cache.clear()\n\n    def _get_scheme(self):\n        return self._scheme\n\n    def _set_scheme(self, value):\n        self._scheme = value\n\n    scheme = property(_get_scheme, _set_scheme)\n\n    def _get_project(self, name):\n        \"\"\"\n        For a given project, get a dictionary mapping available versions to Distribution\n        instances.\n\n        This should be implemented in subclasses.\n\n        If called from a locate() request, self.matcher will be set to a\n        matcher for the requirement to satisfy, otherwise it will be None.\n        \"\"\"\n        raise NotImplementedError('Please implement in the subclass')\n\n    def get_distribution_names(self):\n        \"\"\"\n        Return all the distribution names known to this locator.\n        \"\"\"\n        raise NotImplementedError('Please implement in the subclass')\n\n    def get_project(self, name):\n        \"\"\"\n        For a given project, get a dictionary mapping available versions to Distribution\n        instances.\n\n        This calls _get_project to do all the work, and just implements a caching layer on top.\n        \"\"\"\n        if self._cache is None:  # pragma: no cover\n            result = self._get_project(name)\n        elif name in self._cache:\n            result = self._cache[name]\n        else:\n            self.clear_errors()\n            result = self._get_project(name)\n            self._cache[name] = result\n        return result\n\n    def score_url(self, url):\n        \"\"\"\n        Give an url a score which can be used to choose preferred URLs\n        for a given project release.\n        \"\"\"\n        t = urlparse(url)\n        basename = posixpath.basename(t.path)\n        compatible = True\n        is_wheel = basename.endswith('.whl')\n        is_downloadable = basename.endswith(self.downloadable_extensions)\n        if is_wheel:\n            compatible = is_compatible(Wheel(basename), self.wheel_tags)\n        return (t.scheme == 'https', 'pypi.org' in t.netloc,\n                is_downloadable, is_wheel, compatible, basename)\n\n    def prefer_url(self, url1, url2):\n        \"\"\"\n        Choose one of two URLs where both are candidates for distribution\n        archives for the same version of a distribution (for example,\n        .tar.gz vs. zip).\n\n        The current implementation favours https:// URLs over http://, archives\n        from PyPI over those from other locations, wheel compatibility (if a\n        wheel) and then the archive name.\n        \"\"\"\n        result = url2\n        if url1:\n            s1 = self.score_url(url1)\n            s2 = self.score_url(url2)\n            if s1 > s2:\n                result = url1\n            if result != url2:\n                logger.debug('Not replacing %r with %r', url1, url2)\n            else:\n                logger.debug('Replacing %r with %r', url1, url2)\n        return result\n\n    def split_filename(self, filename, project_name):\n        \"\"\"\n        Attempt to split a filename in project name, version and Python version.\n        \"\"\"\n        return split_filename(filename, project_name)\n\n    def convert_url_to_download_info(self, url, project_name):\n        \"\"\"\n        See if a URL is a candidate for a download URL for a project (the URL\n        has typically been scraped from an HTML page).\n\n        If it is, a dictionary is returned with keys \"name\", \"version\",\n        \"filename\" and \"url\"; otherwise, None is returned.\n        \"\"\"\n        def same_project(name1, name2):\n            return normalize_name(name1) == normalize_name(name2)\n\n        result = None\n        scheme, netloc, path, params, query, frag = urlparse(url)\n        if frag.lower().startswith('egg='):  # pragma: no cover\n            logger.debug('%s: version hint in fragment: %r',\n                         project_name, frag)\n        m = HASHER_HASH.match(frag)\n        if m:\n            algo, digest = m.groups()\n        else:\n            algo, digest = None, None\n        origpath = path\n        if path and path[-1] == '/':  # pragma: no cover\n            path = path[:-1]\n        if path.endswith('.whl'):\n            try:\n                wheel = Wheel(path)\n                if not is_compatible(wheel, self.wheel_tags):\n                    logger.debug('Wheel not compatible: %s', path)\n                else:\n                    if project_name is None:\n                        include = True\n                    else:\n                        include = same_project(wheel.name, project_name)\n                    if include:\n                        result = {\n                            'name': wheel.name,\n                            'version': wheel.version,\n                            'filename': wheel.filename,\n                            'url': urlunparse((scheme, netloc, origpath,\n                                               params, query, '')),\n                            'python-version': ', '.join(\n                                ['.'.join(list(v[2:])) for v in wheel.pyver]),\n                        }\n            except Exception as e:  # pragma: no cover\n                logger.warning('invalid path for wheel: %s', path)\n        elif not path.endswith(self.downloadable_extensions):  # pragma: no cover\n            logger.debug('Not downloadable: %s', path)\n        else:  # downloadable extension\n            path = filename = posixpath.basename(path)\n            for ext in self.downloadable_extensions:\n                if path.endswith(ext):\n                    path = path[:-len(ext)]\n                    t = self.split_filename(path, project_name)\n                    if not t:  # pragma: no cover\n                        logger.debug('No match for project/version: %s', path)\n                    else:\n                        name, version, pyver = t\n                        if not project_name or same_project(project_name, name):\n                            result = {\n                                'name': name,\n                                'version': version,\n                                'filename': filename,\n                                'url': urlunparse((scheme, netloc, origpath,\n                                                   params, query, '')),\n                                #'packagetype': 'sdist',\n                            }\n                            if pyver:  # pragma: no cover\n                                result['python-version'] = pyver\n                    break\n        if result and algo:\n            result['%s_digest' % algo] = digest\n        return result\n\n    def _get_digest(self, info):\n        \"\"\"\n        Get a digest from a dictionary by looking at a \"digests\" dictionary\n        or keys of the form 'algo_digest'.\n\n        Returns a 2-tuple (algo, digest) if found, else None. Currently\n        looks only for SHA256, then MD5.\n        \"\"\"\n        result = None\n        if 'digests' in info:\n            digests = info['digests']\n            for algo in ('sha256', 'md5'):\n                if algo in digests:\n                    result = (algo, digests[algo])\n                    break\n        if not result:\n            for algo in ('sha256', 'md5'):\n                key = '%s_digest' % algo\n                if key in info:\n                    result = (algo, info[key])\n                    break\n        return result\n\n    def _update_version_data(self, result, info):\n        \"\"\"\n        Update a result dictionary (the final result from _get_project) with a\n        dictionary for a specific version, which typically holds information\n        gleaned from a filename or URL for an archive for the distribution.\n        \"\"\"\n        name = info.pop('name')\n        version = info.pop('version')\n        if version in result:\n            dist = result[version]\n            md = dist.metadata\n        else:\n            dist = make_dist(name, version, scheme=self.scheme)\n            md = dist.metadata\n        dist.digest = digest = self._get_digest(info)\n        url = info['url']\n        result['digests'][url] = digest\n        if md.source_url != info['url']:\n            md.source_url = self.prefer_url(md.source_url, url)\n            result['urls'].setdefault(version, set()).add(url)\n        dist.locator = self\n        result[version] = dist\n\n    def locate(self, requirement, prereleases=False):\n        \"\"\"\n        Find the most recent distribution which matches the given\n        requirement.\n\n        :param requirement: A requirement of the form 'foo (1.0)' or perhaps\n                            'foo (>= 1.0, < 2.0, != 1.3)'\n        :param prereleases: If ``True``, allow pre-release versions\n                            to be located. Otherwise, pre-release versions\n                            are not returned.\n        :return: A :class:`Distribution` instance, or ``None`` if no such\n                 distribution could be located.\n        \"\"\"\n        result = None\n        r = parse_requirement(requirement)\n        if r is None:  # pragma: no cover\n            raise DistlibException('Not a valid requirement: %r' % requirement)\n        scheme = get_scheme(self.scheme)\n        self.matcher = matcher = scheme.matcher(r.requirement)\n        logger.debug('matcher: %s (%s)', matcher, type(matcher).__name__)\n        versions = self.get_project(r.name)\n        if len(versions) > 2:   # urls and digests keys are present\n            # sometimes, versions are invalid\n            slist = []\n            vcls = matcher.version_class\n            for k in versions:\n                if k in ('urls', 'digests'):\n                    continue\n                try:\n                    if not matcher.match(k):\n                        pass  # logger.debug('%s did not match %r', matcher, k)\n                    else:\n                        if prereleases or not vcls(k).is_prerelease:\n                            slist.append(k)\n                        # else:\n                            # logger.debug('skipping pre-release '\n                                         # 'version %s of %s', k, matcher.name)\n                except Exception:  # pragma: no cover\n                    logger.warning('error matching %s with %r', matcher, k)\n                    pass # slist.append(k)\n            if len(slist) > 1:\n                slist = sorted(slist, key=scheme.key)\n            if slist:\n                logger.debug('sorted list: %s', slist)\n                version = slist[-1]\n                result = versions[version]\n        if result:\n            if r.extras:\n                result.extras = r.extras\n            result.download_urls = versions.get('urls', {}).get(version, set())\n            d = {}\n            sd = versions.get('digests', {})\n            for url in result.download_urls:\n                if url in sd:  # pragma: no cover\n                    d[url] = sd[url]\n            result.digests = d\n        self.matcher = None\n        return result\n\n\nclass PyPIRPCLocator(Locator):\n    \"\"\"\n    This locator uses XML-RPC to locate distributions. It therefore\n    cannot be used with simple mirrors (that only mirror file content).\n    \"\"\"\n    def __init__(self, url, **kwargs):\n        \"\"\"\n        Initialise an instance.\n\n        :param url: The URL to use for XML-RPC.\n        :param kwargs: Passed to the superclass constructor.\n        \"\"\"\n        super(PyPIRPCLocator, self).__init__(**kwargs)\n        self.base_url = url\n        self.client = ServerProxy(url, timeout=3.0)\n\n    def get_distribution_names(self):\n        \"\"\"\n        Return all the distribution names known to this locator.\n        \"\"\"\n        return set(self.client.list_packages())\n\n    def _get_project(self, name):\n        result = {'urls': {}, 'digests': {}}\n        versions = self.client.package_releases(name, True)\n        for v in versions:\n            urls = self.client.release_urls(name, v)\n            data = self.client.release_data(name, v)\n            metadata = Metadata(scheme=self.scheme)\n            metadata.name = data['name']\n            metadata.version = data['version']\n            metadata.license = data.get('license')\n            metadata.keywords = data.get('keywords', [])\n            metadata.summary = data.get('summary')\n            dist = Distribution(metadata)\n            if urls:\n                info = urls[0]\n                metadata.source_url = info['url']\n                dist.digest = self._get_digest(info)\n                dist.locator = self\n                result[v] = dist\n                for info in urls:\n                    url = info['url']\n                    digest = self._get_digest(info)\n                    result['urls'].setdefault(v, set()).add(url)\n                    result['digests'][url] = digest\n        return result\n\nclass PyPIJSONLocator(Locator):\n    \"\"\"\n    This locator uses PyPI's JSON interface. It's very limited in functionality\n    and probably not worth using.\n    \"\"\"\n    def __init__(self, url, **kwargs):\n        super(PyPIJSONLocator, self).__init__(**kwargs)\n        self.base_url = ensure_slash(url)\n\n    def get_distribution_names(self):\n        \"\"\"\n        Return all the distribution names known to this locator.\n        \"\"\"\n        raise NotImplementedError('Not available from this locator')\n\n    def _get_project(self, name):\n        result = {'urls': {}, 'digests': {}}\n        url = urljoin(self.base_url, '%s/json' % quote(name))\n        try:\n            resp = self.opener.open(url)\n            data = resp.read().decode() # for now\n            d = json.loads(data)\n            md = Metadata(scheme=self.scheme)\n            data = d['info']\n            md.name = data['name']\n            md.version = data['version']\n            md.license = data.get('license')\n            md.keywords = data.get('keywords', [])\n            md.summary = data.get('summary')\n            dist = Distribution(md)\n            dist.locator = self\n            urls = d['urls']\n            result[md.version] = dist\n            for info in d['urls']:\n                url = info['url']\n                dist.download_urls.add(url)\n                dist.digests[url] = self._get_digest(info)\n                result['urls'].setdefault(md.version, set()).add(url)\n                result['digests'][url] = self._get_digest(info)\n            # Now get other releases\n            for version, infos in d['releases'].items():\n                if version == md.version:\n                    continue    # already done\n                omd = Metadata(scheme=self.scheme)\n                omd.name = md.name\n                omd.version = version\n                odist = Distribution(omd)\n                odist.locator = self\n                result[version] = odist\n                for info in infos:\n                    url = info['url']\n                    odist.download_urls.add(url)\n                    odist.digests[url] = self._get_digest(info)\n                    result['urls'].setdefault(version, set()).add(url)\n                    result['digests'][url] = self._get_digest(info)\n#            for info in urls:\n#                md.source_url = info['url']\n#                dist.digest = self._get_digest(info)\n#                dist.locator = self\n#                for info in urls:\n#                    url = info['url']\n#                    result['urls'].setdefault(md.version, set()).add(url)\n#                    result['digests'][url] = self._get_digest(info)\n        except Exception as e:\n            self.errors.put(text_type(e))\n            logger.exception('JSON fetch failed: %s', e)\n        return result\n\n\nclass Page(object):\n    \"\"\"\n    This class represents a scraped HTML page.\n    \"\"\"\n    # The following slightly hairy-looking regex just looks for the contents of\n    # an anchor link, which has an attribute \"href\" either immediately preceded\n    # or immediately followed by a \"rel\" attribute. The attribute values can be\n    # declared with double quotes, single quotes or no quotes - which leads to\n    # the length of the expression.\n    _href = re.compile(\"\"\"\n(rel\\\\s*=\\\\s*(?:\"(?P<rel1>[^\"]*)\"|'(?P<rel2>[^']*)'|(?P<rel3>[^>\\\\s\\n]*))\\\\s+)?\nhref\\\\s*=\\\\s*(?:\"(?P<url1>[^\"]*)\"|'(?P<url2>[^']*)'|(?P<url3>[^>\\\\s\\n]*))\n(\\\\s+rel\\\\s*=\\\\s*(?:\"(?P<rel4>[^\"]*)\"|'(?P<rel5>[^']*)'|(?P<rel6>[^>\\\\s\\n]*)))?\n\"\"\", re.I | re.S | re.X)\n    _base = re.compile(r\"\"\"<base\\s+href\\s*=\\s*['\"]?([^'\">]+)\"\"\", re.I | re.S)\n\n    def __init__(self, data, url):\n        \"\"\"\n        Initialise an instance with the Unicode page contents and the URL they\n        came from.\n        \"\"\"\n        self.data = data\n        self.base_url = self.url = url\n        m = self._base.search(self.data)\n        if m:\n            self.base_url = m.group(1)\n\n    _clean_re = re.compile(r'[^a-z0-9$&+,/:;=?@.#%_\\\\|-]', re.I)\n\n    @cached_property\n    def links(self):\n        \"\"\"\n        Return the URLs of all the links on a page together with information\n        about their \"rel\" attribute, for determining which ones to treat as\n        downloads and which ones to queue for further scraping.\n        \"\"\"\n        def clean(url):\n            \"Tidy up an URL.\"\n            scheme, netloc, path, params, query, frag = urlparse(url)\n            return urlunparse((scheme, netloc, quote(path),\n                               params, query, frag))\n\n        result = set()\n        for match in self._href.finditer(self.data):\n            d = match.groupdict('')\n            rel = (d['rel1'] or d['rel2'] or d['rel3'] or\n                   d['rel4'] or d['rel5'] or d['rel6'])\n            url = d['url1'] or d['url2'] or d['url3']\n            url = urljoin(self.base_url, url)\n            url = unescape(url)\n            url = self._clean_re.sub(lambda m: '%%%2x' % ord(m.group(0)), url)\n            result.add((url, rel))\n        # We sort the result, hoping to bring the most recent versions\n        # to the front\n        result = sorted(result, key=lambda t: t[0], reverse=True)\n        return result\n\n\nclass SimpleScrapingLocator(Locator):\n    \"\"\"\n    A locator which scrapes HTML pages to locate downloads for a distribution.\n    This runs multiple threads to do the I/O; performance is at least as good\n    as pip's PackageFinder, which works in an analogous fashion.\n    \"\"\"\n\n    # These are used to deal with various Content-Encoding schemes.\n    decoders = {\n        'deflate': zlib.decompress,\n        'gzip': lambda b: gzip.GzipFile(fileobj=BytesIO(b)).read(),\n        'none': lambda b: b,\n    }\n\n    def __init__(self, url, timeout=None, num_workers=10, **kwargs):\n        \"\"\"\n        Initialise an instance.\n        :param url: The root URL to use for scraping.\n        :param timeout: The timeout, in seconds, to be applied to requests.\n                        This defaults to ``None`` (no timeout specified).\n        :param num_workers: The number of worker threads you want to do I/O,\n                            This defaults to 10.\n        :param kwargs: Passed to the superclass.\n        \"\"\"\n        super(SimpleScrapingLocator, self).__init__(**kwargs)\n        self.base_url = ensure_slash(url)\n        self.timeout = timeout\n        self._page_cache = {}\n        self._seen = set()\n        self._to_fetch = queue.Queue()\n        self._bad_hosts = set()\n        self.skip_externals = False\n        self.num_workers = num_workers\n        self._lock = threading.RLock()\n        # See issue #45: we need to be resilient when the locator is used\n        # in a thread, e.g. with concurrent.futures. We can't use self._lock\n        # as it is for coordinating our internal threads - the ones created\n        # in _prepare_threads.\n        self._gplock = threading.RLock()\n        self.platform_check = False  # See issue #112\n\n    def _prepare_threads(self):\n        \"\"\"\n        Threads are created only when get_project is called, and terminate\n        before it returns. They are there primarily to parallelise I/O (i.e.\n        fetching web pages).\n        \"\"\"\n        self._threads = []\n        for i in range(self.num_workers):\n            t = threading.Thread(target=self._fetch)\n            t.daemon = True\n            t.start()\n            self._threads.append(t)\n\n    def _wait_threads(self):\n        \"\"\"\n        Tell all the threads to terminate (by sending a sentinel value) and\n        wait for them to do so.\n        \"\"\"\n        # Note that you need two loops, since you can't say which\n        # thread will get each sentinel\n        for t in self._threads:\n            self._to_fetch.put(None)    # sentinel\n        for t in self._threads:\n            t.join()\n        self._threads = []\n\n    def _get_project(self, name):\n        result = {'urls': {}, 'digests': {}}\n        with self._gplock:\n            self.result = result\n            self.project_name = name\n            url = urljoin(self.base_url, '%s/' % quote(name))\n            self._seen.clear()\n            self._page_cache.clear()\n            self._prepare_threads()\n            try:\n                logger.debug('Queueing %s', url)\n                self._to_fetch.put(url)\n                self._to_fetch.join()\n            finally:\n                self._wait_threads()\n            del self.result\n        return result\n\n    platform_dependent = re.compile(r'\\b(linux_(i\\d86|x86_64|arm\\w+)|'\n                                    r'win(32|_amd64)|macosx_?\\d+)\\b', re.I)\n\n    def _is_platform_dependent(self, url):\n        \"\"\"\n        Does an URL refer to a platform-specific download?\n        \"\"\"\n        return self.platform_dependent.search(url)\n\n    def _process_download(self, url):\n        \"\"\"\n        See if an URL is a suitable download for a project.\n\n        If it is, register information in the result dictionary (for\n        _get_project) about the specific version it's for.\n\n        Note that the return value isn't actually used other than as a boolean\n        value.\n        \"\"\"\n        if self.platform_check and self._is_platform_dependent(url):\n            info = None\n        else:\n            info = self.convert_url_to_download_info(url, self.project_name)\n        logger.debug('process_download: %s -> %s', url, info)\n        if info:\n            with self._lock:    # needed because self.result is shared\n                self._update_version_data(self.result, info)\n        return info\n\n    def _should_queue(self, link, referrer, rel):\n        \"\"\"\n        Determine whether a link URL from a referring page and with a\n        particular \"rel\" attribute should be queued for scraping.\n        \"\"\"\n        scheme, netloc, path, _, _, _ = urlparse(link)\n        if path.endswith(self.source_extensions + self.binary_extensions +\n                         self.excluded_extensions):\n            result = False\n        elif self.skip_externals and not link.startswith(self.base_url):\n            result = False\n        elif not referrer.startswith(self.base_url):\n            result = False\n        elif rel not in ('homepage', 'download'):\n            result = False\n        elif scheme not in ('http', 'https', 'ftp'):\n            result = False\n        elif self._is_platform_dependent(link):\n            result = False\n        else:\n            host = netloc.split(':', 1)[0]\n            if host.lower() == 'localhost':\n                result = False\n            else:\n                result = True\n        logger.debug('should_queue: %s (%s) from %s -> %s', link, rel,\n                     referrer, result)\n        return result\n\n    def _fetch(self):\n        \"\"\"\n        Get a URL to fetch from the work queue, get the HTML page, examine its\n        links for download candidates and candidates for further scraping.\n\n        This is a handy method to run in a thread.\n        \"\"\"\n        while True:\n            url = self._to_fetch.get()\n            try:\n                if url:\n                    page = self.get_page(url)\n                    if page is None:    # e.g. after an error\n                        continue\n                    for link, rel in page.links:\n                        if link not in self._seen:\n                            try:\n                                self._seen.add(link)\n                                if (not self._process_download(link) and\n                                    self._should_queue(link, url, rel)):\n                                    logger.debug('Queueing %s from %s', link, url)\n                                    self._to_fetch.put(link)\n                            except MetadataInvalidError:  # e.g. invalid versions\n                                pass\n            except Exception as e:  # pragma: no cover\n                self.errors.put(text_type(e))\n            finally:\n                # always do this, to avoid hangs :-)\n                self._to_fetch.task_done()\n            if not url:\n                #logger.debug('Sentinel seen, quitting.')\n                break\n\n    def get_page(self, url):\n        \"\"\"\n        Get the HTML for an URL, possibly from an in-memory cache.\n\n        XXX TODO Note: this cache is never actually cleared. It's assumed that\n        the data won't get stale over the lifetime of a locator instance (not\n        necessarily true for the default_locator).\n        \"\"\"\n        # http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api\n        scheme, netloc, path, _, _, _ = urlparse(url)\n        if scheme == 'file' and os.path.isdir(url2pathname(path)):\n            url = urljoin(ensure_slash(url), 'index.html')\n\n        if url in self._page_cache:\n            result = self._page_cache[url]\n            logger.debug('Returning %s from cache: %s', url, result)\n        else:\n            host = netloc.split(':', 1)[0]\n            result = None\n            if host in self._bad_hosts:\n                logger.debug('Skipping %s due to bad host %s', url, host)\n            else:\n                req = Request(url, headers={'Accept-encoding': 'identity'})\n                try:\n                    logger.debug('Fetching %s', url)\n                    resp = self.opener.open(req, timeout=self.timeout)\n                    logger.debug('Fetched %s', url)\n                    headers = resp.info()\n                    content_type = headers.get('Content-Type', '')\n                    if HTML_CONTENT_TYPE.match(content_type):\n                        final_url = resp.geturl()\n                        data = resp.read()\n                        encoding = headers.get('Content-Encoding')\n                        if encoding:\n                            decoder = self.decoders[encoding]   # fail if not found\n                            data = decoder(data)\n                        encoding = 'utf-8'\n                        m = CHARSET.search(content_type)\n                        if m:\n                            encoding = m.group(1)\n                        try:\n                            data = data.decode(encoding)\n                        except UnicodeError:  # pragma: no cover\n                            data = data.decode('latin-1')    # fallback\n                        result = Page(data, final_url)\n                        self._page_cache[final_url] = result\n                except HTTPError as e:\n                    if e.code != 404:\n                        logger.exception('Fetch failed: %s: %s', url, e)\n                except URLError as e:  # pragma: no cover\n                    logger.exception('Fetch failed: %s: %s', url, e)\n                    with self._lock:\n                        self._bad_hosts.add(host)\n                except Exception as e:  # pragma: no cover\n                    logger.exception('Fetch failed: %s: %s', url, e)\n                finally:\n                    self._page_cache[url] = result   # even if None (failure)\n        return result\n\n    _distname_re = re.compile('<a href=[^>]*>([^<]+)<')\n\n    def get_distribution_names(self):\n        \"\"\"\n        Return all the distribution names known to this locator.\n        \"\"\"\n        result = set()\n        page = self.get_page(self.base_url)\n        if not page:\n            raise DistlibException('Unable to get %s' % self.base_url)\n        for match in self._distname_re.finditer(page.data):\n            result.add(match.group(1))\n        return result\n\nclass DirectoryLocator(Locator):\n    \"\"\"\n    This class locates distributions in a directory tree.\n    \"\"\"\n\n    def __init__(self, path, **kwargs):\n        \"\"\"\n        Initialise an instance.\n        :param path: The root of the directory tree to search.\n        :param kwargs: Passed to the superclass constructor,\n                       except for:\n                       * recursive - if True (the default), subdirectories are\n                         recursed into. If False, only the top-level directory\n                         is searched,\n        \"\"\"\n        self.recursive = kwargs.pop('recursive', True)\n        super(DirectoryLocator, self).__init__(**kwargs)\n        path = os.path.abspath(path)\n        if not os.path.isdir(path):  # pragma: no cover\n            raise DistlibException('Not a directory: %r' % path)\n        self.base_dir = path\n\n    def should_include(self, filename, parent):\n        \"\"\"\n        Should a filename be considered as a candidate for a distribution\n        archive? As well as the filename, the directory which contains it\n        is provided, though not used by the current implementation.\n        \"\"\"\n        return filename.endswith(self.downloadable_extensions)\n\n    def _get_project(self, name):\n        result = {'urls': {}, 'digests': {}}\n        for root, dirs, files in os.walk(self.base_dir):\n            for fn in files:\n                if self.should_include(fn, root):\n                    fn = os.path.join(root, fn)\n                    url = urlunparse(('file', '',\n                                      pathname2url(os.path.abspath(fn)),\n                                      '', '', ''))\n                    info = self.convert_url_to_download_info(url, name)\n                    if info:\n                        self._update_version_data(result, info)\n            if not self.recursive:\n                break\n        return result\n\n    def get_distribution_names(self):\n        \"\"\"\n        Return all the distribution names known to this locator.\n        \"\"\"\n        result = set()\n        for root, dirs, files in os.walk(self.base_dir):\n            for fn in files:\n                if self.should_include(fn, root):\n                    fn = os.path.join(root, fn)\n                    url = urlunparse(('file', '',\n                                      pathname2url(os.path.abspath(fn)),\n                                      '', '', ''))\n                    info = self.convert_url_to_download_info(url, None)\n                    if info:\n                        result.add(info['name'])\n            if not self.recursive:\n                break\n        return result\n\nclass JSONLocator(Locator):\n    \"\"\"\n    This locator uses special extended metadata (not available on PyPI) and is\n    the basis of performant dependency resolution in distlib. Other locators\n    require archive downloads before dependencies can be determined! As you\n    might imagine, that can be slow.\n    \"\"\"\n    def get_distribution_names(self):\n        \"\"\"\n        Return all the distribution names known to this locator.\n        \"\"\"\n        raise NotImplementedError('Not available from this locator')\n\n    def _get_project(self, name):\n        result = {'urls': {}, 'digests': {}}\n        data = get_project_data(name)\n        if data:\n            for info in data.get('files', []):\n                if info['ptype'] != 'sdist' or info['pyversion'] != 'source':\n                    continue\n                # We don't store summary in project metadata as it makes\n                # the data bigger for no benefit during dependency\n                # resolution\n                dist = make_dist(data['name'], info['version'],\n                                 summary=data.get('summary',\n                                                  'Placeholder for summary'),\n                                 scheme=self.scheme)\n                md = dist.metadata\n                md.source_url = info['url']\n                # TODO SHA256 digest\n                if 'digest' in info and info['digest']:\n                    dist.digest = ('md5', info['digest'])\n                md.dependencies = info.get('requirements', {})\n                dist.exports = info.get('exports', {})\n                result[dist.version] = dist\n                result['urls'].setdefault(dist.version, set()).add(info['url'])\n        return result\n\nclass DistPathLocator(Locator):\n    \"\"\"\n    This locator finds installed distributions in a path. It can be useful for\n    adding to an :class:`AggregatingLocator`.\n    \"\"\"\n    def __init__(self, distpath, **kwargs):\n        \"\"\"\n        Initialise an instance.\n\n        :param distpath: A :class:`DistributionPath` instance to search.\n        \"\"\"\n        super(DistPathLocator, self).__init__(**kwargs)\n        assert isinstance(distpath, DistributionPath)\n        self.distpath = distpath\n\n    def _get_project(self, name):\n        dist = self.distpath.get_distribution(name)\n        if dist is None:\n            result = {'urls': {}, 'digests': {}}\n        else:\n            result = {\n                dist.version: dist,\n                'urls': {dist.version: set([dist.source_url])},\n                'digests': {dist.version: set([None])}\n            }\n        return result\n\n\nclass AggregatingLocator(Locator):\n    \"\"\"\n    This class allows you to chain and/or merge a list of locators.\n    \"\"\"\n    def __init__(self, *locators, **kwargs):\n        \"\"\"\n        Initialise an instance.\n\n        :param locators: The list of locators to search.\n        :param kwargs: Passed to the superclass constructor,\n                       except for:\n                       * merge - if False (the default), the first successful\n                         search from any of the locators is returned. If True,\n                         the results from all locators are merged (this can be\n                         slow).\n        \"\"\"\n        self.merge = kwargs.pop('merge', False)\n        self.locators = locators\n        super(AggregatingLocator, self).__init__(**kwargs)\n\n    def clear_cache(self):\n        super(AggregatingLocator, self).clear_cache()\n        for locator in self.locators:\n            locator.clear_cache()\n\n    def _set_scheme(self, value):\n        self._scheme = value\n        for locator in self.locators:\n            locator.scheme = value\n\n    scheme = property(Locator.scheme.fget, _set_scheme)\n\n    def _get_project(self, name):\n        result = {}\n        for locator in self.locators:\n            d = locator.get_project(name)\n            if d:\n                if self.merge:\n                    files = result.get('urls', {})\n                    digests = result.get('digests', {})\n                    # next line could overwrite result['urls'], result['digests']\n                    result.update(d)\n                    df = result.get('urls')\n                    if files and df:\n                        for k, v in files.items():\n                            if k in df:\n                                df[k] |= v\n                            else:\n                                df[k] = v\n                    dd = result.get('digests')\n                    if digests and dd:\n                        dd.update(digests)\n                else:\n                    # See issue #18. If any dists are found and we're looking\n                    # for specific constraints, we only return something if\n                    # a match is found. For example, if a DirectoryLocator\n                    # returns just foo (1.0) while we're looking for\n                    # foo (>= 2.0), we'll pretend there was nothing there so\n                    # that subsequent locators can be queried. Otherwise we\n                    # would just return foo (1.0) which would then lead to a\n                    # failure to find foo (>= 2.0), because other locators\n                    # weren't searched. Note that this only matters when\n                    # merge=False.\n                    if self.matcher is None:\n                        found = True\n                    else:\n                        found = False\n                        for k in d:\n                            if self.matcher.match(k):\n                                found = True\n                                break\n                    if found:\n                        result = d\n                        break\n        return result\n\n    def get_distribution_names(self):\n        \"\"\"\n        Return all the distribution names known to this locator.\n        \"\"\"\n        result = set()\n        for locator in self.locators:\n            try:\n                result |= locator.get_distribution_names()\n            except NotImplementedError:\n                pass\n        return result\n\n\n# We use a legacy scheme simply because most of the dists on PyPI use legacy\n# versions which don't conform to PEP 440.\ndefault_locator = AggregatingLocator(\n                    # JSONLocator(), # don't use as PEP 426 is withdrawn\n                    SimpleScrapingLocator('https://pypi.org/simple/',\n                                          timeout=3.0),\n                    scheme='legacy')\n\nlocate = default_locator.locate\n\n\nclass DependencyFinder(object):\n    \"\"\"\n    Locate dependencies for distributions.\n    \"\"\"\n\n    def __init__(self, locator=None):\n        \"\"\"\n        Initialise an instance, using the specified locator\n        to locate distributions.\n        \"\"\"\n        self.locator = locator or default_locator\n        self.scheme = get_scheme(self.locator.scheme)\n\n    def add_distribution(self, dist):\n        \"\"\"\n        Add a distribution to the finder. This will update internal information\n        about who provides what.\n        :param dist: The distribution to add.\n        \"\"\"\n        logger.debug('adding distribution %s', dist)\n        name = dist.key\n        self.dists_by_name[name] = dist\n        self.dists[(name, dist.version)] = dist\n        for p in dist.provides:\n            name, version = parse_name_and_version(p)\n            logger.debug('Add to provided: %s, %s, %s', name, version, dist)\n            self.provided.setdefault(name, set()).add((version, dist))\n\n    def remove_distribution(self, dist):\n        \"\"\"\n        Remove a distribution from the finder. This will update internal\n        information about who provides what.\n        :param dist: The distribution to remove.\n        \"\"\"\n        logger.debug('removing distribution %s', dist)\n        name = dist.key\n        del self.dists_by_name[name]\n        del self.dists[(name, dist.version)]\n        for p in dist.provides:\n            name, version = parse_name_and_version(p)\n            logger.debug('Remove from provided: %s, %s, %s', name, version, dist)\n            s = self.provided[name]\n            s.remove((version, dist))\n            if not s:\n                del self.provided[name]\n\n    def get_matcher(self, reqt):\n        \"\"\"\n        Get a version matcher for a requirement.\n        :param reqt: The requirement\n        :type reqt: str\n        :return: A version matcher (an instance of\n                 :class:`distlib.version.Matcher`).\n        \"\"\"\n        try:\n            matcher = self.scheme.matcher(reqt)\n        except UnsupportedVersionError:  # pragma: no cover\n            # XXX compat-mode if cannot read the version\n            name = reqt.split()[0]\n            matcher = self.scheme.matcher(name)\n        return matcher\n\n    def find_providers(self, reqt):\n        \"\"\"\n        Find the distributions which can fulfill a requirement.\n\n        :param reqt: The requirement.\n         :type reqt: str\n        :return: A set of distribution which can fulfill the requirement.\n        \"\"\"\n        matcher = self.get_matcher(reqt)\n        name = matcher.key   # case-insensitive\n        result = set()\n        provided = self.provided\n        if name in provided:\n            for version, provider in provided[name]:\n                try:\n                    match = matcher.match(version)\n                except UnsupportedVersionError:\n                    match = False\n\n                if match:\n                    result.add(provider)\n                    break\n        return result\n\n    def try_to_replace(self, provider, other, problems):\n        \"\"\"\n        Attempt to replace one provider with another. This is typically used\n        when resolving dependencies from multiple sources, e.g. A requires\n        (B >= 1.0) while C requires (B >= 1.1).\n\n        For successful replacement, ``provider`` must meet all the requirements\n        which ``other`` fulfills.\n\n        :param provider: The provider we are trying to replace with.\n        :param other: The provider we're trying to replace.\n        :param problems: If False is returned, this will contain what\n                         problems prevented replacement. This is currently\n                         a tuple of the literal string 'cantreplace',\n                         ``provider``, ``other``  and the set of requirements\n                         that ``provider`` couldn't fulfill.\n        :return: True if we can replace ``other`` with ``provider``, else\n                 False.\n        \"\"\"\n        rlist = self.reqts[other]\n        unmatched = set()\n        for s in rlist:\n            matcher = self.get_matcher(s)\n            if not matcher.match(provider.version):\n                unmatched.add(s)\n        if unmatched:\n            # can't replace other with provider\n            problems.add(('cantreplace', provider, other,\n                          frozenset(unmatched)))\n            result = False\n        else:\n            # can replace other with provider\n            self.remove_distribution(other)\n            del self.reqts[other]\n            for s in rlist:\n                self.reqts.setdefault(provider, set()).add(s)\n            self.add_distribution(provider)\n            result = True\n        return result\n\n    def find(self, requirement, meta_extras=None, prereleases=False):\n        \"\"\"\n        Find a distribution and all distributions it depends on.\n\n        :param requirement: The requirement specifying the distribution to\n                            find, or a Distribution instance.\n        :param meta_extras: A list of meta extras such as :test:, :build: and\n                            so on.\n        :param prereleases: If ``True``, allow pre-release versions to be\n                            returned - otherwise, don't return prereleases\n                            unless they're all that's available.\n\n        Return a set of :class:`Distribution` instances and a set of\n        problems.\n\n        The distributions returned should be such that they have the\n        :attr:`required` attribute set to ``True`` if they were\n        from the ``requirement`` passed to ``find()``, and they have the\n        :attr:`build_time_dependency` attribute set to ``True`` unless they\n        are post-installation dependencies of the ``requirement``.\n\n        The problems should be a tuple consisting of the string\n        ``'unsatisfied'`` and the requirement which couldn't be satisfied\n        by any distribution known to the locator.\n        \"\"\"\n\n        self.provided = {}\n        self.dists = {}\n        self.dists_by_name = {}\n        self.reqts = {}\n\n        meta_extras = set(meta_extras or [])\n        if ':*:' in meta_extras:\n            meta_extras.remove(':*:')\n            # :meta: and :run: are implicitly included\n            meta_extras |= set([':test:', ':build:', ':dev:'])\n\n        if isinstance(requirement, Distribution):\n            dist = odist = requirement\n            logger.debug('passed %s as requirement', odist)\n        else:\n            dist = odist = self.locator.locate(requirement,\n                                               prereleases=prereleases)\n            if dist is None:\n                raise DistlibException('Unable to locate %r' % requirement)\n            logger.debug('located %s', odist)\n        dist.requested = True\n        problems = set()\n        todo = set([dist])\n        install_dists = set([odist])\n        while todo:\n            dist = todo.pop()\n            name = dist.key     # case-insensitive\n            if name not in self.dists_by_name:\n                self.add_distribution(dist)\n            else:\n                #import pdb; pdb.set_trace()\n                other = self.dists_by_name[name]\n                if other != dist:\n                    self.try_to_replace(dist, other, problems)\n\n            ireqts = dist.run_requires | dist.meta_requires\n            sreqts = dist.build_requires\n            ereqts = set()\n            if meta_extras and dist in install_dists:\n                for key in ('test', 'build', 'dev'):\n                    e = ':%s:' % key\n                    if e in meta_extras:\n                        ereqts |= getattr(dist, '%s_requires' % key)\n            all_reqts = ireqts | sreqts | ereqts\n            for r in all_reqts:\n                providers = self.find_providers(r)\n                if not providers:\n                    logger.debug('No providers found for %r', r)\n                    provider = self.locator.locate(r, prereleases=prereleases)\n                    # If no provider is found and we didn't consider\n                    # prereleases, consider them now.\n                    if provider is None and not prereleases:\n                        provider = self.locator.locate(r, prereleases=True)\n                    if provider is None:\n                        logger.debug('Cannot satisfy %r', r)\n                        problems.add(('unsatisfied', r))\n                    else:\n                        n, v = provider.key, provider.version\n                        if (n, v) not in self.dists:\n                            todo.add(provider)\n                        providers.add(provider)\n                        if r in ireqts and dist in install_dists:\n                            install_dists.add(provider)\n                            logger.debug('Adding %s to install_dists',\n                                         provider.name_and_version)\n                for p in providers:\n                    name = p.key\n                    if name not in self.dists_by_name:\n                        self.reqts.setdefault(p, set()).add(r)\n                    else:\n                        other = self.dists_by_name[name]\n                        if other != p:\n                            # see if other can be replaced by p\n                            self.try_to_replace(p, other, problems)\n\n        dists = set(self.dists.values())\n        for dist in dists:\n            dist.build_time_dependency = dist not in install_dists\n            if dist.build_time_dependency:\n                logger.debug('%s is a build-time dependency only.',\n                             dist.name_and_version)\n        logger.debug('find done for %s', odist)\n        return dists, problems\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distlib/manifest.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2012-2013 Python Software Foundation.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\n\"\"\"\nClass representing the list of files in a distribution.\n\nEquivalent to distutils.filelist, but fixes some problems.\n\"\"\"\nimport fnmatch\nimport logging\nimport os\nimport re\nimport sys\n\nfrom . import DistlibException\nfrom .compat import fsdecode\nfrom .util import convert_path\n\n\n__all__ = ['Manifest']\n\nlogger = logging.getLogger(__name__)\n\n# a \\ followed by some spaces + EOL\n_COLLAPSE_PATTERN = re.compile('\\\\\\\\w*\\n', re.M)\n_COMMENTED_LINE = re.compile('#.*?(?=\\n)|\\n(?=$)', re.M | re.S)\n\n#\n# Due to the different results returned by fnmatch.translate, we need\n# to do slightly different processing for Python 2.7 and 3.2 ... this needed\n# to be brought in for Python 3.6 onwards.\n#\n_PYTHON_VERSION = sys.version_info[:2]\n\nclass Manifest(object):\n    \"\"\"A list of files built by on exploring the filesystem and filtered by\n    applying various patterns to what we find there.\n    \"\"\"\n\n    def __init__(self, base=None):\n        \"\"\"\n        Initialise an instance.\n\n        :param base: The base directory to explore under.\n        \"\"\"\n        self.base = os.path.abspath(os.path.normpath(base or os.getcwd()))\n        self.prefix = self.base + os.sep\n        self.allfiles = None\n        self.files = set()\n\n    #\n    # Public API\n    #\n\n    def findall(self):\n        \"\"\"Find all files under the base and set ``allfiles`` to the absolute\n        pathnames of files found.\n        \"\"\"\n        from stat import S_ISREG, S_ISDIR, S_ISLNK\n\n        self.allfiles = allfiles = []\n        root = self.base\n        stack = [root]\n        pop = stack.pop\n        push = stack.append\n\n        while stack:\n            root = pop()\n            names = os.listdir(root)\n\n            for name in names:\n                fullname = os.path.join(root, name)\n\n                # Avoid excess stat calls -- just one will do, thank you!\n                stat = os.stat(fullname)\n                mode = stat.st_mode\n                if S_ISREG(mode):\n                    allfiles.append(fsdecode(fullname))\n                elif S_ISDIR(mode) and not S_ISLNK(mode):\n                    push(fullname)\n\n    def add(self, item):\n        \"\"\"\n        Add a file to the manifest.\n\n        :param item: The pathname to add. This can be relative to the base.\n        \"\"\"\n        if not item.startswith(self.prefix):\n            item = os.path.join(self.base, item)\n        self.files.add(os.path.normpath(item))\n\n    def add_many(self, items):\n        \"\"\"\n        Add a list of files to the manifest.\n\n        :param items: The pathnames to add. These can be relative to the base.\n        \"\"\"\n        for item in items:\n            self.add(item)\n\n    def sorted(self, wantdirs=False):\n        \"\"\"\n        Return sorted files in directory order\n        \"\"\"\n\n        def add_dir(dirs, d):\n            dirs.add(d)\n            logger.debug('add_dir added %s', d)\n            if d != self.base:\n                parent, _ = os.path.split(d)\n                assert parent not in ('', '/')\n                add_dir(dirs, parent)\n\n        result = set(self.files)    # make a copy!\n        if wantdirs:\n            dirs = set()\n            for f in result:\n                add_dir(dirs, os.path.dirname(f))\n            result |= dirs\n        return [os.path.join(*path_tuple) for path_tuple in\n                sorted(os.path.split(path) for path in result)]\n\n    def clear(self):\n        \"\"\"Clear all collected files.\"\"\"\n        self.files = set()\n        self.allfiles = []\n\n    def process_directive(self, directive):\n        \"\"\"\n        Process a directive which either adds some files from ``allfiles`` to\n        ``files``, or removes some files from ``files``.\n\n        :param directive: The directive to process. This should be in a format\n                     compatible with distutils ``MANIFEST.in`` files:\n\n                     http://docs.python.org/distutils/sourcedist.html#commands\n        \"\"\"\n        # Parse the line: split it up, make sure the right number of words\n        # is there, and return the relevant words.  'action' is always\n        # defined: it's the first word of the line.  Which of the other\n        # three are defined depends on the action; it'll be either\n        # patterns, (dir and patterns), or (dirpattern).\n        action, patterns, thedir, dirpattern = self._parse_directive(directive)\n\n        # OK, now we know that the action is valid and we have the\n        # right number of words on the line for that action -- so we\n        # can proceed with minimal error-checking.\n        if action == 'include':\n            for pattern in patterns:\n                if not self._include_pattern(pattern, anchor=True):\n                    logger.warning('no files found matching %r', pattern)\n\n        elif action == 'exclude':\n            for pattern in patterns:\n                found = self._exclude_pattern(pattern, anchor=True)\n                #if not found:\n                #    logger.warning('no previously-included files '\n                #                   'found matching %r', pattern)\n\n        elif action == 'global-include':\n            for pattern in patterns:\n                if not self._include_pattern(pattern, anchor=False):\n                    logger.warning('no files found matching %r '\n                                   'anywhere in distribution', pattern)\n\n        elif action == 'global-exclude':\n            for pattern in patterns:\n                found = self._exclude_pattern(pattern, anchor=False)\n                #if not found:\n                #    logger.warning('no previously-included files '\n                #                   'matching %r found anywhere in '\n                #                   'distribution', pattern)\n\n        elif action == 'recursive-include':\n            for pattern in patterns:\n                if not self._include_pattern(pattern, prefix=thedir):\n                    logger.warning('no files found matching %r '\n                                   'under directory %r', pattern, thedir)\n\n        elif action == 'recursive-exclude':\n            for pattern in patterns:\n                found = self._exclude_pattern(pattern, prefix=thedir)\n                #if not found:\n                #    logger.warning('no previously-included files '\n                #                   'matching %r found under directory %r',\n                #                   pattern, thedir)\n\n        elif action == 'graft':\n            if not self._include_pattern(None, prefix=dirpattern):\n                logger.warning('no directories found matching %r',\n                               dirpattern)\n\n        elif action == 'prune':\n            if not self._exclude_pattern(None, prefix=dirpattern):\n                logger.warning('no previously-included directories found '\n                               'matching %r', dirpattern)\n        else:   # pragma: no cover\n            # This should never happen, as it should be caught in\n            # _parse_template_line\n            raise DistlibException(\n                'invalid action %r' % action)\n\n    #\n    # Private API\n    #\n\n    def _parse_directive(self, directive):\n        \"\"\"\n        Validate a directive.\n        :param directive: The directive to validate.\n        :return: A tuple of action, patterns, thedir, dir_patterns\n        \"\"\"\n        words = directive.split()\n        if len(words) == 1 and words[0] not in ('include', 'exclude',\n                                                'global-include',\n                                                'global-exclude',\n                                                'recursive-include',\n                                                'recursive-exclude',\n                                                'graft', 'prune'):\n            # no action given, let's use the default 'include'\n            words.insert(0, 'include')\n\n        action = words[0]\n        patterns = thedir = dir_pattern = None\n\n        if action in ('include', 'exclude',\n                      'global-include', 'global-exclude'):\n            if len(words) < 2:\n                raise DistlibException(\n                    '%r expects <pattern1> <pattern2> ...' % action)\n\n            patterns = [convert_path(word) for word in words[1:]]\n\n        elif action in ('recursive-include', 'recursive-exclude'):\n            if len(words) < 3:\n                raise DistlibException(\n                    '%r expects <dir> <pattern1> <pattern2> ...' % action)\n\n            thedir = convert_path(words[1])\n            patterns = [convert_path(word) for word in words[2:]]\n\n        elif action in ('graft', 'prune'):\n            if len(words) != 2:\n                raise DistlibException(\n                    '%r expects a single <dir_pattern>' % action)\n\n            dir_pattern = convert_path(words[1])\n\n        else:\n            raise DistlibException('unknown action %r' % action)\n\n        return action, patterns, thedir, dir_pattern\n\n    def _include_pattern(self, pattern, anchor=True, prefix=None,\n                         is_regex=False):\n        \"\"\"Select strings (presumably filenames) from 'self.files' that\n        match 'pattern', a Unix-style wildcard (glob) pattern.\n\n        Patterns are not quite the same as implemented by the 'fnmatch'\n        module: '*' and '?'  match non-special characters, where \"special\"\n        is platform-dependent: slash on Unix; colon, slash, and backslash on\n        DOS/Windows; and colon on Mac OS.\n\n        If 'anchor' is true (the default), then the pattern match is more\n        stringent: \"*.py\" will match \"foo.py\" but not \"foo/bar.py\".  If\n        'anchor' is false, both of these will match.\n\n        If 'prefix' is supplied, then only filenames starting with 'prefix'\n        (itself a pattern) and ending with 'pattern', with anything in between\n        them, will match.  'anchor' is ignored in this case.\n\n        If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and\n        'pattern' is assumed to be either a string containing a regex or a\n        regex object -- no translation is done, the regex is just compiled\n        and used as-is.\n\n        Selected strings will be added to self.files.\n\n        Return True if files are found.\n        \"\"\"\n        # XXX docstring lying about what the special chars are?\n        found = False\n        pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)\n\n        # delayed loading of allfiles list\n        if self.allfiles is None:\n            self.findall()\n\n        for name in self.allfiles:\n            if pattern_re.search(name):\n                self.files.add(name)\n                found = True\n        return found\n\n    def _exclude_pattern(self, pattern, anchor=True, prefix=None,\n                         is_regex=False):\n        \"\"\"Remove strings (presumably filenames) from 'files' that match\n        'pattern'.\n\n        Other parameters are the same as for 'include_pattern()', above.\n        The list 'self.files' is modified in place. Return True if files are\n        found.\n\n        This API is public to allow e.g. exclusion of SCM subdirs, e.g. when\n        packaging source distributions\n        \"\"\"\n        found = False\n        pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)\n        for f in list(self.files):\n            if pattern_re.search(f):\n                self.files.remove(f)\n                found = True\n        return found\n\n    def _translate_pattern(self, pattern, anchor=True, prefix=None,\n                           is_regex=False):\n        \"\"\"Translate a shell-like wildcard pattern to a compiled regular\n        expression.\n\n        Return the compiled regex.  If 'is_regex' true,\n        then 'pattern' is directly compiled to a regex (if it's a string)\n        or just returned as-is (assumes it's a regex object).\n        \"\"\"\n        if is_regex:\n            if isinstance(pattern, str):\n                return re.compile(pattern)\n            else:\n                return pattern\n\n        if _PYTHON_VERSION > (3, 2):\n            # ditch start and end characters\n            start, _, end = self._glob_to_re('_').partition('_')\n\n        if pattern:\n            pattern_re = self._glob_to_re(pattern)\n            if _PYTHON_VERSION > (3, 2):\n                assert pattern_re.startswith(start) and pattern_re.endswith(end)\n        else:\n            pattern_re = ''\n\n        base = re.escape(os.path.join(self.base, ''))\n        if prefix is not None:\n            # ditch end of pattern character\n            if _PYTHON_VERSION <= (3, 2):\n                empty_pattern = self._glob_to_re('')\n                prefix_re = self._glob_to_re(prefix)[:-len(empty_pattern)]\n            else:\n                prefix_re = self._glob_to_re(prefix)\n                assert prefix_re.startswith(start) and prefix_re.endswith(end)\n                prefix_re = prefix_re[len(start): len(prefix_re) - len(end)]\n            sep = os.sep\n            if os.sep == '\\\\':\n                sep = r'\\\\'\n            if _PYTHON_VERSION <= (3, 2):\n                pattern_re = '^' + base + sep.join((prefix_re,\n                                                    '.*' + pattern_re))\n            else:\n                pattern_re = pattern_re[len(start): len(pattern_re) - len(end)]\n                pattern_re = r'%s%s%s%s.*%s%s' % (start, base, prefix_re, sep,\n                                                  pattern_re, end)\n        else:  # no prefix -- respect anchor flag\n            if anchor:\n                if _PYTHON_VERSION <= (3, 2):\n                    pattern_re = '^' + base + pattern_re\n                else:\n                    pattern_re = r'%s%s%s' % (start, base, pattern_re[len(start):])\n\n        return re.compile(pattern_re)\n\n    def _glob_to_re(self, pattern):\n        \"\"\"Translate a shell-like glob pattern to a regular expression.\n\n        Return a string containing the regex.  Differs from\n        'fnmatch.translate()' in that '*' does not match \"special characters\"\n        (which are platform-specific).\n        \"\"\"\n        pattern_re = fnmatch.translate(pattern)\n\n        # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which\n        # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,\n        # and by extension they shouldn't match such \"special characters\" under\n        # any OS.  So change all non-escaped dots in the RE to match any\n        # character except the special characters (currently: just os.sep).\n        sep = os.sep\n        if os.sep == '\\\\':\n            # we're using a regex to manipulate a regex, so we need\n            # to escape the backslash twice\n            sep = r'\\\\\\\\'\n        escaped = r'\\1[^%s]' % sep\n        pattern_re = re.sub(r'((?<!\\\\)(\\\\\\\\)*)\\.', escaped, pattern_re)\n        return pattern_re\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distlib/markers.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2012-2017 Vinay Sajip.\n# Licensed to the Python Software Foundation under a contributor agreement.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\n\"\"\"\nParser for the environment markers micro-language defined in PEP 508.\n\"\"\"\n\n# Note: In PEP 345, the micro-language was Python compatible, so the ast\n# module could be used to parse it. However, PEP 508 introduced operators such\n# as ~= and === which aren't in Python, necessitating a different approach.\n\nimport os\nimport re\nimport sys\nimport platform\n\nfrom .compat import string_types\nfrom .util import in_venv, parse_marker\nfrom .version import NormalizedVersion as NV\n\n__all__ = ['interpret']\n\n_VERSION_PATTERN = re.compile(r'((\\d+(\\.\\d+)*\\w*)|\\'(\\d+(\\.\\d+)*\\w*)\\'|\\\"(\\d+(\\.\\d+)*\\w*)\\\")')\n\ndef _is_literal(o):\n    if not isinstance(o, string_types) or not o:\n        return False\n    return o[0] in '\\'\"'\n\ndef _get_versions(s):\n    result = []\n    for m in _VERSION_PATTERN.finditer(s):\n        result.append(NV(m.groups()[0]))\n    return set(result)\n\nclass Evaluator(object):\n    \"\"\"\n    This class is used to evaluate marker expessions.\n    \"\"\"\n\n    operations = {\n        '==': lambda x, y: x == y,\n        '===': lambda x, y: x == y,\n        '~=': lambda x, y: x == y or x > y,\n        '!=': lambda x, y: x != y,\n        '<':  lambda x, y: x < y,\n        '<=':  lambda x, y: x == y or x < y,\n        '>':  lambda x, y: x > y,\n        '>=':  lambda x, y: x == y or x > y,\n        'and': lambda x, y: x and y,\n        'or': lambda x, y: x or y,\n        'in': lambda x, y: x in y,\n        'not in': lambda x, y: x not in y,\n    }\n\n    def evaluate(self, expr, context):\n        \"\"\"\n        Evaluate a marker expression returned by the :func:`parse_requirement`\n        function in the specified context.\n        \"\"\"\n        if isinstance(expr, string_types):\n            if expr[0] in '\\'\"':\n                result = expr[1:-1]\n            else:\n                if expr not in context:\n                    raise SyntaxError('unknown variable: %s' % expr)\n                result = context[expr]\n        else:\n            assert isinstance(expr, dict)\n            op = expr['op']\n            if op not in self.operations:\n                raise NotImplementedError('op not implemented: %s' % op)\n            elhs = expr['lhs']\n            erhs = expr['rhs']\n            if _is_literal(expr['lhs']) and _is_literal(expr['rhs']):\n                raise SyntaxError('invalid comparison: %s %s %s' % (elhs, op, erhs))\n\n            lhs = self.evaluate(elhs, context)\n            rhs = self.evaluate(erhs, context)\n            if ((elhs == 'python_version' or erhs == 'python_version') and\n                op in ('<', '<=', '>', '>=', '===', '==', '!=', '~=')):\n                lhs = NV(lhs)\n                rhs = NV(rhs)\n            elif elhs == 'python_version' and op in ('in', 'not in'):\n                lhs = NV(lhs)\n                rhs = _get_versions(rhs)\n            result = self.operations[op](lhs, rhs)\n        return result\n\n_DIGITS = re.compile(r'\\d+\\.\\d+')\n\ndef default_context():\n    def format_full_version(info):\n        version = '%s.%s.%s' % (info.major, info.minor, info.micro)\n        kind = info.releaselevel\n        if kind != 'final':\n            version += kind[0] + str(info.serial)\n        return version\n\n    if hasattr(sys, 'implementation'):\n        implementation_version = format_full_version(sys.implementation.version)\n        implementation_name = sys.implementation.name\n    else:\n        implementation_version = '0'\n        implementation_name = ''\n\n    ppv = platform.python_version()\n    m = _DIGITS.match(ppv)\n    pv = m.group(0)\n    result = {\n        'implementation_name': implementation_name,\n        'implementation_version': implementation_version,\n        'os_name': os.name,\n        'platform_machine': platform.machine(),\n        'platform_python_implementation': platform.python_implementation(),\n        'platform_release': platform.release(),\n        'platform_system': platform.system(),\n        'platform_version': platform.version(),\n        'platform_in_venv': str(in_venv()),\n        'python_full_version': ppv,\n        'python_version': pv,\n        'sys_platform': sys.platform,\n    }\n    return result\n\nDEFAULT_CONTEXT = default_context()\ndel default_context\n\nevaluator = Evaluator()\n\ndef interpret(marker, execution_context=None):\n    \"\"\"\n    Interpret a marker and return a result depending on environment.\n\n    :param marker: The marker to interpret.\n    :type marker: str\n    :param execution_context: The context used for name lookup.\n    :type execution_context: mapping\n    \"\"\"\n    try:\n        expr, rest = parse_marker(marker)\n    except Exception as e:\n        raise SyntaxError('Unable to interpret marker syntax: %s: %s' % (marker, e))\n    if rest and rest[0] != '#':\n        raise SyntaxError('unexpected trailing data in marker: %s: %s' % (marker, rest))\n    context = dict(DEFAULT_CONTEXT)\n    if execution_context:\n        context.update(execution_context)\n    return evaluator.evaluate(expr, context)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distlib/metadata.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2012 The Python Software Foundation.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\n\"\"\"Implementation of the Metadata for Python packages PEPs.\n\nSupports all metadata formats (1.0, 1.1, 1.2, 1.3/2.1 and 2.2).\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport codecs\nfrom email import message_from_file\nimport json\nimport logging\nimport re\n\n\nfrom . import DistlibException, __version__\nfrom .compat import StringIO, string_types, text_type\nfrom .markers import interpret\nfrom .util import extract_by_key, get_extras\nfrom .version import get_scheme, PEP440_VERSION_RE\n\nlogger = logging.getLogger(__name__)\n\n\nclass MetadataMissingError(DistlibException):\n    \"\"\"A required metadata is missing\"\"\"\n\n\nclass MetadataConflictError(DistlibException):\n    \"\"\"Attempt to read or write metadata fields that are conflictual.\"\"\"\n\n\nclass MetadataUnrecognizedVersionError(DistlibException):\n    \"\"\"Unknown metadata version number.\"\"\"\n\n\nclass MetadataInvalidError(DistlibException):\n    \"\"\"A metadata value is invalid\"\"\"\n\n# public API of this module\n__all__ = ['Metadata', 'PKG_INFO_ENCODING', 'PKG_INFO_PREFERRED_VERSION']\n\n# Encoding used for the PKG-INFO files\nPKG_INFO_ENCODING = 'utf-8'\n\n# preferred version. Hopefully will be changed\n# to 1.2 once PEP 345 is supported everywhere\nPKG_INFO_PREFERRED_VERSION = '1.1'\n\n_LINE_PREFIX_1_2 = re.compile('\\n       \\\\|')\n_LINE_PREFIX_PRE_1_2 = re.compile('\\n        ')\n_241_FIELDS = ('Metadata-Version', 'Name', 'Version', 'Platform',\n               'Summary', 'Description',\n               'Keywords', 'Home-page', 'Author', 'Author-email',\n               'License')\n\n_314_FIELDS = ('Metadata-Version', 'Name', 'Version', 'Platform',\n               'Supported-Platform', 'Summary', 'Description',\n               'Keywords', 'Home-page', 'Author', 'Author-email',\n               'License', 'Classifier', 'Download-URL', 'Obsoletes',\n               'Provides', 'Requires')\n\n_314_MARKERS = ('Obsoletes', 'Provides', 'Requires', 'Classifier',\n                'Download-URL')\n\n_345_FIELDS = ('Metadata-Version', 'Name', 'Version', 'Platform',\n               'Supported-Platform', 'Summary', 'Description',\n               'Keywords', 'Home-page', 'Author', 'Author-email',\n               'Maintainer', 'Maintainer-email', 'License',\n               'Classifier', 'Download-URL', 'Obsoletes-Dist',\n               'Project-URL', 'Provides-Dist', 'Requires-Dist',\n               'Requires-Python', 'Requires-External')\n\n_345_MARKERS = ('Provides-Dist', 'Requires-Dist', 'Requires-Python',\n                'Obsoletes-Dist', 'Requires-External', 'Maintainer',\n                'Maintainer-email', 'Project-URL')\n\n_426_FIELDS = ('Metadata-Version', 'Name', 'Version', 'Platform',\n               'Supported-Platform', 'Summary', 'Description',\n               'Keywords', 'Home-page', 'Author', 'Author-email',\n               'Maintainer', 'Maintainer-email', 'License',\n               'Classifier', 'Download-URL', 'Obsoletes-Dist',\n               'Project-URL', 'Provides-Dist', 'Requires-Dist',\n               'Requires-Python', 'Requires-External', 'Private-Version',\n               'Obsoleted-By', 'Setup-Requires-Dist', 'Extension',\n               'Provides-Extra')\n\n_426_MARKERS = ('Private-Version', 'Provides-Extra', 'Obsoleted-By',\n                'Setup-Requires-Dist', 'Extension')\n\n# See issue #106: Sometimes 'Requires' and 'Provides' occur wrongly in\n# the metadata. Include them in the tuple literal below to allow them\n# (for now).\n# Ditto for Obsoletes - see issue #140.\n_566_FIELDS = _426_FIELDS + ('Description-Content-Type',\n                             'Requires', 'Provides', 'Obsoletes')\n\n_566_MARKERS = ('Description-Content-Type',)\n\n_643_MARKERS = ('Dynamic', 'License-File')\n\n_643_FIELDS = _566_FIELDS + _643_MARKERS\n\n_ALL_FIELDS = set()\n_ALL_FIELDS.update(_241_FIELDS)\n_ALL_FIELDS.update(_314_FIELDS)\n_ALL_FIELDS.update(_345_FIELDS)\n_ALL_FIELDS.update(_426_FIELDS)\n_ALL_FIELDS.update(_566_FIELDS)\n_ALL_FIELDS.update(_643_FIELDS)\n\nEXTRA_RE = re.compile(r'''extra\\s*==\\s*(\"([^\"]+)\"|'([^']+)')''')\n\n\ndef _version2fieldlist(version):\n    if version == '1.0':\n        return _241_FIELDS\n    elif version == '1.1':\n        return _314_FIELDS\n    elif version == '1.2':\n        return _345_FIELDS\n    elif version in ('1.3', '2.1'):\n        # avoid adding field names if already there\n        return _345_FIELDS + tuple(f for f in _566_FIELDS if f not in _345_FIELDS)\n    elif version == '2.0':\n        raise ValueError('Metadata 2.0 is withdrawn and not supported')\n        # return _426_FIELDS\n    elif version == '2.2':\n        return _643_FIELDS\n    raise MetadataUnrecognizedVersionError(version)\n\n\ndef _best_version(fields):\n    \"\"\"Detect the best version depending on the fields used.\"\"\"\n    def _has_marker(keys, markers):\n        for marker in markers:\n            if marker in keys:\n                return True\n        return False\n\n    keys = []\n    for key, value in fields.items():\n        if value in ([], 'UNKNOWN', None):\n            continue\n        keys.append(key)\n\n    possible_versions = ['1.0', '1.1', '1.2', '1.3', '2.1', '2.2']  # 2.0 removed\n\n    # first let's try to see if a field is not part of one of the version\n    for key in keys:\n        if key not in _241_FIELDS and '1.0' in possible_versions:\n            possible_versions.remove('1.0')\n            logger.debug('Removed 1.0 due to %s', key)\n        if key not in _314_FIELDS and '1.1' in possible_versions:\n            possible_versions.remove('1.1')\n            logger.debug('Removed 1.1 due to %s', key)\n        if key not in _345_FIELDS and '1.2' in possible_versions:\n            possible_versions.remove('1.2')\n            logger.debug('Removed 1.2 due to %s', key)\n        if key not in _566_FIELDS and '1.3' in possible_versions:\n            possible_versions.remove('1.3')\n            logger.debug('Removed 1.3 due to %s', key)\n        if key not in _566_FIELDS and '2.1' in possible_versions:\n            if key != 'Description':  # In 2.1, description allowed after headers\n                possible_versions.remove('2.1')\n                logger.debug('Removed 2.1 due to %s', key)\n        if key not in _643_FIELDS and '2.2' in possible_versions:\n            possible_versions.remove('2.2')\n            logger.debug('Removed 2.2 due to %s', key)\n        # if key not in _426_FIELDS and '2.0' in possible_versions:\n            # possible_versions.remove('2.0')\n            # logger.debug('Removed 2.0 due to %s', key)\n\n    # possible_version contains qualified versions\n    if len(possible_versions) == 1:\n        return possible_versions[0]   # found !\n    elif len(possible_versions) == 0:\n        logger.debug('Out of options - unknown metadata set: %s', fields)\n        raise MetadataConflictError('Unknown metadata set')\n\n    # let's see if one unique marker is found\n    is_1_1 = '1.1' in possible_versions and _has_marker(keys, _314_MARKERS)\n    is_1_2 = '1.2' in possible_versions and _has_marker(keys, _345_MARKERS)\n    is_2_1 = '2.1' in possible_versions and _has_marker(keys, _566_MARKERS)\n    # is_2_0 = '2.0' in possible_versions and _has_marker(keys, _426_MARKERS)\n    is_2_2 = '2.2' in possible_versions and _has_marker(keys, _643_MARKERS)\n    if int(is_1_1) + int(is_1_2) + int(is_2_1) + int(is_2_2) > 1:\n        raise MetadataConflictError('You used incompatible 1.1/1.2/2.1/2.2 fields')\n\n    # we have the choice, 1.0, or 1.2, 2.1 or 2.2\n    #   - 1.0 has a broken Summary field but works with all tools\n    #   - 1.1 is to avoid\n    #   - 1.2 fixes Summary but has little adoption\n    #   - 2.1 adds more features\n    #   - 2.2 is the latest\n    if not is_1_1 and not is_1_2 and not is_2_1 and not is_2_2:\n        # we couldn't find any specific marker\n        if PKG_INFO_PREFERRED_VERSION in possible_versions:\n            return PKG_INFO_PREFERRED_VERSION\n    if is_1_1:\n        return '1.1'\n    if is_1_2:\n        return '1.2'\n    if is_2_1:\n        return '2.1'\n    # if is_2_2:\n        # return '2.2'\n\n    return '2.2'\n\n# This follows the rules about transforming keys as described in\n# https://www.python.org/dev/peps/pep-0566/#id17\n_ATTR2FIELD = {\n    name.lower().replace(\"-\", \"_\"): name for name in _ALL_FIELDS\n}\n_FIELD2ATTR = {field: attr for attr, field in _ATTR2FIELD.items()}\n\n_PREDICATE_FIELDS = ('Requires-Dist', 'Obsoletes-Dist', 'Provides-Dist')\n_VERSIONS_FIELDS = ('Requires-Python',)\n_VERSION_FIELDS = ('Version',)\n_LISTFIELDS = ('Platform', 'Classifier', 'Obsoletes',\n               'Requires', 'Provides', 'Obsoletes-Dist',\n               'Provides-Dist', 'Requires-Dist', 'Requires-External',\n               'Project-URL', 'Supported-Platform', 'Setup-Requires-Dist',\n               'Provides-Extra', 'Extension', 'License-File')\n_LISTTUPLEFIELDS = ('Project-URL',)\n\n_ELEMENTSFIELD = ('Keywords',)\n\n_UNICODEFIELDS = ('Author', 'Maintainer', 'Summary', 'Description')\n\n_MISSING = object()\n\n_FILESAFE = re.compile('[^A-Za-z0-9.]+')\n\n\ndef _get_name_and_version(name, version, for_filename=False):\n    \"\"\"Return the distribution name with version.\n\n    If for_filename is true, return a filename-escaped form.\"\"\"\n    if for_filename:\n        # For both name and version any runs of non-alphanumeric or '.'\n        # characters are replaced with a single '-'.  Additionally any\n        # spaces in the version string become '.'\n        name = _FILESAFE.sub('-', name)\n        version = _FILESAFE.sub('-', version.replace(' ', '.'))\n    return '%s-%s' % (name, version)\n\n\nclass LegacyMetadata(object):\n    \"\"\"The legacy metadata of a release.\n\n    Supports versions 1.0, 1.1, 1.2, 2.0 and 1.3/2.1 (auto-detected). You can\n    instantiate the class with one of these arguments (or none):\n    - *path*, the path to a metadata file\n    - *fileobj* give a file-like object with metadata as content\n    - *mapping* is a dict-like object\n    - *scheme* is a version scheme name\n    \"\"\"\n    # TODO document the mapping API and UNKNOWN default key\n\n    def __init__(self, path=None, fileobj=None, mapping=None,\n                 scheme='default'):\n        if [path, fileobj, mapping].count(None) < 2:\n            raise TypeError('path, fileobj and mapping are exclusive')\n        self._fields = {}\n        self.requires_files = []\n        self._dependencies = None\n        self.scheme = scheme\n        if path is not None:\n            self.read(path)\n        elif fileobj is not None:\n            self.read_file(fileobj)\n        elif mapping is not None:\n            self.update(mapping)\n            self.set_metadata_version()\n\n    def set_metadata_version(self):\n        self._fields['Metadata-Version'] = _best_version(self._fields)\n\n    def _write_field(self, fileobj, name, value):\n        fileobj.write('%s: %s\\n' % (name, value))\n\n    def __getitem__(self, name):\n        return self.get(name)\n\n    def __setitem__(self, name, value):\n        return self.set(name, value)\n\n    def __delitem__(self, name):\n        field_name = self._convert_name(name)\n        try:\n            del self._fields[field_name]\n        except KeyError:\n            raise KeyError(name)\n\n    def __contains__(self, name):\n        return (name in self._fields or\n                self._convert_name(name) in self._fields)\n\n    def _convert_name(self, name):\n        if name in _ALL_FIELDS:\n            return name\n        name = name.replace('-', '_').lower()\n        return _ATTR2FIELD.get(name, name)\n\n    def _default_value(self, name):\n        if name in _LISTFIELDS or name in _ELEMENTSFIELD:\n            return []\n        return 'UNKNOWN'\n\n    def _remove_line_prefix(self, value):\n        if self.metadata_version in ('1.0', '1.1'):\n            return _LINE_PREFIX_PRE_1_2.sub('\\n', value)\n        else:\n            return _LINE_PREFIX_1_2.sub('\\n', value)\n\n    def __getattr__(self, name):\n        if name in _ATTR2FIELD:\n            return self[name]\n        raise AttributeError(name)\n\n    #\n    # Public API\n    #\n\n#    dependencies = property(_get_dependencies, _set_dependencies)\n\n    def get_fullname(self, filesafe=False):\n        \"\"\"Return the distribution name with version.\n\n        If filesafe is true, return a filename-escaped form.\"\"\"\n        return _get_name_and_version(self['Name'], self['Version'], filesafe)\n\n    def is_field(self, name):\n        \"\"\"return True if name is a valid metadata key\"\"\"\n        name = self._convert_name(name)\n        return name in _ALL_FIELDS\n\n    def is_multi_field(self, name):\n        name = self._convert_name(name)\n        return name in _LISTFIELDS\n\n    def read(self, filepath):\n        \"\"\"Read the metadata values from a file path.\"\"\"\n        fp = codecs.open(filepath, 'r', encoding='utf-8')\n        try:\n            self.read_file(fp)\n        finally:\n            fp.close()\n\n    def read_file(self, fileob):\n        \"\"\"Read the metadata values from a file object.\"\"\"\n        msg = message_from_file(fileob)\n        self._fields['Metadata-Version'] = msg['metadata-version']\n\n        # When reading, get all the fields we can\n        for field in _ALL_FIELDS:\n            if field not in msg:\n                continue\n            if field in _LISTFIELDS:\n                # we can have multiple lines\n                values = msg.get_all(field)\n                if field in _LISTTUPLEFIELDS and values is not None:\n                    values = [tuple(value.split(',')) for value in values]\n                self.set(field, values)\n            else:\n                # single line\n                value = msg[field]\n                if value is not None and value != 'UNKNOWN':\n                    self.set(field, value)\n\n        # PEP 566 specifies that the body be used for the description, if\n        # available\n        body = msg.get_payload()\n        self[\"Description\"] = body if body else self[\"Description\"]\n        # logger.debug('Attempting to set metadata for %s', self)\n        # self.set_metadata_version()\n\n    def write(self, filepath, skip_unknown=False):\n        \"\"\"Write the metadata fields to filepath.\"\"\"\n        fp = codecs.open(filepath, 'w', encoding='utf-8')\n        try:\n            self.write_file(fp, skip_unknown)\n        finally:\n            fp.close()\n\n    def write_file(self, fileobject, skip_unknown=False):\n        \"\"\"Write the PKG-INFO format data to a file object.\"\"\"\n        self.set_metadata_version()\n\n        for field in _version2fieldlist(self['Metadata-Version']):\n            values = self.get(field)\n            if skip_unknown and values in ('UNKNOWN', [], ['UNKNOWN']):\n                continue\n            if field in _ELEMENTSFIELD:\n                self._write_field(fileobject, field, ','.join(values))\n                continue\n            if field not in _LISTFIELDS:\n                if field == 'Description':\n                    if self.metadata_version in ('1.0', '1.1'):\n                        values = values.replace('\\n', '\\n        ')\n                    else:\n                        values = values.replace('\\n', '\\n       |')\n                values = [values]\n\n            if field in _LISTTUPLEFIELDS:\n                values = [','.join(value) for value in values]\n\n            for value in values:\n                self._write_field(fileobject, field, value)\n\n    def update(self, other=None, **kwargs):\n        \"\"\"Set metadata values from the given iterable `other` and kwargs.\n\n        Behavior is like `dict.update`: If `other` has a ``keys`` method,\n        they are looped over and ``self[key]`` is assigned ``other[key]``.\n        Else, ``other`` is an iterable of ``(key, value)`` iterables.\n\n        Keys that don't match a metadata field or that have an empty value are\n        dropped.\n        \"\"\"\n        def _set(key, value):\n            if key in _ATTR2FIELD and value:\n                self.set(self._convert_name(key), value)\n\n        if not other:\n            # other is None or empty container\n            pass\n        elif hasattr(other, 'keys'):\n            for k in other.keys():\n                _set(k, other[k])\n        else:\n            for k, v in other:\n                _set(k, v)\n\n        if kwargs:\n            for k, v in kwargs.items():\n                _set(k, v)\n\n    def set(self, name, value):\n        \"\"\"Control then set a metadata field.\"\"\"\n        name = self._convert_name(name)\n\n        if ((name in _ELEMENTSFIELD or name == 'Platform') and\n            not isinstance(value, (list, tuple))):\n            if isinstance(value, string_types):\n                value = [v.strip() for v in value.split(',')]\n            else:\n                value = []\n        elif (name in _LISTFIELDS and\n              not isinstance(value, (list, tuple))):\n            if isinstance(value, string_types):\n                value = [value]\n            else:\n                value = []\n\n        if logger.isEnabledFor(logging.WARNING):\n            project_name = self['Name']\n\n            scheme = get_scheme(self.scheme)\n            if name in _PREDICATE_FIELDS and value is not None:\n                for v in value:\n                    # check that the values are valid\n                    if not scheme.is_valid_matcher(v.split(';')[0]):\n                        logger.warning(\n                            \"'%s': '%s' is not valid (field '%s')\",\n                            project_name, v, name)\n            # FIXME this rejects UNKNOWN, is that right?\n            elif name in _VERSIONS_FIELDS and value is not None:\n                if not scheme.is_valid_constraint_list(value):\n                    logger.warning(\"'%s': '%s' is not a valid version (field '%s')\",\n                                   project_name, value, name)\n            elif name in _VERSION_FIELDS and value is not None:\n                if not scheme.is_valid_version(value):\n                    logger.warning(\"'%s': '%s' is not a valid version (field '%s')\",\n                                   project_name, value, name)\n\n        if name in _UNICODEFIELDS:\n            if name == 'Description':\n                value = self._remove_line_prefix(value)\n\n        self._fields[name] = value\n\n    def get(self, name, default=_MISSING):\n        \"\"\"Get a metadata field.\"\"\"\n        name = self._convert_name(name)\n        if name not in self._fields:\n            if default is _MISSING:\n                default = self._default_value(name)\n            return default\n        if name in _UNICODEFIELDS:\n            value = self._fields[name]\n            return value\n        elif name in _LISTFIELDS:\n            value = self._fields[name]\n            if value is None:\n                return []\n            res = []\n            for val in value:\n                if name not in _LISTTUPLEFIELDS:\n                    res.append(val)\n                else:\n                    # That's for Project-URL\n                    res.append((val[0], val[1]))\n            return res\n\n        elif name in _ELEMENTSFIELD:\n            value = self._fields[name]\n            if isinstance(value, string_types):\n                return value.split(',')\n        return self._fields[name]\n\n    def check(self, strict=False):\n        \"\"\"Check if the metadata is compliant. If strict is True then raise if\n        no Name or Version are provided\"\"\"\n        self.set_metadata_version()\n\n        # XXX should check the versions (if the file was loaded)\n        missing, warnings = [], []\n\n        for attr in ('Name', 'Version'):  # required by PEP 345\n            if attr not in self:\n                missing.append(attr)\n\n        if strict and missing != []:\n            msg = 'missing required metadata: %s' % ', '.join(missing)\n            raise MetadataMissingError(msg)\n\n        for attr in ('Home-page', 'Author'):\n            if attr not in self:\n                missing.append(attr)\n\n        # checking metadata 1.2 (XXX needs to check 1.1, 1.0)\n        if self['Metadata-Version'] != '1.2':\n            return missing, warnings\n\n        scheme = get_scheme(self.scheme)\n\n        def are_valid_constraints(value):\n            for v in value:\n                if not scheme.is_valid_matcher(v.split(';')[0]):\n                    return False\n            return True\n\n        for fields, controller in ((_PREDICATE_FIELDS, are_valid_constraints),\n                                   (_VERSIONS_FIELDS,\n                                    scheme.is_valid_constraint_list),\n                                   (_VERSION_FIELDS,\n                                    scheme.is_valid_version)):\n            for field in fields:\n                value = self.get(field, None)\n                if value is not None and not controller(value):\n                    warnings.append(\"Wrong value for '%s': %s\" % (field, value))\n\n        return missing, warnings\n\n    def todict(self, skip_missing=False):\n        \"\"\"Return fields as a dict.\n\n        Field names will be converted to use the underscore-lowercase style\n        instead of hyphen-mixed case (i.e. home_page instead of Home-page).\n        This is as per https://www.python.org/dev/peps/pep-0566/#id17.\n        \"\"\"\n        self.set_metadata_version()\n\n        fields = _version2fieldlist(self['Metadata-Version'])\n\n        data = {}\n\n        for field_name in fields:\n            if not skip_missing or field_name in self._fields:\n                key = _FIELD2ATTR[field_name]\n                if key != 'project_url':\n                    data[key] = self[field_name]\n                else:\n                    data[key] = [','.join(u) for u in self[field_name]]\n\n        return data\n\n    def add_requirements(self, requirements):\n        if self['Metadata-Version'] == '1.1':\n            # we can't have 1.1 metadata *and* Setuptools requires\n            for field in ('Obsoletes', 'Requires', 'Provides'):\n                if field in self:\n                    del self[field]\n        self['Requires-Dist'] += requirements\n\n    # Mapping API\n    # TODO could add iter* variants\n\n    def keys(self):\n        return list(_version2fieldlist(self['Metadata-Version']))\n\n    def __iter__(self):\n        for key in self.keys():\n            yield key\n\n    def values(self):\n        return [self[key] for key in self.keys()]\n\n    def items(self):\n        return [(key, self[key]) for key in self.keys()]\n\n    def __repr__(self):\n        return '<%s %s %s>' % (self.__class__.__name__, self.name,\n                               self.version)\n\n\nMETADATA_FILENAME = 'pydist.json'\nWHEEL_METADATA_FILENAME = 'metadata.json'\nLEGACY_METADATA_FILENAME = 'METADATA'\n\n\nclass Metadata(object):\n    \"\"\"\n    The metadata of a release. This implementation uses 2.1\n    metadata where possible. If not possible, it wraps a LegacyMetadata\n    instance which handles the key-value metadata format.\n    \"\"\"\n\n    METADATA_VERSION_MATCHER = re.compile(r'^\\d+(\\.\\d+)*$')\n\n    NAME_MATCHER = re.compile('^[0-9A-Z]([0-9A-Z_.-]*[0-9A-Z])?$', re.I)\n\n    FIELDNAME_MATCHER = re.compile('^[A-Z]([0-9A-Z-]*[0-9A-Z])?$', re.I)\n\n    VERSION_MATCHER = PEP440_VERSION_RE\n\n    SUMMARY_MATCHER = re.compile('.{1,2047}')\n\n    METADATA_VERSION = '2.0'\n\n    GENERATOR = 'distlib (%s)' % __version__\n\n    MANDATORY_KEYS = {\n        'name': (),\n        'version': (),\n        'summary': ('legacy',),\n    }\n\n    INDEX_KEYS = ('name version license summary description author '\n                  'author_email keywords platform home_page classifiers '\n                  'download_url')\n\n    DEPENDENCY_KEYS = ('extras run_requires test_requires build_requires '\n                       'dev_requires provides meta_requires obsoleted_by '\n                       'supports_environments')\n\n    SYNTAX_VALIDATORS = {\n        'metadata_version': (METADATA_VERSION_MATCHER, ()),\n        'name': (NAME_MATCHER, ('legacy',)),\n        'version': (VERSION_MATCHER, ('legacy',)),\n        'summary': (SUMMARY_MATCHER, ('legacy',)),\n        'dynamic': (FIELDNAME_MATCHER, ('legacy',)),\n    }\n\n    __slots__ = ('_legacy', '_data', 'scheme')\n\n    def __init__(self, path=None, fileobj=None, mapping=None,\n                 scheme='default'):\n        if [path, fileobj, mapping].count(None) < 2:\n            raise TypeError('path, fileobj and mapping are exclusive')\n        self._legacy = None\n        self._data = None\n        self.scheme = scheme\n        #import pdb; pdb.set_trace()\n        if mapping is not None:\n            try:\n                self._validate_mapping(mapping, scheme)\n                self._data = mapping\n            except MetadataUnrecognizedVersionError:\n                self._legacy = LegacyMetadata(mapping=mapping, scheme=scheme)\n                self.validate()\n        else:\n            data = None\n            if path:\n                with open(path, 'rb') as f:\n                    data = f.read()\n            elif fileobj:\n                data = fileobj.read()\n            if data is None:\n                # Initialised with no args - to be added\n                self._data = {\n                    'metadata_version': self.METADATA_VERSION,\n                    'generator': self.GENERATOR,\n                }\n            else:\n                if not isinstance(data, text_type):\n                    data = data.decode('utf-8')\n                try:\n                    self._data = json.loads(data)\n                    self._validate_mapping(self._data, scheme)\n                except ValueError:\n                    # Note: MetadataUnrecognizedVersionError does not\n                    # inherit from ValueError (it's a DistlibException,\n                    # which should not inherit from ValueError).\n                    # The ValueError comes from the json.load - if that\n                    # succeeds and we get a validation error, we want\n                    # that to propagate\n                    self._legacy = LegacyMetadata(fileobj=StringIO(data),\n                                                  scheme=scheme)\n                    self.validate()\n\n    common_keys = set(('name', 'version', 'license', 'keywords', 'summary'))\n\n    none_list = (None, list)\n    none_dict = (None, dict)\n\n    mapped_keys = {\n        'run_requires': ('Requires-Dist', list),\n        'build_requires': ('Setup-Requires-Dist', list),\n        'dev_requires': none_list,\n        'test_requires': none_list,\n        'meta_requires': none_list,\n        'extras': ('Provides-Extra', list),\n        'modules': none_list,\n        'namespaces': none_list,\n        'exports': none_dict,\n        'commands': none_dict,\n        'classifiers': ('Classifier', list),\n        'source_url': ('Download-URL', None),\n        'metadata_version': ('Metadata-Version', None),\n    }\n\n    del none_list, none_dict\n\n    def __getattribute__(self, key):\n        common = object.__getattribute__(self, 'common_keys')\n        mapped = object.__getattribute__(self, 'mapped_keys')\n        if key in mapped:\n            lk, maker = mapped[key]\n            if self._legacy:\n                if lk is None:\n                    result = None if maker is None else maker()\n                else:\n                    result = self._legacy.get(lk)\n            else:\n                value = None if maker is None else maker()\n                if key not in ('commands', 'exports', 'modules', 'namespaces',\n                               'classifiers'):\n                    result = self._data.get(key, value)\n                else:\n                    # special cases for PEP 459\n                    sentinel = object()\n                    result = sentinel\n                    d = self._data.get('extensions')\n                    if d:\n                        if key == 'commands':\n                            result = d.get('python.commands', value)\n                        elif key == 'classifiers':\n                            d = d.get('python.details')\n                            if d:\n                                result = d.get(key, value)\n                        else:\n                            d = d.get('python.exports')\n                            if not d:\n                                d = self._data.get('python.exports')\n                            if d:\n                                result = d.get(key, value)\n                    if result is sentinel:\n                        result = value\n        elif key not in common:\n            result = object.__getattribute__(self, key)\n        elif self._legacy:\n            result = self._legacy.get(key)\n        else:\n            result = self._data.get(key)\n        return result\n\n    def _validate_value(self, key, value, scheme=None):\n        if key in self.SYNTAX_VALIDATORS:\n            pattern, exclusions = self.SYNTAX_VALIDATORS[key]\n            if (scheme or self.scheme) not in exclusions:\n                m = pattern.match(value)\n                if not m:\n                    raise MetadataInvalidError(\"'%s' is an invalid value for \"\n                                               \"the '%s' property\" % (value,\n                                                                    key))\n\n    def __setattr__(self, key, value):\n        self._validate_value(key, value)\n        common = object.__getattribute__(self, 'common_keys')\n        mapped = object.__getattribute__(self, 'mapped_keys')\n        if key in mapped:\n            lk, _ = mapped[key]\n            if self._legacy:\n                if lk is None:\n                    raise NotImplementedError\n                self._legacy[lk] = value\n            elif key not in ('commands', 'exports', 'modules', 'namespaces',\n                             'classifiers'):\n                self._data[key] = value\n            else:\n                # special cases for PEP 459\n                d = self._data.setdefault('extensions', {})\n                if key == 'commands':\n                    d['python.commands'] = value\n                elif key == 'classifiers':\n                    d = d.setdefault('python.details', {})\n                    d[key] = value\n                else:\n                    d = d.setdefault('python.exports', {})\n                    d[key] = value\n        elif key not in common:\n            object.__setattr__(self, key, value)\n        else:\n            if key == 'keywords':\n                if isinstance(value, string_types):\n                    value = value.strip()\n                    if value:\n                        value = value.split()\n                    else:\n                        value = []\n            if self._legacy:\n                self._legacy[key] = value\n            else:\n                self._data[key] = value\n\n    @property\n    def name_and_version(self):\n        return _get_name_and_version(self.name, self.version, True)\n\n    @property\n    def provides(self):\n        if self._legacy:\n            result = self._legacy['Provides-Dist']\n        else:\n            result = self._data.setdefault('provides', [])\n        s = '%s (%s)' % (self.name, self.version)\n        if s not in result:\n            result.append(s)\n        return result\n\n    @provides.setter\n    def provides(self, value):\n        if self._legacy:\n            self._legacy['Provides-Dist'] = value\n        else:\n            self._data['provides'] = value\n\n    def get_requirements(self, reqts, extras=None, env=None):\n        \"\"\"\n        Base method to get dependencies, given a set of extras\n        to satisfy and an optional environment context.\n        :param reqts: A list of sometimes-wanted dependencies,\n                      perhaps dependent on extras and environment.\n        :param extras: A list of optional components being requested.\n        :param env: An optional environment for marker evaluation.\n        \"\"\"\n        if self._legacy:\n            result = reqts\n        else:\n            result = []\n            extras = get_extras(extras or [], self.extras)\n            for d in reqts:\n                if 'extra' not in d and 'environment' not in d:\n                    # unconditional\n                    include = True\n                else:\n                    if 'extra' not in d:\n                        # Not extra-dependent - only environment-dependent\n                        include = True\n                    else:\n                        include = d.get('extra') in extras\n                    if include:\n                        # Not excluded because of extras, check environment\n                        marker = d.get('environment')\n                        if marker:\n                            include = interpret(marker, env)\n                if include:\n                    result.extend(d['requires'])\n            for key in ('build', 'dev', 'test'):\n                e = ':%s:' % key\n                if e in extras:\n                    extras.remove(e)\n                    # A recursive call, but it should terminate since 'test'\n                    # has been removed from the extras\n                    reqts = self._data.get('%s_requires' % key, [])\n                    result.extend(self.get_requirements(reqts, extras=extras,\n                                                        env=env))\n        return result\n\n    @property\n    def dictionary(self):\n        if self._legacy:\n            return self._from_legacy()\n        return self._data\n\n    @property\n    def dependencies(self):\n        if self._legacy:\n            raise NotImplementedError\n        else:\n            return extract_by_key(self._data, self.DEPENDENCY_KEYS)\n\n    @dependencies.setter\n    def dependencies(self, value):\n        if self._legacy:\n            raise NotImplementedError\n        else:\n            self._data.update(value)\n\n    def _validate_mapping(self, mapping, scheme):\n        if mapping.get('metadata_version') != self.METADATA_VERSION:\n            raise MetadataUnrecognizedVersionError()\n        missing = []\n        for key, exclusions in self.MANDATORY_KEYS.items():\n            if key not in mapping:\n                if scheme not in exclusions:\n                    missing.append(key)\n        if missing:\n            msg = 'Missing metadata items: %s' % ', '.join(missing)\n            raise MetadataMissingError(msg)\n        for k, v in mapping.items():\n            self._validate_value(k, v, scheme)\n\n    def validate(self):\n        if self._legacy:\n            missing, warnings = self._legacy.check(True)\n            if missing or warnings:\n                logger.warning('Metadata: missing: %s, warnings: %s',\n                               missing, warnings)\n        else:\n            self._validate_mapping(self._data, self.scheme)\n\n    def todict(self):\n        if self._legacy:\n            return self._legacy.todict(True)\n        else:\n            result = extract_by_key(self._data, self.INDEX_KEYS)\n            return result\n\n    def _from_legacy(self):\n        assert self._legacy and not self._data\n        result = {\n            'metadata_version': self.METADATA_VERSION,\n            'generator': self.GENERATOR,\n        }\n        lmd = self._legacy.todict(True)     # skip missing ones\n        for k in ('name', 'version', 'license', 'summary', 'description',\n                  'classifier'):\n            if k in lmd:\n                if k == 'classifier':\n                    nk = 'classifiers'\n                else:\n                    nk = k\n                result[nk] = lmd[k]\n        kw = lmd.get('Keywords', [])\n        if kw == ['']:\n            kw = []\n        result['keywords'] = kw\n        keys = (('requires_dist', 'run_requires'),\n                ('setup_requires_dist', 'build_requires'))\n        for ok, nk in keys:\n            if ok in lmd and lmd[ok]:\n                result[nk] = [{'requires': lmd[ok]}]\n        result['provides'] = self.provides\n        author = {}\n        maintainer = {}\n        return result\n\n    LEGACY_MAPPING = {\n        'name': 'Name',\n        'version': 'Version',\n        ('extensions', 'python.details', 'license'): 'License',\n        'summary': 'Summary',\n        'description': 'Description',\n        ('extensions', 'python.project', 'project_urls', 'Home'): 'Home-page',\n        ('extensions', 'python.project', 'contacts', 0, 'name'): 'Author',\n        ('extensions', 'python.project', 'contacts', 0, 'email'): 'Author-email',\n        'source_url': 'Download-URL',\n        ('extensions', 'python.details', 'classifiers'): 'Classifier',\n    }\n\n    def _to_legacy(self):\n        def process_entries(entries):\n            reqts = set()\n            for e in entries:\n                extra = e.get('extra')\n                env = e.get('environment')\n                rlist = e['requires']\n                for r in rlist:\n                    if not env and not extra:\n                        reqts.add(r)\n                    else:\n                        marker = ''\n                        if extra:\n                            marker = 'extra == \"%s\"' % extra\n                        if env:\n                            if marker:\n                                marker = '(%s) and %s' % (env, marker)\n                            else:\n                                marker = env\n                        reqts.add(';'.join((r, marker)))\n            return reqts\n\n        assert self._data and not self._legacy\n        result = LegacyMetadata()\n        nmd = self._data\n        # import pdb; pdb.set_trace()\n        for nk, ok in self.LEGACY_MAPPING.items():\n            if not isinstance(nk, tuple):\n                if nk in nmd:\n                    result[ok] = nmd[nk]\n            else:\n                d = nmd\n                found = True\n                for k in nk:\n                    try:\n                        d = d[k]\n                    except (KeyError, IndexError):\n                        found = False\n                        break\n                if found:\n                    result[ok] = d\n        r1 = process_entries(self.run_requires + self.meta_requires)\n        r2 = process_entries(self.build_requires + self.dev_requires)\n        if self.extras:\n            result['Provides-Extra'] = sorted(self.extras)\n        result['Requires-Dist'] = sorted(r1)\n        result['Setup-Requires-Dist'] = sorted(r2)\n        # TODO: any other fields wanted\n        return result\n\n    def write(self, path=None, fileobj=None, legacy=False, skip_unknown=True):\n        if [path, fileobj].count(None) != 1:\n            raise ValueError('Exactly one of path and fileobj is needed')\n        self.validate()\n        if legacy:\n            if self._legacy:\n                legacy_md = self._legacy\n            else:\n                legacy_md = self._to_legacy()\n            if path:\n                legacy_md.write(path, skip_unknown=skip_unknown)\n            else:\n                legacy_md.write_file(fileobj, skip_unknown=skip_unknown)\n        else:\n            if self._legacy:\n                d = self._from_legacy()\n            else:\n                d = self._data\n            if fileobj:\n                json.dump(d, fileobj, ensure_ascii=True, indent=2,\n                          sort_keys=True)\n            else:\n                with codecs.open(path, 'w', 'utf-8') as f:\n                    json.dump(d, f, ensure_ascii=True, indent=2,\n                              sort_keys=True)\n\n    def add_requirements(self, requirements):\n        if self._legacy:\n            self._legacy.add_requirements(requirements)\n        else:\n            run_requires = self._data.setdefault('run_requires', [])\n            always = None\n            for entry in run_requires:\n                if 'environment' not in entry and 'extra' not in entry:\n                    always = entry\n                    break\n            if always is None:\n                always = { 'requires': requirements }\n                run_requires.insert(0, always)\n            else:\n                rset = set(always['requires']) | set(requirements)\n                always['requires'] = sorted(rset)\n\n    def __repr__(self):\n        name = self.name or '(no name)'\n        version = self.version or 'no version'\n        return '<%s %s %s (%s)>' % (self.__class__.__name__,\n                                    self.metadata_version, name, version)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distlib/resources.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013-2017 Vinay Sajip.\n# Licensed to the Python Software Foundation under a contributor agreement.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\nfrom __future__ import unicode_literals\n\nimport bisect\nimport io\nimport logging\nimport os\nimport pkgutil\nimport sys\nimport types\nimport zipimport\n\nfrom . import DistlibException\nfrom .util import cached_property, get_cache_base, Cache\n\nlogger = logging.getLogger(__name__)\n\n\ncache = None    # created when needed\n\n\nclass ResourceCache(Cache):\n    def __init__(self, base=None):\n        if base is None:\n            # Use native string to avoid issues on 2.x: see Python #20140.\n            base = os.path.join(get_cache_base(), str('resource-cache'))\n        super(ResourceCache, self).__init__(base)\n\n    def is_stale(self, resource, path):\n        \"\"\"\n        Is the cache stale for the given resource?\n\n        :param resource: The :class:`Resource` being cached.\n        :param path: The path of the resource in the cache.\n        :return: True if the cache is stale.\n        \"\"\"\n        # Cache invalidation is a hard problem :-)\n        return True\n\n    def get(self, resource):\n        \"\"\"\n        Get a resource into the cache,\n\n        :param resource: A :class:`Resource` instance.\n        :return: The pathname of the resource in the cache.\n        \"\"\"\n        prefix, path = resource.finder.get_cache_info(resource)\n        if prefix is None:\n            result = path\n        else:\n            result = os.path.join(self.base, self.prefix_to_dir(prefix), path)\n            dirname = os.path.dirname(result)\n            if not os.path.isdir(dirname):\n                os.makedirs(dirname)\n            if not os.path.exists(result):\n                stale = True\n            else:\n                stale = self.is_stale(resource, path)\n            if stale:\n                # write the bytes of the resource to the cache location\n                with open(result, 'wb') as f:\n                    f.write(resource.bytes)\n        return result\n\n\nclass ResourceBase(object):\n    def __init__(self, finder, name):\n        self.finder = finder\n        self.name = name\n\n\nclass Resource(ResourceBase):\n    \"\"\"\n    A class representing an in-package resource, such as a data file. This is\n    not normally instantiated by user code, but rather by a\n    :class:`ResourceFinder` which manages the resource.\n    \"\"\"\n    is_container = False        # Backwards compatibility\n\n    def as_stream(self):\n        \"\"\"\n        Get the resource as a stream.\n\n        This is not a property to make it obvious that it returns a new stream\n        each time.\n        \"\"\"\n        return self.finder.get_stream(self)\n\n    @cached_property\n    def file_path(self):\n        global cache\n        if cache is None:\n            cache = ResourceCache()\n        return cache.get(self)\n\n    @cached_property\n    def bytes(self):\n        return self.finder.get_bytes(self)\n\n    @cached_property\n    def size(self):\n        return self.finder.get_size(self)\n\n\nclass ResourceContainer(ResourceBase):\n    is_container = True     # Backwards compatibility\n\n    @cached_property\n    def resources(self):\n        return self.finder.get_resources(self)\n\n\nclass ResourceFinder(object):\n    \"\"\"\n    Resource finder for file system resources.\n    \"\"\"\n\n    if sys.platform.startswith('java'):\n        skipped_extensions = ('.pyc', '.pyo', '.class')\n    else:\n        skipped_extensions = ('.pyc', '.pyo')\n\n    def __init__(self, module):\n        self.module = module\n        self.loader = getattr(module, '__loader__', None)\n        self.base = os.path.dirname(getattr(module, '__file__', ''))\n\n    def _adjust_path(self, path):\n        return os.path.realpath(path)\n\n    def _make_path(self, resource_name):\n        # Issue #50: need to preserve type of path on Python 2.x\n        # like os.path._get_sep\n        if isinstance(resource_name, bytes):    # should only happen on 2.x\n            sep = b'/'\n        else:\n            sep = '/'\n        parts = resource_name.split(sep)\n        parts.insert(0, self.base)\n        result = os.path.join(*parts)\n        return self._adjust_path(result)\n\n    def _find(self, path):\n        return os.path.exists(path)\n\n    def get_cache_info(self, resource):\n        return None, resource.path\n\n    def find(self, resource_name):\n        path = self._make_path(resource_name)\n        if not self._find(path):\n            result = None\n        else:\n            if self._is_directory(path):\n                result = ResourceContainer(self, resource_name)\n            else:\n                result = Resource(self, resource_name)\n            result.path = path\n        return result\n\n    def get_stream(self, resource):\n        return open(resource.path, 'rb')\n\n    def get_bytes(self, resource):\n        with open(resource.path, 'rb') as f:\n            return f.read()\n\n    def get_size(self, resource):\n        return os.path.getsize(resource.path)\n\n    def get_resources(self, resource):\n        def allowed(f):\n            return (f != '__pycache__' and not\n                    f.endswith(self.skipped_extensions))\n        return set([f for f in os.listdir(resource.path) if allowed(f)])\n\n    def is_container(self, resource):\n        return self._is_directory(resource.path)\n\n    _is_directory = staticmethod(os.path.isdir)\n\n    def iterator(self, resource_name):\n        resource = self.find(resource_name)\n        if resource is not None:\n            todo = [resource]\n            while todo:\n                resource = todo.pop(0)\n                yield resource\n                if resource.is_container:\n                    rname = resource.name\n                    for name in resource.resources:\n                        if not rname:\n                            new_name = name\n                        else:\n                            new_name = '/'.join([rname, name])\n                        child = self.find(new_name)\n                        if child.is_container:\n                            todo.append(child)\n                        else:\n                            yield child\n\n\nclass ZipResourceFinder(ResourceFinder):\n    \"\"\"\n    Resource finder for resources in .zip files.\n    \"\"\"\n    def __init__(self, module):\n        super(ZipResourceFinder, self).__init__(module)\n        archive = self.loader.archive\n        self.prefix_len = 1 + len(archive)\n        # PyPy doesn't have a _files attr on zipimporter, and you can't set one\n        if hasattr(self.loader, '_files'):\n            self._files = self.loader._files\n        else:\n            self._files = zipimport._zip_directory_cache[archive]\n        self.index = sorted(self._files)\n\n    def _adjust_path(self, path):\n        return path\n\n    def _find(self, path):\n        path = path[self.prefix_len:]\n        if path in self._files:\n            result = True\n        else:\n            if path and path[-1] != os.sep:\n                path = path + os.sep\n            i = bisect.bisect(self.index, path)\n            try:\n                result = self.index[i].startswith(path)\n            except IndexError:\n                result = False\n        if not result:\n            logger.debug('_find failed: %r %r', path, self.loader.prefix)\n        else:\n            logger.debug('_find worked: %r %r', path, self.loader.prefix)\n        return result\n\n    def get_cache_info(self, resource):\n        prefix = self.loader.archive\n        path = resource.path[1 + len(prefix):]\n        return prefix, path\n\n    def get_bytes(self, resource):\n        return self.loader.get_data(resource.path)\n\n    def get_stream(self, resource):\n        return io.BytesIO(self.get_bytes(resource))\n\n    def get_size(self, resource):\n        path = resource.path[self.prefix_len:]\n        return self._files[path][3]\n\n    def get_resources(self, resource):\n        path = resource.path[self.prefix_len:]\n        if path and path[-1] != os.sep:\n            path += os.sep\n        plen = len(path)\n        result = set()\n        i = bisect.bisect(self.index, path)\n        while i < len(self.index):\n            if not self.index[i].startswith(path):\n                break\n            s = self.index[i][plen:]\n            result.add(s.split(os.sep, 1)[0])   # only immediate children\n            i += 1\n        return result\n\n    def _is_directory(self, path):\n        path = path[self.prefix_len:]\n        if path and path[-1] != os.sep:\n            path += os.sep\n        i = bisect.bisect(self.index, path)\n        try:\n            result = self.index[i].startswith(path)\n        except IndexError:\n            result = False\n        return result\n\n\n_finder_registry = {\n    type(None): ResourceFinder,\n    zipimport.zipimporter: ZipResourceFinder\n}\n\ntry:\n    # In Python 3.6, _frozen_importlib -> _frozen_importlib_external\n    try:\n        import _frozen_importlib_external as _fi\n    except ImportError:\n        import _frozen_importlib as _fi\n    _finder_registry[_fi.SourceFileLoader] = ResourceFinder\n    _finder_registry[_fi.FileFinder] = ResourceFinder\n    # See issue #146\n    _finder_registry[_fi.SourcelessFileLoader] = ResourceFinder\n    del _fi\nexcept (ImportError, AttributeError):\n    pass\n\n\ndef register_finder(loader, finder_maker):\n    _finder_registry[type(loader)] = finder_maker\n\n\n_finder_cache = {}\n\n\ndef finder(package):\n    \"\"\"\n    Return a resource finder for a package.\n    :param package: The name of the package.\n    :return: A :class:`ResourceFinder` instance for the package.\n    \"\"\"\n    if package in _finder_cache:\n        result = _finder_cache[package]\n    else:\n        if package not in sys.modules:\n            __import__(package)\n        module = sys.modules[package]\n        path = getattr(module, '__path__', None)\n        if path is None:\n            raise DistlibException('You cannot get a finder for a module, '\n                                   'only for a package')\n        loader = getattr(module, '__loader__', None)\n        finder_maker = _finder_registry.get(type(loader))\n        if finder_maker is None:\n            raise DistlibException('Unable to locate finder for %r' % package)\n        result = finder_maker(module)\n        _finder_cache[package] = result\n    return result\n\n\n_dummy_module = types.ModuleType(str('__dummy__'))\n\n\ndef finder_for_path(path):\n    \"\"\"\n    Return a resource finder for a path, which should represent a container.\n\n    :param path: The path.\n    :return: A :class:`ResourceFinder` instance for the path.\n    \"\"\"\n    result = None\n    # calls any path hooks, gets importer into cache\n    pkgutil.get_importer(path)\n    loader = sys.path_importer_cache.get(path)\n    finder = _finder_registry.get(type(loader))\n    if finder:\n        module = _dummy_module\n        module.__file__ = os.path.join(path, '')\n        module.__loader__ = loader\n        result = finder(module)\n    return result\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distlib/scripts.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013-2015 Vinay Sajip.\n# Licensed to the Python Software Foundation under a contributor agreement.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\nfrom io import BytesIO\nimport logging\nimport os\nimport re\nimport struct\nimport sys\nimport time\nfrom zipfile import ZipInfo\n\nfrom .compat import sysconfig, detect_encoding, ZipFile\nfrom .resources import finder\nfrom .util import (FileOperator, get_export_entry, convert_path,\n                   get_executable, get_platform, in_venv)\n\nlogger = logging.getLogger(__name__)\n\n_DEFAULT_MANIFEST = '''\n<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n <assemblyIdentity version=\"1.0.0.0\"\n processorArchitecture=\"X86\"\n name=\"%s\"\n type=\"win32\"/>\n\n <!-- Identify the application security requirements. -->\n <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n <security>\n <requestedPrivileges>\n <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n </requestedPrivileges>\n </security>\n </trustInfo>\n</assembly>'''.strip()\n\n# check if Python is called on the first line with this expression\nFIRST_LINE_RE = re.compile(b'^#!.*pythonw?[0-9.]*([ \\t].*)?$')\nSCRIPT_TEMPLATE = r'''# -*- coding: utf-8 -*-\nimport re\nimport sys\nfrom %(module)s import %(import_name)s\nif __name__ == '__main__':\n    sys.argv[0] = re.sub(r'(-script\\.pyw|\\.exe)?$', '', sys.argv[0])\n    sys.exit(%(func)s())\n'''\n\n\ndef enquote_executable(executable):\n    if ' ' in executable:\n        # make sure we quote only the executable in case of env\n        # for example /usr/bin/env \"/dir with spaces/bin/jython\"\n        # instead of \"/usr/bin/env /dir with spaces/bin/jython\"\n        # otherwise whole\n        if executable.startswith('/usr/bin/env '):\n            env, _executable = executable.split(' ', 1)\n            if ' ' in _executable and not _executable.startswith('\"'):\n                executable = '%s \"%s\"' % (env, _executable)\n        else:\n            if not executable.startswith('\"'):\n                executable = '\"%s\"' % executable\n    return executable\n\n# Keep the old name around (for now), as there is at least one project using it!\n_enquote_executable = enquote_executable\n\nclass ScriptMaker(object):\n    \"\"\"\n    A class to copy or create scripts from source scripts or callable\n    specifications.\n    \"\"\"\n    script_template = SCRIPT_TEMPLATE\n\n    executable = None  # for shebangs\n\n    def __init__(self, source_dir, target_dir, add_launchers=True,\n                 dry_run=False, fileop=None):\n        self.source_dir = source_dir\n        self.target_dir = target_dir\n        self.add_launchers = add_launchers\n        self.force = False\n        self.clobber = False\n        # It only makes sense to set mode bits on POSIX.\n        self.set_mode = (os.name == 'posix') or (os.name == 'java' and\n                                                 os._name == 'posix')\n        self.variants = set(('', 'X.Y'))\n        self._fileop = fileop or FileOperator(dry_run)\n\n        self._is_nt = os.name == 'nt' or (\n            os.name == 'java' and os._name == 'nt')\n        self.version_info = sys.version_info\n\n    def _get_alternate_executable(self, executable, options):\n        if options.get('gui', False) and self._is_nt:  # pragma: no cover\n            dn, fn = os.path.split(executable)\n            fn = fn.replace('python', 'pythonw')\n            executable = os.path.join(dn, fn)\n        return executable\n\n    if sys.platform.startswith('java'):  # pragma: no cover\n        def _is_shell(self, executable):\n            \"\"\"\n            Determine if the specified executable is a script\n            (contains a #! line)\n            \"\"\"\n            try:\n                with open(executable) as fp:\n                    return fp.read(2) == '#!'\n            except (OSError, IOError):\n                logger.warning('Failed to open %s', executable)\n                return False\n\n        def _fix_jython_executable(self, executable):\n            if self._is_shell(executable):\n                # Workaround for Jython is not needed on Linux systems.\n                import java\n\n                if java.lang.System.getProperty('os.name') == 'Linux':\n                    return executable\n            elif executable.lower().endswith('jython.exe'):\n                # Use wrapper exe for Jython on Windows\n                return executable\n            return '/usr/bin/env %s' % executable\n\n    def _build_shebang(self, executable, post_interp):\n        \"\"\"\n        Build a shebang line. In the simple case (on Windows, or a shebang line\n        which is not too long or contains spaces) use a simple formulation for\n        the shebang. Otherwise, use /bin/sh as the executable, with a contrived\n        shebang which allows the script to run either under Python or sh, using\n        suitable quoting. Thanks to Harald Nordgren for his input.\n\n        See also: http://www.in-ulm.de/~mascheck/various/shebang/#length\n                  https://hg.mozilla.org/mozilla-central/file/tip/mach\n        \"\"\"\n        if os.name != 'posix':\n            simple_shebang = True\n        else:\n            # Add 3 for '#!' prefix and newline suffix.\n            shebang_length = len(executable) + len(post_interp) + 3\n            if sys.platform == 'darwin':\n                max_shebang_length = 512\n            else:\n                max_shebang_length = 127\n            simple_shebang = ((b' ' not in executable) and\n                              (shebang_length <= max_shebang_length))\n\n        if simple_shebang:\n            result = b'#!' + executable + post_interp + b'\\n'\n        else:\n            result = b'#!/bin/sh\\n'\n            result += b\"'''exec' \" + executable + post_interp + b' \"$0\" \"$@\"\\n'\n            result += b\"' '''\"\n        return result\n\n    def _get_shebang(self, encoding, post_interp=b'', options=None):\n        enquote = True\n        if self.executable:\n            executable = self.executable\n            enquote = False     # assume this will be taken care of\n        elif not sysconfig.is_python_build():\n            executable = get_executable()\n        elif in_venv():  # pragma: no cover\n            executable = os.path.join(sysconfig.get_path('scripts'),\n                            'python%s' % sysconfig.get_config_var('EXE'))\n        else:  # pragma: no cover\n            executable = os.path.join(\n                sysconfig.get_config_var('BINDIR'),\n               'python%s%s' % (sysconfig.get_config_var('VERSION'),\n                               sysconfig.get_config_var('EXE')))\n            if not os.path.isfile(executable):\n                # for Python builds from source on Windows, no Python executables with\n                # a version suffix are created, so we use python.exe\n                executable = os.path.join(sysconfig.get_config_var('BINDIR'),\n                                'python%s' % (sysconfig.get_config_var('EXE')))\n        if options:\n            executable = self._get_alternate_executable(executable, options)\n\n        if sys.platform.startswith('java'):  # pragma: no cover\n            executable = self._fix_jython_executable(executable)\n\n        # Normalise case for Windows - COMMENTED OUT\n        # executable = os.path.normcase(executable)\n        # N.B. The normalising operation above has been commented out: See\n        # issue #124. Although paths in Windows are generally case-insensitive,\n        # they aren't always. For example, a path containing a ẞ (which is a\n        # LATIN CAPITAL LETTER SHARP S - U+1E9E) is normcased to ß (which is a\n        # LATIN SMALL LETTER SHARP S' - U+00DF). The two are not considered by\n        # Windows as equivalent in path names.\n\n        # If the user didn't specify an executable, it may be necessary to\n        # cater for executable paths with spaces (not uncommon on Windows)\n        if enquote:\n            executable = enquote_executable(executable)\n        # Issue #51: don't use fsencode, since we later try to\n        # check that the shebang is decodable using utf-8.\n        executable = executable.encode('utf-8')\n        # in case of IronPython, play safe and enable frames support\n        if (sys.platform == 'cli' and '-X:Frames' not in post_interp\n            and '-X:FullFrames' not in post_interp):  # pragma: no cover\n            post_interp += b' -X:Frames'\n        shebang = self._build_shebang(executable, post_interp)\n        # Python parser starts to read a script using UTF-8 until\n        # it gets a #coding:xxx cookie. The shebang has to be the\n        # first line of a file, the #coding:xxx cookie cannot be\n        # written before. So the shebang has to be decodable from\n        # UTF-8.\n        try:\n            shebang.decode('utf-8')\n        except UnicodeDecodeError:  # pragma: no cover\n            raise ValueError(\n                'The shebang (%r) is not decodable from utf-8' % shebang)\n        # If the script is encoded to a custom encoding (use a\n        # #coding:xxx cookie), the shebang has to be decodable from\n        # the script encoding too.\n        if encoding != 'utf-8':\n            try:\n                shebang.decode(encoding)\n            except UnicodeDecodeError:  # pragma: no cover\n                raise ValueError(\n                    'The shebang (%r) is not decodable '\n                    'from the script encoding (%r)' % (shebang, encoding))\n        return shebang\n\n    def _get_script_text(self, entry):\n        return self.script_template % dict(module=entry.prefix,\n                                           import_name=entry.suffix.split('.')[0],\n                                           func=entry.suffix)\n\n    manifest = _DEFAULT_MANIFEST\n\n    def get_manifest(self, exename):\n        base = os.path.basename(exename)\n        return self.manifest % base\n\n    def _write_script(self, names, shebang, script_bytes, filenames, ext):\n        use_launcher = self.add_launchers and self._is_nt\n        linesep = os.linesep.encode('utf-8')\n        if not shebang.endswith(linesep):\n            shebang += linesep\n        if not use_launcher:\n            script_bytes = shebang + script_bytes\n        else:  # pragma: no cover\n            if ext == 'py':\n                launcher = self._get_launcher('t')\n            else:\n                launcher = self._get_launcher('w')\n            stream = BytesIO()\n            with ZipFile(stream, 'w') as zf:\n                source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH')\n                if source_date_epoch:\n                    date_time = time.gmtime(int(source_date_epoch))[:6]\n                    zinfo = ZipInfo(filename='__main__.py', date_time=date_time)\n                    zf.writestr(zinfo, script_bytes)\n                else:\n                    zf.writestr('__main__.py', script_bytes)\n            zip_data = stream.getvalue()\n            script_bytes = launcher + shebang + zip_data\n        for name in names:\n            outname = os.path.join(self.target_dir, name)\n            if use_launcher:  # pragma: no cover\n                n, e = os.path.splitext(outname)\n                if e.startswith('.py'):\n                    outname = n\n                outname = '%s.exe' % outname\n                try:\n                    self._fileop.write_binary_file(outname, script_bytes)\n                except Exception:\n                    # Failed writing an executable - it might be in use.\n                    logger.warning('Failed to write executable - trying to '\n                                   'use .deleteme logic')\n                    dfname = '%s.deleteme' % outname\n                    if os.path.exists(dfname):\n                        os.remove(dfname)       # Not allowed to fail here\n                    os.rename(outname, dfname)  # nor here\n                    self._fileop.write_binary_file(outname, script_bytes)\n                    logger.debug('Able to replace executable using '\n                                 '.deleteme logic')\n                    try:\n                        os.remove(dfname)\n                    except Exception:\n                        pass    # still in use - ignore error\n            else:\n                if self._is_nt and not outname.endswith('.' + ext):  # pragma: no cover\n                    outname = '%s.%s' % (outname, ext)\n                if os.path.exists(outname) and not self.clobber:\n                    logger.warning('Skipping existing file %s', outname)\n                    continue\n                self._fileop.write_binary_file(outname, script_bytes)\n                if self.set_mode:\n                    self._fileop.set_executable_mode([outname])\n            filenames.append(outname)\n\n    variant_separator = '-'\n\n    def get_script_filenames(self, name):\n        result = set()\n        if '' in self.variants:\n            result.add(name)\n        if 'X' in self.variants:\n            result.add('%s%s' % (name, self.version_info[0]))\n        if 'X.Y' in self.variants:\n            result.add('%s%s%s.%s' % (name, self.variant_separator,\n                                      self.version_info[0], self.version_info[1]))\n        return result\n\n    def _make_script(self, entry, filenames, options=None):\n        post_interp = b''\n        if options:\n            args = options.get('interpreter_args', [])\n            if args:\n                args = ' %s' % ' '.join(args)\n                post_interp = args.encode('utf-8')\n        shebang = self._get_shebang('utf-8', post_interp, options=options)\n        script = self._get_script_text(entry).encode('utf-8')\n        scriptnames = self.get_script_filenames(entry.name)\n        if options and options.get('gui', False):\n            ext = 'pyw'\n        else:\n            ext = 'py'\n        self._write_script(scriptnames, shebang, script, filenames, ext)\n\n    def _copy_script(self, script, filenames):\n        adjust = False\n        script = os.path.join(self.source_dir, convert_path(script))\n        outname = os.path.join(self.target_dir, os.path.basename(script))\n        if not self.force and not self._fileop.newer(script, outname):\n            logger.debug('not copying %s (up-to-date)', script)\n            return\n\n        # Always open the file, but ignore failures in dry-run mode --\n        # that way, we'll get accurate feedback if we can read the\n        # script.\n        try:\n            f = open(script, 'rb')\n        except IOError:  # pragma: no cover\n            if not self.dry_run:\n                raise\n            f = None\n        else:\n            first_line = f.readline()\n            if not first_line:  # pragma: no cover\n                logger.warning('%s is an empty file (skipping)', script)\n                return\n\n            match = FIRST_LINE_RE.match(first_line.replace(b'\\r\\n', b'\\n'))\n            if match:\n                adjust = True\n                post_interp = match.group(1) or b''\n\n        if not adjust:\n            if f:\n                f.close()\n            self._fileop.copy_file(script, outname)\n            if self.set_mode:\n                self._fileop.set_executable_mode([outname])\n            filenames.append(outname)\n        else:\n            logger.info('copying and adjusting %s -> %s', script,\n                        self.target_dir)\n            if not self._fileop.dry_run:\n                encoding, lines = detect_encoding(f.readline)\n                f.seek(0)\n                shebang = self._get_shebang(encoding, post_interp)\n                if b'pythonw' in first_line:  # pragma: no cover\n                    ext = 'pyw'\n                else:\n                    ext = 'py'\n                n = os.path.basename(outname)\n                self._write_script([n], shebang, f.read(), filenames, ext)\n            if f:\n                f.close()\n\n    @property\n    def dry_run(self):\n        return self._fileop.dry_run\n\n    @dry_run.setter\n    def dry_run(self, value):\n        self._fileop.dry_run = value\n\n    if os.name == 'nt' or (os.name == 'java' and os._name == 'nt'):  # pragma: no cover\n        # Executable launcher support.\n        # Launchers are from https://bitbucket.org/vinay.sajip/simple_launcher/\n\n        def _get_launcher(self, kind):\n            if struct.calcsize('P') == 8:   # 64-bit\n                bits = '64'\n            else:\n                bits = '32'\n            platform_suffix = '-arm' if get_platform() == 'win-arm64' else ''\n            name = '%s%s%s.exe' % (kind, bits, platform_suffix)\n            # Issue 31: don't hardcode an absolute package name, but\n            # determine it relative to the current package\n            distlib_package = __name__.rsplit('.', 1)[0]\n            resource = finder(distlib_package).find(name)\n            if not resource:\n                msg = ('Unable to find resource %s in package %s' % (name,\n                       distlib_package))\n                raise ValueError(msg)\n            return resource.bytes\n\n    # Public API follows\n\n    def make(self, specification, options=None):\n        \"\"\"\n        Make a script.\n\n        :param specification: The specification, which is either a valid export\n                              entry specification (to make a script from a\n                              callable) or a filename (to make a script by\n                              copying from a source location).\n        :param options: A dictionary of options controlling script generation.\n        :return: A list of all absolute pathnames written to.\n        \"\"\"\n        filenames = []\n        entry = get_export_entry(specification)\n        if entry is None:\n            self._copy_script(specification, filenames)\n        else:\n            self._make_script(entry, filenames, options=options)\n        return filenames\n\n    def make_multiple(self, specifications, options=None):\n        \"\"\"\n        Take a list of specifications and make scripts from them,\n        :param specifications: A list of specifications.\n        :return: A list of all absolute pathnames written to,\n        \"\"\"\n        filenames = []\n        for specification in specifications:\n            filenames.extend(self.make(specification, options))\n        return filenames\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distlib/util.py",
    "content": "#\n# Copyright (C) 2012-2021 The Python Software Foundation.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\nimport codecs\nfrom collections import deque\nimport contextlib\nimport csv\nfrom glob import iglob as std_iglob\nimport io\nimport json\nimport logging\nimport os\nimport py_compile\nimport re\nimport socket\ntry:\n    import ssl\nexcept ImportError:  # pragma: no cover\n    ssl = None\nimport subprocess\nimport sys\nimport tarfile\nimport tempfile\nimport textwrap\n\ntry:\n    import threading\nexcept ImportError:  # pragma: no cover\n    import dummy_threading as threading\nimport time\n\nfrom . import DistlibException\nfrom .compat import (string_types, text_type, shutil, raw_input, StringIO,\n                     cache_from_source, urlopen, urljoin, httplib, xmlrpclib,\n                     splittype, HTTPHandler, BaseConfigurator, valid_ident,\n                     Container, configparser, URLError, ZipFile, fsdecode,\n                     unquote, urlparse)\n\nlogger = logging.getLogger(__name__)\n\n#\n# Requirement parsing code as per PEP 508\n#\n\nIDENTIFIER = re.compile(r'^([\\w\\.-]+)\\s*')\nVERSION_IDENTIFIER = re.compile(r'^([\\w\\.*+-]+)\\s*')\nCOMPARE_OP = re.compile(r'^(<=?|>=?|={2,3}|[~!]=)\\s*')\nMARKER_OP = re.compile(r'^((<=?)|(>=?)|={2,3}|[~!]=|in|not\\s+in)\\s*')\nOR = re.compile(r'^or\\b\\s*')\nAND = re.compile(r'^and\\b\\s*')\nNON_SPACE = re.compile(r'(\\S+)\\s*')\nSTRING_CHUNK = re.compile(r'([\\s\\w\\.{}()*+#:;,/?!~`@$%^&=|<>\\[\\]-]+)')\n\n\ndef parse_marker(marker_string):\n    \"\"\"\n    Parse a marker string and return a dictionary containing a marker expression.\n\n    The dictionary will contain keys \"op\", \"lhs\" and \"rhs\" for non-terminals in\n    the expression grammar, or strings. A string contained in quotes is to be\n    interpreted as a literal string, and a string not contained in quotes is a\n    variable (such as os_name).\n    \"\"\"\n    def marker_var(remaining):\n        # either identifier, or literal string\n        m = IDENTIFIER.match(remaining)\n        if m:\n            result = m.groups()[0]\n            remaining = remaining[m.end():]\n        elif not remaining:\n            raise SyntaxError('unexpected end of input')\n        else:\n            q = remaining[0]\n            if q not in '\\'\"':\n                raise SyntaxError('invalid expression: %s' % remaining)\n            oq = '\\'\"'.replace(q, '')\n            remaining = remaining[1:]\n            parts = [q]\n            while remaining:\n                # either a string chunk, or oq, or q to terminate\n                if remaining[0] == q:\n                    break\n                elif remaining[0] == oq:\n                    parts.append(oq)\n                    remaining = remaining[1:]\n                else:\n                    m = STRING_CHUNK.match(remaining)\n                    if not m:\n                        raise SyntaxError('error in string literal: %s' % remaining)\n                    parts.append(m.groups()[0])\n                    remaining = remaining[m.end():]\n            else:\n                s = ''.join(parts)\n                raise SyntaxError('unterminated string: %s' % s)\n            parts.append(q)\n            result = ''.join(parts)\n            remaining = remaining[1:].lstrip() # skip past closing quote\n        return result, remaining\n\n    def marker_expr(remaining):\n        if remaining and remaining[0] == '(':\n            result, remaining = marker(remaining[1:].lstrip())\n            if remaining[0] != ')':\n                raise SyntaxError('unterminated parenthesis: %s' % remaining)\n            remaining = remaining[1:].lstrip()\n        else:\n            lhs, remaining = marker_var(remaining)\n            while remaining:\n                m = MARKER_OP.match(remaining)\n                if not m:\n                    break\n                op = m.groups()[0]\n                remaining = remaining[m.end():]\n                rhs, remaining = marker_var(remaining)\n                lhs = {'op': op, 'lhs': lhs, 'rhs': rhs}\n            result = lhs\n        return result, remaining\n\n    def marker_and(remaining):\n        lhs, remaining = marker_expr(remaining)\n        while remaining:\n            m = AND.match(remaining)\n            if not m:\n                break\n            remaining = remaining[m.end():]\n            rhs, remaining = marker_expr(remaining)\n            lhs = {'op': 'and', 'lhs': lhs, 'rhs': rhs}\n        return lhs, remaining\n\n    def marker(remaining):\n        lhs, remaining = marker_and(remaining)\n        while remaining:\n            m = OR.match(remaining)\n            if not m:\n                break\n            remaining = remaining[m.end():]\n            rhs, remaining = marker_and(remaining)\n            lhs = {'op': 'or', 'lhs': lhs, 'rhs': rhs}\n        return lhs, remaining\n\n    return marker(marker_string)\n\n\ndef parse_requirement(req):\n    \"\"\"\n    Parse a requirement passed in as a string. Return a Container\n    whose attributes contain the various parts of the requirement.\n    \"\"\"\n    remaining = req.strip()\n    if not remaining or remaining.startswith('#'):\n        return None\n    m = IDENTIFIER.match(remaining)\n    if not m:\n        raise SyntaxError('name expected: %s' % remaining)\n    distname = m.groups()[0]\n    remaining = remaining[m.end():]\n    extras = mark_expr = versions = uri = None\n    if remaining and remaining[0] == '[':\n        i = remaining.find(']', 1)\n        if i < 0:\n            raise SyntaxError('unterminated extra: %s' % remaining)\n        s = remaining[1:i]\n        remaining = remaining[i + 1:].lstrip()\n        extras = []\n        while s:\n            m = IDENTIFIER.match(s)\n            if not m:\n                raise SyntaxError('malformed extra: %s' % s)\n            extras.append(m.groups()[0])\n            s = s[m.end():]\n            if not s:\n                break\n            if s[0] != ',':\n                raise SyntaxError('comma expected in extras: %s' % s)\n            s = s[1:].lstrip()\n        if not extras:\n            extras = None\n    if remaining:\n        if remaining[0] == '@':\n            # it's a URI\n            remaining = remaining[1:].lstrip()\n            m = NON_SPACE.match(remaining)\n            if not m:\n                raise SyntaxError('invalid URI: %s' % remaining)\n            uri = m.groups()[0]\n            t = urlparse(uri)\n            # there are issues with Python and URL parsing, so this test\n            # is a bit crude. See bpo-20271, bpo-23505. Python doesn't\n            # always parse invalid URLs correctly - it should raise\n            # exceptions for malformed URLs\n            if not (t.scheme and t.netloc):\n                raise SyntaxError('Invalid URL: %s' % uri)\n            remaining = remaining[m.end():].lstrip()\n        else:\n\n            def get_versions(ver_remaining):\n                \"\"\"\n                Return a list of operator, version tuples if any are\n                specified, else None.\n                \"\"\"\n                m = COMPARE_OP.match(ver_remaining)\n                versions = None\n                if m:\n                    versions = []\n                    while True:\n                        op = m.groups()[0]\n                        ver_remaining = ver_remaining[m.end():]\n                        m = VERSION_IDENTIFIER.match(ver_remaining)\n                        if not m:\n                            raise SyntaxError('invalid version: %s' % ver_remaining)\n                        v = m.groups()[0]\n                        versions.append((op, v))\n                        ver_remaining = ver_remaining[m.end():]\n                        if not ver_remaining or ver_remaining[0] != ',':\n                            break\n                        ver_remaining = ver_remaining[1:].lstrip()\n                        # Some packages have a trailing comma which would break things\n                        # See issue #148\n                        if not ver_remaining:\n                            break\n                        m = COMPARE_OP.match(ver_remaining)\n                        if not m:\n                            raise SyntaxError('invalid constraint: %s' % ver_remaining)\n                    if not versions:\n                        versions = None\n                return versions, ver_remaining\n\n            if remaining[0] != '(':\n                versions, remaining = get_versions(remaining)\n            else:\n                i = remaining.find(')', 1)\n                if i < 0:\n                    raise SyntaxError('unterminated parenthesis: %s' % remaining)\n                s = remaining[1:i]\n                remaining = remaining[i + 1:].lstrip()\n                # As a special diversion from PEP 508, allow a version number\n                # a.b.c in parentheses as a synonym for ~= a.b.c (because this\n                # is allowed in earlier PEPs)\n                if COMPARE_OP.match(s):\n                    versions, _ = get_versions(s)\n                else:\n                    m = VERSION_IDENTIFIER.match(s)\n                    if not m:\n                        raise SyntaxError('invalid constraint: %s' % s)\n                    v = m.groups()[0]\n                    s = s[m.end():].lstrip()\n                    if s:\n                        raise SyntaxError('invalid constraint: %s' % s)\n                    versions = [('~=', v)]\n\n    if remaining:\n        if remaining[0] != ';':\n            raise SyntaxError('invalid requirement: %s' % remaining)\n        remaining = remaining[1:].lstrip()\n\n        mark_expr, remaining = parse_marker(remaining)\n\n    if remaining and remaining[0] != '#':\n        raise SyntaxError('unexpected trailing data: %s' % remaining)\n\n    if not versions:\n        rs = distname\n    else:\n        rs = '%s %s' % (distname, ', '.join(['%s %s' % con for con in versions]))\n    return Container(name=distname, extras=extras, constraints=versions,\n                     marker=mark_expr, url=uri, requirement=rs)\n\n\ndef get_resources_dests(resources_root, rules):\n    \"\"\"Find destinations for resources files\"\"\"\n\n    def get_rel_path(root, path):\n        # normalizes and returns a lstripped-/-separated path\n        root = root.replace(os.path.sep, '/')\n        path = path.replace(os.path.sep, '/')\n        assert path.startswith(root)\n        return path[len(root):].lstrip('/')\n\n    destinations = {}\n    for base, suffix, dest in rules:\n        prefix = os.path.join(resources_root, base)\n        for abs_base in iglob(prefix):\n            abs_glob = os.path.join(abs_base, suffix)\n            for abs_path in iglob(abs_glob):\n                resource_file = get_rel_path(resources_root, abs_path)\n                if dest is None:  # remove the entry if it was here\n                    destinations.pop(resource_file, None)\n                else:\n                    rel_path = get_rel_path(abs_base, abs_path)\n                    rel_dest = dest.replace(os.path.sep, '/').rstrip('/')\n                    destinations[resource_file] = rel_dest + '/' + rel_path\n    return destinations\n\n\ndef in_venv():\n    if hasattr(sys, 'real_prefix'):\n        # virtualenv venvs\n        result = True\n    else:\n        # PEP 405 venvs\n        result = sys.prefix != getattr(sys, 'base_prefix', sys.prefix)\n    return result\n\n\ndef get_executable():\n# The __PYVENV_LAUNCHER__ dance is apparently no longer needed, as\n# changes to the stub launcher mean that sys.executable always points\n# to the stub on OS X\n#    if sys.platform == 'darwin' and ('__PYVENV_LAUNCHER__'\n#                                     in os.environ):\n#        result =  os.environ['__PYVENV_LAUNCHER__']\n#    else:\n#        result = sys.executable\n#    return result\n    # Avoid normcasing: see issue #143\n    # result = os.path.normcase(sys.executable)\n    result = sys.executable\n    if not isinstance(result, text_type):\n        result = fsdecode(result)\n    return result\n\n\ndef proceed(prompt, allowed_chars, error_prompt=None, default=None):\n    p = prompt\n    while True:\n        s = raw_input(p)\n        p = prompt\n        if not s and default:\n            s = default\n        if s:\n            c = s[0].lower()\n            if c in allowed_chars:\n                break\n            if error_prompt:\n                p = '%c: %s\\n%s' % (c, error_prompt, prompt)\n    return c\n\n\ndef extract_by_key(d, keys):\n    if isinstance(keys, string_types):\n        keys = keys.split()\n    result = {}\n    for key in keys:\n        if key in d:\n            result[key] = d[key]\n    return result\n\ndef read_exports(stream):\n    if sys.version_info[0] >= 3:\n        # needs to be a text stream\n        stream = codecs.getreader('utf-8')(stream)\n    # Try to load as JSON, falling back on legacy format\n    data = stream.read()\n    stream = StringIO(data)\n    try:\n        jdata = json.load(stream)\n        result = jdata['extensions']['python.exports']['exports']\n        for group, entries in result.items():\n            for k, v in entries.items():\n                s = '%s = %s' % (k, v)\n                entry = get_export_entry(s)\n                assert entry is not None\n                entries[k] = entry\n        return result\n    except Exception:\n        stream.seek(0, 0)\n\n    def read_stream(cp, stream):\n        if hasattr(cp, 'read_file'):\n            cp.read_file(stream)\n        else:\n            cp.readfp(stream)\n\n    cp = configparser.ConfigParser()\n    try:\n        read_stream(cp, stream)\n    except configparser.MissingSectionHeaderError:\n        stream.close()\n        data = textwrap.dedent(data)\n        stream = StringIO(data)\n        read_stream(cp, stream)\n\n    result = {}\n    for key in cp.sections():\n        result[key] = entries = {}\n        for name, value in cp.items(key):\n            s = '%s = %s' % (name, value)\n            entry = get_export_entry(s)\n            assert entry is not None\n            #entry.dist = self\n            entries[name] = entry\n    return result\n\n\ndef write_exports(exports, stream):\n    if sys.version_info[0] >= 3:\n        # needs to be a text stream\n        stream = codecs.getwriter('utf-8')(stream)\n    cp = configparser.ConfigParser()\n    for k, v in exports.items():\n        # TODO check k, v for valid values\n        cp.add_section(k)\n        for entry in v.values():\n            if entry.suffix is None:\n                s = entry.prefix\n            else:\n                s = '%s:%s' % (entry.prefix, entry.suffix)\n            if entry.flags:\n                s = '%s [%s]' % (s, ', '.join(entry.flags))\n            cp.set(k, entry.name, s)\n    cp.write(stream)\n\n\n@contextlib.contextmanager\ndef tempdir():\n    td = tempfile.mkdtemp()\n    try:\n        yield td\n    finally:\n        shutil.rmtree(td)\n\n@contextlib.contextmanager\ndef chdir(d):\n    cwd = os.getcwd()\n    try:\n        os.chdir(d)\n        yield\n    finally:\n        os.chdir(cwd)\n\n\n@contextlib.contextmanager\ndef socket_timeout(seconds=15):\n    cto = socket.getdefaulttimeout()\n    try:\n        socket.setdefaulttimeout(seconds)\n        yield\n    finally:\n        socket.setdefaulttimeout(cto)\n\n\nclass cached_property(object):\n    def __init__(self, func):\n        self.func = func\n        #for attr in ('__name__', '__module__', '__doc__'):\n        #    setattr(self, attr, getattr(func, attr, None))\n\n    def __get__(self, obj, cls=None):\n        if obj is None:\n            return self\n        value = self.func(obj)\n        object.__setattr__(obj, self.func.__name__, value)\n        #obj.__dict__[self.func.__name__] = value = self.func(obj)\n        return value\n\ndef convert_path(pathname):\n    \"\"\"Return 'pathname' as a name that will work on the native filesystem.\n\n    The path is split on '/' and put back together again using the current\n    directory separator.  Needed because filenames in the setup script are\n    always supplied in Unix style, and have to be converted to the local\n    convention before we can actually use them in the filesystem.  Raises\n    ValueError on non-Unix-ish systems if 'pathname' either starts or\n    ends with a slash.\n    \"\"\"\n    if os.sep == '/':\n        return pathname\n    if not pathname:\n        return pathname\n    if pathname[0] == '/':\n        raise ValueError(\"path '%s' cannot be absolute\" % pathname)\n    if pathname[-1] == '/':\n        raise ValueError(\"path '%s' cannot end with '/'\" % pathname)\n\n    paths = pathname.split('/')\n    while os.curdir in paths:\n        paths.remove(os.curdir)\n    if not paths:\n        return os.curdir\n    return os.path.join(*paths)\n\n\nclass FileOperator(object):\n    def __init__(self, dry_run=False):\n        self.dry_run = dry_run\n        self.ensured = set()\n        self._init_record()\n\n    def _init_record(self):\n        self.record = False\n        self.files_written = set()\n        self.dirs_created = set()\n\n    def record_as_written(self, path):\n        if self.record:\n            self.files_written.add(path)\n\n    def newer(self, source, target):\n        \"\"\"Tell if the target is newer than the source.\n\n        Returns true if 'source' exists and is more recently modified than\n        'target', or if 'source' exists and 'target' doesn't.\n\n        Returns false if both exist and 'target' is the same age or younger\n        than 'source'. Raise PackagingFileError if 'source' does not exist.\n\n        Note that this test is not very accurate: files created in the same\n        second will have the same \"age\".\n        \"\"\"\n        if not os.path.exists(source):\n            raise DistlibException(\"file '%r' does not exist\" %\n                                   os.path.abspath(source))\n        if not os.path.exists(target):\n            return True\n\n        return os.stat(source).st_mtime > os.stat(target).st_mtime\n\n    def copy_file(self, infile, outfile, check=True):\n        \"\"\"Copy a file respecting dry-run and force flags.\n        \"\"\"\n        self.ensure_dir(os.path.dirname(outfile))\n        logger.info('Copying %s to %s', infile, outfile)\n        if not self.dry_run:\n            msg = None\n            if check:\n                if os.path.islink(outfile):\n                    msg = '%s is a symlink' % outfile\n                elif os.path.exists(outfile) and not os.path.isfile(outfile):\n                    msg = '%s is a non-regular file' % outfile\n            if msg:\n                raise ValueError(msg + ' which would be overwritten')\n            shutil.copyfile(infile, outfile)\n        self.record_as_written(outfile)\n\n    def copy_stream(self, instream, outfile, encoding=None):\n        assert not os.path.isdir(outfile)\n        self.ensure_dir(os.path.dirname(outfile))\n        logger.info('Copying stream %s to %s', instream, outfile)\n        if not self.dry_run:\n            if encoding is None:\n                outstream = open(outfile, 'wb')\n            else:\n                outstream = codecs.open(outfile, 'w', encoding=encoding)\n            try:\n                shutil.copyfileobj(instream, outstream)\n            finally:\n                outstream.close()\n        self.record_as_written(outfile)\n\n    def write_binary_file(self, path, data):\n        self.ensure_dir(os.path.dirname(path))\n        if not self.dry_run:\n            if os.path.exists(path):\n                os.remove(path)\n            with open(path, 'wb') as f:\n                f.write(data)\n        self.record_as_written(path)\n\n    def write_text_file(self, path, data, encoding):\n        self.write_binary_file(path, data.encode(encoding))\n\n    def set_mode(self, bits, mask, files):\n        if os.name == 'posix' or (os.name == 'java' and os._name == 'posix'):\n            # Set the executable bits (owner, group, and world) on\n            # all the files specified.\n            for f in files:\n                if self.dry_run:\n                    logger.info(\"changing mode of %s\", f)\n                else:\n                    mode = (os.stat(f).st_mode | bits) & mask\n                    logger.info(\"changing mode of %s to %o\", f, mode)\n                    os.chmod(f, mode)\n\n    set_executable_mode = lambda s, f: s.set_mode(0o555, 0o7777, f)\n\n    def ensure_dir(self, path):\n        path = os.path.abspath(path)\n        if path not in self.ensured and not os.path.exists(path):\n            self.ensured.add(path)\n            d, f = os.path.split(path)\n            self.ensure_dir(d)\n            logger.info('Creating %s' % path)\n            if not self.dry_run:\n                os.mkdir(path)\n            if self.record:\n                self.dirs_created.add(path)\n\n    def byte_compile(self, path, optimize=False, force=False, prefix=None, hashed_invalidation=False):\n        dpath = cache_from_source(path, not optimize)\n        logger.info('Byte-compiling %s to %s', path, dpath)\n        if not self.dry_run:\n            if force or self.newer(path, dpath):\n                if not prefix:\n                    diagpath = None\n                else:\n                    assert path.startswith(prefix)\n                    diagpath = path[len(prefix):]\n            compile_kwargs = {}\n            if hashed_invalidation and hasattr(py_compile, 'PycInvalidationMode'):\n                compile_kwargs['invalidation_mode'] = py_compile.PycInvalidationMode.CHECKED_HASH\n            py_compile.compile(path, dpath, diagpath, True, **compile_kwargs)     # raise error\n        self.record_as_written(dpath)\n        return dpath\n\n    def ensure_removed(self, path):\n        if os.path.exists(path):\n            if os.path.isdir(path) and not os.path.islink(path):\n                logger.debug('Removing directory tree at %s', path)\n                if not self.dry_run:\n                    shutil.rmtree(path)\n                if self.record:\n                    if path in self.dirs_created:\n                        self.dirs_created.remove(path)\n            else:\n                if os.path.islink(path):\n                    s = 'link'\n                else:\n                    s = 'file'\n                logger.debug('Removing %s %s', s, path)\n                if not self.dry_run:\n                    os.remove(path)\n                if self.record:\n                    if path in self.files_written:\n                        self.files_written.remove(path)\n\n    def is_writable(self, path):\n        result = False\n        while not result:\n            if os.path.exists(path):\n                result = os.access(path, os.W_OK)\n                break\n            parent = os.path.dirname(path)\n            if parent == path:\n                break\n            path = parent\n        return result\n\n    def commit(self):\n        \"\"\"\n        Commit recorded changes, turn off recording, return\n        changes.\n        \"\"\"\n        assert self.record\n        result = self.files_written, self.dirs_created\n        self._init_record()\n        return result\n\n    def rollback(self):\n        if not self.dry_run:\n            for f in list(self.files_written):\n                if os.path.exists(f):\n                    os.remove(f)\n            # dirs should all be empty now, except perhaps for\n            # __pycache__ subdirs\n            # reverse so that subdirs appear before their parents\n            dirs = sorted(self.dirs_created, reverse=True)\n            for d in dirs:\n                flist = os.listdir(d)\n                if flist:\n                    assert flist == ['__pycache__']\n                    sd = os.path.join(d, flist[0])\n                    os.rmdir(sd)\n                os.rmdir(d)     # should fail if non-empty\n        self._init_record()\n\ndef resolve(module_name, dotted_path):\n    if module_name in sys.modules:\n        mod = sys.modules[module_name]\n    else:\n        mod = __import__(module_name)\n    if dotted_path is None:\n        result = mod\n    else:\n        parts = dotted_path.split('.')\n        result = getattr(mod, parts.pop(0))\n        for p in parts:\n            result = getattr(result, p)\n    return result\n\n\nclass ExportEntry(object):\n    def __init__(self, name, prefix, suffix, flags):\n        self.name = name\n        self.prefix = prefix\n        self.suffix = suffix\n        self.flags = flags\n\n    @cached_property\n    def value(self):\n        return resolve(self.prefix, self.suffix)\n\n    def __repr__(self):  # pragma: no cover\n        return '<ExportEntry %s = %s:%s %s>' % (self.name, self.prefix,\n                                                self.suffix, self.flags)\n\n    def __eq__(self, other):\n        if not isinstance(other, ExportEntry):\n            result = False\n        else:\n            result = (self.name == other.name and\n                      self.prefix == other.prefix and\n                      self.suffix == other.suffix and\n                      self.flags == other.flags)\n        return result\n\n    __hash__ = object.__hash__\n\n\nENTRY_RE = re.compile(r'''(?P<name>(\\w|[-.+])+)\n                      \\s*=\\s*(?P<callable>(\\w+)([:\\.]\\w+)*)\n                      \\s*(\\[\\s*(?P<flags>[\\w-]+(=\\w+)?(,\\s*\\w+(=\\w+)?)*)\\s*\\])?\n                      ''', re.VERBOSE)\n\ndef get_export_entry(specification):\n    m = ENTRY_RE.search(specification)\n    if not m:\n        result = None\n        if '[' in specification or ']' in specification:\n            raise DistlibException(\"Invalid specification \"\n                                   \"'%s'\" % specification)\n    else:\n        d = m.groupdict()\n        name = d['name']\n        path = d['callable']\n        colons = path.count(':')\n        if colons == 0:\n            prefix, suffix = path, None\n        else:\n            if colons != 1:\n                raise DistlibException(\"Invalid specification \"\n                                       \"'%s'\" % specification)\n            prefix, suffix = path.split(':')\n        flags = d['flags']\n        if flags is None:\n            if '[' in specification or ']' in specification:\n                raise DistlibException(\"Invalid specification \"\n                                       \"'%s'\" % specification)\n            flags = []\n        else:\n            flags = [f.strip() for f in flags.split(',')]\n        result = ExportEntry(name, prefix, suffix, flags)\n    return result\n\n\ndef get_cache_base(suffix=None):\n    \"\"\"\n    Return the default base location for distlib caches. If the directory does\n    not exist, it is created. Use the suffix provided for the base directory,\n    and default to '.distlib' if it isn't provided.\n\n    On Windows, if LOCALAPPDATA is defined in the environment, then it is\n    assumed to be a directory, and will be the parent directory of the result.\n    On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home\n    directory - using os.expanduser('~') - will be the parent directory of\n    the result.\n\n    The result is just the directory '.distlib' in the parent directory as\n    determined above, or with the name specified with ``suffix``.\n    \"\"\"\n    if suffix is None:\n        suffix = '.distlib'\n    if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:\n        result = os.path.expandvars('$localappdata')\n    else:\n        # Assume posix, or old Windows\n        result = os.path.expanduser('~')\n    # we use 'isdir' instead of 'exists', because we want to\n    # fail if there's a file with that name\n    if os.path.isdir(result):\n        usable = os.access(result, os.W_OK)\n        if not usable:\n            logger.warning('Directory exists but is not writable: %s', result)\n    else:\n        try:\n            os.makedirs(result)\n            usable = True\n        except OSError:\n            logger.warning('Unable to create %s', result, exc_info=True)\n            usable = False\n    if not usable:\n        result = tempfile.mkdtemp()\n        logger.warning('Default location unusable, using %s', result)\n    return os.path.join(result, suffix)\n\n\ndef path_to_cache_dir(path):\n    \"\"\"\n    Convert an absolute path to a directory name for use in a cache.\n\n    The algorithm used is:\n\n    #. On Windows, any ``':'`` in the drive is replaced with ``'---'``.\n    #. Any occurrence of ``os.sep`` is replaced with ``'--'``.\n    #. ``'.cache'`` is appended.\n    \"\"\"\n    d, p = os.path.splitdrive(os.path.abspath(path))\n    if d:\n        d = d.replace(':', '---')\n    p = p.replace(os.sep, '--')\n    return d + p + '.cache'\n\n\ndef ensure_slash(s):\n    if not s.endswith('/'):\n        return s + '/'\n    return s\n\n\ndef parse_credentials(netloc):\n    username = password = None\n    if '@' in netloc:\n        prefix, netloc = netloc.rsplit('@', 1)\n        if ':' not in prefix:\n            username = prefix\n        else:\n            username, password = prefix.split(':', 1)\n    if username:\n        username = unquote(username)\n    if password:\n        password = unquote(password)\n    return username, password, netloc\n\n\ndef get_process_umask():\n    result = os.umask(0o22)\n    os.umask(result)\n    return result\n\ndef is_string_sequence(seq):\n    result = True\n    i = None\n    for i, s in enumerate(seq):\n        if not isinstance(s, string_types):\n            result = False\n            break\n    assert i is not None\n    return result\n\nPROJECT_NAME_AND_VERSION = re.compile('([a-z0-9_]+([.-][a-z_][a-z0-9_]*)*)-'\n                                      '([a-z0-9_.+-]+)', re.I)\nPYTHON_VERSION = re.compile(r'-py(\\d\\.?\\d?)')\n\n\ndef split_filename(filename, project_name=None):\n    \"\"\"\n    Extract name, version, python version from a filename (no extension)\n\n    Return name, version, pyver or None\n    \"\"\"\n    result = None\n    pyver = None\n    filename = unquote(filename).replace(' ', '-')\n    m = PYTHON_VERSION.search(filename)\n    if m:\n        pyver = m.group(1)\n        filename = filename[:m.start()]\n    if project_name and len(filename) > len(project_name) + 1:\n        m = re.match(re.escape(project_name) + r'\\b', filename)\n        if m:\n            n = m.end()\n            result = filename[:n], filename[n + 1:], pyver\n    if result is None:\n        m = PROJECT_NAME_AND_VERSION.match(filename)\n        if m:\n            result = m.group(1), m.group(3), pyver\n    return result\n\n# Allow spaces in name because of legacy dists like \"Twisted Core\"\nNAME_VERSION_RE = re.compile(r'(?P<name>[\\w .-]+)\\s*'\n                             r'\\(\\s*(?P<ver>[^\\s)]+)\\)$')\n\ndef parse_name_and_version(p):\n    \"\"\"\n    A utility method used to get name and version from a string.\n\n    From e.g. a Provides-Dist value.\n\n    :param p: A value in a form 'foo (1.0)'\n    :return: The name and version as a tuple.\n    \"\"\"\n    m = NAME_VERSION_RE.match(p)\n    if not m:\n        raise DistlibException('Ill-formed name/version string: \\'%s\\'' % p)\n    d = m.groupdict()\n    return d['name'].strip().lower(), d['ver']\n\ndef get_extras(requested, available):\n    result = set()\n    requested = set(requested or [])\n    available = set(available or [])\n    if '*' in requested:\n        requested.remove('*')\n        result |= available\n    for r in requested:\n        if r == '-':\n            result.add(r)\n        elif r.startswith('-'):\n            unwanted = r[1:]\n            if unwanted not in available:\n                logger.warning('undeclared extra: %s' % unwanted)\n            if unwanted in result:\n                result.remove(unwanted)\n        else:\n            if r not in available:\n                logger.warning('undeclared extra: %s' % r)\n            result.add(r)\n    return result\n#\n# Extended metadata functionality\n#\n\ndef _get_external_data(url):\n    result = {}\n    try:\n        # urlopen might fail if it runs into redirections,\n        # because of Python issue #13696. Fixed in locators\n        # using a custom redirect handler.\n        resp = urlopen(url)\n        headers = resp.info()\n        ct = headers.get('Content-Type')\n        if not ct.startswith('application/json'):\n            logger.debug('Unexpected response for JSON request: %s', ct)\n        else:\n            reader = codecs.getreader('utf-8')(resp)\n            #data = reader.read().decode('utf-8')\n            #result = json.loads(data)\n            result = json.load(reader)\n    except Exception as e:\n        logger.exception('Failed to get external data for %s: %s', url, e)\n    return result\n\n_external_data_base_url = 'https://www.red-dove.com/pypi/projects/'\n\ndef get_project_data(name):\n    url = '%s/%s/project.json' % (name[0].upper(), name)\n    url = urljoin(_external_data_base_url, url)\n    result = _get_external_data(url)\n    return result\n\ndef get_package_data(name, version):\n    url = '%s/%s/package-%s.json' % (name[0].upper(), name, version)\n    url = urljoin(_external_data_base_url, url)\n    return _get_external_data(url)\n\n\nclass Cache(object):\n    \"\"\"\n    A class implementing a cache for resources that need to live in the file system\n    e.g. shared libraries. This class was moved from resources to here because it\n    could be used by other modules, e.g. the wheel module.\n    \"\"\"\n\n    def __init__(self, base):\n        \"\"\"\n        Initialise an instance.\n\n        :param base: The base directory where the cache should be located.\n        \"\"\"\n        # we use 'isdir' instead of 'exists', because we want to\n        # fail if there's a file with that name\n        if not os.path.isdir(base):  # pragma: no cover\n            os.makedirs(base)\n        if (os.stat(base).st_mode & 0o77) != 0:\n            logger.warning('Directory \\'%s\\' is not private', base)\n        self.base = os.path.abspath(os.path.normpath(base))\n\n    def prefix_to_dir(self, prefix):\n        \"\"\"\n        Converts a resource prefix to a directory name in the cache.\n        \"\"\"\n        return path_to_cache_dir(prefix)\n\n    def clear(self):\n        \"\"\"\n        Clear the cache.\n        \"\"\"\n        not_removed = []\n        for fn in os.listdir(self.base):\n            fn = os.path.join(self.base, fn)\n            try:\n                if os.path.islink(fn) or os.path.isfile(fn):\n                    os.remove(fn)\n                elif os.path.isdir(fn):\n                    shutil.rmtree(fn)\n            except Exception:\n                not_removed.append(fn)\n        return not_removed\n\n\nclass EventMixin(object):\n    \"\"\"\n    A very simple publish/subscribe system.\n    \"\"\"\n    def __init__(self):\n        self._subscribers = {}\n\n    def add(self, event, subscriber, append=True):\n        \"\"\"\n        Add a subscriber for an event.\n\n        :param event: The name of an event.\n        :param subscriber: The subscriber to be added (and called when the\n                           event is published).\n        :param append: Whether to append or prepend the subscriber to an\n                       existing subscriber list for the event.\n        \"\"\"\n        subs = self._subscribers\n        if event not in subs:\n            subs[event] = deque([subscriber])\n        else:\n            sq = subs[event]\n            if append:\n                sq.append(subscriber)\n            else:\n                sq.appendleft(subscriber)\n\n    def remove(self, event, subscriber):\n        \"\"\"\n        Remove a subscriber for an event.\n\n        :param event: The name of an event.\n        :param subscriber: The subscriber to be removed.\n        \"\"\"\n        subs = self._subscribers\n        if event not in subs:\n            raise ValueError('No subscribers: %r' % event)\n        subs[event].remove(subscriber)\n\n    def get_subscribers(self, event):\n        \"\"\"\n        Return an iterator for the subscribers for an event.\n        :param event: The event to return subscribers for.\n        \"\"\"\n        return iter(self._subscribers.get(event, ()))\n\n    def publish(self, event, *args, **kwargs):\n        \"\"\"\n        Publish a event and return a list of values returned by its\n        subscribers.\n\n        :param event: The event to publish.\n        :param args: The positional arguments to pass to the event's\n                     subscribers.\n        :param kwargs: The keyword arguments to pass to the event's\n                       subscribers.\n        \"\"\"\n        result = []\n        for subscriber in self.get_subscribers(event):\n            try:\n                value = subscriber(event, *args, **kwargs)\n            except Exception:\n                logger.exception('Exception during event publication')\n                value = None\n            result.append(value)\n        logger.debug('publish %s: args = %s, kwargs = %s, result = %s',\n                     event, args, kwargs, result)\n        return result\n\n#\n# Simple sequencing\n#\nclass Sequencer(object):\n    def __init__(self):\n        self._preds = {}\n        self._succs = {}\n        self._nodes = set()     # nodes with no preds/succs\n\n    def add_node(self, node):\n        self._nodes.add(node)\n\n    def remove_node(self, node, edges=False):\n        if node in self._nodes:\n            self._nodes.remove(node)\n        if edges:\n            for p in set(self._preds.get(node, ())):\n                self.remove(p, node)\n            for s in set(self._succs.get(node, ())):\n                self.remove(node, s)\n            # Remove empties\n            for k, v in list(self._preds.items()):\n                if not v:\n                    del self._preds[k]\n            for k, v in list(self._succs.items()):\n                if not v:\n                    del self._succs[k]\n\n    def add(self, pred, succ):\n        assert pred != succ\n        self._preds.setdefault(succ, set()).add(pred)\n        self._succs.setdefault(pred, set()).add(succ)\n\n    def remove(self, pred, succ):\n        assert pred != succ\n        try:\n            preds = self._preds[succ]\n            succs = self._succs[pred]\n        except KeyError:  # pragma: no cover\n            raise ValueError('%r not a successor of anything' % succ)\n        try:\n            preds.remove(pred)\n            succs.remove(succ)\n        except KeyError:  # pragma: no cover\n            raise ValueError('%r not a successor of %r' % (succ, pred))\n\n    def is_step(self, step):\n        return (step in self._preds or step in self._succs or\n                step in self._nodes)\n\n    def get_steps(self, final):\n        if not self.is_step(final):\n            raise ValueError('Unknown: %r' % final)\n        result = []\n        todo = []\n        seen = set()\n        todo.append(final)\n        while todo:\n            step = todo.pop(0)\n            if step in seen:\n                # if a step was already seen,\n                # move it to the end (so it will appear earlier\n                # when reversed on return) ... but not for the\n                # final step, as that would be confusing for\n                # users\n                if step != final:\n                    result.remove(step)\n                    result.append(step)\n            else:\n                seen.add(step)\n                result.append(step)\n                preds = self._preds.get(step, ())\n                todo.extend(preds)\n        return reversed(result)\n\n    @property\n    def strong_connections(self):\n        #http://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm\n        index_counter = [0]\n        stack = []\n        lowlinks = {}\n        index = {}\n        result = []\n\n        graph = self._succs\n\n        def strongconnect(node):\n            # set the depth index for this node to the smallest unused index\n            index[node] = index_counter[0]\n            lowlinks[node] = index_counter[0]\n            index_counter[0] += 1\n            stack.append(node)\n\n            # Consider successors\n            try:\n                successors = graph[node]\n            except Exception:\n                successors = []\n            for successor in successors:\n                if successor not in lowlinks:\n                    # Successor has not yet been visited\n                    strongconnect(successor)\n                    lowlinks[node] = min(lowlinks[node],lowlinks[successor])\n                elif successor in stack:\n                    # the successor is in the stack and hence in the current\n                    # strongly connected component (SCC)\n                    lowlinks[node] = min(lowlinks[node],index[successor])\n\n            # If `node` is a root node, pop the stack and generate an SCC\n            if lowlinks[node] == index[node]:\n                connected_component = []\n\n                while True:\n                    successor = stack.pop()\n                    connected_component.append(successor)\n                    if successor == node: break\n                component = tuple(connected_component)\n                # storing the result\n                result.append(component)\n\n        for node in graph:\n            if node not in lowlinks:\n                strongconnect(node)\n\n        return result\n\n    @property\n    def dot(self):\n        result = ['digraph G {']\n        for succ in self._preds:\n            preds = self._preds[succ]\n            for pred in preds:\n                result.append('  %s -> %s;' % (pred, succ))\n        for node in self._nodes:\n            result.append('  %s;' % node)\n        result.append('}')\n        return '\\n'.join(result)\n\n#\n# Unarchiving functionality for zip, tar, tgz, tbz, whl\n#\n\nARCHIVE_EXTENSIONS = ('.tar.gz', '.tar.bz2', '.tar', '.zip',\n                      '.tgz', '.tbz', '.whl')\n\ndef unarchive(archive_filename, dest_dir, format=None, check=True):\n\n    def check_path(path):\n        if not isinstance(path, text_type):\n            path = path.decode('utf-8')\n        p = os.path.abspath(os.path.join(dest_dir, path))\n        if not p.startswith(dest_dir) or p[plen] != os.sep:\n            raise ValueError('path outside destination: %r' % p)\n\n    dest_dir = os.path.abspath(dest_dir)\n    plen = len(dest_dir)\n    archive = None\n    if format is None:\n        if archive_filename.endswith(('.zip', '.whl')):\n            format = 'zip'\n        elif archive_filename.endswith(('.tar.gz', '.tgz')):\n            format = 'tgz'\n            mode = 'r:gz'\n        elif archive_filename.endswith(('.tar.bz2', '.tbz')):\n            format = 'tbz'\n            mode = 'r:bz2'\n        elif archive_filename.endswith('.tar'):\n            format = 'tar'\n            mode = 'r'\n        else:  # pragma: no cover\n            raise ValueError('Unknown format for %r' % archive_filename)\n    try:\n        if format == 'zip':\n            archive = ZipFile(archive_filename, 'r')\n            if check:\n                names = archive.namelist()\n                for name in names:\n                    check_path(name)\n        else:\n            archive = tarfile.open(archive_filename, mode)\n            if check:\n                names = archive.getnames()\n                for name in names:\n                    check_path(name)\n        if format != 'zip' and sys.version_info[0] < 3:\n            # See Python issue 17153. If the dest path contains Unicode,\n            # tarfile extraction fails on Python 2.x if a member path name\n            # contains non-ASCII characters - it leads to an implicit\n            # bytes -> unicode conversion using ASCII to decode.\n            for tarinfo in archive.getmembers():\n                if not isinstance(tarinfo.name, text_type):\n                    tarinfo.name = tarinfo.name.decode('utf-8')\n        archive.extractall(dest_dir)\n\n    finally:\n        if archive:\n            archive.close()\n\n\ndef zip_dir(directory):\n    \"\"\"zip a directory tree into a BytesIO object\"\"\"\n    result = io.BytesIO()\n    dlen = len(directory)\n    with ZipFile(result, \"w\") as zf:\n        for root, dirs, files in os.walk(directory):\n            for name in files:\n                full = os.path.join(root, name)\n                rel = root[dlen:]\n                dest = os.path.join(rel, name)\n                zf.write(full, dest)\n    return result\n\n#\n# Simple progress bar\n#\n\nUNITS = ('', 'K', 'M', 'G','T','P')\n\n\nclass Progress(object):\n    unknown = 'UNKNOWN'\n\n    def __init__(self, minval=0, maxval=100):\n        assert maxval is None or maxval >= minval\n        self.min = self.cur = minval\n        self.max = maxval\n        self.started = None\n        self.elapsed = 0\n        self.done = False\n\n    def update(self, curval):\n        assert self.min <= curval\n        assert self.max is None or curval <= self.max\n        self.cur = curval\n        now = time.time()\n        if self.started is None:\n            self.started = now\n        else:\n            self.elapsed = now - self.started\n\n    def increment(self, incr):\n        assert incr >= 0\n        self.update(self.cur + incr)\n\n    def start(self):\n        self.update(self.min)\n        return self\n\n    def stop(self):\n        if self.max is not None:\n            self.update(self.max)\n        self.done = True\n\n    @property\n    def maximum(self):\n        return self.unknown if self.max is None else self.max\n\n    @property\n    def percentage(self):\n        if self.done:\n            result = '100 %'\n        elif self.max is None:\n            result = ' ?? %'\n        else:\n            v = 100.0 * (self.cur - self.min) / (self.max - self.min)\n            result = '%3d %%' % v\n        return result\n\n    def format_duration(self, duration):\n        if (duration <= 0) and self.max is None or self.cur == self.min:\n            result = '??:??:??'\n        #elif duration < 1:\n        #    result = '--:--:--'\n        else:\n            result = time.strftime('%H:%M:%S', time.gmtime(duration))\n        return result\n\n    @property\n    def ETA(self):\n        if self.done:\n            prefix = 'Done'\n            t = self.elapsed\n            #import pdb; pdb.set_trace()\n        else:\n            prefix = 'ETA '\n            if self.max is None:\n                t = -1\n            elif self.elapsed == 0 or (self.cur == self.min):\n                t = 0\n            else:\n                #import pdb; pdb.set_trace()\n                t = float(self.max - self.min)\n                t /= self.cur - self.min\n                t = (t - 1) * self.elapsed\n        return '%s: %s' % (prefix, self.format_duration(t))\n\n    @property\n    def speed(self):\n        if self.elapsed == 0:\n            result = 0.0\n        else:\n            result = (self.cur - self.min) / self.elapsed\n        for unit in UNITS:\n            if result < 1000:\n                break\n            result /= 1000.0\n        return '%d %sB/s' % (result, unit)\n\n#\n# Glob functionality\n#\n\nRICH_GLOB = re.compile(r'\\{([^}]*)\\}')\n_CHECK_RECURSIVE_GLOB = re.compile(r'[^/\\\\,{]\\*\\*|\\*\\*[^/\\\\,}]')\n_CHECK_MISMATCH_SET = re.compile(r'^[^{]*\\}|\\{[^}]*$')\n\n\ndef iglob(path_glob):\n    \"\"\"Extended globbing function that supports ** and {opt1,opt2,opt3}.\"\"\"\n    if _CHECK_RECURSIVE_GLOB.search(path_glob):\n        msg = \"\"\"invalid glob %r: recursive glob \"**\" must be used alone\"\"\"\n        raise ValueError(msg % path_glob)\n    if _CHECK_MISMATCH_SET.search(path_glob):\n        msg = \"\"\"invalid glob %r: mismatching set marker '{' or '}'\"\"\"\n        raise ValueError(msg % path_glob)\n    return _iglob(path_glob)\n\n\ndef _iglob(path_glob):\n    rich_path_glob = RICH_GLOB.split(path_glob, 1)\n    if len(rich_path_glob) > 1:\n        assert len(rich_path_glob) == 3, rich_path_glob\n        prefix, set, suffix = rich_path_glob\n        for item in set.split(','):\n            for path in _iglob(''.join((prefix, item, suffix))):\n                yield path\n    else:\n        if '**' not in path_glob:\n            for item in std_iglob(path_glob):\n                yield item\n        else:\n            prefix, radical = path_glob.split('**', 1)\n            if prefix == '':\n                prefix = '.'\n            if radical == '':\n                radical = '*'\n            else:\n                # we support both\n                radical = radical.lstrip('/')\n                radical = radical.lstrip('\\\\')\n            for path, dir, files in os.walk(prefix):\n                path = os.path.normpath(path)\n                for fn in _iglob(os.path.join(path, radical)):\n                    yield fn\n\nif ssl:\n    from .compat import (HTTPSHandler as BaseHTTPSHandler, match_hostname,\n                         CertificateError)\n\n\n#\n# HTTPSConnection which verifies certificates/matches domains\n#\n\n    class HTTPSConnection(httplib.HTTPSConnection):\n        ca_certs = None # set this to the path to the certs file (.pem)\n        check_domain = True # only used if ca_certs is not None\n\n        # noinspection PyPropertyAccess\n        def connect(self):\n            sock = socket.create_connection((self.host, self.port), self.timeout)\n            if getattr(self, '_tunnel_host', False):\n                self.sock = sock\n                self._tunnel()\n\n            context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)\n            if hasattr(ssl, 'OP_NO_SSLv2'):\n                context.options |= ssl.OP_NO_SSLv2\n            if self.cert_file:\n                context.load_cert_chain(self.cert_file, self.key_file)\n            kwargs = {}\n            if self.ca_certs:\n                context.verify_mode = ssl.CERT_REQUIRED\n                context.load_verify_locations(cafile=self.ca_certs)\n                if getattr(ssl, 'HAS_SNI', False):\n                    kwargs['server_hostname'] = self.host\n\n            self.sock = context.wrap_socket(sock, **kwargs)\n            if self.ca_certs and self.check_domain:\n                try:\n                    match_hostname(self.sock.getpeercert(), self.host)\n                    logger.debug('Host verified: %s', self.host)\n                except CertificateError:  # pragma: no cover\n                    self.sock.shutdown(socket.SHUT_RDWR)\n                    self.sock.close()\n                    raise\n\n    class HTTPSHandler(BaseHTTPSHandler):\n        def __init__(self, ca_certs, check_domain=True):\n            BaseHTTPSHandler.__init__(self)\n            self.ca_certs = ca_certs\n            self.check_domain = check_domain\n\n        def _conn_maker(self, *args, **kwargs):\n            \"\"\"\n            This is called to create a connection instance. Normally you'd\n            pass a connection class to do_open, but it doesn't actually check for\n            a class, and just expects a callable. As long as we behave just as a\n            constructor would have, we should be OK. If it ever changes so that\n            we *must* pass a class, we'll create an UnsafeHTTPSConnection class\n            which just sets check_domain to False in the class definition, and\n            choose which one to pass to do_open.\n            \"\"\"\n            result = HTTPSConnection(*args, **kwargs)\n            if self.ca_certs:\n                result.ca_certs = self.ca_certs\n                result.check_domain = self.check_domain\n            return result\n\n        def https_open(self, req):\n            try:\n                return self.do_open(self._conn_maker, req)\n            except URLError as e:\n                if 'certificate verify failed' in str(e.reason):\n                    raise CertificateError('Unable to verify server certificate '\n                                           'for %s' % req.host)\n                else:\n                    raise\n\n    #\n    # To prevent against mixing HTTP traffic with HTTPS (examples: A Man-In-The-\n    # Middle proxy using HTTP listens on port 443, or an index mistakenly serves\n    # HTML containing a http://xyz link when it should be https://xyz),\n    # you can use the following handler class, which does not allow HTTP traffic.\n    #\n    # It works by inheriting from HTTPHandler - so build_opener won't add a\n    # handler for HTTP itself.\n    #\n    class HTTPSOnlyHandler(HTTPSHandler, HTTPHandler):\n        def http_open(self, req):\n            raise URLError('Unexpected HTTP request on what should be a secure '\n                           'connection: %s' % req)\n\n#\n# XML-RPC with timeouts\n#\nclass Transport(xmlrpclib.Transport):\n    def __init__(self, timeout, use_datetime=0):\n        self.timeout = timeout\n        xmlrpclib.Transport.__init__(self, use_datetime)\n\n    def make_connection(self, host):\n        h, eh, x509 = self.get_host_info(host)\n        if not self._connection or host != self._connection[0]:\n            self._extra_headers = eh\n            self._connection = host, httplib.HTTPConnection(h)\n        return self._connection[1]\n\nif ssl:\n    class SafeTransport(xmlrpclib.SafeTransport):\n        def __init__(self, timeout, use_datetime=0):\n            self.timeout = timeout\n            xmlrpclib.SafeTransport.__init__(self, use_datetime)\n\n        def make_connection(self, host):\n            h, eh, kwargs = self.get_host_info(host)\n            if not kwargs:\n                kwargs = {}\n            kwargs['timeout'] = self.timeout\n            if not self._connection or host != self._connection[0]:\n                self._extra_headers = eh\n                self._connection = host, httplib.HTTPSConnection(h, None,\n                                                                 **kwargs)\n            return self._connection[1]\n\n\nclass ServerProxy(xmlrpclib.ServerProxy):\n    def __init__(self, uri, **kwargs):\n        self.timeout = timeout = kwargs.pop('timeout', None)\n        # The above classes only come into play if a timeout\n        # is specified\n        if timeout is not None:\n            # scheme = splittype(uri)  # deprecated as of Python 3.8\n            scheme = urlparse(uri)[0]\n            use_datetime = kwargs.get('use_datetime', 0)\n            if scheme == 'https':\n                tcls = SafeTransport\n            else:\n                tcls = Transport\n            kwargs['transport'] = t = tcls(timeout, use_datetime=use_datetime)\n            self.transport = t\n        xmlrpclib.ServerProxy.__init__(self, uri, **kwargs)\n\n#\n# CSV functionality. This is provided because on 2.x, the csv module can't\n# handle Unicode. However, we need to deal with Unicode in e.g. RECORD files.\n#\n\ndef _csv_open(fn, mode, **kwargs):\n    if sys.version_info[0] < 3:\n        mode += 'b'\n    else:\n        kwargs['newline'] = ''\n        # Python 3 determines encoding from locale. Force 'utf-8'\n        # file encoding to match other forced utf-8 encoding\n        kwargs['encoding'] = 'utf-8'\n    return open(fn, mode, **kwargs)\n\n\nclass CSVBase(object):\n    defaults = {\n        'delimiter': str(','),      # The strs are used because we need native\n        'quotechar': str('\"'),      # str in the csv API (2.x won't take\n        'lineterminator': str('\\n') # Unicode)\n    }\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *exc_info):\n        self.stream.close()\n\n\nclass CSVReader(CSVBase):\n    def __init__(self, **kwargs):\n        if 'stream' in kwargs:\n            stream = kwargs['stream']\n            if sys.version_info[0] >= 3:\n                # needs to be a text stream\n                stream = codecs.getreader('utf-8')(stream)\n            self.stream = stream\n        else:\n            self.stream = _csv_open(kwargs['path'], 'r')\n        self.reader = csv.reader(self.stream, **self.defaults)\n\n    def __iter__(self):\n        return self\n\n    def next(self):\n        result = next(self.reader)\n        if sys.version_info[0] < 3:\n            for i, item in enumerate(result):\n                if not isinstance(item, text_type):\n                    result[i] = item.decode('utf-8')\n        return result\n\n    __next__ = next\n\nclass CSVWriter(CSVBase):\n    def __init__(self, fn, **kwargs):\n        self.stream = _csv_open(fn, 'w')\n        self.writer = csv.writer(self.stream, **self.defaults)\n\n    def writerow(self, row):\n        if sys.version_info[0] < 3:\n            r = []\n            for item in row:\n                if isinstance(item, text_type):\n                    item = item.encode('utf-8')\n                r.append(item)\n            row = r\n        self.writer.writerow(row)\n\n#\n#   Configurator functionality\n#\n\nclass Configurator(BaseConfigurator):\n\n    value_converters = dict(BaseConfigurator.value_converters)\n    value_converters['inc'] = 'inc_convert'\n\n    def __init__(self, config, base=None):\n        super(Configurator, self).__init__(config)\n        self.base = base or os.getcwd()\n\n    def configure_custom(self, config):\n        def convert(o):\n            if isinstance(o, (list, tuple)):\n                result = type(o)([convert(i) for i in o])\n            elif isinstance(o, dict):\n                if '()' in o:\n                    result = self.configure_custom(o)\n                else:\n                    result = {}\n                    for k in o:\n                        result[k] = convert(o[k])\n            else:\n                result = self.convert(o)\n            return result\n\n        c = config.pop('()')\n        if not callable(c):\n            c = self.resolve(c)\n        props = config.pop('.', None)\n        # Check for valid identifiers\n        args = config.pop('[]', ())\n        if args:\n            args = tuple([convert(o) for o in args])\n        items = [(k, convert(config[k])) for k in config if valid_ident(k)]\n        kwargs = dict(items)\n        result = c(*args, **kwargs)\n        if props:\n            for n, v in props.items():\n                setattr(result, n, convert(v))\n        return result\n\n    def __getitem__(self, key):\n        result = self.config[key]\n        if isinstance(result, dict) and '()' in result:\n            self.config[key] = result = self.configure_custom(result)\n        return result\n\n    def inc_convert(self, value):\n        \"\"\"Default converter for the inc:// protocol.\"\"\"\n        if not os.path.isabs(value):\n            value = os.path.join(self.base, value)\n        with codecs.open(value, 'r', encoding='utf-8') as f:\n            result = json.load(f)\n        return result\n\n\nclass SubprocessMixin(object):\n    \"\"\"\n    Mixin for running subprocesses and capturing their output\n    \"\"\"\n    def __init__(self, verbose=False, progress=None):\n        self.verbose = verbose\n        self.progress = progress\n\n    def reader(self, stream, context):\n        \"\"\"\n        Read lines from a subprocess' output stream and either pass to a progress\n        callable (if specified) or write progress information to sys.stderr.\n        \"\"\"\n        progress = self.progress\n        verbose = self.verbose\n        while True:\n            s = stream.readline()\n            if not s:\n                break\n            if progress is not None:\n                progress(s, context)\n            else:\n                if not verbose:\n                    sys.stderr.write('.')\n                else:\n                    sys.stderr.write(s.decode('utf-8'))\n                sys.stderr.flush()\n        stream.close()\n\n    def run_command(self, cmd, **kwargs):\n        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,\n                             stderr=subprocess.PIPE, **kwargs)\n        t1 = threading.Thread(target=self.reader, args=(p.stdout, 'stdout'))\n        t1.start()\n        t2 = threading.Thread(target=self.reader, args=(p.stderr, 'stderr'))\n        t2.start()\n        p.wait()\n        t1.join()\n        t2.join()\n        if self.progress is not None:\n            self.progress('done.', 'main')\n        elif self.verbose:\n            sys.stderr.write('done.\\n')\n        return p\n\n\ndef normalize_name(name):\n    \"\"\"Normalize a python package name a la PEP 503\"\"\"\n    # https://www.python.org/dev/peps/pep-0503/#normalized-names\n    return re.sub('[-_.]+', '-', name).lower()\n\n# def _get_pypirc_command():\n    # \"\"\"\n    # Get the distutils command for interacting with PyPI configurations.\n    # :return: the command.\n    # \"\"\"\n    # from distutils.core import Distribution\n    # from distutils.config import PyPIRCCommand\n    # d = Distribution()\n    # return PyPIRCCommand(d)\n\nclass PyPIRCFile(object):\n\n    DEFAULT_REPOSITORY = 'https://upload.pypi.org/legacy/'\n    DEFAULT_REALM = 'pypi'\n\n    def __init__(self, fn=None, url=None):\n        if fn is None:\n            fn = os.path.join(os.path.expanduser('~'), '.pypirc')\n        self.filename = fn\n        self.url = url\n\n    def read(self):\n        result = {}\n\n        if os.path.exists(self.filename):\n            repository = self.url or self.DEFAULT_REPOSITORY\n\n            config = configparser.RawConfigParser()\n            config.read(self.filename)\n            sections = config.sections()\n            if 'distutils' in sections:\n                # let's get the list of servers\n                index_servers = config.get('distutils', 'index-servers')\n                _servers = [server.strip() for server in\n                            index_servers.split('\\n')\n                            if server.strip() != '']\n                if _servers == []:\n                    # nothing set, let's try to get the default pypi\n                    if 'pypi' in sections:\n                        _servers = ['pypi']\n                else:\n                    for server in _servers:\n                        result = {'server': server}\n                        result['username'] = config.get(server, 'username')\n\n                        # optional params\n                        for key, default in (('repository', self.DEFAULT_REPOSITORY),\n                                             ('realm', self.DEFAULT_REALM),\n                                             ('password', None)):\n                            if config.has_option(server, key):\n                                result[key] = config.get(server, key)\n                            else:\n                                result[key] = default\n\n                        # work around people having \"repository\" for the \"pypi\"\n                        # section of their config set to the HTTP (rather than\n                        # HTTPS) URL\n                        if (server == 'pypi' and\n                            repository in (self.DEFAULT_REPOSITORY, 'pypi')):\n                            result['repository'] = self.DEFAULT_REPOSITORY\n                        elif (result['server'] != repository and\n                              result['repository'] != repository):\n                            result = {}\n            elif 'server-login' in sections:\n                # old format\n                server = 'server-login'\n                if config.has_option(server, 'repository'):\n                    repository = config.get(server, 'repository')\n                else:\n                    repository = self.DEFAULT_REPOSITORY\n                result = {\n                    'username': config.get(server, 'username'),\n                    'password': config.get(server, 'password'),\n                    'repository': repository,\n                    'server': server,\n                    'realm': self.DEFAULT_REALM\n                }\n        return result\n\n    def update(self, username, password):\n        # import pdb; pdb.set_trace()\n        config = configparser.RawConfigParser()\n        fn = self.filename\n        config.read(fn)\n        if not config.has_section('pypi'):\n            config.add_section('pypi')\n        config.set('pypi', 'username', username)\n        config.set('pypi', 'password', password)\n        with open(fn, 'w') as f:\n            config.write(f)\n\ndef _load_pypirc(index):\n    \"\"\"\n    Read the PyPI access configuration as supported by distutils.\n    \"\"\"\n    return PyPIRCFile(url=index.url).read()\n\ndef _store_pypirc(index):\n    PyPIRCFile().update(index.username, index.password)\n\n#\n# get_platform()/get_host_platform() copied from Python 3.10.a0 source, with some minor\n# tweaks\n#\n\ndef get_host_platform():\n    \"\"\"Return a string that identifies the current platform.  This is used mainly to\n    distinguish platform-specific build directories and platform-specific built\n    distributions.  Typically includes the OS name and version and the\n    architecture (as supplied by 'os.uname()'), although the exact information\n    included depends on the OS; eg. on Linux, the kernel version isn't\n    particularly important.\n\n    Examples of returned values:\n       linux-i586\n       linux-alpha (?)\n       solaris-2.6-sun4u\n\n    Windows will return one of:\n       win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc)\n       win32 (all others - specifically, sys.platform is returned)\n\n    For other non-POSIX platforms, currently just returns 'sys.platform'.\n\n    \"\"\"\n    if os.name == 'nt':\n        if 'amd64' in sys.version.lower():\n            return 'win-amd64'\n        if '(arm)' in sys.version.lower():\n            return 'win-arm32'\n        if '(arm64)' in sys.version.lower():\n            return 'win-arm64'\n        return sys.platform\n\n    # Set for cross builds explicitly\n    if \"_PYTHON_HOST_PLATFORM\" in os.environ:\n        return os.environ[\"_PYTHON_HOST_PLATFORM\"]\n\n    if os.name != 'posix' or not hasattr(os, 'uname'):\n        # XXX what about the architecture? NT is Intel or Alpha,\n        # Mac OS is M68k or PPC, etc.\n        return sys.platform\n\n    # Try to distinguish various flavours of Unix\n\n    (osname, host, release, version, machine) = os.uname()\n\n    # Convert the OS name to lowercase, remove '/' characters, and translate\n    # spaces (for \"Power Macintosh\")\n    osname = osname.lower().replace('/', '')\n    machine = machine.replace(' ', '_').replace('/', '-')\n\n    if osname[:5] == 'linux':\n        # At least on Linux/Intel, 'machine' is the processor --\n        # i386, etc.\n        # XXX what about Alpha, SPARC, etc?\n        return  \"%s-%s\" % (osname, machine)\n\n    elif osname[:5] == 'sunos':\n        if release[0] >= '5':           # SunOS 5 == Solaris 2\n            osname = 'solaris'\n            release = '%d.%s' % (int(release[0]) - 3, release[2:])\n            # We can't use 'platform.architecture()[0]' because a\n            # bootstrap problem. We use a dict to get an error\n            # if some suspicious happens.\n            bitness = {2147483647:'32bit', 9223372036854775807:'64bit'}\n            machine += '.%s' % bitness[sys.maxsize]\n        # fall through to standard osname-release-machine representation\n    elif osname[:3] == 'aix':\n        from _aix_support import aix_platform\n        return aix_platform()\n    elif osname[:6] == 'cygwin':\n        osname = 'cygwin'\n        rel_re = re.compile (r'[\\d.]+', re.ASCII)\n        m = rel_re.match(release)\n        if m:\n            release = m.group()\n    elif osname[:6] == 'darwin':\n        import _osx_support, distutils.sysconfig\n        osname, release, machine = _osx_support.get_platform_osx(\n                                        distutils.sysconfig.get_config_vars(),\n                                        osname, release, machine)\n\n    return '%s-%s-%s' % (osname, release, machine)\n\n\n_TARGET_TO_PLAT = {\n    'x86' : 'win32',\n    'x64' : 'win-amd64',\n    'arm' : 'win-arm32',\n}\n\n\ndef get_platform():\n    if os.name != 'nt':\n        return get_host_platform()\n    cross_compilation_target = os.environ.get('VSCMD_ARG_TGT_ARCH')\n    if cross_compilation_target not in _TARGET_TO_PLAT:\n        return get_host_platform()\n    return _TARGET_TO_PLAT[cross_compilation_target]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distlib/version.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2012-2017 The Python Software Foundation.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\n\"\"\"\nImplementation of a flexible versioning scheme providing support for PEP-440,\nsetuptools-compatible and semantic versioning.\n\"\"\"\n\nimport logging\nimport re\n\nfrom .compat import string_types\nfrom .util import parse_requirement\n\n__all__ = ['NormalizedVersion', 'NormalizedMatcher',\n           'LegacyVersion', 'LegacyMatcher',\n           'SemanticVersion', 'SemanticMatcher',\n           'UnsupportedVersionError', 'get_scheme']\n\nlogger = logging.getLogger(__name__)\n\n\nclass UnsupportedVersionError(ValueError):\n    \"\"\"This is an unsupported version.\"\"\"\n    pass\n\n\nclass Version(object):\n    def __init__(self, s):\n        self._string = s = s.strip()\n        self._parts = parts = self.parse(s)\n        assert isinstance(parts, tuple)\n        assert len(parts) > 0\n\n    def parse(self, s):\n        raise NotImplementedError('please implement in a subclass')\n\n    def _check_compatible(self, other):\n        if type(self) != type(other):\n            raise TypeError('cannot compare %r and %r' % (self, other))\n\n    def __eq__(self, other):\n        self._check_compatible(other)\n        return self._parts == other._parts\n\n    def __ne__(self, other):\n        return not self.__eq__(other)\n\n    def __lt__(self, other):\n        self._check_compatible(other)\n        return self._parts < other._parts\n\n    def __gt__(self, other):\n        return not (self.__lt__(other) or self.__eq__(other))\n\n    def __le__(self, other):\n        return self.__lt__(other) or self.__eq__(other)\n\n    def __ge__(self, other):\n        return self.__gt__(other) or self.__eq__(other)\n\n    # See http://docs.python.org/reference/datamodel#object.__hash__\n    def __hash__(self):\n        return hash(self._parts)\n\n    def __repr__(self):\n        return \"%s('%s')\" % (self.__class__.__name__, self._string)\n\n    def __str__(self):\n        return self._string\n\n    @property\n    def is_prerelease(self):\n        raise NotImplementedError('Please implement in subclasses.')\n\n\nclass Matcher(object):\n    version_class = None\n\n    # value is either a callable or the name of a method\n    _operators = {\n        '<': lambda v, c, p: v < c,\n        '>': lambda v, c, p: v > c,\n        '<=': lambda v, c, p: v == c or v < c,\n        '>=': lambda v, c, p: v == c or v > c,\n        '==': lambda v, c, p: v == c,\n        '===': lambda v, c, p: v == c,\n        # by default, compatible => >=.\n        '~=': lambda v, c, p: v == c or v > c,\n        '!=': lambda v, c, p: v != c,\n    }\n\n    # this is a method only to support alternative implementations\n    # via overriding\n    def parse_requirement(self, s):\n        return parse_requirement(s)\n\n    def __init__(self, s):\n        if self.version_class is None:\n            raise ValueError('Please specify a version class')\n        self._string = s = s.strip()\n        r = self.parse_requirement(s)\n        if not r:\n            raise ValueError('Not valid: %r' % s)\n        self.name = r.name\n        self.key = self.name.lower()    # for case-insensitive comparisons\n        clist = []\n        if r.constraints:\n            # import pdb; pdb.set_trace()\n            for op, s in r.constraints:\n                if s.endswith('.*'):\n                    if op not in ('==', '!='):\n                        raise ValueError('\\'.*\\' not allowed for '\n                                         '%r constraints' % op)\n                    # Could be a partial version (e.g. for '2.*') which\n                    # won't parse as a version, so keep it as a string\n                    vn, prefix = s[:-2], True\n                    # Just to check that vn is a valid version\n                    self.version_class(vn)\n                else:\n                    # Should parse as a version, so we can create an\n                    # instance for the comparison\n                    vn, prefix = self.version_class(s), False\n                clist.append((op, vn, prefix))\n        self._parts = tuple(clist)\n\n    def match(self, version):\n        \"\"\"\n        Check if the provided version matches the constraints.\n\n        :param version: The version to match against this instance.\n        :type version: String or :class:`Version` instance.\n        \"\"\"\n        if isinstance(version, string_types):\n            version = self.version_class(version)\n        for operator, constraint, prefix in self._parts:\n            f = self._operators.get(operator)\n            if isinstance(f, string_types):\n                f = getattr(self, f)\n            if not f:\n                msg = ('%r not implemented '\n                       'for %s' % (operator, self.__class__.__name__))\n                raise NotImplementedError(msg)\n            if not f(version, constraint, prefix):\n                return False\n        return True\n\n    @property\n    def exact_version(self):\n        result = None\n        if len(self._parts) == 1 and self._parts[0][0] in ('==', '==='):\n            result = self._parts[0][1]\n        return result\n\n    def _check_compatible(self, other):\n        if type(self) != type(other) or self.name != other.name:\n            raise TypeError('cannot compare %s and %s' % (self, other))\n\n    def __eq__(self, other):\n        self._check_compatible(other)\n        return self.key == other.key and self._parts == other._parts\n\n    def __ne__(self, other):\n        return not self.__eq__(other)\n\n    # See http://docs.python.org/reference/datamodel#object.__hash__\n    def __hash__(self):\n        return hash(self.key) + hash(self._parts)\n\n    def __repr__(self):\n        return \"%s(%r)\" % (self.__class__.__name__, self._string)\n\n    def __str__(self):\n        return self._string\n\n\nPEP440_VERSION_RE = re.compile(r'^v?(\\d+!)?(\\d+(\\.\\d+)*)((a|b|c|rc)(\\d+))?'\n                               r'(\\.(post)(\\d+))?(\\.(dev)(\\d+))?'\n                               r'(\\+([a-zA-Z\\d]+(\\.[a-zA-Z\\d]+)?))?$')\n\n\ndef _pep_440_key(s):\n    s = s.strip()\n    m = PEP440_VERSION_RE.match(s)\n    if not m:\n        raise UnsupportedVersionError('Not a valid version: %s' % s)\n    groups = m.groups()\n    nums = tuple(int(v) for v in groups[1].split('.'))\n    while len(nums) > 1 and nums[-1] == 0:\n        nums = nums[:-1]\n\n    if not groups[0]:\n        epoch = 0\n    else:\n        epoch = int(groups[0][:-1])\n    pre = groups[4:6]\n    post = groups[7:9]\n    dev = groups[10:12]\n    local = groups[13]\n    if pre == (None, None):\n        pre = ()\n    else:\n        pre = pre[0], int(pre[1])\n    if post == (None, None):\n        post = ()\n    else:\n        post = post[0], int(post[1])\n    if dev == (None, None):\n        dev = ()\n    else:\n        dev = dev[0], int(dev[1])\n    if local is None:\n        local = ()\n    else:\n        parts = []\n        for part in local.split('.'):\n            # to ensure that numeric compares as > lexicographic, avoid\n            # comparing them directly, but encode a tuple which ensures\n            # correct sorting\n            if part.isdigit():\n                part = (1, int(part))\n            else:\n                part = (0, part)\n            parts.append(part)\n        local = tuple(parts)\n    if not pre:\n        # either before pre-release, or final release and after\n        if not post and dev:\n            # before pre-release\n            pre = ('a', -1)     # to sort before a0\n        else:\n            pre = ('z',)        # to sort after all pre-releases\n    # now look at the state of post and dev.\n    if not post:\n        post = ('_',)   # sort before 'a'\n    if not dev:\n        dev = ('final',)\n\n    #print('%s -> %s' % (s, m.groups()))\n    return epoch, nums, pre, post, dev, local\n\n\n_normalized_key = _pep_440_key\n\n\nclass NormalizedVersion(Version):\n    \"\"\"A rational version.\n\n    Good:\n        1.2         # equivalent to \"1.2.0\"\n        1.2.0\n        1.2a1\n        1.2.3a2\n        1.2.3b1\n        1.2.3c1\n        1.2.3.4\n        TODO: fill this out\n\n    Bad:\n        1           # minimum two numbers\n        1.2a        # release level must have a release serial\n        1.2.3b\n    \"\"\"\n    def parse(self, s):\n        result = _normalized_key(s)\n        # _normalized_key loses trailing zeroes in the release\n        # clause, since that's needed to ensure that X.Y == X.Y.0 == X.Y.0.0\n        # However, PEP 440 prefix matching needs it: for example,\n        # (~= 1.4.5.0) matches differently to (~= 1.4.5.0.0).\n        m = PEP440_VERSION_RE.match(s)      # must succeed\n        groups = m.groups()\n        self._release_clause = tuple(int(v) for v in groups[1].split('.'))\n        return result\n\n    PREREL_TAGS = set(['a', 'b', 'c', 'rc', 'dev'])\n\n    @property\n    def is_prerelease(self):\n        return any(t[0] in self.PREREL_TAGS for t in self._parts if t)\n\n\ndef _match_prefix(x, y):\n    x = str(x)\n    y = str(y)\n    if x == y:\n        return True\n    if not x.startswith(y):\n        return False\n    n = len(y)\n    return x[n] == '.'\n\n\nclass NormalizedMatcher(Matcher):\n    version_class = NormalizedVersion\n\n    # value is either a callable or the name of a method\n    _operators = {\n        '~=': '_match_compatible',\n        '<': '_match_lt',\n        '>': '_match_gt',\n        '<=': '_match_le',\n        '>=': '_match_ge',\n        '==': '_match_eq',\n        '===': '_match_arbitrary',\n        '!=': '_match_ne',\n    }\n\n    def _adjust_local(self, version, constraint, prefix):\n        if prefix:\n            strip_local = '+' not in constraint and version._parts[-1]\n        else:\n            # both constraint and version are\n            # NormalizedVersion instances.\n            # If constraint does not have a local component,\n            # ensure the version doesn't, either.\n            strip_local = not constraint._parts[-1] and version._parts[-1]\n        if strip_local:\n            s = version._string.split('+', 1)[0]\n            version = self.version_class(s)\n        return version, constraint\n\n    def _match_lt(self, version, constraint, prefix):\n        version, constraint = self._adjust_local(version, constraint, prefix)\n        if version >= constraint:\n            return False\n        release_clause = constraint._release_clause\n        pfx = '.'.join([str(i) for i in release_clause])\n        return not _match_prefix(version, pfx)\n\n    def _match_gt(self, version, constraint, prefix):\n        version, constraint = self._adjust_local(version, constraint, prefix)\n        if version <= constraint:\n            return False\n        release_clause = constraint._release_clause\n        pfx = '.'.join([str(i) for i in release_clause])\n        return not _match_prefix(version, pfx)\n\n    def _match_le(self, version, constraint, prefix):\n        version, constraint = self._adjust_local(version, constraint, prefix)\n        return version <= constraint\n\n    def _match_ge(self, version, constraint, prefix):\n        version, constraint = self._adjust_local(version, constraint, prefix)\n        return version >= constraint\n\n    def _match_eq(self, version, constraint, prefix):\n        version, constraint = self._adjust_local(version, constraint, prefix)\n        if not prefix:\n            result = (version == constraint)\n        else:\n            result = _match_prefix(version, constraint)\n        return result\n\n    def _match_arbitrary(self, version, constraint, prefix):\n        return str(version) == str(constraint)\n\n    def _match_ne(self, version, constraint, prefix):\n        version, constraint = self._adjust_local(version, constraint, prefix)\n        if not prefix:\n            result = (version != constraint)\n        else:\n            result = not _match_prefix(version, constraint)\n        return result\n\n    def _match_compatible(self, version, constraint, prefix):\n        version, constraint = self._adjust_local(version, constraint, prefix)\n        if version == constraint:\n            return True\n        if version < constraint:\n            return False\n#        if not prefix:\n#            return True\n        release_clause = constraint._release_clause\n        if len(release_clause) > 1:\n            release_clause = release_clause[:-1]\n        pfx = '.'.join([str(i) for i in release_clause])\n        return _match_prefix(version, pfx)\n\n_REPLACEMENTS = (\n    (re.compile('[.+-]$'), ''),                     # remove trailing puncts\n    (re.compile(r'^[.](\\d)'), r'0.\\1'),             # .N -> 0.N at start\n    (re.compile('^[.-]'), ''),                      # remove leading puncts\n    (re.compile(r'^\\((.*)\\)$'), r'\\1'),             # remove parentheses\n    (re.compile(r'^v(ersion)?\\s*(\\d+)'), r'\\2'),    # remove leading v(ersion)\n    (re.compile(r'^r(ev)?\\s*(\\d+)'), r'\\2'),        # remove leading v(ersion)\n    (re.compile('[.]{2,}'), '.'),                   # multiple runs of '.'\n    (re.compile(r'\\b(alfa|apha)\\b'), 'alpha'),      # misspelt alpha\n    (re.compile(r'\\b(pre-alpha|prealpha)\\b'),\n                'pre.alpha'),                       # standardise\n    (re.compile(r'\\(beta\\)$'), 'beta'),             # remove parentheses\n)\n\n_SUFFIX_REPLACEMENTS = (\n    (re.compile('^[:~._+-]+'), ''),                   # remove leading puncts\n    (re.compile('[,*\")([\\\\]]'), ''),                  # remove unwanted chars\n    (re.compile('[~:+_ -]'), '.'),                    # replace illegal chars\n    (re.compile('[.]{2,}'), '.'),                   # multiple runs of '.'\n    (re.compile(r'\\.$'), ''),                       # trailing '.'\n)\n\n_NUMERIC_PREFIX = re.compile(r'(\\d+(\\.\\d+)*)')\n\n\ndef _suggest_semantic_version(s):\n    \"\"\"\n    Try to suggest a semantic form for a version for which\n    _suggest_normalized_version couldn't come up with anything.\n    \"\"\"\n    result = s.strip().lower()\n    for pat, repl in _REPLACEMENTS:\n        result = pat.sub(repl, result)\n    if not result:\n        result = '0.0.0'\n\n    # Now look for numeric prefix, and separate it out from\n    # the rest.\n    #import pdb; pdb.set_trace()\n    m = _NUMERIC_PREFIX.match(result)\n    if not m:\n        prefix = '0.0.0'\n        suffix = result\n    else:\n        prefix = m.groups()[0].split('.')\n        prefix = [int(i) for i in prefix]\n        while len(prefix) < 3:\n            prefix.append(0)\n        if len(prefix) == 3:\n            suffix = result[m.end():]\n        else:\n            suffix = '.'.join([str(i) for i in prefix[3:]]) + result[m.end():]\n            prefix = prefix[:3]\n        prefix = '.'.join([str(i) for i in prefix])\n        suffix = suffix.strip()\n    if suffix:\n        #import pdb; pdb.set_trace()\n        # massage the suffix.\n        for pat, repl in _SUFFIX_REPLACEMENTS:\n            suffix = pat.sub(repl, suffix)\n\n    if not suffix:\n        result = prefix\n    else:\n        sep = '-' if 'dev' in suffix else '+'\n        result = prefix + sep + suffix\n    if not is_semver(result):\n        result = None\n    return result\n\n\ndef _suggest_normalized_version(s):\n    \"\"\"Suggest a normalized version close to the given version string.\n\n    If you have a version string that isn't rational (i.e. NormalizedVersion\n    doesn't like it) then you might be able to get an equivalent (or close)\n    rational version from this function.\n\n    This does a number of simple normalizations to the given string, based\n    on observation of versions currently in use on PyPI. Given a dump of\n    those version during PyCon 2009, 4287 of them:\n    - 2312 (53.93%) match NormalizedVersion without change\n      with the automatic suggestion\n    - 3474 (81.04%) match when using this suggestion method\n\n    @param s {str} An irrational version string.\n    @returns A rational version string, or None, if couldn't determine one.\n    \"\"\"\n    try:\n        _normalized_key(s)\n        return s   # already rational\n    except UnsupportedVersionError:\n        pass\n\n    rs = s.lower()\n\n    # part of this could use maketrans\n    for orig, repl in (('-alpha', 'a'), ('-beta', 'b'), ('alpha', 'a'),\n                       ('beta', 'b'), ('rc', 'c'), ('-final', ''),\n                       ('-pre', 'c'),\n                       ('-release', ''), ('.release', ''), ('-stable', ''),\n                       ('+', '.'), ('_', '.'), (' ', ''), ('.final', ''),\n                       ('final', '')):\n        rs = rs.replace(orig, repl)\n\n    # if something ends with dev or pre, we add a 0\n    rs = re.sub(r\"pre$\", r\"pre0\", rs)\n    rs = re.sub(r\"dev$\", r\"dev0\", rs)\n\n    # if we have something like \"b-2\" or \"a.2\" at the end of the\n    # version, that is probably beta, alpha, etc\n    # let's remove the dash or dot\n    rs = re.sub(r\"([abc]|rc)[\\-\\.](\\d+)$\", r\"\\1\\2\", rs)\n\n    # 1.0-dev-r371 -> 1.0.dev371\n    # 0.1-dev-r79 -> 0.1.dev79\n    rs = re.sub(r\"[\\-\\.](dev)[\\-\\.]?r?(\\d+)$\", r\".\\1\\2\", rs)\n\n    # Clean: 2.0.a.3, 2.0.b1, 0.9.0~c1\n    rs = re.sub(r\"[.~]?([abc])\\.?\", r\"\\1\", rs)\n\n    # Clean: v0.3, v1.0\n    if rs.startswith('v'):\n        rs = rs[1:]\n\n    # Clean leading '0's on numbers.\n    #TODO: unintended side-effect on, e.g., \"2003.05.09\"\n    # PyPI stats: 77 (~2%) better\n    rs = re.sub(r\"\\b0+(\\d+)(?!\\d)\", r\"\\1\", rs)\n\n    # Clean a/b/c with no version. E.g. \"1.0a\" -> \"1.0a0\". Setuptools infers\n    # zero.\n    # PyPI stats: 245 (7.56%) better\n    rs = re.sub(r\"(\\d+[abc])$\", r\"\\g<1>0\", rs)\n\n    # the 'dev-rNNN' tag is a dev tag\n    rs = re.sub(r\"\\.?(dev-r|dev\\.r)\\.?(\\d+)$\", r\".dev\\2\", rs)\n\n    # clean the - when used as a pre delimiter\n    rs = re.sub(r\"-(a|b|c)(\\d+)$\", r\"\\1\\2\", rs)\n\n    # a terminal \"dev\" or \"devel\" can be changed into \".dev0\"\n    rs = re.sub(r\"[\\.\\-](dev|devel)$\", r\".dev0\", rs)\n\n    # a terminal \"dev\" can be changed into \".dev0\"\n    rs = re.sub(r\"(?![\\.\\-])dev$\", r\".dev0\", rs)\n\n    # a terminal \"final\" or \"stable\" can be removed\n    rs = re.sub(r\"(final|stable)$\", \"\", rs)\n\n    # The 'r' and the '-' tags are post release tags\n    #   0.4a1.r10       ->  0.4a1.post10\n    #   0.9.33-17222    ->  0.9.33.post17222\n    #   0.9.33-r17222   ->  0.9.33.post17222\n    rs = re.sub(r\"\\.?(r|-|-r)\\.?(\\d+)$\", r\".post\\2\", rs)\n\n    # Clean 'r' instead of 'dev' usage:\n    #   0.9.33+r17222   ->  0.9.33.dev17222\n    #   1.0dev123       ->  1.0.dev123\n    #   1.0.git123      ->  1.0.dev123\n    #   1.0.bzr123      ->  1.0.dev123\n    #   0.1a0dev.123    ->  0.1a0.dev123\n    # PyPI stats:  ~150 (~4%) better\n    rs = re.sub(r\"\\.?(dev|git|bzr)\\.?(\\d+)$\", r\".dev\\2\", rs)\n\n    # Clean '.pre' (normalized from '-pre' above) instead of 'c' usage:\n    #   0.2.pre1        ->  0.2c1\n    #   0.2-c1         ->  0.2c1\n    #   1.0preview123   ->  1.0c123\n    # PyPI stats: ~21 (0.62%) better\n    rs = re.sub(r\"\\.?(pre|preview|-c)(\\d+)$\", r\"c\\g<2>\", rs)\n\n    # Tcl/Tk uses \"px\" for their post release markers\n    rs = re.sub(r\"p(\\d+)$\", r\".post\\1\", rs)\n\n    try:\n        _normalized_key(rs)\n    except UnsupportedVersionError:\n        rs = None\n    return rs\n\n#\n#   Legacy version processing (distribute-compatible)\n#\n\n_VERSION_PART = re.compile(r'([a-z]+|\\d+|[\\.-])', re.I)\n_VERSION_REPLACE = {\n    'pre': 'c',\n    'preview': 'c',\n    '-': 'final-',\n    'rc': 'c',\n    'dev': '@',\n    '': None,\n    '.': None,\n}\n\n\ndef _legacy_key(s):\n    def get_parts(s):\n        result = []\n        for p in _VERSION_PART.split(s.lower()):\n            p = _VERSION_REPLACE.get(p, p)\n            if p:\n                if '0' <= p[:1] <= '9':\n                    p = p.zfill(8)\n                else:\n                    p = '*' + p\n                result.append(p)\n        result.append('*final')\n        return result\n\n    result = []\n    for p in get_parts(s):\n        if p.startswith('*'):\n            if p < '*final':\n                while result and result[-1] == '*final-':\n                    result.pop()\n            while result and result[-1] == '00000000':\n                result.pop()\n        result.append(p)\n    return tuple(result)\n\n\nclass LegacyVersion(Version):\n    def parse(self, s):\n        return _legacy_key(s)\n\n    @property\n    def is_prerelease(self):\n        result = False\n        for x in self._parts:\n            if (isinstance(x, string_types) and x.startswith('*') and\n                x < '*final'):\n                result = True\n                break\n        return result\n\n\nclass LegacyMatcher(Matcher):\n    version_class = LegacyVersion\n\n    _operators = dict(Matcher._operators)\n    _operators['~='] = '_match_compatible'\n\n    numeric_re = re.compile(r'^(\\d+(\\.\\d+)*)')\n\n    def _match_compatible(self, version, constraint, prefix):\n        if version < constraint:\n            return False\n        m = self.numeric_re.match(str(constraint))\n        if not m:\n            logger.warning('Cannot compute compatible match for version %s '\n                           ' and constraint %s', version, constraint)\n            return True\n        s = m.groups()[0]\n        if '.' in s:\n            s = s.rsplit('.', 1)[0]\n        return _match_prefix(version, s)\n\n#\n#   Semantic versioning\n#\n\n_SEMVER_RE = re.compile(r'^(\\d+)\\.(\\d+)\\.(\\d+)'\n                        r'(-[a-z0-9]+(\\.[a-z0-9-]+)*)?'\n                        r'(\\+[a-z0-9]+(\\.[a-z0-9-]+)*)?$', re.I)\n\n\ndef is_semver(s):\n    return _SEMVER_RE.match(s)\n\n\ndef _semantic_key(s):\n    def make_tuple(s, absent):\n        if s is None:\n            result = (absent,)\n        else:\n            parts = s[1:].split('.')\n            # We can't compare ints and strings on Python 3, so fudge it\n            # by zero-filling numeric values so simulate a numeric comparison\n            result = tuple([p.zfill(8) if p.isdigit() else p for p in parts])\n        return result\n\n    m = is_semver(s)\n    if not m:\n        raise UnsupportedVersionError(s)\n    groups = m.groups()\n    major, minor, patch = [int(i) for i in groups[:3]]\n    # choose the '|' and '*' so that versions sort correctly\n    pre, build = make_tuple(groups[3], '|'), make_tuple(groups[5], '*')\n    return (major, minor, patch), pre, build\n\n\nclass SemanticVersion(Version):\n    def parse(self, s):\n        return _semantic_key(s)\n\n    @property\n    def is_prerelease(self):\n        return self._parts[1][0] != '|'\n\n\nclass SemanticMatcher(Matcher):\n    version_class = SemanticVersion\n\n\nclass VersionScheme(object):\n    def __init__(self, key, matcher, suggester=None):\n        self.key = key\n        self.matcher = matcher\n        self.suggester = suggester\n\n    def is_valid_version(self, s):\n        try:\n            self.matcher.version_class(s)\n            result = True\n        except UnsupportedVersionError:\n            result = False\n        return result\n\n    def is_valid_matcher(self, s):\n        try:\n            self.matcher(s)\n            result = True\n        except UnsupportedVersionError:\n            result = False\n        return result\n\n    def is_valid_constraint_list(self, s):\n        \"\"\"\n        Used for processing some metadata fields\n        \"\"\"\n        # See issue #140. Be tolerant of a single trailing comma.\n        if s.endswith(','):\n            s = s[:-1]\n        return self.is_valid_matcher('dummy_name (%s)' % s)\n\n    def suggest(self, s):\n        if self.suggester is None:\n            result = None\n        else:\n            result = self.suggester(s)\n        return result\n\n_SCHEMES = {\n    'normalized': VersionScheme(_normalized_key, NormalizedMatcher,\n                                _suggest_normalized_version),\n    'legacy': VersionScheme(_legacy_key, LegacyMatcher, lambda self, s: s),\n    'semantic': VersionScheme(_semantic_key, SemanticMatcher,\n                              _suggest_semantic_version),\n}\n\n_SCHEMES['default'] = _SCHEMES['normalized']\n\n\ndef get_scheme(name):\n    if name not in _SCHEMES:\n        raise ValueError('unknown scheme name: %r' % name)\n    return _SCHEMES[name]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distlib/wheel.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2013-2020 Vinay Sajip.\n# Licensed to the Python Software Foundation under a contributor agreement.\n# See LICENSE.txt and CONTRIBUTORS.txt.\n#\nfrom __future__ import unicode_literals\n\nimport base64\nimport codecs\nimport datetime\nfrom email import message_from_file\nimport hashlib\nimport json\nimport logging\nimport os\nimport posixpath\nimport re\nimport shutil\nimport sys\nimport tempfile\nimport zipfile\n\nfrom . import __version__, DistlibException\nfrom .compat import sysconfig, ZipFile, fsdecode, text_type, filter\nfrom .database import InstalledDistribution\nfrom .metadata import (Metadata, METADATA_FILENAME, WHEEL_METADATA_FILENAME,\n                       LEGACY_METADATA_FILENAME)\nfrom .util import (FileOperator, convert_path, CSVReader, CSVWriter, Cache,\n                   cached_property, get_cache_base, read_exports, tempdir,\n                   get_platform)\nfrom .version import NormalizedVersion, UnsupportedVersionError\n\nlogger = logging.getLogger(__name__)\n\ncache = None    # created when needed\n\nif hasattr(sys, 'pypy_version_info'):  # pragma: no cover\n    IMP_PREFIX = 'pp'\nelif sys.platform.startswith('java'):  # pragma: no cover\n    IMP_PREFIX = 'jy'\nelif sys.platform == 'cli':  # pragma: no cover\n    IMP_PREFIX = 'ip'\nelse:\n    IMP_PREFIX = 'cp'\n\nVER_SUFFIX = sysconfig.get_config_var('py_version_nodot')\nif not VER_SUFFIX:   # pragma: no cover\n    VER_SUFFIX = '%s%s' % sys.version_info[:2]\nPYVER = 'py' + VER_SUFFIX\nIMPVER = IMP_PREFIX + VER_SUFFIX\n\nARCH = get_platform().replace('-', '_').replace('.', '_')\n\nABI = sysconfig.get_config_var('SOABI')\nif ABI and ABI.startswith('cpython-'):\n    ABI = ABI.replace('cpython-', 'cp').split('-')[0]\nelse:\n    def _derive_abi():\n        parts = ['cp', VER_SUFFIX]\n        if sysconfig.get_config_var('Py_DEBUG'):\n            parts.append('d')\n        if IMP_PREFIX == 'cp':\n            vi = sys.version_info[:2]\n            if vi < (3, 8):\n                wpm = sysconfig.get_config_var('WITH_PYMALLOC')\n                if wpm is None:\n                    wpm = True\n                if wpm:\n                    parts.append('m')\n                if vi < (3, 3):\n                    us = sysconfig.get_config_var('Py_UNICODE_SIZE')\n                    if us == 4 or (us is None and sys.maxunicode == 0x10FFFF):\n                        parts.append('u')\n        return ''.join(parts)\n    ABI = _derive_abi()\n    del _derive_abi\n\nFILENAME_RE = re.compile(r'''\n(?P<nm>[^-]+)\n-(?P<vn>\\d+[^-]*)\n(-(?P<bn>\\d+[^-]*))?\n-(?P<py>\\w+\\d+(\\.\\w+\\d+)*)\n-(?P<bi>\\w+)\n-(?P<ar>\\w+(\\.\\w+)*)\n\\.whl$\n''', re.IGNORECASE | re.VERBOSE)\n\nNAME_VERSION_RE = re.compile(r'''\n(?P<nm>[^-]+)\n-(?P<vn>\\d+[^-]*)\n(-(?P<bn>\\d+[^-]*))?$\n''', re.IGNORECASE | re.VERBOSE)\n\nSHEBANG_RE = re.compile(br'\\s*#![^\\r\\n]*')\nSHEBANG_DETAIL_RE = re.compile(br'^(\\s*#!(\"[^\"]+\"|\\S+))\\s+(.*)$')\nSHEBANG_PYTHON = b'#!python'\nSHEBANG_PYTHONW = b'#!pythonw'\n\nif os.sep == '/':\n    to_posix = lambda o: o\nelse:\n    to_posix = lambda o: o.replace(os.sep, '/')\n\nif sys.version_info[0] < 3:\n    import imp\nelse:\n    imp = None\n    import importlib.machinery\n    import importlib.util\n\ndef _get_suffixes():\n    if imp:\n        return [s[0] for s in imp.get_suffixes()]\n    else:\n        return importlib.machinery.EXTENSION_SUFFIXES\n\ndef _load_dynamic(name, path):\n    # https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly\n    if imp:\n        return imp.load_dynamic(name, path)\n    else:\n        spec = importlib.util.spec_from_file_location(name, path)\n        module = importlib.util.module_from_spec(spec)\n        sys.modules[name] = module\n        spec.loader.exec_module(module)\n        return module\n\nclass Mounter(object):\n    def __init__(self):\n        self.impure_wheels = {}\n        self.libs = {}\n\n    def add(self, pathname, extensions):\n        self.impure_wheels[pathname] = extensions\n        self.libs.update(extensions)\n\n    def remove(self, pathname):\n        extensions = self.impure_wheels.pop(pathname)\n        for k, v in extensions:\n            if k in self.libs:\n                del self.libs[k]\n\n    def find_module(self, fullname, path=None):\n        if fullname in self.libs:\n            result = self\n        else:\n            result = None\n        return result\n\n    def load_module(self, fullname):\n        if fullname in sys.modules:\n            result = sys.modules[fullname]\n        else:\n            if fullname not in self.libs:\n                raise ImportError('unable to find extension for %s' % fullname)\n            result = _load_dynamic(fullname, self.libs[fullname])\n            result.__loader__ = self\n            parts = fullname.rsplit('.', 1)\n            if len(parts) > 1:\n                result.__package__ = parts[0]\n        return result\n\n_hook = Mounter()\n\n\nclass Wheel(object):\n    \"\"\"\n    Class to build and install from Wheel files (PEP 427).\n    \"\"\"\n\n    wheel_version = (1, 1)\n    hash_kind = 'sha256'\n\n    def __init__(self, filename=None, sign=False, verify=False):\n        \"\"\"\n        Initialise an instance using a (valid) filename.\n        \"\"\"\n        self.sign = sign\n        self.should_verify = verify\n        self.buildver = ''\n        self.pyver = [PYVER]\n        self.abi = ['none']\n        self.arch = ['any']\n        self.dirname = os.getcwd()\n        if filename is None:\n            self.name = 'dummy'\n            self.version = '0.1'\n            self._filename = self.filename\n        else:\n            m = NAME_VERSION_RE.match(filename)\n            if m:\n                info = m.groupdict('')\n                self.name = info['nm']\n                # Reinstate the local version separator\n                self.version = info['vn'].replace('_', '-')\n                self.buildver = info['bn']\n                self._filename = self.filename\n            else:\n                dirname, filename = os.path.split(filename)\n                m = FILENAME_RE.match(filename)\n                if not m:\n                    raise DistlibException('Invalid name or '\n                                           'filename: %r' % filename)\n                if dirname:\n                    self.dirname = os.path.abspath(dirname)\n                self._filename = filename\n                info = m.groupdict('')\n                self.name = info['nm']\n                self.version = info['vn']\n                self.buildver = info['bn']\n                self.pyver = info['py'].split('.')\n                self.abi = info['bi'].split('.')\n                self.arch = info['ar'].split('.')\n\n    @property\n    def filename(self):\n        \"\"\"\n        Build and return a filename from the various components.\n        \"\"\"\n        if self.buildver:\n            buildver = '-' + self.buildver\n        else:\n            buildver = ''\n        pyver = '.'.join(self.pyver)\n        abi = '.'.join(self.abi)\n        arch = '.'.join(self.arch)\n        # replace - with _ as a local version separator\n        version = self.version.replace('-', '_')\n        return '%s-%s%s-%s-%s-%s.whl' % (self.name, version, buildver,\n                                         pyver, abi, arch)\n\n    @property\n    def exists(self):\n        path = os.path.join(self.dirname, self.filename)\n        return os.path.isfile(path)\n\n    @property\n    def tags(self):\n        for pyver in self.pyver:\n            for abi in self.abi:\n                for arch in self.arch:\n                    yield pyver, abi, arch\n\n    @cached_property\n    def metadata(self):\n        pathname = os.path.join(self.dirname, self.filename)\n        name_ver = '%s-%s' % (self.name, self.version)\n        info_dir = '%s.dist-info' % name_ver\n        wrapper = codecs.getreader('utf-8')\n        with ZipFile(pathname, 'r') as zf:\n            wheel_metadata = self.get_wheel_metadata(zf)\n            wv = wheel_metadata['Wheel-Version'].split('.', 1)\n            file_version = tuple([int(i) for i in wv])\n            # if file_version < (1, 1):\n                # fns = [WHEEL_METADATA_FILENAME, METADATA_FILENAME,\n                       # LEGACY_METADATA_FILENAME]\n            # else:\n                # fns = [WHEEL_METADATA_FILENAME, METADATA_FILENAME]\n            fns = [WHEEL_METADATA_FILENAME, LEGACY_METADATA_FILENAME]\n            result = None\n            for fn in fns:\n                try:\n                    metadata_filename = posixpath.join(info_dir, fn)\n                    with zf.open(metadata_filename) as bf:\n                        wf = wrapper(bf)\n                        result = Metadata(fileobj=wf)\n                        if result:\n                            break\n                except KeyError:\n                    pass\n            if not result:\n                raise ValueError('Invalid wheel, because metadata is '\n                                 'missing: looked in %s' % ', '.join(fns))\n        return result\n\n    def get_wheel_metadata(self, zf):\n        name_ver = '%s-%s' % (self.name, self.version)\n        info_dir = '%s.dist-info' % name_ver\n        metadata_filename = posixpath.join(info_dir, 'WHEEL')\n        with zf.open(metadata_filename) as bf:\n            wf = codecs.getreader('utf-8')(bf)\n            message = message_from_file(wf)\n        return dict(message)\n\n    @cached_property\n    def info(self):\n        pathname = os.path.join(self.dirname, self.filename)\n        with ZipFile(pathname, 'r') as zf:\n            result = self.get_wheel_metadata(zf)\n        return result\n\n    def process_shebang(self, data):\n        m = SHEBANG_RE.match(data)\n        if m:\n            end = m.end()\n            shebang, data_after_shebang = data[:end], data[end:]\n            # Preserve any arguments after the interpreter\n            if b'pythonw' in shebang.lower():\n                shebang_python = SHEBANG_PYTHONW\n            else:\n                shebang_python = SHEBANG_PYTHON\n            m = SHEBANG_DETAIL_RE.match(shebang)\n            if m:\n                args = b' ' + m.groups()[-1]\n            else:\n                args = b''\n            shebang = shebang_python + args\n            data = shebang + data_after_shebang\n        else:\n            cr = data.find(b'\\r')\n            lf = data.find(b'\\n')\n            if cr < 0 or cr > lf:\n                term = b'\\n'\n            else:\n                if data[cr:cr + 2] == b'\\r\\n':\n                    term = b'\\r\\n'\n                else:\n                    term = b'\\r'\n            data = SHEBANG_PYTHON + term + data\n        return data\n\n    def get_hash(self, data, hash_kind=None):\n        if hash_kind is None:\n            hash_kind = self.hash_kind\n        try:\n            hasher = getattr(hashlib, hash_kind)\n        except AttributeError:\n            raise DistlibException('Unsupported hash algorithm: %r' % hash_kind)\n        result = hasher(data).digest()\n        result = base64.urlsafe_b64encode(result).rstrip(b'=').decode('ascii')\n        return hash_kind, result\n\n    def write_record(self, records, record_path, archive_record_path):\n        records = list(records) # make a copy, as mutated\n        records.append((archive_record_path, '', ''))\n        with CSVWriter(record_path) as writer:\n            for row in records:\n                writer.writerow(row)\n\n    def write_records(self, info, libdir, archive_paths):\n        records = []\n        distinfo, info_dir = info\n        hasher = getattr(hashlib, self.hash_kind)\n        for ap, p in archive_paths:\n            with open(p, 'rb') as f:\n                data = f.read()\n            digest = '%s=%s' % self.get_hash(data)\n            size = os.path.getsize(p)\n            records.append((ap, digest, size))\n\n        p = os.path.join(distinfo, 'RECORD')\n        ap = to_posix(os.path.join(info_dir, 'RECORD'))\n        self.write_record(records, p, ap)\n        archive_paths.append((ap, p))\n\n    def build_zip(self, pathname, archive_paths):\n        with ZipFile(pathname, 'w', zipfile.ZIP_DEFLATED) as zf:\n            for ap, p in archive_paths:\n                logger.debug('Wrote %s to %s in wheel', p, ap)\n                zf.write(p, ap)\n\n    def build(self, paths, tags=None, wheel_version=None):\n        \"\"\"\n        Build a wheel from files in specified paths, and use any specified tags\n        when determining the name of the wheel.\n        \"\"\"\n        if tags is None:\n            tags = {}\n\n        libkey = list(filter(lambda o: o in paths, ('purelib', 'platlib')))[0]\n        if libkey == 'platlib':\n            is_pure = 'false'\n            default_pyver = [IMPVER]\n            default_abi = [ABI]\n            default_arch = [ARCH]\n        else:\n            is_pure = 'true'\n            default_pyver = [PYVER]\n            default_abi = ['none']\n            default_arch = ['any']\n\n        self.pyver = tags.get('pyver', default_pyver)\n        self.abi = tags.get('abi', default_abi)\n        self.arch = tags.get('arch', default_arch)\n\n        libdir = paths[libkey]\n\n        name_ver = '%s-%s' % (self.name, self.version)\n        data_dir = '%s.data' % name_ver\n        info_dir = '%s.dist-info' % name_ver\n\n        archive_paths = []\n\n        # First, stuff which is not in site-packages\n        for key in ('data', 'headers', 'scripts'):\n            if key not in paths:\n                continue\n            path = paths[key]\n            if os.path.isdir(path):\n                for root, dirs, files in os.walk(path):\n                    for fn in files:\n                        p = fsdecode(os.path.join(root, fn))\n                        rp = os.path.relpath(p, path)\n                        ap = to_posix(os.path.join(data_dir, key, rp))\n                        archive_paths.append((ap, p))\n                        if key == 'scripts' and not p.endswith('.exe'):\n                            with open(p, 'rb') as f:\n                                data = f.read()\n                            data = self.process_shebang(data)\n                            with open(p, 'wb') as f:\n                                f.write(data)\n\n        # Now, stuff which is in site-packages, other than the\n        # distinfo stuff.\n        path = libdir\n        distinfo = None\n        for root, dirs, files in os.walk(path):\n            if root == path:\n                # At the top level only, save distinfo for later\n                # and skip it for now\n                for i, dn in enumerate(dirs):\n                    dn = fsdecode(dn)\n                    if dn.endswith('.dist-info'):\n                        distinfo = os.path.join(root, dn)\n                        del dirs[i]\n                        break\n                assert distinfo, '.dist-info directory expected, not found'\n\n            for fn in files:\n                # comment out next suite to leave .pyc files in\n                if fsdecode(fn).endswith(('.pyc', '.pyo')):\n                    continue\n                p = os.path.join(root, fn)\n                rp = to_posix(os.path.relpath(p, path))\n                archive_paths.append((rp, p))\n\n        # Now distinfo. Assumed to be flat, i.e. os.listdir is enough.\n        files = os.listdir(distinfo)\n        for fn in files:\n            if fn not in ('RECORD', 'INSTALLER', 'SHARED', 'WHEEL'):\n                p = fsdecode(os.path.join(distinfo, fn))\n                ap = to_posix(os.path.join(info_dir, fn))\n                archive_paths.append((ap, p))\n\n        wheel_metadata = [\n            'Wheel-Version: %d.%d' % (wheel_version or self.wheel_version),\n            'Generator: distlib %s' % __version__,\n            'Root-Is-Purelib: %s' % is_pure,\n        ]\n        for pyver, abi, arch in self.tags:\n            wheel_metadata.append('Tag: %s-%s-%s' % (pyver, abi, arch))\n        p = os.path.join(distinfo, 'WHEEL')\n        with open(p, 'w') as f:\n            f.write('\\n'.join(wheel_metadata))\n        ap = to_posix(os.path.join(info_dir, 'WHEEL'))\n        archive_paths.append((ap, p))\n\n        # sort the entries by archive path. Not needed by any spec, but it\n        # keeps the archive listing and RECORD tidier than they would otherwise\n        # be. Use the number of path segments to keep directory entries together,\n        # and keep the dist-info stuff at the end.\n        def sorter(t):\n            ap = t[0]\n            n = ap.count('/')\n            if '.dist-info' in ap:\n                n += 10000\n            return (n, ap)\n        archive_paths = sorted(archive_paths, key=sorter)\n\n        # Now, at last, RECORD.\n        # Paths in here are archive paths - nothing else makes sense.\n        self.write_records((distinfo, info_dir), libdir, archive_paths)\n        # Now, ready to build the zip file\n        pathname = os.path.join(self.dirname, self.filename)\n        self.build_zip(pathname, archive_paths)\n        return pathname\n\n    def skip_entry(self, arcname):\n        \"\"\"\n        Determine whether an archive entry should be skipped when verifying\n        or installing.\n        \"\"\"\n        # The signature file won't be in RECORD,\n        # and we  don't currently don't do anything with it\n        # We also skip directories, as they won't be in RECORD\n        # either. See:\n        #\n        # https://github.com/pypa/wheel/issues/294\n        # https://github.com/pypa/wheel/issues/287\n        # https://github.com/pypa/wheel/pull/289\n        #\n        return arcname.endswith(('/', '/RECORD.jws'))\n\n    def install(self, paths, maker, **kwargs):\n        \"\"\"\n        Install a wheel to the specified paths. If kwarg ``warner`` is\n        specified, it should be a callable, which will be called with two\n        tuples indicating the wheel version of this software and the wheel\n        version in the file, if there is a discrepancy in the versions.\n        This can be used to issue any warnings to raise any exceptions.\n        If kwarg ``lib_only`` is True, only the purelib/platlib files are\n        installed, and the headers, scripts, data and dist-info metadata are\n        not written. If kwarg ``bytecode_hashed_invalidation`` is True, written\n        bytecode will try to use file-hash based invalidation (PEP-552) on\n        supported interpreter versions (CPython 2.7+).\n\n        The return value is a :class:`InstalledDistribution` instance unless\n        ``options.lib_only`` is True, in which case the return value is ``None``.\n        \"\"\"\n\n        dry_run = maker.dry_run\n        warner = kwargs.get('warner')\n        lib_only = kwargs.get('lib_only', False)\n        bc_hashed_invalidation = kwargs.get('bytecode_hashed_invalidation', False)\n\n        pathname = os.path.join(self.dirname, self.filename)\n        name_ver = '%s-%s' % (self.name, self.version)\n        data_dir = '%s.data' % name_ver\n        info_dir = '%s.dist-info' % name_ver\n\n        metadata_name = posixpath.join(info_dir, LEGACY_METADATA_FILENAME)\n        wheel_metadata_name = posixpath.join(info_dir, 'WHEEL')\n        record_name = posixpath.join(info_dir, 'RECORD')\n\n        wrapper = codecs.getreader('utf-8')\n\n        with ZipFile(pathname, 'r') as zf:\n            with zf.open(wheel_metadata_name) as bwf:\n                wf = wrapper(bwf)\n                message = message_from_file(wf)\n            wv = message['Wheel-Version'].split('.', 1)\n            file_version = tuple([int(i) for i in wv])\n            if (file_version != self.wheel_version) and warner:\n                warner(self.wheel_version, file_version)\n\n            if message['Root-Is-Purelib'] == 'true':\n                libdir = paths['purelib']\n            else:\n                libdir = paths['platlib']\n\n            records = {}\n            with zf.open(record_name) as bf:\n                with CSVReader(stream=bf) as reader:\n                    for row in reader:\n                        p = row[0]\n                        records[p] = row\n\n            data_pfx = posixpath.join(data_dir, '')\n            info_pfx = posixpath.join(info_dir, '')\n            script_pfx = posixpath.join(data_dir, 'scripts', '')\n\n            # make a new instance rather than a copy of maker's,\n            # as we mutate it\n            fileop = FileOperator(dry_run=dry_run)\n            fileop.record = True    # so we can rollback if needed\n\n            bc = not sys.dont_write_bytecode    # Double negatives. Lovely!\n\n            outfiles = []   # for RECORD writing\n\n            # for script copying/shebang processing\n            workdir = tempfile.mkdtemp()\n            # set target dir later\n            # we default add_launchers to False, as the\n            # Python Launcher should be used instead\n            maker.source_dir = workdir\n            maker.target_dir = None\n            try:\n                for zinfo in zf.infolist():\n                    arcname = zinfo.filename\n                    if isinstance(arcname, text_type):\n                        u_arcname = arcname\n                    else:\n                        u_arcname = arcname.decode('utf-8')\n                    if self.skip_entry(u_arcname):\n                        continue\n                    row = records[u_arcname]\n                    if row[2] and str(zinfo.file_size) != row[2]:\n                        raise DistlibException('size mismatch for '\n                                               '%s' % u_arcname)\n                    if row[1]:\n                        kind, value = row[1].split('=', 1)\n                        with zf.open(arcname) as bf:\n                            data = bf.read()\n                        _, digest = self.get_hash(data, kind)\n                        if digest != value:\n                            raise DistlibException('digest mismatch for '\n                                                   '%s' % arcname)\n\n                    if lib_only and u_arcname.startswith((info_pfx, data_pfx)):\n                        logger.debug('lib_only: skipping %s', u_arcname)\n                        continue\n                    is_script = (u_arcname.startswith(script_pfx)\n                                 and not u_arcname.endswith('.exe'))\n\n                    if u_arcname.startswith(data_pfx):\n                        _, where, rp = u_arcname.split('/', 2)\n                        outfile = os.path.join(paths[where], convert_path(rp))\n                    else:\n                        # meant for site-packages.\n                        if u_arcname in (wheel_metadata_name, record_name):\n                            continue\n                        outfile = os.path.join(libdir, convert_path(u_arcname))\n                    if not is_script:\n                        with zf.open(arcname) as bf:\n                            fileop.copy_stream(bf, outfile)\n                        # Issue #147: permission bits aren't preserved. Using\n                        # zf.extract(zinfo, libdir) should have worked, but didn't,\n                        # see https://www.thetopsites.net/article/53834422.shtml\n                        # So ... manually preserve permission bits as given in zinfo\n                        if os.name == 'posix':\n                            # just set the normal permission bits\n                            os.chmod(outfile, (zinfo.external_attr >> 16) & 0x1FF)\n                        outfiles.append(outfile)\n                        # Double check the digest of the written file\n                        if not dry_run and row[1]:\n                            with open(outfile, 'rb') as bf:\n                                data = bf.read()\n                                _, newdigest = self.get_hash(data, kind)\n                                if newdigest != digest:\n                                    raise DistlibException('digest mismatch '\n                                                           'on write for '\n                                                           '%s' % outfile)\n                        if bc and outfile.endswith('.py'):\n                            try:\n                                pyc = fileop.byte_compile(outfile,\n                                                          hashed_invalidation=bc_hashed_invalidation)\n                                outfiles.append(pyc)\n                            except Exception:\n                                # Don't give up if byte-compilation fails,\n                                # but log it and perhaps warn the user\n                                logger.warning('Byte-compilation failed',\n                                               exc_info=True)\n                    else:\n                        fn = os.path.basename(convert_path(arcname))\n                        workname = os.path.join(workdir, fn)\n                        with zf.open(arcname) as bf:\n                            fileop.copy_stream(bf, workname)\n\n                        dn, fn = os.path.split(outfile)\n                        maker.target_dir = dn\n                        filenames = maker.make(fn)\n                        fileop.set_executable_mode(filenames)\n                        outfiles.extend(filenames)\n\n                if lib_only:\n                    logger.debug('lib_only: returning None')\n                    dist = None\n                else:\n                    # Generate scripts\n\n                    # Try to get pydist.json so we can see if there are\n                    # any commands to generate. If this fails (e.g. because\n                    # of a legacy wheel), log a warning but don't give up.\n                    commands = None\n                    file_version = self.info['Wheel-Version']\n                    if file_version == '1.0':\n                        # Use legacy info\n                        ep = posixpath.join(info_dir, 'entry_points.txt')\n                        try:\n                            with zf.open(ep) as bwf:\n                                epdata = read_exports(bwf)\n                            commands = {}\n                            for key in ('console', 'gui'):\n                                k = '%s_scripts' % key\n                                if k in epdata:\n                                    commands['wrap_%s' % key] = d = {}\n                                    for v in epdata[k].values():\n                                        s = '%s:%s' % (v.prefix, v.suffix)\n                                        if v.flags:\n                                            s += ' [%s]' % ','.join(v.flags)\n                                        d[v.name] = s\n                        except Exception:\n                            logger.warning('Unable to read legacy script '\n                                           'metadata, so cannot generate '\n                                           'scripts')\n                    else:\n                        try:\n                            with zf.open(metadata_name) as bwf:\n                                wf = wrapper(bwf)\n                                commands = json.load(wf).get('extensions')\n                                if commands:\n                                    commands = commands.get('python.commands')\n                        except Exception:\n                            logger.warning('Unable to read JSON metadata, so '\n                                           'cannot generate scripts')\n                    if commands:\n                        console_scripts = commands.get('wrap_console', {})\n                        gui_scripts = commands.get('wrap_gui', {})\n                        if console_scripts or gui_scripts:\n                            script_dir = paths.get('scripts', '')\n                            if not os.path.isdir(script_dir):\n                                raise ValueError('Valid script path not '\n                                                 'specified')\n                            maker.target_dir = script_dir\n                            for k, v in console_scripts.items():\n                                script = '%s = %s' % (k, v)\n                                filenames = maker.make(script)\n                                fileop.set_executable_mode(filenames)\n\n                            if gui_scripts:\n                                options = {'gui': True }\n                                for k, v in gui_scripts.items():\n                                    script = '%s = %s' % (k, v)\n                                    filenames = maker.make(script, options)\n                                    fileop.set_executable_mode(filenames)\n\n                    p = os.path.join(libdir, info_dir)\n                    dist = InstalledDistribution(p)\n\n                    # Write SHARED\n                    paths = dict(paths)     # don't change passed in dict\n                    del paths['purelib']\n                    del paths['platlib']\n                    paths['lib'] = libdir\n                    p = dist.write_shared_locations(paths, dry_run)\n                    if p:\n                        outfiles.append(p)\n\n                    # Write RECORD\n                    dist.write_installed_files(outfiles, paths['prefix'],\n                                               dry_run)\n                return dist\n            except Exception:  # pragma: no cover\n                logger.exception('installation failed.')\n                fileop.rollback()\n                raise\n            finally:\n                shutil.rmtree(workdir)\n\n    def _get_dylib_cache(self):\n        global cache\n        if cache is None:\n            # Use native string to avoid issues on 2.x: see Python #20140.\n            base = os.path.join(get_cache_base(), str('dylib-cache'),\n                                '%s.%s' % sys.version_info[:2])\n            cache = Cache(base)\n        return cache\n\n    def _get_extensions(self):\n        pathname = os.path.join(self.dirname, self.filename)\n        name_ver = '%s-%s' % (self.name, self.version)\n        info_dir = '%s.dist-info' % name_ver\n        arcname = posixpath.join(info_dir, 'EXTENSIONS')\n        wrapper = codecs.getreader('utf-8')\n        result = []\n        with ZipFile(pathname, 'r') as zf:\n            try:\n                with zf.open(arcname) as bf:\n                    wf = wrapper(bf)\n                    extensions = json.load(wf)\n                    cache = self._get_dylib_cache()\n                    prefix = cache.prefix_to_dir(pathname)\n                    cache_base = os.path.join(cache.base, prefix)\n                    if not os.path.isdir(cache_base):\n                        os.makedirs(cache_base)\n                    for name, relpath in extensions.items():\n                        dest = os.path.join(cache_base, convert_path(relpath))\n                        if not os.path.exists(dest):\n                            extract = True\n                        else:\n                            file_time = os.stat(dest).st_mtime\n                            file_time = datetime.datetime.fromtimestamp(file_time)\n                            info = zf.getinfo(relpath)\n                            wheel_time = datetime.datetime(*info.date_time)\n                            extract = wheel_time > file_time\n                        if extract:\n                            zf.extract(relpath, cache_base)\n                        result.append((name, dest))\n            except KeyError:\n                pass\n        return result\n\n    def is_compatible(self):\n        \"\"\"\n        Determine if a wheel is compatible with the running system.\n        \"\"\"\n        return is_compatible(self)\n\n    def is_mountable(self):\n        \"\"\"\n        Determine if a wheel is asserted as mountable by its metadata.\n        \"\"\"\n        return True # for now - metadata details TBD\n\n    def mount(self, append=False):\n        pathname = os.path.abspath(os.path.join(self.dirname, self.filename))\n        if not self.is_compatible():\n            msg = 'Wheel %s not compatible with this Python.' % pathname\n            raise DistlibException(msg)\n        if not self.is_mountable():\n            msg = 'Wheel %s is marked as not mountable.' % pathname\n            raise DistlibException(msg)\n        if pathname in sys.path:\n            logger.debug('%s already in path', pathname)\n        else:\n            if append:\n                sys.path.append(pathname)\n            else:\n                sys.path.insert(0, pathname)\n            extensions = self._get_extensions()\n            if extensions:\n                if _hook not in sys.meta_path:\n                    sys.meta_path.append(_hook)\n                _hook.add(pathname, extensions)\n\n    def unmount(self):\n        pathname = os.path.abspath(os.path.join(self.dirname, self.filename))\n        if pathname not in sys.path:\n            logger.debug('%s not in path', pathname)\n        else:\n            sys.path.remove(pathname)\n            if pathname in _hook.impure_wheels:\n                _hook.remove(pathname)\n            if not _hook.impure_wheels:\n                if _hook in sys.meta_path:\n                    sys.meta_path.remove(_hook)\n\n    def verify(self):\n        pathname = os.path.join(self.dirname, self.filename)\n        name_ver = '%s-%s' % (self.name, self.version)\n        data_dir = '%s.data' % name_ver\n        info_dir = '%s.dist-info' % name_ver\n\n        metadata_name = posixpath.join(info_dir, LEGACY_METADATA_FILENAME)\n        wheel_metadata_name = posixpath.join(info_dir, 'WHEEL')\n        record_name = posixpath.join(info_dir, 'RECORD')\n\n        wrapper = codecs.getreader('utf-8')\n\n        with ZipFile(pathname, 'r') as zf:\n            with zf.open(wheel_metadata_name) as bwf:\n                wf = wrapper(bwf)\n                message = message_from_file(wf)\n            wv = message['Wheel-Version'].split('.', 1)\n            file_version = tuple([int(i) for i in wv])\n            # TODO version verification\n\n            records = {}\n            with zf.open(record_name) as bf:\n                with CSVReader(stream=bf) as reader:\n                    for row in reader:\n                        p = row[0]\n                        records[p] = row\n\n            for zinfo in zf.infolist():\n                arcname = zinfo.filename\n                if isinstance(arcname, text_type):\n                    u_arcname = arcname\n                else:\n                    u_arcname = arcname.decode('utf-8')\n                # See issue #115: some wheels have .. in their entries, but\n                # in the filename ... e.g. __main__..py ! So the check is\n                # updated to look for .. in the directory portions\n                p = u_arcname.split('/')\n                if '..' in p:\n                    raise DistlibException('invalid entry in '\n                                           'wheel: %r' % u_arcname)\n\n                if self.skip_entry(u_arcname):\n                    continue\n                row = records[u_arcname]\n                if row[2] and str(zinfo.file_size) != row[2]:\n                    raise DistlibException('size mismatch for '\n                                           '%s' % u_arcname)\n                if row[1]:\n                    kind, value = row[1].split('=', 1)\n                    with zf.open(arcname) as bf:\n                        data = bf.read()\n                    _, digest = self.get_hash(data, kind)\n                    if digest != value:\n                        raise DistlibException('digest mismatch for '\n                                               '%s' % arcname)\n\n    def update(self, modifier, dest_dir=None, **kwargs):\n        \"\"\"\n        Update the contents of a wheel in a generic way. The modifier should\n        be a callable which expects a dictionary argument: its keys are\n        archive-entry paths, and its values are absolute filesystem paths\n        where the contents the corresponding archive entries can be found. The\n        modifier is free to change the contents of the files pointed to, add\n        new entries and remove entries, before returning. This method will\n        extract the entire contents of the wheel to a temporary location, call\n        the modifier, and then use the passed (and possibly updated)\n        dictionary to write a new wheel. If ``dest_dir`` is specified, the new\n        wheel is written there -- otherwise, the original wheel is overwritten.\n\n        The modifier should return True if it updated the wheel, else False.\n        This method returns the same value the modifier returns.\n        \"\"\"\n\n        def get_version(path_map, info_dir):\n            version = path = None\n            key = '%s/%s' % (info_dir, LEGACY_METADATA_FILENAME)\n            if key not in path_map:\n                key = '%s/PKG-INFO' % info_dir\n            if key in path_map:\n                path = path_map[key]\n                version = Metadata(path=path).version\n            return version, path\n\n        def update_version(version, path):\n            updated = None\n            try:\n                v = NormalizedVersion(version)\n                i = version.find('-')\n                if i < 0:\n                    updated = '%s+1' % version\n                else:\n                    parts = [int(s) for s in version[i + 1:].split('.')]\n                    parts[-1] += 1\n                    updated = '%s+%s' % (version[:i],\n                                         '.'.join(str(i) for i in parts))\n            except UnsupportedVersionError:\n                logger.debug('Cannot update non-compliant (PEP-440) '\n                             'version %r', version)\n            if updated:\n                md = Metadata(path=path)\n                md.version = updated\n                legacy = path.endswith(LEGACY_METADATA_FILENAME)\n                md.write(path=path, legacy=legacy)\n                logger.debug('Version updated from %r to %r', version,\n                             updated)\n\n        pathname = os.path.join(self.dirname, self.filename)\n        name_ver = '%s-%s' % (self.name, self.version)\n        info_dir = '%s.dist-info' % name_ver\n        record_name = posixpath.join(info_dir, 'RECORD')\n        with tempdir() as workdir:\n            with ZipFile(pathname, 'r') as zf:\n                path_map = {}\n                for zinfo in zf.infolist():\n                    arcname = zinfo.filename\n                    if isinstance(arcname, text_type):\n                        u_arcname = arcname\n                    else:\n                        u_arcname = arcname.decode('utf-8')\n                    if u_arcname == record_name:\n                        continue\n                    if '..' in u_arcname:\n                        raise DistlibException('invalid entry in '\n                                               'wheel: %r' % u_arcname)\n                    zf.extract(zinfo, workdir)\n                    path = os.path.join(workdir, convert_path(u_arcname))\n                    path_map[u_arcname] = path\n\n            # Remember the version.\n            original_version, _ = get_version(path_map, info_dir)\n            # Files extracted. Call the modifier.\n            modified = modifier(path_map, **kwargs)\n            if modified:\n                # Something changed - need to build a new wheel.\n                current_version, path = get_version(path_map, info_dir)\n                if current_version and (current_version == original_version):\n                    # Add or update local version to signify changes.\n                    update_version(current_version, path)\n                # Decide where the new wheel goes.\n                if dest_dir is None:\n                    fd, newpath = tempfile.mkstemp(suffix='.whl',\n                                                   prefix='wheel-update-',\n                                                   dir=workdir)\n                    os.close(fd)\n                else:\n                    if not os.path.isdir(dest_dir):\n                        raise DistlibException('Not a directory: %r' % dest_dir)\n                    newpath = os.path.join(dest_dir, self.filename)\n                archive_paths = list(path_map.items())\n                distinfo = os.path.join(workdir, info_dir)\n                info = distinfo, info_dir\n                self.write_records(info, workdir, archive_paths)\n                self.build_zip(newpath, archive_paths)\n                if dest_dir is None:\n                    shutil.copyfile(newpath, pathname)\n        return modified\n\ndef _get_glibc_version():\n    import platform\n    ver = platform.libc_ver()\n    result = []\n    if ver[0] == 'glibc':\n        for s in ver[1].split('.'):\n            result.append(int(s) if s.isdigit() else 0)\n        result = tuple(result)\n    return result\n\ndef compatible_tags():\n    \"\"\"\n    Return (pyver, abi, arch) tuples compatible with this Python.\n    \"\"\"\n    versions = [VER_SUFFIX]\n    major = VER_SUFFIX[0]\n    for minor in range(sys.version_info[1] - 1, - 1, -1):\n        versions.append(''.join([major, str(minor)]))\n\n    abis = []\n    for suffix in _get_suffixes():\n        if suffix.startswith('.abi'):\n            abis.append(suffix.split('.', 2)[1])\n    abis.sort()\n    if ABI != 'none':\n        abis.insert(0, ABI)\n    abis.append('none')\n    result = []\n\n    arches = [ARCH]\n    if sys.platform == 'darwin':\n        m = re.match(r'(\\w+)_(\\d+)_(\\d+)_(\\w+)$', ARCH)\n        if m:\n            name, major, minor, arch = m.groups()\n            minor = int(minor)\n            matches = [arch]\n            if arch in ('i386', 'ppc'):\n                matches.append('fat')\n            if arch in ('i386', 'ppc', 'x86_64'):\n                matches.append('fat3')\n            if arch in ('ppc64', 'x86_64'):\n                matches.append('fat64')\n            if arch in ('i386', 'x86_64'):\n                matches.append('intel')\n            if arch in ('i386', 'x86_64', 'intel', 'ppc', 'ppc64'):\n                matches.append('universal')\n            while minor >= 0:\n                for match in matches:\n                    s = '%s_%s_%s_%s' % (name, major, minor, match)\n                    if s != ARCH:   # already there\n                        arches.append(s)\n                minor -= 1\n\n    # Most specific - our Python version, ABI and arch\n    for abi in abis:\n        for arch in arches:\n            result.append((''.join((IMP_PREFIX, versions[0])), abi, arch))\n            # manylinux\n            if abi != 'none' and sys.platform.startswith('linux'):\n                arch = arch.replace('linux_', '')\n                parts = _get_glibc_version()\n                if len(parts) == 2:\n                    if parts >= (2, 5):\n                        result.append((''.join((IMP_PREFIX, versions[0])), abi,\n                                       'manylinux1_%s' % arch))\n                    if parts >= (2, 12):\n                        result.append((''.join((IMP_PREFIX, versions[0])), abi,\n                                       'manylinux2010_%s' % arch))\n                    if parts >= (2, 17):\n                        result.append((''.join((IMP_PREFIX, versions[0])), abi,\n                                       'manylinux2014_%s' % arch))\n                    result.append((''.join((IMP_PREFIX, versions[0])), abi,\n                                   'manylinux_%s_%s_%s' % (parts[0], parts[1],\n                                                           arch)))\n\n    # where no ABI / arch dependency, but IMP_PREFIX dependency\n    for i, version in enumerate(versions):\n        result.append((''.join((IMP_PREFIX, version)), 'none', 'any'))\n        if i == 0:\n            result.append((''.join((IMP_PREFIX, version[0])), 'none', 'any'))\n\n    # no IMP_PREFIX, ABI or arch dependency\n    for i, version in enumerate(versions):\n        result.append((''.join(('py', version)), 'none', 'any'))\n        if i == 0:\n            result.append((''.join(('py', version[0])), 'none', 'any'))\n\n    return set(result)\n\n\nCOMPATIBLE_TAGS = compatible_tags()\n\ndel compatible_tags\n\n\ndef is_compatible(wheel, tags=None):\n    if not isinstance(wheel, Wheel):\n        wheel = Wheel(wheel)    # assume it's a filename\n    result = False\n    if tags is None:\n        tags = COMPATIBLE_TAGS\n    for ver, abi, arch in tags:\n        if ver in wheel.pyver and abi in wheel.abi and arch in wheel.arch:\n            result = True\n            break\n    return result\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distro/__init__.py",
    "content": "from .distro import (\n    NORMALIZED_DISTRO_ID,\n    NORMALIZED_LSB_ID,\n    NORMALIZED_OS_ID,\n    LinuxDistribution,\n    __version__,\n    build_number,\n    codename,\n    distro_release_attr,\n    distro_release_info,\n    id,\n    info,\n    like,\n    linux_distribution,\n    lsb_release_attr,\n    lsb_release_info,\n    major_version,\n    minor_version,\n    name,\n    os_release_attr,\n    os_release_info,\n    uname_attr,\n    uname_info,\n    version,\n    version_parts,\n)\n\n__all__ = [\n    \"NORMALIZED_DISTRO_ID\",\n    \"NORMALIZED_LSB_ID\",\n    \"NORMALIZED_OS_ID\",\n    \"LinuxDistribution\",\n    \"build_number\",\n    \"codename\",\n    \"distro_release_attr\",\n    \"distro_release_info\",\n    \"id\",\n    \"info\",\n    \"like\",\n    \"linux_distribution\",\n    \"lsb_release_attr\",\n    \"lsb_release_info\",\n    \"major_version\",\n    \"minor_version\",\n    \"name\",\n    \"os_release_attr\",\n    \"os_release_info\",\n    \"uname_attr\",\n    \"uname_info\",\n    \"version\",\n    \"version_parts\",\n]\n\n__version__ = __version__\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distro/__main__.py",
    "content": "from .distro import main\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/distro/distro.py",
    "content": "#!/usr/bin/env python\n# Copyright 2015,2016,2017 Nir Cohen\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nThe ``distro`` package (``distro`` stands for Linux Distribution) provides\ninformation about the Linux distribution it runs on, such as a reliable\nmachine-readable distro ID, or version information.\n\nIt is the recommended replacement for Python's original\n:py:func:`platform.linux_distribution` function, but it provides much more\nfunctionality. An alternative implementation became necessary because Python\n3.5 deprecated this function, and Python 3.8 removed it altogether. Its\npredecessor function :py:func:`platform.dist` was already deprecated since\nPython 2.6 and removed in Python 3.8. Still, there are many cases in which\naccess to OS distribution information is needed. See `Python issue 1322\n<https://bugs.python.org/issue1322>`_ for more information.\n\"\"\"\n\nimport argparse\nimport json\nimport logging\nimport os\nimport re\nimport shlex\nimport subprocess\nimport sys\nimport warnings\nfrom typing import (\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    Optional,\n    Sequence,\n    TextIO,\n    Tuple,\n    Type,\n)\n\ntry:\n    from typing import TypedDict\nexcept ImportError:\n    # Python 3.7\n    TypedDict = dict\n\n__version__ = \"1.7.0\"\n\n\nclass VersionDict(TypedDict):\n    major: str\n    minor: str\n    build_number: str\n\n\nclass InfoDict(TypedDict):\n    id: str\n    version: str\n    version_parts: VersionDict\n    like: str\n    codename: str\n\n\n_UNIXCONFDIR = os.environ.get(\"UNIXCONFDIR\", \"/etc\")\n_UNIXUSRLIBDIR = os.environ.get(\"UNIXUSRLIBDIR\", \"/usr/lib\")\n_OS_RELEASE_BASENAME = \"os-release\"\n\n#: Translation table for normalizing the \"ID\" attribute defined in os-release\n#: files, for use by the :func:`distro.id` method.\n#:\n#: * Key: Value as defined in the os-release file, translated to lower case,\n#:   with blanks translated to underscores.\n#:\n#: * Value: Normalized value.\nNORMALIZED_OS_ID = {\n    \"ol\": \"oracle\",  # Oracle Linux\n    \"opensuse-leap\": \"opensuse\",  # Newer versions of OpenSuSE report as opensuse-leap\n}\n\n#: Translation table for normalizing the \"Distributor ID\" attribute returned by\n#: the lsb_release command, for use by the :func:`distro.id` method.\n#:\n#: * Key: Value as returned by the lsb_release command, translated to lower\n#:   case, with blanks translated to underscores.\n#:\n#: * Value: Normalized value.\nNORMALIZED_LSB_ID = {\n    \"enterpriseenterpriseas\": \"oracle\",  # Oracle Enterprise Linux 4\n    \"enterpriseenterpriseserver\": \"oracle\",  # Oracle Linux 5\n    \"redhatenterpriseworkstation\": \"rhel\",  # RHEL 6, 7 Workstation\n    \"redhatenterpriseserver\": \"rhel\",  # RHEL 6, 7 Server\n    \"redhatenterprisecomputenode\": \"rhel\",  # RHEL 6 ComputeNode\n}\n\n#: Translation table for normalizing the distro ID derived from the file name\n#: of distro release files, for use by the :func:`distro.id` method.\n#:\n#: * Key: Value as derived from the file name of a distro release file,\n#:   translated to lower case, with blanks translated to underscores.\n#:\n#: * Value: Normalized value.\nNORMALIZED_DISTRO_ID = {\n    \"redhat\": \"rhel\",  # RHEL 6.x, 7.x\n}\n\n# Pattern for content of distro release file (reversed)\n_DISTRO_RELEASE_CONTENT_REVERSED_PATTERN = re.compile(\n    r\"(?:[^)]*\\)(.*)\\()? *(?:STL )?([\\d.+\\-a-z]*\\d) *(?:esaeler *)?(.+)\"\n)\n\n# Pattern for base file name of distro release file\n_DISTRO_RELEASE_BASENAME_PATTERN = re.compile(r\"(\\w+)[-_](release|version)$\")\n\n# Base file names to be ignored when searching for distro release file\n_DISTRO_RELEASE_IGNORE_BASENAMES = (\n    \"debian_version\",\n    \"lsb-release\",\n    \"oem-release\",\n    _OS_RELEASE_BASENAME,\n    \"system-release\",\n    \"plesk-release\",\n    \"iredmail-release\",\n)\n\n\ndef linux_distribution(full_distribution_name: bool = True) -> Tuple[str, str, str]:\n    \"\"\"\n    .. deprecated:: 1.6.0\n\n        :func:`distro.linux_distribution()` is deprecated. It should only be\n        used as a compatibility shim with Python's\n        :py:func:`platform.linux_distribution()`. Please use :func:`distro.id`,\n        :func:`distro.version` and :func:`distro.name` instead.\n\n    Return information about the current OS distribution as a tuple\n    ``(id_name, version, codename)`` with items as follows:\n\n    * ``id_name``:  If *full_distribution_name* is false, the result of\n      :func:`distro.id`. Otherwise, the result of :func:`distro.name`.\n\n    * ``version``:  The result of :func:`distro.version`.\n\n    * ``codename``:  The extra item (usually in parentheses) after the\n      os-release version number, or the result of :func:`distro.codename`.\n\n    The interface of this function is compatible with the original\n    :py:func:`platform.linux_distribution` function, supporting a subset of\n    its parameters.\n\n    The data it returns may not exactly be the same, because it uses more data\n    sources than the original function, and that may lead to different data if\n    the OS distribution is not consistent across multiple data sources it\n    provides (there are indeed such distributions ...).\n\n    Another reason for differences is the fact that the :func:`distro.id`\n    method normalizes the distro ID string to a reliable machine-readable value\n    for a number of popular OS distributions.\n    \"\"\"\n    warnings.warn(\n        \"distro.linux_distribution() is deprecated. It should only be used as a \"\n        \"compatibility shim with Python's platform.linux_distribution(). Please use \"\n        \"distro.id(), distro.version() and distro.name() instead.\",\n        DeprecationWarning,\n        stacklevel=2,\n    )\n    return _distro.linux_distribution(full_distribution_name)\n\n\ndef id() -> str:\n    \"\"\"\n    Return the distro ID of the current distribution, as a\n    machine-readable string.\n\n    For a number of OS distributions, the returned distro ID value is\n    *reliable*, in the sense that it is documented and that it does not change\n    across releases of the distribution.\n\n    This package maintains the following reliable distro ID values:\n\n    ==============  =========================================\n    Distro ID       Distribution\n    ==============  =========================================\n    \"ubuntu\"        Ubuntu\n    \"debian\"        Debian\n    \"rhel\"          RedHat Enterprise Linux\n    \"centos\"        CentOS\n    \"fedora\"        Fedora\n    \"sles\"          SUSE Linux Enterprise Server\n    \"opensuse\"      openSUSE\n    \"amzn\"          Amazon Linux\n    \"arch\"          Arch Linux\n    \"cloudlinux\"    CloudLinux OS\n    \"exherbo\"       Exherbo Linux\n    \"gentoo\"        GenToo Linux\n    \"ibm_powerkvm\"  IBM PowerKVM\n    \"kvmibm\"        KVM for IBM z Systems\n    \"linuxmint\"     Linux Mint\n    \"mageia\"        Mageia\n    \"mandriva\"      Mandriva Linux\n    \"parallels\"     Parallels\n    \"pidora\"        Pidora\n    \"raspbian\"      Raspbian\n    \"oracle\"        Oracle Linux (and Oracle Enterprise Linux)\n    \"scientific\"    Scientific Linux\n    \"slackware\"     Slackware\n    \"xenserver\"     XenServer\n    \"openbsd\"       OpenBSD\n    \"netbsd\"        NetBSD\n    \"freebsd\"       FreeBSD\n    \"midnightbsd\"   MidnightBSD\n    \"rocky\"         Rocky Linux\n    \"aix\"           AIX\n    ==============  =========================================\n\n    If you have a need to get distros for reliable IDs added into this set,\n    or if you find that the :func:`distro.id` function returns a different\n    distro ID for one of the listed distros, please create an issue in the\n    `distro issue tracker`_.\n\n    **Lookup hierarchy and transformations:**\n\n    First, the ID is obtained from the following sources, in the specified\n    order. The first available and non-empty value is used:\n\n    * the value of the \"ID\" attribute of the os-release file,\n\n    * the value of the \"Distributor ID\" attribute returned by the lsb_release\n      command,\n\n    * the first part of the file name of the distro release file,\n\n    The so determined ID value then passes the following transformations,\n    before it is returned by this method:\n\n    * it is translated to lower case,\n\n    * blanks (which should not be there anyway) are translated to underscores,\n\n    * a normalization of the ID is performed, based upon\n      `normalization tables`_. The purpose of this normalization is to ensure\n      that the ID is as reliable as possible, even across incompatible changes\n      in the OS distributions. A common reason for an incompatible change is\n      the addition of an os-release file, or the addition of the lsb_release\n      command, with ID values that differ from what was previously determined\n      from the distro release file name.\n    \"\"\"\n    return _distro.id()\n\n\ndef name(pretty: bool = False) -> str:\n    \"\"\"\n    Return the name of the current OS distribution, as a human-readable\n    string.\n\n    If *pretty* is false, the name is returned without version or codename.\n    (e.g. \"CentOS Linux\")\n\n    If *pretty* is true, the version and codename are appended.\n    (e.g. \"CentOS Linux 7.1.1503 (Core)\")\n\n    **Lookup hierarchy:**\n\n    The name is obtained from the following sources, in the specified order.\n    The first available and non-empty value is used:\n\n    * If *pretty* is false:\n\n      - the value of the \"NAME\" attribute of the os-release file,\n\n      - the value of the \"Distributor ID\" attribute returned by the lsb_release\n        command,\n\n      - the value of the \"<name>\" field of the distro release file.\n\n    * If *pretty* is true:\n\n      - the value of the \"PRETTY_NAME\" attribute of the os-release file,\n\n      - the value of the \"Description\" attribute returned by the lsb_release\n        command,\n\n      - the value of the \"<name>\" field of the distro release file, appended\n        with the value of the pretty version (\"<version_id>\" and \"<codename>\"\n        fields) of the distro release file, if available.\n    \"\"\"\n    return _distro.name(pretty)\n\n\ndef version(pretty: bool = False, best: bool = False) -> str:\n    \"\"\"\n    Return the version of the current OS distribution, as a human-readable\n    string.\n\n    If *pretty* is false, the version is returned without codename (e.g.\n    \"7.0\").\n\n    If *pretty* is true, the codename in parenthesis is appended, if the\n    codename is non-empty (e.g. \"7.0 (Maipo)\").\n\n    Some distributions provide version numbers with different precisions in\n    the different sources of distribution information. Examining the different\n    sources in a fixed priority order does not always yield the most precise\n    version (e.g. for Debian 8.2, or CentOS 7.1).\n\n    Some other distributions may not provide this kind of information. In these\n    cases, an empty string would be returned. This behavior can be observed\n    with rolling releases distributions (e.g. Arch Linux).\n\n    The *best* parameter can be used to control the approach for the returned\n    version:\n\n    If *best* is false, the first non-empty version number in priority order of\n    the examined sources is returned.\n\n    If *best* is true, the most precise version number out of all examined\n    sources is returned.\n\n    **Lookup hierarchy:**\n\n    In all cases, the version number is obtained from the following sources.\n    If *best* is false, this order represents the priority order:\n\n    * the value of the \"VERSION_ID\" attribute of the os-release file,\n    * the value of the \"Release\" attribute returned by the lsb_release\n      command,\n    * the version number parsed from the \"<version_id>\" field of the first line\n      of the distro release file,\n    * the version number parsed from the \"PRETTY_NAME\" attribute of the\n      os-release file, if it follows the format of the distro release files.\n    * the version number parsed from the \"Description\" attribute returned by\n      the lsb_release command, if it follows the format of the distro release\n      files.\n    \"\"\"\n    return _distro.version(pretty, best)\n\n\ndef version_parts(best: bool = False) -> Tuple[str, str, str]:\n    \"\"\"\n    Return the version of the current OS distribution as a tuple\n    ``(major, minor, build_number)`` with items as follows:\n\n    * ``major``:  The result of :func:`distro.major_version`.\n\n    * ``minor``:  The result of :func:`distro.minor_version`.\n\n    * ``build_number``:  The result of :func:`distro.build_number`.\n\n    For a description of the *best* parameter, see the :func:`distro.version`\n    method.\n    \"\"\"\n    return _distro.version_parts(best)\n\n\ndef major_version(best: bool = False) -> str:\n    \"\"\"\n    Return the major version of the current OS distribution, as a string,\n    if provided.\n    Otherwise, the empty string is returned. The major version is the first\n    part of the dot-separated version string.\n\n    For a description of the *best* parameter, see the :func:`distro.version`\n    method.\n    \"\"\"\n    return _distro.major_version(best)\n\n\ndef minor_version(best: bool = False) -> str:\n    \"\"\"\n    Return the minor version of the current OS distribution, as a string,\n    if provided.\n    Otherwise, the empty string is returned. The minor version is the second\n    part of the dot-separated version string.\n\n    For a description of the *best* parameter, see the :func:`distro.version`\n    method.\n    \"\"\"\n    return _distro.minor_version(best)\n\n\ndef build_number(best: bool = False) -> str:\n    \"\"\"\n    Return the build number of the current OS distribution, as a string,\n    if provided.\n    Otherwise, the empty string is returned. The build number is the third part\n    of the dot-separated version string.\n\n    For a description of the *best* parameter, see the :func:`distro.version`\n    method.\n    \"\"\"\n    return _distro.build_number(best)\n\n\ndef like() -> str:\n    \"\"\"\n    Return a space-separated list of distro IDs of distributions that are\n    closely related to the current OS distribution in regards to packaging\n    and programming interfaces, for example distributions the current\n    distribution is a derivative from.\n\n    **Lookup hierarchy:**\n\n    This information item is only provided by the os-release file.\n    For details, see the description of the \"ID_LIKE\" attribute in the\n    `os-release man page\n    <http://www.freedesktop.org/software/systemd/man/os-release.html>`_.\n    \"\"\"\n    return _distro.like()\n\n\ndef codename() -> str:\n    \"\"\"\n    Return the codename for the release of the current OS distribution,\n    as a string.\n\n    If the distribution does not have a codename, an empty string is returned.\n\n    Note that the returned codename is not always really a codename. For\n    example, openSUSE returns \"x86_64\". This function does not handle such\n    cases in any special way and just returns the string it finds, if any.\n\n    **Lookup hierarchy:**\n\n    * the codename within the \"VERSION\" attribute of the os-release file, if\n      provided,\n\n    * the value of the \"Codename\" attribute returned by the lsb_release\n      command,\n\n    * the value of the \"<codename>\" field of the distro release file.\n    \"\"\"\n    return _distro.codename()\n\n\ndef info(pretty: bool = False, best: bool = False) -> InfoDict:\n    \"\"\"\n    Return certain machine-readable information items about the current OS\n    distribution in a dictionary, as shown in the following example:\n\n    .. sourcecode:: python\n\n        {\n            'id': 'rhel',\n            'version': '7.0',\n            'version_parts': {\n                'major': '7',\n                'minor': '0',\n                'build_number': ''\n            },\n            'like': 'fedora',\n            'codename': 'Maipo'\n        }\n\n    The dictionary structure and keys are always the same, regardless of which\n    information items are available in the underlying data sources. The values\n    for the various keys are as follows:\n\n    * ``id``:  The result of :func:`distro.id`.\n\n    * ``version``:  The result of :func:`distro.version`.\n\n    * ``version_parts -> major``:  The result of :func:`distro.major_version`.\n\n    * ``version_parts -> minor``:  The result of :func:`distro.minor_version`.\n\n    * ``version_parts -> build_number``:  The result of\n      :func:`distro.build_number`.\n\n    * ``like``:  The result of :func:`distro.like`.\n\n    * ``codename``:  The result of :func:`distro.codename`.\n\n    For a description of the *pretty* and *best* parameters, see the\n    :func:`distro.version` method.\n    \"\"\"\n    return _distro.info(pretty, best)\n\n\ndef os_release_info() -> Dict[str, str]:\n    \"\"\"\n    Return a dictionary containing key-value pairs for the information items\n    from the os-release file data source of the current OS distribution.\n\n    See `os-release file`_ for details about these information items.\n    \"\"\"\n    return _distro.os_release_info()\n\n\ndef lsb_release_info() -> Dict[str, str]:\n    \"\"\"\n    Return a dictionary containing key-value pairs for the information items\n    from the lsb_release command data source of the current OS distribution.\n\n    See `lsb_release command output`_ for details about these information\n    items.\n    \"\"\"\n    return _distro.lsb_release_info()\n\n\ndef distro_release_info() -> Dict[str, str]:\n    \"\"\"\n    Return a dictionary containing key-value pairs for the information items\n    from the distro release file data source of the current OS distribution.\n\n    See `distro release file`_ for details about these information items.\n    \"\"\"\n    return _distro.distro_release_info()\n\n\ndef uname_info() -> Dict[str, str]:\n    \"\"\"\n    Return a dictionary containing key-value pairs for the information items\n    from the distro release file data source of the current OS distribution.\n    \"\"\"\n    return _distro.uname_info()\n\n\ndef os_release_attr(attribute: str) -> str:\n    \"\"\"\n    Return a single named information item from the os-release file data source\n    of the current OS distribution.\n\n    Parameters:\n\n    * ``attribute`` (string): Key of the information item.\n\n    Returns:\n\n    * (string): Value of the information item, if the item exists.\n      The empty string, if the item does not exist.\n\n    See `os-release file`_ for details about these information items.\n    \"\"\"\n    return _distro.os_release_attr(attribute)\n\n\ndef lsb_release_attr(attribute: str) -> str:\n    \"\"\"\n    Return a single named information item from the lsb_release command output\n    data source of the current OS distribution.\n\n    Parameters:\n\n    * ``attribute`` (string): Key of the information item.\n\n    Returns:\n\n    * (string): Value of the information item, if the item exists.\n      The empty string, if the item does not exist.\n\n    See `lsb_release command output`_ for details about these information\n    items.\n    \"\"\"\n    return _distro.lsb_release_attr(attribute)\n\n\ndef distro_release_attr(attribute: str) -> str:\n    \"\"\"\n    Return a single named information item from the distro release file\n    data source of the current OS distribution.\n\n    Parameters:\n\n    * ``attribute`` (string): Key of the information item.\n\n    Returns:\n\n    * (string): Value of the information item, if the item exists.\n      The empty string, if the item does not exist.\n\n    See `distro release file`_ for details about these information items.\n    \"\"\"\n    return _distro.distro_release_attr(attribute)\n\n\ndef uname_attr(attribute: str) -> str:\n    \"\"\"\n    Return a single named information item from the distro release file\n    data source of the current OS distribution.\n\n    Parameters:\n\n    * ``attribute`` (string): Key of the information item.\n\n    Returns:\n\n    * (string): Value of the information item, if the item exists.\n                The empty string, if the item does not exist.\n    \"\"\"\n    return _distro.uname_attr(attribute)\n\n\ntry:\n    from functools import cached_property\nexcept ImportError:\n    # Python < 3.8\n    class cached_property:  # type: ignore\n        \"\"\"A version of @property which caches the value.  On access, it calls the\n        underlying function and sets the value in `__dict__` so future accesses\n        will not re-call the property.\n        \"\"\"\n\n        def __init__(self, f: Callable[[Any], Any]) -> None:\n            self._fname = f.__name__\n            self._f = f\n\n        def __get__(self, obj: Any, owner: Type[Any]) -> Any:\n            assert obj is not None, f\"call {self._fname} on an instance\"\n            ret = obj.__dict__[self._fname] = self._f(obj)\n            return ret\n\n\nclass LinuxDistribution:\n    \"\"\"\n    Provides information about a OS distribution.\n\n    This package creates a private module-global instance of this class with\n    default initialization arguments, that is used by the\n    `consolidated accessor functions`_ and `single source accessor functions`_.\n    By using default initialization arguments, that module-global instance\n    returns data about the current OS distribution (i.e. the distro this\n    package runs on).\n\n    Normally, it is not necessary to create additional instances of this class.\n    However, in situations where control is needed over the exact data sources\n    that are used, instances of this class can be created with a specific\n    distro release file, or a specific os-release file, or without invoking the\n    lsb_release command.\n    \"\"\"\n\n    def __init__(\n        self,\n        include_lsb: Optional[bool] = None,\n        os_release_file: str = \"\",\n        distro_release_file: str = \"\",\n        include_uname: Optional[bool] = None,\n        root_dir: Optional[str] = None,\n        include_oslevel: Optional[bool] = None,\n    ) -> None:\n        \"\"\"\n        The initialization method of this class gathers information from the\n        available data sources, and stores that in private instance attributes.\n        Subsequent access to the information items uses these private instance\n        attributes, so that the data sources are read only once.\n\n        Parameters:\n\n        * ``include_lsb`` (bool): Controls whether the\n          `lsb_release command output`_ is included as a data source.\n\n          If the lsb_release command is not available in the program execution\n          path, the data source for the lsb_release command will be empty.\n\n        * ``os_release_file`` (string): The path name of the\n          `os-release file`_ that is to be used as a data source.\n\n          An empty string (the default) will cause the default path name to\n          be used (see `os-release file`_ for details).\n\n          If the specified or defaulted os-release file does not exist, the\n          data source for the os-release file will be empty.\n\n        * ``distro_release_file`` (string): The path name of the\n          `distro release file`_ that is to be used as a data source.\n\n          An empty string (the default) will cause a default search algorithm\n          to be used (see `distro release file`_ for details).\n\n          If the specified distro release file does not exist, or if no default\n          distro release file can be found, the data source for the distro\n          release file will be empty.\n\n        * ``include_uname`` (bool): Controls whether uname command output is\n          included as a data source. If the uname command is not available in\n          the program execution path the data source for the uname command will\n          be empty.\n\n        * ``root_dir`` (string): The absolute path to the root directory to use\n          to find distro-related information files. Note that ``include_*``\n          parameters must not be enabled in combination with ``root_dir``.\n\n        * ``include_oslevel`` (bool): Controls whether (AIX) oslevel command\n          output is included as a data source. If the oslevel command is not\n          available in the program execution path the data source will be\n          empty.\n\n        Public instance attributes:\n\n        * ``os_release_file`` (string): The path name of the\n          `os-release file`_ that is actually used as a data source. The\n          empty string if no distro release file is used as a data source.\n\n        * ``distro_release_file`` (string): The path name of the\n          `distro release file`_ that is actually used as a data source. The\n          empty string if no distro release file is used as a data source.\n\n        * ``include_lsb`` (bool): The result of the ``include_lsb`` parameter.\n          This controls whether the lsb information will be loaded.\n\n        * ``include_uname`` (bool): The result of the ``include_uname``\n          parameter. This controls whether the uname information will\n          be loaded.\n\n        * ``include_oslevel`` (bool): The result of the ``include_oslevel``\n          parameter. This controls whether (AIX) oslevel information will be\n          loaded.\n\n        * ``root_dir`` (string): The result of the ``root_dir`` parameter.\n          The absolute path to the root directory to use to find distro-related\n          information files.\n\n        Raises:\n\n        * :py:exc:`ValueError`: Initialization parameters combination is not\n           supported.\n\n        * :py:exc:`OSError`: Some I/O issue with an os-release file or distro\n          release file.\n\n        * :py:exc:`UnicodeError`: A data source has unexpected characters or\n          uses an unexpected encoding.\n        \"\"\"\n        self.root_dir = root_dir\n        self.etc_dir = os.path.join(root_dir, \"etc\") if root_dir else _UNIXCONFDIR\n        self.usr_lib_dir = (\n            os.path.join(root_dir, \"usr/lib\") if root_dir else _UNIXUSRLIBDIR\n        )\n\n        if os_release_file:\n            self.os_release_file = os_release_file\n        else:\n            etc_dir_os_release_file = os.path.join(self.etc_dir, _OS_RELEASE_BASENAME)\n            usr_lib_os_release_file = os.path.join(\n                self.usr_lib_dir, _OS_RELEASE_BASENAME\n            )\n\n            # NOTE: The idea is to respect order **and** have it set\n            #       at all times for API backwards compatibility.\n            if os.path.isfile(etc_dir_os_release_file) or not os.path.isfile(\n                usr_lib_os_release_file\n            ):\n                self.os_release_file = etc_dir_os_release_file\n            else:\n                self.os_release_file = usr_lib_os_release_file\n\n        self.distro_release_file = distro_release_file or \"\"  # updated later\n\n        is_root_dir_defined = root_dir is not None\n        if is_root_dir_defined and (include_lsb or include_uname or include_oslevel):\n            raise ValueError(\n                \"Including subprocess data sources from specific root_dir is disallowed\"\n                \" to prevent false information\"\n            )\n        self.include_lsb = (\n            include_lsb if include_lsb is not None else not is_root_dir_defined\n        )\n        self.include_uname = (\n            include_uname if include_uname is not None else not is_root_dir_defined\n        )\n        self.include_oslevel = (\n            include_oslevel if include_oslevel is not None else not is_root_dir_defined\n        )\n\n    def __repr__(self) -> str:\n        \"\"\"Return repr of all info\"\"\"\n        return (\n            \"LinuxDistribution(\"\n            \"os_release_file={self.os_release_file!r}, \"\n            \"distro_release_file={self.distro_release_file!r}, \"\n            \"include_lsb={self.include_lsb!r}, \"\n            \"include_uname={self.include_uname!r}, \"\n            \"include_oslevel={self.include_oslevel!r}, \"\n            \"root_dir={self.root_dir!r}, \"\n            \"_os_release_info={self._os_release_info!r}, \"\n            \"_lsb_release_info={self._lsb_release_info!r}, \"\n            \"_distro_release_info={self._distro_release_info!r}, \"\n            \"_uname_info={self._uname_info!r}, \"\n            \"_oslevel_info={self._oslevel_info!r})\".format(self=self)\n        )\n\n    def linux_distribution(\n        self, full_distribution_name: bool = True\n    ) -> Tuple[str, str, str]:\n        \"\"\"\n        Return information about the OS distribution that is compatible\n        with Python's :func:`platform.linux_distribution`, supporting a subset\n        of its parameters.\n\n        For details, see :func:`distro.linux_distribution`.\n        \"\"\"\n        return (\n            self.name() if full_distribution_name else self.id(),\n            self.version(),\n            self._os_release_info.get(\"release_codename\") or self.codename(),\n        )\n\n    def id(self) -> str:\n        \"\"\"Return the distro ID of the OS distribution, as a string.\n\n        For details, see :func:`distro.id`.\n        \"\"\"\n\n        def normalize(distro_id: str, table: Dict[str, str]) -> str:\n            distro_id = distro_id.lower().replace(\" \", \"_\")\n            return table.get(distro_id, distro_id)\n\n        distro_id = self.os_release_attr(\"id\")\n        if distro_id:\n            return normalize(distro_id, NORMALIZED_OS_ID)\n\n        distro_id = self.lsb_release_attr(\"distributor_id\")\n        if distro_id:\n            return normalize(distro_id, NORMALIZED_LSB_ID)\n\n        distro_id = self.distro_release_attr(\"id\")\n        if distro_id:\n            return normalize(distro_id, NORMALIZED_DISTRO_ID)\n\n        distro_id = self.uname_attr(\"id\")\n        if distro_id:\n            return normalize(distro_id, NORMALIZED_DISTRO_ID)\n\n        return \"\"\n\n    def name(self, pretty: bool = False) -> str:\n        \"\"\"\n        Return the name of the OS distribution, as a string.\n\n        For details, see :func:`distro.name`.\n        \"\"\"\n        name = (\n            self.os_release_attr(\"name\")\n            or self.lsb_release_attr(\"distributor_id\")\n            or self.distro_release_attr(\"name\")\n            or self.uname_attr(\"name\")\n        )\n        if pretty:\n            name = self.os_release_attr(\"pretty_name\") or self.lsb_release_attr(\n                \"description\"\n            )\n            if not name:\n                name = self.distro_release_attr(\"name\") or self.uname_attr(\"name\")\n                version = self.version(pretty=True)\n                if version:\n                    name = f\"{name} {version}\"\n        return name or \"\"\n\n    def version(self, pretty: bool = False, best: bool = False) -> str:\n        \"\"\"\n        Return the version of the OS distribution, as a string.\n\n        For details, see :func:`distro.version`.\n        \"\"\"\n        versions = [\n            self.os_release_attr(\"version_id\"),\n            self.lsb_release_attr(\"release\"),\n            self.distro_release_attr(\"version_id\"),\n            self._parse_distro_release_content(self.os_release_attr(\"pretty_name\")).get(\n                \"version_id\", \"\"\n            ),\n            self._parse_distro_release_content(\n                self.lsb_release_attr(\"description\")\n            ).get(\"version_id\", \"\"),\n            self.uname_attr(\"release\"),\n        ]\n        if self.uname_attr(\"id\").startswith(\"aix\"):\n            # On AIX platforms, prefer oslevel command output.\n            versions.insert(0, self.oslevel_info())\n        version = \"\"\n        if best:\n            # This algorithm uses the last version in priority order that has\n            # the best precision. If the versions are not in conflict, that\n            # does not matter; otherwise, using the last one instead of the\n            # first one might be considered a surprise.\n            for v in versions:\n                if v.count(\".\") > version.count(\".\") or version == \"\":\n                    version = v\n        else:\n            for v in versions:\n                if v != \"\":\n                    version = v\n                    break\n        if pretty and version and self.codename():\n            version = f\"{version} ({self.codename()})\"\n        return version\n\n    def version_parts(self, best: bool = False) -> Tuple[str, str, str]:\n        \"\"\"\n        Return the version of the OS distribution, as a tuple of version\n        numbers.\n\n        For details, see :func:`distro.version_parts`.\n        \"\"\"\n        version_str = self.version(best=best)\n        if version_str:\n            version_regex = re.compile(r\"(\\d+)\\.?(\\d+)?\\.?(\\d+)?\")\n            matches = version_regex.match(version_str)\n            if matches:\n                major, minor, build_number = matches.groups()\n                return major, minor or \"\", build_number or \"\"\n        return \"\", \"\", \"\"\n\n    def major_version(self, best: bool = False) -> str:\n        \"\"\"\n        Return the major version number of the current distribution.\n\n        For details, see :func:`distro.major_version`.\n        \"\"\"\n        return self.version_parts(best)[0]\n\n    def minor_version(self, best: bool = False) -> str:\n        \"\"\"\n        Return the minor version number of the current distribution.\n\n        For details, see :func:`distro.minor_version`.\n        \"\"\"\n        return self.version_parts(best)[1]\n\n    def build_number(self, best: bool = False) -> str:\n        \"\"\"\n        Return the build number of the current distribution.\n\n        For details, see :func:`distro.build_number`.\n        \"\"\"\n        return self.version_parts(best)[2]\n\n    def like(self) -> str:\n        \"\"\"\n        Return the IDs of distributions that are like the OS distribution.\n\n        For details, see :func:`distro.like`.\n        \"\"\"\n        return self.os_release_attr(\"id_like\") or \"\"\n\n    def codename(self) -> str:\n        \"\"\"\n        Return the codename of the OS distribution.\n\n        For details, see :func:`distro.codename`.\n        \"\"\"\n        try:\n            # Handle os_release specially since distros might purposefully set\n            # this to empty string to have no codename\n            return self._os_release_info[\"codename\"]\n        except KeyError:\n            return (\n                self.lsb_release_attr(\"codename\")\n                or self.distro_release_attr(\"codename\")\n                or \"\"\n            )\n\n    def info(self, pretty: bool = False, best: bool = False) -> InfoDict:\n        \"\"\"\n        Return certain machine-readable information about the OS\n        distribution.\n\n        For details, see :func:`distro.info`.\n        \"\"\"\n        return dict(\n            id=self.id(),\n            version=self.version(pretty, best),\n            version_parts=dict(\n                major=self.major_version(best),\n                minor=self.minor_version(best),\n                build_number=self.build_number(best),\n            ),\n            like=self.like(),\n            codename=self.codename(),\n        )\n\n    def os_release_info(self) -> Dict[str, str]:\n        \"\"\"\n        Return a dictionary containing key-value pairs for the information\n        items from the os-release file data source of the OS distribution.\n\n        For details, see :func:`distro.os_release_info`.\n        \"\"\"\n        return self._os_release_info\n\n    def lsb_release_info(self) -> Dict[str, str]:\n        \"\"\"\n        Return a dictionary containing key-value pairs for the information\n        items from the lsb_release command data source of the OS\n        distribution.\n\n        For details, see :func:`distro.lsb_release_info`.\n        \"\"\"\n        return self._lsb_release_info\n\n    def distro_release_info(self) -> Dict[str, str]:\n        \"\"\"\n        Return a dictionary containing key-value pairs for the information\n        items from the distro release file data source of the OS\n        distribution.\n\n        For details, see :func:`distro.distro_release_info`.\n        \"\"\"\n        return self._distro_release_info\n\n    def uname_info(self) -> Dict[str, str]:\n        \"\"\"\n        Return a dictionary containing key-value pairs for the information\n        items from the uname command data source of the OS distribution.\n\n        For details, see :func:`distro.uname_info`.\n        \"\"\"\n        return self._uname_info\n\n    def oslevel_info(self) -> str:\n        \"\"\"\n        Return AIX' oslevel command output.\n        \"\"\"\n        return self._oslevel_info\n\n    def os_release_attr(self, attribute: str) -> str:\n        \"\"\"\n        Return a single named information item from the os-release file data\n        source of the OS distribution.\n\n        For details, see :func:`distro.os_release_attr`.\n        \"\"\"\n        return self._os_release_info.get(attribute, \"\")\n\n    def lsb_release_attr(self, attribute: str) -> str:\n        \"\"\"\n        Return a single named information item from the lsb_release command\n        output data source of the OS distribution.\n\n        For details, see :func:`distro.lsb_release_attr`.\n        \"\"\"\n        return self._lsb_release_info.get(attribute, \"\")\n\n    def distro_release_attr(self, attribute: str) -> str:\n        \"\"\"\n        Return a single named information item from the distro release file\n        data source of the OS distribution.\n\n        For details, see :func:`distro.distro_release_attr`.\n        \"\"\"\n        return self._distro_release_info.get(attribute, \"\")\n\n    def uname_attr(self, attribute: str) -> str:\n        \"\"\"\n        Return a single named information item from the uname command\n        output data source of the OS distribution.\n\n        For details, see :func:`distro.uname_attr`.\n        \"\"\"\n        return self._uname_info.get(attribute, \"\")\n\n    @cached_property\n    def _os_release_info(self) -> Dict[str, str]:\n        \"\"\"\n        Get the information items from the specified os-release file.\n\n        Returns:\n            A dictionary containing all information items.\n        \"\"\"\n        if os.path.isfile(self.os_release_file):\n            with open(self.os_release_file, encoding=\"utf-8\") as release_file:\n                return self._parse_os_release_content(release_file)\n        return {}\n\n    @staticmethod\n    def _parse_os_release_content(lines: TextIO) -> Dict[str, str]:\n        \"\"\"\n        Parse the lines of an os-release file.\n\n        Parameters:\n\n        * lines: Iterable through the lines in the os-release file.\n                 Each line must be a unicode string or a UTF-8 encoded byte\n                 string.\n\n        Returns:\n            A dictionary containing all information items.\n        \"\"\"\n        props = {}\n        lexer = shlex.shlex(lines, posix=True)\n        lexer.whitespace_split = True\n\n        tokens = list(lexer)\n        for token in tokens:\n            # At this point, all shell-like parsing has been done (i.e.\n            # comments processed, quotes and backslash escape sequences\n            # processed, multi-line values assembled, trailing newlines\n            # stripped, etc.), so the tokens are now either:\n            # * variable assignments: var=value\n            # * commands or their arguments (not allowed in os-release)\n            # Ignore any tokens that are not variable assignments\n            if \"=\" in token:\n                k, v = token.split(\"=\", 1)\n                props[k.lower()] = v\n\n        if \"version\" in props:\n            # extract release codename (if any) from version attribute\n            match = re.search(r\"\\((\\D+)\\)|,\\s*(\\D+)\", props[\"version\"])\n            if match:\n                release_codename = match.group(1) or match.group(2)\n                props[\"codename\"] = props[\"release_codename\"] = release_codename\n\n        if \"version_codename\" in props:\n            # os-release added a version_codename field.  Use that in\n            # preference to anything else Note that some distros purposefully\n            # do not have code names.  They should be setting\n            # version_codename=\"\"\n            props[\"codename\"] = props[\"version_codename\"]\n        elif \"ubuntu_codename\" in props:\n            # Same as above but a non-standard field name used on older Ubuntus\n            props[\"codename\"] = props[\"ubuntu_codename\"]\n\n        return props\n\n    @cached_property\n    def _lsb_release_info(self) -> Dict[str, str]:\n        \"\"\"\n        Get the information items from the lsb_release command output.\n\n        Returns:\n            A dictionary containing all information items.\n        \"\"\"\n        if not self.include_lsb:\n            return {}\n        try:\n            cmd = (\"lsb_release\", \"-a\")\n            stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)\n        # Command not found or lsb_release returned error\n        except (OSError, subprocess.CalledProcessError):\n            return {}\n        content = self._to_str(stdout).splitlines()\n        return self._parse_lsb_release_content(content)\n\n    @staticmethod\n    def _parse_lsb_release_content(lines: Iterable[str]) -> Dict[str, str]:\n        \"\"\"\n        Parse the output of the lsb_release command.\n\n        Parameters:\n\n        * lines: Iterable through the lines of the lsb_release output.\n                 Each line must be a unicode string or a UTF-8 encoded byte\n                 string.\n\n        Returns:\n            A dictionary containing all information items.\n        \"\"\"\n        props = {}\n        for line in lines:\n            kv = line.strip(\"\\n\").split(\":\", 1)\n            if len(kv) != 2:\n                # Ignore lines without colon.\n                continue\n            k, v = kv\n            props.update({k.replace(\" \", \"_\").lower(): v.strip()})\n        return props\n\n    @cached_property\n    def _uname_info(self) -> Dict[str, str]:\n        if not self.include_uname:\n            return {}\n        try:\n            cmd = (\"uname\", \"-rs\")\n            stdout = subprocess.check_output(cmd, stderr=subprocess.DEVNULL)\n        except OSError:\n            return {}\n        content = self._to_str(stdout).splitlines()\n        return self._parse_uname_content(content)\n\n    @cached_property\n    def _oslevel_info(self) -> str:\n        if not self.include_oslevel:\n            return \"\"\n        try:\n            stdout = subprocess.check_output(\"oslevel\", stderr=subprocess.DEVNULL)\n        except (OSError, subprocess.CalledProcessError):\n            return \"\"\n        return self._to_str(stdout).strip()\n\n    @staticmethod\n    def _parse_uname_content(lines: Sequence[str]) -> Dict[str, str]:\n        if not lines:\n            return {}\n        props = {}\n        match = re.search(r\"^([^\\s]+)\\s+([\\d\\.]+)\", lines[0].strip())\n        if match:\n            name, version = match.groups()\n\n            # This is to prevent the Linux kernel version from\n            # appearing as the 'best' version on otherwise\n            # identifiable distributions.\n            if name == \"Linux\":\n                return {}\n            props[\"id\"] = name.lower()\n            props[\"name\"] = name\n            props[\"release\"] = version\n        return props\n\n    @staticmethod\n    def _to_str(bytestring: bytes) -> str:\n        encoding = sys.getfilesystemencoding()\n        return bytestring.decode(encoding)\n\n    @cached_property\n    def _distro_release_info(self) -> Dict[str, str]:\n        \"\"\"\n        Get the information items from the specified distro release file.\n\n        Returns:\n            A dictionary containing all information items.\n        \"\"\"\n        if self.distro_release_file:\n            # If it was specified, we use it and parse what we can, even if\n            # its file name or content does not match the expected pattern.\n            distro_info = self._parse_distro_release_file(self.distro_release_file)\n            basename = os.path.basename(self.distro_release_file)\n            # The file name pattern for user-specified distro release files\n            # is somewhat more tolerant (compared to when searching for the\n            # file), because we want to use what was specified as best as\n            # possible.\n            match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)\n            if \"name\" in distro_info and \"cloudlinux\" in distro_info[\"name\"].lower():\n                distro_info[\"id\"] = \"cloudlinux\"\n            elif match:\n                distro_info[\"id\"] = match.group(1)\n            return distro_info\n        else:\n            try:\n                basenames = os.listdir(self.etc_dir)\n                # We sort for repeatability in cases where there are multiple\n                # distro specific files; e.g. CentOS, Oracle, Enterprise all\n                # containing `redhat-release` on top of their own.\n                basenames.sort()\n            except OSError:\n                # This may occur when /etc is not readable but we can't be\n                # sure about the *-release files. Check common entries of\n                # /etc for information. If they turn out to not be there the\n                # error is handled in `_parse_distro_release_file()`.\n                basenames = [\n                    \"SuSE-release\",\n                    \"arch-release\",\n                    \"base-release\",\n                    \"centos-release\",\n                    \"fedora-release\",\n                    \"gentoo-release\",\n                    \"mageia-release\",\n                    \"mandrake-release\",\n                    \"mandriva-release\",\n                    \"mandrivalinux-release\",\n                    \"manjaro-release\",\n                    \"oracle-release\",\n                    \"redhat-release\",\n                    \"rocky-release\",\n                    \"sl-release\",\n                    \"slackware-version\",\n                ]\n            for basename in basenames:\n                if basename in _DISTRO_RELEASE_IGNORE_BASENAMES:\n                    continue\n                match = _DISTRO_RELEASE_BASENAME_PATTERN.match(basename)\n                if match:\n                    filepath = os.path.join(self.etc_dir, basename)\n                    distro_info = self._parse_distro_release_file(filepath)\n                    if \"name\" in distro_info:\n                        # The name is always present if the pattern matches\n                        self.distro_release_file = filepath\n                        distro_info[\"id\"] = match.group(1)\n                        if \"cloudlinux\" in distro_info[\"name\"].lower():\n                            distro_info[\"id\"] = \"cloudlinux\"\n                        return distro_info\n            return {}\n\n    def _parse_distro_release_file(self, filepath: str) -> Dict[str, str]:\n        \"\"\"\n        Parse a distro release file.\n\n        Parameters:\n\n        * filepath: Path name of the distro release file.\n\n        Returns:\n            A dictionary containing all information items.\n        \"\"\"\n        try:\n            with open(filepath, encoding=\"utf-8\") as fp:\n                # Only parse the first line. For instance, on SLES there\n                # are multiple lines. We don't want them...\n                return self._parse_distro_release_content(fp.readline())\n        except OSError:\n            # Ignore not being able to read a specific, seemingly version\n            # related file.\n            # See https://github.com/python-distro/distro/issues/162\n            return {}\n\n    @staticmethod\n    def _parse_distro_release_content(line: str) -> Dict[str, str]:\n        \"\"\"\n        Parse a line from a distro release file.\n\n        Parameters:\n        * line: Line from the distro release file. Must be a unicode string\n                or a UTF-8 encoded byte string.\n\n        Returns:\n            A dictionary containing all information items.\n        \"\"\"\n        matches = _DISTRO_RELEASE_CONTENT_REVERSED_PATTERN.match(line.strip()[::-1])\n        distro_info = {}\n        if matches:\n            # regexp ensures non-None\n            distro_info[\"name\"] = matches.group(3)[::-1]\n            if matches.group(2):\n                distro_info[\"version_id\"] = matches.group(2)[::-1]\n            if matches.group(1):\n                distro_info[\"codename\"] = matches.group(1)[::-1]\n        elif line:\n            distro_info[\"name\"] = line.strip()\n        return distro_info\n\n\n_distro = LinuxDistribution()\n\n\ndef main() -> None:\n    logger = logging.getLogger(__name__)\n    logger.setLevel(logging.DEBUG)\n    logger.addHandler(logging.StreamHandler(sys.stdout))\n\n    parser = argparse.ArgumentParser(description=\"OS distro info tool\")\n    parser.add_argument(\n        \"--json\", \"-j\", help=\"Output in machine readable format\", action=\"store_true\"\n    )\n\n    parser.add_argument(\n        \"--root-dir\",\n        \"-r\",\n        type=str,\n        dest=\"root_dir\",\n        help=\"Path to the root filesystem directory (defaults to /)\",\n    )\n\n    args = parser.parse_args()\n\n    if args.root_dir:\n        dist = LinuxDistribution(\n            include_lsb=False,\n            include_uname=False,\n            include_oslevel=False,\n            root_dir=args.root_dir,\n        )\n    else:\n        dist = _distro\n\n    if args.json:\n        logger.info(json.dumps(dist.info(), indent=4, sort_keys=True))\n    else:\n        logger.info(\"Name: %s\", dist.name(pretty=True))\n        distribution_version = dist.version(pretty=True)\n        logger.info(\"Version: %s\", distribution_version)\n        distribution_codename = dist.codename()\n        logger.info(\"Codename: %s\", distribution_codename)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/idna/__init__.py",
    "content": "from .package_data import __version__\nfrom .core import (\n    IDNABidiError,\n    IDNAError,\n    InvalidCodepoint,\n    InvalidCodepointContext,\n    alabel,\n    check_bidi,\n    check_hyphen_ok,\n    check_initial_combiner,\n    check_label,\n    check_nfc,\n    decode,\n    encode,\n    ulabel,\n    uts46_remap,\n    valid_contextj,\n    valid_contexto,\n    valid_label_length,\n    valid_string_length,\n)\nfrom .intranges import intranges_contain\n\n__all__ = [\n    \"IDNABidiError\",\n    \"IDNAError\",\n    \"InvalidCodepoint\",\n    \"InvalidCodepointContext\",\n    \"alabel\",\n    \"check_bidi\",\n    \"check_hyphen_ok\",\n    \"check_initial_combiner\",\n    \"check_label\",\n    \"check_nfc\",\n    \"decode\",\n    \"encode\",\n    \"intranges_contain\",\n    \"ulabel\",\n    \"uts46_remap\",\n    \"valid_contextj\",\n    \"valid_contexto\",\n    \"valid_label_length\",\n    \"valid_string_length\",\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/idna/codec.py",
    "content": "from .core import encode, decode, alabel, ulabel, IDNAError\nimport codecs\nimport re\nfrom typing import Tuple, Optional\n\n_unicode_dots_re = re.compile('[\\u002e\\u3002\\uff0e\\uff61]')\n\nclass Codec(codecs.Codec):\n\n    def encode(self, data: str, errors: str = 'strict') -> Tuple[bytes, int]:\n        if errors != 'strict':\n            raise IDNAError('Unsupported error handling \\\"{}\\\"'.format(errors))\n\n        if not data:\n            return b\"\", 0\n\n        return encode(data), len(data)\n\n    def decode(self, data: bytes, errors: str = 'strict') -> Tuple[str, int]:\n        if errors != 'strict':\n            raise IDNAError('Unsupported error handling \\\"{}\\\"'.format(errors))\n\n        if not data:\n            return '', 0\n\n        return decode(data), len(data)\n\nclass IncrementalEncoder(codecs.BufferedIncrementalEncoder):\n    def _buffer_encode(self, data: str, errors: str, final: bool) -> Tuple[str, int]:  # type: ignore\n        if errors != 'strict':\n            raise IDNAError('Unsupported error handling \\\"{}\\\"'.format(errors))\n\n        if not data:\n            return \"\", 0\n\n        labels = _unicode_dots_re.split(data)\n        trailing_dot = ''\n        if labels:\n            if not labels[-1]:\n                trailing_dot = '.'\n                del labels[-1]\n            elif not final:\n                # Keep potentially unfinished label until the next call\n                del labels[-1]\n                if labels:\n                    trailing_dot = '.'\n\n        result = []\n        size = 0\n        for label in labels:\n            result.append(alabel(label))\n            if size:\n                size += 1\n            size += len(label)\n\n        # Join with U+002E\n        result_str = '.'.join(result) + trailing_dot  # type: ignore\n        size += len(trailing_dot)\n        return result_str, size\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n    def _buffer_decode(self, data: str, errors: str, final: bool) -> Tuple[str, int]:  # type: ignore\n        if errors != 'strict':\n            raise IDNAError('Unsupported error handling \\\"{}\\\"'.format(errors))\n\n        if not data:\n            return ('', 0)\n\n        labels = _unicode_dots_re.split(data)\n        trailing_dot = ''\n        if labels:\n            if not labels[-1]:\n                trailing_dot = '.'\n                del labels[-1]\n            elif not final:\n                # Keep potentially unfinished label until the next call\n                del labels[-1]\n                if labels:\n                    trailing_dot = '.'\n\n        result = []\n        size = 0\n        for label in labels:\n            result.append(ulabel(label))\n            if size:\n                size += 1\n            size += len(label)\n\n        result_str = '.'.join(result) + trailing_dot\n        size += len(trailing_dot)\n        return (result_str, size)\n\n\nclass StreamWriter(Codec, codecs.StreamWriter):\n    pass\n\n\nclass StreamReader(Codec, codecs.StreamReader):\n    pass\n\n\ndef getregentry() -> codecs.CodecInfo:\n    # Compatibility as a search_function for codecs.register()\n    return codecs.CodecInfo(\n        name='idna',\n        encode=Codec().encode,  # type: ignore\n        decode=Codec().decode,  # type: ignore\n        incrementalencoder=IncrementalEncoder,\n        incrementaldecoder=IncrementalDecoder,\n        streamwriter=StreamWriter,\n        streamreader=StreamReader,\n    )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/idna/compat.py",
    "content": "from .core import *\nfrom .codec import *\nfrom typing import Any, Union\n\ndef ToASCII(label: str) -> bytes:\n    return encode(label)\n\ndef ToUnicode(label: Union[bytes, bytearray]) -> str:\n    return decode(label)\n\ndef nameprep(s: Any) -> None:\n    raise NotImplementedError('IDNA 2008 does not utilise nameprep protocol')\n\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/idna/core.py",
    "content": "from . import idnadata\nimport bisect\nimport unicodedata\nimport re\nfrom typing import Union, Optional\nfrom .intranges import intranges_contain\n\n_virama_combining_class = 9\n_alabel_prefix = b'xn--'\n_unicode_dots_re = re.compile('[\\u002e\\u3002\\uff0e\\uff61]')\n\nclass IDNAError(UnicodeError):\n    \"\"\" Base exception for all IDNA-encoding related problems \"\"\"\n    pass\n\n\nclass IDNABidiError(IDNAError):\n    \"\"\" Exception when bidirectional requirements are not satisfied \"\"\"\n    pass\n\n\nclass InvalidCodepoint(IDNAError):\n    \"\"\" Exception when a disallowed or unallocated codepoint is used \"\"\"\n    pass\n\n\nclass InvalidCodepointContext(IDNAError):\n    \"\"\" Exception when the codepoint is not valid in the context it is used \"\"\"\n    pass\n\n\ndef _combining_class(cp: int) -> int:\n    v = unicodedata.combining(chr(cp))\n    if v == 0:\n        if not unicodedata.name(chr(cp)):\n            raise ValueError('Unknown character in unicodedata')\n    return v\n\ndef _is_script(cp: str, script: str) -> bool:\n    return intranges_contain(ord(cp), idnadata.scripts[script])\n\ndef _punycode(s: str) -> bytes:\n    return s.encode('punycode')\n\ndef _unot(s: int) -> str:\n    return 'U+{:04X}'.format(s)\n\n\ndef valid_label_length(label: Union[bytes, str]) -> bool:\n    if len(label) > 63:\n        return False\n    return True\n\n\ndef valid_string_length(label: Union[bytes, str], trailing_dot: bool) -> bool:\n    if len(label) > (254 if trailing_dot else 253):\n        return False\n    return True\n\n\ndef check_bidi(label: str, check_ltr: bool = False) -> bool:\n    # Bidi rules should only be applied if string contains RTL characters\n    bidi_label = False\n    for (idx, cp) in enumerate(label, 1):\n        direction = unicodedata.bidirectional(cp)\n        if direction == '':\n            # String likely comes from a newer version of Unicode\n            raise IDNABidiError('Unknown directionality in label {} at position {}'.format(repr(label), idx))\n        if direction in ['R', 'AL', 'AN']:\n            bidi_label = True\n    if not bidi_label and not check_ltr:\n        return True\n\n    # Bidi rule 1\n    direction = unicodedata.bidirectional(label[0])\n    if direction in ['R', 'AL']:\n        rtl = True\n    elif direction == 'L':\n        rtl = False\n    else:\n        raise IDNABidiError('First codepoint in label {} must be directionality L, R or AL'.format(repr(label)))\n\n    valid_ending = False\n    number_type = None  # type: Optional[str]\n    for (idx, cp) in enumerate(label, 1):\n        direction = unicodedata.bidirectional(cp)\n\n        if rtl:\n            # Bidi rule 2\n            if not direction in ['R', 'AL', 'AN', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']:\n                raise IDNABidiError('Invalid direction for codepoint at position {} in a right-to-left label'.format(idx))\n            # Bidi rule 3\n            if direction in ['R', 'AL', 'EN', 'AN']:\n                valid_ending = True\n            elif direction != 'NSM':\n                valid_ending = False\n            # Bidi rule 4\n            if direction in ['AN', 'EN']:\n                if not number_type:\n                    number_type = direction\n                else:\n                    if number_type != direction:\n                        raise IDNABidiError('Can not mix numeral types in a right-to-left label')\n        else:\n            # Bidi rule 5\n            if not direction in ['L', 'EN', 'ES', 'CS', 'ET', 'ON', 'BN', 'NSM']:\n                raise IDNABidiError('Invalid direction for codepoint at position {} in a left-to-right label'.format(idx))\n            # Bidi rule 6\n            if direction in ['L', 'EN']:\n                valid_ending = True\n            elif direction != 'NSM':\n                valid_ending = False\n\n    if not valid_ending:\n        raise IDNABidiError('Label ends with illegal codepoint directionality')\n\n    return True\n\n\ndef check_initial_combiner(label: str) -> bool:\n    if unicodedata.category(label[0])[0] == 'M':\n        raise IDNAError('Label begins with an illegal combining character')\n    return True\n\n\ndef check_hyphen_ok(label: str) -> bool:\n    if label[2:4] == '--':\n        raise IDNAError('Label has disallowed hyphens in 3rd and 4th position')\n    if label[0] == '-' or label[-1] == '-':\n        raise IDNAError('Label must not start or end with a hyphen')\n    return True\n\n\ndef check_nfc(label: str) -> None:\n    if unicodedata.normalize('NFC', label) != label:\n        raise IDNAError('Label must be in Normalization Form C')\n\n\ndef valid_contextj(label: str, pos: int) -> bool:\n    cp_value = ord(label[pos])\n\n    if cp_value == 0x200c:\n\n        if pos > 0:\n            if _combining_class(ord(label[pos - 1])) == _virama_combining_class:\n                return True\n\n        ok = False\n        for i in range(pos-1, -1, -1):\n            joining_type = idnadata.joining_types.get(ord(label[i]))\n            if joining_type == ord('T'):\n                continue\n            if joining_type in [ord('L'), ord('D')]:\n                ok = True\n                break\n\n        if not ok:\n            return False\n\n        ok = False\n        for i in range(pos+1, len(label)):\n            joining_type = idnadata.joining_types.get(ord(label[i]))\n            if joining_type == ord('T'):\n                continue\n            if joining_type in [ord('R'), ord('D')]:\n                ok = True\n                break\n        return ok\n\n    if cp_value == 0x200d:\n\n        if pos > 0:\n            if _combining_class(ord(label[pos - 1])) == _virama_combining_class:\n                return True\n        return False\n\n    else:\n\n        return False\n\n\ndef valid_contexto(label: str, pos: int, exception: bool = False) -> bool:\n    cp_value = ord(label[pos])\n\n    if cp_value == 0x00b7:\n        if 0 < pos < len(label)-1:\n            if ord(label[pos - 1]) == 0x006c and ord(label[pos + 1]) == 0x006c:\n                return True\n        return False\n\n    elif cp_value == 0x0375:\n        if pos < len(label)-1 and len(label) > 1:\n            return _is_script(label[pos + 1], 'Greek')\n        return False\n\n    elif cp_value == 0x05f3 or cp_value == 0x05f4:\n        if pos > 0:\n            return _is_script(label[pos - 1], 'Hebrew')\n        return False\n\n    elif cp_value == 0x30fb:\n        for cp in label:\n            if cp == '\\u30fb':\n                continue\n            if _is_script(cp, 'Hiragana') or _is_script(cp, 'Katakana') or _is_script(cp, 'Han'):\n                return True\n        return False\n\n    elif 0x660 <= cp_value <= 0x669:\n        for cp in label:\n            if 0x6f0 <= ord(cp) <= 0x06f9:\n                return False\n        return True\n\n    elif 0x6f0 <= cp_value <= 0x6f9:\n        for cp in label:\n            if 0x660 <= ord(cp) <= 0x0669:\n                return False\n        return True\n\n    return False\n\n\ndef check_label(label: Union[str, bytes, bytearray]) -> None:\n    if isinstance(label, (bytes, bytearray)):\n        label = label.decode('utf-8')\n    if len(label) == 0:\n        raise IDNAError('Empty Label')\n\n    check_nfc(label)\n    check_hyphen_ok(label)\n    check_initial_combiner(label)\n\n    for (pos, cp) in enumerate(label):\n        cp_value = ord(cp)\n        if intranges_contain(cp_value, idnadata.codepoint_classes['PVALID']):\n            continue\n        elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTJ']):\n            try:\n                if not valid_contextj(label, pos):\n                    raise InvalidCodepointContext('Joiner {} not allowed at position {} in {}'.format(\n                        _unot(cp_value), pos+1, repr(label)))\n            except ValueError:\n                raise IDNAError('Unknown codepoint adjacent to joiner {} at position {} in {}'.format(\n                    _unot(cp_value), pos+1, repr(label)))\n        elif intranges_contain(cp_value, idnadata.codepoint_classes['CONTEXTO']):\n            if not valid_contexto(label, pos):\n                raise InvalidCodepointContext('Codepoint {} not allowed at position {} in {}'.format(_unot(cp_value), pos+1, repr(label)))\n        else:\n            raise InvalidCodepoint('Codepoint {} at position {} of {} not allowed'.format(_unot(cp_value), pos+1, repr(label)))\n\n    check_bidi(label)\n\n\ndef alabel(label: str) -> bytes:\n    try:\n        label_bytes = label.encode('ascii')\n        ulabel(label_bytes)\n        if not valid_label_length(label_bytes):\n            raise IDNAError('Label too long')\n        return label_bytes\n    except UnicodeEncodeError:\n        pass\n\n    if not label:\n        raise IDNAError('No Input')\n\n    label = str(label)\n    check_label(label)\n    label_bytes = _punycode(label)\n    label_bytes = _alabel_prefix + label_bytes\n\n    if not valid_label_length(label_bytes):\n        raise IDNAError('Label too long')\n\n    return label_bytes\n\n\ndef ulabel(label: Union[str, bytes, bytearray]) -> str:\n    if not isinstance(label, (bytes, bytearray)):\n        try:\n            label_bytes = label.encode('ascii')\n        except UnicodeEncodeError:\n            check_label(label)\n            return label\n    else:\n        label_bytes = label\n\n    label_bytes = label_bytes.lower()\n    if label_bytes.startswith(_alabel_prefix):\n        label_bytes = label_bytes[len(_alabel_prefix):]\n        if not label_bytes:\n            raise IDNAError('Malformed A-label, no Punycode eligible content found')\n        if label_bytes.decode('ascii')[-1] == '-':\n            raise IDNAError('A-label must not end with a hyphen')\n    else:\n        check_label(label_bytes)\n        return label_bytes.decode('ascii')\n\n    try:\n        label = label_bytes.decode('punycode')\n    except UnicodeError:\n        raise IDNAError('Invalid A-label')\n    check_label(label)\n    return label\n\n\ndef uts46_remap(domain: str, std3_rules: bool = True, transitional: bool = False) -> str:\n    \"\"\"Re-map the characters in the string according to UTS46 processing.\"\"\"\n    from .uts46data import uts46data\n    output = ''\n\n    for pos, char in enumerate(domain):\n        code_point = ord(char)\n        try:\n            uts46row = uts46data[code_point if code_point < 256 else\n                bisect.bisect_left(uts46data, (code_point, 'Z')) - 1]\n            status = uts46row[1]\n            replacement = None  # type: Optional[str]\n            if len(uts46row) == 3:\n                replacement = uts46row[2]  # type: ignore\n            if (status == 'V' or\n                    (status == 'D' and not transitional) or\n                    (status == '3' and not std3_rules and replacement is None)):\n                output += char\n            elif replacement is not None and (status == 'M' or\n                    (status == '3' and not std3_rules) or\n                    (status == 'D' and transitional)):\n                output += replacement\n            elif status != 'I':\n                raise IndexError()\n        except IndexError:\n            raise InvalidCodepoint(\n                'Codepoint {} not allowed at position {} in {}'.format(\n                _unot(code_point), pos + 1, repr(domain)))\n\n    return unicodedata.normalize('NFC', output)\n\n\ndef encode(s: Union[str, bytes, bytearray], strict: bool = False, uts46: bool = False, std3_rules: bool = False, transitional: bool = False) -> bytes:\n    if isinstance(s, (bytes, bytearray)):\n        try:\n            s = s.decode('ascii')\n        except UnicodeDecodeError:\n            raise IDNAError('should pass a unicode string to the function rather than a byte string.')\n    if uts46:\n        s = uts46_remap(s, std3_rules, transitional)\n    trailing_dot = False\n    result = []\n    if strict:\n        labels = s.split('.')\n    else:\n        labels = _unicode_dots_re.split(s)\n    if not labels or labels == ['']:\n        raise IDNAError('Empty domain')\n    if labels[-1] == '':\n        del labels[-1]\n        trailing_dot = True\n    for label in labels:\n        s = alabel(label)\n        if s:\n            result.append(s)\n        else:\n            raise IDNAError('Empty label')\n    if trailing_dot:\n        result.append(b'')\n    s = b'.'.join(result)\n    if not valid_string_length(s, trailing_dot):\n        raise IDNAError('Domain too long')\n    return s\n\n\ndef decode(s: Union[str, bytes, bytearray], strict: bool = False, uts46: bool = False, std3_rules: bool = False) -> str:\n    try:\n        if isinstance(s, (bytes, bytearray)):\n            s = s.decode('ascii')\n    except UnicodeDecodeError:\n        raise IDNAError('Invalid ASCII in A-label')\n    if uts46:\n        s = uts46_remap(s, std3_rules, False)\n    trailing_dot = False\n    result = []\n    if not strict:\n        labels = _unicode_dots_re.split(s)\n    else:\n        labels = s.split('.')\n    if not labels or labels == ['']:\n        raise IDNAError('Empty domain')\n    if not labels[-1]:\n        del labels[-1]\n        trailing_dot = True\n    for label in labels:\n        s = ulabel(label)\n        if s:\n            result.append(s)\n        else:\n            raise IDNAError('Empty label')\n    if trailing_dot:\n        result.append('')\n    return '.'.join(result)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/idna/idnadata.py",
    "content": "# This file is automatically generated by tools/idna-data\n\n__version__ = '15.0.0'\nscripts = {\n    'Greek': (\n        0x37000000374,\n        0x37500000378,\n        0x37a0000037e,\n        0x37f00000380,\n        0x38400000385,\n        0x38600000387,\n        0x3880000038b,\n        0x38c0000038d,\n        0x38e000003a2,\n        0x3a3000003e2,\n        0x3f000000400,\n        0x1d2600001d2b,\n        0x1d5d00001d62,\n        0x1d6600001d6b,\n        0x1dbf00001dc0,\n        0x1f0000001f16,\n        0x1f1800001f1e,\n        0x1f2000001f46,\n        0x1f4800001f4e,\n        0x1f5000001f58,\n        0x1f5900001f5a,\n        0x1f5b00001f5c,\n        0x1f5d00001f5e,\n        0x1f5f00001f7e,\n        0x1f8000001fb5,\n        0x1fb600001fc5,\n        0x1fc600001fd4,\n        0x1fd600001fdc,\n        0x1fdd00001ff0,\n        0x1ff200001ff5,\n        0x1ff600001fff,\n        0x212600002127,\n        0xab650000ab66,\n        0x101400001018f,\n        0x101a0000101a1,\n        0x1d2000001d246,\n    ),\n    'Han': (\n        0x2e8000002e9a,\n        0x2e9b00002ef4,\n        0x2f0000002fd6,\n        0x300500003006,\n        0x300700003008,\n        0x30210000302a,\n        0x30380000303c,\n        0x340000004dc0,\n        0x4e000000a000,\n        0xf9000000fa6e,\n        0xfa700000fada,\n        0x16fe200016fe4,\n        0x16ff000016ff2,\n        0x200000002a6e0,\n        0x2a7000002b73a,\n        0x2b7400002b81e,\n        0x2b8200002cea2,\n        0x2ceb00002ebe1,\n        0x2f8000002fa1e,\n        0x300000003134b,\n        0x31350000323b0,\n    ),\n    'Hebrew': (\n        0x591000005c8,\n        0x5d0000005eb,\n        0x5ef000005f5,\n        0xfb1d0000fb37,\n        0xfb380000fb3d,\n        0xfb3e0000fb3f,\n        0xfb400000fb42,\n        0xfb430000fb45,\n        0xfb460000fb50,\n    ),\n    'Hiragana': (\n        0x304100003097,\n        0x309d000030a0,\n        0x1b0010001b120,\n        0x1b1320001b133,\n        0x1b1500001b153,\n        0x1f2000001f201,\n    ),\n    'Katakana': (\n        0x30a1000030fb,\n        0x30fd00003100,\n        0x31f000003200,\n        0x32d0000032ff,\n        0x330000003358,\n        0xff660000ff70,\n        0xff710000ff9e,\n        0x1aff00001aff4,\n        0x1aff50001affc,\n        0x1affd0001afff,\n        0x1b0000001b001,\n        0x1b1200001b123,\n        0x1b1550001b156,\n        0x1b1640001b168,\n    ),\n}\njoining_types = {\n    0x600: 85,\n    0x601: 85,\n    0x602: 85,\n    0x603: 85,\n    0x604: 85,\n    0x605: 85,\n    0x608: 85,\n    0x60b: 85,\n    0x620: 68,\n    0x621: 85,\n    0x622: 82,\n    0x623: 82,\n    0x624: 82,\n    0x625: 82,\n    0x626: 68,\n    0x627: 82,\n    0x628: 68,\n    0x629: 82,\n    0x62a: 68,\n    0x62b: 68,\n    0x62c: 68,\n    0x62d: 68,\n    0x62e: 68,\n    0x62f: 82,\n    0x630: 82,\n    0x631: 82,\n    0x632: 82,\n    0x633: 68,\n    0x634: 68,\n    0x635: 68,\n    0x636: 68,\n    0x637: 68,\n    0x638: 68,\n    0x639: 68,\n    0x63a: 68,\n    0x63b: 68,\n    0x63c: 68,\n    0x63d: 68,\n    0x63e: 68,\n    0x63f: 68,\n    0x640: 67,\n    0x641: 68,\n    0x642: 68,\n    0x643: 68,\n    0x644: 68,\n    0x645: 68,\n    0x646: 68,\n    0x647: 68,\n    0x648: 82,\n    0x649: 68,\n    0x64a: 68,\n    0x66e: 68,\n    0x66f: 68,\n    0x671: 82,\n    0x672: 82,\n    0x673: 82,\n    0x674: 85,\n    0x675: 82,\n    0x676: 82,\n    0x677: 82,\n    0x678: 68,\n    0x679: 68,\n    0x67a: 68,\n    0x67b: 68,\n    0x67c: 68,\n    0x67d: 68,\n    0x67e: 68,\n    0x67f: 68,\n    0x680: 68,\n    0x681: 68,\n    0x682: 68,\n    0x683: 68,\n    0x684: 68,\n    0x685: 68,\n    0x686: 68,\n    0x687: 68,\n    0x688: 82,\n    0x689: 82,\n    0x68a: 82,\n    0x68b: 82,\n    0x68c: 82,\n    0x68d: 82,\n    0x68e: 82,\n    0x68f: 82,\n    0x690: 82,\n    0x691: 82,\n    0x692: 82,\n    0x693: 82,\n    0x694: 82,\n    0x695: 82,\n    0x696: 82,\n    0x697: 82,\n    0x698: 82,\n    0x699: 82,\n    0x69a: 68,\n    0x69b: 68,\n    0x69c: 68,\n    0x69d: 68,\n    0x69e: 68,\n    0x69f: 68,\n    0x6a0: 68,\n    0x6a1: 68,\n    0x6a2: 68,\n    0x6a3: 68,\n    0x6a4: 68,\n    0x6a5: 68,\n    0x6a6: 68,\n    0x6a7: 68,\n    0x6a8: 68,\n    0x6a9: 68,\n    0x6aa: 68,\n    0x6ab: 68,\n    0x6ac: 68,\n    0x6ad: 68,\n    0x6ae: 68,\n    0x6af: 68,\n    0x6b0: 68,\n    0x6b1: 68,\n    0x6b2: 68,\n    0x6b3: 68,\n    0x6b4: 68,\n    0x6b5: 68,\n    0x6b6: 68,\n    0x6b7: 68,\n    0x6b8: 68,\n    0x6b9: 68,\n    0x6ba: 68,\n    0x6bb: 68,\n    0x6bc: 68,\n    0x6bd: 68,\n    0x6be: 68,\n    0x6bf: 68,\n    0x6c0: 82,\n    0x6c1: 68,\n    0x6c2: 68,\n    0x6c3: 82,\n    0x6c4: 82,\n    0x6c5: 82,\n    0x6c6: 82,\n    0x6c7: 82,\n    0x6c8: 82,\n    0x6c9: 82,\n    0x6ca: 82,\n    0x6cb: 82,\n    0x6cc: 68,\n    0x6cd: 82,\n    0x6ce: 68,\n    0x6cf: 82,\n    0x6d0: 68,\n    0x6d1: 68,\n    0x6d2: 82,\n    0x6d3: 82,\n    0x6d5: 82,\n    0x6dd: 85,\n    0x6ee: 82,\n    0x6ef: 82,\n    0x6fa: 68,\n    0x6fb: 68,\n    0x6fc: 68,\n    0x6ff: 68,\n    0x70f: 84,\n    0x710: 82,\n    0x712: 68,\n    0x713: 68,\n    0x714: 68,\n    0x715: 82,\n    0x716: 82,\n    0x717: 82,\n    0x718: 82,\n    0x719: 82,\n    0x71a: 68,\n    0x71b: 68,\n    0x71c: 68,\n    0x71d: 68,\n    0x71e: 82,\n    0x71f: 68,\n    0x720: 68,\n    0x721: 68,\n    0x722: 68,\n    0x723: 68,\n    0x724: 68,\n    0x725: 68,\n    0x726: 68,\n    0x727: 68,\n    0x728: 82,\n    0x729: 68,\n    0x72a: 82,\n    0x72b: 68,\n    0x72c: 82,\n    0x72d: 68,\n    0x72e: 68,\n    0x72f: 82,\n    0x74d: 82,\n    0x74e: 68,\n    0x74f: 68,\n    0x750: 68,\n    0x751: 68,\n    0x752: 68,\n    0x753: 68,\n    0x754: 68,\n    0x755: 68,\n    0x756: 68,\n    0x757: 68,\n    0x758: 68,\n    0x759: 82,\n    0x75a: 82,\n    0x75b: 82,\n    0x75c: 68,\n    0x75d: 68,\n    0x75e: 68,\n    0x75f: 68,\n    0x760: 68,\n    0x761: 68,\n    0x762: 68,\n    0x763: 68,\n    0x764: 68,\n    0x765: 68,\n    0x766: 68,\n    0x767: 68,\n    0x768: 68,\n    0x769: 68,\n    0x76a: 68,\n    0x76b: 82,\n    0x76c: 82,\n    0x76d: 68,\n    0x76e: 68,\n    0x76f: 68,\n    0x770: 68,\n    0x771: 82,\n    0x772: 68,\n    0x773: 82,\n    0x774: 82,\n    0x775: 68,\n    0x776: 68,\n    0x777: 68,\n    0x778: 82,\n    0x779: 82,\n    0x77a: 68,\n    0x77b: 68,\n    0x77c: 68,\n    0x77d: 68,\n    0x77e: 68,\n    0x77f: 68,\n    0x7ca: 68,\n    0x7cb: 68,\n    0x7cc: 68,\n    0x7cd: 68,\n    0x7ce: 68,\n    0x7cf: 68,\n    0x7d0: 68,\n    0x7d1: 68,\n    0x7d2: 68,\n    0x7d3: 68,\n    0x7d4: 68,\n    0x7d5: 68,\n    0x7d6: 68,\n    0x7d7: 68,\n    0x7d8: 68,\n    0x7d9: 68,\n    0x7da: 68,\n    0x7db: 68,\n    0x7dc: 68,\n    0x7dd: 68,\n    0x7de: 68,\n    0x7df: 68,\n    0x7e0: 68,\n    0x7e1: 68,\n    0x7e2: 68,\n    0x7e3: 68,\n    0x7e4: 68,\n    0x7e5: 68,\n    0x7e6: 68,\n    0x7e7: 68,\n    0x7e8: 68,\n    0x7e9: 68,\n    0x7ea: 68,\n    0x7fa: 67,\n    0x840: 82,\n    0x841: 68,\n    0x842: 68,\n    0x843: 68,\n    0x844: 68,\n    0x845: 68,\n    0x846: 82,\n    0x847: 82,\n    0x848: 68,\n    0x849: 82,\n    0x84a: 68,\n    0x84b: 68,\n    0x84c: 68,\n    0x84d: 68,\n    0x84e: 68,\n    0x84f: 68,\n    0x850: 68,\n    0x851: 68,\n    0x852: 68,\n    0x853: 68,\n    0x854: 82,\n    0x855: 68,\n    0x856: 82,\n    0x857: 82,\n    0x858: 82,\n    0x860: 68,\n    0x861: 85,\n    0x862: 68,\n    0x863: 68,\n    0x864: 68,\n    0x865: 68,\n    0x866: 85,\n    0x867: 82,\n    0x868: 68,\n    0x869: 82,\n    0x86a: 82,\n    0x870: 82,\n    0x871: 82,\n    0x872: 82,\n    0x873: 82,\n    0x874: 82,\n    0x875: 82,\n    0x876: 82,\n    0x877: 82,\n    0x878: 82,\n    0x879: 82,\n    0x87a: 82,\n    0x87b: 82,\n    0x87c: 82,\n    0x87d: 82,\n    0x87e: 82,\n    0x87f: 82,\n    0x880: 82,\n    0x881: 82,\n    0x882: 82,\n    0x883: 67,\n    0x884: 67,\n    0x885: 67,\n    0x886: 68,\n    0x887: 85,\n    0x888: 85,\n    0x889: 68,\n    0x88a: 68,\n    0x88b: 68,\n    0x88c: 68,\n    0x88d: 68,\n    0x88e: 82,\n    0x890: 85,\n    0x891: 85,\n    0x8a0: 68,\n    0x8a1: 68,\n    0x8a2: 68,\n    0x8a3: 68,\n    0x8a4: 68,\n    0x8a5: 68,\n    0x8a6: 68,\n    0x8a7: 68,\n    0x8a8: 68,\n    0x8a9: 68,\n    0x8aa: 82,\n    0x8ab: 82,\n    0x8ac: 82,\n    0x8ad: 85,\n    0x8ae: 82,\n    0x8af: 68,\n    0x8b0: 68,\n    0x8b1: 82,\n    0x8b2: 82,\n    0x8b3: 68,\n    0x8b4: 68,\n    0x8b5: 68,\n    0x8b6: 68,\n    0x8b7: 68,\n    0x8b8: 68,\n    0x8b9: 82,\n    0x8ba: 68,\n    0x8bb: 68,\n    0x8bc: 68,\n    0x8bd: 68,\n    0x8be: 68,\n    0x8bf: 68,\n    0x8c0: 68,\n    0x8c1: 68,\n    0x8c2: 68,\n    0x8c3: 68,\n    0x8c4: 68,\n    0x8c5: 68,\n    0x8c6: 68,\n    0x8c7: 68,\n    0x8c8: 68,\n    0x8e2: 85,\n    0x1806: 85,\n    0x1807: 68,\n    0x180a: 67,\n    0x180e: 85,\n    0x1820: 68,\n    0x1821: 68,\n    0x1822: 68,\n    0x1823: 68,\n    0x1824: 68,\n    0x1825: 68,\n    0x1826: 68,\n    0x1827: 68,\n    0x1828: 68,\n    0x1829: 68,\n    0x182a: 68,\n    0x182b: 68,\n    0x182c: 68,\n    0x182d: 68,\n    0x182e: 68,\n    0x182f: 68,\n    0x1830: 68,\n    0x1831: 68,\n    0x1832: 68,\n    0x1833: 68,\n    0x1834: 68,\n    0x1835: 68,\n    0x1836: 68,\n    0x1837: 68,\n    0x1838: 68,\n    0x1839: 68,\n    0x183a: 68,\n    0x183b: 68,\n    0x183c: 68,\n    0x183d: 68,\n    0x183e: 68,\n    0x183f: 68,\n    0x1840: 68,\n    0x1841: 68,\n    0x1842: 68,\n    0x1843: 68,\n    0x1844: 68,\n    0x1845: 68,\n    0x1846: 68,\n    0x1847: 68,\n    0x1848: 68,\n    0x1849: 68,\n    0x184a: 68,\n    0x184b: 68,\n    0x184c: 68,\n    0x184d: 68,\n    0x184e: 68,\n    0x184f: 68,\n    0x1850: 68,\n    0x1851: 68,\n    0x1852: 68,\n    0x1853: 68,\n    0x1854: 68,\n    0x1855: 68,\n    0x1856: 68,\n    0x1857: 68,\n    0x1858: 68,\n    0x1859: 68,\n    0x185a: 68,\n    0x185b: 68,\n    0x185c: 68,\n    0x185d: 68,\n    0x185e: 68,\n    0x185f: 68,\n    0x1860: 68,\n    0x1861: 68,\n    0x1862: 68,\n    0x1863: 68,\n    0x1864: 68,\n    0x1865: 68,\n    0x1866: 68,\n    0x1867: 68,\n    0x1868: 68,\n    0x1869: 68,\n    0x186a: 68,\n    0x186b: 68,\n    0x186c: 68,\n    0x186d: 68,\n    0x186e: 68,\n    0x186f: 68,\n    0x1870: 68,\n    0x1871: 68,\n    0x1872: 68,\n    0x1873: 68,\n    0x1874: 68,\n    0x1875: 68,\n    0x1876: 68,\n    0x1877: 68,\n    0x1878: 68,\n    0x1880: 85,\n    0x1881: 85,\n    0x1882: 85,\n    0x1883: 85,\n    0x1884: 85,\n    0x1885: 84,\n    0x1886: 84,\n    0x1887: 68,\n    0x1888: 68,\n    0x1889: 68,\n    0x188a: 68,\n    0x188b: 68,\n    0x188c: 68,\n    0x188d: 68,\n    0x188e: 68,\n    0x188f: 68,\n    0x1890: 68,\n    0x1891: 68,\n    0x1892: 68,\n    0x1893: 68,\n    0x1894: 68,\n    0x1895: 68,\n    0x1896: 68,\n    0x1897: 68,\n    0x1898: 68,\n    0x1899: 68,\n    0x189a: 68,\n    0x189b: 68,\n    0x189c: 68,\n    0x189d: 68,\n    0x189e: 68,\n    0x189f: 68,\n    0x18a0: 68,\n    0x18a1: 68,\n    0x18a2: 68,\n    0x18a3: 68,\n    0x18a4: 68,\n    0x18a5: 68,\n    0x18a6: 68,\n    0x18a7: 68,\n    0x18a8: 68,\n    0x18aa: 68,\n    0x200c: 85,\n    0x200d: 67,\n    0x202f: 85,\n    0x2066: 85,\n    0x2067: 85,\n    0x2068: 85,\n    0x2069: 85,\n    0xa840: 68,\n    0xa841: 68,\n    0xa842: 68,\n    0xa843: 68,\n    0xa844: 68,\n    0xa845: 68,\n    0xa846: 68,\n    0xa847: 68,\n    0xa848: 68,\n    0xa849: 68,\n    0xa84a: 68,\n    0xa84b: 68,\n    0xa84c: 68,\n    0xa84d: 68,\n    0xa84e: 68,\n    0xa84f: 68,\n    0xa850: 68,\n    0xa851: 68,\n    0xa852: 68,\n    0xa853: 68,\n    0xa854: 68,\n    0xa855: 68,\n    0xa856: 68,\n    0xa857: 68,\n    0xa858: 68,\n    0xa859: 68,\n    0xa85a: 68,\n    0xa85b: 68,\n    0xa85c: 68,\n    0xa85d: 68,\n    0xa85e: 68,\n    0xa85f: 68,\n    0xa860: 68,\n    0xa861: 68,\n    0xa862: 68,\n    0xa863: 68,\n    0xa864: 68,\n    0xa865: 68,\n    0xa866: 68,\n    0xa867: 68,\n    0xa868: 68,\n    0xa869: 68,\n    0xa86a: 68,\n    0xa86b: 68,\n    0xa86c: 68,\n    0xa86d: 68,\n    0xa86e: 68,\n    0xa86f: 68,\n    0xa870: 68,\n    0xa871: 68,\n    0xa872: 76,\n    0xa873: 85,\n    0x10ac0: 68,\n    0x10ac1: 68,\n    0x10ac2: 68,\n    0x10ac3: 68,\n    0x10ac4: 68,\n    0x10ac5: 82,\n    0x10ac6: 85,\n    0x10ac7: 82,\n    0x10ac8: 85,\n    0x10ac9: 82,\n    0x10aca: 82,\n    0x10acb: 85,\n    0x10acc: 85,\n    0x10acd: 76,\n    0x10ace: 82,\n    0x10acf: 82,\n    0x10ad0: 82,\n    0x10ad1: 82,\n    0x10ad2: 82,\n    0x10ad3: 68,\n    0x10ad4: 68,\n    0x10ad5: 68,\n    0x10ad6: 68,\n    0x10ad7: 76,\n    0x10ad8: 68,\n    0x10ad9: 68,\n    0x10ada: 68,\n    0x10adb: 68,\n    0x10adc: 68,\n    0x10add: 82,\n    0x10ade: 68,\n    0x10adf: 68,\n    0x10ae0: 68,\n    0x10ae1: 82,\n    0x10ae2: 85,\n    0x10ae3: 85,\n    0x10ae4: 82,\n    0x10aeb: 68,\n    0x10aec: 68,\n    0x10aed: 68,\n    0x10aee: 68,\n    0x10aef: 82,\n    0x10b80: 68,\n    0x10b81: 82,\n    0x10b82: 68,\n    0x10b83: 82,\n    0x10b84: 82,\n    0x10b85: 82,\n    0x10b86: 68,\n    0x10b87: 68,\n    0x10b88: 68,\n    0x10b89: 82,\n    0x10b8a: 68,\n    0x10b8b: 68,\n    0x10b8c: 82,\n    0x10b8d: 68,\n    0x10b8e: 82,\n    0x10b8f: 82,\n    0x10b90: 68,\n    0x10b91: 82,\n    0x10ba9: 82,\n    0x10baa: 82,\n    0x10bab: 82,\n    0x10bac: 82,\n    0x10bad: 68,\n    0x10bae: 68,\n    0x10baf: 85,\n    0x10d00: 76,\n    0x10d01: 68,\n    0x10d02: 68,\n    0x10d03: 68,\n    0x10d04: 68,\n    0x10d05: 68,\n    0x10d06: 68,\n    0x10d07: 68,\n    0x10d08: 68,\n    0x10d09: 68,\n    0x10d0a: 68,\n    0x10d0b: 68,\n    0x10d0c: 68,\n    0x10d0d: 68,\n    0x10d0e: 68,\n    0x10d0f: 68,\n    0x10d10: 68,\n    0x10d11: 68,\n    0x10d12: 68,\n    0x10d13: 68,\n    0x10d14: 68,\n    0x10d15: 68,\n    0x10d16: 68,\n    0x10d17: 68,\n    0x10d18: 68,\n    0x10d19: 68,\n    0x10d1a: 68,\n    0x10d1b: 68,\n    0x10d1c: 68,\n    0x10d1d: 68,\n    0x10d1e: 68,\n    0x10d1f: 68,\n    0x10d20: 68,\n    0x10d21: 68,\n    0x10d22: 82,\n    0x10d23: 68,\n    0x10f30: 68,\n    0x10f31: 68,\n    0x10f32: 68,\n    0x10f33: 82,\n    0x10f34: 68,\n    0x10f35: 68,\n    0x10f36: 68,\n    0x10f37: 68,\n    0x10f38: 68,\n    0x10f39: 68,\n    0x10f3a: 68,\n    0x10f3b: 68,\n    0x10f3c: 68,\n    0x10f3d: 68,\n    0x10f3e: 68,\n    0x10f3f: 68,\n    0x10f40: 68,\n    0x10f41: 68,\n    0x10f42: 68,\n    0x10f43: 68,\n    0x10f44: 68,\n    0x10f45: 85,\n    0x10f51: 68,\n    0x10f52: 68,\n    0x10f53: 68,\n    0x10f54: 82,\n    0x10f70: 68,\n    0x10f71: 68,\n    0x10f72: 68,\n    0x10f73: 68,\n    0x10f74: 82,\n    0x10f75: 82,\n    0x10f76: 68,\n    0x10f77: 68,\n    0x10f78: 68,\n    0x10f79: 68,\n    0x10f7a: 68,\n    0x10f7b: 68,\n    0x10f7c: 68,\n    0x10f7d: 68,\n    0x10f7e: 68,\n    0x10f7f: 68,\n    0x10f80: 68,\n    0x10f81: 68,\n    0x10fb0: 68,\n    0x10fb1: 85,\n    0x10fb2: 68,\n    0x10fb3: 68,\n    0x10fb4: 82,\n    0x10fb5: 82,\n    0x10fb6: 82,\n    0x10fb7: 85,\n    0x10fb8: 68,\n    0x10fb9: 82,\n    0x10fba: 82,\n    0x10fbb: 68,\n    0x10fbc: 68,\n    0x10fbd: 82,\n    0x10fbe: 68,\n    0x10fbf: 68,\n    0x10fc0: 85,\n    0x10fc1: 68,\n    0x10fc2: 82,\n    0x10fc3: 82,\n    0x10fc4: 68,\n    0x10fc5: 85,\n    0x10fc6: 85,\n    0x10fc7: 85,\n    0x10fc8: 85,\n    0x10fc9: 82,\n    0x10fca: 68,\n    0x10fcb: 76,\n    0x110bd: 85,\n    0x110cd: 85,\n    0x1e900: 68,\n    0x1e901: 68,\n    0x1e902: 68,\n    0x1e903: 68,\n    0x1e904: 68,\n    0x1e905: 68,\n    0x1e906: 68,\n    0x1e907: 68,\n    0x1e908: 68,\n    0x1e909: 68,\n    0x1e90a: 68,\n    0x1e90b: 68,\n    0x1e90c: 68,\n    0x1e90d: 68,\n    0x1e90e: 68,\n    0x1e90f: 68,\n    0x1e910: 68,\n    0x1e911: 68,\n    0x1e912: 68,\n    0x1e913: 68,\n    0x1e914: 68,\n    0x1e915: 68,\n    0x1e916: 68,\n    0x1e917: 68,\n    0x1e918: 68,\n    0x1e919: 68,\n    0x1e91a: 68,\n    0x1e91b: 68,\n    0x1e91c: 68,\n    0x1e91d: 68,\n    0x1e91e: 68,\n    0x1e91f: 68,\n    0x1e920: 68,\n    0x1e921: 68,\n    0x1e922: 68,\n    0x1e923: 68,\n    0x1e924: 68,\n    0x1e925: 68,\n    0x1e926: 68,\n    0x1e927: 68,\n    0x1e928: 68,\n    0x1e929: 68,\n    0x1e92a: 68,\n    0x1e92b: 68,\n    0x1e92c: 68,\n    0x1e92d: 68,\n    0x1e92e: 68,\n    0x1e92f: 68,\n    0x1e930: 68,\n    0x1e931: 68,\n    0x1e932: 68,\n    0x1e933: 68,\n    0x1e934: 68,\n    0x1e935: 68,\n    0x1e936: 68,\n    0x1e937: 68,\n    0x1e938: 68,\n    0x1e939: 68,\n    0x1e93a: 68,\n    0x1e93b: 68,\n    0x1e93c: 68,\n    0x1e93d: 68,\n    0x1e93e: 68,\n    0x1e93f: 68,\n    0x1e940: 68,\n    0x1e941: 68,\n    0x1e942: 68,\n    0x1e943: 68,\n    0x1e94b: 84,\n}\ncodepoint_classes = {\n    'PVALID': (\n        0x2d0000002e,\n        0x300000003a,\n        0x610000007b,\n        0xdf000000f7,\n        0xf800000100,\n        0x10100000102,\n        0x10300000104,\n        0x10500000106,\n        0x10700000108,\n        0x1090000010a,\n        0x10b0000010c,\n        0x10d0000010e,\n        0x10f00000110,\n        0x11100000112,\n        0x11300000114,\n        0x11500000116,\n        0x11700000118,\n        0x1190000011a,\n        0x11b0000011c,\n        0x11d0000011e,\n        0x11f00000120,\n        0x12100000122,\n        0x12300000124,\n        0x12500000126,\n        0x12700000128,\n        0x1290000012a,\n        0x12b0000012c,\n        0x12d0000012e,\n        0x12f00000130,\n        0x13100000132,\n        0x13500000136,\n        0x13700000139,\n        0x13a0000013b,\n        0x13c0000013d,\n        0x13e0000013f,\n        0x14200000143,\n        0x14400000145,\n        0x14600000147,\n        0x14800000149,\n        0x14b0000014c,\n        0x14d0000014e,\n        0x14f00000150,\n        0x15100000152,\n        0x15300000154,\n        0x15500000156,\n        0x15700000158,\n        0x1590000015a,\n        0x15b0000015c,\n        0x15d0000015e,\n        0x15f00000160,\n        0x16100000162,\n        0x16300000164,\n        0x16500000166,\n        0x16700000168,\n        0x1690000016a,\n        0x16b0000016c,\n        0x16d0000016e,\n        0x16f00000170,\n        0x17100000172,\n        0x17300000174,\n        0x17500000176,\n        0x17700000178,\n        0x17a0000017b,\n        0x17c0000017d,\n        0x17e0000017f,\n        0x18000000181,\n        0x18300000184,\n        0x18500000186,\n        0x18800000189,\n        0x18c0000018e,\n        0x19200000193,\n        0x19500000196,\n        0x1990000019c,\n        0x19e0000019f,\n        0x1a1000001a2,\n        0x1a3000001a4,\n        0x1a5000001a6,\n        0x1a8000001a9,\n        0x1aa000001ac,\n        0x1ad000001ae,\n        0x1b0000001b1,\n        0x1b4000001b5,\n        0x1b6000001b7,\n        0x1b9000001bc,\n        0x1bd000001c4,\n        0x1ce000001cf,\n        0x1d0000001d1,\n        0x1d2000001d3,\n        0x1d4000001d5,\n        0x1d6000001d7,\n        0x1d8000001d9,\n        0x1da000001db,\n        0x1dc000001de,\n        0x1df000001e0,\n        0x1e1000001e2,\n        0x1e3000001e4,\n        0x1e5000001e6,\n        0x1e7000001e8,\n        0x1e9000001ea,\n        0x1eb000001ec,\n        0x1ed000001ee,\n        0x1ef000001f1,\n        0x1f5000001f6,\n        0x1f9000001fa,\n        0x1fb000001fc,\n        0x1fd000001fe,\n        0x1ff00000200,\n        0x20100000202,\n        0x20300000204,\n        0x20500000206,\n        0x20700000208,\n        0x2090000020a,\n        0x20b0000020c,\n        0x20d0000020e,\n        0x20f00000210,\n        0x21100000212,\n        0x21300000214,\n        0x21500000216,\n        0x21700000218,\n        0x2190000021a,\n        0x21b0000021c,\n        0x21d0000021e,\n        0x21f00000220,\n        0x22100000222,\n        0x22300000224,\n        0x22500000226,\n        0x22700000228,\n        0x2290000022a,\n        0x22b0000022c,\n        0x22d0000022e,\n        0x22f00000230,\n        0x23100000232,\n        0x2330000023a,\n        0x23c0000023d,\n        0x23f00000241,\n        0x24200000243,\n        0x24700000248,\n        0x2490000024a,\n        0x24b0000024c,\n        0x24d0000024e,\n        0x24f000002b0,\n        0x2b9000002c2,\n        0x2c6000002d2,\n        0x2ec000002ed,\n        0x2ee000002ef,\n        0x30000000340,\n        0x34200000343,\n        0x3460000034f,\n        0x35000000370,\n        0x37100000372,\n        0x37300000374,\n        0x37700000378,\n        0x37b0000037e,\n        0x39000000391,\n        0x3ac000003cf,\n        0x3d7000003d8,\n        0x3d9000003da,\n        0x3db000003dc,\n        0x3dd000003de,\n        0x3df000003e0,\n        0x3e1000003e2,\n        0x3e3000003e4,\n        0x3e5000003e6,\n        0x3e7000003e8,\n        0x3e9000003ea,\n        0x3eb000003ec,\n        0x3ed000003ee,\n        0x3ef000003f0,\n        0x3f3000003f4,\n        0x3f8000003f9,\n        0x3fb000003fd,\n        0x43000000460,\n        0x46100000462,\n        0x46300000464,\n        0x46500000466,\n        0x46700000468,\n        0x4690000046a,\n        0x46b0000046c,\n        0x46d0000046e,\n        0x46f00000470,\n        0x47100000472,\n        0x47300000474,\n        0x47500000476,\n        0x47700000478,\n        0x4790000047a,\n        0x47b0000047c,\n        0x47d0000047e,\n        0x47f00000480,\n        0x48100000482,\n        0x48300000488,\n        0x48b0000048c,\n        0x48d0000048e,\n        0x48f00000490,\n        0x49100000492,\n        0x49300000494,\n        0x49500000496,\n        0x49700000498,\n        0x4990000049a,\n        0x49b0000049c,\n        0x49d0000049e,\n        0x49f000004a0,\n        0x4a1000004a2,\n        0x4a3000004a4,\n        0x4a5000004a6,\n        0x4a7000004a8,\n        0x4a9000004aa,\n        0x4ab000004ac,\n        0x4ad000004ae,\n        0x4af000004b0,\n        0x4b1000004b2,\n        0x4b3000004b4,\n        0x4b5000004b6,\n        0x4b7000004b8,\n        0x4b9000004ba,\n        0x4bb000004bc,\n        0x4bd000004be,\n        0x4bf000004c0,\n        0x4c2000004c3,\n        0x4c4000004c5,\n        0x4c6000004c7,\n        0x4c8000004c9,\n        0x4ca000004cb,\n        0x4cc000004cd,\n        0x4ce000004d0,\n        0x4d1000004d2,\n        0x4d3000004d4,\n        0x4d5000004d6,\n        0x4d7000004d8,\n        0x4d9000004da,\n        0x4db000004dc,\n        0x4dd000004de,\n        0x4df000004e0,\n        0x4e1000004e2,\n        0x4e3000004e4,\n        0x4e5000004e6,\n        0x4e7000004e8,\n        0x4e9000004ea,\n        0x4eb000004ec,\n        0x4ed000004ee,\n        0x4ef000004f0,\n        0x4f1000004f2,\n        0x4f3000004f4,\n        0x4f5000004f6,\n        0x4f7000004f8,\n        0x4f9000004fa,\n        0x4fb000004fc,\n        0x4fd000004fe,\n        0x4ff00000500,\n        0x50100000502,\n        0x50300000504,\n        0x50500000506,\n        0x50700000508,\n        0x5090000050a,\n        0x50b0000050c,\n        0x50d0000050e,\n        0x50f00000510,\n        0x51100000512,\n        0x51300000514,\n        0x51500000516,\n        0x51700000518,\n        0x5190000051a,\n        0x51b0000051c,\n        0x51d0000051e,\n        0x51f00000520,\n        0x52100000522,\n        0x52300000524,\n        0x52500000526,\n        0x52700000528,\n        0x5290000052a,\n        0x52b0000052c,\n        0x52d0000052e,\n        0x52f00000530,\n        0x5590000055a,\n        0x56000000587,\n        0x58800000589,\n        0x591000005be,\n        0x5bf000005c0,\n        0x5c1000005c3,\n        0x5c4000005c6,\n        0x5c7000005c8,\n        0x5d0000005eb,\n        0x5ef000005f3,\n        0x6100000061b,\n        0x62000000640,\n        0x64100000660,\n        0x66e00000675,\n        0x679000006d4,\n        0x6d5000006dd,\n        0x6df000006e9,\n        0x6ea000006f0,\n        0x6fa00000700,\n        0x7100000074b,\n        0x74d000007b2,\n        0x7c0000007f6,\n        0x7fd000007fe,\n        0x8000000082e,\n        0x8400000085c,\n        0x8600000086b,\n        0x87000000888,\n        0x8890000088f,\n        0x898000008e2,\n        0x8e300000958,\n        0x96000000964,\n        0x96600000970,\n        0x97100000984,\n        0x9850000098d,\n        0x98f00000991,\n        0x993000009a9,\n        0x9aa000009b1,\n        0x9b2000009b3,\n        0x9b6000009ba,\n        0x9bc000009c5,\n        0x9c7000009c9,\n        0x9cb000009cf,\n        0x9d7000009d8,\n        0x9e0000009e4,\n        0x9e6000009f2,\n        0x9fc000009fd,\n        0x9fe000009ff,\n        0xa0100000a04,\n        0xa0500000a0b,\n        0xa0f00000a11,\n        0xa1300000a29,\n        0xa2a00000a31,\n        0xa3200000a33,\n        0xa3500000a36,\n        0xa3800000a3a,\n        0xa3c00000a3d,\n        0xa3e00000a43,\n        0xa4700000a49,\n        0xa4b00000a4e,\n        0xa5100000a52,\n        0xa5c00000a5d,\n        0xa6600000a76,\n        0xa8100000a84,\n        0xa8500000a8e,\n        0xa8f00000a92,\n        0xa9300000aa9,\n        0xaaa00000ab1,\n        0xab200000ab4,\n        0xab500000aba,\n        0xabc00000ac6,\n        0xac700000aca,\n        0xacb00000ace,\n        0xad000000ad1,\n        0xae000000ae4,\n        0xae600000af0,\n        0xaf900000b00,\n        0xb0100000b04,\n        0xb0500000b0d,\n        0xb0f00000b11,\n        0xb1300000b29,\n        0xb2a00000b31,\n        0xb3200000b34,\n        0xb3500000b3a,\n        0xb3c00000b45,\n        0xb4700000b49,\n        0xb4b00000b4e,\n        0xb5500000b58,\n        0xb5f00000b64,\n        0xb6600000b70,\n        0xb7100000b72,\n        0xb8200000b84,\n        0xb8500000b8b,\n        0xb8e00000b91,\n        0xb9200000b96,\n        0xb9900000b9b,\n        0xb9c00000b9d,\n        0xb9e00000ba0,\n        0xba300000ba5,\n        0xba800000bab,\n        0xbae00000bba,\n        0xbbe00000bc3,\n        0xbc600000bc9,\n        0xbca00000bce,\n        0xbd000000bd1,\n        0xbd700000bd8,\n        0xbe600000bf0,\n        0xc0000000c0d,\n        0xc0e00000c11,\n        0xc1200000c29,\n        0xc2a00000c3a,\n        0xc3c00000c45,\n        0xc4600000c49,\n        0xc4a00000c4e,\n        0xc5500000c57,\n        0xc5800000c5b,\n        0xc5d00000c5e,\n        0xc6000000c64,\n        0xc6600000c70,\n        0xc8000000c84,\n        0xc8500000c8d,\n        0xc8e00000c91,\n        0xc9200000ca9,\n        0xcaa00000cb4,\n        0xcb500000cba,\n        0xcbc00000cc5,\n        0xcc600000cc9,\n        0xcca00000cce,\n        0xcd500000cd7,\n        0xcdd00000cdf,\n        0xce000000ce4,\n        0xce600000cf0,\n        0xcf100000cf4,\n        0xd0000000d0d,\n        0xd0e00000d11,\n        0xd1200000d45,\n        0xd4600000d49,\n        0xd4a00000d4f,\n        0xd5400000d58,\n        0xd5f00000d64,\n        0xd6600000d70,\n        0xd7a00000d80,\n        0xd8100000d84,\n        0xd8500000d97,\n        0xd9a00000db2,\n        0xdb300000dbc,\n        0xdbd00000dbe,\n        0xdc000000dc7,\n        0xdca00000dcb,\n        0xdcf00000dd5,\n        0xdd600000dd7,\n        0xdd800000de0,\n        0xde600000df0,\n        0xdf200000df4,\n        0xe0100000e33,\n        0xe3400000e3b,\n        0xe4000000e4f,\n        0xe5000000e5a,\n        0xe8100000e83,\n        0xe8400000e85,\n        0xe8600000e8b,\n        0xe8c00000ea4,\n        0xea500000ea6,\n        0xea700000eb3,\n        0xeb400000ebe,\n        0xec000000ec5,\n        0xec600000ec7,\n        0xec800000ecf,\n        0xed000000eda,\n        0xede00000ee0,\n        0xf0000000f01,\n        0xf0b00000f0c,\n        0xf1800000f1a,\n        0xf2000000f2a,\n        0xf3500000f36,\n        0xf3700000f38,\n        0xf3900000f3a,\n        0xf3e00000f43,\n        0xf4400000f48,\n        0xf4900000f4d,\n        0xf4e00000f52,\n        0xf5300000f57,\n        0xf5800000f5c,\n        0xf5d00000f69,\n        0xf6a00000f6d,\n        0xf7100000f73,\n        0xf7400000f75,\n        0xf7a00000f81,\n        0xf8200000f85,\n        0xf8600000f93,\n        0xf9400000f98,\n        0xf9900000f9d,\n        0xf9e00000fa2,\n        0xfa300000fa7,\n        0xfa800000fac,\n        0xfad00000fb9,\n        0xfba00000fbd,\n        0xfc600000fc7,\n        0x10000000104a,\n        0x10500000109e,\n        0x10d0000010fb,\n        0x10fd00001100,\n        0x120000001249,\n        0x124a0000124e,\n        0x125000001257,\n        0x125800001259,\n        0x125a0000125e,\n        0x126000001289,\n        0x128a0000128e,\n        0x1290000012b1,\n        0x12b2000012b6,\n        0x12b8000012bf,\n        0x12c0000012c1,\n        0x12c2000012c6,\n        0x12c8000012d7,\n        0x12d800001311,\n        0x131200001316,\n        0x13180000135b,\n        0x135d00001360,\n        0x138000001390,\n        0x13a0000013f6,\n        0x14010000166d,\n        0x166f00001680,\n        0x16810000169b,\n        0x16a0000016eb,\n        0x16f1000016f9,\n        0x170000001716,\n        0x171f00001735,\n        0x174000001754,\n        0x17600000176d,\n        0x176e00001771,\n        0x177200001774,\n        0x1780000017b4,\n        0x17b6000017d4,\n        0x17d7000017d8,\n        0x17dc000017de,\n        0x17e0000017ea,\n        0x18100000181a,\n        0x182000001879,\n        0x1880000018ab,\n        0x18b0000018f6,\n        0x19000000191f,\n        0x19200000192c,\n        0x19300000193c,\n        0x19460000196e,\n        0x197000001975,\n        0x1980000019ac,\n        0x19b0000019ca,\n        0x19d0000019da,\n        0x1a0000001a1c,\n        0x1a2000001a5f,\n        0x1a6000001a7d,\n        0x1a7f00001a8a,\n        0x1a9000001a9a,\n        0x1aa700001aa8,\n        0x1ab000001abe,\n        0x1abf00001acf,\n        0x1b0000001b4d,\n        0x1b5000001b5a,\n        0x1b6b00001b74,\n        0x1b8000001bf4,\n        0x1c0000001c38,\n        0x1c4000001c4a,\n        0x1c4d00001c7e,\n        0x1cd000001cd3,\n        0x1cd400001cfb,\n        0x1d0000001d2c,\n        0x1d2f00001d30,\n        0x1d3b00001d3c,\n        0x1d4e00001d4f,\n        0x1d6b00001d78,\n        0x1d7900001d9b,\n        0x1dc000001e00,\n        0x1e0100001e02,\n        0x1e0300001e04,\n        0x1e0500001e06,\n        0x1e0700001e08,\n        0x1e0900001e0a,\n        0x1e0b00001e0c,\n        0x1e0d00001e0e,\n        0x1e0f00001e10,\n        0x1e1100001e12,\n        0x1e1300001e14,\n        0x1e1500001e16,\n        0x1e1700001e18,\n        0x1e1900001e1a,\n        0x1e1b00001e1c,\n        0x1e1d00001e1e,\n        0x1e1f00001e20,\n        0x1e2100001e22,\n        0x1e2300001e24,\n        0x1e2500001e26,\n        0x1e2700001e28,\n        0x1e2900001e2a,\n        0x1e2b00001e2c,\n        0x1e2d00001e2e,\n        0x1e2f00001e30,\n        0x1e3100001e32,\n        0x1e3300001e34,\n        0x1e3500001e36,\n        0x1e3700001e38,\n        0x1e3900001e3a,\n        0x1e3b00001e3c,\n        0x1e3d00001e3e,\n        0x1e3f00001e40,\n        0x1e4100001e42,\n        0x1e4300001e44,\n        0x1e4500001e46,\n        0x1e4700001e48,\n        0x1e4900001e4a,\n        0x1e4b00001e4c,\n        0x1e4d00001e4e,\n        0x1e4f00001e50,\n        0x1e5100001e52,\n        0x1e5300001e54,\n        0x1e5500001e56,\n        0x1e5700001e58,\n        0x1e5900001e5a,\n        0x1e5b00001e5c,\n        0x1e5d00001e5e,\n        0x1e5f00001e60,\n        0x1e6100001e62,\n        0x1e6300001e64,\n        0x1e6500001e66,\n        0x1e6700001e68,\n        0x1e6900001e6a,\n        0x1e6b00001e6c,\n        0x1e6d00001e6e,\n        0x1e6f00001e70,\n        0x1e7100001e72,\n        0x1e7300001e74,\n        0x1e7500001e76,\n        0x1e7700001e78,\n        0x1e7900001e7a,\n        0x1e7b00001e7c,\n        0x1e7d00001e7e,\n        0x1e7f00001e80,\n        0x1e8100001e82,\n        0x1e8300001e84,\n        0x1e8500001e86,\n        0x1e8700001e88,\n        0x1e8900001e8a,\n        0x1e8b00001e8c,\n        0x1e8d00001e8e,\n        0x1e8f00001e90,\n        0x1e9100001e92,\n        0x1e9300001e94,\n        0x1e9500001e9a,\n        0x1e9c00001e9e,\n        0x1e9f00001ea0,\n        0x1ea100001ea2,\n        0x1ea300001ea4,\n        0x1ea500001ea6,\n        0x1ea700001ea8,\n        0x1ea900001eaa,\n        0x1eab00001eac,\n        0x1ead00001eae,\n        0x1eaf00001eb0,\n        0x1eb100001eb2,\n        0x1eb300001eb4,\n        0x1eb500001eb6,\n        0x1eb700001eb8,\n        0x1eb900001eba,\n        0x1ebb00001ebc,\n        0x1ebd00001ebe,\n        0x1ebf00001ec0,\n        0x1ec100001ec2,\n        0x1ec300001ec4,\n        0x1ec500001ec6,\n        0x1ec700001ec8,\n        0x1ec900001eca,\n        0x1ecb00001ecc,\n        0x1ecd00001ece,\n        0x1ecf00001ed0,\n        0x1ed100001ed2,\n        0x1ed300001ed4,\n        0x1ed500001ed6,\n        0x1ed700001ed8,\n        0x1ed900001eda,\n        0x1edb00001edc,\n        0x1edd00001ede,\n        0x1edf00001ee0,\n        0x1ee100001ee2,\n        0x1ee300001ee4,\n        0x1ee500001ee6,\n        0x1ee700001ee8,\n        0x1ee900001eea,\n        0x1eeb00001eec,\n        0x1eed00001eee,\n        0x1eef00001ef0,\n        0x1ef100001ef2,\n        0x1ef300001ef4,\n        0x1ef500001ef6,\n        0x1ef700001ef8,\n        0x1ef900001efa,\n        0x1efb00001efc,\n        0x1efd00001efe,\n        0x1eff00001f08,\n        0x1f1000001f16,\n        0x1f2000001f28,\n        0x1f3000001f38,\n        0x1f4000001f46,\n        0x1f5000001f58,\n        0x1f6000001f68,\n        0x1f7000001f71,\n        0x1f7200001f73,\n        0x1f7400001f75,\n        0x1f7600001f77,\n        0x1f7800001f79,\n        0x1f7a00001f7b,\n        0x1f7c00001f7d,\n        0x1fb000001fb2,\n        0x1fb600001fb7,\n        0x1fc600001fc7,\n        0x1fd000001fd3,\n        0x1fd600001fd8,\n        0x1fe000001fe3,\n        0x1fe400001fe8,\n        0x1ff600001ff7,\n        0x214e0000214f,\n        0x218400002185,\n        0x2c3000002c60,\n        0x2c6100002c62,\n        0x2c6500002c67,\n        0x2c6800002c69,\n        0x2c6a00002c6b,\n        0x2c6c00002c6d,\n        0x2c7100002c72,\n        0x2c7300002c75,\n        0x2c7600002c7c,\n        0x2c8100002c82,\n        0x2c8300002c84,\n        0x2c8500002c86,\n        0x2c8700002c88,\n        0x2c8900002c8a,\n        0x2c8b00002c8c,\n        0x2c8d00002c8e,\n        0x2c8f00002c90,\n        0x2c9100002c92,\n        0x2c9300002c94,\n        0x2c9500002c96,\n        0x2c9700002c98,\n        0x2c9900002c9a,\n        0x2c9b00002c9c,\n        0x2c9d00002c9e,\n        0x2c9f00002ca0,\n        0x2ca100002ca2,\n        0x2ca300002ca4,\n        0x2ca500002ca6,\n        0x2ca700002ca8,\n        0x2ca900002caa,\n        0x2cab00002cac,\n        0x2cad00002cae,\n        0x2caf00002cb0,\n        0x2cb100002cb2,\n        0x2cb300002cb4,\n        0x2cb500002cb6,\n        0x2cb700002cb8,\n        0x2cb900002cba,\n        0x2cbb00002cbc,\n        0x2cbd00002cbe,\n        0x2cbf00002cc0,\n        0x2cc100002cc2,\n        0x2cc300002cc4,\n        0x2cc500002cc6,\n        0x2cc700002cc8,\n        0x2cc900002cca,\n        0x2ccb00002ccc,\n        0x2ccd00002cce,\n        0x2ccf00002cd0,\n        0x2cd100002cd2,\n        0x2cd300002cd4,\n        0x2cd500002cd6,\n        0x2cd700002cd8,\n        0x2cd900002cda,\n        0x2cdb00002cdc,\n        0x2cdd00002cde,\n        0x2cdf00002ce0,\n        0x2ce100002ce2,\n        0x2ce300002ce5,\n        0x2cec00002ced,\n        0x2cee00002cf2,\n        0x2cf300002cf4,\n        0x2d0000002d26,\n        0x2d2700002d28,\n        0x2d2d00002d2e,\n        0x2d3000002d68,\n        0x2d7f00002d97,\n        0x2da000002da7,\n        0x2da800002daf,\n        0x2db000002db7,\n        0x2db800002dbf,\n        0x2dc000002dc7,\n        0x2dc800002dcf,\n        0x2dd000002dd7,\n        0x2dd800002ddf,\n        0x2de000002e00,\n        0x2e2f00002e30,\n        0x300500003008,\n        0x302a0000302e,\n        0x303c0000303d,\n        0x304100003097,\n        0x30990000309b,\n        0x309d0000309f,\n        0x30a1000030fb,\n        0x30fc000030ff,\n        0x310500003130,\n        0x31a0000031c0,\n        0x31f000003200,\n        0x340000004dc0,\n        0x4e000000a48d,\n        0xa4d00000a4fe,\n        0xa5000000a60d,\n        0xa6100000a62c,\n        0xa6410000a642,\n        0xa6430000a644,\n        0xa6450000a646,\n        0xa6470000a648,\n        0xa6490000a64a,\n        0xa64b0000a64c,\n        0xa64d0000a64e,\n        0xa64f0000a650,\n        0xa6510000a652,\n        0xa6530000a654,\n        0xa6550000a656,\n        0xa6570000a658,\n        0xa6590000a65a,\n        0xa65b0000a65c,\n        0xa65d0000a65e,\n        0xa65f0000a660,\n        0xa6610000a662,\n        0xa6630000a664,\n        0xa6650000a666,\n        0xa6670000a668,\n        0xa6690000a66a,\n        0xa66b0000a66c,\n        0xa66d0000a670,\n        0xa6740000a67e,\n        0xa67f0000a680,\n        0xa6810000a682,\n        0xa6830000a684,\n        0xa6850000a686,\n        0xa6870000a688,\n        0xa6890000a68a,\n        0xa68b0000a68c,\n        0xa68d0000a68e,\n        0xa68f0000a690,\n        0xa6910000a692,\n        0xa6930000a694,\n        0xa6950000a696,\n        0xa6970000a698,\n        0xa6990000a69a,\n        0xa69b0000a69c,\n        0xa69e0000a6e6,\n        0xa6f00000a6f2,\n        0xa7170000a720,\n        0xa7230000a724,\n        0xa7250000a726,\n        0xa7270000a728,\n        0xa7290000a72a,\n        0xa72b0000a72c,\n        0xa72d0000a72e,\n        0xa72f0000a732,\n        0xa7330000a734,\n        0xa7350000a736,\n        0xa7370000a738,\n        0xa7390000a73a,\n        0xa73b0000a73c,\n        0xa73d0000a73e,\n        0xa73f0000a740,\n        0xa7410000a742,\n        0xa7430000a744,\n        0xa7450000a746,\n        0xa7470000a748,\n        0xa7490000a74a,\n        0xa74b0000a74c,\n        0xa74d0000a74e,\n        0xa74f0000a750,\n        0xa7510000a752,\n        0xa7530000a754,\n        0xa7550000a756,\n        0xa7570000a758,\n        0xa7590000a75a,\n        0xa75b0000a75c,\n        0xa75d0000a75e,\n        0xa75f0000a760,\n        0xa7610000a762,\n        0xa7630000a764,\n        0xa7650000a766,\n        0xa7670000a768,\n        0xa7690000a76a,\n        0xa76b0000a76c,\n        0xa76d0000a76e,\n        0xa76f0000a770,\n        0xa7710000a779,\n        0xa77a0000a77b,\n        0xa77c0000a77d,\n        0xa77f0000a780,\n        0xa7810000a782,\n        0xa7830000a784,\n        0xa7850000a786,\n        0xa7870000a789,\n        0xa78c0000a78d,\n        0xa78e0000a790,\n        0xa7910000a792,\n        0xa7930000a796,\n        0xa7970000a798,\n        0xa7990000a79a,\n        0xa79b0000a79c,\n        0xa79d0000a79e,\n        0xa79f0000a7a0,\n        0xa7a10000a7a2,\n        0xa7a30000a7a4,\n        0xa7a50000a7a6,\n        0xa7a70000a7a8,\n        0xa7a90000a7aa,\n        0xa7af0000a7b0,\n        0xa7b50000a7b6,\n        0xa7b70000a7b8,\n        0xa7b90000a7ba,\n        0xa7bb0000a7bc,\n        0xa7bd0000a7be,\n        0xa7bf0000a7c0,\n        0xa7c10000a7c2,\n        0xa7c30000a7c4,\n        0xa7c80000a7c9,\n        0xa7ca0000a7cb,\n        0xa7d10000a7d2,\n        0xa7d30000a7d4,\n        0xa7d50000a7d6,\n        0xa7d70000a7d8,\n        0xa7d90000a7da,\n        0xa7f20000a7f5,\n        0xa7f60000a7f8,\n        0xa7fa0000a828,\n        0xa82c0000a82d,\n        0xa8400000a874,\n        0xa8800000a8c6,\n        0xa8d00000a8da,\n        0xa8e00000a8f8,\n        0xa8fb0000a8fc,\n        0xa8fd0000a92e,\n        0xa9300000a954,\n        0xa9800000a9c1,\n        0xa9cf0000a9da,\n        0xa9e00000a9ff,\n        0xaa000000aa37,\n        0xaa400000aa4e,\n        0xaa500000aa5a,\n        0xaa600000aa77,\n        0xaa7a0000aac3,\n        0xaadb0000aade,\n        0xaae00000aaf0,\n        0xaaf20000aaf7,\n        0xab010000ab07,\n        0xab090000ab0f,\n        0xab110000ab17,\n        0xab200000ab27,\n        0xab280000ab2f,\n        0xab300000ab5b,\n        0xab600000ab69,\n        0xabc00000abeb,\n        0xabec0000abee,\n        0xabf00000abfa,\n        0xac000000d7a4,\n        0xfa0e0000fa10,\n        0xfa110000fa12,\n        0xfa130000fa15,\n        0xfa1f0000fa20,\n        0xfa210000fa22,\n        0xfa230000fa25,\n        0xfa270000fa2a,\n        0xfb1e0000fb1f,\n        0xfe200000fe30,\n        0xfe730000fe74,\n        0x100000001000c,\n        0x1000d00010027,\n        0x100280001003b,\n        0x1003c0001003e,\n        0x1003f0001004e,\n        0x100500001005e,\n        0x10080000100fb,\n        0x101fd000101fe,\n        0x102800001029d,\n        0x102a0000102d1,\n        0x102e0000102e1,\n        0x1030000010320,\n        0x1032d00010341,\n        0x103420001034a,\n        0x103500001037b,\n        0x103800001039e,\n        0x103a0000103c4,\n        0x103c8000103d0,\n        0x104280001049e,\n        0x104a0000104aa,\n        0x104d8000104fc,\n        0x1050000010528,\n        0x1053000010564,\n        0x10597000105a2,\n        0x105a3000105b2,\n        0x105b3000105ba,\n        0x105bb000105bd,\n        0x1060000010737,\n        0x1074000010756,\n        0x1076000010768,\n        0x1078000010786,\n        0x10787000107b1,\n        0x107b2000107bb,\n        0x1080000010806,\n        0x1080800010809,\n        0x1080a00010836,\n        0x1083700010839,\n        0x1083c0001083d,\n        0x1083f00010856,\n        0x1086000010877,\n        0x108800001089f,\n        0x108e0000108f3,\n        0x108f4000108f6,\n        0x1090000010916,\n        0x109200001093a,\n        0x10980000109b8,\n        0x109be000109c0,\n        0x10a0000010a04,\n        0x10a0500010a07,\n        0x10a0c00010a14,\n        0x10a1500010a18,\n        0x10a1900010a36,\n        0x10a3800010a3b,\n        0x10a3f00010a40,\n        0x10a6000010a7d,\n        0x10a8000010a9d,\n        0x10ac000010ac8,\n        0x10ac900010ae7,\n        0x10b0000010b36,\n        0x10b4000010b56,\n        0x10b6000010b73,\n        0x10b8000010b92,\n        0x10c0000010c49,\n        0x10cc000010cf3,\n        0x10d0000010d28,\n        0x10d3000010d3a,\n        0x10e8000010eaa,\n        0x10eab00010ead,\n        0x10eb000010eb2,\n        0x10efd00010f1d,\n        0x10f2700010f28,\n        0x10f3000010f51,\n        0x10f7000010f86,\n        0x10fb000010fc5,\n        0x10fe000010ff7,\n        0x1100000011047,\n        0x1106600011076,\n        0x1107f000110bb,\n        0x110c2000110c3,\n        0x110d0000110e9,\n        0x110f0000110fa,\n        0x1110000011135,\n        0x1113600011140,\n        0x1114400011148,\n        0x1115000011174,\n        0x1117600011177,\n        0x11180000111c5,\n        0x111c9000111cd,\n        0x111ce000111db,\n        0x111dc000111dd,\n        0x1120000011212,\n        0x1121300011238,\n        0x1123e00011242,\n        0x1128000011287,\n        0x1128800011289,\n        0x1128a0001128e,\n        0x1128f0001129e,\n        0x1129f000112a9,\n        0x112b0000112eb,\n        0x112f0000112fa,\n        0x1130000011304,\n        0x113050001130d,\n        0x1130f00011311,\n        0x1131300011329,\n        0x1132a00011331,\n        0x1133200011334,\n        0x113350001133a,\n        0x1133b00011345,\n        0x1134700011349,\n        0x1134b0001134e,\n        0x1135000011351,\n        0x1135700011358,\n        0x1135d00011364,\n        0x113660001136d,\n        0x1137000011375,\n        0x114000001144b,\n        0x114500001145a,\n        0x1145e00011462,\n        0x11480000114c6,\n        0x114c7000114c8,\n        0x114d0000114da,\n        0x11580000115b6,\n        0x115b8000115c1,\n        0x115d8000115de,\n        0x1160000011641,\n        0x1164400011645,\n        0x116500001165a,\n        0x11680000116b9,\n        0x116c0000116ca,\n        0x117000001171b,\n        0x1171d0001172c,\n        0x117300001173a,\n        0x1174000011747,\n        0x118000001183b,\n        0x118c0000118ea,\n        0x118ff00011907,\n        0x119090001190a,\n        0x1190c00011914,\n        0x1191500011917,\n        0x1191800011936,\n        0x1193700011939,\n        0x1193b00011944,\n        0x119500001195a,\n        0x119a0000119a8,\n        0x119aa000119d8,\n        0x119da000119e2,\n        0x119e3000119e5,\n        0x11a0000011a3f,\n        0x11a4700011a48,\n        0x11a5000011a9a,\n        0x11a9d00011a9e,\n        0x11ab000011af9,\n        0x11c0000011c09,\n        0x11c0a00011c37,\n        0x11c3800011c41,\n        0x11c5000011c5a,\n        0x11c7200011c90,\n        0x11c9200011ca8,\n        0x11ca900011cb7,\n        0x11d0000011d07,\n        0x11d0800011d0a,\n        0x11d0b00011d37,\n        0x11d3a00011d3b,\n        0x11d3c00011d3e,\n        0x11d3f00011d48,\n        0x11d5000011d5a,\n        0x11d6000011d66,\n        0x11d6700011d69,\n        0x11d6a00011d8f,\n        0x11d9000011d92,\n        0x11d9300011d99,\n        0x11da000011daa,\n        0x11ee000011ef7,\n        0x11f0000011f11,\n        0x11f1200011f3b,\n        0x11f3e00011f43,\n        0x11f5000011f5a,\n        0x11fb000011fb1,\n        0x120000001239a,\n        0x1248000012544,\n        0x12f9000012ff1,\n        0x1300000013430,\n        0x1344000013456,\n        0x1440000014647,\n        0x1680000016a39,\n        0x16a4000016a5f,\n        0x16a6000016a6a,\n        0x16a7000016abf,\n        0x16ac000016aca,\n        0x16ad000016aee,\n        0x16af000016af5,\n        0x16b0000016b37,\n        0x16b4000016b44,\n        0x16b5000016b5a,\n        0x16b6300016b78,\n        0x16b7d00016b90,\n        0x16e6000016e80,\n        0x16f0000016f4b,\n        0x16f4f00016f88,\n        0x16f8f00016fa0,\n        0x16fe000016fe2,\n        0x16fe300016fe5,\n        0x16ff000016ff2,\n        0x17000000187f8,\n        0x1880000018cd6,\n        0x18d0000018d09,\n        0x1aff00001aff4,\n        0x1aff50001affc,\n        0x1affd0001afff,\n        0x1b0000001b123,\n        0x1b1320001b133,\n        0x1b1500001b153,\n        0x1b1550001b156,\n        0x1b1640001b168,\n        0x1b1700001b2fc,\n        0x1bc000001bc6b,\n        0x1bc700001bc7d,\n        0x1bc800001bc89,\n        0x1bc900001bc9a,\n        0x1bc9d0001bc9f,\n        0x1cf000001cf2e,\n        0x1cf300001cf47,\n        0x1da000001da37,\n        0x1da3b0001da6d,\n        0x1da750001da76,\n        0x1da840001da85,\n        0x1da9b0001daa0,\n        0x1daa10001dab0,\n        0x1df000001df1f,\n        0x1df250001df2b,\n        0x1e0000001e007,\n        0x1e0080001e019,\n        0x1e01b0001e022,\n        0x1e0230001e025,\n        0x1e0260001e02b,\n        0x1e0300001e06e,\n        0x1e08f0001e090,\n        0x1e1000001e12d,\n        0x1e1300001e13e,\n        0x1e1400001e14a,\n        0x1e14e0001e14f,\n        0x1e2900001e2af,\n        0x1e2c00001e2fa,\n        0x1e4d00001e4fa,\n        0x1e7e00001e7e7,\n        0x1e7e80001e7ec,\n        0x1e7ed0001e7ef,\n        0x1e7f00001e7ff,\n        0x1e8000001e8c5,\n        0x1e8d00001e8d7,\n        0x1e9220001e94c,\n        0x1e9500001e95a,\n        0x200000002a6e0,\n        0x2a7000002b73a,\n        0x2b7400002b81e,\n        0x2b8200002cea2,\n        0x2ceb00002ebe1,\n        0x300000003134b,\n        0x31350000323b0,\n    ),\n    'CONTEXTJ': (\n        0x200c0000200e,\n    ),\n    'CONTEXTO': (\n        0xb7000000b8,\n        0x37500000376,\n        0x5f3000005f5,\n        0x6600000066a,\n        0x6f0000006fa,\n        0x30fb000030fc,\n    ),\n}\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/idna/intranges.py",
    "content": "\"\"\"\nGiven a list of integers, made up of (hopefully) a small number of long runs\nof consecutive integers, compute a representation of the form\n((start1, end1), (start2, end2) ...). Then answer the question \"was x present\nin the original list?\" in time O(log(# runs)).\n\"\"\"\n\nimport bisect\nfrom typing import List, Tuple\n\ndef intranges_from_list(list_: List[int]) -> Tuple[int, ...]:\n    \"\"\"Represent a list of integers as a sequence of ranges:\n    ((start_0, end_0), (start_1, end_1), ...), such that the original\n    integers are exactly those x such that start_i <= x < end_i for some i.\n\n    Ranges are encoded as single integers (start << 32 | end), not as tuples.\n    \"\"\"\n\n    sorted_list = sorted(list_)\n    ranges = []\n    last_write = -1\n    for i in range(len(sorted_list)):\n        if i+1 < len(sorted_list):\n            if sorted_list[i] == sorted_list[i+1]-1:\n                continue\n        current_range = sorted_list[last_write+1:i+1]\n        ranges.append(_encode_range(current_range[0], current_range[-1] + 1))\n        last_write = i\n\n    return tuple(ranges)\n\ndef _encode_range(start: int, end: int) -> int:\n    return (start << 32) | end\n\ndef _decode_range(r: int) -> Tuple[int, int]:\n    return (r >> 32), (r & ((1 << 32) - 1))\n\n\ndef intranges_contain(int_: int, ranges: Tuple[int, ...]) -> bool:\n    \"\"\"Determine if `int_` falls into one of the ranges in `ranges`.\"\"\"\n    tuple_ = _encode_range(int_, 0)\n    pos = bisect.bisect_left(ranges, tuple_)\n    # we could be immediately ahead of a tuple (start, end)\n    # with start < int_ <= end\n    if pos > 0:\n        left, right = _decode_range(ranges[pos-1])\n        if left <= int_ < right:\n            return True\n    # or we could be immediately behind a tuple (int_, end)\n    if pos < len(ranges):\n        left, _ = _decode_range(ranges[pos])\n        if left == int_:\n            return True\n    return False\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/idna/package_data.py",
    "content": "__version__ = '3.4'\n\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/idna/uts46data.py",
    "content": "# This file is automatically generated by tools/idna-data\n# vim: set fileencoding=utf-8 :\n\nfrom typing import List, Tuple, Union\n\n\n\"\"\"IDNA Mapping Table from UTS46.\"\"\"\n\n\n__version__ = '15.0.0'\ndef _seg_0() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x0, '3'),\n    (0x1, '3'),\n    (0x2, '3'),\n    (0x3, '3'),\n    (0x4, '3'),\n    (0x5, '3'),\n    (0x6, '3'),\n    (0x7, '3'),\n    (0x8, '3'),\n    (0x9, '3'),\n    (0xA, '3'),\n    (0xB, '3'),\n    (0xC, '3'),\n    (0xD, '3'),\n    (0xE, '3'),\n    (0xF, '3'),\n    (0x10, '3'),\n    (0x11, '3'),\n    (0x12, '3'),\n    (0x13, '3'),\n    (0x14, '3'),\n    (0x15, '3'),\n    (0x16, '3'),\n    (0x17, '3'),\n    (0x18, '3'),\n    (0x19, '3'),\n    (0x1A, '3'),\n    (0x1B, '3'),\n    (0x1C, '3'),\n    (0x1D, '3'),\n    (0x1E, '3'),\n    (0x1F, '3'),\n    (0x20, '3'),\n    (0x21, '3'),\n    (0x22, '3'),\n    (0x23, '3'),\n    (0x24, '3'),\n    (0x25, '3'),\n    (0x26, '3'),\n    (0x27, '3'),\n    (0x28, '3'),\n    (0x29, '3'),\n    (0x2A, '3'),\n    (0x2B, '3'),\n    (0x2C, '3'),\n    (0x2D, 'V'),\n    (0x2E, 'V'),\n    (0x2F, '3'),\n    (0x30, 'V'),\n    (0x31, 'V'),\n    (0x32, 'V'),\n    (0x33, 'V'),\n    (0x34, 'V'),\n    (0x35, 'V'),\n    (0x36, 'V'),\n    (0x37, 'V'),\n    (0x38, 'V'),\n    (0x39, 'V'),\n    (0x3A, '3'),\n    (0x3B, '3'),\n    (0x3C, '3'),\n    (0x3D, '3'),\n    (0x3E, '3'),\n    (0x3F, '3'),\n    (0x40, '3'),\n    (0x41, 'M', 'a'),\n    (0x42, 'M', 'b'),\n    (0x43, 'M', 'c'),\n    (0x44, 'M', 'd'),\n    (0x45, 'M', 'e'),\n    (0x46, 'M', 'f'),\n    (0x47, 'M', 'g'),\n    (0x48, 'M', 'h'),\n    (0x49, 'M', 'i'),\n    (0x4A, 'M', 'j'),\n    (0x4B, 'M', 'k'),\n    (0x4C, 'M', 'l'),\n    (0x4D, 'M', 'm'),\n    (0x4E, 'M', 'n'),\n    (0x4F, 'M', 'o'),\n    (0x50, 'M', 'p'),\n    (0x51, 'M', 'q'),\n    (0x52, 'M', 'r'),\n    (0x53, 'M', 's'),\n    (0x54, 'M', 't'),\n    (0x55, 'M', 'u'),\n    (0x56, 'M', 'v'),\n    (0x57, 'M', 'w'),\n    (0x58, 'M', 'x'),\n    (0x59, 'M', 'y'),\n    (0x5A, 'M', 'z'),\n    (0x5B, '3'),\n    (0x5C, '3'),\n    (0x5D, '3'),\n    (0x5E, '3'),\n    (0x5F, '3'),\n    (0x60, '3'),\n    (0x61, 'V'),\n    (0x62, 'V'),\n    (0x63, 'V'),\n    ]\n\ndef _seg_1() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x64, 'V'),\n    (0x65, 'V'),\n    (0x66, 'V'),\n    (0x67, 'V'),\n    (0x68, 'V'),\n    (0x69, 'V'),\n    (0x6A, 'V'),\n    (0x6B, 'V'),\n    (0x6C, 'V'),\n    (0x6D, 'V'),\n    (0x6E, 'V'),\n    (0x6F, 'V'),\n    (0x70, 'V'),\n    (0x71, 'V'),\n    (0x72, 'V'),\n    (0x73, 'V'),\n    (0x74, 'V'),\n    (0x75, 'V'),\n    (0x76, 'V'),\n    (0x77, 'V'),\n    (0x78, 'V'),\n    (0x79, 'V'),\n    (0x7A, 'V'),\n    (0x7B, '3'),\n    (0x7C, '3'),\n    (0x7D, '3'),\n    (0x7E, '3'),\n    (0x7F, '3'),\n    (0x80, 'X'),\n    (0x81, 'X'),\n    (0x82, 'X'),\n    (0x83, 'X'),\n    (0x84, 'X'),\n    (0x85, 'X'),\n    (0x86, 'X'),\n    (0x87, 'X'),\n    (0x88, 'X'),\n    (0x89, 'X'),\n    (0x8A, 'X'),\n    (0x8B, 'X'),\n    (0x8C, 'X'),\n    (0x8D, 'X'),\n    (0x8E, 'X'),\n    (0x8F, 'X'),\n    (0x90, 'X'),\n    (0x91, 'X'),\n    (0x92, 'X'),\n    (0x93, 'X'),\n    (0x94, 'X'),\n    (0x95, 'X'),\n    (0x96, 'X'),\n    (0x97, 'X'),\n    (0x98, 'X'),\n    (0x99, 'X'),\n    (0x9A, 'X'),\n    (0x9B, 'X'),\n    (0x9C, 'X'),\n    (0x9D, 'X'),\n    (0x9E, 'X'),\n    (0x9F, 'X'),\n    (0xA0, '3', ' '),\n    (0xA1, 'V'),\n    (0xA2, 'V'),\n    (0xA3, 'V'),\n    (0xA4, 'V'),\n    (0xA5, 'V'),\n    (0xA6, 'V'),\n    (0xA7, 'V'),\n    (0xA8, '3', ' ̈'),\n    (0xA9, 'V'),\n    (0xAA, 'M', 'a'),\n    (0xAB, 'V'),\n    (0xAC, 'V'),\n    (0xAD, 'I'),\n    (0xAE, 'V'),\n    (0xAF, '3', ' ̄'),\n    (0xB0, 'V'),\n    (0xB1, 'V'),\n    (0xB2, 'M', '2'),\n    (0xB3, 'M', '3'),\n    (0xB4, '3', ' ́'),\n    (0xB5, 'M', 'μ'),\n    (0xB6, 'V'),\n    (0xB7, 'V'),\n    (0xB8, '3', ' ̧'),\n    (0xB9, 'M', '1'),\n    (0xBA, 'M', 'o'),\n    (0xBB, 'V'),\n    (0xBC, 'M', '1⁄4'),\n    (0xBD, 'M', '1⁄2'),\n    (0xBE, 'M', '3⁄4'),\n    (0xBF, 'V'),\n    (0xC0, 'M', 'à'),\n    (0xC1, 'M', 'á'),\n    (0xC2, 'M', 'â'),\n    (0xC3, 'M', 'ã'),\n    (0xC4, 'M', 'ä'),\n    (0xC5, 'M', 'å'),\n    (0xC6, 'M', 'æ'),\n    (0xC7, 'M', 'ç'),\n    ]\n\ndef _seg_2() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xC8, 'M', 'è'),\n    (0xC9, 'M', 'é'),\n    (0xCA, 'M', 'ê'),\n    (0xCB, 'M', 'ë'),\n    (0xCC, 'M', 'ì'),\n    (0xCD, 'M', 'í'),\n    (0xCE, 'M', 'î'),\n    (0xCF, 'M', 'ï'),\n    (0xD0, 'M', 'ð'),\n    (0xD1, 'M', 'ñ'),\n    (0xD2, 'M', 'ò'),\n    (0xD3, 'M', 'ó'),\n    (0xD4, 'M', 'ô'),\n    (0xD5, 'M', 'õ'),\n    (0xD6, 'M', 'ö'),\n    (0xD7, 'V'),\n    (0xD8, 'M', 'ø'),\n    (0xD9, 'M', 'ù'),\n    (0xDA, 'M', 'ú'),\n    (0xDB, 'M', 'û'),\n    (0xDC, 'M', 'ü'),\n    (0xDD, 'M', 'ý'),\n    (0xDE, 'M', 'þ'),\n    (0xDF, 'D', 'ss'),\n    (0xE0, 'V'),\n    (0xE1, 'V'),\n    (0xE2, 'V'),\n    (0xE3, 'V'),\n    (0xE4, 'V'),\n    (0xE5, 'V'),\n    (0xE6, 'V'),\n    (0xE7, 'V'),\n    (0xE8, 'V'),\n    (0xE9, 'V'),\n    (0xEA, 'V'),\n    (0xEB, 'V'),\n    (0xEC, 'V'),\n    (0xED, 'V'),\n    (0xEE, 'V'),\n    (0xEF, 'V'),\n    (0xF0, 'V'),\n    (0xF1, 'V'),\n    (0xF2, 'V'),\n    (0xF3, 'V'),\n    (0xF4, 'V'),\n    (0xF5, 'V'),\n    (0xF6, 'V'),\n    (0xF7, 'V'),\n    (0xF8, 'V'),\n    (0xF9, 'V'),\n    (0xFA, 'V'),\n    (0xFB, 'V'),\n    (0xFC, 'V'),\n    (0xFD, 'V'),\n    (0xFE, 'V'),\n    (0xFF, 'V'),\n    (0x100, 'M', 'ā'),\n    (0x101, 'V'),\n    (0x102, 'M', 'ă'),\n    (0x103, 'V'),\n    (0x104, 'M', 'ą'),\n    (0x105, 'V'),\n    (0x106, 'M', 'ć'),\n    (0x107, 'V'),\n    (0x108, 'M', 'ĉ'),\n    (0x109, 'V'),\n    (0x10A, 'M', 'ċ'),\n    (0x10B, 'V'),\n    (0x10C, 'M', 'č'),\n    (0x10D, 'V'),\n    (0x10E, 'M', 'ď'),\n    (0x10F, 'V'),\n    (0x110, 'M', 'đ'),\n    (0x111, 'V'),\n    (0x112, 'M', 'ē'),\n    (0x113, 'V'),\n    (0x114, 'M', 'ĕ'),\n    (0x115, 'V'),\n    (0x116, 'M', 'ė'),\n    (0x117, 'V'),\n    (0x118, 'M', 'ę'),\n    (0x119, 'V'),\n    (0x11A, 'M', 'ě'),\n    (0x11B, 'V'),\n    (0x11C, 'M', 'ĝ'),\n    (0x11D, 'V'),\n    (0x11E, 'M', 'ğ'),\n    (0x11F, 'V'),\n    (0x120, 'M', 'ġ'),\n    (0x121, 'V'),\n    (0x122, 'M', 'ģ'),\n    (0x123, 'V'),\n    (0x124, 'M', 'ĥ'),\n    (0x125, 'V'),\n    (0x126, 'M', 'ħ'),\n    (0x127, 'V'),\n    (0x128, 'M', 'ĩ'),\n    (0x129, 'V'),\n    (0x12A, 'M', 'ī'),\n    (0x12B, 'V'),\n    ]\n\ndef _seg_3() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x12C, 'M', 'ĭ'),\n    (0x12D, 'V'),\n    (0x12E, 'M', 'į'),\n    (0x12F, 'V'),\n    (0x130, 'M', 'i̇'),\n    (0x131, 'V'),\n    (0x132, 'M', 'ij'),\n    (0x134, 'M', 'ĵ'),\n    (0x135, 'V'),\n    (0x136, 'M', 'ķ'),\n    (0x137, 'V'),\n    (0x139, 'M', 'ĺ'),\n    (0x13A, 'V'),\n    (0x13B, 'M', 'ļ'),\n    (0x13C, 'V'),\n    (0x13D, 'M', 'ľ'),\n    (0x13E, 'V'),\n    (0x13F, 'M', 'l·'),\n    (0x141, 'M', 'ł'),\n    (0x142, 'V'),\n    (0x143, 'M', 'ń'),\n    (0x144, 'V'),\n    (0x145, 'M', 'ņ'),\n    (0x146, 'V'),\n    (0x147, 'M', 'ň'),\n    (0x148, 'V'),\n    (0x149, 'M', 'ʼn'),\n    (0x14A, 'M', 'ŋ'),\n    (0x14B, 'V'),\n    (0x14C, 'M', 'ō'),\n    (0x14D, 'V'),\n    (0x14E, 'M', 'ŏ'),\n    (0x14F, 'V'),\n    (0x150, 'M', 'ő'),\n    (0x151, 'V'),\n    (0x152, 'M', 'œ'),\n    (0x153, 'V'),\n    (0x154, 'M', 'ŕ'),\n    (0x155, 'V'),\n    (0x156, 'M', 'ŗ'),\n    (0x157, 'V'),\n    (0x158, 'M', 'ř'),\n    (0x159, 'V'),\n    (0x15A, 'M', 'ś'),\n    (0x15B, 'V'),\n    (0x15C, 'M', 'ŝ'),\n    (0x15D, 'V'),\n    (0x15E, 'M', 'ş'),\n    (0x15F, 'V'),\n    (0x160, 'M', 'š'),\n    (0x161, 'V'),\n    (0x162, 'M', 'ţ'),\n    (0x163, 'V'),\n    (0x164, 'M', 'ť'),\n    (0x165, 'V'),\n    (0x166, 'M', 'ŧ'),\n    (0x167, 'V'),\n    (0x168, 'M', 'ũ'),\n    (0x169, 'V'),\n    (0x16A, 'M', 'ū'),\n    (0x16B, 'V'),\n    (0x16C, 'M', 'ŭ'),\n    (0x16D, 'V'),\n    (0x16E, 'M', 'ů'),\n    (0x16F, 'V'),\n    (0x170, 'M', 'ű'),\n    (0x171, 'V'),\n    (0x172, 'M', 'ų'),\n    (0x173, 'V'),\n    (0x174, 'M', 'ŵ'),\n    (0x175, 'V'),\n    (0x176, 'M', 'ŷ'),\n    (0x177, 'V'),\n    (0x178, 'M', 'ÿ'),\n    (0x179, 'M', 'ź'),\n    (0x17A, 'V'),\n    (0x17B, 'M', 'ż'),\n    (0x17C, 'V'),\n    (0x17D, 'M', 'ž'),\n    (0x17E, 'V'),\n    (0x17F, 'M', 's'),\n    (0x180, 'V'),\n    (0x181, 'M', 'ɓ'),\n    (0x182, 'M', 'ƃ'),\n    (0x183, 'V'),\n    (0x184, 'M', 'ƅ'),\n    (0x185, 'V'),\n    (0x186, 'M', 'ɔ'),\n    (0x187, 'M', 'ƈ'),\n    (0x188, 'V'),\n    (0x189, 'M', 'ɖ'),\n    (0x18A, 'M', 'ɗ'),\n    (0x18B, 'M', 'ƌ'),\n    (0x18C, 'V'),\n    (0x18E, 'M', 'ǝ'),\n    (0x18F, 'M', 'ə'),\n    (0x190, 'M', 'ɛ'),\n    (0x191, 'M', 'ƒ'),\n    (0x192, 'V'),\n    (0x193, 'M', 'ɠ'),\n    ]\n\ndef _seg_4() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x194, 'M', 'ɣ'),\n    (0x195, 'V'),\n    (0x196, 'M', 'ɩ'),\n    (0x197, 'M', 'ɨ'),\n    (0x198, 'M', 'ƙ'),\n    (0x199, 'V'),\n    (0x19C, 'M', 'ɯ'),\n    (0x19D, 'M', 'ɲ'),\n    (0x19E, 'V'),\n    (0x19F, 'M', 'ɵ'),\n    (0x1A0, 'M', 'ơ'),\n    (0x1A1, 'V'),\n    (0x1A2, 'M', 'ƣ'),\n    (0x1A3, 'V'),\n    (0x1A4, 'M', 'ƥ'),\n    (0x1A5, 'V'),\n    (0x1A6, 'M', 'ʀ'),\n    (0x1A7, 'M', 'ƨ'),\n    (0x1A8, 'V'),\n    (0x1A9, 'M', 'ʃ'),\n    (0x1AA, 'V'),\n    (0x1AC, 'M', 'ƭ'),\n    (0x1AD, 'V'),\n    (0x1AE, 'M', 'ʈ'),\n    (0x1AF, 'M', 'ư'),\n    (0x1B0, 'V'),\n    (0x1B1, 'M', 'ʊ'),\n    (0x1B2, 'M', 'ʋ'),\n    (0x1B3, 'M', 'ƴ'),\n    (0x1B4, 'V'),\n    (0x1B5, 'M', 'ƶ'),\n    (0x1B6, 'V'),\n    (0x1B7, 'M', 'ʒ'),\n    (0x1B8, 'M', 'ƹ'),\n    (0x1B9, 'V'),\n    (0x1BC, 'M', 'ƽ'),\n    (0x1BD, 'V'),\n    (0x1C4, 'M', 'dž'),\n    (0x1C7, 'M', 'lj'),\n    (0x1CA, 'M', 'nj'),\n    (0x1CD, 'M', 'ǎ'),\n    (0x1CE, 'V'),\n    (0x1CF, 'M', 'ǐ'),\n    (0x1D0, 'V'),\n    (0x1D1, 'M', 'ǒ'),\n    (0x1D2, 'V'),\n    (0x1D3, 'M', 'ǔ'),\n    (0x1D4, 'V'),\n    (0x1D5, 'M', 'ǖ'),\n    (0x1D6, 'V'),\n    (0x1D7, 'M', 'ǘ'),\n    (0x1D8, 'V'),\n    (0x1D9, 'M', 'ǚ'),\n    (0x1DA, 'V'),\n    (0x1DB, 'M', 'ǜ'),\n    (0x1DC, 'V'),\n    (0x1DE, 'M', 'ǟ'),\n    (0x1DF, 'V'),\n    (0x1E0, 'M', 'ǡ'),\n    (0x1E1, 'V'),\n    (0x1E2, 'M', 'ǣ'),\n    (0x1E3, 'V'),\n    (0x1E4, 'M', 'ǥ'),\n    (0x1E5, 'V'),\n    (0x1E6, 'M', 'ǧ'),\n    (0x1E7, 'V'),\n    (0x1E8, 'M', 'ǩ'),\n    (0x1E9, 'V'),\n    (0x1EA, 'M', 'ǫ'),\n    (0x1EB, 'V'),\n    (0x1EC, 'M', 'ǭ'),\n    (0x1ED, 'V'),\n    (0x1EE, 'M', 'ǯ'),\n    (0x1EF, 'V'),\n    (0x1F1, 'M', 'dz'),\n    (0x1F4, 'M', 'ǵ'),\n    (0x1F5, 'V'),\n    (0x1F6, 'M', 'ƕ'),\n    (0x1F7, 'M', 'ƿ'),\n    (0x1F8, 'M', 'ǹ'),\n    (0x1F9, 'V'),\n    (0x1FA, 'M', 'ǻ'),\n    (0x1FB, 'V'),\n    (0x1FC, 'M', 'ǽ'),\n    (0x1FD, 'V'),\n    (0x1FE, 'M', 'ǿ'),\n    (0x1FF, 'V'),\n    (0x200, 'M', 'ȁ'),\n    (0x201, 'V'),\n    (0x202, 'M', 'ȃ'),\n    (0x203, 'V'),\n    (0x204, 'M', 'ȅ'),\n    (0x205, 'V'),\n    (0x206, 'M', 'ȇ'),\n    (0x207, 'V'),\n    (0x208, 'M', 'ȉ'),\n    (0x209, 'V'),\n    (0x20A, 'M', 'ȋ'),\n    (0x20B, 'V'),\n    (0x20C, 'M', 'ȍ'),\n    ]\n\ndef _seg_5() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x20D, 'V'),\n    (0x20E, 'M', 'ȏ'),\n    (0x20F, 'V'),\n    (0x210, 'M', 'ȑ'),\n    (0x211, 'V'),\n    (0x212, 'M', 'ȓ'),\n    (0x213, 'V'),\n    (0x214, 'M', 'ȕ'),\n    (0x215, 'V'),\n    (0x216, 'M', 'ȗ'),\n    (0x217, 'V'),\n    (0x218, 'M', 'ș'),\n    (0x219, 'V'),\n    (0x21A, 'M', 'ț'),\n    (0x21B, 'V'),\n    (0x21C, 'M', 'ȝ'),\n    (0x21D, 'V'),\n    (0x21E, 'M', 'ȟ'),\n    (0x21F, 'V'),\n    (0x220, 'M', 'ƞ'),\n    (0x221, 'V'),\n    (0x222, 'M', 'ȣ'),\n    (0x223, 'V'),\n    (0x224, 'M', 'ȥ'),\n    (0x225, 'V'),\n    (0x226, 'M', 'ȧ'),\n    (0x227, 'V'),\n    (0x228, 'M', 'ȩ'),\n    (0x229, 'V'),\n    (0x22A, 'M', 'ȫ'),\n    (0x22B, 'V'),\n    (0x22C, 'M', 'ȭ'),\n    (0x22D, 'V'),\n    (0x22E, 'M', 'ȯ'),\n    (0x22F, 'V'),\n    (0x230, 'M', 'ȱ'),\n    (0x231, 'V'),\n    (0x232, 'M', 'ȳ'),\n    (0x233, 'V'),\n    (0x23A, 'M', 'ⱥ'),\n    (0x23B, 'M', 'ȼ'),\n    (0x23C, 'V'),\n    (0x23D, 'M', 'ƚ'),\n    (0x23E, 'M', 'ⱦ'),\n    (0x23F, 'V'),\n    (0x241, 'M', 'ɂ'),\n    (0x242, 'V'),\n    (0x243, 'M', 'ƀ'),\n    (0x244, 'M', 'ʉ'),\n    (0x245, 'M', 'ʌ'),\n    (0x246, 'M', 'ɇ'),\n    (0x247, 'V'),\n    (0x248, 'M', 'ɉ'),\n    (0x249, 'V'),\n    (0x24A, 'M', 'ɋ'),\n    (0x24B, 'V'),\n    (0x24C, 'M', 'ɍ'),\n    (0x24D, 'V'),\n    (0x24E, 'M', 'ɏ'),\n    (0x24F, 'V'),\n    (0x2B0, 'M', 'h'),\n    (0x2B1, 'M', 'ɦ'),\n    (0x2B2, 'M', 'j'),\n    (0x2B3, 'M', 'r'),\n    (0x2B4, 'M', 'ɹ'),\n    (0x2B5, 'M', 'ɻ'),\n    (0x2B6, 'M', 'ʁ'),\n    (0x2B7, 'M', 'w'),\n    (0x2B8, 'M', 'y'),\n    (0x2B9, 'V'),\n    (0x2D8, '3', ' ̆'),\n    (0x2D9, '3', ' ̇'),\n    (0x2DA, '3', ' ̊'),\n    (0x2DB, '3', ' ̨'),\n    (0x2DC, '3', ' ̃'),\n    (0x2DD, '3', ' ̋'),\n    (0x2DE, 'V'),\n    (0x2E0, 'M', 'ɣ'),\n    (0x2E1, 'M', 'l'),\n    (0x2E2, 'M', 's'),\n    (0x2E3, 'M', 'x'),\n    (0x2E4, 'M', 'ʕ'),\n    (0x2E5, 'V'),\n    (0x340, 'M', '̀'),\n    (0x341, 'M', '́'),\n    (0x342, 'V'),\n    (0x343, 'M', '̓'),\n    (0x344, 'M', '̈́'),\n    (0x345, 'M', 'ι'),\n    (0x346, 'V'),\n    (0x34F, 'I'),\n    (0x350, 'V'),\n    (0x370, 'M', 'ͱ'),\n    (0x371, 'V'),\n    (0x372, 'M', 'ͳ'),\n    (0x373, 'V'),\n    (0x374, 'M', 'ʹ'),\n    (0x375, 'V'),\n    (0x376, 'M', 'ͷ'),\n    (0x377, 'V'),\n    ]\n\ndef _seg_6() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x378, 'X'),\n    (0x37A, '3', ' ι'),\n    (0x37B, 'V'),\n    (0x37E, '3', ';'),\n    (0x37F, 'M', 'ϳ'),\n    (0x380, 'X'),\n    (0x384, '3', ' ́'),\n    (0x385, '3', ' ̈́'),\n    (0x386, 'M', 'ά'),\n    (0x387, 'M', '·'),\n    (0x388, 'M', 'έ'),\n    (0x389, 'M', 'ή'),\n    (0x38A, 'M', 'ί'),\n    (0x38B, 'X'),\n    (0x38C, 'M', 'ό'),\n    (0x38D, 'X'),\n    (0x38E, 'M', 'ύ'),\n    (0x38F, 'M', 'ώ'),\n    (0x390, 'V'),\n    (0x391, 'M', 'α'),\n    (0x392, 'M', 'β'),\n    (0x393, 'M', 'γ'),\n    (0x394, 'M', 'δ'),\n    (0x395, 'M', 'ε'),\n    (0x396, 'M', 'ζ'),\n    (0x397, 'M', 'η'),\n    (0x398, 'M', 'θ'),\n    (0x399, 'M', 'ι'),\n    (0x39A, 'M', 'κ'),\n    (0x39B, 'M', 'λ'),\n    (0x39C, 'M', 'μ'),\n    (0x39D, 'M', 'ν'),\n    (0x39E, 'M', 'ξ'),\n    (0x39F, 'M', 'ο'),\n    (0x3A0, 'M', 'π'),\n    (0x3A1, 'M', 'ρ'),\n    (0x3A2, 'X'),\n    (0x3A3, 'M', 'σ'),\n    (0x3A4, 'M', 'τ'),\n    (0x3A5, 'M', 'υ'),\n    (0x3A6, 'M', 'φ'),\n    (0x3A7, 'M', 'χ'),\n    (0x3A8, 'M', 'ψ'),\n    (0x3A9, 'M', 'ω'),\n    (0x3AA, 'M', 'ϊ'),\n    (0x3AB, 'M', 'ϋ'),\n    (0x3AC, 'V'),\n    (0x3C2, 'D', 'σ'),\n    (0x3C3, 'V'),\n    (0x3CF, 'M', 'ϗ'),\n    (0x3D0, 'M', 'β'),\n    (0x3D1, 'M', 'θ'),\n    (0x3D2, 'M', 'υ'),\n    (0x3D3, 'M', 'ύ'),\n    (0x3D4, 'M', 'ϋ'),\n    (0x3D5, 'M', 'φ'),\n    (0x3D6, 'M', 'π'),\n    (0x3D7, 'V'),\n    (0x3D8, 'M', 'ϙ'),\n    (0x3D9, 'V'),\n    (0x3DA, 'M', 'ϛ'),\n    (0x3DB, 'V'),\n    (0x3DC, 'M', 'ϝ'),\n    (0x3DD, 'V'),\n    (0x3DE, 'M', 'ϟ'),\n    (0x3DF, 'V'),\n    (0x3E0, 'M', 'ϡ'),\n    (0x3E1, 'V'),\n    (0x3E2, 'M', 'ϣ'),\n    (0x3E3, 'V'),\n    (0x3E4, 'M', 'ϥ'),\n    (0x3E5, 'V'),\n    (0x3E6, 'M', 'ϧ'),\n    (0x3E7, 'V'),\n    (0x3E8, 'M', 'ϩ'),\n    (0x3E9, 'V'),\n    (0x3EA, 'M', 'ϫ'),\n    (0x3EB, 'V'),\n    (0x3EC, 'M', 'ϭ'),\n    (0x3ED, 'V'),\n    (0x3EE, 'M', 'ϯ'),\n    (0x3EF, 'V'),\n    (0x3F0, 'M', 'κ'),\n    (0x3F1, 'M', 'ρ'),\n    (0x3F2, 'M', 'σ'),\n    (0x3F3, 'V'),\n    (0x3F4, 'M', 'θ'),\n    (0x3F5, 'M', 'ε'),\n    (0x3F6, 'V'),\n    (0x3F7, 'M', 'ϸ'),\n    (0x3F8, 'V'),\n    (0x3F9, 'M', 'σ'),\n    (0x3FA, 'M', 'ϻ'),\n    (0x3FB, 'V'),\n    (0x3FD, 'M', 'ͻ'),\n    (0x3FE, 'M', 'ͼ'),\n    (0x3FF, 'M', 'ͽ'),\n    (0x400, 'M', 'ѐ'),\n    (0x401, 'M', 'ё'),\n    (0x402, 'M', 'ђ'),\n    ]\n\ndef _seg_7() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x403, 'M', 'ѓ'),\n    (0x404, 'M', 'є'),\n    (0x405, 'M', 'ѕ'),\n    (0x406, 'M', 'і'),\n    (0x407, 'M', 'ї'),\n    (0x408, 'M', 'ј'),\n    (0x409, 'M', 'љ'),\n    (0x40A, 'M', 'њ'),\n    (0x40B, 'M', 'ћ'),\n    (0x40C, 'M', 'ќ'),\n    (0x40D, 'M', 'ѝ'),\n    (0x40E, 'M', 'ў'),\n    (0x40F, 'M', 'џ'),\n    (0x410, 'M', 'а'),\n    (0x411, 'M', 'б'),\n    (0x412, 'M', 'в'),\n    (0x413, 'M', 'г'),\n    (0x414, 'M', 'д'),\n    (0x415, 'M', 'е'),\n    (0x416, 'M', 'ж'),\n    (0x417, 'M', 'з'),\n    (0x418, 'M', 'и'),\n    (0x419, 'M', 'й'),\n    (0x41A, 'M', 'к'),\n    (0x41B, 'M', 'л'),\n    (0x41C, 'M', 'м'),\n    (0x41D, 'M', 'н'),\n    (0x41E, 'M', 'о'),\n    (0x41F, 'M', 'п'),\n    (0x420, 'M', 'р'),\n    (0x421, 'M', 'с'),\n    (0x422, 'M', 'т'),\n    (0x423, 'M', 'у'),\n    (0x424, 'M', 'ф'),\n    (0x425, 'M', 'х'),\n    (0x426, 'M', 'ц'),\n    (0x427, 'M', 'ч'),\n    (0x428, 'M', 'ш'),\n    (0x429, 'M', 'щ'),\n    (0x42A, 'M', 'ъ'),\n    (0x42B, 'M', 'ы'),\n    (0x42C, 'M', 'ь'),\n    (0x42D, 'M', 'э'),\n    (0x42E, 'M', 'ю'),\n    (0x42F, 'M', 'я'),\n    (0x430, 'V'),\n    (0x460, 'M', 'ѡ'),\n    (0x461, 'V'),\n    (0x462, 'M', 'ѣ'),\n    (0x463, 'V'),\n    (0x464, 'M', 'ѥ'),\n    (0x465, 'V'),\n    (0x466, 'M', 'ѧ'),\n    (0x467, 'V'),\n    (0x468, 'M', 'ѩ'),\n    (0x469, 'V'),\n    (0x46A, 'M', 'ѫ'),\n    (0x46B, 'V'),\n    (0x46C, 'M', 'ѭ'),\n    (0x46D, 'V'),\n    (0x46E, 'M', 'ѯ'),\n    (0x46F, 'V'),\n    (0x470, 'M', 'ѱ'),\n    (0x471, 'V'),\n    (0x472, 'M', 'ѳ'),\n    (0x473, 'V'),\n    (0x474, 'M', 'ѵ'),\n    (0x475, 'V'),\n    (0x476, 'M', 'ѷ'),\n    (0x477, 'V'),\n    (0x478, 'M', 'ѹ'),\n    (0x479, 'V'),\n    (0x47A, 'M', 'ѻ'),\n    (0x47B, 'V'),\n    (0x47C, 'M', 'ѽ'),\n    (0x47D, 'V'),\n    (0x47E, 'M', 'ѿ'),\n    (0x47F, 'V'),\n    (0x480, 'M', 'ҁ'),\n    (0x481, 'V'),\n    (0x48A, 'M', 'ҋ'),\n    (0x48B, 'V'),\n    (0x48C, 'M', 'ҍ'),\n    (0x48D, 'V'),\n    (0x48E, 'M', 'ҏ'),\n    (0x48F, 'V'),\n    (0x490, 'M', 'ґ'),\n    (0x491, 'V'),\n    (0x492, 'M', 'ғ'),\n    (0x493, 'V'),\n    (0x494, 'M', 'ҕ'),\n    (0x495, 'V'),\n    (0x496, 'M', 'җ'),\n    (0x497, 'V'),\n    (0x498, 'M', 'ҙ'),\n    (0x499, 'V'),\n    (0x49A, 'M', 'қ'),\n    (0x49B, 'V'),\n    (0x49C, 'M', 'ҝ'),\n    (0x49D, 'V'),\n    ]\n\ndef _seg_8() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x49E, 'M', 'ҟ'),\n    (0x49F, 'V'),\n    (0x4A0, 'M', 'ҡ'),\n    (0x4A1, 'V'),\n    (0x4A2, 'M', 'ң'),\n    (0x4A3, 'V'),\n    (0x4A4, 'M', 'ҥ'),\n    (0x4A5, 'V'),\n    (0x4A6, 'M', 'ҧ'),\n    (0x4A7, 'V'),\n    (0x4A8, 'M', 'ҩ'),\n    (0x4A9, 'V'),\n    (0x4AA, 'M', 'ҫ'),\n    (0x4AB, 'V'),\n    (0x4AC, 'M', 'ҭ'),\n    (0x4AD, 'V'),\n    (0x4AE, 'M', 'ү'),\n    (0x4AF, 'V'),\n    (0x4B0, 'M', 'ұ'),\n    (0x4B1, 'V'),\n    (0x4B2, 'M', 'ҳ'),\n    (0x4B3, 'V'),\n    (0x4B4, 'M', 'ҵ'),\n    (0x4B5, 'V'),\n    (0x4B6, 'M', 'ҷ'),\n    (0x4B7, 'V'),\n    (0x4B8, 'M', 'ҹ'),\n    (0x4B9, 'V'),\n    (0x4BA, 'M', 'һ'),\n    (0x4BB, 'V'),\n    (0x4BC, 'M', 'ҽ'),\n    (0x4BD, 'V'),\n    (0x4BE, 'M', 'ҿ'),\n    (0x4BF, 'V'),\n    (0x4C0, 'X'),\n    (0x4C1, 'M', 'ӂ'),\n    (0x4C2, 'V'),\n    (0x4C3, 'M', 'ӄ'),\n    (0x4C4, 'V'),\n    (0x4C5, 'M', 'ӆ'),\n    (0x4C6, 'V'),\n    (0x4C7, 'M', 'ӈ'),\n    (0x4C8, 'V'),\n    (0x4C9, 'M', 'ӊ'),\n    (0x4CA, 'V'),\n    (0x4CB, 'M', 'ӌ'),\n    (0x4CC, 'V'),\n    (0x4CD, 'M', 'ӎ'),\n    (0x4CE, 'V'),\n    (0x4D0, 'M', 'ӑ'),\n    (0x4D1, 'V'),\n    (0x4D2, 'M', 'ӓ'),\n    (0x4D3, 'V'),\n    (0x4D4, 'M', 'ӕ'),\n    (0x4D5, 'V'),\n    (0x4D6, 'M', 'ӗ'),\n    (0x4D7, 'V'),\n    (0x4D8, 'M', 'ә'),\n    (0x4D9, 'V'),\n    (0x4DA, 'M', 'ӛ'),\n    (0x4DB, 'V'),\n    (0x4DC, 'M', 'ӝ'),\n    (0x4DD, 'V'),\n    (0x4DE, 'M', 'ӟ'),\n    (0x4DF, 'V'),\n    (0x4E0, 'M', 'ӡ'),\n    (0x4E1, 'V'),\n    (0x4E2, 'M', 'ӣ'),\n    (0x4E3, 'V'),\n    (0x4E4, 'M', 'ӥ'),\n    (0x4E5, 'V'),\n    (0x4E6, 'M', 'ӧ'),\n    (0x4E7, 'V'),\n    (0x4E8, 'M', 'ө'),\n    (0x4E9, 'V'),\n    (0x4EA, 'M', 'ӫ'),\n    (0x4EB, 'V'),\n    (0x4EC, 'M', 'ӭ'),\n    (0x4ED, 'V'),\n    (0x4EE, 'M', 'ӯ'),\n    (0x4EF, 'V'),\n    (0x4F0, 'M', 'ӱ'),\n    (0x4F1, 'V'),\n    (0x4F2, 'M', 'ӳ'),\n    (0x4F3, 'V'),\n    (0x4F4, 'M', 'ӵ'),\n    (0x4F5, 'V'),\n    (0x4F6, 'M', 'ӷ'),\n    (0x4F7, 'V'),\n    (0x4F8, 'M', 'ӹ'),\n    (0x4F9, 'V'),\n    (0x4FA, 'M', 'ӻ'),\n    (0x4FB, 'V'),\n    (0x4FC, 'M', 'ӽ'),\n    (0x4FD, 'V'),\n    (0x4FE, 'M', 'ӿ'),\n    (0x4FF, 'V'),\n    (0x500, 'M', 'ԁ'),\n    (0x501, 'V'),\n    (0x502, 'M', 'ԃ'),\n    ]\n\ndef _seg_9() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x503, 'V'),\n    (0x504, 'M', 'ԅ'),\n    (0x505, 'V'),\n    (0x506, 'M', 'ԇ'),\n    (0x507, 'V'),\n    (0x508, 'M', 'ԉ'),\n    (0x509, 'V'),\n    (0x50A, 'M', 'ԋ'),\n    (0x50B, 'V'),\n    (0x50C, 'M', 'ԍ'),\n    (0x50D, 'V'),\n    (0x50E, 'M', 'ԏ'),\n    (0x50F, 'V'),\n    (0x510, 'M', 'ԑ'),\n    (0x511, 'V'),\n    (0x512, 'M', 'ԓ'),\n    (0x513, 'V'),\n    (0x514, 'M', 'ԕ'),\n    (0x515, 'V'),\n    (0x516, 'M', 'ԗ'),\n    (0x517, 'V'),\n    (0x518, 'M', 'ԙ'),\n    (0x519, 'V'),\n    (0x51A, 'M', 'ԛ'),\n    (0x51B, 'V'),\n    (0x51C, 'M', 'ԝ'),\n    (0x51D, 'V'),\n    (0x51E, 'M', 'ԟ'),\n    (0x51F, 'V'),\n    (0x520, 'M', 'ԡ'),\n    (0x521, 'V'),\n    (0x522, 'M', 'ԣ'),\n    (0x523, 'V'),\n    (0x524, 'M', 'ԥ'),\n    (0x525, 'V'),\n    (0x526, 'M', 'ԧ'),\n    (0x527, 'V'),\n    (0x528, 'M', 'ԩ'),\n    (0x529, 'V'),\n    (0x52A, 'M', 'ԫ'),\n    (0x52B, 'V'),\n    (0x52C, 'M', 'ԭ'),\n    (0x52D, 'V'),\n    (0x52E, 'M', 'ԯ'),\n    (0x52F, 'V'),\n    (0x530, 'X'),\n    (0x531, 'M', 'ա'),\n    (0x532, 'M', 'բ'),\n    (0x533, 'M', 'գ'),\n    (0x534, 'M', 'դ'),\n    (0x535, 'M', 'ե'),\n    (0x536, 'M', 'զ'),\n    (0x537, 'M', 'է'),\n    (0x538, 'M', 'ը'),\n    (0x539, 'M', 'թ'),\n    (0x53A, 'M', 'ժ'),\n    (0x53B, 'M', 'ի'),\n    (0x53C, 'M', 'լ'),\n    (0x53D, 'M', 'խ'),\n    (0x53E, 'M', 'ծ'),\n    (0x53F, 'M', 'կ'),\n    (0x540, 'M', 'հ'),\n    (0x541, 'M', 'ձ'),\n    (0x542, 'M', 'ղ'),\n    (0x543, 'M', 'ճ'),\n    (0x544, 'M', 'մ'),\n    (0x545, 'M', 'յ'),\n    (0x546, 'M', 'ն'),\n    (0x547, 'M', 'շ'),\n    (0x548, 'M', 'ո'),\n    (0x549, 'M', 'չ'),\n    (0x54A, 'M', 'պ'),\n    (0x54B, 'M', 'ջ'),\n    (0x54C, 'M', 'ռ'),\n    (0x54D, 'M', 'ս'),\n    (0x54E, 'M', 'վ'),\n    (0x54F, 'M', 'տ'),\n    (0x550, 'M', 'ր'),\n    (0x551, 'M', 'ց'),\n    (0x552, 'M', 'ւ'),\n    (0x553, 'M', 'փ'),\n    (0x554, 'M', 'ք'),\n    (0x555, 'M', 'օ'),\n    (0x556, 'M', 'ֆ'),\n    (0x557, 'X'),\n    (0x559, 'V'),\n    (0x587, 'M', 'եւ'),\n    (0x588, 'V'),\n    (0x58B, 'X'),\n    (0x58D, 'V'),\n    (0x590, 'X'),\n    (0x591, 'V'),\n    (0x5C8, 'X'),\n    (0x5D0, 'V'),\n    (0x5EB, 'X'),\n    (0x5EF, 'V'),\n    (0x5F5, 'X'),\n    (0x606, 'V'),\n    (0x61C, 'X'),\n    (0x61D, 'V'),\n    ]\n\ndef _seg_10() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x675, 'M', 'اٴ'),\n    (0x676, 'M', 'وٴ'),\n    (0x677, 'M', 'ۇٴ'),\n    (0x678, 'M', 'يٴ'),\n    (0x679, 'V'),\n    (0x6DD, 'X'),\n    (0x6DE, 'V'),\n    (0x70E, 'X'),\n    (0x710, 'V'),\n    (0x74B, 'X'),\n    (0x74D, 'V'),\n    (0x7B2, 'X'),\n    (0x7C0, 'V'),\n    (0x7FB, 'X'),\n    (0x7FD, 'V'),\n    (0x82E, 'X'),\n    (0x830, 'V'),\n    (0x83F, 'X'),\n    (0x840, 'V'),\n    (0x85C, 'X'),\n    (0x85E, 'V'),\n    (0x85F, 'X'),\n    (0x860, 'V'),\n    (0x86B, 'X'),\n    (0x870, 'V'),\n    (0x88F, 'X'),\n    (0x898, 'V'),\n    (0x8E2, 'X'),\n    (0x8E3, 'V'),\n    (0x958, 'M', 'क़'),\n    (0x959, 'M', 'ख़'),\n    (0x95A, 'M', 'ग़'),\n    (0x95B, 'M', 'ज़'),\n    (0x95C, 'M', 'ड़'),\n    (0x95D, 'M', 'ढ़'),\n    (0x95E, 'M', 'फ़'),\n    (0x95F, 'M', 'य़'),\n    (0x960, 'V'),\n    (0x984, 'X'),\n    (0x985, 'V'),\n    (0x98D, 'X'),\n    (0x98F, 'V'),\n    (0x991, 'X'),\n    (0x993, 'V'),\n    (0x9A9, 'X'),\n    (0x9AA, 'V'),\n    (0x9B1, 'X'),\n    (0x9B2, 'V'),\n    (0x9B3, 'X'),\n    (0x9B6, 'V'),\n    (0x9BA, 'X'),\n    (0x9BC, 'V'),\n    (0x9C5, 'X'),\n    (0x9C7, 'V'),\n    (0x9C9, 'X'),\n    (0x9CB, 'V'),\n    (0x9CF, 'X'),\n    (0x9D7, 'V'),\n    (0x9D8, 'X'),\n    (0x9DC, 'M', 'ড়'),\n    (0x9DD, 'M', 'ঢ়'),\n    (0x9DE, 'X'),\n    (0x9DF, 'M', 'য়'),\n    (0x9E0, 'V'),\n    (0x9E4, 'X'),\n    (0x9E6, 'V'),\n    (0x9FF, 'X'),\n    (0xA01, 'V'),\n    (0xA04, 'X'),\n    (0xA05, 'V'),\n    (0xA0B, 'X'),\n    (0xA0F, 'V'),\n    (0xA11, 'X'),\n    (0xA13, 'V'),\n    (0xA29, 'X'),\n    (0xA2A, 'V'),\n    (0xA31, 'X'),\n    (0xA32, 'V'),\n    (0xA33, 'M', 'ਲ਼'),\n    (0xA34, 'X'),\n    (0xA35, 'V'),\n    (0xA36, 'M', 'ਸ਼'),\n    (0xA37, 'X'),\n    (0xA38, 'V'),\n    (0xA3A, 'X'),\n    (0xA3C, 'V'),\n    (0xA3D, 'X'),\n    (0xA3E, 'V'),\n    (0xA43, 'X'),\n    (0xA47, 'V'),\n    (0xA49, 'X'),\n    (0xA4B, 'V'),\n    (0xA4E, 'X'),\n    (0xA51, 'V'),\n    (0xA52, 'X'),\n    (0xA59, 'M', 'ਖ਼'),\n    (0xA5A, 'M', 'ਗ਼'),\n    (0xA5B, 'M', 'ਜ਼'),\n    (0xA5C, 'V'),\n    (0xA5D, 'X'),\n    ]\n\ndef _seg_11() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xA5E, 'M', 'ਫ਼'),\n    (0xA5F, 'X'),\n    (0xA66, 'V'),\n    (0xA77, 'X'),\n    (0xA81, 'V'),\n    (0xA84, 'X'),\n    (0xA85, 'V'),\n    (0xA8E, 'X'),\n    (0xA8F, 'V'),\n    (0xA92, 'X'),\n    (0xA93, 'V'),\n    (0xAA9, 'X'),\n    (0xAAA, 'V'),\n    (0xAB1, 'X'),\n    (0xAB2, 'V'),\n    (0xAB4, 'X'),\n    (0xAB5, 'V'),\n    (0xABA, 'X'),\n    (0xABC, 'V'),\n    (0xAC6, 'X'),\n    (0xAC7, 'V'),\n    (0xACA, 'X'),\n    (0xACB, 'V'),\n    (0xACE, 'X'),\n    (0xAD0, 'V'),\n    (0xAD1, 'X'),\n    (0xAE0, 'V'),\n    (0xAE4, 'X'),\n    (0xAE6, 'V'),\n    (0xAF2, 'X'),\n    (0xAF9, 'V'),\n    (0xB00, 'X'),\n    (0xB01, 'V'),\n    (0xB04, 'X'),\n    (0xB05, 'V'),\n    (0xB0D, 'X'),\n    (0xB0F, 'V'),\n    (0xB11, 'X'),\n    (0xB13, 'V'),\n    (0xB29, 'X'),\n    (0xB2A, 'V'),\n    (0xB31, 'X'),\n    (0xB32, 'V'),\n    (0xB34, 'X'),\n    (0xB35, 'V'),\n    (0xB3A, 'X'),\n    (0xB3C, 'V'),\n    (0xB45, 'X'),\n    (0xB47, 'V'),\n    (0xB49, 'X'),\n    (0xB4B, 'V'),\n    (0xB4E, 'X'),\n    (0xB55, 'V'),\n    (0xB58, 'X'),\n    (0xB5C, 'M', 'ଡ଼'),\n    (0xB5D, 'M', 'ଢ଼'),\n    (0xB5E, 'X'),\n    (0xB5F, 'V'),\n    (0xB64, 'X'),\n    (0xB66, 'V'),\n    (0xB78, 'X'),\n    (0xB82, 'V'),\n    (0xB84, 'X'),\n    (0xB85, 'V'),\n    (0xB8B, 'X'),\n    (0xB8E, 'V'),\n    (0xB91, 'X'),\n    (0xB92, 'V'),\n    (0xB96, 'X'),\n    (0xB99, 'V'),\n    (0xB9B, 'X'),\n    (0xB9C, 'V'),\n    (0xB9D, 'X'),\n    (0xB9E, 'V'),\n    (0xBA0, 'X'),\n    (0xBA3, 'V'),\n    (0xBA5, 'X'),\n    (0xBA8, 'V'),\n    (0xBAB, 'X'),\n    (0xBAE, 'V'),\n    (0xBBA, 'X'),\n    (0xBBE, 'V'),\n    (0xBC3, 'X'),\n    (0xBC6, 'V'),\n    (0xBC9, 'X'),\n    (0xBCA, 'V'),\n    (0xBCE, 'X'),\n    (0xBD0, 'V'),\n    (0xBD1, 'X'),\n    (0xBD7, 'V'),\n    (0xBD8, 'X'),\n    (0xBE6, 'V'),\n    (0xBFB, 'X'),\n    (0xC00, 'V'),\n    (0xC0D, 'X'),\n    (0xC0E, 'V'),\n    (0xC11, 'X'),\n    (0xC12, 'V'),\n    (0xC29, 'X'),\n    (0xC2A, 'V'),\n    ]\n\ndef _seg_12() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xC3A, 'X'),\n    (0xC3C, 'V'),\n    (0xC45, 'X'),\n    (0xC46, 'V'),\n    (0xC49, 'X'),\n    (0xC4A, 'V'),\n    (0xC4E, 'X'),\n    (0xC55, 'V'),\n    (0xC57, 'X'),\n    (0xC58, 'V'),\n    (0xC5B, 'X'),\n    (0xC5D, 'V'),\n    (0xC5E, 'X'),\n    (0xC60, 'V'),\n    (0xC64, 'X'),\n    (0xC66, 'V'),\n    (0xC70, 'X'),\n    (0xC77, 'V'),\n    (0xC8D, 'X'),\n    (0xC8E, 'V'),\n    (0xC91, 'X'),\n    (0xC92, 'V'),\n    (0xCA9, 'X'),\n    (0xCAA, 'V'),\n    (0xCB4, 'X'),\n    (0xCB5, 'V'),\n    (0xCBA, 'X'),\n    (0xCBC, 'V'),\n    (0xCC5, 'X'),\n    (0xCC6, 'V'),\n    (0xCC9, 'X'),\n    (0xCCA, 'V'),\n    (0xCCE, 'X'),\n    (0xCD5, 'V'),\n    (0xCD7, 'X'),\n    (0xCDD, 'V'),\n    (0xCDF, 'X'),\n    (0xCE0, 'V'),\n    (0xCE4, 'X'),\n    (0xCE6, 'V'),\n    (0xCF0, 'X'),\n    (0xCF1, 'V'),\n    (0xCF4, 'X'),\n    (0xD00, 'V'),\n    (0xD0D, 'X'),\n    (0xD0E, 'V'),\n    (0xD11, 'X'),\n    (0xD12, 'V'),\n    (0xD45, 'X'),\n    (0xD46, 'V'),\n    (0xD49, 'X'),\n    (0xD4A, 'V'),\n    (0xD50, 'X'),\n    (0xD54, 'V'),\n    (0xD64, 'X'),\n    (0xD66, 'V'),\n    (0xD80, 'X'),\n    (0xD81, 'V'),\n    (0xD84, 'X'),\n    (0xD85, 'V'),\n    (0xD97, 'X'),\n    (0xD9A, 'V'),\n    (0xDB2, 'X'),\n    (0xDB3, 'V'),\n    (0xDBC, 'X'),\n    (0xDBD, 'V'),\n    (0xDBE, 'X'),\n    (0xDC0, 'V'),\n    (0xDC7, 'X'),\n    (0xDCA, 'V'),\n    (0xDCB, 'X'),\n    (0xDCF, 'V'),\n    (0xDD5, 'X'),\n    (0xDD6, 'V'),\n    (0xDD7, 'X'),\n    (0xDD8, 'V'),\n    (0xDE0, 'X'),\n    (0xDE6, 'V'),\n    (0xDF0, 'X'),\n    (0xDF2, 'V'),\n    (0xDF5, 'X'),\n    (0xE01, 'V'),\n    (0xE33, 'M', 'ํา'),\n    (0xE34, 'V'),\n    (0xE3B, 'X'),\n    (0xE3F, 'V'),\n    (0xE5C, 'X'),\n    (0xE81, 'V'),\n    (0xE83, 'X'),\n    (0xE84, 'V'),\n    (0xE85, 'X'),\n    (0xE86, 'V'),\n    (0xE8B, 'X'),\n    (0xE8C, 'V'),\n    (0xEA4, 'X'),\n    (0xEA5, 'V'),\n    (0xEA6, 'X'),\n    (0xEA7, 'V'),\n    (0xEB3, 'M', 'ໍາ'),\n    (0xEB4, 'V'),\n    ]\n\ndef _seg_13() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xEBE, 'X'),\n    (0xEC0, 'V'),\n    (0xEC5, 'X'),\n    (0xEC6, 'V'),\n    (0xEC7, 'X'),\n    (0xEC8, 'V'),\n    (0xECF, 'X'),\n    (0xED0, 'V'),\n    (0xEDA, 'X'),\n    (0xEDC, 'M', 'ຫນ'),\n    (0xEDD, 'M', 'ຫມ'),\n    (0xEDE, 'V'),\n    (0xEE0, 'X'),\n    (0xF00, 'V'),\n    (0xF0C, 'M', '་'),\n    (0xF0D, 'V'),\n    (0xF43, 'M', 'གྷ'),\n    (0xF44, 'V'),\n    (0xF48, 'X'),\n    (0xF49, 'V'),\n    (0xF4D, 'M', 'ཌྷ'),\n    (0xF4E, 'V'),\n    (0xF52, 'M', 'དྷ'),\n    (0xF53, 'V'),\n    (0xF57, 'M', 'བྷ'),\n    (0xF58, 'V'),\n    (0xF5C, 'M', 'ཛྷ'),\n    (0xF5D, 'V'),\n    (0xF69, 'M', 'ཀྵ'),\n    (0xF6A, 'V'),\n    (0xF6D, 'X'),\n    (0xF71, 'V'),\n    (0xF73, 'M', 'ཱི'),\n    (0xF74, 'V'),\n    (0xF75, 'M', 'ཱུ'),\n    (0xF76, 'M', 'ྲྀ'),\n    (0xF77, 'M', 'ྲཱྀ'),\n    (0xF78, 'M', 'ླྀ'),\n    (0xF79, 'M', 'ླཱྀ'),\n    (0xF7A, 'V'),\n    (0xF81, 'M', 'ཱྀ'),\n    (0xF82, 'V'),\n    (0xF93, 'M', 'ྒྷ'),\n    (0xF94, 'V'),\n    (0xF98, 'X'),\n    (0xF99, 'V'),\n    (0xF9D, 'M', 'ྜྷ'),\n    (0xF9E, 'V'),\n    (0xFA2, 'M', 'ྡྷ'),\n    (0xFA3, 'V'),\n    (0xFA7, 'M', 'ྦྷ'),\n    (0xFA8, 'V'),\n    (0xFAC, 'M', 'ྫྷ'),\n    (0xFAD, 'V'),\n    (0xFB9, 'M', 'ྐྵ'),\n    (0xFBA, 'V'),\n    (0xFBD, 'X'),\n    (0xFBE, 'V'),\n    (0xFCD, 'X'),\n    (0xFCE, 'V'),\n    (0xFDB, 'X'),\n    (0x1000, 'V'),\n    (0x10A0, 'X'),\n    (0x10C7, 'M', 'ⴧ'),\n    (0x10C8, 'X'),\n    (0x10CD, 'M', 'ⴭ'),\n    (0x10CE, 'X'),\n    (0x10D0, 'V'),\n    (0x10FC, 'M', 'ნ'),\n    (0x10FD, 'V'),\n    (0x115F, 'X'),\n    (0x1161, 'V'),\n    (0x1249, 'X'),\n    (0x124A, 'V'),\n    (0x124E, 'X'),\n    (0x1250, 'V'),\n    (0x1257, 'X'),\n    (0x1258, 'V'),\n    (0x1259, 'X'),\n    (0x125A, 'V'),\n    (0x125E, 'X'),\n    (0x1260, 'V'),\n    (0x1289, 'X'),\n    (0x128A, 'V'),\n    (0x128E, 'X'),\n    (0x1290, 'V'),\n    (0x12B1, 'X'),\n    (0x12B2, 'V'),\n    (0x12B6, 'X'),\n    (0x12B8, 'V'),\n    (0x12BF, 'X'),\n    (0x12C0, 'V'),\n    (0x12C1, 'X'),\n    (0x12C2, 'V'),\n    (0x12C6, 'X'),\n    (0x12C8, 'V'),\n    (0x12D7, 'X'),\n    (0x12D8, 'V'),\n    (0x1311, 'X'),\n    (0x1312, 'V'),\n    ]\n\ndef _seg_14() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1316, 'X'),\n    (0x1318, 'V'),\n    (0x135B, 'X'),\n    (0x135D, 'V'),\n    (0x137D, 'X'),\n    (0x1380, 'V'),\n    (0x139A, 'X'),\n    (0x13A0, 'V'),\n    (0x13F6, 'X'),\n    (0x13F8, 'M', 'Ᏸ'),\n    (0x13F9, 'M', 'Ᏹ'),\n    (0x13FA, 'M', 'Ᏺ'),\n    (0x13FB, 'M', 'Ᏻ'),\n    (0x13FC, 'M', 'Ᏼ'),\n    (0x13FD, 'M', 'Ᏽ'),\n    (0x13FE, 'X'),\n    (0x1400, 'V'),\n    (0x1680, 'X'),\n    (0x1681, 'V'),\n    (0x169D, 'X'),\n    (0x16A0, 'V'),\n    (0x16F9, 'X'),\n    (0x1700, 'V'),\n    (0x1716, 'X'),\n    (0x171F, 'V'),\n    (0x1737, 'X'),\n    (0x1740, 'V'),\n    (0x1754, 'X'),\n    (0x1760, 'V'),\n    (0x176D, 'X'),\n    (0x176E, 'V'),\n    (0x1771, 'X'),\n    (0x1772, 'V'),\n    (0x1774, 'X'),\n    (0x1780, 'V'),\n    (0x17B4, 'X'),\n    (0x17B6, 'V'),\n    (0x17DE, 'X'),\n    (0x17E0, 'V'),\n    (0x17EA, 'X'),\n    (0x17F0, 'V'),\n    (0x17FA, 'X'),\n    (0x1800, 'V'),\n    (0x1806, 'X'),\n    (0x1807, 'V'),\n    (0x180B, 'I'),\n    (0x180E, 'X'),\n    (0x180F, 'I'),\n    (0x1810, 'V'),\n    (0x181A, 'X'),\n    (0x1820, 'V'),\n    (0x1879, 'X'),\n    (0x1880, 'V'),\n    (0x18AB, 'X'),\n    (0x18B0, 'V'),\n    (0x18F6, 'X'),\n    (0x1900, 'V'),\n    (0x191F, 'X'),\n    (0x1920, 'V'),\n    (0x192C, 'X'),\n    (0x1930, 'V'),\n    (0x193C, 'X'),\n    (0x1940, 'V'),\n    (0x1941, 'X'),\n    (0x1944, 'V'),\n    (0x196E, 'X'),\n    (0x1970, 'V'),\n    (0x1975, 'X'),\n    (0x1980, 'V'),\n    (0x19AC, 'X'),\n    (0x19B0, 'V'),\n    (0x19CA, 'X'),\n    (0x19D0, 'V'),\n    (0x19DB, 'X'),\n    (0x19DE, 'V'),\n    (0x1A1C, 'X'),\n    (0x1A1E, 'V'),\n    (0x1A5F, 'X'),\n    (0x1A60, 'V'),\n    (0x1A7D, 'X'),\n    (0x1A7F, 'V'),\n    (0x1A8A, 'X'),\n    (0x1A90, 'V'),\n    (0x1A9A, 'X'),\n    (0x1AA0, 'V'),\n    (0x1AAE, 'X'),\n    (0x1AB0, 'V'),\n    (0x1ACF, 'X'),\n    (0x1B00, 'V'),\n    (0x1B4D, 'X'),\n    (0x1B50, 'V'),\n    (0x1B7F, 'X'),\n    (0x1B80, 'V'),\n    (0x1BF4, 'X'),\n    (0x1BFC, 'V'),\n    (0x1C38, 'X'),\n    (0x1C3B, 'V'),\n    (0x1C4A, 'X'),\n    (0x1C4D, 'V'),\n    (0x1C80, 'M', 'в'),\n    ]\n\ndef _seg_15() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1C81, 'M', 'д'),\n    (0x1C82, 'M', 'о'),\n    (0x1C83, 'M', 'с'),\n    (0x1C84, 'M', 'т'),\n    (0x1C86, 'M', 'ъ'),\n    (0x1C87, 'M', 'ѣ'),\n    (0x1C88, 'M', 'ꙋ'),\n    (0x1C89, 'X'),\n    (0x1C90, 'M', 'ა'),\n    (0x1C91, 'M', 'ბ'),\n    (0x1C92, 'M', 'გ'),\n    (0x1C93, 'M', 'დ'),\n    (0x1C94, 'M', 'ე'),\n    (0x1C95, 'M', 'ვ'),\n    (0x1C96, 'M', 'ზ'),\n    (0x1C97, 'M', 'თ'),\n    (0x1C98, 'M', 'ი'),\n    (0x1C99, 'M', 'კ'),\n    (0x1C9A, 'M', 'ლ'),\n    (0x1C9B, 'M', 'მ'),\n    (0x1C9C, 'M', 'ნ'),\n    (0x1C9D, 'M', 'ო'),\n    (0x1C9E, 'M', 'პ'),\n    (0x1C9F, 'M', 'ჟ'),\n    (0x1CA0, 'M', 'რ'),\n    (0x1CA1, 'M', 'ს'),\n    (0x1CA2, 'M', 'ტ'),\n    (0x1CA3, 'M', 'უ'),\n    (0x1CA4, 'M', 'ფ'),\n    (0x1CA5, 'M', 'ქ'),\n    (0x1CA6, 'M', 'ღ'),\n    (0x1CA7, 'M', 'ყ'),\n    (0x1CA8, 'M', 'შ'),\n    (0x1CA9, 'M', 'ჩ'),\n    (0x1CAA, 'M', 'ც'),\n    (0x1CAB, 'M', 'ძ'),\n    (0x1CAC, 'M', 'წ'),\n    (0x1CAD, 'M', 'ჭ'),\n    (0x1CAE, 'M', 'ხ'),\n    (0x1CAF, 'M', 'ჯ'),\n    (0x1CB0, 'M', 'ჰ'),\n    (0x1CB1, 'M', 'ჱ'),\n    (0x1CB2, 'M', 'ჲ'),\n    (0x1CB3, 'M', 'ჳ'),\n    (0x1CB4, 'M', 'ჴ'),\n    (0x1CB5, 'M', 'ჵ'),\n    (0x1CB6, 'M', 'ჶ'),\n    (0x1CB7, 'M', 'ჷ'),\n    (0x1CB8, 'M', 'ჸ'),\n    (0x1CB9, 'M', 'ჹ'),\n    (0x1CBA, 'M', 'ჺ'),\n    (0x1CBB, 'X'),\n    (0x1CBD, 'M', 'ჽ'),\n    (0x1CBE, 'M', 'ჾ'),\n    (0x1CBF, 'M', 'ჿ'),\n    (0x1CC0, 'V'),\n    (0x1CC8, 'X'),\n    (0x1CD0, 'V'),\n    (0x1CFB, 'X'),\n    (0x1D00, 'V'),\n    (0x1D2C, 'M', 'a'),\n    (0x1D2D, 'M', 'æ'),\n    (0x1D2E, 'M', 'b'),\n    (0x1D2F, 'V'),\n    (0x1D30, 'M', 'd'),\n    (0x1D31, 'M', 'e'),\n    (0x1D32, 'M', 'ǝ'),\n    (0x1D33, 'M', 'g'),\n    (0x1D34, 'M', 'h'),\n    (0x1D35, 'M', 'i'),\n    (0x1D36, 'M', 'j'),\n    (0x1D37, 'M', 'k'),\n    (0x1D38, 'M', 'l'),\n    (0x1D39, 'M', 'm'),\n    (0x1D3A, 'M', 'n'),\n    (0x1D3B, 'V'),\n    (0x1D3C, 'M', 'o'),\n    (0x1D3D, 'M', 'ȣ'),\n    (0x1D3E, 'M', 'p'),\n    (0x1D3F, 'M', 'r'),\n    (0x1D40, 'M', 't'),\n    (0x1D41, 'M', 'u'),\n    (0x1D42, 'M', 'w'),\n    (0x1D43, 'M', 'a'),\n    (0x1D44, 'M', 'ɐ'),\n    (0x1D45, 'M', 'ɑ'),\n    (0x1D46, 'M', 'ᴂ'),\n    (0x1D47, 'M', 'b'),\n    (0x1D48, 'M', 'd'),\n    (0x1D49, 'M', 'e'),\n    (0x1D4A, 'M', 'ə'),\n    (0x1D4B, 'M', 'ɛ'),\n    (0x1D4C, 'M', 'ɜ'),\n    (0x1D4D, 'M', 'g'),\n    (0x1D4E, 'V'),\n    (0x1D4F, 'M', 'k'),\n    (0x1D50, 'M', 'm'),\n    (0x1D51, 'M', 'ŋ'),\n    (0x1D52, 'M', 'o'),\n    (0x1D53, 'M', 'ɔ'),\n    ]\n\ndef _seg_16() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1D54, 'M', 'ᴖ'),\n    (0x1D55, 'M', 'ᴗ'),\n    (0x1D56, 'M', 'p'),\n    (0x1D57, 'M', 't'),\n    (0x1D58, 'M', 'u'),\n    (0x1D59, 'M', 'ᴝ'),\n    (0x1D5A, 'M', 'ɯ'),\n    (0x1D5B, 'M', 'v'),\n    (0x1D5C, 'M', 'ᴥ'),\n    (0x1D5D, 'M', 'β'),\n    (0x1D5E, 'M', 'γ'),\n    (0x1D5F, 'M', 'δ'),\n    (0x1D60, 'M', 'φ'),\n    (0x1D61, 'M', 'χ'),\n    (0x1D62, 'M', 'i'),\n    (0x1D63, 'M', 'r'),\n    (0x1D64, 'M', 'u'),\n    (0x1D65, 'M', 'v'),\n    (0x1D66, 'M', 'β'),\n    (0x1D67, 'M', 'γ'),\n    (0x1D68, 'M', 'ρ'),\n    (0x1D69, 'M', 'φ'),\n    (0x1D6A, 'M', 'χ'),\n    (0x1D6B, 'V'),\n    (0x1D78, 'M', 'н'),\n    (0x1D79, 'V'),\n    (0x1D9B, 'M', 'ɒ'),\n    (0x1D9C, 'M', 'c'),\n    (0x1D9D, 'M', 'ɕ'),\n    (0x1D9E, 'M', 'ð'),\n    (0x1D9F, 'M', 'ɜ'),\n    (0x1DA0, 'M', 'f'),\n    (0x1DA1, 'M', 'ɟ'),\n    (0x1DA2, 'M', 'ɡ'),\n    (0x1DA3, 'M', 'ɥ'),\n    (0x1DA4, 'M', 'ɨ'),\n    (0x1DA5, 'M', 'ɩ'),\n    (0x1DA6, 'M', 'ɪ'),\n    (0x1DA7, 'M', 'ᵻ'),\n    (0x1DA8, 'M', 'ʝ'),\n    (0x1DA9, 'M', 'ɭ'),\n    (0x1DAA, 'M', 'ᶅ'),\n    (0x1DAB, 'M', 'ʟ'),\n    (0x1DAC, 'M', 'ɱ'),\n    (0x1DAD, 'M', 'ɰ'),\n    (0x1DAE, 'M', 'ɲ'),\n    (0x1DAF, 'M', 'ɳ'),\n    (0x1DB0, 'M', 'ɴ'),\n    (0x1DB1, 'M', 'ɵ'),\n    (0x1DB2, 'M', 'ɸ'),\n    (0x1DB3, 'M', 'ʂ'),\n    (0x1DB4, 'M', 'ʃ'),\n    (0x1DB5, 'M', 'ƫ'),\n    (0x1DB6, 'M', 'ʉ'),\n    (0x1DB7, 'M', 'ʊ'),\n    (0x1DB8, 'M', 'ᴜ'),\n    (0x1DB9, 'M', 'ʋ'),\n    (0x1DBA, 'M', 'ʌ'),\n    (0x1DBB, 'M', 'z'),\n    (0x1DBC, 'M', 'ʐ'),\n    (0x1DBD, 'M', 'ʑ'),\n    (0x1DBE, 'M', 'ʒ'),\n    (0x1DBF, 'M', 'θ'),\n    (0x1DC0, 'V'),\n    (0x1E00, 'M', 'ḁ'),\n    (0x1E01, 'V'),\n    (0x1E02, 'M', 'ḃ'),\n    (0x1E03, 'V'),\n    (0x1E04, 'M', 'ḅ'),\n    (0x1E05, 'V'),\n    (0x1E06, 'M', 'ḇ'),\n    (0x1E07, 'V'),\n    (0x1E08, 'M', 'ḉ'),\n    (0x1E09, 'V'),\n    (0x1E0A, 'M', 'ḋ'),\n    (0x1E0B, 'V'),\n    (0x1E0C, 'M', 'ḍ'),\n    (0x1E0D, 'V'),\n    (0x1E0E, 'M', 'ḏ'),\n    (0x1E0F, 'V'),\n    (0x1E10, 'M', 'ḑ'),\n    (0x1E11, 'V'),\n    (0x1E12, 'M', 'ḓ'),\n    (0x1E13, 'V'),\n    (0x1E14, 'M', 'ḕ'),\n    (0x1E15, 'V'),\n    (0x1E16, 'M', 'ḗ'),\n    (0x1E17, 'V'),\n    (0x1E18, 'M', 'ḙ'),\n    (0x1E19, 'V'),\n    (0x1E1A, 'M', 'ḛ'),\n    (0x1E1B, 'V'),\n    (0x1E1C, 'M', 'ḝ'),\n    (0x1E1D, 'V'),\n    (0x1E1E, 'M', 'ḟ'),\n    (0x1E1F, 'V'),\n    (0x1E20, 'M', 'ḡ'),\n    (0x1E21, 'V'),\n    (0x1E22, 'M', 'ḣ'),\n    (0x1E23, 'V'),\n    ]\n\ndef _seg_17() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1E24, 'M', 'ḥ'),\n    (0x1E25, 'V'),\n    (0x1E26, 'M', 'ḧ'),\n    (0x1E27, 'V'),\n    (0x1E28, 'M', 'ḩ'),\n    (0x1E29, 'V'),\n    (0x1E2A, 'M', 'ḫ'),\n    (0x1E2B, 'V'),\n    (0x1E2C, 'M', 'ḭ'),\n    (0x1E2D, 'V'),\n    (0x1E2E, 'M', 'ḯ'),\n    (0x1E2F, 'V'),\n    (0x1E30, 'M', 'ḱ'),\n    (0x1E31, 'V'),\n    (0x1E32, 'M', 'ḳ'),\n    (0x1E33, 'V'),\n    (0x1E34, 'M', 'ḵ'),\n    (0x1E35, 'V'),\n    (0x1E36, 'M', 'ḷ'),\n    (0x1E37, 'V'),\n    (0x1E38, 'M', 'ḹ'),\n    (0x1E39, 'V'),\n    (0x1E3A, 'M', 'ḻ'),\n    (0x1E3B, 'V'),\n    (0x1E3C, 'M', 'ḽ'),\n    (0x1E3D, 'V'),\n    (0x1E3E, 'M', 'ḿ'),\n    (0x1E3F, 'V'),\n    (0x1E40, 'M', 'ṁ'),\n    (0x1E41, 'V'),\n    (0x1E42, 'M', 'ṃ'),\n    (0x1E43, 'V'),\n    (0x1E44, 'M', 'ṅ'),\n    (0x1E45, 'V'),\n    (0x1E46, 'M', 'ṇ'),\n    (0x1E47, 'V'),\n    (0x1E48, 'M', 'ṉ'),\n    (0x1E49, 'V'),\n    (0x1E4A, 'M', 'ṋ'),\n    (0x1E4B, 'V'),\n    (0x1E4C, 'M', 'ṍ'),\n    (0x1E4D, 'V'),\n    (0x1E4E, 'M', 'ṏ'),\n    (0x1E4F, 'V'),\n    (0x1E50, 'M', 'ṑ'),\n    (0x1E51, 'V'),\n    (0x1E52, 'M', 'ṓ'),\n    (0x1E53, 'V'),\n    (0x1E54, 'M', 'ṕ'),\n    (0x1E55, 'V'),\n    (0x1E56, 'M', 'ṗ'),\n    (0x1E57, 'V'),\n    (0x1E58, 'M', 'ṙ'),\n    (0x1E59, 'V'),\n    (0x1E5A, 'M', 'ṛ'),\n    (0x1E5B, 'V'),\n    (0x1E5C, 'M', 'ṝ'),\n    (0x1E5D, 'V'),\n    (0x1E5E, 'M', 'ṟ'),\n    (0x1E5F, 'V'),\n    (0x1E60, 'M', 'ṡ'),\n    (0x1E61, 'V'),\n    (0x1E62, 'M', 'ṣ'),\n    (0x1E63, 'V'),\n    (0x1E64, 'M', 'ṥ'),\n    (0x1E65, 'V'),\n    (0x1E66, 'M', 'ṧ'),\n    (0x1E67, 'V'),\n    (0x1E68, 'M', 'ṩ'),\n    (0x1E69, 'V'),\n    (0x1E6A, 'M', 'ṫ'),\n    (0x1E6B, 'V'),\n    (0x1E6C, 'M', 'ṭ'),\n    (0x1E6D, 'V'),\n    (0x1E6E, 'M', 'ṯ'),\n    (0x1E6F, 'V'),\n    (0x1E70, 'M', 'ṱ'),\n    (0x1E71, 'V'),\n    (0x1E72, 'M', 'ṳ'),\n    (0x1E73, 'V'),\n    (0x1E74, 'M', 'ṵ'),\n    (0x1E75, 'V'),\n    (0x1E76, 'M', 'ṷ'),\n    (0x1E77, 'V'),\n    (0x1E78, 'M', 'ṹ'),\n    (0x1E79, 'V'),\n    (0x1E7A, 'M', 'ṻ'),\n    (0x1E7B, 'V'),\n    (0x1E7C, 'M', 'ṽ'),\n    (0x1E7D, 'V'),\n    (0x1E7E, 'M', 'ṿ'),\n    (0x1E7F, 'V'),\n    (0x1E80, 'M', 'ẁ'),\n    (0x1E81, 'V'),\n    (0x1E82, 'M', 'ẃ'),\n    (0x1E83, 'V'),\n    (0x1E84, 'M', 'ẅ'),\n    (0x1E85, 'V'),\n    (0x1E86, 'M', 'ẇ'),\n    (0x1E87, 'V'),\n    ]\n\ndef _seg_18() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1E88, 'M', 'ẉ'),\n    (0x1E89, 'V'),\n    (0x1E8A, 'M', 'ẋ'),\n    (0x1E8B, 'V'),\n    (0x1E8C, 'M', 'ẍ'),\n    (0x1E8D, 'V'),\n    (0x1E8E, 'M', 'ẏ'),\n    (0x1E8F, 'V'),\n    (0x1E90, 'M', 'ẑ'),\n    (0x1E91, 'V'),\n    (0x1E92, 'M', 'ẓ'),\n    (0x1E93, 'V'),\n    (0x1E94, 'M', 'ẕ'),\n    (0x1E95, 'V'),\n    (0x1E9A, 'M', 'aʾ'),\n    (0x1E9B, 'M', 'ṡ'),\n    (0x1E9C, 'V'),\n    (0x1E9E, 'M', 'ss'),\n    (0x1E9F, 'V'),\n    (0x1EA0, 'M', 'ạ'),\n    (0x1EA1, 'V'),\n    (0x1EA2, 'M', 'ả'),\n    (0x1EA3, 'V'),\n    (0x1EA4, 'M', 'ấ'),\n    (0x1EA5, 'V'),\n    (0x1EA6, 'M', 'ầ'),\n    (0x1EA7, 'V'),\n    (0x1EA8, 'M', 'ẩ'),\n    (0x1EA9, 'V'),\n    (0x1EAA, 'M', 'ẫ'),\n    (0x1EAB, 'V'),\n    (0x1EAC, 'M', 'ậ'),\n    (0x1EAD, 'V'),\n    (0x1EAE, 'M', 'ắ'),\n    (0x1EAF, 'V'),\n    (0x1EB0, 'M', 'ằ'),\n    (0x1EB1, 'V'),\n    (0x1EB2, 'M', 'ẳ'),\n    (0x1EB3, 'V'),\n    (0x1EB4, 'M', 'ẵ'),\n    (0x1EB5, 'V'),\n    (0x1EB6, 'M', 'ặ'),\n    (0x1EB7, 'V'),\n    (0x1EB8, 'M', 'ẹ'),\n    (0x1EB9, 'V'),\n    (0x1EBA, 'M', 'ẻ'),\n    (0x1EBB, 'V'),\n    (0x1EBC, 'M', 'ẽ'),\n    (0x1EBD, 'V'),\n    (0x1EBE, 'M', 'ế'),\n    (0x1EBF, 'V'),\n    (0x1EC0, 'M', 'ề'),\n    (0x1EC1, 'V'),\n    (0x1EC2, 'M', 'ể'),\n    (0x1EC3, 'V'),\n    (0x1EC4, 'M', 'ễ'),\n    (0x1EC5, 'V'),\n    (0x1EC6, 'M', 'ệ'),\n    (0x1EC7, 'V'),\n    (0x1EC8, 'M', 'ỉ'),\n    (0x1EC9, 'V'),\n    (0x1ECA, 'M', 'ị'),\n    (0x1ECB, 'V'),\n    (0x1ECC, 'M', 'ọ'),\n    (0x1ECD, 'V'),\n    (0x1ECE, 'M', 'ỏ'),\n    (0x1ECF, 'V'),\n    (0x1ED0, 'M', 'ố'),\n    (0x1ED1, 'V'),\n    (0x1ED2, 'M', 'ồ'),\n    (0x1ED3, 'V'),\n    (0x1ED4, 'M', 'ổ'),\n    (0x1ED5, 'V'),\n    (0x1ED6, 'M', 'ỗ'),\n    (0x1ED7, 'V'),\n    (0x1ED8, 'M', 'ộ'),\n    (0x1ED9, 'V'),\n    (0x1EDA, 'M', 'ớ'),\n    (0x1EDB, 'V'),\n    (0x1EDC, 'M', 'ờ'),\n    (0x1EDD, 'V'),\n    (0x1EDE, 'M', 'ở'),\n    (0x1EDF, 'V'),\n    (0x1EE0, 'M', 'ỡ'),\n    (0x1EE1, 'V'),\n    (0x1EE2, 'M', 'ợ'),\n    (0x1EE3, 'V'),\n    (0x1EE4, 'M', 'ụ'),\n    (0x1EE5, 'V'),\n    (0x1EE6, 'M', 'ủ'),\n    (0x1EE7, 'V'),\n    (0x1EE8, 'M', 'ứ'),\n    (0x1EE9, 'V'),\n    (0x1EEA, 'M', 'ừ'),\n    (0x1EEB, 'V'),\n    (0x1EEC, 'M', 'ử'),\n    (0x1EED, 'V'),\n    (0x1EEE, 'M', 'ữ'),\n    (0x1EEF, 'V'),\n    (0x1EF0, 'M', 'ự'),\n    ]\n\ndef _seg_19() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1EF1, 'V'),\n    (0x1EF2, 'M', 'ỳ'),\n    (0x1EF3, 'V'),\n    (0x1EF4, 'M', 'ỵ'),\n    (0x1EF5, 'V'),\n    (0x1EF6, 'M', 'ỷ'),\n    (0x1EF7, 'V'),\n    (0x1EF8, 'M', 'ỹ'),\n    (0x1EF9, 'V'),\n    (0x1EFA, 'M', 'ỻ'),\n    (0x1EFB, 'V'),\n    (0x1EFC, 'M', 'ỽ'),\n    (0x1EFD, 'V'),\n    (0x1EFE, 'M', 'ỿ'),\n    (0x1EFF, 'V'),\n    (0x1F08, 'M', 'ἀ'),\n    (0x1F09, 'M', 'ἁ'),\n    (0x1F0A, 'M', 'ἂ'),\n    (0x1F0B, 'M', 'ἃ'),\n    (0x1F0C, 'M', 'ἄ'),\n    (0x1F0D, 'M', 'ἅ'),\n    (0x1F0E, 'M', 'ἆ'),\n    (0x1F0F, 'M', 'ἇ'),\n    (0x1F10, 'V'),\n    (0x1F16, 'X'),\n    (0x1F18, 'M', 'ἐ'),\n    (0x1F19, 'M', 'ἑ'),\n    (0x1F1A, 'M', 'ἒ'),\n    (0x1F1B, 'M', 'ἓ'),\n    (0x1F1C, 'M', 'ἔ'),\n    (0x1F1D, 'M', 'ἕ'),\n    (0x1F1E, 'X'),\n    (0x1F20, 'V'),\n    (0x1F28, 'M', 'ἠ'),\n    (0x1F29, 'M', 'ἡ'),\n    (0x1F2A, 'M', 'ἢ'),\n    (0x1F2B, 'M', 'ἣ'),\n    (0x1F2C, 'M', 'ἤ'),\n    (0x1F2D, 'M', 'ἥ'),\n    (0x1F2E, 'M', 'ἦ'),\n    (0x1F2F, 'M', 'ἧ'),\n    (0x1F30, 'V'),\n    (0x1F38, 'M', 'ἰ'),\n    (0x1F39, 'M', 'ἱ'),\n    (0x1F3A, 'M', 'ἲ'),\n    (0x1F3B, 'M', 'ἳ'),\n    (0x1F3C, 'M', 'ἴ'),\n    (0x1F3D, 'M', 'ἵ'),\n    (0x1F3E, 'M', 'ἶ'),\n    (0x1F3F, 'M', 'ἷ'),\n    (0x1F40, 'V'),\n    (0x1F46, 'X'),\n    (0x1F48, 'M', 'ὀ'),\n    (0x1F49, 'M', 'ὁ'),\n    (0x1F4A, 'M', 'ὂ'),\n    (0x1F4B, 'M', 'ὃ'),\n    (0x1F4C, 'M', 'ὄ'),\n    (0x1F4D, 'M', 'ὅ'),\n    (0x1F4E, 'X'),\n    (0x1F50, 'V'),\n    (0x1F58, 'X'),\n    (0x1F59, 'M', 'ὑ'),\n    (0x1F5A, 'X'),\n    (0x1F5B, 'M', 'ὓ'),\n    (0x1F5C, 'X'),\n    (0x1F5D, 'M', 'ὕ'),\n    (0x1F5E, 'X'),\n    (0x1F5F, 'M', 'ὗ'),\n    (0x1F60, 'V'),\n    (0x1F68, 'M', 'ὠ'),\n    (0x1F69, 'M', 'ὡ'),\n    (0x1F6A, 'M', 'ὢ'),\n    (0x1F6B, 'M', 'ὣ'),\n    (0x1F6C, 'M', 'ὤ'),\n    (0x1F6D, 'M', 'ὥ'),\n    (0x1F6E, 'M', 'ὦ'),\n    (0x1F6F, 'M', 'ὧ'),\n    (0x1F70, 'V'),\n    (0x1F71, 'M', 'ά'),\n    (0x1F72, 'V'),\n    (0x1F73, 'M', 'έ'),\n    (0x1F74, 'V'),\n    (0x1F75, 'M', 'ή'),\n    (0x1F76, 'V'),\n    (0x1F77, 'M', 'ί'),\n    (0x1F78, 'V'),\n    (0x1F79, 'M', 'ό'),\n    (0x1F7A, 'V'),\n    (0x1F7B, 'M', 'ύ'),\n    (0x1F7C, 'V'),\n    (0x1F7D, 'M', 'ώ'),\n    (0x1F7E, 'X'),\n    (0x1F80, 'M', 'ἀι'),\n    (0x1F81, 'M', 'ἁι'),\n    (0x1F82, 'M', 'ἂι'),\n    (0x1F83, 'M', 'ἃι'),\n    (0x1F84, 'M', 'ἄι'),\n    (0x1F85, 'M', 'ἅι'),\n    (0x1F86, 'M', 'ἆι'),\n    (0x1F87, 'M', 'ἇι'),\n    ]\n\ndef _seg_20() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1F88, 'M', 'ἀι'),\n    (0x1F89, 'M', 'ἁι'),\n    (0x1F8A, 'M', 'ἂι'),\n    (0x1F8B, 'M', 'ἃι'),\n    (0x1F8C, 'M', 'ἄι'),\n    (0x1F8D, 'M', 'ἅι'),\n    (0x1F8E, 'M', 'ἆι'),\n    (0x1F8F, 'M', 'ἇι'),\n    (0x1F90, 'M', 'ἠι'),\n    (0x1F91, 'M', 'ἡι'),\n    (0x1F92, 'M', 'ἢι'),\n    (0x1F93, 'M', 'ἣι'),\n    (0x1F94, 'M', 'ἤι'),\n    (0x1F95, 'M', 'ἥι'),\n    (0x1F96, 'M', 'ἦι'),\n    (0x1F97, 'M', 'ἧι'),\n    (0x1F98, 'M', 'ἠι'),\n    (0x1F99, 'M', 'ἡι'),\n    (0x1F9A, 'M', 'ἢι'),\n    (0x1F9B, 'M', 'ἣι'),\n    (0x1F9C, 'M', 'ἤι'),\n    (0x1F9D, 'M', 'ἥι'),\n    (0x1F9E, 'M', 'ἦι'),\n    (0x1F9F, 'M', 'ἧι'),\n    (0x1FA0, 'M', 'ὠι'),\n    (0x1FA1, 'M', 'ὡι'),\n    (0x1FA2, 'M', 'ὢι'),\n    (0x1FA3, 'M', 'ὣι'),\n    (0x1FA4, 'M', 'ὤι'),\n    (0x1FA5, 'M', 'ὥι'),\n    (0x1FA6, 'M', 'ὦι'),\n    (0x1FA7, 'M', 'ὧι'),\n    (0x1FA8, 'M', 'ὠι'),\n    (0x1FA9, 'M', 'ὡι'),\n    (0x1FAA, 'M', 'ὢι'),\n    (0x1FAB, 'M', 'ὣι'),\n    (0x1FAC, 'M', 'ὤι'),\n    (0x1FAD, 'M', 'ὥι'),\n    (0x1FAE, 'M', 'ὦι'),\n    (0x1FAF, 'M', 'ὧι'),\n    (0x1FB0, 'V'),\n    (0x1FB2, 'M', 'ὰι'),\n    (0x1FB3, 'M', 'αι'),\n    (0x1FB4, 'M', 'άι'),\n    (0x1FB5, 'X'),\n    (0x1FB6, 'V'),\n    (0x1FB7, 'M', 'ᾶι'),\n    (0x1FB8, 'M', 'ᾰ'),\n    (0x1FB9, 'M', 'ᾱ'),\n    (0x1FBA, 'M', 'ὰ'),\n    (0x1FBB, 'M', 'ά'),\n    (0x1FBC, 'M', 'αι'),\n    (0x1FBD, '3', ' ̓'),\n    (0x1FBE, 'M', 'ι'),\n    (0x1FBF, '3', ' ̓'),\n    (0x1FC0, '3', ' ͂'),\n    (0x1FC1, '3', ' ̈͂'),\n    (0x1FC2, 'M', 'ὴι'),\n    (0x1FC3, 'M', 'ηι'),\n    (0x1FC4, 'M', 'ήι'),\n    (0x1FC5, 'X'),\n    (0x1FC6, 'V'),\n    (0x1FC7, 'M', 'ῆι'),\n    (0x1FC8, 'M', 'ὲ'),\n    (0x1FC9, 'M', 'έ'),\n    (0x1FCA, 'M', 'ὴ'),\n    (0x1FCB, 'M', 'ή'),\n    (0x1FCC, 'M', 'ηι'),\n    (0x1FCD, '3', ' ̓̀'),\n    (0x1FCE, '3', ' ̓́'),\n    (0x1FCF, '3', ' ̓͂'),\n    (0x1FD0, 'V'),\n    (0x1FD3, 'M', 'ΐ'),\n    (0x1FD4, 'X'),\n    (0x1FD6, 'V'),\n    (0x1FD8, 'M', 'ῐ'),\n    (0x1FD9, 'M', 'ῑ'),\n    (0x1FDA, 'M', 'ὶ'),\n    (0x1FDB, 'M', 'ί'),\n    (0x1FDC, 'X'),\n    (0x1FDD, '3', ' ̔̀'),\n    (0x1FDE, '3', ' ̔́'),\n    (0x1FDF, '3', ' ̔͂'),\n    (0x1FE0, 'V'),\n    (0x1FE3, 'M', 'ΰ'),\n    (0x1FE4, 'V'),\n    (0x1FE8, 'M', 'ῠ'),\n    (0x1FE9, 'M', 'ῡ'),\n    (0x1FEA, 'M', 'ὺ'),\n    (0x1FEB, 'M', 'ύ'),\n    (0x1FEC, 'M', 'ῥ'),\n    (0x1FED, '3', ' ̈̀'),\n    (0x1FEE, '3', ' ̈́'),\n    (0x1FEF, '3', '`'),\n    (0x1FF0, 'X'),\n    (0x1FF2, 'M', 'ὼι'),\n    (0x1FF3, 'M', 'ωι'),\n    (0x1FF4, 'M', 'ώι'),\n    (0x1FF5, 'X'),\n    (0x1FF6, 'V'),\n    ]\n\ndef _seg_21() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1FF7, 'M', 'ῶι'),\n    (0x1FF8, 'M', 'ὸ'),\n    (0x1FF9, 'M', 'ό'),\n    (0x1FFA, 'M', 'ὼ'),\n    (0x1FFB, 'M', 'ώ'),\n    (0x1FFC, 'M', 'ωι'),\n    (0x1FFD, '3', ' ́'),\n    (0x1FFE, '3', ' ̔'),\n    (0x1FFF, 'X'),\n    (0x2000, '3', ' '),\n    (0x200B, 'I'),\n    (0x200C, 'D', ''),\n    (0x200E, 'X'),\n    (0x2010, 'V'),\n    (0x2011, 'M', '‐'),\n    (0x2012, 'V'),\n    (0x2017, '3', ' ̳'),\n    (0x2018, 'V'),\n    (0x2024, 'X'),\n    (0x2027, 'V'),\n    (0x2028, 'X'),\n    (0x202F, '3', ' '),\n    (0x2030, 'V'),\n    (0x2033, 'M', '′′'),\n    (0x2034, 'M', '′′′'),\n    (0x2035, 'V'),\n    (0x2036, 'M', '‵‵'),\n    (0x2037, 'M', '‵‵‵'),\n    (0x2038, 'V'),\n    (0x203C, '3', '!!'),\n    (0x203D, 'V'),\n    (0x203E, '3', ' ̅'),\n    (0x203F, 'V'),\n    (0x2047, '3', '??'),\n    (0x2048, '3', '?!'),\n    (0x2049, '3', '!?'),\n    (0x204A, 'V'),\n    (0x2057, 'M', '′′′′'),\n    (0x2058, 'V'),\n    (0x205F, '3', ' '),\n    (0x2060, 'I'),\n    (0x2061, 'X'),\n    (0x2064, 'I'),\n    (0x2065, 'X'),\n    (0x2070, 'M', '0'),\n    (0x2071, 'M', 'i'),\n    (0x2072, 'X'),\n    (0x2074, 'M', '4'),\n    (0x2075, 'M', '5'),\n    (0x2076, 'M', '6'),\n    (0x2077, 'M', '7'),\n    (0x2078, 'M', '8'),\n    (0x2079, 'M', '9'),\n    (0x207A, '3', '+'),\n    (0x207B, 'M', '−'),\n    (0x207C, '3', '='),\n    (0x207D, '3', '('),\n    (0x207E, '3', ')'),\n    (0x207F, 'M', 'n'),\n    (0x2080, 'M', '0'),\n    (0x2081, 'M', '1'),\n    (0x2082, 'M', '2'),\n    (0x2083, 'M', '3'),\n    (0x2084, 'M', '4'),\n    (0x2085, 'M', '5'),\n    (0x2086, 'M', '6'),\n    (0x2087, 'M', '7'),\n    (0x2088, 'M', '8'),\n    (0x2089, 'M', '9'),\n    (0x208A, '3', '+'),\n    (0x208B, 'M', '−'),\n    (0x208C, '3', '='),\n    (0x208D, '3', '('),\n    (0x208E, '3', ')'),\n    (0x208F, 'X'),\n    (0x2090, 'M', 'a'),\n    (0x2091, 'M', 'e'),\n    (0x2092, 'M', 'o'),\n    (0x2093, 'M', 'x'),\n    (0x2094, 'M', 'ə'),\n    (0x2095, 'M', 'h'),\n    (0x2096, 'M', 'k'),\n    (0x2097, 'M', 'l'),\n    (0x2098, 'M', 'm'),\n    (0x2099, 'M', 'n'),\n    (0x209A, 'M', 'p'),\n    (0x209B, 'M', 's'),\n    (0x209C, 'M', 't'),\n    (0x209D, 'X'),\n    (0x20A0, 'V'),\n    (0x20A8, 'M', 'rs'),\n    (0x20A9, 'V'),\n    (0x20C1, 'X'),\n    (0x20D0, 'V'),\n    (0x20F1, 'X'),\n    (0x2100, '3', 'a/c'),\n    (0x2101, '3', 'a/s'),\n    (0x2102, 'M', 'c'),\n    (0x2103, 'M', '°c'),\n    (0x2104, 'V'),\n    ]\n\ndef _seg_22() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x2105, '3', 'c/o'),\n    (0x2106, '3', 'c/u'),\n    (0x2107, 'M', 'ɛ'),\n    (0x2108, 'V'),\n    (0x2109, 'M', '°f'),\n    (0x210A, 'M', 'g'),\n    (0x210B, 'M', 'h'),\n    (0x210F, 'M', 'ħ'),\n    (0x2110, 'M', 'i'),\n    (0x2112, 'M', 'l'),\n    (0x2114, 'V'),\n    (0x2115, 'M', 'n'),\n    (0x2116, 'M', 'no'),\n    (0x2117, 'V'),\n    (0x2119, 'M', 'p'),\n    (0x211A, 'M', 'q'),\n    (0x211B, 'M', 'r'),\n    (0x211E, 'V'),\n    (0x2120, 'M', 'sm'),\n    (0x2121, 'M', 'tel'),\n    (0x2122, 'M', 'tm'),\n    (0x2123, 'V'),\n    (0x2124, 'M', 'z'),\n    (0x2125, 'V'),\n    (0x2126, 'M', 'ω'),\n    (0x2127, 'V'),\n    (0x2128, 'M', 'z'),\n    (0x2129, 'V'),\n    (0x212A, 'M', 'k'),\n    (0x212B, 'M', 'å'),\n    (0x212C, 'M', 'b'),\n    (0x212D, 'M', 'c'),\n    (0x212E, 'V'),\n    (0x212F, 'M', 'e'),\n    (0x2131, 'M', 'f'),\n    (0x2132, 'X'),\n    (0x2133, 'M', 'm'),\n    (0x2134, 'M', 'o'),\n    (0x2135, 'M', 'א'),\n    (0x2136, 'M', 'ב'),\n    (0x2137, 'M', 'ג'),\n    (0x2138, 'M', 'ד'),\n    (0x2139, 'M', 'i'),\n    (0x213A, 'V'),\n    (0x213B, 'M', 'fax'),\n    (0x213C, 'M', 'π'),\n    (0x213D, 'M', 'γ'),\n    (0x213F, 'M', 'π'),\n    (0x2140, 'M', '∑'),\n    (0x2141, 'V'),\n    (0x2145, 'M', 'd'),\n    (0x2147, 'M', 'e'),\n    (0x2148, 'M', 'i'),\n    (0x2149, 'M', 'j'),\n    (0x214A, 'V'),\n    (0x2150, 'M', '1⁄7'),\n    (0x2151, 'M', '1⁄9'),\n    (0x2152, 'M', '1⁄10'),\n    (0x2153, 'M', '1⁄3'),\n    (0x2154, 'M', '2⁄3'),\n    (0x2155, 'M', '1⁄5'),\n    (0x2156, 'M', '2⁄5'),\n    (0x2157, 'M', '3⁄5'),\n    (0x2158, 'M', '4⁄5'),\n    (0x2159, 'M', '1⁄6'),\n    (0x215A, 'M', '5⁄6'),\n    (0x215B, 'M', '1⁄8'),\n    (0x215C, 'M', '3⁄8'),\n    (0x215D, 'M', '5⁄8'),\n    (0x215E, 'M', '7⁄8'),\n    (0x215F, 'M', '1⁄'),\n    (0x2160, 'M', 'i'),\n    (0x2161, 'M', 'ii'),\n    (0x2162, 'M', 'iii'),\n    (0x2163, 'M', 'iv'),\n    (0x2164, 'M', 'v'),\n    (0x2165, 'M', 'vi'),\n    (0x2166, 'M', 'vii'),\n    (0x2167, 'M', 'viii'),\n    (0x2168, 'M', 'ix'),\n    (0x2169, 'M', 'x'),\n    (0x216A, 'M', 'xi'),\n    (0x216B, 'M', 'xii'),\n    (0x216C, 'M', 'l'),\n    (0x216D, 'M', 'c'),\n    (0x216E, 'M', 'd'),\n    (0x216F, 'M', 'm'),\n    (0x2170, 'M', 'i'),\n    (0x2171, 'M', 'ii'),\n    (0x2172, 'M', 'iii'),\n    (0x2173, 'M', 'iv'),\n    (0x2174, 'M', 'v'),\n    (0x2175, 'M', 'vi'),\n    (0x2176, 'M', 'vii'),\n    (0x2177, 'M', 'viii'),\n    (0x2178, 'M', 'ix'),\n    (0x2179, 'M', 'x'),\n    (0x217A, 'M', 'xi'),\n    (0x217B, 'M', 'xii'),\n    (0x217C, 'M', 'l'),\n    ]\n\ndef _seg_23() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x217D, 'M', 'c'),\n    (0x217E, 'M', 'd'),\n    (0x217F, 'M', 'm'),\n    (0x2180, 'V'),\n    (0x2183, 'X'),\n    (0x2184, 'V'),\n    (0x2189, 'M', '0⁄3'),\n    (0x218A, 'V'),\n    (0x218C, 'X'),\n    (0x2190, 'V'),\n    (0x222C, 'M', '∫∫'),\n    (0x222D, 'M', '∫∫∫'),\n    (0x222E, 'V'),\n    (0x222F, 'M', '∮∮'),\n    (0x2230, 'M', '∮∮∮'),\n    (0x2231, 'V'),\n    (0x2260, '3'),\n    (0x2261, 'V'),\n    (0x226E, '3'),\n    (0x2270, 'V'),\n    (0x2329, 'M', '〈'),\n    (0x232A, 'M', '〉'),\n    (0x232B, 'V'),\n    (0x2427, 'X'),\n    (0x2440, 'V'),\n    (0x244B, 'X'),\n    (0x2460, 'M', '1'),\n    (0x2461, 'M', '2'),\n    (0x2462, 'M', '3'),\n    (0x2463, 'M', '4'),\n    (0x2464, 'M', '5'),\n    (0x2465, 'M', '6'),\n    (0x2466, 'M', '7'),\n    (0x2467, 'M', '8'),\n    (0x2468, 'M', '9'),\n    (0x2469, 'M', '10'),\n    (0x246A, 'M', '11'),\n    (0x246B, 'M', '12'),\n    (0x246C, 'M', '13'),\n    (0x246D, 'M', '14'),\n    (0x246E, 'M', '15'),\n    (0x246F, 'M', '16'),\n    (0x2470, 'M', '17'),\n    (0x2471, 'M', '18'),\n    (0x2472, 'M', '19'),\n    (0x2473, 'M', '20'),\n    (0x2474, '3', '(1)'),\n    (0x2475, '3', '(2)'),\n    (0x2476, '3', '(3)'),\n    (0x2477, '3', '(4)'),\n    (0x2478, '3', '(5)'),\n    (0x2479, '3', '(6)'),\n    (0x247A, '3', '(7)'),\n    (0x247B, '3', '(8)'),\n    (0x247C, '3', '(9)'),\n    (0x247D, '3', '(10)'),\n    (0x247E, '3', '(11)'),\n    (0x247F, '3', '(12)'),\n    (0x2480, '3', '(13)'),\n    (0x2481, '3', '(14)'),\n    (0x2482, '3', '(15)'),\n    (0x2483, '3', '(16)'),\n    (0x2484, '3', '(17)'),\n    (0x2485, '3', '(18)'),\n    (0x2486, '3', '(19)'),\n    (0x2487, '3', '(20)'),\n    (0x2488, 'X'),\n    (0x249C, '3', '(a)'),\n    (0x249D, '3', '(b)'),\n    (0x249E, '3', '(c)'),\n    (0x249F, '3', '(d)'),\n    (0x24A0, '3', '(e)'),\n    (0x24A1, '3', '(f)'),\n    (0x24A2, '3', '(g)'),\n    (0x24A3, '3', '(h)'),\n    (0x24A4, '3', '(i)'),\n    (0x24A5, '3', '(j)'),\n    (0x24A6, '3', '(k)'),\n    (0x24A7, '3', '(l)'),\n    (0x24A8, '3', '(m)'),\n    (0x24A9, '3', '(n)'),\n    (0x24AA, '3', '(o)'),\n    (0x24AB, '3', '(p)'),\n    (0x24AC, '3', '(q)'),\n    (0x24AD, '3', '(r)'),\n    (0x24AE, '3', '(s)'),\n    (0x24AF, '3', '(t)'),\n    (0x24B0, '3', '(u)'),\n    (0x24B1, '3', '(v)'),\n    (0x24B2, '3', '(w)'),\n    (0x24B3, '3', '(x)'),\n    (0x24B4, '3', '(y)'),\n    (0x24B5, '3', '(z)'),\n    (0x24B6, 'M', 'a'),\n    (0x24B7, 'M', 'b'),\n    (0x24B8, 'M', 'c'),\n    (0x24B9, 'M', 'd'),\n    (0x24BA, 'M', 'e'),\n    (0x24BB, 'M', 'f'),\n    (0x24BC, 'M', 'g'),\n    ]\n\ndef _seg_24() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x24BD, 'M', 'h'),\n    (0x24BE, 'M', 'i'),\n    (0x24BF, 'M', 'j'),\n    (0x24C0, 'M', 'k'),\n    (0x24C1, 'M', 'l'),\n    (0x24C2, 'M', 'm'),\n    (0x24C3, 'M', 'n'),\n    (0x24C4, 'M', 'o'),\n    (0x24C5, 'M', 'p'),\n    (0x24C6, 'M', 'q'),\n    (0x24C7, 'M', 'r'),\n    (0x24C8, 'M', 's'),\n    (0x24C9, 'M', 't'),\n    (0x24CA, 'M', 'u'),\n    (0x24CB, 'M', 'v'),\n    (0x24CC, 'M', 'w'),\n    (0x24CD, 'M', 'x'),\n    (0x24CE, 'M', 'y'),\n    (0x24CF, 'M', 'z'),\n    (0x24D0, 'M', 'a'),\n    (0x24D1, 'M', 'b'),\n    (0x24D2, 'M', 'c'),\n    (0x24D3, 'M', 'd'),\n    (0x24D4, 'M', 'e'),\n    (0x24D5, 'M', 'f'),\n    (0x24D6, 'M', 'g'),\n    (0x24D7, 'M', 'h'),\n    (0x24D8, 'M', 'i'),\n    (0x24D9, 'M', 'j'),\n    (0x24DA, 'M', 'k'),\n    (0x24DB, 'M', 'l'),\n    (0x24DC, 'M', 'm'),\n    (0x24DD, 'M', 'n'),\n    (0x24DE, 'M', 'o'),\n    (0x24DF, 'M', 'p'),\n    (0x24E0, 'M', 'q'),\n    (0x24E1, 'M', 'r'),\n    (0x24E2, 'M', 's'),\n    (0x24E3, 'M', 't'),\n    (0x24E4, 'M', 'u'),\n    (0x24E5, 'M', 'v'),\n    (0x24E6, 'M', 'w'),\n    (0x24E7, 'M', 'x'),\n    (0x24E8, 'M', 'y'),\n    (0x24E9, 'M', 'z'),\n    (0x24EA, 'M', '0'),\n    (0x24EB, 'V'),\n    (0x2A0C, 'M', '∫∫∫∫'),\n    (0x2A0D, 'V'),\n    (0x2A74, '3', '::='),\n    (0x2A75, '3', '=='),\n    (0x2A76, '3', '==='),\n    (0x2A77, 'V'),\n    (0x2ADC, 'M', '⫝̸'),\n    (0x2ADD, 'V'),\n    (0x2B74, 'X'),\n    (0x2B76, 'V'),\n    (0x2B96, 'X'),\n    (0x2B97, 'V'),\n    (0x2C00, 'M', 'ⰰ'),\n    (0x2C01, 'M', 'ⰱ'),\n    (0x2C02, 'M', 'ⰲ'),\n    (0x2C03, 'M', 'ⰳ'),\n    (0x2C04, 'M', 'ⰴ'),\n    (0x2C05, 'M', 'ⰵ'),\n    (0x2C06, 'M', 'ⰶ'),\n    (0x2C07, 'M', 'ⰷ'),\n    (0x2C08, 'M', 'ⰸ'),\n    (0x2C09, 'M', 'ⰹ'),\n    (0x2C0A, 'M', 'ⰺ'),\n    (0x2C0B, 'M', 'ⰻ'),\n    (0x2C0C, 'M', 'ⰼ'),\n    (0x2C0D, 'M', 'ⰽ'),\n    (0x2C0E, 'M', 'ⰾ'),\n    (0x2C0F, 'M', 'ⰿ'),\n    (0x2C10, 'M', 'ⱀ'),\n    (0x2C11, 'M', 'ⱁ'),\n    (0x2C12, 'M', 'ⱂ'),\n    (0x2C13, 'M', 'ⱃ'),\n    (0x2C14, 'M', 'ⱄ'),\n    (0x2C15, 'M', 'ⱅ'),\n    (0x2C16, 'M', 'ⱆ'),\n    (0x2C17, 'M', 'ⱇ'),\n    (0x2C18, 'M', 'ⱈ'),\n    (0x2C19, 'M', 'ⱉ'),\n    (0x2C1A, 'M', 'ⱊ'),\n    (0x2C1B, 'M', 'ⱋ'),\n    (0x2C1C, 'M', 'ⱌ'),\n    (0x2C1D, 'M', 'ⱍ'),\n    (0x2C1E, 'M', 'ⱎ'),\n    (0x2C1F, 'M', 'ⱏ'),\n    (0x2C20, 'M', 'ⱐ'),\n    (0x2C21, 'M', 'ⱑ'),\n    (0x2C22, 'M', 'ⱒ'),\n    (0x2C23, 'M', 'ⱓ'),\n    (0x2C24, 'M', 'ⱔ'),\n    (0x2C25, 'M', 'ⱕ'),\n    (0x2C26, 'M', 'ⱖ'),\n    (0x2C27, 'M', 'ⱗ'),\n    (0x2C28, 'M', 'ⱘ'),\n    ]\n\ndef _seg_25() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x2C29, 'M', 'ⱙ'),\n    (0x2C2A, 'M', 'ⱚ'),\n    (0x2C2B, 'M', 'ⱛ'),\n    (0x2C2C, 'M', 'ⱜ'),\n    (0x2C2D, 'M', 'ⱝ'),\n    (0x2C2E, 'M', 'ⱞ'),\n    (0x2C2F, 'M', 'ⱟ'),\n    (0x2C30, 'V'),\n    (0x2C60, 'M', 'ⱡ'),\n    (0x2C61, 'V'),\n    (0x2C62, 'M', 'ɫ'),\n    (0x2C63, 'M', 'ᵽ'),\n    (0x2C64, 'M', 'ɽ'),\n    (0x2C65, 'V'),\n    (0x2C67, 'M', 'ⱨ'),\n    (0x2C68, 'V'),\n    (0x2C69, 'M', 'ⱪ'),\n    (0x2C6A, 'V'),\n    (0x2C6B, 'M', 'ⱬ'),\n    (0x2C6C, 'V'),\n    (0x2C6D, 'M', 'ɑ'),\n    (0x2C6E, 'M', 'ɱ'),\n    (0x2C6F, 'M', 'ɐ'),\n    (0x2C70, 'M', 'ɒ'),\n    (0x2C71, 'V'),\n    (0x2C72, 'M', 'ⱳ'),\n    (0x2C73, 'V'),\n    (0x2C75, 'M', 'ⱶ'),\n    (0x2C76, 'V'),\n    (0x2C7C, 'M', 'j'),\n    (0x2C7D, 'M', 'v'),\n    (0x2C7E, 'M', 'ȿ'),\n    (0x2C7F, 'M', 'ɀ'),\n    (0x2C80, 'M', 'ⲁ'),\n    (0x2C81, 'V'),\n    (0x2C82, 'M', 'ⲃ'),\n    (0x2C83, 'V'),\n    (0x2C84, 'M', 'ⲅ'),\n    (0x2C85, 'V'),\n    (0x2C86, 'M', 'ⲇ'),\n    (0x2C87, 'V'),\n    (0x2C88, 'M', 'ⲉ'),\n    (0x2C89, 'V'),\n    (0x2C8A, 'M', 'ⲋ'),\n    (0x2C8B, 'V'),\n    (0x2C8C, 'M', 'ⲍ'),\n    (0x2C8D, 'V'),\n    (0x2C8E, 'M', 'ⲏ'),\n    (0x2C8F, 'V'),\n    (0x2C90, 'M', 'ⲑ'),\n    (0x2C91, 'V'),\n    (0x2C92, 'M', 'ⲓ'),\n    (0x2C93, 'V'),\n    (0x2C94, 'M', 'ⲕ'),\n    (0x2C95, 'V'),\n    (0x2C96, 'M', 'ⲗ'),\n    (0x2C97, 'V'),\n    (0x2C98, 'M', 'ⲙ'),\n    (0x2C99, 'V'),\n    (0x2C9A, 'M', 'ⲛ'),\n    (0x2C9B, 'V'),\n    (0x2C9C, 'M', 'ⲝ'),\n    (0x2C9D, 'V'),\n    (0x2C9E, 'M', 'ⲟ'),\n    (0x2C9F, 'V'),\n    (0x2CA0, 'M', 'ⲡ'),\n    (0x2CA1, 'V'),\n    (0x2CA2, 'M', 'ⲣ'),\n    (0x2CA3, 'V'),\n    (0x2CA4, 'M', 'ⲥ'),\n    (0x2CA5, 'V'),\n    (0x2CA6, 'M', 'ⲧ'),\n    (0x2CA7, 'V'),\n    (0x2CA8, 'M', 'ⲩ'),\n    (0x2CA9, 'V'),\n    (0x2CAA, 'M', 'ⲫ'),\n    (0x2CAB, 'V'),\n    (0x2CAC, 'M', 'ⲭ'),\n    (0x2CAD, 'V'),\n    (0x2CAE, 'M', 'ⲯ'),\n    (0x2CAF, 'V'),\n    (0x2CB0, 'M', 'ⲱ'),\n    (0x2CB1, 'V'),\n    (0x2CB2, 'M', 'ⲳ'),\n    (0x2CB3, 'V'),\n    (0x2CB4, 'M', 'ⲵ'),\n    (0x2CB5, 'V'),\n    (0x2CB6, 'M', 'ⲷ'),\n    (0x2CB7, 'V'),\n    (0x2CB8, 'M', 'ⲹ'),\n    (0x2CB9, 'V'),\n    (0x2CBA, 'M', 'ⲻ'),\n    (0x2CBB, 'V'),\n    (0x2CBC, 'M', 'ⲽ'),\n    (0x2CBD, 'V'),\n    (0x2CBE, 'M', 'ⲿ'),\n    (0x2CBF, 'V'),\n    (0x2CC0, 'M', 'ⳁ'),\n    (0x2CC1, 'V'),\n    (0x2CC2, 'M', 'ⳃ'),\n    ]\n\ndef _seg_26() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x2CC3, 'V'),\n    (0x2CC4, 'M', 'ⳅ'),\n    (0x2CC5, 'V'),\n    (0x2CC6, 'M', 'ⳇ'),\n    (0x2CC7, 'V'),\n    (0x2CC8, 'M', 'ⳉ'),\n    (0x2CC9, 'V'),\n    (0x2CCA, 'M', 'ⳋ'),\n    (0x2CCB, 'V'),\n    (0x2CCC, 'M', 'ⳍ'),\n    (0x2CCD, 'V'),\n    (0x2CCE, 'M', 'ⳏ'),\n    (0x2CCF, 'V'),\n    (0x2CD0, 'M', 'ⳑ'),\n    (0x2CD1, 'V'),\n    (0x2CD2, 'M', 'ⳓ'),\n    (0x2CD3, 'V'),\n    (0x2CD4, 'M', 'ⳕ'),\n    (0x2CD5, 'V'),\n    (0x2CD6, 'M', 'ⳗ'),\n    (0x2CD7, 'V'),\n    (0x2CD8, 'M', 'ⳙ'),\n    (0x2CD9, 'V'),\n    (0x2CDA, 'M', 'ⳛ'),\n    (0x2CDB, 'V'),\n    (0x2CDC, 'M', 'ⳝ'),\n    (0x2CDD, 'V'),\n    (0x2CDE, 'M', 'ⳟ'),\n    (0x2CDF, 'V'),\n    (0x2CE0, 'M', 'ⳡ'),\n    (0x2CE1, 'V'),\n    (0x2CE2, 'M', 'ⳣ'),\n    (0x2CE3, 'V'),\n    (0x2CEB, 'M', 'ⳬ'),\n    (0x2CEC, 'V'),\n    (0x2CED, 'M', 'ⳮ'),\n    (0x2CEE, 'V'),\n    (0x2CF2, 'M', 'ⳳ'),\n    (0x2CF3, 'V'),\n    (0x2CF4, 'X'),\n    (0x2CF9, 'V'),\n    (0x2D26, 'X'),\n    (0x2D27, 'V'),\n    (0x2D28, 'X'),\n    (0x2D2D, 'V'),\n    (0x2D2E, 'X'),\n    (0x2D30, 'V'),\n    (0x2D68, 'X'),\n    (0x2D6F, 'M', 'ⵡ'),\n    (0x2D70, 'V'),\n    (0x2D71, 'X'),\n    (0x2D7F, 'V'),\n    (0x2D97, 'X'),\n    (0x2DA0, 'V'),\n    (0x2DA7, 'X'),\n    (0x2DA8, 'V'),\n    (0x2DAF, 'X'),\n    (0x2DB0, 'V'),\n    (0x2DB7, 'X'),\n    (0x2DB8, 'V'),\n    (0x2DBF, 'X'),\n    (0x2DC0, 'V'),\n    (0x2DC7, 'X'),\n    (0x2DC8, 'V'),\n    (0x2DCF, 'X'),\n    (0x2DD0, 'V'),\n    (0x2DD7, 'X'),\n    (0x2DD8, 'V'),\n    (0x2DDF, 'X'),\n    (0x2DE0, 'V'),\n    (0x2E5E, 'X'),\n    (0x2E80, 'V'),\n    (0x2E9A, 'X'),\n    (0x2E9B, 'V'),\n    (0x2E9F, 'M', '母'),\n    (0x2EA0, 'V'),\n    (0x2EF3, 'M', '龟'),\n    (0x2EF4, 'X'),\n    (0x2F00, 'M', '一'),\n    (0x2F01, 'M', '丨'),\n    (0x2F02, 'M', '丶'),\n    (0x2F03, 'M', '丿'),\n    (0x2F04, 'M', '乙'),\n    (0x2F05, 'M', '亅'),\n    (0x2F06, 'M', '二'),\n    (0x2F07, 'M', '亠'),\n    (0x2F08, 'M', '人'),\n    (0x2F09, 'M', '儿'),\n    (0x2F0A, 'M', '入'),\n    (0x2F0B, 'M', '八'),\n    (0x2F0C, 'M', '冂'),\n    (0x2F0D, 'M', '冖'),\n    (0x2F0E, 'M', '冫'),\n    (0x2F0F, 'M', '几'),\n    (0x2F10, 'M', '凵'),\n    (0x2F11, 'M', '刀'),\n    (0x2F12, 'M', '力'),\n    (0x2F13, 'M', '勹'),\n    (0x2F14, 'M', '匕'),\n    (0x2F15, 'M', '匚'),\n    ]\n\ndef _seg_27() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x2F16, 'M', '匸'),\n    (0x2F17, 'M', '十'),\n    (0x2F18, 'M', '卜'),\n    (0x2F19, 'M', '卩'),\n    (0x2F1A, 'M', '厂'),\n    (0x2F1B, 'M', '厶'),\n    (0x2F1C, 'M', '又'),\n    (0x2F1D, 'M', '口'),\n    (0x2F1E, 'M', '囗'),\n    (0x2F1F, 'M', '土'),\n    (0x2F20, 'M', '士'),\n    (0x2F21, 'M', '夂'),\n    (0x2F22, 'M', '夊'),\n    (0x2F23, 'M', '夕'),\n    (0x2F24, 'M', '大'),\n    (0x2F25, 'M', '女'),\n    (0x2F26, 'M', '子'),\n    (0x2F27, 'M', '宀'),\n    (0x2F28, 'M', '寸'),\n    (0x2F29, 'M', '小'),\n    (0x2F2A, 'M', '尢'),\n    (0x2F2B, 'M', '尸'),\n    (0x2F2C, 'M', '屮'),\n    (0x2F2D, 'M', '山'),\n    (0x2F2E, 'M', '巛'),\n    (0x2F2F, 'M', '工'),\n    (0x2F30, 'M', '己'),\n    (0x2F31, 'M', '巾'),\n    (0x2F32, 'M', '干'),\n    (0x2F33, 'M', '幺'),\n    (0x2F34, 'M', '广'),\n    (0x2F35, 'M', '廴'),\n    (0x2F36, 'M', '廾'),\n    (0x2F37, 'M', '弋'),\n    (0x2F38, 'M', '弓'),\n    (0x2F39, 'M', '彐'),\n    (0x2F3A, 'M', '彡'),\n    (0x2F3B, 'M', '彳'),\n    (0x2F3C, 'M', '心'),\n    (0x2F3D, 'M', '戈'),\n    (0x2F3E, 'M', '戶'),\n    (0x2F3F, 'M', '手'),\n    (0x2F40, 'M', '支'),\n    (0x2F41, 'M', '攴'),\n    (0x2F42, 'M', '文'),\n    (0x2F43, 'M', '斗'),\n    (0x2F44, 'M', '斤'),\n    (0x2F45, 'M', '方'),\n    (0x2F46, 'M', '无'),\n    (0x2F47, 'M', '日'),\n    (0x2F48, 'M', '曰'),\n    (0x2F49, 'M', '月'),\n    (0x2F4A, 'M', '木'),\n    (0x2F4B, 'M', '欠'),\n    (0x2F4C, 'M', '止'),\n    (0x2F4D, 'M', '歹'),\n    (0x2F4E, 'M', '殳'),\n    (0x2F4F, 'M', '毋'),\n    (0x2F50, 'M', '比'),\n    (0x2F51, 'M', '毛'),\n    (0x2F52, 'M', '氏'),\n    (0x2F53, 'M', '气'),\n    (0x2F54, 'M', '水'),\n    (0x2F55, 'M', '火'),\n    (0x2F56, 'M', '爪'),\n    (0x2F57, 'M', '父'),\n    (0x2F58, 'M', '爻'),\n    (0x2F59, 'M', '爿'),\n    (0x2F5A, 'M', '片'),\n    (0x2F5B, 'M', '牙'),\n    (0x2F5C, 'M', '牛'),\n    (0x2F5D, 'M', '犬'),\n    (0x2F5E, 'M', '玄'),\n    (0x2F5F, 'M', '玉'),\n    (0x2F60, 'M', '瓜'),\n    (0x2F61, 'M', '瓦'),\n    (0x2F62, 'M', '甘'),\n    (0x2F63, 'M', '生'),\n    (0x2F64, 'M', '用'),\n    (0x2F65, 'M', '田'),\n    (0x2F66, 'M', '疋'),\n    (0x2F67, 'M', '疒'),\n    (0x2F68, 'M', '癶'),\n    (0x2F69, 'M', '白'),\n    (0x2F6A, 'M', '皮'),\n    (0x2F6B, 'M', '皿'),\n    (0x2F6C, 'M', '目'),\n    (0x2F6D, 'M', '矛'),\n    (0x2F6E, 'M', '矢'),\n    (0x2F6F, 'M', '石'),\n    (0x2F70, 'M', '示'),\n    (0x2F71, 'M', '禸'),\n    (0x2F72, 'M', '禾'),\n    (0x2F73, 'M', '穴'),\n    (0x2F74, 'M', '立'),\n    (0x2F75, 'M', '竹'),\n    (0x2F76, 'M', '米'),\n    (0x2F77, 'M', '糸'),\n    (0x2F78, 'M', '缶'),\n    (0x2F79, 'M', '网'),\n    ]\n\ndef _seg_28() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x2F7A, 'M', '羊'),\n    (0x2F7B, 'M', '羽'),\n    (0x2F7C, 'M', '老'),\n    (0x2F7D, 'M', '而'),\n    (0x2F7E, 'M', '耒'),\n    (0x2F7F, 'M', '耳'),\n    (0x2F80, 'M', '聿'),\n    (0x2F81, 'M', '肉'),\n    (0x2F82, 'M', '臣'),\n    (0x2F83, 'M', '自'),\n    (0x2F84, 'M', '至'),\n    (0x2F85, 'M', '臼'),\n    (0x2F86, 'M', '舌'),\n    (0x2F87, 'M', '舛'),\n    (0x2F88, 'M', '舟'),\n    (0x2F89, 'M', '艮'),\n    (0x2F8A, 'M', '色'),\n    (0x2F8B, 'M', '艸'),\n    (0x2F8C, 'M', '虍'),\n    (0x2F8D, 'M', '虫'),\n    (0x2F8E, 'M', '血'),\n    (0x2F8F, 'M', '行'),\n    (0x2F90, 'M', '衣'),\n    (0x2F91, 'M', '襾'),\n    (0x2F92, 'M', '見'),\n    (0x2F93, 'M', '角'),\n    (0x2F94, 'M', '言'),\n    (0x2F95, 'M', '谷'),\n    (0x2F96, 'M', '豆'),\n    (0x2F97, 'M', '豕'),\n    (0x2F98, 'M', '豸'),\n    (0x2F99, 'M', '貝'),\n    (0x2F9A, 'M', '赤'),\n    (0x2F9B, 'M', '走'),\n    (0x2F9C, 'M', '足'),\n    (0x2F9D, 'M', '身'),\n    (0x2F9E, 'M', '車'),\n    (0x2F9F, 'M', '辛'),\n    (0x2FA0, 'M', '辰'),\n    (0x2FA1, 'M', '辵'),\n    (0x2FA2, 'M', '邑'),\n    (0x2FA3, 'M', '酉'),\n    (0x2FA4, 'M', '釆'),\n    (0x2FA5, 'M', '里'),\n    (0x2FA6, 'M', '金'),\n    (0x2FA7, 'M', '長'),\n    (0x2FA8, 'M', '門'),\n    (0x2FA9, 'M', '阜'),\n    (0x2FAA, 'M', '隶'),\n    (0x2FAB, 'M', '隹'),\n    (0x2FAC, 'M', '雨'),\n    (0x2FAD, 'M', '靑'),\n    (0x2FAE, 'M', '非'),\n    (0x2FAF, 'M', '面'),\n    (0x2FB0, 'M', '革'),\n    (0x2FB1, 'M', '韋'),\n    (0x2FB2, 'M', '韭'),\n    (0x2FB3, 'M', '音'),\n    (0x2FB4, 'M', '頁'),\n    (0x2FB5, 'M', '風'),\n    (0x2FB6, 'M', '飛'),\n    (0x2FB7, 'M', '食'),\n    (0x2FB8, 'M', '首'),\n    (0x2FB9, 'M', '香'),\n    (0x2FBA, 'M', '馬'),\n    (0x2FBB, 'M', '骨'),\n    (0x2FBC, 'M', '高'),\n    (0x2FBD, 'M', '髟'),\n    (0x2FBE, 'M', '鬥'),\n    (0x2FBF, 'M', '鬯'),\n    (0x2FC0, 'M', '鬲'),\n    (0x2FC1, 'M', '鬼'),\n    (0x2FC2, 'M', '魚'),\n    (0x2FC3, 'M', '鳥'),\n    (0x2FC4, 'M', '鹵'),\n    (0x2FC5, 'M', '鹿'),\n    (0x2FC6, 'M', '麥'),\n    (0x2FC7, 'M', '麻'),\n    (0x2FC8, 'M', '黃'),\n    (0x2FC9, 'M', '黍'),\n    (0x2FCA, 'M', '黑'),\n    (0x2FCB, 'M', '黹'),\n    (0x2FCC, 'M', '黽'),\n    (0x2FCD, 'M', '鼎'),\n    (0x2FCE, 'M', '鼓'),\n    (0x2FCF, 'M', '鼠'),\n    (0x2FD0, 'M', '鼻'),\n    (0x2FD1, 'M', '齊'),\n    (0x2FD2, 'M', '齒'),\n    (0x2FD3, 'M', '龍'),\n    (0x2FD4, 'M', '龜'),\n    (0x2FD5, 'M', '龠'),\n    (0x2FD6, 'X'),\n    (0x3000, '3', ' '),\n    (0x3001, 'V'),\n    (0x3002, 'M', '.'),\n    (0x3003, 'V'),\n    (0x3036, 'M', '〒'),\n    (0x3037, 'V'),\n    (0x3038, 'M', '十'),\n    ]\n\ndef _seg_29() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x3039, 'M', '卄'),\n    (0x303A, 'M', '卅'),\n    (0x303B, 'V'),\n    (0x3040, 'X'),\n    (0x3041, 'V'),\n    (0x3097, 'X'),\n    (0x3099, 'V'),\n    (0x309B, '3', ' ゙'),\n    (0x309C, '3', ' ゚'),\n    (0x309D, 'V'),\n    (0x309F, 'M', 'より'),\n    (0x30A0, 'V'),\n    (0x30FF, 'M', 'コト'),\n    (0x3100, 'X'),\n    (0x3105, 'V'),\n    (0x3130, 'X'),\n    (0x3131, 'M', 'ᄀ'),\n    (0x3132, 'M', 'ᄁ'),\n    (0x3133, 'M', 'ᆪ'),\n    (0x3134, 'M', 'ᄂ'),\n    (0x3135, 'M', 'ᆬ'),\n    (0x3136, 'M', 'ᆭ'),\n    (0x3137, 'M', 'ᄃ'),\n    (0x3138, 'M', 'ᄄ'),\n    (0x3139, 'M', 'ᄅ'),\n    (0x313A, 'M', 'ᆰ'),\n    (0x313B, 'M', 'ᆱ'),\n    (0x313C, 'M', 'ᆲ'),\n    (0x313D, 'M', 'ᆳ'),\n    (0x313E, 'M', 'ᆴ'),\n    (0x313F, 'M', 'ᆵ'),\n    (0x3140, 'M', 'ᄚ'),\n    (0x3141, 'M', 'ᄆ'),\n    (0x3142, 'M', 'ᄇ'),\n    (0x3143, 'M', 'ᄈ'),\n    (0x3144, 'M', 'ᄡ'),\n    (0x3145, 'M', 'ᄉ'),\n    (0x3146, 'M', 'ᄊ'),\n    (0x3147, 'M', 'ᄋ'),\n    (0x3148, 'M', 'ᄌ'),\n    (0x3149, 'M', 'ᄍ'),\n    (0x314A, 'M', 'ᄎ'),\n    (0x314B, 'M', 'ᄏ'),\n    (0x314C, 'M', 'ᄐ'),\n    (0x314D, 'M', 'ᄑ'),\n    (0x314E, 'M', 'ᄒ'),\n    (0x314F, 'M', 'ᅡ'),\n    (0x3150, 'M', 'ᅢ'),\n    (0x3151, 'M', 'ᅣ'),\n    (0x3152, 'M', 'ᅤ'),\n    (0x3153, 'M', 'ᅥ'),\n    (0x3154, 'M', 'ᅦ'),\n    (0x3155, 'M', 'ᅧ'),\n    (0x3156, 'M', 'ᅨ'),\n    (0x3157, 'M', 'ᅩ'),\n    (0x3158, 'M', 'ᅪ'),\n    (0x3159, 'M', 'ᅫ'),\n    (0x315A, 'M', 'ᅬ'),\n    (0x315B, 'M', 'ᅭ'),\n    (0x315C, 'M', 'ᅮ'),\n    (0x315D, 'M', 'ᅯ'),\n    (0x315E, 'M', 'ᅰ'),\n    (0x315F, 'M', 'ᅱ'),\n    (0x3160, 'M', 'ᅲ'),\n    (0x3161, 'M', 'ᅳ'),\n    (0x3162, 'M', 'ᅴ'),\n    (0x3163, 'M', 'ᅵ'),\n    (0x3164, 'X'),\n    (0x3165, 'M', 'ᄔ'),\n    (0x3166, 'M', 'ᄕ'),\n    (0x3167, 'M', 'ᇇ'),\n    (0x3168, 'M', 'ᇈ'),\n    (0x3169, 'M', 'ᇌ'),\n    (0x316A, 'M', 'ᇎ'),\n    (0x316B, 'M', 'ᇓ'),\n    (0x316C, 'M', 'ᇗ'),\n    (0x316D, 'M', 'ᇙ'),\n    (0x316E, 'M', 'ᄜ'),\n    (0x316F, 'M', 'ᇝ'),\n    (0x3170, 'M', 'ᇟ'),\n    (0x3171, 'M', 'ᄝ'),\n    (0x3172, 'M', 'ᄞ'),\n    (0x3173, 'M', 'ᄠ'),\n    (0x3174, 'M', 'ᄢ'),\n    (0x3175, 'M', 'ᄣ'),\n    (0x3176, 'M', 'ᄧ'),\n    (0x3177, 'M', 'ᄩ'),\n    (0x3178, 'M', 'ᄫ'),\n    (0x3179, 'M', 'ᄬ'),\n    (0x317A, 'M', 'ᄭ'),\n    (0x317B, 'M', 'ᄮ'),\n    (0x317C, 'M', 'ᄯ'),\n    (0x317D, 'M', 'ᄲ'),\n    (0x317E, 'M', 'ᄶ'),\n    (0x317F, 'M', 'ᅀ'),\n    (0x3180, 'M', 'ᅇ'),\n    (0x3181, 'M', 'ᅌ'),\n    (0x3182, 'M', 'ᇱ'),\n    (0x3183, 'M', 'ᇲ'),\n    (0x3184, 'M', 'ᅗ'),\n    ]\n\ndef _seg_30() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x3185, 'M', 'ᅘ'),\n    (0x3186, 'M', 'ᅙ'),\n    (0x3187, 'M', 'ᆄ'),\n    (0x3188, 'M', 'ᆅ'),\n    (0x3189, 'M', 'ᆈ'),\n    (0x318A, 'M', 'ᆑ'),\n    (0x318B, 'M', 'ᆒ'),\n    (0x318C, 'M', 'ᆔ'),\n    (0x318D, 'M', 'ᆞ'),\n    (0x318E, 'M', 'ᆡ'),\n    (0x318F, 'X'),\n    (0x3190, 'V'),\n    (0x3192, 'M', '一'),\n    (0x3193, 'M', '二'),\n    (0x3194, 'M', '三'),\n    (0x3195, 'M', '四'),\n    (0x3196, 'M', '上'),\n    (0x3197, 'M', '中'),\n    (0x3198, 'M', '下'),\n    (0x3199, 'M', '甲'),\n    (0x319A, 'M', '乙'),\n    (0x319B, 'M', '丙'),\n    (0x319C, 'M', '丁'),\n    (0x319D, 'M', '天'),\n    (0x319E, 'M', '地'),\n    (0x319F, 'M', '人'),\n    (0x31A0, 'V'),\n    (0x31E4, 'X'),\n    (0x31F0, 'V'),\n    (0x3200, '3', '(ᄀ)'),\n    (0x3201, '3', '(ᄂ)'),\n    (0x3202, '3', '(ᄃ)'),\n    (0x3203, '3', '(ᄅ)'),\n    (0x3204, '3', '(ᄆ)'),\n    (0x3205, '3', '(ᄇ)'),\n    (0x3206, '3', '(ᄉ)'),\n    (0x3207, '3', '(ᄋ)'),\n    (0x3208, '3', '(ᄌ)'),\n    (0x3209, '3', '(ᄎ)'),\n    (0x320A, '3', '(ᄏ)'),\n    (0x320B, '3', '(ᄐ)'),\n    (0x320C, '3', '(ᄑ)'),\n    (0x320D, '3', '(ᄒ)'),\n    (0x320E, '3', '(가)'),\n    (0x320F, '3', '(나)'),\n    (0x3210, '3', '(다)'),\n    (0x3211, '3', '(라)'),\n    (0x3212, '3', '(마)'),\n    (0x3213, '3', '(바)'),\n    (0x3214, '3', '(사)'),\n    (0x3215, '3', '(아)'),\n    (0x3216, '3', '(자)'),\n    (0x3217, '3', '(차)'),\n    (0x3218, '3', '(카)'),\n    (0x3219, '3', '(타)'),\n    (0x321A, '3', '(파)'),\n    (0x321B, '3', '(하)'),\n    (0x321C, '3', '(주)'),\n    (0x321D, '3', '(오전)'),\n    (0x321E, '3', '(오후)'),\n    (0x321F, 'X'),\n    (0x3220, '3', '(一)'),\n    (0x3221, '3', '(二)'),\n    (0x3222, '3', '(三)'),\n    (0x3223, '3', '(四)'),\n    (0x3224, '3', '(五)'),\n    (0x3225, '3', '(六)'),\n    (0x3226, '3', '(七)'),\n    (0x3227, '3', '(八)'),\n    (0x3228, '3', '(九)'),\n    (0x3229, '3', '(十)'),\n    (0x322A, '3', '(月)'),\n    (0x322B, '3', '(火)'),\n    (0x322C, '3', '(水)'),\n    (0x322D, '3', '(木)'),\n    (0x322E, '3', '(金)'),\n    (0x322F, '3', '(土)'),\n    (0x3230, '3', '(日)'),\n    (0x3231, '3', '(株)'),\n    (0x3232, '3', '(有)'),\n    (0x3233, '3', '(社)'),\n    (0x3234, '3', '(名)'),\n    (0x3235, '3', '(特)'),\n    (0x3236, '3', '(財)'),\n    (0x3237, '3', '(祝)'),\n    (0x3238, '3', '(労)'),\n    (0x3239, '3', '(代)'),\n    (0x323A, '3', '(呼)'),\n    (0x323B, '3', '(学)'),\n    (0x323C, '3', '(監)'),\n    (0x323D, '3', '(企)'),\n    (0x323E, '3', '(資)'),\n    (0x323F, '3', '(協)'),\n    (0x3240, '3', '(祭)'),\n    (0x3241, '3', '(休)'),\n    (0x3242, '3', '(自)'),\n    (0x3243, '3', '(至)'),\n    (0x3244, 'M', '問'),\n    (0x3245, 'M', '幼'),\n    (0x3246, 'M', '文'),\n    ]\n\ndef _seg_31() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x3247, 'M', '箏'),\n    (0x3248, 'V'),\n    (0x3250, 'M', 'pte'),\n    (0x3251, 'M', '21'),\n    (0x3252, 'M', '22'),\n    (0x3253, 'M', '23'),\n    (0x3254, 'M', '24'),\n    (0x3255, 'M', '25'),\n    (0x3256, 'M', '26'),\n    (0x3257, 'M', '27'),\n    (0x3258, 'M', '28'),\n    (0x3259, 'M', '29'),\n    (0x325A, 'M', '30'),\n    (0x325B, 'M', '31'),\n    (0x325C, 'M', '32'),\n    (0x325D, 'M', '33'),\n    (0x325E, 'M', '34'),\n    (0x325F, 'M', '35'),\n    (0x3260, 'M', 'ᄀ'),\n    (0x3261, 'M', 'ᄂ'),\n    (0x3262, 'M', 'ᄃ'),\n    (0x3263, 'M', 'ᄅ'),\n    (0x3264, 'M', 'ᄆ'),\n    (0x3265, 'M', 'ᄇ'),\n    (0x3266, 'M', 'ᄉ'),\n    (0x3267, 'M', 'ᄋ'),\n    (0x3268, 'M', 'ᄌ'),\n    (0x3269, 'M', 'ᄎ'),\n    (0x326A, 'M', 'ᄏ'),\n    (0x326B, 'M', 'ᄐ'),\n    (0x326C, 'M', 'ᄑ'),\n    (0x326D, 'M', 'ᄒ'),\n    (0x326E, 'M', '가'),\n    (0x326F, 'M', '나'),\n    (0x3270, 'M', '다'),\n    (0x3271, 'M', '라'),\n    (0x3272, 'M', '마'),\n    (0x3273, 'M', '바'),\n    (0x3274, 'M', '사'),\n    (0x3275, 'M', '아'),\n    (0x3276, 'M', '자'),\n    (0x3277, 'M', '차'),\n    (0x3278, 'M', '카'),\n    (0x3279, 'M', '타'),\n    (0x327A, 'M', '파'),\n    (0x327B, 'M', '하'),\n    (0x327C, 'M', '참고'),\n    (0x327D, 'M', '주의'),\n    (0x327E, 'M', '우'),\n    (0x327F, 'V'),\n    (0x3280, 'M', '一'),\n    (0x3281, 'M', '二'),\n    (0x3282, 'M', '三'),\n    (0x3283, 'M', '四'),\n    (0x3284, 'M', '五'),\n    (0x3285, 'M', '六'),\n    (0x3286, 'M', '七'),\n    (0x3287, 'M', '八'),\n    (0x3288, 'M', '九'),\n    (0x3289, 'M', '十'),\n    (0x328A, 'M', '月'),\n    (0x328B, 'M', '火'),\n    (0x328C, 'M', '水'),\n    (0x328D, 'M', '木'),\n    (0x328E, 'M', '金'),\n    (0x328F, 'M', '土'),\n    (0x3290, 'M', '日'),\n    (0x3291, 'M', '株'),\n    (0x3292, 'M', '有'),\n    (0x3293, 'M', '社'),\n    (0x3294, 'M', '名'),\n    (0x3295, 'M', '特'),\n    (0x3296, 'M', '財'),\n    (0x3297, 'M', '祝'),\n    (0x3298, 'M', '労'),\n    (0x3299, 'M', '秘'),\n    (0x329A, 'M', '男'),\n    (0x329B, 'M', '女'),\n    (0x329C, 'M', '適'),\n    (0x329D, 'M', '優'),\n    (0x329E, 'M', '印'),\n    (0x329F, 'M', '注'),\n    (0x32A0, 'M', '項'),\n    (0x32A1, 'M', '休'),\n    (0x32A2, 'M', '写'),\n    (0x32A3, 'M', '正'),\n    (0x32A4, 'M', '上'),\n    (0x32A5, 'M', '中'),\n    (0x32A6, 'M', '下'),\n    (0x32A7, 'M', '左'),\n    (0x32A8, 'M', '右'),\n    (0x32A9, 'M', '医'),\n    (0x32AA, 'M', '宗'),\n    (0x32AB, 'M', '学'),\n    (0x32AC, 'M', '監'),\n    (0x32AD, 'M', '企'),\n    (0x32AE, 'M', '資'),\n    (0x32AF, 'M', '協'),\n    (0x32B0, 'M', '夜'),\n    (0x32B1, 'M', '36'),\n    ]\n\ndef _seg_32() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x32B2, 'M', '37'),\n    (0x32B3, 'M', '38'),\n    (0x32B4, 'M', '39'),\n    (0x32B5, 'M', '40'),\n    (0x32B6, 'M', '41'),\n    (0x32B7, 'M', '42'),\n    (0x32B8, 'M', '43'),\n    (0x32B9, 'M', '44'),\n    (0x32BA, 'M', '45'),\n    (0x32BB, 'M', '46'),\n    (0x32BC, 'M', '47'),\n    (0x32BD, 'M', '48'),\n    (0x32BE, 'M', '49'),\n    (0x32BF, 'M', '50'),\n    (0x32C0, 'M', '1月'),\n    (0x32C1, 'M', '2月'),\n    (0x32C2, 'M', '3月'),\n    (0x32C3, 'M', '4月'),\n    (0x32C4, 'M', '5月'),\n    (0x32C5, 'M', '6月'),\n    (0x32C6, 'M', '7月'),\n    (0x32C7, 'M', '8月'),\n    (0x32C8, 'M', '9月'),\n    (0x32C9, 'M', '10月'),\n    (0x32CA, 'M', '11月'),\n    (0x32CB, 'M', '12月'),\n    (0x32CC, 'M', 'hg'),\n    (0x32CD, 'M', 'erg'),\n    (0x32CE, 'M', 'ev'),\n    (0x32CF, 'M', 'ltd'),\n    (0x32D0, 'M', 'ア'),\n    (0x32D1, 'M', 'イ'),\n    (0x32D2, 'M', 'ウ'),\n    (0x32D3, 'M', 'エ'),\n    (0x32D4, 'M', 'オ'),\n    (0x32D5, 'M', 'カ'),\n    (0x32D6, 'M', 'キ'),\n    (0x32D7, 'M', 'ク'),\n    (0x32D8, 'M', 'ケ'),\n    (0x32D9, 'M', 'コ'),\n    (0x32DA, 'M', 'サ'),\n    (0x32DB, 'M', 'シ'),\n    (0x32DC, 'M', 'ス'),\n    (0x32DD, 'M', 'セ'),\n    (0x32DE, 'M', 'ソ'),\n    (0x32DF, 'M', 'タ'),\n    (0x32E0, 'M', 'チ'),\n    (0x32E1, 'M', 'ツ'),\n    (0x32E2, 'M', 'テ'),\n    (0x32E3, 'M', 'ト'),\n    (0x32E4, 'M', 'ナ'),\n    (0x32E5, 'M', 'ニ'),\n    (0x32E6, 'M', 'ヌ'),\n    (0x32E7, 'M', 'ネ'),\n    (0x32E8, 'M', 'ノ'),\n    (0x32E9, 'M', 'ハ'),\n    (0x32EA, 'M', 'ヒ'),\n    (0x32EB, 'M', 'フ'),\n    (0x32EC, 'M', 'ヘ'),\n    (0x32ED, 'M', 'ホ'),\n    (0x32EE, 'M', 'マ'),\n    (0x32EF, 'M', 'ミ'),\n    (0x32F0, 'M', 'ム'),\n    (0x32F1, 'M', 'メ'),\n    (0x32F2, 'M', 'モ'),\n    (0x32F3, 'M', 'ヤ'),\n    (0x32F4, 'M', 'ユ'),\n    (0x32F5, 'M', 'ヨ'),\n    (0x32F6, 'M', 'ラ'),\n    (0x32F7, 'M', 'リ'),\n    (0x32F8, 'M', 'ル'),\n    (0x32F9, 'M', 'レ'),\n    (0x32FA, 'M', 'ロ'),\n    (0x32FB, 'M', 'ワ'),\n    (0x32FC, 'M', 'ヰ'),\n    (0x32FD, 'M', 'ヱ'),\n    (0x32FE, 'M', 'ヲ'),\n    (0x32FF, 'M', '令和'),\n    (0x3300, 'M', 'アパート'),\n    (0x3301, 'M', 'アルファ'),\n    (0x3302, 'M', 'アンペア'),\n    (0x3303, 'M', 'アール'),\n    (0x3304, 'M', 'イニング'),\n    (0x3305, 'M', 'インチ'),\n    (0x3306, 'M', 'ウォン'),\n    (0x3307, 'M', 'エスクード'),\n    (0x3308, 'M', 'エーカー'),\n    (0x3309, 'M', 'オンス'),\n    (0x330A, 'M', 'オーム'),\n    (0x330B, 'M', 'カイリ'),\n    (0x330C, 'M', 'カラット'),\n    (0x330D, 'M', 'カロリー'),\n    (0x330E, 'M', 'ガロン'),\n    (0x330F, 'M', 'ガンマ'),\n    (0x3310, 'M', 'ギガ'),\n    (0x3311, 'M', 'ギニー'),\n    (0x3312, 'M', 'キュリー'),\n    (0x3313, 'M', 'ギルダー'),\n    (0x3314, 'M', 'キロ'),\n    (0x3315, 'M', 'キログラム'),\n    ]\n\ndef _seg_33() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x3316, 'M', 'キロメートル'),\n    (0x3317, 'M', 'キロワット'),\n    (0x3318, 'M', 'グラム'),\n    (0x3319, 'M', 'グラムトン'),\n    (0x331A, 'M', 'クルゼイロ'),\n    (0x331B, 'M', 'クローネ'),\n    (0x331C, 'M', 'ケース'),\n    (0x331D, 'M', 'コルナ'),\n    (0x331E, 'M', 'コーポ'),\n    (0x331F, 'M', 'サイクル'),\n    (0x3320, 'M', 'サンチーム'),\n    (0x3321, 'M', 'シリング'),\n    (0x3322, 'M', 'センチ'),\n    (0x3323, 'M', 'セント'),\n    (0x3324, 'M', 'ダース'),\n    (0x3325, 'M', 'デシ'),\n    (0x3326, 'M', 'ドル'),\n    (0x3327, 'M', 'トン'),\n    (0x3328, 'M', 'ナノ'),\n    (0x3329, 'M', 'ノット'),\n    (0x332A, 'M', 'ハイツ'),\n    (0x332B, 'M', 'パーセント'),\n    (0x332C, 'M', 'パーツ'),\n    (0x332D, 'M', 'バーレル'),\n    (0x332E, 'M', 'ピアストル'),\n    (0x332F, 'M', 'ピクル'),\n    (0x3330, 'M', 'ピコ'),\n    (0x3331, 'M', 'ビル'),\n    (0x3332, 'M', 'ファラッド'),\n    (0x3333, 'M', 'フィート'),\n    (0x3334, 'M', 'ブッシェル'),\n    (0x3335, 'M', 'フラン'),\n    (0x3336, 'M', 'ヘクタール'),\n    (0x3337, 'M', 'ペソ'),\n    (0x3338, 'M', 'ペニヒ'),\n    (0x3339, 'M', 'ヘルツ'),\n    (0x333A, 'M', 'ペンス'),\n    (0x333B, 'M', 'ページ'),\n    (0x333C, 'M', 'ベータ'),\n    (0x333D, 'M', 'ポイント'),\n    (0x333E, 'M', 'ボルト'),\n    (0x333F, 'M', 'ホン'),\n    (0x3340, 'M', 'ポンド'),\n    (0x3341, 'M', 'ホール'),\n    (0x3342, 'M', 'ホーン'),\n    (0x3343, 'M', 'マイクロ'),\n    (0x3344, 'M', 'マイル'),\n    (0x3345, 'M', 'マッハ'),\n    (0x3346, 'M', 'マルク'),\n    (0x3347, 'M', 'マンション'),\n    (0x3348, 'M', 'ミクロン'),\n    (0x3349, 'M', 'ミリ'),\n    (0x334A, 'M', 'ミリバール'),\n    (0x334B, 'M', 'メガ'),\n    (0x334C, 'M', 'メガトン'),\n    (0x334D, 'M', 'メートル'),\n    (0x334E, 'M', 'ヤード'),\n    (0x334F, 'M', 'ヤール'),\n    (0x3350, 'M', 'ユアン'),\n    (0x3351, 'M', 'リットル'),\n    (0x3352, 'M', 'リラ'),\n    (0x3353, 'M', 'ルピー'),\n    (0x3354, 'M', 'ルーブル'),\n    (0x3355, 'M', 'レム'),\n    (0x3356, 'M', 'レントゲン'),\n    (0x3357, 'M', 'ワット'),\n    (0x3358, 'M', '0点'),\n    (0x3359, 'M', '1点'),\n    (0x335A, 'M', '2点'),\n    (0x335B, 'M', '3点'),\n    (0x335C, 'M', '4点'),\n    (0x335D, 'M', '5点'),\n    (0x335E, 'M', '6点'),\n    (0x335F, 'M', '7点'),\n    (0x3360, 'M', '8点'),\n    (0x3361, 'M', '9点'),\n    (0x3362, 'M', '10点'),\n    (0x3363, 'M', '11点'),\n    (0x3364, 'M', '12点'),\n    (0x3365, 'M', '13点'),\n    (0x3366, 'M', '14点'),\n    (0x3367, 'M', '15点'),\n    (0x3368, 'M', '16点'),\n    (0x3369, 'M', '17点'),\n    (0x336A, 'M', '18点'),\n    (0x336B, 'M', '19点'),\n    (0x336C, 'M', '20点'),\n    (0x336D, 'M', '21点'),\n    (0x336E, 'M', '22点'),\n    (0x336F, 'M', '23点'),\n    (0x3370, 'M', '24点'),\n    (0x3371, 'M', 'hpa'),\n    (0x3372, 'M', 'da'),\n    (0x3373, 'M', 'au'),\n    (0x3374, 'M', 'bar'),\n    (0x3375, 'M', 'ov'),\n    (0x3376, 'M', 'pc'),\n    (0x3377, 'M', 'dm'),\n    (0x3378, 'M', 'dm2'),\n    (0x3379, 'M', 'dm3'),\n    ]\n\ndef _seg_34() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x337A, 'M', 'iu'),\n    (0x337B, 'M', '平成'),\n    (0x337C, 'M', '昭和'),\n    (0x337D, 'M', '大正'),\n    (0x337E, 'M', '明治'),\n    (0x337F, 'M', '株式会社'),\n    (0x3380, 'M', 'pa'),\n    (0x3381, 'M', 'na'),\n    (0x3382, 'M', 'μa'),\n    (0x3383, 'M', 'ma'),\n    (0x3384, 'M', 'ka'),\n    (0x3385, 'M', 'kb'),\n    (0x3386, 'M', 'mb'),\n    (0x3387, 'M', 'gb'),\n    (0x3388, 'M', 'cal'),\n    (0x3389, 'M', 'kcal'),\n    (0x338A, 'M', 'pf'),\n    (0x338B, 'M', 'nf'),\n    (0x338C, 'M', 'μf'),\n    (0x338D, 'M', 'μg'),\n    (0x338E, 'M', 'mg'),\n    (0x338F, 'M', 'kg'),\n    (0x3390, 'M', 'hz'),\n    (0x3391, 'M', 'khz'),\n    (0x3392, 'M', 'mhz'),\n    (0x3393, 'M', 'ghz'),\n    (0x3394, 'M', 'thz'),\n    (0x3395, 'M', 'μl'),\n    (0x3396, 'M', 'ml'),\n    (0x3397, 'M', 'dl'),\n    (0x3398, 'M', 'kl'),\n    (0x3399, 'M', 'fm'),\n    (0x339A, 'M', 'nm'),\n    (0x339B, 'M', 'μm'),\n    (0x339C, 'M', 'mm'),\n    (0x339D, 'M', 'cm'),\n    (0x339E, 'M', 'km'),\n    (0x339F, 'M', 'mm2'),\n    (0x33A0, 'M', 'cm2'),\n    (0x33A1, 'M', 'm2'),\n    (0x33A2, 'M', 'km2'),\n    (0x33A3, 'M', 'mm3'),\n    (0x33A4, 'M', 'cm3'),\n    (0x33A5, 'M', 'm3'),\n    (0x33A6, 'M', 'km3'),\n    (0x33A7, 'M', 'm∕s'),\n    (0x33A8, 'M', 'm∕s2'),\n    (0x33A9, 'M', 'pa'),\n    (0x33AA, 'M', 'kpa'),\n    (0x33AB, 'M', 'mpa'),\n    (0x33AC, 'M', 'gpa'),\n    (0x33AD, 'M', 'rad'),\n    (0x33AE, 'M', 'rad∕s'),\n    (0x33AF, 'M', 'rad∕s2'),\n    (0x33B0, 'M', 'ps'),\n    (0x33B1, 'M', 'ns'),\n    (0x33B2, 'M', 'μs'),\n    (0x33B3, 'M', 'ms'),\n    (0x33B4, 'M', 'pv'),\n    (0x33B5, 'M', 'nv'),\n    (0x33B6, 'M', 'μv'),\n    (0x33B7, 'M', 'mv'),\n    (0x33B8, 'M', 'kv'),\n    (0x33B9, 'M', 'mv'),\n    (0x33BA, 'M', 'pw'),\n    (0x33BB, 'M', 'nw'),\n    (0x33BC, 'M', 'μw'),\n    (0x33BD, 'M', 'mw'),\n    (0x33BE, 'M', 'kw'),\n    (0x33BF, 'M', 'mw'),\n    (0x33C0, 'M', 'kω'),\n    (0x33C1, 'M', 'mω'),\n    (0x33C2, 'X'),\n    (0x33C3, 'M', 'bq'),\n    (0x33C4, 'M', 'cc'),\n    (0x33C5, 'M', 'cd'),\n    (0x33C6, 'M', 'c∕kg'),\n    (0x33C7, 'X'),\n    (0x33C8, 'M', 'db'),\n    (0x33C9, 'M', 'gy'),\n    (0x33CA, 'M', 'ha'),\n    (0x33CB, 'M', 'hp'),\n    (0x33CC, 'M', 'in'),\n    (0x33CD, 'M', 'kk'),\n    (0x33CE, 'M', 'km'),\n    (0x33CF, 'M', 'kt'),\n    (0x33D0, 'M', 'lm'),\n    (0x33D1, 'M', 'ln'),\n    (0x33D2, 'M', 'log'),\n    (0x33D3, 'M', 'lx'),\n    (0x33D4, 'M', 'mb'),\n    (0x33D5, 'M', 'mil'),\n    (0x33D6, 'M', 'mol'),\n    (0x33D7, 'M', 'ph'),\n    (0x33D8, 'X'),\n    (0x33D9, 'M', 'ppm'),\n    (0x33DA, 'M', 'pr'),\n    (0x33DB, 'M', 'sr'),\n    (0x33DC, 'M', 'sv'),\n    (0x33DD, 'M', 'wb'),\n    ]\n\ndef _seg_35() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x33DE, 'M', 'v∕m'),\n    (0x33DF, 'M', 'a∕m'),\n    (0x33E0, 'M', '1日'),\n    (0x33E1, 'M', '2日'),\n    (0x33E2, 'M', '3日'),\n    (0x33E3, 'M', '4日'),\n    (0x33E4, 'M', '5日'),\n    (0x33E5, 'M', '6日'),\n    (0x33E6, 'M', '7日'),\n    (0x33E7, 'M', '8日'),\n    (0x33E8, 'M', '9日'),\n    (0x33E9, 'M', '10日'),\n    (0x33EA, 'M', '11日'),\n    (0x33EB, 'M', '12日'),\n    (0x33EC, 'M', '13日'),\n    (0x33ED, 'M', '14日'),\n    (0x33EE, 'M', '15日'),\n    (0x33EF, 'M', '16日'),\n    (0x33F0, 'M', '17日'),\n    (0x33F1, 'M', '18日'),\n    (0x33F2, 'M', '19日'),\n    (0x33F3, 'M', '20日'),\n    (0x33F4, 'M', '21日'),\n    (0x33F5, 'M', '22日'),\n    (0x33F6, 'M', '23日'),\n    (0x33F7, 'M', '24日'),\n    (0x33F8, 'M', '25日'),\n    (0x33F9, 'M', '26日'),\n    (0x33FA, 'M', '27日'),\n    (0x33FB, 'M', '28日'),\n    (0x33FC, 'M', '29日'),\n    (0x33FD, 'M', '30日'),\n    (0x33FE, 'M', '31日'),\n    (0x33FF, 'M', 'gal'),\n    (0x3400, 'V'),\n    (0xA48D, 'X'),\n    (0xA490, 'V'),\n    (0xA4C7, 'X'),\n    (0xA4D0, 'V'),\n    (0xA62C, 'X'),\n    (0xA640, 'M', 'ꙁ'),\n    (0xA641, 'V'),\n    (0xA642, 'M', 'ꙃ'),\n    (0xA643, 'V'),\n    (0xA644, 'M', 'ꙅ'),\n    (0xA645, 'V'),\n    (0xA646, 'M', 'ꙇ'),\n    (0xA647, 'V'),\n    (0xA648, 'M', 'ꙉ'),\n    (0xA649, 'V'),\n    (0xA64A, 'M', 'ꙋ'),\n    (0xA64B, 'V'),\n    (0xA64C, 'M', 'ꙍ'),\n    (0xA64D, 'V'),\n    (0xA64E, 'M', 'ꙏ'),\n    (0xA64F, 'V'),\n    (0xA650, 'M', 'ꙑ'),\n    (0xA651, 'V'),\n    (0xA652, 'M', 'ꙓ'),\n    (0xA653, 'V'),\n    (0xA654, 'M', 'ꙕ'),\n    (0xA655, 'V'),\n    (0xA656, 'M', 'ꙗ'),\n    (0xA657, 'V'),\n    (0xA658, 'M', 'ꙙ'),\n    (0xA659, 'V'),\n    (0xA65A, 'M', 'ꙛ'),\n    (0xA65B, 'V'),\n    (0xA65C, 'M', 'ꙝ'),\n    (0xA65D, 'V'),\n    (0xA65E, 'M', 'ꙟ'),\n    (0xA65F, 'V'),\n    (0xA660, 'M', 'ꙡ'),\n    (0xA661, 'V'),\n    (0xA662, 'M', 'ꙣ'),\n    (0xA663, 'V'),\n    (0xA664, 'M', 'ꙥ'),\n    (0xA665, 'V'),\n    (0xA666, 'M', 'ꙧ'),\n    (0xA667, 'V'),\n    (0xA668, 'M', 'ꙩ'),\n    (0xA669, 'V'),\n    (0xA66A, 'M', 'ꙫ'),\n    (0xA66B, 'V'),\n    (0xA66C, 'M', 'ꙭ'),\n    (0xA66D, 'V'),\n    (0xA680, 'M', 'ꚁ'),\n    (0xA681, 'V'),\n    (0xA682, 'M', 'ꚃ'),\n    (0xA683, 'V'),\n    (0xA684, 'M', 'ꚅ'),\n    (0xA685, 'V'),\n    (0xA686, 'M', 'ꚇ'),\n    (0xA687, 'V'),\n    (0xA688, 'M', 'ꚉ'),\n    (0xA689, 'V'),\n    (0xA68A, 'M', 'ꚋ'),\n    (0xA68B, 'V'),\n    (0xA68C, 'M', 'ꚍ'),\n    (0xA68D, 'V'),\n    ]\n\ndef _seg_36() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xA68E, 'M', 'ꚏ'),\n    (0xA68F, 'V'),\n    (0xA690, 'M', 'ꚑ'),\n    (0xA691, 'V'),\n    (0xA692, 'M', 'ꚓ'),\n    (0xA693, 'V'),\n    (0xA694, 'M', 'ꚕ'),\n    (0xA695, 'V'),\n    (0xA696, 'M', 'ꚗ'),\n    (0xA697, 'V'),\n    (0xA698, 'M', 'ꚙ'),\n    (0xA699, 'V'),\n    (0xA69A, 'M', 'ꚛ'),\n    (0xA69B, 'V'),\n    (0xA69C, 'M', 'ъ'),\n    (0xA69D, 'M', 'ь'),\n    (0xA69E, 'V'),\n    (0xA6F8, 'X'),\n    (0xA700, 'V'),\n    (0xA722, 'M', 'ꜣ'),\n    (0xA723, 'V'),\n    (0xA724, 'M', 'ꜥ'),\n    (0xA725, 'V'),\n    (0xA726, 'M', 'ꜧ'),\n    (0xA727, 'V'),\n    (0xA728, 'M', 'ꜩ'),\n    (0xA729, 'V'),\n    (0xA72A, 'M', 'ꜫ'),\n    (0xA72B, 'V'),\n    (0xA72C, 'M', 'ꜭ'),\n    (0xA72D, 'V'),\n    (0xA72E, 'M', 'ꜯ'),\n    (0xA72F, 'V'),\n    (0xA732, 'M', 'ꜳ'),\n    (0xA733, 'V'),\n    (0xA734, 'M', 'ꜵ'),\n    (0xA735, 'V'),\n    (0xA736, 'M', 'ꜷ'),\n    (0xA737, 'V'),\n    (0xA738, 'M', 'ꜹ'),\n    (0xA739, 'V'),\n    (0xA73A, 'M', 'ꜻ'),\n    (0xA73B, 'V'),\n    (0xA73C, 'M', 'ꜽ'),\n    (0xA73D, 'V'),\n    (0xA73E, 'M', 'ꜿ'),\n    (0xA73F, 'V'),\n    (0xA740, 'M', 'ꝁ'),\n    (0xA741, 'V'),\n    (0xA742, 'M', 'ꝃ'),\n    (0xA743, 'V'),\n    (0xA744, 'M', 'ꝅ'),\n    (0xA745, 'V'),\n    (0xA746, 'M', 'ꝇ'),\n    (0xA747, 'V'),\n    (0xA748, 'M', 'ꝉ'),\n    (0xA749, 'V'),\n    (0xA74A, 'M', 'ꝋ'),\n    (0xA74B, 'V'),\n    (0xA74C, 'M', 'ꝍ'),\n    (0xA74D, 'V'),\n    (0xA74E, 'M', 'ꝏ'),\n    (0xA74F, 'V'),\n    (0xA750, 'M', 'ꝑ'),\n    (0xA751, 'V'),\n    (0xA752, 'M', 'ꝓ'),\n    (0xA753, 'V'),\n    (0xA754, 'M', 'ꝕ'),\n    (0xA755, 'V'),\n    (0xA756, 'M', 'ꝗ'),\n    (0xA757, 'V'),\n    (0xA758, 'M', 'ꝙ'),\n    (0xA759, 'V'),\n    (0xA75A, 'M', 'ꝛ'),\n    (0xA75B, 'V'),\n    (0xA75C, 'M', 'ꝝ'),\n    (0xA75D, 'V'),\n    (0xA75E, 'M', 'ꝟ'),\n    (0xA75F, 'V'),\n    (0xA760, 'M', 'ꝡ'),\n    (0xA761, 'V'),\n    (0xA762, 'M', 'ꝣ'),\n    (0xA763, 'V'),\n    (0xA764, 'M', 'ꝥ'),\n    (0xA765, 'V'),\n    (0xA766, 'M', 'ꝧ'),\n    (0xA767, 'V'),\n    (0xA768, 'M', 'ꝩ'),\n    (0xA769, 'V'),\n    (0xA76A, 'M', 'ꝫ'),\n    (0xA76B, 'V'),\n    (0xA76C, 'M', 'ꝭ'),\n    (0xA76D, 'V'),\n    (0xA76E, 'M', 'ꝯ'),\n    (0xA76F, 'V'),\n    (0xA770, 'M', 'ꝯ'),\n    (0xA771, 'V'),\n    (0xA779, 'M', 'ꝺ'),\n    (0xA77A, 'V'),\n    (0xA77B, 'M', 'ꝼ'),\n    ]\n\ndef _seg_37() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xA77C, 'V'),\n    (0xA77D, 'M', 'ᵹ'),\n    (0xA77E, 'M', 'ꝿ'),\n    (0xA77F, 'V'),\n    (0xA780, 'M', 'ꞁ'),\n    (0xA781, 'V'),\n    (0xA782, 'M', 'ꞃ'),\n    (0xA783, 'V'),\n    (0xA784, 'M', 'ꞅ'),\n    (0xA785, 'V'),\n    (0xA786, 'M', 'ꞇ'),\n    (0xA787, 'V'),\n    (0xA78B, 'M', 'ꞌ'),\n    (0xA78C, 'V'),\n    (0xA78D, 'M', 'ɥ'),\n    (0xA78E, 'V'),\n    (0xA790, 'M', 'ꞑ'),\n    (0xA791, 'V'),\n    (0xA792, 'M', 'ꞓ'),\n    (0xA793, 'V'),\n    (0xA796, 'M', 'ꞗ'),\n    (0xA797, 'V'),\n    (0xA798, 'M', 'ꞙ'),\n    (0xA799, 'V'),\n    (0xA79A, 'M', 'ꞛ'),\n    (0xA79B, 'V'),\n    (0xA79C, 'M', 'ꞝ'),\n    (0xA79D, 'V'),\n    (0xA79E, 'M', 'ꞟ'),\n    (0xA79F, 'V'),\n    (0xA7A0, 'M', 'ꞡ'),\n    (0xA7A1, 'V'),\n    (0xA7A2, 'M', 'ꞣ'),\n    (0xA7A3, 'V'),\n    (0xA7A4, 'M', 'ꞥ'),\n    (0xA7A5, 'V'),\n    (0xA7A6, 'M', 'ꞧ'),\n    (0xA7A7, 'V'),\n    (0xA7A8, 'M', 'ꞩ'),\n    (0xA7A9, 'V'),\n    (0xA7AA, 'M', 'ɦ'),\n    (0xA7AB, 'M', 'ɜ'),\n    (0xA7AC, 'M', 'ɡ'),\n    (0xA7AD, 'M', 'ɬ'),\n    (0xA7AE, 'M', 'ɪ'),\n    (0xA7AF, 'V'),\n    (0xA7B0, 'M', 'ʞ'),\n    (0xA7B1, 'M', 'ʇ'),\n    (0xA7B2, 'M', 'ʝ'),\n    (0xA7B3, 'M', 'ꭓ'),\n    (0xA7B4, 'M', 'ꞵ'),\n    (0xA7B5, 'V'),\n    (0xA7B6, 'M', 'ꞷ'),\n    (0xA7B7, 'V'),\n    (0xA7B8, 'M', 'ꞹ'),\n    (0xA7B9, 'V'),\n    (0xA7BA, 'M', 'ꞻ'),\n    (0xA7BB, 'V'),\n    (0xA7BC, 'M', 'ꞽ'),\n    (0xA7BD, 'V'),\n    (0xA7BE, 'M', 'ꞿ'),\n    (0xA7BF, 'V'),\n    (0xA7C0, 'M', 'ꟁ'),\n    (0xA7C1, 'V'),\n    (0xA7C2, 'M', 'ꟃ'),\n    (0xA7C3, 'V'),\n    (0xA7C4, 'M', 'ꞔ'),\n    (0xA7C5, 'M', 'ʂ'),\n    (0xA7C6, 'M', 'ᶎ'),\n    (0xA7C7, 'M', 'ꟈ'),\n    (0xA7C8, 'V'),\n    (0xA7C9, 'M', 'ꟊ'),\n    (0xA7CA, 'V'),\n    (0xA7CB, 'X'),\n    (0xA7D0, 'M', 'ꟑ'),\n    (0xA7D1, 'V'),\n    (0xA7D2, 'X'),\n    (0xA7D3, 'V'),\n    (0xA7D4, 'X'),\n    (0xA7D5, 'V'),\n    (0xA7D6, 'M', 'ꟗ'),\n    (0xA7D7, 'V'),\n    (0xA7D8, 'M', 'ꟙ'),\n    (0xA7D9, 'V'),\n    (0xA7DA, 'X'),\n    (0xA7F2, 'M', 'c'),\n    (0xA7F3, 'M', 'f'),\n    (0xA7F4, 'M', 'q'),\n    (0xA7F5, 'M', 'ꟶ'),\n    (0xA7F6, 'V'),\n    (0xA7F8, 'M', 'ħ'),\n    (0xA7F9, 'M', 'œ'),\n    (0xA7FA, 'V'),\n    (0xA82D, 'X'),\n    (0xA830, 'V'),\n    (0xA83A, 'X'),\n    (0xA840, 'V'),\n    (0xA878, 'X'),\n    (0xA880, 'V'),\n    (0xA8C6, 'X'),\n    ]\n\ndef _seg_38() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xA8CE, 'V'),\n    (0xA8DA, 'X'),\n    (0xA8E0, 'V'),\n    (0xA954, 'X'),\n    (0xA95F, 'V'),\n    (0xA97D, 'X'),\n    (0xA980, 'V'),\n    (0xA9CE, 'X'),\n    (0xA9CF, 'V'),\n    (0xA9DA, 'X'),\n    (0xA9DE, 'V'),\n    (0xA9FF, 'X'),\n    (0xAA00, 'V'),\n    (0xAA37, 'X'),\n    (0xAA40, 'V'),\n    (0xAA4E, 'X'),\n    (0xAA50, 'V'),\n    (0xAA5A, 'X'),\n    (0xAA5C, 'V'),\n    (0xAAC3, 'X'),\n    (0xAADB, 'V'),\n    (0xAAF7, 'X'),\n    (0xAB01, 'V'),\n    (0xAB07, 'X'),\n    (0xAB09, 'V'),\n    (0xAB0F, 'X'),\n    (0xAB11, 'V'),\n    (0xAB17, 'X'),\n    (0xAB20, 'V'),\n    (0xAB27, 'X'),\n    (0xAB28, 'V'),\n    (0xAB2F, 'X'),\n    (0xAB30, 'V'),\n    (0xAB5C, 'M', 'ꜧ'),\n    (0xAB5D, 'M', 'ꬷ'),\n    (0xAB5E, 'M', 'ɫ'),\n    (0xAB5F, 'M', 'ꭒ'),\n    (0xAB60, 'V'),\n    (0xAB69, 'M', 'ʍ'),\n    (0xAB6A, 'V'),\n    (0xAB6C, 'X'),\n    (0xAB70, 'M', 'Ꭰ'),\n    (0xAB71, 'M', 'Ꭱ'),\n    (0xAB72, 'M', 'Ꭲ'),\n    (0xAB73, 'M', 'Ꭳ'),\n    (0xAB74, 'M', 'Ꭴ'),\n    (0xAB75, 'M', 'Ꭵ'),\n    (0xAB76, 'M', 'Ꭶ'),\n    (0xAB77, 'M', 'Ꭷ'),\n    (0xAB78, 'M', 'Ꭸ'),\n    (0xAB79, 'M', 'Ꭹ'),\n    (0xAB7A, 'M', 'Ꭺ'),\n    (0xAB7B, 'M', 'Ꭻ'),\n    (0xAB7C, 'M', 'Ꭼ'),\n    (0xAB7D, 'M', 'Ꭽ'),\n    (0xAB7E, 'M', 'Ꭾ'),\n    (0xAB7F, 'M', 'Ꭿ'),\n    (0xAB80, 'M', 'Ꮀ'),\n    (0xAB81, 'M', 'Ꮁ'),\n    (0xAB82, 'M', 'Ꮂ'),\n    (0xAB83, 'M', 'Ꮃ'),\n    (0xAB84, 'M', 'Ꮄ'),\n    (0xAB85, 'M', 'Ꮅ'),\n    (0xAB86, 'M', 'Ꮆ'),\n    (0xAB87, 'M', 'Ꮇ'),\n    (0xAB88, 'M', 'Ꮈ'),\n    (0xAB89, 'M', 'Ꮉ'),\n    (0xAB8A, 'M', 'Ꮊ'),\n    (0xAB8B, 'M', 'Ꮋ'),\n    (0xAB8C, 'M', 'Ꮌ'),\n    (0xAB8D, 'M', 'Ꮍ'),\n    (0xAB8E, 'M', 'Ꮎ'),\n    (0xAB8F, 'M', 'Ꮏ'),\n    (0xAB90, 'M', 'Ꮐ'),\n    (0xAB91, 'M', 'Ꮑ'),\n    (0xAB92, 'M', 'Ꮒ'),\n    (0xAB93, 'M', 'Ꮓ'),\n    (0xAB94, 'M', 'Ꮔ'),\n    (0xAB95, 'M', 'Ꮕ'),\n    (0xAB96, 'M', 'Ꮖ'),\n    (0xAB97, 'M', 'Ꮗ'),\n    (0xAB98, 'M', 'Ꮘ'),\n    (0xAB99, 'M', 'Ꮙ'),\n    (0xAB9A, 'M', 'Ꮚ'),\n    (0xAB9B, 'M', 'Ꮛ'),\n    (0xAB9C, 'M', 'Ꮜ'),\n    (0xAB9D, 'M', 'Ꮝ'),\n    (0xAB9E, 'M', 'Ꮞ'),\n    (0xAB9F, 'M', 'Ꮟ'),\n    (0xABA0, 'M', 'Ꮠ'),\n    (0xABA1, 'M', 'Ꮡ'),\n    (0xABA2, 'M', 'Ꮢ'),\n    (0xABA3, 'M', 'Ꮣ'),\n    (0xABA4, 'M', 'Ꮤ'),\n    (0xABA5, 'M', 'Ꮥ'),\n    (0xABA6, 'M', 'Ꮦ'),\n    (0xABA7, 'M', 'Ꮧ'),\n    (0xABA8, 'M', 'Ꮨ'),\n    (0xABA9, 'M', 'Ꮩ'),\n    (0xABAA, 'M', 'Ꮪ'),\n    ]\n\ndef _seg_39() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xABAB, 'M', 'Ꮫ'),\n    (0xABAC, 'M', 'Ꮬ'),\n    (0xABAD, 'M', 'Ꮭ'),\n    (0xABAE, 'M', 'Ꮮ'),\n    (0xABAF, 'M', 'Ꮯ'),\n    (0xABB0, 'M', 'Ꮰ'),\n    (0xABB1, 'M', 'Ꮱ'),\n    (0xABB2, 'M', 'Ꮲ'),\n    (0xABB3, 'M', 'Ꮳ'),\n    (0xABB4, 'M', 'Ꮴ'),\n    (0xABB5, 'M', 'Ꮵ'),\n    (0xABB6, 'M', 'Ꮶ'),\n    (0xABB7, 'M', 'Ꮷ'),\n    (0xABB8, 'M', 'Ꮸ'),\n    (0xABB9, 'M', 'Ꮹ'),\n    (0xABBA, 'M', 'Ꮺ'),\n    (0xABBB, 'M', 'Ꮻ'),\n    (0xABBC, 'M', 'Ꮼ'),\n    (0xABBD, 'M', 'Ꮽ'),\n    (0xABBE, 'M', 'Ꮾ'),\n    (0xABBF, 'M', 'Ꮿ'),\n    (0xABC0, 'V'),\n    (0xABEE, 'X'),\n    (0xABF0, 'V'),\n    (0xABFA, 'X'),\n    (0xAC00, 'V'),\n    (0xD7A4, 'X'),\n    (0xD7B0, 'V'),\n    (0xD7C7, 'X'),\n    (0xD7CB, 'V'),\n    (0xD7FC, 'X'),\n    (0xF900, 'M', '豈'),\n    (0xF901, 'M', '更'),\n    (0xF902, 'M', '車'),\n    (0xF903, 'M', '賈'),\n    (0xF904, 'M', '滑'),\n    (0xF905, 'M', '串'),\n    (0xF906, 'M', '句'),\n    (0xF907, 'M', '龜'),\n    (0xF909, 'M', '契'),\n    (0xF90A, 'M', '金'),\n    (0xF90B, 'M', '喇'),\n    (0xF90C, 'M', '奈'),\n    (0xF90D, 'M', '懶'),\n    (0xF90E, 'M', '癩'),\n    (0xF90F, 'M', '羅'),\n    (0xF910, 'M', '蘿'),\n    (0xF911, 'M', '螺'),\n    (0xF912, 'M', '裸'),\n    (0xF913, 'M', '邏'),\n    (0xF914, 'M', '樂'),\n    (0xF915, 'M', '洛'),\n    (0xF916, 'M', '烙'),\n    (0xF917, 'M', '珞'),\n    (0xF918, 'M', '落'),\n    (0xF919, 'M', '酪'),\n    (0xF91A, 'M', '駱'),\n    (0xF91B, 'M', '亂'),\n    (0xF91C, 'M', '卵'),\n    (0xF91D, 'M', '欄'),\n    (0xF91E, 'M', '爛'),\n    (0xF91F, 'M', '蘭'),\n    (0xF920, 'M', '鸞'),\n    (0xF921, 'M', '嵐'),\n    (0xF922, 'M', '濫'),\n    (0xF923, 'M', '藍'),\n    (0xF924, 'M', '襤'),\n    (0xF925, 'M', '拉'),\n    (0xF926, 'M', '臘'),\n    (0xF927, 'M', '蠟'),\n    (0xF928, 'M', '廊'),\n    (0xF929, 'M', '朗'),\n    (0xF92A, 'M', '浪'),\n    (0xF92B, 'M', '狼'),\n    (0xF92C, 'M', '郎'),\n    (0xF92D, 'M', '來'),\n    (0xF92E, 'M', '冷'),\n    (0xF92F, 'M', '勞'),\n    (0xF930, 'M', '擄'),\n    (0xF931, 'M', '櫓'),\n    (0xF932, 'M', '爐'),\n    (0xF933, 'M', '盧'),\n    (0xF934, 'M', '老'),\n    (0xF935, 'M', '蘆'),\n    (0xF936, 'M', '虜'),\n    (0xF937, 'M', '路'),\n    (0xF938, 'M', '露'),\n    (0xF939, 'M', '魯'),\n    (0xF93A, 'M', '鷺'),\n    (0xF93B, 'M', '碌'),\n    (0xF93C, 'M', '祿'),\n    (0xF93D, 'M', '綠'),\n    (0xF93E, 'M', '菉'),\n    (0xF93F, 'M', '錄'),\n    (0xF940, 'M', '鹿'),\n    (0xF941, 'M', '論'),\n    (0xF942, 'M', '壟'),\n    (0xF943, 'M', '弄'),\n    (0xF944, 'M', '籠'),\n    (0xF945, 'M', '聾'),\n    ]\n\ndef _seg_40() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xF946, 'M', '牢'),\n    (0xF947, 'M', '磊'),\n    (0xF948, 'M', '賂'),\n    (0xF949, 'M', '雷'),\n    (0xF94A, 'M', '壘'),\n    (0xF94B, 'M', '屢'),\n    (0xF94C, 'M', '樓'),\n    (0xF94D, 'M', '淚'),\n    (0xF94E, 'M', '漏'),\n    (0xF94F, 'M', '累'),\n    (0xF950, 'M', '縷'),\n    (0xF951, 'M', '陋'),\n    (0xF952, 'M', '勒'),\n    (0xF953, 'M', '肋'),\n    (0xF954, 'M', '凜'),\n    (0xF955, 'M', '凌'),\n    (0xF956, 'M', '稜'),\n    (0xF957, 'M', '綾'),\n    (0xF958, 'M', '菱'),\n    (0xF959, 'M', '陵'),\n    (0xF95A, 'M', '讀'),\n    (0xF95B, 'M', '拏'),\n    (0xF95C, 'M', '樂'),\n    (0xF95D, 'M', '諾'),\n    (0xF95E, 'M', '丹'),\n    (0xF95F, 'M', '寧'),\n    (0xF960, 'M', '怒'),\n    (0xF961, 'M', '率'),\n    (0xF962, 'M', '異'),\n    (0xF963, 'M', '北'),\n    (0xF964, 'M', '磻'),\n    (0xF965, 'M', '便'),\n    (0xF966, 'M', '復'),\n    (0xF967, 'M', '不'),\n    (0xF968, 'M', '泌'),\n    (0xF969, 'M', '數'),\n    (0xF96A, 'M', '索'),\n    (0xF96B, 'M', '參'),\n    (0xF96C, 'M', '塞'),\n    (0xF96D, 'M', '省'),\n    (0xF96E, 'M', '葉'),\n    (0xF96F, 'M', '說'),\n    (0xF970, 'M', '殺'),\n    (0xF971, 'M', '辰'),\n    (0xF972, 'M', '沈'),\n    (0xF973, 'M', '拾'),\n    (0xF974, 'M', '若'),\n    (0xF975, 'M', '掠'),\n    (0xF976, 'M', '略'),\n    (0xF977, 'M', '亮'),\n    (0xF978, 'M', '兩'),\n    (0xF979, 'M', '凉'),\n    (0xF97A, 'M', '梁'),\n    (0xF97B, 'M', '糧'),\n    (0xF97C, 'M', '良'),\n    (0xF97D, 'M', '諒'),\n    (0xF97E, 'M', '量'),\n    (0xF97F, 'M', '勵'),\n    (0xF980, 'M', '呂'),\n    (0xF981, 'M', '女'),\n    (0xF982, 'M', '廬'),\n    (0xF983, 'M', '旅'),\n    (0xF984, 'M', '濾'),\n    (0xF985, 'M', '礪'),\n    (0xF986, 'M', '閭'),\n    (0xF987, 'M', '驪'),\n    (0xF988, 'M', '麗'),\n    (0xF989, 'M', '黎'),\n    (0xF98A, 'M', '力'),\n    (0xF98B, 'M', '曆'),\n    (0xF98C, 'M', '歷'),\n    (0xF98D, 'M', '轢'),\n    (0xF98E, 'M', '年'),\n    (0xF98F, 'M', '憐'),\n    (0xF990, 'M', '戀'),\n    (0xF991, 'M', '撚'),\n    (0xF992, 'M', '漣'),\n    (0xF993, 'M', '煉'),\n    (0xF994, 'M', '璉'),\n    (0xF995, 'M', '秊'),\n    (0xF996, 'M', '練'),\n    (0xF997, 'M', '聯'),\n    (0xF998, 'M', '輦'),\n    (0xF999, 'M', '蓮'),\n    (0xF99A, 'M', '連'),\n    (0xF99B, 'M', '鍊'),\n    (0xF99C, 'M', '列'),\n    (0xF99D, 'M', '劣'),\n    (0xF99E, 'M', '咽'),\n    (0xF99F, 'M', '烈'),\n    (0xF9A0, 'M', '裂'),\n    (0xF9A1, 'M', '說'),\n    (0xF9A2, 'M', '廉'),\n    (0xF9A3, 'M', '念'),\n    (0xF9A4, 'M', '捻'),\n    (0xF9A5, 'M', '殮'),\n    (0xF9A6, 'M', '簾'),\n    (0xF9A7, 'M', '獵'),\n    (0xF9A8, 'M', '令'),\n    (0xF9A9, 'M', '囹'),\n    ]\n\ndef _seg_41() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xF9AA, 'M', '寧'),\n    (0xF9AB, 'M', '嶺'),\n    (0xF9AC, 'M', '怜'),\n    (0xF9AD, 'M', '玲'),\n    (0xF9AE, 'M', '瑩'),\n    (0xF9AF, 'M', '羚'),\n    (0xF9B0, 'M', '聆'),\n    (0xF9B1, 'M', '鈴'),\n    (0xF9B2, 'M', '零'),\n    (0xF9B3, 'M', '靈'),\n    (0xF9B4, 'M', '領'),\n    (0xF9B5, 'M', '例'),\n    (0xF9B6, 'M', '禮'),\n    (0xF9B7, 'M', '醴'),\n    (0xF9B8, 'M', '隸'),\n    (0xF9B9, 'M', '惡'),\n    (0xF9BA, 'M', '了'),\n    (0xF9BB, 'M', '僚'),\n    (0xF9BC, 'M', '寮'),\n    (0xF9BD, 'M', '尿'),\n    (0xF9BE, 'M', '料'),\n    (0xF9BF, 'M', '樂'),\n    (0xF9C0, 'M', '燎'),\n    (0xF9C1, 'M', '療'),\n    (0xF9C2, 'M', '蓼'),\n    (0xF9C3, 'M', '遼'),\n    (0xF9C4, 'M', '龍'),\n    (0xF9C5, 'M', '暈'),\n    (0xF9C6, 'M', '阮'),\n    (0xF9C7, 'M', '劉'),\n    (0xF9C8, 'M', '杻'),\n    (0xF9C9, 'M', '柳'),\n    (0xF9CA, 'M', '流'),\n    (0xF9CB, 'M', '溜'),\n    (0xF9CC, 'M', '琉'),\n    (0xF9CD, 'M', '留'),\n    (0xF9CE, 'M', '硫'),\n    (0xF9CF, 'M', '紐'),\n    (0xF9D0, 'M', '類'),\n    (0xF9D1, 'M', '六'),\n    (0xF9D2, 'M', '戮'),\n    (0xF9D3, 'M', '陸'),\n    (0xF9D4, 'M', '倫'),\n    (0xF9D5, 'M', '崙'),\n    (0xF9D6, 'M', '淪'),\n    (0xF9D7, 'M', '輪'),\n    (0xF9D8, 'M', '律'),\n    (0xF9D9, 'M', '慄'),\n    (0xF9DA, 'M', '栗'),\n    (0xF9DB, 'M', '率'),\n    (0xF9DC, 'M', '隆'),\n    (0xF9DD, 'M', '利'),\n    (0xF9DE, 'M', '吏'),\n    (0xF9DF, 'M', '履'),\n    (0xF9E0, 'M', '易'),\n    (0xF9E1, 'M', '李'),\n    (0xF9E2, 'M', '梨'),\n    (0xF9E3, 'M', '泥'),\n    (0xF9E4, 'M', '理'),\n    (0xF9E5, 'M', '痢'),\n    (0xF9E6, 'M', '罹'),\n    (0xF9E7, 'M', '裏'),\n    (0xF9E8, 'M', '裡'),\n    (0xF9E9, 'M', '里'),\n    (0xF9EA, 'M', '離'),\n    (0xF9EB, 'M', '匿'),\n    (0xF9EC, 'M', '溺'),\n    (0xF9ED, 'M', '吝'),\n    (0xF9EE, 'M', '燐'),\n    (0xF9EF, 'M', '璘'),\n    (0xF9F0, 'M', '藺'),\n    (0xF9F1, 'M', '隣'),\n    (0xF9F2, 'M', '鱗'),\n    (0xF9F3, 'M', '麟'),\n    (0xF9F4, 'M', '林'),\n    (0xF9F5, 'M', '淋'),\n    (0xF9F6, 'M', '臨'),\n    (0xF9F7, 'M', '立'),\n    (0xF9F8, 'M', '笠'),\n    (0xF9F9, 'M', '粒'),\n    (0xF9FA, 'M', '狀'),\n    (0xF9FB, 'M', '炙'),\n    (0xF9FC, 'M', '識'),\n    (0xF9FD, 'M', '什'),\n    (0xF9FE, 'M', '茶'),\n    (0xF9FF, 'M', '刺'),\n    (0xFA00, 'M', '切'),\n    (0xFA01, 'M', '度'),\n    (0xFA02, 'M', '拓'),\n    (0xFA03, 'M', '糖'),\n    (0xFA04, 'M', '宅'),\n    (0xFA05, 'M', '洞'),\n    (0xFA06, 'M', '暴'),\n    (0xFA07, 'M', '輻'),\n    (0xFA08, 'M', '行'),\n    (0xFA09, 'M', '降'),\n    (0xFA0A, 'M', '見'),\n    (0xFA0B, 'M', '廓'),\n    (0xFA0C, 'M', '兀'),\n    (0xFA0D, 'M', '嗀'),\n    ]\n\ndef _seg_42() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xFA0E, 'V'),\n    (0xFA10, 'M', '塚'),\n    (0xFA11, 'V'),\n    (0xFA12, 'M', '晴'),\n    (0xFA13, 'V'),\n    (0xFA15, 'M', '凞'),\n    (0xFA16, 'M', '猪'),\n    (0xFA17, 'M', '益'),\n    (0xFA18, 'M', '礼'),\n    (0xFA19, 'M', '神'),\n    (0xFA1A, 'M', '祥'),\n    (0xFA1B, 'M', '福'),\n    (0xFA1C, 'M', '靖'),\n    (0xFA1D, 'M', '精'),\n    (0xFA1E, 'M', '羽'),\n    (0xFA1F, 'V'),\n    (0xFA20, 'M', '蘒'),\n    (0xFA21, 'V'),\n    (0xFA22, 'M', '諸'),\n    (0xFA23, 'V'),\n    (0xFA25, 'M', '逸'),\n    (0xFA26, 'M', '都'),\n    (0xFA27, 'V'),\n    (0xFA2A, 'M', '飯'),\n    (0xFA2B, 'M', '飼'),\n    (0xFA2C, 'M', '館'),\n    (0xFA2D, 'M', '鶴'),\n    (0xFA2E, 'M', '郞'),\n    (0xFA2F, 'M', '隷'),\n    (0xFA30, 'M', '侮'),\n    (0xFA31, 'M', '僧'),\n    (0xFA32, 'M', '免'),\n    (0xFA33, 'M', '勉'),\n    (0xFA34, 'M', '勤'),\n    (0xFA35, 'M', '卑'),\n    (0xFA36, 'M', '喝'),\n    (0xFA37, 'M', '嘆'),\n    (0xFA38, 'M', '器'),\n    (0xFA39, 'M', '塀'),\n    (0xFA3A, 'M', '墨'),\n    (0xFA3B, 'M', '層'),\n    (0xFA3C, 'M', '屮'),\n    (0xFA3D, 'M', '悔'),\n    (0xFA3E, 'M', '慨'),\n    (0xFA3F, 'M', '憎'),\n    (0xFA40, 'M', '懲'),\n    (0xFA41, 'M', '敏'),\n    (0xFA42, 'M', '既'),\n    (0xFA43, 'M', '暑'),\n    (0xFA44, 'M', '梅'),\n    (0xFA45, 'M', '海'),\n    (0xFA46, 'M', '渚'),\n    (0xFA47, 'M', '漢'),\n    (0xFA48, 'M', '煮'),\n    (0xFA49, 'M', '爫'),\n    (0xFA4A, 'M', '琢'),\n    (0xFA4B, 'M', '碑'),\n    (0xFA4C, 'M', '社'),\n    (0xFA4D, 'M', '祉'),\n    (0xFA4E, 'M', '祈'),\n    (0xFA4F, 'M', '祐'),\n    (0xFA50, 'M', '祖'),\n    (0xFA51, 'M', '祝'),\n    (0xFA52, 'M', '禍'),\n    (0xFA53, 'M', '禎'),\n    (0xFA54, 'M', '穀'),\n    (0xFA55, 'M', '突'),\n    (0xFA56, 'M', '節'),\n    (0xFA57, 'M', '練'),\n    (0xFA58, 'M', '縉'),\n    (0xFA59, 'M', '繁'),\n    (0xFA5A, 'M', '署'),\n    (0xFA5B, 'M', '者'),\n    (0xFA5C, 'M', '臭'),\n    (0xFA5D, 'M', '艹'),\n    (0xFA5F, 'M', '著'),\n    (0xFA60, 'M', '褐'),\n    (0xFA61, 'M', '視'),\n    (0xFA62, 'M', '謁'),\n    (0xFA63, 'M', '謹'),\n    (0xFA64, 'M', '賓'),\n    (0xFA65, 'M', '贈'),\n    (0xFA66, 'M', '辶'),\n    (0xFA67, 'M', '逸'),\n    (0xFA68, 'M', '難'),\n    (0xFA69, 'M', '響'),\n    (0xFA6A, 'M', '頻'),\n    (0xFA6B, 'M', '恵'),\n    (0xFA6C, 'M', '𤋮'),\n    (0xFA6D, 'M', '舘'),\n    (0xFA6E, 'X'),\n    (0xFA70, 'M', '並'),\n    (0xFA71, 'M', '况'),\n    (0xFA72, 'M', '全'),\n    (0xFA73, 'M', '侀'),\n    (0xFA74, 'M', '充'),\n    (0xFA75, 'M', '冀'),\n    (0xFA76, 'M', '勇'),\n    (0xFA77, 'M', '勺'),\n    (0xFA78, 'M', '喝'),\n    ]\n\ndef _seg_43() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xFA79, 'M', '啕'),\n    (0xFA7A, 'M', '喙'),\n    (0xFA7B, 'M', '嗢'),\n    (0xFA7C, 'M', '塚'),\n    (0xFA7D, 'M', '墳'),\n    (0xFA7E, 'M', '奄'),\n    (0xFA7F, 'M', '奔'),\n    (0xFA80, 'M', '婢'),\n    (0xFA81, 'M', '嬨'),\n    (0xFA82, 'M', '廒'),\n    (0xFA83, 'M', '廙'),\n    (0xFA84, 'M', '彩'),\n    (0xFA85, 'M', '徭'),\n    (0xFA86, 'M', '惘'),\n    (0xFA87, 'M', '慎'),\n    (0xFA88, 'M', '愈'),\n    (0xFA89, 'M', '憎'),\n    (0xFA8A, 'M', '慠'),\n    (0xFA8B, 'M', '懲'),\n    (0xFA8C, 'M', '戴'),\n    (0xFA8D, 'M', '揄'),\n    (0xFA8E, 'M', '搜'),\n    (0xFA8F, 'M', '摒'),\n    (0xFA90, 'M', '敖'),\n    (0xFA91, 'M', '晴'),\n    (0xFA92, 'M', '朗'),\n    (0xFA93, 'M', '望'),\n    (0xFA94, 'M', '杖'),\n    (0xFA95, 'M', '歹'),\n    (0xFA96, 'M', '殺'),\n    (0xFA97, 'M', '流'),\n    (0xFA98, 'M', '滛'),\n    (0xFA99, 'M', '滋'),\n    (0xFA9A, 'M', '漢'),\n    (0xFA9B, 'M', '瀞'),\n    (0xFA9C, 'M', '煮'),\n    (0xFA9D, 'M', '瞧'),\n    (0xFA9E, 'M', '爵'),\n    (0xFA9F, 'M', '犯'),\n    (0xFAA0, 'M', '猪'),\n    (0xFAA1, 'M', '瑱'),\n    (0xFAA2, 'M', '甆'),\n    (0xFAA3, 'M', '画'),\n    (0xFAA4, 'M', '瘝'),\n    (0xFAA5, 'M', '瘟'),\n    (0xFAA6, 'M', '益'),\n    (0xFAA7, 'M', '盛'),\n    (0xFAA8, 'M', '直'),\n    (0xFAA9, 'M', '睊'),\n    (0xFAAA, 'M', '着'),\n    (0xFAAB, 'M', '磌'),\n    (0xFAAC, 'M', '窱'),\n    (0xFAAD, 'M', '節'),\n    (0xFAAE, 'M', '类'),\n    (0xFAAF, 'M', '絛'),\n    (0xFAB0, 'M', '練'),\n    (0xFAB1, 'M', '缾'),\n    (0xFAB2, 'M', '者'),\n    (0xFAB3, 'M', '荒'),\n    (0xFAB4, 'M', '華'),\n    (0xFAB5, 'M', '蝹'),\n    (0xFAB6, 'M', '襁'),\n    (0xFAB7, 'M', '覆'),\n    (0xFAB8, 'M', '視'),\n    (0xFAB9, 'M', '調'),\n    (0xFABA, 'M', '諸'),\n    (0xFABB, 'M', '請'),\n    (0xFABC, 'M', '謁'),\n    (0xFABD, 'M', '諾'),\n    (0xFABE, 'M', '諭'),\n    (0xFABF, 'M', '謹'),\n    (0xFAC0, 'M', '變'),\n    (0xFAC1, 'M', '贈'),\n    (0xFAC2, 'M', '輸'),\n    (0xFAC3, 'M', '遲'),\n    (0xFAC4, 'M', '醙'),\n    (0xFAC5, 'M', '鉶'),\n    (0xFAC6, 'M', '陼'),\n    (0xFAC7, 'M', '難'),\n    (0xFAC8, 'M', '靖'),\n    (0xFAC9, 'M', '韛'),\n    (0xFACA, 'M', '響'),\n    (0xFACB, 'M', '頋'),\n    (0xFACC, 'M', '頻'),\n    (0xFACD, 'M', '鬒'),\n    (0xFACE, 'M', '龜'),\n    (0xFACF, 'M', '𢡊'),\n    (0xFAD0, 'M', '𢡄'),\n    (0xFAD1, 'M', '𣏕'),\n    (0xFAD2, 'M', '㮝'),\n    (0xFAD3, 'M', '䀘'),\n    (0xFAD4, 'M', '䀹'),\n    (0xFAD5, 'M', '𥉉'),\n    (0xFAD6, 'M', '𥳐'),\n    (0xFAD7, 'M', '𧻓'),\n    (0xFAD8, 'M', '齃'),\n    (0xFAD9, 'M', '龎'),\n    (0xFADA, 'X'),\n    (0xFB00, 'M', 'ff'),\n    (0xFB01, 'M', 'fi'),\n    ]\n\ndef _seg_44() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xFB02, 'M', 'fl'),\n    (0xFB03, 'M', 'ffi'),\n    (0xFB04, 'M', 'ffl'),\n    (0xFB05, 'M', 'st'),\n    (0xFB07, 'X'),\n    (0xFB13, 'M', 'մն'),\n    (0xFB14, 'M', 'մե'),\n    (0xFB15, 'M', 'մի'),\n    (0xFB16, 'M', 'վն'),\n    (0xFB17, 'M', 'մխ'),\n    (0xFB18, 'X'),\n    (0xFB1D, 'M', 'יִ'),\n    (0xFB1E, 'V'),\n    (0xFB1F, 'M', 'ײַ'),\n    (0xFB20, 'M', 'ע'),\n    (0xFB21, 'M', 'א'),\n    (0xFB22, 'M', 'ד'),\n    (0xFB23, 'M', 'ה'),\n    (0xFB24, 'M', 'כ'),\n    (0xFB25, 'M', 'ל'),\n    (0xFB26, 'M', 'ם'),\n    (0xFB27, 'M', 'ר'),\n    (0xFB28, 'M', 'ת'),\n    (0xFB29, '3', '+'),\n    (0xFB2A, 'M', 'שׁ'),\n    (0xFB2B, 'M', 'שׂ'),\n    (0xFB2C, 'M', 'שּׁ'),\n    (0xFB2D, 'M', 'שּׂ'),\n    (0xFB2E, 'M', 'אַ'),\n    (0xFB2F, 'M', 'אָ'),\n    (0xFB30, 'M', 'אּ'),\n    (0xFB31, 'M', 'בּ'),\n    (0xFB32, 'M', 'גּ'),\n    (0xFB33, 'M', 'דּ'),\n    (0xFB34, 'M', 'הּ'),\n    (0xFB35, 'M', 'וּ'),\n    (0xFB36, 'M', 'זּ'),\n    (0xFB37, 'X'),\n    (0xFB38, 'M', 'טּ'),\n    (0xFB39, 'M', 'יּ'),\n    (0xFB3A, 'M', 'ךּ'),\n    (0xFB3B, 'M', 'כּ'),\n    (0xFB3C, 'M', 'לּ'),\n    (0xFB3D, 'X'),\n    (0xFB3E, 'M', 'מּ'),\n    (0xFB3F, 'X'),\n    (0xFB40, 'M', 'נּ'),\n    (0xFB41, 'M', 'סּ'),\n    (0xFB42, 'X'),\n    (0xFB43, 'M', 'ףּ'),\n    (0xFB44, 'M', 'פּ'),\n    (0xFB45, 'X'),\n    (0xFB46, 'M', 'צּ'),\n    (0xFB47, 'M', 'קּ'),\n    (0xFB48, 'M', 'רּ'),\n    (0xFB49, 'M', 'שּ'),\n    (0xFB4A, 'M', 'תּ'),\n    (0xFB4B, 'M', 'וֹ'),\n    (0xFB4C, 'M', 'בֿ'),\n    (0xFB4D, 'M', 'כֿ'),\n    (0xFB4E, 'M', 'פֿ'),\n    (0xFB4F, 'M', 'אל'),\n    (0xFB50, 'M', 'ٱ'),\n    (0xFB52, 'M', 'ٻ'),\n    (0xFB56, 'M', 'پ'),\n    (0xFB5A, 'M', 'ڀ'),\n    (0xFB5E, 'M', 'ٺ'),\n    (0xFB62, 'M', 'ٿ'),\n    (0xFB66, 'M', 'ٹ'),\n    (0xFB6A, 'M', 'ڤ'),\n    (0xFB6E, 'M', 'ڦ'),\n    (0xFB72, 'M', 'ڄ'),\n    (0xFB76, 'M', 'ڃ'),\n    (0xFB7A, 'M', 'چ'),\n    (0xFB7E, 'M', 'ڇ'),\n    (0xFB82, 'M', 'ڍ'),\n    (0xFB84, 'M', 'ڌ'),\n    (0xFB86, 'M', 'ڎ'),\n    (0xFB88, 'M', 'ڈ'),\n    (0xFB8A, 'M', 'ژ'),\n    (0xFB8C, 'M', 'ڑ'),\n    (0xFB8E, 'M', 'ک'),\n    (0xFB92, 'M', 'گ'),\n    (0xFB96, 'M', 'ڳ'),\n    (0xFB9A, 'M', 'ڱ'),\n    (0xFB9E, 'M', 'ں'),\n    (0xFBA0, 'M', 'ڻ'),\n    (0xFBA4, 'M', 'ۀ'),\n    (0xFBA6, 'M', 'ہ'),\n    (0xFBAA, 'M', 'ھ'),\n    (0xFBAE, 'M', 'ے'),\n    (0xFBB0, 'M', 'ۓ'),\n    (0xFBB2, 'V'),\n    (0xFBC3, 'X'),\n    (0xFBD3, 'M', 'ڭ'),\n    (0xFBD7, 'M', 'ۇ'),\n    (0xFBD9, 'M', 'ۆ'),\n    (0xFBDB, 'M', 'ۈ'),\n    (0xFBDD, 'M', 'ۇٴ'),\n    (0xFBDE, 'M', 'ۋ'),\n    ]\n\ndef _seg_45() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xFBE0, 'M', 'ۅ'),\n    (0xFBE2, 'M', 'ۉ'),\n    (0xFBE4, 'M', 'ې'),\n    (0xFBE8, 'M', 'ى'),\n    (0xFBEA, 'M', 'ئا'),\n    (0xFBEC, 'M', 'ئە'),\n    (0xFBEE, 'M', 'ئو'),\n    (0xFBF0, 'M', 'ئۇ'),\n    (0xFBF2, 'M', 'ئۆ'),\n    (0xFBF4, 'M', 'ئۈ'),\n    (0xFBF6, 'M', 'ئې'),\n    (0xFBF9, 'M', 'ئى'),\n    (0xFBFC, 'M', 'ی'),\n    (0xFC00, 'M', 'ئج'),\n    (0xFC01, 'M', 'ئح'),\n    (0xFC02, 'M', 'ئم'),\n    (0xFC03, 'M', 'ئى'),\n    (0xFC04, 'M', 'ئي'),\n    (0xFC05, 'M', 'بج'),\n    (0xFC06, 'M', 'بح'),\n    (0xFC07, 'M', 'بخ'),\n    (0xFC08, 'M', 'بم'),\n    (0xFC09, 'M', 'بى'),\n    (0xFC0A, 'M', 'بي'),\n    (0xFC0B, 'M', 'تج'),\n    (0xFC0C, 'M', 'تح'),\n    (0xFC0D, 'M', 'تخ'),\n    (0xFC0E, 'M', 'تم'),\n    (0xFC0F, 'M', 'تى'),\n    (0xFC10, 'M', 'تي'),\n    (0xFC11, 'M', 'ثج'),\n    (0xFC12, 'M', 'ثم'),\n    (0xFC13, 'M', 'ثى'),\n    (0xFC14, 'M', 'ثي'),\n    (0xFC15, 'M', 'جح'),\n    (0xFC16, 'M', 'جم'),\n    (0xFC17, 'M', 'حج'),\n    (0xFC18, 'M', 'حم'),\n    (0xFC19, 'M', 'خج'),\n    (0xFC1A, 'M', 'خح'),\n    (0xFC1B, 'M', 'خم'),\n    (0xFC1C, 'M', 'سج'),\n    (0xFC1D, 'M', 'سح'),\n    (0xFC1E, 'M', 'سخ'),\n    (0xFC1F, 'M', 'سم'),\n    (0xFC20, 'M', 'صح'),\n    (0xFC21, 'M', 'صم'),\n    (0xFC22, 'M', 'ضج'),\n    (0xFC23, 'M', 'ضح'),\n    (0xFC24, 'M', 'ضخ'),\n    (0xFC25, 'M', 'ضم'),\n    (0xFC26, 'M', 'طح'),\n    (0xFC27, 'M', 'طم'),\n    (0xFC28, 'M', 'ظم'),\n    (0xFC29, 'M', 'عج'),\n    (0xFC2A, 'M', 'عم'),\n    (0xFC2B, 'M', 'غج'),\n    (0xFC2C, 'M', 'غم'),\n    (0xFC2D, 'M', 'فج'),\n    (0xFC2E, 'M', 'فح'),\n    (0xFC2F, 'M', 'فخ'),\n    (0xFC30, 'M', 'فم'),\n    (0xFC31, 'M', 'فى'),\n    (0xFC32, 'M', 'في'),\n    (0xFC33, 'M', 'قح'),\n    (0xFC34, 'M', 'قم'),\n    (0xFC35, 'M', 'قى'),\n    (0xFC36, 'M', 'قي'),\n    (0xFC37, 'M', 'كا'),\n    (0xFC38, 'M', 'كج'),\n    (0xFC39, 'M', 'كح'),\n    (0xFC3A, 'M', 'كخ'),\n    (0xFC3B, 'M', 'كل'),\n    (0xFC3C, 'M', 'كم'),\n    (0xFC3D, 'M', 'كى'),\n    (0xFC3E, 'M', 'كي'),\n    (0xFC3F, 'M', 'لج'),\n    (0xFC40, 'M', 'لح'),\n    (0xFC41, 'M', 'لخ'),\n    (0xFC42, 'M', 'لم'),\n    (0xFC43, 'M', 'لى'),\n    (0xFC44, 'M', 'لي'),\n    (0xFC45, 'M', 'مج'),\n    (0xFC46, 'M', 'مح'),\n    (0xFC47, 'M', 'مخ'),\n    (0xFC48, 'M', 'مم'),\n    (0xFC49, 'M', 'مى'),\n    (0xFC4A, 'M', 'مي'),\n    (0xFC4B, 'M', 'نج'),\n    (0xFC4C, 'M', 'نح'),\n    (0xFC4D, 'M', 'نخ'),\n    (0xFC4E, 'M', 'نم'),\n    (0xFC4F, 'M', 'نى'),\n    (0xFC50, 'M', 'ني'),\n    (0xFC51, 'M', 'هج'),\n    (0xFC52, 'M', 'هم'),\n    (0xFC53, 'M', 'هى'),\n    (0xFC54, 'M', 'هي'),\n    (0xFC55, 'M', 'يج'),\n    (0xFC56, 'M', 'يح'),\n    ]\n\ndef _seg_46() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xFC57, 'M', 'يخ'),\n    (0xFC58, 'M', 'يم'),\n    (0xFC59, 'M', 'يى'),\n    (0xFC5A, 'M', 'يي'),\n    (0xFC5B, 'M', 'ذٰ'),\n    (0xFC5C, 'M', 'رٰ'),\n    (0xFC5D, 'M', 'ىٰ'),\n    (0xFC5E, '3', ' ٌّ'),\n    (0xFC5F, '3', ' ٍّ'),\n    (0xFC60, '3', ' َّ'),\n    (0xFC61, '3', ' ُّ'),\n    (0xFC62, '3', ' ِّ'),\n    (0xFC63, '3', ' ّٰ'),\n    (0xFC64, 'M', 'ئر'),\n    (0xFC65, 'M', 'ئز'),\n    (0xFC66, 'M', 'ئم'),\n    (0xFC67, 'M', 'ئن'),\n    (0xFC68, 'M', 'ئى'),\n    (0xFC69, 'M', 'ئي'),\n    (0xFC6A, 'M', 'بر'),\n    (0xFC6B, 'M', 'بز'),\n    (0xFC6C, 'M', 'بم'),\n    (0xFC6D, 'M', 'بن'),\n    (0xFC6E, 'M', 'بى'),\n    (0xFC6F, 'M', 'بي'),\n    (0xFC70, 'M', 'تر'),\n    (0xFC71, 'M', 'تز'),\n    (0xFC72, 'M', 'تم'),\n    (0xFC73, 'M', 'تن'),\n    (0xFC74, 'M', 'تى'),\n    (0xFC75, 'M', 'تي'),\n    (0xFC76, 'M', 'ثر'),\n    (0xFC77, 'M', 'ثز'),\n    (0xFC78, 'M', 'ثم'),\n    (0xFC79, 'M', 'ثن'),\n    (0xFC7A, 'M', 'ثى'),\n    (0xFC7B, 'M', 'ثي'),\n    (0xFC7C, 'M', 'فى'),\n    (0xFC7D, 'M', 'في'),\n    (0xFC7E, 'M', 'قى'),\n    (0xFC7F, 'M', 'قي'),\n    (0xFC80, 'M', 'كا'),\n    (0xFC81, 'M', 'كل'),\n    (0xFC82, 'M', 'كم'),\n    (0xFC83, 'M', 'كى'),\n    (0xFC84, 'M', 'كي'),\n    (0xFC85, 'M', 'لم'),\n    (0xFC86, 'M', 'لى'),\n    (0xFC87, 'M', 'لي'),\n    (0xFC88, 'M', 'ما'),\n    (0xFC89, 'M', 'مم'),\n    (0xFC8A, 'M', 'نر'),\n    (0xFC8B, 'M', 'نز'),\n    (0xFC8C, 'M', 'نم'),\n    (0xFC8D, 'M', 'نن'),\n    (0xFC8E, 'M', 'نى'),\n    (0xFC8F, 'M', 'ني'),\n    (0xFC90, 'M', 'ىٰ'),\n    (0xFC91, 'M', 'ير'),\n    (0xFC92, 'M', 'يز'),\n    (0xFC93, 'M', 'يم'),\n    (0xFC94, 'M', 'ين'),\n    (0xFC95, 'M', 'يى'),\n    (0xFC96, 'M', 'يي'),\n    (0xFC97, 'M', 'ئج'),\n    (0xFC98, 'M', 'ئح'),\n    (0xFC99, 'M', 'ئخ'),\n    (0xFC9A, 'M', 'ئم'),\n    (0xFC9B, 'M', 'ئه'),\n    (0xFC9C, 'M', 'بج'),\n    (0xFC9D, 'M', 'بح'),\n    (0xFC9E, 'M', 'بخ'),\n    (0xFC9F, 'M', 'بم'),\n    (0xFCA0, 'M', 'به'),\n    (0xFCA1, 'M', 'تج'),\n    (0xFCA2, 'M', 'تح'),\n    (0xFCA3, 'M', 'تخ'),\n    (0xFCA4, 'M', 'تم'),\n    (0xFCA5, 'M', 'ته'),\n    (0xFCA6, 'M', 'ثم'),\n    (0xFCA7, 'M', 'جح'),\n    (0xFCA8, 'M', 'جم'),\n    (0xFCA9, 'M', 'حج'),\n    (0xFCAA, 'M', 'حم'),\n    (0xFCAB, 'M', 'خج'),\n    (0xFCAC, 'M', 'خم'),\n    (0xFCAD, 'M', 'سج'),\n    (0xFCAE, 'M', 'سح'),\n    (0xFCAF, 'M', 'سخ'),\n    (0xFCB0, 'M', 'سم'),\n    (0xFCB1, 'M', 'صح'),\n    (0xFCB2, 'M', 'صخ'),\n    (0xFCB3, 'M', 'صم'),\n    (0xFCB4, 'M', 'ضج'),\n    (0xFCB5, 'M', 'ضح'),\n    (0xFCB6, 'M', 'ضخ'),\n    (0xFCB7, 'M', 'ضم'),\n    (0xFCB8, 'M', 'طح'),\n    (0xFCB9, 'M', 'ظم'),\n    (0xFCBA, 'M', 'عج'),\n    ]\n\ndef _seg_47() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xFCBB, 'M', 'عم'),\n    (0xFCBC, 'M', 'غج'),\n    (0xFCBD, 'M', 'غم'),\n    (0xFCBE, 'M', 'فج'),\n    (0xFCBF, 'M', 'فح'),\n    (0xFCC0, 'M', 'فخ'),\n    (0xFCC1, 'M', 'فم'),\n    (0xFCC2, 'M', 'قح'),\n    (0xFCC3, 'M', 'قم'),\n    (0xFCC4, 'M', 'كج'),\n    (0xFCC5, 'M', 'كح'),\n    (0xFCC6, 'M', 'كخ'),\n    (0xFCC7, 'M', 'كل'),\n    (0xFCC8, 'M', 'كم'),\n    (0xFCC9, 'M', 'لج'),\n    (0xFCCA, 'M', 'لح'),\n    (0xFCCB, 'M', 'لخ'),\n    (0xFCCC, 'M', 'لم'),\n    (0xFCCD, 'M', 'له'),\n    (0xFCCE, 'M', 'مج'),\n    (0xFCCF, 'M', 'مح'),\n    (0xFCD0, 'M', 'مخ'),\n    (0xFCD1, 'M', 'مم'),\n    (0xFCD2, 'M', 'نج'),\n    (0xFCD3, 'M', 'نح'),\n    (0xFCD4, 'M', 'نخ'),\n    (0xFCD5, 'M', 'نم'),\n    (0xFCD6, 'M', 'نه'),\n    (0xFCD7, 'M', 'هج'),\n    (0xFCD8, 'M', 'هم'),\n    (0xFCD9, 'M', 'هٰ'),\n    (0xFCDA, 'M', 'يج'),\n    (0xFCDB, 'M', 'يح'),\n    (0xFCDC, 'M', 'يخ'),\n    (0xFCDD, 'M', 'يم'),\n    (0xFCDE, 'M', 'يه'),\n    (0xFCDF, 'M', 'ئم'),\n    (0xFCE0, 'M', 'ئه'),\n    (0xFCE1, 'M', 'بم'),\n    (0xFCE2, 'M', 'به'),\n    (0xFCE3, 'M', 'تم'),\n    (0xFCE4, 'M', 'ته'),\n    (0xFCE5, 'M', 'ثم'),\n    (0xFCE6, 'M', 'ثه'),\n    (0xFCE7, 'M', 'سم'),\n    (0xFCE8, 'M', 'سه'),\n    (0xFCE9, 'M', 'شم'),\n    (0xFCEA, 'M', 'شه'),\n    (0xFCEB, 'M', 'كل'),\n    (0xFCEC, 'M', 'كم'),\n    (0xFCED, 'M', 'لم'),\n    (0xFCEE, 'M', 'نم'),\n    (0xFCEF, 'M', 'نه'),\n    (0xFCF0, 'M', 'يم'),\n    (0xFCF1, 'M', 'يه'),\n    (0xFCF2, 'M', 'ـَّ'),\n    (0xFCF3, 'M', 'ـُّ'),\n    (0xFCF4, 'M', 'ـِّ'),\n    (0xFCF5, 'M', 'طى'),\n    (0xFCF6, 'M', 'طي'),\n    (0xFCF7, 'M', 'عى'),\n    (0xFCF8, 'M', 'عي'),\n    (0xFCF9, 'M', 'غى'),\n    (0xFCFA, 'M', 'غي'),\n    (0xFCFB, 'M', 'سى'),\n    (0xFCFC, 'M', 'سي'),\n    (0xFCFD, 'M', 'شى'),\n    (0xFCFE, 'M', 'شي'),\n    (0xFCFF, 'M', 'حى'),\n    (0xFD00, 'M', 'حي'),\n    (0xFD01, 'M', 'جى'),\n    (0xFD02, 'M', 'جي'),\n    (0xFD03, 'M', 'خى'),\n    (0xFD04, 'M', 'خي'),\n    (0xFD05, 'M', 'صى'),\n    (0xFD06, 'M', 'صي'),\n    (0xFD07, 'M', 'ضى'),\n    (0xFD08, 'M', 'ضي'),\n    (0xFD09, 'M', 'شج'),\n    (0xFD0A, 'M', 'شح'),\n    (0xFD0B, 'M', 'شخ'),\n    (0xFD0C, 'M', 'شم'),\n    (0xFD0D, 'M', 'شر'),\n    (0xFD0E, 'M', 'سر'),\n    (0xFD0F, 'M', 'صر'),\n    (0xFD10, 'M', 'ضر'),\n    (0xFD11, 'M', 'طى'),\n    (0xFD12, 'M', 'طي'),\n    (0xFD13, 'M', 'عى'),\n    (0xFD14, 'M', 'عي'),\n    (0xFD15, 'M', 'غى'),\n    (0xFD16, 'M', 'غي'),\n    (0xFD17, 'M', 'سى'),\n    (0xFD18, 'M', 'سي'),\n    (0xFD19, 'M', 'شى'),\n    (0xFD1A, 'M', 'شي'),\n    (0xFD1B, 'M', 'حى'),\n    (0xFD1C, 'M', 'حي'),\n    (0xFD1D, 'M', 'جى'),\n    (0xFD1E, 'M', 'جي'),\n    ]\n\ndef _seg_48() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xFD1F, 'M', 'خى'),\n    (0xFD20, 'M', 'خي'),\n    (0xFD21, 'M', 'صى'),\n    (0xFD22, 'M', 'صي'),\n    (0xFD23, 'M', 'ضى'),\n    (0xFD24, 'M', 'ضي'),\n    (0xFD25, 'M', 'شج'),\n    (0xFD26, 'M', 'شح'),\n    (0xFD27, 'M', 'شخ'),\n    (0xFD28, 'M', 'شم'),\n    (0xFD29, 'M', 'شر'),\n    (0xFD2A, 'M', 'سر'),\n    (0xFD2B, 'M', 'صر'),\n    (0xFD2C, 'M', 'ضر'),\n    (0xFD2D, 'M', 'شج'),\n    (0xFD2E, 'M', 'شح'),\n    (0xFD2F, 'M', 'شخ'),\n    (0xFD30, 'M', 'شم'),\n    (0xFD31, 'M', 'سه'),\n    (0xFD32, 'M', 'شه'),\n    (0xFD33, 'M', 'طم'),\n    (0xFD34, 'M', 'سج'),\n    (0xFD35, 'M', 'سح'),\n    (0xFD36, 'M', 'سخ'),\n    (0xFD37, 'M', 'شج'),\n    (0xFD38, 'M', 'شح'),\n    (0xFD39, 'M', 'شخ'),\n    (0xFD3A, 'M', 'طم'),\n    (0xFD3B, 'M', 'ظم'),\n    (0xFD3C, 'M', 'اً'),\n    (0xFD3E, 'V'),\n    (0xFD50, 'M', 'تجم'),\n    (0xFD51, 'M', 'تحج'),\n    (0xFD53, 'M', 'تحم'),\n    (0xFD54, 'M', 'تخم'),\n    (0xFD55, 'M', 'تمج'),\n    (0xFD56, 'M', 'تمح'),\n    (0xFD57, 'M', 'تمخ'),\n    (0xFD58, 'M', 'جمح'),\n    (0xFD5A, 'M', 'حمي'),\n    (0xFD5B, 'M', 'حمى'),\n    (0xFD5C, 'M', 'سحج'),\n    (0xFD5D, 'M', 'سجح'),\n    (0xFD5E, 'M', 'سجى'),\n    (0xFD5F, 'M', 'سمح'),\n    (0xFD61, 'M', 'سمج'),\n    (0xFD62, 'M', 'سمم'),\n    (0xFD64, 'M', 'صحح'),\n    (0xFD66, 'M', 'صمم'),\n    (0xFD67, 'M', 'شحم'),\n    (0xFD69, 'M', 'شجي'),\n    (0xFD6A, 'M', 'شمخ'),\n    (0xFD6C, 'M', 'شمم'),\n    (0xFD6E, 'M', 'ضحى'),\n    (0xFD6F, 'M', 'ضخم'),\n    (0xFD71, 'M', 'طمح'),\n    (0xFD73, 'M', 'طمم'),\n    (0xFD74, 'M', 'طمي'),\n    (0xFD75, 'M', 'عجم'),\n    (0xFD76, 'M', 'عمم'),\n    (0xFD78, 'M', 'عمى'),\n    (0xFD79, 'M', 'غمم'),\n    (0xFD7A, 'M', 'غمي'),\n    (0xFD7B, 'M', 'غمى'),\n    (0xFD7C, 'M', 'فخم'),\n    (0xFD7E, 'M', 'قمح'),\n    (0xFD7F, 'M', 'قمم'),\n    (0xFD80, 'M', 'لحم'),\n    (0xFD81, 'M', 'لحي'),\n    (0xFD82, 'M', 'لحى'),\n    (0xFD83, 'M', 'لجج'),\n    (0xFD85, 'M', 'لخم'),\n    (0xFD87, 'M', 'لمح'),\n    (0xFD89, 'M', 'محج'),\n    (0xFD8A, 'M', 'محم'),\n    (0xFD8B, 'M', 'محي'),\n    (0xFD8C, 'M', 'مجح'),\n    (0xFD8D, 'M', 'مجم'),\n    (0xFD8E, 'M', 'مخج'),\n    (0xFD8F, 'M', 'مخم'),\n    (0xFD90, 'X'),\n    (0xFD92, 'M', 'مجخ'),\n    (0xFD93, 'M', 'همج'),\n    (0xFD94, 'M', 'همم'),\n    (0xFD95, 'M', 'نحم'),\n    (0xFD96, 'M', 'نحى'),\n    (0xFD97, 'M', 'نجم'),\n    (0xFD99, 'M', 'نجى'),\n    (0xFD9A, 'M', 'نمي'),\n    (0xFD9B, 'M', 'نمى'),\n    (0xFD9C, 'M', 'يمم'),\n    (0xFD9E, 'M', 'بخي'),\n    (0xFD9F, 'M', 'تجي'),\n    (0xFDA0, 'M', 'تجى'),\n    (0xFDA1, 'M', 'تخي'),\n    (0xFDA2, 'M', 'تخى'),\n    (0xFDA3, 'M', 'تمي'),\n    (0xFDA4, 'M', 'تمى'),\n    (0xFDA5, 'M', 'جمي'),\n    (0xFDA6, 'M', 'جحى'),\n    ]\n\ndef _seg_49() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xFDA7, 'M', 'جمى'),\n    (0xFDA8, 'M', 'سخى'),\n    (0xFDA9, 'M', 'صحي'),\n    (0xFDAA, 'M', 'شحي'),\n    (0xFDAB, 'M', 'ضحي'),\n    (0xFDAC, 'M', 'لجي'),\n    (0xFDAD, 'M', 'لمي'),\n    (0xFDAE, 'M', 'يحي'),\n    (0xFDAF, 'M', 'يجي'),\n    (0xFDB0, 'M', 'يمي'),\n    (0xFDB1, 'M', 'ممي'),\n    (0xFDB2, 'M', 'قمي'),\n    (0xFDB3, 'M', 'نحي'),\n    (0xFDB4, 'M', 'قمح'),\n    (0xFDB5, 'M', 'لحم'),\n    (0xFDB6, 'M', 'عمي'),\n    (0xFDB7, 'M', 'كمي'),\n    (0xFDB8, 'M', 'نجح'),\n    (0xFDB9, 'M', 'مخي'),\n    (0xFDBA, 'M', 'لجم'),\n    (0xFDBB, 'M', 'كمم'),\n    (0xFDBC, 'M', 'لجم'),\n    (0xFDBD, 'M', 'نجح'),\n    (0xFDBE, 'M', 'جحي'),\n    (0xFDBF, 'M', 'حجي'),\n    (0xFDC0, 'M', 'مجي'),\n    (0xFDC1, 'M', 'فمي'),\n    (0xFDC2, 'M', 'بحي'),\n    (0xFDC3, 'M', 'كمم'),\n    (0xFDC4, 'M', 'عجم'),\n    (0xFDC5, 'M', 'صمم'),\n    (0xFDC6, 'M', 'سخي'),\n    (0xFDC7, 'M', 'نجي'),\n    (0xFDC8, 'X'),\n    (0xFDCF, 'V'),\n    (0xFDD0, 'X'),\n    (0xFDF0, 'M', 'صلے'),\n    (0xFDF1, 'M', 'قلے'),\n    (0xFDF2, 'M', 'الله'),\n    (0xFDF3, 'M', 'اكبر'),\n    (0xFDF4, 'M', 'محمد'),\n    (0xFDF5, 'M', 'صلعم'),\n    (0xFDF6, 'M', 'رسول'),\n    (0xFDF7, 'M', 'عليه'),\n    (0xFDF8, 'M', 'وسلم'),\n    (0xFDF9, 'M', 'صلى'),\n    (0xFDFA, '3', 'صلى الله عليه وسلم'),\n    (0xFDFB, '3', 'جل جلاله'),\n    (0xFDFC, 'M', 'ریال'),\n    (0xFDFD, 'V'),\n    (0xFE00, 'I'),\n    (0xFE10, '3', ','),\n    (0xFE11, 'M', '、'),\n    (0xFE12, 'X'),\n    (0xFE13, '3', ':'),\n    (0xFE14, '3', ';'),\n    (0xFE15, '3', '!'),\n    (0xFE16, '3', '?'),\n    (0xFE17, 'M', '〖'),\n    (0xFE18, 'M', '〗'),\n    (0xFE19, 'X'),\n    (0xFE20, 'V'),\n    (0xFE30, 'X'),\n    (0xFE31, 'M', '—'),\n    (0xFE32, 'M', '–'),\n    (0xFE33, '3', '_'),\n    (0xFE35, '3', '('),\n    (0xFE36, '3', ')'),\n    (0xFE37, '3', '{'),\n    (0xFE38, '3', '}'),\n    (0xFE39, 'M', '〔'),\n    (0xFE3A, 'M', '〕'),\n    (0xFE3B, 'M', '【'),\n    (0xFE3C, 'M', '】'),\n    (0xFE3D, 'M', '《'),\n    (0xFE3E, 'M', '》'),\n    (0xFE3F, 'M', '〈'),\n    (0xFE40, 'M', '〉'),\n    (0xFE41, 'M', '「'),\n    (0xFE42, 'M', '」'),\n    (0xFE43, 'M', '『'),\n    (0xFE44, 'M', '』'),\n    (0xFE45, 'V'),\n    (0xFE47, '3', '['),\n    (0xFE48, '3', ']'),\n    (0xFE49, '3', ' ̅'),\n    (0xFE4D, '3', '_'),\n    (0xFE50, '3', ','),\n    (0xFE51, 'M', '、'),\n    (0xFE52, 'X'),\n    (0xFE54, '3', ';'),\n    (0xFE55, '3', ':'),\n    (0xFE56, '3', '?'),\n    (0xFE57, '3', '!'),\n    (0xFE58, 'M', '—'),\n    (0xFE59, '3', '('),\n    (0xFE5A, '3', ')'),\n    (0xFE5B, '3', '{'),\n    (0xFE5C, '3', '}'),\n    (0xFE5D, 'M', '〔'),\n    ]\n\ndef _seg_50() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xFE5E, 'M', '〕'),\n    (0xFE5F, '3', '#'),\n    (0xFE60, '3', '&'),\n    (0xFE61, '3', '*'),\n    (0xFE62, '3', '+'),\n    (0xFE63, 'M', '-'),\n    (0xFE64, '3', '<'),\n    (0xFE65, '3', '>'),\n    (0xFE66, '3', '='),\n    (0xFE67, 'X'),\n    (0xFE68, '3', '\\\\'),\n    (0xFE69, '3', '$'),\n    (0xFE6A, '3', '%'),\n    (0xFE6B, '3', '@'),\n    (0xFE6C, 'X'),\n    (0xFE70, '3', ' ً'),\n    (0xFE71, 'M', 'ـً'),\n    (0xFE72, '3', ' ٌ'),\n    (0xFE73, 'V'),\n    (0xFE74, '3', ' ٍ'),\n    (0xFE75, 'X'),\n    (0xFE76, '3', ' َ'),\n    (0xFE77, 'M', 'ـَ'),\n    (0xFE78, '3', ' ُ'),\n    (0xFE79, 'M', 'ـُ'),\n    (0xFE7A, '3', ' ِ'),\n    (0xFE7B, 'M', 'ـِ'),\n    (0xFE7C, '3', ' ّ'),\n    (0xFE7D, 'M', 'ـّ'),\n    (0xFE7E, '3', ' ْ'),\n    (0xFE7F, 'M', 'ـْ'),\n    (0xFE80, 'M', 'ء'),\n    (0xFE81, 'M', 'آ'),\n    (0xFE83, 'M', 'أ'),\n    (0xFE85, 'M', 'ؤ'),\n    (0xFE87, 'M', 'إ'),\n    (0xFE89, 'M', 'ئ'),\n    (0xFE8D, 'M', 'ا'),\n    (0xFE8F, 'M', 'ب'),\n    (0xFE93, 'M', 'ة'),\n    (0xFE95, 'M', 'ت'),\n    (0xFE99, 'M', 'ث'),\n    (0xFE9D, 'M', 'ج'),\n    (0xFEA1, 'M', 'ح'),\n    (0xFEA5, 'M', 'خ'),\n    (0xFEA9, 'M', 'د'),\n    (0xFEAB, 'M', 'ذ'),\n    (0xFEAD, 'M', 'ر'),\n    (0xFEAF, 'M', 'ز'),\n    (0xFEB1, 'M', 'س'),\n    (0xFEB5, 'M', 'ش'),\n    (0xFEB9, 'M', 'ص'),\n    (0xFEBD, 'M', 'ض'),\n    (0xFEC1, 'M', 'ط'),\n    (0xFEC5, 'M', 'ظ'),\n    (0xFEC9, 'M', 'ع'),\n    (0xFECD, 'M', 'غ'),\n    (0xFED1, 'M', 'ف'),\n    (0xFED5, 'M', 'ق'),\n    (0xFED9, 'M', 'ك'),\n    (0xFEDD, 'M', 'ل'),\n    (0xFEE1, 'M', 'م'),\n    (0xFEE5, 'M', 'ن'),\n    (0xFEE9, 'M', 'ه'),\n    (0xFEED, 'M', 'و'),\n    (0xFEEF, 'M', 'ى'),\n    (0xFEF1, 'M', 'ي'),\n    (0xFEF5, 'M', 'لآ'),\n    (0xFEF7, 'M', 'لأ'),\n    (0xFEF9, 'M', 'لإ'),\n    (0xFEFB, 'M', 'لا'),\n    (0xFEFD, 'X'),\n    (0xFEFF, 'I'),\n    (0xFF00, 'X'),\n    (0xFF01, '3', '!'),\n    (0xFF02, '3', '\"'),\n    (0xFF03, '3', '#'),\n    (0xFF04, '3', '$'),\n    (0xFF05, '3', '%'),\n    (0xFF06, '3', '&'),\n    (0xFF07, '3', '\\''),\n    (0xFF08, '3', '('),\n    (0xFF09, '3', ')'),\n    (0xFF0A, '3', '*'),\n    (0xFF0B, '3', '+'),\n    (0xFF0C, '3', ','),\n    (0xFF0D, 'M', '-'),\n    (0xFF0E, 'M', '.'),\n    (0xFF0F, '3', '/'),\n    (0xFF10, 'M', '0'),\n    (0xFF11, 'M', '1'),\n    (0xFF12, 'M', '2'),\n    (0xFF13, 'M', '3'),\n    (0xFF14, 'M', '4'),\n    (0xFF15, 'M', '5'),\n    (0xFF16, 'M', '6'),\n    (0xFF17, 'M', '7'),\n    (0xFF18, 'M', '8'),\n    (0xFF19, 'M', '9'),\n    (0xFF1A, '3', ':'),\n    ]\n\ndef _seg_51() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xFF1B, '3', ';'),\n    (0xFF1C, '3', '<'),\n    (0xFF1D, '3', '='),\n    (0xFF1E, '3', '>'),\n    (0xFF1F, '3', '?'),\n    (0xFF20, '3', '@'),\n    (0xFF21, 'M', 'a'),\n    (0xFF22, 'M', 'b'),\n    (0xFF23, 'M', 'c'),\n    (0xFF24, 'M', 'd'),\n    (0xFF25, 'M', 'e'),\n    (0xFF26, 'M', 'f'),\n    (0xFF27, 'M', 'g'),\n    (0xFF28, 'M', 'h'),\n    (0xFF29, 'M', 'i'),\n    (0xFF2A, 'M', 'j'),\n    (0xFF2B, 'M', 'k'),\n    (0xFF2C, 'M', 'l'),\n    (0xFF2D, 'M', 'm'),\n    (0xFF2E, 'M', 'n'),\n    (0xFF2F, 'M', 'o'),\n    (0xFF30, 'M', 'p'),\n    (0xFF31, 'M', 'q'),\n    (0xFF32, 'M', 'r'),\n    (0xFF33, 'M', 's'),\n    (0xFF34, 'M', 't'),\n    (0xFF35, 'M', 'u'),\n    (0xFF36, 'M', 'v'),\n    (0xFF37, 'M', 'w'),\n    (0xFF38, 'M', 'x'),\n    (0xFF39, 'M', 'y'),\n    (0xFF3A, 'M', 'z'),\n    (0xFF3B, '3', '['),\n    (0xFF3C, '3', '\\\\'),\n    (0xFF3D, '3', ']'),\n    (0xFF3E, '3', '^'),\n    (0xFF3F, '3', '_'),\n    (0xFF40, '3', '`'),\n    (0xFF41, 'M', 'a'),\n    (0xFF42, 'M', 'b'),\n    (0xFF43, 'M', 'c'),\n    (0xFF44, 'M', 'd'),\n    (0xFF45, 'M', 'e'),\n    (0xFF46, 'M', 'f'),\n    (0xFF47, 'M', 'g'),\n    (0xFF48, 'M', 'h'),\n    (0xFF49, 'M', 'i'),\n    (0xFF4A, 'M', 'j'),\n    (0xFF4B, 'M', 'k'),\n    (0xFF4C, 'M', 'l'),\n    (0xFF4D, 'M', 'm'),\n    (0xFF4E, 'M', 'n'),\n    (0xFF4F, 'M', 'o'),\n    (0xFF50, 'M', 'p'),\n    (0xFF51, 'M', 'q'),\n    (0xFF52, 'M', 'r'),\n    (0xFF53, 'M', 's'),\n    (0xFF54, 'M', 't'),\n    (0xFF55, 'M', 'u'),\n    (0xFF56, 'M', 'v'),\n    (0xFF57, 'M', 'w'),\n    (0xFF58, 'M', 'x'),\n    (0xFF59, 'M', 'y'),\n    (0xFF5A, 'M', 'z'),\n    (0xFF5B, '3', '{'),\n    (0xFF5C, '3', '|'),\n    (0xFF5D, '3', '}'),\n    (0xFF5E, '3', '~'),\n    (0xFF5F, 'M', '⦅'),\n    (0xFF60, 'M', '⦆'),\n    (0xFF61, 'M', '.'),\n    (0xFF62, 'M', '「'),\n    (0xFF63, 'M', '」'),\n    (0xFF64, 'M', '、'),\n    (0xFF65, 'M', '・'),\n    (0xFF66, 'M', 'ヲ'),\n    (0xFF67, 'M', 'ァ'),\n    (0xFF68, 'M', 'ィ'),\n    (0xFF69, 'M', 'ゥ'),\n    (0xFF6A, 'M', 'ェ'),\n    (0xFF6B, 'M', 'ォ'),\n    (0xFF6C, 'M', 'ャ'),\n    (0xFF6D, 'M', 'ュ'),\n    (0xFF6E, 'M', 'ョ'),\n    (0xFF6F, 'M', 'ッ'),\n    (0xFF70, 'M', 'ー'),\n    (0xFF71, 'M', 'ア'),\n    (0xFF72, 'M', 'イ'),\n    (0xFF73, 'M', 'ウ'),\n    (0xFF74, 'M', 'エ'),\n    (0xFF75, 'M', 'オ'),\n    (0xFF76, 'M', 'カ'),\n    (0xFF77, 'M', 'キ'),\n    (0xFF78, 'M', 'ク'),\n    (0xFF79, 'M', 'ケ'),\n    (0xFF7A, 'M', 'コ'),\n    (0xFF7B, 'M', 'サ'),\n    (0xFF7C, 'M', 'シ'),\n    (0xFF7D, 'M', 'ス'),\n    (0xFF7E, 'M', 'セ'),\n    ]\n\ndef _seg_52() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xFF7F, 'M', 'ソ'),\n    (0xFF80, 'M', 'タ'),\n    (0xFF81, 'M', 'チ'),\n    (0xFF82, 'M', 'ツ'),\n    (0xFF83, 'M', 'テ'),\n    (0xFF84, 'M', 'ト'),\n    (0xFF85, 'M', 'ナ'),\n    (0xFF86, 'M', 'ニ'),\n    (0xFF87, 'M', 'ヌ'),\n    (0xFF88, 'M', 'ネ'),\n    (0xFF89, 'M', 'ノ'),\n    (0xFF8A, 'M', 'ハ'),\n    (0xFF8B, 'M', 'ヒ'),\n    (0xFF8C, 'M', 'フ'),\n    (0xFF8D, 'M', 'ヘ'),\n    (0xFF8E, 'M', 'ホ'),\n    (0xFF8F, 'M', 'マ'),\n    (0xFF90, 'M', 'ミ'),\n    (0xFF91, 'M', 'ム'),\n    (0xFF92, 'M', 'メ'),\n    (0xFF93, 'M', 'モ'),\n    (0xFF94, 'M', 'ヤ'),\n    (0xFF95, 'M', 'ユ'),\n    (0xFF96, 'M', 'ヨ'),\n    (0xFF97, 'M', 'ラ'),\n    (0xFF98, 'M', 'リ'),\n    (0xFF99, 'M', 'ル'),\n    (0xFF9A, 'M', 'レ'),\n    (0xFF9B, 'M', 'ロ'),\n    (0xFF9C, 'M', 'ワ'),\n    (0xFF9D, 'M', 'ン'),\n    (0xFF9E, 'M', '゙'),\n    (0xFF9F, 'M', '゚'),\n    (0xFFA0, 'X'),\n    (0xFFA1, 'M', 'ᄀ'),\n    (0xFFA2, 'M', 'ᄁ'),\n    (0xFFA3, 'M', 'ᆪ'),\n    (0xFFA4, 'M', 'ᄂ'),\n    (0xFFA5, 'M', 'ᆬ'),\n    (0xFFA6, 'M', 'ᆭ'),\n    (0xFFA7, 'M', 'ᄃ'),\n    (0xFFA8, 'M', 'ᄄ'),\n    (0xFFA9, 'M', 'ᄅ'),\n    (0xFFAA, 'M', 'ᆰ'),\n    (0xFFAB, 'M', 'ᆱ'),\n    (0xFFAC, 'M', 'ᆲ'),\n    (0xFFAD, 'M', 'ᆳ'),\n    (0xFFAE, 'M', 'ᆴ'),\n    (0xFFAF, 'M', 'ᆵ'),\n    (0xFFB0, 'M', 'ᄚ'),\n    (0xFFB1, 'M', 'ᄆ'),\n    (0xFFB2, 'M', 'ᄇ'),\n    (0xFFB3, 'M', 'ᄈ'),\n    (0xFFB4, 'M', 'ᄡ'),\n    (0xFFB5, 'M', 'ᄉ'),\n    (0xFFB6, 'M', 'ᄊ'),\n    (0xFFB7, 'M', 'ᄋ'),\n    (0xFFB8, 'M', 'ᄌ'),\n    (0xFFB9, 'M', 'ᄍ'),\n    (0xFFBA, 'M', 'ᄎ'),\n    (0xFFBB, 'M', 'ᄏ'),\n    (0xFFBC, 'M', 'ᄐ'),\n    (0xFFBD, 'M', 'ᄑ'),\n    (0xFFBE, 'M', 'ᄒ'),\n    (0xFFBF, 'X'),\n    (0xFFC2, 'M', 'ᅡ'),\n    (0xFFC3, 'M', 'ᅢ'),\n    (0xFFC4, 'M', 'ᅣ'),\n    (0xFFC5, 'M', 'ᅤ'),\n    (0xFFC6, 'M', 'ᅥ'),\n    (0xFFC7, 'M', 'ᅦ'),\n    (0xFFC8, 'X'),\n    (0xFFCA, 'M', 'ᅧ'),\n    (0xFFCB, 'M', 'ᅨ'),\n    (0xFFCC, 'M', 'ᅩ'),\n    (0xFFCD, 'M', 'ᅪ'),\n    (0xFFCE, 'M', 'ᅫ'),\n    (0xFFCF, 'M', 'ᅬ'),\n    (0xFFD0, 'X'),\n    (0xFFD2, 'M', 'ᅭ'),\n    (0xFFD3, 'M', 'ᅮ'),\n    (0xFFD4, 'M', 'ᅯ'),\n    (0xFFD5, 'M', 'ᅰ'),\n    (0xFFD6, 'M', 'ᅱ'),\n    (0xFFD7, 'M', 'ᅲ'),\n    (0xFFD8, 'X'),\n    (0xFFDA, 'M', 'ᅳ'),\n    (0xFFDB, 'M', 'ᅴ'),\n    (0xFFDC, 'M', 'ᅵ'),\n    (0xFFDD, 'X'),\n    (0xFFE0, 'M', '¢'),\n    (0xFFE1, 'M', '£'),\n    (0xFFE2, 'M', '¬'),\n    (0xFFE3, '3', ' ̄'),\n    (0xFFE4, 'M', '¦'),\n    (0xFFE5, 'M', '¥'),\n    (0xFFE6, 'M', '₩'),\n    (0xFFE7, 'X'),\n    (0xFFE8, 'M', '│'),\n    (0xFFE9, 'M', '←'),\n    ]\n\ndef _seg_53() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0xFFEA, 'M', '↑'),\n    (0xFFEB, 'M', '→'),\n    (0xFFEC, 'M', '↓'),\n    (0xFFED, 'M', '■'),\n    (0xFFEE, 'M', '○'),\n    (0xFFEF, 'X'),\n    (0x10000, 'V'),\n    (0x1000C, 'X'),\n    (0x1000D, 'V'),\n    (0x10027, 'X'),\n    (0x10028, 'V'),\n    (0x1003B, 'X'),\n    (0x1003C, 'V'),\n    (0x1003E, 'X'),\n    (0x1003F, 'V'),\n    (0x1004E, 'X'),\n    (0x10050, 'V'),\n    (0x1005E, 'X'),\n    (0x10080, 'V'),\n    (0x100FB, 'X'),\n    (0x10100, 'V'),\n    (0x10103, 'X'),\n    (0x10107, 'V'),\n    (0x10134, 'X'),\n    (0x10137, 'V'),\n    (0x1018F, 'X'),\n    (0x10190, 'V'),\n    (0x1019D, 'X'),\n    (0x101A0, 'V'),\n    (0x101A1, 'X'),\n    (0x101D0, 'V'),\n    (0x101FE, 'X'),\n    (0x10280, 'V'),\n    (0x1029D, 'X'),\n    (0x102A0, 'V'),\n    (0x102D1, 'X'),\n    (0x102E0, 'V'),\n    (0x102FC, 'X'),\n    (0x10300, 'V'),\n    (0x10324, 'X'),\n    (0x1032D, 'V'),\n    (0x1034B, 'X'),\n    (0x10350, 'V'),\n    (0x1037B, 'X'),\n    (0x10380, 'V'),\n    (0x1039E, 'X'),\n    (0x1039F, 'V'),\n    (0x103C4, 'X'),\n    (0x103C8, 'V'),\n    (0x103D6, 'X'),\n    (0x10400, 'M', '𐐨'),\n    (0x10401, 'M', '𐐩'),\n    (0x10402, 'M', '𐐪'),\n    (0x10403, 'M', '𐐫'),\n    (0x10404, 'M', '𐐬'),\n    (0x10405, 'M', '𐐭'),\n    (0x10406, 'M', '𐐮'),\n    (0x10407, 'M', '𐐯'),\n    (0x10408, 'M', '𐐰'),\n    (0x10409, 'M', '𐐱'),\n    (0x1040A, 'M', '𐐲'),\n    (0x1040B, 'M', '𐐳'),\n    (0x1040C, 'M', '𐐴'),\n    (0x1040D, 'M', '𐐵'),\n    (0x1040E, 'M', '𐐶'),\n    (0x1040F, 'M', '𐐷'),\n    (0x10410, 'M', '𐐸'),\n    (0x10411, 'M', '𐐹'),\n    (0x10412, 'M', '𐐺'),\n    (0x10413, 'M', '𐐻'),\n    (0x10414, 'M', '𐐼'),\n    (0x10415, 'M', '𐐽'),\n    (0x10416, 'M', '𐐾'),\n    (0x10417, 'M', '𐐿'),\n    (0x10418, 'M', '𐑀'),\n    (0x10419, 'M', '𐑁'),\n    (0x1041A, 'M', '𐑂'),\n    (0x1041B, 'M', '𐑃'),\n    (0x1041C, 'M', '𐑄'),\n    (0x1041D, 'M', '𐑅'),\n    (0x1041E, 'M', '𐑆'),\n    (0x1041F, 'M', '𐑇'),\n    (0x10420, 'M', '𐑈'),\n    (0x10421, 'M', '𐑉'),\n    (0x10422, 'M', '𐑊'),\n    (0x10423, 'M', '𐑋'),\n    (0x10424, 'M', '𐑌'),\n    (0x10425, 'M', '𐑍'),\n    (0x10426, 'M', '𐑎'),\n    (0x10427, 'M', '𐑏'),\n    (0x10428, 'V'),\n    (0x1049E, 'X'),\n    (0x104A0, 'V'),\n    (0x104AA, 'X'),\n    (0x104B0, 'M', '𐓘'),\n    (0x104B1, 'M', '𐓙'),\n    (0x104B2, 'M', '𐓚'),\n    (0x104B3, 'M', '𐓛'),\n    (0x104B4, 'M', '𐓜'),\n    (0x104B5, 'M', '𐓝'),\n    ]\n\ndef _seg_54() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x104B6, 'M', '𐓞'),\n    (0x104B7, 'M', '𐓟'),\n    (0x104B8, 'M', '𐓠'),\n    (0x104B9, 'M', '𐓡'),\n    (0x104BA, 'M', '𐓢'),\n    (0x104BB, 'M', '𐓣'),\n    (0x104BC, 'M', '𐓤'),\n    (0x104BD, 'M', '𐓥'),\n    (0x104BE, 'M', '𐓦'),\n    (0x104BF, 'M', '𐓧'),\n    (0x104C0, 'M', '𐓨'),\n    (0x104C1, 'M', '𐓩'),\n    (0x104C2, 'M', '𐓪'),\n    (0x104C3, 'M', '𐓫'),\n    (0x104C4, 'M', '𐓬'),\n    (0x104C5, 'M', '𐓭'),\n    (0x104C6, 'M', '𐓮'),\n    (0x104C7, 'M', '𐓯'),\n    (0x104C8, 'M', '𐓰'),\n    (0x104C9, 'M', '𐓱'),\n    (0x104CA, 'M', '𐓲'),\n    (0x104CB, 'M', '𐓳'),\n    (0x104CC, 'M', '𐓴'),\n    (0x104CD, 'M', '𐓵'),\n    (0x104CE, 'M', '𐓶'),\n    (0x104CF, 'M', '𐓷'),\n    (0x104D0, 'M', '𐓸'),\n    (0x104D1, 'M', '𐓹'),\n    (0x104D2, 'M', '𐓺'),\n    (0x104D3, 'M', '𐓻'),\n    (0x104D4, 'X'),\n    (0x104D8, 'V'),\n    (0x104FC, 'X'),\n    (0x10500, 'V'),\n    (0x10528, 'X'),\n    (0x10530, 'V'),\n    (0x10564, 'X'),\n    (0x1056F, 'V'),\n    (0x10570, 'M', '𐖗'),\n    (0x10571, 'M', '𐖘'),\n    (0x10572, 'M', '𐖙'),\n    (0x10573, 'M', '𐖚'),\n    (0x10574, 'M', '𐖛'),\n    (0x10575, 'M', '𐖜'),\n    (0x10576, 'M', '𐖝'),\n    (0x10577, 'M', '𐖞'),\n    (0x10578, 'M', '𐖟'),\n    (0x10579, 'M', '𐖠'),\n    (0x1057A, 'M', '𐖡'),\n    (0x1057B, 'X'),\n    (0x1057C, 'M', '𐖣'),\n    (0x1057D, 'M', '𐖤'),\n    (0x1057E, 'M', '𐖥'),\n    (0x1057F, 'M', '𐖦'),\n    (0x10580, 'M', '𐖧'),\n    (0x10581, 'M', '𐖨'),\n    (0x10582, 'M', '𐖩'),\n    (0x10583, 'M', '𐖪'),\n    (0x10584, 'M', '𐖫'),\n    (0x10585, 'M', '𐖬'),\n    (0x10586, 'M', '𐖭'),\n    (0x10587, 'M', '𐖮'),\n    (0x10588, 'M', '𐖯'),\n    (0x10589, 'M', '𐖰'),\n    (0x1058A, 'M', '𐖱'),\n    (0x1058B, 'X'),\n    (0x1058C, 'M', '𐖳'),\n    (0x1058D, 'M', '𐖴'),\n    (0x1058E, 'M', '𐖵'),\n    (0x1058F, 'M', '𐖶'),\n    (0x10590, 'M', '𐖷'),\n    (0x10591, 'M', '𐖸'),\n    (0x10592, 'M', '𐖹'),\n    (0x10593, 'X'),\n    (0x10594, 'M', '𐖻'),\n    (0x10595, 'M', '𐖼'),\n    (0x10596, 'X'),\n    (0x10597, 'V'),\n    (0x105A2, 'X'),\n    (0x105A3, 'V'),\n    (0x105B2, 'X'),\n    (0x105B3, 'V'),\n    (0x105BA, 'X'),\n    (0x105BB, 'V'),\n    (0x105BD, 'X'),\n    (0x10600, 'V'),\n    (0x10737, 'X'),\n    (0x10740, 'V'),\n    (0x10756, 'X'),\n    (0x10760, 'V'),\n    (0x10768, 'X'),\n    (0x10780, 'V'),\n    (0x10781, 'M', 'ː'),\n    (0x10782, 'M', 'ˑ'),\n    (0x10783, 'M', 'æ'),\n    (0x10784, 'M', 'ʙ'),\n    (0x10785, 'M', 'ɓ'),\n    (0x10786, 'X'),\n    (0x10787, 'M', 'ʣ'),\n    (0x10788, 'M', 'ꭦ'),\n    ]\n\ndef _seg_55() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x10789, 'M', 'ʥ'),\n    (0x1078A, 'M', 'ʤ'),\n    (0x1078B, 'M', 'ɖ'),\n    (0x1078C, 'M', 'ɗ'),\n    (0x1078D, 'M', 'ᶑ'),\n    (0x1078E, 'M', 'ɘ'),\n    (0x1078F, 'M', 'ɞ'),\n    (0x10790, 'M', 'ʩ'),\n    (0x10791, 'M', 'ɤ'),\n    (0x10792, 'M', 'ɢ'),\n    (0x10793, 'M', 'ɠ'),\n    (0x10794, 'M', 'ʛ'),\n    (0x10795, 'M', 'ħ'),\n    (0x10796, 'M', 'ʜ'),\n    (0x10797, 'M', 'ɧ'),\n    (0x10798, 'M', 'ʄ'),\n    (0x10799, 'M', 'ʪ'),\n    (0x1079A, 'M', 'ʫ'),\n    (0x1079B, 'M', 'ɬ'),\n    (0x1079C, 'M', '𝼄'),\n    (0x1079D, 'M', 'ꞎ'),\n    (0x1079E, 'M', 'ɮ'),\n    (0x1079F, 'M', '𝼅'),\n    (0x107A0, 'M', 'ʎ'),\n    (0x107A1, 'M', '𝼆'),\n    (0x107A2, 'M', 'ø'),\n    (0x107A3, 'M', 'ɶ'),\n    (0x107A4, 'M', 'ɷ'),\n    (0x107A5, 'M', 'q'),\n    (0x107A6, 'M', 'ɺ'),\n    (0x107A7, 'M', '𝼈'),\n    (0x107A8, 'M', 'ɽ'),\n    (0x107A9, 'M', 'ɾ'),\n    (0x107AA, 'M', 'ʀ'),\n    (0x107AB, 'M', 'ʨ'),\n    (0x107AC, 'M', 'ʦ'),\n    (0x107AD, 'M', 'ꭧ'),\n    (0x107AE, 'M', 'ʧ'),\n    (0x107AF, 'M', 'ʈ'),\n    (0x107B0, 'M', 'ⱱ'),\n    (0x107B1, 'X'),\n    (0x107B2, 'M', 'ʏ'),\n    (0x107B3, 'M', 'ʡ'),\n    (0x107B4, 'M', 'ʢ'),\n    (0x107B5, 'M', 'ʘ'),\n    (0x107B6, 'M', 'ǀ'),\n    (0x107B7, 'M', 'ǁ'),\n    (0x107B8, 'M', 'ǂ'),\n    (0x107B9, 'M', '𝼊'),\n    (0x107BA, 'M', '𝼞'),\n    (0x107BB, 'X'),\n    (0x10800, 'V'),\n    (0x10806, 'X'),\n    (0x10808, 'V'),\n    (0x10809, 'X'),\n    (0x1080A, 'V'),\n    (0x10836, 'X'),\n    (0x10837, 'V'),\n    (0x10839, 'X'),\n    (0x1083C, 'V'),\n    (0x1083D, 'X'),\n    (0x1083F, 'V'),\n    (0x10856, 'X'),\n    (0x10857, 'V'),\n    (0x1089F, 'X'),\n    (0x108A7, 'V'),\n    (0x108B0, 'X'),\n    (0x108E0, 'V'),\n    (0x108F3, 'X'),\n    (0x108F4, 'V'),\n    (0x108F6, 'X'),\n    (0x108FB, 'V'),\n    (0x1091C, 'X'),\n    (0x1091F, 'V'),\n    (0x1093A, 'X'),\n    (0x1093F, 'V'),\n    (0x10940, 'X'),\n    (0x10980, 'V'),\n    (0x109B8, 'X'),\n    (0x109BC, 'V'),\n    (0x109D0, 'X'),\n    (0x109D2, 'V'),\n    (0x10A04, 'X'),\n    (0x10A05, 'V'),\n    (0x10A07, 'X'),\n    (0x10A0C, 'V'),\n    (0x10A14, 'X'),\n    (0x10A15, 'V'),\n    (0x10A18, 'X'),\n    (0x10A19, 'V'),\n    (0x10A36, 'X'),\n    (0x10A38, 'V'),\n    (0x10A3B, 'X'),\n    (0x10A3F, 'V'),\n    (0x10A49, 'X'),\n    (0x10A50, 'V'),\n    (0x10A59, 'X'),\n    (0x10A60, 'V'),\n    (0x10AA0, 'X'),\n    (0x10AC0, 'V'),\n    ]\n\ndef _seg_56() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x10AE7, 'X'),\n    (0x10AEB, 'V'),\n    (0x10AF7, 'X'),\n    (0x10B00, 'V'),\n    (0x10B36, 'X'),\n    (0x10B39, 'V'),\n    (0x10B56, 'X'),\n    (0x10B58, 'V'),\n    (0x10B73, 'X'),\n    (0x10B78, 'V'),\n    (0x10B92, 'X'),\n    (0x10B99, 'V'),\n    (0x10B9D, 'X'),\n    (0x10BA9, 'V'),\n    (0x10BB0, 'X'),\n    (0x10C00, 'V'),\n    (0x10C49, 'X'),\n    (0x10C80, 'M', '𐳀'),\n    (0x10C81, 'M', '𐳁'),\n    (0x10C82, 'M', '𐳂'),\n    (0x10C83, 'M', '𐳃'),\n    (0x10C84, 'M', '𐳄'),\n    (0x10C85, 'M', '𐳅'),\n    (0x10C86, 'M', '𐳆'),\n    (0x10C87, 'M', '𐳇'),\n    (0x10C88, 'M', '𐳈'),\n    (0x10C89, 'M', '𐳉'),\n    (0x10C8A, 'M', '𐳊'),\n    (0x10C8B, 'M', '𐳋'),\n    (0x10C8C, 'M', '𐳌'),\n    (0x10C8D, 'M', '𐳍'),\n    (0x10C8E, 'M', '𐳎'),\n    (0x10C8F, 'M', '𐳏'),\n    (0x10C90, 'M', '𐳐'),\n    (0x10C91, 'M', '𐳑'),\n    (0x10C92, 'M', '𐳒'),\n    (0x10C93, 'M', '𐳓'),\n    (0x10C94, 'M', '𐳔'),\n    (0x10C95, 'M', '𐳕'),\n    (0x10C96, 'M', '𐳖'),\n    (0x10C97, 'M', '𐳗'),\n    (0x10C98, 'M', '𐳘'),\n    (0x10C99, 'M', '𐳙'),\n    (0x10C9A, 'M', '𐳚'),\n    (0x10C9B, 'M', '𐳛'),\n    (0x10C9C, 'M', '𐳜'),\n    (0x10C9D, 'M', '𐳝'),\n    (0x10C9E, 'M', '𐳞'),\n    (0x10C9F, 'M', '𐳟'),\n    (0x10CA0, 'M', '𐳠'),\n    (0x10CA1, 'M', '𐳡'),\n    (0x10CA2, 'M', '𐳢'),\n    (0x10CA3, 'M', '𐳣'),\n    (0x10CA4, 'M', '𐳤'),\n    (0x10CA5, 'M', '𐳥'),\n    (0x10CA6, 'M', '𐳦'),\n    (0x10CA7, 'M', '𐳧'),\n    (0x10CA8, 'M', '𐳨'),\n    (0x10CA9, 'M', '𐳩'),\n    (0x10CAA, 'M', '𐳪'),\n    (0x10CAB, 'M', '𐳫'),\n    (0x10CAC, 'M', '𐳬'),\n    (0x10CAD, 'M', '𐳭'),\n    (0x10CAE, 'M', '𐳮'),\n    (0x10CAF, 'M', '𐳯'),\n    (0x10CB0, 'M', '𐳰'),\n    (0x10CB1, 'M', '𐳱'),\n    (0x10CB2, 'M', '𐳲'),\n    (0x10CB3, 'X'),\n    (0x10CC0, 'V'),\n    (0x10CF3, 'X'),\n    (0x10CFA, 'V'),\n    (0x10D28, 'X'),\n    (0x10D30, 'V'),\n    (0x10D3A, 'X'),\n    (0x10E60, 'V'),\n    (0x10E7F, 'X'),\n    (0x10E80, 'V'),\n    (0x10EAA, 'X'),\n    (0x10EAB, 'V'),\n    (0x10EAE, 'X'),\n    (0x10EB0, 'V'),\n    (0x10EB2, 'X'),\n    (0x10EFD, 'V'),\n    (0x10F28, 'X'),\n    (0x10F30, 'V'),\n    (0x10F5A, 'X'),\n    (0x10F70, 'V'),\n    (0x10F8A, 'X'),\n    (0x10FB0, 'V'),\n    (0x10FCC, 'X'),\n    (0x10FE0, 'V'),\n    (0x10FF7, 'X'),\n    (0x11000, 'V'),\n    (0x1104E, 'X'),\n    (0x11052, 'V'),\n    (0x11076, 'X'),\n    (0x1107F, 'V'),\n    (0x110BD, 'X'),\n    (0x110BE, 'V'),\n    ]\n\ndef _seg_57() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x110C3, 'X'),\n    (0x110D0, 'V'),\n    (0x110E9, 'X'),\n    (0x110F0, 'V'),\n    (0x110FA, 'X'),\n    (0x11100, 'V'),\n    (0x11135, 'X'),\n    (0x11136, 'V'),\n    (0x11148, 'X'),\n    (0x11150, 'V'),\n    (0x11177, 'X'),\n    (0x11180, 'V'),\n    (0x111E0, 'X'),\n    (0x111E1, 'V'),\n    (0x111F5, 'X'),\n    (0x11200, 'V'),\n    (0x11212, 'X'),\n    (0x11213, 'V'),\n    (0x11242, 'X'),\n    (0x11280, 'V'),\n    (0x11287, 'X'),\n    (0x11288, 'V'),\n    (0x11289, 'X'),\n    (0x1128A, 'V'),\n    (0x1128E, 'X'),\n    (0x1128F, 'V'),\n    (0x1129E, 'X'),\n    (0x1129F, 'V'),\n    (0x112AA, 'X'),\n    (0x112B0, 'V'),\n    (0x112EB, 'X'),\n    (0x112F0, 'V'),\n    (0x112FA, 'X'),\n    (0x11300, 'V'),\n    (0x11304, 'X'),\n    (0x11305, 'V'),\n    (0x1130D, 'X'),\n    (0x1130F, 'V'),\n    (0x11311, 'X'),\n    (0x11313, 'V'),\n    (0x11329, 'X'),\n    (0x1132A, 'V'),\n    (0x11331, 'X'),\n    (0x11332, 'V'),\n    (0x11334, 'X'),\n    (0x11335, 'V'),\n    (0x1133A, 'X'),\n    (0x1133B, 'V'),\n    (0x11345, 'X'),\n    (0x11347, 'V'),\n    (0x11349, 'X'),\n    (0x1134B, 'V'),\n    (0x1134E, 'X'),\n    (0x11350, 'V'),\n    (0x11351, 'X'),\n    (0x11357, 'V'),\n    (0x11358, 'X'),\n    (0x1135D, 'V'),\n    (0x11364, 'X'),\n    (0x11366, 'V'),\n    (0x1136D, 'X'),\n    (0x11370, 'V'),\n    (0x11375, 'X'),\n    (0x11400, 'V'),\n    (0x1145C, 'X'),\n    (0x1145D, 'V'),\n    (0x11462, 'X'),\n    (0x11480, 'V'),\n    (0x114C8, 'X'),\n    (0x114D0, 'V'),\n    (0x114DA, 'X'),\n    (0x11580, 'V'),\n    (0x115B6, 'X'),\n    (0x115B8, 'V'),\n    (0x115DE, 'X'),\n    (0x11600, 'V'),\n    (0x11645, 'X'),\n    (0x11650, 'V'),\n    (0x1165A, 'X'),\n    (0x11660, 'V'),\n    (0x1166D, 'X'),\n    (0x11680, 'V'),\n    (0x116BA, 'X'),\n    (0x116C0, 'V'),\n    (0x116CA, 'X'),\n    (0x11700, 'V'),\n    (0x1171B, 'X'),\n    (0x1171D, 'V'),\n    (0x1172C, 'X'),\n    (0x11730, 'V'),\n    (0x11747, 'X'),\n    (0x11800, 'V'),\n    (0x1183C, 'X'),\n    (0x118A0, 'M', '𑣀'),\n    (0x118A1, 'M', '𑣁'),\n    (0x118A2, 'M', '𑣂'),\n    (0x118A3, 'M', '𑣃'),\n    (0x118A4, 'M', '𑣄'),\n    (0x118A5, 'M', '𑣅'),\n    (0x118A6, 'M', '𑣆'),\n    ]\n\ndef _seg_58() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x118A7, 'M', '𑣇'),\n    (0x118A8, 'M', '𑣈'),\n    (0x118A9, 'M', '𑣉'),\n    (0x118AA, 'M', '𑣊'),\n    (0x118AB, 'M', '𑣋'),\n    (0x118AC, 'M', '𑣌'),\n    (0x118AD, 'M', '𑣍'),\n    (0x118AE, 'M', '𑣎'),\n    (0x118AF, 'M', '𑣏'),\n    (0x118B0, 'M', '𑣐'),\n    (0x118B1, 'M', '𑣑'),\n    (0x118B2, 'M', '𑣒'),\n    (0x118B3, 'M', '𑣓'),\n    (0x118B4, 'M', '𑣔'),\n    (0x118B5, 'M', '𑣕'),\n    (0x118B6, 'M', '𑣖'),\n    (0x118B7, 'M', '𑣗'),\n    (0x118B8, 'M', '𑣘'),\n    (0x118B9, 'M', '𑣙'),\n    (0x118BA, 'M', '𑣚'),\n    (0x118BB, 'M', '𑣛'),\n    (0x118BC, 'M', '𑣜'),\n    (0x118BD, 'M', '𑣝'),\n    (0x118BE, 'M', '𑣞'),\n    (0x118BF, 'M', '𑣟'),\n    (0x118C0, 'V'),\n    (0x118F3, 'X'),\n    (0x118FF, 'V'),\n    (0x11907, 'X'),\n    (0x11909, 'V'),\n    (0x1190A, 'X'),\n    (0x1190C, 'V'),\n    (0x11914, 'X'),\n    (0x11915, 'V'),\n    (0x11917, 'X'),\n    (0x11918, 'V'),\n    (0x11936, 'X'),\n    (0x11937, 'V'),\n    (0x11939, 'X'),\n    (0x1193B, 'V'),\n    (0x11947, 'X'),\n    (0x11950, 'V'),\n    (0x1195A, 'X'),\n    (0x119A0, 'V'),\n    (0x119A8, 'X'),\n    (0x119AA, 'V'),\n    (0x119D8, 'X'),\n    (0x119DA, 'V'),\n    (0x119E5, 'X'),\n    (0x11A00, 'V'),\n    (0x11A48, 'X'),\n    (0x11A50, 'V'),\n    (0x11AA3, 'X'),\n    (0x11AB0, 'V'),\n    (0x11AF9, 'X'),\n    (0x11B00, 'V'),\n    (0x11B0A, 'X'),\n    (0x11C00, 'V'),\n    (0x11C09, 'X'),\n    (0x11C0A, 'V'),\n    (0x11C37, 'X'),\n    (0x11C38, 'V'),\n    (0x11C46, 'X'),\n    (0x11C50, 'V'),\n    (0x11C6D, 'X'),\n    (0x11C70, 'V'),\n    (0x11C90, 'X'),\n    (0x11C92, 'V'),\n    (0x11CA8, 'X'),\n    (0x11CA9, 'V'),\n    (0x11CB7, 'X'),\n    (0x11D00, 'V'),\n    (0x11D07, 'X'),\n    (0x11D08, 'V'),\n    (0x11D0A, 'X'),\n    (0x11D0B, 'V'),\n    (0x11D37, 'X'),\n    (0x11D3A, 'V'),\n    (0x11D3B, 'X'),\n    (0x11D3C, 'V'),\n    (0x11D3E, 'X'),\n    (0x11D3F, 'V'),\n    (0x11D48, 'X'),\n    (0x11D50, 'V'),\n    (0x11D5A, 'X'),\n    (0x11D60, 'V'),\n    (0x11D66, 'X'),\n    (0x11D67, 'V'),\n    (0x11D69, 'X'),\n    (0x11D6A, 'V'),\n    (0x11D8F, 'X'),\n    (0x11D90, 'V'),\n    (0x11D92, 'X'),\n    (0x11D93, 'V'),\n    (0x11D99, 'X'),\n    (0x11DA0, 'V'),\n    (0x11DAA, 'X'),\n    (0x11EE0, 'V'),\n    (0x11EF9, 'X'),\n    (0x11F00, 'V'),\n    ]\n\ndef _seg_59() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x11F11, 'X'),\n    (0x11F12, 'V'),\n    (0x11F3B, 'X'),\n    (0x11F3E, 'V'),\n    (0x11F5A, 'X'),\n    (0x11FB0, 'V'),\n    (0x11FB1, 'X'),\n    (0x11FC0, 'V'),\n    (0x11FF2, 'X'),\n    (0x11FFF, 'V'),\n    (0x1239A, 'X'),\n    (0x12400, 'V'),\n    (0x1246F, 'X'),\n    (0x12470, 'V'),\n    (0x12475, 'X'),\n    (0x12480, 'V'),\n    (0x12544, 'X'),\n    (0x12F90, 'V'),\n    (0x12FF3, 'X'),\n    (0x13000, 'V'),\n    (0x13430, 'X'),\n    (0x13440, 'V'),\n    (0x13456, 'X'),\n    (0x14400, 'V'),\n    (0x14647, 'X'),\n    (0x16800, 'V'),\n    (0x16A39, 'X'),\n    (0x16A40, 'V'),\n    (0x16A5F, 'X'),\n    (0x16A60, 'V'),\n    (0x16A6A, 'X'),\n    (0x16A6E, 'V'),\n    (0x16ABF, 'X'),\n    (0x16AC0, 'V'),\n    (0x16ACA, 'X'),\n    (0x16AD0, 'V'),\n    (0x16AEE, 'X'),\n    (0x16AF0, 'V'),\n    (0x16AF6, 'X'),\n    (0x16B00, 'V'),\n    (0x16B46, 'X'),\n    (0x16B50, 'V'),\n    (0x16B5A, 'X'),\n    (0x16B5B, 'V'),\n    (0x16B62, 'X'),\n    (0x16B63, 'V'),\n    (0x16B78, 'X'),\n    (0x16B7D, 'V'),\n    (0x16B90, 'X'),\n    (0x16E40, 'M', '𖹠'),\n    (0x16E41, 'M', '𖹡'),\n    (0x16E42, 'M', '𖹢'),\n    (0x16E43, 'M', '𖹣'),\n    (0x16E44, 'M', '𖹤'),\n    (0x16E45, 'M', '𖹥'),\n    (0x16E46, 'M', '𖹦'),\n    (0x16E47, 'M', '𖹧'),\n    (0x16E48, 'M', '𖹨'),\n    (0x16E49, 'M', '𖹩'),\n    (0x16E4A, 'M', '𖹪'),\n    (0x16E4B, 'M', '𖹫'),\n    (0x16E4C, 'M', '𖹬'),\n    (0x16E4D, 'M', '𖹭'),\n    (0x16E4E, 'M', '𖹮'),\n    (0x16E4F, 'M', '𖹯'),\n    (0x16E50, 'M', '𖹰'),\n    (0x16E51, 'M', '𖹱'),\n    (0x16E52, 'M', '𖹲'),\n    (0x16E53, 'M', '𖹳'),\n    (0x16E54, 'M', '𖹴'),\n    (0x16E55, 'M', '𖹵'),\n    (0x16E56, 'M', '𖹶'),\n    (0x16E57, 'M', '𖹷'),\n    (0x16E58, 'M', '𖹸'),\n    (0x16E59, 'M', '𖹹'),\n    (0x16E5A, 'M', '𖹺'),\n    (0x16E5B, 'M', '𖹻'),\n    (0x16E5C, 'M', '𖹼'),\n    (0x16E5D, 'M', '𖹽'),\n    (0x16E5E, 'M', '𖹾'),\n    (0x16E5F, 'M', '𖹿'),\n    (0x16E60, 'V'),\n    (0x16E9B, 'X'),\n    (0x16F00, 'V'),\n    (0x16F4B, 'X'),\n    (0x16F4F, 'V'),\n    (0x16F88, 'X'),\n    (0x16F8F, 'V'),\n    (0x16FA0, 'X'),\n    (0x16FE0, 'V'),\n    (0x16FE5, 'X'),\n    (0x16FF0, 'V'),\n    (0x16FF2, 'X'),\n    (0x17000, 'V'),\n    (0x187F8, 'X'),\n    (0x18800, 'V'),\n    (0x18CD6, 'X'),\n    (0x18D00, 'V'),\n    (0x18D09, 'X'),\n    (0x1AFF0, 'V'),\n    ]\n\ndef _seg_60() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1AFF4, 'X'),\n    (0x1AFF5, 'V'),\n    (0x1AFFC, 'X'),\n    (0x1AFFD, 'V'),\n    (0x1AFFF, 'X'),\n    (0x1B000, 'V'),\n    (0x1B123, 'X'),\n    (0x1B132, 'V'),\n    (0x1B133, 'X'),\n    (0x1B150, 'V'),\n    (0x1B153, 'X'),\n    (0x1B155, 'V'),\n    (0x1B156, 'X'),\n    (0x1B164, 'V'),\n    (0x1B168, 'X'),\n    (0x1B170, 'V'),\n    (0x1B2FC, 'X'),\n    (0x1BC00, 'V'),\n    (0x1BC6B, 'X'),\n    (0x1BC70, 'V'),\n    (0x1BC7D, 'X'),\n    (0x1BC80, 'V'),\n    (0x1BC89, 'X'),\n    (0x1BC90, 'V'),\n    (0x1BC9A, 'X'),\n    (0x1BC9C, 'V'),\n    (0x1BCA0, 'I'),\n    (0x1BCA4, 'X'),\n    (0x1CF00, 'V'),\n    (0x1CF2E, 'X'),\n    (0x1CF30, 'V'),\n    (0x1CF47, 'X'),\n    (0x1CF50, 'V'),\n    (0x1CFC4, 'X'),\n    (0x1D000, 'V'),\n    (0x1D0F6, 'X'),\n    (0x1D100, 'V'),\n    (0x1D127, 'X'),\n    (0x1D129, 'V'),\n    (0x1D15E, 'M', '𝅗𝅥'),\n    (0x1D15F, 'M', '𝅘𝅥'),\n    (0x1D160, 'M', '𝅘𝅥𝅮'),\n    (0x1D161, 'M', '𝅘𝅥𝅯'),\n    (0x1D162, 'M', '𝅘𝅥𝅰'),\n    (0x1D163, 'M', '𝅘𝅥𝅱'),\n    (0x1D164, 'M', '𝅘𝅥𝅲'),\n    (0x1D165, 'V'),\n    (0x1D173, 'X'),\n    (0x1D17B, 'V'),\n    (0x1D1BB, 'M', '𝆹𝅥'),\n    (0x1D1BC, 'M', '𝆺𝅥'),\n    (0x1D1BD, 'M', '𝆹𝅥𝅮'),\n    (0x1D1BE, 'M', '𝆺𝅥𝅮'),\n    (0x1D1BF, 'M', '𝆹𝅥𝅯'),\n    (0x1D1C0, 'M', '𝆺𝅥𝅯'),\n    (0x1D1C1, 'V'),\n    (0x1D1EB, 'X'),\n    (0x1D200, 'V'),\n    (0x1D246, 'X'),\n    (0x1D2C0, 'V'),\n    (0x1D2D4, 'X'),\n    (0x1D2E0, 'V'),\n    (0x1D2F4, 'X'),\n    (0x1D300, 'V'),\n    (0x1D357, 'X'),\n    (0x1D360, 'V'),\n    (0x1D379, 'X'),\n    (0x1D400, 'M', 'a'),\n    (0x1D401, 'M', 'b'),\n    (0x1D402, 'M', 'c'),\n    (0x1D403, 'M', 'd'),\n    (0x1D404, 'M', 'e'),\n    (0x1D405, 'M', 'f'),\n    (0x1D406, 'M', 'g'),\n    (0x1D407, 'M', 'h'),\n    (0x1D408, 'M', 'i'),\n    (0x1D409, 'M', 'j'),\n    (0x1D40A, 'M', 'k'),\n    (0x1D40B, 'M', 'l'),\n    (0x1D40C, 'M', 'm'),\n    (0x1D40D, 'M', 'n'),\n    (0x1D40E, 'M', 'o'),\n    (0x1D40F, 'M', 'p'),\n    (0x1D410, 'M', 'q'),\n    (0x1D411, 'M', 'r'),\n    (0x1D412, 'M', 's'),\n    (0x1D413, 'M', 't'),\n    (0x1D414, 'M', 'u'),\n    (0x1D415, 'M', 'v'),\n    (0x1D416, 'M', 'w'),\n    (0x1D417, 'M', 'x'),\n    (0x1D418, 'M', 'y'),\n    (0x1D419, 'M', 'z'),\n    (0x1D41A, 'M', 'a'),\n    (0x1D41B, 'M', 'b'),\n    (0x1D41C, 'M', 'c'),\n    (0x1D41D, 'M', 'd'),\n    (0x1D41E, 'M', 'e'),\n    (0x1D41F, 'M', 'f'),\n    (0x1D420, 'M', 'g'),\n    ]\n\ndef _seg_61() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1D421, 'M', 'h'),\n    (0x1D422, 'M', 'i'),\n    (0x1D423, 'M', 'j'),\n    (0x1D424, 'M', 'k'),\n    (0x1D425, 'M', 'l'),\n    (0x1D426, 'M', 'm'),\n    (0x1D427, 'M', 'n'),\n    (0x1D428, 'M', 'o'),\n    (0x1D429, 'M', 'p'),\n    (0x1D42A, 'M', 'q'),\n    (0x1D42B, 'M', 'r'),\n    (0x1D42C, 'M', 's'),\n    (0x1D42D, 'M', 't'),\n    (0x1D42E, 'M', 'u'),\n    (0x1D42F, 'M', 'v'),\n    (0x1D430, 'M', 'w'),\n    (0x1D431, 'M', 'x'),\n    (0x1D432, 'M', 'y'),\n    (0x1D433, 'M', 'z'),\n    (0x1D434, 'M', 'a'),\n    (0x1D435, 'M', 'b'),\n    (0x1D436, 'M', 'c'),\n    (0x1D437, 'M', 'd'),\n    (0x1D438, 'M', 'e'),\n    (0x1D439, 'M', 'f'),\n    (0x1D43A, 'M', 'g'),\n    (0x1D43B, 'M', 'h'),\n    (0x1D43C, 'M', 'i'),\n    (0x1D43D, 'M', 'j'),\n    (0x1D43E, 'M', 'k'),\n    (0x1D43F, 'M', 'l'),\n    (0x1D440, 'M', 'm'),\n    (0x1D441, 'M', 'n'),\n    (0x1D442, 'M', 'o'),\n    (0x1D443, 'M', 'p'),\n    (0x1D444, 'M', 'q'),\n    (0x1D445, 'M', 'r'),\n    (0x1D446, 'M', 's'),\n    (0x1D447, 'M', 't'),\n    (0x1D448, 'M', 'u'),\n    (0x1D449, 'M', 'v'),\n    (0x1D44A, 'M', 'w'),\n    (0x1D44B, 'M', 'x'),\n    (0x1D44C, 'M', 'y'),\n    (0x1D44D, 'M', 'z'),\n    (0x1D44E, 'M', 'a'),\n    (0x1D44F, 'M', 'b'),\n    (0x1D450, 'M', 'c'),\n    (0x1D451, 'M', 'd'),\n    (0x1D452, 'M', 'e'),\n    (0x1D453, 'M', 'f'),\n    (0x1D454, 'M', 'g'),\n    (0x1D455, 'X'),\n    (0x1D456, 'M', 'i'),\n    (0x1D457, 'M', 'j'),\n    (0x1D458, 'M', 'k'),\n    (0x1D459, 'M', 'l'),\n    (0x1D45A, 'M', 'm'),\n    (0x1D45B, 'M', 'n'),\n    (0x1D45C, 'M', 'o'),\n    (0x1D45D, 'M', 'p'),\n    (0x1D45E, 'M', 'q'),\n    (0x1D45F, 'M', 'r'),\n    (0x1D460, 'M', 's'),\n    (0x1D461, 'M', 't'),\n    (0x1D462, 'M', 'u'),\n    (0x1D463, 'M', 'v'),\n    (0x1D464, 'M', 'w'),\n    (0x1D465, 'M', 'x'),\n    (0x1D466, 'M', 'y'),\n    (0x1D467, 'M', 'z'),\n    (0x1D468, 'M', 'a'),\n    (0x1D469, 'M', 'b'),\n    (0x1D46A, 'M', 'c'),\n    (0x1D46B, 'M', 'd'),\n    (0x1D46C, 'M', 'e'),\n    (0x1D46D, 'M', 'f'),\n    (0x1D46E, 'M', 'g'),\n    (0x1D46F, 'M', 'h'),\n    (0x1D470, 'M', 'i'),\n    (0x1D471, 'M', 'j'),\n    (0x1D472, 'M', 'k'),\n    (0x1D473, 'M', 'l'),\n    (0x1D474, 'M', 'm'),\n    (0x1D475, 'M', 'n'),\n    (0x1D476, 'M', 'o'),\n    (0x1D477, 'M', 'p'),\n    (0x1D478, 'M', 'q'),\n    (0x1D479, 'M', 'r'),\n    (0x1D47A, 'M', 's'),\n    (0x1D47B, 'M', 't'),\n    (0x1D47C, 'M', 'u'),\n    (0x1D47D, 'M', 'v'),\n    (0x1D47E, 'M', 'w'),\n    (0x1D47F, 'M', 'x'),\n    (0x1D480, 'M', 'y'),\n    (0x1D481, 'M', 'z'),\n    (0x1D482, 'M', 'a'),\n    (0x1D483, 'M', 'b'),\n    (0x1D484, 'M', 'c'),\n    ]\n\ndef _seg_62() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1D485, 'M', 'd'),\n    (0x1D486, 'M', 'e'),\n    (0x1D487, 'M', 'f'),\n    (0x1D488, 'M', 'g'),\n    (0x1D489, 'M', 'h'),\n    (0x1D48A, 'M', 'i'),\n    (0x1D48B, 'M', 'j'),\n    (0x1D48C, 'M', 'k'),\n    (0x1D48D, 'M', 'l'),\n    (0x1D48E, 'M', 'm'),\n    (0x1D48F, 'M', 'n'),\n    (0x1D490, 'M', 'o'),\n    (0x1D491, 'M', 'p'),\n    (0x1D492, 'M', 'q'),\n    (0x1D493, 'M', 'r'),\n    (0x1D494, 'M', 's'),\n    (0x1D495, 'M', 't'),\n    (0x1D496, 'M', 'u'),\n    (0x1D497, 'M', 'v'),\n    (0x1D498, 'M', 'w'),\n    (0x1D499, 'M', 'x'),\n    (0x1D49A, 'M', 'y'),\n    (0x1D49B, 'M', 'z'),\n    (0x1D49C, 'M', 'a'),\n    (0x1D49D, 'X'),\n    (0x1D49E, 'M', 'c'),\n    (0x1D49F, 'M', 'd'),\n    (0x1D4A0, 'X'),\n    (0x1D4A2, 'M', 'g'),\n    (0x1D4A3, 'X'),\n    (0x1D4A5, 'M', 'j'),\n    (0x1D4A6, 'M', 'k'),\n    (0x1D4A7, 'X'),\n    (0x1D4A9, 'M', 'n'),\n    (0x1D4AA, 'M', 'o'),\n    (0x1D4AB, 'M', 'p'),\n    (0x1D4AC, 'M', 'q'),\n    (0x1D4AD, 'X'),\n    (0x1D4AE, 'M', 's'),\n    (0x1D4AF, 'M', 't'),\n    (0x1D4B0, 'M', 'u'),\n    (0x1D4B1, 'M', 'v'),\n    (0x1D4B2, 'M', 'w'),\n    (0x1D4B3, 'M', 'x'),\n    (0x1D4B4, 'M', 'y'),\n    (0x1D4B5, 'M', 'z'),\n    (0x1D4B6, 'M', 'a'),\n    (0x1D4B7, 'M', 'b'),\n    (0x1D4B8, 'M', 'c'),\n    (0x1D4B9, 'M', 'd'),\n    (0x1D4BA, 'X'),\n    (0x1D4BB, 'M', 'f'),\n    (0x1D4BC, 'X'),\n    (0x1D4BD, 'M', 'h'),\n    (0x1D4BE, 'M', 'i'),\n    (0x1D4BF, 'M', 'j'),\n    (0x1D4C0, 'M', 'k'),\n    (0x1D4C1, 'M', 'l'),\n    (0x1D4C2, 'M', 'm'),\n    (0x1D4C3, 'M', 'n'),\n    (0x1D4C4, 'X'),\n    (0x1D4C5, 'M', 'p'),\n    (0x1D4C6, 'M', 'q'),\n    (0x1D4C7, 'M', 'r'),\n    (0x1D4C8, 'M', 's'),\n    (0x1D4C9, 'M', 't'),\n    (0x1D4CA, 'M', 'u'),\n    (0x1D4CB, 'M', 'v'),\n    (0x1D4CC, 'M', 'w'),\n    (0x1D4CD, 'M', 'x'),\n    (0x1D4CE, 'M', 'y'),\n    (0x1D4CF, 'M', 'z'),\n    (0x1D4D0, 'M', 'a'),\n    (0x1D4D1, 'M', 'b'),\n    (0x1D4D2, 'M', 'c'),\n    (0x1D4D3, 'M', 'd'),\n    (0x1D4D4, 'M', 'e'),\n    (0x1D4D5, 'M', 'f'),\n    (0x1D4D6, 'M', 'g'),\n    (0x1D4D7, 'M', 'h'),\n    (0x1D4D8, 'M', 'i'),\n    (0x1D4D9, 'M', 'j'),\n    (0x1D4DA, 'M', 'k'),\n    (0x1D4DB, 'M', 'l'),\n    (0x1D4DC, 'M', 'm'),\n    (0x1D4DD, 'M', 'n'),\n    (0x1D4DE, 'M', 'o'),\n    (0x1D4DF, 'M', 'p'),\n    (0x1D4E0, 'M', 'q'),\n    (0x1D4E1, 'M', 'r'),\n    (0x1D4E2, 'M', 's'),\n    (0x1D4E3, 'M', 't'),\n    (0x1D4E4, 'M', 'u'),\n    (0x1D4E5, 'M', 'v'),\n    (0x1D4E6, 'M', 'w'),\n    (0x1D4E7, 'M', 'x'),\n    (0x1D4E8, 'M', 'y'),\n    (0x1D4E9, 'M', 'z'),\n    (0x1D4EA, 'M', 'a'),\n    (0x1D4EB, 'M', 'b'),\n    ]\n\ndef _seg_63() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1D4EC, 'M', 'c'),\n    (0x1D4ED, 'M', 'd'),\n    (0x1D4EE, 'M', 'e'),\n    (0x1D4EF, 'M', 'f'),\n    (0x1D4F0, 'M', 'g'),\n    (0x1D4F1, 'M', 'h'),\n    (0x1D4F2, 'M', 'i'),\n    (0x1D4F3, 'M', 'j'),\n    (0x1D4F4, 'M', 'k'),\n    (0x1D4F5, 'M', 'l'),\n    (0x1D4F6, 'M', 'm'),\n    (0x1D4F7, 'M', 'n'),\n    (0x1D4F8, 'M', 'o'),\n    (0x1D4F9, 'M', 'p'),\n    (0x1D4FA, 'M', 'q'),\n    (0x1D4FB, 'M', 'r'),\n    (0x1D4FC, 'M', 's'),\n    (0x1D4FD, 'M', 't'),\n    (0x1D4FE, 'M', 'u'),\n    (0x1D4FF, 'M', 'v'),\n    (0x1D500, 'M', 'w'),\n    (0x1D501, 'M', 'x'),\n    (0x1D502, 'M', 'y'),\n    (0x1D503, 'M', 'z'),\n    (0x1D504, 'M', 'a'),\n    (0x1D505, 'M', 'b'),\n    (0x1D506, 'X'),\n    (0x1D507, 'M', 'd'),\n    (0x1D508, 'M', 'e'),\n    (0x1D509, 'M', 'f'),\n    (0x1D50A, 'M', 'g'),\n    (0x1D50B, 'X'),\n    (0x1D50D, 'M', 'j'),\n    (0x1D50E, 'M', 'k'),\n    (0x1D50F, 'M', 'l'),\n    (0x1D510, 'M', 'm'),\n    (0x1D511, 'M', 'n'),\n    (0x1D512, 'M', 'o'),\n    (0x1D513, 'M', 'p'),\n    (0x1D514, 'M', 'q'),\n    (0x1D515, 'X'),\n    (0x1D516, 'M', 's'),\n    (0x1D517, 'M', 't'),\n    (0x1D518, 'M', 'u'),\n    (0x1D519, 'M', 'v'),\n    (0x1D51A, 'M', 'w'),\n    (0x1D51B, 'M', 'x'),\n    (0x1D51C, 'M', 'y'),\n    (0x1D51D, 'X'),\n    (0x1D51E, 'M', 'a'),\n    (0x1D51F, 'M', 'b'),\n    (0x1D520, 'M', 'c'),\n    (0x1D521, 'M', 'd'),\n    (0x1D522, 'M', 'e'),\n    (0x1D523, 'M', 'f'),\n    (0x1D524, 'M', 'g'),\n    (0x1D525, 'M', 'h'),\n    (0x1D526, 'M', 'i'),\n    (0x1D527, 'M', 'j'),\n    (0x1D528, 'M', 'k'),\n    (0x1D529, 'M', 'l'),\n    (0x1D52A, 'M', 'm'),\n    (0x1D52B, 'M', 'n'),\n    (0x1D52C, 'M', 'o'),\n    (0x1D52D, 'M', 'p'),\n    (0x1D52E, 'M', 'q'),\n    (0x1D52F, 'M', 'r'),\n    (0x1D530, 'M', 's'),\n    (0x1D531, 'M', 't'),\n    (0x1D532, 'M', 'u'),\n    (0x1D533, 'M', 'v'),\n    (0x1D534, 'M', 'w'),\n    (0x1D535, 'M', 'x'),\n    (0x1D536, 'M', 'y'),\n    (0x1D537, 'M', 'z'),\n    (0x1D538, 'M', 'a'),\n    (0x1D539, 'M', 'b'),\n    (0x1D53A, 'X'),\n    (0x1D53B, 'M', 'd'),\n    (0x1D53C, 'M', 'e'),\n    (0x1D53D, 'M', 'f'),\n    (0x1D53E, 'M', 'g'),\n    (0x1D53F, 'X'),\n    (0x1D540, 'M', 'i'),\n    (0x1D541, 'M', 'j'),\n    (0x1D542, 'M', 'k'),\n    (0x1D543, 'M', 'l'),\n    (0x1D544, 'M', 'm'),\n    (0x1D545, 'X'),\n    (0x1D546, 'M', 'o'),\n    (0x1D547, 'X'),\n    (0x1D54A, 'M', 's'),\n    (0x1D54B, 'M', 't'),\n    (0x1D54C, 'M', 'u'),\n    (0x1D54D, 'M', 'v'),\n    (0x1D54E, 'M', 'w'),\n    (0x1D54F, 'M', 'x'),\n    (0x1D550, 'M', 'y'),\n    (0x1D551, 'X'),\n    (0x1D552, 'M', 'a'),\n    ]\n\ndef _seg_64() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1D553, 'M', 'b'),\n    (0x1D554, 'M', 'c'),\n    (0x1D555, 'M', 'd'),\n    (0x1D556, 'M', 'e'),\n    (0x1D557, 'M', 'f'),\n    (0x1D558, 'M', 'g'),\n    (0x1D559, 'M', 'h'),\n    (0x1D55A, 'M', 'i'),\n    (0x1D55B, 'M', 'j'),\n    (0x1D55C, 'M', 'k'),\n    (0x1D55D, 'M', 'l'),\n    (0x1D55E, 'M', 'm'),\n    (0x1D55F, 'M', 'n'),\n    (0x1D560, 'M', 'o'),\n    (0x1D561, 'M', 'p'),\n    (0x1D562, 'M', 'q'),\n    (0x1D563, 'M', 'r'),\n    (0x1D564, 'M', 's'),\n    (0x1D565, 'M', 't'),\n    (0x1D566, 'M', 'u'),\n    (0x1D567, 'M', 'v'),\n    (0x1D568, 'M', 'w'),\n    (0x1D569, 'M', 'x'),\n    (0x1D56A, 'M', 'y'),\n    (0x1D56B, 'M', 'z'),\n    (0x1D56C, 'M', 'a'),\n    (0x1D56D, 'M', 'b'),\n    (0x1D56E, 'M', 'c'),\n    (0x1D56F, 'M', 'd'),\n    (0x1D570, 'M', 'e'),\n    (0x1D571, 'M', 'f'),\n    (0x1D572, 'M', 'g'),\n    (0x1D573, 'M', 'h'),\n    (0x1D574, 'M', 'i'),\n    (0x1D575, 'M', 'j'),\n    (0x1D576, 'M', 'k'),\n    (0x1D577, 'M', 'l'),\n    (0x1D578, 'M', 'm'),\n    (0x1D579, 'M', 'n'),\n    (0x1D57A, 'M', 'o'),\n    (0x1D57B, 'M', 'p'),\n    (0x1D57C, 'M', 'q'),\n    (0x1D57D, 'M', 'r'),\n    (0x1D57E, 'M', 's'),\n    (0x1D57F, 'M', 't'),\n    (0x1D580, 'M', 'u'),\n    (0x1D581, 'M', 'v'),\n    (0x1D582, 'M', 'w'),\n    (0x1D583, 'M', 'x'),\n    (0x1D584, 'M', 'y'),\n    (0x1D585, 'M', 'z'),\n    (0x1D586, 'M', 'a'),\n    (0x1D587, 'M', 'b'),\n    (0x1D588, 'M', 'c'),\n    (0x1D589, 'M', 'd'),\n    (0x1D58A, 'M', 'e'),\n    (0x1D58B, 'M', 'f'),\n    (0x1D58C, 'M', 'g'),\n    (0x1D58D, 'M', 'h'),\n    (0x1D58E, 'M', 'i'),\n    (0x1D58F, 'M', 'j'),\n    (0x1D590, 'M', 'k'),\n    (0x1D591, 'M', 'l'),\n    (0x1D592, 'M', 'm'),\n    (0x1D593, 'M', 'n'),\n    (0x1D594, 'M', 'o'),\n    (0x1D595, 'M', 'p'),\n    (0x1D596, 'M', 'q'),\n    (0x1D597, 'M', 'r'),\n    (0x1D598, 'M', 's'),\n    (0x1D599, 'M', 't'),\n    (0x1D59A, 'M', 'u'),\n    (0x1D59B, 'M', 'v'),\n    (0x1D59C, 'M', 'w'),\n    (0x1D59D, 'M', 'x'),\n    (0x1D59E, 'M', 'y'),\n    (0x1D59F, 'M', 'z'),\n    (0x1D5A0, 'M', 'a'),\n    (0x1D5A1, 'M', 'b'),\n    (0x1D5A2, 'M', 'c'),\n    (0x1D5A3, 'M', 'd'),\n    (0x1D5A4, 'M', 'e'),\n    (0x1D5A5, 'M', 'f'),\n    (0x1D5A6, 'M', 'g'),\n    (0x1D5A7, 'M', 'h'),\n    (0x1D5A8, 'M', 'i'),\n    (0x1D5A9, 'M', 'j'),\n    (0x1D5AA, 'M', 'k'),\n    (0x1D5AB, 'M', 'l'),\n    (0x1D5AC, 'M', 'm'),\n    (0x1D5AD, 'M', 'n'),\n    (0x1D5AE, 'M', 'o'),\n    (0x1D5AF, 'M', 'p'),\n    (0x1D5B0, 'M', 'q'),\n    (0x1D5B1, 'M', 'r'),\n    (0x1D5B2, 'M', 's'),\n    (0x1D5B3, 'M', 't'),\n    (0x1D5B4, 'M', 'u'),\n    (0x1D5B5, 'M', 'v'),\n    (0x1D5B6, 'M', 'w'),\n    ]\n\ndef _seg_65() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1D5B7, 'M', 'x'),\n    (0x1D5B8, 'M', 'y'),\n    (0x1D5B9, 'M', 'z'),\n    (0x1D5BA, 'M', 'a'),\n    (0x1D5BB, 'M', 'b'),\n    (0x1D5BC, 'M', 'c'),\n    (0x1D5BD, 'M', 'd'),\n    (0x1D5BE, 'M', 'e'),\n    (0x1D5BF, 'M', 'f'),\n    (0x1D5C0, 'M', 'g'),\n    (0x1D5C1, 'M', 'h'),\n    (0x1D5C2, 'M', 'i'),\n    (0x1D5C3, 'M', 'j'),\n    (0x1D5C4, 'M', 'k'),\n    (0x1D5C5, 'M', 'l'),\n    (0x1D5C6, 'M', 'm'),\n    (0x1D5C7, 'M', 'n'),\n    (0x1D5C8, 'M', 'o'),\n    (0x1D5C9, 'M', 'p'),\n    (0x1D5CA, 'M', 'q'),\n    (0x1D5CB, 'M', 'r'),\n    (0x1D5CC, 'M', 's'),\n    (0x1D5CD, 'M', 't'),\n    (0x1D5CE, 'M', 'u'),\n    (0x1D5CF, 'M', 'v'),\n    (0x1D5D0, 'M', 'w'),\n    (0x1D5D1, 'M', 'x'),\n    (0x1D5D2, 'M', 'y'),\n    (0x1D5D3, 'M', 'z'),\n    (0x1D5D4, 'M', 'a'),\n    (0x1D5D5, 'M', 'b'),\n    (0x1D5D6, 'M', 'c'),\n    (0x1D5D7, 'M', 'd'),\n    (0x1D5D8, 'M', 'e'),\n    (0x1D5D9, 'M', 'f'),\n    (0x1D5DA, 'M', 'g'),\n    (0x1D5DB, 'M', 'h'),\n    (0x1D5DC, 'M', 'i'),\n    (0x1D5DD, 'M', 'j'),\n    (0x1D5DE, 'M', 'k'),\n    (0x1D5DF, 'M', 'l'),\n    (0x1D5E0, 'M', 'm'),\n    (0x1D5E1, 'M', 'n'),\n    (0x1D5E2, 'M', 'o'),\n    (0x1D5E3, 'M', 'p'),\n    (0x1D5E4, 'M', 'q'),\n    (0x1D5E5, 'M', 'r'),\n    (0x1D5E6, 'M', 's'),\n    (0x1D5E7, 'M', 't'),\n    (0x1D5E8, 'M', 'u'),\n    (0x1D5E9, 'M', 'v'),\n    (0x1D5EA, 'M', 'w'),\n    (0x1D5EB, 'M', 'x'),\n    (0x1D5EC, 'M', 'y'),\n    (0x1D5ED, 'M', 'z'),\n    (0x1D5EE, 'M', 'a'),\n    (0x1D5EF, 'M', 'b'),\n    (0x1D5F0, 'M', 'c'),\n    (0x1D5F1, 'M', 'd'),\n    (0x1D5F2, 'M', 'e'),\n    (0x1D5F3, 'M', 'f'),\n    (0x1D5F4, 'M', 'g'),\n    (0x1D5F5, 'M', 'h'),\n    (0x1D5F6, 'M', 'i'),\n    (0x1D5F7, 'M', 'j'),\n    (0x1D5F8, 'M', 'k'),\n    (0x1D5F9, 'M', 'l'),\n    (0x1D5FA, 'M', 'm'),\n    (0x1D5FB, 'M', 'n'),\n    (0x1D5FC, 'M', 'o'),\n    (0x1D5FD, 'M', 'p'),\n    (0x1D5FE, 'M', 'q'),\n    (0x1D5FF, 'M', 'r'),\n    (0x1D600, 'M', 's'),\n    (0x1D601, 'M', 't'),\n    (0x1D602, 'M', 'u'),\n    (0x1D603, 'M', 'v'),\n    (0x1D604, 'M', 'w'),\n    (0x1D605, 'M', 'x'),\n    (0x1D606, 'M', 'y'),\n    (0x1D607, 'M', 'z'),\n    (0x1D608, 'M', 'a'),\n    (0x1D609, 'M', 'b'),\n    (0x1D60A, 'M', 'c'),\n    (0x1D60B, 'M', 'd'),\n    (0x1D60C, 'M', 'e'),\n    (0x1D60D, 'M', 'f'),\n    (0x1D60E, 'M', 'g'),\n    (0x1D60F, 'M', 'h'),\n    (0x1D610, 'M', 'i'),\n    (0x1D611, 'M', 'j'),\n    (0x1D612, 'M', 'k'),\n    (0x1D613, 'M', 'l'),\n    (0x1D614, 'M', 'm'),\n    (0x1D615, 'M', 'n'),\n    (0x1D616, 'M', 'o'),\n    (0x1D617, 'M', 'p'),\n    (0x1D618, 'M', 'q'),\n    (0x1D619, 'M', 'r'),\n    (0x1D61A, 'M', 's'),\n    ]\n\ndef _seg_66() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1D61B, 'M', 't'),\n    (0x1D61C, 'M', 'u'),\n    (0x1D61D, 'M', 'v'),\n    (0x1D61E, 'M', 'w'),\n    (0x1D61F, 'M', 'x'),\n    (0x1D620, 'M', 'y'),\n    (0x1D621, 'M', 'z'),\n    (0x1D622, 'M', 'a'),\n    (0x1D623, 'M', 'b'),\n    (0x1D624, 'M', 'c'),\n    (0x1D625, 'M', 'd'),\n    (0x1D626, 'M', 'e'),\n    (0x1D627, 'M', 'f'),\n    (0x1D628, 'M', 'g'),\n    (0x1D629, 'M', 'h'),\n    (0x1D62A, 'M', 'i'),\n    (0x1D62B, 'M', 'j'),\n    (0x1D62C, 'M', 'k'),\n    (0x1D62D, 'M', 'l'),\n    (0x1D62E, 'M', 'm'),\n    (0x1D62F, 'M', 'n'),\n    (0x1D630, 'M', 'o'),\n    (0x1D631, 'M', 'p'),\n    (0x1D632, 'M', 'q'),\n    (0x1D633, 'M', 'r'),\n    (0x1D634, 'M', 's'),\n    (0x1D635, 'M', 't'),\n    (0x1D636, 'M', 'u'),\n    (0x1D637, 'M', 'v'),\n    (0x1D638, 'M', 'w'),\n    (0x1D639, 'M', 'x'),\n    (0x1D63A, 'M', 'y'),\n    (0x1D63B, 'M', 'z'),\n    (0x1D63C, 'M', 'a'),\n    (0x1D63D, 'M', 'b'),\n    (0x1D63E, 'M', 'c'),\n    (0x1D63F, 'M', 'd'),\n    (0x1D640, 'M', 'e'),\n    (0x1D641, 'M', 'f'),\n    (0x1D642, 'M', 'g'),\n    (0x1D643, 'M', 'h'),\n    (0x1D644, 'M', 'i'),\n    (0x1D645, 'M', 'j'),\n    (0x1D646, 'M', 'k'),\n    (0x1D647, 'M', 'l'),\n    (0x1D648, 'M', 'm'),\n    (0x1D649, 'M', 'n'),\n    (0x1D64A, 'M', 'o'),\n    (0x1D64B, 'M', 'p'),\n    (0x1D64C, 'M', 'q'),\n    (0x1D64D, 'M', 'r'),\n    (0x1D64E, 'M', 's'),\n    (0x1D64F, 'M', 't'),\n    (0x1D650, 'M', 'u'),\n    (0x1D651, 'M', 'v'),\n    (0x1D652, 'M', 'w'),\n    (0x1D653, 'M', 'x'),\n    (0x1D654, 'M', 'y'),\n    (0x1D655, 'M', 'z'),\n    (0x1D656, 'M', 'a'),\n    (0x1D657, 'M', 'b'),\n    (0x1D658, 'M', 'c'),\n    (0x1D659, 'M', 'd'),\n    (0x1D65A, 'M', 'e'),\n    (0x1D65B, 'M', 'f'),\n    (0x1D65C, 'M', 'g'),\n    (0x1D65D, 'M', 'h'),\n    (0x1D65E, 'M', 'i'),\n    (0x1D65F, 'M', 'j'),\n    (0x1D660, 'M', 'k'),\n    (0x1D661, 'M', 'l'),\n    (0x1D662, 'M', 'm'),\n    (0x1D663, 'M', 'n'),\n    (0x1D664, 'M', 'o'),\n    (0x1D665, 'M', 'p'),\n    (0x1D666, 'M', 'q'),\n    (0x1D667, 'M', 'r'),\n    (0x1D668, 'M', 's'),\n    (0x1D669, 'M', 't'),\n    (0x1D66A, 'M', 'u'),\n    (0x1D66B, 'M', 'v'),\n    (0x1D66C, 'M', 'w'),\n    (0x1D66D, 'M', 'x'),\n    (0x1D66E, 'M', 'y'),\n    (0x1D66F, 'M', 'z'),\n    (0x1D670, 'M', 'a'),\n    (0x1D671, 'M', 'b'),\n    (0x1D672, 'M', 'c'),\n    (0x1D673, 'M', 'd'),\n    (0x1D674, 'M', 'e'),\n    (0x1D675, 'M', 'f'),\n    (0x1D676, 'M', 'g'),\n    (0x1D677, 'M', 'h'),\n    (0x1D678, 'M', 'i'),\n    (0x1D679, 'M', 'j'),\n    (0x1D67A, 'M', 'k'),\n    (0x1D67B, 'M', 'l'),\n    (0x1D67C, 'M', 'm'),\n    (0x1D67D, 'M', 'n'),\n    (0x1D67E, 'M', 'o'),\n    ]\n\ndef _seg_67() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1D67F, 'M', 'p'),\n    (0x1D680, 'M', 'q'),\n    (0x1D681, 'M', 'r'),\n    (0x1D682, 'M', 's'),\n    (0x1D683, 'M', 't'),\n    (0x1D684, 'M', 'u'),\n    (0x1D685, 'M', 'v'),\n    (0x1D686, 'M', 'w'),\n    (0x1D687, 'M', 'x'),\n    (0x1D688, 'M', 'y'),\n    (0x1D689, 'M', 'z'),\n    (0x1D68A, 'M', 'a'),\n    (0x1D68B, 'M', 'b'),\n    (0x1D68C, 'M', 'c'),\n    (0x1D68D, 'M', 'd'),\n    (0x1D68E, 'M', 'e'),\n    (0x1D68F, 'M', 'f'),\n    (0x1D690, 'M', 'g'),\n    (0x1D691, 'M', 'h'),\n    (0x1D692, 'M', 'i'),\n    (0x1D693, 'M', 'j'),\n    (0x1D694, 'M', 'k'),\n    (0x1D695, 'M', 'l'),\n    (0x1D696, 'M', 'm'),\n    (0x1D697, 'M', 'n'),\n    (0x1D698, 'M', 'o'),\n    (0x1D699, 'M', 'p'),\n    (0x1D69A, 'M', 'q'),\n    (0x1D69B, 'M', 'r'),\n    (0x1D69C, 'M', 's'),\n    (0x1D69D, 'M', 't'),\n    (0x1D69E, 'M', 'u'),\n    (0x1D69F, 'M', 'v'),\n    (0x1D6A0, 'M', 'w'),\n    (0x1D6A1, 'M', 'x'),\n    (0x1D6A2, 'M', 'y'),\n    (0x1D6A3, 'M', 'z'),\n    (0x1D6A4, 'M', 'ı'),\n    (0x1D6A5, 'M', 'ȷ'),\n    (0x1D6A6, 'X'),\n    (0x1D6A8, 'M', 'α'),\n    (0x1D6A9, 'M', 'β'),\n    (0x1D6AA, 'M', 'γ'),\n    (0x1D6AB, 'M', 'δ'),\n    (0x1D6AC, 'M', 'ε'),\n    (0x1D6AD, 'M', 'ζ'),\n    (0x1D6AE, 'M', 'η'),\n    (0x1D6AF, 'M', 'θ'),\n    (0x1D6B0, 'M', 'ι'),\n    (0x1D6B1, 'M', 'κ'),\n    (0x1D6B2, 'M', 'λ'),\n    (0x1D6B3, 'M', 'μ'),\n    (0x1D6B4, 'M', 'ν'),\n    (0x1D6B5, 'M', 'ξ'),\n    (0x1D6B6, 'M', 'ο'),\n    (0x1D6B7, 'M', 'π'),\n    (0x1D6B8, 'M', 'ρ'),\n    (0x1D6B9, 'M', 'θ'),\n    (0x1D6BA, 'M', 'σ'),\n    (0x1D6BB, 'M', 'τ'),\n    (0x1D6BC, 'M', 'υ'),\n    (0x1D6BD, 'M', 'φ'),\n    (0x1D6BE, 'M', 'χ'),\n    (0x1D6BF, 'M', 'ψ'),\n    (0x1D6C0, 'M', 'ω'),\n    (0x1D6C1, 'M', '∇'),\n    (0x1D6C2, 'M', 'α'),\n    (0x1D6C3, 'M', 'β'),\n    (0x1D6C4, 'M', 'γ'),\n    (0x1D6C5, 'M', 'δ'),\n    (0x1D6C6, 'M', 'ε'),\n    (0x1D6C7, 'M', 'ζ'),\n    (0x1D6C8, 'M', 'η'),\n    (0x1D6C9, 'M', 'θ'),\n    (0x1D6CA, 'M', 'ι'),\n    (0x1D6CB, 'M', 'κ'),\n    (0x1D6CC, 'M', 'λ'),\n    (0x1D6CD, 'M', 'μ'),\n    (0x1D6CE, 'M', 'ν'),\n    (0x1D6CF, 'M', 'ξ'),\n    (0x1D6D0, 'M', 'ο'),\n    (0x1D6D1, 'M', 'π'),\n    (0x1D6D2, 'M', 'ρ'),\n    (0x1D6D3, 'M', 'σ'),\n    (0x1D6D5, 'M', 'τ'),\n    (0x1D6D6, 'M', 'υ'),\n    (0x1D6D7, 'M', 'φ'),\n    (0x1D6D8, 'M', 'χ'),\n    (0x1D6D9, 'M', 'ψ'),\n    (0x1D6DA, 'M', 'ω'),\n    (0x1D6DB, 'M', '∂'),\n    (0x1D6DC, 'M', 'ε'),\n    (0x1D6DD, 'M', 'θ'),\n    (0x1D6DE, 'M', 'κ'),\n    (0x1D6DF, 'M', 'φ'),\n    (0x1D6E0, 'M', 'ρ'),\n    (0x1D6E1, 'M', 'π'),\n    (0x1D6E2, 'M', 'α'),\n    (0x1D6E3, 'M', 'β'),\n    (0x1D6E4, 'M', 'γ'),\n    ]\n\ndef _seg_68() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1D6E5, 'M', 'δ'),\n    (0x1D6E6, 'M', 'ε'),\n    (0x1D6E7, 'M', 'ζ'),\n    (0x1D6E8, 'M', 'η'),\n    (0x1D6E9, 'M', 'θ'),\n    (0x1D6EA, 'M', 'ι'),\n    (0x1D6EB, 'M', 'κ'),\n    (0x1D6EC, 'M', 'λ'),\n    (0x1D6ED, 'M', 'μ'),\n    (0x1D6EE, 'M', 'ν'),\n    (0x1D6EF, 'M', 'ξ'),\n    (0x1D6F0, 'M', 'ο'),\n    (0x1D6F1, 'M', 'π'),\n    (0x1D6F2, 'M', 'ρ'),\n    (0x1D6F3, 'M', 'θ'),\n    (0x1D6F4, 'M', 'σ'),\n    (0x1D6F5, 'M', 'τ'),\n    (0x1D6F6, 'M', 'υ'),\n    (0x1D6F7, 'M', 'φ'),\n    (0x1D6F8, 'M', 'χ'),\n    (0x1D6F9, 'M', 'ψ'),\n    (0x1D6FA, 'M', 'ω'),\n    (0x1D6FB, 'M', '∇'),\n    (0x1D6FC, 'M', 'α'),\n    (0x1D6FD, 'M', 'β'),\n    (0x1D6FE, 'M', 'γ'),\n    (0x1D6FF, 'M', 'δ'),\n    (0x1D700, 'M', 'ε'),\n    (0x1D701, 'M', 'ζ'),\n    (0x1D702, 'M', 'η'),\n    (0x1D703, 'M', 'θ'),\n    (0x1D704, 'M', 'ι'),\n    (0x1D705, 'M', 'κ'),\n    (0x1D706, 'M', 'λ'),\n    (0x1D707, 'M', 'μ'),\n    (0x1D708, 'M', 'ν'),\n    (0x1D709, 'M', 'ξ'),\n    (0x1D70A, 'M', 'ο'),\n    (0x1D70B, 'M', 'π'),\n    (0x1D70C, 'M', 'ρ'),\n    (0x1D70D, 'M', 'σ'),\n    (0x1D70F, 'M', 'τ'),\n    (0x1D710, 'M', 'υ'),\n    (0x1D711, 'M', 'φ'),\n    (0x1D712, 'M', 'χ'),\n    (0x1D713, 'M', 'ψ'),\n    (0x1D714, 'M', 'ω'),\n    (0x1D715, 'M', '∂'),\n    (0x1D716, 'M', 'ε'),\n    (0x1D717, 'M', 'θ'),\n    (0x1D718, 'M', 'κ'),\n    (0x1D719, 'M', 'φ'),\n    (0x1D71A, 'M', 'ρ'),\n    (0x1D71B, 'M', 'π'),\n    (0x1D71C, 'M', 'α'),\n    (0x1D71D, 'M', 'β'),\n    (0x1D71E, 'M', 'γ'),\n    (0x1D71F, 'M', 'δ'),\n    (0x1D720, 'M', 'ε'),\n    (0x1D721, 'M', 'ζ'),\n    (0x1D722, 'M', 'η'),\n    (0x1D723, 'M', 'θ'),\n    (0x1D724, 'M', 'ι'),\n    (0x1D725, 'M', 'κ'),\n    (0x1D726, 'M', 'λ'),\n    (0x1D727, 'M', 'μ'),\n    (0x1D728, 'M', 'ν'),\n    (0x1D729, 'M', 'ξ'),\n    (0x1D72A, 'M', 'ο'),\n    (0x1D72B, 'M', 'π'),\n    (0x1D72C, 'M', 'ρ'),\n    (0x1D72D, 'M', 'θ'),\n    (0x1D72E, 'M', 'σ'),\n    (0x1D72F, 'M', 'τ'),\n    (0x1D730, 'M', 'υ'),\n    (0x1D731, 'M', 'φ'),\n    (0x1D732, 'M', 'χ'),\n    (0x1D733, 'M', 'ψ'),\n    (0x1D734, 'M', 'ω'),\n    (0x1D735, 'M', '∇'),\n    (0x1D736, 'M', 'α'),\n    (0x1D737, 'M', 'β'),\n    (0x1D738, 'M', 'γ'),\n    (0x1D739, 'M', 'δ'),\n    (0x1D73A, 'M', 'ε'),\n    (0x1D73B, 'M', 'ζ'),\n    (0x1D73C, 'M', 'η'),\n    (0x1D73D, 'M', 'θ'),\n    (0x1D73E, 'M', 'ι'),\n    (0x1D73F, 'M', 'κ'),\n    (0x1D740, 'M', 'λ'),\n    (0x1D741, 'M', 'μ'),\n    (0x1D742, 'M', 'ν'),\n    (0x1D743, 'M', 'ξ'),\n    (0x1D744, 'M', 'ο'),\n    (0x1D745, 'M', 'π'),\n    (0x1D746, 'M', 'ρ'),\n    (0x1D747, 'M', 'σ'),\n    (0x1D749, 'M', 'τ'),\n    (0x1D74A, 'M', 'υ'),\n    ]\n\ndef _seg_69() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1D74B, 'M', 'φ'),\n    (0x1D74C, 'M', 'χ'),\n    (0x1D74D, 'M', 'ψ'),\n    (0x1D74E, 'M', 'ω'),\n    (0x1D74F, 'M', '∂'),\n    (0x1D750, 'M', 'ε'),\n    (0x1D751, 'M', 'θ'),\n    (0x1D752, 'M', 'κ'),\n    (0x1D753, 'M', 'φ'),\n    (0x1D754, 'M', 'ρ'),\n    (0x1D755, 'M', 'π'),\n    (0x1D756, 'M', 'α'),\n    (0x1D757, 'M', 'β'),\n    (0x1D758, 'M', 'γ'),\n    (0x1D759, 'M', 'δ'),\n    (0x1D75A, 'M', 'ε'),\n    (0x1D75B, 'M', 'ζ'),\n    (0x1D75C, 'M', 'η'),\n    (0x1D75D, 'M', 'θ'),\n    (0x1D75E, 'M', 'ι'),\n    (0x1D75F, 'M', 'κ'),\n    (0x1D760, 'M', 'λ'),\n    (0x1D761, 'M', 'μ'),\n    (0x1D762, 'M', 'ν'),\n    (0x1D763, 'M', 'ξ'),\n    (0x1D764, 'M', 'ο'),\n    (0x1D765, 'M', 'π'),\n    (0x1D766, 'M', 'ρ'),\n    (0x1D767, 'M', 'θ'),\n    (0x1D768, 'M', 'σ'),\n    (0x1D769, 'M', 'τ'),\n    (0x1D76A, 'M', 'υ'),\n    (0x1D76B, 'M', 'φ'),\n    (0x1D76C, 'M', 'χ'),\n    (0x1D76D, 'M', 'ψ'),\n    (0x1D76E, 'M', 'ω'),\n    (0x1D76F, 'M', '∇'),\n    (0x1D770, 'M', 'α'),\n    (0x1D771, 'M', 'β'),\n    (0x1D772, 'M', 'γ'),\n    (0x1D773, 'M', 'δ'),\n    (0x1D774, 'M', 'ε'),\n    (0x1D775, 'M', 'ζ'),\n    (0x1D776, 'M', 'η'),\n    (0x1D777, 'M', 'θ'),\n    (0x1D778, 'M', 'ι'),\n    (0x1D779, 'M', 'κ'),\n    (0x1D77A, 'M', 'λ'),\n    (0x1D77B, 'M', 'μ'),\n    (0x1D77C, 'M', 'ν'),\n    (0x1D77D, 'M', 'ξ'),\n    (0x1D77E, 'M', 'ο'),\n    (0x1D77F, 'M', 'π'),\n    (0x1D780, 'M', 'ρ'),\n    (0x1D781, 'M', 'σ'),\n    (0x1D783, 'M', 'τ'),\n    (0x1D784, 'M', 'υ'),\n    (0x1D785, 'M', 'φ'),\n    (0x1D786, 'M', 'χ'),\n    (0x1D787, 'M', 'ψ'),\n    (0x1D788, 'M', 'ω'),\n    (0x1D789, 'M', '∂'),\n    (0x1D78A, 'M', 'ε'),\n    (0x1D78B, 'M', 'θ'),\n    (0x1D78C, 'M', 'κ'),\n    (0x1D78D, 'M', 'φ'),\n    (0x1D78E, 'M', 'ρ'),\n    (0x1D78F, 'M', 'π'),\n    (0x1D790, 'M', 'α'),\n    (0x1D791, 'M', 'β'),\n    (0x1D792, 'M', 'γ'),\n    (0x1D793, 'M', 'δ'),\n    (0x1D794, 'M', 'ε'),\n    (0x1D795, 'M', 'ζ'),\n    (0x1D796, 'M', 'η'),\n    (0x1D797, 'M', 'θ'),\n    (0x1D798, 'M', 'ι'),\n    (0x1D799, 'M', 'κ'),\n    (0x1D79A, 'M', 'λ'),\n    (0x1D79B, 'M', 'μ'),\n    (0x1D79C, 'M', 'ν'),\n    (0x1D79D, 'M', 'ξ'),\n    (0x1D79E, 'M', 'ο'),\n    (0x1D79F, 'M', 'π'),\n    (0x1D7A0, 'M', 'ρ'),\n    (0x1D7A1, 'M', 'θ'),\n    (0x1D7A2, 'M', 'σ'),\n    (0x1D7A3, 'M', 'τ'),\n    (0x1D7A4, 'M', 'υ'),\n    (0x1D7A5, 'M', 'φ'),\n    (0x1D7A6, 'M', 'χ'),\n    (0x1D7A7, 'M', 'ψ'),\n    (0x1D7A8, 'M', 'ω'),\n    (0x1D7A9, 'M', '∇'),\n    (0x1D7AA, 'M', 'α'),\n    (0x1D7AB, 'M', 'β'),\n    (0x1D7AC, 'M', 'γ'),\n    (0x1D7AD, 'M', 'δ'),\n    (0x1D7AE, 'M', 'ε'),\n    (0x1D7AF, 'M', 'ζ'),\n    ]\n\ndef _seg_70() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1D7B0, 'M', 'η'),\n    (0x1D7B1, 'M', 'θ'),\n    (0x1D7B2, 'M', 'ι'),\n    (0x1D7B3, 'M', 'κ'),\n    (0x1D7B4, 'M', 'λ'),\n    (0x1D7B5, 'M', 'μ'),\n    (0x1D7B6, 'M', 'ν'),\n    (0x1D7B7, 'M', 'ξ'),\n    (0x1D7B8, 'M', 'ο'),\n    (0x1D7B9, 'M', 'π'),\n    (0x1D7BA, 'M', 'ρ'),\n    (0x1D7BB, 'M', 'σ'),\n    (0x1D7BD, 'M', 'τ'),\n    (0x1D7BE, 'M', 'υ'),\n    (0x1D7BF, 'M', 'φ'),\n    (0x1D7C0, 'M', 'χ'),\n    (0x1D7C1, 'M', 'ψ'),\n    (0x1D7C2, 'M', 'ω'),\n    (0x1D7C3, 'M', '∂'),\n    (0x1D7C4, 'M', 'ε'),\n    (0x1D7C5, 'M', 'θ'),\n    (0x1D7C6, 'M', 'κ'),\n    (0x1D7C7, 'M', 'φ'),\n    (0x1D7C8, 'M', 'ρ'),\n    (0x1D7C9, 'M', 'π'),\n    (0x1D7CA, 'M', 'ϝ'),\n    (0x1D7CC, 'X'),\n    (0x1D7CE, 'M', '0'),\n    (0x1D7CF, 'M', '1'),\n    (0x1D7D0, 'M', '2'),\n    (0x1D7D1, 'M', '3'),\n    (0x1D7D2, 'M', '4'),\n    (0x1D7D3, 'M', '5'),\n    (0x1D7D4, 'M', '6'),\n    (0x1D7D5, 'M', '7'),\n    (0x1D7D6, 'M', '8'),\n    (0x1D7D7, 'M', '9'),\n    (0x1D7D8, 'M', '0'),\n    (0x1D7D9, 'M', '1'),\n    (0x1D7DA, 'M', '2'),\n    (0x1D7DB, 'M', '3'),\n    (0x1D7DC, 'M', '4'),\n    (0x1D7DD, 'M', '5'),\n    (0x1D7DE, 'M', '6'),\n    (0x1D7DF, 'M', '7'),\n    (0x1D7E0, 'M', '8'),\n    (0x1D7E1, 'M', '9'),\n    (0x1D7E2, 'M', '0'),\n    (0x1D7E3, 'M', '1'),\n    (0x1D7E4, 'M', '2'),\n    (0x1D7E5, 'M', '3'),\n    (0x1D7E6, 'M', '4'),\n    (0x1D7E7, 'M', '5'),\n    (0x1D7E8, 'M', '6'),\n    (0x1D7E9, 'M', '7'),\n    (0x1D7EA, 'M', '8'),\n    (0x1D7EB, 'M', '9'),\n    (0x1D7EC, 'M', '0'),\n    (0x1D7ED, 'M', '1'),\n    (0x1D7EE, 'M', '2'),\n    (0x1D7EF, 'M', '3'),\n    (0x1D7F0, 'M', '4'),\n    (0x1D7F1, 'M', '5'),\n    (0x1D7F2, 'M', '6'),\n    (0x1D7F3, 'M', '7'),\n    (0x1D7F4, 'M', '8'),\n    (0x1D7F5, 'M', '9'),\n    (0x1D7F6, 'M', '0'),\n    (0x1D7F7, 'M', '1'),\n    (0x1D7F8, 'M', '2'),\n    (0x1D7F9, 'M', '3'),\n    (0x1D7FA, 'M', '4'),\n    (0x1D7FB, 'M', '5'),\n    (0x1D7FC, 'M', '6'),\n    (0x1D7FD, 'M', '7'),\n    (0x1D7FE, 'M', '8'),\n    (0x1D7FF, 'M', '9'),\n    (0x1D800, 'V'),\n    (0x1DA8C, 'X'),\n    (0x1DA9B, 'V'),\n    (0x1DAA0, 'X'),\n    (0x1DAA1, 'V'),\n    (0x1DAB0, 'X'),\n    (0x1DF00, 'V'),\n    (0x1DF1F, 'X'),\n    (0x1DF25, 'V'),\n    (0x1DF2B, 'X'),\n    (0x1E000, 'V'),\n    (0x1E007, 'X'),\n    (0x1E008, 'V'),\n    (0x1E019, 'X'),\n    (0x1E01B, 'V'),\n    (0x1E022, 'X'),\n    (0x1E023, 'V'),\n    (0x1E025, 'X'),\n    (0x1E026, 'V'),\n    (0x1E02B, 'X'),\n    (0x1E030, 'M', 'а'),\n    (0x1E031, 'M', 'б'),\n    (0x1E032, 'M', 'в'),\n    ]\n\ndef _seg_71() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1E033, 'M', 'г'),\n    (0x1E034, 'M', 'д'),\n    (0x1E035, 'M', 'е'),\n    (0x1E036, 'M', 'ж'),\n    (0x1E037, 'M', 'з'),\n    (0x1E038, 'M', 'и'),\n    (0x1E039, 'M', 'к'),\n    (0x1E03A, 'M', 'л'),\n    (0x1E03B, 'M', 'м'),\n    (0x1E03C, 'M', 'о'),\n    (0x1E03D, 'M', 'п'),\n    (0x1E03E, 'M', 'р'),\n    (0x1E03F, 'M', 'с'),\n    (0x1E040, 'M', 'т'),\n    (0x1E041, 'M', 'у'),\n    (0x1E042, 'M', 'ф'),\n    (0x1E043, 'M', 'х'),\n    (0x1E044, 'M', 'ц'),\n    (0x1E045, 'M', 'ч'),\n    (0x1E046, 'M', 'ш'),\n    (0x1E047, 'M', 'ы'),\n    (0x1E048, 'M', 'э'),\n    (0x1E049, 'M', 'ю'),\n    (0x1E04A, 'M', 'ꚉ'),\n    (0x1E04B, 'M', 'ә'),\n    (0x1E04C, 'M', 'і'),\n    (0x1E04D, 'M', 'ј'),\n    (0x1E04E, 'M', 'ө'),\n    (0x1E04F, 'M', 'ү'),\n    (0x1E050, 'M', 'ӏ'),\n    (0x1E051, 'M', 'а'),\n    (0x1E052, 'M', 'б'),\n    (0x1E053, 'M', 'в'),\n    (0x1E054, 'M', 'г'),\n    (0x1E055, 'M', 'д'),\n    (0x1E056, 'M', 'е'),\n    (0x1E057, 'M', 'ж'),\n    (0x1E058, 'M', 'з'),\n    (0x1E059, 'M', 'и'),\n    (0x1E05A, 'M', 'к'),\n    (0x1E05B, 'M', 'л'),\n    (0x1E05C, 'M', 'о'),\n    (0x1E05D, 'M', 'п'),\n    (0x1E05E, 'M', 'с'),\n    (0x1E05F, 'M', 'у'),\n    (0x1E060, 'M', 'ф'),\n    (0x1E061, 'M', 'х'),\n    (0x1E062, 'M', 'ц'),\n    (0x1E063, 'M', 'ч'),\n    (0x1E064, 'M', 'ш'),\n    (0x1E065, 'M', 'ъ'),\n    (0x1E066, 'M', 'ы'),\n    (0x1E067, 'M', 'ґ'),\n    (0x1E068, 'M', 'і'),\n    (0x1E069, 'M', 'ѕ'),\n    (0x1E06A, 'M', 'џ'),\n    (0x1E06B, 'M', 'ҫ'),\n    (0x1E06C, 'M', 'ꙑ'),\n    (0x1E06D, 'M', 'ұ'),\n    (0x1E06E, 'X'),\n    (0x1E08F, 'V'),\n    (0x1E090, 'X'),\n    (0x1E100, 'V'),\n    (0x1E12D, 'X'),\n    (0x1E130, 'V'),\n    (0x1E13E, 'X'),\n    (0x1E140, 'V'),\n    (0x1E14A, 'X'),\n    (0x1E14E, 'V'),\n    (0x1E150, 'X'),\n    (0x1E290, 'V'),\n    (0x1E2AF, 'X'),\n    (0x1E2C0, 'V'),\n    (0x1E2FA, 'X'),\n    (0x1E2FF, 'V'),\n    (0x1E300, 'X'),\n    (0x1E4D0, 'V'),\n    (0x1E4FA, 'X'),\n    (0x1E7E0, 'V'),\n    (0x1E7E7, 'X'),\n    (0x1E7E8, 'V'),\n    (0x1E7EC, 'X'),\n    (0x1E7ED, 'V'),\n    (0x1E7EF, 'X'),\n    (0x1E7F0, 'V'),\n    (0x1E7FF, 'X'),\n    (0x1E800, 'V'),\n    (0x1E8C5, 'X'),\n    (0x1E8C7, 'V'),\n    (0x1E8D7, 'X'),\n    (0x1E900, 'M', '𞤢'),\n    (0x1E901, 'M', '𞤣'),\n    (0x1E902, 'M', '𞤤'),\n    (0x1E903, 'M', '𞤥'),\n    (0x1E904, 'M', '𞤦'),\n    (0x1E905, 'M', '𞤧'),\n    (0x1E906, 'M', '𞤨'),\n    (0x1E907, 'M', '𞤩'),\n    (0x1E908, 'M', '𞤪'),\n    (0x1E909, 'M', '𞤫'),\n    ]\n\ndef _seg_72() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1E90A, 'M', '𞤬'),\n    (0x1E90B, 'M', '𞤭'),\n    (0x1E90C, 'M', '𞤮'),\n    (0x1E90D, 'M', '𞤯'),\n    (0x1E90E, 'M', '𞤰'),\n    (0x1E90F, 'M', '𞤱'),\n    (0x1E910, 'M', '𞤲'),\n    (0x1E911, 'M', '𞤳'),\n    (0x1E912, 'M', '𞤴'),\n    (0x1E913, 'M', '𞤵'),\n    (0x1E914, 'M', '𞤶'),\n    (0x1E915, 'M', '𞤷'),\n    (0x1E916, 'M', '𞤸'),\n    (0x1E917, 'M', '𞤹'),\n    (0x1E918, 'M', '𞤺'),\n    (0x1E919, 'M', '𞤻'),\n    (0x1E91A, 'M', '𞤼'),\n    (0x1E91B, 'M', '𞤽'),\n    (0x1E91C, 'M', '𞤾'),\n    (0x1E91D, 'M', '𞤿'),\n    (0x1E91E, 'M', '𞥀'),\n    (0x1E91F, 'M', '𞥁'),\n    (0x1E920, 'M', '𞥂'),\n    (0x1E921, 'M', '𞥃'),\n    (0x1E922, 'V'),\n    (0x1E94C, 'X'),\n    (0x1E950, 'V'),\n    (0x1E95A, 'X'),\n    (0x1E95E, 'V'),\n    (0x1E960, 'X'),\n    (0x1EC71, 'V'),\n    (0x1ECB5, 'X'),\n    (0x1ED01, 'V'),\n    (0x1ED3E, 'X'),\n    (0x1EE00, 'M', 'ا'),\n    (0x1EE01, 'M', 'ب'),\n    (0x1EE02, 'M', 'ج'),\n    (0x1EE03, 'M', 'د'),\n    (0x1EE04, 'X'),\n    (0x1EE05, 'M', 'و'),\n    (0x1EE06, 'M', 'ز'),\n    (0x1EE07, 'M', 'ح'),\n    (0x1EE08, 'M', 'ط'),\n    (0x1EE09, 'M', 'ي'),\n    (0x1EE0A, 'M', 'ك'),\n    (0x1EE0B, 'M', 'ل'),\n    (0x1EE0C, 'M', 'م'),\n    (0x1EE0D, 'M', 'ن'),\n    (0x1EE0E, 'M', 'س'),\n    (0x1EE0F, 'M', 'ع'),\n    (0x1EE10, 'M', 'ف'),\n    (0x1EE11, 'M', 'ص'),\n    (0x1EE12, 'M', 'ق'),\n    (0x1EE13, 'M', 'ر'),\n    (0x1EE14, 'M', 'ش'),\n    (0x1EE15, 'M', 'ت'),\n    (0x1EE16, 'M', 'ث'),\n    (0x1EE17, 'M', 'خ'),\n    (0x1EE18, 'M', 'ذ'),\n    (0x1EE19, 'M', 'ض'),\n    (0x1EE1A, 'M', 'ظ'),\n    (0x1EE1B, 'M', 'غ'),\n    (0x1EE1C, 'M', 'ٮ'),\n    (0x1EE1D, 'M', 'ں'),\n    (0x1EE1E, 'M', 'ڡ'),\n    (0x1EE1F, 'M', 'ٯ'),\n    (0x1EE20, 'X'),\n    (0x1EE21, 'M', 'ب'),\n    (0x1EE22, 'M', 'ج'),\n    (0x1EE23, 'X'),\n    (0x1EE24, 'M', 'ه'),\n    (0x1EE25, 'X'),\n    (0x1EE27, 'M', 'ح'),\n    (0x1EE28, 'X'),\n    (0x1EE29, 'M', 'ي'),\n    (0x1EE2A, 'M', 'ك'),\n    (0x1EE2B, 'M', 'ل'),\n    (0x1EE2C, 'M', 'م'),\n    (0x1EE2D, 'M', 'ن'),\n    (0x1EE2E, 'M', 'س'),\n    (0x1EE2F, 'M', 'ع'),\n    (0x1EE30, 'M', 'ف'),\n    (0x1EE31, 'M', 'ص'),\n    (0x1EE32, 'M', 'ق'),\n    (0x1EE33, 'X'),\n    (0x1EE34, 'M', 'ش'),\n    (0x1EE35, 'M', 'ت'),\n    (0x1EE36, 'M', 'ث'),\n    (0x1EE37, 'M', 'خ'),\n    (0x1EE38, 'X'),\n    (0x1EE39, 'M', 'ض'),\n    (0x1EE3A, 'X'),\n    (0x1EE3B, 'M', 'غ'),\n    (0x1EE3C, 'X'),\n    (0x1EE42, 'M', 'ج'),\n    (0x1EE43, 'X'),\n    (0x1EE47, 'M', 'ح'),\n    (0x1EE48, 'X'),\n    (0x1EE49, 'M', 'ي'),\n    (0x1EE4A, 'X'),\n    ]\n\ndef _seg_73() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1EE4B, 'M', 'ل'),\n    (0x1EE4C, 'X'),\n    (0x1EE4D, 'M', 'ن'),\n    (0x1EE4E, 'M', 'س'),\n    (0x1EE4F, 'M', 'ع'),\n    (0x1EE50, 'X'),\n    (0x1EE51, 'M', 'ص'),\n    (0x1EE52, 'M', 'ق'),\n    (0x1EE53, 'X'),\n    (0x1EE54, 'M', 'ش'),\n    (0x1EE55, 'X'),\n    (0x1EE57, 'M', 'خ'),\n    (0x1EE58, 'X'),\n    (0x1EE59, 'M', 'ض'),\n    (0x1EE5A, 'X'),\n    (0x1EE5B, 'M', 'غ'),\n    (0x1EE5C, 'X'),\n    (0x1EE5D, 'M', 'ں'),\n    (0x1EE5E, 'X'),\n    (0x1EE5F, 'M', 'ٯ'),\n    (0x1EE60, 'X'),\n    (0x1EE61, 'M', 'ب'),\n    (0x1EE62, 'M', 'ج'),\n    (0x1EE63, 'X'),\n    (0x1EE64, 'M', 'ه'),\n    (0x1EE65, 'X'),\n    (0x1EE67, 'M', 'ح'),\n    (0x1EE68, 'M', 'ط'),\n    (0x1EE69, 'M', 'ي'),\n    (0x1EE6A, 'M', 'ك'),\n    (0x1EE6B, 'X'),\n    (0x1EE6C, 'M', 'م'),\n    (0x1EE6D, 'M', 'ن'),\n    (0x1EE6E, 'M', 'س'),\n    (0x1EE6F, 'M', 'ع'),\n    (0x1EE70, 'M', 'ف'),\n    (0x1EE71, 'M', 'ص'),\n    (0x1EE72, 'M', 'ق'),\n    (0x1EE73, 'X'),\n    (0x1EE74, 'M', 'ش'),\n    (0x1EE75, 'M', 'ت'),\n    (0x1EE76, 'M', 'ث'),\n    (0x1EE77, 'M', 'خ'),\n    (0x1EE78, 'X'),\n    (0x1EE79, 'M', 'ض'),\n    (0x1EE7A, 'M', 'ظ'),\n    (0x1EE7B, 'M', 'غ'),\n    (0x1EE7C, 'M', 'ٮ'),\n    (0x1EE7D, 'X'),\n    (0x1EE7E, 'M', 'ڡ'),\n    (0x1EE7F, 'X'),\n    (0x1EE80, 'M', 'ا'),\n    (0x1EE81, 'M', 'ب'),\n    (0x1EE82, 'M', 'ج'),\n    (0x1EE83, 'M', 'د'),\n    (0x1EE84, 'M', 'ه'),\n    (0x1EE85, 'M', 'و'),\n    (0x1EE86, 'M', 'ز'),\n    (0x1EE87, 'M', 'ح'),\n    (0x1EE88, 'M', 'ط'),\n    (0x1EE89, 'M', 'ي'),\n    (0x1EE8A, 'X'),\n    (0x1EE8B, 'M', 'ل'),\n    (0x1EE8C, 'M', 'م'),\n    (0x1EE8D, 'M', 'ن'),\n    (0x1EE8E, 'M', 'س'),\n    (0x1EE8F, 'M', 'ع'),\n    (0x1EE90, 'M', 'ف'),\n    (0x1EE91, 'M', 'ص'),\n    (0x1EE92, 'M', 'ق'),\n    (0x1EE93, 'M', 'ر'),\n    (0x1EE94, 'M', 'ش'),\n    (0x1EE95, 'M', 'ت'),\n    (0x1EE96, 'M', 'ث'),\n    (0x1EE97, 'M', 'خ'),\n    (0x1EE98, 'M', 'ذ'),\n    (0x1EE99, 'M', 'ض'),\n    (0x1EE9A, 'M', 'ظ'),\n    (0x1EE9B, 'M', 'غ'),\n    (0x1EE9C, 'X'),\n    (0x1EEA1, 'M', 'ب'),\n    (0x1EEA2, 'M', 'ج'),\n    (0x1EEA3, 'M', 'د'),\n    (0x1EEA4, 'X'),\n    (0x1EEA5, 'M', 'و'),\n    (0x1EEA6, 'M', 'ز'),\n    (0x1EEA7, 'M', 'ح'),\n    (0x1EEA8, 'M', 'ط'),\n    (0x1EEA9, 'M', 'ي'),\n    (0x1EEAA, 'X'),\n    (0x1EEAB, 'M', 'ل'),\n    (0x1EEAC, 'M', 'م'),\n    (0x1EEAD, 'M', 'ن'),\n    (0x1EEAE, 'M', 'س'),\n    (0x1EEAF, 'M', 'ع'),\n    (0x1EEB0, 'M', 'ف'),\n    (0x1EEB1, 'M', 'ص'),\n    (0x1EEB2, 'M', 'ق'),\n    (0x1EEB3, 'M', 'ر'),\n    (0x1EEB4, 'M', 'ش'),\n    ]\n\ndef _seg_74() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1EEB5, 'M', 'ت'),\n    (0x1EEB6, 'M', 'ث'),\n    (0x1EEB7, 'M', 'خ'),\n    (0x1EEB8, 'M', 'ذ'),\n    (0x1EEB9, 'M', 'ض'),\n    (0x1EEBA, 'M', 'ظ'),\n    (0x1EEBB, 'M', 'غ'),\n    (0x1EEBC, 'X'),\n    (0x1EEF0, 'V'),\n    (0x1EEF2, 'X'),\n    (0x1F000, 'V'),\n    (0x1F02C, 'X'),\n    (0x1F030, 'V'),\n    (0x1F094, 'X'),\n    (0x1F0A0, 'V'),\n    (0x1F0AF, 'X'),\n    (0x1F0B1, 'V'),\n    (0x1F0C0, 'X'),\n    (0x1F0C1, 'V'),\n    (0x1F0D0, 'X'),\n    (0x1F0D1, 'V'),\n    (0x1F0F6, 'X'),\n    (0x1F101, '3', '0,'),\n    (0x1F102, '3', '1,'),\n    (0x1F103, '3', '2,'),\n    (0x1F104, '3', '3,'),\n    (0x1F105, '3', '4,'),\n    (0x1F106, '3', '5,'),\n    (0x1F107, '3', '6,'),\n    (0x1F108, '3', '7,'),\n    (0x1F109, '3', '8,'),\n    (0x1F10A, '3', '9,'),\n    (0x1F10B, 'V'),\n    (0x1F110, '3', '(a)'),\n    (0x1F111, '3', '(b)'),\n    (0x1F112, '3', '(c)'),\n    (0x1F113, '3', '(d)'),\n    (0x1F114, '3', '(e)'),\n    (0x1F115, '3', '(f)'),\n    (0x1F116, '3', '(g)'),\n    (0x1F117, '3', '(h)'),\n    (0x1F118, '3', '(i)'),\n    (0x1F119, '3', '(j)'),\n    (0x1F11A, '3', '(k)'),\n    (0x1F11B, '3', '(l)'),\n    (0x1F11C, '3', '(m)'),\n    (0x1F11D, '3', '(n)'),\n    (0x1F11E, '3', '(o)'),\n    (0x1F11F, '3', '(p)'),\n    (0x1F120, '3', '(q)'),\n    (0x1F121, '3', '(r)'),\n    (0x1F122, '3', '(s)'),\n    (0x1F123, '3', '(t)'),\n    (0x1F124, '3', '(u)'),\n    (0x1F125, '3', '(v)'),\n    (0x1F126, '3', '(w)'),\n    (0x1F127, '3', '(x)'),\n    (0x1F128, '3', '(y)'),\n    (0x1F129, '3', '(z)'),\n    (0x1F12A, 'M', '〔s〕'),\n    (0x1F12B, 'M', 'c'),\n    (0x1F12C, 'M', 'r'),\n    (0x1F12D, 'M', 'cd'),\n    (0x1F12E, 'M', 'wz'),\n    (0x1F12F, 'V'),\n    (0x1F130, 'M', 'a'),\n    (0x1F131, 'M', 'b'),\n    (0x1F132, 'M', 'c'),\n    (0x1F133, 'M', 'd'),\n    (0x1F134, 'M', 'e'),\n    (0x1F135, 'M', 'f'),\n    (0x1F136, 'M', 'g'),\n    (0x1F137, 'M', 'h'),\n    (0x1F138, 'M', 'i'),\n    (0x1F139, 'M', 'j'),\n    (0x1F13A, 'M', 'k'),\n    (0x1F13B, 'M', 'l'),\n    (0x1F13C, 'M', 'm'),\n    (0x1F13D, 'M', 'n'),\n    (0x1F13E, 'M', 'o'),\n    (0x1F13F, 'M', 'p'),\n    (0x1F140, 'M', 'q'),\n    (0x1F141, 'M', 'r'),\n    (0x1F142, 'M', 's'),\n    (0x1F143, 'M', 't'),\n    (0x1F144, 'M', 'u'),\n    (0x1F145, 'M', 'v'),\n    (0x1F146, 'M', 'w'),\n    (0x1F147, 'M', 'x'),\n    (0x1F148, 'M', 'y'),\n    (0x1F149, 'M', 'z'),\n    (0x1F14A, 'M', 'hv'),\n    (0x1F14B, 'M', 'mv'),\n    (0x1F14C, 'M', 'sd'),\n    (0x1F14D, 'M', 'ss'),\n    (0x1F14E, 'M', 'ppv'),\n    (0x1F14F, 'M', 'wc'),\n    (0x1F150, 'V'),\n    (0x1F16A, 'M', 'mc'),\n    (0x1F16B, 'M', 'md'),\n    ]\n\ndef _seg_75() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1F16C, 'M', 'mr'),\n    (0x1F16D, 'V'),\n    (0x1F190, 'M', 'dj'),\n    (0x1F191, 'V'),\n    (0x1F1AE, 'X'),\n    (0x1F1E6, 'V'),\n    (0x1F200, 'M', 'ほか'),\n    (0x1F201, 'M', 'ココ'),\n    (0x1F202, 'M', 'サ'),\n    (0x1F203, 'X'),\n    (0x1F210, 'M', '手'),\n    (0x1F211, 'M', '字'),\n    (0x1F212, 'M', '双'),\n    (0x1F213, 'M', 'デ'),\n    (0x1F214, 'M', '二'),\n    (0x1F215, 'M', '多'),\n    (0x1F216, 'M', '解'),\n    (0x1F217, 'M', '天'),\n    (0x1F218, 'M', '交'),\n    (0x1F219, 'M', '映'),\n    (0x1F21A, 'M', '無'),\n    (0x1F21B, 'M', '料'),\n    (0x1F21C, 'M', '前'),\n    (0x1F21D, 'M', '後'),\n    (0x1F21E, 'M', '再'),\n    (0x1F21F, 'M', '新'),\n    (0x1F220, 'M', '初'),\n    (0x1F221, 'M', '終'),\n    (0x1F222, 'M', '生'),\n    (0x1F223, 'M', '販'),\n    (0x1F224, 'M', '声'),\n    (0x1F225, 'M', '吹'),\n    (0x1F226, 'M', '演'),\n    (0x1F227, 'M', '投'),\n    (0x1F228, 'M', '捕'),\n    (0x1F229, 'M', '一'),\n    (0x1F22A, 'M', '三'),\n    (0x1F22B, 'M', '遊'),\n    (0x1F22C, 'M', '左'),\n    (0x1F22D, 'M', '中'),\n    (0x1F22E, 'M', '右'),\n    (0x1F22F, 'M', '指'),\n    (0x1F230, 'M', '走'),\n    (0x1F231, 'M', '打'),\n    (0x1F232, 'M', '禁'),\n    (0x1F233, 'M', '空'),\n    (0x1F234, 'M', '合'),\n    (0x1F235, 'M', '満'),\n    (0x1F236, 'M', '有'),\n    (0x1F237, 'M', '月'),\n    (0x1F238, 'M', '申'),\n    (0x1F239, 'M', '割'),\n    (0x1F23A, 'M', '営'),\n    (0x1F23B, 'M', '配'),\n    (0x1F23C, 'X'),\n    (0x1F240, 'M', '〔本〕'),\n    (0x1F241, 'M', '〔三〕'),\n    (0x1F242, 'M', '〔二〕'),\n    (0x1F243, 'M', '〔安〕'),\n    (0x1F244, 'M', '〔点〕'),\n    (0x1F245, 'M', '〔打〕'),\n    (0x1F246, 'M', '〔盗〕'),\n    (0x1F247, 'M', '〔勝〕'),\n    (0x1F248, 'M', '〔敗〕'),\n    (0x1F249, 'X'),\n    (0x1F250, 'M', '得'),\n    (0x1F251, 'M', '可'),\n    (0x1F252, 'X'),\n    (0x1F260, 'V'),\n    (0x1F266, 'X'),\n    (0x1F300, 'V'),\n    (0x1F6D8, 'X'),\n    (0x1F6DC, 'V'),\n    (0x1F6ED, 'X'),\n    (0x1F6F0, 'V'),\n    (0x1F6FD, 'X'),\n    (0x1F700, 'V'),\n    (0x1F777, 'X'),\n    (0x1F77B, 'V'),\n    (0x1F7DA, 'X'),\n    (0x1F7E0, 'V'),\n    (0x1F7EC, 'X'),\n    (0x1F7F0, 'V'),\n    (0x1F7F1, 'X'),\n    (0x1F800, 'V'),\n    (0x1F80C, 'X'),\n    (0x1F810, 'V'),\n    (0x1F848, 'X'),\n    (0x1F850, 'V'),\n    (0x1F85A, 'X'),\n    (0x1F860, 'V'),\n    (0x1F888, 'X'),\n    (0x1F890, 'V'),\n    (0x1F8AE, 'X'),\n    (0x1F8B0, 'V'),\n    (0x1F8B2, 'X'),\n    (0x1F900, 'V'),\n    (0x1FA54, 'X'),\n    (0x1FA60, 'V'),\n    (0x1FA6E, 'X'),\n    ]\n\ndef _seg_76() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x1FA70, 'V'),\n    (0x1FA7D, 'X'),\n    (0x1FA80, 'V'),\n    (0x1FA89, 'X'),\n    (0x1FA90, 'V'),\n    (0x1FABE, 'X'),\n    (0x1FABF, 'V'),\n    (0x1FAC6, 'X'),\n    (0x1FACE, 'V'),\n    (0x1FADC, 'X'),\n    (0x1FAE0, 'V'),\n    (0x1FAE9, 'X'),\n    (0x1FAF0, 'V'),\n    (0x1FAF9, 'X'),\n    (0x1FB00, 'V'),\n    (0x1FB93, 'X'),\n    (0x1FB94, 'V'),\n    (0x1FBCB, 'X'),\n    (0x1FBF0, 'M', '0'),\n    (0x1FBF1, 'M', '1'),\n    (0x1FBF2, 'M', '2'),\n    (0x1FBF3, 'M', '3'),\n    (0x1FBF4, 'M', '4'),\n    (0x1FBF5, 'M', '5'),\n    (0x1FBF6, 'M', '6'),\n    (0x1FBF7, 'M', '7'),\n    (0x1FBF8, 'M', '8'),\n    (0x1FBF9, 'M', '9'),\n    (0x1FBFA, 'X'),\n    (0x20000, 'V'),\n    (0x2A6E0, 'X'),\n    (0x2A700, 'V'),\n    (0x2B73A, 'X'),\n    (0x2B740, 'V'),\n    (0x2B81E, 'X'),\n    (0x2B820, 'V'),\n    (0x2CEA2, 'X'),\n    (0x2CEB0, 'V'),\n    (0x2EBE1, 'X'),\n    (0x2F800, 'M', '丽'),\n    (0x2F801, 'M', '丸'),\n    (0x2F802, 'M', '乁'),\n    (0x2F803, 'M', '𠄢'),\n    (0x2F804, 'M', '你'),\n    (0x2F805, 'M', '侮'),\n    (0x2F806, 'M', '侻'),\n    (0x2F807, 'M', '倂'),\n    (0x2F808, 'M', '偺'),\n    (0x2F809, 'M', '備'),\n    (0x2F80A, 'M', '僧'),\n    (0x2F80B, 'M', '像'),\n    (0x2F80C, 'M', '㒞'),\n    (0x2F80D, 'M', '𠘺'),\n    (0x2F80E, 'M', '免'),\n    (0x2F80F, 'M', '兔'),\n    (0x2F810, 'M', '兤'),\n    (0x2F811, 'M', '具'),\n    (0x2F812, 'M', '𠔜'),\n    (0x2F813, 'M', '㒹'),\n    (0x2F814, 'M', '內'),\n    (0x2F815, 'M', '再'),\n    (0x2F816, 'M', '𠕋'),\n    (0x2F817, 'M', '冗'),\n    (0x2F818, 'M', '冤'),\n    (0x2F819, 'M', '仌'),\n    (0x2F81A, 'M', '冬'),\n    (0x2F81B, 'M', '况'),\n    (0x2F81C, 'M', '𩇟'),\n    (0x2F81D, 'M', '凵'),\n    (0x2F81E, 'M', '刃'),\n    (0x2F81F, 'M', '㓟'),\n    (0x2F820, 'M', '刻'),\n    (0x2F821, 'M', '剆'),\n    (0x2F822, 'M', '割'),\n    (0x2F823, 'M', '剷'),\n    (0x2F824, 'M', '㔕'),\n    (0x2F825, 'M', '勇'),\n    (0x2F826, 'M', '勉'),\n    (0x2F827, 'M', '勤'),\n    (0x2F828, 'M', '勺'),\n    (0x2F829, 'M', '包'),\n    (0x2F82A, 'M', '匆'),\n    (0x2F82B, 'M', '北'),\n    (0x2F82C, 'M', '卉'),\n    (0x2F82D, 'M', '卑'),\n    (0x2F82E, 'M', '博'),\n    (0x2F82F, 'M', '即'),\n    (0x2F830, 'M', '卽'),\n    (0x2F831, 'M', '卿'),\n    (0x2F834, 'M', '𠨬'),\n    (0x2F835, 'M', '灰'),\n    (0x2F836, 'M', '及'),\n    (0x2F837, 'M', '叟'),\n    (0x2F838, 'M', '𠭣'),\n    (0x2F839, 'M', '叫'),\n    (0x2F83A, 'M', '叱'),\n    (0x2F83B, 'M', '吆'),\n    (0x2F83C, 'M', '咞'),\n    (0x2F83D, 'M', '吸'),\n    (0x2F83E, 'M', '呈'),\n    ]\n\ndef _seg_77() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x2F83F, 'M', '周'),\n    (0x2F840, 'M', '咢'),\n    (0x2F841, 'M', '哶'),\n    (0x2F842, 'M', '唐'),\n    (0x2F843, 'M', '啓'),\n    (0x2F844, 'M', '啣'),\n    (0x2F845, 'M', '善'),\n    (0x2F847, 'M', '喙'),\n    (0x2F848, 'M', '喫'),\n    (0x2F849, 'M', '喳'),\n    (0x2F84A, 'M', '嗂'),\n    (0x2F84B, 'M', '圖'),\n    (0x2F84C, 'M', '嘆'),\n    (0x2F84D, 'M', '圗'),\n    (0x2F84E, 'M', '噑'),\n    (0x2F84F, 'M', '噴'),\n    (0x2F850, 'M', '切'),\n    (0x2F851, 'M', '壮'),\n    (0x2F852, 'M', '城'),\n    (0x2F853, 'M', '埴'),\n    (0x2F854, 'M', '堍'),\n    (0x2F855, 'M', '型'),\n    (0x2F856, 'M', '堲'),\n    (0x2F857, 'M', '報'),\n    (0x2F858, 'M', '墬'),\n    (0x2F859, 'M', '𡓤'),\n    (0x2F85A, 'M', '売'),\n    (0x2F85B, 'M', '壷'),\n    (0x2F85C, 'M', '夆'),\n    (0x2F85D, 'M', '多'),\n    (0x2F85E, 'M', '夢'),\n    (0x2F85F, 'M', '奢'),\n    (0x2F860, 'M', '𡚨'),\n    (0x2F861, 'M', '𡛪'),\n    (0x2F862, 'M', '姬'),\n    (0x2F863, 'M', '娛'),\n    (0x2F864, 'M', '娧'),\n    (0x2F865, 'M', '姘'),\n    (0x2F866, 'M', '婦'),\n    (0x2F867, 'M', '㛮'),\n    (0x2F868, 'X'),\n    (0x2F869, 'M', '嬈'),\n    (0x2F86A, 'M', '嬾'),\n    (0x2F86C, 'M', '𡧈'),\n    (0x2F86D, 'M', '寃'),\n    (0x2F86E, 'M', '寘'),\n    (0x2F86F, 'M', '寧'),\n    (0x2F870, 'M', '寳'),\n    (0x2F871, 'M', '𡬘'),\n    (0x2F872, 'M', '寿'),\n    (0x2F873, 'M', '将'),\n    (0x2F874, 'X'),\n    (0x2F875, 'M', '尢'),\n    (0x2F876, 'M', '㞁'),\n    (0x2F877, 'M', '屠'),\n    (0x2F878, 'M', '屮'),\n    (0x2F879, 'M', '峀'),\n    (0x2F87A, 'M', '岍'),\n    (0x2F87B, 'M', '𡷤'),\n    (0x2F87C, 'M', '嵃'),\n    (0x2F87D, 'M', '𡷦'),\n    (0x2F87E, 'M', '嵮'),\n    (0x2F87F, 'M', '嵫'),\n    (0x2F880, 'M', '嵼'),\n    (0x2F881, 'M', '巡'),\n    (0x2F882, 'M', '巢'),\n    (0x2F883, 'M', '㠯'),\n    (0x2F884, 'M', '巽'),\n    (0x2F885, 'M', '帨'),\n    (0x2F886, 'M', '帽'),\n    (0x2F887, 'M', '幩'),\n    (0x2F888, 'M', '㡢'),\n    (0x2F889, 'M', '𢆃'),\n    (0x2F88A, 'M', '㡼'),\n    (0x2F88B, 'M', '庰'),\n    (0x2F88C, 'M', '庳'),\n    (0x2F88D, 'M', '庶'),\n    (0x2F88E, 'M', '廊'),\n    (0x2F88F, 'M', '𪎒'),\n    (0x2F890, 'M', '廾'),\n    (0x2F891, 'M', '𢌱'),\n    (0x2F893, 'M', '舁'),\n    (0x2F894, 'M', '弢'),\n    (0x2F896, 'M', '㣇'),\n    (0x2F897, 'M', '𣊸'),\n    (0x2F898, 'M', '𦇚'),\n    (0x2F899, 'M', '形'),\n    (0x2F89A, 'M', '彫'),\n    (0x2F89B, 'M', '㣣'),\n    (0x2F89C, 'M', '徚'),\n    (0x2F89D, 'M', '忍'),\n    (0x2F89E, 'M', '志'),\n    (0x2F89F, 'M', '忹'),\n    (0x2F8A0, 'M', '悁'),\n    (0x2F8A1, 'M', '㤺'),\n    (0x2F8A2, 'M', '㤜'),\n    (0x2F8A3, 'M', '悔'),\n    (0x2F8A4, 'M', '𢛔'),\n    (0x2F8A5, 'M', '惇'),\n    (0x2F8A6, 'M', '慈'),\n    ]\n\ndef _seg_78() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x2F8A7, 'M', '慌'),\n    (0x2F8A8, 'M', '慎'),\n    (0x2F8A9, 'M', '慌'),\n    (0x2F8AA, 'M', '慺'),\n    (0x2F8AB, 'M', '憎'),\n    (0x2F8AC, 'M', '憲'),\n    (0x2F8AD, 'M', '憤'),\n    (0x2F8AE, 'M', '憯'),\n    (0x2F8AF, 'M', '懞'),\n    (0x2F8B0, 'M', '懲'),\n    (0x2F8B1, 'M', '懶'),\n    (0x2F8B2, 'M', '成'),\n    (0x2F8B3, 'M', '戛'),\n    (0x2F8B4, 'M', '扝'),\n    (0x2F8B5, 'M', '抱'),\n    (0x2F8B6, 'M', '拔'),\n    (0x2F8B7, 'M', '捐'),\n    (0x2F8B8, 'M', '𢬌'),\n    (0x2F8B9, 'M', '挽'),\n    (0x2F8BA, 'M', '拼'),\n    (0x2F8BB, 'M', '捨'),\n    (0x2F8BC, 'M', '掃'),\n    (0x2F8BD, 'M', '揤'),\n    (0x2F8BE, 'M', '𢯱'),\n    (0x2F8BF, 'M', '搢'),\n    (0x2F8C0, 'M', '揅'),\n    (0x2F8C1, 'M', '掩'),\n    (0x2F8C2, 'M', '㨮'),\n    (0x2F8C3, 'M', '摩'),\n    (0x2F8C4, 'M', '摾'),\n    (0x2F8C5, 'M', '撝'),\n    (0x2F8C6, 'M', '摷'),\n    (0x2F8C7, 'M', '㩬'),\n    (0x2F8C8, 'M', '敏'),\n    (0x2F8C9, 'M', '敬'),\n    (0x2F8CA, 'M', '𣀊'),\n    (0x2F8CB, 'M', '旣'),\n    (0x2F8CC, 'M', '書'),\n    (0x2F8CD, 'M', '晉'),\n    (0x2F8CE, 'M', '㬙'),\n    (0x2F8CF, 'M', '暑'),\n    (0x2F8D0, 'M', '㬈'),\n    (0x2F8D1, 'M', '㫤'),\n    (0x2F8D2, 'M', '冒'),\n    (0x2F8D3, 'M', '冕'),\n    (0x2F8D4, 'M', '最'),\n    (0x2F8D5, 'M', '暜'),\n    (0x2F8D6, 'M', '肭'),\n    (0x2F8D7, 'M', '䏙'),\n    (0x2F8D8, 'M', '朗'),\n    (0x2F8D9, 'M', '望'),\n    (0x2F8DA, 'M', '朡'),\n    (0x2F8DB, 'M', '杞'),\n    (0x2F8DC, 'M', '杓'),\n    (0x2F8DD, 'M', '𣏃'),\n    (0x2F8DE, 'M', '㭉'),\n    (0x2F8DF, 'M', '柺'),\n    (0x2F8E0, 'M', '枅'),\n    (0x2F8E1, 'M', '桒'),\n    (0x2F8E2, 'M', '梅'),\n    (0x2F8E3, 'M', '𣑭'),\n    (0x2F8E4, 'M', '梎'),\n    (0x2F8E5, 'M', '栟'),\n    (0x2F8E6, 'M', '椔'),\n    (0x2F8E7, 'M', '㮝'),\n    (0x2F8E8, 'M', '楂'),\n    (0x2F8E9, 'M', '榣'),\n    (0x2F8EA, 'M', '槪'),\n    (0x2F8EB, 'M', '檨'),\n    (0x2F8EC, 'M', '𣚣'),\n    (0x2F8ED, 'M', '櫛'),\n    (0x2F8EE, 'M', '㰘'),\n    (0x2F8EF, 'M', '次'),\n    (0x2F8F0, 'M', '𣢧'),\n    (0x2F8F1, 'M', '歔'),\n    (0x2F8F2, 'M', '㱎'),\n    (0x2F8F3, 'M', '歲'),\n    (0x2F8F4, 'M', '殟'),\n    (0x2F8F5, 'M', '殺'),\n    (0x2F8F6, 'M', '殻'),\n    (0x2F8F7, 'M', '𣪍'),\n    (0x2F8F8, 'M', '𡴋'),\n    (0x2F8F9, 'M', '𣫺'),\n    (0x2F8FA, 'M', '汎'),\n    (0x2F8FB, 'M', '𣲼'),\n    (0x2F8FC, 'M', '沿'),\n    (0x2F8FD, 'M', '泍'),\n    (0x2F8FE, 'M', '汧'),\n    (0x2F8FF, 'M', '洖'),\n    (0x2F900, 'M', '派'),\n    (0x2F901, 'M', '海'),\n    (0x2F902, 'M', '流'),\n    (0x2F903, 'M', '浩'),\n    (0x2F904, 'M', '浸'),\n    (0x2F905, 'M', '涅'),\n    (0x2F906, 'M', '𣴞'),\n    (0x2F907, 'M', '洴'),\n    (0x2F908, 'M', '港'),\n    (0x2F909, 'M', '湮'),\n    (0x2F90A, 'M', '㴳'),\n    ]\n\ndef _seg_79() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x2F90B, 'M', '滋'),\n    (0x2F90C, 'M', '滇'),\n    (0x2F90D, 'M', '𣻑'),\n    (0x2F90E, 'M', '淹'),\n    (0x2F90F, 'M', '潮'),\n    (0x2F910, 'M', '𣽞'),\n    (0x2F911, 'M', '𣾎'),\n    (0x2F912, 'M', '濆'),\n    (0x2F913, 'M', '瀹'),\n    (0x2F914, 'M', '瀞'),\n    (0x2F915, 'M', '瀛'),\n    (0x2F916, 'M', '㶖'),\n    (0x2F917, 'M', '灊'),\n    (0x2F918, 'M', '災'),\n    (0x2F919, 'M', '灷'),\n    (0x2F91A, 'M', '炭'),\n    (0x2F91B, 'M', '𠔥'),\n    (0x2F91C, 'M', '煅'),\n    (0x2F91D, 'M', '𤉣'),\n    (0x2F91E, 'M', '熜'),\n    (0x2F91F, 'X'),\n    (0x2F920, 'M', '爨'),\n    (0x2F921, 'M', '爵'),\n    (0x2F922, 'M', '牐'),\n    (0x2F923, 'M', '𤘈'),\n    (0x2F924, 'M', '犀'),\n    (0x2F925, 'M', '犕'),\n    (0x2F926, 'M', '𤜵'),\n    (0x2F927, 'M', '𤠔'),\n    (0x2F928, 'M', '獺'),\n    (0x2F929, 'M', '王'),\n    (0x2F92A, 'M', '㺬'),\n    (0x2F92B, 'M', '玥'),\n    (0x2F92C, 'M', '㺸'),\n    (0x2F92E, 'M', '瑇'),\n    (0x2F92F, 'M', '瑜'),\n    (0x2F930, 'M', '瑱'),\n    (0x2F931, 'M', '璅'),\n    (0x2F932, 'M', '瓊'),\n    (0x2F933, 'M', '㼛'),\n    (0x2F934, 'M', '甤'),\n    (0x2F935, 'M', '𤰶'),\n    (0x2F936, 'M', '甾'),\n    (0x2F937, 'M', '𤲒'),\n    (0x2F938, 'M', '異'),\n    (0x2F939, 'M', '𢆟'),\n    (0x2F93A, 'M', '瘐'),\n    (0x2F93B, 'M', '𤾡'),\n    (0x2F93C, 'M', '𤾸'),\n    (0x2F93D, 'M', '𥁄'),\n    (0x2F93E, 'M', '㿼'),\n    (0x2F93F, 'M', '䀈'),\n    (0x2F940, 'M', '直'),\n    (0x2F941, 'M', '𥃳'),\n    (0x2F942, 'M', '𥃲'),\n    (0x2F943, 'M', '𥄙'),\n    (0x2F944, 'M', '𥄳'),\n    (0x2F945, 'M', '眞'),\n    (0x2F946, 'M', '真'),\n    (0x2F948, 'M', '睊'),\n    (0x2F949, 'M', '䀹'),\n    (0x2F94A, 'M', '瞋'),\n    (0x2F94B, 'M', '䁆'),\n    (0x2F94C, 'M', '䂖'),\n    (0x2F94D, 'M', '𥐝'),\n    (0x2F94E, 'M', '硎'),\n    (0x2F94F, 'M', '碌'),\n    (0x2F950, 'M', '磌'),\n    (0x2F951, 'M', '䃣'),\n    (0x2F952, 'M', '𥘦'),\n    (0x2F953, 'M', '祖'),\n    (0x2F954, 'M', '𥚚'),\n    (0x2F955, 'M', '𥛅'),\n    (0x2F956, 'M', '福'),\n    (0x2F957, 'M', '秫'),\n    (0x2F958, 'M', '䄯'),\n    (0x2F959, 'M', '穀'),\n    (0x2F95A, 'M', '穊'),\n    (0x2F95B, 'M', '穏'),\n    (0x2F95C, 'M', '𥥼'),\n    (0x2F95D, 'M', '𥪧'),\n    (0x2F95F, 'X'),\n    (0x2F960, 'M', '䈂'),\n    (0x2F961, 'M', '𥮫'),\n    (0x2F962, 'M', '篆'),\n    (0x2F963, 'M', '築'),\n    (0x2F964, 'M', '䈧'),\n    (0x2F965, 'M', '𥲀'),\n    (0x2F966, 'M', '糒'),\n    (0x2F967, 'M', '䊠'),\n    (0x2F968, 'M', '糨'),\n    (0x2F969, 'M', '糣'),\n    (0x2F96A, 'M', '紀'),\n    (0x2F96B, 'M', '𥾆'),\n    (0x2F96C, 'M', '絣'),\n    (0x2F96D, 'M', '䌁'),\n    (0x2F96E, 'M', '緇'),\n    (0x2F96F, 'M', '縂'),\n    (0x2F970, 'M', '繅'),\n    (0x2F971, 'M', '䌴'),\n    ]\n\ndef _seg_80() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x2F972, 'M', '𦈨'),\n    (0x2F973, 'M', '𦉇'),\n    (0x2F974, 'M', '䍙'),\n    (0x2F975, 'M', '𦋙'),\n    (0x2F976, 'M', '罺'),\n    (0x2F977, 'M', '𦌾'),\n    (0x2F978, 'M', '羕'),\n    (0x2F979, 'M', '翺'),\n    (0x2F97A, 'M', '者'),\n    (0x2F97B, 'M', '𦓚'),\n    (0x2F97C, 'M', '𦔣'),\n    (0x2F97D, 'M', '聠'),\n    (0x2F97E, 'M', '𦖨'),\n    (0x2F97F, 'M', '聰'),\n    (0x2F980, 'M', '𣍟'),\n    (0x2F981, 'M', '䏕'),\n    (0x2F982, 'M', '育'),\n    (0x2F983, 'M', '脃'),\n    (0x2F984, 'M', '䐋'),\n    (0x2F985, 'M', '脾'),\n    (0x2F986, 'M', '媵'),\n    (0x2F987, 'M', '𦞧'),\n    (0x2F988, 'M', '𦞵'),\n    (0x2F989, 'M', '𣎓'),\n    (0x2F98A, 'M', '𣎜'),\n    (0x2F98B, 'M', '舁'),\n    (0x2F98C, 'M', '舄'),\n    (0x2F98D, 'M', '辞'),\n    (0x2F98E, 'M', '䑫'),\n    (0x2F98F, 'M', '芑'),\n    (0x2F990, 'M', '芋'),\n    (0x2F991, 'M', '芝'),\n    (0x2F992, 'M', '劳'),\n    (0x2F993, 'M', '花'),\n    (0x2F994, 'M', '芳'),\n    (0x2F995, 'M', '芽'),\n    (0x2F996, 'M', '苦'),\n    (0x2F997, 'M', '𦬼'),\n    (0x2F998, 'M', '若'),\n    (0x2F999, 'M', '茝'),\n    (0x2F99A, 'M', '荣'),\n    (0x2F99B, 'M', '莭'),\n    (0x2F99C, 'M', '茣'),\n    (0x2F99D, 'M', '莽'),\n    (0x2F99E, 'M', '菧'),\n    (0x2F99F, 'M', '著'),\n    (0x2F9A0, 'M', '荓'),\n    (0x2F9A1, 'M', '菊'),\n    (0x2F9A2, 'M', '菌'),\n    (0x2F9A3, 'M', '菜'),\n    (0x2F9A4, 'M', '𦰶'),\n    (0x2F9A5, 'M', '𦵫'),\n    (0x2F9A6, 'M', '𦳕'),\n    (0x2F9A7, 'M', '䔫'),\n    (0x2F9A8, 'M', '蓱'),\n    (0x2F9A9, 'M', '蓳'),\n    (0x2F9AA, 'M', '蔖'),\n    (0x2F9AB, 'M', '𧏊'),\n    (0x2F9AC, 'M', '蕤'),\n    (0x2F9AD, 'M', '𦼬'),\n    (0x2F9AE, 'M', '䕝'),\n    (0x2F9AF, 'M', '䕡'),\n    (0x2F9B0, 'M', '𦾱'),\n    (0x2F9B1, 'M', '𧃒'),\n    (0x2F9B2, 'M', '䕫'),\n    (0x2F9B3, 'M', '虐'),\n    (0x2F9B4, 'M', '虜'),\n    (0x2F9B5, 'M', '虧'),\n    (0x2F9B6, 'M', '虩'),\n    (0x2F9B7, 'M', '蚩'),\n    (0x2F9B8, 'M', '蚈'),\n    (0x2F9B9, 'M', '蜎'),\n    (0x2F9BA, 'M', '蛢'),\n    (0x2F9BB, 'M', '蝹'),\n    (0x2F9BC, 'M', '蜨'),\n    (0x2F9BD, 'M', '蝫'),\n    (0x2F9BE, 'M', '螆'),\n    (0x2F9BF, 'X'),\n    (0x2F9C0, 'M', '蟡'),\n    (0x2F9C1, 'M', '蠁'),\n    (0x2F9C2, 'M', '䗹'),\n    (0x2F9C3, 'M', '衠'),\n    (0x2F9C4, 'M', '衣'),\n    (0x2F9C5, 'M', '𧙧'),\n    (0x2F9C6, 'M', '裗'),\n    (0x2F9C7, 'M', '裞'),\n    (0x2F9C8, 'M', '䘵'),\n    (0x2F9C9, 'M', '裺'),\n    (0x2F9CA, 'M', '㒻'),\n    (0x2F9CB, 'M', '𧢮'),\n    (0x2F9CC, 'M', '𧥦'),\n    (0x2F9CD, 'M', '䚾'),\n    (0x2F9CE, 'M', '䛇'),\n    (0x2F9CF, 'M', '誠'),\n    (0x2F9D0, 'M', '諭'),\n    (0x2F9D1, 'M', '變'),\n    (0x2F9D2, 'M', '豕'),\n    (0x2F9D3, 'M', '𧲨'),\n    (0x2F9D4, 'M', '貫'),\n    (0x2F9D5, 'M', '賁'),\n    ]\n\ndef _seg_81() -> List[Union[Tuple[int, str], Tuple[int, str, str]]]:\n    return [\n    (0x2F9D6, 'M', '贛'),\n    (0x2F9D7, 'M', '起'),\n    (0x2F9D8, 'M', '𧼯'),\n    (0x2F9D9, 'M', '𠠄'),\n    (0x2F9DA, 'M', '跋'),\n    (0x2F9DB, 'M', '趼'),\n    (0x2F9DC, 'M', '跰'),\n    (0x2F9DD, 'M', '𠣞'),\n    (0x2F9DE, 'M', '軔'),\n    (0x2F9DF, 'M', '輸'),\n    (0x2F9E0, 'M', '𨗒'),\n    (0x2F9E1, 'M', '𨗭'),\n    (0x2F9E2, 'M', '邔'),\n    (0x2F9E3, 'M', '郱'),\n    (0x2F9E4, 'M', '鄑'),\n    (0x2F9E5, 'M', '𨜮'),\n    (0x2F9E6, 'M', '鄛'),\n    (0x2F9E7, 'M', '鈸'),\n    (0x2F9E8, 'M', '鋗'),\n    (0x2F9E9, 'M', '鋘'),\n    (0x2F9EA, 'M', '鉼'),\n    (0x2F9EB, 'M', '鏹'),\n    (0x2F9EC, 'M', '鐕'),\n    (0x2F9ED, 'M', '𨯺'),\n    (0x2F9EE, 'M', '開'),\n    (0x2F9EF, 'M', '䦕'),\n    (0x2F9F0, 'M', '閷'),\n    (0x2F9F1, 'M', '𨵷'),\n    (0x2F9F2, 'M', '䧦'),\n    (0x2F9F3, 'M', '雃'),\n    (0x2F9F4, 'M', '嶲'),\n    (0x2F9F5, 'M', '霣'),\n    (0x2F9F6, 'M', '𩅅'),\n    (0x2F9F7, 'M', '𩈚'),\n    (0x2F9F8, 'M', '䩮'),\n    (0x2F9F9, 'M', '䩶'),\n    (0x2F9FA, 'M', '韠'),\n    (0x2F9FB, 'M', '𩐊'),\n    (0x2F9FC, 'M', '䪲'),\n    (0x2F9FD, 'M', '𩒖'),\n    (0x2F9FE, 'M', '頋'),\n    (0x2FA00, 'M', '頩'),\n    (0x2FA01, 'M', '𩖶'),\n    (0x2FA02, 'M', '飢'),\n    (0x2FA03, 'M', '䬳'),\n    (0x2FA04, 'M', '餩'),\n    (0x2FA05, 'M', '馧'),\n    (0x2FA06, 'M', '駂'),\n    (0x2FA07, 'M', '駾'),\n    (0x2FA08, 'M', '䯎'),\n    (0x2FA09, 'M', '𩬰'),\n    (0x2FA0A, 'M', '鬒'),\n    (0x2FA0B, 'M', '鱀'),\n    (0x2FA0C, 'M', '鳽'),\n    (0x2FA0D, 'M', '䳎'),\n    (0x2FA0E, 'M', '䳭'),\n    (0x2FA0F, 'M', '鵧'),\n    (0x2FA10, 'M', '𪃎'),\n    (0x2FA11, 'M', '䳸'),\n    (0x2FA12, 'M', '𪄅'),\n    (0x2FA13, 'M', '𪈎'),\n    (0x2FA14, 'M', '𪊑'),\n    (0x2FA15, 'M', '麻'),\n    (0x2FA16, 'M', '䵖'),\n    (0x2FA17, 'M', '黹'),\n    (0x2FA18, 'M', '黾'),\n    (0x2FA19, 'M', '鼅'),\n    (0x2FA1A, 'M', '鼏'),\n    (0x2FA1B, 'M', '鼖'),\n    (0x2FA1C, 'M', '鼻'),\n    (0x2FA1D, 'M', '𪘀'),\n    (0x2FA1E, 'X'),\n    (0x30000, 'V'),\n    (0x3134B, 'X'),\n    (0x31350, 'V'),\n    (0x323B0, 'X'),\n    (0xE0100, 'I'),\n    (0xE01F0, 'X'),\n    ]\n\nuts46data = tuple(\n    _seg_0()\n    + _seg_1()\n    + _seg_2()\n    + _seg_3()\n    + _seg_4()\n    + _seg_5()\n    + _seg_6()\n    + _seg_7()\n    + _seg_8()\n    + _seg_9()\n    + _seg_10()\n    + _seg_11()\n    + _seg_12()\n    + _seg_13()\n    + _seg_14()\n    + _seg_15()\n    + _seg_16()\n    + _seg_17()\n    + _seg_18()\n    + _seg_19()\n    + _seg_20()\n    + _seg_21()\n    + _seg_22()\n    + _seg_23()\n    + _seg_24()\n    + _seg_25()\n    + _seg_26()\n    + _seg_27()\n    + _seg_28()\n    + _seg_29()\n    + _seg_30()\n    + _seg_31()\n    + _seg_32()\n    + _seg_33()\n    + _seg_34()\n    + _seg_35()\n    + _seg_36()\n    + _seg_37()\n    + _seg_38()\n    + _seg_39()\n    + _seg_40()\n    + _seg_41()\n    + _seg_42()\n    + _seg_43()\n    + _seg_44()\n    + _seg_45()\n    + _seg_46()\n    + _seg_47()\n    + _seg_48()\n    + _seg_49()\n    + _seg_50()\n    + _seg_51()\n    + _seg_52()\n    + _seg_53()\n    + _seg_54()\n    + _seg_55()\n    + _seg_56()\n    + _seg_57()\n    + _seg_58()\n    + _seg_59()\n    + _seg_60()\n    + _seg_61()\n    + _seg_62()\n    + _seg_63()\n    + _seg_64()\n    + _seg_65()\n    + _seg_66()\n    + _seg_67()\n    + _seg_68()\n    + _seg_69()\n    + _seg_70()\n    + _seg_71()\n    + _seg_72()\n    + _seg_73()\n    + _seg_74()\n    + _seg_75()\n    + _seg_76()\n    + _seg_77()\n    + _seg_78()\n    + _seg_79()\n    + _seg_80()\n    + _seg_81()\n)  # type: Tuple[Union[Tuple[int, str], Tuple[int, str, str]], ...]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/msgpack/__init__.py",
    "content": "# coding: utf-8\nfrom .exceptions import *\nfrom .ext import ExtType, Timestamp\n\nimport os\nimport sys\n\n\nversion = (1, 0, 4)\n__version__ = \"1.0.4\"\n\n\nif os.environ.get(\"MSGPACK_PUREPYTHON\") or sys.version_info[0] == 2:\n    from .fallback import Packer, unpackb, Unpacker\nelse:\n    try:\n        from ._cmsgpack import Packer, unpackb, Unpacker\n    except ImportError:\n        from .fallback import Packer, unpackb, Unpacker\n\n\ndef pack(o, stream, **kwargs):\n    \"\"\"\n    Pack object `o` and write it to `stream`\n\n    See :class:`Packer` for options.\n    \"\"\"\n    packer = Packer(**kwargs)\n    stream.write(packer.pack(o))\n\n\ndef packb(o, **kwargs):\n    \"\"\"\n    Pack object `o` and return packed bytes\n\n    See :class:`Packer` for options.\n    \"\"\"\n    return Packer(**kwargs).pack(o)\n\n\ndef unpack(stream, **kwargs):\n    \"\"\"\n    Unpack an object from `stream`.\n\n    Raises `ExtraData` when `stream` contains extra bytes.\n    See :class:`Unpacker` for options.\n    \"\"\"\n    data = stream.read()\n    return unpackb(data, **kwargs)\n\n\n# alias for compatibility to simplejson/marshal/pickle.\nload = unpack\nloads = unpackb\n\ndump = pack\ndumps = packb\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/msgpack/exceptions.py",
    "content": "class UnpackException(Exception):\n    \"\"\"Base class for some exceptions raised while unpacking.\n\n    NOTE: unpack may raise exception other than subclass of\n    UnpackException.  If you want to catch all error, catch\n    Exception instead.\n    \"\"\"\n\n\nclass BufferFull(UnpackException):\n    pass\n\n\nclass OutOfData(UnpackException):\n    pass\n\n\nclass FormatError(ValueError, UnpackException):\n    \"\"\"Invalid msgpack format\"\"\"\n\n\nclass StackError(ValueError, UnpackException):\n    \"\"\"Too nested\"\"\"\n\n\n# Deprecated.  Use ValueError instead\nUnpackValueError = ValueError\n\n\nclass ExtraData(UnpackValueError):\n    \"\"\"ExtraData is raised when there is trailing data.\n\n    This exception is raised while only one-shot (not streaming)\n    unpack.\n    \"\"\"\n\n    def __init__(self, unpacked, extra):\n        self.unpacked = unpacked\n        self.extra = extra\n\n    def __str__(self):\n        return \"unpack(b) received extra data.\"\n\n\n# Deprecated.  Use Exception instead to catch all exception during packing.\nPackException = Exception\nPackValueError = ValueError\nPackOverflowError = OverflowError\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/msgpack/ext.py",
    "content": "# coding: utf-8\nfrom collections import namedtuple\nimport datetime\nimport sys\nimport struct\n\n\nPY2 = sys.version_info[0] == 2\n\nif PY2:\n    int_types = (int, long)\n    _utc = None\nelse:\n    int_types = int\n    try:\n        _utc = datetime.timezone.utc\n    except AttributeError:\n        _utc = datetime.timezone(datetime.timedelta(0))\n\n\nclass ExtType(namedtuple(\"ExtType\", \"code data\")):\n    \"\"\"ExtType represents ext type in msgpack.\"\"\"\n\n    def __new__(cls, code, data):\n        if not isinstance(code, int):\n            raise TypeError(\"code must be int\")\n        if not isinstance(data, bytes):\n            raise TypeError(\"data must be bytes\")\n        if not 0 <= code <= 127:\n            raise ValueError(\"code must be 0~127\")\n        return super(ExtType, cls).__new__(cls, code, data)\n\n\nclass Timestamp(object):\n    \"\"\"Timestamp represents the Timestamp extension type in msgpack.\n\n    When built with Cython, msgpack uses C methods to pack and unpack `Timestamp`. When using pure-Python\n    msgpack, :func:`to_bytes` and :func:`from_bytes` are used to pack and unpack `Timestamp`.\n\n    This class is immutable: Do not override seconds and nanoseconds.\n    \"\"\"\n\n    __slots__ = [\"seconds\", \"nanoseconds\"]\n\n    def __init__(self, seconds, nanoseconds=0):\n        \"\"\"Initialize a Timestamp object.\n\n        :param int seconds:\n            Number of seconds since the UNIX epoch (00:00:00 UTC Jan 1 1970, minus leap seconds).\n            May be negative.\n\n        :param int nanoseconds:\n            Number of nanoseconds to add to `seconds` to get fractional time.\n            Maximum is 999_999_999.  Default is 0.\n\n        Note: Negative times (before the UNIX epoch) are represented as negative seconds + positive ns.\n        \"\"\"\n        if not isinstance(seconds, int_types):\n            raise TypeError(\"seconds must be an interger\")\n        if not isinstance(nanoseconds, int_types):\n            raise TypeError(\"nanoseconds must be an integer\")\n        if not (0 <= nanoseconds < 10**9):\n            raise ValueError(\n                \"nanoseconds must be a non-negative integer less than 999999999.\"\n            )\n        self.seconds = seconds\n        self.nanoseconds = nanoseconds\n\n    def __repr__(self):\n        \"\"\"String representation of Timestamp.\"\"\"\n        return \"Timestamp(seconds={0}, nanoseconds={1})\".format(\n            self.seconds, self.nanoseconds\n        )\n\n    def __eq__(self, other):\n        \"\"\"Check for equality with another Timestamp object\"\"\"\n        if type(other) is self.__class__:\n            return (\n                self.seconds == other.seconds and self.nanoseconds == other.nanoseconds\n            )\n        return False\n\n    def __ne__(self, other):\n        \"\"\"not-equals method (see :func:`__eq__()`)\"\"\"\n        return not self.__eq__(other)\n\n    def __hash__(self):\n        return hash((self.seconds, self.nanoseconds))\n\n    @staticmethod\n    def from_bytes(b):\n        \"\"\"Unpack bytes into a `Timestamp` object.\n\n        Used for pure-Python msgpack unpacking.\n\n        :param b: Payload from msgpack ext message with code -1\n        :type b: bytes\n\n        :returns: Timestamp object unpacked from msgpack ext payload\n        :rtype: Timestamp\n        \"\"\"\n        if len(b) == 4:\n            seconds = struct.unpack(\"!L\", b)[0]\n            nanoseconds = 0\n        elif len(b) == 8:\n            data64 = struct.unpack(\"!Q\", b)[0]\n            seconds = data64 & 0x00000003FFFFFFFF\n            nanoseconds = data64 >> 34\n        elif len(b) == 12:\n            nanoseconds, seconds = struct.unpack(\"!Iq\", b)\n        else:\n            raise ValueError(\n                \"Timestamp type can only be created from 32, 64, or 96-bit byte objects\"\n            )\n        return Timestamp(seconds, nanoseconds)\n\n    def to_bytes(self):\n        \"\"\"Pack this Timestamp object into bytes.\n\n        Used for pure-Python msgpack packing.\n\n        :returns data: Payload for EXT message with code -1 (timestamp type)\n        :rtype: bytes\n        \"\"\"\n        if (self.seconds >> 34) == 0:  # seconds is non-negative and fits in 34 bits\n            data64 = self.nanoseconds << 34 | self.seconds\n            if data64 & 0xFFFFFFFF00000000 == 0:\n                # nanoseconds is zero and seconds < 2**32, so timestamp 32\n                data = struct.pack(\"!L\", data64)\n            else:\n                # timestamp 64\n                data = struct.pack(\"!Q\", data64)\n        else:\n            # timestamp 96\n            data = struct.pack(\"!Iq\", self.nanoseconds, self.seconds)\n        return data\n\n    @staticmethod\n    def from_unix(unix_sec):\n        \"\"\"Create a Timestamp from posix timestamp in seconds.\n\n        :param unix_float: Posix timestamp in seconds.\n        :type unix_float: int or float.\n        \"\"\"\n        seconds = int(unix_sec // 1)\n        nanoseconds = int((unix_sec % 1) * 10**9)\n        return Timestamp(seconds, nanoseconds)\n\n    def to_unix(self):\n        \"\"\"Get the timestamp as a floating-point value.\n\n        :returns: posix timestamp\n        :rtype: float\n        \"\"\"\n        return self.seconds + self.nanoseconds / 1e9\n\n    @staticmethod\n    def from_unix_nano(unix_ns):\n        \"\"\"Create a Timestamp from posix timestamp in nanoseconds.\n\n        :param int unix_ns: Posix timestamp in nanoseconds.\n        :rtype: Timestamp\n        \"\"\"\n        return Timestamp(*divmod(unix_ns, 10**9))\n\n    def to_unix_nano(self):\n        \"\"\"Get the timestamp as a unixtime in nanoseconds.\n\n        :returns: posix timestamp in nanoseconds\n        :rtype: int\n        \"\"\"\n        return self.seconds * 10**9 + self.nanoseconds\n\n    def to_datetime(self):\n        \"\"\"Get the timestamp as a UTC datetime.\n\n        Python 2 is not supported.\n\n        :rtype: datetime.\n        \"\"\"\n        return datetime.datetime.fromtimestamp(0, _utc) + datetime.timedelta(\n            seconds=self.to_unix()\n        )\n\n    @staticmethod\n    def from_datetime(dt):\n        \"\"\"Create a Timestamp from datetime with tzinfo.\n\n        Python 2 is not supported.\n\n        :rtype: Timestamp\n        \"\"\"\n        return Timestamp.from_unix(dt.timestamp())\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py",
    "content": "\"\"\"Fallback pure Python implementation of msgpack\"\"\"\nfrom datetime import datetime as _DateTime\nimport sys\nimport struct\n\n\nPY2 = sys.version_info[0] == 2\nif PY2:\n    int_types = (int, long)\n\n    def dict_iteritems(d):\n        return d.iteritems()\n\nelse:\n    int_types = int\n    unicode = str\n    xrange = range\n\n    def dict_iteritems(d):\n        return d.items()\n\n\nif sys.version_info < (3, 5):\n    # Ugly hack...\n    RecursionError = RuntimeError\n\n    def _is_recursionerror(e):\n        return (\n            len(e.args) == 1\n            and isinstance(e.args[0], str)\n            and e.args[0].startswith(\"maximum recursion depth exceeded\")\n        )\n\nelse:\n\n    def _is_recursionerror(e):\n        return True\n\n\nif hasattr(sys, \"pypy_version_info\"):\n    # StringIO is slow on PyPy, StringIO is faster.  However: PyPy's own\n    # StringBuilder is fastest.\n    from __pypy__ import newlist_hint\n\n    try:\n        from __pypy__.builders import BytesBuilder as StringBuilder\n    except ImportError:\n        from __pypy__.builders import StringBuilder\n    USING_STRINGBUILDER = True\n\n    class StringIO(object):\n        def __init__(self, s=b\"\"):\n            if s:\n                self.builder = StringBuilder(len(s))\n                self.builder.append(s)\n            else:\n                self.builder = StringBuilder()\n\n        def write(self, s):\n            if isinstance(s, memoryview):\n                s = s.tobytes()\n            elif isinstance(s, bytearray):\n                s = bytes(s)\n            self.builder.append(s)\n\n        def getvalue(self):\n            return self.builder.build()\n\nelse:\n    USING_STRINGBUILDER = False\n    from io import BytesIO as StringIO\n\n    newlist_hint = lambda size: []\n\n\nfrom .exceptions import BufferFull, OutOfData, ExtraData, FormatError, StackError\n\nfrom .ext import ExtType, Timestamp\n\n\nEX_SKIP = 0\nEX_CONSTRUCT = 1\nEX_READ_ARRAY_HEADER = 2\nEX_READ_MAP_HEADER = 3\n\nTYPE_IMMEDIATE = 0\nTYPE_ARRAY = 1\nTYPE_MAP = 2\nTYPE_RAW = 3\nTYPE_BIN = 4\nTYPE_EXT = 5\n\nDEFAULT_RECURSE_LIMIT = 511\n\n\ndef _check_type_strict(obj, t, type=type, tuple=tuple):\n    if type(t) is tuple:\n        return type(obj) in t\n    else:\n        return type(obj) is t\n\n\ndef _get_data_from_buffer(obj):\n    view = memoryview(obj)\n    if view.itemsize != 1:\n        raise ValueError(\"cannot unpack from multi-byte object\")\n    return view\n\n\ndef unpackb(packed, **kwargs):\n    \"\"\"\n    Unpack an object from `packed`.\n\n    Raises ``ExtraData`` when *packed* contains extra bytes.\n    Raises ``ValueError`` when *packed* is incomplete.\n    Raises ``FormatError`` when *packed* is not valid msgpack.\n    Raises ``StackError`` when *packed* contains too nested.\n    Other exceptions can be raised during unpacking.\n\n    See :class:`Unpacker` for options.\n    \"\"\"\n    unpacker = Unpacker(None, max_buffer_size=len(packed), **kwargs)\n    unpacker.feed(packed)\n    try:\n        ret = unpacker._unpack()\n    except OutOfData:\n        raise ValueError(\"Unpack failed: incomplete input\")\n    except RecursionError as e:\n        if _is_recursionerror(e):\n            raise StackError\n        raise\n    if unpacker._got_extradata():\n        raise ExtraData(ret, unpacker._get_extradata())\n    return ret\n\n\nif sys.version_info < (2, 7, 6):\n\n    def _unpack_from(f, b, o=0):\n        \"\"\"Explicit type cast for legacy struct.unpack_from\"\"\"\n        return struct.unpack_from(f, bytes(b), o)\n\nelse:\n    _unpack_from = struct.unpack_from\n\n_NO_FORMAT_USED = \"\"\n_MSGPACK_HEADERS = {\n    0xC4: (1, _NO_FORMAT_USED, TYPE_BIN),\n    0xC5: (2, \">H\", TYPE_BIN),\n    0xC6: (4, \">I\", TYPE_BIN),\n    0xC7: (2, \"Bb\", TYPE_EXT),\n    0xC8: (3, \">Hb\", TYPE_EXT),\n    0xC9: (5, \">Ib\", TYPE_EXT),\n    0xCA: (4, \">f\"),\n    0xCB: (8, \">d\"),\n    0xCC: (1, _NO_FORMAT_USED),\n    0xCD: (2, \">H\"),\n    0xCE: (4, \">I\"),\n    0xCF: (8, \">Q\"),\n    0xD0: (1, \"b\"),\n    0xD1: (2, \">h\"),\n    0xD2: (4, \">i\"),\n    0xD3: (8, \">q\"),\n    0xD4: (1, \"b1s\", TYPE_EXT),\n    0xD5: (2, \"b2s\", TYPE_EXT),\n    0xD6: (4, \"b4s\", TYPE_EXT),\n    0xD7: (8, \"b8s\", TYPE_EXT),\n    0xD8: (16, \"b16s\", TYPE_EXT),\n    0xD9: (1, _NO_FORMAT_USED, TYPE_RAW),\n    0xDA: (2, \">H\", TYPE_RAW),\n    0xDB: (4, \">I\", TYPE_RAW),\n    0xDC: (2, \">H\", TYPE_ARRAY),\n    0xDD: (4, \">I\", TYPE_ARRAY),\n    0xDE: (2, \">H\", TYPE_MAP),\n    0xDF: (4, \">I\", TYPE_MAP),\n}\n\n\nclass Unpacker(object):\n    \"\"\"Streaming unpacker.\n\n    Arguments:\n\n    :param file_like:\n        File-like object having `.read(n)` method.\n        If specified, unpacker reads serialized data from it and :meth:`feed()` is not usable.\n\n    :param int read_size:\n        Used as `file_like.read(read_size)`. (default: `min(16*1024, max_buffer_size)`)\n\n    :param bool use_list:\n        If true, unpack msgpack array to Python list.\n        Otherwise, unpack to Python tuple. (default: True)\n\n    :param bool raw:\n        If true, unpack msgpack raw to Python bytes.\n        Otherwise, unpack to Python str by decoding with UTF-8 encoding (default).\n\n    :param int timestamp:\n        Control how timestamp type is unpacked:\n\n            0 - Timestamp\n            1 - float  (Seconds from the EPOCH)\n            2 - int  (Nanoseconds from the EPOCH)\n            3 - datetime.datetime  (UTC).  Python 2 is not supported.\n\n    :param bool strict_map_key:\n        If true (default), only str or bytes are accepted for map (dict) keys.\n\n    :param callable object_hook:\n        When specified, it should be callable.\n        Unpacker calls it with a dict argument after unpacking msgpack map.\n        (See also simplejson)\n\n    :param callable object_pairs_hook:\n        When specified, it should be callable.\n        Unpacker calls it with a list of key-value pairs after unpacking msgpack map.\n        (See also simplejson)\n\n    :param str unicode_errors:\n        The error handler for decoding unicode. (default: 'strict')\n        This option should be used only when you have msgpack data which\n        contains invalid UTF-8 string.\n\n    :param int max_buffer_size:\n        Limits size of data waiting unpacked.  0 means 2**32-1.\n        The default value is 100*1024*1024 (100MiB).\n        Raises `BufferFull` exception when it is insufficient.\n        You should set this parameter when unpacking data from untrusted source.\n\n    :param int max_str_len:\n        Deprecated, use *max_buffer_size* instead.\n        Limits max length of str. (default: max_buffer_size)\n\n    :param int max_bin_len:\n        Deprecated, use *max_buffer_size* instead.\n        Limits max length of bin. (default: max_buffer_size)\n\n    :param int max_array_len:\n        Limits max length of array.\n        (default: max_buffer_size)\n\n    :param int max_map_len:\n        Limits max length of map.\n        (default: max_buffer_size//2)\n\n    :param int max_ext_len:\n        Deprecated, use *max_buffer_size* instead.\n        Limits max size of ext type.  (default: max_buffer_size)\n\n    Example of streaming deserialize from file-like object::\n\n        unpacker = Unpacker(file_like)\n        for o in unpacker:\n            process(o)\n\n    Example of streaming deserialize from socket::\n\n        unpacker = Unpacker()\n        while True:\n            buf = sock.recv(1024**2)\n            if not buf:\n                break\n            unpacker.feed(buf)\n            for o in unpacker:\n                process(o)\n\n    Raises ``ExtraData`` when *packed* contains extra bytes.\n    Raises ``OutOfData`` when *packed* is incomplete.\n    Raises ``FormatError`` when *packed* is not valid msgpack.\n    Raises ``StackError`` when *packed* contains too nested.\n    Other exceptions can be raised during unpacking.\n    \"\"\"\n\n    def __init__(\n        self,\n        file_like=None,\n        read_size=0,\n        use_list=True,\n        raw=False,\n        timestamp=0,\n        strict_map_key=True,\n        object_hook=None,\n        object_pairs_hook=None,\n        list_hook=None,\n        unicode_errors=None,\n        max_buffer_size=100 * 1024 * 1024,\n        ext_hook=ExtType,\n        max_str_len=-1,\n        max_bin_len=-1,\n        max_array_len=-1,\n        max_map_len=-1,\n        max_ext_len=-1,\n    ):\n        if unicode_errors is None:\n            unicode_errors = \"strict\"\n\n        if file_like is None:\n            self._feeding = True\n        else:\n            if not callable(file_like.read):\n                raise TypeError(\"`file_like.read` must be callable\")\n            self.file_like = file_like\n            self._feeding = False\n\n        #: array of bytes fed.\n        self._buffer = bytearray()\n        #: Which position we currently reads\n        self._buff_i = 0\n\n        # When Unpacker is used as an iterable, between the calls to next(),\n        # the buffer is not \"consumed\" completely, for efficiency sake.\n        # Instead, it is done sloppily.  To make sure we raise BufferFull at\n        # the correct moments, we have to keep track of how sloppy we were.\n        # Furthermore, when the buffer is incomplete (that is: in the case\n        # we raise an OutOfData) we need to rollback the buffer to the correct\n        # state, which _buf_checkpoint records.\n        self._buf_checkpoint = 0\n\n        if not max_buffer_size:\n            max_buffer_size = 2**31 - 1\n        if max_str_len == -1:\n            max_str_len = max_buffer_size\n        if max_bin_len == -1:\n            max_bin_len = max_buffer_size\n        if max_array_len == -1:\n            max_array_len = max_buffer_size\n        if max_map_len == -1:\n            max_map_len = max_buffer_size // 2\n        if max_ext_len == -1:\n            max_ext_len = max_buffer_size\n\n        self._max_buffer_size = max_buffer_size\n        if read_size > self._max_buffer_size:\n            raise ValueError(\"read_size must be smaller than max_buffer_size\")\n        self._read_size = read_size or min(self._max_buffer_size, 16 * 1024)\n        self._raw = bool(raw)\n        self._strict_map_key = bool(strict_map_key)\n        self._unicode_errors = unicode_errors\n        self._use_list = use_list\n        if not (0 <= timestamp <= 3):\n            raise ValueError(\"timestamp must be 0..3\")\n        self._timestamp = timestamp\n        self._list_hook = list_hook\n        self._object_hook = object_hook\n        self._object_pairs_hook = object_pairs_hook\n        self._ext_hook = ext_hook\n        self._max_str_len = max_str_len\n        self._max_bin_len = max_bin_len\n        self._max_array_len = max_array_len\n        self._max_map_len = max_map_len\n        self._max_ext_len = max_ext_len\n        self._stream_offset = 0\n\n        if list_hook is not None and not callable(list_hook):\n            raise TypeError(\"`list_hook` is not callable\")\n        if object_hook is not None and not callable(object_hook):\n            raise TypeError(\"`object_hook` is not callable\")\n        if object_pairs_hook is not None and not callable(object_pairs_hook):\n            raise TypeError(\"`object_pairs_hook` is not callable\")\n        if object_hook is not None and object_pairs_hook is not None:\n            raise TypeError(\n                \"object_pairs_hook and object_hook are mutually \" \"exclusive\"\n            )\n        if not callable(ext_hook):\n            raise TypeError(\"`ext_hook` is not callable\")\n\n    def feed(self, next_bytes):\n        assert self._feeding\n        view = _get_data_from_buffer(next_bytes)\n        if len(self._buffer) - self._buff_i + len(view) > self._max_buffer_size:\n            raise BufferFull\n\n        # Strip buffer before checkpoint before reading file.\n        if self._buf_checkpoint > 0:\n            del self._buffer[: self._buf_checkpoint]\n            self._buff_i -= self._buf_checkpoint\n            self._buf_checkpoint = 0\n\n        # Use extend here: INPLACE_ADD += doesn't reliably typecast memoryview in jython\n        self._buffer.extend(view)\n\n    def _consume(self):\n        \"\"\"Gets rid of the used parts of the buffer.\"\"\"\n        self._stream_offset += self._buff_i - self._buf_checkpoint\n        self._buf_checkpoint = self._buff_i\n\n    def _got_extradata(self):\n        return self._buff_i < len(self._buffer)\n\n    def _get_extradata(self):\n        return self._buffer[self._buff_i :]\n\n    def read_bytes(self, n):\n        ret = self._read(n, raise_outofdata=False)\n        self._consume()\n        return ret\n\n    def _read(self, n, raise_outofdata=True):\n        # (int) -> bytearray\n        self._reserve(n, raise_outofdata=raise_outofdata)\n        i = self._buff_i\n        ret = self._buffer[i : i + n]\n        self._buff_i = i + len(ret)\n        return ret\n\n    def _reserve(self, n, raise_outofdata=True):\n        remain_bytes = len(self._buffer) - self._buff_i - n\n\n        # Fast path: buffer has n bytes already\n        if remain_bytes >= 0:\n            return\n\n        if self._feeding:\n            self._buff_i = self._buf_checkpoint\n            raise OutOfData\n\n        # Strip buffer before checkpoint before reading file.\n        if self._buf_checkpoint > 0:\n            del self._buffer[: self._buf_checkpoint]\n            self._buff_i -= self._buf_checkpoint\n            self._buf_checkpoint = 0\n\n        # Read from file\n        remain_bytes = -remain_bytes\n        if remain_bytes + len(self._buffer) > self._max_buffer_size:\n            raise BufferFull\n        while remain_bytes > 0:\n            to_read_bytes = max(self._read_size, remain_bytes)\n            read_data = self.file_like.read(to_read_bytes)\n            if not read_data:\n                break\n            assert isinstance(read_data, bytes)\n            self._buffer += read_data\n            remain_bytes -= len(read_data)\n\n        if len(self._buffer) < n + self._buff_i and raise_outofdata:\n            self._buff_i = 0  # rollback\n            raise OutOfData\n\n    def _read_header(self):\n        typ = TYPE_IMMEDIATE\n        n = 0\n        obj = None\n        self._reserve(1)\n        b = self._buffer[self._buff_i]\n        self._buff_i += 1\n        if b & 0b10000000 == 0:\n            obj = b\n        elif b & 0b11100000 == 0b11100000:\n            obj = -1 - (b ^ 0xFF)\n        elif b & 0b11100000 == 0b10100000:\n            n = b & 0b00011111\n            typ = TYPE_RAW\n            if n > self._max_str_len:\n                raise ValueError(\"%s exceeds max_str_len(%s)\" % (n, self._max_str_len))\n            obj = self._read(n)\n        elif b & 0b11110000 == 0b10010000:\n            n = b & 0b00001111\n            typ = TYPE_ARRAY\n            if n > self._max_array_len:\n                raise ValueError(\n                    \"%s exceeds max_array_len(%s)\" % (n, self._max_array_len)\n                )\n        elif b & 0b11110000 == 0b10000000:\n            n = b & 0b00001111\n            typ = TYPE_MAP\n            if n > self._max_map_len:\n                raise ValueError(\"%s exceeds max_map_len(%s)\" % (n, self._max_map_len))\n        elif b == 0xC0:\n            obj = None\n        elif b == 0xC2:\n            obj = False\n        elif b == 0xC3:\n            obj = True\n        elif 0xC4 <= b <= 0xC6:\n            size, fmt, typ = _MSGPACK_HEADERS[b]\n            self._reserve(size)\n            if len(fmt) > 0:\n                n = _unpack_from(fmt, self._buffer, self._buff_i)[0]\n            else:\n                n = self._buffer[self._buff_i]\n            self._buff_i += size\n            if n > self._max_bin_len:\n                raise ValueError(\"%s exceeds max_bin_len(%s)\" % (n, self._max_bin_len))\n            obj = self._read(n)\n        elif 0xC7 <= b <= 0xC9:\n            size, fmt, typ = _MSGPACK_HEADERS[b]\n            self._reserve(size)\n            L, n = _unpack_from(fmt, self._buffer, self._buff_i)\n            self._buff_i += size\n            if L > self._max_ext_len:\n                raise ValueError(\"%s exceeds max_ext_len(%s)\" % (L, self._max_ext_len))\n            obj = self._read(L)\n        elif 0xCA <= b <= 0xD3:\n            size, fmt = _MSGPACK_HEADERS[b]\n            self._reserve(size)\n            if len(fmt) > 0:\n                obj = _unpack_from(fmt, self._buffer, self._buff_i)[0]\n            else:\n                obj = self._buffer[self._buff_i]\n            self._buff_i += size\n        elif 0xD4 <= b <= 0xD8:\n            size, fmt, typ = _MSGPACK_HEADERS[b]\n            if self._max_ext_len < size:\n                raise ValueError(\n                    \"%s exceeds max_ext_len(%s)\" % (size, self._max_ext_len)\n                )\n            self._reserve(size + 1)\n            n, obj = _unpack_from(fmt, self._buffer, self._buff_i)\n            self._buff_i += size + 1\n        elif 0xD9 <= b <= 0xDB:\n            size, fmt, typ = _MSGPACK_HEADERS[b]\n            self._reserve(size)\n            if len(fmt) > 0:\n                (n,) = _unpack_from(fmt, self._buffer, self._buff_i)\n            else:\n                n = self._buffer[self._buff_i]\n            self._buff_i += size\n            if n > self._max_str_len:\n                raise ValueError(\"%s exceeds max_str_len(%s)\" % (n, self._max_str_len))\n            obj = self._read(n)\n        elif 0xDC <= b <= 0xDD:\n            size, fmt, typ = _MSGPACK_HEADERS[b]\n            self._reserve(size)\n            (n,) = _unpack_from(fmt, self._buffer, self._buff_i)\n            self._buff_i += size\n            if n > self._max_array_len:\n                raise ValueError(\n                    \"%s exceeds max_array_len(%s)\" % (n, self._max_array_len)\n                )\n        elif 0xDE <= b <= 0xDF:\n            size, fmt, typ = _MSGPACK_HEADERS[b]\n            self._reserve(size)\n            (n,) = _unpack_from(fmt, self._buffer, self._buff_i)\n            self._buff_i += size\n            if n > self._max_map_len:\n                raise ValueError(\"%s exceeds max_map_len(%s)\" % (n, self._max_map_len))\n        else:\n            raise FormatError(\"Unknown header: 0x%x\" % b)\n        return typ, n, obj\n\n    def _unpack(self, execute=EX_CONSTRUCT):\n        typ, n, obj = self._read_header()\n\n        if execute == EX_READ_ARRAY_HEADER:\n            if typ != TYPE_ARRAY:\n                raise ValueError(\"Expected array\")\n            return n\n        if execute == EX_READ_MAP_HEADER:\n            if typ != TYPE_MAP:\n                raise ValueError(\"Expected map\")\n            return n\n        # TODO should we eliminate the recursion?\n        if typ == TYPE_ARRAY:\n            if execute == EX_SKIP:\n                for i in xrange(n):\n                    # TODO check whether we need to call `list_hook`\n                    self._unpack(EX_SKIP)\n                return\n            ret = newlist_hint(n)\n            for i in xrange(n):\n                ret.append(self._unpack(EX_CONSTRUCT))\n            if self._list_hook is not None:\n                ret = self._list_hook(ret)\n            # TODO is the interaction between `list_hook` and `use_list` ok?\n            return ret if self._use_list else tuple(ret)\n        if typ == TYPE_MAP:\n            if execute == EX_SKIP:\n                for i in xrange(n):\n                    # TODO check whether we need to call hooks\n                    self._unpack(EX_SKIP)\n                    self._unpack(EX_SKIP)\n                return\n            if self._object_pairs_hook is not None:\n                ret = self._object_pairs_hook(\n                    (self._unpack(EX_CONSTRUCT), self._unpack(EX_CONSTRUCT))\n                    for _ in xrange(n)\n                )\n            else:\n                ret = {}\n                for _ in xrange(n):\n                    key = self._unpack(EX_CONSTRUCT)\n                    if self._strict_map_key and type(key) not in (unicode, bytes):\n                        raise ValueError(\n                            \"%s is not allowed for map key\" % str(type(key))\n                        )\n                    if not PY2 and type(key) is str:\n                        key = sys.intern(key)\n                    ret[key] = self._unpack(EX_CONSTRUCT)\n                if self._object_hook is not None:\n                    ret = self._object_hook(ret)\n            return ret\n        if execute == EX_SKIP:\n            return\n        if typ == TYPE_RAW:\n            if self._raw:\n                obj = bytes(obj)\n            else:\n                obj = obj.decode(\"utf_8\", self._unicode_errors)\n            return obj\n        if typ == TYPE_BIN:\n            return bytes(obj)\n        if typ == TYPE_EXT:\n            if n == -1:  # timestamp\n                ts = Timestamp.from_bytes(bytes(obj))\n                if self._timestamp == 1:\n                    return ts.to_unix()\n                elif self._timestamp == 2:\n                    return ts.to_unix_nano()\n                elif self._timestamp == 3:\n                    return ts.to_datetime()\n                else:\n                    return ts\n            else:\n                return self._ext_hook(n, bytes(obj))\n        assert typ == TYPE_IMMEDIATE\n        return obj\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        try:\n            ret = self._unpack(EX_CONSTRUCT)\n            self._consume()\n            return ret\n        except OutOfData:\n            self._consume()\n            raise StopIteration\n        except RecursionError:\n            raise StackError\n\n    next = __next__\n\n    def skip(self):\n        self._unpack(EX_SKIP)\n        self._consume()\n\n    def unpack(self):\n        try:\n            ret = self._unpack(EX_CONSTRUCT)\n        except RecursionError:\n            raise StackError\n        self._consume()\n        return ret\n\n    def read_array_header(self):\n        ret = self._unpack(EX_READ_ARRAY_HEADER)\n        self._consume()\n        return ret\n\n    def read_map_header(self):\n        ret = self._unpack(EX_READ_MAP_HEADER)\n        self._consume()\n        return ret\n\n    def tell(self):\n        return self._stream_offset\n\n\nclass Packer(object):\n    \"\"\"\n    MessagePack Packer\n\n    Usage::\n\n        packer = Packer()\n        astream.write(packer.pack(a))\n        astream.write(packer.pack(b))\n\n    Packer's constructor has some keyword arguments:\n\n    :param callable default:\n        Convert user type to builtin type that Packer supports.\n        See also simplejson's document.\n\n    :param bool use_single_float:\n        Use single precision float type for float. (default: False)\n\n    :param bool autoreset:\n        Reset buffer after each pack and return its content as `bytes`. (default: True).\n        If set this to false, use `bytes()` to get content and `.reset()` to clear buffer.\n\n    :param bool use_bin_type:\n        Use bin type introduced in msgpack spec 2.0 for bytes.\n        It also enables str8 type for unicode. (default: True)\n\n    :param bool strict_types:\n        If set to true, types will be checked to be exact. Derived classes\n        from serializable types will not be serialized and will be\n        treated as unsupported type and forwarded to default.\n        Additionally tuples will not be serialized as lists.\n        This is useful when trying to implement accurate serialization\n        for python types.\n\n    :param bool datetime:\n        If set to true, datetime with tzinfo is packed into Timestamp type.\n        Note that the tzinfo is stripped in the timestamp.\n        You can get UTC datetime with `timestamp=3` option of the Unpacker.\n        (Python 2 is not supported).\n\n    :param str unicode_errors:\n        The error handler for encoding unicode. (default: 'strict')\n        DO NOT USE THIS!!  This option is kept for very specific usage.\n\n    Example of streaming deserialize from file-like object::\n\n        unpacker = Unpacker(file_like)\n        for o in unpacker:\n            process(o)\n\n    Example of streaming deserialize from socket::\n\n        unpacker = Unpacker()\n        while True:\n            buf = sock.recv(1024**2)\n            if not buf:\n                break\n            unpacker.feed(buf)\n            for o in unpacker:\n                process(o)\n\n    Raises ``ExtraData`` when *packed* contains extra bytes.\n    Raises ``OutOfData`` when *packed* is incomplete.\n    Raises ``FormatError`` when *packed* is not valid msgpack.\n    Raises ``StackError`` when *packed* contains too nested.\n    Other exceptions can be raised during unpacking.\n    \"\"\"\n\n    def __init__(\n        self,\n        default=None,\n        use_single_float=False,\n        autoreset=True,\n        use_bin_type=True,\n        strict_types=False,\n        datetime=False,\n        unicode_errors=None,\n    ):\n        self._strict_types = strict_types\n        self._use_float = use_single_float\n        self._autoreset = autoreset\n        self._use_bin_type = use_bin_type\n        self._buffer = StringIO()\n        if PY2 and datetime:\n            raise ValueError(\"datetime is not supported in Python 2\")\n        self._datetime = bool(datetime)\n        self._unicode_errors = unicode_errors or \"strict\"\n        if default is not None:\n            if not callable(default):\n                raise TypeError(\"default must be callable\")\n        self._default = default\n\n    def _pack(\n        self,\n        obj,\n        nest_limit=DEFAULT_RECURSE_LIMIT,\n        check=isinstance,\n        check_type_strict=_check_type_strict,\n    ):\n        default_used = False\n        if self._strict_types:\n            check = check_type_strict\n            list_types = list\n        else:\n            list_types = (list, tuple)\n        while True:\n            if nest_limit < 0:\n                raise ValueError(\"recursion limit exceeded\")\n            if obj is None:\n                return self._buffer.write(b\"\\xc0\")\n            if check(obj, bool):\n                if obj:\n                    return self._buffer.write(b\"\\xc3\")\n                return self._buffer.write(b\"\\xc2\")\n            if check(obj, int_types):\n                if 0 <= obj < 0x80:\n                    return self._buffer.write(struct.pack(\"B\", obj))\n                if -0x20 <= obj < 0:\n                    return self._buffer.write(struct.pack(\"b\", obj))\n                if 0x80 <= obj <= 0xFF:\n                    return self._buffer.write(struct.pack(\"BB\", 0xCC, obj))\n                if -0x80 <= obj < 0:\n                    return self._buffer.write(struct.pack(\">Bb\", 0xD0, obj))\n                if 0xFF < obj <= 0xFFFF:\n                    return self._buffer.write(struct.pack(\">BH\", 0xCD, obj))\n                if -0x8000 <= obj < -0x80:\n                    return self._buffer.write(struct.pack(\">Bh\", 0xD1, obj))\n                if 0xFFFF < obj <= 0xFFFFFFFF:\n                    return self._buffer.write(struct.pack(\">BI\", 0xCE, obj))\n                if -0x80000000 <= obj < -0x8000:\n                    return self._buffer.write(struct.pack(\">Bi\", 0xD2, obj))\n                if 0xFFFFFFFF < obj <= 0xFFFFFFFFFFFFFFFF:\n                    return self._buffer.write(struct.pack(\">BQ\", 0xCF, obj))\n                if -0x8000000000000000 <= obj < -0x80000000:\n                    return self._buffer.write(struct.pack(\">Bq\", 0xD3, obj))\n                if not default_used and self._default is not None:\n                    obj = self._default(obj)\n                    default_used = True\n                    continue\n                raise OverflowError(\"Integer value out of range\")\n            if check(obj, (bytes, bytearray)):\n                n = len(obj)\n                if n >= 2**32:\n                    raise ValueError(\"%s is too large\" % type(obj).__name__)\n                self._pack_bin_header(n)\n                return self._buffer.write(obj)\n            if check(obj, unicode):\n                obj = obj.encode(\"utf-8\", self._unicode_errors)\n                n = len(obj)\n                if n >= 2**32:\n                    raise ValueError(\"String is too large\")\n                self._pack_raw_header(n)\n                return self._buffer.write(obj)\n            if check(obj, memoryview):\n                n = len(obj) * obj.itemsize\n                if n >= 2**32:\n                    raise ValueError(\"Memoryview is too large\")\n                self._pack_bin_header(n)\n                return self._buffer.write(obj)\n            if check(obj, float):\n                if self._use_float:\n                    return self._buffer.write(struct.pack(\">Bf\", 0xCA, obj))\n                return self._buffer.write(struct.pack(\">Bd\", 0xCB, obj))\n            if check(obj, (ExtType, Timestamp)):\n                if check(obj, Timestamp):\n                    code = -1\n                    data = obj.to_bytes()\n                else:\n                    code = obj.code\n                    data = obj.data\n                assert isinstance(code, int)\n                assert isinstance(data, bytes)\n                L = len(data)\n                if L == 1:\n                    self._buffer.write(b\"\\xd4\")\n                elif L == 2:\n                    self._buffer.write(b\"\\xd5\")\n                elif L == 4:\n                    self._buffer.write(b\"\\xd6\")\n                elif L == 8:\n                    self._buffer.write(b\"\\xd7\")\n                elif L == 16:\n                    self._buffer.write(b\"\\xd8\")\n                elif L <= 0xFF:\n                    self._buffer.write(struct.pack(\">BB\", 0xC7, L))\n                elif L <= 0xFFFF:\n                    self._buffer.write(struct.pack(\">BH\", 0xC8, L))\n                else:\n                    self._buffer.write(struct.pack(\">BI\", 0xC9, L))\n                self._buffer.write(struct.pack(\"b\", code))\n                self._buffer.write(data)\n                return\n            if check(obj, list_types):\n                n = len(obj)\n                self._pack_array_header(n)\n                for i in xrange(n):\n                    self._pack(obj[i], nest_limit - 1)\n                return\n            if check(obj, dict):\n                return self._pack_map_pairs(\n                    len(obj), dict_iteritems(obj), nest_limit - 1\n                )\n\n            if self._datetime and check(obj, _DateTime) and obj.tzinfo is not None:\n                obj = Timestamp.from_datetime(obj)\n                default_used = 1\n                continue\n\n            if not default_used and self._default is not None:\n                obj = self._default(obj)\n                default_used = 1\n                continue\n\n            if self._datetime and check(obj, _DateTime):\n                raise ValueError(\"Cannot serialize %r where tzinfo=None\" % (obj,))\n\n            raise TypeError(\"Cannot serialize %r\" % (obj,))\n\n    def pack(self, obj):\n        try:\n            self._pack(obj)\n        except:\n            self._buffer = StringIO()  # force reset\n            raise\n        if self._autoreset:\n            ret = self._buffer.getvalue()\n            self._buffer = StringIO()\n            return ret\n\n    def pack_map_pairs(self, pairs):\n        self._pack_map_pairs(len(pairs), pairs)\n        if self._autoreset:\n            ret = self._buffer.getvalue()\n            self._buffer = StringIO()\n            return ret\n\n    def pack_array_header(self, n):\n        if n >= 2**32:\n            raise ValueError\n        self._pack_array_header(n)\n        if self._autoreset:\n            ret = self._buffer.getvalue()\n            self._buffer = StringIO()\n            return ret\n\n    def pack_map_header(self, n):\n        if n >= 2**32:\n            raise ValueError\n        self._pack_map_header(n)\n        if self._autoreset:\n            ret = self._buffer.getvalue()\n            self._buffer = StringIO()\n            return ret\n\n    def pack_ext_type(self, typecode, data):\n        if not isinstance(typecode, int):\n            raise TypeError(\"typecode must have int type.\")\n        if not 0 <= typecode <= 127:\n            raise ValueError(\"typecode should be 0-127\")\n        if not isinstance(data, bytes):\n            raise TypeError(\"data must have bytes type\")\n        L = len(data)\n        if L > 0xFFFFFFFF:\n            raise ValueError(\"Too large data\")\n        if L == 1:\n            self._buffer.write(b\"\\xd4\")\n        elif L == 2:\n            self._buffer.write(b\"\\xd5\")\n        elif L == 4:\n            self._buffer.write(b\"\\xd6\")\n        elif L == 8:\n            self._buffer.write(b\"\\xd7\")\n        elif L == 16:\n            self._buffer.write(b\"\\xd8\")\n        elif L <= 0xFF:\n            self._buffer.write(b\"\\xc7\" + struct.pack(\"B\", L))\n        elif L <= 0xFFFF:\n            self._buffer.write(b\"\\xc8\" + struct.pack(\">H\", L))\n        else:\n            self._buffer.write(b\"\\xc9\" + struct.pack(\">I\", L))\n        self._buffer.write(struct.pack(\"B\", typecode))\n        self._buffer.write(data)\n\n    def _pack_array_header(self, n):\n        if n <= 0x0F:\n            return self._buffer.write(struct.pack(\"B\", 0x90 + n))\n        if n <= 0xFFFF:\n            return self._buffer.write(struct.pack(\">BH\", 0xDC, n))\n        if n <= 0xFFFFFFFF:\n            return self._buffer.write(struct.pack(\">BI\", 0xDD, n))\n        raise ValueError(\"Array is too large\")\n\n    def _pack_map_header(self, n):\n        if n <= 0x0F:\n            return self._buffer.write(struct.pack(\"B\", 0x80 + n))\n        if n <= 0xFFFF:\n            return self._buffer.write(struct.pack(\">BH\", 0xDE, n))\n        if n <= 0xFFFFFFFF:\n            return self._buffer.write(struct.pack(\">BI\", 0xDF, n))\n        raise ValueError(\"Dict is too large\")\n\n    def _pack_map_pairs(self, n, pairs, nest_limit=DEFAULT_RECURSE_LIMIT):\n        self._pack_map_header(n)\n        for (k, v) in pairs:\n            self._pack(k, nest_limit - 1)\n            self._pack(v, nest_limit - 1)\n\n    def _pack_raw_header(self, n):\n        if n <= 0x1F:\n            self._buffer.write(struct.pack(\"B\", 0xA0 + n))\n        elif self._use_bin_type and n <= 0xFF:\n            self._buffer.write(struct.pack(\">BB\", 0xD9, n))\n        elif n <= 0xFFFF:\n            self._buffer.write(struct.pack(\">BH\", 0xDA, n))\n        elif n <= 0xFFFFFFFF:\n            self._buffer.write(struct.pack(\">BI\", 0xDB, n))\n        else:\n            raise ValueError(\"Raw is too large\")\n\n    def _pack_bin_header(self, n):\n        if not self._use_bin_type:\n            return self._pack_raw_header(n)\n        elif n <= 0xFF:\n            return self._buffer.write(struct.pack(\">BB\", 0xC4, n))\n        elif n <= 0xFFFF:\n            return self._buffer.write(struct.pack(\">BH\", 0xC5, n))\n        elif n <= 0xFFFFFFFF:\n            return self._buffer.write(struct.pack(\">BI\", 0xC6, n))\n        else:\n            raise ValueError(\"Bin is too large\")\n\n    def bytes(self):\n        \"\"\"Return internal buffer contents as bytes object\"\"\"\n        return self._buffer.getvalue()\n\n    def reset(self):\n        \"\"\"Reset internal buffer.\n\n        This method is useful only when autoreset=False.\n        \"\"\"\n        self._buffer = StringIO()\n\n    def getbuffer(self):\n        \"\"\"Return view of internal buffer.\"\"\"\n        if USING_STRINGBUILDER or PY2:\n            return memoryview(self.bytes())\n        else:\n            return self._buffer.getbuffer()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/packaging/__about__.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\n__all__ = [\n    \"__title__\",\n    \"__summary__\",\n    \"__uri__\",\n    \"__version__\",\n    \"__author__\",\n    \"__email__\",\n    \"__license__\",\n    \"__copyright__\",\n]\n\n__title__ = \"packaging\"\n__summary__ = \"Core utilities for Python packages\"\n__uri__ = \"https://github.com/pypa/packaging\"\n\n__version__ = \"21.3\"\n\n__author__ = \"Donald Stufft and individual contributors\"\n__email__ = \"donald@stufft.io\"\n\n__license__ = \"BSD-2-Clause or Apache-2.0\"\n__copyright__ = \"2014-2019 %s\" % __author__\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/packaging/__init__.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nfrom .__about__ import (\n    __author__,\n    __copyright__,\n    __email__,\n    __license__,\n    __summary__,\n    __title__,\n    __uri__,\n    __version__,\n)\n\n__all__ = [\n    \"__title__\",\n    \"__summary__\",\n    \"__uri__\",\n    \"__version__\",\n    \"__author__\",\n    \"__email__\",\n    \"__license__\",\n    \"__copyright__\",\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/packaging/_manylinux.py",
    "content": "import collections\nimport functools\nimport os\nimport re\nimport struct\nimport sys\nimport warnings\nfrom typing import IO, Dict, Iterator, NamedTuple, Optional, Tuple\n\n\n# Python does not provide platform information at sufficient granularity to\n# identify the architecture of the running executable in some cases, so we\n# determine it dynamically by reading the information from the running\n# process. This only applies on Linux, which uses the ELF format.\nclass _ELFFileHeader:\n    # https://en.wikipedia.org/wiki/Executable_and_Linkable_Format#File_header\n    class _InvalidELFFileHeader(ValueError):\n        \"\"\"\n        An invalid ELF file header was found.\n        \"\"\"\n\n    ELF_MAGIC_NUMBER = 0x7F454C46\n    ELFCLASS32 = 1\n    ELFCLASS64 = 2\n    ELFDATA2LSB = 1\n    ELFDATA2MSB = 2\n    EM_386 = 3\n    EM_S390 = 22\n    EM_ARM = 40\n    EM_X86_64 = 62\n    EF_ARM_ABIMASK = 0xFF000000\n    EF_ARM_ABI_VER5 = 0x05000000\n    EF_ARM_ABI_FLOAT_HARD = 0x00000400\n\n    def __init__(self, file: IO[bytes]) -> None:\n        def unpack(fmt: str) -> int:\n            try:\n                data = file.read(struct.calcsize(fmt))\n                result: Tuple[int, ...] = struct.unpack(fmt, data)\n            except struct.error:\n                raise _ELFFileHeader._InvalidELFFileHeader()\n            return result[0]\n\n        self.e_ident_magic = unpack(\">I\")\n        if self.e_ident_magic != self.ELF_MAGIC_NUMBER:\n            raise _ELFFileHeader._InvalidELFFileHeader()\n        self.e_ident_class = unpack(\"B\")\n        if self.e_ident_class not in {self.ELFCLASS32, self.ELFCLASS64}:\n            raise _ELFFileHeader._InvalidELFFileHeader()\n        self.e_ident_data = unpack(\"B\")\n        if self.e_ident_data not in {self.ELFDATA2LSB, self.ELFDATA2MSB}:\n            raise _ELFFileHeader._InvalidELFFileHeader()\n        self.e_ident_version = unpack(\"B\")\n        self.e_ident_osabi = unpack(\"B\")\n        self.e_ident_abiversion = unpack(\"B\")\n        self.e_ident_pad = file.read(7)\n        format_h = \"<H\" if self.e_ident_data == self.ELFDATA2LSB else \">H\"\n        format_i = \"<I\" if self.e_ident_data == self.ELFDATA2LSB else \">I\"\n        format_q = \"<Q\" if self.e_ident_data == self.ELFDATA2LSB else \">Q\"\n        format_p = format_i if self.e_ident_class == self.ELFCLASS32 else format_q\n        self.e_type = unpack(format_h)\n        self.e_machine = unpack(format_h)\n        self.e_version = unpack(format_i)\n        self.e_entry = unpack(format_p)\n        self.e_phoff = unpack(format_p)\n        self.e_shoff = unpack(format_p)\n        self.e_flags = unpack(format_i)\n        self.e_ehsize = unpack(format_h)\n        self.e_phentsize = unpack(format_h)\n        self.e_phnum = unpack(format_h)\n        self.e_shentsize = unpack(format_h)\n        self.e_shnum = unpack(format_h)\n        self.e_shstrndx = unpack(format_h)\n\n\ndef _get_elf_header() -> Optional[_ELFFileHeader]:\n    try:\n        with open(sys.executable, \"rb\") as f:\n            elf_header = _ELFFileHeader(f)\n    except (OSError, TypeError, _ELFFileHeader._InvalidELFFileHeader):\n        return None\n    return elf_header\n\n\ndef _is_linux_armhf() -> bool:\n    # hard-float ABI can be detected from the ELF header of the running\n    # process\n    # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf\n    elf_header = _get_elf_header()\n    if elf_header is None:\n        return False\n    result = elf_header.e_ident_class == elf_header.ELFCLASS32\n    result &= elf_header.e_ident_data == elf_header.ELFDATA2LSB\n    result &= elf_header.e_machine == elf_header.EM_ARM\n    result &= (\n        elf_header.e_flags & elf_header.EF_ARM_ABIMASK\n    ) == elf_header.EF_ARM_ABI_VER5\n    result &= (\n        elf_header.e_flags & elf_header.EF_ARM_ABI_FLOAT_HARD\n    ) == elf_header.EF_ARM_ABI_FLOAT_HARD\n    return result\n\n\ndef _is_linux_i686() -> bool:\n    elf_header = _get_elf_header()\n    if elf_header is None:\n        return False\n    result = elf_header.e_ident_class == elf_header.ELFCLASS32\n    result &= elf_header.e_ident_data == elf_header.ELFDATA2LSB\n    result &= elf_header.e_machine == elf_header.EM_386\n    return result\n\n\ndef _have_compatible_abi(arch: str) -> bool:\n    if arch == \"armv7l\":\n        return _is_linux_armhf()\n    if arch == \"i686\":\n        return _is_linux_i686()\n    return arch in {\"x86_64\", \"aarch64\", \"ppc64\", \"ppc64le\", \"s390x\"}\n\n\n# If glibc ever changes its major version, we need to know what the last\n# minor version was, so we can build the complete list of all versions.\n# For now, guess what the highest minor version might be, assume it will\n# be 50 for testing. Once this actually happens, update the dictionary\n# with the actual value.\n_LAST_GLIBC_MINOR: Dict[int, int] = collections.defaultdict(lambda: 50)\n\n\nclass _GLibCVersion(NamedTuple):\n    major: int\n    minor: int\n\n\ndef _glibc_version_string_confstr() -> Optional[str]:\n    \"\"\"\n    Primary implementation of glibc_version_string using os.confstr.\n    \"\"\"\n    # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely\n    # to be broken or missing. This strategy is used in the standard library\n    # platform module.\n    # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183\n    try:\n        # os.confstr(\"CS_GNU_LIBC_VERSION\") returns a string like \"glibc 2.17\".\n        version_string = os.confstr(\"CS_GNU_LIBC_VERSION\")\n        assert version_string is not None\n        _, version = version_string.split()\n    except (AssertionError, AttributeError, OSError, ValueError):\n        # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...\n        return None\n    return version\n\n\ndef _glibc_version_string_ctypes() -> Optional[str]:\n    \"\"\"\n    Fallback implementation of glibc_version_string using ctypes.\n    \"\"\"\n    try:\n        import ctypes\n    except ImportError:\n        return None\n\n    # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen\n    # manpage says, \"If filename is NULL, then the returned handle is for the\n    # main program\". This way we can let the linker do the work to figure out\n    # which libc our process is actually using.\n    #\n    # We must also handle the special case where the executable is not a\n    # dynamically linked executable. This can occur when using musl libc,\n    # for example. In this situation, dlopen() will error, leading to an\n    # OSError. Interestingly, at least in the case of musl, there is no\n    # errno set on the OSError. The single string argument used to construct\n    # OSError comes from libc itself and is therefore not portable to\n    # hard code here. In any case, failure to call dlopen() means we\n    # can proceed, so we bail on our attempt.\n    try:\n        process_namespace = ctypes.CDLL(None)\n    except OSError:\n        return None\n\n    try:\n        gnu_get_libc_version = process_namespace.gnu_get_libc_version\n    except AttributeError:\n        # Symbol doesn't exist -> therefore, we are not linked to\n        # glibc.\n        return None\n\n    # Call gnu_get_libc_version, which returns a string like \"2.5\"\n    gnu_get_libc_version.restype = ctypes.c_char_p\n    version_str: str = gnu_get_libc_version()\n    # py2 / py3 compatibility:\n    if not isinstance(version_str, str):\n        version_str = version_str.decode(\"ascii\")\n\n    return version_str\n\n\ndef _glibc_version_string() -> Optional[str]:\n    \"\"\"Returns glibc version string, or None if not using glibc.\"\"\"\n    return _glibc_version_string_confstr() or _glibc_version_string_ctypes()\n\n\ndef _parse_glibc_version(version_str: str) -> Tuple[int, int]:\n    \"\"\"Parse glibc version.\n\n    We use a regexp instead of str.split because we want to discard any\n    random junk that might come after the minor version -- this might happen\n    in patched/forked versions of glibc (e.g. Linaro's version of glibc\n    uses version strings like \"2.20-2014.11\"). See gh-3588.\n    \"\"\"\n    m = re.match(r\"(?P<major>[0-9]+)\\.(?P<minor>[0-9]+)\", version_str)\n    if not m:\n        warnings.warn(\n            \"Expected glibc version with 2 components major.minor,\"\n            \" got: %s\" % version_str,\n            RuntimeWarning,\n        )\n        return -1, -1\n    return int(m.group(\"major\")), int(m.group(\"minor\"))\n\n\n@functools.lru_cache()\ndef _get_glibc_version() -> Tuple[int, int]:\n    version_str = _glibc_version_string()\n    if version_str is None:\n        return (-1, -1)\n    return _parse_glibc_version(version_str)\n\n\n# From PEP 513, PEP 600\ndef _is_compatible(name: str, arch: str, version: _GLibCVersion) -> bool:\n    sys_glibc = _get_glibc_version()\n    if sys_glibc < version:\n        return False\n    # Check for presence of _manylinux module.\n    try:\n        import _manylinux  # noqa\n    except ImportError:\n        return True\n    if hasattr(_manylinux, \"manylinux_compatible\"):\n        result = _manylinux.manylinux_compatible(version[0], version[1], arch)\n        if result is not None:\n            return bool(result)\n        return True\n    if version == _GLibCVersion(2, 5):\n        if hasattr(_manylinux, \"manylinux1_compatible\"):\n            return bool(_manylinux.manylinux1_compatible)\n    if version == _GLibCVersion(2, 12):\n        if hasattr(_manylinux, \"manylinux2010_compatible\"):\n            return bool(_manylinux.manylinux2010_compatible)\n    if version == _GLibCVersion(2, 17):\n        if hasattr(_manylinux, \"manylinux2014_compatible\"):\n            return bool(_manylinux.manylinux2014_compatible)\n    return True\n\n\n_LEGACY_MANYLINUX_MAP = {\n    # CentOS 7 w/ glibc 2.17 (PEP 599)\n    (2, 17): \"manylinux2014\",\n    # CentOS 6 w/ glibc 2.12 (PEP 571)\n    (2, 12): \"manylinux2010\",\n    # CentOS 5 w/ glibc 2.5 (PEP 513)\n    (2, 5): \"manylinux1\",\n}\n\n\ndef platform_tags(linux: str, arch: str) -> Iterator[str]:\n    if not _have_compatible_abi(arch):\n        return\n    # Oldest glibc to be supported regardless of architecture is (2, 17).\n    too_old_glibc2 = _GLibCVersion(2, 16)\n    if arch in {\"x86_64\", \"i686\"}:\n        # On x86/i686 also oldest glibc to be supported is (2, 5).\n        too_old_glibc2 = _GLibCVersion(2, 4)\n    current_glibc = _GLibCVersion(*_get_glibc_version())\n    glibc_max_list = [current_glibc]\n    # We can assume compatibility across glibc major versions.\n    # https://sourceware.org/bugzilla/show_bug.cgi?id=24636\n    #\n    # Build a list of maximum glibc versions so that we can\n    # output the canonical list of all glibc from current_glibc\n    # down to too_old_glibc2, including all intermediary versions.\n    for glibc_major in range(current_glibc.major - 1, 1, -1):\n        glibc_minor = _LAST_GLIBC_MINOR[glibc_major]\n        glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))\n    for glibc_max in glibc_max_list:\n        if glibc_max.major == too_old_glibc2.major:\n            min_minor = too_old_glibc2.minor\n        else:\n            # For other glibc major versions oldest supported is (x, 0).\n            min_minor = -1\n        for glibc_minor in range(glibc_max.minor, min_minor, -1):\n            glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)\n            tag = \"manylinux_{}_{}\".format(*glibc_version)\n            if _is_compatible(tag, arch, glibc_version):\n                yield linux.replace(\"linux\", tag)\n            # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.\n            if glibc_version in _LEGACY_MANYLINUX_MAP:\n                legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version]\n                if _is_compatible(legacy_tag, arch, glibc_version):\n                    yield linux.replace(\"linux\", legacy_tag)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/packaging/_musllinux.py",
    "content": "\"\"\"PEP 656 support.\n\nThis module implements logic to detect if the currently running Python is\nlinked against musl, and what musl version is used.\n\"\"\"\n\nimport contextlib\nimport functools\nimport operator\nimport os\nimport re\nimport struct\nimport subprocess\nimport sys\nfrom typing import IO, Iterator, NamedTuple, Optional, Tuple\n\n\ndef _read_unpacked(f: IO[bytes], fmt: str) -> Tuple[int, ...]:\n    return struct.unpack(fmt, f.read(struct.calcsize(fmt)))\n\n\ndef _parse_ld_musl_from_elf(f: IO[bytes]) -> Optional[str]:\n    \"\"\"Detect musl libc location by parsing the Python executable.\n\n    Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca\n    ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html\n    \"\"\"\n    f.seek(0)\n    try:\n        ident = _read_unpacked(f, \"16B\")\n    except struct.error:\n        return None\n    if ident[:4] != tuple(b\"\\x7fELF\"):  # Invalid magic, not ELF.\n        return None\n    f.seek(struct.calcsize(\"HHI\"), 1)  # Skip file type, machine, and version.\n\n    try:\n        # e_fmt: Format for program header.\n        # p_fmt: Format for section header.\n        # p_idx: Indexes to find p_type, p_offset, and p_filesz.\n        e_fmt, p_fmt, p_idx = {\n            1: (\"IIIIHHH\", \"IIIIIIII\", (0, 1, 4)),  # 32-bit.\n            2: (\"QQQIHHH\", \"IIQQQQQQ\", (0, 2, 5)),  # 64-bit.\n        }[ident[4]]\n    except KeyError:\n        return None\n    else:\n        p_get = operator.itemgetter(*p_idx)\n\n    # Find the interpreter section and return its content.\n    try:\n        _, e_phoff, _, _, _, e_phentsize, e_phnum = _read_unpacked(f, e_fmt)\n    except struct.error:\n        return None\n    for i in range(e_phnum + 1):\n        f.seek(e_phoff + e_phentsize * i)\n        try:\n            p_type, p_offset, p_filesz = p_get(_read_unpacked(f, p_fmt))\n        except struct.error:\n            return None\n        if p_type != 3:  # Not PT_INTERP.\n            continue\n        f.seek(p_offset)\n        interpreter = os.fsdecode(f.read(p_filesz)).strip(\"\\0\")\n        if \"musl\" not in interpreter:\n            return None\n        return interpreter\n    return None\n\n\nclass _MuslVersion(NamedTuple):\n    major: int\n    minor: int\n\n\ndef _parse_musl_version(output: str) -> Optional[_MuslVersion]:\n    lines = [n for n in (n.strip() for n in output.splitlines()) if n]\n    if len(lines) < 2 or lines[0][:4] != \"musl\":\n        return None\n    m = re.match(r\"Version (\\d+)\\.(\\d+)\", lines[1])\n    if not m:\n        return None\n    return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))\n\n\n@functools.lru_cache()\ndef _get_musl_version(executable: str) -> Optional[_MuslVersion]:\n    \"\"\"Detect currently-running musl runtime version.\n\n    This is done by checking the specified executable's dynamic linking\n    information, and invoking the loader to parse its output for a version\n    string. If the loader is musl, the output would be something like::\n\n        musl libc (x86_64)\n        Version 1.2.2\n        Dynamic Program Loader\n    \"\"\"\n    with contextlib.ExitStack() as stack:\n        try:\n            f = stack.enter_context(open(executable, \"rb\"))\n        except OSError:\n            return None\n        ld = _parse_ld_musl_from_elf(f)\n    if not ld:\n        return None\n    proc = subprocess.run([ld], stderr=subprocess.PIPE, universal_newlines=True)\n    return _parse_musl_version(proc.stderr)\n\n\ndef platform_tags(arch: str) -> Iterator[str]:\n    \"\"\"Generate musllinux tags compatible to the current platform.\n\n    :param arch: Should be the part of platform tag after the ``linux_``\n        prefix, e.g. ``x86_64``. The ``linux_`` prefix is assumed as a\n        prerequisite for the current platform to be musllinux-compatible.\n\n    :returns: An iterator of compatible musllinux tags.\n    \"\"\"\n    sys_musl = _get_musl_version(sys.executable)\n    if sys_musl is None:  # Python not dynamically linked against musl.\n        return\n    for minor in range(sys_musl.minor, -1, -1):\n        yield f\"musllinux_{sys_musl.major}_{minor}_{arch}\"\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import sysconfig\n\n    plat = sysconfig.get_platform()\n    assert plat.startswith(\"linux-\"), \"not linux\"\n\n    print(\"plat:\", plat)\n    print(\"musl:\", _get_musl_version(sys.executable))\n    print(\"tags:\", end=\" \")\n    for t in platform_tags(re.sub(r\"[.-]\", \"_\", plat.split(\"-\", 1)[-1])):\n        print(t, end=\"\\n      \")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/packaging/_structures.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\n\nclass InfinityType:\n    def __repr__(self) -> str:\n        return \"Infinity\"\n\n    def __hash__(self) -> int:\n        return hash(repr(self))\n\n    def __lt__(self, other: object) -> bool:\n        return False\n\n    def __le__(self, other: object) -> bool:\n        return False\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, self.__class__)\n\n    def __gt__(self, other: object) -> bool:\n        return True\n\n    def __ge__(self, other: object) -> bool:\n        return True\n\n    def __neg__(self: object) -> \"NegativeInfinityType\":\n        return NegativeInfinity\n\n\nInfinity = InfinityType()\n\n\nclass NegativeInfinityType:\n    def __repr__(self) -> str:\n        return \"-Infinity\"\n\n    def __hash__(self) -> int:\n        return hash(repr(self))\n\n    def __lt__(self, other: object) -> bool:\n        return True\n\n    def __le__(self, other: object) -> bool:\n        return True\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, self.__class__)\n\n    def __gt__(self, other: object) -> bool:\n        return False\n\n    def __ge__(self, other: object) -> bool:\n        return False\n\n    def __neg__(self: object) -> InfinityType:\n        return Infinity\n\n\nNegativeInfinity = NegativeInfinityType()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/packaging/markers.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport operator\nimport os\nimport platform\nimport sys\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union\n\nfrom pip._vendor.pyparsing import (  # noqa: N817\n    Forward,\n    Group,\n    Literal as L,\n    ParseException,\n    ParseResults,\n    QuotedString,\n    ZeroOrMore,\n    stringEnd,\n    stringStart,\n)\n\nfrom .specifiers import InvalidSpecifier, Specifier\n\n__all__ = [\n    \"InvalidMarker\",\n    \"UndefinedComparison\",\n    \"UndefinedEnvironmentName\",\n    \"Marker\",\n    \"default_environment\",\n]\n\nOperator = Callable[[str, str], bool]\n\n\nclass InvalidMarker(ValueError):\n    \"\"\"\n    An invalid marker was found, users should refer to PEP 508.\n    \"\"\"\n\n\nclass UndefinedComparison(ValueError):\n    \"\"\"\n    An invalid operation was attempted on a value that doesn't support it.\n    \"\"\"\n\n\nclass UndefinedEnvironmentName(ValueError):\n    \"\"\"\n    A name was attempted to be used that does not exist inside of the\n    environment.\n    \"\"\"\n\n\nclass Node:\n    def __init__(self, value: Any) -> None:\n        self.value = value\n\n    def __str__(self) -> str:\n        return str(self.value)\n\n    def __repr__(self) -> str:\n        return f\"<{self.__class__.__name__}('{self}')>\"\n\n    def serialize(self) -> str:\n        raise NotImplementedError\n\n\nclass Variable(Node):\n    def serialize(self) -> str:\n        return str(self)\n\n\nclass Value(Node):\n    def serialize(self) -> str:\n        return f'\"{self}\"'\n\n\nclass Op(Node):\n    def serialize(self) -> str:\n        return str(self)\n\n\nVARIABLE = (\n    L(\"implementation_version\")\n    | L(\"platform_python_implementation\")\n    | L(\"implementation_name\")\n    | L(\"python_full_version\")\n    | L(\"platform_release\")\n    | L(\"platform_version\")\n    | L(\"platform_machine\")\n    | L(\"platform_system\")\n    | L(\"python_version\")\n    | L(\"sys_platform\")\n    | L(\"os_name\")\n    | L(\"os.name\")  # PEP-345\n    | L(\"sys.platform\")  # PEP-345\n    | L(\"platform.version\")  # PEP-345\n    | L(\"platform.machine\")  # PEP-345\n    | L(\"platform.python_implementation\")  # PEP-345\n    | L(\"python_implementation\")  # undocumented setuptools legacy\n    | L(\"extra\")  # PEP-508\n)\nALIASES = {\n    \"os.name\": \"os_name\",\n    \"sys.platform\": \"sys_platform\",\n    \"platform.version\": \"platform_version\",\n    \"platform.machine\": \"platform_machine\",\n    \"platform.python_implementation\": \"platform_python_implementation\",\n    \"python_implementation\": \"platform_python_implementation\",\n}\nVARIABLE.setParseAction(lambda s, l, t: Variable(ALIASES.get(t[0], t[0])))\n\nVERSION_CMP = (\n    L(\"===\") | L(\"==\") | L(\">=\") | L(\"<=\") | L(\"!=\") | L(\"~=\") | L(\">\") | L(\"<\")\n)\n\nMARKER_OP = VERSION_CMP | L(\"not in\") | L(\"in\")\nMARKER_OP.setParseAction(lambda s, l, t: Op(t[0]))\n\nMARKER_VALUE = QuotedString(\"'\") | QuotedString('\"')\nMARKER_VALUE.setParseAction(lambda s, l, t: Value(t[0]))\n\nBOOLOP = L(\"and\") | L(\"or\")\n\nMARKER_VAR = VARIABLE | MARKER_VALUE\n\nMARKER_ITEM = Group(MARKER_VAR + MARKER_OP + MARKER_VAR)\nMARKER_ITEM.setParseAction(lambda s, l, t: tuple(t[0]))\n\nLPAREN = L(\"(\").suppress()\nRPAREN = L(\")\").suppress()\n\nMARKER_EXPR = Forward()\nMARKER_ATOM = MARKER_ITEM | Group(LPAREN + MARKER_EXPR + RPAREN)\nMARKER_EXPR << MARKER_ATOM + ZeroOrMore(BOOLOP + MARKER_EXPR)\n\nMARKER = stringStart + MARKER_EXPR + stringEnd\n\n\ndef _coerce_parse_result(results: Union[ParseResults, List[Any]]) -> List[Any]:\n    if isinstance(results, ParseResults):\n        return [_coerce_parse_result(i) for i in results]\n    else:\n        return results\n\n\ndef _format_marker(\n    marker: Union[List[str], Tuple[Node, ...], str], first: Optional[bool] = True\n) -> str:\n\n    assert isinstance(marker, (list, tuple, str))\n\n    # Sometimes we have a structure like [[...]] which is a single item list\n    # where the single item is itself it's own list. In that case we want skip\n    # the rest of this function so that we don't get extraneous () on the\n    # outside.\n    if (\n        isinstance(marker, list)\n        and len(marker) == 1\n        and isinstance(marker[0], (list, tuple))\n    ):\n        return _format_marker(marker[0])\n\n    if isinstance(marker, list):\n        inner = (_format_marker(m, first=False) for m in marker)\n        if first:\n            return \" \".join(inner)\n        else:\n            return \"(\" + \" \".join(inner) + \")\"\n    elif isinstance(marker, tuple):\n        return \" \".join([m.serialize() for m in marker])\n    else:\n        return marker\n\n\n_operators: Dict[str, Operator] = {\n    \"in\": lambda lhs, rhs: lhs in rhs,\n    \"not in\": lambda lhs, rhs: lhs not in rhs,\n    \"<\": operator.lt,\n    \"<=\": operator.le,\n    \"==\": operator.eq,\n    \"!=\": operator.ne,\n    \">=\": operator.ge,\n    \">\": operator.gt,\n}\n\n\ndef _eval_op(lhs: str, op: Op, rhs: str) -> bool:\n    try:\n        spec = Specifier(\"\".join([op.serialize(), rhs]))\n    except InvalidSpecifier:\n        pass\n    else:\n        return spec.contains(lhs)\n\n    oper: Optional[Operator] = _operators.get(op.serialize())\n    if oper is None:\n        raise UndefinedComparison(f\"Undefined {op!r} on {lhs!r} and {rhs!r}.\")\n\n    return oper(lhs, rhs)\n\n\nclass Undefined:\n    pass\n\n\n_undefined = Undefined()\n\n\ndef _get_env(environment: Dict[str, str], name: str) -> str:\n    value: Union[str, Undefined] = environment.get(name, _undefined)\n\n    if isinstance(value, Undefined):\n        raise UndefinedEnvironmentName(\n            f\"{name!r} does not exist in evaluation environment.\"\n        )\n\n    return value\n\n\ndef _evaluate_markers(markers: List[Any], environment: Dict[str, str]) -> bool:\n    groups: List[List[bool]] = [[]]\n\n    for marker in markers:\n        assert isinstance(marker, (list, tuple, str))\n\n        if isinstance(marker, list):\n            groups[-1].append(_evaluate_markers(marker, environment))\n        elif isinstance(marker, tuple):\n            lhs, op, rhs = marker\n\n            if isinstance(lhs, Variable):\n                lhs_value = _get_env(environment, lhs.value)\n                rhs_value = rhs.value\n            else:\n                lhs_value = lhs.value\n                rhs_value = _get_env(environment, rhs.value)\n\n            groups[-1].append(_eval_op(lhs_value, op, rhs_value))\n        else:\n            assert marker in [\"and\", \"or\"]\n            if marker == \"or\":\n                groups.append([])\n\n    return any(all(item) for item in groups)\n\n\ndef format_full_version(info: \"sys._version_info\") -> str:\n    version = \"{0.major}.{0.minor}.{0.micro}\".format(info)\n    kind = info.releaselevel\n    if kind != \"final\":\n        version += kind[0] + str(info.serial)\n    return version\n\n\ndef default_environment() -> Dict[str, str]:\n    iver = format_full_version(sys.implementation.version)\n    implementation_name = sys.implementation.name\n    return {\n        \"implementation_name\": implementation_name,\n        \"implementation_version\": iver,\n        \"os_name\": os.name,\n        \"platform_machine\": platform.machine(),\n        \"platform_release\": platform.release(),\n        \"platform_system\": platform.system(),\n        \"platform_version\": platform.version(),\n        \"python_full_version\": platform.python_version(),\n        \"platform_python_implementation\": platform.python_implementation(),\n        \"python_version\": \".\".join(platform.python_version_tuple()[:2]),\n        \"sys_platform\": sys.platform,\n    }\n\n\nclass Marker:\n    def __init__(self, marker: str) -> None:\n        try:\n            self._markers = _coerce_parse_result(MARKER.parseString(marker))\n        except ParseException as e:\n            raise InvalidMarker(\n                f\"Invalid marker: {marker!r}, parse error at \"\n                f\"{marker[e.loc : e.loc + 8]!r}\"\n            )\n\n    def __str__(self) -> str:\n        return _format_marker(self._markers)\n\n    def __repr__(self) -> str:\n        return f\"<Marker('{self}')>\"\n\n    def evaluate(self, environment: Optional[Dict[str, str]] = None) -> bool:\n        \"\"\"Evaluate a marker.\n\n        Return the boolean from evaluating the given marker against the\n        environment. environment is an optional argument to override all or\n        part of the determined environment.\n\n        The environment is determined from the current Python process.\n        \"\"\"\n        current_environment = default_environment()\n        if environment is not None:\n            current_environment.update(environment)\n\n        return _evaluate_markers(self._markers, current_environment)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/packaging/requirements.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport re\nimport string\nimport urllib.parse\nfrom typing import List, Optional as TOptional, Set\n\nfrom pip._vendor.pyparsing import (  # noqa\n    Combine,\n    Literal as L,\n    Optional,\n    ParseException,\n    Regex,\n    Word,\n    ZeroOrMore,\n    originalTextFor,\n    stringEnd,\n    stringStart,\n)\n\nfrom .markers import MARKER_EXPR, Marker\nfrom .specifiers import LegacySpecifier, Specifier, SpecifierSet\n\n\nclass InvalidRequirement(ValueError):\n    \"\"\"\n    An invalid requirement was found, users should refer to PEP 508.\n    \"\"\"\n\n\nALPHANUM = Word(string.ascii_letters + string.digits)\n\nLBRACKET = L(\"[\").suppress()\nRBRACKET = L(\"]\").suppress()\nLPAREN = L(\"(\").suppress()\nRPAREN = L(\")\").suppress()\nCOMMA = L(\",\").suppress()\nSEMICOLON = L(\";\").suppress()\nAT = L(\"@\").suppress()\n\nPUNCTUATION = Word(\"-_.\")\nIDENTIFIER_END = ALPHANUM | (ZeroOrMore(PUNCTUATION) + ALPHANUM)\nIDENTIFIER = Combine(ALPHANUM + ZeroOrMore(IDENTIFIER_END))\n\nNAME = IDENTIFIER(\"name\")\nEXTRA = IDENTIFIER\n\nURI = Regex(r\"[^ ]+\")(\"url\")\nURL = AT + URI\n\nEXTRAS_LIST = EXTRA + ZeroOrMore(COMMA + EXTRA)\nEXTRAS = (LBRACKET + Optional(EXTRAS_LIST) + RBRACKET)(\"extras\")\n\nVERSION_PEP440 = Regex(Specifier._regex_str, re.VERBOSE | re.IGNORECASE)\nVERSION_LEGACY = Regex(LegacySpecifier._regex_str, re.VERBOSE | re.IGNORECASE)\n\nVERSION_ONE = VERSION_PEP440 ^ VERSION_LEGACY\nVERSION_MANY = Combine(\n    VERSION_ONE + ZeroOrMore(COMMA + VERSION_ONE), joinString=\",\", adjacent=False\n)(\"_raw_spec\")\n_VERSION_SPEC = Optional((LPAREN + VERSION_MANY + RPAREN) | VERSION_MANY)\n_VERSION_SPEC.setParseAction(lambda s, l, t: t._raw_spec or \"\")\n\nVERSION_SPEC = originalTextFor(_VERSION_SPEC)(\"specifier\")\nVERSION_SPEC.setParseAction(lambda s, l, t: t[1])\n\nMARKER_EXPR = originalTextFor(MARKER_EXPR())(\"marker\")\nMARKER_EXPR.setParseAction(\n    lambda s, l, t: Marker(s[t._original_start : t._original_end])\n)\nMARKER_SEPARATOR = SEMICOLON\nMARKER = MARKER_SEPARATOR + MARKER_EXPR\n\nVERSION_AND_MARKER = VERSION_SPEC + Optional(MARKER)\nURL_AND_MARKER = URL + Optional(MARKER)\n\nNAMED_REQUIREMENT = NAME + Optional(EXTRAS) + (URL_AND_MARKER | VERSION_AND_MARKER)\n\nREQUIREMENT = stringStart + NAMED_REQUIREMENT + stringEnd\n# pyparsing isn't thread safe during initialization, so we do it eagerly, see\n# issue #104\nREQUIREMENT.parseString(\"x[]\")\n\n\nclass Requirement:\n    \"\"\"Parse a requirement.\n\n    Parse a given requirement string into its parts, such as name, specifier,\n    URL, and extras. Raises InvalidRequirement on a badly-formed requirement\n    string.\n    \"\"\"\n\n    # TODO: Can we test whether something is contained within a requirement?\n    #       If so how do we do that? Do we need to test against the _name_ of\n    #       the thing as well as the version? What about the markers?\n    # TODO: Can we normalize the name and extra name?\n\n    def __init__(self, requirement_string: str) -> None:\n        try:\n            req = REQUIREMENT.parseString(requirement_string)\n        except ParseException as e:\n            raise InvalidRequirement(\n                f'Parse error at \"{ requirement_string[e.loc : e.loc + 8]!r}\": {e.msg}'\n            )\n\n        self.name: str = req.name\n        if req.url:\n            parsed_url = urllib.parse.urlparse(req.url)\n            if parsed_url.scheme == \"file\":\n                if urllib.parse.urlunparse(parsed_url) != req.url:\n                    raise InvalidRequirement(\"Invalid URL given\")\n            elif not (parsed_url.scheme and parsed_url.netloc) or (\n                not parsed_url.scheme and not parsed_url.netloc\n            ):\n                raise InvalidRequirement(f\"Invalid URL: {req.url}\")\n            self.url: TOptional[str] = req.url\n        else:\n            self.url = None\n        self.extras: Set[str] = set(req.extras.asList() if req.extras else [])\n        self.specifier: SpecifierSet = SpecifierSet(req.specifier)\n        self.marker: TOptional[Marker] = req.marker if req.marker else None\n\n    def __str__(self) -> str:\n        parts: List[str] = [self.name]\n\n        if self.extras:\n            formatted_extras = \",\".join(sorted(self.extras))\n            parts.append(f\"[{formatted_extras}]\")\n\n        if self.specifier:\n            parts.append(str(self.specifier))\n\n        if self.url:\n            parts.append(f\"@ {self.url}\")\n            if self.marker:\n                parts.append(\" \")\n\n        if self.marker:\n            parts.append(f\"; {self.marker}\")\n\n        return \"\".join(parts)\n\n    def __repr__(self) -> str:\n        return f\"<Requirement('{self}')>\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/packaging/specifiers.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport abc\nimport functools\nimport itertools\nimport re\nimport warnings\nfrom typing import (\n    Callable,\n    Dict,\n    Iterable,\n    Iterator,\n    List,\n    Optional,\n    Pattern,\n    Set,\n    Tuple,\n    TypeVar,\n    Union,\n)\n\nfrom .utils import canonicalize_version\nfrom .version import LegacyVersion, Version, parse\n\nParsedVersion = Union[Version, LegacyVersion]\nUnparsedVersion = Union[Version, LegacyVersion, str]\nVersionTypeVar = TypeVar(\"VersionTypeVar\", bound=UnparsedVersion)\nCallableOperator = Callable[[ParsedVersion, str], bool]\n\n\nclass InvalidSpecifier(ValueError):\n    \"\"\"\n    An invalid specifier was found, users should refer to PEP 440.\n    \"\"\"\n\n\nclass BaseSpecifier(metaclass=abc.ABCMeta):\n    @abc.abstractmethod\n    def __str__(self) -> str:\n        \"\"\"\n        Returns the str representation of this Specifier like object. This\n        should be representative of the Specifier itself.\n        \"\"\"\n\n    @abc.abstractmethod\n    def __hash__(self) -> int:\n        \"\"\"\n        Returns a hash value for this Specifier like object.\n        \"\"\"\n\n    @abc.abstractmethod\n    def __eq__(self, other: object) -> bool:\n        \"\"\"\n        Returns a boolean representing whether or not the two Specifier like\n        objects are equal.\n        \"\"\"\n\n    @abc.abstractproperty\n    def prereleases(self) -> Optional[bool]:\n        \"\"\"\n        Returns whether or not pre-releases as a whole are allowed by this\n        specifier.\n        \"\"\"\n\n    @prereleases.setter\n    def prereleases(self, value: bool) -> None:\n        \"\"\"\n        Sets whether or not pre-releases as a whole are allowed by this\n        specifier.\n        \"\"\"\n\n    @abc.abstractmethod\n    def contains(self, item: str, prereleases: Optional[bool] = None) -> bool:\n        \"\"\"\n        Determines if the given item is contained within this specifier.\n        \"\"\"\n\n    @abc.abstractmethod\n    def filter(\n        self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None\n    ) -> Iterable[VersionTypeVar]:\n        \"\"\"\n        Takes an iterable of items and filters them so that only items which\n        are contained within this specifier are allowed in it.\n        \"\"\"\n\n\nclass _IndividualSpecifier(BaseSpecifier):\n\n    _operators: Dict[str, str] = {}\n    _regex: Pattern[str]\n\n    def __init__(self, spec: str = \"\", prereleases: Optional[bool] = None) -> None:\n        match = self._regex.search(spec)\n        if not match:\n            raise InvalidSpecifier(f\"Invalid specifier: '{spec}'\")\n\n        self._spec: Tuple[str, str] = (\n            match.group(\"operator\").strip(),\n            match.group(\"version\").strip(),\n        )\n\n        # Store whether or not this Specifier should accept prereleases\n        self._prereleases = prereleases\n\n    def __repr__(self) -> str:\n        pre = (\n            f\", prereleases={self.prereleases!r}\"\n            if self._prereleases is not None\n            else \"\"\n        )\n\n        return f\"<{self.__class__.__name__}({str(self)!r}{pre})>\"\n\n    def __str__(self) -> str:\n        return \"{}{}\".format(*self._spec)\n\n    @property\n    def _canonical_spec(self) -> Tuple[str, str]:\n        return self._spec[0], canonicalize_version(self._spec[1])\n\n    def __hash__(self) -> int:\n        return hash(self._canonical_spec)\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, str):\n            try:\n                other = self.__class__(str(other))\n            except InvalidSpecifier:\n                return NotImplemented\n        elif not isinstance(other, self.__class__):\n            return NotImplemented\n\n        return self._canonical_spec == other._canonical_spec\n\n    def _get_operator(self, op: str) -> CallableOperator:\n        operator_callable: CallableOperator = getattr(\n            self, f\"_compare_{self._operators[op]}\"\n        )\n        return operator_callable\n\n    def _coerce_version(self, version: UnparsedVersion) -> ParsedVersion:\n        if not isinstance(version, (LegacyVersion, Version)):\n            version = parse(version)\n        return version\n\n    @property\n    def operator(self) -> str:\n        return self._spec[0]\n\n    @property\n    def version(self) -> str:\n        return self._spec[1]\n\n    @property\n    def prereleases(self) -> Optional[bool]:\n        return self._prereleases\n\n    @prereleases.setter\n    def prereleases(self, value: bool) -> None:\n        self._prereleases = value\n\n    def __contains__(self, item: str) -> bool:\n        return self.contains(item)\n\n    def contains(\n        self, item: UnparsedVersion, prereleases: Optional[bool] = None\n    ) -> bool:\n\n        # Determine if prereleases are to be allowed or not.\n        if prereleases is None:\n            prereleases = self.prereleases\n\n        # Normalize item to a Version or LegacyVersion, this allows us to have\n        # a shortcut for ``\"2.0\" in Specifier(\">=2\")\n        normalized_item = self._coerce_version(item)\n\n        # Determine if we should be supporting prereleases in this specifier\n        # or not, if we do not support prereleases than we can short circuit\n        # logic if this version is a prereleases.\n        if normalized_item.is_prerelease and not prereleases:\n            return False\n\n        # Actually do the comparison to determine if this item is contained\n        # within this Specifier or not.\n        operator_callable: CallableOperator = self._get_operator(self.operator)\n        return operator_callable(normalized_item, self.version)\n\n    def filter(\n        self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None\n    ) -> Iterable[VersionTypeVar]:\n\n        yielded = False\n        found_prereleases = []\n\n        kw = {\"prereleases\": prereleases if prereleases is not None else True}\n\n        # Attempt to iterate over all the values in the iterable and if any of\n        # them match, yield them.\n        for version in iterable:\n            parsed_version = self._coerce_version(version)\n\n            if self.contains(parsed_version, **kw):\n                # If our version is a prerelease, and we were not set to allow\n                # prereleases, then we'll store it for later in case nothing\n                # else matches this specifier.\n                if parsed_version.is_prerelease and not (\n                    prereleases or self.prereleases\n                ):\n                    found_prereleases.append(version)\n                # Either this is not a prerelease, or we should have been\n                # accepting prereleases from the beginning.\n                else:\n                    yielded = True\n                    yield version\n\n        # Now that we've iterated over everything, determine if we've yielded\n        # any values, and if we have not and we have any prereleases stored up\n        # then we will go ahead and yield the prereleases.\n        if not yielded and found_prereleases:\n            for version in found_prereleases:\n                yield version\n\n\nclass LegacySpecifier(_IndividualSpecifier):\n\n    _regex_str = r\"\"\"\n        (?P<operator>(==|!=|<=|>=|<|>))\n        \\s*\n        (?P<version>\n            [^,;\\s)]* # Since this is a \"legacy\" specifier, and the version\n                      # string can be just about anything, we match everything\n                      # except for whitespace, a semi-colon for marker support,\n                      # a closing paren since versions can be enclosed in\n                      # them, and a comma since it's a version separator.\n        )\n        \"\"\"\n\n    _regex = re.compile(r\"^\\s*\" + _regex_str + r\"\\s*$\", re.VERBOSE | re.IGNORECASE)\n\n    _operators = {\n        \"==\": \"equal\",\n        \"!=\": \"not_equal\",\n        \"<=\": \"less_than_equal\",\n        \">=\": \"greater_than_equal\",\n        \"<\": \"less_than\",\n        \">\": \"greater_than\",\n    }\n\n    def __init__(self, spec: str = \"\", prereleases: Optional[bool] = None) -> None:\n        super().__init__(spec, prereleases)\n\n        warnings.warn(\n            \"Creating a LegacyVersion has been deprecated and will be \"\n            \"removed in the next major release\",\n            DeprecationWarning,\n        )\n\n    def _coerce_version(self, version: UnparsedVersion) -> LegacyVersion:\n        if not isinstance(version, LegacyVersion):\n            version = LegacyVersion(str(version))\n        return version\n\n    def _compare_equal(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective == self._coerce_version(spec)\n\n    def _compare_not_equal(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective != self._coerce_version(spec)\n\n    def _compare_less_than_equal(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective <= self._coerce_version(spec)\n\n    def _compare_greater_than_equal(\n        self, prospective: LegacyVersion, spec: str\n    ) -> bool:\n        return prospective >= self._coerce_version(spec)\n\n    def _compare_less_than(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective < self._coerce_version(spec)\n\n    def _compare_greater_than(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective > self._coerce_version(spec)\n\n\ndef _require_version_compare(\n    fn: Callable[[\"Specifier\", ParsedVersion, str], bool]\n) -> Callable[[\"Specifier\", ParsedVersion, str], bool]:\n    @functools.wraps(fn)\n    def wrapped(self: \"Specifier\", prospective: ParsedVersion, spec: str) -> bool:\n        if not isinstance(prospective, Version):\n            return False\n        return fn(self, prospective, spec)\n\n    return wrapped\n\n\nclass Specifier(_IndividualSpecifier):\n\n    _regex_str = r\"\"\"\n        (?P<operator>(~=|==|!=|<=|>=|<|>|===))\n        (?P<version>\n            (?:\n                # The identity operators allow for an escape hatch that will\n                # do an exact string match of the version you wish to install.\n                # This will not be parsed by PEP 440 and we cannot determine\n                # any semantic meaning from it. This operator is discouraged\n                # but included entirely as an escape hatch.\n                (?<====)  # Only match for the identity operator\n                \\s*\n                [^\\s]*    # We just match everything, except for whitespace\n                          # since we are only testing for strict identity.\n            )\n            |\n            (?:\n                # The (non)equality operators allow for wild card and local\n                # versions to be specified so we have to define these two\n                # operators separately to enable that.\n                (?<===|!=)            # Only match for equals and not equals\n\n                \\s*\n                v?\n                (?:[0-9]+!)?          # epoch\n                [0-9]+(?:\\.[0-9]+)*   # release\n                (?:                   # pre release\n                    [-_\\.]?\n                    (a|b|c|rc|alpha|beta|pre|preview)\n                    [-_\\.]?\n                    [0-9]*\n                )?\n                (?:                   # post release\n                    (?:-[0-9]+)|(?:[-_\\.]?(post|rev|r)[-_\\.]?[0-9]*)\n                )?\n\n                # You cannot use a wild card and a dev or local version\n                # together so group them with a | and make them optional.\n                (?:\n                    (?:[-_\\.]?dev[-_\\.]?[0-9]*)?         # dev release\n                    (?:\\+[a-z0-9]+(?:[-_\\.][a-z0-9]+)*)? # local\n                    |\n                    \\.\\*  # Wild card syntax of .*\n                )?\n            )\n            |\n            (?:\n                # The compatible operator requires at least two digits in the\n                # release segment.\n                (?<=~=)               # Only match for the compatible operator\n\n                \\s*\n                v?\n                (?:[0-9]+!)?          # epoch\n                [0-9]+(?:\\.[0-9]+)+   # release  (We have a + instead of a *)\n                (?:                   # pre release\n                    [-_\\.]?\n                    (a|b|c|rc|alpha|beta|pre|preview)\n                    [-_\\.]?\n                    [0-9]*\n                )?\n                (?:                                   # post release\n                    (?:-[0-9]+)|(?:[-_\\.]?(post|rev|r)[-_\\.]?[0-9]*)\n                )?\n                (?:[-_\\.]?dev[-_\\.]?[0-9]*)?          # dev release\n            )\n            |\n            (?:\n                # All other operators only allow a sub set of what the\n                # (non)equality operators do. Specifically they do not allow\n                # local versions to be specified nor do they allow the prefix\n                # matching wild cards.\n                (?<!==|!=|~=)         # We have special cases for these\n                                      # operators so we want to make sure they\n                                      # don't match here.\n\n                \\s*\n                v?\n                (?:[0-9]+!)?          # epoch\n                [0-9]+(?:\\.[0-9]+)*   # release\n                (?:                   # pre release\n                    [-_\\.]?\n                    (a|b|c|rc|alpha|beta|pre|preview)\n                    [-_\\.]?\n                    [0-9]*\n                )?\n                (?:                                   # post release\n                    (?:-[0-9]+)|(?:[-_\\.]?(post|rev|r)[-_\\.]?[0-9]*)\n                )?\n                (?:[-_\\.]?dev[-_\\.]?[0-9]*)?          # dev release\n            )\n        )\n        \"\"\"\n\n    _regex = re.compile(r\"^\\s*\" + _regex_str + r\"\\s*$\", re.VERBOSE | re.IGNORECASE)\n\n    _operators = {\n        \"~=\": \"compatible\",\n        \"==\": \"equal\",\n        \"!=\": \"not_equal\",\n        \"<=\": \"less_than_equal\",\n        \">=\": \"greater_than_equal\",\n        \"<\": \"less_than\",\n        \">\": \"greater_than\",\n        \"===\": \"arbitrary\",\n    }\n\n    @_require_version_compare\n    def _compare_compatible(self, prospective: ParsedVersion, spec: str) -> bool:\n\n        # Compatible releases have an equivalent combination of >= and ==. That\n        # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to\n        # implement this in terms of the other specifiers instead of\n        # implementing it ourselves. The only thing we need to do is construct\n        # the other specifiers.\n\n        # We want everything but the last item in the version, but we want to\n        # ignore suffix segments.\n        prefix = \".\".join(\n            list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1]\n        )\n\n        # Add the prefix notation to the end of our string\n        prefix += \".*\"\n\n        return self._get_operator(\">=\")(prospective, spec) and self._get_operator(\"==\")(\n            prospective, prefix\n        )\n\n    @_require_version_compare\n    def _compare_equal(self, prospective: ParsedVersion, spec: str) -> bool:\n\n        # We need special logic to handle prefix matching\n        if spec.endswith(\".*\"):\n            # In the case of prefix matching we want to ignore local segment.\n            prospective = Version(prospective.public)\n            # Split the spec out by dots, and pretend that there is an implicit\n            # dot in between a release segment and a pre-release segment.\n            split_spec = _version_split(spec[:-2])  # Remove the trailing .*\n\n            # Split the prospective version out by dots, and pretend that there\n            # is an implicit dot in between a release segment and a pre-release\n            # segment.\n            split_prospective = _version_split(str(prospective))\n\n            # Shorten the prospective version to be the same length as the spec\n            # so that we can determine if the specifier is a prefix of the\n            # prospective version or not.\n            shortened_prospective = split_prospective[: len(split_spec)]\n\n            # Pad out our two sides with zeros so that they both equal the same\n            # length.\n            padded_spec, padded_prospective = _pad_version(\n                split_spec, shortened_prospective\n            )\n\n            return padded_prospective == padded_spec\n        else:\n            # Convert our spec string into a Version\n            spec_version = Version(spec)\n\n            # If the specifier does not have a local segment, then we want to\n            # act as if the prospective version also does not have a local\n            # segment.\n            if not spec_version.local:\n                prospective = Version(prospective.public)\n\n            return prospective == spec_version\n\n    @_require_version_compare\n    def _compare_not_equal(self, prospective: ParsedVersion, spec: str) -> bool:\n        return not self._compare_equal(prospective, spec)\n\n    @_require_version_compare\n    def _compare_less_than_equal(self, prospective: ParsedVersion, spec: str) -> bool:\n\n        # NB: Local version identifiers are NOT permitted in the version\n        # specifier, so local version labels can be universally removed from\n        # the prospective version.\n        return Version(prospective.public) <= Version(spec)\n\n    @_require_version_compare\n    def _compare_greater_than_equal(\n        self, prospective: ParsedVersion, spec: str\n    ) -> bool:\n\n        # NB: Local version identifiers are NOT permitted in the version\n        # specifier, so local version labels can be universally removed from\n        # the prospective version.\n        return Version(prospective.public) >= Version(spec)\n\n    @_require_version_compare\n    def _compare_less_than(self, prospective: ParsedVersion, spec_str: str) -> bool:\n\n        # Convert our spec to a Version instance, since we'll want to work with\n        # it as a version.\n        spec = Version(spec_str)\n\n        # Check to see if the prospective version is less than the spec\n        # version. If it's not we can short circuit and just return False now\n        # instead of doing extra unneeded work.\n        if not prospective < spec:\n            return False\n\n        # This special case is here so that, unless the specifier itself\n        # includes is a pre-release version, that we do not accept pre-release\n        # versions for the version mentioned in the specifier (e.g. <3.1 should\n        # not match 3.1.dev0, but should match 3.0.dev0).\n        if not spec.is_prerelease and prospective.is_prerelease:\n            if Version(prospective.base_version) == Version(spec.base_version):\n                return False\n\n        # If we've gotten to here, it means that prospective version is both\n        # less than the spec version *and* it's not a pre-release of the same\n        # version in the spec.\n        return True\n\n    @_require_version_compare\n    def _compare_greater_than(self, prospective: ParsedVersion, spec_str: str) -> bool:\n\n        # Convert our spec to a Version instance, since we'll want to work with\n        # it as a version.\n        spec = Version(spec_str)\n\n        # Check to see if the prospective version is greater than the spec\n        # version. If it's not we can short circuit and just return False now\n        # instead of doing extra unneeded work.\n        if not prospective > spec:\n            return False\n\n        # This special case is here so that, unless the specifier itself\n        # includes is a post-release version, that we do not accept\n        # post-release versions for the version mentioned in the specifier\n        # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).\n        if not spec.is_postrelease and prospective.is_postrelease:\n            if Version(prospective.base_version) == Version(spec.base_version):\n                return False\n\n        # Ensure that we do not allow a local version of the version mentioned\n        # in the specifier, which is technically greater than, to match.\n        if prospective.local is not None:\n            if Version(prospective.base_version) == Version(spec.base_version):\n                return False\n\n        # If we've gotten to here, it means that prospective version is both\n        # greater than the spec version *and* it's not a pre-release of the\n        # same version in the spec.\n        return True\n\n    def _compare_arbitrary(self, prospective: Version, spec: str) -> bool:\n        return str(prospective).lower() == str(spec).lower()\n\n    @property\n    def prereleases(self) -> bool:\n\n        # If there is an explicit prereleases set for this, then we'll just\n        # blindly use that.\n        if self._prereleases is not None:\n            return self._prereleases\n\n        # Look at all of our specifiers and determine if they are inclusive\n        # operators, and if they are if they are including an explicit\n        # prerelease.\n        operator, version = self._spec\n        if operator in [\"==\", \">=\", \"<=\", \"~=\", \"===\"]:\n            # The == specifier can include a trailing .*, if it does we\n            # want to remove before parsing.\n            if operator == \"==\" and version.endswith(\".*\"):\n                version = version[:-2]\n\n            # Parse the version, and if it is a pre-release than this\n            # specifier allows pre-releases.\n            if parse(version).is_prerelease:\n                return True\n\n        return False\n\n    @prereleases.setter\n    def prereleases(self, value: bool) -> None:\n        self._prereleases = value\n\n\n_prefix_regex = re.compile(r\"^([0-9]+)((?:a|b|c|rc)[0-9]+)$\")\n\n\ndef _version_split(version: str) -> List[str]:\n    result: List[str] = []\n    for item in version.split(\".\"):\n        match = _prefix_regex.search(item)\n        if match:\n            result.extend(match.groups())\n        else:\n            result.append(item)\n    return result\n\n\ndef _is_not_suffix(segment: str) -> bool:\n    return not any(\n        segment.startswith(prefix) for prefix in (\"dev\", \"a\", \"b\", \"rc\", \"post\")\n    )\n\n\ndef _pad_version(left: List[str], right: List[str]) -> Tuple[List[str], List[str]]:\n    left_split, right_split = [], []\n\n    # Get the release segment of our versions\n    left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left)))\n    right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right)))\n\n    # Get the rest of our versions\n    left_split.append(left[len(left_split[0]) :])\n    right_split.append(right[len(right_split[0]) :])\n\n    # Insert our padding\n    left_split.insert(1, [\"0\"] * max(0, len(right_split[0]) - len(left_split[0])))\n    right_split.insert(1, [\"0\"] * max(0, len(left_split[0]) - len(right_split[0])))\n\n    return (list(itertools.chain(*left_split)), list(itertools.chain(*right_split)))\n\n\nclass SpecifierSet(BaseSpecifier):\n    def __init__(\n        self, specifiers: str = \"\", prereleases: Optional[bool] = None\n    ) -> None:\n\n        # Split on , to break each individual specifier into it's own item, and\n        # strip each item to remove leading/trailing whitespace.\n        split_specifiers = [s.strip() for s in specifiers.split(\",\") if s.strip()]\n\n        # Parsed each individual specifier, attempting first to make it a\n        # Specifier and falling back to a LegacySpecifier.\n        parsed: Set[_IndividualSpecifier] = set()\n        for specifier in split_specifiers:\n            try:\n                parsed.add(Specifier(specifier))\n            except InvalidSpecifier:\n                parsed.add(LegacySpecifier(specifier))\n\n        # Turn our parsed specifiers into a frozen set and save them for later.\n        self._specs = frozenset(parsed)\n\n        # Store our prereleases value so we can use it later to determine if\n        # we accept prereleases or not.\n        self._prereleases = prereleases\n\n    def __repr__(self) -> str:\n        pre = (\n            f\", prereleases={self.prereleases!r}\"\n            if self._prereleases is not None\n            else \"\"\n        )\n\n        return f\"<SpecifierSet({str(self)!r}{pre})>\"\n\n    def __str__(self) -> str:\n        return \",\".join(sorted(str(s) for s in self._specs))\n\n    def __hash__(self) -> int:\n        return hash(self._specs)\n\n    def __and__(self, other: Union[\"SpecifierSet\", str]) -> \"SpecifierSet\":\n        if isinstance(other, str):\n            other = SpecifierSet(other)\n        elif not isinstance(other, SpecifierSet):\n            return NotImplemented\n\n        specifier = SpecifierSet()\n        specifier._specs = frozenset(self._specs | other._specs)\n\n        if self._prereleases is None and other._prereleases is not None:\n            specifier._prereleases = other._prereleases\n        elif self._prereleases is not None and other._prereleases is None:\n            specifier._prereleases = self._prereleases\n        elif self._prereleases == other._prereleases:\n            specifier._prereleases = self._prereleases\n        else:\n            raise ValueError(\n                \"Cannot combine SpecifierSets with True and False prerelease \"\n                \"overrides.\"\n            )\n\n        return specifier\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, (str, _IndividualSpecifier)):\n            other = SpecifierSet(str(other))\n        elif not isinstance(other, SpecifierSet):\n            return NotImplemented\n\n        return self._specs == other._specs\n\n    def __len__(self) -> int:\n        return len(self._specs)\n\n    def __iter__(self) -> Iterator[_IndividualSpecifier]:\n        return iter(self._specs)\n\n    @property\n    def prereleases(self) -> Optional[bool]:\n\n        # If we have been given an explicit prerelease modifier, then we'll\n        # pass that through here.\n        if self._prereleases is not None:\n            return self._prereleases\n\n        # If we don't have any specifiers, and we don't have a forced value,\n        # then we'll just return None since we don't know if this should have\n        # pre-releases or not.\n        if not self._specs:\n            return None\n\n        # Otherwise we'll see if any of the given specifiers accept\n        # prereleases, if any of them do we'll return True, otherwise False.\n        return any(s.prereleases for s in self._specs)\n\n    @prereleases.setter\n    def prereleases(self, value: bool) -> None:\n        self._prereleases = value\n\n    def __contains__(self, item: UnparsedVersion) -> bool:\n        return self.contains(item)\n\n    def contains(\n        self, item: UnparsedVersion, prereleases: Optional[bool] = None\n    ) -> bool:\n\n        # Ensure that our item is a Version or LegacyVersion instance.\n        if not isinstance(item, (LegacyVersion, Version)):\n            item = parse(item)\n\n        # Determine if we're forcing a prerelease or not, if we're not forcing\n        # one for this particular filter call, then we'll use whatever the\n        # SpecifierSet thinks for whether or not we should support prereleases.\n        if prereleases is None:\n            prereleases = self.prereleases\n\n        # We can determine if we're going to allow pre-releases by looking to\n        # see if any of the underlying items supports them. If none of them do\n        # and this item is a pre-release then we do not allow it and we can\n        # short circuit that here.\n        # Note: This means that 1.0.dev1 would not be contained in something\n        #       like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0\n        if not prereleases and item.is_prerelease:\n            return False\n\n        # We simply dispatch to the underlying specs here to make sure that the\n        # given version is contained within all of them.\n        # Note: This use of all() here means that an empty set of specifiers\n        #       will always return True, this is an explicit design decision.\n        return all(s.contains(item, prereleases=prereleases) for s in self._specs)\n\n    def filter(\n        self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None\n    ) -> Iterable[VersionTypeVar]:\n\n        # Determine if we're forcing a prerelease or not, if we're not forcing\n        # one for this particular filter call, then we'll use whatever the\n        # SpecifierSet thinks for whether or not we should support prereleases.\n        if prereleases is None:\n            prereleases = self.prereleases\n\n        # If we have any specifiers, then we want to wrap our iterable in the\n        # filter method for each one, this will act as a logical AND amongst\n        # each specifier.\n        if self._specs:\n            for spec in self._specs:\n                iterable = spec.filter(iterable, prereleases=bool(prereleases))\n            return iterable\n        # If we do not have any specifiers, then we need to have a rough filter\n        # which will filter out any pre-releases, unless there are no final\n        # releases, and which will filter out LegacyVersion in general.\n        else:\n            filtered: List[VersionTypeVar] = []\n            found_prereleases: List[VersionTypeVar] = []\n\n            item: UnparsedVersion\n            parsed_version: Union[Version, LegacyVersion]\n\n            for item in iterable:\n                # Ensure that we some kind of Version class for this item.\n                if not isinstance(item, (LegacyVersion, Version)):\n                    parsed_version = parse(item)\n                else:\n                    parsed_version = item\n\n                # Filter out any item which is parsed as a LegacyVersion\n                if isinstance(parsed_version, LegacyVersion):\n                    continue\n\n                # Store any item which is a pre-release for later unless we've\n                # already found a final version or we are accepting prereleases\n                if parsed_version.is_prerelease and not prereleases:\n                    if not filtered:\n                        found_prereleases.append(item)\n                else:\n                    filtered.append(item)\n\n            # If we've found no items except for pre-releases, then we'll go\n            # ahead and use the pre-releases\n            if not filtered and found_prereleases and prereleases is None:\n                return found_prereleases\n\n            return filtered\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/packaging/tags.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport logging\nimport platform\nimport sys\nimport sysconfig\nfrom importlib.machinery import EXTENSION_SUFFIXES\nfrom typing import (\n    Dict,\n    FrozenSet,\n    Iterable,\n    Iterator,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n    cast,\n)\n\nfrom . import _manylinux, _musllinux\n\nlogger = logging.getLogger(__name__)\n\nPythonVersion = Sequence[int]\nMacVersion = Tuple[int, int]\n\nINTERPRETER_SHORT_NAMES: Dict[str, str] = {\n    \"python\": \"py\",  # Generic.\n    \"cpython\": \"cp\",\n    \"pypy\": \"pp\",\n    \"ironpython\": \"ip\",\n    \"jython\": \"jy\",\n}\n\n\n_32_BIT_INTERPRETER = sys.maxsize <= 2 ** 32\n\n\nclass Tag:\n    \"\"\"\n    A representation of the tag triple for a wheel.\n\n    Instances are considered immutable and thus are hashable. Equality checking\n    is also supported.\n    \"\"\"\n\n    __slots__ = [\"_interpreter\", \"_abi\", \"_platform\", \"_hash\"]\n\n    def __init__(self, interpreter: str, abi: str, platform: str) -> None:\n        self._interpreter = interpreter.lower()\n        self._abi = abi.lower()\n        self._platform = platform.lower()\n        # The __hash__ of every single element in a Set[Tag] will be evaluated each time\n        # that a set calls its `.disjoint()` method, which may be called hundreds of\n        # times when scanning a page of links for packages with tags matching that\n        # Set[Tag]. Pre-computing the value here produces significant speedups for\n        # downstream consumers.\n        self._hash = hash((self._interpreter, self._abi, self._platform))\n\n    @property\n    def interpreter(self) -> str:\n        return self._interpreter\n\n    @property\n    def abi(self) -> str:\n        return self._abi\n\n    @property\n    def platform(self) -> str:\n        return self._platform\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Tag):\n            return NotImplemented\n\n        return (\n            (self._hash == other._hash)  # Short-circuit ASAP for perf reasons.\n            and (self._platform == other._platform)\n            and (self._abi == other._abi)\n            and (self._interpreter == other._interpreter)\n        )\n\n    def __hash__(self) -> int:\n        return self._hash\n\n    def __str__(self) -> str:\n        return f\"{self._interpreter}-{self._abi}-{self._platform}\"\n\n    def __repr__(self) -> str:\n        return f\"<{self} @ {id(self)}>\"\n\n\ndef parse_tag(tag: str) -> FrozenSet[Tag]:\n    \"\"\"\n    Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.\n\n    Returning a set is required due to the possibility that the tag is a\n    compressed tag set.\n    \"\"\"\n    tags = set()\n    interpreters, abis, platforms = tag.split(\"-\")\n    for interpreter in interpreters.split(\".\"):\n        for abi in abis.split(\".\"):\n            for platform_ in platforms.split(\".\"):\n                tags.add(Tag(interpreter, abi, platform_))\n    return frozenset(tags)\n\n\ndef _get_config_var(name: str, warn: bool = False) -> Union[int, str, None]:\n    value = sysconfig.get_config_var(name)\n    if value is None and warn:\n        logger.debug(\n            \"Config variable '%s' is unset, Python ABI tag may be incorrect\", name\n        )\n    return value\n\n\ndef _normalize_string(string: str) -> str:\n    return string.replace(\".\", \"_\").replace(\"-\", \"_\")\n\n\ndef _abi3_applies(python_version: PythonVersion) -> bool:\n    \"\"\"\n    Determine if the Python version supports abi3.\n\n    PEP 384 was first implemented in Python 3.2.\n    \"\"\"\n    return len(python_version) > 1 and tuple(python_version) >= (3, 2)\n\n\ndef _cpython_abis(py_version: PythonVersion, warn: bool = False) -> List[str]:\n    py_version = tuple(py_version)  # To allow for version comparison.\n    abis = []\n    version = _version_nodot(py_version[:2])\n    debug = pymalloc = ucs4 = \"\"\n    with_debug = _get_config_var(\"Py_DEBUG\", warn)\n    has_refcount = hasattr(sys, \"gettotalrefcount\")\n    # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled\n    # extension modules is the best option.\n    # https://github.com/pypa/pip/issues/3383#issuecomment-173267692\n    has_ext = \"_d.pyd\" in EXTENSION_SUFFIXES\n    if with_debug or (with_debug is None and (has_refcount or has_ext)):\n        debug = \"d\"\n    if py_version < (3, 8):\n        with_pymalloc = _get_config_var(\"WITH_PYMALLOC\", warn)\n        if with_pymalloc or with_pymalloc is None:\n            pymalloc = \"m\"\n        if py_version < (3, 3):\n            unicode_size = _get_config_var(\"Py_UNICODE_SIZE\", warn)\n            if unicode_size == 4 or (\n                unicode_size is None and sys.maxunicode == 0x10FFFF\n            ):\n                ucs4 = \"u\"\n    elif debug:\n        # Debug builds can also load \"normal\" extension modules.\n        # We can also assume no UCS-4 or pymalloc requirement.\n        abis.append(f\"cp{version}\")\n    abis.insert(\n        0,\n        \"cp{version}{debug}{pymalloc}{ucs4}\".format(\n            version=version, debug=debug, pymalloc=pymalloc, ucs4=ucs4\n        ),\n    )\n    return abis\n\n\ndef cpython_tags(\n    python_version: Optional[PythonVersion] = None,\n    abis: Optional[Iterable[str]] = None,\n    platforms: Optional[Iterable[str]] = None,\n    *,\n    warn: bool = False,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the tags for a CPython interpreter.\n\n    The tags consist of:\n    - cp<python_version>-<abi>-<platform>\n    - cp<python_version>-abi3-<platform>\n    - cp<python_version>-none-<platform>\n    - cp<less than python_version>-abi3-<platform>  # Older Python versions down to 3.2.\n\n    If python_version only specifies a major version then user-provided ABIs and\n    the 'none' ABItag will be used.\n\n    If 'abi3' or 'none' are specified in 'abis' then they will be yielded at\n    their normal position and not at the beginning.\n    \"\"\"\n    if not python_version:\n        python_version = sys.version_info[:2]\n\n    interpreter = f\"cp{_version_nodot(python_version[:2])}\"\n\n    if abis is None:\n        if len(python_version) > 1:\n            abis = _cpython_abis(python_version, warn)\n        else:\n            abis = []\n    abis = list(abis)\n    # 'abi3' and 'none' are explicitly handled later.\n    for explicit_abi in (\"abi3\", \"none\"):\n        try:\n            abis.remove(explicit_abi)\n        except ValueError:\n            pass\n\n    platforms = list(platforms or platform_tags())\n    for abi in abis:\n        for platform_ in platforms:\n            yield Tag(interpreter, abi, platform_)\n    if _abi3_applies(python_version):\n        yield from (Tag(interpreter, \"abi3\", platform_) for platform_ in platforms)\n    yield from (Tag(interpreter, \"none\", platform_) for platform_ in platforms)\n\n    if _abi3_applies(python_version):\n        for minor_version in range(python_version[1] - 1, 1, -1):\n            for platform_ in platforms:\n                interpreter = \"cp{version}\".format(\n                    version=_version_nodot((python_version[0], minor_version))\n                )\n                yield Tag(interpreter, \"abi3\", platform_)\n\n\ndef _generic_abi() -> Iterator[str]:\n    abi = sysconfig.get_config_var(\"SOABI\")\n    if abi:\n        yield _normalize_string(abi)\n\n\ndef generic_tags(\n    interpreter: Optional[str] = None,\n    abis: Optional[Iterable[str]] = None,\n    platforms: Optional[Iterable[str]] = None,\n    *,\n    warn: bool = False,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the tags for a generic interpreter.\n\n    The tags consist of:\n    - <interpreter>-<abi>-<platform>\n\n    The \"none\" ABI will be added if it was not explicitly provided.\n    \"\"\"\n    if not interpreter:\n        interp_name = interpreter_name()\n        interp_version = interpreter_version(warn=warn)\n        interpreter = \"\".join([interp_name, interp_version])\n    if abis is None:\n        abis = _generic_abi()\n    platforms = list(platforms or platform_tags())\n    abis = list(abis)\n    if \"none\" not in abis:\n        abis.append(\"none\")\n    for abi in abis:\n        for platform_ in platforms:\n            yield Tag(interpreter, abi, platform_)\n\n\ndef _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]:\n    \"\"\"\n    Yields Python versions in descending order.\n\n    After the latest version, the major-only version will be yielded, and then\n    all previous versions of that major version.\n    \"\"\"\n    if len(py_version) > 1:\n        yield f\"py{_version_nodot(py_version[:2])}\"\n    yield f\"py{py_version[0]}\"\n    if len(py_version) > 1:\n        for minor in range(py_version[1] - 1, -1, -1):\n            yield f\"py{_version_nodot((py_version[0], minor))}\"\n\n\ndef compatible_tags(\n    python_version: Optional[PythonVersion] = None,\n    interpreter: Optional[str] = None,\n    platforms: Optional[Iterable[str]] = None,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the sequence of tags that are compatible with a specific version of Python.\n\n    The tags consist of:\n    - py*-none-<platform>\n    - <interpreter>-none-any  # ... if `interpreter` is provided.\n    - py*-none-any\n    \"\"\"\n    if not python_version:\n        python_version = sys.version_info[:2]\n    platforms = list(platforms or platform_tags())\n    for version in _py_interpreter_range(python_version):\n        for platform_ in platforms:\n            yield Tag(version, \"none\", platform_)\n    if interpreter:\n        yield Tag(interpreter, \"none\", \"any\")\n    for version in _py_interpreter_range(python_version):\n        yield Tag(version, \"none\", \"any\")\n\n\ndef _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str:\n    if not is_32bit:\n        return arch\n\n    if arch.startswith(\"ppc\"):\n        return \"ppc\"\n\n    return \"i386\"\n\n\ndef _mac_binary_formats(version: MacVersion, cpu_arch: str) -> List[str]:\n    formats = [cpu_arch]\n    if cpu_arch == \"x86_64\":\n        if version < (10, 4):\n            return []\n        formats.extend([\"intel\", \"fat64\", \"fat32\"])\n\n    elif cpu_arch == \"i386\":\n        if version < (10, 4):\n            return []\n        formats.extend([\"intel\", \"fat32\", \"fat\"])\n\n    elif cpu_arch == \"ppc64\":\n        # TODO: Need to care about 32-bit PPC for ppc64 through 10.2?\n        if version > (10, 5) or version < (10, 4):\n            return []\n        formats.append(\"fat64\")\n\n    elif cpu_arch == \"ppc\":\n        if version > (10, 6):\n            return []\n        formats.extend([\"fat32\", \"fat\"])\n\n    if cpu_arch in {\"arm64\", \"x86_64\"}:\n        formats.append(\"universal2\")\n\n    if cpu_arch in {\"x86_64\", \"i386\", \"ppc64\", \"ppc\", \"intel\"}:\n        formats.append(\"universal\")\n\n    return formats\n\n\ndef mac_platforms(\n    version: Optional[MacVersion] = None, arch: Optional[str] = None\n) -> Iterator[str]:\n    \"\"\"\n    Yields the platform tags for a macOS system.\n\n    The `version` parameter is a two-item tuple specifying the macOS version to\n    generate platform tags for. The `arch` parameter is the CPU architecture to\n    generate platform tags for. Both parameters default to the appropriate value\n    for the current system.\n    \"\"\"\n    version_str, _, cpu_arch = platform.mac_ver()\n    if version is None:\n        version = cast(\"MacVersion\", tuple(map(int, version_str.split(\".\")[:2])))\n    else:\n        version = version\n    if arch is None:\n        arch = _mac_arch(cpu_arch)\n    else:\n        arch = arch\n\n    if (10, 0) <= version and version < (11, 0):\n        # Prior to Mac OS 11, each yearly release of Mac OS bumped the\n        # \"minor\" version number.  The major version was always 10.\n        for minor_version in range(version[1], -1, -1):\n            compat_version = 10, minor_version\n            binary_formats = _mac_binary_formats(compat_version, arch)\n            for binary_format in binary_formats:\n                yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                    major=10, minor=minor_version, binary_format=binary_format\n                )\n\n    if version >= (11, 0):\n        # Starting with Mac OS 11, each yearly release bumps the major version\n        # number.   The minor versions are now the midyear updates.\n        for major_version in range(version[0], 10, -1):\n            compat_version = major_version, 0\n            binary_formats = _mac_binary_formats(compat_version, arch)\n            for binary_format in binary_formats:\n                yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                    major=major_version, minor=0, binary_format=binary_format\n                )\n\n    if version >= (11, 0):\n        # Mac OS 11 on x86_64 is compatible with binaries from previous releases.\n        # Arm64 support was introduced in 11.0, so no Arm binaries from previous\n        # releases exist.\n        #\n        # However, the \"universal2\" binary format can have a\n        # macOS version earlier than 11.0 when the x86_64 part of the binary supports\n        # that version of macOS.\n        if arch == \"x86_64\":\n            for minor_version in range(16, 3, -1):\n                compat_version = 10, minor_version\n                binary_formats = _mac_binary_formats(compat_version, arch)\n                for binary_format in binary_formats:\n                    yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                        major=compat_version[0],\n                        minor=compat_version[1],\n                        binary_format=binary_format,\n                    )\n        else:\n            for minor_version in range(16, 3, -1):\n                compat_version = 10, minor_version\n                binary_format = \"universal2\"\n                yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                    major=compat_version[0],\n                    minor=compat_version[1],\n                    binary_format=binary_format,\n                )\n\n\ndef _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]:\n    linux = _normalize_string(sysconfig.get_platform())\n    if is_32bit:\n        if linux == \"linux_x86_64\":\n            linux = \"linux_i686\"\n        elif linux == \"linux_aarch64\":\n            linux = \"linux_armv7l\"\n    _, arch = linux.split(\"_\", 1)\n    yield from _manylinux.platform_tags(linux, arch)\n    yield from _musllinux.platform_tags(arch)\n    yield linux\n\n\ndef _generic_platforms() -> Iterator[str]:\n    yield _normalize_string(sysconfig.get_platform())\n\n\ndef platform_tags() -> Iterator[str]:\n    \"\"\"\n    Provides the platform tags for this installation.\n    \"\"\"\n    if platform.system() == \"Darwin\":\n        return mac_platforms()\n    elif platform.system() == \"Linux\":\n        return _linux_platforms()\n    else:\n        return _generic_platforms()\n\n\ndef interpreter_name() -> str:\n    \"\"\"\n    Returns the name of the running interpreter.\n    \"\"\"\n    name = sys.implementation.name\n    return INTERPRETER_SHORT_NAMES.get(name) or name\n\n\ndef interpreter_version(*, warn: bool = False) -> str:\n    \"\"\"\n    Returns the version of the running interpreter.\n    \"\"\"\n    version = _get_config_var(\"py_version_nodot\", warn=warn)\n    if version:\n        version = str(version)\n    else:\n        version = _version_nodot(sys.version_info[:2])\n    return version\n\n\ndef _version_nodot(version: PythonVersion) -> str:\n    return \"\".join(map(str, version))\n\n\ndef sys_tags(*, warn: bool = False) -> Iterator[Tag]:\n    \"\"\"\n    Returns the sequence of tag triples for the running interpreter.\n\n    The order of the sequence corresponds to priority order for the\n    interpreter, from most to least important.\n    \"\"\"\n\n    interp_name = interpreter_name()\n    if interp_name == \"cp\":\n        yield from cpython_tags(warn=warn)\n    else:\n        yield from generic_tags()\n\n    if interp_name == \"pp\":\n        yield from compatible_tags(interpreter=\"pp3\")\n    else:\n        yield from compatible_tags()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/packaging/utils.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport re\nfrom typing import FrozenSet, NewType, Tuple, Union, cast\n\nfrom .tags import Tag, parse_tag\nfrom .version import InvalidVersion, Version\n\nBuildTag = Union[Tuple[()], Tuple[int, str]]\nNormalizedName = NewType(\"NormalizedName\", str)\n\n\nclass InvalidWheelFilename(ValueError):\n    \"\"\"\n    An invalid wheel filename was found, users should refer to PEP 427.\n    \"\"\"\n\n\nclass InvalidSdistFilename(ValueError):\n    \"\"\"\n    An invalid sdist filename was found, users should refer to the packaging user guide.\n    \"\"\"\n\n\n_canonicalize_regex = re.compile(r\"[-_.]+\")\n# PEP 427: The build number must start with a digit.\n_build_tag_regex = re.compile(r\"(\\d+)(.*)\")\n\n\ndef canonicalize_name(name: str) -> NormalizedName:\n    # This is taken from PEP 503.\n    value = _canonicalize_regex.sub(\"-\", name).lower()\n    return cast(NormalizedName, value)\n\n\ndef canonicalize_version(version: Union[Version, str]) -> str:\n    \"\"\"\n    This is very similar to Version.__str__, but has one subtle difference\n    with the way it handles the release segment.\n    \"\"\"\n    if isinstance(version, str):\n        try:\n            parsed = Version(version)\n        except InvalidVersion:\n            # Legacy versions cannot be normalized\n            return version\n    else:\n        parsed = version\n\n    parts = []\n\n    # Epoch\n    if parsed.epoch != 0:\n        parts.append(f\"{parsed.epoch}!\")\n\n    # Release segment\n    # NB: This strips trailing '.0's to normalize\n    parts.append(re.sub(r\"(\\.0)+$\", \"\", \".\".join(str(x) for x in parsed.release)))\n\n    # Pre-release\n    if parsed.pre is not None:\n        parts.append(\"\".join(str(x) for x in parsed.pre))\n\n    # Post-release\n    if parsed.post is not None:\n        parts.append(f\".post{parsed.post}\")\n\n    # Development release\n    if parsed.dev is not None:\n        parts.append(f\".dev{parsed.dev}\")\n\n    # Local version segment\n    if parsed.local is not None:\n        parts.append(f\"+{parsed.local}\")\n\n    return \"\".join(parts)\n\n\ndef parse_wheel_filename(\n    filename: str,\n) -> Tuple[NormalizedName, Version, BuildTag, FrozenSet[Tag]]:\n    if not filename.endswith(\".whl\"):\n        raise InvalidWheelFilename(\n            f\"Invalid wheel filename (extension must be '.whl'): {filename}\"\n        )\n\n    filename = filename[:-4]\n    dashes = filename.count(\"-\")\n    if dashes not in (4, 5):\n        raise InvalidWheelFilename(\n            f\"Invalid wheel filename (wrong number of parts): {filename}\"\n        )\n\n    parts = filename.split(\"-\", dashes - 2)\n    name_part = parts[0]\n    # See PEP 427 for the rules on escaping the project name\n    if \"__\" in name_part or re.match(r\"^[\\w\\d._]*$\", name_part, re.UNICODE) is None:\n        raise InvalidWheelFilename(f\"Invalid project name: {filename}\")\n    name = canonicalize_name(name_part)\n    version = Version(parts[1])\n    if dashes == 5:\n        build_part = parts[2]\n        build_match = _build_tag_regex.match(build_part)\n        if build_match is None:\n            raise InvalidWheelFilename(\n                f\"Invalid build number: {build_part} in '{filename}'\"\n            )\n        build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2)))\n    else:\n        build = ()\n    tags = parse_tag(parts[-1])\n    return (name, version, build, tags)\n\n\ndef parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]:\n    if filename.endswith(\".tar.gz\"):\n        file_stem = filename[: -len(\".tar.gz\")]\n    elif filename.endswith(\".zip\"):\n        file_stem = filename[: -len(\".zip\")]\n    else:\n        raise InvalidSdistFilename(\n            f\"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):\"\n            f\" {filename}\"\n        )\n\n    # We are requiring a PEP 440 version, which cannot contain dashes,\n    # so we split on the last dash.\n    name_part, sep, version_part = file_stem.rpartition(\"-\")\n    if not sep:\n        raise InvalidSdistFilename(f\"Invalid sdist filename: {filename}\")\n\n    name = canonicalize_name(name_part)\n    version = Version(version_part)\n    return (name, version)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/packaging/version.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport collections\nimport itertools\nimport re\nimport warnings\nfrom typing import Callable, Iterator, List, Optional, SupportsInt, Tuple, Union\n\nfrom ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType\n\n__all__ = [\"parse\", \"Version\", \"LegacyVersion\", \"InvalidVersion\", \"VERSION_PATTERN\"]\n\nInfiniteTypes = Union[InfinityType, NegativeInfinityType]\nPrePostDevType = Union[InfiniteTypes, Tuple[str, int]]\nSubLocalType = Union[InfiniteTypes, int, str]\nLocalType = Union[\n    NegativeInfinityType,\n    Tuple[\n        Union[\n            SubLocalType,\n            Tuple[SubLocalType, str],\n            Tuple[NegativeInfinityType, SubLocalType],\n        ],\n        ...,\n    ],\n]\nCmpKey = Tuple[\n    int, Tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType\n]\nLegacyCmpKey = Tuple[int, Tuple[str, ...]]\nVersionComparisonMethod = Callable[\n    [Union[CmpKey, LegacyCmpKey], Union[CmpKey, LegacyCmpKey]], bool\n]\n\n_Version = collections.namedtuple(\n    \"_Version\", [\"epoch\", \"release\", \"dev\", \"pre\", \"post\", \"local\"]\n)\n\n\ndef parse(version: str) -> Union[\"LegacyVersion\", \"Version\"]:\n    \"\"\"\n    Parse the given version string and return either a :class:`Version` object\n    or a :class:`LegacyVersion` object depending on if the given version is\n    a valid PEP 440 version or a legacy version.\n    \"\"\"\n    try:\n        return Version(version)\n    except InvalidVersion:\n        return LegacyVersion(version)\n\n\nclass InvalidVersion(ValueError):\n    \"\"\"\n    An invalid version was found, users should refer to PEP 440.\n    \"\"\"\n\n\nclass _BaseVersion:\n    _key: Union[CmpKey, LegacyCmpKey]\n\n    def __hash__(self) -> int:\n        return hash(self._key)\n\n    # Please keep the duplicated `isinstance` check\n    # in the six comparisons hereunder\n    # unless you find a way to avoid adding overhead function calls.\n    def __lt__(self, other: \"_BaseVersion\") -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key < other._key\n\n    def __le__(self, other: \"_BaseVersion\") -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key <= other._key\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key == other._key\n\n    def __ge__(self, other: \"_BaseVersion\") -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key >= other._key\n\n    def __gt__(self, other: \"_BaseVersion\") -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key > other._key\n\n    def __ne__(self, other: object) -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key != other._key\n\n\nclass LegacyVersion(_BaseVersion):\n    def __init__(self, version: str) -> None:\n        self._version = str(version)\n        self._key = _legacy_cmpkey(self._version)\n\n        warnings.warn(\n            \"Creating a LegacyVersion has been deprecated and will be \"\n            \"removed in the next major release\",\n            DeprecationWarning,\n        )\n\n    def __str__(self) -> str:\n        return self._version\n\n    def __repr__(self) -> str:\n        return f\"<LegacyVersion('{self}')>\"\n\n    @property\n    def public(self) -> str:\n        return self._version\n\n    @property\n    def base_version(self) -> str:\n        return self._version\n\n    @property\n    def epoch(self) -> int:\n        return -1\n\n    @property\n    def release(self) -> None:\n        return None\n\n    @property\n    def pre(self) -> None:\n        return None\n\n    @property\n    def post(self) -> None:\n        return None\n\n    @property\n    def dev(self) -> None:\n        return None\n\n    @property\n    def local(self) -> None:\n        return None\n\n    @property\n    def is_prerelease(self) -> bool:\n        return False\n\n    @property\n    def is_postrelease(self) -> bool:\n        return False\n\n    @property\n    def is_devrelease(self) -> bool:\n        return False\n\n\n_legacy_version_component_re = re.compile(r\"(\\d+ | [a-z]+ | \\.| -)\", re.VERBOSE)\n\n_legacy_version_replacement_map = {\n    \"pre\": \"c\",\n    \"preview\": \"c\",\n    \"-\": \"final-\",\n    \"rc\": \"c\",\n    \"dev\": \"@\",\n}\n\n\ndef _parse_version_parts(s: str) -> Iterator[str]:\n    for part in _legacy_version_component_re.split(s):\n        part = _legacy_version_replacement_map.get(part, part)\n\n        if not part or part == \".\":\n            continue\n\n        if part[:1] in \"0123456789\":\n            # pad for numeric comparison\n            yield part.zfill(8)\n        else:\n            yield \"*\" + part\n\n    # ensure that alpha/beta/candidate are before final\n    yield \"*final\"\n\n\ndef _legacy_cmpkey(version: str) -> LegacyCmpKey:\n\n    # We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch\n    # greater than or equal to 0. This will effectively put the LegacyVersion,\n    # which uses the defacto standard originally implemented by setuptools,\n    # as before all PEP 440 versions.\n    epoch = -1\n\n    # This scheme is taken from pkg_resources.parse_version setuptools prior to\n    # it's adoption of the packaging library.\n    parts: List[str] = []\n    for part in _parse_version_parts(version.lower()):\n        if part.startswith(\"*\"):\n            # remove \"-\" before a prerelease tag\n            if part < \"*final\":\n                while parts and parts[-1] == \"*final-\":\n                    parts.pop()\n\n            # remove trailing zeros from each series of numeric parts\n            while parts and parts[-1] == \"00000000\":\n                parts.pop()\n\n        parts.append(part)\n\n    return epoch, tuple(parts)\n\n\n# Deliberately not anchored to the start and end of the string, to make it\n# easier for 3rd party code to reuse\nVERSION_PATTERN = r\"\"\"\n    v?\n    (?:\n        (?:(?P<epoch>[0-9]+)!)?                           # epoch\n        (?P<release>[0-9]+(?:\\.[0-9]+)*)                  # release segment\n        (?P<pre>                                          # pre-release\n            [-_\\.]?\n            (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))\n            [-_\\.]?\n            (?P<pre_n>[0-9]+)?\n        )?\n        (?P<post>                                         # post release\n            (?:-(?P<post_n1>[0-9]+))\n            |\n            (?:\n                [-_\\.]?\n                (?P<post_l>post|rev|r)\n                [-_\\.]?\n                (?P<post_n2>[0-9]+)?\n            )\n        )?\n        (?P<dev>                                          # dev release\n            [-_\\.]?\n            (?P<dev_l>dev)\n            [-_\\.]?\n            (?P<dev_n>[0-9]+)?\n        )?\n    )\n    (?:\\+(?P<local>[a-z0-9]+(?:[-_\\.][a-z0-9]+)*))?       # local version\n\"\"\"\n\n\nclass Version(_BaseVersion):\n\n    _regex = re.compile(r\"^\\s*\" + VERSION_PATTERN + r\"\\s*$\", re.VERBOSE | re.IGNORECASE)\n\n    def __init__(self, version: str) -> None:\n\n        # Validate the version and parse it into pieces\n        match = self._regex.search(version)\n        if not match:\n            raise InvalidVersion(f\"Invalid version: '{version}'\")\n\n        # Store the parsed out pieces of the version\n        self._version = _Version(\n            epoch=int(match.group(\"epoch\")) if match.group(\"epoch\") else 0,\n            release=tuple(int(i) for i in match.group(\"release\").split(\".\")),\n            pre=_parse_letter_version(match.group(\"pre_l\"), match.group(\"pre_n\")),\n            post=_parse_letter_version(\n                match.group(\"post_l\"), match.group(\"post_n1\") or match.group(\"post_n2\")\n            ),\n            dev=_parse_letter_version(match.group(\"dev_l\"), match.group(\"dev_n\")),\n            local=_parse_local_version(match.group(\"local\")),\n        )\n\n        # Generate a key which will be used for sorting\n        self._key = _cmpkey(\n            self._version.epoch,\n            self._version.release,\n            self._version.pre,\n            self._version.post,\n            self._version.dev,\n            self._version.local,\n        )\n\n    def __repr__(self) -> str:\n        return f\"<Version('{self}')>\"\n\n    def __str__(self) -> str:\n        parts = []\n\n        # Epoch\n        if self.epoch != 0:\n            parts.append(f\"{self.epoch}!\")\n\n        # Release segment\n        parts.append(\".\".join(str(x) for x in self.release))\n\n        # Pre-release\n        if self.pre is not None:\n            parts.append(\"\".join(str(x) for x in self.pre))\n\n        # Post-release\n        if self.post is not None:\n            parts.append(f\".post{self.post}\")\n\n        # Development release\n        if self.dev is not None:\n            parts.append(f\".dev{self.dev}\")\n\n        # Local version segment\n        if self.local is not None:\n            parts.append(f\"+{self.local}\")\n\n        return \"\".join(parts)\n\n    @property\n    def epoch(self) -> int:\n        _epoch: int = self._version.epoch\n        return _epoch\n\n    @property\n    def release(self) -> Tuple[int, ...]:\n        _release: Tuple[int, ...] = self._version.release\n        return _release\n\n    @property\n    def pre(self) -> Optional[Tuple[str, int]]:\n        _pre: Optional[Tuple[str, int]] = self._version.pre\n        return _pre\n\n    @property\n    def post(self) -> Optional[int]:\n        return self._version.post[1] if self._version.post else None\n\n    @property\n    def dev(self) -> Optional[int]:\n        return self._version.dev[1] if self._version.dev else None\n\n    @property\n    def local(self) -> Optional[str]:\n        if self._version.local:\n            return \".\".join(str(x) for x in self._version.local)\n        else:\n            return None\n\n    @property\n    def public(self) -> str:\n        return str(self).split(\"+\", 1)[0]\n\n    @property\n    def base_version(self) -> str:\n        parts = []\n\n        # Epoch\n        if self.epoch != 0:\n            parts.append(f\"{self.epoch}!\")\n\n        # Release segment\n        parts.append(\".\".join(str(x) for x in self.release))\n\n        return \"\".join(parts)\n\n    @property\n    def is_prerelease(self) -> bool:\n        return self.dev is not None or self.pre is not None\n\n    @property\n    def is_postrelease(self) -> bool:\n        return self.post is not None\n\n    @property\n    def is_devrelease(self) -> bool:\n        return self.dev is not None\n\n    @property\n    def major(self) -> int:\n        return self.release[0] if len(self.release) >= 1 else 0\n\n    @property\n    def minor(self) -> int:\n        return self.release[1] if len(self.release) >= 2 else 0\n\n    @property\n    def micro(self) -> int:\n        return self.release[2] if len(self.release) >= 3 else 0\n\n\ndef _parse_letter_version(\n    letter: str, number: Union[str, bytes, SupportsInt]\n) -> Optional[Tuple[str, int]]:\n\n    if letter:\n        # We consider there to be an implicit 0 in a pre-release if there is\n        # not a numeral associated with it.\n        if number is None:\n            number = 0\n\n        # We normalize any letters to their lower case form\n        letter = letter.lower()\n\n        # We consider some words to be alternate spellings of other words and\n        # in those cases we want to normalize the spellings to our preferred\n        # spelling.\n        if letter == \"alpha\":\n            letter = \"a\"\n        elif letter == \"beta\":\n            letter = \"b\"\n        elif letter in [\"c\", \"pre\", \"preview\"]:\n            letter = \"rc\"\n        elif letter in [\"rev\", \"r\"]:\n            letter = \"post\"\n\n        return letter, int(number)\n    if not letter and number:\n        # We assume if we are given a number, but we are not given a letter\n        # then this is using the implicit post release syntax (e.g. 1.0-1)\n        letter = \"post\"\n\n        return letter, int(number)\n\n    return None\n\n\n_local_version_separators = re.compile(r\"[\\._-]\")\n\n\ndef _parse_local_version(local: str) -> Optional[LocalType]:\n    \"\"\"\n    Takes a string like abc.1.twelve and turns it into (\"abc\", 1, \"twelve\").\n    \"\"\"\n    if local is not None:\n        return tuple(\n            part.lower() if not part.isdigit() else int(part)\n            for part in _local_version_separators.split(local)\n        )\n    return None\n\n\ndef _cmpkey(\n    epoch: int,\n    release: Tuple[int, ...],\n    pre: Optional[Tuple[str, int]],\n    post: Optional[Tuple[str, int]],\n    dev: Optional[Tuple[str, int]],\n    local: Optional[Tuple[SubLocalType]],\n) -> CmpKey:\n\n    # When we compare a release version, we want to compare it with all of the\n    # trailing zeros removed. So we'll use a reverse the list, drop all the now\n    # leading zeros until we come to something non zero, then take the rest\n    # re-reverse it back into the correct order and make it a tuple and use\n    # that for our sorting key.\n    _release = tuple(\n        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))\n    )\n\n    # We need to \"trick\" the sorting algorithm to put 1.0.dev0 before 1.0a0.\n    # We'll do this by abusing the pre segment, but we _only_ want to do this\n    # if there is not a pre or a post segment. If we have one of those then\n    # the normal sorting rules will handle this case correctly.\n    if pre is None and post is None and dev is not None:\n        _pre: PrePostDevType = NegativeInfinity\n    # Versions without a pre-release (except as noted above) should sort after\n    # those with one.\n    elif pre is None:\n        _pre = Infinity\n    else:\n        _pre = pre\n\n    # Versions without a post segment should sort before those with one.\n    if post is None:\n        _post: PrePostDevType = NegativeInfinity\n\n    else:\n        _post = post\n\n    # Versions without a development segment should sort after those with one.\n    if dev is None:\n        _dev: PrePostDevType = Infinity\n\n    else:\n        _dev = dev\n\n    if local is None:\n        # Versions without a local segment should sort before those with one.\n        _local: LocalType = NegativeInfinity\n    else:\n        # Versions with a local segment need that segment parsed to implement\n        # the sorting rules in PEP440.\n        # - Alpha numeric segments sort before numeric segments\n        # - Alpha numeric segments sort lexicographically\n        # - Numeric segments sort numerically\n        # - Shorter versions sort before longer versions when the prefixes\n        #   match exactly\n        _local = tuple(\n            (i, \"\") if isinstance(i, int) else (NegativeInfinity, i) for i in local\n        )\n\n    return epoch, _release, _pre, _post, _dev, _local\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pep517/__init__.py",
    "content": "\"\"\"Wrappers to build Python packages using PEP 517 hooks\n\"\"\"\n\n__version__ = '0.13.0'\n\nfrom .wrappers import *  # noqa: F401, F403\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pep517/_compat.py",
    "content": "__all__ = (\"tomllib\",)\n\nimport sys\n\nif sys.version_info >= (3, 11):\n    import tomllib\nelse:\n    from pip._vendor import tomli as tomllib\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pep517/build.py",
    "content": "\"\"\"Build a project using PEP 517 hooks.\n\"\"\"\nimport argparse\nimport logging\nimport os\nimport shutil\nimport tempfile\n\nfrom ._compat import tomllib\nfrom .envbuild import BuildEnvironment\nfrom .wrappers import Pep517HookCaller\n\nlog = logging.getLogger(__name__)\n\n\ndef validate_system(system):\n    \"\"\"\n    Ensure build system has the requisite fields.\n    \"\"\"\n    required = {'requires', 'build-backend'}\n    if not (required <= set(system)):\n        message = \"Missing required fields: {missing}\".format(\n            missing=required-set(system),\n        )\n        raise ValueError(message)\n\n\ndef load_system(source_dir):\n    \"\"\"\n    Load the build system from a source dir (pyproject.toml).\n    \"\"\"\n    pyproject = os.path.join(source_dir, 'pyproject.toml')\n    with open(pyproject, 'rb') as f:\n        pyproject_data = tomllib.load(f)\n    return pyproject_data['build-system']\n\n\ndef compat_system(source_dir):\n    \"\"\"\n    Given a source dir, attempt to get a build system backend\n    and requirements from pyproject.toml. Fallback to\n    setuptools but only if the file was not found or a build\n    system was not indicated.\n    \"\"\"\n    try:\n        system = load_system(source_dir)\n    except (FileNotFoundError, KeyError):\n        system = {}\n    system.setdefault(\n        'build-backend',\n        'setuptools.build_meta:__legacy__',\n    )\n    system.setdefault('requires', ['setuptools', 'wheel'])\n    return system\n\n\ndef _do_build(hooks, env, dist, dest):\n    get_requires_name = 'get_requires_for_build_{dist}'.format(**locals())\n    get_requires = getattr(hooks, get_requires_name)\n    reqs = get_requires({})\n    log.info('Got build requires: %s', reqs)\n\n    env.pip_install(reqs)\n    log.info('Installed dynamic build dependencies')\n\n    with tempfile.TemporaryDirectory() as td:\n        log.info('Trying to build %s in %s', dist, td)\n        build_name = 'build_{dist}'.format(**locals())\n        build = getattr(hooks, build_name)\n        filename = build(td, {})\n        source = os.path.join(td, filename)\n        shutil.move(source, os.path.join(dest, os.path.basename(filename)))\n\n\ndef build(source_dir, dist, dest=None, system=None):\n    system = system or load_system(source_dir)\n    dest = os.path.join(source_dir, dest or 'dist')\n    os.makedirs(dest, exist_ok=True)\n\n    validate_system(system)\n    hooks = Pep517HookCaller(\n        source_dir, system['build-backend'], system.get('backend-path')\n    )\n\n    with BuildEnvironment() as env:\n        env.pip_install(system['requires'])\n        _do_build(hooks, env, dist, dest)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n    'source_dir',\n    help=\"A directory containing pyproject.toml\",\n)\nparser.add_argument(\n    '--binary', '-b',\n    action='store_true',\n    default=False,\n)\nparser.add_argument(\n    '--source', '-s',\n    action='store_true',\n    default=False,\n)\nparser.add_argument(\n    '--out-dir', '-o',\n    help=\"Destination in which to save the builds relative to source dir\",\n)\n\n\ndef main(args):\n    log.warning('pep517.build is deprecated. '\n                'Consider switching to https://pypi.org/project/build/')\n\n    # determine which dists to build\n    dists = list(filter(None, (\n        'sdist' if args.source or not args.binary else None,\n        'wheel' if args.binary or not args.source else None,\n    )))\n\n    for dist in dists:\n        build(args.source_dir, dist, args.out_dir)\n\n\nif __name__ == '__main__':\n    main(parser.parse_args())\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pep517/check.py",
    "content": "\"\"\"Check a project and backend by attempting to build using PEP 517 hooks.\n\"\"\"\nimport argparse\nimport logging\nimport os\nimport shutil\nimport sys\nimport tarfile\nimport zipfile\nfrom os.path import isfile\nfrom os.path import join as pjoin\nfrom subprocess import CalledProcessError\nfrom tempfile import mkdtemp\n\nfrom ._compat import tomllib\nfrom .colorlog import enable_colourful_output\nfrom .envbuild import BuildEnvironment\nfrom .wrappers import Pep517HookCaller\n\nlog = logging.getLogger(__name__)\n\n\ndef check_build_sdist(hooks, build_sys_requires):\n    with BuildEnvironment() as env:\n        try:\n            env.pip_install(build_sys_requires)\n            log.info('Installed static build dependencies')\n        except CalledProcessError:\n            log.error('Failed to install static build dependencies')\n            return False\n\n        try:\n            reqs = hooks.get_requires_for_build_sdist({})\n            log.info('Got build requires: %s', reqs)\n        except Exception:\n            log.error('Failure in get_requires_for_build_sdist', exc_info=True)\n            return False\n\n        try:\n            env.pip_install(reqs)\n            log.info('Installed dynamic build dependencies')\n        except CalledProcessError:\n            log.error('Failed to install dynamic build dependencies')\n            return False\n\n        td = mkdtemp()\n        log.info('Trying to build sdist in %s', td)\n        try:\n            try:\n                filename = hooks.build_sdist(td, {})\n                log.info('build_sdist returned %r', filename)\n            except Exception:\n                log.info('Failure in build_sdist', exc_info=True)\n                return False\n\n            if not filename.endswith('.tar.gz'):\n                log.error(\n                    \"Filename %s doesn't have .tar.gz extension\", filename)\n                return False\n\n            path = pjoin(td, filename)\n            if isfile(path):\n                log.info(\"Output file %s exists\", path)\n            else:\n                log.error(\"Output file %s does not exist\", path)\n                return False\n\n            if tarfile.is_tarfile(path):\n                log.info(\"Output file is a tar file\")\n            else:\n                log.error(\"Output file is not a tar file\")\n                return False\n\n        finally:\n            shutil.rmtree(td)\n\n        return True\n\n\ndef check_build_wheel(hooks, build_sys_requires):\n    with BuildEnvironment() as env:\n        try:\n            env.pip_install(build_sys_requires)\n            log.info('Installed static build dependencies')\n        except CalledProcessError:\n            log.error('Failed to install static build dependencies')\n            return False\n\n        try:\n            reqs = hooks.get_requires_for_build_wheel({})\n            log.info('Got build requires: %s', reqs)\n        except Exception:\n            log.error('Failure in get_requires_for_build_sdist', exc_info=True)\n            return False\n\n        try:\n            env.pip_install(reqs)\n            log.info('Installed dynamic build dependencies')\n        except CalledProcessError:\n            log.error('Failed to install dynamic build dependencies')\n            return False\n\n        td = mkdtemp()\n        log.info('Trying to build wheel in %s', td)\n        try:\n            try:\n                filename = hooks.build_wheel(td, {})\n                log.info('build_wheel returned %r', filename)\n            except Exception:\n                log.info('Failure in build_wheel', exc_info=True)\n                return False\n\n            if not filename.endswith('.whl'):\n                log.error(\"Filename %s doesn't have .whl extension\", filename)\n                return False\n\n            path = pjoin(td, filename)\n            if isfile(path):\n                log.info(\"Output file %s exists\", path)\n            else:\n                log.error(\"Output file %s does not exist\", path)\n                return False\n\n            if zipfile.is_zipfile(path):\n                log.info(\"Output file is a zip file\")\n            else:\n                log.error(\"Output file is not a zip file\")\n                return False\n\n        finally:\n            shutil.rmtree(td)\n\n        return True\n\n\ndef check(source_dir):\n    pyproject = pjoin(source_dir, 'pyproject.toml')\n    if isfile(pyproject):\n        log.info('Found pyproject.toml')\n    else:\n        log.error('Missing pyproject.toml')\n        return False\n\n    try:\n        with open(pyproject, 'rb') as f:\n            pyproject_data = tomllib.load(f)\n        # Ensure the mandatory data can be loaded\n        buildsys = pyproject_data['build-system']\n        requires = buildsys['requires']\n        backend = buildsys['build-backend']\n        backend_path = buildsys.get('backend-path')\n        log.info('Loaded pyproject.toml')\n    except (tomllib.TOMLDecodeError, KeyError):\n        log.error(\"Invalid pyproject.toml\", exc_info=True)\n        return False\n\n    hooks = Pep517HookCaller(source_dir, backend, backend_path)\n\n    sdist_ok = check_build_sdist(hooks, requires)\n    wheel_ok = check_build_wheel(hooks, requires)\n\n    if not sdist_ok:\n        log.warning('Sdist checks failed; scroll up to see')\n    if not wheel_ok:\n        log.warning('Wheel checks failed')\n\n    return sdist_ok\n\n\ndef main(argv=None):\n    log.warning('pep517.check is deprecated. '\n                'Consider switching to https://pypi.org/project/build/')\n\n    ap = argparse.ArgumentParser()\n    ap.add_argument(\n        'source_dir',\n        help=\"A directory containing pyproject.toml\")\n    args = ap.parse_args(argv)\n\n    enable_colourful_output()\n\n    ok = check(args.source_dir)\n\n    if ok:\n        print(ansi('Checks passed', 'green'))\n    else:\n        print(ansi('Checks failed', 'red'))\n        sys.exit(1)\n\n\nansi_codes = {\n    'reset': '\\x1b[0m',\n    'bold': '\\x1b[1m',\n    'red': '\\x1b[31m',\n    'green': '\\x1b[32m',\n}\n\n\ndef ansi(s, attr):\n    if os.name != 'nt' and sys.stdout.isatty():\n        return ansi_codes[attr] + str(s) + ansi_codes['reset']\n    else:\n        return str(s)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pep517/colorlog.py",
    "content": "\"\"\"Nicer log formatting with colours.\n\nCode copied from Tornado, Apache licensed.\n\"\"\"\n# Copyright 2012 Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport logging\nimport sys\n\ntry:\n    import curses\nexcept ImportError:\n    curses = None\n\n\ndef _stderr_supports_color():\n    color = False\n    if curses and hasattr(sys.stderr, 'isatty') and sys.stderr.isatty():\n        try:\n            curses.setupterm()\n            if curses.tigetnum(\"colors\") > 0:\n                color = True\n        except Exception:\n            pass\n    return color\n\n\nclass LogFormatter(logging.Formatter):\n    \"\"\"Log formatter with colour support\n    \"\"\"\n    DEFAULT_COLORS = {\n        logging.INFO: 2,  # Green\n        logging.WARNING: 3,  # Yellow\n        logging.ERROR: 1,  # Red\n        logging.CRITICAL: 1,\n    }\n\n    def __init__(self, color=True, datefmt=None):\n        r\"\"\"\n        :arg bool color: Enables color support.\n        :arg string fmt: Log message format.\n        It will be applied to the attributes dict of log records. The\n        text between ``%(color)s`` and ``%(end_color)s`` will be colored\n        depending on the level if color support is on.\n        :arg dict colors: color mappings from logging level to terminal color\n        code\n        :arg string datefmt: Datetime format.\n        Used for formatting ``(asctime)`` placeholder in ``prefix_fmt``.\n        .. versionchanged:: 3.2\n        Added ``fmt`` and ``datefmt`` arguments.\n        \"\"\"\n        logging.Formatter.__init__(self, datefmt=datefmt)\n        self._colors = {}\n        if color and _stderr_supports_color():\n            # The curses module has some str/bytes confusion in\n            # python3. Until version 3.2.3, most methods return\n            # bytes, but only accept strings. In addition, we want to\n            # output these strings with the logging module, which\n            # works with unicode strings. The explicit calls to\n            # unicode() below are harmless in python2 but will do the\n            # right conversion in python 3.\n            fg_color = (curses.tigetstr(\"setaf\") or\n                        curses.tigetstr(\"setf\") or \"\")\n\n            for levelno, code in self.DEFAULT_COLORS.items():\n                self._colors[levelno] = str(\n                    curses.tparm(fg_color, code), \"ascii\")\n            self._normal = str(curses.tigetstr(\"sgr0\"), \"ascii\")\n\n            scr = curses.initscr()\n            self.termwidth = scr.getmaxyx()[1]\n            curses.endwin()\n        else:\n            self._normal = ''\n            # Default width is usually 80, but too wide is\n            # worse than too narrow\n            self.termwidth = 70\n\n    def formatMessage(self, record):\n        mlen = len(record.message)\n        right_text = '{initial}-{name}'.format(initial=record.levelname[0],\n                                               name=record.name)\n        if mlen + len(right_text) < self.termwidth:\n            space = ' ' * (self.termwidth - (mlen + len(right_text)))\n        else:\n            space = '  '\n\n        if record.levelno in self._colors:\n            start_color = self._colors[record.levelno]\n            end_color = self._normal\n        else:\n            start_color = end_color = ''\n\n        return record.message + space + start_color + right_text + end_color\n\n\ndef enable_colourful_output(level=logging.INFO):\n    handler = logging.StreamHandler()\n    handler.setFormatter(LogFormatter())\n    logging.root.addHandler(handler)\n    logging.root.setLevel(level)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pep517/dirtools.py",
    "content": "import io\nimport os\nimport zipfile\n\n\ndef dir_to_zipfile(root):\n    \"\"\"Construct an in-memory zip file for a directory.\"\"\"\n    buffer = io.BytesIO()\n    zip_file = zipfile.ZipFile(buffer, 'w')\n    for root, dirs, files in os.walk(root):\n        for path in dirs:\n            fs_path = os.path.join(root, path)\n            rel_path = os.path.relpath(fs_path, root)\n            zip_file.writestr(rel_path + '/', '')\n        for path in files:\n            fs_path = os.path.join(root, path)\n            rel_path = os.path.relpath(fs_path, root)\n            zip_file.write(fs_path, rel_path)\n    return zip_file\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pep517/envbuild.py",
    "content": "\"\"\"Build wheels/sdists by installing build deps to a temporary environment.\n\"\"\"\n\nimport logging\nimport os\nimport shutil\nimport sys\nfrom subprocess import check_call\nfrom sysconfig import get_paths\nfrom tempfile import mkdtemp\n\nfrom ._compat import tomllib\nfrom .wrappers import LoggerWrapper, Pep517HookCaller\n\nlog = logging.getLogger(__name__)\n\n\ndef _load_pyproject(source_dir):\n    with open(\n            os.path.join(source_dir, 'pyproject.toml'),\n            'rb',\n            ) as f:\n        pyproject_data = tomllib.load(f)\n    buildsys = pyproject_data['build-system']\n    return (\n        buildsys['requires'],\n        buildsys['build-backend'],\n        buildsys.get('backend-path'),\n    )\n\n\nclass BuildEnvironment:\n    \"\"\"Context manager to install build deps in a simple temporary environment\n\n    Based on code I wrote for pip, which is MIT licensed.\n    \"\"\"\n    # Copyright (c) 2008-2016 The pip developers (see AUTHORS.txt file)\n    #\n    # Permission is hereby granted, free of charge, to any person obtaining\n    # a copy of this software and associated documentation files (the\n    # \"Software\"), to deal in the Software without restriction, including\n    # without limitation the rights to use, copy, modify, merge, publish,\n    # distribute, sublicense, and/or sell copies of the Software, and to\n    # permit persons to whom the Software is furnished to do so, subject to\n    # the following conditions:\n    #\n    # The above copyright notice and this permission notice shall be\n    # included in all copies or substantial portions of the Software.\n    #\n    # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n    # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n    # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n    # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n    # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n    # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n    # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n    path = None\n\n    def __init__(self, cleanup=True):\n        self._cleanup = cleanup\n\n    def __enter__(self):\n        self.path = mkdtemp(prefix='pep517-build-env-')\n        log.info('Temporary build environment: %s', self.path)\n\n        self.save_path = os.environ.get('PATH', None)\n        self.save_pythonpath = os.environ.get('PYTHONPATH', None)\n\n        install_scheme = 'nt' if (os.name == 'nt') else 'posix_prefix'\n        install_dirs = get_paths(install_scheme, vars={\n            'base': self.path,\n            'platbase': self.path,\n        })\n\n        scripts = install_dirs['scripts']\n        if self.save_path:\n            os.environ['PATH'] = scripts + os.pathsep + self.save_path\n        else:\n            os.environ['PATH'] = scripts + os.pathsep + os.defpath\n\n        if install_dirs['purelib'] == install_dirs['platlib']:\n            lib_dirs = install_dirs['purelib']\n        else:\n            lib_dirs = install_dirs['purelib'] + os.pathsep + \\\n                install_dirs['platlib']\n        if self.save_pythonpath:\n            os.environ['PYTHONPATH'] = lib_dirs + os.pathsep + \\\n                self.save_pythonpath\n        else:\n            os.environ['PYTHONPATH'] = lib_dirs\n\n        return self\n\n    def pip_install(self, reqs):\n        \"\"\"Install dependencies into this env by calling pip in a subprocess\"\"\"\n        if not reqs:\n            return\n        log.info('Calling pip to install %s', reqs)\n        cmd = [\n            sys.executable, '-m', 'pip', 'install', '--ignore-installed',\n            '--prefix', self.path] + list(reqs)\n        check_call(\n            cmd,\n            stdout=LoggerWrapper(log, logging.INFO),\n            stderr=LoggerWrapper(log, logging.ERROR),\n        )\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        needs_cleanup = (\n            self._cleanup and\n            self.path is not None and\n            os.path.isdir(self.path)\n        )\n        if needs_cleanup:\n            shutil.rmtree(self.path)\n\n        if self.save_path is None:\n            os.environ.pop('PATH', None)\n        else:\n            os.environ['PATH'] = self.save_path\n\n        if self.save_pythonpath is None:\n            os.environ.pop('PYTHONPATH', None)\n        else:\n            os.environ['PYTHONPATH'] = self.save_pythonpath\n\n\ndef build_wheel(source_dir, wheel_dir, config_settings=None):\n    \"\"\"Build a wheel from a source directory using PEP 517 hooks.\n\n    :param str source_dir: Source directory containing pyproject.toml\n    :param str wheel_dir: Target directory to create wheel in\n    :param dict config_settings: Options to pass to build backend\n\n    This is a blocking function which will run pip in a subprocess to install\n    build requirements.\n    \"\"\"\n    if config_settings is None:\n        config_settings = {}\n    requires, backend, backend_path = _load_pyproject(source_dir)\n    hooks = Pep517HookCaller(source_dir, backend, backend_path)\n\n    with BuildEnvironment() as env:\n        env.pip_install(requires)\n        reqs = hooks.get_requires_for_build_wheel(config_settings)\n        env.pip_install(reqs)\n        return hooks.build_wheel(wheel_dir, config_settings)\n\n\ndef build_sdist(source_dir, sdist_dir, config_settings=None):\n    \"\"\"Build an sdist from a source directory using PEP 517 hooks.\n\n    :param str source_dir: Source directory containing pyproject.toml\n    :param str sdist_dir: Target directory to place sdist in\n    :param dict config_settings: Options to pass to build backend\n\n    This is a blocking function which will run pip in a subprocess to install\n    build requirements.\n    \"\"\"\n    if config_settings is None:\n        config_settings = {}\n    requires, backend, backend_path = _load_pyproject(source_dir)\n    hooks = Pep517HookCaller(source_dir, backend, backend_path)\n\n    with BuildEnvironment() as env:\n        env.pip_install(requires)\n        reqs = hooks.get_requires_for_build_sdist(config_settings)\n        env.pip_install(reqs)\n        return hooks.build_sdist(sdist_dir, config_settings)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pep517/in_process/__init__.py",
    "content": "\"\"\"This is a subpackage because the directory is on sys.path for _in_process.py\n\nThe subpackage should stay as empty as possible to avoid shadowing modules that\nthe backend might import.\n\"\"\"\nfrom contextlib import contextmanager\nfrom os.path import abspath, dirname\nfrom os.path import join as pjoin\n\ntry:\n    import importlib.resources as resources\n    try:\n        resources.files\n    except AttributeError:\n        # Python 3.8 compatibility\n        def _in_proc_script_path():\n            return resources.path(__package__, '_in_process.py')\n    else:\n        def _in_proc_script_path():\n            return resources.as_file(\n                resources.files(__package__).joinpath('_in_process.py'))\nexcept ImportError:\n    # Python 3.6 compatibility\n    @contextmanager\n    def _in_proc_script_path():\n        yield pjoin(dirname(abspath(__file__)), '_in_process.py')\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pep517/in_process/_in_process.py",
    "content": "\"\"\"This is invoked in a subprocess to call the build backend hooks.\n\nIt expects:\n- Command line args: hook_name, control_dir\n- Environment variables:\n      PEP517_BUILD_BACKEND=entry.point:spec\n      PEP517_BACKEND_PATH=paths (separated with os.pathsep)\n- control_dir/input.json:\n  - {\"kwargs\": {...}}\n\nResults:\n- control_dir/output.json\n  - {\"return_val\": ...}\n\"\"\"\nimport json\nimport os\nimport os.path\nimport re\nimport shutil\nimport sys\nimport traceback\nfrom glob import glob\nfrom importlib import import_module\nfrom os.path import join as pjoin\n\n# This file is run as a script, and `import wrappers` is not zip-safe, so we\n# include write_json() and read_json() from wrappers.py.\n\n\ndef write_json(obj, path, **kwargs):\n    with open(path, 'w', encoding='utf-8') as f:\n        json.dump(obj, f, **kwargs)\n\n\ndef read_json(path):\n    with open(path, encoding='utf-8') as f:\n        return json.load(f)\n\n\nclass BackendUnavailable(Exception):\n    \"\"\"Raised if we cannot import the backend\"\"\"\n    def __init__(self, traceback):\n        self.traceback = traceback\n\n\nclass BackendInvalid(Exception):\n    \"\"\"Raised if the backend is invalid\"\"\"\n    def __init__(self, message):\n        self.message = message\n\n\nclass HookMissing(Exception):\n    \"\"\"Raised if a hook is missing and we are not executing the fallback\"\"\"\n    def __init__(self, hook_name=None):\n        super().__init__(hook_name)\n        self.hook_name = hook_name\n\n\ndef contained_in(filename, directory):\n    \"\"\"Test if a file is located within the given directory.\"\"\"\n    filename = os.path.normcase(os.path.abspath(filename))\n    directory = os.path.normcase(os.path.abspath(directory))\n    return os.path.commonprefix([filename, directory]) == directory\n\n\ndef _build_backend():\n    \"\"\"Find and load the build backend\"\"\"\n    # Add in-tree backend directories to the front of sys.path.\n    backend_path = os.environ.get('PEP517_BACKEND_PATH')\n    if backend_path:\n        extra_pathitems = backend_path.split(os.pathsep)\n        sys.path[:0] = extra_pathitems\n\n    ep = os.environ['PEP517_BUILD_BACKEND']\n    mod_path, _, obj_path = ep.partition(':')\n    try:\n        obj = import_module(mod_path)\n    except ImportError:\n        raise BackendUnavailable(traceback.format_exc())\n\n    if backend_path:\n        if not any(\n            contained_in(obj.__file__, path)\n            for path in extra_pathitems\n        ):\n            raise BackendInvalid(\"Backend was not loaded from backend-path\")\n\n    if obj_path:\n        for path_part in obj_path.split('.'):\n            obj = getattr(obj, path_part)\n    return obj\n\n\ndef _supported_features():\n    \"\"\"Return the list of options features supported by the backend.\n\n    Returns a list of strings.\n    The only possible value is 'build_editable'.\n    \"\"\"\n    backend = _build_backend()\n    features = []\n    if hasattr(backend, \"build_editable\"):\n        features.append(\"build_editable\")\n    return features\n\n\ndef get_requires_for_build_wheel(config_settings):\n    \"\"\"Invoke the optional get_requires_for_build_wheel hook\n\n    Returns [] if the hook is not defined.\n    \"\"\"\n    backend = _build_backend()\n    try:\n        hook = backend.get_requires_for_build_wheel\n    except AttributeError:\n        return []\n    else:\n        return hook(config_settings)\n\n\ndef get_requires_for_build_editable(config_settings):\n    \"\"\"Invoke the optional get_requires_for_build_editable hook\n\n    Returns [] if the hook is not defined.\n    \"\"\"\n    backend = _build_backend()\n    try:\n        hook = backend.get_requires_for_build_editable\n    except AttributeError:\n        return []\n    else:\n        return hook(config_settings)\n\n\ndef prepare_metadata_for_build_wheel(\n        metadata_directory, config_settings, _allow_fallback):\n    \"\"\"Invoke optional prepare_metadata_for_build_wheel\n\n    Implements a fallback by building a wheel if the hook isn't defined,\n    unless _allow_fallback is False in which case HookMissing is raised.\n    \"\"\"\n    backend = _build_backend()\n    try:\n        hook = backend.prepare_metadata_for_build_wheel\n    except AttributeError:\n        if not _allow_fallback:\n            raise HookMissing()\n        whl_basename = backend.build_wheel(metadata_directory, config_settings)\n        return _get_wheel_metadata_from_wheel(whl_basename, metadata_directory,\n                                              config_settings)\n    else:\n        return hook(metadata_directory, config_settings)\n\n\ndef prepare_metadata_for_build_editable(\n        metadata_directory, config_settings, _allow_fallback):\n    \"\"\"Invoke optional prepare_metadata_for_build_editable\n\n    Implements a fallback by building an editable wheel if the hook isn't\n    defined, unless _allow_fallback is False in which case HookMissing is\n    raised.\n    \"\"\"\n    backend = _build_backend()\n    try:\n        hook = backend.prepare_metadata_for_build_editable\n    except AttributeError:\n        if not _allow_fallback:\n            raise HookMissing()\n        try:\n            build_hook = backend.build_editable\n        except AttributeError:\n            raise HookMissing(hook_name='build_editable')\n        else:\n            whl_basename = build_hook(metadata_directory, config_settings)\n            return _get_wheel_metadata_from_wheel(whl_basename,\n                                                  metadata_directory,\n                                                  config_settings)\n    else:\n        return hook(metadata_directory, config_settings)\n\n\nWHEEL_BUILT_MARKER = 'PEP517_ALREADY_BUILT_WHEEL'\n\n\ndef _dist_info_files(whl_zip):\n    \"\"\"Identify the .dist-info folder inside a wheel ZipFile.\"\"\"\n    res = []\n    for path in whl_zip.namelist():\n        m = re.match(r'[^/\\\\]+-[^/\\\\]+\\.dist-info/', path)\n        if m:\n            res.append(path)\n    if res:\n        return res\n    raise Exception(\"No .dist-info folder found in wheel\")\n\n\ndef _get_wheel_metadata_from_wheel(\n        whl_basename, metadata_directory, config_settings):\n    \"\"\"Extract the metadata from a wheel.\n\n    Fallback for when the build backend does not\n    define the 'get_wheel_metadata' hook.\n    \"\"\"\n    from zipfile import ZipFile\n    with open(os.path.join(metadata_directory, WHEEL_BUILT_MARKER), 'wb'):\n        pass  # Touch marker file\n\n    whl_file = os.path.join(metadata_directory, whl_basename)\n    with ZipFile(whl_file) as zipf:\n        dist_info = _dist_info_files(zipf)\n        zipf.extractall(path=metadata_directory, members=dist_info)\n    return dist_info[0].split('/')[0]\n\n\ndef _find_already_built_wheel(metadata_directory):\n    \"\"\"Check for a wheel already built during the get_wheel_metadata hook.\n    \"\"\"\n    if not metadata_directory:\n        return None\n    metadata_parent = os.path.dirname(metadata_directory)\n    if not os.path.isfile(pjoin(metadata_parent, WHEEL_BUILT_MARKER)):\n        return None\n\n    whl_files = glob(os.path.join(metadata_parent, '*.whl'))\n    if not whl_files:\n        print('Found wheel built marker, but no .whl files')\n        return None\n    if len(whl_files) > 1:\n        print('Found multiple .whl files; unspecified behaviour. '\n              'Will call build_wheel.')\n        return None\n\n    # Exactly one .whl file\n    return whl_files[0]\n\n\ndef build_wheel(wheel_directory, config_settings, metadata_directory=None):\n    \"\"\"Invoke the mandatory build_wheel hook.\n\n    If a wheel was already built in the\n    prepare_metadata_for_build_wheel fallback, this\n    will copy it rather than rebuilding the wheel.\n    \"\"\"\n    prebuilt_whl = _find_already_built_wheel(metadata_directory)\n    if prebuilt_whl:\n        shutil.copy2(prebuilt_whl, wheel_directory)\n        return os.path.basename(prebuilt_whl)\n\n    return _build_backend().build_wheel(wheel_directory, config_settings,\n                                        metadata_directory)\n\n\ndef build_editable(wheel_directory, config_settings, metadata_directory=None):\n    \"\"\"Invoke the optional build_editable hook.\n\n    If a wheel was already built in the\n    prepare_metadata_for_build_editable fallback, this\n    will copy it rather than rebuilding the wheel.\n    \"\"\"\n    backend = _build_backend()\n    try:\n        hook = backend.build_editable\n    except AttributeError:\n        raise HookMissing()\n    else:\n        prebuilt_whl = _find_already_built_wheel(metadata_directory)\n        if prebuilt_whl:\n            shutil.copy2(prebuilt_whl, wheel_directory)\n            return os.path.basename(prebuilt_whl)\n\n        return hook(wheel_directory, config_settings, metadata_directory)\n\n\ndef get_requires_for_build_sdist(config_settings):\n    \"\"\"Invoke the optional get_requires_for_build_wheel hook\n\n    Returns [] if the hook is not defined.\n    \"\"\"\n    backend = _build_backend()\n    try:\n        hook = backend.get_requires_for_build_sdist\n    except AttributeError:\n        return []\n    else:\n        return hook(config_settings)\n\n\nclass _DummyException(Exception):\n    \"\"\"Nothing should ever raise this exception\"\"\"\n\n\nclass GotUnsupportedOperation(Exception):\n    \"\"\"For internal use when backend raises UnsupportedOperation\"\"\"\n    def __init__(self, traceback):\n        self.traceback = traceback\n\n\ndef build_sdist(sdist_directory, config_settings):\n    \"\"\"Invoke the mandatory build_sdist hook.\"\"\"\n    backend = _build_backend()\n    try:\n        return backend.build_sdist(sdist_directory, config_settings)\n    except getattr(backend, 'UnsupportedOperation', _DummyException):\n        raise GotUnsupportedOperation(traceback.format_exc())\n\n\nHOOK_NAMES = {\n    'get_requires_for_build_wheel',\n    'prepare_metadata_for_build_wheel',\n    'build_wheel',\n    'get_requires_for_build_editable',\n    'prepare_metadata_for_build_editable',\n    'build_editable',\n    'get_requires_for_build_sdist',\n    'build_sdist',\n    '_supported_features',\n}\n\n\ndef main():\n    if len(sys.argv) < 3:\n        sys.exit(\"Needs args: hook_name, control_dir\")\n    hook_name = sys.argv[1]\n    control_dir = sys.argv[2]\n    if hook_name not in HOOK_NAMES:\n        sys.exit(\"Unknown hook: %s\" % hook_name)\n    hook = globals()[hook_name]\n\n    hook_input = read_json(pjoin(control_dir, 'input.json'))\n\n    json_out = {'unsupported': False, 'return_val': None}\n    try:\n        json_out['return_val'] = hook(**hook_input['kwargs'])\n    except BackendUnavailable as e:\n        json_out['no_backend'] = True\n        json_out['traceback'] = e.traceback\n    except BackendInvalid as e:\n        json_out['backend_invalid'] = True\n        json_out['backend_error'] = e.message\n    except GotUnsupportedOperation as e:\n        json_out['unsupported'] = True\n        json_out['traceback'] = e.traceback\n    except HookMissing as e:\n        json_out['hook_missing'] = True\n        json_out['missing_hook_name'] = e.hook_name or hook_name\n\n    write_json(json_out, pjoin(control_dir, 'output.json'), indent=2)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pep517/meta.py",
    "content": "\"\"\"Build metadata for a project using PEP 517 hooks.\n\"\"\"\nimport argparse\nimport functools\nimport logging\nimport os\nimport shutil\nimport tempfile\n\ntry:\n    import importlib.metadata as imp_meta\nexcept ImportError:\n    import importlib_metadata as imp_meta\n\ntry:\n    from zipfile import Path\nexcept ImportError:\n    from zipp import Path\n\nfrom .build import compat_system, load_system, validate_system\nfrom .dirtools import dir_to_zipfile\nfrom .envbuild import BuildEnvironment\nfrom .wrappers import Pep517HookCaller, quiet_subprocess_runner\n\nlog = logging.getLogger(__name__)\n\n\ndef _prep_meta(hooks, env, dest):\n    reqs = hooks.get_requires_for_build_wheel({})\n    log.info('Got build requires: %s', reqs)\n\n    env.pip_install(reqs)\n    log.info('Installed dynamic build dependencies')\n\n    with tempfile.TemporaryDirectory() as td:\n        log.info('Trying to build metadata in %s', td)\n        filename = hooks.prepare_metadata_for_build_wheel(td, {})\n        source = os.path.join(td, filename)\n        shutil.move(source, os.path.join(dest, os.path.basename(filename)))\n\n\ndef build(source_dir='.', dest=None, system=None):\n    system = system or load_system(source_dir)\n    dest = os.path.join(source_dir, dest or 'dist')\n    os.makedirs(dest, exist_ok=True)\n    validate_system(system)\n    hooks = Pep517HookCaller(\n        source_dir, system['build-backend'], system.get('backend-path')\n    )\n\n    with hooks.subprocess_runner(quiet_subprocess_runner):\n        with BuildEnvironment() as env:\n            env.pip_install(system['requires'])\n            _prep_meta(hooks, env, dest)\n\n\ndef build_as_zip(builder=build):\n    with tempfile.TemporaryDirectory() as out_dir:\n        builder(dest=out_dir)\n        return dir_to_zipfile(out_dir)\n\n\ndef load(root):\n    \"\"\"\n    Given a source directory (root) of a package,\n    return an importlib.metadata.Distribution object\n    with metadata build from that package.\n    \"\"\"\n    root = os.path.expanduser(root)\n    system = compat_system(root)\n    builder = functools.partial(build, source_dir=root, system=system)\n    path = Path(build_as_zip(builder))\n    return imp_meta.PathDistribution(path)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\n    'source_dir',\n    help=\"A directory containing pyproject.toml\",\n)\nparser.add_argument(\n    '--out-dir', '-o',\n    help=\"Destination in which to save the builds relative to source dir\",\n)\n\n\ndef main():\n    args = parser.parse_args()\n    build(args.source_dir, args.out_dir)\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pep517/wrappers.py",
    "content": "import json\nimport os\nimport sys\nimport tempfile\nimport threading\nfrom contextlib import contextmanager\nfrom os.path import abspath\nfrom os.path import join as pjoin\nfrom subprocess import STDOUT, check_call, check_output\n\nfrom .in_process import _in_proc_script_path\n\n__all__ = [\n    'BackendUnavailable',\n    'BackendInvalid',\n    'HookMissing',\n    'UnsupportedOperation',\n    'default_subprocess_runner',\n    'quiet_subprocess_runner',\n    'Pep517HookCaller',\n]\n\n\ndef write_json(obj, path, **kwargs):\n    with open(path, 'w', encoding='utf-8') as f:\n        json.dump(obj, f, **kwargs)\n\n\ndef read_json(path):\n    with open(path, encoding='utf-8') as f:\n        return json.load(f)\n\n\nclass BackendUnavailable(Exception):\n    \"\"\"Will be raised if the backend cannot be imported in the hook process.\"\"\"\n    def __init__(self, traceback):\n        self.traceback = traceback\n\n\nclass BackendInvalid(Exception):\n    \"\"\"Will be raised if the backend is invalid.\"\"\"\n    def __init__(self, backend_name, backend_path, message):\n        self.backend_name = backend_name\n        self.backend_path = backend_path\n        self.message = message\n\n\nclass HookMissing(Exception):\n    \"\"\"Will be raised on missing hooks.\"\"\"\n    def __init__(self, hook_name):\n        super().__init__(hook_name)\n        self.hook_name = hook_name\n\n\nclass UnsupportedOperation(Exception):\n    \"\"\"May be raised by build_sdist if the backend indicates that it can't.\"\"\"\n    def __init__(self, traceback):\n        self.traceback = traceback\n\n\ndef default_subprocess_runner(cmd, cwd=None, extra_environ=None):\n    \"\"\"The default method of calling the wrapper subprocess.\"\"\"\n    env = os.environ.copy()\n    if extra_environ:\n        env.update(extra_environ)\n\n    check_call(cmd, cwd=cwd, env=env)\n\n\ndef quiet_subprocess_runner(cmd, cwd=None, extra_environ=None):\n    \"\"\"A method of calling the wrapper subprocess while suppressing output.\"\"\"\n    env = os.environ.copy()\n    if extra_environ:\n        env.update(extra_environ)\n\n    check_output(cmd, cwd=cwd, env=env, stderr=STDOUT)\n\n\ndef norm_and_check(source_tree, requested):\n    \"\"\"Normalise and check a backend path.\n\n    Ensure that the requested backend path is specified as a relative path,\n    and resolves to a location under the given source tree.\n\n    Return an absolute version of the requested path.\n    \"\"\"\n    if os.path.isabs(requested):\n        raise ValueError(\"paths must be relative\")\n\n    abs_source = os.path.abspath(source_tree)\n    abs_requested = os.path.normpath(os.path.join(abs_source, requested))\n    # We have to use commonprefix for Python 2.7 compatibility. So we\n    # normalise case to avoid problems because commonprefix is a character\n    # based comparison :-(\n    norm_source = os.path.normcase(abs_source)\n    norm_requested = os.path.normcase(abs_requested)\n    if os.path.commonprefix([norm_source, norm_requested]) != norm_source:\n        raise ValueError(\"paths must be inside source tree\")\n\n    return abs_requested\n\n\nclass Pep517HookCaller:\n    \"\"\"A wrapper around a source directory to be built with a PEP 517 backend.\n\n    :param source_dir: The path to the source directory, containing\n        pyproject.toml.\n    :param build_backend: The build backend spec, as per PEP 517, from\n        pyproject.toml.\n    :param backend_path: The backend path, as per PEP 517, from pyproject.toml.\n    :param runner: A callable that invokes the wrapper subprocess.\n    :param python_executable: The Python executable used to invoke the backend\n\n    The 'runner', if provided, must expect the following:\n\n    - cmd: a list of strings representing the command and arguments to\n      execute, as would be passed to e.g. 'subprocess.check_call'.\n    - cwd: a string representing the working directory that must be\n      used for the subprocess. Corresponds to the provided source_dir.\n    - extra_environ: a dict mapping environment variable names to values\n      which must be set for the subprocess execution.\n    \"\"\"\n    def __init__(\n            self,\n            source_dir,\n            build_backend,\n            backend_path=None,\n            runner=None,\n            python_executable=None,\n    ):\n        if runner is None:\n            runner = default_subprocess_runner\n\n        self.source_dir = abspath(source_dir)\n        self.build_backend = build_backend\n        if backend_path:\n            backend_path = [\n                norm_and_check(self.source_dir, p) for p in backend_path\n            ]\n        self.backend_path = backend_path\n        self._subprocess_runner = runner\n        if not python_executable:\n            python_executable = sys.executable\n        self.python_executable = python_executable\n\n    @contextmanager\n    def subprocess_runner(self, runner):\n        \"\"\"A context manager for temporarily overriding the default subprocess\n        runner.\n        \"\"\"\n        prev = self._subprocess_runner\n        self._subprocess_runner = runner\n        try:\n            yield\n        finally:\n            self._subprocess_runner = prev\n\n    def _supported_features(self):\n        \"\"\"Return the list of optional features supported by the backend.\"\"\"\n        return self._call_hook('_supported_features', {})\n\n    def get_requires_for_build_wheel(self, config_settings=None):\n        \"\"\"Identify packages required for building a wheel\n\n        Returns a list of dependency specifications, e.g.::\n\n            [\"wheel >= 0.25\", \"setuptools\"]\n\n        This does not include requirements specified in pyproject.toml.\n        It returns the result of calling the equivalently named hook in a\n        subprocess.\n        \"\"\"\n        return self._call_hook('get_requires_for_build_wheel', {\n            'config_settings': config_settings\n        })\n\n    def prepare_metadata_for_build_wheel(\n            self, metadata_directory, config_settings=None,\n            _allow_fallback=True):\n        \"\"\"Prepare a ``*.dist-info`` folder with metadata for this project.\n\n        Returns the name of the newly created folder.\n\n        If the build backend defines a hook with this name, it will be called\n        in a subprocess. If not, the backend will be asked to build a wheel,\n        and the dist-info extracted from that (unless _allow_fallback is\n        False).\n        \"\"\"\n        return self._call_hook('prepare_metadata_for_build_wheel', {\n            'metadata_directory': abspath(metadata_directory),\n            'config_settings': config_settings,\n            '_allow_fallback': _allow_fallback,\n        })\n\n    def build_wheel(\n            self, wheel_directory, config_settings=None,\n            metadata_directory=None):\n        \"\"\"Build a wheel from this project.\n\n        Returns the name of the newly created file.\n\n        In general, this will call the 'build_wheel' hook in the backend.\n        However, if that was previously called by\n        'prepare_metadata_for_build_wheel', and the same metadata_directory is\n        used, the previously built wheel will be copied to wheel_directory.\n        \"\"\"\n        if metadata_directory is not None:\n            metadata_directory = abspath(metadata_directory)\n        return self._call_hook('build_wheel', {\n            'wheel_directory': abspath(wheel_directory),\n            'config_settings': config_settings,\n            'metadata_directory': metadata_directory,\n        })\n\n    def get_requires_for_build_editable(self, config_settings=None):\n        \"\"\"Identify packages required for building an editable wheel\n\n        Returns a list of dependency specifications, e.g.::\n\n            [\"wheel >= 0.25\", \"setuptools\"]\n\n        This does not include requirements specified in pyproject.toml.\n        It returns the result of calling the equivalently named hook in a\n        subprocess.\n        \"\"\"\n        return self._call_hook('get_requires_for_build_editable', {\n            'config_settings': config_settings\n        })\n\n    def prepare_metadata_for_build_editable(\n            self, metadata_directory, config_settings=None,\n            _allow_fallback=True):\n        \"\"\"Prepare a ``*.dist-info`` folder with metadata for this project.\n\n        Returns the name of the newly created folder.\n\n        If the build backend defines a hook with this name, it will be called\n        in a subprocess. If not, the backend will be asked to build an editable\n        wheel, and the dist-info extracted from that (unless _allow_fallback is\n        False).\n        \"\"\"\n        return self._call_hook('prepare_metadata_for_build_editable', {\n            'metadata_directory': abspath(metadata_directory),\n            'config_settings': config_settings,\n            '_allow_fallback': _allow_fallback,\n        })\n\n    def build_editable(\n            self, wheel_directory, config_settings=None,\n            metadata_directory=None):\n        \"\"\"Build an editable wheel from this project.\n\n        Returns the name of the newly created file.\n\n        In general, this will call the 'build_editable' hook in the backend.\n        However, if that was previously called by\n        'prepare_metadata_for_build_editable', and the same metadata_directory\n        is used, the previously built wheel will be copied to wheel_directory.\n        \"\"\"\n        if metadata_directory is not None:\n            metadata_directory = abspath(metadata_directory)\n        return self._call_hook('build_editable', {\n            'wheel_directory': abspath(wheel_directory),\n            'config_settings': config_settings,\n            'metadata_directory': metadata_directory,\n        })\n\n    def get_requires_for_build_sdist(self, config_settings=None):\n        \"\"\"Identify packages required for building a wheel\n\n        Returns a list of dependency specifications, e.g.::\n\n            [\"setuptools >= 26\"]\n\n        This does not include requirements specified in pyproject.toml.\n        It returns the result of calling the equivalently named hook in a\n        subprocess.\n        \"\"\"\n        return self._call_hook('get_requires_for_build_sdist', {\n            'config_settings': config_settings\n        })\n\n    def build_sdist(self, sdist_directory, config_settings=None):\n        \"\"\"Build an sdist from this project.\n\n        Returns the name of the newly created file.\n\n        This calls the 'build_sdist' backend hook in a subprocess.\n        \"\"\"\n        return self._call_hook('build_sdist', {\n            'sdist_directory': abspath(sdist_directory),\n            'config_settings': config_settings,\n        })\n\n    def _call_hook(self, hook_name, kwargs):\n        extra_environ = {'PEP517_BUILD_BACKEND': self.build_backend}\n\n        if self.backend_path:\n            backend_path = os.pathsep.join(self.backend_path)\n            extra_environ['PEP517_BACKEND_PATH'] = backend_path\n\n        with tempfile.TemporaryDirectory() as td:\n            hook_input = {'kwargs': kwargs}\n            write_json(hook_input, pjoin(td, 'input.json'), indent=2)\n\n            # Run the hook in a subprocess\n            with _in_proc_script_path() as script:\n                python = self.python_executable\n                self._subprocess_runner(\n                    [python, abspath(str(script)), hook_name, td],\n                    cwd=self.source_dir,\n                    extra_environ=extra_environ\n                )\n\n            data = read_json(pjoin(td, 'output.json'))\n            if data.get('unsupported'):\n                raise UnsupportedOperation(data.get('traceback', ''))\n            if data.get('no_backend'):\n                raise BackendUnavailable(data.get('traceback', ''))\n            if data.get('backend_invalid'):\n                raise BackendInvalid(\n                    backend_name=self.build_backend,\n                    backend_path=self.backend_path,\n                    message=data.get('backend_error', '')\n                )\n            if data.get('hook_missing'):\n                raise HookMissing(data.get('missing_hook_name') or hook_name)\n            return data['return_val']\n\n\nclass LoggerWrapper(threading.Thread):\n    \"\"\"\n    Read messages from a pipe and redirect them\n    to a logger (see python's logging module).\n    \"\"\"\n\n    def __init__(self, logger, level):\n        threading.Thread.__init__(self)\n        self.daemon = True\n\n        self.logger = logger\n        self.level = level\n\n        # create the pipe and reader\n        self.fd_read, self.fd_write = os.pipe()\n        self.reader = os.fdopen(self.fd_read)\n\n        self.start()\n\n    def fileno(self):\n        return self.fd_write\n\n    @staticmethod\n    def remove_newline(msg):\n        return msg[:-1] if msg.endswith(os.linesep) else msg\n\n    def run(self):\n        for line in self.reader:\n            self._write(self.remove_newline(line))\n\n    def _write(self, message):\n        self.logger.log(self.level, message)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pkg_resources/__init__.py",
    "content": "# coding: utf-8\n\"\"\"\nPackage resource API\n--------------------\n\nA resource is a logical file contained within a package, or a logical\nsubdirectory thereof.  The package resource API expects resource names\nto have their path parts separated with ``/``, *not* whatever the local\npath separator is.  Do not use os.path operations to manipulate resource\nnames being passed into the API.\n\nThe package resource API is designed to work with normal filesystem packages,\n.egg files, and unpacked .egg files.  It can also work in a limited way with\n.zip files and with custom PEP 302 loaders that support the ``get_data()``\nmethod.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport sys\nimport os\nimport io\nimport time\nimport re\nimport types\nimport zipfile\nimport zipimport\nimport warnings\nimport stat\nimport functools\nimport pkgutil\nimport operator\nimport platform\nimport collections\nimport plistlib\nimport email.parser\nimport errno\nimport tempfile\nimport textwrap\nimport itertools\nimport inspect\nimport ntpath\nimport posixpath\nfrom pkgutil import get_importer\n\ntry:\n    import _imp\nexcept ImportError:\n    # Python 3.2 compatibility\n    import imp as _imp\n\ntry:\n    FileExistsError\nexcept NameError:\n    FileExistsError = OSError\n\nfrom pip._vendor import six\nfrom pip._vendor.six.moves import urllib, map, filter\n\n# capture these to bypass sandboxing\nfrom os import utime\ntry:\n    from os import mkdir, rename, unlink\n    WRITE_SUPPORT = True\nexcept ImportError:\n    # no write support, probably under GAE\n    WRITE_SUPPORT = False\n\nfrom os import open as os_open\nfrom os.path import isdir, split\n\ntry:\n    import importlib.machinery as importlib_machinery\n    # access attribute to force import under delayed import mechanisms.\n    importlib_machinery.__name__\nexcept ImportError:\n    importlib_machinery = None\n\nfrom . import py31compat\nfrom pip._vendor import platformdirs\nfrom pip._vendor import packaging\n__import__('pip._vendor.packaging.version')\n__import__('pip._vendor.packaging.specifiers')\n__import__('pip._vendor.packaging.requirements')\n__import__('pip._vendor.packaging.markers')\n\n\n__metaclass__ = type\n\n\nif (3, 0) < sys.version_info < (3, 5):\n    raise RuntimeError(\"Python 3.5 or later is required\")\n\nif six.PY2:\n    # Those builtin exceptions are only defined in Python 3\n    PermissionError = None\n    NotADirectoryError = None\n\n# declare some globals that will be defined later to\n# satisfy the linters.\nrequire = None\nworking_set = None\nadd_activation_listener = None\nresources_stream = None\ncleanup_resources = None\nresource_dir = None\nresource_stream = None\nset_extraction_path = None\nresource_isdir = None\nresource_string = None\niter_entry_points = None\nresource_listdir = None\nresource_filename = None\nresource_exists = None\n_distribution_finders = None\n_namespace_handlers = None\n_namespace_packages = None\n\n\nclass PEP440Warning(RuntimeWarning):\n    \"\"\"\n    Used when there is an issue with a version or specifier not complying with\n    PEP 440.\n    \"\"\"\n\n\ndef parse_version(v):\n    try:\n        return packaging.version.Version(v)\n    except packaging.version.InvalidVersion:\n        return packaging.version.LegacyVersion(v)\n\n\n_state_vars = {}\n\n\ndef _declare_state(vartype, **kw):\n    globals().update(kw)\n    _state_vars.update(dict.fromkeys(kw, vartype))\n\n\ndef __getstate__():\n    state = {}\n    g = globals()\n    for k, v in _state_vars.items():\n        state[k] = g['_sget_' + v](g[k])\n    return state\n\n\ndef __setstate__(state):\n    g = globals()\n    for k, v in state.items():\n        g['_sset_' + _state_vars[k]](k, g[k], v)\n    return state\n\n\ndef _sget_dict(val):\n    return val.copy()\n\n\ndef _sset_dict(key, ob, state):\n    ob.clear()\n    ob.update(state)\n\n\ndef _sget_object(val):\n    return val.__getstate__()\n\n\ndef _sset_object(key, ob, state):\n    ob.__setstate__(state)\n\n\n_sget_none = _sset_none = lambda *args: None\n\n\ndef get_supported_platform():\n    \"\"\"Return this platform's maximum compatible version.\n\n    distutils.util.get_platform() normally reports the minimum version\n    of Mac OS X that would be required to *use* extensions produced by\n    distutils.  But what we want when checking compatibility is to know the\n    version of Mac OS X that we are *running*.  To allow usage of packages that\n    explicitly require a newer version of Mac OS X, we must also know the\n    current version of the OS.\n\n    If this condition occurs for any other platform with a version in its\n    platform strings, this function should be extended accordingly.\n    \"\"\"\n    plat = get_build_platform()\n    m = macosVersionString.match(plat)\n    if m is not None and sys.platform == \"darwin\":\n        try:\n            plat = 'macosx-%s-%s' % ('.'.join(_macosx_vers()[:2]), m.group(3))\n        except ValueError:\n            # not Mac OS X\n            pass\n    return plat\n\n\n__all__ = [\n    # Basic resource access and distribution/entry point discovery\n    'require', 'run_script', 'get_provider', 'get_distribution',\n    'load_entry_point', 'get_entry_map', 'get_entry_info',\n    'iter_entry_points',\n    'resource_string', 'resource_stream', 'resource_filename',\n    'resource_listdir', 'resource_exists', 'resource_isdir',\n\n    # Environmental control\n    'declare_namespace', 'working_set', 'add_activation_listener',\n    'find_distributions', 'set_extraction_path', 'cleanup_resources',\n    'get_default_cache',\n\n    # Primary implementation classes\n    'Environment', 'WorkingSet', 'ResourceManager',\n    'Distribution', 'Requirement', 'EntryPoint',\n\n    # Exceptions\n    'ResolutionError', 'VersionConflict', 'DistributionNotFound',\n    'UnknownExtra', 'ExtractionError',\n\n    # Warnings\n    'PEP440Warning',\n\n    # Parsing functions and string utilities\n    'parse_requirements', 'parse_version', 'safe_name', 'safe_version',\n    'get_platform', 'compatible_platforms', 'yield_lines', 'split_sections',\n    'safe_extra', 'to_filename', 'invalid_marker', 'evaluate_marker',\n\n    # filesystem utilities\n    'ensure_directory', 'normalize_path',\n\n    # Distribution \"precedence\" constants\n    'EGG_DIST', 'BINARY_DIST', 'SOURCE_DIST', 'CHECKOUT_DIST', 'DEVELOP_DIST',\n\n    # \"Provider\" interfaces, implementations, and registration/lookup APIs\n    'IMetadataProvider', 'IResourceProvider', 'FileMetadata',\n    'PathMetadata', 'EggMetadata', 'EmptyProvider', 'empty_provider',\n    'NullProvider', 'EggProvider', 'DefaultProvider', 'ZipProvider',\n    'register_finder', 'register_namespace_handler', 'register_loader_type',\n    'fixup_namespace_packages', 'get_importer',\n\n    # Warnings\n    'PkgResourcesDeprecationWarning',\n\n    # Deprecated/backward compatibility only\n    'run_main', 'AvailableDistributions',\n]\n\n\nclass ResolutionError(Exception):\n    \"\"\"Abstract base for dependency resolution errors\"\"\"\n\n    def __repr__(self):\n        return self.__class__.__name__ + repr(self.args)\n\n\nclass VersionConflict(ResolutionError):\n    \"\"\"\n    An already-installed version conflicts with the requested version.\n\n    Should be initialized with the installed Distribution and the requested\n    Requirement.\n    \"\"\"\n\n    _template = \"{self.dist} is installed but {self.req} is required\"\n\n    @property\n    def dist(self):\n        return self.args[0]\n\n    @property\n    def req(self):\n        return self.args[1]\n\n    def report(self):\n        return self._template.format(**locals())\n\n    def with_context(self, required_by):\n        \"\"\"\n        If required_by is non-empty, return a version of self that is a\n        ContextualVersionConflict.\n        \"\"\"\n        if not required_by:\n            return self\n        args = self.args + (required_by,)\n        return ContextualVersionConflict(*args)\n\n\nclass ContextualVersionConflict(VersionConflict):\n    \"\"\"\n    A VersionConflict that accepts a third parameter, the set of the\n    requirements that required the installed Distribution.\n    \"\"\"\n\n    _template = VersionConflict._template + ' by {self.required_by}'\n\n    @property\n    def required_by(self):\n        return self.args[2]\n\n\nclass DistributionNotFound(ResolutionError):\n    \"\"\"A requested distribution was not found\"\"\"\n\n    _template = (\"The '{self.req}' distribution was not found \"\n                 \"and is required by {self.requirers_str}\")\n\n    @property\n    def req(self):\n        return self.args[0]\n\n    @property\n    def requirers(self):\n        return self.args[1]\n\n    @property\n    def requirers_str(self):\n        if not self.requirers:\n            return 'the application'\n        return ', '.join(self.requirers)\n\n    def report(self):\n        return self._template.format(**locals())\n\n    def __str__(self):\n        return self.report()\n\n\nclass UnknownExtra(ResolutionError):\n    \"\"\"Distribution doesn't have an \"extra feature\" of the given name\"\"\"\n\n\n_provider_factories = {}\n\nPY_MAJOR = '{}.{}'.format(*sys.version_info)\nEGG_DIST = 3\nBINARY_DIST = 2\nSOURCE_DIST = 1\nCHECKOUT_DIST = 0\nDEVELOP_DIST = -1\n\n\ndef register_loader_type(loader_type, provider_factory):\n    \"\"\"Register `provider_factory` to make providers for `loader_type`\n\n    `loader_type` is the type or class of a PEP 302 ``module.__loader__``,\n    and `provider_factory` is a function that, passed a *module* object,\n    returns an ``IResourceProvider`` for that module.\n    \"\"\"\n    _provider_factories[loader_type] = provider_factory\n\n\ndef get_provider(moduleOrReq):\n    \"\"\"Return an IResourceProvider for the named module or requirement\"\"\"\n    if isinstance(moduleOrReq, Requirement):\n        return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]\n    try:\n        module = sys.modules[moduleOrReq]\n    except KeyError:\n        __import__(moduleOrReq)\n        module = sys.modules[moduleOrReq]\n    loader = getattr(module, '__loader__', None)\n    return _find_adapter(_provider_factories, loader)(module)\n\n\ndef _macosx_vers(_cache=[]):\n    if not _cache:\n        version = platform.mac_ver()[0]\n        # fallback for MacPorts\n        if version == '':\n            plist = '/System/Library/CoreServices/SystemVersion.plist'\n            if os.path.exists(plist):\n                if hasattr(plistlib, 'readPlist'):\n                    plist_content = plistlib.readPlist(plist)\n                    if 'ProductVersion' in plist_content:\n                        version = plist_content['ProductVersion']\n\n        _cache.append(version.split('.'))\n    return _cache[0]\n\n\ndef _macosx_arch(machine):\n    return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)\n\n\ndef get_build_platform():\n    \"\"\"Return this platform's string for platform-specific distributions\n\n    XXX Currently this is the same as ``distutils.util.get_platform()``, but it\n    needs some hacks for Linux and Mac OS X.\n    \"\"\"\n    from sysconfig import get_platform\n\n    plat = get_platform()\n    if sys.platform == \"darwin\" and not plat.startswith('macosx-'):\n        try:\n            version = _macosx_vers()\n            machine = os.uname()[4].replace(\" \", \"_\")\n            return \"macosx-%d.%d-%s\" % (\n                int(version[0]), int(version[1]),\n                _macosx_arch(machine),\n            )\n        except ValueError:\n            # if someone is running a non-Mac darwin system, this will fall\n            # through to the default implementation\n            pass\n    return plat\n\n\nmacosVersionString = re.compile(r\"macosx-(\\d+)\\.(\\d+)-(.*)\")\ndarwinVersionString = re.compile(r\"darwin-(\\d+)\\.(\\d+)\\.(\\d+)-(.*)\")\n# XXX backward compat\nget_platform = get_build_platform\n\n\ndef compatible_platforms(provided, required):\n    \"\"\"Can code for the `provided` platform run on the `required` platform?\n\n    Returns true if either platform is ``None``, or the platforms are equal.\n\n    XXX Needs compatibility checks for Linux and other unixy OSes.\n    \"\"\"\n    if provided is None or required is None or provided == required:\n        # easy case\n        return True\n\n    # Mac OS X special cases\n    reqMac = macosVersionString.match(required)\n    if reqMac:\n        provMac = macosVersionString.match(provided)\n\n        # is this a Mac package?\n        if not provMac:\n            # this is backwards compatibility for packages built before\n            # setuptools 0.6. All packages built after this point will\n            # use the new macosx designation.\n            provDarwin = darwinVersionString.match(provided)\n            if provDarwin:\n                dversion = int(provDarwin.group(1))\n                macosversion = \"%s.%s\" % (reqMac.group(1), reqMac.group(2))\n                if dversion == 7 and macosversion >= \"10.3\" or \\\n                        dversion == 8 and macosversion >= \"10.4\":\n                    return True\n            # egg isn't macosx or legacy darwin\n            return False\n\n        # are they the same major version and machine type?\n        if provMac.group(1) != reqMac.group(1) or \\\n                provMac.group(3) != reqMac.group(3):\n            return False\n\n        # is the required OS major update >= the provided one?\n        if int(provMac.group(2)) > int(reqMac.group(2)):\n            return False\n\n        return True\n\n    # XXX Linux and other platforms' special cases should go here\n    return False\n\n\ndef run_script(dist_spec, script_name):\n    \"\"\"Locate distribution `dist_spec` and run its `script_name` script\"\"\"\n    ns = sys._getframe(1).f_globals\n    name = ns['__name__']\n    ns.clear()\n    ns['__name__'] = name\n    require(dist_spec)[0].run_script(script_name, ns)\n\n\n# backward compatibility\nrun_main = run_script\n\n\ndef get_distribution(dist):\n    \"\"\"Return a current distribution object for a Requirement or string\"\"\"\n    if isinstance(dist, six.string_types):\n        dist = Requirement.parse(dist)\n    if isinstance(dist, Requirement):\n        dist = get_provider(dist)\n    if not isinstance(dist, Distribution):\n        raise TypeError(\"Expected string, Requirement, or Distribution\", dist)\n    return dist\n\n\ndef load_entry_point(dist, group, name):\n    \"\"\"Return `name` entry point of `group` for `dist` or raise ImportError\"\"\"\n    return get_distribution(dist).load_entry_point(group, name)\n\n\ndef get_entry_map(dist, group=None):\n    \"\"\"Return the entry point map for `group`, or the full entry map\"\"\"\n    return get_distribution(dist).get_entry_map(group)\n\n\ndef get_entry_info(dist, group, name):\n    \"\"\"Return the EntryPoint object for `group`+`name`, or ``None``\"\"\"\n    return get_distribution(dist).get_entry_info(group, name)\n\n\nclass IMetadataProvider:\n    def has_metadata(name):\n        \"\"\"Does the package's distribution contain the named metadata?\"\"\"\n\n    def get_metadata(name):\n        \"\"\"The named metadata resource as a string\"\"\"\n\n    def get_metadata_lines(name):\n        \"\"\"Yield named metadata resource as list of non-blank non-comment lines\n\n       Leading and trailing whitespace is stripped from each line, and lines\n       with ``#`` as the first non-blank character are omitted.\"\"\"\n\n    def metadata_isdir(name):\n        \"\"\"Is the named metadata a directory?  (like ``os.path.isdir()``)\"\"\"\n\n    def metadata_listdir(name):\n        \"\"\"List of metadata names in the directory (like ``os.listdir()``)\"\"\"\n\n    def run_script(script_name, namespace):\n        \"\"\"Execute the named script in the supplied namespace dictionary\"\"\"\n\n\nclass IResourceProvider(IMetadataProvider):\n    \"\"\"An object that provides access to package resources\"\"\"\n\n    def get_resource_filename(manager, resource_name):\n        \"\"\"Return a true filesystem path for `resource_name`\n\n        `manager` must be an ``IResourceManager``\"\"\"\n\n    def get_resource_stream(manager, resource_name):\n        \"\"\"Return a readable file-like object for `resource_name`\n\n        `manager` must be an ``IResourceManager``\"\"\"\n\n    def get_resource_string(manager, resource_name):\n        \"\"\"Return a string containing the contents of `resource_name`\n\n        `manager` must be an ``IResourceManager``\"\"\"\n\n    def has_resource(resource_name):\n        \"\"\"Does the package contain the named resource?\"\"\"\n\n    def resource_isdir(resource_name):\n        \"\"\"Is the named resource a directory?  (like ``os.path.isdir()``)\"\"\"\n\n    def resource_listdir(resource_name):\n        \"\"\"List of resource names in the directory (like ``os.listdir()``)\"\"\"\n\n\nclass WorkingSet:\n    \"\"\"A collection of active distributions on sys.path (or a similar list)\"\"\"\n\n    def __init__(self, entries=None):\n        \"\"\"Create working set from list of path entries (default=sys.path)\"\"\"\n        self.entries = []\n        self.entry_keys = {}\n        self.by_key = {}\n        self.callbacks = []\n\n        if entries is None:\n            entries = sys.path\n\n        for entry in entries:\n            self.add_entry(entry)\n\n    @classmethod\n    def _build_master(cls):\n        \"\"\"\n        Prepare the master working set.\n        \"\"\"\n        ws = cls()\n        try:\n            from __main__ import __requires__\n        except ImportError:\n            # The main program does not list any requirements\n            return ws\n\n        # ensure the requirements are met\n        try:\n            ws.require(__requires__)\n        except VersionConflict:\n            return cls._build_from_requirements(__requires__)\n\n        return ws\n\n    @classmethod\n    def _build_from_requirements(cls, req_spec):\n        \"\"\"\n        Build a working set from a requirement spec. Rewrites sys.path.\n        \"\"\"\n        # try it without defaults already on sys.path\n        # by starting with an empty path\n        ws = cls([])\n        reqs = parse_requirements(req_spec)\n        dists = ws.resolve(reqs, Environment())\n        for dist in dists:\n            ws.add(dist)\n\n        # add any missing entries from sys.path\n        for entry in sys.path:\n            if entry not in ws.entries:\n                ws.add_entry(entry)\n\n        # then copy back to sys.path\n        sys.path[:] = ws.entries\n        return ws\n\n    def add_entry(self, entry):\n        \"\"\"Add a path item to ``.entries``, finding any distributions on it\n\n        ``find_distributions(entry, True)`` is used to find distributions\n        corresponding to the path entry, and they are added.  `entry` is\n        always appended to ``.entries``, even if it is already present.\n        (This is because ``sys.path`` can contain the same value more than\n        once, and the ``.entries`` of the ``sys.path`` WorkingSet should always\n        equal ``sys.path``.)\n        \"\"\"\n        self.entry_keys.setdefault(entry, [])\n        self.entries.append(entry)\n        for dist in find_distributions(entry, True):\n            self.add(dist, entry, False)\n\n    def __contains__(self, dist):\n        \"\"\"True if `dist` is the active distribution for its project\"\"\"\n        return self.by_key.get(dist.key) == dist\n\n    def find(self, req):\n        \"\"\"Find a distribution matching requirement `req`\n\n        If there is an active distribution for the requested project, this\n        returns it as long as it meets the version requirement specified by\n        `req`.  But, if there is an active distribution for the project and it\n        does *not* meet the `req` requirement, ``VersionConflict`` is raised.\n        If there is no active distribution for the requested project, ``None``\n        is returned.\n        \"\"\"\n        dist = self.by_key.get(req.key)\n        if dist is not None and dist not in req:\n            # XXX add more info\n            raise VersionConflict(dist, req)\n        return dist\n\n    def iter_entry_points(self, group, name=None):\n        \"\"\"Yield entry point objects from `group` matching `name`\n\n        If `name` is None, yields all entry points in `group` from all\n        distributions in the working set, otherwise only ones matching\n        both `group` and `name` are yielded (in distribution order).\n        \"\"\"\n        return (\n            entry\n            for dist in self\n            for entry in dist.get_entry_map(group).values()\n            if name is None or name == entry.name\n        )\n\n    def run_script(self, requires, script_name):\n        \"\"\"Locate distribution for `requires` and run `script_name` script\"\"\"\n        ns = sys._getframe(1).f_globals\n        name = ns['__name__']\n        ns.clear()\n        ns['__name__'] = name\n        self.require(requires)[0].run_script(script_name, ns)\n\n    def __iter__(self):\n        \"\"\"Yield distributions for non-duplicate projects in the working set\n\n        The yield order is the order in which the items' path entries were\n        added to the working set.\n        \"\"\"\n        seen = {}\n        for item in self.entries:\n            if item not in self.entry_keys:\n                # workaround a cache issue\n                continue\n\n            for key in self.entry_keys[item]:\n                if key not in seen:\n                    seen[key] = 1\n                    yield self.by_key[key]\n\n    def add(self, dist, entry=None, insert=True, replace=False):\n        \"\"\"Add `dist` to working set, associated with `entry`\n\n        If `entry` is unspecified, it defaults to the ``.location`` of `dist`.\n        On exit from this routine, `entry` is added to the end of the working\n        set's ``.entries`` (if it wasn't already present).\n\n        `dist` is only added to the working set if it's for a project that\n        doesn't already have a distribution in the set, unless `replace=True`.\n        If it's added, any callbacks registered with the ``subscribe()`` method\n        will be called.\n        \"\"\"\n        if insert:\n            dist.insert_on(self.entries, entry, replace=replace)\n\n        if entry is None:\n            entry = dist.location\n        keys = self.entry_keys.setdefault(entry, [])\n        keys2 = self.entry_keys.setdefault(dist.location, [])\n        if not replace and dist.key in self.by_key:\n            # ignore hidden distros\n            return\n\n        self.by_key[dist.key] = dist\n        if dist.key not in keys:\n            keys.append(dist.key)\n        if dist.key not in keys2:\n            keys2.append(dist.key)\n        self._added_new(dist)\n\n    def resolve(self, requirements, env=None, installer=None,\n                replace_conflicting=False, extras=None):\n        \"\"\"List all distributions needed to (recursively) meet `requirements`\n\n        `requirements` must be a sequence of ``Requirement`` objects.  `env`,\n        if supplied, should be an ``Environment`` instance.  If\n        not supplied, it defaults to all distributions available within any\n        entry or distribution in the working set.  `installer`, if supplied,\n        will be invoked with each requirement that cannot be met by an\n        already-installed distribution; it should return a ``Distribution`` or\n        ``None``.\n\n        Unless `replace_conflicting=True`, raises a VersionConflict exception\n        if\n        any requirements are found on the path that have the correct name but\n        the wrong version.  Otherwise, if an `installer` is supplied it will be\n        invoked to obtain the correct version of the requirement and activate\n        it.\n\n        `extras` is a list of the extras to be used with these requirements.\n        This is important because extra requirements may look like `my_req;\n        extra = \"my_extra\"`, which would otherwise be interpreted as a purely\n        optional requirement.  Instead, we want to be able to assert that these\n        requirements are truly required.\n        \"\"\"\n\n        # set up the stack\n        requirements = list(requirements)[::-1]\n        # set of processed requirements\n        processed = {}\n        # key -> dist\n        best = {}\n        to_activate = []\n\n        req_extras = _ReqExtras()\n\n        # Mapping of requirement to set of distributions that required it;\n        # useful for reporting info about conflicts.\n        required_by = collections.defaultdict(set)\n\n        while requirements:\n            # process dependencies breadth-first\n            req = requirements.pop(0)\n            if req in processed:\n                # Ignore cyclic or redundant dependencies\n                continue\n\n            if not req_extras.markers_pass(req, extras):\n                continue\n\n            dist = best.get(req.key)\n            if dist is None:\n                # Find the best distribution and add it to the map\n                dist = self.by_key.get(req.key)\n                if dist is None or (dist not in req and replace_conflicting):\n                    ws = self\n                    if env is None:\n                        if dist is None:\n                            env = Environment(self.entries)\n                        else:\n                            # Use an empty environment and workingset to avoid\n                            # any further conflicts with the conflicting\n                            # distribution\n                            env = Environment([])\n                            ws = WorkingSet([])\n                    dist = best[req.key] = env.best_match(\n                        req, ws, installer,\n                        replace_conflicting=replace_conflicting\n                    )\n                    if dist is None:\n                        requirers = required_by.get(req, None)\n                        raise DistributionNotFound(req, requirers)\n                to_activate.append(dist)\n            if dist not in req:\n                # Oops, the \"best\" so far conflicts with a dependency\n                dependent_req = required_by[req]\n                raise VersionConflict(dist, req).with_context(dependent_req)\n\n            # push the new requirements onto the stack\n            new_requirements = dist.requires(req.extras)[::-1]\n            requirements.extend(new_requirements)\n\n            # Register the new requirements needed by req\n            for new_requirement in new_requirements:\n                required_by[new_requirement].add(req.project_name)\n                req_extras[new_requirement] = req.extras\n\n            processed[req] = True\n\n        # return list of distros to activate\n        return to_activate\n\n    def find_plugins(\n            self, plugin_env, full_env=None, installer=None, fallback=True):\n        \"\"\"Find all activatable distributions in `plugin_env`\n\n        Example usage::\n\n            distributions, errors = working_set.find_plugins(\n                Environment(plugin_dirlist)\n            )\n            # add plugins+libs to sys.path\n            map(working_set.add, distributions)\n            # display errors\n            print('Could not load', errors)\n\n        The `plugin_env` should be an ``Environment`` instance that contains\n        only distributions that are in the project's \"plugin directory\" or\n        directories. The `full_env`, if supplied, should be an ``Environment``\n        contains all currently-available distributions.  If `full_env` is not\n        supplied, one is created automatically from the ``WorkingSet`` this\n        method is called on, which will typically mean that every directory on\n        ``sys.path`` will be scanned for distributions.\n\n        `installer` is a standard installer callback as used by the\n        ``resolve()`` method. The `fallback` flag indicates whether we should\n        attempt to resolve older versions of a plugin if the newest version\n        cannot be resolved.\n\n        This method returns a 2-tuple: (`distributions`, `error_info`), where\n        `distributions` is a list of the distributions found in `plugin_env`\n        that were loadable, along with any other distributions that are needed\n        to resolve their dependencies.  `error_info` is a dictionary mapping\n        unloadable plugin distributions to an exception instance describing the\n        error that occurred. Usually this will be a ``DistributionNotFound`` or\n        ``VersionConflict`` instance.\n        \"\"\"\n\n        plugin_projects = list(plugin_env)\n        # scan project names in alphabetic order\n        plugin_projects.sort()\n\n        error_info = {}\n        distributions = {}\n\n        if full_env is None:\n            env = Environment(self.entries)\n            env += plugin_env\n        else:\n            env = full_env + plugin_env\n\n        shadow_set = self.__class__([])\n        # put all our entries in shadow_set\n        list(map(shadow_set.add, self))\n\n        for project_name in plugin_projects:\n\n            for dist in plugin_env[project_name]:\n\n                req = [dist.as_requirement()]\n\n                try:\n                    resolvees = shadow_set.resolve(req, env, installer)\n\n                except ResolutionError as v:\n                    # save error info\n                    error_info[dist] = v\n                    if fallback:\n                        # try the next older version of project\n                        continue\n                    else:\n                        # give up on this project, keep going\n                        break\n\n                else:\n                    list(map(shadow_set.add, resolvees))\n                    distributions.update(dict.fromkeys(resolvees))\n\n                    # success, no need to try any more versions of this project\n                    break\n\n        distributions = list(distributions)\n        distributions.sort()\n\n        return distributions, error_info\n\n    def require(self, *requirements):\n        \"\"\"Ensure that distributions matching `requirements` are activated\n\n        `requirements` must be a string or a (possibly-nested) sequence\n        thereof, specifying the distributions and versions required.  The\n        return value is a sequence of the distributions that needed to be\n        activated to fulfill the requirements; all relevant distributions are\n        included, even if they were already activated in this working set.\n        \"\"\"\n        needed = self.resolve(parse_requirements(requirements))\n\n        for dist in needed:\n            self.add(dist)\n\n        return needed\n\n    def subscribe(self, callback, existing=True):\n        \"\"\"Invoke `callback` for all distributions\n\n        If `existing=True` (default),\n        call on all existing ones, as well.\n        \"\"\"\n        if callback in self.callbacks:\n            return\n        self.callbacks.append(callback)\n        if not existing:\n            return\n        for dist in self:\n            callback(dist)\n\n    def _added_new(self, dist):\n        for callback in self.callbacks:\n            callback(dist)\n\n    def __getstate__(self):\n        return (\n            self.entries[:], self.entry_keys.copy(), self.by_key.copy(),\n            self.callbacks[:]\n        )\n\n    def __setstate__(self, e_k_b_c):\n        entries, keys, by_key, callbacks = e_k_b_c\n        self.entries = entries[:]\n        self.entry_keys = keys.copy()\n        self.by_key = by_key.copy()\n        self.callbacks = callbacks[:]\n\n\nclass _ReqExtras(dict):\n    \"\"\"\n    Map each requirement to the extras that demanded it.\n    \"\"\"\n\n    def markers_pass(self, req, extras=None):\n        \"\"\"\n        Evaluate markers for req against each extra that\n        demanded it.\n\n        Return False if the req has a marker and fails\n        evaluation. Otherwise, return True.\n        \"\"\"\n        extra_evals = (\n            req.marker.evaluate({'extra': extra})\n            for extra in self.get(req, ()) + (extras or (None,))\n        )\n        return not req.marker or any(extra_evals)\n\n\nclass Environment:\n    \"\"\"Searchable snapshot of distributions on a search path\"\"\"\n\n    def __init__(\n            self, search_path=None, platform=get_supported_platform(),\n            python=PY_MAJOR):\n        \"\"\"Snapshot distributions available on a search path\n\n        Any distributions found on `search_path` are added to the environment.\n        `search_path` should be a sequence of ``sys.path`` items.  If not\n        supplied, ``sys.path`` is used.\n\n        `platform` is an optional string specifying the name of the platform\n        that platform-specific distributions must be compatible with.  If\n        unspecified, it defaults to the current platform.  `python` is an\n        optional string naming the desired version of Python (e.g. ``'3.6'``);\n        it defaults to the current version.\n\n        You may explicitly set `platform` (and/or `python`) to ``None`` if you\n        wish to map *all* distributions, not just those compatible with the\n        running platform or Python version.\n        \"\"\"\n        self._distmap = {}\n        self.platform = platform\n        self.python = python\n        self.scan(search_path)\n\n    def can_add(self, dist):\n        \"\"\"Is distribution `dist` acceptable for this environment?\n\n        The distribution must match the platform and python version\n        requirements specified when this environment was created, or False\n        is returned.\n        \"\"\"\n        py_compat = (\n            self.python is None\n            or dist.py_version is None\n            or dist.py_version == self.python\n        )\n        return py_compat and compatible_platforms(dist.platform, self.platform)\n\n    def remove(self, dist):\n        \"\"\"Remove `dist` from the environment\"\"\"\n        self._distmap[dist.key].remove(dist)\n\n    def scan(self, search_path=None):\n        \"\"\"Scan `search_path` for distributions usable in this environment\n\n        Any distributions found are added to the environment.\n        `search_path` should be a sequence of ``sys.path`` items.  If not\n        supplied, ``sys.path`` is used.  Only distributions conforming to\n        the platform/python version defined at initialization are added.\n        \"\"\"\n        if search_path is None:\n            search_path = sys.path\n\n        for item in search_path:\n            for dist in find_distributions(item):\n                self.add(dist)\n\n    def __getitem__(self, project_name):\n        \"\"\"Return a newest-to-oldest list of distributions for `project_name`\n\n        Uses case-insensitive `project_name` comparison, assuming all the\n        project's distributions use their project's name converted to all\n        lowercase as their key.\n\n        \"\"\"\n        distribution_key = project_name.lower()\n        return self._distmap.get(distribution_key, [])\n\n    def add(self, dist):\n        \"\"\"Add `dist` if we ``can_add()`` it and it has not already been added\n        \"\"\"\n        if self.can_add(dist) and dist.has_version():\n            dists = self._distmap.setdefault(dist.key, [])\n            if dist not in dists:\n                dists.append(dist)\n                dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)\n\n    def best_match(\n            self, req, working_set, installer=None, replace_conflicting=False):\n        \"\"\"Find distribution best matching `req` and usable on `working_set`\n\n        This calls the ``find(req)`` method of the `working_set` to see if a\n        suitable distribution is already active.  (This may raise\n        ``VersionConflict`` if an unsuitable version of the project is already\n        active in the specified `working_set`.)  If a suitable distribution\n        isn't active, this method returns the newest distribution in the\n        environment that meets the ``Requirement`` in `req`.  If no suitable\n        distribution is found, and `installer` is supplied, then the result of\n        calling the environment's ``obtain(req, installer)`` method will be\n        returned.\n        \"\"\"\n        try:\n            dist = working_set.find(req)\n        except VersionConflict:\n            if not replace_conflicting:\n                raise\n            dist = None\n        if dist is not None:\n            return dist\n        for dist in self[req.key]:\n            if dist in req:\n                return dist\n        # try to download/install\n        return self.obtain(req, installer)\n\n    def obtain(self, requirement, installer=None):\n        \"\"\"Obtain a distribution matching `requirement` (e.g. via download)\n\n        Obtain a distro that matches requirement (e.g. via download).  In the\n        base ``Environment`` class, this routine just returns\n        ``installer(requirement)``, unless `installer` is None, in which case\n        None is returned instead.  This method is a hook that allows subclasses\n        to attempt other ways of obtaining a distribution before falling back\n        to the `installer` argument.\"\"\"\n        if installer is not None:\n            return installer(requirement)\n\n    def __iter__(self):\n        \"\"\"Yield the unique project names of the available distributions\"\"\"\n        for key in self._distmap.keys():\n            if self[key]:\n                yield key\n\n    def __iadd__(self, other):\n        \"\"\"In-place addition of a distribution or environment\"\"\"\n        if isinstance(other, Distribution):\n            self.add(other)\n        elif isinstance(other, Environment):\n            for project in other:\n                for dist in other[project]:\n                    self.add(dist)\n        else:\n            raise TypeError(\"Can't add %r to environment\" % (other,))\n        return self\n\n    def __add__(self, other):\n        \"\"\"Add an environment or distribution to an environment\"\"\"\n        new = self.__class__([], platform=None, python=None)\n        for env in self, other:\n            new += env\n        return new\n\n\n# XXX backward compatibility\nAvailableDistributions = Environment\n\n\nclass ExtractionError(RuntimeError):\n    \"\"\"An error occurred extracting a resource\n\n    The following attributes are available from instances of this exception:\n\n    manager\n        The resource manager that raised this exception\n\n    cache_path\n        The base directory for resource extraction\n\n    original_error\n        The exception instance that caused extraction to fail\n    \"\"\"\n\n\nclass ResourceManager:\n    \"\"\"Manage resource extraction and packages\"\"\"\n    extraction_path = None\n\n    def __init__(self):\n        self.cached_files = {}\n\n    def resource_exists(self, package_or_requirement, resource_name):\n        \"\"\"Does the named resource exist?\"\"\"\n        return get_provider(package_or_requirement).has_resource(resource_name)\n\n    def resource_isdir(self, package_or_requirement, resource_name):\n        \"\"\"Is the named resource an existing directory?\"\"\"\n        return get_provider(package_or_requirement).resource_isdir(\n            resource_name\n        )\n\n    def resource_filename(self, package_or_requirement, resource_name):\n        \"\"\"Return a true filesystem path for specified resource\"\"\"\n        return get_provider(package_or_requirement).get_resource_filename(\n            self, resource_name\n        )\n\n    def resource_stream(self, package_or_requirement, resource_name):\n        \"\"\"Return a readable file-like object for specified resource\"\"\"\n        return get_provider(package_or_requirement).get_resource_stream(\n            self, resource_name\n        )\n\n    def resource_string(self, package_or_requirement, resource_name):\n        \"\"\"Return specified resource as a string\"\"\"\n        return get_provider(package_or_requirement).get_resource_string(\n            self, resource_name\n        )\n\n    def resource_listdir(self, package_or_requirement, resource_name):\n        \"\"\"List the contents of the named resource directory\"\"\"\n        return get_provider(package_or_requirement).resource_listdir(\n            resource_name\n        )\n\n    def extraction_error(self):\n        \"\"\"Give an error message for problems extracting file(s)\"\"\"\n\n        old_exc = sys.exc_info()[1]\n        cache_path = self.extraction_path or get_default_cache()\n\n        tmpl = textwrap.dedent(\"\"\"\n            Can't extract file(s) to egg cache\n\n            The following error occurred while trying to extract file(s)\n            to the Python egg cache:\n\n              {old_exc}\n\n            The Python egg cache directory is currently set to:\n\n              {cache_path}\n\n            Perhaps your account does not have write access to this directory?\n            You can change the cache directory by setting the PYTHON_EGG_CACHE\n            environment variable to point to an accessible directory.\n            \"\"\").lstrip()\n        err = ExtractionError(tmpl.format(**locals()))\n        err.manager = self\n        err.cache_path = cache_path\n        err.original_error = old_exc\n        raise err\n\n    def get_cache_path(self, archive_name, names=()):\n        \"\"\"Return absolute location in cache for `archive_name` and `names`\n\n        The parent directory of the resulting path will be created if it does\n        not already exist.  `archive_name` should be the base filename of the\n        enclosing egg (which may not be the name of the enclosing zipfile!),\n        including its \".egg\" extension.  `names`, if provided, should be a\n        sequence of path name parts \"under\" the egg's extraction location.\n\n        This method should only be called by resource providers that need to\n        obtain an extraction location, and only for names they intend to\n        extract, as it tracks the generated names for possible cleanup later.\n        \"\"\"\n        extract_path = self.extraction_path or get_default_cache()\n        target_path = os.path.join(extract_path, archive_name + '-tmp', *names)\n        try:\n            _bypass_ensure_directory(target_path)\n        except Exception:\n            self.extraction_error()\n\n        self._warn_unsafe_extraction_path(extract_path)\n\n        self.cached_files[target_path] = 1\n        return target_path\n\n    @staticmethod\n    def _warn_unsafe_extraction_path(path):\n        \"\"\"\n        If the default extraction path is overridden and set to an insecure\n        location, such as /tmp, it opens up an opportunity for an attacker to\n        replace an extracted file with an unauthorized payload. Warn the user\n        if a known insecure location is used.\n\n        See Distribute #375 for more details.\n        \"\"\"\n        if os.name == 'nt' and not path.startswith(os.environ['windir']):\n            # On Windows, permissions are generally restrictive by default\n            #  and temp directories are not writable by other users, so\n            #  bypass the warning.\n            return\n        mode = os.stat(path).st_mode\n        if mode & stat.S_IWOTH or mode & stat.S_IWGRP:\n            msg = (\n                \"%s is writable by group/others and vulnerable to attack \"\n                \"when \"\n                \"used with get_resource_filename. Consider a more secure \"\n                \"location (set with .set_extraction_path or the \"\n                \"PYTHON_EGG_CACHE environment variable).\" % path\n            )\n            warnings.warn(msg, UserWarning)\n\n    def postprocess(self, tempname, filename):\n        \"\"\"Perform any platform-specific postprocessing of `tempname`\n\n        This is where Mac header rewrites should be done; other platforms don't\n        have anything special they should do.\n\n        Resource providers should call this method ONLY after successfully\n        extracting a compressed resource.  They must NOT call it on resources\n        that are already in the filesystem.\n\n        `tempname` is the current (temporary) name of the file, and `filename`\n        is the name it will be renamed to by the caller after this routine\n        returns.\n        \"\"\"\n\n        if os.name == 'posix':\n            # Make the resource executable\n            mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777\n            os.chmod(tempname, mode)\n\n    def set_extraction_path(self, path):\n        \"\"\"Set the base path where resources will be extracted to, if needed.\n\n        If you do not call this routine before any extractions take place, the\n        path defaults to the return value of ``get_default_cache()``.  (Which\n        is based on the ``PYTHON_EGG_CACHE`` environment variable, with various\n        platform-specific fallbacks.  See that routine's documentation for more\n        details.)\n\n        Resources are extracted to subdirectories of this path based upon\n        information given by the ``IResourceProvider``.  You may set this to a\n        temporary directory, but then you must call ``cleanup_resources()`` to\n        delete the extracted files when done.  There is no guarantee that\n        ``cleanup_resources()`` will be able to remove all extracted files.\n\n        (Note: you may not change the extraction path for a given resource\n        manager once resources have been extracted, unless you first call\n        ``cleanup_resources()``.)\n        \"\"\"\n        if self.cached_files:\n            raise ValueError(\n                \"Can't change extraction path, files already extracted\"\n            )\n\n        self.extraction_path = path\n\n    def cleanup_resources(self, force=False):\n        \"\"\"\n        Delete all extracted resource files and directories, returning a list\n        of the file and directory names that could not be successfully removed.\n        This function does not have any concurrency protection, so it should\n        generally only be called when the extraction path is a temporary\n        directory exclusive to a single process.  This method is not\n        automatically called; you must call it explicitly or register it as an\n        ``atexit`` function if you wish to ensure cleanup of a temporary\n        directory used for extractions.\n        \"\"\"\n        # XXX\n\n\ndef get_default_cache():\n    \"\"\"\n    Return the ``PYTHON_EGG_CACHE`` environment variable\n    or a platform-relevant user cache dir for an app\n    named \"Python-Eggs\".\n    \"\"\"\n    return (\n        os.environ.get('PYTHON_EGG_CACHE')\n        or platformdirs.user_cache_dir(appname='Python-Eggs')\n    )\n\n\ndef safe_name(name):\n    \"\"\"Convert an arbitrary string to a standard distribution name\n\n    Any runs of non-alphanumeric/. characters are replaced with a single '-'.\n    \"\"\"\n    return re.sub('[^A-Za-z0-9.]+', '-', name)\n\n\ndef safe_version(version):\n    \"\"\"\n    Convert an arbitrary string to a standard version string\n    \"\"\"\n    try:\n        # normalize the version\n        return str(packaging.version.Version(version))\n    except packaging.version.InvalidVersion:\n        version = version.replace(' ', '.')\n        return re.sub('[^A-Za-z0-9.]+', '-', version)\n\n\ndef safe_extra(extra):\n    \"\"\"Convert an arbitrary string to a standard 'extra' name\n\n    Any runs of non-alphanumeric characters are replaced with a single '_',\n    and the result is always lowercased.\n    \"\"\"\n    return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower()\n\n\ndef to_filename(name):\n    \"\"\"Convert a project or version name to its filename-escaped form\n\n    Any '-' characters are currently replaced with '_'.\n    \"\"\"\n    return name.replace('-', '_')\n\n\ndef invalid_marker(text):\n    \"\"\"\n    Validate text as a PEP 508 environment marker; return an exception\n    if invalid or False otherwise.\n    \"\"\"\n    try:\n        evaluate_marker(text)\n    except SyntaxError as e:\n        e.filename = None\n        e.lineno = None\n        return e\n    return False\n\n\ndef evaluate_marker(text, extra=None):\n    \"\"\"\n    Evaluate a PEP 508 environment marker.\n    Return a boolean indicating the marker result in this environment.\n    Raise SyntaxError if marker is invalid.\n\n    This implementation uses the 'pyparsing' module.\n    \"\"\"\n    try:\n        marker = packaging.markers.Marker(text)\n        return marker.evaluate()\n    except packaging.markers.InvalidMarker as e:\n        raise SyntaxError(e)\n\n\nclass NullProvider:\n    \"\"\"Try to implement resources and metadata for arbitrary PEP 302 loaders\"\"\"\n\n    egg_name = None\n    egg_info = None\n    loader = None\n\n    def __init__(self, module):\n        self.loader = getattr(module, '__loader__', None)\n        self.module_path = os.path.dirname(getattr(module, '__file__', ''))\n\n    def get_resource_filename(self, manager, resource_name):\n        return self._fn(self.module_path, resource_name)\n\n    def get_resource_stream(self, manager, resource_name):\n        return io.BytesIO(self.get_resource_string(manager, resource_name))\n\n    def get_resource_string(self, manager, resource_name):\n        return self._get(self._fn(self.module_path, resource_name))\n\n    def has_resource(self, resource_name):\n        return self._has(self._fn(self.module_path, resource_name))\n\n    def _get_metadata_path(self, name):\n        return self._fn(self.egg_info, name)\n\n    def has_metadata(self, name):\n        if not self.egg_info:\n            return self.egg_info\n\n        path = self._get_metadata_path(name)\n        return self._has(path)\n\n    def get_metadata(self, name):\n        if not self.egg_info:\n            return \"\"\n        path = self._get_metadata_path(name)\n        value = self._get(path)\n        if six.PY2:\n            return value\n        try:\n            return value.decode('utf-8')\n        except UnicodeDecodeError as exc:\n            # Include the path in the error message to simplify\n            # troubleshooting, and without changing the exception type.\n            exc.reason += ' in {} file at path: {}'.format(name, path)\n            raise\n\n    def get_metadata_lines(self, name):\n        return yield_lines(self.get_metadata(name))\n\n    def resource_isdir(self, resource_name):\n        return self._isdir(self._fn(self.module_path, resource_name))\n\n    def metadata_isdir(self, name):\n        return self.egg_info and self._isdir(self._fn(self.egg_info, name))\n\n    def resource_listdir(self, resource_name):\n        return self._listdir(self._fn(self.module_path, resource_name))\n\n    def metadata_listdir(self, name):\n        if self.egg_info:\n            return self._listdir(self._fn(self.egg_info, name))\n        return []\n\n    def run_script(self, script_name, namespace):\n        script = 'scripts/' + script_name\n        if not self.has_metadata(script):\n            raise ResolutionError(\n                \"Script {script!r} not found in metadata at {self.egg_info!r}\"\n                .format(**locals()),\n            )\n        script_text = self.get_metadata(script).replace('\\r\\n', '\\n')\n        script_text = script_text.replace('\\r', '\\n')\n        script_filename = self._fn(self.egg_info, script)\n        namespace['__file__'] = script_filename\n        if os.path.exists(script_filename):\n            source = open(script_filename).read()\n            code = compile(source, script_filename, 'exec')\n            exec(code, namespace, namespace)\n        else:\n            from linecache import cache\n            cache[script_filename] = (\n                len(script_text), 0, script_text.split('\\n'), script_filename\n            )\n            script_code = compile(script_text, script_filename, 'exec')\n            exec(script_code, namespace, namespace)\n\n    def _has(self, path):\n        raise NotImplementedError(\n            \"Can't perform this operation for unregistered loader type\"\n        )\n\n    def _isdir(self, path):\n        raise NotImplementedError(\n            \"Can't perform this operation for unregistered loader type\"\n        )\n\n    def _listdir(self, path):\n        raise NotImplementedError(\n            \"Can't perform this operation for unregistered loader type\"\n        )\n\n    def _fn(self, base, resource_name):\n        self._validate_resource_path(resource_name)\n        if resource_name:\n            return os.path.join(base, *resource_name.split('/'))\n        return base\n\n    @staticmethod\n    def _validate_resource_path(path):\n        \"\"\"\n        Validate the resource paths according to the docs.\n        https://setuptools.readthedocs.io/en/latest/pkg_resources.html#basic-resource-access\n\n        >>> warned = getfixture('recwarn')\n        >>> warnings.simplefilter('always')\n        >>> vrp = NullProvider._validate_resource_path\n        >>> vrp('foo/bar.txt')\n        >>> bool(warned)\n        False\n        >>> vrp('../foo/bar.txt')\n        >>> bool(warned)\n        True\n        >>> warned.clear()\n        >>> vrp('/foo/bar.txt')\n        >>> bool(warned)\n        True\n        >>> vrp('foo/../../bar.txt')\n        >>> bool(warned)\n        True\n        >>> warned.clear()\n        >>> vrp('foo/f../bar.txt')\n        >>> bool(warned)\n        False\n\n        Windows path separators are straight-up disallowed.\n        >>> vrp(r'\\\\foo/bar.txt')\n        Traceback (most recent call last):\n        ...\n        ValueError: Use of .. or absolute path in a resource path \\\nis not allowed.\n\n        >>> vrp(r'C:\\\\foo/bar.txt')\n        Traceback (most recent call last):\n        ...\n        ValueError: Use of .. or absolute path in a resource path \\\nis not allowed.\n\n        Blank values are allowed\n\n        >>> vrp('')\n        >>> bool(warned)\n        False\n\n        Non-string values are not.\n\n        >>> vrp(None)\n        Traceback (most recent call last):\n        ...\n        AttributeError: ...\n        \"\"\"\n        invalid = (\n            os.path.pardir in path.split(posixpath.sep) or\n            posixpath.isabs(path) or\n            ntpath.isabs(path)\n        )\n        if not invalid:\n            return\n\n        msg = \"Use of .. or absolute path in a resource path is not allowed.\"\n\n        # Aggressively disallow Windows absolute paths\n        if ntpath.isabs(path) and not posixpath.isabs(path):\n            raise ValueError(msg)\n\n        # for compatibility, warn; in future\n        # raise ValueError(msg)\n        warnings.warn(\n            msg[:-1] + \" and will raise exceptions in a future release.\",\n            DeprecationWarning,\n            stacklevel=4,\n        )\n\n    def _get(self, path):\n        if hasattr(self.loader, 'get_data'):\n            return self.loader.get_data(path)\n        raise NotImplementedError(\n            \"Can't perform this operation for loaders without 'get_data()'\"\n        )\n\n\nregister_loader_type(object, NullProvider)\n\n\nclass EggProvider(NullProvider):\n    \"\"\"Provider based on a virtual filesystem\"\"\"\n\n    def __init__(self, module):\n        NullProvider.__init__(self, module)\n        self._setup_prefix()\n\n    def _setup_prefix(self):\n        # we assume here that our metadata may be nested inside a \"basket\"\n        # of multiple eggs; that's why we use module_path instead of .archive\n        path = self.module_path\n        old = None\n        while path != old:\n            if _is_egg_path(path):\n                self.egg_name = os.path.basename(path)\n                self.egg_info = os.path.join(path, 'EGG-INFO')\n                self.egg_root = path\n                break\n            old = path\n            path, base = os.path.split(path)\n\n\nclass DefaultProvider(EggProvider):\n    \"\"\"Provides access to package resources in the filesystem\"\"\"\n\n    def _has(self, path):\n        return os.path.exists(path)\n\n    def _isdir(self, path):\n        return os.path.isdir(path)\n\n    def _listdir(self, path):\n        return os.listdir(path)\n\n    def get_resource_stream(self, manager, resource_name):\n        return open(self._fn(self.module_path, resource_name), 'rb')\n\n    def _get(self, path):\n        with open(path, 'rb') as stream:\n            return stream.read()\n\n    @classmethod\n    def _register(cls):\n        loader_names = 'SourceFileLoader', 'SourcelessFileLoader',\n        for name in loader_names:\n            loader_cls = getattr(importlib_machinery, name, type(None))\n            register_loader_type(loader_cls, cls)\n\n\nDefaultProvider._register()\n\n\nclass EmptyProvider(NullProvider):\n    \"\"\"Provider that returns nothing for all requests\"\"\"\n\n    module_path = None\n\n    _isdir = _has = lambda self, path: False\n\n    def _get(self, path):\n        return ''\n\n    def _listdir(self, path):\n        return []\n\n    def __init__(self):\n        pass\n\n\nempty_provider = EmptyProvider()\n\n\nclass ZipManifests(dict):\n    \"\"\"\n    zip manifest builder\n    \"\"\"\n\n    @classmethod\n    def build(cls, path):\n        \"\"\"\n        Build a dictionary similar to the zipimport directory\n        caches, except instead of tuples, store ZipInfo objects.\n\n        Use a platform-specific path separator (os.sep) for the path keys\n        for compatibility with pypy on Windows.\n        \"\"\"\n        with zipfile.ZipFile(path) as zfile:\n            items = (\n                (\n                    name.replace('/', os.sep),\n                    zfile.getinfo(name),\n                )\n                for name in zfile.namelist()\n            )\n            return dict(items)\n\n    load = build\n\n\nclass MemoizedZipManifests(ZipManifests):\n    \"\"\"\n    Memoized zipfile manifests.\n    \"\"\"\n    manifest_mod = collections.namedtuple('manifest_mod', 'manifest mtime')\n\n    def load(self, path):\n        \"\"\"\n        Load a manifest at path or return a suitable manifest already loaded.\n        \"\"\"\n        path = os.path.normpath(path)\n        mtime = os.stat(path).st_mtime\n\n        if path not in self or self[path].mtime != mtime:\n            manifest = self.build(path)\n            self[path] = self.manifest_mod(manifest, mtime)\n\n        return self[path].manifest\n\n\nclass ZipProvider(EggProvider):\n    \"\"\"Resource support for zips and eggs\"\"\"\n\n    eagers = None\n    _zip_manifests = MemoizedZipManifests()\n\n    def __init__(self, module):\n        EggProvider.__init__(self, module)\n        self.zip_pre = self.loader.archive + os.sep\n\n    def _zipinfo_name(self, fspath):\n        # Convert a virtual filename (full path to file) into a zipfile subpath\n        # usable with the zipimport directory cache for our target archive\n        fspath = fspath.rstrip(os.sep)\n        if fspath == self.loader.archive:\n            return ''\n        if fspath.startswith(self.zip_pre):\n            return fspath[len(self.zip_pre):]\n        raise AssertionError(\n            \"%s is not a subpath of %s\" % (fspath, self.zip_pre)\n        )\n\n    def _parts(self, zip_path):\n        # Convert a zipfile subpath into an egg-relative path part list.\n        # pseudo-fs path\n        fspath = self.zip_pre + zip_path\n        if fspath.startswith(self.egg_root + os.sep):\n            return fspath[len(self.egg_root) + 1:].split(os.sep)\n        raise AssertionError(\n            \"%s is not a subpath of %s\" % (fspath, self.egg_root)\n        )\n\n    @property\n    def zipinfo(self):\n        return self._zip_manifests.load(self.loader.archive)\n\n    def get_resource_filename(self, manager, resource_name):\n        if not self.egg_name:\n            raise NotImplementedError(\n                \"resource_filename() only supported for .egg, not .zip\"\n            )\n        # no need to lock for extraction, since we use temp names\n        zip_path = self._resource_to_zip(resource_name)\n        eagers = self._get_eager_resources()\n        if '/'.join(self._parts(zip_path)) in eagers:\n            for name in eagers:\n                self._extract_resource(manager, self._eager_to_zip(name))\n        return self._extract_resource(manager, zip_path)\n\n    @staticmethod\n    def _get_date_and_size(zip_stat):\n        size = zip_stat.file_size\n        # ymdhms+wday, yday, dst\n        date_time = zip_stat.date_time + (0, 0, -1)\n        # 1980 offset already done\n        timestamp = time.mktime(date_time)\n        return timestamp, size\n\n    def _extract_resource(self, manager, zip_path):\n\n        if zip_path in self._index():\n            for name in self._index()[zip_path]:\n                last = self._extract_resource(\n                    manager, os.path.join(zip_path, name)\n                )\n            # return the extracted directory name\n            return os.path.dirname(last)\n\n        timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])\n\n        if not WRITE_SUPPORT:\n            raise IOError('\"os.rename\" and \"os.unlink\" are not supported '\n                          'on this platform')\n        try:\n\n            real_path = manager.get_cache_path(\n                self.egg_name, self._parts(zip_path)\n            )\n\n            if self._is_current(real_path, zip_path):\n                return real_path\n\n            outf, tmpnam = _mkstemp(\n                \".$extract\",\n                dir=os.path.dirname(real_path),\n            )\n            os.write(outf, self.loader.get_data(zip_path))\n            os.close(outf)\n            utime(tmpnam, (timestamp, timestamp))\n            manager.postprocess(tmpnam, real_path)\n\n            try:\n                rename(tmpnam, real_path)\n\n            except os.error:\n                if os.path.isfile(real_path):\n                    if self._is_current(real_path, zip_path):\n                        # the file became current since it was checked above,\n                        #  so proceed.\n                        return real_path\n                    # Windows, del old file and retry\n                    elif os.name == 'nt':\n                        unlink(real_path)\n                        rename(tmpnam, real_path)\n                        return real_path\n                raise\n\n        except os.error:\n            # report a user-friendly error\n            manager.extraction_error()\n\n        return real_path\n\n    def _is_current(self, file_path, zip_path):\n        \"\"\"\n        Return True if the file_path is current for this zip_path\n        \"\"\"\n        timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])\n        if not os.path.isfile(file_path):\n            return False\n        stat = os.stat(file_path)\n        if stat.st_size != size or stat.st_mtime != timestamp:\n            return False\n        # check that the contents match\n        zip_contents = self.loader.get_data(zip_path)\n        with open(file_path, 'rb') as f:\n            file_contents = f.read()\n        return zip_contents == file_contents\n\n    def _get_eager_resources(self):\n        if self.eagers is None:\n            eagers = []\n            for name in ('native_libs.txt', 'eager_resources.txt'):\n                if self.has_metadata(name):\n                    eagers.extend(self.get_metadata_lines(name))\n            self.eagers = eagers\n        return self.eagers\n\n    def _index(self):\n        try:\n            return self._dirindex\n        except AttributeError:\n            ind = {}\n            for path in self.zipinfo:\n                parts = path.split(os.sep)\n                while parts:\n                    parent = os.sep.join(parts[:-1])\n                    if parent in ind:\n                        ind[parent].append(parts[-1])\n                        break\n                    else:\n                        ind[parent] = [parts.pop()]\n            self._dirindex = ind\n            return ind\n\n    def _has(self, fspath):\n        zip_path = self._zipinfo_name(fspath)\n        return zip_path in self.zipinfo or zip_path in self._index()\n\n    def _isdir(self, fspath):\n        return self._zipinfo_name(fspath) in self._index()\n\n    def _listdir(self, fspath):\n        return list(self._index().get(self._zipinfo_name(fspath), ()))\n\n    def _eager_to_zip(self, resource_name):\n        return self._zipinfo_name(self._fn(self.egg_root, resource_name))\n\n    def _resource_to_zip(self, resource_name):\n        return self._zipinfo_name(self._fn(self.module_path, resource_name))\n\n\nregister_loader_type(zipimport.zipimporter, ZipProvider)\n\n\nclass FileMetadata(EmptyProvider):\n    \"\"\"Metadata handler for standalone PKG-INFO files\n\n    Usage::\n\n        metadata = FileMetadata(\"/path/to/PKG-INFO\")\n\n    This provider rejects all data and metadata requests except for PKG-INFO,\n    which is treated as existing, and will be the contents of the file at\n    the provided location.\n    \"\"\"\n\n    def __init__(self, path):\n        self.path = path\n\n    def _get_metadata_path(self, name):\n        return self.path\n\n    def has_metadata(self, name):\n        return name == 'PKG-INFO' and os.path.isfile(self.path)\n\n    def get_metadata(self, name):\n        if name != 'PKG-INFO':\n            raise KeyError(\"No metadata except PKG-INFO is available\")\n\n        with io.open(self.path, encoding='utf-8', errors=\"replace\") as f:\n            metadata = f.read()\n        self._warn_on_replacement(metadata)\n        return metadata\n\n    def _warn_on_replacement(self, metadata):\n        # Python 2.7 compat for: replacement_char = '�'\n        replacement_char = b'\\xef\\xbf\\xbd'.decode('utf-8')\n        if replacement_char in metadata:\n            tmpl = \"{self.path} could not be properly decoded in UTF-8\"\n            msg = tmpl.format(**locals())\n            warnings.warn(msg)\n\n    def get_metadata_lines(self, name):\n        return yield_lines(self.get_metadata(name))\n\n\nclass PathMetadata(DefaultProvider):\n    \"\"\"Metadata provider for egg directories\n\n    Usage::\n\n        # Development eggs:\n\n        egg_info = \"/path/to/PackageName.egg-info\"\n        base_dir = os.path.dirname(egg_info)\n        metadata = PathMetadata(base_dir, egg_info)\n        dist_name = os.path.splitext(os.path.basename(egg_info))[0]\n        dist = Distribution(basedir, project_name=dist_name, metadata=metadata)\n\n        # Unpacked egg directories:\n\n        egg_path = \"/path/to/PackageName-ver-pyver-etc.egg\"\n        metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))\n        dist = Distribution.from_filename(egg_path, metadata=metadata)\n    \"\"\"\n\n    def __init__(self, path, egg_info):\n        self.module_path = path\n        self.egg_info = egg_info\n\n\nclass EggMetadata(ZipProvider):\n    \"\"\"Metadata provider for .egg files\"\"\"\n\n    def __init__(self, importer):\n        \"\"\"Create a metadata provider from a zipimporter\"\"\"\n\n        self.zip_pre = importer.archive + os.sep\n        self.loader = importer\n        if importer.prefix:\n            self.module_path = os.path.join(importer.archive, importer.prefix)\n        else:\n            self.module_path = importer.archive\n        self._setup_prefix()\n\n\n_declare_state('dict', _distribution_finders={})\n\n\ndef register_finder(importer_type, distribution_finder):\n    \"\"\"Register `distribution_finder` to find distributions in sys.path items\n\n    `importer_type` is the type or class of a PEP 302 \"Importer\" (sys.path item\n    handler), and `distribution_finder` is a callable that, passed a path\n    item and the importer instance, yields ``Distribution`` instances found on\n    that path item.  See ``pkg_resources.find_on_path`` for an example.\"\"\"\n    _distribution_finders[importer_type] = distribution_finder\n\n\ndef find_distributions(path_item, only=False):\n    \"\"\"Yield distributions accessible via `path_item`\"\"\"\n    importer = get_importer(path_item)\n    finder = _find_adapter(_distribution_finders, importer)\n    return finder(importer, path_item, only)\n\n\ndef find_eggs_in_zip(importer, path_item, only=False):\n    \"\"\"\n    Find eggs in zip files; possibly multiple nested eggs.\n    \"\"\"\n    if importer.archive.endswith('.whl'):\n        # wheels are not supported with this finder\n        # they don't have PKG-INFO metadata, and won't ever contain eggs\n        return\n    metadata = EggMetadata(importer)\n    if metadata.has_metadata('PKG-INFO'):\n        yield Distribution.from_filename(path_item, metadata=metadata)\n    if only:\n        # don't yield nested distros\n        return\n    for subitem in metadata.resource_listdir(''):\n        if _is_egg_path(subitem):\n            subpath = os.path.join(path_item, subitem)\n            dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)\n            for dist in dists:\n                yield dist\n        elif subitem.lower().endswith('.dist-info'):\n            subpath = os.path.join(path_item, subitem)\n            submeta = EggMetadata(zipimport.zipimporter(subpath))\n            submeta.egg_info = subpath\n            yield Distribution.from_location(path_item, subitem, submeta)\n\n\nregister_finder(zipimport.zipimporter, find_eggs_in_zip)\n\n\ndef find_nothing(importer, path_item, only=False):\n    return ()\n\n\nregister_finder(object, find_nothing)\n\n\ndef _by_version_descending(names):\n    \"\"\"\n    Given a list of filenames, return them in descending order\n    by version number.\n\n    >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'\n    >>> _by_version_descending(names)\n    ['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar']\n    >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'\n    >>> _by_version_descending(names)\n    ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']\n    >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'\n    >>> _by_version_descending(names)\n    ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']\n    \"\"\"\n    def _by_version(name):\n        \"\"\"\n        Parse each component of the filename\n        \"\"\"\n        name, ext = os.path.splitext(name)\n        parts = itertools.chain(name.split('-'), [ext])\n        return [packaging.version.parse(part) for part in parts]\n\n    return sorted(names, key=_by_version, reverse=True)\n\n\ndef find_on_path(importer, path_item, only=False):\n    \"\"\"Yield distributions accessible on a sys.path directory\"\"\"\n    path_item = _normalize_cached(path_item)\n\n    if _is_unpacked_egg(path_item):\n        yield Distribution.from_filename(\n            path_item, metadata=PathMetadata(\n                path_item, os.path.join(path_item, 'EGG-INFO')\n            )\n        )\n        return\n\n    entries = safe_listdir(path_item)\n\n    # for performance, before sorting by version,\n    # screen entries for only those that will yield\n    # distributions\n    filtered = (\n        entry\n        for entry in entries\n        if dist_factory(path_item, entry, only)\n    )\n\n    # scan for .egg and .egg-info in directory\n    path_item_entries = _by_version_descending(filtered)\n    for entry in path_item_entries:\n        fullpath = os.path.join(path_item, entry)\n        factory = dist_factory(path_item, entry, only)\n        for dist in factory(fullpath):\n            yield dist\n\n\ndef dist_factory(path_item, entry, only):\n    \"\"\"\n    Return a dist_factory for a path_item and entry\n    \"\"\"\n    lower = entry.lower()\n    is_meta = any(map(lower.endswith, ('.egg-info', '.dist-info')))\n    return (\n        distributions_from_metadata\n        if is_meta else\n        find_distributions\n        if not only and _is_egg_path(entry) else\n        resolve_egg_link\n        if not only and lower.endswith('.egg-link') else\n        NoDists()\n    )\n\n\nclass NoDists:\n    \"\"\"\n    >>> bool(NoDists())\n    False\n\n    >>> list(NoDists()('anything'))\n    []\n    \"\"\"\n    def __bool__(self):\n        return False\n    if six.PY2:\n        __nonzero__ = __bool__\n\n    def __call__(self, fullpath):\n        return iter(())\n\n\ndef safe_listdir(path):\n    \"\"\"\n    Attempt to list contents of path, but suppress some exceptions.\n    \"\"\"\n    try:\n        return os.listdir(path)\n    except (PermissionError, NotADirectoryError):\n        pass\n    except OSError as e:\n        # Ignore the directory if does not exist, not a directory or\n        # permission denied\n        ignorable = (\n            e.errno in (errno.ENOTDIR, errno.EACCES, errno.ENOENT)\n            # Python 2 on Windows needs to be handled this way :(\n            or getattr(e, \"winerror\", None) == 267\n        )\n        if not ignorable:\n            raise\n    return ()\n\n\ndef distributions_from_metadata(path):\n    root = os.path.dirname(path)\n    if os.path.isdir(path):\n        if len(os.listdir(path)) == 0:\n            # empty metadata dir; skip\n            return\n        metadata = PathMetadata(root, path)\n    else:\n        metadata = FileMetadata(path)\n    entry = os.path.basename(path)\n    yield Distribution.from_location(\n        root, entry, metadata, precedence=DEVELOP_DIST,\n    )\n\n\ndef non_empty_lines(path):\n    \"\"\"\n    Yield non-empty lines from file at path\n    \"\"\"\n    with open(path) as f:\n        for line in f:\n            line = line.strip()\n            if line:\n                yield line\n\n\ndef resolve_egg_link(path):\n    \"\"\"\n    Given a path to an .egg-link, resolve distributions\n    present in the referenced path.\n    \"\"\"\n    referenced_paths = non_empty_lines(path)\n    resolved_paths = (\n        os.path.join(os.path.dirname(path), ref)\n        for ref in referenced_paths\n    )\n    dist_groups = map(find_distributions, resolved_paths)\n    return next(dist_groups, ())\n\n\nregister_finder(pkgutil.ImpImporter, find_on_path)\n\nif hasattr(importlib_machinery, 'FileFinder'):\n    register_finder(importlib_machinery.FileFinder, find_on_path)\n\n_declare_state('dict', _namespace_handlers={})\n_declare_state('dict', _namespace_packages={})\n\n\ndef register_namespace_handler(importer_type, namespace_handler):\n    \"\"\"Register `namespace_handler` to declare namespace packages\n\n    `importer_type` is the type or class of a PEP 302 \"Importer\" (sys.path item\n    handler), and `namespace_handler` is a callable like this::\n\n        def namespace_handler(importer, path_entry, moduleName, module):\n            # return a path_entry to use for child packages\n\n    Namespace handlers are only called if the importer object has already\n    agreed that it can handle the relevant path item, and they should only\n    return a subpath if the module __path__ does not already contain an\n    equivalent subpath.  For an example namespace handler, see\n    ``pkg_resources.file_ns_handler``.\n    \"\"\"\n    _namespace_handlers[importer_type] = namespace_handler\n\n\ndef _handle_ns(packageName, path_item):\n    \"\"\"Ensure that named package includes a subpath of path_item (if needed)\"\"\"\n\n    importer = get_importer(path_item)\n    if importer is None:\n        return None\n\n    # capture warnings due to #1111\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        loader = importer.find_module(packageName)\n\n    if loader is None:\n        return None\n    module = sys.modules.get(packageName)\n    if module is None:\n        module = sys.modules[packageName] = types.ModuleType(packageName)\n        module.__path__ = []\n        _set_parent_ns(packageName)\n    elif not hasattr(module, '__path__'):\n        raise TypeError(\"Not a package:\", packageName)\n    handler = _find_adapter(_namespace_handlers, importer)\n    subpath = handler(importer, path_item, packageName, module)\n    if subpath is not None:\n        path = module.__path__\n        path.append(subpath)\n        loader.load_module(packageName)\n        _rebuild_mod_path(path, packageName, module)\n    return subpath\n\n\ndef _rebuild_mod_path(orig_path, package_name, module):\n    \"\"\"\n    Rebuild module.__path__ ensuring that all entries are ordered\n    corresponding to their sys.path order\n    \"\"\"\n    sys_path = [_normalize_cached(p) for p in sys.path]\n\n    def safe_sys_path_index(entry):\n        \"\"\"\n        Workaround for #520 and #513.\n        \"\"\"\n        try:\n            return sys_path.index(entry)\n        except ValueError:\n            return float('inf')\n\n    def position_in_sys_path(path):\n        \"\"\"\n        Return the ordinal of the path based on its position in sys.path\n        \"\"\"\n        path_parts = path.split(os.sep)\n        module_parts = package_name.count('.') + 1\n        parts = path_parts[:-module_parts]\n        return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))\n\n    new_path = sorted(orig_path, key=position_in_sys_path)\n    new_path = [_normalize_cached(p) for p in new_path]\n\n    if isinstance(module.__path__, list):\n        module.__path__[:] = new_path\n    else:\n        module.__path__ = new_path\n\n\ndef declare_namespace(packageName):\n    \"\"\"Declare that package 'packageName' is a namespace package\"\"\"\n\n    _imp.acquire_lock()\n    try:\n        if packageName in _namespace_packages:\n            return\n\n        path = sys.path\n        parent, _, _ = packageName.rpartition('.')\n\n        if parent:\n            declare_namespace(parent)\n            if parent not in _namespace_packages:\n                __import__(parent)\n            try:\n                path = sys.modules[parent].__path__\n            except AttributeError:\n                raise TypeError(\"Not a package:\", parent)\n\n        # Track what packages are namespaces, so when new path items are added,\n        # they can be updated\n        _namespace_packages.setdefault(parent or None, []).append(packageName)\n        _namespace_packages.setdefault(packageName, [])\n\n        for path_item in path:\n            # Ensure all the parent's path items are reflected in the child,\n            # if they apply\n            _handle_ns(packageName, path_item)\n\n    finally:\n        _imp.release_lock()\n\n\ndef fixup_namespace_packages(path_item, parent=None):\n    \"\"\"Ensure that previously-declared namespace packages include path_item\"\"\"\n    _imp.acquire_lock()\n    try:\n        for package in _namespace_packages.get(parent, ()):\n            subpath = _handle_ns(package, path_item)\n            if subpath:\n                fixup_namespace_packages(subpath, package)\n    finally:\n        _imp.release_lock()\n\n\ndef file_ns_handler(importer, path_item, packageName, module):\n    \"\"\"Compute an ns-package subpath for a filesystem or zipfile importer\"\"\"\n\n    subpath = os.path.join(path_item, packageName.split('.')[-1])\n    normalized = _normalize_cached(subpath)\n    for item in module.__path__:\n        if _normalize_cached(item) == normalized:\n            break\n    else:\n        # Only return the path if it's not already there\n        return subpath\n\n\nregister_namespace_handler(pkgutil.ImpImporter, file_ns_handler)\nregister_namespace_handler(zipimport.zipimporter, file_ns_handler)\n\nif hasattr(importlib_machinery, 'FileFinder'):\n    register_namespace_handler(importlib_machinery.FileFinder, file_ns_handler)\n\n\ndef null_ns_handler(importer, path_item, packageName, module):\n    return None\n\n\nregister_namespace_handler(object, null_ns_handler)\n\n\ndef normalize_path(filename):\n    \"\"\"Normalize a file/dir name for comparison purposes\"\"\"\n    return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename))))\n\n\ndef _cygwin_patch(filename):  # pragma: nocover\n    \"\"\"\n    Contrary to POSIX 2008, on Cygwin, getcwd (3) contains\n    symlink components. Using\n    os.path.abspath() works around this limitation. A fix in os.getcwd()\n    would probably better, in Cygwin even more so, except\n    that this seems to be by design...\n    \"\"\"\n    return os.path.abspath(filename) if sys.platform == 'cygwin' else filename\n\n\ndef _normalize_cached(filename, _cache={}):\n    try:\n        return _cache[filename]\n    except KeyError:\n        _cache[filename] = result = normalize_path(filename)\n        return result\n\n\ndef _is_egg_path(path):\n    \"\"\"\n    Determine if given path appears to be an egg.\n    \"\"\"\n    return path.lower().endswith('.egg')\n\n\ndef _is_unpacked_egg(path):\n    \"\"\"\n    Determine if given path appears to be an unpacked egg.\n    \"\"\"\n    return (\n        _is_egg_path(path) and\n        os.path.isfile(os.path.join(path, 'EGG-INFO', 'PKG-INFO'))\n    )\n\n\ndef _set_parent_ns(packageName):\n    parts = packageName.split('.')\n    name = parts.pop()\n    if parts:\n        parent = '.'.join(parts)\n        setattr(sys.modules[parent], name, sys.modules[packageName])\n\n\ndef yield_lines(strs):\n    \"\"\"Yield non-empty/non-comment lines of a string or sequence\"\"\"\n    if isinstance(strs, six.string_types):\n        for s in strs.splitlines():\n            s = s.strip()\n            # skip blank lines/comments\n            if s and not s.startswith('#'):\n                yield s\n    else:\n        for ss in strs:\n            for s in yield_lines(ss):\n                yield s\n\n\nMODULE = re.compile(r\"\\w+(\\.\\w+)*$\").match\nEGG_NAME = re.compile(\n    r\"\"\"\n    (?P<name>[^-]+) (\n        -(?P<ver>[^-]+) (\n            -py(?P<pyver>[^-]+) (\n                -(?P<plat>.+)\n            )?\n        )?\n    )?\n    \"\"\",\n    re.VERBOSE | re.IGNORECASE,\n).match\n\n\nclass EntryPoint:\n    \"\"\"Object representing an advertised importable object\"\"\"\n\n    def __init__(self, name, module_name, attrs=(), extras=(), dist=None):\n        if not MODULE(module_name):\n            raise ValueError(\"Invalid module name\", module_name)\n        self.name = name\n        self.module_name = module_name\n        self.attrs = tuple(attrs)\n        self.extras = tuple(extras)\n        self.dist = dist\n\n    def __str__(self):\n        s = \"%s = %s\" % (self.name, self.module_name)\n        if self.attrs:\n            s += ':' + '.'.join(self.attrs)\n        if self.extras:\n            s += ' [%s]' % ','.join(self.extras)\n        return s\n\n    def __repr__(self):\n        return \"EntryPoint.parse(%r)\" % str(self)\n\n    def load(self, require=True, *args, **kwargs):\n        \"\"\"\n        Require packages for this EntryPoint, then resolve it.\n        \"\"\"\n        if not require or args or kwargs:\n            warnings.warn(\n                \"Parameters to load are deprecated.  Call .resolve and \"\n                \".require separately.\",\n                PkgResourcesDeprecationWarning,\n                stacklevel=2,\n            )\n        if require:\n            self.require(*args, **kwargs)\n        return self.resolve()\n\n    def resolve(self):\n        \"\"\"\n        Resolve the entry point from its module and attrs.\n        \"\"\"\n        module = __import__(self.module_name, fromlist=['__name__'], level=0)\n        try:\n            return functools.reduce(getattr, self.attrs, module)\n        except AttributeError as exc:\n            raise ImportError(str(exc))\n\n    def require(self, env=None, installer=None):\n        if self.extras and not self.dist:\n            raise UnknownExtra(\"Can't require() without a distribution\", self)\n\n        # Get the requirements for this entry point with all its extras and\n        # then resolve them. We have to pass `extras` along when resolving so\n        # that the working set knows what extras we want. Otherwise, for\n        # dist-info distributions, the working set will assume that the\n        # requirements for that extra are purely optional and skip over them.\n        reqs = self.dist.requires(self.extras)\n        items = working_set.resolve(reqs, env, installer, extras=self.extras)\n        list(map(working_set.add, items))\n\n    pattern = re.compile(\n        r'\\s*'\n        r'(?P<name>.+?)\\s*'\n        r'=\\s*'\n        r'(?P<module>[\\w.]+)\\s*'\n        r'(:\\s*(?P<attr>[\\w.]+))?\\s*'\n        r'(?P<extras>\\[.*\\])?\\s*$'\n    )\n\n    @classmethod\n    def parse(cls, src, dist=None):\n        \"\"\"Parse a single entry point from string `src`\n\n        Entry point syntax follows the form::\n\n            name = some.module:some.attr [extra1, extra2]\n\n        The entry name and module name are required, but the ``:attrs`` and\n        ``[extras]`` parts are optional\n        \"\"\"\n        m = cls.pattern.match(src)\n        if not m:\n            msg = \"EntryPoint must be in 'name=module:attrs [extras]' format\"\n            raise ValueError(msg, src)\n        res = m.groupdict()\n        extras = cls._parse_extras(res['extras'])\n        attrs = res['attr'].split('.') if res['attr'] else ()\n        return cls(res['name'], res['module'], attrs, extras, dist)\n\n    @classmethod\n    def _parse_extras(cls, extras_spec):\n        if not extras_spec:\n            return ()\n        req = Requirement.parse('x' + extras_spec)\n        if req.specs:\n            raise ValueError()\n        return req.extras\n\n    @classmethod\n    def parse_group(cls, group, lines, dist=None):\n        \"\"\"Parse an entry point group\"\"\"\n        if not MODULE(group):\n            raise ValueError(\"Invalid group name\", group)\n        this = {}\n        for line in yield_lines(lines):\n            ep = cls.parse(line, dist)\n            if ep.name in this:\n                raise ValueError(\"Duplicate entry point\", group, ep.name)\n            this[ep.name] = ep\n        return this\n\n    @classmethod\n    def parse_map(cls, data, dist=None):\n        \"\"\"Parse a map of entry point groups\"\"\"\n        if isinstance(data, dict):\n            data = data.items()\n        else:\n            data = split_sections(data)\n        maps = {}\n        for group, lines in data:\n            if group is None:\n                if not lines:\n                    continue\n                raise ValueError(\"Entry points must be listed in groups\")\n            group = group.strip()\n            if group in maps:\n                raise ValueError(\"Duplicate group name\", group)\n            maps[group] = cls.parse_group(group, lines, dist)\n        return maps\n\n\ndef _remove_md5_fragment(location):\n    if not location:\n        return ''\n    parsed = urllib.parse.urlparse(location)\n    if parsed[-1].startswith('md5='):\n        return urllib.parse.urlunparse(parsed[:-1] + ('',))\n    return location\n\n\ndef _version_from_file(lines):\n    \"\"\"\n    Given an iterable of lines from a Metadata file, return\n    the value of the Version field, if present, or None otherwise.\n    \"\"\"\n    def is_version_line(line):\n        return line.lower().startswith('version:')\n    version_lines = filter(is_version_line, lines)\n    line = next(iter(version_lines), '')\n    _, _, value = line.partition(':')\n    return safe_version(value.strip()) or None\n\n\nclass Distribution:\n    \"\"\"Wrap an actual or potential sys.path entry w/metadata\"\"\"\n    PKG_INFO = 'PKG-INFO'\n\n    def __init__(\n            self, location=None, metadata=None, project_name=None,\n            version=None, py_version=PY_MAJOR, platform=None,\n            precedence=EGG_DIST):\n        self.project_name = safe_name(project_name or 'Unknown')\n        if version is not None:\n            self._version = safe_version(version)\n        self.py_version = py_version\n        self.platform = platform\n        self.location = location\n        self.precedence = precedence\n        self._provider = metadata or empty_provider\n\n    @classmethod\n    def from_location(cls, location, basename, metadata=None, **kw):\n        project_name, version, py_version, platform = [None] * 4\n        basename, ext = os.path.splitext(basename)\n        if ext.lower() in _distributionImpl:\n            cls = _distributionImpl[ext.lower()]\n\n            match = EGG_NAME(basename)\n            if match:\n                project_name, version, py_version, platform = match.group(\n                    'name', 'ver', 'pyver', 'plat'\n                )\n        return cls(\n            location, metadata, project_name=project_name, version=version,\n            py_version=py_version, platform=platform, **kw\n        )._reload_version()\n\n    def _reload_version(self):\n        return self\n\n    @property\n    def hashcmp(self):\n        return (\n            self.parsed_version,\n            self.precedence,\n            self.key,\n            _remove_md5_fragment(self.location),\n            self.py_version or '',\n            self.platform or '',\n        )\n\n    def __hash__(self):\n        return hash(self.hashcmp)\n\n    def __lt__(self, other):\n        return self.hashcmp < other.hashcmp\n\n    def __le__(self, other):\n        return self.hashcmp <= other.hashcmp\n\n    def __gt__(self, other):\n        return self.hashcmp > other.hashcmp\n\n    def __ge__(self, other):\n        return self.hashcmp >= other.hashcmp\n\n    def __eq__(self, other):\n        if not isinstance(other, self.__class__):\n            # It's not a Distribution, so they are not equal\n            return False\n        return self.hashcmp == other.hashcmp\n\n    def __ne__(self, other):\n        return not self == other\n\n    # These properties have to be lazy so that we don't have to load any\n    # metadata until/unless it's actually needed.  (i.e., some distributions\n    # may not know their name or version without loading PKG-INFO)\n\n    @property\n    def key(self):\n        try:\n            return self._key\n        except AttributeError:\n            self._key = key = self.project_name.lower()\n            return key\n\n    @property\n    def parsed_version(self):\n        if not hasattr(self, \"_parsed_version\"):\n            self._parsed_version = parse_version(self.version)\n\n        return self._parsed_version\n\n    def _warn_legacy_version(self):\n        LV = packaging.version.LegacyVersion\n        is_legacy = isinstance(self._parsed_version, LV)\n        if not is_legacy:\n            return\n\n        # While an empty version is technically a legacy version and\n        # is not a valid PEP 440 version, it's also unlikely to\n        # actually come from someone and instead it is more likely that\n        # it comes from setuptools attempting to parse a filename and\n        # including it in the list. So for that we'll gate this warning\n        # on if the version is anything at all or not.\n        if not self.version:\n            return\n\n        tmpl = textwrap.dedent(\"\"\"\n            '{project_name} ({version})' is being parsed as a legacy,\n            non PEP 440,\n            version. You may find odd behavior and sort order.\n            In particular it will be sorted as less than 0.0. It\n            is recommended to migrate to PEP 440 compatible\n            versions.\n            \"\"\").strip().replace('\\n', ' ')\n\n        warnings.warn(tmpl.format(**vars(self)), PEP440Warning)\n\n    @property\n    def version(self):\n        try:\n            return self._version\n        except AttributeError:\n            version = self._get_version()\n            if version is None:\n                path = self._get_metadata_path_for_display(self.PKG_INFO)\n                msg = (\n                    \"Missing 'Version:' header and/or {} file at path: {}\"\n                ).format(self.PKG_INFO, path)\n                raise ValueError(msg, self)\n\n            return version\n\n    @property\n    def _dep_map(self):\n        \"\"\"\n        A map of extra to its list of (direct) requirements\n        for this distribution, including the null extra.\n        \"\"\"\n        try:\n            return self.__dep_map\n        except AttributeError:\n            self.__dep_map = self._filter_extras(self._build_dep_map())\n        return self.__dep_map\n\n    @staticmethod\n    def _filter_extras(dm):\n        \"\"\"\n        Given a mapping of extras to dependencies, strip off\n        environment markers and filter out any dependencies\n        not matching the markers.\n        \"\"\"\n        for extra in list(filter(None, dm)):\n            new_extra = extra\n            reqs = dm.pop(extra)\n            new_extra, _, marker = extra.partition(':')\n            fails_marker = marker and (\n                invalid_marker(marker)\n                or not evaluate_marker(marker)\n            )\n            if fails_marker:\n                reqs = []\n            new_extra = safe_extra(new_extra) or None\n\n            dm.setdefault(new_extra, []).extend(reqs)\n        return dm\n\n    def _build_dep_map(self):\n        dm = {}\n        for name in 'requires.txt', 'depends.txt':\n            for extra, reqs in split_sections(self._get_metadata(name)):\n                dm.setdefault(extra, []).extend(parse_requirements(reqs))\n        return dm\n\n    def requires(self, extras=()):\n        \"\"\"List of Requirements needed for this distro if `extras` are used\"\"\"\n        dm = self._dep_map\n        deps = []\n        deps.extend(dm.get(None, ()))\n        for ext in extras:\n            try:\n                deps.extend(dm[safe_extra(ext)])\n            except KeyError:\n                raise UnknownExtra(\n                    \"%s has no such extra feature %r\" % (self, ext)\n                )\n        return deps\n\n    def _get_metadata_path_for_display(self, name):\n        \"\"\"\n        Return the path to the given metadata file, if available.\n        \"\"\"\n        try:\n            # We need to access _get_metadata_path() on the provider object\n            # directly rather than through this class's __getattr__()\n            # since _get_metadata_path() is marked private.\n            path = self._provider._get_metadata_path(name)\n\n        # Handle exceptions e.g. in case the distribution's metadata\n        # provider doesn't support _get_metadata_path().\n        except Exception:\n            return '[could not detect]'\n\n        return path\n\n    def _get_metadata(self, name):\n        if self.has_metadata(name):\n            for line in self.get_metadata_lines(name):\n                yield line\n\n    def _get_version(self):\n        lines = self._get_metadata(self.PKG_INFO)\n        version = _version_from_file(lines)\n\n        return version\n\n    def activate(self, path=None, replace=False):\n        \"\"\"Ensure distribution is importable on `path` (default=sys.path)\"\"\"\n        if path is None:\n            path = sys.path\n        self.insert_on(path, replace=replace)\n        if path is sys.path:\n            fixup_namespace_packages(self.location)\n            for pkg in self._get_metadata('namespace_packages.txt'):\n                if pkg in sys.modules:\n                    declare_namespace(pkg)\n\n    def egg_name(self):\n        \"\"\"Return what this distribution's standard .egg filename should be\"\"\"\n        filename = \"%s-%s-py%s\" % (\n            to_filename(self.project_name), to_filename(self.version),\n            self.py_version or PY_MAJOR\n        )\n\n        if self.platform:\n            filename += '-' + self.platform\n        return filename\n\n    def __repr__(self):\n        if self.location:\n            return \"%s (%s)\" % (self, self.location)\n        else:\n            return str(self)\n\n    def __str__(self):\n        try:\n            version = getattr(self, 'version', None)\n        except ValueError:\n            version = None\n        version = version or \"[unknown version]\"\n        return \"%s %s\" % (self.project_name, version)\n\n    def __getattr__(self, attr):\n        \"\"\"Delegate all unrecognized public attributes to .metadata provider\"\"\"\n        if attr.startswith('_'):\n            raise AttributeError(attr)\n        return getattr(self._provider, attr)\n\n    def __dir__(self):\n        return list(\n            set(super(Distribution, self).__dir__())\n            | set(\n                attr for attr in self._provider.__dir__()\n                if not attr.startswith('_')\n            )\n        )\n\n    if not hasattr(object, '__dir__'):\n        # python 2.7 not supported\n        del __dir__\n\n    @classmethod\n    def from_filename(cls, filename, metadata=None, **kw):\n        return cls.from_location(\n            _normalize_cached(filename), os.path.basename(filename), metadata,\n            **kw\n        )\n\n    def as_requirement(self):\n        \"\"\"Return a ``Requirement`` that matches this distribution exactly\"\"\"\n        if isinstance(self.parsed_version, packaging.version.Version):\n            spec = \"%s==%s\" % (self.project_name, self.parsed_version)\n        else:\n            spec = \"%s===%s\" % (self.project_name, self.parsed_version)\n\n        return Requirement.parse(spec)\n\n    def load_entry_point(self, group, name):\n        \"\"\"Return the `name` entry point of `group` or raise ImportError\"\"\"\n        ep = self.get_entry_info(group, name)\n        if ep is None:\n            raise ImportError(\"Entry point %r not found\" % ((group, name),))\n        return ep.load()\n\n    def get_entry_map(self, group=None):\n        \"\"\"Return the entry point map for `group`, or the full entry map\"\"\"\n        try:\n            ep_map = self._ep_map\n        except AttributeError:\n            ep_map = self._ep_map = EntryPoint.parse_map(\n                self._get_metadata('entry_points.txt'), self\n            )\n        if group is not None:\n            return ep_map.get(group, {})\n        return ep_map\n\n    def get_entry_info(self, group, name):\n        \"\"\"Return the EntryPoint object for `group`+`name`, or ``None``\"\"\"\n        return self.get_entry_map(group).get(name)\n\n    def insert_on(self, path, loc=None, replace=False):\n        \"\"\"Ensure self.location is on path\n\n        If replace=False (default):\n            - If location is already in path anywhere, do nothing.\n            - Else:\n              - If it's an egg and its parent directory is on path,\n                insert just ahead of the parent.\n              - Else: add to the end of path.\n        If replace=True:\n            - If location is already on path anywhere (not eggs)\n              or higher priority than its parent (eggs)\n              do nothing.\n            - Else:\n              - If it's an egg and its parent directory is on path,\n                insert just ahead of the parent,\n                removing any lower-priority entries.\n              - Else: add it to the front of path.\n        \"\"\"\n\n        loc = loc or self.location\n        if not loc:\n            return\n\n        nloc = _normalize_cached(loc)\n        bdir = os.path.dirname(nloc)\n        npath = [(p and _normalize_cached(p) or p) for p in path]\n\n        for p, item in enumerate(npath):\n            if item == nloc:\n                if replace:\n                    break\n                else:\n                    # don't modify path (even removing duplicates) if\n                    # found and not replace\n                    return\n            elif item == bdir and self.precedence == EGG_DIST:\n                # if it's an .egg, give it precedence over its directory\n                # UNLESS it's already been added to sys.path and replace=False\n                if (not replace) and nloc in npath[p:]:\n                    return\n                if path is sys.path:\n                    self.check_version_conflict()\n                path.insert(p, loc)\n                npath.insert(p, nloc)\n                break\n        else:\n            if path is sys.path:\n                self.check_version_conflict()\n            if replace:\n                path.insert(0, loc)\n            else:\n                path.append(loc)\n            return\n\n        # p is the spot where we found or inserted loc; now remove duplicates\n        while True:\n            try:\n                np = npath.index(nloc, p + 1)\n            except ValueError:\n                break\n            else:\n                del npath[np], path[np]\n                # ha!\n                p = np\n\n        return\n\n    def check_version_conflict(self):\n        if self.key == 'setuptools':\n            # ignore the inevitable setuptools self-conflicts  :(\n            return\n\n        nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))\n        loc = normalize_path(self.location)\n        for modname in self._get_metadata('top_level.txt'):\n            if (modname not in sys.modules or modname in nsp\n                    or modname in _namespace_packages):\n                continue\n            if modname in ('pkg_resources', 'setuptools', 'site'):\n                continue\n            fn = getattr(sys.modules[modname], '__file__', None)\n            if fn and (normalize_path(fn).startswith(loc) or\n                       fn.startswith(self.location)):\n                continue\n            issue_warning(\n                \"Module %s was already imported from %s, but %s is being added\"\n                \" to sys.path\" % (modname, fn, self.location),\n            )\n\n    def has_version(self):\n        try:\n            self.version\n        except ValueError:\n            issue_warning(\"Unbuilt egg for \" + repr(self))\n            return False\n        return True\n\n    def clone(self, **kw):\n        \"\"\"Copy this distribution, substituting in any changed keyword args\"\"\"\n        names = 'project_name version py_version platform location precedence'\n        for attr in names.split():\n            kw.setdefault(attr, getattr(self, attr, None))\n        kw.setdefault('metadata', self._provider)\n        return self.__class__(**kw)\n\n    @property\n    def extras(self):\n        return [dep for dep in self._dep_map if dep]\n\n\nclass EggInfoDistribution(Distribution):\n    def _reload_version(self):\n        \"\"\"\n        Packages installed by distutils (e.g. numpy or scipy),\n        which uses an old safe_version, and so\n        their version numbers can get mangled when\n        converted to filenames (e.g., 1.11.0.dev0+2329eae to\n        1.11.0.dev0_2329eae). These distributions will not be\n        parsed properly\n        downstream by Distribution and safe_version, so\n        take an extra step and try to get the version number from\n        the metadata file itself instead of the filename.\n        \"\"\"\n        md_version = self._get_version()\n        if md_version:\n            self._version = md_version\n        return self\n\n\nclass DistInfoDistribution(Distribution):\n    \"\"\"\n    Wrap an actual or potential sys.path entry\n    w/metadata, .dist-info style.\n    \"\"\"\n    PKG_INFO = 'METADATA'\n    EQEQ = re.compile(r\"([\\(,])\\s*(\\d.*?)\\s*([,\\)])\")\n\n    @property\n    def _parsed_pkg_info(self):\n        \"\"\"Parse and cache metadata\"\"\"\n        try:\n            return self._pkg_info\n        except AttributeError:\n            metadata = self.get_metadata(self.PKG_INFO)\n            self._pkg_info = email.parser.Parser().parsestr(metadata)\n            return self._pkg_info\n\n    @property\n    def _dep_map(self):\n        try:\n            return self.__dep_map\n        except AttributeError:\n            self.__dep_map = self._compute_dependencies()\n            return self.__dep_map\n\n    def _compute_dependencies(self):\n        \"\"\"Recompute this distribution's dependencies.\"\"\"\n        dm = self.__dep_map = {None: []}\n\n        reqs = []\n        # Including any condition expressions\n        for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:\n            reqs.extend(parse_requirements(req))\n\n        def reqs_for_extra(extra):\n            for req in reqs:\n                if not req.marker or req.marker.evaluate({'extra': extra}):\n                    yield req\n\n        common = frozenset(reqs_for_extra(None))\n        dm[None].extend(common)\n\n        for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:\n            s_extra = safe_extra(extra.strip())\n            dm[s_extra] = list(frozenset(reqs_for_extra(extra)) - common)\n\n        return dm\n\n\n_distributionImpl = {\n    '.egg': Distribution,\n    '.egg-info': EggInfoDistribution,\n    '.dist-info': DistInfoDistribution,\n}\n\n\ndef issue_warning(*args, **kw):\n    level = 1\n    g = globals()\n    try:\n        # find the first stack frame that is *not* code in\n        # the pkg_resources module, to use for the warning\n        while sys._getframe(level).f_globals is g:\n            level += 1\n    except ValueError:\n        pass\n    warnings.warn(stacklevel=level + 1, *args, **kw)\n\n\nclass RequirementParseError(ValueError):\n    def __str__(self):\n        return ' '.join(self.args)\n\n\ndef parse_requirements(strs):\n    \"\"\"Yield ``Requirement`` objects for each specification in `strs`\n\n    `strs` must be a string, or a (possibly-nested) iterable thereof.\n    \"\"\"\n    # create a steppable iterator, so we can handle \\-continuations\n    lines = iter(yield_lines(strs))\n\n    for line in lines:\n        # Drop comments -- a hash without a space may be in a URL.\n        if ' #' in line:\n            line = line[:line.find(' #')]\n        # If there is a line continuation, drop it, and append the next line.\n        if line.endswith('\\\\'):\n            line = line[:-2].strip()\n            try:\n                line += next(lines)\n            except StopIteration:\n                return\n        yield Requirement(line)\n\n\nclass Requirement(packaging.requirements.Requirement):\n    def __init__(self, requirement_string):\n        \"\"\"DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!\"\"\"\n        try:\n            super(Requirement, self).__init__(requirement_string)\n        except packaging.requirements.InvalidRequirement as e:\n            raise RequirementParseError(str(e))\n        self.unsafe_name = self.name\n        project_name = safe_name(self.name)\n        self.project_name, self.key = project_name, project_name.lower()\n        self.specs = [\n            (spec.operator, spec.version) for spec in self.specifier]\n        self.extras = tuple(map(safe_extra, self.extras))\n        self.hashCmp = (\n            self.key,\n            self.url,\n            self.specifier,\n            frozenset(self.extras),\n            str(self.marker) if self.marker else None,\n        )\n        self.__hash = hash(self.hashCmp)\n\n    def __eq__(self, other):\n        return (\n            isinstance(other, Requirement) and\n            self.hashCmp == other.hashCmp\n        )\n\n    def __ne__(self, other):\n        return not self == other\n\n    def __contains__(self, item):\n        if isinstance(item, Distribution):\n            if item.key != self.key:\n                return False\n\n            item = item.version\n\n        # Allow prereleases always in order to match the previous behavior of\n        # this method. In the future this should be smarter and follow PEP 440\n        # more accurately.\n        return self.specifier.contains(item, prereleases=True)\n\n    def __hash__(self):\n        return self.__hash\n\n    def __repr__(self):\n        return \"Requirement.parse(%r)\" % str(self)\n\n    @staticmethod\n    def parse(s):\n        req, = parse_requirements(s)\n        return req\n\n\ndef _always_object(classes):\n    \"\"\"\n    Ensure object appears in the mro even\n    for old-style classes.\n    \"\"\"\n    if object not in classes:\n        return classes + (object,)\n    return classes\n\n\ndef _find_adapter(registry, ob):\n    \"\"\"Return an adapter factory for `ob` from `registry`\"\"\"\n    types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))\n    for t in types:\n        if t in registry:\n            return registry[t]\n\n\ndef ensure_directory(path):\n    \"\"\"Ensure that the parent directory of `path` exists\"\"\"\n    dirname = os.path.dirname(path)\n    py31compat.makedirs(dirname, exist_ok=True)\n\n\ndef _bypass_ensure_directory(path):\n    \"\"\"Sandbox-bypassing version of ensure_directory()\"\"\"\n    if not WRITE_SUPPORT:\n        raise IOError('\"os.mkdir\" not supported on this platform.')\n    dirname, filename = split(path)\n    if dirname and filename and not isdir(dirname):\n        _bypass_ensure_directory(dirname)\n        try:\n            mkdir(dirname, 0o755)\n        except FileExistsError:\n            pass\n\n\ndef split_sections(s):\n    \"\"\"Split a string or iterable thereof into (section, content) pairs\n\n    Each ``section`` is a stripped version of the section header (\"[section]\")\n    and each ``content`` is a list of stripped lines excluding blank lines and\n    comment-only lines.  If there are any such lines before the first section\n    header, they're returned in a first ``section`` of ``None``.\n    \"\"\"\n    section = None\n    content = []\n    for line in yield_lines(s):\n        if line.startswith(\"[\"):\n            if line.endswith(\"]\"):\n                if section or content:\n                    yield section, content\n                section = line[1:-1].strip()\n                content = []\n            else:\n                raise ValueError(\"Invalid section heading\", line)\n        else:\n            content.append(line)\n\n    # wrap up last segment\n    yield section, content\n\n\ndef _mkstemp(*args, **kw):\n    old_open = os.open\n    try:\n        # temporarily bypass sandboxing\n        os.open = os_open\n        return tempfile.mkstemp(*args, **kw)\n    finally:\n        # and then put it back\n        os.open = old_open\n\n\n# Silence the PEP440Warning by default, so that end users don't get hit by it\n# randomly just because they use pkg_resources. We want to append the rule\n# because we want earlier uses of filterwarnings to take precedence over this\n# one.\nwarnings.filterwarnings(\"ignore\", category=PEP440Warning, append=True)\n\n\n# from jaraco.functools 1.3\ndef _call_aside(f, *args, **kwargs):\n    f(*args, **kwargs)\n    return f\n\n\n@_call_aside\ndef _initialize(g=globals()):\n    \"Set up global resource manager (deliberately not state-saved)\"\n    manager = ResourceManager()\n    g['_manager'] = manager\n    g.update(\n        (name, getattr(manager, name))\n        for name in dir(manager)\n        if not name.startswith('_')\n    )\n\n\n@_call_aside\ndef _initialize_master_working_set():\n    \"\"\"\n    Prepare the master working set and make the ``require()``\n    API available.\n\n    This function has explicit effects on the global state\n    of pkg_resources. It is intended to be invoked once at\n    the initialization of this module.\n\n    Invocation by other packages is unsupported and done\n    at their own risk.\n    \"\"\"\n    working_set = WorkingSet._build_master()\n    _declare_state('object', working_set=working_set)\n\n    require = working_set.require\n    iter_entry_points = working_set.iter_entry_points\n    add_activation_listener = working_set.subscribe\n    run_script = working_set.run_script\n    # backward compatibility\n    run_main = run_script\n    # Activate all distributions already on sys.path with replace=False and\n    # ensure that all distributions added to the working set in the future\n    # (e.g. by calling ``require()``) will get activated as well,\n    # with higher priority (replace=True).\n    tuple(\n        dist.activate(replace=False)\n        for dist in working_set\n    )\n    add_activation_listener(\n        lambda dist: dist.activate(replace=True),\n        existing=False,\n    )\n    working_set.entries = []\n    # match order\n    list(map(working_set.add_entry, sys.path))\n    globals().update(locals())\n\nclass PkgResourcesDeprecationWarning(Warning):\n    \"\"\"\n    Base class for warning about deprecations in ``pkg_resources``\n\n    This class is not derived from ``DeprecationWarning``, and as such is\n    visible by default.\n    \"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pkg_resources/py31compat.py",
    "content": "import os\nimport errno\nimport sys\n\nfrom pip._vendor import six\n\n\ndef _makedirs_31(path, exist_ok=False):\n    try:\n        os.makedirs(path)\n    except OSError as exc:\n        if not exist_ok or exc.errno != errno.EEXIST:\n            raise\n\n\n# rely on compatibility behavior until mode considerations\n#  and exists_ok considerations are disentangled.\n# See https://github.com/pypa/setuptools/pull/1083#issuecomment-315168663\nneeds_makedirs = (\n    six.PY2 or\n    (3, 4) <= sys.version_info < (3, 4, 1)\n)\nmakedirs = _makedirs_31 if needs_makedirs else os.makedirs\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/platformdirs/__init__.py",
    "content": "\"\"\"\nUtilities for determining application-specific dirs. See <https://github.com/platformdirs/platformdirs> for details and\nusage.\n\"\"\"\nfrom __future__ import annotations\n\nimport os\nimport sys\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from pip._vendor.typing_extensions import Literal  # pragma: no cover\n\nfrom .api import PlatformDirsABC\nfrom .version import __version__, __version_info__\n\n\ndef _set_platform_dir_class() -> type[PlatformDirsABC]:\n    if sys.platform == \"win32\":\n        from pip._vendor.platformdirs.windows import Windows as Result\n    elif sys.platform == \"darwin\":\n        from pip._vendor.platformdirs.macos import MacOS as Result\n    else:\n        from pip._vendor.platformdirs.unix import Unix as Result\n\n    if os.getenv(\"ANDROID_DATA\") == \"/data\" and os.getenv(\"ANDROID_ROOT\") == \"/system\":\n\n        if os.getenv(\"SHELL\") is not None:\n            return Result\n\n        from pip._vendor.platformdirs.android import _android_folder\n\n        if _android_folder() is not None:\n            from pip._vendor.platformdirs.android import Android\n\n            return Android  # return to avoid redefinition of result\n\n    return Result\n\n\nPlatformDirs = _set_platform_dir_class()  #: Currently active platform\nAppDirs = PlatformDirs  #: Backwards compatibility with appdirs\n\n\ndef user_data_dir(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    roaming: bool = False,\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param roaming: See `roaming <platformdirs.api.PlatformDirsABC.version>`.\n    :returns: data directory tied to the user\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_data_dir\n\n\ndef site_data_dir(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    multipath: bool = False,\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param multipath: See `roaming <platformdirs.api.PlatformDirsABC.multipath>`.\n    :returns: data directory shared by users\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, multipath=multipath).site_data_dir\n\n\ndef user_config_dir(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    roaming: bool = False,\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param roaming: See `roaming <platformdirs.api.PlatformDirsABC.version>`.\n    :returns: config directory tied to the user\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_config_dir\n\n\ndef site_config_dir(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    multipath: bool = False,\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param multipath: See `roaming <platformdirs.api.PlatformDirsABC.multipath>`.\n    :returns: config directory shared by the users\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, multipath=multipath).site_config_dir\n\n\ndef user_cache_dir(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    opinion: bool = True,\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `roaming <platformdirs.api.PlatformDirsABC.opinion>`.\n    :returns: cache directory tied to the user\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_cache_dir\n\n\ndef user_state_dir(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    roaming: bool = False,\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param roaming: See `roaming <platformdirs.api.PlatformDirsABC.version>`.\n    :returns: state directory tied to the user\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_state_dir\n\n\ndef user_log_dir(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    opinion: bool = True,\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `roaming <platformdirs.api.PlatformDirsABC.opinion>`.\n    :returns: log directory tied to the user\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_log_dir\n\n\ndef user_documents_dir() -> str:\n    \"\"\"\n    :returns: documents directory tied to the user\n    \"\"\"\n    return PlatformDirs().user_documents_dir\n\n\ndef user_runtime_dir(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    opinion: bool = True,\n) -> str:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `opinion <platformdirs.api.PlatformDirsABC.opinion>`.\n    :returns: runtime directory tied to the user\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_runtime_dir\n\n\ndef user_data_path(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    roaming: bool = False,\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param roaming: See `roaming <platformdirs.api.PlatformDirsABC.version>`.\n    :returns: data path tied to the user\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_data_path\n\n\ndef site_data_path(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    multipath: bool = False,\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param multipath: See `multipath <platformdirs.api.PlatformDirsABC.multipath>`.\n    :returns: data path shared by users\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, multipath=multipath).site_data_path\n\n\ndef user_config_path(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    roaming: bool = False,\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param roaming: See `roaming <platformdirs.api.PlatformDirsABC.version>`.\n    :returns: config path tied to the user\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_config_path\n\n\ndef site_config_path(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    multipath: bool = False,\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param multipath: See `roaming <platformdirs.api.PlatformDirsABC.multipath>`.\n    :returns: config path shared by the users\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, multipath=multipath).site_config_path\n\n\ndef user_cache_path(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    opinion: bool = True,\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `roaming <platformdirs.api.PlatformDirsABC.opinion>`.\n    :returns: cache path tied to the user\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_cache_path\n\n\ndef user_state_path(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    roaming: bool = False,\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param roaming: See `roaming <platformdirs.api.PlatformDirsABC.version>`.\n    :returns: state path tied to the user\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, roaming=roaming).user_state_path\n\n\ndef user_log_path(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    opinion: bool = True,\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `roaming <platformdirs.api.PlatformDirsABC.opinion>`.\n    :returns: log path tied to the user\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_log_path\n\n\ndef user_documents_path() -> Path:\n    \"\"\"\n    :returns: documents path tied to the user\n    \"\"\"\n    return PlatformDirs().user_documents_path\n\n\ndef user_runtime_path(\n    appname: str | None = None,\n    appauthor: str | None | Literal[False] = None,\n    version: str | None = None,\n    opinion: bool = True,\n) -> Path:\n    \"\"\"\n    :param appname: See `appname <platformdirs.api.PlatformDirsABC.appname>`.\n    :param appauthor: See `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`.\n    :param version: See `version <platformdirs.api.PlatformDirsABC.version>`.\n    :param opinion: See `opinion <platformdirs.api.PlatformDirsABC.opinion>`.\n    :returns: runtime path tied to the user\n    \"\"\"\n    return PlatformDirs(appname=appname, appauthor=appauthor, version=version, opinion=opinion).user_runtime_path\n\n\n__all__ = [\n    \"__version__\",\n    \"__version_info__\",\n    \"PlatformDirs\",\n    \"AppDirs\",\n    \"PlatformDirsABC\",\n    \"user_data_dir\",\n    \"user_config_dir\",\n    \"user_cache_dir\",\n    \"user_state_dir\",\n    \"user_log_dir\",\n    \"user_documents_dir\",\n    \"user_runtime_dir\",\n    \"site_data_dir\",\n    \"site_config_dir\",\n    \"user_data_path\",\n    \"user_config_path\",\n    \"user_cache_path\",\n    \"user_state_path\",\n    \"user_log_path\",\n    \"user_documents_path\",\n    \"user_runtime_path\",\n    \"site_data_path\",\n    \"site_config_path\",\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/platformdirs/__main__.py",
    "content": "from __future__ import annotations\n\nfrom pip._vendor.platformdirs import PlatformDirs, __version__\n\nPROPS = (\n    \"user_data_dir\",\n    \"user_config_dir\",\n    \"user_cache_dir\",\n    \"user_state_dir\",\n    \"user_log_dir\",\n    \"user_documents_dir\",\n    \"user_runtime_dir\",\n    \"site_data_dir\",\n    \"site_config_dir\",\n)\n\n\ndef main() -> None:\n    app_name = \"MyApp\"\n    app_author = \"MyCompany\"\n\n    print(f\"-- platformdirs {__version__} --\")\n\n    print(\"-- app dirs (with optional 'version')\")\n    dirs = PlatformDirs(app_name, app_author, version=\"1.0\")\n    for prop in PROPS:\n        print(f\"{prop}: {getattr(dirs, prop)}\")\n\n    print(\"\\n-- app dirs (without optional 'version')\")\n    dirs = PlatformDirs(app_name, app_author)\n    for prop in PROPS:\n        print(f\"{prop}: {getattr(dirs, prop)}\")\n\n    print(\"\\n-- app dirs (without optional 'appauthor')\")\n    dirs = PlatformDirs(app_name)\n    for prop in PROPS:\n        print(f\"{prop}: {getattr(dirs, prop)}\")\n\n    print(\"\\n-- app dirs (with disabled 'appauthor')\")\n    dirs = PlatformDirs(app_name, appauthor=False)\n    for prop in PROPS:\n        print(f\"{prop}: {getattr(dirs, prop)}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/platformdirs/android.py",
    "content": "from __future__ import annotations\n\nimport os\nimport re\nimport sys\nfrom functools import lru_cache\nfrom typing import cast\n\nfrom .api import PlatformDirsABC\n\n\nclass Android(PlatformDirsABC):\n    \"\"\"\n    Follows the guidance `from here <https://android.stackexchange.com/a/216132>`_. Makes use of the\n    `appname <platformdirs.api.PlatformDirsABC.appname>` and\n    `version <platformdirs.api.PlatformDirsABC.version>`.\n    \"\"\"\n\n    @property\n    def user_data_dir(self) -> str:\n        \"\"\":return: data directory tied to the user, e.g. ``/data/user/<userid>/<packagename>/files/<AppName>``\"\"\"\n        return self._append_app_name_and_version(cast(str, _android_folder()), \"files\")\n\n    @property\n    def site_data_dir(self) -> str:\n        \"\"\":return: data directory shared by users, same as `user_data_dir`\"\"\"\n        return self.user_data_dir\n\n    @property\n    def user_config_dir(self) -> str:\n        \"\"\"\n        :return: config directory tied to the user, e.g. ``/data/user/<userid>/<packagename>/shared_prefs/<AppName>``\n        \"\"\"\n        return self._append_app_name_and_version(cast(str, _android_folder()), \"shared_prefs\")\n\n    @property\n    def site_config_dir(self) -> str:\n        \"\"\":return: config directory shared by the users, same as `user_config_dir`\"\"\"\n        return self.user_config_dir\n\n    @property\n    def user_cache_dir(self) -> str:\n        \"\"\":return: cache directory tied to the user, e.g. e.g. ``/data/user/<userid>/<packagename>/cache/<AppName>``\"\"\"\n        return self._append_app_name_and_version(cast(str, _android_folder()), \"cache\")\n\n    @property\n    def user_state_dir(self) -> str:\n        \"\"\":return: state directory tied to the user, same as `user_data_dir`\"\"\"\n        return self.user_data_dir\n\n    @property\n    def user_log_dir(self) -> str:\n        \"\"\"\n        :return: log directory tied to the user, same as `user_cache_dir` if not opinionated else ``log`` in it,\n          e.g. ``/data/user/<userid>/<packagename>/cache/<AppName>/log``\n        \"\"\"\n        path = self.user_cache_dir\n        if self.opinion:\n            path = os.path.join(path, \"log\")\n        return path\n\n    @property\n    def user_documents_dir(self) -> str:\n        \"\"\"\n        :return: documents directory tied to the user e.g. ``/storage/emulated/0/Documents``\n        \"\"\"\n        return _android_documents_folder()\n\n    @property\n    def user_runtime_dir(self) -> str:\n        \"\"\"\n        :return: runtime directory tied to the user, same as `user_cache_dir` if not opinionated else ``tmp`` in it,\n          e.g. ``/data/user/<userid>/<packagename>/cache/<AppName>/tmp``\n        \"\"\"\n        path = self.user_cache_dir\n        if self.opinion:\n            path = os.path.join(path, \"tmp\")\n        return path\n\n\n@lru_cache(maxsize=1)\ndef _android_folder() -> str | None:\n    \"\"\":return: base folder for the Android OS or None if cannot be found\"\"\"\n    try:\n        # First try to get path to android app via pyjnius\n        from jnius import autoclass\n\n        Context = autoclass(\"android.content.Context\")  # noqa: N806\n        result: str | None = Context.getFilesDir().getParentFile().getAbsolutePath()\n    except Exception:\n        # if fails find an android folder looking path on the sys.path\n        pattern = re.compile(r\"/data/(data|user/\\d+)/(.+)/files\")\n        for path in sys.path:\n            if pattern.match(path):\n                result = path.split(\"/files\")[0]\n                break\n        else:\n            result = None\n    return result\n\n\n@lru_cache(maxsize=1)\ndef _android_documents_folder() -> str:\n    \"\"\":return: documents folder for the Android OS\"\"\"\n    # Get directories with pyjnius\n    try:\n        from jnius import autoclass\n\n        Context = autoclass(\"android.content.Context\")  # noqa: N806\n        Environment = autoclass(\"android.os.Environment\")  # noqa: N806\n        documents_dir: str = Context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath()\n    except Exception:\n        documents_dir = \"/storage/emulated/0/Documents\"\n\n    return documents_dir\n\n\n__all__ = [\n    \"Android\",\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/platformdirs/api.py",
    "content": "from __future__ import annotations\n\nimport os\nimport sys\nfrom abc import ABC, abstractmethod\nfrom pathlib import Path\n\nif sys.version_info >= (3, 8):  # pragma: no branch\n    from typing import Literal  # pragma: no cover\n\n\nclass PlatformDirsABC(ABC):\n    \"\"\"\n    Abstract base class for platform directories.\n    \"\"\"\n\n    def __init__(\n        self,\n        appname: str | None = None,\n        appauthor: str | None | Literal[False] = None,\n        version: str | None = None,\n        roaming: bool = False,\n        multipath: bool = False,\n        opinion: bool = True,\n    ):\n        \"\"\"\n        Create a new platform directory.\n\n        :param appname: See `appname`.\n        :param appauthor: See `appauthor`.\n        :param version: See `version`.\n        :param roaming: See `roaming`.\n        :param multipath: See `multipath`.\n        :param opinion: See `opinion`.\n        \"\"\"\n        self.appname = appname  #: The name of application.\n        self.appauthor = appauthor\n        \"\"\"\n        The name of the app author or distributing body for this application. Typically, it is the owning company name.\n        Defaults to `appname`. You may pass ``False`` to disable it.\n        \"\"\"\n        self.version = version\n        \"\"\"\n        An optional version path element to append to the path. You might want to use this if you want multiple versions\n        of your app to be able to run independently. If used, this would typically be ``<major>.<minor>``.\n        \"\"\"\n        self.roaming = roaming\n        \"\"\"\n        Whether to use the roaming appdata directory on Windows. That means that for users on a Windows network setup\n        for roaming profiles, this user data will be synced on login (see\n        `here <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>`_).\n        \"\"\"\n        self.multipath = multipath\n        \"\"\"\n        An optional parameter only applicable to Unix/Linux which indicates that the entire list of data dirs should be\n        returned. By default, the first item would only be returned.\n        \"\"\"\n        self.opinion = opinion  #: A flag to indicating to use opinionated values.\n\n    def _append_app_name_and_version(self, *base: str) -> str:\n        params = list(base[1:])\n        if self.appname:\n            params.append(self.appname)\n            if self.version:\n                params.append(self.version)\n        return os.path.join(base[0], *params)\n\n    @property\n    @abstractmethod\n    def user_data_dir(self) -> str:\n        \"\"\":return: data directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def site_data_dir(self) -> str:\n        \"\"\":return: data directory shared by users\"\"\"\n\n    @property\n    @abstractmethod\n    def user_config_dir(self) -> str:\n        \"\"\":return: config directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def site_config_dir(self) -> str:\n        \"\"\":return: config directory shared by the users\"\"\"\n\n    @property\n    @abstractmethod\n    def user_cache_dir(self) -> str:\n        \"\"\":return: cache directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def user_state_dir(self) -> str:\n        \"\"\":return: state directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def user_log_dir(self) -> str:\n        \"\"\":return: log directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def user_documents_dir(self) -> str:\n        \"\"\":return: documents directory tied to the user\"\"\"\n\n    @property\n    @abstractmethod\n    def user_runtime_dir(self) -> str:\n        \"\"\":return: runtime directory tied to the user\"\"\"\n\n    @property\n    def user_data_path(self) -> Path:\n        \"\"\":return: data path tied to the user\"\"\"\n        return Path(self.user_data_dir)\n\n    @property\n    def site_data_path(self) -> Path:\n        \"\"\":return: data path shared by users\"\"\"\n        return Path(self.site_data_dir)\n\n    @property\n    def user_config_path(self) -> Path:\n        \"\"\":return: config path tied to the user\"\"\"\n        return Path(self.user_config_dir)\n\n    @property\n    def site_config_path(self) -> Path:\n        \"\"\":return: config path shared by the users\"\"\"\n        return Path(self.site_config_dir)\n\n    @property\n    def user_cache_path(self) -> Path:\n        \"\"\":return: cache path tied to the user\"\"\"\n        return Path(self.user_cache_dir)\n\n    @property\n    def user_state_path(self) -> Path:\n        \"\"\":return: state path tied to the user\"\"\"\n        return Path(self.user_state_dir)\n\n    @property\n    def user_log_path(self) -> Path:\n        \"\"\":return: log path tied to the user\"\"\"\n        return Path(self.user_log_dir)\n\n    @property\n    def user_documents_path(self) -> Path:\n        \"\"\":return: documents path tied to the user\"\"\"\n        return Path(self.user_documents_dir)\n\n    @property\n    def user_runtime_path(self) -> Path:\n        \"\"\":return: runtime path tied to the user\"\"\"\n        return Path(self.user_runtime_dir)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/platformdirs/macos.py",
    "content": "from __future__ import annotations\n\nimport os\n\nfrom .api import PlatformDirsABC\n\n\nclass MacOS(PlatformDirsABC):\n    \"\"\"\n    Platform directories for the macOS operating system. Follows the guidance from `Apple documentation\n    <https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/MacOSXDirectories/MacOSXDirectories.html>`_.\n    Makes use of the `appname <platformdirs.api.PlatformDirsABC.appname>` and\n    `version <platformdirs.api.PlatformDirsABC.version>`.\n    \"\"\"\n\n    @property\n    def user_data_dir(self) -> str:\n        \"\"\":return: data directory tied to the user, e.g. ``~/Library/Application Support/$appname/$version``\"\"\"\n        return self._append_app_name_and_version(os.path.expanduser(\"~/Library/Application Support/\"))\n\n    @property\n    def site_data_dir(self) -> str:\n        \"\"\":return: data directory shared by users, e.g. ``/Library/Application Support/$appname/$version``\"\"\"\n        return self._append_app_name_and_version(\"/Library/Application Support\")\n\n    @property\n    def user_config_dir(self) -> str:\n        \"\"\":return: config directory tied to the user, e.g. ``~/Library/Preferences/$appname/$version``\"\"\"\n        return self._append_app_name_and_version(os.path.expanduser(\"~/Library/Preferences/\"))\n\n    @property\n    def site_config_dir(self) -> str:\n        \"\"\":return: config directory shared by the users, e.g. ``/Library/Preferences/$appname``\"\"\"\n        return self._append_app_name_and_version(\"/Library/Preferences\")\n\n    @property\n    def user_cache_dir(self) -> str:\n        \"\"\":return: cache directory tied to the user, e.g. ``~/Library/Caches/$appname/$version``\"\"\"\n        return self._append_app_name_and_version(os.path.expanduser(\"~/Library/Caches\"))\n\n    @property\n    def user_state_dir(self) -> str:\n        \"\"\":return: state directory tied to the user, same as `user_data_dir`\"\"\"\n        return self.user_data_dir\n\n    @property\n    def user_log_dir(self) -> str:\n        \"\"\":return: log directory tied to the user, e.g. ``~/Library/Logs/$appname/$version``\"\"\"\n        return self._append_app_name_and_version(os.path.expanduser(\"~/Library/Logs\"))\n\n    @property\n    def user_documents_dir(self) -> str:\n        \"\"\":return: documents directory tied to the user, e.g. ``~/Documents``\"\"\"\n        return os.path.expanduser(\"~/Documents\")\n\n    @property\n    def user_runtime_dir(self) -> str:\n        \"\"\":return: runtime directory tied to the user, e.g. ``~/Library/Caches/TemporaryItems/$appname/$version``\"\"\"\n        return self._append_app_name_and_version(os.path.expanduser(\"~/Library/Caches/TemporaryItems\"))\n\n\n__all__ = [\n    \"MacOS\",\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/platformdirs/unix.py",
    "content": "from __future__ import annotations\n\nimport os\nimport sys\nfrom configparser import ConfigParser\nfrom pathlib import Path\n\nfrom .api import PlatformDirsABC\n\nif sys.platform.startswith(\"linux\"):  # pragma: no branch # no op check, only to please the type checker\n    from os import getuid\nelse:\n\n    def getuid() -> int:\n        raise RuntimeError(\"should only be used on Linux\")\n\n\nclass Unix(PlatformDirsABC):\n    \"\"\"\n    On Unix/Linux, we follow the\n    `XDG Basedir Spec <https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html>`_. The spec allows\n    overriding directories with environment variables. The examples show are the default values, alongside the name of\n    the environment variable that overrides them. Makes use of the\n    `appname <platformdirs.api.PlatformDirsABC.appname>`,\n    `version <platformdirs.api.PlatformDirsABC.version>`,\n    `multipath <platformdirs.api.PlatformDirsABC.multipath>`,\n    `opinion <platformdirs.api.PlatformDirsABC.opinion>`.\n    \"\"\"\n\n    @property\n    def user_data_dir(self) -> str:\n        \"\"\"\n        :return: data directory tied to the user, e.g. ``~/.local/share/$appname/$version`` or\n         ``$XDG_DATA_HOME/$appname/$version``\n        \"\"\"\n        path = os.environ.get(\"XDG_DATA_HOME\", \"\")\n        if not path.strip():\n            path = os.path.expanduser(\"~/.local/share\")\n        return self._append_app_name_and_version(path)\n\n    @property\n    def site_data_dir(self) -> str:\n        \"\"\"\n        :return: data directories shared by users (if `multipath <platformdirs.api.PlatformDirsABC.multipath>` is\n         enabled and ``XDG_DATA_DIR`` is set and a multi path the response is also a multi path separated by the OS\n         path separator), e.g. ``/usr/local/share/$appname/$version`` or ``/usr/share/$appname/$version``\n        \"\"\"\n        # XDG default for $XDG_DATA_DIRS; only first, if multipath is False\n        path = os.environ.get(\"XDG_DATA_DIRS\", \"\")\n        if not path.strip():\n            path = f\"/usr/local/share{os.pathsep}/usr/share\"\n        return self._with_multi_path(path)\n\n    def _with_multi_path(self, path: str) -> str:\n        path_list = path.split(os.pathsep)\n        if not self.multipath:\n            path_list = path_list[0:1]\n        path_list = [self._append_app_name_and_version(os.path.expanduser(p)) for p in path_list]\n        return os.pathsep.join(path_list)\n\n    @property\n    def user_config_dir(self) -> str:\n        \"\"\"\n        :return: config directory tied to the user, e.g. ``~/.config/$appname/$version`` or\n         ``$XDG_CONFIG_HOME/$appname/$version``\n        \"\"\"\n        path = os.environ.get(\"XDG_CONFIG_HOME\", \"\")\n        if not path.strip():\n            path = os.path.expanduser(\"~/.config\")\n        return self._append_app_name_and_version(path)\n\n    @property\n    def site_config_dir(self) -> str:\n        \"\"\"\n        :return: config directories shared by users (if `multipath <platformdirs.api.PlatformDirsABC.multipath>`\n         is enabled and ``XDG_DATA_DIR`` is set and a multi path the response is also a multi path separated by the OS\n         path separator), e.g. ``/etc/xdg/$appname/$version``\n        \"\"\"\n        # XDG default for $XDG_CONFIG_DIRS only first, if multipath is False\n        path = os.environ.get(\"XDG_CONFIG_DIRS\", \"\")\n        if not path.strip():\n            path = \"/etc/xdg\"\n        return self._with_multi_path(path)\n\n    @property\n    def user_cache_dir(self) -> str:\n        \"\"\"\n        :return: cache directory tied to the user, e.g. ``~/.cache/$appname/$version`` or\n         ``~/$XDG_CACHE_HOME/$appname/$version``\n        \"\"\"\n        path = os.environ.get(\"XDG_CACHE_HOME\", \"\")\n        if not path.strip():\n            path = os.path.expanduser(\"~/.cache\")\n        return self._append_app_name_and_version(path)\n\n    @property\n    def user_state_dir(self) -> str:\n        \"\"\"\n        :return: state directory tied to the user, e.g. ``~/.local/state/$appname/$version`` or\n         ``$XDG_STATE_HOME/$appname/$version``\n        \"\"\"\n        path = os.environ.get(\"XDG_STATE_HOME\", \"\")\n        if not path.strip():\n            path = os.path.expanduser(\"~/.local/state\")\n        return self._append_app_name_and_version(path)\n\n    @property\n    def user_log_dir(self) -> str:\n        \"\"\"\n        :return: log directory tied to the user, same as `user_data_dir` if not opinionated else ``log`` in it\n        \"\"\"\n        path = self.user_cache_dir\n        if self.opinion:\n            path = os.path.join(path, \"log\")\n        return path\n\n    @property\n    def user_documents_dir(self) -> str:\n        \"\"\"\n        :return: documents directory tied to the user, e.g. ``~/Documents``\n        \"\"\"\n        documents_dir = _get_user_dirs_folder(\"XDG_DOCUMENTS_DIR\")\n        if documents_dir is None:\n            documents_dir = os.environ.get(\"XDG_DOCUMENTS_DIR\", \"\").strip()\n            if not documents_dir:\n                documents_dir = os.path.expanduser(\"~/Documents\")\n\n        return documents_dir\n\n    @property\n    def user_runtime_dir(self) -> str:\n        \"\"\"\n        :return: runtime directory tied to the user, e.g. ``/run/user/$(id -u)/$appname/$version`` or\n         ``$XDG_RUNTIME_DIR/$appname/$version``\n        \"\"\"\n        path = os.environ.get(\"XDG_RUNTIME_DIR\", \"\")\n        if not path.strip():\n            path = f\"/run/user/{getuid()}\"\n        return self._append_app_name_and_version(path)\n\n    @property\n    def site_data_path(self) -> Path:\n        \"\"\":return: data path shared by users. Only return first item, even if ``multipath`` is set to ``True``\"\"\"\n        return self._first_item_as_path_if_multipath(self.site_data_dir)\n\n    @property\n    def site_config_path(self) -> Path:\n        \"\"\":return: config path shared by the users. Only return first item, even if ``multipath`` is set to ``True``\"\"\"\n        return self._first_item_as_path_if_multipath(self.site_config_dir)\n\n    def _first_item_as_path_if_multipath(self, directory: str) -> Path:\n        if self.multipath:\n            # If multipath is True, the first path is returned.\n            directory = directory.split(os.pathsep)[0]\n        return Path(directory)\n\n\ndef _get_user_dirs_folder(key: str) -> str | None:\n    \"\"\"Return directory from user-dirs.dirs config file. See https://freedesktop.org/wiki/Software/xdg-user-dirs/\"\"\"\n    user_dirs_config_path = os.path.join(Unix().user_config_dir, \"user-dirs.dirs\")\n    if os.path.exists(user_dirs_config_path):\n        parser = ConfigParser()\n\n        with open(user_dirs_config_path) as stream:\n            # Add fake section header, so ConfigParser doesn't complain\n            parser.read_string(f\"[top]\\n{stream.read()}\")\n\n        if key not in parser[\"top\"]:\n            return None\n\n        path = parser[\"top\"][key].strip('\"')\n        # Handle relative home paths\n        path = path.replace(\"$HOME\", os.path.expanduser(\"~\"))\n        return path\n\n    return None\n\n\n__all__ = [\n    \"Unix\",\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/platformdirs/version.py",
    "content": "\"\"\"Version information\"\"\"\n\n__version__ = \"2.5.2\"\n__version_info__ = (2, 5, 2)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/platformdirs/windows.py",
    "content": "from __future__ import annotations\n\nimport ctypes\nimport os\nfrom functools import lru_cache\nfrom typing import Callable\n\nfrom .api import PlatformDirsABC\n\n\nclass Windows(PlatformDirsABC):\n    \"\"\"`MSDN on where to store app data files\n    <http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120>`_.\n    Makes use of the\n    `appname <platformdirs.api.PlatformDirsABC.appname>`,\n    `appauthor <platformdirs.api.PlatformDirsABC.appauthor>`,\n    `version <platformdirs.api.PlatformDirsABC.version>`,\n    `roaming <platformdirs.api.PlatformDirsABC.roaming>`,\n    `opinion <platformdirs.api.PlatformDirsABC.opinion>`.\"\"\"\n\n    @property\n    def user_data_dir(self) -> str:\n        \"\"\"\n        :return: data directory tied to the user, e.g.\n         ``%USERPROFILE%\\\\AppData\\\\Local\\\\$appauthor\\\\$appname`` (not roaming) or\n         ``%USERPROFILE%\\\\AppData\\\\Roaming\\\\$appauthor\\\\$appname`` (roaming)\n        \"\"\"\n        const = \"CSIDL_APPDATA\" if self.roaming else \"CSIDL_LOCAL_APPDATA\"\n        path = os.path.normpath(get_win_folder(const))\n        return self._append_parts(path)\n\n    def _append_parts(self, path: str, *, opinion_value: str | None = None) -> str:\n        params = []\n        if self.appname:\n            if self.appauthor is not False:\n                author = self.appauthor or self.appname\n                params.append(author)\n            params.append(self.appname)\n            if opinion_value is not None and self.opinion:\n                params.append(opinion_value)\n            if self.version:\n                params.append(self.version)\n        return os.path.join(path, *params)\n\n    @property\n    def site_data_dir(self) -> str:\n        \"\"\":return: data directory shared by users, e.g. ``C:\\\\ProgramData\\\\$appauthor\\\\$appname``\"\"\"\n        path = os.path.normpath(get_win_folder(\"CSIDL_COMMON_APPDATA\"))\n        return self._append_parts(path)\n\n    @property\n    def user_config_dir(self) -> str:\n        \"\"\":return: config directory tied to the user, same as `user_data_dir`\"\"\"\n        return self.user_data_dir\n\n    @property\n    def site_config_dir(self) -> str:\n        \"\"\":return: config directory shared by the users, same as `site_data_dir`\"\"\"\n        return self.site_data_dir\n\n    @property\n    def user_cache_dir(self) -> str:\n        \"\"\"\n        :return: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g.\n         ``%USERPROFILE%\\\\AppData\\\\Local\\\\$appauthor\\\\$appname\\\\Cache\\\\$version``\n        \"\"\"\n        path = os.path.normpath(get_win_folder(\"CSIDL_LOCAL_APPDATA\"))\n        return self._append_parts(path, opinion_value=\"Cache\")\n\n    @property\n    def user_state_dir(self) -> str:\n        \"\"\":return: state directory tied to the user, same as `user_data_dir`\"\"\"\n        return self.user_data_dir\n\n    @property\n    def user_log_dir(self) -> str:\n        \"\"\"\n        :return: log directory tied to the user, same as `user_data_dir` if not opinionated else ``Logs`` in it\n        \"\"\"\n        path = self.user_data_dir\n        if self.opinion:\n            path = os.path.join(path, \"Logs\")\n        return path\n\n    @property\n    def user_documents_dir(self) -> str:\n        \"\"\"\n        :return: documents directory tied to the user e.g. ``%USERPROFILE%\\\\Documents``\n        \"\"\"\n        return os.path.normpath(get_win_folder(\"CSIDL_PERSONAL\"))\n\n    @property\n    def user_runtime_dir(self) -> str:\n        \"\"\"\n        :return: runtime directory tied to the user, e.g.\n         ``%USERPROFILE%\\\\AppData\\\\Local\\\\Temp\\\\$appauthor\\\\$appname``\n        \"\"\"\n        path = os.path.normpath(os.path.join(get_win_folder(\"CSIDL_LOCAL_APPDATA\"), \"Temp\"))\n        return self._append_parts(path)\n\n\ndef get_win_folder_from_env_vars(csidl_name: str) -> str:\n    \"\"\"Get folder from environment variables.\"\"\"\n    if csidl_name == \"CSIDL_PERSONAL\":  # does not have an environment name\n        return os.path.join(os.path.normpath(os.environ[\"USERPROFILE\"]), \"Documents\")\n\n    env_var_name = {\n        \"CSIDL_APPDATA\": \"APPDATA\",\n        \"CSIDL_COMMON_APPDATA\": \"ALLUSERSPROFILE\",\n        \"CSIDL_LOCAL_APPDATA\": \"LOCALAPPDATA\",\n    }.get(csidl_name)\n    if env_var_name is None:\n        raise ValueError(f\"Unknown CSIDL name: {csidl_name}\")\n    result = os.environ.get(env_var_name)\n    if result is None:\n        raise ValueError(f\"Unset environment variable: {env_var_name}\")\n    return result\n\n\ndef get_win_folder_from_registry(csidl_name: str) -> str:\n    \"\"\"Get folder from the registry.\n\n    This is a fallback technique at best. I'm not sure if using the\n    registry for this guarantees us the correct answer for all CSIDL_*\n    names.\n    \"\"\"\n    shell_folder_name = {\n        \"CSIDL_APPDATA\": \"AppData\",\n        \"CSIDL_COMMON_APPDATA\": \"Common AppData\",\n        \"CSIDL_LOCAL_APPDATA\": \"Local AppData\",\n        \"CSIDL_PERSONAL\": \"Personal\",\n    }.get(csidl_name)\n    if shell_folder_name is None:\n        raise ValueError(f\"Unknown CSIDL name: {csidl_name}\")\n\n    import winreg\n\n    key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\")\n    directory, _ = winreg.QueryValueEx(key, shell_folder_name)\n    return str(directory)\n\n\ndef get_win_folder_via_ctypes(csidl_name: str) -> str:\n    \"\"\"Get folder with ctypes.\"\"\"\n    csidl_const = {\n        \"CSIDL_APPDATA\": 26,\n        \"CSIDL_COMMON_APPDATA\": 35,\n        \"CSIDL_LOCAL_APPDATA\": 28,\n        \"CSIDL_PERSONAL\": 5,\n    }.get(csidl_name)\n    if csidl_const is None:\n        raise ValueError(f\"Unknown CSIDL name: {csidl_name}\")\n\n    buf = ctypes.create_unicode_buffer(1024)\n    windll = getattr(ctypes, \"windll\")  # noqa: B009 # using getattr to avoid false positive with mypy type checker\n    windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)\n\n    # Downgrade to short path name if it has highbit chars.\n    if any(ord(c) > 255 for c in buf):\n        buf2 = ctypes.create_unicode_buffer(1024)\n        if windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):\n            buf = buf2\n\n    return buf.value\n\n\ndef _pick_get_win_folder() -> Callable[[str], str]:\n    if hasattr(ctypes, \"windll\"):\n        return get_win_folder_via_ctypes\n    try:\n        import winreg  # noqa: F401\n    except ImportError:\n        return get_win_folder_from_env_vars\n    else:\n        return get_win_folder_from_registry\n\n\nget_win_folder = lru_cache(maxsize=None)(_pick_get_win_folder())\n\n__all__ = [\n    \"Windows\",\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/__init__.py",
    "content": "\"\"\"\n    Pygments\n    ~~~~~~~~\n\n    Pygments is a syntax highlighting package written in Python.\n\n    It is a generic syntax highlighter for general use in all kinds of software\n    such as forum systems, wikis or other applications that need to prettify\n    source code. Highlights are:\n\n    * a wide range of common languages and markup formats is supported\n    * special attention is paid to details, increasing quality by a fair amount\n    * support for new languages and formats are added easily\n    * a number of output formats, presently HTML, LaTeX, RTF, SVG, all image\n      formats that PIL supports, and ANSI sequences\n    * it is usable as a command-line tool and as a library\n    * ... and it highlights even Brainfuck!\n\n    The `Pygments master branch`_ is installable with ``easy_install Pygments==dev``.\n\n    .. _Pygments master branch:\n       https://github.com/pygments/pygments/archive/master.zip#egg=Pygments-dev\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\nfrom io import StringIO, BytesIO\n\n__version__ = '2.13.0'\n__docformat__ = 'restructuredtext'\n\n__all__ = ['lex', 'format', 'highlight']\n\n\ndef lex(code, lexer):\n    \"\"\"\n    Lex ``code`` with ``lexer`` and return an iterable of tokens.\n    \"\"\"\n    try:\n        return lexer.get_tokens(code)\n    except TypeError:\n        # Heuristic to catch a common mistake.\n        from pip._vendor.pygments.lexer import RegexLexer\n        if isinstance(lexer, type) and issubclass(lexer, RegexLexer):\n            raise TypeError('lex() argument must be a lexer instance, '\n                            'not a class')\n        raise\n\n\ndef format(tokens, formatter, outfile=None):  # pylint: disable=redefined-builtin\n    \"\"\"\n    Format a tokenlist ``tokens`` with the formatter ``formatter``.\n\n    If ``outfile`` is given and a valid file object (an object\n    with a ``write`` method), the result will be written to it, otherwise\n    it is returned as a string.\n    \"\"\"\n    try:\n        if not outfile:\n            realoutfile = getattr(formatter, 'encoding', None) and BytesIO() or StringIO()\n            formatter.format(tokens, realoutfile)\n            return realoutfile.getvalue()\n        else:\n            formatter.format(tokens, outfile)\n    except TypeError:\n        # Heuristic to catch a common mistake.\n        from pip._vendor.pygments.formatter import Formatter\n        if isinstance(formatter, type) and issubclass(formatter, Formatter):\n            raise TypeError('format() argument must be a formatter instance, '\n                            'not a class')\n        raise\n\n\ndef highlight(code, lexer, formatter, outfile=None):\n    \"\"\"\n    Lex ``code`` with ``lexer`` and format it with the formatter ``formatter``.\n\n    If ``outfile`` is given and a valid file object (an object\n    with a ``write`` method), the result will be written to it, otherwise\n    it is returned as a string.\n    \"\"\"\n    return format(lex(code, lexer), formatter, outfile)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/__main__.py",
    "content": "\"\"\"\n    pygments.__main__\n    ~~~~~~~~~~~~~~~~~\n\n    Main entry point for ``python -m pygments``.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport sys\nfrom pip._vendor.pygments.cmdline import main\n\ntry:\n    sys.exit(main(sys.argv))\nexcept KeyboardInterrupt:\n    sys.exit(1)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/cmdline.py",
    "content": "\"\"\"\n    pygments.cmdline\n    ~~~~~~~~~~~~~~~~\n\n    Command line interface.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport os\nimport sys\nimport shutil\nimport argparse\nfrom textwrap import dedent\n\nfrom pip._vendor.pygments import __version__, highlight\nfrom pip._vendor.pygments.util import ClassNotFound, OptionError, docstring_headline, \\\n    guess_decode, guess_decode_from_terminal, terminal_encoding, \\\n    UnclosingTextIOWrapper\nfrom pip._vendor.pygments.lexers import get_all_lexers, get_lexer_by_name, guess_lexer, \\\n    load_lexer_from_file, get_lexer_for_filename, find_lexer_class_for_filename\nfrom pip._vendor.pygments.lexers.special import TextLexer\nfrom pip._vendor.pygments.formatters.latex import LatexEmbeddedLexer, LatexFormatter\nfrom pip._vendor.pygments.formatters import get_all_formatters, get_formatter_by_name, \\\n    load_formatter_from_file, get_formatter_for_filename, find_formatter_class\nfrom pip._vendor.pygments.formatters.terminal import TerminalFormatter\nfrom pip._vendor.pygments.formatters.terminal256 import Terminal256Formatter, TerminalTrueColorFormatter\nfrom pip._vendor.pygments.filters import get_all_filters, find_filter_class\nfrom pip._vendor.pygments.styles import get_all_styles, get_style_by_name\n\n\ndef _parse_options(o_strs):\n    opts = {}\n    if not o_strs:\n        return opts\n    for o_str in o_strs:\n        if not o_str.strip():\n            continue\n        o_args = o_str.split(',')\n        for o_arg in o_args:\n            o_arg = o_arg.strip()\n            try:\n                o_key, o_val = o_arg.split('=', 1)\n                o_key = o_key.strip()\n                o_val = o_val.strip()\n            except ValueError:\n                opts[o_arg] = True\n            else:\n                opts[o_key] = o_val\n    return opts\n\n\ndef _parse_filters(f_strs):\n    filters = []\n    if not f_strs:\n        return filters\n    for f_str in f_strs:\n        if ':' in f_str:\n            fname, fopts = f_str.split(':', 1)\n            filters.append((fname, _parse_options([fopts])))\n        else:\n            filters.append((f_str, {}))\n    return filters\n\n\ndef _print_help(what, name):\n    try:\n        if what == 'lexer':\n            cls = get_lexer_by_name(name)\n            print(\"Help on the %s lexer:\" % cls.name)\n            print(dedent(cls.__doc__))\n        elif what == 'formatter':\n            cls = find_formatter_class(name)\n            print(\"Help on the %s formatter:\" % cls.name)\n            print(dedent(cls.__doc__))\n        elif what == 'filter':\n            cls = find_filter_class(name)\n            print(\"Help on the %s filter:\" % name)\n            print(dedent(cls.__doc__))\n        return 0\n    except (AttributeError, ValueError):\n        print(\"%s not found!\" % what, file=sys.stderr)\n        return 1\n\n\ndef _print_list(what):\n    if what == 'lexer':\n        print()\n        print(\"Lexers:\")\n        print(\"~~~~~~~\")\n\n        info = []\n        for fullname, names, exts, _ in get_all_lexers():\n            tup = (', '.join(names)+':', fullname,\n                   exts and '(filenames ' + ', '.join(exts) + ')' or '')\n            info.append(tup)\n        info.sort()\n        for i in info:\n            print(('* %s\\n    %s %s') % i)\n\n    elif what == 'formatter':\n        print()\n        print(\"Formatters:\")\n        print(\"~~~~~~~~~~~\")\n\n        info = []\n        for cls in get_all_formatters():\n            doc = docstring_headline(cls)\n            tup = (', '.join(cls.aliases) + ':', doc, cls.filenames and\n                   '(filenames ' + ', '.join(cls.filenames) + ')' or '')\n            info.append(tup)\n        info.sort()\n        for i in info:\n            print(('* %s\\n    %s %s') % i)\n\n    elif what == 'filter':\n        print()\n        print(\"Filters:\")\n        print(\"~~~~~~~~\")\n\n        for name in get_all_filters():\n            cls = find_filter_class(name)\n            print(\"* \" + name + ':')\n            print(\"    %s\" % docstring_headline(cls))\n\n    elif what == 'style':\n        print()\n        print(\"Styles:\")\n        print(\"~~~~~~~\")\n\n        for name in get_all_styles():\n            cls = get_style_by_name(name)\n            print(\"* \" + name + ':')\n            print(\"    %s\" % docstring_headline(cls))\n\n\ndef _print_list_as_json(requested_items):\n    import json\n    result = {}\n    if 'lexer' in requested_items:\n        info = {}\n        for fullname, names, filenames, mimetypes in get_all_lexers():\n            info[fullname] = {\n                'aliases': names,\n                'filenames': filenames,\n                'mimetypes': mimetypes\n            }\n        result['lexers'] = info\n\n    if 'formatter' in requested_items:\n        info = {}\n        for cls in get_all_formatters():\n            doc = docstring_headline(cls)\n            info[cls.name] = {\n                'aliases': cls.aliases,\n                'filenames': cls.filenames,\n                'doc': doc\n            }\n        result['formatters'] = info\n\n    if 'filter' in requested_items:\n        info = {}\n        for name in get_all_filters():\n            cls = find_filter_class(name)\n            info[name] = {\n                'doc': docstring_headline(cls)\n            }\n        result['filters'] = info\n\n    if 'style' in requested_items:\n        info = {}\n        for name in get_all_styles():\n            cls = get_style_by_name(name)\n            info[name] = {\n                'doc': docstring_headline(cls)\n            }\n        result['styles'] = info\n\n    json.dump(result, sys.stdout)\n\ndef main_inner(parser, argns):\n    if argns.help:\n        parser.print_help()\n        return 0\n\n    if argns.V:\n        print('Pygments version %s, (c) 2006-2022 by Georg Brandl, Matthäus '\n              'Chajdas and contributors.' % __version__)\n        return 0\n\n    def is_only_option(opt):\n        return not any(v for (k, v) in vars(argns).items() if k != opt)\n\n    # handle ``pygmentize -L``\n    if argns.L is not None:\n        arg_set = set()\n        for k, v in vars(argns).items():\n            if v:\n                arg_set.add(k)\n\n        arg_set.discard('L')\n        arg_set.discard('json')\n\n        if arg_set:\n            parser.print_help(sys.stderr)\n            return 2\n\n        # print version\n        if not argns.json:\n            main(['', '-V'])\n        allowed_types = {'lexer', 'formatter', 'filter', 'style'}\n        largs = [arg.rstrip('s') for arg in argns.L]\n        if any(arg not in allowed_types for arg in largs):\n            parser.print_help(sys.stderr)\n            return 0\n        if not largs:\n            largs = allowed_types\n        if not argns.json:\n            for arg in largs:\n                _print_list(arg)\n        else:\n            _print_list_as_json(largs)\n        return 0\n\n    # handle ``pygmentize -H``\n    if argns.H:\n        if not is_only_option('H'):\n            parser.print_help(sys.stderr)\n            return 2\n        what, name = argns.H\n        if what not in ('lexer', 'formatter', 'filter'):\n            parser.print_help(sys.stderr)\n            return 2\n        return _print_help(what, name)\n\n    # parse -O options\n    parsed_opts = _parse_options(argns.O or [])\n\n    # parse -P options\n    for p_opt in argns.P or []:\n        try:\n            name, value = p_opt.split('=', 1)\n        except ValueError:\n            parsed_opts[p_opt] = True\n        else:\n            parsed_opts[name] = value\n\n    # encodings\n    inencoding = parsed_opts.get('inencoding', parsed_opts.get('encoding'))\n    outencoding = parsed_opts.get('outencoding', parsed_opts.get('encoding'))\n\n    # handle ``pygmentize -N``\n    if argns.N:\n        lexer = find_lexer_class_for_filename(argns.N)\n        if lexer is None:\n            lexer = TextLexer\n\n        print(lexer.aliases[0])\n        return 0\n\n    # handle ``pygmentize -C``\n    if argns.C:\n        inp = sys.stdin.buffer.read()\n        try:\n            lexer = guess_lexer(inp, inencoding=inencoding)\n        except ClassNotFound:\n            lexer = TextLexer\n\n        print(lexer.aliases[0])\n        return 0\n\n    # handle ``pygmentize -S``\n    S_opt = argns.S\n    a_opt = argns.a\n    if S_opt is not None:\n        f_opt = argns.f\n        if not f_opt:\n            parser.print_help(sys.stderr)\n            return 2\n        if argns.l or argns.INPUTFILE:\n            parser.print_help(sys.stderr)\n            return 2\n\n        try:\n            parsed_opts['style'] = S_opt\n            fmter = get_formatter_by_name(f_opt, **parsed_opts)\n        except ClassNotFound as err:\n            print(err, file=sys.stderr)\n            return 1\n\n        print(fmter.get_style_defs(a_opt or ''))\n        return 0\n\n    # if no -S is given, -a is not allowed\n    if argns.a is not None:\n        parser.print_help(sys.stderr)\n        return 2\n\n    # parse -F options\n    F_opts = _parse_filters(argns.F or [])\n\n    # -x: allow custom (eXternal) lexers and formatters\n    allow_custom_lexer_formatter = bool(argns.x)\n\n    # select lexer\n    lexer = None\n\n    # given by name?\n    lexername = argns.l\n    if lexername:\n        # custom lexer, located relative to user's cwd\n        if allow_custom_lexer_formatter and '.py' in lexername:\n            try:\n                filename = None\n                name = None\n                if ':' in lexername:\n                    filename, name = lexername.rsplit(':', 1)\n\n                    if '.py' in name:\n                        # This can happen on Windows: If the lexername is\n                        # C:\\lexer.py -- return to normal load path in that case\n                        name = None\n\n                if filename and name:\n                    lexer = load_lexer_from_file(filename, name,\n                                                 **parsed_opts)\n                else:\n                    lexer = load_lexer_from_file(lexername, **parsed_opts)\n            except ClassNotFound as err:\n                print('Error:', err, file=sys.stderr)\n                return 1\n        else:\n            try:\n                lexer = get_lexer_by_name(lexername, **parsed_opts)\n            except (OptionError, ClassNotFound) as err:\n                print('Error:', err, file=sys.stderr)\n                return 1\n\n    # read input code\n    code = None\n\n    if argns.INPUTFILE:\n        if argns.s:\n            print('Error: -s option not usable when input file specified',\n                  file=sys.stderr)\n            return 2\n\n        infn = argns.INPUTFILE\n        try:\n            with open(infn, 'rb') as infp:\n                code = infp.read()\n        except Exception as err:\n            print('Error: cannot read infile:', err, file=sys.stderr)\n            return 1\n        if not inencoding:\n            code, inencoding = guess_decode(code)\n\n        # do we have to guess the lexer?\n        if not lexer:\n            try:\n                lexer = get_lexer_for_filename(infn, code, **parsed_opts)\n            except ClassNotFound as err:\n                if argns.g:\n                    try:\n                        lexer = guess_lexer(code, **parsed_opts)\n                    except ClassNotFound:\n                        lexer = TextLexer(**parsed_opts)\n                else:\n                    print('Error:', err, file=sys.stderr)\n                    return 1\n            except OptionError as err:\n                print('Error:', err, file=sys.stderr)\n                return 1\n\n    elif not argns.s:  # treat stdin as full file (-s support is later)\n        # read code from terminal, always in binary mode since we want to\n        # decode ourselves and be tolerant with it\n        code = sys.stdin.buffer.read()  # use .buffer to get a binary stream\n        if not inencoding:\n            code, inencoding = guess_decode_from_terminal(code, sys.stdin)\n            # else the lexer will do the decoding\n        if not lexer:\n            try:\n                lexer = guess_lexer(code, **parsed_opts)\n            except ClassNotFound:\n                lexer = TextLexer(**parsed_opts)\n\n    else:  # -s option needs a lexer with -l\n        if not lexer:\n            print('Error: when using -s a lexer has to be selected with -l',\n                  file=sys.stderr)\n            return 2\n\n    # process filters\n    for fname, fopts in F_opts:\n        try:\n            lexer.add_filter(fname, **fopts)\n        except ClassNotFound as err:\n            print('Error:', err, file=sys.stderr)\n            return 1\n\n    # select formatter\n    outfn = argns.o\n    fmter = argns.f\n    if fmter:\n        # custom formatter, located relative to user's cwd\n        if allow_custom_lexer_formatter and '.py' in fmter:\n            try:\n                filename = None\n                name = None\n                if ':' in fmter:\n                    # Same logic as above for custom lexer\n                    filename, name = fmter.rsplit(':', 1)\n\n                    if '.py' in name:\n                        name = None\n\n                if filename and name:\n                    fmter = load_formatter_from_file(filename, name,\n                                                     **parsed_opts)\n                else:\n                    fmter = load_formatter_from_file(fmter, **parsed_opts)\n            except ClassNotFound as err:\n                print('Error:', err, file=sys.stderr)\n                return 1\n        else:\n            try:\n                fmter = get_formatter_by_name(fmter, **parsed_opts)\n            except (OptionError, ClassNotFound) as err:\n                print('Error:', err, file=sys.stderr)\n                return 1\n\n    if outfn:\n        if not fmter:\n            try:\n                fmter = get_formatter_for_filename(outfn, **parsed_opts)\n            except (OptionError, ClassNotFound) as err:\n                print('Error:', err, file=sys.stderr)\n                return 1\n        try:\n            outfile = open(outfn, 'wb')\n        except Exception as err:\n            print('Error: cannot open outfile:', err, file=sys.stderr)\n            return 1\n    else:\n        if not fmter:\n            if os.environ.get('COLORTERM','') in ('truecolor', '24bit'):\n                fmter = TerminalTrueColorFormatter(**parsed_opts)\n            elif '256' in os.environ.get('TERM', ''):\n                fmter = Terminal256Formatter(**parsed_opts)\n            else:\n                fmter = TerminalFormatter(**parsed_opts)\n        outfile = sys.stdout.buffer\n\n    # determine output encoding if not explicitly selected\n    if not outencoding:\n        if outfn:\n            # output file? use lexer encoding for now (can still be None)\n            fmter.encoding = inencoding\n        else:\n            # else use terminal encoding\n            fmter.encoding = terminal_encoding(sys.stdout)\n\n    # provide coloring under Windows, if possible\n    if not outfn and sys.platform in ('win32', 'cygwin') and \\\n       fmter.name in ('Terminal', 'Terminal256'):  # pragma: no cover\n        # unfortunately colorama doesn't support binary streams on Py3\n        outfile = UnclosingTextIOWrapper(outfile, encoding=fmter.encoding)\n        fmter.encoding = None\n        try:\n            import pip._vendor.colorama.initialise as colorama_initialise\n        except ImportError:\n            pass\n        else:\n            outfile = colorama_initialise.wrap_stream(\n                outfile, convert=None, strip=None, autoreset=False, wrap=True)\n\n    # When using the LaTeX formatter and the option `escapeinside` is\n    # specified, we need a special lexer which collects escaped text\n    # before running the chosen language lexer.\n    escapeinside = parsed_opts.get('escapeinside', '')\n    if len(escapeinside) == 2 and isinstance(fmter, LatexFormatter):\n        left = escapeinside[0]\n        right = escapeinside[1]\n        lexer = LatexEmbeddedLexer(left, right, lexer)\n\n    # ... and do it!\n    if not argns.s:\n        # process whole input as per normal...\n        try:\n            highlight(code, lexer, fmter, outfile)\n        finally:\n            if outfn:\n                outfile.close()\n        return 0\n    else:\n        # line by line processing of stdin (eg: for 'tail -f')...\n        try:\n            while 1:\n                line = sys.stdin.buffer.readline()\n                if not line:\n                    break\n                if not inencoding:\n                    line = guess_decode_from_terminal(line, sys.stdin)[0]\n                highlight(line, lexer, fmter, outfile)\n                if hasattr(outfile, 'flush'):\n                    outfile.flush()\n            return 0\n        except KeyboardInterrupt:  # pragma: no cover\n            return 0\n        finally:\n            if outfn:\n                outfile.close()\n\n\nclass HelpFormatter(argparse.HelpFormatter):\n    def __init__(self, prog, indent_increment=2, max_help_position=16, width=None):\n        if width is None:\n            try:\n                width = shutil.get_terminal_size().columns - 2\n            except Exception:\n                pass\n        argparse.HelpFormatter.__init__(self, prog, indent_increment,\n                                        max_help_position, width)\n\n\ndef main(args=sys.argv):\n    \"\"\"\n    Main command line entry point.\n    \"\"\"\n    desc = \"Highlight an input file and write the result to an output file.\"\n    parser = argparse.ArgumentParser(description=desc, add_help=False,\n                                     formatter_class=HelpFormatter)\n\n    operation = parser.add_argument_group('Main operation')\n    lexersel = operation.add_mutually_exclusive_group()\n    lexersel.add_argument(\n        '-l', metavar='LEXER',\n        help='Specify the lexer to use.  (Query names with -L.)  If not '\n        'given and -g is not present, the lexer is guessed from the filename.')\n    lexersel.add_argument(\n        '-g', action='store_true',\n        help='Guess the lexer from the file contents, or pass through '\n        'as plain text if nothing can be guessed.')\n    operation.add_argument(\n        '-F', metavar='FILTER[:options]', action='append',\n        help='Add a filter to the token stream.  (Query names with -L.) '\n        'Filter options are given after a colon if necessary.')\n    operation.add_argument(\n        '-f', metavar='FORMATTER',\n        help='Specify the formatter to use.  (Query names with -L.) '\n        'If not given, the formatter is guessed from the output filename, '\n        'and defaults to the terminal formatter if the output is to the '\n        'terminal or an unknown file extension.')\n    operation.add_argument(\n        '-O', metavar='OPTION=value[,OPTION=value,...]', action='append',\n        help='Give options to the lexer and formatter as a comma-separated '\n        'list of key-value pairs. '\n        'Example: `-O bg=light,python=cool`.')\n    operation.add_argument(\n        '-P', metavar='OPTION=value', action='append',\n        help='Give a single option to the lexer and formatter - with this '\n        'you can pass options whose value contains commas and equal signs. '\n        'Example: `-P \"heading=Pygments, the Python highlighter\"`.')\n    operation.add_argument(\n        '-o', metavar='OUTPUTFILE',\n        help='Where to write the output.  Defaults to standard output.')\n\n    operation.add_argument(\n        'INPUTFILE', nargs='?',\n        help='Where to read the input.  Defaults to standard input.')\n\n    flags = parser.add_argument_group('Operation flags')\n    flags.add_argument(\n        '-v', action='store_true',\n        help='Print a detailed traceback on unhandled exceptions, which '\n        'is useful for debugging and bug reports.')\n    flags.add_argument(\n        '-s', action='store_true',\n        help='Process lines one at a time until EOF, rather than waiting to '\n        'process the entire file.  This only works for stdin, only for lexers '\n        'with no line-spanning constructs, and is intended for streaming '\n        'input such as you get from `tail -f`. '\n        'Example usage: `tail -f sql.log | pygmentize -s -l sql`.')\n    flags.add_argument(\n        '-x', action='store_true',\n        help='Allow custom lexers and formatters to be loaded from a .py file '\n        'relative to the current working directory. For example, '\n        '`-l ./customlexer.py -x`. By default, this option expects a file '\n        'with a class named CustomLexer or CustomFormatter; you can also '\n        'specify your own class name with a colon (`-l ./lexer.py:MyLexer`). '\n        'Users should be very careful not to use this option with untrusted '\n        'files, because it will import and run them.')\n    flags.add_argument('--json', help='Output as JSON. This can '\n        'be only used in conjunction with -L.',\n        default=False,\n        action='store_true')\n\n    special_modes_group = parser.add_argument_group(\n        'Special modes - do not do any highlighting')\n    special_modes = special_modes_group.add_mutually_exclusive_group()\n    special_modes.add_argument(\n        '-S', metavar='STYLE -f formatter',\n        help='Print style definitions for STYLE for a formatter '\n        'given with -f. The argument given by -a is formatter '\n        'dependent.')\n    special_modes.add_argument(\n        '-L', nargs='*', metavar='WHAT',\n        help='List lexers, formatters, styles or filters -- '\n        'give additional arguments for the thing(s) you want to list '\n        '(e.g. \"styles\"), or omit them to list everything.')\n    special_modes.add_argument(\n        '-N', metavar='FILENAME',\n        help='Guess and print out a lexer name based solely on the given '\n        'filename. Does not take input or highlight anything. If no specific '\n        'lexer can be determined, \"text\" is printed.')\n    special_modes.add_argument(\n        '-C', action='store_true',\n        help='Like -N, but print out a lexer name based solely on '\n        'a given content from standard input.')\n    special_modes.add_argument(\n        '-H', action='store', nargs=2, metavar=('NAME', 'TYPE'),\n        help='Print detailed help for the object <name> of type <type>, '\n        'where <type> is one of \"lexer\", \"formatter\" or \"filter\".')\n    special_modes.add_argument(\n        '-V', action='store_true',\n        help='Print the package version.')\n    special_modes.add_argument(\n        '-h', '--help', action='store_true',\n        help='Print this help.')\n    special_modes_group.add_argument(\n        '-a', metavar='ARG',\n        help='Formatter-specific additional argument for the -S (print '\n        'style sheet) mode.')\n\n    argns = parser.parse_args(args[1:])\n\n    try:\n        return main_inner(parser, argns)\n    except BrokenPipeError:\n        # someone closed our stdout, e.g. by quitting a pager.\n        return 0\n    except Exception:\n        if argns.v:\n            print(file=sys.stderr)\n            print('*' * 65, file=sys.stderr)\n            print('An unhandled exception occurred while highlighting.',\n                  file=sys.stderr)\n            print('Please report the whole traceback to the issue tracker at',\n                  file=sys.stderr)\n            print('<https://github.com/pygments/pygments/issues>.',\n                  file=sys.stderr)\n            print('*' * 65, file=sys.stderr)\n            print(file=sys.stderr)\n            raise\n        import traceback\n        info = traceback.format_exception(*sys.exc_info())\n        msg = info[-1].strip()\n        if len(info) >= 3:\n            # extract relevant file and position info\n            msg += '\\n   (f%s)' % info[-2].split('\\n')[0].strip()[1:]\n        print(file=sys.stderr)\n        print('*** Error while highlighting:', file=sys.stderr)\n        print(msg, file=sys.stderr)\n        print('*** If this is a bug you want to report, please rerun with -v.',\n              file=sys.stderr)\n        return 1\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/console.py",
    "content": "\"\"\"\n    pygments.console\n    ~~~~~~~~~~~~~~~~\n\n    Format colored console output.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nesc = \"\\x1b[\"\n\ncodes = {}\ncodes[\"\"] = \"\"\ncodes[\"reset\"] = esc + \"39;49;00m\"\n\ncodes[\"bold\"] = esc + \"01m\"\ncodes[\"faint\"] = esc + \"02m\"\ncodes[\"standout\"] = esc + \"03m\"\ncodes[\"underline\"] = esc + \"04m\"\ncodes[\"blink\"] = esc + \"05m\"\ncodes[\"overline\"] = esc + \"06m\"\n\ndark_colors = [\"black\", \"red\", \"green\", \"yellow\", \"blue\",\n               \"magenta\", \"cyan\", \"gray\"]\nlight_colors = [\"brightblack\", \"brightred\", \"brightgreen\", \"brightyellow\", \"brightblue\",\n                \"brightmagenta\", \"brightcyan\", \"white\"]\n\nx = 30\nfor d, l in zip(dark_colors, light_colors):\n    codes[d] = esc + \"%im\" % x\n    codes[l] = esc + \"%im\" % (60 + x)\n    x += 1\n\ndel d, l, x\n\ncodes[\"white\"] = codes[\"bold\"]\n\n\ndef reset_color():\n    return codes[\"reset\"]\n\n\ndef colorize(color_key, text):\n    return codes[color_key] + text + codes[\"reset\"]\n\n\ndef ansiformat(attr, text):\n    \"\"\"\n    Format ``text`` with a color and/or some attributes::\n\n        color       normal color\n        *color*     bold color\n        _color_     underlined color\n        +color+     blinking color\n    \"\"\"\n    result = []\n    if attr[:1] == attr[-1:] == '+':\n        result.append(codes['blink'])\n        attr = attr[1:-1]\n    if attr[:1] == attr[-1:] == '*':\n        result.append(codes['bold'])\n        attr = attr[1:-1]\n    if attr[:1] == attr[-1:] == '_':\n        result.append(codes['underline'])\n        attr = attr[1:-1]\n    result.append(codes[attr])\n    result.append(text)\n    result.append(codes['reset'])\n    return ''.join(result)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/filter.py",
    "content": "\"\"\"\n    pygments.filter\n    ~~~~~~~~~~~~~~~\n\n    Module that implements the default filter.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\n\ndef apply_filters(stream, filters, lexer=None):\n    \"\"\"\n    Use this method to apply an iterable of filters to\n    a stream. If lexer is given it's forwarded to the\n    filter, otherwise the filter receives `None`.\n    \"\"\"\n    def _apply(filter_, stream):\n        yield from filter_.filter(lexer, stream)\n    for filter_ in filters:\n        stream = _apply(filter_, stream)\n    return stream\n\n\ndef simplefilter(f):\n    \"\"\"\n    Decorator that converts a function into a filter::\n\n        @simplefilter\n        def lowercase(self, lexer, stream, options):\n            for ttype, value in stream:\n                yield ttype, value.lower()\n    \"\"\"\n    return type(f.__name__, (FunctionFilter,), {\n        '__module__': getattr(f, '__module__'),\n        '__doc__': f.__doc__,\n        'function': f,\n    })\n\n\nclass Filter:\n    \"\"\"\n    Default filter. Subclass this class or use the `simplefilter`\n    decorator to create own filters.\n    \"\"\"\n\n    def __init__(self, **options):\n        self.options = options\n\n    def filter(self, lexer, stream):\n        raise NotImplementedError()\n\n\nclass FunctionFilter(Filter):\n    \"\"\"\n    Abstract class used by `simplefilter` to create simple\n    function filters on the fly. The `simplefilter` decorator\n    automatically creates subclasses of this class for\n    functions passed to it.\n    \"\"\"\n    function = None\n\n    def __init__(self, **options):\n        if not hasattr(self, 'function'):\n            raise TypeError('%r used without bound function' %\n                            self.__class__.__name__)\n        Filter.__init__(self, **options)\n\n    def filter(self, lexer, stream):\n        # pylint: disable=not-callable\n        yield from self.function(lexer, stream, self.options)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/filters/__init__.py",
    "content": "\"\"\"\n    pygments.filters\n    ~~~~~~~~~~~~~~~~\n\n    Module containing filter lookup functions and default\n    filters.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\n\nfrom pip._vendor.pygments.token import String, Comment, Keyword, Name, Error, Whitespace, \\\n    string_to_tokentype\nfrom pip._vendor.pygments.filter import Filter\nfrom pip._vendor.pygments.util import get_list_opt, get_int_opt, get_bool_opt, \\\n    get_choice_opt, ClassNotFound, OptionError\nfrom pip._vendor.pygments.plugin import find_plugin_filters\n\n\ndef find_filter_class(filtername):\n    \"\"\"Lookup a filter by name. Return None if not found.\"\"\"\n    if filtername in FILTERS:\n        return FILTERS[filtername]\n    for name, cls in find_plugin_filters():\n        if name == filtername:\n            return cls\n    return None\n\n\ndef get_filter_by_name(filtername, **options):\n    \"\"\"Return an instantiated filter.\n\n    Options are passed to the filter initializer if wanted.\n    Raise a ClassNotFound if not found.\n    \"\"\"\n    cls = find_filter_class(filtername)\n    if cls:\n        return cls(**options)\n    else:\n        raise ClassNotFound('filter %r not found' % filtername)\n\n\ndef get_all_filters():\n    \"\"\"Return a generator of all filter names.\"\"\"\n    yield from FILTERS\n    for name, _ in find_plugin_filters():\n        yield name\n\n\ndef _replace_special(ttype, value, regex, specialttype,\n                     replacefunc=lambda x: x):\n    last = 0\n    for match in regex.finditer(value):\n        start, end = match.start(), match.end()\n        if start != last:\n            yield ttype, value[last:start]\n        yield specialttype, replacefunc(value[start:end])\n        last = end\n    if last != len(value):\n        yield ttype, value[last:]\n\n\nclass CodeTagFilter(Filter):\n    \"\"\"Highlight special code tags in comments and docstrings.\n\n    Options accepted:\n\n    `codetags` : list of strings\n       A list of strings that are flagged as code tags.  The default is to\n       highlight ``XXX``, ``TODO``, ``FIXME``, ``BUG`` and ``NOTE``.\n\n    .. versionchanged:: 2.13\n       Now recognizes ``FIXME`` by default.\n    \"\"\"\n\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n        tags = get_list_opt(options, 'codetags',\n                            ['XXX', 'TODO', 'FIXME', 'BUG', 'NOTE'])\n        self.tag_re = re.compile(r'\\b(%s)\\b' % '|'.join([\n            re.escape(tag) for tag in tags if tag\n        ]))\n\n    def filter(self, lexer, stream):\n        regex = self.tag_re\n        for ttype, value in stream:\n            if ttype in String.Doc or \\\n               ttype in Comment and \\\n               ttype not in Comment.Preproc:\n                yield from _replace_special(ttype, value, regex, Comment.Special)\n            else:\n                yield ttype, value\n\n\nclass SymbolFilter(Filter):\n    \"\"\"Convert mathematical symbols such as \\\\<longrightarrow> in Isabelle\n    or \\\\longrightarrow in LaTeX into Unicode characters.\n\n    This is mostly useful for HTML or console output when you want to\n    approximate the source rendering you'd see in an IDE.\n\n    Options accepted:\n\n    `lang` : string\n       The symbol language. Must be one of ``'isabelle'`` or\n       ``'latex'``.  The default is ``'isabelle'``.\n    \"\"\"\n\n    latex_symbols = {\n        '\\\\alpha'                : '\\U000003b1',\n        '\\\\beta'                 : '\\U000003b2',\n        '\\\\gamma'                : '\\U000003b3',\n        '\\\\delta'                : '\\U000003b4',\n        '\\\\varepsilon'           : '\\U000003b5',\n        '\\\\zeta'                 : '\\U000003b6',\n        '\\\\eta'                  : '\\U000003b7',\n        '\\\\vartheta'             : '\\U000003b8',\n        '\\\\iota'                 : '\\U000003b9',\n        '\\\\kappa'                : '\\U000003ba',\n        '\\\\lambda'               : '\\U000003bb',\n        '\\\\mu'                   : '\\U000003bc',\n        '\\\\nu'                   : '\\U000003bd',\n        '\\\\xi'                   : '\\U000003be',\n        '\\\\pi'                   : '\\U000003c0',\n        '\\\\varrho'               : '\\U000003c1',\n        '\\\\sigma'                : '\\U000003c3',\n        '\\\\tau'                  : '\\U000003c4',\n        '\\\\upsilon'              : '\\U000003c5',\n        '\\\\varphi'               : '\\U000003c6',\n        '\\\\chi'                  : '\\U000003c7',\n        '\\\\psi'                  : '\\U000003c8',\n        '\\\\omega'                : '\\U000003c9',\n        '\\\\Gamma'                : '\\U00000393',\n        '\\\\Delta'                : '\\U00000394',\n        '\\\\Theta'                : '\\U00000398',\n        '\\\\Lambda'               : '\\U0000039b',\n        '\\\\Xi'                   : '\\U0000039e',\n        '\\\\Pi'                   : '\\U000003a0',\n        '\\\\Sigma'                : '\\U000003a3',\n        '\\\\Upsilon'              : '\\U000003a5',\n        '\\\\Phi'                  : '\\U000003a6',\n        '\\\\Psi'                  : '\\U000003a8',\n        '\\\\Omega'                : '\\U000003a9',\n        '\\\\leftarrow'            : '\\U00002190',\n        '\\\\longleftarrow'        : '\\U000027f5',\n        '\\\\rightarrow'           : '\\U00002192',\n        '\\\\longrightarrow'       : '\\U000027f6',\n        '\\\\Leftarrow'            : '\\U000021d0',\n        '\\\\Longleftarrow'        : '\\U000027f8',\n        '\\\\Rightarrow'           : '\\U000021d2',\n        '\\\\Longrightarrow'       : '\\U000027f9',\n        '\\\\leftrightarrow'       : '\\U00002194',\n        '\\\\longleftrightarrow'   : '\\U000027f7',\n        '\\\\Leftrightarrow'       : '\\U000021d4',\n        '\\\\Longleftrightarrow'   : '\\U000027fa',\n        '\\\\mapsto'               : '\\U000021a6',\n        '\\\\longmapsto'           : '\\U000027fc',\n        '\\\\relbar'               : '\\U00002500',\n        '\\\\Relbar'               : '\\U00002550',\n        '\\\\hookleftarrow'        : '\\U000021a9',\n        '\\\\hookrightarrow'       : '\\U000021aa',\n        '\\\\leftharpoondown'      : '\\U000021bd',\n        '\\\\rightharpoondown'     : '\\U000021c1',\n        '\\\\leftharpoonup'        : '\\U000021bc',\n        '\\\\rightharpoonup'       : '\\U000021c0',\n        '\\\\rightleftharpoons'    : '\\U000021cc',\n        '\\\\leadsto'              : '\\U0000219d',\n        '\\\\downharpoonleft'      : '\\U000021c3',\n        '\\\\downharpoonright'     : '\\U000021c2',\n        '\\\\upharpoonleft'        : '\\U000021bf',\n        '\\\\upharpoonright'       : '\\U000021be',\n        '\\\\restriction'          : '\\U000021be',\n        '\\\\uparrow'              : '\\U00002191',\n        '\\\\Uparrow'              : '\\U000021d1',\n        '\\\\downarrow'            : '\\U00002193',\n        '\\\\Downarrow'            : '\\U000021d3',\n        '\\\\updownarrow'          : '\\U00002195',\n        '\\\\Updownarrow'          : '\\U000021d5',\n        '\\\\langle'               : '\\U000027e8',\n        '\\\\rangle'               : '\\U000027e9',\n        '\\\\lceil'                : '\\U00002308',\n        '\\\\rceil'                : '\\U00002309',\n        '\\\\lfloor'               : '\\U0000230a',\n        '\\\\rfloor'               : '\\U0000230b',\n        '\\\\flqq'                 : '\\U000000ab',\n        '\\\\frqq'                 : '\\U000000bb',\n        '\\\\bot'                  : '\\U000022a5',\n        '\\\\top'                  : '\\U000022a4',\n        '\\\\wedge'                : '\\U00002227',\n        '\\\\bigwedge'             : '\\U000022c0',\n        '\\\\vee'                  : '\\U00002228',\n        '\\\\bigvee'               : '\\U000022c1',\n        '\\\\forall'               : '\\U00002200',\n        '\\\\exists'               : '\\U00002203',\n        '\\\\nexists'              : '\\U00002204',\n        '\\\\neg'                  : '\\U000000ac',\n        '\\\\Box'                  : '\\U000025a1',\n        '\\\\Diamond'              : '\\U000025c7',\n        '\\\\vdash'                : '\\U000022a2',\n        '\\\\models'               : '\\U000022a8',\n        '\\\\dashv'                : '\\U000022a3',\n        '\\\\surd'                 : '\\U0000221a',\n        '\\\\le'                   : '\\U00002264',\n        '\\\\ge'                   : '\\U00002265',\n        '\\\\ll'                   : '\\U0000226a',\n        '\\\\gg'                   : '\\U0000226b',\n        '\\\\lesssim'              : '\\U00002272',\n        '\\\\gtrsim'               : '\\U00002273',\n        '\\\\lessapprox'           : '\\U00002a85',\n        '\\\\gtrapprox'            : '\\U00002a86',\n        '\\\\in'                   : '\\U00002208',\n        '\\\\notin'                : '\\U00002209',\n        '\\\\subset'               : '\\U00002282',\n        '\\\\supset'               : '\\U00002283',\n        '\\\\subseteq'             : '\\U00002286',\n        '\\\\supseteq'             : '\\U00002287',\n        '\\\\sqsubset'             : '\\U0000228f',\n        '\\\\sqsupset'             : '\\U00002290',\n        '\\\\sqsubseteq'           : '\\U00002291',\n        '\\\\sqsupseteq'           : '\\U00002292',\n        '\\\\cap'                  : '\\U00002229',\n        '\\\\bigcap'               : '\\U000022c2',\n        '\\\\cup'                  : '\\U0000222a',\n        '\\\\bigcup'               : '\\U000022c3',\n        '\\\\sqcup'                : '\\U00002294',\n        '\\\\bigsqcup'             : '\\U00002a06',\n        '\\\\sqcap'                : '\\U00002293',\n        '\\\\Bigsqcap'             : '\\U00002a05',\n        '\\\\setminus'             : '\\U00002216',\n        '\\\\propto'               : '\\U0000221d',\n        '\\\\uplus'                : '\\U0000228e',\n        '\\\\bigplus'              : '\\U00002a04',\n        '\\\\sim'                  : '\\U0000223c',\n        '\\\\doteq'                : '\\U00002250',\n        '\\\\simeq'                : '\\U00002243',\n        '\\\\approx'               : '\\U00002248',\n        '\\\\asymp'                : '\\U0000224d',\n        '\\\\cong'                 : '\\U00002245',\n        '\\\\equiv'                : '\\U00002261',\n        '\\\\Join'                 : '\\U000022c8',\n        '\\\\bowtie'               : '\\U00002a1d',\n        '\\\\prec'                 : '\\U0000227a',\n        '\\\\succ'                 : '\\U0000227b',\n        '\\\\preceq'               : '\\U0000227c',\n        '\\\\succeq'               : '\\U0000227d',\n        '\\\\parallel'             : '\\U00002225',\n        '\\\\mid'                  : '\\U000000a6',\n        '\\\\pm'                   : '\\U000000b1',\n        '\\\\mp'                   : '\\U00002213',\n        '\\\\times'                : '\\U000000d7',\n        '\\\\div'                  : '\\U000000f7',\n        '\\\\cdot'                 : '\\U000022c5',\n        '\\\\star'                 : '\\U000022c6',\n        '\\\\circ'                 : '\\U00002218',\n        '\\\\dagger'               : '\\U00002020',\n        '\\\\ddagger'              : '\\U00002021',\n        '\\\\lhd'                  : '\\U000022b2',\n        '\\\\rhd'                  : '\\U000022b3',\n        '\\\\unlhd'                : '\\U000022b4',\n        '\\\\unrhd'                : '\\U000022b5',\n        '\\\\triangleleft'         : '\\U000025c3',\n        '\\\\triangleright'        : '\\U000025b9',\n        '\\\\triangle'             : '\\U000025b3',\n        '\\\\triangleq'            : '\\U0000225c',\n        '\\\\oplus'                : '\\U00002295',\n        '\\\\bigoplus'             : '\\U00002a01',\n        '\\\\otimes'               : '\\U00002297',\n        '\\\\bigotimes'            : '\\U00002a02',\n        '\\\\odot'                 : '\\U00002299',\n        '\\\\bigodot'              : '\\U00002a00',\n        '\\\\ominus'               : '\\U00002296',\n        '\\\\oslash'               : '\\U00002298',\n        '\\\\dots'                 : '\\U00002026',\n        '\\\\cdots'                : '\\U000022ef',\n        '\\\\sum'                  : '\\U00002211',\n        '\\\\prod'                 : '\\U0000220f',\n        '\\\\coprod'               : '\\U00002210',\n        '\\\\infty'                : '\\U0000221e',\n        '\\\\int'                  : '\\U0000222b',\n        '\\\\oint'                 : '\\U0000222e',\n        '\\\\clubsuit'             : '\\U00002663',\n        '\\\\diamondsuit'          : '\\U00002662',\n        '\\\\heartsuit'            : '\\U00002661',\n        '\\\\spadesuit'            : '\\U00002660',\n        '\\\\aleph'                : '\\U00002135',\n        '\\\\emptyset'             : '\\U00002205',\n        '\\\\nabla'                : '\\U00002207',\n        '\\\\partial'              : '\\U00002202',\n        '\\\\flat'                 : '\\U0000266d',\n        '\\\\natural'              : '\\U0000266e',\n        '\\\\sharp'                : '\\U0000266f',\n        '\\\\angle'                : '\\U00002220',\n        '\\\\copyright'            : '\\U000000a9',\n        '\\\\textregistered'       : '\\U000000ae',\n        '\\\\textonequarter'       : '\\U000000bc',\n        '\\\\textonehalf'          : '\\U000000bd',\n        '\\\\textthreequarters'    : '\\U000000be',\n        '\\\\textordfeminine'      : '\\U000000aa',\n        '\\\\textordmasculine'     : '\\U000000ba',\n        '\\\\euro'                 : '\\U000020ac',\n        '\\\\pounds'               : '\\U000000a3',\n        '\\\\yen'                  : '\\U000000a5',\n        '\\\\textcent'             : '\\U000000a2',\n        '\\\\textcurrency'         : '\\U000000a4',\n        '\\\\textdegree'           : '\\U000000b0',\n    }\n\n    isabelle_symbols = {\n        '\\\\<zero>'                 : '\\U0001d7ec',\n        '\\\\<one>'                  : '\\U0001d7ed',\n        '\\\\<two>'                  : '\\U0001d7ee',\n        '\\\\<three>'                : '\\U0001d7ef',\n        '\\\\<four>'                 : '\\U0001d7f0',\n        '\\\\<five>'                 : '\\U0001d7f1',\n        '\\\\<six>'                  : '\\U0001d7f2',\n        '\\\\<seven>'                : '\\U0001d7f3',\n        '\\\\<eight>'                : '\\U0001d7f4',\n        '\\\\<nine>'                 : '\\U0001d7f5',\n        '\\\\<A>'                    : '\\U0001d49c',\n        '\\\\<B>'                    : '\\U0000212c',\n        '\\\\<C>'                    : '\\U0001d49e',\n        '\\\\<D>'                    : '\\U0001d49f',\n        '\\\\<E>'                    : '\\U00002130',\n        '\\\\<F>'                    : '\\U00002131',\n        '\\\\<G>'                    : '\\U0001d4a2',\n        '\\\\<H>'                    : '\\U0000210b',\n        '\\\\<I>'                    : '\\U00002110',\n        '\\\\<J>'                    : '\\U0001d4a5',\n        '\\\\<K>'                    : '\\U0001d4a6',\n        '\\\\<L>'                    : '\\U00002112',\n        '\\\\<M>'                    : '\\U00002133',\n        '\\\\<N>'                    : '\\U0001d4a9',\n        '\\\\<O>'                    : '\\U0001d4aa',\n        '\\\\<P>'                    : '\\U0001d4ab',\n        '\\\\<Q>'                    : '\\U0001d4ac',\n        '\\\\<R>'                    : '\\U0000211b',\n        '\\\\<S>'                    : '\\U0001d4ae',\n        '\\\\<T>'                    : '\\U0001d4af',\n        '\\\\<U>'                    : '\\U0001d4b0',\n        '\\\\<V>'                    : '\\U0001d4b1',\n        '\\\\<W>'                    : '\\U0001d4b2',\n        '\\\\<X>'                    : '\\U0001d4b3',\n        '\\\\<Y>'                    : '\\U0001d4b4',\n        '\\\\<Z>'                    : '\\U0001d4b5',\n        '\\\\<a>'                    : '\\U0001d5ba',\n        '\\\\<b>'                    : '\\U0001d5bb',\n        '\\\\<c>'                    : '\\U0001d5bc',\n        '\\\\<d>'                    : '\\U0001d5bd',\n        '\\\\<e>'                    : '\\U0001d5be',\n        '\\\\<f>'                    : '\\U0001d5bf',\n        '\\\\<g>'                    : '\\U0001d5c0',\n        '\\\\<h>'                    : '\\U0001d5c1',\n        '\\\\<i>'                    : '\\U0001d5c2',\n        '\\\\<j>'                    : '\\U0001d5c3',\n        '\\\\<k>'                    : '\\U0001d5c4',\n        '\\\\<l>'                    : '\\U0001d5c5',\n        '\\\\<m>'                    : '\\U0001d5c6',\n        '\\\\<n>'                    : '\\U0001d5c7',\n        '\\\\<o>'                    : '\\U0001d5c8',\n        '\\\\<p>'                    : '\\U0001d5c9',\n        '\\\\<q>'                    : '\\U0001d5ca',\n        '\\\\<r>'                    : '\\U0001d5cb',\n        '\\\\<s>'                    : '\\U0001d5cc',\n        '\\\\<t>'                    : '\\U0001d5cd',\n        '\\\\<u>'                    : '\\U0001d5ce',\n        '\\\\<v>'                    : '\\U0001d5cf',\n        '\\\\<w>'                    : '\\U0001d5d0',\n        '\\\\<x>'                    : '\\U0001d5d1',\n        '\\\\<y>'                    : '\\U0001d5d2',\n        '\\\\<z>'                    : '\\U0001d5d3',\n        '\\\\<AA>'                   : '\\U0001d504',\n        '\\\\<BB>'                   : '\\U0001d505',\n        '\\\\<CC>'                   : '\\U0000212d',\n        '\\\\<DD>'                   : '\\U0001d507',\n        '\\\\<EE>'                   : '\\U0001d508',\n        '\\\\<FF>'                   : '\\U0001d509',\n        '\\\\<GG>'                   : '\\U0001d50a',\n        '\\\\<HH>'                   : '\\U0000210c',\n        '\\\\<II>'                   : '\\U00002111',\n        '\\\\<JJ>'                   : '\\U0001d50d',\n        '\\\\<KK>'                   : '\\U0001d50e',\n        '\\\\<LL>'                   : '\\U0001d50f',\n        '\\\\<MM>'                   : '\\U0001d510',\n        '\\\\<NN>'                   : '\\U0001d511',\n        '\\\\<OO>'                   : '\\U0001d512',\n        '\\\\<PP>'                   : '\\U0001d513',\n        '\\\\<QQ>'                   : '\\U0001d514',\n        '\\\\<RR>'                   : '\\U0000211c',\n        '\\\\<SS>'                   : '\\U0001d516',\n        '\\\\<TT>'                   : '\\U0001d517',\n        '\\\\<UU>'                   : '\\U0001d518',\n        '\\\\<VV>'                   : '\\U0001d519',\n        '\\\\<WW>'                   : '\\U0001d51a',\n        '\\\\<XX>'                   : '\\U0001d51b',\n        '\\\\<YY>'                   : '\\U0001d51c',\n        '\\\\<ZZ>'                   : '\\U00002128',\n        '\\\\<aa>'                   : '\\U0001d51e',\n        '\\\\<bb>'                   : '\\U0001d51f',\n        '\\\\<cc>'                   : '\\U0001d520',\n        '\\\\<dd>'                   : '\\U0001d521',\n        '\\\\<ee>'                   : '\\U0001d522',\n        '\\\\<ff>'                   : '\\U0001d523',\n        '\\\\<gg>'                   : '\\U0001d524',\n        '\\\\<hh>'                   : '\\U0001d525',\n        '\\\\<ii>'                   : '\\U0001d526',\n        '\\\\<jj>'                   : '\\U0001d527',\n        '\\\\<kk>'                   : '\\U0001d528',\n        '\\\\<ll>'                   : '\\U0001d529',\n        '\\\\<mm>'                   : '\\U0001d52a',\n        '\\\\<nn>'                   : '\\U0001d52b',\n        '\\\\<oo>'                   : '\\U0001d52c',\n        '\\\\<pp>'                   : '\\U0001d52d',\n        '\\\\<qq>'                   : '\\U0001d52e',\n        '\\\\<rr>'                   : '\\U0001d52f',\n        '\\\\<ss>'                   : '\\U0001d530',\n        '\\\\<tt>'                   : '\\U0001d531',\n        '\\\\<uu>'                   : '\\U0001d532',\n        '\\\\<vv>'                   : '\\U0001d533',\n        '\\\\<ww>'                   : '\\U0001d534',\n        '\\\\<xx>'                   : '\\U0001d535',\n        '\\\\<yy>'                   : '\\U0001d536',\n        '\\\\<zz>'                   : '\\U0001d537',\n        '\\\\<alpha>'                : '\\U000003b1',\n        '\\\\<beta>'                 : '\\U000003b2',\n        '\\\\<gamma>'                : '\\U000003b3',\n        '\\\\<delta>'                : '\\U000003b4',\n        '\\\\<epsilon>'              : '\\U000003b5',\n        '\\\\<zeta>'                 : '\\U000003b6',\n        '\\\\<eta>'                  : '\\U000003b7',\n        '\\\\<theta>'                : '\\U000003b8',\n        '\\\\<iota>'                 : '\\U000003b9',\n        '\\\\<kappa>'                : '\\U000003ba',\n        '\\\\<lambda>'               : '\\U000003bb',\n        '\\\\<mu>'                   : '\\U000003bc',\n        '\\\\<nu>'                   : '\\U000003bd',\n        '\\\\<xi>'                   : '\\U000003be',\n        '\\\\<pi>'                   : '\\U000003c0',\n        '\\\\<rho>'                  : '\\U000003c1',\n        '\\\\<sigma>'                : '\\U000003c3',\n        '\\\\<tau>'                  : '\\U000003c4',\n        '\\\\<upsilon>'              : '\\U000003c5',\n        '\\\\<phi>'                  : '\\U000003c6',\n        '\\\\<chi>'                  : '\\U000003c7',\n        '\\\\<psi>'                  : '\\U000003c8',\n        '\\\\<omega>'                : '\\U000003c9',\n        '\\\\<Gamma>'                : '\\U00000393',\n        '\\\\<Delta>'                : '\\U00000394',\n        '\\\\<Theta>'                : '\\U00000398',\n        '\\\\<Lambda>'               : '\\U0000039b',\n        '\\\\<Xi>'                   : '\\U0000039e',\n        '\\\\<Pi>'                   : '\\U000003a0',\n        '\\\\<Sigma>'                : '\\U000003a3',\n        '\\\\<Upsilon>'              : '\\U000003a5',\n        '\\\\<Phi>'                  : '\\U000003a6',\n        '\\\\<Psi>'                  : '\\U000003a8',\n        '\\\\<Omega>'                : '\\U000003a9',\n        '\\\\<bool>'                 : '\\U0001d539',\n        '\\\\<complex>'              : '\\U00002102',\n        '\\\\<nat>'                  : '\\U00002115',\n        '\\\\<rat>'                  : '\\U0000211a',\n        '\\\\<real>'                 : '\\U0000211d',\n        '\\\\<int>'                  : '\\U00002124',\n        '\\\\<leftarrow>'            : '\\U00002190',\n        '\\\\<longleftarrow>'        : '\\U000027f5',\n        '\\\\<rightarrow>'           : '\\U00002192',\n        '\\\\<longrightarrow>'       : '\\U000027f6',\n        '\\\\<Leftarrow>'            : '\\U000021d0',\n        '\\\\<Longleftarrow>'        : '\\U000027f8',\n        '\\\\<Rightarrow>'           : '\\U000021d2',\n        '\\\\<Longrightarrow>'       : '\\U000027f9',\n        '\\\\<leftrightarrow>'       : '\\U00002194',\n        '\\\\<longleftrightarrow>'   : '\\U000027f7',\n        '\\\\<Leftrightarrow>'       : '\\U000021d4',\n        '\\\\<Longleftrightarrow>'   : '\\U000027fa',\n        '\\\\<mapsto>'               : '\\U000021a6',\n        '\\\\<longmapsto>'           : '\\U000027fc',\n        '\\\\<midarrow>'             : '\\U00002500',\n        '\\\\<Midarrow>'             : '\\U00002550',\n        '\\\\<hookleftarrow>'        : '\\U000021a9',\n        '\\\\<hookrightarrow>'       : '\\U000021aa',\n        '\\\\<leftharpoondown>'      : '\\U000021bd',\n        '\\\\<rightharpoondown>'     : '\\U000021c1',\n        '\\\\<leftharpoonup>'        : '\\U000021bc',\n        '\\\\<rightharpoonup>'       : '\\U000021c0',\n        '\\\\<rightleftharpoons>'    : '\\U000021cc',\n        '\\\\<leadsto>'              : '\\U0000219d',\n        '\\\\<downharpoonleft>'      : '\\U000021c3',\n        '\\\\<downharpoonright>'     : '\\U000021c2',\n        '\\\\<upharpoonleft>'        : '\\U000021bf',\n        '\\\\<upharpoonright>'       : '\\U000021be',\n        '\\\\<restriction>'          : '\\U000021be',\n        '\\\\<Colon>'                : '\\U00002237',\n        '\\\\<up>'                   : '\\U00002191',\n        '\\\\<Up>'                   : '\\U000021d1',\n        '\\\\<down>'                 : '\\U00002193',\n        '\\\\<Down>'                 : '\\U000021d3',\n        '\\\\<updown>'               : '\\U00002195',\n        '\\\\<Updown>'               : '\\U000021d5',\n        '\\\\<langle>'               : '\\U000027e8',\n        '\\\\<rangle>'               : '\\U000027e9',\n        '\\\\<lceil>'                : '\\U00002308',\n        '\\\\<rceil>'                : '\\U00002309',\n        '\\\\<lfloor>'               : '\\U0000230a',\n        '\\\\<rfloor>'               : '\\U0000230b',\n        '\\\\<lparr>'                : '\\U00002987',\n        '\\\\<rparr>'                : '\\U00002988',\n        '\\\\<lbrakk>'               : '\\U000027e6',\n        '\\\\<rbrakk>'               : '\\U000027e7',\n        '\\\\<lbrace>'               : '\\U00002983',\n        '\\\\<rbrace>'               : '\\U00002984',\n        '\\\\<guillemotleft>'        : '\\U000000ab',\n        '\\\\<guillemotright>'       : '\\U000000bb',\n        '\\\\<bottom>'               : '\\U000022a5',\n        '\\\\<top>'                  : '\\U000022a4',\n        '\\\\<and>'                  : '\\U00002227',\n        '\\\\<And>'                  : '\\U000022c0',\n        '\\\\<or>'                   : '\\U00002228',\n        '\\\\<Or>'                   : '\\U000022c1',\n        '\\\\<forall>'               : '\\U00002200',\n        '\\\\<exists>'               : '\\U00002203',\n        '\\\\<nexists>'              : '\\U00002204',\n        '\\\\<not>'                  : '\\U000000ac',\n        '\\\\<box>'                  : '\\U000025a1',\n        '\\\\<diamond>'              : '\\U000025c7',\n        '\\\\<turnstile>'            : '\\U000022a2',\n        '\\\\<Turnstile>'            : '\\U000022a8',\n        '\\\\<tturnstile>'           : '\\U000022a9',\n        '\\\\<TTurnstile>'           : '\\U000022ab',\n        '\\\\<stileturn>'            : '\\U000022a3',\n        '\\\\<surd>'                 : '\\U0000221a',\n        '\\\\<le>'                   : '\\U00002264',\n        '\\\\<ge>'                   : '\\U00002265',\n        '\\\\<lless>'                : '\\U0000226a',\n        '\\\\<ggreater>'             : '\\U0000226b',\n        '\\\\<lesssim>'              : '\\U00002272',\n        '\\\\<greatersim>'           : '\\U00002273',\n        '\\\\<lessapprox>'           : '\\U00002a85',\n        '\\\\<greaterapprox>'        : '\\U00002a86',\n        '\\\\<in>'                   : '\\U00002208',\n        '\\\\<notin>'                : '\\U00002209',\n        '\\\\<subset>'               : '\\U00002282',\n        '\\\\<supset>'               : '\\U00002283',\n        '\\\\<subseteq>'             : '\\U00002286',\n        '\\\\<supseteq>'             : '\\U00002287',\n        '\\\\<sqsubset>'             : '\\U0000228f',\n        '\\\\<sqsupset>'             : '\\U00002290',\n        '\\\\<sqsubseteq>'           : '\\U00002291',\n        '\\\\<sqsupseteq>'           : '\\U00002292',\n        '\\\\<inter>'                : '\\U00002229',\n        '\\\\<Inter>'                : '\\U000022c2',\n        '\\\\<union>'                : '\\U0000222a',\n        '\\\\<Union>'                : '\\U000022c3',\n        '\\\\<squnion>'              : '\\U00002294',\n        '\\\\<Squnion>'              : '\\U00002a06',\n        '\\\\<sqinter>'              : '\\U00002293',\n        '\\\\<Sqinter>'              : '\\U00002a05',\n        '\\\\<setminus>'             : '\\U00002216',\n        '\\\\<propto>'               : '\\U0000221d',\n        '\\\\<uplus>'                : '\\U0000228e',\n        '\\\\<Uplus>'                : '\\U00002a04',\n        '\\\\<noteq>'                : '\\U00002260',\n        '\\\\<sim>'                  : '\\U0000223c',\n        '\\\\<doteq>'                : '\\U00002250',\n        '\\\\<simeq>'                : '\\U00002243',\n        '\\\\<approx>'               : '\\U00002248',\n        '\\\\<asymp>'                : '\\U0000224d',\n        '\\\\<cong>'                 : '\\U00002245',\n        '\\\\<smile>'                : '\\U00002323',\n        '\\\\<equiv>'                : '\\U00002261',\n        '\\\\<frown>'                : '\\U00002322',\n        '\\\\<Join>'                 : '\\U000022c8',\n        '\\\\<bowtie>'               : '\\U00002a1d',\n        '\\\\<prec>'                 : '\\U0000227a',\n        '\\\\<succ>'                 : '\\U0000227b',\n        '\\\\<preceq>'               : '\\U0000227c',\n        '\\\\<succeq>'               : '\\U0000227d',\n        '\\\\<parallel>'             : '\\U00002225',\n        '\\\\<bar>'                  : '\\U000000a6',\n        '\\\\<plusminus>'            : '\\U000000b1',\n        '\\\\<minusplus>'            : '\\U00002213',\n        '\\\\<times>'                : '\\U000000d7',\n        '\\\\<div>'                  : '\\U000000f7',\n        '\\\\<cdot>'                 : '\\U000022c5',\n        '\\\\<star>'                 : '\\U000022c6',\n        '\\\\<bullet>'               : '\\U00002219',\n        '\\\\<circ>'                 : '\\U00002218',\n        '\\\\<dagger>'               : '\\U00002020',\n        '\\\\<ddagger>'              : '\\U00002021',\n        '\\\\<lhd>'                  : '\\U000022b2',\n        '\\\\<rhd>'                  : '\\U000022b3',\n        '\\\\<unlhd>'                : '\\U000022b4',\n        '\\\\<unrhd>'                : '\\U000022b5',\n        '\\\\<triangleleft>'         : '\\U000025c3',\n        '\\\\<triangleright>'        : '\\U000025b9',\n        '\\\\<triangle>'             : '\\U000025b3',\n        '\\\\<triangleq>'            : '\\U0000225c',\n        '\\\\<oplus>'                : '\\U00002295',\n        '\\\\<Oplus>'                : '\\U00002a01',\n        '\\\\<otimes>'               : '\\U00002297',\n        '\\\\<Otimes>'               : '\\U00002a02',\n        '\\\\<odot>'                 : '\\U00002299',\n        '\\\\<Odot>'                 : '\\U00002a00',\n        '\\\\<ominus>'               : '\\U00002296',\n        '\\\\<oslash>'               : '\\U00002298',\n        '\\\\<dots>'                 : '\\U00002026',\n        '\\\\<cdots>'                : '\\U000022ef',\n        '\\\\<Sum>'                  : '\\U00002211',\n        '\\\\<Prod>'                 : '\\U0000220f',\n        '\\\\<Coprod>'               : '\\U00002210',\n        '\\\\<infinity>'             : '\\U0000221e',\n        '\\\\<integral>'             : '\\U0000222b',\n        '\\\\<ointegral>'            : '\\U0000222e',\n        '\\\\<clubsuit>'             : '\\U00002663',\n        '\\\\<diamondsuit>'          : '\\U00002662',\n        '\\\\<heartsuit>'            : '\\U00002661',\n        '\\\\<spadesuit>'            : '\\U00002660',\n        '\\\\<aleph>'                : '\\U00002135',\n        '\\\\<emptyset>'             : '\\U00002205',\n        '\\\\<nabla>'                : '\\U00002207',\n        '\\\\<partial>'              : '\\U00002202',\n        '\\\\<flat>'                 : '\\U0000266d',\n        '\\\\<natural>'              : '\\U0000266e',\n        '\\\\<sharp>'                : '\\U0000266f',\n        '\\\\<angle>'                : '\\U00002220',\n        '\\\\<copyright>'            : '\\U000000a9',\n        '\\\\<registered>'           : '\\U000000ae',\n        '\\\\<hyphen>'               : '\\U000000ad',\n        '\\\\<inverse>'              : '\\U000000af',\n        '\\\\<onequarter>'           : '\\U000000bc',\n        '\\\\<onehalf>'              : '\\U000000bd',\n        '\\\\<threequarters>'        : '\\U000000be',\n        '\\\\<ordfeminine>'          : '\\U000000aa',\n        '\\\\<ordmasculine>'         : '\\U000000ba',\n        '\\\\<section>'              : '\\U000000a7',\n        '\\\\<paragraph>'            : '\\U000000b6',\n        '\\\\<exclamdown>'           : '\\U000000a1',\n        '\\\\<questiondown>'         : '\\U000000bf',\n        '\\\\<euro>'                 : '\\U000020ac',\n        '\\\\<pounds>'               : '\\U000000a3',\n        '\\\\<yen>'                  : '\\U000000a5',\n        '\\\\<cent>'                 : '\\U000000a2',\n        '\\\\<currency>'             : '\\U000000a4',\n        '\\\\<degree>'               : '\\U000000b0',\n        '\\\\<amalg>'                : '\\U00002a3f',\n        '\\\\<mho>'                  : '\\U00002127',\n        '\\\\<lozenge>'              : '\\U000025ca',\n        '\\\\<wp>'                   : '\\U00002118',\n        '\\\\<wrong>'                : '\\U00002240',\n        '\\\\<struct>'               : '\\U000022c4',\n        '\\\\<acute>'                : '\\U000000b4',\n        '\\\\<index>'                : '\\U00000131',\n        '\\\\<dieresis>'             : '\\U000000a8',\n        '\\\\<cedilla>'              : '\\U000000b8',\n        '\\\\<hungarumlaut>'         : '\\U000002dd',\n        '\\\\<some>'                 : '\\U000003f5',\n        '\\\\<newline>'              : '\\U000023ce',\n        '\\\\<open>'                 : '\\U00002039',\n        '\\\\<close>'                : '\\U0000203a',\n        '\\\\<here>'                 : '\\U00002302',\n        '\\\\<^sub>'                 : '\\U000021e9',\n        '\\\\<^sup>'                 : '\\U000021e7',\n        '\\\\<^bold>'                : '\\U00002759',\n        '\\\\<^bsub>'                : '\\U000021d8',\n        '\\\\<^esub>'                : '\\U000021d9',\n        '\\\\<^bsup>'                : '\\U000021d7',\n        '\\\\<^esup>'                : '\\U000021d6',\n    }\n\n    lang_map = {'isabelle' : isabelle_symbols, 'latex' : latex_symbols}\n\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n        lang = get_choice_opt(options, 'lang',\n                              ['isabelle', 'latex'], 'isabelle')\n        self.symbols = self.lang_map[lang]\n\n    def filter(self, lexer, stream):\n        for ttype, value in stream:\n            if value in self.symbols:\n                yield ttype, self.symbols[value]\n            else:\n                yield ttype, value\n\n\nclass KeywordCaseFilter(Filter):\n    \"\"\"Convert keywords to lowercase or uppercase or capitalize them, which\n    means first letter uppercase, rest lowercase.\n\n    This can be useful e.g. if you highlight Pascal code and want to adapt the\n    code to your styleguide.\n\n    Options accepted:\n\n    `case` : string\n       The casing to convert keywords to. Must be one of ``'lower'``,\n       ``'upper'`` or ``'capitalize'``.  The default is ``'lower'``.\n    \"\"\"\n\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n        case = get_choice_opt(options, 'case',\n                              ['lower', 'upper', 'capitalize'], 'lower')\n        self.convert = getattr(str, case)\n\n    def filter(self, lexer, stream):\n        for ttype, value in stream:\n            if ttype in Keyword:\n                yield ttype, self.convert(value)\n            else:\n                yield ttype, value\n\n\nclass NameHighlightFilter(Filter):\n    \"\"\"Highlight a normal Name (and Name.*) token with a different token type.\n\n    Example::\n\n        filter = NameHighlightFilter(\n            names=['foo', 'bar', 'baz'],\n            tokentype=Name.Function,\n        )\n\n    This would highlight the names \"foo\", \"bar\" and \"baz\"\n    as functions. `Name.Function` is the default token type.\n\n    Options accepted:\n\n    `names` : list of strings\n      A list of names that should be given the different token type.\n      There is no default.\n    `tokentype` : TokenType or string\n      A token type or a string containing a token type name that is\n      used for highlighting the strings in `names`.  The default is\n      `Name.Function`.\n    \"\"\"\n\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n        self.names = set(get_list_opt(options, 'names', []))\n        tokentype = options.get('tokentype')\n        if tokentype:\n            self.tokentype = string_to_tokentype(tokentype)\n        else:\n            self.tokentype = Name.Function\n\n    def filter(self, lexer, stream):\n        for ttype, value in stream:\n            if ttype in Name and value in self.names:\n                yield self.tokentype, value\n            else:\n                yield ttype, value\n\n\nclass ErrorToken(Exception):\n    pass\n\n\nclass RaiseOnErrorTokenFilter(Filter):\n    \"\"\"Raise an exception when the lexer generates an error token.\n\n    Options accepted:\n\n    `excclass` : Exception class\n      The exception class to raise.\n      The default is `pygments.filters.ErrorToken`.\n\n    .. versionadded:: 0.8\n    \"\"\"\n\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n        self.exception = options.get('excclass', ErrorToken)\n        try:\n            # issubclass() will raise TypeError if first argument is not a class\n            if not issubclass(self.exception, Exception):\n                raise TypeError\n        except TypeError:\n            raise OptionError('excclass option is not an exception class')\n\n    def filter(self, lexer, stream):\n        for ttype, value in stream:\n            if ttype is Error:\n                raise self.exception(value)\n            yield ttype, value\n\n\nclass VisibleWhitespaceFilter(Filter):\n    \"\"\"Convert tabs, newlines and/or spaces to visible characters.\n\n    Options accepted:\n\n    `spaces` : string or bool\n      If this is a one-character string, spaces will be replaces by this string.\n      If it is another true value, spaces will be replaced by ``·`` (unicode\n      MIDDLE DOT).  If it is a false value, spaces will not be replaced.  The\n      default is ``False``.\n    `tabs` : string or bool\n      The same as for `spaces`, but the default replacement character is ``»``\n      (unicode RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK).  The default value\n      is ``False``.  Note: this will not work if the `tabsize` option for the\n      lexer is nonzero, as tabs will already have been expanded then.\n    `tabsize` : int\n      If tabs are to be replaced by this filter (see the `tabs` option), this\n      is the total number of characters that a tab should be expanded to.\n      The default is ``8``.\n    `newlines` : string or bool\n      The same as for `spaces`, but the default replacement character is ``¶``\n      (unicode PILCROW SIGN).  The default value is ``False``.\n    `wstokentype` : bool\n      If true, give whitespace the special `Whitespace` token type.  This allows\n      styling the visible whitespace differently (e.g. greyed out), but it can\n      disrupt background colors.  The default is ``True``.\n\n    .. versionadded:: 0.8\n    \"\"\"\n\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n        for name, default in [('spaces',   '·'),\n                              ('tabs',     '»'),\n                              ('newlines', '¶')]:\n            opt = options.get(name, False)\n            if isinstance(opt, str) and len(opt) == 1:\n                setattr(self, name, opt)\n            else:\n                setattr(self, name, (opt and default or ''))\n        tabsize = get_int_opt(options, 'tabsize', 8)\n        if self.tabs:\n            self.tabs += ' ' * (tabsize - 1)\n        if self.newlines:\n            self.newlines += '\\n'\n        self.wstt = get_bool_opt(options, 'wstokentype', True)\n\n    def filter(self, lexer, stream):\n        if self.wstt:\n            spaces = self.spaces or ' '\n            tabs = self.tabs or '\\t'\n            newlines = self.newlines or '\\n'\n            regex = re.compile(r'\\s')\n\n            def replacefunc(wschar):\n                if wschar == ' ':\n                    return spaces\n                elif wschar == '\\t':\n                    return tabs\n                elif wschar == '\\n':\n                    return newlines\n                return wschar\n\n            for ttype, value in stream:\n                yield from _replace_special(ttype, value, regex, Whitespace,\n                                            replacefunc)\n        else:\n            spaces, tabs, newlines = self.spaces, self.tabs, self.newlines\n            # simpler processing\n            for ttype, value in stream:\n                if spaces:\n                    value = value.replace(' ', spaces)\n                if tabs:\n                    value = value.replace('\\t', tabs)\n                if newlines:\n                    value = value.replace('\\n', newlines)\n                yield ttype, value\n\n\nclass GobbleFilter(Filter):\n    \"\"\"Gobbles source code lines (eats initial characters).\n\n    This filter drops the first ``n`` characters off every line of code.  This\n    may be useful when the source code fed to the lexer is indented by a fixed\n    amount of space that isn't desired in the output.\n\n    Options accepted:\n\n    `n` : int\n       The number of characters to gobble.\n\n    .. versionadded:: 1.2\n    \"\"\"\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n        self.n = get_int_opt(options, 'n', 0)\n\n    def gobble(self, value, left):\n        if left < len(value):\n            return value[left:], 0\n        else:\n            return '', left - len(value)\n\n    def filter(self, lexer, stream):\n        n = self.n\n        left = n  # How many characters left to gobble.\n        for ttype, value in stream:\n            # Remove ``left`` tokens from first line, ``n`` from all others.\n            parts = value.split('\\n')\n            (parts[0], left) = self.gobble(parts[0], left)\n            for i in range(1, len(parts)):\n                (parts[i], left) = self.gobble(parts[i], n)\n            value = '\\n'.join(parts)\n\n            if value != '':\n                yield ttype, value\n\n\nclass TokenMergeFilter(Filter):\n    \"\"\"Merges consecutive tokens with the same token type in the output\n    stream of a lexer.\n\n    .. versionadded:: 1.2\n    \"\"\"\n    def __init__(self, **options):\n        Filter.__init__(self, **options)\n\n    def filter(self, lexer, stream):\n        current_type = None\n        current_value = None\n        for ttype, value in stream:\n            if ttype is current_type:\n                current_value += value\n            else:\n                if current_type is not None:\n                    yield current_type, current_value\n                current_type = ttype\n                current_value = value\n        if current_type is not None:\n            yield current_type, current_value\n\n\nFILTERS = {\n    'codetagify':     CodeTagFilter,\n    'keywordcase':    KeywordCaseFilter,\n    'highlight':      NameHighlightFilter,\n    'raiseonerror':   RaiseOnErrorTokenFilter,\n    'whitespace':     VisibleWhitespaceFilter,\n    'gobble':         GobbleFilter,\n    'tokenmerge':     TokenMergeFilter,\n    'symbols':        SymbolFilter,\n}\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatter.py",
    "content": "\"\"\"\n    pygments.formatter\n    ~~~~~~~~~~~~~~~~~~\n\n    Base formatter class.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport codecs\n\nfrom pip._vendor.pygments.util import get_bool_opt\nfrom pip._vendor.pygments.styles import get_style_by_name\n\n__all__ = ['Formatter']\n\n\ndef _lookup_style(style):\n    if isinstance(style, str):\n        return get_style_by_name(style)\n    return style\n\n\nclass Formatter:\n    \"\"\"\n    Converts a token stream to text.\n\n    Options accepted:\n\n    ``style``\n        The style to use, can be a string or a Style subclass\n        (default: \"default\"). Not used by e.g. the\n        TerminalFormatter.\n    ``full``\n        Tells the formatter to output a \"full\" document, i.e.\n        a complete self-contained document. This doesn't have\n        any effect for some formatters (default: false).\n    ``title``\n        If ``full`` is true, the title that should be used to\n        caption the document (default: '').\n    ``encoding``\n        If given, must be an encoding name. This will be used to\n        convert the Unicode token strings to byte strings in the\n        output. If it is \"\" or None, Unicode strings will be written\n        to the output file, which most file-like objects do not\n        support (default: None).\n    ``outencoding``\n        Overrides ``encoding`` if given.\n    \"\"\"\n\n    #: Name of the formatter\n    name = None\n\n    #: Shortcuts for the formatter\n    aliases = []\n\n    #: fn match rules\n    filenames = []\n\n    #: If True, this formatter outputs Unicode strings when no encoding\n    #: option is given.\n    unicodeoutput = True\n\n    def __init__(self, **options):\n        self.style = _lookup_style(options.get('style', 'default'))\n        self.full = get_bool_opt(options, 'full', False)\n        self.title = options.get('title', '')\n        self.encoding = options.get('encoding', None) or None\n        if self.encoding in ('guess', 'chardet'):\n            # can happen for e.g. pygmentize -O encoding=guess\n            self.encoding = 'utf-8'\n        self.encoding = options.get('outencoding') or self.encoding\n        self.options = options\n\n    def get_style_defs(self, arg=''):\n        \"\"\"\n        Return the style definitions for the current style as a string.\n\n        ``arg`` is an additional argument whose meaning depends on the\n        formatter used. Note that ``arg`` can also be a list or tuple\n        for some formatters like the html formatter.\n        \"\"\"\n        return ''\n\n    def format(self, tokensource, outfile):\n        \"\"\"\n        Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``\n        tuples and write it into ``outfile``.\n        \"\"\"\n        if self.encoding:\n            # wrap the outfile in a StreamWriter\n            outfile = codecs.lookup(self.encoding)[3](outfile)\n        return self.format_unencoded(tokensource, outfile)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatters/__init__.py",
    "content": "\"\"\"\n    pygments.formatters\n    ~~~~~~~~~~~~~~~~~~~\n\n    Pygments formatters.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\nimport sys\nimport types\nfrom fnmatch import fnmatch\nfrom os.path import basename\n\nfrom pip._vendor.pygments.formatters._mapping import FORMATTERS\nfrom pip._vendor.pygments.plugin import find_plugin_formatters\nfrom pip._vendor.pygments.util import ClassNotFound\n\n__all__ = ['get_formatter_by_name', 'get_formatter_for_filename',\n           'get_all_formatters', 'load_formatter_from_file'] + list(FORMATTERS)\n\n_formatter_cache = {}  # classes by name\n\ndef _load_formatters(module_name):\n    \"\"\"Load a formatter (and all others in the module too).\"\"\"\n    mod = __import__(module_name, None, None, ['__all__'])\n    for formatter_name in mod.__all__:\n        cls = getattr(mod, formatter_name)\n        _formatter_cache[cls.name] = cls\n\n\ndef get_all_formatters():\n    \"\"\"Return a generator for all formatter classes.\"\"\"\n    # NB: this returns formatter classes, not info like get_all_lexers().\n    for info in FORMATTERS.values():\n        if info[1] not in _formatter_cache:\n            _load_formatters(info[0])\n        yield _formatter_cache[info[1]]\n    for _, formatter in find_plugin_formatters():\n        yield formatter\n\n\ndef find_formatter_class(alias):\n    \"\"\"Lookup a formatter by alias.\n\n    Returns None if not found.\n    \"\"\"\n    for module_name, name, aliases, _, _ in FORMATTERS.values():\n        if alias in aliases:\n            if name not in _formatter_cache:\n                _load_formatters(module_name)\n            return _formatter_cache[name]\n    for _, cls in find_plugin_formatters():\n        if alias in cls.aliases:\n            return cls\n\n\ndef get_formatter_by_name(_alias, **options):\n    \"\"\"Lookup and instantiate a formatter by alias.\n\n    Raises ClassNotFound if not found.\n    \"\"\"\n    cls = find_formatter_class(_alias)\n    if cls is None:\n        raise ClassNotFound(\"no formatter found for name %r\" % _alias)\n    return cls(**options)\n\n\ndef load_formatter_from_file(filename, formattername=\"CustomFormatter\",\n                             **options):\n    \"\"\"Load a formatter from a file.\n\n    This method expects a file located relative to the current working\n    directory, which contains a class named CustomFormatter. By default,\n    it expects the Formatter to be named CustomFormatter; you can specify\n    your own class name as the second argument to this function.\n\n    Users should be very careful with the input, because this method\n    is equivalent to running eval on the input file.\n\n    Raises ClassNotFound if there are any problems importing the Formatter.\n\n    .. versionadded:: 2.2\n    \"\"\"\n    try:\n        # This empty dict will contain the namespace for the exec'd file\n        custom_namespace = {}\n        with open(filename, 'rb') as f:\n            exec(f.read(), custom_namespace)\n        # Retrieve the class `formattername` from that namespace\n        if formattername not in custom_namespace:\n            raise ClassNotFound('no valid %s class found in %s' %\n                                (formattername, filename))\n        formatter_class = custom_namespace[formattername]\n        # And finally instantiate it with the options\n        return formatter_class(**options)\n    except OSError as err:\n        raise ClassNotFound('cannot read %s: %s' % (filename, err))\n    except ClassNotFound:\n        raise\n    except Exception as err:\n        raise ClassNotFound('error when loading custom formatter: %s' % err)\n\n\ndef get_formatter_for_filename(fn, **options):\n    \"\"\"Lookup and instantiate a formatter by filename pattern.\n\n    Raises ClassNotFound if not found.\n    \"\"\"\n    fn = basename(fn)\n    for modname, name, _, filenames, _ in FORMATTERS.values():\n        for filename in filenames:\n            if fnmatch(fn, filename):\n                if name not in _formatter_cache:\n                    _load_formatters(modname)\n                return _formatter_cache[name](**options)\n    for cls in find_plugin_formatters():\n        for filename in cls.filenames:\n            if fnmatch(fn, filename):\n                return cls(**options)\n    raise ClassNotFound(\"no formatter found for file name %r\" % fn)\n\n\nclass _automodule(types.ModuleType):\n    \"\"\"Automatically import formatters.\"\"\"\n\n    def __getattr__(self, name):\n        info = FORMATTERS.get(name)\n        if info:\n            _load_formatters(info[0])\n            cls = _formatter_cache[info[1]]\n            setattr(self, name, cls)\n            return cls\n        raise AttributeError(name)\n\n\noldmod = sys.modules[__name__]\nnewmod = _automodule(__name__)\nnewmod.__dict__.update(oldmod.__dict__)\nsys.modules[__name__] = newmod\ndel newmod.newmod, newmod.oldmod, newmod.sys, newmod.types\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatters/_mapping.py",
    "content": "# Automatically generated by scripts/gen_mapfiles.py.\n# DO NOT EDIT BY HAND; run `make mapfiles` instead.\n\nFORMATTERS = {\n    'BBCodeFormatter': ('pygments.formatters.bbcode', 'BBCode', ('bbcode', 'bb'), (), 'Format tokens with BBcodes. These formatting codes are used by many bulletin boards, so you can highlight your sourcecode with pygments before posting it there.'),\n    'BmpImageFormatter': ('pygments.formatters.img', 'img_bmp', ('bmp', 'bitmap'), ('*.bmp',), 'Create a bitmap image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),\n    'GifImageFormatter': ('pygments.formatters.img', 'img_gif', ('gif',), ('*.gif',), 'Create a GIF image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),\n    'GroffFormatter': ('pygments.formatters.groff', 'groff', ('groff', 'troff', 'roff'), (), 'Format tokens with groff escapes to change their color and font style.'),\n    'HtmlFormatter': ('pygments.formatters.html', 'HTML', ('html',), ('*.html', '*.htm'), \"Format tokens as HTML 4 ``<span>`` tags within a ``<pre>`` tag, wrapped in a ``<div>`` tag. The ``<div>``'s CSS class can be set by the `cssclass` option.\"),\n    'IRCFormatter': ('pygments.formatters.irc', 'IRC', ('irc', 'IRC'), (), 'Format tokens with IRC color sequences'),\n    'ImageFormatter': ('pygments.formatters.img', 'img', ('img', 'IMG', 'png'), ('*.png',), 'Create a PNG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),\n    'JpgImageFormatter': ('pygments.formatters.img', 'img_jpg', ('jpg', 'jpeg'), ('*.jpg',), 'Create a JPEG image from source code. This uses the Python Imaging Library to generate a pixmap from the source code.'),\n    'LatexFormatter': ('pygments.formatters.latex', 'LaTeX', ('latex', 'tex'), ('*.tex',), 'Format tokens as LaTeX code. This needs the `fancyvrb` and `color` standard packages.'),\n    'NullFormatter': ('pygments.formatters.other', 'Text only', ('text', 'null'), ('*.txt',), 'Output the text unchanged without any formatting.'),\n    'PangoMarkupFormatter': ('pygments.formatters.pangomarkup', 'Pango Markup', ('pango', 'pangomarkup'), (), 'Format tokens as Pango Markup code. It can then be rendered to an SVG.'),\n    'RawTokenFormatter': ('pygments.formatters.other', 'Raw tokens', ('raw', 'tokens'), ('*.raw',), 'Format tokens as a raw representation for storing token streams.'),\n    'RtfFormatter': ('pygments.formatters.rtf', 'RTF', ('rtf',), ('*.rtf',), 'Format tokens as RTF markup. This formatter automatically outputs full RTF documents with color information and other useful stuff. Perfect for Copy and Paste into Microsoft(R) Word(R) documents.'),\n    'SvgFormatter': ('pygments.formatters.svg', 'SVG', ('svg',), ('*.svg',), 'Format tokens as an SVG graphics file.  This formatter is still experimental. Each line of code is a ``<text>`` element with explicit ``x`` and ``y`` coordinates containing ``<tspan>`` elements with the individual token styles.'),\n    'Terminal256Formatter': ('pygments.formatters.terminal256', 'Terminal256', ('terminal256', 'console256', '256'), (), 'Format tokens with ANSI color sequences, for output in a 256-color terminal or console.  Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'),\n    'TerminalFormatter': ('pygments.formatters.terminal', 'Terminal', ('terminal', 'console'), (), 'Format tokens with ANSI color sequences, for output in a text console. Color sequences are terminated at newlines, so that paging the output works correctly.'),\n    'TerminalTrueColorFormatter': ('pygments.formatters.terminal256', 'TerminalTrueColor', ('terminal16m', 'console16m', '16m'), (), 'Format tokens with ANSI color sequences, for output in a true-color terminal or console.  Like in `TerminalFormatter` color sequences are terminated at newlines, so that paging the output works correctly.'),\n    'TestcaseFormatter': ('pygments.formatters.other', 'Testcase', ('testcase',), (), 'Format tokens as appropriate for a new testcase.'),\n}\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatters/bbcode.py",
    "content": "\"\"\"\n    pygments.formatters.bbcode\n    ~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    BBcode formatter.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\n\nfrom pip._vendor.pygments.formatter import Formatter\nfrom pip._vendor.pygments.util import get_bool_opt\n\n__all__ = ['BBCodeFormatter']\n\n\nclass BBCodeFormatter(Formatter):\n    \"\"\"\n    Format tokens with BBcodes. These formatting codes are used by many\n    bulletin boards, so you can highlight your sourcecode with pygments before\n    posting it there.\n\n    This formatter has no support for background colors and borders, as there\n    are no common BBcode tags for that.\n\n    Some board systems (e.g. phpBB) don't support colors in their [code] tag,\n    so you can't use the highlighting together with that tag.\n    Text in a [code] tag usually is shown with a monospace font (which this\n    formatter can do with the ``monofont`` option) and no spaces (which you\n    need for indentation) are removed.\n\n    Additional options accepted:\n\n    `style`\n        The style to use, can be a string or a Style subclass (default:\n        ``'default'``).\n\n    `codetag`\n        If set to true, put the output into ``[code]`` tags (default:\n        ``false``)\n\n    `monofont`\n        If set to true, add a tag to show the code with a monospace font\n        (default: ``false``).\n    \"\"\"\n    name = 'BBCode'\n    aliases = ['bbcode', 'bb']\n    filenames = []\n\n    def __init__(self, **options):\n        Formatter.__init__(self, **options)\n        self._code = get_bool_opt(options, 'codetag', False)\n        self._mono = get_bool_opt(options, 'monofont', False)\n\n        self.styles = {}\n        self._make_styles()\n\n    def _make_styles(self):\n        for ttype, ndef in self.style:\n            start = end = ''\n            if ndef['color']:\n                start += '[color=#%s]' % ndef['color']\n                end = '[/color]' + end\n            if ndef['bold']:\n                start += '[b]'\n                end = '[/b]' + end\n            if ndef['italic']:\n                start += '[i]'\n                end = '[/i]' + end\n            if ndef['underline']:\n                start += '[u]'\n                end = '[/u]' + end\n            # there are no common BBcodes for background-color and border\n\n            self.styles[ttype] = start, end\n\n    def format_unencoded(self, tokensource, outfile):\n        if self._code:\n            outfile.write('[code]')\n        if self._mono:\n            outfile.write('[font=monospace]')\n\n        lastval = ''\n        lasttype = None\n\n        for ttype, value in tokensource:\n            while ttype not in self.styles:\n                ttype = ttype.parent\n            if ttype == lasttype:\n                lastval += value\n            else:\n                if lastval:\n                    start, end = self.styles[lasttype]\n                    outfile.write(''.join((start, lastval, end)))\n                lastval = value\n                lasttype = ttype\n\n        if lastval:\n            start, end = self.styles[lasttype]\n            outfile.write(''.join((start, lastval, end)))\n\n        if self._mono:\n            outfile.write('[/font]')\n        if self._code:\n            outfile.write('[/code]')\n        if self._code or self._mono:\n            outfile.write('\\n')\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatters/groff.py",
    "content": "\"\"\"\n    pygments.formatters.groff\n    ~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    Formatter for groff output.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport math\nfrom pip._vendor.pygments.formatter import Formatter\nfrom pip._vendor.pygments.util import get_bool_opt, get_int_opt\n\n__all__ = ['GroffFormatter']\n\n\nclass GroffFormatter(Formatter):\n    \"\"\"\n    Format tokens with groff escapes to change their color and font style.\n\n    .. versionadded:: 2.11\n\n    Additional options accepted:\n\n    `style`\n        The style to use, can be a string or a Style subclass (default:\n        ``'default'``).\n\n    `monospaced`\n        If set to true, monospace font will be used (default: ``true``).\n\n    `linenos`\n        If set to true, print the line numbers (default: ``false``).\n\n    `wrap`\n        Wrap lines to the specified number of characters. Disabled if set to 0\n        (default: ``0``).\n    \"\"\"\n\n    name = 'groff'\n    aliases = ['groff','troff','roff']\n    filenames = []\n\n    def __init__(self, **options):\n        Formatter.__init__(self, **options)\n\n        self.monospaced = get_bool_opt(options, 'monospaced', True)\n        self.linenos = get_bool_opt(options, 'linenos', False)\n        self._lineno = 0\n        self.wrap = get_int_opt(options, 'wrap', 0)\n        self._linelen = 0\n\n        self.styles = {}\n        self._make_styles()\n\n\n    def _make_styles(self):\n        regular = '\\\\f[CR]' if self.monospaced else '\\\\f[R]'\n        bold = '\\\\f[CB]' if self.monospaced else '\\\\f[B]'\n        italic = '\\\\f[CI]' if self.monospaced else '\\\\f[I]'\n\n        for ttype, ndef in self.style:\n            start = end = ''\n            if ndef['color']:\n                start += '\\\\m[%s]' % ndef['color']\n                end = '\\\\m[]' + end\n            if ndef['bold']:\n                start += bold\n                end = regular + end\n            if ndef['italic']:\n                start += italic\n                end = regular + end\n            if ndef['bgcolor']:\n                start += '\\\\M[%s]' % ndef['bgcolor']\n                end = '\\\\M[]' + end\n\n            self.styles[ttype] = start, end\n\n\n    def _define_colors(self, outfile):\n        colors = set()\n        for _, ndef in self.style:\n            if ndef['color'] is not None:\n                colors.add(ndef['color'])\n\n        for color in colors:\n            outfile.write('.defcolor ' + color + ' rgb #' + color + '\\n')\n\n\n    def _write_lineno(self, outfile):\n        self._lineno += 1\n        outfile.write(\"%s% 4d \" % (self._lineno != 1 and '\\n' or '', self._lineno))\n\n\n    def _wrap_line(self, line):\n        length = len(line.rstrip('\\n'))\n        space = '     ' if self.linenos else ''\n        newline = ''\n\n        if length > self.wrap:\n            for i in range(0, math.floor(length / self.wrap)):\n                chunk = line[i*self.wrap:i*self.wrap+self.wrap]\n                newline += (chunk + '\\n' + space)\n            remainder = length % self.wrap\n            if remainder > 0:\n                newline += line[-remainder-1:]\n                self._linelen = remainder\n        elif self._linelen + length > self.wrap:\n            newline = ('\\n' + space) + line\n            self._linelen = length\n        else:\n            newline = line\n            self._linelen += length\n\n        return newline\n\n\n    def _escape_chars(self, text):\n        text = text.replace('\\\\', '\\\\[u005C]'). \\\n                    replace('.', '\\\\[char46]'). \\\n                    replace('\\'', '\\\\[u0027]'). \\\n                    replace('`', '\\\\[u0060]'). \\\n                    replace('~', '\\\\[u007E]')\n        copy = text\n\n        for char in copy:\n            if len(char) != len(char.encode()):\n                uni = char.encode('unicode_escape') \\\n                    .decode()[1:] \\\n                    .replace('x', 'u00') \\\n                    .upper()\n                text = text.replace(char, '\\\\[u' + uni[1:] + ']')\n\n        return text\n\n\n    def format_unencoded(self, tokensource, outfile):\n        self._define_colors(outfile)\n\n        outfile.write('.nf\\n\\\\f[CR]\\n')\n\n        if self.linenos:\n            self._write_lineno(outfile)\n\n        for ttype, value in tokensource:\n            while ttype not in self.styles:\n                ttype = ttype.parent\n            start, end = self.styles[ttype]\n\n            for line in value.splitlines(True):\n                if self.wrap > 0:\n                    line = self._wrap_line(line)\n\n                if start and end:\n                    text = self._escape_chars(line.rstrip('\\n'))\n                    if text != '':\n                        outfile.write(''.join((start, text, end)))\n                else:\n                    outfile.write(self._escape_chars(line.rstrip('\\n')))\n\n                if line.endswith('\\n'):\n                    if self.linenos:\n                        self._write_lineno(outfile)\n                        self._linelen = 0\n                    else:\n                        outfile.write('\\n')\n                        self._linelen = 0\n\n        outfile.write('\\n.fi')\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatters/html.py",
    "content": "\"\"\"\n    pygments.formatters.html\n    ~~~~~~~~~~~~~~~~~~~~~~~~\n\n    Formatter for HTML output.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport functools\nimport os\nimport sys\nimport os.path\nfrom io import StringIO\n\nfrom pip._vendor.pygments.formatter import Formatter\nfrom pip._vendor.pygments.token import Token, Text, STANDARD_TYPES\nfrom pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt\n\ntry:\n    import ctags\nexcept ImportError:\n    ctags = None\n\n__all__ = ['HtmlFormatter']\n\n\n_escape_html_table = {\n    ord('&'): '&amp;',\n    ord('<'): '&lt;',\n    ord('>'): '&gt;',\n    ord('\"'): '&quot;',\n    ord(\"'\"): '&#39;',\n}\n\n\ndef escape_html(text, table=_escape_html_table):\n    \"\"\"Escape &, <, > as well as single and double quotes for HTML.\"\"\"\n    return text.translate(table)\n\n\ndef webify(color):\n    if color.startswith('calc') or color.startswith('var'):\n        return color\n    else:\n        return '#' + color\n\n\ndef _get_ttype_class(ttype):\n    fname = STANDARD_TYPES.get(ttype)\n    if fname:\n        return fname\n    aname = ''\n    while fname is None:\n        aname = '-' + ttype[-1] + aname\n        ttype = ttype.parent\n        fname = STANDARD_TYPES.get(ttype)\n    return fname + aname\n\n\nCSSFILE_TEMPLATE = '''\\\n/*\ngenerated by Pygments <https://pygments.org/>\nCopyright 2006-2022 by the Pygments team.\nLicensed under the BSD license, see LICENSE for details.\n*/\n%(styledefs)s\n'''\n\nDOC_HEADER = '''\\\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n   \"http://www.w3.org/TR/html4/strict.dtd\">\n<!--\ngenerated by Pygments <https://pygments.org/>\nCopyright 2006-2022 by the Pygments team.\nLicensed under the BSD license, see LICENSE for details.\n-->\n<html>\n<head>\n  <title>%(title)s</title>\n  <meta http-equiv=\"content-type\" content=\"text/html; charset=%(encoding)s\">\n  <style type=\"text/css\">\n''' + CSSFILE_TEMPLATE + '''\n  </style>\n</head>\n<body>\n<h2>%(title)s</h2>\n\n'''\n\nDOC_HEADER_EXTERNALCSS = '''\\\n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n   \"http://www.w3.org/TR/html4/strict.dtd\">\n\n<html>\n<head>\n  <title>%(title)s</title>\n  <meta http-equiv=\"content-type\" content=\"text/html; charset=%(encoding)s\">\n  <link rel=\"stylesheet\" href=\"%(cssfile)s\" type=\"text/css\">\n</head>\n<body>\n<h2>%(title)s</h2>\n\n'''\n\nDOC_FOOTER = '''\\\n</body>\n</html>\n'''\n\n\nclass HtmlFormatter(Formatter):\n    r\"\"\"\n    Format tokens as HTML 4 ``<span>`` tags within a ``<pre>`` tag, wrapped\n    in a ``<div>`` tag. The ``<div>``'s CSS class can be set by the `cssclass`\n    option.\n\n    If the `linenos` option is set to ``\"table\"``, the ``<pre>`` is\n    additionally wrapped inside a ``<table>`` which has one row and two\n    cells: one containing the line numbers and one containing the code.\n    Example:\n\n    .. sourcecode:: html\n\n        <div class=\"highlight\" >\n        <table><tr>\n          <td class=\"linenos\" title=\"click to toggle\"\n            onclick=\"with (this.firstChild.style)\n                     { display = (display == '') ? 'none' : '' }\">\n            <pre>1\n            2</pre>\n          </td>\n          <td class=\"code\">\n            <pre><span class=\"Ke\">def </span><span class=\"NaFu\">foo</span>(bar):\n              <span class=\"Ke\">pass</span>\n            </pre>\n          </td>\n        </tr></table></div>\n\n    (whitespace added to improve clarity).\n\n    Wrapping can be disabled using the `nowrap` option.\n\n    A list of lines can be specified using the `hl_lines` option to make these\n    lines highlighted (as of Pygments 0.11).\n\n    With the `full` option, a complete HTML 4 document is output, including\n    the style definitions inside a ``<style>`` tag, or in a separate file if\n    the `cssfile` option is given.\n\n    When `tagsfile` is set to the path of a ctags index file, it is used to\n    generate hyperlinks from names to their definition.  You must enable\n    `lineanchors` and run ctags with the `-n` option for this to work.  The\n    `python-ctags` module from PyPI must be installed to use this feature;\n    otherwise a `RuntimeError` will be raised.\n\n    The `get_style_defs(arg='')` method of a `HtmlFormatter` returns a string\n    containing CSS rules for the CSS classes used by the formatter. The\n    argument `arg` can be used to specify additional CSS selectors that\n    are prepended to the classes. A call `fmter.get_style_defs('td .code')`\n    would result in the following CSS classes:\n\n    .. sourcecode:: css\n\n        td .code .kw { font-weight: bold; color: #00FF00 }\n        td .code .cm { color: #999999 }\n        ...\n\n    If you have Pygments 0.6 or higher, you can also pass a list or tuple to the\n    `get_style_defs()` method to request multiple prefixes for the tokens:\n\n    .. sourcecode:: python\n\n        formatter.get_style_defs(['div.syntax pre', 'pre.syntax'])\n\n    The output would then look like this:\n\n    .. sourcecode:: css\n\n        div.syntax pre .kw,\n        pre.syntax .kw { font-weight: bold; color: #00FF00 }\n        div.syntax pre .cm,\n        pre.syntax .cm { color: #999999 }\n        ...\n\n    Additional options accepted:\n\n    `nowrap`\n        If set to ``True``, don't wrap the tokens at all, not even inside a ``<pre>``\n        tag. This disables most other options (default: ``False``).\n\n    `full`\n        Tells the formatter to output a \"full\" document, i.e. a complete\n        self-contained document (default: ``False``).\n\n    `title`\n        If `full` is true, the title that should be used to caption the\n        document (default: ``''``).\n\n    `style`\n        The style to use, can be a string or a Style subclass (default:\n        ``'default'``). This option has no effect if the `cssfile`\n        and `noclobber_cssfile` option are given and the file specified in\n        `cssfile` exists.\n\n    `noclasses`\n        If set to true, token ``<span>`` tags (as well as line number elements)\n        will not use CSS classes, but inline styles. This is not recommended\n        for larger pieces of code since it increases output size by quite a bit\n        (default: ``False``).\n\n    `classprefix`\n        Since the token types use relatively short class names, they may clash\n        with some of your own class names. In this case you can use the\n        `classprefix` option to give a string to prepend to all Pygments-generated\n        CSS class names for token types.\n        Note that this option also affects the output of `get_style_defs()`.\n\n    `cssclass`\n        CSS class for the wrapping ``<div>`` tag (default: ``'highlight'``).\n        If you set this option, the default selector for `get_style_defs()`\n        will be this class.\n\n        .. versionadded:: 0.9\n           If you select the ``'table'`` line numbers, the wrapping table will\n           have a CSS class of this string plus ``'table'``, the default is\n           accordingly ``'highlighttable'``.\n\n    `cssstyles`\n        Inline CSS styles for the wrapping ``<div>`` tag (default: ``''``).\n\n    `prestyles`\n        Inline CSS styles for the ``<pre>`` tag (default: ``''``).\n\n        .. versionadded:: 0.11\n\n    `cssfile`\n        If the `full` option is true and this option is given, it must be the\n        name of an external file. If the filename does not include an absolute\n        path, the file's path will be assumed to be relative to the main output\n        file's path, if the latter can be found. The stylesheet is then written\n        to this file instead of the HTML file.\n\n        .. versionadded:: 0.6\n\n    `noclobber_cssfile`\n        If `cssfile` is given and the specified file exists, the css file will\n        not be overwritten. This allows the use of the `full` option in\n        combination with a user specified css file. Default is ``False``.\n\n        .. versionadded:: 1.1\n\n    `linenos`\n        If set to ``'table'``, output line numbers as a table with two cells,\n        one containing the line numbers, the other the whole code.  This is\n        copy-and-paste-friendly, but may cause alignment problems with some\n        browsers or fonts.  If set to ``'inline'``, the line numbers will be\n        integrated in the ``<pre>`` tag that contains the code (that setting\n        is *new in Pygments 0.8*).\n\n        For compatibility with Pygments 0.7 and earlier, every true value\n        except ``'inline'`` means the same as ``'table'`` (in particular, that\n        means also ``True``).\n\n        The default value is ``False``, which means no line numbers at all.\n\n        **Note:** with the default (\"table\") line number mechanism, the line\n        numbers and code can have different line heights in Internet Explorer\n        unless you give the enclosing ``<pre>`` tags an explicit ``line-height``\n        CSS property (you get the default line spacing with ``line-height:\n        125%``).\n\n    `hl_lines`\n        Specify a list of lines to be highlighted. The line numbers are always\n        relative to the input (i.e. the first line is line 1) and are\n        independent of `linenostart`.\n\n        .. versionadded:: 0.11\n\n    `linenostart`\n        The line number for the first line (default: ``1``).\n\n    `linenostep`\n        If set to a number n > 1, only every nth line number is printed.\n\n    `linenospecial`\n        If set to a number n > 0, every nth line number is given the CSS\n        class ``\"special\"`` (default: ``0``).\n\n    `nobackground`\n        If set to ``True``, the formatter won't output the background color\n        for the wrapping element (this automatically defaults to ``False``\n        when there is no wrapping element [eg: no argument for the\n        `get_syntax_defs` method given]) (default: ``False``).\n\n        .. versionadded:: 0.6\n\n    `lineseparator`\n        This string is output between lines of code. It defaults to ``\"\\n\"``,\n        which is enough to break a line inside ``<pre>`` tags, but you can\n        e.g. set it to ``\"<br>\"`` to get HTML line breaks.\n\n        .. versionadded:: 0.7\n\n    `lineanchors`\n        If set to a nonempty string, e.g. ``foo``, the formatter will wrap each\n        output line in an anchor tag with an ``id`` (and `name`) of ``foo-linenumber``.\n        This allows easy linking to certain lines.\n\n        .. versionadded:: 0.9\n\n    `linespans`\n        If set to a nonempty string, e.g. ``foo``, the formatter will wrap each\n        output line in a span tag with an ``id`` of ``foo-linenumber``.\n        This allows easy access to lines via javascript.\n\n        .. versionadded:: 1.6\n\n    `anchorlinenos`\n        If set to `True`, will wrap line numbers in <a> tags. Used in\n        combination with `linenos` and `lineanchors`.\n\n    `tagsfile`\n        If set to the path of a ctags file, wrap names in anchor tags that\n        link to their definitions. `lineanchors` should be used, and the\n        tags file should specify line numbers (see the `-n` option to ctags).\n\n        .. versionadded:: 1.6\n\n    `tagurlformat`\n        A string formatting pattern used to generate links to ctags definitions.\n        Available variables are `%(path)s`, `%(fname)s` and `%(fext)s`.\n        Defaults to an empty string, resulting in just `#prefix-number` links.\n\n        .. versionadded:: 1.6\n\n    `filename`\n        A string used to generate a filename when rendering ``<pre>`` blocks,\n        for example if displaying source code. If `linenos` is set to\n        ``'table'`` then the filename will be rendered in an initial row\n        containing a single `<th>` which spans both columns.\n\n        .. versionadded:: 2.1\n\n    `wrapcode`\n        Wrap the code inside ``<pre>`` blocks using ``<code>``, as recommended\n        by the HTML5 specification.\n\n        .. versionadded:: 2.4\n\n    `debug_token_types`\n        Add ``title`` attributes to all token ``<span>`` tags that show the\n        name of the token.\n\n        .. versionadded:: 2.10\n\n\n    **Subclassing the HTML formatter**\n\n    .. versionadded:: 0.7\n\n    The HTML formatter is now built in a way that allows easy subclassing, thus\n    customizing the output HTML code. The `format()` method calls\n    `self._format_lines()` which returns a generator that yields tuples of ``(1,\n    line)``, where the ``1`` indicates that the ``line`` is a line of the\n    formatted source code.\n\n    If the `nowrap` option is set, the generator is the iterated over and the\n    resulting HTML is output.\n\n    Otherwise, `format()` calls `self.wrap()`, which wraps the generator with\n    other generators. These may add some HTML code to the one generated by\n    `_format_lines()`, either by modifying the lines generated by the latter,\n    then yielding them again with ``(1, line)``, and/or by yielding other HTML\n    code before or after the lines, with ``(0, html)``. The distinction between\n    source lines and other code makes it possible to wrap the generator multiple\n    times.\n\n    The default `wrap()` implementation adds a ``<div>`` and a ``<pre>`` tag.\n\n    A custom `HtmlFormatter` subclass could look like this:\n\n    .. sourcecode:: python\n\n        class CodeHtmlFormatter(HtmlFormatter):\n\n            def wrap(self, source, *, include_div):\n                return self._wrap_code(source)\n\n            def _wrap_code(self, source):\n                yield 0, '<code>'\n                for i, t in source:\n                    if i == 1:\n                        # it's a line of formatted code\n                        t += '<br>'\n                    yield i, t\n                yield 0, '</code>'\n\n    This results in wrapping the formatted lines with a ``<code>`` tag, where the\n    source lines are broken using ``<br>`` tags.\n\n    After calling `wrap()`, the `format()` method also adds the \"line numbers\"\n    and/or \"full document\" wrappers if the respective options are set. Then, all\n    HTML yielded by the wrapped generator is output.\n    \"\"\"\n\n    name = 'HTML'\n    aliases = ['html']\n    filenames = ['*.html', '*.htm']\n\n    def __init__(self, **options):\n        Formatter.__init__(self, **options)\n        self.title = self._decodeifneeded(self.title)\n        self.nowrap = get_bool_opt(options, 'nowrap', False)\n        self.noclasses = get_bool_opt(options, 'noclasses', False)\n        self.classprefix = options.get('classprefix', '')\n        self.cssclass = self._decodeifneeded(options.get('cssclass', 'highlight'))\n        self.cssstyles = self._decodeifneeded(options.get('cssstyles', ''))\n        self.prestyles = self._decodeifneeded(options.get('prestyles', ''))\n        self.cssfile = self._decodeifneeded(options.get('cssfile', ''))\n        self.noclobber_cssfile = get_bool_opt(options, 'noclobber_cssfile', False)\n        self.tagsfile = self._decodeifneeded(options.get('tagsfile', ''))\n        self.tagurlformat = self._decodeifneeded(options.get('tagurlformat', ''))\n        self.filename = self._decodeifneeded(options.get('filename', ''))\n        self.wrapcode = get_bool_opt(options, 'wrapcode', False)\n        self.span_element_openers = {}\n        self.debug_token_types = get_bool_opt(options, 'debug_token_types', False)\n\n        if self.tagsfile:\n            if not ctags:\n                raise RuntimeError('The \"ctags\" package must to be installed '\n                                   'to be able to use the \"tagsfile\" feature.')\n            self._ctags = ctags.CTags(self.tagsfile)\n\n        linenos = options.get('linenos', False)\n        if linenos == 'inline':\n            self.linenos = 2\n        elif linenos:\n            # compatibility with <= 0.7\n            self.linenos = 1\n        else:\n            self.linenos = 0\n        self.linenostart = abs(get_int_opt(options, 'linenostart', 1))\n        self.linenostep = abs(get_int_opt(options, 'linenostep', 1))\n        self.linenospecial = abs(get_int_opt(options, 'linenospecial', 0))\n        self.nobackground = get_bool_opt(options, 'nobackground', False)\n        self.lineseparator = options.get('lineseparator', '\\n')\n        self.lineanchors = options.get('lineanchors', '')\n        self.linespans = options.get('linespans', '')\n        self.anchorlinenos = get_bool_opt(options, 'anchorlinenos', False)\n        self.hl_lines = set()\n        for lineno in get_list_opt(options, 'hl_lines', []):\n            try:\n                self.hl_lines.add(int(lineno))\n            except ValueError:\n                pass\n\n        self._create_stylesheet()\n\n    def _get_css_class(self, ttype):\n        \"\"\"Return the css class of this token type prefixed with\n        the classprefix option.\"\"\"\n        ttypeclass = _get_ttype_class(ttype)\n        if ttypeclass:\n            return self.classprefix + ttypeclass\n        return ''\n\n    def _get_css_classes(self, ttype):\n        \"\"\"Return the CSS classes of this token type prefixed with the classprefix option.\"\"\"\n        cls = self._get_css_class(ttype)\n        while ttype not in STANDARD_TYPES:\n            ttype = ttype.parent\n            cls = self._get_css_class(ttype) + ' ' + cls\n        return cls or ''\n\n    def _get_css_inline_styles(self, ttype):\n        \"\"\"Return the inline CSS styles for this token type.\"\"\"\n        cclass = self.ttype2class.get(ttype)\n        while cclass is None:\n            ttype = ttype.parent\n            cclass = self.ttype2class.get(ttype)\n        return cclass or ''\n\n    def _create_stylesheet(self):\n        t2c = self.ttype2class = {Token: ''}\n        c2s = self.class2style = {}\n        for ttype, ndef in self.style:\n            name = self._get_css_class(ttype)\n            style = ''\n            if ndef['color']:\n                style += 'color: %s; ' % webify(ndef['color'])\n            if ndef['bold']:\n                style += 'font-weight: bold; '\n            if ndef['italic']:\n                style += 'font-style: italic; '\n            if ndef['underline']:\n                style += 'text-decoration: underline; '\n            if ndef['bgcolor']:\n                style += 'background-color: %s; ' % webify(ndef['bgcolor'])\n            if ndef['border']:\n                style += 'border: 1px solid %s; ' % webify(ndef['border'])\n            if style:\n                t2c[ttype] = name\n                # save len(ttype) to enable ordering the styles by\n                # hierarchy (necessary for CSS cascading rules!)\n                c2s[name] = (style[:-2], ttype, len(ttype))\n\n    def get_style_defs(self, arg=None):\n        \"\"\"\n        Return CSS style definitions for the classes produced by the current\n        highlighting style. ``arg`` can be a string or list of selectors to\n        insert before the token type classes.\n        \"\"\"\n        style_lines = []\n\n        style_lines.extend(self.get_linenos_style_defs())\n        style_lines.extend(self.get_background_style_defs(arg))\n        style_lines.extend(self.get_token_style_defs(arg))\n\n        return '\\n'.join(style_lines)\n\n    def get_token_style_defs(self, arg=None):\n        prefix = self.get_css_prefix(arg)\n\n        styles = [\n            (level, ttype, cls, style)\n            for cls, (style, ttype, level) in self.class2style.items()\n            if cls and style\n        ]\n        styles.sort()\n\n        lines = [\n            '%s { %s } /* %s */' % (prefix(cls), style, repr(ttype)[6:])\n            for (level, ttype, cls, style) in styles\n        ]\n\n        return lines\n\n    def get_background_style_defs(self, arg=None):\n        prefix = self.get_css_prefix(arg)\n        bg_color = self.style.background_color\n        hl_color = self.style.highlight_color\n\n        lines = []\n\n        if arg and not self.nobackground and bg_color is not None:\n            text_style = ''\n            if Text in self.ttype2class:\n                text_style = ' ' + self.class2style[self.ttype2class[Text]][0]\n            lines.insert(\n                0, '%s{ background: %s;%s }' % (\n                    prefix(''), bg_color, text_style\n                )\n            )\n        if hl_color is not None:\n            lines.insert(\n                0, '%s { background-color: %s }' % (prefix('hll'), hl_color)\n            )\n\n        return lines\n\n    def get_linenos_style_defs(self):\n        lines = [\n            'pre { %s }' % self._pre_style,\n            'td.linenos .normal { %s }' % self._linenos_style,\n            'span.linenos { %s }' % self._linenos_style,\n            'td.linenos .special { %s }' % self._linenos_special_style,\n            'span.linenos.special { %s }' % self._linenos_special_style,\n        ]\n\n        return lines\n\n    def get_css_prefix(self, arg):\n        if arg is None:\n            arg = ('cssclass' in self.options and '.'+self.cssclass or '')\n        if isinstance(arg, str):\n            args = [arg]\n        else:\n            args = list(arg)\n\n        def prefix(cls):\n            if cls:\n                cls = '.' + cls\n            tmp = []\n            for arg in args:\n                tmp.append((arg and arg + ' ' or '') + cls)\n            return ', '.join(tmp)\n\n        return prefix\n\n    @property\n    def _pre_style(self):\n        return 'line-height: 125%;'\n\n    @property\n    def _linenos_style(self):\n        return 'color: %s; background-color: %s; padding-left: 5px; padding-right: 5px;' % (\n            self.style.line_number_color,\n            self.style.line_number_background_color\n        )\n\n    @property\n    def _linenos_special_style(self):\n        return 'color: %s; background-color: %s; padding-left: 5px; padding-right: 5px;' % (\n            self.style.line_number_special_color,\n            self.style.line_number_special_background_color\n        )\n\n    def _decodeifneeded(self, value):\n        if isinstance(value, bytes):\n            if self.encoding:\n                return value.decode(self.encoding)\n            return value.decode()\n        return value\n\n    def _wrap_full(self, inner, outfile):\n        if self.cssfile:\n            if os.path.isabs(self.cssfile):\n                # it's an absolute filename\n                cssfilename = self.cssfile\n            else:\n                try:\n                    filename = outfile.name\n                    if not filename or filename[0] == '<':\n                        # pseudo files, e.g. name == '<fdopen>'\n                        raise AttributeError\n                    cssfilename = os.path.join(os.path.dirname(filename),\n                                               self.cssfile)\n                except AttributeError:\n                    print('Note: Cannot determine output file name, '\n                          'using current directory as base for the CSS file name',\n                          file=sys.stderr)\n                    cssfilename = self.cssfile\n            # write CSS file only if noclobber_cssfile isn't given as an option.\n            try:\n                if not os.path.exists(cssfilename) or not self.noclobber_cssfile:\n                    with open(cssfilename, \"w\") as cf:\n                        cf.write(CSSFILE_TEMPLATE %\n                                 {'styledefs': self.get_style_defs('body')})\n            except OSError as err:\n                err.strerror = 'Error writing CSS file: ' + err.strerror\n                raise\n\n            yield 0, (DOC_HEADER_EXTERNALCSS %\n                      dict(title=self.title,\n                           cssfile=self.cssfile,\n                           encoding=self.encoding))\n        else:\n            yield 0, (DOC_HEADER %\n                      dict(title=self.title,\n                           styledefs=self.get_style_defs('body'),\n                           encoding=self.encoding))\n\n        yield from inner\n        yield 0, DOC_FOOTER\n\n    def _wrap_tablelinenos(self, inner):\n        dummyoutfile = StringIO()\n        lncount = 0\n        for t, line in inner:\n            if t:\n                lncount += 1\n            dummyoutfile.write(line)\n\n        fl = self.linenostart\n        mw = len(str(lncount + fl - 1))\n        sp = self.linenospecial\n        st = self.linenostep\n        anchor_name = self.lineanchors or self.linespans\n        aln = self.anchorlinenos\n        nocls = self.noclasses\n\n        lines = []\n\n        for i in range(fl, fl+lncount):\n            print_line = i % st == 0\n            special_line = sp and i % sp == 0\n\n            if print_line:\n                line = '%*d' % (mw, i)\n                if aln:\n                    line = '<a href=\"#%s-%d\">%s</a>' % (anchor_name, i, line)\n            else:\n                line = ' ' * mw\n\n            if nocls:\n                if special_line:\n                    style = ' style=\"%s\"' % self._linenos_special_style\n                else:\n                    style = ' style=\"%s\"' % self._linenos_style\n            else:\n                if special_line:\n                    style = ' class=\"special\"'\n                else:\n                    style = ' class=\"normal\"'\n\n            if style:\n                line = '<span%s>%s</span>' % (style, line)\n\n            lines.append(line)\n\n        ls = '\\n'.join(lines)\n\n        # If a filename was specified, we can't put it into the code table as it\n        # would misalign the line numbers. Hence we emit a separate row for it.\n        filename_tr = \"\"\n        if self.filename:\n            filename_tr = (\n                '<tr><th colspan=\"2\" class=\"filename\">'\n                '<span class=\"filename\">' + self.filename + '</span>'\n                '</th></tr>')\n\n        # in case you wonder about the seemingly redundant <div> here: since the\n        # content in the other cell also is wrapped in a div, some browsers in\n        # some configurations seem to mess up the formatting...\n        yield 0, (f'<table class=\"{self.cssclass}table\">' + filename_tr +\n            '<tr><td class=\"linenos\"><div class=\"linenodiv\"><pre>' +\n            ls + '</pre></div></td><td class=\"code\">')\n        yield 0, '<div>'\n        yield 0, dummyoutfile.getvalue()\n        yield 0, '</div>'\n        yield 0, '</td></tr></table>'\n        \n\n    def _wrap_inlinelinenos(self, inner):\n        # need a list of lines since we need the width of a single number :(\n        inner_lines = list(inner)\n        sp = self.linenospecial\n        st = self.linenostep\n        num = self.linenostart\n        mw = len(str(len(inner_lines) + num - 1))\n        anchor_name = self.lineanchors or self.linespans\n        aln = self.anchorlinenos\n        nocls = self.noclasses\n\n        for _, inner_line in inner_lines:\n            print_line = num % st == 0\n            special_line = sp and num % sp == 0\n\n            if print_line:\n                line = '%*d' % (mw, num)\n            else:\n                line = ' ' * mw\n\n            if nocls:\n                if special_line:\n                    style = ' style=\"%s\"' % self._linenos_special_style\n                else:\n                    style = ' style=\"%s\"' % self._linenos_style\n            else:\n                if special_line:\n                    style = ' class=\"linenos special\"'\n                else:\n                    style = ' class=\"linenos\"'\n\n            if style:\n                linenos = '<span%s>%s</span>' % (style, line)\n            else:\n                linenos = line\n\n            if aln:\n                yield 1, ('<a href=\"#%s-%d\">%s</a>' % (anchor_name, num, linenos) +\n                          inner_line)\n            else:\n                yield 1, linenos + inner_line\n            num += 1\n\n    def _wrap_lineanchors(self, inner):\n        s = self.lineanchors\n        # subtract 1 since we have to increment i *before* yielding\n        i = self.linenostart - 1\n        for t, line in inner:\n            if t:\n                i += 1\n                href = \"\" if self.linenos else ' href=\"#%s-%d\"' % (s, i)\n                yield 1, '<a id=\"%s-%d\" name=\"%s-%d\"%s></a>' % (s, i, s, i, href) + line\n            else:\n                yield 0, line\n\n    def _wrap_linespans(self, inner):\n        s = self.linespans\n        i = self.linenostart - 1\n        for t, line in inner:\n            if t:\n                i += 1\n                yield 1, '<span id=\"%s-%d\">%s</span>' % (s, i, line)\n            else:\n                yield 0, line\n\n    def _wrap_div(self, inner):\n        style = []\n        if (self.noclasses and not self.nobackground and\n                self.style.background_color is not None):\n            style.append('background: %s' % (self.style.background_color,))\n        if self.cssstyles:\n            style.append(self.cssstyles)\n        style = '; '.join(style)\n\n        yield 0, ('<div' + (self.cssclass and ' class=\"%s\"' % self.cssclass) +\n                  (style and (' style=\"%s\"' % style)) + '>')\n        yield from inner\n        yield 0, '</div>\\n'\n\n    def _wrap_pre(self, inner):\n        style = []\n        if self.prestyles:\n            style.append(self.prestyles)\n        if self.noclasses:\n            style.append(self._pre_style)\n        style = '; '.join(style)\n\n        if self.filename and self.linenos != 1:\n            yield 0, ('<span class=\"filename\">' + self.filename + '</span>')\n\n        # the empty span here is to keep leading empty lines from being\n        # ignored by HTML parsers\n        yield 0, ('<pre' + (style and ' style=\"%s\"' % style) + '><span></span>')\n        yield from inner\n        yield 0, '</pre>'\n\n    def _wrap_code(self, inner):\n        yield 0, '<code>'\n        yield from inner\n        yield 0, '</code>'\n\n    @functools.lru_cache(maxsize=100)\n    def _translate_parts(self, value):\n        \"\"\"HTML-escape a value and split it by newlines.\"\"\"\n        return value.translate(_escape_html_table).split('\\n')\n\n    def _format_lines(self, tokensource):\n        \"\"\"\n        Just format the tokens, without any wrapping tags.\n        Yield individual lines.\n        \"\"\"\n        nocls = self.noclasses\n        lsep = self.lineseparator\n        tagsfile = self.tagsfile\n\n        lspan = ''\n        line = []\n        for ttype, value in tokensource:\n            try:\n                cspan = self.span_element_openers[ttype]\n            except KeyError:\n                title = ' title=\"%s\"' % '.'.join(ttype) if self.debug_token_types else ''\n                if nocls:\n                    css_style = self._get_css_inline_styles(ttype)\n                    if css_style:\n                        css_style = self.class2style[css_style][0]\n                        cspan = '<span style=\"%s\"%s>' % (css_style, title)\n                    else:\n                        cspan = ''\n                else:\n                    css_class = self._get_css_classes(ttype)\n                    if css_class:\n                        cspan = '<span class=\"%s\"%s>' % (css_class, title)\n                    else:\n                        cspan = ''\n                self.span_element_openers[ttype] = cspan\n\n            parts = self._translate_parts(value)\n\n            if tagsfile and ttype in Token.Name:\n                filename, linenumber = self._lookup_ctag(value)\n                if linenumber:\n                    base, filename = os.path.split(filename)\n                    if base:\n                        base += '/'\n                    filename, extension = os.path.splitext(filename)\n                    url = self.tagurlformat % {'path': base, 'fname': filename,\n                                               'fext': extension}\n                    parts[0] = \"<a href=\\\"%s#%s-%d\\\">%s\" % \\\n                        (url, self.lineanchors, linenumber, parts[0])\n                    parts[-1] = parts[-1] + \"</a>\"\n\n            # for all but the last line\n            for part in parts[:-1]:\n                if line:\n                    if lspan != cspan:\n                        line.extend(((lspan and '</span>'), cspan, part,\n                                     (cspan and '</span>'), lsep))\n                    else:  # both are the same\n                        line.extend((part, (lspan and '</span>'), lsep))\n                    yield 1, ''.join(line)\n                    line = []\n                elif part:\n                    yield 1, ''.join((cspan, part, (cspan and '</span>'), lsep))\n                else:\n                    yield 1, lsep\n            # for the last line\n            if line and parts[-1]:\n                if lspan != cspan:\n                    line.extend(((lspan and '</span>'), cspan, parts[-1]))\n                    lspan = cspan\n                else:\n                    line.append(parts[-1])\n            elif parts[-1]:\n                line = [cspan, parts[-1]]\n                lspan = cspan\n            # else we neither have to open a new span nor set lspan\n\n        if line:\n            line.extend(((lspan and '</span>'), lsep))\n            yield 1, ''.join(line)\n\n    def _lookup_ctag(self, token):\n        entry = ctags.TagEntry()\n        if self._ctags.find(entry, token.encode(), 0):\n            return entry['file'], entry['lineNumber']\n        else:\n            return None, None\n\n    def _highlight_lines(self, tokensource):\n        \"\"\"\n        Highlighted the lines specified in the `hl_lines` option by\n        post-processing the token stream coming from `_format_lines`.\n        \"\"\"\n        hls = self.hl_lines\n\n        for i, (t, value) in enumerate(tokensource):\n            if t != 1:\n                yield t, value\n            if i + 1 in hls:  # i + 1 because Python indexes start at 0\n                if self.noclasses:\n                    style = ''\n                    if self.style.highlight_color is not None:\n                        style = (' style=\"background-color: %s\"' %\n                                 (self.style.highlight_color,))\n                    yield 1, '<span%s>%s</span>' % (style, value)\n                else:\n                    yield 1, '<span class=\"hll\">%s</span>' % value\n            else:\n                yield 1, value\n\n    def wrap(self, source):\n        \"\"\"\n        Wrap the ``source``, which is a generator yielding\n        individual lines, in custom generators. See docstring\n        for `format`. Can be overridden.\n        \"\"\"\n\n        output = source\n        if self.wrapcode:\n            output = self._wrap_code(output)\n        \n        output = self._wrap_pre(output)\n    \n        return output\n\n    def format_unencoded(self, tokensource, outfile):\n        \"\"\"\n        The formatting process uses several nested generators; which of\n        them are used is determined by the user's options.\n\n        Each generator should take at least one argument, ``inner``,\n        and wrap the pieces of text generated by this.\n\n        Always yield 2-tuples: (code, text). If \"code\" is 1, the text\n        is part of the original tokensource being highlighted, if it's\n        0, the text is some piece of wrapping. This makes it possible to\n        use several different wrappers that process the original source\n        linewise, e.g. line number generators.\n        \"\"\"\n        source = self._format_lines(tokensource)\n\n        # As a special case, we wrap line numbers before line highlighting\n        # so the line numbers get wrapped in the highlighting tag.\n        if not self.nowrap and self.linenos == 2:\n            source = self._wrap_inlinelinenos(source)\n\n        if self.hl_lines:\n            source = self._highlight_lines(source)\n\n        if not self.nowrap:\n            if self.lineanchors:\n                source = self._wrap_lineanchors(source)\n            if self.linespans:\n                source = self._wrap_linespans(source)\n            source = self.wrap(source)\n            if self.linenos == 1:\n                source = self._wrap_tablelinenos(source)\n            source = self._wrap_div(source)\n            if self.full:\n                source = self._wrap_full(source, outfile)\n\n        for t, piece in source:\n            outfile.write(piece)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatters/img.py",
    "content": "\"\"\"\n    pygments.formatters.img\n    ~~~~~~~~~~~~~~~~~~~~~~~\n\n    Formatter for Pixmap output.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport os\nimport sys\n\nfrom pip._vendor.pygments.formatter import Formatter\nfrom pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt, \\\n    get_choice_opt\n\nimport subprocess\n\n# Import this carefully\ntry:\n    from PIL import Image, ImageDraw, ImageFont\n    pil_available = True\nexcept ImportError:\n    pil_available = False\n\ntry:\n    import _winreg\nexcept ImportError:\n    try:\n        import winreg as _winreg\n    except ImportError:\n        _winreg = None\n\n__all__ = ['ImageFormatter', 'GifImageFormatter', 'JpgImageFormatter',\n           'BmpImageFormatter']\n\n\n# For some unknown reason every font calls it something different\nSTYLES = {\n    'NORMAL':     ['', 'Roman', 'Book', 'Normal', 'Regular', 'Medium'],\n    'ITALIC':     ['Oblique', 'Italic'],\n    'BOLD':       ['Bold'],\n    'BOLDITALIC': ['Bold Oblique', 'Bold Italic'],\n}\n\n# A sane default for modern systems\nDEFAULT_FONT_NAME_NIX = 'DejaVu Sans Mono'\nDEFAULT_FONT_NAME_WIN = 'Courier New'\nDEFAULT_FONT_NAME_MAC = 'Menlo'\n\n\nclass PilNotAvailable(ImportError):\n    \"\"\"When Python imaging library is not available\"\"\"\n\n\nclass FontNotFound(Exception):\n    \"\"\"When there are no usable fonts specified\"\"\"\n\n\nclass FontManager:\n    \"\"\"\n    Manages a set of fonts: normal, italic, bold, etc...\n    \"\"\"\n\n    def __init__(self, font_name, font_size=14):\n        self.font_name = font_name\n        self.font_size = font_size\n        self.fonts = {}\n        self.encoding = None\n        if sys.platform.startswith('win'):\n            if not font_name:\n                self.font_name = DEFAULT_FONT_NAME_WIN\n            self._create_win()\n        elif sys.platform.startswith('darwin'):\n            if not font_name:\n                self.font_name = DEFAULT_FONT_NAME_MAC\n            self._create_mac()\n        else:\n            if not font_name:\n                self.font_name = DEFAULT_FONT_NAME_NIX\n            self._create_nix()\n\n    def _get_nix_font_path(self, name, style):\n        proc = subprocess.Popen(['fc-list', \"%s:style=%s\" % (name, style), 'file'],\n                                stdout=subprocess.PIPE, stderr=None)\n        stdout, _ = proc.communicate()\n        if proc.returncode == 0:\n            lines = stdout.splitlines()\n            for line in lines:\n                if line.startswith(b'Fontconfig warning:'):\n                    continue\n                path = line.decode().strip().strip(':')\n                if path:\n                    return path\n            return None\n\n    def _create_nix(self):\n        for name in STYLES['NORMAL']:\n            path = self._get_nix_font_path(self.font_name, name)\n            if path is not None:\n                self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)\n                break\n        else:\n            raise FontNotFound('No usable fonts named: \"%s\"' %\n                               self.font_name)\n        for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):\n            for stylename in STYLES[style]:\n                path = self._get_nix_font_path(self.font_name, stylename)\n                if path is not None:\n                    self.fonts[style] = ImageFont.truetype(path, self.font_size)\n                    break\n            else:\n                if style == 'BOLDITALIC':\n                    self.fonts[style] = self.fonts['BOLD']\n                else:\n                    self.fonts[style] = self.fonts['NORMAL']\n\n    def _get_mac_font_path(self, font_map, name, style):\n        return font_map.get((name + ' ' + style).strip().lower())\n\n    def _create_mac(self):\n        font_map = {}\n        for font_dir in (os.path.join(os.getenv(\"HOME\"), 'Library/Fonts/'),\n                         '/Library/Fonts/', '/System/Library/Fonts/'):\n            font_map.update(\n                (os.path.splitext(f)[0].lower(), os.path.join(font_dir, f))\n                for f in os.listdir(font_dir)\n                if f.lower().endswith(('ttf', 'ttc')))\n\n        for name in STYLES['NORMAL']:\n            path = self._get_mac_font_path(font_map, self.font_name, name)\n            if path is not None:\n                self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)\n                break\n        else:\n            raise FontNotFound('No usable fonts named: \"%s\"' %\n                               self.font_name)\n        for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):\n            for stylename in STYLES[style]:\n                path = self._get_mac_font_path(font_map, self.font_name, stylename)\n                if path is not None:\n                    self.fonts[style] = ImageFont.truetype(path, self.font_size)\n                    break\n            else:\n                if style == 'BOLDITALIC':\n                    self.fonts[style] = self.fonts['BOLD']\n                else:\n                    self.fonts[style] = self.fonts['NORMAL']\n\n    def _lookup_win(self, key, basename, styles, fail=False):\n        for suffix in ('', ' (TrueType)'):\n            for style in styles:\n                try:\n                    valname = '%s%s%s' % (basename, style and ' '+style, suffix)\n                    val, _ = _winreg.QueryValueEx(key, valname)\n                    return val\n                except OSError:\n                    continue\n        else:\n            if fail:\n                raise FontNotFound('Font %s (%s) not found in registry' %\n                                   (basename, styles[0]))\n            return None\n\n    def _create_win(self):\n        lookuperror = None\n        keynames = [ (_winreg.HKEY_CURRENT_USER, r'Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts'),\n                     (_winreg.HKEY_CURRENT_USER, r'Software\\Microsoft\\Windows\\CurrentVersion\\Fonts'),\n                     (_winreg.HKEY_LOCAL_MACHINE, r'Software\\Microsoft\\Windows NT\\CurrentVersion\\Fonts'),\n                     (_winreg.HKEY_LOCAL_MACHINE, r'Software\\Microsoft\\Windows\\CurrentVersion\\Fonts') ]\n        for keyname in keynames:\n            try:\n                key = _winreg.OpenKey(*keyname)\n                try:\n                    path = self._lookup_win(key, self.font_name, STYLES['NORMAL'], True)\n                    self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)\n                    for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):\n                        path = self._lookup_win(key, self.font_name, STYLES[style])\n                        if path:\n                            self.fonts[style] = ImageFont.truetype(path, self.font_size)\n                        else:\n                            if style == 'BOLDITALIC':\n                                self.fonts[style] = self.fonts['BOLD']\n                            else:\n                                self.fonts[style] = self.fonts['NORMAL']\n                    return\n                except FontNotFound as err:\n                    lookuperror = err\n                finally:\n                    _winreg.CloseKey(key)\n            except OSError:\n                pass\n        else:\n            # If we get here, we checked all registry keys and had no luck\n            # We can be in one of two situations now:\n            # * All key lookups failed. In this case lookuperror is None and we\n            #   will raise a generic error\n            # * At least one lookup failed with a FontNotFound error. In this\n            #   case, we will raise that as a more specific error\n            if lookuperror:\n                raise lookuperror\n            raise FontNotFound('Can\\'t open Windows font registry key')\n\n    def get_char_size(self):\n        \"\"\"\n        Get the character size.\n        \"\"\"\n        return self.get_text_size('M')\n\n    def get_text_size(self, text):\n        \"\"\"\n        Get the text size (width, height).\n        \"\"\"\n        font = self.fonts['NORMAL']\n        if hasattr(font, 'getbbox'):  # Pillow >= 9.2.0\n            return font.getbbox(text)[2:4]\n        else:\n            return font.getsize(text)\n\n    def get_font(self, bold, oblique):\n        \"\"\"\n        Get the font based on bold and italic flags.\n        \"\"\"\n        if bold and oblique:\n            return self.fonts['BOLDITALIC']\n        elif bold:\n            return self.fonts['BOLD']\n        elif oblique:\n            return self.fonts['ITALIC']\n        else:\n            return self.fonts['NORMAL']\n\n\nclass ImageFormatter(Formatter):\n    \"\"\"\n    Create a PNG image from source code. This uses the Python Imaging Library to\n    generate a pixmap from the source code.\n\n    .. versionadded:: 0.10\n\n    Additional options accepted:\n\n    `image_format`\n        An image format to output to that is recognised by PIL, these include:\n\n        * \"PNG\" (default)\n        * \"JPEG\"\n        * \"BMP\"\n        * \"GIF\"\n\n    `line_pad`\n        The extra spacing (in pixels) between each line of text.\n\n        Default: 2\n\n    `font_name`\n        The font name to be used as the base font from which others, such as\n        bold and italic fonts will be generated.  This really should be a\n        monospace font to look sane.\n\n        Default: \"Courier New\" on Windows, \"Menlo\" on Mac OS, and\n                 \"DejaVu Sans Mono\" on \\\\*nix\n\n    `font_size`\n        The font size in points to be used.\n\n        Default: 14\n\n    `image_pad`\n        The padding, in pixels to be used at each edge of the resulting image.\n\n        Default: 10\n\n    `line_numbers`\n        Whether line numbers should be shown: True/False\n\n        Default: True\n\n    `line_number_start`\n        The line number of the first line.\n\n        Default: 1\n\n    `line_number_step`\n        The step used when printing line numbers.\n\n        Default: 1\n\n    `line_number_bg`\n        The background colour (in \"#123456\" format) of the line number bar, or\n        None to use the style background color.\n\n        Default: \"#eed\"\n\n    `line_number_fg`\n        The text color of the line numbers (in \"#123456\"-like format).\n\n        Default: \"#886\"\n\n    `line_number_chars`\n        The number of columns of line numbers allowable in the line number\n        margin.\n\n        Default: 2\n\n    `line_number_bold`\n        Whether line numbers will be bold: True/False\n\n        Default: False\n\n    `line_number_italic`\n        Whether line numbers will be italicized: True/False\n\n        Default: False\n\n    `line_number_separator`\n        Whether a line will be drawn between the line number area and the\n        source code area: True/False\n\n        Default: True\n\n    `line_number_pad`\n        The horizontal padding (in pixels) between the line number margin, and\n        the source code area.\n\n        Default: 6\n\n    `hl_lines`\n        Specify a list of lines to be highlighted.\n\n        .. versionadded:: 1.2\n\n        Default: empty list\n\n    `hl_color`\n        Specify the color for highlighting lines.\n\n        .. versionadded:: 1.2\n\n        Default: highlight color of the selected style\n    \"\"\"\n\n    # Required by the pygments mapper\n    name = 'img'\n    aliases = ['img', 'IMG', 'png']\n    filenames = ['*.png']\n\n    unicodeoutput = False\n\n    default_image_format = 'png'\n\n    def __init__(self, **options):\n        \"\"\"\n        See the class docstring for explanation of options.\n        \"\"\"\n        if not pil_available:\n            raise PilNotAvailable(\n                'Python Imaging Library is required for this formatter')\n        Formatter.__init__(self, **options)\n        self.encoding = 'latin1'  # let pygments.format() do the right thing\n        # Read the style\n        self.styles = dict(self.style)\n        if self.style.background_color is None:\n            self.background_color = '#fff'\n        else:\n            self.background_color = self.style.background_color\n        # Image options\n        self.image_format = get_choice_opt(\n            options, 'image_format', ['png', 'jpeg', 'gif', 'bmp'],\n            self.default_image_format, normcase=True)\n        self.image_pad = get_int_opt(options, 'image_pad', 10)\n        self.line_pad = get_int_opt(options, 'line_pad', 2)\n        # The fonts\n        fontsize = get_int_opt(options, 'font_size', 14)\n        self.fonts = FontManager(options.get('font_name', ''), fontsize)\n        self.fontw, self.fonth = self.fonts.get_char_size()\n        # Line number options\n        self.line_number_fg = options.get('line_number_fg', '#886')\n        self.line_number_bg = options.get('line_number_bg', '#eed')\n        self.line_number_chars = get_int_opt(options,\n                                             'line_number_chars', 2)\n        self.line_number_bold = get_bool_opt(options,\n                                             'line_number_bold', False)\n        self.line_number_italic = get_bool_opt(options,\n                                               'line_number_italic', False)\n        self.line_number_pad = get_int_opt(options, 'line_number_pad', 6)\n        self.line_numbers = get_bool_opt(options, 'line_numbers', True)\n        self.line_number_separator = get_bool_opt(options,\n                                                  'line_number_separator', True)\n        self.line_number_step = get_int_opt(options, 'line_number_step', 1)\n        self.line_number_start = get_int_opt(options, 'line_number_start', 1)\n        if self.line_numbers:\n            self.line_number_width = (self.fontw * self.line_number_chars +\n                                      self.line_number_pad * 2)\n        else:\n            self.line_number_width = 0\n        self.hl_lines = []\n        hl_lines_str = get_list_opt(options, 'hl_lines', [])\n        for line in hl_lines_str:\n            try:\n                self.hl_lines.append(int(line))\n            except ValueError:\n                pass\n        self.hl_color = options.get('hl_color',\n                                    self.style.highlight_color) or '#f90'\n        self.drawables = []\n\n    def get_style_defs(self, arg=''):\n        raise NotImplementedError('The -S option is meaningless for the image '\n                                  'formatter. Use -O style=<stylename> instead.')\n\n    def _get_line_height(self):\n        \"\"\"\n        Get the height of a line.\n        \"\"\"\n        return self.fonth + self.line_pad\n\n    def _get_line_y(self, lineno):\n        \"\"\"\n        Get the Y coordinate of a line number.\n        \"\"\"\n        return lineno * self._get_line_height() + self.image_pad\n\n    def _get_char_width(self):\n        \"\"\"\n        Get the width of a character.\n        \"\"\"\n        return self.fontw\n\n    def _get_char_x(self, linelength):\n        \"\"\"\n        Get the X coordinate of a character position.\n        \"\"\"\n        return linelength + self.image_pad + self.line_number_width\n\n    def _get_text_pos(self, linelength, lineno):\n        \"\"\"\n        Get the actual position for a character and line position.\n        \"\"\"\n        return self._get_char_x(linelength), self._get_line_y(lineno)\n\n    def _get_linenumber_pos(self, lineno):\n        \"\"\"\n        Get the actual position for the start of a line number.\n        \"\"\"\n        return (self.image_pad, self._get_line_y(lineno))\n\n    def _get_text_color(self, style):\n        \"\"\"\n        Get the correct color for the token from the style.\n        \"\"\"\n        if style['color'] is not None:\n            fill = '#' + style['color']\n        else:\n            fill = '#000'\n        return fill\n\n    def _get_text_bg_color(self, style):\n        \"\"\"\n        Get the correct background color for the token from the style.\n        \"\"\"\n        if style['bgcolor'] is not None:\n            bg_color = '#' + style['bgcolor']\n        else:\n            bg_color = None\n        return bg_color\n\n    def _get_style_font(self, style):\n        \"\"\"\n        Get the correct font for the style.\n        \"\"\"\n        return self.fonts.get_font(style['bold'], style['italic'])\n\n    def _get_image_size(self, maxlinelength, maxlineno):\n        \"\"\"\n        Get the required image size.\n        \"\"\"\n        return (self._get_char_x(maxlinelength) + self.image_pad,\n                self._get_line_y(maxlineno + 0) + self.image_pad)\n\n    def _draw_linenumber(self, posno, lineno):\n        \"\"\"\n        Remember a line number drawable to paint later.\n        \"\"\"\n        self._draw_text(\n            self._get_linenumber_pos(posno),\n            str(lineno).rjust(self.line_number_chars),\n            font=self.fonts.get_font(self.line_number_bold,\n                                     self.line_number_italic),\n            text_fg=self.line_number_fg,\n            text_bg=None,\n        )\n\n    def _draw_text(self, pos, text, font, text_fg, text_bg):\n        \"\"\"\n        Remember a single drawable tuple to paint later.\n        \"\"\"\n        self.drawables.append((pos, text, font, text_fg, text_bg))\n\n    def _create_drawables(self, tokensource):\n        \"\"\"\n        Create drawables for the token content.\n        \"\"\"\n        lineno = charno = maxcharno = 0\n        maxlinelength = linelength = 0\n        for ttype, value in tokensource:\n            while ttype not in self.styles:\n                ttype = ttype.parent\n            style = self.styles[ttype]\n            # TODO: make sure tab expansion happens earlier in the chain.  It\n            # really ought to be done on the input, as to do it right here is\n            # quite complex.\n            value = value.expandtabs(4)\n            lines = value.splitlines(True)\n            # print lines\n            for i, line in enumerate(lines):\n                temp = line.rstrip('\\n')\n                if temp:\n                    self._draw_text(\n                        self._get_text_pos(linelength, lineno),\n                        temp,\n                        font = self._get_style_font(style),\n                        text_fg = self._get_text_color(style),\n                        text_bg = self._get_text_bg_color(style),\n                    )\n                    temp_width, _ = self.fonts.get_text_size(temp)\n                    linelength += temp_width\n                    maxlinelength = max(maxlinelength, linelength)\n                    charno += len(temp)\n                    maxcharno = max(maxcharno, charno)\n                if line.endswith('\\n'):\n                    # add a line for each extra line in the value\n                    linelength = 0\n                    charno = 0\n                    lineno += 1\n        self.maxlinelength = maxlinelength\n        self.maxcharno = maxcharno\n        self.maxlineno = lineno\n\n    def _draw_line_numbers(self):\n        \"\"\"\n        Create drawables for the line numbers.\n        \"\"\"\n        if not self.line_numbers:\n            return\n        for p in range(self.maxlineno):\n            n = p + self.line_number_start\n            if (n % self.line_number_step) == 0:\n                self._draw_linenumber(p, n)\n\n    def _paint_line_number_bg(self, im):\n        \"\"\"\n        Paint the line number background on the image.\n        \"\"\"\n        if not self.line_numbers:\n            return\n        if self.line_number_fg is None:\n            return\n        draw = ImageDraw.Draw(im)\n        recth = im.size[-1]\n        rectw = self.image_pad + self.line_number_width - self.line_number_pad\n        draw.rectangle([(0, 0), (rectw, recth)],\n                       fill=self.line_number_bg)\n        if self.line_number_separator:\n            draw.line([(rectw, 0), (rectw, recth)], fill=self.line_number_fg)\n        del draw\n\n    def format(self, tokensource, outfile):\n        \"\"\"\n        Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``\n        tuples and write it into ``outfile``.\n\n        This implementation calculates where it should draw each token on the\n        pixmap, then calculates the required pixmap size and draws the items.\n        \"\"\"\n        self._create_drawables(tokensource)\n        self._draw_line_numbers()\n        im = Image.new(\n            'RGB',\n            self._get_image_size(self.maxlinelength, self.maxlineno),\n            self.background_color\n        )\n        self._paint_line_number_bg(im)\n        draw = ImageDraw.Draw(im)\n        # Highlight\n        if self.hl_lines:\n            x = self.image_pad + self.line_number_width - self.line_number_pad + 1\n            recth = self._get_line_height()\n            rectw = im.size[0] - x\n            for linenumber in self.hl_lines:\n                y = self._get_line_y(linenumber - 1)\n                draw.rectangle([(x, y), (x + rectw, y + recth)],\n                               fill=self.hl_color)\n        for pos, value, font, text_fg, text_bg in self.drawables:\n            if text_bg:\n                text_size = draw.textsize(text=value, font=font)\n                draw.rectangle([pos[0], pos[1], pos[0] + text_size[0], pos[1] + text_size[1]], fill=text_bg)\n            draw.text(pos, value, font=font, fill=text_fg)\n        im.save(outfile, self.image_format.upper())\n\n\n# Add one formatter per format, so that the \"-f gif\" option gives the correct result\n# when used in pygmentize.\n\nclass GifImageFormatter(ImageFormatter):\n    \"\"\"\n    Create a GIF image from source code. This uses the Python Imaging Library to\n    generate a pixmap from the source code.\n\n    .. versionadded:: 1.0\n    \"\"\"\n\n    name = 'img_gif'\n    aliases = ['gif']\n    filenames = ['*.gif']\n    default_image_format = 'gif'\n\n\nclass JpgImageFormatter(ImageFormatter):\n    \"\"\"\n    Create a JPEG image from source code. This uses the Python Imaging Library to\n    generate a pixmap from the source code.\n\n    .. versionadded:: 1.0\n    \"\"\"\n\n    name = 'img_jpg'\n    aliases = ['jpg', 'jpeg']\n    filenames = ['*.jpg']\n    default_image_format = 'jpeg'\n\n\nclass BmpImageFormatter(ImageFormatter):\n    \"\"\"\n    Create a bitmap image from source code. This uses the Python Imaging Library to\n    generate a pixmap from the source code.\n\n    .. versionadded:: 1.0\n    \"\"\"\n\n    name = 'img_bmp'\n    aliases = ['bmp', 'bitmap']\n    filenames = ['*.bmp']\n    default_image_format = 'bmp'\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatters/irc.py",
    "content": "\"\"\"\n    pygments.formatters.irc\n    ~~~~~~~~~~~~~~~~~~~~~~~\n\n    Formatter for IRC output\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nfrom pip._vendor.pygments.formatter import Formatter\nfrom pip._vendor.pygments.token import Keyword, Name, Comment, String, Error, \\\n    Number, Operator, Generic, Token, Whitespace\nfrom pip._vendor.pygments.util import get_choice_opt\n\n\n__all__ = ['IRCFormatter']\n\n\n#: Map token types to a tuple of color values for light and dark\n#: backgrounds.\nIRC_COLORS = {\n    Token:              ('',            ''),\n\n    Whitespace:         ('gray',   'brightblack'),\n    Comment:            ('gray',   'brightblack'),\n    Comment.Preproc:    ('cyan',        'brightcyan'),\n    Keyword:            ('blue',    'brightblue'),\n    Keyword.Type:       ('cyan',        'brightcyan'),\n    Operator.Word:      ('magenta',      'brightcyan'),\n    Name.Builtin:       ('cyan',        'brightcyan'),\n    Name.Function:      ('green',   'brightgreen'),\n    Name.Namespace:     ('_cyan_',      '_brightcyan_'),\n    Name.Class:         ('_green_', '_brightgreen_'),\n    Name.Exception:     ('cyan',        'brightcyan'),\n    Name.Decorator:     ('brightblack',    'gray'),\n    Name.Variable:      ('red',     'brightred'),\n    Name.Constant:      ('red',     'brightred'),\n    Name.Attribute:     ('cyan',        'brightcyan'),\n    Name.Tag:           ('brightblue',        'brightblue'),\n    String:             ('yellow',       'yellow'),\n    Number:             ('blue',    'brightblue'),\n\n    Generic.Deleted:    ('brightred',        'brightred'),\n    Generic.Inserted:   ('green',  'brightgreen'),\n    Generic.Heading:    ('**',         '**'),\n    Generic.Subheading: ('*magenta*',   '*brightmagenta*'),\n    Generic.Error:      ('brightred',        'brightred'),\n\n    Error:              ('_brightred_',      '_brightred_'),\n}\n\n\nIRC_COLOR_MAP = {\n    'white': 0,\n    'black': 1,\n    'blue': 2,\n    'brightgreen': 3,\n    'brightred': 4,\n    'yellow': 5,\n    'magenta': 6,\n    'orange': 7,\n    'green': 7, #compat w/ ansi\n    'brightyellow': 8,\n    'lightgreen': 9,\n    'brightcyan': 9, # compat w/ ansi\n    'cyan': 10,\n    'lightblue': 11,\n    'red': 11, # compat w/ ansi\n    'brightblue': 12,\n    'brightmagenta': 13,\n    'brightblack': 14,\n    'gray': 15,\n}\n\ndef ircformat(color, text):\n    if len(color) < 1:\n        return text\n    add = sub = ''\n    if '_' in color: # italic\n        add += '\\x1D'\n        sub = '\\x1D' + sub\n        color = color.strip('_')\n    if '*' in color: # bold\n        add += '\\x02'\n        sub = '\\x02' + sub\n        color = color.strip('*')\n    # underline (\\x1F) not supported\n    # backgrounds (\\x03FF,BB) not supported\n    if len(color) > 0: # actual color - may have issues with ircformat(\"red\", \"blah\")+\"10\" type stuff\n        add += '\\x03' + str(IRC_COLOR_MAP[color]).zfill(2)\n        sub = '\\x03' + sub\n    return add + text + sub\n    return '<'+add+'>'+text+'</'+sub+'>'\n\n\nclass IRCFormatter(Formatter):\n    r\"\"\"\n    Format tokens with IRC color sequences\n\n    The `get_style_defs()` method doesn't do anything special since there is\n    no support for common styles.\n\n    Options accepted:\n\n    `bg`\n        Set to ``\"light\"`` or ``\"dark\"`` depending on the terminal's background\n        (default: ``\"light\"``).\n\n    `colorscheme`\n        A dictionary mapping token types to (lightbg, darkbg) color names or\n        ``None`` (default: ``None`` = use builtin colorscheme).\n\n    `linenos`\n        Set to ``True`` to have line numbers in the output as well\n        (default: ``False`` = no line numbers).\n    \"\"\"\n    name = 'IRC'\n    aliases = ['irc', 'IRC']\n    filenames = []\n\n    def __init__(self, **options):\n        Formatter.__init__(self, **options)\n        self.darkbg = get_choice_opt(options, 'bg',\n                                     ['light', 'dark'], 'light') == 'dark'\n        self.colorscheme = options.get('colorscheme', None) or IRC_COLORS\n        self.linenos = options.get('linenos', False)\n        self._lineno = 0\n\n    def _write_lineno(self, outfile):\n        self._lineno += 1\n        outfile.write(\"\\n%04d: \" % self._lineno)\n\n    def _format_unencoded_with_lineno(self, tokensource, outfile):\n        self._write_lineno(outfile)\n\n        for ttype, value in tokensource:\n            if value.endswith(\"\\n\"):\n                self._write_lineno(outfile)\n                value = value[:-1]\n            color = self.colorscheme.get(ttype)\n            while color is None:\n                ttype = ttype.parent\n                color = self.colorscheme.get(ttype)\n            if color:\n                color = color[self.darkbg]\n                spl = value.split('\\n')\n                for line in spl[:-1]:\n                    self._write_lineno(outfile)\n                    if line:\n                        outfile.write(ircformat(color, line[:-1]))\n                if spl[-1]:\n                    outfile.write(ircformat(color, spl[-1]))\n            else:\n                outfile.write(value)\n\n        outfile.write(\"\\n\")\n\n    def format_unencoded(self, tokensource, outfile):\n        if self.linenos:\n            self._format_unencoded_with_lineno(tokensource, outfile)\n            return\n\n        for ttype, value in tokensource:\n            color = self.colorscheme.get(ttype)\n            while color is None:\n                ttype = ttype[:-1]\n                color = self.colorscheme.get(ttype)\n            if color:\n                color = color[self.darkbg]\n                spl = value.split('\\n')\n                for line in spl[:-1]:\n                    if line:\n                        outfile.write(ircformat(color, line))\n                    outfile.write('\\n')\n                if spl[-1]:\n                    outfile.write(ircformat(color, spl[-1]))\n            else:\n                outfile.write(value)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatters/latex.py",
    "content": "\"\"\"\n    pygments.formatters.latex\n    ~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    Formatter for LaTeX fancyvrb output.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nfrom io import StringIO\n\nfrom pip._vendor.pygments.formatter import Formatter\nfrom pip._vendor.pygments.lexer import Lexer, do_insertions\nfrom pip._vendor.pygments.token import Token, STANDARD_TYPES\nfrom pip._vendor.pygments.util import get_bool_opt, get_int_opt\n\n\n__all__ = ['LatexFormatter']\n\n\ndef escape_tex(text, commandprefix):\n    return text.replace('\\\\', '\\x00'). \\\n                replace('{', '\\x01'). \\\n                replace('}', '\\x02'). \\\n                replace('\\x00', r'\\%sZbs{}' % commandprefix). \\\n                replace('\\x01', r'\\%sZob{}' % commandprefix). \\\n                replace('\\x02', r'\\%sZcb{}' % commandprefix). \\\n                replace('^', r'\\%sZca{}' % commandprefix). \\\n                replace('_', r'\\%sZus{}' % commandprefix). \\\n                replace('&', r'\\%sZam{}' % commandprefix). \\\n                replace('<', r'\\%sZlt{}' % commandprefix). \\\n                replace('>', r'\\%sZgt{}' % commandprefix). \\\n                replace('#', r'\\%sZsh{}' % commandprefix). \\\n                replace('%', r'\\%sZpc{}' % commandprefix). \\\n                replace('$', r'\\%sZdl{}' % commandprefix). \\\n                replace('-', r'\\%sZhy{}' % commandprefix). \\\n                replace(\"'\", r'\\%sZsq{}' % commandprefix). \\\n                replace('\"', r'\\%sZdq{}' % commandprefix). \\\n                replace('~', r'\\%sZti{}' % commandprefix)\n\n\nDOC_TEMPLATE = r'''\n\\documentclass{%(docclass)s}\n\\usepackage{fancyvrb}\n\\usepackage{color}\n\\usepackage[%(encoding)s]{inputenc}\n%(preamble)s\n\n%(styledefs)s\n\n\\begin{document}\n\n\\section*{%(title)s}\n\n%(code)s\n\\end{document}\n'''\n\n## Small explanation of the mess below :)\n#\n# The previous version of the LaTeX formatter just assigned a command to\n# each token type defined in the current style.  That obviously is\n# problematic if the highlighted code is produced for a different style\n# than the style commands themselves.\n#\n# This version works much like the HTML formatter which assigns multiple\n# CSS classes to each <span> tag, from the most specific to the least\n# specific token type, thus falling back to the parent token type if one\n# is not defined.  Here, the classes are there too and use the same short\n# forms given in token.STANDARD_TYPES.\n#\n# Highlighted code now only uses one custom command, which by default is\n# \\PY and selectable by the commandprefix option (and in addition the\n# escapes \\PYZat, \\PYZlb and \\PYZrb which haven't been renamed for\n# backwards compatibility purposes).\n#\n# \\PY has two arguments: the classes, separated by +, and the text to\n# render in that style.  The classes are resolved into the respective\n# style commands by magic, which serves to ignore unknown classes.\n#\n# The magic macros are:\n# * \\PY@it, \\PY@bf, etc. are unconditionally wrapped around the text\n#   to render in \\PY@do.  Their definition determines the style.\n# * \\PY@reset resets \\PY@it etc. to do nothing.\n# * \\PY@toks parses the list of classes, using magic inspired by the\n#   keyval package (but modified to use plusses instead of commas\n#   because fancyvrb redefines commas inside its environments).\n# * \\PY@tok processes one class, calling the \\PY@tok@classname command\n#   if it exists.\n# * \\PY@tok@classname sets the \\PY@it etc. to reflect the chosen style\n#   for its class.\n# * \\PY resets the style, parses the classnames and then calls \\PY@do.\n#\n# Tip: to read this code, print it out in substituted form using e.g.\n# >>> print STYLE_TEMPLATE % {'cp': 'PY'}\n\nSTYLE_TEMPLATE = r'''\n\\makeatletter\n\\def\\%(cp)s@reset{\\let\\%(cp)s@it=\\relax \\let\\%(cp)s@bf=\\relax%%\n    \\let\\%(cp)s@ul=\\relax \\let\\%(cp)s@tc=\\relax%%\n    \\let\\%(cp)s@bc=\\relax \\let\\%(cp)s@ff=\\relax}\n\\def\\%(cp)s@tok#1{\\csname %(cp)s@tok@#1\\endcsname}\n\\def\\%(cp)s@toks#1+{\\ifx\\relax#1\\empty\\else%%\n    \\%(cp)s@tok{#1}\\expandafter\\%(cp)s@toks\\fi}\n\\def\\%(cp)s@do#1{\\%(cp)s@bc{\\%(cp)s@tc{\\%(cp)s@ul{%%\n    \\%(cp)s@it{\\%(cp)s@bf{\\%(cp)s@ff{#1}}}}}}}\n\\def\\%(cp)s#1#2{\\%(cp)s@reset\\%(cp)s@toks#1+\\relax+\\%(cp)s@do{#2}}\n\n%(styles)s\n\n\\def\\%(cp)sZbs{\\char`\\\\}\n\\def\\%(cp)sZus{\\char`\\_}\n\\def\\%(cp)sZob{\\char`\\{}\n\\def\\%(cp)sZcb{\\char`\\}}\n\\def\\%(cp)sZca{\\char`\\^}\n\\def\\%(cp)sZam{\\char`\\&}\n\\def\\%(cp)sZlt{\\char`\\<}\n\\def\\%(cp)sZgt{\\char`\\>}\n\\def\\%(cp)sZsh{\\char`\\#}\n\\def\\%(cp)sZpc{\\char`\\%%}\n\\def\\%(cp)sZdl{\\char`\\$}\n\\def\\%(cp)sZhy{\\char`\\-}\n\\def\\%(cp)sZsq{\\char`\\'}\n\\def\\%(cp)sZdq{\\char`\\\"}\n\\def\\%(cp)sZti{\\char`\\~}\n%% for compatibility with earlier versions\n\\def\\%(cp)sZat{@}\n\\def\\%(cp)sZlb{[}\n\\def\\%(cp)sZrb{]}\n\\makeatother\n'''\n\n\ndef _get_ttype_name(ttype):\n    fname = STANDARD_TYPES.get(ttype)\n    if fname:\n        return fname\n    aname = ''\n    while fname is None:\n        aname = ttype[-1] + aname\n        ttype = ttype.parent\n        fname = STANDARD_TYPES.get(ttype)\n    return fname + aname\n\n\nclass LatexFormatter(Formatter):\n    r\"\"\"\n    Format tokens as LaTeX code. This needs the `fancyvrb` and `color`\n    standard packages.\n\n    Without the `full` option, code is formatted as one ``Verbatim``\n    environment, like this:\n\n    .. sourcecode:: latex\n\n        \\begin{Verbatim}[commandchars=\\\\\\{\\}]\n        \\PY{k}{def }\\PY{n+nf}{foo}(\\PY{n}{bar}):\n            \\PY{k}{pass}\n        \\end{Verbatim}\n\n    Wrapping can be disabled using the `nowrap` option.\n\n    The special command used here (``\\PY``) and all the other macros it needs\n    are output by the `get_style_defs` method.\n\n    With the `full` option, a complete LaTeX document is output, including\n    the command definitions in the preamble.\n\n    The `get_style_defs()` method of a `LatexFormatter` returns a string\n    containing ``\\def`` commands defining the macros needed inside the\n    ``Verbatim`` environments.\n\n    Additional options accepted:\n\n    `nowrap`\n        If set to ``True``, don't wrap the tokens at all, not even inside a\n        ``\\begin{Verbatim}`` environment. This disables most other options\n        (default: ``False``).\n\n    `style`\n        The style to use, can be a string or a Style subclass (default:\n        ``'default'``).\n\n    `full`\n        Tells the formatter to output a \"full\" document, i.e. a complete\n        self-contained document (default: ``False``).\n\n    `title`\n        If `full` is true, the title that should be used to caption the\n        document (default: ``''``).\n\n    `docclass`\n        If the `full` option is enabled, this is the document class to use\n        (default: ``'article'``).\n\n    `preamble`\n        If the `full` option is enabled, this can be further preamble commands,\n        e.g. ``\\usepackage`` (default: ``''``).\n\n    `linenos`\n        If set to ``True``, output line numbers (default: ``False``).\n\n    `linenostart`\n        The line number for the first line (default: ``1``).\n\n    `linenostep`\n        If set to a number n > 1, only every nth line number is printed.\n\n    `verboptions`\n        Additional options given to the Verbatim environment (see the *fancyvrb*\n        docs for possible values) (default: ``''``).\n\n    `commandprefix`\n        The LaTeX commands used to produce colored output are constructed\n        using this prefix and some letters (default: ``'PY'``).\n\n        .. versionadded:: 0.7\n        .. versionchanged:: 0.10\n           The default is now ``'PY'`` instead of ``'C'``.\n\n    `texcomments`\n        If set to ``True``, enables LaTeX comment lines.  That is, LaTex markup\n        in comment tokens is not escaped so that LaTeX can render it (default:\n        ``False``).\n\n        .. versionadded:: 1.2\n\n    `mathescape`\n        If set to ``True``, enables LaTeX math mode escape in comments. That\n        is, ``'$...$'`` inside a comment will trigger math mode (default:\n        ``False``).\n\n        .. versionadded:: 1.2\n\n    `escapeinside`\n        If set to a string of length 2, enables escaping to LaTeX. Text\n        delimited by these 2 characters is read as LaTeX code and\n        typeset accordingly. It has no effect in string literals. It has\n        no effect in comments if `texcomments` or `mathescape` is\n        set. (default: ``''``).\n\n        .. versionadded:: 2.0\n\n    `envname`\n        Allows you to pick an alternative environment name replacing Verbatim.\n        The alternate environment still has to support Verbatim's option syntax.\n        (default: ``'Verbatim'``).\n\n        .. versionadded:: 2.0\n    \"\"\"\n    name = 'LaTeX'\n    aliases = ['latex', 'tex']\n    filenames = ['*.tex']\n\n    def __init__(self, **options):\n        Formatter.__init__(self, **options)\n        self.nowrap = get_bool_opt(options, 'nowrap', False)\n        self.docclass = options.get('docclass', 'article')\n        self.preamble = options.get('preamble', '')\n        self.linenos = get_bool_opt(options, 'linenos', False)\n        self.linenostart = abs(get_int_opt(options, 'linenostart', 1))\n        self.linenostep = abs(get_int_opt(options, 'linenostep', 1))\n        self.verboptions = options.get('verboptions', '')\n        self.nobackground = get_bool_opt(options, 'nobackground', False)\n        self.commandprefix = options.get('commandprefix', 'PY')\n        self.texcomments = get_bool_opt(options, 'texcomments', False)\n        self.mathescape = get_bool_opt(options, 'mathescape', False)\n        self.escapeinside = options.get('escapeinside', '')\n        if len(self.escapeinside) == 2:\n            self.left = self.escapeinside[0]\n            self.right = self.escapeinside[1]\n        else:\n            self.escapeinside = ''\n        self.envname = options.get('envname', 'Verbatim')\n\n        self._create_stylesheet()\n\n    def _create_stylesheet(self):\n        t2n = self.ttype2name = {Token: ''}\n        c2d = self.cmd2def = {}\n        cp = self.commandprefix\n\n        def rgbcolor(col):\n            if col:\n                return ','.join(['%.2f' % (int(col[i] + col[i + 1], 16) / 255.0)\n                                 for i in (0, 2, 4)])\n            else:\n                return '1,1,1'\n\n        for ttype, ndef in self.style:\n            name = _get_ttype_name(ttype)\n            cmndef = ''\n            if ndef['bold']:\n                cmndef += r'\\let\\$$@bf=\\textbf'\n            if ndef['italic']:\n                cmndef += r'\\let\\$$@it=\\textit'\n            if ndef['underline']:\n                cmndef += r'\\let\\$$@ul=\\underline'\n            if ndef['roman']:\n                cmndef += r'\\let\\$$@ff=\\textrm'\n            if ndef['sans']:\n                cmndef += r'\\let\\$$@ff=\\textsf'\n            if ndef['mono']:\n                cmndef += r'\\let\\$$@ff=\\textsf'\n            if ndef['color']:\n                cmndef += (r'\\def\\$$@tc##1{\\textcolor[rgb]{%s}{##1}}' %\n                           rgbcolor(ndef['color']))\n            if ndef['border']:\n                cmndef += (r'\\def\\$$@bc##1{{\\setlength{\\fboxsep}{\\string -\\fboxrule}'\n                           r'\\fcolorbox[rgb]{%s}{%s}{\\strut ##1}}}' %\n                           (rgbcolor(ndef['border']),\n                            rgbcolor(ndef['bgcolor'])))\n            elif ndef['bgcolor']:\n                cmndef += (r'\\def\\$$@bc##1{{\\setlength{\\fboxsep}{0pt}'\n                           r'\\colorbox[rgb]{%s}{\\strut ##1}}}' %\n                           rgbcolor(ndef['bgcolor']))\n            if cmndef == '':\n                continue\n            cmndef = cmndef.replace('$$', cp)\n            t2n[ttype] = name\n            c2d[name] = cmndef\n\n    def get_style_defs(self, arg=''):\n        \"\"\"\n        Return the command sequences needed to define the commands\n        used to format text in the verbatim environment. ``arg`` is ignored.\n        \"\"\"\n        cp = self.commandprefix\n        styles = []\n        for name, definition in self.cmd2def.items():\n            styles.append(r'\\@namedef{%s@tok@%s}{%s}' % (cp, name, definition))\n        return STYLE_TEMPLATE % {'cp': self.commandprefix,\n                                 'styles': '\\n'.join(styles)}\n\n    def format_unencoded(self, tokensource, outfile):\n        # TODO: add support for background colors\n        t2n = self.ttype2name\n        cp = self.commandprefix\n\n        if self.full:\n            realoutfile = outfile\n            outfile = StringIO()\n\n        if not self.nowrap:\n            outfile.write('\\\\begin{' + self.envname + '}[commandchars=\\\\\\\\\\\\{\\\\}')\n            if self.linenos:\n                start, step = self.linenostart, self.linenostep\n                outfile.write(',numbers=left' +\n                              (start and ',firstnumber=%d' % start or '') +\n                              (step and ',stepnumber=%d' % step or ''))\n            if self.mathescape or self.texcomments or self.escapeinside:\n                outfile.write(',codes={\\\\catcode`\\\\$=3\\\\catcode`\\\\^=7'\n                              '\\\\catcode`\\\\_=8\\\\relax}')\n            if self.verboptions:\n                outfile.write(',' + self.verboptions)\n            outfile.write(']\\n')\n\n        for ttype, value in tokensource:\n            if ttype in Token.Comment:\n                if self.texcomments:\n                    # Try to guess comment starting lexeme and escape it ...\n                    start = value[0:1]\n                    for i in range(1, len(value)):\n                        if start[0] != value[i]:\n                            break\n                        start += value[i]\n\n                    value = value[len(start):]\n                    start = escape_tex(start, cp)\n\n                    # ... but do not escape inside comment.\n                    value = start + value\n                elif self.mathescape:\n                    # Only escape parts not inside a math environment.\n                    parts = value.split('$')\n                    in_math = False\n                    for i, part in enumerate(parts):\n                        if not in_math:\n                            parts[i] = escape_tex(part, cp)\n                        in_math = not in_math\n                    value = '$'.join(parts)\n                elif self.escapeinside:\n                    text = value\n                    value = ''\n                    while text:\n                        a, sep1, text = text.partition(self.left)\n                        if sep1:\n                            b, sep2, text = text.partition(self.right)\n                            if sep2:\n                                value += escape_tex(a, cp) + b\n                            else:\n                                value += escape_tex(a + sep1 + b, cp)\n                        else:\n                            value += escape_tex(a, cp)\n                else:\n                    value = escape_tex(value, cp)\n            elif ttype not in Token.Escape:\n                value = escape_tex(value, cp)\n            styles = []\n            while ttype is not Token:\n                try:\n                    styles.append(t2n[ttype])\n                except KeyError:\n                    # not in current style\n                    styles.append(_get_ttype_name(ttype))\n                ttype = ttype.parent\n            styleval = '+'.join(reversed(styles))\n            if styleval:\n                spl = value.split('\\n')\n                for line in spl[:-1]:\n                    if line:\n                        outfile.write(\"\\\\%s{%s}{%s}\" % (cp, styleval, line))\n                    outfile.write('\\n')\n                if spl[-1]:\n                    outfile.write(\"\\\\%s{%s}{%s}\" % (cp, styleval, spl[-1]))\n            else:\n                outfile.write(value)\n\n        if not self.nowrap:\n            outfile.write('\\\\end{' + self.envname + '}\\n')\n\n        if self.full:\n            encoding = self.encoding or 'utf8'\n            # map known existings encodings from LaTeX distribution\n            encoding = {\n                'utf_8': 'utf8',\n                'latin_1': 'latin1',\n                'iso_8859_1': 'latin1',\n            }.get(encoding.replace('-', '_'), encoding)\n            realoutfile.write(DOC_TEMPLATE %\n                dict(docclass  = self.docclass,\n                     preamble  = self.preamble,\n                     title     = self.title,\n                     encoding  = encoding,\n                     styledefs = self.get_style_defs(),\n                     code      = outfile.getvalue()))\n\n\nclass LatexEmbeddedLexer(Lexer):\n    \"\"\"\n    This lexer takes one lexer as argument, the lexer for the language\n    being formatted, and the left and right delimiters for escaped text.\n\n    First everything is scanned using the language lexer to obtain\n    strings and comments. All other consecutive tokens are merged and\n    the resulting text is scanned for escaped segments, which are given\n    the Token.Escape type. Finally text that is not escaped is scanned\n    again with the language lexer.\n    \"\"\"\n    def __init__(self, left, right, lang, **options):\n        self.left = left\n        self.right = right\n        self.lang = lang\n        Lexer.__init__(self, **options)\n\n    def get_tokens_unprocessed(self, text):\n        # find and remove all the escape tokens (replace with an empty string)\n        # this is very similar to DelegatingLexer.get_tokens_unprocessed.\n        buffered = ''\n        insertions = []\n        insertion_buf = []\n        for i, t, v in self._find_safe_escape_tokens(text):\n            if t is None:\n                if insertion_buf:\n                    insertions.append((len(buffered), insertion_buf))\n                    insertion_buf = []\n                buffered += v\n            else:\n                insertion_buf.append((i, t, v))\n        if insertion_buf:\n            insertions.append((len(buffered), insertion_buf))\n        return do_insertions(insertions,\n                             self.lang.get_tokens_unprocessed(buffered))\n\n    def _find_safe_escape_tokens(self, text):\n        \"\"\" find escape tokens that are not in strings or comments \"\"\"\n        for i, t, v in self._filter_to(\n            self.lang.get_tokens_unprocessed(text),\n            lambda t: t in Token.Comment or t in Token.String\n        ):\n            if t is None:\n                for i2, t2, v2 in self._find_escape_tokens(v):\n                    yield i + i2, t2, v2\n            else:\n                yield i, None, v\n\n    def _filter_to(self, it, pred):\n        \"\"\" Keep only the tokens that match `pred`, merge the others together \"\"\"\n        buf = ''\n        idx = 0\n        for i, t, v in it:\n            if pred(t):\n                if buf:\n                    yield idx, None, buf\n                    buf = ''\n                yield i, t, v\n            else:\n                if not buf:\n                    idx = i\n                buf += v\n        if buf:\n            yield idx, None, buf\n\n    def _find_escape_tokens(self, text):\n        \"\"\" Find escape tokens within text, give token=None otherwise \"\"\"\n        index = 0\n        while text:\n            a, sep1, text = text.partition(self.left)\n            if a:\n                yield index, None, a\n                index += len(a)\n            if sep1:\n                b, sep2, text = text.partition(self.right)\n                if sep2:\n                    yield index + len(sep1), Token.Escape, b\n                    index += len(sep1) + len(b) + len(sep2)\n                else:\n                    yield index, Token.Error, sep1\n                    index += len(sep1)\n                    text = b\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatters/other.py",
    "content": "\"\"\"\n    pygments.formatters.other\n    ~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    Other formatters: NullFormatter, RawTokenFormatter.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nfrom pip._vendor.pygments.formatter import Formatter\nfrom pip._vendor.pygments.util import get_choice_opt\nfrom pip._vendor.pygments.token import Token\nfrom pip._vendor.pygments.console import colorize\n\n__all__ = ['NullFormatter', 'RawTokenFormatter', 'TestcaseFormatter']\n\n\nclass NullFormatter(Formatter):\n    \"\"\"\n    Output the text unchanged without any formatting.\n    \"\"\"\n    name = 'Text only'\n    aliases = ['text', 'null']\n    filenames = ['*.txt']\n\n    def format(self, tokensource, outfile):\n        enc = self.encoding\n        for ttype, value in tokensource:\n            if enc:\n                outfile.write(value.encode(enc))\n            else:\n                outfile.write(value)\n\n\nclass RawTokenFormatter(Formatter):\n    r\"\"\"\n    Format tokens as a raw representation for storing token streams.\n\n    The format is ``tokentype<TAB>repr(tokenstring)\\n``. The output can later\n    be converted to a token stream with the `RawTokenLexer`, described in the\n    :doc:`lexer list <lexers>`.\n\n    Only two options are accepted:\n\n    `compress`\n        If set to ``'gz'`` or ``'bz2'``, compress the output with the given\n        compression algorithm after encoding (default: ``''``).\n    `error_color`\n        If set to a color name, highlight error tokens using that color.  If\n        set but with no value, defaults to ``'red'``.\n\n        .. versionadded:: 0.11\n\n    \"\"\"\n    name = 'Raw tokens'\n    aliases = ['raw', 'tokens']\n    filenames = ['*.raw']\n\n    unicodeoutput = False\n\n    def __init__(self, **options):\n        Formatter.__init__(self, **options)\n        # We ignore self.encoding if it is set, since it gets set for lexer\n        # and formatter if given with -Oencoding on the command line.\n        # The RawTokenFormatter outputs only ASCII. Override here.\n        self.encoding = 'ascii'  # let pygments.format() do the right thing\n        self.compress = get_choice_opt(options, 'compress',\n                                       ['', 'none', 'gz', 'bz2'], '')\n        self.error_color = options.get('error_color', None)\n        if self.error_color is True:\n            self.error_color = 'red'\n        if self.error_color is not None:\n            try:\n                colorize(self.error_color, '')\n            except KeyError:\n                raise ValueError(\"Invalid color %r specified\" %\n                                 self.error_color)\n\n    def format(self, tokensource, outfile):\n        try:\n            outfile.write(b'')\n        except TypeError:\n            raise TypeError('The raw tokens formatter needs a binary '\n                            'output file')\n        if self.compress == 'gz':\n            import gzip\n            outfile = gzip.GzipFile('', 'wb', 9, outfile)\n\n            write = outfile.write\n            flush = outfile.close\n        elif self.compress == 'bz2':\n            import bz2\n            compressor = bz2.BZ2Compressor(9)\n\n            def write(text):\n                outfile.write(compressor.compress(text))\n\n            def flush():\n                outfile.write(compressor.flush())\n                outfile.flush()\n        else:\n            write = outfile.write\n            flush = outfile.flush\n\n        if self.error_color:\n            for ttype, value in tokensource:\n                line = b\"%r\\t%r\\n\" % (ttype, value)\n                if ttype is Token.Error:\n                    write(colorize(self.error_color, line))\n                else:\n                    write(line)\n        else:\n            for ttype, value in tokensource:\n                write(b\"%r\\t%r\\n\" % (ttype, value))\n        flush()\n\n\nTESTCASE_BEFORE = '''\\\n    def testNeedsName(lexer):\n        fragment = %r\n        tokens = [\n'''\nTESTCASE_AFTER = '''\\\n        ]\n        assert list(lexer.get_tokens(fragment)) == tokens\n'''\n\n\nclass TestcaseFormatter(Formatter):\n    \"\"\"\n    Format tokens as appropriate for a new testcase.\n\n    .. versionadded:: 2.0\n    \"\"\"\n    name = 'Testcase'\n    aliases = ['testcase']\n\n    def __init__(self, **options):\n        Formatter.__init__(self, **options)\n        if self.encoding is not None and self.encoding != 'utf-8':\n            raise ValueError(\"Only None and utf-8 are allowed encodings.\")\n\n    def format(self, tokensource, outfile):\n        indentation = ' ' * 12\n        rawbuf = []\n        outbuf = []\n        for ttype, value in tokensource:\n            rawbuf.append(value)\n            outbuf.append('%s(%s, %r),\\n' % (indentation, ttype, value))\n\n        before = TESTCASE_BEFORE % (''.join(rawbuf),)\n        during = ''.join(outbuf)\n        after = TESTCASE_AFTER\n        if self.encoding is None:\n            outfile.write(before + during + after)\n        else:\n            outfile.write(before.encode('utf-8'))\n            outfile.write(during.encode('utf-8'))\n            outfile.write(after.encode('utf-8'))\n        outfile.flush()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatters/pangomarkup.py",
    "content": "\"\"\"\n    pygments.formatters.pangomarkup\n    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    Formatter for Pango markup output.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nfrom pip._vendor.pygments.formatter import Formatter\n\n\n__all__ = ['PangoMarkupFormatter']\n\n\n_escape_table = {\n    ord('&'): '&amp;',\n    ord('<'): '&lt;',\n}\n\n\ndef escape_special_chars(text, table=_escape_table):\n    \"\"\"Escape & and < for Pango Markup.\"\"\"\n    return text.translate(table)\n\n\nclass PangoMarkupFormatter(Formatter):\n    \"\"\"\n    Format tokens as Pango Markup code. It can then be rendered to an SVG.\n\n    .. versionadded:: 2.9\n    \"\"\"\n\n    name = 'Pango Markup'\n    aliases = ['pango', 'pangomarkup']\n    filenames = []\n\n    def __init__(self, **options):\n        Formatter.__init__(self, **options)\n\n        self.styles = {}\n\n        for token, style in self.style:\n            start = ''\n            end = ''\n            if style['color']:\n                start += '<span fgcolor=\"#%s\">' % style['color']\n                end = '</span>' + end\n            if style['bold']:\n                start += '<b>'\n                end = '</b>' + end\n            if style['italic']:\n                start += '<i>'\n                end = '</i>' + end\n            if style['underline']:\n                start += '<u>'\n                end = '</u>' + end\n            self.styles[token] = (start, end)\n\n    def format_unencoded(self, tokensource, outfile):\n        lastval = ''\n        lasttype = None\n\n        outfile.write('<tt>')\n\n        for ttype, value in tokensource:\n            while ttype not in self.styles:\n                ttype = ttype.parent\n            if ttype == lasttype:\n                lastval += escape_special_chars(value)\n            else:\n                if lastval:\n                    stylebegin, styleend = self.styles[lasttype]\n                    outfile.write(stylebegin + lastval + styleend)\n                lastval = escape_special_chars(value)\n                lasttype = ttype\n\n        if lastval:\n            stylebegin, styleend = self.styles[lasttype]\n            outfile.write(stylebegin + lastval + styleend)\n\n        outfile.write('</tt>')\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatters/rtf.py",
    "content": "\"\"\"\n    pygments.formatters.rtf\n    ~~~~~~~~~~~~~~~~~~~~~~~\n\n    A formatter that generates RTF files.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nfrom pip._vendor.pygments.formatter import Formatter\nfrom pip._vendor.pygments.util import get_int_opt, surrogatepair\n\n\n__all__ = ['RtfFormatter']\n\n\nclass RtfFormatter(Formatter):\n    \"\"\"\n    Format tokens as RTF markup. This formatter automatically outputs full RTF\n    documents with color information and other useful stuff. Perfect for Copy and\n    Paste into Microsoft(R) Word(R) documents.\n\n    Please note that ``encoding`` and ``outencoding`` options are ignored.\n    The RTF format is ASCII natively, but handles unicode characters correctly\n    thanks to escape sequences.\n\n    .. versionadded:: 0.6\n\n    Additional options accepted:\n\n    `style`\n        The style to use, can be a string or a Style subclass (default:\n        ``'default'``).\n\n    `fontface`\n        The used font family, for example ``Bitstream Vera Sans``. Defaults to\n        some generic font which is supposed to have fixed width.\n\n    `fontsize`\n        Size of the font used. Size is specified in half points. The\n        default is 24 half-points, giving a size 12 font.\n\n        .. versionadded:: 2.0\n    \"\"\"\n    name = 'RTF'\n    aliases = ['rtf']\n    filenames = ['*.rtf']\n\n    def __init__(self, **options):\n        r\"\"\"\n        Additional options accepted:\n\n        ``fontface``\n            Name of the font used. Could for example be ``'Courier New'``\n            to further specify the default which is ``'\\fmodern'``. The RTF\n            specification claims that ``\\fmodern`` are \"Fixed-pitch serif\n            and sans serif fonts\". Hope every RTF implementation thinks\n            the same about modern...\n\n        \"\"\"\n        Formatter.__init__(self, **options)\n        self.fontface = options.get('fontface') or ''\n        self.fontsize = get_int_opt(options, 'fontsize', 0)\n\n    def _escape(self, text):\n        return text.replace('\\\\', '\\\\\\\\') \\\n                   .replace('{', '\\\\{') \\\n                   .replace('}', '\\\\}')\n\n    def _escape_text(self, text):\n        # empty strings, should give a small performance improvement\n        if not text:\n            return ''\n\n        # escape text\n        text = self._escape(text)\n\n        buf = []\n        for c in text:\n            cn = ord(c)\n            if cn < (2**7):\n                # ASCII character\n                buf.append(str(c))\n            elif (2**7) <= cn < (2**16):\n                # single unicode escape sequence\n                buf.append('{\\\\u%d}' % cn)\n            elif (2**16) <= cn:\n                # RTF limits unicode to 16 bits.\n                # Force surrogate pairs\n                buf.append('{\\\\u%d}{\\\\u%d}' % surrogatepair(cn))\n\n        return ''.join(buf).replace('\\n', '\\\\par\\n')\n\n    def format_unencoded(self, tokensource, outfile):\n        # rtf 1.8 header\n        outfile.write('{\\\\rtf1\\\\ansi\\\\uc0\\\\deff0'\n                      '{\\\\fonttbl{\\\\f0\\\\fmodern\\\\fprq1\\\\fcharset0%s;}}'\n                      '{\\\\colortbl;' % (self.fontface and\n                                        ' ' + self._escape(self.fontface) or\n                                        ''))\n\n        # convert colors and save them in a mapping to access them later.\n        color_mapping = {}\n        offset = 1\n        for _, style in self.style:\n            for color in style['color'], style['bgcolor'], style['border']:\n                if color and color not in color_mapping:\n                    color_mapping[color] = offset\n                    outfile.write('\\\\red%d\\\\green%d\\\\blue%d;' % (\n                        int(color[0:2], 16),\n                        int(color[2:4], 16),\n                        int(color[4:6], 16)\n                    ))\n                    offset += 1\n        outfile.write('}\\\\f0 ')\n        if self.fontsize:\n            outfile.write('\\\\fs%d' % self.fontsize)\n\n        # highlight stream\n        for ttype, value in tokensource:\n            while not self.style.styles_token(ttype) and ttype.parent:\n                ttype = ttype.parent\n            style = self.style.style_for_token(ttype)\n            buf = []\n            if style['bgcolor']:\n                buf.append('\\\\cb%d' % color_mapping[style['bgcolor']])\n            if style['color']:\n                buf.append('\\\\cf%d' % color_mapping[style['color']])\n            if style['bold']:\n                buf.append('\\\\b')\n            if style['italic']:\n                buf.append('\\\\i')\n            if style['underline']:\n                buf.append('\\\\ul')\n            if style['border']:\n                buf.append('\\\\chbrdr\\\\chcfpat%d' %\n                           color_mapping[style['border']])\n            start = ''.join(buf)\n            if start:\n                outfile.write('{%s ' % start)\n            outfile.write(self._escape_text(value))\n            if start:\n                outfile.write('}')\n\n        outfile.write('}')\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatters/svg.py",
    "content": "\"\"\"\n    pygments.formatters.svg\n    ~~~~~~~~~~~~~~~~~~~~~~~\n\n    Formatter for SVG output.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nfrom pip._vendor.pygments.formatter import Formatter\nfrom pip._vendor.pygments.token import Comment\nfrom pip._vendor.pygments.util import get_bool_opt, get_int_opt\n\n__all__ = ['SvgFormatter']\n\n\ndef escape_html(text):\n    \"\"\"Escape &, <, > as well as single and double quotes for HTML.\"\"\"\n    return text.replace('&', '&amp;').  \\\n                replace('<', '&lt;').   \\\n                replace('>', '&gt;').   \\\n                replace('\"', '&quot;'). \\\n                replace(\"'\", '&#39;')\n\n\nclass2style = {}\n\nclass SvgFormatter(Formatter):\n    \"\"\"\n    Format tokens as an SVG graphics file.  This formatter is still experimental.\n    Each line of code is a ``<text>`` element with explicit ``x`` and ``y``\n    coordinates containing ``<tspan>`` elements with the individual token styles.\n\n    By default, this formatter outputs a full SVG document including doctype\n    declaration and the ``<svg>`` root element.\n\n    .. versionadded:: 0.9\n\n    Additional options accepted:\n\n    `nowrap`\n        Don't wrap the SVG ``<text>`` elements in ``<svg><g>`` elements and\n        don't add a XML declaration and a doctype.  If true, the `fontfamily`\n        and `fontsize` options are ignored.  Defaults to ``False``.\n\n    `fontfamily`\n        The value to give the wrapping ``<g>`` element's ``font-family``\n        attribute, defaults to ``\"monospace\"``.\n\n    `fontsize`\n        The value to give the wrapping ``<g>`` element's ``font-size``\n        attribute, defaults to ``\"14px\"``.\n\n    `linenos`\n        If ``True``, add line numbers (default: ``False``).\n\n    `linenostart`\n        The line number for the first line (default: ``1``).\n\n    `linenostep`\n        If set to a number n > 1, only every nth line number is printed.\n        \n    `linenowidth`\n        Maximum width devoted to line numbers (default: ``3*ystep``, sufficient\n        for up to 4-digit line numbers. Increase width for longer code blocks).  \n        \n    `xoffset`\n        Starting offset in X direction, defaults to ``0``.\n\n    `yoffset`\n        Starting offset in Y direction, defaults to the font size if it is given\n        in pixels, or ``20`` else.  (This is necessary since text coordinates\n        refer to the text baseline, not the top edge.)\n\n    `ystep`\n        Offset to add to the Y coordinate for each subsequent line.  This should\n        roughly be the text size plus 5.  It defaults to that value if the text\n        size is given in pixels, or ``25`` else.\n\n    `spacehack`\n        Convert spaces in the source to ``&#160;``, which are non-breaking\n        spaces.  SVG provides the ``xml:space`` attribute to control how\n        whitespace inside tags is handled, in theory, the ``preserve`` value\n        could be used to keep all whitespace as-is.  However, many current SVG\n        viewers don't obey that rule, so this option is provided as a workaround\n        and defaults to ``True``.\n    \"\"\"\n    name = 'SVG'\n    aliases = ['svg']\n    filenames = ['*.svg']\n\n    def __init__(self, **options):\n        Formatter.__init__(self, **options)\n        self.nowrap = get_bool_opt(options, 'nowrap', False)\n        self.fontfamily = options.get('fontfamily', 'monospace')\n        self.fontsize = options.get('fontsize', '14px')\n        self.xoffset = get_int_opt(options, 'xoffset', 0)\n        fs = self.fontsize.strip()\n        if fs.endswith('px'): fs = fs[:-2].strip()\n        try:\n            int_fs = int(fs)\n        except:\n            int_fs = 20\n        self.yoffset = get_int_opt(options, 'yoffset', int_fs)\n        self.ystep = get_int_opt(options, 'ystep', int_fs + 5)\n        self.spacehack = get_bool_opt(options, 'spacehack', True)\n        self.linenos = get_bool_opt(options,'linenos',False)\n        self.linenostart = get_int_opt(options,'linenostart',1)\n        self.linenostep = get_int_opt(options,'linenostep',1)\n        self.linenowidth = get_int_opt(options,'linenowidth', 3*self.ystep)\n        self._stylecache = {}\n\n    def format_unencoded(self, tokensource, outfile):\n        \"\"\"\n        Format ``tokensource``, an iterable of ``(tokentype, tokenstring)``\n        tuples and write it into ``outfile``.\n\n        For our implementation we put all lines in their own 'line group'.\n        \"\"\"\n        x = self.xoffset\n        y = self.yoffset\n        if not self.nowrap:\n            if self.encoding:\n                outfile.write('<?xml version=\"1.0\" encoding=\"%s\"?>\\n' %\n                              self.encoding)\n            else:\n                outfile.write('<?xml version=\"1.0\"?>\\n')\n            outfile.write('<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.0//EN\" '\n                          '\"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/'\n                          'svg10.dtd\">\\n')\n            outfile.write('<svg xmlns=\"http://www.w3.org/2000/svg\">\\n')\n            outfile.write('<g font-family=\"%s\" font-size=\"%s\">\\n' %\n                          (self.fontfamily, self.fontsize))\n        \n        counter = self.linenostart \n        counter_step = self.linenostep\n        counter_style = self._get_style(Comment)\n        line_x = x\n        \n        if self.linenos:\n            if counter % counter_step == 0:\n                outfile.write('<text x=\"%s\" y=\"%s\" %s text-anchor=\"end\">%s</text>' %\n                    (x+self.linenowidth,y,counter_style,counter))\n            line_x += self.linenowidth + self.ystep\n            counter += 1\n\n        outfile.write('<text x=\"%s\" y=\"%s\" xml:space=\"preserve\">' % (line_x, y))\n        for ttype, value in tokensource:\n            style = self._get_style(ttype)\n            tspan = style and '<tspan' + style + '>' or ''\n            tspanend = tspan and '</tspan>' or ''\n            value = escape_html(value)\n            if self.spacehack:\n                value = value.expandtabs().replace(' ', '&#160;')\n            parts = value.split('\\n')\n            for part in parts[:-1]:\n                outfile.write(tspan + part + tspanend)\n                y += self.ystep\n                outfile.write('</text>\\n')\n                if self.linenos and counter % counter_step == 0:\n                    outfile.write('<text x=\"%s\" y=\"%s\" text-anchor=\"end\" %s>%s</text>' %\n                        (x+self.linenowidth,y,counter_style,counter))\n                \n                counter += 1\n                outfile.write('<text x=\"%s\" y=\"%s\" ' 'xml:space=\"preserve\">' % (line_x,y))\n            outfile.write(tspan + parts[-1] + tspanend)\n        outfile.write('</text>')\n\n        if not self.nowrap:\n            outfile.write('</g></svg>\\n')\n\n    def _get_style(self, tokentype):\n        if tokentype in self._stylecache:\n            return self._stylecache[tokentype]\n        otokentype = tokentype\n        while not self.style.styles_token(tokentype):\n            tokentype = tokentype.parent\n        value = self.style.style_for_token(tokentype)\n        result = ''\n        if value['color']:\n            result = ' fill=\"#' + value['color'] + '\"'\n        if value['bold']:\n            result += ' font-weight=\"bold\"'\n        if value['italic']:\n            result += ' font-style=\"italic\"'\n        self._stylecache[otokentype] = result\n        return result\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatters/terminal.py",
    "content": "\"\"\"\n    pygments.formatters.terminal\n    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    Formatter for terminal output with ANSI sequences.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nfrom pip._vendor.pygments.formatter import Formatter\nfrom pip._vendor.pygments.token import Keyword, Name, Comment, String, Error, \\\n    Number, Operator, Generic, Token, Whitespace\nfrom pip._vendor.pygments.console import ansiformat\nfrom pip._vendor.pygments.util import get_choice_opt\n\n\n__all__ = ['TerminalFormatter']\n\n\n#: Map token types to a tuple of color values for light and dark\n#: backgrounds.\nTERMINAL_COLORS = {\n    Token:              ('',            ''),\n\n    Whitespace:         ('gray',   'brightblack'),\n    Comment:            ('gray',   'brightblack'),\n    Comment.Preproc:    ('cyan',        'brightcyan'),\n    Keyword:            ('blue',    'brightblue'),\n    Keyword.Type:       ('cyan',        'brightcyan'),\n    Operator.Word:      ('magenta',      'brightmagenta'),\n    Name.Builtin:       ('cyan',        'brightcyan'),\n    Name.Function:      ('green',   'brightgreen'),\n    Name.Namespace:     ('_cyan_',      '_brightcyan_'),\n    Name.Class:         ('_green_', '_brightgreen_'),\n    Name.Exception:     ('cyan',        'brightcyan'),\n    Name.Decorator:     ('brightblack',    'gray'),\n    Name.Variable:      ('red',     'brightred'),\n    Name.Constant:      ('red',     'brightred'),\n    Name.Attribute:     ('cyan',        'brightcyan'),\n    Name.Tag:           ('brightblue',        'brightblue'),\n    String:             ('yellow',       'yellow'),\n    Number:             ('blue',    'brightblue'),\n\n    Generic.Deleted:    ('brightred',        'brightred'),\n    Generic.Inserted:   ('green',  'brightgreen'),\n    Generic.Heading:    ('**',         '**'),\n    Generic.Subheading: ('*magenta*',   '*brightmagenta*'),\n    Generic.Prompt:     ('**',         '**'),\n    Generic.Error:      ('brightred',        'brightred'),\n\n    Error:              ('_brightred_',      '_brightred_'),\n}\n\n\nclass TerminalFormatter(Formatter):\n    r\"\"\"\n    Format tokens with ANSI color sequences, for output in a text console.\n    Color sequences are terminated at newlines, so that paging the output\n    works correctly.\n\n    The `get_style_defs()` method doesn't do anything special since there is\n    no support for common styles.\n\n    Options accepted:\n\n    `bg`\n        Set to ``\"light\"`` or ``\"dark\"`` depending on the terminal's background\n        (default: ``\"light\"``).\n\n    `colorscheme`\n        A dictionary mapping token types to (lightbg, darkbg) color names or\n        ``None`` (default: ``None`` = use builtin colorscheme).\n\n    `linenos`\n        Set to ``True`` to have line numbers on the terminal output as well\n        (default: ``False`` = no line numbers).\n    \"\"\"\n    name = 'Terminal'\n    aliases = ['terminal', 'console']\n    filenames = []\n\n    def __init__(self, **options):\n        Formatter.__init__(self, **options)\n        self.darkbg = get_choice_opt(options, 'bg',\n                                     ['light', 'dark'], 'light') == 'dark'\n        self.colorscheme = options.get('colorscheme', None) or TERMINAL_COLORS\n        self.linenos = options.get('linenos', False)\n        self._lineno = 0\n\n    def format(self, tokensource, outfile):\n        return Formatter.format(self, tokensource, outfile)\n\n    def _write_lineno(self, outfile):\n        self._lineno += 1\n        outfile.write(\"%s%04d: \" % (self._lineno != 1 and '\\n' or '', self._lineno))\n\n    def _get_color(self, ttype):\n        # self.colorscheme is a dict containing usually generic types, so we\n        # have to walk the tree of dots.  The base Token type must be a key,\n        # even if it's empty string, as in the default above.\n        colors = self.colorscheme.get(ttype)\n        while colors is None:\n            ttype = ttype.parent\n            colors = self.colorscheme.get(ttype)\n        return colors[self.darkbg]\n\n    def format_unencoded(self, tokensource, outfile):\n        if self.linenos:\n            self._write_lineno(outfile)\n\n        for ttype, value in tokensource:\n            color = self._get_color(ttype)\n\n            for line in value.splitlines(True):\n                if color:\n                    outfile.write(ansiformat(color, line.rstrip('\\n')))\n                else:\n                    outfile.write(line.rstrip('\\n'))\n                if line.endswith('\\n'):\n                    if self.linenos:\n                        self._write_lineno(outfile)\n                    else:\n                        outfile.write('\\n')\n\n        if self.linenos:\n            outfile.write(\"\\n\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/formatters/terminal256.py",
    "content": "\"\"\"\n    pygments.formatters.terminal256\n    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    Formatter for 256-color terminal output with ANSI sequences.\n\n    RGB-to-XTERM color conversion routines adapted from xterm256-conv\n    tool (http://frexx.de/xterm-256-notes/data/xterm256-conv2.tar.bz2)\n    by Wolfgang Frisch.\n\n    Formatter version 1.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\n# TODO:\n#  - Options to map style's bold/underline/italic/border attributes\n#    to some ANSI attrbutes (something like 'italic=underline')\n#  - An option to output \"style RGB to xterm RGB/index\" conversion table\n#  - An option to indicate that we are running in \"reverse background\"\n#    xterm. This means that default colors are white-on-black, not\n#    black-on-while, so colors like \"white background\" need to be converted\n#    to \"white background, black foreground\", etc...\n\nfrom pip._vendor.pygments.formatter import Formatter\nfrom pip._vendor.pygments.console import codes\nfrom pip._vendor.pygments.style import ansicolors\n\n\n__all__ = ['Terminal256Formatter', 'TerminalTrueColorFormatter']\n\n\nclass EscapeSequence:\n    def __init__(self, fg=None, bg=None, bold=False, underline=False, italic=False):\n        self.fg = fg\n        self.bg = bg\n        self.bold = bold\n        self.underline = underline\n        self.italic = italic\n\n    def escape(self, attrs):\n        if len(attrs):\n            return \"\\x1b[\" + \";\".join(attrs) + \"m\"\n        return \"\"\n\n    def color_string(self):\n        attrs = []\n        if self.fg is not None:\n            if self.fg in ansicolors:\n                esc = codes[self.fg.replace('ansi','')]\n                if ';01m' in esc:\n                    self.bold = True\n                # extract fg color code.\n                attrs.append(esc[2:4])\n            else:\n                attrs.extend((\"38\", \"5\", \"%i\" % self.fg))\n        if self.bg is not None:\n            if self.bg in ansicolors:\n                esc = codes[self.bg.replace('ansi','')]\n                # extract fg color code, add 10 for bg.\n                attrs.append(str(int(esc[2:4])+10))\n            else:\n                attrs.extend((\"48\", \"5\", \"%i\" % self.bg))\n        if self.bold:\n            attrs.append(\"01\")\n        if self.underline:\n            attrs.append(\"04\")\n        if self.italic:\n            attrs.append(\"03\")\n        return self.escape(attrs)\n\n    def true_color_string(self):\n        attrs = []\n        if self.fg:\n            attrs.extend((\"38\", \"2\", str(self.fg[0]), str(self.fg[1]), str(self.fg[2])))\n        if self.bg:\n            attrs.extend((\"48\", \"2\", str(self.bg[0]), str(self.bg[1]), str(self.bg[2])))\n        if self.bold:\n            attrs.append(\"01\")\n        if self.underline:\n            attrs.append(\"04\")\n        if self.italic:\n            attrs.append(\"03\")\n        return self.escape(attrs)\n\n    def reset_string(self):\n        attrs = []\n        if self.fg is not None:\n            attrs.append(\"39\")\n        if self.bg is not None:\n            attrs.append(\"49\")\n        if self.bold or self.underline or self.italic:\n            attrs.append(\"00\")\n        return self.escape(attrs)\n\n\nclass Terminal256Formatter(Formatter):\n    \"\"\"\n    Format tokens with ANSI color sequences, for output in a 256-color\n    terminal or console.  Like in `TerminalFormatter` color sequences\n    are terminated at newlines, so that paging the output works correctly.\n\n    The formatter takes colors from a style defined by the `style` option\n    and converts them to nearest ANSI 256-color escape sequences. Bold and\n    underline attributes from the style are preserved (and displayed).\n\n    .. versionadded:: 0.9\n\n    .. versionchanged:: 2.2\n       If the used style defines foreground colors in the form ``#ansi*``, then\n       `Terminal256Formatter` will map these to non extended foreground color.\n       See :ref:`AnsiTerminalStyle` for more information.\n\n    .. versionchanged:: 2.4\n       The ANSI color names have been updated with names that are easier to\n       understand and align with colornames of other projects and terminals.\n       See :ref:`this table <new-ansi-color-names>` for more information.\n\n\n    Options accepted:\n\n    `style`\n        The style to use, can be a string or a Style subclass (default:\n        ``'default'``).\n\n    `linenos`\n        Set to ``True`` to have line numbers on the terminal output as well\n        (default: ``False`` = no line numbers).\n    \"\"\"\n    name = 'Terminal256'\n    aliases = ['terminal256', 'console256', '256']\n    filenames = []\n\n    def __init__(self, **options):\n        Formatter.__init__(self, **options)\n\n        self.xterm_colors = []\n        self.best_match = {}\n        self.style_string = {}\n\n        self.usebold = 'nobold' not in options\n        self.useunderline = 'nounderline' not in options\n        self.useitalic = 'noitalic' not in options\n\n        self._build_color_table()  # build an RGB-to-256 color conversion table\n        self._setup_styles()  # convert selected style's colors to term. colors\n\n        self.linenos = options.get('linenos', False)\n        self._lineno = 0\n\n    def _build_color_table(self):\n        # colors 0..15: 16 basic colors\n\n        self.xterm_colors.append((0x00, 0x00, 0x00))  # 0\n        self.xterm_colors.append((0xcd, 0x00, 0x00))  # 1\n        self.xterm_colors.append((0x00, 0xcd, 0x00))  # 2\n        self.xterm_colors.append((0xcd, 0xcd, 0x00))  # 3\n        self.xterm_colors.append((0x00, 0x00, 0xee))  # 4\n        self.xterm_colors.append((0xcd, 0x00, 0xcd))  # 5\n        self.xterm_colors.append((0x00, 0xcd, 0xcd))  # 6\n        self.xterm_colors.append((0xe5, 0xe5, 0xe5))  # 7\n        self.xterm_colors.append((0x7f, 0x7f, 0x7f))  # 8\n        self.xterm_colors.append((0xff, 0x00, 0x00))  # 9\n        self.xterm_colors.append((0x00, 0xff, 0x00))  # 10\n        self.xterm_colors.append((0xff, 0xff, 0x00))  # 11\n        self.xterm_colors.append((0x5c, 0x5c, 0xff))  # 12\n        self.xterm_colors.append((0xff, 0x00, 0xff))  # 13\n        self.xterm_colors.append((0x00, 0xff, 0xff))  # 14\n        self.xterm_colors.append((0xff, 0xff, 0xff))  # 15\n\n        # colors 16..232: the 6x6x6 color cube\n\n        valuerange = (0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff)\n\n        for i in range(217):\n            r = valuerange[(i // 36) % 6]\n            g = valuerange[(i // 6) % 6]\n            b = valuerange[i % 6]\n            self.xterm_colors.append((r, g, b))\n\n        # colors 233..253: grayscale\n\n        for i in range(1, 22):\n            v = 8 + i * 10\n            self.xterm_colors.append((v, v, v))\n\n    def _closest_color(self, r, g, b):\n        distance = 257*257*3  # \"infinity\" (>distance from #000000 to #ffffff)\n        match = 0\n\n        for i in range(0, 254):\n            values = self.xterm_colors[i]\n\n            rd = r - values[0]\n            gd = g - values[1]\n            bd = b - values[2]\n            d = rd*rd + gd*gd + bd*bd\n\n            if d < distance:\n                match = i\n                distance = d\n        return match\n\n    def _color_index(self, color):\n        index = self.best_match.get(color, None)\n        if color in ansicolors:\n            # strip the `ansi/#ansi` part and look up code\n            index = color\n            self.best_match[color] = index\n        if index is None:\n            try:\n                rgb = int(str(color), 16)\n            except ValueError:\n                rgb = 0\n\n            r = (rgb >> 16) & 0xff\n            g = (rgb >> 8) & 0xff\n            b = rgb & 0xff\n            index = self._closest_color(r, g, b)\n            self.best_match[color] = index\n        return index\n\n    def _setup_styles(self):\n        for ttype, ndef in self.style:\n            escape = EscapeSequence()\n            # get foreground from ansicolor if set\n            if ndef['ansicolor']:\n                escape.fg = self._color_index(ndef['ansicolor'])\n            elif ndef['color']:\n                escape.fg = self._color_index(ndef['color'])\n            if ndef['bgansicolor']:\n                escape.bg = self._color_index(ndef['bgansicolor'])\n            elif ndef['bgcolor']:\n                escape.bg = self._color_index(ndef['bgcolor'])\n            if self.usebold and ndef['bold']:\n                escape.bold = True\n            if self.useunderline and ndef['underline']:\n                escape.underline = True\n            if self.useitalic and ndef['italic']:\n                escape.italic = True\n            self.style_string[str(ttype)] = (escape.color_string(),\n                                             escape.reset_string())\n\n    def _write_lineno(self, outfile):\n        self._lineno += 1\n        outfile.write(\"%s%04d: \" % (self._lineno != 1 and '\\n' or '', self._lineno))\n\n    def format(self, tokensource, outfile):\n        return Formatter.format(self, tokensource, outfile)\n\n    def format_unencoded(self, tokensource, outfile):\n        if self.linenos:\n            self._write_lineno(outfile)\n\n        for ttype, value in tokensource:\n            not_found = True\n            while ttype and not_found:\n                try:\n                    # outfile.write( \"<\" + str(ttype) + \">\" )\n                    on, off = self.style_string[str(ttype)]\n\n                    # Like TerminalFormatter, add \"reset colors\" escape sequence\n                    # on newline.\n                    spl = value.split('\\n')\n                    for line in spl[:-1]:\n                        if line:\n                            outfile.write(on + line + off)\n                        if self.linenos:\n                            self._write_lineno(outfile)\n                        else:\n                            outfile.write('\\n')\n\n                    if spl[-1]:\n                        outfile.write(on + spl[-1] + off)\n\n                    not_found = False\n                    # outfile.write( '#' + str(ttype) + '#' )\n\n                except KeyError:\n                    # ottype = ttype\n                    ttype = ttype.parent\n                    # outfile.write( '!' + str(ottype) + '->' + str(ttype) + '!' )\n\n            if not_found:\n                outfile.write(value)\n\n        if self.linenos:\n            outfile.write(\"\\n\")\n\n\n\nclass TerminalTrueColorFormatter(Terminal256Formatter):\n    r\"\"\"\n    Format tokens with ANSI color sequences, for output in a true-color\n    terminal or console.  Like in `TerminalFormatter` color sequences\n    are terminated at newlines, so that paging the output works correctly.\n\n    .. versionadded:: 2.1\n\n    Options accepted:\n\n    `style`\n        The style to use, can be a string or a Style subclass (default:\n        ``'default'``).\n    \"\"\"\n    name = 'TerminalTrueColor'\n    aliases = ['terminal16m', 'console16m', '16m']\n    filenames = []\n\n    def _build_color_table(self):\n        pass\n\n    def _color_tuple(self, color):\n        try:\n            rgb = int(str(color), 16)\n        except ValueError:\n            return None\n        r = (rgb >> 16) & 0xff\n        g = (rgb >> 8) & 0xff\n        b = rgb & 0xff\n        return (r, g, b)\n\n    def _setup_styles(self):\n        for ttype, ndef in self.style:\n            escape = EscapeSequence()\n            if ndef['color']:\n                escape.fg = self._color_tuple(ndef['color'])\n            if ndef['bgcolor']:\n                escape.bg = self._color_tuple(ndef['bgcolor'])\n            if self.usebold and ndef['bold']:\n                escape.bold = True\n            if self.useunderline and ndef['underline']:\n                escape.underline = True\n            if self.useitalic and ndef['italic']:\n                escape.italic = True\n            self.style_string[str(ttype)] = (escape.true_color_string(),\n                                             escape.reset_string())\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/lexer.py",
    "content": "\"\"\"\n    pygments.lexer\n    ~~~~~~~~~~~~~~\n\n    Base lexer classes.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\nimport sys\nimport time\n\nfrom pip._vendor.pygments.filter import apply_filters, Filter\nfrom pip._vendor.pygments.filters import get_filter_by_name\nfrom pip._vendor.pygments.token import Error, Text, Other, _TokenType\nfrom pip._vendor.pygments.util import get_bool_opt, get_int_opt, get_list_opt, \\\n    make_analysator, Future, guess_decode\nfrom pip._vendor.pygments.regexopt import regex_opt\n\n__all__ = ['Lexer', 'RegexLexer', 'ExtendedRegexLexer', 'DelegatingLexer',\n           'LexerContext', 'include', 'inherit', 'bygroups', 'using', 'this',\n           'default', 'words']\n\n\n_encoding_map = [(b'\\xef\\xbb\\xbf', 'utf-8'),\n                 (b'\\xff\\xfe\\0\\0', 'utf-32'),\n                 (b'\\0\\0\\xfe\\xff', 'utf-32be'),\n                 (b'\\xff\\xfe', 'utf-16'),\n                 (b'\\xfe\\xff', 'utf-16be')]\n\n_default_analyse = staticmethod(lambda x: 0.0)\n\n\nclass LexerMeta(type):\n    \"\"\"\n    This metaclass automagically converts ``analyse_text`` methods into\n    static methods which always return float values.\n    \"\"\"\n\n    def __new__(mcs, name, bases, d):\n        if 'analyse_text' in d:\n            d['analyse_text'] = make_analysator(d['analyse_text'])\n        return type.__new__(mcs, name, bases, d)\n\n\nclass Lexer(metaclass=LexerMeta):\n    \"\"\"\n    Lexer for a specific language.\n\n    Basic options recognized:\n    ``stripnl``\n        Strip leading and trailing newlines from the input (default: True).\n    ``stripall``\n        Strip all leading and trailing whitespace from the input\n        (default: False).\n    ``ensurenl``\n        Make sure that the input ends with a newline (default: True).  This\n        is required for some lexers that consume input linewise.\n\n        .. versionadded:: 1.3\n\n    ``tabsize``\n        If given and greater than 0, expand tabs in the input (default: 0).\n    ``encoding``\n        If given, must be an encoding name. This encoding will be used to\n        convert the input string to Unicode, if it is not already a Unicode\n        string (default: ``'guess'``, which uses a simple UTF-8 / Locale /\n        Latin1 detection.  Can also be ``'chardet'`` to use the chardet\n        library, if it is installed.\n    ``inencoding``\n        Overrides the ``encoding`` if given.\n    \"\"\"\n\n    #: Name of the lexer\n    name = None\n\n    #: URL of the language specification/definition\n    url = None\n\n    #: Shortcuts for the lexer\n    aliases = []\n\n    #: File name globs\n    filenames = []\n\n    #: Secondary file name globs\n    alias_filenames = []\n\n    #: MIME types\n    mimetypes = []\n\n    #: Priority, should multiple lexers match and no content is provided\n    priority = 0\n\n    def __init__(self, **options):\n        self.options = options\n        self.stripnl = get_bool_opt(options, 'stripnl', True)\n        self.stripall = get_bool_opt(options, 'stripall', False)\n        self.ensurenl = get_bool_opt(options, 'ensurenl', True)\n        self.tabsize = get_int_opt(options, 'tabsize', 0)\n        self.encoding = options.get('encoding', 'guess')\n        self.encoding = options.get('inencoding') or self.encoding\n        self.filters = []\n        for filter_ in get_list_opt(options, 'filters', ()):\n            self.add_filter(filter_)\n\n    def __repr__(self):\n        if self.options:\n            return '<pygments.lexers.%s with %r>' % (self.__class__.__name__,\n                                                     self.options)\n        else:\n            return '<pygments.lexers.%s>' % self.__class__.__name__\n\n    def add_filter(self, filter_, **options):\n        \"\"\"\n        Add a new stream filter to this lexer.\n        \"\"\"\n        if not isinstance(filter_, Filter):\n            filter_ = get_filter_by_name(filter_, **options)\n        self.filters.append(filter_)\n\n    def analyse_text(text):\n        \"\"\"\n        Has to return a float between ``0`` and ``1`` that indicates\n        if a lexer wants to highlight this text. Used by ``guess_lexer``.\n        If this method returns ``0`` it won't highlight it in any case, if\n        it returns ``1`` highlighting with this lexer is guaranteed.\n\n        The `LexerMeta` metaclass automatically wraps this function so\n        that it works like a static method (no ``self`` or ``cls``\n        parameter) and the return value is automatically converted to\n        `float`. If the return value is an object that is boolean `False`\n        it's the same as if the return values was ``0.0``.\n        \"\"\"\n\n    def get_tokens(self, text, unfiltered=False):\n        \"\"\"\n        Return an iterable of (tokentype, value) pairs generated from\n        `text`. If `unfiltered` is set to `True`, the filtering mechanism\n        is bypassed even if filters are defined.\n\n        Also preprocess the text, i.e. expand tabs and strip it if\n        wanted and applies registered filters.\n        \"\"\"\n        if not isinstance(text, str):\n            if self.encoding == 'guess':\n                text, _ = guess_decode(text)\n            elif self.encoding == 'chardet':\n                try:\n                    from pip._vendor import chardet\n                except ImportError as e:\n                    raise ImportError('To enable chardet encoding guessing, '\n                                      'please install the chardet library '\n                                      'from http://chardet.feedparser.org/') from e\n                # check for BOM first\n                decoded = None\n                for bom, encoding in _encoding_map:\n                    if text.startswith(bom):\n                        decoded = text[len(bom):].decode(encoding, 'replace')\n                        break\n                # no BOM found, so use chardet\n                if decoded is None:\n                    enc = chardet.detect(text[:1024])  # Guess using first 1KB\n                    decoded = text.decode(enc.get('encoding') or 'utf-8',\n                                          'replace')\n                text = decoded\n            else:\n                text = text.decode(self.encoding)\n                if text.startswith('\\ufeff'):\n                    text = text[len('\\ufeff'):]\n        else:\n            if text.startswith('\\ufeff'):\n                text = text[len('\\ufeff'):]\n\n        # text now *is* a unicode string\n        text = text.replace('\\r\\n', '\\n')\n        text = text.replace('\\r', '\\n')\n        if self.stripall:\n            text = text.strip()\n        elif self.stripnl:\n            text = text.strip('\\n')\n        if self.tabsize > 0:\n            text = text.expandtabs(self.tabsize)\n        if self.ensurenl and not text.endswith('\\n'):\n            text += '\\n'\n\n        def streamer():\n            for _, t, v in self.get_tokens_unprocessed(text):\n                yield t, v\n        stream = streamer()\n        if not unfiltered:\n            stream = apply_filters(stream, self.filters, self)\n        return stream\n\n    def get_tokens_unprocessed(self, text):\n        \"\"\"\n        Return an iterable of (index, tokentype, value) pairs where \"index\"\n        is the starting position of the token within the input text.\n\n        In subclasses, implement this method as a generator to\n        maximize effectiveness.\n        \"\"\"\n        raise NotImplementedError\n\n\nclass DelegatingLexer(Lexer):\n    \"\"\"\n    This lexer takes two lexer as arguments. A root lexer and\n    a language lexer. First everything is scanned using the language\n    lexer, afterwards all ``Other`` tokens are lexed using the root\n    lexer.\n\n    The lexers from the ``template`` lexer package use this base lexer.\n    \"\"\"\n\n    def __init__(self, _root_lexer, _language_lexer, _needle=Other, **options):\n        self.root_lexer = _root_lexer(**options)\n        self.language_lexer = _language_lexer(**options)\n        self.needle = _needle\n        Lexer.__init__(self, **options)\n\n    def get_tokens_unprocessed(self, text):\n        buffered = ''\n        insertions = []\n        lng_buffer = []\n        for i, t, v in self.language_lexer.get_tokens_unprocessed(text):\n            if t is self.needle:\n                if lng_buffer:\n                    insertions.append((len(buffered), lng_buffer))\n                    lng_buffer = []\n                buffered += v\n            else:\n                lng_buffer.append((i, t, v))\n        if lng_buffer:\n            insertions.append((len(buffered), lng_buffer))\n        return do_insertions(insertions,\n                             self.root_lexer.get_tokens_unprocessed(buffered))\n\n\n# ------------------------------------------------------------------------------\n# RegexLexer and ExtendedRegexLexer\n#\n\n\nclass include(str):  # pylint: disable=invalid-name\n    \"\"\"\n    Indicates that a state should include rules from another state.\n    \"\"\"\n    pass\n\n\nclass _inherit:\n    \"\"\"\n    Indicates the a state should inherit from its superclass.\n    \"\"\"\n    def __repr__(self):\n        return 'inherit'\n\ninherit = _inherit()  # pylint: disable=invalid-name\n\n\nclass combined(tuple):  # pylint: disable=invalid-name\n    \"\"\"\n    Indicates a state combined from multiple states.\n    \"\"\"\n\n    def __new__(cls, *args):\n        return tuple.__new__(cls, args)\n\n    def __init__(self, *args):\n        # tuple.__init__ doesn't do anything\n        pass\n\n\nclass _PseudoMatch:\n    \"\"\"\n    A pseudo match object constructed from a string.\n    \"\"\"\n\n    def __init__(self, start, text):\n        self._text = text\n        self._start = start\n\n    def start(self, arg=None):\n        return self._start\n\n    def end(self, arg=None):\n        return self._start + len(self._text)\n\n    def group(self, arg=None):\n        if arg:\n            raise IndexError('No such group')\n        return self._text\n\n    def groups(self):\n        return (self._text,)\n\n    def groupdict(self):\n        return {}\n\n\ndef bygroups(*args):\n    \"\"\"\n    Callback that yields multiple actions for each group in the match.\n    \"\"\"\n    def callback(lexer, match, ctx=None):\n        for i, action in enumerate(args):\n            if action is None:\n                continue\n            elif type(action) is _TokenType:\n                data = match.group(i + 1)\n                if data:\n                    yield match.start(i + 1), action, data\n            else:\n                data = match.group(i + 1)\n                if data is not None:\n                    if ctx:\n                        ctx.pos = match.start(i + 1)\n                    for item in action(lexer,\n                                       _PseudoMatch(match.start(i + 1), data), ctx):\n                        if item:\n                            yield item\n        if ctx:\n            ctx.pos = match.end()\n    return callback\n\n\nclass _This:\n    \"\"\"\n    Special singleton used for indicating the caller class.\n    Used by ``using``.\n    \"\"\"\n\nthis = _This()\n\n\ndef using(_other, **kwargs):\n    \"\"\"\n    Callback that processes the match with a different lexer.\n\n    The keyword arguments are forwarded to the lexer, except `state` which\n    is handled separately.\n\n    `state` specifies the state that the new lexer will start in, and can\n    be an enumerable such as ('root', 'inline', 'string') or a simple\n    string which is assumed to be on top of the root state.\n\n    Note: For that to work, `_other` must not be an `ExtendedRegexLexer`.\n    \"\"\"\n    gt_kwargs = {}\n    if 'state' in kwargs:\n        s = kwargs.pop('state')\n        if isinstance(s, (list, tuple)):\n            gt_kwargs['stack'] = s\n        else:\n            gt_kwargs['stack'] = ('root', s)\n\n    if _other is this:\n        def callback(lexer, match, ctx=None):\n            # if keyword arguments are given the callback\n            # function has to create a new lexer instance\n            if kwargs:\n                # XXX: cache that somehow\n                kwargs.update(lexer.options)\n                lx = lexer.__class__(**kwargs)\n            else:\n                lx = lexer\n            s = match.start()\n            for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs):\n                yield i + s, t, v\n            if ctx:\n                ctx.pos = match.end()\n    else:\n        def callback(lexer, match, ctx=None):\n            # XXX: cache that somehow\n            kwargs.update(lexer.options)\n            lx = _other(**kwargs)\n\n            s = match.start()\n            for i, t, v in lx.get_tokens_unprocessed(match.group(), **gt_kwargs):\n                yield i + s, t, v\n            if ctx:\n                ctx.pos = match.end()\n    return callback\n\n\nclass default:\n    \"\"\"\n    Indicates a state or state action (e.g. #pop) to apply.\n    For example default('#pop') is equivalent to ('', Token, '#pop')\n    Note that state tuples may be used as well.\n\n    .. versionadded:: 2.0\n    \"\"\"\n    def __init__(self, state):\n        self.state = state\n\n\nclass words(Future):\n    \"\"\"\n    Indicates a list of literal words that is transformed into an optimized\n    regex that matches any of the words.\n\n    .. versionadded:: 2.0\n    \"\"\"\n    def __init__(self, words, prefix='', suffix=''):\n        self.words = words\n        self.prefix = prefix\n        self.suffix = suffix\n\n    def get(self):\n        return regex_opt(self.words, prefix=self.prefix, suffix=self.suffix)\n\n\nclass RegexLexerMeta(LexerMeta):\n    \"\"\"\n    Metaclass for RegexLexer, creates the self._tokens attribute from\n    self.tokens on the first instantiation.\n    \"\"\"\n\n    def _process_regex(cls, regex, rflags, state):\n        \"\"\"Preprocess the regular expression component of a token definition.\"\"\"\n        if isinstance(regex, Future):\n            regex = regex.get()\n        return re.compile(regex, rflags).match\n\n    def _process_token(cls, token):\n        \"\"\"Preprocess the token component of a token definition.\"\"\"\n        assert type(token) is _TokenType or callable(token), \\\n            'token type must be simple type or callable, not %r' % (token,)\n        return token\n\n    def _process_new_state(cls, new_state, unprocessed, processed):\n        \"\"\"Preprocess the state transition action of a token definition.\"\"\"\n        if isinstance(new_state, str):\n            # an existing state\n            if new_state == '#pop':\n                return -1\n            elif new_state in unprocessed:\n                return (new_state,)\n            elif new_state == '#push':\n                return new_state\n            elif new_state[:5] == '#pop:':\n                return -int(new_state[5:])\n            else:\n                assert False, 'unknown new state %r' % new_state\n        elif isinstance(new_state, combined):\n            # combine a new state from existing ones\n            tmp_state = '_tmp_%d' % cls._tmpname\n            cls._tmpname += 1\n            itokens = []\n            for istate in new_state:\n                assert istate != new_state, 'circular state ref %r' % istate\n                itokens.extend(cls._process_state(unprocessed,\n                                                  processed, istate))\n            processed[tmp_state] = itokens\n            return (tmp_state,)\n        elif isinstance(new_state, tuple):\n            # push more than one state\n            for istate in new_state:\n                assert (istate in unprocessed or\n                        istate in ('#pop', '#push')), \\\n                    'unknown new state ' + istate\n            return new_state\n        else:\n            assert False, 'unknown new state def %r' % new_state\n\n    def _process_state(cls, unprocessed, processed, state):\n        \"\"\"Preprocess a single state definition.\"\"\"\n        assert type(state) is str, \"wrong state name %r\" % state\n        assert state[0] != '#', \"invalid state name %r\" % state\n        if state in processed:\n            return processed[state]\n        tokens = processed[state] = []\n        rflags = cls.flags\n        for tdef in unprocessed[state]:\n            if isinstance(tdef, include):\n                # it's a state reference\n                assert tdef != state, \"circular state reference %r\" % state\n                tokens.extend(cls._process_state(unprocessed, processed,\n                                                 str(tdef)))\n                continue\n            if isinstance(tdef, _inherit):\n                # should be processed already, but may not in the case of:\n                # 1. the state has no counterpart in any parent\n                # 2. the state includes more than one 'inherit'\n                continue\n            if isinstance(tdef, default):\n                new_state = cls._process_new_state(tdef.state, unprocessed, processed)\n                tokens.append((re.compile('').match, None, new_state))\n                continue\n\n            assert type(tdef) is tuple, \"wrong rule def %r\" % tdef\n\n            try:\n                rex = cls._process_regex(tdef[0], rflags, state)\n            except Exception as err:\n                raise ValueError(\"uncompilable regex %r in state %r of %r: %s\" %\n                                 (tdef[0], state, cls, err)) from err\n\n            token = cls._process_token(tdef[1])\n\n            if len(tdef) == 2:\n                new_state = None\n            else:\n                new_state = cls._process_new_state(tdef[2],\n                                                   unprocessed, processed)\n\n            tokens.append((rex, token, new_state))\n        return tokens\n\n    def process_tokendef(cls, name, tokendefs=None):\n        \"\"\"Preprocess a dictionary of token definitions.\"\"\"\n        processed = cls._all_tokens[name] = {}\n        tokendefs = tokendefs or cls.tokens[name]\n        for state in list(tokendefs):\n            cls._process_state(tokendefs, processed, state)\n        return processed\n\n    def get_tokendefs(cls):\n        \"\"\"\n        Merge tokens from superclasses in MRO order, returning a single tokendef\n        dictionary.\n\n        Any state that is not defined by a subclass will be inherited\n        automatically.  States that *are* defined by subclasses will, by\n        default, override that state in the superclass.  If a subclass wishes to\n        inherit definitions from a superclass, it can use the special value\n        \"inherit\", which will cause the superclass' state definition to be\n        included at that point in the state.\n        \"\"\"\n        tokens = {}\n        inheritable = {}\n        for c in cls.__mro__:\n            toks = c.__dict__.get('tokens', {})\n\n            for state, items in toks.items():\n                curitems = tokens.get(state)\n                if curitems is None:\n                    # N.b. because this is assigned by reference, sufficiently\n                    # deep hierarchies are processed incrementally (e.g. for\n                    # A(B), B(C), C(RegexLexer), B will be premodified so X(B)\n                    # will not see any inherits in B).\n                    tokens[state] = items\n                    try:\n                        inherit_ndx = items.index(inherit)\n                    except ValueError:\n                        continue\n                    inheritable[state] = inherit_ndx\n                    continue\n\n                inherit_ndx = inheritable.pop(state, None)\n                if inherit_ndx is None:\n                    continue\n\n                # Replace the \"inherit\" value with the items\n                curitems[inherit_ndx:inherit_ndx+1] = items\n                try:\n                    # N.b. this is the index in items (that is, the superclass\n                    # copy), so offset required when storing below.\n                    new_inh_ndx = items.index(inherit)\n                except ValueError:\n                    pass\n                else:\n                    inheritable[state] = inherit_ndx + new_inh_ndx\n\n        return tokens\n\n    def __call__(cls, *args, **kwds):\n        \"\"\"Instantiate cls after preprocessing its token definitions.\"\"\"\n        if '_tokens' not in cls.__dict__:\n            cls._all_tokens = {}\n            cls._tmpname = 0\n            if hasattr(cls, 'token_variants') and cls.token_variants:\n                # don't process yet\n                pass\n            else:\n                cls._tokens = cls.process_tokendef('', cls.get_tokendefs())\n\n        return type.__call__(cls, *args, **kwds)\n\n\nclass RegexLexer(Lexer, metaclass=RegexLexerMeta):\n    \"\"\"\n    Base for simple stateful regular expression-based lexers.\n    Simplifies the lexing process so that you need only\n    provide a list of states and regular expressions.\n    \"\"\"\n\n    #: Flags for compiling the regular expressions.\n    #: Defaults to MULTILINE.\n    flags = re.MULTILINE\n\n    #: At all time there is a stack of states. Initially, the stack contains\n    #: a single state 'root'. The top of the stack is called \"the current state\".\n    #:\n    #: Dict of ``{'state': [(regex, tokentype, new_state), ...], ...}``\n    #:\n    #: ``new_state`` can be omitted to signify no state transition.\n    #: If ``new_state`` is a string, it is pushed on the stack. This ensure\n    #: the new current state is ``new_state``.\n    #: If ``new_state`` is a tuple of strings, all of those strings are pushed\n    #: on the stack and the current state will be the last element of the list.\n    #: ``new_state`` can also be ``combined('state1', 'state2', ...)``\n    #: to signify a new, anonymous state combined from the rules of two\n    #: or more existing ones.\n    #: Furthermore, it can be '#pop' to signify going back one step in\n    #: the state stack, or '#push' to push the current state on the stack\n    #: again. Note that if you push while in a combined state, the combined\n    #: state itself is pushed, and not only the state in which the rule is\n    #: defined.\n    #:\n    #: The tuple can also be replaced with ``include('state')``, in which\n    #: case the rules from the state named by the string are included in the\n    #: current one.\n    tokens = {}\n\n    def get_tokens_unprocessed(self, text, stack=('root',)):\n        \"\"\"\n        Split ``text`` into (tokentype, text) pairs.\n\n        ``stack`` is the initial stack (default: ``['root']``)\n        \"\"\"\n        pos = 0\n        tokendefs = self._tokens\n        statestack = list(stack)\n        statetokens = tokendefs[statestack[-1]]\n        while 1:\n            for rexmatch, action, new_state in statetokens:\n                m = rexmatch(text, pos)\n                if m:\n                    if action is not None:\n                        if type(action) is _TokenType:\n                            yield pos, action, m.group()\n                        else:\n                            yield from action(self, m)\n                    pos = m.end()\n                    if new_state is not None:\n                        # state transition\n                        if isinstance(new_state, tuple):\n                            for state in new_state:\n                                if state == '#pop':\n                                    if len(statestack) > 1:\n                                        statestack.pop()\n                                elif state == '#push':\n                                    statestack.append(statestack[-1])\n                                else:\n                                    statestack.append(state)\n                        elif isinstance(new_state, int):\n                            # pop, but keep at least one state on the stack\n                            # (random code leading to unexpected pops should\n                            # not allow exceptions)\n                            if abs(new_state) >= len(statestack):\n                                del statestack[1:]\n                            else:\n                                del statestack[new_state:]\n                        elif new_state == '#push':\n                            statestack.append(statestack[-1])\n                        else:\n                            assert False, \"wrong state def: %r\" % new_state\n                        statetokens = tokendefs[statestack[-1]]\n                    break\n            else:\n                # We are here only if all state tokens have been considered\n                # and there was not a match on any of them.\n                try:\n                    if text[pos] == '\\n':\n                        # at EOL, reset state to \"root\"\n                        statestack = ['root']\n                        statetokens = tokendefs['root']\n                        yield pos, Text, '\\n'\n                        pos += 1\n                        continue\n                    yield pos, Error, text[pos]\n                    pos += 1\n                except IndexError:\n                    break\n\n\nclass LexerContext:\n    \"\"\"\n    A helper object that holds lexer position data.\n    \"\"\"\n\n    def __init__(self, text, pos, stack=None, end=None):\n        self.text = text\n        self.pos = pos\n        self.end = end or len(text)  # end=0 not supported ;-)\n        self.stack = stack or ['root']\n\n    def __repr__(self):\n        return 'LexerContext(%r, %r, %r)' % (\n            self.text, self.pos, self.stack)\n\n\nclass ExtendedRegexLexer(RegexLexer):\n    \"\"\"\n    A RegexLexer that uses a context object to store its state.\n    \"\"\"\n\n    def get_tokens_unprocessed(self, text=None, context=None):\n        \"\"\"\n        Split ``text`` into (tokentype, text) pairs.\n        If ``context`` is given, use this lexer context instead.\n        \"\"\"\n        tokendefs = self._tokens\n        if not context:\n            ctx = LexerContext(text, 0)\n            statetokens = tokendefs['root']\n        else:\n            ctx = context\n            statetokens = tokendefs[ctx.stack[-1]]\n            text = ctx.text\n        while 1:\n            for rexmatch, action, new_state in statetokens:\n                m = rexmatch(text, ctx.pos, ctx.end)\n                if m:\n                    if action is not None:\n                        if type(action) is _TokenType:\n                            yield ctx.pos, action, m.group()\n                            ctx.pos = m.end()\n                        else:\n                            yield from action(self, m, ctx)\n                            if not new_state:\n                                # altered the state stack?\n                                statetokens = tokendefs[ctx.stack[-1]]\n                    # CAUTION: callback must set ctx.pos!\n                    if new_state is not None:\n                        # state transition\n                        if isinstance(new_state, tuple):\n                            for state in new_state:\n                                if state == '#pop':\n                                    if len(ctx.stack) > 1:\n                                        ctx.stack.pop()\n                                elif state == '#push':\n                                    ctx.stack.append(ctx.stack[-1])\n                                else:\n                                    ctx.stack.append(state)\n                        elif isinstance(new_state, int):\n                            # see RegexLexer for why this check is made\n                            if abs(new_state) >= len(ctx.stack):\n                                del ctx.stack[1:]\n                            else:\n                                del ctx.stack[new_state:]\n                        elif new_state == '#push':\n                            ctx.stack.append(ctx.stack[-1])\n                        else:\n                            assert False, \"wrong state def: %r\" % new_state\n                        statetokens = tokendefs[ctx.stack[-1]]\n                    break\n            else:\n                try:\n                    if ctx.pos >= ctx.end:\n                        break\n                    if text[ctx.pos] == '\\n':\n                        # at EOL, reset state to \"root\"\n                        ctx.stack = ['root']\n                        statetokens = tokendefs['root']\n                        yield ctx.pos, Text, '\\n'\n                        ctx.pos += 1\n                        continue\n                    yield ctx.pos, Error, text[ctx.pos]\n                    ctx.pos += 1\n                except IndexError:\n                    break\n\n\ndef do_insertions(insertions, tokens):\n    \"\"\"\n    Helper for lexers which must combine the results of several\n    sublexers.\n\n    ``insertions`` is a list of ``(index, itokens)`` pairs.\n    Each ``itokens`` iterable should be inserted at position\n    ``index`` into the token stream given by the ``tokens``\n    argument.\n\n    The result is a combined token stream.\n\n    TODO: clean up the code here.\n    \"\"\"\n    insertions = iter(insertions)\n    try:\n        index, itokens = next(insertions)\n    except StopIteration:\n        # no insertions\n        yield from tokens\n        return\n\n    realpos = None\n    insleft = True\n\n    # iterate over the token stream where we want to insert\n    # the tokens from the insertion list.\n    for i, t, v in tokens:\n        # first iteration. store the position of first item\n        if realpos is None:\n            realpos = i\n        oldi = 0\n        while insleft and i + len(v) >= index:\n            tmpval = v[oldi:index - i]\n            if tmpval:\n                yield realpos, t, tmpval\n                realpos += len(tmpval)\n            for it_index, it_token, it_value in itokens:\n                yield realpos, it_token, it_value\n                realpos += len(it_value)\n            oldi = index - i\n            try:\n                index, itokens = next(insertions)\n            except StopIteration:\n                insleft = False\n                break  # not strictly necessary\n        if oldi < len(v):\n            yield realpos, t, v[oldi:]\n            realpos += len(v) - oldi\n\n    # leftover tokens\n    while insleft:\n        # no normal tokens, set realpos to zero\n        realpos = realpos or 0\n        for p, t, v in itokens:\n            yield realpos, t, v\n            realpos += len(v)\n        try:\n            index, itokens = next(insertions)\n        except StopIteration:\n            insleft = False\n            break  # not strictly necessary\n\n\nclass ProfilingRegexLexerMeta(RegexLexerMeta):\n    \"\"\"Metaclass for ProfilingRegexLexer, collects regex timing info.\"\"\"\n\n    def _process_regex(cls, regex, rflags, state):\n        if isinstance(regex, words):\n            rex = regex_opt(regex.words, prefix=regex.prefix,\n                            suffix=regex.suffix)\n        else:\n            rex = regex\n        compiled = re.compile(rex, rflags)\n\n        def match_func(text, pos, endpos=sys.maxsize):\n            info = cls._prof_data[-1].setdefault((state, rex), [0, 0.0])\n            t0 = time.time()\n            res = compiled.match(text, pos, endpos)\n            t1 = time.time()\n            info[0] += 1\n            info[1] += t1 - t0\n            return res\n        return match_func\n\n\nclass ProfilingRegexLexer(RegexLexer, metaclass=ProfilingRegexLexerMeta):\n    \"\"\"Drop-in replacement for RegexLexer that does profiling of its regexes.\"\"\"\n\n    _prof_data = []\n    _prof_sort_index = 4  # defaults to time per call\n\n    def get_tokens_unprocessed(self, text, stack=('root',)):\n        # this needs to be a stack, since using(this) will produce nested calls\n        self.__class__._prof_data.append({})\n        yield from RegexLexer.get_tokens_unprocessed(self, text, stack)\n        rawdata = self.__class__._prof_data.pop()\n        data = sorted(((s, repr(r).strip('u\\'').replace('\\\\\\\\', '\\\\')[:65],\n                        n, 1000 * t, 1000 * t / n)\n                       for ((s, r), (n, t)) in rawdata.items()),\n                      key=lambda x: x[self._prof_sort_index],\n                      reverse=True)\n        sum_total = sum(x[3] for x in data)\n\n        print()\n        print('Profiling result for %s lexing %d chars in %.3f ms' %\n              (self.__class__.__name__, len(text), sum_total))\n        print('=' * 110)\n        print('%-20s %-64s ncalls  tottime  percall' % ('state', 'regex'))\n        print('-' * 110)\n        for d in data:\n            print('%-20s %-65s %5d %8.4f %8.4f' % d)\n        print('=' * 110)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/lexers/__init__.py",
    "content": "\"\"\"\n    pygments.lexers\n    ~~~~~~~~~~~~~~~\n\n    Pygments lexers.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\nimport sys\nimport types\nfrom fnmatch import fnmatch\nfrom os.path import basename\n\nfrom pip._vendor.pygments.lexers._mapping import LEXERS\nfrom pip._vendor.pygments.modeline import get_filetype_from_buffer\nfrom pip._vendor.pygments.plugin import find_plugin_lexers\nfrom pip._vendor.pygments.util import ClassNotFound, guess_decode\n\nCOMPAT = {\n    'Python3Lexer': 'PythonLexer',\n    'Python3TracebackLexer': 'PythonTracebackLexer',\n}\n\n__all__ = ['get_lexer_by_name', 'get_lexer_for_filename', 'find_lexer_class',\n           'guess_lexer', 'load_lexer_from_file'] + list(LEXERS) + list(COMPAT)\n\n_lexer_cache = {}\n\ndef _load_lexers(module_name):\n    \"\"\"Load a lexer (and all others in the module too).\"\"\"\n    mod = __import__(module_name, None, None, ['__all__'])\n    for lexer_name in mod.__all__:\n        cls = getattr(mod, lexer_name)\n        _lexer_cache[cls.name] = cls\n\n\ndef get_all_lexers(plugins=True):\n    \"\"\"Return a generator of tuples in the form ``(name, aliases,\n    filenames, mimetypes)`` of all know lexers.\n\n    If *plugins* is true (the default), plugin lexers supplied by entrypoints\n    are also returned.  Otherwise, only builtin ones are considered.\n    \"\"\"\n    for item in LEXERS.values():\n        yield item[1:]\n    if plugins:\n        for lexer in find_plugin_lexers():\n            yield lexer.name, lexer.aliases, lexer.filenames, lexer.mimetypes\n\n\ndef find_lexer_class(name):\n    \"\"\"Lookup a lexer class by name.\n\n    Return None if not found.\n    \"\"\"\n    if name in _lexer_cache:\n        return _lexer_cache[name]\n    # lookup builtin lexers\n    for module_name, lname, aliases, _, _ in LEXERS.values():\n        if name == lname:\n            _load_lexers(module_name)\n            return _lexer_cache[name]\n    # continue with lexers from setuptools entrypoints\n    for cls in find_plugin_lexers():\n        if cls.name == name:\n            return cls\n\n\ndef find_lexer_class_by_name(_alias):\n    \"\"\"Lookup a lexer class by alias.\n\n    Like `get_lexer_by_name`, but does not instantiate the class.\n\n    .. versionadded:: 2.2\n    \"\"\"\n    if not _alias:\n        raise ClassNotFound('no lexer for alias %r found' % _alias)\n    # lookup builtin lexers\n    for module_name, name, aliases, _, _ in LEXERS.values():\n        if _alias.lower() in aliases:\n            if name not in _lexer_cache:\n                _load_lexers(module_name)\n            return _lexer_cache[name]\n    # continue with lexers from setuptools entrypoints\n    for cls in find_plugin_lexers():\n        if _alias.lower() in cls.aliases:\n            return cls\n    raise ClassNotFound('no lexer for alias %r found' % _alias)\n\n\ndef get_lexer_by_name(_alias, **options):\n    \"\"\"Get a lexer by an alias.\n\n    Raises ClassNotFound if not found.\n    \"\"\"\n    if not _alias:\n        raise ClassNotFound('no lexer for alias %r found' % _alias)\n\n    # lookup builtin lexers\n    for module_name, name, aliases, _, _ in LEXERS.values():\n        if _alias.lower() in aliases:\n            if name not in _lexer_cache:\n                _load_lexers(module_name)\n            return _lexer_cache[name](**options)\n    # continue with lexers from setuptools entrypoints\n    for cls in find_plugin_lexers():\n        if _alias.lower() in cls.aliases:\n            return cls(**options)\n    raise ClassNotFound('no lexer for alias %r found' % _alias)\n\n\ndef load_lexer_from_file(filename, lexername=\"CustomLexer\", **options):\n    \"\"\"Load a lexer from a file.\n\n    This method expects a file located relative to the current working\n    directory, which contains a Lexer class. By default, it expects the\n    Lexer to be name CustomLexer; you can specify your own class name\n    as the second argument to this function.\n\n    Users should be very careful with the input, because this method\n    is equivalent to running eval on the input file.\n\n    Raises ClassNotFound if there are any problems importing the Lexer.\n\n    .. versionadded:: 2.2\n    \"\"\"\n    try:\n        # This empty dict will contain the namespace for the exec'd file\n        custom_namespace = {}\n        with open(filename, 'rb') as f:\n            exec(f.read(), custom_namespace)\n        # Retrieve the class `lexername` from that namespace\n        if lexername not in custom_namespace:\n            raise ClassNotFound('no valid %s class found in %s' %\n                                (lexername, filename))\n        lexer_class = custom_namespace[lexername]\n        # And finally instantiate it with the options\n        return lexer_class(**options)\n    except OSError as err:\n        raise ClassNotFound('cannot read %s: %s' % (filename, err))\n    except ClassNotFound:\n        raise\n    except Exception as err:\n        raise ClassNotFound('error when loading custom lexer: %s' % err)\n\n\ndef find_lexer_class_for_filename(_fn, code=None):\n    \"\"\"Get a lexer for a filename.\n\n    If multiple lexers match the filename pattern, use ``analyse_text()`` to\n    figure out which one is more appropriate.\n\n    Returns None if not found.\n    \"\"\"\n    matches = []\n    fn = basename(_fn)\n    for modname, name, _, filenames, _ in LEXERS.values():\n        for filename in filenames:\n            if fnmatch(fn, filename):\n                if name not in _lexer_cache:\n                    _load_lexers(modname)\n                matches.append((_lexer_cache[name], filename))\n    for cls in find_plugin_lexers():\n        for filename in cls.filenames:\n            if fnmatch(fn, filename):\n                matches.append((cls, filename))\n\n    if isinstance(code, bytes):\n        # decode it, since all analyse_text functions expect unicode\n        code = guess_decode(code)\n\n    def get_rating(info):\n        cls, filename = info\n        # explicit patterns get a bonus\n        bonus = '*' not in filename and 0.5 or 0\n        # The class _always_ defines analyse_text because it's included in\n        # the Lexer class.  The default implementation returns None which\n        # gets turned into 0.0.  Run scripts/detect_missing_analyse_text.py\n        # to find lexers which need it overridden.\n        if code:\n            return cls.analyse_text(code) + bonus, cls.__name__\n        return cls.priority + bonus, cls.__name__\n\n    if matches:\n        matches.sort(key=get_rating)\n        # print \"Possible lexers, after sort:\", matches\n        return matches[-1][0]\n\n\ndef get_lexer_for_filename(_fn, code=None, **options):\n    \"\"\"Get a lexer for a filename.\n\n    If multiple lexers match the filename pattern, use ``analyse_text()`` to\n    figure out which one is more appropriate.\n\n    Raises ClassNotFound if not found.\n    \"\"\"\n    res = find_lexer_class_for_filename(_fn, code)\n    if not res:\n        raise ClassNotFound('no lexer for filename %r found' % _fn)\n    return res(**options)\n\n\ndef get_lexer_for_mimetype(_mime, **options):\n    \"\"\"Get a lexer for a mimetype.\n\n    Raises ClassNotFound if not found.\n    \"\"\"\n    for modname, name, _, _, mimetypes in LEXERS.values():\n        if _mime in mimetypes:\n            if name not in _lexer_cache:\n                _load_lexers(modname)\n            return _lexer_cache[name](**options)\n    for cls in find_plugin_lexers():\n        if _mime in cls.mimetypes:\n            return cls(**options)\n    raise ClassNotFound('no lexer for mimetype %r found' % _mime)\n\n\ndef _iter_lexerclasses(plugins=True):\n    \"\"\"Return an iterator over all lexer classes.\"\"\"\n    for key in sorted(LEXERS):\n        module_name, name = LEXERS[key][:2]\n        if name not in _lexer_cache:\n            _load_lexers(module_name)\n        yield _lexer_cache[name]\n    if plugins:\n        yield from find_plugin_lexers()\n\n\ndef guess_lexer_for_filename(_fn, _text, **options):\n    \"\"\"\n    Lookup all lexers that handle those filenames primary (``filenames``)\n    or secondary (``alias_filenames``). Then run a text analysis for those\n    lexers and choose the best result.\n\n    usage::\n\n        >>> from pygments.lexers import guess_lexer_for_filename\n        >>> guess_lexer_for_filename('hello.html', '<%= @foo %>')\n        <pygments.lexers.templates.RhtmlLexer object at 0xb7d2f32c>\n        >>> guess_lexer_for_filename('hello.html', '<h1>{{ title|e }}</h1>')\n        <pygments.lexers.templates.HtmlDjangoLexer object at 0xb7d2f2ac>\n        >>> guess_lexer_for_filename('style.css', 'a { color: <?= $link ?> }')\n        <pygments.lexers.templates.CssPhpLexer object at 0xb7ba518c>\n    \"\"\"\n    fn = basename(_fn)\n    primary = {}\n    matching_lexers = set()\n    for lexer in _iter_lexerclasses():\n        for filename in lexer.filenames:\n            if fnmatch(fn, filename):\n                matching_lexers.add(lexer)\n                primary[lexer] = True\n        for filename in lexer.alias_filenames:\n            if fnmatch(fn, filename):\n                matching_lexers.add(lexer)\n                primary[lexer] = False\n    if not matching_lexers:\n        raise ClassNotFound('no lexer for filename %r found' % fn)\n    if len(matching_lexers) == 1:\n        return matching_lexers.pop()(**options)\n    result = []\n    for lexer in matching_lexers:\n        rv = lexer.analyse_text(_text)\n        if rv == 1.0:\n            return lexer(**options)\n        result.append((rv, lexer))\n\n    def type_sort(t):\n        # sort by:\n        # - analyse score\n        # - is primary filename pattern?\n        # - priority\n        # - last resort: class name\n        return (t[0], primary[t[1]], t[1].priority, t[1].__name__)\n    result.sort(key=type_sort)\n\n    return result[-1][1](**options)\n\n\ndef guess_lexer(_text, **options):\n    \"\"\"Guess a lexer by strong distinctions in the text (eg, shebang).\"\"\"\n\n    if not isinstance(_text, str):\n        inencoding = options.get('inencoding', options.get('encoding'))\n        if inencoding:\n            _text = _text.decode(inencoding or 'utf8')\n        else:\n            _text, _ = guess_decode(_text)\n\n    # try to get a vim modeline first\n    ft = get_filetype_from_buffer(_text)\n\n    if ft is not None:\n        try:\n            return get_lexer_by_name(ft, **options)\n        except ClassNotFound:\n            pass\n\n    best_lexer = [0.0, None]\n    for lexer in _iter_lexerclasses():\n        rv = lexer.analyse_text(_text)\n        if rv == 1.0:\n            return lexer(**options)\n        if rv > best_lexer[0]:\n            best_lexer[:] = (rv, lexer)\n    if not best_lexer[0] or best_lexer[1] is None:\n        raise ClassNotFound('no lexer matching the text found')\n    return best_lexer[1](**options)\n\n\nclass _automodule(types.ModuleType):\n    \"\"\"Automatically import lexers.\"\"\"\n\n    def __getattr__(self, name):\n        info = LEXERS.get(name)\n        if info:\n            _load_lexers(info[0])\n            cls = _lexer_cache[info[1]]\n            setattr(self, name, cls)\n            return cls\n        if name in COMPAT:\n            return getattr(self, COMPAT[name])\n        raise AttributeError(name)\n\n\noldmod = sys.modules[__name__]\nnewmod = _automodule(__name__)\nnewmod.__dict__.update(oldmod.__dict__)\nsys.modules[__name__] = newmod\ndel newmod.newmod, newmod.oldmod, newmod.sys, newmod.types\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/lexers/_mapping.py",
    "content": "# Automatically generated by scripts/gen_mapfiles.py.\n# DO NOT EDIT BY HAND; run `make mapfiles` instead.\n\nLEXERS = {\n    'ABAPLexer': ('pip._vendor.pygments.lexers.business', 'ABAP', ('abap',), ('*.abap', '*.ABAP'), ('text/x-abap',)),\n    'AMDGPULexer': ('pip._vendor.pygments.lexers.amdgpu', 'AMDGPU', ('amdgpu',), ('*.isa',), ()),\n    'APLLexer': ('pip._vendor.pygments.lexers.apl', 'APL', ('apl',), ('*.apl', '*.aplf', '*.aplo', '*.apln', '*.aplc', '*.apli', '*.dyalog'), ()),\n    'AbnfLexer': ('pip._vendor.pygments.lexers.grammar_notation', 'ABNF', ('abnf',), ('*.abnf',), ('text/x-abnf',)),\n    'ActionScript3Lexer': ('pip._vendor.pygments.lexers.actionscript', 'ActionScript 3', ('actionscript3', 'as3'), ('*.as',), ('application/x-actionscript3', 'text/x-actionscript3', 'text/actionscript3')),\n    'ActionScriptLexer': ('pip._vendor.pygments.lexers.actionscript', 'ActionScript', ('actionscript', 'as'), ('*.as',), ('application/x-actionscript', 'text/x-actionscript', 'text/actionscript')),\n    'AdaLexer': ('pip._vendor.pygments.lexers.ada', 'Ada', ('ada', 'ada95', 'ada2005'), ('*.adb', '*.ads', '*.ada'), ('text/x-ada',)),\n    'AdlLexer': ('pip._vendor.pygments.lexers.archetype', 'ADL', ('adl',), ('*.adl', '*.adls', '*.adlf', '*.adlx'), ()),\n    'AgdaLexer': ('pip._vendor.pygments.lexers.haskell', 'Agda', ('agda',), ('*.agda',), ('text/x-agda',)),\n    'AheuiLexer': ('pip._vendor.pygments.lexers.esoteric', 'Aheui', ('aheui',), ('*.aheui',), ()),\n    'AlloyLexer': ('pip._vendor.pygments.lexers.dsls', 'Alloy', ('alloy',), ('*.als',), ('text/x-alloy',)),\n    'AmbientTalkLexer': ('pip._vendor.pygments.lexers.ambient', 'AmbientTalk', ('ambienttalk', 'ambienttalk/2', 'at'), ('*.at',), ('text/x-ambienttalk',)),\n    'AmplLexer': ('pip._vendor.pygments.lexers.ampl', 'Ampl', ('ampl',), ('*.run',), ()),\n    'Angular2HtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML + Angular2', ('html+ng2',), ('*.ng2',), ()),\n    'Angular2Lexer': ('pip._vendor.pygments.lexers.templates', 'Angular2', ('ng2',), (), ()),\n    'AntlrActionScriptLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With ActionScript Target', ('antlr-actionscript', 'antlr-as'), ('*.G', '*.g'), ()),\n    'AntlrCSharpLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With C# Target', ('antlr-csharp', 'antlr-c#'), ('*.G', '*.g'), ()),\n    'AntlrCppLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With CPP Target', ('antlr-cpp',), ('*.G', '*.g'), ()),\n    'AntlrJavaLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With Java Target', ('antlr-java',), ('*.G', '*.g'), ()),\n    'AntlrLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR', ('antlr',), (), ()),\n    'AntlrObjectiveCLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With ObjectiveC Target', ('antlr-objc',), ('*.G', '*.g'), ()),\n    'AntlrPerlLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With Perl Target', ('antlr-perl',), ('*.G', '*.g'), ()),\n    'AntlrPythonLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With Python Target', ('antlr-python',), ('*.G', '*.g'), ()),\n    'AntlrRubyLexer': ('pip._vendor.pygments.lexers.parsers', 'ANTLR With Ruby Target', ('antlr-ruby', 'antlr-rb'), ('*.G', '*.g'), ()),\n    'ApacheConfLexer': ('pip._vendor.pygments.lexers.configs', 'ApacheConf', ('apacheconf', 'aconf', 'apache'), ('.htaccess', 'apache.conf', 'apache2.conf'), ('text/x-apacheconf',)),\n    'AppleScriptLexer': ('pip._vendor.pygments.lexers.scripting', 'AppleScript', ('applescript',), ('*.applescript',), ()),\n    'ArduinoLexer': ('pip._vendor.pygments.lexers.c_like', 'Arduino', ('arduino',), ('*.ino',), ('text/x-arduino',)),\n    'ArrowLexer': ('pip._vendor.pygments.lexers.arrow', 'Arrow', ('arrow',), ('*.arw',), ()),\n    'AscLexer': ('pip._vendor.pygments.lexers.asc', 'ASCII armored', ('asc', 'pem'), ('*.asc', '*.pem', 'id_dsa', 'id_ecdsa', 'id_ecdsa_sk', 'id_ed25519', 'id_ed25519_sk', 'id_rsa'), ('application/pgp-keys', 'application/pgp-encrypted', 'application/pgp-signature')),\n    'AspectJLexer': ('pip._vendor.pygments.lexers.jvm', 'AspectJ', ('aspectj',), ('*.aj',), ('text/x-aspectj',)),\n    'AsymptoteLexer': ('pip._vendor.pygments.lexers.graphics', 'Asymptote', ('asymptote', 'asy'), ('*.asy',), ('text/x-asymptote',)),\n    'AugeasLexer': ('pip._vendor.pygments.lexers.configs', 'Augeas', ('augeas',), ('*.aug',), ()),\n    'AutoItLexer': ('pip._vendor.pygments.lexers.automation', 'AutoIt', ('autoit',), ('*.au3',), ('text/x-autoit',)),\n    'AutohotkeyLexer': ('pip._vendor.pygments.lexers.automation', 'autohotkey', ('autohotkey', 'ahk'), ('*.ahk', '*.ahkl'), ('text/x-autohotkey',)),\n    'AwkLexer': ('pip._vendor.pygments.lexers.textedit', 'Awk', ('awk', 'gawk', 'mawk', 'nawk'), ('*.awk',), ('application/x-awk',)),\n    'BBCBasicLexer': ('pip._vendor.pygments.lexers.basic', 'BBC Basic', ('bbcbasic',), ('*.bbc',), ()),\n    'BBCodeLexer': ('pip._vendor.pygments.lexers.markup', 'BBCode', ('bbcode',), (), ('text/x-bbcode',)),\n    'BCLexer': ('pip._vendor.pygments.lexers.algebra', 'BC', ('bc',), ('*.bc',), ()),\n    'BSTLexer': ('pip._vendor.pygments.lexers.bibtex', 'BST', ('bst', 'bst-pybtex'), ('*.bst',), ()),\n    'BareLexer': ('pip._vendor.pygments.lexers.bare', 'BARE', ('bare',), ('*.bare',), ()),\n    'BaseMakefileLexer': ('pip._vendor.pygments.lexers.make', 'Base Makefile', ('basemake',), (), ()),\n    'BashLexer': ('pip._vendor.pygments.lexers.shell', 'Bash', ('bash', 'sh', 'ksh', 'zsh', 'shell'), ('*.sh', '*.ksh', '*.bash', '*.ebuild', '*.eclass', '*.exheres-0', '*.exlib', '*.zsh', '.bashrc', 'bashrc', '.bash_*', 'bash_*', 'zshrc', '.zshrc', '.kshrc', 'kshrc', 'PKGBUILD'), ('application/x-sh', 'application/x-shellscript', 'text/x-shellscript')),\n    'BashSessionLexer': ('pip._vendor.pygments.lexers.shell', 'Bash Session', ('console', 'shell-session'), ('*.sh-session', '*.shell-session'), ('application/x-shell-session', 'application/x-sh-session')),\n    'BatchLexer': ('pip._vendor.pygments.lexers.shell', 'Batchfile', ('batch', 'bat', 'dosbatch', 'winbatch'), ('*.bat', '*.cmd'), ('application/x-dos-batch',)),\n    'BddLexer': ('pip._vendor.pygments.lexers.bdd', 'Bdd', ('bdd',), ('*.feature',), ('text/x-bdd',)),\n    'BefungeLexer': ('pip._vendor.pygments.lexers.esoteric', 'Befunge', ('befunge',), ('*.befunge',), ('application/x-befunge',)),\n    'BerryLexer': ('pip._vendor.pygments.lexers.berry', 'Berry', ('berry', 'be'), ('*.be',), ('text/x-berry', 'application/x-berry')),\n    'BibTeXLexer': ('pip._vendor.pygments.lexers.bibtex', 'BibTeX', ('bibtex', 'bib'), ('*.bib',), ('text/x-bibtex',)),\n    'BlitzBasicLexer': ('pip._vendor.pygments.lexers.basic', 'BlitzBasic', ('blitzbasic', 'b3d', 'bplus'), ('*.bb', '*.decls'), ('text/x-bb',)),\n    'BlitzMaxLexer': ('pip._vendor.pygments.lexers.basic', 'BlitzMax', ('blitzmax', 'bmax'), ('*.bmx',), ('text/x-bmx',)),\n    'BnfLexer': ('pip._vendor.pygments.lexers.grammar_notation', 'BNF', ('bnf',), ('*.bnf',), ('text/x-bnf',)),\n    'BoaLexer': ('pip._vendor.pygments.lexers.boa', 'Boa', ('boa',), ('*.boa',), ()),\n    'BooLexer': ('pip._vendor.pygments.lexers.dotnet', 'Boo', ('boo',), ('*.boo',), ('text/x-boo',)),\n    'BoogieLexer': ('pip._vendor.pygments.lexers.verification', 'Boogie', ('boogie',), ('*.bpl',), ()),\n    'BrainfuckLexer': ('pip._vendor.pygments.lexers.esoteric', 'Brainfuck', ('brainfuck', 'bf'), ('*.bf', '*.b'), ('application/x-brainfuck',)),\n    'BugsLexer': ('pip._vendor.pygments.lexers.modeling', 'BUGS', ('bugs', 'winbugs', 'openbugs'), ('*.bug',), ()),\n    'CAmkESLexer': ('pip._vendor.pygments.lexers.esoteric', 'CAmkES', ('camkes', 'idl4'), ('*.camkes', '*.idl4'), ()),\n    'CLexer': ('pip._vendor.pygments.lexers.c_cpp', 'C', ('c',), ('*.c', '*.h', '*.idc', '*.x[bp]m'), ('text/x-chdr', 'text/x-csrc', 'image/x-xbitmap', 'image/x-xpixmap')),\n    'CMakeLexer': ('pip._vendor.pygments.lexers.make', 'CMake', ('cmake',), ('*.cmake', 'CMakeLists.txt'), ('text/x-cmake',)),\n    'CObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'c-objdump', ('c-objdump',), ('*.c-objdump',), ('text/x-c-objdump',)),\n    'CPSALexer': ('pip._vendor.pygments.lexers.lisp', 'CPSA', ('cpsa',), ('*.cpsa',), ()),\n    'CSSUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'CSS+UL4', ('css+ul4',), ('*.cssul4',), ()),\n    'CSharpAspxLexer': ('pip._vendor.pygments.lexers.dotnet', 'aspx-cs', ('aspx-cs',), ('*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'), ()),\n    'CSharpLexer': ('pip._vendor.pygments.lexers.dotnet', 'C#', ('csharp', 'c#', 'cs'), ('*.cs',), ('text/x-csharp',)),\n    'Ca65Lexer': ('pip._vendor.pygments.lexers.asm', 'ca65 assembler', ('ca65',), ('*.s',), ()),\n    'CadlLexer': ('pip._vendor.pygments.lexers.archetype', 'cADL', ('cadl',), ('*.cadl',), ()),\n    'CapDLLexer': ('pip._vendor.pygments.lexers.esoteric', 'CapDL', ('capdl',), ('*.cdl',), ()),\n    'CapnProtoLexer': ('pip._vendor.pygments.lexers.capnproto', \"Cap'n Proto\", ('capnp',), ('*.capnp',), ()),\n    'CbmBasicV2Lexer': ('pip._vendor.pygments.lexers.basic', 'CBM BASIC V2', ('cbmbas',), ('*.bas',), ()),\n    'CddlLexer': ('pip._vendor.pygments.lexers.cddl', 'CDDL', ('cddl',), ('*.cddl',), ('text/x-cddl',)),\n    'CeylonLexer': ('pip._vendor.pygments.lexers.jvm', 'Ceylon', ('ceylon',), ('*.ceylon',), ('text/x-ceylon',)),\n    'Cfengine3Lexer': ('pip._vendor.pygments.lexers.configs', 'CFEngine3', ('cfengine3', 'cf3'), ('*.cf',), ()),\n    'ChaiscriptLexer': ('pip._vendor.pygments.lexers.scripting', 'ChaiScript', ('chaiscript', 'chai'), ('*.chai',), ('text/x-chaiscript', 'application/x-chaiscript')),\n    'ChapelLexer': ('pip._vendor.pygments.lexers.chapel', 'Chapel', ('chapel', 'chpl'), ('*.chpl',), ()),\n    'CharmciLexer': ('pip._vendor.pygments.lexers.c_like', 'Charmci', ('charmci',), ('*.ci',), ()),\n    'CheetahHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Cheetah', ('html+cheetah', 'html+spitfire', 'htmlcheetah'), (), ('text/html+cheetah', 'text/html+spitfire')),\n    'CheetahJavascriptLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Cheetah', ('javascript+cheetah', 'js+cheetah', 'javascript+spitfire', 'js+spitfire'), (), ('application/x-javascript+cheetah', 'text/x-javascript+cheetah', 'text/javascript+cheetah', 'application/x-javascript+spitfire', 'text/x-javascript+spitfire', 'text/javascript+spitfire')),\n    'CheetahLexer': ('pip._vendor.pygments.lexers.templates', 'Cheetah', ('cheetah', 'spitfire'), ('*.tmpl', '*.spt'), ('application/x-cheetah', 'application/x-spitfire')),\n    'CheetahXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Cheetah', ('xml+cheetah', 'xml+spitfire'), (), ('application/xml+cheetah', 'application/xml+spitfire')),\n    'CirruLexer': ('pip._vendor.pygments.lexers.webmisc', 'Cirru', ('cirru',), ('*.cirru',), ('text/x-cirru',)),\n    'ClayLexer': ('pip._vendor.pygments.lexers.c_like', 'Clay', ('clay',), ('*.clay',), ('text/x-clay',)),\n    'CleanLexer': ('pip._vendor.pygments.lexers.clean', 'Clean', ('clean',), ('*.icl', '*.dcl'), ()),\n    'ClojureLexer': ('pip._vendor.pygments.lexers.jvm', 'Clojure', ('clojure', 'clj'), ('*.clj', '*.cljc'), ('text/x-clojure', 'application/x-clojure')),\n    'ClojureScriptLexer': ('pip._vendor.pygments.lexers.jvm', 'ClojureScript', ('clojurescript', 'cljs'), ('*.cljs',), ('text/x-clojurescript', 'application/x-clojurescript')),\n    'CobolFreeformatLexer': ('pip._vendor.pygments.lexers.business', 'COBOLFree', ('cobolfree',), ('*.cbl', '*.CBL'), ()),\n    'CobolLexer': ('pip._vendor.pygments.lexers.business', 'COBOL', ('cobol',), ('*.cob', '*.COB', '*.cpy', '*.CPY'), ('text/x-cobol',)),\n    'CoffeeScriptLexer': ('pip._vendor.pygments.lexers.javascript', 'CoffeeScript', ('coffeescript', 'coffee-script', 'coffee'), ('*.coffee',), ('text/coffeescript',)),\n    'ColdfusionCFCLexer': ('pip._vendor.pygments.lexers.templates', 'Coldfusion CFC', ('cfc',), ('*.cfc',), ()),\n    'ColdfusionHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'Coldfusion HTML', ('cfm',), ('*.cfm', '*.cfml'), ('application/x-coldfusion',)),\n    'ColdfusionLexer': ('pip._vendor.pygments.lexers.templates', 'cfstatement', ('cfs',), (), ()),\n    'Comal80Lexer': ('pip._vendor.pygments.lexers.comal', 'COMAL-80', ('comal', 'comal80'), ('*.cml', '*.comal'), ()),\n    'CommonLispLexer': ('pip._vendor.pygments.lexers.lisp', 'Common Lisp', ('common-lisp', 'cl', 'lisp'), ('*.cl', '*.lisp'), ('text/x-common-lisp',)),\n    'ComponentPascalLexer': ('pip._vendor.pygments.lexers.oberon', 'Component Pascal', ('componentpascal', 'cp'), ('*.cp', '*.cps'), ('text/x-component-pascal',)),\n    'CoqLexer': ('pip._vendor.pygments.lexers.theorem', 'Coq', ('coq',), ('*.v',), ('text/x-coq',)),\n    'CplintLexer': ('pip._vendor.pygments.lexers.cplint', 'cplint', ('cplint',), ('*.ecl', '*.prolog', '*.pro', '*.pl', '*.P', '*.lpad', '*.cpl'), ('text/x-cplint',)),\n    'CppLexer': ('pip._vendor.pygments.lexers.c_cpp', 'C++', ('cpp', 'c++'), ('*.cpp', '*.hpp', '*.c++', '*.h++', '*.cc', '*.hh', '*.cxx', '*.hxx', '*.C', '*.H', '*.cp', '*.CPP', '*.tpp'), ('text/x-c++hdr', 'text/x-c++src')),\n    'CppObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'cpp-objdump', ('cpp-objdump', 'c++-objdumb', 'cxx-objdump'), ('*.cpp-objdump', '*.c++-objdump', '*.cxx-objdump'), ('text/x-cpp-objdump',)),\n    'CrmshLexer': ('pip._vendor.pygments.lexers.dsls', 'Crmsh', ('crmsh', 'pcmk'), ('*.crmsh', '*.pcmk'), ()),\n    'CrocLexer': ('pip._vendor.pygments.lexers.d', 'Croc', ('croc',), ('*.croc',), ('text/x-crocsrc',)),\n    'CryptolLexer': ('pip._vendor.pygments.lexers.haskell', 'Cryptol', ('cryptol', 'cry'), ('*.cry',), ('text/x-cryptol',)),\n    'CrystalLexer': ('pip._vendor.pygments.lexers.crystal', 'Crystal', ('cr', 'crystal'), ('*.cr',), ('text/x-crystal',)),\n    'CsoundDocumentLexer': ('pip._vendor.pygments.lexers.csound', 'Csound Document', ('csound-document', 'csound-csd'), ('*.csd',), ()),\n    'CsoundOrchestraLexer': ('pip._vendor.pygments.lexers.csound', 'Csound Orchestra', ('csound', 'csound-orc'), ('*.orc', '*.udo'), ()),\n    'CsoundScoreLexer': ('pip._vendor.pygments.lexers.csound', 'Csound Score', ('csound-score', 'csound-sco'), ('*.sco',), ()),\n    'CssDjangoLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Django/Jinja', ('css+django', 'css+jinja'), ('*.css.j2', '*.css.jinja2'), ('text/css+django', 'text/css+jinja')),\n    'CssErbLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Ruby', ('css+ruby', 'css+erb'), (), ('text/css+ruby',)),\n    'CssGenshiLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Genshi Text', ('css+genshitext', 'css+genshi'), (), ('text/css+genshi',)),\n    'CssLexer': ('pip._vendor.pygments.lexers.css', 'CSS', ('css',), ('*.css',), ('text/css',)),\n    'CssPhpLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+PHP', ('css+php',), (), ('text/css+php',)),\n    'CssSmartyLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Smarty', ('css+smarty',), (), ('text/css+smarty',)),\n    'CudaLexer': ('pip._vendor.pygments.lexers.c_like', 'CUDA', ('cuda', 'cu'), ('*.cu', '*.cuh'), ('text/x-cuda',)),\n    'CypherLexer': ('pip._vendor.pygments.lexers.graph', 'Cypher', ('cypher',), ('*.cyp', '*.cypher'), ()),\n    'CythonLexer': ('pip._vendor.pygments.lexers.python', 'Cython', ('cython', 'pyx', 'pyrex'), ('*.pyx', '*.pxd', '*.pxi'), ('text/x-cython', 'application/x-cython')),\n    'DLexer': ('pip._vendor.pygments.lexers.d', 'D', ('d',), ('*.d', '*.di'), ('text/x-dsrc',)),\n    'DObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'd-objdump', ('d-objdump',), ('*.d-objdump',), ('text/x-d-objdump',)),\n    'DarcsPatchLexer': ('pip._vendor.pygments.lexers.diff', 'Darcs Patch', ('dpatch',), ('*.dpatch', '*.darcspatch'), ()),\n    'DartLexer': ('pip._vendor.pygments.lexers.javascript', 'Dart', ('dart',), ('*.dart',), ('text/x-dart',)),\n    'Dasm16Lexer': ('pip._vendor.pygments.lexers.asm', 'DASM16', ('dasm16',), ('*.dasm16', '*.dasm'), ('text/x-dasm16',)),\n    'DebianControlLexer': ('pip._vendor.pygments.lexers.installers', 'Debian Control file', ('debcontrol', 'control'), ('control',), ()),\n    'DelphiLexer': ('pip._vendor.pygments.lexers.pascal', 'Delphi', ('delphi', 'pas', 'pascal', 'objectpascal'), ('*.pas', '*.dpr'), ('text/x-pascal',)),\n    'DevicetreeLexer': ('pip._vendor.pygments.lexers.devicetree', 'Devicetree', ('devicetree', 'dts'), ('*.dts', '*.dtsi'), ('text/x-c',)),\n    'DgLexer': ('pip._vendor.pygments.lexers.python', 'dg', ('dg',), ('*.dg',), ('text/x-dg',)),\n    'DiffLexer': ('pip._vendor.pygments.lexers.diff', 'Diff', ('diff', 'udiff'), ('*.diff', '*.patch'), ('text/x-diff', 'text/x-patch')),\n    'DjangoLexer': ('pip._vendor.pygments.lexers.templates', 'Django/Jinja', ('django', 'jinja'), (), ('application/x-django-templating', 'application/x-jinja')),\n    'DockerLexer': ('pip._vendor.pygments.lexers.configs', 'Docker', ('docker', 'dockerfile'), ('Dockerfile', '*.docker'), ('text/x-dockerfile-config',)),\n    'DtdLexer': ('pip._vendor.pygments.lexers.html', 'DTD', ('dtd',), ('*.dtd',), ('application/xml-dtd',)),\n    'DuelLexer': ('pip._vendor.pygments.lexers.webmisc', 'Duel', ('duel', 'jbst', 'jsonml+bst'), ('*.duel', '*.jbst'), ('text/x-duel', 'text/x-jbst')),\n    'DylanConsoleLexer': ('pip._vendor.pygments.lexers.dylan', 'Dylan session', ('dylan-console', 'dylan-repl'), ('*.dylan-console',), ('text/x-dylan-console',)),\n    'DylanLexer': ('pip._vendor.pygments.lexers.dylan', 'Dylan', ('dylan',), ('*.dylan', '*.dyl', '*.intr'), ('text/x-dylan',)),\n    'DylanLidLexer': ('pip._vendor.pygments.lexers.dylan', 'DylanLID', ('dylan-lid', 'lid'), ('*.lid', '*.hdp'), ('text/x-dylan-lid',)),\n    'ECLLexer': ('pip._vendor.pygments.lexers.ecl', 'ECL', ('ecl',), ('*.ecl',), ('application/x-ecl',)),\n    'ECLexer': ('pip._vendor.pygments.lexers.c_like', 'eC', ('ec',), ('*.ec', '*.eh'), ('text/x-echdr', 'text/x-ecsrc')),\n    'EarlGreyLexer': ('pip._vendor.pygments.lexers.javascript', 'Earl Grey', ('earl-grey', 'earlgrey', 'eg'), ('*.eg',), ('text/x-earl-grey',)),\n    'EasytrieveLexer': ('pip._vendor.pygments.lexers.scripting', 'Easytrieve', ('easytrieve',), ('*.ezt', '*.mac'), ('text/x-easytrieve',)),\n    'EbnfLexer': ('pip._vendor.pygments.lexers.parsers', 'EBNF', ('ebnf',), ('*.ebnf',), ('text/x-ebnf',)),\n    'EiffelLexer': ('pip._vendor.pygments.lexers.eiffel', 'Eiffel', ('eiffel',), ('*.e',), ('text/x-eiffel',)),\n    'ElixirConsoleLexer': ('pip._vendor.pygments.lexers.erlang', 'Elixir iex session', ('iex',), (), ('text/x-elixir-shellsession',)),\n    'ElixirLexer': ('pip._vendor.pygments.lexers.erlang', 'Elixir', ('elixir', 'ex', 'exs'), ('*.ex', '*.eex', '*.exs', '*.leex'), ('text/x-elixir',)),\n    'ElmLexer': ('pip._vendor.pygments.lexers.elm', 'Elm', ('elm',), ('*.elm',), ('text/x-elm',)),\n    'ElpiLexer': ('pip._vendor.pygments.lexers.elpi', 'Elpi', ('elpi',), ('*.elpi',), ('text/x-elpi',)),\n    'EmacsLispLexer': ('pip._vendor.pygments.lexers.lisp', 'EmacsLisp', ('emacs-lisp', 'elisp', 'emacs'), ('*.el',), ('text/x-elisp', 'application/x-elisp')),\n    'EmailLexer': ('pip._vendor.pygments.lexers.email', 'E-mail', ('email', 'eml'), ('*.eml',), ('message/rfc822',)),\n    'ErbLexer': ('pip._vendor.pygments.lexers.templates', 'ERB', ('erb',), (), ('application/x-ruby-templating',)),\n    'ErlangLexer': ('pip._vendor.pygments.lexers.erlang', 'Erlang', ('erlang',), ('*.erl', '*.hrl', '*.es', '*.escript'), ('text/x-erlang',)),\n    'ErlangShellLexer': ('pip._vendor.pygments.lexers.erlang', 'Erlang erl session', ('erl',), ('*.erl-sh',), ('text/x-erl-shellsession',)),\n    'EvoqueHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Evoque', ('html+evoque',), ('*.html',), ('text/html+evoque',)),\n    'EvoqueLexer': ('pip._vendor.pygments.lexers.templates', 'Evoque', ('evoque',), ('*.evoque',), ('application/x-evoque',)),\n    'EvoqueXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Evoque', ('xml+evoque',), ('*.xml',), ('application/xml+evoque',)),\n    'ExeclineLexer': ('pip._vendor.pygments.lexers.shell', 'execline', ('execline',), ('*.exec',), ()),\n    'EzhilLexer': ('pip._vendor.pygments.lexers.ezhil', 'Ezhil', ('ezhil',), ('*.n',), ('text/x-ezhil',)),\n    'FSharpLexer': ('pip._vendor.pygments.lexers.dotnet', 'F#', ('fsharp', 'f#'), ('*.fs', '*.fsi'), ('text/x-fsharp',)),\n    'FStarLexer': ('pip._vendor.pygments.lexers.ml', 'FStar', ('fstar',), ('*.fst', '*.fsti'), ('text/x-fstar',)),\n    'FactorLexer': ('pip._vendor.pygments.lexers.factor', 'Factor', ('factor',), ('*.factor',), ('text/x-factor',)),\n    'FancyLexer': ('pip._vendor.pygments.lexers.ruby', 'Fancy', ('fancy', 'fy'), ('*.fy', '*.fancypack'), ('text/x-fancysrc',)),\n    'FantomLexer': ('pip._vendor.pygments.lexers.fantom', 'Fantom', ('fan',), ('*.fan',), ('application/x-fantom',)),\n    'FelixLexer': ('pip._vendor.pygments.lexers.felix', 'Felix', ('felix', 'flx'), ('*.flx', '*.flxh'), ('text/x-felix',)),\n    'FennelLexer': ('pip._vendor.pygments.lexers.lisp', 'Fennel', ('fennel', 'fnl'), ('*.fnl',), ()),\n    'FishShellLexer': ('pip._vendor.pygments.lexers.shell', 'Fish', ('fish', 'fishshell'), ('*.fish', '*.load'), ('application/x-fish',)),\n    'FlatlineLexer': ('pip._vendor.pygments.lexers.dsls', 'Flatline', ('flatline',), (), ('text/x-flatline',)),\n    'FloScriptLexer': ('pip._vendor.pygments.lexers.floscript', 'FloScript', ('floscript', 'flo'), ('*.flo',), ()),\n    'ForthLexer': ('pip._vendor.pygments.lexers.forth', 'Forth', ('forth',), ('*.frt', '*.fs'), ('application/x-forth',)),\n    'FortranFixedLexer': ('pip._vendor.pygments.lexers.fortran', 'FortranFixed', ('fortranfixed',), ('*.f', '*.F'), ()),\n    'FortranLexer': ('pip._vendor.pygments.lexers.fortran', 'Fortran', ('fortran', 'f90'), ('*.f03', '*.f90', '*.F03', '*.F90'), ('text/x-fortran',)),\n    'FoxProLexer': ('pip._vendor.pygments.lexers.foxpro', 'FoxPro', ('foxpro', 'vfp', 'clipper', 'xbase'), ('*.PRG', '*.prg'), ()),\n    'FreeFemLexer': ('pip._vendor.pygments.lexers.freefem', 'Freefem', ('freefem',), ('*.edp',), ('text/x-freefem',)),\n    'FutharkLexer': ('pip._vendor.pygments.lexers.futhark', 'Futhark', ('futhark',), ('*.fut',), ('text/x-futhark',)),\n    'GAPLexer': ('pip._vendor.pygments.lexers.algebra', 'GAP', ('gap',), ('*.g', '*.gd', '*.gi', '*.gap'), ()),\n    'GDScriptLexer': ('pip._vendor.pygments.lexers.gdscript', 'GDScript', ('gdscript', 'gd'), ('*.gd',), ('text/x-gdscript', 'application/x-gdscript')),\n    'GLShaderLexer': ('pip._vendor.pygments.lexers.graphics', 'GLSL', ('glsl',), ('*.vert', '*.frag', '*.geo'), ('text/x-glslsrc',)),\n    'GSQLLexer': ('pip._vendor.pygments.lexers.gsql', 'GSQL', ('gsql',), ('*.gsql',), ()),\n    'GasLexer': ('pip._vendor.pygments.lexers.asm', 'GAS', ('gas', 'asm'), ('*.s', '*.S'), ('text/x-gas',)),\n    'GcodeLexer': ('pip._vendor.pygments.lexers.gcodelexer', 'g-code', ('gcode',), ('*.gcode',), ()),\n    'GenshiLexer': ('pip._vendor.pygments.lexers.templates', 'Genshi', ('genshi', 'kid', 'xml+genshi', 'xml+kid'), ('*.kid',), ('application/x-genshi', 'application/x-kid')),\n    'GenshiTextLexer': ('pip._vendor.pygments.lexers.templates', 'Genshi Text', ('genshitext',), (), ('application/x-genshi-text', 'text/x-genshi')),\n    'GettextLexer': ('pip._vendor.pygments.lexers.textfmts', 'Gettext Catalog', ('pot', 'po'), ('*.pot', '*.po'), ('application/x-gettext', 'text/x-gettext', 'text/gettext')),\n    'GherkinLexer': ('pip._vendor.pygments.lexers.testing', 'Gherkin', ('gherkin', 'cucumber'), ('*.feature',), ('text/x-gherkin',)),\n    'GnuplotLexer': ('pip._vendor.pygments.lexers.graphics', 'Gnuplot', ('gnuplot',), ('*.plot', '*.plt'), ('text/x-gnuplot',)),\n    'GoLexer': ('pip._vendor.pygments.lexers.go', 'Go', ('go', 'golang'), ('*.go',), ('text/x-gosrc',)),\n    'GoloLexer': ('pip._vendor.pygments.lexers.jvm', 'Golo', ('golo',), ('*.golo',), ()),\n    'GoodDataCLLexer': ('pip._vendor.pygments.lexers.business', 'GoodData-CL', ('gooddata-cl',), ('*.gdc',), ('text/x-gooddata-cl',)),\n    'GosuLexer': ('pip._vendor.pygments.lexers.jvm', 'Gosu', ('gosu',), ('*.gs', '*.gsx', '*.gsp', '*.vark'), ('text/x-gosu',)),\n    'GosuTemplateLexer': ('pip._vendor.pygments.lexers.jvm', 'Gosu Template', ('gst',), ('*.gst',), ('text/x-gosu-template',)),\n    'GraphvizLexer': ('pip._vendor.pygments.lexers.graphviz', 'Graphviz', ('graphviz', 'dot'), ('*.gv', '*.dot'), ('text/x-graphviz', 'text/vnd.graphviz')),\n    'GroffLexer': ('pip._vendor.pygments.lexers.markup', 'Groff', ('groff', 'nroff', 'man'), ('*.[1-9]', '*.man', '*.1p', '*.3pm'), ('application/x-troff', 'text/troff')),\n    'GroovyLexer': ('pip._vendor.pygments.lexers.jvm', 'Groovy', ('groovy',), ('*.groovy', '*.gradle'), ('text/x-groovy',)),\n    'HLSLShaderLexer': ('pip._vendor.pygments.lexers.graphics', 'HLSL', ('hlsl',), ('*.hlsl', '*.hlsli'), ('text/x-hlsl',)),\n    'HTMLUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'HTML+UL4', ('html+ul4',), ('*.htmlul4',), ()),\n    'HamlLexer': ('pip._vendor.pygments.lexers.html', 'Haml', ('haml',), ('*.haml',), ('text/x-haml',)),\n    'HandlebarsHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Handlebars', ('html+handlebars',), ('*.handlebars', '*.hbs'), ('text/html+handlebars', 'text/x-handlebars-template')),\n    'HandlebarsLexer': ('pip._vendor.pygments.lexers.templates', 'Handlebars', ('handlebars',), (), ()),\n    'HaskellLexer': ('pip._vendor.pygments.lexers.haskell', 'Haskell', ('haskell', 'hs'), ('*.hs',), ('text/x-haskell',)),\n    'HaxeLexer': ('pip._vendor.pygments.lexers.haxe', 'Haxe', ('haxe', 'hxsl', 'hx'), ('*.hx', '*.hxsl'), ('text/haxe', 'text/x-haxe', 'text/x-hx')),\n    'HexdumpLexer': ('pip._vendor.pygments.lexers.hexdump', 'Hexdump', ('hexdump',), (), ()),\n    'HsailLexer': ('pip._vendor.pygments.lexers.asm', 'HSAIL', ('hsail', 'hsa'), ('*.hsail',), ('text/x-hsail',)),\n    'HspecLexer': ('pip._vendor.pygments.lexers.haskell', 'Hspec', ('hspec',), (), ()),\n    'HtmlDjangoLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Django/Jinja', ('html+django', 'html+jinja', 'htmldjango'), ('*.html.j2', '*.htm.j2', '*.xhtml.j2', '*.html.jinja2', '*.htm.jinja2', '*.xhtml.jinja2'), ('text/html+django', 'text/html+jinja')),\n    'HtmlGenshiLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Genshi', ('html+genshi', 'html+kid'), (), ('text/html+genshi',)),\n    'HtmlLexer': ('pip._vendor.pygments.lexers.html', 'HTML', ('html',), ('*.html', '*.htm', '*.xhtml', '*.xslt'), ('text/html', 'application/xhtml+xml')),\n    'HtmlPhpLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+PHP', ('html+php',), ('*.phtml',), ('application/x-php', 'application/x-httpd-php', 'application/x-httpd-php3', 'application/x-httpd-php4', 'application/x-httpd-php5')),\n    'HtmlSmartyLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Smarty', ('html+smarty',), (), ('text/html+smarty',)),\n    'HttpLexer': ('pip._vendor.pygments.lexers.textfmts', 'HTTP', ('http',), (), ()),\n    'HxmlLexer': ('pip._vendor.pygments.lexers.haxe', 'Hxml', ('haxeml', 'hxml'), ('*.hxml',), ()),\n    'HyLexer': ('pip._vendor.pygments.lexers.lisp', 'Hy', ('hylang',), ('*.hy',), ('text/x-hy', 'application/x-hy')),\n    'HybrisLexer': ('pip._vendor.pygments.lexers.scripting', 'Hybris', ('hybris', 'hy'), ('*.hy', '*.hyb'), ('text/x-hybris', 'application/x-hybris')),\n    'IDLLexer': ('pip._vendor.pygments.lexers.idl', 'IDL', ('idl',), ('*.pro',), ('text/idl',)),\n    'IconLexer': ('pip._vendor.pygments.lexers.unicon', 'Icon', ('icon',), ('*.icon', '*.ICON'), ()),\n    'IdrisLexer': ('pip._vendor.pygments.lexers.haskell', 'Idris', ('idris', 'idr'), ('*.idr',), ('text/x-idris',)),\n    'IgorLexer': ('pip._vendor.pygments.lexers.igor', 'Igor', ('igor', 'igorpro'), ('*.ipf',), ('text/ipf',)),\n    'Inform6Lexer': ('pip._vendor.pygments.lexers.int_fiction', 'Inform 6', ('inform6', 'i6'), ('*.inf',), ()),\n    'Inform6TemplateLexer': ('pip._vendor.pygments.lexers.int_fiction', 'Inform 6 template', ('i6t',), ('*.i6t',), ()),\n    'Inform7Lexer': ('pip._vendor.pygments.lexers.int_fiction', 'Inform 7', ('inform7', 'i7'), ('*.ni', '*.i7x'), ()),\n    'IniLexer': ('pip._vendor.pygments.lexers.configs', 'INI', ('ini', 'cfg', 'dosini'), ('*.ini', '*.cfg', '*.inf', '.editorconfig', '*.service', '*.socket', '*.device', '*.mount', '*.automount', '*.swap', '*.target', '*.path', '*.timer', '*.slice', '*.scope'), ('text/x-ini', 'text/inf')),\n    'IoLexer': ('pip._vendor.pygments.lexers.iolang', 'Io', ('io',), ('*.io',), ('text/x-iosrc',)),\n    'IokeLexer': ('pip._vendor.pygments.lexers.jvm', 'Ioke', ('ioke', 'ik'), ('*.ik',), ('text/x-iokesrc',)),\n    'IrcLogsLexer': ('pip._vendor.pygments.lexers.textfmts', 'IRC logs', ('irc',), ('*.weechatlog',), ('text/x-irclog',)),\n    'IsabelleLexer': ('pip._vendor.pygments.lexers.theorem', 'Isabelle', ('isabelle',), ('*.thy',), ('text/x-isabelle',)),\n    'JLexer': ('pip._vendor.pygments.lexers.j', 'J', ('j',), ('*.ijs',), ('text/x-j',)),\n    'JMESPathLexer': ('pip._vendor.pygments.lexers.jmespath', 'JMESPath', ('jmespath', 'jp'), ('*.jp',), ()),\n    'JSLTLexer': ('pip._vendor.pygments.lexers.jslt', 'JSLT', ('jslt',), ('*.jslt',), ('text/x-jslt',)),\n    'JagsLexer': ('pip._vendor.pygments.lexers.modeling', 'JAGS', ('jags',), ('*.jag', '*.bug'), ()),\n    'JasminLexer': ('pip._vendor.pygments.lexers.jvm', 'Jasmin', ('jasmin', 'jasminxt'), ('*.j',), ()),\n    'JavaLexer': ('pip._vendor.pygments.lexers.jvm', 'Java', ('java',), ('*.java',), ('text/x-java',)),\n    'JavascriptDjangoLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Django/Jinja', ('javascript+django', 'js+django', 'javascript+jinja', 'js+jinja'), ('*.js.j2', '*.js.jinja2'), ('application/x-javascript+django', 'application/x-javascript+jinja', 'text/x-javascript+django', 'text/x-javascript+jinja', 'text/javascript+django', 'text/javascript+jinja')),\n    'JavascriptErbLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Ruby', ('javascript+ruby', 'js+ruby', 'javascript+erb', 'js+erb'), (), ('application/x-javascript+ruby', 'text/x-javascript+ruby', 'text/javascript+ruby')),\n    'JavascriptGenshiLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Genshi Text', ('js+genshitext', 'js+genshi', 'javascript+genshitext', 'javascript+genshi'), (), ('application/x-javascript+genshi', 'text/x-javascript+genshi', 'text/javascript+genshi')),\n    'JavascriptLexer': ('pip._vendor.pygments.lexers.javascript', 'JavaScript', ('javascript', 'js'), ('*.js', '*.jsm', '*.mjs', '*.cjs'), ('application/javascript', 'application/x-javascript', 'text/x-javascript', 'text/javascript')),\n    'JavascriptPhpLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+PHP', ('javascript+php', 'js+php'), (), ('application/x-javascript+php', 'text/x-javascript+php', 'text/javascript+php')),\n    'JavascriptSmartyLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Smarty', ('javascript+smarty', 'js+smarty'), (), ('application/x-javascript+smarty', 'text/x-javascript+smarty', 'text/javascript+smarty')),\n    'JavascriptUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'Javascript+UL4', ('js+ul4',), ('*.jsul4',), ()),\n    'JclLexer': ('pip._vendor.pygments.lexers.scripting', 'JCL', ('jcl',), ('*.jcl',), ('text/x-jcl',)),\n    'JsgfLexer': ('pip._vendor.pygments.lexers.grammar_notation', 'JSGF', ('jsgf',), ('*.jsgf',), ('application/jsgf', 'application/x-jsgf', 'text/jsgf')),\n    'JsonBareObjectLexer': ('pip._vendor.pygments.lexers.data', 'JSONBareObject', (), (), ()),\n    'JsonLdLexer': ('pip._vendor.pygments.lexers.data', 'JSON-LD', ('jsonld', 'json-ld'), ('*.jsonld',), ('application/ld+json',)),\n    'JsonLexer': ('pip._vendor.pygments.lexers.data', 'JSON', ('json', 'json-object'), ('*.json', 'Pipfile.lock'), ('application/json', 'application/json-object')),\n    'JspLexer': ('pip._vendor.pygments.lexers.templates', 'Java Server Page', ('jsp',), ('*.jsp',), ('application/x-jsp',)),\n    'JuliaConsoleLexer': ('pip._vendor.pygments.lexers.julia', 'Julia console', ('jlcon', 'julia-repl'), (), ()),\n    'JuliaLexer': ('pip._vendor.pygments.lexers.julia', 'Julia', ('julia', 'jl'), ('*.jl',), ('text/x-julia', 'application/x-julia')),\n    'JuttleLexer': ('pip._vendor.pygments.lexers.javascript', 'Juttle', ('juttle',), ('*.juttle',), ('application/juttle', 'application/x-juttle', 'text/x-juttle', 'text/juttle')),\n    'KLexer': ('pip._vendor.pygments.lexers.q', 'K', ('k',), ('*.k',), ()),\n    'KalLexer': ('pip._vendor.pygments.lexers.javascript', 'Kal', ('kal',), ('*.kal',), ('text/kal', 'application/kal')),\n    'KconfigLexer': ('pip._vendor.pygments.lexers.configs', 'Kconfig', ('kconfig', 'menuconfig', 'linux-config', 'kernel-config'), ('Kconfig*', '*Config.in*', 'external.in*', 'standard-modules.in'), ('text/x-kconfig',)),\n    'KernelLogLexer': ('pip._vendor.pygments.lexers.textfmts', 'Kernel log', ('kmsg', 'dmesg'), ('*.kmsg', '*.dmesg'), ()),\n    'KokaLexer': ('pip._vendor.pygments.lexers.haskell', 'Koka', ('koka',), ('*.kk', '*.kki'), ('text/x-koka',)),\n    'KotlinLexer': ('pip._vendor.pygments.lexers.jvm', 'Kotlin', ('kotlin',), ('*.kt', '*.kts'), ('text/x-kotlin',)),\n    'KuinLexer': ('pip._vendor.pygments.lexers.kuin', 'Kuin', ('kuin',), ('*.kn',), ()),\n    'LSLLexer': ('pip._vendor.pygments.lexers.scripting', 'LSL', ('lsl',), ('*.lsl',), ('text/x-lsl',)),\n    'LassoCssLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Lasso', ('css+lasso',), (), ('text/css+lasso',)),\n    'LassoHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Lasso', ('html+lasso',), (), ('text/html+lasso', 'application/x-httpd-lasso', 'application/x-httpd-lasso[89]')),\n    'LassoJavascriptLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Lasso', ('javascript+lasso', 'js+lasso'), (), ('application/x-javascript+lasso', 'text/x-javascript+lasso', 'text/javascript+lasso')),\n    'LassoLexer': ('pip._vendor.pygments.lexers.javascript', 'Lasso', ('lasso', 'lassoscript'), ('*.lasso', '*.lasso[89]'), ('text/x-lasso',)),\n    'LassoXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Lasso', ('xml+lasso',), (), ('application/xml+lasso',)),\n    'LeanLexer': ('pip._vendor.pygments.lexers.theorem', 'Lean', ('lean',), ('*.lean',), ('text/x-lean',)),\n    'LessCssLexer': ('pip._vendor.pygments.lexers.css', 'LessCss', ('less',), ('*.less',), ('text/x-less-css',)),\n    'LighttpdConfLexer': ('pip._vendor.pygments.lexers.configs', 'Lighttpd configuration file', ('lighttpd', 'lighty'), ('lighttpd.conf',), ('text/x-lighttpd-conf',)),\n    'LilyPondLexer': ('pip._vendor.pygments.lexers.lilypond', 'LilyPond', ('lilypond',), ('*.ly',), ()),\n    'LimboLexer': ('pip._vendor.pygments.lexers.inferno', 'Limbo', ('limbo',), ('*.b',), ('text/limbo',)),\n    'LiquidLexer': ('pip._vendor.pygments.lexers.templates', 'liquid', ('liquid',), ('*.liquid',), ()),\n    'LiterateAgdaLexer': ('pip._vendor.pygments.lexers.haskell', 'Literate Agda', ('literate-agda', 'lagda'), ('*.lagda',), ('text/x-literate-agda',)),\n    'LiterateCryptolLexer': ('pip._vendor.pygments.lexers.haskell', 'Literate Cryptol', ('literate-cryptol', 'lcryptol', 'lcry'), ('*.lcry',), ('text/x-literate-cryptol',)),\n    'LiterateHaskellLexer': ('pip._vendor.pygments.lexers.haskell', 'Literate Haskell', ('literate-haskell', 'lhaskell', 'lhs'), ('*.lhs',), ('text/x-literate-haskell',)),\n    'LiterateIdrisLexer': ('pip._vendor.pygments.lexers.haskell', 'Literate Idris', ('literate-idris', 'lidris', 'lidr'), ('*.lidr',), ('text/x-literate-idris',)),\n    'LiveScriptLexer': ('pip._vendor.pygments.lexers.javascript', 'LiveScript', ('livescript', 'live-script'), ('*.ls',), ('text/livescript',)),\n    'LlvmLexer': ('pip._vendor.pygments.lexers.asm', 'LLVM', ('llvm',), ('*.ll',), ('text/x-llvm',)),\n    'LlvmMirBodyLexer': ('pip._vendor.pygments.lexers.asm', 'LLVM-MIR Body', ('llvm-mir-body',), (), ()),\n    'LlvmMirLexer': ('pip._vendor.pygments.lexers.asm', 'LLVM-MIR', ('llvm-mir',), ('*.mir',), ()),\n    'LogosLexer': ('pip._vendor.pygments.lexers.objective', 'Logos', ('logos',), ('*.x', '*.xi', '*.xm', '*.xmi'), ('text/x-logos',)),\n    'LogtalkLexer': ('pip._vendor.pygments.lexers.prolog', 'Logtalk', ('logtalk',), ('*.lgt', '*.logtalk'), ('text/x-logtalk',)),\n    'LuaLexer': ('pip._vendor.pygments.lexers.scripting', 'Lua', ('lua',), ('*.lua', '*.wlua'), ('text/x-lua', 'application/x-lua')),\n    'MCFunctionLexer': ('pip._vendor.pygments.lexers.mcfunction', 'MCFunction', ('mcfunction', 'mcf'), ('*.mcfunction',), ('text/mcfunction',)),\n    'MIMELexer': ('pip._vendor.pygments.lexers.mime', 'MIME', ('mime',), (), ('multipart/mixed', 'multipart/related', 'multipart/alternative')),\n    'MOOCodeLexer': ('pip._vendor.pygments.lexers.scripting', 'MOOCode', ('moocode', 'moo'), ('*.moo',), ('text/x-moocode',)),\n    'MSDOSSessionLexer': ('pip._vendor.pygments.lexers.shell', 'MSDOS Session', ('doscon',), (), ()),\n    'Macaulay2Lexer': ('pip._vendor.pygments.lexers.macaulay2', 'Macaulay2', ('macaulay2',), ('*.m2',), ()),\n    'MakefileLexer': ('pip._vendor.pygments.lexers.make', 'Makefile', ('make', 'makefile', 'mf', 'bsdmake'), ('*.mak', '*.mk', 'Makefile', 'makefile', 'Makefile.*', 'GNUmakefile'), ('text/x-makefile',)),\n    'MakoCssLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Mako', ('css+mako',), (), ('text/css+mako',)),\n    'MakoHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Mako', ('html+mako',), (), ('text/html+mako',)),\n    'MakoJavascriptLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Mako', ('javascript+mako', 'js+mako'), (), ('application/x-javascript+mako', 'text/x-javascript+mako', 'text/javascript+mako')),\n    'MakoLexer': ('pip._vendor.pygments.lexers.templates', 'Mako', ('mako',), ('*.mao',), ('application/x-mako',)),\n    'MakoXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Mako', ('xml+mako',), (), ('application/xml+mako',)),\n    'MaqlLexer': ('pip._vendor.pygments.lexers.business', 'MAQL', ('maql',), ('*.maql',), ('text/x-gooddata-maql', 'application/x-gooddata-maql')),\n    'MarkdownLexer': ('pip._vendor.pygments.lexers.markup', 'Markdown', ('markdown', 'md'), ('*.md', '*.markdown'), ('text/x-markdown',)),\n    'MaskLexer': ('pip._vendor.pygments.lexers.javascript', 'Mask', ('mask',), ('*.mask',), ('text/x-mask',)),\n    'MasonLexer': ('pip._vendor.pygments.lexers.templates', 'Mason', ('mason',), ('*.m', '*.mhtml', '*.mc', '*.mi', 'autohandler', 'dhandler'), ('application/x-mason',)),\n    'MathematicaLexer': ('pip._vendor.pygments.lexers.algebra', 'Mathematica', ('mathematica', 'mma', 'nb'), ('*.nb', '*.cdf', '*.nbp', '*.ma'), ('application/mathematica', 'application/vnd.wolfram.mathematica', 'application/vnd.wolfram.mathematica.package', 'application/vnd.wolfram.cdf')),\n    'MatlabLexer': ('pip._vendor.pygments.lexers.matlab', 'Matlab', ('matlab',), ('*.m',), ('text/matlab',)),\n    'MatlabSessionLexer': ('pip._vendor.pygments.lexers.matlab', 'Matlab session', ('matlabsession',), (), ()),\n    'MaximaLexer': ('pip._vendor.pygments.lexers.maxima', 'Maxima', ('maxima', 'macsyma'), ('*.mac', '*.max'), ()),\n    'MesonLexer': ('pip._vendor.pygments.lexers.meson', 'Meson', ('meson', 'meson.build'), ('meson.build', 'meson_options.txt'), ('text/x-meson',)),\n    'MiniDLexer': ('pip._vendor.pygments.lexers.d', 'MiniD', ('minid',), (), ('text/x-minidsrc',)),\n    'MiniScriptLexer': ('pip._vendor.pygments.lexers.scripting', 'MiniScript', ('miniscript', 'ms'), ('*.ms',), ('text/x-minicript', 'application/x-miniscript')),\n    'ModelicaLexer': ('pip._vendor.pygments.lexers.modeling', 'Modelica', ('modelica',), ('*.mo',), ('text/x-modelica',)),\n    'Modula2Lexer': ('pip._vendor.pygments.lexers.modula2', 'Modula-2', ('modula2', 'm2'), ('*.def', '*.mod'), ('text/x-modula2',)),\n    'MoinWikiLexer': ('pip._vendor.pygments.lexers.markup', 'MoinMoin/Trac Wiki markup', ('trac-wiki', 'moin'), (), ('text/x-trac-wiki',)),\n    'MonkeyLexer': ('pip._vendor.pygments.lexers.basic', 'Monkey', ('monkey',), ('*.monkey',), ('text/x-monkey',)),\n    'MonteLexer': ('pip._vendor.pygments.lexers.monte', 'Monte', ('monte',), ('*.mt',), ()),\n    'MoonScriptLexer': ('pip._vendor.pygments.lexers.scripting', 'MoonScript', ('moonscript', 'moon'), ('*.moon',), ('text/x-moonscript', 'application/x-moonscript')),\n    'MoselLexer': ('pip._vendor.pygments.lexers.mosel', 'Mosel', ('mosel',), ('*.mos',), ()),\n    'MozPreprocCssLexer': ('pip._vendor.pygments.lexers.markup', 'CSS+mozpreproc', ('css+mozpreproc',), ('*.css.in',), ()),\n    'MozPreprocHashLexer': ('pip._vendor.pygments.lexers.markup', 'mozhashpreproc', ('mozhashpreproc',), (), ()),\n    'MozPreprocJavascriptLexer': ('pip._vendor.pygments.lexers.markup', 'Javascript+mozpreproc', ('javascript+mozpreproc',), ('*.js.in',), ()),\n    'MozPreprocPercentLexer': ('pip._vendor.pygments.lexers.markup', 'mozpercentpreproc', ('mozpercentpreproc',), (), ()),\n    'MozPreprocXulLexer': ('pip._vendor.pygments.lexers.markup', 'XUL+mozpreproc', ('xul+mozpreproc',), ('*.xul.in',), ()),\n    'MqlLexer': ('pip._vendor.pygments.lexers.c_like', 'MQL', ('mql', 'mq4', 'mq5', 'mql4', 'mql5'), ('*.mq4', '*.mq5', '*.mqh'), ('text/x-mql',)),\n    'MscgenLexer': ('pip._vendor.pygments.lexers.dsls', 'Mscgen', ('mscgen', 'msc'), ('*.msc',), ()),\n    'MuPADLexer': ('pip._vendor.pygments.lexers.algebra', 'MuPAD', ('mupad',), ('*.mu',), ()),\n    'MxmlLexer': ('pip._vendor.pygments.lexers.actionscript', 'MXML', ('mxml',), ('*.mxml',), ()),\n    'MySqlLexer': ('pip._vendor.pygments.lexers.sql', 'MySQL', ('mysql',), (), ('text/x-mysql',)),\n    'MyghtyCssLexer': ('pip._vendor.pygments.lexers.templates', 'CSS+Myghty', ('css+myghty',), (), ('text/css+myghty',)),\n    'MyghtyHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Myghty', ('html+myghty',), (), ('text/html+myghty',)),\n    'MyghtyJavascriptLexer': ('pip._vendor.pygments.lexers.templates', 'JavaScript+Myghty', ('javascript+myghty', 'js+myghty'), (), ('application/x-javascript+myghty', 'text/x-javascript+myghty', 'text/javascript+mygthy')),\n    'MyghtyLexer': ('pip._vendor.pygments.lexers.templates', 'Myghty', ('myghty',), ('*.myt', 'autodelegate'), ('application/x-myghty',)),\n    'MyghtyXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Myghty', ('xml+myghty',), (), ('application/xml+myghty',)),\n    'NCLLexer': ('pip._vendor.pygments.lexers.ncl', 'NCL', ('ncl',), ('*.ncl',), ('text/ncl',)),\n    'NSISLexer': ('pip._vendor.pygments.lexers.installers', 'NSIS', ('nsis', 'nsi', 'nsh'), ('*.nsi', '*.nsh'), ('text/x-nsis',)),\n    'NasmLexer': ('pip._vendor.pygments.lexers.asm', 'NASM', ('nasm',), ('*.asm', '*.ASM'), ('text/x-nasm',)),\n    'NasmObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'objdump-nasm', ('objdump-nasm',), ('*.objdump-intel',), ('text/x-nasm-objdump',)),\n    'NemerleLexer': ('pip._vendor.pygments.lexers.dotnet', 'Nemerle', ('nemerle',), ('*.n',), ('text/x-nemerle',)),\n    'NesCLexer': ('pip._vendor.pygments.lexers.c_like', 'nesC', ('nesc',), ('*.nc',), ('text/x-nescsrc',)),\n    'NestedTextLexer': ('pip._vendor.pygments.lexers.configs', 'NestedText', ('nestedtext', 'nt'), ('*.nt',), ()),\n    'NewLispLexer': ('pip._vendor.pygments.lexers.lisp', 'NewLisp', ('newlisp',), ('*.lsp', '*.nl', '*.kif'), ('text/x-newlisp', 'application/x-newlisp')),\n    'NewspeakLexer': ('pip._vendor.pygments.lexers.smalltalk', 'Newspeak', ('newspeak',), ('*.ns2',), ('text/x-newspeak',)),\n    'NginxConfLexer': ('pip._vendor.pygments.lexers.configs', 'Nginx configuration file', ('nginx',), ('nginx.conf',), ('text/x-nginx-conf',)),\n    'NimrodLexer': ('pip._vendor.pygments.lexers.nimrod', 'Nimrod', ('nimrod', 'nim'), ('*.nim', '*.nimrod'), ('text/x-nim',)),\n    'NitLexer': ('pip._vendor.pygments.lexers.nit', 'Nit', ('nit',), ('*.nit',), ()),\n    'NixLexer': ('pip._vendor.pygments.lexers.nix', 'Nix', ('nixos', 'nix'), ('*.nix',), ('text/x-nix',)),\n    'NodeConsoleLexer': ('pip._vendor.pygments.lexers.javascript', 'Node.js REPL console session', ('nodejsrepl',), (), ('text/x-nodejsrepl',)),\n    'NotmuchLexer': ('pip._vendor.pygments.lexers.textfmts', 'Notmuch', ('notmuch',), (), ()),\n    'NuSMVLexer': ('pip._vendor.pygments.lexers.smv', 'NuSMV', ('nusmv',), ('*.smv',), ()),\n    'NumPyLexer': ('pip._vendor.pygments.lexers.python', 'NumPy', ('numpy',), (), ()),\n    'ObjdumpLexer': ('pip._vendor.pygments.lexers.asm', 'objdump', ('objdump',), ('*.objdump',), ('text/x-objdump',)),\n    'ObjectiveCLexer': ('pip._vendor.pygments.lexers.objective', 'Objective-C', ('objective-c', 'objectivec', 'obj-c', 'objc'), ('*.m', '*.h'), ('text/x-objective-c',)),\n    'ObjectiveCppLexer': ('pip._vendor.pygments.lexers.objective', 'Objective-C++', ('objective-c++', 'objectivec++', 'obj-c++', 'objc++'), ('*.mm', '*.hh'), ('text/x-objective-c++',)),\n    'ObjectiveJLexer': ('pip._vendor.pygments.lexers.javascript', 'Objective-J', ('objective-j', 'objectivej', 'obj-j', 'objj'), ('*.j',), ('text/x-objective-j',)),\n    'OcamlLexer': ('pip._vendor.pygments.lexers.ml', 'OCaml', ('ocaml',), ('*.ml', '*.mli', '*.mll', '*.mly'), ('text/x-ocaml',)),\n    'OctaveLexer': ('pip._vendor.pygments.lexers.matlab', 'Octave', ('octave',), ('*.m',), ('text/octave',)),\n    'OdinLexer': ('pip._vendor.pygments.lexers.archetype', 'ODIN', ('odin',), ('*.odin',), ('text/odin',)),\n    'OmgIdlLexer': ('pip._vendor.pygments.lexers.c_like', 'OMG Interface Definition Language', ('omg-idl',), ('*.idl', '*.pidl'), ()),\n    'OocLexer': ('pip._vendor.pygments.lexers.ooc', 'Ooc', ('ooc',), ('*.ooc',), ('text/x-ooc',)),\n    'OpaLexer': ('pip._vendor.pygments.lexers.ml', 'Opa', ('opa',), ('*.opa',), ('text/x-opa',)),\n    'OpenEdgeLexer': ('pip._vendor.pygments.lexers.business', 'OpenEdge ABL', ('openedge', 'abl', 'progress'), ('*.p', '*.cls'), ('text/x-openedge', 'application/x-openedge')),\n    'OutputLexer': ('pip._vendor.pygments.lexers.special', 'Text output', ('output',), (), ()),\n    'PacmanConfLexer': ('pip._vendor.pygments.lexers.configs', 'PacmanConf', ('pacmanconf',), ('pacman.conf',), ()),\n    'PanLexer': ('pip._vendor.pygments.lexers.dsls', 'Pan', ('pan',), ('*.pan',), ()),\n    'ParaSailLexer': ('pip._vendor.pygments.lexers.parasail', 'ParaSail', ('parasail',), ('*.psi', '*.psl'), ('text/x-parasail',)),\n    'PawnLexer': ('pip._vendor.pygments.lexers.pawn', 'Pawn', ('pawn',), ('*.p', '*.pwn', '*.inc'), ('text/x-pawn',)),\n    'PegLexer': ('pip._vendor.pygments.lexers.grammar_notation', 'PEG', ('peg',), ('*.peg',), ('text/x-peg',)),\n    'Perl6Lexer': ('pip._vendor.pygments.lexers.perl', 'Perl6', ('perl6', 'pl6', 'raku'), ('*.pl', '*.pm', '*.nqp', '*.p6', '*.6pl', '*.p6l', '*.pl6', '*.6pm', '*.p6m', '*.pm6', '*.t', '*.raku', '*.rakumod', '*.rakutest', '*.rakudoc'), ('text/x-perl6', 'application/x-perl6')),\n    'PerlLexer': ('pip._vendor.pygments.lexers.perl', 'Perl', ('perl', 'pl'), ('*.pl', '*.pm', '*.t', '*.perl'), ('text/x-perl', 'application/x-perl')),\n    'PhpLexer': ('pip._vendor.pygments.lexers.php', 'PHP', ('php', 'php3', 'php4', 'php5'), ('*.php', '*.php[345]', '*.inc'), ('text/x-php',)),\n    'PigLexer': ('pip._vendor.pygments.lexers.jvm', 'Pig', ('pig',), ('*.pig',), ('text/x-pig',)),\n    'PikeLexer': ('pip._vendor.pygments.lexers.c_like', 'Pike', ('pike',), ('*.pike', '*.pmod'), ('text/x-pike',)),\n    'PkgConfigLexer': ('pip._vendor.pygments.lexers.configs', 'PkgConfig', ('pkgconfig',), ('*.pc',), ()),\n    'PlPgsqlLexer': ('pip._vendor.pygments.lexers.sql', 'PL/pgSQL', ('plpgsql',), (), ('text/x-plpgsql',)),\n    'PointlessLexer': ('pip._vendor.pygments.lexers.pointless', 'Pointless', ('pointless',), ('*.ptls',), ()),\n    'PonyLexer': ('pip._vendor.pygments.lexers.pony', 'Pony', ('pony',), ('*.pony',), ()),\n    'PostScriptLexer': ('pip._vendor.pygments.lexers.graphics', 'PostScript', ('postscript', 'postscr'), ('*.ps', '*.eps'), ('application/postscript',)),\n    'PostgresConsoleLexer': ('pip._vendor.pygments.lexers.sql', 'PostgreSQL console (psql)', ('psql', 'postgresql-console', 'postgres-console'), (), ('text/x-postgresql-psql',)),\n    'PostgresLexer': ('pip._vendor.pygments.lexers.sql', 'PostgreSQL SQL dialect', ('postgresql', 'postgres'), (), ('text/x-postgresql',)),\n    'PovrayLexer': ('pip._vendor.pygments.lexers.graphics', 'POVRay', ('pov',), ('*.pov', '*.inc'), ('text/x-povray',)),\n    'PowerShellLexer': ('pip._vendor.pygments.lexers.shell', 'PowerShell', ('powershell', 'pwsh', 'posh', 'ps1', 'psm1'), ('*.ps1', '*.psm1'), ('text/x-powershell',)),\n    'PowerShellSessionLexer': ('pip._vendor.pygments.lexers.shell', 'PowerShell Session', ('pwsh-session', 'ps1con'), (), ()),\n    'PraatLexer': ('pip._vendor.pygments.lexers.praat', 'Praat', ('praat',), ('*.praat', '*.proc', '*.psc'), ()),\n    'ProcfileLexer': ('pip._vendor.pygments.lexers.procfile', 'Procfile', ('procfile',), ('Procfile',), ()),\n    'PrologLexer': ('pip._vendor.pygments.lexers.prolog', 'Prolog', ('prolog',), ('*.ecl', '*.prolog', '*.pro', '*.pl'), ('text/x-prolog',)),\n    'PromQLLexer': ('pip._vendor.pygments.lexers.promql', 'PromQL', ('promql',), ('*.promql',), ()),\n    'PropertiesLexer': ('pip._vendor.pygments.lexers.configs', 'Properties', ('properties', 'jproperties'), ('*.properties',), ('text/x-java-properties',)),\n    'ProtoBufLexer': ('pip._vendor.pygments.lexers.dsls', 'Protocol Buffer', ('protobuf', 'proto'), ('*.proto',), ()),\n    'PsyshConsoleLexer': ('pip._vendor.pygments.lexers.php', 'PsySH console session for PHP', ('psysh',), (), ()),\n    'PugLexer': ('pip._vendor.pygments.lexers.html', 'Pug', ('pug', 'jade'), ('*.pug', '*.jade'), ('text/x-pug', 'text/x-jade')),\n    'PuppetLexer': ('pip._vendor.pygments.lexers.dsls', 'Puppet', ('puppet',), ('*.pp',), ()),\n    'PyPyLogLexer': ('pip._vendor.pygments.lexers.console', 'PyPy Log', ('pypylog', 'pypy'), ('*.pypylog',), ('application/x-pypylog',)),\n    'Python2Lexer': ('pip._vendor.pygments.lexers.python', 'Python 2.x', ('python2', 'py2'), (), ('text/x-python2', 'application/x-python2')),\n    'Python2TracebackLexer': ('pip._vendor.pygments.lexers.python', 'Python 2.x Traceback', ('py2tb',), ('*.py2tb',), ('text/x-python2-traceback',)),\n    'PythonConsoleLexer': ('pip._vendor.pygments.lexers.python', 'Python console session', ('pycon',), (), ('text/x-python-doctest',)),\n    'PythonLexer': ('pip._vendor.pygments.lexers.python', 'Python', ('python', 'py', 'sage', 'python3', 'py3'), ('*.py', '*.pyw', '*.jy', '*.sage', '*.sc', 'SConstruct', 'SConscript', '*.bzl', 'BUCK', 'BUILD', 'BUILD.bazel', 'WORKSPACE', '*.tac'), ('text/x-python', 'application/x-python', 'text/x-python3', 'application/x-python3')),\n    'PythonTracebackLexer': ('pip._vendor.pygments.lexers.python', 'Python Traceback', ('pytb', 'py3tb'), ('*.pytb', '*.py3tb'), ('text/x-python-traceback', 'text/x-python3-traceback')),\n    'PythonUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'Python+UL4', ('py+ul4',), ('*.pyul4',), ()),\n    'QBasicLexer': ('pip._vendor.pygments.lexers.basic', 'QBasic', ('qbasic', 'basic'), ('*.BAS', '*.bas'), ('text/basic',)),\n    'QLexer': ('pip._vendor.pygments.lexers.q', 'Q', ('q',), ('*.q',), ()),\n    'QVToLexer': ('pip._vendor.pygments.lexers.qvt', 'QVTO', ('qvto', 'qvt'), ('*.qvto',), ()),\n    'QlikLexer': ('pip._vendor.pygments.lexers.qlik', 'Qlik', ('qlik', 'qlikview', 'qliksense', 'qlikscript'), ('*.qvs', '*.qvw'), ()),\n    'QmlLexer': ('pip._vendor.pygments.lexers.webmisc', 'QML', ('qml', 'qbs'), ('*.qml', '*.qbs'), ('application/x-qml', 'application/x-qt.qbs+qml')),\n    'RConsoleLexer': ('pip._vendor.pygments.lexers.r', 'RConsole', ('rconsole', 'rout'), ('*.Rout',), ()),\n    'RNCCompactLexer': ('pip._vendor.pygments.lexers.rnc', 'Relax-NG Compact', ('rng-compact', 'rnc'), ('*.rnc',), ()),\n    'RPMSpecLexer': ('pip._vendor.pygments.lexers.installers', 'RPMSpec', ('spec',), ('*.spec',), ('text/x-rpm-spec',)),\n    'RacketLexer': ('pip._vendor.pygments.lexers.lisp', 'Racket', ('racket', 'rkt'), ('*.rkt', '*.rktd', '*.rktl'), ('text/x-racket', 'application/x-racket')),\n    'RagelCLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in C Host', ('ragel-c',), ('*.rl',), ()),\n    'RagelCppLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in CPP Host', ('ragel-cpp',), ('*.rl',), ()),\n    'RagelDLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in D Host', ('ragel-d',), ('*.rl',), ()),\n    'RagelEmbeddedLexer': ('pip._vendor.pygments.lexers.parsers', 'Embedded Ragel', ('ragel-em',), ('*.rl',), ()),\n    'RagelJavaLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in Java Host', ('ragel-java',), ('*.rl',), ()),\n    'RagelLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel', ('ragel',), (), ()),\n    'RagelObjectiveCLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in Objective C Host', ('ragel-objc',), ('*.rl',), ()),\n    'RagelRubyLexer': ('pip._vendor.pygments.lexers.parsers', 'Ragel in Ruby Host', ('ragel-ruby', 'ragel-rb'), ('*.rl',), ()),\n    'RawTokenLexer': ('pip._vendor.pygments.lexers.special', 'Raw token data', (), (), ('application/x-pygments-tokens',)),\n    'RdLexer': ('pip._vendor.pygments.lexers.r', 'Rd', ('rd',), ('*.Rd',), ('text/x-r-doc',)),\n    'ReasonLexer': ('pip._vendor.pygments.lexers.ml', 'ReasonML', ('reasonml', 'reason'), ('*.re', '*.rei'), ('text/x-reasonml',)),\n    'RebolLexer': ('pip._vendor.pygments.lexers.rebol', 'REBOL', ('rebol',), ('*.r', '*.r3', '*.reb'), ('text/x-rebol',)),\n    'RedLexer': ('pip._vendor.pygments.lexers.rebol', 'Red', ('red', 'red/system'), ('*.red', '*.reds'), ('text/x-red', 'text/x-red-system')),\n    'RedcodeLexer': ('pip._vendor.pygments.lexers.esoteric', 'Redcode', ('redcode',), ('*.cw',), ()),\n    'RegeditLexer': ('pip._vendor.pygments.lexers.configs', 'reg', ('registry',), ('*.reg',), ('text/x-windows-registry',)),\n    'ResourceLexer': ('pip._vendor.pygments.lexers.resource', 'ResourceBundle', ('resourcebundle', 'resource'), (), ()),\n    'RexxLexer': ('pip._vendor.pygments.lexers.scripting', 'Rexx', ('rexx', 'arexx'), ('*.rexx', '*.rex', '*.rx', '*.arexx'), ('text/x-rexx',)),\n    'RhtmlLexer': ('pip._vendor.pygments.lexers.templates', 'RHTML', ('rhtml', 'html+erb', 'html+ruby'), ('*.rhtml',), ('text/html+ruby',)),\n    'RideLexer': ('pip._vendor.pygments.lexers.ride', 'Ride', ('ride',), ('*.ride',), ('text/x-ride',)),\n    'RitaLexer': ('pip._vendor.pygments.lexers.rita', 'Rita', ('rita',), ('*.rita',), ('text/rita',)),\n    'RoboconfGraphLexer': ('pip._vendor.pygments.lexers.roboconf', 'Roboconf Graph', ('roboconf-graph',), ('*.graph',), ()),\n    'RoboconfInstancesLexer': ('pip._vendor.pygments.lexers.roboconf', 'Roboconf Instances', ('roboconf-instances',), ('*.instances',), ()),\n    'RobotFrameworkLexer': ('pip._vendor.pygments.lexers.robotframework', 'RobotFramework', ('robotframework',), ('*.robot', '*.resource'), ('text/x-robotframework',)),\n    'RqlLexer': ('pip._vendor.pygments.lexers.sql', 'RQL', ('rql',), ('*.rql',), ('text/x-rql',)),\n    'RslLexer': ('pip._vendor.pygments.lexers.dsls', 'RSL', ('rsl',), ('*.rsl',), ('text/rsl',)),\n    'RstLexer': ('pip._vendor.pygments.lexers.markup', 'reStructuredText', ('restructuredtext', 'rst', 'rest'), ('*.rst', '*.rest'), ('text/x-rst', 'text/prs.fallenstein.rst')),\n    'RtsLexer': ('pip._vendor.pygments.lexers.trafficscript', 'TrafficScript', ('trafficscript', 'rts'), ('*.rts',), ()),\n    'RubyConsoleLexer': ('pip._vendor.pygments.lexers.ruby', 'Ruby irb session', ('rbcon', 'irb'), (), ('text/x-ruby-shellsession',)),\n    'RubyLexer': ('pip._vendor.pygments.lexers.ruby', 'Ruby', ('ruby', 'rb', 'duby'), ('*.rb', '*.rbw', 'Rakefile', '*.rake', '*.gemspec', '*.rbx', '*.duby', 'Gemfile', 'Vagrantfile'), ('text/x-ruby', 'application/x-ruby')),\n    'RustLexer': ('pip._vendor.pygments.lexers.rust', 'Rust', ('rust', 'rs'), ('*.rs', '*.rs.in'), ('text/rust', 'text/x-rust')),\n    'SASLexer': ('pip._vendor.pygments.lexers.sas', 'SAS', ('sas',), ('*.SAS', '*.sas'), ('text/x-sas', 'text/sas', 'application/x-sas')),\n    'SLexer': ('pip._vendor.pygments.lexers.r', 'S', ('splus', 's', 'r'), ('*.S', '*.R', '.Rhistory', '.Rprofile', '.Renviron'), ('text/S-plus', 'text/S', 'text/x-r-source', 'text/x-r', 'text/x-R', 'text/x-r-history', 'text/x-r-profile')),\n    'SMLLexer': ('pip._vendor.pygments.lexers.ml', 'Standard ML', ('sml',), ('*.sml', '*.sig', '*.fun'), ('text/x-standardml', 'application/x-standardml')),\n    'SNBTLexer': ('pip._vendor.pygments.lexers.mcfunction', 'SNBT', ('snbt',), ('*.snbt',), ('text/snbt',)),\n    'SarlLexer': ('pip._vendor.pygments.lexers.jvm', 'SARL', ('sarl',), ('*.sarl',), ('text/x-sarl',)),\n    'SassLexer': ('pip._vendor.pygments.lexers.css', 'Sass', ('sass',), ('*.sass',), ('text/x-sass',)),\n    'SaviLexer': ('pip._vendor.pygments.lexers.savi', 'Savi', ('savi',), ('*.savi',), ()),\n    'ScalaLexer': ('pip._vendor.pygments.lexers.jvm', 'Scala', ('scala',), ('*.scala',), ('text/x-scala',)),\n    'ScamlLexer': ('pip._vendor.pygments.lexers.html', 'Scaml', ('scaml',), ('*.scaml',), ('text/x-scaml',)),\n    'ScdocLexer': ('pip._vendor.pygments.lexers.scdoc', 'scdoc', ('scdoc', 'scd'), ('*.scd', '*.scdoc'), ()),\n    'SchemeLexer': ('pip._vendor.pygments.lexers.lisp', 'Scheme', ('scheme', 'scm'), ('*.scm', '*.ss'), ('text/x-scheme', 'application/x-scheme')),\n    'ScilabLexer': ('pip._vendor.pygments.lexers.matlab', 'Scilab', ('scilab',), ('*.sci', '*.sce', '*.tst'), ('text/scilab',)),\n    'ScssLexer': ('pip._vendor.pygments.lexers.css', 'SCSS', ('scss',), ('*.scss',), ('text/x-scss',)),\n    'SedLexer': ('pip._vendor.pygments.lexers.textedit', 'Sed', ('sed', 'gsed', 'ssed'), ('*.sed', '*.[gs]sed'), ('text/x-sed',)),\n    'ShExCLexer': ('pip._vendor.pygments.lexers.rdf', 'ShExC', ('shexc', 'shex'), ('*.shex',), ('text/shex',)),\n    'ShenLexer': ('pip._vendor.pygments.lexers.lisp', 'Shen', ('shen',), ('*.shen',), ('text/x-shen', 'application/x-shen')),\n    'SieveLexer': ('pip._vendor.pygments.lexers.sieve', 'Sieve', ('sieve',), ('*.siv', '*.sieve'), ()),\n    'SilverLexer': ('pip._vendor.pygments.lexers.verification', 'Silver', ('silver',), ('*.sil', '*.vpr'), ()),\n    'SingularityLexer': ('pip._vendor.pygments.lexers.configs', 'Singularity', ('singularity',), ('*.def', 'Singularity'), ()),\n    'SlashLexer': ('pip._vendor.pygments.lexers.slash', 'Slash', ('slash',), ('*.sla',), ()),\n    'SlimLexer': ('pip._vendor.pygments.lexers.webmisc', 'Slim', ('slim',), ('*.slim',), ('text/x-slim',)),\n    'SlurmBashLexer': ('pip._vendor.pygments.lexers.shell', 'Slurm', ('slurm', 'sbatch'), ('*.sl',), ()),\n    'SmaliLexer': ('pip._vendor.pygments.lexers.dalvik', 'Smali', ('smali',), ('*.smali',), ('text/smali',)),\n    'SmalltalkLexer': ('pip._vendor.pygments.lexers.smalltalk', 'Smalltalk', ('smalltalk', 'squeak', 'st'), ('*.st',), ('text/x-smalltalk',)),\n    'SmartGameFormatLexer': ('pip._vendor.pygments.lexers.sgf', 'SmartGameFormat', ('sgf',), ('*.sgf',), ()),\n    'SmartyLexer': ('pip._vendor.pygments.lexers.templates', 'Smarty', ('smarty',), ('*.tpl',), ('application/x-smarty',)),\n    'SmithyLexer': ('pip._vendor.pygments.lexers.smithy', 'Smithy', ('smithy',), ('*.smithy',), ()),\n    'SnobolLexer': ('pip._vendor.pygments.lexers.snobol', 'Snobol', ('snobol',), ('*.snobol',), ('text/x-snobol',)),\n    'SnowballLexer': ('pip._vendor.pygments.lexers.dsls', 'Snowball', ('snowball',), ('*.sbl',), ()),\n    'SolidityLexer': ('pip._vendor.pygments.lexers.solidity', 'Solidity', ('solidity',), ('*.sol',), ()),\n    'SophiaLexer': ('pip._vendor.pygments.lexers.sophia', 'Sophia', ('sophia',), ('*.aes',), ()),\n    'SourcePawnLexer': ('pip._vendor.pygments.lexers.pawn', 'SourcePawn', ('sp',), ('*.sp',), ('text/x-sourcepawn',)),\n    'SourcesListLexer': ('pip._vendor.pygments.lexers.installers', 'Debian Sourcelist', ('debsources', 'sourceslist', 'sources.list'), ('sources.list',), ()),\n    'SparqlLexer': ('pip._vendor.pygments.lexers.rdf', 'SPARQL', ('sparql',), ('*.rq', '*.sparql'), ('application/sparql-query',)),\n    'SpiceLexer': ('pip._vendor.pygments.lexers.spice', 'Spice', ('spice', 'spicelang'), ('*.spice',), ('text/x-spice',)),\n    'SqlJinjaLexer': ('pip._vendor.pygments.lexers.templates', 'SQL+Jinja', ('sql+jinja',), ('*.sql', '*.sql.j2', '*.sql.jinja2'), ()),\n    'SqlLexer': ('pip._vendor.pygments.lexers.sql', 'SQL', ('sql',), ('*.sql',), ('text/x-sql',)),\n    'SqliteConsoleLexer': ('pip._vendor.pygments.lexers.sql', 'sqlite3con', ('sqlite3',), ('*.sqlite3-console',), ('text/x-sqlite3-console',)),\n    'SquidConfLexer': ('pip._vendor.pygments.lexers.configs', 'SquidConf', ('squidconf', 'squid.conf', 'squid'), ('squid.conf',), ('text/x-squidconf',)),\n    'SrcinfoLexer': ('pip._vendor.pygments.lexers.srcinfo', 'Srcinfo', ('srcinfo',), ('.SRCINFO',), ()),\n    'SspLexer': ('pip._vendor.pygments.lexers.templates', 'Scalate Server Page', ('ssp',), ('*.ssp',), ('application/x-ssp',)),\n    'StanLexer': ('pip._vendor.pygments.lexers.modeling', 'Stan', ('stan',), ('*.stan',), ()),\n    'StataLexer': ('pip._vendor.pygments.lexers.stata', 'Stata', ('stata', 'do'), ('*.do', '*.ado'), ('text/x-stata', 'text/stata', 'application/x-stata')),\n    'SuperColliderLexer': ('pip._vendor.pygments.lexers.supercollider', 'SuperCollider', ('supercollider', 'sc'), ('*.sc', '*.scd'), ('application/supercollider', 'text/supercollider')),\n    'SwiftLexer': ('pip._vendor.pygments.lexers.objective', 'Swift', ('swift',), ('*.swift',), ('text/x-swift',)),\n    'SwigLexer': ('pip._vendor.pygments.lexers.c_like', 'SWIG', ('swig',), ('*.swg', '*.i'), ('text/swig',)),\n    'SystemVerilogLexer': ('pip._vendor.pygments.lexers.hdl', 'systemverilog', ('systemverilog', 'sv'), ('*.sv', '*.svh'), ('text/x-systemverilog',)),\n    'TAPLexer': ('pip._vendor.pygments.lexers.testing', 'TAP', ('tap',), ('*.tap',), ()),\n    'TNTLexer': ('pip._vendor.pygments.lexers.tnt', 'Typographic Number Theory', ('tnt',), ('*.tnt',), ()),\n    'TOMLLexer': ('pip._vendor.pygments.lexers.configs', 'TOML', ('toml',), ('*.toml', 'Pipfile', 'poetry.lock'), ()),\n    'Tads3Lexer': ('pip._vendor.pygments.lexers.int_fiction', 'TADS 3', ('tads3',), ('*.t',), ()),\n    'TalLexer': ('pip._vendor.pygments.lexers.tal', 'Tal', ('tal', 'uxntal'), ('*.tal',), ('text/x-uxntal',)),\n    'TasmLexer': ('pip._vendor.pygments.lexers.asm', 'TASM', ('tasm',), ('*.asm', '*.ASM', '*.tasm'), ('text/x-tasm',)),\n    'TclLexer': ('pip._vendor.pygments.lexers.tcl', 'Tcl', ('tcl',), ('*.tcl', '*.rvt'), ('text/x-tcl', 'text/x-script.tcl', 'application/x-tcl')),\n    'TcshLexer': ('pip._vendor.pygments.lexers.shell', 'Tcsh', ('tcsh', 'csh'), ('*.tcsh', '*.csh'), ('application/x-csh',)),\n    'TcshSessionLexer': ('pip._vendor.pygments.lexers.shell', 'Tcsh Session', ('tcshcon',), (), ()),\n    'TeaTemplateLexer': ('pip._vendor.pygments.lexers.templates', 'Tea', ('tea',), ('*.tea',), ('text/x-tea',)),\n    'TealLexer': ('pip._vendor.pygments.lexers.teal', 'teal', ('teal',), ('*.teal',), ()),\n    'TeraTermLexer': ('pip._vendor.pygments.lexers.teraterm', 'Tera Term macro', ('teratermmacro', 'teraterm', 'ttl'), ('*.ttl',), ('text/x-teratermmacro',)),\n    'TermcapLexer': ('pip._vendor.pygments.lexers.configs', 'Termcap', ('termcap',), ('termcap', 'termcap.src'), ()),\n    'TerminfoLexer': ('pip._vendor.pygments.lexers.configs', 'Terminfo', ('terminfo',), ('terminfo', 'terminfo.src'), ()),\n    'TerraformLexer': ('pip._vendor.pygments.lexers.configs', 'Terraform', ('terraform', 'tf'), ('*.tf',), ('application/x-tf', 'application/x-terraform')),\n    'TexLexer': ('pip._vendor.pygments.lexers.markup', 'TeX', ('tex', 'latex'), ('*.tex', '*.aux', '*.toc'), ('text/x-tex', 'text/x-latex')),\n    'TextLexer': ('pip._vendor.pygments.lexers.special', 'Text only', ('text',), ('*.txt',), ('text/plain',)),\n    'ThingsDBLexer': ('pip._vendor.pygments.lexers.thingsdb', 'ThingsDB', ('ti', 'thingsdb'), ('*.ti',), ()),\n    'ThriftLexer': ('pip._vendor.pygments.lexers.dsls', 'Thrift', ('thrift',), ('*.thrift',), ('application/x-thrift',)),\n    'TiddlyWiki5Lexer': ('pip._vendor.pygments.lexers.markup', 'tiddler', ('tid',), ('*.tid',), ('text/vnd.tiddlywiki',)),\n    'TodotxtLexer': ('pip._vendor.pygments.lexers.textfmts', 'Todotxt', ('todotxt',), ('todo.txt', '*.todotxt'), ('text/x-todo',)),\n    'TransactSqlLexer': ('pip._vendor.pygments.lexers.sql', 'Transact-SQL', ('tsql', 't-sql'), ('*.sql',), ('text/x-tsql',)),\n    'TreetopLexer': ('pip._vendor.pygments.lexers.parsers', 'Treetop', ('treetop',), ('*.treetop', '*.tt'), ()),\n    'TurtleLexer': ('pip._vendor.pygments.lexers.rdf', 'Turtle', ('turtle',), ('*.ttl',), ('text/turtle', 'application/x-turtle')),\n    'TwigHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Twig', ('html+twig',), ('*.twig',), ('text/html+twig',)),\n    'TwigLexer': ('pip._vendor.pygments.lexers.templates', 'Twig', ('twig',), (), ('application/x-twig',)),\n    'TypeScriptLexer': ('pip._vendor.pygments.lexers.javascript', 'TypeScript', ('typescript', 'ts'), ('*.ts',), ('application/x-typescript', 'text/x-typescript')),\n    'TypoScriptCssDataLexer': ('pip._vendor.pygments.lexers.typoscript', 'TypoScriptCssData', ('typoscriptcssdata',), (), ()),\n    'TypoScriptHtmlDataLexer': ('pip._vendor.pygments.lexers.typoscript', 'TypoScriptHtmlData', ('typoscripthtmldata',), (), ()),\n    'TypoScriptLexer': ('pip._vendor.pygments.lexers.typoscript', 'TypoScript', ('typoscript',), ('*.typoscript',), ('text/x-typoscript',)),\n    'UL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'UL4', ('ul4',), ('*.ul4',), ()),\n    'UcodeLexer': ('pip._vendor.pygments.lexers.unicon', 'ucode', ('ucode',), ('*.u', '*.u1', '*.u2'), ()),\n    'UniconLexer': ('pip._vendor.pygments.lexers.unicon', 'Unicon', ('unicon',), ('*.icn',), ('text/unicon',)),\n    'UnixConfigLexer': ('pip._vendor.pygments.lexers.configs', 'Unix/Linux config files', ('unixconfig', 'linuxconfig'), (), ()),\n    'UrbiscriptLexer': ('pip._vendor.pygments.lexers.urbi', 'UrbiScript', ('urbiscript',), ('*.u',), ('application/x-urbiscript',)),\n    'UsdLexer': ('pip._vendor.pygments.lexers.usd', 'USD', ('usd', 'usda'), ('*.usd', '*.usda'), ()),\n    'VBScriptLexer': ('pip._vendor.pygments.lexers.basic', 'VBScript', ('vbscript',), ('*.vbs', '*.VBS'), ()),\n    'VCLLexer': ('pip._vendor.pygments.lexers.varnish', 'VCL', ('vcl',), ('*.vcl',), ('text/x-vclsrc',)),\n    'VCLSnippetLexer': ('pip._vendor.pygments.lexers.varnish', 'VCLSnippets', ('vclsnippets', 'vclsnippet'), (), ('text/x-vclsnippet',)),\n    'VCTreeStatusLexer': ('pip._vendor.pygments.lexers.console', 'VCTreeStatus', ('vctreestatus',), (), ()),\n    'VGLLexer': ('pip._vendor.pygments.lexers.dsls', 'VGL', ('vgl',), ('*.rpf',), ()),\n    'ValaLexer': ('pip._vendor.pygments.lexers.c_like', 'Vala', ('vala', 'vapi'), ('*.vala', '*.vapi'), ('text/x-vala',)),\n    'VbNetAspxLexer': ('pip._vendor.pygments.lexers.dotnet', 'aspx-vb', ('aspx-vb',), ('*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd'), ()),\n    'VbNetLexer': ('pip._vendor.pygments.lexers.dotnet', 'VB.net', ('vb.net', 'vbnet', 'lobas', 'oobas', 'sobas'), ('*.vb', '*.bas'), ('text/x-vbnet', 'text/x-vba')),\n    'VelocityHtmlLexer': ('pip._vendor.pygments.lexers.templates', 'HTML+Velocity', ('html+velocity',), (), ('text/html+velocity',)),\n    'VelocityLexer': ('pip._vendor.pygments.lexers.templates', 'Velocity', ('velocity',), ('*.vm', '*.fhtml'), ()),\n    'VelocityXmlLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Velocity', ('xml+velocity',), (), ('application/xml+velocity',)),\n    'VerilogLexer': ('pip._vendor.pygments.lexers.hdl', 'verilog', ('verilog', 'v'), ('*.v',), ('text/x-verilog',)),\n    'VhdlLexer': ('pip._vendor.pygments.lexers.hdl', 'vhdl', ('vhdl',), ('*.vhdl', '*.vhd'), ('text/x-vhdl',)),\n    'VimLexer': ('pip._vendor.pygments.lexers.textedit', 'VimL', ('vim',), ('*.vim', '.vimrc', '.exrc', '.gvimrc', '_vimrc', '_exrc', '_gvimrc', 'vimrc', 'gvimrc'), ('text/x-vim',)),\n    'WDiffLexer': ('pip._vendor.pygments.lexers.diff', 'WDiff', ('wdiff',), ('*.wdiff',), ()),\n    'WatLexer': ('pip._vendor.pygments.lexers.webassembly', 'WebAssembly', ('wast', 'wat'), ('*.wat', '*.wast'), ()),\n    'WebIDLLexer': ('pip._vendor.pygments.lexers.webidl', 'Web IDL', ('webidl',), ('*.webidl',), ()),\n    'WhileyLexer': ('pip._vendor.pygments.lexers.whiley', 'Whiley', ('whiley',), ('*.whiley',), ('text/x-whiley',)),\n    'X10Lexer': ('pip._vendor.pygments.lexers.x10', 'X10', ('x10', 'xten'), ('*.x10',), ('text/x-x10',)),\n    'XMLUL4Lexer': ('pip._vendor.pygments.lexers.ul4', 'XML+UL4', ('xml+ul4',), ('*.xmlul4',), ()),\n    'XQueryLexer': ('pip._vendor.pygments.lexers.webmisc', 'XQuery', ('xquery', 'xqy', 'xq', 'xql', 'xqm'), ('*.xqy', '*.xquery', '*.xq', '*.xql', '*.xqm'), ('text/xquery', 'application/xquery')),\n    'XmlDjangoLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Django/Jinja', ('xml+django', 'xml+jinja'), ('*.xml.j2', '*.xml.jinja2'), ('application/xml+django', 'application/xml+jinja')),\n    'XmlErbLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Ruby', ('xml+ruby', 'xml+erb'), (), ('application/xml+ruby',)),\n    'XmlLexer': ('pip._vendor.pygments.lexers.html', 'XML', ('xml',), ('*.xml', '*.xsl', '*.rss', '*.xslt', '*.xsd', '*.wsdl', '*.wsf'), ('text/xml', 'application/xml', 'image/svg+xml', 'application/rss+xml', 'application/atom+xml')),\n    'XmlPhpLexer': ('pip._vendor.pygments.lexers.templates', 'XML+PHP', ('xml+php',), (), ('application/xml+php',)),\n    'XmlSmartyLexer': ('pip._vendor.pygments.lexers.templates', 'XML+Smarty', ('xml+smarty',), (), ('application/xml+smarty',)),\n    'XorgLexer': ('pip._vendor.pygments.lexers.xorg', 'Xorg', ('xorg.conf',), ('xorg.conf',), ()),\n    'XsltLexer': ('pip._vendor.pygments.lexers.html', 'XSLT', ('xslt',), ('*.xsl', '*.xslt', '*.xpl'), ('application/xsl+xml', 'application/xslt+xml')),\n    'XtendLexer': ('pip._vendor.pygments.lexers.jvm', 'Xtend', ('xtend',), ('*.xtend',), ('text/x-xtend',)),\n    'XtlangLexer': ('pip._vendor.pygments.lexers.lisp', 'xtlang', ('extempore',), ('*.xtm',), ()),\n    'YamlJinjaLexer': ('pip._vendor.pygments.lexers.templates', 'YAML+Jinja', ('yaml+jinja', 'salt', 'sls'), ('*.sls', '*.yaml.j2', '*.yml.j2', '*.yaml.jinja2', '*.yml.jinja2'), ('text/x-yaml+jinja', 'text/x-sls')),\n    'YamlLexer': ('pip._vendor.pygments.lexers.data', 'YAML', ('yaml',), ('*.yaml', '*.yml'), ('text/x-yaml',)),\n    'YangLexer': ('pip._vendor.pygments.lexers.yang', 'YANG', ('yang',), ('*.yang',), ('application/yang',)),\n    'ZeekLexer': ('pip._vendor.pygments.lexers.dsls', 'Zeek', ('zeek', 'bro'), ('*.zeek', '*.bro'), ()),\n    'ZephirLexer': ('pip._vendor.pygments.lexers.php', 'Zephir', ('zephir',), ('*.zep',), ()),\n    'ZigLexer': ('pip._vendor.pygments.lexers.zig', 'Zig', ('zig',), ('*.zig',), ('text/zig',)),\n    'apdlexer': ('pip._vendor.pygments.lexers.apdlexer', 'ANSYS parametric design language', ('ansys', 'apdl'), ('*.ans',), ()),\n}\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/lexers/python.py",
    "content": "\"\"\"\n    pygments.lexers.python\n    ~~~~~~~~~~~~~~~~~~~~~~\n\n    Lexers for Python and related languages.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\nimport keyword\n\nfrom pip._vendor.pygments.lexer import Lexer, RegexLexer, include, bygroups, using, \\\n    default, words, combined, do_insertions, this\nfrom pip._vendor.pygments.util import get_bool_opt, shebang_matches\nfrom pip._vendor.pygments.token import Text, Comment, Operator, Keyword, Name, String, \\\n    Number, Punctuation, Generic, Other, Error\nfrom pip._vendor.pygments import unistring as uni\n\n__all__ = ['PythonLexer', 'PythonConsoleLexer', 'PythonTracebackLexer',\n           'Python2Lexer', 'Python2TracebackLexer',\n           'CythonLexer', 'DgLexer', 'NumPyLexer']\n\nline_re = re.compile('.*?\\n')\n\n\nclass PythonLexer(RegexLexer):\n    \"\"\"\n    For Python source code (version 3.x).\n\n    .. versionadded:: 0.10\n\n    .. versionchanged:: 2.5\n       This is now the default ``PythonLexer``.  It is still available as the\n       alias ``Python3Lexer``.\n    \"\"\"\n\n    name = 'Python'\n    url = 'http://www.python.org'\n    aliases = ['python', 'py', 'sage', 'python3', 'py3']\n    filenames = [\n        '*.py',\n        '*.pyw',\n        # Jython\n        '*.jy',\n        # Sage\n        '*.sage',\n        # SCons\n        '*.sc',\n        'SConstruct',\n        'SConscript',\n        # Skylark/Starlark (used by Bazel, Buck, and Pants)\n        '*.bzl',\n        'BUCK',\n        'BUILD',\n        'BUILD.bazel',\n        'WORKSPACE',\n        # Twisted Application infrastructure\n        '*.tac',\n    ]\n    mimetypes = ['text/x-python', 'application/x-python',\n                 'text/x-python3', 'application/x-python3']\n\n    uni_name = \"[%s][%s]*\" % (uni.xid_start, uni.xid_continue)\n\n    def innerstring_rules(ttype):\n        return [\n            # the old style '%s' % (...) string formatting (still valid in Py3)\n            (r'%(\\(\\w+\\))?[-#0 +]*([0-9]+|[*])?(\\.([0-9]+|[*]))?'\n             '[hlL]?[E-GXc-giorsaux%]', String.Interpol),\n            # the new style '{}'.format(...) string formatting\n            (r'\\{'\n             r'((\\w+)((\\.\\w+)|(\\[[^\\]]+\\]))*)?'  # field name\n             r'(\\![sra])?'                       # conversion\n             r'(\\:(.?[<>=\\^])?[-+ ]?#?0?(\\d+)?,?(\\.\\d+)?[E-GXb-gnosx%]?)?'\n             r'\\}', String.Interpol),\n\n            # backslashes, quotes and formatting signs must be parsed one at a time\n            (r'[^\\\\\\'\"%{\\n]+', ttype),\n            (r'[\\'\"\\\\]', ttype),\n            # unhandled string formatting sign\n            (r'%|(\\{{1,2})', ttype)\n            # newlines are an error (use \"nl\" state)\n        ]\n\n    def fstring_rules(ttype):\n        return [\n            # Assuming that a '}' is the closing brace after format specifier.\n            # Sadly, this means that we won't detect syntax error. But it's\n            # more important to parse correct syntax correctly, than to\n            # highlight invalid syntax.\n            (r'\\}', String.Interpol),\n            (r'\\{', String.Interpol, 'expr-inside-fstring'),\n            # backslashes, quotes and formatting signs must be parsed one at a time\n            (r'[^\\\\\\'\"{}\\n]+', ttype),\n            (r'[\\'\"\\\\]', ttype),\n            # newlines are an error (use \"nl\" state)\n        ]\n\n    tokens = {\n        'root': [\n            (r'\\n', Text),\n            (r'^(\\s*)([rRuUbB]{,2})(\"\"\"(?:.|\\n)*?\"\"\")',\n             bygroups(Text, String.Affix, String.Doc)),\n            (r\"^(\\s*)([rRuUbB]{,2})('''(?:.|\\n)*?''')\",\n             bygroups(Text, String.Affix, String.Doc)),\n            (r'\\A#!.+$', Comment.Hashbang),\n            (r'#.*$', Comment.Single),\n            (r'\\\\\\n', Text),\n            (r'\\\\', Text),\n            include('keywords'),\n            include('soft-keywords'),\n            (r'(def)((?:\\s|\\\\\\s)+)', bygroups(Keyword, Text), 'funcname'),\n            (r'(class)((?:\\s|\\\\\\s)+)', bygroups(Keyword, Text), 'classname'),\n            (r'(from)((?:\\s|\\\\\\s)+)', bygroups(Keyword.Namespace, Text),\n             'fromimport'),\n            (r'(import)((?:\\s|\\\\\\s)+)', bygroups(Keyword.Namespace, Text),\n             'import'),\n            include('expr'),\n        ],\n        'expr': [\n            # raw f-strings\n            ('(?i)(rf|fr)(\"\"\")',\n             bygroups(String.Affix, String.Double),\n             combined('rfstringescape', 'tdqf')),\n            (\"(?i)(rf|fr)(''')\",\n             bygroups(String.Affix, String.Single),\n             combined('rfstringescape', 'tsqf')),\n            ('(?i)(rf|fr)(\")',\n             bygroups(String.Affix, String.Double),\n             combined('rfstringescape', 'dqf')),\n            (\"(?i)(rf|fr)(')\",\n             bygroups(String.Affix, String.Single),\n             combined('rfstringescape', 'sqf')),\n            # non-raw f-strings\n            ('([fF])(\"\"\")', bygroups(String.Affix, String.Double),\n             combined('fstringescape', 'tdqf')),\n            (\"([fF])(''')\", bygroups(String.Affix, String.Single),\n             combined('fstringescape', 'tsqf')),\n            ('([fF])(\")', bygroups(String.Affix, String.Double),\n             combined('fstringescape', 'dqf')),\n            (\"([fF])(')\", bygroups(String.Affix, String.Single),\n             combined('fstringescape', 'sqf')),\n            # raw bytes and strings\n            ('(?i)(rb|br|r)(\"\"\")',\n             bygroups(String.Affix, String.Double), 'tdqs'),\n            (\"(?i)(rb|br|r)(''')\",\n             bygroups(String.Affix, String.Single), 'tsqs'),\n            ('(?i)(rb|br|r)(\")',\n             bygroups(String.Affix, String.Double), 'dqs'),\n            (\"(?i)(rb|br|r)(')\",\n             bygroups(String.Affix, String.Single), 'sqs'),\n            # non-raw strings\n            ('([uU]?)(\"\"\")', bygroups(String.Affix, String.Double),\n             combined('stringescape', 'tdqs')),\n            (\"([uU]?)(''')\", bygroups(String.Affix, String.Single),\n             combined('stringescape', 'tsqs')),\n            ('([uU]?)(\")', bygroups(String.Affix, String.Double),\n             combined('stringescape', 'dqs')),\n            (\"([uU]?)(')\", bygroups(String.Affix, String.Single),\n             combined('stringescape', 'sqs')),\n            # non-raw bytes\n            ('([bB])(\"\"\")', bygroups(String.Affix, String.Double),\n             combined('bytesescape', 'tdqs')),\n            (\"([bB])(''')\", bygroups(String.Affix, String.Single),\n             combined('bytesescape', 'tsqs')),\n            ('([bB])(\")', bygroups(String.Affix, String.Double),\n             combined('bytesescape', 'dqs')),\n            (\"([bB])(')\", bygroups(String.Affix, String.Single),\n             combined('bytesescape', 'sqs')),\n            \n            (r'[^\\S\\n]+', Text),\n            include('numbers'),\n            (r'!=|==|<<|>>|:=|[-~+/*%=<>&^|.]', Operator),\n            (r'[]{}:(),;[]', Punctuation),\n            (r'(in|is|and|or|not)\\b', Operator.Word),\n            include('expr-keywords'),\n            include('builtins'),\n            include('magicfuncs'),\n            include('magicvars'),\n            include('name'),\n        ],\n        'expr-inside-fstring': [\n            (r'[{([]', Punctuation, 'expr-inside-fstring-inner'),\n            # without format specifier\n            (r'(=\\s*)?'         # debug (https://bugs.python.org/issue36817)\n             r'(\\![sraf])?'     # conversion\n             r'\\}', String.Interpol, '#pop'),\n            # with format specifier\n            # we'll catch the remaining '}' in the outer scope\n            (r'(=\\s*)?'         # debug (https://bugs.python.org/issue36817)\n             r'(\\![sraf])?'     # conversion\n             r':', String.Interpol, '#pop'),\n            (r'\\s+', Text),  # allow new lines\n            include('expr'),\n        ],\n        'expr-inside-fstring-inner': [\n            (r'[{([]', Punctuation, 'expr-inside-fstring-inner'),\n            (r'[])}]', Punctuation, '#pop'),\n            (r'\\s+', Text),  # allow new lines\n            include('expr'),\n        ],\n        'expr-keywords': [\n            # Based on https://docs.python.org/3/reference/expressions.html\n            (words((\n                'async for', 'await', 'else', 'for', 'if', 'lambda',\n                'yield', 'yield from'), suffix=r'\\b'),\n             Keyword),\n            (words(('True', 'False', 'None'), suffix=r'\\b'), Keyword.Constant),\n        ],\n        'keywords': [\n            (words((\n                'assert', 'async', 'await', 'break', 'continue', 'del', 'elif',\n                'else', 'except', 'finally', 'for', 'global', 'if', 'lambda',\n                'pass', 'raise', 'nonlocal', 'return', 'try', 'while', 'yield',\n                'yield from', 'as', 'with'), suffix=r'\\b'),\n             Keyword),\n            (words(('True', 'False', 'None'), suffix=r'\\b'), Keyword.Constant),\n        ],\n        'soft-keywords': [\n            # `match`, `case` and `_` soft keywords\n            (r'(^[ \\t]*)'              # at beginning of line + possible indentation\n             r'(match|case)\\b'         # a possible keyword\n             r'(?![ \\t]*(?:'           # not followed by...\n             r'[:,;=^&|@~)\\]}]|(?:' +  # characters and keywords that mean this isn't\n             r'|'.join(keyword.kwlist) + r')\\b))',                 # pattern matching\n             bygroups(Text, Keyword), 'soft-keywords-inner'),\n        ],\n        'soft-keywords-inner': [\n            # optional `_` keyword\n            (r'(\\s+)([^\\n_]*)(_\\b)', bygroups(Text, using(this), Keyword)),\n            default('#pop')\n        ],\n        'builtins': [\n            (words((\n                '__import__', 'abs', 'all', 'any', 'bin', 'bool', 'bytearray',\n                'breakpoint', 'bytes', 'chr', 'classmethod', 'compile', 'complex',\n                'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'filter',\n                'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',\n                'hash', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',\n                'iter', 'len', 'list', 'locals', 'map', 'max', 'memoryview',\n                'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print',\n                'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr',\n                'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',\n                'type', 'vars', 'zip'), prefix=r'(?<!\\.)', suffix=r'\\b'),\n             Name.Builtin),\n            (r'(?<!\\.)(self|Ellipsis|NotImplemented|cls)\\b', Name.Builtin.Pseudo),\n            (words((\n                'ArithmeticError', 'AssertionError', 'AttributeError',\n                'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning',\n                'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError',\n                'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',\n                'ImportWarning', 'IndentationError', 'IndexError', 'KeyError',\n                'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError',\n                'NotImplementedError', 'OSError', 'OverflowError',\n                'PendingDeprecationWarning', 'ReferenceError', 'ResourceWarning',\n                'RuntimeError', 'RuntimeWarning', 'StopIteration',\n                'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit',\n                'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',\n                'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',\n                'UnicodeWarning', 'UserWarning', 'ValueError', 'VMSError',\n                'Warning', 'WindowsError', 'ZeroDivisionError',\n                # new builtin exceptions from PEP 3151\n                'BlockingIOError', 'ChildProcessError', 'ConnectionError',\n                'BrokenPipeError', 'ConnectionAbortedError', 'ConnectionRefusedError',\n                'ConnectionResetError', 'FileExistsError', 'FileNotFoundError',\n                'InterruptedError', 'IsADirectoryError', 'NotADirectoryError',\n                'PermissionError', 'ProcessLookupError', 'TimeoutError',\n                # others new in Python 3\n                'StopAsyncIteration', 'ModuleNotFoundError', 'RecursionError',\n                'EncodingWarning'),\n                prefix=r'(?<!\\.)', suffix=r'\\b'),\n             Name.Exception),\n        ],\n        'magicfuncs': [\n            (words((\n                '__abs__', '__add__', '__aenter__', '__aexit__', '__aiter__',\n                '__and__', '__anext__', '__await__', '__bool__', '__bytes__',\n                '__call__', '__complex__', '__contains__', '__del__', '__delattr__',\n                '__delete__', '__delitem__', '__dir__', '__divmod__', '__enter__',\n                '__eq__', '__exit__', '__float__', '__floordiv__', '__format__',\n                '__ge__', '__get__', '__getattr__', '__getattribute__',\n                '__getitem__', '__gt__', '__hash__', '__iadd__', '__iand__',\n                '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__',\n                '__imul__', '__index__', '__init__', '__instancecheck__',\n                '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__',\n                '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__',\n                '__len__', '__length_hint__', '__lshift__', '__lt__', '__matmul__',\n                '__missing__', '__mod__', '__mul__', '__ne__', '__neg__',\n                '__new__', '__next__', '__or__', '__pos__', '__pow__',\n                '__prepare__', '__radd__', '__rand__', '__rdivmod__', '__repr__',\n                '__reversed__', '__rfloordiv__', '__rlshift__', '__rmatmul__',\n                '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__',\n                '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__',\n                '__rxor__', '__set__', '__setattr__', '__setitem__', '__str__',\n                '__sub__', '__subclasscheck__', '__truediv__',\n                '__xor__'), suffix=r'\\b'),\n             Name.Function.Magic),\n        ],\n        'magicvars': [\n            (words((\n                '__annotations__', '__bases__', '__class__', '__closure__',\n                '__code__', '__defaults__', '__dict__', '__doc__', '__file__',\n                '__func__', '__globals__', '__kwdefaults__', '__module__',\n                '__mro__', '__name__', '__objclass__', '__qualname__',\n                '__self__', '__slots__', '__weakref__'), suffix=r'\\b'),\n             Name.Variable.Magic),\n        ],\n        'numbers': [\n            (r'(\\d(?:_?\\d)*\\.(?:\\d(?:_?\\d)*)?|(?:\\d(?:_?\\d)*)?\\.\\d(?:_?\\d)*)'\n             r'([eE][+-]?\\d(?:_?\\d)*)?', Number.Float),\n            (r'\\d(?:_?\\d)*[eE][+-]?\\d(?:_?\\d)*j?', Number.Float),\n            (r'0[oO](?:_?[0-7])+', Number.Oct),\n            (r'0[bB](?:_?[01])+', Number.Bin),\n            (r'0[xX](?:_?[a-fA-F0-9])+', Number.Hex),\n            (r'\\d(?:_?\\d)*', Number.Integer),\n        ],\n        'name': [\n            (r'@' + uni_name, Name.Decorator),\n            (r'@', Operator),  # new matrix multiplication operator\n            (uni_name, Name),\n        ],\n        'funcname': [\n            include('magicfuncs'),\n            (uni_name, Name.Function, '#pop'),\n            default('#pop'),\n        ],\n        'classname': [\n            (uni_name, Name.Class, '#pop'),\n        ],\n        'import': [\n            (r'(\\s+)(as)(\\s+)', bygroups(Text, Keyword, Text)),\n            (r'\\.', Name.Namespace),\n            (uni_name, Name.Namespace),\n            (r'(\\s*)(,)(\\s*)', bygroups(Text, Operator, Text)),\n            default('#pop')  # all else: go back\n        ],\n        'fromimport': [\n            (r'(\\s+)(import)\\b', bygroups(Text, Keyword.Namespace), '#pop'),\n            (r'\\.', Name.Namespace),\n            # if None occurs here, it's \"raise x from None\", since None can\n            # never be a module name\n            (r'None\\b', Name.Builtin.Pseudo, '#pop'),\n            (uni_name, Name.Namespace),\n            default('#pop'),\n        ],\n        'rfstringescape': [\n            (r'\\{\\{', String.Escape),\n            (r'\\}\\}', String.Escape),\n        ],\n        'fstringescape': [\n            include('rfstringescape'),\n            include('stringescape'),\n        ],\n        'bytesescape': [\n            (r'\\\\([\\\\abfnrtv\"\\']|\\n|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)\n        ],\n        'stringescape': [\n            (r'\\\\(N\\{.*?\\}|u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8})', String.Escape),\n            include('bytesescape')\n        ],\n        'fstrings-single': fstring_rules(String.Single),\n        'fstrings-double': fstring_rules(String.Double),\n        'strings-single': innerstring_rules(String.Single),\n        'strings-double': innerstring_rules(String.Double),\n        'dqf': [\n            (r'\"', String.Double, '#pop'),\n            (r'\\\\\\\\|\\\\\"|\\\\\\n', String.Escape),  # included here for raw strings\n            include('fstrings-double')\n        ],\n        'sqf': [\n            (r\"'\", String.Single, '#pop'),\n            (r\"\\\\\\\\|\\\\'|\\\\\\n\", String.Escape),  # included here for raw strings\n            include('fstrings-single')\n        ],\n        'dqs': [\n            (r'\"', String.Double, '#pop'),\n            (r'\\\\\\\\|\\\\\"|\\\\\\n', String.Escape),  # included here for raw strings\n            include('strings-double')\n        ],\n        'sqs': [\n            (r\"'\", String.Single, '#pop'),\n            (r\"\\\\\\\\|\\\\'|\\\\\\n\", String.Escape),  # included here for raw strings\n            include('strings-single')\n        ],\n        'tdqf': [\n            (r'\"\"\"', String.Double, '#pop'),\n            include('fstrings-double'),\n            (r'\\n', String.Double)\n        ],\n        'tsqf': [\n            (r\"'''\", String.Single, '#pop'),\n            include('fstrings-single'),\n            (r'\\n', String.Single)\n        ],\n        'tdqs': [\n            (r'\"\"\"', String.Double, '#pop'),\n            include('strings-double'),\n            (r'\\n', String.Double)\n        ],\n        'tsqs': [\n            (r\"'''\", String.Single, '#pop'),\n            include('strings-single'),\n            (r'\\n', String.Single)\n        ],\n    }\n\n    def analyse_text(text):\n        return shebang_matches(text, r'pythonw?(3(\\.\\d)?)?') or \\\n            'import ' in text[:1000]\n\n\nPython3Lexer = PythonLexer\n\n\nclass Python2Lexer(RegexLexer):\n    \"\"\"\n    For Python 2.x source code.\n\n    .. versionchanged:: 2.5\n       This class has been renamed from ``PythonLexer``.  ``PythonLexer`` now\n       refers to the Python 3 variant.  File name patterns like ``*.py`` have\n       been moved to Python 3 as well.\n    \"\"\"\n\n    name = 'Python 2.x'\n    url = 'http://www.python.org'\n    aliases = ['python2', 'py2']\n    filenames = []  # now taken over by PythonLexer (3.x)\n    mimetypes = ['text/x-python2', 'application/x-python2']\n\n    def innerstring_rules(ttype):\n        return [\n            # the old style '%s' % (...) string formatting\n            (r'%(\\(\\w+\\))?[-#0 +]*([0-9]+|[*])?(\\.([0-9]+|[*]))?'\n             '[hlL]?[E-GXc-giorsux%]', String.Interpol),\n            # backslashes, quotes and formatting signs must be parsed one at a time\n            (r'[^\\\\\\'\"%\\n]+', ttype),\n            (r'[\\'\"\\\\]', ttype),\n            # unhandled string formatting sign\n            (r'%', ttype),\n            # newlines are an error (use \"nl\" state)\n        ]\n\n    tokens = {\n        'root': [\n            (r'\\n', Text),\n            (r'^(\\s*)([rRuUbB]{,2})(\"\"\"(?:.|\\n)*?\"\"\")',\n             bygroups(Text, String.Affix, String.Doc)),\n            (r\"^(\\s*)([rRuUbB]{,2})('''(?:.|\\n)*?''')\",\n             bygroups(Text, String.Affix, String.Doc)),\n            (r'[^\\S\\n]+', Text),\n            (r'\\A#!.+$', Comment.Hashbang),\n            (r'#.*$', Comment.Single),\n            (r'[]{}:(),;[]', Punctuation),\n            (r'\\\\\\n', Text),\n            (r'\\\\', Text),\n            (r'(in|is|and|or|not)\\b', Operator.Word),\n            (r'!=|==|<<|>>|[-~+/*%=<>&^|.]', Operator),\n            include('keywords'),\n            (r'(def)((?:\\s|\\\\\\s)+)', bygroups(Keyword, Text), 'funcname'),\n            (r'(class)((?:\\s|\\\\\\s)+)', bygroups(Keyword, Text), 'classname'),\n            (r'(from)((?:\\s|\\\\\\s)+)', bygroups(Keyword.Namespace, Text),\n             'fromimport'),\n            (r'(import)((?:\\s|\\\\\\s)+)', bygroups(Keyword.Namespace, Text),\n             'import'),\n            include('builtins'),\n            include('magicfuncs'),\n            include('magicvars'),\n            include('backtick'),\n            ('([rR]|[uUbB][rR]|[rR][uUbB])(\"\"\")',\n             bygroups(String.Affix, String.Double), 'tdqs'),\n            (\"([rR]|[uUbB][rR]|[rR][uUbB])(''')\",\n             bygroups(String.Affix, String.Single), 'tsqs'),\n            ('([rR]|[uUbB][rR]|[rR][uUbB])(\")',\n             bygroups(String.Affix, String.Double), 'dqs'),\n            (\"([rR]|[uUbB][rR]|[rR][uUbB])(')\",\n             bygroups(String.Affix, String.Single), 'sqs'),\n            ('([uUbB]?)(\"\"\")', bygroups(String.Affix, String.Double),\n             combined('stringescape', 'tdqs')),\n            (\"([uUbB]?)(''')\", bygroups(String.Affix, String.Single),\n             combined('stringescape', 'tsqs')),\n            ('([uUbB]?)(\")', bygroups(String.Affix, String.Double),\n             combined('stringescape', 'dqs')),\n            (\"([uUbB]?)(')\", bygroups(String.Affix, String.Single),\n             combined('stringescape', 'sqs')),\n            include('name'),\n            include('numbers'),\n        ],\n        'keywords': [\n            (words((\n                'assert', 'break', 'continue', 'del', 'elif', 'else', 'except',\n                'exec', 'finally', 'for', 'global', 'if', 'lambda', 'pass',\n                'print', 'raise', 'return', 'try', 'while', 'yield',\n                'yield from', 'as', 'with'), suffix=r'\\b'),\n             Keyword),\n        ],\n        'builtins': [\n            (words((\n                '__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin',\n                'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod',\n                'cmp', 'coerce', 'compile', 'complex', 'delattr', 'dict', 'dir', 'divmod',\n                'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',\n                'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'hex', 'id',\n                'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len',\n                'list', 'locals', 'long', 'map', 'max', 'min', 'next', 'object',\n                'oct', 'open', 'ord', 'pow', 'property', 'range', 'raw_input', 'reduce',\n                'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',\n                'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type',\n                'unichr', 'unicode', 'vars', 'xrange', 'zip'),\n                prefix=r'(?<!\\.)', suffix=r'\\b'),\n             Name.Builtin),\n            (r'(?<!\\.)(self|None|Ellipsis|NotImplemented|False|True|cls'\n             r')\\b', Name.Builtin.Pseudo),\n            (words((\n                'ArithmeticError', 'AssertionError', 'AttributeError',\n                'BaseException', 'DeprecationWarning', 'EOFError', 'EnvironmentError',\n                'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit',\n                'IOError', 'ImportError', 'ImportWarning', 'IndentationError',\n                'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError',\n                'MemoryError', 'NameError',\n                'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning',\n                'PendingDeprecationWarning', 'ReferenceError',\n                'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration',\n                'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit',\n                'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',\n                'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',\n                'UnicodeWarning', 'UserWarning', 'ValueError', 'VMSError', 'Warning',\n                'WindowsError', 'ZeroDivisionError'), prefix=r'(?<!\\.)', suffix=r'\\b'),\n             Name.Exception),\n        ],\n        'magicfuncs': [\n            (words((\n                '__abs__', '__add__', '__and__', '__call__', '__cmp__', '__coerce__',\n                '__complex__', '__contains__', '__del__', '__delattr__', '__delete__',\n                '__delitem__', '__delslice__', '__div__', '__divmod__', '__enter__',\n                '__eq__', '__exit__', '__float__', '__floordiv__', '__ge__', '__get__',\n                '__getattr__', '__getattribute__', '__getitem__', '__getslice__', '__gt__',\n                '__hash__', '__hex__', '__iadd__', '__iand__', '__idiv__', '__ifloordiv__',\n                '__ilshift__', '__imod__', '__imul__', '__index__', '__init__',\n                '__instancecheck__', '__int__', '__invert__', '__iop__', '__ior__',\n                '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__',\n                '__ixor__', '__le__', '__len__', '__long__', '__lshift__', '__lt__',\n                '__missing__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__',\n                '__nonzero__', '__oct__', '__op__', '__or__', '__pos__', '__pow__',\n                '__radd__', '__rand__', '__rcmp__', '__rdiv__', '__rdivmod__', '__repr__',\n                '__reversed__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__',\n                '__rop__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__',\n                '__rtruediv__', '__rxor__', '__set__', '__setattr__', '__setitem__',\n                '__setslice__', '__str__', '__sub__', '__subclasscheck__', '__truediv__',\n                '__unicode__', '__xor__'), suffix=r'\\b'),\n             Name.Function.Magic),\n        ],\n        'magicvars': [\n            (words((\n                '__bases__', '__class__', '__closure__', '__code__', '__defaults__',\n                '__dict__', '__doc__', '__file__', '__func__', '__globals__',\n                '__metaclass__', '__module__', '__mro__', '__name__', '__self__',\n                '__slots__', '__weakref__'),\n                suffix=r'\\b'),\n             Name.Variable.Magic),\n        ],\n        'numbers': [\n            (r'(\\d+\\.\\d*|\\d*\\.\\d+)([eE][+-]?[0-9]+)?j?', Number.Float),\n            (r'\\d+[eE][+-]?[0-9]+j?', Number.Float),\n            (r'0[0-7]+j?', Number.Oct),\n            (r'0[bB][01]+', Number.Bin),\n            (r'0[xX][a-fA-F0-9]+', Number.Hex),\n            (r'\\d+L', Number.Integer.Long),\n            (r'\\d+j?', Number.Integer)\n        ],\n        'backtick': [\n            ('`.*?`', String.Backtick),\n        ],\n        'name': [\n            (r'@[\\w.]+', Name.Decorator),\n            (r'[a-zA-Z_]\\w*', Name),\n        ],\n        'funcname': [\n            include('magicfuncs'),\n            (r'[a-zA-Z_]\\w*', Name.Function, '#pop'),\n            default('#pop'),\n        ],\n        'classname': [\n            (r'[a-zA-Z_]\\w*', Name.Class, '#pop')\n        ],\n        'import': [\n            (r'(?:[ \\t]|\\\\\\n)+', Text),\n            (r'as\\b', Keyword.Namespace),\n            (r',', Operator),\n            (r'[a-zA-Z_][\\w.]*', Name.Namespace),\n            default('#pop')  # all else: go back\n        ],\n        'fromimport': [\n            (r'(?:[ \\t]|\\\\\\n)+', Text),\n            (r'import\\b', Keyword.Namespace, '#pop'),\n            # if None occurs here, it's \"raise x from None\", since None can\n            # never be a module name\n            (r'None\\b', Name.Builtin.Pseudo, '#pop'),\n            # sadly, in \"raise x from y\" y will be highlighted as namespace too\n            (r'[a-zA-Z_.][\\w.]*', Name.Namespace),\n            # anything else here also means \"raise x from y\" and is therefore\n            # not an error\n            default('#pop'),\n        ],\n        'stringescape': [\n            (r'\\\\([\\\\abfnrtv\"\\']|\\n|N\\{.*?\\}|u[a-fA-F0-9]{4}|'\n             r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)\n        ],\n        'strings-single': innerstring_rules(String.Single),\n        'strings-double': innerstring_rules(String.Double),\n        'dqs': [\n            (r'\"', String.Double, '#pop'),\n            (r'\\\\\\\\|\\\\\"|\\\\\\n', String.Escape),  # included here for raw strings\n            include('strings-double')\n        ],\n        'sqs': [\n            (r\"'\", String.Single, '#pop'),\n            (r\"\\\\\\\\|\\\\'|\\\\\\n\", String.Escape),  # included here for raw strings\n            include('strings-single')\n        ],\n        'tdqs': [\n            (r'\"\"\"', String.Double, '#pop'),\n            include('strings-double'),\n            (r'\\n', String.Double)\n        ],\n        'tsqs': [\n            (r\"'''\", String.Single, '#pop'),\n            include('strings-single'),\n            (r'\\n', String.Single)\n        ],\n    }\n\n    def analyse_text(text):\n        return shebang_matches(text, r'pythonw?2(\\.\\d)?')\n\n\nclass PythonConsoleLexer(Lexer):\n    \"\"\"\n    For Python console output or doctests, such as:\n\n    .. sourcecode:: pycon\n\n        >>> a = 'foo'\n        >>> print a\n        foo\n        >>> 1 / 0\n        Traceback (most recent call last):\n          File \"<stdin>\", line 1, in <module>\n        ZeroDivisionError: integer division or modulo by zero\n\n    Additional options:\n\n    `python3`\n        Use Python 3 lexer for code.  Default is ``True``.\n\n        .. versionadded:: 1.0\n        .. versionchanged:: 2.5\n           Now defaults to ``True``.\n    \"\"\"\n    name = 'Python console session'\n    aliases = ['pycon']\n    mimetypes = ['text/x-python-doctest']\n\n    def __init__(self, **options):\n        self.python3 = get_bool_opt(options, 'python3', True)\n        Lexer.__init__(self, **options)\n\n    def get_tokens_unprocessed(self, text):\n        if self.python3:\n            pylexer = PythonLexer(**self.options)\n            tblexer = PythonTracebackLexer(**self.options)\n        else:\n            pylexer = Python2Lexer(**self.options)\n            tblexer = Python2TracebackLexer(**self.options)\n\n        curcode = ''\n        insertions = []\n        curtb = ''\n        tbindex = 0\n        tb = 0\n        for match in line_re.finditer(text):\n            line = match.group()\n            if line.startswith('>>> ') or line.startswith('... '):\n                tb = 0\n                insertions.append((len(curcode),\n                                   [(0, Generic.Prompt, line[:4])]))\n                curcode += line[4:]\n            elif line.rstrip() == '...' and not tb:\n                # only a new >>> prompt can end an exception block\n                # otherwise an ellipsis in place of the traceback frames\n                # will be mishandled\n                insertions.append((len(curcode),\n                                   [(0, Generic.Prompt, '...')]))\n                curcode += line[3:]\n            else:\n                if curcode:\n                    yield from do_insertions(\n                        insertions, pylexer.get_tokens_unprocessed(curcode))\n                    curcode = ''\n                    insertions = []\n                if (line.startswith('Traceback (most recent call last):') or\n                        re.match('  File \"[^\"]+\", line \\\\d+\\\\n$', line)):\n                    tb = 1\n                    curtb = line\n                    tbindex = match.start()\n                elif line == 'KeyboardInterrupt\\n':\n                    yield match.start(), Name.Class, line\n                elif tb:\n                    curtb += line\n                    if not (line.startswith(' ') or line.strip() == '...'):\n                        tb = 0\n                        for i, t, v in tblexer.get_tokens_unprocessed(curtb):\n                            yield tbindex+i, t, v\n                        curtb = ''\n                else:\n                    yield match.start(), Generic.Output, line\n        if curcode:\n            yield from do_insertions(insertions,\n                                     pylexer.get_tokens_unprocessed(curcode))\n        if curtb:\n            for i, t, v in tblexer.get_tokens_unprocessed(curtb):\n                yield tbindex+i, t, v\n\n\nclass PythonTracebackLexer(RegexLexer):\n    \"\"\"\n    For Python 3.x tracebacks, with support for chained exceptions.\n\n    .. versionadded:: 1.0\n\n    .. versionchanged:: 2.5\n       This is now the default ``PythonTracebackLexer``.  It is still available\n       as the alias ``Python3TracebackLexer``.\n    \"\"\"\n\n    name = 'Python Traceback'\n    aliases = ['pytb', 'py3tb']\n    filenames = ['*.pytb', '*.py3tb']\n    mimetypes = ['text/x-python-traceback', 'text/x-python3-traceback']\n\n    tokens = {\n        'root': [\n            (r'\\n', Text),\n            (r'^Traceback \\(most recent call last\\):\\n', Generic.Traceback, 'intb'),\n            (r'^During handling of the above exception, another '\n             r'exception occurred:\\n\\n', Generic.Traceback),\n            (r'^The above exception was the direct cause of the '\n             r'following exception:\\n\\n', Generic.Traceback),\n            (r'^(?=  File \"[^\"]+\", line \\d+)', Generic.Traceback, 'intb'),\n            (r'^.*\\n', Other),\n        ],\n        'intb': [\n            (r'^(  File )(\"[^\"]+\")(, line )(\\d+)(, in )(.+)(\\n)',\n             bygroups(Text, Name.Builtin, Text, Number, Text, Name, Text)),\n            (r'^(  File )(\"[^\"]+\")(, line )(\\d+)(\\n)',\n             bygroups(Text, Name.Builtin, Text, Number, Text)),\n            (r'^(    )(.+)(\\n)',\n             bygroups(Text, using(PythonLexer), Text), 'markers'),\n            (r'^([ \\t]*)(\\.\\.\\.)(\\n)',\n             bygroups(Text, Comment, Text)),  # for doctests...\n            (r'^([^:]+)(: )(.+)(\\n)',\n             bygroups(Generic.Error, Text, Name, Text), '#pop'),\n            (r'^([a-zA-Z_][\\w.]*)(:?\\n)',\n             bygroups(Generic.Error, Text), '#pop')\n        ],\n        'markers': [\n            # Either `PEP 657 <https://www.python.org/dev/peps/pep-0657/>`\n            # error locations in Python 3.11+, or single-caret markers\n            # for syntax errors before that.\n            (r'^( {4,})([~^]+)(\\n)',\n             bygroups(Text, Punctuation.Marker, Text),\n             '#pop'),\n            default('#pop'),\n        ],\n    }\n\n\nPython3TracebackLexer = PythonTracebackLexer\n\n\nclass Python2TracebackLexer(RegexLexer):\n    \"\"\"\n    For Python tracebacks.\n\n    .. versionadded:: 0.7\n\n    .. versionchanged:: 2.5\n       This class has been renamed from ``PythonTracebackLexer``.\n       ``PythonTracebackLexer`` now refers to the Python 3 variant.\n    \"\"\"\n\n    name = 'Python 2.x Traceback'\n    aliases = ['py2tb']\n    filenames = ['*.py2tb']\n    mimetypes = ['text/x-python2-traceback']\n\n    tokens = {\n        'root': [\n            # Cover both (most recent call last) and (innermost last)\n            # The optional ^C allows us to catch keyboard interrupt signals.\n            (r'^(\\^C)?(Traceback.*\\n)',\n             bygroups(Text, Generic.Traceback), 'intb'),\n            # SyntaxError starts with this.\n            (r'^(?=  File \"[^\"]+\", line \\d+)', Generic.Traceback, 'intb'),\n            (r'^.*\\n', Other),\n        ],\n        'intb': [\n            (r'^(  File )(\"[^\"]+\")(, line )(\\d+)(, in )(.+)(\\n)',\n             bygroups(Text, Name.Builtin, Text, Number, Text, Name, Text)),\n            (r'^(  File )(\"[^\"]+\")(, line )(\\d+)(\\n)',\n             bygroups(Text, Name.Builtin, Text, Number, Text)),\n            (r'^(    )(.+)(\\n)',\n             bygroups(Text, using(Python2Lexer), Text), 'marker'),\n            (r'^([ \\t]*)(\\.\\.\\.)(\\n)',\n             bygroups(Text, Comment, Text)),  # for doctests...\n            (r'^([^:]+)(: )(.+)(\\n)',\n             bygroups(Generic.Error, Text, Name, Text), '#pop'),\n            (r'^([a-zA-Z_]\\w*)(:?\\n)',\n             bygroups(Generic.Error, Text), '#pop')\n        ],\n        'marker': [\n            # For syntax errors.\n            (r'( {4,})(\\^)', bygroups(Text, Punctuation.Marker), '#pop'),\n            default('#pop'),\n        ],\n    }\n\n\nclass CythonLexer(RegexLexer):\n    \"\"\"\n    For Pyrex and Cython source code.\n\n    .. versionadded:: 1.1\n    \"\"\"\n\n    name = 'Cython'\n    url = 'http://cython.org'\n    aliases = ['cython', 'pyx', 'pyrex']\n    filenames = ['*.pyx', '*.pxd', '*.pxi']\n    mimetypes = ['text/x-cython', 'application/x-cython']\n\n    tokens = {\n        'root': [\n            (r'\\n', Text),\n            (r'^(\\s*)(\"\"\"(?:.|\\n)*?\"\"\")', bygroups(Text, String.Doc)),\n            (r\"^(\\s*)('''(?:.|\\n)*?''')\", bygroups(Text, String.Doc)),\n            (r'[^\\S\\n]+', Text),\n            (r'#.*$', Comment),\n            (r'[]{}:(),;[]', Punctuation),\n            (r'\\\\\\n', Text),\n            (r'\\\\', Text),\n            (r'(in|is|and|or|not)\\b', Operator.Word),\n            (r'(<)([a-zA-Z0-9.?]+)(>)',\n             bygroups(Punctuation, Keyword.Type, Punctuation)),\n            (r'!=|==|<<|>>|[-~+/*%=<>&^|.?]', Operator),\n            (r'(from)(\\d+)(<=)(\\s+)(<)(\\d+)(:)',\n             bygroups(Keyword, Number.Integer, Operator, Name, Operator,\n                      Name, Punctuation)),\n            include('keywords'),\n            (r'(def|property)(\\s+)', bygroups(Keyword, Text), 'funcname'),\n            (r'(cp?def)(\\s+)', bygroups(Keyword, Text), 'cdef'),\n            # (should actually start a block with only cdefs)\n            (r'(cdef)(:)', bygroups(Keyword, Punctuation)),\n            (r'(class|struct)(\\s+)', bygroups(Keyword, Text), 'classname'),\n            (r'(from)(\\s+)', bygroups(Keyword, Text), 'fromimport'),\n            (r'(c?import)(\\s+)', bygroups(Keyword, Text), 'import'),\n            include('builtins'),\n            include('backtick'),\n            ('(?:[rR]|[uU][rR]|[rR][uU])\"\"\"', String, 'tdqs'),\n            (\"(?:[rR]|[uU][rR]|[rR][uU])'''\", String, 'tsqs'),\n            ('(?:[rR]|[uU][rR]|[rR][uU])\"', String, 'dqs'),\n            (\"(?:[rR]|[uU][rR]|[rR][uU])'\", String, 'sqs'),\n            ('[uU]?\"\"\"', String, combined('stringescape', 'tdqs')),\n            (\"[uU]?'''\", String, combined('stringescape', 'tsqs')),\n            ('[uU]?\"', String, combined('stringescape', 'dqs')),\n            (\"[uU]?'\", String, combined('stringescape', 'sqs')),\n            include('name'),\n            include('numbers'),\n        ],\n        'keywords': [\n            (words((\n                'assert', 'async', 'await', 'break', 'by', 'continue', 'ctypedef', 'del', 'elif',\n                'else', 'except', 'except?', 'exec', 'finally', 'for', 'fused', 'gil',\n                'global', 'if', 'include', 'lambda', 'nogil', 'pass', 'print',\n                'raise', 'return', 'try', 'while', 'yield', 'as', 'with'), suffix=r'\\b'),\n             Keyword),\n            (r'(DEF|IF|ELIF|ELSE)\\b', Comment.Preproc),\n        ],\n        'builtins': [\n            (words((\n                '__import__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bint',\n                'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr',\n                'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'delattr',\n                'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit',\n                'file', 'filter', 'float', 'frozenset', 'getattr', 'globals',\n                'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'intern', 'isinstance',\n                'issubclass', 'iter', 'len', 'list', 'locals', 'long', 'map', 'max',\n                'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'Py_ssize_t',\n                'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed',\n                'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod',\n                'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'unsigned',\n                'vars', 'xrange', 'zip'), prefix=r'(?<!\\.)', suffix=r'\\b'),\n             Name.Builtin),\n            (r'(?<!\\.)(self|None|Ellipsis|NotImplemented|False|True|NULL'\n             r')\\b', Name.Builtin.Pseudo),\n            (words((\n                'ArithmeticError', 'AssertionError', 'AttributeError',\n                'BaseException', 'DeprecationWarning', 'EOFError', 'EnvironmentError',\n                'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit',\n                'IOError', 'ImportError', 'ImportWarning', 'IndentationError',\n                'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError',\n                'MemoryError', 'NameError', 'NotImplemented', 'NotImplementedError',\n                'OSError', 'OverflowError', 'OverflowWarning',\n                'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',\n                'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',\n                'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError',\n                'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',\n                'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',\n                'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning',\n                'ZeroDivisionError'), prefix=r'(?<!\\.)', suffix=r'\\b'),\n             Name.Exception),\n        ],\n        'numbers': [\n            (r'(\\d+\\.?\\d*|\\d*\\.\\d+)([eE][+-]?[0-9]+)?', Number.Float),\n            (r'0\\d+', Number.Oct),\n            (r'0[xX][a-fA-F0-9]+', Number.Hex),\n            (r'\\d+L', Number.Integer.Long),\n            (r'\\d+', Number.Integer)\n        ],\n        'backtick': [\n            ('`.*?`', String.Backtick),\n        ],\n        'name': [\n            (r'@\\w+', Name.Decorator),\n            (r'[a-zA-Z_]\\w*', Name),\n        ],\n        'funcname': [\n            (r'[a-zA-Z_]\\w*', Name.Function, '#pop')\n        ],\n        'cdef': [\n            (r'(public|readonly|extern|api|inline)\\b', Keyword.Reserved),\n            (r'(struct|enum|union|class)\\b', Keyword),\n            (r'([a-zA-Z_]\\w*)(\\s*)(?=[(:#=]|$)',\n             bygroups(Name.Function, Text), '#pop'),\n            (r'([a-zA-Z_]\\w*)(\\s*)(,)',\n             bygroups(Name.Function, Text, Punctuation)),\n            (r'from\\b', Keyword, '#pop'),\n            (r'as\\b', Keyword),\n            (r':', Punctuation, '#pop'),\n            (r'(?=[\"\\'])', Text, '#pop'),\n            (r'[a-zA-Z_]\\w*', Keyword.Type),\n            (r'.', Text),\n        ],\n        'classname': [\n            (r'[a-zA-Z_]\\w*', Name.Class, '#pop')\n        ],\n        'import': [\n            (r'(\\s+)(as)(\\s+)', bygroups(Text, Keyword, Text)),\n            (r'[a-zA-Z_][\\w.]*', Name.Namespace),\n            (r'(\\s*)(,)(\\s*)', bygroups(Text, Operator, Text)),\n            default('#pop')  # all else: go back\n        ],\n        'fromimport': [\n            (r'(\\s+)(c?import)\\b', bygroups(Text, Keyword), '#pop'),\n            (r'[a-zA-Z_.][\\w.]*', Name.Namespace),\n            # ``cdef foo from \"header\"``, or ``for foo from 0 < i < 10``\n            default('#pop'),\n        ],\n        'stringescape': [\n            (r'\\\\([\\\\abfnrtv\"\\']|\\n|N\\{.*?\\}|u[a-fA-F0-9]{4}|'\n             r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)\n        ],\n        'strings': [\n            (r'%(\\([a-zA-Z0-9]+\\))?[-#0 +]*([0-9]+|[*])?(\\.([0-9]+|[*]))?'\n             '[hlL]?[E-GXc-giorsux%]', String.Interpol),\n            (r'[^\\\\\\'\"%\\n]+', String),\n            # quotes, percents and backslashes must be parsed one at a time\n            (r'[\\'\"\\\\]', String),\n            # unhandled string formatting sign\n            (r'%', String)\n            # newlines are an error (use \"nl\" state)\n        ],\n        'nl': [\n            (r'\\n', String)\n        ],\n        'dqs': [\n            (r'\"', String, '#pop'),\n            (r'\\\\\\\\|\\\\\"|\\\\\\n', String.Escape),  # included here again for raw strings\n            include('strings')\n        ],\n        'sqs': [\n            (r\"'\", String, '#pop'),\n            (r\"\\\\\\\\|\\\\'|\\\\\\n\", String.Escape),  # included here again for raw strings\n            include('strings')\n        ],\n        'tdqs': [\n            (r'\"\"\"', String, '#pop'),\n            include('strings'),\n            include('nl')\n        ],\n        'tsqs': [\n            (r\"'''\", String, '#pop'),\n            include('strings'),\n            include('nl')\n        ],\n    }\n\n\nclass DgLexer(RegexLexer):\n    \"\"\"\n    Lexer for dg,\n    a functional and object-oriented programming language\n    running on the CPython 3 VM.\n\n    .. versionadded:: 1.6\n    \"\"\"\n    name = 'dg'\n    aliases = ['dg']\n    filenames = ['*.dg']\n    mimetypes = ['text/x-dg']\n\n    tokens = {\n        'root': [\n            (r'\\s+', Text),\n            (r'#.*?$', Comment.Single),\n\n            (r'(?i)0b[01]+', Number.Bin),\n            (r'(?i)0o[0-7]+', Number.Oct),\n            (r'(?i)0x[0-9a-f]+', Number.Hex),\n            (r'(?i)[+-]?[0-9]+\\.[0-9]+(e[+-]?[0-9]+)?j?', Number.Float),\n            (r'(?i)[+-]?[0-9]+e[+-]?\\d+j?', Number.Float),\n            (r'(?i)[+-]?[0-9]+j?', Number.Integer),\n\n            (r\"(?i)(br|r?b?)'''\", String, combined('stringescape', 'tsqs', 'string')),\n            (r'(?i)(br|r?b?)\"\"\"', String, combined('stringescape', 'tdqs', 'string')),\n            (r\"(?i)(br|r?b?)'\", String, combined('stringescape', 'sqs', 'string')),\n            (r'(?i)(br|r?b?)\"', String, combined('stringescape', 'dqs', 'string')),\n\n            (r\"`\\w+'*`\", Operator),\n            (r'\\b(and|in|is|or|where)\\b', Operator.Word),\n            (r'[!$%&*+\\-./:<-@\\\\^|~;,]+', Operator),\n\n            (words((\n                'bool', 'bytearray', 'bytes', 'classmethod', 'complex', 'dict', 'dict\\'',\n                'float', 'frozenset', 'int', 'list', 'list\\'', 'memoryview', 'object',\n                'property', 'range', 'set', 'set\\'', 'slice', 'staticmethod', 'str',\n                'super', 'tuple', 'tuple\\'', 'type'),\n                   prefix=r'(?<!\\.)', suffix=r'(?![\\'\\w])'),\n             Name.Builtin),\n            (words((\n                '__import__', 'abs', 'all', 'any', 'bin', 'bind', 'chr', 'cmp', 'compile',\n                'complex', 'delattr', 'dir', 'divmod', 'drop', 'dropwhile', 'enumerate',\n                'eval', 'exhaust', 'filter', 'flip', 'foldl1?', 'format', 'fst',\n                'getattr', 'globals', 'hasattr', 'hash', 'head', 'hex', 'id', 'init',\n                'input', 'isinstance', 'issubclass', 'iter', 'iterate', 'last', 'len',\n                'locals', 'map', 'max', 'min', 'next', 'oct', 'open', 'ord', 'pow',\n                'print', 'repr', 'reversed', 'round', 'setattr', 'scanl1?', 'snd',\n                'sorted', 'sum', 'tail', 'take', 'takewhile', 'vars', 'zip'),\n                   prefix=r'(?<!\\.)', suffix=r'(?![\\'\\w])'),\n             Name.Builtin),\n            (r\"(?<!\\.)(self|Ellipsis|NotImplemented|None|True|False)(?!['\\w])\",\n             Name.Builtin.Pseudo),\n\n            (r\"(?<!\\.)[A-Z]\\w*(Error|Exception|Warning)'*(?!['\\w])\",\n             Name.Exception),\n            (r\"(?<!\\.)(Exception|GeneratorExit|KeyboardInterrupt|StopIteration|\"\n             r\"SystemExit)(?!['\\w])\", Name.Exception),\n\n            (r\"(?<![\\w.])(except|finally|for|if|import|not|otherwise|raise|\"\n             r\"subclass|while|with|yield)(?!['\\w])\", Keyword.Reserved),\n\n            (r\"[A-Z_]+'*(?!['\\w])\", Name),\n            (r\"[A-Z]\\w+'*(?!['\\w])\", Keyword.Type),\n            (r\"\\w+'*\", Name),\n\n            (r'[()]', Punctuation),\n            (r'.', Error),\n        ],\n        'stringescape': [\n            (r'\\\\([\\\\abfnrtv\"\\']|\\n|N\\{.*?\\}|u[a-fA-F0-9]{4}|'\n             r'U[a-fA-F0-9]{8}|x[a-fA-F0-9]{2}|[0-7]{1,3})', String.Escape)\n        ],\n        'string': [\n            (r'%(\\(\\w+\\))?[-#0 +]*([0-9]+|[*])?(\\.([0-9]+|[*]))?'\n             '[hlL]?[E-GXc-giorsux%]', String.Interpol),\n            (r'[^\\\\\\'\"%\\n]+', String),\n            # quotes, percents and backslashes must be parsed one at a time\n            (r'[\\'\"\\\\]', String),\n            # unhandled string formatting sign\n            (r'%', String),\n            (r'\\n', String)\n        ],\n        'dqs': [\n            (r'\"', String, '#pop')\n        ],\n        'sqs': [\n            (r\"'\", String, '#pop')\n        ],\n        'tdqs': [\n            (r'\"\"\"', String, '#pop')\n        ],\n        'tsqs': [\n            (r\"'''\", String, '#pop')\n        ],\n    }\n\n\nclass NumPyLexer(PythonLexer):\n    \"\"\"\n    A Python lexer recognizing Numerical Python builtins.\n\n    .. versionadded:: 0.10\n    \"\"\"\n\n    name = 'NumPy'\n    url = 'https://numpy.org/'\n    aliases = ['numpy']\n\n    # override the mimetypes to not inherit them from python\n    mimetypes = []\n    filenames = []\n\n    EXTRA_KEYWORDS = {\n        'abs', 'absolute', 'accumulate', 'add', 'alen', 'all', 'allclose',\n        'alltrue', 'alterdot', 'amax', 'amin', 'angle', 'any', 'append',\n        'apply_along_axis', 'apply_over_axes', 'arange', 'arccos', 'arccosh',\n        'arcsin', 'arcsinh', 'arctan', 'arctan2', 'arctanh', 'argmax', 'argmin',\n        'argsort', 'argwhere', 'around', 'array', 'array2string', 'array_equal',\n        'array_equiv', 'array_repr', 'array_split', 'array_str', 'arrayrange',\n        'asanyarray', 'asarray', 'asarray_chkfinite', 'ascontiguousarray',\n        'asfarray', 'asfortranarray', 'asmatrix', 'asscalar', 'astype',\n        'atleast_1d', 'atleast_2d', 'atleast_3d', 'average', 'bartlett',\n        'base_repr', 'beta', 'binary_repr', 'bincount', 'binomial',\n        'bitwise_and', 'bitwise_not', 'bitwise_or', 'bitwise_xor', 'blackman',\n        'bmat', 'broadcast', 'byte_bounds', 'bytes', 'byteswap', 'c_',\n        'can_cast', 'ceil', 'choose', 'clip', 'column_stack', 'common_type',\n        'compare_chararrays', 'compress', 'concatenate', 'conj', 'conjugate',\n        'convolve', 'copy', 'corrcoef', 'correlate', 'cos', 'cosh', 'cov',\n        'cross', 'cumprod', 'cumproduct', 'cumsum', 'delete', 'deprecate',\n        'diag', 'diagflat', 'diagonal', 'diff', 'digitize', 'disp', 'divide',\n        'dot', 'dsplit', 'dstack', 'dtype', 'dump', 'dumps', 'ediff1d', 'empty',\n        'empty_like', 'equal', 'exp', 'expand_dims', 'expm1', 'extract', 'eye',\n        'fabs', 'fastCopyAndTranspose', 'fft', 'fftfreq', 'fftshift', 'fill',\n        'finfo', 'fix', 'flat', 'flatnonzero', 'flatten', 'fliplr', 'flipud',\n        'floor', 'floor_divide', 'fmod', 'frexp', 'fromarrays', 'frombuffer',\n        'fromfile', 'fromfunction', 'fromiter', 'frompyfunc', 'fromstring',\n        'generic', 'get_array_wrap', 'get_include', 'get_numarray_include',\n        'get_numpy_include', 'get_printoptions', 'getbuffer', 'getbufsize',\n        'geterr', 'geterrcall', 'geterrobj', 'getfield', 'gradient', 'greater',\n        'greater_equal', 'gumbel', 'hamming', 'hanning', 'histogram',\n        'histogram2d', 'histogramdd', 'hsplit', 'hstack', 'hypot', 'i0',\n        'identity', 'ifft', 'imag', 'index_exp', 'indices', 'inf', 'info',\n        'inner', 'insert', 'int_asbuffer', 'interp', 'intersect1d',\n        'intersect1d_nu', 'inv', 'invert', 'iscomplex', 'iscomplexobj',\n        'isfinite', 'isfortran', 'isinf', 'isnan', 'isneginf', 'isposinf',\n        'isreal', 'isrealobj', 'isscalar', 'issctype', 'issubclass_',\n        'issubdtype', 'issubsctype', 'item', 'itemset', 'iterable', 'ix_',\n        'kaiser', 'kron', 'ldexp', 'left_shift', 'less', 'less_equal', 'lexsort',\n        'linspace', 'load', 'loads', 'loadtxt', 'log', 'log10', 'log1p', 'log2',\n        'logical_and', 'logical_not', 'logical_or', 'logical_xor', 'logspace',\n        'lstsq', 'mat', 'matrix', 'max', 'maximum', 'maximum_sctype',\n        'may_share_memory', 'mean', 'median', 'meshgrid', 'mgrid', 'min',\n        'minimum', 'mintypecode', 'mod', 'modf', 'msort', 'multiply', 'nan',\n        'nan_to_num', 'nanargmax', 'nanargmin', 'nanmax', 'nanmin', 'nansum',\n        'ndenumerate', 'ndim', 'ndindex', 'negative', 'newaxis', 'newbuffer',\n        'newbyteorder', 'nonzero', 'not_equal', 'obj2sctype', 'ogrid', 'ones',\n        'ones_like', 'outer', 'permutation', 'piecewise', 'pinv', 'pkgload',\n        'place', 'poisson', 'poly', 'poly1d', 'polyadd', 'polyder', 'polydiv',\n        'polyfit', 'polyint', 'polymul', 'polysub', 'polyval', 'power', 'prod',\n        'product', 'ptp', 'put', 'putmask', 'r_', 'randint', 'random_integers',\n        'random_sample', 'ranf', 'rank', 'ravel', 'real', 'real_if_close',\n        'recarray', 'reciprocal', 'reduce', 'remainder', 'repeat', 'require',\n        'reshape', 'resize', 'restoredot', 'right_shift', 'rint', 'roll',\n        'rollaxis', 'roots', 'rot90', 'round', 'round_', 'row_stack', 's_',\n        'sample', 'savetxt', 'sctype2char', 'searchsorted', 'seed', 'select',\n        'set_numeric_ops', 'set_printoptions', 'set_string_function',\n        'setbufsize', 'setdiff1d', 'seterr', 'seterrcall', 'seterrobj',\n        'setfield', 'setflags', 'setmember1d', 'setxor1d', 'shape',\n        'show_config', 'shuffle', 'sign', 'signbit', 'sin', 'sinc', 'sinh',\n        'size', 'slice', 'solve', 'sometrue', 'sort', 'sort_complex', 'source',\n        'split', 'sqrt', 'square', 'squeeze', 'standard_normal', 'std',\n        'subtract', 'sum', 'svd', 'swapaxes', 'take', 'tan', 'tanh', 'tensordot',\n        'test', 'tile', 'tofile', 'tolist', 'tostring', 'trace', 'transpose',\n        'trapz', 'tri', 'tril', 'trim_zeros', 'triu', 'true_divide', 'typeDict',\n        'typename', 'uniform', 'union1d', 'unique', 'unique1d', 'unravel_index',\n        'unwrap', 'vander', 'var', 'vdot', 'vectorize', 'view', 'vonmises',\n        'vsplit', 'vstack', 'weibull', 'where', 'who', 'zeros', 'zeros_like'\n    }\n\n    def get_tokens_unprocessed(self, text):\n        for index, token, value in \\\n                PythonLexer.get_tokens_unprocessed(self, text):\n            if token is Name and value in self.EXTRA_KEYWORDS:\n                yield index, Keyword.Pseudo, value\n            else:\n                yield index, token, value\n\n    def analyse_text(text):\n        ltext = text[:1000]\n        return (shebang_matches(text, r'pythonw?(3(\\.\\d)?)?') or\n                'import ' in ltext) \\\n            and ('import numpy' in ltext or 'from numpy import' in ltext)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/modeline.py",
    "content": "\"\"\"\n    pygments.modeline\n    ~~~~~~~~~~~~~~~~~\n\n    A simple modeline parser (based on pymodeline).\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\n\n__all__ = ['get_filetype_from_buffer']\n\n\nmodeline_re = re.compile(r'''\n    (?: vi | vim | ex ) (?: [<=>]? \\d* )? :\n    .* (?: ft | filetype | syn | syntax ) = ( [^:\\s]+ )\n''', re.VERBOSE)\n\n\ndef get_filetype_from_line(l):\n    m = modeline_re.search(l)\n    if m:\n        return m.group(1)\n\n\ndef get_filetype_from_buffer(buf, max_lines=5):\n    \"\"\"\n    Scan the buffer for modelines and return filetype if one is found.\n    \"\"\"\n    lines = buf.splitlines()\n    for l in lines[-1:-max_lines-1:-1]:\n        ret = get_filetype_from_line(l)\n        if ret:\n            return ret\n    for i in range(max_lines, -1, -1):\n        if i < len(lines):\n            ret = get_filetype_from_line(lines[i])\n            if ret:\n                return ret\n\n    return None\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/plugin.py",
    "content": "\"\"\"\n    pygments.plugin\n    ~~~~~~~~~~~~~~~\n\n    Pygments plugin interface. By default, this tries to use\n    ``importlib.metadata``, which is in the Python standard\n    library since Python 3.8, or its ``importlib_metadata``\n    backport for earlier versions of Python. It falls back on\n    ``pkg_resources`` if not found. Finally, if ``pkg_resources``\n    is not found either, no plugins are loaded at all.\n\n    lexer plugins::\n\n        [pygments.lexers]\n        yourlexer = yourmodule:YourLexer\n\n    formatter plugins::\n\n        [pygments.formatters]\n        yourformatter = yourformatter:YourFormatter\n        /.ext = yourformatter:YourFormatter\n\n    As you can see, you can define extensions for the formatter\n    with a leading slash.\n\n    syntax plugins::\n\n        [pygments.styles]\n        yourstyle = yourstyle:YourStyle\n\n    filter plugin::\n\n        [pygments.filter]\n        yourfilter = yourfilter:YourFilter\n\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nLEXER_ENTRY_POINT = 'pygments.lexers'\nFORMATTER_ENTRY_POINT = 'pygments.formatters'\nSTYLE_ENTRY_POINT = 'pygments.styles'\nFILTER_ENTRY_POINT = 'pygments.filters'\n\n\ndef iter_entry_points(group_name):\n    try:\n        from importlib.metadata import entry_points\n    except ImportError:\n        try:\n            from importlib_metadata import entry_points\n        except ImportError:\n            try:\n                from pip._vendor.pkg_resources import iter_entry_points\n            except (ImportError, OSError):\n                return []\n            else:\n                return iter_entry_points(group_name)\n    groups = entry_points()\n    if hasattr(groups, 'select'):\n        # New interface in Python 3.10 and newer versions of the\n        # importlib_metadata backport.\n        return groups.select(group=group_name)\n    else:\n        # Older interface, deprecated in Python 3.10 and recent\n        # importlib_metadata, but we need it in Python 3.8 and 3.9.\n        return groups.get(group_name, [])\n\n\ndef find_plugin_lexers():\n    for entrypoint in iter_entry_points(LEXER_ENTRY_POINT):\n        yield entrypoint.load()\n\n\ndef find_plugin_formatters():\n    for entrypoint in iter_entry_points(FORMATTER_ENTRY_POINT):\n        yield entrypoint.name, entrypoint.load()\n\n\ndef find_plugin_styles():\n    for entrypoint in iter_entry_points(STYLE_ENTRY_POINT):\n        yield entrypoint.name, entrypoint.load()\n\n\ndef find_plugin_filters():\n    for entrypoint in iter_entry_points(FILTER_ENTRY_POINT):\n        yield entrypoint.name, entrypoint.load()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/regexopt.py",
    "content": "\"\"\"\n    pygments.regexopt\n    ~~~~~~~~~~~~~~~~~\n\n    An algorithm that generates optimized regexes for matching long lists of\n    literal strings.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\nfrom re import escape\nfrom os.path import commonprefix\nfrom itertools import groupby\nfrom operator import itemgetter\n\nCS_ESCAPE = re.compile(r'[\\[\\^\\\\\\-\\]]')\nFIRST_ELEMENT = itemgetter(0)\n\n\ndef make_charset(letters):\n    return '[' + CS_ESCAPE.sub(lambda m: '\\\\' + m.group(), ''.join(letters)) + ']'\n\n\ndef regex_opt_inner(strings, open_paren):\n    \"\"\"Return a regex that matches any string in the sorted list of strings.\"\"\"\n    close_paren = open_paren and ')' or ''\n    # print strings, repr(open_paren)\n    if not strings:\n        # print '-> nothing left'\n        return ''\n    first = strings[0]\n    if len(strings) == 1:\n        # print '-> only 1 string'\n        return open_paren + escape(first) + close_paren\n    if not first:\n        # print '-> first string empty'\n        return open_paren + regex_opt_inner(strings[1:], '(?:') \\\n            + '?' + close_paren\n    if len(first) == 1:\n        # multiple one-char strings? make a charset\n        oneletter = []\n        rest = []\n        for s in strings:\n            if len(s) == 1:\n                oneletter.append(s)\n            else:\n                rest.append(s)\n        if len(oneletter) > 1:  # do we have more than one oneletter string?\n            if rest:\n                # print '-> 1-character + rest'\n                return open_paren + regex_opt_inner(rest, '') + '|' \\\n                    + make_charset(oneletter) + close_paren\n            # print '-> only 1-character'\n            return open_paren + make_charset(oneletter) + close_paren\n    prefix = commonprefix(strings)\n    if prefix:\n        plen = len(prefix)\n        # we have a prefix for all strings\n        # print '-> prefix:', prefix\n        return open_paren + escape(prefix) \\\n            + regex_opt_inner([s[plen:] for s in strings], '(?:') \\\n            + close_paren\n    # is there a suffix?\n    strings_rev = [s[::-1] for s in strings]\n    suffix = commonprefix(strings_rev)\n    if suffix:\n        slen = len(suffix)\n        # print '-> suffix:', suffix[::-1]\n        return open_paren \\\n            + regex_opt_inner(sorted(s[:-slen] for s in strings), '(?:') \\\n            + escape(suffix[::-1]) + close_paren\n    # recurse on common 1-string prefixes\n    # print '-> last resort'\n    return open_paren + \\\n        '|'.join(regex_opt_inner(list(group[1]), '')\n                 for group in groupby(strings, lambda s: s[0] == first[0])) \\\n        + close_paren\n\n\ndef regex_opt(strings, prefix='', suffix=''):\n    \"\"\"Return a compiled regex that matches any string in the given list.\n\n    The strings to match must be literal strings, not regexes.  They will be\n    regex-escaped.\n\n    *prefix* and *suffix* are pre- and appended to the final regex.\n    \"\"\"\n    strings = sorted(strings)\n    return prefix + regex_opt_inner(strings, '(') + suffix\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/scanner.py",
    "content": "\"\"\"\n    pygments.scanner\n    ~~~~~~~~~~~~~~~~\n\n    This library implements a regex based scanner. Some languages\n    like Pascal are easy to parse but have some keywords that\n    depend on the context. Because of this it's impossible to lex\n    that just by using a regular expression lexer like the\n    `RegexLexer`.\n\n    Have a look at the `DelphiLexer` to get an idea of how to use\n    this scanner.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\nimport re\n\n\nclass EndOfText(RuntimeError):\n    \"\"\"\n    Raise if end of text is reached and the user\n    tried to call a match function.\n    \"\"\"\n\n\nclass Scanner:\n    \"\"\"\n    Simple scanner\n\n    All method patterns are regular expression strings (not\n    compiled expressions!)\n    \"\"\"\n\n    def __init__(self, text, flags=0):\n        \"\"\"\n        :param text:    The text which should be scanned\n        :param flags:   default regular expression flags\n        \"\"\"\n        self.data = text\n        self.data_length = len(text)\n        self.start_pos = 0\n        self.pos = 0\n        self.flags = flags\n        self.last = None\n        self.match = None\n        self._re_cache = {}\n\n    def eos(self):\n        \"\"\"`True` if the scanner reached the end of text.\"\"\"\n        return self.pos >= self.data_length\n    eos = property(eos, eos.__doc__)\n\n    def check(self, pattern):\n        \"\"\"\n        Apply `pattern` on the current position and return\n        the match object. (Doesn't touch pos). Use this for\n        lookahead.\n        \"\"\"\n        if self.eos:\n            raise EndOfText()\n        if pattern not in self._re_cache:\n            self._re_cache[pattern] = re.compile(pattern, self.flags)\n        return self._re_cache[pattern].match(self.data, self.pos)\n\n    def test(self, pattern):\n        \"\"\"Apply a pattern on the current position and check\n        if it patches. Doesn't touch pos.\n        \"\"\"\n        return self.check(pattern) is not None\n\n    def scan(self, pattern):\n        \"\"\"\n        Scan the text for the given pattern and update pos/match\n        and related fields. The return value is a boolean that\n        indicates if the pattern matched. The matched value is\n        stored on the instance as ``match``, the last value is\n        stored as ``last``. ``start_pos`` is the position of the\n        pointer before the pattern was matched, ``pos`` is the\n        end position.\n        \"\"\"\n        if self.eos:\n            raise EndOfText()\n        if pattern not in self._re_cache:\n            self._re_cache[pattern] = re.compile(pattern, self.flags)\n        self.last = self.match\n        m = self._re_cache[pattern].match(self.data, self.pos)\n        if m is None:\n            return False\n        self.start_pos = m.start()\n        self.pos = m.end()\n        self.match = m.group()\n        return True\n\n    def get_char(self):\n        \"\"\"Scan exactly one char.\"\"\"\n        self.scan('.')\n\n    def __repr__(self):\n        return '<%s %d/%d>' % (\n            self.__class__.__name__,\n            self.pos,\n            self.data_length\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/sphinxext.py",
    "content": "\"\"\"\n    pygments.sphinxext\n    ~~~~~~~~~~~~~~~~~~\n\n    Sphinx extension to generate automatic documentation of lexers,\n    formatters and filters.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport sys\n\nfrom docutils import nodes\nfrom docutils.statemachine import ViewList\nfrom docutils.parsers.rst import Directive\nfrom sphinx.util.nodes import nested_parse_with_titles\n\n\nMODULEDOC = '''\n.. module:: %s\n\n%s\n%s\n'''\n\nLEXERDOC = '''\n.. class:: %s\n\n    :Short names: %s\n    :Filenames:   %s\n    :MIME types:  %s\n\n    %s\n\n'''\n\nFMTERDOC = '''\n.. class:: %s\n\n    :Short names: %s\n    :Filenames: %s\n\n    %s\n\n'''\n\nFILTERDOC = '''\n.. class:: %s\n\n    :Name: %s\n\n    %s\n\n'''\n\n\nclass PygmentsDoc(Directive):\n    \"\"\"\n    A directive to collect all lexers/formatters/filters and generate\n    autoclass directives for them.\n    \"\"\"\n    has_content = False\n    required_arguments = 1\n    optional_arguments = 0\n    final_argument_whitespace = False\n    option_spec = {}\n\n    def run(self):\n        self.filenames = set()\n        if self.arguments[0] == 'lexers':\n            out = self.document_lexers()\n        elif self.arguments[0] == 'formatters':\n            out = self.document_formatters()\n        elif self.arguments[0] == 'filters':\n            out = self.document_filters()\n        else:\n            raise Exception('invalid argument for \"pygmentsdoc\" directive')\n        node = nodes.compound()\n        vl = ViewList(out.split('\\n'), source='')\n        nested_parse_with_titles(self.state, vl, node)\n        for fn in self.filenames:\n            self.state.document.settings.record_dependencies.add(fn)\n        return node.children\n\n    def document_lexers(self):\n        from pip._vendor.pygments.lexers._mapping import LEXERS\n        out = []\n        modules = {}\n        moduledocstrings = {}\n        for classname, data in sorted(LEXERS.items(), key=lambda x: x[0]):\n            module = data[0]\n            mod = __import__(module, None, None, [classname])\n            self.filenames.add(mod.__file__)\n            cls = getattr(mod, classname)\n            if not cls.__doc__:\n                print(\"Warning: %s does not have a docstring.\" % classname)\n            docstring = cls.__doc__\n            if isinstance(docstring, bytes):\n                docstring = docstring.decode('utf8')\n            modules.setdefault(module, []).append((\n                classname,\n                ', '.join(data[2]) or 'None',\n                ', '.join(data[3]).replace('*', '\\\\*').replace('_', '\\\\') or 'None',\n                ', '.join(data[4]) or 'None',\n                docstring))\n            if module not in moduledocstrings:\n                moddoc = mod.__doc__\n                if isinstance(moddoc, bytes):\n                    moddoc = moddoc.decode('utf8')\n                moduledocstrings[module] = moddoc\n\n        for module, lexers in sorted(modules.items(), key=lambda x: x[0]):\n            if moduledocstrings[module] is None:\n                raise Exception(\"Missing docstring for %s\" % (module,))\n            heading = moduledocstrings[module].splitlines()[4].strip().rstrip('.')\n            out.append(MODULEDOC % (module, heading, '-'*len(heading)))\n            for data in lexers:\n                out.append(LEXERDOC % data)\n\n        return ''.join(out)\n\n    def document_formatters(self):\n        from pip._vendor.pygments.formatters import FORMATTERS\n\n        out = []\n        for classname, data in sorted(FORMATTERS.items(), key=lambda x: x[0]):\n            module = data[0]\n            mod = __import__(module, None, None, [classname])\n            self.filenames.add(mod.__file__)\n            cls = getattr(mod, classname)\n            docstring = cls.__doc__\n            if isinstance(docstring, bytes):\n                docstring = docstring.decode('utf8')\n            heading = cls.__name__\n            out.append(FMTERDOC % (heading, ', '.join(data[2]) or 'None',\n                                   ', '.join(data[3]).replace('*', '\\\\*') or 'None',\n                                   docstring))\n        return ''.join(out)\n\n    def document_filters(self):\n        from pip._vendor.pygments.filters import FILTERS\n\n        out = []\n        for name, cls in FILTERS.items():\n            self.filenames.add(sys.modules[cls.__module__].__file__)\n            docstring = cls.__doc__\n            if isinstance(docstring, bytes):\n                docstring = docstring.decode('utf8')\n            out.append(FILTERDOC % (cls.__name__, name, docstring))\n        return ''.join(out)\n\n\ndef setup(app):\n    app.add_directive('pygmentsdoc', PygmentsDoc)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/style.py",
    "content": "\"\"\"\n    pygments.style\n    ~~~~~~~~~~~~~~\n\n    Basic style object.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nfrom pip._vendor.pygments.token import Token, STANDARD_TYPES\n\n# Default mapping of ansixxx to RGB colors.\n_ansimap = {\n    # dark\n    'ansiblack': '000000',\n    'ansired': '7f0000',\n    'ansigreen': '007f00',\n    'ansiyellow': '7f7fe0',\n    'ansiblue': '00007f',\n    'ansimagenta': '7f007f',\n    'ansicyan': '007f7f',\n    'ansigray': 'e5e5e5',\n    # normal\n    'ansibrightblack': '555555',\n    'ansibrightred': 'ff0000',\n    'ansibrightgreen': '00ff00',\n    'ansibrightyellow': 'ffff00',\n    'ansibrightblue': '0000ff',\n    'ansibrightmagenta': 'ff00ff',\n    'ansibrightcyan': '00ffff',\n    'ansiwhite': 'ffffff',\n}\n# mapping of deprecated #ansixxx colors to new color names\n_deprecated_ansicolors = {\n    # dark\n    '#ansiblack': 'ansiblack',\n    '#ansidarkred': 'ansired',\n    '#ansidarkgreen': 'ansigreen',\n    '#ansibrown': 'ansiyellow',\n    '#ansidarkblue': 'ansiblue',\n    '#ansipurple': 'ansimagenta',\n    '#ansiteal': 'ansicyan',\n    '#ansilightgray': 'ansigray',\n    # normal\n    '#ansidarkgray': 'ansibrightblack',\n    '#ansired': 'ansibrightred',\n    '#ansigreen': 'ansibrightgreen',\n    '#ansiyellow': 'ansibrightyellow',\n    '#ansiblue': 'ansibrightblue',\n    '#ansifuchsia': 'ansibrightmagenta',\n    '#ansiturquoise': 'ansibrightcyan',\n    '#ansiwhite': 'ansiwhite',\n}\nansicolors = set(_ansimap)\n\n\nclass StyleMeta(type):\n\n    def __new__(mcs, name, bases, dct):\n        obj = type.__new__(mcs, name, bases, dct)\n        for token in STANDARD_TYPES:\n            if token not in obj.styles:\n                obj.styles[token] = ''\n\n        def colorformat(text):\n            if text in ansicolors:\n                return text\n            if text[0:1] == '#':\n                col = text[1:]\n                if len(col) == 6:\n                    return col\n                elif len(col) == 3:\n                    return col[0] * 2 + col[1] * 2 + col[2] * 2\n            elif text == '':\n                return ''\n            elif text.startswith('var') or text.startswith('calc'):\n                return text\n            assert False, \"wrong color format %r\" % text\n\n        _styles = obj._styles = {}\n\n        for ttype in obj.styles:\n            for token in ttype.split():\n                if token in _styles:\n                    continue\n                ndef = _styles.get(token.parent, None)\n                styledefs = obj.styles.get(token, '').split()\n                if not ndef or token is None:\n                    ndef = ['', 0, 0, 0, '', '', 0, 0, 0]\n                elif 'noinherit' in styledefs and token is not Token:\n                    ndef = _styles[Token][:]\n                else:\n                    ndef = ndef[:]\n                _styles[token] = ndef\n                for styledef in obj.styles.get(token, '').split():\n                    if styledef == 'noinherit':\n                        pass\n                    elif styledef == 'bold':\n                        ndef[1] = 1\n                    elif styledef == 'nobold':\n                        ndef[1] = 0\n                    elif styledef == 'italic':\n                        ndef[2] = 1\n                    elif styledef == 'noitalic':\n                        ndef[2] = 0\n                    elif styledef == 'underline':\n                        ndef[3] = 1\n                    elif styledef == 'nounderline':\n                        ndef[3] = 0\n                    elif styledef[:3] == 'bg:':\n                        ndef[4] = colorformat(styledef[3:])\n                    elif styledef[:7] == 'border:':\n                        ndef[5] = colorformat(styledef[7:])\n                    elif styledef == 'roman':\n                        ndef[6] = 1\n                    elif styledef == 'sans':\n                        ndef[7] = 1\n                    elif styledef == 'mono':\n                        ndef[8] = 1\n                    else:\n                        ndef[0] = colorformat(styledef)\n\n        return obj\n\n    def style_for_token(cls, token):\n        t = cls._styles[token]\n        ansicolor = bgansicolor = None\n        color = t[0]\n        if color in _deprecated_ansicolors:\n            color = _deprecated_ansicolors[color]\n        if color in ansicolors:\n            ansicolor = color\n            color = _ansimap[color]\n        bgcolor = t[4]\n        if bgcolor in _deprecated_ansicolors:\n            bgcolor = _deprecated_ansicolors[bgcolor]\n        if bgcolor in ansicolors:\n            bgansicolor = bgcolor\n            bgcolor = _ansimap[bgcolor]\n\n        return {\n            'color':        color or None,\n            'bold':         bool(t[1]),\n            'italic':       bool(t[2]),\n            'underline':    bool(t[3]),\n            'bgcolor':      bgcolor or None,\n            'border':       t[5] or None,\n            'roman':        bool(t[6]) or None,\n            'sans':         bool(t[7]) or None,\n            'mono':         bool(t[8]) or None,\n            'ansicolor':    ansicolor,\n            'bgansicolor':  bgansicolor,\n        }\n\n    def list_styles(cls):\n        return list(cls)\n\n    def styles_token(cls, ttype):\n        return ttype in cls._styles\n\n    def __iter__(cls):\n        for token in cls._styles:\n            yield token, cls.style_for_token(token)\n\n    def __len__(cls):\n        return len(cls._styles)\n\n\nclass Style(metaclass=StyleMeta):\n\n    #: overall background color (``None`` means transparent)\n    background_color = '#ffffff'\n\n    #: highlight background color\n    highlight_color = '#ffffcc'\n\n    #: line number font color\n    line_number_color = 'inherit'\n\n    #: line number background color\n    line_number_background_color = 'transparent'\n\n    #: special line number font color\n    line_number_special_color = '#000000'\n\n    #: special line number background color\n    line_number_special_background_color = '#ffffc0'\n\n    #: Style definitions for individual token types.\n    styles = {}\n\n    # Attribute for lexers defined within Pygments. If set\n    # to True, the style is not shown in the style gallery\n    # on the website. This is intended for language-specific\n    # styles.\n    web_style_gallery_exclude = False\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/styles/__init__.py",
    "content": "\"\"\"\n    pygments.styles\n    ~~~~~~~~~~~~~~~\n\n    Contains built-in styles.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nfrom pip._vendor.pygments.plugin import find_plugin_styles\nfrom pip._vendor.pygments.util import ClassNotFound\n\n\n#: Maps style names to 'submodule::classname'.\nSTYLE_MAP = {\n    'default':  'default::DefaultStyle',\n    'emacs':    'emacs::EmacsStyle',\n    'friendly': 'friendly::FriendlyStyle',\n    'friendly_grayscale': 'friendly_grayscale::FriendlyGrayscaleStyle',\n    'colorful': 'colorful::ColorfulStyle',\n    'autumn':   'autumn::AutumnStyle',\n    'murphy':   'murphy::MurphyStyle',\n    'manni':    'manni::ManniStyle',\n    'material': 'material::MaterialStyle',\n    'monokai':  'monokai::MonokaiStyle',\n    'perldoc':  'perldoc::PerldocStyle',\n    'pastie':   'pastie::PastieStyle',\n    'borland':  'borland::BorlandStyle',\n    'trac':     'trac::TracStyle',\n    'native':   'native::NativeStyle',\n    'fruity':   'fruity::FruityStyle',\n    'bw':       'bw::BlackWhiteStyle',\n    'vim':      'vim::VimStyle',\n    'vs':       'vs::VisualStudioStyle',\n    'tango':    'tango::TangoStyle',\n    'rrt':      'rrt::RrtStyle',\n    'xcode':    'xcode::XcodeStyle',\n    'igor':     'igor::IgorStyle',\n    'paraiso-light': 'paraiso_light::ParaisoLightStyle',\n    'paraiso-dark': 'paraiso_dark::ParaisoDarkStyle',\n    'lovelace': 'lovelace::LovelaceStyle',\n    'algol':    'algol::AlgolStyle',\n    'algol_nu': 'algol_nu::Algol_NuStyle',\n    'arduino':  'arduino::ArduinoStyle',\n    'rainbow_dash': 'rainbow_dash::RainbowDashStyle',\n    'abap':     'abap::AbapStyle',\n    'solarized-dark': 'solarized::SolarizedDarkStyle',\n    'solarized-light': 'solarized::SolarizedLightStyle',\n    'sas':         'sas::SasStyle',\n    'staroffice' : 'staroffice::StarofficeStyle',\n    'stata':       'stata_light::StataLightStyle',\n    'stata-light': 'stata_light::StataLightStyle',\n    'stata-dark':  'stata_dark::StataDarkStyle',\n    'inkpot':      'inkpot::InkPotStyle',\n    'zenburn': 'zenburn::ZenburnStyle',\n    'gruvbox-dark': 'gruvbox::GruvboxDarkStyle',\n    'gruvbox-light': 'gruvbox::GruvboxLightStyle',\n    'dracula': 'dracula::DraculaStyle',\n    'one-dark': 'onedark::OneDarkStyle',\n    'lilypond' : 'lilypond::LilyPondStyle',\n    'nord': 'nord::NordStyle',\n    'nord-darker': 'nord::NordDarkerStyle',\n    'github-dark': 'gh_dark::GhDarkStyle'\n}\n\n\ndef get_style_by_name(name):\n    if name in STYLE_MAP:\n        mod, cls = STYLE_MAP[name].split('::')\n        builtin = \"yes\"\n    else:\n        for found_name, style in find_plugin_styles():\n            if name == found_name:\n                return style\n        # perhaps it got dropped into our styles package\n        builtin = \"\"\n        mod = name\n        cls = name.title() + \"Style\"\n\n    try:\n        mod = __import__('pygments.styles.' + mod, None, None, [cls])\n    except ImportError:\n        raise ClassNotFound(\"Could not find style module %r\" % mod +\n                         (builtin and \", though it should be builtin\") + \".\")\n    try:\n        return getattr(mod, cls)\n    except AttributeError:\n        raise ClassNotFound(\"Could not find style class %r in style module.\" % cls)\n\n\ndef get_all_styles():\n    \"\"\"Return a generator for all styles by name,\n    both builtin and plugin.\"\"\"\n    yield from STYLE_MAP\n    for name, _ in find_plugin_styles():\n        yield name\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/token.py",
    "content": "\"\"\"\n    pygments.token\n    ~~~~~~~~~~~~~~\n\n    Basic token types and the standard tokens.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\n\nclass _TokenType(tuple):\n    parent = None\n\n    def split(self):\n        buf = []\n        node = self\n        while node is not None:\n            buf.append(node)\n            node = node.parent\n        buf.reverse()\n        return buf\n\n    def __init__(self, *args):\n        # no need to call super.__init__\n        self.subtypes = set()\n\n    def __contains__(self, val):\n        return self is val or (\n            type(val) is self.__class__ and\n            val[:len(self)] == self\n        )\n\n    def __getattr__(self, val):\n        if not val or not val[0].isupper():\n            return tuple.__getattribute__(self, val)\n        new = _TokenType(self + (val,))\n        setattr(self, val, new)\n        self.subtypes.add(new)\n        new.parent = self\n        return new\n\n    def __repr__(self):\n        return 'Token' + (self and '.' or '') + '.'.join(self)\n\n    def __copy__(self):\n        # These instances are supposed to be singletons\n        return self\n\n    def __deepcopy__(self, memo):\n        # These instances are supposed to be singletons\n        return self\n\n\nToken = _TokenType()\n\n# Special token types\nText = Token.Text\nWhitespace = Text.Whitespace\nEscape = Token.Escape\nError = Token.Error\n# Text that doesn't belong to this lexer (e.g. HTML in PHP)\nOther = Token.Other\n\n# Common token types for source code\nKeyword = Token.Keyword\nName = Token.Name\nLiteral = Token.Literal\nString = Literal.String\nNumber = Literal.Number\nPunctuation = Token.Punctuation\nOperator = Token.Operator\nComment = Token.Comment\n\n# Generic types for non-source code\nGeneric = Token.Generic\n\n# String and some others are not direct children of Token.\n# alias them:\nToken.Token = Token\nToken.String = String\nToken.Number = Number\n\n\ndef is_token_subtype(ttype, other):\n    \"\"\"\n    Return True if ``ttype`` is a subtype of ``other``.\n\n    exists for backwards compatibility. use ``ttype in other`` now.\n    \"\"\"\n    return ttype in other\n\n\ndef string_to_tokentype(s):\n    \"\"\"\n    Convert a string into a token type::\n\n        >>> string_to_token('String.Double')\n        Token.Literal.String.Double\n        >>> string_to_token('Token.Literal.Number')\n        Token.Literal.Number\n        >>> string_to_token('')\n        Token\n\n    Tokens that are already tokens are returned unchanged:\n\n        >>> string_to_token(String)\n        Token.Literal.String\n    \"\"\"\n    if isinstance(s, _TokenType):\n        return s\n    if not s:\n        return Token\n    node = Token\n    for item in s.split('.'):\n        node = getattr(node, item)\n    return node\n\n\n# Map standard token types to short names, used in CSS class naming.\n# If you add a new item, please be sure to run this file to perform\n# a consistency check for duplicate values.\nSTANDARD_TYPES = {\n    Token:                         '',\n\n    Text:                          '',\n    Whitespace:                    'w',\n    Escape:                        'esc',\n    Error:                         'err',\n    Other:                         'x',\n\n    Keyword:                       'k',\n    Keyword.Constant:              'kc',\n    Keyword.Declaration:           'kd',\n    Keyword.Namespace:             'kn',\n    Keyword.Pseudo:                'kp',\n    Keyword.Reserved:              'kr',\n    Keyword.Type:                  'kt',\n\n    Name:                          'n',\n    Name.Attribute:                'na',\n    Name.Builtin:                  'nb',\n    Name.Builtin.Pseudo:           'bp',\n    Name.Class:                    'nc',\n    Name.Constant:                 'no',\n    Name.Decorator:                'nd',\n    Name.Entity:                   'ni',\n    Name.Exception:                'ne',\n    Name.Function:                 'nf',\n    Name.Function.Magic:           'fm',\n    Name.Property:                 'py',\n    Name.Label:                    'nl',\n    Name.Namespace:                'nn',\n    Name.Other:                    'nx',\n    Name.Tag:                      'nt',\n    Name.Variable:                 'nv',\n    Name.Variable.Class:           'vc',\n    Name.Variable.Global:          'vg',\n    Name.Variable.Instance:        'vi',\n    Name.Variable.Magic:           'vm',\n\n    Literal:                       'l',\n    Literal.Date:                  'ld',\n\n    String:                        's',\n    String.Affix:                  'sa',\n    String.Backtick:               'sb',\n    String.Char:                   'sc',\n    String.Delimiter:              'dl',\n    String.Doc:                    'sd',\n    String.Double:                 's2',\n    String.Escape:                 'se',\n    String.Heredoc:                'sh',\n    String.Interpol:               'si',\n    String.Other:                  'sx',\n    String.Regex:                  'sr',\n    String.Single:                 's1',\n    String.Symbol:                 'ss',\n\n    Number:                        'm',\n    Number.Bin:                    'mb',\n    Number.Float:                  'mf',\n    Number.Hex:                    'mh',\n    Number.Integer:                'mi',\n    Number.Integer.Long:           'il',\n    Number.Oct:                    'mo',\n\n    Operator:                      'o',\n    Operator.Word:                 'ow',\n\n    Punctuation:                   'p',\n    Punctuation.Marker:            'pm',\n\n    Comment:                       'c',\n    Comment.Hashbang:              'ch',\n    Comment.Multiline:             'cm',\n    Comment.Preproc:               'cp',\n    Comment.PreprocFile:           'cpf',\n    Comment.Single:                'c1',\n    Comment.Special:               'cs',\n\n    Generic:                       'g',\n    Generic.Deleted:               'gd',\n    Generic.Emph:                  'ge',\n    Generic.Error:                 'gr',\n    Generic.Heading:               'gh',\n    Generic.Inserted:              'gi',\n    Generic.Output:                'go',\n    Generic.Prompt:                'gp',\n    Generic.Strong:                'gs',\n    Generic.Subheading:            'gu',\n    Generic.Traceback:             'gt',\n}\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/unistring.py",
    "content": "\"\"\"\n    pygments.unistring\n    ~~~~~~~~~~~~~~~~~~\n\n    Strings of all Unicode characters of a certain category.\n    Used for matching in Unicode-aware languages. Run to regenerate.\n\n    Inspired by chartypes_create.py from the MoinMoin project.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nCc = '\\x00-\\x1f\\x7f-\\x9f'\n\nCf = '\\xad\\u0600-\\u0605\\u061c\\u06dd\\u070f\\u08e2\\u180e\\u200b-\\u200f\\u202a-\\u202e\\u2060-\\u2064\\u2066-\\u206f\\ufeff\\ufff9-\\ufffb\\U000110bd\\U000110cd\\U0001bca0-\\U0001bca3\\U0001d173-\\U0001d17a\\U000e0001\\U000e0020-\\U000e007f'\n\nCn = '\\u0378-\\u0379\\u0380-\\u0383\\u038b\\u038d\\u03a2\\u0530\\u0557-\\u0558\\u058b-\\u058c\\u0590\\u05c8-\\u05cf\\u05eb-\\u05ee\\u05f5-\\u05ff\\u061d\\u070e\\u074b-\\u074c\\u07b2-\\u07bf\\u07fb-\\u07fc\\u082e-\\u082f\\u083f\\u085c-\\u085d\\u085f\\u086b-\\u089f\\u08b5\\u08be-\\u08d2\\u0984\\u098d-\\u098e\\u0991-\\u0992\\u09a9\\u09b1\\u09b3-\\u09b5\\u09ba-\\u09bb\\u09c5-\\u09c6\\u09c9-\\u09ca\\u09cf-\\u09d6\\u09d8-\\u09db\\u09de\\u09e4-\\u09e5\\u09ff-\\u0a00\\u0a04\\u0a0b-\\u0a0e\\u0a11-\\u0a12\\u0a29\\u0a31\\u0a34\\u0a37\\u0a3a-\\u0a3b\\u0a3d\\u0a43-\\u0a46\\u0a49-\\u0a4a\\u0a4e-\\u0a50\\u0a52-\\u0a58\\u0a5d\\u0a5f-\\u0a65\\u0a77-\\u0a80\\u0a84\\u0a8e\\u0a92\\u0aa9\\u0ab1\\u0ab4\\u0aba-\\u0abb\\u0ac6\\u0aca\\u0ace-\\u0acf\\u0ad1-\\u0adf\\u0ae4-\\u0ae5\\u0af2-\\u0af8\\u0b00\\u0b04\\u0b0d-\\u0b0e\\u0b11-\\u0b12\\u0b29\\u0b31\\u0b34\\u0b3a-\\u0b3b\\u0b45-\\u0b46\\u0b49-\\u0b4a\\u0b4e-\\u0b55\\u0b58-\\u0b5b\\u0b5e\\u0b64-\\u0b65\\u0b78-\\u0b81\\u0b84\\u0b8b-\\u0b8d\\u0b91\\u0b96-\\u0b98\\u0b9b\\u0b9d\\u0ba0-\\u0ba2\\u0ba5-\\u0ba7\\u0bab-\\u0bad\\u0bba-\\u0bbd\\u0bc3-\\u0bc5\\u0bc9\\u0bce-\\u0bcf\\u0bd1-\\u0bd6\\u0bd8-\\u0be5\\u0bfb-\\u0bff\\u0c0d\\u0c11\\u0c29\\u0c3a-\\u0c3c\\u0c45\\u0c49\\u0c4e-\\u0c54\\u0c57\\u0c5b-\\u0c5f\\u0c64-\\u0c65\\u0c70-\\u0c77\\u0c8d\\u0c91\\u0ca9\\u0cb4\\u0cba-\\u0cbb\\u0cc5\\u0cc9\\u0cce-\\u0cd4\\u0cd7-\\u0cdd\\u0cdf\\u0ce4-\\u0ce5\\u0cf0\\u0cf3-\\u0cff\\u0d04\\u0d0d\\u0d11\\u0d45\\u0d49\\u0d50-\\u0d53\\u0d64-\\u0d65\\u0d80-\\u0d81\\u0d84\\u0d97-\\u0d99\\u0db2\\u0dbc\\u0dbe-\\u0dbf\\u0dc7-\\u0dc9\\u0dcb-\\u0dce\\u0dd5\\u0dd7\\u0de0-\\u0de5\\u0df0-\\u0df1\\u0df5-\\u0e00\\u0e3b-\\u0e3e\\u0e5c-\\u0e80\\u0e83\\u0e85-\\u0e86\\u0e89\\u0e8b-\\u0e8c\\u0e8e-\\u0e93\\u0e98\\u0ea0\\u0ea4\\u0ea6\\u0ea8-\\u0ea9\\u0eac\\u0eba\\u0ebe-\\u0ebf\\u0ec5\\u0ec7\\u0ece-\\u0ecf\\u0eda-\\u0edb\\u0ee0-\\u0eff\\u0f48\\u0f6d-\\u0f70\\u0f98\\u0fbd\\u0fcd\\u0fdb-\\u0fff\\u10c6\\u10c8-\\u10cc\\u10ce-\\u10cf\\u1249\\u124e-\\u124f\\u1257\\u1259\\u125e-\\u125f\\u1289\\u128e-\\u128f\\u12b1\\u12b6-\\u12b7\\u12bf\\u12c1\\u12c6-\\u12c7\\u12d7\\u1311\\u1316-\\u1317\\u135b-\\u135c\\u137d-\\u137f\\u139a-\\u139f\\u13f6-\\u13f7\\u13fe-\\u13ff\\u169d-\\u169f\\u16f9-\\u16ff\\u170d\\u1715-\\u171f\\u1737-\\u173f\\u1754-\\u175f\\u176d\\u1771\\u1774-\\u177f\\u17de-\\u17df\\u17ea-\\u17ef\\u17fa-\\u17ff\\u180f\\u181a-\\u181f\\u1879-\\u187f\\u18ab-\\u18af\\u18f6-\\u18ff\\u191f\\u192c-\\u192f\\u193c-\\u193f\\u1941-\\u1943\\u196e-\\u196f\\u1975-\\u197f\\u19ac-\\u19af\\u19ca-\\u19cf\\u19db-\\u19dd\\u1a1c-\\u1a1d\\u1a5f\\u1a7d-\\u1a7e\\u1a8a-\\u1a8f\\u1a9a-\\u1a9f\\u1aae-\\u1aaf\\u1abf-\\u1aff\\u1b4c-\\u1b4f\\u1b7d-\\u1b7f\\u1bf4-\\u1bfb\\u1c38-\\u1c3a\\u1c4a-\\u1c4c\\u1c89-\\u1c8f\\u1cbb-\\u1cbc\\u1cc8-\\u1ccf\\u1cfa-\\u1cff\\u1dfa\\u1f16-\\u1f17\\u1f1e-\\u1f1f\\u1f46-\\u1f47\\u1f4e-\\u1f4f\\u1f58\\u1f5a\\u1f5c\\u1f5e\\u1f7e-\\u1f7f\\u1fb5\\u1fc5\\u1fd4-\\u1fd5\\u1fdc\\u1ff0-\\u1ff1\\u1ff5\\u1fff\\u2065\\u2072-\\u2073\\u208f\\u209d-\\u209f\\u20c0-\\u20cf\\u20f1-\\u20ff\\u218c-\\u218f\\u2427-\\u243f\\u244b-\\u245f\\u2b74-\\u2b75\\u2b96-\\u2b97\\u2bc9\\u2bff\\u2c2f\\u2c5f\\u2cf4-\\u2cf8\\u2d26\\u2d28-\\u2d2c\\u2d2e-\\u2d2f\\u2d68-\\u2d6e\\u2d71-\\u2d7e\\u2d97-\\u2d9f\\u2da7\\u2daf\\u2db7\\u2dbf\\u2dc7\\u2dcf\\u2dd7\\u2ddf\\u2e4f-\\u2e7f\\u2e9a\\u2ef4-\\u2eff\\u2fd6-\\u2fef\\u2ffc-\\u2fff\\u3040\\u3097-\\u3098\\u3100-\\u3104\\u3130\\u318f\\u31bb-\\u31bf\\u31e4-\\u31ef\\u321f\\u32ff\\u4db6-\\u4dbf\\u9ff0-\\u9fff\\ua48d-\\ua48f\\ua4c7-\\ua4cf\\ua62c-\\ua63f\\ua6f8-\\ua6ff\\ua7ba-\\ua7f6\\ua82c-\\ua82f\\ua83a-\\ua83f\\ua878-\\ua87f\\ua8c6-\\ua8cd\\ua8da-\\ua8df\\ua954-\\ua95e\\ua97d-\\ua97f\\ua9ce\\ua9da-\\ua9dd\\ua9ff\\uaa37-\\uaa3f\\uaa4e-\\uaa4f\\uaa5a-\\uaa5b\\uaac3-\\uaada\\uaaf7-\\uab00\\uab07-\\uab08\\uab0f-\\uab10\\uab17-\\uab1f\\uab27\\uab2f\\uab66-\\uab6f\\uabee-\\uabef\\uabfa-\\uabff\\ud7a4-\\ud7af\\ud7c7-\\ud7ca\\ud7fc-\\ud7ff\\ufa6e-\\ufa6f\\ufada-\\ufaff\\ufb07-\\ufb12\\ufb18-\\ufb1c\\ufb37\\ufb3d\\ufb3f\\ufb42\\ufb45\\ufbc2-\\ufbd2\\ufd40-\\ufd4f\\ufd90-\\ufd91\\ufdc8-\\ufdef\\ufdfe-\\ufdff\\ufe1a-\\ufe1f\\ufe53\\ufe67\\ufe6c-\\ufe6f\\ufe75\\ufefd-\\ufefe\\uff00\\uffbf-\\uffc1\\uffc8-\\uffc9\\uffd0-\\uffd1\\uffd8-\\uffd9\\uffdd-\\uffdf\\uffe7\\uffef-\\ufff8\\ufffe-\\uffff\\U0001000c\\U00010027\\U0001003b\\U0001003e\\U0001004e-\\U0001004f\\U0001005e-\\U0001007f\\U000100fb-\\U000100ff\\U00010103-\\U00010106\\U00010134-\\U00010136\\U0001018f\\U0001019c-\\U0001019f\\U000101a1-\\U000101cf\\U000101fe-\\U0001027f\\U0001029d-\\U0001029f\\U000102d1-\\U000102df\\U000102fc-\\U000102ff\\U00010324-\\U0001032c\\U0001034b-\\U0001034f\\U0001037b-\\U0001037f\\U0001039e\\U000103c4-\\U000103c7\\U000103d6-\\U000103ff\\U0001049e-\\U0001049f\\U000104aa-\\U000104af\\U000104d4-\\U000104d7\\U000104fc-\\U000104ff\\U00010528-\\U0001052f\\U00010564-\\U0001056e\\U00010570-\\U000105ff\\U00010737-\\U0001073f\\U00010756-\\U0001075f\\U00010768-\\U000107ff\\U00010806-\\U00010807\\U00010809\\U00010836\\U00010839-\\U0001083b\\U0001083d-\\U0001083e\\U00010856\\U0001089f-\\U000108a6\\U000108b0-\\U000108df\\U000108f3\\U000108f6-\\U000108fa\\U0001091c-\\U0001091e\\U0001093a-\\U0001093e\\U00010940-\\U0001097f\\U000109b8-\\U000109bb\\U000109d0-\\U000109d1\\U00010a04\\U00010a07-\\U00010a0b\\U00010a14\\U00010a18\\U00010a36-\\U00010a37\\U00010a3b-\\U00010a3e\\U00010a49-\\U00010a4f\\U00010a59-\\U00010a5f\\U00010aa0-\\U00010abf\\U00010ae7-\\U00010aea\\U00010af7-\\U00010aff\\U00010b36-\\U00010b38\\U00010b56-\\U00010b57\\U00010b73-\\U00010b77\\U00010b92-\\U00010b98\\U00010b9d-\\U00010ba8\\U00010bb0-\\U00010bff\\U00010c49-\\U00010c7f\\U00010cb3-\\U00010cbf\\U00010cf3-\\U00010cf9\\U00010d28-\\U00010d2f\\U00010d3a-\\U00010e5f\\U00010e7f-\\U00010eff\\U00010f28-\\U00010f2f\\U00010f5a-\\U00010fff\\U0001104e-\\U00011051\\U00011070-\\U0001107e\\U000110c2-\\U000110cc\\U000110ce-\\U000110cf\\U000110e9-\\U000110ef\\U000110fa-\\U000110ff\\U00011135\\U00011147-\\U0001114f\\U00011177-\\U0001117f\\U000111ce-\\U000111cf\\U000111e0\\U000111f5-\\U000111ff\\U00011212\\U0001123f-\\U0001127f\\U00011287\\U00011289\\U0001128e\\U0001129e\\U000112aa-\\U000112af\\U000112eb-\\U000112ef\\U000112fa-\\U000112ff\\U00011304\\U0001130d-\\U0001130e\\U00011311-\\U00011312\\U00011329\\U00011331\\U00011334\\U0001133a\\U00011345-\\U00011346\\U00011349-\\U0001134a\\U0001134e-\\U0001134f\\U00011351-\\U00011356\\U00011358-\\U0001135c\\U00011364-\\U00011365\\U0001136d-\\U0001136f\\U00011375-\\U000113ff\\U0001145a\\U0001145c\\U0001145f-\\U0001147f\\U000114c8-\\U000114cf\\U000114da-\\U0001157f\\U000115b6-\\U000115b7\\U000115de-\\U000115ff\\U00011645-\\U0001164f\\U0001165a-\\U0001165f\\U0001166d-\\U0001167f\\U000116b8-\\U000116bf\\U000116ca-\\U000116ff\\U0001171b-\\U0001171c\\U0001172c-\\U0001172f\\U00011740-\\U000117ff\\U0001183c-\\U0001189f\\U000118f3-\\U000118fe\\U00011900-\\U000119ff\\U00011a48-\\U00011a4f\\U00011a84-\\U00011a85\\U00011aa3-\\U00011abf\\U00011af9-\\U00011bff\\U00011c09\\U00011c37\\U00011c46-\\U00011c4f\\U00011c6d-\\U00011c6f\\U00011c90-\\U00011c91\\U00011ca8\\U00011cb7-\\U00011cff\\U00011d07\\U00011d0a\\U00011d37-\\U00011d39\\U00011d3b\\U00011d3e\\U00011d48-\\U00011d4f\\U00011d5a-\\U00011d5f\\U00011d66\\U00011d69\\U00011d8f\\U00011d92\\U00011d99-\\U00011d9f\\U00011daa-\\U00011edf\\U00011ef9-\\U00011fff\\U0001239a-\\U000123ff\\U0001246f\\U00012475-\\U0001247f\\U00012544-\\U00012fff\\U0001342f-\\U000143ff\\U00014647-\\U000167ff\\U00016a39-\\U00016a3f\\U00016a5f\\U00016a6a-\\U00016a6d\\U00016a70-\\U00016acf\\U00016aee-\\U00016aef\\U00016af6-\\U00016aff\\U00016b46-\\U00016b4f\\U00016b5a\\U00016b62\\U00016b78-\\U00016b7c\\U00016b90-\\U00016e3f\\U00016e9b-\\U00016eff\\U00016f45-\\U00016f4f\\U00016f7f-\\U00016f8e\\U00016fa0-\\U00016fdf\\U00016fe2-\\U00016fff\\U000187f2-\\U000187ff\\U00018af3-\\U0001afff\\U0001b11f-\\U0001b16f\\U0001b2fc-\\U0001bbff\\U0001bc6b-\\U0001bc6f\\U0001bc7d-\\U0001bc7f\\U0001bc89-\\U0001bc8f\\U0001bc9a-\\U0001bc9b\\U0001bca4-\\U0001cfff\\U0001d0f6-\\U0001d0ff\\U0001d127-\\U0001d128\\U0001d1e9-\\U0001d1ff\\U0001d246-\\U0001d2df\\U0001d2f4-\\U0001d2ff\\U0001d357-\\U0001d35f\\U0001d379-\\U0001d3ff\\U0001d455\\U0001d49d\\U0001d4a0-\\U0001d4a1\\U0001d4a3-\\U0001d4a4\\U0001d4a7-\\U0001d4a8\\U0001d4ad\\U0001d4ba\\U0001d4bc\\U0001d4c4\\U0001d506\\U0001d50b-\\U0001d50c\\U0001d515\\U0001d51d\\U0001d53a\\U0001d53f\\U0001d545\\U0001d547-\\U0001d549\\U0001d551\\U0001d6a6-\\U0001d6a7\\U0001d7cc-\\U0001d7cd\\U0001da8c-\\U0001da9a\\U0001daa0\\U0001dab0-\\U0001dfff\\U0001e007\\U0001e019-\\U0001e01a\\U0001e022\\U0001e025\\U0001e02b-\\U0001e7ff\\U0001e8c5-\\U0001e8c6\\U0001e8d7-\\U0001e8ff\\U0001e94b-\\U0001e94f\\U0001e95a-\\U0001e95d\\U0001e960-\\U0001ec70\\U0001ecb5-\\U0001edff\\U0001ee04\\U0001ee20\\U0001ee23\\U0001ee25-\\U0001ee26\\U0001ee28\\U0001ee33\\U0001ee38\\U0001ee3a\\U0001ee3c-\\U0001ee41\\U0001ee43-\\U0001ee46\\U0001ee48\\U0001ee4a\\U0001ee4c\\U0001ee50\\U0001ee53\\U0001ee55-\\U0001ee56\\U0001ee58\\U0001ee5a\\U0001ee5c\\U0001ee5e\\U0001ee60\\U0001ee63\\U0001ee65-\\U0001ee66\\U0001ee6b\\U0001ee73\\U0001ee78\\U0001ee7d\\U0001ee7f\\U0001ee8a\\U0001ee9c-\\U0001eea0\\U0001eea4\\U0001eeaa\\U0001eebc-\\U0001eeef\\U0001eef2-\\U0001efff\\U0001f02c-\\U0001f02f\\U0001f094-\\U0001f09f\\U0001f0af-\\U0001f0b0\\U0001f0c0\\U0001f0d0\\U0001f0f6-\\U0001f0ff\\U0001f10d-\\U0001f10f\\U0001f16c-\\U0001f16f\\U0001f1ad-\\U0001f1e5\\U0001f203-\\U0001f20f\\U0001f23c-\\U0001f23f\\U0001f249-\\U0001f24f\\U0001f252-\\U0001f25f\\U0001f266-\\U0001f2ff\\U0001f6d5-\\U0001f6df\\U0001f6ed-\\U0001f6ef\\U0001f6fa-\\U0001f6ff\\U0001f774-\\U0001f77f\\U0001f7d9-\\U0001f7ff\\U0001f80c-\\U0001f80f\\U0001f848-\\U0001f84f\\U0001f85a-\\U0001f85f\\U0001f888-\\U0001f88f\\U0001f8ae-\\U0001f8ff\\U0001f90c-\\U0001f90f\\U0001f93f\\U0001f971-\\U0001f972\\U0001f977-\\U0001f979\\U0001f97b\\U0001f9a3-\\U0001f9af\\U0001f9ba-\\U0001f9bf\\U0001f9c3-\\U0001f9cf\\U0001fa00-\\U0001fa5f\\U0001fa6e-\\U0001ffff\\U0002a6d7-\\U0002a6ff\\U0002b735-\\U0002b73f\\U0002b81e-\\U0002b81f\\U0002cea2-\\U0002ceaf\\U0002ebe1-\\U0002f7ff\\U0002fa1e-\\U000e0000\\U000e0002-\\U000e001f\\U000e0080-\\U000e00ff\\U000e01f0-\\U000effff\\U000ffffe-\\U000fffff\\U0010fffe-\\U0010ffff'\n\nCo = '\\ue000-\\uf8ff\\U000f0000-\\U000ffffd\\U00100000-\\U0010fffd'\n\nCs = '\\ud800-\\udbff\\\\\\udc00\\udc01-\\udfff'\n\nLl = 'a-z\\xb5\\xdf-\\xf6\\xf8-\\xff\\u0101\\u0103\\u0105\\u0107\\u0109\\u010b\\u010d\\u010f\\u0111\\u0113\\u0115\\u0117\\u0119\\u011b\\u011d\\u011f\\u0121\\u0123\\u0125\\u0127\\u0129\\u012b\\u012d\\u012f\\u0131\\u0133\\u0135\\u0137-\\u0138\\u013a\\u013c\\u013e\\u0140\\u0142\\u0144\\u0146\\u0148-\\u0149\\u014b\\u014d\\u014f\\u0151\\u0153\\u0155\\u0157\\u0159\\u015b\\u015d\\u015f\\u0161\\u0163\\u0165\\u0167\\u0169\\u016b\\u016d\\u016f\\u0171\\u0173\\u0175\\u0177\\u017a\\u017c\\u017e-\\u0180\\u0183\\u0185\\u0188\\u018c-\\u018d\\u0192\\u0195\\u0199-\\u019b\\u019e\\u01a1\\u01a3\\u01a5\\u01a8\\u01aa-\\u01ab\\u01ad\\u01b0\\u01b4\\u01b6\\u01b9-\\u01ba\\u01bd-\\u01bf\\u01c6\\u01c9\\u01cc\\u01ce\\u01d0\\u01d2\\u01d4\\u01d6\\u01d8\\u01da\\u01dc-\\u01dd\\u01df\\u01e1\\u01e3\\u01e5\\u01e7\\u01e9\\u01eb\\u01ed\\u01ef-\\u01f0\\u01f3\\u01f5\\u01f9\\u01fb\\u01fd\\u01ff\\u0201\\u0203\\u0205\\u0207\\u0209\\u020b\\u020d\\u020f\\u0211\\u0213\\u0215\\u0217\\u0219\\u021b\\u021d\\u021f\\u0221\\u0223\\u0225\\u0227\\u0229\\u022b\\u022d\\u022f\\u0231\\u0233-\\u0239\\u023c\\u023f-\\u0240\\u0242\\u0247\\u0249\\u024b\\u024d\\u024f-\\u0293\\u0295-\\u02af\\u0371\\u0373\\u0377\\u037b-\\u037d\\u0390\\u03ac-\\u03ce\\u03d0-\\u03d1\\u03d5-\\u03d7\\u03d9\\u03db\\u03dd\\u03df\\u03e1\\u03e3\\u03e5\\u03e7\\u03e9\\u03eb\\u03ed\\u03ef-\\u03f3\\u03f5\\u03f8\\u03fb-\\u03fc\\u0430-\\u045f\\u0461\\u0463\\u0465\\u0467\\u0469\\u046b\\u046d\\u046f\\u0471\\u0473\\u0475\\u0477\\u0479\\u047b\\u047d\\u047f\\u0481\\u048b\\u048d\\u048f\\u0491\\u0493\\u0495\\u0497\\u0499\\u049b\\u049d\\u049f\\u04a1\\u04a3\\u04a5\\u04a7\\u04a9\\u04ab\\u04ad\\u04af\\u04b1\\u04b3\\u04b5\\u04b7\\u04b9\\u04bb\\u04bd\\u04bf\\u04c2\\u04c4\\u04c6\\u04c8\\u04ca\\u04cc\\u04ce-\\u04cf\\u04d1\\u04d3\\u04d5\\u04d7\\u04d9\\u04db\\u04dd\\u04df\\u04e1\\u04e3\\u04e5\\u04e7\\u04e9\\u04eb\\u04ed\\u04ef\\u04f1\\u04f3\\u04f5\\u04f7\\u04f9\\u04fb\\u04fd\\u04ff\\u0501\\u0503\\u0505\\u0507\\u0509\\u050b\\u050d\\u050f\\u0511\\u0513\\u0515\\u0517\\u0519\\u051b\\u051d\\u051f\\u0521\\u0523\\u0525\\u0527\\u0529\\u052b\\u052d\\u052f\\u0560-\\u0588\\u10d0-\\u10fa\\u10fd-\\u10ff\\u13f8-\\u13fd\\u1c80-\\u1c88\\u1d00-\\u1d2b\\u1d6b-\\u1d77\\u1d79-\\u1d9a\\u1e01\\u1e03\\u1e05\\u1e07\\u1e09\\u1e0b\\u1e0d\\u1e0f\\u1e11\\u1e13\\u1e15\\u1e17\\u1e19\\u1e1b\\u1e1d\\u1e1f\\u1e21\\u1e23\\u1e25\\u1e27\\u1e29\\u1e2b\\u1e2d\\u1e2f\\u1e31\\u1e33\\u1e35\\u1e37\\u1e39\\u1e3b\\u1e3d\\u1e3f\\u1e41\\u1e43\\u1e45\\u1e47\\u1e49\\u1e4b\\u1e4d\\u1e4f\\u1e51\\u1e53\\u1e55\\u1e57\\u1e59\\u1e5b\\u1e5d\\u1e5f\\u1e61\\u1e63\\u1e65\\u1e67\\u1e69\\u1e6b\\u1e6d\\u1e6f\\u1e71\\u1e73\\u1e75\\u1e77\\u1e79\\u1e7b\\u1e7d\\u1e7f\\u1e81\\u1e83\\u1e85\\u1e87\\u1e89\\u1e8b\\u1e8d\\u1e8f\\u1e91\\u1e93\\u1e95-\\u1e9d\\u1e9f\\u1ea1\\u1ea3\\u1ea5\\u1ea7\\u1ea9\\u1eab\\u1ead\\u1eaf\\u1eb1\\u1eb3\\u1eb5\\u1eb7\\u1eb9\\u1ebb\\u1ebd\\u1ebf\\u1ec1\\u1ec3\\u1ec5\\u1ec7\\u1ec9\\u1ecb\\u1ecd\\u1ecf\\u1ed1\\u1ed3\\u1ed5\\u1ed7\\u1ed9\\u1edb\\u1edd\\u1edf\\u1ee1\\u1ee3\\u1ee5\\u1ee7\\u1ee9\\u1eeb\\u1eed\\u1eef\\u1ef1\\u1ef3\\u1ef5\\u1ef7\\u1ef9\\u1efb\\u1efd\\u1eff-\\u1f07\\u1f10-\\u1f15\\u1f20-\\u1f27\\u1f30-\\u1f37\\u1f40-\\u1f45\\u1f50-\\u1f57\\u1f60-\\u1f67\\u1f70-\\u1f7d\\u1f80-\\u1f87\\u1f90-\\u1f97\\u1fa0-\\u1fa7\\u1fb0-\\u1fb4\\u1fb6-\\u1fb7\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fc7\\u1fd0-\\u1fd3\\u1fd6-\\u1fd7\\u1fe0-\\u1fe7\\u1ff2-\\u1ff4\\u1ff6-\\u1ff7\\u210a\\u210e-\\u210f\\u2113\\u212f\\u2134\\u2139\\u213c-\\u213d\\u2146-\\u2149\\u214e\\u2184\\u2c30-\\u2c5e\\u2c61\\u2c65-\\u2c66\\u2c68\\u2c6a\\u2c6c\\u2c71\\u2c73-\\u2c74\\u2c76-\\u2c7b\\u2c81\\u2c83\\u2c85\\u2c87\\u2c89\\u2c8b\\u2c8d\\u2c8f\\u2c91\\u2c93\\u2c95\\u2c97\\u2c99\\u2c9b\\u2c9d\\u2c9f\\u2ca1\\u2ca3\\u2ca5\\u2ca7\\u2ca9\\u2cab\\u2cad\\u2caf\\u2cb1\\u2cb3\\u2cb5\\u2cb7\\u2cb9\\u2cbb\\u2cbd\\u2cbf\\u2cc1\\u2cc3\\u2cc5\\u2cc7\\u2cc9\\u2ccb\\u2ccd\\u2ccf\\u2cd1\\u2cd3\\u2cd5\\u2cd7\\u2cd9\\u2cdb\\u2cdd\\u2cdf\\u2ce1\\u2ce3-\\u2ce4\\u2cec\\u2cee\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\ua641\\ua643\\ua645\\ua647\\ua649\\ua64b\\ua64d\\ua64f\\ua651\\ua653\\ua655\\ua657\\ua659\\ua65b\\ua65d\\ua65f\\ua661\\ua663\\ua665\\ua667\\ua669\\ua66b\\ua66d\\ua681\\ua683\\ua685\\ua687\\ua689\\ua68b\\ua68d\\ua68f\\ua691\\ua693\\ua695\\ua697\\ua699\\ua69b\\ua723\\ua725\\ua727\\ua729\\ua72b\\ua72d\\ua72f-\\ua731\\ua733\\ua735\\ua737\\ua739\\ua73b\\ua73d\\ua73f\\ua741\\ua743\\ua745\\ua747\\ua749\\ua74b\\ua74d\\ua74f\\ua751\\ua753\\ua755\\ua757\\ua759\\ua75b\\ua75d\\ua75f\\ua761\\ua763\\ua765\\ua767\\ua769\\ua76b\\ua76d\\ua76f\\ua771-\\ua778\\ua77a\\ua77c\\ua77f\\ua781\\ua783\\ua785\\ua787\\ua78c\\ua78e\\ua791\\ua793-\\ua795\\ua797\\ua799\\ua79b\\ua79d\\ua79f\\ua7a1\\ua7a3\\ua7a5\\ua7a7\\ua7a9\\ua7af\\ua7b5\\ua7b7\\ua7b9\\ua7fa\\uab30-\\uab5a\\uab60-\\uab65\\uab70-\\uabbf\\ufb00-\\ufb06\\ufb13-\\ufb17\\uff41-\\uff5a\\U00010428-\\U0001044f\\U000104d8-\\U000104fb\\U00010cc0-\\U00010cf2\\U000118c0-\\U000118df\\U00016e60-\\U00016e7f\\U0001d41a-\\U0001d433\\U0001d44e-\\U0001d454\\U0001d456-\\U0001d467\\U0001d482-\\U0001d49b\\U0001d4b6-\\U0001d4b9\\U0001d4bb\\U0001d4bd-\\U0001d4c3\\U0001d4c5-\\U0001d4cf\\U0001d4ea-\\U0001d503\\U0001d51e-\\U0001d537\\U0001d552-\\U0001d56b\\U0001d586-\\U0001d59f\\U0001d5ba-\\U0001d5d3\\U0001d5ee-\\U0001d607\\U0001d622-\\U0001d63b\\U0001d656-\\U0001d66f\\U0001d68a-\\U0001d6a5\\U0001d6c2-\\U0001d6da\\U0001d6dc-\\U0001d6e1\\U0001d6fc-\\U0001d714\\U0001d716-\\U0001d71b\\U0001d736-\\U0001d74e\\U0001d750-\\U0001d755\\U0001d770-\\U0001d788\\U0001d78a-\\U0001d78f\\U0001d7aa-\\U0001d7c2\\U0001d7c4-\\U0001d7c9\\U0001d7cb\\U0001e922-\\U0001e943'\n\nLm = '\\u02b0-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0374\\u037a\\u0559\\u0640\\u06e5-\\u06e6\\u07f4-\\u07f5\\u07fa\\u081a\\u0824\\u0828\\u0971\\u0e46\\u0ec6\\u10fc\\u17d7\\u1843\\u1aa7\\u1c78-\\u1c7d\\u1d2c-\\u1d6a\\u1d78\\u1d9b-\\u1dbf\\u2071\\u207f\\u2090-\\u209c\\u2c7c-\\u2c7d\\u2d6f\\u2e2f\\u3005\\u3031-\\u3035\\u303b\\u309d-\\u309e\\u30fc-\\u30fe\\ua015\\ua4f8-\\ua4fd\\ua60c\\ua67f\\ua69c-\\ua69d\\ua717-\\ua71f\\ua770\\ua788\\ua7f8-\\ua7f9\\ua9cf\\ua9e6\\uaa70\\uaadd\\uaaf3-\\uaaf4\\uab5c-\\uab5f\\uff70\\uff9e-\\uff9f\\U00016b40-\\U00016b43\\U00016f93-\\U00016f9f\\U00016fe0-\\U00016fe1'\n\nLo = '\\xaa\\xba\\u01bb\\u01c0-\\u01c3\\u0294\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0620-\\u063f\\u0641-\\u064a\\u066e-\\u066f\\u0671-\\u06d3\\u06d5\\u06ee-\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u0800-\\u0815\\u0840-\\u0858\\u0860-\\u086a\\u08a0-\\u08b4\\u08b6-\\u08bd\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0972-\\u0980\\u0985-\\u098c\\u098f-\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc-\\u09dd\\u09df-\\u09e1\\u09f0-\\u09f1\\u09fc\\u0a05-\\u0a0a\\u0a0f-\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32-\\u0a33\\u0a35-\\u0a36\\u0a38-\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2-\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0-\\u0ae1\\u0af9\\u0b05-\\u0b0c\\u0b0f-\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32-\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c-\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99-\\u0b9a\\u0b9c\\u0b9e-\\u0b9f\\u0ba3-\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d\\u0c58-\\u0c5a\\u0c60-\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cde\\u0ce0-\\u0ce1\\u0cf1-\\u0cf2\\u0d05-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d54-\\u0d56\\u0d5f-\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32-\\u0e33\\u0e40-\\u0e45\\u0e81-\\u0e82\\u0e84\\u0e87-\\u0e88\\u0e8a\\u0e8d\\u0e94-\\u0e97\\u0e99-\\u0e9f\\u0ea1-\\u0ea3\\u0ea5\\u0ea7\\u0eaa-\\u0eab\\u0ead-\\u0eb0\\u0eb2-\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065-\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u1100-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16f1-\\u16f8\\u1700-\\u170c\\u170e-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17dc\\u1820-\\u1842\\u1844-\\u1878\\u1880-\\u1884\\u1887-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1b05-\\u1b33\\u1b45-\\u1b4b\\u1b83-\\u1ba0\\u1bae-\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c77\\u1ce9-\\u1cec\\u1cee-\\u1cf1\\u1cf5-\\u1cf6\\u2135-\\u2138\\u2d30-\\u2d67\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3006\\u303c\\u3041-\\u3096\\u309f\\u30a1-\\u30fa\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31ba\\u31f0-\\u31ff\\u3400-\\u4db5\\u4e00-\\u9fef\\ua000-\\ua014\\ua016-\\ua48c\\ua4d0-\\ua4f7\\ua500-\\ua60b\\ua610-\\ua61f\\ua62a-\\ua62b\\ua66e\\ua6a0-\\ua6e5\\ua78f\\ua7f7\\ua7fb-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd-\\ua8fe\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9e0-\\ua9e4\\ua9e7-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa6f\\uaa71-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5-\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadc\\uaae0-\\uaaea\\uaaf2\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uabc0-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40-\\ufb41\\ufb43-\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff66-\\uff6f\\uff71-\\uff9d\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\\U00010000-\\U0001000b\\U0001000d-\\U00010026\\U00010028-\\U0001003a\\U0001003c-\\U0001003d\\U0001003f-\\U0001004d\\U00010050-\\U0001005d\\U00010080-\\U000100fa\\U00010280-\\U0001029c\\U000102a0-\\U000102d0\\U00010300-\\U0001031f\\U0001032d-\\U00010340\\U00010342-\\U00010349\\U00010350-\\U00010375\\U00010380-\\U0001039d\\U000103a0-\\U000103c3\\U000103c8-\\U000103cf\\U00010450-\\U0001049d\\U00010500-\\U00010527\\U00010530-\\U00010563\\U00010600-\\U00010736\\U00010740-\\U00010755\\U00010760-\\U00010767\\U00010800-\\U00010805\\U00010808\\U0001080a-\\U00010835\\U00010837-\\U00010838\\U0001083c\\U0001083f-\\U00010855\\U00010860-\\U00010876\\U00010880-\\U0001089e\\U000108e0-\\U000108f2\\U000108f4-\\U000108f5\\U00010900-\\U00010915\\U00010920-\\U00010939\\U00010980-\\U000109b7\\U000109be-\\U000109bf\\U00010a00\\U00010a10-\\U00010a13\\U00010a15-\\U00010a17\\U00010a19-\\U00010a35\\U00010a60-\\U00010a7c\\U00010a80-\\U00010a9c\\U00010ac0-\\U00010ac7\\U00010ac9-\\U00010ae4\\U00010b00-\\U00010b35\\U00010b40-\\U00010b55\\U00010b60-\\U00010b72\\U00010b80-\\U00010b91\\U00010c00-\\U00010c48\\U00010d00-\\U00010d23\\U00010f00-\\U00010f1c\\U00010f27\\U00010f30-\\U00010f45\\U00011003-\\U00011037\\U00011083-\\U000110af\\U000110d0-\\U000110e8\\U00011103-\\U00011126\\U00011144\\U00011150-\\U00011172\\U00011176\\U00011183-\\U000111b2\\U000111c1-\\U000111c4\\U000111da\\U000111dc\\U00011200-\\U00011211\\U00011213-\\U0001122b\\U00011280-\\U00011286\\U00011288\\U0001128a-\\U0001128d\\U0001128f-\\U0001129d\\U0001129f-\\U000112a8\\U000112b0-\\U000112de\\U00011305-\\U0001130c\\U0001130f-\\U00011310\\U00011313-\\U00011328\\U0001132a-\\U00011330\\U00011332-\\U00011333\\U00011335-\\U00011339\\U0001133d\\U00011350\\U0001135d-\\U00011361\\U00011400-\\U00011434\\U00011447-\\U0001144a\\U00011480-\\U000114af\\U000114c4-\\U000114c5\\U000114c7\\U00011580-\\U000115ae\\U000115d8-\\U000115db\\U00011600-\\U0001162f\\U00011644\\U00011680-\\U000116aa\\U00011700-\\U0001171a\\U00011800-\\U0001182b\\U000118ff\\U00011a00\\U00011a0b-\\U00011a32\\U00011a3a\\U00011a50\\U00011a5c-\\U00011a83\\U00011a86-\\U00011a89\\U00011a9d\\U00011ac0-\\U00011af8\\U00011c00-\\U00011c08\\U00011c0a-\\U00011c2e\\U00011c40\\U00011c72-\\U00011c8f\\U00011d00-\\U00011d06\\U00011d08-\\U00011d09\\U00011d0b-\\U00011d30\\U00011d46\\U00011d60-\\U00011d65\\U00011d67-\\U00011d68\\U00011d6a-\\U00011d89\\U00011d98\\U00011ee0-\\U00011ef2\\U00012000-\\U00012399\\U00012480-\\U00012543\\U00013000-\\U0001342e\\U00014400-\\U00014646\\U00016800-\\U00016a38\\U00016a40-\\U00016a5e\\U00016ad0-\\U00016aed\\U00016b00-\\U00016b2f\\U00016b63-\\U00016b77\\U00016b7d-\\U00016b8f\\U00016f00-\\U00016f44\\U00016f50\\U00017000-\\U000187f1\\U00018800-\\U00018af2\\U0001b000-\\U0001b11e\\U0001b170-\\U0001b2fb\\U0001bc00-\\U0001bc6a\\U0001bc70-\\U0001bc7c\\U0001bc80-\\U0001bc88\\U0001bc90-\\U0001bc99\\U0001e800-\\U0001e8c4\\U0001ee00-\\U0001ee03\\U0001ee05-\\U0001ee1f\\U0001ee21-\\U0001ee22\\U0001ee24\\U0001ee27\\U0001ee29-\\U0001ee32\\U0001ee34-\\U0001ee37\\U0001ee39\\U0001ee3b\\U0001ee42\\U0001ee47\\U0001ee49\\U0001ee4b\\U0001ee4d-\\U0001ee4f\\U0001ee51-\\U0001ee52\\U0001ee54\\U0001ee57\\U0001ee59\\U0001ee5b\\U0001ee5d\\U0001ee5f\\U0001ee61-\\U0001ee62\\U0001ee64\\U0001ee67-\\U0001ee6a\\U0001ee6c-\\U0001ee72\\U0001ee74-\\U0001ee77\\U0001ee79-\\U0001ee7c\\U0001ee7e\\U0001ee80-\\U0001ee89\\U0001ee8b-\\U0001ee9b\\U0001eea1-\\U0001eea3\\U0001eea5-\\U0001eea9\\U0001eeab-\\U0001eebb\\U00020000-\\U0002a6d6\\U0002a700-\\U0002b734\\U0002b740-\\U0002b81d\\U0002b820-\\U0002cea1\\U0002ceb0-\\U0002ebe0\\U0002f800-\\U0002fa1d'\n\nLt = '\\u01c5\\u01c8\\u01cb\\u01f2\\u1f88-\\u1f8f\\u1f98-\\u1f9f\\u1fa8-\\u1faf\\u1fbc\\u1fcc\\u1ffc'\n\nLu = 'A-Z\\xc0-\\xd6\\xd8-\\xde\\u0100\\u0102\\u0104\\u0106\\u0108\\u010a\\u010c\\u010e\\u0110\\u0112\\u0114\\u0116\\u0118\\u011a\\u011c\\u011e\\u0120\\u0122\\u0124\\u0126\\u0128\\u012a\\u012c\\u012e\\u0130\\u0132\\u0134\\u0136\\u0139\\u013b\\u013d\\u013f\\u0141\\u0143\\u0145\\u0147\\u014a\\u014c\\u014e\\u0150\\u0152\\u0154\\u0156\\u0158\\u015a\\u015c\\u015e\\u0160\\u0162\\u0164\\u0166\\u0168\\u016a\\u016c\\u016e\\u0170\\u0172\\u0174\\u0176\\u0178-\\u0179\\u017b\\u017d\\u0181-\\u0182\\u0184\\u0186-\\u0187\\u0189-\\u018b\\u018e-\\u0191\\u0193-\\u0194\\u0196-\\u0198\\u019c-\\u019d\\u019f-\\u01a0\\u01a2\\u01a4\\u01a6-\\u01a7\\u01a9\\u01ac\\u01ae-\\u01af\\u01b1-\\u01b3\\u01b5\\u01b7-\\u01b8\\u01bc\\u01c4\\u01c7\\u01ca\\u01cd\\u01cf\\u01d1\\u01d3\\u01d5\\u01d7\\u01d9\\u01db\\u01de\\u01e0\\u01e2\\u01e4\\u01e6\\u01e8\\u01ea\\u01ec\\u01ee\\u01f1\\u01f4\\u01f6-\\u01f8\\u01fa\\u01fc\\u01fe\\u0200\\u0202\\u0204\\u0206\\u0208\\u020a\\u020c\\u020e\\u0210\\u0212\\u0214\\u0216\\u0218\\u021a\\u021c\\u021e\\u0220\\u0222\\u0224\\u0226\\u0228\\u022a\\u022c\\u022e\\u0230\\u0232\\u023a-\\u023b\\u023d-\\u023e\\u0241\\u0243-\\u0246\\u0248\\u024a\\u024c\\u024e\\u0370\\u0372\\u0376\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u038f\\u0391-\\u03a1\\u03a3-\\u03ab\\u03cf\\u03d2-\\u03d4\\u03d8\\u03da\\u03dc\\u03de\\u03e0\\u03e2\\u03e4\\u03e6\\u03e8\\u03ea\\u03ec\\u03ee\\u03f4\\u03f7\\u03f9-\\u03fa\\u03fd-\\u042f\\u0460\\u0462\\u0464\\u0466\\u0468\\u046a\\u046c\\u046e\\u0470\\u0472\\u0474\\u0476\\u0478\\u047a\\u047c\\u047e\\u0480\\u048a\\u048c\\u048e\\u0490\\u0492\\u0494\\u0496\\u0498\\u049a\\u049c\\u049e\\u04a0\\u04a2\\u04a4\\u04a6\\u04a8\\u04aa\\u04ac\\u04ae\\u04b0\\u04b2\\u04b4\\u04b6\\u04b8\\u04ba\\u04bc\\u04be\\u04c0-\\u04c1\\u04c3\\u04c5\\u04c7\\u04c9\\u04cb\\u04cd\\u04d0\\u04d2\\u04d4\\u04d6\\u04d8\\u04da\\u04dc\\u04de\\u04e0\\u04e2\\u04e4\\u04e6\\u04e8\\u04ea\\u04ec\\u04ee\\u04f0\\u04f2\\u04f4\\u04f6\\u04f8\\u04fa\\u04fc\\u04fe\\u0500\\u0502\\u0504\\u0506\\u0508\\u050a\\u050c\\u050e\\u0510\\u0512\\u0514\\u0516\\u0518\\u051a\\u051c\\u051e\\u0520\\u0522\\u0524\\u0526\\u0528\\u052a\\u052c\\u052e\\u0531-\\u0556\\u10a0-\\u10c5\\u10c7\\u10cd\\u13a0-\\u13f5\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1e00\\u1e02\\u1e04\\u1e06\\u1e08\\u1e0a\\u1e0c\\u1e0e\\u1e10\\u1e12\\u1e14\\u1e16\\u1e18\\u1e1a\\u1e1c\\u1e1e\\u1e20\\u1e22\\u1e24\\u1e26\\u1e28\\u1e2a\\u1e2c\\u1e2e\\u1e30\\u1e32\\u1e34\\u1e36\\u1e38\\u1e3a\\u1e3c\\u1e3e\\u1e40\\u1e42\\u1e44\\u1e46\\u1e48\\u1e4a\\u1e4c\\u1e4e\\u1e50\\u1e52\\u1e54\\u1e56\\u1e58\\u1e5a\\u1e5c\\u1e5e\\u1e60\\u1e62\\u1e64\\u1e66\\u1e68\\u1e6a\\u1e6c\\u1e6e\\u1e70\\u1e72\\u1e74\\u1e76\\u1e78\\u1e7a\\u1e7c\\u1e7e\\u1e80\\u1e82\\u1e84\\u1e86\\u1e88\\u1e8a\\u1e8c\\u1e8e\\u1e90\\u1e92\\u1e94\\u1e9e\\u1ea0\\u1ea2\\u1ea4\\u1ea6\\u1ea8\\u1eaa\\u1eac\\u1eae\\u1eb0\\u1eb2\\u1eb4\\u1eb6\\u1eb8\\u1eba\\u1ebc\\u1ebe\\u1ec0\\u1ec2\\u1ec4\\u1ec6\\u1ec8\\u1eca\\u1ecc\\u1ece\\u1ed0\\u1ed2\\u1ed4\\u1ed6\\u1ed8\\u1eda\\u1edc\\u1ede\\u1ee0\\u1ee2\\u1ee4\\u1ee6\\u1ee8\\u1eea\\u1eec\\u1eee\\u1ef0\\u1ef2\\u1ef4\\u1ef6\\u1ef8\\u1efa\\u1efc\\u1efe\\u1f08-\\u1f0f\\u1f18-\\u1f1d\\u1f28-\\u1f2f\\u1f38-\\u1f3f\\u1f48-\\u1f4d\\u1f59\\u1f5b\\u1f5d\\u1f5f\\u1f68-\\u1f6f\\u1fb8-\\u1fbb\\u1fc8-\\u1fcb\\u1fd8-\\u1fdb\\u1fe8-\\u1fec\\u1ff8-\\u1ffb\\u2102\\u2107\\u210b-\\u210d\\u2110-\\u2112\\u2115\\u2119-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u212d\\u2130-\\u2133\\u213e-\\u213f\\u2145\\u2183\\u2c00-\\u2c2e\\u2c60\\u2c62-\\u2c64\\u2c67\\u2c69\\u2c6b\\u2c6d-\\u2c70\\u2c72\\u2c75\\u2c7e-\\u2c80\\u2c82\\u2c84\\u2c86\\u2c88\\u2c8a\\u2c8c\\u2c8e\\u2c90\\u2c92\\u2c94\\u2c96\\u2c98\\u2c9a\\u2c9c\\u2c9e\\u2ca0\\u2ca2\\u2ca4\\u2ca6\\u2ca8\\u2caa\\u2cac\\u2cae\\u2cb0\\u2cb2\\u2cb4\\u2cb6\\u2cb8\\u2cba\\u2cbc\\u2cbe\\u2cc0\\u2cc2\\u2cc4\\u2cc6\\u2cc8\\u2cca\\u2ccc\\u2cce\\u2cd0\\u2cd2\\u2cd4\\u2cd6\\u2cd8\\u2cda\\u2cdc\\u2cde\\u2ce0\\u2ce2\\u2ceb\\u2ced\\u2cf2\\ua640\\ua642\\ua644\\ua646\\ua648\\ua64a\\ua64c\\ua64e\\ua650\\ua652\\ua654\\ua656\\ua658\\ua65a\\ua65c\\ua65e\\ua660\\ua662\\ua664\\ua666\\ua668\\ua66a\\ua66c\\ua680\\ua682\\ua684\\ua686\\ua688\\ua68a\\ua68c\\ua68e\\ua690\\ua692\\ua694\\ua696\\ua698\\ua69a\\ua722\\ua724\\ua726\\ua728\\ua72a\\ua72c\\ua72e\\ua732\\ua734\\ua736\\ua738\\ua73a\\ua73c\\ua73e\\ua740\\ua742\\ua744\\ua746\\ua748\\ua74a\\ua74c\\ua74e\\ua750\\ua752\\ua754\\ua756\\ua758\\ua75a\\ua75c\\ua75e\\ua760\\ua762\\ua764\\ua766\\ua768\\ua76a\\ua76c\\ua76e\\ua779\\ua77b\\ua77d-\\ua77e\\ua780\\ua782\\ua784\\ua786\\ua78b\\ua78d\\ua790\\ua792\\ua796\\ua798\\ua79a\\ua79c\\ua79e\\ua7a0\\ua7a2\\ua7a4\\ua7a6\\ua7a8\\ua7aa-\\ua7ae\\ua7b0-\\ua7b4\\ua7b6\\ua7b8\\uff21-\\uff3a\\U00010400-\\U00010427\\U000104b0-\\U000104d3\\U00010c80-\\U00010cb2\\U000118a0-\\U000118bf\\U00016e40-\\U00016e5f\\U0001d400-\\U0001d419\\U0001d434-\\U0001d44d\\U0001d468-\\U0001d481\\U0001d49c\\U0001d49e-\\U0001d49f\\U0001d4a2\\U0001d4a5-\\U0001d4a6\\U0001d4a9-\\U0001d4ac\\U0001d4ae-\\U0001d4b5\\U0001d4d0-\\U0001d4e9\\U0001d504-\\U0001d505\\U0001d507-\\U0001d50a\\U0001d50d-\\U0001d514\\U0001d516-\\U0001d51c\\U0001d538-\\U0001d539\\U0001d53b-\\U0001d53e\\U0001d540-\\U0001d544\\U0001d546\\U0001d54a-\\U0001d550\\U0001d56c-\\U0001d585\\U0001d5a0-\\U0001d5b9\\U0001d5d4-\\U0001d5ed\\U0001d608-\\U0001d621\\U0001d63c-\\U0001d655\\U0001d670-\\U0001d689\\U0001d6a8-\\U0001d6c0\\U0001d6e2-\\U0001d6fa\\U0001d71c-\\U0001d734\\U0001d756-\\U0001d76e\\U0001d790-\\U0001d7a8\\U0001d7ca\\U0001e900-\\U0001e921'\n\nMc = '\\u0903\\u093b\\u093e-\\u0940\\u0949-\\u094c\\u094e-\\u094f\\u0982-\\u0983\\u09be-\\u09c0\\u09c7-\\u09c8\\u09cb-\\u09cc\\u09d7\\u0a03\\u0a3e-\\u0a40\\u0a83\\u0abe-\\u0ac0\\u0ac9\\u0acb-\\u0acc\\u0b02-\\u0b03\\u0b3e\\u0b40\\u0b47-\\u0b48\\u0b4b-\\u0b4c\\u0b57\\u0bbe-\\u0bbf\\u0bc1-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcc\\u0bd7\\u0c01-\\u0c03\\u0c41-\\u0c44\\u0c82-\\u0c83\\u0cbe\\u0cc0-\\u0cc4\\u0cc7-\\u0cc8\\u0cca-\\u0ccb\\u0cd5-\\u0cd6\\u0d02-\\u0d03\\u0d3e-\\u0d40\\u0d46-\\u0d48\\u0d4a-\\u0d4c\\u0d57\\u0d82-\\u0d83\\u0dcf-\\u0dd1\\u0dd8-\\u0ddf\\u0df2-\\u0df3\\u0f3e-\\u0f3f\\u0f7f\\u102b-\\u102c\\u1031\\u1038\\u103b-\\u103c\\u1056-\\u1057\\u1062-\\u1064\\u1067-\\u106d\\u1083-\\u1084\\u1087-\\u108c\\u108f\\u109a-\\u109c\\u17b6\\u17be-\\u17c5\\u17c7-\\u17c8\\u1923-\\u1926\\u1929-\\u192b\\u1930-\\u1931\\u1933-\\u1938\\u1a19-\\u1a1a\\u1a55\\u1a57\\u1a61\\u1a63-\\u1a64\\u1a6d-\\u1a72\\u1b04\\u1b35\\u1b3b\\u1b3d-\\u1b41\\u1b43-\\u1b44\\u1b82\\u1ba1\\u1ba6-\\u1ba7\\u1baa\\u1be7\\u1bea-\\u1bec\\u1bee\\u1bf2-\\u1bf3\\u1c24-\\u1c2b\\u1c34-\\u1c35\\u1ce1\\u1cf2-\\u1cf3\\u1cf7\\u302e-\\u302f\\ua823-\\ua824\\ua827\\ua880-\\ua881\\ua8b4-\\ua8c3\\ua952-\\ua953\\ua983\\ua9b4-\\ua9b5\\ua9ba-\\ua9bb\\ua9bd-\\ua9c0\\uaa2f-\\uaa30\\uaa33-\\uaa34\\uaa4d\\uaa7b\\uaa7d\\uaaeb\\uaaee-\\uaaef\\uaaf5\\uabe3-\\uabe4\\uabe6-\\uabe7\\uabe9-\\uabea\\uabec\\U00011000\\U00011002\\U00011082\\U000110b0-\\U000110b2\\U000110b7-\\U000110b8\\U0001112c\\U00011145-\\U00011146\\U00011182\\U000111b3-\\U000111b5\\U000111bf-\\U000111c0\\U0001122c-\\U0001122e\\U00011232-\\U00011233\\U00011235\\U000112e0-\\U000112e2\\U00011302-\\U00011303\\U0001133e-\\U0001133f\\U00011341-\\U00011344\\U00011347-\\U00011348\\U0001134b-\\U0001134d\\U00011357\\U00011362-\\U00011363\\U00011435-\\U00011437\\U00011440-\\U00011441\\U00011445\\U000114b0-\\U000114b2\\U000114b9\\U000114bb-\\U000114be\\U000114c1\\U000115af-\\U000115b1\\U000115b8-\\U000115bb\\U000115be\\U00011630-\\U00011632\\U0001163b-\\U0001163c\\U0001163e\\U000116ac\\U000116ae-\\U000116af\\U000116b6\\U00011720-\\U00011721\\U00011726\\U0001182c-\\U0001182e\\U00011838\\U00011a39\\U00011a57-\\U00011a58\\U00011a97\\U00011c2f\\U00011c3e\\U00011ca9\\U00011cb1\\U00011cb4\\U00011d8a-\\U00011d8e\\U00011d93-\\U00011d94\\U00011d96\\U00011ef5-\\U00011ef6\\U00016f51-\\U00016f7e\\U0001d165-\\U0001d166\\U0001d16d-\\U0001d172'\n\nMe = '\\u0488-\\u0489\\u1abe\\u20dd-\\u20e0\\u20e2-\\u20e4\\ua670-\\ua672'\n\nMn = '\\u0300-\\u036f\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1-\\u05c2\\u05c4-\\u05c5\\u05c7\\u0610-\\u061a\\u064b-\\u065f\\u0670\\u06d6-\\u06dc\\u06df-\\u06e4\\u06e7-\\u06e8\\u06ea-\\u06ed\\u0711\\u0730-\\u074a\\u07a6-\\u07b0\\u07eb-\\u07f3\\u07fd\\u0816-\\u0819\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0859-\\u085b\\u08d3-\\u08e1\\u08e3-\\u0902\\u093a\\u093c\\u0941-\\u0948\\u094d\\u0951-\\u0957\\u0962-\\u0963\\u0981\\u09bc\\u09c1-\\u09c4\\u09cd\\u09e2-\\u09e3\\u09fe\\u0a01-\\u0a02\\u0a3c\\u0a41-\\u0a42\\u0a47-\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a70-\\u0a71\\u0a75\\u0a81-\\u0a82\\u0abc\\u0ac1-\\u0ac5\\u0ac7-\\u0ac8\\u0acd\\u0ae2-\\u0ae3\\u0afa-\\u0aff\\u0b01\\u0b3c\\u0b3f\\u0b41-\\u0b44\\u0b4d\\u0b56\\u0b62-\\u0b63\\u0b82\\u0bc0\\u0bcd\\u0c00\\u0c04\\u0c3e-\\u0c40\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55-\\u0c56\\u0c62-\\u0c63\\u0c81\\u0cbc\\u0cbf\\u0cc6\\u0ccc-\\u0ccd\\u0ce2-\\u0ce3\\u0d00-\\u0d01\\u0d3b-\\u0d3c\\u0d41-\\u0d44\\u0d4d\\u0d62-\\u0d63\\u0dca\\u0dd2-\\u0dd4\\u0dd6\\u0e31\\u0e34-\\u0e3a\\u0e47-\\u0e4e\\u0eb1\\u0eb4-\\u0eb9\\u0ebb-\\u0ebc\\u0ec8-\\u0ecd\\u0f18-\\u0f19\\u0f35\\u0f37\\u0f39\\u0f71-\\u0f7e\\u0f80-\\u0f84\\u0f86-\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u102d-\\u1030\\u1032-\\u1037\\u1039-\\u103a\\u103d-\\u103e\\u1058-\\u1059\\u105e-\\u1060\\u1071-\\u1074\\u1082\\u1085-\\u1086\\u108d\\u109d\\u135d-\\u135f\\u1712-\\u1714\\u1732-\\u1734\\u1752-\\u1753\\u1772-\\u1773\\u17b4-\\u17b5\\u17b7-\\u17bd\\u17c6\\u17c9-\\u17d3\\u17dd\\u180b-\\u180d\\u1885-\\u1886\\u18a9\\u1920-\\u1922\\u1927-\\u1928\\u1932\\u1939-\\u193b\\u1a17-\\u1a18\\u1a1b\\u1a56\\u1a58-\\u1a5e\\u1a60\\u1a62\\u1a65-\\u1a6c\\u1a73-\\u1a7c\\u1a7f\\u1ab0-\\u1abd\\u1b00-\\u1b03\\u1b34\\u1b36-\\u1b3a\\u1b3c\\u1b42\\u1b6b-\\u1b73\\u1b80-\\u1b81\\u1ba2-\\u1ba5\\u1ba8-\\u1ba9\\u1bab-\\u1bad\\u1be6\\u1be8-\\u1be9\\u1bed\\u1bef-\\u1bf1\\u1c2c-\\u1c33\\u1c36-\\u1c37\\u1cd0-\\u1cd2\\u1cd4-\\u1ce0\\u1ce2-\\u1ce8\\u1ced\\u1cf4\\u1cf8-\\u1cf9\\u1dc0-\\u1df9\\u1dfb-\\u1dff\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2cef-\\u2cf1\\u2d7f\\u2de0-\\u2dff\\u302a-\\u302d\\u3099-\\u309a\\ua66f\\ua674-\\ua67d\\ua69e-\\ua69f\\ua6f0-\\ua6f1\\ua802\\ua806\\ua80b\\ua825-\\ua826\\ua8c4-\\ua8c5\\ua8e0-\\ua8f1\\ua8ff\\ua926-\\ua92d\\ua947-\\ua951\\ua980-\\ua982\\ua9b3\\ua9b6-\\ua9b9\\ua9bc\\ua9e5\\uaa29-\\uaa2e\\uaa31-\\uaa32\\uaa35-\\uaa36\\uaa43\\uaa4c\\uaa7c\\uaab0\\uaab2-\\uaab4\\uaab7-\\uaab8\\uaabe-\\uaabf\\uaac1\\uaaec-\\uaaed\\uaaf6\\uabe5\\uabe8\\uabed\\ufb1e\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\U000101fd\\U000102e0\\U00010376-\\U0001037a\\U00010a01-\\U00010a03\\U00010a05-\\U00010a06\\U00010a0c-\\U00010a0f\\U00010a38-\\U00010a3a\\U00010a3f\\U00010ae5-\\U00010ae6\\U00010d24-\\U00010d27\\U00010f46-\\U00010f50\\U00011001\\U00011038-\\U00011046\\U0001107f-\\U00011081\\U000110b3-\\U000110b6\\U000110b9-\\U000110ba\\U00011100-\\U00011102\\U00011127-\\U0001112b\\U0001112d-\\U00011134\\U00011173\\U00011180-\\U00011181\\U000111b6-\\U000111be\\U000111c9-\\U000111cc\\U0001122f-\\U00011231\\U00011234\\U00011236-\\U00011237\\U0001123e\\U000112df\\U000112e3-\\U000112ea\\U00011300-\\U00011301\\U0001133b-\\U0001133c\\U00011340\\U00011366-\\U0001136c\\U00011370-\\U00011374\\U00011438-\\U0001143f\\U00011442-\\U00011444\\U00011446\\U0001145e\\U000114b3-\\U000114b8\\U000114ba\\U000114bf-\\U000114c0\\U000114c2-\\U000114c3\\U000115b2-\\U000115b5\\U000115bc-\\U000115bd\\U000115bf-\\U000115c0\\U000115dc-\\U000115dd\\U00011633-\\U0001163a\\U0001163d\\U0001163f-\\U00011640\\U000116ab\\U000116ad\\U000116b0-\\U000116b5\\U000116b7\\U0001171d-\\U0001171f\\U00011722-\\U00011725\\U00011727-\\U0001172b\\U0001182f-\\U00011837\\U00011839-\\U0001183a\\U00011a01-\\U00011a0a\\U00011a33-\\U00011a38\\U00011a3b-\\U00011a3e\\U00011a47\\U00011a51-\\U00011a56\\U00011a59-\\U00011a5b\\U00011a8a-\\U00011a96\\U00011a98-\\U00011a99\\U00011c30-\\U00011c36\\U00011c38-\\U00011c3d\\U00011c3f\\U00011c92-\\U00011ca7\\U00011caa-\\U00011cb0\\U00011cb2-\\U00011cb3\\U00011cb5-\\U00011cb6\\U00011d31-\\U00011d36\\U00011d3a\\U00011d3c-\\U00011d3d\\U00011d3f-\\U00011d45\\U00011d47\\U00011d90-\\U00011d91\\U00011d95\\U00011d97\\U00011ef3-\\U00011ef4\\U00016af0-\\U00016af4\\U00016b30-\\U00016b36\\U00016f8f-\\U00016f92\\U0001bc9d-\\U0001bc9e\\U0001d167-\\U0001d169\\U0001d17b-\\U0001d182\\U0001d185-\\U0001d18b\\U0001d1aa-\\U0001d1ad\\U0001d242-\\U0001d244\\U0001da00-\\U0001da36\\U0001da3b-\\U0001da6c\\U0001da75\\U0001da84\\U0001da9b-\\U0001da9f\\U0001daa1-\\U0001daaf\\U0001e000-\\U0001e006\\U0001e008-\\U0001e018\\U0001e01b-\\U0001e021\\U0001e023-\\U0001e024\\U0001e026-\\U0001e02a\\U0001e8d0-\\U0001e8d6\\U0001e944-\\U0001e94a\\U000e0100-\\U000e01ef'\n\nNd = '0-9\\u0660-\\u0669\\u06f0-\\u06f9\\u07c0-\\u07c9\\u0966-\\u096f\\u09e6-\\u09ef\\u0a66-\\u0a6f\\u0ae6-\\u0aef\\u0b66-\\u0b6f\\u0be6-\\u0bef\\u0c66-\\u0c6f\\u0ce6-\\u0cef\\u0d66-\\u0d6f\\u0de6-\\u0def\\u0e50-\\u0e59\\u0ed0-\\u0ed9\\u0f20-\\u0f29\\u1040-\\u1049\\u1090-\\u1099\\u17e0-\\u17e9\\u1810-\\u1819\\u1946-\\u194f\\u19d0-\\u19d9\\u1a80-\\u1a89\\u1a90-\\u1a99\\u1b50-\\u1b59\\u1bb0-\\u1bb9\\u1c40-\\u1c49\\u1c50-\\u1c59\\ua620-\\ua629\\ua8d0-\\ua8d9\\ua900-\\ua909\\ua9d0-\\ua9d9\\ua9f0-\\ua9f9\\uaa50-\\uaa59\\uabf0-\\uabf9\\uff10-\\uff19\\U000104a0-\\U000104a9\\U00010d30-\\U00010d39\\U00011066-\\U0001106f\\U000110f0-\\U000110f9\\U00011136-\\U0001113f\\U000111d0-\\U000111d9\\U000112f0-\\U000112f9\\U00011450-\\U00011459\\U000114d0-\\U000114d9\\U00011650-\\U00011659\\U000116c0-\\U000116c9\\U00011730-\\U00011739\\U000118e0-\\U000118e9\\U00011c50-\\U00011c59\\U00011d50-\\U00011d59\\U00011da0-\\U00011da9\\U00016a60-\\U00016a69\\U00016b50-\\U00016b59\\U0001d7ce-\\U0001d7ff\\U0001e950-\\U0001e959'\n\nNl = '\\u16ee-\\u16f0\\u2160-\\u2182\\u2185-\\u2188\\u3007\\u3021-\\u3029\\u3038-\\u303a\\ua6e6-\\ua6ef\\U00010140-\\U00010174\\U00010341\\U0001034a\\U000103d1-\\U000103d5\\U00012400-\\U0001246e'\n\nNo = '\\xb2-\\xb3\\xb9\\xbc-\\xbe\\u09f4-\\u09f9\\u0b72-\\u0b77\\u0bf0-\\u0bf2\\u0c78-\\u0c7e\\u0d58-\\u0d5e\\u0d70-\\u0d78\\u0f2a-\\u0f33\\u1369-\\u137c\\u17f0-\\u17f9\\u19da\\u2070\\u2074-\\u2079\\u2080-\\u2089\\u2150-\\u215f\\u2189\\u2460-\\u249b\\u24ea-\\u24ff\\u2776-\\u2793\\u2cfd\\u3192-\\u3195\\u3220-\\u3229\\u3248-\\u324f\\u3251-\\u325f\\u3280-\\u3289\\u32b1-\\u32bf\\ua830-\\ua835\\U00010107-\\U00010133\\U00010175-\\U00010178\\U0001018a-\\U0001018b\\U000102e1-\\U000102fb\\U00010320-\\U00010323\\U00010858-\\U0001085f\\U00010879-\\U0001087f\\U000108a7-\\U000108af\\U000108fb-\\U000108ff\\U00010916-\\U0001091b\\U000109bc-\\U000109bd\\U000109c0-\\U000109cf\\U000109d2-\\U000109ff\\U00010a40-\\U00010a48\\U00010a7d-\\U00010a7e\\U00010a9d-\\U00010a9f\\U00010aeb-\\U00010aef\\U00010b58-\\U00010b5f\\U00010b78-\\U00010b7f\\U00010ba9-\\U00010baf\\U00010cfa-\\U00010cff\\U00010e60-\\U00010e7e\\U00010f1d-\\U00010f26\\U00010f51-\\U00010f54\\U00011052-\\U00011065\\U000111e1-\\U000111f4\\U0001173a-\\U0001173b\\U000118ea-\\U000118f2\\U00011c5a-\\U00011c6c\\U00016b5b-\\U00016b61\\U00016e80-\\U00016e96\\U0001d2e0-\\U0001d2f3\\U0001d360-\\U0001d378\\U0001e8c7-\\U0001e8cf\\U0001ec71-\\U0001ecab\\U0001ecad-\\U0001ecaf\\U0001ecb1-\\U0001ecb4\\U0001f100-\\U0001f10c'\n\nPc = '_\\u203f-\\u2040\\u2054\\ufe33-\\ufe34\\ufe4d-\\ufe4f\\uff3f'\n\nPd = '\\\\-\\u058a\\u05be\\u1400\\u1806\\u2010-\\u2015\\u2e17\\u2e1a\\u2e3a-\\u2e3b\\u2e40\\u301c\\u3030\\u30a0\\ufe31-\\ufe32\\ufe58\\ufe63\\uff0d'\n\nPe = ')\\\\]}\\u0f3b\\u0f3d\\u169c\\u2046\\u207e\\u208e\\u2309\\u230b\\u232a\\u2769\\u276b\\u276d\\u276f\\u2771\\u2773\\u2775\\u27c6\\u27e7\\u27e9\\u27eb\\u27ed\\u27ef\\u2984\\u2986\\u2988\\u298a\\u298c\\u298e\\u2990\\u2992\\u2994\\u2996\\u2998\\u29d9\\u29db\\u29fd\\u2e23\\u2e25\\u2e27\\u2e29\\u3009\\u300b\\u300d\\u300f\\u3011\\u3015\\u3017\\u3019\\u301b\\u301e-\\u301f\\ufd3e\\ufe18\\ufe36\\ufe38\\ufe3a\\ufe3c\\ufe3e\\ufe40\\ufe42\\ufe44\\ufe48\\ufe5a\\ufe5c\\ufe5e\\uff09\\uff3d\\uff5d\\uff60\\uff63'\n\nPf = '\\xbb\\u2019\\u201d\\u203a\\u2e03\\u2e05\\u2e0a\\u2e0d\\u2e1d\\u2e21'\n\nPi = '\\xab\\u2018\\u201b-\\u201c\\u201f\\u2039\\u2e02\\u2e04\\u2e09\\u2e0c\\u2e1c\\u2e20'\n\nPo = \"!-#%-'*,.-/:-;?-@\\\\\\\\\\xa1\\xa7\\xb6-\\xb7\\xbf\\u037e\\u0387\\u055a-\\u055f\\u0589\\u05c0\\u05c3\\u05c6\\u05f3-\\u05f4\\u0609-\\u060a\\u060c-\\u060d\\u061b\\u061e-\\u061f\\u066a-\\u066d\\u06d4\\u0700-\\u070d\\u07f7-\\u07f9\\u0830-\\u083e\\u085e\\u0964-\\u0965\\u0970\\u09fd\\u0a76\\u0af0\\u0c84\\u0df4\\u0e4f\\u0e5a-\\u0e5b\\u0f04-\\u0f12\\u0f14\\u0f85\\u0fd0-\\u0fd4\\u0fd9-\\u0fda\\u104a-\\u104f\\u10fb\\u1360-\\u1368\\u166d-\\u166e\\u16eb-\\u16ed\\u1735-\\u1736\\u17d4-\\u17d6\\u17d8-\\u17da\\u1800-\\u1805\\u1807-\\u180a\\u1944-\\u1945\\u1a1e-\\u1a1f\\u1aa0-\\u1aa6\\u1aa8-\\u1aad\\u1b5a-\\u1b60\\u1bfc-\\u1bff\\u1c3b-\\u1c3f\\u1c7e-\\u1c7f\\u1cc0-\\u1cc7\\u1cd3\\u2016-\\u2017\\u2020-\\u2027\\u2030-\\u2038\\u203b-\\u203e\\u2041-\\u2043\\u2047-\\u2051\\u2053\\u2055-\\u205e\\u2cf9-\\u2cfc\\u2cfe-\\u2cff\\u2d70\\u2e00-\\u2e01\\u2e06-\\u2e08\\u2e0b\\u2e0e-\\u2e16\\u2e18-\\u2e19\\u2e1b\\u2e1e-\\u2e1f\\u2e2a-\\u2e2e\\u2e30-\\u2e39\\u2e3c-\\u2e3f\\u2e41\\u2e43-\\u2e4e\\u3001-\\u3003\\u303d\\u30fb\\ua4fe-\\ua4ff\\ua60d-\\ua60f\\ua673\\ua67e\\ua6f2-\\ua6f7\\ua874-\\ua877\\ua8ce-\\ua8cf\\ua8f8-\\ua8fa\\ua8fc\\ua92e-\\ua92f\\ua95f\\ua9c1-\\ua9cd\\ua9de-\\ua9df\\uaa5c-\\uaa5f\\uaade-\\uaadf\\uaaf0-\\uaaf1\\uabeb\\ufe10-\\ufe16\\ufe19\\ufe30\\ufe45-\\ufe46\\ufe49-\\ufe4c\\ufe50-\\ufe52\\ufe54-\\ufe57\\ufe5f-\\ufe61\\ufe68\\ufe6a-\\ufe6b\\uff01-\\uff03\\uff05-\\uff07\\uff0a\\uff0c\\uff0e-\\uff0f\\uff1a-\\uff1b\\uff1f-\\uff20\\uff3c\\uff61\\uff64-\\uff65\\U00010100-\\U00010102\\U0001039f\\U000103d0\\U0001056f\\U00010857\\U0001091f\\U0001093f\\U00010a50-\\U00010a58\\U00010a7f\\U00010af0-\\U00010af6\\U00010b39-\\U00010b3f\\U00010b99-\\U00010b9c\\U00010f55-\\U00010f59\\U00011047-\\U0001104d\\U000110bb-\\U000110bc\\U000110be-\\U000110c1\\U00011140-\\U00011143\\U00011174-\\U00011175\\U000111c5-\\U000111c8\\U000111cd\\U000111db\\U000111dd-\\U000111df\\U00011238-\\U0001123d\\U000112a9\\U0001144b-\\U0001144f\\U0001145b\\U0001145d\\U000114c6\\U000115c1-\\U000115d7\\U00011641-\\U00011643\\U00011660-\\U0001166c\\U0001173c-\\U0001173e\\U0001183b\\U00011a3f-\\U00011a46\\U00011a9a-\\U00011a9c\\U00011a9e-\\U00011aa2\\U00011c41-\\U00011c45\\U00011c70-\\U00011c71\\U00011ef7-\\U00011ef8\\U00012470-\\U00012474\\U00016a6e-\\U00016a6f\\U00016af5\\U00016b37-\\U00016b3b\\U00016b44\\U00016e97-\\U00016e9a\\U0001bc9f\\U0001da87-\\U0001da8b\\U0001e95e-\\U0001e95f\"\n\nPs = '(\\\\[{\\u0f3a\\u0f3c\\u169b\\u201a\\u201e\\u2045\\u207d\\u208d\\u2308\\u230a\\u2329\\u2768\\u276a\\u276c\\u276e\\u2770\\u2772\\u2774\\u27c5\\u27e6\\u27e8\\u27ea\\u27ec\\u27ee\\u2983\\u2985\\u2987\\u2989\\u298b\\u298d\\u298f\\u2991\\u2993\\u2995\\u2997\\u29d8\\u29da\\u29fc\\u2e22\\u2e24\\u2e26\\u2e28\\u2e42\\u3008\\u300a\\u300c\\u300e\\u3010\\u3014\\u3016\\u3018\\u301a\\u301d\\ufd3f\\ufe17\\ufe35\\ufe37\\ufe39\\ufe3b\\ufe3d\\ufe3f\\ufe41\\ufe43\\ufe47\\ufe59\\ufe5b\\ufe5d\\uff08\\uff3b\\uff5b\\uff5f\\uff62'\n\nSc = '$\\xa2-\\xa5\\u058f\\u060b\\u07fe-\\u07ff\\u09f2-\\u09f3\\u09fb\\u0af1\\u0bf9\\u0e3f\\u17db\\u20a0-\\u20bf\\ua838\\ufdfc\\ufe69\\uff04\\uffe0-\\uffe1\\uffe5-\\uffe6\\U0001ecb0'\n\nSk = '\\\\^`\\xa8\\xaf\\xb4\\xb8\\u02c2-\\u02c5\\u02d2-\\u02df\\u02e5-\\u02eb\\u02ed\\u02ef-\\u02ff\\u0375\\u0384-\\u0385\\u1fbd\\u1fbf-\\u1fc1\\u1fcd-\\u1fcf\\u1fdd-\\u1fdf\\u1fed-\\u1fef\\u1ffd-\\u1ffe\\u309b-\\u309c\\ua700-\\ua716\\ua720-\\ua721\\ua789-\\ua78a\\uab5b\\ufbb2-\\ufbc1\\uff3e\\uff40\\uffe3\\U0001f3fb-\\U0001f3ff'\n\nSm = '+<->|~\\xac\\xb1\\xd7\\xf7\\u03f6\\u0606-\\u0608\\u2044\\u2052\\u207a-\\u207c\\u208a-\\u208c\\u2118\\u2140-\\u2144\\u214b\\u2190-\\u2194\\u219a-\\u219b\\u21a0\\u21a3\\u21a6\\u21ae\\u21ce-\\u21cf\\u21d2\\u21d4\\u21f4-\\u22ff\\u2320-\\u2321\\u237c\\u239b-\\u23b3\\u23dc-\\u23e1\\u25b7\\u25c1\\u25f8-\\u25ff\\u266f\\u27c0-\\u27c4\\u27c7-\\u27e5\\u27f0-\\u27ff\\u2900-\\u2982\\u2999-\\u29d7\\u29dc-\\u29fb\\u29fe-\\u2aff\\u2b30-\\u2b44\\u2b47-\\u2b4c\\ufb29\\ufe62\\ufe64-\\ufe66\\uff0b\\uff1c-\\uff1e\\uff5c\\uff5e\\uffe2\\uffe9-\\uffec\\U0001d6c1\\U0001d6db\\U0001d6fb\\U0001d715\\U0001d735\\U0001d74f\\U0001d76f\\U0001d789\\U0001d7a9\\U0001d7c3\\U0001eef0-\\U0001eef1'\n\nSo = '\\xa6\\xa9\\xae\\xb0\\u0482\\u058d-\\u058e\\u060e-\\u060f\\u06de\\u06e9\\u06fd-\\u06fe\\u07f6\\u09fa\\u0b70\\u0bf3-\\u0bf8\\u0bfa\\u0c7f\\u0d4f\\u0d79\\u0f01-\\u0f03\\u0f13\\u0f15-\\u0f17\\u0f1a-\\u0f1f\\u0f34\\u0f36\\u0f38\\u0fbe-\\u0fc5\\u0fc7-\\u0fcc\\u0fce-\\u0fcf\\u0fd5-\\u0fd8\\u109e-\\u109f\\u1390-\\u1399\\u1940\\u19de-\\u19ff\\u1b61-\\u1b6a\\u1b74-\\u1b7c\\u2100-\\u2101\\u2103-\\u2106\\u2108-\\u2109\\u2114\\u2116-\\u2117\\u211e-\\u2123\\u2125\\u2127\\u2129\\u212e\\u213a-\\u213b\\u214a\\u214c-\\u214d\\u214f\\u218a-\\u218b\\u2195-\\u2199\\u219c-\\u219f\\u21a1-\\u21a2\\u21a4-\\u21a5\\u21a7-\\u21ad\\u21af-\\u21cd\\u21d0-\\u21d1\\u21d3\\u21d5-\\u21f3\\u2300-\\u2307\\u230c-\\u231f\\u2322-\\u2328\\u232b-\\u237b\\u237d-\\u239a\\u23b4-\\u23db\\u23e2-\\u2426\\u2440-\\u244a\\u249c-\\u24e9\\u2500-\\u25b6\\u25b8-\\u25c0\\u25c2-\\u25f7\\u2600-\\u266e\\u2670-\\u2767\\u2794-\\u27bf\\u2800-\\u28ff\\u2b00-\\u2b2f\\u2b45-\\u2b46\\u2b4d-\\u2b73\\u2b76-\\u2b95\\u2b98-\\u2bc8\\u2bca-\\u2bfe\\u2ce5-\\u2cea\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u2ff0-\\u2ffb\\u3004\\u3012-\\u3013\\u3020\\u3036-\\u3037\\u303e-\\u303f\\u3190-\\u3191\\u3196-\\u319f\\u31c0-\\u31e3\\u3200-\\u321e\\u322a-\\u3247\\u3250\\u3260-\\u327f\\u328a-\\u32b0\\u32c0-\\u32fe\\u3300-\\u33ff\\u4dc0-\\u4dff\\ua490-\\ua4c6\\ua828-\\ua82b\\ua836-\\ua837\\ua839\\uaa77-\\uaa79\\ufdfd\\uffe4\\uffe8\\uffed-\\uffee\\ufffc-\\ufffd\\U00010137-\\U0001013f\\U00010179-\\U00010189\\U0001018c-\\U0001018e\\U00010190-\\U0001019b\\U000101a0\\U000101d0-\\U000101fc\\U00010877-\\U00010878\\U00010ac8\\U0001173f\\U00016b3c-\\U00016b3f\\U00016b45\\U0001bc9c\\U0001d000-\\U0001d0f5\\U0001d100-\\U0001d126\\U0001d129-\\U0001d164\\U0001d16a-\\U0001d16c\\U0001d183-\\U0001d184\\U0001d18c-\\U0001d1a9\\U0001d1ae-\\U0001d1e8\\U0001d200-\\U0001d241\\U0001d245\\U0001d300-\\U0001d356\\U0001d800-\\U0001d9ff\\U0001da37-\\U0001da3a\\U0001da6d-\\U0001da74\\U0001da76-\\U0001da83\\U0001da85-\\U0001da86\\U0001ecac\\U0001f000-\\U0001f02b\\U0001f030-\\U0001f093\\U0001f0a0-\\U0001f0ae\\U0001f0b1-\\U0001f0bf\\U0001f0c1-\\U0001f0cf\\U0001f0d1-\\U0001f0f5\\U0001f110-\\U0001f16b\\U0001f170-\\U0001f1ac\\U0001f1e6-\\U0001f202\\U0001f210-\\U0001f23b\\U0001f240-\\U0001f248\\U0001f250-\\U0001f251\\U0001f260-\\U0001f265\\U0001f300-\\U0001f3fa\\U0001f400-\\U0001f6d4\\U0001f6e0-\\U0001f6ec\\U0001f6f0-\\U0001f6f9\\U0001f700-\\U0001f773\\U0001f780-\\U0001f7d8\\U0001f800-\\U0001f80b\\U0001f810-\\U0001f847\\U0001f850-\\U0001f859\\U0001f860-\\U0001f887\\U0001f890-\\U0001f8ad\\U0001f900-\\U0001f90b\\U0001f910-\\U0001f93e\\U0001f940-\\U0001f970\\U0001f973-\\U0001f976\\U0001f97a\\U0001f97c-\\U0001f9a2\\U0001f9b0-\\U0001f9b9\\U0001f9c0-\\U0001f9c2\\U0001f9d0-\\U0001f9ff\\U0001fa60-\\U0001fa6d'\n\nZl = '\\u2028'\n\nZp = '\\u2029'\n\nZs = ' \\xa0\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000'\n\nxid_continue = '0-9A-Z_a-z\\xaa\\xb5\\xb7\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0300-\\u0374\\u0376-\\u0377\\u037b-\\u037d\\u037f\\u0386-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u0483-\\u0487\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u0591-\\u05bd\\u05bf\\u05c1-\\u05c2\\u05c4-\\u05c5\\u05c7\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0610-\\u061a\\u0620-\\u0669\\u066e-\\u06d3\\u06d5-\\u06dc\\u06df-\\u06e8\\u06ea-\\u06fc\\u06ff\\u0710-\\u074a\\u074d-\\u07b1\\u07c0-\\u07f5\\u07fa\\u07fd\\u0800-\\u082d\\u0840-\\u085b\\u0860-\\u086a\\u08a0-\\u08b4\\u08b6-\\u08bd\\u08d3-\\u08e1\\u08e3-\\u0963\\u0966-\\u096f\\u0971-\\u0983\\u0985-\\u098c\\u098f-\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bc-\\u09c4\\u09c7-\\u09c8\\u09cb-\\u09ce\\u09d7\\u09dc-\\u09dd\\u09df-\\u09e3\\u09e6-\\u09f1\\u09fc\\u09fe\\u0a01-\\u0a03\\u0a05-\\u0a0a\\u0a0f-\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32-\\u0a33\\u0a35-\\u0a36\\u0a38-\\u0a39\\u0a3c\\u0a3e-\\u0a42\\u0a47-\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a59-\\u0a5c\\u0a5e\\u0a66-\\u0a75\\u0a81-\\u0a83\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2-\\u0ab3\\u0ab5-\\u0ab9\\u0abc-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ad0\\u0ae0-\\u0ae3\\u0ae6-\\u0aef\\u0af9-\\u0aff\\u0b01-\\u0b03\\u0b05-\\u0b0c\\u0b0f-\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32-\\u0b33\\u0b35-\\u0b39\\u0b3c-\\u0b44\\u0b47-\\u0b48\\u0b4b-\\u0b4d\\u0b56-\\u0b57\\u0b5c-\\u0b5d\\u0b5f-\\u0b63\\u0b66-\\u0b6f\\u0b71\\u0b82-\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99-\\u0b9a\\u0b9c\\u0b9e-\\u0b9f\\u0ba3-\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd0\\u0bd7\\u0be6-\\u0bef\\u0c00-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d-\\u0c44\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55-\\u0c56\\u0c58-\\u0c5a\\u0c60-\\u0c63\\u0c66-\\u0c6f\\u0c80-\\u0c83\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbc-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5-\\u0cd6\\u0cde\\u0ce0-\\u0ce3\\u0ce6-\\u0cef\\u0cf1-\\u0cf2\\u0d00-\\u0d03\\u0d05-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d44\\u0d46-\\u0d48\\u0d4a-\\u0d4e\\u0d54-\\u0d57\\u0d5f-\\u0d63\\u0d66-\\u0d6f\\u0d7a-\\u0d7f\\u0d82-\\u0d83\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0de6-\\u0def\\u0df2-\\u0df3\\u0e01-\\u0e3a\\u0e40-\\u0e4e\\u0e50-\\u0e59\\u0e81-\\u0e82\\u0e84\\u0e87-\\u0e88\\u0e8a\\u0e8d\\u0e94-\\u0e97\\u0e99-\\u0e9f\\u0ea1-\\u0ea3\\u0ea5\\u0ea7\\u0eaa-\\u0eab\\u0ead-\\u0eb9\\u0ebb-\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0ec8-\\u0ecd\\u0ed0-\\u0ed9\\u0edc-\\u0edf\\u0f00\\u0f18-\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f3e-\\u0f47\\u0f49-\\u0f6c\\u0f71-\\u0f84\\u0f86-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u1000-\\u1049\\u1050-\\u109d\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u135d-\\u135f\\u1369-\\u1371\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u170c\\u170e-\\u1714\\u1720-\\u1734\\u1740-\\u1753\\u1760-\\u176c\\u176e-\\u1770\\u1772-\\u1773\\u1780-\\u17d3\\u17d7\\u17dc-\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u1810-\\u1819\\u1820-\\u1878\\u1880-\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1920-\\u192b\\u1930-\\u193b\\u1946-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u19d0-\\u19da\\u1a00-\\u1a1b\\u1a20-\\u1a5e\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1aa7\\u1ab0-\\u1abd\\u1b00-\\u1b4b\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1b80-\\u1bf3\\u1c00-\\u1c37\\u1c40-\\u1c49\\u1c4d-\\u1c7d\\u1c80-\\u1c88\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1cd0-\\u1cd2\\u1cd4-\\u1cf9\\u1d00-\\u1df9\\u1dfb-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u203f-\\u2040\\u2054\\u2071\\u207f\\u2090-\\u209c\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2c2e\\u2c30-\\u2c5e\\u2c60-\\u2ce4\\u2ceb-\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d7f-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u2de0-\\u2dff\\u3005-\\u3007\\u3021-\\u302f\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u3099-\\u309a\\u309d-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31ba\\u31f0-\\u31ff\\u3400-\\u4db5\\u4e00-\\u9fef\\ua000-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua62b\\ua640-\\ua66f\\ua674-\\ua67d\\ua67f-\\ua6f1\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7b9\\ua7f7-\\ua827\\ua840-\\ua873\\ua880-\\ua8c5\\ua8d0-\\ua8d9\\ua8e0-\\ua8f7\\ua8fb\\ua8fd-\\ua92d\\ua930-\\ua953\\ua960-\\ua97c\\ua980-\\ua9c0\\ua9cf-\\ua9d9\\ua9e0-\\ua9fe\\uaa00-\\uaa36\\uaa40-\\uaa4d\\uaa50-\\uaa59\\uaa60-\\uaa76\\uaa7a-\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaef\\uaaf2-\\uaaf6\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab65\\uab70-\\uabea\\uabec-\\uabed\\uabf0-\\uabf9\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40-\\ufb41\\ufb43-\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufc5d\\ufc64-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdf9\\ufe00-\\ufe0f\\ufe20-\\ufe2f\\ufe33-\\ufe34\\ufe4d-\\ufe4f\\ufe71\\ufe73\\ufe77\\ufe79\\ufe7b\\ufe7d\\ufe7f-\\ufefc\\uff10-\\uff19\\uff21-\\uff3a\\uff3f\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\\U00010000-\\U0001000b\\U0001000d-\\U00010026\\U00010028-\\U0001003a\\U0001003c-\\U0001003d\\U0001003f-\\U0001004d\\U00010050-\\U0001005d\\U00010080-\\U000100fa\\U00010140-\\U00010174\\U000101fd\\U00010280-\\U0001029c\\U000102a0-\\U000102d0\\U000102e0\\U00010300-\\U0001031f\\U0001032d-\\U0001034a\\U00010350-\\U0001037a\\U00010380-\\U0001039d\\U000103a0-\\U000103c3\\U000103c8-\\U000103cf\\U000103d1-\\U000103d5\\U00010400-\\U0001049d\\U000104a0-\\U000104a9\\U000104b0-\\U000104d3\\U000104d8-\\U000104fb\\U00010500-\\U00010527\\U00010530-\\U00010563\\U00010600-\\U00010736\\U00010740-\\U00010755\\U00010760-\\U00010767\\U00010800-\\U00010805\\U00010808\\U0001080a-\\U00010835\\U00010837-\\U00010838\\U0001083c\\U0001083f-\\U00010855\\U00010860-\\U00010876\\U00010880-\\U0001089e\\U000108e0-\\U000108f2\\U000108f4-\\U000108f5\\U00010900-\\U00010915\\U00010920-\\U00010939\\U00010980-\\U000109b7\\U000109be-\\U000109bf\\U00010a00-\\U00010a03\\U00010a05-\\U00010a06\\U00010a0c-\\U00010a13\\U00010a15-\\U00010a17\\U00010a19-\\U00010a35\\U00010a38-\\U00010a3a\\U00010a3f\\U00010a60-\\U00010a7c\\U00010a80-\\U00010a9c\\U00010ac0-\\U00010ac7\\U00010ac9-\\U00010ae6\\U00010b00-\\U00010b35\\U00010b40-\\U00010b55\\U00010b60-\\U00010b72\\U00010b80-\\U00010b91\\U00010c00-\\U00010c48\\U00010c80-\\U00010cb2\\U00010cc0-\\U00010cf2\\U00010d00-\\U00010d27\\U00010d30-\\U00010d39\\U00010f00-\\U00010f1c\\U00010f27\\U00010f30-\\U00010f50\\U00011000-\\U00011046\\U00011066-\\U0001106f\\U0001107f-\\U000110ba\\U000110d0-\\U000110e8\\U000110f0-\\U000110f9\\U00011100-\\U00011134\\U00011136-\\U0001113f\\U00011144-\\U00011146\\U00011150-\\U00011173\\U00011176\\U00011180-\\U000111c4\\U000111c9-\\U000111cc\\U000111d0-\\U000111da\\U000111dc\\U00011200-\\U00011211\\U00011213-\\U00011237\\U0001123e\\U00011280-\\U00011286\\U00011288\\U0001128a-\\U0001128d\\U0001128f-\\U0001129d\\U0001129f-\\U000112a8\\U000112b0-\\U000112ea\\U000112f0-\\U000112f9\\U00011300-\\U00011303\\U00011305-\\U0001130c\\U0001130f-\\U00011310\\U00011313-\\U00011328\\U0001132a-\\U00011330\\U00011332-\\U00011333\\U00011335-\\U00011339\\U0001133b-\\U00011344\\U00011347-\\U00011348\\U0001134b-\\U0001134d\\U00011350\\U00011357\\U0001135d-\\U00011363\\U00011366-\\U0001136c\\U00011370-\\U00011374\\U00011400-\\U0001144a\\U00011450-\\U00011459\\U0001145e\\U00011480-\\U000114c5\\U000114c7\\U000114d0-\\U000114d9\\U00011580-\\U000115b5\\U000115b8-\\U000115c0\\U000115d8-\\U000115dd\\U00011600-\\U00011640\\U00011644\\U00011650-\\U00011659\\U00011680-\\U000116b7\\U000116c0-\\U000116c9\\U00011700-\\U0001171a\\U0001171d-\\U0001172b\\U00011730-\\U00011739\\U00011800-\\U0001183a\\U000118a0-\\U000118e9\\U000118ff\\U00011a00-\\U00011a3e\\U00011a47\\U00011a50-\\U00011a83\\U00011a86-\\U00011a99\\U00011a9d\\U00011ac0-\\U00011af8\\U00011c00-\\U00011c08\\U00011c0a-\\U00011c36\\U00011c38-\\U00011c40\\U00011c50-\\U00011c59\\U00011c72-\\U00011c8f\\U00011c92-\\U00011ca7\\U00011ca9-\\U00011cb6\\U00011d00-\\U00011d06\\U00011d08-\\U00011d09\\U00011d0b-\\U00011d36\\U00011d3a\\U00011d3c-\\U00011d3d\\U00011d3f-\\U00011d47\\U00011d50-\\U00011d59\\U00011d60-\\U00011d65\\U00011d67-\\U00011d68\\U00011d6a-\\U00011d8e\\U00011d90-\\U00011d91\\U00011d93-\\U00011d98\\U00011da0-\\U00011da9\\U00011ee0-\\U00011ef6\\U00012000-\\U00012399\\U00012400-\\U0001246e\\U00012480-\\U00012543\\U00013000-\\U0001342e\\U00014400-\\U00014646\\U00016800-\\U00016a38\\U00016a40-\\U00016a5e\\U00016a60-\\U00016a69\\U00016ad0-\\U00016aed\\U00016af0-\\U00016af4\\U00016b00-\\U00016b36\\U00016b40-\\U00016b43\\U00016b50-\\U00016b59\\U00016b63-\\U00016b77\\U00016b7d-\\U00016b8f\\U00016e40-\\U00016e7f\\U00016f00-\\U00016f44\\U00016f50-\\U00016f7e\\U00016f8f-\\U00016f9f\\U00016fe0-\\U00016fe1\\U00017000-\\U000187f1\\U00018800-\\U00018af2\\U0001b000-\\U0001b11e\\U0001b170-\\U0001b2fb\\U0001bc00-\\U0001bc6a\\U0001bc70-\\U0001bc7c\\U0001bc80-\\U0001bc88\\U0001bc90-\\U0001bc99\\U0001bc9d-\\U0001bc9e\\U0001d165-\\U0001d169\\U0001d16d-\\U0001d172\\U0001d17b-\\U0001d182\\U0001d185-\\U0001d18b\\U0001d1aa-\\U0001d1ad\\U0001d242-\\U0001d244\\U0001d400-\\U0001d454\\U0001d456-\\U0001d49c\\U0001d49e-\\U0001d49f\\U0001d4a2\\U0001d4a5-\\U0001d4a6\\U0001d4a9-\\U0001d4ac\\U0001d4ae-\\U0001d4b9\\U0001d4bb\\U0001d4bd-\\U0001d4c3\\U0001d4c5-\\U0001d505\\U0001d507-\\U0001d50a\\U0001d50d-\\U0001d514\\U0001d516-\\U0001d51c\\U0001d51e-\\U0001d539\\U0001d53b-\\U0001d53e\\U0001d540-\\U0001d544\\U0001d546\\U0001d54a-\\U0001d550\\U0001d552-\\U0001d6a5\\U0001d6a8-\\U0001d6c0\\U0001d6c2-\\U0001d6da\\U0001d6dc-\\U0001d6fa\\U0001d6fc-\\U0001d714\\U0001d716-\\U0001d734\\U0001d736-\\U0001d74e\\U0001d750-\\U0001d76e\\U0001d770-\\U0001d788\\U0001d78a-\\U0001d7a8\\U0001d7aa-\\U0001d7c2\\U0001d7c4-\\U0001d7cb\\U0001d7ce-\\U0001d7ff\\U0001da00-\\U0001da36\\U0001da3b-\\U0001da6c\\U0001da75\\U0001da84\\U0001da9b-\\U0001da9f\\U0001daa1-\\U0001daaf\\U0001e000-\\U0001e006\\U0001e008-\\U0001e018\\U0001e01b-\\U0001e021\\U0001e023-\\U0001e024\\U0001e026-\\U0001e02a\\U0001e800-\\U0001e8c4\\U0001e8d0-\\U0001e8d6\\U0001e900-\\U0001e94a\\U0001e950-\\U0001e959\\U0001ee00-\\U0001ee03\\U0001ee05-\\U0001ee1f\\U0001ee21-\\U0001ee22\\U0001ee24\\U0001ee27\\U0001ee29-\\U0001ee32\\U0001ee34-\\U0001ee37\\U0001ee39\\U0001ee3b\\U0001ee42\\U0001ee47\\U0001ee49\\U0001ee4b\\U0001ee4d-\\U0001ee4f\\U0001ee51-\\U0001ee52\\U0001ee54\\U0001ee57\\U0001ee59\\U0001ee5b\\U0001ee5d\\U0001ee5f\\U0001ee61-\\U0001ee62\\U0001ee64\\U0001ee67-\\U0001ee6a\\U0001ee6c-\\U0001ee72\\U0001ee74-\\U0001ee77\\U0001ee79-\\U0001ee7c\\U0001ee7e\\U0001ee80-\\U0001ee89\\U0001ee8b-\\U0001ee9b\\U0001eea1-\\U0001eea3\\U0001eea5-\\U0001eea9\\U0001eeab-\\U0001eebb\\U00020000-\\U0002a6d6\\U0002a700-\\U0002b734\\U0002b740-\\U0002b81d\\U0002b820-\\U0002cea1\\U0002ceb0-\\U0002ebe0\\U0002f800-\\U0002fa1d\\U000e0100-\\U000e01ef'\n\nxid_start = 'A-Z_a-z\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376-\\u0377\\u037b-\\u037d\\u037f\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u052f\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u05d0-\\u05ea\\u05ef-\\u05f2\\u0620-\\u064a\\u066e-\\u066f\\u0671-\\u06d3\\u06d5\\u06e5-\\u06e6\\u06ee-\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4-\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u0860-\\u086a\\u08a0-\\u08b4\\u08b6-\\u08bd\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098c\\u098f-\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc-\\u09dd\\u09df-\\u09e1\\u09f0-\\u09f1\\u09fc\\u0a05-\\u0a0a\\u0a0f-\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32-\\u0a33\\u0a35-\\u0a36\\u0a38-\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2-\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0-\\u0ae1\\u0af9\\u0b05-\\u0b0c\\u0b0f-\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32-\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c-\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99-\\u0b9a\\u0b9c\\u0b9e-\\u0b9f\\u0ba3-\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c39\\u0c3d\\u0c58-\\u0c5a\\u0c60-\\u0c61\\u0c80\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cde\\u0ce0-\\u0ce1\\u0cf1-\\u0cf2\\u0d05-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d54-\\u0d56\\u0d5f-\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e40-\\u0e46\\u0e81-\\u0e82\\u0e84\\u0e87-\\u0e88\\u0e8a\\u0e8d\\u0e94-\\u0e97\\u0e99-\\u0e9f\\u0ea1-\\u0ea3\\u0ea5\\u0ea7\\u0eaa-\\u0eab\\u0ead-\\u0eb0\\u0eb2\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065-\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f5\\u13f8-\\u13fd\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f8\\u1700-\\u170c\\u170e-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1878\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191e\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19b0-\\u19c9\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4b\\u1b83-\\u1ba0\\u1bae-\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1c80-\\u1c88\\u1c90-\\u1cba\\u1cbd-\\u1cbf\\u1ce9-\\u1cec\\u1cee-\\u1cf1\\u1cf5-\\u1cf6\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2118-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2c2e\\u2c30-\\u2c5e\\u2c60-\\u2ce4\\u2ceb-\\u2cee\\u2cf2-\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309d-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u31a0-\\u31ba\\u31f0-\\u31ff\\u3400-\\u4db5\\u4e00-\\u9fef\\ua000-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a-\\ua62b\\ua640-\\ua66e\\ua67f-\\ua69d\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua7b9\\ua7f7-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua8fd-\\ua8fe\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\ua9e0-\\ua9e4\\ua9e6-\\ua9ef\\ua9fa-\\ua9fe\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa7e-\\uaaaf\\uaab1\\uaab5-\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uab30-\\uab5a\\uab5c-\\uab65\\uab70-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40-\\ufb41\\ufb43-\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufc5d\\ufc64-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdf9\\ufe71\\ufe73\\ufe77\\ufe79\\ufe7b\\ufe7d\\ufe7f-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uff9d\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\\U00010000-\\U0001000b\\U0001000d-\\U00010026\\U00010028-\\U0001003a\\U0001003c-\\U0001003d\\U0001003f-\\U0001004d\\U00010050-\\U0001005d\\U00010080-\\U000100fa\\U00010140-\\U00010174\\U00010280-\\U0001029c\\U000102a0-\\U000102d0\\U00010300-\\U0001031f\\U0001032d-\\U0001034a\\U00010350-\\U00010375\\U00010380-\\U0001039d\\U000103a0-\\U000103c3\\U000103c8-\\U000103cf\\U000103d1-\\U000103d5\\U00010400-\\U0001049d\\U000104b0-\\U000104d3\\U000104d8-\\U000104fb\\U00010500-\\U00010527\\U00010530-\\U00010563\\U00010600-\\U00010736\\U00010740-\\U00010755\\U00010760-\\U00010767\\U00010800-\\U00010805\\U00010808\\U0001080a-\\U00010835\\U00010837-\\U00010838\\U0001083c\\U0001083f-\\U00010855\\U00010860-\\U00010876\\U00010880-\\U0001089e\\U000108e0-\\U000108f2\\U000108f4-\\U000108f5\\U00010900-\\U00010915\\U00010920-\\U00010939\\U00010980-\\U000109b7\\U000109be-\\U000109bf\\U00010a00\\U00010a10-\\U00010a13\\U00010a15-\\U00010a17\\U00010a19-\\U00010a35\\U00010a60-\\U00010a7c\\U00010a80-\\U00010a9c\\U00010ac0-\\U00010ac7\\U00010ac9-\\U00010ae4\\U00010b00-\\U00010b35\\U00010b40-\\U00010b55\\U00010b60-\\U00010b72\\U00010b80-\\U00010b91\\U00010c00-\\U00010c48\\U00010c80-\\U00010cb2\\U00010cc0-\\U00010cf2\\U00010d00-\\U00010d23\\U00010f00-\\U00010f1c\\U00010f27\\U00010f30-\\U00010f45\\U00011003-\\U00011037\\U00011083-\\U000110af\\U000110d0-\\U000110e8\\U00011103-\\U00011126\\U00011144\\U00011150-\\U00011172\\U00011176\\U00011183-\\U000111b2\\U000111c1-\\U000111c4\\U000111da\\U000111dc\\U00011200-\\U00011211\\U00011213-\\U0001122b\\U00011280-\\U00011286\\U00011288\\U0001128a-\\U0001128d\\U0001128f-\\U0001129d\\U0001129f-\\U000112a8\\U000112b0-\\U000112de\\U00011305-\\U0001130c\\U0001130f-\\U00011310\\U00011313-\\U00011328\\U0001132a-\\U00011330\\U00011332-\\U00011333\\U00011335-\\U00011339\\U0001133d\\U00011350\\U0001135d-\\U00011361\\U00011400-\\U00011434\\U00011447-\\U0001144a\\U00011480-\\U000114af\\U000114c4-\\U000114c5\\U000114c7\\U00011580-\\U000115ae\\U000115d8-\\U000115db\\U00011600-\\U0001162f\\U00011644\\U00011680-\\U000116aa\\U00011700-\\U0001171a\\U00011800-\\U0001182b\\U000118a0-\\U000118df\\U000118ff\\U00011a00\\U00011a0b-\\U00011a32\\U00011a3a\\U00011a50\\U00011a5c-\\U00011a83\\U00011a86-\\U00011a89\\U00011a9d\\U00011ac0-\\U00011af8\\U00011c00-\\U00011c08\\U00011c0a-\\U00011c2e\\U00011c40\\U00011c72-\\U00011c8f\\U00011d00-\\U00011d06\\U00011d08-\\U00011d09\\U00011d0b-\\U00011d30\\U00011d46\\U00011d60-\\U00011d65\\U00011d67-\\U00011d68\\U00011d6a-\\U00011d89\\U00011d98\\U00011ee0-\\U00011ef2\\U00012000-\\U00012399\\U00012400-\\U0001246e\\U00012480-\\U00012543\\U00013000-\\U0001342e\\U00014400-\\U00014646\\U00016800-\\U00016a38\\U00016a40-\\U00016a5e\\U00016ad0-\\U00016aed\\U00016b00-\\U00016b2f\\U00016b40-\\U00016b43\\U00016b63-\\U00016b77\\U00016b7d-\\U00016b8f\\U00016e40-\\U00016e7f\\U00016f00-\\U00016f44\\U00016f50\\U00016f93-\\U00016f9f\\U00016fe0-\\U00016fe1\\U00017000-\\U000187f1\\U00018800-\\U00018af2\\U0001b000-\\U0001b11e\\U0001b170-\\U0001b2fb\\U0001bc00-\\U0001bc6a\\U0001bc70-\\U0001bc7c\\U0001bc80-\\U0001bc88\\U0001bc90-\\U0001bc99\\U0001d400-\\U0001d454\\U0001d456-\\U0001d49c\\U0001d49e-\\U0001d49f\\U0001d4a2\\U0001d4a5-\\U0001d4a6\\U0001d4a9-\\U0001d4ac\\U0001d4ae-\\U0001d4b9\\U0001d4bb\\U0001d4bd-\\U0001d4c3\\U0001d4c5-\\U0001d505\\U0001d507-\\U0001d50a\\U0001d50d-\\U0001d514\\U0001d516-\\U0001d51c\\U0001d51e-\\U0001d539\\U0001d53b-\\U0001d53e\\U0001d540-\\U0001d544\\U0001d546\\U0001d54a-\\U0001d550\\U0001d552-\\U0001d6a5\\U0001d6a8-\\U0001d6c0\\U0001d6c2-\\U0001d6da\\U0001d6dc-\\U0001d6fa\\U0001d6fc-\\U0001d714\\U0001d716-\\U0001d734\\U0001d736-\\U0001d74e\\U0001d750-\\U0001d76e\\U0001d770-\\U0001d788\\U0001d78a-\\U0001d7a8\\U0001d7aa-\\U0001d7c2\\U0001d7c4-\\U0001d7cb\\U0001e800-\\U0001e8c4\\U0001e900-\\U0001e943\\U0001ee00-\\U0001ee03\\U0001ee05-\\U0001ee1f\\U0001ee21-\\U0001ee22\\U0001ee24\\U0001ee27\\U0001ee29-\\U0001ee32\\U0001ee34-\\U0001ee37\\U0001ee39\\U0001ee3b\\U0001ee42\\U0001ee47\\U0001ee49\\U0001ee4b\\U0001ee4d-\\U0001ee4f\\U0001ee51-\\U0001ee52\\U0001ee54\\U0001ee57\\U0001ee59\\U0001ee5b\\U0001ee5d\\U0001ee5f\\U0001ee61-\\U0001ee62\\U0001ee64\\U0001ee67-\\U0001ee6a\\U0001ee6c-\\U0001ee72\\U0001ee74-\\U0001ee77\\U0001ee79-\\U0001ee7c\\U0001ee7e\\U0001ee80-\\U0001ee89\\U0001ee8b-\\U0001ee9b\\U0001eea1-\\U0001eea3\\U0001eea5-\\U0001eea9\\U0001eeab-\\U0001eebb\\U00020000-\\U0002a6d6\\U0002a700-\\U0002b734\\U0002b740-\\U0002b81d\\U0002b820-\\U0002cea1\\U0002ceb0-\\U0002ebe0\\U0002f800-\\U0002fa1d'\n\ncats = ['Cc', 'Cf', 'Cn', 'Co', 'Cs', 'Ll', 'Lm', 'Lo', 'Lt', 'Lu', 'Mc', 'Me', 'Mn', 'Nd', 'Nl', 'No', 'Pc', 'Pd', 'Pe', 'Pf', 'Pi', 'Po', 'Ps', 'Sc', 'Sk', 'Sm', 'So', 'Zl', 'Zp', 'Zs']\n\n# Generated from unidata 11.0.0\n\ndef combine(*args):\n    return ''.join(globals()[cat] for cat in args)\n\n\ndef allexcept(*args):\n    newcats = cats[:]\n    for arg in args:\n        newcats.remove(arg)\n    return ''.join(globals()[cat] for cat in newcats)\n\n\ndef _handle_runs(char_list):  # pragma: no cover\n    buf = []\n    for c in char_list:\n        if len(c) == 1:\n            if buf and buf[-1][1] == chr(ord(c)-1):\n                buf[-1] = (buf[-1][0], c)\n            else:\n                buf.append((c, c))\n        else:\n            buf.append((c, c))\n    for a, b in buf:\n        if a == b:\n            yield a\n        else:\n            yield '%s-%s' % (a, b)\n\n\nif __name__ == '__main__':  # pragma: no cover\n    import unicodedata\n\n    categories = {'xid_start': [], 'xid_continue': []}\n\n    with open(__file__) as fp:\n        content = fp.read()\n\n    header = content[:content.find('Cc =')]\n    footer = content[content.find(\"def combine(\"):]\n\n    for code in range(0x110000):\n        c = chr(code)\n        cat = unicodedata.category(c)\n        if ord(c) == 0xdc00:\n            # Hack to avoid combining this combining with the preceding high\n            # surrogate, 0xdbff, when doing a repr.\n            c = '\\\\' + c\n        elif ord(c) in (0x2d, 0x5b, 0x5c, 0x5d, 0x5e):\n            # Escape regex metachars.\n            c = '\\\\' + c\n        categories.setdefault(cat, []).append(c)\n        # XID_START and XID_CONTINUE are special categories used for matching\n        # identifiers in Python 3.\n        if c.isidentifier():\n            categories['xid_start'].append(c)\n        if ('a' + c).isidentifier():\n            categories['xid_continue'].append(c)\n\n    with open(__file__, 'w') as fp:\n        fp.write(header)\n\n        for cat in sorted(categories):\n            val = ''.join(_handle_runs(categories[cat]))\n            fp.write('%s = %a\\n\\n' % (cat, val))\n\n        cats = sorted(categories)\n        cats.remove('xid_start')\n        cats.remove('xid_continue')\n        fp.write('cats = %r\\n\\n' % cats)\n\n        fp.write('# Generated from unidata %s\\n\\n' % (unicodedata.unidata_version,))\n\n        fp.write(footer)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pygments/util.py",
    "content": "\"\"\"\n    pygments.util\n    ~~~~~~~~~~~~~\n\n    Utility functions.\n\n    :copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.\n    :license: BSD, see LICENSE for details.\n\"\"\"\n\nimport re\nfrom io import TextIOWrapper\n\n\nsplit_path_re = re.compile(r'[/\\\\ ]')\ndoctype_lookup_re = re.compile(r'''\n    <!DOCTYPE\\s+(\n     [a-zA-Z_][a-zA-Z0-9]*\n     (?: \\s+      # optional in HTML5\n     [a-zA-Z_][a-zA-Z0-9]*\\s+\n     \"[^\"]*\")?\n     )\n     [^>]*>\n''', re.DOTALL | re.MULTILINE | re.VERBOSE)\ntag_re = re.compile(r'<(.+?)(\\s.*?)?>.*?</.+?>',\n                    re.IGNORECASE | re.DOTALL | re.MULTILINE)\nxml_decl_re = re.compile(r'\\s*<\\?xml[^>]*\\?>', re.I)\n\n\nclass ClassNotFound(ValueError):\n    \"\"\"Raised if one of the lookup functions didn't find a matching class.\"\"\"\n\n\nclass OptionError(Exception):\n    pass\n\n\ndef get_choice_opt(options, optname, allowed, default=None, normcase=False):\n    string = options.get(optname, default)\n    if normcase:\n        string = string.lower()\n    if string not in allowed:\n        raise OptionError('Value for option %s must be one of %s' %\n                          (optname, ', '.join(map(str, allowed))))\n    return string\n\n\ndef get_bool_opt(options, optname, default=None):\n    string = options.get(optname, default)\n    if isinstance(string, bool):\n        return string\n    elif isinstance(string, int):\n        return bool(string)\n    elif not isinstance(string, str):\n        raise OptionError('Invalid type %r for option %s; use '\n                          '1/0, yes/no, true/false, on/off' % (\n                              string, optname))\n    elif string.lower() in ('1', 'yes', 'true', 'on'):\n        return True\n    elif string.lower() in ('0', 'no', 'false', 'off'):\n        return False\n    else:\n        raise OptionError('Invalid value %r for option %s; use '\n                          '1/0, yes/no, true/false, on/off' % (\n                              string, optname))\n\n\ndef get_int_opt(options, optname, default=None):\n    string = options.get(optname, default)\n    try:\n        return int(string)\n    except TypeError:\n        raise OptionError('Invalid type %r for option %s; you '\n                          'must give an integer value' % (\n                              string, optname))\n    except ValueError:\n        raise OptionError('Invalid value %r for option %s; you '\n                          'must give an integer value' % (\n                              string, optname))\n\n\ndef get_list_opt(options, optname, default=None):\n    val = options.get(optname, default)\n    if isinstance(val, str):\n        return val.split()\n    elif isinstance(val, (list, tuple)):\n        return list(val)\n    else:\n        raise OptionError('Invalid type %r for option %s; you '\n                          'must give a list value' % (\n                              val, optname))\n\n\ndef docstring_headline(obj):\n    if not obj.__doc__:\n        return ''\n    res = []\n    for line in obj.__doc__.strip().splitlines():\n        if line.strip():\n            res.append(\" \" + line.strip())\n        else:\n            break\n    return ''.join(res).lstrip()\n\n\ndef make_analysator(f):\n    \"\"\"Return a static text analyser function that returns float values.\"\"\"\n    def text_analyse(text):\n        try:\n            rv = f(text)\n        except Exception:\n            return 0.0\n        if not rv:\n            return 0.0\n        try:\n            return min(1.0, max(0.0, float(rv)))\n        except (ValueError, TypeError):\n            return 0.0\n    text_analyse.__doc__ = f.__doc__\n    return staticmethod(text_analyse)\n\n\ndef shebang_matches(text, regex):\n    r\"\"\"Check if the given regular expression matches the last part of the\n    shebang if one exists.\n\n        >>> from pygments.util import shebang_matches\n        >>> shebang_matches('#!/usr/bin/env python', r'python(2\\.\\d)?')\n        True\n        >>> shebang_matches('#!/usr/bin/python2.4', r'python(2\\.\\d)?')\n        True\n        >>> shebang_matches('#!/usr/bin/python-ruby', r'python(2\\.\\d)?')\n        False\n        >>> shebang_matches('#!/usr/bin/python/ruby', r'python(2\\.\\d)?')\n        False\n        >>> shebang_matches('#!/usr/bin/startsomethingwith python',\n        ...                 r'python(2\\.\\d)?')\n        True\n\n    It also checks for common windows executable file extensions::\n\n        >>> shebang_matches('#!C:\\\\Python2.4\\\\Python.exe', r'python(2\\.\\d)?')\n        True\n\n    Parameters (``'-f'`` or ``'--foo'`` are ignored so ``'perl'`` does\n    the same as ``'perl -e'``)\n\n    Note that this method automatically searches the whole string (eg:\n    the regular expression is wrapped in ``'^$'``)\n    \"\"\"\n    index = text.find('\\n')\n    if index >= 0:\n        first_line = text[:index].lower()\n    else:\n        first_line = text.lower()\n    if first_line.startswith('#!'):\n        try:\n            found = [x for x in split_path_re.split(first_line[2:].strip())\n                     if x and not x.startswith('-')][-1]\n        except IndexError:\n            return False\n        regex = re.compile(r'^%s(\\.(exe|cmd|bat|bin))?$' % regex, re.IGNORECASE)\n        if regex.search(found) is not None:\n            return True\n    return False\n\n\ndef doctype_matches(text, regex):\n    \"\"\"Check if the doctype matches a regular expression (if present).\n\n    Note that this method only checks the first part of a DOCTYPE.\n    eg: 'html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"'\n    \"\"\"\n    m = doctype_lookup_re.search(text)\n    if m is None:\n        return False\n    doctype = m.group(1)\n    return re.compile(regex, re.I).match(doctype.strip()) is not None\n\n\ndef html_doctype_matches(text):\n    \"\"\"Check if the file looks like it has a html doctype.\"\"\"\n    return doctype_matches(text, r'html')\n\n\n_looks_like_xml_cache = {}\n\n\ndef looks_like_xml(text):\n    \"\"\"Check if a doctype exists or if we have some tags.\"\"\"\n    if xml_decl_re.match(text):\n        return True\n    key = hash(text)\n    try:\n        return _looks_like_xml_cache[key]\n    except KeyError:\n        m = doctype_lookup_re.search(text)\n        if m is not None:\n            return True\n        rv = tag_re.search(text[:1000]) is not None\n        _looks_like_xml_cache[key] = rv\n        return rv\n\n\ndef surrogatepair(c):\n    \"\"\"Given a unicode character code with length greater than 16 bits,\n    return the two 16 bit surrogate pair.\n    \"\"\"\n    # From example D28 of:\n    # http://www.unicode.org/book/ch03.pdf\n    return (0xd7c0 + (c >> 10), (0xdc00 + (c & 0x3ff)))\n\n\ndef format_lines(var_name, seq, raw=False, indent_level=0):\n    \"\"\"Formats a sequence of strings for output.\"\"\"\n    lines = []\n    base_indent = ' ' * indent_level * 4\n    inner_indent = ' ' * (indent_level + 1) * 4\n    lines.append(base_indent + var_name + ' = (')\n    if raw:\n        # These should be preformatted reprs of, say, tuples.\n        for i in seq:\n            lines.append(inner_indent + i + ',')\n    else:\n        for i in seq:\n            # Force use of single quotes\n            r = repr(i + '\"')\n            lines.append(inner_indent + r[:-2] + r[-1] + ',')\n    lines.append(base_indent + ')')\n    return '\\n'.join(lines)\n\n\ndef duplicates_removed(it, already_seen=()):\n    \"\"\"\n    Returns a list with duplicates removed from the iterable `it`.\n\n    Order is preserved.\n    \"\"\"\n    lst = []\n    seen = set()\n    for i in it:\n        if i in seen or i in already_seen:\n            continue\n        lst.append(i)\n        seen.add(i)\n    return lst\n\n\nclass Future:\n    \"\"\"Generic class to defer some work.\n\n    Handled specially in RegexLexerMeta, to support regex string construction at\n    first use.\n    \"\"\"\n    def get(self):\n        raise NotImplementedError\n\n\ndef guess_decode(text):\n    \"\"\"Decode *text* with guessed encoding.\n\n    First try UTF-8; this should fail for non-UTF-8 encodings.\n    Then try the preferred locale encoding.\n    Fall back to latin-1, which always works.\n    \"\"\"\n    try:\n        text = text.decode('utf-8')\n        return text, 'utf-8'\n    except UnicodeDecodeError:\n        try:\n            import locale\n            prefencoding = locale.getpreferredencoding()\n            text = text.decode()\n            return text, prefencoding\n        except (UnicodeDecodeError, LookupError):\n            text = text.decode('latin1')\n            return text, 'latin1'\n\n\ndef guess_decode_from_terminal(text, term):\n    \"\"\"Decode *text* coming from terminal *term*.\n\n    First try the terminal encoding, if given.\n    Then try UTF-8.  Then try the preferred locale encoding.\n    Fall back to latin-1, which always works.\n    \"\"\"\n    if getattr(term, 'encoding', None):\n        try:\n            text = text.decode(term.encoding)\n        except UnicodeDecodeError:\n            pass\n        else:\n            return text, term.encoding\n    return guess_decode(text)\n\n\ndef terminal_encoding(term):\n    \"\"\"Return our best guess of encoding for the given *term*.\"\"\"\n    if getattr(term, 'encoding', None):\n        return term.encoding\n    import locale\n    return locale.getpreferredencoding()\n\n\nclass UnclosingTextIOWrapper(TextIOWrapper):\n    # Don't close underlying buffer on destruction.\n    def close(self):\n        self.flush()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pyparsing/__init__.py",
    "content": "# module pyparsing.py\n#\n# Copyright (c) 2003-2022  Paul T. McGuire\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n\n__doc__ = \"\"\"\npyparsing module - Classes and methods to define and execute parsing grammars\n=============================================================================\n\nThe pyparsing module is an alternative approach to creating and\nexecuting simple grammars, vs. the traditional lex/yacc approach, or the\nuse of regular expressions.  With pyparsing, you don't need to learn\na new syntax for defining grammars or matching expressions - the parsing\nmodule provides a library of classes that you use to construct the\ngrammar directly in Python.\n\nHere is a program to parse \"Hello, World!\" (or any greeting of the form\n``\"<salutation>, <addressee>!\"``), built up using :class:`Word`,\n:class:`Literal`, and :class:`And` elements\n(the :meth:`'+'<ParserElement.__add__>` operators create :class:`And` expressions,\nand the strings are auto-converted to :class:`Literal` expressions)::\n\n    from pip._vendor.pyparsing import Word, alphas\n\n    # define grammar of a greeting\n    greet = Word(alphas) + \",\" + Word(alphas) + \"!\"\n\n    hello = \"Hello, World!\"\n    print(hello, \"->\", greet.parse_string(hello))\n\nThe program outputs the following::\n\n    Hello, World! -> ['Hello', ',', 'World', '!']\n\nThe Python representation of the grammar is quite readable, owing to the\nself-explanatory class names, and the use of :class:`'+'<And>`,\n:class:`'|'<MatchFirst>`, :class:`'^'<Or>` and :class:`'&'<Each>` operators.\n\nThe :class:`ParseResults` object returned from\n:class:`ParserElement.parseString` can be\naccessed as a nested list, a dictionary, or an object with named\nattributes.\n\nThe pyparsing module handles some of the problems that are typically\nvexing when writing text parsers:\n\n  - extra or missing whitespace (the above program will also handle\n    \"Hello,World!\", \"Hello  ,  World  !\", etc.)\n  - quoted strings\n  - embedded comments\n\n\nGetting Started -\n-----------------\nVisit the classes :class:`ParserElement` and :class:`ParseResults` to\nsee the base classes that most other pyparsing\nclasses inherit from. Use the docstrings for examples of how to:\n\n - construct literal match expressions from :class:`Literal` and\n   :class:`CaselessLiteral` classes\n - construct character word-group expressions using the :class:`Word`\n   class\n - see how to create repetitive expressions using :class:`ZeroOrMore`\n   and :class:`OneOrMore` classes\n - use :class:`'+'<And>`, :class:`'|'<MatchFirst>`, :class:`'^'<Or>`,\n   and :class:`'&'<Each>` operators to combine simple expressions into\n   more complex ones\n - associate names with your parsed results using\n   :class:`ParserElement.setResultsName`\n - access the parsed data, which is returned as a :class:`ParseResults`\n   object\n - find some helpful expression short-cuts like :class:`delimitedList`\n   and :class:`oneOf`\n - find more useful common expressions in the :class:`pyparsing_common`\n   namespace class\n\"\"\"\nfrom typing import NamedTuple\n\n\nclass version_info(NamedTuple):\n    major: int\n    minor: int\n    micro: int\n    releaselevel: str\n    serial: int\n\n    @property\n    def __version__(self):\n        return (\n            \"{}.{}.{}\".format(self.major, self.minor, self.micro)\n            + (\n                \"{}{}{}\".format(\n                    \"r\" if self.releaselevel[0] == \"c\" else \"\",\n                    self.releaselevel[0],\n                    self.serial,\n                ),\n                \"\",\n            )[self.releaselevel == \"final\"]\n        )\n\n    def __str__(self):\n        return \"{} {} / {}\".format(__name__, self.__version__, __version_time__)\n\n    def __repr__(self):\n        return \"{}.{}({})\".format(\n            __name__,\n            type(self).__name__,\n            \", \".join(\"{}={!r}\".format(*nv) for nv in zip(self._fields, self)),\n        )\n\n\n__version_info__ = version_info(3, 0, 9, \"final\", 0)\n__version_time__ = \"05 May 2022 07:02 UTC\"\n__version__ = __version_info__.__version__\n__versionTime__ = __version_time__\n__author__ = \"Paul McGuire <ptmcg.gm+pyparsing@gmail.com>\"\n\nfrom .util import *\nfrom .exceptions import *\nfrom .actions import *\nfrom .core import __diag__, __compat__\nfrom .results import *\nfrom .core import *\nfrom .core import _builtin_exprs as core_builtin_exprs\nfrom .helpers import *\nfrom .helpers import _builtin_exprs as helper_builtin_exprs\n\nfrom .unicode import unicode_set, UnicodeRangeList, pyparsing_unicode as unicode\nfrom .testing import pyparsing_test as testing\nfrom .common import (\n    pyparsing_common as common,\n    _builtin_exprs as common_builtin_exprs,\n)\n\n# define backward compat synonyms\nif \"pyparsing_unicode\" not in globals():\n    pyparsing_unicode = unicode\nif \"pyparsing_common\" not in globals():\n    pyparsing_common = common\nif \"pyparsing_test\" not in globals():\n    pyparsing_test = testing\n\ncore_builtin_exprs += common_builtin_exprs + helper_builtin_exprs\n\n\n__all__ = [\n    \"__version__\",\n    \"__version_time__\",\n    \"__author__\",\n    \"__compat__\",\n    \"__diag__\",\n    \"And\",\n    \"AtLineStart\",\n    \"AtStringStart\",\n    \"CaselessKeyword\",\n    \"CaselessLiteral\",\n    \"CharsNotIn\",\n    \"Combine\",\n    \"Dict\",\n    \"Each\",\n    \"Empty\",\n    \"FollowedBy\",\n    \"Forward\",\n    \"GoToColumn\",\n    \"Group\",\n    \"IndentedBlock\",\n    \"Keyword\",\n    \"LineEnd\",\n    \"LineStart\",\n    \"Literal\",\n    \"Located\",\n    \"PrecededBy\",\n    \"MatchFirst\",\n    \"NoMatch\",\n    \"NotAny\",\n    \"OneOrMore\",\n    \"OnlyOnce\",\n    \"OpAssoc\",\n    \"Opt\",\n    \"Optional\",\n    \"Or\",\n    \"ParseBaseException\",\n    \"ParseElementEnhance\",\n    \"ParseException\",\n    \"ParseExpression\",\n    \"ParseFatalException\",\n    \"ParseResults\",\n    \"ParseSyntaxException\",\n    \"ParserElement\",\n    \"PositionToken\",\n    \"QuotedString\",\n    \"RecursiveGrammarException\",\n    \"Regex\",\n    \"SkipTo\",\n    \"StringEnd\",\n    \"StringStart\",\n    \"Suppress\",\n    \"Token\",\n    \"TokenConverter\",\n    \"White\",\n    \"Word\",\n    \"WordEnd\",\n    \"WordStart\",\n    \"ZeroOrMore\",\n    \"Char\",\n    \"alphanums\",\n    \"alphas\",\n    \"alphas8bit\",\n    \"any_close_tag\",\n    \"any_open_tag\",\n    \"c_style_comment\",\n    \"col\",\n    \"common_html_entity\",\n    \"counted_array\",\n    \"cpp_style_comment\",\n    \"dbl_quoted_string\",\n    \"dbl_slash_comment\",\n    \"delimited_list\",\n    \"dict_of\",\n    \"empty\",\n    \"hexnums\",\n    \"html_comment\",\n    \"identchars\",\n    \"identbodychars\",\n    \"java_style_comment\",\n    \"line\",\n    \"line_end\",\n    \"line_start\",\n    \"lineno\",\n    \"make_html_tags\",\n    \"make_xml_tags\",\n    \"match_only_at_col\",\n    \"match_previous_expr\",\n    \"match_previous_literal\",\n    \"nested_expr\",\n    \"null_debug_action\",\n    \"nums\",\n    \"one_of\",\n    \"printables\",\n    \"punc8bit\",\n    \"python_style_comment\",\n    \"quoted_string\",\n    \"remove_quotes\",\n    \"replace_with\",\n    \"replace_html_entity\",\n    \"rest_of_line\",\n    \"sgl_quoted_string\",\n    \"srange\",\n    \"string_end\",\n    \"string_start\",\n    \"trace_parse_action\",\n    \"unicode_string\",\n    \"with_attribute\",\n    \"indentedBlock\",\n    \"original_text_for\",\n    \"ungroup\",\n    \"infix_notation\",\n    \"locatedExpr\",\n    \"with_class\",\n    \"CloseMatch\",\n    \"token_map\",\n    \"pyparsing_common\",\n    \"pyparsing_unicode\",\n    \"unicode_set\",\n    \"condition_as_parse_action\",\n    \"pyparsing_test\",\n    # pre-PEP8 compatibility names\n    \"__versionTime__\",\n    \"anyCloseTag\",\n    \"anyOpenTag\",\n    \"cStyleComment\",\n    \"commonHTMLEntity\",\n    \"countedArray\",\n    \"cppStyleComment\",\n    \"dblQuotedString\",\n    \"dblSlashComment\",\n    \"delimitedList\",\n    \"dictOf\",\n    \"htmlComment\",\n    \"javaStyleComment\",\n    \"lineEnd\",\n    \"lineStart\",\n    \"makeHTMLTags\",\n    \"makeXMLTags\",\n    \"matchOnlyAtCol\",\n    \"matchPreviousExpr\",\n    \"matchPreviousLiteral\",\n    \"nestedExpr\",\n    \"nullDebugAction\",\n    \"oneOf\",\n    \"opAssoc\",\n    \"pythonStyleComment\",\n    \"quotedString\",\n    \"removeQuotes\",\n    \"replaceHTMLEntity\",\n    \"replaceWith\",\n    \"restOfLine\",\n    \"sglQuotedString\",\n    \"stringEnd\",\n    \"stringStart\",\n    \"traceParseAction\",\n    \"unicodeString\",\n    \"withAttribute\",\n    \"indentedBlock\",\n    \"originalTextFor\",\n    \"infixNotation\",\n    \"locatedExpr\",\n    \"withClass\",\n    \"tokenMap\",\n    \"conditionAsParseAction\",\n    \"autoname_elements\",\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pyparsing/actions.py",
    "content": "# actions.py\n\nfrom .exceptions import ParseException\nfrom .util import col\n\n\nclass OnlyOnce:\n    \"\"\"\n    Wrapper for parse actions, to ensure they are only called once.\n    \"\"\"\n\n    def __init__(self, method_call):\n        from .core import _trim_arity\n\n        self.callable = _trim_arity(method_call)\n        self.called = False\n\n    def __call__(self, s, l, t):\n        if not self.called:\n            results = self.callable(s, l, t)\n            self.called = True\n            return results\n        raise ParseException(s, l, \"OnlyOnce obj called multiple times w/out reset\")\n\n    def reset(self):\n        \"\"\"\n        Allow the associated parse action to be called once more.\n        \"\"\"\n\n        self.called = False\n\n\ndef match_only_at_col(n):\n    \"\"\"\n    Helper method for defining parse actions that require matching at\n    a specific column in the input text.\n    \"\"\"\n\n    def verify_col(strg, locn, toks):\n        if col(locn, strg) != n:\n            raise ParseException(strg, locn, \"matched token not at column {}\".format(n))\n\n    return verify_col\n\n\ndef replace_with(repl_str):\n    \"\"\"\n    Helper method for common parse actions that simply return\n    a literal value.  Especially useful when used with\n    :class:`transform_string<ParserElement.transform_string>` ().\n\n    Example::\n\n        num = Word(nums).set_parse_action(lambda toks: int(toks[0]))\n        na = one_of(\"N/A NA\").set_parse_action(replace_with(math.nan))\n        term = na | num\n\n        term[1, ...].parse_string(\"324 234 N/A 234\") # -> [324, 234, nan, 234]\n    \"\"\"\n    return lambda s, l, t: [repl_str]\n\n\ndef remove_quotes(s, l, t):\n    \"\"\"\n    Helper parse action for removing quotation marks from parsed\n    quoted strings.\n\n    Example::\n\n        # by default, quotation marks are included in parsed results\n        quoted_string.parse_string(\"'Now is the Winter of our Discontent'\") # -> [\"'Now is the Winter of our Discontent'\"]\n\n        # use remove_quotes to strip quotation marks from parsed results\n        quoted_string.set_parse_action(remove_quotes)\n        quoted_string.parse_string(\"'Now is the Winter of our Discontent'\") # -> [\"Now is the Winter of our Discontent\"]\n    \"\"\"\n    return t[0][1:-1]\n\n\ndef with_attribute(*args, **attr_dict):\n    \"\"\"\n    Helper to create a validating parse action to be used with start\n    tags created with :class:`make_xml_tags` or\n    :class:`make_html_tags`. Use ``with_attribute`` to qualify\n    a starting tag with a required attribute value, to avoid false\n    matches on common tags such as ``<TD>`` or ``<DIV>``.\n\n    Call ``with_attribute`` with a series of attribute names and\n    values. Specify the list of filter attributes names and values as:\n\n    - keyword arguments, as in ``(align=\"right\")``, or\n    - as an explicit dict with ``**`` operator, when an attribute\n      name is also a Python reserved word, as in ``**{\"class\":\"Customer\", \"align\":\"right\"}``\n    - a list of name-value tuples, as in ``((\"ns1:class\", \"Customer\"), (\"ns2:align\", \"right\"))``\n\n    For attribute names with a namespace prefix, you must use the second\n    form.  Attribute names are matched insensitive to upper/lower case.\n\n    If just testing for ``class`` (with or without a namespace), use\n    :class:`with_class`.\n\n    To verify that the attribute exists, but without specifying a value,\n    pass ``with_attribute.ANY_VALUE`` as the value.\n\n    Example::\n\n        html = '''\n            <div>\n            Some text\n            <div type=\"grid\">1 4 0 1 0</div>\n            <div type=\"graph\">1,3 2,3 1,1</div>\n            <div>this has no type</div>\n            </div>\n\n        '''\n        div,div_end = make_html_tags(\"div\")\n\n        # only match div tag having a type attribute with value \"grid\"\n        div_grid = div().set_parse_action(with_attribute(type=\"grid\"))\n        grid_expr = div_grid + SkipTo(div | div_end)(\"body\")\n        for grid_header in grid_expr.search_string(html):\n            print(grid_header.body)\n\n        # construct a match with any div tag having a type attribute, regardless of the value\n        div_any_type = div().set_parse_action(with_attribute(type=with_attribute.ANY_VALUE))\n        div_expr = div_any_type + SkipTo(div | div_end)(\"body\")\n        for div_header in div_expr.search_string(html):\n            print(div_header.body)\n\n    prints::\n\n        1 4 0 1 0\n\n        1 4 0 1 0\n        1,3 2,3 1,1\n    \"\"\"\n    if args:\n        attrs = args[:]\n    else:\n        attrs = attr_dict.items()\n    attrs = [(k, v) for k, v in attrs]\n\n    def pa(s, l, tokens):\n        for attrName, attrValue in attrs:\n            if attrName not in tokens:\n                raise ParseException(s, l, \"no matching attribute \" + attrName)\n            if attrValue != with_attribute.ANY_VALUE and tokens[attrName] != attrValue:\n                raise ParseException(\n                    s,\n                    l,\n                    \"attribute {!r} has value {!r}, must be {!r}\".format(\n                        attrName, tokens[attrName], attrValue\n                    ),\n                )\n\n    return pa\n\n\nwith_attribute.ANY_VALUE = object()\n\n\ndef with_class(classname, namespace=\"\"):\n    \"\"\"\n    Simplified version of :class:`with_attribute` when\n    matching on a div class - made difficult because ``class`` is\n    a reserved word in Python.\n\n    Example::\n\n        html = '''\n            <div>\n            Some text\n            <div class=\"grid\">1 4 0 1 0</div>\n            <div class=\"graph\">1,3 2,3 1,1</div>\n            <div>this &lt;div&gt; has no class</div>\n            </div>\n\n        '''\n        div,div_end = make_html_tags(\"div\")\n        div_grid = div().set_parse_action(with_class(\"grid\"))\n\n        grid_expr = div_grid + SkipTo(div | div_end)(\"body\")\n        for grid_header in grid_expr.search_string(html):\n            print(grid_header.body)\n\n        div_any_type = div().set_parse_action(with_class(withAttribute.ANY_VALUE))\n        div_expr = div_any_type + SkipTo(div | div_end)(\"body\")\n        for div_header in div_expr.search_string(html):\n            print(div_header.body)\n\n    prints::\n\n        1 4 0 1 0\n\n        1 4 0 1 0\n        1,3 2,3 1,1\n    \"\"\"\n    classattr = \"{}:class\".format(namespace) if namespace else \"class\"\n    return with_attribute(**{classattr: classname})\n\n\n# pre-PEP8 compatibility symbols\nreplaceWith = replace_with\nremoveQuotes = remove_quotes\nwithAttribute = with_attribute\nwithClass = with_class\nmatchOnlyAtCol = match_only_at_col\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pyparsing/common.py",
    "content": "# common.py\nfrom .core import *\nfrom .helpers import delimited_list, any_open_tag, any_close_tag\nfrom datetime import datetime\n\n\n# some other useful expressions - using lower-case class name since we are really using this as a namespace\nclass pyparsing_common:\n    \"\"\"Here are some common low-level expressions that may be useful in\n    jump-starting parser development:\n\n    - numeric forms (:class:`integers<integer>`, :class:`reals<real>`,\n      :class:`scientific notation<sci_real>`)\n    - common :class:`programming identifiers<identifier>`\n    - network addresses (:class:`MAC<mac_address>`,\n      :class:`IPv4<ipv4_address>`, :class:`IPv6<ipv6_address>`)\n    - ISO8601 :class:`dates<iso8601_date>` and\n      :class:`datetime<iso8601_datetime>`\n    - :class:`UUID<uuid>`\n    - :class:`comma-separated list<comma_separated_list>`\n    - :class:`url`\n\n    Parse actions:\n\n    - :class:`convertToInteger`\n    - :class:`convertToFloat`\n    - :class:`convertToDate`\n    - :class:`convertToDatetime`\n    - :class:`stripHTMLTags`\n    - :class:`upcaseTokens`\n    - :class:`downcaseTokens`\n\n    Example::\n\n        pyparsing_common.number.runTests('''\n            # any int or real number, returned as the appropriate type\n            100\n            -100\n            +100\n            3.14159\n            6.02e23\n            1e-12\n            ''')\n\n        pyparsing_common.fnumber.runTests('''\n            # any int or real number, returned as float\n            100\n            -100\n            +100\n            3.14159\n            6.02e23\n            1e-12\n            ''')\n\n        pyparsing_common.hex_integer.runTests('''\n            # hex numbers\n            100\n            FF\n            ''')\n\n        pyparsing_common.fraction.runTests('''\n            # fractions\n            1/2\n            -3/4\n            ''')\n\n        pyparsing_common.mixed_integer.runTests('''\n            # mixed fractions\n            1\n            1/2\n            -3/4\n            1-3/4\n            ''')\n\n        import uuid\n        pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID))\n        pyparsing_common.uuid.runTests('''\n            # uuid\n            12345678-1234-5678-1234-567812345678\n            ''')\n\n    prints::\n\n        # any int or real number, returned as the appropriate type\n        100\n        [100]\n\n        -100\n        [-100]\n\n        +100\n        [100]\n\n        3.14159\n        [3.14159]\n\n        6.02e23\n        [6.02e+23]\n\n        1e-12\n        [1e-12]\n\n        # any int or real number, returned as float\n        100\n        [100.0]\n\n        -100\n        [-100.0]\n\n        +100\n        [100.0]\n\n        3.14159\n        [3.14159]\n\n        6.02e23\n        [6.02e+23]\n\n        1e-12\n        [1e-12]\n\n        # hex numbers\n        100\n        [256]\n\n        FF\n        [255]\n\n        # fractions\n        1/2\n        [0.5]\n\n        -3/4\n        [-0.75]\n\n        # mixed fractions\n        1\n        [1]\n\n        1/2\n        [0.5]\n\n        -3/4\n        [-0.75]\n\n        1-3/4\n        [1.75]\n\n        # uuid\n        12345678-1234-5678-1234-567812345678\n        [UUID('12345678-1234-5678-1234-567812345678')]\n    \"\"\"\n\n    convert_to_integer = token_map(int)\n    \"\"\"\n    Parse action for converting parsed integers to Python int\n    \"\"\"\n\n    convert_to_float = token_map(float)\n    \"\"\"\n    Parse action for converting parsed numbers to Python float\n    \"\"\"\n\n    integer = Word(nums).set_name(\"integer\").set_parse_action(convert_to_integer)\n    \"\"\"expression that parses an unsigned integer, returns an int\"\"\"\n\n    hex_integer = (\n        Word(hexnums).set_name(\"hex integer\").set_parse_action(token_map(int, 16))\n    )\n    \"\"\"expression that parses a hexadecimal integer, returns an int\"\"\"\n\n    signed_integer = (\n        Regex(r\"[+-]?\\d+\")\n        .set_name(\"signed integer\")\n        .set_parse_action(convert_to_integer)\n    )\n    \"\"\"expression that parses an integer with optional leading sign, returns an int\"\"\"\n\n    fraction = (\n        signed_integer().set_parse_action(convert_to_float)\n        + \"/\"\n        + signed_integer().set_parse_action(convert_to_float)\n    ).set_name(\"fraction\")\n    \"\"\"fractional expression of an integer divided by an integer, returns a float\"\"\"\n    fraction.add_parse_action(lambda tt: tt[0] / tt[-1])\n\n    mixed_integer = (\n        fraction | signed_integer + Opt(Opt(\"-\").suppress() + fraction)\n    ).set_name(\"fraction or mixed integer-fraction\")\n    \"\"\"mixed integer of the form 'integer - fraction', with optional leading integer, returns float\"\"\"\n    mixed_integer.add_parse_action(sum)\n\n    real = (\n        Regex(r\"[+-]?(?:\\d+\\.\\d*|\\.\\d+)\")\n        .set_name(\"real number\")\n        .set_parse_action(convert_to_float)\n    )\n    \"\"\"expression that parses a floating point number and returns a float\"\"\"\n\n    sci_real = (\n        Regex(r\"[+-]?(?:\\d+(?:[eE][+-]?\\d+)|(?:\\d+\\.\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?)\")\n        .set_name(\"real number with scientific notation\")\n        .set_parse_action(convert_to_float)\n    )\n    \"\"\"expression that parses a floating point number with optional\n    scientific notation and returns a float\"\"\"\n\n    # streamlining this expression makes the docs nicer-looking\n    number = (sci_real | real | signed_integer).setName(\"number\").streamline()\n    \"\"\"any numeric expression, returns the corresponding Python type\"\"\"\n\n    fnumber = (\n        Regex(r\"[+-]?\\d+\\.?\\d*([eE][+-]?\\d+)?\")\n        .set_name(\"fnumber\")\n        .set_parse_action(convert_to_float)\n    )\n    \"\"\"any int or real number, returned as float\"\"\"\n\n    identifier = Word(identchars, identbodychars).set_name(\"identifier\")\n    \"\"\"typical code identifier (leading alpha or '_', followed by 0 or more alphas, nums, or '_')\"\"\"\n\n    ipv4_address = Regex(\n        r\"(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}\"\n    ).set_name(\"IPv4 address\")\n    \"IPv4 address (``0.0.0.0 - 255.255.255.255``)\"\n\n    _ipv6_part = Regex(r\"[0-9a-fA-F]{1,4}\").set_name(\"hex_integer\")\n    _full_ipv6_address = (_ipv6_part + (\":\" + _ipv6_part) * 7).set_name(\n        \"full IPv6 address\"\n    )\n    _short_ipv6_address = (\n        Opt(_ipv6_part + (\":\" + _ipv6_part) * (0, 6))\n        + \"::\"\n        + Opt(_ipv6_part + (\":\" + _ipv6_part) * (0, 6))\n    ).set_name(\"short IPv6 address\")\n    _short_ipv6_address.add_condition(\n        lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8\n    )\n    _mixed_ipv6_address = (\"::ffff:\" + ipv4_address).set_name(\"mixed IPv6 address\")\n    ipv6_address = Combine(\n        (_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).set_name(\n            \"IPv6 address\"\n        )\n    ).set_name(\"IPv6 address\")\n    \"IPv6 address (long, short, or mixed form)\"\n\n    mac_address = Regex(\n        r\"[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\\1[0-9a-fA-F]{2}){4}\"\n    ).set_name(\"MAC address\")\n    \"MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)\"\n\n    @staticmethod\n    def convert_to_date(fmt: str = \"%Y-%m-%d\"):\n        \"\"\"\n        Helper to create a parse action for converting parsed date string to Python datetime.date\n\n        Params -\n        - fmt - format to be passed to datetime.strptime (default= ``\"%Y-%m-%d\"``)\n\n        Example::\n\n            date_expr = pyparsing_common.iso8601_date.copy()\n            date_expr.setParseAction(pyparsing_common.convertToDate())\n            print(date_expr.parseString(\"1999-12-31\"))\n\n        prints::\n\n            [datetime.date(1999, 12, 31)]\n        \"\"\"\n\n        def cvt_fn(ss, ll, tt):\n            try:\n                return datetime.strptime(tt[0], fmt).date()\n            except ValueError as ve:\n                raise ParseException(ss, ll, str(ve))\n\n        return cvt_fn\n\n    @staticmethod\n    def convert_to_datetime(fmt: str = \"%Y-%m-%dT%H:%M:%S.%f\"):\n        \"\"\"Helper to create a parse action for converting parsed\n        datetime string to Python datetime.datetime\n\n        Params -\n        - fmt - format to be passed to datetime.strptime (default= ``\"%Y-%m-%dT%H:%M:%S.%f\"``)\n\n        Example::\n\n            dt_expr = pyparsing_common.iso8601_datetime.copy()\n            dt_expr.setParseAction(pyparsing_common.convertToDatetime())\n            print(dt_expr.parseString(\"1999-12-31T23:59:59.999\"))\n\n        prints::\n\n            [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]\n        \"\"\"\n\n        def cvt_fn(s, l, t):\n            try:\n                return datetime.strptime(t[0], fmt)\n            except ValueError as ve:\n                raise ParseException(s, l, str(ve))\n\n        return cvt_fn\n\n    iso8601_date = Regex(\n        r\"(?P<year>\\d{4})(?:-(?P<month>\\d\\d)(?:-(?P<day>\\d\\d))?)?\"\n    ).set_name(\"ISO8601 date\")\n    \"ISO8601 date (``yyyy-mm-dd``)\"\n\n    iso8601_datetime = Regex(\n        r\"(?P<year>\\d{4})-(?P<month>\\d\\d)-(?P<day>\\d\\d)[T ](?P<hour>\\d\\d):(?P<minute>\\d\\d)(:(?P<second>\\d\\d(\\.\\d*)?)?)?(?P<tz>Z|[+-]\\d\\d:?\\d\\d)?\"\n    ).set_name(\"ISO8601 datetime\")\n    \"ISO8601 datetime (``yyyy-mm-ddThh:mm:ss.s(Z|+-00:00)``) - trailing seconds, milliseconds, and timezone optional; accepts separating ``'T'`` or ``' '``\"\n\n    uuid = Regex(r\"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}\").set_name(\"UUID\")\n    \"UUID (``xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx``)\"\n\n    _html_stripper = any_open_tag.suppress() | any_close_tag.suppress()\n\n    @staticmethod\n    def strip_html_tags(s: str, l: int, tokens: ParseResults):\n        \"\"\"Parse action to remove HTML tags from web page HTML source\n\n        Example::\n\n            # strip HTML links from normal text\n            text = '<td>More info at the <a href=\"https://github.com/pyparsing/pyparsing/wiki\">pyparsing</a> wiki page</td>'\n            td, td_end = makeHTMLTags(\"TD\")\n            table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)(\"body\") + td_end\n            print(table_text.parseString(text).body)\n\n        Prints::\n\n            More info at the pyparsing wiki page\n        \"\"\"\n        return pyparsing_common._html_stripper.transform_string(tokens[0])\n\n    _commasepitem = (\n        Combine(\n            OneOrMore(\n                ~Literal(\",\")\n                + ~LineEnd()\n                + Word(printables, exclude_chars=\",\")\n                + Opt(White(\" \\t\") + ~FollowedBy(LineEnd() | \",\"))\n            )\n        )\n        .streamline()\n        .set_name(\"commaItem\")\n    )\n    comma_separated_list = delimited_list(\n        Opt(quoted_string.copy() | _commasepitem, default=\"\")\n    ).set_name(\"comma separated list\")\n    \"\"\"Predefined expression of 1 or more printable words or quoted strings, separated by commas.\"\"\"\n\n    upcase_tokens = staticmethod(token_map(lambda t: t.upper()))\n    \"\"\"Parse action to convert tokens to upper case.\"\"\"\n\n    downcase_tokens = staticmethod(token_map(lambda t: t.lower()))\n    \"\"\"Parse action to convert tokens to lower case.\"\"\"\n\n    # fmt: off\n    url = Regex(\n        # https://mathiasbynens.be/demo/url-regex\n        # https://gist.github.com/dperini/729294\n        r\"^\" +\n        # protocol identifier (optional)\n        # short syntax // still required\n        r\"(?:(?:(?P<scheme>https?|ftp):)?\\/\\/)\" +\n        # user:pass BasicAuth (optional)\n        r\"(?:(?P<auth>\\S+(?::\\S*)?)@)?\" +\n        r\"(?P<host>\" +\n        # IP address exclusion\n        # private & local networks\n        r\"(?!(?:10|127)(?:\\.\\d{1,3}){3})\" +\n        r\"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})\" +\n        r\"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})\" +\n        # IP address dotted notation octets\n        # excludes loopback network 0.0.0.0\n        # excludes reserved space >= 224.0.0.0\n        # excludes network & broadcast addresses\n        # (first & last IP address of each class)\n        r\"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])\" +\n        r\"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}\" +\n        r\"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))\" +\n        r\"|\" +\n        # host & domain names, may end with dot\n        # can be replaced by a shortest alternative\n        # (?![-_])(?:[-\\w\\u00a1-\\uffff]{0,63}[^-_]\\.)+\n        r\"(?:\" +\n        r\"(?:\" +\n        r\"[a-z0-9\\u00a1-\\uffff]\" +\n        r\"[a-z0-9\\u00a1-\\uffff_-]{0,62}\" +\n        r\")?\" +\n        r\"[a-z0-9\\u00a1-\\uffff]\\.\" +\n        r\")+\" +\n        # TLD identifier name, may end with dot\n        r\"(?:[a-z\\u00a1-\\uffff]{2,}\\.?)\" +\n        r\")\" +\n        # port number (optional)\n        r\"(:(?P<port>\\d{2,5}))?\" +\n        # resource path (optional)\n        r\"(?P<path>\\/[^?# ]*)?\" +\n        # query string (optional)\n        r\"(\\?(?P<query>[^#]*))?\" +\n        # fragment (optional)\n        r\"(#(?P<fragment>\\S*))?\" +\n        r\"$\"\n    ).set_name(\"url\")\n    # fmt: on\n\n    # pre-PEP8 compatibility names\n    convertToInteger = convert_to_integer\n    convertToFloat = convert_to_float\n    convertToDate = convert_to_date\n    convertToDatetime = convert_to_datetime\n    stripHTMLTags = strip_html_tags\n    upcaseTokens = upcase_tokens\n    downcaseTokens = downcase_tokens\n\n\n_builtin_exprs = [\n    v for v in vars(pyparsing_common).values() if isinstance(v, ParserElement)\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pyparsing/core.py",
    "content": "#\n# core.py\n#\nimport os\nimport typing\nfrom typing import (\n    NamedTuple,\n    Union,\n    Callable,\n    Any,\n    Generator,\n    Tuple,\n    List,\n    TextIO,\n    Set,\n    Sequence,\n)\nfrom abc import ABC, abstractmethod\nfrom enum import Enum\nimport string\nimport copy\nimport warnings\nimport re\nimport sys\nfrom collections.abc import Iterable\nimport traceback\nimport types\nfrom operator import itemgetter\nfrom functools import wraps\nfrom threading import RLock\nfrom pathlib import Path\n\nfrom .util import (\n    _FifoCache,\n    _UnboundedCache,\n    __config_flags,\n    _collapse_string_to_ranges,\n    _escape_regex_range_chars,\n    _bslash,\n    _flatten,\n    LRUMemo as _LRUMemo,\n    UnboundedMemo as _UnboundedMemo,\n)\nfrom .exceptions import *\nfrom .actions import *\nfrom .results import ParseResults, _ParseResultsWithOffset\nfrom .unicode import pyparsing_unicode\n\n_MAX_INT = sys.maxsize\nstr_type: Tuple[type, ...] = (str, bytes)\n\n#\n# Copyright (c) 2003-2022  Paul T. McGuire\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n\n\nif sys.version_info >= (3, 8):\n    from functools import cached_property\nelse:\n\n    class cached_property:\n        def __init__(self, func):\n            self._func = func\n\n        def __get__(self, instance, owner=None):\n            ret = instance.__dict__[self._func.__name__] = self._func(instance)\n            return ret\n\n\nclass __compat__(__config_flags):\n    \"\"\"\n    A cross-version compatibility configuration for pyparsing features that will be\n    released in a future version. By setting values in this configuration to True,\n    those features can be enabled in prior versions for compatibility development\n    and testing.\n\n    - ``collect_all_And_tokens`` - flag to enable fix for Issue #63 that fixes erroneous grouping\n      of results names when an :class:`And` expression is nested within an :class:`Or` or :class:`MatchFirst`;\n      maintained for compatibility, but setting to ``False`` no longer restores pre-2.3.1\n      behavior\n    \"\"\"\n\n    _type_desc = \"compatibility\"\n\n    collect_all_And_tokens = True\n\n    _all_names = [__ for __ in locals() if not __.startswith(\"_\")]\n    _fixed_names = \"\"\"\n        collect_all_And_tokens\n        \"\"\".split()\n\n\nclass __diag__(__config_flags):\n    _type_desc = \"diagnostic\"\n\n    warn_multiple_tokens_in_named_alternation = False\n    warn_ungrouped_named_tokens_in_collection = False\n    warn_name_set_on_empty_Forward = False\n    warn_on_parse_using_empty_Forward = False\n    warn_on_assignment_to_Forward = False\n    warn_on_multiple_string_args_to_oneof = False\n    warn_on_match_first_with_lshift_operator = False\n    enable_debug_on_named_expressions = False\n\n    _all_names = [__ for __ in locals() if not __.startswith(\"_\")]\n    _warning_names = [name for name in _all_names if name.startswith(\"warn\")]\n    _debug_names = [name for name in _all_names if name.startswith(\"enable_debug\")]\n\n    @classmethod\n    def enable_all_warnings(cls) -> None:\n        for name in cls._warning_names:\n            cls.enable(name)\n\n\nclass Diagnostics(Enum):\n    \"\"\"\n    Diagnostic configuration (all default to disabled)\n    - ``warn_multiple_tokens_in_named_alternation`` - flag to enable warnings when a results\n      name is defined on a :class:`MatchFirst` or :class:`Or` expression with one or more :class:`And` subexpressions\n    - ``warn_ungrouped_named_tokens_in_collection`` - flag to enable warnings when a results\n      name is defined on a containing expression with ungrouped subexpressions that also\n      have results names\n    - ``warn_name_set_on_empty_Forward`` - flag to enable warnings when a :class:`Forward` is defined\n      with a results name, but has no contents defined\n    - ``warn_on_parse_using_empty_Forward`` - flag to enable warnings when a :class:`Forward` is\n      defined in a grammar but has never had an expression attached to it\n    - ``warn_on_assignment_to_Forward`` - flag to enable warnings when a :class:`Forward` is defined\n      but is overwritten by assigning using ``'='`` instead of ``'<<='`` or ``'<<'``\n    - ``warn_on_multiple_string_args_to_oneof`` - flag to enable warnings when :class:`one_of` is\n      incorrectly called with multiple str arguments\n    - ``enable_debug_on_named_expressions`` - flag to auto-enable debug on all subsequent\n      calls to :class:`ParserElement.set_name`\n\n    Diagnostics are enabled/disabled by calling :class:`enable_diag` and :class:`disable_diag`.\n    All warnings can be enabled by calling :class:`enable_all_warnings`.\n    \"\"\"\n\n    warn_multiple_tokens_in_named_alternation = 0\n    warn_ungrouped_named_tokens_in_collection = 1\n    warn_name_set_on_empty_Forward = 2\n    warn_on_parse_using_empty_Forward = 3\n    warn_on_assignment_to_Forward = 4\n    warn_on_multiple_string_args_to_oneof = 5\n    warn_on_match_first_with_lshift_operator = 6\n    enable_debug_on_named_expressions = 7\n\n\ndef enable_diag(diag_enum: Diagnostics) -> None:\n    \"\"\"\n    Enable a global pyparsing diagnostic flag (see :class:`Diagnostics`).\n    \"\"\"\n    __diag__.enable(diag_enum.name)\n\n\ndef disable_diag(diag_enum: Diagnostics) -> None:\n    \"\"\"\n    Disable a global pyparsing diagnostic flag (see :class:`Diagnostics`).\n    \"\"\"\n    __diag__.disable(diag_enum.name)\n\n\ndef enable_all_warnings() -> None:\n    \"\"\"\n    Enable all global pyparsing diagnostic warnings (see :class:`Diagnostics`).\n    \"\"\"\n    __diag__.enable_all_warnings()\n\n\n# hide abstract class\ndel __config_flags\n\n\ndef _should_enable_warnings(\n    cmd_line_warn_options: typing.Iterable[str], warn_env_var: typing.Optional[str]\n) -> bool:\n    enable = bool(warn_env_var)\n    for warn_opt in cmd_line_warn_options:\n        w_action, w_message, w_category, w_module, w_line = (warn_opt + \"::::\").split(\n            \":\"\n        )[:5]\n        if not w_action.lower().startswith(\"i\") and (\n            not (w_message or w_category or w_module) or w_module == \"pyparsing\"\n        ):\n            enable = True\n        elif w_action.lower().startswith(\"i\") and w_module in (\"pyparsing\", \"\"):\n            enable = False\n    return enable\n\n\nif _should_enable_warnings(\n    sys.warnoptions, os.environ.get(\"PYPARSINGENABLEALLWARNINGS\")\n):\n    enable_all_warnings()\n\n\n# build list of single arg builtins, that can be used as parse actions\n_single_arg_builtins = {\n    sum,\n    len,\n    sorted,\n    reversed,\n    list,\n    tuple,\n    set,\n    any,\n    all,\n    min,\n    max,\n}\n\n_generatorType = types.GeneratorType\nParseAction = Union[\n    Callable[[], Any],\n    Callable[[ParseResults], Any],\n    Callable[[int, ParseResults], Any],\n    Callable[[str, int, ParseResults], Any],\n]\nParseCondition = Union[\n    Callable[[], bool],\n    Callable[[ParseResults], bool],\n    Callable[[int, ParseResults], bool],\n    Callable[[str, int, ParseResults], bool],\n]\nParseFailAction = Callable[[str, int, \"ParserElement\", Exception], None]\nDebugStartAction = Callable[[str, int, \"ParserElement\", bool], None]\nDebugSuccessAction = Callable[\n    [str, int, int, \"ParserElement\", ParseResults, bool], None\n]\nDebugExceptionAction = Callable[[str, int, \"ParserElement\", Exception, bool], None]\n\n\nalphas = string.ascii_uppercase + string.ascii_lowercase\nidentchars = pyparsing_unicode.Latin1.identchars\nidentbodychars = pyparsing_unicode.Latin1.identbodychars\nnums = \"0123456789\"\nhexnums = nums + \"ABCDEFabcdef\"\nalphanums = alphas + nums\nprintables = \"\".join([c for c in string.printable if c not in string.whitespace])\n\n_trim_arity_call_line: traceback.StackSummary = None\n\n\ndef _trim_arity(func, max_limit=3):\n    \"\"\"decorator to trim function calls to match the arity of the target\"\"\"\n    global _trim_arity_call_line\n\n    if func in _single_arg_builtins:\n        return lambda s, l, t: func(t)\n\n    limit = 0\n    found_arity = False\n\n    def extract_tb(tb, limit=0):\n        frames = traceback.extract_tb(tb, limit=limit)\n        frame_summary = frames[-1]\n        return [frame_summary[:2]]\n\n    # synthesize what would be returned by traceback.extract_stack at the call to\n    # user's parse action 'func', so that we don't incur call penalty at parse time\n\n    # fmt: off\n    LINE_DIFF = 7\n    # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND\n    # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!!\n    _trim_arity_call_line = (_trim_arity_call_line or traceback.extract_stack(limit=2)[-1])\n    pa_call_line_synth = (_trim_arity_call_line[0], _trim_arity_call_line[1] + LINE_DIFF)\n\n    def wrapper(*args):\n        nonlocal found_arity, limit\n        while 1:\n            try:\n                ret = func(*args[limit:])\n                found_arity = True\n                return ret\n            except TypeError as te:\n                # re-raise TypeErrors if they did not come from our arity testing\n                if found_arity:\n                    raise\n                else:\n                    tb = te.__traceback__\n                    trim_arity_type_error = (\n                        extract_tb(tb, limit=2)[-1][:2] == pa_call_line_synth\n                    )\n                    del tb\n\n                    if trim_arity_type_error:\n                        if limit < max_limit:\n                            limit += 1\n                            continue\n\n                    raise\n    # fmt: on\n\n    # copy func name to wrapper for sensible debug output\n    # (can't use functools.wraps, since that messes with function signature)\n    func_name = getattr(func, \"__name__\", getattr(func, \"__class__\").__name__)\n    wrapper.__name__ = func_name\n    wrapper.__doc__ = func.__doc__\n\n    return wrapper\n\n\ndef condition_as_parse_action(\n    fn: ParseCondition, message: str = None, fatal: bool = False\n) -> ParseAction:\n    \"\"\"\n    Function to convert a simple predicate function that returns ``True`` or ``False``\n    into a parse action. Can be used in places when a parse action is required\n    and :class:`ParserElement.add_condition` cannot be used (such as when adding a condition\n    to an operator level in :class:`infix_notation`).\n\n    Optional keyword arguments:\n\n    - ``message`` - define a custom message to be used in the raised exception\n    - ``fatal`` - if True, will raise :class:`ParseFatalException` to stop parsing immediately;\n      otherwise will raise :class:`ParseException`\n\n    \"\"\"\n    msg = message if message is not None else \"failed user-defined condition\"\n    exc_type = ParseFatalException if fatal else ParseException\n    fn = _trim_arity(fn)\n\n    @wraps(fn)\n    def pa(s, l, t):\n        if not bool(fn(s, l, t)):\n            raise exc_type(s, l, msg)\n\n    return pa\n\n\ndef _default_start_debug_action(\n    instring: str, loc: int, expr: \"ParserElement\", cache_hit: bool = False\n):\n    cache_hit_str = \"*\" if cache_hit else \"\"\n    print(\n        (\n            \"{}Match {} at loc {}({},{})\\n  {}\\n  {}^\".format(\n                cache_hit_str,\n                expr,\n                loc,\n                lineno(loc, instring),\n                col(loc, instring),\n                line(loc, instring),\n                \" \" * (col(loc, instring) - 1),\n            )\n        )\n    )\n\n\ndef _default_success_debug_action(\n    instring: str,\n    startloc: int,\n    endloc: int,\n    expr: \"ParserElement\",\n    toks: ParseResults,\n    cache_hit: bool = False,\n):\n    cache_hit_str = \"*\" if cache_hit else \"\"\n    print(\"{}Matched {} -> {}\".format(cache_hit_str, expr, toks.as_list()))\n\n\ndef _default_exception_debug_action(\n    instring: str,\n    loc: int,\n    expr: \"ParserElement\",\n    exc: Exception,\n    cache_hit: bool = False,\n):\n    cache_hit_str = \"*\" if cache_hit else \"\"\n    print(\n        \"{}Match {} failed, {} raised: {}\".format(\n            cache_hit_str, expr, type(exc).__name__, exc\n        )\n    )\n\n\ndef null_debug_action(*args):\n    \"\"\"'Do-nothing' debug action, to suppress debugging output during parsing.\"\"\"\n\n\nclass ParserElement(ABC):\n    \"\"\"Abstract base level parser element class.\"\"\"\n\n    DEFAULT_WHITE_CHARS: str = \" \\n\\t\\r\"\n    verbose_stacktrace: bool = False\n    _literalStringClass: typing.Optional[type] = None\n\n    @staticmethod\n    def set_default_whitespace_chars(chars: str) -> None:\n        r\"\"\"\n        Overrides the default whitespace chars\n\n        Example::\n\n            # default whitespace chars are space, <TAB> and newline\n            Word(alphas)[1, ...].parse_string(\"abc def\\nghi jkl\")  # -> ['abc', 'def', 'ghi', 'jkl']\n\n            # change to just treat newline as significant\n            ParserElement.set_default_whitespace_chars(\" \\t\")\n            Word(alphas)[1, ...].parse_string(\"abc def\\nghi jkl\")  # -> ['abc', 'def']\n        \"\"\"\n        ParserElement.DEFAULT_WHITE_CHARS = chars\n\n        # update whitespace all parse expressions defined in this module\n        for expr in _builtin_exprs:\n            if expr.copyDefaultWhiteChars:\n                expr.whiteChars = set(chars)\n\n    @staticmethod\n    def inline_literals_using(cls: type) -> None:\n        \"\"\"\n        Set class to be used for inclusion of string literals into a parser.\n\n        Example::\n\n            # default literal class used is Literal\n            integer = Word(nums)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            date_str.parse_string(\"1999/12/31\")  # -> ['1999', '/', '12', '/', '31']\n\n\n            # change to Suppress\n            ParserElement.inline_literals_using(Suppress)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            date_str.parse_string(\"1999/12/31\")  # -> ['1999', '12', '31']\n        \"\"\"\n        ParserElement._literalStringClass = cls\n\n    class DebugActions(NamedTuple):\n        debug_try: typing.Optional[DebugStartAction]\n        debug_match: typing.Optional[DebugSuccessAction]\n        debug_fail: typing.Optional[DebugExceptionAction]\n\n    def __init__(self, savelist: bool = False):\n        self.parseAction: List[ParseAction] = list()\n        self.failAction: typing.Optional[ParseFailAction] = None\n        self.customName = None\n        self._defaultName = None\n        self.resultsName = None\n        self.saveAsList = savelist\n        self.skipWhitespace = True\n        self.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS)\n        self.copyDefaultWhiteChars = True\n        # used when checking for left-recursion\n        self.mayReturnEmpty = False\n        self.keepTabs = False\n        self.ignoreExprs: List[\"ParserElement\"] = list()\n        self.debug = False\n        self.streamlined = False\n        # optimize exception handling for subclasses that don't advance parse index\n        self.mayIndexError = True\n        self.errmsg = \"\"\n        # mark results names as modal (report only last) or cumulative (list all)\n        self.modalResults = True\n        # custom debug actions\n        self.debugActions = self.DebugActions(None, None, None)\n        # avoid redundant calls to preParse\n        self.callPreparse = True\n        self.callDuringTry = False\n        self.suppress_warnings_: List[Diagnostics] = []\n\n    def suppress_warning(self, warning_type: Diagnostics) -> \"ParserElement\":\n        \"\"\"\n        Suppress warnings emitted for a particular diagnostic on this expression.\n\n        Example::\n\n            base = pp.Forward()\n            base.suppress_warning(Diagnostics.warn_on_parse_using_empty_Forward)\n\n            # statement would normally raise a warning, but is now suppressed\n            print(base.parseString(\"x\"))\n\n        \"\"\"\n        self.suppress_warnings_.append(warning_type)\n        return self\n\n    def copy(self) -> \"ParserElement\":\n        \"\"\"\n        Make a copy of this :class:`ParserElement`.  Useful for defining\n        different parse actions for the same parsing pattern, using copies of\n        the original parse element.\n\n        Example::\n\n            integer = Word(nums).set_parse_action(lambda toks: int(toks[0]))\n            integerK = integer.copy().add_parse_action(lambda toks: toks[0] * 1024) + Suppress(\"K\")\n            integerM = integer.copy().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress(\"M\")\n\n            print((integerK | integerM | integer)[1, ...].parse_string(\"5K 100 640K 256M\"))\n\n        prints::\n\n            [5120, 100, 655360, 268435456]\n\n        Equivalent form of ``expr.copy()`` is just ``expr()``::\n\n            integerM = integer().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress(\"M\")\n        \"\"\"\n        cpy = copy.copy(self)\n        cpy.parseAction = self.parseAction[:]\n        cpy.ignoreExprs = self.ignoreExprs[:]\n        if self.copyDefaultWhiteChars:\n            cpy.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS)\n        return cpy\n\n    def set_results_name(\n        self, name: str, list_all_matches: bool = False, *, listAllMatches: bool = False\n    ) -> \"ParserElement\":\n        \"\"\"\n        Define name for referencing matching tokens as a nested attribute\n        of the returned parse results.\n\n        Normally, results names are assigned as you would assign keys in a dict:\n        any existing value is overwritten by later values. If it is necessary to\n        keep all values captured for a particular results name, call ``set_results_name``\n        with ``list_all_matches`` = True.\n\n        NOTE: ``set_results_name`` returns a *copy* of the original :class:`ParserElement` object;\n        this is so that the client can define a basic element, such as an\n        integer, and reference it in multiple places with different names.\n\n        You can also set results names using the abbreviated syntax,\n        ``expr(\"name\")`` in place of ``expr.set_results_name(\"name\")``\n        - see :class:`__call__`. If ``list_all_matches`` is required, use\n        ``expr(\"name*\")``.\n\n        Example::\n\n            date_str = (integer.set_results_name(\"year\") + '/'\n                        + integer.set_results_name(\"month\") + '/'\n                        + integer.set_results_name(\"day\"))\n\n            # equivalent form:\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n        \"\"\"\n        listAllMatches = listAllMatches or list_all_matches\n        return self._setResultsName(name, listAllMatches)\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if name is None:\n            return self\n        newself = self.copy()\n        if name.endswith(\"*\"):\n            name = name[:-1]\n            listAllMatches = True\n        newself.resultsName = name\n        newself.modalResults = not listAllMatches\n        return newself\n\n    def set_break(self, break_flag: bool = True) -> \"ParserElement\":\n        \"\"\"\n        Method to invoke the Python pdb debugger when this element is\n        about to be parsed. Set ``break_flag`` to ``True`` to enable, ``False`` to\n        disable.\n        \"\"\"\n        if break_flag:\n            _parseMethod = self._parse\n\n            def breaker(instring, loc, doActions=True, callPreParse=True):\n                import pdb\n\n                # this call to pdb.set_trace() is intentional, not a checkin error\n                pdb.set_trace()\n                return _parseMethod(instring, loc, doActions, callPreParse)\n\n            breaker._originalParseMethod = _parseMethod\n            self._parse = breaker\n        else:\n            if hasattr(self._parse, \"_originalParseMethod\"):\n                self._parse = self._parse._originalParseMethod\n        return self\n\n    def set_parse_action(self, *fns: ParseAction, **kwargs) -> \"ParserElement\":\n        \"\"\"\n        Define one or more actions to perform when successfully matching parse element definition.\n\n        Parse actions can be called to perform data conversions, do extra validation,\n        update external data structures, or enhance or replace the parsed tokens.\n        Each parse action ``fn`` is a callable method with 0-3 arguments, called as\n        ``fn(s, loc, toks)`` , ``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where:\n\n        - s   = the original string being parsed (see note below)\n        - loc = the location of the matching substring\n        - toks = a list of the matched tokens, packaged as a :class:`ParseResults` object\n\n        The parsed tokens are passed to the parse action as ParseResults. They can be\n        modified in place using list-style append, extend, and pop operations to update\n        the parsed list elements; and with dictionary-style item set and del operations\n        to add, update, or remove any named results. If the tokens are modified in place,\n        it is not necessary to return them with a return statement.\n\n        Parse actions can also completely replace the given tokens, with another ``ParseResults``\n        object, or with some entirely different object (common for parse actions that perform data\n        conversions). A convenient way to build a new parse result is to define the values\n        using a dict, and then create the return value using :class:`ParseResults.from_dict`.\n\n        If None is passed as the ``fn`` parse action, all previously added parse actions for this\n        expression are cleared.\n\n        Optional keyword arguments:\n\n        - call_during_try = (default= ``False``) indicate if parse action should be run during\n          lookaheads and alternate testing. For parse actions that have side effects, it is\n          important to only call the parse action once it is determined that it is being\n          called as part of a successful parse. For parse actions that perform additional\n          validation, then call_during_try should be passed as True, so that the validation\n          code is included in the preliminary \"try\" parses.\n\n        Note: the default parsing behavior is to expand tabs in the input string\n        before starting the parsing process.  See :class:`parse_string` for more\n        information on parsing strings containing ``<TAB>`` s, and suggested\n        methods to maintain a consistent view of the parsed string, the parse\n        location, and line and column positions within the parsed string.\n\n        Example::\n\n            # parse dates in the form YYYY/MM/DD\n\n            # use parse action to convert toks from str to int at parse time\n            def convert_to_int(toks):\n                return int(toks[0])\n\n            # use a parse action to verify that the date is a valid date\n            def is_valid_date(instring, loc, toks):\n                from datetime import date\n                year, month, day = toks[::2]\n                try:\n                    date(year, month, day)\n                except ValueError:\n                    raise ParseException(instring, loc, \"invalid date given\")\n\n            integer = Word(nums)\n            date_str = integer + '/' + integer + '/' + integer\n\n            # add parse actions\n            integer.set_parse_action(convert_to_int)\n            date_str.set_parse_action(is_valid_date)\n\n            # note that integer fields are now ints, not strings\n            date_str.run_tests('''\n                # successful parse - note that integer fields were converted to ints\n                1999/12/31\n\n                # fail - invalid date\n                1999/13/31\n                ''')\n        \"\"\"\n        if list(fns) == [None]:\n            self.parseAction = []\n        else:\n            if not all(callable(fn) for fn in fns):\n                raise TypeError(\"parse actions must be callable\")\n            self.parseAction = [_trim_arity(fn) for fn in fns]\n            self.callDuringTry = kwargs.get(\n                \"call_during_try\", kwargs.get(\"callDuringTry\", False)\n            )\n        return self\n\n    def add_parse_action(self, *fns: ParseAction, **kwargs) -> \"ParserElement\":\n        \"\"\"\n        Add one or more parse actions to expression's list of parse actions. See :class:`set_parse_action`.\n\n        See examples in :class:`copy`.\n        \"\"\"\n        self.parseAction += [_trim_arity(fn) for fn in fns]\n        self.callDuringTry = self.callDuringTry or kwargs.get(\n            \"call_during_try\", kwargs.get(\"callDuringTry\", False)\n        )\n        return self\n\n    def add_condition(self, *fns: ParseCondition, **kwargs) -> \"ParserElement\":\n        \"\"\"Add a boolean predicate function to expression's list of parse actions. See\n        :class:`set_parse_action` for function call signatures. Unlike ``set_parse_action``,\n        functions passed to ``add_condition`` need to return boolean success/fail of the condition.\n\n        Optional keyword arguments:\n\n        - message = define a custom message to be used in the raised exception\n        - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise\n          ParseException\n        - call_during_try = boolean to indicate if this method should be called during internal tryParse calls,\n          default=False\n\n        Example::\n\n            integer = Word(nums).set_parse_action(lambda toks: int(toks[0]))\n            year_int = integer.copy()\n            year_int.add_condition(lambda toks: toks[0] >= 2000, message=\"Only support years 2000 and later\")\n            date_str = year_int + '/' + integer + '/' + integer\n\n            result = date_str.parse_string(\"1999/12/31\")  # -> Exception: Only support years 2000 and later (at char 0),\n                                                                         (line:1, col:1)\n        \"\"\"\n        for fn in fns:\n            self.parseAction.append(\n                condition_as_parse_action(\n                    fn, message=kwargs.get(\"message\"), fatal=kwargs.get(\"fatal\", False)\n                )\n            )\n\n        self.callDuringTry = self.callDuringTry or kwargs.get(\n            \"call_during_try\", kwargs.get(\"callDuringTry\", False)\n        )\n        return self\n\n    def set_fail_action(self, fn: ParseFailAction) -> \"ParserElement\":\n        \"\"\"\n        Define action to perform if parsing fails at this expression.\n        Fail acton fn is a callable function that takes the arguments\n        ``fn(s, loc, expr, err)`` where:\n\n        - s = string being parsed\n        - loc = location where expression match was attempted and failed\n        - expr = the parse expression that failed\n        - err = the exception thrown\n\n        The function returns no value.  It may throw :class:`ParseFatalException`\n        if it is desired to stop parsing immediately.\"\"\"\n        self.failAction = fn\n        return self\n\n    def _skipIgnorables(self, instring, loc):\n        exprsFound = True\n        while exprsFound:\n            exprsFound = False\n            for e in self.ignoreExprs:\n                try:\n                    while 1:\n                        loc, dummy = e._parse(instring, loc)\n                        exprsFound = True\n                except ParseException:\n                    pass\n        return loc\n\n    def preParse(self, instring, loc):\n        if self.ignoreExprs:\n            loc = self._skipIgnorables(instring, loc)\n\n        if self.skipWhitespace:\n            instrlen = len(instring)\n            white_chars = self.whiteChars\n            while loc < instrlen and instring[loc] in white_chars:\n                loc += 1\n\n        return loc\n\n    def parseImpl(self, instring, loc, doActions=True):\n        return loc, []\n\n    def postParse(self, instring, loc, tokenlist):\n        return tokenlist\n\n    # @profile\n    def _parseNoCache(\n        self, instring, loc, doActions=True, callPreParse=True\n    ) -> Tuple[int, ParseResults]:\n        TRY, MATCH, FAIL = 0, 1, 2\n        debugging = self.debug  # and doActions)\n        len_instring = len(instring)\n\n        if debugging or self.failAction:\n            # print(\"Match {} at loc {}({}, {})\".format(self, loc, lineno(loc, instring), col(loc, instring)))\n            try:\n                if callPreParse and self.callPreparse:\n                    pre_loc = self.preParse(instring, loc)\n                else:\n                    pre_loc = loc\n                tokens_start = pre_loc\n                if self.debugActions.debug_try:\n                    self.debugActions.debug_try(instring, tokens_start, self, False)\n                if self.mayIndexError or pre_loc >= len_instring:\n                    try:\n                        loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n                    except IndexError:\n                        raise ParseException(instring, len_instring, self.errmsg, self)\n                else:\n                    loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n            except Exception as err:\n                # print(\"Exception raised:\", err)\n                if self.debugActions.debug_fail:\n                    self.debugActions.debug_fail(\n                        instring, tokens_start, self, err, False\n                    )\n                if self.failAction:\n                    self.failAction(instring, tokens_start, self, err)\n                raise\n        else:\n            if callPreParse and self.callPreparse:\n                pre_loc = self.preParse(instring, loc)\n            else:\n                pre_loc = loc\n            tokens_start = pre_loc\n            if self.mayIndexError or pre_loc >= len_instring:\n                try:\n                    loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n                except IndexError:\n                    raise ParseException(instring, len_instring, self.errmsg, self)\n            else:\n                loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n\n        tokens = self.postParse(instring, loc, tokens)\n\n        ret_tokens = ParseResults(\n            tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults\n        )\n        if self.parseAction and (doActions or self.callDuringTry):\n            if debugging:\n                try:\n                    for fn in self.parseAction:\n                        try:\n                            tokens = fn(instring, tokens_start, ret_tokens)\n                        except IndexError as parse_action_exc:\n                            exc = ParseException(\"exception raised in parse action\")\n                            raise exc from parse_action_exc\n\n                        if tokens is not None and tokens is not ret_tokens:\n                            ret_tokens = ParseResults(\n                                tokens,\n                                self.resultsName,\n                                asList=self.saveAsList\n                                and isinstance(tokens, (ParseResults, list)),\n                                modal=self.modalResults,\n                            )\n                except Exception as err:\n                    # print \"Exception raised in user parse action:\", err\n                    if self.debugActions.debug_fail:\n                        self.debugActions.debug_fail(\n                            instring, tokens_start, self, err, False\n                        )\n                    raise\n            else:\n                for fn in self.parseAction:\n                    try:\n                        tokens = fn(instring, tokens_start, ret_tokens)\n                    except IndexError as parse_action_exc:\n                        exc = ParseException(\"exception raised in parse action\")\n                        raise exc from parse_action_exc\n\n                    if tokens is not None and tokens is not ret_tokens:\n                        ret_tokens = ParseResults(\n                            tokens,\n                            self.resultsName,\n                            asList=self.saveAsList\n                            and isinstance(tokens, (ParseResults, list)),\n                            modal=self.modalResults,\n                        )\n        if debugging:\n            # print(\"Matched\", self, \"->\", ret_tokens.as_list())\n            if self.debugActions.debug_match:\n                self.debugActions.debug_match(\n                    instring, tokens_start, loc, self, ret_tokens, False\n                )\n\n        return loc, ret_tokens\n\n    def try_parse(self, instring: str, loc: int, raise_fatal: bool = False) -> int:\n        try:\n            return self._parse(instring, loc, doActions=False)[0]\n        except ParseFatalException:\n            if raise_fatal:\n                raise\n            raise ParseException(instring, loc, self.errmsg, self)\n\n    def can_parse_next(self, instring: str, loc: int) -> bool:\n        try:\n            self.try_parse(instring, loc)\n        except (ParseException, IndexError):\n            return False\n        else:\n            return True\n\n    # cache for left-recursion in Forward references\n    recursion_lock = RLock()\n    recursion_memos: typing.Dict[\n        Tuple[int, \"Forward\", bool], Tuple[int, Union[ParseResults, Exception]]\n    ] = {}\n\n    # argument cache for optimizing repeated calls when backtracking through recursive expressions\n    packrat_cache = (\n        {}\n    )  # this is set later by enabled_packrat(); this is here so that reset_cache() doesn't fail\n    packrat_cache_lock = RLock()\n    packrat_cache_stats = [0, 0]\n\n    # this method gets repeatedly called during backtracking with the same arguments -\n    # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression\n    def _parseCache(\n        self, instring, loc, doActions=True, callPreParse=True\n    ) -> Tuple[int, ParseResults]:\n        HIT, MISS = 0, 1\n        TRY, MATCH, FAIL = 0, 1, 2\n        lookup = (self, instring, loc, callPreParse, doActions)\n        with ParserElement.packrat_cache_lock:\n            cache = ParserElement.packrat_cache\n            value = cache.get(lookup)\n            if value is cache.not_in_cache:\n                ParserElement.packrat_cache_stats[MISS] += 1\n                try:\n                    value = self._parseNoCache(instring, loc, doActions, callPreParse)\n                except ParseBaseException as pe:\n                    # cache a copy of the exception, without the traceback\n                    cache.set(lookup, pe.__class__(*pe.args))\n                    raise\n                else:\n                    cache.set(lookup, (value[0], value[1].copy(), loc))\n                    return value\n            else:\n                ParserElement.packrat_cache_stats[HIT] += 1\n                if self.debug and self.debugActions.debug_try:\n                    try:\n                        self.debugActions.debug_try(instring, loc, self, cache_hit=True)\n                    except TypeError:\n                        pass\n                if isinstance(value, Exception):\n                    if self.debug and self.debugActions.debug_fail:\n                        try:\n                            self.debugActions.debug_fail(\n                                instring, loc, self, value, cache_hit=True\n                            )\n                        except TypeError:\n                            pass\n                    raise value\n\n                loc_, result, endloc = value[0], value[1].copy(), value[2]\n                if self.debug and self.debugActions.debug_match:\n                    try:\n                        self.debugActions.debug_match(\n                            instring, loc_, endloc, self, result, cache_hit=True\n                        )\n                    except TypeError:\n                        pass\n\n                return loc_, result\n\n    _parse = _parseNoCache\n\n    @staticmethod\n    def reset_cache() -> None:\n        ParserElement.packrat_cache.clear()\n        ParserElement.packrat_cache_stats[:] = [0] * len(\n            ParserElement.packrat_cache_stats\n        )\n        ParserElement.recursion_memos.clear()\n\n    _packratEnabled = False\n    _left_recursion_enabled = False\n\n    @staticmethod\n    def disable_memoization() -> None:\n        \"\"\"\n        Disables active Packrat or Left Recursion parsing and their memoization\n\n        This method also works if neither Packrat nor Left Recursion are enabled.\n        This makes it safe to call before activating Packrat nor Left Recursion\n        to clear any previous settings.\n        \"\"\"\n        ParserElement.reset_cache()\n        ParserElement._left_recursion_enabled = False\n        ParserElement._packratEnabled = False\n        ParserElement._parse = ParserElement._parseNoCache\n\n    @staticmethod\n    def enable_left_recursion(\n        cache_size_limit: typing.Optional[int] = None, *, force=False\n    ) -> None:\n        \"\"\"\n        Enables \"bounded recursion\" parsing, which allows for both direct and indirect\n        left-recursion. During parsing, left-recursive :class:`Forward` elements are\n        repeatedly matched with a fixed recursion depth that is gradually increased\n        until finding the longest match.\n\n        Example::\n\n            from pip._vendor import pyparsing as pp\n            pp.ParserElement.enable_left_recursion()\n\n            E = pp.Forward(\"E\")\n            num = pp.Word(pp.nums)\n            # match `num`, or `num '+' num`, or `num '+' num '+' num`, ...\n            E <<= E + '+' - num | num\n\n            print(E.parse_string(\"1+2+3\"))\n\n        Recursion search naturally memoizes matches of ``Forward`` elements and may\n        thus skip reevaluation of parse actions during backtracking. This may break\n        programs with parse actions which rely on strict ordering of side-effects.\n\n        Parameters:\n\n        - cache_size_limit - (default=``None``) - memoize at most this many\n          ``Forward`` elements during matching; if ``None`` (the default),\n          memoize all ``Forward`` elements.\n\n        Bounded Recursion parsing works similar but not identical to Packrat parsing,\n        thus the two cannot be used together. Use ``force=True`` to disable any\n        previous, conflicting settings.\n        \"\"\"\n        if force:\n            ParserElement.disable_memoization()\n        elif ParserElement._packratEnabled:\n            raise RuntimeError(\"Packrat and Bounded Recursion are not compatible\")\n        if cache_size_limit is None:\n            ParserElement.recursion_memos = _UnboundedMemo()\n        elif cache_size_limit > 0:\n            ParserElement.recursion_memos = _LRUMemo(capacity=cache_size_limit)\n        else:\n            raise NotImplementedError(\"Memo size of %s\" % cache_size_limit)\n        ParserElement._left_recursion_enabled = True\n\n    @staticmethod\n    def enable_packrat(cache_size_limit: int = 128, *, force: bool = False) -> None:\n        \"\"\"\n        Enables \"packrat\" parsing, which adds memoizing to the parsing logic.\n        Repeated parse attempts at the same string location (which happens\n        often in many complex grammars) can immediately return a cached value,\n        instead of re-executing parsing/validating code.  Memoizing is done of\n        both valid results and parsing exceptions.\n\n        Parameters:\n\n        - cache_size_limit - (default= ``128``) - if an integer value is provided\n          will limit the size of the packrat cache; if None is passed, then\n          the cache size will be unbounded; if 0 is passed, the cache will\n          be effectively disabled.\n\n        This speedup may break existing programs that use parse actions that\n        have side-effects.  For this reason, packrat parsing is disabled when\n        you first import pyparsing.  To activate the packrat feature, your\n        program must call the class method :class:`ParserElement.enable_packrat`.\n        For best results, call ``enable_packrat()`` immediately after\n        importing pyparsing.\n\n        Example::\n\n            from pip._vendor import pyparsing\n            pyparsing.ParserElement.enable_packrat()\n\n        Packrat parsing works similar but not identical to Bounded Recursion parsing,\n        thus the two cannot be used together. Use ``force=True`` to disable any\n        previous, conflicting settings.\n        \"\"\"\n        if force:\n            ParserElement.disable_memoization()\n        elif ParserElement._left_recursion_enabled:\n            raise RuntimeError(\"Packrat and Bounded Recursion are not compatible\")\n        if not ParserElement._packratEnabled:\n            ParserElement._packratEnabled = True\n            if cache_size_limit is None:\n                ParserElement.packrat_cache = _UnboundedCache()\n            else:\n                ParserElement.packrat_cache = _FifoCache(cache_size_limit)\n            ParserElement._parse = ParserElement._parseCache\n\n    def parse_string(\n        self, instring: str, parse_all: bool = False, *, parseAll: bool = False\n    ) -> ParseResults:\n        \"\"\"\n        Parse a string with respect to the parser definition. This function is intended as the primary interface to the\n        client code.\n\n        :param instring: The input string to be parsed.\n        :param parse_all: If set, the entire input string must match the grammar.\n        :param parseAll: retained for pre-PEP8 compatibility, will be removed in a future release.\n        :raises ParseException: Raised if ``parse_all`` is set and the input string does not match the whole grammar.\n        :returns: the parsed data as a :class:`ParseResults` object, which may be accessed as a `list`, a `dict`, or\n          an object with attributes if the given parser includes results names.\n\n        If the input string is required to match the entire grammar, ``parse_all`` flag must be set to ``True``. This\n        is also equivalent to ending the grammar with :class:`StringEnd`().\n\n        To report proper column numbers, ``parse_string`` operates on a copy of the input string where all tabs are\n        converted to spaces (8 spaces per tab, as per the default in ``string.expandtabs``). If the input string\n        contains tabs and the grammar uses parse actions that use the ``loc`` argument to index into the string\n        being parsed, one can ensure a consistent view of the input string by doing one of the following:\n\n        - calling ``parse_with_tabs`` on your grammar before calling ``parse_string`` (see :class:`parse_with_tabs`),\n        - define your parse action using the full ``(s,loc,toks)`` signature, and reference the input string using the\n          parse action's ``s`` argument, or\n        - explicitly expand the tabs in your input string before calling ``parse_string``.\n\n        Examples:\n\n        By default, partial matches are OK.\n\n        >>> res = Word('a').parse_string('aaaaabaaa')\n        >>> print(res)\n        ['aaaaa']\n\n        The parsing behavior varies by the inheriting class of this abstract class. Please refer to the children\n        directly to see more examples.\n\n        It raises an exception if parse_all flag is set and instring does not match the whole grammar.\n\n        >>> res = Word('a').parse_string('aaaaabaaa', parse_all=True)\n        Traceback (most recent call last):\n        ...\n        pyparsing.ParseException: Expected end of text, found 'b'  (at char 5), (line:1, col:6)\n        \"\"\"\n        parseAll = parse_all or parseAll\n\n        ParserElement.reset_cache()\n        if not self.streamlined:\n            self.streamline()\n        for e in self.ignoreExprs:\n            e.streamline()\n        if not self.keepTabs:\n            instring = instring.expandtabs()\n        try:\n            loc, tokens = self._parse(instring, 0)\n            if parseAll:\n                loc = self.preParse(instring, loc)\n                se = Empty() + StringEnd()\n                se._parse(instring, loc)\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clearing out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n        else:\n            return tokens\n\n    def scan_string(\n        self,\n        instring: str,\n        max_matches: int = _MAX_INT,\n        overlap: bool = False,\n        *,\n        debug: bool = False,\n        maxMatches: int = _MAX_INT,\n    ) -> Generator[Tuple[ParseResults, int, int], None, None]:\n        \"\"\"\n        Scan the input string for expression matches.  Each match will return the\n        matching tokens, start location, and end location.  May be called with optional\n        ``max_matches`` argument, to clip scanning after 'n' matches are found.  If\n        ``overlap`` is specified, then overlapping matches will be reported.\n\n        Note that the start and end locations are reported relative to the string\n        being parsed.  See :class:`parse_string` for more information on parsing\n        strings with embedded tabs.\n\n        Example::\n\n            source = \"sldjf123lsdjjkf345sldkjf879lkjsfd987\"\n            print(source)\n            for tokens, start, end in Word(alphas).scan_string(source):\n                print(' '*start + '^'*(end-start))\n                print(' '*start + tokens[0])\n\n        prints::\n\n            sldjf123lsdjjkf345sldkjf879lkjsfd987\n            ^^^^^\n            sldjf\n                    ^^^^^^^\n                    lsdjjkf\n                              ^^^^^^\n                              sldkjf\n                                       ^^^^^^\n                                       lkjsfd\n        \"\"\"\n        maxMatches = min(maxMatches, max_matches)\n        if not self.streamlined:\n            self.streamline()\n        for e in self.ignoreExprs:\n            e.streamline()\n\n        if not self.keepTabs:\n            instring = str(instring).expandtabs()\n        instrlen = len(instring)\n        loc = 0\n        preparseFn = self.preParse\n        parseFn = self._parse\n        ParserElement.resetCache()\n        matches = 0\n        try:\n            while loc <= instrlen and matches < maxMatches:\n                try:\n                    preloc = preparseFn(instring, loc)\n                    nextLoc, tokens = parseFn(instring, preloc, callPreParse=False)\n                except ParseException:\n                    loc = preloc + 1\n                else:\n                    if nextLoc > loc:\n                        matches += 1\n                        if debug:\n                            print(\n                                {\n                                    \"tokens\": tokens.asList(),\n                                    \"start\": preloc,\n                                    \"end\": nextLoc,\n                                }\n                            )\n                        yield tokens, preloc, nextLoc\n                        if overlap:\n                            nextloc = preparseFn(instring, loc)\n                            if nextloc > loc:\n                                loc = nextLoc\n                            else:\n                                loc += 1\n                        else:\n                            loc = nextLoc\n                    else:\n                        loc = preloc + 1\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clears out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n\n    def transform_string(self, instring: str, *, debug: bool = False) -> str:\n        \"\"\"\n        Extension to :class:`scan_string`, to modify matching text with modified tokens that may\n        be returned from a parse action.  To use ``transform_string``, define a grammar and\n        attach a parse action to it that modifies the returned token list.\n        Invoking ``transform_string()`` on a target string will then scan for matches,\n        and replace the matched text patterns according to the logic in the parse\n        action.  ``transform_string()`` returns the resulting transformed string.\n\n        Example::\n\n            wd = Word(alphas)\n            wd.set_parse_action(lambda toks: toks[0].title())\n\n            print(wd.transform_string(\"now is the winter of our discontent made glorious summer by this sun of york.\"))\n\n        prints::\n\n            Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.\n        \"\"\"\n        out: List[str] = []\n        lastE = 0\n        # force preservation of <TAB>s, to minimize unwanted transformation of string, and to\n        # keep string locs straight between transform_string and scan_string\n        self.keepTabs = True\n        try:\n            for t, s, e in self.scan_string(instring, debug=debug):\n                out.append(instring[lastE:s])\n                if t:\n                    if isinstance(t, ParseResults):\n                        out += t.as_list()\n                    elif isinstance(t, Iterable) and not isinstance(t, str_type):\n                        out.extend(t)\n                    else:\n                        out.append(t)\n                lastE = e\n            out.append(instring[lastE:])\n            out = [o for o in out if o]\n            return \"\".join([str(s) for s in _flatten(out)])\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clears out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n\n    def search_string(\n        self,\n        instring: str,\n        max_matches: int = _MAX_INT,\n        *,\n        debug: bool = False,\n        maxMatches: int = _MAX_INT,\n    ) -> ParseResults:\n        \"\"\"\n        Another extension to :class:`scan_string`, simplifying the access to the tokens found\n        to match the given parse expression.  May be called with optional\n        ``max_matches`` argument, to clip searching after 'n' matches are found.\n\n        Example::\n\n            # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters\n            cap_word = Word(alphas.upper(), alphas.lower())\n\n            print(cap_word.search_string(\"More than Iron, more than Lead, more than Gold I need Electricity\"))\n\n            # the sum() builtin can be used to merge results into a single ParseResults object\n            print(sum(cap_word.search_string(\"More than Iron, more than Lead, more than Gold I need Electricity\")))\n\n        prints::\n\n            [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']]\n            ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity']\n        \"\"\"\n        maxMatches = min(maxMatches, max_matches)\n        try:\n            return ParseResults(\n                [t for t, s, e in self.scan_string(instring, maxMatches, debug=debug)]\n            )\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clears out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n\n    def split(\n        self,\n        instring: str,\n        maxsplit: int = _MAX_INT,\n        include_separators: bool = False,\n        *,\n        includeSeparators=False,\n    ) -> Generator[str, None, None]:\n        \"\"\"\n        Generator method to split a string using the given expression as a separator.\n        May be called with optional ``maxsplit`` argument, to limit the number of splits;\n        and the optional ``include_separators`` argument (default= ``False``), if the separating\n        matching text should be included in the split results.\n\n        Example::\n\n            punc = one_of(list(\".,;:/-!?\"))\n            print(list(punc.split(\"This, this?, this sentence, is badly punctuated!\")))\n\n        prints::\n\n            ['This', ' this', '', ' this sentence', ' is badly punctuated', '']\n        \"\"\"\n        includeSeparators = includeSeparators or include_separators\n        last = 0\n        for t, s, e in self.scan_string(instring, max_matches=maxsplit):\n            yield instring[last:s]\n            if includeSeparators:\n                yield t[0]\n            last = e\n        yield instring[last:]\n\n    def __add__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``+`` operator - returns :class:`And`. Adding strings to a :class:`ParserElement`\n        converts them to :class:`Literal`s by default.\n\n        Example::\n\n            greet = Word(alphas) + \",\" + Word(alphas) + \"!\"\n            hello = \"Hello, World!\"\n            print(hello, \"->\", greet.parse_string(hello))\n\n        prints::\n\n            Hello, World! -> ['Hello', ',', 'World', '!']\n\n        ``...`` may be used as a parse expression as a short form of :class:`SkipTo`.\n\n            Literal('start') + ... + Literal('end')\n\n        is equivalent to:\n\n            Literal('start') + SkipTo('end')(\"_skipped*\") + Literal('end')\n\n        Note that the skipped text is returned with '_skipped' as a results name,\n        and to support having multiple skips in the same parser, the value returned is\n        a list of all skipped text.\n        \"\"\"\n        if other is Ellipsis:\n            return _PendingSkip(self)\n\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return And([self, other])\n\n    def __radd__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``+`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if other is Ellipsis:\n            return SkipTo(self)(\"_skipped*\") + self\n\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other + self\n\n    def __sub__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``-`` operator, returns :class:`And` with error stop\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return self + And._ErrorStop() + other\n\n    def __rsub__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``-`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other - self\n\n    def __mul__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``*`` operator, allows use of ``expr * 3`` in place of\n        ``expr + expr + expr``.  Expressions may also be multiplied by a 2-integer\n        tuple, similar to ``{min, max}`` multipliers in regular expressions.  Tuples\n        may also include ``None`` as in:\n        - ``expr*(n, None)`` or ``expr*(n, )`` is equivalent\n             to ``expr*n + ZeroOrMore(expr)``\n             (read as \"at least n instances of ``expr``\")\n        - ``expr*(None, n)`` is equivalent to ``expr*(0, n)``\n             (read as \"0 to n instances of ``expr``\")\n        - ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)``\n        - ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)``\n\n        Note that ``expr*(None, n)`` does not raise an exception if\n        more than n exprs exist in the input stream; that is,\n        ``expr*(None, n)`` does not enforce a maximum number of expr\n        occurrences.  If this behavior is desired, then write\n        ``expr*(None, n) + ~expr``\n        \"\"\"\n        if other is Ellipsis:\n            other = (0, None)\n        elif isinstance(other, tuple) and other[:1] == (Ellipsis,):\n            other = ((0,) + other[1:] + (None,))[:2]\n\n        if isinstance(other, int):\n            minElements, optElements = other, 0\n        elif isinstance(other, tuple):\n            other = tuple(o if o is not Ellipsis else None for o in other)\n            other = (other + (None, None))[:2]\n            if other[0] is None:\n                other = (0, other[1])\n            if isinstance(other[0], int) and other[1] is None:\n                if other[0] == 0:\n                    return ZeroOrMore(self)\n                if other[0] == 1:\n                    return OneOrMore(self)\n                else:\n                    return self * other[0] + ZeroOrMore(self)\n            elif isinstance(other[0], int) and isinstance(other[1], int):\n                minElements, optElements = other\n                optElements -= minElements\n            else:\n                raise TypeError(\n                    \"cannot multiply ParserElement and ({}) objects\".format(\n                        \",\".join(type(item).__name__ for item in other)\n                    )\n                )\n        else:\n            raise TypeError(\n                \"cannot multiply ParserElement and {} objects\".format(\n                    type(other).__name__\n                )\n            )\n\n        if minElements < 0:\n            raise ValueError(\"cannot multiply ParserElement by negative value\")\n        if optElements < 0:\n            raise ValueError(\n                \"second tuple value must be greater or equal to first tuple value\"\n            )\n        if minElements == optElements == 0:\n            return And([])\n\n        if optElements:\n\n            def makeOptionalList(n):\n                if n > 1:\n                    return Opt(self + makeOptionalList(n - 1))\n                else:\n                    return Opt(self)\n\n            if minElements:\n                if minElements == 1:\n                    ret = self + makeOptionalList(optElements)\n                else:\n                    ret = And([self] * minElements) + makeOptionalList(optElements)\n            else:\n                ret = makeOptionalList(optElements)\n        else:\n            if minElements == 1:\n                ret = self\n            else:\n                ret = And([self] * minElements)\n        return ret\n\n    def __rmul__(self, other) -> \"ParserElement\":\n        return self.__mul__(other)\n\n    def __or__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``|`` operator - returns :class:`MatchFirst`\n        \"\"\"\n        if other is Ellipsis:\n            return _PendingSkip(self, must_skip=True)\n\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return MatchFirst([self, other])\n\n    def __ror__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``|`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other | self\n\n    def __xor__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``^`` operator - returns :class:`Or`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return Or([self, other])\n\n    def __rxor__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``^`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other ^ self\n\n    def __and__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``&`` operator - returns :class:`Each`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return Each([self, other])\n\n    def __rand__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``&`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other & self\n\n    def __invert__(self) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``~`` operator - returns :class:`NotAny`\n        \"\"\"\n        return NotAny(self)\n\n    # disable __iter__ to override legacy use of sequential access to __getitem__ to\n    # iterate over a sequence\n    __iter__ = None\n\n    def __getitem__(self, key):\n        \"\"\"\n        use ``[]`` indexing notation as a short form for expression repetition:\n\n        - ``expr[n]`` is equivalent to ``expr*n``\n        - ``expr[m, n]`` is equivalent to ``expr*(m, n)``\n        - ``expr[n, ...]`` or ``expr[n,]`` is equivalent\n             to ``expr*n + ZeroOrMore(expr)``\n             (read as \"at least n instances of ``expr``\")\n        - ``expr[..., n]`` is equivalent to ``expr*(0, n)``\n             (read as \"0 to n instances of ``expr``\")\n        - ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)``\n        - ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)``\n\n        ``None`` may be used in place of ``...``.\n\n        Note that ``expr[..., n]`` and ``expr[m, n]``do not raise an exception\n        if more than ``n`` ``expr``s exist in the input stream.  If this behavior is\n        desired, then write ``expr[..., n] + ~expr``.\n        \"\"\"\n\n        # convert single arg keys to tuples\n        try:\n            if isinstance(key, str_type):\n                key = (key,)\n            iter(key)\n        except TypeError:\n            key = (key, key)\n\n        if len(key) > 2:\n            raise TypeError(\n                \"only 1 or 2 index arguments supported ({}{})\".format(\n                    key[:5], \"... [{}]\".format(len(key)) if len(key) > 5 else \"\"\n                )\n            )\n\n        # clip to 2 elements\n        ret = self * tuple(key[:2])\n        return ret\n\n    def __call__(self, name: str = None) -> \"ParserElement\":\n        \"\"\"\n        Shortcut for :class:`set_results_name`, with ``list_all_matches=False``.\n\n        If ``name`` is given with a trailing ``'*'`` character, then ``list_all_matches`` will be\n        passed as ``True``.\n\n        If ``name` is omitted, same as calling :class:`copy`.\n\n        Example::\n\n            # these are equivalent\n            userdata = Word(alphas).set_results_name(\"name\") + Word(nums + \"-\").set_results_name(\"socsecno\")\n            userdata = Word(alphas)(\"name\") + Word(nums + \"-\")(\"socsecno\")\n        \"\"\"\n        if name is not None:\n            return self._setResultsName(name)\n        else:\n            return self.copy()\n\n    def suppress(self) -> \"ParserElement\":\n        \"\"\"\n        Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from\n        cluttering up returned output.\n        \"\"\"\n        return Suppress(self)\n\n    def ignore_whitespace(self, recursive: bool = True) -> \"ParserElement\":\n        \"\"\"\n        Enables the skipping of whitespace before matching the characters in the\n        :class:`ParserElement`'s defined pattern.\n\n        :param recursive: If ``True`` (the default), also enable whitespace skipping in child elements (if any)\n        \"\"\"\n        self.skipWhitespace = True\n        return self\n\n    def leave_whitespace(self, recursive: bool = True) -> \"ParserElement\":\n        \"\"\"\n        Disables the skipping of whitespace before matching the characters in the\n        :class:`ParserElement`'s defined pattern.  This is normally only used internally by\n        the pyparsing module, but may be needed in some whitespace-sensitive grammars.\n\n        :param recursive: If true (the default), also disable whitespace skipping in child elements (if any)\n        \"\"\"\n        self.skipWhitespace = False\n        return self\n\n    def set_whitespace_chars(\n        self, chars: Union[Set[str], str], copy_defaults: bool = False\n    ) -> \"ParserElement\":\n        \"\"\"\n        Overrides the default whitespace chars\n        \"\"\"\n        self.skipWhitespace = True\n        self.whiteChars = set(chars)\n        self.copyDefaultWhiteChars = copy_defaults\n        return self\n\n    def parse_with_tabs(self) -> \"ParserElement\":\n        \"\"\"\n        Overrides default behavior to expand ``<TAB>`` s to spaces before parsing the input string.\n        Must be called before ``parse_string`` when the input grammar contains elements that\n        match ``<TAB>`` characters.\n        \"\"\"\n        self.keepTabs = True\n        return self\n\n    def ignore(self, other: \"ParserElement\") -> \"ParserElement\":\n        \"\"\"\n        Define expression to be ignored (e.g., comments) while doing pattern\n        matching; may be called repeatedly, to define multiple comment or other\n        ignorable patterns.\n\n        Example::\n\n            patt = Word(alphas)[1, ...]\n            patt.parse_string('ablaj /* comment */ lskjd')\n            # -> ['ablaj']\n\n            patt.ignore(c_style_comment)\n            patt.parse_string('ablaj /* comment */ lskjd')\n            # -> ['ablaj', 'lskjd']\n        \"\"\"\n        import typing\n\n        if isinstance(other, str_type):\n            other = Suppress(other)\n\n        if isinstance(other, Suppress):\n            if other not in self.ignoreExprs:\n                self.ignoreExprs.append(other)\n        else:\n            self.ignoreExprs.append(Suppress(other.copy()))\n        return self\n\n    def set_debug_actions(\n        self,\n        start_action: DebugStartAction,\n        success_action: DebugSuccessAction,\n        exception_action: DebugExceptionAction,\n    ) -> \"ParserElement\":\n        \"\"\"\n        Customize display of debugging messages while doing pattern matching:\n\n        - ``start_action`` - method to be called when an expression is about to be parsed;\n          should have the signature ``fn(input_string: str, location: int, expression: ParserElement, cache_hit: bool)``\n\n        - ``success_action`` - method to be called when an expression has successfully parsed;\n          should have the signature ``fn(input_string: str, start_location: int, end_location: int, expression: ParserELement, parsed_tokens: ParseResults, cache_hit: bool)``\n\n        - ``exception_action`` - method to be called when expression fails to parse;\n          should have the signature ``fn(input_string: str, location: int, expression: ParserElement, exception: Exception, cache_hit: bool)``\n        \"\"\"\n        self.debugActions = self.DebugActions(\n            start_action or _default_start_debug_action,\n            success_action or _default_success_debug_action,\n            exception_action or _default_exception_debug_action,\n        )\n        self.debug = True\n        return self\n\n    def set_debug(self, flag: bool = True) -> \"ParserElement\":\n        \"\"\"\n        Enable display of debugging messages while doing pattern matching.\n        Set ``flag`` to ``True`` to enable, ``False`` to disable.\n\n        Example::\n\n            wd = Word(alphas).set_name(\"alphaword\")\n            integer = Word(nums).set_name(\"numword\")\n            term = wd | integer\n\n            # turn on debugging for wd\n            wd.set_debug()\n\n            term[1, ...].parse_string(\"abc 123 xyz 890\")\n\n        prints::\n\n            Match alphaword at loc 0(1,1)\n            Matched alphaword -> ['abc']\n            Match alphaword at loc 3(1,4)\n            Exception raised:Expected alphaword (at char 4), (line:1, col:5)\n            Match alphaword at loc 7(1,8)\n            Matched alphaword -> ['xyz']\n            Match alphaword at loc 11(1,12)\n            Exception raised:Expected alphaword (at char 12), (line:1, col:13)\n            Match alphaword at loc 15(1,16)\n            Exception raised:Expected alphaword (at char 15), (line:1, col:16)\n\n        The output shown is that produced by the default debug actions - custom debug actions can be\n        specified using :class:`set_debug_actions`. Prior to attempting\n        to match the ``wd`` expression, the debugging message ``\"Match <exprname> at loc <n>(<line>,<col>)\"``\n        is shown. Then if the parse succeeds, a ``\"Matched\"`` message is shown, or an ``\"Exception raised\"``\n        message is shown. Also note the use of :class:`set_name` to assign a human-readable name to the expression,\n        which makes debugging and exception messages easier to understand - for instance, the default\n        name created for the :class:`Word` expression without calling ``set_name`` is ``\"W:(A-Za-z)\"``.\n        \"\"\"\n        if flag:\n            self.set_debug_actions(\n                _default_start_debug_action,\n                _default_success_debug_action,\n                _default_exception_debug_action,\n            )\n        else:\n            self.debug = False\n        return self\n\n    @property\n    def default_name(self) -> str:\n        if self._defaultName is None:\n            self._defaultName = self._generateDefaultName()\n        return self._defaultName\n\n    @abstractmethod\n    def _generateDefaultName(self):\n        \"\"\"\n        Child classes must define this method, which defines how the ``default_name`` is set.\n        \"\"\"\n\n    def set_name(self, name: str) -> \"ParserElement\":\n        \"\"\"\n        Define name for this expression, makes debugging and exception messages clearer.\n        Example::\n            Word(nums).parse_string(\"ABC\")  # -> Exception: Expected W:(0-9) (at char 0), (line:1, col:1)\n            Word(nums).set_name(\"integer\").parse_string(\"ABC\")  # -> Exception: Expected integer (at char 0), (line:1, col:1)\n        \"\"\"\n        self.customName = name\n        self.errmsg = \"Expected \" + self.name\n        if __diag__.enable_debug_on_named_expressions:\n            self.set_debug()\n        return self\n\n    @property\n    def name(self) -> str:\n        # This will use a user-defined name if available, but otherwise defaults back to the auto-generated name\n        return self.customName if self.customName is not None else self.default_name\n\n    def __str__(self) -> str:\n        return self.name\n\n    def __repr__(self) -> str:\n        return str(self)\n\n    def streamline(self) -> \"ParserElement\":\n        self.streamlined = True\n        self._defaultName = None\n        return self\n\n    def recurse(self) -> Sequence[\"ParserElement\"]:\n        return []\n\n    def _checkRecursion(self, parseElementList):\n        subRecCheckList = parseElementList[:] + [self]\n        for e in self.recurse():\n            e._checkRecursion(subRecCheckList)\n\n    def validate(self, validateTrace=None) -> None:\n        \"\"\"\n        Check defined expressions for valid structure, check for infinite recursive definitions.\n        \"\"\"\n        self._checkRecursion([])\n\n    def parse_file(\n        self,\n        file_or_filename: Union[str, Path, TextIO],\n        encoding: str = \"utf-8\",\n        parse_all: bool = False,\n        *,\n        parseAll: bool = False,\n    ) -> ParseResults:\n        \"\"\"\n        Execute the parse expression on the given file or filename.\n        If a filename is specified (instead of a file object),\n        the entire file is opened, read, and closed before parsing.\n        \"\"\"\n        parseAll = parseAll or parse_all\n        try:\n            file_contents = file_or_filename.read()\n        except AttributeError:\n            with open(file_or_filename, \"r\", encoding=encoding) as f:\n                file_contents = f.read()\n        try:\n            return self.parse_string(file_contents, parseAll)\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clears out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif isinstance(other, str_type):\n            return self.matches(other, parse_all=True)\n        elif isinstance(other, ParserElement):\n            return vars(self) == vars(other)\n        return False\n\n    def __hash__(self):\n        return id(self)\n\n    def matches(\n        self, test_string: str, parse_all: bool = True, *, parseAll: bool = True\n    ) -> bool:\n        \"\"\"\n        Method for quick testing of a parser against a test string. Good for simple\n        inline microtests of sub expressions while building up larger parser.\n\n        Parameters:\n        - ``test_string`` - to test against this expression for a match\n        - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests\n\n        Example::\n\n            expr = Word(nums)\n            assert expr.matches(\"100\")\n        \"\"\"\n        parseAll = parseAll and parse_all\n        try:\n            self.parse_string(str(test_string), parse_all=parseAll)\n            return True\n        except ParseBaseException:\n            return False\n\n    def run_tests(\n        self,\n        tests: Union[str, List[str]],\n        parse_all: bool = True,\n        comment: typing.Optional[Union[\"ParserElement\", str]] = \"#\",\n        full_dump: bool = True,\n        print_results: bool = True,\n        failure_tests: bool = False,\n        post_parse: Callable[[str, ParseResults], str] = None,\n        file: typing.Optional[TextIO] = None,\n        with_line_numbers: bool = False,\n        *,\n        parseAll: bool = True,\n        fullDump: bool = True,\n        printResults: bool = True,\n        failureTests: bool = False,\n        postParse: Callable[[str, ParseResults], str] = None,\n    ) -> Tuple[bool, List[Tuple[str, Union[ParseResults, Exception]]]]:\n        \"\"\"\n        Execute the parse expression on a series of test strings, showing each\n        test, the parsed results or where the parse failed. Quick and easy way to\n        run a parse expression against a list of sample strings.\n\n        Parameters:\n        - ``tests`` - a list of separate test strings, or a multiline string of test strings\n        - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests\n        - ``comment`` - (default= ``'#'``) - expression for indicating embedded comments in the test\n          string; pass None to disable comment filtering\n        - ``full_dump`` - (default= ``True``) - dump results as list followed by results names in nested outline;\n          if False, only dump nested list\n        - ``print_results`` - (default= ``True``) prints test output to stdout\n        - ``failure_tests`` - (default= ``False``) indicates if these tests are expected to fail parsing\n        - ``post_parse`` - (default= ``None``) optional callback for successful parse results; called as\n          `fn(test_string, parse_results)` and returns a string to be added to the test output\n        - ``file`` - (default= ``None``) optional file-like object to which test output will be written;\n          if None, will default to ``sys.stdout``\n        - ``with_line_numbers`` - default= ``False``) show test strings with line and column numbers\n\n        Returns: a (success, results) tuple, where success indicates that all tests succeeded\n        (or failed if ``failure_tests`` is True), and the results contain a list of lines of each\n        test's output\n\n        Example::\n\n            number_expr = pyparsing_common.number.copy()\n\n            result = number_expr.run_tests('''\n                # unsigned integer\n                100\n                # negative integer\n                -100\n                # float with scientific notation\n                6.02e23\n                # integer with scientific notation\n                1e-12\n                ''')\n            print(\"Success\" if result[0] else \"Failed!\")\n\n            result = number_expr.run_tests('''\n                # stray character\n                100Z\n                # missing leading digit before '.'\n                -.100\n                # too many '.'\n                3.14.159\n                ''', failure_tests=True)\n            print(\"Success\" if result[0] else \"Failed!\")\n\n        prints::\n\n            # unsigned integer\n            100\n            [100]\n\n            # negative integer\n            -100\n            [-100]\n\n            # float with scientific notation\n            6.02e23\n            [6.02e+23]\n\n            # integer with scientific notation\n            1e-12\n            [1e-12]\n\n            Success\n\n            # stray character\n            100Z\n               ^\n            FAIL: Expected end of text (at char 3), (line:1, col:4)\n\n            # missing leading digit before '.'\n            -.100\n            ^\n            FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)\n\n            # too many '.'\n            3.14.159\n                ^\n            FAIL: Expected end of text (at char 4), (line:1, col:5)\n\n            Success\n\n        Each test string must be on a single line. If you want to test a string that spans multiple\n        lines, create a test like this::\n\n            expr.run_tests(r\"this is a test\\\\n of strings that spans \\\\n 3 lines\")\n\n        (Note that this is a raw string literal, you must include the leading ``'r'``.)\n        \"\"\"\n        from .testing import pyparsing_test\n\n        parseAll = parseAll and parse_all\n        fullDump = fullDump and full_dump\n        printResults = printResults and print_results\n        failureTests = failureTests or failure_tests\n        postParse = postParse or post_parse\n        if isinstance(tests, str_type):\n            line_strip = type(tests).strip\n            tests = [line_strip(test_line) for test_line in tests.rstrip().splitlines()]\n        if isinstance(comment, str_type):\n            comment = Literal(comment)\n        if file is None:\n            file = sys.stdout\n        print_ = file.write\n\n        result: Union[ParseResults, Exception]\n        allResults = []\n        comments = []\n        success = True\n        NL = Literal(r\"\\n\").add_parse_action(replace_with(\"\\n\")).ignore(quoted_string)\n        BOM = \"\\ufeff\"\n        for t in tests:\n            if comment is not None and comment.matches(t, False) or comments and not t:\n                comments.append(\n                    pyparsing_test.with_line_numbers(t) if with_line_numbers else t\n                )\n                continue\n            if not t:\n                continue\n            out = [\n                \"\\n\" + \"\\n\".join(comments) if comments else \"\",\n                pyparsing_test.with_line_numbers(t) if with_line_numbers else t,\n            ]\n            comments = []\n            try:\n                # convert newline marks to actual newlines, and strip leading BOM if present\n                t = NL.transform_string(t.lstrip(BOM))\n                result = self.parse_string(t, parse_all=parseAll)\n            except ParseBaseException as pe:\n                fatal = \"(FATAL)\" if isinstance(pe, ParseFatalException) else \"\"\n                out.append(pe.explain())\n                out.append(\"FAIL: \" + str(pe))\n                if ParserElement.verbose_stacktrace:\n                    out.extend(traceback.format_tb(pe.__traceback__))\n                success = success and failureTests\n                result = pe\n            except Exception as exc:\n                out.append(\"FAIL-EXCEPTION: {}: {}\".format(type(exc).__name__, exc))\n                if ParserElement.verbose_stacktrace:\n                    out.extend(traceback.format_tb(exc.__traceback__))\n                success = success and failureTests\n                result = exc\n            else:\n                success = success and not failureTests\n                if postParse is not None:\n                    try:\n                        pp_value = postParse(t, result)\n                        if pp_value is not None:\n                            if isinstance(pp_value, ParseResults):\n                                out.append(pp_value.dump())\n                            else:\n                                out.append(str(pp_value))\n                        else:\n                            out.append(result.dump())\n                    except Exception as e:\n                        out.append(result.dump(full=fullDump))\n                        out.append(\n                            \"{} failed: {}: {}\".format(\n                                postParse.__name__, type(e).__name__, e\n                            )\n                        )\n                else:\n                    out.append(result.dump(full=fullDump))\n            out.append(\"\")\n\n            if printResults:\n                print_(\"\\n\".join(out))\n\n            allResults.append((t, result))\n\n        return success, allResults\n\n    def create_diagram(\n        self,\n        output_html: Union[TextIO, Path, str],\n        vertical: int = 3,\n        show_results_names: bool = False,\n        show_groups: bool = False,\n        **kwargs,\n    ) -> None:\n        \"\"\"\n        Create a railroad diagram for the parser.\n\n        Parameters:\n        - output_html (str or file-like object) - output target for generated\n          diagram HTML\n        - vertical (int) - threshold for formatting multiple alternatives vertically\n          instead of horizontally (default=3)\n        - show_results_names - bool flag whether diagram should show annotations for\n          defined results names\n        - show_groups - bool flag whether groups should be highlighted with an unlabeled surrounding box\n        Additional diagram-formatting keyword arguments can also be included;\n        see railroad.Diagram class.\n        \"\"\"\n\n        try:\n            from .diagram import to_railroad, railroad_to_html\n        except ImportError as ie:\n            raise Exception(\n                \"must ``pip install pyparsing[diagrams]`` to generate parser railroad diagrams\"\n            ) from ie\n\n        self.streamline()\n\n        railroad = to_railroad(\n            self,\n            vertical=vertical,\n            show_results_names=show_results_names,\n            show_groups=show_groups,\n            diagram_kwargs=kwargs,\n        )\n        if isinstance(output_html, (str, Path)):\n            with open(output_html, \"w\", encoding=\"utf-8\") as diag_file:\n                diag_file.write(railroad_to_html(railroad))\n        else:\n            # we were passed a file-like object, just write to it\n            output_html.write(railroad_to_html(railroad))\n\n    setDefaultWhitespaceChars = set_default_whitespace_chars\n    inlineLiteralsUsing = inline_literals_using\n    setResultsName = set_results_name\n    setBreak = set_break\n    setParseAction = set_parse_action\n    addParseAction = add_parse_action\n    addCondition = add_condition\n    setFailAction = set_fail_action\n    tryParse = try_parse\n    canParseNext = can_parse_next\n    resetCache = reset_cache\n    enableLeftRecursion = enable_left_recursion\n    enablePackrat = enable_packrat\n    parseString = parse_string\n    scanString = scan_string\n    searchString = search_string\n    transformString = transform_string\n    setWhitespaceChars = set_whitespace_chars\n    parseWithTabs = parse_with_tabs\n    setDebugActions = set_debug_actions\n    setDebug = set_debug\n    defaultName = default_name\n    setName = set_name\n    parseFile = parse_file\n    runTests = run_tests\n    ignoreWhitespace = ignore_whitespace\n    leaveWhitespace = leave_whitespace\n\n\nclass _PendingSkip(ParserElement):\n    # internal placeholder class to hold a place were '...' is added to a parser element,\n    # once another ParserElement is added, this placeholder will be replaced with a SkipTo\n    def __init__(self, expr: ParserElement, must_skip: bool = False):\n        super().__init__()\n        self.anchor = expr\n        self.must_skip = must_skip\n\n    def _generateDefaultName(self):\n        return str(self.anchor + Empty()).replace(\"Empty\", \"...\")\n\n    def __add__(self, other) -> \"ParserElement\":\n        skipper = SkipTo(other).set_name(\"...\")(\"_skipped*\")\n        if self.must_skip:\n\n            def must_skip(t):\n                if not t._skipped or t._skipped.as_list() == [\"\"]:\n                    del t[0]\n                    t.pop(\"_skipped\", None)\n\n            def show_skip(t):\n                if t._skipped.as_list()[-1:] == [\"\"]:\n                    t.pop(\"_skipped\")\n                    t[\"_skipped\"] = \"missing <\" + repr(self.anchor) + \">\"\n\n            return (\n                self.anchor + skipper().add_parse_action(must_skip)\n                | skipper().add_parse_action(show_skip)\n            ) + other\n\n        return self.anchor + skipper + other\n\n    def __repr__(self):\n        return self.defaultName\n\n    def parseImpl(self, *args):\n        raise Exception(\n            \"use of `...` expression without following SkipTo target expression\"\n        )\n\n\nclass Token(ParserElement):\n    \"\"\"Abstract :class:`ParserElement` subclass, for defining atomic\n    matching patterns.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__(savelist=False)\n\n    def _generateDefaultName(self):\n        return type(self).__name__\n\n\nclass Empty(Token):\n    \"\"\"\n    An empty token, will always match.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n\n\nclass NoMatch(Token):\n    \"\"\"\n    A token that will never match.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n        self.errmsg = \"Unmatchable token\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass Literal(Token):\n    \"\"\"\n    Token to exactly match a specified string.\n\n    Example::\n\n        Literal('blah').parse_string('blah')  # -> ['blah']\n        Literal('blah').parse_string('blahfooblah')  # -> ['blah']\n        Literal('blah').parse_string('bla')  # -> Exception: Expected \"blah\"\n\n    For case-insensitive matching, use :class:`CaselessLiteral`.\n\n    For keyword matching (force word break before and after the matched string),\n    use :class:`Keyword` or :class:`CaselessKeyword`.\n    \"\"\"\n\n    def __init__(self, match_string: str = \"\", *, matchString: str = \"\"):\n        super().__init__()\n        match_string = matchString or match_string\n        self.match = match_string\n        self.matchLen = len(match_string)\n        try:\n            self.firstMatchChar = match_string[0]\n        except IndexError:\n            raise ValueError(\"null string passed to Literal; use Empty() instead\")\n        self.errmsg = \"Expected \" + self.name\n        self.mayReturnEmpty = False\n        self.mayIndexError = False\n\n        # Performance tuning: modify __class__ to select\n        # a parseImpl optimized for single-character check\n        if self.matchLen == 1 and type(self) is Literal:\n            self.__class__ = _SingleCharLiteral\n\n    def _generateDefaultName(self):\n        return repr(self.match)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc] == self.firstMatchChar and instring.startswith(\n            self.match, loc\n        ):\n            return loc + self.matchLen, self.match\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass _SingleCharLiteral(Literal):\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc] == self.firstMatchChar:\n            return loc + 1, self.match\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nParserElement._literalStringClass = Literal\n\n\nclass Keyword(Token):\n    \"\"\"\n    Token to exactly match a specified string as a keyword, that is,\n    it must be immediately followed by a non-keyword character.  Compare\n    with :class:`Literal`:\n\n    - ``Literal(\"if\")`` will match the leading ``'if'`` in\n      ``'ifAndOnlyIf'``.\n    - ``Keyword(\"if\")`` will not; it will only match the leading\n      ``'if'`` in ``'if x=1'``, or ``'if(y==2)'``\n\n    Accepts two optional constructor arguments in addition to the\n    keyword string:\n\n    - ``identChars`` is a string of characters that would be valid\n      identifier characters, defaulting to all alphanumerics + \"_\" and\n      \"$\"\n    - ``caseless`` allows case-insensitive matching, default is ``False``.\n\n    Example::\n\n        Keyword(\"start\").parse_string(\"start\")  # -> ['start']\n        Keyword(\"start\").parse_string(\"starting\")  # -> Exception\n\n    For case-insensitive matching, use :class:`CaselessKeyword`.\n    \"\"\"\n\n    DEFAULT_KEYWORD_CHARS = alphanums + \"_$\"\n\n    def __init__(\n        self,\n        match_string: str = \"\",\n        ident_chars: typing.Optional[str] = None,\n        caseless: bool = False,\n        *,\n        matchString: str = \"\",\n        identChars: typing.Optional[str] = None,\n    ):\n        super().__init__()\n        identChars = identChars or ident_chars\n        if identChars is None:\n            identChars = Keyword.DEFAULT_KEYWORD_CHARS\n        match_string = matchString or match_string\n        self.match = match_string\n        self.matchLen = len(match_string)\n        try:\n            self.firstMatchChar = match_string[0]\n        except IndexError:\n            raise ValueError(\"null string passed to Keyword; use Empty() instead\")\n        self.errmsg = \"Expected {} {}\".format(type(self).__name__, self.name)\n        self.mayReturnEmpty = False\n        self.mayIndexError = False\n        self.caseless = caseless\n        if caseless:\n            self.caselessmatch = match_string.upper()\n            identChars = identChars.upper()\n        self.identChars = set(identChars)\n\n    def _generateDefaultName(self):\n        return repr(self.match)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        errmsg = self.errmsg\n        errloc = loc\n        if self.caseless:\n            if instring[loc : loc + self.matchLen].upper() == self.caselessmatch:\n                if loc == 0 or instring[loc - 1].upper() not in self.identChars:\n                    if (\n                        loc >= len(instring) - self.matchLen\n                        or instring[loc + self.matchLen].upper() not in self.identChars\n                    ):\n                        return loc + self.matchLen, self.match\n                    else:\n                        # followed by keyword char\n                        errmsg += \", was immediately followed by keyword character\"\n                        errloc = loc + self.matchLen\n                else:\n                    # preceded by keyword char\n                    errmsg += \", keyword was immediately preceded by keyword character\"\n                    errloc = loc - 1\n            # else no match just raise plain exception\n\n        else:\n            if (\n                instring[loc] == self.firstMatchChar\n                and self.matchLen == 1\n                or instring.startswith(self.match, loc)\n            ):\n                if loc == 0 or instring[loc - 1] not in self.identChars:\n                    if (\n                        loc >= len(instring) - self.matchLen\n                        or instring[loc + self.matchLen] not in self.identChars\n                    ):\n                        return loc + self.matchLen, self.match\n                    else:\n                        # followed by keyword char\n                        errmsg += (\n                            \", keyword was immediately followed by keyword character\"\n                        )\n                        errloc = loc + self.matchLen\n                else:\n                    # preceded by keyword char\n                    errmsg += \", keyword was immediately preceded by keyword character\"\n                    errloc = loc - 1\n            # else no match just raise plain exception\n\n        raise ParseException(instring, errloc, errmsg, self)\n\n    @staticmethod\n    def set_default_keyword_chars(chars) -> None:\n        \"\"\"\n        Overrides the default characters used by :class:`Keyword` expressions.\n        \"\"\"\n        Keyword.DEFAULT_KEYWORD_CHARS = chars\n\n    setDefaultKeywordChars = set_default_keyword_chars\n\n\nclass CaselessLiteral(Literal):\n    \"\"\"\n    Token to match a specified string, ignoring case of letters.\n    Note: the matched results will always be in the case of the given\n    match string, NOT the case of the input text.\n\n    Example::\n\n        CaselessLiteral(\"CMD\")[1, ...].parse_string(\"cmd CMD Cmd10\")\n        # -> ['CMD', 'CMD', 'CMD']\n\n    (Contrast with example for :class:`CaselessKeyword`.)\n    \"\"\"\n\n    def __init__(self, match_string: str = \"\", *, matchString: str = \"\"):\n        match_string = matchString or match_string\n        super().__init__(match_string.upper())\n        # Preserve the defining literal.\n        self.returnString = match_string\n        self.errmsg = \"Expected \" + self.name\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc : loc + self.matchLen].upper() == self.match:\n            return loc + self.matchLen, self.returnString\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass CaselessKeyword(Keyword):\n    \"\"\"\n    Caseless version of :class:`Keyword`.\n\n    Example::\n\n        CaselessKeyword(\"CMD\")[1, ...].parse_string(\"cmd CMD Cmd10\")\n        # -> ['CMD', 'CMD']\n\n    (Contrast with example for :class:`CaselessLiteral`.)\n    \"\"\"\n\n    def __init__(\n        self,\n        match_string: str = \"\",\n        ident_chars: typing.Optional[str] = None,\n        *,\n        matchString: str = \"\",\n        identChars: typing.Optional[str] = None,\n    ):\n        identChars = identChars or ident_chars\n        match_string = matchString or match_string\n        super().__init__(match_string, identChars, caseless=True)\n\n\nclass CloseMatch(Token):\n    \"\"\"A variation on :class:`Literal` which matches \"close\" matches,\n    that is, strings with at most 'n' mismatching characters.\n    :class:`CloseMatch` takes parameters:\n\n    - ``match_string`` - string to be matched\n    - ``caseless`` - a boolean indicating whether to ignore casing when comparing characters\n    - ``max_mismatches`` - (``default=1``) maximum number of\n      mismatches allowed to count as a match\n\n    The results from a successful parse will contain the matched text\n    from the input string and the following named results:\n\n    - ``mismatches`` - a list of the positions within the\n      match_string where mismatches were found\n    - ``original`` - the original match_string used to compare\n      against the input string\n\n    If ``mismatches`` is an empty list, then the match was an exact\n    match.\n\n    Example::\n\n        patt = CloseMatch(\"ATCATCGAATGGA\")\n        patt.parse_string(\"ATCATCGAAXGGA\") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']})\n        patt.parse_string(\"ATCAXCGAAXGGA\") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1)\n\n        # exact match\n        patt.parse_string(\"ATCATCGAATGGA\") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']})\n\n        # close match allowing up to 2 mismatches\n        patt = CloseMatch(\"ATCATCGAATGGA\", max_mismatches=2)\n        patt.parse_string(\"ATCAXCGAAXGGA\") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']})\n    \"\"\"\n\n    def __init__(\n        self,\n        match_string: str,\n        max_mismatches: int = None,\n        *,\n        maxMismatches: int = 1,\n        caseless=False,\n    ):\n        maxMismatches = max_mismatches if max_mismatches is not None else maxMismatches\n        super().__init__()\n        self.match_string = match_string\n        self.maxMismatches = maxMismatches\n        self.errmsg = \"Expected {!r} (with up to {} mismatches)\".format(\n            self.match_string, self.maxMismatches\n        )\n        self.caseless = caseless\n        self.mayIndexError = False\n        self.mayReturnEmpty = False\n\n    def _generateDefaultName(self):\n        return \"{}:{!r}\".format(type(self).__name__, self.match_string)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        start = loc\n        instrlen = len(instring)\n        maxloc = start + len(self.match_string)\n\n        if maxloc <= instrlen:\n            match_string = self.match_string\n            match_stringloc = 0\n            mismatches = []\n            maxMismatches = self.maxMismatches\n\n            for match_stringloc, s_m in enumerate(\n                zip(instring[loc:maxloc], match_string)\n            ):\n                src, mat = s_m\n                if self.caseless:\n                    src, mat = src.lower(), mat.lower()\n\n                if src != mat:\n                    mismatches.append(match_stringloc)\n                    if len(mismatches) > maxMismatches:\n                        break\n            else:\n                loc = start + match_stringloc + 1\n                results = ParseResults([instring[start:loc]])\n                results[\"original\"] = match_string\n                results[\"mismatches\"] = mismatches\n                return loc, results\n\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass Word(Token):\n    \"\"\"Token for matching words composed of allowed character sets.\n    Parameters:\n    - ``init_chars`` - string of all characters that should be used to\n      match as a word; \"ABC\" will match \"AAA\", \"ABAB\", \"CBAC\", etc.;\n      if ``body_chars`` is also specified, then this is the string of\n      initial characters\n    - ``body_chars`` - string of characters that\n      can be used for matching after a matched initial character as\n      given in ``init_chars``; if omitted, same as the initial characters\n      (default=``None``)\n    - ``min`` - minimum number of characters to match (default=1)\n    - ``max`` - maximum number of characters to match (default=0)\n    - ``exact`` - exact number of characters to match (default=0)\n    - ``as_keyword`` - match as a keyword (default=``False``)\n    - ``exclude_chars`` - characters that might be\n      found in the input ``body_chars`` string but which should not be\n      accepted for matching ;useful to define a word of all\n      printables except for one or two characters, for instance\n      (default=``None``)\n\n    :class:`srange` is useful for defining custom character set strings\n    for defining :class:`Word` expressions, using range notation from\n    regular expression character sets.\n\n    A common mistake is to use :class:`Word` to match a specific literal\n    string, as in ``Word(\"Address\")``. Remember that :class:`Word`\n    uses the string argument to define *sets* of matchable characters.\n    This expression would match \"Add\", \"AAA\", \"dAred\", or any other word\n    made up of the characters 'A', 'd', 'r', 'e', and 's'. To match an\n    exact literal string, use :class:`Literal` or :class:`Keyword`.\n\n    pyparsing includes helper strings for building Words:\n\n    - :class:`alphas`\n    - :class:`nums`\n    - :class:`alphanums`\n    - :class:`hexnums`\n    - :class:`alphas8bit` (alphabetic characters in ASCII range 128-255\n      - accented, tilded, umlauted, etc.)\n    - :class:`punc8bit` (non-alphabetic characters in ASCII range\n      128-255 - currency, symbols, superscripts, diacriticals, etc.)\n    - :class:`printables` (any non-whitespace character)\n\n    ``alphas``, ``nums``, and ``printables`` are also defined in several\n    Unicode sets - see :class:`pyparsing_unicode``.\n\n    Example::\n\n        # a word composed of digits\n        integer = Word(nums) # equivalent to Word(\"0123456789\") or Word(srange(\"0-9\"))\n\n        # a word with a leading capital, and zero or more lowercase\n        capital_word = Word(alphas.upper(), alphas.lower())\n\n        # hostnames are alphanumeric, with leading alpha, and '-'\n        hostname = Word(alphas, alphanums + '-')\n\n        # roman numeral (not a strict parser, accepts invalid mix of characters)\n        roman = Word(\"IVXLCDM\")\n\n        # any string of non-whitespace characters, except for ','\n        csv_value = Word(printables, exclude_chars=\",\")\n    \"\"\"\n\n    def __init__(\n        self,\n        init_chars: str = \"\",\n        body_chars: typing.Optional[str] = None,\n        min: int = 1,\n        max: int = 0,\n        exact: int = 0,\n        as_keyword: bool = False,\n        exclude_chars: typing.Optional[str] = None,\n        *,\n        initChars: typing.Optional[str] = None,\n        bodyChars: typing.Optional[str] = None,\n        asKeyword: bool = False,\n        excludeChars: typing.Optional[str] = None,\n    ):\n        initChars = initChars or init_chars\n        bodyChars = bodyChars or body_chars\n        asKeyword = asKeyword or as_keyword\n        excludeChars = excludeChars or exclude_chars\n        super().__init__()\n        if not initChars:\n            raise ValueError(\n                \"invalid {}, initChars cannot be empty string\".format(\n                    type(self).__name__\n                )\n            )\n\n        initChars = set(initChars)\n        self.initChars = initChars\n        if excludeChars:\n            excludeChars = set(excludeChars)\n            initChars -= excludeChars\n            if bodyChars:\n                bodyChars = set(bodyChars) - excludeChars\n        self.initCharsOrig = \"\".join(sorted(initChars))\n\n        if bodyChars:\n            self.bodyCharsOrig = \"\".join(sorted(bodyChars))\n            self.bodyChars = set(bodyChars)\n        else:\n            self.bodyCharsOrig = \"\".join(sorted(initChars))\n            self.bodyChars = set(initChars)\n\n        self.maxSpecified = max > 0\n\n        if min < 1:\n            raise ValueError(\n                \"cannot specify a minimum length < 1; use Opt(Word()) if zero-length word is permitted\"\n            )\n\n        self.minLen = min\n\n        if max > 0:\n            self.maxLen = max\n        else:\n            self.maxLen = _MAX_INT\n\n        if exact > 0:\n            self.maxLen = exact\n            self.minLen = exact\n\n        self.errmsg = \"Expected \" + self.name\n        self.mayIndexError = False\n        self.asKeyword = asKeyword\n\n        # see if we can make a regex for this Word\n        if \" \" not in self.initChars | self.bodyChars and (min == 1 and exact == 0):\n            if self.bodyChars == self.initChars:\n                if max == 0:\n                    repeat = \"+\"\n                elif max == 1:\n                    repeat = \"\"\n                else:\n                    repeat = \"{{{},{}}}\".format(\n                        self.minLen, \"\" if self.maxLen == _MAX_INT else self.maxLen\n                    )\n                self.reString = \"[{}]{}\".format(\n                    _collapse_string_to_ranges(self.initChars),\n                    repeat,\n                )\n            elif len(self.initChars) == 1:\n                if max == 0:\n                    repeat = \"*\"\n                else:\n                    repeat = \"{{0,{}}}\".format(max - 1)\n                self.reString = \"{}[{}]{}\".format(\n                    re.escape(self.initCharsOrig),\n                    _collapse_string_to_ranges(self.bodyChars),\n                    repeat,\n                )\n            else:\n                if max == 0:\n                    repeat = \"*\"\n                elif max == 2:\n                    repeat = \"\"\n                else:\n                    repeat = \"{{0,{}}}\".format(max - 1)\n                self.reString = \"[{}][{}]{}\".format(\n                    _collapse_string_to_ranges(self.initChars),\n                    _collapse_string_to_ranges(self.bodyChars),\n                    repeat,\n                )\n            if self.asKeyword:\n                self.reString = r\"\\b\" + self.reString + r\"\\b\"\n\n            try:\n                self.re = re.compile(self.reString)\n            except re.error:\n                self.re = None\n            else:\n                self.re_match = self.re.match\n                self.__class__ = _WordRegex\n\n    def _generateDefaultName(self):\n        def charsAsStr(s):\n            max_repr_len = 16\n            s = _collapse_string_to_ranges(s, re_escape=False)\n            if len(s) > max_repr_len:\n                return s[: max_repr_len - 3] + \"...\"\n            else:\n                return s\n\n        if self.initChars != self.bodyChars:\n            base = \"W:({}, {})\".format(\n                charsAsStr(self.initChars), charsAsStr(self.bodyChars)\n            )\n        else:\n            base = \"W:({})\".format(charsAsStr(self.initChars))\n\n        # add length specification\n        if self.minLen > 1 or self.maxLen != _MAX_INT:\n            if self.minLen == self.maxLen:\n                if self.minLen == 1:\n                    return base[2:]\n                else:\n                    return base + \"{{{}}}\".format(self.minLen)\n            elif self.maxLen == _MAX_INT:\n                return base + \"{{{},...}}\".format(self.minLen)\n            else:\n                return base + \"{{{},{}}}\".format(self.minLen, self.maxLen)\n        return base\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc] not in self.initChars:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        start = loc\n        loc += 1\n        instrlen = len(instring)\n        bodychars = self.bodyChars\n        maxloc = start + self.maxLen\n        maxloc = min(maxloc, instrlen)\n        while loc < maxloc and instring[loc] in bodychars:\n            loc += 1\n\n        throwException = False\n        if loc - start < self.minLen:\n            throwException = True\n        elif self.maxSpecified and loc < instrlen and instring[loc] in bodychars:\n            throwException = True\n        elif self.asKeyword:\n            if (\n                start > 0\n                and instring[start - 1] in bodychars\n                or loc < instrlen\n                and instring[loc] in bodychars\n            ):\n                throwException = True\n\n        if throwException:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        return loc, instring[start:loc]\n\n\nclass _WordRegex(Word):\n    def parseImpl(self, instring, loc, doActions=True):\n        result = self.re_match(instring, loc)\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        return loc, result.group()\n\n\nclass Char(_WordRegex):\n    \"\"\"A short-cut class for defining :class:`Word` ``(characters, exact=1)``,\n    when defining a match of any single character in a string of\n    characters.\n    \"\"\"\n\n    def __init__(\n        self,\n        charset: str,\n        as_keyword: bool = False,\n        exclude_chars: typing.Optional[str] = None,\n        *,\n        asKeyword: bool = False,\n        excludeChars: typing.Optional[str] = None,\n    ):\n        asKeyword = asKeyword or as_keyword\n        excludeChars = excludeChars or exclude_chars\n        super().__init__(\n            charset, exact=1, asKeyword=asKeyword, excludeChars=excludeChars\n        )\n        self.reString = \"[{}]\".format(_collapse_string_to_ranges(self.initChars))\n        if asKeyword:\n            self.reString = r\"\\b{}\\b\".format(self.reString)\n        self.re = re.compile(self.reString)\n        self.re_match = self.re.match\n\n\nclass Regex(Token):\n    r\"\"\"Token for matching strings that match a given regular\n    expression. Defined with string specifying the regular expression in\n    a form recognized by the stdlib Python  `re module <https://docs.python.org/3/library/re.html>`_.\n    If the given regex contains named groups (defined using ``(?P<name>...)``),\n    these will be preserved as named :class:`ParseResults`.\n\n    If instead of the Python stdlib ``re`` module you wish to use a different RE module\n    (such as the ``regex`` module), you can do so by building your ``Regex`` object with\n    a compiled RE that was compiled using ``regex``.\n\n    Example::\n\n        realnum = Regex(r\"[+-]?\\d+\\.\\d*\")\n        # ref: https://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression\n        roman = Regex(r\"M{0,4}(CM|CD|D?{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\")\n\n        # named fields in a regex will be returned as named results\n        date = Regex(r'(?P<year>\\d{4})-(?P<month>\\d\\d?)-(?P<day>\\d\\d?)')\n\n        # the Regex class will accept re's compiled using the regex module\n        import regex\n        parser = pp.Regex(regex.compile(r'[0-9]'))\n    \"\"\"\n\n    def __init__(\n        self,\n        pattern: Any,\n        flags: Union[re.RegexFlag, int] = 0,\n        as_group_list: bool = False,\n        as_match: bool = False,\n        *,\n        asGroupList: bool = False,\n        asMatch: bool = False,\n    ):\n        \"\"\"The parameters ``pattern`` and ``flags`` are passed\n        to the ``re.compile()`` function as-is. See the Python\n        `re module <https://docs.python.org/3/library/re.html>`_ module for an\n        explanation of the acceptable patterns and flags.\n        \"\"\"\n        super().__init__()\n        asGroupList = asGroupList or as_group_list\n        asMatch = asMatch or as_match\n\n        if isinstance(pattern, str_type):\n            if not pattern:\n                raise ValueError(\"null string passed to Regex; use Empty() instead\")\n\n            self._re = None\n            self.reString = self.pattern = pattern\n            self.flags = flags\n\n        elif hasattr(pattern, \"pattern\") and hasattr(pattern, \"match\"):\n            self._re = pattern\n            self.pattern = self.reString = pattern.pattern\n            self.flags = flags\n\n        else:\n            raise TypeError(\n                \"Regex may only be constructed with a string or a compiled RE object\"\n            )\n\n        self.errmsg = \"Expected \" + self.name\n        self.mayIndexError = False\n        self.asGroupList = asGroupList\n        self.asMatch = asMatch\n        if self.asGroupList:\n            self.parseImpl = self.parseImplAsGroupList\n        if self.asMatch:\n            self.parseImpl = self.parseImplAsMatch\n\n    @cached_property\n    def re(self):\n        if self._re:\n            return self._re\n        else:\n            try:\n                return re.compile(self.pattern, self.flags)\n            except re.error:\n                raise ValueError(\n                    \"invalid pattern ({!r}) passed to Regex\".format(self.pattern)\n                )\n\n    @cached_property\n    def re_match(self):\n        return self.re.match\n\n    @cached_property\n    def mayReturnEmpty(self):\n        return self.re_match(\"\") is not None\n\n    def _generateDefaultName(self):\n        return \"Re:({})\".format(repr(self.pattern).replace(\"\\\\\\\\\", \"\\\\\"))\n\n    def parseImpl(self, instring, loc, doActions=True):\n        result = self.re_match(instring, loc)\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        ret = ParseResults(result.group())\n        d = result.groupdict()\n        if d:\n            for k, v in d.items():\n                ret[k] = v\n        return loc, ret\n\n    def parseImplAsGroupList(self, instring, loc, doActions=True):\n        result = self.re_match(instring, loc)\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        ret = result.groups()\n        return loc, ret\n\n    def parseImplAsMatch(self, instring, loc, doActions=True):\n        result = self.re_match(instring, loc)\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        ret = result\n        return loc, ret\n\n    def sub(self, repl: str) -> ParserElement:\n        r\"\"\"\n        Return :class:`Regex` with an attached parse action to transform the parsed\n        result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_.\n\n        Example::\n\n            make_html = Regex(r\"(\\w+):(.*?):\").sub(r\"<\\1>\\2</\\1>\")\n            print(make_html.transform_string(\"h1:main title:\"))\n            # prints \"<h1>main title</h1>\"\n        \"\"\"\n        if self.asGroupList:\n            raise TypeError(\"cannot use sub() with Regex(asGroupList=True)\")\n\n        if self.asMatch and callable(repl):\n            raise TypeError(\"cannot use sub() with a callable with Regex(asMatch=True)\")\n\n        if self.asMatch:\n\n            def pa(tokens):\n                return tokens[0].expand(repl)\n\n        else:\n\n            def pa(tokens):\n                return self.re.sub(repl, tokens[0])\n\n        return self.add_parse_action(pa)\n\n\nclass QuotedString(Token):\n    r\"\"\"\n    Token for matching strings that are delimited by quoting characters.\n\n    Defined with the following parameters:\n\n    - ``quote_char`` - string of one or more characters defining the\n      quote delimiting string\n    - ``esc_char`` - character to re_escape quotes, typically backslash\n      (default= ``None``)\n    - ``esc_quote`` - special quote sequence to re_escape an embedded quote\n      string (such as SQL's ``\"\"`` to re_escape an embedded ``\"``)\n      (default= ``None``)\n    - ``multiline`` - boolean indicating whether quotes can span\n      multiple lines (default= ``False``)\n    - ``unquote_results`` - boolean indicating whether the matched text\n      should be unquoted (default= ``True``)\n    - ``end_quote_char`` - string of one or more characters defining the\n      end of the quote delimited string (default= ``None``  => same as\n      quote_char)\n    - ``convert_whitespace_escapes`` - convert escaped whitespace\n      (``'\\t'``, ``'\\n'``, etc.) to actual whitespace\n      (default= ``True``)\n\n    Example::\n\n        qs = QuotedString('\"')\n        print(qs.search_string('lsjdf \"This is the quote\" sldjf'))\n        complex_qs = QuotedString('{{', end_quote_char='}}')\n        print(complex_qs.search_string('lsjdf {{This is the \"quote\"}} sldjf'))\n        sql_qs = QuotedString('\"', esc_quote='\"\"')\n        print(sql_qs.search_string('lsjdf \"This is the quote with \"\"embedded\"\" quotes\" sldjf'))\n\n    prints::\n\n        [['This is the quote']]\n        [['This is the \"quote\"']]\n        [['This is the quote with \"embedded\" quotes']]\n    \"\"\"\n    ws_map = ((r\"\\t\", \"\\t\"), (r\"\\n\", \"\\n\"), (r\"\\f\", \"\\f\"), (r\"\\r\", \"\\r\"))\n\n    def __init__(\n        self,\n        quote_char: str = \"\",\n        esc_char: typing.Optional[str] = None,\n        esc_quote: typing.Optional[str] = None,\n        multiline: bool = False,\n        unquote_results: bool = True,\n        end_quote_char: typing.Optional[str] = None,\n        convert_whitespace_escapes: bool = True,\n        *,\n        quoteChar: str = \"\",\n        escChar: typing.Optional[str] = None,\n        escQuote: typing.Optional[str] = None,\n        unquoteResults: bool = True,\n        endQuoteChar: typing.Optional[str] = None,\n        convertWhitespaceEscapes: bool = True,\n    ):\n        super().__init__()\n        escChar = escChar or esc_char\n        escQuote = escQuote or esc_quote\n        unquoteResults = unquoteResults and unquote_results\n        endQuoteChar = endQuoteChar or end_quote_char\n        convertWhitespaceEscapes = (\n            convertWhitespaceEscapes and convert_whitespace_escapes\n        )\n        quote_char = quoteChar or quote_char\n\n        # remove white space from quote chars - wont work anyway\n        quote_char = quote_char.strip()\n        if not quote_char:\n            raise ValueError(\"quote_char cannot be the empty string\")\n\n        if endQuoteChar is None:\n            endQuoteChar = quote_char\n        else:\n            endQuoteChar = endQuoteChar.strip()\n            if not endQuoteChar:\n                raise ValueError(\"endQuoteChar cannot be the empty string\")\n\n        self.quoteChar = quote_char\n        self.quoteCharLen = len(quote_char)\n        self.firstQuoteChar = quote_char[0]\n        self.endQuoteChar = endQuoteChar\n        self.endQuoteCharLen = len(endQuoteChar)\n        self.escChar = escChar\n        self.escQuote = escQuote\n        self.unquoteResults = unquoteResults\n        self.convertWhitespaceEscapes = convertWhitespaceEscapes\n\n        sep = \"\"\n        inner_pattern = \"\"\n\n        if escQuote:\n            inner_pattern += r\"{}(?:{})\".format(sep, re.escape(escQuote))\n            sep = \"|\"\n\n        if escChar:\n            inner_pattern += r\"{}(?:{}.)\".format(sep, re.escape(escChar))\n            sep = \"|\"\n            self.escCharReplacePattern = re.escape(self.escChar) + \"(.)\"\n\n        if len(self.endQuoteChar) > 1:\n            inner_pattern += (\n                \"{}(?:\".format(sep)\n                + \"|\".join(\n                    \"(?:{}(?!{}))\".format(\n                        re.escape(self.endQuoteChar[:i]),\n                        re.escape(self.endQuoteChar[i:]),\n                    )\n                    for i in range(len(self.endQuoteChar) - 1, 0, -1)\n                )\n                + \")\"\n            )\n            sep = \"|\"\n\n        if multiline:\n            self.flags = re.MULTILINE | re.DOTALL\n            inner_pattern += r\"{}(?:[^{}{}])\".format(\n                sep,\n                _escape_regex_range_chars(self.endQuoteChar[0]),\n                (_escape_regex_range_chars(escChar) if escChar is not None else \"\"),\n            )\n        else:\n            self.flags = 0\n            inner_pattern += r\"{}(?:[^{}\\n\\r{}])\".format(\n                sep,\n                _escape_regex_range_chars(self.endQuoteChar[0]),\n                (_escape_regex_range_chars(escChar) if escChar is not None else \"\"),\n            )\n\n        self.pattern = \"\".join(\n            [\n                re.escape(self.quoteChar),\n                \"(?:\",\n                inner_pattern,\n                \")*\",\n                re.escape(self.endQuoteChar),\n            ]\n        )\n\n        try:\n            self.re = re.compile(self.pattern, self.flags)\n            self.reString = self.pattern\n            self.re_match = self.re.match\n        except re.error:\n            raise ValueError(\n                \"invalid pattern {!r} passed to Regex\".format(self.pattern)\n            )\n\n        self.errmsg = \"Expected \" + self.name\n        self.mayIndexError = False\n        self.mayReturnEmpty = True\n\n    def _generateDefaultName(self):\n        if self.quoteChar == self.endQuoteChar and isinstance(self.quoteChar, str_type):\n            return \"string enclosed in {!r}\".format(self.quoteChar)\n\n        return \"quoted string, starting with {} ending with {}\".format(\n            self.quoteChar, self.endQuoteChar\n        )\n\n    def parseImpl(self, instring, loc, doActions=True):\n        result = (\n            instring[loc] == self.firstQuoteChar\n            and self.re_match(instring, loc)\n            or None\n        )\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        ret = result.group()\n\n        if self.unquoteResults:\n\n            # strip off quotes\n            ret = ret[self.quoteCharLen : -self.endQuoteCharLen]\n\n            if isinstance(ret, str_type):\n                # replace escaped whitespace\n                if \"\\\\\" in ret and self.convertWhitespaceEscapes:\n                    for wslit, wschar in self.ws_map:\n                        ret = ret.replace(wslit, wschar)\n\n                # replace escaped characters\n                if self.escChar:\n                    ret = re.sub(self.escCharReplacePattern, r\"\\g<1>\", ret)\n\n                # replace escaped quotes\n                if self.escQuote:\n                    ret = ret.replace(self.escQuote, self.endQuoteChar)\n\n        return loc, ret\n\n\nclass CharsNotIn(Token):\n    \"\"\"Token for matching words composed of characters *not* in a given\n    set (will include whitespace in matched characters if not listed in\n    the provided exclusion set - see example). Defined with string\n    containing all disallowed characters, and an optional minimum,\n    maximum, and/or exact length.  The default value for ``min`` is\n    1 (a minimum value < 1 is not valid); the default values for\n    ``max`` and ``exact`` are 0, meaning no maximum or exact\n    length restriction.\n\n    Example::\n\n        # define a comma-separated-value as anything that is not a ','\n        csv_value = CharsNotIn(',')\n        print(delimited_list(csv_value).parse_string(\"dkls,lsdkjf,s12 34,@!#,213\"))\n\n    prints::\n\n        ['dkls', 'lsdkjf', 's12 34', '@!#', '213']\n    \"\"\"\n\n    def __init__(\n        self,\n        not_chars: str = \"\",\n        min: int = 1,\n        max: int = 0,\n        exact: int = 0,\n        *,\n        notChars: str = \"\",\n    ):\n        super().__init__()\n        self.skipWhitespace = False\n        self.notChars = not_chars or notChars\n        self.notCharsSet = set(self.notChars)\n\n        if min < 1:\n            raise ValueError(\n                \"cannot specify a minimum length < 1; use \"\n                \"Opt(CharsNotIn()) if zero-length char group is permitted\"\n            )\n\n        self.minLen = min\n\n        if max > 0:\n            self.maxLen = max\n        else:\n            self.maxLen = _MAX_INT\n\n        if exact > 0:\n            self.maxLen = exact\n            self.minLen = exact\n\n        self.errmsg = \"Expected \" + self.name\n        self.mayReturnEmpty = self.minLen == 0\n        self.mayIndexError = False\n\n    def _generateDefaultName(self):\n        not_chars_str = _collapse_string_to_ranges(self.notChars)\n        if len(not_chars_str) > 16:\n            return \"!W:({}...)\".format(self.notChars[: 16 - 3])\n        else:\n            return \"!W:({})\".format(self.notChars)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        notchars = self.notCharsSet\n        if instring[loc] in notchars:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        start = loc\n        loc += 1\n        maxlen = min(start + self.maxLen, len(instring))\n        while loc < maxlen and instring[loc] not in notchars:\n            loc += 1\n\n        if loc - start < self.minLen:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        return loc, instring[start:loc]\n\n\nclass White(Token):\n    \"\"\"Special matching class for matching whitespace.  Normally,\n    whitespace is ignored by pyparsing grammars.  This class is included\n    when some whitespace structures are significant.  Define with\n    a string containing the whitespace characters to be matched; default\n    is ``\" \\\\t\\\\r\\\\n\"``.  Also takes optional ``min``,\n    ``max``, and ``exact`` arguments, as defined for the\n    :class:`Word` class.\n    \"\"\"\n\n    whiteStrs = {\n        \" \": \"<SP>\",\n        \"\\t\": \"<TAB>\",\n        \"\\n\": \"<LF>\",\n        \"\\r\": \"<CR>\",\n        \"\\f\": \"<FF>\",\n        \"\\u00A0\": \"<NBSP>\",\n        \"\\u1680\": \"<OGHAM_SPACE_MARK>\",\n        \"\\u180E\": \"<MONGOLIAN_VOWEL_SEPARATOR>\",\n        \"\\u2000\": \"<EN_QUAD>\",\n        \"\\u2001\": \"<EM_QUAD>\",\n        \"\\u2002\": \"<EN_SPACE>\",\n        \"\\u2003\": \"<EM_SPACE>\",\n        \"\\u2004\": \"<THREE-PER-EM_SPACE>\",\n        \"\\u2005\": \"<FOUR-PER-EM_SPACE>\",\n        \"\\u2006\": \"<SIX-PER-EM_SPACE>\",\n        \"\\u2007\": \"<FIGURE_SPACE>\",\n        \"\\u2008\": \"<PUNCTUATION_SPACE>\",\n        \"\\u2009\": \"<THIN_SPACE>\",\n        \"\\u200A\": \"<HAIR_SPACE>\",\n        \"\\u200B\": \"<ZERO_WIDTH_SPACE>\",\n        \"\\u202F\": \"<NNBSP>\",\n        \"\\u205F\": \"<MMSP>\",\n        \"\\u3000\": \"<IDEOGRAPHIC_SPACE>\",\n    }\n\n    def __init__(self, ws: str = \" \\t\\r\\n\", min: int = 1, max: int = 0, exact: int = 0):\n        super().__init__()\n        self.matchWhite = ws\n        self.set_whitespace_chars(\n            \"\".join(c for c in self.whiteStrs if c not in self.matchWhite),\n            copy_defaults=True,\n        )\n        # self.leave_whitespace()\n        self.mayReturnEmpty = True\n        self.errmsg = \"Expected \" + self.name\n\n        self.minLen = min\n\n        if max > 0:\n            self.maxLen = max\n        else:\n            self.maxLen = _MAX_INT\n\n        if exact > 0:\n            self.maxLen = exact\n            self.minLen = exact\n\n    def _generateDefaultName(self):\n        return \"\".join(White.whiteStrs[c] for c in self.matchWhite)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc] not in self.matchWhite:\n            raise ParseException(instring, loc, self.errmsg, self)\n        start = loc\n        loc += 1\n        maxloc = start + self.maxLen\n        maxloc = min(maxloc, len(instring))\n        while loc < maxloc and instring[loc] in self.matchWhite:\n            loc += 1\n\n        if loc - start < self.minLen:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        return loc, instring[start:loc]\n\n\nclass PositionToken(Token):\n    def __init__(self):\n        super().__init__()\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n\n\nclass GoToColumn(PositionToken):\n    \"\"\"Token to advance to a specific column of input text; useful for\n    tabular report scraping.\n    \"\"\"\n\n    def __init__(self, colno: int):\n        super().__init__()\n        self.col = colno\n\n    def preParse(self, instring, loc):\n        if col(loc, instring) != self.col:\n            instrlen = len(instring)\n            if self.ignoreExprs:\n                loc = self._skipIgnorables(instring, loc)\n            while (\n                loc < instrlen\n                and instring[loc].isspace()\n                and col(loc, instring) != self.col\n            ):\n                loc += 1\n        return loc\n\n    def parseImpl(self, instring, loc, doActions=True):\n        thiscol = col(loc, instring)\n        if thiscol > self.col:\n            raise ParseException(instring, loc, \"Text not in expected column\", self)\n        newloc = loc + self.col - thiscol\n        ret = instring[loc:newloc]\n        return newloc, ret\n\n\nclass LineStart(PositionToken):\n    r\"\"\"Matches if current position is at the beginning of a line within\n    the parse string\n\n    Example::\n\n        test = '''\\\n        AAA this line\n        AAA and this line\n          AAA but not this one\n        B AAA and definitely not this one\n        '''\n\n        for t in (LineStart() + 'AAA' + restOfLine).search_string(test):\n            print(t)\n\n    prints::\n\n        ['AAA', ' this line']\n        ['AAA', ' and this line']\n\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.leave_whitespace()\n        self.orig_whiteChars = set() | self.whiteChars\n        self.whiteChars.discard(\"\\n\")\n        self.skipper = Empty().set_whitespace_chars(self.whiteChars)\n        self.errmsg = \"Expected start of line\"\n\n    def preParse(self, instring, loc):\n        if loc == 0:\n            return loc\n        else:\n            ret = self.skipper.preParse(instring, loc)\n            if \"\\n\" in self.orig_whiteChars:\n                while instring[ret : ret + 1] == \"\\n\":\n                    ret = self.skipper.preParse(instring, ret + 1)\n            return ret\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if col(loc, instring) == 1:\n            return loc, []\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass LineEnd(PositionToken):\n    \"\"\"Matches if current position is at the end of a line within the\n    parse string\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.whiteChars.discard(\"\\n\")\n        self.set_whitespace_chars(self.whiteChars, copy_defaults=False)\n        self.errmsg = \"Expected end of line\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc < len(instring):\n            if instring[loc] == \"\\n\":\n                return loc + 1, \"\\n\"\n            else:\n                raise ParseException(instring, loc, self.errmsg, self)\n        elif loc == len(instring):\n            return loc + 1, []\n        else:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass StringStart(PositionToken):\n    \"\"\"Matches if current position is at the beginning of the parse\n    string\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.errmsg = \"Expected start of text\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc != 0:\n            # see if entire string up to here is just whitespace and ignoreables\n            if loc != self.preParse(instring, 0):\n                raise ParseException(instring, loc, self.errmsg, self)\n        return loc, []\n\n\nclass StringEnd(PositionToken):\n    \"\"\"\n    Matches if current position is at the end of the parse string\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.errmsg = \"Expected end of text\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc < len(instring):\n            raise ParseException(instring, loc, self.errmsg, self)\n        elif loc == len(instring):\n            return loc + 1, []\n        elif loc > len(instring):\n            return loc, []\n        else:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass WordStart(PositionToken):\n    \"\"\"Matches if the current position is at the beginning of a\n    :class:`Word`, and is not preceded by any character in a given\n    set of ``word_chars`` (default= ``printables``). To emulate the\n    ``\\b`` behavior of regular expressions, use\n    ``WordStart(alphanums)``. ``WordStart`` will also match at\n    the beginning of the string being parsed, or at the beginning of\n    a line.\n    \"\"\"\n\n    def __init__(self, word_chars: str = printables, *, wordChars: str = printables):\n        wordChars = word_chars if wordChars == printables else wordChars\n        super().__init__()\n        self.wordChars = set(wordChars)\n        self.errmsg = \"Not at the start of a word\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc != 0:\n            if (\n                instring[loc - 1] in self.wordChars\n                or instring[loc] not in self.wordChars\n            ):\n                raise ParseException(instring, loc, self.errmsg, self)\n        return loc, []\n\n\nclass WordEnd(PositionToken):\n    \"\"\"Matches if the current position is at the end of a :class:`Word`,\n    and is not followed by any character in a given set of ``word_chars``\n    (default= ``printables``). To emulate the ``\\b`` behavior of\n    regular expressions, use ``WordEnd(alphanums)``. ``WordEnd``\n    will also match at the end of the string being parsed, or at the end\n    of a line.\n    \"\"\"\n\n    def __init__(self, word_chars: str = printables, *, wordChars: str = printables):\n        wordChars = word_chars if wordChars == printables else wordChars\n        super().__init__()\n        self.wordChars = set(wordChars)\n        self.skipWhitespace = False\n        self.errmsg = \"Not at the end of a word\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        instrlen = len(instring)\n        if instrlen > 0 and loc < instrlen:\n            if (\n                instring[loc] in self.wordChars\n                or instring[loc - 1] not in self.wordChars\n            ):\n                raise ParseException(instring, loc, self.errmsg, self)\n        return loc, []\n\n\nclass ParseExpression(ParserElement):\n    \"\"\"Abstract subclass of ParserElement, for combining and\n    post-processing parsed tokens.\n    \"\"\"\n\n    def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False):\n        super().__init__(savelist)\n        self.exprs: List[ParserElement]\n        if isinstance(exprs, _generatorType):\n            exprs = list(exprs)\n\n        if isinstance(exprs, str_type):\n            self.exprs = [self._literalStringClass(exprs)]\n        elif isinstance(exprs, ParserElement):\n            self.exprs = [exprs]\n        elif isinstance(exprs, Iterable):\n            exprs = list(exprs)\n            # if sequence of strings provided, wrap with Literal\n            if any(isinstance(expr, str_type) for expr in exprs):\n                exprs = (\n                    self._literalStringClass(e) if isinstance(e, str_type) else e\n                    for e in exprs\n                )\n            self.exprs = list(exprs)\n        else:\n            try:\n                self.exprs = list(exprs)\n            except TypeError:\n                self.exprs = [exprs]\n        self.callPreparse = False\n\n    def recurse(self) -> Sequence[ParserElement]:\n        return self.exprs[:]\n\n    def append(self, other) -> ParserElement:\n        self.exprs.append(other)\n        self._defaultName = None\n        return self\n\n    def leave_whitespace(self, recursive: bool = True) -> ParserElement:\n        \"\"\"\n        Extends ``leave_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on\n           all contained expressions.\n        \"\"\"\n        super().leave_whitespace(recursive)\n\n        if recursive:\n            self.exprs = [e.copy() for e in self.exprs]\n            for e in self.exprs:\n                e.leave_whitespace(recursive)\n        return self\n\n    def ignore_whitespace(self, recursive: bool = True) -> ParserElement:\n        \"\"\"\n        Extends ``ignore_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on\n           all contained expressions.\n        \"\"\"\n        super().ignore_whitespace(recursive)\n        if recursive:\n            self.exprs = [e.copy() for e in self.exprs]\n            for e in self.exprs:\n                e.ignore_whitespace(recursive)\n        return self\n\n    def ignore(self, other) -> ParserElement:\n        if isinstance(other, Suppress):\n            if other not in self.ignoreExprs:\n                super().ignore(other)\n                for e in self.exprs:\n                    e.ignore(self.ignoreExprs[-1])\n        else:\n            super().ignore(other)\n            for e in self.exprs:\n                e.ignore(self.ignoreExprs[-1])\n        return self\n\n    def _generateDefaultName(self):\n        return \"{}:({})\".format(self.__class__.__name__, str(self.exprs))\n\n    def streamline(self) -> ParserElement:\n        if self.streamlined:\n            return self\n\n        super().streamline()\n\n        for e in self.exprs:\n            e.streamline()\n\n        # collapse nested :class:`And`'s of the form ``And(And(And(a, b), c), d)`` to ``And(a, b, c, d)``\n        # but only if there are no parse actions or resultsNames on the nested And's\n        # (likewise for :class:`Or`'s and :class:`MatchFirst`'s)\n        if len(self.exprs) == 2:\n            other = self.exprs[0]\n            if (\n                isinstance(other, self.__class__)\n                and not other.parseAction\n                and other.resultsName is None\n                and not other.debug\n            ):\n                self.exprs = other.exprs[:] + [self.exprs[1]]\n                self._defaultName = None\n                self.mayReturnEmpty |= other.mayReturnEmpty\n                self.mayIndexError |= other.mayIndexError\n\n            other = self.exprs[-1]\n            if (\n                isinstance(other, self.__class__)\n                and not other.parseAction\n                and other.resultsName is None\n                and not other.debug\n            ):\n                self.exprs = self.exprs[:-1] + other.exprs[:]\n                self._defaultName = None\n                self.mayReturnEmpty |= other.mayReturnEmpty\n                self.mayIndexError |= other.mayIndexError\n\n        self.errmsg = \"Expected \" + str(self)\n\n        return self\n\n    def validate(self, validateTrace=None) -> None:\n        tmp = (validateTrace if validateTrace is not None else [])[:] + [self]\n        for e in self.exprs:\n            e.validate(tmp)\n        self._checkRecursion([])\n\n    def copy(self) -> ParserElement:\n        ret = super().copy()\n        ret.exprs = [e.copy() for e in self.exprs]\n        return ret\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if (\n            __diag__.warn_ungrouped_named_tokens_in_collection\n            and Diagnostics.warn_ungrouped_named_tokens_in_collection\n            not in self.suppress_warnings_\n        ):\n            for e in self.exprs:\n                if (\n                    isinstance(e, ParserElement)\n                    and e.resultsName\n                    and Diagnostics.warn_ungrouped_named_tokens_in_collection\n                    not in e.suppress_warnings_\n                ):\n                    warnings.warn(\n                        \"{}: setting results name {!r} on {} expression \"\n                        \"collides with {!r} on contained expression\".format(\n                            \"warn_ungrouped_named_tokens_in_collection\",\n                            name,\n                            type(self).__name__,\n                            e.resultsName,\n                        ),\n                        stacklevel=3,\n                    )\n\n        return super()._setResultsName(name, listAllMatches)\n\n    ignoreWhitespace = ignore_whitespace\n    leaveWhitespace = leave_whitespace\n\n\nclass And(ParseExpression):\n    \"\"\"\n    Requires all given :class:`ParseExpression` s to be found in the given order.\n    Expressions may be separated by whitespace.\n    May be constructed using the ``'+'`` operator.\n    May also be constructed using the ``'-'`` operator, which will\n    suppress backtracking.\n\n    Example::\n\n        integer = Word(nums)\n        name_expr = Word(alphas)[1, ...]\n\n        expr = And([integer(\"id\"), name_expr(\"name\"), integer(\"age\")])\n        # more easily written as:\n        expr = integer(\"id\") + name_expr(\"name\") + integer(\"age\")\n    \"\"\"\n\n    class _ErrorStop(Empty):\n        def __init__(self, *args, **kwargs):\n            super().__init__(*args, **kwargs)\n            self.leave_whitespace()\n\n        def _generateDefaultName(self):\n            return \"-\"\n\n    def __init__(\n        self, exprs_arg: typing.Iterable[ParserElement], savelist: bool = True\n    ):\n        exprs: List[ParserElement] = list(exprs_arg)\n        if exprs and Ellipsis in exprs:\n            tmp = []\n            for i, expr in enumerate(exprs):\n                if expr is Ellipsis:\n                    if i < len(exprs) - 1:\n                        skipto_arg: ParserElement = (Empty() + exprs[i + 1]).exprs[-1]\n                        tmp.append(SkipTo(skipto_arg)(\"_skipped*\"))\n                    else:\n                        raise Exception(\n                            \"cannot construct And with sequence ending in ...\"\n                        )\n                else:\n                    tmp.append(expr)\n            exprs[:] = tmp\n        super().__init__(exprs, savelist)\n        if self.exprs:\n            self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)\n            if not isinstance(self.exprs[0], White):\n                self.set_whitespace_chars(\n                    self.exprs[0].whiteChars,\n                    copy_defaults=self.exprs[0].copyDefaultWhiteChars,\n                )\n                self.skipWhitespace = self.exprs[0].skipWhitespace\n            else:\n                self.skipWhitespace = False\n        else:\n            self.mayReturnEmpty = True\n        self.callPreparse = True\n\n    def streamline(self) -> ParserElement:\n        # collapse any _PendingSkip's\n        if self.exprs:\n            if any(\n                isinstance(e, ParseExpression)\n                and e.exprs\n                and isinstance(e.exprs[-1], _PendingSkip)\n                for e in self.exprs[:-1]\n            ):\n                for i, e in enumerate(self.exprs[:-1]):\n                    if e is None:\n                        continue\n                    if (\n                        isinstance(e, ParseExpression)\n                        and e.exprs\n                        and isinstance(e.exprs[-1], _PendingSkip)\n                    ):\n                        e.exprs[-1] = e.exprs[-1] + self.exprs[i + 1]\n                        self.exprs[i + 1] = None\n                self.exprs = [e for e in self.exprs if e is not None]\n\n        super().streamline()\n\n        # link any IndentedBlocks to the prior expression\n        for prev, cur in zip(self.exprs, self.exprs[1:]):\n            # traverse cur or any first embedded expr of cur looking for an IndentedBlock\n            # (but watch out for recursive grammar)\n            seen = set()\n            while cur:\n                if id(cur) in seen:\n                    break\n                seen.add(id(cur))\n                if isinstance(cur, IndentedBlock):\n                    prev.add_parse_action(\n                        lambda s, l, t, cur_=cur: setattr(\n                            cur_, \"parent_anchor\", col(l, s)\n                        )\n                    )\n                    break\n                subs = cur.recurse()\n                cur = next(iter(subs), None)\n\n        self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        # pass False as callPreParse arg to _parse for first element, since we already\n        # pre-parsed the string as part of our And pre-parsing\n        loc, resultlist = self.exprs[0]._parse(\n            instring, loc, doActions, callPreParse=False\n        )\n        errorStop = False\n        for e in self.exprs[1:]:\n            # if isinstance(e, And._ErrorStop):\n            if type(e) is And._ErrorStop:\n                errorStop = True\n                continue\n            if errorStop:\n                try:\n                    loc, exprtokens = e._parse(instring, loc, doActions)\n                except ParseSyntaxException:\n                    raise\n                except ParseBaseException as pe:\n                    pe.__traceback__ = None\n                    raise ParseSyntaxException._from_exception(pe)\n                except IndexError:\n                    raise ParseSyntaxException(\n                        instring, len(instring), self.errmsg, self\n                    )\n            else:\n                loc, exprtokens = e._parse(instring, loc, doActions)\n            if exprtokens or exprtokens.haskeys():\n                resultlist += exprtokens\n        return loc, resultlist\n\n    def __iadd__(self, other):\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        return self.append(other)  # And([self, other])\n\n    def _checkRecursion(self, parseElementList):\n        subRecCheckList = parseElementList[:] + [self]\n        for e in self.exprs:\n            e._checkRecursion(subRecCheckList)\n            if not e.mayReturnEmpty:\n                break\n\n    def _generateDefaultName(self):\n        inner = \" \".join(str(e) for e in self.exprs)\n        # strip off redundant inner {}'s\n        while len(inner) > 1 and inner[0 :: len(inner) - 1] == \"{}\":\n            inner = inner[1:-1]\n        return \"{\" + inner + \"}\"\n\n\nclass Or(ParseExpression):\n    \"\"\"Requires that at least one :class:`ParseExpression` is found. If\n    two expressions match, the expression that matches the longest\n    string will be used. May be constructed using the ``'^'``\n    operator.\n\n    Example::\n\n        # construct Or using '^' operator\n\n        number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums))\n        print(number.search_string(\"123 3.1416 789\"))\n\n    prints::\n\n        [['123'], ['3.1416'], ['789']]\n    \"\"\"\n\n    def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False):\n        super().__init__(exprs, savelist)\n        if self.exprs:\n            self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)\n            self.skipWhitespace = all(e.skipWhitespace for e in self.exprs)\n        else:\n            self.mayReturnEmpty = True\n\n    def streamline(self) -> ParserElement:\n        super().streamline()\n        if self.exprs:\n            self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)\n            self.saveAsList = any(e.saveAsList for e in self.exprs)\n            self.skipWhitespace = all(\n                e.skipWhitespace and not isinstance(e, White) for e in self.exprs\n            )\n        else:\n            self.saveAsList = False\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        maxExcLoc = -1\n        maxException = None\n        matches = []\n        fatals = []\n        if all(e.callPreparse for e in self.exprs):\n            loc = self.preParse(instring, loc)\n        for e in self.exprs:\n            try:\n                loc2 = e.try_parse(instring, loc, raise_fatal=True)\n            except ParseFatalException as pfe:\n                pfe.__traceback__ = None\n                pfe.parserElement = e\n                fatals.append(pfe)\n                maxException = None\n                maxExcLoc = -1\n            except ParseException as err:\n                if not fatals:\n                    err.__traceback__ = None\n                    if err.loc > maxExcLoc:\n                        maxException = err\n                        maxExcLoc = err.loc\n            except IndexError:\n                if len(instring) > maxExcLoc:\n                    maxException = ParseException(\n                        instring, len(instring), e.errmsg, self\n                    )\n                    maxExcLoc = len(instring)\n            else:\n                # save match among all matches, to retry longest to shortest\n                matches.append((loc2, e))\n\n        if matches:\n            # re-evaluate all matches in descending order of length of match, in case attached actions\n            # might change whether or how much they match of the input.\n            matches.sort(key=itemgetter(0), reverse=True)\n\n            if not doActions:\n                # no further conditions or parse actions to change the selection of\n                # alternative, so the first match will be the best match\n                best_expr = matches[0][1]\n                return best_expr._parse(instring, loc, doActions)\n\n            longest = -1, None\n            for loc1, expr1 in matches:\n                if loc1 <= longest[0]:\n                    # already have a longer match than this one will deliver, we are done\n                    return longest\n\n                try:\n                    loc2, toks = expr1._parse(instring, loc, doActions)\n                except ParseException as err:\n                    err.__traceback__ = None\n                    if err.loc > maxExcLoc:\n                        maxException = err\n                        maxExcLoc = err.loc\n                else:\n                    if loc2 >= loc1:\n                        return loc2, toks\n                    # didn't match as much as before\n                    elif loc2 > longest[0]:\n                        longest = loc2, toks\n\n            if longest != (-1, None):\n                return longest\n\n        if fatals:\n            if len(fatals) > 1:\n                fatals.sort(key=lambda e: -e.loc)\n                if fatals[0].loc == fatals[1].loc:\n                    fatals.sort(key=lambda e: (-e.loc, -len(str(e.parserElement))))\n            max_fatal = fatals[0]\n            raise max_fatal\n\n        if maxException is not None:\n            maxException.msg = self.errmsg\n            raise maxException\n        else:\n            raise ParseException(\n                instring, loc, \"no defined alternatives to match\", self\n            )\n\n    def __ixor__(self, other):\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        return self.append(other)  # Or([self, other])\n\n    def _generateDefaultName(self):\n        return \"{\" + \" ^ \".join(str(e) for e in self.exprs) + \"}\"\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if (\n            __diag__.warn_multiple_tokens_in_named_alternation\n            and Diagnostics.warn_multiple_tokens_in_named_alternation\n            not in self.suppress_warnings_\n        ):\n            if any(\n                isinstance(e, And)\n                and Diagnostics.warn_multiple_tokens_in_named_alternation\n                not in e.suppress_warnings_\n                for e in self.exprs\n            ):\n                warnings.warn(\n                    \"{}: setting results name {!r} on {} expression \"\n                    \"will return a list of all parsed tokens in an And alternative, \"\n                    \"in prior versions only the first token was returned; enclose \"\n                    \"contained argument in Group\".format(\n                        \"warn_multiple_tokens_in_named_alternation\",\n                        name,\n                        type(self).__name__,\n                    ),\n                    stacklevel=3,\n                )\n\n        return super()._setResultsName(name, listAllMatches)\n\n\nclass MatchFirst(ParseExpression):\n    \"\"\"Requires that at least one :class:`ParseExpression` is found. If\n    more than one expression matches, the first one listed is the one that will\n    match. May be constructed using the ``'|'`` operator.\n\n    Example::\n\n        # construct MatchFirst using '|' operator\n\n        # watch the order of expressions to match\n        number = Word(nums) | Combine(Word(nums) + '.' + Word(nums))\n        print(number.search_string(\"123 3.1416 789\")) #  Fail! -> [['123'], ['3'], ['1416'], ['789']]\n\n        # put more selective expression first\n        number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums)\n        print(number.search_string(\"123 3.1416 789\")) #  Better -> [['123'], ['3.1416'], ['789']]\n    \"\"\"\n\n    def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False):\n        super().__init__(exprs, savelist)\n        if self.exprs:\n            self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)\n            self.skipWhitespace = all(e.skipWhitespace for e in self.exprs)\n        else:\n            self.mayReturnEmpty = True\n\n    def streamline(self) -> ParserElement:\n        if self.streamlined:\n            return self\n\n        super().streamline()\n        if self.exprs:\n            self.saveAsList = any(e.saveAsList for e in self.exprs)\n            self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)\n            self.skipWhitespace = all(\n                e.skipWhitespace and not isinstance(e, White) for e in self.exprs\n            )\n        else:\n            self.saveAsList = False\n            self.mayReturnEmpty = True\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        maxExcLoc = -1\n        maxException = None\n\n        for e in self.exprs:\n            try:\n                return e._parse(\n                    instring,\n                    loc,\n                    doActions,\n                )\n            except ParseFatalException as pfe:\n                pfe.__traceback__ = None\n                pfe.parserElement = e\n                raise\n            except ParseException as err:\n                if err.loc > maxExcLoc:\n                    maxException = err\n                    maxExcLoc = err.loc\n            except IndexError:\n                if len(instring) > maxExcLoc:\n                    maxException = ParseException(\n                        instring, len(instring), e.errmsg, self\n                    )\n                    maxExcLoc = len(instring)\n\n        if maxException is not None:\n            maxException.msg = self.errmsg\n            raise maxException\n        else:\n            raise ParseException(\n                instring, loc, \"no defined alternatives to match\", self\n            )\n\n    def __ior__(self, other):\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        return self.append(other)  # MatchFirst([self, other])\n\n    def _generateDefaultName(self):\n        return \"{\" + \" | \".join(str(e) for e in self.exprs) + \"}\"\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if (\n            __diag__.warn_multiple_tokens_in_named_alternation\n            and Diagnostics.warn_multiple_tokens_in_named_alternation\n            not in self.suppress_warnings_\n        ):\n            if any(\n                isinstance(e, And)\n                and Diagnostics.warn_multiple_tokens_in_named_alternation\n                not in e.suppress_warnings_\n                for e in self.exprs\n            ):\n                warnings.warn(\n                    \"{}: setting results name {!r} on {} expression \"\n                    \"will return a list of all parsed tokens in an And alternative, \"\n                    \"in prior versions only the first token was returned; enclose \"\n                    \"contained argument in Group\".format(\n                        \"warn_multiple_tokens_in_named_alternation\",\n                        name,\n                        type(self).__name__,\n                    ),\n                    stacklevel=3,\n                )\n\n        return super()._setResultsName(name, listAllMatches)\n\n\nclass Each(ParseExpression):\n    \"\"\"Requires all given :class:`ParseExpression` s to be found, but in\n    any order. Expressions may be separated by whitespace.\n\n    May be constructed using the ``'&'`` operator.\n\n    Example::\n\n        color = one_of(\"RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN\")\n        shape_type = one_of(\"SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON\")\n        integer = Word(nums)\n        shape_attr = \"shape:\" + shape_type(\"shape\")\n        posn_attr = \"posn:\" + Group(integer(\"x\") + ',' + integer(\"y\"))(\"posn\")\n        color_attr = \"color:\" + color(\"color\")\n        size_attr = \"size:\" + integer(\"size\")\n\n        # use Each (using operator '&') to accept attributes in any order\n        # (shape and posn are required, color and size are optional)\n        shape_spec = shape_attr & posn_attr & Opt(color_attr) & Opt(size_attr)\n\n        shape_spec.run_tests('''\n            shape: SQUARE color: BLACK posn: 100, 120\n            shape: CIRCLE size: 50 color: BLUE posn: 50,80\n            color:GREEN size:20 shape:TRIANGLE posn:20,40\n            '''\n            )\n\n    prints::\n\n        shape: SQUARE color: BLACK posn: 100, 120\n        ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']]\n        - color: BLACK\n        - posn: ['100', ',', '120']\n          - x: 100\n          - y: 120\n        - shape: SQUARE\n\n\n        shape: CIRCLE size: 50 color: BLUE posn: 50,80\n        ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']]\n        - color: BLUE\n        - posn: ['50', ',', '80']\n          - x: 50\n          - y: 80\n        - shape: CIRCLE\n        - size: 50\n\n\n        color: GREEN size: 20 shape: TRIANGLE posn: 20,40\n        ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']]\n        - color: GREEN\n        - posn: ['20', ',', '40']\n          - x: 20\n          - y: 40\n        - shape: TRIANGLE\n        - size: 20\n    \"\"\"\n\n    def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = True):\n        super().__init__(exprs, savelist)\n        if self.exprs:\n            self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)\n        else:\n            self.mayReturnEmpty = True\n        self.skipWhitespace = True\n        self.initExprGroups = True\n        self.saveAsList = True\n\n    def streamline(self) -> ParserElement:\n        super().streamline()\n        if self.exprs:\n            self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)\n        else:\n            self.mayReturnEmpty = True\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if self.initExprGroups:\n            self.opt1map = dict(\n                (id(e.expr), e) for e in self.exprs if isinstance(e, Opt)\n            )\n            opt1 = [e.expr for e in self.exprs if isinstance(e, Opt)]\n            opt2 = [\n                e\n                for e in self.exprs\n                if e.mayReturnEmpty and not isinstance(e, (Opt, Regex, ZeroOrMore))\n            ]\n            self.optionals = opt1 + opt2\n            self.multioptionals = [\n                e.expr.set_results_name(e.resultsName, list_all_matches=True)\n                for e in self.exprs\n                if isinstance(e, _MultipleMatch)\n            ]\n            self.multirequired = [\n                e.expr.set_results_name(e.resultsName, list_all_matches=True)\n                for e in self.exprs\n                if isinstance(e, OneOrMore)\n            ]\n            self.required = [\n                e for e in self.exprs if not isinstance(e, (Opt, ZeroOrMore, OneOrMore))\n            ]\n            self.required += self.multirequired\n            self.initExprGroups = False\n\n        tmpLoc = loc\n        tmpReqd = self.required[:]\n        tmpOpt = self.optionals[:]\n        multis = self.multioptionals[:]\n        matchOrder = []\n\n        keepMatching = True\n        failed = []\n        fatals = []\n        while keepMatching:\n            tmpExprs = tmpReqd + tmpOpt + multis\n            failed.clear()\n            fatals.clear()\n            for e in tmpExprs:\n                try:\n                    tmpLoc = e.try_parse(instring, tmpLoc, raise_fatal=True)\n                except ParseFatalException as pfe:\n                    pfe.__traceback__ = None\n                    pfe.parserElement = e\n                    fatals.append(pfe)\n                    failed.append(e)\n                except ParseException:\n                    failed.append(e)\n                else:\n                    matchOrder.append(self.opt1map.get(id(e), e))\n                    if e in tmpReqd:\n                        tmpReqd.remove(e)\n                    elif e in tmpOpt:\n                        tmpOpt.remove(e)\n            if len(failed) == len(tmpExprs):\n                keepMatching = False\n\n        # look for any ParseFatalExceptions\n        if fatals:\n            if len(fatals) > 1:\n                fatals.sort(key=lambda e: -e.loc)\n                if fatals[0].loc == fatals[1].loc:\n                    fatals.sort(key=lambda e: (-e.loc, -len(str(e.parserElement))))\n            max_fatal = fatals[0]\n            raise max_fatal\n\n        if tmpReqd:\n            missing = \", \".join([str(e) for e in tmpReqd])\n            raise ParseException(\n                instring,\n                loc,\n                \"Missing one or more required elements ({})\".format(missing),\n            )\n\n        # add any unmatched Opts, in case they have default values defined\n        matchOrder += [e for e in self.exprs if isinstance(e, Opt) and e.expr in tmpOpt]\n\n        total_results = ParseResults([])\n        for e in matchOrder:\n            loc, results = e._parse(instring, loc, doActions)\n            total_results += results\n\n        return loc, total_results\n\n    def _generateDefaultName(self):\n        return \"{\" + \" & \".join(str(e) for e in self.exprs) + \"}\"\n\n\nclass ParseElementEnhance(ParserElement):\n    \"\"\"Abstract subclass of :class:`ParserElement`, for combining and\n    post-processing parsed tokens.\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str], savelist: bool = False):\n        super().__init__(savelist)\n        if isinstance(expr, str_type):\n            if issubclass(self._literalStringClass, Token):\n                expr = self._literalStringClass(expr)\n            elif issubclass(type(self), self._literalStringClass):\n                expr = Literal(expr)\n            else:\n                expr = self._literalStringClass(Literal(expr))\n        self.expr = expr\n        if expr is not None:\n            self.mayIndexError = expr.mayIndexError\n            self.mayReturnEmpty = expr.mayReturnEmpty\n            self.set_whitespace_chars(\n                expr.whiteChars, copy_defaults=expr.copyDefaultWhiteChars\n            )\n            self.skipWhitespace = expr.skipWhitespace\n            self.saveAsList = expr.saveAsList\n            self.callPreparse = expr.callPreparse\n            self.ignoreExprs.extend(expr.ignoreExprs)\n\n    def recurse(self) -> Sequence[ParserElement]:\n        return [self.expr] if self.expr is not None else []\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if self.expr is not None:\n            return self.expr._parse(instring, loc, doActions, callPreParse=False)\n        else:\n            raise ParseException(instring, loc, \"No expression defined\", self)\n\n    def leave_whitespace(self, recursive: bool = True) -> ParserElement:\n        super().leave_whitespace(recursive)\n\n        if recursive:\n            self.expr = self.expr.copy()\n            if self.expr is not None:\n                self.expr.leave_whitespace(recursive)\n        return self\n\n    def ignore_whitespace(self, recursive: bool = True) -> ParserElement:\n        super().ignore_whitespace(recursive)\n\n        if recursive:\n            self.expr = self.expr.copy()\n            if self.expr is not None:\n                self.expr.ignore_whitespace(recursive)\n        return self\n\n    def ignore(self, other) -> ParserElement:\n        if isinstance(other, Suppress):\n            if other not in self.ignoreExprs:\n                super().ignore(other)\n                if self.expr is not None:\n                    self.expr.ignore(self.ignoreExprs[-1])\n        else:\n            super().ignore(other)\n            if self.expr is not None:\n                self.expr.ignore(self.ignoreExprs[-1])\n        return self\n\n    def streamline(self) -> ParserElement:\n        super().streamline()\n        if self.expr is not None:\n            self.expr.streamline()\n        return self\n\n    def _checkRecursion(self, parseElementList):\n        if self in parseElementList:\n            raise RecursiveGrammarException(parseElementList + [self])\n        subRecCheckList = parseElementList[:] + [self]\n        if self.expr is not None:\n            self.expr._checkRecursion(subRecCheckList)\n\n    def validate(self, validateTrace=None) -> None:\n        if validateTrace is None:\n            validateTrace = []\n        tmp = validateTrace[:] + [self]\n        if self.expr is not None:\n            self.expr.validate(tmp)\n        self._checkRecursion([])\n\n    def _generateDefaultName(self):\n        return \"{}:({})\".format(self.__class__.__name__, str(self.expr))\n\n    ignoreWhitespace = ignore_whitespace\n    leaveWhitespace = leave_whitespace\n\n\nclass IndentedBlock(ParseElementEnhance):\n    \"\"\"\n    Expression to match one or more expressions at a given indentation level.\n    Useful for parsing text where structure is implied by indentation (like Python source code).\n    \"\"\"\n\n    class _Indent(Empty):\n        def __init__(self, ref_col: int):\n            super().__init__()\n            self.errmsg = \"expected indent at column {}\".format(ref_col)\n            self.add_condition(lambda s, l, t: col(l, s) == ref_col)\n\n    class _IndentGreater(Empty):\n        def __init__(self, ref_col: int):\n            super().__init__()\n            self.errmsg = \"expected indent at column greater than {}\".format(ref_col)\n            self.add_condition(lambda s, l, t: col(l, s) > ref_col)\n\n    def __init__(\n        self, expr: ParserElement, *, recursive: bool = False, grouped: bool = True\n    ):\n        super().__init__(expr, savelist=True)\n        # if recursive:\n        #     raise NotImplementedError(\"IndentedBlock with recursive is not implemented\")\n        self._recursive = recursive\n        self._grouped = grouped\n        self.parent_anchor = 1\n\n    def parseImpl(self, instring, loc, doActions=True):\n        # advance parse position to non-whitespace by using an Empty()\n        # this should be the column to be used for all subsequent indented lines\n        anchor_loc = Empty().preParse(instring, loc)\n\n        # see if self.expr matches at the current location - if not it will raise an exception\n        # and no further work is necessary\n        self.expr.try_parse(instring, anchor_loc, doActions)\n\n        indent_col = col(anchor_loc, instring)\n        peer_detect_expr = self._Indent(indent_col)\n\n        inner_expr = Empty() + peer_detect_expr + self.expr\n        if self._recursive:\n            sub_indent = self._IndentGreater(indent_col)\n            nested_block = IndentedBlock(\n                self.expr, recursive=self._recursive, grouped=self._grouped\n            )\n            nested_block.set_debug(self.debug)\n            nested_block.parent_anchor = indent_col\n            inner_expr += Opt(sub_indent + nested_block)\n\n        inner_expr.set_name(f\"inner {hex(id(inner_expr))[-4:].upper()}@{indent_col}\")\n        block = OneOrMore(inner_expr)\n\n        trailing_undent = self._Indent(self.parent_anchor) | StringEnd()\n\n        if self._grouped:\n            wrapper = Group\n        else:\n            wrapper = lambda expr: expr\n        return (wrapper(block) + Optional(trailing_undent)).parseImpl(\n            instring, anchor_loc, doActions\n        )\n\n\nclass AtStringStart(ParseElementEnhance):\n    \"\"\"Matches if expression matches at the beginning of the parse\n    string::\n\n        AtStringStart(Word(nums)).parse_string(\"123\")\n        # prints [\"123\"]\n\n        AtStringStart(Word(nums)).parse_string(\"    123\")\n        # raises ParseException\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str]):\n        super().__init__(expr)\n        self.callPreparse = False\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc != 0:\n            raise ParseException(instring, loc, \"not found at string start\")\n        return super().parseImpl(instring, loc, doActions)\n\n\nclass AtLineStart(ParseElementEnhance):\n    r\"\"\"Matches if an expression matches at the beginning of a line within\n    the parse string\n\n    Example::\n\n        test = '''\\\n        AAA this line\n        AAA and this line\n          AAA but not this one\n        B AAA and definitely not this one\n        '''\n\n        for t in (AtLineStart('AAA') + restOfLine).search_string(test):\n            print(t)\n\n    prints::\n\n        ['AAA', ' this line']\n        ['AAA', ' and this line']\n\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str]):\n        super().__init__(expr)\n        self.callPreparse = False\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if col(loc, instring) != 1:\n            raise ParseException(instring, loc, \"not found at line start\")\n        return super().parseImpl(instring, loc, doActions)\n\n\nclass FollowedBy(ParseElementEnhance):\n    \"\"\"Lookahead matching of the given parse expression.\n    ``FollowedBy`` does *not* advance the parsing position within\n    the input string, it only verifies that the specified parse\n    expression matches at the current position.  ``FollowedBy``\n    always returns a null token list. If any results names are defined\n    in the lookahead expression, those *will* be returned for access by\n    name.\n\n    Example::\n\n        # use FollowedBy to match a label only if it is followed by a ':'\n        data_word = Word(alphas)\n        label = data_word + FollowedBy(':')\n        attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))\n\n        attr_expr[1, ...].parse_string(\"shape: SQUARE color: BLACK posn: upper left\").pprint()\n\n    prints::\n\n        [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']]\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str]):\n        super().__init__(expr)\n        self.mayReturnEmpty = True\n\n    def parseImpl(self, instring, loc, doActions=True):\n        # by using self._expr.parse and deleting the contents of the returned ParseResults list\n        # we keep any named results that were defined in the FollowedBy expression\n        _, ret = self.expr._parse(instring, loc, doActions=doActions)\n        del ret[:]\n\n        return loc, ret\n\n\nclass PrecededBy(ParseElementEnhance):\n    \"\"\"Lookbehind matching of the given parse expression.\n    ``PrecededBy`` does not advance the parsing position within the\n    input string, it only verifies that the specified parse expression\n    matches prior to the current position.  ``PrecededBy`` always\n    returns a null token list, but if a results name is defined on the\n    given expression, it is returned.\n\n    Parameters:\n\n    - expr - expression that must match prior to the current parse\n      location\n    - retreat - (default= ``None``) - (int) maximum number of characters\n      to lookbehind prior to the current parse location\n\n    If the lookbehind expression is a string, :class:`Literal`,\n    :class:`Keyword`, or a :class:`Word` or :class:`CharsNotIn`\n    with a specified exact or maximum length, then the retreat\n    parameter is not required. Otherwise, retreat must be specified to\n    give a maximum number of characters to look back from\n    the current parse position for a lookbehind match.\n\n    Example::\n\n        # VB-style variable names with type prefixes\n        int_var = PrecededBy(\"#\") + pyparsing_common.identifier\n        str_var = PrecededBy(\"$\") + pyparsing_common.identifier\n\n    \"\"\"\n\n    def __init__(\n        self, expr: Union[ParserElement, str], retreat: typing.Optional[int] = None\n    ):\n        super().__init__(expr)\n        self.expr = self.expr().leave_whitespace()\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n        self.exact = False\n        if isinstance(expr, str_type):\n            retreat = len(expr)\n            self.exact = True\n        elif isinstance(expr, (Literal, Keyword)):\n            retreat = expr.matchLen\n            self.exact = True\n        elif isinstance(expr, (Word, CharsNotIn)) and expr.maxLen != _MAX_INT:\n            retreat = expr.maxLen\n            self.exact = True\n        elif isinstance(expr, PositionToken):\n            retreat = 0\n            self.exact = True\n        self.retreat = retreat\n        self.errmsg = \"not preceded by \" + str(expr)\n        self.skipWhitespace = False\n        self.parseAction.append(lambda s, l, t: t.__delitem__(slice(None, None)))\n\n    def parseImpl(self, instring, loc=0, doActions=True):\n        if self.exact:\n            if loc < self.retreat:\n                raise ParseException(instring, loc, self.errmsg)\n            start = loc - self.retreat\n            _, ret = self.expr._parse(instring, start)\n        else:\n            # retreat specified a maximum lookbehind window, iterate\n            test_expr = self.expr + StringEnd()\n            instring_slice = instring[max(0, loc - self.retreat) : loc]\n            last_expr = ParseException(instring, loc, self.errmsg)\n            for offset in range(1, min(loc, self.retreat + 1) + 1):\n                try:\n                    # print('trying', offset, instring_slice, repr(instring_slice[loc - offset:]))\n                    _, ret = test_expr._parse(\n                        instring_slice, len(instring_slice) - offset\n                    )\n                except ParseBaseException as pbe:\n                    last_expr = pbe\n                else:\n                    break\n            else:\n                raise last_expr\n        return loc, ret\n\n\nclass Located(ParseElementEnhance):\n    \"\"\"\n    Decorates a returned token with its starting and ending\n    locations in the input string.\n\n    This helper adds the following results names:\n\n    - ``locn_start`` - location where matched expression begins\n    - ``locn_end`` - location where matched expression ends\n    - ``value`` - the actual parsed results\n\n    Be careful if the input text contains ``<TAB>`` characters, you\n    may want to call :class:`ParserElement.parse_with_tabs`\n\n    Example::\n\n        wd = Word(alphas)\n        for match in Located(wd).search_string(\"ljsdf123lksdjjf123lkkjj1222\"):\n            print(match)\n\n    prints::\n\n        [0, ['ljsdf'], 5]\n        [8, ['lksdjjf'], 15]\n        [18, ['lkkjj'], 23]\n\n    \"\"\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        start = loc\n        loc, tokens = self.expr._parse(instring, start, doActions, callPreParse=False)\n        ret_tokens = ParseResults([start, tokens, loc])\n        ret_tokens[\"locn_start\"] = start\n        ret_tokens[\"value\"] = tokens\n        ret_tokens[\"locn_end\"] = loc\n        if self.resultsName:\n            # must return as a list, so that the name will be attached to the complete group\n            return loc, [ret_tokens]\n        else:\n            return loc, ret_tokens\n\n\nclass NotAny(ParseElementEnhance):\n    \"\"\"\n    Lookahead to disallow matching with the given parse expression.\n    ``NotAny`` does *not* advance the parsing position within the\n    input string, it only verifies that the specified parse expression\n    does *not* match at the current position.  Also, ``NotAny`` does\n    *not* skip over leading whitespace. ``NotAny`` always returns\n    a null token list.  May be constructed using the ``'~'`` operator.\n\n    Example::\n\n        AND, OR, NOT = map(CaselessKeyword, \"AND OR NOT\".split())\n\n        # take care not to mistake keywords for identifiers\n        ident = ~(AND | OR | NOT) + Word(alphas)\n        boolean_term = Opt(NOT) + ident\n\n        # very crude boolean expression - to support parenthesis groups and\n        # operation hierarchy, use infix_notation\n        boolean_expr = boolean_term + ((AND | OR) + boolean_term)[...]\n\n        # integers that are followed by \".\" are actually floats\n        integer = Word(nums) + ~Char(\".\")\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str]):\n        super().__init__(expr)\n        # do NOT use self.leave_whitespace(), don't want to propagate to exprs\n        # self.leave_whitespace()\n        self.skipWhitespace = False\n\n        self.mayReturnEmpty = True\n        self.errmsg = \"Found unwanted token, \" + str(self.expr)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if self.expr.can_parse_next(instring, loc):\n            raise ParseException(instring, loc, self.errmsg, self)\n        return loc, []\n\n    def _generateDefaultName(self):\n        return \"~{\" + str(self.expr) + \"}\"\n\n\nclass _MultipleMatch(ParseElementEnhance):\n    def __init__(\n        self,\n        expr: ParserElement,\n        stop_on: typing.Optional[Union[ParserElement, str]] = None,\n        *,\n        stopOn: typing.Optional[Union[ParserElement, str]] = None,\n    ):\n        super().__init__(expr)\n        stopOn = stopOn or stop_on\n        self.saveAsList = True\n        ender = stopOn\n        if isinstance(ender, str_type):\n            ender = self._literalStringClass(ender)\n        self.stopOn(ender)\n\n    def stopOn(self, ender) -> ParserElement:\n        if isinstance(ender, str_type):\n            ender = self._literalStringClass(ender)\n        self.not_ender = ~ender if ender is not None else None\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        self_expr_parse = self.expr._parse\n        self_skip_ignorables = self._skipIgnorables\n        check_ender = self.not_ender is not None\n        if check_ender:\n            try_not_ender = self.not_ender.tryParse\n\n        # must be at least one (but first see if we are the stopOn sentinel;\n        # if so, fail)\n        if check_ender:\n            try_not_ender(instring, loc)\n        loc, tokens = self_expr_parse(instring, loc, doActions)\n        try:\n            hasIgnoreExprs = not not self.ignoreExprs\n            while 1:\n                if check_ender:\n                    try_not_ender(instring, loc)\n                if hasIgnoreExprs:\n                    preloc = self_skip_ignorables(instring, loc)\n                else:\n                    preloc = loc\n                loc, tmptokens = self_expr_parse(instring, preloc, doActions)\n                if tmptokens or tmptokens.haskeys():\n                    tokens += tmptokens\n        except (ParseException, IndexError):\n            pass\n\n        return loc, tokens\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if (\n            __diag__.warn_ungrouped_named_tokens_in_collection\n            and Diagnostics.warn_ungrouped_named_tokens_in_collection\n            not in self.suppress_warnings_\n        ):\n            for e in [self.expr] + self.expr.recurse():\n                if (\n                    isinstance(e, ParserElement)\n                    and e.resultsName\n                    and Diagnostics.warn_ungrouped_named_tokens_in_collection\n                    not in e.suppress_warnings_\n                ):\n                    warnings.warn(\n                        \"{}: setting results name {!r} on {} expression \"\n                        \"collides with {!r} on contained expression\".format(\n                            \"warn_ungrouped_named_tokens_in_collection\",\n                            name,\n                            type(self).__name__,\n                            e.resultsName,\n                        ),\n                        stacklevel=3,\n                    )\n\n        return super()._setResultsName(name, listAllMatches)\n\n\nclass OneOrMore(_MultipleMatch):\n    \"\"\"\n    Repetition of one or more of the given expression.\n\n    Parameters:\n    - expr - expression that must match one or more times\n    - stop_on - (default= ``None``) - expression for a terminating sentinel\n         (only required if the sentinel would ordinarily match the repetition\n         expression)\n\n    Example::\n\n        data_word = Word(alphas)\n        label = data_word + FollowedBy(':')\n        attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).set_parse_action(' '.join))\n\n        text = \"shape: SQUARE posn: upper left color: BLACK\"\n        attr_expr[1, ...].parse_string(text).pprint()  # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']]\n\n        # use stop_on attribute for OneOrMore to avoid reading label string as part of the data\n        attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))\n        OneOrMore(attr_expr).parse_string(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']]\n\n        # could also be written as\n        (attr_expr * (1,)).parse_string(text).pprint()\n    \"\"\"\n\n    def _generateDefaultName(self):\n        return \"{\" + str(self.expr) + \"}...\"\n\n\nclass ZeroOrMore(_MultipleMatch):\n    \"\"\"\n    Optional repetition of zero or more of the given expression.\n\n    Parameters:\n    - ``expr`` - expression that must match zero or more times\n    - ``stop_on`` - expression for a terminating sentinel\n      (only required if the sentinel would ordinarily match the repetition\n      expression) - (default= ``None``)\n\n    Example: similar to :class:`OneOrMore`\n    \"\"\"\n\n    def __init__(\n        self,\n        expr: ParserElement,\n        stop_on: typing.Optional[Union[ParserElement, str]] = None,\n        *,\n        stopOn: typing.Optional[Union[ParserElement, str]] = None,\n    ):\n        super().__init__(expr, stopOn=stopOn or stop_on)\n        self.mayReturnEmpty = True\n\n    def parseImpl(self, instring, loc, doActions=True):\n        try:\n            return super().parseImpl(instring, loc, doActions)\n        except (ParseException, IndexError):\n            return loc, ParseResults([], name=self.resultsName)\n\n    def _generateDefaultName(self):\n        return \"[\" + str(self.expr) + \"]...\"\n\n\nclass _NullToken:\n    def __bool__(self):\n        return False\n\n    def __str__(self):\n        return \"\"\n\n\nclass Opt(ParseElementEnhance):\n    \"\"\"\n    Optional matching of the given expression.\n\n    Parameters:\n    - ``expr`` - expression that must match zero or more times\n    - ``default`` (optional) - value to be returned if the optional expression is not found.\n\n    Example::\n\n        # US postal code can be a 5-digit zip, plus optional 4-digit qualifier\n        zip = Combine(Word(nums, exact=5) + Opt('-' + Word(nums, exact=4)))\n        zip.run_tests('''\n            # traditional ZIP code\n            12345\n\n            # ZIP+4 form\n            12101-0001\n\n            # invalid ZIP\n            98765-\n            ''')\n\n    prints::\n\n        # traditional ZIP code\n        12345\n        ['12345']\n\n        # ZIP+4 form\n        12101-0001\n        ['12101-0001']\n\n        # invalid ZIP\n        98765-\n             ^\n        FAIL: Expected end of text (at char 5), (line:1, col:6)\n    \"\"\"\n\n    __optionalNotMatched = _NullToken()\n\n    def __init__(\n        self, expr: Union[ParserElement, str], default: Any = __optionalNotMatched\n    ):\n        super().__init__(expr, savelist=False)\n        self.saveAsList = self.expr.saveAsList\n        self.defaultValue = default\n        self.mayReturnEmpty = True\n\n    def parseImpl(self, instring, loc, doActions=True):\n        self_expr = self.expr\n        try:\n            loc, tokens = self_expr._parse(instring, loc, doActions, callPreParse=False)\n        except (ParseException, IndexError):\n            default_value = self.defaultValue\n            if default_value is not self.__optionalNotMatched:\n                if self_expr.resultsName:\n                    tokens = ParseResults([default_value])\n                    tokens[self_expr.resultsName] = default_value\n                else:\n                    tokens = [default_value]\n            else:\n                tokens = []\n        return loc, tokens\n\n    def _generateDefaultName(self):\n        inner = str(self.expr)\n        # strip off redundant inner {}'s\n        while len(inner) > 1 and inner[0 :: len(inner) - 1] == \"{}\":\n            inner = inner[1:-1]\n        return \"[\" + inner + \"]\"\n\n\nOptional = Opt\n\n\nclass SkipTo(ParseElementEnhance):\n    \"\"\"\n    Token for skipping over all undefined text until the matched\n    expression is found.\n\n    Parameters:\n    - ``expr`` - target expression marking the end of the data to be skipped\n    - ``include`` - if ``True``, the target expression is also parsed\n      (the skipped text and target expression are returned as a 2-element\n      list) (default= ``False``).\n    - ``ignore`` - (default= ``None``) used to define grammars (typically quoted strings and\n      comments) that might contain false matches to the target expression\n    - ``fail_on`` - (default= ``None``) define expressions that are not allowed to be\n      included in the skipped test; if found before the target expression is found,\n      the :class:`SkipTo` is not a match\n\n    Example::\n\n        report = '''\n            Outstanding Issues Report - 1 Jan 2000\n\n               # | Severity | Description                               |  Days Open\n            -----+----------+-------------------------------------------+-----------\n             101 | Critical | Intermittent system crash                 |          6\n              94 | Cosmetic | Spelling error on Login ('log|n')         |         14\n              79 | Minor    | System slow when running too many reports |         47\n            '''\n        integer = Word(nums)\n        SEP = Suppress('|')\n        # use SkipTo to simply match everything up until the next SEP\n        # - ignore quoted strings, so that a '|' character inside a quoted string does not match\n        # - parse action will call token.strip() for each matched token, i.e., the description body\n        string_data = SkipTo(SEP, ignore=quoted_string)\n        string_data.set_parse_action(token_map(str.strip))\n        ticket_expr = (integer(\"issue_num\") + SEP\n                      + string_data(\"sev\") + SEP\n                      + string_data(\"desc\") + SEP\n                      + integer(\"days_open\"))\n\n        for tkt in ticket_expr.search_string(report):\n            print tkt.dump()\n\n    prints::\n\n        ['101', 'Critical', 'Intermittent system crash', '6']\n        - days_open: '6'\n        - desc: 'Intermittent system crash'\n        - issue_num: '101'\n        - sev: 'Critical'\n        ['94', 'Cosmetic', \"Spelling error on Login ('log|n')\", '14']\n        - days_open: '14'\n        - desc: \"Spelling error on Login ('log|n')\"\n        - issue_num: '94'\n        - sev: 'Cosmetic'\n        ['79', 'Minor', 'System slow when running too many reports', '47']\n        - days_open: '47'\n        - desc: 'System slow when running too many reports'\n        - issue_num: '79'\n        - sev: 'Minor'\n    \"\"\"\n\n    def __init__(\n        self,\n        other: Union[ParserElement, str],\n        include: bool = False,\n        ignore: bool = None,\n        fail_on: typing.Optional[Union[ParserElement, str]] = None,\n        *,\n        failOn: Union[ParserElement, str] = None,\n    ):\n        super().__init__(other)\n        failOn = failOn or fail_on\n        self.ignoreExpr = ignore\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n        self.includeMatch = include\n        self.saveAsList = False\n        if isinstance(failOn, str_type):\n            self.failOn = self._literalStringClass(failOn)\n        else:\n            self.failOn = failOn\n        self.errmsg = \"No match found for \" + str(self.expr)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        startloc = loc\n        instrlen = len(instring)\n        self_expr_parse = self.expr._parse\n        self_failOn_canParseNext = (\n            self.failOn.canParseNext if self.failOn is not None else None\n        )\n        self_ignoreExpr_tryParse = (\n            self.ignoreExpr.tryParse if self.ignoreExpr is not None else None\n        )\n\n        tmploc = loc\n        while tmploc <= instrlen:\n            if self_failOn_canParseNext is not None:\n                # break if failOn expression matches\n                if self_failOn_canParseNext(instring, tmploc):\n                    break\n\n            if self_ignoreExpr_tryParse is not None:\n                # advance past ignore expressions\n                while 1:\n                    try:\n                        tmploc = self_ignoreExpr_tryParse(instring, tmploc)\n                    except ParseBaseException:\n                        break\n\n            try:\n                self_expr_parse(instring, tmploc, doActions=False, callPreParse=False)\n            except (ParseException, IndexError):\n                # no match, advance loc in string\n                tmploc += 1\n            else:\n                # matched skipto expr, done\n                break\n\n        else:\n            # ran off the end of the input string without matching skipto expr, fail\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        # build up return values\n        loc = tmploc\n        skiptext = instring[startloc:loc]\n        skipresult = ParseResults(skiptext)\n\n        if self.includeMatch:\n            loc, mat = self_expr_parse(instring, loc, doActions, callPreParse=False)\n            skipresult += mat\n\n        return loc, skipresult\n\n\nclass Forward(ParseElementEnhance):\n    \"\"\"\n    Forward declaration of an expression to be defined later -\n    used for recursive grammars, such as algebraic infix notation.\n    When the expression is known, it is assigned to the ``Forward``\n    variable using the ``'<<'`` operator.\n\n    Note: take care when assigning to ``Forward`` not to overlook\n    precedence of operators.\n\n    Specifically, ``'|'`` has a lower precedence than ``'<<'``, so that::\n\n        fwd_expr << a | b | c\n\n    will actually be evaluated as::\n\n        (fwd_expr << a) | b | c\n\n    thereby leaving b and c out as parseable alternatives.  It is recommended that you\n    explicitly group the values inserted into the ``Forward``::\n\n        fwd_expr << (a | b | c)\n\n    Converting to use the ``'<<='`` operator instead will avoid this problem.\n\n    See :class:`ParseResults.pprint` for an example of a recursive\n    parser created using ``Forward``.\n    \"\"\"\n\n    def __init__(self, other: typing.Optional[Union[ParserElement, str]] = None):\n        self.caller_frame = traceback.extract_stack(limit=2)[0]\n        super().__init__(other, savelist=False)\n        self.lshift_line = None\n\n    def __lshift__(self, other):\n        if hasattr(self, \"caller_frame\"):\n            del self.caller_frame\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        self.expr = other\n        self.mayIndexError = self.expr.mayIndexError\n        self.mayReturnEmpty = self.expr.mayReturnEmpty\n        self.set_whitespace_chars(\n            self.expr.whiteChars, copy_defaults=self.expr.copyDefaultWhiteChars\n        )\n        self.skipWhitespace = self.expr.skipWhitespace\n        self.saveAsList = self.expr.saveAsList\n        self.ignoreExprs.extend(self.expr.ignoreExprs)\n        self.lshift_line = traceback.extract_stack(limit=2)[-2]\n        return self\n\n    def __ilshift__(self, other):\n        return self << other\n\n    def __or__(self, other):\n        caller_line = traceback.extract_stack(limit=2)[-2]\n        if (\n            __diag__.warn_on_match_first_with_lshift_operator\n            and caller_line == self.lshift_line\n            and Diagnostics.warn_on_match_first_with_lshift_operator\n            not in self.suppress_warnings_\n        ):\n            warnings.warn(\n                \"using '<<' operator with '|' is probably an error, use '<<='\",\n                stacklevel=2,\n            )\n        ret = super().__or__(other)\n        return ret\n\n    def __del__(self):\n        # see if we are getting dropped because of '=' reassignment of var instead of '<<=' or '<<'\n        if (\n            self.expr is None\n            and __diag__.warn_on_assignment_to_Forward\n            and Diagnostics.warn_on_assignment_to_Forward not in self.suppress_warnings_\n        ):\n            warnings.warn_explicit(\n                \"Forward defined here but no expression attached later using '<<=' or '<<'\",\n                UserWarning,\n                filename=self.caller_frame.filename,\n                lineno=self.caller_frame.lineno,\n            )\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if (\n            self.expr is None\n            and __diag__.warn_on_parse_using_empty_Forward\n            and Diagnostics.warn_on_parse_using_empty_Forward\n            not in self.suppress_warnings_\n        ):\n            # walk stack until parse_string, scan_string, search_string, or transform_string is found\n            parse_fns = [\n                \"parse_string\",\n                \"scan_string\",\n                \"search_string\",\n                \"transform_string\",\n            ]\n            tb = traceback.extract_stack(limit=200)\n            for i, frm in enumerate(reversed(tb), start=1):\n                if frm.name in parse_fns:\n                    stacklevel = i + 1\n                    break\n            else:\n                stacklevel = 2\n            warnings.warn(\n                \"Forward expression was never assigned a value, will not parse any input\",\n                stacklevel=stacklevel,\n            )\n        if not ParserElement._left_recursion_enabled:\n            return super().parseImpl(instring, loc, doActions)\n        # ## Bounded Recursion algorithm ##\n        # Recursion only needs to be processed at ``Forward`` elements, since they are\n        # the only ones that can actually refer to themselves. The general idea is\n        # to handle recursion stepwise: We start at no recursion, then recurse once,\n        # recurse twice, ..., until more recursion offers no benefit (we hit the bound).\n        #\n        # The \"trick\" here is that each ``Forward`` gets evaluated in two contexts\n        # - to *match* a specific recursion level, and\n        # - to *search* the bounded recursion level\n        # and the two run concurrently. The *search* must *match* each recursion level\n        # to find the best possible match. This is handled by a memo table, which\n        # provides the previous match to the next level match attempt.\n        #\n        # See also \"Left Recursion in Parsing Expression Grammars\", Medeiros et al.\n        #\n        # There is a complication since we not only *parse* but also *transform* via\n        # actions: We do not want to run the actions too often while expanding. Thus,\n        # we expand using `doActions=False` and only run `doActions=True` if the next\n        # recursion level is acceptable.\n        with ParserElement.recursion_lock:\n            memo = ParserElement.recursion_memos\n            try:\n                # we are parsing at a specific recursion expansion - use it as-is\n                prev_loc, prev_result = memo[loc, self, doActions]\n                if isinstance(prev_result, Exception):\n                    raise prev_result\n                return prev_loc, prev_result.copy()\n            except KeyError:\n                act_key = (loc, self, True)\n                peek_key = (loc, self, False)\n                # we are searching for the best recursion expansion - keep on improving\n                # both `doActions` cases must be tracked separately here!\n                prev_loc, prev_peek = memo[peek_key] = (\n                    loc - 1,\n                    ParseException(\n                        instring, loc, \"Forward recursion without base case\", self\n                    ),\n                )\n                if doActions:\n                    memo[act_key] = memo[peek_key]\n                while True:\n                    try:\n                        new_loc, new_peek = super().parseImpl(instring, loc, False)\n                    except ParseException:\n                        # we failed before getting any match – do not hide the error\n                        if isinstance(prev_peek, Exception):\n                            raise\n                        new_loc, new_peek = prev_loc, prev_peek\n                    # the match did not get better: we are done\n                    if new_loc <= prev_loc:\n                        if doActions:\n                            # replace the match for doActions=False as well,\n                            # in case the action did backtrack\n                            prev_loc, prev_result = memo[peek_key] = memo[act_key]\n                            del memo[peek_key], memo[act_key]\n                            return prev_loc, prev_result.copy()\n                        del memo[peek_key]\n                        return prev_loc, prev_peek.copy()\n                    # the match did get better: see if we can improve further\n                    else:\n                        if doActions:\n                            try:\n                                memo[act_key] = super().parseImpl(instring, loc, True)\n                            except ParseException as e:\n                                memo[peek_key] = memo[act_key] = (new_loc, e)\n                                raise\n                        prev_loc, prev_peek = memo[peek_key] = new_loc, new_peek\n\n    def leave_whitespace(self, recursive: bool = True) -> ParserElement:\n        self.skipWhitespace = False\n        return self\n\n    def ignore_whitespace(self, recursive: bool = True) -> ParserElement:\n        self.skipWhitespace = True\n        return self\n\n    def streamline(self) -> ParserElement:\n        if not self.streamlined:\n            self.streamlined = True\n            if self.expr is not None:\n                self.expr.streamline()\n        return self\n\n    def validate(self, validateTrace=None) -> None:\n        if validateTrace is None:\n            validateTrace = []\n\n        if self not in validateTrace:\n            tmp = validateTrace[:] + [self]\n            if self.expr is not None:\n                self.expr.validate(tmp)\n        self._checkRecursion([])\n\n    def _generateDefaultName(self):\n        # Avoid infinite recursion by setting a temporary _defaultName\n        self._defaultName = \": ...\"\n\n        # Use the string representation of main expression.\n        retString = \"...\"\n        try:\n            if self.expr is not None:\n                retString = str(self.expr)[:1000]\n            else:\n                retString = \"None\"\n        finally:\n            return self.__class__.__name__ + \": \" + retString\n\n    def copy(self) -> ParserElement:\n        if self.expr is not None:\n            return super().copy()\n        else:\n            ret = Forward()\n            ret <<= self\n            return ret\n\n    def _setResultsName(self, name, list_all_matches=False):\n        if (\n            __diag__.warn_name_set_on_empty_Forward\n            and Diagnostics.warn_name_set_on_empty_Forward\n            not in self.suppress_warnings_\n        ):\n            if self.expr is None:\n                warnings.warn(\n                    \"{}: setting results name {!r} on {} expression \"\n                    \"that has no contained expression\".format(\n                        \"warn_name_set_on_empty_Forward\", name, type(self).__name__\n                    ),\n                    stacklevel=3,\n                )\n\n        return super()._setResultsName(name, list_all_matches)\n\n    ignoreWhitespace = ignore_whitespace\n    leaveWhitespace = leave_whitespace\n\n\nclass TokenConverter(ParseElementEnhance):\n    \"\"\"\n    Abstract subclass of :class:`ParseExpression`, for converting parsed results.\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str], savelist=False):\n        super().__init__(expr)  # , savelist)\n        self.saveAsList = False\n\n\nclass Combine(TokenConverter):\n    \"\"\"Converter to concatenate all matching tokens to a single string.\n    By default, the matching patterns must also be contiguous in the\n    input string; this can be disabled by specifying\n    ``'adjacent=False'`` in the constructor.\n\n    Example::\n\n        real = Word(nums) + '.' + Word(nums)\n        print(real.parse_string('3.1416')) # -> ['3', '.', '1416']\n        # will also erroneously match the following\n        print(real.parse_string('3. 1416')) # -> ['3', '.', '1416']\n\n        real = Combine(Word(nums) + '.' + Word(nums))\n        print(real.parse_string('3.1416')) # -> ['3.1416']\n        # no match when there are internal spaces\n        print(real.parse_string('3. 1416')) # -> Exception: Expected W:(0123...)\n    \"\"\"\n\n    def __init__(\n        self,\n        expr: ParserElement,\n        join_string: str = \"\",\n        adjacent: bool = True,\n        *,\n        joinString: typing.Optional[str] = None,\n    ):\n        super().__init__(expr)\n        joinString = joinString if joinString is not None else join_string\n        # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself\n        if adjacent:\n            self.leave_whitespace()\n        self.adjacent = adjacent\n        self.skipWhitespace = True\n        self.joinString = joinString\n        self.callPreparse = True\n\n    def ignore(self, other) -> ParserElement:\n        if self.adjacent:\n            ParserElement.ignore(self, other)\n        else:\n            super().ignore(other)\n        return self\n\n    def postParse(self, instring, loc, tokenlist):\n        retToks = tokenlist.copy()\n        del retToks[:]\n        retToks += ParseResults(\n            [\"\".join(tokenlist._asStringList(self.joinString))], modal=self.modalResults\n        )\n\n        if self.resultsName and retToks.haskeys():\n            return [retToks]\n        else:\n            return retToks\n\n\nclass Group(TokenConverter):\n    \"\"\"Converter to return the matched tokens as a list - useful for\n    returning tokens of :class:`ZeroOrMore` and :class:`OneOrMore` expressions.\n\n    The optional ``aslist`` argument when set to True will return the\n    parsed tokens as a Python list instead of a pyparsing ParseResults.\n\n    Example::\n\n        ident = Word(alphas)\n        num = Word(nums)\n        term = ident | num\n        func = ident + Opt(delimited_list(term))\n        print(func.parse_string(\"fn a, b, 100\"))\n        # -> ['fn', 'a', 'b', '100']\n\n        func = ident + Group(Opt(delimited_list(term)))\n        print(func.parse_string(\"fn a, b, 100\"))\n        # -> ['fn', ['a', 'b', '100']]\n    \"\"\"\n\n    def __init__(self, expr: ParserElement, aslist: bool = False):\n        super().__init__(expr)\n        self.saveAsList = True\n        self._asPythonList = aslist\n\n    def postParse(self, instring, loc, tokenlist):\n        if self._asPythonList:\n            return ParseResults.List(\n                tokenlist.asList()\n                if isinstance(tokenlist, ParseResults)\n                else list(tokenlist)\n            )\n        else:\n            return [tokenlist]\n\n\nclass Dict(TokenConverter):\n    \"\"\"Converter to return a repetitive expression as a list, but also\n    as a dictionary. Each element can also be referenced using the first\n    token in the expression as its key. Useful for tabular report\n    scraping when the first column can be used as a item key.\n\n    The optional ``asdict`` argument when set to True will return the\n    parsed tokens as a Python dict instead of a pyparsing ParseResults.\n\n    Example::\n\n        data_word = Word(alphas)\n        label = data_word + FollowedBy(':')\n\n        text = \"shape: SQUARE posn: upper left color: light blue texture: burlap\"\n        attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))\n\n        # print attributes as plain groups\n        print(attr_expr[1, ...].parse_string(text).dump())\n\n        # instead of OneOrMore(expr), parse using Dict(Group(expr)[1, ...]) - Dict will auto-assign names\n        result = Dict(Group(attr_expr)[1, ...]).parse_string(text)\n        print(result.dump())\n\n        # access named fields as dict entries, or output as dict\n        print(result['shape'])\n        print(result.as_dict())\n\n    prints::\n\n        ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap']\n        [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]\n        - color: 'light blue'\n        - posn: 'upper left'\n        - shape: 'SQUARE'\n        - texture: 'burlap'\n        SQUARE\n        {'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'}\n\n    See more examples at :class:`ParseResults` of accessing fields by results name.\n    \"\"\"\n\n    def __init__(self, expr: ParserElement, asdict: bool = False):\n        super().__init__(expr)\n        self.saveAsList = True\n        self._asPythonDict = asdict\n\n    def postParse(self, instring, loc, tokenlist):\n        for i, tok in enumerate(tokenlist):\n            if len(tok) == 0:\n                continue\n\n            ikey = tok[0]\n            if isinstance(ikey, int):\n                ikey = str(ikey).strip()\n\n            if len(tok) == 1:\n                tokenlist[ikey] = _ParseResultsWithOffset(\"\", i)\n\n            elif len(tok) == 2 and not isinstance(tok[1], ParseResults):\n                tokenlist[ikey] = _ParseResultsWithOffset(tok[1], i)\n\n            else:\n                try:\n                    dictvalue = tok.copy()  # ParseResults(i)\n                except Exception:\n                    exc = TypeError(\n                        \"could not extract dict values from parsed results\"\n                        \" - Dict expression must contain Grouped expressions\"\n                    )\n                    raise exc from None\n\n                del dictvalue[0]\n\n                if len(dictvalue) != 1 or (\n                    isinstance(dictvalue, ParseResults) and dictvalue.haskeys()\n                ):\n                    tokenlist[ikey] = _ParseResultsWithOffset(dictvalue, i)\n                else:\n                    tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0], i)\n\n        if self._asPythonDict:\n            return [tokenlist.as_dict()] if self.resultsName else tokenlist.as_dict()\n        else:\n            return [tokenlist] if self.resultsName else tokenlist\n\n\nclass Suppress(TokenConverter):\n    \"\"\"Converter for ignoring the results of a parsed expression.\n\n    Example::\n\n        source = \"a, b, c,d\"\n        wd = Word(alphas)\n        wd_list1 = wd + (',' + wd)[...]\n        print(wd_list1.parse_string(source))\n\n        # often, delimiters that are useful during parsing are just in the\n        # way afterward - use Suppress to keep them out of the parsed output\n        wd_list2 = wd + (Suppress(',') + wd)[...]\n        print(wd_list2.parse_string(source))\n\n        # Skipped text (using '...') can be suppressed as well\n        source = \"lead in START relevant text END trailing text\"\n        start_marker = Keyword(\"START\")\n        end_marker = Keyword(\"END\")\n        find_body = Suppress(...) + start_marker + ... + end_marker\n        print(find_body.parse_string(source)\n\n    prints::\n\n        ['a', ',', 'b', ',', 'c', ',', 'd']\n        ['a', 'b', 'c', 'd']\n        ['START', 'relevant text ', 'END']\n\n    (See also :class:`delimited_list`.)\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str], savelist: bool = False):\n        if expr is ...:\n            expr = _PendingSkip(NoMatch())\n        super().__init__(expr)\n\n    def __add__(self, other) -> \"ParserElement\":\n        if isinstance(self.expr, _PendingSkip):\n            return Suppress(SkipTo(other)) + other\n        else:\n            return super().__add__(other)\n\n    def __sub__(self, other) -> \"ParserElement\":\n        if isinstance(self.expr, _PendingSkip):\n            return Suppress(SkipTo(other)) - other\n        else:\n            return super().__sub__(other)\n\n    def postParse(self, instring, loc, tokenlist):\n        return []\n\n    def suppress(self) -> ParserElement:\n        return self\n\n\ndef trace_parse_action(f: ParseAction) -> ParseAction:\n    \"\"\"Decorator for debugging parse actions.\n\n    When the parse action is called, this decorator will print\n    ``\">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)\"``.\n    When the parse action completes, the decorator will print\n    ``\"<<\"`` followed by the returned value, or any exception that the parse action raised.\n\n    Example::\n\n        wd = Word(alphas)\n\n        @trace_parse_action\n        def remove_duplicate_chars(tokens):\n            return ''.join(sorted(set(''.join(tokens))))\n\n        wds = wd[1, ...].set_parse_action(remove_duplicate_chars)\n        print(wds.parse_string(\"slkdjs sld sldd sdlf sdljf\"))\n\n    prints::\n\n        >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {}))\n        <<leaving remove_duplicate_chars (ret: 'dfjkls')\n        ['dfjkls']\n    \"\"\"\n    f = _trim_arity(f)\n\n    def z(*paArgs):\n        thisFunc = f.__name__\n        s, l, t = paArgs[-3:]\n        if len(paArgs) > 3:\n            thisFunc = paArgs[0].__class__.__name__ + \".\" + thisFunc\n        sys.stderr.write(\n            \">>entering {}(line: {!r}, {}, {!r})\\n\".format(thisFunc, line(l, s), l, t)\n        )\n        try:\n            ret = f(*paArgs)\n        except Exception as exc:\n            sys.stderr.write(\"<<leaving {} (exception: {})\\n\".format(thisFunc, exc))\n            raise\n        sys.stderr.write(\"<<leaving {} (ret: {!r})\\n\".format(thisFunc, ret))\n        return ret\n\n    z.__name__ = f.__name__\n    return z\n\n\n# convenience constants for positional expressions\nempty = Empty().set_name(\"empty\")\nline_start = LineStart().set_name(\"line_start\")\nline_end = LineEnd().set_name(\"line_end\")\nstring_start = StringStart().set_name(\"string_start\")\nstring_end = StringEnd().set_name(\"string_end\")\n\n_escapedPunc = Word(_bslash, r\"\\[]-*.$+^?()~ \", exact=2).set_parse_action(\n    lambda s, l, t: t[0][1]\n)\n_escapedHexChar = Regex(r\"\\\\0?[xX][0-9a-fA-F]+\").set_parse_action(\n    lambda s, l, t: chr(int(t[0].lstrip(r\"\\0x\"), 16))\n)\n_escapedOctChar = Regex(r\"\\\\0[0-7]+\").set_parse_action(\n    lambda s, l, t: chr(int(t[0][1:], 8))\n)\n_singleChar = (\n    _escapedPunc | _escapedHexChar | _escapedOctChar | CharsNotIn(r\"\\]\", exact=1)\n)\n_charRange = Group(_singleChar + Suppress(\"-\") + _singleChar)\n_reBracketExpr = (\n    Literal(\"[\")\n    + Opt(\"^\").set_results_name(\"negate\")\n    + Group(OneOrMore(_charRange | _singleChar)).set_results_name(\"body\")\n    + \"]\"\n)\n\n\ndef srange(s: str) -> str:\n    r\"\"\"Helper to easily define string ranges for use in :class:`Word`\n    construction. Borrows syntax from regexp ``'[]'`` string range\n    definitions::\n\n        srange(\"[0-9]\")   -> \"0123456789\"\n        srange(\"[a-z]\")   -> \"abcdefghijklmnopqrstuvwxyz\"\n        srange(\"[a-z$_]\") -> \"abcdefghijklmnopqrstuvwxyz$_\"\n\n    The input string must be enclosed in []'s, and the returned string\n    is the expanded character set joined into a single string. The\n    values enclosed in the []'s may be:\n\n    - a single character\n    - an escaped character with a leading backslash (such as ``\\-``\n      or ``\\]``)\n    - an escaped hex character with a leading ``'\\x'``\n      (``\\x21``, which is a ``'!'`` character) (``\\0x##``\n      is also supported for backwards compatibility)\n    - an escaped octal character with a leading ``'\\0'``\n      (``\\041``, which is a ``'!'`` character)\n    - a range of any of the above, separated by a dash (``'a-z'``,\n      etc.)\n    - any combination of the above (``'aeiouy'``,\n      ``'a-zA-Z0-9_$'``, etc.)\n    \"\"\"\n    _expanded = (\n        lambda p: p\n        if not isinstance(p, ParseResults)\n        else \"\".join(chr(c) for c in range(ord(p[0]), ord(p[1]) + 1))\n    )\n    try:\n        return \"\".join(_expanded(part) for part in _reBracketExpr.parse_string(s).body)\n    except Exception:\n        return \"\"\n\n\ndef token_map(func, *args) -> ParseAction:\n    \"\"\"Helper to define a parse action by mapping a function to all\n    elements of a :class:`ParseResults` list. If any additional args are passed,\n    they are forwarded to the given function as additional arguments\n    after the token, as in\n    ``hex_integer = Word(hexnums).set_parse_action(token_map(int, 16))``,\n    which will convert the parsed data to an integer using base 16.\n\n    Example (compare the last to example in :class:`ParserElement.transform_string`::\n\n        hex_ints = Word(hexnums)[1, ...].set_parse_action(token_map(int, 16))\n        hex_ints.run_tests('''\n            00 11 22 aa FF 0a 0d 1a\n            ''')\n\n        upperword = Word(alphas).set_parse_action(token_map(str.upper))\n        upperword[1, ...].run_tests('''\n            my kingdom for a horse\n            ''')\n\n        wd = Word(alphas).set_parse_action(token_map(str.title))\n        wd[1, ...].set_parse_action(' '.join).run_tests('''\n            now is the winter of our discontent made glorious summer by this sun of york\n            ''')\n\n    prints::\n\n        00 11 22 aa FF 0a 0d 1a\n        [0, 17, 34, 170, 255, 10, 13, 26]\n\n        my kingdom for a horse\n        ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE']\n\n        now is the winter of our discontent made glorious summer by this sun of york\n        ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York']\n    \"\"\"\n\n    def pa(s, l, t):\n        return [func(tokn, *args) for tokn in t]\n\n    func_name = getattr(func, \"__name__\", getattr(func, \"__class__\").__name__)\n    pa.__name__ = func_name\n\n    return pa\n\n\ndef autoname_elements() -> None:\n    \"\"\"\n    Utility to simplify mass-naming of parser elements, for\n    generating railroad diagram with named subdiagrams.\n    \"\"\"\n    for name, var in sys._getframe().f_back.f_locals.items():\n        if isinstance(var, ParserElement) and not var.customName:\n            var.set_name(name)\n\n\ndbl_quoted_string = Combine(\n    Regex(r'\"(?:[^\"\\n\\r\\\\]|(?:\"\")|(?:\\\\(?:[^x]|x[0-9a-fA-F]+)))*') + '\"'\n).set_name(\"string enclosed in double quotes\")\n\nsgl_quoted_string = Combine(\n    Regex(r\"'(?:[^'\\n\\r\\\\]|(?:'')|(?:\\\\(?:[^x]|x[0-9a-fA-F]+)))*\") + \"'\"\n).set_name(\"string enclosed in single quotes\")\n\nquoted_string = Combine(\n    Regex(r'\"(?:[^\"\\n\\r\\\\]|(?:\"\")|(?:\\\\(?:[^x]|x[0-9a-fA-F]+)))*') + '\"'\n    | Regex(r\"'(?:[^'\\n\\r\\\\]|(?:'')|(?:\\\\(?:[^x]|x[0-9a-fA-F]+)))*\") + \"'\"\n).set_name(\"quotedString using single or double quotes\")\n\nunicode_string = Combine(\"u\" + quoted_string.copy()).set_name(\"unicode string literal\")\n\n\nalphas8bit = srange(r\"[\\0xc0-\\0xd6\\0xd8-\\0xf6\\0xf8-\\0xff]\")\npunc8bit = srange(r\"[\\0xa1-\\0xbf\\0xd7\\0xf7]\")\n\n# build list of built-in expressions, for future reference if a global default value\n# gets updated\n_builtin_exprs: List[ParserElement] = [\n    v for v in vars().values() if isinstance(v, ParserElement)\n]\n\n# backward compatibility names\ntokenMap = token_map\nconditionAsParseAction = condition_as_parse_action\nnullDebugAction = null_debug_action\nsglQuotedString = sgl_quoted_string\ndblQuotedString = dbl_quoted_string\nquotedString = quoted_string\nunicodeString = unicode_string\nlineStart = line_start\nlineEnd = line_end\nstringStart = string_start\nstringEnd = string_end\ntraceParseAction = trace_parse_action\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pyparsing/diagram/__init__.py",
    "content": "import railroad\nfrom pip._vendor import pyparsing\nimport typing\nfrom typing import (\n    List,\n    NamedTuple,\n    Generic,\n    TypeVar,\n    Dict,\n    Callable,\n    Set,\n    Iterable,\n)\nfrom jinja2 import Template\nfrom io import StringIO\nimport inspect\n\n\njinja2_template_source = \"\"\"\\\n<!DOCTYPE html>\n<html>\n<head>\n    {% if not head %}\n        <style type=\"text/css\">\n            .railroad-heading {\n                font-family: monospace;\n            }\n        </style>\n    {% else %}\n        {{ head | safe }}\n    {% endif %}\n</head>\n<body>\n{{ body | safe }}\n{% for diagram in diagrams %}\n    <div class=\"railroad-group\">\n        <h1 class=\"railroad-heading\">{{ diagram.title }}</h1>\n        <div class=\"railroad-description\">{{ diagram.text }}</div>\n        <div class=\"railroad-svg\">\n            {{ diagram.svg }}\n        </div>\n    </div>\n{% endfor %}\n</body>\n</html>\n\"\"\"\n\ntemplate = Template(jinja2_template_source)\n\n# Note: ideally this would be a dataclass, but we're supporting Python 3.5+ so we can't do this yet\nNamedDiagram = NamedTuple(\n    \"NamedDiagram\",\n    [(\"name\", str), (\"diagram\", typing.Optional[railroad.DiagramItem]), (\"index\", int)],\n)\n\"\"\"\nA simple structure for associating a name with a railroad diagram\n\"\"\"\n\nT = TypeVar(\"T\")\n\n\nclass EachItem(railroad.Group):\n    \"\"\"\n    Custom railroad item to compose a:\n    - Group containing a\n      - OneOrMore containing a\n        - Choice of the elements in the Each\n    with the group label indicating that all must be matched\n    \"\"\"\n\n    all_label = \"[ALL]\"\n\n    def __init__(self, *items):\n        choice_item = railroad.Choice(len(items) - 1, *items)\n        one_or_more_item = railroad.OneOrMore(item=choice_item)\n        super().__init__(one_or_more_item, label=self.all_label)\n\n\nclass AnnotatedItem(railroad.Group):\n    \"\"\"\n    Simple subclass of Group that creates an annotation label\n    \"\"\"\n\n    def __init__(self, label: str, item):\n        super().__init__(item=item, label=\"[{}]\".format(label) if label else label)\n\n\nclass EditablePartial(Generic[T]):\n    \"\"\"\n    Acts like a functools.partial, but can be edited. In other words, it represents a type that hasn't yet been\n    constructed.\n    \"\"\"\n\n    # We need this here because the railroad constructors actually transform the data, so can't be called until the\n    # entire tree is assembled\n\n    def __init__(self, func: Callable[..., T], args: list, kwargs: dict):\n        self.func = func\n        self.args = args\n        self.kwargs = kwargs\n\n    @classmethod\n    def from_call(cls, func: Callable[..., T], *args, **kwargs) -> \"EditablePartial[T]\":\n        \"\"\"\n        If you call this function in the same way that you would call the constructor, it will store the arguments\n        as you expect. For example EditablePartial.from_call(Fraction, 1, 3)() == Fraction(1, 3)\n        \"\"\"\n        return EditablePartial(func=func, args=list(args), kwargs=kwargs)\n\n    @property\n    def name(self):\n        return self.kwargs[\"name\"]\n\n    def __call__(self) -> T:\n        \"\"\"\n        Evaluate the partial and return the result\n        \"\"\"\n        args = self.args.copy()\n        kwargs = self.kwargs.copy()\n\n        # This is a helpful hack to allow you to specify varargs parameters (e.g. *args) as keyword args (e.g.\n        # args=['list', 'of', 'things'])\n        arg_spec = inspect.getfullargspec(self.func)\n        if arg_spec.varargs in self.kwargs:\n            args += kwargs.pop(arg_spec.varargs)\n\n        return self.func(*args, **kwargs)\n\n\ndef railroad_to_html(diagrams: List[NamedDiagram], **kwargs) -> str:\n    \"\"\"\n    Given a list of NamedDiagram, produce a single HTML string that visualises those diagrams\n    :params kwargs: kwargs to be passed in to the template\n    \"\"\"\n    data = []\n    for diagram in diagrams:\n        if diagram.diagram is None:\n            continue\n        io = StringIO()\n        diagram.diagram.writeSvg(io.write)\n        title = diagram.name\n        if diagram.index == 0:\n            title += \" (root)\"\n        data.append({\"title\": title, \"text\": \"\", \"svg\": io.getvalue()})\n\n    return template.render(diagrams=data, **kwargs)\n\n\ndef resolve_partial(partial: \"EditablePartial[T]\") -> T:\n    \"\"\"\n    Recursively resolves a collection of Partials into whatever type they are\n    \"\"\"\n    if isinstance(partial, EditablePartial):\n        partial.args = resolve_partial(partial.args)\n        partial.kwargs = resolve_partial(partial.kwargs)\n        return partial()\n    elif isinstance(partial, list):\n        return [resolve_partial(x) for x in partial]\n    elif isinstance(partial, dict):\n        return {key: resolve_partial(x) for key, x in partial.items()}\n    else:\n        return partial\n\n\ndef to_railroad(\n    element: pyparsing.ParserElement,\n    diagram_kwargs: typing.Optional[dict] = None,\n    vertical: int = 3,\n    show_results_names: bool = False,\n    show_groups: bool = False,\n) -> List[NamedDiagram]:\n    \"\"\"\n    Convert a pyparsing element tree into a list of diagrams. This is the recommended entrypoint to diagram\n    creation if you want to access the Railroad tree before it is converted to HTML\n    :param element: base element of the parser being diagrammed\n    :param diagram_kwargs: kwargs to pass to the Diagram() constructor\n    :param vertical: (optional) - int - limit at which number of alternatives should be\n       shown vertically instead of horizontally\n    :param show_results_names - bool to indicate whether results name annotations should be\n       included in the diagram\n    :param show_groups - bool to indicate whether groups should be highlighted with an unlabeled\n       surrounding box\n    \"\"\"\n    # Convert the whole tree underneath the root\n    lookup = ConverterState(diagram_kwargs=diagram_kwargs or {})\n    _to_diagram_element(\n        element,\n        lookup=lookup,\n        parent=None,\n        vertical=vertical,\n        show_results_names=show_results_names,\n        show_groups=show_groups,\n    )\n\n    root_id = id(element)\n    # Convert the root if it hasn't been already\n    if root_id in lookup:\n        if not element.customName:\n            lookup[root_id].name = \"\"\n        lookup[root_id].mark_for_extraction(root_id, lookup, force=True)\n\n    # Now that we're finished, we can convert from intermediate structures into Railroad elements\n    diags = list(lookup.diagrams.values())\n    if len(diags) > 1:\n        # collapse out duplicate diags with the same name\n        seen = set()\n        deduped_diags = []\n        for d in diags:\n            # don't extract SkipTo elements, they are uninformative as subdiagrams\n            if d.name == \"...\":\n                continue\n            if d.name is not None and d.name not in seen:\n                seen.add(d.name)\n                deduped_diags.append(d)\n        resolved = [resolve_partial(partial) for partial in deduped_diags]\n    else:\n        # special case - if just one diagram, always display it, even if\n        # it has no name\n        resolved = [resolve_partial(partial) for partial in diags]\n    return sorted(resolved, key=lambda diag: diag.index)\n\n\ndef _should_vertical(\n    specification: int, exprs: Iterable[pyparsing.ParserElement]\n) -> bool:\n    \"\"\"\n    Returns true if we should return a vertical list of elements\n    \"\"\"\n    if specification is None:\n        return False\n    else:\n        return len(_visible_exprs(exprs)) >= specification\n\n\nclass ElementState:\n    \"\"\"\n    State recorded for an individual pyparsing Element\n    \"\"\"\n\n    # Note: this should be a dataclass, but we have to support Python 3.5\n    def __init__(\n        self,\n        element: pyparsing.ParserElement,\n        converted: EditablePartial,\n        parent: EditablePartial,\n        number: int,\n        name: str = None,\n        parent_index: typing.Optional[int] = None,\n    ):\n        #: The pyparsing element that this represents\n        self.element: pyparsing.ParserElement = element\n        #: The name of the element\n        self.name: typing.Optional[str] = name\n        #: The output Railroad element in an unconverted state\n        self.converted: EditablePartial = converted\n        #: The parent Railroad element, which we store so that we can extract this if it's duplicated\n        self.parent: EditablePartial = parent\n        #: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram\n        self.number: int = number\n        #: The index of this inside its parent\n        self.parent_index: typing.Optional[int] = parent_index\n        #: If true, we should extract this out into a subdiagram\n        self.extract: bool = False\n        #: If true, all of this element's children have been filled out\n        self.complete: bool = False\n\n    def mark_for_extraction(\n        self, el_id: int, state: \"ConverterState\", name: str = None, force: bool = False\n    ):\n        \"\"\"\n        Called when this instance has been seen twice, and thus should eventually be extracted into a sub-diagram\n        :param el_id: id of the element\n        :param state: element/diagram state tracker\n        :param name: name to use for this element's text\n        :param force: If true, force extraction now, regardless of the state of this. Only useful for extracting the\n        root element when we know we're finished\n        \"\"\"\n        self.extract = True\n\n        # Set the name\n        if not self.name:\n            if name:\n                # Allow forcing a custom name\n                self.name = name\n            elif self.element.customName:\n                self.name = self.element.customName\n            else:\n                self.name = \"\"\n\n        # Just because this is marked for extraction doesn't mean we can do it yet. We may have to wait for children\n        # to be added\n        # Also, if this is just a string literal etc, don't bother extracting it\n        if force or (self.complete and _worth_extracting(self.element)):\n            state.extract_into_diagram(el_id)\n\n\nclass ConverterState:\n    \"\"\"\n    Stores some state that persists between recursions into the element tree\n    \"\"\"\n\n    def __init__(self, diagram_kwargs: typing.Optional[dict] = None):\n        #: A dictionary mapping ParserElements to state relating to them\n        self._element_diagram_states: Dict[int, ElementState] = {}\n        #: A dictionary mapping ParserElement IDs to subdiagrams generated from them\n        self.diagrams: Dict[int, EditablePartial[NamedDiagram]] = {}\n        #: The index of the next unnamed element\n        self.unnamed_index: int = 1\n        #: The index of the next element. This is used for sorting\n        self.index: int = 0\n        #: Shared kwargs that are used to customize the construction of diagrams\n        self.diagram_kwargs: dict = diagram_kwargs or {}\n        self.extracted_diagram_names: Set[str] = set()\n\n    def __setitem__(self, key: int, value: ElementState):\n        self._element_diagram_states[key] = value\n\n    def __getitem__(self, key: int) -> ElementState:\n        return self._element_diagram_states[key]\n\n    def __delitem__(self, key: int):\n        del self._element_diagram_states[key]\n\n    def __contains__(self, key: int):\n        return key in self._element_diagram_states\n\n    def generate_unnamed(self) -> int:\n        \"\"\"\n        Generate a number used in the name of an otherwise unnamed diagram\n        \"\"\"\n        self.unnamed_index += 1\n        return self.unnamed_index\n\n    def generate_index(self) -> int:\n        \"\"\"\n        Generate a number used to index a diagram\n        \"\"\"\n        self.index += 1\n        return self.index\n\n    def extract_into_diagram(self, el_id: int):\n        \"\"\"\n        Used when we encounter the same token twice in the same tree. When this\n        happens, we replace all instances of that token with a terminal, and\n        create a new subdiagram for the token\n        \"\"\"\n        position = self[el_id]\n\n        # Replace the original definition of this element with a regular block\n        if position.parent:\n            ret = EditablePartial.from_call(railroad.NonTerminal, text=position.name)\n            if \"item\" in position.parent.kwargs:\n                position.parent.kwargs[\"item\"] = ret\n            elif \"items\" in position.parent.kwargs:\n                position.parent.kwargs[\"items\"][position.parent_index] = ret\n\n        # If the element we're extracting is a group, skip to its content but keep the title\n        if position.converted.func == railroad.Group:\n            content = position.converted.kwargs[\"item\"]\n        else:\n            content = position.converted\n\n        self.diagrams[el_id] = EditablePartial.from_call(\n            NamedDiagram,\n            name=position.name,\n            diagram=EditablePartial.from_call(\n                railroad.Diagram, content, **self.diagram_kwargs\n            ),\n            index=position.number,\n        )\n\n        del self[el_id]\n\n\ndef _worth_extracting(element: pyparsing.ParserElement) -> bool:\n    \"\"\"\n    Returns true if this element is worth having its own sub-diagram. Simply, if any of its children\n    themselves have children, then its complex enough to extract\n    \"\"\"\n    children = element.recurse()\n    return any(child.recurse() for child in children)\n\n\ndef _apply_diagram_item_enhancements(fn):\n    \"\"\"\n    decorator to ensure enhancements to a diagram item (such as results name annotations)\n    get applied on return from _to_diagram_element (we do this since there are several\n    returns in _to_diagram_element)\n    \"\"\"\n\n    def _inner(\n        element: pyparsing.ParserElement,\n        parent: typing.Optional[EditablePartial],\n        lookup: ConverterState = None,\n        vertical: int = None,\n        index: int = 0,\n        name_hint: str = None,\n        show_results_names: bool = False,\n        show_groups: bool = False,\n    ) -> typing.Optional[EditablePartial]:\n\n        ret = fn(\n            element,\n            parent,\n            lookup,\n            vertical,\n            index,\n            name_hint,\n            show_results_names,\n            show_groups,\n        )\n\n        # apply annotation for results name, if present\n        if show_results_names and ret is not None:\n            element_results_name = element.resultsName\n            if element_results_name:\n                # add \"*\" to indicate if this is a \"list all results\" name\n                element_results_name += \"\" if element.modalResults else \"*\"\n                ret = EditablePartial.from_call(\n                    railroad.Group, item=ret, label=element_results_name\n                )\n\n        return ret\n\n    return _inner\n\n\ndef _visible_exprs(exprs: Iterable[pyparsing.ParserElement]):\n    non_diagramming_exprs = (\n        pyparsing.ParseElementEnhance,\n        pyparsing.PositionToken,\n        pyparsing.And._ErrorStop,\n    )\n    return [\n        e\n        for e in exprs\n        if not (e.customName or e.resultsName or isinstance(e, non_diagramming_exprs))\n    ]\n\n\n@_apply_diagram_item_enhancements\ndef _to_diagram_element(\n    element: pyparsing.ParserElement,\n    parent: typing.Optional[EditablePartial],\n    lookup: ConverterState = None,\n    vertical: int = None,\n    index: int = 0,\n    name_hint: str = None,\n    show_results_names: bool = False,\n    show_groups: bool = False,\n) -> typing.Optional[EditablePartial]:\n    \"\"\"\n    Recursively converts a PyParsing Element to a railroad Element\n    :param lookup: The shared converter state that keeps track of useful things\n    :param index: The index of this element within the parent\n    :param parent: The parent of this element in the output tree\n    :param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default),\n    it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never\n    do so\n    :param name_hint: If provided, this will override the generated name\n    :param show_results_names: bool flag indicating whether to add annotations for results names\n    :returns: The converted version of the input element, but as a Partial that hasn't yet been constructed\n    :param show_groups: bool flag indicating whether to show groups using bounding box\n    \"\"\"\n    exprs = element.recurse()\n    name = name_hint or element.customName or element.__class__.__name__\n\n    # Python's id() is used to provide a unique identifier for elements\n    el_id = id(element)\n\n    element_results_name = element.resultsName\n\n    # Here we basically bypass processing certain wrapper elements if they contribute nothing to the diagram\n    if not element.customName:\n        if isinstance(\n            element,\n            (\n                # pyparsing.TokenConverter,\n                # pyparsing.Forward,\n                pyparsing.Located,\n            ),\n        ):\n            # However, if this element has a useful custom name, and its child does not, we can pass it on to the child\n            if exprs:\n                if not exprs[0].customName:\n                    propagated_name = name\n                else:\n                    propagated_name = None\n\n                return _to_diagram_element(\n                    element.expr,\n                    parent=parent,\n                    lookup=lookup,\n                    vertical=vertical,\n                    index=index,\n                    name_hint=propagated_name,\n                    show_results_names=show_results_names,\n                    show_groups=show_groups,\n                )\n\n    # If the element isn't worth extracting, we always treat it as the first time we say it\n    if _worth_extracting(element):\n        if el_id in lookup:\n            # If we've seen this element exactly once before, we are only just now finding out that it's a duplicate,\n            # so we have to extract it into a new diagram.\n            looked_up = lookup[el_id]\n            looked_up.mark_for_extraction(el_id, lookup, name=name_hint)\n            ret = EditablePartial.from_call(railroad.NonTerminal, text=looked_up.name)\n            return ret\n\n        elif el_id in lookup.diagrams:\n            # If we have seen the element at least twice before, and have already extracted it into a subdiagram, we\n            # just put in a marker element that refers to the sub-diagram\n            ret = EditablePartial.from_call(\n                railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs[\"name\"]\n            )\n            return ret\n\n    # Recursively convert child elements\n    # Here we find the most relevant Railroad element for matching pyparsing Element\n    # We use ``items=[]`` here to hold the place for where the child elements will go once created\n    if isinstance(element, pyparsing.And):\n        # detect And's created with ``expr*N`` notation - for these use a OneOrMore with a repeat\n        # (all will have the same name, and resultsName)\n        if not exprs:\n            return None\n        if len(set((e.name, e.resultsName) for e in exprs)) == 1:\n            ret = EditablePartial.from_call(\n                railroad.OneOrMore, item=\"\", repeat=str(len(exprs))\n            )\n        elif _should_vertical(vertical, exprs):\n            ret = EditablePartial.from_call(railroad.Stack, items=[])\n        else:\n            ret = EditablePartial.from_call(railroad.Sequence, items=[])\n    elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)):\n        if not exprs:\n            return None\n        if _should_vertical(vertical, exprs):\n            ret = EditablePartial.from_call(railroad.Choice, 0, items=[])\n        else:\n            ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[])\n    elif isinstance(element, pyparsing.Each):\n        if not exprs:\n            return None\n        ret = EditablePartial.from_call(EachItem, items=[])\n    elif isinstance(element, pyparsing.NotAny):\n        ret = EditablePartial.from_call(AnnotatedItem, label=\"NOT\", item=\"\")\n    elif isinstance(element, pyparsing.FollowedBy):\n        ret = EditablePartial.from_call(AnnotatedItem, label=\"LOOKAHEAD\", item=\"\")\n    elif isinstance(element, pyparsing.PrecededBy):\n        ret = EditablePartial.from_call(AnnotatedItem, label=\"LOOKBEHIND\", item=\"\")\n    elif isinstance(element, pyparsing.Group):\n        if show_groups:\n            ret = EditablePartial.from_call(AnnotatedItem, label=\"\", item=\"\")\n        else:\n            ret = EditablePartial.from_call(railroad.Group, label=\"\", item=\"\")\n    elif isinstance(element, pyparsing.TokenConverter):\n        ret = EditablePartial.from_call(\n            AnnotatedItem, label=type(element).__name__.lower(), item=\"\"\n        )\n    elif isinstance(element, pyparsing.Opt):\n        ret = EditablePartial.from_call(railroad.Optional, item=\"\")\n    elif isinstance(element, pyparsing.OneOrMore):\n        ret = EditablePartial.from_call(railroad.OneOrMore, item=\"\")\n    elif isinstance(element, pyparsing.ZeroOrMore):\n        ret = EditablePartial.from_call(railroad.ZeroOrMore, item=\"\")\n    elif isinstance(element, pyparsing.Group):\n        ret = EditablePartial.from_call(\n            railroad.Group, item=None, label=element_results_name\n        )\n    elif isinstance(element, pyparsing.Empty) and not element.customName:\n        # Skip unnamed \"Empty\" elements\n        ret = None\n    elif len(exprs) > 1:\n        ret = EditablePartial.from_call(railroad.Sequence, items=[])\n    elif len(exprs) > 0 and not element_results_name:\n        ret = EditablePartial.from_call(railroad.Group, item=\"\", label=name)\n    else:\n        terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName)\n        ret = terminal\n\n    if ret is None:\n        return\n\n    # Indicate this element's position in the tree so we can extract it if necessary\n    lookup[el_id] = ElementState(\n        element=element,\n        converted=ret,\n        parent=parent,\n        parent_index=index,\n        number=lookup.generate_index(),\n    )\n    if element.customName:\n        lookup[el_id].mark_for_extraction(el_id, lookup, element.customName)\n\n    i = 0\n    for expr in exprs:\n        # Add a placeholder index in case we have to extract the child before we even add it to the parent\n        if \"items\" in ret.kwargs:\n            ret.kwargs[\"items\"].insert(i, None)\n\n        item = _to_diagram_element(\n            expr,\n            parent=ret,\n            lookup=lookup,\n            vertical=vertical,\n            index=i,\n            show_results_names=show_results_names,\n            show_groups=show_groups,\n        )\n\n        # Some elements don't need to be shown in the diagram\n        if item is not None:\n            if \"item\" in ret.kwargs:\n                ret.kwargs[\"item\"] = item\n            elif \"items\" in ret.kwargs:\n                # If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal\n                ret.kwargs[\"items\"][i] = item\n                i += 1\n        elif \"items\" in ret.kwargs:\n            # If we're supposed to skip this element, remove it from the parent\n            del ret.kwargs[\"items\"][i]\n\n    # If all this items children are none, skip this item\n    if ret and (\n        (\"items\" in ret.kwargs and len(ret.kwargs[\"items\"]) == 0)\n        or (\"item\" in ret.kwargs and ret.kwargs[\"item\"] is None)\n    ):\n        ret = EditablePartial.from_call(railroad.Terminal, name)\n\n    # Mark this element as \"complete\", ie it has all of its children\n    if el_id in lookup:\n        lookup[el_id].complete = True\n\n    if el_id in lookup and lookup[el_id].extract and lookup[el_id].complete:\n        lookup.extract_into_diagram(el_id)\n        if ret is not None:\n            ret = EditablePartial.from_call(\n                railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs[\"name\"]\n            )\n\n    return ret\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pyparsing/exceptions.py",
    "content": "# exceptions.py\n\nimport re\nimport sys\nimport typing\n\nfrom .util import col, line, lineno, _collapse_string_to_ranges\nfrom .unicode import pyparsing_unicode as ppu\n\n\nclass ExceptionWordUnicode(ppu.Latin1, ppu.LatinA, ppu.LatinB, ppu.Greek, ppu.Cyrillic):\n    pass\n\n\n_extract_alphanums = _collapse_string_to_ranges(ExceptionWordUnicode.alphanums)\n_exception_word_extractor = re.compile(\"([\" + _extract_alphanums + \"]{1,16})|.\")\n\n\nclass ParseBaseException(Exception):\n    \"\"\"base exception class for all parsing runtime exceptions\"\"\"\n\n    # Performance tuning: we construct a *lot* of these, so keep this\n    # constructor as small and fast as possible\n    def __init__(\n        self,\n        pstr: str,\n        loc: int = 0,\n        msg: typing.Optional[str] = None,\n        elem=None,\n    ):\n        self.loc = loc\n        if msg is None:\n            self.msg = pstr\n            self.pstr = \"\"\n        else:\n            self.msg = msg\n            self.pstr = pstr\n        self.parser_element = self.parserElement = elem\n        self.args = (pstr, loc, msg)\n\n    @staticmethod\n    def explain_exception(exc, depth=16):\n        \"\"\"\n        Method to take an exception and translate the Python internal traceback into a list\n        of the pyparsing expressions that caused the exception to be raised.\n\n        Parameters:\n\n        - exc - exception raised during parsing (need not be a ParseException, in support\n          of Python exceptions that might be raised in a parse action)\n        - depth (default=16) - number of levels back in the stack trace to list expression\n          and function names; if None, the full stack trace names will be listed; if 0, only\n          the failing input line, marker, and exception string will be shown\n\n        Returns a multi-line string listing the ParserElements and/or function names in the\n        exception's stack trace.\n        \"\"\"\n        import inspect\n        from .core import ParserElement\n\n        if depth is None:\n            depth = sys.getrecursionlimit()\n        ret = []\n        if isinstance(exc, ParseBaseException):\n            ret.append(exc.line)\n            ret.append(\" \" * (exc.column - 1) + \"^\")\n        ret.append(\"{}: {}\".format(type(exc).__name__, exc))\n\n        if depth > 0:\n            callers = inspect.getinnerframes(exc.__traceback__, context=depth)\n            seen = set()\n            for i, ff in enumerate(callers[-depth:]):\n                frm = ff[0]\n\n                f_self = frm.f_locals.get(\"self\", None)\n                if isinstance(f_self, ParserElement):\n                    if frm.f_code.co_name not in (\"parseImpl\", \"_parseNoCache\"):\n                        continue\n                    if id(f_self) in seen:\n                        continue\n                    seen.add(id(f_self))\n\n                    self_type = type(f_self)\n                    ret.append(\n                        \"{}.{} - {}\".format(\n                            self_type.__module__, self_type.__name__, f_self\n                        )\n                    )\n\n                elif f_self is not None:\n                    self_type = type(f_self)\n                    ret.append(\"{}.{}\".format(self_type.__module__, self_type.__name__))\n\n                else:\n                    code = frm.f_code\n                    if code.co_name in (\"wrapper\", \"<module>\"):\n                        continue\n\n                    ret.append(\"{}\".format(code.co_name))\n\n                depth -= 1\n                if not depth:\n                    break\n\n        return \"\\n\".join(ret)\n\n    @classmethod\n    def _from_exception(cls, pe):\n        \"\"\"\n        internal factory method to simplify creating one type of ParseException\n        from another - avoids having __init__ signature conflicts among subclasses\n        \"\"\"\n        return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)\n\n    @property\n    def line(self) -> str:\n        \"\"\"\n        Return the line of text where the exception occurred.\n        \"\"\"\n        return line(self.loc, self.pstr)\n\n    @property\n    def lineno(self) -> int:\n        \"\"\"\n        Return the 1-based line number of text where the exception occurred.\n        \"\"\"\n        return lineno(self.loc, self.pstr)\n\n    @property\n    def col(self) -> int:\n        \"\"\"\n        Return the 1-based column on the line of text where the exception occurred.\n        \"\"\"\n        return col(self.loc, self.pstr)\n\n    @property\n    def column(self) -> int:\n        \"\"\"\n        Return the 1-based column on the line of text where the exception occurred.\n        \"\"\"\n        return col(self.loc, self.pstr)\n\n    def __str__(self) -> str:\n        if self.pstr:\n            if self.loc >= len(self.pstr):\n                foundstr = \", found end of text\"\n            else:\n                # pull out next word at error location\n                found_match = _exception_word_extractor.match(self.pstr, self.loc)\n                if found_match is not None:\n                    found = found_match.group(0)\n                else:\n                    found = self.pstr[self.loc : self.loc + 1]\n                foundstr = (\", found %r\" % found).replace(r\"\\\\\", \"\\\\\")\n        else:\n            foundstr = \"\"\n        return \"{}{}  (at char {}), (line:{}, col:{})\".format(\n            self.msg, foundstr, self.loc, self.lineno, self.column\n        )\n\n    def __repr__(self):\n        return str(self)\n\n    def mark_input_line(self, marker_string: str = None, *, markerString=\">!<\") -> str:\n        \"\"\"\n        Extracts the exception line from the input string, and marks\n        the location of the exception with a special symbol.\n        \"\"\"\n        markerString = marker_string if marker_string is not None else markerString\n        line_str = self.line\n        line_column = self.column - 1\n        if markerString:\n            line_str = \"\".join(\n                (line_str[:line_column], markerString, line_str[line_column:])\n            )\n        return line_str.strip()\n\n    def explain(self, depth=16) -> str:\n        \"\"\"\n        Method to translate the Python internal traceback into a list\n        of the pyparsing expressions that caused the exception to be raised.\n\n        Parameters:\n\n        - depth (default=16) - number of levels back in the stack trace to list expression\n          and function names; if None, the full stack trace names will be listed; if 0, only\n          the failing input line, marker, and exception string will be shown\n\n        Returns a multi-line string listing the ParserElements and/or function names in the\n        exception's stack trace.\n\n        Example::\n\n            expr = pp.Word(pp.nums) * 3\n            try:\n                expr.parse_string(\"123 456 A789\")\n            except pp.ParseException as pe:\n                print(pe.explain(depth=0))\n\n        prints::\n\n            123 456 A789\n                    ^\n            ParseException: Expected W:(0-9), found 'A'  (at char 8), (line:1, col:9)\n\n        Note: the diagnostic output will include string representations of the expressions\n        that failed to parse. These representations will be more helpful if you use `set_name` to\n        give identifiable names to your expressions. Otherwise they will use the default string\n        forms, which may be cryptic to read.\n\n        Note: pyparsing's default truncation of exception tracebacks may also truncate the\n        stack of expressions that are displayed in the ``explain`` output. To get the full listing\n        of parser expressions, you may have to set ``ParserElement.verbose_stacktrace = True``\n        \"\"\"\n        return self.explain_exception(self, depth)\n\n    markInputline = mark_input_line\n\n\nclass ParseException(ParseBaseException):\n    \"\"\"\n    Exception thrown when a parse expression doesn't match the input string\n\n    Example::\n\n        try:\n            Word(nums).set_name(\"integer\").parse_string(\"ABC\")\n        except ParseException as pe:\n            print(pe)\n            print(\"column: {}\".format(pe.column))\n\n    prints::\n\n       Expected integer (at char 0), (line:1, col:1)\n        column: 1\n\n    \"\"\"\n\n\nclass ParseFatalException(ParseBaseException):\n    \"\"\"\n    User-throwable exception thrown when inconsistent parse content\n    is found; stops all parsing immediately\n    \"\"\"\n\n\nclass ParseSyntaxException(ParseFatalException):\n    \"\"\"\n    Just like :class:`ParseFatalException`, but thrown internally\n    when an :class:`ErrorStop<And._ErrorStop>` ('-' operator) indicates\n    that parsing is to stop immediately because an unbacktrackable\n    syntax error has been found.\n    \"\"\"\n\n\nclass RecursiveGrammarException(Exception):\n    \"\"\"\n    Exception thrown by :class:`ParserElement.validate` if the\n    grammar could be left-recursive; parser may need to enable\n    left recursion using :class:`ParserElement.enable_left_recursion<ParserElement.enable_left_recursion>`\n    \"\"\"\n\n    def __init__(self, parseElementList):\n        self.parseElementTrace = parseElementList\n\n    def __str__(self) -> str:\n        return \"RecursiveGrammarException: {}\".format(self.parseElementTrace)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pyparsing/helpers.py",
    "content": "# helpers.py\nimport html.entities\nimport re\nimport typing\n\nfrom . import __diag__\nfrom .core import *\nfrom .util import _bslash, _flatten, _escape_regex_range_chars\n\n\n#\n# global helpers\n#\ndef delimited_list(\n    expr: Union[str, ParserElement],\n    delim: Union[str, ParserElement] = \",\",\n    combine: bool = False,\n    min: typing.Optional[int] = None,\n    max: typing.Optional[int] = None,\n    *,\n    allow_trailing_delim: bool = False,\n) -> ParserElement:\n    \"\"\"Helper to define a delimited list of expressions - the delimiter\n    defaults to ','. By default, the list elements and delimiters can\n    have intervening whitespace, and comments, but this can be\n    overridden by passing ``combine=True`` in the constructor. If\n    ``combine`` is set to ``True``, the matching tokens are\n    returned as a single token string, with the delimiters included;\n    otherwise, the matching tokens are returned as a list of tokens,\n    with the delimiters suppressed.\n\n    If ``allow_trailing_delim`` is set to True, then the list may end with\n    a delimiter.\n\n    Example::\n\n        delimited_list(Word(alphas)).parse_string(\"aa,bb,cc\") # -> ['aa', 'bb', 'cc']\n        delimited_list(Word(hexnums), delim=':', combine=True).parse_string(\"AA:BB:CC:DD:EE\") # -> ['AA:BB:CC:DD:EE']\n    \"\"\"\n    if isinstance(expr, str_type):\n        expr = ParserElement._literalStringClass(expr)\n\n    dlName = \"{expr} [{delim} {expr}]...{end}\".format(\n        expr=str(expr.copy().streamline()),\n        delim=str(delim),\n        end=\" [{}]\".format(str(delim)) if allow_trailing_delim else \"\",\n    )\n\n    if not combine:\n        delim = Suppress(delim)\n\n    if min is not None:\n        if min < 1:\n            raise ValueError(\"min must be greater than 0\")\n        min -= 1\n    if max is not None:\n        if min is not None and max <= min:\n            raise ValueError(\"max must be greater than, or equal to min\")\n        max -= 1\n    delimited_list_expr = expr + (delim + expr)[min, max]\n\n    if allow_trailing_delim:\n        delimited_list_expr += Opt(delim)\n\n    if combine:\n        return Combine(delimited_list_expr).set_name(dlName)\n    else:\n        return delimited_list_expr.set_name(dlName)\n\n\ndef counted_array(\n    expr: ParserElement,\n    int_expr: typing.Optional[ParserElement] = None,\n    *,\n    intExpr: typing.Optional[ParserElement] = None,\n) -> ParserElement:\n    \"\"\"Helper to define a counted list of expressions.\n\n    This helper defines a pattern of the form::\n\n        integer expr expr expr...\n\n    where the leading integer tells how many expr expressions follow.\n    The matched tokens returns the array of expr tokens as a list - the\n    leading count token is suppressed.\n\n    If ``int_expr`` is specified, it should be a pyparsing expression\n    that produces an integer value.\n\n    Example::\n\n        counted_array(Word(alphas)).parse_string('2 ab cd ef')  # -> ['ab', 'cd']\n\n        # in this parser, the leading integer value is given in binary,\n        # '10' indicating that 2 values are in the array\n        binary_constant = Word('01').set_parse_action(lambda t: int(t[0], 2))\n        counted_array(Word(alphas), int_expr=binary_constant).parse_string('10 ab cd ef')  # -> ['ab', 'cd']\n\n        # if other fields must be parsed after the count but before the\n        # list items, give the fields results names and they will\n        # be preserved in the returned ParseResults:\n        count_with_metadata = integer + Word(alphas)(\"type\")\n        typed_array = counted_array(Word(alphanums), int_expr=count_with_metadata)(\"items\")\n        result = typed_array.parse_string(\"3 bool True True False\")\n        print(result.dump())\n\n        # prints\n        # ['True', 'True', 'False']\n        # - items: ['True', 'True', 'False']\n        # - type: 'bool'\n    \"\"\"\n    intExpr = intExpr or int_expr\n    array_expr = Forward()\n\n    def count_field_parse_action(s, l, t):\n        nonlocal array_expr\n        n = t[0]\n        array_expr <<= (expr * n) if n else Empty()\n        # clear list contents, but keep any named results\n        del t[:]\n\n    if intExpr is None:\n        intExpr = Word(nums).set_parse_action(lambda t: int(t[0]))\n    else:\n        intExpr = intExpr.copy()\n    intExpr.set_name(\"arrayLen\")\n    intExpr.add_parse_action(count_field_parse_action, call_during_try=True)\n    return (intExpr + array_expr).set_name(\"(len) \" + str(expr) + \"...\")\n\n\ndef match_previous_literal(expr: ParserElement) -> ParserElement:\n    \"\"\"Helper to define an expression that is indirectly defined from\n    the tokens matched in a previous expression, that is, it looks for\n    a 'repeat' of a previous expression.  For example::\n\n        first = Word(nums)\n        second = match_previous_literal(first)\n        match_expr = first + \":\" + second\n\n    will match ``\"1:1\"``, but not ``\"1:2\"``.  Because this\n    matches a previous literal, will also match the leading\n    ``\"1:1\"`` in ``\"1:10\"``. If this is not desired, use\n    :class:`match_previous_expr`. Do *not* use with packrat parsing\n    enabled.\n    \"\"\"\n    rep = Forward()\n\n    def copy_token_to_repeater(s, l, t):\n        if t:\n            if len(t) == 1:\n                rep << t[0]\n            else:\n                # flatten t tokens\n                tflat = _flatten(t.as_list())\n                rep << And(Literal(tt) for tt in tflat)\n        else:\n            rep << Empty()\n\n    expr.add_parse_action(copy_token_to_repeater, callDuringTry=True)\n    rep.set_name(\"(prev) \" + str(expr))\n    return rep\n\n\ndef match_previous_expr(expr: ParserElement) -> ParserElement:\n    \"\"\"Helper to define an expression that is indirectly defined from\n    the tokens matched in a previous expression, that is, it looks for\n    a 'repeat' of a previous expression.  For example::\n\n        first = Word(nums)\n        second = match_previous_expr(first)\n        match_expr = first + \":\" + second\n\n    will match ``\"1:1\"``, but not ``\"1:2\"``.  Because this\n    matches by expressions, will *not* match the leading ``\"1:1\"``\n    in ``\"1:10\"``; the expressions are evaluated first, and then\n    compared, so ``\"1\"`` is compared with ``\"10\"``. Do *not* use\n    with packrat parsing enabled.\n    \"\"\"\n    rep = Forward()\n    e2 = expr.copy()\n    rep <<= e2\n\n    def copy_token_to_repeater(s, l, t):\n        matchTokens = _flatten(t.as_list())\n\n        def must_match_these_tokens(s, l, t):\n            theseTokens = _flatten(t.as_list())\n            if theseTokens != matchTokens:\n                raise ParseException(\n                    s, l, \"Expected {}, found{}\".format(matchTokens, theseTokens)\n                )\n\n        rep.set_parse_action(must_match_these_tokens, callDuringTry=True)\n\n    expr.add_parse_action(copy_token_to_repeater, callDuringTry=True)\n    rep.set_name(\"(prev) \" + str(expr))\n    return rep\n\n\ndef one_of(\n    strs: Union[typing.Iterable[str], str],\n    caseless: bool = False,\n    use_regex: bool = True,\n    as_keyword: bool = False,\n    *,\n    useRegex: bool = True,\n    asKeyword: bool = False,\n) -> ParserElement:\n    \"\"\"Helper to quickly define a set of alternative :class:`Literal` s,\n    and makes sure to do longest-first testing when there is a conflict,\n    regardless of the input order, but returns\n    a :class:`MatchFirst` for best performance.\n\n    Parameters:\n\n    - ``strs`` - a string of space-delimited literals, or a collection of\n      string literals\n    - ``caseless`` - treat all literals as caseless - (default= ``False``)\n    - ``use_regex`` - as an optimization, will\n      generate a :class:`Regex` object; otherwise, will generate\n      a :class:`MatchFirst` object (if ``caseless=True`` or ``asKeyword=True``, or if\n      creating a :class:`Regex` raises an exception) - (default= ``True``)\n    - ``as_keyword`` - enforce :class:`Keyword`-style matching on the\n      generated expressions - (default= ``False``)\n    - ``asKeyword`` and ``useRegex`` are retained for pre-PEP8 compatibility,\n      but will be removed in a future release\n\n    Example::\n\n        comp_oper = one_of(\"< = > <= >= !=\")\n        var = Word(alphas)\n        number = Word(nums)\n        term = var | number\n        comparison_expr = term + comp_oper + term\n        print(comparison_expr.search_string(\"B = 12  AA=23 B<=AA AA>12\"))\n\n    prints::\n\n        [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']]\n    \"\"\"\n    asKeyword = asKeyword or as_keyword\n    useRegex = useRegex and use_regex\n\n    if (\n        isinstance(caseless, str_type)\n        and __diag__.warn_on_multiple_string_args_to_oneof\n    ):\n        warnings.warn(\n            \"More than one string argument passed to one_of, pass\"\n            \" choices as a list or space-delimited string\",\n            stacklevel=2,\n        )\n\n    if caseless:\n        isequal = lambda a, b: a.upper() == b.upper()\n        masks = lambda a, b: b.upper().startswith(a.upper())\n        parseElementClass = CaselessKeyword if asKeyword else CaselessLiteral\n    else:\n        isequal = lambda a, b: a == b\n        masks = lambda a, b: b.startswith(a)\n        parseElementClass = Keyword if asKeyword else Literal\n\n    symbols: List[str] = []\n    if isinstance(strs, str_type):\n        symbols = strs.split()\n    elif isinstance(strs, Iterable):\n        symbols = list(strs)\n    else:\n        raise TypeError(\"Invalid argument to one_of, expected string or iterable\")\n    if not symbols:\n        return NoMatch()\n\n    # reorder given symbols to take care to avoid masking longer choices with shorter ones\n    # (but only if the given symbols are not just single characters)\n    if any(len(sym) > 1 for sym in symbols):\n        i = 0\n        while i < len(symbols) - 1:\n            cur = symbols[i]\n            for j, other in enumerate(symbols[i + 1 :]):\n                if isequal(other, cur):\n                    del symbols[i + j + 1]\n                    break\n                elif masks(cur, other):\n                    del symbols[i + j + 1]\n                    symbols.insert(i, other)\n                    break\n            else:\n                i += 1\n\n    if useRegex:\n        re_flags: int = re.IGNORECASE if caseless else 0\n\n        try:\n            if all(len(sym) == 1 for sym in symbols):\n                # symbols are just single characters, create range regex pattern\n                patt = \"[{}]\".format(\n                    \"\".join(_escape_regex_range_chars(sym) for sym in symbols)\n                )\n            else:\n                patt = \"|\".join(re.escape(sym) for sym in symbols)\n\n            # wrap with \\b word break markers if defining as keywords\n            if asKeyword:\n                patt = r\"\\b(?:{})\\b\".format(patt)\n\n            ret = Regex(patt, flags=re_flags).set_name(\" | \".join(symbols))\n\n            if caseless:\n                # add parse action to return symbols as specified, not in random\n                # casing as found in input string\n                symbol_map = {sym.lower(): sym for sym in symbols}\n                ret.add_parse_action(lambda s, l, t: symbol_map[t[0].lower()])\n\n            return ret\n\n        except re.error:\n            warnings.warn(\n                \"Exception creating Regex for one_of, building MatchFirst\", stacklevel=2\n            )\n\n    # last resort, just use MatchFirst\n    return MatchFirst(parseElementClass(sym) for sym in symbols).set_name(\n        \" | \".join(symbols)\n    )\n\n\ndef dict_of(key: ParserElement, value: ParserElement) -> ParserElement:\n    \"\"\"Helper to easily and clearly define a dictionary by specifying\n    the respective patterns for the key and value.  Takes care of\n    defining the :class:`Dict`, :class:`ZeroOrMore`, and\n    :class:`Group` tokens in the proper order.  The key pattern\n    can include delimiting markers or punctuation, as long as they are\n    suppressed, thereby leaving the significant key text.  The value\n    pattern can include named results, so that the :class:`Dict` results\n    can include named token fields.\n\n    Example::\n\n        text = \"shape: SQUARE posn: upper left color: light blue texture: burlap\"\n        attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))\n        print(attr_expr[1, ...].parse_string(text).dump())\n\n        attr_label = label\n        attr_value = Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)\n\n        # similar to Dict, but simpler call format\n        result = dict_of(attr_label, attr_value).parse_string(text)\n        print(result.dump())\n        print(result['shape'])\n        print(result.shape)  # object attribute access works too\n        print(result.as_dict())\n\n    prints::\n\n        [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]\n        - color: 'light blue'\n        - posn: 'upper left'\n        - shape: 'SQUARE'\n        - texture: 'burlap'\n        SQUARE\n        SQUARE\n        {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}\n    \"\"\"\n    return Dict(OneOrMore(Group(key + value)))\n\n\ndef original_text_for(\n    expr: ParserElement, as_string: bool = True, *, asString: bool = True\n) -> ParserElement:\n    \"\"\"Helper to return the original, untokenized text for a given\n    expression.  Useful to restore the parsed fields of an HTML start\n    tag into the raw tag text itself, or to revert separate tokens with\n    intervening whitespace back to the original matching input text. By\n    default, returns astring containing the original parsed text.\n\n    If the optional ``as_string`` argument is passed as\n    ``False``, then the return value is\n    a :class:`ParseResults` containing any results names that\n    were originally matched, and a single token containing the original\n    matched text from the input string.  So if the expression passed to\n    :class:`original_text_for` contains expressions with defined\n    results names, you must set ``as_string`` to ``False`` if you\n    want to preserve those results name values.\n\n    The ``asString`` pre-PEP8 argument is retained for compatibility,\n    but will be removed in a future release.\n\n    Example::\n\n        src = \"this is test <b> bold <i>text</i> </b> normal text \"\n        for tag in (\"b\", \"i\"):\n            opener, closer = make_html_tags(tag)\n            patt = original_text_for(opener + SkipTo(closer) + closer)\n            print(patt.search_string(src)[0])\n\n    prints::\n\n        ['<b> bold <i>text</i> </b>']\n        ['<i>text</i>']\n    \"\"\"\n    asString = asString and as_string\n\n    locMarker = Empty().set_parse_action(lambda s, loc, t: loc)\n    endlocMarker = locMarker.copy()\n    endlocMarker.callPreparse = False\n    matchExpr = locMarker(\"_original_start\") + expr + endlocMarker(\"_original_end\")\n    if asString:\n        extractText = lambda s, l, t: s[t._original_start : t._original_end]\n    else:\n\n        def extractText(s, l, t):\n            t[:] = [s[t.pop(\"_original_start\") : t.pop(\"_original_end\")]]\n\n    matchExpr.set_parse_action(extractText)\n    matchExpr.ignoreExprs = expr.ignoreExprs\n    matchExpr.suppress_warning(Diagnostics.warn_ungrouped_named_tokens_in_collection)\n    return matchExpr\n\n\ndef ungroup(expr: ParserElement) -> ParserElement:\n    \"\"\"Helper to undo pyparsing's default grouping of And expressions,\n    even if all but one are non-empty.\n    \"\"\"\n    return TokenConverter(expr).add_parse_action(lambda t: t[0])\n\n\ndef locatedExpr(expr: ParserElement) -> ParserElement:\n    \"\"\"\n    (DEPRECATED - future code should use the Located class)\n    Helper to decorate a returned token with its starting and ending\n    locations in the input string.\n\n    This helper adds the following results names:\n\n    - ``locn_start`` - location where matched expression begins\n    - ``locn_end`` - location where matched expression ends\n    - ``value`` - the actual parsed results\n\n    Be careful if the input text contains ``<TAB>`` characters, you\n    may want to call :class:`ParserElement.parseWithTabs`\n\n    Example::\n\n        wd = Word(alphas)\n        for match in locatedExpr(wd).searchString(\"ljsdf123lksdjjf123lkkjj1222\"):\n            print(match)\n\n    prints::\n\n        [[0, 'ljsdf', 5]]\n        [[8, 'lksdjjf', 15]]\n        [[18, 'lkkjj', 23]]\n    \"\"\"\n    locator = Empty().set_parse_action(lambda ss, ll, tt: ll)\n    return Group(\n        locator(\"locn_start\")\n        + expr(\"value\")\n        + locator.copy().leaveWhitespace()(\"locn_end\")\n    )\n\n\ndef nested_expr(\n    opener: Union[str, ParserElement] = \"(\",\n    closer: Union[str, ParserElement] = \")\",\n    content: typing.Optional[ParserElement] = None,\n    ignore_expr: ParserElement = quoted_string(),\n    *,\n    ignoreExpr: ParserElement = quoted_string(),\n) -> ParserElement:\n    \"\"\"Helper method for defining nested lists enclosed in opening and\n    closing delimiters (``\"(\"`` and ``\")\"`` are the default).\n\n    Parameters:\n    - ``opener`` - opening character for a nested list\n      (default= ``\"(\"``); can also be a pyparsing expression\n    - ``closer`` - closing character for a nested list\n      (default= ``\")\"``); can also be a pyparsing expression\n    - ``content`` - expression for items within the nested lists\n      (default= ``None``)\n    - ``ignore_expr`` - expression for ignoring opening and closing delimiters\n      (default= :class:`quoted_string`)\n    - ``ignoreExpr`` - this pre-PEP8 argument is retained for compatibility\n      but will be removed in a future release\n\n    If an expression is not provided for the content argument, the\n    nested expression will capture all whitespace-delimited content\n    between delimiters as a list of separate values.\n\n    Use the ``ignore_expr`` argument to define expressions that may\n    contain opening or closing characters that should not be treated as\n    opening or closing characters for nesting, such as quoted_string or\n    a comment expression.  Specify multiple expressions using an\n    :class:`Or` or :class:`MatchFirst`. The default is\n    :class:`quoted_string`, but if no expressions are to be ignored, then\n    pass ``None`` for this argument.\n\n    Example::\n\n        data_type = one_of(\"void int short long char float double\")\n        decl_data_type = Combine(data_type + Opt(Word('*')))\n        ident = Word(alphas+'_', alphanums+'_')\n        number = pyparsing_common.number\n        arg = Group(decl_data_type + ident)\n        LPAR, RPAR = map(Suppress, \"()\")\n\n        code_body = nested_expr('{', '}', ignore_expr=(quoted_string | c_style_comment))\n\n        c_function = (decl_data_type(\"type\")\n                      + ident(\"name\")\n                      + LPAR + Opt(delimited_list(arg), [])(\"args\") + RPAR\n                      + code_body(\"body\"))\n        c_function.ignore(c_style_comment)\n\n        source_code = '''\n            int is_odd(int x) {\n                return (x%2);\n            }\n\n            int dec_to_hex(char hchar) {\n                if (hchar >= '0' && hchar <= '9') {\n                    return (ord(hchar)-ord('0'));\n                } else {\n                    return (10+ord(hchar)-ord('A'));\n                }\n            }\n        '''\n        for func in c_function.search_string(source_code):\n            print(\"%(name)s (%(type)s) args: %(args)s\" % func)\n\n\n    prints::\n\n        is_odd (int) args: [['int', 'x']]\n        dec_to_hex (int) args: [['char', 'hchar']]\n    \"\"\"\n    if ignoreExpr != ignore_expr:\n        ignoreExpr = ignore_expr if ignoreExpr == quoted_string() else ignoreExpr\n    if opener == closer:\n        raise ValueError(\"opening and closing strings cannot be the same\")\n    if content is None:\n        if isinstance(opener, str_type) and isinstance(closer, str_type):\n            if len(opener) == 1 and len(closer) == 1:\n                if ignoreExpr is not None:\n                    content = Combine(\n                        OneOrMore(\n                            ~ignoreExpr\n                            + CharsNotIn(\n                                opener + closer + ParserElement.DEFAULT_WHITE_CHARS,\n                                exact=1,\n                            )\n                        )\n                    ).set_parse_action(lambda t: t[0].strip())\n                else:\n                    content = empty.copy() + CharsNotIn(\n                        opener + closer + ParserElement.DEFAULT_WHITE_CHARS\n                    ).set_parse_action(lambda t: t[0].strip())\n            else:\n                if ignoreExpr is not None:\n                    content = Combine(\n                        OneOrMore(\n                            ~ignoreExpr\n                            + ~Literal(opener)\n                            + ~Literal(closer)\n                            + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1)\n                        )\n                    ).set_parse_action(lambda t: t[0].strip())\n                else:\n                    content = Combine(\n                        OneOrMore(\n                            ~Literal(opener)\n                            + ~Literal(closer)\n                            + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1)\n                        )\n                    ).set_parse_action(lambda t: t[0].strip())\n        else:\n            raise ValueError(\n                \"opening and closing arguments must be strings if no content expression is given\"\n            )\n    ret = Forward()\n    if ignoreExpr is not None:\n        ret <<= Group(\n            Suppress(opener) + ZeroOrMore(ignoreExpr | ret | content) + Suppress(closer)\n        )\n    else:\n        ret <<= Group(Suppress(opener) + ZeroOrMore(ret | content) + Suppress(closer))\n    ret.set_name(\"nested %s%s expression\" % (opener, closer))\n    return ret\n\n\ndef _makeTags(tagStr, xml, suppress_LT=Suppress(\"<\"), suppress_GT=Suppress(\">\")):\n    \"\"\"Internal helper to construct opening and closing tag expressions, given a tag name\"\"\"\n    if isinstance(tagStr, str_type):\n        resname = tagStr\n        tagStr = Keyword(tagStr, caseless=not xml)\n    else:\n        resname = tagStr.name\n\n    tagAttrName = Word(alphas, alphanums + \"_-:\")\n    if xml:\n        tagAttrValue = dbl_quoted_string.copy().set_parse_action(remove_quotes)\n        openTag = (\n            suppress_LT\n            + tagStr(\"tag\")\n            + Dict(ZeroOrMore(Group(tagAttrName + Suppress(\"=\") + tagAttrValue)))\n            + Opt(\"/\", default=[False])(\"empty\").set_parse_action(\n                lambda s, l, t: t[0] == \"/\"\n            )\n            + suppress_GT\n        )\n    else:\n        tagAttrValue = quoted_string.copy().set_parse_action(remove_quotes) | Word(\n            printables, exclude_chars=\">\"\n        )\n        openTag = (\n            suppress_LT\n            + tagStr(\"tag\")\n            + Dict(\n                ZeroOrMore(\n                    Group(\n                        tagAttrName.set_parse_action(lambda t: t[0].lower())\n                        + Opt(Suppress(\"=\") + tagAttrValue)\n                    )\n                )\n            )\n            + Opt(\"/\", default=[False])(\"empty\").set_parse_action(\n                lambda s, l, t: t[0] == \"/\"\n            )\n            + suppress_GT\n        )\n    closeTag = Combine(Literal(\"</\") + tagStr + \">\", adjacent=False)\n\n    openTag.set_name(\"<%s>\" % resname)\n    # add start<tagname> results name in parse action now that ungrouped names are not reported at two levels\n    openTag.add_parse_action(\n        lambda t: t.__setitem__(\n            \"start\" + \"\".join(resname.replace(\":\", \" \").title().split()), t.copy()\n        )\n    )\n    closeTag = closeTag(\n        \"end\" + \"\".join(resname.replace(\":\", \" \").title().split())\n    ).set_name(\"</%s>\" % resname)\n    openTag.tag = resname\n    closeTag.tag = resname\n    openTag.tag_body = SkipTo(closeTag())\n    return openTag, closeTag\n\n\ndef make_html_tags(\n    tag_str: Union[str, ParserElement]\n) -> Tuple[ParserElement, ParserElement]:\n    \"\"\"Helper to construct opening and closing tag expressions for HTML,\n    given a tag name. Matches tags in either upper or lower case,\n    attributes with namespaces and with quoted or unquoted values.\n\n    Example::\n\n        text = '<td>More info at the <a href=\"https://github.com/pyparsing/pyparsing/wiki\">pyparsing</a> wiki page</td>'\n        # make_html_tags returns pyparsing expressions for the opening and\n        # closing tags as a 2-tuple\n        a, a_end = make_html_tags(\"A\")\n        link_expr = a + SkipTo(a_end)(\"link_text\") + a_end\n\n        for link in link_expr.search_string(text):\n            # attributes in the <A> tag (like \"href\" shown here) are\n            # also accessible as named results\n            print(link.link_text, '->', link.href)\n\n    prints::\n\n        pyparsing -> https://github.com/pyparsing/pyparsing/wiki\n    \"\"\"\n    return _makeTags(tag_str, False)\n\n\ndef make_xml_tags(\n    tag_str: Union[str, ParserElement]\n) -> Tuple[ParserElement, ParserElement]:\n    \"\"\"Helper to construct opening and closing tag expressions for XML,\n    given a tag name. Matches tags only in the given upper/lower case.\n\n    Example: similar to :class:`make_html_tags`\n    \"\"\"\n    return _makeTags(tag_str, True)\n\n\nany_open_tag: ParserElement\nany_close_tag: ParserElement\nany_open_tag, any_close_tag = make_html_tags(\n    Word(alphas, alphanums + \"_:\").set_name(\"any tag\")\n)\n\n_htmlEntityMap = {k.rstrip(\";\"): v for k, v in html.entities.html5.items()}\ncommon_html_entity = Regex(\"&(?P<entity>\" + \"|\".join(_htmlEntityMap) + \");\").set_name(\n    \"common HTML entity\"\n)\n\n\ndef replace_html_entity(t):\n    \"\"\"Helper parser action to replace common HTML entities with their special characters\"\"\"\n    return _htmlEntityMap.get(t.entity)\n\n\nclass OpAssoc(Enum):\n    LEFT = 1\n    RIGHT = 2\n\n\nInfixNotationOperatorArgType = Union[\n    ParserElement, str, Tuple[Union[ParserElement, str], Union[ParserElement, str]]\n]\nInfixNotationOperatorSpec = Union[\n    Tuple[\n        InfixNotationOperatorArgType,\n        int,\n        OpAssoc,\n        typing.Optional[ParseAction],\n    ],\n    Tuple[\n        InfixNotationOperatorArgType,\n        int,\n        OpAssoc,\n    ],\n]\n\n\ndef infix_notation(\n    base_expr: ParserElement,\n    op_list: List[InfixNotationOperatorSpec],\n    lpar: Union[str, ParserElement] = Suppress(\"(\"),\n    rpar: Union[str, ParserElement] = Suppress(\")\"),\n) -> ParserElement:\n    \"\"\"Helper method for constructing grammars of expressions made up of\n    operators working in a precedence hierarchy.  Operators may be unary\n    or binary, left- or right-associative.  Parse actions can also be\n    attached to operator expressions. The generated parser will also\n    recognize the use of parentheses to override operator precedences\n    (see example below).\n\n    Note: if you define a deep operator list, you may see performance\n    issues when using infix_notation. See\n    :class:`ParserElement.enable_packrat` for a mechanism to potentially\n    improve your parser performance.\n\n    Parameters:\n    - ``base_expr`` - expression representing the most basic operand to\n      be used in the expression\n    - ``op_list`` - list of tuples, one for each operator precedence level\n      in the expression grammar; each tuple is of the form ``(op_expr,\n      num_operands, right_left_assoc, (optional)parse_action)``, where:\n\n      - ``op_expr`` is the pyparsing expression for the operator; may also\n        be a string, which will be converted to a Literal; if ``num_operands``\n        is 3, ``op_expr`` is a tuple of two expressions, for the two\n        operators separating the 3 terms\n      - ``num_operands`` is the number of terms for this operator (must be 1,\n        2, or 3)\n      - ``right_left_assoc`` is the indicator whether the operator is right\n        or left associative, using the pyparsing-defined constants\n        ``OpAssoc.RIGHT`` and ``OpAssoc.LEFT``.\n      - ``parse_action`` is the parse action to be associated with\n        expressions matching this operator expression (the parse action\n        tuple member may be omitted); if the parse action is passed\n        a tuple or list of functions, this is equivalent to calling\n        ``set_parse_action(*fn)``\n        (:class:`ParserElement.set_parse_action`)\n    - ``lpar`` - expression for matching left-parentheses; if passed as a\n      str, then will be parsed as Suppress(lpar). If lpar is passed as\n      an expression (such as ``Literal('(')``), then it will be kept in\n      the parsed results, and grouped with them. (default= ``Suppress('(')``)\n    - ``rpar`` - expression for matching right-parentheses; if passed as a\n      str, then will be parsed as Suppress(rpar). If rpar is passed as\n      an expression (such as ``Literal(')')``), then it will be kept in\n      the parsed results, and grouped with them. (default= ``Suppress(')')``)\n\n    Example::\n\n        # simple example of four-function arithmetic with ints and\n        # variable names\n        integer = pyparsing_common.signed_integer\n        varname = pyparsing_common.identifier\n\n        arith_expr = infix_notation(integer | varname,\n            [\n            ('-', 1, OpAssoc.RIGHT),\n            (one_of('* /'), 2, OpAssoc.LEFT),\n            (one_of('+ -'), 2, OpAssoc.LEFT),\n            ])\n\n        arith_expr.run_tests('''\n            5+3*6\n            (5+3)*6\n            -2--11\n            ''', full_dump=False)\n\n    prints::\n\n        5+3*6\n        [[5, '+', [3, '*', 6]]]\n\n        (5+3)*6\n        [[[5, '+', 3], '*', 6]]\n\n        -2--11\n        [[['-', 2], '-', ['-', 11]]]\n    \"\"\"\n    # captive version of FollowedBy that does not do parse actions or capture results names\n    class _FB(FollowedBy):\n        def parseImpl(self, instring, loc, doActions=True):\n            self.expr.try_parse(instring, loc)\n            return loc, []\n\n    _FB.__name__ = \"FollowedBy>\"\n\n    ret = Forward()\n    if isinstance(lpar, str):\n        lpar = Suppress(lpar)\n    if isinstance(rpar, str):\n        rpar = Suppress(rpar)\n\n    # if lpar and rpar are not suppressed, wrap in group\n    if not (isinstance(rpar, Suppress) and isinstance(rpar, Suppress)):\n        lastExpr = base_expr | Group(lpar + ret + rpar)\n    else:\n        lastExpr = base_expr | (lpar + ret + rpar)\n\n    for i, operDef in enumerate(op_list):\n        opExpr, arity, rightLeftAssoc, pa = (operDef + (None,))[:4]\n        if isinstance(opExpr, str_type):\n            opExpr = ParserElement._literalStringClass(opExpr)\n        if arity == 3:\n            if not isinstance(opExpr, (tuple, list)) or len(opExpr) != 2:\n                raise ValueError(\n                    \"if numterms=3, opExpr must be a tuple or list of two expressions\"\n                )\n            opExpr1, opExpr2 = opExpr\n            term_name = \"{}{} term\".format(opExpr1, opExpr2)\n        else:\n            term_name = \"{} term\".format(opExpr)\n\n        if not 1 <= arity <= 3:\n            raise ValueError(\"operator must be unary (1), binary (2), or ternary (3)\")\n\n        if rightLeftAssoc not in (OpAssoc.LEFT, OpAssoc.RIGHT):\n            raise ValueError(\"operator must indicate right or left associativity\")\n\n        thisExpr: Forward = Forward().set_name(term_name)\n        if rightLeftAssoc is OpAssoc.LEFT:\n            if arity == 1:\n                matchExpr = _FB(lastExpr + opExpr) + Group(lastExpr + opExpr[1, ...])\n            elif arity == 2:\n                if opExpr is not None:\n                    matchExpr = _FB(lastExpr + opExpr + lastExpr) + Group(\n                        lastExpr + (opExpr + lastExpr)[1, ...]\n                    )\n                else:\n                    matchExpr = _FB(lastExpr + lastExpr) + Group(lastExpr[2, ...])\n            elif arity == 3:\n                matchExpr = _FB(\n                    lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr\n                ) + Group(lastExpr + OneOrMore(opExpr1 + lastExpr + opExpr2 + lastExpr))\n        elif rightLeftAssoc is OpAssoc.RIGHT:\n            if arity == 1:\n                # try to avoid LR with this extra test\n                if not isinstance(opExpr, Opt):\n                    opExpr = Opt(opExpr)\n                matchExpr = _FB(opExpr.expr + thisExpr) + Group(opExpr + thisExpr)\n            elif arity == 2:\n                if opExpr is not None:\n                    matchExpr = _FB(lastExpr + opExpr + thisExpr) + Group(\n                        lastExpr + (opExpr + thisExpr)[1, ...]\n                    )\n                else:\n                    matchExpr = _FB(lastExpr + thisExpr) + Group(\n                        lastExpr + thisExpr[1, ...]\n                    )\n            elif arity == 3:\n                matchExpr = _FB(\n                    lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr\n                ) + Group(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr)\n        if pa:\n            if isinstance(pa, (tuple, list)):\n                matchExpr.set_parse_action(*pa)\n            else:\n                matchExpr.set_parse_action(pa)\n        thisExpr <<= (matchExpr | lastExpr).setName(term_name)\n        lastExpr = thisExpr\n    ret <<= lastExpr\n    return ret\n\n\ndef indentedBlock(blockStatementExpr, indentStack, indent=True, backup_stacks=[]):\n    \"\"\"\n    (DEPRECATED - use IndentedBlock class instead)\n    Helper method for defining space-delimited indentation blocks,\n    such as those used to define block statements in Python source code.\n\n    Parameters:\n\n    - ``blockStatementExpr`` - expression defining syntax of statement that\n      is repeated within the indented block\n    - ``indentStack`` - list created by caller to manage indentation stack\n      (multiple ``statementWithIndentedBlock`` expressions within a single\n      grammar should share a common ``indentStack``)\n    - ``indent`` - boolean indicating whether block must be indented beyond\n      the current level; set to ``False`` for block of left-most statements\n      (default= ``True``)\n\n    A valid block must contain at least one ``blockStatement``.\n\n    (Note that indentedBlock uses internal parse actions which make it\n    incompatible with packrat parsing.)\n\n    Example::\n\n        data = '''\n        def A(z):\n          A1\n          B = 100\n          G = A2\n          A2\n          A3\n        B\n        def BB(a,b,c):\n          BB1\n          def BBA():\n            bba1\n            bba2\n            bba3\n        C\n        D\n        def spam(x,y):\n             def eggs(z):\n                 pass\n        '''\n\n\n        indentStack = [1]\n        stmt = Forward()\n\n        identifier = Word(alphas, alphanums)\n        funcDecl = (\"def\" + identifier + Group(\"(\" + Opt(delimitedList(identifier)) + \")\") + \":\")\n        func_body = indentedBlock(stmt, indentStack)\n        funcDef = Group(funcDecl + func_body)\n\n        rvalue = Forward()\n        funcCall = Group(identifier + \"(\" + Opt(delimitedList(rvalue)) + \")\")\n        rvalue << (funcCall | identifier | Word(nums))\n        assignment = Group(identifier + \"=\" + rvalue)\n        stmt << (funcDef | assignment | identifier)\n\n        module_body = stmt[1, ...]\n\n        parseTree = module_body.parseString(data)\n        parseTree.pprint()\n\n    prints::\n\n        [['def',\n          'A',\n          ['(', 'z', ')'],\n          ':',\n          [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],\n         'B',\n         ['def',\n          'BB',\n          ['(', 'a', 'b', 'c', ')'],\n          ':',\n          [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],\n         'C',\n         'D',\n         ['def',\n          'spam',\n          ['(', 'x', 'y', ')'],\n          ':',\n          [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]]\n    \"\"\"\n    backup_stacks.append(indentStack[:])\n\n    def reset_stack():\n        indentStack[:] = backup_stacks[-1]\n\n    def checkPeerIndent(s, l, t):\n        if l >= len(s):\n            return\n        curCol = col(l, s)\n        if curCol != indentStack[-1]:\n            if curCol > indentStack[-1]:\n                raise ParseException(s, l, \"illegal nesting\")\n            raise ParseException(s, l, \"not a peer entry\")\n\n    def checkSubIndent(s, l, t):\n        curCol = col(l, s)\n        if curCol > indentStack[-1]:\n            indentStack.append(curCol)\n        else:\n            raise ParseException(s, l, \"not a subentry\")\n\n    def checkUnindent(s, l, t):\n        if l >= len(s):\n            return\n        curCol = col(l, s)\n        if not (indentStack and curCol in indentStack):\n            raise ParseException(s, l, \"not an unindent\")\n        if curCol < indentStack[-1]:\n            indentStack.pop()\n\n    NL = OneOrMore(LineEnd().set_whitespace_chars(\"\\t \").suppress())\n    INDENT = (Empty() + Empty().set_parse_action(checkSubIndent)).set_name(\"INDENT\")\n    PEER = Empty().set_parse_action(checkPeerIndent).set_name(\"\")\n    UNDENT = Empty().set_parse_action(checkUnindent).set_name(\"UNINDENT\")\n    if indent:\n        smExpr = Group(\n            Opt(NL)\n            + INDENT\n            + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL))\n            + UNDENT\n        )\n    else:\n        smExpr = Group(\n            Opt(NL)\n            + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL))\n            + Opt(UNDENT)\n        )\n\n    # add a parse action to remove backup_stack from list of backups\n    smExpr.add_parse_action(\n        lambda: backup_stacks.pop(-1) and None if backup_stacks else None\n    )\n    smExpr.set_fail_action(lambda a, b, c, d: reset_stack())\n    blockStatementExpr.ignore(_bslash + LineEnd())\n    return smExpr.set_name(\"indented block\")\n\n\n# it's easy to get these comment structures wrong - they're very common, so may as well make them available\nc_style_comment = Combine(Regex(r\"/\\*(?:[^*]|\\*(?!/))*\") + \"*/\").set_name(\n    \"C style comment\"\n)\n\"Comment of the form ``/* ... */``\"\n\nhtml_comment = Regex(r\"<!--[\\s\\S]*?-->\").set_name(\"HTML comment\")\n\"Comment of the form ``<!-- ... -->``\"\n\nrest_of_line = Regex(r\".*\").leave_whitespace().set_name(\"rest of line\")\ndbl_slash_comment = Regex(r\"//(?:\\\\\\n|[^\\n])*\").set_name(\"// comment\")\n\"Comment of the form ``// ... (to end of line)``\"\n\ncpp_style_comment = Combine(\n    Regex(r\"/\\*(?:[^*]|\\*(?!/))*\") + \"*/\" | dbl_slash_comment\n).set_name(\"C++ style comment\")\n\"Comment of either form :class:`c_style_comment` or :class:`dbl_slash_comment`\"\n\njava_style_comment = cpp_style_comment\n\"Same as :class:`cpp_style_comment`\"\n\npython_style_comment = Regex(r\"#.*\").set_name(\"Python style comment\")\n\"Comment of the form ``# ... (to end of line)``\"\n\n\n# build list of built-in expressions, for future reference if a global default value\n# gets updated\n_builtin_exprs: List[ParserElement] = [\n    v for v in vars().values() if isinstance(v, ParserElement)\n]\n\n\n# pre-PEP8 compatible names\ndelimitedList = delimited_list\ncountedArray = counted_array\nmatchPreviousLiteral = match_previous_literal\nmatchPreviousExpr = match_previous_expr\noneOf = one_of\ndictOf = dict_of\noriginalTextFor = original_text_for\nnestedExpr = nested_expr\nmakeHTMLTags = make_html_tags\nmakeXMLTags = make_xml_tags\nanyOpenTag, anyCloseTag = any_open_tag, any_close_tag\ncommonHTMLEntity = common_html_entity\nreplaceHTMLEntity = replace_html_entity\nopAssoc = OpAssoc\ninfixNotation = infix_notation\ncStyleComment = c_style_comment\nhtmlComment = html_comment\nrestOfLine = rest_of_line\ndblSlashComment = dbl_slash_comment\ncppStyleComment = cpp_style_comment\njavaStyleComment = java_style_comment\npythonStyleComment = python_style_comment\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pyparsing/results.py",
    "content": "# results.py\nfrom collections.abc import MutableMapping, Mapping, MutableSequence, Iterator\nimport pprint\nfrom weakref import ref as wkref\nfrom typing import Tuple, Any\n\nstr_type: Tuple[type, ...] = (str, bytes)\n_generator_type = type((_ for _ in ()))\n\n\nclass _ParseResultsWithOffset:\n    __slots__ = [\"tup\"]\n\n    def __init__(self, p1, p2):\n        self.tup = (p1, p2)\n\n    def __getitem__(self, i):\n        return self.tup[i]\n\n    def __getstate__(self):\n        return self.tup\n\n    def __setstate__(self, *args):\n        self.tup = args[0]\n\n\nclass ParseResults:\n    \"\"\"Structured parse results, to provide multiple means of access to\n    the parsed data:\n\n    - as a list (``len(results)``)\n    - by list index (``results[0], results[1]``, etc.)\n    - by attribute (``results.<results_name>`` - see :class:`ParserElement.set_results_name`)\n\n    Example::\n\n        integer = Word(nums)\n        date_str = (integer.set_results_name(\"year\") + '/'\n                    + integer.set_results_name(\"month\") + '/'\n                    + integer.set_results_name(\"day\"))\n        # equivalent form:\n        # date_str = (integer(\"year\") + '/'\n        #             + integer(\"month\") + '/'\n        #             + integer(\"day\"))\n\n        # parse_string returns a ParseResults object\n        result = date_str.parse_string(\"1999/12/31\")\n\n        def test(s, fn=repr):\n            print(\"{} -> {}\".format(s, fn(eval(s))))\n        test(\"list(result)\")\n        test(\"result[0]\")\n        test(\"result['month']\")\n        test(\"result.day\")\n        test(\"'month' in result\")\n        test(\"'minutes' in result\")\n        test(\"result.dump()\", str)\n\n    prints::\n\n        list(result) -> ['1999', '/', '12', '/', '31']\n        result[0] -> '1999'\n        result['month'] -> '12'\n        result.day -> '31'\n        'month' in result -> True\n        'minutes' in result -> False\n        result.dump() -> ['1999', '/', '12', '/', '31']\n        - day: '31'\n        - month: '12'\n        - year: '1999'\n    \"\"\"\n\n    _null_values: Tuple[Any, ...] = (None, [], \"\", ())\n\n    __slots__ = [\n        \"_name\",\n        \"_parent\",\n        \"_all_names\",\n        \"_modal\",\n        \"_toklist\",\n        \"_tokdict\",\n        \"__weakref__\",\n    ]\n\n    class List(list):\n        \"\"\"\n        Simple wrapper class to distinguish parsed list results that should be preserved\n        as actual Python lists, instead of being converted to :class:`ParseResults`:\n\n            LBRACK, RBRACK = map(pp.Suppress, \"[]\")\n            element = pp.Forward()\n            item = ppc.integer\n            element_list = LBRACK + pp.delimited_list(element) + RBRACK\n\n            # add parse actions to convert from ParseResults to actual Python collection types\n            def as_python_list(t):\n                return pp.ParseResults.List(t.as_list())\n            element_list.add_parse_action(as_python_list)\n\n            element <<= item | element_list\n\n            element.run_tests('''\n                100\n                [2,3,4]\n                [[2, 1],3,4]\n                [(2, 1),3,4]\n                (2,3,4)\n                ''', post_parse=lambda s, r: (r[0], type(r[0])))\n\n        prints:\n\n            100\n            (100, <class 'int'>)\n\n            [2,3,4]\n            ([2, 3, 4], <class 'list'>)\n\n            [[2, 1],3,4]\n            ([[2, 1], 3, 4], <class 'list'>)\n\n        (Used internally by :class:`Group` when `aslist=True`.)\n        \"\"\"\n\n        def __new__(cls, contained=None):\n            if contained is None:\n                contained = []\n\n            if not isinstance(contained, list):\n                raise TypeError(\n                    \"{} may only be constructed with a list,\"\n                    \" not {}\".format(cls.__name__, type(contained).__name__)\n                )\n\n            return list.__new__(cls)\n\n    def __new__(cls, toklist=None, name=None, **kwargs):\n        if isinstance(toklist, ParseResults):\n            return toklist\n        self = object.__new__(cls)\n        self._name = None\n        self._parent = None\n        self._all_names = set()\n\n        if toklist is None:\n            self._toklist = []\n        elif isinstance(toklist, (list, _generator_type)):\n            self._toklist = (\n                [toklist[:]]\n                if isinstance(toklist, ParseResults.List)\n                else list(toklist)\n            )\n        else:\n            self._toklist = [toklist]\n        self._tokdict = dict()\n        return self\n\n    # Performance tuning: we construct a *lot* of these, so keep this\n    # constructor as small and fast as possible\n    def __init__(\n        self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance\n    ):\n        self._modal = modal\n        if name is not None and name != \"\":\n            if isinstance(name, int):\n                name = str(name)\n            if not modal:\n                self._all_names = {name}\n            self._name = name\n            if toklist not in self._null_values:\n                if isinstance(toklist, (str_type, type)):\n                    toklist = [toklist]\n                if asList:\n                    if isinstance(toklist, ParseResults):\n                        self[name] = _ParseResultsWithOffset(\n                            ParseResults(toklist._toklist), 0\n                        )\n                    else:\n                        self[name] = _ParseResultsWithOffset(\n                            ParseResults(toklist[0]), 0\n                        )\n                    self[name]._name = name\n                else:\n                    try:\n                        self[name] = toklist[0]\n                    except (KeyError, TypeError, IndexError):\n                        if toklist is not self:\n                            self[name] = toklist\n                        else:\n                            self._name = name\n\n    def __getitem__(self, i):\n        if isinstance(i, (int, slice)):\n            return self._toklist[i]\n        else:\n            if i not in self._all_names:\n                return self._tokdict[i][-1][0]\n            else:\n                return ParseResults([v[0] for v in self._tokdict[i]])\n\n    def __setitem__(self, k, v, isinstance=isinstance):\n        if isinstance(v, _ParseResultsWithOffset):\n            self._tokdict[k] = self._tokdict.get(k, list()) + [v]\n            sub = v[0]\n        elif isinstance(k, (int, slice)):\n            self._toklist[k] = v\n            sub = v\n        else:\n            self._tokdict[k] = self._tokdict.get(k, list()) + [\n                _ParseResultsWithOffset(v, 0)\n            ]\n            sub = v\n        if isinstance(sub, ParseResults):\n            sub._parent = wkref(self)\n\n    def __delitem__(self, i):\n        if isinstance(i, (int, slice)):\n            mylen = len(self._toklist)\n            del self._toklist[i]\n\n            # convert int to slice\n            if isinstance(i, int):\n                if i < 0:\n                    i += mylen\n                i = slice(i, i + 1)\n            # get removed indices\n            removed = list(range(*i.indices(mylen)))\n            removed.reverse()\n            # fixup indices in token dictionary\n            for name, occurrences in self._tokdict.items():\n                for j in removed:\n                    for k, (value, position) in enumerate(occurrences):\n                        occurrences[k] = _ParseResultsWithOffset(\n                            value, position - (position > j)\n                        )\n        else:\n            del self._tokdict[i]\n\n    def __contains__(self, k) -> bool:\n        return k in self._tokdict\n\n    def __len__(self) -> int:\n        return len(self._toklist)\n\n    def __bool__(self) -> bool:\n        return not not (self._toklist or self._tokdict)\n\n    def __iter__(self) -> Iterator:\n        return iter(self._toklist)\n\n    def __reversed__(self) -> Iterator:\n        return iter(self._toklist[::-1])\n\n    def keys(self):\n        return iter(self._tokdict)\n\n    def values(self):\n        return (self[k] for k in self.keys())\n\n    def items(self):\n        return ((k, self[k]) for k in self.keys())\n\n    def haskeys(self) -> bool:\n        \"\"\"\n        Since ``keys()`` returns an iterator, this method is helpful in bypassing\n        code that looks for the existence of any defined results names.\"\"\"\n        return bool(self._tokdict)\n\n    def pop(self, *args, **kwargs):\n        \"\"\"\n        Removes and returns item at specified index (default= ``last``).\n        Supports both ``list`` and ``dict`` semantics for ``pop()``. If\n        passed no argument or an integer argument, it will use ``list``\n        semantics and pop tokens from the list of parsed tokens. If passed\n        a non-integer argument (most likely a string), it will use ``dict``\n        semantics and pop the corresponding value from any defined results\n        names. A second default return value argument is supported, just as in\n        ``dict.pop()``.\n\n        Example::\n\n            numlist = Word(nums)[...]\n            print(numlist.parse_string(\"0 123 321\")) # -> ['0', '123', '321']\n\n            def remove_first(tokens):\n                tokens.pop(0)\n            numlist.add_parse_action(remove_first)\n            print(numlist.parse_string(\"0 123 321\")) # -> ['123', '321']\n\n            label = Word(alphas)\n            patt = label(\"LABEL\") + Word(nums)[1, ...]\n            print(patt.parse_string(\"AAB 123 321\").dump())\n\n            # Use pop() in a parse action to remove named result (note that corresponding value is not\n            # removed from list form of results)\n            def remove_LABEL(tokens):\n                tokens.pop(\"LABEL\")\n                return tokens\n            patt.add_parse_action(remove_LABEL)\n            print(patt.parse_string(\"AAB 123 321\").dump())\n\n        prints::\n\n            ['AAB', '123', '321']\n            - LABEL: 'AAB'\n\n            ['AAB', '123', '321']\n        \"\"\"\n        if not args:\n            args = [-1]\n        for k, v in kwargs.items():\n            if k == \"default\":\n                args = (args[0], v)\n            else:\n                raise TypeError(\n                    \"pop() got an unexpected keyword argument {!r}\".format(k)\n                )\n        if isinstance(args[0], int) or len(args) == 1 or args[0] in self:\n            index = args[0]\n            ret = self[index]\n            del self[index]\n            return ret\n        else:\n            defaultvalue = args[1]\n            return defaultvalue\n\n    def get(self, key, default_value=None):\n        \"\"\"\n        Returns named result matching the given key, or if there is no\n        such name, then returns the given ``default_value`` or ``None`` if no\n        ``default_value`` is specified.\n\n        Similar to ``dict.get()``.\n\n        Example::\n\n            integer = Word(nums)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            result = date_str.parse_string(\"1999/12/31\")\n            print(result.get(\"year\")) # -> '1999'\n            print(result.get(\"hour\", \"not specified\")) # -> 'not specified'\n            print(result.get(\"hour\")) # -> None\n        \"\"\"\n        if key in self:\n            return self[key]\n        else:\n            return default_value\n\n    def insert(self, index, ins_string):\n        \"\"\"\n        Inserts new element at location index in the list of parsed tokens.\n\n        Similar to ``list.insert()``.\n\n        Example::\n\n            numlist = Word(nums)[...]\n            print(numlist.parse_string(\"0 123 321\")) # -> ['0', '123', '321']\n\n            # use a parse action to insert the parse location in the front of the parsed results\n            def insert_locn(locn, tokens):\n                tokens.insert(0, locn)\n            numlist.add_parse_action(insert_locn)\n            print(numlist.parse_string(\"0 123 321\")) # -> [0, '0', '123', '321']\n        \"\"\"\n        self._toklist.insert(index, ins_string)\n        # fixup indices in token dictionary\n        for name, occurrences in self._tokdict.items():\n            for k, (value, position) in enumerate(occurrences):\n                occurrences[k] = _ParseResultsWithOffset(\n                    value, position + (position > index)\n                )\n\n    def append(self, item):\n        \"\"\"\n        Add single element to end of ``ParseResults`` list of elements.\n\n        Example::\n\n            numlist = Word(nums)[...]\n            print(numlist.parse_string(\"0 123 321\")) # -> ['0', '123', '321']\n\n            # use a parse action to compute the sum of the parsed integers, and add it to the end\n            def append_sum(tokens):\n                tokens.append(sum(map(int, tokens)))\n            numlist.add_parse_action(append_sum)\n            print(numlist.parse_string(\"0 123 321\")) # -> ['0', '123', '321', 444]\n        \"\"\"\n        self._toklist.append(item)\n\n    def extend(self, itemseq):\n        \"\"\"\n        Add sequence of elements to end of ``ParseResults`` list of elements.\n\n        Example::\n\n            patt = Word(alphas)[1, ...]\n\n            # use a parse action to append the reverse of the matched strings, to make a palindrome\n            def make_palindrome(tokens):\n                tokens.extend(reversed([t[::-1] for t in tokens]))\n                return ''.join(tokens)\n            patt.add_parse_action(make_palindrome)\n            print(patt.parse_string(\"lskdj sdlkjf lksd\")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'\n        \"\"\"\n        if isinstance(itemseq, ParseResults):\n            self.__iadd__(itemseq)\n        else:\n            self._toklist.extend(itemseq)\n\n    def clear(self):\n        \"\"\"\n        Clear all elements and results names.\n        \"\"\"\n        del self._toklist[:]\n        self._tokdict.clear()\n\n    def __getattr__(self, name):\n        try:\n            return self[name]\n        except KeyError:\n            if name.startswith(\"__\"):\n                raise AttributeError(name)\n            return \"\"\n\n    def __add__(self, other) -> \"ParseResults\":\n        ret = self.copy()\n        ret += other\n        return ret\n\n    def __iadd__(self, other) -> \"ParseResults\":\n        if other._tokdict:\n            offset = len(self._toklist)\n            addoffset = lambda a: offset if a < 0 else a + offset\n            otheritems = other._tokdict.items()\n            otherdictitems = [\n                (k, _ParseResultsWithOffset(v[0], addoffset(v[1])))\n                for k, vlist in otheritems\n                for v in vlist\n            ]\n            for k, v in otherdictitems:\n                self[k] = v\n                if isinstance(v[0], ParseResults):\n                    v[0]._parent = wkref(self)\n\n        self._toklist += other._toklist\n        self._all_names |= other._all_names\n        return self\n\n    def __radd__(self, other) -> \"ParseResults\":\n        if isinstance(other, int) and other == 0:\n            # useful for merging many ParseResults using sum() builtin\n            return self.copy()\n        else:\n            # this may raise a TypeError - so be it\n            return other + self\n\n    def __repr__(self) -> str:\n        return \"{}({!r}, {})\".format(type(self).__name__, self._toklist, self.as_dict())\n\n    def __str__(self) -> str:\n        return (\n            \"[\"\n            + \", \".join(\n                [\n                    str(i) if isinstance(i, ParseResults) else repr(i)\n                    for i in self._toklist\n                ]\n            )\n            + \"]\"\n        )\n\n    def _asStringList(self, sep=\"\"):\n        out = []\n        for item in self._toklist:\n            if out and sep:\n                out.append(sep)\n            if isinstance(item, ParseResults):\n                out += item._asStringList()\n            else:\n                out.append(str(item))\n        return out\n\n    def as_list(self) -> list:\n        \"\"\"\n        Returns the parse results as a nested list of matching tokens, all converted to strings.\n\n        Example::\n\n            patt = Word(alphas)[1, ...]\n            result = patt.parse_string(\"sldkj lsdkj sldkj\")\n            # even though the result prints in string-like form, it is actually a pyparsing ParseResults\n            print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']\n\n            # Use as_list() to create an actual list\n            result_list = result.as_list()\n            print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']\n        \"\"\"\n        return [\n            res.as_list() if isinstance(res, ParseResults) else res\n            for res in self._toklist\n        ]\n\n    def as_dict(self) -> dict:\n        \"\"\"\n        Returns the named parse results as a nested dictionary.\n\n        Example::\n\n            integer = Word(nums)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            result = date_str.parse_string('12/31/1999')\n            print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})\n\n            result_dict = result.as_dict()\n            print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}\n\n            # even though a ParseResults supports dict-like access, sometime you just need to have a dict\n            import json\n            print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable\n            print(json.dumps(result.as_dict())) # -> {\"month\": \"31\", \"day\": \"1999\", \"year\": \"12\"}\n        \"\"\"\n\n        def to_item(obj):\n            if isinstance(obj, ParseResults):\n                return obj.as_dict() if obj.haskeys() else [to_item(v) for v in obj]\n            else:\n                return obj\n\n        return dict((k, to_item(v)) for k, v in self.items())\n\n    def copy(self) -> \"ParseResults\":\n        \"\"\"\n        Returns a new copy of a :class:`ParseResults` object.\n        \"\"\"\n        ret = ParseResults(self._toklist)\n        ret._tokdict = self._tokdict.copy()\n        ret._parent = self._parent\n        ret._all_names |= self._all_names\n        ret._name = self._name\n        return ret\n\n    def get_name(self):\n        r\"\"\"\n        Returns the results name for this token expression. Useful when several\n        different expressions might match at a particular location.\n\n        Example::\n\n            integer = Word(nums)\n            ssn_expr = Regex(r\"\\d\\d\\d-\\d\\d-\\d\\d\\d\\d\")\n            house_number_expr = Suppress('#') + Word(nums, alphanums)\n            user_data = (Group(house_number_expr)(\"house_number\")\n                        | Group(ssn_expr)(\"ssn\")\n                        | Group(integer)(\"age\"))\n            user_info = user_data[1, ...]\n\n            result = user_info.parse_string(\"22 111-22-3333 #221B\")\n            for item in result:\n                print(item.get_name(), ':', item[0])\n\n        prints::\n\n            age : 22\n            ssn : 111-22-3333\n            house_number : 221B\n        \"\"\"\n        if self._name:\n            return self._name\n        elif self._parent:\n            par = self._parent()\n\n            def find_in_parent(sub):\n                return next(\n                    (\n                        k\n                        for k, vlist in par._tokdict.items()\n                        for v, loc in vlist\n                        if sub is v\n                    ),\n                    None,\n                )\n\n            return find_in_parent(self) if par else None\n        elif (\n            len(self) == 1\n            and len(self._tokdict) == 1\n            and next(iter(self._tokdict.values()))[0][1] in (0, -1)\n        ):\n            return next(iter(self._tokdict.keys()))\n        else:\n            return None\n\n    def dump(self, indent=\"\", full=True, include_list=True, _depth=0) -> str:\n        \"\"\"\n        Diagnostic method for listing out the contents of\n        a :class:`ParseResults`. Accepts an optional ``indent`` argument so\n        that this string can be embedded in a nested display of other data.\n\n        Example::\n\n            integer = Word(nums)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            result = date_str.parse_string('1999/12/31')\n            print(result.dump())\n\n        prints::\n\n            ['1999', '/', '12', '/', '31']\n            - day: '31'\n            - month: '12'\n            - year: '1999'\n        \"\"\"\n        out = []\n        NL = \"\\n\"\n        out.append(indent + str(self.as_list()) if include_list else \"\")\n\n        if full:\n            if self.haskeys():\n                items = sorted((str(k), v) for k, v in self.items())\n                for k, v in items:\n                    if out:\n                        out.append(NL)\n                    out.append(\"{}{}- {}: \".format(indent, (\"  \" * _depth), k))\n                    if isinstance(v, ParseResults):\n                        if v:\n                            out.append(\n                                v.dump(\n                                    indent=indent,\n                                    full=full,\n                                    include_list=include_list,\n                                    _depth=_depth + 1,\n                                )\n                            )\n                        else:\n                            out.append(str(v))\n                    else:\n                        out.append(repr(v))\n            if any(isinstance(vv, ParseResults) for vv in self):\n                v = self\n                for i, vv in enumerate(v):\n                    if isinstance(vv, ParseResults):\n                        out.append(\n                            \"\\n{}{}[{}]:\\n{}{}{}\".format(\n                                indent,\n                                (\"  \" * (_depth)),\n                                i,\n                                indent,\n                                (\"  \" * (_depth + 1)),\n                                vv.dump(\n                                    indent=indent,\n                                    full=full,\n                                    include_list=include_list,\n                                    _depth=_depth + 1,\n                                ),\n                            )\n                        )\n                    else:\n                        out.append(\n                            \"\\n%s%s[%d]:\\n%s%s%s\"\n                            % (\n                                indent,\n                                (\"  \" * (_depth)),\n                                i,\n                                indent,\n                                (\"  \" * (_depth + 1)),\n                                str(vv),\n                            )\n                        )\n\n        return \"\".join(out)\n\n    def pprint(self, *args, **kwargs):\n        \"\"\"\n        Pretty-printer for parsed results as a list, using the\n        `pprint <https://docs.python.org/3/library/pprint.html>`_ module.\n        Accepts additional positional or keyword args as defined for\n        `pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ .\n\n        Example::\n\n            ident = Word(alphas, alphanums)\n            num = Word(nums)\n            func = Forward()\n            term = ident | num | Group('(' + func + ')')\n            func <<= ident + Group(Optional(delimited_list(term)))\n            result = func.parse_string(\"fna a,b,(fnb c,d,200),100\")\n            result.pprint(width=40)\n\n        prints::\n\n            ['fna',\n             ['a',\n              'b',\n              ['(', 'fnb', ['c', 'd', '200'], ')'],\n              '100']]\n        \"\"\"\n        pprint.pprint(self.as_list(), *args, **kwargs)\n\n    # add support for pickle protocol\n    def __getstate__(self):\n        return (\n            self._toklist,\n            (\n                self._tokdict.copy(),\n                self._parent is not None and self._parent() or None,\n                self._all_names,\n                self._name,\n            ),\n        )\n\n    def __setstate__(self, state):\n        self._toklist, (self._tokdict, par, inAccumNames, self._name) = state\n        self._all_names = set(inAccumNames)\n        if par is not None:\n            self._parent = wkref(par)\n        else:\n            self._parent = None\n\n    def __getnewargs__(self):\n        return self._toklist, self._name\n\n    def __dir__(self):\n        return dir(type(self)) + list(self.keys())\n\n    @classmethod\n    def from_dict(cls, other, name=None) -> \"ParseResults\":\n        \"\"\"\n        Helper classmethod to construct a ``ParseResults`` from a ``dict``, preserving the\n        name-value relations as results names. If an optional ``name`` argument is\n        given, a nested ``ParseResults`` will be returned.\n        \"\"\"\n\n        def is_iterable(obj):\n            try:\n                iter(obj)\n            except Exception:\n                return False\n            else:\n                return not isinstance(obj, str_type)\n\n        ret = cls([])\n        for k, v in other.items():\n            if isinstance(v, Mapping):\n                ret += cls.from_dict(v, name=k)\n            else:\n                ret += cls([v], name=k, asList=is_iterable(v))\n        if name is not None:\n            ret = cls([ret], name=name)\n        return ret\n\n    asList = as_list\n    asDict = as_dict\n    getName = get_name\n\n\nMutableMapping.register(ParseResults)\nMutableSequence.register(ParseResults)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pyparsing/testing.py",
    "content": "# testing.py\n\nfrom contextlib import contextmanager\nimport typing\n\nfrom .core import (\n    ParserElement,\n    ParseException,\n    Keyword,\n    __diag__,\n    __compat__,\n)\n\n\nclass pyparsing_test:\n    \"\"\"\n    namespace class for classes useful in writing unit tests\n    \"\"\"\n\n    class reset_pyparsing_context:\n        \"\"\"\n        Context manager to be used when writing unit tests that modify pyparsing config values:\n        - packrat parsing\n        - bounded recursion parsing\n        - default whitespace characters.\n        - default keyword characters\n        - literal string auto-conversion class\n        - __diag__ settings\n\n        Example::\n\n            with reset_pyparsing_context():\n                # test that literals used to construct a grammar are automatically suppressed\n                ParserElement.inlineLiteralsUsing(Suppress)\n\n                term = Word(alphas) | Word(nums)\n                group = Group('(' + term[...] + ')')\n\n                # assert that the '()' characters are not included in the parsed tokens\n                self.assertParseAndCheckList(group, \"(abc 123 def)\", ['abc', '123', 'def'])\n\n            # after exiting context manager, literals are converted to Literal expressions again\n        \"\"\"\n\n        def __init__(self):\n            self._save_context = {}\n\n        def save(self):\n            self._save_context[\"default_whitespace\"] = ParserElement.DEFAULT_WHITE_CHARS\n            self._save_context[\"default_keyword_chars\"] = Keyword.DEFAULT_KEYWORD_CHARS\n\n            self._save_context[\n                \"literal_string_class\"\n            ] = ParserElement._literalStringClass\n\n            self._save_context[\"verbose_stacktrace\"] = ParserElement.verbose_stacktrace\n\n            self._save_context[\"packrat_enabled\"] = ParserElement._packratEnabled\n            if ParserElement._packratEnabled:\n                self._save_context[\n                    \"packrat_cache_size\"\n                ] = ParserElement.packrat_cache.size\n            else:\n                self._save_context[\"packrat_cache_size\"] = None\n            self._save_context[\"packrat_parse\"] = ParserElement._parse\n            self._save_context[\n                \"recursion_enabled\"\n            ] = ParserElement._left_recursion_enabled\n\n            self._save_context[\"__diag__\"] = {\n                name: getattr(__diag__, name) for name in __diag__._all_names\n            }\n\n            self._save_context[\"__compat__\"] = {\n                \"collect_all_And_tokens\": __compat__.collect_all_And_tokens\n            }\n\n            return self\n\n        def restore(self):\n            # reset pyparsing global state\n            if (\n                ParserElement.DEFAULT_WHITE_CHARS\n                != self._save_context[\"default_whitespace\"]\n            ):\n                ParserElement.set_default_whitespace_chars(\n                    self._save_context[\"default_whitespace\"]\n                )\n\n            ParserElement.verbose_stacktrace = self._save_context[\"verbose_stacktrace\"]\n\n            Keyword.DEFAULT_KEYWORD_CHARS = self._save_context[\"default_keyword_chars\"]\n            ParserElement.inlineLiteralsUsing(\n                self._save_context[\"literal_string_class\"]\n            )\n\n            for name, value in self._save_context[\"__diag__\"].items():\n                (__diag__.enable if value else __diag__.disable)(name)\n\n            ParserElement._packratEnabled = False\n            if self._save_context[\"packrat_enabled\"]:\n                ParserElement.enable_packrat(self._save_context[\"packrat_cache_size\"])\n            else:\n                ParserElement._parse = self._save_context[\"packrat_parse\"]\n            ParserElement._left_recursion_enabled = self._save_context[\n                \"recursion_enabled\"\n            ]\n\n            __compat__.collect_all_And_tokens = self._save_context[\"__compat__\"]\n\n            return self\n\n        def copy(self):\n            ret = type(self)()\n            ret._save_context.update(self._save_context)\n            return ret\n\n        def __enter__(self):\n            return self.save()\n\n        def __exit__(self, *args):\n            self.restore()\n\n    class TestParseResultsAsserts:\n        \"\"\"\n        A mixin class to add parse results assertion methods to normal unittest.TestCase classes.\n        \"\"\"\n\n        def assertParseResultsEquals(\n            self, result, expected_list=None, expected_dict=None, msg=None\n        ):\n            \"\"\"\n            Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``,\n            and compare any defined results names with an optional ``expected_dict``.\n            \"\"\"\n            if expected_list is not None:\n                self.assertEqual(expected_list, result.as_list(), msg=msg)\n            if expected_dict is not None:\n                self.assertEqual(expected_dict, result.as_dict(), msg=msg)\n\n        def assertParseAndCheckList(\n            self, expr, test_string, expected_list, msg=None, verbose=True\n        ):\n            \"\"\"\n            Convenience wrapper assert to test a parser element and input string, and assert that\n            the resulting ``ParseResults.asList()`` is equal to the ``expected_list``.\n            \"\"\"\n            result = expr.parse_string(test_string, parse_all=True)\n            if verbose:\n                print(result.dump())\n            else:\n                print(result.as_list())\n            self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg)\n\n        def assertParseAndCheckDict(\n            self, expr, test_string, expected_dict, msg=None, verbose=True\n        ):\n            \"\"\"\n            Convenience wrapper assert to test a parser element and input string, and assert that\n            the resulting ``ParseResults.asDict()`` is equal to the ``expected_dict``.\n            \"\"\"\n            result = expr.parse_string(test_string, parseAll=True)\n            if verbose:\n                print(result.dump())\n            else:\n                print(result.as_list())\n            self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg)\n\n        def assertRunTestResults(\n            self, run_tests_report, expected_parse_results=None, msg=None\n        ):\n            \"\"\"\n            Unit test assertion to evaluate output of ``ParserElement.runTests()``. If a list of\n            list-dict tuples is given as the ``expected_parse_results`` argument, then these are zipped\n            with the report tuples returned by ``runTests`` and evaluated using ``assertParseResultsEquals``.\n            Finally, asserts that the overall ``runTests()`` success value is ``True``.\n\n            :param run_tests_report: tuple(bool, [tuple(str, ParseResults or Exception)]) returned from runTests\n            :param expected_parse_results (optional): [tuple(str, list, dict, Exception)]\n            \"\"\"\n            run_test_success, run_test_results = run_tests_report\n\n            if expected_parse_results is not None:\n                merged = [\n                    (*rpt, expected)\n                    for rpt, expected in zip(run_test_results, expected_parse_results)\n                ]\n                for test_string, result, expected in merged:\n                    # expected should be a tuple containing a list and/or a dict or an exception,\n                    # and optional failure message string\n                    # an empty tuple will skip any result validation\n                    fail_msg = next(\n                        (exp for exp in expected if isinstance(exp, str)), None\n                    )\n                    expected_exception = next(\n                        (\n                            exp\n                            for exp in expected\n                            if isinstance(exp, type) and issubclass(exp, Exception)\n                        ),\n                        None,\n                    )\n                    if expected_exception is not None:\n                        with self.assertRaises(\n                            expected_exception=expected_exception, msg=fail_msg or msg\n                        ):\n                            if isinstance(result, Exception):\n                                raise result\n                    else:\n                        expected_list = next(\n                            (exp for exp in expected if isinstance(exp, list)), None\n                        )\n                        expected_dict = next(\n                            (exp for exp in expected if isinstance(exp, dict)), None\n                        )\n                        if (expected_list, expected_dict) != (None, None):\n                            self.assertParseResultsEquals(\n                                result,\n                                expected_list=expected_list,\n                                expected_dict=expected_dict,\n                                msg=fail_msg or msg,\n                            )\n                        else:\n                            # warning here maybe?\n                            print(\"no validation for {!r}\".format(test_string))\n\n            # do this last, in case some specific test results can be reported instead\n            self.assertTrue(\n                run_test_success, msg=msg if msg is not None else \"failed runTests\"\n            )\n\n        @contextmanager\n        def assertRaisesParseException(self, exc_type=ParseException, msg=None):\n            with self.assertRaises(exc_type, msg=msg):\n                yield\n\n    @staticmethod\n    def with_line_numbers(\n        s: str,\n        start_line: typing.Optional[int] = None,\n        end_line: typing.Optional[int] = None,\n        expand_tabs: bool = True,\n        eol_mark: str = \"|\",\n        mark_spaces: typing.Optional[str] = None,\n        mark_control: typing.Optional[str] = None,\n    ) -> str:\n        \"\"\"\n        Helpful method for debugging a parser - prints a string with line and column numbers.\n        (Line and column numbers are 1-based.)\n\n        :param s: tuple(bool, str - string to be printed with line and column numbers\n        :param start_line: int - (optional) starting line number in s to print (default=1)\n        :param end_line: int - (optional) ending line number in s to print (default=len(s))\n        :param expand_tabs: bool - (optional) expand tabs to spaces, to match the pyparsing default\n        :param eol_mark: str - (optional) string to mark the end of lines, helps visualize trailing spaces (default=\"|\")\n        :param mark_spaces: str - (optional) special character to display in place of spaces\n        :param mark_control: str - (optional) convert non-printing control characters to a placeholding\n                                 character; valid values:\n                                 - \"unicode\" - replaces control chars with Unicode symbols, such as \"␍\" and \"␊\"\n                                 - any single character string - replace control characters with given string\n                                 - None (default) - string is displayed as-is\n\n        :return: str - input string with leading line numbers and column number headers\n        \"\"\"\n        if expand_tabs:\n            s = s.expandtabs()\n        if mark_control is not None:\n            if mark_control == \"unicode\":\n                tbl = str.maketrans(\n                    {c: u for c, u in zip(range(0, 33), range(0x2400, 0x2433))}\n                    | {127: 0x2421}\n                )\n                eol_mark = \"\"\n            else:\n                tbl = str.maketrans(\n                    {c: mark_control for c in list(range(0, 32)) + [127]}\n                )\n            s = s.translate(tbl)\n        if mark_spaces is not None and mark_spaces != \" \":\n            if mark_spaces == \"unicode\":\n                tbl = str.maketrans({9: 0x2409, 32: 0x2423})\n                s = s.translate(tbl)\n            else:\n                s = s.replace(\" \", mark_spaces)\n        if start_line is None:\n            start_line = 1\n        if end_line is None:\n            end_line = len(s)\n        end_line = min(end_line, len(s))\n        start_line = min(max(1, start_line), end_line)\n\n        if mark_control != \"unicode\":\n            s_lines = s.splitlines()[start_line - 1 : end_line]\n        else:\n            s_lines = [line + \"␊\" for line in s.split(\"␊\")[start_line - 1 : end_line]]\n        if not s_lines:\n            return \"\"\n\n        lineno_width = len(str(end_line))\n        max_line_len = max(len(line) for line in s_lines)\n        lead = \" \" * (lineno_width + 1)\n        if max_line_len >= 99:\n            header0 = (\n                lead\n                + \"\".join(\n                    \"{}{}\".format(\" \" * 99, (i + 1) % 100)\n                    for i in range(max(max_line_len // 100, 1))\n                )\n                + \"\\n\"\n            )\n        else:\n            header0 = \"\"\n        header1 = (\n            header0\n            + lead\n            + \"\".join(\n                \"         {}\".format((i + 1) % 10)\n                for i in range(-(-max_line_len // 10))\n            )\n            + \"\\n\"\n        )\n        header2 = lead + \"1234567890\" * (-(-max_line_len // 10)) + \"\\n\"\n        return (\n            header1\n            + header2\n            + \"\\n\".join(\n                \"{:{}d}:{}{}\".format(i, lineno_width, line, eol_mark)\n                for i, line in enumerate(s_lines, start=start_line)\n            )\n            + \"\\n\"\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pyparsing/unicode.py",
    "content": "# unicode.py\n\nimport sys\nfrom itertools import filterfalse\nfrom typing import List, Tuple, Union\n\n\nclass _lazyclassproperty:\n    def __init__(self, fn):\n        self.fn = fn\n        self.__doc__ = fn.__doc__\n        self.__name__ = fn.__name__\n\n    def __get__(self, obj, cls):\n        if cls is None:\n            cls = type(obj)\n        if not hasattr(cls, \"_intern\") or any(\n            cls._intern is getattr(superclass, \"_intern\", [])\n            for superclass in cls.__mro__[1:]\n        ):\n            cls._intern = {}\n        attrname = self.fn.__name__\n        if attrname not in cls._intern:\n            cls._intern[attrname] = self.fn(cls)\n        return cls._intern[attrname]\n\n\nUnicodeRangeList = List[Union[Tuple[int, int], Tuple[int]]]\n\n\nclass unicode_set:\n    \"\"\"\n    A set of Unicode characters, for language-specific strings for\n    ``alphas``, ``nums``, ``alphanums``, and ``printables``.\n    A unicode_set is defined by a list of ranges in the Unicode character\n    set, in a class attribute ``_ranges``. Ranges can be specified using\n    2-tuples or a 1-tuple, such as::\n\n        _ranges = [\n            (0x0020, 0x007e),\n            (0x00a0, 0x00ff),\n            (0x0100,),\n            ]\n\n    Ranges are left- and right-inclusive. A 1-tuple of (x,) is treated as (x, x).\n\n    A unicode set can also be defined using multiple inheritance of other unicode sets::\n\n        class CJK(Chinese, Japanese, Korean):\n            pass\n    \"\"\"\n\n    _ranges: UnicodeRangeList = []\n\n    @_lazyclassproperty\n    def _chars_for_ranges(cls):\n        ret = []\n        for cc in cls.__mro__:\n            if cc is unicode_set:\n                break\n            for rr in getattr(cc, \"_ranges\", ()):\n                ret.extend(range(rr[0], rr[-1] + 1))\n        return [chr(c) for c in sorted(set(ret))]\n\n    @_lazyclassproperty\n    def printables(cls):\n        \"all non-whitespace characters in this range\"\n        return \"\".join(filterfalse(str.isspace, cls._chars_for_ranges))\n\n    @_lazyclassproperty\n    def alphas(cls):\n        \"all alphabetic characters in this range\"\n        return \"\".join(filter(str.isalpha, cls._chars_for_ranges))\n\n    @_lazyclassproperty\n    def nums(cls):\n        \"all numeric digit characters in this range\"\n        return \"\".join(filter(str.isdigit, cls._chars_for_ranges))\n\n    @_lazyclassproperty\n    def alphanums(cls):\n        \"all alphanumeric characters in this range\"\n        return cls.alphas + cls.nums\n\n    @_lazyclassproperty\n    def identchars(cls):\n        \"all characters in this range that are valid identifier characters, plus underscore '_'\"\n        return \"\".join(\n            sorted(\n                set(\n                    \"\".join(filter(str.isidentifier, cls._chars_for_ranges))\n                    + \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzªµº\"\n                    + \"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\"\n                    + \"_\"\n                )\n            )\n        )\n\n    @_lazyclassproperty\n    def identbodychars(cls):\n        \"\"\"\n        all characters in this range that are valid identifier body characters,\n        plus the digits 0-9\n        \"\"\"\n        return \"\".join(\n            sorted(\n                set(\n                    cls.identchars\n                    + \"0123456789\"\n                    + \"\".join(\n                        [c for c in cls._chars_for_ranges if (\"_\" + c).isidentifier()]\n                    )\n                )\n            )\n        )\n\n\nclass pyparsing_unicode(unicode_set):\n    \"\"\"\n    A namespace class for defining common language unicode_sets.\n    \"\"\"\n\n    # fmt: off\n\n    # define ranges in language character sets\n    _ranges: UnicodeRangeList = [\n        (0x0020, sys.maxunicode),\n    ]\n\n    class BasicMultilingualPlane(unicode_set):\n        \"Unicode set for the Basic Multilingual Plane\"\n        _ranges: UnicodeRangeList = [\n            (0x0020, 0xFFFF),\n        ]\n\n    class Latin1(unicode_set):\n        \"Unicode set for Latin-1 Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0020, 0x007E),\n            (0x00A0, 0x00FF),\n        ]\n\n    class LatinA(unicode_set):\n        \"Unicode set for Latin-A Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0100, 0x017F),\n        ]\n\n    class LatinB(unicode_set):\n        \"Unicode set for Latin-B Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0180, 0x024F),\n        ]\n\n    class Greek(unicode_set):\n        \"Unicode set for Greek Unicode Character Ranges\"\n        _ranges: UnicodeRangeList = [\n            (0x0342, 0x0345),\n            (0x0370, 0x0377),\n            (0x037A, 0x037F),\n            (0x0384, 0x038A),\n            (0x038C,),\n            (0x038E, 0x03A1),\n            (0x03A3, 0x03E1),\n            (0x03F0, 0x03FF),\n            (0x1D26, 0x1D2A),\n            (0x1D5E,),\n            (0x1D60,),\n            (0x1D66, 0x1D6A),\n            (0x1F00, 0x1F15),\n            (0x1F18, 0x1F1D),\n            (0x1F20, 0x1F45),\n            (0x1F48, 0x1F4D),\n            (0x1F50, 0x1F57),\n            (0x1F59,),\n            (0x1F5B,),\n            (0x1F5D,),\n            (0x1F5F, 0x1F7D),\n            (0x1F80, 0x1FB4),\n            (0x1FB6, 0x1FC4),\n            (0x1FC6, 0x1FD3),\n            (0x1FD6, 0x1FDB),\n            (0x1FDD, 0x1FEF),\n            (0x1FF2, 0x1FF4),\n            (0x1FF6, 0x1FFE),\n            (0x2129,),\n            (0x2719, 0x271A),\n            (0xAB65,),\n            (0x10140, 0x1018D),\n            (0x101A0,),\n            (0x1D200, 0x1D245),\n            (0x1F7A1, 0x1F7A7),\n        ]\n\n    class Cyrillic(unicode_set):\n        \"Unicode set for Cyrillic Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0400, 0x052F),\n            (0x1C80, 0x1C88),\n            (0x1D2B,),\n            (0x1D78,),\n            (0x2DE0, 0x2DFF),\n            (0xA640, 0xA672),\n            (0xA674, 0xA69F),\n            (0xFE2E, 0xFE2F),\n        ]\n\n    class Chinese(unicode_set):\n        \"Unicode set for Chinese Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x2E80, 0x2E99),\n            (0x2E9B, 0x2EF3),\n            (0x31C0, 0x31E3),\n            (0x3400, 0x4DB5),\n            (0x4E00, 0x9FEF),\n            (0xA700, 0xA707),\n            (0xF900, 0xFA6D),\n            (0xFA70, 0xFAD9),\n            (0x16FE2, 0x16FE3),\n            (0x1F210, 0x1F212),\n            (0x1F214, 0x1F23B),\n            (0x1F240, 0x1F248),\n            (0x20000, 0x2A6D6),\n            (0x2A700, 0x2B734),\n            (0x2B740, 0x2B81D),\n            (0x2B820, 0x2CEA1),\n            (0x2CEB0, 0x2EBE0),\n            (0x2F800, 0x2FA1D),\n        ]\n\n    class Japanese(unicode_set):\n        \"Unicode set for Japanese Unicode Character Range, combining Kanji, Hiragana, and Katakana ranges\"\n        _ranges: UnicodeRangeList = []\n\n        class Kanji(unicode_set):\n            \"Unicode set for Kanji Unicode Character Range\"\n            _ranges: UnicodeRangeList = [\n                (0x4E00, 0x9FBF),\n                (0x3000, 0x303F),\n            ]\n\n        class Hiragana(unicode_set):\n            \"Unicode set for Hiragana Unicode Character Range\"\n            _ranges: UnicodeRangeList = [\n                (0x3041, 0x3096),\n                (0x3099, 0x30A0),\n                (0x30FC,),\n                (0xFF70,),\n                (0x1B001,),\n                (0x1B150, 0x1B152),\n                (0x1F200,),\n            ]\n\n        class Katakana(unicode_set):\n            \"Unicode set for Katakana  Unicode Character Range\"\n            _ranges: UnicodeRangeList = [\n                (0x3099, 0x309C),\n                (0x30A0, 0x30FF),\n                (0x31F0, 0x31FF),\n                (0x32D0, 0x32FE),\n                (0xFF65, 0xFF9F),\n                (0x1B000,),\n                (0x1B164, 0x1B167),\n                (0x1F201, 0x1F202),\n                (0x1F213,),\n            ]\n\n    class Hangul(unicode_set):\n        \"Unicode set for Hangul (Korean) Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x1100, 0x11FF),\n            (0x302E, 0x302F),\n            (0x3131, 0x318E),\n            (0x3200, 0x321C),\n            (0x3260, 0x327B),\n            (0x327E,),\n            (0xA960, 0xA97C),\n            (0xAC00, 0xD7A3),\n            (0xD7B0, 0xD7C6),\n            (0xD7CB, 0xD7FB),\n            (0xFFA0, 0xFFBE),\n            (0xFFC2, 0xFFC7),\n            (0xFFCA, 0xFFCF),\n            (0xFFD2, 0xFFD7),\n            (0xFFDA, 0xFFDC),\n        ]\n\n    Korean = Hangul\n\n    class CJK(Chinese, Japanese, Hangul):\n        \"Unicode set for combined Chinese, Japanese, and Korean (CJK) Unicode Character Range\"\n\n    class Thai(unicode_set):\n        \"Unicode set for Thai Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0E01, 0x0E3A),\n            (0x0E3F, 0x0E5B)\n        ]\n\n    class Arabic(unicode_set):\n        \"Unicode set for Arabic Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0600, 0x061B),\n            (0x061E, 0x06FF),\n            (0x0700, 0x077F),\n        ]\n\n    class Hebrew(unicode_set):\n        \"Unicode set for Hebrew Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0591, 0x05C7),\n            (0x05D0, 0x05EA),\n            (0x05EF, 0x05F4),\n            (0xFB1D, 0xFB36),\n            (0xFB38, 0xFB3C),\n            (0xFB3E,),\n            (0xFB40, 0xFB41),\n            (0xFB43, 0xFB44),\n            (0xFB46, 0xFB4F),\n        ]\n\n    class Devanagari(unicode_set):\n        \"Unicode set for Devanagari Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0900, 0x097F),\n            (0xA8E0, 0xA8FF)\n        ]\n\n    # fmt: on\n\n\npyparsing_unicode.Japanese._ranges = (\n    pyparsing_unicode.Japanese.Kanji._ranges\n    + pyparsing_unicode.Japanese.Hiragana._ranges\n    + pyparsing_unicode.Japanese.Katakana._ranges\n)\n\npyparsing_unicode.BMP = pyparsing_unicode.BasicMultilingualPlane\n\n# add language identifiers using language Unicode\npyparsing_unicode.العربية = pyparsing_unicode.Arabic\npyparsing_unicode.中文 = pyparsing_unicode.Chinese\npyparsing_unicode.кириллица = pyparsing_unicode.Cyrillic\npyparsing_unicode.Ελληνικά = pyparsing_unicode.Greek\npyparsing_unicode.עִברִית = pyparsing_unicode.Hebrew\npyparsing_unicode.日本語 = pyparsing_unicode.Japanese\npyparsing_unicode.Japanese.漢字 = pyparsing_unicode.Japanese.Kanji\npyparsing_unicode.Japanese.カタカナ = pyparsing_unicode.Japanese.Katakana\npyparsing_unicode.Japanese.ひらがな = pyparsing_unicode.Japanese.Hiragana\npyparsing_unicode.한국어 = pyparsing_unicode.Korean\npyparsing_unicode.ไทย = pyparsing_unicode.Thai\npyparsing_unicode.देवनागरी = pyparsing_unicode.Devanagari\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/pyparsing/util.py",
    "content": "# util.py\nimport warnings\nimport types\nimport collections\nimport itertools\nfrom functools import lru_cache\nfrom typing import List, Union, Iterable\n\n_bslash = chr(92)\n\n\nclass __config_flags:\n    \"\"\"Internal class for defining compatibility and debugging flags\"\"\"\n\n    _all_names: List[str] = []\n    _fixed_names: List[str] = []\n    _type_desc = \"configuration\"\n\n    @classmethod\n    def _set(cls, dname, value):\n        if dname in cls._fixed_names:\n            warnings.warn(\n                \"{}.{} {} is {} and cannot be overridden\".format(\n                    cls.__name__,\n                    dname,\n                    cls._type_desc,\n                    str(getattr(cls, dname)).upper(),\n                )\n            )\n            return\n        if dname in cls._all_names:\n            setattr(cls, dname, value)\n        else:\n            raise ValueError(\"no such {} {!r}\".format(cls._type_desc, dname))\n\n    enable = classmethod(lambda cls, name: cls._set(name, True))\n    disable = classmethod(lambda cls, name: cls._set(name, False))\n\n\n@lru_cache(maxsize=128)\ndef col(loc: int, strg: str) -> int:\n    \"\"\"\n    Returns current column within a string, counting newlines as line separators.\n    The first column is number 1.\n\n    Note: the default parsing behavior is to expand tabs in the input string\n    before starting the parsing process.  See\n    :class:`ParserElement.parseString` for more\n    information on parsing strings containing ``<TAB>`` s, and suggested\n    methods to maintain a consistent view of the parsed string, the parse\n    location, and line and column positions within the parsed string.\n    \"\"\"\n    s = strg\n    return 1 if 0 < loc < len(s) and s[loc - 1] == \"\\n\" else loc - s.rfind(\"\\n\", 0, loc)\n\n\n@lru_cache(maxsize=128)\ndef lineno(loc: int, strg: str) -> int:\n    \"\"\"Returns current line number within a string, counting newlines as line separators.\n    The first line is number 1.\n\n    Note - the default parsing behavior is to expand tabs in the input string\n    before starting the parsing process.  See :class:`ParserElement.parseString`\n    for more information on parsing strings containing ``<TAB>`` s, and\n    suggested methods to maintain a consistent view of the parsed string, the\n    parse location, and line and column positions within the parsed string.\n    \"\"\"\n    return strg.count(\"\\n\", 0, loc) + 1\n\n\n@lru_cache(maxsize=128)\ndef line(loc: int, strg: str) -> str:\n    \"\"\"\n    Returns the line of text containing loc within a string, counting newlines as line separators.\n    \"\"\"\n    last_cr = strg.rfind(\"\\n\", 0, loc)\n    next_cr = strg.find(\"\\n\", loc)\n    return strg[last_cr + 1 : next_cr] if next_cr >= 0 else strg[last_cr + 1 :]\n\n\nclass _UnboundedCache:\n    def __init__(self):\n        cache = {}\n        cache_get = cache.get\n        self.not_in_cache = not_in_cache = object()\n\n        def get(_, key):\n            return cache_get(key, not_in_cache)\n\n        def set_(_, key, value):\n            cache[key] = value\n\n        def clear(_):\n            cache.clear()\n\n        self.size = None\n        self.get = types.MethodType(get, self)\n        self.set = types.MethodType(set_, self)\n        self.clear = types.MethodType(clear, self)\n\n\nclass _FifoCache:\n    def __init__(self, size):\n        self.not_in_cache = not_in_cache = object()\n        cache = collections.OrderedDict()\n        cache_get = cache.get\n\n        def get(_, key):\n            return cache_get(key, not_in_cache)\n\n        def set_(_, key, value):\n            cache[key] = value\n            while len(cache) > size:\n                cache.popitem(last=False)\n\n        def clear(_):\n            cache.clear()\n\n        self.size = size\n        self.get = types.MethodType(get, self)\n        self.set = types.MethodType(set_, self)\n        self.clear = types.MethodType(clear, self)\n\n\nclass LRUMemo:\n    \"\"\"\n    A memoizing mapping that retains `capacity` deleted items\n\n    The memo tracks retained items by their access order; once `capacity` items\n    are retained, the least recently used item is discarded.\n    \"\"\"\n\n    def __init__(self, capacity):\n        self._capacity = capacity\n        self._active = {}\n        self._memory = collections.OrderedDict()\n\n    def __getitem__(self, key):\n        try:\n            return self._active[key]\n        except KeyError:\n            self._memory.move_to_end(key)\n            return self._memory[key]\n\n    def __setitem__(self, key, value):\n        self._memory.pop(key, None)\n        self._active[key] = value\n\n    def __delitem__(self, key):\n        try:\n            value = self._active.pop(key)\n        except KeyError:\n            pass\n        else:\n            while len(self._memory) >= self._capacity:\n                self._memory.popitem(last=False)\n            self._memory[key] = value\n\n    def clear(self):\n        self._active.clear()\n        self._memory.clear()\n\n\nclass UnboundedMemo(dict):\n    \"\"\"\n    A memoizing mapping that retains all deleted items\n    \"\"\"\n\n    def __delitem__(self, key):\n        pass\n\n\ndef _escape_regex_range_chars(s: str) -> str:\n    # escape these chars: ^-[]\n    for c in r\"\\^-[]\":\n        s = s.replace(c, _bslash + c)\n    s = s.replace(\"\\n\", r\"\\n\")\n    s = s.replace(\"\\t\", r\"\\t\")\n    return str(s)\n\n\ndef _collapse_string_to_ranges(\n    s: Union[str, Iterable[str]], re_escape: bool = True\n) -> str:\n    def is_consecutive(c):\n        c_int = ord(c)\n        is_consecutive.prev, prev = c_int, is_consecutive.prev\n        if c_int - prev > 1:\n            is_consecutive.value = next(is_consecutive.counter)\n        return is_consecutive.value\n\n    is_consecutive.prev = 0\n    is_consecutive.counter = itertools.count()\n    is_consecutive.value = -1\n\n    def escape_re_range_char(c):\n        return \"\\\\\" + c if c in r\"\\^-][\" else c\n\n    def no_escape_re_range_char(c):\n        return c\n\n    if not re_escape:\n        escape_re_range_char = no_escape_re_range_char\n\n    ret = []\n    s = \"\".join(sorted(set(s)))\n    if len(s) > 3:\n        for _, chars in itertools.groupby(s, key=is_consecutive):\n            first = last = next(chars)\n            last = collections.deque(\n                itertools.chain(iter([last]), chars), maxlen=1\n            ).pop()\n            if first == last:\n                ret.append(escape_re_range_char(first))\n            else:\n                sep = \"\" if ord(last) == ord(first) + 1 else \"-\"\n                ret.append(\n                    \"{}{}{}\".format(\n                        escape_re_range_char(first), sep, escape_re_range_char(last)\n                    )\n                )\n    else:\n        ret = [escape_re_range_char(c) for c in s]\n\n    return \"\".join(ret)\n\n\ndef _flatten(ll: list) -> list:\n    ret = []\n    for i in ll:\n        if isinstance(i, list):\n            ret.extend(_flatten(i))\n        else:\n            ret.append(i)\n    return ret\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/__init__.py",
    "content": "#   __\n#  /__)  _  _     _   _ _/   _\n# / (   (- (/ (/ (- _)  /  _)\n#          /\n\n\"\"\"\nRequests HTTP Library\n~~~~~~~~~~~~~~~~~~~~~\n\nRequests is an HTTP library, written in Python, for human beings.\nBasic GET usage:\n\n   >>> import requests\n   >>> r = requests.get('https://www.python.org')\n   >>> r.status_code\n   200\n   >>> b'Python is a programming language' in r.content\n   True\n\n... or POST:\n\n   >>> payload = dict(key1='value1', key2='value2')\n   >>> r = requests.post('https://httpbin.org/post', data=payload)\n   >>> print(r.text)\n   {\n     ...\n     \"form\": {\n       \"key1\": \"value1\",\n       \"key2\": \"value2\"\n     },\n     ...\n   }\n\nThe other HTTP methods are supported - see `requests.api`. Full documentation\nis at <https://requests.readthedocs.io>.\n\n:copyright: (c) 2017 by Kenneth Reitz.\n:license: Apache 2.0, see LICENSE for more details.\n\"\"\"\n\nimport warnings\n\nfrom pip._vendor import urllib3\n\nfrom .exceptions import RequestsDependencyWarning\n\ncharset_normalizer_version = None\n\ntry:\n    from pip._vendor.chardet import __version__ as chardet_version\nexcept ImportError:\n    chardet_version = None\n\n\ndef check_compatibility(urllib3_version, chardet_version, charset_normalizer_version):\n    urllib3_version = urllib3_version.split(\".\")\n    assert urllib3_version != [\"dev\"]  # Verify urllib3 isn't installed from git.\n\n    # Sometimes, urllib3 only reports its version as 16.1.\n    if len(urllib3_version) == 2:\n        urllib3_version.append(\"0\")\n\n    # Check urllib3 for compatibility.\n    major, minor, patch = urllib3_version  # noqa: F811\n    major, minor, patch = int(major), int(minor), int(patch)\n    # urllib3 >= 1.21.1, <= 1.26\n    assert major == 1\n    assert minor >= 21\n    assert minor <= 26\n\n    # Check charset_normalizer for compatibility.\n    if chardet_version:\n        major, minor, patch = chardet_version.split(\".\")[:3]\n        major, minor, patch = int(major), int(minor), int(patch)\n        # chardet_version >= 3.0.2, < 6.0.0\n        assert (3, 0, 2) <= (major, minor, patch) < (6, 0, 0)\n    elif charset_normalizer_version:\n        major, minor, patch = charset_normalizer_version.split(\".\")[:3]\n        major, minor, patch = int(major), int(minor), int(patch)\n        # charset_normalizer >= 2.0.0 < 3.0.0\n        assert (2, 0, 0) <= (major, minor, patch) < (3, 0, 0)\n    else:\n        raise Exception(\"You need either charset_normalizer or chardet installed\")\n\n\ndef _check_cryptography(cryptography_version):\n    # cryptography < 1.3.4\n    try:\n        cryptography_version = list(map(int, cryptography_version.split(\".\")))\n    except ValueError:\n        return\n\n    if cryptography_version < [1, 3, 4]:\n        warning = \"Old version of cryptography ({}) may cause slowdown.\".format(\n            cryptography_version\n        )\n        warnings.warn(warning, RequestsDependencyWarning)\n\n\n# Check imported dependencies for compatibility.\ntry:\n    check_compatibility(\n        urllib3.__version__, chardet_version, charset_normalizer_version\n    )\nexcept (AssertionError, ValueError):\n    warnings.warn(\n        \"urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported \"\n        \"version!\".format(\n            urllib3.__version__, chardet_version, charset_normalizer_version\n        ),\n        RequestsDependencyWarning,\n    )\n\n# Attempt to enable urllib3's fallback for SNI support\n# if the standard library doesn't support SNI or the\n# 'ssl' library isn't available.\ntry:\n    # Note: This logic prevents upgrading cryptography on Windows, if imported\n    #       as part of pip.\n    from pip._internal.utils.compat import WINDOWS\n    if not WINDOWS:\n        raise ImportError(\"pip internals: don't import cryptography on Windows\")\n    try:\n        import ssl\n    except ImportError:\n        ssl = None\n\n    if not getattr(ssl, \"HAS_SNI\", False):\n        from pip._vendor.urllib3.contrib import pyopenssl\n\n        pyopenssl.inject_into_urllib3()\n\n        # Check cryptography version\n        from cryptography import __version__ as cryptography_version\n\n        _check_cryptography(cryptography_version)\nexcept ImportError:\n    pass\n\n# urllib3's DependencyWarnings should be silenced.\nfrom pip._vendor.urllib3.exceptions import DependencyWarning\n\nwarnings.simplefilter(\"ignore\", DependencyWarning)\n\n# Set default logging handler to avoid \"No handler found\" warnings.\nimport logging\nfrom logging import NullHandler\n\nfrom . import packages, utils\nfrom .__version__ import (\n    __author__,\n    __author_email__,\n    __build__,\n    __cake__,\n    __copyright__,\n    __description__,\n    __license__,\n    __title__,\n    __url__,\n    __version__,\n)\nfrom .api import delete, get, head, options, patch, post, put, request\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    FileModeWarning,\n    HTTPError,\n    JSONDecodeError,\n    ReadTimeout,\n    RequestException,\n    Timeout,\n    TooManyRedirects,\n    URLRequired,\n)\nfrom .models import PreparedRequest, Request, Response\nfrom .sessions import Session, session\nfrom .status_codes import codes\n\nlogging.getLogger(__name__).addHandler(NullHandler())\n\n# FileModeWarnings go off per the default.\nwarnings.simplefilter(\"default\", FileModeWarning, append=True)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/__version__.py",
    "content": "# .-. .-. .-. . . .-. .-. .-. .-.\n# |(  |-  |.| | | |-  `-.  |  `-.\n# ' ' `-' `-`.`-' `-' `-'  '  `-'\n\n__title__ = \"requests\"\n__description__ = \"Python HTTP for Humans.\"\n__url__ = \"https://requests.readthedocs.io\"\n__version__ = \"2.28.1\"\n__build__ = 0x022801\n__author__ = \"Kenneth Reitz\"\n__author_email__ = \"me@kennethreitz.org\"\n__license__ = \"Apache 2.0\"\n__copyright__ = \"Copyright 2022 Kenneth Reitz\"\n__cake__ = \"\\u2728 \\U0001f370 \\u2728\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/_internal_utils.py",
    "content": "\"\"\"\nrequests._internal_utils\n~~~~~~~~~~~~~~\n\nProvides utility functions that are consumed internally by Requests\nwhich depend on extremely few external helpers (such as compat)\n\"\"\"\nimport re\n\nfrom .compat import builtin_str\n\n_VALID_HEADER_NAME_RE_BYTE = re.compile(rb\"^[^:\\s][^:\\r\\n]*$\")\n_VALID_HEADER_NAME_RE_STR = re.compile(r\"^[^:\\s][^:\\r\\n]*$\")\n_VALID_HEADER_VALUE_RE_BYTE = re.compile(rb\"^\\S[^\\r\\n]*$|^$\")\n_VALID_HEADER_VALUE_RE_STR = re.compile(r\"^\\S[^\\r\\n]*$|^$\")\n\nHEADER_VALIDATORS = {\n    bytes: (_VALID_HEADER_NAME_RE_BYTE, _VALID_HEADER_VALUE_RE_BYTE),\n    str: (_VALID_HEADER_NAME_RE_STR, _VALID_HEADER_VALUE_RE_STR),\n}\n\n\ndef to_native_string(string, encoding=\"ascii\"):\n    \"\"\"Given a string object, regardless of type, returns a representation of\n    that string in the native string type, encoding and decoding where\n    necessary. This assumes ASCII unless told otherwise.\n    \"\"\"\n    if isinstance(string, builtin_str):\n        out = string\n    else:\n        out = string.decode(encoding)\n\n    return out\n\n\ndef unicode_is_ascii(u_string):\n    \"\"\"Determine if unicode string only contains ASCII characters.\n\n    :param str u_string: unicode string to check. Must be unicode\n        and not Python 2 `str`.\n    :rtype: bool\n    \"\"\"\n    assert isinstance(u_string, str)\n    try:\n        u_string.encode(\"ascii\")\n        return True\n    except UnicodeEncodeError:\n        return False\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/adapters.py",
    "content": "\"\"\"\nrequests.adapters\n~~~~~~~~~~~~~~~~~\n\nThis module contains the transport adapters that Requests uses to define\nand maintain connections.\n\"\"\"\n\nimport os.path\nimport socket  # noqa: F401\n\nfrom pip._vendor.urllib3.exceptions import ClosedPoolError, ConnectTimeoutError\nfrom pip._vendor.urllib3.exceptions import HTTPError as _HTTPError\nfrom pip._vendor.urllib3.exceptions import InvalidHeader as _InvalidHeader\nfrom pip._vendor.urllib3.exceptions import (\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n)\nfrom pip._vendor.urllib3.exceptions import ProxyError as _ProxyError\nfrom pip._vendor.urllib3.exceptions import ReadTimeoutError, ResponseError\nfrom pip._vendor.urllib3.exceptions import SSLError as _SSLError\nfrom pip._vendor.urllib3.poolmanager import PoolManager, proxy_from_url\nfrom pip._vendor.urllib3.response import HTTPResponse\nfrom pip._vendor.urllib3.util import Timeout as TimeoutSauce\nfrom pip._vendor.urllib3.util import parse_url\nfrom pip._vendor.urllib3.util.retry import Retry\n\nfrom .auth import _basic_auth_str\nfrom .compat import basestring, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .exceptions import (\n    ConnectionError,\n    ConnectTimeout,\n    InvalidHeader,\n    InvalidProxyURL,\n    InvalidSchema,\n    InvalidURL,\n    ProxyError,\n    ReadTimeout,\n    RetryError,\n    SSLError,\n)\nfrom .models import Response\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    DEFAULT_CA_BUNDLE_PATH,\n    extract_zipped_paths,\n    get_auth_from_url,\n    get_encoding_from_headers,\n    prepend_scheme_if_needed,\n    select_proxy,\n    urldefragauth,\n)\n\ntry:\n    from pip._vendor.urllib3.contrib.socks import SOCKSProxyManager\nexcept ImportError:\n\n    def SOCKSProxyManager(*args, **kwargs):\n        raise InvalidSchema(\"Missing dependencies for SOCKS support.\")\n\n\nDEFAULT_POOLBLOCK = False\nDEFAULT_POOLSIZE = 10\nDEFAULT_RETRIES = 0\nDEFAULT_POOL_TIMEOUT = None\n\n\nclass BaseAdapter:\n    \"\"\"The Base Transport Adapter\"\"\"\n\n    def __init__(self):\n        super().__init__()\n\n    def send(\n        self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None\n    ):\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        \"\"\"\n        raise NotImplementedError\n\n    def close(self):\n        \"\"\"Cleans up adapter specific items.\"\"\"\n        raise NotImplementedError\n\n\nclass HTTPAdapter(BaseAdapter):\n    \"\"\"The built-in HTTP Adapter for urllib3.\n\n    Provides a general-case interface for Requests sessions to contact HTTP and\n    HTTPS urls by implementing the Transport Adapter interface. This class will\n    usually be created by the :class:`Session <Session>` class under the\n    covers.\n\n    :param pool_connections: The number of urllib3 connection pools to cache.\n    :param pool_maxsize: The maximum number of connections to save in the pool.\n    :param max_retries: The maximum number of retries each connection\n        should attempt. Note, this applies only to failed DNS lookups, socket\n        connections and connection timeouts, never to requests where data has\n        made it to the server. By default, Requests does not retry failed\n        connections. If you need granular control over the conditions under\n        which we retry a request, import urllib3's ``Retry`` class and pass\n        that instead.\n    :param pool_block: Whether the connection pool should block for connections.\n\n    Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> a = requests.adapters.HTTPAdapter(max_retries=3)\n      >>> s.mount('http://', a)\n    \"\"\"\n\n    __attrs__ = [\n        \"max_retries\",\n        \"config\",\n        \"_pool_connections\",\n        \"_pool_maxsize\",\n        \"_pool_block\",\n    ]\n\n    def __init__(\n        self,\n        pool_connections=DEFAULT_POOLSIZE,\n        pool_maxsize=DEFAULT_POOLSIZE,\n        max_retries=DEFAULT_RETRIES,\n        pool_block=DEFAULT_POOLBLOCK,\n    ):\n        if max_retries == DEFAULT_RETRIES:\n            self.max_retries = Retry(0, read=False)\n        else:\n            self.max_retries = Retry.from_int(max_retries)\n        self.config = {}\n        self.proxy_manager = {}\n\n        super().__init__()\n\n        self._pool_connections = pool_connections\n        self._pool_maxsize = pool_maxsize\n        self._pool_block = pool_block\n\n        self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n\n    def __getstate__(self):\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state):\n        # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n        # self.poolmanager uses a lambda function, which isn't pickleable.\n        self.proxy_manager = {}\n        self.config = {}\n\n        for attr, value in state.items():\n            setattr(self, attr, value)\n\n        self.init_poolmanager(\n            self._pool_connections, self._pool_maxsize, block=self._pool_block\n        )\n\n    def init_poolmanager(\n        self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs\n    ):\n        \"\"\"Initializes a urllib3 PoolManager.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param connections: The number of urllib3 connection pools to cache.\n        :param maxsize: The maximum number of connections to save in the pool.\n        :param block: Block when no free connections are available.\n        :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.\n        \"\"\"\n        # save these values for pickling\n        self._pool_connections = connections\n        self._pool_maxsize = maxsize\n        self._pool_block = block\n\n        self.poolmanager = PoolManager(\n            num_pools=connections,\n            maxsize=maxsize,\n            block=block,\n            strict=True,\n            **pool_kwargs,\n        )\n\n    def proxy_manager_for(self, proxy, **proxy_kwargs):\n        \"\"\"Return urllib3 ProxyManager for the given proxy.\n\n        This method should not be called from user code, and is only\n        exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The proxy to return a urllib3 ProxyManager for.\n        :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.\n        :returns: ProxyManager\n        :rtype: urllib3.ProxyManager\n        \"\"\"\n        if proxy in self.proxy_manager:\n            manager = self.proxy_manager[proxy]\n        elif proxy.lower().startswith(\"socks\"):\n            username, password = get_auth_from_url(proxy)\n            manager = self.proxy_manager[proxy] = SOCKSProxyManager(\n                proxy,\n                username=username,\n                password=password,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n        else:\n            proxy_headers = self.proxy_headers(proxy)\n            manager = self.proxy_manager[proxy] = proxy_from_url(\n                proxy,\n                proxy_headers=proxy_headers,\n                num_pools=self._pool_connections,\n                maxsize=self._pool_maxsize,\n                block=self._pool_block,\n                **proxy_kwargs,\n            )\n\n        return manager\n\n    def cert_verify(self, conn, url, verify, cert):\n        \"\"\"Verify a SSL certificate. This method should not be called from user\n        code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param conn: The urllib3 connection object associated with the cert.\n        :param url: The requested URL.\n        :param verify: Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use\n        :param cert: The SSL certificate to verify.\n        \"\"\"\n        if url.lower().startswith(\"https\") and verify:\n\n            cert_loc = None\n\n            # Allow self-specified cert location.\n            if verify is not True:\n                cert_loc = verify\n\n            if not cert_loc:\n                cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)\n\n            if not cert_loc or not os.path.exists(cert_loc):\n                raise OSError(\n                    f\"Could not find a suitable TLS CA certificate bundle, \"\n                    f\"invalid path: {cert_loc}\"\n                )\n\n            conn.cert_reqs = \"CERT_REQUIRED\"\n\n            if not os.path.isdir(cert_loc):\n                conn.ca_certs = cert_loc\n            else:\n                conn.ca_cert_dir = cert_loc\n        else:\n            conn.cert_reqs = \"CERT_NONE\"\n            conn.ca_certs = None\n            conn.ca_cert_dir = None\n\n        if cert:\n            if not isinstance(cert, basestring):\n                conn.cert_file = cert[0]\n                conn.key_file = cert[1]\n            else:\n                conn.cert_file = cert\n                conn.key_file = None\n            if conn.cert_file and not os.path.exists(conn.cert_file):\n                raise OSError(\n                    f\"Could not find the TLS certificate file, \"\n                    f\"invalid path: {conn.cert_file}\"\n                )\n            if conn.key_file and not os.path.exists(conn.key_file):\n                raise OSError(\n                    f\"Could not find the TLS key file, invalid path: {conn.key_file}\"\n                )\n\n    def build_response(self, req, resp):\n        \"\"\"Builds a :class:`Response <requests.Response>` object from a urllib3\n        response. This should not be called from user code, and is only exposed\n        for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`\n\n        :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.\n        :param resp: The urllib3 response object.\n        :rtype: requests.Response\n        \"\"\"\n        response = Response()\n\n        # Fallback to None if there's no status_code, for whatever reason.\n        response.status_code = getattr(resp, \"status\", None)\n\n        # Make headers case-insensitive.\n        response.headers = CaseInsensitiveDict(getattr(resp, \"headers\", {}))\n\n        # Set encoding.\n        response.encoding = get_encoding_from_headers(response.headers)\n        response.raw = resp\n        response.reason = response.raw.reason\n\n        if isinstance(req.url, bytes):\n            response.url = req.url.decode(\"utf-8\")\n        else:\n            response.url = req.url\n\n        # Add new cookies from the server.\n        extract_cookies_to_jar(response.cookies, req, resp)\n\n        # Give the Response some context.\n        response.request = req\n        response.connection = self\n\n        return response\n\n    def get_connection(self, url, proxies=None):\n        \"\"\"Returns a urllib3 connection for the given URL. This should not be\n        called from user code, and is only exposed for use when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param url: The URL to connect to.\n        :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n        :rtype: urllib3.ConnectionPool\n        \"\"\"\n        proxy = select_proxy(url, proxies)\n\n        if proxy:\n            proxy = prepend_scheme_if_needed(proxy, \"http\")\n            proxy_url = parse_url(proxy)\n            if not proxy_url.host:\n                raise InvalidProxyURL(\n                    \"Please check proxy URL. It is malformed \"\n                    \"and could be missing the host.\"\n                )\n            proxy_manager = self.proxy_manager_for(proxy)\n            conn = proxy_manager.connection_from_url(url)\n        else:\n            # Only scheme should be lower case\n            parsed = urlparse(url)\n            url = parsed.geturl()\n            conn = self.poolmanager.connection_from_url(url)\n\n        return conn\n\n    def close(self):\n        \"\"\"Disposes of any internal state.\n\n        Currently, this closes the PoolManager and any active ProxyManager,\n        which closes any pooled connections.\n        \"\"\"\n        self.poolmanager.clear()\n        for proxy in self.proxy_manager.values():\n            proxy.clear()\n\n    def request_url(self, request, proxies):\n        \"\"\"Obtain the url to use when making the final request.\n\n        If the message is being sent through a HTTP proxy, the full URL has to\n        be used. Otherwise, we should only use the path portion of the URL.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.\n        :rtype: str\n        \"\"\"\n        proxy = select_proxy(request.url, proxies)\n        scheme = urlparse(request.url).scheme\n\n        is_proxied_http_request = proxy and scheme != \"https\"\n        using_socks_proxy = False\n        if proxy:\n            proxy_scheme = urlparse(proxy).scheme.lower()\n            using_socks_proxy = proxy_scheme.startswith(\"socks\")\n\n        url = request.path_url\n        if is_proxied_http_request and not using_socks_proxy:\n            url = urldefragauth(request.url)\n\n        return url\n\n    def add_headers(self, request, **kwargs):\n        \"\"\"Add any headers needed by the connection. As of v2.0 this does\n        nothing by default, but is left for overriding by users that subclass\n        the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.\n        :param kwargs: The keyword arguments from the call to send().\n        \"\"\"\n        pass\n\n    def proxy_headers(self, proxy):\n        \"\"\"Returns a dictionary of the headers to add to any request sent\n        through a proxy. This works with urllib3 magic to ensure that they are\n        correctly sent to the proxy, rather than in a tunnelled request if\n        CONNECT is being used.\n\n        This should not be called from user code, and is only exposed for use\n        when subclassing the\n        :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.\n\n        :param proxy: The url of the proxy being used for this request.\n        :rtype: dict\n        \"\"\"\n        headers = {}\n        username, password = get_auth_from_url(proxy)\n\n        if username:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return headers\n\n    def send(\n        self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None\n    ):\n        \"\"\"Sends PreparedRequest object. Returns Response object.\n\n        :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.\n        :param stream: (optional) Whether to stream the request content.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple or urllib3 Timeout object\n        :param verify: (optional) Either a boolean, in which case it controls whether\n            we verify the server's TLS certificate, or a string, in which case it\n            must be a path to a CA bundle to use\n        :param cert: (optional) Any user-provided SSL certificate to be trusted.\n        :param proxies: (optional) The proxies dictionary to apply to the request.\n        :rtype: requests.Response\n        \"\"\"\n\n        try:\n            conn = self.get_connection(request.url, proxies)\n        except LocationValueError as e:\n            raise InvalidURL(e, request=request)\n\n        self.cert_verify(conn, request.url, verify, cert)\n        url = self.request_url(request, proxies)\n        self.add_headers(\n            request,\n            stream=stream,\n            timeout=timeout,\n            verify=verify,\n            cert=cert,\n            proxies=proxies,\n        )\n\n        chunked = not (request.body is None or \"Content-Length\" in request.headers)\n\n        if isinstance(timeout, tuple):\n            try:\n                connect, read = timeout\n                timeout = TimeoutSauce(connect=connect, read=read)\n            except ValueError:\n                raise ValueError(\n                    f\"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, \"\n                    f\"or a single float to set both timeouts to the same value.\"\n                )\n        elif isinstance(timeout, TimeoutSauce):\n            pass\n        else:\n            timeout = TimeoutSauce(connect=timeout, read=timeout)\n\n        try:\n            if not chunked:\n                resp = conn.urlopen(\n                    method=request.method,\n                    url=url,\n                    body=request.body,\n                    headers=request.headers,\n                    redirect=False,\n                    assert_same_host=False,\n                    preload_content=False,\n                    decode_content=False,\n                    retries=self.max_retries,\n                    timeout=timeout,\n                )\n\n            # Send the request.\n            else:\n                if hasattr(conn, \"proxy_pool\"):\n                    conn = conn.proxy_pool\n\n                low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)\n\n                try:\n                    skip_host = \"Host\" in request.headers\n                    low_conn.putrequest(\n                        request.method,\n                        url,\n                        skip_accept_encoding=True,\n                        skip_host=skip_host,\n                    )\n\n                    for header, value in request.headers.items():\n                        low_conn.putheader(header, value)\n\n                    low_conn.endheaders()\n\n                    for i in request.body:\n                        low_conn.send(hex(len(i))[2:].encode(\"utf-8\"))\n                        low_conn.send(b\"\\r\\n\")\n                        low_conn.send(i)\n                        low_conn.send(b\"\\r\\n\")\n                    low_conn.send(b\"0\\r\\n\\r\\n\")\n\n                    # Receive the response from the server\n                    r = low_conn.getresponse()\n\n                    resp = HTTPResponse.from_httplib(\n                        r,\n                        pool=conn,\n                        connection=low_conn,\n                        preload_content=False,\n                        decode_content=False,\n                    )\n                except Exception:\n                    # If we hit any problems here, clean up the connection.\n                    # Then, raise so that we can handle the actual exception.\n                    low_conn.close()\n                    raise\n\n        except (ProtocolError, OSError) as err:\n            raise ConnectionError(err, request=request)\n\n        except MaxRetryError as e:\n            if isinstance(e.reason, ConnectTimeoutError):\n                # TODO: Remove this in 3.0.0: see #2811\n                if not isinstance(e.reason, NewConnectionError):\n                    raise ConnectTimeout(e, request=request)\n\n            if isinstance(e.reason, ResponseError):\n                raise RetryError(e, request=request)\n\n            if isinstance(e.reason, _ProxyError):\n                raise ProxyError(e, request=request)\n\n            if isinstance(e.reason, _SSLError):\n                # This branch is for urllib3 v1.22 and later.\n                raise SSLError(e, request=request)\n\n            raise ConnectionError(e, request=request)\n\n        except ClosedPoolError as e:\n            raise ConnectionError(e, request=request)\n\n        except _ProxyError as e:\n            raise ProxyError(e)\n\n        except (_SSLError, _HTTPError) as e:\n            if isinstance(e, _SSLError):\n                # This branch is for urllib3 versions earlier than v1.22\n                raise SSLError(e, request=request)\n            elif isinstance(e, ReadTimeoutError):\n                raise ReadTimeout(e, request=request)\n            elif isinstance(e, _InvalidHeader):\n                raise InvalidHeader(e, request=request)\n            else:\n                raise\n\n        return self.build_response(request, resp)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/api.py",
    "content": "\"\"\"\nrequests.api\n~~~~~~~~~~~~\n\nThis module implements the Requests API.\n\n:copyright: (c) 2012 by Kenneth Reitz.\n:license: Apache2, see LICENSE for more details.\n\"\"\"\n\nfrom . import sessions\n\n\ndef request(method, url, **kwargs):\n    \"\"\"Constructs and sends a :class:`Request <Request>`.\n\n    :param method: method for the new :class:`Request` object: ``GET``, ``OPTIONS``, ``HEAD``, ``POST``, ``PUT``, ``PATCH``, or ``DELETE``.\n    :param url: URL for the new :class:`Request` object.\n    :param params: (optional) Dictionary, list of tuples or bytes to send\n        in the query string for the :class:`Request`.\n    :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n        object to send in the body of the :class:`Request`.\n    :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n    :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.\n    :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.\n    :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.\n        ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``\n        or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string\n        defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers\n        to add for the file.\n    :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.\n    :param timeout: (optional) How many seconds to wait for the server to send data\n        before giving up, as a float, or a :ref:`(connect timeout, read\n        timeout) <timeouts>` tuple.\n    :type timeout: float or tuple\n    :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.\n    :type allow_redirects: bool\n    :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.\n    :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``.\n    :param stream: (optional) if ``False``, the response content will be immediately downloaded.\n    :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.request('GET', 'https://httpbin.org/get')\n      >>> req\n      <Response [200]>\n    \"\"\"\n\n    # By using the 'with' statement we are sure the session is closed, thus we\n    # avoid leaving sockets open which can trigger a ResourceWarning in some\n    # cases, and look like a memory leak in others.\n    with sessions.Session() as session:\n        return session.request(method=method, url=url, **kwargs)\n\n\ndef get(url, params=None, **kwargs):\n    r\"\"\"Sends a GET request.\n\n    :param url: URL for the new :class:`Request` object.\n    :param params: (optional) Dictionary, list of tuples or bytes to send\n        in the query string for the :class:`Request`.\n    :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n    \"\"\"\n\n    return request(\"get\", url, params=params, **kwargs)\n\n\ndef options(url, **kwargs):\n    r\"\"\"Sends an OPTIONS request.\n\n    :param url: URL for the new :class:`Request` object.\n    :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n    \"\"\"\n\n    return request(\"options\", url, **kwargs)\n\n\ndef head(url, **kwargs):\n    r\"\"\"Sends a HEAD request.\n\n    :param url: URL for the new :class:`Request` object.\n    :param \\*\\*kwargs: Optional arguments that ``request`` takes. If\n        `allow_redirects` is not provided, it will be set to `False` (as\n        opposed to the default :meth:`request` behavior).\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n    \"\"\"\n\n    kwargs.setdefault(\"allow_redirects\", False)\n    return request(\"head\", url, **kwargs)\n\n\ndef post(url, data=None, json=None, **kwargs):\n    r\"\"\"Sends a POST request.\n\n    :param url: URL for the new :class:`Request` object.\n    :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n        object to send in the body of the :class:`Request`.\n    :param json: (optional) json data to send in the body of the :class:`Request`.\n    :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n    \"\"\"\n\n    return request(\"post\", url, data=data, json=json, **kwargs)\n\n\ndef put(url, data=None, **kwargs):\n    r\"\"\"Sends a PUT request.\n\n    :param url: URL for the new :class:`Request` object.\n    :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n        object to send in the body of the :class:`Request`.\n    :param json: (optional) json data to send in the body of the :class:`Request`.\n    :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n    \"\"\"\n\n    return request(\"put\", url, data=data, **kwargs)\n\n\ndef patch(url, data=None, **kwargs):\n    r\"\"\"Sends a PATCH request.\n\n    :param url: URL for the new :class:`Request` object.\n    :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n        object to send in the body of the :class:`Request`.\n    :param json: (optional) json data to send in the body of the :class:`Request`.\n    :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n    \"\"\"\n\n    return request(\"patch\", url, data=data, **kwargs)\n\n\ndef delete(url, **kwargs):\n    r\"\"\"Sends a DELETE request.\n\n    :param url: URL for the new :class:`Request` object.\n    :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n    :return: :class:`Response <Response>` object\n    :rtype: requests.Response\n    \"\"\"\n\n    return request(\"delete\", url, **kwargs)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/auth.py",
    "content": "\"\"\"\nrequests.auth\n~~~~~~~~~~~~~\n\nThis module contains the authentication handlers for Requests.\n\"\"\"\n\nimport hashlib\nimport os\nimport re\nimport threading\nimport time\nimport warnings\nfrom base64 import b64encode\n\nfrom ._internal_utils import to_native_string\nfrom .compat import basestring, str, urlparse\nfrom .cookies import extract_cookies_to_jar\nfrom .utils import parse_dict_header\n\nCONTENT_TYPE_FORM_URLENCODED = \"application/x-www-form-urlencoded\"\nCONTENT_TYPE_MULTI_PART = \"multipart/form-data\"\n\n\ndef _basic_auth_str(username, password):\n    \"\"\"Returns a Basic Auth string.\"\"\"\n\n    # \"I want us to put a big-ol' comment on top of it that\n    # says that this behaviour is dumb but we need to preserve\n    # it because people are relying on it.\"\n    #    - Lukasa\n    #\n    # These are here solely to maintain backwards compatibility\n    # for things like ints. This will be removed in 3.0.0.\n    if not isinstance(username, basestring):\n        warnings.warn(\n            \"Non-string usernames will no longer be supported in Requests \"\n            \"3.0.0. Please convert the object you've passed in ({!r}) to \"\n            \"a string or bytes object in the near future to avoid \"\n            \"problems.\".format(username),\n            category=DeprecationWarning,\n        )\n        username = str(username)\n\n    if not isinstance(password, basestring):\n        warnings.warn(\n            \"Non-string passwords will no longer be supported in Requests \"\n            \"3.0.0. Please convert the object you've passed in ({!r}) to \"\n            \"a string or bytes object in the near future to avoid \"\n            \"problems.\".format(type(password)),\n            category=DeprecationWarning,\n        )\n        password = str(password)\n    # -- End Removal --\n\n    if isinstance(username, str):\n        username = username.encode(\"latin1\")\n\n    if isinstance(password, str):\n        password = password.encode(\"latin1\")\n\n    authstr = \"Basic \" + to_native_string(\n        b64encode(b\":\".join((username, password))).strip()\n    )\n\n    return authstr\n\n\nclass AuthBase:\n    \"\"\"Base class that all auth implementations derive from\"\"\"\n\n    def __call__(self, r):\n        raise NotImplementedError(\"Auth hooks must be callable.\")\n\n\nclass HTTPBasicAuth(AuthBase):\n    \"\"\"Attaches HTTP Basic Authentication to the given Request object.\"\"\"\n\n    def __init__(self, username, password):\n        self.username = username\n        self.password = password\n\n    def __eq__(self, other):\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other):\n        return not self == other\n\n    def __call__(self, r):\n        r.headers[\"Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n\n\nclass HTTPProxyAuth(HTTPBasicAuth):\n    \"\"\"Attaches HTTP Proxy Authentication to a given Request object.\"\"\"\n\n    def __call__(self, r):\n        r.headers[\"Proxy-Authorization\"] = _basic_auth_str(self.username, self.password)\n        return r\n\n\nclass HTTPDigestAuth(AuthBase):\n    \"\"\"Attaches HTTP Digest Authentication to the given Request object.\"\"\"\n\n    def __init__(self, username, password):\n        self.username = username\n        self.password = password\n        # Keep state in per-thread local storage\n        self._thread_local = threading.local()\n\n    def init_per_thread_state(self):\n        # Ensure state is initialized just once per-thread\n        if not hasattr(self._thread_local, \"init\"):\n            self._thread_local.init = True\n            self._thread_local.last_nonce = \"\"\n            self._thread_local.nonce_count = 0\n            self._thread_local.chal = {}\n            self._thread_local.pos = None\n            self._thread_local.num_401_calls = None\n\n    def build_digest_header(self, method, url):\n        \"\"\"\n        :rtype: str\n        \"\"\"\n\n        realm = self._thread_local.chal[\"realm\"]\n        nonce = self._thread_local.chal[\"nonce\"]\n        qop = self._thread_local.chal.get(\"qop\")\n        algorithm = self._thread_local.chal.get(\"algorithm\")\n        opaque = self._thread_local.chal.get(\"opaque\")\n        hash_utf8 = None\n\n        if algorithm is None:\n            _algorithm = \"MD5\"\n        else:\n            _algorithm = algorithm.upper()\n        # lambdas assume digest modules are imported at the top level\n        if _algorithm == \"MD5\" or _algorithm == \"MD5-SESS\":\n\n            def md5_utf8(x):\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.md5(x).hexdigest()\n\n            hash_utf8 = md5_utf8\n        elif _algorithm == \"SHA\":\n\n            def sha_utf8(x):\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha1(x).hexdigest()\n\n            hash_utf8 = sha_utf8\n        elif _algorithm == \"SHA-256\":\n\n            def sha256_utf8(x):\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha256(x).hexdigest()\n\n            hash_utf8 = sha256_utf8\n        elif _algorithm == \"SHA-512\":\n\n            def sha512_utf8(x):\n                if isinstance(x, str):\n                    x = x.encode(\"utf-8\")\n                return hashlib.sha512(x).hexdigest()\n\n            hash_utf8 = sha512_utf8\n\n        KD = lambda s, d: hash_utf8(f\"{s}:{d}\")  # noqa:E731\n\n        if hash_utf8 is None:\n            return None\n\n        # XXX not implemented yet\n        entdig = None\n        p_parsed = urlparse(url)\n        #: path is request-uri defined in RFC 2616 which should not be empty\n        path = p_parsed.path or \"/\"\n        if p_parsed.query:\n            path += f\"?{p_parsed.query}\"\n\n        A1 = f\"{self.username}:{realm}:{self.password}\"\n        A2 = f\"{method}:{path}\"\n\n        HA1 = hash_utf8(A1)\n        HA2 = hash_utf8(A2)\n\n        if nonce == self._thread_local.last_nonce:\n            self._thread_local.nonce_count += 1\n        else:\n            self._thread_local.nonce_count = 1\n        ncvalue = f\"{self._thread_local.nonce_count:08x}\"\n        s = str(self._thread_local.nonce_count).encode(\"utf-8\")\n        s += nonce.encode(\"utf-8\")\n        s += time.ctime().encode(\"utf-8\")\n        s += os.urandom(8)\n\n        cnonce = hashlib.sha1(s).hexdigest()[:16]\n        if _algorithm == \"MD5-SESS\":\n            HA1 = hash_utf8(f\"{HA1}:{nonce}:{cnonce}\")\n\n        if not qop:\n            respdig = KD(HA1, f\"{nonce}:{HA2}\")\n        elif qop == \"auth\" or \"auth\" in qop.split(\",\"):\n            noncebit = f\"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}\"\n            respdig = KD(HA1, noncebit)\n        else:\n            # XXX handle auth-int.\n            return None\n\n        self._thread_local.last_nonce = nonce\n\n        # XXX should the partial digests be encoded too?\n        base = (\n            f'username=\"{self.username}\", realm=\"{realm}\", nonce=\"{nonce}\", '\n            f'uri=\"{path}\", response=\"{respdig}\"'\n        )\n        if opaque:\n            base += f', opaque=\"{opaque}\"'\n        if algorithm:\n            base += f', algorithm=\"{algorithm}\"'\n        if entdig:\n            base += f', digest=\"{entdig}\"'\n        if qop:\n            base += f', qop=\"auth\", nc={ncvalue}, cnonce=\"{cnonce}\"'\n\n        return f\"Digest {base}\"\n\n    def handle_redirect(self, r, **kwargs):\n        \"\"\"Reset num_401_calls counter on redirects.\"\"\"\n        if r.is_redirect:\n            self._thread_local.num_401_calls = 1\n\n    def handle_401(self, r, **kwargs):\n        \"\"\"\n        Takes the given response and tries digest-auth, if needed.\n\n        :rtype: requests.Response\n        \"\"\"\n\n        # If response is not 4xx, do not auth\n        # See https://github.com/psf/requests/issues/3772\n        if not 400 <= r.status_code < 500:\n            self._thread_local.num_401_calls = 1\n            return r\n\n        if self._thread_local.pos is not None:\n            # Rewind the file position indicator of the body to where\n            # it was to resend the request.\n            r.request.body.seek(self._thread_local.pos)\n        s_auth = r.headers.get(\"www-authenticate\", \"\")\n\n        if \"digest\" in s_auth.lower() and self._thread_local.num_401_calls < 2:\n\n            self._thread_local.num_401_calls += 1\n            pat = re.compile(r\"digest \", flags=re.IGNORECASE)\n            self._thread_local.chal = parse_dict_header(pat.sub(\"\", s_auth, count=1))\n\n            # Consume content and release the original connection\n            # to allow our new request to reuse the same one.\n            r.content\n            r.close()\n            prep = r.request.copy()\n            extract_cookies_to_jar(prep._cookies, r.request, r.raw)\n            prep.prepare_cookies(prep._cookies)\n\n            prep.headers[\"Authorization\"] = self.build_digest_header(\n                prep.method, prep.url\n            )\n            _r = r.connection.send(prep, **kwargs)\n            _r.history.append(r)\n            _r.request = prep\n\n            return _r\n\n        self._thread_local.num_401_calls = 1\n        return r\n\n    def __call__(self, r):\n        # Initialize per-thread state, if needed\n        self.init_per_thread_state()\n        # If we have a saved nonce, skip the 401\n        if self._thread_local.last_nonce:\n            r.headers[\"Authorization\"] = self.build_digest_header(r.method, r.url)\n        try:\n            self._thread_local.pos = r.body.tell()\n        except AttributeError:\n            # In the case of HTTPDigestAuth being reused and the body of\n            # the previous request was a file-like object, pos has the\n            # file position of the previous body. Ensure it's set to\n            # None.\n            self._thread_local.pos = None\n        r.register_hook(\"response\", self.handle_401)\n        r.register_hook(\"response\", self.handle_redirect)\n        self._thread_local.num_401_calls = 1\n\n        return r\n\n    def __eq__(self, other):\n        return all(\n            [\n                self.username == getattr(other, \"username\", None),\n                self.password == getattr(other, \"password\", None),\n            ]\n        )\n\n    def __ne__(self, other):\n        return not self == other\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/certs.py",
    "content": "#!/usr/bin/env python\n\n\"\"\"\nrequests.certs\n~~~~~~~~~~~~~~\n\nThis module returns the preferred default CA certificate bundle. There is\nonly one — the one from the certifi package.\n\nIf you are packaging Requests, e.g., for a Linux distribution or a managed\nenvironment, you can change the definition of where() to return a separately\npackaged CA bundle.\n\"\"\"\n\nimport os\n\nif \"_PIP_STANDALONE_CERT\" not in os.environ:\n    from pip._vendor.certifi import where\nelse:\n    def where():\n        return os.environ[\"_PIP_STANDALONE_CERT\"]\n\nif __name__ == \"__main__\":\n    print(where())\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/compat.py",
    "content": "\"\"\"\nrequests.compat\n~~~~~~~~~~~~~~~\n\nThis module previously handled import compatibility issues\nbetween Python 2 and Python 3. It remains for backwards\ncompatibility until the next major version.\n\"\"\"\n\nfrom pip._vendor import chardet\n\nimport sys\n\n# -------\n# Pythons\n# -------\n\n# Syntax sugar.\n_ver = sys.version_info\n\n#: Python 2.x?\nis_py2 = _ver[0] == 2\n\n#: Python 3.x?\nis_py3 = _ver[0] == 3\n\n# Note: We've patched out simplejson support in pip because it prevents\n#       upgrading simplejson on Windows.\nimport json\nfrom json import JSONDecodeError\n\n# Keep OrderedDict for backwards compatibility.\nfrom collections import OrderedDict\nfrom collections.abc import Callable, Mapping, MutableMapping\nfrom http import cookiejar as cookielib\nfrom http.cookies import Morsel\nfrom io import StringIO\n\n# --------------\n# Legacy Imports\n# --------------\nfrom urllib.parse import (\n    quote,\n    quote_plus,\n    unquote,\n    unquote_plus,\n    urldefrag,\n    urlencode,\n    urljoin,\n    urlparse,\n    urlsplit,\n    urlunparse,\n)\nfrom urllib.request import (\n    getproxies,\n    getproxies_environment,\n    parse_http_list,\n    proxy_bypass,\n    proxy_bypass_environment,\n)\n\nbuiltin_str = str\nstr = str\nbytes = bytes\nbasestring = (str, bytes)\nnumeric_types = (int, float)\ninteger_types = (int,)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/cookies.py",
    "content": "\"\"\"\nrequests.cookies\n~~~~~~~~~~~~~~~~\n\nCompatibility code to be able to use `cookielib.CookieJar` with requests.\n\nrequests.utils imports from here, so be careful with imports.\n\"\"\"\n\nimport calendar\nimport copy\nimport time\n\nfrom ._internal_utils import to_native_string\nfrom .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse\n\ntry:\n    import threading\nexcept ImportError:\n    import dummy_threading as threading\n\n\nclass MockRequest:\n    \"\"\"Wraps a `requests.Request` to mimic a `urllib2.Request`.\n\n    The code in `cookielib.CookieJar` expects this interface in order to correctly\n    manage cookie policies, i.e., determine whether a cookie can be set, given the\n    domains of the request and the cookie.\n\n    The original request object is read-only. The client is responsible for collecting\n    the new headers via `get_new_headers()` and interpreting them appropriately. You\n    probably want `get_cookie_header`, defined below.\n    \"\"\"\n\n    def __init__(self, request):\n        self._r = request\n        self._new_headers = {}\n        self.type = urlparse(self._r.url).scheme\n\n    def get_type(self):\n        return self.type\n\n    def get_host(self):\n        return urlparse(self._r.url).netloc\n\n    def get_origin_req_host(self):\n        return self.get_host()\n\n    def get_full_url(self):\n        # Only return the response's URL if the user hadn't set the Host\n        # header\n        if not self._r.headers.get(\"Host\"):\n            return self._r.url\n        # If they did set it, retrieve it and reconstruct the expected domain\n        host = to_native_string(self._r.headers[\"Host\"], encoding=\"utf-8\")\n        parsed = urlparse(self._r.url)\n        # Reconstruct the URL as we expect it\n        return urlunparse(\n            [\n                parsed.scheme,\n                host,\n                parsed.path,\n                parsed.params,\n                parsed.query,\n                parsed.fragment,\n            ]\n        )\n\n    def is_unverifiable(self):\n        return True\n\n    def has_header(self, name):\n        return name in self._r.headers or name in self._new_headers\n\n    def get_header(self, name, default=None):\n        return self._r.headers.get(name, self._new_headers.get(name, default))\n\n    def add_header(self, key, val):\n        \"\"\"cookielib has no legitimate use for this method; add it back if you find one.\"\"\"\n        raise NotImplementedError(\n            \"Cookie headers should be added with add_unredirected_header()\"\n        )\n\n    def add_unredirected_header(self, name, value):\n        self._new_headers[name] = value\n\n    def get_new_headers(self):\n        return self._new_headers\n\n    @property\n    def unverifiable(self):\n        return self.is_unverifiable()\n\n    @property\n    def origin_req_host(self):\n        return self.get_origin_req_host()\n\n    @property\n    def host(self):\n        return self.get_host()\n\n\nclass MockResponse:\n    \"\"\"Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.\n\n    ...what? Basically, expose the parsed HTTP headers from the server response\n    the way `cookielib` expects to see them.\n    \"\"\"\n\n    def __init__(self, headers):\n        \"\"\"Make a MockResponse for `cookielib` to read.\n\n        :param headers: a httplib.HTTPMessage or analogous carrying the headers\n        \"\"\"\n        self._headers = headers\n\n    def info(self):\n        return self._headers\n\n    def getheaders(self, name):\n        self._headers.getheaders(name)\n\n\ndef extract_cookies_to_jar(jar, request, response):\n    \"\"\"Extract the cookies from the response into a CookieJar.\n\n    :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)\n    :param request: our own requests.Request object\n    :param response: urllib3.HTTPResponse object\n    \"\"\"\n    if not (hasattr(response, \"_original_response\") and response._original_response):\n        return\n    # the _original_response field is the wrapped httplib.HTTPResponse object,\n    req = MockRequest(request)\n    # pull out the HTTPMessage with the headers and put it in the mock:\n    res = MockResponse(response._original_response.msg)\n    jar.extract_cookies(res, req)\n\n\ndef get_cookie_header(jar, request):\n    \"\"\"\n    Produce an appropriate Cookie header string to be sent with `request`, or None.\n\n    :rtype: str\n    \"\"\"\n    r = MockRequest(request)\n    jar.add_cookie_header(r)\n    return r.get_new_headers().get(\"Cookie\")\n\n\ndef remove_cookie_by_name(cookiejar, name, domain=None, path=None):\n    \"\"\"Unsets a cookie by name, by default over all domains and paths.\n\n    Wraps CookieJar.clear(), is O(n).\n    \"\"\"\n    clearables = []\n    for cookie in cookiejar:\n        if cookie.name != name:\n            continue\n        if domain is not None and domain != cookie.domain:\n            continue\n        if path is not None and path != cookie.path:\n            continue\n        clearables.append((cookie.domain, cookie.path, cookie.name))\n\n    for domain, path, name in clearables:\n        cookiejar.clear(domain, path, name)\n\n\nclass CookieConflictError(RuntimeError):\n    \"\"\"There are two cookies that meet the criteria specified in the cookie jar.\n    Use .get and .set and include domain and path args in order to be more specific.\n    \"\"\"\n\n\nclass RequestsCookieJar(cookielib.CookieJar, MutableMapping):\n    \"\"\"Compatibility class; is a cookielib.CookieJar, but exposes a dict\n    interface.\n\n    This is the CookieJar we create by default for requests and sessions that\n    don't specify one, since some clients may expect response.cookies and\n    session.cookies to support dict operations.\n\n    Requests does not use the dict interface internally; it's just for\n    compatibility with external client code. All requests code should work\n    out of the box with externally provided instances of ``CookieJar``, e.g.\n    ``LWPCookieJar`` and ``FileCookieJar``.\n\n    Unlike a regular CookieJar, this class is pickleable.\n\n    .. warning:: dictionary operations that are normally O(1) may be O(n).\n    \"\"\"\n\n    def get(self, name, default=None, domain=None, path=None):\n        \"\"\"Dict-like get() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        try:\n            return self._find_no_duplicates(name, domain, path)\n        except KeyError:\n            return default\n\n    def set(self, name, value, **kwargs):\n        \"\"\"Dict-like set() that also supports optional domain and path args in\n        order to resolve naming collisions from using one cookie jar over\n        multiple domains.\n        \"\"\"\n        # support client code that unsets cookies by assignment of a None value:\n        if value is None:\n            remove_cookie_by_name(\n                self, name, domain=kwargs.get(\"domain\"), path=kwargs.get(\"path\")\n            )\n            return\n\n        if isinstance(value, Morsel):\n            c = morsel_to_cookie(value)\n        else:\n            c = create_cookie(name, value, **kwargs)\n        self.set_cookie(c)\n        return c\n\n    def iterkeys(self):\n        \"\"\"Dict-like iterkeys() that returns an iterator of names of cookies\n        from the jar.\n\n        .. seealso:: itervalues() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name\n\n    def keys(self):\n        \"\"\"Dict-like keys() that returns a list of names of cookies from the\n        jar.\n\n        .. seealso:: values() and items().\n        \"\"\"\n        return list(self.iterkeys())\n\n    def itervalues(self):\n        \"\"\"Dict-like itervalues() that returns an iterator of values of cookies\n        from the jar.\n\n        .. seealso:: iterkeys() and iteritems().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.value\n\n    def values(self):\n        \"\"\"Dict-like values() that returns a list of values of cookies from the\n        jar.\n\n        .. seealso:: keys() and items().\n        \"\"\"\n        return list(self.itervalues())\n\n    def iteritems(self):\n        \"\"\"Dict-like iteritems() that returns an iterator of name-value tuples\n        from the jar.\n\n        .. seealso:: iterkeys() and itervalues().\n        \"\"\"\n        for cookie in iter(self):\n            yield cookie.name, cookie.value\n\n    def items(self):\n        \"\"\"Dict-like items() that returns a list of name-value tuples from the\n        jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a\n        vanilla python dict of key value pairs.\n\n        .. seealso:: keys() and values().\n        \"\"\"\n        return list(self.iteritems())\n\n    def list_domains(self):\n        \"\"\"Utility method to list all the domains in the jar.\"\"\"\n        domains = []\n        for cookie in iter(self):\n            if cookie.domain not in domains:\n                domains.append(cookie.domain)\n        return domains\n\n    def list_paths(self):\n        \"\"\"Utility method to list all the paths in the jar.\"\"\"\n        paths = []\n        for cookie in iter(self):\n            if cookie.path not in paths:\n                paths.append(cookie.path)\n        return paths\n\n    def multiple_domains(self):\n        \"\"\"Returns True if there are multiple domains in the jar.\n        Returns False otherwise.\n\n        :rtype: bool\n        \"\"\"\n        domains = []\n        for cookie in iter(self):\n            if cookie.domain is not None and cookie.domain in domains:\n                return True\n            domains.append(cookie.domain)\n        return False  # there is only one domain in jar\n\n    def get_dict(self, domain=None, path=None):\n        \"\"\"Takes as an argument an optional domain and path and returns a plain\n        old Python dict of name-value pairs of cookies that meet the\n        requirements.\n\n        :rtype: dict\n        \"\"\"\n        dictionary = {}\n        for cookie in iter(self):\n            if (domain is None or cookie.domain == domain) and (\n                path is None or cookie.path == path\n            ):\n                dictionary[cookie.name] = cookie.value\n        return dictionary\n\n    def __contains__(self, name):\n        try:\n            return super().__contains__(name)\n        except CookieConflictError:\n            return True\n\n    def __getitem__(self, name):\n        \"\"\"Dict-like __getitem__() for compatibility with client code. Throws\n        exception if there are more than one cookie with name. In that case,\n        use the more explicit get() method instead.\n\n        .. warning:: operation is O(n), not O(1).\n        \"\"\"\n        return self._find_no_duplicates(name)\n\n    def __setitem__(self, name, value):\n        \"\"\"Dict-like __setitem__ for compatibility with client code. Throws\n        exception if there is already a cookie of that name in the jar. In that\n        case, use the more explicit set() method instead.\n        \"\"\"\n        self.set(name, value)\n\n    def __delitem__(self, name):\n        \"\"\"Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s\n        ``remove_cookie_by_name()``.\n        \"\"\"\n        remove_cookie_by_name(self, name)\n\n    def set_cookie(self, cookie, *args, **kwargs):\n        if (\n            hasattr(cookie.value, \"startswith\")\n            and cookie.value.startswith('\"')\n            and cookie.value.endswith('\"')\n        ):\n            cookie.value = cookie.value.replace('\\\\\"', \"\")\n        return super().set_cookie(cookie, *args, **kwargs)\n\n    def update(self, other):\n        \"\"\"Updates this jar with cookies from another CookieJar or dict-like\"\"\"\n        if isinstance(other, cookielib.CookieJar):\n            for cookie in other:\n                self.set_cookie(copy.copy(cookie))\n        else:\n            super().update(other)\n\n    def _find(self, name, domain=None, path=None):\n        \"\"\"Requests uses this method internally to get cookie values.\n\n        If there are conflicting cookies, _find arbitrarily chooses one.\n        See _find_no_duplicates if you want an exception thrown if there are\n        conflicting cookies.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :return: cookie.value\n        \"\"\"\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        return cookie.value\n\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def _find_no_duplicates(self, name, domain=None, path=None):\n        \"\"\"Both ``__get_item__`` and ``get`` call this function: it's never\n        used elsewhere in Requests.\n\n        :param name: a string containing name of cookie\n        :param domain: (optional) string containing domain of cookie\n        :param path: (optional) string containing path of cookie\n        :raises KeyError: if cookie is not found\n        :raises CookieConflictError: if there are multiple cookies\n            that match name and optionally domain and path\n        :return: cookie.value\n        \"\"\"\n        toReturn = None\n        for cookie in iter(self):\n            if cookie.name == name:\n                if domain is None or cookie.domain == domain:\n                    if path is None or cookie.path == path:\n                        if toReturn is not None:\n                            # if there are multiple cookies that meet passed in criteria\n                            raise CookieConflictError(\n                                f\"There are multiple cookies with name, {name!r}\"\n                            )\n                        # we will eventually return this as long as no cookie conflict\n                        toReturn = cookie.value\n\n        if toReturn:\n            return toReturn\n        raise KeyError(f\"name={name!r}, domain={domain!r}, path={path!r}\")\n\n    def __getstate__(self):\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        state = self.__dict__.copy()\n        # remove the unpickleable RLock object\n        state.pop(\"_cookies_lock\")\n        return state\n\n    def __setstate__(self, state):\n        \"\"\"Unlike a normal CookieJar, this class is pickleable.\"\"\"\n        self.__dict__.update(state)\n        if \"_cookies_lock\" not in self.__dict__:\n            self._cookies_lock = threading.RLock()\n\n    def copy(self):\n        \"\"\"Return a copy of this RequestsCookieJar.\"\"\"\n        new_cj = RequestsCookieJar()\n        new_cj.set_policy(self.get_policy())\n        new_cj.update(self)\n        return new_cj\n\n    def get_policy(self):\n        \"\"\"Return the CookiePolicy instance used.\"\"\"\n        return self._policy\n\n\ndef _copy_cookie_jar(jar):\n    if jar is None:\n        return None\n\n    if hasattr(jar, \"copy\"):\n        # We're dealing with an instance of RequestsCookieJar\n        return jar.copy()\n    # We're dealing with a generic CookieJar instance\n    new_jar = copy.copy(jar)\n    new_jar.clear()\n    for cookie in jar:\n        new_jar.set_cookie(copy.copy(cookie))\n    return new_jar\n\n\ndef create_cookie(name, value, **kwargs):\n    \"\"\"Make a cookie from underspecified parameters.\n\n    By default, the pair of `name` and `value` will be set for the domain ''\n    and sent on every request (this is sometimes called a \"supercookie\").\n    \"\"\"\n    result = {\n        \"version\": 0,\n        \"name\": name,\n        \"value\": value,\n        \"port\": None,\n        \"domain\": \"\",\n        \"path\": \"/\",\n        \"secure\": False,\n        \"expires\": None,\n        \"discard\": True,\n        \"comment\": None,\n        \"comment_url\": None,\n        \"rest\": {\"HttpOnly\": None},\n        \"rfc2109\": False,\n    }\n\n    badargs = set(kwargs) - set(result)\n    if badargs:\n        raise TypeError(\n            f\"create_cookie() got unexpected keyword arguments: {list(badargs)}\"\n        )\n\n    result.update(kwargs)\n    result[\"port_specified\"] = bool(result[\"port\"])\n    result[\"domain_specified\"] = bool(result[\"domain\"])\n    result[\"domain_initial_dot\"] = result[\"domain\"].startswith(\".\")\n    result[\"path_specified\"] = bool(result[\"path\"])\n\n    return cookielib.Cookie(**result)\n\n\ndef morsel_to_cookie(morsel):\n    \"\"\"Convert a Morsel object into a Cookie containing the one k/v pair.\"\"\"\n\n    expires = None\n    if morsel[\"max-age\"]:\n        try:\n            expires = int(time.time() + int(morsel[\"max-age\"]))\n        except ValueError:\n            raise TypeError(f\"max-age: {morsel['max-age']} must be integer\")\n    elif morsel[\"expires\"]:\n        time_template = \"%a, %d-%b-%Y %H:%M:%S GMT\"\n        expires = calendar.timegm(time.strptime(morsel[\"expires\"], time_template))\n    return create_cookie(\n        comment=morsel[\"comment\"],\n        comment_url=bool(morsel[\"comment\"]),\n        discard=False,\n        domain=morsel[\"domain\"],\n        expires=expires,\n        name=morsel.key,\n        path=morsel[\"path\"],\n        port=None,\n        rest={\"HttpOnly\": morsel[\"httponly\"]},\n        rfc2109=False,\n        secure=bool(morsel[\"secure\"]),\n        value=morsel.value,\n        version=morsel[\"version\"] or 0,\n    )\n\n\ndef cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):\n    \"\"\"Returns a CookieJar from a key/value dictionary.\n\n    :param cookie_dict: Dict of key/values to insert into CookieJar.\n    :param cookiejar: (optional) A cookiejar to add the cookies to.\n    :param overwrite: (optional) If False, will not replace cookies\n        already in the jar with new ones.\n    :rtype: CookieJar\n    \"\"\"\n    if cookiejar is None:\n        cookiejar = RequestsCookieJar()\n\n    if cookie_dict is not None:\n        names_from_jar = [cookie.name for cookie in cookiejar]\n        for name in cookie_dict:\n            if overwrite or (name not in names_from_jar):\n                cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))\n\n    return cookiejar\n\n\ndef merge_cookies(cookiejar, cookies):\n    \"\"\"Add cookies to cookiejar and returns a merged CookieJar.\n\n    :param cookiejar: CookieJar object to add the cookies to.\n    :param cookies: Dictionary or CookieJar object to be added.\n    :rtype: CookieJar\n    \"\"\"\n    if not isinstance(cookiejar, cookielib.CookieJar):\n        raise ValueError(\"You can only merge into CookieJar\")\n\n    if isinstance(cookies, dict):\n        cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False)\n    elif isinstance(cookies, cookielib.CookieJar):\n        try:\n            cookiejar.update(cookies)\n        except AttributeError:\n            for cookie_in_jar in cookies:\n                cookiejar.set_cookie(cookie_in_jar)\n\n    return cookiejar\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/exceptions.py",
    "content": "\"\"\"\nrequests.exceptions\n~~~~~~~~~~~~~~~~~~~\n\nThis module contains the set of Requests' exceptions.\n\"\"\"\nfrom pip._vendor.urllib3.exceptions import HTTPError as BaseHTTPError\n\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\n\nclass RequestException(IOError):\n    \"\"\"There was an ambiguous exception that occurred while handling your\n    request.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"Initialize RequestException with `request` and `response` objects.\"\"\"\n        response = kwargs.pop(\"response\", None)\n        self.response = response\n        self.request = kwargs.pop(\"request\", None)\n        if response is not None and not self.request and hasattr(response, \"request\"):\n            self.request = self.response.request\n        super().__init__(*args, **kwargs)\n\n\nclass InvalidJSONError(RequestException):\n    \"\"\"A JSON error occurred.\"\"\"\n\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n    \"\"\"Couldn't decode the text into json\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"\n        Construct the JSONDecodeError instance first with all\n        args. Then use it's args to construct the IOError so that\n        the json specific args aren't used as IOError specific args\n        and the error message from JSONDecodeError is preserved.\n        \"\"\"\n        CompatJSONDecodeError.__init__(self, *args)\n        InvalidJSONError.__init__(self, *self.args, **kwargs)\n\n\nclass HTTPError(RequestException):\n    \"\"\"An HTTP error occurred.\"\"\"\n\n\nclass ConnectionError(RequestException):\n    \"\"\"A Connection error occurred.\"\"\"\n\n\nclass ProxyError(ConnectionError):\n    \"\"\"A proxy error occurred.\"\"\"\n\n\nclass SSLError(ConnectionError):\n    \"\"\"An SSL error occurred.\"\"\"\n\n\nclass Timeout(RequestException):\n    \"\"\"The request timed out.\n\n    Catching this error will catch both\n    :exc:`~requests.exceptions.ConnectTimeout` and\n    :exc:`~requests.exceptions.ReadTimeout` errors.\n    \"\"\"\n\n\nclass ConnectTimeout(ConnectionError, Timeout):\n    \"\"\"The request timed out while trying to connect to the remote server.\n\n    Requests that produced this error are safe to retry.\n    \"\"\"\n\n\nclass ReadTimeout(Timeout):\n    \"\"\"The server did not send any data in the allotted amount of time.\"\"\"\n\n\nclass URLRequired(RequestException):\n    \"\"\"A valid URL is required to make a request.\"\"\"\n\n\nclass TooManyRedirects(RequestException):\n    \"\"\"Too many redirects.\"\"\"\n\n\nclass MissingSchema(RequestException, ValueError):\n    \"\"\"The URL scheme (e.g. http or https) is missing.\"\"\"\n\n\nclass InvalidSchema(RequestException, ValueError):\n    \"\"\"The URL scheme provided is either invalid or unsupported.\"\"\"\n\n\nclass InvalidURL(RequestException, ValueError):\n    \"\"\"The URL provided was somehow invalid.\"\"\"\n\n\nclass InvalidHeader(RequestException, ValueError):\n    \"\"\"The header value provided was somehow invalid.\"\"\"\n\n\nclass InvalidProxyURL(InvalidURL):\n    \"\"\"The proxy URL provided is invalid.\"\"\"\n\n\nclass ChunkedEncodingError(RequestException):\n    \"\"\"The server declared chunked encoding but sent an invalid chunk.\"\"\"\n\n\nclass ContentDecodingError(RequestException, BaseHTTPError):\n    \"\"\"Failed to decode response content.\"\"\"\n\n\nclass StreamConsumedError(RequestException, TypeError):\n    \"\"\"The content for this response was already consumed.\"\"\"\n\n\nclass RetryError(RequestException):\n    \"\"\"Custom retries logic failed\"\"\"\n\n\nclass UnrewindableBodyError(RequestException):\n    \"\"\"Requests encountered an error when trying to rewind a body.\"\"\"\n\n\n# Warnings\n\n\nclass RequestsWarning(Warning):\n    \"\"\"Base warning for Requests.\"\"\"\n\n\nclass FileModeWarning(RequestsWarning, DeprecationWarning):\n    \"\"\"A file was opened in text mode, but Requests determined its binary length.\"\"\"\n\n\nclass RequestsDependencyWarning(RequestsWarning):\n    \"\"\"An imported dependency doesn't match the expected version range.\"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/help.py",
    "content": "\"\"\"Module containing bug report helper(s).\"\"\"\n\nimport json\nimport platform\nimport ssl\nimport sys\n\nfrom pip._vendor import idna\nfrom pip._vendor import urllib3\n\nfrom . import __version__ as requests_version\n\ncharset_normalizer = None\n\ntry:\n    from pip._vendor import chardet\nexcept ImportError:\n    chardet = None\n\ntry:\n    from pip._vendor.urllib3.contrib import pyopenssl\nexcept ImportError:\n    pyopenssl = None\n    OpenSSL = None\n    cryptography = None\nelse:\n    import cryptography\n    import OpenSSL\n\n\ndef _implementation():\n    \"\"\"Return a dict with the Python implementation and version.\n\n    Provide both the name and the version of the Python implementation\n    currently running. For example, on CPython 3.10.3 it will return\n    {'name': 'CPython', 'version': '3.10.3'}.\n\n    This function works best on CPython and PyPy: in particular, it probably\n    doesn't work for Jython or IronPython. Future investigation should be done\n    to work out the correct shape of the code for those platforms.\n    \"\"\"\n    implementation = platform.python_implementation()\n\n    if implementation == \"CPython\":\n        implementation_version = platform.python_version()\n    elif implementation == \"PyPy\":\n        implementation_version = \"{}.{}.{}\".format(\n            sys.pypy_version_info.major,\n            sys.pypy_version_info.minor,\n            sys.pypy_version_info.micro,\n        )\n        if sys.pypy_version_info.releaselevel != \"final\":\n            implementation_version = \"\".join(\n                [implementation_version, sys.pypy_version_info.releaselevel]\n            )\n    elif implementation == \"Jython\":\n        implementation_version = platform.python_version()  # Complete Guess\n    elif implementation == \"IronPython\":\n        implementation_version = platform.python_version()  # Complete Guess\n    else:\n        implementation_version = \"Unknown\"\n\n    return {\"name\": implementation, \"version\": implementation_version}\n\n\ndef info():\n    \"\"\"Generate information for a bug report.\"\"\"\n    try:\n        platform_info = {\n            \"system\": platform.system(),\n            \"release\": platform.release(),\n        }\n    except OSError:\n        platform_info = {\n            \"system\": \"Unknown\",\n            \"release\": \"Unknown\",\n        }\n\n    implementation_info = _implementation()\n    urllib3_info = {\"version\": urllib3.__version__}\n    charset_normalizer_info = {\"version\": None}\n    chardet_info = {\"version\": None}\n    if charset_normalizer:\n        charset_normalizer_info = {\"version\": charset_normalizer.__version__}\n    if chardet:\n        chardet_info = {\"version\": chardet.__version__}\n\n    pyopenssl_info = {\n        \"version\": None,\n        \"openssl_version\": \"\",\n    }\n    if OpenSSL:\n        pyopenssl_info = {\n            \"version\": OpenSSL.__version__,\n            \"openssl_version\": f\"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}\",\n        }\n    cryptography_info = {\n        \"version\": getattr(cryptography, \"__version__\", \"\"),\n    }\n    idna_info = {\n        \"version\": getattr(idna, \"__version__\", \"\"),\n    }\n\n    system_ssl = ssl.OPENSSL_VERSION_NUMBER\n    system_ssl_info = {\"version\": f\"{system_ssl:x}\" if system_ssl is not None else \"\"}\n\n    return {\n        \"platform\": platform_info,\n        \"implementation\": implementation_info,\n        \"system_ssl\": system_ssl_info,\n        \"using_pyopenssl\": pyopenssl is not None,\n        \"using_charset_normalizer\": chardet is None,\n        \"pyOpenSSL\": pyopenssl_info,\n        \"urllib3\": urllib3_info,\n        \"chardet\": chardet_info,\n        \"charset_normalizer\": charset_normalizer_info,\n        \"cryptography\": cryptography_info,\n        \"idna\": idna_info,\n        \"requests\": {\n            \"version\": requests_version,\n        },\n    }\n\n\ndef main():\n    \"\"\"Pretty-print the bug information as JSON.\"\"\"\n    print(json.dumps(info(), sort_keys=True, indent=2))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/hooks.py",
    "content": "\"\"\"\nrequests.hooks\n~~~~~~~~~~~~~~\n\nThis module provides the capabilities for the Requests hooks system.\n\nAvailable hooks:\n\n``response``:\n    The response generated from a Request.\n\"\"\"\nHOOKS = [\"response\"]\n\n\ndef default_hooks():\n    return {event: [] for event in HOOKS}\n\n\n# TODO: response is the only one\n\n\ndef dispatch_hook(key, hooks, hook_data, **kwargs):\n    \"\"\"Dispatches a hook dictionary on a given piece of data.\"\"\"\n    hooks = hooks or {}\n    hooks = hooks.get(key)\n    if hooks:\n        if hasattr(hooks, \"__call__\"):\n            hooks = [hooks]\n        for hook in hooks:\n            _hook_data = hook(hook_data, **kwargs)\n            if _hook_data is not None:\n                hook_data = _hook_data\n    return hook_data\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/models.py",
    "content": "\"\"\"\nrequests.models\n~~~~~~~~~~~~~~~\n\nThis module contains the primary objects that power Requests.\n\"\"\"\n\nimport datetime\n\n# Import encoding now, to avoid implicit import later.\n# Implicit import within threads may cause LookupError when standard library is in a ZIP,\n# such as in Embedded Python. See https://github.com/psf/requests/issues/3578.\nimport encodings.idna  # noqa: F401\nfrom io import UnsupportedOperation\n\nfrom pip._vendor.urllib3.exceptions import (\n    DecodeError,\n    LocationParseError,\n    ProtocolError,\n    ReadTimeoutError,\n    SSLError,\n)\nfrom pip._vendor.urllib3.fields import RequestField\nfrom pip._vendor.urllib3.filepost import encode_multipart_formdata\nfrom pip._vendor.urllib3.util import parse_url\n\nfrom ._internal_utils import to_native_string, unicode_is_ascii\nfrom .auth import HTTPBasicAuth\nfrom .compat import (\n    Callable,\n    JSONDecodeError,\n    Mapping,\n    basestring,\n    builtin_str,\n    chardet,\n    cookielib,\n)\nfrom .compat import json as complexjson\nfrom .compat import urlencode, urlsplit, urlunparse\nfrom .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ConnectionError,\n    ContentDecodingError,\n    HTTPError,\n    InvalidJSONError,\n    InvalidURL,\n)\nfrom .exceptions import JSONDecodeError as RequestsJSONDecodeError\nfrom .exceptions import MissingSchema\nfrom .exceptions import SSLError as RequestsSSLError\nfrom .exceptions import StreamConsumedError\nfrom .hooks import default_hooks\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (\n    check_header_validity,\n    get_auth_from_url,\n    guess_filename,\n    guess_json_utf,\n    iter_slices,\n    parse_header_links,\n    requote_uri,\n    stream_decode_response_unicode,\n    super_len,\n    to_key_val_list,\n)\n\n#: The set of HTTP status codes that indicate an automatically\n#: processable redirect.\nREDIRECT_STATI = (\n    codes.moved,  # 301\n    codes.found,  # 302\n    codes.other,  # 303\n    codes.temporary_redirect,  # 307\n    codes.permanent_redirect,  # 308\n)\n\nDEFAULT_REDIRECT_LIMIT = 30\nCONTENT_CHUNK_SIZE = 10 * 1024\nITER_CHUNK_SIZE = 512\n\n\nclass RequestEncodingMixin:\n    @property\n    def path_url(self):\n        \"\"\"Build the path URL to use.\"\"\"\n\n        url = []\n\n        p = urlsplit(self.url)\n\n        path = p.path\n        if not path:\n            path = \"/\"\n\n        url.append(path)\n\n        query = p.query\n        if query:\n            url.append(\"?\")\n            url.append(query)\n\n        return \"\".join(url)\n\n    @staticmethod\n    def _encode_params(data):\n        \"\"\"Encode parameters in a piece of data.\n\n        Will successfully encode parameters when passed as a dict or a list of\n        2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n        if parameters are supplied as a dict.\n        \"\"\"\n\n        if isinstance(data, (str, bytes)):\n            return data\n        elif hasattr(data, \"read\"):\n            return data\n        elif hasattr(data, \"__iter__\"):\n            result = []\n            for k, vs in to_key_val_list(data):\n                if isinstance(vs, basestring) or not hasattr(vs, \"__iter__\"):\n                    vs = [vs]\n                for v in vs:\n                    if v is not None:\n                        result.append(\n                            (\n                                k.encode(\"utf-8\") if isinstance(k, str) else k,\n                                v.encode(\"utf-8\") if isinstance(v, str) else v,\n                            )\n                        )\n            return urlencode(result, doseq=True)\n        else:\n            return data\n\n    @staticmethod\n    def _encode_files(files, data):\n        \"\"\"Build the body for a multipart/form-data request.\n\n        Will successfully encode files when passed as a dict or a list of\n        tuples. Order is retained if data is a list of tuples but arbitrary\n        if parameters are supplied as a dict.\n        The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)\n        or 4-tuples (filename, fileobj, contentype, custom_headers).\n        \"\"\"\n        if not files:\n            raise ValueError(\"Files must be provided.\")\n        elif isinstance(data, basestring):\n            raise ValueError(\"Data must not be a string.\")\n\n        new_fields = []\n        fields = to_key_val_list(data or {})\n        files = to_key_val_list(files or {})\n\n        for field, val in fields:\n            if isinstance(val, basestring) or not hasattr(val, \"__iter__\"):\n                val = [val]\n            for v in val:\n                if v is not None:\n                    # Don't call str() on bytestrings: in Py3 it all goes wrong.\n                    if not isinstance(v, bytes):\n                        v = str(v)\n\n                    new_fields.append(\n                        (\n                            field.decode(\"utf-8\")\n                            if isinstance(field, bytes)\n                            else field,\n                            v.encode(\"utf-8\") if isinstance(v, str) else v,\n                        )\n                    )\n\n        for (k, v) in files:\n            # support for explicit filename\n            ft = None\n            fh = None\n            if isinstance(v, (tuple, list)):\n                if len(v) == 2:\n                    fn, fp = v\n                elif len(v) == 3:\n                    fn, fp, ft = v\n                else:\n                    fn, fp, ft, fh = v\n            else:\n                fn = guess_filename(v) or k\n                fp = v\n\n            if isinstance(fp, (str, bytes, bytearray)):\n                fdata = fp\n            elif hasattr(fp, \"read\"):\n                fdata = fp.read()\n            elif fp is None:\n                continue\n            else:\n                fdata = fp\n\n            rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n            rf.make_multipart(content_type=ft)\n            new_fields.append(rf)\n\n        body, content_type = encode_multipart_formdata(new_fields)\n\n        return body, content_type\n\n\nclass RequestHooksMixin:\n    def register_hook(self, event, hook):\n        \"\"\"Properly register a hook.\"\"\"\n\n        if event not in self.hooks:\n            raise ValueError(f'Unsupported event specified, with event name \"{event}\"')\n\n        if isinstance(hook, Callable):\n            self.hooks[event].append(hook)\n        elif hasattr(hook, \"__iter__\"):\n            self.hooks[event].extend(h for h in hook if isinstance(h, Callable))\n\n    def deregister_hook(self, event, hook):\n        \"\"\"Deregister a previously registered hook.\n        Returns True if the hook existed, False if not.\n        \"\"\"\n\n        try:\n            self.hooks[event].remove(hook)\n            return True\n        except ValueError:\n            return False\n\n\nclass Request(RequestHooksMixin):\n    \"\"\"A user-created :class:`Request <Request>` object.\n\n    Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.\n\n    :param method: HTTP method to use.\n    :param url: URL to send.\n    :param headers: dictionary of headers to send.\n    :param files: dictionary of {filename: fileobject} files to multipart upload.\n    :param data: the body to attach to the request. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param json: json for the body to attach to the request (if files or data is not specified).\n    :param params: URL parameters to append to the URL. If a dictionary or\n        list of tuples ``[(key, value)]`` is provided, form-encoding will\n        take place.\n    :param auth: Auth handler or (user, pass) tuple.\n    :param cookies: dictionary or CookieJar of cookies to attach to this request.\n    :param hooks: dictionary of callback hooks, for internal usage.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> req.prepare()\n      <PreparedRequest [GET]>\n    \"\"\"\n\n    def __init__(\n        self,\n        method=None,\n        url=None,\n        headers=None,\n        files=None,\n        data=None,\n        params=None,\n        auth=None,\n        cookies=None,\n        hooks=None,\n        json=None,\n    ):\n\n        # Default empty dicts for dict params.\n        data = [] if data is None else data\n        files = [] if files is None else files\n        headers = {} if headers is None else headers\n        params = {} if params is None else params\n        hooks = {} if hooks is None else hooks\n\n        self.hooks = default_hooks()\n        for (k, v) in list(hooks.items()):\n            self.register_hook(event=k, hook=v)\n\n        self.method = method\n        self.url = url\n        self.headers = headers\n        self.files = files\n        self.data = data\n        self.json = json\n        self.params = params\n        self.auth = auth\n        self.cookies = cookies\n\n    def __repr__(self):\n        return f\"<Request [{self.method}]>\"\n\n    def prepare(self):\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it.\"\"\"\n        p = PreparedRequest()\n        p.prepare(\n            method=self.method,\n            url=self.url,\n            headers=self.headers,\n            files=self.files,\n            data=self.data,\n            json=self.json,\n            params=self.params,\n            auth=self.auth,\n            cookies=self.cookies,\n            hooks=self.hooks,\n        )\n        return p\n\n\nclass PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n    \"\"\"The fully mutable :class:`PreparedRequest <PreparedRequest>` object,\n    containing the exact bytes that will be sent to the server.\n\n    Instances are generated from a :class:`Request <Request>` object, and\n    should not be instantiated manually; doing so may produce undesirable\n    effects.\n\n    Usage::\n\n      >>> import requests\n      >>> req = requests.Request('GET', 'https://httpbin.org/get')\n      >>> r = req.prepare()\n      >>> r\n      <PreparedRequest [GET]>\n\n      >>> s = requests.Session()\n      >>> s.send(r)\n      <Response [200]>\n    \"\"\"\n\n    def __init__(self):\n        #: HTTP verb to send to the server.\n        self.method = None\n        #: HTTP URL to send the request to.\n        self.url = None\n        #: dictionary of HTTP headers.\n        self.headers = None\n        # The `CookieJar` used to create the Cookie header will be stored here\n        # after prepare_cookies is called\n        self._cookies = None\n        #: request body to send to the server.\n        self.body = None\n        #: dictionary of callback hooks, for internal usage.\n        self.hooks = default_hooks()\n        #: integer denoting starting position of a readable file-like body.\n        self._body_position = None\n\n    def prepare(\n        self,\n        method=None,\n        url=None,\n        headers=None,\n        files=None,\n        data=None,\n        params=None,\n        auth=None,\n        cookies=None,\n        hooks=None,\n        json=None,\n    ):\n        \"\"\"Prepares the entire request with the given parameters.\"\"\"\n\n        self.prepare_method(method)\n        self.prepare_url(url, params)\n        self.prepare_headers(headers)\n        self.prepare_cookies(cookies)\n        self.prepare_body(data, files, json)\n        self.prepare_auth(auth, url)\n\n        # Note that prepare_auth must be last to enable authentication schemes\n        # such as OAuth to work on a fully prepared request.\n\n        # This MUST go after prepare_auth. Authenticators could add a hook\n        self.prepare_hooks(hooks)\n\n    def __repr__(self):\n        return f\"<PreparedRequest [{self.method}]>\"\n\n    def copy(self):\n        p = PreparedRequest()\n        p.method = self.method\n        p.url = self.url\n        p.headers = self.headers.copy() if self.headers is not None else None\n        p._cookies = _copy_cookie_jar(self._cookies)\n        p.body = self.body\n        p.hooks = self.hooks\n        p._body_position = self._body_position\n        return p\n\n    def prepare_method(self, method):\n        \"\"\"Prepares the given HTTP method.\"\"\"\n        self.method = method\n        if self.method is not None:\n            self.method = to_native_string(self.method.upper())\n\n    @staticmethod\n    def _get_idna_encoded_host(host):\n        from pip._vendor import idna\n\n        try:\n            host = idna.encode(host, uts46=True).decode(\"utf-8\")\n        except idna.IDNAError:\n            raise UnicodeError\n        return host\n\n    def prepare_url(self, url, params):\n        \"\"\"Prepares the given HTTP URL.\"\"\"\n        #: Accept objects that have string representations.\n        #: We're unable to blindly call unicode/str functions\n        #: as this will include the bytestring indicator (b'')\n        #: on python 3.x.\n        #: https://github.com/psf/requests/pull/2238\n        if isinstance(url, bytes):\n            url = url.decode(\"utf8\")\n        else:\n            url = str(url)\n\n        # Remove leading whitespaces from url\n        url = url.lstrip()\n\n        # Don't do any URL preparation for non-HTTP schemes like `mailto`,\n        # `data` etc to work around exceptions from `url_parse`, which\n        # handles RFC 3986 only.\n        if \":\" in url and not url.lower().startswith(\"http\"):\n            self.url = url\n            return\n\n        # Support for unicode domain names and paths.\n        try:\n            scheme, auth, host, port, path, query, fragment = parse_url(url)\n        except LocationParseError as e:\n            raise InvalidURL(*e.args)\n\n        if not scheme:\n            raise MissingSchema(\n                f\"Invalid URL {url!r}: No scheme supplied. \"\n                f\"Perhaps you meant http://{url}?\"\n            )\n\n        if not host:\n            raise InvalidURL(f\"Invalid URL {url!r}: No host supplied\")\n\n        # In general, we want to try IDNA encoding the hostname if the string contains\n        # non-ASCII characters. This allows users to automatically get the correct IDNA\n        # behaviour. For strings containing only ASCII characters, we need to also verify\n        # it doesn't start with a wildcard (*), before allowing the unencoded hostname.\n        if not unicode_is_ascii(host):\n            try:\n                host = self._get_idna_encoded_host(host)\n            except UnicodeError:\n                raise InvalidURL(\"URL has an invalid label.\")\n        elif host.startswith((\"*\", \".\")):\n            raise InvalidURL(\"URL has an invalid label.\")\n\n        # Carefully reconstruct the network location\n        netloc = auth or \"\"\n        if netloc:\n            netloc += \"@\"\n        netloc += host\n        if port:\n            netloc += f\":{port}\"\n\n        # Bare domains aren't valid URLs.\n        if not path:\n            path = \"/\"\n\n        if isinstance(params, (str, bytes)):\n            params = to_native_string(params)\n\n        enc_params = self._encode_params(params)\n        if enc_params:\n            if query:\n                query = f\"{query}&{enc_params}\"\n            else:\n                query = enc_params\n\n        url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))\n        self.url = url\n\n    def prepare_headers(self, headers):\n        \"\"\"Prepares the given HTTP headers.\"\"\"\n\n        self.headers = CaseInsensitiveDict()\n        if headers:\n            for header in headers.items():\n                # Raise exception on invalid header value.\n                check_header_validity(header)\n                name, value = header\n                self.headers[to_native_string(name)] = value\n\n    def prepare_body(self, data, files, json=None):\n        \"\"\"Prepares the given HTTP body data.\"\"\"\n\n        # Check if file, fo, generator, iterator.\n        # If not, run through normal process.\n\n        # Nottin' on you.\n        body = None\n        content_type = None\n\n        if not data and json is not None:\n            # urllib3 requires a bytes-like body. Python 2's json.dumps\n            # provides this natively, but Python 3 gives a Unicode string.\n            content_type = \"application/json\"\n\n            try:\n                body = complexjson.dumps(json, allow_nan=False)\n            except ValueError as ve:\n                raise InvalidJSONError(ve, request=self)\n\n            if not isinstance(body, bytes):\n                body = body.encode(\"utf-8\")\n\n        is_stream = all(\n            [\n                hasattr(data, \"__iter__\"),\n                not isinstance(data, (basestring, list, tuple, Mapping)),\n            ]\n        )\n\n        if is_stream:\n            try:\n                length = super_len(data)\n            except (TypeError, AttributeError, UnsupportedOperation):\n                length = None\n\n            body = data\n\n            if getattr(body, \"tell\", None) is not None:\n                # Record the current file position before reading.\n                # This will allow us to rewind a file in the event\n                # of a redirect.\n                try:\n                    self._body_position = body.tell()\n                except OSError:\n                    # This differentiates from None, allowing us to catch\n                    # a failed `tell()` later when trying to rewind the body\n                    self._body_position = object()\n\n            if files:\n                raise NotImplementedError(\n                    \"Streamed bodies and files are mutually exclusive.\"\n                )\n\n            if length:\n                self.headers[\"Content-Length\"] = builtin_str(length)\n            else:\n                self.headers[\"Transfer-Encoding\"] = \"chunked\"\n        else:\n            # Multi-part file uploads.\n            if files:\n                (body, content_type) = self._encode_files(files, data)\n            else:\n                if data:\n                    body = self._encode_params(data)\n                    if isinstance(data, basestring) or hasattr(data, \"read\"):\n                        content_type = None\n                    else:\n                        content_type = \"application/x-www-form-urlencoded\"\n\n            self.prepare_content_length(body)\n\n            # Add content-type if it wasn't explicitly provided.\n            if content_type and (\"content-type\" not in self.headers):\n                self.headers[\"Content-Type\"] = content_type\n\n        self.body = body\n\n    def prepare_content_length(self, body):\n        \"\"\"Prepare Content-Length header based on request method and body\"\"\"\n        if body is not None:\n            length = super_len(body)\n            if length:\n                # If length exists, set it. Otherwise, we fallback\n                # to Transfer-Encoding: chunked.\n                self.headers[\"Content-Length\"] = builtin_str(length)\n        elif (\n            self.method not in (\"GET\", \"HEAD\")\n            and self.headers.get(\"Content-Length\") is None\n        ):\n            # Set Content-Length to 0 for methods that can have a body\n            # but don't provide one. (i.e. not GET or HEAD)\n            self.headers[\"Content-Length\"] = \"0\"\n\n    def prepare_auth(self, auth, url=\"\"):\n        \"\"\"Prepares the given HTTP auth data.\"\"\"\n\n        # If no Auth is explicitly provided, extract it from the URL first.\n        if auth is None:\n            url_auth = get_auth_from_url(self.url)\n            auth = url_auth if any(url_auth) else None\n\n        if auth:\n            if isinstance(auth, tuple) and len(auth) == 2:\n                # special-case basic HTTP auth\n                auth = HTTPBasicAuth(*auth)\n\n            # Allow auth to make its changes.\n            r = auth(self)\n\n            # Update self to reflect the auth changes.\n            self.__dict__.update(r.__dict__)\n\n            # Recompute Content-Length\n            self.prepare_content_length(self.body)\n\n    def prepare_cookies(self, cookies):\n        \"\"\"Prepares the given HTTP cookie data.\n\n        This function eventually generates a ``Cookie`` header from the\n        given cookies using cookielib. Due to cookielib's design, the header\n        will not be regenerated if it already exists, meaning this function\n        can only be called once for the life of the\n        :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls\n        to ``prepare_cookies`` will have no actual effect, unless the \"Cookie\"\n        header is removed beforehand.\n        \"\"\"\n        if isinstance(cookies, cookielib.CookieJar):\n            self._cookies = cookies\n        else:\n            self._cookies = cookiejar_from_dict(cookies)\n\n        cookie_header = get_cookie_header(self._cookies, self)\n        if cookie_header is not None:\n            self.headers[\"Cookie\"] = cookie_header\n\n    def prepare_hooks(self, hooks):\n        \"\"\"Prepares the given hooks.\"\"\"\n        # hooks can be passed as None to the prepare method and to this\n        # method. To prevent iterating over None, simply use an empty list\n        # if hooks is False-y\n        hooks = hooks or []\n        for event in hooks:\n            self.register_hook(event, hooks[event])\n\n\nclass Response:\n    \"\"\"The :class:`Response <Response>` object, which contains a\n    server's response to an HTTP request.\n    \"\"\"\n\n    __attrs__ = [\n        \"_content\",\n        \"status_code\",\n        \"headers\",\n        \"url\",\n        \"history\",\n        \"encoding\",\n        \"reason\",\n        \"cookies\",\n        \"elapsed\",\n        \"request\",\n    ]\n\n    def __init__(self):\n        self._content = False\n        self._content_consumed = False\n        self._next = None\n\n        #: Integer Code of responded HTTP Status, e.g. 404 or 200.\n        self.status_code = None\n\n        #: Case-insensitive Dictionary of Response Headers.\n        #: For example, ``headers['content-encoding']`` will return the\n        #: value of a ``'Content-Encoding'`` response header.\n        self.headers = CaseInsensitiveDict()\n\n        #: File-like object representation of response (for advanced usage).\n        #: Use of ``raw`` requires that ``stream=True`` be set on the request.\n        #: This requirement does not apply for use internally to Requests.\n        self.raw = None\n\n        #: Final URL location of Response.\n        self.url = None\n\n        #: Encoding to decode with when accessing r.text.\n        self.encoding = None\n\n        #: A list of :class:`Response <Response>` objects from\n        #: the history of the Request. Any redirect responses will end\n        #: up here. The list is sorted from the oldest to the most recent request.\n        self.history = []\n\n        #: Textual reason of responded HTTP Status, e.g. \"Not Found\" or \"OK\".\n        self.reason = None\n\n        #: A CookieJar of Cookies the server sent back.\n        self.cookies = cookiejar_from_dict({})\n\n        #: The amount of time elapsed between sending the request\n        #: and the arrival of the response (as a timedelta).\n        #: This property specifically measures the time taken between sending\n        #: the first byte of the request and finishing parsing the headers. It\n        #: is therefore unaffected by consuming the response content or the\n        #: value of the ``stream`` keyword argument.\n        self.elapsed = datetime.timedelta(0)\n\n        #: The :class:`PreparedRequest <PreparedRequest>` object to which this\n        #: is a response.\n        self.request = None\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        self.close()\n\n    def __getstate__(self):\n        # Consume everything; accessing the content attribute makes\n        # sure the content has been fully read.\n        if not self._content_consumed:\n            self.content\n\n        return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n\n    def __setstate__(self, state):\n        for name, value in state.items():\n            setattr(self, name, value)\n\n        # pickled objects do not have .raw\n        setattr(self, \"_content_consumed\", True)\n        setattr(self, \"raw\", None)\n\n    def __repr__(self):\n        return f\"<Response [{self.status_code}]>\"\n\n    def __bool__(self):\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __nonzero__(self):\n        \"\"\"Returns True if :attr:`status_code` is less than 400.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code, is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        return self.ok\n\n    def __iter__(self):\n        \"\"\"Allows you to use a response as an iterator.\"\"\"\n        return self.iter_content(128)\n\n    @property\n    def ok(self):\n        \"\"\"Returns True if :attr:`status_code` is less than 400, False if not.\n\n        This attribute checks if the status code of the response is between\n        400 and 600 to see if there was a client error or a server error. If\n        the status code is between 200 and 400, this will return True. This\n        is **not** a check to see if the response code is ``200 OK``.\n        \"\"\"\n        try:\n            self.raise_for_status()\n        except HTTPError:\n            return False\n        return True\n\n    @property\n    def is_redirect(self):\n        \"\"\"True if this Response is a well-formed HTTP redirect that could have\n        been processed automatically (by :meth:`Session.resolve_redirects`).\n        \"\"\"\n        return \"location\" in self.headers and self.status_code in REDIRECT_STATI\n\n    @property\n    def is_permanent_redirect(self):\n        \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n        return \"location\" in self.headers and self.status_code in (\n            codes.moved_permanently,\n            codes.permanent_redirect,\n        )\n\n    @property\n    def next(self):\n        \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n        return self._next\n\n    @property\n    def apparent_encoding(self):\n        \"\"\"The apparent encoding, provided by the charset_normalizer or chardet libraries.\"\"\"\n        return chardet.detect(self.content)[\"encoding\"]\n\n    def iter_content(self, chunk_size=1, decode_unicode=False):\n        \"\"\"Iterates over the response data.  When stream=True is set on the\n        request, this avoids reading the content at once into memory for\n        large responses.  The chunk size is the number of bytes it should\n        read into memory.  This is not necessarily the length of each item\n        returned as decoding can take place.\n\n        chunk_size must be of type int or None. A value of None will\n        function differently depending on the value of `stream`.\n        stream=True will read data as it arrives in whatever size the\n        chunks are received. If stream=False, data is returned as\n        a single chunk.\n\n        If decode_unicode is True, content will be decoded using the best\n        available encoding based on the response.\n        \"\"\"\n\n        def generate():\n            # Special case for urllib3.\n            if hasattr(self.raw, \"stream\"):\n                try:\n                    yield from self.raw.stream(chunk_size, decode_content=True)\n                except ProtocolError as e:\n                    raise ChunkedEncodingError(e)\n                except DecodeError as e:\n                    raise ContentDecodingError(e)\n                except ReadTimeoutError as e:\n                    raise ConnectionError(e)\n                except SSLError as e:\n                    raise RequestsSSLError(e)\n            else:\n                # Standard file-like object.\n                while True:\n                    chunk = self.raw.read(chunk_size)\n                    if not chunk:\n                        break\n                    yield chunk\n\n            self._content_consumed = True\n\n        if self._content_consumed and isinstance(self._content, bool):\n            raise StreamConsumedError()\n        elif chunk_size is not None and not isinstance(chunk_size, int):\n            raise TypeError(\n                f\"chunk_size must be an int, it is instead a {type(chunk_size)}.\"\n            )\n        # simulate reading small chunks of the content\n        reused_chunks = iter_slices(self._content, chunk_size)\n\n        stream_chunks = generate()\n\n        chunks = reused_chunks if self._content_consumed else stream_chunks\n\n        if decode_unicode:\n            chunks = stream_decode_response_unicode(chunks, self)\n\n        return chunks\n\n    def iter_lines(\n        self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None\n    ):\n        \"\"\"Iterates over the response data, one line at a time.  When\n        stream=True is set on the request, this avoids reading the\n        content at once into memory for large responses.\n\n        .. note:: This method is not reentrant safe.\n        \"\"\"\n\n        pending = None\n\n        for chunk in self.iter_content(\n            chunk_size=chunk_size, decode_unicode=decode_unicode\n        ):\n\n            if pending is not None:\n                chunk = pending + chunk\n\n            if delimiter:\n                lines = chunk.split(delimiter)\n            else:\n                lines = chunk.splitlines()\n\n            if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:\n                pending = lines.pop()\n            else:\n                pending = None\n\n            yield from lines\n\n        if pending is not None:\n            yield pending\n\n    @property\n    def content(self):\n        \"\"\"Content of the response, in bytes.\"\"\"\n\n        if self._content is False:\n            # Read the contents.\n            if self._content_consumed:\n                raise RuntimeError(\"The content for this response was already consumed\")\n\n            if self.status_code == 0 or self.raw is None:\n                self._content = None\n            else:\n                self._content = b\"\".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b\"\"\n\n        self._content_consumed = True\n        # don't need to release the connection; that's been handled by urllib3\n        # since we exhausted the data.\n        return self._content\n\n    @property\n    def text(self):\n        \"\"\"Content of the response, in unicode.\n\n        If Response.encoding is None, encoding will be guessed using\n        ``charset_normalizer`` or ``chardet``.\n\n        The encoding of the response content is determined based solely on HTTP\n        headers, following RFC 2616 to the letter. If you can take advantage of\n        non-HTTP knowledge to make a better guess at the encoding, you should\n        set ``r.encoding`` appropriately before accessing this property.\n        \"\"\"\n\n        # Try charset from content-type\n        content = None\n        encoding = self.encoding\n\n        if not self.content:\n            return \"\"\n\n        # Fallback to auto-detected encoding.\n        if self.encoding is None:\n            encoding = self.apparent_encoding\n\n        # Decode unicode from given encoding.\n        try:\n            content = str(self.content, encoding, errors=\"replace\")\n        except (LookupError, TypeError):\n            # A LookupError is raised if the encoding was not found which could\n            # indicate a misspelling or similar mistake.\n            #\n            # A TypeError can be raised if encoding is None\n            #\n            # So we try blindly encoding.\n            content = str(self.content, errors=\"replace\")\n\n        return content\n\n    def json(self, **kwargs):\n        r\"\"\"Returns the json-encoded content of a response, if any.\n\n        :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n        :raises requests.exceptions.JSONDecodeError: If the response body does not\n            contain valid json.\n        \"\"\"\n\n        if not self.encoding and self.content and len(self.content) > 3:\n            # No encoding set. JSON RFC 4627 section 3 states we should expect\n            # UTF-8, -16 or -32. Detect which one to use; If the detection or\n            # decoding fails, fall back to `self.text` (using charset_normalizer to make\n            # a best guess).\n            encoding = guess_json_utf(self.content)\n            if encoding is not None:\n                try:\n                    return complexjson.loads(self.content.decode(encoding), **kwargs)\n                except UnicodeDecodeError:\n                    # Wrong UTF codec detected; usually because it's not UTF-8\n                    # but some other 8-bit codec.  This is an RFC violation,\n                    # and the server didn't bother to tell us what codec *was*\n                    # used.\n                    pass\n                except JSONDecodeError as e:\n                    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n        try:\n            return complexjson.loads(self.text, **kwargs)\n        except JSONDecodeError as e:\n            # Catch JSON-related errors and raise as requests.JSONDecodeError\n            # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n            raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n\n    @property\n    def links(self):\n        \"\"\"Returns the parsed header links of the response, if any.\"\"\"\n\n        header = self.headers.get(\"link\")\n\n        resolved_links = {}\n\n        if header:\n            links = parse_header_links(header)\n\n            for link in links:\n                key = link.get(\"rel\") or link.get(\"url\")\n                resolved_links[key] = link\n\n        return resolved_links\n\n    def raise_for_status(self):\n        \"\"\"Raises :class:`HTTPError`, if one occurred.\"\"\"\n\n        http_error_msg = \"\"\n        if isinstance(self.reason, bytes):\n            # We attempt to decode utf-8 first because some servers\n            # choose to localize their reason strings. If the string\n            # isn't utf-8, we fall back to iso-8859-1 for all other\n            # encodings. (See PR #3538)\n            try:\n                reason = self.reason.decode(\"utf-8\")\n            except UnicodeDecodeError:\n                reason = self.reason.decode(\"iso-8859-1\")\n        else:\n            reason = self.reason\n\n        if 400 <= self.status_code < 500:\n            http_error_msg = (\n                f\"{self.status_code} Client Error: {reason} for url: {self.url}\"\n            )\n\n        elif 500 <= self.status_code < 600:\n            http_error_msg = (\n                f\"{self.status_code} Server Error: {reason} for url: {self.url}\"\n            )\n\n        if http_error_msg:\n            raise HTTPError(http_error_msg, response=self)\n\n    def close(self):\n        \"\"\"Releases the connection back to the pool. Once this method has been\n        called the underlying ``raw`` object must not be accessed again.\n\n        *Note: Should not normally need to be called explicitly.*\n        \"\"\"\n        if not self._content_consumed:\n            self.raw.close()\n\n        release_conn = getattr(self.raw, \"release_conn\", None)\n        if release_conn is not None:\n            release_conn()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/packages.py",
    "content": "import sys\n\n# This code exists for backwards compatibility reasons.\n# I don't like it either. Just look the other way. :)\n\nfor package in ('urllib3', 'idna', 'chardet'):\n    vendored_package = \"pip._vendor.\" + package\n    locals()[package] = __import__(vendored_package)\n    # This traversal is apparently necessary such that the identities are\n    # preserved (requests.packages.urllib3.* is urllib3.*)\n    for mod in list(sys.modules):\n        if mod == vendored_package or mod.startswith(vendored_package + '.'):\n            unprefixed_mod = mod[len(\"pip._vendor.\"):]\n            sys.modules['pip._vendor.requests.packages.' + unprefixed_mod] = sys.modules[mod]\n\n# Kinda cool, though, right?\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/sessions.py",
    "content": "\"\"\"\nrequests.sessions\n~~~~~~~~~~~~~~~~~\n\nThis module provides a Session object to manage and persist settings across\nrequests (cookies, auth, proxies).\n\"\"\"\nimport os\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom datetime import timedelta\n\nfrom ._internal_utils import to_native_string\nfrom .adapters import HTTPAdapter\nfrom .auth import _basic_auth_str\nfrom .compat import Mapping, cookielib, urljoin, urlparse\nfrom .cookies import (\n    RequestsCookieJar,\n    cookiejar_from_dict,\n    extract_cookies_to_jar,\n    merge_cookies,\n)\nfrom .exceptions import (\n    ChunkedEncodingError,\n    ContentDecodingError,\n    InvalidSchema,\n    TooManyRedirects,\n)\nfrom .hooks import default_hooks, dispatch_hook\n\n# formerly defined here, reexposed here for backward compatibility\nfrom .models import (  # noqa: F401\n    DEFAULT_REDIRECT_LIMIT,\n    REDIRECT_STATI,\n    PreparedRequest,\n    Request,\n)\nfrom .status_codes import codes\nfrom .structures import CaseInsensitiveDict\nfrom .utils import (  # noqa: F401\n    DEFAULT_PORTS,\n    default_headers,\n    get_auth_from_url,\n    get_environ_proxies,\n    get_netrc_auth,\n    requote_uri,\n    resolve_proxies,\n    rewind_body,\n    should_bypass_proxies,\n    to_key_val_list,\n)\n\n# Preferred clock, based on which one is more accurate on a given system.\nif sys.platform == \"win32\":\n    preferred_clock = time.perf_counter\nelse:\n    preferred_clock = time.time\n\n\ndef merge_setting(request_setting, session_setting, dict_class=OrderedDict):\n    \"\"\"Determines appropriate setting for a given request, taking into account\n    the explicit setting on that request, and the setting in the session. If a\n    setting is a dictionary, they will be merged together using `dict_class`\n    \"\"\"\n\n    if session_setting is None:\n        return request_setting\n\n    if request_setting is None:\n        return session_setting\n\n    # Bypass if not a dictionary (e.g. verify)\n    if not (\n        isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)\n    ):\n        return request_setting\n\n    merged_setting = dict_class(to_key_val_list(session_setting))\n    merged_setting.update(to_key_val_list(request_setting))\n\n    # Remove keys that are set to None. Extract keys first to avoid altering\n    # the dictionary during iteration.\n    none_keys = [k for (k, v) in merged_setting.items() if v is None]\n    for key in none_keys:\n        del merged_setting[key]\n\n    return merged_setting\n\n\ndef merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):\n    \"\"\"Properly merges both requests and session hooks.\n\n    This is necessary because when request_hooks == {'response': []}, the\n    merge breaks Session hooks entirely.\n    \"\"\"\n    if session_hooks is None or session_hooks.get(\"response\") == []:\n        return request_hooks\n\n    if request_hooks is None or request_hooks.get(\"response\") == []:\n        return session_hooks\n\n    return merge_setting(request_hooks, session_hooks, dict_class)\n\n\nclass SessionRedirectMixin:\n    def get_redirect_target(self, resp):\n        \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n        # Due to the nature of how requests processes redirects this method will\n        # be called at least once upon the original response and at least twice\n        # on each subsequent redirect response (if any).\n        # If a custom mixin is used to handle this logic, it may be advantageous\n        # to cache the redirect location onto the response object as a private\n        # attribute.\n        if resp.is_redirect:\n            location = resp.headers[\"location\"]\n            # Currently the underlying http module on py3 decode headers\n            # in latin1, but empirical evidence suggests that latin1 is very\n            # rarely used with non-ASCII characters in HTTP headers.\n            # It is more likely to get UTF8 header rather than latin1.\n            # This causes incorrect handling of UTF8 encoded location headers.\n            # To solve this, we re-encode the location in latin1.\n            location = location.encode(\"latin1\")\n            return to_native_string(location, \"utf8\")\n        return None\n\n    def should_strip_auth(self, old_url, new_url):\n        \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n        old_parsed = urlparse(old_url)\n        new_parsed = urlparse(new_url)\n        if old_parsed.hostname != new_parsed.hostname:\n            return True\n        # Special case: allow http -> https redirect when using the standard\n        # ports. This isn't specified by RFC 7235, but is kept to avoid\n        # breaking backwards compatibility with older versions of requests\n        # that allowed any redirects on the same host.\n        if (\n            old_parsed.scheme == \"http\"\n            and old_parsed.port in (80, None)\n            and new_parsed.scheme == \"https\"\n            and new_parsed.port in (443, None)\n        ):\n            return False\n\n        # Handle default port usage corresponding to scheme.\n        changed_port = old_parsed.port != new_parsed.port\n        changed_scheme = old_parsed.scheme != new_parsed.scheme\n        default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)\n        if (\n            not changed_scheme\n            and old_parsed.port in default_port\n            and new_parsed.port in default_port\n        ):\n            return False\n\n        # Standard case: root URI must match\n        return changed_port or changed_scheme\n\n    def resolve_redirects(\n        self,\n        resp,\n        req,\n        stream=False,\n        timeout=None,\n        verify=True,\n        cert=None,\n        proxies=None,\n        yield_requests=False,\n        **adapter_kwargs,\n    ):\n        \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n\n        hist = []  # keep track of history\n\n        url = self.get_redirect_target(resp)\n        previous_fragment = urlparse(req.url).fragment\n        while url:\n            prepared_request = req.copy()\n\n            # Update history and keep track of redirects.\n            # resp.history must ignore the original request in this loop\n            hist.append(resp)\n            resp.history = hist[1:]\n\n            try:\n                resp.content  # Consume socket so it can be released\n            except (ChunkedEncodingError, ContentDecodingError, RuntimeError):\n                resp.raw.read(decode_content=False)\n\n            if len(resp.history) >= self.max_redirects:\n                raise TooManyRedirects(\n                    f\"Exceeded {self.max_redirects} redirects.\", response=resp\n                )\n\n            # Release the connection back into the pool.\n            resp.close()\n\n            # Handle redirection without scheme (see: RFC 1808 Section 4)\n            if url.startswith(\"//\"):\n                parsed_rurl = urlparse(resp.url)\n                url = \":\".join([to_native_string(parsed_rurl.scheme), url])\n\n            # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n            parsed = urlparse(url)\n            if parsed.fragment == \"\" and previous_fragment:\n                parsed = parsed._replace(fragment=previous_fragment)\n            elif parsed.fragment:\n                previous_fragment = parsed.fragment\n            url = parsed.geturl()\n\n            # Facilitate relative 'location' headers, as allowed by RFC 7231.\n            # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')\n            # Compliant with RFC3986, we percent encode the url.\n            if not parsed.netloc:\n                url = urljoin(resp.url, requote_uri(url))\n            else:\n                url = requote_uri(url)\n\n            prepared_request.url = to_native_string(url)\n\n            self.rebuild_method(prepared_request, resp)\n\n            # https://github.com/psf/requests/issues/1084\n            if resp.status_code not in (\n                codes.temporary_redirect,\n                codes.permanent_redirect,\n            ):\n                # https://github.com/psf/requests/issues/3490\n                purged_headers = (\"Content-Length\", \"Content-Type\", \"Transfer-Encoding\")\n                for header in purged_headers:\n                    prepared_request.headers.pop(header, None)\n                prepared_request.body = None\n\n            headers = prepared_request.headers\n            headers.pop(\"Cookie\", None)\n\n            # Extract any cookies sent on the response to the cookiejar\n            # in the new request. Because we've mutated our copied prepared\n            # request, use the old one that we haven't yet touched.\n            extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)\n            merge_cookies(prepared_request._cookies, self.cookies)\n            prepared_request.prepare_cookies(prepared_request._cookies)\n\n            # Rebuild auth and proxy information.\n            proxies = self.rebuild_proxies(prepared_request, proxies)\n            self.rebuild_auth(prepared_request, resp)\n\n            # A failed tell() sets `_body_position` to `object()`. This non-None\n            # value ensures `rewindable` will be True, allowing us to raise an\n            # UnrewindableBodyError, instead of hanging the connection.\n            rewindable = prepared_request._body_position is not None and (\n                \"Content-Length\" in headers or \"Transfer-Encoding\" in headers\n            )\n\n            # Attempt to rewind consumed file-like object.\n            if rewindable:\n                rewind_body(prepared_request)\n\n            # Override the original request.\n            req = prepared_request\n\n            if yield_requests:\n                yield req\n            else:\n\n                resp = self.send(\n                    req,\n                    stream=stream,\n                    timeout=timeout,\n                    verify=verify,\n                    cert=cert,\n                    proxies=proxies,\n                    allow_redirects=False,\n                    **adapter_kwargs,\n                )\n\n                extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n\n                # extract redirect url, if any, for the next loop\n                url = self.get_redirect_target(resp)\n                yield resp\n\n    def rebuild_auth(self, prepared_request, response):\n        \"\"\"When being redirected we may want to strip authentication from the\n        request to avoid leaking credentials. This method intelligently removes\n        and reapplies authentication where possible to avoid credential loss.\n        \"\"\"\n        headers = prepared_request.headers\n        url = prepared_request.url\n\n        if \"Authorization\" in headers and self.should_strip_auth(\n            response.request.url, url\n        ):\n            # If we get redirected to a new host, we should strip out any\n            # authentication headers.\n            del headers[\"Authorization\"]\n\n        # .netrc might have more auth for us on our new host.\n        new_auth = get_netrc_auth(url) if self.trust_env else None\n        if new_auth is not None:\n            prepared_request.prepare_auth(new_auth)\n\n    def rebuild_proxies(self, prepared_request, proxies):\n        \"\"\"This method re-evaluates the proxy configuration by considering the\n        environment variables. If we are redirected to a URL covered by\n        NO_PROXY, we strip the proxy configuration. Otherwise, we set missing\n        proxy keys for this URL (in case they were stripped by a previous\n        redirect).\n\n        This method also replaces the Proxy-Authorization header where\n        necessary.\n\n        :rtype: dict\n        \"\"\"\n        headers = prepared_request.headers\n        scheme = urlparse(prepared_request.url).scheme\n        new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n\n        if \"Proxy-Authorization\" in headers:\n            del headers[\"Proxy-Authorization\"]\n\n        try:\n            username, password = get_auth_from_url(new_proxies[scheme])\n        except KeyError:\n            username, password = None, None\n\n        if username and password:\n            headers[\"Proxy-Authorization\"] = _basic_auth_str(username, password)\n\n        return new_proxies\n\n    def rebuild_method(self, prepared_request, response):\n        \"\"\"When being redirected we may want to change the method of the request\n        based on certain specs or browser behavior.\n        \"\"\"\n        method = prepared_request.method\n\n        # https://tools.ietf.org/html/rfc7231#section-6.4.4\n        if response.status_code == codes.see_other and method != \"HEAD\":\n            method = \"GET\"\n\n        # Do what the browsers do, despite standards...\n        # First, turn 302s into GETs.\n        if response.status_code == codes.found and method != \"HEAD\":\n            method = \"GET\"\n\n        # Second, if a POST is responded to with a 301, turn it into a GET.\n        # This bizarre behaviour is explained in Issue 1704.\n        if response.status_code == codes.moved and method == \"POST\":\n            method = \"GET\"\n\n        prepared_request.method = method\n\n\nclass Session(SessionRedirectMixin):\n    \"\"\"A Requests session.\n\n    Provides cookie persistence, connection-pooling, and configuration.\n\n    Basic Usage::\n\n      >>> import requests\n      >>> s = requests.Session()\n      >>> s.get('https://httpbin.org/get')\n      <Response [200]>\n\n    Or as a context manager::\n\n      >>> with requests.Session() as s:\n      ...     s.get('https://httpbin.org/get')\n      <Response [200]>\n    \"\"\"\n\n    __attrs__ = [\n        \"headers\",\n        \"cookies\",\n        \"auth\",\n        \"proxies\",\n        \"hooks\",\n        \"params\",\n        \"verify\",\n        \"cert\",\n        \"adapters\",\n        \"stream\",\n        \"trust_env\",\n        \"max_redirects\",\n    ]\n\n    def __init__(self):\n\n        #: A case-insensitive dictionary of headers to be sent on each\n        #: :class:`Request <Request>` sent from this\n        #: :class:`Session <Session>`.\n        self.headers = default_headers()\n\n        #: Default Authentication tuple or object to attach to\n        #: :class:`Request <Request>`.\n        self.auth = None\n\n        #: Dictionary mapping protocol or protocol and host to the URL of the proxy\n        #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to\n        #: be used on each :class:`Request <Request>`.\n        self.proxies = {}\n\n        #: Event-handling hooks.\n        self.hooks = default_hooks()\n\n        #: Dictionary of querystring data to attach to each\n        #: :class:`Request <Request>`. The dictionary values may be lists for\n        #: representing multivalued query parameters.\n        self.params = {}\n\n        #: Stream response content default.\n        self.stream = False\n\n        #: SSL Verification default.\n        #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n        #: remote end.\n        #: If verify is set to `False`, requests will accept any TLS certificate\n        #: presented by the server, and will ignore hostname mismatches and/or\n        #: expired certificates, which will make your application vulnerable to\n        #: man-in-the-middle (MitM) attacks.\n        #: Only set this to `False` for testing.\n        self.verify = True\n\n        #: SSL client certificate default, if String, path to ssl client\n        #: cert file (.pem). If Tuple, ('cert', 'key') pair.\n        self.cert = None\n\n        #: Maximum number of redirects allowed. If the request exceeds this\n        #: limit, a :class:`TooManyRedirects` exception is raised.\n        #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is\n        #: 30.\n        self.max_redirects = DEFAULT_REDIRECT_LIMIT\n\n        #: Trust environment settings for proxy configuration, default\n        #: authentication and similar.\n        self.trust_env = True\n\n        #: A CookieJar containing all currently outstanding cookies set on this\n        #: session. By default it is a\n        #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but\n        #: may be any other ``cookielib.CookieJar`` compatible object.\n        self.cookies = cookiejar_from_dict({})\n\n        # Default connection adapters.\n        self.adapters = OrderedDict()\n        self.mount(\"https://\", HTTPAdapter())\n        self.mount(\"http://\", HTTPAdapter())\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *args):\n        self.close()\n\n    def prepare_request(self, request):\n        \"\"\"Constructs a :class:`PreparedRequest <PreparedRequest>` for\n        transmission and returns it. The :class:`PreparedRequest` has settings\n        merged from the :class:`Request <Request>` instance and those of the\n        :class:`Session`.\n\n        :param request: :class:`Request` instance to prepare with this\n            session's settings.\n        :rtype: requests.PreparedRequest\n        \"\"\"\n        cookies = request.cookies or {}\n\n        # Bootstrap CookieJar.\n        if not isinstance(cookies, cookielib.CookieJar):\n            cookies = cookiejar_from_dict(cookies)\n\n        # Merge with session cookies\n        merged_cookies = merge_cookies(\n            merge_cookies(RequestsCookieJar(), self.cookies), cookies\n        )\n\n        # Set environment's basic authentication if not explicitly set.\n        auth = request.auth\n        if self.trust_env and not auth and not self.auth:\n            auth = get_netrc_auth(request.url)\n\n        p = PreparedRequest()\n        p.prepare(\n            method=request.method.upper(),\n            url=request.url,\n            files=request.files,\n            data=request.data,\n            json=request.json,\n            headers=merge_setting(\n                request.headers, self.headers, dict_class=CaseInsensitiveDict\n            ),\n            params=merge_setting(request.params, self.params),\n            auth=merge_setting(auth, self.auth),\n            cookies=merged_cookies,\n            hooks=merge_hooks(request.hooks, self.hooks),\n        )\n        return p\n\n    def request(\n        self,\n        method,\n        url,\n        params=None,\n        data=None,\n        headers=None,\n        cookies=None,\n        files=None,\n        auth=None,\n        timeout=None,\n        allow_redirects=True,\n        proxies=None,\n        hooks=None,\n        stream=None,\n        verify=None,\n        cert=None,\n        json=None,\n    ):\n        \"\"\"Constructs a :class:`Request <Request>`, prepares it and sends it.\n        Returns :class:`Response <Response>` object.\n\n        :param method: method for the new :class:`Request` object.\n        :param url: URL for the new :class:`Request` object.\n        :param params: (optional) Dictionary or bytes to be sent in the query\n            string for the :class:`Request`.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the\n            :class:`Request`.\n        :param headers: (optional) Dictionary of HTTP Headers to send with the\n            :class:`Request`.\n        :param cookies: (optional) Dict or CookieJar object to send with the\n            :class:`Request`.\n        :param files: (optional) Dictionary of ``'filename': file-like-objects``\n            for multipart encoding upload.\n        :param auth: (optional) Auth tuple or callable to enable\n            Basic/Digest/Custom HTTP Auth.\n        :param timeout: (optional) How long to wait for the server to send\n            data before giving up, as a float, or a :ref:`(connect timeout,\n            read timeout) <timeouts>` tuple.\n        :type timeout: float or tuple\n        :param allow_redirects: (optional) Set to True by default.\n        :type allow_redirects: bool\n        :param proxies: (optional) Dictionary mapping protocol or protocol and\n            hostname to the URL of the proxy.\n        :param stream: (optional) whether to immediately download the response\n            content. Defaults to ``False``.\n        :param verify: (optional) Either a boolean, in which case it controls whether we verify\n            the server's TLS certificate, or a string, in which case it must be a path\n            to a CA bundle to use. Defaults to ``True``. When set to\n            ``False``, requests will accept any TLS certificate presented by\n            the server, and will ignore hostname mismatches and/or expired\n            certificates, which will make your application vulnerable to\n            man-in-the-middle (MitM) attacks. Setting verify to ``False``\n            may be useful during local development or testing.\n        :param cert: (optional) if String, path to ssl client cert file (.pem).\n            If Tuple, ('cert', 'key') pair.\n        :rtype: requests.Response\n        \"\"\"\n        # Create the Request.\n        req = Request(\n            method=method.upper(),\n            url=url,\n            headers=headers,\n            files=files,\n            data=data or {},\n            json=json,\n            params=params or {},\n            auth=auth,\n            cookies=cookies,\n            hooks=hooks,\n        )\n        prep = self.prepare_request(req)\n\n        proxies = proxies or {}\n\n        settings = self.merge_environment_settings(\n            prep.url, proxies, stream, verify, cert\n        )\n\n        # Send the request.\n        send_kwargs = {\n            \"timeout\": timeout,\n            \"allow_redirects\": allow_redirects,\n        }\n        send_kwargs.update(settings)\n        resp = self.send(prep, **send_kwargs)\n\n        return resp\n\n    def get(self, url, **kwargs):\n        r\"\"\"Sends a GET request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"GET\", url, **kwargs)\n\n    def options(self, url, **kwargs):\n        r\"\"\"Sends a OPTIONS request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", True)\n        return self.request(\"OPTIONS\", url, **kwargs)\n\n    def head(self, url, **kwargs):\n        r\"\"\"Sends a HEAD request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        kwargs.setdefault(\"allow_redirects\", False)\n        return self.request(\"HEAD\", url, **kwargs)\n\n    def post(self, url, data=None, json=None, **kwargs):\n        r\"\"\"Sends a POST request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param json: (optional) json to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"POST\", url, data=data, json=json, **kwargs)\n\n    def put(self, url, data=None, **kwargs):\n        r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PUT\", url, data=data, **kwargs)\n\n    def patch(self, url, data=None, **kwargs):\n        r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n            object to send in the body of the :class:`Request`.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"PATCH\", url, data=data, **kwargs)\n\n    def delete(self, url, **kwargs):\n        r\"\"\"Sends a DELETE request. Returns :class:`Response` object.\n\n        :param url: URL for the new :class:`Request` object.\n        :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n        :rtype: requests.Response\n        \"\"\"\n\n        return self.request(\"DELETE\", url, **kwargs)\n\n    def send(self, request, **kwargs):\n        \"\"\"Send a given PreparedRequest.\n\n        :rtype: requests.Response\n        \"\"\"\n        # Set defaults that the hooks can utilize to ensure they always have\n        # the correct parameters to reproduce the previous request.\n        kwargs.setdefault(\"stream\", self.stream)\n        kwargs.setdefault(\"verify\", self.verify)\n        kwargs.setdefault(\"cert\", self.cert)\n        if \"proxies\" not in kwargs:\n            kwargs[\"proxies\"] = resolve_proxies(request, self.proxies, self.trust_env)\n\n        # It's possible that users might accidentally send a Request object.\n        # Guard against that specific failure case.\n        if isinstance(request, Request):\n            raise ValueError(\"You can only send PreparedRequests.\")\n\n        # Set up variables needed for resolve_redirects and dispatching of hooks\n        allow_redirects = kwargs.pop(\"allow_redirects\", True)\n        stream = kwargs.get(\"stream\")\n        hooks = request.hooks\n\n        # Get the appropriate adapter to use\n        adapter = self.get_adapter(url=request.url)\n\n        # Start time (approximately) of the request\n        start = preferred_clock()\n\n        # Send the request\n        r = adapter.send(request, **kwargs)\n\n        # Total elapsed time of the request (approximately)\n        elapsed = preferred_clock() - start\n        r.elapsed = timedelta(seconds=elapsed)\n\n        # Response manipulation hooks\n        r = dispatch_hook(\"response\", hooks, r, **kwargs)\n\n        # Persist cookies\n        if r.history:\n\n            # If the hooks create history then we want those cookies too\n            for resp in r.history:\n                extract_cookies_to_jar(self.cookies, resp.request, resp.raw)\n\n        extract_cookies_to_jar(self.cookies, request, r.raw)\n\n        # Resolve redirects if allowed.\n        if allow_redirects:\n            # Redirect resolving generator.\n            gen = self.resolve_redirects(r, request, **kwargs)\n            history = [resp for resp in gen]\n        else:\n            history = []\n\n        # Shuffle things around if there's history.\n        if history:\n            # Insert the first (original) request at the start\n            history.insert(0, r)\n            # Get the last request made\n            r = history.pop()\n            r.history = history\n\n        # If redirects aren't being followed, store the response on the Request for Response.next().\n        if not allow_redirects:\n            try:\n                r._next = next(\n                    self.resolve_redirects(r, request, yield_requests=True, **kwargs)\n                )\n            except StopIteration:\n                pass\n\n        if not stream:\n            r.content\n\n        return r\n\n    def merge_environment_settings(self, url, proxies, stream, verify, cert):\n        \"\"\"\n        Check the environment and merge it with some settings.\n\n        :rtype: dict\n        \"\"\"\n        # Gather clues from the surrounding environment.\n        if self.trust_env:\n            # Set environment's proxies.\n            no_proxy = proxies.get(\"no_proxy\") if proxies is not None else None\n            env_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n            for (k, v) in env_proxies.items():\n                proxies.setdefault(k, v)\n\n            # Look for requests environment configuration\n            # and be compatible with cURL.\n            if verify is True or verify is None:\n                verify = (\n                    os.environ.get(\"REQUESTS_CA_BUNDLE\")\n                    or os.environ.get(\"CURL_CA_BUNDLE\")\n                    or verify\n                )\n\n        # Merge all the kwargs.\n        proxies = merge_setting(proxies, self.proxies)\n        stream = merge_setting(stream, self.stream)\n        verify = merge_setting(verify, self.verify)\n        cert = merge_setting(cert, self.cert)\n\n        return {\"proxies\": proxies, \"stream\": stream, \"verify\": verify, \"cert\": cert}\n\n    def get_adapter(self, url):\n        \"\"\"\n        Returns the appropriate connection adapter for the given URL.\n\n        :rtype: requests.adapters.BaseAdapter\n        \"\"\"\n        for (prefix, adapter) in self.adapters.items():\n\n            if url.lower().startswith(prefix.lower()):\n                return adapter\n\n        # Nothing matches :-/\n        raise InvalidSchema(f\"No connection adapters were found for {url!r}\")\n\n    def close(self):\n        \"\"\"Closes all adapters and as such the session\"\"\"\n        for v in self.adapters.values():\n            v.close()\n\n    def mount(self, prefix, adapter):\n        \"\"\"Registers a connection adapter to a prefix.\n\n        Adapters are sorted in descending order by prefix length.\n        \"\"\"\n        self.adapters[prefix] = adapter\n        keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]\n\n        for key in keys_to_move:\n            self.adapters[key] = self.adapters.pop(key)\n\n    def __getstate__(self):\n        state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n        return state\n\n    def __setstate__(self, state):\n        for attr, value in state.items():\n            setattr(self, attr, value)\n\n\ndef session():\n    \"\"\"\n    Returns a :class:`Session` for context-management.\n\n    .. deprecated:: 1.0.0\n\n        This method has been deprecated since version 1.0.0 and is only kept for\n        backwards compatibility. New code should use :class:`~requests.sessions.Session`\n        to create a session. This may be removed at a future date.\n\n    :rtype: Session\n    \"\"\"\n    return Session()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/status_codes.py",
    "content": "r\"\"\"\nThe ``codes`` object defines a mapping from common names for HTTP statuses\nto their numerical codes, accessible either as attributes or as dictionary\nitems.\n\nExample::\n\n    >>> import requests\n    >>> requests.codes['temporary_redirect']\n    307\n    >>> requests.codes.teapot\n    418\n    >>> requests.codes['\\o/']\n    200\n\nSome codes have multiple names, and both upper- and lower-case versions of\nthe names are allowed. For example, ``codes.ok``, ``codes.OK``, and\n``codes.okay`` all correspond to the HTTP status code 200.\n\"\"\"\n\nfrom .structures import LookupDict\n\n_codes = {\n    # Informational.\n    100: (\"continue\",),\n    101: (\"switching_protocols\",),\n    102: (\"processing\",),\n    103: (\"checkpoint\",),\n    122: (\"uri_too_long\", \"request_uri_too_long\"),\n    200: (\"ok\", \"okay\", \"all_ok\", \"all_okay\", \"all_good\", \"\\\\o/\", \"✓\"),\n    201: (\"created\",),\n    202: (\"accepted\",),\n    203: (\"non_authoritative_info\", \"non_authoritative_information\"),\n    204: (\"no_content\",),\n    205: (\"reset_content\", \"reset\"),\n    206: (\"partial_content\", \"partial\"),\n    207: (\"multi_status\", \"multiple_status\", \"multi_stati\", \"multiple_stati\"),\n    208: (\"already_reported\",),\n    226: (\"im_used\",),\n    # Redirection.\n    300: (\"multiple_choices\",),\n    301: (\"moved_permanently\", \"moved\", \"\\\\o-\"),\n    302: (\"found\",),\n    303: (\"see_other\", \"other\"),\n    304: (\"not_modified\",),\n    305: (\"use_proxy\",),\n    306: (\"switch_proxy\",),\n    307: (\"temporary_redirect\", \"temporary_moved\", \"temporary\"),\n    308: (\n        \"permanent_redirect\",\n        \"resume_incomplete\",\n        \"resume\",\n    ),  # \"resume\" and \"resume_incomplete\" to be removed in 3.0\n    # Client Error.\n    400: (\"bad_request\", \"bad\"),\n    401: (\"unauthorized\",),\n    402: (\"payment_required\", \"payment\"),\n    403: (\"forbidden\",),\n    404: (\"not_found\", \"-o-\"),\n    405: (\"method_not_allowed\", \"not_allowed\"),\n    406: (\"not_acceptable\",),\n    407: (\"proxy_authentication_required\", \"proxy_auth\", \"proxy_authentication\"),\n    408: (\"request_timeout\", \"timeout\"),\n    409: (\"conflict\",),\n    410: (\"gone\",),\n    411: (\"length_required\",),\n    412: (\"precondition_failed\", \"precondition\"),\n    413: (\"request_entity_too_large\",),\n    414: (\"request_uri_too_large\",),\n    415: (\"unsupported_media_type\", \"unsupported_media\", \"media_type\"),\n    416: (\n        \"requested_range_not_satisfiable\",\n        \"requested_range\",\n        \"range_not_satisfiable\",\n    ),\n    417: (\"expectation_failed\",),\n    418: (\"im_a_teapot\", \"teapot\", \"i_am_a_teapot\"),\n    421: (\"misdirected_request\",),\n    422: (\"unprocessable_entity\", \"unprocessable\"),\n    423: (\"locked\",),\n    424: (\"failed_dependency\", \"dependency\"),\n    425: (\"unordered_collection\", \"unordered\"),\n    426: (\"upgrade_required\", \"upgrade\"),\n    428: (\"precondition_required\", \"precondition\"),\n    429: (\"too_many_requests\", \"too_many\"),\n    431: (\"header_fields_too_large\", \"fields_too_large\"),\n    444: (\"no_response\", \"none\"),\n    449: (\"retry_with\", \"retry\"),\n    450: (\"blocked_by_windows_parental_controls\", \"parental_controls\"),\n    451: (\"unavailable_for_legal_reasons\", \"legal_reasons\"),\n    499: (\"client_closed_request\",),\n    # Server Error.\n    500: (\"internal_server_error\", \"server_error\", \"/o\\\\\", \"✗\"),\n    501: (\"not_implemented\",),\n    502: (\"bad_gateway\",),\n    503: (\"service_unavailable\", \"unavailable\"),\n    504: (\"gateway_timeout\",),\n    505: (\"http_version_not_supported\", \"http_version\"),\n    506: (\"variant_also_negotiates\",),\n    507: (\"insufficient_storage\",),\n    509: (\"bandwidth_limit_exceeded\", \"bandwidth\"),\n    510: (\"not_extended\",),\n    511: (\"network_authentication_required\", \"network_auth\", \"network_authentication\"),\n}\n\ncodes = LookupDict(name=\"status_codes\")\n\n\ndef _init():\n    for code, titles in _codes.items():\n        for title in titles:\n            setattr(codes, title, code)\n            if not title.startswith((\"\\\\\", \"/\")):\n                setattr(codes, title.upper(), code)\n\n    def doc(code):\n        names = \", \".join(f\"``{n}``\" for n in _codes[code])\n        return \"* %d: %s\" % (code, names)\n\n    global __doc__\n    __doc__ = (\n        __doc__ + \"\\n\" + \"\\n\".join(doc(code) for code in sorted(_codes))\n        if __doc__ is not None\n        else None\n    )\n\n\n_init()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/structures.py",
    "content": "\"\"\"\nrequests.structures\n~~~~~~~~~~~~~~~~~~~\n\nData structures that power Requests.\n\"\"\"\n\nfrom collections import OrderedDict\n\nfrom .compat import Mapping, MutableMapping\n\n\nclass CaseInsensitiveDict(MutableMapping):\n    \"\"\"A case-insensitive ``dict``-like object.\n\n    Implements all methods and operations of\n    ``MutableMapping`` as well as dict's ``copy``. Also\n    provides ``lower_items``.\n\n    All keys are expected to be strings. The structure remembers the\n    case of the last key to be set, and ``iter(instance)``,\n    ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``\n    will contain case-sensitive keys. However, querying and contains\n    testing is case insensitive::\n\n        cid = CaseInsensitiveDict()\n        cid['Accept'] = 'application/json'\n        cid['aCCEPT'] == 'application/json'  # True\n        list(cid) == ['Accept']  # True\n\n    For example, ``headers['content-encoding']`` will return the\n    value of a ``'Content-Encoding'`` response header, regardless\n    of how the header name was originally stored.\n\n    If the constructor, ``.update``, or equality comparison\n    operations are given keys that have equal ``.lower()``s, the\n    behavior is undefined.\n    \"\"\"\n\n    def __init__(self, data=None, **kwargs):\n        self._store = OrderedDict()\n        if data is None:\n            data = {}\n        self.update(data, **kwargs)\n\n    def __setitem__(self, key, value):\n        # Use the lowercased key for lookups, but store the actual\n        # key alongside the value.\n        self._store[key.lower()] = (key, value)\n\n    def __getitem__(self, key):\n        return self._store[key.lower()][1]\n\n    def __delitem__(self, key):\n        del self._store[key.lower()]\n\n    def __iter__(self):\n        return (casedkey for casedkey, mappedvalue in self._store.values())\n\n    def __len__(self):\n        return len(self._store)\n\n    def lower_items(self):\n        \"\"\"Like iteritems(), but with all lowercase keys.\"\"\"\n        return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())\n\n    def __eq__(self, other):\n        if isinstance(other, Mapping):\n            other = CaseInsensitiveDict(other)\n        else:\n            return NotImplemented\n        # Compare insensitively\n        return dict(self.lower_items()) == dict(other.lower_items())\n\n    # Copy is required\n    def copy(self):\n        return CaseInsensitiveDict(self._store.values())\n\n    def __repr__(self):\n        return str(dict(self.items()))\n\n\nclass LookupDict(dict):\n    \"\"\"Dictionary lookup object.\"\"\"\n\n    def __init__(self, name=None):\n        self.name = name\n        super().__init__()\n\n    def __repr__(self):\n        return f\"<lookup '{self.name}'>\"\n\n    def __getitem__(self, key):\n        # We allow fall-through here, so values default to None\n\n        return self.__dict__.get(key, None)\n\n    def get(self, key, default=None):\n        return self.__dict__.get(key, default)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/requests/utils.py",
    "content": "\"\"\"\nrequests.utils\n~~~~~~~~~~~~~~\n\nThis module provides utility functions that are used within Requests\nthat are also useful for external consumption.\n\"\"\"\n\nimport codecs\nimport contextlib\nimport io\nimport os\nimport re\nimport socket\nimport struct\nimport sys\nimport tempfile\nimport warnings\nimport zipfile\nfrom collections import OrderedDict\n\nfrom pip._vendor.urllib3.util import make_headers, parse_url\n\nfrom . import certs\nfrom .__version__ import __version__\n\n# to_native_string is unused here, but imported here for backwards compatibility\nfrom ._internal_utils import HEADER_VALIDATORS, to_native_string  # noqa: F401\nfrom .compat import (\n    Mapping,\n    basestring,\n    bytes,\n    getproxies,\n    getproxies_environment,\n    integer_types,\n)\nfrom .compat import parse_http_list as _parse_list_header\nfrom .compat import (\n    proxy_bypass,\n    proxy_bypass_environment,\n    quote,\n    str,\n    unquote,\n    urlparse,\n    urlunparse,\n)\nfrom .cookies import cookiejar_from_dict\nfrom .exceptions import (\n    FileModeWarning,\n    InvalidHeader,\n    InvalidURL,\n    UnrewindableBodyError,\n)\nfrom .structures import CaseInsensitiveDict\n\nNETRC_FILES = (\".netrc\", \"_netrc\")\n\nDEFAULT_CA_BUNDLE_PATH = certs.where()\n\nDEFAULT_PORTS = {\"http\": 80, \"https\": 443}\n\n# Ensure that ', ' is used to preserve previous delimiter behavior.\nDEFAULT_ACCEPT_ENCODING = \", \".join(\n    re.split(r\",\\s*\", make_headers(accept_encoding=True)[\"accept-encoding\"])\n)\n\n\nif sys.platform == \"win32\":\n    # provide a proxy_bypass version on Windows without DNS lookups\n\n    def proxy_bypass_registry(host):\n        try:\n            import winreg\n        except ImportError:\n            return False\n\n        try:\n            internetSettings = winreg.OpenKey(\n                winreg.HKEY_CURRENT_USER,\n                r\"Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\",\n            )\n            # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it\n            proxyEnable = int(winreg.QueryValueEx(internetSettings, \"ProxyEnable\")[0])\n            # ProxyOverride is almost always a string\n            proxyOverride = winreg.QueryValueEx(internetSettings, \"ProxyOverride\")[0]\n        except (OSError, ValueError):\n            return False\n        if not proxyEnable or not proxyOverride:\n            return False\n\n        # make a check value list from the registry entry: replace the\n        # '<local>' string by the localhost entry and the corresponding\n        # canonical entry.\n        proxyOverride = proxyOverride.split(\";\")\n        # now check if we match one of the registry values.\n        for test in proxyOverride:\n            if test == \"<local>\":\n                if \".\" not in host:\n                    return True\n            test = test.replace(\".\", r\"\\.\")  # mask dots\n            test = test.replace(\"*\", r\".*\")  # change glob sequence\n            test = test.replace(\"?\", r\".\")  # change glob char\n            if re.match(test, host, re.I):\n                return True\n        return False\n\n    def proxy_bypass(host):  # noqa\n        \"\"\"Return True, if the host should be bypassed.\n\n        Checks proxy settings gathered from the environment, if specified,\n        or the registry.\n        \"\"\"\n        if getproxies_environment():\n            return proxy_bypass_environment(host)\n        else:\n            return proxy_bypass_registry(host)\n\n\ndef dict_to_sequence(d):\n    \"\"\"Returns an internal sequence dictionary update.\"\"\"\n\n    if hasattr(d, \"items\"):\n        d = d.items()\n\n    return d\n\n\ndef super_len(o):\n    total_length = None\n    current_position = 0\n\n    if hasattr(o, \"__len__\"):\n        total_length = len(o)\n\n    elif hasattr(o, \"len\"):\n        total_length = o.len\n\n    elif hasattr(o, \"fileno\"):\n        try:\n            fileno = o.fileno()\n        except (io.UnsupportedOperation, AttributeError):\n            # AttributeError is a surprising exception, seeing as how we've just checked\n            # that `hasattr(o, 'fileno')`.  It happens for objects obtained via\n            # `Tarfile.extractfile()`, per issue 5229.\n            pass\n        else:\n            total_length = os.fstat(fileno).st_size\n\n            # Having used fstat to determine the file length, we need to\n            # confirm that this file was opened up in binary mode.\n            if \"b\" not in o.mode:\n                warnings.warn(\n                    (\n                        \"Requests has determined the content-length for this \"\n                        \"request using the binary size of the file: however, the \"\n                        \"file has been opened in text mode (i.e. without the 'b' \"\n                        \"flag in the mode). This may lead to an incorrect \"\n                        \"content-length. In Requests 3.0, support will be removed \"\n                        \"for files in text mode.\"\n                    ),\n                    FileModeWarning,\n                )\n\n    if hasattr(o, \"tell\"):\n        try:\n            current_position = o.tell()\n        except OSError:\n            # This can happen in some weird situations, such as when the file\n            # is actually a special file descriptor like stdin. In this\n            # instance, we don't know what the length is, so set it to zero and\n            # let requests chunk it instead.\n            if total_length is not None:\n                current_position = total_length\n        else:\n            if hasattr(o, \"seek\") and total_length is None:\n                # StringIO and BytesIO have seek but no usable fileno\n                try:\n                    # seek to end of file\n                    o.seek(0, 2)\n                    total_length = o.tell()\n\n                    # seek back to current position to support\n                    # partially read file-like objects\n                    o.seek(current_position or 0)\n                except OSError:\n                    total_length = 0\n\n    if total_length is None:\n        total_length = 0\n\n    return max(0, total_length - current_position)\n\n\ndef get_netrc_auth(url, raise_errors=False):\n    \"\"\"Returns the Requests tuple auth for a given url from netrc.\"\"\"\n\n    netrc_file = os.environ.get(\"NETRC\")\n    if netrc_file is not None:\n        netrc_locations = (netrc_file,)\n    else:\n        netrc_locations = (f\"~/{f}\" for f in NETRC_FILES)\n\n    try:\n        from netrc import NetrcParseError, netrc\n\n        netrc_path = None\n\n        for f in netrc_locations:\n            try:\n                loc = os.path.expanduser(f)\n            except KeyError:\n                # os.path.expanduser can fail when $HOME is undefined and\n                # getpwuid fails. See https://bugs.python.org/issue20164 &\n                # https://github.com/psf/requests/issues/1846\n                return\n\n            if os.path.exists(loc):\n                netrc_path = loc\n                break\n\n        # Abort early if there isn't one.\n        if netrc_path is None:\n            return\n\n        ri = urlparse(url)\n\n        # Strip port numbers from netloc. This weird `if...encode`` dance is\n        # used for Python 3.2, which doesn't support unicode literals.\n        splitstr = b\":\"\n        if isinstance(url, str):\n            splitstr = splitstr.decode(\"ascii\")\n        host = ri.netloc.split(splitstr)[0]\n\n        try:\n            _netrc = netrc(netrc_path).authenticators(host)\n            if _netrc:\n                # Return with login / password\n                login_i = 0 if _netrc[0] else 1\n                return (_netrc[login_i], _netrc[2])\n        except (NetrcParseError, OSError):\n            # If there was a parsing error or a permissions issue reading the file,\n            # we'll just skip netrc auth unless explicitly asked to raise errors.\n            if raise_errors:\n                raise\n\n    # App Engine hackiness.\n    except (ImportError, AttributeError):\n        pass\n\n\ndef guess_filename(obj):\n    \"\"\"Tries to guess the filename of the given object.\"\"\"\n    name = getattr(obj, \"name\", None)\n    if name and isinstance(name, basestring) and name[0] != \"<\" and name[-1] != \">\":\n        return os.path.basename(name)\n\n\ndef extract_zipped_paths(path):\n    \"\"\"Replace nonexistent paths that look like they refer to a member of a zip\n    archive with the location of an extracted copy of the target, or else\n    just return the provided path unchanged.\n    \"\"\"\n    if os.path.exists(path):\n        # this is already a valid path, no need to do anything further\n        return path\n\n    # find the first valid part of the provided path and treat that as a zip archive\n    # assume the rest of the path is the name of a member in the archive\n    archive, member = os.path.split(path)\n    while archive and not os.path.exists(archive):\n        archive, prefix = os.path.split(archive)\n        if not prefix:\n            # If we don't check for an empty prefix after the split (in other words, archive remains unchanged after the split),\n            # we _can_ end up in an infinite loop on a rare corner case affecting a small number of users\n            break\n        member = \"/\".join([prefix, member])\n\n    if not zipfile.is_zipfile(archive):\n        return path\n\n    zip_file = zipfile.ZipFile(archive)\n    if member not in zip_file.namelist():\n        return path\n\n    # we have a valid zip archive and a valid member of that archive\n    tmp = tempfile.gettempdir()\n    extracted_path = os.path.join(tmp, member.split(\"/\")[-1])\n    if not os.path.exists(extracted_path):\n        # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition\n        with atomic_open(extracted_path) as file_handler:\n            file_handler.write(zip_file.read(member))\n    return extracted_path\n\n\n@contextlib.contextmanager\ndef atomic_open(filename):\n    \"\"\"Write a file to the disk in an atomic fashion\"\"\"\n    tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))\n    try:\n        with os.fdopen(tmp_descriptor, \"wb\") as tmp_handler:\n            yield tmp_handler\n        os.replace(tmp_name, filename)\n    except BaseException:\n        os.remove(tmp_name)\n        raise\n\n\ndef from_key_val_list(value):\n    \"\"\"Take an object and test to see if it can be represented as a\n    dictionary. Unless it can not be represented as such, return an\n    OrderedDict, e.g.,\n\n    ::\n\n        >>> from_key_val_list([('key', 'val')])\n        OrderedDict([('key', 'val')])\n        >>> from_key_val_list('string')\n        Traceback (most recent call last):\n        ...\n        ValueError: cannot encode objects that are not 2-tuples\n        >>> from_key_val_list({'key': 'val'})\n        OrderedDict([('key', 'val')])\n\n    :rtype: OrderedDict\n    \"\"\"\n    if value is None:\n        return None\n\n    if isinstance(value, (str, bytes, bool, int)):\n        raise ValueError(\"cannot encode objects that are not 2-tuples\")\n\n    return OrderedDict(value)\n\n\ndef to_key_val_list(value):\n    \"\"\"Take an object and test to see if it can be represented as a\n    dictionary. If it can be, return a list of tuples, e.g.,\n\n    ::\n\n        >>> to_key_val_list([('key', 'val')])\n        [('key', 'val')]\n        >>> to_key_val_list({'key': 'val'})\n        [('key', 'val')]\n        >>> to_key_val_list('string')\n        Traceback (most recent call last):\n        ...\n        ValueError: cannot encode objects that are not 2-tuples\n\n    :rtype: list\n    \"\"\"\n    if value is None:\n        return None\n\n    if isinstance(value, (str, bytes, bool, int)):\n        raise ValueError(\"cannot encode objects that are not 2-tuples\")\n\n    if isinstance(value, Mapping):\n        value = value.items()\n\n    return list(value)\n\n\n# From mitsuhiko/werkzeug (used with permission).\ndef parse_list_header(value):\n    \"\"\"Parse lists as described by RFC 2068 Section 2.\n\n    In particular, parse comma-separated lists where the elements of\n    the list may include quoted-strings.  A quoted-string could\n    contain a comma.  A non-quoted string could have quotes in the\n    middle.  Quotes are removed automatically after parsing.\n\n    It basically works like :func:`parse_set_header` just that items\n    may appear multiple times and case sensitivity is preserved.\n\n    The return value is a standard :class:`list`:\n\n    >>> parse_list_header('token, \"quoted value\"')\n    ['token', 'quoted value']\n\n    To create a header from the :class:`list` again, use the\n    :func:`dump_header` function.\n\n    :param value: a string with a list header.\n    :return: :class:`list`\n    :rtype: list\n    \"\"\"\n    result = []\n    for item in _parse_list_header(value):\n        if item[:1] == item[-1:] == '\"':\n            item = unquote_header_value(item[1:-1])\n        result.append(item)\n    return result\n\n\n# From mitsuhiko/werkzeug (used with permission).\ndef parse_dict_header(value):\n    \"\"\"Parse lists of key, value pairs as described by RFC 2068 Section 2 and\n    convert them into a python dict:\n\n    >>> d = parse_dict_header('foo=\"is a fish\", bar=\"as well\"')\n    >>> type(d) is dict\n    True\n    >>> sorted(d.items())\n    [('bar', 'as well'), ('foo', 'is a fish')]\n\n    If there is no value for a key it will be `None`:\n\n    >>> parse_dict_header('key_without_value')\n    {'key_without_value': None}\n\n    To create a header from the :class:`dict` again, use the\n    :func:`dump_header` function.\n\n    :param value: a string with a dict header.\n    :return: :class:`dict`\n    :rtype: dict\n    \"\"\"\n    result = {}\n    for item in _parse_list_header(value):\n        if \"=\" not in item:\n            result[item] = None\n            continue\n        name, value = item.split(\"=\", 1)\n        if value[:1] == value[-1:] == '\"':\n            value = unquote_header_value(value[1:-1])\n        result[name] = value\n    return result\n\n\n# From mitsuhiko/werkzeug (used with permission).\ndef unquote_header_value(value, is_filename=False):\n    r\"\"\"Unquotes a header value.  (Reversal of :func:`quote_header_value`).\n    This does not use the real unquoting but what browsers are actually\n    using for quoting.\n\n    :param value: the header value to unquote.\n    :rtype: str\n    \"\"\"\n    if value and value[0] == value[-1] == '\"':\n        # this is not the real unquoting, but fixing this so that the\n        # RFC is met will result in bugs with internet explorer and\n        # probably some other browsers as well.  IE for example is\n        # uploading files with \"C:\\foo\\bar.txt\" as filename\n        value = value[1:-1]\n\n        # if this is a filename and the starting characters look like\n        # a UNC path, then just return the value without quotes.  Using the\n        # replace sequence below on a UNC path has the effect of turning\n        # the leading double slash into a single slash and then\n        # _fix_ie_filename() doesn't work correctly.  See #458.\n        if not is_filename or value[:2] != \"\\\\\\\\\":\n            return value.replace(\"\\\\\\\\\", \"\\\\\").replace('\\\\\"', '\"')\n    return value\n\n\ndef dict_from_cookiejar(cj):\n    \"\"\"Returns a key/value dictionary from a CookieJar.\n\n    :param cj: CookieJar object to extract cookies from.\n    :rtype: dict\n    \"\"\"\n\n    cookie_dict = {}\n\n    for cookie in cj:\n        cookie_dict[cookie.name] = cookie.value\n\n    return cookie_dict\n\n\ndef add_dict_to_cookiejar(cj, cookie_dict):\n    \"\"\"Returns a CookieJar from a key/value dictionary.\n\n    :param cj: CookieJar to insert cookies into.\n    :param cookie_dict: Dict of key/values to insert into CookieJar.\n    :rtype: CookieJar\n    \"\"\"\n\n    return cookiejar_from_dict(cookie_dict, cj)\n\n\ndef get_encodings_from_content(content):\n    \"\"\"Returns encodings from given content string.\n\n    :param content: bytestring to extract encodings from.\n    \"\"\"\n    warnings.warn(\n        (\n            \"In requests 3.0, get_encodings_from_content will be removed. For \"\n            \"more information, please see the discussion on issue #2266. (This\"\n            \" warning should only appear once.)\"\n        ),\n        DeprecationWarning,\n    )\n\n    charset_re = re.compile(r'<meta.*?charset=[\"\\']*(.+?)[\"\\'>]', flags=re.I)\n    pragma_re = re.compile(r'<meta.*?content=[\"\\']*;?charset=(.+?)[\"\\'>]', flags=re.I)\n    xml_re = re.compile(r'^<\\?xml.*?encoding=[\"\\']*(.+?)[\"\\'>]')\n\n    return (\n        charset_re.findall(content)\n        + pragma_re.findall(content)\n        + xml_re.findall(content)\n    )\n\n\ndef _parse_content_type_header(header):\n    \"\"\"Returns content type and parameters from given header\n\n    :param header: string\n    :return: tuple containing content type and dictionary of\n         parameters\n    \"\"\"\n\n    tokens = header.split(\";\")\n    content_type, params = tokens[0].strip(), tokens[1:]\n    params_dict = {}\n    items_to_strip = \"\\\"' \"\n\n    for param in params:\n        param = param.strip()\n        if param:\n            key, value = param, True\n            index_of_equals = param.find(\"=\")\n            if index_of_equals != -1:\n                key = param[:index_of_equals].strip(items_to_strip)\n                value = param[index_of_equals + 1 :].strip(items_to_strip)\n            params_dict[key.lower()] = value\n    return content_type, params_dict\n\n\ndef get_encoding_from_headers(headers):\n    \"\"\"Returns encodings from given HTTP Header Dict.\n\n    :param headers: dictionary to extract encoding from.\n    :rtype: str\n    \"\"\"\n\n    content_type = headers.get(\"content-type\")\n\n    if not content_type:\n        return None\n\n    content_type, params = _parse_content_type_header(content_type)\n\n    if \"charset\" in params:\n        return params[\"charset\"].strip(\"'\\\"\")\n\n    if \"text\" in content_type:\n        return \"ISO-8859-1\"\n\n    if \"application/json\" in content_type:\n        # Assume UTF-8 based on RFC 4627: https://www.ietf.org/rfc/rfc4627.txt since the charset was unset\n        return \"utf-8\"\n\n\ndef stream_decode_response_unicode(iterator, r):\n    \"\"\"Stream decodes an iterator.\"\"\"\n\n    if r.encoding is None:\n        yield from iterator\n        return\n\n    decoder = codecs.getincrementaldecoder(r.encoding)(errors=\"replace\")\n    for chunk in iterator:\n        rv = decoder.decode(chunk)\n        if rv:\n            yield rv\n    rv = decoder.decode(b\"\", final=True)\n    if rv:\n        yield rv\n\n\ndef iter_slices(string, slice_length):\n    \"\"\"Iterate over slices of a string.\"\"\"\n    pos = 0\n    if slice_length is None or slice_length <= 0:\n        slice_length = len(string)\n    while pos < len(string):\n        yield string[pos : pos + slice_length]\n        pos += slice_length\n\n\ndef get_unicode_from_response(r):\n    \"\"\"Returns the requested content back in unicode.\n\n    :param r: Response object to get unicode content from.\n\n    Tried:\n\n    1. charset from content-type\n    2. fall back and replace all unicode characters\n\n    :rtype: str\n    \"\"\"\n    warnings.warn(\n        (\n            \"In requests 3.0, get_unicode_from_response will be removed. For \"\n            \"more information, please see the discussion on issue #2266. (This\"\n            \" warning should only appear once.)\"\n        ),\n        DeprecationWarning,\n    )\n\n    tried_encodings = []\n\n    # Try charset from content-type\n    encoding = get_encoding_from_headers(r.headers)\n\n    if encoding:\n        try:\n            return str(r.content, encoding)\n        except UnicodeError:\n            tried_encodings.append(encoding)\n\n    # Fall back:\n    try:\n        return str(r.content, encoding, errors=\"replace\")\n    except TypeError:\n        return r.content\n\n\n# The unreserved URI characters (RFC 3986)\nUNRESERVED_SET = frozenset(\n    \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\" + \"0123456789-._~\"\n)\n\n\ndef unquote_unreserved(uri):\n    \"\"\"Un-escape any percent-escape sequences in a URI that are unreserved\n    characters. This leaves all reserved, illegal and non-ASCII bytes encoded.\n\n    :rtype: str\n    \"\"\"\n    parts = uri.split(\"%\")\n    for i in range(1, len(parts)):\n        h = parts[i][0:2]\n        if len(h) == 2 and h.isalnum():\n            try:\n                c = chr(int(h, 16))\n            except ValueError:\n                raise InvalidURL(f\"Invalid percent-escape sequence: '{h}'\")\n\n            if c in UNRESERVED_SET:\n                parts[i] = c + parts[i][2:]\n            else:\n                parts[i] = f\"%{parts[i]}\"\n        else:\n            parts[i] = f\"%{parts[i]}\"\n    return \"\".join(parts)\n\n\ndef requote_uri(uri):\n    \"\"\"Re-quote the given URI.\n\n    This function passes the given URI through an unquote/quote cycle to\n    ensure that it is fully and consistently quoted.\n\n    :rtype: str\n    \"\"\"\n    safe_with_percent = \"!#$%&'()*+,/:;=?@[]~\"\n    safe_without_percent = \"!#$&'()*+,/:;=?@[]~\"\n    try:\n        # Unquote only the unreserved characters\n        # Then quote only illegal characters (do not quote reserved,\n        # unreserved, or '%')\n        return quote(unquote_unreserved(uri), safe=safe_with_percent)\n    except InvalidURL:\n        # We couldn't unquote the given URI, so let's try quoting it, but\n        # there may be unquoted '%'s in the URI. We need to make sure they're\n        # properly quoted so they do not cause issues elsewhere.\n        return quote(uri, safe=safe_without_percent)\n\n\ndef address_in_network(ip, net):\n    \"\"\"This function allows you to check if an IP belongs to a network subnet\n\n    Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24\n             returns False if ip = 192.168.1.1 and net = 192.168.100.0/24\n\n    :rtype: bool\n    \"\"\"\n    ipaddr = struct.unpack(\"=L\", socket.inet_aton(ip))[0]\n    netaddr, bits = net.split(\"/\")\n    netmask = struct.unpack(\"=L\", socket.inet_aton(dotted_netmask(int(bits))))[0]\n    network = struct.unpack(\"=L\", socket.inet_aton(netaddr))[0] & netmask\n    return (ipaddr & netmask) == (network & netmask)\n\n\ndef dotted_netmask(mask):\n    \"\"\"Converts mask from /xx format to xxx.xxx.xxx.xxx\n\n    Example: if mask is 24 function returns 255.255.255.0\n\n    :rtype: str\n    \"\"\"\n    bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1\n    return socket.inet_ntoa(struct.pack(\">I\", bits))\n\n\ndef is_ipv4_address(string_ip):\n    \"\"\"\n    :rtype: bool\n    \"\"\"\n    try:\n        socket.inet_aton(string_ip)\n    except OSError:\n        return False\n    return True\n\n\ndef is_valid_cidr(string_network):\n    \"\"\"\n    Very simple check of the cidr format in no_proxy variable.\n\n    :rtype: bool\n    \"\"\"\n    if string_network.count(\"/\") == 1:\n        try:\n            mask = int(string_network.split(\"/\")[1])\n        except ValueError:\n            return False\n\n        if mask < 1 or mask > 32:\n            return False\n\n        try:\n            socket.inet_aton(string_network.split(\"/\")[0])\n        except OSError:\n            return False\n    else:\n        return False\n    return True\n\n\n@contextlib.contextmanager\ndef set_environ(env_name, value):\n    \"\"\"Set the environment variable 'env_name' to 'value'\n\n    Save previous value, yield, and then restore the previous value stored in\n    the environment variable 'env_name'.\n\n    If 'value' is None, do nothing\"\"\"\n    value_changed = value is not None\n    if value_changed:\n        old_value = os.environ.get(env_name)\n        os.environ[env_name] = value\n    try:\n        yield\n    finally:\n        if value_changed:\n            if old_value is None:\n                del os.environ[env_name]\n            else:\n                os.environ[env_name] = old_value\n\n\ndef should_bypass_proxies(url, no_proxy):\n    \"\"\"\n    Returns whether we should bypass proxies or not.\n\n    :rtype: bool\n    \"\"\"\n    # Prioritize lowercase environment variables over uppercase\n    # to keep a consistent behaviour with other http projects (curl, wget).\n    def get_proxy(key):\n        return os.environ.get(key) or os.environ.get(key.upper())\n\n    # First check whether no_proxy is defined. If it is, check that the URL\n    # we're getting isn't in the no_proxy list.\n    no_proxy_arg = no_proxy\n    if no_proxy is None:\n        no_proxy = get_proxy(\"no_proxy\")\n    parsed = urlparse(url)\n\n    if parsed.hostname is None:\n        # URLs don't always have hostnames, e.g. file:/// urls.\n        return True\n\n    if no_proxy:\n        # We need to check whether we match here. We need to see if we match\n        # the end of the hostname, both with and without the port.\n        no_proxy = (host for host in no_proxy.replace(\" \", \"\").split(\",\") if host)\n\n        if is_ipv4_address(parsed.hostname):\n            for proxy_ip in no_proxy:\n                if is_valid_cidr(proxy_ip):\n                    if address_in_network(parsed.hostname, proxy_ip):\n                        return True\n                elif parsed.hostname == proxy_ip:\n                    # If no_proxy ip was defined in plain IP notation instead of cidr notation &\n                    # matches the IP of the index\n                    return True\n        else:\n            host_with_port = parsed.hostname\n            if parsed.port:\n                host_with_port += f\":{parsed.port}\"\n\n            for host in no_proxy:\n                if parsed.hostname.endswith(host) or host_with_port.endswith(host):\n                    # The URL does match something in no_proxy, so we don't want\n                    # to apply the proxies on this URL.\n                    return True\n\n    with set_environ(\"no_proxy\", no_proxy_arg):\n        # parsed.hostname can be `None` in cases such as a file URI.\n        try:\n            bypass = proxy_bypass(parsed.hostname)\n        except (TypeError, socket.gaierror):\n            bypass = False\n\n    if bypass:\n        return True\n\n    return False\n\n\ndef get_environ_proxies(url, no_proxy=None):\n    \"\"\"\n    Return a dict of environment proxies.\n\n    :rtype: dict\n    \"\"\"\n    if should_bypass_proxies(url, no_proxy=no_proxy):\n        return {}\n    else:\n        return getproxies()\n\n\ndef select_proxy(url, proxies):\n    \"\"\"Select a proxy for the url, if applicable.\n\n    :param url: The url being for the request\n    :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs\n    \"\"\"\n    proxies = proxies or {}\n    urlparts = urlparse(url)\n    if urlparts.hostname is None:\n        return proxies.get(urlparts.scheme, proxies.get(\"all\"))\n\n    proxy_keys = [\n        urlparts.scheme + \"://\" + urlparts.hostname,\n        urlparts.scheme,\n        \"all://\" + urlparts.hostname,\n        \"all\",\n    ]\n    proxy = None\n    for proxy_key in proxy_keys:\n        if proxy_key in proxies:\n            proxy = proxies[proxy_key]\n            break\n\n    return proxy\n\n\ndef resolve_proxies(request, proxies, trust_env=True):\n    \"\"\"This method takes proxy information from a request and configuration\n    input to resolve a mapping of target proxies. This will consider settings\n    such a NO_PROXY to strip proxy configurations.\n\n    :param request: Request or PreparedRequest\n    :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs\n    :param trust_env: Boolean declaring whether to trust environment configs\n\n    :rtype: dict\n    \"\"\"\n    proxies = proxies if proxies is not None else {}\n    url = request.url\n    scheme = urlparse(url).scheme\n    no_proxy = proxies.get(\"no_proxy\")\n    new_proxies = proxies.copy()\n\n    if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy):\n        environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n\n        proxy = environ_proxies.get(scheme, environ_proxies.get(\"all\"))\n\n        if proxy:\n            new_proxies.setdefault(scheme, proxy)\n    return new_proxies\n\n\ndef default_user_agent(name=\"python-requests\"):\n    \"\"\"\n    Return a string representing the default user agent.\n\n    :rtype: str\n    \"\"\"\n    return f\"{name}/{__version__}\"\n\n\ndef default_headers():\n    \"\"\"\n    :rtype: requests.structures.CaseInsensitiveDict\n    \"\"\"\n    return CaseInsensitiveDict(\n        {\n            \"User-Agent\": default_user_agent(),\n            \"Accept-Encoding\": DEFAULT_ACCEPT_ENCODING,\n            \"Accept\": \"*/*\",\n            \"Connection\": \"keep-alive\",\n        }\n    )\n\n\ndef parse_header_links(value):\n    \"\"\"Return a list of parsed link headers proxies.\n\n    i.e. Link: <http:/.../front.jpeg>; rel=front; type=\"image/jpeg\",<http://.../back.jpeg>; rel=back;type=\"image/jpeg\"\n\n    :rtype: list\n    \"\"\"\n\n    links = []\n\n    replace_chars = \" '\\\"\"\n\n    value = value.strip(replace_chars)\n    if not value:\n        return links\n\n    for val in re.split(\", *<\", value):\n        try:\n            url, params = val.split(\";\", 1)\n        except ValueError:\n            url, params = val, \"\"\n\n        link = {\"url\": url.strip(\"<> '\\\"\")}\n\n        for param in params.split(\";\"):\n            try:\n                key, value = param.split(\"=\")\n            except ValueError:\n                break\n\n            link[key.strip(replace_chars)] = value.strip(replace_chars)\n\n        links.append(link)\n\n    return links\n\n\n# Null bytes; no need to recreate these on each call to guess_json_utf\n_null = \"\\x00\".encode(\"ascii\")  # encoding to ASCII for Python 3\n_null2 = _null * 2\n_null3 = _null * 3\n\n\ndef guess_json_utf(data):\n    \"\"\"\n    :rtype: str\n    \"\"\"\n    # JSON always starts with two ASCII characters, so detection is as\n    # easy as counting the nulls and from their location and count\n    # determine the encoding. Also detect a BOM, if present.\n    sample = data[:4]\n    if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):\n        return \"utf-32\"  # BOM included\n    if sample[:3] == codecs.BOM_UTF8:\n        return \"utf-8-sig\"  # BOM included, MS style (discouraged)\n    if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):\n        return \"utf-16\"  # BOM included\n    nullcount = sample.count(_null)\n    if nullcount == 0:\n        return \"utf-8\"\n    if nullcount == 2:\n        if sample[::2] == _null2:  # 1st and 3rd are null\n            return \"utf-16-be\"\n        if sample[1::2] == _null2:  # 2nd and 4th are null\n            return \"utf-16-le\"\n        # Did not detect 2 valid UTF-16 ascii-range characters\n    if nullcount == 3:\n        if sample[:3] == _null3:\n            return \"utf-32-be\"\n        if sample[1:] == _null3:\n            return \"utf-32-le\"\n        # Did not detect a valid UTF-32 ascii-range character\n    return None\n\n\ndef prepend_scheme_if_needed(url, new_scheme):\n    \"\"\"Given a URL that may or may not have a scheme, prepend the given scheme.\n    Does not replace a present scheme with the one provided as an argument.\n\n    :rtype: str\n    \"\"\"\n    parsed = parse_url(url)\n    scheme, auth, host, port, path, query, fragment = parsed\n\n    # A defect in urlparse determines that there isn't a netloc present in some\n    # urls. We previously assumed parsing was overly cautious, and swapped the\n    # netloc and path. Due to a lack of tests on the original defect, this is\n    # maintained with parse_url for backwards compatibility.\n    netloc = parsed.netloc\n    if not netloc:\n        netloc, path = path, netloc\n\n    if auth:\n        # parse_url doesn't provide the netloc with auth\n        # so we'll add it ourselves.\n        netloc = \"@\".join([auth, netloc])\n    if scheme is None:\n        scheme = new_scheme\n    if path is None:\n        path = \"\"\n\n    return urlunparse((scheme, netloc, path, \"\", query, fragment))\n\n\ndef get_auth_from_url(url):\n    \"\"\"Given a url with authentication components, extract them into a tuple of\n    username,password.\n\n    :rtype: (str,str)\n    \"\"\"\n    parsed = urlparse(url)\n\n    try:\n        auth = (unquote(parsed.username), unquote(parsed.password))\n    except (AttributeError, TypeError):\n        auth = (\"\", \"\")\n\n    return auth\n\n\ndef check_header_validity(header):\n    \"\"\"Verifies that header parts don't contain leading whitespace\n    reserved characters, or return characters.\n\n    :param header: tuple, in the format (name, value).\n    \"\"\"\n    name, value = header\n\n    for part in header:\n        if type(part) not in HEADER_VALIDATORS:\n            raise InvalidHeader(\n                f\"Header part ({part!r}) from {{{name!r}: {value!r}}} must be \"\n                f\"of type str or bytes, not {type(part)}\"\n            )\n\n    _validate_header_part(name, \"name\", HEADER_VALIDATORS[type(name)][0])\n    _validate_header_part(value, \"value\", HEADER_VALIDATORS[type(value)][1])\n\n\ndef _validate_header_part(header_part, header_kind, validator):\n    if not validator.match(header_part):\n        raise InvalidHeader(\n            f\"Invalid leading whitespace, reserved character(s), or return\"\n            f\"character(s) in header {header_kind}: {header_part!r}\"\n        )\n\n\ndef urldefragauth(url):\n    \"\"\"\n    Given a url remove the fragment and the authentication part.\n\n    :rtype: str\n    \"\"\"\n    scheme, netloc, path, params, query, fragment = urlparse(url)\n\n    # see func:`prepend_scheme_if_needed`\n    if not netloc:\n        netloc, path = path, netloc\n\n    netloc = netloc.rsplit(\"@\", 1)[-1]\n\n    return urlunparse((scheme, netloc, path, params, query, \"\"))\n\n\ndef rewind_body(prepared_request):\n    \"\"\"Move file pointer back to its recorded starting position\n    so it can be read again on redirect.\n    \"\"\"\n    body_seek = getattr(prepared_request.body, \"seek\", None)\n    if body_seek is not None and isinstance(\n        prepared_request._body_position, integer_types\n    ):\n        try:\n            body_seek(prepared_request._body_position)\n        except OSError:\n            raise UnrewindableBodyError(\n                \"An error occurred when rewinding request body for redirect.\"\n            )\n    else:\n        raise UnrewindableBodyError(\"Unable to rewind request body for redirect.\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/resolvelib/__init__.py",
    "content": "__all__ = [\n    \"__version__\",\n    \"AbstractProvider\",\n    \"AbstractResolver\",\n    \"BaseReporter\",\n    \"InconsistentCandidate\",\n    \"Resolver\",\n    \"RequirementsConflicted\",\n    \"ResolutionError\",\n    \"ResolutionImpossible\",\n    \"ResolutionTooDeep\",\n]\n\n__version__ = \"0.8.1\"\n\n\nfrom .providers import AbstractProvider, AbstractResolver\nfrom .reporters import BaseReporter\nfrom .resolvers import (\n    InconsistentCandidate,\n    RequirementsConflicted,\n    ResolutionError,\n    ResolutionImpossible,\n    ResolutionTooDeep,\n    Resolver,\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/resolvelib/compat/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/resolvelib/compat/collections_abc.py",
    "content": "__all__ = [\"Mapping\", \"Sequence\"]\n\ntry:\n    from collections.abc import Mapping, Sequence\nexcept ImportError:\n    from collections import Mapping, Sequence\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/resolvelib/providers.py",
    "content": "class AbstractProvider(object):\n    \"\"\"Delegate class to provide requirement interface for the resolver.\"\"\"\n\n    def identify(self, requirement_or_candidate):\n        \"\"\"Given a requirement, return an identifier for it.\n\n        This is used to identify a requirement, e.g. whether two requirements\n        should have their specifier parts merged.\n        \"\"\"\n        raise NotImplementedError\n\n    def get_preference(\n        self,\n        identifier,\n        resolutions,\n        candidates,\n        information,\n        backtrack_causes,\n    ):\n        \"\"\"Produce a sort key for given requirement based on preference.\n\n        The preference is defined as \"I think this requirement should be\n        resolved first\". The lower the return value is, the more preferred\n        this group of arguments is.\n\n        :param identifier: An identifier as returned by ``identify()``. This\n            identifies the dependency matches of which should be returned.\n        :param resolutions: Mapping of candidates currently pinned by the\n            resolver. Each key is an identifier, and the value a candidate.\n            The candidate may conflict with requirements from ``information``.\n        :param candidates: Mapping of each dependency's possible candidates.\n            Each value is an iterator of candidates.\n        :param information: Mapping of requirement information of each package.\n            Each value is an iterator of *requirement information*.\n        :param backtrack_causes: Sequence of requirement information that were\n            the requirements that caused the resolver to most recently backtrack.\n\n        A *requirement information* instance is a named tuple with two members:\n\n        * ``requirement`` specifies a requirement contributing to the current\n          list of candidates.\n        * ``parent`` specifies the candidate that provides (dependend on) the\n          requirement, or ``None`` to indicate a root requirement.\n\n        The preference could depend on a various of issues, including (not\n        necessarily in this order):\n\n        * Is this package pinned in the current resolution result?\n        * How relaxed is the requirement? Stricter ones should probably be\n          worked on first? (I don't know, actually.)\n        * How many possibilities are there to satisfy this requirement? Those\n          with few left should likely be worked on first, I guess?\n        * Are there any known conflicts for this requirement? We should\n          probably work on those with the most known conflicts.\n\n        A sortable value should be returned (this will be used as the ``key``\n        parameter of the built-in sorting function). The smaller the value is,\n        the more preferred this requirement is (i.e. the sorting function\n        is called with ``reverse=False``).\n        \"\"\"\n        raise NotImplementedError\n\n    def find_matches(self, identifier, requirements, incompatibilities):\n        \"\"\"Find all possible candidates that satisfy given constraints.\n\n        :param identifier: An identifier as returned by ``identify()``. This\n            identifies the dependency matches of which should be returned.\n        :param requirements: A mapping of requirements that all returned\n            candidates must satisfy. Each key is an identifier, and the value\n            an iterator of requirements for that dependency.\n        :param incompatibilities: A mapping of known incompatibilities of\n            each dependency. Each key is an identifier, and the value an\n            iterator of incompatibilities known to the resolver. All\n            incompatibilities *must* be excluded from the return value.\n\n        This should try to get candidates based on the requirements' types.\n        For VCS, local, and archive requirements, the one-and-only match is\n        returned, and for a \"named\" requirement, the index(es) should be\n        consulted to find concrete candidates for this requirement.\n\n        The return value should produce candidates ordered by preference; the\n        most preferred candidate should come first. The return type may be one\n        of the following:\n\n        * A callable that returns an iterator that yields candidates.\n        * An collection of candidates.\n        * An iterable of candidates. This will be consumed immediately into a\n          list of candidates.\n        \"\"\"\n        raise NotImplementedError\n\n    def is_satisfied_by(self, requirement, candidate):\n        \"\"\"Whether the given requirement can be satisfied by a candidate.\n\n        The candidate is guarenteed to have been generated from the\n        requirement.\n\n        A boolean should be returned to indicate whether ``candidate`` is a\n        viable solution to the requirement.\n        \"\"\"\n        raise NotImplementedError\n\n    def get_dependencies(self, candidate):\n        \"\"\"Get dependencies of a candidate.\n\n        This should return a collection of requirements that `candidate`\n        specifies as its dependencies.\n        \"\"\"\n        raise NotImplementedError\n\n\nclass AbstractResolver(object):\n    \"\"\"The thing that performs the actual resolution work.\"\"\"\n\n    base_exception = Exception\n\n    def __init__(self, provider, reporter):\n        self.provider = provider\n        self.reporter = reporter\n\n    def resolve(self, requirements, **kwargs):\n        \"\"\"Take a collection of constraints, spit out the resolution result.\n\n        This returns a representation of the final resolution state, with one\n        guarenteed attribute ``mapping`` that contains resolved candidates as\n        values. The keys are their respective identifiers.\n\n        :param requirements: A collection of constraints.\n        :param kwargs: Additional keyword arguments that subclasses may accept.\n\n        :raises: ``self.base_exception`` or its subclass.\n        \"\"\"\n        raise NotImplementedError\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/resolvelib/reporters.py",
    "content": "class BaseReporter(object):\n    \"\"\"Delegate class to provider progress reporting for the resolver.\"\"\"\n\n    def starting(self):\n        \"\"\"Called before the resolution actually starts.\"\"\"\n\n    def starting_round(self, index):\n        \"\"\"Called before each round of resolution starts.\n\n        The index is zero-based.\n        \"\"\"\n\n    def ending_round(self, index, state):\n        \"\"\"Called before each round of resolution ends.\n\n        This is NOT called if the resolution ends at this round. Use `ending`\n        if you want to report finalization. The index is zero-based.\n        \"\"\"\n\n    def ending(self, state):\n        \"\"\"Called before the resolution ends successfully.\"\"\"\n\n    def adding_requirement(self, requirement, parent):\n        \"\"\"Called when adding a new requirement into the resolve criteria.\n\n        :param requirement: The additional requirement to be applied to filter\n            the available candidaites.\n        :param parent: The candidate that requires ``requirement`` as a\n            dependency, or None if ``requirement`` is one of the root\n            requirements passed in from ``Resolver.resolve()``.\n        \"\"\"\n\n    def resolving_conflicts(self, causes):\n        \"\"\"Called when starting to attempt requirement conflict resolution.\n\n        :param causes: The information on the collision that caused the backtracking.\n        \"\"\"\n\n    def backtracking(self, candidate):\n        \"\"\"Called when rejecting a candidate during backtracking.\"\"\"\n\n    def pinning(self, candidate):\n        \"\"\"Called when adding a candidate to the potential solution.\"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/resolvelib/resolvers.py",
    "content": "import collections\nimport operator\n\nfrom .providers import AbstractResolver\nfrom .structs import DirectedGraph, IteratorMapping, build_iter_view\n\nRequirementInformation = collections.namedtuple(\n    \"RequirementInformation\", [\"requirement\", \"parent\"]\n)\n\n\nclass ResolverException(Exception):\n    \"\"\"A base class for all exceptions raised by this module.\n\n    Exceptions derived by this class should all be handled in this module. Any\n    bubbling pass the resolver should be treated as a bug.\n    \"\"\"\n\n\nclass RequirementsConflicted(ResolverException):\n    def __init__(self, criterion):\n        super(RequirementsConflicted, self).__init__(criterion)\n        self.criterion = criterion\n\n    def __str__(self):\n        return \"Requirements conflict: {}\".format(\n            \", \".join(repr(r) for r in self.criterion.iter_requirement()),\n        )\n\n\nclass InconsistentCandidate(ResolverException):\n    def __init__(self, candidate, criterion):\n        super(InconsistentCandidate, self).__init__(candidate, criterion)\n        self.candidate = candidate\n        self.criterion = criterion\n\n    def __str__(self):\n        return \"Provided candidate {!r} does not satisfy {}\".format(\n            self.candidate,\n            \", \".join(repr(r) for r in self.criterion.iter_requirement()),\n        )\n\n\nclass Criterion(object):\n    \"\"\"Representation of possible resolution results of a package.\n\n    This holds three attributes:\n\n    * `information` is a collection of `RequirementInformation` pairs.\n      Each pair is a requirement contributing to this criterion, and the\n      candidate that provides the requirement.\n    * `incompatibilities` is a collection of all known not-to-work candidates\n      to exclude from consideration.\n    * `candidates` is a collection containing all possible candidates deducted\n      from the union of contributing requirements and known incompatibilities.\n      It should never be empty, except when the criterion is an attribute of a\n      raised `RequirementsConflicted` (in which case it is always empty).\n\n    .. note::\n        This class is intended to be externally immutable. **Do not** mutate\n        any of its attribute containers.\n    \"\"\"\n\n    def __init__(self, candidates, information, incompatibilities):\n        self.candidates = candidates\n        self.information = information\n        self.incompatibilities = incompatibilities\n\n    def __repr__(self):\n        requirements = \", \".join(\n            \"({!r}, via={!r})\".format(req, parent)\n            for req, parent in self.information\n        )\n        return \"Criterion({})\".format(requirements)\n\n    def iter_requirement(self):\n        return (i.requirement for i in self.information)\n\n    def iter_parent(self):\n        return (i.parent for i in self.information)\n\n\nclass ResolutionError(ResolverException):\n    pass\n\n\nclass ResolutionImpossible(ResolutionError):\n    def __init__(self, causes):\n        super(ResolutionImpossible, self).__init__(causes)\n        # causes is a list of RequirementInformation objects\n        self.causes = causes\n\n\nclass ResolutionTooDeep(ResolutionError):\n    def __init__(self, round_count):\n        super(ResolutionTooDeep, self).__init__(round_count)\n        self.round_count = round_count\n\n\n# Resolution state in a round.\nState = collections.namedtuple(\"State\", \"mapping criteria backtrack_causes\")\n\n\nclass Resolution(object):\n    \"\"\"Stateful resolution object.\n\n    This is designed as a one-off object that holds information to kick start\n    the resolution process, and holds the results afterwards.\n    \"\"\"\n\n    def __init__(self, provider, reporter):\n        self._p = provider\n        self._r = reporter\n        self._states = []\n\n    @property\n    def state(self):\n        try:\n            return self._states[-1]\n        except IndexError:\n            raise AttributeError(\"state\")\n\n    def _push_new_state(self):\n        \"\"\"Push a new state into history.\n\n        This new state will be used to hold resolution results of the next\n        coming round.\n        \"\"\"\n        base = self._states[-1]\n        state = State(\n            mapping=base.mapping.copy(),\n            criteria=base.criteria.copy(),\n            backtrack_causes=base.backtrack_causes[:],\n        )\n        self._states.append(state)\n\n    def _add_to_criteria(self, criteria, requirement, parent):\n        self._r.adding_requirement(requirement=requirement, parent=parent)\n\n        identifier = self._p.identify(requirement_or_candidate=requirement)\n        criterion = criteria.get(identifier)\n        if criterion:\n            incompatibilities = list(criterion.incompatibilities)\n        else:\n            incompatibilities = []\n\n        matches = self._p.find_matches(\n            identifier=identifier,\n            requirements=IteratorMapping(\n                criteria,\n                operator.methodcaller(\"iter_requirement\"),\n                {identifier: [requirement]},\n            ),\n            incompatibilities=IteratorMapping(\n                criteria,\n                operator.attrgetter(\"incompatibilities\"),\n                {identifier: incompatibilities},\n            ),\n        )\n\n        if criterion:\n            information = list(criterion.information)\n            information.append(RequirementInformation(requirement, parent))\n        else:\n            information = [RequirementInformation(requirement, parent)]\n\n        criterion = Criterion(\n            candidates=build_iter_view(matches),\n            information=information,\n            incompatibilities=incompatibilities,\n        )\n        if not criterion.candidates:\n            raise RequirementsConflicted(criterion)\n        criteria[identifier] = criterion\n\n    def _get_preference(self, name):\n        return self._p.get_preference(\n            identifier=name,\n            resolutions=self.state.mapping,\n            candidates=IteratorMapping(\n                self.state.criteria,\n                operator.attrgetter(\"candidates\"),\n            ),\n            information=IteratorMapping(\n                self.state.criteria,\n                operator.attrgetter(\"information\"),\n            ),\n            backtrack_causes=self.state.backtrack_causes,\n        )\n\n    def _is_current_pin_satisfying(self, name, criterion):\n        try:\n            current_pin = self.state.mapping[name]\n        except KeyError:\n            return False\n        return all(\n            self._p.is_satisfied_by(requirement=r, candidate=current_pin)\n            for r in criterion.iter_requirement()\n        )\n\n    def _get_updated_criteria(self, candidate):\n        criteria = self.state.criteria.copy()\n        for requirement in self._p.get_dependencies(candidate=candidate):\n            self._add_to_criteria(criteria, requirement, parent=candidate)\n        return criteria\n\n    def _attempt_to_pin_criterion(self, name):\n        criterion = self.state.criteria[name]\n\n        causes = []\n        for candidate in criterion.candidates:\n            try:\n                criteria = self._get_updated_criteria(candidate)\n            except RequirementsConflicted as e:\n                causes.append(e.criterion)\n                continue\n\n            # Check the newly-pinned candidate actually works. This should\n            # always pass under normal circumstances, but in the case of a\n            # faulty provider, we will raise an error to notify the implementer\n            # to fix find_matches() and/or is_satisfied_by().\n            satisfied = all(\n                self._p.is_satisfied_by(requirement=r, candidate=candidate)\n                for r in criterion.iter_requirement()\n            )\n            if not satisfied:\n                raise InconsistentCandidate(candidate, criterion)\n\n            self._r.pinning(candidate=candidate)\n            self.state.criteria.update(criteria)\n\n            # Put newly-pinned candidate at the end. This is essential because\n            # backtracking looks at this mapping to get the last pin.\n            self.state.mapping.pop(name, None)\n            self.state.mapping[name] = candidate\n\n            return []\n\n        # All candidates tried, nothing works. This criterion is a dead\n        # end, signal for backtracking.\n        return causes\n\n    def _backtrack(self):\n        \"\"\"Perform backtracking.\n\n        When we enter here, the stack is like this::\n\n            [ state Z ]\n            [ state Y ]\n            [ state X ]\n            .... earlier states are irrelevant.\n\n        1. No pins worked for Z, so it does not have a pin.\n        2. We want to reset state Y to unpinned, and pin another candidate.\n        3. State X holds what state Y was before the pin, but does not\n           have the incompatibility information gathered in state Y.\n\n        Each iteration of the loop will:\n\n        1.  Discard Z.\n        2.  Discard Y but remember its incompatibility information gathered\n            previously, and the failure we're dealing with right now.\n        3.  Push a new state Y' based on X, and apply the incompatibility\n            information from Y to Y'.\n        4a. If this causes Y' to conflict, we need to backtrack again. Make Y'\n            the new Z and go back to step 2.\n        4b. If the incompatibilities apply cleanly, end backtracking.\n        \"\"\"\n        while len(self._states) >= 3:\n            # Remove the state that triggered backtracking.\n            del self._states[-1]\n\n            # Retrieve the last candidate pin and known incompatibilities.\n            broken_state = self._states.pop()\n            name, candidate = broken_state.mapping.popitem()\n            incompatibilities_from_broken = [\n                (k, list(v.incompatibilities))\n                for k, v in broken_state.criteria.items()\n            ]\n\n            # Also mark the newly known incompatibility.\n            incompatibilities_from_broken.append((name, [candidate]))\n\n            self._r.backtracking(candidate=candidate)\n\n            # Create a new state from the last known-to-work one, and apply\n            # the previously gathered incompatibility information.\n            def _patch_criteria():\n                for k, incompatibilities in incompatibilities_from_broken:\n                    if not incompatibilities:\n                        continue\n                    try:\n                        criterion = self.state.criteria[k]\n                    except KeyError:\n                        continue\n                    matches = self._p.find_matches(\n                        identifier=k,\n                        requirements=IteratorMapping(\n                            self.state.criteria,\n                            operator.methodcaller(\"iter_requirement\"),\n                        ),\n                        incompatibilities=IteratorMapping(\n                            self.state.criteria,\n                            operator.attrgetter(\"incompatibilities\"),\n                            {k: incompatibilities},\n                        ),\n                    )\n                    candidates = build_iter_view(matches)\n                    if not candidates:\n                        return False\n                    incompatibilities.extend(criterion.incompatibilities)\n                    self.state.criteria[k] = Criterion(\n                        candidates=candidates,\n                        information=list(criterion.information),\n                        incompatibilities=incompatibilities,\n                    )\n                return True\n\n            self._push_new_state()\n            success = _patch_criteria()\n\n            # It works! Let's work on this new state.\n            if success:\n                return True\n\n            # State does not work after applying known incompatibilities.\n            # Try the still previous state.\n\n        # No way to backtrack anymore.\n        return False\n\n    def resolve(self, requirements, max_rounds):\n        if self._states:\n            raise RuntimeError(\"already resolved\")\n\n        self._r.starting()\n\n        # Initialize the root state.\n        self._states = [\n            State(\n                mapping=collections.OrderedDict(),\n                criteria={},\n                backtrack_causes=[],\n            )\n        ]\n        for r in requirements:\n            try:\n                self._add_to_criteria(self.state.criteria, r, parent=None)\n            except RequirementsConflicted as e:\n                raise ResolutionImpossible(e.criterion.information)\n\n        # The root state is saved as a sentinel so the first ever pin can have\n        # something to backtrack to if it fails. The root state is basically\n        # pinning the virtual \"root\" package in the graph.\n        self._push_new_state()\n\n        for round_index in range(max_rounds):\n            self._r.starting_round(index=round_index)\n\n            unsatisfied_names = [\n                key\n                for key, criterion in self.state.criteria.items()\n                if not self._is_current_pin_satisfying(key, criterion)\n            ]\n\n            # All criteria are accounted for. Nothing more to pin, we are done!\n            if not unsatisfied_names:\n                self._r.ending(state=self.state)\n                return self.state\n\n            # Choose the most preferred unpinned criterion to try.\n            name = min(unsatisfied_names, key=self._get_preference)\n            failure_causes = self._attempt_to_pin_criterion(name)\n\n            if failure_causes:\n                causes = [i for c in failure_causes for i in c.information]\n                # Backtrack if pinning fails. The backtrack process puts us in\n                # an unpinned state, so we can work on it in the next round.\n                self._r.resolving_conflicts(causes=causes)\n                success = self._backtrack()\n                self.state.backtrack_causes[:] = causes\n\n                # Dead ends everywhere. Give up.\n                if not success:\n                    raise ResolutionImpossible(self.state.backtrack_causes)\n            else:\n                # Pinning was successful. Push a new state to do another pin.\n                self._push_new_state()\n\n            self._r.ending_round(index=round_index, state=self.state)\n\n        raise ResolutionTooDeep(max_rounds)\n\n\ndef _has_route_to_root(criteria, key, all_keys, connected):\n    if key in connected:\n        return True\n    if key not in criteria:\n        return False\n    for p in criteria[key].iter_parent():\n        try:\n            pkey = all_keys[id(p)]\n        except KeyError:\n            continue\n        if pkey in connected:\n            connected.add(key)\n            return True\n        if _has_route_to_root(criteria, pkey, all_keys, connected):\n            connected.add(key)\n            return True\n    return False\n\n\nResult = collections.namedtuple(\"Result\", \"mapping graph criteria\")\n\n\ndef _build_result(state):\n    mapping = state.mapping\n    all_keys = {id(v): k for k, v in mapping.items()}\n    all_keys[id(None)] = None\n\n    graph = DirectedGraph()\n    graph.add(None)  # Sentinel as root dependencies' parent.\n\n    connected = {None}\n    for key, criterion in state.criteria.items():\n        if not _has_route_to_root(state.criteria, key, all_keys, connected):\n            continue\n        if key not in graph:\n            graph.add(key)\n        for p in criterion.iter_parent():\n            try:\n                pkey = all_keys[id(p)]\n            except KeyError:\n                continue\n            if pkey not in graph:\n                graph.add(pkey)\n            graph.connect(pkey, key)\n\n    return Result(\n        mapping={k: v for k, v in mapping.items() if k in connected},\n        graph=graph,\n        criteria=state.criteria,\n    )\n\n\nclass Resolver(AbstractResolver):\n    \"\"\"The thing that performs the actual resolution work.\"\"\"\n\n    base_exception = ResolverException\n\n    def resolve(self, requirements, max_rounds=100):\n        \"\"\"Take a collection of constraints, spit out the resolution result.\n\n        The return value is a representation to the final resolution result. It\n        is a tuple subclass with three public members:\n\n        * `mapping`: A dict of resolved candidates. Each key is an identifier\n            of a requirement (as returned by the provider's `identify` method),\n            and the value is the resolved candidate.\n        * `graph`: A `DirectedGraph` instance representing the dependency tree.\n            The vertices are keys of `mapping`, and each edge represents *why*\n            a particular package is included. A special vertex `None` is\n            included to represent parents of user-supplied requirements.\n        * `criteria`: A dict of \"criteria\" that hold detailed information on\n            how edges in the graph are derived. Each key is an identifier of a\n            requirement, and the value is a `Criterion` instance.\n\n        The following exceptions may be raised if a resolution cannot be found:\n\n        * `ResolutionImpossible`: A resolution cannot be found for the given\n            combination of requirements. The `causes` attribute of the\n            exception is a list of (requirement, parent), giving the\n            requirements that could not be satisfied.\n        * `ResolutionTooDeep`: The dependency tree is too deeply nested and\n            the resolver gave up. This is usually caused by a circular\n            dependency, but you can try to resolve this by increasing the\n            `max_rounds` argument.\n        \"\"\"\n        resolution = Resolution(self.provider, self.reporter)\n        state = resolution.resolve(requirements, max_rounds=max_rounds)\n        return _build_result(state)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/resolvelib/structs.py",
    "content": "import itertools\n\nfrom .compat import collections_abc\n\n\nclass DirectedGraph(object):\n    \"\"\"A graph structure with directed edges.\"\"\"\n\n    def __init__(self):\n        self._vertices = set()\n        self._forwards = {}  # <key> -> Set[<key>]\n        self._backwards = {}  # <key> -> Set[<key>]\n\n    def __iter__(self):\n        return iter(self._vertices)\n\n    def __len__(self):\n        return len(self._vertices)\n\n    def __contains__(self, key):\n        return key in self._vertices\n\n    def copy(self):\n        \"\"\"Return a shallow copy of this graph.\"\"\"\n        other = DirectedGraph()\n        other._vertices = set(self._vertices)\n        other._forwards = {k: set(v) for k, v in self._forwards.items()}\n        other._backwards = {k: set(v) for k, v in self._backwards.items()}\n        return other\n\n    def add(self, key):\n        \"\"\"Add a new vertex to the graph.\"\"\"\n        if key in self._vertices:\n            raise ValueError(\"vertex exists\")\n        self._vertices.add(key)\n        self._forwards[key] = set()\n        self._backwards[key] = set()\n\n    def remove(self, key):\n        \"\"\"Remove a vertex from the graph, disconnecting all edges from/to it.\"\"\"\n        self._vertices.remove(key)\n        for f in self._forwards.pop(key):\n            self._backwards[f].remove(key)\n        for t in self._backwards.pop(key):\n            self._forwards[t].remove(key)\n\n    def connected(self, f, t):\n        return f in self._backwards[t] and t in self._forwards[f]\n\n    def connect(self, f, t):\n        \"\"\"Connect two existing vertices.\n\n        Nothing happens if the vertices are already connected.\n        \"\"\"\n        if t not in self._vertices:\n            raise KeyError(t)\n        self._forwards[f].add(t)\n        self._backwards[t].add(f)\n\n    def iter_edges(self):\n        for f, children in self._forwards.items():\n            for t in children:\n                yield f, t\n\n    def iter_children(self, key):\n        return iter(self._forwards[key])\n\n    def iter_parents(self, key):\n        return iter(self._backwards[key])\n\n\nclass IteratorMapping(collections_abc.Mapping):\n    def __init__(self, mapping, accessor, appends=None):\n        self._mapping = mapping\n        self._accessor = accessor\n        self._appends = appends or {}\n\n    def __repr__(self):\n        return \"IteratorMapping({!r}, {!r}, {!r})\".format(\n            self._mapping,\n            self._accessor,\n            self._appends,\n        )\n\n    def __bool__(self):\n        return bool(self._mapping or self._appends)\n\n    __nonzero__ = __bool__  # XXX: Python 2.\n\n    def __contains__(self, key):\n        return key in self._mapping or key in self._appends\n\n    def __getitem__(self, k):\n        try:\n            v = self._mapping[k]\n        except KeyError:\n            return iter(self._appends[k])\n        return itertools.chain(self._accessor(v), self._appends.get(k, ()))\n\n    def __iter__(self):\n        more = (k for k in self._appends if k not in self._mapping)\n        return itertools.chain(self._mapping, more)\n\n    def __len__(self):\n        more = sum(1 for k in self._appends if k not in self._mapping)\n        return len(self._mapping) + more\n\n\nclass _FactoryIterableView(object):\n    \"\"\"Wrap an iterator factory returned by `find_matches()`.\n\n    Calling `iter()` on this class would invoke the underlying iterator\n    factory, making it a \"collection with ordering\" that can be iterated\n    through multiple times, but lacks random access methods presented in\n    built-in Python sequence types.\n    \"\"\"\n\n    def __init__(self, factory):\n        self._factory = factory\n\n    def __repr__(self):\n        return \"{}({})\".format(type(self).__name__, list(self._factory()))\n\n    def __bool__(self):\n        try:\n            next(self._factory())\n        except StopIteration:\n            return False\n        return True\n\n    __nonzero__ = __bool__  # XXX: Python 2.\n\n    def __iter__(self):\n        return self._factory()\n\n\nclass _SequenceIterableView(object):\n    \"\"\"Wrap an iterable returned by find_matches().\n\n    This is essentially just a proxy to the underlying sequence that provides\n    the same interface as `_FactoryIterableView`.\n    \"\"\"\n\n    def __init__(self, sequence):\n        self._sequence = sequence\n\n    def __repr__(self):\n        return \"{}({})\".format(type(self).__name__, self._sequence)\n\n    def __bool__(self):\n        return bool(self._sequence)\n\n    __nonzero__ = __bool__  # XXX: Python 2.\n\n    def __iter__(self):\n        return iter(self._sequence)\n\n\ndef build_iter_view(matches):\n    \"\"\"Build an iterable view from the value returned by `find_matches()`.\"\"\"\n    if callable(matches):\n        return _FactoryIterableView(matches)\n    if not isinstance(matches, collections_abc.Sequence):\n        matches = list(matches)\n    return _SequenceIterableView(matches)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/__init__.py",
    "content": "\"\"\"Rich text and beautiful formatting in the terminal.\"\"\"\n\nimport os\nfrom typing import IO, TYPE_CHECKING, Any, Callable, Optional, Union\n\nfrom ._extension import load_ipython_extension  # noqa: F401\n\n__all__ = [\"get_console\", \"reconfigure\", \"print\", \"inspect\"]\n\nif TYPE_CHECKING:\n    from .console import Console\n\n# Global console used by alternative print\n_console: Optional[\"Console\"] = None\n\ntry:\n    _IMPORT_CWD = os.path.abspath(os.getcwd())\nexcept FileNotFoundError:\n    # Can happen if the cwd has been deleted\n    _IMPORT_CWD = \"\"\n\n\ndef get_console() -> \"Console\":\n    \"\"\"Get a global :class:`~rich.console.Console` instance. This function is used when Rich requires a Console,\n    and hasn't been explicitly given one.\n\n    Returns:\n        Console: A console instance.\n    \"\"\"\n    global _console\n    if _console is None:\n        from .console import Console\n\n        _console = Console()\n\n    return _console\n\n\ndef reconfigure(*args: Any, **kwargs: Any) -> None:\n    \"\"\"Reconfigures the global console by replacing it with another.\n\n    Args:\n        console (Console): Replacement console instance.\n    \"\"\"\n    from pip._vendor.rich.console import Console\n\n    new_console = Console(*args, **kwargs)\n    _console = get_console()\n    _console.__dict__ = new_console.__dict__\n\n\ndef print(\n    *objects: Any,\n    sep: str = \" \",\n    end: str = \"\\n\",\n    file: Optional[IO[str]] = None,\n    flush: bool = False,\n) -> None:\n    r\"\"\"Print object(s) supplied via positional arguments.\n    This function has an identical signature to the built-in print.\n    For more advanced features, see the :class:`~rich.console.Console` class.\n\n    Args:\n        sep (str, optional): Separator between printed objects. Defaults to \" \".\n        end (str, optional): Character to write at end of output. Defaults to \"\\\\n\".\n        file (IO[str], optional): File to write to, or None for stdout. Defaults to None.\n        flush (bool, optional): Has no effect as Rich always flushes output. Defaults to False.\n\n    \"\"\"\n    from .console import Console\n\n    write_console = get_console() if file is None else Console(file=file)\n    return write_console.print(*objects, sep=sep, end=end)\n\n\ndef print_json(\n    json: Optional[str] = None,\n    *,\n    data: Any = None,\n    indent: Union[None, int, str] = 2,\n    highlight: bool = True,\n    skip_keys: bool = False,\n    ensure_ascii: bool = True,\n    check_circular: bool = True,\n    allow_nan: bool = True,\n    default: Optional[Callable[[Any], Any]] = None,\n    sort_keys: bool = False,\n) -> None:\n    \"\"\"Pretty prints JSON. Output will be valid JSON.\n\n    Args:\n        json (str): A string containing JSON.\n        data (Any): If json is not supplied, then encode this data.\n        indent (int, optional): Number of spaces to indent. Defaults to 2.\n        highlight (bool, optional): Enable highlighting of output: Defaults to True.\n        skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.\n        ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.\n        check_circular (bool, optional): Check for circular references. Defaults to True.\n        allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.\n        default (Callable, optional): A callable that converts values that can not be encoded\n            in to something that can be JSON encoded. Defaults to None.\n        sort_keys (bool, optional): Sort dictionary keys. Defaults to False.\n    \"\"\"\n\n    get_console().print_json(\n        json,\n        data=data,\n        indent=indent,\n        highlight=highlight,\n        skip_keys=skip_keys,\n        ensure_ascii=ensure_ascii,\n        check_circular=check_circular,\n        allow_nan=allow_nan,\n        default=default,\n        sort_keys=sort_keys,\n    )\n\n\ndef inspect(\n    obj: Any,\n    *,\n    console: Optional[\"Console\"] = None,\n    title: Optional[str] = None,\n    help: bool = False,\n    methods: bool = False,\n    docs: bool = True,\n    private: bool = False,\n    dunder: bool = False,\n    sort: bool = True,\n    all: bool = False,\n    value: bool = True,\n) -> None:\n    \"\"\"Inspect any Python object.\n\n    * inspect(<OBJECT>) to see summarized info.\n    * inspect(<OBJECT>, methods=True) to see methods.\n    * inspect(<OBJECT>, help=True) to see full (non-abbreviated) help.\n    * inspect(<OBJECT>, private=True) to see private attributes (single underscore).\n    * inspect(<OBJECT>, dunder=True) to see attributes beginning with double underscore.\n    * inspect(<OBJECT>, all=True) to see all attributes.\n\n    Args:\n        obj (Any): An object to inspect.\n        title (str, optional): Title to display over inspect result, or None use type. Defaults to None.\n        help (bool, optional): Show full help text rather than just first paragraph. Defaults to False.\n        methods (bool, optional): Enable inspection of callables. Defaults to False.\n        docs (bool, optional): Also render doc strings. Defaults to True.\n        private (bool, optional): Show private attributes (beginning with underscore). Defaults to False.\n        dunder (bool, optional): Show attributes starting with double underscore. Defaults to False.\n        sort (bool, optional): Sort attributes alphabetically. Defaults to True.\n        all (bool, optional): Show all attributes. Defaults to False.\n        value (bool, optional): Pretty print value. Defaults to True.\n    \"\"\"\n    _console = console or get_console()\n    from pip._vendor.rich._inspect import Inspect\n\n    # Special case for inspect(inspect)\n    is_inspect = obj is inspect\n\n    _inspect = Inspect(\n        obj,\n        title=title,\n        help=is_inspect or help,\n        methods=is_inspect or methods,\n        docs=is_inspect or docs,\n        private=private,\n        dunder=dunder,\n        sort=sort,\n        all=all,\n        value=value,\n    )\n    _console.print(_inspect)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    print(\"Hello, **World**\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/__main__.py",
    "content": "import colorsys\nimport io\nfrom time import process_time\n\nfrom pip._vendor.rich import box\nfrom pip._vendor.rich.color import Color\nfrom pip._vendor.rich.console import Console, ConsoleOptions, Group, RenderableType, RenderResult\nfrom pip._vendor.rich.markdown import Markdown\nfrom pip._vendor.rich.measure import Measurement\nfrom pip._vendor.rich.pretty import Pretty\nfrom pip._vendor.rich.segment import Segment\nfrom pip._vendor.rich.style import Style\nfrom pip._vendor.rich.syntax import Syntax\nfrom pip._vendor.rich.table import Table\nfrom pip._vendor.rich.text import Text\n\n\nclass ColorBox:\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        for y in range(0, 5):\n            for x in range(options.max_width):\n                h = x / options.max_width\n                l = 0.1 + ((y / 5) * 0.7)\n                r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0)\n                r2, g2, b2 = colorsys.hls_to_rgb(h, l + 0.7 / 10, 1.0)\n                bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255)\n                color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255)\n                yield Segment(\"▄\", Style(color=color, bgcolor=bgcolor))\n            yield Segment.line()\n\n    def __rich_measure__(\n        self, console: \"Console\", options: ConsoleOptions\n    ) -> Measurement:\n        return Measurement(1, options.max_width)\n\n\ndef make_test_card() -> Table:\n    \"\"\"Get a renderable that demonstrates a number of features.\"\"\"\n    table = Table.grid(padding=1, pad_edge=True)\n    table.title = \"Rich features\"\n    table.add_column(\"Feature\", no_wrap=True, justify=\"center\", style=\"bold red\")\n    table.add_column(\"Demonstration\")\n\n    color_table = Table(\n        box=None,\n        expand=False,\n        show_header=False,\n        show_edge=False,\n        pad_edge=False,\n    )\n    color_table.add_row(\n        (\n            \"✓ [bold green]4-bit color[/]\\n\"\n            \"✓ [bold blue]8-bit color[/]\\n\"\n            \"✓ [bold magenta]Truecolor (16.7 million)[/]\\n\"\n            \"✓ [bold yellow]Dumb terminals[/]\\n\"\n            \"✓ [bold cyan]Automatic color conversion\"\n        ),\n        ColorBox(),\n    )\n\n    table.add_row(\"Colors\", color_table)\n\n    table.add_row(\n        \"Styles\",\n        \"All ansi styles: [bold]bold[/], [dim]dim[/], [italic]italic[/italic], [underline]underline[/], [strike]strikethrough[/], [reverse]reverse[/], and even [blink]blink[/].\",\n    )\n\n    lorem = \"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in metus sed sapien ultricies pretium a at justo. Maecenas luctus velit et auctor maximus.\"\n    lorem_table = Table.grid(padding=1, collapse_padding=True)\n    lorem_table.pad_edge = False\n    lorem_table.add_row(\n        Text(lorem, justify=\"left\", style=\"green\"),\n        Text(lorem, justify=\"center\", style=\"yellow\"),\n        Text(lorem, justify=\"right\", style=\"blue\"),\n        Text(lorem, justify=\"full\", style=\"red\"),\n    )\n    table.add_row(\n        \"Text\",\n        Group(\n            Text.from_markup(\n                \"\"\"Word wrap text. Justify [green]left[/], [yellow]center[/], [blue]right[/] or [red]full[/].\\n\"\"\"\n            ),\n            lorem_table,\n        ),\n    )\n\n    def comparison(renderable1: RenderableType, renderable2: RenderableType) -> Table:\n        table = Table(show_header=False, pad_edge=False, box=None, expand=True)\n        table.add_column(\"1\", ratio=1)\n        table.add_column(\"2\", ratio=1)\n        table.add_row(renderable1, renderable2)\n        return table\n\n    table.add_row(\n        \"Asian\\nlanguage\\nsupport\",\n        \":flag_for_china:  该库支持中文，日文和韩文文本！\\n:flag_for_japan:  ライブラリは中国語、日本語、韓国語のテキストをサポートしています\\n:flag_for_south_korea:  이 라이브러리는 중국어, 일본어 및 한국어 텍스트를 지원합니다\",\n    )\n\n    markup_example = (\n        \"[bold magenta]Rich[/] supports a simple [i]bbcode[/i]-like [b]markup[/b] for [yellow]color[/], [underline]style[/], and emoji! \"\n        \":+1: :apple: :ant: :bear: :baguette_bread: :bus: \"\n    )\n    table.add_row(\"Markup\", markup_example)\n\n    example_table = Table(\n        show_edge=False,\n        show_header=True,\n        expand=False,\n        row_styles=[\"none\", \"dim\"],\n        box=box.SIMPLE,\n    )\n    example_table.add_column(\"[green]Date\", style=\"green\", no_wrap=True)\n    example_table.add_column(\"[blue]Title\", style=\"blue\")\n    example_table.add_column(\n        \"[cyan]Production Budget\",\n        style=\"cyan\",\n        justify=\"right\",\n        no_wrap=True,\n    )\n    example_table.add_column(\n        \"[magenta]Box Office\",\n        style=\"magenta\",\n        justify=\"right\",\n        no_wrap=True,\n    )\n    example_table.add_row(\n        \"Dec 20, 2019\",\n        \"Star Wars: The Rise of Skywalker\",\n        \"$275,000,000\",\n        \"$375,126,118\",\n    )\n    example_table.add_row(\n        \"May 25, 2018\",\n        \"[b]Solo[/]: A Star Wars Story\",\n        \"$275,000,000\",\n        \"$393,151,347\",\n    )\n    example_table.add_row(\n        \"Dec 15, 2017\",\n        \"Star Wars Ep. VIII: The Last Jedi\",\n        \"$262,000,000\",\n        \"[bold]$1,332,539,889[/bold]\",\n    )\n    example_table.add_row(\n        \"May 19, 1999\",\n        \"Star Wars Ep. [b]I[/b]: [i]The phantom Menace\",\n        \"$115,000,000\",\n        \"$1,027,044,677\",\n    )\n\n    table.add_row(\"Tables\", example_table)\n\n    code = '''\\\ndef iter_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:\n    \"\"\"Iterate and generate a tuple with a flag for last value.\"\"\"\n    iter_values = iter(values)\n    try:\n        previous_value = next(iter_values)\n    except StopIteration:\n        return\n    for value in iter_values:\n        yield False, previous_value\n        previous_value = value\n    yield True, previous_value'''\n\n    pretty_data = {\n        \"foo\": [\n            3.1427,\n            (\n                \"Paul Atreides\",\n                \"Vladimir Harkonnen\",\n                \"Thufir Hawat\",\n            ),\n        ],\n        \"atomic\": (False, True, None),\n    }\n    table.add_row(\n        \"Syntax\\nhighlighting\\n&\\npretty\\nprinting\",\n        comparison(\n            Syntax(code, \"python3\", line_numbers=True, indent_guides=True),\n            Pretty(pretty_data, indent_guides=True),\n        ),\n    )\n\n    markdown_example = \"\"\"\\\n# Markdown\n\nSupports much of the *markdown* __syntax__!\n\n- Headers\n- Basic formatting: **bold**, *italic*, `code`\n- Block quotes\n- Lists, and more...\n    \"\"\"\n    table.add_row(\n        \"Markdown\", comparison(\"[cyan]\" + markdown_example, Markdown(markdown_example))\n    )\n\n    table.add_row(\n        \"+more!\",\n        \"\"\"Progress bars, columns, styled logging handler, tracebacks, etc...\"\"\",\n    )\n    return table\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n\n    console = Console(\n        file=io.StringIO(),\n        force_terminal=True,\n    )\n    test_card = make_test_card()\n\n    # Print once to warm cache\n    start = process_time()\n    console.print(test_card)\n    pre_cache_taken = round((process_time() - start) * 1000.0, 1)\n\n    console.file = io.StringIO()\n\n    start = process_time()\n    console.print(test_card)\n    taken = round((process_time() - start) * 1000.0, 1)\n\n    c = Console(record=True)\n    c.print(test_card)\n    # c.save_svg(\n    #     path=\"/Users/darrenburns/Library/Application Support/JetBrains/PyCharm2021.3/scratches/svg_export.svg\",\n    #     title=\"Rich can export to SVG\",\n    # )\n\n    print(f\"rendered in {pre_cache_taken}ms (cold cache)\")\n    print(f\"rendered in {taken}ms (warm cache)\")\n\n    from pip._vendor.rich.panel import Panel\n\n    console = Console()\n\n    sponsor_message = Table.grid(padding=1)\n    sponsor_message.add_column(style=\"green\", justify=\"right\")\n    sponsor_message.add_column(no_wrap=True)\n\n    sponsor_message.add_row(\n        \"Textualize\",\n        \"[u blue link=https://github.com/textualize]https://github.com/textualize\",\n    )\n    sponsor_message.add_row(\n        \"Buy devs a :coffee:\",\n        \"[u blue link=https://ko-fi.com/textualize]https://ko-fi.com/textualize\",\n    )\n    sponsor_message.add_row(\n        \"Twitter\",\n        \"[u blue link=https://twitter.com/willmcgugan]https://twitter.com/willmcgugan\",\n    )\n\n    intro_message = Text.from_markup(\n        \"\"\"\\\nWe hope you enjoy using Rich!\n\nRich is maintained with [red]:heart:[/] by [link=https://www.textualize.io]Textualize.io[/]\n\n- Will McGugan\"\"\"\n    )\n\n    message = Table.grid(padding=2)\n    message.add_column()\n    message.add_column(no_wrap=True)\n    message.add_row(intro_message, sponsor_message)\n\n    console.print(\n        Panel.fit(\n            message,\n            box=box.ROUNDED,\n            padding=(1, 2),\n            title=\"[b red]Thanks for trying out Rich!\",\n            border_style=\"bright_blue\",\n        ),\n        justify=\"center\",\n    )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_cell_widths.py",
    "content": "# Auto generated by make_terminal_widths.py\n\nCELL_WIDTHS = [\n    (0, 0, 0),\n    (1, 31, -1),\n    (127, 159, -1),\n    (768, 879, 0),\n    (1155, 1161, 0),\n    (1425, 1469, 0),\n    (1471, 1471, 0),\n    (1473, 1474, 0),\n    (1476, 1477, 0),\n    (1479, 1479, 0),\n    (1552, 1562, 0),\n    (1611, 1631, 0),\n    (1648, 1648, 0),\n    (1750, 1756, 0),\n    (1759, 1764, 0),\n    (1767, 1768, 0),\n    (1770, 1773, 0),\n    (1809, 1809, 0),\n    (1840, 1866, 0),\n    (1958, 1968, 0),\n    (2027, 2035, 0),\n    (2045, 2045, 0),\n    (2070, 2073, 0),\n    (2075, 2083, 0),\n    (2085, 2087, 0),\n    (2089, 2093, 0),\n    (2137, 2139, 0),\n    (2259, 2273, 0),\n    (2275, 2306, 0),\n    (2362, 2362, 0),\n    (2364, 2364, 0),\n    (2369, 2376, 0),\n    (2381, 2381, 0),\n    (2385, 2391, 0),\n    (2402, 2403, 0),\n    (2433, 2433, 0),\n    (2492, 2492, 0),\n    (2497, 2500, 0),\n    (2509, 2509, 0),\n    (2530, 2531, 0),\n    (2558, 2558, 0),\n    (2561, 2562, 0),\n    (2620, 2620, 0),\n    (2625, 2626, 0),\n    (2631, 2632, 0),\n    (2635, 2637, 0),\n    (2641, 2641, 0),\n    (2672, 2673, 0),\n    (2677, 2677, 0),\n    (2689, 2690, 0),\n    (2748, 2748, 0),\n    (2753, 2757, 0),\n    (2759, 2760, 0),\n    (2765, 2765, 0),\n    (2786, 2787, 0),\n    (2810, 2815, 0),\n    (2817, 2817, 0),\n    (2876, 2876, 0),\n    (2879, 2879, 0),\n    (2881, 2884, 0),\n    (2893, 2893, 0),\n    (2901, 2902, 0),\n    (2914, 2915, 0),\n    (2946, 2946, 0),\n    (3008, 3008, 0),\n    (3021, 3021, 0),\n    (3072, 3072, 0),\n    (3076, 3076, 0),\n    (3134, 3136, 0),\n    (3142, 3144, 0),\n    (3146, 3149, 0),\n    (3157, 3158, 0),\n    (3170, 3171, 0),\n    (3201, 3201, 0),\n    (3260, 3260, 0),\n    (3263, 3263, 0),\n    (3270, 3270, 0),\n    (3276, 3277, 0),\n    (3298, 3299, 0),\n    (3328, 3329, 0),\n    (3387, 3388, 0),\n    (3393, 3396, 0),\n    (3405, 3405, 0),\n    (3426, 3427, 0),\n    (3457, 3457, 0),\n    (3530, 3530, 0),\n    (3538, 3540, 0),\n    (3542, 3542, 0),\n    (3633, 3633, 0),\n    (3636, 3642, 0),\n    (3655, 3662, 0),\n    (3761, 3761, 0),\n    (3764, 3772, 0),\n    (3784, 3789, 0),\n    (3864, 3865, 0),\n    (3893, 3893, 0),\n    (3895, 3895, 0),\n    (3897, 3897, 0),\n    (3953, 3966, 0),\n    (3968, 3972, 0),\n    (3974, 3975, 0),\n    (3981, 3991, 0),\n    (3993, 4028, 0),\n    (4038, 4038, 0),\n    (4141, 4144, 0),\n    (4146, 4151, 0),\n    (4153, 4154, 0),\n    (4157, 4158, 0),\n    (4184, 4185, 0),\n    (4190, 4192, 0),\n    (4209, 4212, 0),\n    (4226, 4226, 0),\n    (4229, 4230, 0),\n    (4237, 4237, 0),\n    (4253, 4253, 0),\n    (4352, 4447, 2),\n    (4957, 4959, 0),\n    (5906, 5908, 0),\n    (5938, 5940, 0),\n    (5970, 5971, 0),\n    (6002, 6003, 0),\n    (6068, 6069, 0),\n    (6071, 6077, 0),\n    (6086, 6086, 0),\n    (6089, 6099, 0),\n    (6109, 6109, 0),\n    (6155, 6157, 0),\n    (6277, 6278, 0),\n    (6313, 6313, 0),\n    (6432, 6434, 0),\n    (6439, 6440, 0),\n    (6450, 6450, 0),\n    (6457, 6459, 0),\n    (6679, 6680, 0),\n    (6683, 6683, 0),\n    (6742, 6742, 0),\n    (6744, 6750, 0),\n    (6752, 6752, 0),\n    (6754, 6754, 0),\n    (6757, 6764, 0),\n    (6771, 6780, 0),\n    (6783, 6783, 0),\n    (6832, 6848, 0),\n    (6912, 6915, 0),\n    (6964, 6964, 0),\n    (6966, 6970, 0),\n    (6972, 6972, 0),\n    (6978, 6978, 0),\n    (7019, 7027, 0),\n    (7040, 7041, 0),\n    (7074, 7077, 0),\n    (7080, 7081, 0),\n    (7083, 7085, 0),\n    (7142, 7142, 0),\n    (7144, 7145, 0),\n    (7149, 7149, 0),\n    (7151, 7153, 0),\n    (7212, 7219, 0),\n    (7222, 7223, 0),\n    (7376, 7378, 0),\n    (7380, 7392, 0),\n    (7394, 7400, 0),\n    (7405, 7405, 0),\n    (7412, 7412, 0),\n    (7416, 7417, 0),\n    (7616, 7673, 0),\n    (7675, 7679, 0),\n    (8203, 8207, 0),\n    (8232, 8238, 0),\n    (8288, 8291, 0),\n    (8400, 8432, 0),\n    (8986, 8987, 2),\n    (9001, 9002, 2),\n    (9193, 9196, 2),\n    (9200, 9200, 2),\n    (9203, 9203, 2),\n    (9725, 9726, 2),\n    (9748, 9749, 2),\n    (9800, 9811, 2),\n    (9855, 9855, 2),\n    (9875, 9875, 2),\n    (9889, 9889, 2),\n    (9898, 9899, 2),\n    (9917, 9918, 2),\n    (9924, 9925, 2),\n    (9934, 9934, 2),\n    (9940, 9940, 2),\n    (9962, 9962, 2),\n    (9970, 9971, 2),\n    (9973, 9973, 2),\n    (9978, 9978, 2),\n    (9981, 9981, 2),\n    (9989, 9989, 2),\n    (9994, 9995, 2),\n    (10024, 10024, 2),\n    (10060, 10060, 2),\n    (10062, 10062, 2),\n    (10067, 10069, 2),\n    (10071, 10071, 2),\n    (10133, 10135, 2),\n    (10160, 10160, 2),\n    (10175, 10175, 2),\n    (11035, 11036, 2),\n    (11088, 11088, 2),\n    (11093, 11093, 2),\n    (11503, 11505, 0),\n    (11647, 11647, 0),\n    (11744, 11775, 0),\n    (11904, 11929, 2),\n    (11931, 12019, 2),\n    (12032, 12245, 2),\n    (12272, 12283, 2),\n    (12288, 12329, 2),\n    (12330, 12333, 0),\n    (12334, 12350, 2),\n    (12353, 12438, 2),\n    (12441, 12442, 0),\n    (12443, 12543, 2),\n    (12549, 12591, 2),\n    (12593, 12686, 2),\n    (12688, 12771, 2),\n    (12784, 12830, 2),\n    (12832, 12871, 2),\n    (12880, 19903, 2),\n    (19968, 42124, 2),\n    (42128, 42182, 2),\n    (42607, 42610, 0),\n    (42612, 42621, 0),\n    (42654, 42655, 0),\n    (42736, 42737, 0),\n    (43010, 43010, 0),\n    (43014, 43014, 0),\n    (43019, 43019, 0),\n    (43045, 43046, 0),\n    (43052, 43052, 0),\n    (43204, 43205, 0),\n    (43232, 43249, 0),\n    (43263, 43263, 0),\n    (43302, 43309, 0),\n    (43335, 43345, 0),\n    (43360, 43388, 2),\n    (43392, 43394, 0),\n    (43443, 43443, 0),\n    (43446, 43449, 0),\n    (43452, 43453, 0),\n    (43493, 43493, 0),\n    (43561, 43566, 0),\n    (43569, 43570, 0),\n    (43573, 43574, 0),\n    (43587, 43587, 0),\n    (43596, 43596, 0),\n    (43644, 43644, 0),\n    (43696, 43696, 0),\n    (43698, 43700, 0),\n    (43703, 43704, 0),\n    (43710, 43711, 0),\n    (43713, 43713, 0),\n    (43756, 43757, 0),\n    (43766, 43766, 0),\n    (44005, 44005, 0),\n    (44008, 44008, 0),\n    (44013, 44013, 0),\n    (44032, 55203, 2),\n    (63744, 64255, 2),\n    (64286, 64286, 0),\n    (65024, 65039, 0),\n    (65040, 65049, 2),\n    (65056, 65071, 0),\n    (65072, 65106, 2),\n    (65108, 65126, 2),\n    (65128, 65131, 2),\n    (65281, 65376, 2),\n    (65504, 65510, 2),\n    (66045, 66045, 0),\n    (66272, 66272, 0),\n    (66422, 66426, 0),\n    (68097, 68099, 0),\n    (68101, 68102, 0),\n    (68108, 68111, 0),\n    (68152, 68154, 0),\n    (68159, 68159, 0),\n    (68325, 68326, 0),\n    (68900, 68903, 0),\n    (69291, 69292, 0),\n    (69446, 69456, 0),\n    (69633, 69633, 0),\n    (69688, 69702, 0),\n    (69759, 69761, 0),\n    (69811, 69814, 0),\n    (69817, 69818, 0),\n    (69888, 69890, 0),\n    (69927, 69931, 0),\n    (69933, 69940, 0),\n    (70003, 70003, 0),\n    (70016, 70017, 0),\n    (70070, 70078, 0),\n    (70089, 70092, 0),\n    (70095, 70095, 0),\n    (70191, 70193, 0),\n    (70196, 70196, 0),\n    (70198, 70199, 0),\n    (70206, 70206, 0),\n    (70367, 70367, 0),\n    (70371, 70378, 0),\n    (70400, 70401, 0),\n    (70459, 70460, 0),\n    (70464, 70464, 0),\n    (70502, 70508, 0),\n    (70512, 70516, 0),\n    (70712, 70719, 0),\n    (70722, 70724, 0),\n    (70726, 70726, 0),\n    (70750, 70750, 0),\n    (70835, 70840, 0),\n    (70842, 70842, 0),\n    (70847, 70848, 0),\n    (70850, 70851, 0),\n    (71090, 71093, 0),\n    (71100, 71101, 0),\n    (71103, 71104, 0),\n    (71132, 71133, 0),\n    (71219, 71226, 0),\n    (71229, 71229, 0),\n    (71231, 71232, 0),\n    (71339, 71339, 0),\n    (71341, 71341, 0),\n    (71344, 71349, 0),\n    (71351, 71351, 0),\n    (71453, 71455, 0),\n    (71458, 71461, 0),\n    (71463, 71467, 0),\n    (71727, 71735, 0),\n    (71737, 71738, 0),\n    (71995, 71996, 0),\n    (71998, 71998, 0),\n    (72003, 72003, 0),\n    (72148, 72151, 0),\n    (72154, 72155, 0),\n    (72160, 72160, 0),\n    (72193, 72202, 0),\n    (72243, 72248, 0),\n    (72251, 72254, 0),\n    (72263, 72263, 0),\n    (72273, 72278, 0),\n    (72281, 72283, 0),\n    (72330, 72342, 0),\n    (72344, 72345, 0),\n    (72752, 72758, 0),\n    (72760, 72765, 0),\n    (72767, 72767, 0),\n    (72850, 72871, 0),\n    (72874, 72880, 0),\n    (72882, 72883, 0),\n    (72885, 72886, 0),\n    (73009, 73014, 0),\n    (73018, 73018, 0),\n    (73020, 73021, 0),\n    (73023, 73029, 0),\n    (73031, 73031, 0),\n    (73104, 73105, 0),\n    (73109, 73109, 0),\n    (73111, 73111, 0),\n    (73459, 73460, 0),\n    (92912, 92916, 0),\n    (92976, 92982, 0),\n    (94031, 94031, 0),\n    (94095, 94098, 0),\n    (94176, 94179, 2),\n    (94180, 94180, 0),\n    (94192, 94193, 2),\n    (94208, 100343, 2),\n    (100352, 101589, 2),\n    (101632, 101640, 2),\n    (110592, 110878, 2),\n    (110928, 110930, 2),\n    (110948, 110951, 2),\n    (110960, 111355, 2),\n    (113821, 113822, 0),\n    (119143, 119145, 0),\n    (119163, 119170, 0),\n    (119173, 119179, 0),\n    (119210, 119213, 0),\n    (119362, 119364, 0),\n    (121344, 121398, 0),\n    (121403, 121452, 0),\n    (121461, 121461, 0),\n    (121476, 121476, 0),\n    (121499, 121503, 0),\n    (121505, 121519, 0),\n    (122880, 122886, 0),\n    (122888, 122904, 0),\n    (122907, 122913, 0),\n    (122915, 122916, 0),\n    (122918, 122922, 0),\n    (123184, 123190, 0),\n    (123628, 123631, 0),\n    (125136, 125142, 0),\n    (125252, 125258, 0),\n    (126980, 126980, 2),\n    (127183, 127183, 2),\n    (127374, 127374, 2),\n    (127377, 127386, 2),\n    (127488, 127490, 2),\n    (127504, 127547, 2),\n    (127552, 127560, 2),\n    (127568, 127569, 2),\n    (127584, 127589, 2),\n    (127744, 127776, 2),\n    (127789, 127797, 2),\n    (127799, 127868, 2),\n    (127870, 127891, 2),\n    (127904, 127946, 2),\n    (127951, 127955, 2),\n    (127968, 127984, 2),\n    (127988, 127988, 2),\n    (127992, 128062, 2),\n    (128064, 128064, 2),\n    (128066, 128252, 2),\n    (128255, 128317, 2),\n    (128331, 128334, 2),\n    (128336, 128359, 2),\n    (128378, 128378, 2),\n    (128405, 128406, 2),\n    (128420, 128420, 2),\n    (128507, 128591, 2),\n    (128640, 128709, 2),\n    (128716, 128716, 2),\n    (128720, 128722, 2),\n    (128725, 128727, 2),\n    (128747, 128748, 2),\n    (128756, 128764, 2),\n    (128992, 129003, 2),\n    (129292, 129338, 2),\n    (129340, 129349, 2),\n    (129351, 129400, 2),\n    (129402, 129483, 2),\n    (129485, 129535, 2),\n    (129648, 129652, 2),\n    (129656, 129658, 2),\n    (129664, 129670, 2),\n    (129680, 129704, 2),\n    (129712, 129718, 2),\n    (129728, 129730, 2),\n    (129744, 129750, 2),\n    (131072, 196605, 2),\n    (196608, 262141, 2),\n    (917760, 917999, 0),\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_emoji_codes.py",
    "content": "EMOJI = {\n    \"1st_place_medal\": \"🥇\",\n    \"2nd_place_medal\": \"🥈\",\n    \"3rd_place_medal\": \"🥉\",\n    \"ab_button_(blood_type)\": \"🆎\",\n    \"atm_sign\": \"🏧\",\n    \"a_button_(blood_type)\": \"🅰\",\n    \"afghanistan\": \"🇦🇫\",\n    \"albania\": \"🇦🇱\",\n    \"algeria\": \"🇩🇿\",\n    \"american_samoa\": \"🇦🇸\",\n    \"andorra\": \"🇦🇩\",\n    \"angola\": \"🇦🇴\",\n    \"anguilla\": \"🇦🇮\",\n    \"antarctica\": \"🇦🇶\",\n    \"antigua_&_barbuda\": \"🇦🇬\",\n    \"aquarius\": \"♒\",\n    \"argentina\": \"🇦🇷\",\n    \"aries\": \"♈\",\n    \"armenia\": \"🇦🇲\",\n    \"aruba\": \"🇦🇼\",\n    \"ascension_island\": \"🇦🇨\",\n    \"australia\": \"🇦🇺\",\n    \"austria\": \"🇦🇹\",\n    \"azerbaijan\": \"🇦🇿\",\n    \"back_arrow\": \"🔙\",\n    \"b_button_(blood_type)\": \"🅱\",\n    \"bahamas\": \"🇧🇸\",\n    \"bahrain\": \"🇧🇭\",\n    \"bangladesh\": \"🇧🇩\",\n    \"barbados\": \"🇧🇧\",\n    \"belarus\": \"🇧🇾\",\n    \"belgium\": \"🇧🇪\",\n    \"belize\": \"🇧🇿\",\n    \"benin\": \"🇧🇯\",\n    \"bermuda\": \"🇧🇲\",\n    \"bhutan\": \"🇧🇹\",\n    \"bolivia\": \"🇧🇴\",\n    \"bosnia_&_herzegovina\": \"🇧🇦\",\n    \"botswana\": \"🇧🇼\",\n    \"bouvet_island\": \"🇧🇻\",\n    \"brazil\": \"🇧🇷\",\n    \"british_indian_ocean_territory\": \"🇮🇴\",\n    \"british_virgin_islands\": \"🇻🇬\",\n    \"brunei\": \"🇧🇳\",\n    \"bulgaria\": \"🇧🇬\",\n    \"burkina_faso\": \"🇧🇫\",\n    \"burundi\": \"🇧🇮\",\n    \"cl_button\": \"🆑\",\n    \"cool_button\": \"🆒\",\n    \"cambodia\": \"🇰🇭\",\n    \"cameroon\": \"🇨🇲\",\n    \"canada\": \"🇨🇦\",\n    \"canary_islands\": \"🇮🇨\",\n    \"cancer\": \"♋\",\n    \"cape_verde\": \"🇨🇻\",\n    \"capricorn\": \"♑\",\n    \"caribbean_netherlands\": \"🇧🇶\",\n    \"cayman_islands\": \"🇰🇾\",\n    \"central_african_republic\": \"🇨🇫\",\n    \"ceuta_&_melilla\": \"🇪🇦\",\n    \"chad\": \"🇹🇩\",\n    \"chile\": \"🇨🇱\",\n    \"china\": \"🇨🇳\",\n    \"christmas_island\": \"🇨🇽\",\n    \"christmas_tree\": \"🎄\",\n    \"clipperton_island\": \"🇨🇵\",\n    \"cocos_(keeling)_islands\": \"🇨🇨\",\n    \"colombia\": \"🇨🇴\",\n    \"comoros\": \"🇰🇲\",\n    \"congo_-_brazzaville\": \"🇨🇬\",\n    \"congo_-_kinshasa\": \"🇨🇩\",\n    \"cook_islands\": \"🇨🇰\",\n    \"costa_rica\": \"🇨🇷\",\n    \"croatia\": \"🇭🇷\",\n    \"cuba\": \"🇨🇺\",\n    \"curaçao\": \"🇨🇼\",\n    \"cyprus\": \"🇨🇾\",\n    \"czechia\": \"🇨🇿\",\n    \"côte_d’ivoire\": \"🇨🇮\",\n    \"denmark\": \"🇩🇰\",\n    \"diego_garcia\": \"🇩🇬\",\n    \"djibouti\": \"🇩🇯\",\n    \"dominica\": \"🇩🇲\",\n    \"dominican_republic\": \"🇩🇴\",\n    \"end_arrow\": \"🔚\",\n    \"ecuador\": \"🇪🇨\",\n    \"egypt\": \"🇪🇬\",\n    \"el_salvador\": \"🇸🇻\",\n    \"england\": \"🏴\\U000e0067\\U000e0062\\U000e0065\\U000e006e\\U000e0067\\U000e007f\",\n    \"equatorial_guinea\": \"🇬🇶\",\n    \"eritrea\": \"🇪🇷\",\n    \"estonia\": \"🇪🇪\",\n    \"ethiopia\": \"🇪🇹\",\n    \"european_union\": \"🇪🇺\",\n    \"free_button\": \"🆓\",\n    \"falkland_islands\": \"🇫🇰\",\n    \"faroe_islands\": \"🇫🇴\",\n    \"fiji\": \"🇫🇯\",\n    \"finland\": \"🇫🇮\",\n    \"france\": \"🇫🇷\",\n    \"french_guiana\": \"🇬🇫\",\n    \"french_polynesia\": \"🇵🇫\",\n    \"french_southern_territories\": \"🇹🇫\",\n    \"gabon\": \"🇬🇦\",\n    \"gambia\": \"🇬🇲\",\n    \"gemini\": \"♊\",\n    \"georgia\": \"🇬🇪\",\n    \"germany\": \"🇩🇪\",\n    \"ghana\": \"🇬🇭\",\n    \"gibraltar\": \"🇬🇮\",\n    \"greece\": \"🇬🇷\",\n    \"greenland\": \"🇬🇱\",\n    \"grenada\": \"🇬🇩\",\n    \"guadeloupe\": \"🇬🇵\",\n    \"guam\": \"🇬🇺\",\n    \"guatemala\": \"🇬🇹\",\n    \"guernsey\": \"🇬🇬\",\n    \"guinea\": \"🇬🇳\",\n    \"guinea-bissau\": \"🇬🇼\",\n    \"guyana\": \"🇬🇾\",\n    \"haiti\": \"🇭🇹\",\n    \"heard_&_mcdonald_islands\": \"🇭🇲\",\n    \"honduras\": \"🇭🇳\",\n    \"hong_kong_sar_china\": \"🇭🇰\",\n    \"hungary\": \"🇭🇺\",\n    \"id_button\": \"🆔\",\n    \"iceland\": \"🇮🇸\",\n    \"india\": \"🇮🇳\",\n    \"indonesia\": \"🇮🇩\",\n    \"iran\": \"🇮🇷\",\n    \"iraq\": \"🇮🇶\",\n    \"ireland\": \"🇮🇪\",\n    \"isle_of_man\": \"🇮🇲\",\n    \"israel\": \"🇮🇱\",\n    \"italy\": \"🇮🇹\",\n    \"jamaica\": \"🇯🇲\",\n    \"japan\": \"🗾\",\n    \"japanese_acceptable_button\": \"🉑\",\n    \"japanese_application_button\": \"🈸\",\n    \"japanese_bargain_button\": \"🉐\",\n    \"japanese_castle\": \"🏯\",\n    \"japanese_congratulations_button\": \"㊗\",\n    \"japanese_discount_button\": \"🈹\",\n    \"japanese_dolls\": \"🎎\",\n    \"japanese_free_of_charge_button\": \"🈚\",\n    \"japanese_here_button\": \"🈁\",\n    \"japanese_monthly_amount_button\": \"🈷\",\n    \"japanese_no_vacancy_button\": \"🈵\",\n    \"japanese_not_free_of_charge_button\": \"🈶\",\n    \"japanese_open_for_business_button\": \"🈺\",\n    \"japanese_passing_grade_button\": \"🈴\",\n    \"japanese_post_office\": \"🏣\",\n    \"japanese_prohibited_button\": \"🈲\",\n    \"japanese_reserved_button\": \"🈯\",\n    \"japanese_secret_button\": \"㊙\",\n    \"japanese_service_charge_button\": \"🈂\",\n    \"japanese_symbol_for_beginner\": \"🔰\",\n    \"japanese_vacancy_button\": \"🈳\",\n    \"jersey\": \"🇯🇪\",\n    \"jordan\": \"🇯🇴\",\n    \"kazakhstan\": \"🇰🇿\",\n    \"kenya\": \"🇰🇪\",\n    \"kiribati\": \"🇰🇮\",\n    \"kosovo\": \"🇽🇰\",\n    \"kuwait\": \"🇰🇼\",\n    \"kyrgyzstan\": \"🇰🇬\",\n    \"laos\": \"🇱🇦\",\n    \"latvia\": \"🇱🇻\",\n    \"lebanon\": \"🇱🇧\",\n    \"leo\": \"♌\",\n    \"lesotho\": \"🇱🇸\",\n    \"liberia\": \"🇱🇷\",\n    \"libra\": \"♎\",\n    \"libya\": \"🇱🇾\",\n    \"liechtenstein\": \"🇱🇮\",\n    \"lithuania\": \"🇱🇹\",\n    \"luxembourg\": \"🇱🇺\",\n    \"macau_sar_china\": \"🇲🇴\",\n    \"macedonia\": \"🇲🇰\",\n    \"madagascar\": \"🇲🇬\",\n    \"malawi\": \"🇲🇼\",\n    \"malaysia\": \"🇲🇾\",\n    \"maldives\": \"🇲🇻\",\n    \"mali\": \"🇲🇱\",\n    \"malta\": \"🇲🇹\",\n    \"marshall_islands\": \"🇲🇭\",\n    \"martinique\": \"🇲🇶\",\n    \"mauritania\": \"🇲🇷\",\n    \"mauritius\": \"🇲🇺\",\n    \"mayotte\": \"🇾🇹\",\n    \"mexico\": \"🇲🇽\",\n    \"micronesia\": \"🇫🇲\",\n    \"moldova\": \"🇲🇩\",\n    \"monaco\": \"🇲🇨\",\n    \"mongolia\": \"🇲🇳\",\n    \"montenegro\": \"🇲🇪\",\n    \"montserrat\": \"🇲🇸\",\n    \"morocco\": \"🇲🇦\",\n    \"mozambique\": \"🇲🇿\",\n    \"mrs._claus\": \"🤶\",\n    \"mrs._claus_dark_skin_tone\": \"🤶🏿\",\n    \"mrs._claus_light_skin_tone\": \"🤶🏻\",\n    \"mrs._claus_medium-dark_skin_tone\": \"🤶🏾\",\n    \"mrs._claus_medium-light_skin_tone\": \"🤶🏼\",\n    \"mrs._claus_medium_skin_tone\": \"🤶🏽\",\n    \"myanmar_(burma)\": \"🇲🇲\",\n    \"new_button\": \"🆕\",\n    \"ng_button\": \"🆖\",\n    \"namibia\": \"🇳🇦\",\n    \"nauru\": \"🇳🇷\",\n    \"nepal\": \"🇳🇵\",\n    \"netherlands\": \"🇳🇱\",\n    \"new_caledonia\": \"🇳🇨\",\n    \"new_zealand\": \"🇳🇿\",\n    \"nicaragua\": \"🇳🇮\",\n    \"niger\": \"🇳🇪\",\n    \"nigeria\": \"🇳🇬\",\n    \"niue\": \"🇳🇺\",\n    \"norfolk_island\": \"🇳🇫\",\n    \"north_korea\": \"🇰🇵\",\n    \"northern_mariana_islands\": \"🇲🇵\",\n    \"norway\": \"🇳🇴\",\n    \"ok_button\": \"🆗\",\n    \"ok_hand\": \"👌\",\n    \"ok_hand_dark_skin_tone\": \"👌🏿\",\n    \"ok_hand_light_skin_tone\": \"👌🏻\",\n    \"ok_hand_medium-dark_skin_tone\": \"👌🏾\",\n    \"ok_hand_medium-light_skin_tone\": \"👌🏼\",\n    \"ok_hand_medium_skin_tone\": \"👌🏽\",\n    \"on!_arrow\": \"🔛\",\n    \"o_button_(blood_type)\": \"🅾\",\n    \"oman\": \"🇴🇲\",\n    \"ophiuchus\": \"⛎\",\n    \"p_button\": \"🅿\",\n    \"pakistan\": \"🇵🇰\",\n    \"palau\": \"🇵🇼\",\n    \"palestinian_territories\": \"🇵🇸\",\n    \"panama\": \"🇵🇦\",\n    \"papua_new_guinea\": \"🇵🇬\",\n    \"paraguay\": \"🇵🇾\",\n    \"peru\": \"🇵🇪\",\n    \"philippines\": \"🇵🇭\",\n    \"pisces\": \"♓\",\n    \"pitcairn_islands\": \"🇵🇳\",\n    \"poland\": \"🇵🇱\",\n    \"portugal\": \"🇵🇹\",\n    \"puerto_rico\": \"🇵🇷\",\n    \"qatar\": \"🇶🇦\",\n    \"romania\": \"🇷🇴\",\n    \"russia\": \"🇷🇺\",\n    \"rwanda\": \"🇷🇼\",\n    \"réunion\": \"🇷🇪\",\n    \"soon_arrow\": \"🔜\",\n    \"sos_button\": \"🆘\",\n    \"sagittarius\": \"♐\",\n    \"samoa\": \"🇼🇸\",\n    \"san_marino\": \"🇸🇲\",\n    \"santa_claus\": \"🎅\",\n    \"santa_claus_dark_skin_tone\": \"🎅🏿\",\n    \"santa_claus_light_skin_tone\": \"🎅🏻\",\n    \"santa_claus_medium-dark_skin_tone\": \"🎅🏾\",\n    \"santa_claus_medium-light_skin_tone\": \"🎅🏼\",\n    \"santa_claus_medium_skin_tone\": \"🎅🏽\",\n    \"saudi_arabia\": \"🇸🇦\",\n    \"scorpio\": \"♏\",\n    \"scotland\": \"🏴\\U000e0067\\U000e0062\\U000e0073\\U000e0063\\U000e0074\\U000e007f\",\n    \"senegal\": \"🇸🇳\",\n    \"serbia\": \"🇷🇸\",\n    \"seychelles\": \"🇸🇨\",\n    \"sierra_leone\": \"🇸🇱\",\n    \"singapore\": \"🇸🇬\",\n    \"sint_maarten\": \"🇸🇽\",\n    \"slovakia\": \"🇸🇰\",\n    \"slovenia\": \"🇸🇮\",\n    \"solomon_islands\": \"🇸🇧\",\n    \"somalia\": \"🇸🇴\",\n    \"south_africa\": \"🇿🇦\",\n    \"south_georgia_&_south_sandwich_islands\": \"🇬🇸\",\n    \"south_korea\": \"🇰🇷\",\n    \"south_sudan\": \"🇸🇸\",\n    \"spain\": \"🇪🇸\",\n    \"sri_lanka\": \"🇱🇰\",\n    \"st._barthélemy\": \"🇧🇱\",\n    \"st._helena\": \"🇸🇭\",\n    \"st._kitts_&_nevis\": \"🇰🇳\",\n    \"st._lucia\": \"🇱🇨\",\n    \"st._martin\": \"🇲🇫\",\n    \"st._pierre_&_miquelon\": \"🇵🇲\",\n    \"st._vincent_&_grenadines\": \"🇻🇨\",\n    \"statue_of_liberty\": \"🗽\",\n    \"sudan\": \"🇸🇩\",\n    \"suriname\": \"🇸🇷\",\n    \"svalbard_&_jan_mayen\": \"🇸🇯\",\n    \"swaziland\": \"🇸🇿\",\n    \"sweden\": \"🇸🇪\",\n    \"switzerland\": \"🇨🇭\",\n    \"syria\": \"🇸🇾\",\n    \"são_tomé_&_príncipe\": \"🇸🇹\",\n    \"t-rex\": \"🦖\",\n    \"top_arrow\": \"🔝\",\n    \"taiwan\": \"🇹🇼\",\n    \"tajikistan\": \"🇹🇯\",\n    \"tanzania\": \"🇹🇿\",\n    \"taurus\": \"♉\",\n    \"thailand\": \"🇹🇭\",\n    \"timor-leste\": \"🇹🇱\",\n    \"togo\": \"🇹🇬\",\n    \"tokelau\": \"🇹🇰\",\n    \"tokyo_tower\": \"🗼\",\n    \"tonga\": \"🇹🇴\",\n    \"trinidad_&_tobago\": \"🇹🇹\",\n    \"tristan_da_cunha\": \"🇹🇦\",\n    \"tunisia\": \"🇹🇳\",\n    \"turkey\": \"🦃\",\n    \"turkmenistan\": \"🇹🇲\",\n    \"turks_&_caicos_islands\": \"🇹🇨\",\n    \"tuvalu\": \"🇹🇻\",\n    \"u.s._outlying_islands\": \"🇺🇲\",\n    \"u.s._virgin_islands\": \"🇻🇮\",\n    \"up!_button\": \"🆙\",\n    \"uganda\": \"🇺🇬\",\n    \"ukraine\": \"🇺🇦\",\n    \"united_arab_emirates\": \"🇦🇪\",\n    \"united_kingdom\": \"🇬🇧\",\n    \"united_nations\": \"🇺🇳\",\n    \"united_states\": \"🇺🇸\",\n    \"uruguay\": \"🇺🇾\",\n    \"uzbekistan\": \"🇺🇿\",\n    \"vs_button\": \"🆚\",\n    \"vanuatu\": \"🇻🇺\",\n    \"vatican_city\": \"🇻🇦\",\n    \"venezuela\": \"🇻🇪\",\n    \"vietnam\": \"🇻🇳\",\n    \"virgo\": \"♍\",\n    \"wales\": \"🏴\\U000e0067\\U000e0062\\U000e0077\\U000e006c\\U000e0073\\U000e007f\",\n    \"wallis_&_futuna\": \"🇼🇫\",\n    \"western_sahara\": \"🇪🇭\",\n    \"yemen\": \"🇾🇪\",\n    \"zambia\": \"🇿🇲\",\n    \"zimbabwe\": \"🇿🇼\",\n    \"abacus\": \"🧮\",\n    \"adhesive_bandage\": \"🩹\",\n    \"admission_tickets\": \"🎟\",\n    \"adult\": \"🧑\",\n    \"adult_dark_skin_tone\": \"🧑🏿\",\n    \"adult_light_skin_tone\": \"🧑🏻\",\n    \"adult_medium-dark_skin_tone\": \"🧑🏾\",\n    \"adult_medium-light_skin_tone\": \"🧑🏼\",\n    \"adult_medium_skin_tone\": \"🧑🏽\",\n    \"aerial_tramway\": \"🚡\",\n    \"airplane\": \"✈\",\n    \"airplane_arrival\": \"🛬\",\n    \"airplane_departure\": \"🛫\",\n    \"alarm_clock\": \"⏰\",\n    \"alembic\": \"⚗\",\n    \"alien\": \"👽\",\n    \"alien_monster\": \"👾\",\n    \"ambulance\": \"🚑\",\n    \"american_football\": \"🏈\",\n    \"amphora\": \"🏺\",\n    \"anchor\": \"⚓\",\n    \"anger_symbol\": \"💢\",\n    \"angry_face\": \"😠\",\n    \"angry_face_with_horns\": \"👿\",\n    \"anguished_face\": \"😧\",\n    \"ant\": \"🐜\",\n    \"antenna_bars\": \"📶\",\n    \"anxious_face_with_sweat\": \"😰\",\n    \"articulated_lorry\": \"🚛\",\n    \"artist_palette\": \"🎨\",\n    \"astonished_face\": \"😲\",\n    \"atom_symbol\": \"⚛\",\n    \"auto_rickshaw\": \"🛺\",\n    \"automobile\": \"🚗\",\n    \"avocado\": \"🥑\",\n    \"axe\": \"🪓\",\n    \"baby\": \"👶\",\n    \"baby_angel\": \"👼\",\n    \"baby_angel_dark_skin_tone\": \"👼🏿\",\n    \"baby_angel_light_skin_tone\": \"👼🏻\",\n    \"baby_angel_medium-dark_skin_tone\": \"👼🏾\",\n    \"baby_angel_medium-light_skin_tone\": \"👼🏼\",\n    \"baby_angel_medium_skin_tone\": \"👼🏽\",\n    \"baby_bottle\": \"🍼\",\n    \"baby_chick\": \"🐤\",\n    \"baby_dark_skin_tone\": \"👶🏿\",\n    \"baby_light_skin_tone\": \"👶🏻\",\n    \"baby_medium-dark_skin_tone\": \"👶🏾\",\n    \"baby_medium-light_skin_tone\": \"👶🏼\",\n    \"baby_medium_skin_tone\": \"👶🏽\",\n    \"baby_symbol\": \"🚼\",\n    \"backhand_index_pointing_down\": \"👇\",\n    \"backhand_index_pointing_down_dark_skin_tone\": \"👇🏿\",\n    \"backhand_index_pointing_down_light_skin_tone\": \"👇🏻\",\n    \"backhand_index_pointing_down_medium-dark_skin_tone\": \"👇🏾\",\n    \"backhand_index_pointing_down_medium-light_skin_tone\": \"👇🏼\",\n    \"backhand_index_pointing_down_medium_skin_tone\": \"👇🏽\",\n    \"backhand_index_pointing_left\": \"👈\",\n    \"backhand_index_pointing_left_dark_skin_tone\": \"👈🏿\",\n    \"backhand_index_pointing_left_light_skin_tone\": \"👈🏻\",\n    \"backhand_index_pointing_left_medium-dark_skin_tone\": \"👈🏾\",\n    \"backhand_index_pointing_left_medium-light_skin_tone\": \"👈🏼\",\n    \"backhand_index_pointing_left_medium_skin_tone\": \"👈🏽\",\n    \"backhand_index_pointing_right\": \"👉\",\n    \"backhand_index_pointing_right_dark_skin_tone\": \"👉🏿\",\n    \"backhand_index_pointing_right_light_skin_tone\": \"👉🏻\",\n    \"backhand_index_pointing_right_medium-dark_skin_tone\": \"👉🏾\",\n    \"backhand_index_pointing_right_medium-light_skin_tone\": \"👉🏼\",\n    \"backhand_index_pointing_right_medium_skin_tone\": \"👉🏽\",\n    \"backhand_index_pointing_up\": \"👆\",\n    \"backhand_index_pointing_up_dark_skin_tone\": \"👆🏿\",\n    \"backhand_index_pointing_up_light_skin_tone\": \"👆🏻\",\n    \"backhand_index_pointing_up_medium-dark_skin_tone\": \"👆🏾\",\n    \"backhand_index_pointing_up_medium-light_skin_tone\": \"👆🏼\",\n    \"backhand_index_pointing_up_medium_skin_tone\": \"👆🏽\",\n    \"bacon\": \"🥓\",\n    \"badger\": \"🦡\",\n    \"badminton\": \"🏸\",\n    \"bagel\": \"🥯\",\n    \"baggage_claim\": \"🛄\",\n    \"baguette_bread\": \"🥖\",\n    \"balance_scale\": \"⚖\",\n    \"bald\": \"🦲\",\n    \"bald_man\": \"👨\\u200d🦲\",\n    \"bald_woman\": \"👩\\u200d🦲\",\n    \"ballet_shoes\": \"🩰\",\n    \"balloon\": \"🎈\",\n    \"ballot_box_with_ballot\": \"🗳\",\n    \"ballot_box_with_check\": \"☑\",\n    \"banana\": \"🍌\",\n    \"banjo\": \"🪕\",\n    \"bank\": \"🏦\",\n    \"bar_chart\": \"📊\",\n    \"barber_pole\": \"💈\",\n    \"baseball\": \"⚾\",\n    \"basket\": \"🧺\",\n    \"basketball\": \"🏀\",\n    \"bat\": \"🦇\",\n    \"bathtub\": \"🛁\",\n    \"battery\": \"🔋\",\n    \"beach_with_umbrella\": \"🏖\",\n    \"beaming_face_with_smiling_eyes\": \"😁\",\n    \"bear_face\": \"🐻\",\n    \"bearded_person\": \"🧔\",\n    \"bearded_person_dark_skin_tone\": \"🧔🏿\",\n    \"bearded_person_light_skin_tone\": \"🧔🏻\",\n    \"bearded_person_medium-dark_skin_tone\": \"🧔🏾\",\n    \"bearded_person_medium-light_skin_tone\": \"🧔🏼\",\n    \"bearded_person_medium_skin_tone\": \"🧔🏽\",\n    \"beating_heart\": \"💓\",\n    \"bed\": \"🛏\",\n    \"beer_mug\": \"🍺\",\n    \"bell\": \"🔔\",\n    \"bell_with_slash\": \"🔕\",\n    \"bellhop_bell\": \"🛎\",\n    \"bento_box\": \"🍱\",\n    \"beverage_box\": \"🧃\",\n    \"bicycle\": \"🚲\",\n    \"bikini\": \"👙\",\n    \"billed_cap\": \"🧢\",\n    \"biohazard\": \"☣\",\n    \"bird\": \"🐦\",\n    \"birthday_cake\": \"🎂\",\n    \"black_circle\": \"⚫\",\n    \"black_flag\": \"🏴\",\n    \"black_heart\": \"🖤\",\n    \"black_large_square\": \"⬛\",\n    \"black_medium-small_square\": \"◾\",\n    \"black_medium_square\": \"◼\",\n    \"black_nib\": \"✒\",\n    \"black_small_square\": \"▪\",\n    \"black_square_button\": \"🔲\",\n    \"blond-haired_man\": \"👱\\u200d♂️\",\n    \"blond-haired_man_dark_skin_tone\": \"👱🏿\\u200d♂️\",\n    \"blond-haired_man_light_skin_tone\": \"👱🏻\\u200d♂️\",\n    \"blond-haired_man_medium-dark_skin_tone\": \"👱🏾\\u200d♂️\",\n    \"blond-haired_man_medium-light_skin_tone\": \"👱🏼\\u200d♂️\",\n    \"blond-haired_man_medium_skin_tone\": \"👱🏽\\u200d♂️\",\n    \"blond-haired_person\": \"👱\",\n    \"blond-haired_person_dark_skin_tone\": \"👱🏿\",\n    \"blond-haired_person_light_skin_tone\": \"👱🏻\",\n    \"blond-haired_person_medium-dark_skin_tone\": \"👱🏾\",\n    \"blond-haired_person_medium-light_skin_tone\": \"👱🏼\",\n    \"blond-haired_person_medium_skin_tone\": \"👱🏽\",\n    \"blond-haired_woman\": \"👱\\u200d♀️\",\n    \"blond-haired_woman_dark_skin_tone\": \"👱🏿\\u200d♀️\",\n    \"blond-haired_woman_light_skin_tone\": \"👱🏻\\u200d♀️\",\n    \"blond-haired_woman_medium-dark_skin_tone\": \"👱🏾\\u200d♀️\",\n    \"blond-haired_woman_medium-light_skin_tone\": \"👱🏼\\u200d♀️\",\n    \"blond-haired_woman_medium_skin_tone\": \"👱🏽\\u200d♀️\",\n    \"blossom\": \"🌼\",\n    \"blowfish\": \"🐡\",\n    \"blue_book\": \"📘\",\n    \"blue_circle\": \"🔵\",\n    \"blue_heart\": \"💙\",\n    \"blue_square\": \"🟦\",\n    \"boar\": \"🐗\",\n    \"bomb\": \"💣\",\n    \"bone\": \"🦴\",\n    \"bookmark\": \"🔖\",\n    \"bookmark_tabs\": \"📑\",\n    \"books\": \"📚\",\n    \"bottle_with_popping_cork\": \"🍾\",\n    \"bouquet\": \"💐\",\n    \"bow_and_arrow\": \"🏹\",\n    \"bowl_with_spoon\": \"🥣\",\n    \"bowling\": \"🎳\",\n    \"boxing_glove\": \"🥊\",\n    \"boy\": \"👦\",\n    \"boy_dark_skin_tone\": \"👦🏿\",\n    \"boy_light_skin_tone\": \"👦🏻\",\n    \"boy_medium-dark_skin_tone\": \"👦🏾\",\n    \"boy_medium-light_skin_tone\": \"👦🏼\",\n    \"boy_medium_skin_tone\": \"👦🏽\",\n    \"brain\": \"🧠\",\n    \"bread\": \"🍞\",\n    \"breast-feeding\": \"🤱\",\n    \"breast-feeding_dark_skin_tone\": \"🤱🏿\",\n    \"breast-feeding_light_skin_tone\": \"🤱🏻\",\n    \"breast-feeding_medium-dark_skin_tone\": \"🤱🏾\",\n    \"breast-feeding_medium-light_skin_tone\": \"🤱🏼\",\n    \"breast-feeding_medium_skin_tone\": \"🤱🏽\",\n    \"brick\": \"🧱\",\n    \"bride_with_veil\": \"👰\",\n    \"bride_with_veil_dark_skin_tone\": \"👰🏿\",\n    \"bride_with_veil_light_skin_tone\": \"👰🏻\",\n    \"bride_with_veil_medium-dark_skin_tone\": \"👰🏾\",\n    \"bride_with_veil_medium-light_skin_tone\": \"👰🏼\",\n    \"bride_with_veil_medium_skin_tone\": \"👰🏽\",\n    \"bridge_at_night\": \"🌉\",\n    \"briefcase\": \"💼\",\n    \"briefs\": \"🩲\",\n    \"bright_button\": \"🔆\",\n    \"broccoli\": \"🥦\",\n    \"broken_heart\": \"💔\",\n    \"broom\": \"🧹\",\n    \"brown_circle\": \"🟤\",\n    \"brown_heart\": \"🤎\",\n    \"brown_square\": \"🟫\",\n    \"bug\": \"🐛\",\n    \"building_construction\": \"🏗\",\n    \"bullet_train\": \"🚅\",\n    \"burrito\": \"🌯\",\n    \"bus\": \"🚌\",\n    \"bus_stop\": \"🚏\",\n    \"bust_in_silhouette\": \"👤\",\n    \"busts_in_silhouette\": \"👥\",\n    \"butter\": \"🧈\",\n    \"butterfly\": \"🦋\",\n    \"cactus\": \"🌵\",\n    \"calendar\": \"📆\",\n    \"call_me_hand\": \"🤙\",\n    \"call_me_hand_dark_skin_tone\": \"🤙🏿\",\n    \"call_me_hand_light_skin_tone\": \"🤙🏻\",\n    \"call_me_hand_medium-dark_skin_tone\": \"🤙🏾\",\n    \"call_me_hand_medium-light_skin_tone\": \"🤙🏼\",\n    \"call_me_hand_medium_skin_tone\": \"🤙🏽\",\n    \"camel\": \"🐫\",\n    \"camera\": \"📷\",\n    \"camera_with_flash\": \"📸\",\n    \"camping\": \"🏕\",\n    \"candle\": \"🕯\",\n    \"candy\": \"🍬\",\n    \"canned_food\": \"🥫\",\n    \"canoe\": \"🛶\",\n    \"card_file_box\": \"🗃\",\n    \"card_index\": \"📇\",\n    \"card_index_dividers\": \"🗂\",\n    \"carousel_horse\": \"🎠\",\n    \"carp_streamer\": \"🎏\",\n    \"carrot\": \"🥕\",\n    \"castle\": \"🏰\",\n    \"cat\": \"🐱\",\n    \"cat_face\": \"🐱\",\n    \"cat_face_with_tears_of_joy\": \"😹\",\n    \"cat_face_with_wry_smile\": \"😼\",\n    \"chains\": \"⛓\",\n    \"chair\": \"🪑\",\n    \"chart_decreasing\": \"📉\",\n    \"chart_increasing\": \"📈\",\n    \"chart_increasing_with_yen\": \"💹\",\n    \"cheese_wedge\": \"🧀\",\n    \"chequered_flag\": \"🏁\",\n    \"cherries\": \"🍒\",\n    \"cherry_blossom\": \"🌸\",\n    \"chess_pawn\": \"♟\",\n    \"chestnut\": \"🌰\",\n    \"chicken\": \"🐔\",\n    \"child\": \"🧒\",\n    \"child_dark_skin_tone\": \"🧒🏿\",\n    \"child_light_skin_tone\": \"🧒🏻\",\n    \"child_medium-dark_skin_tone\": \"🧒🏾\",\n    \"child_medium-light_skin_tone\": \"🧒🏼\",\n    \"child_medium_skin_tone\": \"🧒🏽\",\n    \"children_crossing\": \"🚸\",\n    \"chipmunk\": \"🐿\",\n    \"chocolate_bar\": \"🍫\",\n    \"chopsticks\": \"🥢\",\n    \"church\": \"⛪\",\n    \"cigarette\": \"🚬\",\n    \"cinema\": \"🎦\",\n    \"circled_m\": \"Ⓜ\",\n    \"circus_tent\": \"🎪\",\n    \"cityscape\": \"🏙\",\n    \"cityscape_at_dusk\": \"🌆\",\n    \"clamp\": \"🗜\",\n    \"clapper_board\": \"🎬\",\n    \"clapping_hands\": \"👏\",\n    \"clapping_hands_dark_skin_tone\": \"👏🏿\",\n    \"clapping_hands_light_skin_tone\": \"👏🏻\",\n    \"clapping_hands_medium-dark_skin_tone\": \"👏🏾\",\n    \"clapping_hands_medium-light_skin_tone\": \"👏🏼\",\n    \"clapping_hands_medium_skin_tone\": \"👏🏽\",\n    \"classical_building\": \"🏛\",\n    \"clinking_beer_mugs\": \"🍻\",\n    \"clinking_glasses\": \"🥂\",\n    \"clipboard\": \"📋\",\n    \"clockwise_vertical_arrows\": \"🔃\",\n    \"closed_book\": \"📕\",\n    \"closed_mailbox_with_lowered_flag\": \"📪\",\n    \"closed_mailbox_with_raised_flag\": \"📫\",\n    \"closed_umbrella\": \"🌂\",\n    \"cloud\": \"☁\",\n    \"cloud_with_lightning\": \"🌩\",\n    \"cloud_with_lightning_and_rain\": \"⛈\",\n    \"cloud_with_rain\": \"🌧\",\n    \"cloud_with_snow\": \"🌨\",\n    \"clown_face\": \"🤡\",\n    \"club_suit\": \"♣\",\n    \"clutch_bag\": \"👝\",\n    \"coat\": \"🧥\",\n    \"cocktail_glass\": \"🍸\",\n    \"coconut\": \"🥥\",\n    \"coffin\": \"⚰\",\n    \"cold_face\": \"🥶\",\n    \"collision\": \"💥\",\n    \"comet\": \"☄\",\n    \"compass\": \"🧭\",\n    \"computer_disk\": \"💽\",\n    \"computer_mouse\": \"🖱\",\n    \"confetti_ball\": \"🎊\",\n    \"confounded_face\": \"😖\",\n    \"confused_face\": \"😕\",\n    \"construction\": \"🚧\",\n    \"construction_worker\": \"👷\",\n    \"construction_worker_dark_skin_tone\": \"👷🏿\",\n    \"construction_worker_light_skin_tone\": \"👷🏻\",\n    \"construction_worker_medium-dark_skin_tone\": \"👷🏾\",\n    \"construction_worker_medium-light_skin_tone\": \"👷🏼\",\n    \"construction_worker_medium_skin_tone\": \"👷🏽\",\n    \"control_knobs\": \"🎛\",\n    \"convenience_store\": \"🏪\",\n    \"cooked_rice\": \"🍚\",\n    \"cookie\": \"🍪\",\n    \"cooking\": \"🍳\",\n    \"copyright\": \"©\",\n    \"couch_and_lamp\": \"🛋\",\n    \"counterclockwise_arrows_button\": \"🔄\",\n    \"couple_with_heart\": \"💑\",\n    \"couple_with_heart_man_man\": \"👨\\u200d❤️\\u200d👨\",\n    \"couple_with_heart_woman_man\": \"👩\\u200d❤️\\u200d👨\",\n    \"couple_with_heart_woman_woman\": \"👩\\u200d❤️\\u200d👩\",\n    \"cow\": \"🐮\",\n    \"cow_face\": \"🐮\",\n    \"cowboy_hat_face\": \"🤠\",\n    \"crab\": \"🦀\",\n    \"crayon\": \"🖍\",\n    \"credit_card\": \"💳\",\n    \"crescent_moon\": \"🌙\",\n    \"cricket\": \"🦗\",\n    \"cricket_game\": \"🏏\",\n    \"crocodile\": \"🐊\",\n    \"croissant\": \"🥐\",\n    \"cross_mark\": \"❌\",\n    \"cross_mark_button\": \"❎\",\n    \"crossed_fingers\": \"🤞\",\n    \"crossed_fingers_dark_skin_tone\": \"🤞🏿\",\n    \"crossed_fingers_light_skin_tone\": \"🤞🏻\",\n    \"crossed_fingers_medium-dark_skin_tone\": \"🤞🏾\",\n    \"crossed_fingers_medium-light_skin_tone\": \"🤞🏼\",\n    \"crossed_fingers_medium_skin_tone\": \"🤞🏽\",\n    \"crossed_flags\": \"🎌\",\n    \"crossed_swords\": \"⚔\",\n    \"crown\": \"👑\",\n    \"crying_cat_face\": \"😿\",\n    \"crying_face\": \"😢\",\n    \"crystal_ball\": \"🔮\",\n    \"cucumber\": \"🥒\",\n    \"cupcake\": \"🧁\",\n    \"cup_with_straw\": \"🥤\",\n    \"curling_stone\": \"🥌\",\n    \"curly_hair\": \"🦱\",\n    \"curly-haired_man\": \"👨\\u200d🦱\",\n    \"curly-haired_woman\": \"👩\\u200d🦱\",\n    \"curly_loop\": \"➰\",\n    \"currency_exchange\": \"💱\",\n    \"curry_rice\": \"🍛\",\n    \"custard\": \"🍮\",\n    \"customs\": \"🛃\",\n    \"cut_of_meat\": \"🥩\",\n    \"cyclone\": \"🌀\",\n    \"dagger\": \"🗡\",\n    \"dango\": \"🍡\",\n    \"dashing_away\": \"💨\",\n    \"deaf_person\": \"🧏\",\n    \"deciduous_tree\": \"🌳\",\n    \"deer\": \"🦌\",\n    \"delivery_truck\": \"🚚\",\n    \"department_store\": \"🏬\",\n    \"derelict_house\": \"🏚\",\n    \"desert\": \"🏜\",\n    \"desert_island\": \"🏝\",\n    \"desktop_computer\": \"🖥\",\n    \"detective\": \"🕵\",\n    \"detective_dark_skin_tone\": \"🕵🏿\",\n    \"detective_light_skin_tone\": \"🕵🏻\",\n    \"detective_medium-dark_skin_tone\": \"🕵🏾\",\n    \"detective_medium-light_skin_tone\": \"🕵🏼\",\n    \"detective_medium_skin_tone\": \"🕵🏽\",\n    \"diamond_suit\": \"♦\",\n    \"diamond_with_a_dot\": \"💠\",\n    \"dim_button\": \"🔅\",\n    \"direct_hit\": \"🎯\",\n    \"disappointed_face\": \"😞\",\n    \"diving_mask\": \"🤿\",\n    \"diya_lamp\": \"🪔\",\n    \"dizzy\": \"💫\",\n    \"dizzy_face\": \"😵\",\n    \"dna\": \"🧬\",\n    \"dog\": \"🐶\",\n    \"dog_face\": \"🐶\",\n    \"dollar_banknote\": \"💵\",\n    \"dolphin\": \"🐬\",\n    \"door\": \"🚪\",\n    \"dotted_six-pointed_star\": \"🔯\",\n    \"double_curly_loop\": \"➿\",\n    \"double_exclamation_mark\": \"‼\",\n    \"doughnut\": \"🍩\",\n    \"dove\": \"🕊\",\n    \"down-left_arrow\": \"↙\",\n    \"down-right_arrow\": \"↘\",\n    \"down_arrow\": \"⬇\",\n    \"downcast_face_with_sweat\": \"😓\",\n    \"downwards_button\": \"🔽\",\n    \"dragon\": \"🐉\",\n    \"dragon_face\": \"🐲\",\n    \"dress\": \"👗\",\n    \"drooling_face\": \"🤤\",\n    \"drop_of_blood\": \"🩸\",\n    \"droplet\": \"💧\",\n    \"drum\": \"🥁\",\n    \"duck\": \"🦆\",\n    \"dumpling\": \"🥟\",\n    \"dvd\": \"📀\",\n    \"e-mail\": \"📧\",\n    \"eagle\": \"🦅\",\n    \"ear\": \"👂\",\n    \"ear_dark_skin_tone\": \"👂🏿\",\n    \"ear_light_skin_tone\": \"👂🏻\",\n    \"ear_medium-dark_skin_tone\": \"👂🏾\",\n    \"ear_medium-light_skin_tone\": \"👂🏼\",\n    \"ear_medium_skin_tone\": \"👂🏽\",\n    \"ear_of_corn\": \"🌽\",\n    \"ear_with_hearing_aid\": \"🦻\",\n    \"egg\": \"🍳\",\n    \"eggplant\": \"🍆\",\n    \"eight-pointed_star\": \"✴\",\n    \"eight-spoked_asterisk\": \"✳\",\n    \"eight-thirty\": \"🕣\",\n    \"eight_o’clock\": \"🕗\",\n    \"eject_button\": \"⏏\",\n    \"electric_plug\": \"🔌\",\n    \"elephant\": \"🐘\",\n    \"eleven-thirty\": \"🕦\",\n    \"eleven_o’clock\": \"🕚\",\n    \"elf\": \"🧝\",\n    \"elf_dark_skin_tone\": \"🧝🏿\",\n    \"elf_light_skin_tone\": \"🧝🏻\",\n    \"elf_medium-dark_skin_tone\": \"🧝🏾\",\n    \"elf_medium-light_skin_tone\": \"🧝🏼\",\n    \"elf_medium_skin_tone\": \"🧝🏽\",\n    \"envelope\": \"✉\",\n    \"envelope_with_arrow\": \"📩\",\n    \"euro_banknote\": \"💶\",\n    \"evergreen_tree\": \"🌲\",\n    \"ewe\": \"🐑\",\n    \"exclamation_mark\": \"❗\",\n    \"exclamation_question_mark\": \"⁉\",\n    \"exploding_head\": \"🤯\",\n    \"expressionless_face\": \"😑\",\n    \"eye\": \"👁\",\n    \"eye_in_speech_bubble\": \"👁️\\u200d🗨️\",\n    \"eyes\": \"👀\",\n    \"face_blowing_a_kiss\": \"😘\",\n    \"face_savoring_food\": \"😋\",\n    \"face_screaming_in_fear\": \"😱\",\n    \"face_vomiting\": \"🤮\",\n    \"face_with_hand_over_mouth\": \"🤭\",\n    \"face_with_head-bandage\": \"🤕\",\n    \"face_with_medical_mask\": \"😷\",\n    \"face_with_monocle\": \"🧐\",\n    \"face_with_open_mouth\": \"😮\",\n    \"face_with_raised_eyebrow\": \"🤨\",\n    \"face_with_rolling_eyes\": \"🙄\",\n    \"face_with_steam_from_nose\": \"😤\",\n    \"face_with_symbols_on_mouth\": \"🤬\",\n    \"face_with_tears_of_joy\": \"😂\",\n    \"face_with_thermometer\": \"🤒\",\n    \"face_with_tongue\": \"😛\",\n    \"face_without_mouth\": \"😶\",\n    \"factory\": \"🏭\",\n    \"fairy\": \"🧚\",\n    \"fairy_dark_skin_tone\": \"🧚🏿\",\n    \"fairy_light_skin_tone\": \"🧚🏻\",\n    \"fairy_medium-dark_skin_tone\": \"🧚🏾\",\n    \"fairy_medium-light_skin_tone\": \"🧚🏼\",\n    \"fairy_medium_skin_tone\": \"🧚🏽\",\n    \"falafel\": \"🧆\",\n    \"fallen_leaf\": \"🍂\",\n    \"family\": \"👪\",\n    \"family_man_boy\": \"👨\\u200d👦\",\n    \"family_man_boy_boy\": \"👨\\u200d👦\\u200d👦\",\n    \"family_man_girl\": \"👨\\u200d👧\",\n    \"family_man_girl_boy\": \"👨\\u200d👧\\u200d👦\",\n    \"family_man_girl_girl\": \"👨\\u200d👧\\u200d👧\",\n    \"family_man_man_boy\": \"👨\\u200d👨\\u200d👦\",\n    \"family_man_man_boy_boy\": \"👨\\u200d👨\\u200d👦\\u200d👦\",\n    \"family_man_man_girl\": \"👨\\u200d👨\\u200d👧\",\n    \"family_man_man_girl_boy\": \"👨\\u200d👨\\u200d👧\\u200d👦\",\n    \"family_man_man_girl_girl\": \"👨\\u200d👨\\u200d👧\\u200d👧\",\n    \"family_man_woman_boy\": \"👨\\u200d👩\\u200d👦\",\n    \"family_man_woman_boy_boy\": \"👨\\u200d👩\\u200d👦\\u200d👦\",\n    \"family_man_woman_girl\": \"👨\\u200d👩\\u200d👧\",\n    \"family_man_woman_girl_boy\": \"👨\\u200d👩\\u200d👧\\u200d👦\",\n    \"family_man_woman_girl_girl\": \"👨\\u200d👩\\u200d👧\\u200d👧\",\n    \"family_woman_boy\": \"👩\\u200d👦\",\n    \"family_woman_boy_boy\": \"👩\\u200d👦\\u200d👦\",\n    \"family_woman_girl\": \"👩\\u200d👧\",\n    \"family_woman_girl_boy\": \"👩\\u200d👧\\u200d👦\",\n    \"family_woman_girl_girl\": \"👩\\u200d👧\\u200d👧\",\n    \"family_woman_woman_boy\": \"👩\\u200d👩\\u200d👦\",\n    \"family_woman_woman_boy_boy\": \"👩\\u200d👩\\u200d👦\\u200d👦\",\n    \"family_woman_woman_girl\": \"👩\\u200d👩\\u200d👧\",\n    \"family_woman_woman_girl_boy\": \"👩\\u200d👩\\u200d👧\\u200d👦\",\n    \"family_woman_woman_girl_girl\": \"👩\\u200d👩\\u200d👧\\u200d👧\",\n    \"fast-forward_button\": \"⏩\",\n    \"fast_down_button\": \"⏬\",\n    \"fast_reverse_button\": \"⏪\",\n    \"fast_up_button\": \"⏫\",\n    \"fax_machine\": \"📠\",\n    \"fearful_face\": \"😨\",\n    \"female_sign\": \"♀\",\n    \"ferris_wheel\": \"🎡\",\n    \"ferry\": \"⛴\",\n    \"field_hockey\": \"🏑\",\n    \"file_cabinet\": \"🗄\",\n    \"file_folder\": \"📁\",\n    \"film_frames\": \"🎞\",\n    \"film_projector\": \"📽\",\n    \"fire\": \"🔥\",\n    \"fire_extinguisher\": \"🧯\",\n    \"firecracker\": \"🧨\",\n    \"fire_engine\": \"🚒\",\n    \"fireworks\": \"🎆\",\n    \"first_quarter_moon\": \"🌓\",\n    \"first_quarter_moon_face\": \"🌛\",\n    \"fish\": \"🐟\",\n    \"fish_cake_with_swirl\": \"🍥\",\n    \"fishing_pole\": \"🎣\",\n    \"five-thirty\": \"🕠\",\n    \"five_o’clock\": \"🕔\",\n    \"flag_in_hole\": \"⛳\",\n    \"flamingo\": \"🦩\",\n    \"flashlight\": \"🔦\",\n    \"flat_shoe\": \"🥿\",\n    \"fleur-de-lis\": \"⚜\",\n    \"flexed_biceps\": \"💪\",\n    \"flexed_biceps_dark_skin_tone\": \"💪🏿\",\n    \"flexed_biceps_light_skin_tone\": \"💪🏻\",\n    \"flexed_biceps_medium-dark_skin_tone\": \"💪🏾\",\n    \"flexed_biceps_medium-light_skin_tone\": \"💪🏼\",\n    \"flexed_biceps_medium_skin_tone\": \"💪🏽\",\n    \"floppy_disk\": \"💾\",\n    \"flower_playing_cards\": \"🎴\",\n    \"flushed_face\": \"😳\",\n    \"flying_disc\": \"🥏\",\n    \"flying_saucer\": \"🛸\",\n    \"fog\": \"🌫\",\n    \"foggy\": \"🌁\",\n    \"folded_hands\": \"🙏\",\n    \"folded_hands_dark_skin_tone\": \"🙏🏿\",\n    \"folded_hands_light_skin_tone\": \"🙏🏻\",\n    \"folded_hands_medium-dark_skin_tone\": \"🙏🏾\",\n    \"folded_hands_medium-light_skin_tone\": \"🙏🏼\",\n    \"folded_hands_medium_skin_tone\": \"🙏🏽\",\n    \"foot\": \"🦶\",\n    \"footprints\": \"👣\",\n    \"fork_and_knife\": \"🍴\",\n    \"fork_and_knife_with_plate\": \"🍽\",\n    \"fortune_cookie\": \"🥠\",\n    \"fountain\": \"⛲\",\n    \"fountain_pen\": \"🖋\",\n    \"four-thirty\": \"🕟\",\n    \"four_leaf_clover\": \"🍀\",\n    \"four_o’clock\": \"🕓\",\n    \"fox_face\": \"🦊\",\n    \"framed_picture\": \"🖼\",\n    \"french_fries\": \"🍟\",\n    \"fried_shrimp\": \"🍤\",\n    \"frog_face\": \"🐸\",\n    \"front-facing_baby_chick\": \"🐥\",\n    \"frowning_face\": \"☹\",\n    \"frowning_face_with_open_mouth\": \"😦\",\n    \"fuel_pump\": \"⛽\",\n    \"full_moon\": \"🌕\",\n    \"full_moon_face\": \"🌝\",\n    \"funeral_urn\": \"⚱\",\n    \"game_die\": \"🎲\",\n    \"garlic\": \"🧄\",\n    \"gear\": \"⚙\",\n    \"gem_stone\": \"💎\",\n    \"genie\": \"🧞\",\n    \"ghost\": \"👻\",\n    \"giraffe\": \"🦒\",\n    \"girl\": \"👧\",\n    \"girl_dark_skin_tone\": \"👧🏿\",\n    \"girl_light_skin_tone\": \"👧🏻\",\n    \"girl_medium-dark_skin_tone\": \"👧🏾\",\n    \"girl_medium-light_skin_tone\": \"👧🏼\",\n    \"girl_medium_skin_tone\": \"👧🏽\",\n    \"glass_of_milk\": \"🥛\",\n    \"glasses\": \"👓\",\n    \"globe_showing_americas\": \"🌎\",\n    \"globe_showing_asia-australia\": \"🌏\",\n    \"globe_showing_europe-africa\": \"🌍\",\n    \"globe_with_meridians\": \"🌐\",\n    \"gloves\": \"🧤\",\n    \"glowing_star\": \"🌟\",\n    \"goal_net\": \"🥅\",\n    \"goat\": \"🐐\",\n    \"goblin\": \"👺\",\n    \"goggles\": \"🥽\",\n    \"gorilla\": \"🦍\",\n    \"graduation_cap\": \"🎓\",\n    \"grapes\": \"🍇\",\n    \"green_apple\": \"🍏\",\n    \"green_book\": \"📗\",\n    \"green_circle\": \"🟢\",\n    \"green_heart\": \"💚\",\n    \"green_salad\": \"🥗\",\n    \"green_square\": \"🟩\",\n    \"grimacing_face\": \"😬\",\n    \"grinning_cat_face\": \"😺\",\n    \"grinning_cat_face_with_smiling_eyes\": \"😸\",\n    \"grinning_face\": \"😀\",\n    \"grinning_face_with_big_eyes\": \"😃\",\n    \"grinning_face_with_smiling_eyes\": \"😄\",\n    \"grinning_face_with_sweat\": \"😅\",\n    \"grinning_squinting_face\": \"😆\",\n    \"growing_heart\": \"💗\",\n    \"guard\": \"💂\",\n    \"guard_dark_skin_tone\": \"💂🏿\",\n    \"guard_light_skin_tone\": \"💂🏻\",\n    \"guard_medium-dark_skin_tone\": \"💂🏾\",\n    \"guard_medium-light_skin_tone\": \"💂🏼\",\n    \"guard_medium_skin_tone\": \"💂🏽\",\n    \"guide_dog\": \"🦮\",\n    \"guitar\": \"🎸\",\n    \"hamburger\": \"🍔\",\n    \"hammer\": \"🔨\",\n    \"hammer_and_pick\": \"⚒\",\n    \"hammer_and_wrench\": \"🛠\",\n    \"hamster_face\": \"🐹\",\n    \"hand_with_fingers_splayed\": \"🖐\",\n    \"hand_with_fingers_splayed_dark_skin_tone\": \"🖐🏿\",\n    \"hand_with_fingers_splayed_light_skin_tone\": \"🖐🏻\",\n    \"hand_with_fingers_splayed_medium-dark_skin_tone\": \"🖐🏾\",\n    \"hand_with_fingers_splayed_medium-light_skin_tone\": \"🖐🏼\",\n    \"hand_with_fingers_splayed_medium_skin_tone\": \"🖐🏽\",\n    \"handbag\": \"👜\",\n    \"handshake\": \"🤝\",\n    \"hatching_chick\": \"🐣\",\n    \"headphone\": \"🎧\",\n    \"hear-no-evil_monkey\": \"🙉\",\n    \"heart_decoration\": \"💟\",\n    \"heart_suit\": \"♥\",\n    \"heart_with_arrow\": \"💘\",\n    \"heart_with_ribbon\": \"💝\",\n    \"heavy_check_mark\": \"✔\",\n    \"heavy_division_sign\": \"➗\",\n    \"heavy_dollar_sign\": \"💲\",\n    \"heavy_heart_exclamation\": \"❣\",\n    \"heavy_large_circle\": \"⭕\",\n    \"heavy_minus_sign\": \"➖\",\n    \"heavy_multiplication_x\": \"✖\",\n    \"heavy_plus_sign\": \"➕\",\n    \"hedgehog\": \"🦔\",\n    \"helicopter\": \"🚁\",\n    \"herb\": \"🌿\",\n    \"hibiscus\": \"🌺\",\n    \"high-heeled_shoe\": \"👠\",\n    \"high-speed_train\": \"🚄\",\n    \"high_voltage\": \"⚡\",\n    \"hiking_boot\": \"🥾\",\n    \"hindu_temple\": \"🛕\",\n    \"hippopotamus\": \"🦛\",\n    \"hole\": \"🕳\",\n    \"honey_pot\": \"🍯\",\n    \"honeybee\": \"🐝\",\n    \"horizontal_traffic_light\": \"🚥\",\n    \"horse\": \"🐴\",\n    \"horse_face\": \"🐴\",\n    \"horse_racing\": \"🏇\",\n    \"horse_racing_dark_skin_tone\": \"🏇🏿\",\n    \"horse_racing_light_skin_tone\": \"🏇🏻\",\n    \"horse_racing_medium-dark_skin_tone\": \"🏇🏾\",\n    \"horse_racing_medium-light_skin_tone\": \"🏇🏼\",\n    \"horse_racing_medium_skin_tone\": \"🏇🏽\",\n    \"hospital\": \"🏥\",\n    \"hot_beverage\": \"☕\",\n    \"hot_dog\": \"🌭\",\n    \"hot_face\": \"🥵\",\n    \"hot_pepper\": \"🌶\",\n    \"hot_springs\": \"♨\",\n    \"hotel\": \"🏨\",\n    \"hourglass_done\": \"⌛\",\n    \"hourglass_not_done\": \"⏳\",\n    \"house\": \"🏠\",\n    \"house_with_garden\": \"🏡\",\n    \"houses\": \"🏘\",\n    \"hugging_face\": \"🤗\",\n    \"hundred_points\": \"💯\",\n    \"hushed_face\": \"😯\",\n    \"ice\": \"🧊\",\n    \"ice_cream\": \"🍨\",\n    \"ice_hockey\": \"🏒\",\n    \"ice_skate\": \"⛸\",\n    \"inbox_tray\": \"📥\",\n    \"incoming_envelope\": \"📨\",\n    \"index_pointing_up\": \"☝\",\n    \"index_pointing_up_dark_skin_tone\": \"☝🏿\",\n    \"index_pointing_up_light_skin_tone\": \"☝🏻\",\n    \"index_pointing_up_medium-dark_skin_tone\": \"☝🏾\",\n    \"index_pointing_up_medium-light_skin_tone\": \"☝🏼\",\n    \"index_pointing_up_medium_skin_tone\": \"☝🏽\",\n    \"infinity\": \"♾\",\n    \"information\": \"ℹ\",\n    \"input_latin_letters\": \"🔤\",\n    \"input_latin_lowercase\": \"🔡\",\n    \"input_latin_uppercase\": \"🔠\",\n    \"input_numbers\": \"🔢\",\n    \"input_symbols\": \"🔣\",\n    \"jack-o-lantern\": \"🎃\",\n    \"jeans\": \"👖\",\n    \"jigsaw\": \"🧩\",\n    \"joker\": \"🃏\",\n    \"joystick\": \"🕹\",\n    \"kaaba\": \"🕋\",\n    \"kangaroo\": \"🦘\",\n    \"key\": \"🔑\",\n    \"keyboard\": \"⌨\",\n    \"keycap_#\": \"#️⃣\",\n    \"keycap_*\": \"*️⃣\",\n    \"keycap_0\": \"0️⃣\",\n    \"keycap_1\": \"1️⃣\",\n    \"keycap_10\": \"🔟\",\n    \"keycap_2\": \"2️⃣\",\n    \"keycap_3\": \"3️⃣\",\n    \"keycap_4\": \"4️⃣\",\n    \"keycap_5\": \"5️⃣\",\n    \"keycap_6\": \"6️⃣\",\n    \"keycap_7\": \"7️⃣\",\n    \"keycap_8\": \"8️⃣\",\n    \"keycap_9\": \"9️⃣\",\n    \"kick_scooter\": \"🛴\",\n    \"kimono\": \"👘\",\n    \"kiss\": \"💋\",\n    \"kiss_man_man\": \"👨\\u200d❤️\\u200d💋\\u200d👨\",\n    \"kiss_mark\": \"💋\",\n    \"kiss_woman_man\": \"👩\\u200d❤️\\u200d💋\\u200d👨\",\n    \"kiss_woman_woman\": \"👩\\u200d❤️\\u200d💋\\u200d👩\",\n    \"kissing_cat_face\": \"😽\",\n    \"kissing_face\": \"😗\",\n    \"kissing_face_with_closed_eyes\": \"😚\",\n    \"kissing_face_with_smiling_eyes\": \"😙\",\n    \"kitchen_knife\": \"🔪\",\n    \"kite\": \"🪁\",\n    \"kiwi_fruit\": \"🥝\",\n    \"koala\": \"🐨\",\n    \"lab_coat\": \"🥼\",\n    \"label\": \"🏷\",\n    \"lacrosse\": \"🥍\",\n    \"lady_beetle\": \"🐞\",\n    \"laptop_computer\": \"💻\",\n    \"large_blue_diamond\": \"🔷\",\n    \"large_orange_diamond\": \"🔶\",\n    \"last_quarter_moon\": \"🌗\",\n    \"last_quarter_moon_face\": \"🌜\",\n    \"last_track_button\": \"⏮\",\n    \"latin_cross\": \"✝\",\n    \"leaf_fluttering_in_wind\": \"🍃\",\n    \"leafy_green\": \"🥬\",\n    \"ledger\": \"📒\",\n    \"left-facing_fist\": \"🤛\",\n    \"left-facing_fist_dark_skin_tone\": \"🤛🏿\",\n    \"left-facing_fist_light_skin_tone\": \"🤛🏻\",\n    \"left-facing_fist_medium-dark_skin_tone\": \"🤛🏾\",\n    \"left-facing_fist_medium-light_skin_tone\": \"🤛🏼\",\n    \"left-facing_fist_medium_skin_tone\": \"🤛🏽\",\n    \"left-right_arrow\": \"↔\",\n    \"left_arrow\": \"⬅\",\n    \"left_arrow_curving_right\": \"↪\",\n    \"left_luggage\": \"🛅\",\n    \"left_speech_bubble\": \"🗨\",\n    \"leg\": \"🦵\",\n    \"lemon\": \"🍋\",\n    \"leopard\": \"🐆\",\n    \"level_slider\": \"🎚\",\n    \"light_bulb\": \"💡\",\n    \"light_rail\": \"🚈\",\n    \"link\": \"🔗\",\n    \"linked_paperclips\": \"🖇\",\n    \"lion_face\": \"🦁\",\n    \"lipstick\": \"💄\",\n    \"litter_in_bin_sign\": \"🚮\",\n    \"lizard\": \"🦎\",\n    \"llama\": \"🦙\",\n    \"lobster\": \"🦞\",\n    \"locked\": \"🔒\",\n    \"locked_with_key\": \"🔐\",\n    \"locked_with_pen\": \"🔏\",\n    \"locomotive\": \"🚂\",\n    \"lollipop\": \"🍭\",\n    \"lotion_bottle\": \"🧴\",\n    \"loudly_crying_face\": \"😭\",\n    \"loudspeaker\": \"📢\",\n    \"love-you_gesture\": \"🤟\",\n    \"love-you_gesture_dark_skin_tone\": \"🤟🏿\",\n    \"love-you_gesture_light_skin_tone\": \"🤟🏻\",\n    \"love-you_gesture_medium-dark_skin_tone\": \"🤟🏾\",\n    \"love-you_gesture_medium-light_skin_tone\": \"🤟🏼\",\n    \"love-you_gesture_medium_skin_tone\": \"🤟🏽\",\n    \"love_hotel\": \"🏩\",\n    \"love_letter\": \"💌\",\n    \"luggage\": \"🧳\",\n    \"lying_face\": \"🤥\",\n    \"mage\": \"🧙\",\n    \"mage_dark_skin_tone\": \"🧙🏿\",\n    \"mage_light_skin_tone\": \"🧙🏻\",\n    \"mage_medium-dark_skin_tone\": \"🧙🏾\",\n    \"mage_medium-light_skin_tone\": \"🧙🏼\",\n    \"mage_medium_skin_tone\": \"🧙🏽\",\n    \"magnet\": \"🧲\",\n    \"magnifying_glass_tilted_left\": \"🔍\",\n    \"magnifying_glass_tilted_right\": \"🔎\",\n    \"mahjong_red_dragon\": \"🀄\",\n    \"male_sign\": \"♂\",\n    \"man\": \"👨\",\n    \"man_and_woman_holding_hands\": \"👫\",\n    \"man_artist\": \"👨\\u200d🎨\",\n    \"man_artist_dark_skin_tone\": \"👨🏿\\u200d🎨\",\n    \"man_artist_light_skin_tone\": \"👨🏻\\u200d🎨\",\n    \"man_artist_medium-dark_skin_tone\": \"👨🏾\\u200d🎨\",\n    \"man_artist_medium-light_skin_tone\": \"👨🏼\\u200d🎨\",\n    \"man_artist_medium_skin_tone\": \"👨🏽\\u200d🎨\",\n    \"man_astronaut\": \"👨\\u200d🚀\",\n    \"man_astronaut_dark_skin_tone\": \"👨🏿\\u200d🚀\",\n    \"man_astronaut_light_skin_tone\": \"👨🏻\\u200d🚀\",\n    \"man_astronaut_medium-dark_skin_tone\": \"👨🏾\\u200d🚀\",\n    \"man_astronaut_medium-light_skin_tone\": \"👨🏼\\u200d🚀\",\n    \"man_astronaut_medium_skin_tone\": \"👨🏽\\u200d🚀\",\n    \"man_biking\": \"🚴\\u200d♂️\",\n    \"man_biking_dark_skin_tone\": \"🚴🏿\\u200d♂️\",\n    \"man_biking_light_skin_tone\": \"🚴🏻\\u200d♂️\",\n    \"man_biking_medium-dark_skin_tone\": \"🚴🏾\\u200d♂️\",\n    \"man_biking_medium-light_skin_tone\": \"🚴🏼\\u200d♂️\",\n    \"man_biking_medium_skin_tone\": \"🚴🏽\\u200d♂️\",\n    \"man_bouncing_ball\": \"⛹️\\u200d♂️\",\n    \"man_bouncing_ball_dark_skin_tone\": \"⛹🏿\\u200d♂️\",\n    \"man_bouncing_ball_light_skin_tone\": \"⛹🏻\\u200d♂️\",\n    \"man_bouncing_ball_medium-dark_skin_tone\": \"⛹🏾\\u200d♂️\",\n    \"man_bouncing_ball_medium-light_skin_tone\": \"⛹🏼\\u200d♂️\",\n    \"man_bouncing_ball_medium_skin_tone\": \"⛹🏽\\u200d♂️\",\n    \"man_bowing\": \"🙇\\u200d♂️\",\n    \"man_bowing_dark_skin_tone\": \"🙇🏿\\u200d♂️\",\n    \"man_bowing_light_skin_tone\": \"🙇🏻\\u200d♂️\",\n    \"man_bowing_medium-dark_skin_tone\": \"🙇🏾\\u200d♂️\",\n    \"man_bowing_medium-light_skin_tone\": \"🙇🏼\\u200d♂️\",\n    \"man_bowing_medium_skin_tone\": \"🙇🏽\\u200d♂️\",\n    \"man_cartwheeling\": \"🤸\\u200d♂️\",\n    \"man_cartwheeling_dark_skin_tone\": \"🤸🏿\\u200d♂️\",\n    \"man_cartwheeling_light_skin_tone\": \"🤸🏻\\u200d♂️\",\n    \"man_cartwheeling_medium-dark_skin_tone\": \"🤸🏾\\u200d♂️\",\n    \"man_cartwheeling_medium-light_skin_tone\": \"🤸🏼\\u200d♂️\",\n    \"man_cartwheeling_medium_skin_tone\": \"🤸🏽\\u200d♂️\",\n    \"man_climbing\": \"🧗\\u200d♂️\",\n    \"man_climbing_dark_skin_tone\": \"🧗🏿\\u200d♂️\",\n    \"man_climbing_light_skin_tone\": \"🧗🏻\\u200d♂️\",\n    \"man_climbing_medium-dark_skin_tone\": \"🧗🏾\\u200d♂️\",\n    \"man_climbing_medium-light_skin_tone\": \"🧗🏼\\u200d♂️\",\n    \"man_climbing_medium_skin_tone\": \"🧗🏽\\u200d♂️\",\n    \"man_construction_worker\": \"👷\\u200d♂️\",\n    \"man_construction_worker_dark_skin_tone\": \"👷🏿\\u200d♂️\",\n    \"man_construction_worker_light_skin_tone\": \"👷🏻\\u200d♂️\",\n    \"man_construction_worker_medium-dark_skin_tone\": \"👷🏾\\u200d♂️\",\n    \"man_construction_worker_medium-light_skin_tone\": \"👷🏼\\u200d♂️\",\n    \"man_construction_worker_medium_skin_tone\": \"👷🏽\\u200d♂️\",\n    \"man_cook\": \"👨\\u200d🍳\",\n    \"man_cook_dark_skin_tone\": \"👨🏿\\u200d🍳\",\n    \"man_cook_light_skin_tone\": \"👨🏻\\u200d🍳\",\n    \"man_cook_medium-dark_skin_tone\": \"👨🏾\\u200d🍳\",\n    \"man_cook_medium-light_skin_tone\": \"👨🏼\\u200d🍳\",\n    \"man_cook_medium_skin_tone\": \"👨🏽\\u200d🍳\",\n    \"man_dancing\": \"🕺\",\n    \"man_dancing_dark_skin_tone\": \"🕺🏿\",\n    \"man_dancing_light_skin_tone\": \"🕺🏻\",\n    \"man_dancing_medium-dark_skin_tone\": \"🕺🏾\",\n    \"man_dancing_medium-light_skin_tone\": \"🕺🏼\",\n    \"man_dancing_medium_skin_tone\": \"🕺🏽\",\n    \"man_dark_skin_tone\": \"👨🏿\",\n    \"man_detective\": \"🕵️\\u200d♂️\",\n    \"man_detective_dark_skin_tone\": \"🕵🏿\\u200d♂️\",\n    \"man_detective_light_skin_tone\": \"🕵🏻\\u200d♂️\",\n    \"man_detective_medium-dark_skin_tone\": \"🕵🏾\\u200d♂️\",\n    \"man_detective_medium-light_skin_tone\": \"🕵🏼\\u200d♂️\",\n    \"man_detective_medium_skin_tone\": \"🕵🏽\\u200d♂️\",\n    \"man_elf\": \"🧝\\u200d♂️\",\n    \"man_elf_dark_skin_tone\": \"🧝🏿\\u200d♂️\",\n    \"man_elf_light_skin_tone\": \"🧝🏻\\u200d♂️\",\n    \"man_elf_medium-dark_skin_tone\": \"🧝🏾\\u200d♂️\",\n    \"man_elf_medium-light_skin_tone\": \"🧝🏼\\u200d♂️\",\n    \"man_elf_medium_skin_tone\": \"🧝🏽\\u200d♂️\",\n    \"man_facepalming\": \"🤦\\u200d♂️\",\n    \"man_facepalming_dark_skin_tone\": \"🤦🏿\\u200d♂️\",\n    \"man_facepalming_light_skin_tone\": \"🤦🏻\\u200d♂️\",\n    \"man_facepalming_medium-dark_skin_tone\": \"🤦🏾\\u200d♂️\",\n    \"man_facepalming_medium-light_skin_tone\": \"🤦🏼\\u200d♂️\",\n    \"man_facepalming_medium_skin_tone\": \"🤦🏽\\u200d♂️\",\n    \"man_factory_worker\": \"👨\\u200d🏭\",\n    \"man_factory_worker_dark_skin_tone\": \"👨🏿\\u200d🏭\",\n    \"man_factory_worker_light_skin_tone\": \"👨🏻\\u200d🏭\",\n    \"man_factory_worker_medium-dark_skin_tone\": \"👨🏾\\u200d🏭\",\n    \"man_factory_worker_medium-light_skin_tone\": \"👨🏼\\u200d🏭\",\n    \"man_factory_worker_medium_skin_tone\": \"👨🏽\\u200d🏭\",\n    \"man_fairy\": \"🧚\\u200d♂️\",\n    \"man_fairy_dark_skin_tone\": \"🧚🏿\\u200d♂️\",\n    \"man_fairy_light_skin_tone\": \"🧚🏻\\u200d♂️\",\n    \"man_fairy_medium-dark_skin_tone\": \"🧚🏾\\u200d♂️\",\n    \"man_fairy_medium-light_skin_tone\": \"🧚🏼\\u200d♂️\",\n    \"man_fairy_medium_skin_tone\": \"🧚🏽\\u200d♂️\",\n    \"man_farmer\": \"👨\\u200d🌾\",\n    \"man_farmer_dark_skin_tone\": \"👨🏿\\u200d🌾\",\n    \"man_farmer_light_skin_tone\": \"👨🏻\\u200d🌾\",\n    \"man_farmer_medium-dark_skin_tone\": \"👨🏾\\u200d🌾\",\n    \"man_farmer_medium-light_skin_tone\": \"👨🏼\\u200d🌾\",\n    \"man_farmer_medium_skin_tone\": \"👨🏽\\u200d🌾\",\n    \"man_firefighter\": \"👨\\u200d🚒\",\n    \"man_firefighter_dark_skin_tone\": \"👨🏿\\u200d🚒\",\n    \"man_firefighter_light_skin_tone\": \"👨🏻\\u200d🚒\",\n    \"man_firefighter_medium-dark_skin_tone\": \"👨🏾\\u200d🚒\",\n    \"man_firefighter_medium-light_skin_tone\": \"👨🏼\\u200d🚒\",\n    \"man_firefighter_medium_skin_tone\": \"👨🏽\\u200d🚒\",\n    \"man_frowning\": \"🙍\\u200d♂️\",\n    \"man_frowning_dark_skin_tone\": \"🙍🏿\\u200d♂️\",\n    \"man_frowning_light_skin_tone\": \"🙍🏻\\u200d♂️\",\n    \"man_frowning_medium-dark_skin_tone\": \"🙍🏾\\u200d♂️\",\n    \"man_frowning_medium-light_skin_tone\": \"🙍🏼\\u200d♂️\",\n    \"man_frowning_medium_skin_tone\": \"🙍🏽\\u200d♂️\",\n    \"man_genie\": \"🧞\\u200d♂️\",\n    \"man_gesturing_no\": \"🙅\\u200d♂️\",\n    \"man_gesturing_no_dark_skin_tone\": \"🙅🏿\\u200d♂️\",\n    \"man_gesturing_no_light_skin_tone\": \"🙅🏻\\u200d♂️\",\n    \"man_gesturing_no_medium-dark_skin_tone\": \"🙅🏾\\u200d♂️\",\n    \"man_gesturing_no_medium-light_skin_tone\": \"🙅🏼\\u200d♂️\",\n    \"man_gesturing_no_medium_skin_tone\": \"🙅🏽\\u200d♂️\",\n    \"man_gesturing_ok\": \"🙆\\u200d♂️\",\n    \"man_gesturing_ok_dark_skin_tone\": \"🙆🏿\\u200d♂️\",\n    \"man_gesturing_ok_light_skin_tone\": \"🙆🏻\\u200d♂️\",\n    \"man_gesturing_ok_medium-dark_skin_tone\": \"🙆🏾\\u200d♂️\",\n    \"man_gesturing_ok_medium-light_skin_tone\": \"🙆🏼\\u200d♂️\",\n    \"man_gesturing_ok_medium_skin_tone\": \"🙆🏽\\u200d♂️\",\n    \"man_getting_haircut\": \"💇\\u200d♂️\",\n    \"man_getting_haircut_dark_skin_tone\": \"💇🏿\\u200d♂️\",\n    \"man_getting_haircut_light_skin_tone\": \"💇🏻\\u200d♂️\",\n    \"man_getting_haircut_medium-dark_skin_tone\": \"💇🏾\\u200d♂️\",\n    \"man_getting_haircut_medium-light_skin_tone\": \"💇🏼\\u200d♂️\",\n    \"man_getting_haircut_medium_skin_tone\": \"💇🏽\\u200d♂️\",\n    \"man_getting_massage\": \"💆\\u200d♂️\",\n    \"man_getting_massage_dark_skin_tone\": \"💆🏿\\u200d♂️\",\n    \"man_getting_massage_light_skin_tone\": \"💆🏻\\u200d♂️\",\n    \"man_getting_massage_medium-dark_skin_tone\": \"💆🏾\\u200d♂️\",\n    \"man_getting_massage_medium-light_skin_tone\": \"💆🏼\\u200d♂️\",\n    \"man_getting_massage_medium_skin_tone\": \"💆🏽\\u200d♂️\",\n    \"man_golfing\": \"🏌️\\u200d♂️\",\n    \"man_golfing_dark_skin_tone\": \"🏌🏿\\u200d♂️\",\n    \"man_golfing_light_skin_tone\": \"🏌🏻\\u200d♂️\",\n    \"man_golfing_medium-dark_skin_tone\": \"🏌🏾\\u200d♂️\",\n    \"man_golfing_medium-light_skin_tone\": \"🏌🏼\\u200d♂️\",\n    \"man_golfing_medium_skin_tone\": \"🏌🏽\\u200d♂️\",\n    \"man_guard\": \"💂\\u200d♂️\",\n    \"man_guard_dark_skin_tone\": \"💂🏿\\u200d♂️\",\n    \"man_guard_light_skin_tone\": \"💂🏻\\u200d♂️\",\n    \"man_guard_medium-dark_skin_tone\": \"💂🏾\\u200d♂️\",\n    \"man_guard_medium-light_skin_tone\": \"💂🏼\\u200d♂️\",\n    \"man_guard_medium_skin_tone\": \"💂🏽\\u200d♂️\",\n    \"man_health_worker\": \"👨\\u200d⚕️\",\n    \"man_health_worker_dark_skin_tone\": \"👨🏿\\u200d⚕️\",\n    \"man_health_worker_light_skin_tone\": \"👨🏻\\u200d⚕️\",\n    \"man_health_worker_medium-dark_skin_tone\": \"👨🏾\\u200d⚕️\",\n    \"man_health_worker_medium-light_skin_tone\": \"👨🏼\\u200d⚕️\",\n    \"man_health_worker_medium_skin_tone\": \"👨🏽\\u200d⚕️\",\n    \"man_in_lotus_position\": \"🧘\\u200d♂️\",\n    \"man_in_lotus_position_dark_skin_tone\": \"🧘🏿\\u200d♂️\",\n    \"man_in_lotus_position_light_skin_tone\": \"🧘🏻\\u200d♂️\",\n    \"man_in_lotus_position_medium-dark_skin_tone\": \"🧘🏾\\u200d♂️\",\n    \"man_in_lotus_position_medium-light_skin_tone\": \"🧘🏼\\u200d♂️\",\n    \"man_in_lotus_position_medium_skin_tone\": \"🧘🏽\\u200d♂️\",\n    \"man_in_manual_wheelchair\": \"👨\\u200d🦽\",\n    \"man_in_motorized_wheelchair\": \"👨\\u200d🦼\",\n    \"man_in_steamy_room\": \"🧖\\u200d♂️\",\n    \"man_in_steamy_room_dark_skin_tone\": \"🧖🏿\\u200d♂️\",\n    \"man_in_steamy_room_light_skin_tone\": \"🧖🏻\\u200d♂️\",\n    \"man_in_steamy_room_medium-dark_skin_tone\": \"🧖🏾\\u200d♂️\",\n    \"man_in_steamy_room_medium-light_skin_tone\": \"🧖🏼\\u200d♂️\",\n    \"man_in_steamy_room_medium_skin_tone\": \"🧖🏽\\u200d♂️\",\n    \"man_in_suit_levitating\": \"🕴\",\n    \"man_in_suit_levitating_dark_skin_tone\": \"🕴🏿\",\n    \"man_in_suit_levitating_light_skin_tone\": \"🕴🏻\",\n    \"man_in_suit_levitating_medium-dark_skin_tone\": \"🕴🏾\",\n    \"man_in_suit_levitating_medium-light_skin_tone\": \"🕴🏼\",\n    \"man_in_suit_levitating_medium_skin_tone\": \"🕴🏽\",\n    \"man_in_tuxedo\": \"🤵\",\n    \"man_in_tuxedo_dark_skin_tone\": \"🤵🏿\",\n    \"man_in_tuxedo_light_skin_tone\": \"🤵🏻\",\n    \"man_in_tuxedo_medium-dark_skin_tone\": \"🤵🏾\",\n    \"man_in_tuxedo_medium-light_skin_tone\": \"🤵🏼\",\n    \"man_in_tuxedo_medium_skin_tone\": \"🤵🏽\",\n    \"man_judge\": \"👨\\u200d⚖️\",\n    \"man_judge_dark_skin_tone\": \"👨🏿\\u200d⚖️\",\n    \"man_judge_light_skin_tone\": \"👨🏻\\u200d⚖️\",\n    \"man_judge_medium-dark_skin_tone\": \"👨🏾\\u200d⚖️\",\n    \"man_judge_medium-light_skin_tone\": \"👨🏼\\u200d⚖️\",\n    \"man_judge_medium_skin_tone\": \"👨🏽\\u200d⚖️\",\n    \"man_juggling\": \"🤹\\u200d♂️\",\n    \"man_juggling_dark_skin_tone\": \"🤹🏿\\u200d♂️\",\n    \"man_juggling_light_skin_tone\": \"🤹🏻\\u200d♂️\",\n    \"man_juggling_medium-dark_skin_tone\": \"🤹🏾\\u200d♂️\",\n    \"man_juggling_medium-light_skin_tone\": \"🤹🏼\\u200d♂️\",\n    \"man_juggling_medium_skin_tone\": \"🤹🏽\\u200d♂️\",\n    \"man_lifting_weights\": \"🏋️\\u200d♂️\",\n    \"man_lifting_weights_dark_skin_tone\": \"🏋🏿\\u200d♂️\",\n    \"man_lifting_weights_light_skin_tone\": \"🏋🏻\\u200d♂️\",\n    \"man_lifting_weights_medium-dark_skin_tone\": \"🏋🏾\\u200d♂️\",\n    \"man_lifting_weights_medium-light_skin_tone\": \"🏋🏼\\u200d♂️\",\n    \"man_lifting_weights_medium_skin_tone\": \"🏋🏽\\u200d♂️\",\n    \"man_light_skin_tone\": \"👨🏻\",\n    \"man_mage\": \"🧙\\u200d♂️\",\n    \"man_mage_dark_skin_tone\": \"🧙🏿\\u200d♂️\",\n    \"man_mage_light_skin_tone\": \"🧙🏻\\u200d♂️\",\n    \"man_mage_medium-dark_skin_tone\": \"🧙🏾\\u200d♂️\",\n    \"man_mage_medium-light_skin_tone\": \"🧙🏼\\u200d♂️\",\n    \"man_mage_medium_skin_tone\": \"🧙🏽\\u200d♂️\",\n    \"man_mechanic\": \"👨\\u200d🔧\",\n    \"man_mechanic_dark_skin_tone\": \"👨🏿\\u200d🔧\",\n    \"man_mechanic_light_skin_tone\": \"👨🏻\\u200d🔧\",\n    \"man_mechanic_medium-dark_skin_tone\": \"👨🏾\\u200d🔧\",\n    \"man_mechanic_medium-light_skin_tone\": \"👨🏼\\u200d🔧\",\n    \"man_mechanic_medium_skin_tone\": \"👨🏽\\u200d🔧\",\n    \"man_medium-dark_skin_tone\": \"👨🏾\",\n    \"man_medium-light_skin_tone\": \"👨🏼\",\n    \"man_medium_skin_tone\": \"👨🏽\",\n    \"man_mountain_biking\": \"🚵\\u200d♂️\",\n    \"man_mountain_biking_dark_skin_tone\": \"🚵🏿\\u200d♂️\",\n    \"man_mountain_biking_light_skin_tone\": \"🚵🏻\\u200d♂️\",\n    \"man_mountain_biking_medium-dark_skin_tone\": \"🚵🏾\\u200d♂️\",\n    \"man_mountain_biking_medium-light_skin_tone\": \"🚵🏼\\u200d♂️\",\n    \"man_mountain_biking_medium_skin_tone\": \"🚵🏽\\u200d♂️\",\n    \"man_office_worker\": \"👨\\u200d💼\",\n    \"man_office_worker_dark_skin_tone\": \"👨🏿\\u200d💼\",\n    \"man_office_worker_light_skin_tone\": \"👨🏻\\u200d💼\",\n    \"man_office_worker_medium-dark_skin_tone\": \"👨🏾\\u200d💼\",\n    \"man_office_worker_medium-light_skin_tone\": \"👨🏼\\u200d💼\",\n    \"man_office_worker_medium_skin_tone\": \"👨🏽\\u200d💼\",\n    \"man_pilot\": \"👨\\u200d✈️\",\n    \"man_pilot_dark_skin_tone\": \"👨🏿\\u200d✈️\",\n    \"man_pilot_light_skin_tone\": \"👨🏻\\u200d✈️\",\n    \"man_pilot_medium-dark_skin_tone\": \"👨🏾\\u200d✈️\",\n    \"man_pilot_medium-light_skin_tone\": \"👨🏼\\u200d✈️\",\n    \"man_pilot_medium_skin_tone\": \"👨🏽\\u200d✈️\",\n    \"man_playing_handball\": \"🤾\\u200d♂️\",\n    \"man_playing_handball_dark_skin_tone\": \"🤾🏿\\u200d♂️\",\n    \"man_playing_handball_light_skin_tone\": \"🤾🏻\\u200d♂️\",\n    \"man_playing_handball_medium-dark_skin_tone\": \"🤾🏾\\u200d♂️\",\n    \"man_playing_handball_medium-light_skin_tone\": \"🤾🏼\\u200d♂️\",\n    \"man_playing_handball_medium_skin_tone\": \"🤾🏽\\u200d♂️\",\n    \"man_playing_water_polo\": \"🤽\\u200d♂️\",\n    \"man_playing_water_polo_dark_skin_tone\": \"🤽🏿\\u200d♂️\",\n    \"man_playing_water_polo_light_skin_tone\": \"🤽🏻\\u200d♂️\",\n    \"man_playing_water_polo_medium-dark_skin_tone\": \"🤽🏾\\u200d♂️\",\n    \"man_playing_water_polo_medium-light_skin_tone\": \"🤽🏼\\u200d♂️\",\n    \"man_playing_water_polo_medium_skin_tone\": \"🤽🏽\\u200d♂️\",\n    \"man_police_officer\": \"👮\\u200d♂️\",\n    \"man_police_officer_dark_skin_tone\": \"👮🏿\\u200d♂️\",\n    \"man_police_officer_light_skin_tone\": \"👮🏻\\u200d♂️\",\n    \"man_police_officer_medium-dark_skin_tone\": \"👮🏾\\u200d♂️\",\n    \"man_police_officer_medium-light_skin_tone\": \"👮🏼\\u200d♂️\",\n    \"man_police_officer_medium_skin_tone\": \"👮🏽\\u200d♂️\",\n    \"man_pouting\": \"🙎\\u200d♂️\",\n    \"man_pouting_dark_skin_tone\": \"🙎🏿\\u200d♂️\",\n    \"man_pouting_light_skin_tone\": \"🙎🏻\\u200d♂️\",\n    \"man_pouting_medium-dark_skin_tone\": \"🙎🏾\\u200d♂️\",\n    \"man_pouting_medium-light_skin_tone\": \"🙎🏼\\u200d♂️\",\n    \"man_pouting_medium_skin_tone\": \"🙎🏽\\u200d♂️\",\n    \"man_raising_hand\": \"🙋\\u200d♂️\",\n    \"man_raising_hand_dark_skin_tone\": \"🙋🏿\\u200d♂️\",\n    \"man_raising_hand_light_skin_tone\": \"🙋🏻\\u200d♂️\",\n    \"man_raising_hand_medium-dark_skin_tone\": \"🙋🏾\\u200d♂️\",\n    \"man_raising_hand_medium-light_skin_tone\": \"🙋🏼\\u200d♂️\",\n    \"man_raising_hand_medium_skin_tone\": \"🙋🏽\\u200d♂️\",\n    \"man_rowing_boat\": \"🚣\\u200d♂️\",\n    \"man_rowing_boat_dark_skin_tone\": \"🚣🏿\\u200d♂️\",\n    \"man_rowing_boat_light_skin_tone\": \"🚣🏻\\u200d♂️\",\n    \"man_rowing_boat_medium-dark_skin_tone\": \"🚣🏾\\u200d♂️\",\n    \"man_rowing_boat_medium-light_skin_tone\": \"🚣🏼\\u200d♂️\",\n    \"man_rowing_boat_medium_skin_tone\": \"🚣🏽\\u200d♂️\",\n    \"man_running\": \"🏃\\u200d♂️\",\n    \"man_running_dark_skin_tone\": \"🏃🏿\\u200d♂️\",\n    \"man_running_light_skin_tone\": \"🏃🏻\\u200d♂️\",\n    \"man_running_medium-dark_skin_tone\": \"🏃🏾\\u200d♂️\",\n    \"man_running_medium-light_skin_tone\": \"🏃🏼\\u200d♂️\",\n    \"man_running_medium_skin_tone\": \"🏃🏽\\u200d♂️\",\n    \"man_scientist\": \"👨\\u200d🔬\",\n    \"man_scientist_dark_skin_tone\": \"👨🏿\\u200d🔬\",\n    \"man_scientist_light_skin_tone\": \"👨🏻\\u200d🔬\",\n    \"man_scientist_medium-dark_skin_tone\": \"👨🏾\\u200d🔬\",\n    \"man_scientist_medium-light_skin_tone\": \"👨🏼\\u200d🔬\",\n    \"man_scientist_medium_skin_tone\": \"👨🏽\\u200d🔬\",\n    \"man_shrugging\": \"🤷\\u200d♂️\",\n    \"man_shrugging_dark_skin_tone\": \"🤷🏿\\u200d♂️\",\n    \"man_shrugging_light_skin_tone\": \"🤷🏻\\u200d♂️\",\n    \"man_shrugging_medium-dark_skin_tone\": \"🤷🏾\\u200d♂️\",\n    \"man_shrugging_medium-light_skin_tone\": \"🤷🏼\\u200d♂️\",\n    \"man_shrugging_medium_skin_tone\": \"🤷🏽\\u200d♂️\",\n    \"man_singer\": \"👨\\u200d🎤\",\n    \"man_singer_dark_skin_tone\": \"👨🏿\\u200d🎤\",\n    \"man_singer_light_skin_tone\": \"👨🏻\\u200d🎤\",\n    \"man_singer_medium-dark_skin_tone\": \"👨🏾\\u200d🎤\",\n    \"man_singer_medium-light_skin_tone\": \"👨🏼\\u200d🎤\",\n    \"man_singer_medium_skin_tone\": \"👨🏽\\u200d🎤\",\n    \"man_student\": \"👨\\u200d🎓\",\n    \"man_student_dark_skin_tone\": \"👨🏿\\u200d🎓\",\n    \"man_student_light_skin_tone\": \"👨🏻\\u200d🎓\",\n    \"man_student_medium-dark_skin_tone\": \"👨🏾\\u200d🎓\",\n    \"man_student_medium-light_skin_tone\": \"👨🏼\\u200d🎓\",\n    \"man_student_medium_skin_tone\": \"👨🏽\\u200d🎓\",\n    \"man_surfing\": \"🏄\\u200d♂️\",\n    \"man_surfing_dark_skin_tone\": \"🏄🏿\\u200d♂️\",\n    \"man_surfing_light_skin_tone\": \"🏄🏻\\u200d♂️\",\n    \"man_surfing_medium-dark_skin_tone\": \"🏄🏾\\u200d♂️\",\n    \"man_surfing_medium-light_skin_tone\": \"🏄🏼\\u200d♂️\",\n    \"man_surfing_medium_skin_tone\": \"🏄🏽\\u200d♂️\",\n    \"man_swimming\": \"🏊\\u200d♂️\",\n    \"man_swimming_dark_skin_tone\": \"🏊🏿\\u200d♂️\",\n    \"man_swimming_light_skin_tone\": \"🏊🏻\\u200d♂️\",\n    \"man_swimming_medium-dark_skin_tone\": \"🏊🏾\\u200d♂️\",\n    \"man_swimming_medium-light_skin_tone\": \"🏊🏼\\u200d♂️\",\n    \"man_swimming_medium_skin_tone\": \"🏊🏽\\u200d♂️\",\n    \"man_teacher\": \"👨\\u200d🏫\",\n    \"man_teacher_dark_skin_tone\": \"👨🏿\\u200d🏫\",\n    \"man_teacher_light_skin_tone\": \"👨🏻\\u200d🏫\",\n    \"man_teacher_medium-dark_skin_tone\": \"👨🏾\\u200d🏫\",\n    \"man_teacher_medium-light_skin_tone\": \"👨🏼\\u200d🏫\",\n    \"man_teacher_medium_skin_tone\": \"👨🏽\\u200d🏫\",\n    \"man_technologist\": \"👨\\u200d💻\",\n    \"man_technologist_dark_skin_tone\": \"👨🏿\\u200d💻\",\n    \"man_technologist_light_skin_tone\": \"👨🏻\\u200d💻\",\n    \"man_technologist_medium-dark_skin_tone\": \"👨🏾\\u200d💻\",\n    \"man_technologist_medium-light_skin_tone\": \"👨🏼\\u200d💻\",\n    \"man_technologist_medium_skin_tone\": \"👨🏽\\u200d💻\",\n    \"man_tipping_hand\": \"💁\\u200d♂️\",\n    \"man_tipping_hand_dark_skin_tone\": \"💁🏿\\u200d♂️\",\n    \"man_tipping_hand_light_skin_tone\": \"💁🏻\\u200d♂️\",\n    \"man_tipping_hand_medium-dark_skin_tone\": \"💁🏾\\u200d♂️\",\n    \"man_tipping_hand_medium-light_skin_tone\": \"💁🏼\\u200d♂️\",\n    \"man_tipping_hand_medium_skin_tone\": \"💁🏽\\u200d♂️\",\n    \"man_vampire\": \"🧛\\u200d♂️\",\n    \"man_vampire_dark_skin_tone\": \"🧛🏿\\u200d♂️\",\n    \"man_vampire_light_skin_tone\": \"🧛🏻\\u200d♂️\",\n    \"man_vampire_medium-dark_skin_tone\": \"🧛🏾\\u200d♂️\",\n    \"man_vampire_medium-light_skin_tone\": \"🧛🏼\\u200d♂️\",\n    \"man_vampire_medium_skin_tone\": \"🧛🏽\\u200d♂️\",\n    \"man_walking\": \"🚶\\u200d♂️\",\n    \"man_walking_dark_skin_tone\": \"🚶🏿\\u200d♂️\",\n    \"man_walking_light_skin_tone\": \"🚶🏻\\u200d♂️\",\n    \"man_walking_medium-dark_skin_tone\": \"🚶🏾\\u200d♂️\",\n    \"man_walking_medium-light_skin_tone\": \"🚶🏼\\u200d♂️\",\n    \"man_walking_medium_skin_tone\": \"🚶🏽\\u200d♂️\",\n    \"man_wearing_turban\": \"👳\\u200d♂️\",\n    \"man_wearing_turban_dark_skin_tone\": \"👳🏿\\u200d♂️\",\n    \"man_wearing_turban_light_skin_tone\": \"👳🏻\\u200d♂️\",\n    \"man_wearing_turban_medium-dark_skin_tone\": \"👳🏾\\u200d♂️\",\n    \"man_wearing_turban_medium-light_skin_tone\": \"👳🏼\\u200d♂️\",\n    \"man_wearing_turban_medium_skin_tone\": \"👳🏽\\u200d♂️\",\n    \"man_with_probing_cane\": \"👨\\u200d🦯\",\n    \"man_with_chinese_cap\": \"👲\",\n    \"man_with_chinese_cap_dark_skin_tone\": \"👲🏿\",\n    \"man_with_chinese_cap_light_skin_tone\": \"👲🏻\",\n    \"man_with_chinese_cap_medium-dark_skin_tone\": \"👲🏾\",\n    \"man_with_chinese_cap_medium-light_skin_tone\": \"👲🏼\",\n    \"man_with_chinese_cap_medium_skin_tone\": \"👲🏽\",\n    \"man_zombie\": \"🧟\\u200d♂️\",\n    \"mango\": \"🥭\",\n    \"mantelpiece_clock\": \"🕰\",\n    \"manual_wheelchair\": \"🦽\",\n    \"man’s_shoe\": \"👞\",\n    \"map_of_japan\": \"🗾\",\n    \"maple_leaf\": \"🍁\",\n    \"martial_arts_uniform\": \"🥋\",\n    \"mate\": \"🧉\",\n    \"meat_on_bone\": \"🍖\",\n    \"mechanical_arm\": \"🦾\",\n    \"mechanical_leg\": \"🦿\",\n    \"medical_symbol\": \"⚕\",\n    \"megaphone\": \"📣\",\n    \"melon\": \"🍈\",\n    \"memo\": \"📝\",\n    \"men_with_bunny_ears\": \"👯\\u200d♂️\",\n    \"men_wrestling\": \"🤼\\u200d♂️\",\n    \"menorah\": \"🕎\",\n    \"men’s_room\": \"🚹\",\n    \"mermaid\": \"🧜\\u200d♀️\",\n    \"mermaid_dark_skin_tone\": \"🧜🏿\\u200d♀️\",\n    \"mermaid_light_skin_tone\": \"🧜🏻\\u200d♀️\",\n    \"mermaid_medium-dark_skin_tone\": \"🧜🏾\\u200d♀️\",\n    \"mermaid_medium-light_skin_tone\": \"🧜🏼\\u200d♀️\",\n    \"mermaid_medium_skin_tone\": \"🧜🏽\\u200d♀️\",\n    \"merman\": \"🧜\\u200d♂️\",\n    \"merman_dark_skin_tone\": \"🧜🏿\\u200d♂️\",\n    \"merman_light_skin_tone\": \"🧜🏻\\u200d♂️\",\n    \"merman_medium-dark_skin_tone\": \"🧜🏾\\u200d♂️\",\n    \"merman_medium-light_skin_tone\": \"🧜🏼\\u200d♂️\",\n    \"merman_medium_skin_tone\": \"🧜🏽\\u200d♂️\",\n    \"merperson\": \"🧜\",\n    \"merperson_dark_skin_tone\": \"🧜🏿\",\n    \"merperson_light_skin_tone\": \"🧜🏻\",\n    \"merperson_medium-dark_skin_tone\": \"🧜🏾\",\n    \"merperson_medium-light_skin_tone\": \"🧜🏼\",\n    \"merperson_medium_skin_tone\": \"🧜🏽\",\n    \"metro\": \"🚇\",\n    \"microbe\": \"🦠\",\n    \"microphone\": \"🎤\",\n    \"microscope\": \"🔬\",\n    \"middle_finger\": \"🖕\",\n    \"middle_finger_dark_skin_tone\": \"🖕🏿\",\n    \"middle_finger_light_skin_tone\": \"🖕🏻\",\n    \"middle_finger_medium-dark_skin_tone\": \"🖕🏾\",\n    \"middle_finger_medium-light_skin_tone\": \"🖕🏼\",\n    \"middle_finger_medium_skin_tone\": \"🖕🏽\",\n    \"military_medal\": \"🎖\",\n    \"milky_way\": \"🌌\",\n    \"minibus\": \"🚐\",\n    \"moai\": \"🗿\",\n    \"mobile_phone\": \"📱\",\n    \"mobile_phone_off\": \"📴\",\n    \"mobile_phone_with_arrow\": \"📲\",\n    \"money-mouth_face\": \"🤑\",\n    \"money_bag\": \"💰\",\n    \"money_with_wings\": \"💸\",\n    \"monkey\": \"🐒\",\n    \"monkey_face\": \"🐵\",\n    \"monorail\": \"🚝\",\n    \"moon_cake\": \"🥮\",\n    \"moon_viewing_ceremony\": \"🎑\",\n    \"mosque\": \"🕌\",\n    \"mosquito\": \"🦟\",\n    \"motor_boat\": \"🛥\",\n    \"motor_scooter\": \"🛵\",\n    \"motorcycle\": \"🏍\",\n    \"motorized_wheelchair\": \"🦼\",\n    \"motorway\": \"🛣\",\n    \"mount_fuji\": \"🗻\",\n    \"mountain\": \"⛰\",\n    \"mountain_cableway\": \"🚠\",\n    \"mountain_railway\": \"🚞\",\n    \"mouse\": \"🐭\",\n    \"mouse_face\": \"🐭\",\n    \"mouth\": \"👄\",\n    \"movie_camera\": \"🎥\",\n    \"mushroom\": \"🍄\",\n    \"musical_keyboard\": \"🎹\",\n    \"musical_note\": \"🎵\",\n    \"musical_notes\": \"🎶\",\n    \"musical_score\": \"🎼\",\n    \"muted_speaker\": \"🔇\",\n    \"nail_polish\": \"💅\",\n    \"nail_polish_dark_skin_tone\": \"💅🏿\",\n    \"nail_polish_light_skin_tone\": \"💅🏻\",\n    \"nail_polish_medium-dark_skin_tone\": \"💅🏾\",\n    \"nail_polish_medium-light_skin_tone\": \"💅🏼\",\n    \"nail_polish_medium_skin_tone\": \"💅🏽\",\n    \"name_badge\": \"📛\",\n    \"national_park\": \"🏞\",\n    \"nauseated_face\": \"🤢\",\n    \"nazar_amulet\": \"🧿\",\n    \"necktie\": \"👔\",\n    \"nerd_face\": \"🤓\",\n    \"neutral_face\": \"😐\",\n    \"new_moon\": \"🌑\",\n    \"new_moon_face\": \"🌚\",\n    \"newspaper\": \"📰\",\n    \"next_track_button\": \"⏭\",\n    \"night_with_stars\": \"🌃\",\n    \"nine-thirty\": \"🕤\",\n    \"nine_o’clock\": \"🕘\",\n    \"no_bicycles\": \"🚳\",\n    \"no_entry\": \"⛔\",\n    \"no_littering\": \"🚯\",\n    \"no_mobile_phones\": \"📵\",\n    \"no_one_under_eighteen\": \"🔞\",\n    \"no_pedestrians\": \"🚷\",\n    \"no_smoking\": \"🚭\",\n    \"non-potable_water\": \"🚱\",\n    \"nose\": \"👃\",\n    \"nose_dark_skin_tone\": \"👃🏿\",\n    \"nose_light_skin_tone\": \"👃🏻\",\n    \"nose_medium-dark_skin_tone\": \"👃🏾\",\n    \"nose_medium-light_skin_tone\": \"👃🏼\",\n    \"nose_medium_skin_tone\": \"👃🏽\",\n    \"notebook\": \"📓\",\n    \"notebook_with_decorative_cover\": \"📔\",\n    \"nut_and_bolt\": \"🔩\",\n    \"octopus\": \"🐙\",\n    \"oden\": \"🍢\",\n    \"office_building\": \"🏢\",\n    \"ogre\": \"👹\",\n    \"oil_drum\": \"🛢\",\n    \"old_key\": \"🗝\",\n    \"old_man\": \"👴\",\n    \"old_man_dark_skin_tone\": \"👴🏿\",\n    \"old_man_light_skin_tone\": \"👴🏻\",\n    \"old_man_medium-dark_skin_tone\": \"👴🏾\",\n    \"old_man_medium-light_skin_tone\": \"👴🏼\",\n    \"old_man_medium_skin_tone\": \"👴🏽\",\n    \"old_woman\": \"👵\",\n    \"old_woman_dark_skin_tone\": \"👵🏿\",\n    \"old_woman_light_skin_tone\": \"👵🏻\",\n    \"old_woman_medium-dark_skin_tone\": \"👵🏾\",\n    \"old_woman_medium-light_skin_tone\": \"👵🏼\",\n    \"old_woman_medium_skin_tone\": \"👵🏽\",\n    \"older_adult\": \"🧓\",\n    \"older_adult_dark_skin_tone\": \"🧓🏿\",\n    \"older_adult_light_skin_tone\": \"🧓🏻\",\n    \"older_adult_medium-dark_skin_tone\": \"🧓🏾\",\n    \"older_adult_medium-light_skin_tone\": \"🧓🏼\",\n    \"older_adult_medium_skin_tone\": \"🧓🏽\",\n    \"om\": \"🕉\",\n    \"oncoming_automobile\": \"🚘\",\n    \"oncoming_bus\": \"🚍\",\n    \"oncoming_fist\": \"👊\",\n    \"oncoming_fist_dark_skin_tone\": \"👊🏿\",\n    \"oncoming_fist_light_skin_tone\": \"👊🏻\",\n    \"oncoming_fist_medium-dark_skin_tone\": \"👊🏾\",\n    \"oncoming_fist_medium-light_skin_tone\": \"👊🏼\",\n    \"oncoming_fist_medium_skin_tone\": \"👊🏽\",\n    \"oncoming_police_car\": \"🚔\",\n    \"oncoming_taxi\": \"🚖\",\n    \"one-piece_swimsuit\": \"🩱\",\n    \"one-thirty\": \"🕜\",\n    \"one_o’clock\": \"🕐\",\n    \"onion\": \"🧅\",\n    \"open_book\": \"📖\",\n    \"open_file_folder\": \"📂\",\n    \"open_hands\": \"👐\",\n    \"open_hands_dark_skin_tone\": \"👐🏿\",\n    \"open_hands_light_skin_tone\": \"👐🏻\",\n    \"open_hands_medium-dark_skin_tone\": \"👐🏾\",\n    \"open_hands_medium-light_skin_tone\": \"👐🏼\",\n    \"open_hands_medium_skin_tone\": \"👐🏽\",\n    \"open_mailbox_with_lowered_flag\": \"📭\",\n    \"open_mailbox_with_raised_flag\": \"📬\",\n    \"optical_disk\": \"💿\",\n    \"orange_book\": \"📙\",\n    \"orange_circle\": \"🟠\",\n    \"orange_heart\": \"🧡\",\n    \"orange_square\": \"🟧\",\n    \"orangutan\": \"🦧\",\n    \"orthodox_cross\": \"☦\",\n    \"otter\": \"🦦\",\n    \"outbox_tray\": \"📤\",\n    \"owl\": \"🦉\",\n    \"ox\": \"🐂\",\n    \"oyster\": \"🦪\",\n    \"package\": \"📦\",\n    \"page_facing_up\": \"📄\",\n    \"page_with_curl\": \"📃\",\n    \"pager\": \"📟\",\n    \"paintbrush\": \"🖌\",\n    \"palm_tree\": \"🌴\",\n    \"palms_up_together\": \"🤲\",\n    \"palms_up_together_dark_skin_tone\": \"🤲🏿\",\n    \"palms_up_together_light_skin_tone\": \"🤲🏻\",\n    \"palms_up_together_medium-dark_skin_tone\": \"🤲🏾\",\n    \"palms_up_together_medium-light_skin_tone\": \"🤲🏼\",\n    \"palms_up_together_medium_skin_tone\": \"🤲🏽\",\n    \"pancakes\": \"🥞\",\n    \"panda_face\": \"🐼\",\n    \"paperclip\": \"📎\",\n    \"parrot\": \"🦜\",\n    \"part_alternation_mark\": \"〽\",\n    \"party_popper\": \"🎉\",\n    \"partying_face\": \"🥳\",\n    \"passenger_ship\": \"🛳\",\n    \"passport_control\": \"🛂\",\n    \"pause_button\": \"⏸\",\n    \"paw_prints\": \"🐾\",\n    \"peace_symbol\": \"☮\",\n    \"peach\": \"🍑\",\n    \"peacock\": \"🦚\",\n    \"peanuts\": \"🥜\",\n    \"pear\": \"🍐\",\n    \"pen\": \"🖊\",\n    \"pencil\": \"📝\",\n    \"penguin\": \"🐧\",\n    \"pensive_face\": \"😔\",\n    \"people_holding_hands\": \"🧑\\u200d🤝\\u200d🧑\",\n    \"people_with_bunny_ears\": \"👯\",\n    \"people_wrestling\": \"🤼\",\n    \"performing_arts\": \"🎭\",\n    \"persevering_face\": \"😣\",\n    \"person_biking\": \"🚴\",\n    \"person_biking_dark_skin_tone\": \"🚴🏿\",\n    \"person_biking_light_skin_tone\": \"🚴🏻\",\n    \"person_biking_medium-dark_skin_tone\": \"🚴🏾\",\n    \"person_biking_medium-light_skin_tone\": \"🚴🏼\",\n    \"person_biking_medium_skin_tone\": \"🚴🏽\",\n    \"person_bouncing_ball\": \"⛹\",\n    \"person_bouncing_ball_dark_skin_tone\": \"⛹🏿\",\n    \"person_bouncing_ball_light_skin_tone\": \"⛹🏻\",\n    \"person_bouncing_ball_medium-dark_skin_tone\": \"⛹🏾\",\n    \"person_bouncing_ball_medium-light_skin_tone\": \"⛹🏼\",\n    \"person_bouncing_ball_medium_skin_tone\": \"⛹🏽\",\n    \"person_bowing\": \"🙇\",\n    \"person_bowing_dark_skin_tone\": \"🙇🏿\",\n    \"person_bowing_light_skin_tone\": \"🙇🏻\",\n    \"person_bowing_medium-dark_skin_tone\": \"🙇🏾\",\n    \"person_bowing_medium-light_skin_tone\": \"🙇🏼\",\n    \"person_bowing_medium_skin_tone\": \"🙇🏽\",\n    \"person_cartwheeling\": \"🤸\",\n    \"person_cartwheeling_dark_skin_tone\": \"🤸🏿\",\n    \"person_cartwheeling_light_skin_tone\": \"🤸🏻\",\n    \"person_cartwheeling_medium-dark_skin_tone\": \"🤸🏾\",\n    \"person_cartwheeling_medium-light_skin_tone\": \"🤸🏼\",\n    \"person_cartwheeling_medium_skin_tone\": \"🤸🏽\",\n    \"person_climbing\": \"🧗\",\n    \"person_climbing_dark_skin_tone\": \"🧗🏿\",\n    \"person_climbing_light_skin_tone\": \"🧗🏻\",\n    \"person_climbing_medium-dark_skin_tone\": \"🧗🏾\",\n    \"person_climbing_medium-light_skin_tone\": \"🧗🏼\",\n    \"person_climbing_medium_skin_tone\": \"🧗🏽\",\n    \"person_facepalming\": \"🤦\",\n    \"person_facepalming_dark_skin_tone\": \"🤦🏿\",\n    \"person_facepalming_light_skin_tone\": \"🤦🏻\",\n    \"person_facepalming_medium-dark_skin_tone\": \"🤦🏾\",\n    \"person_facepalming_medium-light_skin_tone\": \"🤦🏼\",\n    \"person_facepalming_medium_skin_tone\": \"🤦🏽\",\n    \"person_fencing\": \"🤺\",\n    \"person_frowning\": \"🙍\",\n    \"person_frowning_dark_skin_tone\": \"🙍🏿\",\n    \"person_frowning_light_skin_tone\": \"🙍🏻\",\n    \"person_frowning_medium-dark_skin_tone\": \"🙍🏾\",\n    \"person_frowning_medium-light_skin_tone\": \"🙍🏼\",\n    \"person_frowning_medium_skin_tone\": \"🙍🏽\",\n    \"person_gesturing_no\": \"🙅\",\n    \"person_gesturing_no_dark_skin_tone\": \"🙅🏿\",\n    \"person_gesturing_no_light_skin_tone\": \"🙅🏻\",\n    \"person_gesturing_no_medium-dark_skin_tone\": \"🙅🏾\",\n    \"person_gesturing_no_medium-light_skin_tone\": \"🙅🏼\",\n    \"person_gesturing_no_medium_skin_tone\": \"🙅🏽\",\n    \"person_gesturing_ok\": \"🙆\",\n    \"person_gesturing_ok_dark_skin_tone\": \"🙆🏿\",\n    \"person_gesturing_ok_light_skin_tone\": \"🙆🏻\",\n    \"person_gesturing_ok_medium-dark_skin_tone\": \"🙆🏾\",\n    \"person_gesturing_ok_medium-light_skin_tone\": \"🙆🏼\",\n    \"person_gesturing_ok_medium_skin_tone\": \"🙆🏽\",\n    \"person_getting_haircut\": \"💇\",\n    \"person_getting_haircut_dark_skin_tone\": \"💇🏿\",\n    \"person_getting_haircut_light_skin_tone\": \"💇🏻\",\n    \"person_getting_haircut_medium-dark_skin_tone\": \"💇🏾\",\n    \"person_getting_haircut_medium-light_skin_tone\": \"💇🏼\",\n    \"person_getting_haircut_medium_skin_tone\": \"💇🏽\",\n    \"person_getting_massage\": \"💆\",\n    \"person_getting_massage_dark_skin_tone\": \"💆🏿\",\n    \"person_getting_massage_light_skin_tone\": \"💆🏻\",\n    \"person_getting_massage_medium-dark_skin_tone\": \"💆🏾\",\n    \"person_getting_massage_medium-light_skin_tone\": \"💆🏼\",\n    \"person_getting_massage_medium_skin_tone\": \"💆🏽\",\n    \"person_golfing\": \"🏌\",\n    \"person_golfing_dark_skin_tone\": \"🏌🏿\",\n    \"person_golfing_light_skin_tone\": \"🏌🏻\",\n    \"person_golfing_medium-dark_skin_tone\": \"🏌🏾\",\n    \"person_golfing_medium-light_skin_tone\": \"🏌🏼\",\n    \"person_golfing_medium_skin_tone\": \"🏌🏽\",\n    \"person_in_bed\": \"🛌\",\n    \"person_in_bed_dark_skin_tone\": \"🛌🏿\",\n    \"person_in_bed_light_skin_tone\": \"🛌🏻\",\n    \"person_in_bed_medium-dark_skin_tone\": \"🛌🏾\",\n    \"person_in_bed_medium-light_skin_tone\": \"🛌🏼\",\n    \"person_in_bed_medium_skin_tone\": \"🛌🏽\",\n    \"person_in_lotus_position\": \"🧘\",\n    \"person_in_lotus_position_dark_skin_tone\": \"🧘🏿\",\n    \"person_in_lotus_position_light_skin_tone\": \"🧘🏻\",\n    \"person_in_lotus_position_medium-dark_skin_tone\": \"🧘🏾\",\n    \"person_in_lotus_position_medium-light_skin_tone\": \"🧘🏼\",\n    \"person_in_lotus_position_medium_skin_tone\": \"🧘🏽\",\n    \"person_in_steamy_room\": \"🧖\",\n    \"person_in_steamy_room_dark_skin_tone\": \"🧖🏿\",\n    \"person_in_steamy_room_light_skin_tone\": \"🧖🏻\",\n    \"person_in_steamy_room_medium-dark_skin_tone\": \"🧖🏾\",\n    \"person_in_steamy_room_medium-light_skin_tone\": \"🧖🏼\",\n    \"person_in_steamy_room_medium_skin_tone\": \"🧖🏽\",\n    \"person_juggling\": \"🤹\",\n    \"person_juggling_dark_skin_tone\": \"🤹🏿\",\n    \"person_juggling_light_skin_tone\": \"🤹🏻\",\n    \"person_juggling_medium-dark_skin_tone\": \"🤹🏾\",\n    \"person_juggling_medium-light_skin_tone\": \"🤹🏼\",\n    \"person_juggling_medium_skin_tone\": \"🤹🏽\",\n    \"person_kneeling\": \"🧎\",\n    \"person_lifting_weights\": \"🏋\",\n    \"person_lifting_weights_dark_skin_tone\": \"🏋🏿\",\n    \"person_lifting_weights_light_skin_tone\": \"🏋🏻\",\n    \"person_lifting_weights_medium-dark_skin_tone\": \"🏋🏾\",\n    \"person_lifting_weights_medium-light_skin_tone\": \"🏋🏼\",\n    \"person_lifting_weights_medium_skin_tone\": \"🏋🏽\",\n    \"person_mountain_biking\": \"🚵\",\n    \"person_mountain_biking_dark_skin_tone\": \"🚵🏿\",\n    \"person_mountain_biking_light_skin_tone\": \"🚵🏻\",\n    \"person_mountain_biking_medium-dark_skin_tone\": \"🚵🏾\",\n    \"person_mountain_biking_medium-light_skin_tone\": \"🚵🏼\",\n    \"person_mountain_biking_medium_skin_tone\": \"🚵🏽\",\n    \"person_playing_handball\": \"🤾\",\n    \"person_playing_handball_dark_skin_tone\": \"🤾🏿\",\n    \"person_playing_handball_light_skin_tone\": \"🤾🏻\",\n    \"person_playing_handball_medium-dark_skin_tone\": \"🤾🏾\",\n    \"person_playing_handball_medium-light_skin_tone\": \"🤾🏼\",\n    \"person_playing_handball_medium_skin_tone\": \"🤾🏽\",\n    \"person_playing_water_polo\": \"🤽\",\n    \"person_playing_water_polo_dark_skin_tone\": \"🤽🏿\",\n    \"person_playing_water_polo_light_skin_tone\": \"🤽🏻\",\n    \"person_playing_water_polo_medium-dark_skin_tone\": \"🤽🏾\",\n    \"person_playing_water_polo_medium-light_skin_tone\": \"🤽🏼\",\n    \"person_playing_water_polo_medium_skin_tone\": \"🤽🏽\",\n    \"person_pouting\": \"🙎\",\n    \"person_pouting_dark_skin_tone\": \"🙎🏿\",\n    \"person_pouting_light_skin_tone\": \"🙎🏻\",\n    \"person_pouting_medium-dark_skin_tone\": \"🙎🏾\",\n    \"person_pouting_medium-light_skin_tone\": \"🙎🏼\",\n    \"person_pouting_medium_skin_tone\": \"🙎🏽\",\n    \"person_raising_hand\": \"🙋\",\n    \"person_raising_hand_dark_skin_tone\": \"🙋🏿\",\n    \"person_raising_hand_light_skin_tone\": \"🙋🏻\",\n    \"person_raising_hand_medium-dark_skin_tone\": \"🙋🏾\",\n    \"person_raising_hand_medium-light_skin_tone\": \"🙋🏼\",\n    \"person_raising_hand_medium_skin_tone\": \"🙋🏽\",\n    \"person_rowing_boat\": \"🚣\",\n    \"person_rowing_boat_dark_skin_tone\": \"🚣🏿\",\n    \"person_rowing_boat_light_skin_tone\": \"🚣🏻\",\n    \"person_rowing_boat_medium-dark_skin_tone\": \"🚣🏾\",\n    \"person_rowing_boat_medium-light_skin_tone\": \"🚣🏼\",\n    \"person_rowing_boat_medium_skin_tone\": \"🚣🏽\",\n    \"person_running\": \"🏃\",\n    \"person_running_dark_skin_tone\": \"🏃🏿\",\n    \"person_running_light_skin_tone\": \"🏃🏻\",\n    \"person_running_medium-dark_skin_tone\": \"🏃🏾\",\n    \"person_running_medium-light_skin_tone\": \"🏃🏼\",\n    \"person_running_medium_skin_tone\": \"🏃🏽\",\n    \"person_shrugging\": \"🤷\",\n    \"person_shrugging_dark_skin_tone\": \"🤷🏿\",\n    \"person_shrugging_light_skin_tone\": \"🤷🏻\",\n    \"person_shrugging_medium-dark_skin_tone\": \"🤷🏾\",\n    \"person_shrugging_medium-light_skin_tone\": \"🤷🏼\",\n    \"person_shrugging_medium_skin_tone\": \"🤷🏽\",\n    \"person_standing\": \"🧍\",\n    \"person_surfing\": \"🏄\",\n    \"person_surfing_dark_skin_tone\": \"🏄🏿\",\n    \"person_surfing_light_skin_tone\": \"🏄🏻\",\n    \"person_surfing_medium-dark_skin_tone\": \"🏄🏾\",\n    \"person_surfing_medium-light_skin_tone\": \"🏄🏼\",\n    \"person_surfing_medium_skin_tone\": \"🏄🏽\",\n    \"person_swimming\": \"🏊\",\n    \"person_swimming_dark_skin_tone\": \"🏊🏿\",\n    \"person_swimming_light_skin_tone\": \"🏊🏻\",\n    \"person_swimming_medium-dark_skin_tone\": \"🏊🏾\",\n    \"person_swimming_medium-light_skin_tone\": \"🏊🏼\",\n    \"person_swimming_medium_skin_tone\": \"🏊🏽\",\n    \"person_taking_bath\": \"🛀\",\n    \"person_taking_bath_dark_skin_tone\": \"🛀🏿\",\n    \"person_taking_bath_light_skin_tone\": \"🛀🏻\",\n    \"person_taking_bath_medium-dark_skin_tone\": \"🛀🏾\",\n    \"person_taking_bath_medium-light_skin_tone\": \"🛀🏼\",\n    \"person_taking_bath_medium_skin_tone\": \"🛀🏽\",\n    \"person_tipping_hand\": \"💁\",\n    \"person_tipping_hand_dark_skin_tone\": \"💁🏿\",\n    \"person_tipping_hand_light_skin_tone\": \"💁🏻\",\n    \"person_tipping_hand_medium-dark_skin_tone\": \"💁🏾\",\n    \"person_tipping_hand_medium-light_skin_tone\": \"💁🏼\",\n    \"person_tipping_hand_medium_skin_tone\": \"💁🏽\",\n    \"person_walking\": \"🚶\",\n    \"person_walking_dark_skin_tone\": \"🚶🏿\",\n    \"person_walking_light_skin_tone\": \"🚶🏻\",\n    \"person_walking_medium-dark_skin_tone\": \"🚶🏾\",\n    \"person_walking_medium-light_skin_tone\": \"🚶🏼\",\n    \"person_walking_medium_skin_tone\": \"🚶🏽\",\n    \"person_wearing_turban\": \"👳\",\n    \"person_wearing_turban_dark_skin_tone\": \"👳🏿\",\n    \"person_wearing_turban_light_skin_tone\": \"👳🏻\",\n    \"person_wearing_turban_medium-dark_skin_tone\": \"👳🏾\",\n    \"person_wearing_turban_medium-light_skin_tone\": \"👳🏼\",\n    \"person_wearing_turban_medium_skin_tone\": \"👳🏽\",\n    \"petri_dish\": \"🧫\",\n    \"pick\": \"⛏\",\n    \"pie\": \"🥧\",\n    \"pig\": \"🐷\",\n    \"pig_face\": \"🐷\",\n    \"pig_nose\": \"🐽\",\n    \"pile_of_poo\": \"💩\",\n    \"pill\": \"💊\",\n    \"pinching_hand\": \"🤏\",\n    \"pine_decoration\": \"🎍\",\n    \"pineapple\": \"🍍\",\n    \"ping_pong\": \"🏓\",\n    \"pirate_flag\": \"🏴\\u200d☠️\",\n    \"pistol\": \"🔫\",\n    \"pizza\": \"🍕\",\n    \"place_of_worship\": \"🛐\",\n    \"play_button\": \"▶\",\n    \"play_or_pause_button\": \"⏯\",\n    \"pleading_face\": \"🥺\",\n    \"police_car\": \"🚓\",\n    \"police_car_light\": \"🚨\",\n    \"police_officer\": \"👮\",\n    \"police_officer_dark_skin_tone\": \"👮🏿\",\n    \"police_officer_light_skin_tone\": \"👮🏻\",\n    \"police_officer_medium-dark_skin_tone\": \"👮🏾\",\n    \"police_officer_medium-light_skin_tone\": \"👮🏼\",\n    \"police_officer_medium_skin_tone\": \"👮🏽\",\n    \"poodle\": \"🐩\",\n    \"pool_8_ball\": \"🎱\",\n    \"popcorn\": \"🍿\",\n    \"post_office\": \"🏣\",\n    \"postal_horn\": \"📯\",\n    \"postbox\": \"📮\",\n    \"pot_of_food\": \"🍲\",\n    \"potable_water\": \"🚰\",\n    \"potato\": \"🥔\",\n    \"poultry_leg\": \"🍗\",\n    \"pound_banknote\": \"💷\",\n    \"pouting_cat_face\": \"😾\",\n    \"pouting_face\": \"😡\",\n    \"prayer_beads\": \"📿\",\n    \"pregnant_woman\": \"🤰\",\n    \"pregnant_woman_dark_skin_tone\": \"🤰🏿\",\n    \"pregnant_woman_light_skin_tone\": \"🤰🏻\",\n    \"pregnant_woman_medium-dark_skin_tone\": \"🤰🏾\",\n    \"pregnant_woman_medium-light_skin_tone\": \"🤰🏼\",\n    \"pregnant_woman_medium_skin_tone\": \"🤰🏽\",\n    \"pretzel\": \"🥨\",\n    \"probing_cane\": \"🦯\",\n    \"prince\": \"🤴\",\n    \"prince_dark_skin_tone\": \"🤴🏿\",\n    \"prince_light_skin_tone\": \"🤴🏻\",\n    \"prince_medium-dark_skin_tone\": \"🤴🏾\",\n    \"prince_medium-light_skin_tone\": \"🤴🏼\",\n    \"prince_medium_skin_tone\": \"🤴🏽\",\n    \"princess\": \"👸\",\n    \"princess_dark_skin_tone\": \"👸🏿\",\n    \"princess_light_skin_tone\": \"👸🏻\",\n    \"princess_medium-dark_skin_tone\": \"👸🏾\",\n    \"princess_medium-light_skin_tone\": \"👸🏼\",\n    \"princess_medium_skin_tone\": \"👸🏽\",\n    \"printer\": \"🖨\",\n    \"prohibited\": \"🚫\",\n    \"purple_circle\": \"🟣\",\n    \"purple_heart\": \"💜\",\n    \"purple_square\": \"🟪\",\n    \"purse\": \"👛\",\n    \"pushpin\": \"📌\",\n    \"question_mark\": \"❓\",\n    \"rabbit\": \"🐰\",\n    \"rabbit_face\": \"🐰\",\n    \"raccoon\": \"🦝\",\n    \"racing_car\": \"🏎\",\n    \"radio\": \"📻\",\n    \"radio_button\": \"🔘\",\n    \"radioactive\": \"☢\",\n    \"railway_car\": \"🚃\",\n    \"railway_track\": \"🛤\",\n    \"rainbow\": \"🌈\",\n    \"rainbow_flag\": \"🏳️\\u200d🌈\",\n    \"raised_back_of_hand\": \"🤚\",\n    \"raised_back_of_hand_dark_skin_tone\": \"🤚🏿\",\n    \"raised_back_of_hand_light_skin_tone\": \"🤚🏻\",\n    \"raised_back_of_hand_medium-dark_skin_tone\": \"🤚🏾\",\n    \"raised_back_of_hand_medium-light_skin_tone\": \"🤚🏼\",\n    \"raised_back_of_hand_medium_skin_tone\": \"🤚🏽\",\n    \"raised_fist\": \"✊\",\n    \"raised_fist_dark_skin_tone\": \"✊🏿\",\n    \"raised_fist_light_skin_tone\": \"✊🏻\",\n    \"raised_fist_medium-dark_skin_tone\": \"✊🏾\",\n    \"raised_fist_medium-light_skin_tone\": \"✊🏼\",\n    \"raised_fist_medium_skin_tone\": \"✊🏽\",\n    \"raised_hand\": \"✋\",\n    \"raised_hand_dark_skin_tone\": \"✋🏿\",\n    \"raised_hand_light_skin_tone\": \"✋🏻\",\n    \"raised_hand_medium-dark_skin_tone\": \"✋🏾\",\n    \"raised_hand_medium-light_skin_tone\": \"✋🏼\",\n    \"raised_hand_medium_skin_tone\": \"✋🏽\",\n    \"raising_hands\": \"🙌\",\n    \"raising_hands_dark_skin_tone\": \"🙌🏿\",\n    \"raising_hands_light_skin_tone\": \"🙌🏻\",\n    \"raising_hands_medium-dark_skin_tone\": \"🙌🏾\",\n    \"raising_hands_medium-light_skin_tone\": \"🙌🏼\",\n    \"raising_hands_medium_skin_tone\": \"🙌🏽\",\n    \"ram\": \"🐏\",\n    \"rat\": \"🐀\",\n    \"razor\": \"🪒\",\n    \"ringed_planet\": \"🪐\",\n    \"receipt\": \"🧾\",\n    \"record_button\": \"⏺\",\n    \"recycling_symbol\": \"♻\",\n    \"red_apple\": \"🍎\",\n    \"red_circle\": \"🔴\",\n    \"red_envelope\": \"🧧\",\n    \"red_hair\": \"🦰\",\n    \"red-haired_man\": \"👨\\u200d🦰\",\n    \"red-haired_woman\": \"👩\\u200d🦰\",\n    \"red_heart\": \"❤\",\n    \"red_paper_lantern\": \"🏮\",\n    \"red_square\": \"🟥\",\n    \"red_triangle_pointed_down\": \"🔻\",\n    \"red_triangle_pointed_up\": \"🔺\",\n    \"registered\": \"®\",\n    \"relieved_face\": \"😌\",\n    \"reminder_ribbon\": \"🎗\",\n    \"repeat_button\": \"🔁\",\n    \"repeat_single_button\": \"🔂\",\n    \"rescue_worker’s_helmet\": \"⛑\",\n    \"restroom\": \"🚻\",\n    \"reverse_button\": \"◀\",\n    \"revolving_hearts\": \"💞\",\n    \"rhinoceros\": \"🦏\",\n    \"ribbon\": \"🎀\",\n    \"rice_ball\": \"🍙\",\n    \"rice_cracker\": \"🍘\",\n    \"right-facing_fist\": \"🤜\",\n    \"right-facing_fist_dark_skin_tone\": \"🤜🏿\",\n    \"right-facing_fist_light_skin_tone\": \"🤜🏻\",\n    \"right-facing_fist_medium-dark_skin_tone\": \"🤜🏾\",\n    \"right-facing_fist_medium-light_skin_tone\": \"🤜🏼\",\n    \"right-facing_fist_medium_skin_tone\": \"🤜🏽\",\n    \"right_anger_bubble\": \"🗯\",\n    \"right_arrow\": \"➡\",\n    \"right_arrow_curving_down\": \"⤵\",\n    \"right_arrow_curving_left\": \"↩\",\n    \"right_arrow_curving_up\": \"⤴\",\n    \"ring\": \"💍\",\n    \"roasted_sweet_potato\": \"🍠\",\n    \"robot_face\": \"🤖\",\n    \"rocket\": \"🚀\",\n    \"roll_of_paper\": \"🧻\",\n    \"rolled-up_newspaper\": \"🗞\",\n    \"roller_coaster\": \"🎢\",\n    \"rolling_on_the_floor_laughing\": \"🤣\",\n    \"rooster\": \"🐓\",\n    \"rose\": \"🌹\",\n    \"rosette\": \"🏵\",\n    \"round_pushpin\": \"📍\",\n    \"rugby_football\": \"🏉\",\n    \"running_shirt\": \"🎽\",\n    \"running_shoe\": \"👟\",\n    \"sad_but_relieved_face\": \"😥\",\n    \"safety_pin\": \"🧷\",\n    \"safety_vest\": \"🦺\",\n    \"salt\": \"🧂\",\n    \"sailboat\": \"⛵\",\n    \"sake\": \"🍶\",\n    \"sandwich\": \"🥪\",\n    \"sari\": \"🥻\",\n    \"satellite\": \"📡\",\n    \"satellite_antenna\": \"📡\",\n    \"sauropod\": \"🦕\",\n    \"saxophone\": \"🎷\",\n    \"scarf\": \"🧣\",\n    \"school\": \"🏫\",\n    \"school_backpack\": \"🎒\",\n    \"scissors\": \"✂\",\n    \"scorpion\": \"🦂\",\n    \"scroll\": \"📜\",\n    \"seat\": \"💺\",\n    \"see-no-evil_monkey\": \"🙈\",\n    \"seedling\": \"🌱\",\n    \"selfie\": \"🤳\",\n    \"selfie_dark_skin_tone\": \"🤳🏿\",\n    \"selfie_light_skin_tone\": \"🤳🏻\",\n    \"selfie_medium-dark_skin_tone\": \"🤳🏾\",\n    \"selfie_medium-light_skin_tone\": \"🤳🏼\",\n    \"selfie_medium_skin_tone\": \"🤳🏽\",\n    \"service_dog\": \"🐕\\u200d🦺\",\n    \"seven-thirty\": \"🕢\",\n    \"seven_o’clock\": \"🕖\",\n    \"shallow_pan_of_food\": \"🥘\",\n    \"shamrock\": \"☘\",\n    \"shark\": \"🦈\",\n    \"shaved_ice\": \"🍧\",\n    \"sheaf_of_rice\": \"🌾\",\n    \"shield\": \"🛡\",\n    \"shinto_shrine\": \"⛩\",\n    \"ship\": \"🚢\",\n    \"shooting_star\": \"🌠\",\n    \"shopping_bags\": \"🛍\",\n    \"shopping_cart\": \"🛒\",\n    \"shortcake\": \"🍰\",\n    \"shorts\": \"🩳\",\n    \"shower\": \"🚿\",\n    \"shrimp\": \"🦐\",\n    \"shuffle_tracks_button\": \"🔀\",\n    \"shushing_face\": \"🤫\",\n    \"sign_of_the_horns\": \"🤘\",\n    \"sign_of_the_horns_dark_skin_tone\": \"🤘🏿\",\n    \"sign_of_the_horns_light_skin_tone\": \"🤘🏻\",\n    \"sign_of_the_horns_medium-dark_skin_tone\": \"🤘🏾\",\n    \"sign_of_the_horns_medium-light_skin_tone\": \"🤘🏼\",\n    \"sign_of_the_horns_medium_skin_tone\": \"🤘🏽\",\n    \"six-thirty\": \"🕡\",\n    \"six_o’clock\": \"🕕\",\n    \"skateboard\": \"🛹\",\n    \"skier\": \"⛷\",\n    \"skis\": \"🎿\",\n    \"skull\": \"💀\",\n    \"skull_and_crossbones\": \"☠\",\n    \"skunk\": \"🦨\",\n    \"sled\": \"🛷\",\n    \"sleeping_face\": \"😴\",\n    \"sleepy_face\": \"😪\",\n    \"slightly_frowning_face\": \"🙁\",\n    \"slightly_smiling_face\": \"🙂\",\n    \"slot_machine\": \"🎰\",\n    \"sloth\": \"🦥\",\n    \"small_airplane\": \"🛩\",\n    \"small_blue_diamond\": \"🔹\",\n    \"small_orange_diamond\": \"🔸\",\n    \"smiling_cat_face_with_heart-eyes\": \"😻\",\n    \"smiling_face\": \"☺\",\n    \"smiling_face_with_halo\": \"😇\",\n    \"smiling_face_with_3_hearts\": \"🥰\",\n    \"smiling_face_with_heart-eyes\": \"😍\",\n    \"smiling_face_with_horns\": \"😈\",\n    \"smiling_face_with_smiling_eyes\": \"😊\",\n    \"smiling_face_with_sunglasses\": \"😎\",\n    \"smirking_face\": \"😏\",\n    \"snail\": \"🐌\",\n    \"snake\": \"🐍\",\n    \"sneezing_face\": \"🤧\",\n    \"snow-capped_mountain\": \"🏔\",\n    \"snowboarder\": \"🏂\",\n    \"snowboarder_dark_skin_tone\": \"🏂🏿\",\n    \"snowboarder_light_skin_tone\": \"🏂🏻\",\n    \"snowboarder_medium-dark_skin_tone\": \"🏂🏾\",\n    \"snowboarder_medium-light_skin_tone\": \"🏂🏼\",\n    \"snowboarder_medium_skin_tone\": \"🏂🏽\",\n    \"snowflake\": \"❄\",\n    \"snowman\": \"☃\",\n    \"snowman_without_snow\": \"⛄\",\n    \"soap\": \"🧼\",\n    \"soccer_ball\": \"⚽\",\n    \"socks\": \"🧦\",\n    \"softball\": \"🥎\",\n    \"soft_ice_cream\": \"🍦\",\n    \"spade_suit\": \"♠\",\n    \"spaghetti\": \"🍝\",\n    \"sparkle\": \"❇\",\n    \"sparkler\": \"🎇\",\n    \"sparkles\": \"✨\",\n    \"sparkling_heart\": \"💖\",\n    \"speak-no-evil_monkey\": \"🙊\",\n    \"speaker_high_volume\": \"🔊\",\n    \"speaker_low_volume\": \"🔈\",\n    \"speaker_medium_volume\": \"🔉\",\n    \"speaking_head\": \"🗣\",\n    \"speech_balloon\": \"💬\",\n    \"speedboat\": \"🚤\",\n    \"spider\": \"🕷\",\n    \"spider_web\": \"🕸\",\n    \"spiral_calendar\": \"🗓\",\n    \"spiral_notepad\": \"🗒\",\n    \"spiral_shell\": \"🐚\",\n    \"spoon\": \"🥄\",\n    \"sponge\": \"🧽\",\n    \"sport_utility_vehicle\": \"🚙\",\n    \"sports_medal\": \"🏅\",\n    \"spouting_whale\": \"🐳\",\n    \"squid\": \"🦑\",\n    \"squinting_face_with_tongue\": \"😝\",\n    \"stadium\": \"🏟\",\n    \"star-struck\": \"🤩\",\n    \"star_and_crescent\": \"☪\",\n    \"star_of_david\": \"✡\",\n    \"station\": \"🚉\",\n    \"steaming_bowl\": \"🍜\",\n    \"stethoscope\": \"🩺\",\n    \"stop_button\": \"⏹\",\n    \"stop_sign\": \"🛑\",\n    \"stopwatch\": \"⏱\",\n    \"straight_ruler\": \"📏\",\n    \"strawberry\": \"🍓\",\n    \"studio_microphone\": \"🎙\",\n    \"stuffed_flatbread\": \"🥙\",\n    \"sun\": \"☀\",\n    \"sun_behind_cloud\": \"⛅\",\n    \"sun_behind_large_cloud\": \"🌥\",\n    \"sun_behind_rain_cloud\": \"🌦\",\n    \"sun_behind_small_cloud\": \"🌤\",\n    \"sun_with_face\": \"🌞\",\n    \"sunflower\": \"🌻\",\n    \"sunglasses\": \"😎\",\n    \"sunrise\": \"🌅\",\n    \"sunrise_over_mountains\": \"🌄\",\n    \"sunset\": \"🌇\",\n    \"superhero\": \"🦸\",\n    \"supervillain\": \"🦹\",\n    \"sushi\": \"🍣\",\n    \"suspension_railway\": \"🚟\",\n    \"swan\": \"🦢\",\n    \"sweat_droplets\": \"💦\",\n    \"synagogue\": \"🕍\",\n    \"syringe\": \"💉\",\n    \"t-shirt\": \"👕\",\n    \"taco\": \"🌮\",\n    \"takeout_box\": \"🥡\",\n    \"tanabata_tree\": \"🎋\",\n    \"tangerine\": \"🍊\",\n    \"taxi\": \"🚕\",\n    \"teacup_without_handle\": \"🍵\",\n    \"tear-off_calendar\": \"📆\",\n    \"teddy_bear\": \"🧸\",\n    \"telephone\": \"☎\",\n    \"telephone_receiver\": \"📞\",\n    \"telescope\": \"🔭\",\n    \"television\": \"📺\",\n    \"ten-thirty\": \"🕥\",\n    \"ten_o’clock\": \"🕙\",\n    \"tennis\": \"🎾\",\n    \"tent\": \"⛺\",\n    \"test_tube\": \"🧪\",\n    \"thermometer\": \"🌡\",\n    \"thinking_face\": \"🤔\",\n    \"thought_balloon\": \"💭\",\n    \"thread\": \"🧵\",\n    \"three-thirty\": \"🕞\",\n    \"three_o’clock\": \"🕒\",\n    \"thumbs_down\": \"👎\",\n    \"thumbs_down_dark_skin_tone\": \"👎🏿\",\n    \"thumbs_down_light_skin_tone\": \"👎🏻\",\n    \"thumbs_down_medium-dark_skin_tone\": \"👎🏾\",\n    \"thumbs_down_medium-light_skin_tone\": \"👎🏼\",\n    \"thumbs_down_medium_skin_tone\": \"👎🏽\",\n    \"thumbs_up\": \"👍\",\n    \"thumbs_up_dark_skin_tone\": \"👍🏿\",\n    \"thumbs_up_light_skin_tone\": \"👍🏻\",\n    \"thumbs_up_medium-dark_skin_tone\": \"👍🏾\",\n    \"thumbs_up_medium-light_skin_tone\": \"👍🏼\",\n    \"thumbs_up_medium_skin_tone\": \"👍🏽\",\n    \"ticket\": \"🎫\",\n    \"tiger\": \"🐯\",\n    \"tiger_face\": \"🐯\",\n    \"timer_clock\": \"⏲\",\n    \"tired_face\": \"😫\",\n    \"toolbox\": \"🧰\",\n    \"toilet\": \"🚽\",\n    \"tomato\": \"🍅\",\n    \"tongue\": \"👅\",\n    \"tooth\": \"🦷\",\n    \"top_hat\": \"🎩\",\n    \"tornado\": \"🌪\",\n    \"trackball\": \"🖲\",\n    \"tractor\": \"🚜\",\n    \"trade_mark\": \"™\",\n    \"train\": \"🚋\",\n    \"tram\": \"🚊\",\n    \"tram_car\": \"🚋\",\n    \"triangular_flag\": \"🚩\",\n    \"triangular_ruler\": \"📐\",\n    \"trident_emblem\": \"🔱\",\n    \"trolleybus\": \"🚎\",\n    \"trophy\": \"🏆\",\n    \"tropical_drink\": \"🍹\",\n    \"tropical_fish\": \"🐠\",\n    \"trumpet\": \"🎺\",\n    \"tulip\": \"🌷\",\n    \"tumbler_glass\": \"🥃\",\n    \"turtle\": \"🐢\",\n    \"twelve-thirty\": \"🕧\",\n    \"twelve_o’clock\": \"🕛\",\n    \"two-hump_camel\": \"🐫\",\n    \"two-thirty\": \"🕝\",\n    \"two_hearts\": \"💕\",\n    \"two_men_holding_hands\": \"👬\",\n    \"two_o’clock\": \"🕑\",\n    \"two_women_holding_hands\": \"👭\",\n    \"umbrella\": \"☂\",\n    \"umbrella_on_ground\": \"⛱\",\n    \"umbrella_with_rain_drops\": \"☔\",\n    \"unamused_face\": \"😒\",\n    \"unicorn_face\": \"🦄\",\n    \"unlocked\": \"🔓\",\n    \"up-down_arrow\": \"↕\",\n    \"up-left_arrow\": \"↖\",\n    \"up-right_arrow\": \"↗\",\n    \"up_arrow\": \"⬆\",\n    \"upside-down_face\": \"🙃\",\n    \"upwards_button\": \"🔼\",\n    \"vampire\": \"🧛\",\n    \"vampire_dark_skin_tone\": \"🧛🏿\",\n    \"vampire_light_skin_tone\": \"🧛🏻\",\n    \"vampire_medium-dark_skin_tone\": \"🧛🏾\",\n    \"vampire_medium-light_skin_tone\": \"🧛🏼\",\n    \"vampire_medium_skin_tone\": \"🧛🏽\",\n    \"vertical_traffic_light\": \"🚦\",\n    \"vibration_mode\": \"📳\",\n    \"victory_hand\": \"✌\",\n    \"victory_hand_dark_skin_tone\": \"✌🏿\",\n    \"victory_hand_light_skin_tone\": \"✌🏻\",\n    \"victory_hand_medium-dark_skin_tone\": \"✌🏾\",\n    \"victory_hand_medium-light_skin_tone\": \"✌🏼\",\n    \"victory_hand_medium_skin_tone\": \"✌🏽\",\n    \"video_camera\": \"📹\",\n    \"video_game\": \"🎮\",\n    \"videocassette\": \"📼\",\n    \"violin\": \"🎻\",\n    \"volcano\": \"🌋\",\n    \"volleyball\": \"🏐\",\n    \"vulcan_salute\": \"🖖\",\n    \"vulcan_salute_dark_skin_tone\": \"🖖🏿\",\n    \"vulcan_salute_light_skin_tone\": \"🖖🏻\",\n    \"vulcan_salute_medium-dark_skin_tone\": \"🖖🏾\",\n    \"vulcan_salute_medium-light_skin_tone\": \"🖖🏼\",\n    \"vulcan_salute_medium_skin_tone\": \"🖖🏽\",\n    \"waffle\": \"🧇\",\n    \"waning_crescent_moon\": \"🌘\",\n    \"waning_gibbous_moon\": \"🌖\",\n    \"warning\": \"⚠\",\n    \"wastebasket\": \"🗑\",\n    \"watch\": \"⌚\",\n    \"water_buffalo\": \"🐃\",\n    \"water_closet\": \"🚾\",\n    \"water_wave\": \"🌊\",\n    \"watermelon\": \"🍉\",\n    \"waving_hand\": \"👋\",\n    \"waving_hand_dark_skin_tone\": \"👋🏿\",\n    \"waving_hand_light_skin_tone\": \"👋🏻\",\n    \"waving_hand_medium-dark_skin_tone\": \"👋🏾\",\n    \"waving_hand_medium-light_skin_tone\": \"👋🏼\",\n    \"waving_hand_medium_skin_tone\": \"👋🏽\",\n    \"wavy_dash\": \"〰\",\n    \"waxing_crescent_moon\": \"🌒\",\n    \"waxing_gibbous_moon\": \"🌔\",\n    \"weary_cat_face\": \"🙀\",\n    \"weary_face\": \"😩\",\n    \"wedding\": \"💒\",\n    \"whale\": \"🐳\",\n    \"wheel_of_dharma\": \"☸\",\n    \"wheelchair_symbol\": \"♿\",\n    \"white_circle\": \"⚪\",\n    \"white_exclamation_mark\": \"❕\",\n    \"white_flag\": \"🏳\",\n    \"white_flower\": \"💮\",\n    \"white_hair\": \"🦳\",\n    \"white-haired_man\": \"👨\\u200d🦳\",\n    \"white-haired_woman\": \"👩\\u200d🦳\",\n    \"white_heart\": \"🤍\",\n    \"white_heavy_check_mark\": \"✅\",\n    \"white_large_square\": \"⬜\",\n    \"white_medium-small_square\": \"◽\",\n    \"white_medium_square\": \"◻\",\n    \"white_medium_star\": \"⭐\",\n    \"white_question_mark\": \"❔\",\n    \"white_small_square\": \"▫\",\n    \"white_square_button\": \"🔳\",\n    \"wilted_flower\": \"🥀\",\n    \"wind_chime\": \"🎐\",\n    \"wind_face\": \"🌬\",\n    \"wine_glass\": \"🍷\",\n    \"winking_face\": \"😉\",\n    \"winking_face_with_tongue\": \"😜\",\n    \"wolf_face\": \"🐺\",\n    \"woman\": \"👩\",\n    \"woman_artist\": \"👩\\u200d🎨\",\n    \"woman_artist_dark_skin_tone\": \"👩🏿\\u200d🎨\",\n    \"woman_artist_light_skin_tone\": \"👩🏻\\u200d🎨\",\n    \"woman_artist_medium-dark_skin_tone\": \"👩🏾\\u200d🎨\",\n    \"woman_artist_medium-light_skin_tone\": \"👩🏼\\u200d🎨\",\n    \"woman_artist_medium_skin_tone\": \"👩🏽\\u200d🎨\",\n    \"woman_astronaut\": \"👩\\u200d🚀\",\n    \"woman_astronaut_dark_skin_tone\": \"👩🏿\\u200d🚀\",\n    \"woman_astronaut_light_skin_tone\": \"👩🏻\\u200d🚀\",\n    \"woman_astronaut_medium-dark_skin_tone\": \"👩🏾\\u200d🚀\",\n    \"woman_astronaut_medium-light_skin_tone\": \"👩🏼\\u200d🚀\",\n    \"woman_astronaut_medium_skin_tone\": \"👩🏽\\u200d🚀\",\n    \"woman_biking\": \"🚴\\u200d♀️\",\n    \"woman_biking_dark_skin_tone\": \"🚴🏿\\u200d♀️\",\n    \"woman_biking_light_skin_tone\": \"🚴🏻\\u200d♀️\",\n    \"woman_biking_medium-dark_skin_tone\": \"🚴🏾\\u200d♀️\",\n    \"woman_biking_medium-light_skin_tone\": \"🚴🏼\\u200d♀️\",\n    \"woman_biking_medium_skin_tone\": \"🚴🏽\\u200d♀️\",\n    \"woman_bouncing_ball\": \"⛹️\\u200d♀️\",\n    \"woman_bouncing_ball_dark_skin_tone\": \"⛹🏿\\u200d♀️\",\n    \"woman_bouncing_ball_light_skin_tone\": \"⛹🏻\\u200d♀️\",\n    \"woman_bouncing_ball_medium-dark_skin_tone\": \"⛹🏾\\u200d♀️\",\n    \"woman_bouncing_ball_medium-light_skin_tone\": \"⛹🏼\\u200d♀️\",\n    \"woman_bouncing_ball_medium_skin_tone\": \"⛹🏽\\u200d♀️\",\n    \"woman_bowing\": \"🙇\\u200d♀️\",\n    \"woman_bowing_dark_skin_tone\": \"🙇🏿\\u200d♀️\",\n    \"woman_bowing_light_skin_tone\": \"🙇🏻\\u200d♀️\",\n    \"woman_bowing_medium-dark_skin_tone\": \"🙇🏾\\u200d♀️\",\n    \"woman_bowing_medium-light_skin_tone\": \"🙇🏼\\u200d♀️\",\n    \"woman_bowing_medium_skin_tone\": \"🙇🏽\\u200d♀️\",\n    \"woman_cartwheeling\": \"🤸\\u200d♀️\",\n    \"woman_cartwheeling_dark_skin_tone\": \"🤸🏿\\u200d♀️\",\n    \"woman_cartwheeling_light_skin_tone\": \"🤸🏻\\u200d♀️\",\n    \"woman_cartwheeling_medium-dark_skin_tone\": \"🤸🏾\\u200d♀️\",\n    \"woman_cartwheeling_medium-light_skin_tone\": \"🤸🏼\\u200d♀️\",\n    \"woman_cartwheeling_medium_skin_tone\": \"🤸🏽\\u200d♀️\",\n    \"woman_climbing\": \"🧗\\u200d♀️\",\n    \"woman_climbing_dark_skin_tone\": \"🧗🏿\\u200d♀️\",\n    \"woman_climbing_light_skin_tone\": \"🧗🏻\\u200d♀️\",\n    \"woman_climbing_medium-dark_skin_tone\": \"🧗🏾\\u200d♀️\",\n    \"woman_climbing_medium-light_skin_tone\": \"🧗🏼\\u200d♀️\",\n    \"woman_climbing_medium_skin_tone\": \"🧗🏽\\u200d♀️\",\n    \"woman_construction_worker\": \"👷\\u200d♀️\",\n    \"woman_construction_worker_dark_skin_tone\": \"👷🏿\\u200d♀️\",\n    \"woman_construction_worker_light_skin_tone\": \"👷🏻\\u200d♀️\",\n    \"woman_construction_worker_medium-dark_skin_tone\": \"👷🏾\\u200d♀️\",\n    \"woman_construction_worker_medium-light_skin_tone\": \"👷🏼\\u200d♀️\",\n    \"woman_construction_worker_medium_skin_tone\": \"👷🏽\\u200d♀️\",\n    \"woman_cook\": \"👩\\u200d🍳\",\n    \"woman_cook_dark_skin_tone\": \"👩🏿\\u200d🍳\",\n    \"woman_cook_light_skin_tone\": \"👩🏻\\u200d🍳\",\n    \"woman_cook_medium-dark_skin_tone\": \"👩🏾\\u200d🍳\",\n    \"woman_cook_medium-light_skin_tone\": \"👩🏼\\u200d🍳\",\n    \"woman_cook_medium_skin_tone\": \"👩🏽\\u200d🍳\",\n    \"woman_dancing\": \"💃\",\n    \"woman_dancing_dark_skin_tone\": \"💃🏿\",\n    \"woman_dancing_light_skin_tone\": \"💃🏻\",\n    \"woman_dancing_medium-dark_skin_tone\": \"💃🏾\",\n    \"woman_dancing_medium-light_skin_tone\": \"💃🏼\",\n    \"woman_dancing_medium_skin_tone\": \"💃🏽\",\n    \"woman_dark_skin_tone\": \"👩🏿\",\n    \"woman_detective\": \"🕵️\\u200d♀️\",\n    \"woman_detective_dark_skin_tone\": \"🕵🏿\\u200d♀️\",\n    \"woman_detective_light_skin_tone\": \"🕵🏻\\u200d♀️\",\n    \"woman_detective_medium-dark_skin_tone\": \"🕵🏾\\u200d♀️\",\n    \"woman_detective_medium-light_skin_tone\": \"🕵🏼\\u200d♀️\",\n    \"woman_detective_medium_skin_tone\": \"🕵🏽\\u200d♀️\",\n    \"woman_elf\": \"🧝\\u200d♀️\",\n    \"woman_elf_dark_skin_tone\": \"🧝🏿\\u200d♀️\",\n    \"woman_elf_light_skin_tone\": \"🧝🏻\\u200d♀️\",\n    \"woman_elf_medium-dark_skin_tone\": \"🧝🏾\\u200d♀️\",\n    \"woman_elf_medium-light_skin_tone\": \"🧝🏼\\u200d♀️\",\n    \"woman_elf_medium_skin_tone\": \"🧝🏽\\u200d♀️\",\n    \"woman_facepalming\": \"🤦\\u200d♀️\",\n    \"woman_facepalming_dark_skin_tone\": \"🤦🏿\\u200d♀️\",\n    \"woman_facepalming_light_skin_tone\": \"🤦🏻\\u200d♀️\",\n    \"woman_facepalming_medium-dark_skin_tone\": \"🤦🏾\\u200d♀️\",\n    \"woman_facepalming_medium-light_skin_tone\": \"🤦🏼\\u200d♀️\",\n    \"woman_facepalming_medium_skin_tone\": \"🤦🏽\\u200d♀️\",\n    \"woman_factory_worker\": \"👩\\u200d🏭\",\n    \"woman_factory_worker_dark_skin_tone\": \"👩🏿\\u200d🏭\",\n    \"woman_factory_worker_light_skin_tone\": \"👩🏻\\u200d🏭\",\n    \"woman_factory_worker_medium-dark_skin_tone\": \"👩🏾\\u200d🏭\",\n    \"woman_factory_worker_medium-light_skin_tone\": \"👩🏼\\u200d🏭\",\n    \"woman_factory_worker_medium_skin_tone\": \"👩🏽\\u200d🏭\",\n    \"woman_fairy\": \"🧚\\u200d♀️\",\n    \"woman_fairy_dark_skin_tone\": \"🧚🏿\\u200d♀️\",\n    \"woman_fairy_light_skin_tone\": \"🧚🏻\\u200d♀️\",\n    \"woman_fairy_medium-dark_skin_tone\": \"🧚🏾\\u200d♀️\",\n    \"woman_fairy_medium-light_skin_tone\": \"🧚🏼\\u200d♀️\",\n    \"woman_fairy_medium_skin_tone\": \"🧚🏽\\u200d♀️\",\n    \"woman_farmer\": \"👩\\u200d🌾\",\n    \"woman_farmer_dark_skin_tone\": \"👩🏿\\u200d🌾\",\n    \"woman_farmer_light_skin_tone\": \"👩🏻\\u200d🌾\",\n    \"woman_farmer_medium-dark_skin_tone\": \"👩🏾\\u200d🌾\",\n    \"woman_farmer_medium-light_skin_tone\": \"👩🏼\\u200d🌾\",\n    \"woman_farmer_medium_skin_tone\": \"👩🏽\\u200d🌾\",\n    \"woman_firefighter\": \"👩\\u200d🚒\",\n    \"woman_firefighter_dark_skin_tone\": \"👩🏿\\u200d🚒\",\n    \"woman_firefighter_light_skin_tone\": \"👩🏻\\u200d🚒\",\n    \"woman_firefighter_medium-dark_skin_tone\": \"👩🏾\\u200d🚒\",\n    \"woman_firefighter_medium-light_skin_tone\": \"👩🏼\\u200d🚒\",\n    \"woman_firefighter_medium_skin_tone\": \"👩🏽\\u200d🚒\",\n    \"woman_frowning\": \"🙍\\u200d♀️\",\n    \"woman_frowning_dark_skin_tone\": \"🙍🏿\\u200d♀️\",\n    \"woman_frowning_light_skin_tone\": \"🙍🏻\\u200d♀️\",\n    \"woman_frowning_medium-dark_skin_tone\": \"🙍🏾\\u200d♀️\",\n    \"woman_frowning_medium-light_skin_tone\": \"🙍🏼\\u200d♀️\",\n    \"woman_frowning_medium_skin_tone\": \"🙍🏽\\u200d♀️\",\n    \"woman_genie\": \"🧞\\u200d♀️\",\n    \"woman_gesturing_no\": \"🙅\\u200d♀️\",\n    \"woman_gesturing_no_dark_skin_tone\": \"🙅🏿\\u200d♀️\",\n    \"woman_gesturing_no_light_skin_tone\": \"🙅🏻\\u200d♀️\",\n    \"woman_gesturing_no_medium-dark_skin_tone\": \"🙅🏾\\u200d♀️\",\n    \"woman_gesturing_no_medium-light_skin_tone\": \"🙅🏼\\u200d♀️\",\n    \"woman_gesturing_no_medium_skin_tone\": \"🙅🏽\\u200d♀️\",\n    \"woman_gesturing_ok\": \"🙆\\u200d♀️\",\n    \"woman_gesturing_ok_dark_skin_tone\": \"🙆🏿\\u200d♀️\",\n    \"woman_gesturing_ok_light_skin_tone\": \"🙆🏻\\u200d♀️\",\n    \"woman_gesturing_ok_medium-dark_skin_tone\": \"🙆🏾\\u200d♀️\",\n    \"woman_gesturing_ok_medium-light_skin_tone\": \"🙆🏼\\u200d♀️\",\n    \"woman_gesturing_ok_medium_skin_tone\": \"🙆🏽\\u200d♀️\",\n    \"woman_getting_haircut\": \"💇\\u200d♀️\",\n    \"woman_getting_haircut_dark_skin_tone\": \"💇🏿\\u200d♀️\",\n    \"woman_getting_haircut_light_skin_tone\": \"💇🏻\\u200d♀️\",\n    \"woman_getting_haircut_medium-dark_skin_tone\": \"💇🏾\\u200d♀️\",\n    \"woman_getting_haircut_medium-light_skin_tone\": \"💇🏼\\u200d♀️\",\n    \"woman_getting_haircut_medium_skin_tone\": \"💇🏽\\u200d♀️\",\n    \"woman_getting_massage\": \"💆\\u200d♀️\",\n    \"woman_getting_massage_dark_skin_tone\": \"💆🏿\\u200d♀️\",\n    \"woman_getting_massage_light_skin_tone\": \"💆🏻\\u200d♀️\",\n    \"woman_getting_massage_medium-dark_skin_tone\": \"💆🏾\\u200d♀️\",\n    \"woman_getting_massage_medium-light_skin_tone\": \"💆🏼\\u200d♀️\",\n    \"woman_getting_massage_medium_skin_tone\": \"💆🏽\\u200d♀️\",\n    \"woman_golfing\": \"🏌️\\u200d♀️\",\n    \"woman_golfing_dark_skin_tone\": \"🏌🏿\\u200d♀️\",\n    \"woman_golfing_light_skin_tone\": \"🏌🏻\\u200d♀️\",\n    \"woman_golfing_medium-dark_skin_tone\": \"🏌🏾\\u200d♀️\",\n    \"woman_golfing_medium-light_skin_tone\": \"🏌🏼\\u200d♀️\",\n    \"woman_golfing_medium_skin_tone\": \"🏌🏽\\u200d♀️\",\n    \"woman_guard\": \"💂\\u200d♀️\",\n    \"woman_guard_dark_skin_tone\": \"💂🏿\\u200d♀️\",\n    \"woman_guard_light_skin_tone\": \"💂🏻\\u200d♀️\",\n    \"woman_guard_medium-dark_skin_tone\": \"💂🏾\\u200d♀️\",\n    \"woman_guard_medium-light_skin_tone\": \"💂🏼\\u200d♀️\",\n    \"woman_guard_medium_skin_tone\": \"💂🏽\\u200d♀️\",\n    \"woman_health_worker\": \"👩\\u200d⚕️\",\n    \"woman_health_worker_dark_skin_tone\": \"👩🏿\\u200d⚕️\",\n    \"woman_health_worker_light_skin_tone\": \"👩🏻\\u200d⚕️\",\n    \"woman_health_worker_medium-dark_skin_tone\": \"👩🏾\\u200d⚕️\",\n    \"woman_health_worker_medium-light_skin_tone\": \"👩🏼\\u200d⚕️\",\n    \"woman_health_worker_medium_skin_tone\": \"👩🏽\\u200d⚕️\",\n    \"woman_in_lotus_position\": \"🧘\\u200d♀️\",\n    \"woman_in_lotus_position_dark_skin_tone\": \"🧘🏿\\u200d♀️\",\n    \"woman_in_lotus_position_light_skin_tone\": \"🧘🏻\\u200d♀️\",\n    \"woman_in_lotus_position_medium-dark_skin_tone\": \"🧘🏾\\u200d♀️\",\n    \"woman_in_lotus_position_medium-light_skin_tone\": \"🧘🏼\\u200d♀️\",\n    \"woman_in_lotus_position_medium_skin_tone\": \"🧘🏽\\u200d♀️\",\n    \"woman_in_manual_wheelchair\": \"👩\\u200d🦽\",\n    \"woman_in_motorized_wheelchair\": \"👩\\u200d🦼\",\n    \"woman_in_steamy_room\": \"🧖\\u200d♀️\",\n    \"woman_in_steamy_room_dark_skin_tone\": \"🧖🏿\\u200d♀️\",\n    \"woman_in_steamy_room_light_skin_tone\": \"🧖🏻\\u200d♀️\",\n    \"woman_in_steamy_room_medium-dark_skin_tone\": \"🧖🏾\\u200d♀️\",\n    \"woman_in_steamy_room_medium-light_skin_tone\": \"🧖🏼\\u200d♀️\",\n    \"woman_in_steamy_room_medium_skin_tone\": \"🧖🏽\\u200d♀️\",\n    \"woman_judge\": \"👩\\u200d⚖️\",\n    \"woman_judge_dark_skin_tone\": \"👩🏿\\u200d⚖️\",\n    \"woman_judge_light_skin_tone\": \"👩🏻\\u200d⚖️\",\n    \"woman_judge_medium-dark_skin_tone\": \"👩🏾\\u200d⚖️\",\n    \"woman_judge_medium-light_skin_tone\": \"👩🏼\\u200d⚖️\",\n    \"woman_judge_medium_skin_tone\": \"👩🏽\\u200d⚖️\",\n    \"woman_juggling\": \"🤹\\u200d♀️\",\n    \"woman_juggling_dark_skin_tone\": \"🤹🏿\\u200d♀️\",\n    \"woman_juggling_light_skin_tone\": \"🤹🏻\\u200d♀️\",\n    \"woman_juggling_medium-dark_skin_tone\": \"🤹🏾\\u200d♀️\",\n    \"woman_juggling_medium-light_skin_tone\": \"🤹🏼\\u200d♀️\",\n    \"woman_juggling_medium_skin_tone\": \"🤹🏽\\u200d♀️\",\n    \"woman_lifting_weights\": \"🏋️\\u200d♀️\",\n    \"woman_lifting_weights_dark_skin_tone\": \"🏋🏿\\u200d♀️\",\n    \"woman_lifting_weights_light_skin_tone\": \"🏋🏻\\u200d♀️\",\n    \"woman_lifting_weights_medium-dark_skin_tone\": \"🏋🏾\\u200d♀️\",\n    \"woman_lifting_weights_medium-light_skin_tone\": \"🏋🏼\\u200d♀️\",\n    \"woman_lifting_weights_medium_skin_tone\": \"🏋🏽\\u200d♀️\",\n    \"woman_light_skin_tone\": \"👩🏻\",\n    \"woman_mage\": \"🧙\\u200d♀️\",\n    \"woman_mage_dark_skin_tone\": \"🧙🏿\\u200d♀️\",\n    \"woman_mage_light_skin_tone\": \"🧙🏻\\u200d♀️\",\n    \"woman_mage_medium-dark_skin_tone\": \"🧙🏾\\u200d♀️\",\n    \"woman_mage_medium-light_skin_tone\": \"🧙🏼\\u200d♀️\",\n    \"woman_mage_medium_skin_tone\": \"🧙🏽\\u200d♀️\",\n    \"woman_mechanic\": \"👩\\u200d🔧\",\n    \"woman_mechanic_dark_skin_tone\": \"👩🏿\\u200d🔧\",\n    \"woman_mechanic_light_skin_tone\": \"👩🏻\\u200d🔧\",\n    \"woman_mechanic_medium-dark_skin_tone\": \"👩🏾\\u200d🔧\",\n    \"woman_mechanic_medium-light_skin_tone\": \"👩🏼\\u200d🔧\",\n    \"woman_mechanic_medium_skin_tone\": \"👩🏽\\u200d🔧\",\n    \"woman_medium-dark_skin_tone\": \"👩🏾\",\n    \"woman_medium-light_skin_tone\": \"👩🏼\",\n    \"woman_medium_skin_tone\": \"👩🏽\",\n    \"woman_mountain_biking\": \"🚵\\u200d♀️\",\n    \"woman_mountain_biking_dark_skin_tone\": \"🚵🏿\\u200d♀️\",\n    \"woman_mountain_biking_light_skin_tone\": \"🚵🏻\\u200d♀️\",\n    \"woman_mountain_biking_medium-dark_skin_tone\": \"🚵🏾\\u200d♀️\",\n    \"woman_mountain_biking_medium-light_skin_tone\": \"🚵🏼\\u200d♀️\",\n    \"woman_mountain_biking_medium_skin_tone\": \"🚵🏽\\u200d♀️\",\n    \"woman_office_worker\": \"👩\\u200d💼\",\n    \"woman_office_worker_dark_skin_tone\": \"👩🏿\\u200d💼\",\n    \"woman_office_worker_light_skin_tone\": \"👩🏻\\u200d💼\",\n    \"woman_office_worker_medium-dark_skin_tone\": \"👩🏾\\u200d💼\",\n    \"woman_office_worker_medium-light_skin_tone\": \"👩🏼\\u200d💼\",\n    \"woman_office_worker_medium_skin_tone\": \"👩🏽\\u200d💼\",\n    \"woman_pilot\": \"👩\\u200d✈️\",\n    \"woman_pilot_dark_skin_tone\": \"👩🏿\\u200d✈️\",\n    \"woman_pilot_light_skin_tone\": \"👩🏻\\u200d✈️\",\n    \"woman_pilot_medium-dark_skin_tone\": \"👩🏾\\u200d✈️\",\n    \"woman_pilot_medium-light_skin_tone\": \"👩🏼\\u200d✈️\",\n    \"woman_pilot_medium_skin_tone\": \"👩🏽\\u200d✈️\",\n    \"woman_playing_handball\": \"🤾\\u200d♀️\",\n    \"woman_playing_handball_dark_skin_tone\": \"🤾🏿\\u200d♀️\",\n    \"woman_playing_handball_light_skin_tone\": \"🤾🏻\\u200d♀️\",\n    \"woman_playing_handball_medium-dark_skin_tone\": \"🤾🏾\\u200d♀️\",\n    \"woman_playing_handball_medium-light_skin_tone\": \"🤾🏼\\u200d♀️\",\n    \"woman_playing_handball_medium_skin_tone\": \"🤾🏽\\u200d♀️\",\n    \"woman_playing_water_polo\": \"🤽\\u200d♀️\",\n    \"woman_playing_water_polo_dark_skin_tone\": \"🤽🏿\\u200d♀️\",\n    \"woman_playing_water_polo_light_skin_tone\": \"🤽🏻\\u200d♀️\",\n    \"woman_playing_water_polo_medium-dark_skin_tone\": \"🤽🏾\\u200d♀️\",\n    \"woman_playing_water_polo_medium-light_skin_tone\": \"🤽🏼\\u200d♀️\",\n    \"woman_playing_water_polo_medium_skin_tone\": \"🤽🏽\\u200d♀️\",\n    \"woman_police_officer\": \"👮\\u200d♀️\",\n    \"woman_police_officer_dark_skin_tone\": \"👮🏿\\u200d♀️\",\n    \"woman_police_officer_light_skin_tone\": \"👮🏻\\u200d♀️\",\n    \"woman_police_officer_medium-dark_skin_tone\": \"👮🏾\\u200d♀️\",\n    \"woman_police_officer_medium-light_skin_tone\": \"👮🏼\\u200d♀️\",\n    \"woman_police_officer_medium_skin_tone\": \"👮🏽\\u200d♀️\",\n    \"woman_pouting\": \"🙎\\u200d♀️\",\n    \"woman_pouting_dark_skin_tone\": \"🙎🏿\\u200d♀️\",\n    \"woman_pouting_light_skin_tone\": \"🙎🏻\\u200d♀️\",\n    \"woman_pouting_medium-dark_skin_tone\": \"🙎🏾\\u200d♀️\",\n    \"woman_pouting_medium-light_skin_tone\": \"🙎🏼\\u200d♀️\",\n    \"woman_pouting_medium_skin_tone\": \"🙎🏽\\u200d♀️\",\n    \"woman_raising_hand\": \"🙋\\u200d♀️\",\n    \"woman_raising_hand_dark_skin_tone\": \"🙋🏿\\u200d♀️\",\n    \"woman_raising_hand_light_skin_tone\": \"🙋🏻\\u200d♀️\",\n    \"woman_raising_hand_medium-dark_skin_tone\": \"🙋🏾\\u200d♀️\",\n    \"woman_raising_hand_medium-light_skin_tone\": \"🙋🏼\\u200d♀️\",\n    \"woman_raising_hand_medium_skin_tone\": \"🙋🏽\\u200d♀️\",\n    \"woman_rowing_boat\": \"🚣\\u200d♀️\",\n    \"woman_rowing_boat_dark_skin_tone\": \"🚣🏿\\u200d♀️\",\n    \"woman_rowing_boat_light_skin_tone\": \"🚣🏻\\u200d♀️\",\n    \"woman_rowing_boat_medium-dark_skin_tone\": \"🚣🏾\\u200d♀️\",\n    \"woman_rowing_boat_medium-light_skin_tone\": \"🚣🏼\\u200d♀️\",\n    \"woman_rowing_boat_medium_skin_tone\": \"🚣🏽\\u200d♀️\",\n    \"woman_running\": \"🏃\\u200d♀️\",\n    \"woman_running_dark_skin_tone\": \"🏃🏿\\u200d♀️\",\n    \"woman_running_light_skin_tone\": \"🏃🏻\\u200d♀️\",\n    \"woman_running_medium-dark_skin_tone\": \"🏃🏾\\u200d♀️\",\n    \"woman_running_medium-light_skin_tone\": \"🏃🏼\\u200d♀️\",\n    \"woman_running_medium_skin_tone\": \"🏃🏽\\u200d♀️\",\n    \"woman_scientist\": \"👩\\u200d🔬\",\n    \"woman_scientist_dark_skin_tone\": \"👩🏿\\u200d🔬\",\n    \"woman_scientist_light_skin_tone\": \"👩🏻\\u200d🔬\",\n    \"woman_scientist_medium-dark_skin_tone\": \"👩🏾\\u200d🔬\",\n    \"woman_scientist_medium-light_skin_tone\": \"👩🏼\\u200d🔬\",\n    \"woman_scientist_medium_skin_tone\": \"👩🏽\\u200d🔬\",\n    \"woman_shrugging\": \"🤷\\u200d♀️\",\n    \"woman_shrugging_dark_skin_tone\": \"🤷🏿\\u200d♀️\",\n    \"woman_shrugging_light_skin_tone\": \"🤷🏻\\u200d♀️\",\n    \"woman_shrugging_medium-dark_skin_tone\": \"🤷🏾\\u200d♀️\",\n    \"woman_shrugging_medium-light_skin_tone\": \"🤷🏼\\u200d♀️\",\n    \"woman_shrugging_medium_skin_tone\": \"🤷🏽\\u200d♀️\",\n    \"woman_singer\": \"👩\\u200d🎤\",\n    \"woman_singer_dark_skin_tone\": \"👩🏿\\u200d🎤\",\n    \"woman_singer_light_skin_tone\": \"👩🏻\\u200d🎤\",\n    \"woman_singer_medium-dark_skin_tone\": \"👩🏾\\u200d🎤\",\n    \"woman_singer_medium-light_skin_tone\": \"👩🏼\\u200d🎤\",\n    \"woman_singer_medium_skin_tone\": \"👩🏽\\u200d🎤\",\n    \"woman_student\": \"👩\\u200d🎓\",\n    \"woman_student_dark_skin_tone\": \"👩🏿\\u200d🎓\",\n    \"woman_student_light_skin_tone\": \"👩🏻\\u200d🎓\",\n    \"woman_student_medium-dark_skin_tone\": \"👩🏾\\u200d🎓\",\n    \"woman_student_medium-light_skin_tone\": \"👩🏼\\u200d🎓\",\n    \"woman_student_medium_skin_tone\": \"👩🏽\\u200d🎓\",\n    \"woman_surfing\": \"🏄\\u200d♀️\",\n    \"woman_surfing_dark_skin_tone\": \"🏄🏿\\u200d♀️\",\n    \"woman_surfing_light_skin_tone\": \"🏄🏻\\u200d♀️\",\n    \"woman_surfing_medium-dark_skin_tone\": \"🏄🏾\\u200d♀️\",\n    \"woman_surfing_medium-light_skin_tone\": \"🏄🏼\\u200d♀️\",\n    \"woman_surfing_medium_skin_tone\": \"🏄🏽\\u200d♀️\",\n    \"woman_swimming\": \"🏊\\u200d♀️\",\n    \"woman_swimming_dark_skin_tone\": \"🏊🏿\\u200d♀️\",\n    \"woman_swimming_light_skin_tone\": \"🏊🏻\\u200d♀️\",\n    \"woman_swimming_medium-dark_skin_tone\": \"🏊🏾\\u200d♀️\",\n    \"woman_swimming_medium-light_skin_tone\": \"🏊🏼\\u200d♀️\",\n    \"woman_swimming_medium_skin_tone\": \"🏊🏽\\u200d♀️\",\n    \"woman_teacher\": \"👩\\u200d🏫\",\n    \"woman_teacher_dark_skin_tone\": \"👩🏿\\u200d🏫\",\n    \"woman_teacher_light_skin_tone\": \"👩🏻\\u200d🏫\",\n    \"woman_teacher_medium-dark_skin_tone\": \"👩🏾\\u200d🏫\",\n    \"woman_teacher_medium-light_skin_tone\": \"👩🏼\\u200d🏫\",\n    \"woman_teacher_medium_skin_tone\": \"👩🏽\\u200d🏫\",\n    \"woman_technologist\": \"👩\\u200d💻\",\n    \"woman_technologist_dark_skin_tone\": \"👩🏿\\u200d💻\",\n    \"woman_technologist_light_skin_tone\": \"👩🏻\\u200d💻\",\n    \"woman_technologist_medium-dark_skin_tone\": \"👩🏾\\u200d💻\",\n    \"woman_technologist_medium-light_skin_tone\": \"👩🏼\\u200d💻\",\n    \"woman_technologist_medium_skin_tone\": \"👩🏽\\u200d💻\",\n    \"woman_tipping_hand\": \"💁\\u200d♀️\",\n    \"woman_tipping_hand_dark_skin_tone\": \"💁🏿\\u200d♀️\",\n    \"woman_tipping_hand_light_skin_tone\": \"💁🏻\\u200d♀️\",\n    \"woman_tipping_hand_medium-dark_skin_tone\": \"💁🏾\\u200d♀️\",\n    \"woman_tipping_hand_medium-light_skin_tone\": \"💁🏼\\u200d♀️\",\n    \"woman_tipping_hand_medium_skin_tone\": \"💁🏽\\u200d♀️\",\n    \"woman_vampire\": \"🧛\\u200d♀️\",\n    \"woman_vampire_dark_skin_tone\": \"🧛🏿\\u200d♀️\",\n    \"woman_vampire_light_skin_tone\": \"🧛🏻\\u200d♀️\",\n    \"woman_vampire_medium-dark_skin_tone\": \"🧛🏾\\u200d♀️\",\n    \"woman_vampire_medium-light_skin_tone\": \"🧛🏼\\u200d♀️\",\n    \"woman_vampire_medium_skin_tone\": \"🧛🏽\\u200d♀️\",\n    \"woman_walking\": \"🚶\\u200d♀️\",\n    \"woman_walking_dark_skin_tone\": \"🚶🏿\\u200d♀️\",\n    \"woman_walking_light_skin_tone\": \"🚶🏻\\u200d♀️\",\n    \"woman_walking_medium-dark_skin_tone\": \"🚶🏾\\u200d♀️\",\n    \"woman_walking_medium-light_skin_tone\": \"🚶🏼\\u200d♀️\",\n    \"woman_walking_medium_skin_tone\": \"🚶🏽\\u200d♀️\",\n    \"woman_wearing_turban\": \"👳\\u200d♀️\",\n    \"woman_wearing_turban_dark_skin_tone\": \"👳🏿\\u200d♀️\",\n    \"woman_wearing_turban_light_skin_tone\": \"👳🏻\\u200d♀️\",\n    \"woman_wearing_turban_medium-dark_skin_tone\": \"👳🏾\\u200d♀️\",\n    \"woman_wearing_turban_medium-light_skin_tone\": \"👳🏼\\u200d♀️\",\n    \"woman_wearing_turban_medium_skin_tone\": \"👳🏽\\u200d♀️\",\n    \"woman_with_headscarf\": \"🧕\",\n    \"woman_with_headscarf_dark_skin_tone\": \"🧕🏿\",\n    \"woman_with_headscarf_light_skin_tone\": \"🧕🏻\",\n    \"woman_with_headscarf_medium-dark_skin_tone\": \"🧕🏾\",\n    \"woman_with_headscarf_medium-light_skin_tone\": \"🧕🏼\",\n    \"woman_with_headscarf_medium_skin_tone\": \"🧕🏽\",\n    \"woman_with_probing_cane\": \"👩\\u200d🦯\",\n    \"woman_zombie\": \"🧟\\u200d♀️\",\n    \"woman’s_boot\": \"👢\",\n    \"woman’s_clothes\": \"👚\",\n    \"woman’s_hat\": \"👒\",\n    \"woman’s_sandal\": \"👡\",\n    \"women_with_bunny_ears\": \"👯\\u200d♀️\",\n    \"women_wrestling\": \"🤼\\u200d♀️\",\n    \"women’s_room\": \"🚺\",\n    \"woozy_face\": \"🥴\",\n    \"world_map\": \"🗺\",\n    \"worried_face\": \"😟\",\n    \"wrapped_gift\": \"🎁\",\n    \"wrench\": \"🔧\",\n    \"writing_hand\": \"✍\",\n    \"writing_hand_dark_skin_tone\": \"✍🏿\",\n    \"writing_hand_light_skin_tone\": \"✍🏻\",\n    \"writing_hand_medium-dark_skin_tone\": \"✍🏾\",\n    \"writing_hand_medium-light_skin_tone\": \"✍🏼\",\n    \"writing_hand_medium_skin_tone\": \"✍🏽\",\n    \"yarn\": \"🧶\",\n    \"yawning_face\": \"🥱\",\n    \"yellow_circle\": \"🟡\",\n    \"yellow_heart\": \"💛\",\n    \"yellow_square\": \"🟨\",\n    \"yen_banknote\": \"💴\",\n    \"yo-yo\": \"🪀\",\n    \"yin_yang\": \"☯\",\n    \"zany_face\": \"🤪\",\n    \"zebra\": \"🦓\",\n    \"zipper-mouth_face\": \"🤐\",\n    \"zombie\": \"🧟\",\n    \"zzz\": \"💤\",\n    \"åland_islands\": \"🇦🇽\",\n    \"keycap_asterisk\": \"*⃣\",\n    \"keycap_digit_eight\": \"8⃣\",\n    \"keycap_digit_five\": \"5⃣\",\n    \"keycap_digit_four\": \"4⃣\",\n    \"keycap_digit_nine\": \"9⃣\",\n    \"keycap_digit_one\": \"1⃣\",\n    \"keycap_digit_seven\": \"7⃣\",\n    \"keycap_digit_six\": \"6⃣\",\n    \"keycap_digit_three\": \"3⃣\",\n    \"keycap_digit_two\": \"2⃣\",\n    \"keycap_digit_zero\": \"0⃣\",\n    \"keycap_number_sign\": \"#⃣\",\n    \"light_skin_tone\": \"🏻\",\n    \"medium_light_skin_tone\": \"🏼\",\n    \"medium_skin_tone\": \"🏽\",\n    \"medium_dark_skin_tone\": \"🏾\",\n    \"dark_skin_tone\": \"🏿\",\n    \"regional_indicator_symbol_letter_a\": \"🇦\",\n    \"regional_indicator_symbol_letter_b\": \"🇧\",\n    \"regional_indicator_symbol_letter_c\": \"🇨\",\n    \"regional_indicator_symbol_letter_d\": \"🇩\",\n    \"regional_indicator_symbol_letter_e\": \"🇪\",\n    \"regional_indicator_symbol_letter_f\": \"🇫\",\n    \"regional_indicator_symbol_letter_g\": \"🇬\",\n    \"regional_indicator_symbol_letter_h\": \"🇭\",\n    \"regional_indicator_symbol_letter_i\": \"🇮\",\n    \"regional_indicator_symbol_letter_j\": \"🇯\",\n    \"regional_indicator_symbol_letter_k\": \"🇰\",\n    \"regional_indicator_symbol_letter_l\": \"🇱\",\n    \"regional_indicator_symbol_letter_m\": \"🇲\",\n    \"regional_indicator_symbol_letter_n\": \"🇳\",\n    \"regional_indicator_symbol_letter_o\": \"🇴\",\n    \"regional_indicator_symbol_letter_p\": \"🇵\",\n    \"regional_indicator_symbol_letter_q\": \"🇶\",\n    \"regional_indicator_symbol_letter_r\": \"🇷\",\n    \"regional_indicator_symbol_letter_s\": \"🇸\",\n    \"regional_indicator_symbol_letter_t\": \"🇹\",\n    \"regional_indicator_symbol_letter_u\": \"🇺\",\n    \"regional_indicator_symbol_letter_v\": \"🇻\",\n    \"regional_indicator_symbol_letter_w\": \"🇼\",\n    \"regional_indicator_symbol_letter_x\": \"🇽\",\n    \"regional_indicator_symbol_letter_y\": \"🇾\",\n    \"regional_indicator_symbol_letter_z\": \"🇿\",\n    \"airplane_arriving\": \"🛬\",\n    \"space_invader\": \"👾\",\n    \"football\": \"🏈\",\n    \"anger\": \"💢\",\n    \"angry\": \"😠\",\n    \"anguished\": \"😧\",\n    \"signal_strength\": \"📶\",\n    \"arrows_counterclockwise\": \"🔄\",\n    \"arrow_heading_down\": \"⤵\",\n    \"arrow_heading_up\": \"⤴\",\n    \"art\": \"🎨\",\n    \"astonished\": \"😲\",\n    \"athletic_shoe\": \"👟\",\n    \"atm\": \"🏧\",\n    \"car\": \"🚗\",\n    \"red_car\": \"🚗\",\n    \"angel\": \"👼\",\n    \"back\": \"🔙\",\n    \"badminton_racquet_and_shuttlecock\": \"🏸\",\n    \"dollar\": \"💵\",\n    \"euro\": \"💶\",\n    \"pound\": \"💷\",\n    \"yen\": \"💴\",\n    \"barber\": \"💈\",\n    \"bath\": \"🛀\",\n    \"bear\": \"🐻\",\n    \"heartbeat\": \"💓\",\n    \"beer\": \"🍺\",\n    \"no_bell\": \"🔕\",\n    \"bento\": \"🍱\",\n    \"bike\": \"🚲\",\n    \"bicyclist\": \"🚴\",\n    \"8ball\": \"🎱\",\n    \"biohazard_sign\": \"☣\",\n    \"birthday\": \"🎂\",\n    \"black_circle_for_record\": \"⏺\",\n    \"clubs\": \"♣\",\n    \"diamonds\": \"♦\",\n    \"arrow_double_down\": \"⏬\",\n    \"hearts\": \"♥\",\n    \"rewind\": \"⏪\",\n    \"black_left__pointing_double_triangle_with_vertical_bar\": \"⏮\",\n    \"arrow_backward\": \"◀\",\n    \"black_medium_small_square\": \"◾\",\n    \"question\": \"❓\",\n    \"fast_forward\": \"⏩\",\n    \"black_right__pointing_double_triangle_with_vertical_bar\": \"⏭\",\n    \"arrow_forward\": \"▶\",\n    \"black_right__pointing_triangle_with_double_vertical_bar\": \"⏯\",\n    \"arrow_right\": \"➡\",\n    \"spades\": \"♠\",\n    \"black_square_for_stop\": \"⏹\",\n    \"sunny\": \"☀\",\n    \"phone\": \"☎\",\n    \"recycle\": \"♻\",\n    \"arrow_double_up\": \"⏫\",\n    \"busstop\": \"🚏\",\n    \"date\": \"📅\",\n    \"flags\": \"🎏\",\n    \"cat2\": \"🐈\",\n    \"joy_cat\": \"😹\",\n    \"smirk_cat\": \"😼\",\n    \"chart_with_downwards_trend\": \"📉\",\n    \"chart_with_upwards_trend\": \"📈\",\n    \"chart\": \"💹\",\n    \"mega\": \"📣\",\n    \"checkered_flag\": \"🏁\",\n    \"accept\": \"🉑\",\n    \"ideograph_advantage\": \"🉐\",\n    \"congratulations\": \"㊗\",\n    \"secret\": \"㊙\",\n    \"m\": \"Ⓜ\",\n    \"city_sunset\": \"🌆\",\n    \"clapper\": \"🎬\",\n    \"clap\": \"👏\",\n    \"beers\": \"🍻\",\n    \"clock830\": \"🕣\",\n    \"clock8\": \"🕗\",\n    \"clock1130\": \"🕦\",\n    \"clock11\": \"🕚\",\n    \"clock530\": \"🕠\",\n    \"clock5\": \"🕔\",\n    \"clock430\": \"🕟\",\n    \"clock4\": \"🕓\",\n    \"clock930\": \"🕤\",\n    \"clock9\": \"🕘\",\n    \"clock130\": \"🕜\",\n    \"clock1\": \"🕐\",\n    \"clock730\": \"🕢\",\n    \"clock7\": \"🕖\",\n    \"clock630\": \"🕡\",\n    \"clock6\": \"🕕\",\n    \"clock1030\": \"🕥\",\n    \"clock10\": \"🕙\",\n    \"clock330\": \"🕞\",\n    \"clock3\": \"🕒\",\n    \"clock1230\": \"🕧\",\n    \"clock12\": \"🕛\",\n    \"clock230\": \"🕝\",\n    \"clock2\": \"🕑\",\n    \"arrows_clockwise\": \"🔃\",\n    \"repeat\": \"🔁\",\n    \"repeat_one\": \"🔂\",\n    \"closed_lock_with_key\": \"🔐\",\n    \"mailbox_closed\": \"📪\",\n    \"mailbox\": \"📫\",\n    \"cloud_with_tornado\": \"🌪\",\n    \"cocktail\": \"🍸\",\n    \"boom\": \"💥\",\n    \"compression\": \"🗜\",\n    \"confounded\": \"😖\",\n    \"confused\": \"😕\",\n    \"rice\": \"🍚\",\n    \"cow2\": \"🐄\",\n    \"cricket_bat_and_ball\": \"🏏\",\n    \"x\": \"❌\",\n    \"cry\": \"😢\",\n    \"curry\": \"🍛\",\n    \"dagger_knife\": \"🗡\",\n    \"dancer\": \"💃\",\n    \"dark_sunglasses\": \"🕶\",\n    \"dash\": \"💨\",\n    \"truck\": \"🚚\",\n    \"derelict_house_building\": \"🏚\",\n    \"diamond_shape_with_a_dot_inside\": \"💠\",\n    \"dart\": \"🎯\",\n    \"disappointed_relieved\": \"😥\",\n    \"disappointed\": \"😞\",\n    \"do_not_litter\": \"🚯\",\n    \"dog2\": \"🐕\",\n    \"flipper\": \"🐬\",\n    \"loop\": \"➿\",\n    \"bangbang\": \"‼\",\n    \"double_vertical_bar\": \"⏸\",\n    \"dove_of_peace\": \"🕊\",\n    \"small_red_triangle_down\": \"🔻\",\n    \"arrow_down_small\": \"🔽\",\n    \"arrow_down\": \"⬇\",\n    \"dromedary_camel\": \"🐪\",\n    \"e__mail\": \"📧\",\n    \"corn\": \"🌽\",\n    \"ear_of_rice\": \"🌾\",\n    \"earth_americas\": \"🌎\",\n    \"earth_asia\": \"🌏\",\n    \"earth_africa\": \"🌍\",\n    \"eight_pointed_black_star\": \"✴\",\n    \"eight_spoked_asterisk\": \"✳\",\n    \"eject_symbol\": \"⏏\",\n    \"bulb\": \"💡\",\n    \"emoji_modifier_fitzpatrick_type__1__2\": \"🏻\",\n    \"emoji_modifier_fitzpatrick_type__3\": \"🏼\",\n    \"emoji_modifier_fitzpatrick_type__4\": \"🏽\",\n    \"emoji_modifier_fitzpatrick_type__5\": \"🏾\",\n    \"emoji_modifier_fitzpatrick_type__6\": \"🏿\",\n    \"end\": \"🔚\",\n    \"email\": \"✉\",\n    \"european_castle\": \"🏰\",\n    \"european_post_office\": \"🏤\",\n    \"interrobang\": \"⁉\",\n    \"expressionless\": \"😑\",\n    \"eyeglasses\": \"👓\",\n    \"massage\": \"💆\",\n    \"yum\": \"😋\",\n    \"scream\": \"😱\",\n    \"kissing_heart\": \"😘\",\n    \"sweat\": \"😓\",\n    \"face_with_head__bandage\": \"🤕\",\n    \"triumph\": \"😤\",\n    \"mask\": \"😷\",\n    \"no_good\": \"🙅\",\n    \"ok_woman\": \"🙆\",\n    \"open_mouth\": \"😮\",\n    \"cold_sweat\": \"😰\",\n    \"stuck_out_tongue\": \"😛\",\n    \"stuck_out_tongue_closed_eyes\": \"😝\",\n    \"stuck_out_tongue_winking_eye\": \"😜\",\n    \"joy\": \"😂\",\n    \"no_mouth\": \"😶\",\n    \"santa\": \"🎅\",\n    \"fax\": \"📠\",\n    \"fearful\": \"😨\",\n    \"field_hockey_stick_and_ball\": \"🏑\",\n    \"first_quarter_moon_with_face\": \"🌛\",\n    \"fish_cake\": \"🍥\",\n    \"fishing_pole_and_fish\": \"🎣\",\n    \"facepunch\": \"👊\",\n    \"punch\": \"👊\",\n    \"flag_for_afghanistan\": \"🇦🇫\",\n    \"flag_for_albania\": \"🇦🇱\",\n    \"flag_for_algeria\": \"🇩🇿\",\n    \"flag_for_american_samoa\": \"🇦🇸\",\n    \"flag_for_andorra\": \"🇦🇩\",\n    \"flag_for_angola\": \"🇦🇴\",\n    \"flag_for_anguilla\": \"🇦🇮\",\n    \"flag_for_antarctica\": \"🇦🇶\",\n    \"flag_for_antigua_&_barbuda\": \"🇦🇬\",\n    \"flag_for_argentina\": \"🇦🇷\",\n    \"flag_for_armenia\": \"🇦🇲\",\n    \"flag_for_aruba\": \"🇦🇼\",\n    \"flag_for_ascension_island\": \"🇦🇨\",\n    \"flag_for_australia\": \"🇦🇺\",\n    \"flag_for_austria\": \"🇦🇹\",\n    \"flag_for_azerbaijan\": \"🇦🇿\",\n    \"flag_for_bahamas\": \"🇧🇸\",\n    \"flag_for_bahrain\": \"🇧🇭\",\n    \"flag_for_bangladesh\": \"🇧🇩\",\n    \"flag_for_barbados\": \"🇧🇧\",\n    \"flag_for_belarus\": \"🇧🇾\",\n    \"flag_for_belgium\": \"🇧🇪\",\n    \"flag_for_belize\": \"🇧🇿\",\n    \"flag_for_benin\": \"🇧🇯\",\n    \"flag_for_bermuda\": \"🇧🇲\",\n    \"flag_for_bhutan\": \"🇧🇹\",\n    \"flag_for_bolivia\": \"🇧🇴\",\n    \"flag_for_bosnia_&_herzegovina\": \"🇧🇦\",\n    \"flag_for_botswana\": \"🇧🇼\",\n    \"flag_for_bouvet_island\": \"🇧🇻\",\n    \"flag_for_brazil\": \"🇧🇷\",\n    \"flag_for_british_indian_ocean_territory\": \"🇮🇴\",\n    \"flag_for_british_virgin_islands\": \"🇻🇬\",\n    \"flag_for_brunei\": \"🇧🇳\",\n    \"flag_for_bulgaria\": \"🇧🇬\",\n    \"flag_for_burkina_faso\": \"🇧🇫\",\n    \"flag_for_burundi\": \"🇧🇮\",\n    \"flag_for_cambodia\": \"🇰🇭\",\n    \"flag_for_cameroon\": \"🇨🇲\",\n    \"flag_for_canada\": \"🇨🇦\",\n    \"flag_for_canary_islands\": \"🇮🇨\",\n    \"flag_for_cape_verde\": \"🇨🇻\",\n    \"flag_for_caribbean_netherlands\": \"🇧🇶\",\n    \"flag_for_cayman_islands\": \"🇰🇾\",\n    \"flag_for_central_african_republic\": \"🇨🇫\",\n    \"flag_for_ceuta_&_melilla\": \"🇪🇦\",\n    \"flag_for_chad\": \"🇹🇩\",\n    \"flag_for_chile\": \"🇨🇱\",\n    \"flag_for_china\": \"🇨🇳\",\n    \"flag_for_christmas_island\": \"🇨🇽\",\n    \"flag_for_clipperton_island\": \"🇨🇵\",\n    \"flag_for_cocos__islands\": \"🇨🇨\",\n    \"flag_for_colombia\": \"🇨🇴\",\n    \"flag_for_comoros\": \"🇰🇲\",\n    \"flag_for_congo____brazzaville\": \"🇨🇬\",\n    \"flag_for_congo____kinshasa\": \"🇨🇩\",\n    \"flag_for_cook_islands\": \"🇨🇰\",\n    \"flag_for_costa_rica\": \"🇨🇷\",\n    \"flag_for_croatia\": \"🇭🇷\",\n    \"flag_for_cuba\": \"🇨🇺\",\n    \"flag_for_curaçao\": \"🇨🇼\",\n    \"flag_for_cyprus\": \"🇨🇾\",\n    \"flag_for_czech_republic\": \"🇨🇿\",\n    \"flag_for_côte_d’ivoire\": \"🇨🇮\",\n    \"flag_for_denmark\": \"🇩🇰\",\n    \"flag_for_diego_garcia\": \"🇩🇬\",\n    \"flag_for_djibouti\": \"🇩🇯\",\n    \"flag_for_dominica\": \"🇩🇲\",\n    \"flag_for_dominican_republic\": \"🇩🇴\",\n    \"flag_for_ecuador\": \"🇪🇨\",\n    \"flag_for_egypt\": \"🇪🇬\",\n    \"flag_for_el_salvador\": \"🇸🇻\",\n    \"flag_for_equatorial_guinea\": \"🇬🇶\",\n    \"flag_for_eritrea\": \"🇪🇷\",\n    \"flag_for_estonia\": \"🇪🇪\",\n    \"flag_for_ethiopia\": \"🇪🇹\",\n    \"flag_for_european_union\": \"🇪🇺\",\n    \"flag_for_falkland_islands\": \"🇫🇰\",\n    \"flag_for_faroe_islands\": \"🇫🇴\",\n    \"flag_for_fiji\": \"🇫🇯\",\n    \"flag_for_finland\": \"🇫🇮\",\n    \"flag_for_france\": \"🇫🇷\",\n    \"flag_for_french_guiana\": \"🇬🇫\",\n    \"flag_for_french_polynesia\": \"🇵🇫\",\n    \"flag_for_french_southern_territories\": \"🇹🇫\",\n    \"flag_for_gabon\": \"🇬🇦\",\n    \"flag_for_gambia\": \"🇬🇲\",\n    \"flag_for_georgia\": \"🇬🇪\",\n    \"flag_for_germany\": \"🇩🇪\",\n    \"flag_for_ghana\": \"🇬🇭\",\n    \"flag_for_gibraltar\": \"🇬🇮\",\n    \"flag_for_greece\": \"🇬🇷\",\n    \"flag_for_greenland\": \"🇬🇱\",\n    \"flag_for_grenada\": \"🇬🇩\",\n    \"flag_for_guadeloupe\": \"🇬🇵\",\n    \"flag_for_guam\": \"🇬🇺\",\n    \"flag_for_guatemala\": \"🇬🇹\",\n    \"flag_for_guernsey\": \"🇬🇬\",\n    \"flag_for_guinea\": \"🇬🇳\",\n    \"flag_for_guinea__bissau\": \"🇬🇼\",\n    \"flag_for_guyana\": \"🇬🇾\",\n    \"flag_for_haiti\": \"🇭🇹\",\n    \"flag_for_heard_&_mcdonald_islands\": \"🇭🇲\",\n    \"flag_for_honduras\": \"🇭🇳\",\n    \"flag_for_hong_kong\": \"🇭🇰\",\n    \"flag_for_hungary\": \"🇭🇺\",\n    \"flag_for_iceland\": \"🇮🇸\",\n    \"flag_for_india\": \"🇮🇳\",\n    \"flag_for_indonesia\": \"🇮🇩\",\n    \"flag_for_iran\": \"🇮🇷\",\n    \"flag_for_iraq\": \"🇮🇶\",\n    \"flag_for_ireland\": \"🇮🇪\",\n    \"flag_for_isle_of_man\": \"🇮🇲\",\n    \"flag_for_israel\": \"🇮🇱\",\n    \"flag_for_italy\": \"🇮🇹\",\n    \"flag_for_jamaica\": \"🇯🇲\",\n    \"flag_for_japan\": \"🇯🇵\",\n    \"flag_for_jersey\": \"🇯🇪\",\n    \"flag_for_jordan\": \"🇯🇴\",\n    \"flag_for_kazakhstan\": \"🇰🇿\",\n    \"flag_for_kenya\": \"🇰🇪\",\n    \"flag_for_kiribati\": \"🇰🇮\",\n    \"flag_for_kosovo\": \"🇽🇰\",\n    \"flag_for_kuwait\": \"🇰🇼\",\n    \"flag_for_kyrgyzstan\": \"🇰🇬\",\n    \"flag_for_laos\": \"🇱🇦\",\n    \"flag_for_latvia\": \"🇱🇻\",\n    \"flag_for_lebanon\": \"🇱🇧\",\n    \"flag_for_lesotho\": \"🇱🇸\",\n    \"flag_for_liberia\": \"🇱🇷\",\n    \"flag_for_libya\": \"🇱🇾\",\n    \"flag_for_liechtenstein\": \"🇱🇮\",\n    \"flag_for_lithuania\": \"🇱🇹\",\n    \"flag_for_luxembourg\": \"🇱🇺\",\n    \"flag_for_macau\": \"🇲🇴\",\n    \"flag_for_macedonia\": \"🇲🇰\",\n    \"flag_for_madagascar\": \"🇲🇬\",\n    \"flag_for_malawi\": \"🇲🇼\",\n    \"flag_for_malaysia\": \"🇲🇾\",\n    \"flag_for_maldives\": \"🇲🇻\",\n    \"flag_for_mali\": \"🇲🇱\",\n    \"flag_for_malta\": \"🇲🇹\",\n    \"flag_for_marshall_islands\": \"🇲🇭\",\n    \"flag_for_martinique\": \"🇲🇶\",\n    \"flag_for_mauritania\": \"🇲🇷\",\n    \"flag_for_mauritius\": \"🇲🇺\",\n    \"flag_for_mayotte\": \"🇾🇹\",\n    \"flag_for_mexico\": \"🇲🇽\",\n    \"flag_for_micronesia\": \"🇫🇲\",\n    \"flag_for_moldova\": \"🇲🇩\",\n    \"flag_for_monaco\": \"🇲🇨\",\n    \"flag_for_mongolia\": \"🇲🇳\",\n    \"flag_for_montenegro\": \"🇲🇪\",\n    \"flag_for_montserrat\": \"🇲🇸\",\n    \"flag_for_morocco\": \"🇲🇦\",\n    \"flag_for_mozambique\": \"🇲🇿\",\n    \"flag_for_myanmar\": \"🇲🇲\",\n    \"flag_for_namibia\": \"🇳🇦\",\n    \"flag_for_nauru\": \"🇳🇷\",\n    \"flag_for_nepal\": \"🇳🇵\",\n    \"flag_for_netherlands\": \"🇳🇱\",\n    \"flag_for_new_caledonia\": \"🇳🇨\",\n    \"flag_for_new_zealand\": \"🇳🇿\",\n    \"flag_for_nicaragua\": \"🇳🇮\",\n    \"flag_for_niger\": \"🇳🇪\",\n    \"flag_for_nigeria\": \"🇳🇬\",\n    \"flag_for_niue\": \"🇳🇺\",\n    \"flag_for_norfolk_island\": \"🇳🇫\",\n    \"flag_for_north_korea\": \"🇰🇵\",\n    \"flag_for_northern_mariana_islands\": \"🇲🇵\",\n    \"flag_for_norway\": \"🇳🇴\",\n    \"flag_for_oman\": \"🇴🇲\",\n    \"flag_for_pakistan\": \"🇵🇰\",\n    \"flag_for_palau\": \"🇵🇼\",\n    \"flag_for_palestinian_territories\": \"🇵🇸\",\n    \"flag_for_panama\": \"🇵🇦\",\n    \"flag_for_papua_new_guinea\": \"🇵🇬\",\n    \"flag_for_paraguay\": \"🇵🇾\",\n    \"flag_for_peru\": \"🇵🇪\",\n    \"flag_for_philippines\": \"🇵🇭\",\n    \"flag_for_pitcairn_islands\": \"🇵🇳\",\n    \"flag_for_poland\": \"🇵🇱\",\n    \"flag_for_portugal\": \"🇵🇹\",\n    \"flag_for_puerto_rico\": \"🇵🇷\",\n    \"flag_for_qatar\": \"🇶🇦\",\n    \"flag_for_romania\": \"🇷🇴\",\n    \"flag_for_russia\": \"🇷🇺\",\n    \"flag_for_rwanda\": \"🇷🇼\",\n    \"flag_for_réunion\": \"🇷🇪\",\n    \"flag_for_samoa\": \"🇼🇸\",\n    \"flag_for_san_marino\": \"🇸🇲\",\n    \"flag_for_saudi_arabia\": \"🇸🇦\",\n    \"flag_for_senegal\": \"🇸🇳\",\n    \"flag_for_serbia\": \"🇷🇸\",\n    \"flag_for_seychelles\": \"🇸🇨\",\n    \"flag_for_sierra_leone\": \"🇸🇱\",\n    \"flag_for_singapore\": \"🇸🇬\",\n    \"flag_for_sint_maarten\": \"🇸🇽\",\n    \"flag_for_slovakia\": \"🇸🇰\",\n    \"flag_for_slovenia\": \"🇸🇮\",\n    \"flag_for_solomon_islands\": \"🇸🇧\",\n    \"flag_for_somalia\": \"🇸🇴\",\n    \"flag_for_south_africa\": \"🇿🇦\",\n    \"flag_for_south_georgia_&_south_sandwich_islands\": \"🇬🇸\",\n    \"flag_for_south_korea\": \"🇰🇷\",\n    \"flag_for_south_sudan\": \"🇸🇸\",\n    \"flag_for_spain\": \"🇪🇸\",\n    \"flag_for_sri_lanka\": \"🇱🇰\",\n    \"flag_for_st._barthélemy\": \"🇧🇱\",\n    \"flag_for_st._helena\": \"🇸🇭\",\n    \"flag_for_st._kitts_&_nevis\": \"🇰🇳\",\n    \"flag_for_st._lucia\": \"🇱🇨\",\n    \"flag_for_st._martin\": \"🇲🇫\",\n    \"flag_for_st._pierre_&_miquelon\": \"🇵🇲\",\n    \"flag_for_st._vincent_&_grenadines\": \"🇻🇨\",\n    \"flag_for_sudan\": \"🇸🇩\",\n    \"flag_for_suriname\": \"🇸🇷\",\n    \"flag_for_svalbard_&_jan_mayen\": \"🇸🇯\",\n    \"flag_for_swaziland\": \"🇸🇿\",\n    \"flag_for_sweden\": \"🇸🇪\",\n    \"flag_for_switzerland\": \"🇨🇭\",\n    \"flag_for_syria\": \"🇸🇾\",\n    \"flag_for_são_tomé_&_príncipe\": \"🇸🇹\",\n    \"flag_for_taiwan\": \"🇹🇼\",\n    \"flag_for_tajikistan\": \"🇹🇯\",\n    \"flag_for_tanzania\": \"🇹🇿\",\n    \"flag_for_thailand\": \"🇹🇭\",\n    \"flag_for_timor__leste\": \"🇹🇱\",\n    \"flag_for_togo\": \"🇹🇬\",\n    \"flag_for_tokelau\": \"🇹🇰\",\n    \"flag_for_tonga\": \"🇹🇴\",\n    \"flag_for_trinidad_&_tobago\": \"🇹🇹\",\n    \"flag_for_tristan_da_cunha\": \"🇹🇦\",\n    \"flag_for_tunisia\": \"🇹🇳\",\n    \"flag_for_turkey\": \"🇹🇷\",\n    \"flag_for_turkmenistan\": \"🇹🇲\",\n    \"flag_for_turks_&_caicos_islands\": \"🇹🇨\",\n    \"flag_for_tuvalu\": \"🇹🇻\",\n    \"flag_for_u.s._outlying_islands\": \"🇺🇲\",\n    \"flag_for_u.s._virgin_islands\": \"🇻🇮\",\n    \"flag_for_uganda\": \"🇺🇬\",\n    \"flag_for_ukraine\": \"🇺🇦\",\n    \"flag_for_united_arab_emirates\": \"🇦🇪\",\n    \"flag_for_united_kingdom\": \"🇬🇧\",\n    \"flag_for_united_states\": \"🇺🇸\",\n    \"flag_for_uruguay\": \"🇺🇾\",\n    \"flag_for_uzbekistan\": \"🇺🇿\",\n    \"flag_for_vanuatu\": \"🇻🇺\",\n    \"flag_for_vatican_city\": \"🇻🇦\",\n    \"flag_for_venezuela\": \"🇻🇪\",\n    \"flag_for_vietnam\": \"🇻🇳\",\n    \"flag_for_wallis_&_futuna\": \"🇼🇫\",\n    \"flag_for_western_sahara\": \"🇪🇭\",\n    \"flag_for_yemen\": \"🇾🇪\",\n    \"flag_for_zambia\": \"🇿🇲\",\n    \"flag_for_zimbabwe\": \"🇿🇼\",\n    \"flag_for_åland_islands\": \"🇦🇽\",\n    \"golf\": \"⛳\",\n    \"fleur__de__lis\": \"⚜\",\n    \"muscle\": \"💪\",\n    \"flushed\": \"😳\",\n    \"frame_with_picture\": \"🖼\",\n    \"fries\": \"🍟\",\n    \"frog\": \"🐸\",\n    \"hatched_chick\": \"🐥\",\n    \"frowning\": \"😦\",\n    \"fuelpump\": \"⛽\",\n    \"full_moon_with_face\": \"🌝\",\n    \"gem\": \"💎\",\n    \"star2\": \"🌟\",\n    \"golfer\": \"🏌\",\n    \"mortar_board\": \"🎓\",\n    \"grimacing\": \"😬\",\n    \"smile_cat\": \"😸\",\n    \"grinning\": \"😀\",\n    \"grin\": \"😁\",\n    \"heartpulse\": \"💗\",\n    \"guardsman\": \"💂\",\n    \"haircut\": \"💇\",\n    \"hamster\": \"🐹\",\n    \"raising_hand\": \"🙋\",\n    \"headphones\": \"🎧\",\n    \"hear_no_evil\": \"🙉\",\n    \"cupid\": \"💘\",\n    \"gift_heart\": \"💝\",\n    \"heart\": \"❤\",\n    \"exclamation\": \"❗\",\n    \"heavy_exclamation_mark\": \"❗\",\n    \"heavy_heart_exclamation_mark_ornament\": \"❣\",\n    \"o\": \"⭕\",\n    \"helm_symbol\": \"⎈\",\n    \"helmet_with_white_cross\": \"⛑\",\n    \"high_heel\": \"👠\",\n    \"bullettrain_side\": \"🚄\",\n    \"bullettrain_front\": \"🚅\",\n    \"high_brightness\": \"🔆\",\n    \"zap\": \"⚡\",\n    \"hocho\": \"🔪\",\n    \"knife\": \"🔪\",\n    \"bee\": \"🐝\",\n    \"traffic_light\": \"🚥\",\n    \"racehorse\": \"🐎\",\n    \"coffee\": \"☕\",\n    \"hotsprings\": \"♨\",\n    \"hourglass\": \"⌛\",\n    \"hourglass_flowing_sand\": \"⏳\",\n    \"house_buildings\": \"🏘\",\n    \"100\": \"💯\",\n    \"hushed\": \"😯\",\n    \"ice_hockey_stick_and_puck\": \"🏒\",\n    \"imp\": \"👿\",\n    \"information_desk_person\": \"💁\",\n    \"information_source\": \"ℹ\",\n    \"capital_abcd\": \"🔠\",\n    \"abc\": \"🔤\",\n    \"abcd\": \"🔡\",\n    \"1234\": \"🔢\",\n    \"symbols\": \"🔣\",\n    \"izakaya_lantern\": \"🏮\",\n    \"lantern\": \"🏮\",\n    \"jack_o_lantern\": \"🎃\",\n    \"dolls\": \"🎎\",\n    \"japanese_goblin\": \"👺\",\n    \"japanese_ogre\": \"👹\",\n    \"beginner\": \"🔰\",\n    \"zero\": \"0️⃣\",\n    \"one\": \"1️⃣\",\n    \"ten\": \"🔟\",\n    \"two\": \"2️⃣\",\n    \"three\": \"3️⃣\",\n    \"four\": \"4️⃣\",\n    \"five\": \"5️⃣\",\n    \"six\": \"6️⃣\",\n    \"seven\": \"7️⃣\",\n    \"eight\": \"8️⃣\",\n    \"nine\": \"9️⃣\",\n    \"couplekiss\": \"💏\",\n    \"kissing_cat\": \"😽\",\n    \"kissing\": \"😗\",\n    \"kissing_closed_eyes\": \"😚\",\n    \"kissing_smiling_eyes\": \"😙\",\n    \"beetle\": \"🐞\",\n    \"large_blue_circle\": \"🔵\",\n    \"last_quarter_moon_with_face\": \"🌜\",\n    \"leaves\": \"🍃\",\n    \"mag\": \"🔍\",\n    \"left_right_arrow\": \"↔\",\n    \"leftwards_arrow_with_hook\": \"↩\",\n    \"arrow_left\": \"⬅\",\n    \"lock\": \"🔒\",\n    \"lock_with_ink_pen\": \"🔏\",\n    \"sob\": \"😭\",\n    \"low_brightness\": \"🔅\",\n    \"lower_left_ballpoint_pen\": \"🖊\",\n    \"lower_left_crayon\": \"🖍\",\n    \"lower_left_fountain_pen\": \"🖋\",\n    \"lower_left_paintbrush\": \"🖌\",\n    \"mahjong\": \"🀄\",\n    \"couple\": \"👫\",\n    \"man_in_business_suit_levitating\": \"🕴\",\n    \"man_with_gua_pi_mao\": \"👲\",\n    \"man_with_turban\": \"👳\",\n    \"mans_shoe\": \"👞\",\n    \"shoe\": \"👞\",\n    \"menorah_with_nine_branches\": \"🕎\",\n    \"mens\": \"🚹\",\n    \"minidisc\": \"💽\",\n    \"iphone\": \"📱\",\n    \"calling\": \"📲\",\n    \"money__mouth_face\": \"🤑\",\n    \"moneybag\": \"💰\",\n    \"rice_scene\": \"🎑\",\n    \"mountain_bicyclist\": \"🚵\",\n    \"mouse2\": \"🐁\",\n    \"lips\": \"👄\",\n    \"moyai\": \"🗿\",\n    \"notes\": \"🎶\",\n    \"nail_care\": \"💅\",\n    \"ab\": \"🆎\",\n    \"negative_squared_cross_mark\": \"❎\",\n    \"a\": \"🅰\",\n    \"b\": \"🅱\",\n    \"o2\": \"🅾\",\n    \"parking\": \"🅿\",\n    \"new_moon_with_face\": \"🌚\",\n    \"no_entry_sign\": \"🚫\",\n    \"underage\": \"🔞\",\n    \"non__potable_water\": \"🚱\",\n    \"arrow_upper_right\": \"↗\",\n    \"arrow_upper_left\": \"↖\",\n    \"office\": \"🏢\",\n    \"older_man\": \"👴\",\n    \"older_woman\": \"👵\",\n    \"om_symbol\": \"🕉\",\n    \"on\": \"🔛\",\n    \"book\": \"📖\",\n    \"unlock\": \"🔓\",\n    \"mailbox_with_no_mail\": \"📭\",\n    \"mailbox_with_mail\": \"📬\",\n    \"cd\": \"💿\",\n    \"tada\": \"🎉\",\n    \"feet\": \"🐾\",\n    \"walking\": \"🚶\",\n    \"pencil2\": \"✏\",\n    \"pensive\": \"😔\",\n    \"persevere\": \"😣\",\n    \"bow\": \"🙇\",\n    \"raised_hands\": \"🙌\",\n    \"person_with_ball\": \"⛹\",\n    \"person_with_blond_hair\": \"👱\",\n    \"pray\": \"🙏\",\n    \"person_with_pouting_face\": \"🙎\",\n    \"computer\": \"💻\",\n    \"pig2\": \"🐖\",\n    \"hankey\": \"💩\",\n    \"poop\": \"💩\",\n    \"shit\": \"💩\",\n    \"bamboo\": \"🎍\",\n    \"gun\": \"🔫\",\n    \"black_joker\": \"🃏\",\n    \"rotating_light\": \"🚨\",\n    \"cop\": \"👮\",\n    \"stew\": \"🍲\",\n    \"pouch\": \"👝\",\n    \"pouting_cat\": \"😾\",\n    \"rage\": \"😡\",\n    \"put_litter_in_its_place\": \"🚮\",\n    \"rabbit2\": \"🐇\",\n    \"racing_motorcycle\": \"🏍\",\n    \"radioactive_sign\": \"☢\",\n    \"fist\": \"✊\",\n    \"hand\": \"✋\",\n    \"raised_hand_with_fingers_splayed\": \"🖐\",\n    \"raised_hand_with_part_between_middle_and_ring_fingers\": \"🖖\",\n    \"blue_car\": \"🚙\",\n    \"apple\": \"🍎\",\n    \"relieved\": \"😌\",\n    \"reversed_hand_with_middle_finger_extended\": \"🖕\",\n    \"mag_right\": \"🔎\",\n    \"arrow_right_hook\": \"↪\",\n    \"sweet_potato\": \"🍠\",\n    \"robot\": \"🤖\",\n    \"rolled__up_newspaper\": \"🗞\",\n    \"rowboat\": \"🚣\",\n    \"runner\": \"🏃\",\n    \"running\": \"🏃\",\n    \"running_shirt_with_sash\": \"🎽\",\n    \"boat\": \"⛵\",\n    \"scales\": \"⚖\",\n    \"school_satchel\": \"🎒\",\n    \"scorpius\": \"♏\",\n    \"see_no_evil\": \"🙈\",\n    \"sheep\": \"🐑\",\n    \"stars\": \"🌠\",\n    \"cake\": \"🍰\",\n    \"six_pointed_star\": \"🔯\",\n    \"ski\": \"🎿\",\n    \"sleeping_accommodation\": \"🛌\",\n    \"sleeping\": \"😴\",\n    \"sleepy\": \"😪\",\n    \"sleuth_or_spy\": \"🕵\",\n    \"heart_eyes_cat\": \"😻\",\n    \"smiley_cat\": \"😺\",\n    \"innocent\": \"😇\",\n    \"heart_eyes\": \"😍\",\n    \"smiling_imp\": \"😈\",\n    \"smiley\": \"😃\",\n    \"sweat_smile\": \"😅\",\n    \"smile\": \"😄\",\n    \"laughing\": \"😆\",\n    \"satisfied\": \"😆\",\n    \"blush\": \"😊\",\n    \"smirk\": \"😏\",\n    \"smoking\": \"🚬\",\n    \"snow_capped_mountain\": \"🏔\",\n    \"soccer\": \"⚽\",\n    \"icecream\": \"🍦\",\n    \"soon\": \"🔜\",\n    \"arrow_lower_right\": \"↘\",\n    \"arrow_lower_left\": \"↙\",\n    \"speak_no_evil\": \"🙊\",\n    \"speaker\": \"🔈\",\n    \"mute\": \"🔇\",\n    \"sound\": \"🔉\",\n    \"loud_sound\": \"🔊\",\n    \"speaking_head_in_silhouette\": \"🗣\",\n    \"spiral_calendar_pad\": \"🗓\",\n    \"spiral_note_pad\": \"🗒\",\n    \"shell\": \"🐚\",\n    \"sweat_drops\": \"💦\",\n    \"u5272\": \"🈹\",\n    \"u5408\": \"🈴\",\n    \"u55b6\": \"🈺\",\n    \"u6307\": \"🈯\",\n    \"u6708\": \"🈷\",\n    \"u6709\": \"🈶\",\n    \"u6e80\": \"🈵\",\n    \"u7121\": \"🈚\",\n    \"u7533\": \"🈸\",\n    \"u7981\": \"🈲\",\n    \"u7a7a\": \"🈳\",\n    \"cl\": \"🆑\",\n    \"cool\": \"🆒\",\n    \"free\": \"🆓\",\n    \"id\": \"🆔\",\n    \"koko\": \"🈁\",\n    \"sa\": \"🈂\",\n    \"new\": \"🆕\",\n    \"ng\": \"🆖\",\n    \"ok\": \"🆗\",\n    \"sos\": \"🆘\",\n    \"up\": \"🆙\",\n    \"vs\": \"🆚\",\n    \"steam_locomotive\": \"🚂\",\n    \"ramen\": \"🍜\",\n    \"partly_sunny\": \"⛅\",\n    \"city_sunrise\": \"🌇\",\n    \"surfer\": \"🏄\",\n    \"swimmer\": \"🏊\",\n    \"shirt\": \"👕\",\n    \"tshirt\": \"👕\",\n    \"table_tennis_paddle_and_ball\": \"🏓\",\n    \"tea\": \"🍵\",\n    \"tv\": \"📺\",\n    \"three_button_mouse\": \"🖱\",\n    \"+1\": \"👍\",\n    \"thumbsup\": \"👍\",\n    \"__1\": \"👎\",\n    \"-1\": \"👎\",\n    \"thumbsdown\": \"👎\",\n    \"thunder_cloud_and_rain\": \"⛈\",\n    \"tiger2\": \"🐅\",\n    \"tophat\": \"🎩\",\n    \"top\": \"🔝\",\n    \"tm\": \"™\",\n    \"train2\": \"🚆\",\n    \"triangular_flag_on_post\": \"🚩\",\n    \"trident\": \"🔱\",\n    \"twisted_rightwards_arrows\": \"🔀\",\n    \"unamused\": \"😒\",\n    \"small_red_triangle\": \"🔺\",\n    \"arrow_up_small\": \"🔼\",\n    \"arrow_up_down\": \"↕\",\n    \"upside__down_face\": \"🙃\",\n    \"arrow_up\": \"⬆\",\n    \"v\": \"✌\",\n    \"vhs\": \"📼\",\n    \"wc\": \"🚾\",\n    \"ocean\": \"🌊\",\n    \"waving_black_flag\": \"🏴\",\n    \"wave\": \"👋\",\n    \"waving_white_flag\": \"🏳\",\n    \"moon\": \"🌔\",\n    \"scream_cat\": \"🙀\",\n    \"weary\": \"😩\",\n    \"weight_lifter\": \"🏋\",\n    \"whale2\": \"🐋\",\n    \"wheelchair\": \"♿\",\n    \"point_down\": \"👇\",\n    \"grey_exclamation\": \"❕\",\n    \"white_frowning_face\": \"☹\",\n    \"white_check_mark\": \"✅\",\n    \"point_left\": \"👈\",\n    \"white_medium_small_square\": \"◽\",\n    \"star\": \"⭐\",\n    \"grey_question\": \"❔\",\n    \"point_right\": \"👉\",\n    \"relaxed\": \"☺\",\n    \"white_sun_behind_cloud\": \"🌥\",\n    \"white_sun_behind_cloud_with_rain\": \"🌦\",\n    \"white_sun_with_small_cloud\": \"🌤\",\n    \"point_up_2\": \"👆\",\n    \"point_up\": \"☝\",\n    \"wind_blowing_face\": \"🌬\",\n    \"wink\": \"😉\",\n    \"wolf\": \"🐺\",\n    \"dancers\": \"👯\",\n    \"boot\": \"👢\",\n    \"womans_clothes\": \"👚\",\n    \"womans_hat\": \"👒\",\n    \"sandal\": \"👡\",\n    \"womens\": \"🚺\",\n    \"worried\": \"😟\",\n    \"gift\": \"🎁\",\n    \"zipper__mouth_face\": \"🤐\",\n    \"regional_indicator_a\": \"🇦\",\n    \"regional_indicator_b\": \"🇧\",\n    \"regional_indicator_c\": \"🇨\",\n    \"regional_indicator_d\": \"🇩\",\n    \"regional_indicator_e\": \"🇪\",\n    \"regional_indicator_f\": \"🇫\",\n    \"regional_indicator_g\": \"🇬\",\n    \"regional_indicator_h\": \"🇭\",\n    \"regional_indicator_i\": \"🇮\",\n    \"regional_indicator_j\": \"🇯\",\n    \"regional_indicator_k\": \"🇰\",\n    \"regional_indicator_l\": \"🇱\",\n    \"regional_indicator_m\": \"🇲\",\n    \"regional_indicator_n\": \"🇳\",\n    \"regional_indicator_o\": \"🇴\",\n    \"regional_indicator_p\": \"🇵\",\n    \"regional_indicator_q\": \"🇶\",\n    \"regional_indicator_r\": \"🇷\",\n    \"regional_indicator_s\": \"🇸\",\n    \"regional_indicator_t\": \"🇹\",\n    \"regional_indicator_u\": \"🇺\",\n    \"regional_indicator_v\": \"🇻\",\n    \"regional_indicator_w\": \"🇼\",\n    \"regional_indicator_x\": \"🇽\",\n    \"regional_indicator_y\": \"🇾\",\n    \"regional_indicator_z\": \"🇿\",\n}\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_emoji_replace.py",
    "content": "from typing import Callable, Match, Optional\nimport re\n\nfrom ._emoji_codes import EMOJI\n\n\n_ReStringMatch = Match[str]  # regex match object\n_ReSubCallable = Callable[[_ReStringMatch], str]  # Callable invoked by re.sub\n_EmojiSubMethod = Callable[[_ReSubCallable, str], str]  # Sub method of a compiled re\n\n\ndef _emoji_replace(\n    text: str,\n    default_variant: Optional[str] = None,\n    _emoji_sub: _EmojiSubMethod = re.compile(r\"(:(\\S*?)(?:(?:\\-)(emoji|text))?:)\").sub,\n) -> str:\n    \"\"\"Replace emoji code in text.\"\"\"\n    get_emoji = EMOJI.__getitem__\n    variants = {\"text\": \"\\uFE0E\", \"emoji\": \"\\uFE0F\"}\n    get_variant = variants.get\n    default_variant_code = variants.get(default_variant, \"\") if default_variant else \"\"\n\n    def do_replace(match: Match[str]) -> str:\n        emoji_code, emoji_name, variant = match.groups()\n        try:\n            return get_emoji(emoji_name.lower()) + get_variant(\n                variant, default_variant_code\n            )\n        except KeyError:\n            return emoji_code\n\n    return _emoji_sub(do_replace, text)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_export_format.py",
    "content": "CONSOLE_HTML_FORMAT = \"\"\"\\\n<!DOCTYPE html>\n<head>\n<meta charset=\"UTF-8\">\n<style>\n{stylesheet}\nbody {{\n    color: {foreground};\n    background-color: {background};\n}}\n</style>\n</head>\n<html>\n<body>\n    <code>\n        <pre style=\"font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">{code}</pre>\n    </code>\n</body>\n</html>\n\"\"\"\n\nCONSOLE_SVG_FORMAT = \"\"\"\\\n<svg class=\"rich-terminal\" viewBox=\"0 0 {width} {height}\" xmlns=\"http://www.w3.org/2000/svg\">\n    <!-- Generated with Rich https://www.textualize.io -->\n    <style>\n\n    @font-face {{\n        font-family: \"Fira Code\";\n        src: local(\"FiraCode-Regular\"),\n                url(\"https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2\") format(\"woff2\"),\n                url(\"https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff\") format(\"woff\");\n        font-style: normal;\n        font-weight: 400;\n    }}\n    @font-face {{\n        font-family: \"Fira Code\";\n        src: local(\"FiraCode-Bold\"),\n                url(\"https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2\") format(\"woff2\"),\n                url(\"https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff\") format(\"woff\");\n        font-style: bold;\n        font-weight: 700;\n    }}\n\n    .{unique_id}-matrix {{\n        font-family: Fira Code, monospace;\n        font-size: {char_height}px;\n        line-height: {line_height}px;\n        font-variant-east-asian: full-width;\n    }}\n\n    .{unique_id}-title {{\n        font-size: 18px;\n        font-weight: bold;\n        font-family: arial;\n    }}\n\n    {styles}\n    </style>\n\n    <defs>\n    <clipPath id=\"{unique_id}-clip-terminal\">\n      <rect x=\"0\" y=\"0\" width=\"{terminal_width}\" height=\"{terminal_height}\" />\n    </clipPath>\n    {lines}\n    </defs>\n\n    {chrome}\n    <g transform=\"translate({terminal_x}, {terminal_y})\" clip-path=\"url(#{unique_id}-clip-terminal)\">\n    {backgrounds}\n    <g class=\"{unique_id}-matrix\">\n    {matrix}\n    </g>\n    </g>\n</svg>\n\"\"\"\n\n_SVG_FONT_FAMILY = \"Rich Fira Code\"\n_SVG_CLASSES_PREFIX = \"rich-svg\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_extension.py",
    "content": "from typing import Any\n\n\ndef load_ipython_extension(ip: Any) -> None:  # pragma: no cover\n    # prevent circular import\n    from pip._vendor.rich.pretty import install\n    from pip._vendor.rich.traceback import install as tr_install\n\n    install()\n    tr_install()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_inspect.py",
    "content": "from __future__ import absolute_import\n\nimport inspect\nfrom inspect import cleandoc, getdoc, getfile, isclass, ismodule, signature\nfrom typing import Any, Collection, Iterable, Optional, Tuple, Type, Union\n\nfrom .console import Group, RenderableType\nfrom .control import escape_control_codes\nfrom .highlighter import ReprHighlighter\nfrom .jupyter import JupyterMixin\nfrom .panel import Panel\nfrom .pretty import Pretty\nfrom .table import Table\nfrom .text import Text, TextType\n\n\ndef _first_paragraph(doc: str) -> str:\n    \"\"\"Get the first paragraph from a docstring.\"\"\"\n    paragraph, _, _ = doc.partition(\"\\n\\n\")\n    return paragraph\n\n\nclass Inspect(JupyterMixin):\n    \"\"\"A renderable to inspect any Python Object.\n\n    Args:\n        obj (Any): An object to inspect.\n        title (str, optional): Title to display over inspect result, or None use type. Defaults to None.\n        help (bool, optional): Show full help text rather than just first paragraph. Defaults to False.\n        methods (bool, optional): Enable inspection of callables. Defaults to False.\n        docs (bool, optional): Also render doc strings. Defaults to True.\n        private (bool, optional): Show private attributes (beginning with underscore). Defaults to False.\n        dunder (bool, optional): Show attributes starting with double underscore. Defaults to False.\n        sort (bool, optional): Sort attributes alphabetically. Defaults to True.\n        all (bool, optional): Show all attributes. Defaults to False.\n        value (bool, optional): Pretty print value of object. Defaults to True.\n    \"\"\"\n\n    def __init__(\n        self,\n        obj: Any,\n        *,\n        title: Optional[TextType] = None,\n        help: bool = False,\n        methods: bool = False,\n        docs: bool = True,\n        private: bool = False,\n        dunder: bool = False,\n        sort: bool = True,\n        all: bool = True,\n        value: bool = True,\n    ) -> None:\n        self.highlighter = ReprHighlighter()\n        self.obj = obj\n        self.title = title or self._make_title(obj)\n        if all:\n            methods = private = dunder = True\n        self.help = help\n        self.methods = methods\n        self.docs = docs or help\n        self.private = private or dunder\n        self.dunder = dunder\n        self.sort = sort\n        self.value = value\n\n    def _make_title(self, obj: Any) -> Text:\n        \"\"\"Make a default title.\"\"\"\n        title_str = (\n            str(obj)\n            if (isclass(obj) or callable(obj) or ismodule(obj))\n            else str(type(obj))\n        )\n        title_text = self.highlighter(title_str)\n        return title_text\n\n    def __rich__(self) -> Panel:\n        return Panel.fit(\n            Group(*self._render()),\n            title=self.title,\n            border_style=\"scope.border\",\n            padding=(0, 1),\n        )\n\n    def _get_signature(self, name: str, obj: Any) -> Optional[Text]:\n        \"\"\"Get a signature for a callable.\"\"\"\n        try:\n            _signature = str(signature(obj)) + \":\"\n        except ValueError:\n            _signature = \"(...)\"\n        except TypeError:\n            return None\n\n        source_filename: Optional[str] = None\n        try:\n            source_filename = getfile(obj)\n        except (OSError, TypeError):\n            # OSError is raised if obj has no source file, e.g. when defined in REPL.\n            pass\n\n        callable_name = Text(name, style=\"inspect.callable\")\n        if source_filename:\n            callable_name.stylize(f\"link file://{source_filename}\")\n        signature_text = self.highlighter(_signature)\n\n        qualname = name or getattr(obj, \"__qualname__\", name)\n\n        # If obj is a module, there may be classes (which are callable) to display\n        if inspect.isclass(obj):\n            prefix = \"class\"\n        elif inspect.iscoroutinefunction(obj):\n            prefix = \"async def\"\n        else:\n            prefix = \"def\"\n\n        qual_signature = Text.assemble(\n            (f\"{prefix} \", f\"inspect.{prefix.replace(' ', '_')}\"),\n            (qualname, \"inspect.callable\"),\n            signature_text,\n        )\n\n        return qual_signature\n\n    def _render(self) -> Iterable[RenderableType]:\n        \"\"\"Render object.\"\"\"\n\n        def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]:\n            key, (_error, value) = item\n            return (callable(value), key.strip(\"_\").lower())\n\n        def safe_getattr(attr_name: str) -> Tuple[Any, Any]:\n            \"\"\"Get attribute or any exception.\"\"\"\n            try:\n                return (None, getattr(obj, attr_name))\n            except Exception as error:\n                return (error, None)\n\n        obj = self.obj\n        keys = dir(obj)\n        total_items = len(keys)\n        if not self.dunder:\n            keys = [key for key in keys if not key.startswith(\"__\")]\n        if not self.private:\n            keys = [key for key in keys if not key.startswith(\"_\")]\n        not_shown_count = total_items - len(keys)\n        items = [(key, safe_getattr(key)) for key in keys]\n        if self.sort:\n            items.sort(key=sort_items)\n\n        items_table = Table.grid(padding=(0, 1), expand=False)\n        items_table.add_column(justify=\"right\")\n        add_row = items_table.add_row\n        highlighter = self.highlighter\n\n        if callable(obj):\n            signature = self._get_signature(\"\", obj)\n            if signature is not None:\n                yield signature\n                yield \"\"\n\n        if self.docs:\n            _doc = self._get_formatted_doc(obj)\n            if _doc is not None:\n                doc_text = Text(_doc, style=\"inspect.help\")\n                doc_text = highlighter(doc_text)\n                yield doc_text\n                yield \"\"\n\n        if self.value and not (isclass(obj) or callable(obj) or ismodule(obj)):\n            yield Panel(\n                Pretty(obj, indent_guides=True, max_length=10, max_string=60),\n                border_style=\"inspect.value.border\",\n            )\n            yield \"\"\n\n        for key, (error, value) in items:\n            key_text = Text.assemble(\n                (\n                    key,\n                    \"inspect.attr.dunder\" if key.startswith(\"__\") else \"inspect.attr\",\n                ),\n                (\" =\", \"inspect.equals\"),\n            )\n            if error is not None:\n                warning = key_text.copy()\n                warning.stylize(\"inspect.error\")\n                add_row(warning, highlighter(repr(error)))\n                continue\n\n            if callable(value):\n                if not self.methods:\n                    continue\n\n                _signature_text = self._get_signature(key, value)\n                if _signature_text is None:\n                    add_row(key_text, Pretty(value, highlighter=highlighter))\n                else:\n                    if self.docs:\n                        docs = self._get_formatted_doc(value)\n                        if docs is not None:\n                            _signature_text.append(\"\\n\" if \"\\n\" in docs else \" \")\n                            doc = highlighter(docs)\n                            doc.stylize(\"inspect.doc\")\n                            _signature_text.append(doc)\n\n                    add_row(key_text, _signature_text)\n            else:\n                add_row(key_text, Pretty(value, highlighter=highlighter))\n        if items_table.row_count:\n            yield items_table\n        elif not_shown_count:\n            yield Text.from_markup(\n                f\"[b cyan]{not_shown_count}[/][i] attribute(s) not shown.[/i] \"\n                f\"Run [b][magenta]inspect[/]([not b]inspect[/])[/b] for options.\"\n            )\n\n    def _get_formatted_doc(self, object_: Any) -> Optional[str]:\n        \"\"\"\n        Extract the docstring of an object, process it and returns it.\n        The processing consists in cleaning up the doctring's indentation,\n        taking only its 1st paragraph if `self.help` is not True,\n        and escape its control codes.\n\n        Args:\n            object_ (Any): the object to get the docstring from.\n\n        Returns:\n            Optional[str]: the processed docstring, or None if no docstring was found.\n        \"\"\"\n        docs = getdoc(object_)\n        if docs is None:\n            return None\n        docs = cleandoc(docs).strip()\n        if not self.help:\n            docs = _first_paragraph(docs)\n        return escape_control_codes(docs)\n\n\ndef get_object_types_mro(obj: Union[object, Type[Any]]) -> Tuple[type, ...]:\n    \"\"\"Returns the MRO of an object's class, or of the object itself if it's a class.\"\"\"\n    if not hasattr(obj, \"__mro__\"):\n        # N.B. we cannot use `if type(obj) is type` here because it doesn't work with\n        # some types of classes, such as the ones that use abc.ABCMeta.\n        obj = type(obj)\n    return getattr(obj, \"__mro__\", ())\n\n\ndef get_object_types_mro_as_strings(obj: object) -> Collection[str]:\n    \"\"\"\n    Returns the MRO of an object's class as full qualified names, or of the object itself if it's a class.\n\n    Examples:\n        `object_types_mro_as_strings(JSONDecoder)` will return `['json.decoder.JSONDecoder', 'builtins.object']`\n    \"\"\"\n    return [\n        f'{getattr(type_, \"__module__\", \"\")}.{getattr(type_, \"__qualname__\", \"\")}'\n        for type_ in get_object_types_mro(obj)\n    ]\n\n\ndef is_object_one_of_types(\n    obj: object, fully_qualified_types_names: Collection[str]\n) -> bool:\n    \"\"\"\n    Returns `True` if the given object's class (or the object itself, if it's a class) has one of the\n    fully qualified names in its MRO.\n    \"\"\"\n    for type_name in get_object_types_mro_as_strings(obj):\n        if type_name in fully_qualified_types_names:\n            return True\n    return False\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_log_render.py",
    "content": "from datetime import datetime\nfrom typing import Iterable, List, Optional, TYPE_CHECKING, Union, Callable\n\n\nfrom .text import Text, TextType\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleRenderable, RenderableType\n    from .table import Table\n\nFormatTimeCallable = Callable[[datetime], Text]\n\n\nclass LogRender:\n    def __init__(\n        self,\n        show_time: bool = True,\n        show_level: bool = False,\n        show_path: bool = True,\n        time_format: Union[str, FormatTimeCallable] = \"[%x %X]\",\n        omit_repeated_times: bool = True,\n        level_width: Optional[int] = 8,\n    ) -> None:\n        self.show_time = show_time\n        self.show_level = show_level\n        self.show_path = show_path\n        self.time_format = time_format\n        self.omit_repeated_times = omit_repeated_times\n        self.level_width = level_width\n        self._last_time: Optional[Text] = None\n\n    def __call__(\n        self,\n        console: \"Console\",\n        renderables: Iterable[\"ConsoleRenderable\"],\n        log_time: Optional[datetime] = None,\n        time_format: Optional[Union[str, FormatTimeCallable]] = None,\n        level: TextType = \"\",\n        path: Optional[str] = None,\n        line_no: Optional[int] = None,\n        link_path: Optional[str] = None,\n    ) -> \"Table\":\n        from .containers import Renderables\n        from .table import Table\n\n        output = Table.grid(padding=(0, 1))\n        output.expand = True\n        if self.show_time:\n            output.add_column(style=\"log.time\")\n        if self.show_level:\n            output.add_column(style=\"log.level\", width=self.level_width)\n        output.add_column(ratio=1, style=\"log.message\", overflow=\"fold\")\n        if self.show_path and path:\n            output.add_column(style=\"log.path\")\n        row: List[\"RenderableType\"] = []\n        if self.show_time:\n            log_time = log_time or console.get_datetime()\n            time_format = time_format or self.time_format\n            if callable(time_format):\n                log_time_display = time_format(log_time)\n            else:\n                log_time_display = Text(log_time.strftime(time_format))\n            if log_time_display == self._last_time and self.omit_repeated_times:\n                row.append(Text(\" \" * len(log_time_display)))\n            else:\n                row.append(log_time_display)\n                self._last_time = log_time_display\n        if self.show_level:\n            row.append(level)\n\n        row.append(Renderables(renderables))\n        if self.show_path and path:\n            path_text = Text()\n            path_text.append(\n                path, style=f\"link file://{link_path}\" if link_path else \"\"\n            )\n            if line_no:\n                path_text.append(\":\")\n                path_text.append(\n                    f\"{line_no}\",\n                    style=f\"link file://{link_path}#{line_no}\" if link_path else \"\",\n                )\n            row.append(path_text)\n\n        output.add_row(*row)\n        return output\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.console import Console\n\n    c = Console()\n    c.print(\"[on blue]Hello\", justify=\"right\")\n    c.log(\"[on blue]hello\", justify=\"right\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_loop.py",
    "content": "from typing import Iterable, Tuple, TypeVar\n\nT = TypeVar(\"T\")\n\n\ndef loop_first(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:\n    \"\"\"Iterate and generate a tuple with a flag for first value.\"\"\"\n    iter_values = iter(values)\n    try:\n        value = next(iter_values)\n    except StopIteration:\n        return\n    yield True, value\n    for value in iter_values:\n        yield False, value\n\n\ndef loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:\n    \"\"\"Iterate and generate a tuple with a flag for last value.\"\"\"\n    iter_values = iter(values)\n    try:\n        previous_value = next(iter_values)\n    except StopIteration:\n        return\n    for value in iter_values:\n        yield False, previous_value\n        previous_value = value\n    yield True, previous_value\n\n\ndef loop_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:\n    \"\"\"Iterate and generate a tuple with a flag for first and last value.\"\"\"\n    iter_values = iter(values)\n    try:\n        previous_value = next(iter_values)\n    except StopIteration:\n        return\n    first = True\n    for value in iter_values:\n        yield first, False, previous_value\n        first = False\n        previous_value = value\n    yield first, True, previous_value\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_palettes.py",
    "content": "from .palette import Palette\n\n\n# Taken from https://en.wikipedia.org/wiki/ANSI_escape_code (Windows 10 column)\nWINDOWS_PALETTE = Palette(\n    [\n        (12, 12, 12),\n        (197, 15, 31),\n        (19, 161, 14),\n        (193, 156, 0),\n        (0, 55, 218),\n        (136, 23, 152),\n        (58, 150, 221),\n        (204, 204, 204),\n        (118, 118, 118),\n        (231, 72, 86),\n        (22, 198, 12),\n        (249, 241, 165),\n        (59, 120, 255),\n        (180, 0, 158),\n        (97, 214, 214),\n        (242, 242, 242),\n    ]\n)\n\n# # The standard ansi colors (including bright variants)\nSTANDARD_PALETTE = Palette(\n    [\n        (0, 0, 0),\n        (170, 0, 0),\n        (0, 170, 0),\n        (170, 85, 0),\n        (0, 0, 170),\n        (170, 0, 170),\n        (0, 170, 170),\n        (170, 170, 170),\n        (85, 85, 85),\n        (255, 85, 85),\n        (85, 255, 85),\n        (255, 255, 85),\n        (85, 85, 255),\n        (255, 85, 255),\n        (85, 255, 255),\n        (255, 255, 255),\n    ]\n)\n\n\n# The 256 color palette\nEIGHT_BIT_PALETTE = Palette(\n    [\n        (0, 0, 0),\n        (128, 0, 0),\n        (0, 128, 0),\n        (128, 128, 0),\n        (0, 0, 128),\n        (128, 0, 128),\n        (0, 128, 128),\n        (192, 192, 192),\n        (128, 128, 128),\n        (255, 0, 0),\n        (0, 255, 0),\n        (255, 255, 0),\n        (0, 0, 255),\n        (255, 0, 255),\n        (0, 255, 255),\n        (255, 255, 255),\n        (0, 0, 0),\n        (0, 0, 95),\n        (0, 0, 135),\n        (0, 0, 175),\n        (0, 0, 215),\n        (0, 0, 255),\n        (0, 95, 0),\n        (0, 95, 95),\n        (0, 95, 135),\n        (0, 95, 175),\n        (0, 95, 215),\n        (0, 95, 255),\n        (0, 135, 0),\n        (0, 135, 95),\n        (0, 135, 135),\n        (0, 135, 175),\n        (0, 135, 215),\n        (0, 135, 255),\n        (0, 175, 0),\n        (0, 175, 95),\n        (0, 175, 135),\n        (0, 175, 175),\n        (0, 175, 215),\n        (0, 175, 255),\n        (0, 215, 0),\n        (0, 215, 95),\n        (0, 215, 135),\n        (0, 215, 175),\n        (0, 215, 215),\n        (0, 215, 255),\n        (0, 255, 0),\n        (0, 255, 95),\n        (0, 255, 135),\n        (0, 255, 175),\n        (0, 255, 215),\n        (0, 255, 255),\n        (95, 0, 0),\n        (95, 0, 95),\n        (95, 0, 135),\n        (95, 0, 175),\n        (95, 0, 215),\n        (95, 0, 255),\n        (95, 95, 0),\n        (95, 95, 95),\n        (95, 95, 135),\n        (95, 95, 175),\n        (95, 95, 215),\n        (95, 95, 255),\n        (95, 135, 0),\n        (95, 135, 95),\n        (95, 135, 135),\n        (95, 135, 175),\n        (95, 135, 215),\n        (95, 135, 255),\n        (95, 175, 0),\n        (95, 175, 95),\n        (95, 175, 135),\n        (95, 175, 175),\n        (95, 175, 215),\n        (95, 175, 255),\n        (95, 215, 0),\n        (95, 215, 95),\n        (95, 215, 135),\n        (95, 215, 175),\n        (95, 215, 215),\n        (95, 215, 255),\n        (95, 255, 0),\n        (95, 255, 95),\n        (95, 255, 135),\n        (95, 255, 175),\n        (95, 255, 215),\n        (95, 255, 255),\n        (135, 0, 0),\n        (135, 0, 95),\n        (135, 0, 135),\n        (135, 0, 175),\n        (135, 0, 215),\n        (135, 0, 255),\n        (135, 95, 0),\n        (135, 95, 95),\n        (135, 95, 135),\n        (135, 95, 175),\n        (135, 95, 215),\n        (135, 95, 255),\n        (135, 135, 0),\n        (135, 135, 95),\n        (135, 135, 135),\n        (135, 135, 175),\n        (135, 135, 215),\n        (135, 135, 255),\n        (135, 175, 0),\n        (135, 175, 95),\n        (135, 175, 135),\n        (135, 175, 175),\n        (135, 175, 215),\n        (135, 175, 255),\n        (135, 215, 0),\n        (135, 215, 95),\n        (135, 215, 135),\n        (135, 215, 175),\n        (135, 215, 215),\n        (135, 215, 255),\n        (135, 255, 0),\n        (135, 255, 95),\n        (135, 255, 135),\n        (135, 255, 175),\n        (135, 255, 215),\n        (135, 255, 255),\n        (175, 0, 0),\n        (175, 0, 95),\n        (175, 0, 135),\n        (175, 0, 175),\n        (175, 0, 215),\n        (175, 0, 255),\n        (175, 95, 0),\n        (175, 95, 95),\n        (175, 95, 135),\n        (175, 95, 175),\n        (175, 95, 215),\n        (175, 95, 255),\n        (175, 135, 0),\n        (175, 135, 95),\n        (175, 135, 135),\n        (175, 135, 175),\n        (175, 135, 215),\n        (175, 135, 255),\n        (175, 175, 0),\n        (175, 175, 95),\n        (175, 175, 135),\n        (175, 175, 175),\n        (175, 175, 215),\n        (175, 175, 255),\n        (175, 215, 0),\n        (175, 215, 95),\n        (175, 215, 135),\n        (175, 215, 175),\n        (175, 215, 215),\n        (175, 215, 255),\n        (175, 255, 0),\n        (175, 255, 95),\n        (175, 255, 135),\n        (175, 255, 175),\n        (175, 255, 215),\n        (175, 255, 255),\n        (215, 0, 0),\n        (215, 0, 95),\n        (215, 0, 135),\n        (215, 0, 175),\n        (215, 0, 215),\n        (215, 0, 255),\n        (215, 95, 0),\n        (215, 95, 95),\n        (215, 95, 135),\n        (215, 95, 175),\n        (215, 95, 215),\n        (215, 95, 255),\n        (215, 135, 0),\n        (215, 135, 95),\n        (215, 135, 135),\n        (215, 135, 175),\n        (215, 135, 215),\n        (215, 135, 255),\n        (215, 175, 0),\n        (215, 175, 95),\n        (215, 175, 135),\n        (215, 175, 175),\n        (215, 175, 215),\n        (215, 175, 255),\n        (215, 215, 0),\n        (215, 215, 95),\n        (215, 215, 135),\n        (215, 215, 175),\n        (215, 215, 215),\n        (215, 215, 255),\n        (215, 255, 0),\n        (215, 255, 95),\n        (215, 255, 135),\n        (215, 255, 175),\n        (215, 255, 215),\n        (215, 255, 255),\n        (255, 0, 0),\n        (255, 0, 95),\n        (255, 0, 135),\n        (255, 0, 175),\n        (255, 0, 215),\n        (255, 0, 255),\n        (255, 95, 0),\n        (255, 95, 95),\n        (255, 95, 135),\n        (255, 95, 175),\n        (255, 95, 215),\n        (255, 95, 255),\n        (255, 135, 0),\n        (255, 135, 95),\n        (255, 135, 135),\n        (255, 135, 175),\n        (255, 135, 215),\n        (255, 135, 255),\n        (255, 175, 0),\n        (255, 175, 95),\n        (255, 175, 135),\n        (255, 175, 175),\n        (255, 175, 215),\n        (255, 175, 255),\n        (255, 215, 0),\n        (255, 215, 95),\n        (255, 215, 135),\n        (255, 215, 175),\n        (255, 215, 215),\n        (255, 215, 255),\n        (255, 255, 0),\n        (255, 255, 95),\n        (255, 255, 135),\n        (255, 255, 175),\n        (255, 255, 215),\n        (255, 255, 255),\n        (8, 8, 8),\n        (18, 18, 18),\n        (28, 28, 28),\n        (38, 38, 38),\n        (48, 48, 48),\n        (58, 58, 58),\n        (68, 68, 68),\n        (78, 78, 78),\n        (88, 88, 88),\n        (98, 98, 98),\n        (108, 108, 108),\n        (118, 118, 118),\n        (128, 128, 128),\n        (138, 138, 138),\n        (148, 148, 148),\n        (158, 158, 158),\n        (168, 168, 168),\n        (178, 178, 178),\n        (188, 188, 188),\n        (198, 198, 198),\n        (208, 208, 208),\n        (218, 218, 218),\n        (228, 228, 228),\n        (238, 238, 238),\n    ]\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_pick.py",
    "content": "from typing import Optional\n\n\ndef pick_bool(*values: Optional[bool]) -> bool:\n    \"\"\"Pick the first non-none bool or return the last value.\n\n    Args:\n        *values (bool): Any number of boolean or None values.\n\n    Returns:\n        bool: First non-none boolean.\n    \"\"\"\n    assert values, \"1 or more values required\"\n    for value in values:\n        if value is not None:\n            return value\n    return bool(value)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_ratio.py",
    "content": "import sys\nfrom fractions import Fraction\nfrom math import ceil\nfrom typing import cast, List, Optional, Sequence\n\nif sys.version_info >= (3, 8):\n    from typing import Protocol\nelse:\n    from pip._vendor.typing_extensions import Protocol  # pragma: no cover\n\n\nclass Edge(Protocol):\n    \"\"\"Any object that defines an edge (such as Layout).\"\"\"\n\n    size: Optional[int] = None\n    ratio: int = 1\n    minimum_size: int = 1\n\n\ndef ratio_resolve(total: int, edges: Sequence[Edge]) -> List[int]:\n    \"\"\"Divide total space to satisfy size, ratio, and minimum_size, constraints.\n\n    The returned list of integers should add up to total in most cases, unless it is\n    impossible to satisfy all the constraints. For instance, if there are two edges\n    with a minimum size of 20 each and `total` is 30 then the returned list will be\n    greater than total. In practice, this would mean that a Layout object would\n    clip the rows that would overflow the screen height.\n\n    Args:\n        total (int): Total number of characters.\n        edges (List[Edge]): Edges within total space.\n\n    Returns:\n        List[int]: Number of characters for each edge.\n    \"\"\"\n    # Size of edge or None for yet to be determined\n    sizes = [(edge.size or None) for edge in edges]\n\n    _Fraction = Fraction\n\n    # While any edges haven't been calculated\n    while None in sizes:\n        # Get flexible edges and index to map these back on to sizes list\n        flexible_edges = [\n            (index, edge)\n            for index, (size, edge) in enumerate(zip(sizes, edges))\n            if size is None\n        ]\n        # Remaining space in total\n        remaining = total - sum(size or 0 for size in sizes)\n        if remaining <= 0:\n            # No room for flexible edges\n            return [\n                ((edge.minimum_size or 1) if size is None else size)\n                for size, edge in zip(sizes, edges)\n            ]\n        # Calculate number of characters in a ratio portion\n        portion = _Fraction(\n            remaining, sum((edge.ratio or 1) for _, edge in flexible_edges)\n        )\n\n        # If any edges will be less than their minimum, replace size with the minimum\n        for index, edge in flexible_edges:\n            if portion * edge.ratio <= edge.minimum_size:\n                sizes[index] = edge.minimum_size\n                # New fixed size will invalidate calculations, so we need to repeat the process\n                break\n        else:\n            # Distribute flexible space and compensate for rounding error\n            # Since edge sizes can only be integers we need to add the remainder\n            # to the following line\n            remainder = _Fraction(0)\n            for index, edge in flexible_edges:\n                size, remainder = divmod(portion * edge.ratio + remainder, 1)\n                sizes[index] = size\n            break\n    # Sizes now contains integers only\n    return cast(List[int], sizes)\n\n\ndef ratio_reduce(\n    total: int, ratios: List[int], maximums: List[int], values: List[int]\n) -> List[int]:\n    \"\"\"Divide an integer total in to parts based on ratios.\n\n    Args:\n        total (int): The total to divide.\n        ratios (List[int]): A list of integer ratios.\n        maximums (List[int]): List of maximums values for each slot.\n        values (List[int]): List of values\n\n    Returns:\n        List[int]: A list of integers guaranteed to sum to total.\n    \"\"\"\n    ratios = [ratio if _max else 0 for ratio, _max in zip(ratios, maximums)]\n    total_ratio = sum(ratios)\n    if not total_ratio:\n        return values[:]\n    total_remaining = total\n    result: List[int] = []\n    append = result.append\n    for ratio, maximum, value in zip(ratios, maximums, values):\n        if ratio and total_ratio > 0:\n            distributed = min(maximum, round(ratio * total_remaining / total_ratio))\n            append(value - distributed)\n            total_remaining -= distributed\n            total_ratio -= ratio\n        else:\n            append(value)\n    return result\n\n\ndef ratio_distribute(\n    total: int, ratios: List[int], minimums: Optional[List[int]] = None\n) -> List[int]:\n    \"\"\"Distribute an integer total in to parts based on ratios.\n\n    Args:\n        total (int): The total to divide.\n        ratios (List[int]): A list of integer ratios.\n        minimums (List[int]): List of minimum values for each slot.\n\n    Returns:\n        List[int]: A list of integers guaranteed to sum to total.\n    \"\"\"\n    if minimums:\n        ratios = [ratio if _min else 0 for ratio, _min in zip(ratios, minimums)]\n    total_ratio = sum(ratios)\n    assert total_ratio > 0, \"Sum of ratios must be > 0\"\n\n    total_remaining = total\n    distributed_total: List[int] = []\n    append = distributed_total.append\n    if minimums is None:\n        _minimums = [0] * len(ratios)\n    else:\n        _minimums = minimums\n    for ratio, minimum in zip(ratios, _minimums):\n        if total_ratio > 0:\n            distributed = max(minimum, ceil(ratio * total_remaining / total_ratio))\n        else:\n            distributed = total_remaining\n        append(distributed)\n        total_ratio -= ratio\n        total_remaining -= distributed\n    return distributed_total\n\n\nif __name__ == \"__main__\":\n    from dataclasses import dataclass\n\n    @dataclass\n    class E:\n\n        size: Optional[int] = None\n        ratio: int = 1\n        minimum_size: int = 1\n\n    resolved = ratio_resolve(110, [E(None, 1, 1), E(None, 1, 1), E(None, 1, 1)])\n    print(sum(resolved))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_spinners.py",
    "content": "\"\"\"\nSpinners are from:\n* cli-spinners:\n    MIT License\n    Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)\n    Permission is hereby granted, free of charge, to any person obtaining a copy\n    of this software and associated documentation files (the \"Software\"), to deal\n    in the Software without restriction, including without limitation the rights to\n    use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n    the Software, and to permit persons to whom the Software is furnished to do so,\n    subject to the following conditions:\n    The above copyright notice and this permission notice shall be included\n    in all copies or substantial portions of the Software.\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n    INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR\n    PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE\n    FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n    ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n    IN THE SOFTWARE.\n\"\"\"\n\nSPINNERS = {\n    \"dots\": {\n        \"interval\": 80,\n        \"frames\": \"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏\",\n    },\n    \"dots2\": {\"interval\": 80, \"frames\": \"⣾⣽⣻⢿⡿⣟⣯⣷\"},\n    \"dots3\": {\n        \"interval\": 80,\n        \"frames\": \"⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓\",\n    },\n    \"dots4\": {\n        \"interval\": 80,\n        \"frames\": \"⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆\",\n    },\n    \"dots5\": {\n        \"interval\": 80,\n        \"frames\": \"⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋\",\n    },\n    \"dots6\": {\n        \"interval\": 80,\n        \"frames\": \"⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁\",\n    },\n    \"dots7\": {\n        \"interval\": 80,\n        \"frames\": \"⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈\",\n    },\n    \"dots8\": {\n        \"interval\": 80,\n        \"frames\": \"⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈\",\n    },\n    \"dots9\": {\"interval\": 80, \"frames\": \"⢹⢺⢼⣸⣇⡧⡗⡏\"},\n    \"dots10\": {\"interval\": 80, \"frames\": \"⢄⢂⢁⡁⡈⡐⡠\"},\n    \"dots11\": {\"interval\": 100, \"frames\": \"⠁⠂⠄⡀⢀⠠⠐⠈\"},\n    \"dots12\": {\n        \"interval\": 80,\n        \"frames\": [\n            \"⢀⠀\",\n            \"⡀⠀\",\n            \"⠄⠀\",\n            \"⢂⠀\",\n            \"⡂⠀\",\n            \"⠅⠀\",\n            \"⢃⠀\",\n            \"⡃⠀\",\n            \"⠍⠀\",\n            \"⢋⠀\",\n            \"⡋⠀\",\n            \"⠍⠁\",\n            \"⢋⠁\",\n            \"⡋⠁\",\n            \"⠍⠉\",\n            \"⠋⠉\",\n            \"⠋⠉\",\n            \"⠉⠙\",\n            \"⠉⠙\",\n            \"⠉⠩\",\n            \"⠈⢙\",\n            \"⠈⡙\",\n            \"⢈⠩\",\n            \"⡀⢙\",\n            \"⠄⡙\",\n            \"⢂⠩\",\n            \"⡂⢘\",\n            \"⠅⡘\",\n            \"⢃⠨\",\n            \"⡃⢐\",\n            \"⠍⡐\",\n            \"⢋⠠\",\n            \"⡋⢀\",\n            \"⠍⡁\",\n            \"⢋⠁\",\n            \"⡋⠁\",\n            \"⠍⠉\",\n            \"⠋⠉\",\n            \"⠋⠉\",\n            \"⠉⠙\",\n            \"⠉⠙\",\n            \"⠉⠩\",\n            \"⠈⢙\",\n            \"⠈⡙\",\n            \"⠈⠩\",\n            \"⠀⢙\",\n            \"⠀⡙\",\n            \"⠀⠩\",\n            \"⠀⢘\",\n            \"⠀⡘\",\n            \"⠀⠨\",\n            \"⠀⢐\",\n            \"⠀⡐\",\n            \"⠀⠠\",\n            \"⠀⢀\",\n            \"⠀⡀\",\n        ],\n    },\n    \"dots8Bit\": {\n        \"interval\": 80,\n        \"frames\": \"⠀⠁⠂⠃⠄⠅⠆⠇⡀⡁⡂⡃⡄⡅⡆⡇⠈⠉⠊⠋⠌⠍⠎⠏⡈⡉⡊⡋⡌⡍⡎⡏⠐⠑⠒⠓⠔⠕⠖⠗⡐⡑⡒⡓⡔⡕⡖⡗⠘⠙⠚⠛⠜⠝⠞⠟⡘⡙\"\n        \"⡚⡛⡜⡝⡞⡟⠠⠡⠢⠣⠤⠥⠦⠧⡠⡡⡢⡣⡤⡥⡦⡧⠨⠩⠪⠫⠬⠭⠮⠯⡨⡩⡪⡫⡬⡭⡮⡯⠰⠱⠲⠳⠴⠵⠶⠷⡰⡱⡲⡳⡴⡵⡶⡷⠸⠹⠺⠻\"\n        \"⠼⠽⠾⠿⡸⡹⡺⡻⡼⡽⡾⡿⢀⢁⢂⢃⢄⢅⢆⢇⣀⣁⣂⣃⣄⣅⣆⣇⢈⢉⢊⢋⢌⢍⢎⢏⣈⣉⣊⣋⣌⣍⣎⣏⢐⢑⢒⢓⢔⢕⢖⢗⣐⣑⣒⣓⣔⣕\"\n        \"⣖⣗⢘⢙⢚⢛⢜⢝⢞⢟⣘⣙⣚⣛⣜⣝⣞⣟⢠⢡⢢⢣⢤⢥⢦⢧⣠⣡⣢⣣⣤⣥⣦⣧⢨⢩⢪⢫⢬⢭⢮⢯⣨⣩⣪⣫⣬⣭⣮⣯⢰⢱⢲⢳⢴⢵⢶⢷\"\n        \"⣰⣱⣲⣳⣴⣵⣶⣷⢸⢹⢺⢻⢼⢽⢾⢿⣸⣹⣺⣻⣼⣽⣾⣿\",\n    },\n    \"line\": {\"interval\": 130, \"frames\": [\"-\", \"\\\\\", \"|\", \"/\"]},\n    \"line2\": {\"interval\": 100, \"frames\": \"⠂-–—–-\"},\n    \"pipe\": {\"interval\": 100, \"frames\": \"┤┘┴└├┌┬┐\"},\n    \"simpleDots\": {\"interval\": 400, \"frames\": [\".  \", \".. \", \"...\", \"   \"]},\n    \"simpleDotsScrolling\": {\n        \"interval\": 200,\n        \"frames\": [\".  \", \".. \", \"...\", \" ..\", \"  .\", \"   \"],\n    },\n    \"star\": {\"interval\": 70, \"frames\": \"✶✸✹✺✹✷\"},\n    \"star2\": {\"interval\": 80, \"frames\": \"+x*\"},\n    \"flip\": {\n        \"interval\": 70,\n        \"frames\": \"___-``'´-___\",\n    },\n    \"hamburger\": {\"interval\": 100, \"frames\": \"☱☲☴\"},\n    \"growVertical\": {\n        \"interval\": 120,\n        \"frames\": \"▁▃▄▅▆▇▆▅▄▃\",\n    },\n    \"growHorizontal\": {\n        \"interval\": 120,\n        \"frames\": \"▏▎▍▌▋▊▉▊▋▌▍▎\",\n    },\n    \"balloon\": {\"interval\": 140, \"frames\": \" .oO@* \"},\n    \"balloon2\": {\"interval\": 120, \"frames\": \".oO°Oo.\"},\n    \"noise\": {\"interval\": 100, \"frames\": \"▓▒░\"},\n    \"bounce\": {\"interval\": 120, \"frames\": \"⠁⠂⠄⠂\"},\n    \"boxBounce\": {\"interval\": 120, \"frames\": \"▖▘▝▗\"},\n    \"boxBounce2\": {\"interval\": 100, \"frames\": \"▌▀▐▄\"},\n    \"triangle\": {\"interval\": 50, \"frames\": \"◢◣◤◥\"},\n    \"arc\": {\"interval\": 100, \"frames\": \"◜◠◝◞◡◟\"},\n    \"circle\": {\"interval\": 120, \"frames\": \"◡⊙◠\"},\n    \"squareCorners\": {\"interval\": 180, \"frames\": \"◰◳◲◱\"},\n    \"circleQuarters\": {\"interval\": 120, \"frames\": \"◴◷◶◵\"},\n    \"circleHalves\": {\"interval\": 50, \"frames\": \"◐◓◑◒\"},\n    \"squish\": {\"interval\": 100, \"frames\": \"╫╪\"},\n    \"toggle\": {\"interval\": 250, \"frames\": \"⊶⊷\"},\n    \"toggle2\": {\"interval\": 80, \"frames\": \"▫▪\"},\n    \"toggle3\": {\"interval\": 120, \"frames\": \"□■\"},\n    \"toggle4\": {\"interval\": 100, \"frames\": \"■□▪▫\"},\n    \"toggle5\": {\"interval\": 100, \"frames\": \"▮▯\"},\n    \"toggle6\": {\"interval\": 300, \"frames\": \"ဝ၀\"},\n    \"toggle7\": {\"interval\": 80, \"frames\": \"⦾⦿\"},\n    \"toggle8\": {\"interval\": 100, \"frames\": \"◍◌\"},\n    \"toggle9\": {\"interval\": 100, \"frames\": \"◉◎\"},\n    \"toggle10\": {\"interval\": 100, \"frames\": \"㊂㊀㊁\"},\n    \"toggle11\": {\"interval\": 50, \"frames\": \"⧇⧆\"},\n    \"toggle12\": {\"interval\": 120, \"frames\": \"☗☖\"},\n    \"toggle13\": {\"interval\": 80, \"frames\": \"=*-\"},\n    \"arrow\": {\"interval\": 100, \"frames\": \"←↖↑↗→↘↓↙\"},\n    \"arrow2\": {\n        \"interval\": 80,\n        \"frames\": [\"⬆️ \", \"↗️ \", \"➡️ \", \"↘️ \", \"⬇️ \", \"↙️ \", \"⬅️ \", \"↖️ \"],\n    },\n    \"arrow3\": {\n        \"interval\": 120,\n        \"frames\": [\"▹▹▹▹▹\", \"▸▹▹▹▹\", \"▹▸▹▹▹\", \"▹▹▸▹▹\", \"▹▹▹▸▹\", \"▹▹▹▹▸\"],\n    },\n    \"bouncingBar\": {\n        \"interval\": 80,\n        \"frames\": [\n            \"[    ]\",\n            \"[=   ]\",\n            \"[==  ]\",\n            \"[=== ]\",\n            \"[ ===]\",\n            \"[  ==]\",\n            \"[   =]\",\n            \"[    ]\",\n            \"[   =]\",\n            \"[  ==]\",\n            \"[ ===]\",\n            \"[====]\",\n            \"[=== ]\",\n            \"[==  ]\",\n            \"[=   ]\",\n        ],\n    },\n    \"bouncingBall\": {\n        \"interval\": 80,\n        \"frames\": [\n            \"( ●    )\",\n            \"(  ●   )\",\n            \"(   ●  )\",\n            \"(    ● )\",\n            \"(     ●)\",\n            \"(    ● )\",\n            \"(   ●  )\",\n            \"(  ●   )\",\n            \"( ●    )\",\n            \"(●     )\",\n        ],\n    },\n    \"smiley\": {\"interval\": 200, \"frames\": [\"😄 \", \"😝 \"]},\n    \"monkey\": {\"interval\": 300, \"frames\": [\"🙈 \", \"🙈 \", \"🙉 \", \"🙊 \"]},\n    \"hearts\": {\"interval\": 100, \"frames\": [\"💛 \", \"💙 \", \"💜 \", \"💚 \", \"❤️ \"]},\n    \"clock\": {\n        \"interval\": 100,\n        \"frames\": [\n            \"🕛 \",\n            \"🕐 \",\n            \"🕑 \",\n            \"🕒 \",\n            \"🕓 \",\n            \"🕔 \",\n            \"🕕 \",\n            \"🕖 \",\n            \"🕗 \",\n            \"🕘 \",\n            \"🕙 \",\n            \"🕚 \",\n        ],\n    },\n    \"earth\": {\"interval\": 180, \"frames\": [\"🌍 \", \"🌎 \", \"🌏 \"]},\n    \"material\": {\n        \"interval\": 17,\n        \"frames\": [\n            \"█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"███▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"████▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"██████▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"███████▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"████████▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"█████████▁▁▁▁▁▁▁▁▁▁▁\",\n            \"█████████▁▁▁▁▁▁▁▁▁▁▁\",\n            \"██████████▁▁▁▁▁▁▁▁▁▁\",\n            \"███████████▁▁▁▁▁▁▁▁▁\",\n            \"█████████████▁▁▁▁▁▁▁\",\n            \"██████████████▁▁▁▁▁▁\",\n            \"██████████████▁▁▁▁▁▁\",\n            \"▁██████████████▁▁▁▁▁\",\n            \"▁██████████████▁▁▁▁▁\",\n            \"▁██████████████▁▁▁▁▁\",\n            \"▁▁██████████████▁▁▁▁\",\n            \"▁▁▁██████████████▁▁▁\",\n            \"▁▁▁▁█████████████▁▁▁\",\n            \"▁▁▁▁██████████████▁▁\",\n            \"▁▁▁▁██████████████▁▁\",\n            \"▁▁▁▁▁██████████████▁\",\n            \"▁▁▁▁▁██████████████▁\",\n            \"▁▁▁▁▁██████████████▁\",\n            \"▁▁▁▁▁▁██████████████\",\n            \"▁▁▁▁▁▁██████████████\",\n            \"▁▁▁▁▁▁▁█████████████\",\n            \"▁▁▁▁▁▁▁█████████████\",\n            \"▁▁▁▁▁▁▁▁████████████\",\n            \"▁▁▁▁▁▁▁▁████████████\",\n            \"▁▁▁▁▁▁▁▁▁███████████\",\n            \"▁▁▁▁▁▁▁▁▁███████████\",\n            \"▁▁▁▁▁▁▁▁▁▁██████████\",\n            \"▁▁▁▁▁▁▁▁▁▁██████████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁████████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁███████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁██████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████\",\n            \"█▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████\",\n            \"██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\n            \"██▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\n            \"███▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\n            \"████▁▁▁▁▁▁▁▁▁▁▁▁▁▁██\",\n            \"█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\n            \"█████▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\n            \"██████▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\n            \"████████▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"█████████▁▁▁▁▁▁▁▁▁▁▁\",\n            \"█████████▁▁▁▁▁▁▁▁▁▁▁\",\n            \"█████████▁▁▁▁▁▁▁▁▁▁▁\",\n            \"█████████▁▁▁▁▁▁▁▁▁▁▁\",\n            \"███████████▁▁▁▁▁▁▁▁▁\",\n            \"████████████▁▁▁▁▁▁▁▁\",\n            \"████████████▁▁▁▁▁▁▁▁\",\n            \"██████████████▁▁▁▁▁▁\",\n            \"██████████████▁▁▁▁▁▁\",\n            \"▁██████████████▁▁▁▁▁\",\n            \"▁██████████████▁▁▁▁▁\",\n            \"▁▁▁█████████████▁▁▁▁\",\n            \"▁▁▁▁▁████████████▁▁▁\",\n            \"▁▁▁▁▁████████████▁▁▁\",\n            \"▁▁▁▁▁▁███████████▁▁▁\",\n            \"▁▁▁▁▁▁▁▁█████████▁▁▁\",\n            \"▁▁▁▁▁▁▁▁█████████▁▁▁\",\n            \"▁▁▁▁▁▁▁▁▁█████████▁▁\",\n            \"▁▁▁▁▁▁▁▁▁█████████▁▁\",\n            \"▁▁▁▁▁▁▁▁▁▁█████████▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁████████▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁████████▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁███████▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁███████▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁███████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁███████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁████\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁███\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁██\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁█\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n            \"▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁\",\n        ],\n    },\n    \"moon\": {\n        \"interval\": 80,\n        \"frames\": [\"🌑 \", \"🌒 \", \"🌓 \", \"🌔 \", \"🌕 \", \"🌖 \", \"🌗 \", \"🌘 \"],\n    },\n    \"runner\": {\"interval\": 140, \"frames\": [\"🚶 \", \"🏃 \"]},\n    \"pong\": {\n        \"interval\": 80,\n        \"frames\": [\n            \"▐⠂       ▌\",\n            \"▐⠈       ▌\",\n            \"▐ ⠂      ▌\",\n            \"▐ ⠠      ▌\",\n            \"▐  ⡀     ▌\",\n            \"▐  ⠠     ▌\",\n            \"▐   ⠂    ▌\",\n            \"▐   ⠈    ▌\",\n            \"▐    ⠂   ▌\",\n            \"▐    ⠠   ▌\",\n            \"▐     ⡀  ▌\",\n            \"▐     ⠠  ▌\",\n            \"▐      ⠂ ▌\",\n            \"▐      ⠈ ▌\",\n            \"▐       ⠂▌\",\n            \"▐       ⠠▌\",\n            \"▐       ⡀▌\",\n            \"▐      ⠠ ▌\",\n            \"▐      ⠂ ▌\",\n            \"▐     ⠈  ▌\",\n            \"▐     ⠂  ▌\",\n            \"▐    ⠠   ▌\",\n            \"▐    ⡀   ▌\",\n            \"▐   ⠠    ▌\",\n            \"▐   ⠂    ▌\",\n            \"▐  ⠈     ▌\",\n            \"▐  ⠂     ▌\",\n            \"▐ ⠠      ▌\",\n            \"▐ ⡀      ▌\",\n            \"▐⠠       ▌\",\n        ],\n    },\n    \"shark\": {\n        \"interval\": 120,\n        \"frames\": [\n            \"▐|\\\\____________▌\",\n            \"▐_|\\\\___________▌\",\n            \"▐__|\\\\__________▌\",\n            \"▐___|\\\\_________▌\",\n            \"▐____|\\\\________▌\",\n            \"▐_____|\\\\_______▌\",\n            \"▐______|\\\\______▌\",\n            \"▐_______|\\\\_____▌\",\n            \"▐________|\\\\____▌\",\n            \"▐_________|\\\\___▌\",\n            \"▐__________|\\\\__▌\",\n            \"▐___________|\\\\_▌\",\n            \"▐____________|\\\\▌\",\n            \"▐____________/|▌\",\n            \"▐___________/|_▌\",\n            \"▐__________/|__▌\",\n            \"▐_________/|___▌\",\n            \"▐________/|____▌\",\n            \"▐_______/|_____▌\",\n            \"▐______/|______▌\",\n            \"▐_____/|_______▌\",\n            \"▐____/|________▌\",\n            \"▐___/|_________▌\",\n            \"▐__/|__________▌\",\n            \"▐_/|___________▌\",\n            \"▐/|____________▌\",\n        ],\n    },\n    \"dqpb\": {\"interval\": 100, \"frames\": \"dqpb\"},\n    \"weather\": {\n        \"interval\": 100,\n        \"frames\": [\n            \"☀️ \",\n            \"☀️ \",\n            \"☀️ \",\n            \"🌤 \",\n            \"⛅️ \",\n            \"🌥 \",\n            \"☁️ \",\n            \"🌧 \",\n            \"🌨 \",\n            \"🌧 \",\n            \"🌨 \",\n            \"🌧 \",\n            \"🌨 \",\n            \"⛈ \",\n            \"🌨 \",\n            \"🌧 \",\n            \"🌨 \",\n            \"☁️ \",\n            \"🌥 \",\n            \"⛅️ \",\n            \"🌤 \",\n            \"☀️ \",\n            \"☀️ \",\n        ],\n    },\n    \"christmas\": {\"interval\": 400, \"frames\": \"🌲🎄\"},\n    \"grenade\": {\n        \"interval\": 80,\n        \"frames\": [\n            \"،   \",\n            \"′   \",\n            \" ´ \",\n            \" ‾ \",\n            \"  ⸌\",\n            \"  ⸊\",\n            \"  |\",\n            \"  ⁎\",\n            \"  ⁕\",\n            \" ෴ \",\n            \"  ⁓\",\n            \"   \",\n            \"   \",\n            \"   \",\n        ],\n    },\n    \"point\": {\"interval\": 125, \"frames\": [\"∙∙∙\", \"●∙∙\", \"∙●∙\", \"∙∙●\", \"∙∙∙\"]},\n    \"layer\": {\"interval\": 150, \"frames\": \"-=≡\"},\n    \"betaWave\": {\n        \"interval\": 80,\n        \"frames\": [\n            \"ρββββββ\",\n            \"βρβββββ\",\n            \"ββρββββ\",\n            \"βββρβββ\",\n            \"ββββρββ\",\n            \"βββββρβ\",\n            \"ββββββρ\",\n        ],\n    },\n    \"aesthetic\": {\n        \"interval\": 80,\n        \"frames\": [\n            \"▰▱▱▱▱▱▱\",\n            \"▰▰▱▱▱▱▱\",\n            \"▰▰▰▱▱▱▱\",\n            \"▰▰▰▰▱▱▱\",\n            \"▰▰▰▰▰▱▱\",\n            \"▰▰▰▰▰▰▱\",\n            \"▰▰▰▰▰▰▰\",\n            \"▰▱▱▱▱▱▱\",\n        ],\n    },\n}\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_stack.py",
    "content": "from typing import List, TypeVar\n\nT = TypeVar(\"T\")\n\n\nclass Stack(List[T]):\n    \"\"\"A small shim over builtin list.\"\"\"\n\n    @property\n    def top(self) -> T:\n        \"\"\"Get top of stack.\"\"\"\n        return self[-1]\n\n    def push(self, item: T) -> None:\n        \"\"\"Push an item on to the stack (append in stack nomenclature).\"\"\"\n        self.append(item)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_timer.py",
    "content": "\"\"\"\nTimer context manager, only used in debug.\n\n\"\"\"\n\nfrom time import time\n\nimport contextlib\nfrom typing import Generator\n\n\n@contextlib.contextmanager\ndef timer(subject: str = \"time\") -> Generator[None, None, None]:\n    \"\"\"print the elapsed time. (only used in debugging)\"\"\"\n    start = time()\n    yield\n    elapsed = time() - start\n    elapsed_ms = elapsed * 1000\n    print(f\"{subject} elapsed {elapsed_ms:.1f}ms\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_win32_console.py",
    "content": "\"\"\"Light wrapper around the Win32 Console API - this module should only be imported on Windows\n\nThe API that this module wraps is documented at https://docs.microsoft.com/en-us/windows/console/console-functions\n\"\"\"\nimport ctypes\nimport sys\nfrom typing import Any\n\nwindll: Any = None\nif sys.platform == \"win32\":\n    windll = ctypes.LibraryLoader(ctypes.WinDLL)\nelse:\n    raise ImportError(f\"{__name__} can only be imported on Windows\")\n\nimport time\nfrom ctypes import Structure, byref, wintypes\nfrom typing import IO, NamedTuple, Type, cast\n\nfrom pip._vendor.rich.color import ColorSystem\nfrom pip._vendor.rich.style import Style\n\nSTDOUT = -11\nENABLE_VIRTUAL_TERMINAL_PROCESSING = 4\n\nCOORD = wintypes._COORD\n\n\nclass LegacyWindowsError(Exception):\n    pass\n\n\nclass WindowsCoordinates(NamedTuple):\n    \"\"\"Coordinates in the Windows Console API are (y, x), not (x, y).\n    This class is intended to prevent that confusion.\n    Rows and columns are indexed from 0.\n    This class can be used in place of wintypes._COORD in arguments and argtypes.\n    \"\"\"\n\n    row: int\n    col: int\n\n    @classmethod\n    def from_param(cls, value: \"WindowsCoordinates\") -> COORD:\n        \"\"\"Converts a WindowsCoordinates into a wintypes _COORD structure.\n        This classmethod is internally called by ctypes to perform the conversion.\n\n        Args:\n            value (WindowsCoordinates): The input coordinates to convert.\n\n        Returns:\n            wintypes._COORD: The converted coordinates struct.\n        \"\"\"\n        return COORD(value.col, value.row)\n\n\nclass CONSOLE_SCREEN_BUFFER_INFO(Structure):\n    _fields_ = [\n        (\"dwSize\", COORD),\n        (\"dwCursorPosition\", COORD),\n        (\"wAttributes\", wintypes.WORD),\n        (\"srWindow\", wintypes.SMALL_RECT),\n        (\"dwMaximumWindowSize\", COORD),\n    ]\n\n\nclass CONSOLE_CURSOR_INFO(ctypes.Structure):\n    _fields_ = [(\"dwSize\", wintypes.DWORD), (\"bVisible\", wintypes.BOOL)]\n\n\n_GetStdHandle = windll.kernel32.GetStdHandle\n_GetStdHandle.argtypes = [\n    wintypes.DWORD,\n]\n_GetStdHandle.restype = wintypes.HANDLE\n\n\ndef GetStdHandle(handle: int = STDOUT) -> wintypes.HANDLE:\n    \"\"\"Retrieves a handle to the specified standard device (standard input, standard output, or standard error).\n\n    Args:\n        handle (int): Integer identifier for the handle. Defaults to -11 (stdout).\n\n    Returns:\n        wintypes.HANDLE: The handle\n    \"\"\"\n    return cast(wintypes.HANDLE, _GetStdHandle(handle))\n\n\n_GetConsoleMode = windll.kernel32.GetConsoleMode\n_GetConsoleMode.argtypes = [wintypes.HANDLE, wintypes.LPDWORD]\n_GetConsoleMode.restype = wintypes.BOOL\n\n\ndef GetConsoleMode(std_handle: wintypes.HANDLE) -> int:\n    \"\"\"Retrieves the current input mode of a console's input buffer\n    or the current output mode of a console screen buffer.\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n\n    Raises:\n        LegacyWindowsError: If any error occurs while calling the Windows console API.\n\n    Returns:\n        int: Value representing the current console mode as documented at\n            https://docs.microsoft.com/en-us/windows/console/getconsolemode#parameters\n    \"\"\"\n\n    console_mode = wintypes.DWORD()\n    success = bool(_GetConsoleMode(std_handle, console_mode))\n    if not success:\n        raise LegacyWindowsError(\"Unable to get legacy Windows Console Mode\")\n    return console_mode.value\n\n\n_FillConsoleOutputCharacterW = windll.kernel32.FillConsoleOutputCharacterW\n_FillConsoleOutputCharacterW.argtypes = [\n    wintypes.HANDLE,\n    ctypes.c_char,\n    wintypes.DWORD,\n    cast(Type[COORD], WindowsCoordinates),\n    ctypes.POINTER(wintypes.DWORD),\n]\n_FillConsoleOutputCharacterW.restype = wintypes.BOOL\n\n\ndef FillConsoleOutputCharacter(\n    std_handle: wintypes.HANDLE,\n    char: str,\n    length: int,\n    start: WindowsCoordinates,\n) -> int:\n    \"\"\"Writes a character to the console screen buffer a specified number of times, beginning at the specified coordinates.\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n        char (str): The character to write. Must be a string of length 1.\n        length (int): The number of times to write the character.\n        start (WindowsCoordinates): The coordinates to start writing at.\n\n    Returns:\n        int: The number of characters written.\n    \"\"\"\n    character = ctypes.c_char(char.encode())\n    num_characters = wintypes.DWORD(length)\n    num_written = wintypes.DWORD(0)\n    _FillConsoleOutputCharacterW(\n        std_handle,\n        character,\n        num_characters,\n        start,\n        byref(num_written),\n    )\n    return num_written.value\n\n\n_FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute\n_FillConsoleOutputAttribute.argtypes = [\n    wintypes.HANDLE,\n    wintypes.WORD,\n    wintypes.DWORD,\n    cast(Type[COORD], WindowsCoordinates),\n    ctypes.POINTER(wintypes.DWORD),\n]\n_FillConsoleOutputAttribute.restype = wintypes.BOOL\n\n\ndef FillConsoleOutputAttribute(\n    std_handle: wintypes.HANDLE,\n    attributes: int,\n    length: int,\n    start: WindowsCoordinates,\n) -> int:\n    \"\"\"Sets the character attributes for a specified number of character cells,\n    beginning at the specified coordinates in a screen buffer.\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n        attributes (int): Integer value representing the foreground and background colours of the cells.\n        length (int): The number of cells to set the output attribute of.\n        start (WindowsCoordinates): The coordinates of the first cell whose attributes are to be set.\n\n    Returns:\n        int: The number of cells whose attributes were actually set.\n    \"\"\"\n    num_cells = wintypes.DWORD(length)\n    style_attrs = wintypes.WORD(attributes)\n    num_written = wintypes.DWORD(0)\n    _FillConsoleOutputAttribute(\n        std_handle, style_attrs, num_cells, start, byref(num_written)\n    )\n    return num_written.value\n\n\n_SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute\n_SetConsoleTextAttribute.argtypes = [\n    wintypes.HANDLE,\n    wintypes.WORD,\n]\n_SetConsoleTextAttribute.restype = wintypes.BOOL\n\n\ndef SetConsoleTextAttribute(\n    std_handle: wintypes.HANDLE, attributes: wintypes.WORD\n) -> bool:\n    \"\"\"Set the colour attributes for all text written after this function is called.\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n        attributes (int): Integer value representing the foreground and background colours.\n\n\n    Returns:\n        bool: True if the attribute was set successfully, otherwise False.\n    \"\"\"\n    return bool(_SetConsoleTextAttribute(std_handle, attributes))\n\n\n_GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo\n_GetConsoleScreenBufferInfo.argtypes = [\n    wintypes.HANDLE,\n    ctypes.POINTER(CONSOLE_SCREEN_BUFFER_INFO),\n]\n_GetConsoleScreenBufferInfo.restype = wintypes.BOOL\n\n\ndef GetConsoleScreenBufferInfo(\n    std_handle: wintypes.HANDLE,\n) -> CONSOLE_SCREEN_BUFFER_INFO:\n    \"\"\"Retrieves information about the specified console screen buffer.\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n\n    Returns:\n        CONSOLE_SCREEN_BUFFER_INFO: A CONSOLE_SCREEN_BUFFER_INFO ctype struct contain information about\n            screen size, cursor position, colour attributes, and more.\"\"\"\n    console_screen_buffer_info = CONSOLE_SCREEN_BUFFER_INFO()\n    _GetConsoleScreenBufferInfo(std_handle, byref(console_screen_buffer_info))\n    return console_screen_buffer_info\n\n\n_SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition\n_SetConsoleCursorPosition.argtypes = [\n    wintypes.HANDLE,\n    cast(Type[COORD], WindowsCoordinates),\n]\n_SetConsoleCursorPosition.restype = wintypes.BOOL\n\n\ndef SetConsoleCursorPosition(\n    std_handle: wintypes.HANDLE, coords: WindowsCoordinates\n) -> bool:\n    \"\"\"Set the position of the cursor in the console screen\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n        coords (WindowsCoordinates): The coordinates to move the cursor to.\n\n    Returns:\n        bool: True if the function succeeds, otherwise False.\n    \"\"\"\n    return bool(_SetConsoleCursorPosition(std_handle, coords))\n\n\n_GetConsoleCursorInfo = windll.kernel32.GetConsoleCursorInfo\n_GetConsoleCursorInfo.argtypes = [\n    wintypes.HANDLE,\n    ctypes.POINTER(CONSOLE_CURSOR_INFO),\n]\n_GetConsoleCursorInfo.restype = wintypes.BOOL\n\n\ndef GetConsoleCursorInfo(\n    std_handle: wintypes.HANDLE, cursor_info: CONSOLE_CURSOR_INFO\n) -> bool:\n    \"\"\"Get the cursor info - used to get cursor visibility and width\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n        cursor_info (CONSOLE_CURSOR_INFO): CONSOLE_CURSOR_INFO ctype struct that receives information\n            about the console's cursor.\n\n    Returns:\n          bool: True if the function succeeds, otherwise False.\n    \"\"\"\n    return bool(_GetConsoleCursorInfo(std_handle, byref(cursor_info)))\n\n\n_SetConsoleCursorInfo = windll.kernel32.SetConsoleCursorInfo\n_SetConsoleCursorInfo.argtypes = [\n    wintypes.HANDLE,\n    ctypes.POINTER(CONSOLE_CURSOR_INFO),\n]\n_SetConsoleCursorInfo.restype = wintypes.BOOL\n\n\ndef SetConsoleCursorInfo(\n    std_handle: wintypes.HANDLE, cursor_info: CONSOLE_CURSOR_INFO\n) -> bool:\n    \"\"\"Set the cursor info - used for adjusting cursor visibility and width\n\n    Args:\n        std_handle (wintypes.HANDLE): A handle to the console input buffer or the console screen buffer.\n        cursor_info (CONSOLE_CURSOR_INFO): CONSOLE_CURSOR_INFO ctype struct containing the new cursor info.\n\n    Returns:\n          bool: True if the function succeeds, otherwise False.\n    \"\"\"\n    return bool(_SetConsoleCursorInfo(std_handle, byref(cursor_info)))\n\n\n_SetConsoleTitle = windll.kernel32.SetConsoleTitleW\n_SetConsoleTitle.argtypes = [wintypes.LPCWSTR]\n_SetConsoleTitle.restype = wintypes.BOOL\n\n\ndef SetConsoleTitle(title: str) -> bool:\n    \"\"\"Sets the title of the current console window\n\n    Args:\n        title (str): The new title of the console window.\n\n    Returns:\n        bool: True if the function succeeds, otherwise False.\n    \"\"\"\n    return bool(_SetConsoleTitle(title))\n\n\nclass LegacyWindowsTerm:\n    \"\"\"This class allows interaction with the legacy Windows Console API. It should only be used in the context\n    of environments where virtual terminal processing is not available. However, if it is used in a Windows environment,\n    the entire API should work.\n\n    Args:\n        file (IO[str]): The file which the Windows Console API HANDLE is retrieved from, defaults to sys.stdout.\n    \"\"\"\n\n    BRIGHT_BIT = 8\n\n    # Indices are ANSI color numbers, values are the corresponding Windows Console API color numbers\n    ANSI_TO_WINDOWS = [\n        0,  # black                      The Windows colours are defined in wincon.h as follows:\n        4,  # red                         define FOREGROUND_BLUE            0x0001 -- 0000 0001\n        2,  # green                       define FOREGROUND_GREEN           0x0002 -- 0000 0010\n        6,  # yellow                      define FOREGROUND_RED             0x0004 -- 0000 0100\n        1,  # blue                        define FOREGROUND_INTENSITY       0x0008 -- 0000 1000\n        5,  # magenta                     define BACKGROUND_BLUE            0x0010 -- 0001 0000\n        3,  # cyan                        define BACKGROUND_GREEN           0x0020 -- 0010 0000\n        7,  # white                       define BACKGROUND_RED             0x0040 -- 0100 0000\n        8,  # bright black (grey)         define BACKGROUND_INTENSITY       0x0080 -- 1000 0000\n        12,  # bright red\n        10,  # bright green\n        14,  # bright yellow\n        9,  # bright blue\n        13,  # bright magenta\n        11,  # bright cyan\n        15,  # bright white\n    ]\n\n    def __init__(self, file: \"IO[str]\") -> None:\n        handle = GetStdHandle(STDOUT)\n        self._handle = handle\n        default_text = GetConsoleScreenBufferInfo(handle).wAttributes\n        self._default_text = default_text\n\n        self._default_fore = default_text & 7\n        self._default_back = (default_text >> 4) & 7\n        self._default_attrs = self._default_fore | (self._default_back << 4)\n\n        self._file = file\n        self.write = file.write\n        self.flush = file.flush\n\n    @property\n    def cursor_position(self) -> WindowsCoordinates:\n        \"\"\"Returns the current position of the cursor (0-based)\n\n        Returns:\n            WindowsCoordinates: The current cursor position.\n        \"\"\"\n        coord: COORD = GetConsoleScreenBufferInfo(self._handle).dwCursorPosition\n        return WindowsCoordinates(row=cast(int, coord.Y), col=cast(int, coord.X))\n\n    @property\n    def screen_size(self) -> WindowsCoordinates:\n        \"\"\"Returns the current size of the console screen buffer, in character columns and rows\n\n        Returns:\n            WindowsCoordinates: The width and height of the screen as WindowsCoordinates.\n        \"\"\"\n        screen_size: COORD = GetConsoleScreenBufferInfo(self._handle).dwSize\n        return WindowsCoordinates(\n            row=cast(int, screen_size.Y), col=cast(int, screen_size.X)\n        )\n\n    def write_text(self, text: str) -> None:\n        \"\"\"Write text directly to the terminal without any modification of styles\n\n        Args:\n            text (str): The text to write to the console\n        \"\"\"\n        self.write(text)\n        self.flush()\n\n    def write_styled(self, text: str, style: Style) -> None:\n        \"\"\"Write styled text to the terminal.\n\n        Args:\n            text (str): The text to write\n            style (Style): The style of the text\n        \"\"\"\n        color = style.color\n        bgcolor = style.bgcolor\n        if style.reverse:\n            color, bgcolor = bgcolor, color\n\n        if color:\n            fore = color.downgrade(ColorSystem.WINDOWS).number\n            fore = fore if fore is not None else 7  # Default to ANSI 7: White\n            if style.bold:\n                fore = fore | self.BRIGHT_BIT\n            if style.dim:\n                fore = fore & ~self.BRIGHT_BIT\n            fore = self.ANSI_TO_WINDOWS[fore]\n        else:\n            fore = self._default_fore\n\n        if bgcolor:\n            back = bgcolor.downgrade(ColorSystem.WINDOWS).number\n            back = back if back is not None else 0  # Default to ANSI 0: Black\n            back = self.ANSI_TO_WINDOWS[back]\n        else:\n            back = self._default_back\n\n        assert fore is not None\n        assert back is not None\n\n        SetConsoleTextAttribute(\n            self._handle, attributes=ctypes.c_ushort(fore | (back << 4))\n        )\n        self.write_text(text)\n        SetConsoleTextAttribute(self._handle, attributes=self._default_text)\n\n    def move_cursor_to(self, new_position: WindowsCoordinates) -> None:\n        \"\"\"Set the position of the cursor\n\n        Args:\n            new_position (WindowsCoordinates): The WindowsCoordinates representing the new position of the cursor.\n        \"\"\"\n        if new_position.col < 0 or new_position.row < 0:\n            return\n        SetConsoleCursorPosition(self._handle, coords=new_position)\n\n    def erase_line(self) -> None:\n        \"\"\"Erase all content on the line the cursor is currently located at\"\"\"\n        screen_size = self.screen_size\n        cursor_position = self.cursor_position\n        cells_to_erase = screen_size.col\n        start_coordinates = WindowsCoordinates(row=cursor_position.row, col=0)\n        FillConsoleOutputCharacter(\n            self._handle, \" \", length=cells_to_erase, start=start_coordinates\n        )\n        FillConsoleOutputAttribute(\n            self._handle,\n            self._default_attrs,\n            length=cells_to_erase,\n            start=start_coordinates,\n        )\n\n    def erase_end_of_line(self) -> None:\n        \"\"\"Erase all content from the cursor position to the end of that line\"\"\"\n        cursor_position = self.cursor_position\n        cells_to_erase = self.screen_size.col - cursor_position.col\n        FillConsoleOutputCharacter(\n            self._handle, \" \", length=cells_to_erase, start=cursor_position\n        )\n        FillConsoleOutputAttribute(\n            self._handle,\n            self._default_attrs,\n            length=cells_to_erase,\n            start=cursor_position,\n        )\n\n    def erase_start_of_line(self) -> None:\n        \"\"\"Erase all content from the cursor position to the start of that line\"\"\"\n        row, col = self.cursor_position\n        start = WindowsCoordinates(row, 0)\n        FillConsoleOutputCharacter(self._handle, \" \", length=col, start=start)\n        FillConsoleOutputAttribute(\n            self._handle, self._default_attrs, length=col, start=start\n        )\n\n    def move_cursor_up(self) -> None:\n        \"\"\"Move the cursor up a single cell\"\"\"\n        cursor_position = self.cursor_position\n        SetConsoleCursorPosition(\n            self._handle,\n            coords=WindowsCoordinates(\n                row=cursor_position.row - 1, col=cursor_position.col\n            ),\n        )\n\n    def move_cursor_down(self) -> None:\n        \"\"\"Move the cursor down a single cell\"\"\"\n        cursor_position = self.cursor_position\n        SetConsoleCursorPosition(\n            self._handle,\n            coords=WindowsCoordinates(\n                row=cursor_position.row + 1,\n                col=cursor_position.col,\n            ),\n        )\n\n    def move_cursor_forward(self) -> None:\n        \"\"\"Move the cursor forward a single cell. Wrap to the next line if required.\"\"\"\n        row, col = self.cursor_position\n        if col == self.screen_size.col - 1:\n            row += 1\n            col = 0\n        else:\n            col += 1\n        SetConsoleCursorPosition(\n            self._handle, coords=WindowsCoordinates(row=row, col=col)\n        )\n\n    def move_cursor_to_column(self, column: int) -> None:\n        \"\"\"Move cursor to the column specified by the zero-based column index, staying on the same row\n\n        Args:\n            column (int): The zero-based column index to move the cursor to.\n        \"\"\"\n        row, _ = self.cursor_position\n        SetConsoleCursorPosition(self._handle, coords=WindowsCoordinates(row, column))\n\n    def move_cursor_backward(self) -> None:\n        \"\"\"Move the cursor backward a single cell. Wrap to the previous line if required.\"\"\"\n        row, col = self.cursor_position\n        if col == 0:\n            row -= 1\n            col = self.screen_size.col - 1\n        else:\n            col -= 1\n        SetConsoleCursorPosition(\n            self._handle, coords=WindowsCoordinates(row=row, col=col)\n        )\n\n    def hide_cursor(self) -> None:\n        \"\"\"Hide the cursor\"\"\"\n        current_cursor_size = self._get_cursor_size()\n        invisible_cursor = CONSOLE_CURSOR_INFO(dwSize=current_cursor_size, bVisible=0)\n        SetConsoleCursorInfo(self._handle, cursor_info=invisible_cursor)\n\n    def show_cursor(self) -> None:\n        \"\"\"Show the cursor\"\"\"\n        current_cursor_size = self._get_cursor_size()\n        visible_cursor = CONSOLE_CURSOR_INFO(dwSize=current_cursor_size, bVisible=1)\n        SetConsoleCursorInfo(self._handle, cursor_info=visible_cursor)\n\n    def set_title(self, title: str) -> None:\n        \"\"\"Set the title of the terminal window\n\n        Args:\n            title (str): The new title of the console window\n        \"\"\"\n        assert len(title) < 255, \"Console title must be less than 255 characters\"\n        SetConsoleTitle(title)\n\n    def _get_cursor_size(self) -> int:\n        \"\"\"Get the percentage of the character cell that is filled by the cursor\"\"\"\n        cursor_info = CONSOLE_CURSOR_INFO()\n        GetConsoleCursorInfo(self._handle, cursor_info=cursor_info)\n        return int(cursor_info.dwSize)\n\n\nif __name__ == \"__main__\":\n    handle = GetStdHandle()\n\n    from pip._vendor.rich.console import Console\n\n    console = Console()\n\n    term = LegacyWindowsTerm(sys.stdout)\n    term.set_title(\"Win32 Console Examples\")\n\n    style = Style(color=\"black\", bgcolor=\"red\")\n\n    heading = Style.parse(\"black on green\")\n\n    # Check colour output\n    console.rule(\"Checking colour output\")\n    console.print(\"[on red]on red!\")\n    console.print(\"[blue]blue!\")\n    console.print(\"[yellow]yellow!\")\n    console.print(\"[bold yellow]bold yellow!\")\n    console.print(\"[bright_yellow]bright_yellow!\")\n    console.print(\"[dim bright_yellow]dim bright_yellow!\")\n    console.print(\"[italic cyan]italic cyan!\")\n    console.print(\"[bold white on blue]bold white on blue!\")\n    console.print(\"[reverse bold white on blue]reverse bold white on blue!\")\n    console.print(\"[bold black on cyan]bold black on cyan!\")\n    console.print(\"[black on green]black on green!\")\n    console.print(\"[blue on green]blue on green!\")\n    console.print(\"[white on black]white on black!\")\n    console.print(\"[black on white]black on white!\")\n    console.print(\"[#1BB152 on #DA812D]#1BB152 on #DA812D!\")\n\n    # Check cursor movement\n    console.rule(\"Checking cursor movement\")\n    console.print()\n    term.move_cursor_backward()\n    term.move_cursor_backward()\n    term.write_text(\"went back and wrapped to prev line\")\n    time.sleep(1)\n    term.move_cursor_up()\n    term.write_text(\"we go up\")\n    time.sleep(1)\n    term.move_cursor_down()\n    term.write_text(\"and down\")\n    time.sleep(1)\n    term.move_cursor_up()\n    term.move_cursor_backward()\n    term.move_cursor_backward()\n    term.write_text(\"we went up and back 2\")\n    time.sleep(1)\n    term.move_cursor_down()\n    term.move_cursor_backward()\n    term.move_cursor_backward()\n    term.write_text(\"we went down and back 2\")\n    time.sleep(1)\n\n    # Check erasing of lines\n    term.hide_cursor()\n    console.print()\n    console.rule(\"Checking line erasing\")\n    console.print(\"\\n...Deleting to the start of the line...\")\n    term.write_text(\"The red arrow shows the cursor location, and direction of erase\")\n    time.sleep(1)\n    term.move_cursor_to_column(16)\n    term.write_styled(\"<\", Style.parse(\"black on red\"))\n    term.move_cursor_backward()\n    time.sleep(1)\n    term.erase_start_of_line()\n    time.sleep(1)\n\n    console.print(\"\\n\\n...And to the end of the line...\")\n    term.write_text(\"The red arrow shows the cursor location, and direction of erase\")\n    time.sleep(1)\n\n    term.move_cursor_to_column(16)\n    term.write_styled(\">\", Style.parse(\"black on red\"))\n    time.sleep(1)\n    term.erase_end_of_line()\n    time.sleep(1)\n\n    console.print(\"\\n\\n...Now the whole line will be erased...\")\n    term.write_styled(\"I'm going to disappear!\", style=Style.parse(\"black on cyan\"))\n    time.sleep(1)\n    term.erase_line()\n\n    term.show_cursor()\n    print(\"\\n\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_windows.py",
    "content": "import sys\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass WindowsConsoleFeatures:\n    \"\"\"Windows features available.\"\"\"\n\n    vt: bool = False\n    \"\"\"The console supports VT codes.\"\"\"\n    truecolor: bool = False\n    \"\"\"The console supports truecolor.\"\"\"\n\n\ntry:\n    import ctypes\n    from ctypes import LibraryLoader\n\n    if sys.platform == \"win32\":\n        windll = LibraryLoader(ctypes.WinDLL)\n    else:\n        windll = None\n        raise ImportError(\"Not windows\")\n\n    from pip._vendor.rich._win32_console import (\n        ENABLE_VIRTUAL_TERMINAL_PROCESSING,\n        GetConsoleMode,\n        GetStdHandle,\n        LegacyWindowsError,\n    )\n\nexcept (AttributeError, ImportError, ValueError):\n\n    # Fallback if we can't load the Windows DLL\n    def get_windows_console_features() -> WindowsConsoleFeatures:\n        features = WindowsConsoleFeatures()\n        return features\n\nelse:\n\n    def get_windows_console_features() -> WindowsConsoleFeatures:\n        \"\"\"Get windows console features.\n\n        Returns:\n            WindowsConsoleFeatures: An instance of WindowsConsoleFeatures.\n        \"\"\"\n        handle = GetStdHandle()\n        try:\n            console_mode = GetConsoleMode(handle)\n            success = True\n        except LegacyWindowsError:\n            console_mode = 0\n            success = False\n        vt = bool(success and console_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)\n        truecolor = False\n        if vt:\n            win_version = sys.getwindowsversion()\n            truecolor = win_version.major > 10 or (\n                win_version.major == 10 and win_version.build >= 15063\n            )\n        features = WindowsConsoleFeatures(vt=vt, truecolor=truecolor)\n        return features\n\n\nif __name__ == \"__main__\":\n    import platform\n\n    features = get_windows_console_features()\n    from pip._vendor.rich import print\n\n    print(f'platform=\"{platform.system()}\"')\n    print(repr(features))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_windows_renderer.py",
    "content": "from typing import Iterable, Sequence, Tuple, cast\n\nfrom pip._vendor.rich._win32_console import LegacyWindowsTerm, WindowsCoordinates\nfrom pip._vendor.rich.segment import ControlCode, ControlType, Segment\n\n\ndef legacy_windows_render(buffer: Iterable[Segment], term: LegacyWindowsTerm) -> None:\n    \"\"\"Makes appropriate Windows Console API calls based on the segments in the buffer.\n\n    Args:\n        buffer (Iterable[Segment]): Iterable of Segments to convert to Win32 API calls.\n        term (LegacyWindowsTerm): Used to call the Windows Console API.\n    \"\"\"\n    for text, style, control in buffer:\n        if not control:\n            if style:\n                term.write_styled(text, style)\n            else:\n                term.write_text(text)\n        else:\n            control_codes: Sequence[ControlCode] = control\n            for control_code in control_codes:\n                control_type = control_code[0]\n                if control_type == ControlType.CURSOR_MOVE_TO:\n                    _, x, y = cast(Tuple[ControlType, int, int], control_code)\n                    term.move_cursor_to(WindowsCoordinates(row=y - 1, col=x - 1))\n                elif control_type == ControlType.CARRIAGE_RETURN:\n                    term.write_text(\"\\r\")\n                elif control_type == ControlType.HOME:\n                    term.move_cursor_to(WindowsCoordinates(0, 0))\n                elif control_type == ControlType.CURSOR_UP:\n                    term.move_cursor_up()\n                elif control_type == ControlType.CURSOR_DOWN:\n                    term.move_cursor_down()\n                elif control_type == ControlType.CURSOR_FORWARD:\n                    term.move_cursor_forward()\n                elif control_type == ControlType.CURSOR_BACKWARD:\n                    term.move_cursor_backward()\n                elif control_type == ControlType.CURSOR_MOVE_TO_COLUMN:\n                    _, column = cast(Tuple[ControlType, int], control_code)\n                    term.move_cursor_to_column(column - 1)\n                elif control_type == ControlType.HIDE_CURSOR:\n                    term.hide_cursor()\n                elif control_type == ControlType.SHOW_CURSOR:\n                    term.show_cursor()\n                elif control_type == ControlType.ERASE_IN_LINE:\n                    _, mode = cast(Tuple[ControlType, int], control_code)\n                    if mode == 0:\n                        term.erase_end_of_line()\n                    elif mode == 1:\n                        term.erase_start_of_line()\n                    elif mode == 2:\n                        term.erase_line()\n                elif control_type == ControlType.SET_WINDOW_TITLE:\n                    _, title = cast(Tuple[ControlType, str], control_code)\n                    term.set_title(title)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/_wrap.py",
    "content": "import re\nfrom typing import Iterable, List, Tuple\n\nfrom ._loop import loop_last\nfrom .cells import cell_len, chop_cells\n\nre_word = re.compile(r\"\\s*\\S+\\s*\")\n\n\ndef words(text: str) -> Iterable[Tuple[int, int, str]]:\n    position = 0\n    word_match = re_word.match(text, position)\n    while word_match is not None:\n        start, end = word_match.span()\n        word = word_match.group(0)\n        yield start, end, word\n        word_match = re_word.match(text, end)\n\n\ndef divide_line(text: str, width: int, fold: bool = True) -> List[int]:\n    divides: List[int] = []\n    append = divides.append\n    line_position = 0\n    _cell_len = cell_len\n    for start, _end, word in words(text):\n        word_length = _cell_len(word.rstrip())\n        if line_position + word_length > width:\n            if word_length > width:\n                if fold:\n                    chopped_words = chop_cells(word, max_size=width, position=0)\n                    for last, line in loop_last(chopped_words):\n                        if start:\n                            append(start)\n\n                        if last:\n                            line_position = _cell_len(line)\n                        else:\n                            start += len(line)\n                else:\n                    if start:\n                        append(start)\n                    line_position = _cell_len(word)\n            elif line_position and start:\n                append(start)\n                line_position = _cell_len(word)\n        else:\n            line_position += _cell_len(word)\n    return divides\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from .console import Console\n\n    console = Console(width=10)\n    console.print(\"12345 abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWXYZ 12345\")\n    print(chop_cells(\"abcdefghijklmnopqrstuvwxyz\", 10, position=2))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/abc.py",
    "content": "from abc import ABC\n\n\nclass RichRenderable(ABC):\n    \"\"\"An abstract base class for Rich renderables.\n\n    Note that there is no need to extend this class, the intended use is to check if an\n    object supports the Rich renderable protocol. For example::\n\n        if isinstance(my_object, RichRenderable):\n            console.print(my_object)\n\n    \"\"\"\n\n    @classmethod\n    def __subclasshook__(cls, other: type) -> bool:\n        \"\"\"Check if this class supports the rich render protocol.\"\"\"\n        return hasattr(other, \"__rich_console__\") or hasattr(other, \"__rich__\")\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.text import Text\n\n    t = Text()\n    print(isinstance(Text, RichRenderable))\n    print(isinstance(t, RichRenderable))\n\n    class Foo:\n        pass\n\n    f = Foo()\n    print(isinstance(f, RichRenderable))\n    print(isinstance(\"\", RichRenderable))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/align.py",
    "content": "import sys\nfrom itertools import chain\nfrom typing import TYPE_CHECKING, Iterable, Optional\n\nif sys.version_info >= (3, 8):\n    from typing import Literal\nelse:\n    from pip._vendor.typing_extensions import Literal  # pragma: no cover\n\nfrom .constrain import Constrain\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .segment import Segment\nfrom .style import StyleType\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderableType, RenderResult\n\nAlignMethod = Literal[\"left\", \"center\", \"right\"]\nVerticalAlignMethod = Literal[\"top\", \"middle\", \"bottom\"]\n\n\nclass Align(JupyterMixin):\n    \"\"\"Align a renderable by adding spaces if necessary.\n\n    Args:\n        renderable (RenderableType): A console renderable.\n        align (AlignMethod): One of \"left\", \"center\", or \"right\"\"\n        style (StyleType, optional): An optional style to apply to the background.\n        vertical (Optional[VerticalAlginMethod], optional): Optional vertical align, one of \"top\", \"middle\", or \"bottom\". Defaults to None.\n        pad (bool, optional): Pad the right with spaces. Defaults to True.\n        width (int, optional): Restrict contents to given width, or None to use default width. Defaults to None.\n        height (int, optional): Set height of align renderable, or None to fit to contents. Defaults to None.\n\n    Raises:\n        ValueError: if ``align`` is not one of the expected values.\n    \"\"\"\n\n    def __init__(\n        self,\n        renderable: \"RenderableType\",\n        align: AlignMethod = \"left\",\n        style: Optional[StyleType] = None,\n        *,\n        vertical: Optional[VerticalAlignMethod] = None,\n        pad: bool = True,\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n    ) -> None:\n        if align not in (\"left\", \"center\", \"right\"):\n            raise ValueError(\n                f'invalid value for align, expected \"left\", \"center\", or \"right\" (not {align!r})'\n            )\n        if vertical is not None and vertical not in (\"top\", \"middle\", \"bottom\"):\n            raise ValueError(\n                f'invalid value for vertical, expected \"top\", \"middle\", or \"bottom\" (not {vertical!r})'\n            )\n        self.renderable = renderable\n        self.align = align\n        self.style = style\n        self.vertical = vertical\n        self.pad = pad\n        self.width = width\n        self.height = height\n\n    def __repr__(self) -> str:\n        return f\"Align({self.renderable!r}, {self.align!r})\"\n\n    @classmethod\n    def left(\n        cls,\n        renderable: \"RenderableType\",\n        style: Optional[StyleType] = None,\n        *,\n        vertical: Optional[VerticalAlignMethod] = None,\n        pad: bool = True,\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n    ) -> \"Align\":\n        \"\"\"Align a renderable to the left.\"\"\"\n        return cls(\n            renderable,\n            \"left\",\n            style=style,\n            vertical=vertical,\n            pad=pad,\n            width=width,\n            height=height,\n        )\n\n    @classmethod\n    def center(\n        cls,\n        renderable: \"RenderableType\",\n        style: Optional[StyleType] = None,\n        *,\n        vertical: Optional[VerticalAlignMethod] = None,\n        pad: bool = True,\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n    ) -> \"Align\":\n        \"\"\"Align a renderable to the center.\"\"\"\n        return cls(\n            renderable,\n            \"center\",\n            style=style,\n            vertical=vertical,\n            pad=pad,\n            width=width,\n            height=height,\n        )\n\n    @classmethod\n    def right(\n        cls,\n        renderable: \"RenderableType\",\n        style: Optional[StyleType] = None,\n        *,\n        vertical: Optional[VerticalAlignMethod] = None,\n        pad: bool = True,\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n    ) -> \"Align\":\n        \"\"\"Align a renderable to the right.\"\"\"\n        return cls(\n            renderable,\n            \"right\",\n            style=style,\n            vertical=vertical,\n            pad=pad,\n            width=width,\n            height=height,\n        )\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        align = self.align\n        width = console.measure(self.renderable, options=options).maximum\n        rendered = console.render(\n            Constrain(\n                self.renderable, width if self.width is None else min(width, self.width)\n            ),\n            options.update(height=None),\n        )\n        lines = list(Segment.split_lines(rendered))\n        width, height = Segment.get_shape(lines)\n        lines = Segment.set_shape(lines, width, height)\n        new_line = Segment.line()\n        excess_space = options.max_width - width\n        style = console.get_style(self.style) if self.style is not None else None\n\n        def generate_segments() -> Iterable[Segment]:\n            if excess_space <= 0:\n                # Exact fit\n                for line in lines:\n                    yield from line\n                    yield new_line\n\n            elif align == \"left\":\n                # Pad on the right\n                pad = Segment(\" \" * excess_space, style) if self.pad else None\n                for line in lines:\n                    yield from line\n                    if pad:\n                        yield pad\n                    yield new_line\n\n            elif align == \"center\":\n                # Pad left and right\n                left = excess_space // 2\n                pad = Segment(\" \" * left, style)\n                pad_right = (\n                    Segment(\" \" * (excess_space - left), style) if self.pad else None\n                )\n                for line in lines:\n                    if left:\n                        yield pad\n                    yield from line\n                    if pad_right:\n                        yield pad_right\n                    yield new_line\n\n            elif align == \"right\":\n                # Padding on left\n                pad = Segment(\" \" * excess_space, style)\n                for line in lines:\n                    yield pad\n                    yield from line\n                    yield new_line\n\n        blank_line = (\n            Segment(f\"{' ' * (self.width or options.max_width)}\\n\", style)\n            if self.pad\n            else Segment(\"\\n\")\n        )\n\n        def blank_lines(count: int) -> Iterable[Segment]:\n            if count > 0:\n                for _ in range(count):\n                    yield blank_line\n\n        vertical_height = self.height or options.height\n        iter_segments: Iterable[Segment]\n        if self.vertical and vertical_height is not None:\n            if self.vertical == \"top\":\n                bottom_space = vertical_height - height\n                iter_segments = chain(generate_segments(), blank_lines(bottom_space))\n            elif self.vertical == \"middle\":\n                top_space = (vertical_height - height) // 2\n                bottom_space = vertical_height - top_space - height\n                iter_segments = chain(\n                    blank_lines(top_space),\n                    generate_segments(),\n                    blank_lines(bottom_space),\n                )\n            else:  #  self.vertical == \"bottom\":\n                top_space = vertical_height - height\n                iter_segments = chain(blank_lines(top_space), generate_segments())\n        else:\n            iter_segments = generate_segments()\n        if self.style:\n            style = console.get_style(self.style)\n            iter_segments = Segment.apply_style(iter_segments, style)\n        yield from iter_segments\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Measurement:\n        measurement = Measurement.get(console, options, self.renderable)\n        return measurement\n\n\nclass VerticalCenter(JupyterMixin):\n    \"\"\"Vertically aligns a renderable.\n\n    Warn:\n        This class is deprecated and may be removed in a future version. Use Align class with\n        `vertical=\"middle\"`.\n\n    Args:\n        renderable (RenderableType): A renderable object.\n    \"\"\"\n\n    def __init__(\n        self,\n        renderable: \"RenderableType\",\n        style: Optional[StyleType] = None,\n    ) -> None:\n        self.renderable = renderable\n        self.style = style\n\n    def __repr__(self) -> str:\n        return f\"VerticalCenter({self.renderable!r})\"\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        style = console.get_style(self.style) if self.style is not None else None\n        lines = console.render_lines(\n            self.renderable, options.update(height=None), pad=False\n        )\n        width, _height = Segment.get_shape(lines)\n        new_line = Segment.line()\n        height = options.height or options.size.height\n        top_space = (height - len(lines)) // 2\n        bottom_space = height - top_space - len(lines)\n        blank_line = Segment(f\"{' ' * width}\", style)\n\n        def blank_lines(count: int) -> Iterable[Segment]:\n            for _ in range(count):\n                yield blank_line\n                yield new_line\n\n        if top_space > 0:\n            yield from blank_lines(top_space)\n        for line in lines:\n            yield from line\n            yield new_line\n        if bottom_space > 0:\n            yield from blank_lines(bottom_space)\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Measurement:\n        measurement = Measurement.get(console, options, self.renderable)\n        return measurement\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.console import Console, Group\n    from pip._vendor.rich.highlighter import ReprHighlighter\n    from pip._vendor.rich.panel import Panel\n\n    highlighter = ReprHighlighter()\n    console = Console()\n\n    panel = Panel(\n        Group(\n            Align.left(highlighter(\"align='left'\")),\n            Align.center(highlighter(\"align='center'\")),\n            Align.right(highlighter(\"align='right'\")),\n        ),\n        width=60,\n        style=\"on dark_blue\",\n        title=\"Algin\",\n    )\n\n    console.print(\n        Align.center(panel, vertical=\"middle\", style=\"on red\", height=console.height)\n    )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/ansi.py",
    "content": "import re\nimport sys\nfrom contextlib import suppress\nfrom typing import Iterable, NamedTuple, Optional\n\nfrom .color import Color\nfrom .style import Style\nfrom .text import Text\n\nre_ansi = re.compile(\n    r\"\"\"\n(?:\\x1b\\](.*?)\\x1b\\\\)|\n(?:\\x1b([(@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~]))\n\"\"\",\n    re.VERBOSE,\n)\n\n\nclass _AnsiToken(NamedTuple):\n    \"\"\"Result of ansi tokenized string.\"\"\"\n\n    plain: str = \"\"\n    sgr: Optional[str] = \"\"\n    osc: Optional[str] = \"\"\n\n\ndef _ansi_tokenize(ansi_text: str) -> Iterable[_AnsiToken]:\n    \"\"\"Tokenize a string in to plain text and ANSI codes.\n\n    Args:\n        ansi_text (str): A String containing ANSI codes.\n\n    Yields:\n        AnsiToken: A named tuple of (plain, sgr, osc)\n    \"\"\"\n\n    position = 0\n    sgr: Optional[str]\n    osc: Optional[str]\n    for match in re_ansi.finditer(ansi_text):\n        start, end = match.span(0)\n        osc, sgr = match.groups()\n        if start > position:\n            yield _AnsiToken(ansi_text[position:start])\n        if sgr:\n            if sgr.endswith(\"m\"):\n                yield _AnsiToken(\"\", sgr[1:-1], osc)\n        else:\n            yield _AnsiToken(\"\", sgr, osc)\n        position = end\n    if position < len(ansi_text):\n        yield _AnsiToken(ansi_text[position:])\n\n\nSGR_STYLE_MAP = {\n    1: \"bold\",\n    2: \"dim\",\n    3: \"italic\",\n    4: \"underline\",\n    5: \"blink\",\n    6: \"blink2\",\n    7: \"reverse\",\n    8: \"conceal\",\n    9: \"strike\",\n    21: \"underline2\",\n    22: \"not dim not bold\",\n    23: \"not italic\",\n    24: \"not underline\",\n    25: \"not blink\",\n    26: \"not blink2\",\n    27: \"not reverse\",\n    28: \"not conceal\",\n    29: \"not strike\",\n    30: \"color(0)\",\n    31: \"color(1)\",\n    32: \"color(2)\",\n    33: \"color(3)\",\n    34: \"color(4)\",\n    35: \"color(5)\",\n    36: \"color(6)\",\n    37: \"color(7)\",\n    39: \"default\",\n    40: \"on color(0)\",\n    41: \"on color(1)\",\n    42: \"on color(2)\",\n    43: \"on color(3)\",\n    44: \"on color(4)\",\n    45: \"on color(5)\",\n    46: \"on color(6)\",\n    47: \"on color(7)\",\n    49: \"on default\",\n    51: \"frame\",\n    52: \"encircle\",\n    53: \"overline\",\n    54: \"not frame not encircle\",\n    55: \"not overline\",\n    90: \"color(8)\",\n    91: \"color(9)\",\n    92: \"color(10)\",\n    93: \"color(11)\",\n    94: \"color(12)\",\n    95: \"color(13)\",\n    96: \"color(14)\",\n    97: \"color(15)\",\n    100: \"on color(8)\",\n    101: \"on color(9)\",\n    102: \"on color(10)\",\n    103: \"on color(11)\",\n    104: \"on color(12)\",\n    105: \"on color(13)\",\n    106: \"on color(14)\",\n    107: \"on color(15)\",\n}\n\n\nclass AnsiDecoder:\n    \"\"\"Translate ANSI code in to styled Text.\"\"\"\n\n    def __init__(self) -> None:\n        self.style = Style.null()\n\n    def decode(self, terminal_text: str) -> Iterable[Text]:\n        \"\"\"Decode ANSI codes in an interable of lines.\n\n        Args:\n            lines (Iterable[str]): An iterable of lines of terminal output.\n\n        Yields:\n            Text: Marked up Text.\n        \"\"\"\n        for line in terminal_text.splitlines():\n            yield self.decode_line(line)\n\n    def decode_line(self, line: str) -> Text:\n        \"\"\"Decode a line containing ansi codes.\n\n        Args:\n            line (str): A line of terminal output.\n\n        Returns:\n            Text: A Text instance marked up according to ansi codes.\n        \"\"\"\n        from_ansi = Color.from_ansi\n        from_rgb = Color.from_rgb\n        _Style = Style\n        text = Text()\n        append = text.append\n        line = line.rsplit(\"\\r\", 1)[-1]\n        for plain_text, sgr, osc in _ansi_tokenize(line):\n            if plain_text:\n                append(plain_text, self.style or None)\n            elif osc is not None:\n                if osc.startswith(\"8;\"):\n                    _params, semicolon, link = osc[2:].partition(\";\")\n                    if semicolon:\n                        self.style = self.style.update_link(link or None)\n            elif sgr is not None:\n                # Translate in to semi-colon separated codes\n                # Ignore invalid codes, because we want to be lenient\n                codes = [\n                    min(255, int(_code) if _code else 0)\n                    for _code in sgr.split(\";\")\n                    if _code.isdigit() or _code == \"\"\n                ]\n                iter_codes = iter(codes)\n                for code in iter_codes:\n                    if code == 0:\n                        # reset\n                        self.style = _Style.null()\n                    elif code in SGR_STYLE_MAP:\n                        # styles\n                        self.style += _Style.parse(SGR_STYLE_MAP[code])\n                    elif code == 38:\n                        #  Foreground\n                        with suppress(StopIteration):\n                            color_type = next(iter_codes)\n                            if color_type == 5:\n                                self.style += _Style.from_color(\n                                    from_ansi(next(iter_codes))\n                                )\n                            elif color_type == 2:\n                                self.style += _Style.from_color(\n                                    from_rgb(\n                                        next(iter_codes),\n                                        next(iter_codes),\n                                        next(iter_codes),\n                                    )\n                                )\n                    elif code == 48:\n                        # Background\n                        with suppress(StopIteration):\n                            color_type = next(iter_codes)\n                            if color_type == 5:\n                                self.style += _Style.from_color(\n                                    None, from_ansi(next(iter_codes))\n                                )\n                            elif color_type == 2:\n                                self.style += _Style.from_color(\n                                    None,\n                                    from_rgb(\n                                        next(iter_codes),\n                                        next(iter_codes),\n                                        next(iter_codes),\n                                    ),\n                                )\n\n        return text\n\n\nif sys.platform != \"win32\" and __name__ == \"__main__\":  # pragma: no cover\n    import io\n    import os\n    import pty\n    import sys\n\n    decoder = AnsiDecoder()\n\n    stdout = io.BytesIO()\n\n    def read(fd: int) -> bytes:\n        data = os.read(fd, 1024)\n        stdout.write(data)\n        return data\n\n    pty.spawn(sys.argv[1:], read)\n\n    from .console import Console\n\n    console = Console(record=True)\n\n    stdout_result = stdout.getvalue().decode(\"utf-8\")\n    print(stdout_result)\n\n    for line in decoder.decode(stdout_result):\n        console.print(line)\n\n    console.save_html(\"stdout.html\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/bar.py",
    "content": "from typing import Optional, Union\n\nfrom .color import Color\nfrom .console import Console, ConsoleOptions, RenderResult\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .segment import Segment\nfrom .style import Style\n\n# There are left-aligned characters for 1/8 to 7/8, but\n# the right-aligned characters exist only for 1/8 and 4/8.\nBEGIN_BLOCK_ELEMENTS = [\"█\", \"█\", \"█\", \"▐\", \"▐\", \"▐\", \"▕\", \"▕\"]\nEND_BLOCK_ELEMENTS = [\" \", \"▏\", \"▎\", \"▍\", \"▌\", \"▋\", \"▊\", \"▉\"]\nFULL_BLOCK = \"█\"\n\n\nclass Bar(JupyterMixin):\n    \"\"\"Renders a solid block bar.\n\n    Args:\n        size (float): Value for the end of the bar.\n        begin (float): Begin point (between 0 and size, inclusive).\n        end (float): End point (between 0 and size, inclusive).\n        width (int, optional): Width of the bar, or ``None`` for maximum width. Defaults to None.\n        color (Union[Color, str], optional): Color of the bar. Defaults to \"default\".\n        bgcolor (Union[Color, str], optional): Color of bar background. Defaults to \"default\".\n    \"\"\"\n\n    def __init__(\n        self,\n        size: float,\n        begin: float,\n        end: float,\n        *,\n        width: Optional[int] = None,\n        color: Union[Color, str] = \"default\",\n        bgcolor: Union[Color, str] = \"default\",\n    ):\n        self.size = size\n        self.begin = max(begin, 0)\n        self.end = min(end, size)\n        self.width = width\n        self.style = Style(color=color, bgcolor=bgcolor)\n\n    def __repr__(self) -> str:\n        return f\"Bar({self.size}, {self.begin}, {self.end})\"\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n\n        width = min(\n            self.width if self.width is not None else options.max_width,\n            options.max_width,\n        )\n\n        if self.begin >= self.end:\n            yield Segment(\" \" * width, self.style)\n            yield Segment.line()\n            return\n\n        prefix_complete_eights = int(width * 8 * self.begin / self.size)\n        prefix_bar_count = prefix_complete_eights // 8\n        prefix_eights_count = prefix_complete_eights % 8\n\n        body_complete_eights = int(width * 8 * self.end / self.size)\n        body_bar_count = body_complete_eights // 8\n        body_eights_count = body_complete_eights % 8\n\n        # When start and end fall into the same cell, we ideally should render\n        # a symbol that's \"center-aligned\", but there is no good symbol in Unicode.\n        # In this case, we fall back to right-aligned block symbol for simplicity.\n\n        prefix = \" \" * prefix_bar_count\n        if prefix_eights_count:\n            prefix += BEGIN_BLOCK_ELEMENTS[prefix_eights_count]\n\n        body = FULL_BLOCK * body_bar_count\n        if body_eights_count:\n            body += END_BLOCK_ELEMENTS[body_eights_count]\n\n        suffix = \" \" * (width - len(body))\n\n        yield Segment(prefix + body[len(prefix) :] + suffix, self.style)\n        yield Segment.line()\n\n    def __rich_measure__(\n        self, console: Console, options: ConsoleOptions\n    ) -> Measurement:\n        return (\n            Measurement(self.width, self.width)\n            if self.width is not None\n            else Measurement(4, options.max_width)\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/box.py",
    "content": "import sys\nfrom typing import TYPE_CHECKING, Iterable, List\n\nif sys.version_info >= (3, 8):\n    from typing import Literal\nelse:\n    from pip._vendor.typing_extensions import Literal  # pragma: no cover\n\n\nfrom ._loop import loop_last\n\nif TYPE_CHECKING:\n    from pip._vendor.rich.console import ConsoleOptions\n\n\nclass Box:\n    \"\"\"Defines characters to render boxes.\n\n    ┌─┬┐ top\n    │ ││ head\n    ├─┼┤ head_row\n    │ ││ mid\n    ├─┼┤ row\n    ├─┼┤ foot_row\n    │ ││ foot\n    └─┴┘ bottom\n\n    Args:\n        box (str): Characters making up box.\n        ascii (bool, optional): True if this box uses ascii characters only. Default is False.\n    \"\"\"\n\n    def __init__(self, box: str, *, ascii: bool = False) -> None:\n        self._box = box\n        self.ascii = ascii\n        line1, line2, line3, line4, line5, line6, line7, line8 = box.splitlines()\n        # top\n        self.top_left, self.top, self.top_divider, self.top_right = iter(line1)\n        # head\n        self.head_left, _, self.head_vertical, self.head_right = iter(line2)\n        # head_row\n        (\n            self.head_row_left,\n            self.head_row_horizontal,\n            self.head_row_cross,\n            self.head_row_right,\n        ) = iter(line3)\n\n        # mid\n        self.mid_left, _, self.mid_vertical, self.mid_right = iter(line4)\n        # row\n        self.row_left, self.row_horizontal, self.row_cross, self.row_right = iter(line5)\n        # foot_row\n        (\n            self.foot_row_left,\n            self.foot_row_horizontal,\n            self.foot_row_cross,\n            self.foot_row_right,\n        ) = iter(line6)\n        # foot\n        self.foot_left, _, self.foot_vertical, self.foot_right = iter(line7)\n        # bottom\n        self.bottom_left, self.bottom, self.bottom_divider, self.bottom_right = iter(\n            line8\n        )\n\n    def __repr__(self) -> str:\n        return \"Box(...)\"\n\n    def __str__(self) -> str:\n        return self._box\n\n    def substitute(self, options: \"ConsoleOptions\", safe: bool = True) -> \"Box\":\n        \"\"\"Substitute this box for another if it won't render due to platform issues.\n\n        Args:\n            options (ConsoleOptions): Console options used in rendering.\n            safe (bool, optional): Substitute this for another Box if there are known problems\n                displaying on the platform (currently only relevant on Windows). Default is True.\n\n        Returns:\n            Box: A different Box or the same Box.\n        \"\"\"\n        box = self\n        if options.legacy_windows and safe:\n            box = LEGACY_WINDOWS_SUBSTITUTIONS.get(box, box)\n        if options.ascii_only and not box.ascii:\n            box = ASCII\n        return box\n\n    def get_plain_headed_box(self) -> \"Box\":\n        \"\"\"If this box uses special characters for the borders of the header, then\n        return the equivalent box that does not.\n\n        Returns:\n            Box: The most similar Box that doesn't use header-specific box characters.\n                If the current Box already satisfies this criterion, then it's returned.\n        \"\"\"\n        return PLAIN_HEADED_SUBSTITUTIONS.get(self, self)\n\n    def get_top(self, widths: Iterable[int]) -> str:\n        \"\"\"Get the top of a simple box.\n\n        Args:\n            widths (List[int]): Widths of columns.\n\n        Returns:\n            str: A string of box characters.\n        \"\"\"\n\n        parts: List[str] = []\n        append = parts.append\n        append(self.top_left)\n        for last, width in loop_last(widths):\n            append(self.top * width)\n            if not last:\n                append(self.top_divider)\n        append(self.top_right)\n        return \"\".join(parts)\n\n    def get_row(\n        self,\n        widths: Iterable[int],\n        level: Literal[\"head\", \"row\", \"foot\", \"mid\"] = \"row\",\n        edge: bool = True,\n    ) -> str:\n        \"\"\"Get the top of a simple box.\n\n        Args:\n            width (List[int]): Widths of columns.\n\n        Returns:\n            str: A string of box characters.\n        \"\"\"\n        if level == \"head\":\n            left = self.head_row_left\n            horizontal = self.head_row_horizontal\n            cross = self.head_row_cross\n            right = self.head_row_right\n        elif level == \"row\":\n            left = self.row_left\n            horizontal = self.row_horizontal\n            cross = self.row_cross\n            right = self.row_right\n        elif level == \"mid\":\n            left = self.mid_left\n            horizontal = \" \"\n            cross = self.mid_vertical\n            right = self.mid_right\n        elif level == \"foot\":\n            left = self.foot_row_left\n            horizontal = self.foot_row_horizontal\n            cross = self.foot_row_cross\n            right = self.foot_row_right\n        else:\n            raise ValueError(\"level must be 'head', 'row' or 'foot'\")\n\n        parts: List[str] = []\n        append = parts.append\n        if edge:\n            append(left)\n        for last, width in loop_last(widths):\n            append(horizontal * width)\n            if not last:\n                append(cross)\n        if edge:\n            append(right)\n        return \"\".join(parts)\n\n    def get_bottom(self, widths: Iterable[int]) -> str:\n        \"\"\"Get the bottom of a simple box.\n\n        Args:\n            widths (List[int]): Widths of columns.\n\n        Returns:\n            str: A string of box characters.\n        \"\"\"\n\n        parts: List[str] = []\n        append = parts.append\n        append(self.bottom_left)\n        for last, width in loop_last(widths):\n            append(self.bottom * width)\n            if not last:\n                append(self.bottom_divider)\n        append(self.bottom_right)\n        return \"\".join(parts)\n\n\nASCII: Box = Box(\n    \"\"\"\\\n+--+\n| ||\n|-+|\n| ||\n|-+|\n|-+|\n| ||\n+--+\n\"\"\",\n    ascii=True,\n)\n\nASCII2: Box = Box(\n    \"\"\"\\\n+-++\n| ||\n+-++\n| ||\n+-++\n+-++\n| ||\n+-++\n\"\"\",\n    ascii=True,\n)\n\nASCII_DOUBLE_HEAD: Box = Box(\n    \"\"\"\\\n+-++\n| ||\n+=++\n| ||\n+-++\n+-++\n| ||\n+-++\n\"\"\",\n    ascii=True,\n)\n\nSQUARE: Box = Box(\n    \"\"\"\\\n┌─┬┐\n│ ││\n├─┼┤\n│ ││\n├─┼┤\n├─┼┤\n│ ││\n└─┴┘\n\"\"\"\n)\n\nSQUARE_DOUBLE_HEAD: Box = Box(\n    \"\"\"\\\n┌─┬┐\n│ ││\n╞═╪╡\n│ ││\n├─┼┤\n├─┼┤\n│ ││\n└─┴┘\n\"\"\"\n)\n\nMINIMAL: Box = Box(\n    \"\"\"\\\n  ╷ \n  │ \n╶─┼╴\n  │ \n╶─┼╴\n╶─┼╴\n  │ \n  ╵ \n\"\"\"\n)\n\n\nMINIMAL_HEAVY_HEAD: Box = Box(\n    \"\"\"\\\n  ╷ \n  │ \n╺━┿╸\n  │ \n╶─┼╴\n╶─┼╴\n  │ \n  ╵ \n\"\"\"\n)\n\nMINIMAL_DOUBLE_HEAD: Box = Box(\n    \"\"\"\\\n  ╷ \n  │ \n ═╪ \n  │ \n ─┼ \n ─┼ \n  │ \n  ╵ \n\"\"\"\n)\n\n\nSIMPLE: Box = Box(\n    \"\"\"\\\n    \n    \n ── \n    \n    \n ── \n    \n    \n\"\"\"\n)\n\nSIMPLE_HEAD: Box = Box(\n    \"\"\"\\\n    \n    \n ── \n    \n    \n    \n    \n    \n\"\"\"\n)\n\n\nSIMPLE_HEAVY: Box = Box(\n    \"\"\"\\\n    \n    \n ━━ \n    \n    \n ━━ \n    \n    \n\"\"\"\n)\n\n\nHORIZONTALS: Box = Box(\n    \"\"\"\\\n ── \n    \n ── \n    \n ── \n ── \n    \n ── \n\"\"\"\n)\n\nROUNDED: Box = Box(\n    \"\"\"\\\n╭─┬╮\n│ ││\n├─┼┤\n│ ││\n├─┼┤\n├─┼┤\n│ ││\n╰─┴╯\n\"\"\"\n)\n\nHEAVY: Box = Box(\n    \"\"\"\\\n┏━┳┓\n┃ ┃┃\n┣━╋┫\n┃ ┃┃\n┣━╋┫\n┣━╋┫\n┃ ┃┃\n┗━┻┛\n\"\"\"\n)\n\nHEAVY_EDGE: Box = Box(\n    \"\"\"\\\n┏━┯┓\n┃ │┃\n┠─┼┨\n┃ │┃\n┠─┼┨\n┠─┼┨\n┃ │┃\n┗━┷┛\n\"\"\"\n)\n\nHEAVY_HEAD: Box = Box(\n    \"\"\"\\\n┏━┳┓\n┃ ┃┃\n┡━╇┩\n│ ││\n├─┼┤\n├─┼┤\n│ ││\n└─┴┘\n\"\"\"\n)\n\nDOUBLE: Box = Box(\n    \"\"\"\\\n╔═╦╗\n║ ║║\n╠═╬╣\n║ ║║\n╠═╬╣\n╠═╬╣\n║ ║║\n╚═╩╝\n\"\"\"\n)\n\nDOUBLE_EDGE: Box = Box(\n    \"\"\"\\\n╔═╤╗\n║ │║\n╟─┼╢\n║ │║\n╟─┼╢\n╟─┼╢\n║ │║\n╚═╧╝\n\"\"\"\n)\n\nMARKDOWN: Box = Box(\n    \"\"\"\\\n    \n| ||\n|-||\n| ||\n|-||\n|-||\n| ||\n    \n\"\"\",\n    ascii=True,\n)\n\n# Map Boxes that don't render with raster fonts on to equivalent that do\nLEGACY_WINDOWS_SUBSTITUTIONS = {\n    ROUNDED: SQUARE,\n    MINIMAL_HEAVY_HEAD: MINIMAL,\n    SIMPLE_HEAVY: SIMPLE,\n    HEAVY: SQUARE,\n    HEAVY_EDGE: SQUARE,\n    HEAVY_HEAD: SQUARE,\n}\n\n# Map headed boxes to their headerless equivalents\nPLAIN_HEADED_SUBSTITUTIONS = {\n    HEAVY_HEAD: SQUARE,\n    SQUARE_DOUBLE_HEAD: SQUARE,\n    MINIMAL_DOUBLE_HEAD: MINIMAL,\n    MINIMAL_HEAVY_HEAD: MINIMAL,\n    ASCII_DOUBLE_HEAD: ASCII2,\n}\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n\n    from pip._vendor.rich.columns import Columns\n    from pip._vendor.rich.panel import Panel\n\n    from . import box as box\n    from .console import Console\n    from .table import Table\n    from .text import Text\n\n    console = Console(record=True)\n\n    BOXES = [\n        \"ASCII\",\n        \"ASCII2\",\n        \"ASCII_DOUBLE_HEAD\",\n        \"SQUARE\",\n        \"SQUARE_DOUBLE_HEAD\",\n        \"MINIMAL\",\n        \"MINIMAL_HEAVY_HEAD\",\n        \"MINIMAL_DOUBLE_HEAD\",\n        \"SIMPLE\",\n        \"SIMPLE_HEAD\",\n        \"SIMPLE_HEAVY\",\n        \"HORIZONTALS\",\n        \"ROUNDED\",\n        \"HEAVY\",\n        \"HEAVY_EDGE\",\n        \"HEAVY_HEAD\",\n        \"DOUBLE\",\n        \"DOUBLE_EDGE\",\n        \"MARKDOWN\",\n    ]\n\n    console.print(Panel(\"[bold green]Box Constants\", style=\"green\"), justify=\"center\")\n    console.print()\n\n    columns = Columns(expand=True, padding=2)\n    for box_name in sorted(BOXES):\n        table = Table(\n            show_footer=True, style=\"dim\", border_style=\"not dim\", expand=True\n        )\n        table.add_column(\"Header 1\", \"Footer 1\")\n        table.add_column(\"Header 2\", \"Footer 2\")\n        table.add_row(\"Cell\", \"Cell\")\n        table.add_row(\"Cell\", \"Cell\")\n        table.box = getattr(box, box_name)\n        table.title = Text(f\"box.{box_name}\", style=\"magenta\")\n        columns.add_renderable(table)\n    console.print(columns)\n\n    # console.save_html(\"box.html\", inline_styles=True)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/cells.py",
    "content": "import re\nfrom functools import lru_cache\nfrom typing import Callable, List\n\nfrom ._cell_widths import CELL_WIDTHS\n\n# Regex to match sequence of the most common character ranges\n_is_single_cell_widths = re.compile(\"^[\\u0020-\\u006f\\u00a0\\u02ff\\u0370-\\u0482]*$\").match\n\n\n@lru_cache(4096)\ndef cached_cell_len(text: str) -> int:\n    \"\"\"Get the number of cells required to display text.\n\n    This method always caches, which may use up a lot of memory. It is recommended to use\n    `cell_len` over this method.\n\n    Args:\n        text (str): Text to display.\n\n    Returns:\n        int: Get the number of cells required to display text.\n    \"\"\"\n    _get_size = get_character_cell_size\n    total_size = sum(_get_size(character) for character in text)\n    return total_size\n\n\ndef cell_len(text: str, _cell_len: Callable[[str], int] = cached_cell_len) -> int:\n    \"\"\"Get the number of cells required to display text.\n\n    Args:\n        text (str): Text to display.\n\n    Returns:\n        int: Get the number of cells required to display text.\n    \"\"\"\n    if len(text) < 512:\n        return _cell_len(text)\n    _get_size = get_character_cell_size\n    total_size = sum(_get_size(character) for character in text)\n    return total_size\n\n\n@lru_cache(maxsize=4096)\ndef get_character_cell_size(character: str) -> int:\n    \"\"\"Get the cell size of a character.\n\n    Args:\n        character (str): A single character.\n\n    Returns:\n        int: Number of cells (0, 1 or 2) occupied by that character.\n    \"\"\"\n    return _get_codepoint_cell_size(ord(character))\n\n\n@lru_cache(maxsize=4096)\ndef _get_codepoint_cell_size(codepoint: int) -> int:\n    \"\"\"Get the cell size of a character.\n\n    Args:\n        character (str): A single character.\n\n    Returns:\n        int: Number of cells (0, 1 or 2) occupied by that character.\n    \"\"\"\n\n    _table = CELL_WIDTHS\n    lower_bound = 0\n    upper_bound = len(_table) - 1\n    index = (lower_bound + upper_bound) // 2\n    while True:\n        start, end, width = _table[index]\n        if codepoint < start:\n            upper_bound = index - 1\n        elif codepoint > end:\n            lower_bound = index + 1\n        else:\n            return 0 if width == -1 else width\n        if upper_bound < lower_bound:\n            break\n        index = (lower_bound + upper_bound) // 2\n    return 1\n\n\ndef set_cell_size(text: str, total: int) -> str:\n    \"\"\"Set the length of a string to fit within given number of cells.\"\"\"\n\n    if _is_single_cell_widths(text):\n        size = len(text)\n        if size < total:\n            return text + \" \" * (total - size)\n        return text[:total]\n\n    if total <= 0:\n        return \"\"\n    cell_size = cell_len(text)\n    if cell_size == total:\n        return text\n    if cell_size < total:\n        return text + \" \" * (total - cell_size)\n\n    start = 0\n    end = len(text)\n\n    # Binary search until we find the right size\n    while True:\n        pos = (start + end) // 2\n        before = text[: pos + 1]\n        before_len = cell_len(before)\n        if before_len == total + 1 and cell_len(before[-1]) == 2:\n            return before[:-1] + \" \"\n        if before_len == total:\n            return before\n        if before_len > total:\n            end = pos\n        else:\n            start = pos\n\n\n# TODO: This is inefficient\n# TODO: This might not work with CWJ type characters\ndef chop_cells(text: str, max_size: int, position: int = 0) -> List[str]:\n    \"\"\"Break text in to equal (cell) length strings, returning the characters in reverse\n    order\"\"\"\n    _get_character_cell_size = get_character_cell_size\n    characters = [\n        (character, _get_character_cell_size(character)) for character in text\n    ]\n    total_size = position\n    lines: List[List[str]] = [[]]\n    append = lines[-1].append\n\n    for character, size in reversed(characters):\n        if total_size + size > max_size:\n            lines.append([character])\n            append = lines[-1].append\n            total_size = size\n        else:\n            total_size += size\n            append(character)\n\n    return [\"\".join(line) for line in lines]\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n\n    print(get_character_cell_size(\"😽\"))\n    for line in chop_cells(\"\"\"这是对亚洲语言支持的测试。面对模棱两可的想法，拒绝猜测的诱惑。\"\"\", 8):\n        print(line)\n    for n in range(80, 1, -1):\n        print(set_cell_size(\"\"\"这是对亚洲语言支持的测试。面对模棱两可的想法，拒绝猜测的诱惑。\"\"\", n) + \"|\")\n        print(\"x\" * n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/color.py",
    "content": "import platform\nimport re\nfrom colorsys import rgb_to_hls\nfrom enum import IntEnum\nfrom functools import lru_cache\nfrom typing import TYPE_CHECKING, NamedTuple, Optional, Tuple\n\nfrom ._palettes import EIGHT_BIT_PALETTE, STANDARD_PALETTE, WINDOWS_PALETTE\nfrom .color_triplet import ColorTriplet\nfrom .repr import Result, rich_repr\nfrom .terminal_theme import DEFAULT_TERMINAL_THEME\n\nif TYPE_CHECKING:  # pragma: no cover\n    from .terminal_theme import TerminalTheme\n    from .text import Text\n\n\nWINDOWS = platform.system() == \"Windows\"\n\n\nclass ColorSystem(IntEnum):\n    \"\"\"One of the 3 color system supported by terminals.\"\"\"\n\n    STANDARD = 1\n    EIGHT_BIT = 2\n    TRUECOLOR = 3\n    WINDOWS = 4\n\n    def __repr__(self) -> str:\n        return f\"ColorSystem.{self.name}\"\n\n\nclass ColorType(IntEnum):\n    \"\"\"Type of color stored in Color class.\"\"\"\n\n    DEFAULT = 0\n    STANDARD = 1\n    EIGHT_BIT = 2\n    TRUECOLOR = 3\n    WINDOWS = 4\n\n    def __repr__(self) -> str:\n        return f\"ColorType.{self.name}\"\n\n\nANSI_COLOR_NAMES = {\n    \"black\": 0,\n    \"red\": 1,\n    \"green\": 2,\n    \"yellow\": 3,\n    \"blue\": 4,\n    \"magenta\": 5,\n    \"cyan\": 6,\n    \"white\": 7,\n    \"bright_black\": 8,\n    \"bright_red\": 9,\n    \"bright_green\": 10,\n    \"bright_yellow\": 11,\n    \"bright_blue\": 12,\n    \"bright_magenta\": 13,\n    \"bright_cyan\": 14,\n    \"bright_white\": 15,\n    \"grey0\": 16,\n    \"gray0\": 16,\n    \"navy_blue\": 17,\n    \"dark_blue\": 18,\n    \"blue3\": 20,\n    \"blue1\": 21,\n    \"dark_green\": 22,\n    \"deep_sky_blue4\": 25,\n    \"dodger_blue3\": 26,\n    \"dodger_blue2\": 27,\n    \"green4\": 28,\n    \"spring_green4\": 29,\n    \"turquoise4\": 30,\n    \"deep_sky_blue3\": 32,\n    \"dodger_blue1\": 33,\n    \"green3\": 40,\n    \"spring_green3\": 41,\n    \"dark_cyan\": 36,\n    \"light_sea_green\": 37,\n    \"deep_sky_blue2\": 38,\n    \"deep_sky_blue1\": 39,\n    \"spring_green2\": 47,\n    \"cyan3\": 43,\n    \"dark_turquoise\": 44,\n    \"turquoise2\": 45,\n    \"green1\": 46,\n    \"spring_green1\": 48,\n    \"medium_spring_green\": 49,\n    \"cyan2\": 50,\n    \"cyan1\": 51,\n    \"dark_red\": 88,\n    \"deep_pink4\": 125,\n    \"purple4\": 55,\n    \"purple3\": 56,\n    \"blue_violet\": 57,\n    \"orange4\": 94,\n    \"grey37\": 59,\n    \"gray37\": 59,\n    \"medium_purple4\": 60,\n    \"slate_blue3\": 62,\n    \"royal_blue1\": 63,\n    \"chartreuse4\": 64,\n    \"dark_sea_green4\": 71,\n    \"pale_turquoise4\": 66,\n    \"steel_blue\": 67,\n    \"steel_blue3\": 68,\n    \"cornflower_blue\": 69,\n    \"chartreuse3\": 76,\n    \"cadet_blue\": 73,\n    \"sky_blue3\": 74,\n    \"steel_blue1\": 81,\n    \"pale_green3\": 114,\n    \"sea_green3\": 78,\n    \"aquamarine3\": 79,\n    \"medium_turquoise\": 80,\n    \"chartreuse2\": 112,\n    \"sea_green2\": 83,\n    \"sea_green1\": 85,\n    \"aquamarine1\": 122,\n    \"dark_slate_gray2\": 87,\n    \"dark_magenta\": 91,\n    \"dark_violet\": 128,\n    \"purple\": 129,\n    \"light_pink4\": 95,\n    \"plum4\": 96,\n    \"medium_purple3\": 98,\n    \"slate_blue1\": 99,\n    \"yellow4\": 106,\n    \"wheat4\": 101,\n    \"grey53\": 102,\n    \"gray53\": 102,\n    \"light_slate_grey\": 103,\n    \"light_slate_gray\": 103,\n    \"medium_purple\": 104,\n    \"light_slate_blue\": 105,\n    \"dark_olive_green3\": 149,\n    \"dark_sea_green\": 108,\n    \"light_sky_blue3\": 110,\n    \"sky_blue2\": 111,\n    \"dark_sea_green3\": 150,\n    \"dark_slate_gray3\": 116,\n    \"sky_blue1\": 117,\n    \"chartreuse1\": 118,\n    \"light_green\": 120,\n    \"pale_green1\": 156,\n    \"dark_slate_gray1\": 123,\n    \"red3\": 160,\n    \"medium_violet_red\": 126,\n    \"magenta3\": 164,\n    \"dark_orange3\": 166,\n    \"indian_red\": 167,\n    \"hot_pink3\": 168,\n    \"medium_orchid3\": 133,\n    \"medium_orchid\": 134,\n    \"medium_purple2\": 140,\n    \"dark_goldenrod\": 136,\n    \"light_salmon3\": 173,\n    \"rosy_brown\": 138,\n    \"grey63\": 139,\n    \"gray63\": 139,\n    \"medium_purple1\": 141,\n    \"gold3\": 178,\n    \"dark_khaki\": 143,\n    \"navajo_white3\": 144,\n    \"grey69\": 145,\n    \"gray69\": 145,\n    \"light_steel_blue3\": 146,\n    \"light_steel_blue\": 147,\n    \"yellow3\": 184,\n    \"dark_sea_green2\": 157,\n    \"light_cyan3\": 152,\n    \"light_sky_blue1\": 153,\n    \"green_yellow\": 154,\n    \"dark_olive_green2\": 155,\n    \"dark_sea_green1\": 193,\n    \"pale_turquoise1\": 159,\n    \"deep_pink3\": 162,\n    \"magenta2\": 200,\n    \"hot_pink2\": 169,\n    \"orchid\": 170,\n    \"medium_orchid1\": 207,\n    \"orange3\": 172,\n    \"light_pink3\": 174,\n    \"pink3\": 175,\n    \"plum3\": 176,\n    \"violet\": 177,\n    \"light_goldenrod3\": 179,\n    \"tan\": 180,\n    \"misty_rose3\": 181,\n    \"thistle3\": 182,\n    \"plum2\": 183,\n    \"khaki3\": 185,\n    \"light_goldenrod2\": 222,\n    \"light_yellow3\": 187,\n    \"grey84\": 188,\n    \"gray84\": 188,\n    \"light_steel_blue1\": 189,\n    \"yellow2\": 190,\n    \"dark_olive_green1\": 192,\n    \"honeydew2\": 194,\n    \"light_cyan1\": 195,\n    \"red1\": 196,\n    \"deep_pink2\": 197,\n    \"deep_pink1\": 199,\n    \"magenta1\": 201,\n    \"orange_red1\": 202,\n    \"indian_red1\": 204,\n    \"hot_pink\": 206,\n    \"dark_orange\": 208,\n    \"salmon1\": 209,\n    \"light_coral\": 210,\n    \"pale_violet_red1\": 211,\n    \"orchid2\": 212,\n    \"orchid1\": 213,\n    \"orange1\": 214,\n    \"sandy_brown\": 215,\n    \"light_salmon1\": 216,\n    \"light_pink1\": 217,\n    \"pink1\": 218,\n    \"plum1\": 219,\n    \"gold1\": 220,\n    \"navajo_white1\": 223,\n    \"misty_rose1\": 224,\n    \"thistle1\": 225,\n    \"yellow1\": 226,\n    \"light_goldenrod1\": 227,\n    \"khaki1\": 228,\n    \"wheat1\": 229,\n    \"cornsilk1\": 230,\n    \"grey100\": 231,\n    \"gray100\": 231,\n    \"grey3\": 232,\n    \"gray3\": 232,\n    \"grey7\": 233,\n    \"gray7\": 233,\n    \"grey11\": 234,\n    \"gray11\": 234,\n    \"grey15\": 235,\n    \"gray15\": 235,\n    \"grey19\": 236,\n    \"gray19\": 236,\n    \"grey23\": 237,\n    \"gray23\": 237,\n    \"grey27\": 238,\n    \"gray27\": 238,\n    \"grey30\": 239,\n    \"gray30\": 239,\n    \"grey35\": 240,\n    \"gray35\": 240,\n    \"grey39\": 241,\n    \"gray39\": 241,\n    \"grey42\": 242,\n    \"gray42\": 242,\n    \"grey46\": 243,\n    \"gray46\": 243,\n    \"grey50\": 244,\n    \"gray50\": 244,\n    \"grey54\": 245,\n    \"gray54\": 245,\n    \"grey58\": 246,\n    \"gray58\": 246,\n    \"grey62\": 247,\n    \"gray62\": 247,\n    \"grey66\": 248,\n    \"gray66\": 248,\n    \"grey70\": 249,\n    \"gray70\": 249,\n    \"grey74\": 250,\n    \"gray74\": 250,\n    \"grey78\": 251,\n    \"gray78\": 251,\n    \"grey82\": 252,\n    \"gray82\": 252,\n    \"grey85\": 253,\n    \"gray85\": 253,\n    \"grey89\": 254,\n    \"gray89\": 254,\n    \"grey93\": 255,\n    \"gray93\": 255,\n}\n\n\nclass ColorParseError(Exception):\n    \"\"\"The color could not be parsed.\"\"\"\n\n\nRE_COLOR = re.compile(\n    r\"\"\"^\n\\#([0-9a-f]{6})$|\ncolor\\(([0-9]{1,3})\\)$|\nrgb\\(([\\d\\s,]+)\\)$\n\"\"\",\n    re.VERBOSE,\n)\n\n\n@rich_repr\nclass Color(NamedTuple):\n    \"\"\"Terminal color definition.\"\"\"\n\n    name: str\n    \"\"\"The name of the color (typically the input to Color.parse).\"\"\"\n    type: ColorType\n    \"\"\"The type of the color.\"\"\"\n    number: Optional[int] = None\n    \"\"\"The color number, if a standard color, or None.\"\"\"\n    triplet: Optional[ColorTriplet] = None\n    \"\"\"A triplet of color components, if an RGB color.\"\"\"\n\n    def __rich__(self) -> \"Text\":\n        \"\"\"Dispays the actual color if Rich printed.\"\"\"\n        from .style import Style\n        from .text import Text\n\n        return Text.assemble(\n            f\"<color {self.name!r} ({self.type.name.lower()})\",\n            (\"⬤\", Style(color=self)),\n            \" >\",\n        )\n\n    def __rich_repr__(self) -> Result:\n        yield self.name\n        yield self.type\n        yield \"number\", self.number, None\n        yield \"triplet\", self.triplet, None\n\n    @property\n    def system(self) -> ColorSystem:\n        \"\"\"Get the native color system for this color.\"\"\"\n        if self.type == ColorType.DEFAULT:\n            return ColorSystem.STANDARD\n        return ColorSystem(int(self.type))\n\n    @property\n    def is_system_defined(self) -> bool:\n        \"\"\"Check if the color is ultimately defined by the system.\"\"\"\n        return self.system not in (ColorSystem.EIGHT_BIT, ColorSystem.TRUECOLOR)\n\n    @property\n    def is_default(self) -> bool:\n        \"\"\"Check if the color is a default color.\"\"\"\n        return self.type == ColorType.DEFAULT\n\n    def get_truecolor(\n        self, theme: Optional[\"TerminalTheme\"] = None, foreground: bool = True\n    ) -> ColorTriplet:\n        \"\"\"Get an equivalent color triplet for this color.\n\n        Args:\n            theme (TerminalTheme, optional): Optional terminal theme, or None to use default. Defaults to None.\n            foreground (bool, optional): True for a foreground color, or False for background. Defaults to True.\n\n        Returns:\n            ColorTriplet: A color triplet containing RGB components.\n        \"\"\"\n\n        if theme is None:\n            theme = DEFAULT_TERMINAL_THEME\n        if self.type == ColorType.TRUECOLOR:\n            assert self.triplet is not None\n            return self.triplet\n        elif self.type == ColorType.EIGHT_BIT:\n            assert self.number is not None\n            return EIGHT_BIT_PALETTE[self.number]\n        elif self.type == ColorType.STANDARD:\n            assert self.number is not None\n            return theme.ansi_colors[self.number]\n        elif self.type == ColorType.WINDOWS:\n            assert self.number is not None\n            return WINDOWS_PALETTE[self.number]\n        else:  # self.type == ColorType.DEFAULT:\n            assert self.number is None\n            return theme.foreground_color if foreground else theme.background_color\n\n    @classmethod\n    def from_ansi(cls, number: int) -> \"Color\":\n        \"\"\"Create a Color number from it's 8-bit ansi number.\n\n        Args:\n            number (int): A number between 0-255 inclusive.\n\n        Returns:\n            Color: A new Color instance.\n        \"\"\"\n        return cls(\n            name=f\"color({number})\",\n            type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT),\n            number=number,\n        )\n\n    @classmethod\n    def from_triplet(cls, triplet: \"ColorTriplet\") -> \"Color\":\n        \"\"\"Create a truecolor RGB color from a triplet of values.\n\n        Args:\n            triplet (ColorTriplet): A color triplet containing red, green and blue components.\n\n        Returns:\n            Color: A new color object.\n        \"\"\"\n        return cls(name=triplet.hex, type=ColorType.TRUECOLOR, triplet=triplet)\n\n    @classmethod\n    def from_rgb(cls, red: float, green: float, blue: float) -> \"Color\":\n        \"\"\"Create a truecolor from three color components in the range(0->255).\n\n        Args:\n            red (float): Red component in range 0-255.\n            green (float): Green component in range 0-255.\n            blue (float): Blue component in range 0-255.\n\n        Returns:\n            Color: A new color object.\n        \"\"\"\n        return cls.from_triplet(ColorTriplet(int(red), int(green), int(blue)))\n\n    @classmethod\n    def default(cls) -> \"Color\":\n        \"\"\"Get a Color instance representing the default color.\n\n        Returns:\n            Color: Default color.\n        \"\"\"\n        return cls(name=\"default\", type=ColorType.DEFAULT)\n\n    @classmethod\n    @lru_cache(maxsize=1024)\n    def parse(cls, color: str) -> \"Color\":\n        \"\"\"Parse a color definition.\"\"\"\n        original_color = color\n        color = color.lower().strip()\n\n        if color == \"default\":\n            return cls(color, type=ColorType.DEFAULT)\n\n        color_number = ANSI_COLOR_NAMES.get(color)\n        if color_number is not None:\n            return cls(\n                color,\n                type=(ColorType.STANDARD if color_number < 16 else ColorType.EIGHT_BIT),\n                number=color_number,\n            )\n\n        color_match = RE_COLOR.match(color)\n        if color_match is None:\n            raise ColorParseError(f\"{original_color!r} is not a valid color\")\n\n        color_24, color_8, color_rgb = color_match.groups()\n        if color_24:\n            triplet = ColorTriplet(\n                int(color_24[0:2], 16), int(color_24[2:4], 16), int(color_24[4:6], 16)\n            )\n            return cls(color, ColorType.TRUECOLOR, triplet=triplet)\n\n        elif color_8:\n            number = int(color_8)\n            if number > 255:\n                raise ColorParseError(f\"color number must be <= 255 in {color!r}\")\n            return cls(\n                color,\n                type=(ColorType.STANDARD if number < 16 else ColorType.EIGHT_BIT),\n                number=number,\n            )\n\n        else:  #  color_rgb:\n            components = color_rgb.split(\",\")\n            if len(components) != 3:\n                raise ColorParseError(\n                    f\"expected three components in {original_color!r}\"\n                )\n            red, green, blue = components\n            triplet = ColorTriplet(int(red), int(green), int(blue))\n            if not all(component <= 255 for component in triplet):\n                raise ColorParseError(\n                    f\"color components must be <= 255 in {original_color!r}\"\n                )\n            return cls(color, ColorType.TRUECOLOR, triplet=triplet)\n\n    @lru_cache(maxsize=1024)\n    def get_ansi_codes(self, foreground: bool = True) -> Tuple[str, ...]:\n        \"\"\"Get the ANSI escape codes for this color.\"\"\"\n        _type = self.type\n        if _type == ColorType.DEFAULT:\n            return (\"39\" if foreground else \"49\",)\n\n        elif _type == ColorType.WINDOWS:\n            number = self.number\n            assert number is not None\n            fore, back = (30, 40) if number < 8 else (82, 92)\n            return (str(fore + number if foreground else back + number),)\n\n        elif _type == ColorType.STANDARD:\n            number = self.number\n            assert number is not None\n            fore, back = (30, 40) if number < 8 else (82, 92)\n            return (str(fore + number if foreground else back + number),)\n\n        elif _type == ColorType.EIGHT_BIT:\n            assert self.number is not None\n            return (\"38\" if foreground else \"48\", \"5\", str(self.number))\n\n        else:  # self.standard == ColorStandard.TRUECOLOR:\n            assert self.triplet is not None\n            red, green, blue = self.triplet\n            return (\"38\" if foreground else \"48\", \"2\", str(red), str(green), str(blue))\n\n    @lru_cache(maxsize=1024)\n    def downgrade(self, system: ColorSystem) -> \"Color\":\n        \"\"\"Downgrade a color system to a system with fewer colors.\"\"\"\n\n        if self.type in [ColorType.DEFAULT, system]:\n            return self\n        # Convert to 8-bit color from truecolor color\n        if system == ColorSystem.EIGHT_BIT and self.system == ColorSystem.TRUECOLOR:\n            assert self.triplet is not None\n            red, green, blue = self.triplet.normalized\n            _h, l, s = rgb_to_hls(red, green, blue)\n            # If saturation is under 10% assume it is grayscale\n            if s < 0.1:\n                gray = round(l * 25.0)\n                if gray == 0:\n                    color_number = 16\n                elif gray == 25:\n                    color_number = 231\n                else:\n                    color_number = 231 + gray\n                return Color(self.name, ColorType.EIGHT_BIT, number=color_number)\n\n            color_number = (\n                16 + 36 * round(red * 5.0) + 6 * round(green * 5.0) + round(blue * 5.0)\n            )\n            return Color(self.name, ColorType.EIGHT_BIT, number=color_number)\n\n        # Convert to standard from truecolor or 8-bit\n        elif system == ColorSystem.STANDARD:\n            if self.system == ColorSystem.TRUECOLOR:\n                assert self.triplet is not None\n                triplet = self.triplet\n            else:  # self.system == ColorSystem.EIGHT_BIT\n                assert self.number is not None\n                triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number])\n\n            color_number = STANDARD_PALETTE.match(triplet)\n            return Color(self.name, ColorType.STANDARD, number=color_number)\n\n        elif system == ColorSystem.WINDOWS:\n            if self.system == ColorSystem.TRUECOLOR:\n                assert self.triplet is not None\n                triplet = self.triplet\n            else:  # self.system == ColorSystem.EIGHT_BIT\n                assert self.number is not None\n                if self.number < 16:\n                    return Color(self.name, ColorType.WINDOWS, number=self.number)\n                triplet = ColorTriplet(*EIGHT_BIT_PALETTE[self.number])\n\n            color_number = WINDOWS_PALETTE.match(triplet)\n            return Color(self.name, ColorType.WINDOWS, number=color_number)\n\n        return self\n\n\ndef parse_rgb_hex(hex_color: str) -> ColorTriplet:\n    \"\"\"Parse six hex characters in to RGB triplet.\"\"\"\n    assert len(hex_color) == 6, \"must be 6 characters\"\n    color = ColorTriplet(\n        int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16)\n    )\n    return color\n\n\ndef blend_rgb(\n    color1: ColorTriplet, color2: ColorTriplet, cross_fade: float = 0.5\n) -> ColorTriplet:\n    \"\"\"Blend one RGB color in to another.\"\"\"\n    r1, g1, b1 = color1\n    r2, g2, b2 = color2\n    new_color = ColorTriplet(\n        int(r1 + (r2 - r1) * cross_fade),\n        int(g1 + (g2 - g1) * cross_fade),\n        int(b1 + (b2 - b1) * cross_fade),\n    )\n    return new_color\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n\n    from .console import Console\n    from .table import Table\n    from .text import Text\n\n    console = Console()\n\n    table = Table(show_footer=False, show_edge=True)\n    table.add_column(\"Color\", width=10, overflow=\"ellipsis\")\n    table.add_column(\"Number\", justify=\"right\", style=\"yellow\")\n    table.add_column(\"Name\", style=\"green\")\n    table.add_column(\"Hex\", style=\"blue\")\n    table.add_column(\"RGB\", style=\"magenta\")\n\n    colors = sorted((v, k) for k, v in ANSI_COLOR_NAMES.items())\n    for color_number, name in colors:\n        if \"grey\" in name:\n            continue\n        color_cell = Text(\" \" * 10, style=f\"on {name}\")\n        if color_number < 16:\n            table.add_row(color_cell, f\"{color_number}\", Text(f'\"{name}\"'))\n        else:\n            color = EIGHT_BIT_PALETTE[color_number]  # type: ignore[has-type]\n            table.add_row(\n                color_cell, str(color_number), Text(f'\"{name}\"'), color.hex, color.rgb\n            )\n\n    console.print(table)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/color_triplet.py",
    "content": "from typing import NamedTuple, Tuple\n\n\nclass ColorTriplet(NamedTuple):\n    \"\"\"The red, green, and blue components of a color.\"\"\"\n\n    red: int\n    \"\"\"Red component in 0 to 255 range.\"\"\"\n    green: int\n    \"\"\"Green component in 0 to 255 range.\"\"\"\n    blue: int\n    \"\"\"Blue component in 0 to 255 range.\"\"\"\n\n    @property\n    def hex(self) -> str:\n        \"\"\"get the color triplet in CSS style.\"\"\"\n        red, green, blue = self\n        return f\"#{red:02x}{green:02x}{blue:02x}\"\n\n    @property\n    def rgb(self) -> str:\n        \"\"\"The color in RGB format.\n\n        Returns:\n            str: An rgb color, e.g. ``\"rgb(100,23,255)\"``.\n        \"\"\"\n        red, green, blue = self\n        return f\"rgb({red},{green},{blue})\"\n\n    @property\n    def normalized(self) -> Tuple[float, float, float]:\n        \"\"\"Convert components into floats between 0 and 1.\n\n        Returns:\n            Tuple[float, float, float]: A tuple of three normalized colour components.\n        \"\"\"\n        red, green, blue = self\n        return red / 255.0, green / 255.0, blue / 255.0\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/columns.py",
    "content": "from collections import defaultdict\nfrom itertools import chain\nfrom operator import itemgetter\nfrom typing import Dict, Iterable, List, Optional, Tuple\n\nfrom .align import Align, AlignMethod\nfrom .console import Console, ConsoleOptions, RenderableType, RenderResult\nfrom .constrain import Constrain\nfrom .measure import Measurement\nfrom .padding import Padding, PaddingDimensions\nfrom .table import Table\nfrom .text import TextType\nfrom .jupyter import JupyterMixin\n\n\nclass Columns(JupyterMixin):\n    \"\"\"Display renderables in neat columns.\n\n    Args:\n        renderables (Iterable[RenderableType]): Any number of Rich renderables (including str).\n        width (int, optional): The desired width of the columns, or None to auto detect. Defaults to None.\n        padding (PaddingDimensions, optional): Optional padding around cells. Defaults to (0, 1).\n        expand (bool, optional): Expand columns to full width. Defaults to False.\n        equal (bool, optional): Arrange in to equal sized columns. Defaults to False.\n        column_first (bool, optional): Align items from top to bottom (rather than left to right). Defaults to False.\n        right_to_left (bool, optional): Start column from right hand side. Defaults to False.\n        align (str, optional): Align value (\"left\", \"right\", or \"center\") or None for default. Defaults to None.\n        title (TextType, optional): Optional title for Columns.\n    \"\"\"\n\n    def __init__(\n        self,\n        renderables: Optional[Iterable[RenderableType]] = None,\n        padding: PaddingDimensions = (0, 1),\n        *,\n        width: Optional[int] = None,\n        expand: bool = False,\n        equal: bool = False,\n        column_first: bool = False,\n        right_to_left: bool = False,\n        align: Optional[AlignMethod] = None,\n        title: Optional[TextType] = None,\n    ) -> None:\n        self.renderables = list(renderables or [])\n        self.width = width\n        self.padding = padding\n        self.expand = expand\n        self.equal = equal\n        self.column_first = column_first\n        self.right_to_left = right_to_left\n        self.align: Optional[AlignMethod] = align\n        self.title = title\n\n    def add_renderable(self, renderable: RenderableType) -> None:\n        \"\"\"Add a renderable to the columns.\n\n        Args:\n            renderable (RenderableType): Any renderable object.\n        \"\"\"\n        self.renderables.append(renderable)\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        render_str = console.render_str\n        renderables = [\n            render_str(renderable) if isinstance(renderable, str) else renderable\n            for renderable in self.renderables\n        ]\n        if not renderables:\n            return\n        _top, right, _bottom, left = Padding.unpack(self.padding)\n        width_padding = max(left, right)\n        max_width = options.max_width\n        widths: Dict[int, int] = defaultdict(int)\n        column_count = len(renderables)\n\n        get_measurement = Measurement.get\n        renderable_widths = [\n            get_measurement(console, options, renderable).maximum\n            for renderable in renderables\n        ]\n        if self.equal:\n            renderable_widths = [max(renderable_widths)] * len(renderable_widths)\n\n        def iter_renderables(\n            column_count: int,\n        ) -> Iterable[Tuple[int, Optional[RenderableType]]]:\n            item_count = len(renderables)\n            if self.column_first:\n                width_renderables = list(zip(renderable_widths, renderables))\n\n                column_lengths: List[int] = [item_count // column_count] * column_count\n                for col_no in range(item_count % column_count):\n                    column_lengths[col_no] += 1\n\n                row_count = (item_count + column_count - 1) // column_count\n                cells = [[-1] * column_count for _ in range(row_count)]\n                row = col = 0\n                for index in range(item_count):\n                    cells[row][col] = index\n                    column_lengths[col] -= 1\n                    if column_lengths[col]:\n                        row += 1\n                    else:\n                        col += 1\n                        row = 0\n                for index in chain.from_iterable(cells):\n                    if index == -1:\n                        break\n                    yield width_renderables[index]\n            else:\n                yield from zip(renderable_widths, renderables)\n            # Pad odd elements with spaces\n            if item_count % column_count:\n                for _ in range(column_count - (item_count % column_count)):\n                    yield 0, None\n\n        table = Table.grid(padding=self.padding, collapse_padding=True, pad_edge=False)\n        table.expand = self.expand\n        table.title = self.title\n\n        if self.width is not None:\n            column_count = (max_width) // (self.width + width_padding)\n            for _ in range(column_count):\n                table.add_column(width=self.width)\n        else:\n            while column_count > 1:\n                widths.clear()\n                column_no = 0\n                for renderable_width, _ in iter_renderables(column_count):\n                    widths[column_no] = max(widths[column_no], renderable_width)\n                    total_width = sum(widths.values()) + width_padding * (\n                        len(widths) - 1\n                    )\n                    if total_width > max_width:\n                        column_count = len(widths) - 1\n                        break\n                    else:\n                        column_no = (column_no + 1) % column_count\n                else:\n                    break\n\n        get_renderable = itemgetter(1)\n        _renderables = [\n            get_renderable(_renderable)\n            for _renderable in iter_renderables(column_count)\n        ]\n        if self.equal:\n            _renderables = [\n                None\n                if renderable is None\n                else Constrain(renderable, renderable_widths[0])\n                for renderable in _renderables\n            ]\n        if self.align:\n            align = self.align\n            _Align = Align\n            _renderables = [\n                None if renderable is None else _Align(renderable, align)\n                for renderable in _renderables\n            ]\n\n        right_to_left = self.right_to_left\n        add_row = table.add_row\n        for start in range(0, len(_renderables), column_count):\n            row = _renderables[start : start + column_count]\n            if right_to_left:\n                row = row[::-1]\n            add_row(*row)\n        yield table\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import os\n\n    console = Console()\n\n    files = [f\"{i} {s}\" for i, s in enumerate(sorted(os.listdir()))]\n    columns = Columns(files, padding=(0, 1), expand=False, equal=False)\n    console.print(columns)\n    console.rule()\n    columns.column_first = True\n    console.print(columns)\n    columns.right_to_left = True\n    console.rule()\n    console.print(columns)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/console.py",
    "content": "import inspect\nimport io\nimport os\nimport platform\nimport sys\nimport threading\nimport zlib\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass, field\nfrom datetime import datetime\nfrom functools import wraps\nfrom getpass import getpass\nfrom html import escape\nfrom inspect import isclass\nfrom itertools import islice\nfrom math import ceil\nfrom time import monotonic\nfrom types import FrameType, ModuleType, TracebackType\nfrom typing import (\n    IO,\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    Mapping,\n    NamedTuple,\n    Optional,\n    TextIO,\n    Tuple,\n    Type,\n    Union,\n    cast,\n)\n\nif sys.version_info >= (3, 8):\n    from typing import Literal, Protocol, runtime_checkable\nelse:\n    from pip._vendor.typing_extensions import (\n        Literal,\n        Protocol,\n        runtime_checkable,\n    )  # pragma: no cover\n\nfrom . import errors, themes\nfrom ._emoji_replace import _emoji_replace\nfrom ._export_format import CONSOLE_HTML_FORMAT, CONSOLE_SVG_FORMAT\nfrom ._log_render import FormatTimeCallable, LogRender\nfrom .align import Align, AlignMethod\nfrom .color import ColorSystem, blend_rgb\nfrom .control import Control\nfrom .emoji import EmojiVariant\nfrom .highlighter import NullHighlighter, ReprHighlighter\nfrom .markup import render as render_markup\nfrom .measure import Measurement, measure_renderables\nfrom .pager import Pager, SystemPager\nfrom .pretty import Pretty, is_expandable\nfrom .protocol import rich_cast\nfrom .region import Region\nfrom .scope import render_scope\nfrom .screen import Screen\nfrom .segment import Segment\nfrom .style import Style, StyleType\nfrom .styled import Styled\nfrom .terminal_theme import DEFAULT_TERMINAL_THEME, SVG_EXPORT_THEME, TerminalTheme\nfrom .text import Text, TextType\nfrom .theme import Theme, ThemeStack\n\nif TYPE_CHECKING:\n    from ._windows import WindowsConsoleFeatures\n    from .live import Live\n    from .status import Status\n\nJUPYTER_DEFAULT_COLUMNS = 115\nJUPYTER_DEFAULT_LINES = 100\nWINDOWS = platform.system() == \"Windows\"\n\nHighlighterType = Callable[[Union[str, \"Text\"]], \"Text\"]\nJustifyMethod = Literal[\"default\", \"left\", \"center\", \"right\", \"full\"]\nOverflowMethod = Literal[\"fold\", \"crop\", \"ellipsis\", \"ignore\"]\n\n\nclass NoChange:\n    pass\n\n\nNO_CHANGE = NoChange()\n\ntry:\n    _STDIN_FILENO = sys.__stdin__.fileno()\nexcept Exception:\n    _STDIN_FILENO = 0\ntry:\n    _STDOUT_FILENO = sys.__stdout__.fileno()\nexcept Exception:\n    _STDOUT_FILENO = 1\ntry:\n    _STDERR_FILENO = sys.__stderr__.fileno()\nexcept Exception:\n    _STDERR_FILENO = 2\n\n_STD_STREAMS = (_STDIN_FILENO, _STDOUT_FILENO, _STDERR_FILENO)\n_STD_STREAMS_OUTPUT = (_STDOUT_FILENO, _STDERR_FILENO)\n\n\n_TERM_COLORS = {\"256color\": ColorSystem.EIGHT_BIT, \"16color\": ColorSystem.STANDARD}\n\n\nclass ConsoleDimensions(NamedTuple):\n    \"\"\"Size of the terminal.\"\"\"\n\n    width: int\n    \"\"\"The width of the console in 'cells'.\"\"\"\n    height: int\n    \"\"\"The height of the console in lines.\"\"\"\n\n\n@dataclass\nclass ConsoleOptions:\n    \"\"\"Options for __rich_console__ method.\"\"\"\n\n    size: ConsoleDimensions\n    \"\"\"Size of console.\"\"\"\n    legacy_windows: bool\n    \"\"\"legacy_windows: flag for legacy windows.\"\"\"\n    min_width: int\n    \"\"\"Minimum width of renderable.\"\"\"\n    max_width: int\n    \"\"\"Maximum width of renderable.\"\"\"\n    is_terminal: bool\n    \"\"\"True if the target is a terminal, otherwise False.\"\"\"\n    encoding: str\n    \"\"\"Encoding of terminal.\"\"\"\n    max_height: int\n    \"\"\"Height of container (starts as terminal)\"\"\"\n    justify: Optional[JustifyMethod] = None\n    \"\"\"Justify value override for renderable.\"\"\"\n    overflow: Optional[OverflowMethod] = None\n    \"\"\"Overflow value override for renderable.\"\"\"\n    no_wrap: Optional[bool] = False\n    \"\"\"Disable wrapping for text.\"\"\"\n    highlight: Optional[bool] = None\n    \"\"\"Highlight override for render_str.\"\"\"\n    markup: Optional[bool] = None\n    \"\"\"Enable markup when rendering strings.\"\"\"\n    height: Optional[int] = None\n\n    @property\n    def ascii_only(self) -> bool:\n        \"\"\"Check if renderables should use ascii only.\"\"\"\n        return not self.encoding.startswith(\"utf\")\n\n    def copy(self) -> \"ConsoleOptions\":\n        \"\"\"Return a copy of the options.\n\n        Returns:\n            ConsoleOptions: a copy of self.\n        \"\"\"\n        options: ConsoleOptions = ConsoleOptions.__new__(ConsoleOptions)\n        options.__dict__ = self.__dict__.copy()\n        return options\n\n    def update(\n        self,\n        *,\n        width: Union[int, NoChange] = NO_CHANGE,\n        min_width: Union[int, NoChange] = NO_CHANGE,\n        max_width: Union[int, NoChange] = NO_CHANGE,\n        justify: Union[Optional[JustifyMethod], NoChange] = NO_CHANGE,\n        overflow: Union[Optional[OverflowMethod], NoChange] = NO_CHANGE,\n        no_wrap: Union[Optional[bool], NoChange] = NO_CHANGE,\n        highlight: Union[Optional[bool], NoChange] = NO_CHANGE,\n        markup: Union[Optional[bool], NoChange] = NO_CHANGE,\n        height: Union[Optional[int], NoChange] = NO_CHANGE,\n    ) -> \"ConsoleOptions\":\n        \"\"\"Update values, return a copy.\"\"\"\n        options = self.copy()\n        if not isinstance(width, NoChange):\n            options.min_width = options.max_width = max(0, width)\n        if not isinstance(min_width, NoChange):\n            options.min_width = min_width\n        if not isinstance(max_width, NoChange):\n            options.max_width = max_width\n        if not isinstance(justify, NoChange):\n            options.justify = justify\n        if not isinstance(overflow, NoChange):\n            options.overflow = overflow\n        if not isinstance(no_wrap, NoChange):\n            options.no_wrap = no_wrap\n        if not isinstance(highlight, NoChange):\n            options.highlight = highlight\n        if not isinstance(markup, NoChange):\n            options.markup = markup\n        if not isinstance(height, NoChange):\n            if height is not None:\n                options.max_height = height\n            options.height = None if height is None else max(0, height)\n        return options\n\n    def update_width(self, width: int) -> \"ConsoleOptions\":\n        \"\"\"Update just the width, return a copy.\n\n        Args:\n            width (int): New width (sets both min_width and max_width)\n\n        Returns:\n            ~ConsoleOptions: New console options instance.\n        \"\"\"\n        options = self.copy()\n        options.min_width = options.max_width = max(0, width)\n        return options\n\n    def update_height(self, height: int) -> \"ConsoleOptions\":\n        \"\"\"Update the height, and return a copy.\n\n        Args:\n            height (int): New height\n\n        Returns:\n            ~ConsoleOptions: New Console options instance.\n        \"\"\"\n        options = self.copy()\n        options.max_height = options.height = height\n        return options\n\n    def reset_height(self) -> \"ConsoleOptions\":\n        \"\"\"Return a copy of the options with height set to ``None``.\n\n        Returns:\n            ~ConsoleOptions: New console options instance.\n        \"\"\"\n        options = self.copy()\n        options.height = None\n        return options\n\n    def update_dimensions(self, width: int, height: int) -> \"ConsoleOptions\":\n        \"\"\"Update the width and height, and return a copy.\n\n        Args:\n            width (int): New width (sets both min_width and max_width).\n            height (int): New height.\n\n        Returns:\n            ~ConsoleOptions: New console options instance.\n        \"\"\"\n        options = self.copy()\n        options.min_width = options.max_width = max(0, width)\n        options.height = options.max_height = height\n        return options\n\n\n@runtime_checkable\nclass RichCast(Protocol):\n    \"\"\"An object that may be 'cast' to a console renderable.\"\"\"\n\n    def __rich__(\n        self,\n    ) -> Union[\"ConsoleRenderable\", \"RichCast\", str]:  # pragma: no cover\n        ...\n\n\n@runtime_checkable\nclass ConsoleRenderable(Protocol):\n    \"\"\"An object that supports the console protocol.\"\"\"\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":  # pragma: no cover\n        ...\n\n\n# A type that may be rendered by Console.\nRenderableType = Union[ConsoleRenderable, RichCast, str]\n\n# The result of calling a __rich_console__ method.\nRenderResult = Iterable[Union[RenderableType, Segment]]\n\n_null_highlighter = NullHighlighter()\n\n\nclass CaptureError(Exception):\n    \"\"\"An error in the Capture context manager.\"\"\"\n\n\nclass NewLine:\n    \"\"\"A renderable to generate new line(s)\"\"\"\n\n    def __init__(self, count: int = 1) -> None:\n        self.count = count\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Iterable[Segment]:\n        yield Segment(\"\\n\" * self.count)\n\n\nclass ScreenUpdate:\n    \"\"\"Render a list of lines at a given offset.\"\"\"\n\n    def __init__(self, lines: List[List[Segment]], x: int, y: int) -> None:\n        self._lines = lines\n        self.x = x\n        self.y = y\n\n    def __rich_console__(\n        self, console: \"Console\", options: ConsoleOptions\n    ) -> RenderResult:\n        x = self.x\n        move_to = Control.move_to\n        for offset, line in enumerate(self._lines, self.y):\n            yield move_to(x, offset)\n            yield from line\n\n\nclass Capture:\n    \"\"\"Context manager to capture the result of printing to the console.\n    See :meth:`~rich.console.Console.capture` for how to use.\n\n    Args:\n        console (Console): A console instance to capture output.\n    \"\"\"\n\n    def __init__(self, console: \"Console\") -> None:\n        self._console = console\n        self._result: Optional[str] = None\n\n    def __enter__(self) -> \"Capture\":\n        self._console.begin_capture()\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self._result = self._console.end_capture()\n\n    def get(self) -> str:\n        \"\"\"Get the result of the capture.\"\"\"\n        if self._result is None:\n            raise CaptureError(\n                \"Capture result is not available until context manager exits.\"\n            )\n        return self._result\n\n\nclass ThemeContext:\n    \"\"\"A context manager to use a temporary theme. See :meth:`~rich.console.Console.use_theme` for usage.\"\"\"\n\n    def __init__(self, console: \"Console\", theme: Theme, inherit: bool = True) -> None:\n        self.console = console\n        self.theme = theme\n        self.inherit = inherit\n\n    def __enter__(self) -> \"ThemeContext\":\n        self.console.push_theme(self.theme)\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.console.pop_theme()\n\n\nclass PagerContext:\n    \"\"\"A context manager that 'pages' content. See :meth:`~rich.console.Console.pager` for usage.\"\"\"\n\n    def __init__(\n        self,\n        console: \"Console\",\n        pager: Optional[Pager] = None,\n        styles: bool = False,\n        links: bool = False,\n    ) -> None:\n        self._console = console\n        self.pager = SystemPager() if pager is None else pager\n        self.styles = styles\n        self.links = links\n\n    def __enter__(self) -> \"PagerContext\":\n        self._console._enter_buffer()\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        if exc_type is None:\n            with self._console._lock:\n                buffer: List[Segment] = self._console._buffer[:]\n                del self._console._buffer[:]\n                segments: Iterable[Segment] = buffer\n                if not self.styles:\n                    segments = Segment.strip_styles(segments)\n                elif not self.links:\n                    segments = Segment.strip_links(segments)\n                content = self._console._render_buffer(segments)\n            self.pager.show(content)\n        self._console._exit_buffer()\n\n\nclass ScreenContext:\n    \"\"\"A context manager that enables an alternative screen. See :meth:`~rich.console.Console.screen` for usage.\"\"\"\n\n    def __init__(\n        self, console: \"Console\", hide_cursor: bool, style: StyleType = \"\"\n    ) -> None:\n        self.console = console\n        self.hide_cursor = hide_cursor\n        self.screen = Screen(style=style)\n        self._changed = False\n\n    def update(\n        self, *renderables: RenderableType, style: Optional[StyleType] = None\n    ) -> None:\n        \"\"\"Update the screen.\n\n        Args:\n            renderable (RenderableType, optional): Optional renderable to replace current renderable,\n                or None for no change. Defaults to None.\n            style: (Style, optional): Replacement style, or None for no change. Defaults to None.\n        \"\"\"\n        if renderables:\n            self.screen.renderable = (\n                Group(*renderables) if len(renderables) > 1 else renderables[0]\n            )\n        if style is not None:\n            self.screen.style = style\n        self.console.print(self.screen, end=\"\")\n\n    def __enter__(self) -> \"ScreenContext\":\n        self._changed = self.console.set_alt_screen(True)\n        if self._changed and self.hide_cursor:\n            self.console.show_cursor(False)\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        if self._changed:\n            self.console.set_alt_screen(False)\n            if self.hide_cursor:\n                self.console.show_cursor(True)\n\n\nclass Group:\n    \"\"\"Takes a group of renderables and returns a renderable object that renders the group.\n\n    Args:\n        renderables (Iterable[RenderableType]): An iterable of renderable objects.\n        fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.\n    \"\"\"\n\n    def __init__(self, *renderables: \"RenderableType\", fit: bool = True) -> None:\n        self._renderables = renderables\n        self.fit = fit\n        self._render: Optional[List[RenderableType]] = None\n\n    @property\n    def renderables(self) -> List[\"RenderableType\"]:\n        if self._render is None:\n            self._render = list(self._renderables)\n        return self._render\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        if self.fit:\n            return measure_renderables(console, options, self.renderables)\n        else:\n            return Measurement(options.max_width, options.max_width)\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> RenderResult:\n        yield from self.renderables\n\n\ndef group(fit: bool = True) -> Callable[..., Callable[..., Group]]:\n    \"\"\"A decorator that turns an iterable of renderables in to a group.\n\n    Args:\n        fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.\n    \"\"\"\n\n    def decorator(\n        method: Callable[..., Iterable[RenderableType]]\n    ) -> Callable[..., Group]:\n        \"\"\"Convert a method that returns an iterable of renderables in to a Group.\"\"\"\n\n        @wraps(method)\n        def _replace(*args: Any, **kwargs: Any) -> Group:\n            renderables = method(*args, **kwargs)\n            return Group(*renderables, fit=fit)\n\n        return _replace\n\n    return decorator\n\n\ndef _is_jupyter() -> bool:  # pragma: no cover\n    \"\"\"Check if we're running in a Jupyter notebook.\"\"\"\n    try:\n        get_ipython  # type: ignore[name-defined]\n    except NameError:\n        return False\n    ipython = get_ipython()  # type: ignore[name-defined]\n    shell = ipython.__class__.__name__\n    if \"google.colab\" in str(ipython.__class__) or shell == \"ZMQInteractiveShell\":\n        return True  # Jupyter notebook or qtconsole\n    elif shell == \"TerminalInteractiveShell\":\n        return False  # Terminal running IPython\n    else:\n        return False  # Other type (?)\n\n\nCOLOR_SYSTEMS = {\n    \"standard\": ColorSystem.STANDARD,\n    \"256\": ColorSystem.EIGHT_BIT,\n    \"truecolor\": ColorSystem.TRUECOLOR,\n    \"windows\": ColorSystem.WINDOWS,\n}\n\n_COLOR_SYSTEMS_NAMES = {system: name for name, system in COLOR_SYSTEMS.items()}\n\n\n@dataclass\nclass ConsoleThreadLocals(threading.local):\n    \"\"\"Thread local values for Console context.\"\"\"\n\n    theme_stack: ThemeStack\n    buffer: List[Segment] = field(default_factory=list)\n    buffer_index: int = 0\n\n\nclass RenderHook(ABC):\n    \"\"\"Provides hooks in to the render process.\"\"\"\n\n    @abstractmethod\n    def process_renderables(\n        self, renderables: List[ConsoleRenderable]\n    ) -> List[ConsoleRenderable]:\n        \"\"\"Called with a list of objects to render.\n\n        This method can return a new list of renderables, or modify and return the same list.\n\n        Args:\n            renderables (List[ConsoleRenderable]): A number of renderable objects.\n\n        Returns:\n            List[ConsoleRenderable]: A replacement list of renderables.\n        \"\"\"\n\n\n_windows_console_features: Optional[\"WindowsConsoleFeatures\"] = None\n\n\ndef get_windows_console_features() -> \"WindowsConsoleFeatures\":  # pragma: no cover\n    global _windows_console_features\n    if _windows_console_features is not None:\n        return _windows_console_features\n    from ._windows import get_windows_console_features\n\n    _windows_console_features = get_windows_console_features()\n    return _windows_console_features\n\n\ndef detect_legacy_windows() -> bool:\n    \"\"\"Detect legacy Windows.\"\"\"\n    return WINDOWS and not get_windows_console_features().vt\n\n\nclass Console:\n    \"\"\"A high level console interface.\n\n    Args:\n        color_system (str, optional): The color system supported by your terminal,\n            either ``\"standard\"``, ``\"256\"`` or ``\"truecolor\"``. Leave as ``\"auto\"`` to autodetect.\n        force_terminal (Optional[bool], optional): Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None.\n        force_jupyter (Optional[bool], optional): Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None.\n        force_interactive (Optional[bool], optional): Enable/disable interactive mode, or None to auto detect. Defaults to None.\n        soft_wrap (Optional[bool], optional): Set soft wrap default on print method. Defaults to False.\n        theme (Theme, optional): An optional style theme object, or ``None`` for default theme.\n        stderr (bool, optional): Use stderr rather than stdout if ``file`` is not specified. Defaults to False.\n        file (IO, optional): A file object where the console should write to. Defaults to stdout.\n        quiet (bool, Optional): Boolean to suppress all output. Defaults to False.\n        width (int, optional): The width of the terminal. Leave as default to auto-detect width.\n        height (int, optional): The height of the terminal. Leave as default to auto-detect height.\n        style (StyleType, optional): Style to apply to all output, or None for no style. Defaults to None.\n        no_color (Optional[bool], optional): Enabled no color mode, or None to auto detect. Defaults to None.\n        tab_size (int, optional): Number of spaces used to replace a tab character. Defaults to 8.\n        record (bool, optional): Boolean to enable recording of terminal output,\n            required to call :meth:`export_html`, :meth:`export_svg`, and :meth:`export_text`. Defaults to False.\n        markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True.\n        emoji (bool, optional): Enable emoji code. Defaults to True.\n        emoji_variant (str, optional): Optional emoji variant, either \"text\" or \"emoji\". Defaults to None.\n        highlight (bool, optional): Enable automatic highlighting. Defaults to True.\n        log_time (bool, optional): Boolean to enable logging of time by :meth:`log` methods. Defaults to True.\n        log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`log`. Defaults to True.\n        log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to \"[%X] \".\n        highlighter (HighlighterType, optional): Default highlighter.\n        legacy_windows (bool, optional): Enable legacy Windows mode, or ``None`` to auto detect. Defaults to ``None``.\n        safe_box (bool, optional): Restrict box options that don't render on legacy Windows.\n        get_datetime (Callable[[], datetime], optional): Callable that gets the current time as a datetime.datetime object (used by Console.log),\n            or None for datetime.now.\n        get_time (Callable[[], time], optional): Callable that gets the current time in seconds, default uses time.monotonic.\n    \"\"\"\n\n    _environ: Mapping[str, str] = os.environ\n\n    def __init__(\n        self,\n        *,\n        color_system: Optional[\n            Literal[\"auto\", \"standard\", \"256\", \"truecolor\", \"windows\"]\n        ] = \"auto\",\n        force_terminal: Optional[bool] = None,\n        force_jupyter: Optional[bool] = None,\n        force_interactive: Optional[bool] = None,\n        soft_wrap: bool = False,\n        theme: Optional[Theme] = None,\n        stderr: bool = False,\n        file: Optional[IO[str]] = None,\n        quiet: bool = False,\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n        style: Optional[StyleType] = None,\n        no_color: Optional[bool] = None,\n        tab_size: int = 8,\n        record: bool = False,\n        markup: bool = True,\n        emoji: bool = True,\n        emoji_variant: Optional[EmojiVariant] = None,\n        highlight: bool = True,\n        log_time: bool = True,\n        log_path: bool = True,\n        log_time_format: Union[str, FormatTimeCallable] = \"[%X]\",\n        highlighter: Optional[\"HighlighterType\"] = ReprHighlighter(),\n        legacy_windows: Optional[bool] = None,\n        safe_box: bool = True,\n        get_datetime: Optional[Callable[[], datetime]] = None,\n        get_time: Optional[Callable[[], float]] = None,\n        _environ: Optional[Mapping[str, str]] = None,\n    ):\n        # Copy of os.environ allows us to replace it for testing\n        if _environ is not None:\n            self._environ = _environ\n\n        self.is_jupyter = _is_jupyter() if force_jupyter is None else force_jupyter\n        if self.is_jupyter:\n            if width is None:\n                jupyter_columns = self._environ.get(\"JUPYTER_COLUMNS\")\n                if jupyter_columns is not None and jupyter_columns.isdigit():\n                    width = int(jupyter_columns)\n                else:\n                    width = JUPYTER_DEFAULT_COLUMNS\n            if height is None:\n                jupyter_lines = self._environ.get(\"JUPYTER_LINES\")\n                if jupyter_lines is not None and jupyter_lines.isdigit():\n                    height = int(jupyter_lines)\n                else:\n                    height = JUPYTER_DEFAULT_LINES\n\n        self.tab_size = tab_size\n        self.record = record\n        self._markup = markup\n        self._emoji = emoji\n        self._emoji_variant: Optional[EmojiVariant] = emoji_variant\n        self._highlight = highlight\n        self.legacy_windows: bool = (\n            (detect_legacy_windows() and not self.is_jupyter)\n            if legacy_windows is None\n            else legacy_windows\n        )\n\n        if width is None:\n            columns = self._environ.get(\"COLUMNS\")\n            if columns is not None and columns.isdigit():\n                width = int(columns) - self.legacy_windows\n        if height is None:\n            lines = self._environ.get(\"LINES\")\n            if lines is not None and lines.isdigit():\n                height = int(lines)\n\n        self.soft_wrap = soft_wrap\n        self._width = width\n        self._height = height\n\n        self._color_system: Optional[ColorSystem]\n        self._force_terminal = force_terminal\n        self._file = file\n        self.quiet = quiet\n        self.stderr = stderr\n\n        if color_system is None:\n            self._color_system = None\n        elif color_system == \"auto\":\n            self._color_system = self._detect_color_system()\n        else:\n            self._color_system = COLOR_SYSTEMS[color_system]\n\n        self._lock = threading.RLock()\n        self._log_render = LogRender(\n            show_time=log_time,\n            show_path=log_path,\n            time_format=log_time_format,\n        )\n        self.highlighter: HighlighterType = highlighter or _null_highlighter\n        self.safe_box = safe_box\n        self.get_datetime = get_datetime or datetime.now\n        self.get_time = get_time or monotonic\n        self.style = style\n        self.no_color = (\n            no_color if no_color is not None else \"NO_COLOR\" in self._environ\n        )\n        self.is_interactive = (\n            (self.is_terminal and not self.is_dumb_terminal)\n            if force_interactive is None\n            else force_interactive\n        )\n\n        self._record_buffer_lock = threading.RLock()\n        self._thread_locals = ConsoleThreadLocals(\n            theme_stack=ThemeStack(themes.DEFAULT if theme is None else theme)\n        )\n        self._record_buffer: List[Segment] = []\n        self._render_hooks: List[RenderHook] = []\n        self._live: Optional[\"Live\"] = None\n        self._is_alt_screen = False\n\n    def __repr__(self) -> str:\n        return f\"<console width={self.width} {str(self._color_system)}>\"\n\n    @property\n    def file(self) -> IO[str]:\n        \"\"\"Get the file object to write to.\"\"\"\n        file = self._file or (sys.stderr if self.stderr else sys.stdout)\n        file = getattr(file, \"rich_proxied_file\", file)\n        return file\n\n    @file.setter\n    def file(self, new_file: IO[str]) -> None:\n        \"\"\"Set a new file object.\"\"\"\n        self._file = new_file\n\n    @property\n    def _buffer(self) -> List[Segment]:\n        \"\"\"Get a thread local buffer.\"\"\"\n        return self._thread_locals.buffer\n\n    @property\n    def _buffer_index(self) -> int:\n        \"\"\"Get a thread local buffer.\"\"\"\n        return self._thread_locals.buffer_index\n\n    @_buffer_index.setter\n    def _buffer_index(self, value: int) -> None:\n        self._thread_locals.buffer_index = value\n\n    @property\n    def _theme_stack(self) -> ThemeStack:\n        \"\"\"Get the thread local theme stack.\"\"\"\n        return self._thread_locals.theme_stack\n\n    def _detect_color_system(self) -> Optional[ColorSystem]:\n        \"\"\"Detect color system from env vars.\"\"\"\n        if self.is_jupyter:\n            return ColorSystem.TRUECOLOR\n        if not self.is_terminal or self.is_dumb_terminal:\n            return None\n        if WINDOWS:  # pragma: no cover\n            if self.legacy_windows:  # pragma: no cover\n                return ColorSystem.WINDOWS\n            windows_console_features = get_windows_console_features()\n            return (\n                ColorSystem.TRUECOLOR\n                if windows_console_features.truecolor\n                else ColorSystem.EIGHT_BIT\n            )\n        else:\n            color_term = self._environ.get(\"COLORTERM\", \"\").strip().lower()\n            if color_term in (\"truecolor\", \"24bit\"):\n                return ColorSystem.TRUECOLOR\n            term = self._environ.get(\"TERM\", \"\").strip().lower()\n            _term_name, _hyphen, colors = term.rpartition(\"-\")\n            color_system = _TERM_COLORS.get(colors, ColorSystem.STANDARD)\n            return color_system\n\n    def _enter_buffer(self) -> None:\n        \"\"\"Enter in to a buffer context, and buffer all output.\"\"\"\n        self._buffer_index += 1\n\n    def _exit_buffer(self) -> None:\n        \"\"\"Leave buffer context, and render content if required.\"\"\"\n        self._buffer_index -= 1\n        self._check_buffer()\n\n    def set_live(self, live: \"Live\") -> None:\n        \"\"\"Set Live instance. Used by Live context manager.\n\n        Args:\n            live (Live): Live instance using this Console.\n\n        Raises:\n            errors.LiveError: If this Console has a Live context currently active.\n        \"\"\"\n        with self._lock:\n            if self._live is not None:\n                raise errors.LiveError(\"Only one live display may be active at once\")\n            self._live = live\n\n    def clear_live(self) -> None:\n        \"\"\"Clear the Live instance.\"\"\"\n        with self._lock:\n            self._live = None\n\n    def push_render_hook(self, hook: RenderHook) -> None:\n        \"\"\"Add a new render hook to the stack.\n\n        Args:\n            hook (RenderHook): Render hook instance.\n        \"\"\"\n        with self._lock:\n            self._render_hooks.append(hook)\n\n    def pop_render_hook(self) -> None:\n        \"\"\"Pop the last renderhook from the stack.\"\"\"\n        with self._lock:\n            self._render_hooks.pop()\n\n    def __enter__(self) -> \"Console\":\n        \"\"\"Own context manager to enter buffer context.\"\"\"\n        self._enter_buffer()\n        return self\n\n    def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:\n        \"\"\"Exit buffer context.\"\"\"\n        self._exit_buffer()\n\n    def begin_capture(self) -> None:\n        \"\"\"Begin capturing console output. Call :meth:`end_capture` to exit capture mode and return output.\"\"\"\n        self._enter_buffer()\n\n    def end_capture(self) -> str:\n        \"\"\"End capture mode and return captured string.\n\n        Returns:\n            str: Console output.\n        \"\"\"\n        render_result = self._render_buffer(self._buffer)\n        del self._buffer[:]\n        self._exit_buffer()\n        return render_result\n\n    def push_theme(self, theme: Theme, *, inherit: bool = True) -> None:\n        \"\"\"Push a new theme on to the top of the stack, replacing the styles from the previous theme.\n        Generally speaking, you should call :meth:`~rich.console.Console.use_theme` to get a context manager, rather\n        than calling this method directly.\n\n        Args:\n            theme (Theme): A theme instance.\n            inherit (bool, optional): Inherit existing styles. Defaults to True.\n        \"\"\"\n        self._theme_stack.push_theme(theme, inherit=inherit)\n\n    def pop_theme(self) -> None:\n        \"\"\"Remove theme from top of stack, restoring previous theme.\"\"\"\n        self._theme_stack.pop_theme()\n\n    def use_theme(self, theme: Theme, *, inherit: bool = True) -> ThemeContext:\n        \"\"\"Use a different theme for the duration of the context manager.\n\n        Args:\n            theme (Theme): Theme instance to user.\n            inherit (bool, optional): Inherit existing console styles. Defaults to True.\n\n        Returns:\n            ThemeContext: [description]\n        \"\"\"\n        return ThemeContext(self, theme, inherit)\n\n    @property\n    def color_system(self) -> Optional[str]:\n        \"\"\"Get color system string.\n\n        Returns:\n            Optional[str]: \"standard\", \"256\" or \"truecolor\".\n        \"\"\"\n\n        if self._color_system is not None:\n            return _COLOR_SYSTEMS_NAMES[self._color_system]\n        else:\n            return None\n\n    @property\n    def encoding(self) -> str:\n        \"\"\"Get the encoding of the console file, e.g. ``\"utf-8\"``.\n\n        Returns:\n            str: A standard encoding string.\n        \"\"\"\n        return (getattr(self.file, \"encoding\", \"utf-8\") or \"utf-8\").lower()\n\n    @property\n    def is_terminal(self) -> bool:\n        \"\"\"Check if the console is writing to a terminal.\n\n        Returns:\n            bool: True if the console writing to a device capable of\n            understanding terminal codes, otherwise False.\n        \"\"\"\n        if self._force_terminal is not None:\n            return self._force_terminal\n\n        if hasattr(sys.stdin, \"__module__\") and sys.stdin.__module__.startswith(\n            \"idlelib\"\n        ):\n            # Return False for Idle which claims to be a tty but can't handle ansi codes\n            return False\n\n        isatty: Optional[Callable[[], bool]] = getattr(self.file, \"isatty\", None)\n        try:\n            return False if isatty is None else isatty()\n        except ValueError:\n            # in some situation (at the end of a pytest run for example) isatty() can raise\n            # ValueError: I/O operation on closed file\n            # return False because we aren't in a terminal anymore\n            return False\n\n    @property\n    def is_dumb_terminal(self) -> bool:\n        \"\"\"Detect dumb terminal.\n\n        Returns:\n            bool: True if writing to a dumb terminal, otherwise False.\n\n        \"\"\"\n        _term = self._environ.get(\"TERM\", \"\")\n        is_dumb = _term.lower() in (\"dumb\", \"unknown\")\n        return self.is_terminal and is_dumb\n\n    @property\n    def options(self) -> ConsoleOptions:\n        \"\"\"Get default console options.\"\"\"\n        return ConsoleOptions(\n            max_height=self.size.height,\n            size=self.size,\n            legacy_windows=self.legacy_windows,\n            min_width=1,\n            max_width=self.width,\n            encoding=self.encoding,\n            is_terminal=self.is_terminal,\n        )\n\n    @property\n    def size(self) -> ConsoleDimensions:\n        \"\"\"Get the size of the console.\n\n        Returns:\n            ConsoleDimensions: A named tuple containing the dimensions.\n        \"\"\"\n\n        if self._width is not None and self._height is not None:\n            return ConsoleDimensions(self._width - self.legacy_windows, self._height)\n\n        if self.is_dumb_terminal:\n            return ConsoleDimensions(80, 25)\n\n        width: Optional[int] = None\n        height: Optional[int] = None\n\n        if WINDOWS:  # pragma: no cover\n            try:\n                width, height = os.get_terminal_size()\n            except (AttributeError, ValueError, OSError):  # Probably not a terminal\n                pass\n        else:\n            for file_descriptor in _STD_STREAMS:\n                try:\n                    width, height = os.get_terminal_size(file_descriptor)\n                except (AttributeError, ValueError, OSError):\n                    pass\n                else:\n                    break\n\n        columns = self._environ.get(\"COLUMNS\")\n        if columns is not None and columns.isdigit():\n            width = int(columns)\n        lines = self._environ.get(\"LINES\")\n        if lines is not None and lines.isdigit():\n            height = int(lines)\n\n        # get_terminal_size can report 0, 0 if run from pseudo-terminal\n        width = width or 80\n        height = height or 25\n        return ConsoleDimensions(\n            width - self.legacy_windows if self._width is None else self._width,\n            height if self._height is None else self._height,\n        )\n\n    @size.setter\n    def size(self, new_size: Tuple[int, int]) -> None:\n        \"\"\"Set a new size for the terminal.\n\n        Args:\n            new_size (Tuple[int, int]): New width and height.\n        \"\"\"\n        width, height = new_size\n        self._width = width\n        self._height = height\n\n    @property\n    def width(self) -> int:\n        \"\"\"Get the width of the console.\n\n        Returns:\n            int: The width (in characters) of the console.\n        \"\"\"\n        return self.size.width\n\n    @width.setter\n    def width(self, width: int) -> None:\n        \"\"\"Set width.\n\n        Args:\n            width (int): New width.\n        \"\"\"\n        self._width = width\n\n    @property\n    def height(self) -> int:\n        \"\"\"Get the height of the console.\n\n        Returns:\n            int: The height (in lines) of the console.\n        \"\"\"\n        return self.size.height\n\n    @height.setter\n    def height(self, height: int) -> None:\n        \"\"\"Set height.\n\n        Args:\n            height (int): new height.\n        \"\"\"\n        self._height = height\n\n    def bell(self) -> None:\n        \"\"\"Play a 'bell' sound (if supported by the terminal).\"\"\"\n        self.control(Control.bell())\n\n    def capture(self) -> Capture:\n        \"\"\"A context manager to *capture* the result of print() or log() in a string,\n        rather than writing it to the console.\n\n        Example:\n            >>> from rich.console import Console\n            >>> console = Console()\n            >>> with console.capture() as capture:\n            ...     console.print(\"[bold magenta]Hello World[/]\")\n            >>> print(capture.get())\n\n        Returns:\n            Capture: Context manager with disables writing to the terminal.\n        \"\"\"\n        capture = Capture(self)\n        return capture\n\n    def pager(\n        self, pager: Optional[Pager] = None, styles: bool = False, links: bool = False\n    ) -> PagerContext:\n        \"\"\"A context manager to display anything printed within a \"pager\". The pager application\n        is defined by the system and will typically support at least pressing a key to scroll.\n\n        Args:\n            pager (Pager, optional): A pager object, or None to use :class:`~rich.pager.SystemPager`. Defaults to None.\n            styles (bool, optional): Show styles in pager. Defaults to False.\n            links (bool, optional): Show links in pager. Defaults to False.\n\n        Example:\n            >>> from rich.console import Console\n            >>> from rich.__main__ import make_test_card\n            >>> console = Console()\n            >>> with console.pager():\n                    console.print(make_test_card())\n\n        Returns:\n            PagerContext: A context manager.\n        \"\"\"\n        return PagerContext(self, pager=pager, styles=styles, links=links)\n\n    def line(self, count: int = 1) -> None:\n        \"\"\"Write new line(s).\n\n        Args:\n            count (int, optional): Number of new lines. Defaults to 1.\n        \"\"\"\n\n        assert count >= 0, \"count must be >= 0\"\n        self.print(NewLine(count))\n\n    def clear(self, home: bool = True) -> None:\n        \"\"\"Clear the screen.\n\n        Args:\n            home (bool, optional): Also move the cursor to 'home' position. Defaults to True.\n        \"\"\"\n        if home:\n            self.control(Control.clear(), Control.home())\n        else:\n            self.control(Control.clear())\n\n    def status(\n        self,\n        status: RenderableType,\n        *,\n        spinner: str = \"dots\",\n        spinner_style: str = \"status.spinner\",\n        speed: float = 1.0,\n        refresh_per_second: float = 12.5,\n    ) -> \"Status\":\n        \"\"\"Display a status and spinner.\n\n        Args:\n            status (RenderableType): A status renderable (str or Text typically).\n            spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to \"dots\".\n            spinner_style (StyleType, optional): Style of spinner. Defaults to \"status.spinner\".\n            speed (float, optional): Speed factor for spinner animation. Defaults to 1.0.\n            refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5.\n\n        Returns:\n            Status: A Status object that may be used as a context manager.\n        \"\"\"\n        from .status import Status\n\n        status_renderable = Status(\n            status,\n            console=self,\n            spinner=spinner,\n            spinner_style=spinner_style,\n            speed=speed,\n            refresh_per_second=refresh_per_second,\n        )\n        return status_renderable\n\n    def show_cursor(self, show: bool = True) -> bool:\n        \"\"\"Show or hide the cursor.\n\n        Args:\n            show (bool, optional): Set visibility of the cursor.\n        \"\"\"\n        if self.is_terminal:\n            self.control(Control.show_cursor(show))\n            return True\n        return False\n\n    def set_alt_screen(self, enable: bool = True) -> bool:\n        \"\"\"Enables alternative screen mode.\n\n        Note, if you enable this mode, you should ensure that is disabled before\n        the application exits. See :meth:`~rich.Console.screen` for a context manager\n        that handles this for you.\n\n        Args:\n            enable (bool, optional): Enable (True) or disable (False) alternate screen. Defaults to True.\n\n        Returns:\n            bool: True if the control codes were written.\n\n        \"\"\"\n        changed = False\n        if self.is_terminal and not self.legacy_windows:\n            self.control(Control.alt_screen(enable))\n            changed = True\n            self._is_alt_screen = enable\n        return changed\n\n    @property\n    def is_alt_screen(self) -> bool:\n        \"\"\"Check if the alt screen was enabled.\n\n        Returns:\n            bool: True if the alt screen was enabled, otherwise False.\n        \"\"\"\n        return self._is_alt_screen\n\n    def set_window_title(self, title: str) -> bool:\n        \"\"\"Set the title of the console terminal window.\n\n        Warning: There is no means within Rich of \"resetting\" the window title to its\n        previous value, meaning the title you set will persist even after your application\n        exits.\n\n        ``fish`` shell resets the window title before and after each command by default,\n        negating this issue. Windows Terminal and command prompt will also reset the title for you.\n        Most other shells and terminals, however, do not do this.\n\n        Some terminals may require configuration changes before you can set the title.\n        Some terminals may not support setting the title at all.\n\n        Other software (including the terminal itself, the shell, custom prompts, plugins, etc.)\n        may also set the terminal window title. This could result in whatever value you write\n        using this method being overwritten.\n\n        Args:\n            title (str): The new title of the terminal window.\n\n        Returns:\n            bool: True if the control code to change the terminal title was\n                written, otherwise False. Note that a return value of True\n                does not guarantee that the window title has actually changed,\n                since the feature may be unsupported/disabled in some terminals.\n        \"\"\"\n        if self.is_terminal:\n            self.control(Control.title(title))\n            return True\n        return False\n\n    def screen(\n        self, hide_cursor: bool = True, style: Optional[StyleType] = None\n    ) -> \"ScreenContext\":\n        \"\"\"Context manager to enable and disable 'alternative screen' mode.\n\n        Args:\n            hide_cursor (bool, optional): Also hide the cursor. Defaults to False.\n            style (Style, optional): Optional style for screen. Defaults to None.\n\n        Returns:\n            ~ScreenContext: Context which enables alternate screen on enter, and disables it on exit.\n        \"\"\"\n        return ScreenContext(self, hide_cursor=hide_cursor, style=style or \"\")\n\n    def measure(\n        self, renderable: RenderableType, *, options: Optional[ConsoleOptions] = None\n    ) -> Measurement:\n        \"\"\"Measure a renderable. Returns a :class:`~rich.measure.Measurement` object which contains\n        information regarding the number of characters required to print the renderable.\n\n        Args:\n            renderable (RenderableType): Any renderable or string.\n            options (Optional[ConsoleOptions], optional): Options to use when measuring, or None\n                to use default options. Defaults to None.\n\n        Returns:\n            Measurement: A measurement of the renderable.\n        \"\"\"\n        measurement = Measurement.get(self, options or self.options, renderable)\n        return measurement\n\n    def render(\n        self, renderable: RenderableType, options: Optional[ConsoleOptions] = None\n    ) -> Iterable[Segment]:\n        \"\"\"Render an object in to an iterable of `Segment` instances.\n\n        This method contains the logic for rendering objects with the console protocol.\n        You are unlikely to need to use it directly, unless you are extending the library.\n\n        Args:\n            renderable (RenderableType): An object supporting the console protocol, or\n                an object that may be converted to a string.\n            options (ConsoleOptions, optional): An options object, or None to use self.options. Defaults to None.\n\n        Returns:\n            Iterable[Segment]: An iterable of segments that may be rendered.\n        \"\"\"\n\n        _options = options or self.options\n        if _options.max_width < 1:\n            # No space to render anything. This prevents potential recursion errors.\n            return\n        render_iterable: RenderResult\n\n        renderable = rich_cast(renderable)\n        if hasattr(renderable, \"__rich_console__\") and not isclass(renderable):\n            render_iterable = renderable.__rich_console__(self, _options)  # type: ignore[union-attr]\n        elif isinstance(renderable, str):\n            text_renderable = self.render_str(\n                renderable, highlight=_options.highlight, markup=_options.markup\n            )\n            render_iterable = text_renderable.__rich_console__(self, _options)\n        else:\n            raise errors.NotRenderableError(\n                f\"Unable to render {renderable!r}; \"\n                \"A str, Segment or object with __rich_console__ method is required\"\n            )\n\n        try:\n            iter_render = iter(render_iterable)\n        except TypeError:\n            raise errors.NotRenderableError(\n                f\"object {render_iterable!r} is not renderable\"\n            )\n        _Segment = Segment\n        _options = _options.reset_height()\n        for render_output in iter_render:\n            if isinstance(render_output, _Segment):\n                yield render_output\n            else:\n                yield from self.render(render_output, _options)\n\n    def render_lines(\n        self,\n        renderable: RenderableType,\n        options: Optional[ConsoleOptions] = None,\n        *,\n        style: Optional[Style] = None,\n        pad: bool = True,\n        new_lines: bool = False,\n    ) -> List[List[Segment]]:\n        \"\"\"Render objects in to a list of lines.\n\n        The output of render_lines is useful when further formatting of rendered console text\n        is required, such as the Panel class which draws a border around any renderable object.\n\n        Args:\n            renderable (RenderableType): Any object renderable in the console.\n            options (Optional[ConsoleOptions], optional): Console options, or None to use self.options. Default to ``None``.\n            style (Style, optional): Optional style to apply to renderables. Defaults to ``None``.\n            pad (bool, optional): Pad lines shorter than render width. Defaults to ``True``.\n            new_lines (bool, optional): Include \"\\n\" characters at end of lines.\n\n        Returns:\n            List[List[Segment]]: A list of lines, where a line is a list of Segment objects.\n        \"\"\"\n        with self._lock:\n            render_options = options or self.options\n            _rendered = self.render(renderable, render_options)\n            if style:\n                _rendered = Segment.apply_style(_rendered, style)\n\n            render_height = render_options.height\n            if render_height is not None:\n                render_height = max(0, render_height)\n\n            lines = list(\n                islice(\n                    Segment.split_and_crop_lines(\n                        _rendered,\n                        render_options.max_width,\n                        include_new_lines=new_lines,\n                        pad=pad,\n                        style=style,\n                    ),\n                    None,\n                    render_height,\n                )\n            )\n            if render_options.height is not None:\n                extra_lines = render_options.height - len(lines)\n                if extra_lines > 0:\n                    pad_line = [\n                        [Segment(\" \" * render_options.max_width, style), Segment(\"\\n\")]\n                        if new_lines\n                        else [Segment(\" \" * render_options.max_width, style)]\n                    ]\n                    lines.extend(pad_line * extra_lines)\n\n            return lines\n\n    def render_str(\n        self,\n        text: str,\n        *,\n        style: Union[str, Style] = \"\",\n        justify: Optional[JustifyMethod] = None,\n        overflow: Optional[OverflowMethod] = None,\n        emoji: Optional[bool] = None,\n        markup: Optional[bool] = None,\n        highlight: Optional[bool] = None,\n        highlighter: Optional[HighlighterType] = None,\n    ) -> \"Text\":\n        \"\"\"Convert a string to a Text instance. This is called automatically if\n        you print or log a string.\n\n        Args:\n            text (str): Text to render.\n            style (Union[str, Style], optional): Style to apply to rendered text.\n            justify (str, optional): Justify method: \"default\", \"left\", \"center\", \"full\", or \"right\". Defaults to ``None``.\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", or \"ellipsis\". Defaults to ``None``.\n            emoji (Optional[bool], optional): Enable emoji, or ``None`` to use Console default.\n            markup (Optional[bool], optional): Enable markup, or ``None`` to use Console default.\n            highlight (Optional[bool], optional): Enable highlighting, or ``None`` to use Console default.\n            highlighter (HighlighterType, optional): Optional highlighter to apply.\n        Returns:\n            ConsoleRenderable: Renderable object.\n\n        \"\"\"\n        emoji_enabled = emoji or (emoji is None and self._emoji)\n        markup_enabled = markup or (markup is None and self._markup)\n        highlight_enabled = highlight or (highlight is None and self._highlight)\n\n        if markup_enabled:\n            rich_text = render_markup(\n                text,\n                style=style,\n                emoji=emoji_enabled,\n                emoji_variant=self._emoji_variant,\n            )\n            rich_text.justify = justify\n            rich_text.overflow = overflow\n        else:\n            rich_text = Text(\n                _emoji_replace(text, default_variant=self._emoji_variant)\n                if emoji_enabled\n                else text,\n                justify=justify,\n                overflow=overflow,\n                style=style,\n            )\n\n        _highlighter = (highlighter or self.highlighter) if highlight_enabled else None\n        if _highlighter is not None:\n            highlight_text = _highlighter(str(rich_text))\n            highlight_text.copy_styles(rich_text)\n            return highlight_text\n\n        return rich_text\n\n    def get_style(\n        self, name: Union[str, Style], *, default: Optional[Union[Style, str]] = None\n    ) -> Style:\n        \"\"\"Get a Style instance by its theme name or parse a definition.\n\n        Args:\n            name (str): The name of a style or a style definition.\n\n        Returns:\n            Style: A Style object.\n\n        Raises:\n            MissingStyle: If no style could be parsed from name.\n\n        \"\"\"\n        if isinstance(name, Style):\n            return name\n\n        try:\n            style = self._theme_stack.get(name)\n            if style is None:\n                style = Style.parse(name)\n            return style.copy() if style.link else style\n        except errors.StyleSyntaxError as error:\n            if default is not None:\n                return self.get_style(default)\n            raise errors.MissingStyle(\n                f\"Failed to get style {name!r}; {error}\"\n            ) from None\n\n    def _collect_renderables(\n        self,\n        objects: Iterable[Any],\n        sep: str,\n        end: str,\n        *,\n        justify: Optional[JustifyMethod] = None,\n        emoji: Optional[bool] = None,\n        markup: Optional[bool] = None,\n        highlight: Optional[bool] = None,\n    ) -> List[ConsoleRenderable]:\n        \"\"\"Combine a number of renderables and text into one renderable.\n\n        Args:\n            objects (Iterable[Any]): Anything that Rich can render.\n            sep (str): String to write between print data.\n            end (str): String to write at end of print data.\n            justify (str, optional): One of \"left\", \"right\", \"center\", or \"full\". Defaults to ``None``.\n            emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default.\n            markup (Optional[bool], optional): Enable markup, or ``None`` to use console default.\n            highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default.\n\n        Returns:\n            List[ConsoleRenderable]: A list of things to render.\n        \"\"\"\n        renderables: List[ConsoleRenderable] = []\n        _append = renderables.append\n        text: List[Text] = []\n        append_text = text.append\n\n        append = _append\n        if justify in (\"left\", \"center\", \"right\"):\n\n            def align_append(renderable: RenderableType) -> None:\n                _append(Align(renderable, cast(AlignMethod, justify)))\n\n            append = align_append\n\n        _highlighter: HighlighterType = _null_highlighter\n        if highlight or (highlight is None and self._highlight):\n            _highlighter = self.highlighter\n\n        def check_text() -> None:\n            if text:\n                sep_text = Text(sep, justify=justify, end=end)\n                append(sep_text.join(text))\n                del text[:]\n\n        for renderable in objects:\n            renderable = rich_cast(renderable)\n            if isinstance(renderable, str):\n                append_text(\n                    self.render_str(\n                        renderable, emoji=emoji, markup=markup, highlighter=_highlighter\n                    )\n                )\n            elif isinstance(renderable, Text):\n                append_text(renderable)\n            elif isinstance(renderable, ConsoleRenderable):\n                check_text()\n                append(renderable)\n            elif is_expandable(renderable):\n                check_text()\n                append(Pretty(renderable, highlighter=_highlighter))\n            else:\n                append_text(_highlighter(str(renderable)))\n\n        check_text()\n\n        if self.style is not None:\n            style = self.get_style(self.style)\n            renderables = [Styled(renderable, style) for renderable in renderables]\n\n        return renderables\n\n    def rule(\n        self,\n        title: TextType = \"\",\n        *,\n        characters: str = \"─\",\n        style: Union[str, Style] = \"rule.line\",\n        align: AlignMethod = \"center\",\n    ) -> None:\n        \"\"\"Draw a line with optional centered title.\n\n        Args:\n            title (str, optional): Text to render over the rule. Defaults to \"\".\n            characters (str, optional): Character(s) to form the line. Defaults to \"─\".\n            style (str, optional): Style of line. Defaults to \"rule.line\".\n            align (str, optional): How to align the title, one of \"left\", \"center\", or \"right\". Defaults to \"center\".\n        \"\"\"\n        from .rule import Rule\n\n        rule = Rule(title=title, characters=characters, style=style, align=align)\n        self.print(rule)\n\n    def control(self, *control: Control) -> None:\n        \"\"\"Insert non-printing control codes.\n\n        Args:\n            control_codes (str): Control codes, such as those that may move the cursor.\n        \"\"\"\n        if not self.is_dumb_terminal:\n            with self:\n                self._buffer.extend(_control.segment for _control in control)\n\n    def out(\n        self,\n        *objects: Any,\n        sep: str = \" \",\n        end: str = \"\\n\",\n        style: Optional[Union[str, Style]] = None,\n        highlight: Optional[bool] = None,\n    ) -> None:\n        \"\"\"Output to the terminal. This is a low-level way of writing to the terminal which unlike\n        :meth:`~rich.console.Console.print` won't pretty print, wrap text, or apply markup, but will\n        optionally apply highlighting and a basic style.\n\n        Args:\n            sep (str, optional): String to write between print data. Defaults to \" \".\n            end (str, optional): String to write at end of print data. Defaults to \"\\\\\\\\n\".\n            style (Union[str, Style], optional): A style to apply to output. Defaults to None.\n            highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use\n                console default. Defaults to ``None``.\n        \"\"\"\n        raw_output: str = sep.join(str(_object) for _object in objects)\n        self.print(\n            raw_output,\n            style=style,\n            highlight=highlight,\n            emoji=False,\n            markup=False,\n            no_wrap=True,\n            overflow=\"ignore\",\n            crop=False,\n            end=end,\n        )\n\n    def print(\n        self,\n        *objects: Any,\n        sep: str = \" \",\n        end: str = \"\\n\",\n        style: Optional[Union[str, Style]] = None,\n        justify: Optional[JustifyMethod] = None,\n        overflow: Optional[OverflowMethod] = None,\n        no_wrap: Optional[bool] = None,\n        emoji: Optional[bool] = None,\n        markup: Optional[bool] = None,\n        highlight: Optional[bool] = None,\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n        crop: bool = True,\n        soft_wrap: Optional[bool] = None,\n        new_line_start: bool = False,\n    ) -> None:\n        \"\"\"Print to the console.\n\n        Args:\n            objects (positional args): Objects to log to the terminal.\n            sep (str, optional): String to write between print data. Defaults to \" \".\n            end (str, optional): String to write at end of print data. Defaults to \"\\\\\\\\n\".\n            style (Union[str, Style], optional): A style to apply to output. Defaults to None.\n            justify (str, optional): Justify method: \"default\", \"left\", \"right\", \"center\", or \"full\". Defaults to ``None``.\n            overflow (str, optional): Overflow method: \"ignore\", \"crop\", \"fold\", or \"ellipsis\". Defaults to None.\n            no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.\n            emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.\n            markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.\n            highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.\n            width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``.\n            crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True.\n            soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or ``None`` for\n                Console default. Defaults to ``None``.\n            new_line_start (bool, False): Insert a new line at the start if the output contains more than one line. Defaults to ``False``.\n        \"\"\"\n        if not objects:\n            objects = (NewLine(),)\n\n        if soft_wrap is None:\n            soft_wrap = self.soft_wrap\n        if soft_wrap:\n            if no_wrap is None:\n                no_wrap = True\n            if overflow is None:\n                overflow = \"ignore\"\n            crop = False\n        render_hooks = self._render_hooks[:]\n        with self:\n            renderables = self._collect_renderables(\n                objects,\n                sep,\n                end,\n                justify=justify,\n                emoji=emoji,\n                markup=markup,\n                highlight=highlight,\n            )\n            for hook in render_hooks:\n                renderables = hook.process_renderables(renderables)\n            render_options = self.options.update(\n                justify=justify,\n                overflow=overflow,\n                width=min(width, self.width) if width is not None else NO_CHANGE,\n                height=height,\n                no_wrap=no_wrap,\n                markup=markup,\n                highlight=highlight,\n            )\n\n            new_segments: List[Segment] = []\n            extend = new_segments.extend\n            render = self.render\n            if style is None:\n                for renderable in renderables:\n                    extend(render(renderable, render_options))\n            else:\n                for renderable in renderables:\n                    extend(\n                        Segment.apply_style(\n                            render(renderable, render_options), self.get_style(style)\n                        )\n                    )\n            if new_line_start:\n                if (\n                    len(\"\".join(segment.text for segment in new_segments).splitlines())\n                    > 1\n                ):\n                    new_segments.insert(0, Segment.line())\n            if crop:\n                buffer_extend = self._buffer.extend\n                for line in Segment.split_and_crop_lines(\n                    new_segments, self.width, pad=False\n                ):\n                    buffer_extend(line)\n            else:\n                self._buffer.extend(new_segments)\n\n    def print_json(\n        self,\n        json: Optional[str] = None,\n        *,\n        data: Any = None,\n        indent: Union[None, int, str] = 2,\n        highlight: bool = True,\n        skip_keys: bool = False,\n        ensure_ascii: bool = True,\n        check_circular: bool = True,\n        allow_nan: bool = True,\n        default: Optional[Callable[[Any], Any]] = None,\n        sort_keys: bool = False,\n    ) -> None:\n        \"\"\"Pretty prints JSON. Output will be valid JSON.\n\n        Args:\n            json (Optional[str]): A string containing JSON.\n            data (Any): If json is not supplied, then encode this data.\n            indent (Union[None, int, str], optional): Number of spaces to indent. Defaults to 2.\n            highlight (bool, optional): Enable highlighting of output: Defaults to True.\n            skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.\n            ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.\n            check_circular (bool, optional): Check for circular references. Defaults to True.\n            allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.\n            default (Callable, optional): A callable that converts values that can not be encoded\n                in to something that can be JSON encoded. Defaults to None.\n            sort_keys (bool, optional): Sort dictionary keys. Defaults to False.\n        \"\"\"\n        from pip._vendor.rich.json import JSON\n\n        if json is None:\n            json_renderable = JSON.from_data(\n                data,\n                indent=indent,\n                highlight=highlight,\n                skip_keys=skip_keys,\n                ensure_ascii=ensure_ascii,\n                check_circular=check_circular,\n                allow_nan=allow_nan,\n                default=default,\n                sort_keys=sort_keys,\n            )\n        else:\n            if not isinstance(json, str):\n                raise TypeError(\n                    f\"json must be str. Did you mean print_json(data={json!r}) ?\"\n                )\n            json_renderable = JSON(\n                json,\n                indent=indent,\n                highlight=highlight,\n                skip_keys=skip_keys,\n                ensure_ascii=ensure_ascii,\n                check_circular=check_circular,\n                allow_nan=allow_nan,\n                default=default,\n                sort_keys=sort_keys,\n            )\n        self.print(json_renderable, soft_wrap=True)\n\n    def update_screen(\n        self,\n        renderable: RenderableType,\n        *,\n        region: Optional[Region] = None,\n        options: Optional[ConsoleOptions] = None,\n    ) -> None:\n        \"\"\"Update the screen at a given offset.\n\n        Args:\n            renderable (RenderableType): A Rich renderable.\n            region (Region, optional): Region of screen to update, or None for entire screen. Defaults to None.\n            x (int, optional): x offset. Defaults to 0.\n            y (int, optional): y offset. Defaults to 0.\n\n        Raises:\n            errors.NoAltScreen: If the Console isn't in alt screen mode.\n\n        \"\"\"\n        if not self.is_alt_screen:\n            raise errors.NoAltScreen(\"Alt screen must be enabled to call update_screen\")\n        render_options = options or self.options\n        if region is None:\n            x = y = 0\n            render_options = render_options.update_dimensions(\n                render_options.max_width, render_options.height or self.height\n            )\n        else:\n            x, y, width, height = region\n            render_options = render_options.update_dimensions(width, height)\n\n        lines = self.render_lines(renderable, options=render_options)\n        self.update_screen_lines(lines, x, y)\n\n    def update_screen_lines(\n        self, lines: List[List[Segment]], x: int = 0, y: int = 0\n    ) -> None:\n        \"\"\"Update lines of the screen at a given offset.\n\n        Args:\n            lines (List[List[Segment]]): Rendered lines (as produced by :meth:`~rich.Console.render_lines`).\n            x (int, optional): x offset (column no). Defaults to 0.\n            y (int, optional): y offset (column no). Defaults to 0.\n\n        Raises:\n            errors.NoAltScreen: If the Console isn't in alt screen mode.\n        \"\"\"\n        if not self.is_alt_screen:\n            raise errors.NoAltScreen(\"Alt screen must be enabled to call update_screen\")\n        screen_update = ScreenUpdate(lines, x, y)\n        segments = self.render(screen_update)\n        self._buffer.extend(segments)\n        self._check_buffer()\n\n    def print_exception(\n        self,\n        *,\n        width: Optional[int] = 100,\n        extra_lines: int = 3,\n        theme: Optional[str] = None,\n        word_wrap: bool = False,\n        show_locals: bool = False,\n        suppress: Iterable[Union[str, ModuleType]] = (),\n        max_frames: int = 100,\n    ) -> None:\n        \"\"\"Prints a rich render of the last exception and traceback.\n\n        Args:\n            width (Optional[int], optional): Number of characters used to render code. Defaults to 100.\n            extra_lines (int, optional): Additional lines of code to render. Defaults to 3.\n            theme (str, optional): Override pygments theme used in traceback\n            word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.\n            show_locals (bool, optional): Enable display of local variables. Defaults to False.\n            suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.\n            max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.\n        \"\"\"\n        from .traceback import Traceback\n\n        traceback = Traceback(\n            width=width,\n            extra_lines=extra_lines,\n            theme=theme,\n            word_wrap=word_wrap,\n            show_locals=show_locals,\n            suppress=suppress,\n            max_frames=max_frames,\n        )\n        self.print(traceback)\n\n    @staticmethod\n    def _caller_frame_info(\n        offset: int,\n        currentframe: Callable[[], Optional[FrameType]] = inspect.currentframe,\n    ) -> Tuple[str, int, Dict[str, Any]]:\n        \"\"\"Get caller frame information.\n\n        Args:\n            offset (int): the caller offset within the current frame stack.\n            currentframe (Callable[[], Optional[FrameType]], optional): the callable to use to\n                retrieve the current frame. Defaults to ``inspect.currentframe``.\n\n        Returns:\n            Tuple[str, int, Dict[str, Any]]: A tuple containing the filename, the line number and\n                the dictionary of local variables associated with the caller frame.\n\n        Raises:\n            RuntimeError: If the stack offset is invalid.\n        \"\"\"\n        # Ignore the frame of this local helper\n        offset += 1\n\n        frame = currentframe()\n        if frame is not None:\n            # Use the faster currentframe where implemented\n            while offset and frame is not None:\n                frame = frame.f_back\n                offset -= 1\n            assert frame is not None\n            return frame.f_code.co_filename, frame.f_lineno, frame.f_locals\n        else:\n            # Fallback to the slower stack\n            frame_info = inspect.stack()[offset]\n            return frame_info.filename, frame_info.lineno, frame_info.frame.f_locals\n\n    def log(\n        self,\n        *objects: Any,\n        sep: str = \" \",\n        end: str = \"\\n\",\n        style: Optional[Union[str, Style]] = None,\n        justify: Optional[JustifyMethod] = None,\n        emoji: Optional[bool] = None,\n        markup: Optional[bool] = None,\n        highlight: Optional[bool] = None,\n        log_locals: bool = False,\n        _stack_offset: int = 1,\n    ) -> None:\n        \"\"\"Log rich content to the terminal.\n\n        Args:\n            objects (positional args): Objects to log to the terminal.\n            sep (str, optional): String to write between print data. Defaults to \" \".\n            end (str, optional): String to write at end of print data. Defaults to \"\\\\\\\\n\".\n            style (Union[str, Style], optional): A style to apply to output. Defaults to None.\n            justify (str, optional): One of \"left\", \"right\", \"center\", or \"full\". Defaults to ``None``.\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", or \"ellipsis\". Defaults to None.\n            emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to None.\n            markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to None.\n            highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to None.\n            log_locals (bool, optional): Boolean to enable logging of locals where ``log()``\n                was called. Defaults to False.\n            _stack_offset (int, optional): Offset of caller from end of call stack. Defaults to 1.\n        \"\"\"\n        if not objects:\n            objects = (NewLine(),)\n\n        render_hooks = self._render_hooks[:]\n\n        with self:\n            renderables = self._collect_renderables(\n                objects,\n                sep,\n                end,\n                justify=justify,\n                emoji=emoji,\n                markup=markup,\n                highlight=highlight,\n            )\n            if style is not None:\n                renderables = [Styled(renderable, style) for renderable in renderables]\n\n            filename, line_no, locals = self._caller_frame_info(_stack_offset)\n            link_path = None if filename.startswith(\"<\") else os.path.abspath(filename)\n            path = filename.rpartition(os.sep)[-1]\n            if log_locals:\n                locals_map = {\n                    key: value\n                    for key, value in locals.items()\n                    if not key.startswith(\"__\")\n                }\n                renderables.append(render_scope(locals_map, title=\"[i]locals\"))\n\n            renderables = [\n                self._log_render(\n                    self,\n                    renderables,\n                    log_time=self.get_datetime(),\n                    path=path,\n                    line_no=line_no,\n                    link_path=link_path,\n                )\n            ]\n            for hook in render_hooks:\n                renderables = hook.process_renderables(renderables)\n            new_segments: List[Segment] = []\n            extend = new_segments.extend\n            render = self.render\n            render_options = self.options\n            for renderable in renderables:\n                extend(render(renderable, render_options))\n            buffer_extend = self._buffer.extend\n            for line in Segment.split_and_crop_lines(\n                new_segments, self.width, pad=False\n            ):\n                buffer_extend(line)\n\n    def _check_buffer(self) -> None:\n        \"\"\"Check if the buffer may be rendered. Render it if it can (e.g. Console.quiet is False)\n        Rendering is supported on Windows, Unix and Jupyter environments. For\n        legacy Windows consoles, the win32 API is called directly.\n        This method will also record what it renders if recording is enabled via Console.record.\n        \"\"\"\n        if self.quiet:\n            del self._buffer[:]\n            return\n        with self._lock:\n            if self.record:\n                with self._record_buffer_lock:\n                    self._record_buffer.extend(self._buffer[:])\n\n            if self._buffer_index == 0:\n\n                if self.is_jupyter:  # pragma: no cover\n                    from .jupyter import display\n\n                    display(self._buffer, self._render_buffer(self._buffer[:]))\n                    del self._buffer[:]\n                else:\n                    if WINDOWS:\n                        use_legacy_windows_render = False\n                        if self.legacy_windows:\n                            try:\n                                use_legacy_windows_render = (\n                                    self.file.fileno() in _STD_STREAMS_OUTPUT\n                                )\n                            except (ValueError, io.UnsupportedOperation):\n                                pass\n\n                        if use_legacy_windows_render:\n                            from pip._vendor.rich._win32_console import LegacyWindowsTerm\n                            from pip._vendor.rich._windows_renderer import legacy_windows_render\n\n                            legacy_windows_render(\n                                self._buffer[:], LegacyWindowsTerm(self.file)\n                            )\n                        else:\n                            # Either a non-std stream on legacy Windows, or modern Windows.\n                            text = self._render_buffer(self._buffer[:])\n                            # https://bugs.python.org/issue37871\n                            write = self.file.write\n                            for line in text.splitlines(True):\n                                try:\n                                    write(line)\n                                except UnicodeEncodeError as error:\n                                    error.reason = f\"{error.reason}\\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***\"\n                                    raise\n                    else:\n                        text = self._render_buffer(self._buffer[:])\n                        try:\n                            self.file.write(text)\n                        except UnicodeEncodeError as error:\n                            error.reason = f\"{error.reason}\\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***\"\n                            raise\n\n                    self.file.flush()\n                    del self._buffer[:]\n\n    def _render_buffer(self, buffer: Iterable[Segment]) -> str:\n        \"\"\"Render buffered output, and clear buffer.\"\"\"\n        output: List[str] = []\n        append = output.append\n        color_system = self._color_system\n        legacy_windows = self.legacy_windows\n        not_terminal = not self.is_terminal\n        if self.no_color and color_system:\n            buffer = Segment.remove_color(buffer)\n        for text, style, control in buffer:\n            if style:\n                append(\n                    style.render(\n                        text,\n                        color_system=color_system,\n                        legacy_windows=legacy_windows,\n                    )\n                )\n            elif not (not_terminal and control):\n                append(text)\n\n        rendered = \"\".join(output)\n        return rendered\n\n    def input(\n        self,\n        prompt: TextType = \"\",\n        *,\n        markup: bool = True,\n        emoji: bool = True,\n        password: bool = False,\n        stream: Optional[TextIO] = None,\n    ) -> str:\n        \"\"\"Displays a prompt and waits for input from the user. The prompt may contain color / style.\n\n        It works in the same way as Python's builtin :func:`input` function and provides elaborate line editing and history features if Python's builtin :mod:`readline` module is previously loaded.\n\n        Args:\n            prompt (Union[str, Text]): Text to render in the prompt.\n            markup (bool, optional): Enable console markup (requires a str prompt). Defaults to True.\n            emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True.\n            password: (bool, optional): Hide typed text. Defaults to False.\n            stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None.\n\n        Returns:\n            str: Text read from stdin.\n        \"\"\"\n        if prompt:\n            self.print(prompt, markup=markup, emoji=emoji, end=\"\")\n        if password:\n            result = getpass(\"\", stream=stream)\n        else:\n            if stream:\n                result = stream.readline()\n            else:\n                result = input()\n        return result\n\n    def export_text(self, *, clear: bool = True, styles: bool = False) -> str:\n        \"\"\"Generate text from console contents (requires record=True argument in constructor).\n\n        Args:\n            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\n            styles (bool, optional): If ``True``, ansi escape codes will be included. ``False`` for plain text.\n                Defaults to ``False``.\n\n        Returns:\n            str: String containing console contents.\n\n        \"\"\"\n        assert (\n            self.record\n        ), \"To export console contents set record=True in the constructor or instance\"\n\n        with self._record_buffer_lock:\n            if styles:\n                text = \"\".join(\n                    (style.render(text) if style else text)\n                    for text, style, _ in self._record_buffer\n                )\n            else:\n                text = \"\".join(\n                    segment.text\n                    for segment in self._record_buffer\n                    if not segment.control\n                )\n            if clear:\n                del self._record_buffer[:]\n        return text\n\n    def save_text(self, path: str, *, clear: bool = True, styles: bool = False) -> None:\n        \"\"\"Generate text from console and save to a given location (requires record=True argument in constructor).\n\n        Args:\n            path (str): Path to write text files.\n            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\n            styles (bool, optional): If ``True``, ansi style codes will be included. ``False`` for plain text.\n                Defaults to ``False``.\n\n        \"\"\"\n        text = self.export_text(clear=clear, styles=styles)\n        with open(path, \"wt\", encoding=\"utf-8\") as write_file:\n            write_file.write(text)\n\n    def export_html(\n        self,\n        *,\n        theme: Optional[TerminalTheme] = None,\n        clear: bool = True,\n        code_format: Optional[str] = None,\n        inline_styles: bool = False,\n    ) -> str:\n        \"\"\"Generate HTML from console contents (requires record=True argument in constructor).\n\n        Args:\n            theme (TerminalTheme, optional): TerminalTheme object containing console colors.\n            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\n            code_format (str, optional): Format string to render HTML. In addition to '{foreground}',\n                '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``.\n            inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files\n                larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.\n                Defaults to False.\n\n        Returns:\n            str: String containing console contents as HTML.\n        \"\"\"\n        assert (\n            self.record\n        ), \"To export console contents set record=True in the constructor or instance\"\n        fragments: List[str] = []\n        append = fragments.append\n        _theme = theme or DEFAULT_TERMINAL_THEME\n        stylesheet = \"\"\n\n        render_code_format = CONSOLE_HTML_FORMAT if code_format is None else code_format\n\n        with self._record_buffer_lock:\n            if inline_styles:\n                for text, style, _ in Segment.filter_control(\n                    Segment.simplify(self._record_buffer)\n                ):\n                    text = escape(text)\n                    if style:\n                        rule = style.get_html_style(_theme)\n                        if style.link:\n                            text = f'<a href=\"{style.link}\">{text}</a>'\n                        text = f'<span style=\"{rule}\">{text}</span>' if rule else text\n                    append(text)\n            else:\n                styles: Dict[str, int] = {}\n                for text, style, _ in Segment.filter_control(\n                    Segment.simplify(self._record_buffer)\n                ):\n                    text = escape(text)\n                    if style:\n                        rule = style.get_html_style(_theme)\n                        style_number = styles.setdefault(rule, len(styles) + 1)\n                        if style.link:\n                            text = f'<a class=\"r{style_number}\" href=\"{style.link}\">{text}</a>'\n                        else:\n                            text = f'<span class=\"r{style_number}\">{text}</span>'\n                    append(text)\n                stylesheet_rules: List[str] = []\n                stylesheet_append = stylesheet_rules.append\n                for style_rule, style_number in styles.items():\n                    if style_rule:\n                        stylesheet_append(f\".r{style_number} {{{style_rule}}}\")\n                stylesheet = \"\\n\".join(stylesheet_rules)\n\n            rendered_code = render_code_format.format(\n                code=\"\".join(fragments),\n                stylesheet=stylesheet,\n                foreground=_theme.foreground_color.hex,\n                background=_theme.background_color.hex,\n            )\n            if clear:\n                del self._record_buffer[:]\n        return rendered_code\n\n    def save_html(\n        self,\n        path: str,\n        *,\n        theme: Optional[TerminalTheme] = None,\n        clear: bool = True,\n        code_format: str = CONSOLE_HTML_FORMAT,\n        inline_styles: bool = False,\n    ) -> None:\n        \"\"\"Generate HTML from console contents and write to a file (requires record=True argument in constructor).\n\n        Args:\n            path (str): Path to write html file.\n            theme (TerminalTheme, optional): TerminalTheme object containing console colors.\n            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\n            code_format (str, optional): Format string to render HTML. In addition to '{foreground}',\n                '{background}', and '{code}', should contain '{stylesheet}' if inline_styles is ``False``.\n            inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files\n                larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.\n                Defaults to False.\n\n        \"\"\"\n        html = self.export_html(\n            theme=theme,\n            clear=clear,\n            code_format=code_format,\n            inline_styles=inline_styles,\n        )\n        with open(path, \"wt\", encoding=\"utf-8\") as write_file:\n            write_file.write(html)\n\n    def export_svg(\n        self,\n        *,\n        title: str = \"Rich\",\n        theme: Optional[TerminalTheme] = None,\n        clear: bool = True,\n        code_format: str = CONSOLE_SVG_FORMAT,\n    ) -> str:\n        \"\"\"\n        Generate an SVG from the console contents (requires record=True in Console constructor).\n\n        Args:\n            path (str): The path to write the SVG to.\n            title (str): The title of the tab in the output image\n            theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal\n            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``\n            code_format (str): Format string used to generate the SVG. Rich will inject a number of variables\n                into the string in order to form the final SVG output. The default template used and the variables\n                injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable.\n        \"\"\"\n\n        from pip._vendor.rich.cells import cell_len\n\n        style_cache: Dict[Style, str] = {}\n\n        def get_svg_style(style: Style) -> str:\n            \"\"\"Convert a Style to CSS rules for SVG.\"\"\"\n            if style in style_cache:\n                return style_cache[style]\n            css_rules = []\n            color = (\n                _theme.foreground_color\n                if (style.color is None or style.color.is_default)\n                else style.color.get_truecolor(_theme)\n            )\n            bgcolor = (\n                _theme.background_color\n                if (style.bgcolor is None or style.bgcolor.is_default)\n                else style.bgcolor.get_truecolor(_theme)\n            )\n            if style.reverse:\n                color, bgcolor = bgcolor, color\n            if style.dim:\n                color = blend_rgb(color, bgcolor, 0.4)\n            css_rules.append(f\"fill: {color.hex}\")\n            if style.bold:\n                css_rules.append(\"font-weight: bold\")\n            if style.italic:\n                css_rules.append(\"font-style: italic;\")\n            if style.underline:\n                css_rules.append(\"text-decoration: underline;\")\n            if style.strike:\n                css_rules.append(\"text-decoration: line-through;\")\n\n            css = \";\".join(css_rules)\n            style_cache[style] = css\n            return css\n\n        _theme = theme or SVG_EXPORT_THEME\n\n        width = self.width\n        char_height = 20\n        char_width = char_height * 0.61\n        line_height = char_height * 1.22\n\n        margin_top = 1\n        margin_right = 1\n        margin_bottom = 1\n        margin_left = 1\n\n        padding_top = 40\n        padding_right = 8\n        padding_bottom = 8\n        padding_left = 8\n\n        padding_width = padding_left + padding_right\n        padding_height = padding_top + padding_bottom\n        margin_width = margin_left + margin_right\n        margin_height = margin_top + margin_bottom\n\n        text_backgrounds: List[str] = []\n        text_group: List[str] = []\n        classes: Dict[str, int] = {}\n        style_no = 1\n\n        def escape_text(text: str) -> str:\n            \"\"\"HTML escape text and replace spaces with nbsp.\"\"\"\n            return escape(text).replace(\" \", \"&#160;\")\n\n        def make_tag(\n            name: str, content: Optional[str] = None, **attribs: object\n        ) -> str:\n            \"\"\"Make a tag from name, content, and attributes.\"\"\"\n\n            def stringify(value: object) -> str:\n                if isinstance(value, (float)):\n                    return format(value, \"g\")\n                return str(value)\n\n            tag_attribs = \" \".join(\n                f'{k.lstrip(\"_\").replace(\"_\", \"-\")}=\"{stringify(v)}\"'\n                for k, v in attribs.items()\n            )\n            return (\n                f\"<{name} {tag_attribs}>{content}</{name}>\"\n                if content\n                else f\"<{name} {tag_attribs}/>\"\n            )\n\n        with self._record_buffer_lock:\n            segments = list(Segment.filter_control(self._record_buffer))\n            if clear:\n                self._record_buffer.clear()\n\n        unique_id = \"terminal-\" + str(\n            zlib.adler32(\n                (\"\".join(segment.text for segment in segments)).encode(\n                    \"utf-8\", \"ignore\"\n                )\n                + title.encode(\"utf-8\", \"ignore\")\n            )\n        )\n        y = 0\n        for y, line in enumerate(Segment.split_and_crop_lines(segments, length=width)):\n            x = 0\n            for text, style, _control in line:\n                style = style or Style()\n                rules = get_svg_style(style)\n                if rules not in classes:\n                    classes[rules] = style_no\n                    style_no += 1\n                class_name = f\"r{classes[rules]}\"\n\n                if style.reverse:\n                    has_background = True\n                    background = (\n                        _theme.foreground_color.hex\n                        if style.color is None\n                        else style.color.get_truecolor(_theme).hex\n                    )\n                else:\n                    bgcolor = style.bgcolor\n                    has_background = bgcolor is not None and not bgcolor.is_default\n                    background = (\n                        _theme.background_color.hex\n                        if style.bgcolor is None\n                        else style.bgcolor.get_truecolor(_theme).hex\n                    )\n\n                text_length = cell_len(text)\n                if has_background:\n                    text_backgrounds.append(\n                        make_tag(\n                            \"rect\",\n                            fill=background,\n                            x=x * char_width,\n                            y=y * line_height + 1.5,\n                            width=char_width * text_length,\n                            height=line_height + 0.25,\n                            shape_rendering=\"crispEdges\",\n                        )\n                    )\n\n                if text != \" \" * len(text):\n                    text_group.append(\n                        make_tag(\n                            \"text\",\n                            escape_text(text),\n                            _class=f\"{unique_id}-{class_name}\",\n                            x=x * char_width,\n                            y=y * line_height + char_height,\n                            textLength=char_width * len(text),\n                            clip_path=f\"url(#{unique_id}-line-{y})\",\n                        )\n                    )\n                x += cell_len(text)\n\n        line_offsets = [line_no * line_height + 1.5 for line_no in range(y)]\n        lines = \"\\n\".join(\n            f\"\"\"<clipPath id=\"{unique_id}-line-{line_no}\">\n    {make_tag(\"rect\", x=0, y=offset, width=char_width * width, height=line_height + 0.25)}\n            </clipPath>\"\"\"\n            for line_no, offset in enumerate(line_offsets)\n        )\n\n        styles = \"\\n\".join(\n            f\".{unique_id}-r{rule_no} {{ {css} }}\" for css, rule_no in classes.items()\n        )\n        backgrounds = \"\".join(text_backgrounds)\n        matrix = \"\".join(text_group)\n\n        terminal_width = ceil(width * char_width + padding_width)\n        terminal_height = (y + 1) * line_height + padding_height\n        chrome = make_tag(\n            \"rect\",\n            fill=_theme.background_color.hex,\n            stroke=\"rgba(255,255,255,0.35)\",\n            stroke_width=\"1\",\n            x=margin_left,\n            y=margin_top,\n            width=terminal_width,\n            height=terminal_height,\n            rx=8,\n        )\n\n        title_color = _theme.foreground_color.hex\n        if title:\n            chrome += make_tag(\n                \"text\",\n                escape_text(title),\n                _class=f\"{unique_id}-title\",\n                fill=title_color,\n                text_anchor=\"middle\",\n                x=terminal_width // 2,\n                y=margin_top + char_height + 6,\n            )\n        chrome += f\"\"\"\n            <g transform=\"translate(26,22)\">\n            <circle cx=\"0\" cy=\"0\" r=\"7\" fill=\"#ff5f57\"/>\n            <circle cx=\"22\" cy=\"0\" r=\"7\" fill=\"#febc2e\"/>\n            <circle cx=\"44\" cy=\"0\" r=\"7\" fill=\"#28c840\"/>\n            </g>\n        \"\"\"\n\n        svg = code_format.format(\n            unique_id=unique_id,\n            char_width=char_width,\n            char_height=char_height,\n            line_height=line_height,\n            terminal_width=char_width * width - 1,\n            terminal_height=(y + 1) * line_height - 1,\n            width=terminal_width + margin_width,\n            height=terminal_height + margin_height,\n            terminal_x=margin_left + padding_left,\n            terminal_y=margin_top + padding_top,\n            styles=styles,\n            chrome=chrome,\n            backgrounds=backgrounds,\n            matrix=matrix,\n            lines=lines,\n        )\n        return svg\n\n    def save_svg(\n        self,\n        path: str,\n        *,\n        title: str = \"Rich\",\n        theme: Optional[TerminalTheme] = None,\n        clear: bool = True,\n        code_format: str = CONSOLE_SVG_FORMAT,\n    ) -> None:\n        \"\"\"Generate an SVG file from the console contents (requires record=True in Console constructor).\n\n        Args:\n            path (str): The path to write the SVG to.\n            title (str): The title of the tab in the output image\n            theme (TerminalTheme, optional): The ``TerminalTheme`` object to use to style the terminal\n            clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``\n            code_format (str): Format string used to generate the SVG. Rich will inject a number of variables\n                into the string in order to form the final SVG output. The default template used and the variables\n                injected by Rich can be found by inspecting the ``console.CONSOLE_SVG_FORMAT`` variable.\n        \"\"\"\n        svg = self.export_svg(\n            title=title,\n            theme=theme,\n            clear=clear,\n            code_format=code_format,\n        )\n        with open(path, \"wt\", encoding=\"utf-8\") as write_file:\n            write_file.write(svg)\n\n\ndef _svg_hash(svg_main_code: str) -> str:\n    \"\"\"Returns a unique hash for the given SVG main code.\n\n    Args:\n        svg_main_code (str): The content we're going to inject in the SVG envelope.\n\n    Returns:\n        str: a hash of the given content\n    \"\"\"\n    return str(zlib.adler32(svg_main_code.encode()))\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    console = Console(record=True)\n\n    console.log(\n        \"JSONRPC [i]request[/i]\",\n        5,\n        1.3,\n        True,\n        False,\n        None,\n        {\n            \"jsonrpc\": \"2.0\",\n            \"method\": \"subtract\",\n            \"params\": {\"minuend\": 42, \"subtrahend\": 23},\n            \"id\": 3,\n        },\n    )\n\n    console.log(\"Hello, World!\", \"{'a': 1}\", repr(console))\n\n    console.print(\n        {\n            \"name\": None,\n            \"empty\": [],\n            \"quiz\": {\n                \"sport\": {\n                    \"answered\": True,\n                    \"q1\": {\n                        \"question\": \"Which one is correct team name in NBA?\",\n                        \"options\": [\n                            \"New York Bulls\",\n                            \"Los Angeles Kings\",\n                            \"Golden State Warriors\",\n                            \"Huston Rocket\",\n                        ],\n                        \"answer\": \"Huston Rocket\",\n                    },\n                },\n                \"maths\": {\n                    \"answered\": False,\n                    \"q1\": {\n                        \"question\": \"5 + 7 = ?\",\n                        \"options\": [10, 11, 12, 13],\n                        \"answer\": 12,\n                    },\n                    \"q2\": {\n                        \"question\": \"12 - 8 = ?\",\n                        \"options\": [1, 2, 3, 4],\n                        \"answer\": 4,\n                    },\n                },\n            },\n        }\n    )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/constrain.py",
    "content": "from typing import Optional, TYPE_CHECKING\n\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderableType, RenderResult\n\n\nclass Constrain(JupyterMixin):\n    \"\"\"Constrain the width of a renderable to a given number of characters.\n\n    Args:\n        renderable (RenderableType): A renderable object.\n        width (int, optional): The maximum width (in characters) to render. Defaults to 80.\n    \"\"\"\n\n    def __init__(self, renderable: \"RenderableType\", width: Optional[int] = 80) -> None:\n        self.renderable = renderable\n        self.width = width\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        if self.width is None:\n            yield self.renderable\n        else:\n            child_options = options.update_width(min(self.width, options.max_width))\n            yield from console.render(self.renderable, child_options)\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        if self.width is not None:\n            options = options.update_width(self.width)\n        measurement = Measurement.get(console, options, self.renderable)\n        return measurement\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/containers.py",
    "content": "from itertools import zip_longest\nfrom typing import (\n    Iterator,\n    Iterable,\n    List,\n    Optional,\n    Union,\n    overload,\n    TypeVar,\n    TYPE_CHECKING,\n)\n\nif TYPE_CHECKING:\n    from .console import (\n        Console,\n        ConsoleOptions,\n        JustifyMethod,\n        OverflowMethod,\n        RenderResult,\n        RenderableType,\n    )\n    from .text import Text\n\nfrom .cells import cell_len\nfrom .measure import Measurement\n\nT = TypeVar(\"T\")\n\n\nclass Renderables:\n    \"\"\"A list subclass which renders its contents to the console.\"\"\"\n\n    def __init__(\n        self, renderables: Optional[Iterable[\"RenderableType\"]] = None\n    ) -> None:\n        self._renderables: List[\"RenderableType\"] = (\n            list(renderables) if renderables is not None else []\n        )\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        \"\"\"Console render method to insert line-breaks.\"\"\"\n        yield from self._renderables\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        dimensions = [\n            Measurement.get(console, options, renderable)\n            for renderable in self._renderables\n        ]\n        if not dimensions:\n            return Measurement(1, 1)\n        _min = max(dimension.minimum for dimension in dimensions)\n        _max = max(dimension.maximum for dimension in dimensions)\n        return Measurement(_min, _max)\n\n    def append(self, renderable: \"RenderableType\") -> None:\n        self._renderables.append(renderable)\n\n    def __iter__(self) -> Iterable[\"RenderableType\"]:\n        return iter(self._renderables)\n\n\nclass Lines:\n    \"\"\"A list subclass which can render to the console.\"\"\"\n\n    def __init__(self, lines: Iterable[\"Text\"] = ()) -> None:\n        self._lines: List[\"Text\"] = list(lines)\n\n    def __repr__(self) -> str:\n        return f\"Lines({self._lines!r})\"\n\n    def __iter__(self) -> Iterator[\"Text\"]:\n        return iter(self._lines)\n\n    @overload\n    def __getitem__(self, index: int) -> \"Text\":\n        ...\n\n    @overload\n    def __getitem__(self, index: slice) -> List[\"Text\"]:\n        ...\n\n    def __getitem__(self, index: Union[slice, int]) -> Union[\"Text\", List[\"Text\"]]:\n        return self._lines[index]\n\n    def __setitem__(self, index: int, value: \"Text\") -> \"Lines\":\n        self._lines[index] = value\n        return self\n\n    def __len__(self) -> int:\n        return self._lines.__len__()\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        \"\"\"Console render method to insert line-breaks.\"\"\"\n        yield from self._lines\n\n    def append(self, line: \"Text\") -> None:\n        self._lines.append(line)\n\n    def extend(self, lines: Iterable[\"Text\"]) -> None:\n        self._lines.extend(lines)\n\n    def pop(self, index: int = -1) -> \"Text\":\n        return self._lines.pop(index)\n\n    def justify(\n        self,\n        console: \"Console\",\n        width: int,\n        justify: \"JustifyMethod\" = \"left\",\n        overflow: \"OverflowMethod\" = \"fold\",\n    ) -> None:\n        \"\"\"Justify and overflow text to a given width.\n\n        Args:\n            console (Console): Console instance.\n            width (int): Number of characters per line.\n            justify (str, optional): Default justify method for text: \"left\", \"center\", \"full\" or \"right\". Defaults to \"left\".\n            overflow (str, optional): Default overflow for text: \"crop\", \"fold\", or \"ellipsis\". Defaults to \"fold\".\n\n        \"\"\"\n        from .text import Text\n\n        if justify == \"left\":\n            for line in self._lines:\n                line.truncate(width, overflow=overflow, pad=True)\n        elif justify == \"center\":\n            for line in self._lines:\n                line.rstrip()\n                line.truncate(width, overflow=overflow)\n                line.pad_left((width - cell_len(line.plain)) // 2)\n                line.pad_right(width - cell_len(line.plain))\n        elif justify == \"right\":\n            for line in self._lines:\n                line.rstrip()\n                line.truncate(width, overflow=overflow)\n                line.pad_left(width - cell_len(line.plain))\n        elif justify == \"full\":\n            for line_index, line in enumerate(self._lines):\n                if line_index == len(self._lines) - 1:\n                    break\n                words = line.split(\" \")\n                words_size = sum(cell_len(word.plain) for word in words)\n                num_spaces = len(words) - 1\n                spaces = [1 for _ in range(num_spaces)]\n                index = 0\n                if spaces:\n                    while words_size + num_spaces < width:\n                        spaces[len(spaces) - index - 1] += 1\n                        num_spaces += 1\n                        index = (index + 1) % len(spaces)\n                tokens: List[Text] = []\n                for index, (word, next_word) in enumerate(\n                    zip_longest(words, words[1:])\n                ):\n                    tokens.append(word)\n                    if index < len(spaces):\n                        style = word.get_style_at_offset(console, -1)\n                        next_style = next_word.get_style_at_offset(console, 0)\n                        space_style = style if style == next_style else line.style\n                        tokens.append(Text(\" \" * spaces[index], style=space_style))\n                self[line_index] = Text(\"\").join(tokens)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/control.py",
    "content": "import sys\nimport time\nfrom typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Union\n\nif sys.version_info >= (3, 8):\n    from typing import Final\nelse:\n    from pip._vendor.typing_extensions import Final  # pragma: no cover\n\nfrom .segment import ControlCode, ControlType, Segment\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderResult\n\nSTRIP_CONTROL_CODES: Final = [\n    7,  # Bell\n    8,  # Backspace\n    11,  # Vertical tab\n    12,  # Form feed\n    13,  # Carriage return\n]\n_CONTROL_STRIP_TRANSLATE: Final = {\n    _codepoint: None for _codepoint in STRIP_CONTROL_CODES\n}\n\nCONTROL_ESCAPE: Final = {\n    7: \"\\\\a\",\n    8: \"\\\\b\",\n    11: \"\\\\v\",\n    12: \"\\\\f\",\n    13: \"\\\\r\",\n}\n\nCONTROL_CODES_FORMAT: Dict[int, Callable[..., str]] = {\n    ControlType.BELL: lambda: \"\\x07\",\n    ControlType.CARRIAGE_RETURN: lambda: \"\\r\",\n    ControlType.HOME: lambda: \"\\x1b[H\",\n    ControlType.CLEAR: lambda: \"\\x1b[2J\",\n    ControlType.ENABLE_ALT_SCREEN: lambda: \"\\x1b[?1049h\",\n    ControlType.DISABLE_ALT_SCREEN: lambda: \"\\x1b[?1049l\",\n    ControlType.SHOW_CURSOR: lambda: \"\\x1b[?25h\",\n    ControlType.HIDE_CURSOR: lambda: \"\\x1b[?25l\",\n    ControlType.CURSOR_UP: lambda param: f\"\\x1b[{param}A\",\n    ControlType.CURSOR_DOWN: lambda param: f\"\\x1b[{param}B\",\n    ControlType.CURSOR_FORWARD: lambda param: f\"\\x1b[{param}C\",\n    ControlType.CURSOR_BACKWARD: lambda param: f\"\\x1b[{param}D\",\n    ControlType.CURSOR_MOVE_TO_COLUMN: lambda param: f\"\\x1b[{param+1}G\",\n    ControlType.ERASE_IN_LINE: lambda param: f\"\\x1b[{param}K\",\n    ControlType.CURSOR_MOVE_TO: lambda x, y: f\"\\x1b[{y+1};{x+1}H\",\n    ControlType.SET_WINDOW_TITLE: lambda title: f\"\\x1b]0;{title}\\x07\",\n}\n\n\nclass Control:\n    \"\"\"A renderable that inserts a control code (non printable but may move cursor).\n\n    Args:\n        *codes (str): Positional arguments are either a :class:`~rich.segment.ControlType` enum or a\n            tuple of ControlType and an integer parameter\n    \"\"\"\n\n    __slots__ = [\"segment\"]\n\n    def __init__(self, *codes: Union[ControlType, ControlCode]) -> None:\n        control_codes: List[ControlCode] = [\n            (code,) if isinstance(code, ControlType) else code for code in codes\n        ]\n        _format_map = CONTROL_CODES_FORMAT\n        rendered_codes = \"\".join(\n            _format_map[code](*parameters) for code, *parameters in control_codes\n        )\n        self.segment = Segment(rendered_codes, None, control_codes)\n\n    @classmethod\n    def bell(cls) -> \"Control\":\n        \"\"\"Ring the 'bell'.\"\"\"\n        return cls(ControlType.BELL)\n\n    @classmethod\n    def home(cls) -> \"Control\":\n        \"\"\"Move cursor to 'home' position.\"\"\"\n        return cls(ControlType.HOME)\n\n    @classmethod\n    def move(cls, x: int = 0, y: int = 0) -> \"Control\":\n        \"\"\"Move cursor relative to current position.\n\n        Args:\n            x (int): X offset.\n            y (int): Y offset.\n\n        Returns:\n            ~Control: Control object.\n\n        \"\"\"\n\n        def get_codes() -> Iterable[ControlCode]:\n            control = ControlType\n            if x:\n                yield (\n                    control.CURSOR_FORWARD if x > 0 else control.CURSOR_BACKWARD,\n                    abs(x),\n                )\n            if y:\n                yield (\n                    control.CURSOR_DOWN if y > 0 else control.CURSOR_UP,\n                    abs(y),\n                )\n\n        control = cls(*get_codes())\n        return control\n\n    @classmethod\n    def move_to_column(cls, x: int, y: int = 0) -> \"Control\":\n        \"\"\"Move to the given column, optionally add offset to row.\n\n        Returns:\n            x (int): absolute x (column)\n            y (int): optional y offset (row)\n\n        Returns:\n            ~Control: Control object.\n        \"\"\"\n\n        return (\n            cls(\n                (ControlType.CURSOR_MOVE_TO_COLUMN, x),\n                (\n                    ControlType.CURSOR_DOWN if y > 0 else ControlType.CURSOR_UP,\n                    abs(y),\n                ),\n            )\n            if y\n            else cls((ControlType.CURSOR_MOVE_TO_COLUMN, x))\n        )\n\n    @classmethod\n    def move_to(cls, x: int, y: int) -> \"Control\":\n        \"\"\"Move cursor to absolute position.\n\n        Args:\n            x (int): x offset (column)\n            y (int): y offset (row)\n\n        Returns:\n            ~Control: Control object.\n        \"\"\"\n        return cls((ControlType.CURSOR_MOVE_TO, x, y))\n\n    @classmethod\n    def clear(cls) -> \"Control\":\n        \"\"\"Clear the screen.\"\"\"\n        return cls(ControlType.CLEAR)\n\n    @classmethod\n    def show_cursor(cls, show: bool) -> \"Control\":\n        \"\"\"Show or hide the cursor.\"\"\"\n        return cls(ControlType.SHOW_CURSOR if show else ControlType.HIDE_CURSOR)\n\n    @classmethod\n    def alt_screen(cls, enable: bool) -> \"Control\":\n        \"\"\"Enable or disable alt screen.\"\"\"\n        if enable:\n            return cls(ControlType.ENABLE_ALT_SCREEN, ControlType.HOME)\n        else:\n            return cls(ControlType.DISABLE_ALT_SCREEN)\n\n    @classmethod\n    def title(cls, title: str) -> \"Control\":\n        \"\"\"Set the terminal window title\n\n        Args:\n            title (str): The new terminal window title\n        \"\"\"\n        return cls((ControlType.SET_WINDOW_TITLE, title))\n\n    def __str__(self) -> str:\n        return self.segment.text\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        if self.segment.text:\n            yield self.segment\n\n\ndef strip_control_codes(\n    text: str, _translate_table: Dict[int, None] = _CONTROL_STRIP_TRANSLATE\n) -> str:\n    \"\"\"Remove control codes from text.\n\n    Args:\n        text (str): A string possibly contain control codes.\n\n    Returns:\n        str: String with control codes removed.\n    \"\"\"\n    return text.translate(_translate_table)\n\n\ndef escape_control_codes(\n    text: str,\n    _translate_table: Dict[int, str] = CONTROL_ESCAPE,\n) -> str:\n    \"\"\"Replace control codes with their \"escaped\" equivalent in the given text.\n    (e.g. \"\\b\" becomes \"\\\\b\")\n\n    Args:\n        text (str): A string possibly containing control codes.\n\n    Returns:\n        str: String with control codes replaced with their escaped version.\n    \"\"\"\n    return text.translate(_translate_table)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.console import Console\n\n    console = Console()\n    console.print(\"Look at the title of your terminal window ^\")\n    # console.print(Control((ControlType.SET_WINDOW_TITLE, \"Hello, world!\")))\n    for i in range(10):\n        console.set_window_title(\"🚀 Loading\" + \".\" * i)\n        time.sleep(0.5)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/default_styles.py",
    "content": "from typing import Dict\n\nfrom .style import Style\n\nDEFAULT_STYLES: Dict[str, Style] = {\n    \"none\": Style.null(),\n    \"reset\": Style(\n        color=\"default\",\n        bgcolor=\"default\",\n        dim=False,\n        bold=False,\n        italic=False,\n        underline=False,\n        blink=False,\n        blink2=False,\n        reverse=False,\n        conceal=False,\n        strike=False,\n    ),\n    \"dim\": Style(dim=True),\n    \"bright\": Style(dim=False),\n    \"bold\": Style(bold=True),\n    \"strong\": Style(bold=True),\n    \"code\": Style(reverse=True, bold=True),\n    \"italic\": Style(italic=True),\n    \"emphasize\": Style(italic=True),\n    \"underline\": Style(underline=True),\n    \"blink\": Style(blink=True),\n    \"blink2\": Style(blink2=True),\n    \"reverse\": Style(reverse=True),\n    \"strike\": Style(strike=True),\n    \"black\": Style(color=\"black\"),\n    \"red\": Style(color=\"red\"),\n    \"green\": Style(color=\"green\"),\n    \"yellow\": Style(color=\"yellow\"),\n    \"magenta\": Style(color=\"magenta\"),\n    \"cyan\": Style(color=\"cyan\"),\n    \"white\": Style(color=\"white\"),\n    \"inspect.attr\": Style(color=\"yellow\", italic=True),\n    \"inspect.attr.dunder\": Style(color=\"yellow\", italic=True, dim=True),\n    \"inspect.callable\": Style(bold=True, color=\"red\"),\n    \"inspect.async_def\": Style(italic=True, color=\"bright_cyan\"),\n    \"inspect.def\": Style(italic=True, color=\"bright_cyan\"),\n    \"inspect.class\": Style(italic=True, color=\"bright_cyan\"),\n    \"inspect.error\": Style(bold=True, color=\"red\"),\n    \"inspect.equals\": Style(),\n    \"inspect.help\": Style(color=\"cyan\"),\n    \"inspect.doc\": Style(dim=True),\n    \"inspect.value.border\": Style(color=\"green\"),\n    \"live.ellipsis\": Style(bold=True, color=\"red\"),\n    \"layout.tree.row\": Style(dim=False, color=\"red\"),\n    \"layout.tree.column\": Style(dim=False, color=\"blue\"),\n    \"logging.keyword\": Style(bold=True, color=\"yellow\"),\n    \"logging.level.notset\": Style(dim=True),\n    \"logging.level.debug\": Style(color=\"green\"),\n    \"logging.level.info\": Style(color=\"blue\"),\n    \"logging.level.warning\": Style(color=\"red\"),\n    \"logging.level.error\": Style(color=\"red\", bold=True),\n    \"logging.level.critical\": Style(color=\"red\", bold=True, reverse=True),\n    \"log.level\": Style.null(),\n    \"log.time\": Style(color=\"cyan\", dim=True),\n    \"log.message\": Style.null(),\n    \"log.path\": Style(dim=True),\n    \"repr.ellipsis\": Style(color=\"yellow\"),\n    \"repr.indent\": Style(color=\"green\", dim=True),\n    \"repr.error\": Style(color=\"red\", bold=True),\n    \"repr.str\": Style(color=\"green\", italic=False, bold=False),\n    \"repr.brace\": Style(bold=True),\n    \"repr.comma\": Style(bold=True),\n    \"repr.ipv4\": Style(bold=True, color=\"bright_green\"),\n    \"repr.ipv6\": Style(bold=True, color=\"bright_green\"),\n    \"repr.eui48\": Style(bold=True, color=\"bright_green\"),\n    \"repr.eui64\": Style(bold=True, color=\"bright_green\"),\n    \"repr.tag_start\": Style(bold=True),\n    \"repr.tag_name\": Style(color=\"bright_magenta\", bold=True),\n    \"repr.tag_contents\": Style(color=\"default\"),\n    \"repr.tag_end\": Style(bold=True),\n    \"repr.attrib_name\": Style(color=\"yellow\", italic=False),\n    \"repr.attrib_equal\": Style(bold=True),\n    \"repr.attrib_value\": Style(color=\"magenta\", italic=False),\n    \"repr.number\": Style(color=\"cyan\", bold=True, italic=False),\n    \"repr.number_complex\": Style(color=\"cyan\", bold=True, italic=False),  # same\n    \"repr.bool_true\": Style(color=\"bright_green\", italic=True),\n    \"repr.bool_false\": Style(color=\"bright_red\", italic=True),\n    \"repr.none\": Style(color=\"magenta\", italic=True),\n    \"repr.url\": Style(underline=True, color=\"bright_blue\", italic=False, bold=False),\n    \"repr.uuid\": Style(color=\"bright_yellow\", bold=False),\n    \"repr.call\": Style(color=\"magenta\", bold=True),\n    \"repr.path\": Style(color=\"magenta\"),\n    \"repr.filename\": Style(color=\"bright_magenta\"),\n    \"rule.line\": Style(color=\"bright_green\"),\n    \"rule.text\": Style.null(),\n    \"json.brace\": Style(bold=True),\n    \"json.bool_true\": Style(color=\"bright_green\", italic=True),\n    \"json.bool_false\": Style(color=\"bright_red\", italic=True),\n    \"json.null\": Style(color=\"magenta\", italic=True),\n    \"json.number\": Style(color=\"cyan\", bold=True, italic=False),\n    \"json.str\": Style(color=\"green\", italic=False, bold=False),\n    \"json.key\": Style(color=\"blue\", bold=True),\n    \"prompt\": Style.null(),\n    \"prompt.choices\": Style(color=\"magenta\", bold=True),\n    \"prompt.default\": Style(color=\"cyan\", bold=True),\n    \"prompt.invalid\": Style(color=\"red\"),\n    \"prompt.invalid.choice\": Style(color=\"red\"),\n    \"pretty\": Style.null(),\n    \"scope.border\": Style(color=\"blue\"),\n    \"scope.key\": Style(color=\"yellow\", italic=True),\n    \"scope.key.special\": Style(color=\"yellow\", italic=True, dim=True),\n    \"scope.equals\": Style(color=\"red\"),\n    \"table.header\": Style(bold=True),\n    \"table.footer\": Style(bold=True),\n    \"table.cell\": Style.null(),\n    \"table.title\": Style(italic=True),\n    \"table.caption\": Style(italic=True, dim=True),\n    \"traceback.error\": Style(color=\"red\", italic=True),\n    \"traceback.border.syntax_error\": Style(color=\"bright_red\"),\n    \"traceback.border\": Style(color=\"red\"),\n    \"traceback.text\": Style.null(),\n    \"traceback.title\": Style(color=\"red\", bold=True),\n    \"traceback.exc_type\": Style(color=\"bright_red\", bold=True),\n    \"traceback.exc_value\": Style.null(),\n    \"traceback.offset\": Style(color=\"bright_red\", bold=True),\n    \"bar.back\": Style(color=\"grey23\"),\n    \"bar.complete\": Style(color=\"rgb(249,38,114)\"),\n    \"bar.finished\": Style(color=\"rgb(114,156,31)\"),\n    \"bar.pulse\": Style(color=\"rgb(249,38,114)\"),\n    \"progress.description\": Style.null(),\n    \"progress.filesize\": Style(color=\"green\"),\n    \"progress.filesize.total\": Style(color=\"green\"),\n    \"progress.download\": Style(color=\"green\"),\n    \"progress.elapsed\": Style(color=\"yellow\"),\n    \"progress.percentage\": Style(color=\"magenta\"),\n    \"progress.remaining\": Style(color=\"cyan\"),\n    \"progress.data.speed\": Style(color=\"red\"),\n    \"progress.spinner\": Style(color=\"green\"),\n    \"status.spinner\": Style(color=\"green\"),\n    \"tree\": Style(),\n    \"tree.line\": Style(),\n    \"markdown.paragraph\": Style(),\n    \"markdown.text\": Style(),\n    \"markdown.emph\": Style(italic=True),\n    \"markdown.strong\": Style(bold=True),\n    \"markdown.code\": Style(bgcolor=\"black\", color=\"bright_white\"),\n    \"markdown.code_block\": Style(dim=True, color=\"cyan\", bgcolor=\"black\"),\n    \"markdown.block_quote\": Style(color=\"magenta\"),\n    \"markdown.list\": Style(color=\"cyan\"),\n    \"markdown.item\": Style(),\n    \"markdown.item.bullet\": Style(color=\"yellow\", bold=True),\n    \"markdown.item.number\": Style(color=\"yellow\", bold=True),\n    \"markdown.hr\": Style(color=\"yellow\"),\n    \"markdown.h1.border\": Style(),\n    \"markdown.h1\": Style(bold=True),\n    \"markdown.h2\": Style(bold=True, underline=True),\n    \"markdown.h3\": Style(bold=True),\n    \"markdown.h4\": Style(bold=True, dim=True),\n    \"markdown.h5\": Style(underline=True),\n    \"markdown.h6\": Style(italic=True),\n    \"markdown.h7\": Style(italic=True, dim=True),\n    \"markdown.link\": Style(color=\"bright_blue\"),\n    \"markdown.link_url\": Style(color=\"blue\"),\n    \"iso8601.date\": Style(color=\"blue\"),\n    \"iso8601.time\": Style(color=\"magenta\"),\n    \"iso8601.timezone\": Style(color=\"yellow\"),\n}\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import argparse\n    import io\n\n    from pip._vendor.rich.console import Console\n    from pip._vendor.rich.table import Table\n    from pip._vendor.rich.text import Text\n\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--html\", action=\"store_true\", help=\"Export as HTML table\")\n    args = parser.parse_args()\n    html: bool = args.html\n    console = Console(record=True, width=70, file=io.StringIO()) if html else Console()\n\n    table = Table(\"Name\", \"Styling\")\n\n    for style_name, style in DEFAULT_STYLES.items():\n        table.add_row(Text(style_name, style=style), str(style))\n\n    console.print(table)\n    if html:\n        print(console.export_html(inline_styles=True))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/diagnose.py",
    "content": "import os\nimport platform\n\nfrom pip._vendor.rich import inspect\nfrom pip._vendor.rich.console import Console, get_windows_console_features\nfrom pip._vendor.rich.panel import Panel\nfrom pip._vendor.rich.pretty import Pretty\n\n\ndef report() -> None:  # pragma: no cover\n    \"\"\"Print a report to the terminal with debugging information\"\"\"\n    console = Console()\n    inspect(console)\n    features = get_windows_console_features()\n    inspect(features)\n\n    env_names = (\n        \"TERM\",\n        \"COLORTERM\",\n        \"CLICOLOR\",\n        \"NO_COLOR\",\n        \"TERM_PROGRAM\",\n        \"COLUMNS\",\n        \"LINES\",\n        \"JUPYTER_COLUMNS\",\n        \"JUPYTER_LINES\",\n        \"JPY_PARENT_PID\",\n        \"VSCODE_VERBOSE_LOGGING\",\n    )\n    env = {name: os.getenv(name) for name in env_names}\n    console.print(Panel.fit((Pretty(env)), title=\"[b]Environment Variables\"))\n\n    console.print(f'platform=\"{platform.system()}\"')\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    report()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/emoji.py",
    "content": "import sys\nfrom typing import TYPE_CHECKING, Optional, Union\n\nfrom .jupyter import JupyterMixin\nfrom .segment import Segment\nfrom .style import Style\nfrom ._emoji_codes import EMOJI\nfrom ._emoji_replace import _emoji_replace\n\nif sys.version_info >= (3, 8):\n    from typing import Literal\nelse:\n    from pip._vendor.typing_extensions import Literal  # pragma: no cover\n\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderResult\n\n\nEmojiVariant = Literal[\"emoji\", \"text\"]\n\n\nclass NoEmoji(Exception):\n    \"\"\"No emoji by that name.\"\"\"\n\n\nclass Emoji(JupyterMixin):\n    __slots__ = [\"name\", \"style\", \"_char\", \"variant\"]\n\n    VARIANTS = {\"text\": \"\\uFE0E\", \"emoji\": \"\\uFE0F\"}\n\n    def __init__(\n        self,\n        name: str,\n        style: Union[str, Style] = \"none\",\n        variant: Optional[EmojiVariant] = None,\n    ) -> None:\n        \"\"\"A single emoji character.\n\n        Args:\n            name (str): Name of emoji.\n            style (Union[str, Style], optional): Optional style. Defaults to None.\n\n        Raises:\n            NoEmoji: If the emoji doesn't exist.\n        \"\"\"\n        self.name = name\n        self.style = style\n        self.variant = variant\n        try:\n            self._char = EMOJI[name]\n        except KeyError:\n            raise NoEmoji(f\"No emoji called {name!r}\")\n        if variant is not None:\n            self._char += self.VARIANTS.get(variant, \"\")\n\n    @classmethod\n    def replace(cls, text: str) -> str:\n        \"\"\"Replace emoji markup with corresponding unicode characters.\n\n        Args:\n            text (str): A string with emojis codes, e.g. \"Hello :smiley:!\"\n\n        Returns:\n            str: A string with emoji codes replaces with actual emoji.\n        \"\"\"\n        return _emoji_replace(text)\n\n    def __repr__(self) -> str:\n        return f\"<emoji {self.name!r}>\"\n\n    def __str__(self) -> str:\n        return self._char\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        yield Segment(self._char, console.get_style(self.style))\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import sys\n\n    from pip._vendor.rich.columns import Columns\n    from pip._vendor.rich.console import Console\n\n    console = Console(record=True)\n\n    columns = Columns(\n        (f\":{name}: {name}\" for name in sorted(EMOJI.keys()) if \"\\u200D\" not in name),\n        column_first=True,\n    )\n\n    console.print(columns)\n    if len(sys.argv) > 1:\n        console.save_html(sys.argv[1])\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/errors.py",
    "content": "class ConsoleError(Exception):\n    \"\"\"An error in console operation.\"\"\"\n\n\nclass StyleError(Exception):\n    \"\"\"An error in styles.\"\"\"\n\n\nclass StyleSyntaxError(ConsoleError):\n    \"\"\"Style was badly formatted.\"\"\"\n\n\nclass MissingStyle(StyleError):\n    \"\"\"No such style.\"\"\"\n\n\nclass StyleStackError(ConsoleError):\n    \"\"\"Style stack is invalid.\"\"\"\n\n\nclass NotRenderableError(ConsoleError):\n    \"\"\"Object is not renderable.\"\"\"\n\n\nclass MarkupError(ConsoleError):\n    \"\"\"Markup was badly formatted.\"\"\"\n\n\nclass LiveError(ConsoleError):\n    \"\"\"Error related to Live display.\"\"\"\n\n\nclass NoAltScreen(ConsoleError):\n    \"\"\"Alt screen mode was required.\"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/file_proxy.py",
    "content": "import io\nfrom typing import IO, TYPE_CHECKING, Any, List\n\nfrom .ansi import AnsiDecoder\nfrom .text import Text\n\nif TYPE_CHECKING:\n    from .console import Console\n\n\nclass FileProxy(io.TextIOBase):\n    \"\"\"Wraps a file (e.g. sys.stdout) and redirects writes to a console.\"\"\"\n\n    def __init__(self, console: \"Console\", file: IO[str]) -> None:\n        self.__console = console\n        self.__file = file\n        self.__buffer: List[str] = []\n        self.__ansi_decoder = AnsiDecoder()\n\n    @property\n    def rich_proxied_file(self) -> IO[str]:\n        \"\"\"Get proxied file.\"\"\"\n        return self.__file\n\n    def __getattr__(self, name: str) -> Any:\n        return getattr(self.__file, name)\n\n    def write(self, text: str) -> int:\n        if not isinstance(text, str):\n            raise TypeError(f\"write() argument must be str, not {type(text).__name__}\")\n        buffer = self.__buffer\n        lines: List[str] = []\n        while text:\n            line, new_line, text = text.partition(\"\\n\")\n            if new_line:\n                lines.append(\"\".join(buffer) + line)\n                del buffer[:]\n            else:\n                buffer.append(line)\n                break\n        if lines:\n            console = self.__console\n            with console:\n                output = Text(\"\\n\").join(\n                    self.__ansi_decoder.decode_line(line) for line in lines\n                )\n                console.print(output)\n        return len(text)\n\n    def flush(self) -> None:\n        output = \"\".join(self.__buffer)\n        if output:\n            self.__console.print(output)\n        del self.__buffer[:]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/filesize.py",
    "content": "# coding: utf-8\n\"\"\"Functions for reporting filesizes. Borrowed from https://github.com/PyFilesystem/pyfilesystem2\n\nThe functions declared in this module should cover the different\nusecases needed to generate a string representation of a file size\nusing several different units. Since there are many standards regarding\nfile size units, three different functions have been implemented.\n\nSee Also:\n    * `Wikipedia: Binary prefix <https://en.wikipedia.org/wiki/Binary_prefix>`_\n\n\"\"\"\n\n__all__ = [\"decimal\"]\n\nfrom typing import Iterable, List, Optional, Tuple\n\n\ndef _to_str(\n    size: int,\n    suffixes: Iterable[str],\n    base: int,\n    *,\n    precision: Optional[int] = 1,\n    separator: Optional[str] = \" \",\n) -> str:\n    if size == 1:\n        return \"1 byte\"\n    elif size < base:\n        return \"{:,} bytes\".format(size)\n\n    for i, suffix in enumerate(suffixes, 2):  # noqa: B007\n        unit = base**i\n        if size < unit:\n            break\n    return \"{:,.{precision}f}{separator}{}\".format(\n        (base * size / unit),\n        suffix,\n        precision=precision,\n        separator=separator,\n    )\n\n\ndef pick_unit_and_suffix(size: int, suffixes: List[str], base: int) -> Tuple[int, str]:\n    \"\"\"Pick a suffix and base for the given size.\"\"\"\n    for i, suffix in enumerate(suffixes):\n        unit = base**i\n        if size < unit * base:\n            break\n    return unit, suffix\n\n\ndef decimal(\n    size: int,\n    *,\n    precision: Optional[int] = 1,\n    separator: Optional[str] = \" \",\n) -> str:\n    \"\"\"Convert a filesize in to a string (powers of 1000, SI prefixes).\n\n    In this convention, ``1000 B = 1 kB``.\n\n    This is typically the format used to advertise the storage\n    capacity of USB flash drives and the like (*256 MB* meaning\n    actually a storage capacity of more than *256 000 000 B*),\n    or used by **Mac OS X** since v10.6 to report file sizes.\n\n    Arguments:\n        int (size): A file size.\n        int (precision): The number of decimal places to include (default = 1).\n        str (separator): The string to separate the value from the units (default = \" \").\n\n    Returns:\n        `str`: A string containing a abbreviated file size and units.\n\n    Example:\n        >>> filesize.decimal(30000)\n        '30.0 kB'\n        >>> filesize.decimal(30000, precision=2, separator=\"\")\n        '30.00kB'\n\n    \"\"\"\n    return _to_str(\n        size,\n        (\"kB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"),\n        1000,\n        precision=precision,\n        separator=separator,\n    )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/highlighter.py",
    "content": "import re\nfrom abc import ABC, abstractmethod\nfrom typing import List, Union\n\nfrom .text import Span, Text\n\n\ndef _combine_regex(*regexes: str) -> str:\n    \"\"\"Combine a number of regexes in to a single regex.\n\n    Returns:\n        str: New regex with all regexes ORed together.\n    \"\"\"\n    return \"|\".join(regexes)\n\n\nclass Highlighter(ABC):\n    \"\"\"Abstract base class for highlighters.\"\"\"\n\n    def __call__(self, text: Union[str, Text]) -> Text:\n        \"\"\"Highlight a str or Text instance.\n\n        Args:\n            text (Union[str, ~Text]): Text to highlight.\n\n        Raises:\n            TypeError: If not called with text or str.\n\n        Returns:\n            Text: A test instance with highlighting applied.\n        \"\"\"\n        if isinstance(text, str):\n            highlight_text = Text(text)\n        elif isinstance(text, Text):\n            highlight_text = text.copy()\n        else:\n            raise TypeError(f\"str or Text instance required, not {text!r}\")\n        self.highlight(highlight_text)\n        return highlight_text\n\n    @abstractmethod\n    def highlight(self, text: Text) -> None:\n        \"\"\"Apply highlighting in place to text.\n\n        Args:\n            text (~Text): A text object highlight.\n        \"\"\"\n\n\nclass NullHighlighter(Highlighter):\n    \"\"\"A highlighter object that doesn't highlight.\n\n    May be used to disable highlighting entirely.\n\n    \"\"\"\n\n    def highlight(self, text: Text) -> None:\n        \"\"\"Nothing to do\"\"\"\n\n\nclass RegexHighlighter(Highlighter):\n    \"\"\"Applies highlighting from a list of regular expressions.\"\"\"\n\n    highlights: List[str] = []\n    base_style: str = \"\"\n\n    def highlight(self, text: Text) -> None:\n        \"\"\"Highlight :class:`rich.text.Text` using regular expressions.\n\n        Args:\n            text (~Text): Text to highlighted.\n\n        \"\"\"\n\n        highlight_regex = text.highlight_regex\n        for re_highlight in self.highlights:\n            highlight_regex(re_highlight, style_prefix=self.base_style)\n\n\nclass ReprHighlighter(RegexHighlighter):\n    \"\"\"Highlights the text typically produced from ``__repr__`` methods.\"\"\"\n\n    base_style = \"repr.\"\n    highlights = [\n        r\"(?P<tag_start><)(?P<tag_name>[-\\w.:|]*)(?P<tag_contents>[\\w\\W]*?)(?P<tag_end>>)\",\n        r'(?P<attrib_name>[\\w_]{1,50})=(?P<attrib_value>\"?[\\w_]+\"?)?',\n        r\"(?P<brace>[][{}()])\",\n        _combine_regex(\n            r\"(?P<ipv4>[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})\",\n            r\"(?P<ipv6>([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4})\",\n            r\"(?P<eui64>(?:[0-9A-Fa-f]{1,2}-){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){7}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\\.){3}[0-9A-Fa-f]{4})\",\n            r\"(?P<eui48>(?:[0-9A-Fa-f]{1,2}-){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{1,2}:){5}[0-9A-Fa-f]{1,2}|(?:[0-9A-Fa-f]{4}\\.){2}[0-9A-Fa-f]{4})\",\n            r\"(?P<uuid>[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12})\",\n            r\"(?P<call>[\\w.]*?)\\(\",\n            r\"\\b(?P<bool_true>True)\\b|\\b(?P<bool_false>False)\\b|\\b(?P<none>None)\\b\",\n            r\"(?P<ellipsis>\\.\\.\\.)\",\n            r\"(?P<number_complex>(?<!\\w)(?:\\-?[0-9]+\\.?[0-9]*(?:e[-+]?\\d+?)?)(?:[-+](?:[0-9]+\\.?[0-9]*(?:e[-+]?\\d+)?))?j)\",\n            r\"(?P<number>(?<!\\w)\\-?[0-9]+\\.?[0-9]*(e[-+]?\\d+?)?\\b|0x[0-9a-fA-F]*)\",\n            r\"(?P<path>\\B(/[-\\w._+]+)*\\/)(?P<filename>[-\\w._+]*)?\",\n            r\"(?<![\\\\\\w])(?P<str>b?'''.*?(?<!\\\\)'''|b?'.*?(?<!\\\\)'|b?\\\"\\\"\\\".*?(?<!\\\\)\\\"\\\"\\\"|b?\\\".*?(?<!\\\\)\\\")\",\n            r\"(?P<url>(file|https|http|ws|wss)://[-0-9a-zA-Z$_+!`(),.?/;:&=%#]*)\",\n        ),\n    ]\n\n\nclass JSONHighlighter(RegexHighlighter):\n    \"\"\"Highlights JSON\"\"\"\n\n    # Captures the start and end of JSON strings, handling escaped quotes\n    JSON_STR = r\"(?<![\\\\\\w])(?P<str>b?\\\".*?(?<!\\\\)\\\")\"\n    JSON_WHITESPACE = {\" \", \"\\n\", \"\\r\", \"\\t\"}\n\n    base_style = \"json.\"\n    highlights = [\n        _combine_regex(\n            r\"(?P<brace>[\\{\\[\\(\\)\\]\\}])\",\n            r\"\\b(?P<bool_true>true)\\b|\\b(?P<bool_false>false)\\b|\\b(?P<null>null)\\b\",\n            r\"(?P<number>(?<!\\w)\\-?[0-9]+\\.?[0-9]*(e[\\-\\+]?\\d+?)?\\b|0x[0-9a-fA-F]*)\",\n            JSON_STR,\n        ),\n    ]\n\n    def highlight(self, text: Text) -> None:\n        super().highlight(text)\n\n        # Additional work to handle highlighting JSON keys\n        plain = text.plain\n        append = text.spans.append\n        whitespace = self.JSON_WHITESPACE\n        for match in re.finditer(self.JSON_STR, plain):\n            start, end = match.span()\n            cursor = end\n            while cursor < len(plain):\n                char = plain[cursor]\n                cursor += 1\n                if char == \":\":\n                    append(Span(start, end, \"json.key\"))\n                elif char in whitespace:\n                    continue\n                break\n\n\nclass ISO8601Highlighter(RegexHighlighter):\n    \"\"\"Highlights the ISO8601 date time strings.\n    Regex reference: https://www.oreilly.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html\n    \"\"\"\n\n    base_style = \"iso8601.\"\n    highlights = [\n        #\n        # Dates\n        #\n        # Calendar month (e.g. 2008-08). The hyphen is required\n        r\"^(?P<year>[0-9]{4})-(?P<month>1[0-2]|0[1-9])$\",\n        # Calendar date w/o hyphens (e.g. 20080830)\n        r\"^(?P<date>(?P<year>[0-9]{4})(?P<month>1[0-2]|0[1-9])(?P<day>3[01]|0[1-9]|[12][0-9]))$\",\n        # Ordinal date (e.g. 2008-243). The hyphen is optional\n        r\"^(?P<date>(?P<year>[0-9]{4})-?(?P<day>36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0[1-9][0-9]|00[1-9]))$\",\n        #\n        # Weeks\n        #\n        # Week of the year (e.g., 2008-W35). The hyphen is optional\n        r\"^(?P<date>(?P<year>[0-9]{4})-?W(?P<week>5[0-3]|[1-4][0-9]|0[1-9]))$\",\n        # Week date (e.g., 2008-W35-6). The hyphens are optional\n        r\"^(?P<date>(?P<year>[0-9]{4})-?W(?P<week>5[0-3]|[1-4][0-9]|0[1-9])-?(?P<day>[1-7]))$\",\n        #\n        # Times\n        #\n        # Hours and minutes (e.g., 17:21). The colon is optional\n        r\"^(?P<time>(?P<hour>2[0-3]|[01][0-9]):?(?P<minute>[0-5][0-9]))$\",\n        # Hours, minutes, and seconds w/o colons (e.g., 172159)\n        r\"^(?P<time>(?P<hour>2[0-3]|[01][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-5][0-9]))$\",\n        # Time zone designator (e.g., Z, +07 or +07:00). The colons and the minutes are optional\n        r\"^(?P<timezone>(Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?))$\",\n        # Hours, minutes, and seconds with time zone designator (e.g., 17:21:59+07:00).\n        # All the colons are optional. The minutes in the time zone designator are also optional\n        r\"^(?P<time>(?P<hour>2[0-3]|[01][0-9])(?P<minute>[0-5][0-9])(?P<second>[0-5][0-9]))(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9])(?::?(?:[0-5][0-9]))?)$\",\n        #\n        # Date and Time\n        #\n        # Calendar date with hours, minutes, and seconds (e.g., 2008-08-30 17:21:59 or 20080830 172159).\n        # A space is required between the date and the time. The hyphens and colons are optional.\n        # This regex matches dates and times that specify some hyphens or colons but omit others.\n        # This does not follow ISO 8601\n        r\"^(?P<date>(?P<year>[0-9]{4})(?P<hyphen>-)?(?P<month>1[0-2]|0[1-9])(?(hyphen)-)(?P<day>3[01]|0[1-9]|[12][0-9])) (?P<time>(?P<hour>2[0-3]|[01][0-9])(?(hyphen):)(?P<minute>[0-5][0-9])(?(hyphen):)(?P<second>[0-5][0-9]))$\",\n        #\n        # XML Schema dates and times\n        #\n        # Date, with optional time zone (e.g., 2008-08-30 or 2008-08-30+07:00).\n        # Hyphens are required. This is the XML Schema 'date' type\n        r\"^(?P<date>(?P<year>-?(?:[1-9][0-9]*)?[0-9]{4})-(?P<month>1[0-2]|0[1-9])-(?P<day>3[01]|0[1-9]|[12][0-9]))(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$\",\n        # Time, with optional fractional seconds and time zone (e.g., 01:45:36 or 01:45:36.123+07:00).\n        # There is no limit on the number of digits for the fractional seconds. This is the XML Schema 'time' type\n        r\"^(?P<time>(?P<hour>2[0-3]|[01][0-9]):(?P<minute>[0-5][0-9]):(?P<second>[0-5][0-9])(?P<frac>\\.[0-9]+)?)(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$\",\n        # Date and time, with optional fractional seconds and time zone (e.g., 2008-08-30T01:45:36 or 2008-08-30T01:45:36.123Z).\n        # This is the XML Schema 'dateTime' type\n        r\"^(?P<date>(?P<year>-?(?:[1-9][0-9]*)?[0-9]{4})-(?P<month>1[0-2]|0[1-9])-(?P<day>3[01]|0[1-9]|[12][0-9]))T(?P<time>(?P<hour>2[0-3]|[01][0-9]):(?P<minute>[0-5][0-9]):(?P<second>[0-5][0-9])(?P<ms>\\.[0-9]+)?)(?P<timezone>Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$\",\n    ]\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from .console import Console\n\n    console = Console()\n    console.print(\"[bold green]hello world![/bold green]\")\n    console.print(\"'[bold green]hello world![/bold green]'\")\n\n    console.print(\" /foo\")\n    console.print(\"/foo/\")\n    console.print(\"/foo/bar\")\n    console.print(\"foo/bar/baz\")\n\n    console.print(\"/foo/bar/baz?foo=bar+egg&egg=baz\")\n    console.print(\"/foo/bar/baz/\")\n    console.print(\"/foo/bar/baz/egg\")\n    console.print(\"/foo/bar/baz/egg.py\")\n    console.print(\"/foo/bar/baz/egg.py word\")\n    console.print(\" /foo/bar/baz/egg.py word\")\n    console.print(\"foo /foo/bar/baz/egg.py word\")\n    console.print(\"foo /foo/bar/ba._++z/egg+.py word\")\n    console.print(\"https://example.org?foo=bar#header\")\n\n    console.print(1234567.34)\n    console.print(1 / 2)\n    console.print(-1 / 123123123123)\n\n    console.print(\n        \"127.0.1.1 bar 192.168.1.4 2001:0db8:85a3:0000:0000:8a2e:0370:7334 foo\"\n    )\n    import json\n\n    console.print_json(json.dumps(obj={\"name\": \"apple\", \"count\": 1}), indent=None)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/json.py",
    "content": "from json import loads, dumps\nfrom typing import Any, Callable, Optional, Union\n\nfrom .text import Text\nfrom .highlighter import JSONHighlighter, NullHighlighter\n\n\nclass JSON:\n    \"\"\"A renderable which pretty prints JSON.\n\n    Args:\n        json (str): JSON encoded data.\n        indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.\n        highlight (bool, optional): Enable highlighting. Defaults to True.\n        skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.\n        ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.\n        check_circular (bool, optional): Check for circular references. Defaults to True.\n        allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.\n        default (Callable, optional): A callable that converts values that can not be encoded\n            in to something that can be JSON encoded. Defaults to None.\n        sort_keys (bool, optional): Sort dictionary keys. Defaults to False.\n    \"\"\"\n\n    def __init__(\n        self,\n        json: str,\n        indent: Union[None, int, str] = 2,\n        highlight: bool = True,\n        skip_keys: bool = False,\n        ensure_ascii: bool = True,\n        check_circular: bool = True,\n        allow_nan: bool = True,\n        default: Optional[Callable[[Any], Any]] = None,\n        sort_keys: bool = False,\n    ) -> None:\n        data = loads(json)\n        json = dumps(\n            data,\n            indent=indent,\n            skipkeys=skip_keys,\n            ensure_ascii=ensure_ascii,\n            check_circular=check_circular,\n            allow_nan=allow_nan,\n            default=default,\n            sort_keys=sort_keys,\n        )\n        highlighter = JSONHighlighter() if highlight else NullHighlighter()\n        self.text = highlighter(json)\n        self.text.no_wrap = True\n        self.text.overflow = None\n\n    @classmethod\n    def from_data(\n        cls,\n        data: Any,\n        indent: Union[None, int, str] = 2,\n        highlight: bool = True,\n        skip_keys: bool = False,\n        ensure_ascii: bool = True,\n        check_circular: bool = True,\n        allow_nan: bool = True,\n        default: Optional[Callable[[Any], Any]] = None,\n        sort_keys: bool = False,\n    ) -> \"JSON\":\n        \"\"\"Encodes a JSON object from arbitrary data.\n\n        Args:\n            data (Any): An object that may be encoded in to JSON\n            indent (Union[None, int, str], optional): Number of characters to indent by. Defaults to 2.\n            highlight (bool, optional): Enable highlighting. Defaults to True.\n            default (Callable, optional): Optional callable which will be called for objects that cannot be serialized. Defaults to None.\n            skip_keys (bool, optional): Skip keys not of a basic type. Defaults to False.\n            ensure_ascii (bool, optional): Escape all non-ascii characters. Defaults to False.\n            check_circular (bool, optional): Check for circular references. Defaults to True.\n            allow_nan (bool, optional): Allow NaN and Infinity values. Defaults to True.\n            default (Callable, optional): A callable that converts values that can not be encoded\n                in to something that can be JSON encoded. Defaults to None.\n            sort_keys (bool, optional): Sort dictionary keys. Defaults to False.\n\n        Returns:\n            JSON: New JSON object from the given data.\n        \"\"\"\n        json_instance: \"JSON\" = cls.__new__(cls)\n        json = dumps(\n            data,\n            indent=indent,\n            skipkeys=skip_keys,\n            ensure_ascii=ensure_ascii,\n            check_circular=check_circular,\n            allow_nan=allow_nan,\n            default=default,\n            sort_keys=sort_keys,\n        )\n        highlighter = JSONHighlighter() if highlight else NullHighlighter()\n        json_instance.text = highlighter(json)\n        json_instance.text.no_wrap = True\n        json_instance.text.overflow = None\n        return json_instance\n\n    def __rich__(self) -> Text:\n        return self.text\n\n\nif __name__ == \"__main__\":\n\n    import argparse\n    import sys\n\n    parser = argparse.ArgumentParser(description=\"Pretty print json\")\n    parser.add_argument(\n        \"path\",\n        metavar=\"PATH\",\n        help=\"path to file, or - for stdin\",\n    )\n    parser.add_argument(\n        \"-i\",\n        \"--indent\",\n        metavar=\"SPACES\",\n        type=int,\n        help=\"Number of spaces in an indent\",\n        default=2,\n    )\n    args = parser.parse_args()\n\n    from pip._vendor.rich.console import Console\n\n    console = Console()\n    error_console = Console(stderr=True)\n\n    try:\n        if args.path == \"-\":\n            json_data = sys.stdin.read()\n        else:\n            with open(args.path, \"rt\") as json_file:\n                json_data = json_file.read()\n    except Exception as error:\n        error_console.print(f\"Unable to read {args.path!r}; {error}\")\n        sys.exit(-1)\n\n    console.print(JSON(json_data, indent=args.indent), soft_wrap=True)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/jupyter.py",
    "content": "from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Sequence\n\nif TYPE_CHECKING:\n    from pip._vendor.rich.console import ConsoleRenderable\n\nfrom . import get_console\nfrom .segment import Segment\nfrom .terminal_theme import DEFAULT_TERMINAL_THEME\n\nif TYPE_CHECKING:\n    from pip._vendor.rich.console import ConsoleRenderable\n\nJUPYTER_HTML_FORMAT = \"\"\"\\\n<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">{code}</pre>\n\"\"\"\n\n\nclass JupyterRenderable:\n    \"\"\"A shim to write html to Jupyter notebook.\"\"\"\n\n    def __init__(self, html: str, text: str) -> None:\n        self.html = html\n        self.text = text\n\n    def _repr_mimebundle_(\n        self, include: Sequence[str], exclude: Sequence[str], **kwargs: Any\n    ) -> Dict[str, str]:\n        data = {\"text/plain\": self.text, \"text/html\": self.html}\n        if include:\n            data = {k: v for (k, v) in data.items() if k in include}\n        if exclude:\n            data = {k: v for (k, v) in data.items() if k not in exclude}\n        return data\n\n\nclass JupyterMixin:\n    \"\"\"Add to an Rich renderable to make it render in Jupyter notebook.\"\"\"\n\n    __slots__ = ()\n\n    def _repr_mimebundle_(\n        self: \"ConsoleRenderable\",\n        include: Sequence[str],\n        exclude: Sequence[str],\n        **kwargs: Any,\n    ) -> Dict[str, str]:\n        console = get_console()\n        segments = list(console.render(self, console.options))\n        html = _render_segments(segments)\n        text = console._render_buffer(segments)\n        data = {\"text/plain\": text, \"text/html\": html}\n        if include:\n            data = {k: v for (k, v) in data.items() if k in include}\n        if exclude:\n            data = {k: v for (k, v) in data.items() if k not in exclude}\n        return data\n\n\ndef _render_segments(segments: Iterable[Segment]) -> str:\n    def escape(text: str) -> str:\n        \"\"\"Escape html.\"\"\"\n        return text.replace(\"&\", \"&amp;\").replace(\"<\", \"&lt;\").replace(\">\", \"&gt;\")\n\n    fragments: List[str] = []\n    append_fragment = fragments.append\n    theme = DEFAULT_TERMINAL_THEME\n    for text, style, control in Segment.simplify(segments):\n        if control:\n            continue\n        text = escape(text)\n        if style:\n            rule = style.get_html_style(theme)\n            text = f'<span style=\"{rule}\">{text}</span>' if rule else text\n            if style.link:\n                text = f'<a href=\"{style.link}\" target=\"_blank\">{text}</a>'\n        append_fragment(text)\n\n    code = \"\".join(fragments)\n    html = JUPYTER_HTML_FORMAT.format(code=code)\n\n    return html\n\n\ndef display(segments: Iterable[Segment], text: str) -> None:\n    \"\"\"Render segments to Jupyter.\"\"\"\n    html = _render_segments(segments)\n    jupyter_renderable = JupyterRenderable(html, text)\n    try:\n        from IPython.display import display as ipython_display\n\n        ipython_display(jupyter_renderable)\n    except ModuleNotFoundError:\n        # Handle the case where the Console has force_jupyter=True,\n        # but IPython is not installed.\n        pass\n\n\ndef print(*args: Any, **kwargs: Any) -> None:\n    \"\"\"Proxy for Console print.\"\"\"\n    console = get_console()\n    return console.print(*args, **kwargs)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/layout.py",
    "content": "from abc import ABC, abstractmethod\nfrom itertools import islice\nfrom operator import itemgetter\nfrom threading import RLock\nfrom typing import (\n    TYPE_CHECKING,\n    Dict,\n    Iterable,\n    List,\n    NamedTuple,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n)\n\nfrom ._ratio import ratio_resolve\nfrom .align import Align\nfrom .console import Console, ConsoleOptions, RenderableType, RenderResult\nfrom .highlighter import ReprHighlighter\nfrom .panel import Panel\nfrom .pretty import Pretty\nfrom .repr import rich_repr, Result\nfrom .region import Region\nfrom .segment import Segment\nfrom .style import StyleType\n\nif TYPE_CHECKING:\n    from pip._vendor.rich.tree import Tree\n\n\nclass LayoutRender(NamedTuple):\n    \"\"\"An individual layout render.\"\"\"\n\n    region: Region\n    render: List[List[Segment]]\n\n\nRegionMap = Dict[\"Layout\", Region]\nRenderMap = Dict[\"Layout\", LayoutRender]\n\n\nclass LayoutError(Exception):\n    \"\"\"Layout related error.\"\"\"\n\n\nclass NoSplitter(LayoutError):\n    \"\"\"Requested splitter does not exist.\"\"\"\n\n\nclass _Placeholder:\n    \"\"\"An internal renderable used as a Layout placeholder.\"\"\"\n\n    highlighter = ReprHighlighter()\n\n    def __init__(self, layout: \"Layout\", style: StyleType = \"\") -> None:\n        self.layout = layout\n        self.style = style\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        width = options.max_width\n        height = options.height or options.size.height\n        layout = self.layout\n        title = (\n            f\"{layout.name!r} ({width} x {height})\"\n            if layout.name\n            else f\"({width} x {height})\"\n        )\n        yield Panel(\n            Align.center(Pretty(layout), vertical=\"middle\"),\n            style=self.style,\n            title=self.highlighter(title),\n            border_style=\"blue\",\n            height=height,\n        )\n\n\nclass Splitter(ABC):\n    \"\"\"Base class for a splitter.\"\"\"\n\n    name: str = \"\"\n\n    @abstractmethod\n    def get_tree_icon(self) -> str:\n        \"\"\"Get the icon (emoji) used in layout.tree\"\"\"\n\n    @abstractmethod\n    def divide(\n        self, children: Sequence[\"Layout\"], region: Region\n    ) -> Iterable[Tuple[\"Layout\", Region]]:\n        \"\"\"Divide a region amongst several child layouts.\n\n        Args:\n            children (Sequence(Layout)): A number of child layouts.\n            region (Region): A rectangular region to divide.\n        \"\"\"\n\n\nclass RowSplitter(Splitter):\n    \"\"\"Split a layout region in to rows.\"\"\"\n\n    name = \"row\"\n\n    def get_tree_icon(self) -> str:\n        return \"[layout.tree.row]⬌\"\n\n    def divide(\n        self, children: Sequence[\"Layout\"], region: Region\n    ) -> Iterable[Tuple[\"Layout\", Region]]:\n        x, y, width, height = region\n        render_widths = ratio_resolve(width, children)\n        offset = 0\n        _Region = Region\n        for child, child_width in zip(children, render_widths):\n            yield child, _Region(x + offset, y, child_width, height)\n            offset += child_width\n\n\nclass ColumnSplitter(Splitter):\n    \"\"\"Split a layout region in to columns.\"\"\"\n\n    name = \"column\"\n\n    def get_tree_icon(self) -> str:\n        return \"[layout.tree.column]⬍\"\n\n    def divide(\n        self, children: Sequence[\"Layout\"], region: Region\n    ) -> Iterable[Tuple[\"Layout\", Region]]:\n        x, y, width, height = region\n        render_heights = ratio_resolve(height, children)\n        offset = 0\n        _Region = Region\n        for child, child_height in zip(children, render_heights):\n            yield child, _Region(x, y + offset, width, child_height)\n            offset += child_height\n\n\n@rich_repr\nclass Layout:\n    \"\"\"A renderable to divide a fixed height in to rows or columns.\n\n    Args:\n        renderable (RenderableType, optional): Renderable content, or None for placeholder. Defaults to None.\n        name (str, optional): Optional identifier for Layout. Defaults to None.\n        size (int, optional): Optional fixed size of layout. Defaults to None.\n        minimum_size (int, optional): Minimum size of layout. Defaults to 1.\n        ratio (int, optional): Optional ratio for flexible layout. Defaults to 1.\n        visible (bool, optional): Visibility of layout. Defaults to True.\n    \"\"\"\n\n    splitters = {\"row\": RowSplitter, \"column\": ColumnSplitter}\n\n    def __init__(\n        self,\n        renderable: Optional[RenderableType] = None,\n        *,\n        name: Optional[str] = None,\n        size: Optional[int] = None,\n        minimum_size: int = 1,\n        ratio: int = 1,\n        visible: bool = True,\n        height: Optional[int] = None,\n    ) -> None:\n        self._renderable = renderable or _Placeholder(self)\n        self.size = size\n        self.minimum_size = minimum_size\n        self.ratio = ratio\n        self.name = name\n        self.visible = visible\n        self.height = height\n        self.splitter: Splitter = self.splitters[\"column\"]()\n        self._children: List[Layout] = []\n        self._render_map: RenderMap = {}\n        self._lock = RLock()\n\n    def __rich_repr__(self) -> Result:\n        yield \"name\", self.name, None\n        yield \"size\", self.size, None\n        yield \"minimum_size\", self.minimum_size, 1\n        yield \"ratio\", self.ratio, 1\n\n    @property\n    def renderable(self) -> RenderableType:\n        \"\"\"Layout renderable.\"\"\"\n        return self if self._children else self._renderable\n\n    @property\n    def children(self) -> List[\"Layout\"]:\n        \"\"\"Gets (visible) layout children.\"\"\"\n        return [child for child in self._children if child.visible]\n\n    @property\n    def map(self) -> RenderMap:\n        \"\"\"Get a map of the last render.\"\"\"\n        return self._render_map\n\n    def get(self, name: str) -> Optional[\"Layout\"]:\n        \"\"\"Get a named layout, or None if it doesn't exist.\n\n        Args:\n            name (str): Name of layout.\n\n        Returns:\n            Optional[Layout]: Layout instance or None if no layout was found.\n        \"\"\"\n        if self.name == name:\n            return self\n        else:\n            for child in self._children:\n                named_layout = child.get(name)\n                if named_layout is not None:\n                    return named_layout\n        return None\n\n    def __getitem__(self, name: str) -> \"Layout\":\n        layout = self.get(name)\n        if layout is None:\n            raise KeyError(f\"No layout with name {name!r}\")\n        return layout\n\n    @property\n    def tree(self) -> \"Tree\":\n        \"\"\"Get a tree renderable to show layout structure.\"\"\"\n        from pip._vendor.rich.styled import Styled\n        from pip._vendor.rich.table import Table\n        from pip._vendor.rich.tree import Tree\n\n        def summary(layout: \"Layout\") -> Table:\n\n            icon = layout.splitter.get_tree_icon()\n\n            table = Table.grid(padding=(0, 1, 0, 0))\n\n            text: RenderableType = (\n                Pretty(layout) if layout.visible else Styled(Pretty(layout), \"dim\")\n            )\n            table.add_row(icon, text)\n            _summary = table\n            return _summary\n\n        layout = self\n        tree = Tree(\n            summary(layout),\n            guide_style=f\"layout.tree.{layout.splitter.name}\",\n            highlight=True,\n        )\n\n        def recurse(tree: \"Tree\", layout: \"Layout\") -> None:\n            for child in layout._children:\n                recurse(\n                    tree.add(\n                        summary(child),\n                        guide_style=f\"layout.tree.{child.splitter.name}\",\n                    ),\n                    child,\n                )\n\n        recurse(tree, self)\n        return tree\n\n    def split(\n        self,\n        *layouts: Union[\"Layout\", RenderableType],\n        splitter: Union[Splitter, str] = \"column\",\n    ) -> None:\n        \"\"\"Split the layout in to multiple sub-layouts.\n\n        Args:\n            *layouts (Layout): Positional arguments should be (sub) Layout instances.\n            splitter (Union[Splitter, str]): Splitter instance or name of splitter.\n        \"\"\"\n        _layouts = [\n            layout if isinstance(layout, Layout) else Layout(layout)\n            for layout in layouts\n        ]\n        try:\n            self.splitter = (\n                splitter\n                if isinstance(splitter, Splitter)\n                else self.splitters[splitter]()\n            )\n        except KeyError:\n            raise NoSplitter(f\"No splitter called {splitter!r}\")\n        self._children[:] = _layouts\n\n    def add_split(self, *layouts: Union[\"Layout\", RenderableType]) -> None:\n        \"\"\"Add a new layout(s) to existing split.\n\n        Args:\n            *layouts (Union[Layout, RenderableType]): Positional arguments should be renderables or (sub) Layout instances.\n\n        \"\"\"\n        _layouts = (\n            layout if isinstance(layout, Layout) else Layout(layout)\n            for layout in layouts\n        )\n        self._children.extend(_layouts)\n\n    def split_row(self, *layouts: Union[\"Layout\", RenderableType]) -> None:\n        \"\"\"Split the layout in to a row (layouts side by side).\n\n        Args:\n            *layouts (Layout): Positional arguments should be (sub) Layout instances.\n        \"\"\"\n        self.split(*layouts, splitter=\"row\")\n\n    def split_column(self, *layouts: Union[\"Layout\", RenderableType]) -> None:\n        \"\"\"Split the layout in to a column (layouts stacked on top of each other).\n\n        Args:\n            *layouts (Layout): Positional arguments should be (sub) Layout instances.\n        \"\"\"\n        self.split(*layouts, splitter=\"column\")\n\n    def unsplit(self) -> None:\n        \"\"\"Reset splits to initial state.\"\"\"\n        del self._children[:]\n\n    def update(self, renderable: RenderableType) -> None:\n        \"\"\"Update renderable.\n\n        Args:\n            renderable (RenderableType): New renderable object.\n        \"\"\"\n        with self._lock:\n            self._renderable = renderable\n\n    def refresh_screen(self, console: \"Console\", layout_name: str) -> None:\n        \"\"\"Refresh a sub-layout.\n\n        Args:\n            console (Console): Console instance where Layout is to be rendered.\n            layout_name (str): Name of layout.\n        \"\"\"\n        with self._lock:\n            layout = self[layout_name]\n            region, _lines = self._render_map[layout]\n            (x, y, width, height) = region\n            lines = console.render_lines(\n                layout, console.options.update_dimensions(width, height)\n            )\n            self._render_map[layout] = LayoutRender(region, lines)\n            console.update_screen_lines(lines, x, y)\n\n    def _make_region_map(self, width: int, height: int) -> RegionMap:\n        \"\"\"Create a dict that maps layout on to Region.\"\"\"\n        stack: List[Tuple[Layout, Region]] = [(self, Region(0, 0, width, height))]\n        push = stack.append\n        pop = stack.pop\n        layout_regions: List[Tuple[Layout, Region]] = []\n        append_layout_region = layout_regions.append\n        while stack:\n            append_layout_region(pop())\n            layout, region = layout_regions[-1]\n            children = layout.children\n            if children:\n                for child_and_region in layout.splitter.divide(children, region):\n                    push(child_and_region)\n\n        region_map = {\n            layout: region\n            for layout, region in sorted(layout_regions, key=itemgetter(1))\n        }\n        return region_map\n\n    def render(self, console: Console, options: ConsoleOptions) -> RenderMap:\n        \"\"\"Render the sub_layouts.\n\n        Args:\n            console (Console): Console instance.\n            options (ConsoleOptions): Console options.\n\n        Returns:\n            RenderMap: A dict that maps Layout on to a tuple of Region, lines\n        \"\"\"\n        render_width = options.max_width\n        render_height = options.height or console.height\n        region_map = self._make_region_map(render_width, render_height)\n        layout_regions = [\n            (layout, region)\n            for layout, region in region_map.items()\n            if not layout.children\n        ]\n        render_map: Dict[\"Layout\", \"LayoutRender\"] = {}\n        render_lines = console.render_lines\n        update_dimensions = options.update_dimensions\n\n        for layout, region in layout_regions:\n            lines = render_lines(\n                layout.renderable, update_dimensions(region.width, region.height)\n            )\n            render_map[layout] = LayoutRender(region, lines)\n        return render_map\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        with self._lock:\n            width = options.max_width or console.width\n            height = options.height or console.height\n            render_map = self.render(console, options.update_dimensions(width, height))\n            self._render_map = render_map\n            layout_lines: List[List[Segment]] = [[] for _ in range(height)]\n            _islice = islice\n            for (region, lines) in render_map.values():\n                _x, y, _layout_width, layout_height = region\n                for row, line in zip(\n                    _islice(layout_lines, y, y + layout_height), lines\n                ):\n                    row.extend(line)\n\n            new_line = Segment.line()\n            for layout_row in layout_lines:\n                yield from layout_row\n                yield new_line\n\n\nif __name__ == \"__main__\":\n    from pip._vendor.rich.console import Console\n\n    console = Console()\n    layout = Layout()\n\n    layout.split_column(\n        Layout(name=\"header\", size=3),\n        Layout(ratio=1, name=\"main\"),\n        Layout(size=10, name=\"footer\"),\n    )\n\n    layout[\"main\"].split_row(Layout(name=\"side\"), Layout(name=\"body\", ratio=2))\n\n    layout[\"body\"].split_row(Layout(name=\"content\", ratio=2), Layout(name=\"s2\"))\n\n    layout[\"s2\"].split_column(\n        Layout(name=\"top\"), Layout(name=\"middle\"), Layout(name=\"bottom\")\n    )\n\n    layout[\"side\"].split_column(Layout(layout.tree, name=\"left1\"), Layout(name=\"left2\"))\n\n    layout[\"content\"].update(\"foo\")\n\n    console.print(layout)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/live.py",
    "content": "import sys\nfrom threading import Event, RLock, Thread\nfrom types import TracebackType\nfrom typing import IO, Any, Callable, List, Optional, TextIO, Type, cast\n\nfrom . import get_console\nfrom .console import Console, ConsoleRenderable, RenderableType, RenderHook\nfrom .control import Control\nfrom .file_proxy import FileProxy\nfrom .jupyter import JupyterMixin\nfrom .live_render import LiveRender, VerticalOverflowMethod\nfrom .screen import Screen\nfrom .text import Text\n\n\nclass _RefreshThread(Thread):\n    \"\"\"A thread that calls refresh() at regular intervals.\"\"\"\n\n    def __init__(self, live: \"Live\", refresh_per_second: float) -> None:\n        self.live = live\n        self.refresh_per_second = refresh_per_second\n        self.done = Event()\n        super().__init__(daemon=True)\n\n    def stop(self) -> None:\n        self.done.set()\n\n    def run(self) -> None:\n        while not self.done.wait(1 / self.refresh_per_second):\n            with self.live._lock:\n                if not self.done.is_set():\n                    self.live.refresh()\n\n\nclass Live(JupyterMixin, RenderHook):\n    \"\"\"Renders an auto-updating live display of any given renderable.\n\n    Args:\n        renderable (RenderableType, optional): The renderable to live display. Defaults to displaying nothing.\n        console (Console, optional): Optional Console instance. Default will an internal Console instance writing to stdout.\n        screen (bool, optional): Enable alternate screen mode. Defaults to False.\n        auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()` or `update()` with refresh flag. Defaults to True\n        refresh_per_second (float, optional): Number of times per second to refresh the live display. Defaults to 4.\n        transient (bool, optional): Clear the renderable on exit (has no effect when screen=True). Defaults to False.\n        redirect_stdout (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True.\n        redirect_stderr (bool, optional): Enable redirection of stderr. Defaults to True.\n        vertical_overflow (VerticalOverflowMethod, optional): How to handle renderable when it is too tall for the console. Defaults to \"ellipsis\".\n        get_renderable (Callable[[], RenderableType], optional): Optional callable to get renderable. Defaults to None.\n    \"\"\"\n\n    def __init__(\n        self,\n        renderable: Optional[RenderableType] = None,\n        *,\n        console: Optional[Console] = None,\n        screen: bool = False,\n        auto_refresh: bool = True,\n        refresh_per_second: float = 4,\n        transient: bool = False,\n        redirect_stdout: bool = True,\n        redirect_stderr: bool = True,\n        vertical_overflow: VerticalOverflowMethod = \"ellipsis\",\n        get_renderable: Optional[Callable[[], RenderableType]] = None,\n    ) -> None:\n        assert refresh_per_second > 0, \"refresh_per_second must be > 0\"\n        self._renderable = renderable\n        self.console = console if console is not None else get_console()\n        self._screen = screen\n        self._alt_screen = False\n\n        self._redirect_stdout = redirect_stdout\n        self._redirect_stderr = redirect_stderr\n        self._restore_stdout: Optional[IO[str]] = None\n        self._restore_stderr: Optional[IO[str]] = None\n\n        self._lock = RLock()\n        self.ipy_widget: Optional[Any] = None\n        self.auto_refresh = auto_refresh\n        self._started: bool = False\n        self.transient = True if screen else transient\n\n        self._refresh_thread: Optional[_RefreshThread] = None\n        self.refresh_per_second = refresh_per_second\n\n        self.vertical_overflow = vertical_overflow\n        self._get_renderable = get_renderable\n        self._live_render = LiveRender(\n            self.get_renderable(), vertical_overflow=vertical_overflow\n        )\n\n    @property\n    def is_started(self) -> bool:\n        \"\"\"Check if live display has been started.\"\"\"\n        return self._started\n\n    def get_renderable(self) -> RenderableType:\n        renderable = (\n            self._get_renderable()\n            if self._get_renderable is not None\n            else self._renderable\n        )\n        return renderable or \"\"\n\n    def start(self, refresh: bool = False) -> None:\n        \"\"\"Start live rendering display.\n\n        Args:\n            refresh (bool, optional): Also refresh. Defaults to False.\n        \"\"\"\n        with self._lock:\n            if self._started:\n                return\n            self.console.set_live(self)\n            self._started = True\n            if self._screen:\n                self._alt_screen = self.console.set_alt_screen(True)\n            self.console.show_cursor(False)\n            self._enable_redirect_io()\n            self.console.push_render_hook(self)\n            if refresh:\n                try:\n                    self.refresh()\n                except Exception:\n                    # If refresh fails, we want to stop the redirection of sys.stderr,\n                    # so the error stacktrace is properly displayed in the terminal.\n                    # (or, if the code that calls Rich captures the exception and wants to display something,\n                    # let this be displayed in the terminal).\n                    self.stop()\n                    raise\n            if self.auto_refresh:\n                self._refresh_thread = _RefreshThread(self, self.refresh_per_second)\n                self._refresh_thread.start()\n\n    def stop(self) -> None:\n        \"\"\"Stop live rendering display.\"\"\"\n        with self._lock:\n            if not self._started:\n                return\n            self.console.clear_live()\n            self._started = False\n\n            if self.auto_refresh and self._refresh_thread is not None:\n                self._refresh_thread.stop()\n                self._refresh_thread = None\n            # allow it to fully render on the last even if overflow\n            self.vertical_overflow = \"visible\"\n            with self.console:\n                try:\n                    if not self._alt_screen and not self.console.is_jupyter:\n                        self.refresh()\n                finally:\n                    self._disable_redirect_io()\n                    self.console.pop_render_hook()\n                    if not self._alt_screen and self.console.is_terminal:\n                        self.console.line()\n                    self.console.show_cursor(True)\n                    if self._alt_screen:\n                        self.console.set_alt_screen(False)\n\n                    if self.transient and not self._alt_screen:\n                        self.console.control(self._live_render.restore_cursor())\n                    if self.ipy_widget is not None and self.transient:\n                        self.ipy_widget.close()  # pragma: no cover\n\n    def __enter__(self) -> \"Live\":\n        self.start(refresh=self._renderable is not None)\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.stop()\n\n    def _enable_redirect_io(self) -> None:\n        \"\"\"Enable redirecting of stdout / stderr.\"\"\"\n        if self.console.is_terminal or self.console.is_jupyter:\n            if self._redirect_stdout and not isinstance(sys.stdout, FileProxy):\n                self._restore_stdout = sys.stdout\n                sys.stdout = cast(\"TextIO\", FileProxy(self.console, sys.stdout))\n            if self._redirect_stderr and not isinstance(sys.stderr, FileProxy):\n                self._restore_stderr = sys.stderr\n                sys.stderr = cast(\"TextIO\", FileProxy(self.console, sys.stderr))\n\n    def _disable_redirect_io(self) -> None:\n        \"\"\"Disable redirecting of stdout / stderr.\"\"\"\n        if self._restore_stdout:\n            sys.stdout = cast(\"TextIO\", self._restore_stdout)\n            self._restore_stdout = None\n        if self._restore_stderr:\n            sys.stderr = cast(\"TextIO\", self._restore_stderr)\n            self._restore_stderr = None\n\n    @property\n    def renderable(self) -> RenderableType:\n        \"\"\"Get the renderable that is being displayed\n\n        Returns:\n            RenderableType: Displayed renderable.\n        \"\"\"\n        renderable = self.get_renderable()\n        return Screen(renderable) if self._alt_screen else renderable\n\n    def update(self, renderable: RenderableType, *, refresh: bool = False) -> None:\n        \"\"\"Update the renderable that is being displayed\n\n        Args:\n            renderable (RenderableType): New renderable to use.\n            refresh (bool, optional): Refresh the display. Defaults to False.\n        \"\"\"\n        with self._lock:\n            self._renderable = renderable\n            if refresh:\n                self.refresh()\n\n    def refresh(self) -> None:\n        \"\"\"Update the display of the Live Render.\"\"\"\n        with self._lock:\n            self._live_render.set_renderable(self.renderable)\n            if self.console.is_jupyter:  # pragma: no cover\n                try:\n                    from IPython.display import display\n                    from ipywidgets import Output\n                except ImportError:\n                    import warnings\n\n                    warnings.warn('install \"ipywidgets\" for Jupyter support')\n                else:\n                    if self.ipy_widget is None:\n                        self.ipy_widget = Output()\n                        display(self.ipy_widget)\n\n                    with self.ipy_widget:\n                        self.ipy_widget.clear_output(wait=True)\n                        self.console.print(self._live_render.renderable)\n            elif self.console.is_terminal and not self.console.is_dumb_terminal:\n                with self.console:\n                    self.console.print(Control())\n            elif (\n                not self._started and not self.transient\n            ):  # if it is finished allow files or dumb-terminals to see final result\n                with self.console:\n                    self.console.print(Control())\n\n    def process_renderables(\n        self, renderables: List[ConsoleRenderable]\n    ) -> List[ConsoleRenderable]:\n        \"\"\"Process renderables to restore cursor and display progress.\"\"\"\n        self._live_render.vertical_overflow = self.vertical_overflow\n        if self.console.is_interactive:\n            # lock needs acquiring as user can modify live_render renderable at any time unlike in Progress.\n            with self._lock:\n                reset = (\n                    Control.home()\n                    if self._alt_screen\n                    else self._live_render.position_cursor()\n                )\n                renderables = [reset, *renderables, self._live_render]\n        elif (\n            not self._started and not self.transient\n        ):  # if it is finished render the final output for files or dumb_terminals\n            renderables = [*renderables, self._live_render]\n\n        return renderables\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import random\n    import time\n    from itertools import cycle\n    from typing import Dict, List, Tuple\n\n    from .align import Align\n    from .console import Console\n    from .live import Live as Live\n    from .panel import Panel\n    from .rule import Rule\n    from .syntax import Syntax\n    from .table import Table\n\n    console = Console()\n\n    syntax = Syntax(\n        '''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:\n    \"\"\"Iterate and generate a tuple with a flag for last value.\"\"\"\n    iter_values = iter(values)\n    try:\n        previous_value = next(iter_values)\n    except StopIteration:\n        return\n    for value in iter_values:\n        yield False, previous_value\n        previous_value = value\n    yield True, previous_value''',\n        \"python\",\n        line_numbers=True,\n    )\n\n    table = Table(\"foo\", \"bar\", \"baz\")\n    table.add_row(\"1\", \"2\", \"3\")\n\n    progress_renderables = [\n        \"You can make the terminal shorter and taller to see the live table hide\"\n        \"Text may be printed while the progress bars are rendering.\",\n        Panel(\"In fact, [i]any[/i] renderable will work\"),\n        \"Such as [magenta]tables[/]...\",\n        table,\n        \"Pretty printed structures...\",\n        {\"type\": \"example\", \"text\": \"Pretty printed\"},\n        \"Syntax...\",\n        syntax,\n        Rule(\"Give it a try!\"),\n    ]\n\n    examples = cycle(progress_renderables)\n\n    exchanges = [\n        \"SGD\",\n        \"MYR\",\n        \"EUR\",\n        \"USD\",\n        \"AUD\",\n        \"JPY\",\n        \"CNH\",\n        \"HKD\",\n        \"CAD\",\n        \"INR\",\n        \"DKK\",\n        \"GBP\",\n        \"RUB\",\n        \"NZD\",\n        \"MXN\",\n        \"IDR\",\n        \"TWD\",\n        \"THB\",\n        \"VND\",\n    ]\n    with Live(console=console) as live_table:\n        exchange_rate_dict: Dict[Tuple[str, str], float] = {}\n\n        for index in range(100):\n            select_exchange = exchanges[index % len(exchanges)]\n\n            for exchange in exchanges:\n                if exchange == select_exchange:\n                    continue\n                time.sleep(0.4)\n                if random.randint(0, 10) < 1:\n                    console.log(next(examples))\n                exchange_rate_dict[(select_exchange, exchange)] = 200 / (\n                    (random.random() * 320) + 1\n                )\n                if len(exchange_rate_dict) > len(exchanges) - 1:\n                    exchange_rate_dict.pop(list(exchange_rate_dict.keys())[0])\n                table = Table(title=\"Exchange Rates\")\n\n                table.add_column(\"Source Currency\")\n                table.add_column(\"Destination Currency\")\n                table.add_column(\"Exchange Rate\")\n\n                for ((source, dest), exchange_rate) in exchange_rate_dict.items():\n                    table.add_row(\n                        source,\n                        dest,\n                        Text(\n                            f\"{exchange_rate:.4f}\",\n                            style=\"red\" if exchange_rate < 1.0 else \"green\",\n                        ),\n                    )\n\n                live_table.update(Align.center(table))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/live_render.py",
    "content": "import sys\nfrom typing import Optional, Tuple\n\nif sys.version_info >= (3, 8):\n    from typing import Literal\nelse:\n    from pip._vendor.typing_extensions import Literal  # pragma: no cover\n\n\nfrom ._loop import loop_last\nfrom .console import Console, ConsoleOptions, RenderableType, RenderResult\nfrom .control import Control\nfrom .segment import ControlType, Segment\nfrom .style import StyleType\nfrom .text import Text\n\nVerticalOverflowMethod = Literal[\"crop\", \"ellipsis\", \"visible\"]\n\n\nclass LiveRender:\n    \"\"\"Creates a renderable that may be updated.\n\n    Args:\n        renderable (RenderableType): Any renderable object.\n        style (StyleType, optional): An optional style to apply to the renderable. Defaults to \"\".\n    \"\"\"\n\n    def __init__(\n        self,\n        renderable: RenderableType,\n        style: StyleType = \"\",\n        vertical_overflow: VerticalOverflowMethod = \"ellipsis\",\n    ) -> None:\n        self.renderable = renderable\n        self.style = style\n        self.vertical_overflow = vertical_overflow\n        self._shape: Optional[Tuple[int, int]] = None\n\n    def set_renderable(self, renderable: RenderableType) -> None:\n        \"\"\"Set a new renderable.\n\n        Args:\n            renderable (RenderableType): Any renderable object, including str.\n        \"\"\"\n        self.renderable = renderable\n\n    def position_cursor(self) -> Control:\n        \"\"\"Get control codes to move cursor to beginning of live render.\n\n        Returns:\n            Control: A control instance that may be printed.\n        \"\"\"\n        if self._shape is not None:\n            _, height = self._shape\n            return Control(\n                ControlType.CARRIAGE_RETURN,\n                (ControlType.ERASE_IN_LINE, 2),\n                *(\n                    (\n                        (ControlType.CURSOR_UP, 1),\n                        (ControlType.ERASE_IN_LINE, 2),\n                    )\n                    * (height - 1)\n                )\n            )\n        return Control()\n\n    def restore_cursor(self) -> Control:\n        \"\"\"Get control codes to clear the render and restore the cursor to its previous position.\n\n        Returns:\n            Control: A Control instance that may be printed.\n        \"\"\"\n        if self._shape is not None:\n            _, height = self._shape\n            return Control(\n                ControlType.CARRIAGE_RETURN,\n                *((ControlType.CURSOR_UP, 1), (ControlType.ERASE_IN_LINE, 2)) * height\n            )\n        return Control()\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n\n        renderable = self.renderable\n        style = console.get_style(self.style)\n        lines = console.render_lines(renderable, options, style=style, pad=False)\n        shape = Segment.get_shape(lines)\n\n        _, height = shape\n        if height > options.size.height:\n            if self.vertical_overflow == \"crop\":\n                lines = lines[: options.size.height]\n                shape = Segment.get_shape(lines)\n            elif self.vertical_overflow == \"ellipsis\":\n                lines = lines[: (options.size.height - 1)]\n                overflow_text = Text(\n                    \"...\",\n                    overflow=\"crop\",\n                    justify=\"center\",\n                    end=\"\",\n                    style=\"live.ellipsis\",\n                )\n                lines.append(list(console.render(overflow_text)))\n                shape = Segment.get_shape(lines)\n        self._shape = shape\n\n        new_line = Segment.line()\n        for last, line in loop_last(lines):\n            yield from line\n            if not last:\n                yield new_line\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/logging.py",
    "content": "import logging\nfrom datetime import datetime\nfrom logging import Handler, LogRecord\nfrom pathlib import Path\nfrom types import ModuleType\nfrom typing import ClassVar, List, Optional, Iterable, Type, Union\n\nfrom . import get_console\nfrom ._log_render import LogRender, FormatTimeCallable\nfrom .console import Console, ConsoleRenderable\nfrom .highlighter import Highlighter, ReprHighlighter\nfrom .text import Text\nfrom .traceback import Traceback\n\n\nclass RichHandler(Handler):\n    \"\"\"A logging handler that renders output with Rich. The time / level / message and file are displayed in columns.\n    The level is color coded, and the message is syntax highlighted.\n\n    Note:\n        Be careful when enabling console markup in log messages if you have configured logging for libraries not\n        under your control. If a dependency writes messages containing square brackets, it may not produce the intended output.\n\n    Args:\n        level (Union[int, str], optional): Log level. Defaults to logging.NOTSET.\n        console (:class:`~rich.console.Console`, optional): Optional console instance to write logs.\n            Default will use a global console instance writing to stdout.\n        show_time (bool, optional): Show a column for the time. Defaults to True.\n        omit_repeated_times (bool, optional): Omit repetition of the same time. Defaults to True.\n        show_level (bool, optional): Show a column for the level. Defaults to True.\n        show_path (bool, optional): Show the path to the original log call. Defaults to True.\n        enable_link_path (bool, optional): Enable terminal link of path column to file. Defaults to True.\n        highlighter (Highlighter, optional): Highlighter to style log messages, or None to use ReprHighlighter. Defaults to None.\n        markup (bool, optional): Enable console markup in log messages. Defaults to False.\n        rich_tracebacks (bool, optional): Enable rich tracebacks with syntax highlighting and formatting. Defaults to False.\n        tracebacks_width (Optional[int], optional): Number of characters used to render tracebacks, or None for full width. Defaults to None.\n        tracebacks_extra_lines (int, optional): Additional lines of code to render tracebacks, or None for full width. Defaults to None.\n        tracebacks_theme (str, optional): Override pygments theme used in traceback.\n        tracebacks_word_wrap (bool, optional): Enable word wrapping of long tracebacks lines. Defaults to True.\n        tracebacks_show_locals (bool, optional): Enable display of locals in tracebacks. Defaults to False.\n        tracebacks_suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.\n        locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to 10.\n        locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.\n        log_time_format (Union[str, TimeFormatterCallable], optional): If ``log_time`` is enabled, either string for strftime or callable that formats the time. Defaults to \"[%x %X] \".\n        keywords (List[str], optional): List of words to highlight instead of ``RichHandler.KEYWORDS``.\n    \"\"\"\n\n    KEYWORDS: ClassVar[Optional[List[str]]] = [\n        \"GET\",\n        \"POST\",\n        \"HEAD\",\n        \"PUT\",\n        \"DELETE\",\n        \"OPTIONS\",\n        \"TRACE\",\n        \"PATCH\",\n    ]\n    HIGHLIGHTER_CLASS: ClassVar[Type[Highlighter]] = ReprHighlighter\n\n    def __init__(\n        self,\n        level: Union[int, str] = logging.NOTSET,\n        console: Optional[Console] = None,\n        *,\n        show_time: bool = True,\n        omit_repeated_times: bool = True,\n        show_level: bool = True,\n        show_path: bool = True,\n        enable_link_path: bool = True,\n        highlighter: Optional[Highlighter] = None,\n        markup: bool = False,\n        rich_tracebacks: bool = False,\n        tracebacks_width: Optional[int] = None,\n        tracebacks_extra_lines: int = 3,\n        tracebacks_theme: Optional[str] = None,\n        tracebacks_word_wrap: bool = True,\n        tracebacks_show_locals: bool = False,\n        tracebacks_suppress: Iterable[Union[str, ModuleType]] = (),\n        locals_max_length: int = 10,\n        locals_max_string: int = 80,\n        log_time_format: Union[str, FormatTimeCallable] = \"[%x %X]\",\n        keywords: Optional[List[str]] = None,\n    ) -> None:\n        super().__init__(level=level)\n        self.console = console or get_console()\n        self.highlighter = highlighter or self.HIGHLIGHTER_CLASS()\n        self._log_render = LogRender(\n            show_time=show_time,\n            show_level=show_level,\n            show_path=show_path,\n            time_format=log_time_format,\n            omit_repeated_times=omit_repeated_times,\n            level_width=None,\n        )\n        self.enable_link_path = enable_link_path\n        self.markup = markup\n        self.rich_tracebacks = rich_tracebacks\n        self.tracebacks_width = tracebacks_width\n        self.tracebacks_extra_lines = tracebacks_extra_lines\n        self.tracebacks_theme = tracebacks_theme\n        self.tracebacks_word_wrap = tracebacks_word_wrap\n        self.tracebacks_show_locals = tracebacks_show_locals\n        self.tracebacks_suppress = tracebacks_suppress\n        self.locals_max_length = locals_max_length\n        self.locals_max_string = locals_max_string\n        self.keywords = keywords\n\n    def get_level_text(self, record: LogRecord) -> Text:\n        \"\"\"Get the level name from the record.\n\n        Args:\n            record (LogRecord): LogRecord instance.\n\n        Returns:\n            Text: A tuple of the style and level name.\n        \"\"\"\n        level_name = record.levelname\n        level_text = Text.styled(\n            level_name.ljust(8), f\"logging.level.{level_name.lower()}\"\n        )\n        return level_text\n\n    def emit(self, record: LogRecord) -> None:\n        \"\"\"Invoked by logging.\"\"\"\n        message = self.format(record)\n        traceback = None\n        if (\n            self.rich_tracebacks\n            and record.exc_info\n            and record.exc_info != (None, None, None)\n        ):\n            exc_type, exc_value, exc_traceback = record.exc_info\n            assert exc_type is not None\n            assert exc_value is not None\n            traceback = Traceback.from_exception(\n                exc_type,\n                exc_value,\n                exc_traceback,\n                width=self.tracebacks_width,\n                extra_lines=self.tracebacks_extra_lines,\n                theme=self.tracebacks_theme,\n                word_wrap=self.tracebacks_word_wrap,\n                show_locals=self.tracebacks_show_locals,\n                locals_max_length=self.locals_max_length,\n                locals_max_string=self.locals_max_string,\n                suppress=self.tracebacks_suppress,\n            )\n            message = record.getMessage()\n            if self.formatter:\n                record.message = record.getMessage()\n                formatter = self.formatter\n                if hasattr(formatter, \"usesTime\") and formatter.usesTime():\n                    record.asctime = formatter.formatTime(record, formatter.datefmt)\n                message = formatter.formatMessage(record)\n\n        message_renderable = self.render_message(record, message)\n        log_renderable = self.render(\n            record=record, traceback=traceback, message_renderable=message_renderable\n        )\n        try:\n            self.console.print(log_renderable)\n        except Exception:\n            self.handleError(record)\n\n    def render_message(self, record: LogRecord, message: str) -> \"ConsoleRenderable\":\n        \"\"\"Render message text in to Text.\n\n        record (LogRecord): logging Record.\n        message (str): String containing log message.\n\n        Returns:\n            ConsoleRenderable: Renderable to display log message.\n        \"\"\"\n        use_markup = getattr(record, \"markup\", self.markup)\n        message_text = Text.from_markup(message) if use_markup else Text(message)\n\n        highlighter = getattr(record, \"highlighter\", self.highlighter)\n        if highlighter:\n            message_text = highlighter(message_text)\n\n        if self.keywords is None:\n            self.keywords = self.KEYWORDS\n\n        if self.keywords:\n            message_text.highlight_words(self.keywords, \"logging.keyword\")\n\n        return message_text\n\n    def render(\n        self,\n        *,\n        record: LogRecord,\n        traceback: Optional[Traceback],\n        message_renderable: \"ConsoleRenderable\",\n    ) -> \"ConsoleRenderable\":\n        \"\"\"Render log for display.\n\n        Args:\n            record (LogRecord): logging Record.\n            traceback (Optional[Traceback]): Traceback instance or None for no Traceback.\n            message_renderable (ConsoleRenderable): Renderable (typically Text) containing log message contents.\n\n        Returns:\n            ConsoleRenderable: Renderable to display log.\n        \"\"\"\n        path = Path(record.pathname).name\n        level = self.get_level_text(record)\n        time_format = None if self.formatter is None else self.formatter.datefmt\n        log_time = datetime.fromtimestamp(record.created)\n\n        log_renderable = self._log_render(\n            self.console,\n            [message_renderable] if not traceback else [message_renderable, traceback],\n            log_time=log_time,\n            time_format=time_format,\n            level=level,\n            path=path,\n            line_no=record.lineno,\n            link_path=record.pathname if self.enable_link_path else None,\n        )\n        return log_renderable\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from time import sleep\n\n    FORMAT = \"%(message)s\"\n    # FORMAT = \"%(asctime)-15s - %(levelname)s - %(message)s\"\n    logging.basicConfig(\n        level=\"NOTSET\",\n        format=FORMAT,\n        datefmt=\"[%X]\",\n        handlers=[RichHandler(rich_tracebacks=True, tracebacks_show_locals=True)],\n    )\n    log = logging.getLogger(\"rich\")\n\n    log.info(\"Server starting...\")\n    log.info(\"Listening on http://127.0.0.1:8080\")\n    sleep(1)\n\n    log.info(\"GET /index.html 200 1298\")\n    log.info(\"GET /imgs/backgrounds/back1.jpg 200 54386\")\n    log.info(\"GET /css/styles.css 200 54386\")\n    log.warning(\"GET /favicon.ico 404 242\")\n    sleep(1)\n\n    log.debug(\n        \"JSONRPC request\\n--> %r\\n<-- %r\",\n        {\n            \"version\": \"1.1\",\n            \"method\": \"confirmFruitPurchase\",\n            \"params\": [[\"apple\", \"orange\", \"mangoes\", \"pomelo\"], 1.123],\n            \"id\": \"194521489\",\n        },\n        {\"version\": \"1.1\", \"result\": True, \"error\": None, \"id\": \"194521489\"},\n    )\n    log.debug(\n        \"Loading configuration file /adasd/asdasd/qeqwe/qwrqwrqwr/sdgsdgsdg/werwerwer/dfgerert/ertertert/ertetert/werwerwer\"\n    )\n    log.error(\"Unable to find 'pomelo' in database!\")\n    log.info(\"POST /jsonrpc/ 200 65532\")\n    log.info(\"POST /admin/ 401 42234\")\n    log.warning(\"password was rejected for admin site.\")\n\n    def divide() -> None:\n        number = 1\n        divisor = 0\n        foos = [\"foo\"] * 100\n        log.debug(\"in divide\")\n        try:\n            number / divisor\n        except:\n            log.exception(\"An error of some kind occurred!\")\n\n    divide()\n    sleep(1)\n    log.critical(\"Out of memory!\")\n    log.info(\"Server exited with code=-1\")\n    log.info(\"[bold]EXITING...[/bold]\", extra=dict(markup=True))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/markup.py",
    "content": "import re\nfrom ast import literal_eval\nfrom operator import attrgetter\nfrom typing import Callable, Iterable, List, Match, NamedTuple, Optional, Tuple, Union\n\nfrom ._emoji_replace import _emoji_replace\nfrom .emoji import EmojiVariant\nfrom .errors import MarkupError\nfrom .style import Style\nfrom .text import Span, Text\n\nRE_TAGS = re.compile(\n    r\"\"\"((\\\\*)\\[([a-z#/@][^[]*?)])\"\"\",\n    re.VERBOSE,\n)\n\nRE_HANDLER = re.compile(r\"^([\\w.]*?)(\\(.*?\\))?$\")\n\n\nclass Tag(NamedTuple):\n    \"\"\"A tag in console markup.\"\"\"\n\n    name: str\n    \"\"\"The tag name. e.g. 'bold'.\"\"\"\n    parameters: Optional[str]\n    \"\"\"Any additional parameters after the name.\"\"\"\n\n    def __str__(self) -> str:\n        return (\n            self.name if self.parameters is None else f\"{self.name} {self.parameters}\"\n        )\n\n    @property\n    def markup(self) -> str:\n        \"\"\"Get the string representation of this tag.\"\"\"\n        return (\n            f\"[{self.name}]\"\n            if self.parameters is None\n            else f\"[{self.name}={self.parameters}]\"\n        )\n\n\n_ReStringMatch = Match[str]  # regex match object\n_ReSubCallable = Callable[[_ReStringMatch], str]  # Callable invoked by re.sub\n_EscapeSubMethod = Callable[[_ReSubCallable, str], str]  # Sub method of a compiled re\n\n\ndef escape(\n    markup: str,\n    _escape: _EscapeSubMethod = re.compile(r\"(\\\\*)(\\[[a-z#/@][^[]*?])\").sub,\n) -> str:\n    \"\"\"Escapes text so that it won't be interpreted as markup.\n\n    Args:\n        markup (str): Content to be inserted in to markup.\n\n    Returns:\n        str: Markup with square brackets escaped.\n    \"\"\"\n\n    def escape_backslashes(match: Match[str]) -> str:\n        \"\"\"Called by re.sub replace matches.\"\"\"\n        backslashes, text = match.groups()\n        return f\"{backslashes}{backslashes}\\\\{text}\"\n\n    markup = _escape(escape_backslashes, markup)\n    return markup\n\n\ndef _parse(markup: str) -> Iterable[Tuple[int, Optional[str], Optional[Tag]]]:\n    \"\"\"Parse markup in to an iterable of tuples of (position, text, tag).\n\n    Args:\n        markup (str): A string containing console markup\n\n    \"\"\"\n    position = 0\n    _divmod = divmod\n    _Tag = Tag\n    for match in RE_TAGS.finditer(markup):\n        full_text, escapes, tag_text = match.groups()\n        start, end = match.span()\n        if start > position:\n            yield start, markup[position:start], None\n        if escapes:\n            backslashes, escaped = _divmod(len(escapes), 2)\n            if backslashes:\n                # Literal backslashes\n                yield start, \"\\\\\" * backslashes, None\n                start += backslashes * 2\n            if escaped:\n                # Escape of tag\n                yield start, full_text[len(escapes) :], None\n                position = end\n                continue\n        text, equals, parameters = tag_text.partition(\"=\")\n        yield start, None, _Tag(text, parameters if equals else None)\n        position = end\n    if position < len(markup):\n        yield position, markup[position:], None\n\n\ndef render(\n    markup: str,\n    style: Union[str, Style] = \"\",\n    emoji: bool = True,\n    emoji_variant: Optional[EmojiVariant] = None,\n) -> Text:\n    \"\"\"Render console markup in to a Text instance.\n\n    Args:\n        markup (str): A string containing console markup.\n        emoji (bool, optional): Also render emoji code. Defaults to True.\n\n    Raises:\n        MarkupError: If there is a syntax error in the markup.\n\n    Returns:\n        Text: A test instance.\n    \"\"\"\n    emoji_replace = _emoji_replace\n    if \"[\" not in markup:\n        return Text(\n            emoji_replace(markup, default_variant=emoji_variant) if emoji else markup,\n            style=style,\n        )\n    text = Text(style=style)\n    append = text.append\n    normalize = Style.normalize\n\n    style_stack: List[Tuple[int, Tag]] = []\n    pop = style_stack.pop\n\n    spans: List[Span] = []\n    append_span = spans.append\n\n    _Span = Span\n    _Tag = Tag\n\n    def pop_style(style_name: str) -> Tuple[int, Tag]:\n        \"\"\"Pop tag matching given style name.\"\"\"\n        for index, (_, tag) in enumerate(reversed(style_stack), 1):\n            if tag.name == style_name:\n                return pop(-index)\n        raise KeyError(style_name)\n\n    for position, plain_text, tag in _parse(markup):\n        if plain_text is not None:\n            # Handle open brace escapes, where the brace is not part of a tag.\n            plain_text = plain_text.replace(\"\\\\[\", \"[\")\n            append(emoji_replace(plain_text) if emoji else plain_text)\n        elif tag is not None:\n            if tag.name.startswith(\"/\"):  # Closing tag\n                style_name = tag.name[1:].strip()\n\n                if style_name:  # explicit close\n                    style_name = normalize(style_name)\n                    try:\n                        start, open_tag = pop_style(style_name)\n                    except KeyError:\n                        raise MarkupError(\n                            f\"closing tag '{tag.markup}' at position {position} doesn't match any open tag\"\n                        ) from None\n                else:  # implicit close\n                    try:\n                        start, open_tag = pop()\n                    except IndexError:\n                        raise MarkupError(\n                            f\"closing tag '[/]' at position {position} has nothing to close\"\n                        ) from None\n\n                if open_tag.name.startswith(\"@\"):\n                    if open_tag.parameters:\n                        handler_name = \"\"\n                        parameters = open_tag.parameters.strip()\n                        handler_match = RE_HANDLER.match(parameters)\n                        if handler_match is not None:\n                            handler_name, match_parameters = handler_match.groups()\n                            parameters = (\n                                \"()\" if match_parameters is None else match_parameters\n                            )\n\n                        try:\n                            meta_params = literal_eval(parameters)\n                        except SyntaxError as error:\n                            raise MarkupError(\n                                f\"error parsing {parameters!r} in {open_tag.parameters!r}; {error.msg}\"\n                            )\n                        except Exception as error:\n                            raise MarkupError(\n                                f\"error parsing {open_tag.parameters!r}; {error}\"\n                            ) from None\n\n                        if handler_name:\n                            meta_params = (\n                                handler_name,\n                                meta_params\n                                if isinstance(meta_params, tuple)\n                                else (meta_params,),\n                            )\n\n                    else:\n                        meta_params = ()\n\n                    append_span(\n                        _Span(\n                            start, len(text), Style(meta={open_tag.name: meta_params})\n                        )\n                    )\n                else:\n                    append_span(_Span(start, len(text), str(open_tag)))\n\n            else:  # Opening tag\n                normalized_tag = _Tag(normalize(tag.name), tag.parameters)\n                style_stack.append((len(text), normalized_tag))\n\n    text_length = len(text)\n    while style_stack:\n        start, tag = style_stack.pop()\n        style = str(tag)\n        if style:\n            append_span(_Span(start, text_length, style))\n\n    text.spans = sorted(spans[::-1], key=attrgetter(\"start\"))\n    return text\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n\n    MARKUP = [\n        \"[red]Hello World[/red]\",\n        \"[magenta]Hello [b]World[/b]\",\n        \"[bold]Bold[italic] bold and italic [/bold]italic[/italic]\",\n        \"Click [link=https://www.willmcgugan.com]here[/link] to visit my Blog\",\n        \":warning-emoji: [bold red blink] DANGER![/]\",\n    ]\n\n    from pip._vendor.rich import print\n    from pip._vendor.rich.table import Table\n\n    grid = Table(\"Markup\", \"Result\", padding=(0, 1))\n\n    for markup in MARKUP:\n        grid.add_row(Text(markup), markup)\n\n    print(grid)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/measure.py",
    "content": "from operator import itemgetter\nfrom typing import TYPE_CHECKING, Callable, NamedTuple, Optional, Sequence\n\nfrom . import errors\nfrom .protocol import is_renderable, rich_cast\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderableType\n\n\nclass Measurement(NamedTuple):\n    \"\"\"Stores the minimum and maximum widths (in characters) required to render an object.\"\"\"\n\n    minimum: int\n    \"\"\"Minimum number of cells required to render.\"\"\"\n    maximum: int\n    \"\"\"Maximum number of cells required to render.\"\"\"\n\n    @property\n    def span(self) -> int:\n        \"\"\"Get difference between maximum and minimum.\"\"\"\n        return self.maximum - self.minimum\n\n    def normalize(self) -> \"Measurement\":\n        \"\"\"Get measurement that ensures that minimum <= maximum and minimum >= 0\n\n        Returns:\n            Measurement: A normalized measurement.\n        \"\"\"\n        minimum, maximum = self\n        minimum = min(max(0, minimum), maximum)\n        return Measurement(max(0, minimum), max(0, max(minimum, maximum)))\n\n    def with_maximum(self, width: int) -> \"Measurement\":\n        \"\"\"Get a RenderableWith where the widths are <= width.\n\n        Args:\n            width (int): Maximum desired width.\n\n        Returns:\n            Measurement: New Measurement object.\n        \"\"\"\n        minimum, maximum = self\n        return Measurement(min(minimum, width), min(maximum, width))\n\n    def with_minimum(self, width: int) -> \"Measurement\":\n        \"\"\"Get a RenderableWith where the widths are >= width.\n\n        Args:\n            width (int): Minimum desired width.\n\n        Returns:\n            Measurement: New Measurement object.\n        \"\"\"\n        minimum, maximum = self\n        width = max(0, width)\n        return Measurement(max(minimum, width), max(maximum, width))\n\n    def clamp(\n        self, min_width: Optional[int] = None, max_width: Optional[int] = None\n    ) -> \"Measurement\":\n        \"\"\"Clamp a measurement within the specified range.\n\n        Args:\n            min_width (int): Minimum desired width, or ``None`` for no minimum. Defaults to None.\n            max_width (int): Maximum desired width, or ``None`` for no maximum. Defaults to None.\n\n        Returns:\n            Measurement: New Measurement object.\n        \"\"\"\n        measurement = self\n        if min_width is not None:\n            measurement = measurement.with_minimum(min_width)\n        if max_width is not None:\n            measurement = measurement.with_maximum(max_width)\n        return measurement\n\n    @classmethod\n    def get(\n        cls, console: \"Console\", options: \"ConsoleOptions\", renderable: \"RenderableType\"\n    ) -> \"Measurement\":\n        \"\"\"Get a measurement for a renderable.\n\n        Args:\n            console (~rich.console.Console): Console instance.\n            options (~rich.console.ConsoleOptions): Console options.\n            renderable (RenderableType): An object that may be rendered with Rich.\n\n        Raises:\n            errors.NotRenderableError: If the object is not renderable.\n\n        Returns:\n            Measurement: Measurement object containing range of character widths required to render the object.\n        \"\"\"\n        _max_width = options.max_width\n        if _max_width < 1:\n            return Measurement(0, 0)\n        if isinstance(renderable, str):\n            renderable = console.render_str(\n                renderable, markup=options.markup, highlight=False\n            )\n        renderable = rich_cast(renderable)\n        if is_renderable(renderable):\n            get_console_width: Optional[\n                Callable[[\"Console\", \"ConsoleOptions\"], \"Measurement\"]\n            ] = getattr(renderable, \"__rich_measure__\", None)\n            if get_console_width is not None:\n                render_width = (\n                    get_console_width(console, options)\n                    .normalize()\n                    .with_maximum(_max_width)\n                )\n                if render_width.maximum < 1:\n                    return Measurement(0, 0)\n                return render_width.normalize()\n            else:\n                return Measurement(0, _max_width)\n        else:\n            raise errors.NotRenderableError(\n                f\"Unable to get render width for {renderable!r}; \"\n                \"a str, Segment, or object with __rich_console__ method is required\"\n            )\n\n\ndef measure_renderables(\n    console: \"Console\",\n    options: \"ConsoleOptions\",\n    renderables: Sequence[\"RenderableType\"],\n) -> \"Measurement\":\n    \"\"\"Get a measurement that would fit a number of renderables.\n\n    Args:\n        console (~rich.console.Console): Console instance.\n        options (~rich.console.ConsoleOptions): Console options.\n        renderables (Iterable[RenderableType]): One or more renderable objects.\n\n    Returns:\n        Measurement: Measurement object containing range of character widths required to\n            contain all given renderables.\n    \"\"\"\n    if not renderables:\n        return Measurement(0, 0)\n    get_measurement = Measurement.get\n    measurements = [\n        get_measurement(console, options, renderable) for renderable in renderables\n    ]\n    measured_width = Measurement(\n        max(measurements, key=itemgetter(0)).minimum,\n        max(measurements, key=itemgetter(1)).maximum,\n    )\n    return measured_width\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/padding.py",
    "content": "from typing import cast, List, Optional, Tuple, TYPE_CHECKING, Union\n\nif TYPE_CHECKING:\n    from .console import (\n        Console,\n        ConsoleOptions,\n        RenderableType,\n        RenderResult,\n    )\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .style import Style\nfrom .segment import Segment\n\n\nPaddingDimensions = Union[int, Tuple[int], Tuple[int, int], Tuple[int, int, int, int]]\n\n\nclass Padding(JupyterMixin):\n    \"\"\"Draw space around content.\n\n    Example:\n        >>> print(Padding(\"Hello\", (2, 4), style=\"on blue\"))\n\n    Args:\n        renderable (RenderableType): String or other renderable.\n        pad (Union[int, Tuple[int]]): Padding for top, right, bottom, and left borders.\n            May be specified with 1, 2, or 4 integers (CSS style).\n        style (Union[str, Style], optional): Style for padding characters. Defaults to \"none\".\n        expand (bool, optional): Expand padding to fit available width. Defaults to True.\n    \"\"\"\n\n    def __init__(\n        self,\n        renderable: \"RenderableType\",\n        pad: \"PaddingDimensions\" = (0, 0, 0, 0),\n        *,\n        style: Union[str, Style] = \"none\",\n        expand: bool = True,\n    ):\n        self.renderable = renderable\n        self.top, self.right, self.bottom, self.left = self.unpack(pad)\n        self.style = style\n        self.expand = expand\n\n    @classmethod\n    def indent(cls, renderable: \"RenderableType\", level: int) -> \"Padding\":\n        \"\"\"Make padding instance to render an indent.\n\n        Args:\n            renderable (RenderableType): String or other renderable.\n            level (int): Number of characters to indent.\n\n        Returns:\n            Padding: A Padding instance.\n        \"\"\"\n\n        return Padding(renderable, pad=(0, 0, 0, level), expand=False)\n\n    @staticmethod\n    def unpack(pad: \"PaddingDimensions\") -> Tuple[int, int, int, int]:\n        \"\"\"Unpack padding specified in CSS style.\"\"\"\n        if isinstance(pad, int):\n            return (pad, pad, pad, pad)\n        if len(pad) == 1:\n            _pad = pad[0]\n            return (_pad, _pad, _pad, _pad)\n        if len(pad) == 2:\n            pad_top, pad_right = cast(Tuple[int, int], pad)\n            return (pad_top, pad_right, pad_top, pad_right)\n        if len(pad) == 4:\n            top, right, bottom, left = cast(Tuple[int, int, int, int], pad)\n            return (top, right, bottom, left)\n        raise ValueError(f\"1, 2 or 4 integers required for padding; {len(pad)} given\")\n\n    def __repr__(self) -> str:\n        return f\"Padding({self.renderable!r}, ({self.top},{self.right},{self.bottom},{self.left}))\"\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        style = console.get_style(self.style)\n        if self.expand:\n            width = options.max_width\n        else:\n            width = min(\n                Measurement.get(console, options, self.renderable).maximum\n                + self.left\n                + self.right,\n                options.max_width,\n            )\n        render_options = options.update_width(width - self.left - self.right)\n        if render_options.height is not None:\n            render_options = render_options.update_height(\n                height=render_options.height - self.top - self.bottom\n            )\n        lines = console.render_lines(\n            self.renderable, render_options, style=style, pad=True\n        )\n        _Segment = Segment\n\n        left = _Segment(\" \" * self.left, style) if self.left else None\n        right = (\n            [_Segment(f'{\" \" * self.right}', style), _Segment.line()]\n            if self.right\n            else [_Segment.line()]\n        )\n        blank_line: Optional[List[Segment]] = None\n        if self.top:\n            blank_line = [_Segment(f'{\" \" * width}\\n', style)]\n            yield from blank_line * self.top\n        if left:\n            for line in lines:\n                yield left\n                yield from line\n                yield from right\n        else:\n            for line in lines:\n                yield from line\n                yield from right\n        if self.bottom:\n            blank_line = blank_line or [_Segment(f'{\" \" * width}\\n', style)]\n            yield from blank_line * self.bottom\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        max_width = options.max_width\n        extra_width = self.left + self.right\n        if max_width - extra_width < 1:\n            return Measurement(max_width, max_width)\n        measure_min, measure_max = Measurement.get(console, options, self.renderable)\n        measurement = Measurement(measure_min + extra_width, measure_max + extra_width)\n        measurement = measurement.with_maximum(max_width)\n        return measurement\n\n\nif __name__ == \"__main__\":  #  pragma: no cover\n    from pip._vendor.rich import print\n\n    print(Padding(\"Hello, World\", (2, 4), style=\"on blue\"))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/pager.py",
    "content": "from abc import ABC, abstractmethod\nfrom typing import Any\n\n\nclass Pager(ABC):\n    \"\"\"Base class for a pager.\"\"\"\n\n    @abstractmethod\n    def show(self, content: str) -> None:\n        \"\"\"Show content in pager.\n\n        Args:\n            content (str): Content to be displayed.\n        \"\"\"\n\n\nclass SystemPager(Pager):\n    \"\"\"Uses the pager installed on the system.\"\"\"\n\n    def _pager(self, content: str) -> Any:  #  pragma: no cover\n        return __import__(\"pydoc\").pager(content)\n\n    def show(self, content: str) -> None:\n        \"\"\"Use the same pager used by pydoc.\"\"\"\n        self._pager(content)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from .__main__ import make_test_card\n    from .console import Console\n\n    console = Console()\n    with console.pager(styles=True):\n        console.print(make_test_card())\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/palette.py",
    "content": "from math import sqrt\nfrom functools import lru_cache\nfrom typing import Sequence, Tuple, TYPE_CHECKING\n\nfrom .color_triplet import ColorTriplet\n\nif TYPE_CHECKING:\n    from pip._vendor.rich.table import Table\n\n\nclass Palette:\n    \"\"\"A palette of available colors.\"\"\"\n\n    def __init__(self, colors: Sequence[Tuple[int, int, int]]):\n        self._colors = colors\n\n    def __getitem__(self, number: int) -> ColorTriplet:\n        return ColorTriplet(*self._colors[number])\n\n    def __rich__(self) -> \"Table\":\n        from pip._vendor.rich.color import Color\n        from pip._vendor.rich.style import Style\n        from pip._vendor.rich.text import Text\n        from pip._vendor.rich.table import Table\n\n        table = Table(\n            \"index\",\n            \"RGB\",\n            \"Color\",\n            title=\"Palette\",\n            caption=f\"{len(self._colors)} colors\",\n            highlight=True,\n            caption_justify=\"right\",\n        )\n        for index, color in enumerate(self._colors):\n            table.add_row(\n                str(index),\n                repr(color),\n                Text(\" \" * 16, style=Style(bgcolor=Color.from_rgb(*color))),\n            )\n        return table\n\n    # This is somewhat inefficient and needs caching\n    @lru_cache(maxsize=1024)\n    def match(self, color: Tuple[int, int, int]) -> int:\n        \"\"\"Find a color from a palette that most closely matches a given color.\n\n        Args:\n            color (Tuple[int, int, int]): RGB components in range 0 > 255.\n\n        Returns:\n            int: Index of closes matching color.\n        \"\"\"\n        red1, green1, blue1 = color\n        _sqrt = sqrt\n        get_color = self._colors.__getitem__\n\n        def get_color_distance(index: int) -> float:\n            \"\"\"Get the distance to a color.\"\"\"\n            red2, green2, blue2 = get_color(index)\n            red_mean = (red1 + red2) // 2\n            red = red1 - red2\n            green = green1 - green2\n            blue = blue1 - blue2\n            return _sqrt(\n                (((512 + red_mean) * red * red) >> 8)\n                + 4 * green * green\n                + (((767 - red_mean) * blue * blue) >> 8)\n            )\n\n        min_index = min(range(len(self._colors)), key=get_color_distance)\n        return min_index\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import colorsys\n    from typing import Iterable\n    from pip._vendor.rich.color import Color\n    from pip._vendor.rich.console import Console, ConsoleOptions\n    from pip._vendor.rich.segment import Segment\n    from pip._vendor.rich.style import Style\n\n    class ColorBox:\n        def __rich_console__(\n            self, console: Console, options: ConsoleOptions\n        ) -> Iterable[Segment]:\n            height = console.size.height - 3\n            for y in range(0, height):\n                for x in range(options.max_width):\n                    h = x / options.max_width\n                    l = y / (height + 1)\n                    r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0)\n                    r2, g2, b2 = colorsys.hls_to_rgb(h, l + (1 / height / 2), 1.0)\n                    bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255)\n                    color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255)\n                    yield Segment(\"▄\", Style(color=color, bgcolor=bgcolor))\n                yield Segment.line()\n\n    console = Console()\n    console.print(ColorBox())\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/panel.py",
    "content": "from typing import TYPE_CHECKING, Optional\n\nfrom .align import AlignMethod\nfrom .box import ROUNDED, Box\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement, measure_renderables\nfrom .padding import Padding, PaddingDimensions\nfrom .segment import Segment\nfrom .style import StyleType\nfrom .text import Text, TextType\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderableType, RenderResult\n\n\nclass Panel(JupyterMixin):\n    \"\"\"A console renderable that draws a border around its contents.\n\n    Example:\n        >>> console.print(Panel(\"Hello, World!\"))\n\n    Args:\n        renderable (RenderableType): A console renderable object.\n        box (Box, optional): A Box instance that defines the look of the border (see :ref:`appendix_box`.\n            Defaults to box.ROUNDED.\n        safe_box (bool, optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True.\n        expand (bool, optional): If True the panel will stretch to fill the console\n            width, otherwise it will be sized to fit the contents. Defaults to True.\n        style (str, optional): The style of the panel (border and contents). Defaults to \"none\".\n        border_style (str, optional): The style of the border. Defaults to \"none\".\n        width (Optional[int], optional): Optional width of panel. Defaults to None to auto-detect.\n        height (Optional[int], optional): Optional height of panel. Defaults to None to auto-detect.\n        padding (Optional[PaddingDimensions]): Optional padding around renderable. Defaults to 0.\n        highlight (bool, optional): Enable automatic highlighting of panel title (if str). Defaults to False.\n    \"\"\"\n\n    def __init__(\n        self,\n        renderable: \"RenderableType\",\n        box: Box = ROUNDED,\n        *,\n        title: Optional[TextType] = None,\n        title_align: AlignMethod = \"center\",\n        subtitle: Optional[TextType] = None,\n        subtitle_align: AlignMethod = \"center\",\n        safe_box: Optional[bool] = None,\n        expand: bool = True,\n        style: StyleType = \"none\",\n        border_style: StyleType = \"none\",\n        width: Optional[int] = None,\n        height: Optional[int] = None,\n        padding: PaddingDimensions = (0, 1),\n        highlight: bool = False,\n    ) -> None:\n        self.renderable = renderable\n        self.box = box\n        self.title = title\n        self.title_align: AlignMethod = title_align\n        self.subtitle = subtitle\n        self.subtitle_align = subtitle_align\n        self.safe_box = safe_box\n        self.expand = expand\n        self.style = style\n        self.border_style = border_style\n        self.width = width\n        self.height = height\n        self.padding = padding\n        self.highlight = highlight\n\n    @classmethod\n    def fit(\n        cls,\n        renderable: \"RenderableType\",\n        box: Box = ROUNDED,\n        *,\n        title: Optional[TextType] = None,\n        title_align: AlignMethod = \"center\",\n        subtitle: Optional[TextType] = None,\n        subtitle_align: AlignMethod = \"center\",\n        safe_box: Optional[bool] = None,\n        style: StyleType = \"none\",\n        border_style: StyleType = \"none\",\n        width: Optional[int] = None,\n        padding: PaddingDimensions = (0, 1),\n    ) -> \"Panel\":\n        \"\"\"An alternative constructor that sets expand=False.\"\"\"\n        return cls(\n            renderable,\n            box,\n            title=title,\n            title_align=title_align,\n            subtitle=subtitle,\n            subtitle_align=subtitle_align,\n            safe_box=safe_box,\n            style=style,\n            border_style=border_style,\n            width=width,\n            padding=padding,\n            expand=False,\n        )\n\n    @property\n    def _title(self) -> Optional[Text]:\n        if self.title:\n            title_text = (\n                Text.from_markup(self.title)\n                if isinstance(self.title, str)\n                else self.title.copy()\n            )\n            title_text.end = \"\"\n            title_text.plain = title_text.plain.replace(\"\\n\", \" \")\n            title_text.no_wrap = True\n            title_text.expand_tabs()\n            title_text.pad(1)\n            return title_text\n        return None\n\n    @property\n    def _subtitle(self) -> Optional[Text]:\n        if self.subtitle:\n            subtitle_text = (\n                Text.from_markup(self.subtitle)\n                if isinstance(self.subtitle, str)\n                else self.subtitle.copy()\n            )\n            subtitle_text.end = \"\"\n            subtitle_text.plain = subtitle_text.plain.replace(\"\\n\", \" \")\n            subtitle_text.no_wrap = True\n            subtitle_text.expand_tabs()\n            subtitle_text.pad(1)\n            return subtitle_text\n        return None\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        _padding = Padding.unpack(self.padding)\n        renderable = (\n            Padding(self.renderable, _padding) if any(_padding) else self.renderable\n        )\n        style = console.get_style(self.style)\n        border_style = style + console.get_style(self.border_style)\n        width = (\n            options.max_width\n            if self.width is None\n            else min(options.max_width, self.width)\n        )\n\n        safe_box: bool = console.safe_box if self.safe_box is None else self.safe_box\n        box = self.box.substitute(options, safe=safe_box)\n\n        title_text = self._title\n        if title_text is not None:\n            title_text.style = border_style\n\n        child_width = (\n            width - 2\n            if self.expand\n            else console.measure(\n                renderable, options=options.update_width(width - 2)\n            ).maximum\n        )\n        child_height = self.height or options.height or None\n        if child_height:\n            child_height -= 2\n        if title_text is not None:\n            child_width = min(\n                options.max_width - 2, max(child_width, title_text.cell_len + 2)\n            )\n\n        width = child_width + 2\n        child_options = options.update(\n            width=child_width, height=child_height, highlight=self.highlight\n        )\n        lines = console.render_lines(renderable, child_options, style=style)\n\n        line_start = Segment(box.mid_left, border_style)\n        line_end = Segment(f\"{box.mid_right}\", border_style)\n        new_line = Segment.line()\n        if title_text is None or width <= 4:\n            yield Segment(box.get_top([width - 2]), border_style)\n        else:\n            title_text.align(self.title_align, width - 4, character=box.top)\n            yield Segment(box.top_left + box.top, border_style)\n            yield from console.render(title_text, child_options.update_width(width - 4))\n            yield Segment(box.top + box.top_right, border_style)\n\n        yield new_line\n        for line in lines:\n            yield line_start\n            yield from line\n            yield line_end\n            yield new_line\n\n        subtitle_text = self._subtitle\n        if subtitle_text is not None:\n            subtitle_text.style = border_style\n\n        if subtitle_text is None or width <= 4:\n            yield Segment(box.get_bottom([width - 2]), border_style)\n        else:\n            subtitle_text.align(self.subtitle_align, width - 4, character=box.bottom)\n            yield Segment(box.bottom_left + box.bottom, border_style)\n            yield from console.render(\n                subtitle_text, child_options.update_width(width - 4)\n            )\n            yield Segment(box.bottom + box.bottom_right, border_style)\n\n        yield new_line\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        _title = self._title\n        _, right, _, left = Padding.unpack(self.padding)\n        padding = left + right\n        renderables = [self.renderable, _title] if _title else [self.renderable]\n\n        if self.width is None:\n            width = (\n                measure_renderables(\n                    console,\n                    options.update_width(options.max_width - padding - 2),\n                    renderables,\n                ).maximum\n                + padding\n                + 2\n            )\n        else:\n            width = self.width\n        return Measurement(width, width)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from .console import Console\n\n    c = Console()\n\n    from .box import DOUBLE, ROUNDED\n    from .padding import Padding\n\n    p = Panel(\n        \"Hello, World!\",\n        title=\"rich.Panel\",\n        style=\"white on blue\",\n        box=DOUBLE,\n        padding=1,\n    )\n\n    c.print()\n    c.print(p)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/pretty.py",
    "content": "import builtins\nimport collections\nimport dataclasses\nimport inspect\nimport os\nimport sys\nfrom array import array\nfrom collections import Counter, UserDict, UserList, defaultdict, deque\nfrom dataclasses import dataclass, fields, is_dataclass\nfrom inspect import isclass\nfrom itertools import islice\nfrom types import MappingProxyType\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    DefaultDict,\n    Dict,\n    Iterable,\n    List,\n    Optional,\n    Sequence,\n    Set,\n    Tuple,\n    Union,\n)\n\nfrom pip._vendor.rich.repr import RichReprResult\n\ntry:\n    import attr as _attr_module\n\n    _has_attrs = True\nexcept ImportError:  # pragma: no cover\n    _has_attrs = False\n\nfrom . import get_console\nfrom ._loop import loop_last\nfrom ._pick import pick_bool\nfrom .abc import RichRenderable\nfrom .cells import cell_len\nfrom .highlighter import ReprHighlighter\nfrom .jupyter import JupyterMixin, JupyterRenderable\nfrom .measure import Measurement\nfrom .text import Text\n\nif TYPE_CHECKING:\n    from .console import (\n        Console,\n        ConsoleOptions,\n        HighlighterType,\n        JustifyMethod,\n        OverflowMethod,\n        RenderResult,\n    )\n\n\nJUPYTER_CLASSES_TO_NOT_RENDER = {\n    # Matplotlib \"Artists\" manage their own rendering in a Jupyter notebook, and we should not try to render them too.\n    # \"Typically, all [Matplotlib] visible elements in a figure are subclasses of Artist.\"\n    \"matplotlib.artist.Artist\",\n}\n\n\ndef _is_attr_object(obj: Any) -> bool:\n    \"\"\"Check if an object was created with attrs module.\"\"\"\n    return _has_attrs and _attr_module.has(type(obj))\n\n\ndef _get_attr_fields(obj: Any) -> Sequence[\"_attr_module.Attribute[Any]\"]:\n    \"\"\"Get fields for an attrs object.\"\"\"\n    return _attr_module.fields(type(obj)) if _has_attrs else []\n\n\ndef _is_dataclass_repr(obj: object) -> bool:\n    \"\"\"Check if an instance of a dataclass contains the default repr.\n\n    Args:\n        obj (object): A dataclass instance.\n\n    Returns:\n        bool: True if the default repr is used, False if there is a custom repr.\n    \"\"\"\n    # Digging in to a lot of internals here\n    # Catching all exceptions in case something is missing on a non CPython implementation\n    try:\n        return obj.__repr__.__code__.co_filename == dataclasses.__file__\n    except Exception:  # pragma: no coverage\n        return False\n\n\n_dummy_namedtuple = collections.namedtuple(\"_dummy_namedtuple\", [])\n\n\ndef _has_default_namedtuple_repr(obj: object) -> bool:\n    \"\"\"Check if an instance of namedtuple contains the default repr\n\n    Args:\n        obj (object): A namedtuple\n\n    Returns:\n        bool: True if the default repr is used, False if there's a custom repr.\n    \"\"\"\n    obj_file = None\n    try:\n        obj_file = inspect.getfile(obj.__repr__)\n    except (OSError, TypeError):\n        # OSError handles case where object is defined in __main__ scope, e.g. REPL - no filename available.\n        # TypeError trapped defensively, in case of object without filename slips through.\n        pass\n    default_repr_file = inspect.getfile(_dummy_namedtuple.__repr__)\n    return obj_file == default_repr_file\n\n\ndef _ipy_display_hook(\n    value: Any,\n    console: Optional[\"Console\"] = None,\n    overflow: \"OverflowMethod\" = \"ignore\",\n    crop: bool = False,\n    indent_guides: bool = False,\n    max_length: Optional[int] = None,\n    max_string: Optional[int] = None,\n    expand_all: bool = False,\n) -> None:\n    # needed here to prevent circular import:\n    from ._inspect import is_object_one_of_types\n    from .console import ConsoleRenderable\n\n    # always skip rich generated jupyter renderables or None values\n    if _safe_isinstance(value, JupyterRenderable) or value is None:\n        return\n\n    console = console or get_console()\n    if console.is_jupyter:\n        # Delegate rendering to IPython if the object (and IPython) supports it\n        #  https://ipython.readthedocs.io/en/stable/config/integrating.html#rich-display\n        ipython_repr_methods = [\n            \"_repr_html_\",\n            \"_repr_markdown_\",\n            \"_repr_json_\",\n            \"_repr_latex_\",\n            \"_repr_jpeg_\",\n            \"_repr_png_\",\n            \"_repr_svg_\",\n            \"_repr_mimebundle_\",\n        ]\n        for repr_method in ipython_repr_methods:\n            method = getattr(value, repr_method, None)\n            if inspect.ismethod(method):\n                # Calling the method ourselves isn't ideal. The interface for the `_repr_*_` methods\n                #  specifies that if they return None, then they should not be rendered\n                #  by the notebook.\n                try:\n                    repr_result = method()\n                except Exception:\n                    continue  # If the method raises, treat it as if it doesn't exist, try any others\n                if repr_result is not None:\n                    return  # Delegate rendering to IPython\n\n        # When in a Jupyter notebook let's avoid the display of some specific classes,\n        # as they result in the rendering of useless and noisy lines such as `<Figure size 432x288 with 1 Axes>`.\n        # What does this do?\n        # --> if the class has \"matplotlib.artist.Artist\" in its hierarchy for example, we don't render it.\n        if is_object_one_of_types(value, JUPYTER_CLASSES_TO_NOT_RENDER):\n            return\n\n    # certain renderables should start on a new line\n    if _safe_isinstance(value, ConsoleRenderable):\n        console.line()\n\n    console.print(\n        value\n        if _safe_isinstance(value, RichRenderable)\n        else Pretty(\n            value,\n            overflow=overflow,\n            indent_guides=indent_guides,\n            max_length=max_length,\n            max_string=max_string,\n            expand_all=expand_all,\n            margin=12,\n        ),\n        crop=crop,\n        new_line_start=True,\n    )\n\n\ndef _safe_isinstance(\n    obj: object, class_or_tuple: Union[type, Tuple[type, ...]]\n) -> bool:\n    \"\"\"isinstance can fail in rare cases, for example types with no __class__\"\"\"\n    try:\n        return isinstance(obj, class_or_tuple)\n    except Exception:\n        return False\n\n\ndef install(\n    console: Optional[\"Console\"] = None,\n    overflow: \"OverflowMethod\" = \"ignore\",\n    crop: bool = False,\n    indent_guides: bool = False,\n    max_length: Optional[int] = None,\n    max_string: Optional[int] = None,\n    expand_all: bool = False,\n) -> None:\n    \"\"\"Install automatic pretty printing in the Python REPL.\n\n    Args:\n        console (Console, optional): Console instance or ``None`` to use global console. Defaults to None.\n        overflow (Optional[OverflowMethod], optional): Overflow method. Defaults to \"ignore\".\n        crop (Optional[bool], optional): Enable cropping of long lines. Defaults to False.\n        indent_guides (bool, optional): Enable indentation guides. Defaults to False.\n        max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to None.\n        max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.\n        expand_all (bool, optional): Expand all containers. Defaults to False.\n        max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.\n    \"\"\"\n    from pip._vendor.rich import get_console\n\n    console = console or get_console()\n    assert console is not None\n\n    def display_hook(value: Any) -> None:\n        \"\"\"Replacement sys.displayhook which prettifies objects with Rich.\"\"\"\n        if value is not None:\n            assert console is not None\n            builtins._ = None  # type: ignore[attr-defined]\n            console.print(\n                value\n                if _safe_isinstance(value, RichRenderable)\n                else Pretty(\n                    value,\n                    overflow=overflow,\n                    indent_guides=indent_guides,\n                    max_length=max_length,\n                    max_string=max_string,\n                    expand_all=expand_all,\n                ),\n                crop=crop,\n            )\n            builtins._ = value  # type: ignore[attr-defined]\n\n    try:  # pragma: no cover\n        ip = get_ipython()  # type: ignore[name-defined]\n        from IPython.core.formatters import BaseFormatter\n\n        class RichFormatter(BaseFormatter):  # type: ignore[misc]\n            pprint: bool = True\n\n            def __call__(self, value: Any) -> Any:\n                if self.pprint:\n                    return _ipy_display_hook(\n                        value,\n                        console=get_console(),\n                        overflow=overflow,\n                        indent_guides=indent_guides,\n                        max_length=max_length,\n                        max_string=max_string,\n                        expand_all=expand_all,\n                    )\n                else:\n                    return repr(value)\n\n        # replace plain text formatter with rich formatter\n        rich_formatter = RichFormatter()\n        ip.display_formatter.formatters[\"text/plain\"] = rich_formatter\n    except Exception:\n        sys.displayhook = display_hook\n\n\nclass Pretty(JupyterMixin):\n    \"\"\"A rich renderable that pretty prints an object.\n\n    Args:\n        _object (Any): An object to pretty print.\n        highlighter (HighlighterType, optional): Highlighter object to apply to result, or None for ReprHighlighter. Defaults to None.\n        indent_size (int, optional): Number of spaces in indent. Defaults to 4.\n        justify (JustifyMethod, optional): Justify method, or None for default. Defaults to None.\n        overflow (OverflowMethod, optional): Overflow method, or None for default. Defaults to None.\n        no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to False.\n        indent_guides (bool, optional): Enable indentation guides. Defaults to False.\n        max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to None.\n        max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.\n        max_depth (int, optional): Maximum depth of nested data structures, or None for no maximum. Defaults to None.\n        expand_all (bool, optional): Expand all containers. Defaults to False.\n        margin (int, optional): Subtrace a margin from width to force containers to expand earlier. Defaults to 0.\n        insert_line (bool, optional): Insert a new line if the output has multiple new lines. Defaults to False.\n    \"\"\"\n\n    def __init__(\n        self,\n        _object: Any,\n        highlighter: Optional[\"HighlighterType\"] = None,\n        *,\n        indent_size: int = 4,\n        justify: Optional[\"JustifyMethod\"] = None,\n        overflow: Optional[\"OverflowMethod\"] = None,\n        no_wrap: Optional[bool] = False,\n        indent_guides: bool = False,\n        max_length: Optional[int] = None,\n        max_string: Optional[int] = None,\n        max_depth: Optional[int] = None,\n        expand_all: bool = False,\n        margin: int = 0,\n        insert_line: bool = False,\n    ) -> None:\n        self._object = _object\n        self.highlighter = highlighter or ReprHighlighter()\n        self.indent_size = indent_size\n        self.justify: Optional[\"JustifyMethod\"] = justify\n        self.overflow: Optional[\"OverflowMethod\"] = overflow\n        self.no_wrap = no_wrap\n        self.indent_guides = indent_guides\n        self.max_length = max_length\n        self.max_string = max_string\n        self.max_depth = max_depth\n        self.expand_all = expand_all\n        self.margin = margin\n        self.insert_line = insert_line\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        pretty_str = pretty_repr(\n            self._object,\n            max_width=options.max_width - self.margin,\n            indent_size=self.indent_size,\n            max_length=self.max_length,\n            max_string=self.max_string,\n            max_depth=self.max_depth,\n            expand_all=self.expand_all,\n        )\n        pretty_text = Text(\n            pretty_str,\n            justify=self.justify or options.justify,\n            overflow=self.overflow or options.overflow,\n            no_wrap=pick_bool(self.no_wrap, options.no_wrap),\n            style=\"pretty\",\n        )\n        pretty_text = (\n            self.highlighter(pretty_text)\n            if pretty_text\n            else Text(\n                f\"{type(self._object)}.__repr__ returned empty string\",\n                style=\"dim italic\",\n            )\n        )\n        if self.indent_guides and not options.ascii_only:\n            pretty_text = pretty_text.with_indent_guides(\n                self.indent_size, style=\"repr.indent\"\n            )\n        if self.insert_line and \"\\n\" in pretty_text:\n            yield \"\"\n        yield pretty_text\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        pretty_str = pretty_repr(\n            self._object,\n            max_width=options.max_width,\n            indent_size=self.indent_size,\n            max_length=self.max_length,\n            max_string=self.max_string,\n            expand_all=self.expand_all,\n        )\n        text_width = (\n            max(cell_len(line) for line in pretty_str.splitlines()) if pretty_str else 0\n        )\n        return Measurement(text_width, text_width)\n\n\ndef _get_braces_for_defaultdict(_object: DefaultDict[Any, Any]) -> Tuple[str, str, str]:\n    return (\n        f\"defaultdict({_object.default_factory!r}, {{\",\n        \"})\",\n        f\"defaultdict({_object.default_factory!r}, {{}})\",\n    )\n\n\ndef _get_braces_for_array(_object: \"array[Any]\") -> Tuple[str, str, str]:\n    return (f\"array({_object.typecode!r}, [\", \"])\", f\"array({_object.typecode!r})\")\n\n\n_BRACES: Dict[type, Callable[[Any], Tuple[str, str, str]]] = {\n    os._Environ: lambda _object: (\"environ({\", \"})\", \"environ({})\"),\n    array: _get_braces_for_array,\n    defaultdict: _get_braces_for_defaultdict,\n    Counter: lambda _object: (\"Counter({\", \"})\", \"Counter()\"),\n    deque: lambda _object: (\"deque([\", \"])\", \"deque()\"),\n    dict: lambda _object: (\"{\", \"}\", \"{}\"),\n    UserDict: lambda _object: (\"{\", \"}\", \"{}\"),\n    frozenset: lambda _object: (\"frozenset({\", \"})\", \"frozenset()\"),\n    list: lambda _object: (\"[\", \"]\", \"[]\"),\n    UserList: lambda _object: (\"[\", \"]\", \"[]\"),\n    set: lambda _object: (\"{\", \"}\", \"set()\"),\n    tuple: lambda _object: (\"(\", \")\", \"()\"),\n    MappingProxyType: lambda _object: (\"mappingproxy({\", \"})\", \"mappingproxy({})\"),\n}\n_CONTAINERS = tuple(_BRACES.keys())\n_MAPPING_CONTAINERS = (dict, os._Environ, MappingProxyType, UserDict)\n\n\ndef is_expandable(obj: Any) -> bool:\n    \"\"\"Check if an object may be expanded by pretty print.\"\"\"\n    return (\n        _safe_isinstance(obj, _CONTAINERS)\n        or (is_dataclass(obj))\n        or (hasattr(obj, \"__rich_repr__\"))\n        or _is_attr_object(obj)\n    ) and not isclass(obj)\n\n\n@dataclass\nclass Node:\n    \"\"\"A node in a repr tree. May be atomic or a container.\"\"\"\n\n    key_repr: str = \"\"\n    value_repr: str = \"\"\n    open_brace: str = \"\"\n    close_brace: str = \"\"\n    empty: str = \"\"\n    last: bool = False\n    is_tuple: bool = False\n    is_namedtuple: bool = False\n    children: Optional[List[\"Node\"]] = None\n    key_separator = \": \"\n    separator: str = \", \"\n\n    def iter_tokens(self) -> Iterable[str]:\n        \"\"\"Generate tokens for this node.\"\"\"\n        if self.key_repr:\n            yield self.key_repr\n            yield self.key_separator\n        if self.value_repr:\n            yield self.value_repr\n        elif self.children is not None:\n            if self.children:\n                yield self.open_brace\n                if self.is_tuple and not self.is_namedtuple and len(self.children) == 1:\n                    yield from self.children[0].iter_tokens()\n                    yield \",\"\n                else:\n                    for child in self.children:\n                        yield from child.iter_tokens()\n                        if not child.last:\n                            yield self.separator\n                yield self.close_brace\n            else:\n                yield self.empty\n\n    def check_length(self, start_length: int, max_length: int) -> bool:\n        \"\"\"Check the length fits within a limit.\n\n        Args:\n            start_length (int): Starting length of the line (indent, prefix, suffix).\n            max_length (int): Maximum length.\n\n        Returns:\n            bool: True if the node can be rendered within max length, otherwise False.\n        \"\"\"\n        total_length = start_length\n        for token in self.iter_tokens():\n            total_length += cell_len(token)\n            if total_length > max_length:\n                return False\n        return True\n\n    def __str__(self) -> str:\n        repr_text = \"\".join(self.iter_tokens())\n        return repr_text\n\n    def render(\n        self, max_width: int = 80, indent_size: int = 4, expand_all: bool = False\n    ) -> str:\n        \"\"\"Render the node to a pretty repr.\n\n        Args:\n            max_width (int, optional): Maximum width of the repr. Defaults to 80.\n            indent_size (int, optional): Size of indents. Defaults to 4.\n            expand_all (bool, optional): Expand all levels. Defaults to False.\n\n        Returns:\n            str: A repr string of the original object.\n        \"\"\"\n        lines = [_Line(node=self, is_root=True)]\n        line_no = 0\n        while line_no < len(lines):\n            line = lines[line_no]\n            if line.expandable and not line.expanded:\n                if expand_all or not line.check_length(max_width):\n                    lines[line_no : line_no + 1] = line.expand(indent_size)\n            line_no += 1\n\n        repr_str = \"\\n\".join(str(line) for line in lines)\n        return repr_str\n\n\n@dataclass\nclass _Line:\n    \"\"\"A line in repr output.\"\"\"\n\n    parent: Optional[\"_Line\"] = None\n    is_root: bool = False\n    node: Optional[Node] = None\n    text: str = \"\"\n    suffix: str = \"\"\n    whitespace: str = \"\"\n    expanded: bool = False\n    last: bool = False\n\n    @property\n    def expandable(self) -> bool:\n        \"\"\"Check if the line may be expanded.\"\"\"\n        return bool(self.node is not None and self.node.children)\n\n    def check_length(self, max_length: int) -> bool:\n        \"\"\"Check this line fits within a given number of cells.\"\"\"\n        start_length = (\n            len(self.whitespace) + cell_len(self.text) + cell_len(self.suffix)\n        )\n        assert self.node is not None\n        return self.node.check_length(start_length, max_length)\n\n    def expand(self, indent_size: int) -> Iterable[\"_Line\"]:\n        \"\"\"Expand this line by adding children on their own line.\"\"\"\n        node = self.node\n        assert node is not None\n        whitespace = self.whitespace\n        assert node.children\n        if node.key_repr:\n            new_line = yield _Line(\n                text=f\"{node.key_repr}{node.key_separator}{node.open_brace}\",\n                whitespace=whitespace,\n            )\n        else:\n            new_line = yield _Line(text=node.open_brace, whitespace=whitespace)\n        child_whitespace = self.whitespace + \" \" * indent_size\n        tuple_of_one = node.is_tuple and len(node.children) == 1\n        for last, child in loop_last(node.children):\n            separator = \",\" if tuple_of_one else node.separator\n            line = _Line(\n                parent=new_line,\n                node=child,\n                whitespace=child_whitespace,\n                suffix=separator,\n                last=last and not tuple_of_one,\n            )\n            yield line\n\n        yield _Line(\n            text=node.close_brace,\n            whitespace=whitespace,\n            suffix=self.suffix,\n            last=self.last,\n        )\n\n    def __str__(self) -> str:\n        if self.last:\n            return f\"{self.whitespace}{self.text}{self.node or ''}\"\n        else:\n            return (\n                f\"{self.whitespace}{self.text}{self.node or ''}{self.suffix.rstrip()}\"\n            )\n\n\ndef _is_namedtuple(obj: Any) -> bool:\n    \"\"\"Checks if an object is most likely a namedtuple. It is possible\n    to craft an object that passes this check and isn't a namedtuple, but\n    there is only a minuscule chance of this happening unintentionally.\n\n    Args:\n        obj (Any): The object to test\n\n    Returns:\n        bool: True if the object is a namedtuple. False otherwise.\n    \"\"\"\n    try:\n        fields = getattr(obj, \"_fields\", None)\n    except Exception:\n        # Being very defensive - if we cannot get the attr then its not a namedtuple\n        return False\n    return isinstance(obj, tuple) and isinstance(fields, tuple)\n\n\ndef traverse(\n    _object: Any,\n    max_length: Optional[int] = None,\n    max_string: Optional[int] = None,\n    max_depth: Optional[int] = None,\n) -> Node:\n    \"\"\"Traverse object and generate a tree.\n\n    Args:\n        _object (Any): Object to be traversed.\n        max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to None.\n        max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.\n            Defaults to None.\n        max_depth (int, optional): Maximum depth of data structures, or None for no maximum.\n            Defaults to None.\n\n    Returns:\n        Node: The root of a tree structure which can be used to render a pretty repr.\n    \"\"\"\n\n    def to_repr(obj: Any) -> str:\n        \"\"\"Get repr string for an object, but catch errors.\"\"\"\n        if (\n            max_string is not None\n            and _safe_isinstance(obj, (bytes, str))\n            and len(obj) > max_string\n        ):\n            truncated = len(obj) - max_string\n            obj_repr = f\"{obj[:max_string]!r}+{truncated}\"\n        else:\n            try:\n                obj_repr = repr(obj)\n            except Exception as error:\n                obj_repr = f\"<repr-error {str(error)!r}>\"\n        return obj_repr\n\n    visited_ids: Set[int] = set()\n    push_visited = visited_ids.add\n    pop_visited = visited_ids.remove\n\n    def _traverse(obj: Any, root: bool = False, depth: int = 0) -> Node:\n        \"\"\"Walk the object depth first.\"\"\"\n\n        obj_type = type(obj)\n        py_version = (sys.version_info.major, sys.version_info.minor)\n        children: List[Node]\n        reached_max_depth = max_depth is not None and depth >= max_depth\n\n        def iter_rich_args(rich_args: Any) -> Iterable[Union[Any, Tuple[str, Any]]]:\n            for arg in rich_args:\n                if _safe_isinstance(arg, tuple):\n                    if len(arg) == 3:\n                        key, child, default = arg\n                        if default == child:\n                            continue\n                        yield key, child\n                    elif len(arg) == 2:\n                        key, child = arg\n                        yield key, child\n                    elif len(arg) == 1:\n                        yield arg[0]\n                else:\n                    yield arg\n\n        try:\n            fake_attributes = hasattr(\n                obj, \"awehoi234_wdfjwljet234_234wdfoijsdfmmnxpi492\"\n            )\n        except Exception:\n            fake_attributes = False\n\n        rich_repr_result: Optional[RichReprResult] = None\n        if not fake_attributes:\n            try:\n                if hasattr(obj, \"__rich_repr__\") and not isclass(obj):\n                    rich_repr_result = obj.__rich_repr__()\n            except Exception:\n                pass\n\n        if rich_repr_result is not None:\n            angular = getattr(obj.__rich_repr__, \"angular\", False)\n            args = list(iter_rich_args(rich_repr_result))\n            class_name = obj.__class__.__name__\n\n            if args:\n                children = []\n                append = children.append\n\n                if reached_max_depth:\n                    node = Node(value_repr=f\"...\")\n                else:\n                    if angular:\n                        node = Node(\n                            open_brace=f\"<{class_name} \",\n                            close_brace=\">\",\n                            children=children,\n                            last=root,\n                            separator=\" \",\n                        )\n                    else:\n                        node = Node(\n                            open_brace=f\"{class_name}(\",\n                            close_brace=\")\",\n                            children=children,\n                            last=root,\n                        )\n                    for last, arg in loop_last(args):\n                        if _safe_isinstance(arg, tuple):\n                            key, child = arg\n                            child_node = _traverse(child, depth=depth + 1)\n                            child_node.last = last\n                            child_node.key_repr = key\n                            child_node.key_separator = \"=\"\n                            append(child_node)\n                        else:\n                            child_node = _traverse(arg, depth=depth + 1)\n                            child_node.last = last\n                            append(child_node)\n            else:\n                node = Node(\n                    value_repr=f\"<{class_name}>\" if angular else f\"{class_name}()\",\n                    children=[],\n                    last=root,\n                )\n        elif _is_attr_object(obj) and not fake_attributes:\n            children = []\n            append = children.append\n\n            attr_fields = _get_attr_fields(obj)\n            if attr_fields:\n                if reached_max_depth:\n                    node = Node(value_repr=f\"...\")\n                else:\n                    node = Node(\n                        open_brace=f\"{obj.__class__.__name__}(\",\n                        close_brace=\")\",\n                        children=children,\n                        last=root,\n                    )\n\n                    def iter_attrs() -> Iterable[\n                        Tuple[str, Any, Optional[Callable[[Any], str]]]\n                    ]:\n                        \"\"\"Iterate over attr fields and values.\"\"\"\n                        for attr in attr_fields:\n                            if attr.repr:\n                                try:\n                                    value = getattr(obj, attr.name)\n                                except Exception as error:\n                                    # Can happen, albeit rarely\n                                    yield (attr.name, error, None)\n                                else:\n                                    yield (\n                                        attr.name,\n                                        value,\n                                        attr.repr if callable(attr.repr) else None,\n                                    )\n\n                    for last, (name, value, repr_callable) in loop_last(iter_attrs()):\n                        if repr_callable:\n                            child_node = Node(value_repr=str(repr_callable(value)))\n                        else:\n                            child_node = _traverse(value, depth=depth + 1)\n                        child_node.last = last\n                        child_node.key_repr = name\n                        child_node.key_separator = \"=\"\n                        append(child_node)\n            else:\n                node = Node(\n                    value_repr=f\"{obj.__class__.__name__}()\", children=[], last=root\n                )\n\n        elif (\n            is_dataclass(obj)\n            and not _safe_isinstance(obj, type)\n            and not fake_attributes\n            and (_is_dataclass_repr(obj) or py_version == (3, 6))\n        ):\n            obj_id = id(obj)\n            if obj_id in visited_ids:\n                # Recursion detected\n                return Node(value_repr=\"...\")\n            push_visited(obj_id)\n\n            children = []\n            append = children.append\n            if reached_max_depth:\n                node = Node(value_repr=f\"...\")\n            else:\n                node = Node(\n                    open_brace=f\"{obj.__class__.__name__}(\",\n                    close_brace=\")\",\n                    children=children,\n                    last=root,\n                )\n\n                for last, field in loop_last(\n                    field for field in fields(obj) if field.repr\n                ):\n                    child_node = _traverse(getattr(obj, field.name), depth=depth + 1)\n                    child_node.key_repr = field.name\n                    child_node.last = last\n                    child_node.key_separator = \"=\"\n                    append(child_node)\n\n                pop_visited(obj_id)\n        elif _is_namedtuple(obj) and _has_default_namedtuple_repr(obj):\n            if reached_max_depth:\n                node = Node(value_repr=\"...\")\n            else:\n                children = []\n                class_name = obj.__class__.__name__\n                node = Node(\n                    open_brace=f\"{class_name}(\",\n                    close_brace=\")\",\n                    children=children,\n                    empty=f\"{class_name}()\",\n                )\n                append = children.append\n                for last, (key, value) in loop_last(obj._asdict().items()):\n                    child_node = _traverse(value, depth=depth + 1)\n                    child_node.key_repr = key\n                    child_node.last = last\n                    child_node.key_separator = \"=\"\n                    append(child_node)\n        elif _safe_isinstance(obj, _CONTAINERS):\n            for container_type in _CONTAINERS:\n                if _safe_isinstance(obj, container_type):\n                    obj_type = container_type\n                    break\n\n            obj_id = id(obj)\n            if obj_id in visited_ids:\n                # Recursion detected\n                return Node(value_repr=\"...\")\n            push_visited(obj_id)\n\n            open_brace, close_brace, empty = _BRACES[obj_type](obj)\n\n            if reached_max_depth:\n                node = Node(value_repr=f\"...\", last=root)\n            elif obj_type.__repr__ != type(obj).__repr__:\n                node = Node(value_repr=to_repr(obj), last=root)\n            elif obj:\n                children = []\n                node = Node(\n                    open_brace=open_brace,\n                    close_brace=close_brace,\n                    children=children,\n                    last=root,\n                )\n                append = children.append\n                num_items = len(obj)\n                last_item_index = num_items - 1\n\n                if _safe_isinstance(obj, _MAPPING_CONTAINERS):\n                    iter_items = iter(obj.items())\n                    if max_length is not None:\n                        iter_items = islice(iter_items, max_length)\n                    for index, (key, child) in enumerate(iter_items):\n                        child_node = _traverse(child, depth=depth + 1)\n                        child_node.key_repr = to_repr(key)\n                        child_node.last = index == last_item_index\n                        append(child_node)\n                else:\n                    iter_values = iter(obj)\n                    if max_length is not None:\n                        iter_values = islice(iter_values, max_length)\n                    for index, child in enumerate(iter_values):\n                        child_node = _traverse(child, depth=depth + 1)\n                        child_node.last = index == last_item_index\n                        append(child_node)\n                if max_length is not None and num_items > max_length:\n                    append(Node(value_repr=f\"... +{num_items - max_length}\", last=True))\n            else:\n                node = Node(empty=empty, children=[], last=root)\n\n            pop_visited(obj_id)\n        else:\n            node = Node(value_repr=to_repr(obj), last=root)\n        node.is_tuple = _safe_isinstance(obj, tuple)\n        node.is_namedtuple = _is_namedtuple(obj)\n        return node\n\n    node = _traverse(_object, root=True)\n    return node\n\n\ndef pretty_repr(\n    _object: Any,\n    *,\n    max_width: int = 80,\n    indent_size: int = 4,\n    max_length: Optional[int] = None,\n    max_string: Optional[int] = None,\n    max_depth: Optional[int] = None,\n    expand_all: bool = False,\n) -> str:\n    \"\"\"Prettify repr string by expanding on to new lines to fit within a given width.\n\n    Args:\n        _object (Any): Object to repr.\n        max_width (int, optional): Desired maximum width of repr string. Defaults to 80.\n        indent_size (int, optional): Number of spaces to indent. Defaults to 4.\n        max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to None.\n        max_string (int, optional): Maximum length of string before truncating, or None to disable truncating.\n            Defaults to None.\n        max_depth (int, optional): Maximum depth of nested data structure, or None for no depth.\n            Defaults to None.\n        expand_all (bool, optional): Expand all containers regardless of available width. Defaults to False.\n\n    Returns:\n        str: A possibly multi-line representation of the object.\n    \"\"\"\n\n    if _safe_isinstance(_object, Node):\n        node = _object\n    else:\n        node = traverse(\n            _object, max_length=max_length, max_string=max_string, max_depth=max_depth\n        )\n    repr_str: str = node.render(\n        max_width=max_width, indent_size=indent_size, expand_all=expand_all\n    )\n    return repr_str\n\n\ndef pprint(\n    _object: Any,\n    *,\n    console: Optional[\"Console\"] = None,\n    indent_guides: bool = True,\n    max_length: Optional[int] = None,\n    max_string: Optional[int] = None,\n    max_depth: Optional[int] = None,\n    expand_all: bool = False,\n) -> None:\n    \"\"\"A convenience function for pretty printing.\n\n    Args:\n        _object (Any): Object to pretty print.\n        console (Console, optional): Console instance, or None to use default. Defaults to None.\n        max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to None.\n        max_string (int, optional): Maximum length of strings before truncating, or None to disable. Defaults to None.\n        max_depth (int, optional): Maximum depth for nested data structures, or None for unlimited depth. Defaults to None.\n        indent_guides (bool, optional): Enable indentation guides. Defaults to True.\n        expand_all (bool, optional): Expand all containers. Defaults to False.\n    \"\"\"\n    _console = get_console() if console is None else console\n    _console.print(\n        Pretty(\n            _object,\n            max_length=max_length,\n            max_string=max_string,\n            max_depth=max_depth,\n            indent_guides=indent_guides,\n            expand_all=expand_all,\n            overflow=\"ignore\",\n        ),\n        soft_wrap=True,\n    )\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n\n    class BrokenRepr:\n        def __repr__(self) -> str:\n            1 / 0\n            return \"this will fail\"\n\n    from typing import NamedTuple\n\n    class StockKeepingUnit(NamedTuple):\n        name: str\n        description: str\n        price: float\n        category: str\n        reviews: List[str]\n\n    d = defaultdict(int)\n    d[\"foo\"] = 5\n    data = {\n        \"foo\": [\n            1,\n            \"Hello World!\",\n            100.123,\n            323.232,\n            432324.0,\n            {5, 6, 7, (1, 2, 3, 4), 8},\n        ],\n        \"bar\": frozenset({1, 2, 3}),\n        \"defaultdict\": defaultdict(\n            list, {\"crumble\": [\"apple\", \"rhubarb\", \"butter\", \"sugar\", \"flour\"]}\n        ),\n        \"counter\": Counter(\n            [\n                \"apple\",\n                \"orange\",\n                \"pear\",\n                \"kumquat\",\n                \"kumquat\",\n                \"durian\" * 100,\n            ]\n        ),\n        \"atomic\": (False, True, None),\n        \"namedtuple\": StockKeepingUnit(\n            \"Sparkling British Spring Water\",\n            \"Carbonated spring water\",\n            0.9,\n            \"water\",\n            [\"its amazing!\", \"its terrible!\"],\n        ),\n        \"Broken\": BrokenRepr(),\n    }\n    data[\"foo\"].append(data)  # type: ignore[attr-defined]\n\n    from pip._vendor.rich import print\n\n    print(Pretty(data, indent_guides=True, max_string=20))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/progress.py",
    "content": "import io\nimport sys\nimport typing\nimport warnings\nfrom abc import ABC, abstractmethod\nfrom collections import deque\nfrom collections.abc import Sized\nfrom dataclasses import dataclass, field\nfrom datetime import timedelta\nfrom io import RawIOBase, UnsupportedOperation\nfrom math import ceil\nfrom mmap import mmap\nfrom os import PathLike, stat\nfrom threading import Event, RLock, Thread\nfrom types import TracebackType\nfrom typing import (\n    Any,\n    BinaryIO,\n    Callable,\n    ContextManager,\n    Deque,\n    Dict,\n    Generic,\n    Iterable,\n    List,\n    NamedTuple,\n    NewType,\n    Optional,\n    Sequence,\n    TextIO,\n    Tuple,\n    Type,\n    TypeVar,\n    Union,\n)\n\nif sys.version_info >= (3, 8):\n    from typing import Literal\nelse:\n    from pip._vendor.typing_extensions import Literal  # pragma: no cover\n\nfrom . import filesize, get_console\nfrom .console import Console, Group, JustifyMethod, RenderableType\nfrom .highlighter import Highlighter\nfrom .jupyter import JupyterMixin\nfrom .live import Live\nfrom .progress_bar import ProgressBar\nfrom .spinner import Spinner\nfrom .style import StyleType\nfrom .table import Column, Table\nfrom .text import Text, TextType\n\nTaskID = NewType(\"TaskID\", int)\n\nProgressType = TypeVar(\"ProgressType\")\n\nGetTimeCallable = Callable[[], float]\n\n\n_I = typing.TypeVar(\"_I\", TextIO, BinaryIO)\n\n\nclass _TrackThread(Thread):\n    \"\"\"A thread to periodically update progress.\"\"\"\n\n    def __init__(self, progress: \"Progress\", task_id: \"TaskID\", update_period: float):\n        self.progress = progress\n        self.task_id = task_id\n        self.update_period = update_period\n        self.done = Event()\n\n        self.completed = 0\n        super().__init__()\n\n    def run(self) -> None:\n        task_id = self.task_id\n        advance = self.progress.advance\n        update_period = self.update_period\n        last_completed = 0\n        wait = self.done.wait\n        while not wait(update_period):\n            completed = self.completed\n            if last_completed != completed:\n                advance(task_id, completed - last_completed)\n                last_completed = completed\n\n        self.progress.update(self.task_id, completed=self.completed, refresh=True)\n\n    def __enter__(self) -> \"_TrackThread\":\n        self.start()\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.done.set()\n        self.join()\n\n\ndef track(\n    sequence: Union[Sequence[ProgressType], Iterable[ProgressType]],\n    description: str = \"Working...\",\n    total: Optional[float] = None,\n    auto_refresh: bool = True,\n    console: Optional[Console] = None,\n    transient: bool = False,\n    get_time: Optional[Callable[[], float]] = None,\n    refresh_per_second: float = 10,\n    style: StyleType = \"bar.back\",\n    complete_style: StyleType = \"bar.complete\",\n    finished_style: StyleType = \"bar.finished\",\n    pulse_style: StyleType = \"bar.pulse\",\n    update_period: float = 0.1,\n    disable: bool = False,\n    show_speed: bool = True,\n) -> Iterable[ProgressType]:\n    \"\"\"Track progress by iterating over a sequence.\n\n    Args:\n        sequence (Iterable[ProgressType]): A sequence (must support \"len\") you wish to iterate over.\n        description (str, optional): Description of task show next to progress bar. Defaults to \"Working\".\n        total: (float, optional): Total number of steps. Default is len(sequence).\n        auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.\n        transient: (bool, optional): Clear the progress on exit. Defaults to False.\n        console (Console, optional): Console to write to. Default creates internal Console instance.\n        refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.\n        style (StyleType, optional): Style for the bar background. Defaults to \"bar.back\".\n        complete_style (StyleType, optional): Style for the completed bar. Defaults to \"bar.complete\".\n        finished_style (StyleType, optional): Style for a finished bar. Defaults to \"bar.done\".\n        pulse_style (StyleType, optional): Style for pulsing bars. Defaults to \"bar.pulse\".\n        update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.\n        disable (bool, optional): Disable display of progress.\n        show_speed (bool, optional): Show speed if total isn't known. Defaults to True.\n    Returns:\n        Iterable[ProgressType]: An iterable of the values in the sequence.\n\n    \"\"\"\n\n    columns: List[\"ProgressColumn\"] = (\n        [TextColumn(\"[progress.description]{task.description}\")] if description else []\n    )\n    columns.extend(\n        (\n            BarColumn(\n                style=style,\n                complete_style=complete_style,\n                finished_style=finished_style,\n                pulse_style=pulse_style,\n            ),\n            TaskProgressColumn(show_speed=show_speed),\n            TimeRemainingColumn(),\n        )\n    )\n    progress = Progress(\n        *columns,\n        auto_refresh=auto_refresh,\n        console=console,\n        transient=transient,\n        get_time=get_time,\n        refresh_per_second=refresh_per_second or 10,\n        disable=disable,\n    )\n\n    with progress:\n        yield from progress.track(\n            sequence, total=total, description=description, update_period=update_period\n        )\n\n\nclass _Reader(RawIOBase, BinaryIO):\n    \"\"\"A reader that tracks progress while it's being read from.\"\"\"\n\n    def __init__(\n        self,\n        handle: BinaryIO,\n        progress: \"Progress\",\n        task: TaskID,\n        close_handle: bool = True,\n    ) -> None:\n        self.handle = handle\n        self.progress = progress\n        self.task = task\n        self.close_handle = close_handle\n        self._closed = False\n\n    def __enter__(self) -> \"_Reader\":\n        self.handle.__enter__()\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.close()\n\n    def __iter__(self) -> BinaryIO:\n        return self\n\n    def __next__(self) -> bytes:\n        line = next(self.handle)\n        self.progress.advance(self.task, advance=len(line))\n        return line\n\n    @property\n    def closed(self) -> bool:\n        return self._closed\n\n    def fileno(self) -> int:\n        return self.handle.fileno()\n\n    def isatty(self) -> bool:\n        return self.handle.isatty()\n\n    @property\n    def name(self) -> str:\n        return self.handle.name\n\n    def readable(self) -> bool:\n        return self.handle.readable()\n\n    def seekable(self) -> bool:\n        return self.handle.seekable()\n\n    def writable(self) -> bool:\n        return False\n\n    def read(self, size: int = -1) -> bytes:\n        block = self.handle.read(size)\n        self.progress.advance(self.task, advance=len(block))\n        return block\n\n    def readinto(self, b: Union[bytearray, memoryview, mmap]):  # type: ignore[no-untyped-def, override]\n        n = self.handle.readinto(b)  # type: ignore[attr-defined]\n        self.progress.advance(self.task, advance=n)\n        return n\n\n    def readline(self, size: int = -1) -> bytes:  # type: ignore[override]\n        line = self.handle.readline(size)\n        self.progress.advance(self.task, advance=len(line))\n        return line\n\n    def readlines(self, hint: int = -1) -> List[bytes]:\n        lines = self.handle.readlines(hint)\n        self.progress.advance(self.task, advance=sum(map(len, lines)))\n        return lines\n\n    def close(self) -> None:\n        if self.close_handle:\n            self.handle.close()\n        self._closed = True\n\n    def seek(self, offset: int, whence: int = 0) -> int:\n        pos = self.handle.seek(offset, whence)\n        self.progress.update(self.task, completed=pos)\n        return pos\n\n    def tell(self) -> int:\n        return self.handle.tell()\n\n    def write(self, s: Any) -> int:\n        raise UnsupportedOperation(\"write\")\n\n\nclass _ReadContext(ContextManager[_I], Generic[_I]):\n    \"\"\"A utility class to handle a context for both a reader and a progress.\"\"\"\n\n    def __init__(self, progress: \"Progress\", reader: _I) -> None:\n        self.progress = progress\n        self.reader: _I = reader\n\n    def __enter__(self) -> _I:\n        self.progress.start()\n        return self.reader.__enter__()\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.progress.stop()\n        self.reader.__exit__(exc_type, exc_val, exc_tb)\n\n\ndef wrap_file(\n    file: BinaryIO,\n    total: int,\n    *,\n    description: str = \"Reading...\",\n    auto_refresh: bool = True,\n    console: Optional[Console] = None,\n    transient: bool = False,\n    get_time: Optional[Callable[[], float]] = None,\n    refresh_per_second: float = 10,\n    style: StyleType = \"bar.back\",\n    complete_style: StyleType = \"bar.complete\",\n    finished_style: StyleType = \"bar.finished\",\n    pulse_style: StyleType = \"bar.pulse\",\n    disable: bool = False,\n) -> ContextManager[BinaryIO]:\n    \"\"\"Read bytes from a file while tracking progress.\n\n    Args:\n        file (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.\n        total (int): Total number of bytes to read.\n        description (str, optional): Description of task show next to progress bar. Defaults to \"Reading\".\n        auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.\n        transient: (bool, optional): Clear the progress on exit. Defaults to False.\n        console (Console, optional): Console to write to. Default creates internal Console instance.\n        refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.\n        style (StyleType, optional): Style for the bar background. Defaults to \"bar.back\".\n        complete_style (StyleType, optional): Style for the completed bar. Defaults to \"bar.complete\".\n        finished_style (StyleType, optional): Style for a finished bar. Defaults to \"bar.done\".\n        pulse_style (StyleType, optional): Style for pulsing bars. Defaults to \"bar.pulse\".\n        disable (bool, optional): Disable display of progress.\n    Returns:\n        ContextManager[BinaryIO]: A context manager yielding a progress reader.\n\n    \"\"\"\n\n    columns: List[\"ProgressColumn\"] = (\n        [TextColumn(\"[progress.description]{task.description}\")] if description else []\n    )\n    columns.extend(\n        (\n            BarColumn(\n                style=style,\n                complete_style=complete_style,\n                finished_style=finished_style,\n                pulse_style=pulse_style,\n            ),\n            DownloadColumn(),\n            TimeRemainingColumn(),\n        )\n    )\n    progress = Progress(\n        *columns,\n        auto_refresh=auto_refresh,\n        console=console,\n        transient=transient,\n        get_time=get_time,\n        refresh_per_second=refresh_per_second or 10,\n        disable=disable,\n    )\n\n    reader = progress.wrap_file(file, total=total, description=description)\n    return _ReadContext(progress, reader)\n\n\n@typing.overload\ndef open(\n    file: Union[str, \"PathLike[str]\", bytes],\n    mode: Union[Literal[\"rt\"], Literal[\"r\"]],\n    buffering: int = -1,\n    encoding: Optional[str] = None,\n    errors: Optional[str] = None,\n    newline: Optional[str] = None,\n    *,\n    total: Optional[int] = None,\n    description: str = \"Reading...\",\n    auto_refresh: bool = True,\n    console: Optional[Console] = None,\n    transient: bool = False,\n    get_time: Optional[Callable[[], float]] = None,\n    refresh_per_second: float = 10,\n    style: StyleType = \"bar.back\",\n    complete_style: StyleType = \"bar.complete\",\n    finished_style: StyleType = \"bar.finished\",\n    pulse_style: StyleType = \"bar.pulse\",\n    disable: bool = False,\n) -> ContextManager[TextIO]:\n    pass\n\n\n@typing.overload\ndef open(\n    file: Union[str, \"PathLike[str]\", bytes],\n    mode: Literal[\"rb\"],\n    buffering: int = -1,\n    encoding: Optional[str] = None,\n    errors: Optional[str] = None,\n    newline: Optional[str] = None,\n    *,\n    total: Optional[int] = None,\n    description: str = \"Reading...\",\n    auto_refresh: bool = True,\n    console: Optional[Console] = None,\n    transient: bool = False,\n    get_time: Optional[Callable[[], float]] = None,\n    refresh_per_second: float = 10,\n    style: StyleType = \"bar.back\",\n    complete_style: StyleType = \"bar.complete\",\n    finished_style: StyleType = \"bar.finished\",\n    pulse_style: StyleType = \"bar.pulse\",\n    disable: bool = False,\n) -> ContextManager[BinaryIO]:\n    pass\n\n\ndef open(\n    file: Union[str, \"PathLike[str]\", bytes],\n    mode: Union[Literal[\"rb\"], Literal[\"rt\"], Literal[\"r\"]] = \"r\",\n    buffering: int = -1,\n    encoding: Optional[str] = None,\n    errors: Optional[str] = None,\n    newline: Optional[str] = None,\n    *,\n    total: Optional[int] = None,\n    description: str = \"Reading...\",\n    auto_refresh: bool = True,\n    console: Optional[Console] = None,\n    transient: bool = False,\n    get_time: Optional[Callable[[], float]] = None,\n    refresh_per_second: float = 10,\n    style: StyleType = \"bar.back\",\n    complete_style: StyleType = \"bar.complete\",\n    finished_style: StyleType = \"bar.finished\",\n    pulse_style: StyleType = \"bar.pulse\",\n    disable: bool = False,\n) -> Union[ContextManager[BinaryIO], ContextManager[TextIO]]:\n    \"\"\"Read bytes from a file while tracking progress.\n\n    Args:\n        path (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.\n        mode (str): The mode to use to open the file. Only supports \"r\", \"rb\" or \"rt\".\n        buffering (int): The buffering strategy to use, see :func:`io.open`.\n        encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`.\n        errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`.\n        newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open`\n        total: (int, optional): Total number of bytes to read. Must be provided if reading from a file handle. Default for a path is os.stat(file).st_size.\n        description (str, optional): Description of task show next to progress bar. Defaults to \"Reading\".\n        auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.\n        transient: (bool, optional): Clear the progress on exit. Defaults to False.\n        console (Console, optional): Console to write to. Default creates internal Console instance.\n        refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.\n        style (StyleType, optional): Style for the bar background. Defaults to \"bar.back\".\n        complete_style (StyleType, optional): Style for the completed bar. Defaults to \"bar.complete\".\n        finished_style (StyleType, optional): Style for a finished bar. Defaults to \"bar.done\".\n        pulse_style (StyleType, optional): Style for pulsing bars. Defaults to \"bar.pulse\".\n        disable (bool, optional): Disable display of progress.\n        encoding (str, optional): The encoding to use when reading in text mode.\n\n    Returns:\n        ContextManager[BinaryIO]: A context manager yielding a progress reader.\n\n    \"\"\"\n\n    columns: List[\"ProgressColumn\"] = (\n        [TextColumn(\"[progress.description]{task.description}\")] if description else []\n    )\n    columns.extend(\n        (\n            BarColumn(\n                style=style,\n                complete_style=complete_style,\n                finished_style=finished_style,\n                pulse_style=pulse_style,\n            ),\n            DownloadColumn(),\n            TimeRemainingColumn(),\n        )\n    )\n    progress = Progress(\n        *columns,\n        auto_refresh=auto_refresh,\n        console=console,\n        transient=transient,\n        get_time=get_time,\n        refresh_per_second=refresh_per_second or 10,\n        disable=disable,\n    )\n\n    reader = progress.open(\n        file,\n        mode=mode,\n        buffering=buffering,\n        encoding=encoding,\n        errors=errors,\n        newline=newline,\n        total=total,\n        description=description,\n    )\n    return _ReadContext(progress, reader)  # type: ignore[return-value, type-var]\n\n\nclass ProgressColumn(ABC):\n    \"\"\"Base class for a widget to use in progress display.\"\"\"\n\n    max_refresh: Optional[float] = None\n\n    def __init__(self, table_column: Optional[Column] = None) -> None:\n        self._table_column = table_column\n        self._renderable_cache: Dict[TaskID, Tuple[float, RenderableType]] = {}\n        self._update_time: Optional[float] = None\n\n    def get_table_column(self) -> Column:\n        \"\"\"Get a table column, used to build tasks table.\"\"\"\n        return self._table_column or Column()\n\n    def __call__(self, task: \"Task\") -> RenderableType:\n        \"\"\"Called by the Progress object to return a renderable for the given task.\n\n        Args:\n            task (Task): An object containing information regarding the task.\n\n        Returns:\n            RenderableType: Anything renderable (including str).\n        \"\"\"\n        current_time = task.get_time()\n        if self.max_refresh is not None and not task.completed:\n            try:\n                timestamp, renderable = self._renderable_cache[task.id]\n            except KeyError:\n                pass\n            else:\n                if timestamp + self.max_refresh > current_time:\n                    return renderable\n\n        renderable = self.render(task)\n        self._renderable_cache[task.id] = (current_time, renderable)\n        return renderable\n\n    @abstractmethod\n    def render(self, task: \"Task\") -> RenderableType:\n        \"\"\"Should return a renderable object.\"\"\"\n\n\nclass RenderableColumn(ProgressColumn):\n    \"\"\"A column to insert an arbitrary column.\n\n    Args:\n        renderable (RenderableType, optional): Any renderable. Defaults to empty string.\n    \"\"\"\n\n    def __init__(\n        self, renderable: RenderableType = \"\", *, table_column: Optional[Column] = None\n    ):\n        self.renderable = renderable\n        super().__init__(table_column=table_column)\n\n    def render(self, task: \"Task\") -> RenderableType:\n        return self.renderable\n\n\nclass SpinnerColumn(ProgressColumn):\n    \"\"\"A column with a 'spinner' animation.\n\n    Args:\n        spinner_name (str, optional): Name of spinner animation. Defaults to \"dots\".\n        style (StyleType, optional): Style of spinner. Defaults to \"progress.spinner\".\n        speed (float, optional): Speed factor of spinner. Defaults to 1.0.\n        finished_text (TextType, optional): Text used when task is finished. Defaults to \" \".\n    \"\"\"\n\n    def __init__(\n        self,\n        spinner_name: str = \"dots\",\n        style: Optional[StyleType] = \"progress.spinner\",\n        speed: float = 1.0,\n        finished_text: TextType = \" \",\n        table_column: Optional[Column] = None,\n    ):\n        self.spinner = Spinner(spinner_name, style=style, speed=speed)\n        self.finished_text = (\n            Text.from_markup(finished_text)\n            if isinstance(finished_text, str)\n            else finished_text\n        )\n        super().__init__(table_column=table_column)\n\n    def set_spinner(\n        self,\n        spinner_name: str,\n        spinner_style: Optional[StyleType] = \"progress.spinner\",\n        speed: float = 1.0,\n    ) -> None:\n        \"\"\"Set a new spinner.\n\n        Args:\n            spinner_name (str): Spinner name, see python -m rich.spinner.\n            spinner_style (Optional[StyleType], optional): Spinner style. Defaults to \"progress.spinner\".\n            speed (float, optional): Speed factor of spinner. Defaults to 1.0.\n        \"\"\"\n        self.spinner = Spinner(spinner_name, style=spinner_style, speed=speed)\n\n    def render(self, task: \"Task\") -> RenderableType:\n        text = (\n            self.finished_text\n            if task.finished\n            else self.spinner.render(task.get_time())\n        )\n        return text\n\n\nclass TextColumn(ProgressColumn):\n    \"\"\"A column containing text.\"\"\"\n\n    def __init__(\n        self,\n        text_format: str,\n        style: StyleType = \"none\",\n        justify: JustifyMethod = \"left\",\n        markup: bool = True,\n        highlighter: Optional[Highlighter] = None,\n        table_column: Optional[Column] = None,\n    ) -> None:\n        self.text_format = text_format\n        self.justify: JustifyMethod = justify\n        self.style = style\n        self.markup = markup\n        self.highlighter = highlighter\n        super().__init__(table_column=table_column or Column(no_wrap=True))\n\n    def render(self, task: \"Task\") -> Text:\n        _text = self.text_format.format(task=task)\n        if self.markup:\n            text = Text.from_markup(_text, style=self.style, justify=self.justify)\n        else:\n            text = Text(_text, style=self.style, justify=self.justify)\n        if self.highlighter:\n            self.highlighter.highlight(text)\n        return text\n\n\nclass BarColumn(ProgressColumn):\n    \"\"\"Renders a visual progress bar.\n\n    Args:\n        bar_width (Optional[int], optional): Width of bar or None for full width. Defaults to 40.\n        style (StyleType, optional): Style for the bar background. Defaults to \"bar.back\".\n        complete_style (StyleType, optional): Style for the completed bar. Defaults to \"bar.complete\".\n        finished_style (StyleType, optional): Style for a finished bar. Defaults to \"bar.done\".\n        pulse_style (StyleType, optional): Style for pulsing bars. Defaults to \"bar.pulse\".\n    \"\"\"\n\n    def __init__(\n        self,\n        bar_width: Optional[int] = 40,\n        style: StyleType = \"bar.back\",\n        complete_style: StyleType = \"bar.complete\",\n        finished_style: StyleType = \"bar.finished\",\n        pulse_style: StyleType = \"bar.pulse\",\n        table_column: Optional[Column] = None,\n    ) -> None:\n        self.bar_width = bar_width\n        self.style = style\n        self.complete_style = complete_style\n        self.finished_style = finished_style\n        self.pulse_style = pulse_style\n        super().__init__(table_column=table_column)\n\n    def render(self, task: \"Task\") -> ProgressBar:\n        \"\"\"Gets a progress bar widget for a task.\"\"\"\n        return ProgressBar(\n            total=max(0, task.total) if task.total is not None else None,\n            completed=max(0, task.completed),\n            width=None if self.bar_width is None else max(1, self.bar_width),\n            pulse=not task.started,\n            animation_time=task.get_time(),\n            style=self.style,\n            complete_style=self.complete_style,\n            finished_style=self.finished_style,\n            pulse_style=self.pulse_style,\n        )\n\n\nclass TimeElapsedColumn(ProgressColumn):\n    \"\"\"Renders time elapsed.\"\"\"\n\n    def render(self, task: \"Task\") -> Text:\n        \"\"\"Show time remaining.\"\"\"\n        elapsed = task.finished_time if task.finished else task.elapsed\n        if elapsed is None:\n            return Text(\"-:--:--\", style=\"progress.elapsed\")\n        delta = timedelta(seconds=int(elapsed))\n        return Text(str(delta), style=\"progress.elapsed\")\n\n\nclass TaskProgressColumn(TextColumn):\n    \"\"\"Show task progress as a percentage.\n\n    Args:\n        text_format (str, optional): Format for percentage display. Defaults to \"[progress.percentage]{task.percentage:>3.0f}%\".\n        text_format_no_percentage (str, optional): Format if percentage is unknown. Defaults to \"\".\n        style (StyleType, optional): Style of output. Defaults to \"none\".\n        justify (JustifyMethod, optional): Text justification. Defaults to \"left\".\n        markup (bool, optional): Enable markup. Defaults to True.\n        highlighter (Optional[Highlighter], optional): Highlighter to apply to output. Defaults to None.\n        table_column (Optional[Column], optional): Table Column to use. Defaults to None.\n        show_speed (bool, optional): Show speed if total is unknown. Defaults to False.\n    \"\"\"\n\n    def __init__(\n        self,\n        text_format: str = \"[progress.percentage]{task.percentage:>3.0f}%\",\n        text_format_no_percentage: str = \"\",\n        style: StyleType = \"none\",\n        justify: JustifyMethod = \"left\",\n        markup: bool = True,\n        highlighter: Optional[Highlighter] = None,\n        table_column: Optional[Column] = None,\n        show_speed: bool = False,\n    ) -> None:\n\n        self.text_format_no_percentage = text_format_no_percentage\n        self.show_speed = show_speed\n        super().__init__(\n            text_format=text_format,\n            style=style,\n            justify=justify,\n            markup=markup,\n            highlighter=highlighter,\n            table_column=table_column,\n        )\n\n    @classmethod\n    def render_speed(cls, speed: Optional[float]) -> Text:\n        \"\"\"Render the speed in iterations per second.\n\n        Args:\n            task (Task): A Task object.\n\n        Returns:\n            Text: Text object containing the task speed.\n        \"\"\"\n        if speed is None:\n            return Text(\"\", style=\"progress.percentage\")\n        unit, suffix = filesize.pick_unit_and_suffix(\n            int(speed),\n            [\"\", \"×10³\", \"×10⁶\", \"×10⁹\", \"×10¹²\"],\n            1000,\n        )\n        data_speed = speed / unit\n        return Text(f\"{data_speed:.1f}{suffix} it/s\", style=\"progress.percentage\")\n\n    def render(self, task: \"Task\") -> Text:\n        if task.total is None and self.show_speed:\n            return self.render_speed(task.finished_speed or task.speed)\n        text_format = (\n            self.text_format_no_percentage if task.total is None else self.text_format\n        )\n        _text = text_format.format(task=task)\n        if self.markup:\n            text = Text.from_markup(_text, style=self.style, justify=self.justify)\n        else:\n            text = Text(_text, style=self.style, justify=self.justify)\n        if self.highlighter:\n            self.highlighter.highlight(text)\n        return text\n\n\nclass TimeRemainingColumn(ProgressColumn):\n    \"\"\"Renders estimated time remaining.\n\n    Args:\n        compact (bool, optional): Render MM:SS when time remaining is less than an hour. Defaults to False.\n        elapsed_when_finished (bool, optional): Render time elapsed when the task is finished. Defaults to False.\n    \"\"\"\n\n    # Only refresh twice a second to prevent jitter\n    max_refresh = 0.5\n\n    def __init__(\n        self,\n        compact: bool = False,\n        elapsed_when_finished: bool = False,\n        table_column: Optional[Column] = None,\n    ):\n        self.compact = compact\n        self.elapsed_when_finished = elapsed_when_finished\n        super().__init__(table_column=table_column)\n\n    def render(self, task: \"Task\") -> Text:\n        \"\"\"Show time remaining.\"\"\"\n        if self.elapsed_when_finished and task.finished:\n            task_time = task.finished_time\n            style = \"progress.elapsed\"\n        else:\n            task_time = task.time_remaining\n            style = \"progress.remaining\"\n\n        if task.total is None:\n            return Text(\"\", style=style)\n\n        if task_time is None:\n            return Text(\"--:--\" if self.compact else \"-:--:--\", style=style)\n\n        # Based on https://github.com/tqdm/tqdm/blob/master/tqdm/std.py\n        minutes, seconds = divmod(int(task_time), 60)\n        hours, minutes = divmod(minutes, 60)\n\n        if self.compact and not hours:\n            formatted = f\"{minutes:02d}:{seconds:02d}\"\n        else:\n            formatted = f\"{hours:d}:{minutes:02d}:{seconds:02d}\"\n\n        return Text(formatted, style=style)\n\n\nclass FileSizeColumn(ProgressColumn):\n    \"\"\"Renders completed filesize.\"\"\"\n\n    def render(self, task: \"Task\") -> Text:\n        \"\"\"Show data completed.\"\"\"\n        data_size = filesize.decimal(int(task.completed))\n        return Text(data_size, style=\"progress.filesize\")\n\n\nclass TotalFileSizeColumn(ProgressColumn):\n    \"\"\"Renders total filesize.\"\"\"\n\n    def render(self, task: \"Task\") -> Text:\n        \"\"\"Show data completed.\"\"\"\n        data_size = filesize.decimal(int(task.total)) if task.total is not None else \"\"\n        return Text(data_size, style=\"progress.filesize.total\")\n\n\nclass MofNCompleteColumn(ProgressColumn):\n    \"\"\"Renders completed count/total, e.g. '  10/1000'.\n\n    Best for bounded tasks with int quantities.\n\n    Space pads the completed count so that progress length does not change as task progresses\n    past powers of 10.\n\n    Args:\n        separator (str, optional): Text to separate completed and total values. Defaults to \"/\".\n    \"\"\"\n\n    def __init__(self, separator: str = \"/\", table_column: Optional[Column] = None):\n        self.separator = separator\n        super().__init__(table_column=table_column)\n\n    def render(self, task: \"Task\") -> Text:\n        \"\"\"Show completed/total.\"\"\"\n        completed = int(task.completed)\n        total = int(task.total) if task.total is not None else \"?\"\n        total_width = len(str(total))\n        return Text(\n            f\"{completed:{total_width}d}{self.separator}{total}\",\n            style=\"progress.download\",\n        )\n\n\nclass DownloadColumn(ProgressColumn):\n    \"\"\"Renders file size downloaded and total, e.g. '0.5/2.3 GB'.\n\n    Args:\n        binary_units (bool, optional): Use binary units, KiB, MiB etc. Defaults to False.\n    \"\"\"\n\n    def __init__(\n        self, binary_units: bool = False, table_column: Optional[Column] = None\n    ) -> None:\n        self.binary_units = binary_units\n        super().__init__(table_column=table_column)\n\n    def render(self, task: \"Task\") -> Text:\n        \"\"\"Calculate common unit for completed and total.\"\"\"\n        completed = int(task.completed)\n\n        unit_and_suffix_calculation_base = (\n            int(task.total) if task.total is not None else completed\n        )\n        if self.binary_units:\n            unit, suffix = filesize.pick_unit_and_suffix(\n                unit_and_suffix_calculation_base,\n                [\"bytes\", \"KiB\", \"MiB\", \"GiB\", \"TiB\", \"PiB\", \"EiB\", \"ZiB\", \"YiB\"],\n                1024,\n            )\n        else:\n            unit, suffix = filesize.pick_unit_and_suffix(\n                unit_and_suffix_calculation_base,\n                [\"bytes\", \"kB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\"],\n                1000,\n            )\n        precision = 0 if unit == 1 else 1\n\n        completed_ratio = completed / unit\n        completed_str = f\"{completed_ratio:,.{precision}f}\"\n\n        if task.total is not None:\n            total = int(task.total)\n            total_ratio = total / unit\n            total_str = f\"{total_ratio:,.{precision}f}\"\n        else:\n            total_str = \"?\"\n\n        download_status = f\"{completed_str}/{total_str} {suffix}\"\n        download_text = Text(download_status, style=\"progress.download\")\n        return download_text\n\n\nclass TransferSpeedColumn(ProgressColumn):\n    \"\"\"Renders human readable transfer speed.\"\"\"\n\n    def render(self, task: \"Task\") -> Text:\n        \"\"\"Show data transfer speed.\"\"\"\n        speed = task.finished_speed or task.speed\n        if speed is None:\n            return Text(\"?\", style=\"progress.data.speed\")\n        data_speed = filesize.decimal(int(speed))\n        return Text(f\"{data_speed}/s\", style=\"progress.data.speed\")\n\n\nclass ProgressSample(NamedTuple):\n    \"\"\"Sample of progress for a given time.\"\"\"\n\n    timestamp: float\n    \"\"\"Timestamp of sample.\"\"\"\n    completed: float\n    \"\"\"Number of steps completed.\"\"\"\n\n\n@dataclass\nclass Task:\n    \"\"\"Information regarding a progress task.\n\n    This object should be considered read-only outside of the :class:`~Progress` class.\n\n    \"\"\"\n\n    id: TaskID\n    \"\"\"Task ID associated with this task (used in Progress methods).\"\"\"\n\n    description: str\n    \"\"\"str: Description of the task.\"\"\"\n\n    total: Optional[float]\n    \"\"\"Optional[float]: Total number of steps in this task.\"\"\"\n\n    completed: float\n    \"\"\"float: Number of steps completed\"\"\"\n\n    _get_time: GetTimeCallable\n    \"\"\"Callable to get the current time.\"\"\"\n\n    finished_time: Optional[float] = None\n    \"\"\"float: Time task was finished.\"\"\"\n\n    visible: bool = True\n    \"\"\"bool: Indicates if this task is visible in the progress display.\"\"\"\n\n    fields: Dict[str, Any] = field(default_factory=dict)\n    \"\"\"dict: Arbitrary fields passed in via Progress.update.\"\"\"\n\n    start_time: Optional[float] = field(default=None, init=False, repr=False)\n    \"\"\"Optional[float]: Time this task was started, or None if not started.\"\"\"\n\n    stop_time: Optional[float] = field(default=None, init=False, repr=False)\n    \"\"\"Optional[float]: Time this task was stopped, or None if not stopped.\"\"\"\n\n    finished_speed: Optional[float] = None\n    \"\"\"Optional[float]: The last speed for a finished task.\"\"\"\n\n    _progress: Deque[ProgressSample] = field(\n        default_factory=lambda: deque(maxlen=1000), init=False, repr=False\n    )\n\n    _lock: RLock = field(repr=False, default_factory=RLock)\n    \"\"\"Thread lock.\"\"\"\n\n    def get_time(self) -> float:\n        \"\"\"float: Get the current time, in seconds.\"\"\"\n        return self._get_time()\n\n    @property\n    def started(self) -> bool:\n        \"\"\"bool: Check if the task as started.\"\"\"\n        return self.start_time is not None\n\n    @property\n    def remaining(self) -> Optional[float]:\n        \"\"\"Optional[float]: Get the number of steps remaining, if a non-None total was set.\"\"\"\n        if self.total is None:\n            return None\n        return self.total - self.completed\n\n    @property\n    def elapsed(self) -> Optional[float]:\n        \"\"\"Optional[float]: Time elapsed since task was started, or ``None`` if the task hasn't started.\"\"\"\n        if self.start_time is None:\n            return None\n        if self.stop_time is not None:\n            return self.stop_time - self.start_time\n        return self.get_time() - self.start_time\n\n    @property\n    def finished(self) -> bool:\n        \"\"\"Check if the task has finished.\"\"\"\n        return self.finished_time is not None\n\n    @property\n    def percentage(self) -> float:\n        \"\"\"float: Get progress of task as a percentage. If a None total was set, returns 0\"\"\"\n        if not self.total:\n            return 0.0\n        completed = (self.completed / self.total) * 100.0\n        completed = min(100.0, max(0.0, completed))\n        return completed\n\n    @property\n    def speed(self) -> Optional[float]:\n        \"\"\"Optional[float]: Get the estimated speed in steps per second.\"\"\"\n        if self.start_time is None:\n            return None\n        with self._lock:\n            progress = self._progress\n            if not progress:\n                return None\n            total_time = progress[-1].timestamp - progress[0].timestamp\n            if total_time == 0:\n                return None\n            iter_progress = iter(progress)\n            next(iter_progress)\n            total_completed = sum(sample.completed for sample in iter_progress)\n            speed = total_completed / total_time\n            return speed\n\n    @property\n    def time_remaining(self) -> Optional[float]:\n        \"\"\"Optional[float]: Get estimated time to completion, or ``None`` if no data.\"\"\"\n        if self.finished:\n            return 0.0\n        speed = self.speed\n        if not speed:\n            return None\n        remaining = self.remaining\n        if remaining is None:\n            return None\n        estimate = ceil(remaining / speed)\n        return estimate\n\n    def _reset(self) -> None:\n        \"\"\"Reset progress.\"\"\"\n        self._progress.clear()\n        self.finished_time = None\n        self.finished_speed = None\n\n\nclass Progress(JupyterMixin):\n    \"\"\"Renders an auto-updating progress bar(s).\n\n    Args:\n        console (Console, optional): Optional Console instance. Default will an internal Console instance writing to stdout.\n        auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()`.\n        refresh_per_second (Optional[float], optional): Number of times per second to refresh the progress information or None to use default (10). Defaults to None.\n        speed_estimate_period: (float, optional): Period (in seconds) used to calculate the speed estimate. Defaults to 30.\n        transient: (bool, optional): Clear the progress on exit. Defaults to False.\n        redirect_stdout: (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True.\n        redirect_stderr: (bool, optional): Enable redirection of stderr. Defaults to True.\n        get_time: (Callable, optional): A callable that gets the current time, or None to use Console.get_time. Defaults to None.\n        disable (bool, optional): Disable progress display. Defaults to False\n        expand (bool, optional): Expand tasks table to fit width. Defaults to False.\n    \"\"\"\n\n    def __init__(\n        self,\n        *columns: Union[str, ProgressColumn],\n        console: Optional[Console] = None,\n        auto_refresh: bool = True,\n        refresh_per_second: float = 10,\n        speed_estimate_period: float = 30.0,\n        transient: bool = False,\n        redirect_stdout: bool = True,\n        redirect_stderr: bool = True,\n        get_time: Optional[GetTimeCallable] = None,\n        disable: bool = False,\n        expand: bool = False,\n    ) -> None:\n        assert refresh_per_second > 0, \"refresh_per_second must be > 0\"\n        self._lock = RLock()\n        self.columns = columns or self.get_default_columns()\n        self.speed_estimate_period = speed_estimate_period\n\n        self.disable = disable\n        self.expand = expand\n        self._tasks: Dict[TaskID, Task] = {}\n        self._task_index: TaskID = TaskID(0)\n        self.live = Live(\n            console=console or get_console(),\n            auto_refresh=auto_refresh,\n            refresh_per_second=refresh_per_second,\n            transient=transient,\n            redirect_stdout=redirect_stdout,\n            redirect_stderr=redirect_stderr,\n            get_renderable=self.get_renderable,\n        )\n        self.get_time = get_time or self.console.get_time\n        self.print = self.console.print\n        self.log = self.console.log\n\n    @classmethod\n    def get_default_columns(cls) -> Tuple[ProgressColumn, ...]:\n        \"\"\"Get the default columns used for a new Progress instance:\n           - a text column for the description (TextColumn)\n           - the bar itself (BarColumn)\n           - a text column showing completion percentage (TextColumn)\n           - an estimated-time-remaining column (TimeRemainingColumn)\n        If the Progress instance is created without passing a columns argument,\n        the default columns defined here will be used.\n\n        You can also create a Progress instance using custom columns before\n        and/or after the defaults, as in this example:\n\n            progress = Progress(\n                SpinnerColumn(),\n                *Progress.default_columns(),\n                \"Elapsed:\",\n                TimeElapsedColumn(),\n            )\n\n        This code shows the creation of a Progress display, containing\n        a spinner to the left, the default columns, and a labeled elapsed\n        time column.\n        \"\"\"\n        return (\n            TextColumn(\"[progress.description]{task.description}\"),\n            BarColumn(),\n            TaskProgressColumn(),\n            TimeRemainingColumn(),\n        )\n\n    @property\n    def console(self) -> Console:\n        return self.live.console\n\n    @property\n    def tasks(self) -> List[Task]:\n        \"\"\"Get a list of Task instances.\"\"\"\n        with self._lock:\n            return list(self._tasks.values())\n\n    @property\n    def task_ids(self) -> List[TaskID]:\n        \"\"\"A list of task IDs.\"\"\"\n        with self._lock:\n            return list(self._tasks.keys())\n\n    @property\n    def finished(self) -> bool:\n        \"\"\"Check if all tasks have been completed.\"\"\"\n        with self._lock:\n            if not self._tasks:\n                return True\n            return all(task.finished for task in self._tasks.values())\n\n    def start(self) -> None:\n        \"\"\"Start the progress display.\"\"\"\n        if not self.disable:\n            self.live.start(refresh=True)\n\n    def stop(self) -> None:\n        \"\"\"Stop the progress display.\"\"\"\n        self.live.stop()\n        if not self.console.is_interactive:\n            self.console.print()\n\n    def __enter__(self) -> \"Progress\":\n        self.start()\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.stop()\n\n    def track(\n        self,\n        sequence: Union[Iterable[ProgressType], Sequence[ProgressType]],\n        total: Optional[float] = None,\n        task_id: Optional[TaskID] = None,\n        description: str = \"Working...\",\n        update_period: float = 0.1,\n    ) -> Iterable[ProgressType]:\n        \"\"\"Track progress by iterating over a sequence.\n\n        Args:\n            sequence (Sequence[ProgressType]): A sequence of values you want to iterate over and track progress.\n            total: (float, optional): Total number of steps. Default is len(sequence).\n            task_id: (TaskID): Task to track. Default is new task.\n            description: (str, optional): Description of task, if new task is created.\n            update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.\n\n        Returns:\n            Iterable[ProgressType]: An iterable of values taken from the provided sequence.\n        \"\"\"\n\n        task_total: Optional[float] = None\n        if total is None:\n            if isinstance(sequence, Sized):\n                task_total = float(len(sequence))\n        else:\n            task_total = total\n\n        if task_id is None:\n            task_id = self.add_task(description, total=task_total)\n        else:\n            self.update(task_id, total=task_total)\n\n        if self.live.auto_refresh:\n            with _TrackThread(self, task_id, update_period) as track_thread:\n                for value in sequence:\n                    yield value\n                    track_thread.completed += 1\n        else:\n            advance = self.advance\n            refresh = self.refresh\n            for value in sequence:\n                yield value\n                advance(task_id, 1)\n                refresh()\n\n    def wrap_file(\n        self,\n        file: BinaryIO,\n        total: Optional[int] = None,\n        *,\n        task_id: Optional[TaskID] = None,\n        description: str = \"Reading...\",\n    ) -> BinaryIO:\n        \"\"\"Track progress file reading from a binary file.\n\n        Args:\n            file (BinaryIO): A file-like object opened in binary mode.\n            total (int, optional): Total number of bytes to read. This must be provided unless a task with a total is also given.\n            task_id (TaskID): Task to track. Default is new task.\n            description (str, optional): Description of task, if new task is created.\n\n        Returns:\n            BinaryIO: A readable file-like object in binary mode.\n\n        Raises:\n            ValueError: When no total value can be extracted from the arguments or the task.\n        \"\"\"\n        # attempt to recover the total from the task\n        total_bytes: Optional[float] = None\n        if total is not None:\n            total_bytes = total\n        elif task_id is not None:\n            with self._lock:\n                total_bytes = self._tasks[task_id].total\n        if total_bytes is None:\n            raise ValueError(\n                f\"unable to get the total number of bytes, please specify 'total'\"\n            )\n\n        # update total of task or create new task\n        if task_id is None:\n            task_id = self.add_task(description, total=total_bytes)\n        else:\n            self.update(task_id, total=total_bytes)\n\n        return _Reader(file, self, task_id, close_handle=False)\n\n    @typing.overload\n    def open(\n        self,\n        file: Union[str, \"PathLike[str]\", bytes],\n        mode: Literal[\"rb\"],\n        buffering: int = -1,\n        encoding: Optional[str] = None,\n        errors: Optional[str] = None,\n        newline: Optional[str] = None,\n        *,\n        total: Optional[int] = None,\n        task_id: Optional[TaskID] = None,\n        description: str = \"Reading...\",\n    ) -> BinaryIO:\n        pass\n\n    @typing.overload\n    def open(\n        self,\n        file: Union[str, \"PathLike[str]\", bytes],\n        mode: Union[Literal[\"r\"], Literal[\"rt\"]],\n        buffering: int = -1,\n        encoding: Optional[str] = None,\n        errors: Optional[str] = None,\n        newline: Optional[str] = None,\n        *,\n        total: Optional[int] = None,\n        task_id: Optional[TaskID] = None,\n        description: str = \"Reading...\",\n    ) -> TextIO:\n        pass\n\n    def open(\n        self,\n        file: Union[str, \"PathLike[str]\", bytes],\n        mode: Union[Literal[\"rb\"], Literal[\"rt\"], Literal[\"r\"]] = \"r\",\n        buffering: int = -1,\n        encoding: Optional[str] = None,\n        errors: Optional[str] = None,\n        newline: Optional[str] = None,\n        *,\n        total: Optional[int] = None,\n        task_id: Optional[TaskID] = None,\n        description: str = \"Reading...\",\n    ) -> Union[BinaryIO, TextIO]:\n        \"\"\"Track progress while reading from a binary file.\n\n        Args:\n            path (Union[str, PathLike[str]]): The path to the file to read.\n            mode (str): The mode to use to open the file. Only supports \"r\", \"rb\" or \"rt\".\n            buffering (int): The buffering strategy to use, see :func:`io.open`.\n            encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`.\n            errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`.\n            newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open`.\n            total (int, optional): Total number of bytes to read. If none given, os.stat(path).st_size is used.\n            task_id (TaskID): Task to track. Default is new task.\n            description (str, optional): Description of task, if new task is created.\n\n        Returns:\n            BinaryIO: A readable file-like object in binary mode.\n\n        Raises:\n            ValueError: When an invalid mode is given.\n        \"\"\"\n        # normalize the mode (always rb, rt)\n        _mode = \"\".join(sorted(mode, reverse=False))\n        if _mode not in (\"br\", \"rt\", \"r\"):\n            raise ValueError(\"invalid mode {!r}\".format(mode))\n\n        # patch buffering to provide the same behaviour as the builtin `open`\n        line_buffering = buffering == 1\n        if _mode == \"br\" and buffering == 1:\n            warnings.warn(\n                \"line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used\",\n                RuntimeWarning,\n            )\n            buffering = -1\n        elif _mode == \"rt\" or _mode == \"r\":\n            if buffering == 0:\n                raise ValueError(\"can't have unbuffered text I/O\")\n            elif buffering == 1:\n                buffering = -1\n\n        # attempt to get the total with `os.stat`\n        if total is None:\n            total = stat(file).st_size\n\n        # update total of task or create new task\n        if task_id is None:\n            task_id = self.add_task(description, total=total)\n        else:\n            self.update(task_id, total=total)\n\n        # open the file in binary mode,\n        handle = io.open(file, \"rb\", buffering=buffering)\n        reader = _Reader(handle, self, task_id, close_handle=True)\n\n        # wrap the reader in a `TextIOWrapper` if text mode\n        if mode == \"r\" or mode == \"rt\":\n            return io.TextIOWrapper(\n                reader,\n                encoding=encoding,\n                errors=errors,\n                newline=newline,\n                line_buffering=line_buffering,\n            )\n\n        return reader\n\n    def start_task(self, task_id: TaskID) -> None:\n        \"\"\"Start a task.\n\n        Starts a task (used when calculating elapsed time). You may need to call this manually,\n        if you called ``add_task`` with ``start=False``.\n\n        Args:\n            task_id (TaskID): ID of task.\n        \"\"\"\n        with self._lock:\n            task = self._tasks[task_id]\n            if task.start_time is None:\n                task.start_time = self.get_time()\n\n    def stop_task(self, task_id: TaskID) -> None:\n        \"\"\"Stop a task.\n\n        This will freeze the elapsed time on the task.\n\n        Args:\n            task_id (TaskID): ID of task.\n        \"\"\"\n        with self._lock:\n            task = self._tasks[task_id]\n            current_time = self.get_time()\n            if task.start_time is None:\n                task.start_time = current_time\n            task.stop_time = current_time\n\n    def update(\n        self,\n        task_id: TaskID,\n        *,\n        total: Optional[float] = None,\n        completed: Optional[float] = None,\n        advance: Optional[float] = None,\n        description: Optional[str] = None,\n        visible: Optional[bool] = None,\n        refresh: bool = False,\n        **fields: Any,\n    ) -> None:\n        \"\"\"Update information associated with a task.\n\n        Args:\n            task_id (TaskID): Task id (returned by add_task).\n            total (float, optional): Updates task.total if not None.\n            completed (float, optional): Updates task.completed if not None.\n            advance (float, optional): Add a value to task.completed if not None.\n            description (str, optional): Change task description if not None.\n            visible (bool, optional): Set visible flag if not None.\n            refresh (bool): Force a refresh of progress information. Default is False.\n            **fields (Any): Additional data fields required for rendering.\n        \"\"\"\n        with self._lock:\n            task = self._tasks[task_id]\n            completed_start = task.completed\n\n            if total is not None and total != task.total:\n                task.total = total\n                task._reset()\n            if advance is not None:\n                task.completed += advance\n            if completed is not None:\n                task.completed = completed\n            if description is not None:\n                task.description = description\n            if visible is not None:\n                task.visible = visible\n            task.fields.update(fields)\n            update_completed = task.completed - completed_start\n\n            current_time = self.get_time()\n            old_sample_time = current_time - self.speed_estimate_period\n            _progress = task._progress\n\n            popleft = _progress.popleft\n            while _progress and _progress[0].timestamp < old_sample_time:\n                popleft()\n            if update_completed > 0:\n                _progress.append(ProgressSample(current_time, update_completed))\n            if (\n                task.total is not None\n                and task.completed >= task.total\n                and task.finished_time is None\n            ):\n                task.finished_time = task.elapsed\n\n        if refresh:\n            self.refresh()\n\n    def reset(\n        self,\n        task_id: TaskID,\n        *,\n        start: bool = True,\n        total: Optional[float] = None,\n        completed: int = 0,\n        visible: Optional[bool] = None,\n        description: Optional[str] = None,\n        **fields: Any,\n    ) -> None:\n        \"\"\"Reset a task so completed is 0 and the clock is reset.\n\n        Args:\n            task_id (TaskID): ID of task.\n            start (bool, optional): Start the task after reset. Defaults to True.\n            total (float, optional): New total steps in task, or None to use current total. Defaults to None.\n            completed (int, optional): Number of steps completed. Defaults to 0.\n            visible (bool, optional): Enable display of the task. Defaults to True.\n            description (str, optional): Change task description if not None. Defaults to None.\n            **fields (str): Additional data fields required for rendering.\n        \"\"\"\n        current_time = self.get_time()\n        with self._lock:\n            task = self._tasks[task_id]\n            task._reset()\n            task.start_time = current_time if start else None\n            if total is not None:\n                task.total = total\n            task.completed = completed\n            if visible is not None:\n                task.visible = visible\n            if fields:\n                task.fields = fields\n            if description is not None:\n                task.description = description\n            task.finished_time = None\n        self.refresh()\n\n    def advance(self, task_id: TaskID, advance: float = 1) -> None:\n        \"\"\"Advance task by a number of steps.\n\n        Args:\n            task_id (TaskID): ID of task.\n            advance (float): Number of steps to advance. Default is 1.\n        \"\"\"\n        current_time = self.get_time()\n        with self._lock:\n            task = self._tasks[task_id]\n            completed_start = task.completed\n            task.completed += advance\n            update_completed = task.completed - completed_start\n            old_sample_time = current_time - self.speed_estimate_period\n            _progress = task._progress\n\n            popleft = _progress.popleft\n            while _progress and _progress[0].timestamp < old_sample_time:\n                popleft()\n            while len(_progress) > 1000:\n                popleft()\n            _progress.append(ProgressSample(current_time, update_completed))\n            if (\n                task.total is not None\n                and task.completed >= task.total\n                and task.finished_time is None\n            ):\n                task.finished_time = task.elapsed\n                task.finished_speed = task.speed\n\n    def refresh(self) -> None:\n        \"\"\"Refresh (render) the progress information.\"\"\"\n        if not self.disable and self.live.is_started:\n            self.live.refresh()\n\n    def get_renderable(self) -> RenderableType:\n        \"\"\"Get a renderable for the progress display.\"\"\"\n        renderable = Group(*self.get_renderables())\n        return renderable\n\n    def get_renderables(self) -> Iterable[RenderableType]:\n        \"\"\"Get a number of renderables for the progress display.\"\"\"\n        table = self.make_tasks_table(self.tasks)\n        yield table\n\n    def make_tasks_table(self, tasks: Iterable[Task]) -> Table:\n        \"\"\"Get a table to render the Progress display.\n\n        Args:\n            tasks (Iterable[Task]): An iterable of Task instances, one per row of the table.\n\n        Returns:\n            Table: A table instance.\n        \"\"\"\n        table_columns = (\n            (\n                Column(no_wrap=True)\n                if isinstance(_column, str)\n                else _column.get_table_column().copy()\n            )\n            for _column in self.columns\n        )\n        table = Table.grid(*table_columns, padding=(0, 1), expand=self.expand)\n\n        for task in tasks:\n            if task.visible:\n                table.add_row(\n                    *(\n                        (\n                            column.format(task=task)\n                            if isinstance(column, str)\n                            else column(task)\n                        )\n                        for column in self.columns\n                    )\n                )\n        return table\n\n    def __rich__(self) -> RenderableType:\n        \"\"\"Makes the Progress class itself renderable.\"\"\"\n        with self._lock:\n            return self.get_renderable()\n\n    def add_task(\n        self,\n        description: str,\n        start: bool = True,\n        total: Optional[float] = 100.0,\n        completed: int = 0,\n        visible: bool = True,\n        **fields: Any,\n    ) -> TaskID:\n        \"\"\"Add a new 'task' to the Progress display.\n\n        Args:\n            description (str): A description of the task.\n            start (bool, optional): Start the task immediately (to calculate elapsed time). If set to False,\n                you will need to call `start` manually. Defaults to True.\n            total (float, optional): Number of total steps in the progress if known.\n                Set to None to render a pulsing animation. Defaults to 100.\n            completed (int, optional): Number of steps completed so far. Defaults to 0.\n            visible (bool, optional): Enable display of the task. Defaults to True.\n            **fields (str): Additional data fields required for rendering.\n\n        Returns:\n            TaskID: An ID you can use when calling `update`.\n        \"\"\"\n        with self._lock:\n            task = Task(\n                self._task_index,\n                description,\n                total,\n                completed,\n                visible=visible,\n                fields=fields,\n                _get_time=self.get_time,\n                _lock=self._lock,\n            )\n            self._tasks[self._task_index] = task\n            if start:\n                self.start_task(self._task_index)\n            new_task_index = self._task_index\n            self._task_index = TaskID(int(self._task_index) + 1)\n        self.refresh()\n        return new_task_index\n\n    def remove_task(self, task_id: TaskID) -> None:\n        \"\"\"Delete a task if it exists.\n\n        Args:\n            task_id (TaskID): A task ID.\n\n        \"\"\"\n        with self._lock:\n            del self._tasks[task_id]\n\n\nif __name__ == \"__main__\":  # pragma: no coverage\n\n    import random\n    import time\n\n    from .panel import Panel\n    from .rule import Rule\n    from .syntax import Syntax\n    from .table import Table\n\n    syntax = Syntax(\n        '''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:\n    \"\"\"Iterate and generate a tuple with a flag for last value.\"\"\"\n    iter_values = iter(values)\n    try:\n        previous_value = next(iter_values)\n    except StopIteration:\n        return\n    for value in iter_values:\n        yield False, previous_value\n        previous_value = value\n    yield True, previous_value''',\n        \"python\",\n        line_numbers=True,\n    )\n\n    table = Table(\"foo\", \"bar\", \"baz\")\n    table.add_row(\"1\", \"2\", \"3\")\n\n    progress_renderables = [\n        \"Text may be printed while the progress bars are rendering.\",\n        Panel(\"In fact, [i]any[/i] renderable will work\"),\n        \"Such as [magenta]tables[/]...\",\n        table,\n        \"Pretty printed structures...\",\n        {\"type\": \"example\", \"text\": \"Pretty printed\"},\n        \"Syntax...\",\n        syntax,\n        Rule(\"Give it a try!\"),\n    ]\n\n    from itertools import cycle\n\n    examples = cycle(progress_renderables)\n\n    console = Console(record=True)\n\n    with Progress(\n        SpinnerColumn(),\n        *Progress.get_default_columns(),\n        TimeElapsedColumn(),\n        console=console,\n        transient=False,\n    ) as progress:\n\n        task1 = progress.add_task(\"[red]Downloading\", total=1000)\n        task2 = progress.add_task(\"[green]Processing\", total=1000)\n        task3 = progress.add_task(\"[yellow]Thinking\", total=None)\n\n        while not progress.finished:\n            progress.update(task1, advance=0.5)\n            progress.update(task2, advance=0.3)\n            time.sleep(0.01)\n            if random.randint(0, 100) < 1:\n                progress.log(next(examples))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/progress_bar.py",
    "content": "import math\nfrom functools import lru_cache\nfrom time import monotonic\nfrom typing import Iterable, List, Optional\n\nfrom .color import Color, blend_rgb\nfrom .color_triplet import ColorTriplet\nfrom .console import Console, ConsoleOptions, RenderResult\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .segment import Segment\nfrom .style import Style, StyleType\n\n# Number of characters before 'pulse' animation repeats\nPULSE_SIZE = 20\n\n\nclass ProgressBar(JupyterMixin):\n    \"\"\"Renders a (progress) bar. Used by rich.progress.\n\n    Args:\n        total (float, optional): Number of steps in the bar. Defaults to 100. Set to None to render a pulsing animation.\n        completed (float, optional): Number of steps completed. Defaults to 0.\n        width (int, optional): Width of the bar, or ``None`` for maximum width. Defaults to None.\n        pulse (bool, optional): Enable pulse effect. Defaults to False. Will pulse if a None total was passed.\n        style (StyleType, optional): Style for the bar background. Defaults to \"bar.back\".\n        complete_style (StyleType, optional): Style for the completed bar. Defaults to \"bar.complete\".\n        finished_style (StyleType, optional): Style for a finished bar. Defaults to \"bar.done\".\n        pulse_style (StyleType, optional): Style for pulsing bars. Defaults to \"bar.pulse\".\n        animation_time (Optional[float], optional): Time in seconds to use for animation, or None to use system time.\n    \"\"\"\n\n    def __init__(\n        self,\n        total: Optional[float] = 100.0,\n        completed: float = 0,\n        width: Optional[int] = None,\n        pulse: bool = False,\n        style: StyleType = \"bar.back\",\n        complete_style: StyleType = \"bar.complete\",\n        finished_style: StyleType = \"bar.finished\",\n        pulse_style: StyleType = \"bar.pulse\",\n        animation_time: Optional[float] = None,\n    ):\n        self.total = total\n        self.completed = completed\n        self.width = width\n        self.pulse = pulse\n        self.style = style\n        self.complete_style = complete_style\n        self.finished_style = finished_style\n        self.pulse_style = pulse_style\n        self.animation_time = animation_time\n\n        self._pulse_segments: Optional[List[Segment]] = None\n\n    def __repr__(self) -> str:\n        return f\"<Bar {self.completed!r} of {self.total!r}>\"\n\n    @property\n    def percentage_completed(self) -> Optional[float]:\n        \"\"\"Calculate percentage complete.\"\"\"\n        if self.total is None:\n            return None\n        completed = (self.completed / self.total) * 100.0\n        completed = min(100, max(0.0, completed))\n        return completed\n\n    @lru_cache(maxsize=16)\n    def _get_pulse_segments(\n        self,\n        fore_style: Style,\n        back_style: Style,\n        color_system: str,\n        no_color: bool,\n        ascii: bool = False,\n    ) -> List[Segment]:\n        \"\"\"Get a list of segments to render a pulse animation.\n\n        Returns:\n            List[Segment]: A list of segments, one segment per character.\n        \"\"\"\n        bar = \"-\" if ascii else \"━\"\n        segments: List[Segment] = []\n        if color_system not in (\"standard\", \"eight_bit\", \"truecolor\") or no_color:\n            segments += [Segment(bar, fore_style)] * (PULSE_SIZE // 2)\n            segments += [Segment(\" \" if no_color else bar, back_style)] * (\n                PULSE_SIZE - (PULSE_SIZE // 2)\n            )\n            return segments\n\n        append = segments.append\n        fore_color = (\n            fore_style.color.get_truecolor()\n            if fore_style.color\n            else ColorTriplet(255, 0, 255)\n        )\n        back_color = (\n            back_style.color.get_truecolor()\n            if back_style.color\n            else ColorTriplet(0, 0, 0)\n        )\n        cos = math.cos\n        pi = math.pi\n        _Segment = Segment\n        _Style = Style\n        from_triplet = Color.from_triplet\n\n        for index in range(PULSE_SIZE):\n            position = index / PULSE_SIZE\n            fade = 0.5 + cos((position * pi * 2)) / 2.0\n            color = blend_rgb(fore_color, back_color, cross_fade=fade)\n            append(_Segment(bar, _Style(color=from_triplet(color))))\n        return segments\n\n    def update(self, completed: float, total: Optional[float] = None) -> None:\n        \"\"\"Update progress with new values.\n\n        Args:\n            completed (float): Number of steps completed.\n            total (float, optional): Total number of steps, or ``None`` to not change. Defaults to None.\n        \"\"\"\n        self.completed = completed\n        self.total = total if total is not None else self.total\n\n    def _render_pulse(\n        self, console: Console, width: int, ascii: bool = False\n    ) -> Iterable[Segment]:\n        \"\"\"Renders the pulse animation.\n\n        Args:\n            console (Console): Console instance.\n            width (int): Width in characters of pulse animation.\n\n        Returns:\n            RenderResult: [description]\n\n        Yields:\n            Iterator[Segment]: Segments to render pulse\n        \"\"\"\n        fore_style = console.get_style(self.pulse_style, default=\"white\")\n        back_style = console.get_style(self.style, default=\"black\")\n\n        pulse_segments = self._get_pulse_segments(\n            fore_style, back_style, console.color_system, console.no_color, ascii=ascii\n        )\n        segment_count = len(pulse_segments)\n        current_time = (\n            monotonic() if self.animation_time is None else self.animation_time\n        )\n        segments = pulse_segments * (int(width / segment_count) + 2)\n        offset = int(-current_time * 15) % segment_count\n        segments = segments[offset : offset + width]\n        yield from segments\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n\n        width = min(self.width or options.max_width, options.max_width)\n        ascii = options.legacy_windows or options.ascii_only\n        should_pulse = self.pulse or self.total is None\n        if should_pulse:\n            yield from self._render_pulse(console, width, ascii=ascii)\n            return\n\n        completed: Optional[float] = (\n            min(self.total, max(0, self.completed)) if self.total is not None else None\n        )\n\n        bar = \"-\" if ascii else \"━\"\n        half_bar_right = \" \" if ascii else \"╸\"\n        half_bar_left = \" \" if ascii else \"╺\"\n        complete_halves = (\n            int(width * 2 * completed / self.total)\n            if self.total and completed is not None\n            else width * 2\n        )\n        bar_count = complete_halves // 2\n        half_bar_count = complete_halves % 2\n        style = console.get_style(self.style)\n        is_finished = self.total is None or self.completed >= self.total\n        complete_style = console.get_style(\n            self.finished_style if is_finished else self.complete_style\n        )\n        _Segment = Segment\n        if bar_count:\n            yield _Segment(bar * bar_count, complete_style)\n        if half_bar_count:\n            yield _Segment(half_bar_right * half_bar_count, complete_style)\n\n        if not console.no_color:\n            remaining_bars = width - bar_count - half_bar_count\n            if remaining_bars and console.color_system is not None:\n                if not half_bar_count and bar_count:\n                    yield _Segment(half_bar_left, style)\n                    remaining_bars -= 1\n                if remaining_bars:\n                    yield _Segment(bar * remaining_bars, style)\n\n    def __rich_measure__(\n        self, console: Console, options: ConsoleOptions\n    ) -> Measurement:\n        return (\n            Measurement(self.width, self.width)\n            if self.width is not None\n            else Measurement(4, options.max_width)\n        )\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    console = Console()\n    bar = ProgressBar(width=50, total=100)\n\n    import time\n\n    console.show_cursor(False)\n    for n in range(0, 101, 1):\n        bar.update(n)\n        console.print(bar)\n        console.file.write(\"\\r\")\n        time.sleep(0.05)\n    console.show_cursor(True)\n    console.print()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/prompt.py",
    "content": "from typing import Any, Generic, List, Optional, TextIO, TypeVar, Union, overload\n\nfrom . import get_console\nfrom .console import Console\nfrom .text import Text, TextType\n\nPromptType = TypeVar(\"PromptType\")\nDefaultType = TypeVar(\"DefaultType\")\n\n\nclass PromptError(Exception):\n    \"\"\"Exception base class for prompt related errors.\"\"\"\n\n\nclass InvalidResponse(PromptError):\n    \"\"\"Exception to indicate a response was invalid. Raise this within process_response() to indicate an error\n    and provide an error message.\n\n    Args:\n        message (Union[str, Text]): Error message.\n    \"\"\"\n\n    def __init__(self, message: TextType) -> None:\n        self.message = message\n\n    def __rich__(self) -> TextType:\n        return self.message\n\n\nclass PromptBase(Generic[PromptType]):\n    \"\"\"Ask the user for input until a valid response is received. This is the base class, see one of\n    the concrete classes for examples.\n\n    Args:\n        prompt (TextType, optional): Prompt text. Defaults to \"\".\n        console (Console, optional): A Console instance or None to use global console. Defaults to None.\n        password (bool, optional): Enable password input. Defaults to False.\n        choices (List[str], optional): A list of valid choices. Defaults to None.\n        show_default (bool, optional): Show default in prompt. Defaults to True.\n        show_choices (bool, optional): Show choices in prompt. Defaults to True.\n    \"\"\"\n\n    response_type: type = str\n\n    validate_error_message = \"[prompt.invalid]Please enter a valid value\"\n    illegal_choice_message = (\n        \"[prompt.invalid.choice]Please select one of the available options\"\n    )\n    prompt_suffix = \": \"\n\n    choices: Optional[List[str]] = None\n\n    def __init__(\n        self,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        show_default: bool = True,\n        show_choices: bool = True,\n    ) -> None:\n        self.console = console or get_console()\n        self.prompt = (\n            Text.from_markup(prompt, style=\"prompt\")\n            if isinstance(prompt, str)\n            else prompt\n        )\n        self.password = password\n        if choices is not None:\n            self.choices = choices\n        self.show_default = show_default\n        self.show_choices = show_choices\n\n    @classmethod\n    @overload\n    def ask(\n        cls,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        show_default: bool = True,\n        show_choices: bool = True,\n        default: DefaultType,\n        stream: Optional[TextIO] = None,\n    ) -> Union[DefaultType, PromptType]:\n        ...\n\n    @classmethod\n    @overload\n    def ask(\n        cls,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        show_default: bool = True,\n        show_choices: bool = True,\n        stream: Optional[TextIO] = None,\n    ) -> PromptType:\n        ...\n\n    @classmethod\n    def ask(\n        cls,\n        prompt: TextType = \"\",\n        *,\n        console: Optional[Console] = None,\n        password: bool = False,\n        choices: Optional[List[str]] = None,\n        show_default: bool = True,\n        show_choices: bool = True,\n        default: Any = ...,\n        stream: Optional[TextIO] = None,\n    ) -> Any:\n        \"\"\"Shortcut to construct and run a prompt loop and return the result.\n\n        Example:\n            >>> filename = Prompt.ask(\"Enter a filename\")\n\n        Args:\n            prompt (TextType, optional): Prompt text. Defaults to \"\".\n            console (Console, optional): A Console instance or None to use global console. Defaults to None.\n            password (bool, optional): Enable password input. Defaults to False.\n            choices (List[str], optional): A list of valid choices. Defaults to None.\n            show_default (bool, optional): Show default in prompt. Defaults to True.\n            show_choices (bool, optional): Show choices in prompt. Defaults to True.\n            stream (TextIO, optional): Optional text file open for reading to get input. Defaults to None.\n        \"\"\"\n        _prompt = cls(\n            prompt,\n            console=console,\n            password=password,\n            choices=choices,\n            show_default=show_default,\n            show_choices=show_choices,\n        )\n        return _prompt(default=default, stream=stream)\n\n    def render_default(self, default: DefaultType) -> Text:\n        \"\"\"Turn the supplied default in to a Text instance.\n\n        Args:\n            default (DefaultType): Default value.\n\n        Returns:\n            Text: Text containing rendering of default value.\n        \"\"\"\n        return Text(f\"({default})\", \"prompt.default\")\n\n    def make_prompt(self, default: DefaultType) -> Text:\n        \"\"\"Make prompt text.\n\n        Args:\n            default (DefaultType): Default value.\n\n        Returns:\n            Text: Text to display in prompt.\n        \"\"\"\n        prompt = self.prompt.copy()\n        prompt.end = \"\"\n\n        if self.show_choices and self.choices:\n            _choices = \"/\".join(self.choices)\n            choices = f\"[{_choices}]\"\n            prompt.append(\" \")\n            prompt.append(choices, \"prompt.choices\")\n\n        if (\n            default != ...\n            and self.show_default\n            and isinstance(default, (str, self.response_type))\n        ):\n            prompt.append(\" \")\n            _default = self.render_default(default)\n            prompt.append(_default)\n\n        prompt.append(self.prompt_suffix)\n\n        return prompt\n\n    @classmethod\n    def get_input(\n        cls,\n        console: Console,\n        prompt: TextType,\n        password: bool,\n        stream: Optional[TextIO] = None,\n    ) -> str:\n        \"\"\"Get input from user.\n\n        Args:\n            console (Console): Console instance.\n            prompt (TextType): Prompt text.\n            password (bool): Enable password entry.\n\n        Returns:\n            str: String from user.\n        \"\"\"\n        return console.input(prompt, password=password, stream=stream)\n\n    def check_choice(self, value: str) -> bool:\n        \"\"\"Check value is in the list of valid choices.\n\n        Args:\n            value (str): Value entered by user.\n\n        Returns:\n            bool: True if choice was valid, otherwise False.\n        \"\"\"\n        assert self.choices is not None\n        return value.strip() in self.choices\n\n    def process_response(self, value: str) -> PromptType:\n        \"\"\"Process response from user, convert to prompt type.\n\n        Args:\n            value (str): String typed by user.\n\n        Raises:\n            InvalidResponse: If ``value`` is invalid.\n\n        Returns:\n            PromptType: The value to be returned from ask method.\n        \"\"\"\n        value = value.strip()\n        try:\n            return_value: PromptType = self.response_type(value)\n        except ValueError:\n            raise InvalidResponse(self.validate_error_message)\n\n        if self.choices is not None and not self.check_choice(value):\n            raise InvalidResponse(self.illegal_choice_message)\n\n        return return_value\n\n    def on_validate_error(self, value: str, error: InvalidResponse) -> None:\n        \"\"\"Called to handle validation error.\n\n        Args:\n            value (str): String entered by user.\n            error (InvalidResponse): Exception instance the initiated the error.\n        \"\"\"\n        self.console.print(error)\n\n    def pre_prompt(self) -> None:\n        \"\"\"Hook to display something before the prompt.\"\"\"\n\n    @overload\n    def __call__(self, *, stream: Optional[TextIO] = None) -> PromptType:\n        ...\n\n    @overload\n    def __call__(\n        self, *, default: DefaultType, stream: Optional[TextIO] = None\n    ) -> Union[PromptType, DefaultType]:\n        ...\n\n    def __call__(self, *, default: Any = ..., stream: Optional[TextIO] = None) -> Any:\n        \"\"\"Run the prompt loop.\n\n        Args:\n            default (Any, optional): Optional default value.\n\n        Returns:\n            PromptType: Processed value.\n        \"\"\"\n        while True:\n            self.pre_prompt()\n            prompt = self.make_prompt(default)\n            value = self.get_input(self.console, prompt, self.password, stream=stream)\n            if value == \"\" and default != ...:\n                return default\n            try:\n                return_value = self.process_response(value)\n            except InvalidResponse as error:\n                self.on_validate_error(value, error)\n                continue\n            else:\n                return return_value\n\n\nclass Prompt(PromptBase[str]):\n    \"\"\"A prompt that returns a str.\n\n    Example:\n        >>> name = Prompt.ask(\"Enter your name\")\n\n\n    \"\"\"\n\n    response_type = str\n\n\nclass IntPrompt(PromptBase[int]):\n    \"\"\"A prompt that returns an integer.\n\n    Example:\n        >>> burrito_count = IntPrompt.ask(\"How many burritos do you want to order\")\n\n    \"\"\"\n\n    response_type = int\n    validate_error_message = \"[prompt.invalid]Please enter a valid integer number\"\n\n\nclass FloatPrompt(PromptBase[int]):\n    \"\"\"A prompt that returns a float.\n\n    Example:\n        >>> temperature = FloatPrompt.ask(\"Enter desired temperature\")\n\n    \"\"\"\n\n    response_type = float\n    validate_error_message = \"[prompt.invalid]Please enter a number\"\n\n\nclass Confirm(PromptBase[bool]):\n    \"\"\"A yes / no confirmation prompt.\n\n    Example:\n        >>> if Confirm.ask(\"Continue\"):\n                run_job()\n\n    \"\"\"\n\n    response_type = bool\n    validate_error_message = \"[prompt.invalid]Please enter Y or N\"\n    choices: List[str] = [\"y\", \"n\"]\n\n    def render_default(self, default: DefaultType) -> Text:\n        \"\"\"Render the default as (y) or (n) rather than True/False.\"\"\"\n        yes, no = self.choices\n        return Text(f\"({yes})\" if default else f\"({no})\", style=\"prompt.default\")\n\n    def process_response(self, value: str) -> bool:\n        \"\"\"Convert choices to a bool.\"\"\"\n        value = value.strip().lower()\n        if value not in self.choices:\n            raise InvalidResponse(self.validate_error_message)\n        return value == self.choices[0]\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n\n    from pip._vendor.rich import print\n\n    if Confirm.ask(\"Run [i]prompt[/i] tests?\", default=True):\n        while True:\n            result = IntPrompt.ask(\n                \":rocket: Enter a number between [b]1[/b] and [b]10[/b]\", default=5\n            )\n            if result >= 1 and result <= 10:\n                break\n            print(\":pile_of_poo: [prompt.invalid]Number must be between 1 and 10\")\n        print(f\"number={result}\")\n\n        while True:\n            password = Prompt.ask(\n                \"Please enter a password [cyan](must be at least 5 characters)\",\n                password=True,\n            )\n            if len(password) >= 5:\n                break\n            print(\"[prompt.invalid]password too short\")\n        print(f\"password={password!r}\")\n\n        fruit = Prompt.ask(\"Enter a fruit\", choices=[\"apple\", \"orange\", \"pear\"])\n        print(f\"fruit={fruit!r}\")\n\n    else:\n        print(\"[b]OK :loudly_crying_face:\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/protocol.py",
    "content": "from typing import Any, cast, Set, TYPE_CHECKING\nfrom inspect import isclass\n\nif TYPE_CHECKING:\n    from pip._vendor.rich.console import RenderableType\n\n_GIBBERISH = \"\"\"aihwerij235234ljsdnp34ksodfipwoe234234jlskjdf\"\"\"\n\n\ndef is_renderable(check_object: Any) -> bool:\n    \"\"\"Check if an object may be rendered by Rich.\"\"\"\n    return (\n        isinstance(check_object, str)\n        or hasattr(check_object, \"__rich__\")\n        or hasattr(check_object, \"__rich_console__\")\n    )\n\n\ndef rich_cast(renderable: object) -> \"RenderableType\":\n    \"\"\"Cast an object to a renderable by calling __rich__ if present.\n\n    Args:\n        renderable (object): A potentially renderable object\n\n    Returns:\n        object: The result of recursively calling __rich__.\n    \"\"\"\n    from pip._vendor.rich.console import RenderableType\n\n    rich_visited_set: Set[type] = set()  # Prevent potential infinite loop\n    while hasattr(renderable, \"__rich__\") and not isclass(renderable):\n        # Detect object which claim to have all the attributes\n        if hasattr(renderable, _GIBBERISH):\n            return repr(renderable)\n        cast_method = getattr(renderable, \"__rich__\")\n        renderable = cast_method()\n        renderable_type = type(renderable)\n        if renderable_type in rich_visited_set:\n            break\n        rich_visited_set.add(renderable_type)\n\n    return cast(RenderableType, renderable)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/region.py",
    "content": "from typing import NamedTuple\n\n\nclass Region(NamedTuple):\n    \"\"\"Defines a rectangular region of the screen.\"\"\"\n\n    x: int\n    y: int\n    width: int\n    height: int\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/repr.py",
    "content": "from functools import partial\nimport inspect\nimport sys\n\nfrom typing import (\n    Any,\n    Callable,\n    Iterable,\n    List,\n    Optional,\n    overload,\n    Union,\n    Tuple,\n    Type,\n    TypeVar,\n)\n\n\nT = TypeVar(\"T\")\n\n\nResult = Iterable[Union[Any, Tuple[Any], Tuple[str, Any], Tuple[str, Any, Any]]]\nRichReprResult = Result\n\n\nclass ReprError(Exception):\n    \"\"\"An error occurred when attempting to build a repr.\"\"\"\n\n\n@overload\ndef auto(cls: Optional[Type[T]]) -> Type[T]:\n    ...\n\n\n@overload\ndef auto(*, angular: bool = False) -> Callable[[Type[T]], Type[T]]:\n    ...\n\n\ndef auto(\n    cls: Optional[Type[T]] = None, *, angular: Optional[bool] = None\n) -> Union[Type[T], Callable[[Type[T]], Type[T]]]:\n    \"\"\"Class decorator to create __repr__ from __rich_repr__\"\"\"\n\n    def do_replace(cls: Type[T], angular: Optional[bool] = None) -> Type[T]:\n        def auto_repr(self: T) -> str:\n            \"\"\"Create repr string from __rich_repr__\"\"\"\n            repr_str: List[str] = []\n            append = repr_str.append\n\n            angular: bool = getattr(self.__rich_repr__, \"angular\", False)  # type: ignore[attr-defined]\n            for arg in self.__rich_repr__():  # type: ignore[attr-defined]\n                if isinstance(arg, tuple):\n                    if len(arg) == 1:\n                        append(repr(arg[0]))\n                    else:\n                        key, value, *default = arg\n                        if key is None:\n                            append(repr(value))\n                        else:\n                            if len(default) and default[0] == value:\n                                continue\n                            append(f\"{key}={value!r}\")\n                else:\n                    append(repr(arg))\n            if angular:\n                return f\"<{self.__class__.__name__} {' '.join(repr_str)}>\"\n            else:\n                return f\"{self.__class__.__name__}({', '.join(repr_str)})\"\n\n        def auto_rich_repr(self: Type[T]) -> Result:\n            \"\"\"Auto generate __rich_rep__ from signature of __init__\"\"\"\n            try:\n                signature = inspect.signature(self.__init__)\n                for name, param in signature.parameters.items():\n                    if param.kind == param.POSITIONAL_ONLY:\n                        yield getattr(self, name)\n                    elif param.kind in (\n                        param.POSITIONAL_OR_KEYWORD,\n                        param.KEYWORD_ONLY,\n                    ):\n                        if param.default == param.empty:\n                            yield getattr(self, param.name)\n                        else:\n                            yield param.name, getattr(self, param.name), param.default\n            except Exception as error:\n                raise ReprError(\n                    f\"Failed to auto generate __rich_repr__; {error}\"\n                ) from None\n\n        if not hasattr(cls, \"__rich_repr__\"):\n            auto_rich_repr.__doc__ = \"Build a rich repr\"\n            cls.__rich_repr__ = auto_rich_repr  # type: ignore[attr-defined]\n\n        auto_repr.__doc__ = \"Return repr(self)\"\n        cls.__repr__ = auto_repr  # type: ignore[assignment]\n        if angular is not None:\n            cls.__rich_repr__.angular = angular  # type: ignore[attr-defined]\n        return cls\n\n    if cls is None:\n        return partial(do_replace, angular=angular)\n    else:\n        return do_replace(cls, angular=angular)\n\n\n@overload\ndef rich_repr(cls: Optional[Type[T]]) -> Type[T]:\n    ...\n\n\n@overload\ndef rich_repr(*, angular: bool = False) -> Callable[[Type[T]], Type[T]]:\n    ...\n\n\ndef rich_repr(\n    cls: Optional[Type[T]] = None, *, angular: bool = False\n) -> Union[Type[T], Callable[[Type[T]], Type[T]]]:\n    if cls is None:\n        return auto(angular=angular)\n    else:\n        return auto(cls)\n\n\nif __name__ == \"__main__\":\n\n    @auto\n    class Foo:\n        def __rich_repr__(self) -> Result:\n            yield \"foo\"\n            yield \"bar\", {\"shopping\": [\"eggs\", \"ham\", \"pineapple\"]}\n            yield \"buy\", \"hand sanitizer\"\n\n    foo = Foo()\n    from pip._vendor.rich.console import Console\n\n    console = Console()\n\n    console.rule(\"Standard repr\")\n    console.print(foo)\n\n    console.print(foo, width=60)\n    console.print(foo, width=30)\n\n    console.rule(\"Angular repr\")\n    Foo.__rich_repr__.angular = True  # type: ignore[attr-defined]\n\n    console.print(foo)\n\n    console.print(foo, width=60)\n    console.print(foo, width=30)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/rule.py",
    "content": "from typing import Union\n\nfrom .align import AlignMethod\nfrom .cells import cell_len, set_cell_size\nfrom .console import Console, ConsoleOptions, RenderResult\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .style import Style\nfrom .text import Text\n\n\nclass Rule(JupyterMixin):\n    \"\"\"A console renderable to draw a horizontal rule (line).\n\n    Args:\n        title (Union[str, Text], optional): Text to render in the rule. Defaults to \"\".\n        characters (str, optional): Character(s) used to draw the line. Defaults to \"─\".\n        style (StyleType, optional): Style of Rule. Defaults to \"rule.line\".\n        end (str, optional): Character at end of Rule. defaults to \"\\\\\\\\n\"\n        align (str, optional): How to align the title, one of \"left\", \"center\", or \"right\". Defaults to \"center\".\n    \"\"\"\n\n    def __init__(\n        self,\n        title: Union[str, Text] = \"\",\n        *,\n        characters: str = \"─\",\n        style: Union[str, Style] = \"rule.line\",\n        end: str = \"\\n\",\n        align: AlignMethod = \"center\",\n    ) -> None:\n        if cell_len(characters) < 1:\n            raise ValueError(\n                \"'characters' argument must have a cell width of at least 1\"\n            )\n        if align not in (\"left\", \"center\", \"right\"):\n            raise ValueError(\n                f'invalid value for align, expected \"left\", \"center\", \"right\" (not {align!r})'\n            )\n        self.title = title\n        self.characters = characters\n        self.style = style\n        self.end = end\n        self.align = align\n\n    def __repr__(self) -> str:\n        return f\"Rule({self.title!r}, {self.characters!r})\"\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        width = options.max_width\n\n        # Python3.6 doesn't have an isascii method on str\n        isascii = getattr(str, \"isascii\", None) or (\n            lambda s: all(ord(c) < 128 for c in s)\n        )\n        characters = (\n            \"-\"\n            if (options.ascii_only and not isascii(self.characters))\n            else self.characters\n        )\n\n        chars_len = cell_len(characters)\n        if not self.title:\n            yield self._rule_line(chars_len, width)\n            return\n\n        if isinstance(self.title, Text):\n            title_text = self.title\n        else:\n            title_text = console.render_str(self.title, style=\"rule.text\")\n\n        title_text.plain = title_text.plain.replace(\"\\n\", \" \")\n        title_text.expand_tabs()\n\n        required_space = 4 if self.align == \"center\" else 2\n        truncate_width = max(0, width - required_space)\n        if not truncate_width:\n            yield self._rule_line(chars_len, width)\n            return\n\n        rule_text = Text(end=self.end)\n        if self.align == \"center\":\n            title_text.truncate(truncate_width, overflow=\"ellipsis\")\n            side_width = (width - cell_len(title_text.plain)) // 2\n            left = Text(characters * (side_width // chars_len + 1))\n            left.truncate(side_width - 1)\n            right_length = width - cell_len(left.plain) - cell_len(title_text.plain)\n            right = Text(characters * (side_width // chars_len + 1))\n            right.truncate(right_length)\n            rule_text.append(left.plain + \" \", self.style)\n            rule_text.append(title_text)\n            rule_text.append(\" \" + right.plain, self.style)\n        elif self.align == \"left\":\n            title_text.truncate(truncate_width, overflow=\"ellipsis\")\n            rule_text.append(title_text)\n            rule_text.append(\" \")\n            rule_text.append(characters * (width - rule_text.cell_len), self.style)\n        elif self.align == \"right\":\n            title_text.truncate(truncate_width, overflow=\"ellipsis\")\n            rule_text.append(characters * (width - title_text.cell_len - 1), self.style)\n            rule_text.append(\" \")\n            rule_text.append(title_text)\n\n        rule_text.plain = set_cell_size(rule_text.plain, width)\n        yield rule_text\n\n    def _rule_line(self, chars_len: int, width: int) -> Text:\n        rule_text = Text(self.characters * ((width // chars_len) + 1), self.style)\n        rule_text.truncate(width)\n        rule_text.plain = set_cell_size(rule_text.plain, width)\n        return rule_text\n\n    def __rich_measure__(\n        self, console: Console, options: ConsoleOptions\n    ) -> Measurement:\n        return Measurement(1, 1)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import sys\n\n    from pip._vendor.rich.console import Console\n\n    try:\n        text = sys.argv[1]\n    except IndexError:\n        text = \"Hello, World\"\n    console = Console()\n    console.print(Rule(title=text))\n\n    console = Console()\n    console.print(Rule(\"foo\"), width=4)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/scope.py",
    "content": "from collections.abc import Mapping\nfrom typing import TYPE_CHECKING, Any, Optional, Tuple\n\nfrom .highlighter import ReprHighlighter\nfrom .panel import Panel\nfrom .pretty import Pretty\nfrom .table import Table\nfrom .text import Text, TextType\n\nif TYPE_CHECKING:\n    from .console import ConsoleRenderable\n\n\ndef render_scope(\n    scope: \"Mapping[str, Any]\",\n    *,\n    title: Optional[TextType] = None,\n    sort_keys: bool = True,\n    indent_guides: bool = False,\n    max_length: Optional[int] = None,\n    max_string: Optional[int] = None,\n) -> \"ConsoleRenderable\":\n    \"\"\"Render python variables in a given scope.\n\n    Args:\n        scope (Mapping): A mapping containing variable names and values.\n        title (str, optional): Optional title. Defaults to None.\n        sort_keys (bool, optional): Enable sorting of items. Defaults to True.\n        indent_guides (bool, optional): Enable indentaton guides. Defaults to False.\n        max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to None.\n        max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to None.\n\n    Returns:\n        ConsoleRenderable: A renderable object.\n    \"\"\"\n    highlighter = ReprHighlighter()\n    items_table = Table.grid(padding=(0, 1), expand=False)\n    items_table.add_column(justify=\"right\")\n\n    def sort_items(item: Tuple[str, Any]) -> Tuple[bool, str]:\n        \"\"\"Sort special variables first, then alphabetically.\"\"\"\n        key, _ = item\n        return (not key.startswith(\"__\"), key.lower())\n\n    items = sorted(scope.items(), key=sort_items) if sort_keys else scope.items()\n    for key, value in items:\n        key_text = Text.assemble(\n            (key, \"scope.key.special\" if key.startswith(\"__\") else \"scope.key\"),\n            (\" =\", \"scope.equals\"),\n        )\n        items_table.add_row(\n            key_text,\n            Pretty(\n                value,\n                highlighter=highlighter,\n                indent_guides=indent_guides,\n                max_length=max_length,\n                max_string=max_string,\n            ),\n        )\n    return Panel.fit(\n        items_table,\n        title=title,\n        border_style=\"scope.border\",\n        padding=(0, 1),\n    )\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich import print\n\n    print()\n\n    def test(foo: float, bar: float) -> None:\n        list_of_things = [1, 2, 3, None, 4, True, False, \"Hello World\"]\n        dict_of_things = {\n            \"version\": \"1.1\",\n            \"method\": \"confirmFruitPurchase\",\n            \"params\": [[\"apple\", \"orange\", \"mangoes\", \"pomelo\"], 1.123],\n            \"id\": \"194521489\",\n        }\n        print(render_scope(locals(), title=\"[i]locals\", sort_keys=False))\n\n    test(20.3423, 3.1427)\n    print()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/screen.py",
    "content": "from typing import Optional, TYPE_CHECKING\n\nfrom .segment import Segment\nfrom .style import StyleType\nfrom ._loop import loop_last\n\n\nif TYPE_CHECKING:\n    from .console import (\n        Console,\n        ConsoleOptions,\n        RenderResult,\n        RenderableType,\n        Group,\n    )\n\n\nclass Screen:\n    \"\"\"A renderable that fills the terminal screen and crops excess.\n\n    Args:\n        renderable (RenderableType): Child renderable.\n        style (StyleType, optional): Optional background style. Defaults to None.\n    \"\"\"\n\n    renderable: \"RenderableType\"\n\n    def __init__(\n        self,\n        *renderables: \"RenderableType\",\n        style: Optional[StyleType] = None,\n        application_mode: bool = False,\n    ) -> None:\n        from pip._vendor.rich.console import Group\n\n        self.renderable = Group(*renderables)\n        self.style = style\n        self.application_mode = application_mode\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        width, height = options.size\n        style = console.get_style(self.style) if self.style else None\n        render_options = options.update(width=width, height=height)\n        lines = console.render_lines(\n            self.renderable or \"\", render_options, style=style, pad=True\n        )\n        lines = Segment.set_shape(lines, width, height, style=style)\n        new_line = Segment(\"\\n\\r\") if self.application_mode else Segment.line()\n        for last, line in loop_last(lines):\n            yield from line\n            if not last:\n                yield new_line\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/segment.py",
    "content": "from enum import IntEnum\nfrom functools import lru_cache\nfrom itertools import filterfalse\nfrom logging import getLogger\nfrom operator import attrgetter\nfrom typing import (\n    TYPE_CHECKING,\n    Dict,\n    Iterable,\n    List,\n    NamedTuple,\n    Optional,\n    Sequence,\n    Tuple,\n    Type,\n    Union,\n)\n\nfrom .cells import (\n    _is_single_cell_widths,\n    cached_cell_len,\n    cell_len,\n    get_character_cell_size,\n    set_cell_size,\n)\nfrom .repr import Result, rich_repr\nfrom .style import Style\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderResult\n\nlog = getLogger(\"rich\")\n\n\nclass ControlType(IntEnum):\n    \"\"\"Non-printable control codes which typically translate to ANSI codes.\"\"\"\n\n    BELL = 1\n    CARRIAGE_RETURN = 2\n    HOME = 3\n    CLEAR = 4\n    SHOW_CURSOR = 5\n    HIDE_CURSOR = 6\n    ENABLE_ALT_SCREEN = 7\n    DISABLE_ALT_SCREEN = 8\n    CURSOR_UP = 9\n    CURSOR_DOWN = 10\n    CURSOR_FORWARD = 11\n    CURSOR_BACKWARD = 12\n    CURSOR_MOVE_TO_COLUMN = 13\n    CURSOR_MOVE_TO = 14\n    ERASE_IN_LINE = 15\n    SET_WINDOW_TITLE = 16\n\n\nControlCode = Union[\n    Tuple[ControlType],\n    Tuple[ControlType, Union[int, str]],\n    Tuple[ControlType, int, int],\n]\n\n\n@rich_repr()\nclass Segment(NamedTuple):\n    \"\"\"A piece of text with associated style. Segments are produced by the Console render process and\n    are ultimately converted in to strings to be written to the terminal.\n\n    Args:\n        text (str): A piece of text.\n        style (:class:`~rich.style.Style`, optional): An optional style to apply to the text.\n        control (Tuple[ControlCode], optional): Optional sequence of control codes.\n\n    Attributes:\n        cell_length (int): The cell length of this Segment.\n    \"\"\"\n\n    text: str\n    style: Optional[Style] = None\n    control: Optional[Sequence[ControlCode]] = None\n\n    @property\n    def cell_length(self) -> int:\n        \"\"\"The number of terminal cells required to display self.text.\n\n        Returns:\n            int: A number of cells.\n        \"\"\"\n        text, _style, control = self\n        return 0 if control else cell_len(text)\n\n    def __rich_repr__(self) -> Result:\n        yield self.text\n        if self.control is None:\n            if self.style is not None:\n                yield self.style\n        else:\n            yield self.style\n            yield self.control\n\n    def __bool__(self) -> bool:\n        \"\"\"Check if the segment contains text.\"\"\"\n        return bool(self.text)\n\n    @property\n    def is_control(self) -> bool:\n        \"\"\"Check if the segment contains control codes.\"\"\"\n        return self.control is not None\n\n    @classmethod\n    @lru_cache(1024 * 16)\n    def _split_cells(cls, segment: \"Segment\", cut: int) -> Tuple[\"Segment\", \"Segment\"]:\n\n        text, style, control = segment\n        _Segment = Segment\n\n        cell_length = segment.cell_length\n        if cut >= cell_length:\n            return segment, _Segment(\"\", style, control)\n\n        cell_size = get_character_cell_size\n\n        pos = int((cut / cell_length) * len(text))\n\n        before = text[:pos]\n        cell_pos = cell_len(before)\n        if cell_pos == cut:\n            return (\n                _Segment(before, style, control),\n                _Segment(text[pos:], style, control),\n            )\n        while pos < len(text):\n            char = text[pos]\n            pos += 1\n            cell_pos += cell_size(char)\n            before = text[:pos]\n            if cell_pos == cut:\n                return (\n                    _Segment(before, style, control),\n                    _Segment(text[pos:], style, control),\n                )\n            if cell_pos > cut:\n                return (\n                    _Segment(before[: pos - 1] + \" \", style, control),\n                    _Segment(\" \" + text[pos:], style, control),\n                )\n\n        raise AssertionError(\"Will never reach here\")\n\n    def split_cells(self, cut: int) -> Tuple[\"Segment\", \"Segment\"]:\n        \"\"\"Split segment in to two segments at the specified column.\n\n        If the cut point falls in the middle of a 2-cell wide character then it is replaced\n        by two spaces, to preserve the display width of the parent segment.\n\n        Returns:\n            Tuple[Segment, Segment]: Two segments.\n        \"\"\"\n        text, style, control = self\n\n        if _is_single_cell_widths(text):\n            # Fast path with all 1 cell characters\n            if cut >= len(text):\n                return self, Segment(\"\", style, control)\n            return (\n                Segment(text[:cut], style, control),\n                Segment(text[cut:], style, control),\n            )\n\n        return self._split_cells(self, cut)\n\n    @classmethod\n    def line(cls) -> \"Segment\":\n        \"\"\"Make a new line segment.\"\"\"\n        return cls(\"\\n\")\n\n    @classmethod\n    def apply_style(\n        cls,\n        segments: Iterable[\"Segment\"],\n        style: Optional[Style] = None,\n        post_style: Optional[Style] = None,\n    ) -> Iterable[\"Segment\"]:\n        \"\"\"Apply style(s) to an iterable of segments.\n\n        Returns an iterable of segments where the style is replaced by ``style + segment.style + post_style``.\n\n        Args:\n            segments (Iterable[Segment]): Segments to process.\n            style (Style, optional): Base style. Defaults to None.\n            post_style (Style, optional): Style to apply on top of segment style. Defaults to None.\n\n        Returns:\n            Iterable[Segments]: A new iterable of segments (possibly the same iterable).\n        \"\"\"\n        result_segments = segments\n        if style:\n            apply = style.__add__\n            result_segments = (\n                cls(text, None if control else apply(_style), control)\n                for text, _style, control in result_segments\n            )\n        if post_style:\n            result_segments = (\n                cls(\n                    text,\n                    (\n                        None\n                        if control\n                        else (_style + post_style if _style else post_style)\n                    ),\n                    control,\n                )\n                for text, _style, control in result_segments\n            )\n        return result_segments\n\n    @classmethod\n    def filter_control(\n        cls, segments: Iterable[\"Segment\"], is_control: bool = False\n    ) -> Iterable[\"Segment\"]:\n        \"\"\"Filter segments by ``is_control`` attribute.\n\n        Args:\n            segments (Iterable[Segment]): An iterable of Segment instances.\n            is_control (bool, optional): is_control flag to match in search.\n\n        Returns:\n            Iterable[Segment]: And iterable of Segment instances.\n\n        \"\"\"\n        if is_control:\n            return filter(attrgetter(\"control\"), segments)\n        else:\n            return filterfalse(attrgetter(\"control\"), segments)\n\n    @classmethod\n    def split_lines(cls, segments: Iterable[\"Segment\"]) -> Iterable[List[\"Segment\"]]:\n        \"\"\"Split a sequence of segments in to a list of lines.\n\n        Args:\n            segments (Iterable[Segment]): Segments potentially containing line feeds.\n\n        Yields:\n            Iterable[List[Segment]]: Iterable of segment lists, one per line.\n        \"\"\"\n        line: List[Segment] = []\n        append = line.append\n\n        for segment in segments:\n            if \"\\n\" in segment.text and not segment.control:\n                text, style, _ = segment\n                while text:\n                    _text, new_line, text = text.partition(\"\\n\")\n                    if _text:\n                        append(cls(_text, style))\n                    if new_line:\n                        yield line\n                        line = []\n                        append = line.append\n            else:\n                append(segment)\n        if line:\n            yield line\n\n    @classmethod\n    def split_and_crop_lines(\n        cls,\n        segments: Iterable[\"Segment\"],\n        length: int,\n        style: Optional[Style] = None,\n        pad: bool = True,\n        include_new_lines: bool = True,\n    ) -> Iterable[List[\"Segment\"]]:\n        \"\"\"Split segments in to lines, and crop lines greater than a given length.\n\n        Args:\n            segments (Iterable[Segment]): An iterable of segments, probably\n                generated from console.render.\n            length (int): Desired line length.\n            style (Style, optional): Style to use for any padding.\n            pad (bool): Enable padding of lines that are less than `length`.\n\n        Returns:\n            Iterable[List[Segment]]: An iterable of lines of segments.\n        \"\"\"\n        line: List[Segment] = []\n        append = line.append\n\n        adjust_line_length = cls.adjust_line_length\n        new_line_segment = cls(\"\\n\")\n\n        for segment in segments:\n            if \"\\n\" in segment.text and not segment.control:\n                text, segment_style, _ = segment\n                while text:\n                    _text, new_line, text = text.partition(\"\\n\")\n                    if _text:\n                        append(cls(_text, segment_style))\n                    if new_line:\n                        cropped_line = adjust_line_length(\n                            line, length, style=style, pad=pad\n                        )\n                        if include_new_lines:\n                            cropped_line.append(new_line_segment)\n                        yield cropped_line\n                        del line[:]\n            else:\n                append(segment)\n        if line:\n            yield adjust_line_length(line, length, style=style, pad=pad)\n\n    @classmethod\n    def adjust_line_length(\n        cls,\n        line: List[\"Segment\"],\n        length: int,\n        style: Optional[Style] = None,\n        pad: bool = True,\n    ) -> List[\"Segment\"]:\n        \"\"\"Adjust a line to a given width (cropping or padding as required).\n\n        Args:\n            segments (Iterable[Segment]): A list of segments in a single line.\n            length (int): The desired width of the line.\n            style (Style, optional): The style of padding if used (space on the end). Defaults to None.\n            pad (bool, optional): Pad lines with spaces if they are shorter than `length`. Defaults to True.\n\n        Returns:\n            List[Segment]: A line of segments with the desired length.\n        \"\"\"\n        line_length = sum(segment.cell_length for segment in line)\n        new_line: List[Segment]\n\n        if line_length < length:\n            if pad:\n                new_line = line + [cls(\" \" * (length - line_length), style)]\n            else:\n                new_line = line[:]\n        elif line_length > length:\n            new_line = []\n            append = new_line.append\n            line_length = 0\n            for segment in line:\n                segment_length = segment.cell_length\n                if line_length + segment_length < length or segment.control:\n                    append(segment)\n                    line_length += segment_length\n                else:\n                    text, segment_style, _ = segment\n                    text = set_cell_size(text, length - line_length)\n                    append(cls(text, segment_style))\n                    break\n        else:\n            new_line = line[:]\n        return new_line\n\n    @classmethod\n    def get_line_length(cls, line: List[\"Segment\"]) -> int:\n        \"\"\"Get the length of list of segments.\n\n        Args:\n            line (List[Segment]): A line encoded as a list of Segments (assumes no '\\\\\\\\n' characters),\n\n        Returns:\n            int: The length of the line.\n        \"\"\"\n        _cell_len = cell_len\n        return sum(_cell_len(segment.text) for segment in line)\n\n    @classmethod\n    def get_shape(cls, lines: List[List[\"Segment\"]]) -> Tuple[int, int]:\n        \"\"\"Get the shape (enclosing rectangle) of a list of lines.\n\n        Args:\n            lines (List[List[Segment]]): A list of lines (no '\\\\\\\\n' characters).\n\n        Returns:\n            Tuple[int, int]: Width and height in characters.\n        \"\"\"\n        get_line_length = cls.get_line_length\n        max_width = max(get_line_length(line) for line in lines) if lines else 0\n        return (max_width, len(lines))\n\n    @classmethod\n    def set_shape(\n        cls,\n        lines: List[List[\"Segment\"]],\n        width: int,\n        height: Optional[int] = None,\n        style: Optional[Style] = None,\n        new_lines: bool = False,\n    ) -> List[List[\"Segment\"]]:\n        \"\"\"Set the shape of a list of lines (enclosing rectangle).\n\n        Args:\n            lines (List[List[Segment]]): A list of lines.\n            width (int): Desired width.\n            height (int, optional): Desired height or None for no change.\n            style (Style, optional): Style of any padding added.\n            new_lines (bool, optional): Padded lines should include \"\\n\". Defaults to False.\n\n        Returns:\n            List[List[Segment]]: New list of lines.\n        \"\"\"\n        _height = height or len(lines)\n\n        blank = (\n            [cls(\" \" * width + \"\\n\", style)] if new_lines else [cls(\" \" * width, style)]\n        )\n\n        adjust_line_length = cls.adjust_line_length\n        shaped_lines = lines[:_height]\n        shaped_lines[:] = [\n            adjust_line_length(line, width, style=style) for line in lines\n        ]\n        if len(shaped_lines) < _height:\n            shaped_lines.extend([blank] * (_height - len(shaped_lines)))\n        return shaped_lines\n\n    @classmethod\n    def align_top(\n        cls: Type[\"Segment\"],\n        lines: List[List[\"Segment\"]],\n        width: int,\n        height: int,\n        style: Style,\n        new_lines: bool = False,\n    ) -> List[List[\"Segment\"]]:\n        \"\"\"Aligns lines to top (adds extra lines to bottom as required).\n\n        Args:\n            lines (List[List[Segment]]): A list of lines.\n            width (int): Desired width.\n            height (int, optional): Desired height or None for no change.\n            style (Style): Style of any padding added.\n            new_lines (bool, optional): Padded lines should include \"\\n\". Defaults to False.\n\n        Returns:\n            List[List[Segment]]: New list of lines.\n        \"\"\"\n        extra_lines = height - len(lines)\n        if not extra_lines:\n            return lines[:]\n        lines = lines[:height]\n        blank = cls(\" \" * width + \"\\n\", style) if new_lines else cls(\" \" * width, style)\n        lines = lines + [[blank]] * extra_lines\n        return lines\n\n    @classmethod\n    def align_bottom(\n        cls: Type[\"Segment\"],\n        lines: List[List[\"Segment\"]],\n        width: int,\n        height: int,\n        style: Style,\n        new_lines: bool = False,\n    ) -> List[List[\"Segment\"]]:\n        \"\"\"Aligns render to bottom (adds extra lines above as required).\n\n        Args:\n            lines (List[List[Segment]]): A list of lines.\n            width (int): Desired width.\n            height (int, optional): Desired height or None for no change.\n            style (Style): Style of any padding added. Defaults to None.\n            new_lines (bool, optional): Padded lines should include \"\\n\". Defaults to False.\n\n        Returns:\n            List[List[Segment]]: New list of lines.\n        \"\"\"\n        extra_lines = height - len(lines)\n        if not extra_lines:\n            return lines[:]\n        lines = lines[:height]\n        blank = cls(\" \" * width + \"\\n\", style) if new_lines else cls(\" \" * width, style)\n        lines = [[blank]] * extra_lines + lines\n        return lines\n\n    @classmethod\n    def align_middle(\n        cls: Type[\"Segment\"],\n        lines: List[List[\"Segment\"]],\n        width: int,\n        height: int,\n        style: Style,\n        new_lines: bool = False,\n    ) -> List[List[\"Segment\"]]:\n        \"\"\"Aligns lines to middle (adds extra lines to above and below as required).\n\n        Args:\n            lines (List[List[Segment]]): A list of lines.\n            width (int): Desired width.\n            height (int, optional): Desired height or None for no change.\n            style (Style): Style of any padding added.\n            new_lines (bool, optional): Padded lines should include \"\\n\". Defaults to False.\n\n        Returns:\n            List[List[Segment]]: New list of lines.\n        \"\"\"\n        extra_lines = height - len(lines)\n        if not extra_lines:\n            return lines[:]\n        lines = lines[:height]\n        blank = cls(\" \" * width + \"\\n\", style) if new_lines else cls(\" \" * width, style)\n        top_lines = extra_lines // 2\n        bottom_lines = extra_lines - top_lines\n        lines = [[blank]] * top_lines + lines + [[blank]] * bottom_lines\n        return lines\n\n    @classmethod\n    def simplify(cls, segments: Iterable[\"Segment\"]) -> Iterable[\"Segment\"]:\n        \"\"\"Simplify an iterable of segments by combining contiguous segments with the same style.\n\n        Args:\n            segments (Iterable[Segment]): An iterable of segments.\n\n        Returns:\n            Iterable[Segment]: A possibly smaller iterable of segments that will render the same way.\n        \"\"\"\n        iter_segments = iter(segments)\n        try:\n            last_segment = next(iter_segments)\n        except StopIteration:\n            return\n\n        _Segment = Segment\n        for segment in iter_segments:\n            if last_segment.style == segment.style and not segment.control:\n                last_segment = _Segment(\n                    last_segment.text + segment.text, last_segment.style\n                )\n            else:\n                yield last_segment\n                last_segment = segment\n        yield last_segment\n\n    @classmethod\n    def strip_links(cls, segments: Iterable[\"Segment\"]) -> Iterable[\"Segment\"]:\n        \"\"\"Remove all links from an iterable of styles.\n\n        Args:\n            segments (Iterable[Segment]): An iterable segments.\n\n        Yields:\n            Segment: Segments with link removed.\n        \"\"\"\n        for segment in segments:\n            if segment.control or segment.style is None:\n                yield segment\n            else:\n                text, style, _control = segment\n                yield cls(text, style.update_link(None) if style else None)\n\n    @classmethod\n    def strip_styles(cls, segments: Iterable[\"Segment\"]) -> Iterable[\"Segment\"]:\n        \"\"\"Remove all styles from an iterable of segments.\n\n        Args:\n            segments (Iterable[Segment]): An iterable segments.\n\n        Yields:\n            Segment: Segments with styles replace with None\n        \"\"\"\n        for text, _style, control in segments:\n            yield cls(text, None, control)\n\n    @classmethod\n    def remove_color(cls, segments: Iterable[\"Segment\"]) -> Iterable[\"Segment\"]:\n        \"\"\"Remove all color from an iterable of segments.\n\n        Args:\n            segments (Iterable[Segment]): An iterable segments.\n\n        Yields:\n            Segment: Segments with colorless style.\n        \"\"\"\n\n        cache: Dict[Style, Style] = {}\n        for text, style, control in segments:\n            if style:\n                colorless_style = cache.get(style)\n                if colorless_style is None:\n                    colorless_style = style.without_color\n                    cache[style] = colorless_style\n                yield cls(text, colorless_style, control)\n            else:\n                yield cls(text, None, control)\n\n    @classmethod\n    def divide(\n        cls, segments: Iterable[\"Segment\"], cuts: Iterable[int]\n    ) -> Iterable[List[\"Segment\"]]:\n        \"\"\"Divides an iterable of segments in to portions.\n\n        Args:\n            cuts (Iterable[int]): Cell positions where to divide.\n\n        Yields:\n            [Iterable[List[Segment]]]: An iterable of Segments in List.\n        \"\"\"\n        split_segments: List[\"Segment\"] = []\n        add_segment = split_segments.append\n\n        iter_cuts = iter(cuts)\n\n        while True:\n            cut = next(iter_cuts, -1)\n            if cut == -1:\n                return []\n            if cut != 0:\n                break\n            yield []\n        pos = 0\n\n        segments_clear = split_segments.clear\n        segments_copy = split_segments.copy\n\n        _cell_len = cached_cell_len\n        for segment in segments:\n            text, _style, control = segment\n            while text:\n                end_pos = pos if control else pos + _cell_len(text)\n                if end_pos < cut:\n                    add_segment(segment)\n                    pos = end_pos\n                    break\n\n                if end_pos == cut:\n                    add_segment(segment)\n                    yield segments_copy()\n                    segments_clear()\n                    pos = end_pos\n\n                    cut = next(iter_cuts, -1)\n                    if cut == -1:\n                        if split_segments:\n                            yield segments_copy()\n                        return\n\n                    break\n\n                else:\n                    before, segment = segment.split_cells(cut - pos)\n                    text, _style, control = segment\n                    add_segment(before)\n                    yield segments_copy()\n                    segments_clear()\n                    pos = cut\n\n                cut = next(iter_cuts, -1)\n                if cut == -1:\n                    if split_segments:\n                        yield segments_copy()\n                    return\n\n        yield segments_copy()\n\n\nclass Segments:\n    \"\"\"A simple renderable to render an iterable of segments. This class may be useful if\n    you want to print segments outside of a __rich_console__ method.\n\n    Args:\n        segments (Iterable[Segment]): An iterable of segments.\n        new_lines (bool, optional): Add new lines between segments. Defaults to False.\n    \"\"\"\n\n    def __init__(self, segments: Iterable[Segment], new_lines: bool = False) -> None:\n        self.segments = list(segments)\n        self.new_lines = new_lines\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        if self.new_lines:\n            line = Segment.line()\n            for segment in self.segments:\n                yield segment\n                yield line\n        else:\n            yield from self.segments\n\n\nclass SegmentLines:\n    def __init__(self, lines: Iterable[List[Segment]], new_lines: bool = False) -> None:\n        \"\"\"A simple renderable containing a number of lines of segments. May be used as an intermediate\n        in rendering process.\n\n        Args:\n            lines (Iterable[List[Segment]]): Lists of segments forming lines.\n            new_lines (bool, optional): Insert new lines after each line. Defaults to False.\n        \"\"\"\n        self.lines = list(lines)\n        self.new_lines = new_lines\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        if self.new_lines:\n            new_line = Segment.line()\n            for line in self.lines:\n                yield from line\n                yield new_line\n        else:\n            for line in self.lines:\n                yield from line\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.console import Console\n    from pip._vendor.rich.syntax import Syntax\n    from pip._vendor.rich.text import Text\n\n    code = \"\"\"from rich.console import Console\nconsole = Console()\ntext = Text.from_markup(\"Hello, [bold magenta]World[/]!\")\nconsole.print(text)\"\"\"\n\n    text = Text.from_markup(\"Hello, [bold magenta]World[/]!\")\n\n    console = Console()\n\n    console.rule(\"rich.Segment\")\n    console.print(\n        \"A Segment is the last step in the Rich render process before generating text with ANSI codes.\"\n    )\n    console.print(\"\\nConsider the following code:\\n\")\n    console.print(Syntax(code, \"python\", line_numbers=True))\n    console.print()\n    console.print(\n        \"When you call [b]print()[/b], Rich [i]renders[/i] the object in to the the following:\\n\"\n    )\n    fragments = list(console.render(text))\n    console.print(fragments)\n    console.print()\n    console.print(\"The Segments are then processed to produce the following output:\\n\")\n    console.print(text)\n    console.print(\n        \"\\nYou will only need to know this if you are implementing your own Rich renderables.\"\n    )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/spinner.py",
    "content": "from typing import cast, List, Optional, TYPE_CHECKING, Union\n\nfrom ._spinners import SPINNERS\nfrom .measure import Measurement\nfrom .table import Table\nfrom .text import Text\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderResult, RenderableType\n    from .style import StyleType\n\n\nclass Spinner:\n    def __init__(\n        self,\n        name: str,\n        text: \"RenderableType\" = \"\",\n        *,\n        style: Optional[\"StyleType\"] = None,\n        speed: float = 1.0,\n    ) -> None:\n        \"\"\"A spinner animation.\n\n        Args:\n            name (str): Name of spinner (run python -m rich.spinner).\n            text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to \"\".\n            style (StyleType, optional): Style for spinner animation. Defaults to None.\n            speed (float, optional): Speed factor for animation. Defaults to 1.0.\n\n        Raises:\n            KeyError: If name isn't one of the supported spinner animations.\n        \"\"\"\n        try:\n            spinner = SPINNERS[name]\n        except KeyError:\n            raise KeyError(f\"no spinner called {name!r}\")\n        self.text: \"Union[RenderableType, Text]\" = (\n            Text.from_markup(text) if isinstance(text, str) else text\n        )\n        self.frames = cast(List[str], spinner[\"frames\"])[:]\n        self.interval = cast(float, spinner[\"interval\"])\n        self.start_time: Optional[float] = None\n        self.style = style\n        self.speed = speed\n        self.frame_no_offset: float = 0.0\n        self._update_speed = 0.0\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        yield self.render(console.get_time())\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Measurement:\n        text = self.render(0)\n        return Measurement.get(console, options, text)\n\n    def render(self, time: float) -> \"RenderableType\":\n        \"\"\"Render the spinner for a given time.\n\n        Args:\n            time (float): Time in seconds.\n\n        Returns:\n            RenderableType: A renderable containing animation frame.\n        \"\"\"\n        if self.start_time is None:\n            self.start_time = time\n\n        frame_no = ((time - self.start_time) * self.speed) / (\n            self.interval / 1000.0\n        ) + self.frame_no_offset\n        frame = Text(\n            self.frames[int(frame_no) % len(self.frames)], style=self.style or \"\"\n        )\n\n        if self._update_speed:\n            self.frame_no_offset = frame_no\n            self.start_time = time\n            self.speed = self._update_speed\n            self._update_speed = 0.0\n\n        if not self.text:\n            return frame\n        elif isinstance(self.text, (str, Text)):\n            return Text.assemble(frame, \" \", self.text)\n        else:\n            table = Table.grid(padding=1)\n            table.add_row(frame, self.text)\n            return table\n\n    def update(\n        self,\n        *,\n        text: \"RenderableType\" = \"\",\n        style: Optional[\"StyleType\"] = None,\n        speed: Optional[float] = None,\n    ) -> None:\n        \"\"\"Updates attributes of a spinner after it has been started.\n\n        Args:\n            text (RenderableType, optional): A renderable to display at the right of the spinner (str or Text typically). Defaults to \"\".\n            style (StyleType, optional): Style for spinner animation. Defaults to None.\n            speed (float, optional): Speed factor for animation. Defaults to None.\n        \"\"\"\n        if text:\n            self.text = Text.from_markup(text) if isinstance(text, str) else text\n        if style:\n            self.style = style\n        if speed:\n            self._update_speed = speed\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from time import sleep\n\n    from .columns import Columns\n    from .panel import Panel\n    from .live import Live\n\n    all_spinners = Columns(\n        [\n            Spinner(spinner_name, text=Text(repr(spinner_name), style=\"green\"))\n            for spinner_name in sorted(SPINNERS.keys())\n        ],\n        column_first=True,\n        expand=True,\n    )\n\n    with Live(\n        Panel(all_spinners, title=\"Spinners\", border_style=\"blue\"),\n        refresh_per_second=20,\n    ) as live:\n        while True:\n            sleep(0.1)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/status.py",
    "content": "from types import TracebackType\nfrom typing import Optional, Type\n\nfrom .console import Console, RenderableType\nfrom .jupyter import JupyterMixin\nfrom .live import Live\nfrom .spinner import Spinner\nfrom .style import StyleType\n\n\nclass Status(JupyterMixin):\n    \"\"\"Displays a status indicator with a 'spinner' animation.\n\n    Args:\n        status (RenderableType): A status renderable (str or Text typically).\n        console (Console, optional): Console instance to use, or None for global console. Defaults to None.\n        spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to \"dots\".\n        spinner_style (StyleType, optional): Style of spinner. Defaults to \"status.spinner\".\n        speed (float, optional): Speed factor for spinner animation. Defaults to 1.0.\n        refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5.\n    \"\"\"\n\n    def __init__(\n        self,\n        status: RenderableType,\n        *,\n        console: Optional[Console] = None,\n        spinner: str = \"dots\",\n        spinner_style: StyleType = \"status.spinner\",\n        speed: float = 1.0,\n        refresh_per_second: float = 12.5,\n    ):\n        self.status = status\n        self.spinner_style = spinner_style\n        self.speed = speed\n        self._spinner = Spinner(spinner, text=status, style=spinner_style, speed=speed)\n        self._live = Live(\n            self.renderable,\n            console=console,\n            refresh_per_second=refresh_per_second,\n            transient=True,\n        )\n\n    @property\n    def renderable(self) -> Spinner:\n        return self._spinner\n\n    @property\n    def console(self) -> \"Console\":\n        \"\"\"Get the Console used by the Status objects.\"\"\"\n        return self._live.console\n\n    def update(\n        self,\n        status: Optional[RenderableType] = None,\n        *,\n        spinner: Optional[str] = None,\n        spinner_style: Optional[StyleType] = None,\n        speed: Optional[float] = None,\n    ) -> None:\n        \"\"\"Update status.\n\n        Args:\n            status (Optional[RenderableType], optional): New status renderable or None for no change. Defaults to None.\n            spinner (Optional[str], optional): New spinner or None for no change. Defaults to None.\n            spinner_style (Optional[StyleType], optional): New spinner style or None for no change. Defaults to None.\n            speed (Optional[float], optional): Speed factor for spinner animation or None for no change. Defaults to None.\n        \"\"\"\n        if status is not None:\n            self.status = status\n        if spinner_style is not None:\n            self.spinner_style = spinner_style\n        if speed is not None:\n            self.speed = speed\n        if spinner is not None:\n            self._spinner = Spinner(\n                spinner, text=self.status, style=self.spinner_style, speed=self.speed\n            )\n            self._live.update(self.renderable, refresh=True)\n        else:\n            self._spinner.update(\n                text=self.status, style=self.spinner_style, speed=self.speed\n            )\n\n    def start(self) -> None:\n        \"\"\"Start the status animation.\"\"\"\n        self._live.start()\n\n    def stop(self) -> None:\n        \"\"\"Stop the spinner animation.\"\"\"\n        self._live.stop()\n\n    def __rich__(self) -> RenderableType:\n        return self.renderable\n\n    def __enter__(self) -> \"Status\":\n        self.start()\n        return self\n\n    def __exit__(\n        self,\n        exc_type: Optional[Type[BaseException]],\n        exc_val: Optional[BaseException],\n        exc_tb: Optional[TracebackType],\n    ) -> None:\n        self.stop()\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n\n    from time import sleep\n\n    from .console import Console\n\n    console = Console()\n    with console.status(\"[magenta]Covid detector booting up\") as status:\n        sleep(3)\n        console.log(\"Importing advanced AI\")\n        sleep(3)\n        console.log(\"Advanced Covid AI Ready\")\n        sleep(3)\n        status.update(status=\"[bold blue] Scanning for Covid\", spinner=\"earth\")\n        sleep(3)\n        console.log(\"Found 10,000,000,000 copies of Covid32.exe\")\n        sleep(3)\n        status.update(\n            status=\"[bold red]Moving Covid32.exe to Trash\",\n            spinner=\"bouncingBall\",\n            spinner_style=\"yellow\",\n        )\n        sleep(5)\n    console.print(\"[bold green]Covid deleted successfully\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/style.py",
    "content": "import sys\nfrom functools import lru_cache\nfrom marshal import dumps, loads\nfrom random import randint\nfrom typing import Any, Dict, Iterable, List, Optional, Type, Union, cast\n\nfrom . import errors\nfrom .color import Color, ColorParseError, ColorSystem, blend_rgb\nfrom .repr import Result, rich_repr\nfrom .terminal_theme import DEFAULT_TERMINAL_THEME, TerminalTheme\n\n# Style instances and style definitions are often interchangeable\nStyleType = Union[str, \"Style\"]\n\n\nclass _Bit:\n    \"\"\"A descriptor to get/set a style attribute bit.\"\"\"\n\n    __slots__ = [\"bit\"]\n\n    def __init__(self, bit_no: int) -> None:\n        self.bit = 1 << bit_no\n\n    def __get__(self, obj: \"Style\", objtype: Type[\"Style\"]) -> Optional[bool]:\n        if obj._set_attributes & self.bit:\n            return obj._attributes & self.bit != 0\n        return None\n\n\n@rich_repr\nclass Style:\n    \"\"\"A terminal style.\n\n    A terminal style consists of a color (`color`), a background color (`bgcolor`), and a number of attributes, such\n    as bold, italic etc. The attributes have 3 states: they can either be on\n    (``True``), off (``False``), or not set (``None``).\n\n    Args:\n        color (Union[Color, str], optional): Color of terminal text. Defaults to None.\n        bgcolor (Union[Color, str], optional): Color of terminal background. Defaults to None.\n        bold (bool, optional): Enable bold text. Defaults to None.\n        dim (bool, optional): Enable dim text. Defaults to None.\n        italic (bool, optional): Enable italic text. Defaults to None.\n        underline (bool, optional): Enable underlined text. Defaults to None.\n        blink (bool, optional): Enabled blinking text. Defaults to None.\n        blink2 (bool, optional): Enable fast blinking text. Defaults to None.\n        reverse (bool, optional): Enabled reverse text. Defaults to None.\n        conceal (bool, optional): Enable concealed text. Defaults to None.\n        strike (bool, optional): Enable strikethrough text. Defaults to None.\n        underline2 (bool, optional): Enable doubly underlined text. Defaults to None.\n        frame (bool, optional): Enable framed text. Defaults to None.\n        encircle (bool, optional): Enable encircled text. Defaults to None.\n        overline (bool, optional): Enable overlined text. Defaults to None.\n        link (str, link): Link URL. Defaults to None.\n\n    \"\"\"\n\n    _color: Optional[Color]\n    _bgcolor: Optional[Color]\n    _attributes: int\n    _set_attributes: int\n    _hash: Optional[int]\n    _null: bool\n    _meta: Optional[bytes]\n\n    __slots__ = [\n        \"_color\",\n        \"_bgcolor\",\n        \"_attributes\",\n        \"_set_attributes\",\n        \"_link\",\n        \"_link_id\",\n        \"_ansi\",\n        \"_style_definition\",\n        \"_hash\",\n        \"_null\",\n        \"_meta\",\n    ]\n\n    # maps bits on to SGR parameter\n    _style_map = {\n        0: \"1\",\n        1: \"2\",\n        2: \"3\",\n        3: \"4\",\n        4: \"5\",\n        5: \"6\",\n        6: \"7\",\n        7: \"8\",\n        8: \"9\",\n        9: \"21\",\n        10: \"51\",\n        11: \"52\",\n        12: \"53\",\n    }\n\n    STYLE_ATTRIBUTES = {\n        \"dim\": \"dim\",\n        \"d\": \"dim\",\n        \"bold\": \"bold\",\n        \"b\": \"bold\",\n        \"italic\": \"italic\",\n        \"i\": \"italic\",\n        \"underline\": \"underline\",\n        \"u\": \"underline\",\n        \"blink\": \"blink\",\n        \"blink2\": \"blink2\",\n        \"reverse\": \"reverse\",\n        \"r\": \"reverse\",\n        \"conceal\": \"conceal\",\n        \"c\": \"conceal\",\n        \"strike\": \"strike\",\n        \"s\": \"strike\",\n        \"underline2\": \"underline2\",\n        \"uu\": \"underline2\",\n        \"frame\": \"frame\",\n        \"encircle\": \"encircle\",\n        \"overline\": \"overline\",\n        \"o\": \"overline\",\n    }\n\n    def __init__(\n        self,\n        *,\n        color: Optional[Union[Color, str]] = None,\n        bgcolor: Optional[Union[Color, str]] = None,\n        bold: Optional[bool] = None,\n        dim: Optional[bool] = None,\n        italic: Optional[bool] = None,\n        underline: Optional[bool] = None,\n        blink: Optional[bool] = None,\n        blink2: Optional[bool] = None,\n        reverse: Optional[bool] = None,\n        conceal: Optional[bool] = None,\n        strike: Optional[bool] = None,\n        underline2: Optional[bool] = None,\n        frame: Optional[bool] = None,\n        encircle: Optional[bool] = None,\n        overline: Optional[bool] = None,\n        link: Optional[str] = None,\n        meta: Optional[Dict[str, Any]] = None,\n    ):\n        self._ansi: Optional[str] = None\n        self._style_definition: Optional[str] = None\n\n        def _make_color(color: Union[Color, str]) -> Color:\n            return color if isinstance(color, Color) else Color.parse(color)\n\n        self._color = None if color is None else _make_color(color)\n        self._bgcolor = None if bgcolor is None else _make_color(bgcolor)\n        self._set_attributes = sum(\n            (\n                bold is not None,\n                dim is not None and 2,\n                italic is not None and 4,\n                underline is not None and 8,\n                blink is not None and 16,\n                blink2 is not None and 32,\n                reverse is not None and 64,\n                conceal is not None and 128,\n                strike is not None and 256,\n                underline2 is not None and 512,\n                frame is not None and 1024,\n                encircle is not None and 2048,\n                overline is not None and 4096,\n            )\n        )\n        self._attributes = (\n            sum(\n                (\n                    bold and 1 or 0,\n                    dim and 2 or 0,\n                    italic and 4 or 0,\n                    underline and 8 or 0,\n                    blink and 16 or 0,\n                    blink2 and 32 or 0,\n                    reverse and 64 or 0,\n                    conceal and 128 or 0,\n                    strike and 256 or 0,\n                    underline2 and 512 or 0,\n                    frame and 1024 or 0,\n                    encircle and 2048 or 0,\n                    overline and 4096 or 0,\n                )\n            )\n            if self._set_attributes\n            else 0\n        )\n\n        self._link = link\n        self._link_id = f\"{randint(0, 999999)}\" if link else \"\"\n        self._meta = None if meta is None else dumps(meta)\n        self._hash: Optional[int] = None\n        self._null = not (self._set_attributes or color or bgcolor or link or meta)\n\n    @classmethod\n    def null(cls) -> \"Style\":\n        \"\"\"Create an 'null' style, equivalent to Style(), but more performant.\"\"\"\n        return NULL_STYLE\n\n    @classmethod\n    def from_color(\n        cls, color: Optional[Color] = None, bgcolor: Optional[Color] = None\n    ) -> \"Style\":\n        \"\"\"Create a new style with colors and no attributes.\n\n        Returns:\n            color (Optional[Color]): A (foreground) color, or None for no color. Defaults to None.\n            bgcolor (Optional[Color]): A (background) color, or None for no color. Defaults to None.\n        \"\"\"\n        style: Style = cls.__new__(Style)\n        style._ansi = None\n        style._style_definition = None\n        style._color = color\n        style._bgcolor = bgcolor\n        style._set_attributes = 0\n        style._attributes = 0\n        style._link = None\n        style._link_id = \"\"\n        style._meta = None\n        style._null = not (color or bgcolor)\n        style._hash = None\n        return style\n\n    @classmethod\n    def from_meta(cls, meta: Optional[Dict[str, Any]]) -> \"Style\":\n        \"\"\"Create a new style with meta data.\n\n        Returns:\n            meta (Optional[Dict[str, Any]]): A dictionary of meta data. Defaults to None.\n        \"\"\"\n        style: Style = cls.__new__(Style)\n        style._ansi = None\n        style._style_definition = None\n        style._color = None\n        style._bgcolor = None\n        style._set_attributes = 0\n        style._attributes = 0\n        style._link = None\n        style._link_id = \"\"\n        style._meta = dumps(meta)\n        style._hash = None\n        style._null = not (meta)\n        return style\n\n    @classmethod\n    def on(cls, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> \"Style\":\n        \"\"\"Create a blank style with meta information.\n\n        Example:\n            style = Style.on(click=self.on_click)\n\n        Args:\n            meta (Optional[Dict[str, Any]], optional): An optional dict of meta information.\n            **handlers (Any): Keyword arguments are translated in to handlers.\n\n        Returns:\n            Style: A Style with meta information attached.\n        \"\"\"\n        meta = {} if meta is None else meta\n        meta.update({f\"@{key}\": value for key, value in handlers.items()})\n        return cls.from_meta(meta)\n\n    bold = _Bit(0)\n    dim = _Bit(1)\n    italic = _Bit(2)\n    underline = _Bit(3)\n    blink = _Bit(4)\n    blink2 = _Bit(5)\n    reverse = _Bit(6)\n    conceal = _Bit(7)\n    strike = _Bit(8)\n    underline2 = _Bit(9)\n    frame = _Bit(10)\n    encircle = _Bit(11)\n    overline = _Bit(12)\n\n    @property\n    def link_id(self) -> str:\n        \"\"\"Get a link id, used in ansi code for links.\"\"\"\n        return self._link_id\n\n    def __str__(self) -> str:\n        \"\"\"Re-generate style definition from attributes.\"\"\"\n        if self._style_definition is None:\n            attributes: List[str] = []\n            append = attributes.append\n            bits = self._set_attributes\n            if bits & 0b0000000001111:\n                if bits & 1:\n                    append(\"bold\" if self.bold else \"not bold\")\n                if bits & (1 << 1):\n                    append(\"dim\" if self.dim else \"not dim\")\n                if bits & (1 << 2):\n                    append(\"italic\" if self.italic else \"not italic\")\n                if bits & (1 << 3):\n                    append(\"underline\" if self.underline else \"not underline\")\n            if bits & 0b0000111110000:\n                if bits & (1 << 4):\n                    append(\"blink\" if self.blink else \"not blink\")\n                if bits & (1 << 5):\n                    append(\"blink2\" if self.blink2 else \"not blink2\")\n                if bits & (1 << 6):\n                    append(\"reverse\" if self.reverse else \"not reverse\")\n                if bits & (1 << 7):\n                    append(\"conceal\" if self.conceal else \"not conceal\")\n                if bits & (1 << 8):\n                    append(\"strike\" if self.strike else \"not strike\")\n            if bits & 0b1111000000000:\n                if bits & (1 << 9):\n                    append(\"underline2\" if self.underline2 else \"not underline2\")\n                if bits & (1 << 10):\n                    append(\"frame\" if self.frame else \"not frame\")\n                if bits & (1 << 11):\n                    append(\"encircle\" if self.encircle else \"not encircle\")\n                if bits & (1 << 12):\n                    append(\"overline\" if self.overline else \"not overline\")\n            if self._color is not None:\n                append(self._color.name)\n            if self._bgcolor is not None:\n                append(\"on\")\n                append(self._bgcolor.name)\n            if self._link:\n                append(\"link\")\n                append(self._link)\n            self._style_definition = \" \".join(attributes) or \"none\"\n        return self._style_definition\n\n    def __bool__(self) -> bool:\n        \"\"\"A Style is false if it has no attributes, colors, or links.\"\"\"\n        return not self._null\n\n    def _make_ansi_codes(self, color_system: ColorSystem) -> str:\n        \"\"\"Generate ANSI codes for this style.\n\n        Args:\n            color_system (ColorSystem): Color system.\n\n        Returns:\n            str: String containing codes.\n        \"\"\"\n\n        if self._ansi is None:\n            sgr: List[str] = []\n            append = sgr.append\n            _style_map = self._style_map\n            attributes = self._attributes & self._set_attributes\n            if attributes:\n                if attributes & 1:\n                    append(_style_map[0])\n                if attributes & 2:\n                    append(_style_map[1])\n                if attributes & 4:\n                    append(_style_map[2])\n                if attributes & 8:\n                    append(_style_map[3])\n                if attributes & 0b0000111110000:\n                    for bit in range(4, 9):\n                        if attributes & (1 << bit):\n                            append(_style_map[bit])\n                if attributes & 0b1111000000000:\n                    for bit in range(9, 13):\n                        if attributes & (1 << bit):\n                            append(_style_map[bit])\n            if self._color is not None:\n                sgr.extend(self._color.downgrade(color_system).get_ansi_codes())\n            if self._bgcolor is not None:\n                sgr.extend(\n                    self._bgcolor.downgrade(color_system).get_ansi_codes(\n                        foreground=False\n                    )\n                )\n            self._ansi = \";\".join(sgr)\n        return self._ansi\n\n    @classmethod\n    @lru_cache(maxsize=1024)\n    def normalize(cls, style: str) -> str:\n        \"\"\"Normalize a style definition so that styles with the same effect have the same string\n        representation.\n\n        Args:\n            style (str): A style definition.\n\n        Returns:\n            str: Normal form of style definition.\n        \"\"\"\n        try:\n            return str(cls.parse(style))\n        except errors.StyleSyntaxError:\n            return style.strip().lower()\n\n    @classmethod\n    def pick_first(cls, *values: Optional[StyleType]) -> StyleType:\n        \"\"\"Pick first non-None style.\"\"\"\n        for value in values:\n            if value is not None:\n                return value\n        raise ValueError(\"expected at least one non-None style\")\n\n    def __rich_repr__(self) -> Result:\n        yield \"color\", self.color, None\n        yield \"bgcolor\", self.bgcolor, None\n        yield \"bold\", self.bold, None,\n        yield \"dim\", self.dim, None,\n        yield \"italic\", self.italic, None\n        yield \"underline\", self.underline, None,\n        yield \"blink\", self.blink, None\n        yield \"blink2\", self.blink2, None\n        yield \"reverse\", self.reverse, None\n        yield \"conceal\", self.conceal, None\n        yield \"strike\", self.strike, None\n        yield \"underline2\", self.underline2, None\n        yield \"frame\", self.frame, None\n        yield \"encircle\", self.encircle, None\n        yield \"link\", self.link, None\n        if self._meta:\n            yield \"meta\", self.meta\n\n    def __eq__(self, other: Any) -> bool:\n        if not isinstance(other, Style):\n            return NotImplemented\n        return self.__hash__() == other.__hash__()\n\n    def __ne__(self, other: Any) -> bool:\n        if not isinstance(other, Style):\n            return NotImplemented\n        return self.__hash__() != other.__hash__()\n\n    def __hash__(self) -> int:\n        if self._hash is not None:\n            return self._hash\n        self._hash = hash(\n            (\n                self._color,\n                self._bgcolor,\n                self._attributes,\n                self._set_attributes,\n                self._link,\n                self._meta,\n            )\n        )\n        return self._hash\n\n    @property\n    def color(self) -> Optional[Color]:\n        \"\"\"The foreground color or None if it is not set.\"\"\"\n        return self._color\n\n    @property\n    def bgcolor(self) -> Optional[Color]:\n        \"\"\"The background color or None if it is not set.\"\"\"\n        return self._bgcolor\n\n    @property\n    def link(self) -> Optional[str]:\n        \"\"\"Link text, if set.\"\"\"\n        return self._link\n\n    @property\n    def transparent_background(self) -> bool:\n        \"\"\"Check if the style specified a transparent background.\"\"\"\n        return self.bgcolor is None or self.bgcolor.is_default\n\n    @property\n    def background_style(self) -> \"Style\":\n        \"\"\"A Style with background only.\"\"\"\n        return Style(bgcolor=self.bgcolor)\n\n    @property\n    def meta(self) -> Dict[str, Any]:\n        \"\"\"Get meta information (can not be changed after construction).\"\"\"\n        return {} if self._meta is None else cast(Dict[str, Any], loads(self._meta))\n\n    @property\n    def without_color(self) -> \"Style\":\n        \"\"\"Get a copy of the style with color removed.\"\"\"\n        if self._null:\n            return NULL_STYLE\n        style: Style = self.__new__(Style)\n        style._ansi = None\n        style._style_definition = None\n        style._color = None\n        style._bgcolor = None\n        style._attributes = self._attributes\n        style._set_attributes = self._set_attributes\n        style._link = self._link\n        style._link_id = f\"{randint(0, 999999)}\" if self._link else \"\"\n        style._null = False\n        style._meta = None\n        style._hash = None\n        return style\n\n    @classmethod\n    @lru_cache(maxsize=4096)\n    def parse(cls, style_definition: str) -> \"Style\":\n        \"\"\"Parse a style definition.\n\n        Args:\n            style_definition (str): A string containing a style.\n\n        Raises:\n            errors.StyleSyntaxError: If the style definition syntax is invalid.\n\n        Returns:\n            `Style`: A Style instance.\n        \"\"\"\n        if style_definition.strip() == \"none\" or not style_definition:\n            return cls.null()\n\n        STYLE_ATTRIBUTES = cls.STYLE_ATTRIBUTES\n        color: Optional[str] = None\n        bgcolor: Optional[str] = None\n        attributes: Dict[str, Optional[Any]] = {}\n        link: Optional[str] = None\n\n        words = iter(style_definition.split())\n        for original_word in words:\n            word = original_word.lower()\n            if word == \"on\":\n                word = next(words, \"\")\n                if not word:\n                    raise errors.StyleSyntaxError(\"color expected after 'on'\")\n                try:\n                    Color.parse(word) is None\n                except ColorParseError as error:\n                    raise errors.StyleSyntaxError(\n                        f\"unable to parse {word!r} as background color; {error}\"\n                    ) from None\n                bgcolor = word\n\n            elif word == \"not\":\n                word = next(words, \"\")\n                attribute = STYLE_ATTRIBUTES.get(word)\n                if attribute is None:\n                    raise errors.StyleSyntaxError(\n                        f\"expected style attribute after 'not', found {word!r}\"\n                    )\n                attributes[attribute] = False\n\n            elif word == \"link\":\n                word = next(words, \"\")\n                if not word:\n                    raise errors.StyleSyntaxError(\"URL expected after 'link'\")\n                link = word\n\n            elif word in STYLE_ATTRIBUTES:\n                attributes[STYLE_ATTRIBUTES[word]] = True\n\n            else:\n                try:\n                    Color.parse(word)\n                except ColorParseError as error:\n                    raise errors.StyleSyntaxError(\n                        f\"unable to parse {word!r} as color; {error}\"\n                    ) from None\n                color = word\n        style = Style(color=color, bgcolor=bgcolor, link=link, **attributes)\n        return style\n\n    @lru_cache(maxsize=1024)\n    def get_html_style(self, theme: Optional[TerminalTheme] = None) -> str:\n        \"\"\"Get a CSS style rule.\"\"\"\n        theme = theme or DEFAULT_TERMINAL_THEME\n        css: List[str] = []\n        append = css.append\n\n        color = self.color\n        bgcolor = self.bgcolor\n        if self.reverse:\n            color, bgcolor = bgcolor, color\n        if self.dim:\n            foreground_color = (\n                theme.foreground_color if color is None else color.get_truecolor(theme)\n            )\n            color = Color.from_triplet(\n                blend_rgb(foreground_color, theme.background_color, 0.5)\n            )\n        if color is not None:\n            theme_color = color.get_truecolor(theme)\n            append(f\"color: {theme_color.hex}\")\n            append(f\"text-decoration-color: {theme_color.hex}\")\n        if bgcolor is not None:\n            theme_color = bgcolor.get_truecolor(theme, foreground=False)\n            append(f\"background-color: {theme_color.hex}\")\n        if self.bold:\n            append(\"font-weight: bold\")\n        if self.italic:\n            append(\"font-style: italic\")\n        if self.underline:\n            append(\"text-decoration: underline\")\n        if self.strike:\n            append(\"text-decoration: line-through\")\n        if self.overline:\n            append(\"text-decoration: overline\")\n        return \"; \".join(css)\n\n    @classmethod\n    def combine(cls, styles: Iterable[\"Style\"]) -> \"Style\":\n        \"\"\"Combine styles and get result.\n\n        Args:\n            styles (Iterable[Style]): Styles to combine.\n\n        Returns:\n            Style: A new style instance.\n        \"\"\"\n        iter_styles = iter(styles)\n        return sum(iter_styles, next(iter_styles))\n\n    @classmethod\n    def chain(cls, *styles: \"Style\") -> \"Style\":\n        \"\"\"Combine styles from positional argument in to a single style.\n\n        Args:\n            *styles (Iterable[Style]): Styles to combine.\n\n        Returns:\n            Style: A new style instance.\n        \"\"\"\n        iter_styles = iter(styles)\n        return sum(iter_styles, next(iter_styles))\n\n    def copy(self) -> \"Style\":\n        \"\"\"Get a copy of this style.\n\n        Returns:\n            Style: A new Style instance with identical attributes.\n        \"\"\"\n        if self._null:\n            return NULL_STYLE\n        style: Style = self.__new__(Style)\n        style._ansi = self._ansi\n        style._style_definition = self._style_definition\n        style._color = self._color\n        style._bgcolor = self._bgcolor\n        style._attributes = self._attributes\n        style._set_attributes = self._set_attributes\n        style._link = self._link\n        style._link_id = f\"{randint(0, 999999)}\" if self._link else \"\"\n        style._hash = self._hash\n        style._null = False\n        style._meta = self._meta\n        return style\n\n    def update_link(self, link: Optional[str] = None) -> \"Style\":\n        \"\"\"Get a copy with a different value for link.\n\n        Args:\n            link (str, optional): New value for link. Defaults to None.\n\n        Returns:\n            Style: A new Style instance.\n        \"\"\"\n        style: Style = self.__new__(Style)\n        style._ansi = self._ansi\n        style._style_definition = self._style_definition\n        style._color = self._color\n        style._bgcolor = self._bgcolor\n        style._attributes = self._attributes\n        style._set_attributes = self._set_attributes\n        style._link = link\n        style._link_id = f\"{randint(0, 999999)}\" if link else \"\"\n        style._hash = None\n        style._null = False\n        style._meta = self._meta\n        return style\n\n    def render(\n        self,\n        text: str = \"\",\n        *,\n        color_system: Optional[ColorSystem] = ColorSystem.TRUECOLOR,\n        legacy_windows: bool = False,\n    ) -> str:\n        \"\"\"Render the ANSI codes for the style.\n\n        Args:\n            text (str, optional): A string to style. Defaults to \"\".\n            color_system (Optional[ColorSystem], optional): Color system to render to. Defaults to ColorSystem.TRUECOLOR.\n\n        Returns:\n            str: A string containing ANSI style codes.\n        \"\"\"\n        if not text or color_system is None:\n            return text\n        attrs = self._ansi or self._make_ansi_codes(color_system)\n        rendered = f\"\\x1b[{attrs}m{text}\\x1b[0m\" if attrs else text\n        if self._link and not legacy_windows:\n            rendered = (\n                f\"\\x1b]8;id={self._link_id};{self._link}\\x1b\\\\{rendered}\\x1b]8;;\\x1b\\\\\"\n            )\n        return rendered\n\n    def test(self, text: Optional[str] = None) -> None:\n        \"\"\"Write text with style directly to terminal.\n\n        This method is for testing purposes only.\n\n        Args:\n            text (Optional[str], optional): Text to style or None for style name.\n\n        \"\"\"\n        text = text or str(self)\n        sys.stdout.write(f\"{self.render(text)}\\n\")\n\n    @lru_cache(maxsize=1024)\n    def _add(self, style: Optional[\"Style\"]) -> \"Style\":\n        if style is None or style._null:\n            return self\n        if self._null:\n            return style\n        new_style: Style = self.__new__(Style)\n        new_style._ansi = None\n        new_style._style_definition = None\n        new_style._color = style._color or self._color\n        new_style._bgcolor = style._bgcolor or self._bgcolor\n        new_style._attributes = (self._attributes & ~style._set_attributes) | (\n            style._attributes & style._set_attributes\n        )\n        new_style._set_attributes = self._set_attributes | style._set_attributes\n        new_style._link = style._link or self._link\n        new_style._link_id = style._link_id or self._link_id\n        new_style._null = style._null\n        if self._meta and style._meta:\n            new_style._meta = dumps({**self.meta, **style.meta})\n        else:\n            new_style._meta = self._meta or style._meta\n        new_style._hash = None\n        return new_style\n\n    def __add__(self, style: Optional[\"Style\"]) -> \"Style\":\n        combined_style = self._add(style)\n        return combined_style.copy() if combined_style.link else combined_style\n\n\nNULL_STYLE = Style()\n\n\nclass StyleStack:\n    \"\"\"A stack of styles.\"\"\"\n\n    __slots__ = [\"_stack\"]\n\n    def __init__(self, default_style: \"Style\") -> None:\n        self._stack: List[Style] = [default_style]\n\n    def __repr__(self) -> str:\n        return f\"<stylestack {self._stack!r}>\"\n\n    @property\n    def current(self) -> Style:\n        \"\"\"Get the Style at the top of the stack.\"\"\"\n        return self._stack[-1]\n\n    def push(self, style: Style) -> None:\n        \"\"\"Push a new style on to the stack.\n\n        Args:\n            style (Style): New style to combine with current style.\n        \"\"\"\n        self._stack.append(self._stack[-1] + style)\n\n    def pop(self) -> Style:\n        \"\"\"Pop last style and discard.\n\n        Returns:\n            Style: New current style (also available as stack.current)\n        \"\"\"\n        self._stack.pop()\n        return self._stack[-1]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/styled.py",
    "content": "from typing import TYPE_CHECKING\n\nfrom .measure import Measurement\nfrom .segment import Segment\nfrom .style import StyleType\n\nif TYPE_CHECKING:\n    from .console import Console, ConsoleOptions, RenderResult, RenderableType\n\n\nclass Styled:\n    \"\"\"Apply a style to a renderable.\n\n    Args:\n        renderable (RenderableType): Any renderable.\n        style (StyleType): A style to apply across the entire renderable.\n    \"\"\"\n\n    def __init__(self, renderable: \"RenderableType\", style: \"StyleType\") -> None:\n        self.renderable = renderable\n        self.style = style\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n        style = console.get_style(self.style)\n        rendered_segments = console.render(self.renderable, options)\n        segments = Segment.apply_style(rendered_segments, style)\n        return segments\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Measurement:\n        return Measurement.get(console, options, self.renderable)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich import print\n    from pip._vendor.rich.panel import Panel\n\n    panel = Styled(Panel(\"hello\"), \"on blue\")\n    print(panel)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/syntax.py",
    "content": "import os.path\nimport platform\nimport re\nimport sys\nimport textwrap\nfrom abc import ABC, abstractmethod\nfrom typing import (\n    Any,\n    Dict,\n    Iterable,\n    List,\n    NamedTuple,\n    Optional,\n    Sequence,\n    Set,\n    Tuple,\n    Type,\n    Union,\n)\n\nfrom pip._vendor.pygments.lexer import Lexer\nfrom pip._vendor.pygments.lexers import get_lexer_by_name, guess_lexer_for_filename\nfrom pip._vendor.pygments.style import Style as PygmentsStyle\nfrom pip._vendor.pygments.styles import get_style_by_name\nfrom pip._vendor.pygments.token import (\n    Comment,\n    Error,\n    Generic,\n    Keyword,\n    Name,\n    Number,\n    Operator,\n    String,\n    Token,\n    Whitespace,\n)\nfrom pip._vendor.pygments.util import ClassNotFound\n\nfrom pip._vendor.rich.containers import Lines\nfrom pip._vendor.rich.padding import Padding, PaddingDimensions\n\nfrom ._loop import loop_first\nfrom .color import Color, blend_rgb\nfrom .console import Console, ConsoleOptions, JustifyMethod, RenderResult\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .segment import Segment, Segments\nfrom .style import Style, StyleType\nfrom .text import Text\n\nTokenType = Tuple[str, ...]\n\nWINDOWS = platform.system() == \"Windows\"\nDEFAULT_THEME = \"monokai\"\n\n# The following styles are based on https://github.com/pygments/pygments/blob/master/pygments/formatters/terminal.py\n# A few modifications were made\n\nANSI_LIGHT: Dict[TokenType, Style] = {\n    Token: Style(),\n    Whitespace: Style(color=\"white\"),\n    Comment: Style(dim=True),\n    Comment.Preproc: Style(color=\"cyan\"),\n    Keyword: Style(color=\"blue\"),\n    Keyword.Type: Style(color=\"cyan\"),\n    Operator.Word: Style(color=\"magenta\"),\n    Name.Builtin: Style(color=\"cyan\"),\n    Name.Function: Style(color=\"green\"),\n    Name.Namespace: Style(color=\"cyan\", underline=True),\n    Name.Class: Style(color=\"green\", underline=True),\n    Name.Exception: Style(color=\"cyan\"),\n    Name.Decorator: Style(color=\"magenta\", bold=True),\n    Name.Variable: Style(color=\"red\"),\n    Name.Constant: Style(color=\"red\"),\n    Name.Attribute: Style(color=\"cyan\"),\n    Name.Tag: Style(color=\"bright_blue\"),\n    String: Style(color=\"yellow\"),\n    Number: Style(color=\"blue\"),\n    Generic.Deleted: Style(color=\"bright_red\"),\n    Generic.Inserted: Style(color=\"green\"),\n    Generic.Heading: Style(bold=True),\n    Generic.Subheading: Style(color=\"magenta\", bold=True),\n    Generic.Prompt: Style(bold=True),\n    Generic.Error: Style(color=\"bright_red\"),\n    Error: Style(color=\"red\", underline=True),\n}\n\nANSI_DARK: Dict[TokenType, Style] = {\n    Token: Style(),\n    Whitespace: Style(color=\"bright_black\"),\n    Comment: Style(dim=True),\n    Comment.Preproc: Style(color=\"bright_cyan\"),\n    Keyword: Style(color=\"bright_blue\"),\n    Keyword.Type: Style(color=\"bright_cyan\"),\n    Operator.Word: Style(color=\"bright_magenta\"),\n    Name.Builtin: Style(color=\"bright_cyan\"),\n    Name.Function: Style(color=\"bright_green\"),\n    Name.Namespace: Style(color=\"bright_cyan\", underline=True),\n    Name.Class: Style(color=\"bright_green\", underline=True),\n    Name.Exception: Style(color=\"bright_cyan\"),\n    Name.Decorator: Style(color=\"bright_magenta\", bold=True),\n    Name.Variable: Style(color=\"bright_red\"),\n    Name.Constant: Style(color=\"bright_red\"),\n    Name.Attribute: Style(color=\"bright_cyan\"),\n    Name.Tag: Style(color=\"bright_blue\"),\n    String: Style(color=\"yellow\"),\n    Number: Style(color=\"bright_blue\"),\n    Generic.Deleted: Style(color=\"bright_red\"),\n    Generic.Inserted: Style(color=\"bright_green\"),\n    Generic.Heading: Style(bold=True),\n    Generic.Subheading: Style(color=\"bright_magenta\", bold=True),\n    Generic.Prompt: Style(bold=True),\n    Generic.Error: Style(color=\"bright_red\"),\n    Error: Style(color=\"red\", underline=True),\n}\n\nRICH_SYNTAX_THEMES = {\"ansi_light\": ANSI_LIGHT, \"ansi_dark\": ANSI_DARK}\nNUMBERS_COLUMN_DEFAULT_PADDING = 2\n\n\nclass SyntaxTheme(ABC):\n    \"\"\"Base class for a syntax theme.\"\"\"\n\n    @abstractmethod\n    def get_style_for_token(self, token_type: TokenType) -> Style:\n        \"\"\"Get a style for a given Pygments token.\"\"\"\n        raise NotImplementedError  # pragma: no cover\n\n    @abstractmethod\n    def get_background_style(self) -> Style:\n        \"\"\"Get the background color.\"\"\"\n        raise NotImplementedError  # pragma: no cover\n\n\nclass PygmentsSyntaxTheme(SyntaxTheme):\n    \"\"\"Syntax theme that delegates to Pygments theme.\"\"\"\n\n    def __init__(self, theme: Union[str, Type[PygmentsStyle]]) -> None:\n        self._style_cache: Dict[TokenType, Style] = {}\n        if isinstance(theme, str):\n            try:\n                self._pygments_style_class = get_style_by_name(theme)\n            except ClassNotFound:\n                self._pygments_style_class = get_style_by_name(\"default\")\n        else:\n            self._pygments_style_class = theme\n\n        self._background_color = self._pygments_style_class.background_color\n        self._background_style = Style(bgcolor=self._background_color)\n\n    def get_style_for_token(self, token_type: TokenType) -> Style:\n        \"\"\"Get a style from a Pygments class.\"\"\"\n        try:\n            return self._style_cache[token_type]\n        except KeyError:\n            try:\n                pygments_style = self._pygments_style_class.style_for_token(token_type)\n            except KeyError:\n                style = Style.null()\n            else:\n                color = pygments_style[\"color\"]\n                bgcolor = pygments_style[\"bgcolor\"]\n                style = Style(\n                    color=\"#\" + color if color else \"#000000\",\n                    bgcolor=\"#\" + bgcolor if bgcolor else self._background_color,\n                    bold=pygments_style[\"bold\"],\n                    italic=pygments_style[\"italic\"],\n                    underline=pygments_style[\"underline\"],\n                )\n            self._style_cache[token_type] = style\n        return style\n\n    def get_background_style(self) -> Style:\n        return self._background_style\n\n\nclass ANSISyntaxTheme(SyntaxTheme):\n    \"\"\"Syntax theme to use standard colors.\"\"\"\n\n    def __init__(self, style_map: Dict[TokenType, Style]) -> None:\n        self.style_map = style_map\n        self._missing_style = Style.null()\n        self._background_style = Style.null()\n        self._style_cache: Dict[TokenType, Style] = {}\n\n    def get_style_for_token(self, token_type: TokenType) -> Style:\n        \"\"\"Look up style in the style map.\"\"\"\n        try:\n            return self._style_cache[token_type]\n        except KeyError:\n            # Styles form a hierarchy\n            # We need to go from most to least specific\n            # e.g. (\"foo\", \"bar\", \"baz\") to (\"foo\", \"bar\")  to (\"foo\",)\n            get_style = self.style_map.get\n            token = tuple(token_type)\n            style = self._missing_style\n            while token:\n                _style = get_style(token)\n                if _style is not None:\n                    style = _style\n                    break\n                token = token[:-1]\n            self._style_cache[token_type] = style\n            return style\n\n    def get_background_style(self) -> Style:\n        return self._background_style\n\n\nSyntaxPosition = Tuple[int, int]\n\n\nclass _SyntaxHighlightRange(NamedTuple):\n    \"\"\"\n    A range to highlight in a Syntax object.\n    `start` and `end` are 2-integers tuples, where the first integer is the line number\n    (starting from 1) and the second integer is the column index (starting from 0).\n    \"\"\"\n\n    style: StyleType\n    start: SyntaxPosition\n    end: SyntaxPosition\n\n\nclass Syntax(JupyterMixin):\n    \"\"\"Construct a Syntax object to render syntax highlighted code.\n\n    Args:\n        code (str): Code to highlight.\n        lexer (Lexer | str): Lexer to use (see https://pygments.org/docs/lexers/)\n        theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to \"monokai\".\n        dedent (bool, optional): Enable stripping of initial whitespace. Defaults to False.\n        line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.\n        start_line (int, optional): Starting number for line numbers. Defaults to 1.\n        line_range (Tuple[int | None, int | None], optional): If given should be a tuple of the start and end line to render.\n            A value of None in the tuple indicates the range is open in that direction.\n        highlight_lines (Set[int]): A set of line numbers to highlight.\n        code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.\n        tab_size (int, optional): Size of tabs. Defaults to 4.\n        word_wrap (bool, optional): Enable word wrapping.\n        background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.\n        indent_guides (bool, optional): Show indent guides. Defaults to False.\n        padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding).\n    \"\"\"\n\n    _pygments_style_class: Type[PygmentsStyle]\n    _theme: SyntaxTheme\n\n    @classmethod\n    def get_theme(cls, name: Union[str, SyntaxTheme]) -> SyntaxTheme:\n        \"\"\"Get a syntax theme instance.\"\"\"\n        if isinstance(name, SyntaxTheme):\n            return name\n        theme: SyntaxTheme\n        if name in RICH_SYNTAX_THEMES:\n            theme = ANSISyntaxTheme(RICH_SYNTAX_THEMES[name])\n        else:\n            theme = PygmentsSyntaxTheme(name)\n        return theme\n\n    def __init__(\n        self,\n        code: str,\n        lexer: Union[Lexer, str],\n        *,\n        theme: Union[str, SyntaxTheme] = DEFAULT_THEME,\n        dedent: bool = False,\n        line_numbers: bool = False,\n        start_line: int = 1,\n        line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,\n        highlight_lines: Optional[Set[int]] = None,\n        code_width: Optional[int] = None,\n        tab_size: int = 4,\n        word_wrap: bool = False,\n        background_color: Optional[str] = None,\n        indent_guides: bool = False,\n        padding: PaddingDimensions = 0,\n    ) -> None:\n        self.code = code\n        self._lexer = lexer\n        self.dedent = dedent\n        self.line_numbers = line_numbers\n        self.start_line = start_line\n        self.line_range = line_range\n        self.highlight_lines = highlight_lines or set()\n        self.code_width = code_width\n        self.tab_size = tab_size\n        self.word_wrap = word_wrap\n        self.background_color = background_color\n        self.background_style = (\n            Style(bgcolor=background_color) if background_color else Style()\n        )\n        self.indent_guides = indent_guides\n        self.padding = padding\n\n        self._theme = self.get_theme(theme)\n        self._stylized_ranges: List[_SyntaxHighlightRange] = []\n\n    @classmethod\n    def from_path(\n        cls,\n        path: str,\n        encoding: str = \"utf-8\",\n        lexer: Optional[Union[Lexer, str]] = None,\n        theme: Union[str, SyntaxTheme] = DEFAULT_THEME,\n        dedent: bool = False,\n        line_numbers: bool = False,\n        line_range: Optional[Tuple[int, int]] = None,\n        start_line: int = 1,\n        highlight_lines: Optional[Set[int]] = None,\n        code_width: Optional[int] = None,\n        tab_size: int = 4,\n        word_wrap: bool = False,\n        background_color: Optional[str] = None,\n        indent_guides: bool = False,\n        padding: PaddingDimensions = 0,\n    ) -> \"Syntax\":\n        \"\"\"Construct a Syntax object from a file.\n\n        Args:\n            path (str): Path to file to highlight.\n            encoding (str): Encoding of file.\n            lexer (str | Lexer, optional): Lexer to use. If None, lexer will be auto-detected from path/file content.\n            theme (str, optional): Color theme, aka Pygments style (see https://pygments.org/docs/styles/#getting-a-list-of-available-styles). Defaults to \"emacs\".\n            dedent (bool, optional): Enable stripping of initial whitespace. Defaults to True.\n            line_numbers (bool, optional): Enable rendering of line numbers. Defaults to False.\n            start_line (int, optional): Starting number for line numbers. Defaults to 1.\n            line_range (Tuple[int, int], optional): If given should be a tuple of the start and end line to render.\n            highlight_lines (Set[int]): A set of line numbers to highlight.\n            code_width: Width of code to render (not including line numbers), or ``None`` to use all available width.\n            tab_size (int, optional): Size of tabs. Defaults to 4.\n            word_wrap (bool, optional): Enable word wrapping of code.\n            background_color (str, optional): Optional background color, or None to use theme color. Defaults to None.\n            indent_guides (bool, optional): Show indent guides. Defaults to False.\n            padding (PaddingDimensions): Padding to apply around the syntax. Defaults to 0 (no padding).\n\n        Returns:\n            [Syntax]: A Syntax object that may be printed to the console\n        \"\"\"\n        with open(path, \"rt\", encoding=encoding) as code_file:\n            code = code_file.read()\n\n        if not lexer:\n            lexer = cls.guess_lexer(path, code=code)\n\n        return cls(\n            code,\n            lexer,\n            theme=theme,\n            dedent=dedent,\n            line_numbers=line_numbers,\n            line_range=line_range,\n            start_line=start_line,\n            highlight_lines=highlight_lines,\n            code_width=code_width,\n            tab_size=tab_size,\n            word_wrap=word_wrap,\n            background_color=background_color,\n            indent_guides=indent_guides,\n            padding=padding,\n        )\n\n    @classmethod\n    def guess_lexer(cls, path: str, code: Optional[str] = None) -> str:\n        \"\"\"Guess the alias of the Pygments lexer to use based on a path and an optional string of code.\n        If code is supplied, it will use a combination of the code and the filename to determine the\n        best lexer to use. For example, if the file is ``index.html`` and the file contains Django\n        templating syntax, then \"html+django\" will be returned. If the file is ``index.html``, and no\n        templating language is used, the \"html\" lexer will be used. If no string of code\n        is supplied, the lexer will be chosen based on the file extension..\n\n        Args:\n             path (AnyStr): The path to the file containing the code you wish to know the lexer for.\n             code (str, optional): Optional string of code that will be used as a fallback if no lexer\n                is found for the supplied path.\n\n        Returns:\n            str: The name of the Pygments lexer that best matches the supplied path/code.\n        \"\"\"\n        lexer: Optional[Lexer] = None\n        lexer_name = \"default\"\n        if code:\n            try:\n                lexer = guess_lexer_for_filename(path, code)\n            except ClassNotFound:\n                pass\n\n        if not lexer:\n            try:\n                _, ext = os.path.splitext(path)\n                if ext:\n                    extension = ext.lstrip(\".\").lower()\n                    lexer = get_lexer_by_name(extension)\n            except ClassNotFound:\n                pass\n\n        if lexer:\n            if lexer.aliases:\n                lexer_name = lexer.aliases[0]\n            else:\n                lexer_name = lexer.name\n\n        return lexer_name\n\n    def _get_base_style(self) -> Style:\n        \"\"\"Get the base style.\"\"\"\n        default_style = self._theme.get_background_style() + self.background_style\n        return default_style\n\n    def _get_token_color(self, token_type: TokenType) -> Optional[Color]:\n        \"\"\"Get a color (if any) for the given token.\n\n        Args:\n            token_type (TokenType): A token type tuple from Pygments.\n\n        Returns:\n            Optional[Color]: Color from theme, or None for no color.\n        \"\"\"\n        style = self._theme.get_style_for_token(token_type)\n        return style.color\n\n    @property\n    def lexer(self) -> Optional[Lexer]:\n        \"\"\"The lexer for this syntax, or None if no lexer was found.\n\n        Tries to find the lexer by name if a string was passed to the constructor.\n        \"\"\"\n\n        if isinstance(self._lexer, Lexer):\n            return self._lexer\n        try:\n            return get_lexer_by_name(\n                self._lexer,\n                stripnl=False,\n                ensurenl=True,\n                tabsize=self.tab_size,\n            )\n        except ClassNotFound:\n            return None\n\n    def highlight(\n        self,\n        code: str,\n        line_range: Optional[Tuple[Optional[int], Optional[int]]] = None,\n    ) -> Text:\n        \"\"\"Highlight code and return a Text instance.\n\n        Args:\n            code (str): Code to highlight.\n            line_range(Tuple[int, int], optional): Optional line range to highlight.\n\n        Returns:\n            Text: A text instance containing highlighted syntax.\n        \"\"\"\n\n        base_style = self._get_base_style()\n        justify: JustifyMethod = (\n            \"default\" if base_style.transparent_background else \"left\"\n        )\n\n        text = Text(\n            justify=justify,\n            style=base_style,\n            tab_size=self.tab_size,\n            no_wrap=not self.word_wrap,\n        )\n        _get_theme_style = self._theme.get_style_for_token\n\n        lexer = self.lexer\n\n        if lexer is None:\n            text.append(code)\n        else:\n            if line_range:\n                # More complicated path to only stylize a portion of the code\n                # This speeds up further operations as there are less spans to process\n                line_start, line_end = line_range\n\n                def line_tokenize() -> Iterable[Tuple[Any, str]]:\n                    \"\"\"Split tokens to one per line.\"\"\"\n                    assert lexer  # required to make MyPy happy - we know lexer is not None at this point\n\n                    for token_type, token in lexer.get_tokens(code):\n                        while token:\n                            line_token, new_line, token = token.partition(\"\\n\")\n                            yield token_type, line_token + new_line\n\n                def tokens_to_spans() -> Iterable[Tuple[str, Optional[Style]]]:\n                    \"\"\"Convert tokens to spans.\"\"\"\n                    tokens = iter(line_tokenize())\n                    line_no = 0\n                    _line_start = line_start - 1 if line_start else 0\n\n                    # Skip over tokens until line start\n                    while line_no < _line_start:\n                        _token_type, token = next(tokens)\n                        yield (token, None)\n                        if token.endswith(\"\\n\"):\n                            line_no += 1\n                    # Generate spans until line end\n                    for token_type, token in tokens:\n                        yield (token, _get_theme_style(token_type))\n                        if token.endswith(\"\\n\"):\n                            line_no += 1\n                            if line_end and line_no >= line_end:\n                                break\n\n                text.append_tokens(tokens_to_spans())\n\n            else:\n                text.append_tokens(\n                    (token, _get_theme_style(token_type))\n                    for token_type, token in lexer.get_tokens(code)\n                )\n            if self.background_color is not None:\n                text.stylize(f\"on {self.background_color}\")\n\n        if self._stylized_ranges:\n            self._apply_stylized_ranges(text)\n\n        return text\n\n    def stylize_range(\n        self, style: StyleType, start: SyntaxPosition, end: SyntaxPosition\n    ) -> None:\n        \"\"\"\n        Adds a custom style on a part of the code, that will be applied to the syntax display when it's rendered.\n        Line numbers are 1-based, while column indexes are 0-based.\n\n        Args:\n            style (StyleType): The style to apply.\n            start (Tuple[int, int]): The start of the range, in the form `[line number, column index]`.\n            end (Tuple[int, int]): The end of the range, in the form `[line number, column index]`.\n        \"\"\"\n        self._stylized_ranges.append(_SyntaxHighlightRange(style, start, end))\n\n    def _get_line_numbers_color(self, blend: float = 0.3) -> Color:\n        background_style = self._theme.get_background_style() + self.background_style\n        background_color = background_style.bgcolor\n        if background_color is None or background_color.is_system_defined:\n            return Color.default()\n        foreground_color = self._get_token_color(Token.Text)\n        if foreground_color is None or foreground_color.is_system_defined:\n            return foreground_color or Color.default()\n        new_color = blend_rgb(\n            background_color.get_truecolor(),\n            foreground_color.get_truecolor(),\n            cross_fade=blend,\n        )\n        return Color.from_triplet(new_color)\n\n    @property\n    def _numbers_column_width(self) -> int:\n        \"\"\"Get the number of characters used to render the numbers column.\"\"\"\n        column_width = 0\n        if self.line_numbers:\n            column_width = (\n                len(str(self.start_line + self.code.count(\"\\n\")))\n                + NUMBERS_COLUMN_DEFAULT_PADDING\n            )\n        return column_width\n\n    def _get_number_styles(self, console: Console) -> Tuple[Style, Style, Style]:\n        \"\"\"Get background, number, and highlight styles for line numbers.\"\"\"\n        background_style = self._get_base_style()\n        if background_style.transparent_background:\n            return Style.null(), Style(dim=True), Style.null()\n        if console.color_system in (\"256\", \"truecolor\"):\n            number_style = Style.chain(\n                background_style,\n                self._theme.get_style_for_token(Token.Text),\n                Style(color=self._get_line_numbers_color()),\n                self.background_style,\n            )\n            highlight_number_style = Style.chain(\n                background_style,\n                self._theme.get_style_for_token(Token.Text),\n                Style(bold=True, color=self._get_line_numbers_color(0.9)),\n                self.background_style,\n            )\n        else:\n            number_style = background_style + Style(dim=True)\n            highlight_number_style = background_style + Style(dim=False)\n        return background_style, number_style, highlight_number_style\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        _, right, _, left = Padding.unpack(self.padding)\n        if self.code_width is not None:\n            width = self.code_width + self._numbers_column_width + right + left\n            return Measurement(self._numbers_column_width, width)\n        return Measurement(self._numbers_column_width, options.max_width)\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        segments = Segments(self._get_syntax(console, options))\n        if self.padding:\n            yield Padding(\n                segments, style=self._theme.get_background_style(), pad=self.padding\n            )\n        else:\n            yield segments\n\n    def _get_syntax(\n        self,\n        console: Console,\n        options: ConsoleOptions,\n    ) -> Iterable[Segment]:\n        \"\"\"\n        Get the Segments for the Syntax object, excluding any vertical/horizontal padding\n        \"\"\"\n        transparent_background = self._get_base_style().transparent_background\n        code_width = (\n            (\n                (options.max_width - self._numbers_column_width - 1)\n                if self.line_numbers\n                else options.max_width\n            )\n            if self.code_width is None\n            else self.code_width\n        )\n\n        ends_on_nl, processed_code = self._process_code(self.code)\n        text = self.highlight(processed_code, self.line_range)\n\n        if not self.line_numbers and not self.word_wrap and not self.line_range:\n            if not ends_on_nl:\n                text.remove_suffix(\"\\n\")\n            # Simple case of just rendering text\n            style = (\n                self._get_base_style()\n                + self._theme.get_style_for_token(Comment)\n                + Style(dim=True)\n                + self.background_style\n            )\n            if self.indent_guides and not options.ascii_only:\n                text = text.with_indent_guides(self.tab_size, style=style)\n                text.overflow = \"crop\"\n            if style.transparent_background:\n                yield from console.render(\n                    text, options=options.update(width=code_width)\n                )\n            else:\n                syntax_lines = console.render_lines(\n                    text,\n                    options.update(width=code_width, height=None, justify=\"left\"),\n                    style=self.background_style,\n                    pad=True,\n                    new_lines=True,\n                )\n                for syntax_line in syntax_lines:\n                    yield from syntax_line\n            return\n\n        start_line, end_line = self.line_range or (None, None)\n        line_offset = 0\n        if start_line:\n            line_offset = max(0, start_line - 1)\n        lines: Union[List[Text], Lines] = text.split(\"\\n\", allow_blank=ends_on_nl)\n        if self.line_range:\n            lines = lines[line_offset:end_line]\n\n        if self.indent_guides and not options.ascii_only:\n            style = (\n                self._get_base_style()\n                + self._theme.get_style_for_token(Comment)\n                + Style(dim=True)\n                + self.background_style\n            )\n            lines = (\n                Text(\"\\n\")\n                .join(lines)\n                .with_indent_guides(self.tab_size, style=style)\n                .split(\"\\n\", allow_blank=True)\n            )\n\n        numbers_column_width = self._numbers_column_width\n        render_options = options.update(width=code_width)\n\n        highlight_line = self.highlight_lines.__contains__\n        _Segment = Segment\n        new_line = _Segment(\"\\n\")\n\n        line_pointer = \"> \" if options.legacy_windows else \"❱ \"\n\n        (\n            background_style,\n            number_style,\n            highlight_number_style,\n        ) = self._get_number_styles(console)\n\n        for line_no, line in enumerate(lines, self.start_line + line_offset):\n            if self.word_wrap:\n                wrapped_lines = console.render_lines(\n                    line,\n                    render_options.update(height=None, justify=\"left\"),\n                    style=background_style,\n                    pad=not transparent_background,\n                )\n            else:\n                segments = list(line.render(console, end=\"\"))\n                if options.no_wrap:\n                    wrapped_lines = [segments]\n                else:\n                    wrapped_lines = [\n                        _Segment.adjust_line_length(\n                            segments,\n                            render_options.max_width,\n                            style=background_style,\n                            pad=not transparent_background,\n                        )\n                    ]\n\n            if self.line_numbers:\n                wrapped_line_left_pad = _Segment(\n                    \" \" * numbers_column_width + \" \", background_style\n                )\n                for first, wrapped_line in loop_first(wrapped_lines):\n                    if first:\n                        line_column = str(line_no).rjust(numbers_column_width - 2) + \" \"\n                        if highlight_line(line_no):\n                            yield _Segment(line_pointer, Style(color=\"red\"))\n                            yield _Segment(line_column, highlight_number_style)\n                        else:\n                            yield _Segment(\"  \", highlight_number_style)\n                            yield _Segment(line_column, number_style)\n                    else:\n                        yield wrapped_line_left_pad\n                    yield from wrapped_line\n                    yield new_line\n            else:\n                for wrapped_line in wrapped_lines:\n                    yield from wrapped_line\n                    yield new_line\n\n    def _apply_stylized_ranges(self, text: Text) -> None:\n        \"\"\"\n        Apply stylized ranges to a text instance,\n        using the given code to determine the right portion to apply the style to.\n\n        Args:\n            text (Text): Text instance to apply the style to.\n        \"\"\"\n        code = text.plain\n        newlines_offsets = [\n            # Let's add outer boundaries at each side of the list:\n            0,\n            # N.B. using \"\\n\" here is much faster than using metacharacters such as \"^\" or \"\\Z\":\n            *[\n                match.start() + 1\n                for match in re.finditer(\"\\n\", code, flags=re.MULTILINE)\n            ],\n            len(code) + 1,\n        ]\n\n        for stylized_range in self._stylized_ranges:\n            start = _get_code_index_for_syntax_position(\n                newlines_offsets, stylized_range.start\n            )\n            end = _get_code_index_for_syntax_position(\n                newlines_offsets, stylized_range.end\n            )\n            if start is not None and end is not None:\n                text.stylize(stylized_range.style, start, end)\n\n    def _process_code(self, code: str) -> Tuple[bool, str]:\n        \"\"\"\n        Applies various processing to a raw code string\n        (normalises it so it always ends with a line return, dedents it if necessary, etc.)\n\n        Args:\n            code (str): The raw code string to process\n\n        Returns:\n            Tuple[bool, str]: the boolean indicates whether the raw code ends with a line return,\n                while the string is the processed code.\n        \"\"\"\n        ends_on_nl = code.endswith(\"\\n\")\n        processed_code = code if ends_on_nl else code + \"\\n\"\n        processed_code = (\n            textwrap.dedent(processed_code) if self.dedent else processed_code\n        )\n        processed_code = processed_code.expandtabs(self.tab_size)\n        return ends_on_nl, processed_code\n\n\ndef _get_code_index_for_syntax_position(\n    newlines_offsets: Sequence[int], position: SyntaxPosition\n) -> Optional[int]:\n    \"\"\"\n    Returns the index of the code string for the given positions.\n\n    Args:\n        newlines_offsets (Sequence[int]): The offset of each newline character found in the code snippet.\n        position (SyntaxPosition): The position to search for.\n\n    Returns:\n        Optional[int]: The index of the code string for this position, or `None`\n            if the given position's line number is out of range (if it's the column that is out of range\n            we silently clamp its value so that it reaches the end of the line)\n    \"\"\"\n    lines_count = len(newlines_offsets)\n\n    line_number, column_index = position\n    if line_number > lines_count or len(newlines_offsets) < (line_number + 1):\n        return None  # `line_number` is out of range\n    line_index = line_number - 1\n    line_length = newlines_offsets[line_index + 1] - newlines_offsets[line_index] - 1\n    # If `column_index` is out of range: let's silently clamp it:\n    column_index = min(line_length, column_index)\n    return newlines_offsets[line_index] + column_index\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n\n    import argparse\n    import sys\n\n    parser = argparse.ArgumentParser(\n        description=\"Render syntax to the console with Rich\"\n    )\n    parser.add_argument(\n        \"path\",\n        metavar=\"PATH\",\n        help=\"path to file, or - for stdin\",\n    )\n    parser.add_argument(\n        \"-c\",\n        \"--force-color\",\n        dest=\"force_color\",\n        action=\"store_true\",\n        default=None,\n        help=\"force color for non-terminals\",\n    )\n    parser.add_argument(\n        \"-i\",\n        \"--indent-guides\",\n        dest=\"indent_guides\",\n        action=\"store_true\",\n        default=False,\n        help=\"display indent guides\",\n    )\n    parser.add_argument(\n        \"-l\",\n        \"--line-numbers\",\n        dest=\"line_numbers\",\n        action=\"store_true\",\n        help=\"render line numbers\",\n    )\n    parser.add_argument(\n        \"-w\",\n        \"--width\",\n        type=int,\n        dest=\"width\",\n        default=None,\n        help=\"width of output (default will auto-detect)\",\n    )\n    parser.add_argument(\n        \"-r\",\n        \"--wrap\",\n        dest=\"word_wrap\",\n        action=\"store_true\",\n        default=False,\n        help=\"word wrap long lines\",\n    )\n    parser.add_argument(\n        \"-s\",\n        \"--soft-wrap\",\n        action=\"store_true\",\n        dest=\"soft_wrap\",\n        default=False,\n        help=\"enable soft wrapping mode\",\n    )\n    parser.add_argument(\n        \"-t\", \"--theme\", dest=\"theme\", default=\"monokai\", help=\"pygments theme\"\n    )\n    parser.add_argument(\n        \"-b\",\n        \"--background-color\",\n        dest=\"background_color\",\n        default=None,\n        help=\"Override background color\",\n    )\n    parser.add_argument(\n        \"-x\",\n        \"--lexer\",\n        default=None,\n        dest=\"lexer_name\",\n        help=\"Lexer name\",\n    )\n    parser.add_argument(\n        \"-p\", \"--padding\", type=int, default=0, dest=\"padding\", help=\"Padding\"\n    )\n    parser.add_argument(\n        \"--highlight-line\",\n        type=int,\n        default=None,\n        dest=\"highlight_line\",\n        help=\"The line number (not index!) to highlight\",\n    )\n    args = parser.parse_args()\n\n    from pip._vendor.rich.console import Console\n\n    console = Console(force_terminal=args.force_color, width=args.width)\n\n    if args.path == \"-\":\n        code = sys.stdin.read()\n        syntax = Syntax(\n            code=code,\n            lexer=args.lexer_name,\n            line_numbers=args.line_numbers,\n            word_wrap=args.word_wrap,\n            theme=args.theme,\n            background_color=args.background_color,\n            indent_guides=args.indent_guides,\n            padding=args.padding,\n            highlight_lines={args.highlight_line},\n        )\n    else:\n        syntax = Syntax.from_path(\n            args.path,\n            lexer=args.lexer_name,\n            line_numbers=args.line_numbers,\n            word_wrap=args.word_wrap,\n            theme=args.theme,\n            background_color=args.background_color,\n            indent_guides=args.indent_guides,\n            padding=args.padding,\n            highlight_lines={args.highlight_line},\n        )\n    console.print(syntax, soft_wrap=args.soft_wrap)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/table.py",
    "content": "from dataclasses import dataclass, field, replace\nfrom typing import (\n    TYPE_CHECKING,\n    Dict,\n    Iterable,\n    List,\n    NamedTuple,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n)\n\nfrom . import box, errors\nfrom ._loop import loop_first_last, loop_last\nfrom ._pick import pick_bool\nfrom ._ratio import ratio_distribute, ratio_reduce\nfrom .align import VerticalAlignMethod\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .padding import Padding, PaddingDimensions\nfrom .protocol import is_renderable\nfrom .segment import Segment\nfrom .style import Style, StyleType\nfrom .text import Text, TextType\n\nif TYPE_CHECKING:\n    from .console import (\n        Console,\n        ConsoleOptions,\n        JustifyMethod,\n        OverflowMethod,\n        RenderableType,\n        RenderResult,\n    )\n\n\n@dataclass\nclass Column:\n    \"\"\"Defines a column within a ~Table.\n\n    Args:\n        title (Union[str, Text], optional): The title of the table rendered at the top. Defaults to None.\n        caption (Union[str, Text], optional): The table caption rendered below. Defaults to None.\n        width (int, optional): The width in characters of the table, or ``None`` to automatically fit. Defaults to None.\n        min_width (Optional[int], optional): The minimum width of the table, or ``None`` for no minimum. Defaults to None.\n        box (box.Box, optional): One of the constants in box.py used to draw the edges (see :ref:`appendix_box`), or ``None`` for no box lines. Defaults to box.HEAVY_HEAD.\n        safe_box (Optional[bool], optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True.\n        padding (PaddingDimensions, optional): Padding for cells (top, right, bottom, left). Defaults to (0, 1).\n        collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to False.\n        pad_edge (bool, optional): Enable padding of edge cells. Defaults to True.\n        expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False.\n        show_header (bool, optional): Show a header row. Defaults to True.\n        show_footer (bool, optional): Show a footer row. Defaults to False.\n        show_edge (bool, optional): Draw a box around the outside of the table. Defaults to True.\n        show_lines (bool, optional): Draw lines between every row. Defaults to False.\n        leading (bool, optional): Number of blank lines between rows (precludes ``show_lines``). Defaults to 0.\n        style (Union[str, Style], optional): Default style for the table. Defaults to \"none\".\n        row_styles (List[Union, str], optional): Optional list of row styles, if more than one style is given then the styles will alternate. Defaults to None.\n        header_style (Union[str, Style], optional): Style of the header. Defaults to \"table.header\".\n        footer_style (Union[str, Style], optional): Style of the footer. Defaults to \"table.footer\".\n        border_style (Union[str, Style], optional): Style of the border. Defaults to None.\n        title_style (Union[str, Style], optional): Style of the title. Defaults to None.\n        caption_style (Union[str, Style], optional): Style of the caption. Defaults to None.\n        title_justify (str, optional): Justify method for title. Defaults to \"center\".\n        caption_justify (str, optional): Justify method for caption. Defaults to \"center\".\n        highlight (bool, optional): Highlight cell contents (if str). Defaults to False.\n    \"\"\"\n\n    header: \"RenderableType\" = \"\"\n    \"\"\"RenderableType: Renderable for the header (typically a string)\"\"\"\n\n    footer: \"RenderableType\" = \"\"\n    \"\"\"RenderableType: Renderable for the footer (typically a string)\"\"\"\n\n    header_style: StyleType = \"\"\n    \"\"\"StyleType: The style of the header.\"\"\"\n\n    footer_style: StyleType = \"\"\n    \"\"\"StyleType: The style of the footer.\"\"\"\n\n    style: StyleType = \"\"\n    \"\"\"StyleType: The style of the column.\"\"\"\n\n    justify: \"JustifyMethod\" = \"left\"\n    \"\"\"str: How to justify text within the column (\"left\", \"center\", \"right\", or \"full\")\"\"\"\n\n    vertical: \"VerticalAlignMethod\" = \"top\"\n    \"\"\"str: How to vertically align content (\"top\", \"middle\", or \"bottom\")\"\"\"\n\n    overflow: \"OverflowMethod\" = \"ellipsis\"\n    \"\"\"str: Overflow method.\"\"\"\n\n    width: Optional[int] = None\n    \"\"\"Optional[int]: Width of the column, or ``None`` (default) to auto calculate width.\"\"\"\n\n    min_width: Optional[int] = None\n    \"\"\"Optional[int]: Minimum width of column, or ``None`` for no minimum. Defaults to None.\"\"\"\n\n    max_width: Optional[int] = None\n    \"\"\"Optional[int]: Maximum width of column, or ``None`` for no maximum. Defaults to None.\"\"\"\n\n    ratio: Optional[int] = None\n    \"\"\"Optional[int]: Ratio to use when calculating column width, or ``None`` (default) to adapt to column contents.\"\"\"\n\n    no_wrap: bool = False\n    \"\"\"bool: Prevent wrapping of text within the column. Defaults to ``False``.\"\"\"\n\n    _index: int = 0\n    \"\"\"Index of column.\"\"\"\n\n    _cells: List[\"RenderableType\"] = field(default_factory=list)\n\n    def copy(self) -> \"Column\":\n        \"\"\"Return a copy of this Column.\"\"\"\n        return replace(self, _cells=[])\n\n    @property\n    def cells(self) -> Iterable[\"RenderableType\"]:\n        \"\"\"Get all cells in the column, not including header.\"\"\"\n        yield from self._cells\n\n    @property\n    def flexible(self) -> bool:\n        \"\"\"Check if this column is flexible.\"\"\"\n        return self.ratio is not None\n\n\n@dataclass\nclass Row:\n    \"\"\"Information regarding a row.\"\"\"\n\n    style: Optional[StyleType] = None\n    \"\"\"Style to apply to row.\"\"\"\n\n    end_section: bool = False\n    \"\"\"Indicated end of section, which will force a line beneath the row.\"\"\"\n\n\nclass _Cell(NamedTuple):\n    \"\"\"A single cell in a table.\"\"\"\n\n    style: StyleType\n    \"\"\"Style to apply to cell.\"\"\"\n    renderable: \"RenderableType\"\n    \"\"\"Cell renderable.\"\"\"\n    vertical: VerticalAlignMethod\n    \"\"\"Cell vertical alignment.\"\"\"\n\n\nclass Table(JupyterMixin):\n    \"\"\"A console renderable to draw a table.\n\n    Args:\n        *headers (Union[Column, str]): Column headers, either as a string, or :class:`~rich.table.Column` instance.\n        title (Union[str, Text], optional): The title of the table rendered at the top. Defaults to None.\n        caption (Union[str, Text], optional): The table caption rendered below. Defaults to None.\n        width (int, optional): The width in characters of the table, or ``None`` to automatically fit. Defaults to None.\n        min_width (Optional[int], optional): The minimum width of the table, or ``None`` for no minimum. Defaults to None.\n        box (box.Box, optional): One of the constants in box.py used to draw the edges (see :ref:`appendix_box`), or ``None`` for no box lines. Defaults to box.HEAVY_HEAD.\n        safe_box (Optional[bool], optional): Disable box characters that don't display on windows legacy terminal with *raster* fonts. Defaults to True.\n        padding (PaddingDimensions, optional): Padding for cells (top, right, bottom, left). Defaults to (0, 1).\n        collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to False.\n        pad_edge (bool, optional): Enable padding of edge cells. Defaults to True.\n        expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False.\n        show_header (bool, optional): Show a header row. Defaults to True.\n        show_footer (bool, optional): Show a footer row. Defaults to False.\n        show_edge (bool, optional): Draw a box around the outside of the table. Defaults to True.\n        show_lines (bool, optional): Draw lines between every row. Defaults to False.\n        leading (bool, optional): Number of blank lines between rows (precludes ``show_lines``). Defaults to 0.\n        style (Union[str, Style], optional): Default style for the table. Defaults to \"none\".\n        row_styles (List[Union, str], optional): Optional list of row styles, if more than one style is given then the styles will alternate. Defaults to None.\n        header_style (Union[str, Style], optional): Style of the header. Defaults to \"table.header\".\n        footer_style (Union[str, Style], optional): Style of the footer. Defaults to \"table.footer\".\n        border_style (Union[str, Style], optional): Style of the border. Defaults to None.\n        title_style (Union[str, Style], optional): Style of the title. Defaults to None.\n        caption_style (Union[str, Style], optional): Style of the caption. Defaults to None.\n        title_justify (str, optional): Justify method for title. Defaults to \"center\".\n        caption_justify (str, optional): Justify method for caption. Defaults to \"center\".\n        highlight (bool, optional): Highlight cell contents (if str). Defaults to False.\n    \"\"\"\n\n    columns: List[Column]\n    rows: List[Row]\n\n    def __init__(\n        self,\n        *headers: Union[Column, str],\n        title: Optional[TextType] = None,\n        caption: Optional[TextType] = None,\n        width: Optional[int] = None,\n        min_width: Optional[int] = None,\n        box: Optional[box.Box] = box.HEAVY_HEAD,\n        safe_box: Optional[bool] = None,\n        padding: PaddingDimensions = (0, 1),\n        collapse_padding: bool = False,\n        pad_edge: bool = True,\n        expand: bool = False,\n        show_header: bool = True,\n        show_footer: bool = False,\n        show_edge: bool = True,\n        show_lines: bool = False,\n        leading: int = 0,\n        style: StyleType = \"none\",\n        row_styles: Optional[Iterable[StyleType]] = None,\n        header_style: Optional[StyleType] = \"table.header\",\n        footer_style: Optional[StyleType] = \"table.footer\",\n        border_style: Optional[StyleType] = None,\n        title_style: Optional[StyleType] = None,\n        caption_style: Optional[StyleType] = None,\n        title_justify: \"JustifyMethod\" = \"center\",\n        caption_justify: \"JustifyMethod\" = \"center\",\n        highlight: bool = False,\n    ) -> None:\n\n        self.columns: List[Column] = []\n        self.rows: List[Row] = []\n        self.title = title\n        self.caption = caption\n        self.width = width\n        self.min_width = min_width\n        self.box = box\n        self.safe_box = safe_box\n        self._padding = Padding.unpack(padding)\n        self.pad_edge = pad_edge\n        self._expand = expand\n        self.show_header = show_header\n        self.show_footer = show_footer\n        self.show_edge = show_edge\n        self.show_lines = show_lines\n        self.leading = leading\n        self.collapse_padding = collapse_padding\n        self.style = style\n        self.header_style = header_style or \"\"\n        self.footer_style = footer_style or \"\"\n        self.border_style = border_style\n        self.title_style = title_style\n        self.caption_style = caption_style\n        self.title_justify: \"JustifyMethod\" = title_justify\n        self.caption_justify: \"JustifyMethod\" = caption_justify\n        self.highlight = highlight\n        self.row_styles: Sequence[StyleType] = list(row_styles or [])\n        append_column = self.columns.append\n        for header in headers:\n            if isinstance(header, str):\n                self.add_column(header=header)\n            else:\n                header._index = len(self.columns)\n                append_column(header)\n\n    @classmethod\n    def grid(\n        cls,\n        *headers: Union[Column, str],\n        padding: PaddingDimensions = 0,\n        collapse_padding: bool = True,\n        pad_edge: bool = False,\n        expand: bool = False,\n    ) -> \"Table\":\n        \"\"\"Get a table with no lines, headers, or footer.\n\n        Args:\n            *headers (Union[Column, str]): Column headers, either as a string, or :class:`~rich.table.Column` instance.\n            padding (PaddingDimensions, optional): Get padding around cells. Defaults to 0.\n            collapse_padding (bool, optional): Enable collapsing of padding around cells. Defaults to True.\n            pad_edge (bool, optional): Enable padding around edges of table. Defaults to False.\n            expand (bool, optional): Expand the table to fit the available space if ``True``, otherwise the table width will be auto-calculated. Defaults to False.\n\n        Returns:\n            Table: A table instance.\n        \"\"\"\n        return cls(\n            *headers,\n            box=None,\n            padding=padding,\n            collapse_padding=collapse_padding,\n            show_header=False,\n            show_footer=False,\n            show_edge=False,\n            pad_edge=pad_edge,\n            expand=expand,\n        )\n\n    @property\n    def expand(self) -> bool:\n        \"\"\"Setting a non-None self.width implies expand.\"\"\"\n        return self._expand or self.width is not None\n\n    @expand.setter\n    def expand(self, expand: bool) -> None:\n        \"\"\"Set expand.\"\"\"\n        self._expand = expand\n\n    @property\n    def _extra_width(self) -> int:\n        \"\"\"Get extra width to add to cell content.\"\"\"\n        width = 0\n        if self.box and self.show_edge:\n            width += 2\n        if self.box:\n            width += len(self.columns) - 1\n        return width\n\n    @property\n    def row_count(self) -> int:\n        \"\"\"Get the current number of rows.\"\"\"\n        return len(self.rows)\n\n    def get_row_style(self, console: \"Console\", index: int) -> StyleType:\n        \"\"\"Get the current row style.\"\"\"\n        style = Style.null()\n        if self.row_styles:\n            style += console.get_style(self.row_styles[index % len(self.row_styles)])\n        row_style = self.rows[index].style\n        if row_style is not None:\n            style += console.get_style(row_style)\n        return style\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Measurement:\n        max_width = options.max_width\n        if self.width is not None:\n            max_width = self.width\n        if max_width < 0:\n            return Measurement(0, 0)\n\n        extra_width = self._extra_width\n        max_width = sum(\n            self._calculate_column_widths(\n                console, options.update_width(max_width - extra_width)\n            )\n        )\n        _measure_column = self._measure_column\n\n        measurements = [\n            _measure_column(console, options.update_width(max_width), column)\n            for column in self.columns\n        ]\n        minimum_width = (\n            sum(measurement.minimum for measurement in measurements) + extra_width\n        )\n        maximum_width = (\n            sum(measurement.maximum for measurement in measurements) + extra_width\n            if (self.width is None)\n            else self.width\n        )\n        measurement = Measurement(minimum_width, maximum_width)\n        measurement = measurement.clamp(self.min_width)\n        return measurement\n\n    @property\n    def padding(self) -> Tuple[int, int, int, int]:\n        \"\"\"Get cell padding.\"\"\"\n        return self._padding\n\n    @padding.setter\n    def padding(self, padding: PaddingDimensions) -> \"Table\":\n        \"\"\"Set cell padding.\"\"\"\n        self._padding = Padding.unpack(padding)\n        return self\n\n    def add_column(\n        self,\n        header: \"RenderableType\" = \"\",\n        footer: \"RenderableType\" = \"\",\n        *,\n        header_style: Optional[StyleType] = None,\n        footer_style: Optional[StyleType] = None,\n        style: Optional[StyleType] = None,\n        justify: \"JustifyMethod\" = \"left\",\n        vertical: \"VerticalAlignMethod\" = \"top\",\n        overflow: \"OverflowMethod\" = \"ellipsis\",\n        width: Optional[int] = None,\n        min_width: Optional[int] = None,\n        max_width: Optional[int] = None,\n        ratio: Optional[int] = None,\n        no_wrap: bool = False,\n    ) -> None:\n        \"\"\"Add a column to the table.\n\n        Args:\n            header (RenderableType, optional): Text or renderable for the header.\n                Defaults to \"\".\n            footer (RenderableType, optional): Text or renderable for the footer.\n                Defaults to \"\".\n            header_style (Union[str, Style], optional): Style for the header, or None for default. Defaults to None.\n            footer_style (Union[str, Style], optional): Style for the footer, or None for default. Defaults to None.\n            style (Union[str, Style], optional): Style for the column cells, or None for default. Defaults to None.\n            justify (JustifyMethod, optional): Alignment for cells. Defaults to \"left\".\n            vertical (VerticalAlignMethod, optional): Vertical alignment, one of \"top\", \"middle\", or \"bottom\". Defaults to \"top\".\n            overflow (OverflowMethod): Overflow method: \"crop\", \"fold\", \"ellipsis\". Defaults to \"ellipsis\".\n            width (int, optional): Desired width of column in characters, or None to fit to contents. Defaults to None.\n            min_width (Optional[int], optional): Minimum width of column, or ``None`` for no minimum. Defaults to None.\n            max_width (Optional[int], optional): Maximum width of column, or ``None`` for no maximum. Defaults to None.\n            ratio (int, optional): Flexible ratio for the column (requires ``Table.expand`` or ``Table.width``). Defaults to None.\n            no_wrap (bool, optional): Set to ``True`` to disable wrapping of this column.\n        \"\"\"\n\n        column = Column(\n            _index=len(self.columns),\n            header=header,\n            footer=footer,\n            header_style=header_style or \"\",\n            footer_style=footer_style or \"\",\n            style=style or \"\",\n            justify=justify,\n            vertical=vertical,\n            overflow=overflow,\n            width=width,\n            min_width=min_width,\n            max_width=max_width,\n            ratio=ratio,\n            no_wrap=no_wrap,\n        )\n        self.columns.append(column)\n\n    def add_row(\n        self,\n        *renderables: Optional[\"RenderableType\"],\n        style: Optional[StyleType] = None,\n        end_section: bool = False,\n    ) -> None:\n        \"\"\"Add a row of renderables.\n\n        Args:\n            *renderables (None or renderable): Each cell in a row must be a renderable object (including str),\n                or ``None`` for a blank cell.\n            style (StyleType, optional): An optional style to apply to the entire row. Defaults to None.\n            end_section (bool, optional): End a section and draw a line. Defaults to False.\n\n        Raises:\n            errors.NotRenderableError: If you add something that can't be rendered.\n        \"\"\"\n\n        def add_cell(column: Column, renderable: \"RenderableType\") -> None:\n            column._cells.append(renderable)\n\n        cell_renderables: List[Optional[\"RenderableType\"]] = list(renderables)\n\n        columns = self.columns\n        if len(cell_renderables) < len(columns):\n            cell_renderables = [\n                *cell_renderables,\n                *[None] * (len(columns) - len(cell_renderables)),\n            ]\n        for index, renderable in enumerate(cell_renderables):\n            if index == len(columns):\n                column = Column(_index=index)\n                for _ in self.rows:\n                    add_cell(column, Text(\"\"))\n                self.columns.append(column)\n            else:\n                column = columns[index]\n            if renderable is None:\n                add_cell(column, \"\")\n            elif is_renderable(renderable):\n                add_cell(column, renderable)\n            else:\n                raise errors.NotRenderableError(\n                    f\"unable to render {type(renderable).__name__}; a string or other renderable object is required\"\n                )\n        self.rows.append(Row(style=style, end_section=end_section))\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n\n        if not self.columns:\n            yield Segment(\"\\n\")\n            return\n\n        max_width = options.max_width\n        if self.width is not None:\n            max_width = self.width\n\n        extra_width = self._extra_width\n        widths = self._calculate_column_widths(\n            console, options.update_width(max_width - extra_width)\n        )\n        table_width = sum(widths) + extra_width\n\n        render_options = options.update(\n            width=table_width, highlight=self.highlight, height=None\n        )\n\n        def render_annotation(\n            text: TextType, style: StyleType, justify: \"JustifyMethod\" = \"center\"\n        ) -> \"RenderResult\":\n            render_text = (\n                console.render_str(text, style=style, highlight=False)\n                if isinstance(text, str)\n                else text\n            )\n            return console.render(\n                render_text, options=render_options.update(justify=justify)\n            )\n\n        if self.title:\n            yield from render_annotation(\n                self.title,\n                style=Style.pick_first(self.title_style, \"table.title\"),\n                justify=self.title_justify,\n            )\n        yield from self._render(console, render_options, widths)\n        if self.caption:\n            yield from render_annotation(\n                self.caption,\n                style=Style.pick_first(self.caption_style, \"table.caption\"),\n                justify=self.caption_justify,\n            )\n\n    def _calculate_column_widths(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> List[int]:\n        \"\"\"Calculate the widths of each column, including padding, not including borders.\"\"\"\n        max_width = options.max_width\n        columns = self.columns\n        width_ranges = [\n            self._measure_column(console, options, column) for column in columns\n        ]\n        widths = [_range.maximum or 1 for _range in width_ranges]\n        get_padding_width = self._get_padding_width\n        extra_width = self._extra_width\n        if self.expand:\n            ratios = [col.ratio or 0 for col in columns if col.flexible]\n            if any(ratios):\n                fixed_widths = [\n                    0 if column.flexible else _range.maximum\n                    for _range, column in zip(width_ranges, columns)\n                ]\n                flex_minimum = [\n                    (column.width or 1) + get_padding_width(column._index)\n                    for column in columns\n                    if column.flexible\n                ]\n                flexible_width = max_width - sum(fixed_widths)\n                flex_widths = ratio_distribute(flexible_width, ratios, flex_minimum)\n                iter_flex_widths = iter(flex_widths)\n                for index, column in enumerate(columns):\n                    if column.flexible:\n                        widths[index] = fixed_widths[index] + next(iter_flex_widths)\n        table_width = sum(widths)\n\n        if table_width > max_width:\n            widths = self._collapse_widths(\n                widths,\n                [(column.width is None and not column.no_wrap) for column in columns],\n                max_width,\n            )\n            table_width = sum(widths)\n            # last resort, reduce columns evenly\n            if table_width > max_width:\n                excess_width = table_width - max_width\n                widths = ratio_reduce(excess_width, [1] * len(widths), widths, widths)\n                table_width = sum(widths)\n\n            width_ranges = [\n                self._measure_column(console, options.update_width(width), column)\n                for width, column in zip(widths, columns)\n            ]\n            widths = [_range.maximum or 0 for _range in width_ranges]\n\n        if (table_width < max_width and self.expand) or (\n            self.min_width is not None and table_width < (self.min_width - extra_width)\n        ):\n            _max_width = (\n                max_width\n                if self.min_width is None\n                else min(self.min_width - extra_width, max_width)\n            )\n            pad_widths = ratio_distribute(_max_width - table_width, widths)\n            widths = [_width + pad for _width, pad in zip(widths, pad_widths)]\n\n        return widths\n\n    @classmethod\n    def _collapse_widths(\n        cls, widths: List[int], wrapable: List[bool], max_width: int\n    ) -> List[int]:\n        \"\"\"Reduce widths so that the total is under max_width.\n\n        Args:\n            widths (List[int]): List of widths.\n            wrapable (List[bool]): List of booleans that indicate if a column may shrink.\n            max_width (int): Maximum width to reduce to.\n\n        Returns:\n            List[int]: A new list of widths.\n        \"\"\"\n        total_width = sum(widths)\n        excess_width = total_width - max_width\n        if any(wrapable):\n            while total_width and excess_width > 0:\n                max_column = max(\n                    width for width, allow_wrap in zip(widths, wrapable) if allow_wrap\n                )\n                second_max_column = max(\n                    width if allow_wrap and width != max_column else 0\n                    for width, allow_wrap in zip(widths, wrapable)\n                )\n                column_difference = max_column - second_max_column\n                ratios = [\n                    (1 if (width == max_column and allow_wrap) else 0)\n                    for width, allow_wrap in zip(widths, wrapable)\n                ]\n                if not any(ratios) or not column_difference:\n                    break\n                max_reduce = [min(excess_width, column_difference)] * len(widths)\n                widths = ratio_reduce(excess_width, ratios, max_reduce, widths)\n\n                total_width = sum(widths)\n                excess_width = total_width - max_width\n        return widths\n\n    def _get_cells(\n        self, console: \"Console\", column_index: int, column: Column\n    ) -> Iterable[_Cell]:\n        \"\"\"Get all the cells with padding and optional header.\"\"\"\n\n        collapse_padding = self.collapse_padding\n        pad_edge = self.pad_edge\n        padding = self.padding\n        any_padding = any(padding)\n\n        first_column = column_index == 0\n        last_column = column_index == len(self.columns) - 1\n\n        _padding_cache: Dict[Tuple[bool, bool], Tuple[int, int, int, int]] = {}\n\n        def get_padding(first_row: bool, last_row: bool) -> Tuple[int, int, int, int]:\n            cached = _padding_cache.get((first_row, last_row))\n            if cached:\n                return cached\n            top, right, bottom, left = padding\n\n            if collapse_padding:\n                if not first_column:\n                    left = max(0, left - right)\n                if not last_row:\n                    bottom = max(0, top - bottom)\n\n            if not pad_edge:\n                if first_column:\n                    left = 0\n                if last_column:\n                    right = 0\n                if first_row:\n                    top = 0\n                if last_row:\n                    bottom = 0\n            _padding = (top, right, bottom, left)\n            _padding_cache[(first_row, last_row)] = _padding\n            return _padding\n\n        raw_cells: List[Tuple[StyleType, \"RenderableType\"]] = []\n        _append = raw_cells.append\n        get_style = console.get_style\n        if self.show_header:\n            header_style = get_style(self.header_style or \"\") + get_style(\n                column.header_style\n            )\n            _append((header_style, column.header))\n        cell_style = get_style(column.style or \"\")\n        for cell in column.cells:\n            _append((cell_style, cell))\n        if self.show_footer:\n            footer_style = get_style(self.footer_style or \"\") + get_style(\n                column.footer_style\n            )\n            _append((footer_style, column.footer))\n\n        if any_padding:\n            _Padding = Padding\n            for first, last, (style, renderable) in loop_first_last(raw_cells):\n                yield _Cell(\n                    style,\n                    _Padding(renderable, get_padding(first, last)),\n                    getattr(renderable, \"vertical\", None) or column.vertical,\n                )\n        else:\n            for (style, renderable) in raw_cells:\n                yield _Cell(\n                    style,\n                    renderable,\n                    getattr(renderable, \"vertical\", None) or column.vertical,\n                )\n\n    def _get_padding_width(self, column_index: int) -> int:\n        \"\"\"Get extra width from padding.\"\"\"\n        _, pad_right, _, pad_left = self.padding\n        if self.collapse_padding:\n            if column_index > 0:\n                pad_left = max(0, pad_left - pad_right)\n        return pad_left + pad_right\n\n    def _measure_column(\n        self,\n        console: \"Console\",\n        options: \"ConsoleOptions\",\n        column: Column,\n    ) -> Measurement:\n        \"\"\"Get the minimum and maximum width of the column.\"\"\"\n\n        max_width = options.max_width\n        if max_width < 1:\n            return Measurement(0, 0)\n\n        padding_width = self._get_padding_width(column._index)\n\n        if column.width is not None:\n            # Fixed width column\n            return Measurement(\n                column.width + padding_width, column.width + padding_width\n            ).with_maximum(max_width)\n        # Flexible column, we need to measure contents\n        min_widths: List[int] = []\n        max_widths: List[int] = []\n        append_min = min_widths.append\n        append_max = max_widths.append\n        get_render_width = Measurement.get\n        for cell in self._get_cells(console, column._index, column):\n            _min, _max = get_render_width(console, options, cell.renderable)\n            append_min(_min)\n            append_max(_max)\n\n        measurement = Measurement(\n            max(min_widths) if min_widths else 1,\n            max(max_widths) if max_widths else max_width,\n        ).with_maximum(max_width)\n        measurement = measurement.clamp(\n            None if column.min_width is None else column.min_width + padding_width,\n            None if column.max_width is None else column.max_width + padding_width,\n        )\n        return measurement\n\n    def _render(\n        self, console: \"Console\", options: \"ConsoleOptions\", widths: List[int]\n    ) -> \"RenderResult\":\n        table_style = console.get_style(self.style or \"\")\n\n        border_style = table_style + console.get_style(self.border_style or \"\")\n        _column_cells = (\n            self._get_cells(console, column_index, column)\n            for column_index, column in enumerate(self.columns)\n        )\n        row_cells: List[Tuple[_Cell, ...]] = list(zip(*_column_cells))\n        _box = (\n            self.box.substitute(\n                options, safe=pick_bool(self.safe_box, console.safe_box)\n            )\n            if self.box\n            else None\n        )\n        _box = _box.get_plain_headed_box() if _box and not self.show_header else _box\n\n        new_line = Segment.line()\n\n        columns = self.columns\n        show_header = self.show_header\n        show_footer = self.show_footer\n        show_edge = self.show_edge\n        show_lines = self.show_lines\n        leading = self.leading\n\n        _Segment = Segment\n        if _box:\n            box_segments = [\n                (\n                    _Segment(_box.head_left, border_style),\n                    _Segment(_box.head_right, border_style),\n                    _Segment(_box.head_vertical, border_style),\n                ),\n                (\n                    _Segment(_box.foot_left, border_style),\n                    _Segment(_box.foot_right, border_style),\n                    _Segment(_box.foot_vertical, border_style),\n                ),\n                (\n                    _Segment(_box.mid_left, border_style),\n                    _Segment(_box.mid_right, border_style),\n                    _Segment(_box.mid_vertical, border_style),\n                ),\n            ]\n            if show_edge:\n                yield _Segment(_box.get_top(widths), border_style)\n                yield new_line\n        else:\n            box_segments = []\n\n        get_row_style = self.get_row_style\n        get_style = console.get_style\n\n        for index, (first, last, row_cell) in enumerate(loop_first_last(row_cells)):\n            header_row = first and show_header\n            footer_row = last and show_footer\n            row = (\n                self.rows[index - show_header]\n                if (not header_row and not footer_row)\n                else None\n            )\n            max_height = 1\n            cells: List[List[List[Segment]]] = []\n            if header_row or footer_row:\n                row_style = Style.null()\n            else:\n                row_style = get_style(\n                    get_row_style(console, index - 1 if show_header else index)\n                )\n            for width, cell, column in zip(widths, row_cell, columns):\n                render_options = options.update(\n                    width=width,\n                    justify=column.justify,\n                    no_wrap=column.no_wrap,\n                    overflow=column.overflow,\n                    height=None,\n                )\n                lines = console.render_lines(\n                    cell.renderable,\n                    render_options,\n                    style=get_style(cell.style) + row_style,\n                )\n                max_height = max(max_height, len(lines))\n                cells.append(lines)\n\n            row_height = max(len(cell) for cell in cells)\n\n            def align_cell(\n                cell: List[List[Segment]],\n                vertical: \"VerticalAlignMethod\",\n                width: int,\n                style: Style,\n            ) -> List[List[Segment]]:\n                if header_row:\n                    vertical = \"bottom\"\n                elif footer_row:\n                    vertical = \"top\"\n\n                if vertical == \"top\":\n                    return _Segment.align_top(cell, width, row_height, style)\n                elif vertical == \"middle\":\n                    return _Segment.align_middle(cell, width, row_height, style)\n                return _Segment.align_bottom(cell, width, row_height, style)\n\n            cells[:] = [\n                _Segment.set_shape(\n                    align_cell(\n                        cell,\n                        _cell.vertical,\n                        width,\n                        get_style(_cell.style) + row_style,\n                    ),\n                    width,\n                    max_height,\n                )\n                for width, _cell, cell, column in zip(widths, row_cell, cells, columns)\n            ]\n\n            if _box:\n                if last and show_footer:\n                    yield _Segment(\n                        _box.get_row(widths, \"foot\", edge=show_edge), border_style\n                    )\n                    yield new_line\n                left, right, _divider = box_segments[0 if first else (2 if last else 1)]\n\n                # If the column divider is whitespace also style it with the row background\n                divider = (\n                    _divider\n                    if _divider.text.strip()\n                    else _Segment(\n                        _divider.text, row_style.background_style + _divider.style\n                    )\n                )\n                for line_no in range(max_height):\n                    if show_edge:\n                        yield left\n                    for last_cell, rendered_cell in loop_last(cells):\n                        yield from rendered_cell[line_no]\n                        if not last_cell:\n                            yield divider\n                    if show_edge:\n                        yield right\n                    yield new_line\n            else:\n                for line_no in range(max_height):\n                    for rendered_cell in cells:\n                        yield from rendered_cell[line_no]\n                    yield new_line\n            if _box and first and show_header:\n                yield _Segment(\n                    _box.get_row(widths, \"head\", edge=show_edge), border_style\n                )\n                yield new_line\n            end_section = row and row.end_section\n            if _box and (show_lines or leading or end_section):\n                if (\n                    not last\n                    and not (show_footer and index >= len(row_cells) - 2)\n                    and not (show_header and header_row)\n                ):\n                    if leading:\n                        yield _Segment(\n                            _box.get_row(widths, \"mid\", edge=show_edge) * leading,\n                            border_style,\n                        )\n                    else:\n                        yield _Segment(\n                            _box.get_row(widths, \"row\", edge=show_edge), border_style\n                        )\n                    yield new_line\n\n        if _box and show_edge:\n            yield _Segment(_box.get_bottom(widths), border_style)\n            yield new_line\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.console import Console\n    from pip._vendor.rich.highlighter import ReprHighlighter\n    from pip._vendor.rich.table import Table as Table\n\n    from ._timer import timer\n\n    with timer(\"Table render\"):\n        table = Table(\n            title=\"Star Wars Movies\",\n            caption=\"Rich example table\",\n            caption_justify=\"right\",\n        )\n\n        table.add_column(\n            \"Released\", header_style=\"bright_cyan\", style=\"cyan\", no_wrap=True\n        )\n        table.add_column(\"Title\", style=\"magenta\")\n        table.add_column(\"Box Office\", justify=\"right\", style=\"green\")\n\n        table.add_row(\n            \"Dec 20, 2019\",\n            \"Star Wars: The Rise of Skywalker\",\n            \"$952,110,690\",\n        )\n        table.add_row(\"May 25, 2018\", \"Solo: A Star Wars Story\", \"$393,151,347\")\n        table.add_row(\n            \"Dec 15, 2017\",\n            \"Star Wars Ep. V111: The Last Jedi\",\n            \"$1,332,539,889\",\n            style=\"on black\",\n            end_section=True,\n        )\n        table.add_row(\n            \"Dec 16, 2016\",\n            \"Rogue One: A Star Wars Story\",\n            \"$1,332,439,889\",\n        )\n\n        def header(text: str) -> None:\n            console.print()\n            console.rule(highlight(text))\n            console.print()\n\n        console = Console()\n        highlight = ReprHighlighter()\n        header(\"Example Table\")\n        console.print(table, justify=\"center\")\n\n        table.expand = True\n        header(\"expand=True\")\n        console.print(table)\n\n        table.width = 50\n        header(\"width=50\")\n\n        console.print(table, justify=\"center\")\n\n        table.width = None\n        table.expand = False\n        table.row_styles = [\"dim\", \"none\"]\n        header(\"row_styles=['dim', 'none']\")\n\n        console.print(table, justify=\"center\")\n\n        table.width = None\n        table.expand = False\n        table.row_styles = [\"dim\", \"none\"]\n        table.leading = 1\n        header(\"leading=1, row_styles=['dim', 'none']\")\n        console.print(table, justify=\"center\")\n\n        table.width = None\n        table.expand = False\n        table.row_styles = [\"dim\", \"none\"]\n        table.show_lines = True\n        table.leading = 0\n        header(\"show_lines=True, row_styles=['dim', 'none']\")\n        console.print(table, justify=\"center\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/terminal_theme.py",
    "content": "from typing import List, Optional, Tuple\n\nfrom .color_triplet import ColorTriplet\nfrom .palette import Palette\n\n_ColorTuple = Tuple[int, int, int]\n\n\nclass TerminalTheme:\n    \"\"\"A color theme used when exporting console content.\n\n    Args:\n        background (Tuple[int, int, int]): The background color.\n        foreground (Tuple[int, int, int]): The foreground (text) color.\n        normal (List[Tuple[int, int, int]]): A list of 8 normal intensity colors.\n        bright (List[Tuple[int, int, int]], optional): A list of 8 bright colors, or None\n            to repeat normal intensity. Defaults to None.\n    \"\"\"\n\n    def __init__(\n        self,\n        background: _ColorTuple,\n        foreground: _ColorTuple,\n        normal: List[_ColorTuple],\n        bright: Optional[List[_ColorTuple]] = None,\n    ) -> None:\n        self.background_color = ColorTriplet(*background)\n        self.foreground_color = ColorTriplet(*foreground)\n        self.ansi_colors = Palette(normal + (bright or normal))\n\n\nDEFAULT_TERMINAL_THEME = TerminalTheme(\n    (255, 255, 255),\n    (0, 0, 0),\n    [\n        (0, 0, 0),\n        (128, 0, 0),\n        (0, 128, 0),\n        (128, 128, 0),\n        (0, 0, 128),\n        (128, 0, 128),\n        (0, 128, 128),\n        (192, 192, 192),\n    ],\n    [\n        (128, 128, 128),\n        (255, 0, 0),\n        (0, 255, 0),\n        (255, 255, 0),\n        (0, 0, 255),\n        (255, 0, 255),\n        (0, 255, 255),\n        (255, 255, 255),\n    ],\n)\n\nMONOKAI = TerminalTheme(\n    (12, 12, 12),\n    (217, 217, 217),\n    [\n        (26, 26, 26),\n        (244, 0, 95),\n        (152, 224, 36),\n        (253, 151, 31),\n        (157, 101, 255),\n        (244, 0, 95),\n        (88, 209, 235),\n        (196, 197, 181),\n        (98, 94, 76),\n    ],\n    [\n        (244, 0, 95),\n        (152, 224, 36),\n        (224, 213, 97),\n        (157, 101, 255),\n        (244, 0, 95),\n        (88, 209, 235),\n        (246, 246, 239),\n    ],\n)\nDIMMED_MONOKAI = TerminalTheme(\n    (25, 25, 25),\n    (185, 188, 186),\n    [\n        (58, 61, 67),\n        (190, 63, 72),\n        (135, 154, 59),\n        (197, 166, 53),\n        (79, 118, 161),\n        (133, 92, 141),\n        (87, 143, 164),\n        (185, 188, 186),\n        (136, 137, 135),\n    ],\n    [\n        (251, 0, 31),\n        (15, 114, 47),\n        (196, 112, 51),\n        (24, 109, 227),\n        (251, 0, 103),\n        (46, 112, 109),\n        (253, 255, 185),\n    ],\n)\nNIGHT_OWLISH = TerminalTheme(\n    (255, 255, 255),\n    (64, 63, 83),\n    [\n        (1, 22, 39),\n        (211, 66, 62),\n        (42, 162, 152),\n        (218, 170, 1),\n        (72, 118, 214),\n        (64, 63, 83),\n        (8, 145, 106),\n        (122, 129, 129),\n        (122, 129, 129),\n    ],\n    [\n        (247, 110, 110),\n        (73, 208, 197),\n        (218, 194, 107),\n        (92, 167, 228),\n        (105, 112, 152),\n        (0, 201, 144),\n        (152, 159, 177),\n    ],\n)\n\nSVG_EXPORT_THEME = TerminalTheme(\n    (41, 41, 41),\n    (197, 200, 198),\n    [\n        (75, 78, 85),\n        (204, 85, 90),\n        (152, 168, 75),\n        (208, 179, 68),\n        (96, 138, 177),\n        (152, 114, 159),\n        (104, 160, 179),\n        (197, 200, 198),\n        (154, 155, 153),\n    ],\n    [\n        (255, 38, 39),\n        (0, 130, 61),\n        (208, 132, 66),\n        (25, 132, 233),\n        (255, 44, 122),\n        (57, 130, 128),\n        (253, 253, 197),\n    ],\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/text.py",
    "content": "import re\nfrom functools import partial, reduce\nfrom math import gcd\nfrom operator import itemgetter\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Callable,\n    Dict,\n    Iterable,\n    List,\n    NamedTuple,\n    Optional,\n    Tuple,\n    Union,\n)\n\nfrom ._loop import loop_last\nfrom ._pick import pick_bool\nfrom ._wrap import divide_line\nfrom .align import AlignMethod\nfrom .cells import cell_len, set_cell_size\nfrom .containers import Lines\nfrom .control import strip_control_codes\nfrom .emoji import EmojiVariant\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .segment import Segment\nfrom .style import Style, StyleType\n\nif TYPE_CHECKING:  # pragma: no cover\n    from .console import Console, ConsoleOptions, JustifyMethod, OverflowMethod\n\nDEFAULT_JUSTIFY: \"JustifyMethod\" = \"default\"\nDEFAULT_OVERFLOW: \"OverflowMethod\" = \"fold\"\n\n\n_re_whitespace = re.compile(r\"\\s+$\")\n\nTextType = Union[str, \"Text\"]\n\nGetStyleCallable = Callable[[str], Optional[StyleType]]\n\n\nclass Span(NamedTuple):\n    \"\"\"A marked up region in some text.\"\"\"\n\n    start: int\n    \"\"\"Span start index.\"\"\"\n    end: int\n    \"\"\"Span end index.\"\"\"\n    style: Union[str, Style]\n    \"\"\"Style associated with the span.\"\"\"\n\n    def __repr__(self) -> str:\n        return (\n            f\"Span({self.start}, {self.end}, {self.style!r})\"\n            if (isinstance(self.style, Style) and self.style._meta)\n            else f\"Span({self.start}, {self.end}, {repr(self.style)})\"\n        )\n\n    def __bool__(self) -> bool:\n        return self.end > self.start\n\n    def split(self, offset: int) -> Tuple[\"Span\", Optional[\"Span\"]]:\n        \"\"\"Split a span in to 2 from a given offset.\"\"\"\n\n        if offset < self.start:\n            return self, None\n        if offset >= self.end:\n            return self, None\n\n        start, end, style = self\n        span1 = Span(start, min(end, offset), style)\n        span2 = Span(span1.end, end, style)\n        return span1, span2\n\n    def move(self, offset: int) -> \"Span\":\n        \"\"\"Move start and end by a given offset.\n\n        Args:\n            offset (int): Number of characters to add to start and end.\n\n        Returns:\n            TextSpan: A new TextSpan with adjusted position.\n        \"\"\"\n        start, end, style = self\n        return Span(start + offset, end + offset, style)\n\n    def right_crop(self, offset: int) -> \"Span\":\n        \"\"\"Crop the span at the given offset.\n\n        Args:\n            offset (int): A value between start and end.\n\n        Returns:\n            Span: A new (possibly smaller) span.\n        \"\"\"\n        start, end, style = self\n        if offset >= end:\n            return self\n        return Span(start, min(offset, end), style)\n\n\nclass Text(JupyterMixin):\n    \"\"\"Text with color / style.\n\n    Args:\n        text (str, optional): Default unstyled text. Defaults to \"\".\n        style (Union[str, Style], optional): Base style for text. Defaults to \"\".\n        justify (str, optional): Justify method: \"left\", \"center\", \"full\", \"right\". Defaults to None.\n        overflow (str, optional): Overflow method: \"crop\", \"fold\", \"ellipsis\". Defaults to None.\n        no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.\n        end (str, optional): Character to end text with. Defaults to \"\\\\\\\\n\".\n        tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to 8.\n        spans (List[Span], optional). A list of predefined style spans. Defaults to None.\n    \"\"\"\n\n    __slots__ = [\n        \"_text\",\n        \"style\",\n        \"justify\",\n        \"overflow\",\n        \"no_wrap\",\n        \"end\",\n        \"tab_size\",\n        \"_spans\",\n        \"_length\",\n    ]\n\n    def __init__(\n        self,\n        text: str = \"\",\n        style: Union[str, Style] = \"\",\n        *,\n        justify: Optional[\"JustifyMethod\"] = None,\n        overflow: Optional[\"OverflowMethod\"] = None,\n        no_wrap: Optional[bool] = None,\n        end: str = \"\\n\",\n        tab_size: Optional[int] = 8,\n        spans: Optional[List[Span]] = None,\n    ) -> None:\n        sanitized_text = strip_control_codes(text)\n        self._text = [sanitized_text]\n        self.style = style\n        self.justify: Optional[\"JustifyMethod\"] = justify\n        self.overflow: Optional[\"OverflowMethod\"] = overflow\n        self.no_wrap = no_wrap\n        self.end = end\n        self.tab_size = tab_size\n        self._spans: List[Span] = spans or []\n        self._length: int = len(sanitized_text)\n\n    def __len__(self) -> int:\n        return self._length\n\n    def __bool__(self) -> bool:\n        return bool(self._length)\n\n    def __str__(self) -> str:\n        return self.plain\n\n    def __repr__(self) -> str:\n        return f\"<text {self.plain!r} {self._spans!r}>\"\n\n    def __add__(self, other: Any) -> \"Text\":\n        if isinstance(other, (str, Text)):\n            result = self.copy()\n            result.append(other)\n            return result\n        return NotImplemented\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Text):\n            return NotImplemented\n        return self.plain == other.plain and self._spans == other._spans\n\n    def __contains__(self, other: object) -> bool:\n        if isinstance(other, str):\n            return other in self.plain\n        elif isinstance(other, Text):\n            return other.plain in self.plain\n        return False\n\n    def __getitem__(self, slice: Union[int, slice]) -> \"Text\":\n        def get_text_at(offset: int) -> \"Text\":\n            _Span = Span\n            text = Text(\n                self.plain[offset],\n                spans=[\n                    _Span(0, 1, style)\n                    for start, end, style in self._spans\n                    if end > offset >= start\n                ],\n                end=\"\",\n            )\n            return text\n\n        if isinstance(slice, int):\n            return get_text_at(slice)\n        else:\n            start, stop, step = slice.indices(len(self.plain))\n            if step == 1:\n                lines = self.divide([start, stop])\n                return lines[1]\n            else:\n                # This would be a bit of work to implement efficiently\n                # For now, its not required\n                raise TypeError(\"slices with step!=1 are not supported\")\n\n    @property\n    def cell_len(self) -> int:\n        \"\"\"Get the number of cells required to render this text.\"\"\"\n        return cell_len(self.plain)\n\n    @property\n    def markup(self) -> str:\n        \"\"\"Get console markup to render this Text.\n\n        Returns:\n            str: A string potentially creating markup tags.\n        \"\"\"\n        from .markup import escape\n\n        output: List[str] = []\n\n        plain = self.plain\n        markup_spans = [\n            (0, False, self.style),\n            *((span.start, False, span.style) for span in self._spans),\n            *((span.end, True, span.style) for span in self._spans),\n            (len(plain), True, self.style),\n        ]\n        markup_spans.sort(key=itemgetter(0, 1))\n        position = 0\n        append = output.append\n        for offset, closing, style in markup_spans:\n            if offset > position:\n                append(escape(plain[position:offset]))\n                position = offset\n            if style:\n                append(f\"[/{style}]\" if closing else f\"[{style}]\")\n        markup = \"\".join(output)\n        return markup\n\n    @classmethod\n    def from_markup(\n        cls,\n        text: str,\n        *,\n        style: Union[str, Style] = \"\",\n        emoji: bool = True,\n        emoji_variant: Optional[EmojiVariant] = None,\n        justify: Optional[\"JustifyMethod\"] = None,\n        overflow: Optional[\"OverflowMethod\"] = None,\n        end: str = \"\\n\",\n    ) -> \"Text\":\n        \"\"\"Create Text instance from markup.\n\n        Args:\n            text (str): A string containing console markup.\n            emoji (bool, optional): Also render emoji code. Defaults to True.\n            justify (str, optional): Justify method: \"left\", \"center\", \"full\", \"right\". Defaults to None.\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", \"ellipsis\". Defaults to None.\n            end (str, optional): Character to end text with. Defaults to \"\\\\\\\\n\".\n\n        Returns:\n            Text: A Text instance with markup rendered.\n        \"\"\"\n        from .markup import render\n\n        rendered_text = render(text, style, emoji=emoji, emoji_variant=emoji_variant)\n        rendered_text.justify = justify\n        rendered_text.overflow = overflow\n        rendered_text.end = end\n        return rendered_text\n\n    @classmethod\n    def from_ansi(\n        cls,\n        text: str,\n        *,\n        style: Union[str, Style] = \"\",\n        justify: Optional[\"JustifyMethod\"] = None,\n        overflow: Optional[\"OverflowMethod\"] = None,\n        no_wrap: Optional[bool] = None,\n        end: str = \"\\n\",\n        tab_size: Optional[int] = 8,\n    ) -> \"Text\":\n        \"\"\"Create a Text object from a string containing ANSI escape codes.\n\n        Args:\n            text (str): A string containing escape codes.\n            style (Union[str, Style], optional): Base style for text. Defaults to \"\".\n            justify (str, optional): Justify method: \"left\", \"center\", \"full\", \"right\". Defaults to None.\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", \"ellipsis\". Defaults to None.\n            no_wrap (bool, optional): Disable text wrapping, or None for default. Defaults to None.\n            end (str, optional): Character to end text with. Defaults to \"\\\\\\\\n\".\n            tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to 8.\n        \"\"\"\n        from .ansi import AnsiDecoder\n\n        joiner = Text(\n            \"\\n\",\n            justify=justify,\n            overflow=overflow,\n            no_wrap=no_wrap,\n            end=end,\n            tab_size=tab_size,\n            style=style,\n        )\n        decoder = AnsiDecoder()\n        result = joiner.join(line for line in decoder.decode(text))\n        return result\n\n    @classmethod\n    def styled(\n        cls,\n        text: str,\n        style: StyleType = \"\",\n        *,\n        justify: Optional[\"JustifyMethod\"] = None,\n        overflow: Optional[\"OverflowMethod\"] = None,\n    ) -> \"Text\":\n        \"\"\"Construct a Text instance with a pre-applied styled. A style applied in this way won't be used\n        to pad the text when it is justified.\n\n        Args:\n            text (str): A string containing console markup.\n            style (Union[str, Style]): Style to apply to the text. Defaults to \"\".\n            justify (str, optional): Justify method: \"left\", \"center\", \"full\", \"right\". Defaults to None.\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", \"ellipsis\". Defaults to None.\n\n        Returns:\n            Text: A text instance with a style applied to the entire string.\n        \"\"\"\n        styled_text = cls(text, justify=justify, overflow=overflow)\n        styled_text.stylize(style)\n        return styled_text\n\n    @classmethod\n    def assemble(\n        cls,\n        *parts: Union[str, \"Text\", Tuple[str, StyleType]],\n        style: Union[str, Style] = \"\",\n        justify: Optional[\"JustifyMethod\"] = None,\n        overflow: Optional[\"OverflowMethod\"] = None,\n        no_wrap: Optional[bool] = None,\n        end: str = \"\\n\",\n        tab_size: int = 8,\n        meta: Optional[Dict[str, Any]] = None,\n    ) -> \"Text\":\n        \"\"\"Construct a text instance by combining a sequence of strings with optional styles.\n        The positional arguments should be either strings, or a tuple of string + style.\n\n        Args:\n            style (Union[str, Style], optional): Base style for text. Defaults to \"\".\n            justify (str, optional): Justify method: \"left\", \"center\", \"full\", \"right\". Defaults to None.\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", \"ellipsis\". Defaults to None.\n            end (str, optional): Character to end text with. Defaults to \"\\\\\\\\n\".\n            tab_size (int): Number of spaces per tab, or ``None`` to use ``console.tab_size``. Defaults to 8.\n            meta (Dict[str, Any], optional). Meta data to apply to text, or None for no meta data. Default to None\n\n        Returns:\n            Text: A new text instance.\n        \"\"\"\n        text = cls(\n            style=style,\n            justify=justify,\n            overflow=overflow,\n            no_wrap=no_wrap,\n            end=end,\n            tab_size=tab_size,\n        )\n        append = text.append\n        _Text = Text\n        for part in parts:\n            if isinstance(part, (_Text, str)):\n                append(part)\n            else:\n                append(*part)\n        if meta:\n            text.apply_meta(meta)\n        return text\n\n    @property\n    def plain(self) -> str:\n        \"\"\"Get the text as a single string.\"\"\"\n        if len(self._text) != 1:\n            self._text[:] = [\"\".join(self._text)]\n        return self._text[0]\n\n    @plain.setter\n    def plain(self, new_text: str) -> None:\n        \"\"\"Set the text to a new value.\"\"\"\n        if new_text != self.plain:\n            sanitized_text = strip_control_codes(new_text)\n            self._text[:] = [sanitized_text]\n            old_length = self._length\n            self._length = len(sanitized_text)\n            if old_length > self._length:\n                self._trim_spans()\n\n    @property\n    def spans(self) -> List[Span]:\n        \"\"\"Get a reference to the internal list of spans.\"\"\"\n        return self._spans\n\n    @spans.setter\n    def spans(self, spans: List[Span]) -> None:\n        \"\"\"Set spans.\"\"\"\n        self._spans = spans[:]\n\n    def blank_copy(self, plain: str = \"\") -> \"Text\":\n        \"\"\"Return a new Text instance with copied meta data (but not the string or spans).\"\"\"\n        copy_self = Text(\n            plain,\n            style=self.style,\n            justify=self.justify,\n            overflow=self.overflow,\n            no_wrap=self.no_wrap,\n            end=self.end,\n            tab_size=self.tab_size,\n        )\n        return copy_self\n\n    def copy(self) -> \"Text\":\n        \"\"\"Return a copy of this instance.\"\"\"\n        copy_self = Text(\n            self.plain,\n            style=self.style,\n            justify=self.justify,\n            overflow=self.overflow,\n            no_wrap=self.no_wrap,\n            end=self.end,\n            tab_size=self.tab_size,\n        )\n        copy_self._spans[:] = self._spans\n        return copy_self\n\n    def stylize(\n        self,\n        style: Union[str, Style],\n        start: int = 0,\n        end: Optional[int] = None,\n    ) -> None:\n        \"\"\"Apply a style to the text, or a portion of the text.\n\n        Args:\n            style (Union[str, Style]): Style instance or style definition to apply.\n            start (int): Start offset (negative indexing is supported). Defaults to 0.\n            end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.\n\n        \"\"\"\n        if style:\n            length = len(self)\n            if start < 0:\n                start = length + start\n            if end is None:\n                end = length\n            if end < 0:\n                end = length + end\n            if start >= length or end <= start:\n                # Span not in text or not valid\n                return\n            self._spans.append(Span(start, min(length, end), style))\n\n    def apply_meta(\n        self, meta: Dict[str, Any], start: int = 0, end: Optional[int] = None\n    ) -> None:\n        \"\"\"Apply meta data to the text, or a portion of the text.\n\n        Args:\n            meta (Dict[str, Any]): A dict of meta information.\n            start (int): Start offset (negative indexing is supported). Defaults to 0.\n            end (Optional[int], optional): End offset (negative indexing is supported), or None for end of text. Defaults to None.\n\n        \"\"\"\n        style = Style.from_meta(meta)\n        self.stylize(style, start=start, end=end)\n\n    def on(self, meta: Optional[Dict[str, Any]] = None, **handlers: Any) -> \"Text\":\n        \"\"\"Apply event handlers (used by Textual project).\n\n        Example:\n            >>> from rich.text import Text\n            >>> text = Text(\"hello world\")\n            >>> text.on(click=\"view.toggle('world')\")\n\n        Args:\n            meta (Dict[str, Any]): Mapping of meta information.\n            **handlers: Keyword args are prefixed with \"@\" to defined handlers.\n\n        Returns:\n            Text: Self is returned to method may be chained.\n        \"\"\"\n        meta = {} if meta is None else meta\n        meta.update({f\"@{key}\": value for key, value in handlers.items()})\n        self.stylize(Style.from_meta(meta))\n        return self\n\n    def remove_suffix(self, suffix: str) -> None:\n        \"\"\"Remove a suffix if it exists.\n\n        Args:\n            suffix (str): Suffix to remove.\n        \"\"\"\n        if self.plain.endswith(suffix):\n            self.right_crop(len(suffix))\n\n    def get_style_at_offset(self, console: \"Console\", offset: int) -> Style:\n        \"\"\"Get the style of a character at give offset.\n\n        Args:\n            console (~Console): Console where text will be rendered.\n            offset (int): Offset in to text (negative indexing supported)\n\n        Returns:\n            Style: A Style instance.\n        \"\"\"\n        # TODO: This is a little inefficient, it is only used by full justify\n        if offset < 0:\n            offset = len(self) + offset\n        get_style = console.get_style\n        style = get_style(self.style).copy()\n        for start, end, span_style in self._spans:\n            if end > offset >= start:\n                style += get_style(span_style, default=\"\")\n        return style\n\n    def highlight_regex(\n        self,\n        re_highlight: str,\n        style: Optional[Union[GetStyleCallable, StyleType]] = None,\n        *,\n        style_prefix: str = \"\",\n    ) -> int:\n        \"\"\"Highlight text with a regular expression, where group names are\n        translated to styles.\n\n        Args:\n            re_highlight (str): A regular expression.\n            style (Union[GetStyleCallable, StyleType]): Optional style to apply to whole match, or a callable\n                which accepts the matched text and returns a style. Defaults to None.\n            style_prefix (str, optional): Optional prefix to add to style group names.\n\n        Returns:\n            int: Number of regex matches\n        \"\"\"\n        count = 0\n        append_span = self._spans.append\n        _Span = Span\n        plain = self.plain\n        for match in re.finditer(re_highlight, plain):\n            get_span = match.span\n            if style:\n                start, end = get_span()\n                match_style = style(plain[start:end]) if callable(style) else style\n                if match_style is not None and end > start:\n                    append_span(_Span(start, end, match_style))\n\n            count += 1\n            for name in match.groupdict().keys():\n                start, end = get_span(name)\n                if start != -1 and end > start:\n                    append_span(_Span(start, end, f\"{style_prefix}{name}\"))\n        return count\n\n    def highlight_words(\n        self,\n        words: Iterable[str],\n        style: Union[str, Style],\n        *,\n        case_sensitive: bool = True,\n    ) -> int:\n        \"\"\"Highlight words with a style.\n\n        Args:\n            words (Iterable[str]): Worlds to highlight.\n            style (Union[str, Style]): Style to apply.\n            case_sensitive (bool, optional): Enable case sensitive matchings. Defaults to True.\n\n        Returns:\n            int: Number of words highlighted.\n        \"\"\"\n        re_words = \"|\".join(re.escape(word) for word in words)\n        add_span = self._spans.append\n        count = 0\n        _Span = Span\n        for match in re.finditer(\n            re_words, self.plain, flags=0 if case_sensitive else re.IGNORECASE\n        ):\n            start, end = match.span(0)\n            add_span(_Span(start, end, style))\n            count += 1\n        return count\n\n    def rstrip(self) -> None:\n        \"\"\"Strip whitespace from end of text.\"\"\"\n        self.plain = self.plain.rstrip()\n\n    def rstrip_end(self, size: int) -> None:\n        \"\"\"Remove whitespace beyond a certain width at the end of the text.\n\n        Args:\n            size (int): The desired size of the text.\n        \"\"\"\n        text_length = len(self)\n        if text_length > size:\n            excess = text_length - size\n            whitespace_match = _re_whitespace.search(self.plain)\n            if whitespace_match is not None:\n                whitespace_count = len(whitespace_match.group(0))\n                self.right_crop(min(whitespace_count, excess))\n\n    def set_length(self, new_length: int) -> None:\n        \"\"\"Set new length of the text, clipping or padding is required.\"\"\"\n        length = len(self)\n        if length != new_length:\n            if length < new_length:\n                self.pad_right(new_length - length)\n            else:\n                self.right_crop(length - new_length)\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Iterable[Segment]:\n        tab_size: int = console.tab_size or self.tab_size or 8\n        justify = self.justify or options.justify or DEFAULT_JUSTIFY\n\n        overflow = self.overflow or options.overflow or DEFAULT_OVERFLOW\n\n        lines = self.wrap(\n            console,\n            options.max_width,\n            justify=justify,\n            overflow=overflow,\n            tab_size=tab_size or 8,\n            no_wrap=pick_bool(self.no_wrap, options.no_wrap, False),\n        )\n        all_lines = Text(\"\\n\").join(lines)\n        yield from all_lines.render(console, end=self.end)\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> Measurement:\n        text = self.plain\n        lines = text.splitlines()\n        max_text_width = max(cell_len(line) for line in lines) if lines else 0\n        words = text.split()\n        min_text_width = (\n            max(cell_len(word) for word in words) if words else max_text_width\n        )\n        return Measurement(min_text_width, max_text_width)\n\n    def render(self, console: \"Console\", end: str = \"\") -> Iterable[\"Segment\"]:\n        \"\"\"Render the text as Segments.\n\n        Args:\n            console (Console): Console instance.\n            end (Optional[str], optional): Optional end character.\n\n        Returns:\n            Iterable[Segment]: Result of render that may be written to the console.\n        \"\"\"\n        _Segment = Segment\n        text = self.plain\n        if not self._spans:\n            yield Segment(text)\n            if end:\n                yield _Segment(end)\n            return\n        get_style = partial(console.get_style, default=Style.null())\n\n        enumerated_spans = list(enumerate(self._spans, 1))\n        style_map = {index: get_style(span.style) for index, span in enumerated_spans}\n        style_map[0] = get_style(self.style)\n\n        spans = [\n            (0, False, 0),\n            *((span.start, False, index) for index, span in enumerated_spans),\n            *((span.end, True, index) for index, span in enumerated_spans),\n            (len(text), True, 0),\n        ]\n        spans.sort(key=itemgetter(0, 1))\n\n        stack: List[int] = []\n        stack_append = stack.append\n        stack_pop = stack.remove\n\n        style_cache: Dict[Tuple[Style, ...], Style] = {}\n        style_cache_get = style_cache.get\n        combine = Style.combine\n\n        def get_current_style() -> Style:\n            \"\"\"Construct current style from stack.\"\"\"\n            styles = tuple(style_map[_style_id] for _style_id in sorted(stack))\n            cached_style = style_cache_get(styles)\n            if cached_style is not None:\n                return cached_style\n            current_style = combine(styles)\n            style_cache[styles] = current_style\n            return current_style\n\n        for (offset, leaving, style_id), (next_offset, _, _) in zip(spans, spans[1:]):\n            if leaving:\n                stack_pop(style_id)\n            else:\n                stack_append(style_id)\n            if next_offset > offset:\n                yield _Segment(text[offset:next_offset], get_current_style())\n        if end:\n            yield _Segment(end)\n\n    def join(self, lines: Iterable[\"Text\"]) -> \"Text\":\n        \"\"\"Join text together with this instance as the separator.\n\n        Args:\n            lines (Iterable[Text]): An iterable of Text instances to join.\n\n        Returns:\n            Text: A new text instance containing join text.\n        \"\"\"\n\n        new_text = self.blank_copy()\n\n        def iter_text() -> Iterable[\"Text\"]:\n            if self.plain:\n                for last, line in loop_last(lines):\n                    yield line\n                    if not last:\n                        yield self\n            else:\n                yield from lines\n\n        extend_text = new_text._text.extend\n        append_span = new_text._spans.append\n        extend_spans = new_text._spans.extend\n        offset = 0\n        _Span = Span\n\n        for text in iter_text():\n            extend_text(text._text)\n            if text.style:\n                append_span(_Span(offset, offset + len(text), text.style))\n            extend_spans(\n                _Span(offset + start, offset + end, style)\n                for start, end, style in text._spans\n            )\n            offset += len(text)\n        new_text._length = offset\n        return new_text\n\n    def expand_tabs(self, tab_size: Optional[int] = None) -> None:\n        \"\"\"Converts tabs to spaces.\n\n        Args:\n            tab_size (int, optional): Size of tabs. Defaults to 8.\n\n        \"\"\"\n        if \"\\t\" not in self.plain:\n            return\n        pos = 0\n        if tab_size is None:\n            tab_size = self.tab_size\n        assert tab_size is not None\n        result = self.blank_copy()\n        append = result.append\n\n        _style = self.style\n        for line in self.split(\"\\n\", include_separator=True):\n            parts = line.split(\"\\t\", include_separator=True)\n            for part in parts:\n                if part.plain.endswith(\"\\t\"):\n                    part._text = [part.plain[:-1] + \" \"]\n                    append(part)\n                    pos += len(part)\n                    spaces = tab_size - ((pos - 1) % tab_size) - 1\n                    if spaces:\n                        append(\" \" * spaces, _style)\n                        pos += spaces\n                else:\n                    append(part)\n        self._text = [result.plain]\n        self._length = len(self.plain)\n        self._spans[:] = result._spans\n\n    def truncate(\n        self,\n        max_width: int,\n        *,\n        overflow: Optional[\"OverflowMethod\"] = None,\n        pad: bool = False,\n    ) -> None:\n        \"\"\"Truncate text if it is longer that a given width.\n\n        Args:\n            max_width (int): Maximum number of characters in text.\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", or \"ellipsis\". Defaults to None, to use self.overflow.\n            pad (bool, optional): Pad with spaces if the length is less than max_width. Defaults to False.\n        \"\"\"\n        _overflow = overflow or self.overflow or DEFAULT_OVERFLOW\n        if _overflow != \"ignore\":\n            length = cell_len(self.plain)\n            if length > max_width:\n                if _overflow == \"ellipsis\":\n                    self.plain = set_cell_size(self.plain, max_width - 1) + \"…\"\n                else:\n                    self.plain = set_cell_size(self.plain, max_width)\n            if pad and length < max_width:\n                spaces = max_width - length\n                self._text = [f\"{self.plain}{' ' * spaces}\"]\n                self._length = len(self.plain)\n\n    def _trim_spans(self) -> None:\n        \"\"\"Remove or modify any spans that are over the end of the text.\"\"\"\n        max_offset = len(self.plain)\n        _Span = Span\n        self._spans[:] = [\n            (\n                span\n                if span.end < max_offset\n                else _Span(span.start, min(max_offset, span.end), span.style)\n            )\n            for span in self._spans\n            if span.start < max_offset\n        ]\n\n    def pad(self, count: int, character: str = \" \") -> None:\n        \"\"\"Pad left and right with a given number of characters.\n\n        Args:\n            count (int): Width of padding.\n        \"\"\"\n        assert len(character) == 1, \"Character must be a string of length 1\"\n        if count:\n            pad_characters = character * count\n            self.plain = f\"{pad_characters}{self.plain}{pad_characters}\"\n            _Span = Span\n            self._spans[:] = [\n                _Span(start + count, end + count, style)\n                for start, end, style in self._spans\n            ]\n\n    def pad_left(self, count: int, character: str = \" \") -> None:\n        \"\"\"Pad the left with a given character.\n\n        Args:\n            count (int): Number of characters to pad.\n            character (str, optional): Character to pad with. Defaults to \" \".\n        \"\"\"\n        assert len(character) == 1, \"Character must be a string of length 1\"\n        if count:\n            self.plain = f\"{character * count}{self.plain}\"\n            _Span = Span\n            self._spans[:] = [\n                _Span(start + count, end + count, style)\n                for start, end, style in self._spans\n            ]\n\n    def pad_right(self, count: int, character: str = \" \") -> None:\n        \"\"\"Pad the right with a given character.\n\n        Args:\n            count (int): Number of characters to pad.\n            character (str, optional): Character to pad with. Defaults to \" \".\n        \"\"\"\n        assert len(character) == 1, \"Character must be a string of length 1\"\n        if count:\n            self.plain = f\"{self.plain}{character * count}\"\n\n    def align(self, align: AlignMethod, width: int, character: str = \" \") -> None:\n        \"\"\"Align text to a given width.\n\n        Args:\n            align (AlignMethod): One of \"left\", \"center\", or \"right\".\n            width (int): Desired width.\n            character (str, optional): Character to pad with. Defaults to \" \".\n        \"\"\"\n        self.truncate(width)\n        excess_space = width - cell_len(self.plain)\n        if excess_space:\n            if align == \"left\":\n                self.pad_right(excess_space, character)\n            elif align == \"center\":\n                left = excess_space // 2\n                self.pad_left(left, character)\n                self.pad_right(excess_space - left, character)\n            else:\n                self.pad_left(excess_space, character)\n\n    def append(\n        self, text: Union[\"Text\", str], style: Optional[Union[str, \"Style\"]] = None\n    ) -> \"Text\":\n        \"\"\"Add text with an optional style.\n\n        Args:\n            text (Union[Text, str]): A str or Text to append.\n            style (str, optional): A style name. Defaults to None.\n\n        Returns:\n            Text: Returns self for chaining.\n        \"\"\"\n\n        if not isinstance(text, (str, Text)):\n            raise TypeError(\"Only str or Text can be appended to Text\")\n\n        if len(text):\n            if isinstance(text, str):\n                sanitized_text = strip_control_codes(text)\n                self._text.append(sanitized_text)\n                offset = len(self)\n                text_length = len(sanitized_text)\n                if style is not None:\n                    self._spans.append(Span(offset, offset + text_length, style))\n                self._length += text_length\n            elif isinstance(text, Text):\n                _Span = Span\n                if style is not None:\n                    raise ValueError(\n                        \"style must not be set when appending Text instance\"\n                    )\n                text_length = self._length\n                if text.style is not None:\n                    self._spans.append(\n                        _Span(text_length, text_length + len(text), text.style)\n                    )\n                self._text.append(text.plain)\n                self._spans.extend(\n                    _Span(start + text_length, end + text_length, style)\n                    for start, end, style in text._spans\n                )\n                self._length += len(text)\n        return self\n\n    def append_text(self, text: \"Text\") -> \"Text\":\n        \"\"\"Append another Text instance. This method is more performant that Text.append, but\n        only works for Text.\n\n        Returns:\n            Text: Returns self for chaining.\n        \"\"\"\n        _Span = Span\n        text_length = self._length\n        if text.style is not None:\n            self._spans.append(_Span(text_length, text_length + len(text), text.style))\n        self._text.append(text.plain)\n        self._spans.extend(\n            _Span(start + text_length, end + text_length, style)\n            for start, end, style in text._spans\n        )\n        self._length += len(text)\n        return self\n\n    def append_tokens(\n        self, tokens: Iterable[Tuple[str, Optional[StyleType]]]\n    ) -> \"Text\":\n        \"\"\"Append iterable of str and style. Style may be a Style instance or a str style definition.\n\n        Args:\n            pairs (Iterable[Tuple[str, Optional[StyleType]]]): An iterable of tuples containing str content and style.\n\n        Returns:\n            Text: Returns self for chaining.\n        \"\"\"\n        append_text = self._text.append\n        append_span = self._spans.append\n        _Span = Span\n        offset = len(self)\n        for content, style in tokens:\n            append_text(content)\n            if style is not None:\n                append_span(_Span(offset, offset + len(content), style))\n            offset += len(content)\n        self._length = offset\n        return self\n\n    def copy_styles(self, text: \"Text\") -> None:\n        \"\"\"Copy styles from another Text instance.\n\n        Args:\n            text (Text): A Text instance to copy styles from, must be the same length.\n        \"\"\"\n        self._spans.extend(text._spans)\n\n    def split(\n        self,\n        separator: str = \"\\n\",\n        *,\n        include_separator: bool = False,\n        allow_blank: bool = False,\n    ) -> Lines:\n        \"\"\"Split rich text in to lines, preserving styles.\n\n        Args:\n            separator (str, optional): String to split on. Defaults to \"\\\\\\\\n\".\n            include_separator (bool, optional): Include the separator in the lines. Defaults to False.\n            allow_blank (bool, optional): Return a blank line if the text ends with a separator. Defaults to False.\n\n        Returns:\n            List[RichText]: A list of rich text, one per line of the original.\n        \"\"\"\n        assert separator, \"separator must not be empty\"\n\n        text = self.plain\n        if separator not in text:\n            return Lines([self.copy()])\n\n        if include_separator:\n            lines = self.divide(\n                match.end() for match in re.finditer(re.escape(separator), text)\n            )\n        else:\n\n            def flatten_spans() -> Iterable[int]:\n                for match in re.finditer(re.escape(separator), text):\n                    start, end = match.span()\n                    yield start\n                    yield end\n\n            lines = Lines(\n                line for line in self.divide(flatten_spans()) if line.plain != separator\n            )\n\n        if not allow_blank and text.endswith(separator):\n            lines.pop()\n\n        return lines\n\n    def divide(self, offsets: Iterable[int]) -> Lines:\n        \"\"\"Divide text in to a number of lines at given offsets.\n\n        Args:\n            offsets (Iterable[int]): Offsets used to divide text.\n\n        Returns:\n            Lines: New RichText instances between offsets.\n        \"\"\"\n        _offsets = list(offsets)\n\n        if not _offsets:\n            return Lines([self.copy()])\n\n        text = self.plain\n        text_length = len(text)\n        divide_offsets = [0, *_offsets, text_length]\n        line_ranges = list(zip(divide_offsets, divide_offsets[1:]))\n\n        style = self.style\n        justify = self.justify\n        overflow = self.overflow\n        _Text = Text\n        new_lines = Lines(\n            _Text(\n                text[start:end],\n                style=style,\n                justify=justify,\n                overflow=overflow,\n            )\n            for start, end in line_ranges\n        )\n        if not self._spans:\n            return new_lines\n\n        _line_appends = [line._spans.append for line in new_lines._lines]\n        line_count = len(line_ranges)\n        _Span = Span\n\n        for span_start, span_end, style in self._spans:\n\n            lower_bound = 0\n            upper_bound = line_count\n            start_line_no = (lower_bound + upper_bound) // 2\n\n            while True:\n                line_start, line_end = line_ranges[start_line_no]\n                if span_start < line_start:\n                    upper_bound = start_line_no - 1\n                elif span_start > line_end:\n                    lower_bound = start_line_no + 1\n                else:\n                    break\n                start_line_no = (lower_bound + upper_bound) // 2\n\n            if span_end < line_end:\n                end_line_no = start_line_no\n            else:\n                end_line_no = lower_bound = start_line_no\n                upper_bound = line_count\n\n                while True:\n                    line_start, line_end = line_ranges[end_line_no]\n                    if span_end < line_start:\n                        upper_bound = end_line_no - 1\n                    elif span_end > line_end:\n                        lower_bound = end_line_no + 1\n                    else:\n                        break\n                    end_line_no = (lower_bound + upper_bound) // 2\n\n            for line_no in range(start_line_no, end_line_no + 1):\n                line_start, line_end = line_ranges[line_no]\n                new_start = max(0, span_start - line_start)\n                new_end = min(span_end - line_start, line_end - line_start)\n                if new_end > new_start:\n                    _line_appends[line_no](_Span(new_start, new_end, style))\n\n        return new_lines\n\n    def right_crop(self, amount: int = 1) -> None:\n        \"\"\"Remove a number of characters from the end of the text.\"\"\"\n        max_offset = len(self.plain) - amount\n        _Span = Span\n        self._spans[:] = [\n            (\n                span\n                if span.end < max_offset\n                else _Span(span.start, min(max_offset, span.end), span.style)\n            )\n            for span in self._spans\n            if span.start < max_offset\n        ]\n        self._text = [self.plain[:-amount]]\n        self._length -= amount\n\n    def wrap(\n        self,\n        console: \"Console\",\n        width: int,\n        *,\n        justify: Optional[\"JustifyMethod\"] = None,\n        overflow: Optional[\"OverflowMethod\"] = None,\n        tab_size: int = 8,\n        no_wrap: Optional[bool] = None,\n    ) -> Lines:\n        \"\"\"Word wrap the text.\n\n        Args:\n            console (Console): Console instance.\n            width (int): Number of characters per line.\n            emoji (bool, optional): Also render emoji code. Defaults to True.\n            justify (str, optional): Justify method: \"default\", \"left\", \"center\", \"full\", \"right\". Defaults to \"default\".\n            overflow (str, optional): Overflow method: \"crop\", \"fold\", or \"ellipsis\". Defaults to None.\n            tab_size (int, optional): Default tab size. Defaults to 8.\n            no_wrap (bool, optional): Disable wrapping, Defaults to False.\n\n        Returns:\n            Lines: Number of lines.\n        \"\"\"\n        wrap_justify = justify or self.justify or DEFAULT_JUSTIFY\n        wrap_overflow = overflow or self.overflow or DEFAULT_OVERFLOW\n\n        no_wrap = pick_bool(no_wrap, self.no_wrap, False) or overflow == \"ignore\"\n\n        lines = Lines()\n        for line in self.split(allow_blank=True):\n            if \"\\t\" in line:\n                line.expand_tabs(tab_size)\n            if no_wrap:\n                new_lines = Lines([line])\n            else:\n                offsets = divide_line(str(line), width, fold=wrap_overflow == \"fold\")\n                new_lines = line.divide(offsets)\n            for line in new_lines:\n                line.rstrip_end(width)\n            if wrap_justify:\n                new_lines.justify(\n                    console, width, justify=wrap_justify, overflow=wrap_overflow\n                )\n            for line in new_lines:\n                line.truncate(width, overflow=wrap_overflow)\n            lines.extend(new_lines)\n        return lines\n\n    def fit(self, width: int) -> Lines:\n        \"\"\"Fit the text in to given width by chopping in to lines.\n\n        Args:\n            width (int): Maximum characters in a line.\n\n        Returns:\n            Lines: List of lines.\n        \"\"\"\n        lines: Lines = Lines()\n        append = lines.append\n        for line in self.split():\n            line.set_length(width)\n            append(line)\n        return lines\n\n    def detect_indentation(self) -> int:\n        \"\"\"Auto-detect indentation of code.\n\n        Returns:\n            int: Number of spaces used to indent code.\n        \"\"\"\n\n        _indentations = {\n            len(match.group(1))\n            for match in re.finditer(r\"^( *)(.*)$\", self.plain, flags=re.MULTILINE)\n        }\n\n        try:\n            indentation = (\n                reduce(gcd, [indent for indent in _indentations if not indent % 2]) or 1\n            )\n        except TypeError:\n            indentation = 1\n\n        return indentation\n\n    def with_indent_guides(\n        self,\n        indent_size: Optional[int] = None,\n        *,\n        character: str = \"│\",\n        style: StyleType = \"dim green\",\n    ) -> \"Text\":\n        \"\"\"Adds indent guide lines to text.\n\n        Args:\n            indent_size (Optional[int]): Size of indentation, or None to auto detect. Defaults to None.\n            character (str, optional): Character to use for indentation. Defaults to \"│\".\n            style (Union[Style, str], optional): Style of indent guides.\n\n        Returns:\n            Text: New text with indentation guides.\n        \"\"\"\n\n        _indent_size = self.detect_indentation() if indent_size is None else indent_size\n\n        text = self.copy()\n        text.expand_tabs()\n        indent_line = f\"{character}{' ' * (_indent_size - 1)}\"\n\n        re_indent = re.compile(r\"^( *)(.*)$\")\n        new_lines: List[Text] = []\n        add_line = new_lines.append\n        blank_lines = 0\n        for line in text.split(allow_blank=True):\n            match = re_indent.match(line.plain)\n            if not match or not match.group(2):\n                blank_lines += 1\n                continue\n            indent = match.group(1)\n            full_indents, remaining_space = divmod(len(indent), _indent_size)\n            new_indent = f\"{indent_line * full_indents}{' ' * remaining_space}\"\n            line.plain = new_indent + line.plain[len(new_indent) :]\n            line.stylize(style, 0, len(new_indent))\n            if blank_lines:\n                new_lines.extend([Text(new_indent, style=style)] * blank_lines)\n                blank_lines = 0\n            add_line(line)\n        if blank_lines:\n            new_lines.extend([Text(\"\", style=style)] * blank_lines)\n\n        new_text = text.blank_copy(\"\\n\").join(new_lines)\n        return new_text\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    from pip._vendor.rich.console import Console\n\n    text = Text(\n        \"\"\"\\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\\n\"\"\"\n    )\n    text.highlight_words([\"Lorem\"], \"bold\")\n    text.highlight_words([\"ipsum\"], \"italic\")\n\n    console = Console()\n\n    console.rule(\"justify='left'\")\n    console.print(text, style=\"red\")\n    console.print()\n\n    console.rule(\"justify='center'\")\n    console.print(text, style=\"green\", justify=\"center\")\n    console.print()\n\n    console.rule(\"justify='right'\")\n    console.print(text, style=\"blue\", justify=\"right\")\n    console.print()\n\n    console.rule(\"justify='full'\")\n    console.print(text, style=\"magenta\", justify=\"full\")\n    console.print()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/theme.py",
    "content": "import configparser\nfrom typing import Dict, List, IO, Mapping, Optional\n\nfrom .default_styles import DEFAULT_STYLES\nfrom .style import Style, StyleType\n\n\nclass Theme:\n    \"\"\"A container for style information, used by :class:`~rich.console.Console`.\n\n    Args:\n        styles (Dict[str, Style], optional): A mapping of style names on to styles. Defaults to None for a theme with no styles.\n        inherit (bool, optional): Inherit default styles. Defaults to True.\n    \"\"\"\n\n    styles: Dict[str, Style]\n\n    def __init__(\n        self, styles: Optional[Mapping[str, StyleType]] = None, inherit: bool = True\n    ):\n        self.styles = DEFAULT_STYLES.copy() if inherit else {}\n        if styles is not None:\n            self.styles.update(\n                {\n                    name: style if isinstance(style, Style) else Style.parse(style)\n                    for name, style in styles.items()\n                }\n            )\n\n    @property\n    def config(self) -> str:\n        \"\"\"Get contents of a config file for this theme.\"\"\"\n        config = \"[styles]\\n\" + \"\\n\".join(\n            f\"{name} = {style}\" for name, style in sorted(self.styles.items())\n        )\n        return config\n\n    @classmethod\n    def from_file(\n        cls, config_file: IO[str], source: Optional[str] = None, inherit: bool = True\n    ) -> \"Theme\":\n        \"\"\"Load a theme from a text mode file.\n\n        Args:\n            config_file (IO[str]): An open conf file.\n            source (str, optional): The filename of the open file. Defaults to None.\n            inherit (bool, optional): Inherit default styles. Defaults to True.\n\n        Returns:\n            Theme: A New theme instance.\n        \"\"\"\n        config = configparser.ConfigParser()\n        config.read_file(config_file, source=source)\n        styles = {name: Style.parse(value) for name, value in config.items(\"styles\")}\n        theme = Theme(styles, inherit=inherit)\n        return theme\n\n    @classmethod\n    def read(cls, path: str, inherit: bool = True) -> \"Theme\":\n        \"\"\"Read a theme from a path.\n\n        Args:\n            path (str): Path to a config file readable by Python configparser module.\n            inherit (bool, optional): Inherit default styles. Defaults to True.\n\n        Returns:\n            Theme: A new theme instance.\n        \"\"\"\n        with open(path, \"rt\") as config_file:\n            return cls.from_file(config_file, source=path, inherit=inherit)\n\n\nclass ThemeStackError(Exception):\n    \"\"\"Base exception for errors related to the theme stack.\"\"\"\n\n\nclass ThemeStack:\n    \"\"\"A stack of themes.\n\n    Args:\n        theme (Theme): A theme instance\n    \"\"\"\n\n    def __init__(self, theme: Theme) -> None:\n        self._entries: List[Dict[str, Style]] = [theme.styles]\n        self.get = self._entries[-1].get\n\n    def push_theme(self, theme: Theme, inherit: bool = True) -> None:\n        \"\"\"Push a theme on the top of the stack.\n\n        Args:\n            theme (Theme): A Theme instance.\n            inherit (boolean, optional): Inherit styles from current top of stack.\n        \"\"\"\n        styles: Dict[str, Style]\n        styles = (\n            {**self._entries[-1], **theme.styles} if inherit else theme.styles.copy()\n        )\n        self._entries.append(styles)\n        self.get = self._entries[-1].get\n\n    def pop_theme(self) -> None:\n        \"\"\"Pop (and discard) the top-most theme.\"\"\"\n        if len(self._entries) == 1:\n            raise ThemeStackError(\"Unable to pop base theme\")\n        self._entries.pop()\n        self.get = self._entries[-1].get\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    theme = Theme()\n    print(theme.config)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/themes.py",
    "content": "from .default_styles import DEFAULT_STYLES\nfrom .theme import Theme\n\n\nDEFAULT = Theme(DEFAULT_STYLES)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/traceback.py",
    "content": "from __future__ import absolute_import\n\nimport os\nimport platform\nimport sys\nfrom dataclasses import dataclass, field\nfrom traceback import walk_tb\nfrom types import ModuleType, TracebackType\nfrom typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Type, Union\n\nfrom pip._vendor.pygments.lexers import guess_lexer_for_filename\nfrom pip._vendor.pygments.token import Comment, Keyword, Name, Number, Operator, String\nfrom pip._vendor.pygments.token import Text as TextToken\nfrom pip._vendor.pygments.token import Token\nfrom pip._vendor.pygments.util import ClassNotFound\n\nfrom . import pretty\nfrom ._loop import loop_last\nfrom .columns import Columns\nfrom .console import Console, ConsoleOptions, ConsoleRenderable, RenderResult, group\nfrom .constrain import Constrain\nfrom .highlighter import RegexHighlighter, ReprHighlighter\nfrom .panel import Panel\nfrom .scope import render_scope\nfrom .style import Style\nfrom .syntax import Syntax\nfrom .text import Text\nfrom .theme import Theme\n\nWINDOWS = platform.system() == \"Windows\"\n\nLOCALS_MAX_LENGTH = 10\nLOCALS_MAX_STRING = 80\n\n\ndef install(\n    *,\n    console: Optional[Console] = None,\n    width: Optional[int] = 100,\n    extra_lines: int = 3,\n    theme: Optional[str] = None,\n    word_wrap: bool = False,\n    show_locals: bool = False,\n    indent_guides: bool = True,\n    suppress: Iterable[Union[str, ModuleType]] = (),\n    max_frames: int = 100,\n) -> Callable[[Type[BaseException], BaseException, Optional[TracebackType]], Any]:\n    \"\"\"Install a rich traceback handler.\n\n    Once installed, any tracebacks will be printed with syntax highlighting and rich formatting.\n\n\n    Args:\n        console (Optional[Console], optional): Console to write exception to. Default uses internal Console instance.\n        width (Optional[int], optional): Width (in characters) of traceback. Defaults to 100.\n        extra_lines (int, optional): Extra lines of code. Defaults to 3.\n        theme (Optional[str], optional): Pygments theme to use in traceback. Defaults to ``None`` which will pick\n            a theme appropriate for the platform.\n        word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.\n        show_locals (bool, optional): Enable display of local variables. Defaults to False.\n        indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.\n        suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.\n\n    Returns:\n        Callable: The previous exception handler that was replaced.\n\n    \"\"\"\n    traceback_console = Console(file=sys.stderr) if console is None else console\n\n    def excepthook(\n        type_: Type[BaseException],\n        value: BaseException,\n        traceback: Optional[TracebackType],\n    ) -> None:\n        traceback_console.print(\n            Traceback.from_exception(\n                type_,\n                value,\n                traceback,\n                width=width,\n                extra_lines=extra_lines,\n                theme=theme,\n                word_wrap=word_wrap,\n                show_locals=show_locals,\n                indent_guides=indent_guides,\n                suppress=suppress,\n                max_frames=max_frames,\n            )\n        )\n\n    def ipy_excepthook_closure(ip: Any) -> None:  # pragma: no cover\n        tb_data = {}  # store information about showtraceback call\n        default_showtraceback = ip.showtraceback  # keep reference of default traceback\n\n        def ipy_show_traceback(*args: Any, **kwargs: Any) -> None:\n            \"\"\"wrap the default ip.showtraceback to store info for ip._showtraceback\"\"\"\n            nonlocal tb_data\n            tb_data = kwargs\n            default_showtraceback(*args, **kwargs)\n\n        def ipy_display_traceback(\n            *args: Any, is_syntax: bool = False, **kwargs: Any\n        ) -> None:\n            \"\"\"Internally called traceback from ip._showtraceback\"\"\"\n            nonlocal tb_data\n            exc_tuple = ip._get_exc_info()\n\n            # do not display trace on syntax error\n            tb: Optional[TracebackType] = None if is_syntax else exc_tuple[2]\n\n            # determine correct tb_offset\n            compiled = tb_data.get(\"running_compiled_code\", False)\n            tb_offset = tb_data.get(\"tb_offset\", 1 if compiled else 0)\n            # remove ipython internal frames from trace with tb_offset\n            for _ in range(tb_offset):\n                if tb is None:\n                    break\n                tb = tb.tb_next\n\n            excepthook(exc_tuple[0], exc_tuple[1], tb)\n            tb_data = {}  # clear data upon usage\n\n        # replace _showtraceback instead of showtraceback to allow ipython features such as debugging to work\n        # this is also what the ipython docs recommends to modify when subclassing InteractiveShell\n        ip._showtraceback = ipy_display_traceback\n        # add wrapper to capture tb_data\n        ip.showtraceback = ipy_show_traceback\n        ip.showsyntaxerror = lambda *args, **kwargs: ipy_display_traceback(\n            *args, is_syntax=True, **kwargs\n        )\n\n    try:  # pragma: no cover\n        # if within ipython, use customized traceback\n        ip = get_ipython()  # type: ignore[name-defined]\n        ipy_excepthook_closure(ip)\n        return sys.excepthook\n    except Exception:\n        # otherwise use default system hook\n        old_excepthook = sys.excepthook\n        sys.excepthook = excepthook\n        return old_excepthook\n\n\n@dataclass\nclass Frame:\n    filename: str\n    lineno: int\n    name: str\n    line: str = \"\"\n    locals: Optional[Dict[str, pretty.Node]] = None\n\n\n@dataclass\nclass _SyntaxError:\n    offset: int\n    filename: str\n    line: str\n    lineno: int\n    msg: str\n\n\n@dataclass\nclass Stack:\n    exc_type: str\n    exc_value: str\n    syntax_error: Optional[_SyntaxError] = None\n    is_cause: bool = False\n    frames: List[Frame] = field(default_factory=list)\n\n\n@dataclass\nclass Trace:\n    stacks: List[Stack]\n\n\nclass PathHighlighter(RegexHighlighter):\n    highlights = [r\"(?P<dim>.*/)(?P<bold>.+)\"]\n\n\nclass Traceback:\n    \"\"\"A Console renderable that renders a traceback.\n\n    Args:\n        trace (Trace, optional): A `Trace` object produced from `extract`. Defaults to None, which uses\n            the last exception.\n        width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.\n        extra_lines (int, optional): Additional lines of code to render. Defaults to 3.\n        theme (str, optional): Override pygments theme used in traceback.\n        word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.\n        show_locals (bool, optional): Enable display of local variables. Defaults to False.\n        indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.\n        locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n            Defaults to 10.\n        locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.\n        suppress (Sequence[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.\n        max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.\n\n    \"\"\"\n\n    LEXERS = {\n        \"\": \"text\",\n        \".py\": \"python\",\n        \".pxd\": \"cython\",\n        \".pyx\": \"cython\",\n        \".pxi\": \"pyrex\",\n    }\n\n    def __init__(\n        self,\n        trace: Optional[Trace] = None,\n        width: Optional[int] = 100,\n        extra_lines: int = 3,\n        theme: Optional[str] = None,\n        word_wrap: bool = False,\n        show_locals: bool = False,\n        indent_guides: bool = True,\n        locals_max_length: int = LOCALS_MAX_LENGTH,\n        locals_max_string: int = LOCALS_MAX_STRING,\n        suppress: Iterable[Union[str, ModuleType]] = (),\n        max_frames: int = 100,\n    ):\n        if trace is None:\n            exc_type, exc_value, traceback = sys.exc_info()\n            if exc_type is None or exc_value is None or traceback is None:\n                raise ValueError(\n                    \"Value for 'trace' required if not called in except: block\"\n                )\n            trace = self.extract(\n                exc_type, exc_value, traceback, show_locals=show_locals\n            )\n        self.trace = trace\n        self.width = width\n        self.extra_lines = extra_lines\n        self.theme = Syntax.get_theme(theme or \"ansi_dark\")\n        self.word_wrap = word_wrap\n        self.show_locals = show_locals\n        self.indent_guides = indent_guides\n        self.locals_max_length = locals_max_length\n        self.locals_max_string = locals_max_string\n\n        self.suppress: Sequence[str] = []\n        for suppress_entity in suppress:\n            if not isinstance(suppress_entity, str):\n                assert (\n                    suppress_entity.__file__ is not None\n                ), f\"{suppress_entity!r} must be a module with '__file__' attribute\"\n                path = os.path.dirname(suppress_entity.__file__)\n            else:\n                path = suppress_entity\n            path = os.path.normpath(os.path.abspath(path))\n            self.suppress.append(path)\n        self.max_frames = max(4, max_frames) if max_frames > 0 else 0\n\n    @classmethod\n    def from_exception(\n        cls,\n        exc_type: Type[Any],\n        exc_value: BaseException,\n        traceback: Optional[TracebackType],\n        width: Optional[int] = 100,\n        extra_lines: int = 3,\n        theme: Optional[str] = None,\n        word_wrap: bool = False,\n        show_locals: bool = False,\n        indent_guides: bool = True,\n        locals_max_length: int = LOCALS_MAX_LENGTH,\n        locals_max_string: int = LOCALS_MAX_STRING,\n        suppress: Iterable[Union[str, ModuleType]] = (),\n        max_frames: int = 100,\n    ) -> \"Traceback\":\n        \"\"\"Create a traceback from exception info\n\n        Args:\n            exc_type (Type[BaseException]): Exception type.\n            exc_value (BaseException): Exception value.\n            traceback (TracebackType): Python Traceback object.\n            width (Optional[int], optional): Number of characters used to traceback. Defaults to 100.\n            extra_lines (int, optional): Additional lines of code to render. Defaults to 3.\n            theme (str, optional): Override pygments theme used in traceback.\n            word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.\n            show_locals (bool, optional): Enable display of local variables. Defaults to False.\n            indent_guides (bool, optional): Enable indent guides in code and locals. Defaults to True.\n            locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n                Defaults to 10.\n            locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.\n            suppress (Iterable[Union[str, ModuleType]]): Optional sequence of modules or paths to exclude from traceback.\n            max_frames (int): Maximum number of frames to show in a traceback, 0 for no maximum. Defaults to 100.\n\n        Returns:\n            Traceback: A Traceback instance that may be printed.\n        \"\"\"\n        rich_traceback = cls.extract(\n            exc_type, exc_value, traceback, show_locals=show_locals\n        )\n        return cls(\n            rich_traceback,\n            width=width,\n            extra_lines=extra_lines,\n            theme=theme,\n            word_wrap=word_wrap,\n            show_locals=show_locals,\n            indent_guides=indent_guides,\n            locals_max_length=locals_max_length,\n            locals_max_string=locals_max_string,\n            suppress=suppress,\n            max_frames=max_frames,\n        )\n\n    @classmethod\n    def extract(\n        cls,\n        exc_type: Type[BaseException],\n        exc_value: BaseException,\n        traceback: Optional[TracebackType],\n        show_locals: bool = False,\n        locals_max_length: int = LOCALS_MAX_LENGTH,\n        locals_max_string: int = LOCALS_MAX_STRING,\n    ) -> Trace:\n        \"\"\"Extract traceback information.\n\n        Args:\n            exc_type (Type[BaseException]): Exception type.\n            exc_value (BaseException): Exception value.\n            traceback (TracebackType): Python Traceback object.\n            show_locals (bool, optional): Enable display of local variables. Defaults to False.\n            locals_max_length (int, optional): Maximum length of containers before abbreviating, or None for no abbreviation.\n                Defaults to 10.\n            locals_max_string (int, optional): Maximum length of string before truncating, or None to disable. Defaults to 80.\n\n        Returns:\n            Trace: A Trace instance which you can use to construct a `Traceback`.\n        \"\"\"\n\n        stacks: List[Stack] = []\n        is_cause = False\n\n        from pip._vendor.rich import _IMPORT_CWD\n\n        def safe_str(_object: Any) -> str:\n            \"\"\"Don't allow exceptions from __str__ to propegate.\"\"\"\n            try:\n                return str(_object)\n            except Exception:\n                return \"<exception str() failed>\"\n\n        while True:\n            stack = Stack(\n                exc_type=safe_str(exc_type.__name__),\n                exc_value=safe_str(exc_value),\n                is_cause=is_cause,\n            )\n\n            if isinstance(exc_value, SyntaxError):\n                stack.syntax_error = _SyntaxError(\n                    offset=exc_value.offset or 0,\n                    filename=exc_value.filename or \"?\",\n                    lineno=exc_value.lineno or 0,\n                    line=exc_value.text or \"\",\n                    msg=exc_value.msg,\n                )\n\n            stacks.append(stack)\n            append = stack.frames.append\n\n            for frame_summary, line_no in walk_tb(traceback):\n                filename = frame_summary.f_code.co_filename\n                if filename and not filename.startswith(\"<\"):\n                    if not os.path.isabs(filename):\n                        filename = os.path.join(_IMPORT_CWD, filename)\n                if frame_summary.f_locals.get(\"_rich_traceback_omit\", False):\n                    continue\n                frame = Frame(\n                    filename=filename or \"?\",\n                    lineno=line_no,\n                    name=frame_summary.f_code.co_name,\n                    locals={\n                        key: pretty.traverse(\n                            value,\n                            max_length=locals_max_length,\n                            max_string=locals_max_string,\n                        )\n                        for key, value in frame_summary.f_locals.items()\n                    }\n                    if show_locals\n                    else None,\n                )\n                append(frame)\n                if frame_summary.f_locals.get(\"_rich_traceback_guard\", False):\n                    del stack.frames[:]\n\n            cause = getattr(exc_value, \"__cause__\", None)\n            if cause and cause.__traceback__:\n                exc_type = cause.__class__\n                exc_value = cause\n                traceback = cause.__traceback__\n                is_cause = True\n                continue\n\n            cause = exc_value.__context__\n            if (\n                cause\n                and cause.__traceback__\n                and not getattr(exc_value, \"__suppress_context__\", False)\n            ):\n                exc_type = cause.__class__\n                exc_value = cause\n                traceback = cause.__traceback__\n                is_cause = False\n                continue\n            # No cover, code is reached but coverage doesn't recognize it.\n            break  # pragma: no cover\n\n        trace = Trace(stacks=stacks)\n        return trace\n\n    def __rich_console__(\n        self, console: Console, options: ConsoleOptions\n    ) -> RenderResult:\n        theme = self.theme\n        background_style = theme.get_background_style()\n        token_style = theme.get_style_for_token\n\n        traceback_theme = Theme(\n            {\n                \"pretty\": token_style(TextToken),\n                \"pygments.text\": token_style(Token),\n                \"pygments.string\": token_style(String),\n                \"pygments.function\": token_style(Name.Function),\n                \"pygments.number\": token_style(Number),\n                \"repr.indent\": token_style(Comment) + Style(dim=True),\n                \"repr.str\": token_style(String),\n                \"repr.brace\": token_style(TextToken) + Style(bold=True),\n                \"repr.number\": token_style(Number),\n                \"repr.bool_true\": token_style(Keyword.Constant),\n                \"repr.bool_false\": token_style(Keyword.Constant),\n                \"repr.none\": token_style(Keyword.Constant),\n                \"scope.border\": token_style(String.Delimiter),\n                \"scope.equals\": token_style(Operator),\n                \"scope.key\": token_style(Name),\n                \"scope.key.special\": token_style(Name.Constant) + Style(dim=True),\n            },\n            inherit=False,\n        )\n\n        highlighter = ReprHighlighter()\n        for last, stack in loop_last(reversed(self.trace.stacks)):\n            if stack.frames:\n                stack_renderable: ConsoleRenderable = Panel(\n                    self._render_stack(stack),\n                    title=\"[traceback.title]Traceback [dim](most recent call last)\",\n                    style=background_style,\n                    border_style=\"traceback.border\",\n                    expand=True,\n                    padding=(0, 1),\n                )\n                stack_renderable = Constrain(stack_renderable, self.width)\n                with console.use_theme(traceback_theme):\n                    yield stack_renderable\n            if stack.syntax_error is not None:\n                with console.use_theme(traceback_theme):\n                    yield Constrain(\n                        Panel(\n                            self._render_syntax_error(stack.syntax_error),\n                            style=background_style,\n                            border_style=\"traceback.border.syntax_error\",\n                            expand=True,\n                            padding=(0, 1),\n                            width=self.width,\n                        ),\n                        self.width,\n                    )\n                yield Text.assemble(\n                    (f\"{stack.exc_type}: \", \"traceback.exc_type\"),\n                    highlighter(stack.syntax_error.msg),\n                )\n            elif stack.exc_value:\n                yield Text.assemble(\n                    (f\"{stack.exc_type}: \", \"traceback.exc_type\"),\n                    highlighter(stack.exc_value),\n                )\n            else:\n                yield Text.assemble((f\"{stack.exc_type}\", \"traceback.exc_type\"))\n\n            if not last:\n                if stack.is_cause:\n                    yield Text.from_markup(\n                        \"\\n[i]The above exception was the direct cause of the following exception:\\n\",\n                    )\n                else:\n                    yield Text.from_markup(\n                        \"\\n[i]During handling of the above exception, another exception occurred:\\n\",\n                    )\n\n    @group()\n    def _render_syntax_error(self, syntax_error: _SyntaxError) -> RenderResult:\n        highlighter = ReprHighlighter()\n        path_highlighter = PathHighlighter()\n        if syntax_error.filename != \"<stdin>\":\n            text = Text.assemble(\n                (f\" {syntax_error.filename}\", \"pygments.string\"),\n                (\":\", \"pygments.text\"),\n                (str(syntax_error.lineno), \"pygments.number\"),\n                style=\"pygments.text\",\n            )\n            yield path_highlighter(text)\n        syntax_error_text = highlighter(syntax_error.line.rstrip())\n        syntax_error_text.no_wrap = True\n        offset = min(syntax_error.offset - 1, len(syntax_error_text))\n        syntax_error_text.stylize(\"bold underline\", offset, offset)\n        syntax_error_text += Text.from_markup(\n            \"\\n\" + \" \" * offset + \"[traceback.offset]▲[/]\",\n            style=\"pygments.text\",\n        )\n        yield syntax_error_text\n\n    @classmethod\n    def _guess_lexer(cls, filename: str, code: str) -> str:\n        ext = os.path.splitext(filename)[-1]\n        if not ext:\n            # No extension, look at first line to see if it is a hashbang\n            # Note, this is an educated guess and not a guarantee\n            # If it fails, the only downside is that the code is highlighted strangely\n            new_line_index = code.index(\"\\n\")\n            first_line = code[:new_line_index] if new_line_index != -1 else code\n            if first_line.startswith(\"#!\") and \"python\" in first_line.lower():\n                return \"python\"\n        try:\n            return cls.LEXERS.get(ext) or guess_lexer_for_filename(filename, code).name\n        except ClassNotFound:\n            return \"text\"\n\n    @group()\n    def _render_stack(self, stack: Stack) -> RenderResult:\n        path_highlighter = PathHighlighter()\n        theme = self.theme\n        code_cache: Dict[str, str] = {}\n\n        def read_code(filename: str) -> str:\n            \"\"\"Read files, and cache results on filename.\n\n            Args:\n                filename (str): Filename to read\n\n            Returns:\n                str: Contents of file\n            \"\"\"\n            code = code_cache.get(filename)\n            if code is None:\n                with open(\n                    filename, \"rt\", encoding=\"utf-8\", errors=\"replace\"\n                ) as code_file:\n                    code = code_file.read()\n                code_cache[filename] = code\n            return code\n\n        def render_locals(frame: Frame) -> Iterable[ConsoleRenderable]:\n            if frame.locals:\n                yield render_scope(\n                    frame.locals,\n                    title=\"locals\",\n                    indent_guides=self.indent_guides,\n                    max_length=self.locals_max_length,\n                    max_string=self.locals_max_string,\n                )\n\n        exclude_frames: Optional[range] = None\n        if self.max_frames != 0:\n            exclude_frames = range(\n                self.max_frames // 2,\n                len(stack.frames) - self.max_frames // 2,\n            )\n\n        excluded = False\n        for frame_index, frame in enumerate(stack.frames):\n\n            if exclude_frames and frame_index in exclude_frames:\n                excluded = True\n                continue\n\n            if excluded:\n                assert exclude_frames is not None\n                yield Text(\n                    f\"\\n... {len(exclude_frames)} frames hidden ...\",\n                    justify=\"center\",\n                    style=\"traceback.error\",\n                )\n                excluded = False\n\n            first = frame_index == 0\n            frame_filename = frame.filename\n            suppressed = any(frame_filename.startswith(path) for path in self.suppress)\n\n            text = Text.assemble(\n                path_highlighter(Text(frame.filename, style=\"pygments.string\")),\n                (\":\", \"pygments.text\"),\n                (str(frame.lineno), \"pygments.number\"),\n                \" in \",\n                (frame.name, \"pygments.function\"),\n                style=\"pygments.text\",\n            )\n            if not frame.filename.startswith(\"<\") and not first:\n                yield \"\"\n            yield text\n            if frame.filename.startswith(\"<\"):\n                yield from render_locals(frame)\n                continue\n            if not suppressed:\n                try:\n                    code = read_code(frame.filename)\n                    lexer_name = self._guess_lexer(frame.filename, code)\n                    syntax = Syntax(\n                        code,\n                        lexer_name,\n                        theme=theme,\n                        line_numbers=True,\n                        line_range=(\n                            frame.lineno - self.extra_lines,\n                            frame.lineno + self.extra_lines,\n                        ),\n                        highlight_lines={frame.lineno},\n                        word_wrap=self.word_wrap,\n                        code_width=88,\n                        indent_guides=self.indent_guides,\n                        dedent=False,\n                    )\n                    yield \"\"\n                except Exception as error:\n                    yield Text.assemble(\n                        (f\"\\n{error}\", \"traceback.error\"),\n                    )\n                else:\n                    yield (\n                        Columns(\n                            [\n                                syntax,\n                                *render_locals(frame),\n                            ],\n                            padding=1,\n                        )\n                        if frame.locals\n                        else syntax\n                    )\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n\n    from .console import Console\n\n    console = Console()\n    import sys\n\n    def bar(a: Any) -> None:  # 这是对亚洲语言支持的测试。面对模棱两可的想法，拒绝猜测的诱惑\n        one = 1\n        print(one / a)\n\n    def foo(a: Any) -> None:\n        _rich_traceback_guard = True\n        zed = {\n            \"characters\": {\n                \"Paul Atreides\",\n                \"Vladimir Harkonnen\",\n                \"Thufir Hawat\",\n                \"Duncan Idaho\",\n            },\n            \"atomic_types\": (None, False, True),\n        }\n        bar(a)\n\n    def error() -> None:\n\n        try:\n            try:\n                foo(0)\n            except:\n                slfkjsldkfj  # type: ignore[name-defined]\n        except:\n            console.print_exception(show_locals=True)\n\n    error()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/rich/tree.py",
    "content": "from typing import Iterator, List, Optional, Tuple\n\nfrom ._loop import loop_first, loop_last\nfrom .console import Console, ConsoleOptions, RenderableType, RenderResult\nfrom .jupyter import JupyterMixin\nfrom .measure import Measurement\nfrom .segment import Segment\nfrom .style import Style, StyleStack, StyleType\nfrom .styled import Styled\n\n\nclass Tree(JupyterMixin):\n    \"\"\"A renderable for a tree structure.\n\n    Args:\n        label (RenderableType): The renderable or str for the tree label.\n        style (StyleType, optional): Style of this tree. Defaults to \"tree\".\n        guide_style (StyleType, optional): Style of the guide lines. Defaults to \"tree.line\".\n        expanded (bool, optional): Also display children. Defaults to True.\n        highlight (bool, optional): Highlight renderable (if str). Defaults to False.\n    \"\"\"\n\n    def __init__(\n        self,\n        label: RenderableType,\n        *,\n        style: StyleType = \"tree\",\n        guide_style: StyleType = \"tree.line\",\n        expanded: bool = True,\n        highlight: bool = False,\n        hide_root: bool = False,\n    ) -> None:\n        self.label = label\n        self.style = style\n        self.guide_style = guide_style\n        self.children: List[Tree] = []\n        self.expanded = expanded\n        self.highlight = highlight\n        self.hide_root = hide_root\n\n    def add(\n        self,\n        label: RenderableType,\n        *,\n        style: Optional[StyleType] = None,\n        guide_style: Optional[StyleType] = None,\n        expanded: bool = True,\n        highlight: Optional[bool] = False,\n    ) -> \"Tree\":\n        \"\"\"Add a child tree.\n\n        Args:\n            label (RenderableType): The renderable or str for the tree label.\n            style (StyleType, optional): Style of this tree. Defaults to \"tree\".\n            guide_style (StyleType, optional): Style of the guide lines. Defaults to \"tree.line\".\n            expanded (bool, optional): Also display children. Defaults to True.\n            highlight (Optional[bool], optional): Highlight renderable (if str). Defaults to False.\n\n        Returns:\n            Tree: A new child Tree, which may be further modified.\n        \"\"\"\n        node = Tree(\n            label,\n            style=self.style if style is None else style,\n            guide_style=self.guide_style if guide_style is None else guide_style,\n            expanded=expanded,\n            highlight=self.highlight if highlight is None else highlight,\n        )\n        self.children.append(node)\n        return node\n\n    def __rich_console__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"RenderResult\":\n\n        stack: List[Iterator[Tuple[bool, Tree]]] = []\n        pop = stack.pop\n        push = stack.append\n        new_line = Segment.line()\n\n        get_style = console.get_style\n        null_style = Style.null()\n        guide_style = get_style(self.guide_style, default=\"\") or null_style\n        SPACE, CONTINUE, FORK, END = range(4)\n\n        ASCII_GUIDES = (\"    \", \"|   \", \"+-- \", \"`-- \")\n        TREE_GUIDES = [\n            (\"    \", \"│   \", \"├── \", \"└── \"),\n            (\"    \", \"┃   \", \"┣━━ \", \"┗━━ \"),\n            (\"    \", \"║   \", \"╠══ \", \"╚══ \"),\n        ]\n        _Segment = Segment\n\n        def make_guide(index: int, style: Style) -> Segment:\n            \"\"\"Make a Segment for a level of the guide lines.\"\"\"\n            if options.ascii_only:\n                line = ASCII_GUIDES[index]\n            else:\n                guide = 1 if style.bold else (2 if style.underline2 else 0)\n                line = TREE_GUIDES[0 if options.legacy_windows else guide][index]\n            return _Segment(line, style)\n\n        levels: List[Segment] = [make_guide(CONTINUE, guide_style)]\n        push(iter(loop_last([self])))\n\n        guide_style_stack = StyleStack(get_style(self.guide_style))\n        style_stack = StyleStack(get_style(self.style))\n        remove_guide_styles = Style(bold=False, underline2=False)\n\n        depth = 0\n\n        while stack:\n            stack_node = pop()\n            try:\n                last, node = next(stack_node)\n            except StopIteration:\n                levels.pop()\n                if levels:\n                    guide_style = levels[-1].style or null_style\n                    levels[-1] = make_guide(FORK, guide_style)\n                    guide_style_stack.pop()\n                    style_stack.pop()\n                continue\n            push(stack_node)\n            if last:\n                levels[-1] = make_guide(END, levels[-1].style or null_style)\n\n            guide_style = guide_style_stack.current + get_style(node.guide_style)\n            style = style_stack.current + get_style(node.style)\n            prefix = levels[(2 if self.hide_root else 1) :]\n            renderable_lines = console.render_lines(\n                Styled(node.label, style),\n                options.update(\n                    width=options.max_width\n                    - sum(level.cell_length for level in prefix),\n                    highlight=self.highlight,\n                    height=None,\n                ),\n                pad=options.justify is not None,\n            )\n\n            if not (depth == 0 and self.hide_root):\n                for first, line in loop_first(renderable_lines):\n                    if prefix:\n                        yield from _Segment.apply_style(\n                            prefix,\n                            style.background_style,\n                            post_style=remove_guide_styles,\n                        )\n                    yield from line\n                    yield new_line\n                    if first and prefix:\n                        prefix[-1] = make_guide(\n                            SPACE if last else CONTINUE, prefix[-1].style or null_style\n                        )\n\n            if node.expanded and node.children:\n                levels[-1] = make_guide(\n                    SPACE if last else CONTINUE, levels[-1].style or null_style\n                )\n                levels.append(\n                    make_guide(END if len(node.children) == 1 else FORK, guide_style)\n                )\n                style_stack.push(get_style(node.style))\n                guide_style_stack.push(get_style(node.guide_style))\n                push(iter(loop_last(node.children)))\n                depth += 1\n\n    def __rich_measure__(\n        self, console: \"Console\", options: \"ConsoleOptions\"\n    ) -> \"Measurement\":\n        stack: List[Iterator[Tree]] = [iter([self])]\n        pop = stack.pop\n        push = stack.append\n        minimum = 0\n        maximum = 0\n        measure = Measurement.get\n        level = 0\n        while stack:\n            iter_tree = pop()\n            try:\n                tree = next(iter_tree)\n            except StopIteration:\n                level -= 1\n                continue\n            push(iter_tree)\n            min_measure, max_measure = measure(console, options, tree.label)\n            indent = level * 4\n            minimum = max(min_measure + indent, minimum)\n            maximum = max(max_measure + indent, maximum)\n            if tree.expanded and tree.children:\n                push(iter(tree.children))\n                level += 1\n        return Measurement(minimum, maximum)\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n\n    from pip._vendor.rich.console import Group\n    from pip._vendor.rich.markdown import Markdown\n    from pip._vendor.rich.panel import Panel\n    from pip._vendor.rich.syntax import Syntax\n    from pip._vendor.rich.table import Table\n\n    table = Table(row_styles=[\"\", \"dim\"])\n\n    table.add_column(\"Released\", style=\"cyan\", no_wrap=True)\n    table.add_column(\"Title\", style=\"magenta\")\n    table.add_column(\"Box Office\", justify=\"right\", style=\"green\")\n\n    table.add_row(\"Dec 20, 2019\", \"Star Wars: The Rise of Skywalker\", \"$952,110,690\")\n    table.add_row(\"May 25, 2018\", \"Solo: A Star Wars Story\", \"$393,151,347\")\n    table.add_row(\"Dec 15, 2017\", \"Star Wars Ep. V111: The Last Jedi\", \"$1,332,539,889\")\n    table.add_row(\"Dec 16, 2016\", \"Rogue One: A Star Wars Story\", \"$1,332,439,889\")\n\n    code = \"\"\"\\\nclass Segment(NamedTuple):\n    text: str = \"\"\n    style: Optional[Style] = None\n    is_control: bool = False\n\"\"\"\n    syntax = Syntax(code, \"python\", theme=\"monokai\", line_numbers=True)\n\n    markdown = Markdown(\n        \"\"\"\\\n### example.md\n> Hello, World!\n>\n> Markdown _all_ the things\n\"\"\"\n    )\n\n    root = Tree(\"🌲 [b green]Rich Tree\", highlight=True, hide_root=True)\n\n    node = root.add(\":file_folder: Renderables\", guide_style=\"red\")\n    simple_node = node.add(\":file_folder: [bold yellow]Atomic\", guide_style=\"uu green\")\n    simple_node.add(Group(\"📄 Syntax\", syntax))\n    simple_node.add(Group(\"📄 Markdown\", Panel(markdown, border_style=\"green\")))\n\n    containers_node = node.add(\n        \":file_folder: [bold magenta]Containers\", guide_style=\"bold magenta\"\n    )\n    containers_node.expanded = True\n    panel = Panel.fit(\"Just a panel\", border_style=\"red\")\n    containers_node.add(Group(\"📄 Panels\", panel))\n\n    containers_node.add(Group(\"📄 [b magenta]Table\", table))\n\n    console = Console()\n\n    console.print(root)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/six.py",
    "content": "# Copyright (c) 2010-2020 Benjamin Peterson\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"Utilities for writing code that runs on Python 2 and 3\"\"\"\n\nfrom __future__ import absolute_import\n\nimport functools\nimport itertools\nimport operator\nimport sys\nimport types\n\n__author__ = \"Benjamin Peterson <benjamin@python.org>\"\n__version__ = \"1.16.0\"\n\n\n# Useful for very coarse version differentiation.\nPY2 = sys.version_info[0] == 2\nPY3 = sys.version_info[0] == 3\nPY34 = sys.version_info[0:2] >= (3, 4)\n\nif PY3:\n    string_types = str,\n    integer_types = int,\n    class_types = type,\n    text_type = str\n    binary_type = bytes\n\n    MAXSIZE = sys.maxsize\nelse:\n    string_types = basestring,\n    integer_types = (int, long)\n    class_types = (type, types.ClassType)\n    text_type = unicode\n    binary_type = str\n\n    if sys.platform.startswith(\"java\"):\n        # Jython always uses 32 bits.\n        MAXSIZE = int((1 << 31) - 1)\n    else:\n        # It's possible to have sizeof(long) != sizeof(Py_ssize_t).\n        class X(object):\n\n            def __len__(self):\n                return 1 << 31\n        try:\n            len(X())\n        except OverflowError:\n            # 32-bit\n            MAXSIZE = int((1 << 31) - 1)\n        else:\n            # 64-bit\n            MAXSIZE = int((1 << 63) - 1)\n        del X\n\nif PY34:\n    from importlib.util import spec_from_loader\nelse:\n    spec_from_loader = None\n\n\ndef _add_doc(func, doc):\n    \"\"\"Add documentation to a function.\"\"\"\n    func.__doc__ = doc\n\n\ndef _import_module(name):\n    \"\"\"Import module, returning the module after the last dot.\"\"\"\n    __import__(name)\n    return sys.modules[name]\n\n\nclass _LazyDescr(object):\n\n    def __init__(self, name):\n        self.name = name\n\n    def __get__(self, obj, tp):\n        result = self._resolve()\n        setattr(obj, self.name, result)  # Invokes __set__.\n        try:\n            # This is a bit ugly, but it avoids running this again by\n            # removing this descriptor.\n            delattr(obj.__class__, self.name)\n        except AttributeError:\n            pass\n        return result\n\n\nclass MovedModule(_LazyDescr):\n\n    def __init__(self, name, old, new=None):\n        super(MovedModule, self).__init__(name)\n        if PY3:\n            if new is None:\n                new = name\n            self.mod = new\n        else:\n            self.mod = old\n\n    def _resolve(self):\n        return _import_module(self.mod)\n\n    def __getattr__(self, attr):\n        _module = self._resolve()\n        value = getattr(_module, attr)\n        setattr(self, attr, value)\n        return value\n\n\nclass _LazyModule(types.ModuleType):\n\n    def __init__(self, name):\n        super(_LazyModule, self).__init__(name)\n        self.__doc__ = self.__class__.__doc__\n\n    def __dir__(self):\n        attrs = [\"__doc__\", \"__name__\"]\n        attrs += [attr.name for attr in self._moved_attributes]\n        return attrs\n\n    # Subclasses should override this\n    _moved_attributes = []\n\n\nclass MovedAttribute(_LazyDescr):\n\n    def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):\n        super(MovedAttribute, self).__init__(name)\n        if PY3:\n            if new_mod is None:\n                new_mod = name\n            self.mod = new_mod\n            if new_attr is None:\n                if old_attr is None:\n                    new_attr = name\n                else:\n                    new_attr = old_attr\n            self.attr = new_attr\n        else:\n            self.mod = old_mod\n            if old_attr is None:\n                old_attr = name\n            self.attr = old_attr\n\n    def _resolve(self):\n        module = _import_module(self.mod)\n        return getattr(module, self.attr)\n\n\nclass _SixMetaPathImporter(object):\n\n    \"\"\"\n    A meta path importer to import six.moves and its submodules.\n\n    This class implements a PEP302 finder and loader. It should be compatible\n    with Python 2.5 and all existing versions of Python3\n    \"\"\"\n\n    def __init__(self, six_module_name):\n        self.name = six_module_name\n        self.known_modules = {}\n\n    def _add_module(self, mod, *fullnames):\n        for fullname in fullnames:\n            self.known_modules[self.name + \".\" + fullname] = mod\n\n    def _get_module(self, fullname):\n        return self.known_modules[self.name + \".\" + fullname]\n\n    def find_module(self, fullname, path=None):\n        if fullname in self.known_modules:\n            return self\n        return None\n\n    def find_spec(self, fullname, path, target=None):\n        if fullname in self.known_modules:\n            return spec_from_loader(fullname, self)\n        return None\n\n    def __get_module(self, fullname):\n        try:\n            return self.known_modules[fullname]\n        except KeyError:\n            raise ImportError(\"This loader does not know module \" + fullname)\n\n    def load_module(self, fullname):\n        try:\n            # in case of a reload\n            return sys.modules[fullname]\n        except KeyError:\n            pass\n        mod = self.__get_module(fullname)\n        if isinstance(mod, MovedModule):\n            mod = mod._resolve()\n        else:\n            mod.__loader__ = self\n        sys.modules[fullname] = mod\n        return mod\n\n    def is_package(self, fullname):\n        \"\"\"\n        Return true, if the named module is a package.\n\n        We need this method to get correct spec objects with\n        Python 3.4 (see PEP451)\n        \"\"\"\n        return hasattr(self.__get_module(fullname), \"__path__\")\n\n    def get_code(self, fullname):\n        \"\"\"Return None\n\n        Required, if is_package is implemented\"\"\"\n        self.__get_module(fullname)  # eventually raises ImportError\n        return None\n    get_source = get_code  # same as get_code\n\n    def create_module(self, spec):\n        return self.load_module(spec.name)\n\n    def exec_module(self, module):\n        pass\n\n_importer = _SixMetaPathImporter(__name__)\n\n\nclass _MovedItems(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects\"\"\"\n    __path__ = []  # mark as package\n\n\n_moved_attributes = [\n    MovedAttribute(\"cStringIO\", \"cStringIO\", \"io\", \"StringIO\"),\n    MovedAttribute(\"filter\", \"itertools\", \"builtins\", \"ifilter\", \"filter\"),\n    MovedAttribute(\"filterfalse\", \"itertools\", \"itertools\", \"ifilterfalse\", \"filterfalse\"),\n    MovedAttribute(\"input\", \"__builtin__\", \"builtins\", \"raw_input\", \"input\"),\n    MovedAttribute(\"intern\", \"__builtin__\", \"sys\"),\n    MovedAttribute(\"map\", \"itertools\", \"builtins\", \"imap\", \"map\"),\n    MovedAttribute(\"getcwd\", \"os\", \"os\", \"getcwdu\", \"getcwd\"),\n    MovedAttribute(\"getcwdb\", \"os\", \"os\", \"getcwd\", \"getcwdb\"),\n    MovedAttribute(\"getoutput\", \"commands\", \"subprocess\"),\n    MovedAttribute(\"range\", \"__builtin__\", \"builtins\", \"xrange\", \"range\"),\n    MovedAttribute(\"reload_module\", \"__builtin__\", \"importlib\" if PY34 else \"imp\", \"reload\"),\n    MovedAttribute(\"reduce\", \"__builtin__\", \"functools\"),\n    MovedAttribute(\"shlex_quote\", \"pipes\", \"shlex\", \"quote\"),\n    MovedAttribute(\"StringIO\", \"StringIO\", \"io\"),\n    MovedAttribute(\"UserDict\", \"UserDict\", \"collections\"),\n    MovedAttribute(\"UserList\", \"UserList\", \"collections\"),\n    MovedAttribute(\"UserString\", \"UserString\", \"collections\"),\n    MovedAttribute(\"xrange\", \"__builtin__\", \"builtins\", \"xrange\", \"range\"),\n    MovedAttribute(\"zip\", \"itertools\", \"builtins\", \"izip\", \"zip\"),\n    MovedAttribute(\"zip_longest\", \"itertools\", \"itertools\", \"izip_longest\", \"zip_longest\"),\n    MovedModule(\"builtins\", \"__builtin__\"),\n    MovedModule(\"configparser\", \"ConfigParser\"),\n    MovedModule(\"collections_abc\", \"collections\", \"collections.abc\" if sys.version_info >= (3, 3) else \"collections\"),\n    MovedModule(\"copyreg\", \"copy_reg\"),\n    MovedModule(\"dbm_gnu\", \"gdbm\", \"dbm.gnu\"),\n    MovedModule(\"dbm_ndbm\", \"dbm\", \"dbm.ndbm\"),\n    MovedModule(\"_dummy_thread\", \"dummy_thread\", \"_dummy_thread\" if sys.version_info < (3, 9) else \"_thread\"),\n    MovedModule(\"http_cookiejar\", \"cookielib\", \"http.cookiejar\"),\n    MovedModule(\"http_cookies\", \"Cookie\", \"http.cookies\"),\n    MovedModule(\"html_entities\", \"htmlentitydefs\", \"html.entities\"),\n    MovedModule(\"html_parser\", \"HTMLParser\", \"html.parser\"),\n    MovedModule(\"http_client\", \"httplib\", \"http.client\"),\n    MovedModule(\"email_mime_base\", \"email.MIMEBase\", \"email.mime.base\"),\n    MovedModule(\"email_mime_image\", \"email.MIMEImage\", \"email.mime.image\"),\n    MovedModule(\"email_mime_multipart\", \"email.MIMEMultipart\", \"email.mime.multipart\"),\n    MovedModule(\"email_mime_nonmultipart\", \"email.MIMENonMultipart\", \"email.mime.nonmultipart\"),\n    MovedModule(\"email_mime_text\", \"email.MIMEText\", \"email.mime.text\"),\n    MovedModule(\"BaseHTTPServer\", \"BaseHTTPServer\", \"http.server\"),\n    MovedModule(\"CGIHTTPServer\", \"CGIHTTPServer\", \"http.server\"),\n    MovedModule(\"SimpleHTTPServer\", \"SimpleHTTPServer\", \"http.server\"),\n    MovedModule(\"cPickle\", \"cPickle\", \"pickle\"),\n    MovedModule(\"queue\", \"Queue\"),\n    MovedModule(\"reprlib\", \"repr\"),\n    MovedModule(\"socketserver\", \"SocketServer\"),\n    MovedModule(\"_thread\", \"thread\", \"_thread\"),\n    MovedModule(\"tkinter\", \"Tkinter\"),\n    MovedModule(\"tkinter_dialog\", \"Dialog\", \"tkinter.dialog\"),\n    MovedModule(\"tkinter_filedialog\", \"FileDialog\", \"tkinter.filedialog\"),\n    MovedModule(\"tkinter_scrolledtext\", \"ScrolledText\", \"tkinter.scrolledtext\"),\n    MovedModule(\"tkinter_simpledialog\", \"SimpleDialog\", \"tkinter.simpledialog\"),\n    MovedModule(\"tkinter_tix\", \"Tix\", \"tkinter.tix\"),\n    MovedModule(\"tkinter_ttk\", \"ttk\", \"tkinter.ttk\"),\n    MovedModule(\"tkinter_constants\", \"Tkconstants\", \"tkinter.constants\"),\n    MovedModule(\"tkinter_dnd\", \"Tkdnd\", \"tkinter.dnd\"),\n    MovedModule(\"tkinter_colorchooser\", \"tkColorChooser\",\n                \"tkinter.colorchooser\"),\n    MovedModule(\"tkinter_commondialog\", \"tkCommonDialog\",\n                \"tkinter.commondialog\"),\n    MovedModule(\"tkinter_tkfiledialog\", \"tkFileDialog\", \"tkinter.filedialog\"),\n    MovedModule(\"tkinter_font\", \"tkFont\", \"tkinter.font\"),\n    MovedModule(\"tkinter_messagebox\", \"tkMessageBox\", \"tkinter.messagebox\"),\n    MovedModule(\"tkinter_tksimpledialog\", \"tkSimpleDialog\",\n                \"tkinter.simpledialog\"),\n    MovedModule(\"urllib_parse\", __name__ + \".moves.urllib_parse\", \"urllib.parse\"),\n    MovedModule(\"urllib_error\", __name__ + \".moves.urllib_error\", \"urllib.error\"),\n    MovedModule(\"urllib\", __name__ + \".moves.urllib\", __name__ + \".moves.urllib\"),\n    MovedModule(\"urllib_robotparser\", \"robotparser\", \"urllib.robotparser\"),\n    MovedModule(\"xmlrpc_client\", \"xmlrpclib\", \"xmlrpc.client\"),\n    MovedModule(\"xmlrpc_server\", \"SimpleXMLRPCServer\", \"xmlrpc.server\"),\n]\n# Add windows specific modules.\nif sys.platform == \"win32\":\n    _moved_attributes += [\n        MovedModule(\"winreg\", \"_winreg\"),\n    ]\n\nfor attr in _moved_attributes:\n    setattr(_MovedItems, attr.name, attr)\n    if isinstance(attr, MovedModule):\n        _importer._add_module(attr, \"moves.\" + attr.name)\ndel attr\n\n_MovedItems._moved_attributes = _moved_attributes\n\nmoves = _MovedItems(__name__ + \".moves\")\n_importer._add_module(moves, \"moves\")\n\n\nclass Module_six_moves_urllib_parse(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_parse\"\"\"\n\n\n_urllib_parse_moved_attributes = [\n    MovedAttribute(\"ParseResult\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"SplitResult\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"parse_qs\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"parse_qsl\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urldefrag\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urljoin\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urlparse\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urlsplit\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urlunparse\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urlunsplit\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"quote\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"quote_plus\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"unquote\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"unquote_plus\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"unquote_to_bytes\", \"urllib\", \"urllib.parse\", \"unquote\", \"unquote_to_bytes\"),\n    MovedAttribute(\"urlencode\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"splitquery\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"splittag\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"splituser\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"splitvalue\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"uses_fragment\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"uses_netloc\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"uses_params\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"uses_query\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"uses_relative\", \"urlparse\", \"urllib.parse\"),\n]\nfor attr in _urllib_parse_moved_attributes:\n    setattr(Module_six_moves_urllib_parse, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes\n\n_importer._add_module(Module_six_moves_urllib_parse(__name__ + \".moves.urllib_parse\"),\n                      \"moves.urllib_parse\", \"moves.urllib.parse\")\n\n\nclass Module_six_moves_urllib_error(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_error\"\"\"\n\n\n_urllib_error_moved_attributes = [\n    MovedAttribute(\"URLError\", \"urllib2\", \"urllib.error\"),\n    MovedAttribute(\"HTTPError\", \"urllib2\", \"urllib.error\"),\n    MovedAttribute(\"ContentTooShortError\", \"urllib\", \"urllib.error\"),\n]\nfor attr in _urllib_error_moved_attributes:\n    setattr(Module_six_moves_urllib_error, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes\n\n_importer._add_module(Module_six_moves_urllib_error(__name__ + \".moves.urllib.error\"),\n                      \"moves.urllib_error\", \"moves.urllib.error\")\n\n\nclass Module_six_moves_urllib_request(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_request\"\"\"\n\n\n_urllib_request_moved_attributes = [\n    MovedAttribute(\"urlopen\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"install_opener\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"build_opener\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"pathname2url\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"url2pathname\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"getproxies\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"Request\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"OpenerDirector\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPDefaultErrorHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPRedirectHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPCookieProcessor\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"ProxyHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"BaseHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPPasswordMgr\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPPasswordMgrWithDefaultRealm\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"AbstractBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"ProxyBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"AbstractDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"ProxyDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPSHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"FileHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"FTPHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"CacheFTPHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"UnknownHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPErrorProcessor\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"urlretrieve\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"urlcleanup\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"URLopener\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"FancyURLopener\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"proxy_bypass\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"parse_http_list\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"parse_keqv_list\", \"urllib2\", \"urllib.request\"),\n]\nfor attr in _urllib_request_moved_attributes:\n    setattr(Module_six_moves_urllib_request, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes\n\n_importer._add_module(Module_six_moves_urllib_request(__name__ + \".moves.urllib.request\"),\n                      \"moves.urllib_request\", \"moves.urllib.request\")\n\n\nclass Module_six_moves_urllib_response(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_response\"\"\"\n\n\n_urllib_response_moved_attributes = [\n    MovedAttribute(\"addbase\", \"urllib\", \"urllib.response\"),\n    MovedAttribute(\"addclosehook\", \"urllib\", \"urllib.response\"),\n    MovedAttribute(\"addinfo\", \"urllib\", \"urllib.response\"),\n    MovedAttribute(\"addinfourl\", \"urllib\", \"urllib.response\"),\n]\nfor attr in _urllib_response_moved_attributes:\n    setattr(Module_six_moves_urllib_response, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes\n\n_importer._add_module(Module_six_moves_urllib_response(__name__ + \".moves.urllib.response\"),\n                      \"moves.urllib_response\", \"moves.urllib.response\")\n\n\nclass Module_six_moves_urllib_robotparser(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_robotparser\"\"\"\n\n\n_urllib_robotparser_moved_attributes = [\n    MovedAttribute(\"RobotFileParser\", \"robotparser\", \"urllib.robotparser\"),\n]\nfor attr in _urllib_robotparser_moved_attributes:\n    setattr(Module_six_moves_urllib_robotparser, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes\n\n_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + \".moves.urllib.robotparser\"),\n                      \"moves.urllib_robotparser\", \"moves.urllib.robotparser\")\n\n\nclass Module_six_moves_urllib(types.ModuleType):\n\n    \"\"\"Create a six.moves.urllib namespace that resembles the Python 3 namespace\"\"\"\n    __path__ = []  # mark as package\n    parse = _importer._get_module(\"moves.urllib_parse\")\n    error = _importer._get_module(\"moves.urllib_error\")\n    request = _importer._get_module(\"moves.urllib_request\")\n    response = _importer._get_module(\"moves.urllib_response\")\n    robotparser = _importer._get_module(\"moves.urllib_robotparser\")\n\n    def __dir__(self):\n        return ['parse', 'error', 'request', 'response', 'robotparser']\n\n_importer._add_module(Module_six_moves_urllib(__name__ + \".moves.urllib\"),\n                      \"moves.urllib\")\n\n\ndef add_move(move):\n    \"\"\"Add an item to six.moves.\"\"\"\n    setattr(_MovedItems, move.name, move)\n\n\ndef remove_move(name):\n    \"\"\"Remove item from six.moves.\"\"\"\n    try:\n        delattr(_MovedItems, name)\n    except AttributeError:\n        try:\n            del moves.__dict__[name]\n        except KeyError:\n            raise AttributeError(\"no such move, %r\" % (name,))\n\n\nif PY3:\n    _meth_func = \"__func__\"\n    _meth_self = \"__self__\"\n\n    _func_closure = \"__closure__\"\n    _func_code = \"__code__\"\n    _func_defaults = \"__defaults__\"\n    _func_globals = \"__globals__\"\nelse:\n    _meth_func = \"im_func\"\n    _meth_self = \"im_self\"\n\n    _func_closure = \"func_closure\"\n    _func_code = \"func_code\"\n    _func_defaults = \"func_defaults\"\n    _func_globals = \"func_globals\"\n\n\ntry:\n    advance_iterator = next\nexcept NameError:\n    def advance_iterator(it):\n        return it.next()\nnext = advance_iterator\n\n\ntry:\n    callable = callable\nexcept NameError:\n    def callable(obj):\n        return any(\"__call__\" in klass.__dict__ for klass in type(obj).__mro__)\n\n\nif PY3:\n    def get_unbound_function(unbound):\n        return unbound\n\n    create_bound_method = types.MethodType\n\n    def create_unbound_method(func, cls):\n        return func\n\n    Iterator = object\nelse:\n    def get_unbound_function(unbound):\n        return unbound.im_func\n\n    def create_bound_method(func, obj):\n        return types.MethodType(func, obj, obj.__class__)\n\n    def create_unbound_method(func, cls):\n        return types.MethodType(func, None, cls)\n\n    class Iterator(object):\n\n        def next(self):\n            return type(self).__next__(self)\n\n    callable = callable\n_add_doc(get_unbound_function,\n         \"\"\"Get the function out of a possibly unbound function\"\"\")\n\n\nget_method_function = operator.attrgetter(_meth_func)\nget_method_self = operator.attrgetter(_meth_self)\nget_function_closure = operator.attrgetter(_func_closure)\nget_function_code = operator.attrgetter(_func_code)\nget_function_defaults = operator.attrgetter(_func_defaults)\nget_function_globals = operator.attrgetter(_func_globals)\n\n\nif PY3:\n    def iterkeys(d, **kw):\n        return iter(d.keys(**kw))\n\n    def itervalues(d, **kw):\n        return iter(d.values(**kw))\n\n    def iteritems(d, **kw):\n        return iter(d.items(**kw))\n\n    def iterlists(d, **kw):\n        return iter(d.lists(**kw))\n\n    viewkeys = operator.methodcaller(\"keys\")\n\n    viewvalues = operator.methodcaller(\"values\")\n\n    viewitems = operator.methodcaller(\"items\")\nelse:\n    def iterkeys(d, **kw):\n        return d.iterkeys(**kw)\n\n    def itervalues(d, **kw):\n        return d.itervalues(**kw)\n\n    def iteritems(d, **kw):\n        return d.iteritems(**kw)\n\n    def iterlists(d, **kw):\n        return d.iterlists(**kw)\n\n    viewkeys = operator.methodcaller(\"viewkeys\")\n\n    viewvalues = operator.methodcaller(\"viewvalues\")\n\n    viewitems = operator.methodcaller(\"viewitems\")\n\n_add_doc(iterkeys, \"Return an iterator over the keys of a dictionary.\")\n_add_doc(itervalues, \"Return an iterator over the values of a dictionary.\")\n_add_doc(iteritems,\n         \"Return an iterator over the (key, value) pairs of a dictionary.\")\n_add_doc(iterlists,\n         \"Return an iterator over the (key, [values]) pairs of a dictionary.\")\n\n\nif PY3:\n    def b(s):\n        return s.encode(\"latin-1\")\n\n    def u(s):\n        return s\n    unichr = chr\n    import struct\n    int2byte = struct.Struct(\">B\").pack\n    del struct\n    byte2int = operator.itemgetter(0)\n    indexbytes = operator.getitem\n    iterbytes = iter\n    import io\n    StringIO = io.StringIO\n    BytesIO = io.BytesIO\n    del io\n    _assertCountEqual = \"assertCountEqual\"\n    if sys.version_info[1] <= 1:\n        _assertRaisesRegex = \"assertRaisesRegexp\"\n        _assertRegex = \"assertRegexpMatches\"\n        _assertNotRegex = \"assertNotRegexpMatches\"\n    else:\n        _assertRaisesRegex = \"assertRaisesRegex\"\n        _assertRegex = \"assertRegex\"\n        _assertNotRegex = \"assertNotRegex\"\nelse:\n    def b(s):\n        return s\n    # Workaround for standalone backslash\n\n    def u(s):\n        return unicode(s.replace(r'\\\\', r'\\\\\\\\'), \"unicode_escape\")\n    unichr = unichr\n    int2byte = chr\n\n    def byte2int(bs):\n        return ord(bs[0])\n\n    def indexbytes(buf, i):\n        return ord(buf[i])\n    iterbytes = functools.partial(itertools.imap, ord)\n    import StringIO\n    StringIO = BytesIO = StringIO.StringIO\n    _assertCountEqual = \"assertItemsEqual\"\n    _assertRaisesRegex = \"assertRaisesRegexp\"\n    _assertRegex = \"assertRegexpMatches\"\n    _assertNotRegex = \"assertNotRegexpMatches\"\n_add_doc(b, \"\"\"Byte literal\"\"\")\n_add_doc(u, \"\"\"Text literal\"\"\")\n\n\ndef assertCountEqual(self, *args, **kwargs):\n    return getattr(self, _assertCountEqual)(*args, **kwargs)\n\n\ndef assertRaisesRegex(self, *args, **kwargs):\n    return getattr(self, _assertRaisesRegex)(*args, **kwargs)\n\n\ndef assertRegex(self, *args, **kwargs):\n    return getattr(self, _assertRegex)(*args, **kwargs)\n\n\ndef assertNotRegex(self, *args, **kwargs):\n    return getattr(self, _assertNotRegex)(*args, **kwargs)\n\n\nif PY3:\n    exec_ = getattr(moves.builtins, \"exec\")\n\n    def reraise(tp, value, tb=None):\n        try:\n            if value is None:\n                value = tp()\n            if value.__traceback__ is not tb:\n                raise value.with_traceback(tb)\n            raise value\n        finally:\n            value = None\n            tb = None\n\nelse:\n    def exec_(_code_, _globs_=None, _locs_=None):\n        \"\"\"Execute code in a namespace.\"\"\"\n        if _globs_ is None:\n            frame = sys._getframe(1)\n            _globs_ = frame.f_globals\n            if _locs_ is None:\n                _locs_ = frame.f_locals\n            del frame\n        elif _locs_ is None:\n            _locs_ = _globs_\n        exec(\"\"\"exec _code_ in _globs_, _locs_\"\"\")\n\n    exec_(\"\"\"def reraise(tp, value, tb=None):\n    try:\n        raise tp, value, tb\n    finally:\n        tb = None\n\"\"\")\n\n\nif sys.version_info[:2] > (3,):\n    exec_(\"\"\"def raise_from(value, from_value):\n    try:\n        raise value from from_value\n    finally:\n        value = None\n\"\"\")\nelse:\n    def raise_from(value, from_value):\n        raise value\n\n\nprint_ = getattr(moves.builtins, \"print\", None)\nif print_ is None:\n    def print_(*args, **kwargs):\n        \"\"\"The new-style print function for Python 2.4 and 2.5.\"\"\"\n        fp = kwargs.pop(\"file\", sys.stdout)\n        if fp is None:\n            return\n\n        def write(data):\n            if not isinstance(data, basestring):\n                data = str(data)\n            # If the file has an encoding, encode unicode with it.\n            if (isinstance(fp, file) and\n                    isinstance(data, unicode) and\n                    fp.encoding is not None):\n                errors = getattr(fp, \"errors\", None)\n                if errors is None:\n                    errors = \"strict\"\n                data = data.encode(fp.encoding, errors)\n            fp.write(data)\n        want_unicode = False\n        sep = kwargs.pop(\"sep\", None)\n        if sep is not None:\n            if isinstance(sep, unicode):\n                want_unicode = True\n            elif not isinstance(sep, str):\n                raise TypeError(\"sep must be None or a string\")\n        end = kwargs.pop(\"end\", None)\n        if end is not None:\n            if isinstance(end, unicode):\n                want_unicode = True\n            elif not isinstance(end, str):\n                raise TypeError(\"end must be None or a string\")\n        if kwargs:\n            raise TypeError(\"invalid keyword arguments to print()\")\n        if not want_unicode:\n            for arg in args:\n                if isinstance(arg, unicode):\n                    want_unicode = True\n                    break\n        if want_unicode:\n            newline = unicode(\"\\n\")\n            space = unicode(\" \")\n        else:\n            newline = \"\\n\"\n            space = \" \"\n        if sep is None:\n            sep = space\n        if end is None:\n            end = newline\n        for i, arg in enumerate(args):\n            if i:\n                write(sep)\n            write(arg)\n        write(end)\nif sys.version_info[:2] < (3, 3):\n    _print = print_\n\n    def print_(*args, **kwargs):\n        fp = kwargs.get(\"file\", sys.stdout)\n        flush = kwargs.pop(\"flush\", False)\n        _print(*args, **kwargs)\n        if flush and fp is not None:\n            fp.flush()\n\n_add_doc(reraise, \"\"\"Reraise an exception.\"\"\")\n\nif sys.version_info[0:2] < (3, 4):\n    # This does exactly the same what the :func:`py3:functools.update_wrapper`\n    # function does on Python versions after 3.2. It sets the ``__wrapped__``\n    # attribute on ``wrapper`` object and it doesn't raise an error if any of\n    # the attributes mentioned in ``assigned`` and ``updated`` are missing on\n    # ``wrapped`` object.\n    def _update_wrapper(wrapper, wrapped,\n                        assigned=functools.WRAPPER_ASSIGNMENTS,\n                        updated=functools.WRAPPER_UPDATES):\n        for attr in assigned:\n            try:\n                value = getattr(wrapped, attr)\n            except AttributeError:\n                continue\n            else:\n                setattr(wrapper, attr, value)\n        for attr in updated:\n            getattr(wrapper, attr).update(getattr(wrapped, attr, {}))\n        wrapper.__wrapped__ = wrapped\n        return wrapper\n    _update_wrapper.__doc__ = functools.update_wrapper.__doc__\n\n    def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS,\n              updated=functools.WRAPPER_UPDATES):\n        return functools.partial(_update_wrapper, wrapped=wrapped,\n                                 assigned=assigned, updated=updated)\n    wraps.__doc__ = functools.wraps.__doc__\n\nelse:\n    wraps = functools.wraps\n\n\ndef with_metaclass(meta, *bases):\n    \"\"\"Create a base class with a metaclass.\"\"\"\n    # This requires a bit of explanation: the basic idea is to make a dummy\n    # metaclass for one level of class instantiation that replaces itself with\n    # the actual metaclass.\n    class metaclass(type):\n\n        def __new__(cls, name, this_bases, d):\n            if sys.version_info[:2] >= (3, 7):\n                # This version introduced PEP 560 that requires a bit\n                # of extra care (we mimic what is done by __build_class__).\n                resolved_bases = types.resolve_bases(bases)\n                if resolved_bases is not bases:\n                    d['__orig_bases__'] = bases\n            else:\n                resolved_bases = bases\n            return meta(name, resolved_bases, d)\n\n        @classmethod\n        def __prepare__(cls, name, this_bases):\n            return meta.__prepare__(name, bases)\n    return type.__new__(metaclass, 'temporary_class', (), {})\n\n\ndef add_metaclass(metaclass):\n    \"\"\"Class decorator for creating a class with a metaclass.\"\"\"\n    def wrapper(cls):\n        orig_vars = cls.__dict__.copy()\n        slots = orig_vars.get('__slots__')\n        if slots is not None:\n            if isinstance(slots, str):\n                slots = [slots]\n            for slots_var in slots:\n                orig_vars.pop(slots_var)\n        orig_vars.pop('__dict__', None)\n        orig_vars.pop('__weakref__', None)\n        if hasattr(cls, '__qualname__'):\n            orig_vars['__qualname__'] = cls.__qualname__\n        return metaclass(cls.__name__, cls.__bases__, orig_vars)\n    return wrapper\n\n\ndef ensure_binary(s, encoding='utf-8', errors='strict'):\n    \"\"\"Coerce **s** to six.binary_type.\n\n    For Python 2:\n      - `unicode` -> encoded to `str`\n      - `str` -> `str`\n\n    For Python 3:\n      - `str` -> encoded to `bytes`\n      - `bytes` -> `bytes`\n    \"\"\"\n    if isinstance(s, binary_type):\n        return s\n    if isinstance(s, text_type):\n        return s.encode(encoding, errors)\n    raise TypeError(\"not expecting type '%s'\" % type(s))\n\n\ndef ensure_str(s, encoding='utf-8', errors='strict'):\n    \"\"\"Coerce *s* to `str`.\n\n    For Python 2:\n      - `unicode` -> encoded to `str`\n      - `str` -> `str`\n\n    For Python 3:\n      - `str` -> `str`\n      - `bytes` -> decoded to `str`\n    \"\"\"\n    # Optimization: Fast return for the common case.\n    if type(s) is str:\n        return s\n    if PY2 and isinstance(s, text_type):\n        return s.encode(encoding, errors)\n    elif PY3 and isinstance(s, binary_type):\n        return s.decode(encoding, errors)\n    elif not isinstance(s, (text_type, binary_type)):\n        raise TypeError(\"not expecting type '%s'\" % type(s))\n    return s\n\n\ndef ensure_text(s, encoding='utf-8', errors='strict'):\n    \"\"\"Coerce *s* to six.text_type.\n\n    For Python 2:\n      - `unicode` -> `unicode`\n      - `str` -> `unicode`\n\n    For Python 3:\n      - `str` -> `str`\n      - `bytes` -> decoded to `str`\n    \"\"\"\n    if isinstance(s, binary_type):\n        return s.decode(encoding, errors)\n    elif isinstance(s, text_type):\n        return s\n    else:\n        raise TypeError(\"not expecting type '%s'\" % type(s))\n\n\ndef python_2_unicode_compatible(klass):\n    \"\"\"\n    A class decorator that defines __unicode__ and __str__ methods under Python 2.\n    Under Python 3 it does nothing.\n\n    To support Python 2 and 3 with a single code base, define a __str__ method\n    returning text and apply this decorator to the class.\n    \"\"\"\n    if PY2:\n        if '__str__' not in klass.__dict__:\n            raise ValueError(\"@python_2_unicode_compatible cannot be applied \"\n                             \"to %s because it doesn't define __str__().\" %\n                             klass.__name__)\n        klass.__unicode__ = klass.__str__\n        klass.__str__ = lambda self: self.__unicode__().encode('utf-8')\n    return klass\n\n\n# Complete the moves implementation.\n# This code is at the end of this module to speed up module loading.\n# Turn this module into a package.\n__path__ = []  # required for PEP 302 and PEP 451\n__package__ = __name__  # see PEP 366 @ReservedAssignment\nif globals().get(\"__spec__\") is not None:\n    __spec__.submodule_search_locations = []  # PEP 451 @UndefinedVariable\n# Remove other six meta path importers, since they cause problems. This can\n# happen if six is removed from sys.modules and then reloaded. (Setuptools does\n# this for some reason.)\nif sys.meta_path:\n    for i, importer in enumerate(sys.meta_path):\n        # Here's some real nastiness: Another \"instance\" of the six module might\n        # be floating around. Therefore, we can't use isinstance() to check for\n        # the six meta path importer, since the other six instance will have\n        # inserted an importer with different class.\n        if (type(importer).__name__ == \"_SixMetaPathImporter\" and\n                importer.name == __name__):\n            del sys.meta_path[i]\n            break\n    del i, importer\n# Finally, add the importer to the meta path import hook.\nsys.meta_path.append(_importer)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tenacity/__init__.py",
    "content": "# Copyright 2016-2018 Julien Danjou\n# Copyright 2017 Elisey Zanko\n# Copyright 2016 Étienne Bersac\n# Copyright 2016 Joshua Harlow\n# Copyright 2013-2014 Ray Holder\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport functools\nimport sys\nimport threading\nimport time\nimport typing as t\nimport warnings\nfrom abc import ABC, abstractmethod\nfrom concurrent import futures\nfrom inspect import iscoroutinefunction\n\n# Import all built-in retry strategies for easier usage.\nfrom .retry import retry_base  # noqa\nfrom .retry import retry_all  # noqa\nfrom .retry import retry_always  # noqa\nfrom .retry import retry_any  # noqa\nfrom .retry import retry_if_exception  # noqa\nfrom .retry import retry_if_exception_type  # noqa\nfrom .retry import retry_if_exception_cause_type  # noqa\nfrom .retry import retry_if_not_exception_type  # noqa\nfrom .retry import retry_if_not_result  # noqa\nfrom .retry import retry_if_result  # noqa\nfrom .retry import retry_never  # noqa\nfrom .retry import retry_unless_exception_type  # noqa\nfrom .retry import retry_if_exception_message  # noqa\nfrom .retry import retry_if_not_exception_message  # noqa\n\n# Import all nap strategies for easier usage.\nfrom .nap import sleep  # noqa\nfrom .nap import sleep_using_event  # noqa\n\n# Import all built-in stop strategies for easier usage.\nfrom .stop import stop_after_attempt  # noqa\nfrom .stop import stop_after_delay  # noqa\nfrom .stop import stop_all  # noqa\nfrom .stop import stop_any  # noqa\nfrom .stop import stop_never  # noqa\nfrom .stop import stop_when_event_set  # noqa\n\n# Import all built-in wait strategies for easier usage.\nfrom .wait import wait_chain  # noqa\nfrom .wait import wait_combine  # noqa\nfrom .wait import wait_exponential  # noqa\nfrom .wait import wait_fixed  # noqa\nfrom .wait import wait_incrementing  # noqa\nfrom .wait import wait_none  # noqa\nfrom .wait import wait_random  # noqa\nfrom .wait import wait_random_exponential  # noqa\nfrom .wait import wait_random_exponential as wait_full_jitter  # noqa\nfrom .wait import wait_exponential_jitter  # noqa\n\n# Import all built-in before strategies for easier usage.\nfrom .before import before_log  # noqa\nfrom .before import before_nothing  # noqa\n\n# Import all built-in after strategies for easier usage.\nfrom .after import after_log  # noqa\nfrom .after import after_nothing  # noqa\n\n# Import all built-in after strategies for easier usage.\nfrom .before_sleep import before_sleep_log  # noqa\nfrom .before_sleep import before_sleep_nothing  # noqa\n\n# Replace a conditional import with a hard-coded None so that pip does\n# not attempt to use tornado even if it is present in the environment.\n# If tornado is non-None, tenacity will attempt to execute some code\n# that is sensitive to the version of tornado, which could break pip\n# if an old version is found.\ntornado = None  # type: ignore\n\nif t.TYPE_CHECKING:\n    import types\n\n    from .wait import wait_base\n    from .stop import stop_base\n\n\nWrappedFn = t.TypeVar(\"WrappedFn\", bound=t.Callable)\n_RetValT = t.TypeVar(\"_RetValT\")\n\n\n@t.overload\ndef retry(fn: WrappedFn) -> WrappedFn:\n    pass\n\n\n@t.overload\ndef retry(*dargs: t.Any, **dkw: t.Any) -> t.Callable[[WrappedFn], WrappedFn]:  # noqa\n    pass\n\n\ndef retry(*dargs: t.Any, **dkw: t.Any) -> t.Union[WrappedFn, t.Callable[[WrappedFn], WrappedFn]]:  # noqa\n    \"\"\"Wrap a function with a new `Retrying` object.\n\n    :param dargs: positional arguments passed to Retrying object\n    :param dkw: keyword arguments passed to the Retrying object\n    \"\"\"\n    # support both @retry and @retry() as valid syntax\n    if len(dargs) == 1 and callable(dargs[0]):\n        return retry()(dargs[0])\n    else:\n\n        def wrap(f: WrappedFn) -> WrappedFn:\n            if isinstance(f, retry_base):\n                warnings.warn(\n                    f\"Got retry_base instance ({f.__class__.__name__}) as callable argument, \"\n                    f\"this will probably hang indefinitely (did you mean retry={f.__class__.__name__}(...)?)\"\n                )\n            if iscoroutinefunction(f):\n                r: \"BaseRetrying\" = AsyncRetrying(*dargs, **dkw)\n            elif tornado and hasattr(tornado.gen, \"is_coroutine_function\") and tornado.gen.is_coroutine_function(f):\n                r = TornadoRetrying(*dargs, **dkw)\n            else:\n                r = Retrying(*dargs, **dkw)\n\n            return r.wraps(f)\n\n        return wrap\n\n\nclass TryAgain(Exception):\n    \"\"\"Always retry the executed function when raised.\"\"\"\n\n\nNO_RESULT = object()\n\n\nclass DoAttempt:\n    pass\n\n\nclass DoSleep(float):\n    pass\n\n\nclass BaseAction:\n    \"\"\"Base class for representing actions to take by retry object.\n\n    Concrete implementations must define:\n    - __init__: to initialize all necessary fields\n    - REPR_FIELDS: class variable specifying attributes to include in repr(self)\n    - NAME: for identification in retry object methods and callbacks\n    \"\"\"\n\n    REPR_FIELDS: t.Sequence[str] = ()\n    NAME: t.Optional[str] = None\n\n    def __repr__(self) -> str:\n        state_str = \", \".join(f\"{field}={getattr(self, field)!r}\" for field in self.REPR_FIELDS)\n        return f\"{self.__class__.__name__}({state_str})\"\n\n    def __str__(self) -> str:\n        return repr(self)\n\n\nclass RetryAction(BaseAction):\n    REPR_FIELDS = (\"sleep\",)\n    NAME = \"retry\"\n\n    def __init__(self, sleep: t.SupportsFloat) -> None:\n        self.sleep = float(sleep)\n\n\n_unset = object()\n\n\ndef _first_set(first: t.Union[t.Any, object], second: t.Any) -> t.Any:\n    return second if first is _unset else first\n\n\nclass RetryError(Exception):\n    \"\"\"Encapsulates the last attempt instance right before giving up.\"\"\"\n\n    def __init__(self, last_attempt: \"Future\") -> None:\n        self.last_attempt = last_attempt\n        super().__init__(last_attempt)\n\n    def reraise(self) -> \"t.NoReturn\":\n        if self.last_attempt.failed:\n            raise self.last_attempt.result()\n        raise self\n\n    def __str__(self) -> str:\n        return f\"{self.__class__.__name__}[{self.last_attempt}]\"\n\n\nclass AttemptManager:\n    \"\"\"Manage attempt context.\"\"\"\n\n    def __init__(self, retry_state: \"RetryCallState\"):\n        self.retry_state = retry_state\n\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(\n        self,\n        exc_type: t.Optional[t.Type[BaseException]],\n        exc_value: t.Optional[BaseException],\n        traceback: t.Optional[\"types.TracebackType\"],\n    ) -> t.Optional[bool]:\n        if isinstance(exc_value, BaseException):\n            self.retry_state.set_exception((exc_type, exc_value, traceback))\n            return True  # Swallow exception.\n        else:\n            # We don't have the result, actually.\n            self.retry_state.set_result(None)\n            return None\n\n\nclass BaseRetrying(ABC):\n    def __init__(\n        self,\n        sleep: t.Callable[[t.Union[int, float]], None] = sleep,\n        stop: \"stop_base\" = stop_never,\n        wait: \"wait_base\" = wait_none(),\n        retry: retry_base = retry_if_exception_type(),\n        before: t.Callable[[\"RetryCallState\"], None] = before_nothing,\n        after: t.Callable[[\"RetryCallState\"], None] = after_nothing,\n        before_sleep: t.Optional[t.Callable[[\"RetryCallState\"], None]] = None,\n        reraise: bool = False,\n        retry_error_cls: t.Type[RetryError] = RetryError,\n        retry_error_callback: t.Optional[t.Callable[[\"RetryCallState\"], t.Any]] = None,\n    ):\n        self.sleep = sleep\n        self.stop = stop\n        self.wait = wait\n        self.retry = retry\n        self.before = before\n        self.after = after\n        self.before_sleep = before_sleep\n        self.reraise = reraise\n        self._local = threading.local()\n        self.retry_error_cls = retry_error_cls\n        self.retry_error_callback = retry_error_callback\n\n    def copy(\n        self,\n        sleep: t.Union[t.Callable[[t.Union[int, float]], None], object] = _unset,\n        stop: t.Union[\"stop_base\", object] = _unset,\n        wait: t.Union[\"wait_base\", object] = _unset,\n        retry: t.Union[retry_base, object] = _unset,\n        before: t.Union[t.Callable[[\"RetryCallState\"], None], object] = _unset,\n        after: t.Union[t.Callable[[\"RetryCallState\"], None], object] = _unset,\n        before_sleep: t.Union[t.Optional[t.Callable[[\"RetryCallState\"], None]], object] = _unset,\n        reraise: t.Union[bool, object] = _unset,\n        retry_error_cls: t.Union[t.Type[RetryError], object] = _unset,\n        retry_error_callback: t.Union[t.Optional[t.Callable[[\"RetryCallState\"], t.Any]], object] = _unset,\n    ) -> \"BaseRetrying\":\n        \"\"\"Copy this object with some parameters changed if needed.\"\"\"\n        return self.__class__(\n            sleep=_first_set(sleep, self.sleep),\n            stop=_first_set(stop, self.stop),\n            wait=_first_set(wait, self.wait),\n            retry=_first_set(retry, self.retry),\n            before=_first_set(before, self.before),\n            after=_first_set(after, self.after),\n            before_sleep=_first_set(before_sleep, self.before_sleep),\n            reraise=_first_set(reraise, self.reraise),\n            retry_error_cls=_first_set(retry_error_cls, self.retry_error_cls),\n            retry_error_callback=_first_set(retry_error_callback, self.retry_error_callback),\n        )\n\n    def __repr__(self) -> str:\n        return (\n            f\"<{self.__class__.__name__} object at 0x{id(self):x} (\"\n            f\"stop={self.stop}, \"\n            f\"wait={self.wait}, \"\n            f\"sleep={self.sleep}, \"\n            f\"retry={self.retry}, \"\n            f\"before={self.before}, \"\n            f\"after={self.after})>\"\n        )\n\n    @property\n    def statistics(self) -> t.Dict[str, t.Any]:\n        \"\"\"Return a dictionary of runtime statistics.\n\n        This dictionary will be empty when the controller has never been\n        ran. When it is running or has ran previously it should have (but\n        may not) have useful and/or informational keys and values when\n        running is underway and/or completed.\n\n        .. warning:: The keys in this dictionary **should** be some what\n                     stable (not changing), but there existence **may**\n                     change between major releases as new statistics are\n                     gathered or removed so before accessing keys ensure that\n                     they actually exist and handle when they do not.\n\n        .. note:: The values in this dictionary are local to the thread\n                  running call (so if multiple threads share the same retrying\n                  object - either directly or indirectly) they will each have\n                  there own view of statistics they have collected (in the\n                  future we may provide a way to aggregate the various\n                  statistics from each thread).\n        \"\"\"\n        try:\n            return self._local.statistics\n        except AttributeError:\n            self._local.statistics = {}\n            return self._local.statistics\n\n    def wraps(self, f: WrappedFn) -> WrappedFn:\n        \"\"\"Wrap a function for retrying.\n\n        :param f: A function to wraps for retrying.\n        \"\"\"\n\n        @functools.wraps(f)\n        def wrapped_f(*args: t.Any, **kw: t.Any) -> t.Any:\n            return self(f, *args, **kw)\n\n        def retry_with(*args: t.Any, **kwargs: t.Any) -> WrappedFn:\n            return self.copy(*args, **kwargs).wraps(f)\n\n        wrapped_f.retry = self\n        wrapped_f.retry_with = retry_with\n\n        return wrapped_f\n\n    def begin(self) -> None:\n        self.statistics.clear()\n        self.statistics[\"start_time\"] = time.monotonic()\n        self.statistics[\"attempt_number\"] = 1\n        self.statistics[\"idle_for\"] = 0\n\n    def iter(self, retry_state: \"RetryCallState\") -> t.Union[DoAttempt, DoSleep, t.Any]:  # noqa\n        fut = retry_state.outcome\n        if fut is None:\n            if self.before is not None:\n                self.before(retry_state)\n            return DoAttempt()\n\n        is_explicit_retry = retry_state.outcome.failed and isinstance(retry_state.outcome.exception(), TryAgain)\n        if not (is_explicit_retry or self.retry(retry_state=retry_state)):\n            return fut.result()\n\n        if self.after is not None:\n            self.after(retry_state)\n\n        self.statistics[\"delay_since_first_attempt\"] = retry_state.seconds_since_start\n        if self.stop(retry_state=retry_state):\n            if self.retry_error_callback:\n                return self.retry_error_callback(retry_state)\n            retry_exc = self.retry_error_cls(fut)\n            if self.reraise:\n                raise retry_exc.reraise()\n            raise retry_exc from fut.exception()\n\n        if self.wait:\n            sleep = self.wait(retry_state=retry_state)\n        else:\n            sleep = 0.0\n        retry_state.next_action = RetryAction(sleep)\n        retry_state.idle_for += sleep\n        self.statistics[\"idle_for\"] += sleep\n        self.statistics[\"attempt_number\"] += 1\n\n        if self.before_sleep is not None:\n            self.before_sleep(retry_state)\n\n        return DoSleep(sleep)\n\n    def __iter__(self) -> t.Generator[AttemptManager, None, None]:\n        self.begin()\n\n        retry_state = RetryCallState(self, fn=None, args=(), kwargs={})\n        while True:\n            do = self.iter(retry_state=retry_state)\n            if isinstance(do, DoAttempt):\n                yield AttemptManager(retry_state=retry_state)\n            elif isinstance(do, DoSleep):\n                retry_state.prepare_for_next_attempt()\n                self.sleep(do)\n            else:\n                break\n\n    @abstractmethod\n    def __call__(self, fn: t.Callable[..., _RetValT], *args: t.Any, **kwargs: t.Any) -> _RetValT:\n        pass\n\n\nclass Retrying(BaseRetrying):\n    \"\"\"Retrying controller.\"\"\"\n\n    def __call__(self, fn: t.Callable[..., _RetValT], *args: t.Any, **kwargs: t.Any) -> _RetValT:\n        self.begin()\n\n        retry_state = RetryCallState(retry_object=self, fn=fn, args=args, kwargs=kwargs)\n        while True:\n            do = self.iter(retry_state=retry_state)\n            if isinstance(do, DoAttempt):\n                try:\n                    result = fn(*args, **kwargs)\n                except BaseException:  # noqa: B902\n                    retry_state.set_exception(sys.exc_info())\n                else:\n                    retry_state.set_result(result)\n            elif isinstance(do, DoSleep):\n                retry_state.prepare_for_next_attempt()\n                self.sleep(do)\n            else:\n                return do\n\n\nclass Future(futures.Future):\n    \"\"\"Encapsulates a (future or past) attempted call to a target function.\"\"\"\n\n    def __init__(self, attempt_number: int) -> None:\n        super().__init__()\n        self.attempt_number = attempt_number\n\n    @property\n    def failed(self) -> bool:\n        \"\"\"Return whether a exception is being held in this future.\"\"\"\n        return self.exception() is not None\n\n    @classmethod\n    def construct(cls, attempt_number: int, value: t.Any, has_exception: bool) -> \"Future\":\n        \"\"\"Construct a new Future object.\"\"\"\n        fut = cls(attempt_number)\n        if has_exception:\n            fut.set_exception(value)\n        else:\n            fut.set_result(value)\n        return fut\n\n\nclass RetryCallState:\n    \"\"\"State related to a single call wrapped with Retrying.\"\"\"\n\n    def __init__(\n        self,\n        retry_object: BaseRetrying,\n        fn: t.Optional[WrappedFn],\n        args: t.Any,\n        kwargs: t.Any,\n    ) -> None:\n        #: Retry call start timestamp\n        self.start_time = time.monotonic()\n        #: Retry manager object\n        self.retry_object = retry_object\n        #: Function wrapped by this retry call\n        self.fn = fn\n        #: Arguments of the function wrapped by this retry call\n        self.args = args\n        #: Keyword arguments of the function wrapped by this retry call\n        self.kwargs = kwargs\n\n        #: The number of the current attempt\n        self.attempt_number: int = 1\n        #: Last outcome (result or exception) produced by the function\n        self.outcome: t.Optional[Future] = None\n        #: Timestamp of the last outcome\n        self.outcome_timestamp: t.Optional[float] = None\n        #: Time spent sleeping in retries\n        self.idle_for: float = 0.0\n        #: Next action as decided by the retry manager\n        self.next_action: t.Optional[RetryAction] = None\n\n    @property\n    def seconds_since_start(self) -> t.Optional[float]:\n        if self.outcome_timestamp is None:\n            return None\n        return self.outcome_timestamp - self.start_time\n\n    def prepare_for_next_attempt(self) -> None:\n        self.outcome = None\n        self.outcome_timestamp = None\n        self.attempt_number += 1\n        self.next_action = None\n\n    def set_result(self, val: t.Any) -> None:\n        ts = time.monotonic()\n        fut = Future(self.attempt_number)\n        fut.set_result(val)\n        self.outcome, self.outcome_timestamp = fut, ts\n\n    def set_exception(self, exc_info: t.Tuple[t.Type[BaseException], BaseException, \"types.TracebackType\"]) -> None:\n        ts = time.monotonic()\n        fut = Future(self.attempt_number)\n        fut.set_exception(exc_info[1])\n        self.outcome, self.outcome_timestamp = fut, ts\n\n    def __repr__(self):\n        if self.outcome is None:\n            result = \"none yet\"\n        elif self.outcome.failed:\n            exception = self.outcome.exception()\n            result = f\"failed ({exception.__class__.__name__} {exception})\"\n        else:\n            result = f\"returned {self.outcome.result()}\"\n\n        slept = float(round(self.idle_for, 2))\n        clsname = self.__class__.__name__\n        return f\"<{clsname} {id(self)}: attempt #{self.attempt_number}; slept for {slept}; last result: {result}>\"\n\n\nfrom pip._vendor.tenacity._asyncio import AsyncRetrying  # noqa:E402,I100\n\nif tornado:\n    from pip._vendor.tenacity.tornadoweb import TornadoRetrying\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tenacity/_asyncio.py",
    "content": "# Copyright 2016 Étienne Bersac\n# Copyright 2016 Julien Danjou\n# Copyright 2016 Joshua Harlow\n# Copyright 2013-2014 Ray Holder\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport functools\nimport sys\nimport typing\nfrom asyncio import sleep\n\nfrom pip._vendor.tenacity import AttemptManager\nfrom pip._vendor.tenacity import BaseRetrying\nfrom pip._vendor.tenacity import DoAttempt\nfrom pip._vendor.tenacity import DoSleep\nfrom pip._vendor.tenacity import RetryCallState\n\nWrappedFn = typing.TypeVar(\"WrappedFn\", bound=typing.Callable)\n_RetValT = typing.TypeVar(\"_RetValT\")\n\n\nclass AsyncRetrying(BaseRetrying):\n    def __init__(self, sleep: typing.Callable[[float], typing.Awaitable] = sleep, **kwargs: typing.Any) -> None:\n        super().__init__(**kwargs)\n        self.sleep = sleep\n\n    async def __call__(  # type: ignore  # Change signature from supertype\n        self,\n        fn: typing.Callable[..., typing.Awaitable[_RetValT]],\n        *args: typing.Any,\n        **kwargs: typing.Any,\n    ) -> _RetValT:\n        self.begin()\n\n        retry_state = RetryCallState(retry_object=self, fn=fn, args=args, kwargs=kwargs)\n        while True:\n            do = self.iter(retry_state=retry_state)\n            if isinstance(do, DoAttempt):\n                try:\n                    result = await fn(*args, **kwargs)\n                except BaseException:  # noqa: B902\n                    retry_state.set_exception(sys.exc_info())\n                else:\n                    retry_state.set_result(result)\n            elif isinstance(do, DoSleep):\n                retry_state.prepare_for_next_attempt()\n                await self.sleep(do)\n            else:\n                return do\n\n    def __aiter__(self) -> \"AsyncRetrying\":\n        self.begin()\n        self._retry_state = RetryCallState(self, fn=None, args=(), kwargs={})\n        return self\n\n    async def __anext__(self) -> typing.Union[AttemptManager, typing.Any]:\n        while True:\n            do = self.iter(retry_state=self._retry_state)\n            if do is None:\n                raise StopAsyncIteration\n            elif isinstance(do, DoAttempt):\n                return AttemptManager(retry_state=self._retry_state)\n            elif isinstance(do, DoSleep):\n                self._retry_state.prepare_for_next_attempt()\n                await self.sleep(do)\n            else:\n                return do\n\n    def wraps(self, fn: WrappedFn) -> WrappedFn:\n        fn = super().wraps(fn)\n        # Ensure wrapper is recognized as a coroutine function.\n\n        @functools.wraps(fn)\n        async def async_wrapped(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:\n            return await fn(*args, **kwargs)\n\n        # Preserve attributes\n        async_wrapped.retry = fn.retry\n        async_wrapped.retry_with = fn.retry_with\n\n        return async_wrapped\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tenacity/_utils.py",
    "content": "# Copyright 2016 Julien Danjou\n# Copyright 2016 Joshua Harlow\n# Copyright 2013-2014 Ray Holder\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nimport typing\n\n\n# sys.maxsize:\n# An integer giving the maximum value a variable of type Py_ssize_t can take.\nMAX_WAIT = sys.maxsize / 2\n\n\ndef find_ordinal(pos_num: int) -> str:\n    # See: https://en.wikipedia.org/wiki/English_numerals#Ordinal_numbers\n    if pos_num == 0:\n        return \"th\"\n    elif pos_num == 1:\n        return \"st\"\n    elif pos_num == 2:\n        return \"nd\"\n    elif pos_num == 3:\n        return \"rd\"\n    elif 4 <= pos_num <= 20:\n        return \"th\"\n    else:\n        return find_ordinal(pos_num % 10)\n\n\ndef to_ordinal(pos_num: int) -> str:\n    return f\"{pos_num}{find_ordinal(pos_num)}\"\n\n\ndef get_callback_name(cb: typing.Callable[..., typing.Any]) -> str:\n    \"\"\"Get a callback fully-qualified name.\n\n    If no name can be produced ``repr(cb)`` is called and returned.\n    \"\"\"\n    segments = []\n    try:\n        segments.append(cb.__qualname__)\n    except AttributeError:\n        try:\n            segments.append(cb.__name__)\n        except AttributeError:\n            pass\n    if not segments:\n        return repr(cb)\n    else:\n        try:\n            # When running under sphinx it appears this can be none?\n            if cb.__module__:\n                segments.insert(0, cb.__module__)\n        except AttributeError:\n            pass\n        return \".\".join(segments)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tenacity/after.py",
    "content": "# Copyright 2016 Julien Danjou\n# Copyright 2016 Joshua Harlow\n# Copyright 2013-2014 Ray Holder\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport typing\n\nfrom pip._vendor.tenacity import _utils\n\nif typing.TYPE_CHECKING:\n    import logging\n\n    from pip._vendor.tenacity import RetryCallState\n\n\ndef after_nothing(retry_state: \"RetryCallState\") -> None:\n    \"\"\"After call strategy that does nothing.\"\"\"\n\n\ndef after_log(\n    logger: \"logging.Logger\",\n    log_level: int,\n    sec_format: str = \"%0.3f\",\n) -> typing.Callable[[\"RetryCallState\"], None]:\n    \"\"\"After call strategy that logs to some logger the finished attempt.\"\"\"\n\n    def log_it(retry_state: \"RetryCallState\") -> None:\n        logger.log(\n            log_level,\n            f\"Finished call to '{_utils.get_callback_name(retry_state.fn)}' \"\n            f\"after {sec_format % retry_state.seconds_since_start}(s), \"\n            f\"this was the {_utils.to_ordinal(retry_state.attempt_number)} time calling it.\",\n        )\n\n    return log_it\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tenacity/before.py",
    "content": "# Copyright 2016 Julien Danjou\n# Copyright 2016 Joshua Harlow\n# Copyright 2013-2014 Ray Holder\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport typing\n\nfrom pip._vendor.tenacity import _utils\n\nif typing.TYPE_CHECKING:\n    import logging\n\n    from pip._vendor.tenacity import RetryCallState\n\n\ndef before_nothing(retry_state: \"RetryCallState\") -> None:\n    \"\"\"Before call strategy that does nothing.\"\"\"\n\n\ndef before_log(logger: \"logging.Logger\", log_level: int) -> typing.Callable[[\"RetryCallState\"], None]:\n    \"\"\"Before call strategy that logs to some logger the attempt.\"\"\"\n\n    def log_it(retry_state: \"RetryCallState\") -> None:\n        logger.log(\n            log_level,\n            f\"Starting call to '{_utils.get_callback_name(retry_state.fn)}', \"\n            f\"this is the {_utils.to_ordinal(retry_state.attempt_number)} time calling it.\",\n        )\n\n    return log_it\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tenacity/before_sleep.py",
    "content": "# Copyright 2016 Julien Danjou\n# Copyright 2016 Joshua Harlow\n# Copyright 2013-2014 Ray Holder\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport typing\n\nfrom pip._vendor.tenacity import _utils\n\nif typing.TYPE_CHECKING:\n    import logging\n\n    from pip._vendor.tenacity import RetryCallState\n\n\ndef before_sleep_nothing(retry_state: \"RetryCallState\") -> None:\n    \"\"\"Before call strategy that does nothing.\"\"\"\n\n\ndef before_sleep_log(\n    logger: \"logging.Logger\",\n    log_level: int,\n    exc_info: bool = False,\n) -> typing.Callable[[\"RetryCallState\"], None]:\n    \"\"\"Before call strategy that logs to some logger the attempt.\"\"\"\n\n    def log_it(retry_state: \"RetryCallState\") -> None:\n        if retry_state.outcome.failed:\n            ex = retry_state.outcome.exception()\n            verb, value = \"raised\", f\"{ex.__class__.__name__}: {ex}\"\n\n            if exc_info:\n                local_exc_info = retry_state.outcome.exception()\n            else:\n                local_exc_info = False\n        else:\n            verb, value = \"returned\", retry_state.outcome.result()\n            local_exc_info = False  # exc_info does not apply when no exception\n\n        logger.log(\n            log_level,\n            f\"Retrying {_utils.get_callback_name(retry_state.fn)} \"\n            f\"in {retry_state.next_action.sleep} seconds as it {verb} {value}.\",\n            exc_info=local_exc_info,\n        )\n\n    return log_it\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tenacity/nap.py",
    "content": "# Copyright 2016 Étienne Bersac\n# Copyright 2016 Julien Danjou\n# Copyright 2016 Joshua Harlow\n# Copyright 2013-2014 Ray Holder\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport time\nimport typing\n\nif typing.TYPE_CHECKING:\n    import threading\n\n\ndef sleep(seconds: float) -> None:\n    \"\"\"\n    Sleep strategy that delays execution for a given number of seconds.\n\n    This is the default strategy, and may be mocked out for unit testing.\n    \"\"\"\n    time.sleep(seconds)\n\n\nclass sleep_using_event:\n    \"\"\"Sleep strategy that waits on an event to be set.\"\"\"\n\n    def __init__(self, event: \"threading.Event\") -> None:\n        self.event = event\n\n    def __call__(self, timeout: typing.Optional[float]) -> None:\n        # NOTE(harlowja): this may *not* actually wait for timeout\n        # seconds if the event is set (ie this may eject out early).\n        self.event.wait(timeout=timeout)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tenacity/retry.py",
    "content": "# Copyright 2016–2021 Julien Danjou\n# Copyright 2016 Joshua Harlow\n# Copyright 2013-2014 Ray Holder\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport abc\nimport re\nimport typing\n\nif typing.TYPE_CHECKING:\n    from pip._vendor.tenacity import RetryCallState\n\n\nclass retry_base(abc.ABC):\n    \"\"\"Abstract base class for retry strategies.\"\"\"\n\n    @abc.abstractmethod\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        pass\n\n    def __and__(self, other: \"retry_base\") -> \"retry_all\":\n        return retry_all(self, other)\n\n    def __or__(self, other: \"retry_base\") -> \"retry_any\":\n        return retry_any(self, other)\n\n\nclass _retry_never(retry_base):\n    \"\"\"Retry strategy that never rejects any result.\"\"\"\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        return False\n\n\nretry_never = _retry_never()\n\n\nclass _retry_always(retry_base):\n    \"\"\"Retry strategy that always rejects any result.\"\"\"\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        return True\n\n\nretry_always = _retry_always()\n\n\nclass retry_if_exception(retry_base):\n    \"\"\"Retry strategy that retries if an exception verifies a predicate.\"\"\"\n\n    def __init__(self, predicate: typing.Callable[[BaseException], bool]) -> None:\n        self.predicate = predicate\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        if retry_state.outcome.failed:\n            return self.predicate(retry_state.outcome.exception())\n        else:\n            return False\n\n\nclass retry_if_exception_type(retry_if_exception):\n    \"\"\"Retries if an exception has been raised of one or more types.\"\"\"\n\n    def __init__(\n        self,\n        exception_types: typing.Union[\n            typing.Type[BaseException],\n            typing.Tuple[typing.Type[BaseException], ...],\n        ] = Exception,\n    ) -> None:\n        self.exception_types = exception_types\n        super().__init__(lambda e: isinstance(e, exception_types))\n\n\nclass retry_if_not_exception_type(retry_if_exception):\n    \"\"\"Retries except an exception has been raised of one or more types.\"\"\"\n\n    def __init__(\n        self,\n        exception_types: typing.Union[\n            typing.Type[BaseException],\n            typing.Tuple[typing.Type[BaseException], ...],\n        ] = Exception,\n    ) -> None:\n        self.exception_types = exception_types\n        super().__init__(lambda e: not isinstance(e, exception_types))\n\n\nclass retry_unless_exception_type(retry_if_exception):\n    \"\"\"Retries until an exception is raised of one or more types.\"\"\"\n\n    def __init__(\n        self,\n        exception_types: typing.Union[\n            typing.Type[BaseException],\n            typing.Tuple[typing.Type[BaseException], ...],\n        ] = Exception,\n    ) -> None:\n        self.exception_types = exception_types\n        super().__init__(lambda e: not isinstance(e, exception_types))\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        # always retry if no exception was raised\n        if not retry_state.outcome.failed:\n            return True\n        return self.predicate(retry_state.outcome.exception())\n\n\nclass retry_if_exception_cause_type(retry_base):\n    \"\"\"Retries if any of the causes of the raised exception is of one or more types.\n\n    The check on the type of the cause of the exception is done recursively (until finding\n    an exception in the chain that has no `__cause__`)\n    \"\"\"\n\n    def __init__(\n        self,\n        exception_types: typing.Union[\n            typing.Type[BaseException],\n            typing.Tuple[typing.Type[BaseException], ...],\n        ] = Exception,\n    ) -> None:\n        self.exception_cause_types = exception_types\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        if retry_state.outcome.failed:\n            exc = retry_state.outcome.exception()\n            while exc is not None:\n                if isinstance(exc.__cause__, self.exception_cause_types):\n                    return True\n                exc = exc.__cause__\n\n        return False\n\n\nclass retry_if_result(retry_base):\n    \"\"\"Retries if the result verifies a predicate.\"\"\"\n\n    def __init__(self, predicate: typing.Callable[[typing.Any], bool]) -> None:\n        self.predicate = predicate\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        if not retry_state.outcome.failed:\n            return self.predicate(retry_state.outcome.result())\n        else:\n            return False\n\n\nclass retry_if_not_result(retry_base):\n    \"\"\"Retries if the result refutes a predicate.\"\"\"\n\n    def __init__(self, predicate: typing.Callable[[typing.Any], bool]) -> None:\n        self.predicate = predicate\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        if not retry_state.outcome.failed:\n            return not self.predicate(retry_state.outcome.result())\n        else:\n            return False\n\n\nclass retry_if_exception_message(retry_if_exception):\n    \"\"\"Retries if an exception message equals or matches.\"\"\"\n\n    def __init__(\n        self,\n        message: typing.Optional[str] = None,\n        match: typing.Optional[str] = None,\n    ) -> None:\n        if message and match:\n            raise TypeError(f\"{self.__class__.__name__}() takes either 'message' or 'match', not both\")\n\n        # set predicate\n        if message:\n\n            def message_fnc(exception: BaseException) -> bool:\n                return message == str(exception)\n\n            predicate = message_fnc\n        elif match:\n            prog = re.compile(match)\n\n            def match_fnc(exception: BaseException) -> bool:\n                return bool(prog.match(str(exception)))\n\n            predicate = match_fnc\n        else:\n            raise TypeError(f\"{self.__class__.__name__}() missing 1 required argument 'message' or 'match'\")\n\n        super().__init__(predicate)\n\n\nclass retry_if_not_exception_message(retry_if_exception_message):\n    \"\"\"Retries until an exception message equals or matches.\"\"\"\n\n    def __init__(\n        self,\n        message: typing.Optional[str] = None,\n        match: typing.Optional[str] = None,\n    ) -> None:\n        super().__init__(message, match)\n        # invert predicate\n        if_predicate = self.predicate\n        self.predicate = lambda *args_, **kwargs_: not if_predicate(*args_, **kwargs_)\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        if not retry_state.outcome.failed:\n            return True\n        return self.predicate(retry_state.outcome.exception())\n\n\nclass retry_any(retry_base):\n    \"\"\"Retries if any of the retries condition is valid.\"\"\"\n\n    def __init__(self, *retries: retry_base) -> None:\n        self.retries = retries\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        return any(r(retry_state) for r in self.retries)\n\n\nclass retry_all(retry_base):\n    \"\"\"Retries if all the retries condition are valid.\"\"\"\n\n    def __init__(self, *retries: retry_base) -> None:\n        self.retries = retries\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        return all(r(retry_state) for r in self.retries)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tenacity/stop.py",
    "content": "# Copyright 2016–2021 Julien Danjou\n# Copyright 2016 Joshua Harlow\n# Copyright 2013-2014 Ray Holder\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport abc\nimport typing\n\nif typing.TYPE_CHECKING:\n    import threading\n\n    from pip._vendor.tenacity import RetryCallState\n\n\nclass stop_base(abc.ABC):\n    \"\"\"Abstract base class for stop strategies.\"\"\"\n\n    @abc.abstractmethod\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        pass\n\n    def __and__(self, other: \"stop_base\") -> \"stop_all\":\n        return stop_all(self, other)\n\n    def __or__(self, other: \"stop_base\") -> \"stop_any\":\n        return stop_any(self, other)\n\n\nclass stop_any(stop_base):\n    \"\"\"Stop if any of the stop condition is valid.\"\"\"\n\n    def __init__(self, *stops: stop_base) -> None:\n        self.stops = stops\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        return any(x(retry_state) for x in self.stops)\n\n\nclass stop_all(stop_base):\n    \"\"\"Stop if all the stop conditions are valid.\"\"\"\n\n    def __init__(self, *stops: stop_base) -> None:\n        self.stops = stops\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        return all(x(retry_state) for x in self.stops)\n\n\nclass _stop_never(stop_base):\n    \"\"\"Never stop.\"\"\"\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        return False\n\n\nstop_never = _stop_never()\n\n\nclass stop_when_event_set(stop_base):\n    \"\"\"Stop when the given event is set.\"\"\"\n\n    def __init__(self, event: \"threading.Event\") -> None:\n        self.event = event\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        return self.event.is_set()\n\n\nclass stop_after_attempt(stop_base):\n    \"\"\"Stop when the previous attempt >= max_attempt.\"\"\"\n\n    def __init__(self, max_attempt_number: int) -> None:\n        self.max_attempt_number = max_attempt_number\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        return retry_state.attempt_number >= self.max_attempt_number\n\n\nclass stop_after_delay(stop_base):\n    \"\"\"Stop when the time from the first attempt >= limit.\"\"\"\n\n    def __init__(self, max_delay: float) -> None:\n        self.max_delay = max_delay\n\n    def __call__(self, retry_state: \"RetryCallState\") -> bool:\n        return retry_state.seconds_since_start >= self.max_delay\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tenacity/tornadoweb.py",
    "content": "# Copyright 2017 Elisey Zanko\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nimport typing\n\nfrom pip._vendor.tenacity import BaseRetrying\nfrom pip._vendor.tenacity import DoAttempt\nfrom pip._vendor.tenacity import DoSleep\nfrom pip._vendor.tenacity import RetryCallState\n\nfrom tornado import gen\n\nif typing.TYPE_CHECKING:\n    from tornado.concurrent import Future\n\n_RetValT = typing.TypeVar(\"_RetValT\")\n\n\nclass TornadoRetrying(BaseRetrying):\n    def __init__(self, sleep: \"typing.Callable[[float], Future[None]]\" = gen.sleep, **kwargs: typing.Any) -> None:\n        super().__init__(**kwargs)\n        self.sleep = sleep\n\n    @gen.coroutine\n    def __call__(  # type: ignore  # Change signature from supertype\n        self,\n        fn: \"typing.Callable[..., typing.Union[typing.Generator[typing.Any, typing.Any, _RetValT], Future[_RetValT]]]\",\n        *args: typing.Any,\n        **kwargs: typing.Any,\n    ) -> \"typing.Generator[typing.Any, typing.Any, _RetValT]\":\n        self.begin()\n\n        retry_state = RetryCallState(retry_object=self, fn=fn, args=args, kwargs=kwargs)\n        while True:\n            do = self.iter(retry_state=retry_state)\n            if isinstance(do, DoAttempt):\n                try:\n                    result = yield fn(*args, **kwargs)\n                except BaseException:  # noqa: B902\n                    retry_state.set_exception(sys.exc_info())\n                else:\n                    retry_state.set_result(result)\n            elif isinstance(do, DoSleep):\n                retry_state.prepare_for_next_attempt()\n                yield self.sleep(do)\n            else:\n                raise gen.Return(do)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tenacity/wait.py",
    "content": "# Copyright 2016–2021 Julien Danjou\n# Copyright 2016 Joshua Harlow\n# Copyright 2013-2014 Ray Holder\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport abc\nimport random\nimport typing\nfrom datetime import timedelta\n\nfrom pip._vendor.tenacity import _utils\n\nif typing.TYPE_CHECKING:\n    from pip._vendor.tenacity import RetryCallState\n\nwait_unit_type = typing.Union[int, float, timedelta]\n\n\ndef to_seconds(wait_unit: wait_unit_type) -> float:\n    return float(wait_unit.total_seconds() if isinstance(wait_unit, timedelta) else wait_unit)\n\n\nclass wait_base(abc.ABC):\n    \"\"\"Abstract base class for wait strategies.\"\"\"\n\n    @abc.abstractmethod\n    def __call__(self, retry_state: \"RetryCallState\") -> float:\n        pass\n\n    def __add__(self, other: \"wait_base\") -> \"wait_combine\":\n        return wait_combine(self, other)\n\n    def __radd__(self, other: \"wait_base\") -> typing.Union[\"wait_combine\", \"wait_base\"]:\n        # make it possible to use multiple waits with the built-in sum function\n        if other == 0:\n            return self\n        return self.__add__(other)\n\n\nclass wait_fixed(wait_base):\n    \"\"\"Wait strategy that waits a fixed amount of time between each retry.\"\"\"\n\n    def __init__(self, wait: wait_unit_type) -> None:\n        self.wait_fixed = to_seconds(wait)\n\n    def __call__(self, retry_state: \"RetryCallState\") -> float:\n        return self.wait_fixed\n\n\nclass wait_none(wait_fixed):\n    \"\"\"Wait strategy that doesn't wait at all before retrying.\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__(0)\n\n\nclass wait_random(wait_base):\n    \"\"\"Wait strategy that waits a random amount of time between min/max.\"\"\"\n\n    def __init__(self, min: wait_unit_type = 0, max: wait_unit_type = 1) -> None:  # noqa\n        self.wait_random_min = to_seconds(min)\n        self.wait_random_max = to_seconds(max)\n\n    def __call__(self, retry_state: \"RetryCallState\") -> float:\n        return self.wait_random_min + (random.random() * (self.wait_random_max - self.wait_random_min))\n\n\nclass wait_combine(wait_base):\n    \"\"\"Combine several waiting strategies.\"\"\"\n\n    def __init__(self, *strategies: wait_base) -> None:\n        self.wait_funcs = strategies\n\n    def __call__(self, retry_state: \"RetryCallState\") -> float:\n        return sum(x(retry_state=retry_state) for x in self.wait_funcs)\n\n\nclass wait_chain(wait_base):\n    \"\"\"Chain two or more waiting strategies.\n\n    If all strategies are exhausted, the very last strategy is used\n    thereafter.\n\n    For example::\n\n        @retry(wait=wait_chain(*[wait_fixed(1) for i in range(3)] +\n                               [wait_fixed(2) for j in range(5)] +\n                               [wait_fixed(5) for k in range(4)))\n        def wait_chained():\n            print(\"Wait 1s for 3 attempts, 2s for 5 attempts and 5s\n                   thereafter.\")\n    \"\"\"\n\n    def __init__(self, *strategies: wait_base) -> None:\n        self.strategies = strategies\n\n    def __call__(self, retry_state: \"RetryCallState\") -> float:\n        wait_func_no = min(max(retry_state.attempt_number, 1), len(self.strategies))\n        wait_func = self.strategies[wait_func_no - 1]\n        return wait_func(retry_state=retry_state)\n\n\nclass wait_incrementing(wait_base):\n    \"\"\"Wait an incremental amount of time after each attempt.\n\n    Starting at a starting value and incrementing by a value for each attempt\n    (and restricting the upper limit to some maximum value).\n    \"\"\"\n\n    def __init__(\n        self,\n        start: wait_unit_type = 0,\n        increment: wait_unit_type = 100,\n        max: wait_unit_type = _utils.MAX_WAIT,  # noqa\n    ) -> None:\n        self.start = to_seconds(start)\n        self.increment = to_seconds(increment)\n        self.max = to_seconds(max)\n\n    def __call__(self, retry_state: \"RetryCallState\") -> float:\n        result = self.start + (self.increment * (retry_state.attempt_number - 1))\n        return max(0, min(result, self.max))\n\n\nclass wait_exponential(wait_base):\n    \"\"\"Wait strategy that applies exponential backoff.\n\n    It allows for a customized multiplier and an ability to restrict the\n    upper and lower limits to some maximum and minimum value.\n\n    The intervals are fixed (i.e. there is no jitter), so this strategy is\n    suitable for balancing retries against latency when a required resource is\n    unavailable for an unknown duration, but *not* suitable for resolving\n    contention between multiple processes for a shared resource. Use\n    wait_random_exponential for the latter case.\n    \"\"\"\n\n    def __init__(\n        self,\n        multiplier: typing.Union[int, float] = 1,\n        max: wait_unit_type = _utils.MAX_WAIT,  # noqa\n        exp_base: typing.Union[int, float] = 2,\n        min: wait_unit_type = 0,  # noqa\n    ) -> None:\n        self.multiplier = multiplier\n        self.min = to_seconds(min)\n        self.max = to_seconds(max)\n        self.exp_base = exp_base\n\n    def __call__(self, retry_state: \"RetryCallState\") -> float:\n        try:\n            exp = self.exp_base ** (retry_state.attempt_number - 1)\n            result = self.multiplier * exp\n        except OverflowError:\n            return self.max\n        return max(max(0, self.min), min(result, self.max))\n\n\nclass wait_random_exponential(wait_exponential):\n    \"\"\"Random wait with exponentially widening window.\n\n    An exponential backoff strategy used to mediate contention between multiple\n    uncoordinated processes for a shared resource in distributed systems. This\n    is the sense in which \"exponential backoff\" is meant in e.g. Ethernet\n    networking, and corresponds to the \"Full Jitter\" algorithm described in\n    this blog post:\n\n    https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/\n\n    Each retry occurs at a random time in a geometrically expanding interval.\n    It allows for a custom multiplier and an ability to restrict the upper\n    limit of the random interval to some maximum value.\n\n    Example::\n\n        wait_random_exponential(multiplier=0.5,  # initial window 0.5s\n                                max=60)          # max 60s timeout\n\n    When waiting for an unavailable resource to become available again, as\n    opposed to trying to resolve contention for a shared resource, the\n    wait_exponential strategy (which uses a fixed interval) may be preferable.\n\n    \"\"\"\n\n    def __call__(self, retry_state: \"RetryCallState\") -> float:\n        high = super().__call__(retry_state=retry_state)\n        return random.uniform(0, high)\n\n\nclass wait_exponential_jitter(wait_base):\n    \"\"\"Wait strategy that applies exponential backoff and jitter.\n\n    It allows for a customized initial wait, maximum wait and jitter.\n\n    This implements the strategy described here:\n    https://cloud.google.com/storage/docs/retry-strategy\n\n    The wait time is min(initial * (2**n + random.uniform(0, jitter)), maximum)\n    where n is the retry count.\n    \"\"\"\n\n    def __init__(\n        self,\n        initial: float = 1,\n        max: float = _utils.MAX_WAIT,  # noqa\n        exp_base: float = 2,\n        jitter: float = 1,\n    ) -> None:\n        self.initial = initial\n        self.max = max\n        self.exp_base = exp_base\n        self.jitter = jitter\n\n    def __call__(self, retry_state: \"RetryCallState\") -> float:\n        jitter = random.uniform(0, self.jitter)\n        try:\n            exp = self.exp_base ** (retry_state.attempt_number - 1)\n            result = self.initial * exp + jitter\n        except OverflowError:\n            result = self.max\n        return max(0, min(result, self.max))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tomli/__init__.py",
    "content": "# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\n__all__ = (\"loads\", \"load\", \"TOMLDecodeError\")\n__version__ = \"2.0.1\"  # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT\n\nfrom ._parser import TOMLDecodeError, load, loads\n\n# Pretend this exception was created here.\nTOMLDecodeError.__module__ = __name__\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tomli/_parser.py",
    "content": "# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterable\nimport string\nfrom types import MappingProxyType\nfrom typing import Any, BinaryIO, NamedTuple\n\nfrom ._re import (\n    RE_DATETIME,\n    RE_LOCALTIME,\n    RE_NUMBER,\n    match_to_datetime,\n    match_to_localtime,\n    match_to_number,\n)\nfrom ._types import Key, ParseFloat, Pos\n\nASCII_CTRL = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))\n\n# Neither of these sets include quotation mark or backslash. They are\n# currently handled as separate cases in the parser functions.\nILLEGAL_BASIC_STR_CHARS = ASCII_CTRL - frozenset(\"\\t\")\nILLEGAL_MULTILINE_BASIC_STR_CHARS = ASCII_CTRL - frozenset(\"\\t\\n\")\n\nILLEGAL_LITERAL_STR_CHARS = ILLEGAL_BASIC_STR_CHARS\nILLEGAL_MULTILINE_LITERAL_STR_CHARS = ILLEGAL_MULTILINE_BASIC_STR_CHARS\n\nILLEGAL_COMMENT_CHARS = ILLEGAL_BASIC_STR_CHARS\n\nTOML_WS = frozenset(\" \\t\")\nTOML_WS_AND_NEWLINE = TOML_WS | frozenset(\"\\n\")\nBARE_KEY_CHARS = frozenset(string.ascii_letters + string.digits + \"-_\")\nKEY_INITIAL_CHARS = BARE_KEY_CHARS | frozenset(\"\\\"'\")\nHEXDIGIT_CHARS = frozenset(string.hexdigits)\n\nBASIC_STR_ESCAPE_REPLACEMENTS = MappingProxyType(\n    {\n        \"\\\\b\": \"\\u0008\",  # backspace\n        \"\\\\t\": \"\\u0009\",  # tab\n        \"\\\\n\": \"\\u000A\",  # linefeed\n        \"\\\\f\": \"\\u000C\",  # form feed\n        \"\\\\r\": \"\\u000D\",  # carriage return\n        '\\\\\"': \"\\u0022\",  # quote\n        \"\\\\\\\\\": \"\\u005C\",  # backslash\n    }\n)\n\n\nclass TOMLDecodeError(ValueError):\n    \"\"\"An error raised if a document is not valid TOML.\"\"\"\n\n\ndef load(__fp: BinaryIO, *, parse_float: ParseFloat = float) -> dict[str, Any]:\n    \"\"\"Parse TOML from a binary file object.\"\"\"\n    b = __fp.read()\n    try:\n        s = b.decode()\n    except AttributeError:\n        raise TypeError(\n            \"File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`\"\n        ) from None\n    return loads(s, parse_float=parse_float)\n\n\ndef loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]:  # noqa: C901\n    \"\"\"Parse TOML from a string.\"\"\"\n\n    # The spec allows converting \"\\r\\n\" to \"\\n\", even in string\n    # literals. Let's do so to simplify parsing.\n    src = __s.replace(\"\\r\\n\", \"\\n\")\n    pos = 0\n    out = Output(NestedDict(), Flags())\n    header: Key = ()\n    parse_float = make_safe_parse_float(parse_float)\n\n    # Parse one statement at a time\n    # (typically means one line in TOML source)\n    while True:\n        # 1. Skip line leading whitespace\n        pos = skip_chars(src, pos, TOML_WS)\n\n        # 2. Parse rules. Expect one of the following:\n        #    - end of file\n        #    - end of line\n        #    - comment\n        #    - key/value pair\n        #    - append dict to list (and move to its namespace)\n        #    - create dict (and move to its namespace)\n        # Skip trailing whitespace when applicable.\n        try:\n            char = src[pos]\n        except IndexError:\n            break\n        if char == \"\\n\":\n            pos += 1\n            continue\n        if char in KEY_INITIAL_CHARS:\n            pos = key_value_rule(src, pos, out, header, parse_float)\n            pos = skip_chars(src, pos, TOML_WS)\n        elif char == \"[\":\n            try:\n                second_char: str | None = src[pos + 1]\n            except IndexError:\n                second_char = None\n            out.flags.finalize_pending()\n            if second_char == \"[\":\n                pos, header = create_list_rule(src, pos, out)\n            else:\n                pos, header = create_dict_rule(src, pos, out)\n            pos = skip_chars(src, pos, TOML_WS)\n        elif char != \"#\":\n            raise suffixed_err(src, pos, \"Invalid statement\")\n\n        # 3. Skip comment\n        pos = skip_comment(src, pos)\n\n        # 4. Expect end of line or end of file\n        try:\n            char = src[pos]\n        except IndexError:\n            break\n        if char != \"\\n\":\n            raise suffixed_err(\n                src, pos, \"Expected newline or end of document after a statement\"\n            )\n        pos += 1\n\n    return out.data.dict\n\n\nclass Flags:\n    \"\"\"Flags that map to parsed keys/namespaces.\"\"\"\n\n    # Marks an immutable namespace (inline array or inline table).\n    FROZEN = 0\n    # Marks a nest that has been explicitly created and can no longer\n    # be opened using the \"[table]\" syntax.\n    EXPLICIT_NEST = 1\n\n    def __init__(self) -> None:\n        self._flags: dict[str, dict] = {}\n        self._pending_flags: set[tuple[Key, int]] = set()\n\n    def add_pending(self, key: Key, flag: int) -> None:\n        self._pending_flags.add((key, flag))\n\n    def finalize_pending(self) -> None:\n        for key, flag in self._pending_flags:\n            self.set(key, flag, recursive=False)\n        self._pending_flags.clear()\n\n    def unset_all(self, key: Key) -> None:\n        cont = self._flags\n        for k in key[:-1]:\n            if k not in cont:\n                return\n            cont = cont[k][\"nested\"]\n        cont.pop(key[-1], None)\n\n    def set(self, key: Key, flag: int, *, recursive: bool) -> None:  # noqa: A003\n        cont = self._flags\n        key_parent, key_stem = key[:-1], key[-1]\n        for k in key_parent:\n            if k not in cont:\n                cont[k] = {\"flags\": set(), \"recursive_flags\": set(), \"nested\": {}}\n            cont = cont[k][\"nested\"]\n        if key_stem not in cont:\n            cont[key_stem] = {\"flags\": set(), \"recursive_flags\": set(), \"nested\": {}}\n        cont[key_stem][\"recursive_flags\" if recursive else \"flags\"].add(flag)\n\n    def is_(self, key: Key, flag: int) -> bool:\n        if not key:\n            return False  # document root has no flags\n        cont = self._flags\n        for k in key[:-1]:\n            if k not in cont:\n                return False\n            inner_cont = cont[k]\n            if flag in inner_cont[\"recursive_flags\"]:\n                return True\n            cont = inner_cont[\"nested\"]\n        key_stem = key[-1]\n        if key_stem in cont:\n            cont = cont[key_stem]\n            return flag in cont[\"flags\"] or flag in cont[\"recursive_flags\"]\n        return False\n\n\nclass NestedDict:\n    def __init__(self) -> None:\n        # The parsed content of the TOML document\n        self.dict: dict[str, Any] = {}\n\n    def get_or_create_nest(\n        self,\n        key: Key,\n        *,\n        access_lists: bool = True,\n    ) -> dict:\n        cont: Any = self.dict\n        for k in key:\n            if k not in cont:\n                cont[k] = {}\n            cont = cont[k]\n            if access_lists and isinstance(cont, list):\n                cont = cont[-1]\n            if not isinstance(cont, dict):\n                raise KeyError(\"There is no nest behind this key\")\n        return cont\n\n    def append_nest_to_list(self, key: Key) -> None:\n        cont = self.get_or_create_nest(key[:-1])\n        last_key = key[-1]\n        if last_key in cont:\n            list_ = cont[last_key]\n            if not isinstance(list_, list):\n                raise KeyError(\"An object other than list found behind this key\")\n            list_.append({})\n        else:\n            cont[last_key] = [{}]\n\n\nclass Output(NamedTuple):\n    data: NestedDict\n    flags: Flags\n\n\ndef skip_chars(src: str, pos: Pos, chars: Iterable[str]) -> Pos:\n    try:\n        while src[pos] in chars:\n            pos += 1\n    except IndexError:\n        pass\n    return pos\n\n\ndef skip_until(\n    src: str,\n    pos: Pos,\n    expect: str,\n    *,\n    error_on: frozenset[str],\n    error_on_eof: bool,\n) -> Pos:\n    try:\n        new_pos = src.index(expect, pos)\n    except ValueError:\n        new_pos = len(src)\n        if error_on_eof:\n            raise suffixed_err(src, new_pos, f\"Expected {expect!r}\") from None\n\n    if not error_on.isdisjoint(src[pos:new_pos]):\n        while src[pos] not in error_on:\n            pos += 1\n        raise suffixed_err(src, pos, f\"Found invalid character {src[pos]!r}\")\n    return new_pos\n\n\ndef skip_comment(src: str, pos: Pos) -> Pos:\n    try:\n        char: str | None = src[pos]\n    except IndexError:\n        char = None\n    if char == \"#\":\n        return skip_until(\n            src, pos + 1, \"\\n\", error_on=ILLEGAL_COMMENT_CHARS, error_on_eof=False\n        )\n    return pos\n\n\ndef skip_comments_and_array_ws(src: str, pos: Pos) -> Pos:\n    while True:\n        pos_before_skip = pos\n        pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)\n        pos = skip_comment(src, pos)\n        if pos == pos_before_skip:\n            return pos\n\n\ndef create_dict_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:\n    pos += 1  # Skip \"[\"\n    pos = skip_chars(src, pos, TOML_WS)\n    pos, key = parse_key(src, pos)\n\n    if out.flags.is_(key, Flags.EXPLICIT_NEST) or out.flags.is_(key, Flags.FROZEN):\n        raise suffixed_err(src, pos, f\"Cannot declare {key} twice\")\n    out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)\n    try:\n        out.data.get_or_create_nest(key)\n    except KeyError:\n        raise suffixed_err(src, pos, \"Cannot overwrite a value\") from None\n\n    if not src.startswith(\"]\", pos):\n        raise suffixed_err(src, pos, \"Expected ']' at the end of a table declaration\")\n    return pos + 1, key\n\n\ndef create_list_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:\n    pos += 2  # Skip \"[[\"\n    pos = skip_chars(src, pos, TOML_WS)\n    pos, key = parse_key(src, pos)\n\n    if out.flags.is_(key, Flags.FROZEN):\n        raise suffixed_err(src, pos, f\"Cannot mutate immutable namespace {key}\")\n    # Free the namespace now that it points to another empty list item...\n    out.flags.unset_all(key)\n    # ...but this key precisely is still prohibited from table declaration\n    out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)\n    try:\n        out.data.append_nest_to_list(key)\n    except KeyError:\n        raise suffixed_err(src, pos, \"Cannot overwrite a value\") from None\n\n    if not src.startswith(\"]]\", pos):\n        raise suffixed_err(src, pos, \"Expected ']]' at the end of an array declaration\")\n    return pos + 2, key\n\n\ndef key_value_rule(\n    src: str, pos: Pos, out: Output, header: Key, parse_float: ParseFloat\n) -> Pos:\n    pos, key, value = parse_key_value_pair(src, pos, parse_float)\n    key_parent, key_stem = key[:-1], key[-1]\n    abs_key_parent = header + key_parent\n\n    relative_path_cont_keys = (header + key[:i] for i in range(1, len(key)))\n    for cont_key in relative_path_cont_keys:\n        # Check that dotted key syntax does not redefine an existing table\n        if out.flags.is_(cont_key, Flags.EXPLICIT_NEST):\n            raise suffixed_err(src, pos, f\"Cannot redefine namespace {cont_key}\")\n        # Containers in the relative path can't be opened with the table syntax or\n        # dotted key/value syntax in following table sections.\n        out.flags.add_pending(cont_key, Flags.EXPLICIT_NEST)\n\n    if out.flags.is_(abs_key_parent, Flags.FROZEN):\n        raise suffixed_err(\n            src, pos, f\"Cannot mutate immutable namespace {abs_key_parent}\"\n        )\n\n    try:\n        nest = out.data.get_or_create_nest(abs_key_parent)\n    except KeyError:\n        raise suffixed_err(src, pos, \"Cannot overwrite a value\") from None\n    if key_stem in nest:\n        raise suffixed_err(src, pos, \"Cannot overwrite a value\")\n    # Mark inline table and array namespaces recursively immutable\n    if isinstance(value, (dict, list)):\n        out.flags.set(header + key, Flags.FROZEN, recursive=True)\n    nest[key_stem] = value\n    return pos\n\n\ndef parse_key_value_pair(\n    src: str, pos: Pos, parse_float: ParseFloat\n) -> tuple[Pos, Key, Any]:\n    pos, key = parse_key(src, pos)\n    try:\n        char: str | None = src[pos]\n    except IndexError:\n        char = None\n    if char != \"=\":\n        raise suffixed_err(src, pos, \"Expected '=' after a key in a key/value pair\")\n    pos += 1\n    pos = skip_chars(src, pos, TOML_WS)\n    pos, value = parse_value(src, pos, parse_float)\n    return pos, key, value\n\n\ndef parse_key(src: str, pos: Pos) -> tuple[Pos, Key]:\n    pos, key_part = parse_key_part(src, pos)\n    key: Key = (key_part,)\n    pos = skip_chars(src, pos, TOML_WS)\n    while True:\n        try:\n            char: str | None = src[pos]\n        except IndexError:\n            char = None\n        if char != \".\":\n            return pos, key\n        pos += 1\n        pos = skip_chars(src, pos, TOML_WS)\n        pos, key_part = parse_key_part(src, pos)\n        key += (key_part,)\n        pos = skip_chars(src, pos, TOML_WS)\n\n\ndef parse_key_part(src: str, pos: Pos) -> tuple[Pos, str]:\n    try:\n        char: str | None = src[pos]\n    except IndexError:\n        char = None\n    if char in BARE_KEY_CHARS:\n        start_pos = pos\n        pos = skip_chars(src, pos, BARE_KEY_CHARS)\n        return pos, src[start_pos:pos]\n    if char == \"'\":\n        return parse_literal_str(src, pos)\n    if char == '\"':\n        return parse_one_line_basic_str(src, pos)\n    raise suffixed_err(src, pos, \"Invalid initial character for a key part\")\n\n\ndef parse_one_line_basic_str(src: str, pos: Pos) -> tuple[Pos, str]:\n    pos += 1\n    return parse_basic_str(src, pos, multiline=False)\n\n\ndef parse_array(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos, list]:\n    pos += 1\n    array: list = []\n\n    pos = skip_comments_and_array_ws(src, pos)\n    if src.startswith(\"]\", pos):\n        return pos + 1, array\n    while True:\n        pos, val = parse_value(src, pos, parse_float)\n        array.append(val)\n        pos = skip_comments_and_array_ws(src, pos)\n\n        c = src[pos : pos + 1]\n        if c == \"]\":\n            return pos + 1, array\n        if c != \",\":\n            raise suffixed_err(src, pos, \"Unclosed array\")\n        pos += 1\n\n        pos = skip_comments_and_array_ws(src, pos)\n        if src.startswith(\"]\", pos):\n            return pos + 1, array\n\n\ndef parse_inline_table(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos, dict]:\n    pos += 1\n    nested_dict = NestedDict()\n    flags = Flags()\n\n    pos = skip_chars(src, pos, TOML_WS)\n    if src.startswith(\"}\", pos):\n        return pos + 1, nested_dict.dict\n    while True:\n        pos, key, value = parse_key_value_pair(src, pos, parse_float)\n        key_parent, key_stem = key[:-1], key[-1]\n        if flags.is_(key, Flags.FROZEN):\n            raise suffixed_err(src, pos, f\"Cannot mutate immutable namespace {key}\")\n        try:\n            nest = nested_dict.get_or_create_nest(key_parent, access_lists=False)\n        except KeyError:\n            raise suffixed_err(src, pos, \"Cannot overwrite a value\") from None\n        if key_stem in nest:\n            raise suffixed_err(src, pos, f\"Duplicate inline table key {key_stem!r}\")\n        nest[key_stem] = value\n        pos = skip_chars(src, pos, TOML_WS)\n        c = src[pos : pos + 1]\n        if c == \"}\":\n            return pos + 1, nested_dict.dict\n        if c != \",\":\n            raise suffixed_err(src, pos, \"Unclosed inline table\")\n        if isinstance(value, (dict, list)):\n            flags.set(key, Flags.FROZEN, recursive=True)\n        pos += 1\n        pos = skip_chars(src, pos, TOML_WS)\n\n\ndef parse_basic_str_escape(\n    src: str, pos: Pos, *, multiline: bool = False\n) -> tuple[Pos, str]:\n    escape_id = src[pos : pos + 2]\n    pos += 2\n    if multiline and escape_id in {\"\\\\ \", \"\\\\\\t\", \"\\\\\\n\"}:\n        # Skip whitespace until next non-whitespace character or end of\n        # the doc. Error if non-whitespace is found before newline.\n        if escape_id != \"\\\\\\n\":\n            pos = skip_chars(src, pos, TOML_WS)\n            try:\n                char = src[pos]\n            except IndexError:\n                return pos, \"\"\n            if char != \"\\n\":\n                raise suffixed_err(src, pos, \"Unescaped '\\\\' in a string\")\n            pos += 1\n        pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)\n        return pos, \"\"\n    if escape_id == \"\\\\u\":\n        return parse_hex_char(src, pos, 4)\n    if escape_id == \"\\\\U\":\n        return parse_hex_char(src, pos, 8)\n    try:\n        return pos, BASIC_STR_ESCAPE_REPLACEMENTS[escape_id]\n    except KeyError:\n        raise suffixed_err(src, pos, \"Unescaped '\\\\' in a string\") from None\n\n\ndef parse_basic_str_escape_multiline(src: str, pos: Pos) -> tuple[Pos, str]:\n    return parse_basic_str_escape(src, pos, multiline=True)\n\n\ndef parse_hex_char(src: str, pos: Pos, hex_len: int) -> tuple[Pos, str]:\n    hex_str = src[pos : pos + hex_len]\n    if len(hex_str) != hex_len or not HEXDIGIT_CHARS.issuperset(hex_str):\n        raise suffixed_err(src, pos, \"Invalid hex value\")\n    pos += hex_len\n    hex_int = int(hex_str, 16)\n    if not is_unicode_scalar_value(hex_int):\n        raise suffixed_err(src, pos, \"Escaped character is not a Unicode scalar value\")\n    return pos, chr(hex_int)\n\n\ndef parse_literal_str(src: str, pos: Pos) -> tuple[Pos, str]:\n    pos += 1  # Skip starting apostrophe\n    start_pos = pos\n    pos = skip_until(\n        src, pos, \"'\", error_on=ILLEGAL_LITERAL_STR_CHARS, error_on_eof=True\n    )\n    return pos + 1, src[start_pos:pos]  # Skip ending apostrophe\n\n\ndef parse_multiline_str(src: str, pos: Pos, *, literal: bool) -> tuple[Pos, str]:\n    pos += 3\n    if src.startswith(\"\\n\", pos):\n        pos += 1\n\n    if literal:\n        delim = \"'\"\n        end_pos = skip_until(\n            src,\n            pos,\n            \"'''\",\n            error_on=ILLEGAL_MULTILINE_LITERAL_STR_CHARS,\n            error_on_eof=True,\n        )\n        result = src[pos:end_pos]\n        pos = end_pos + 3\n    else:\n        delim = '\"'\n        pos, result = parse_basic_str(src, pos, multiline=True)\n\n    # Add at maximum two extra apostrophes/quotes if the end sequence\n    # is 4 or 5 chars long instead of just 3.\n    if not src.startswith(delim, pos):\n        return pos, result\n    pos += 1\n    if not src.startswith(delim, pos):\n        return pos, result + delim\n    pos += 1\n    return pos, result + (delim * 2)\n\n\ndef parse_basic_str(src: str, pos: Pos, *, multiline: bool) -> tuple[Pos, str]:\n    if multiline:\n        error_on = ILLEGAL_MULTILINE_BASIC_STR_CHARS\n        parse_escapes = parse_basic_str_escape_multiline\n    else:\n        error_on = ILLEGAL_BASIC_STR_CHARS\n        parse_escapes = parse_basic_str_escape\n    result = \"\"\n    start_pos = pos\n    while True:\n        try:\n            char = src[pos]\n        except IndexError:\n            raise suffixed_err(src, pos, \"Unterminated string\") from None\n        if char == '\"':\n            if not multiline:\n                return pos + 1, result + src[start_pos:pos]\n            if src.startswith('\"\"\"', pos):\n                return pos + 3, result + src[start_pos:pos]\n            pos += 1\n            continue\n        if char == \"\\\\\":\n            result += src[start_pos:pos]\n            pos, parsed_escape = parse_escapes(src, pos)\n            result += parsed_escape\n            start_pos = pos\n            continue\n        if char in error_on:\n            raise suffixed_err(src, pos, f\"Illegal character {char!r}\")\n        pos += 1\n\n\ndef parse_value(  # noqa: C901\n    src: str, pos: Pos, parse_float: ParseFloat\n) -> tuple[Pos, Any]:\n    try:\n        char: str | None = src[pos]\n    except IndexError:\n        char = None\n\n    # IMPORTANT: order conditions based on speed of checking and likelihood\n\n    # Basic strings\n    if char == '\"':\n        if src.startswith('\"\"\"', pos):\n            return parse_multiline_str(src, pos, literal=False)\n        return parse_one_line_basic_str(src, pos)\n\n    # Literal strings\n    if char == \"'\":\n        if src.startswith(\"'''\", pos):\n            return parse_multiline_str(src, pos, literal=True)\n        return parse_literal_str(src, pos)\n\n    # Booleans\n    if char == \"t\":\n        if src.startswith(\"true\", pos):\n            return pos + 4, True\n    if char == \"f\":\n        if src.startswith(\"false\", pos):\n            return pos + 5, False\n\n    # Arrays\n    if char == \"[\":\n        return parse_array(src, pos, parse_float)\n\n    # Inline tables\n    if char == \"{\":\n        return parse_inline_table(src, pos, parse_float)\n\n    # Dates and times\n    datetime_match = RE_DATETIME.match(src, pos)\n    if datetime_match:\n        try:\n            datetime_obj = match_to_datetime(datetime_match)\n        except ValueError as e:\n            raise suffixed_err(src, pos, \"Invalid date or datetime\") from e\n        return datetime_match.end(), datetime_obj\n    localtime_match = RE_LOCALTIME.match(src, pos)\n    if localtime_match:\n        return localtime_match.end(), match_to_localtime(localtime_match)\n\n    # Integers and \"normal\" floats.\n    # The regex will greedily match any type starting with a decimal\n    # char, so needs to be located after handling of dates and times.\n    number_match = RE_NUMBER.match(src, pos)\n    if number_match:\n        return number_match.end(), match_to_number(number_match, parse_float)\n\n    # Special floats\n    first_three = src[pos : pos + 3]\n    if first_three in {\"inf\", \"nan\"}:\n        return pos + 3, parse_float(first_three)\n    first_four = src[pos : pos + 4]\n    if first_four in {\"-inf\", \"+inf\", \"-nan\", \"+nan\"}:\n        return pos + 4, parse_float(first_four)\n\n    raise suffixed_err(src, pos, \"Invalid value\")\n\n\ndef suffixed_err(src: str, pos: Pos, msg: str) -> TOMLDecodeError:\n    \"\"\"Return a `TOMLDecodeError` where error message is suffixed with\n    coordinates in source.\"\"\"\n\n    def coord_repr(src: str, pos: Pos) -> str:\n        if pos >= len(src):\n            return \"end of document\"\n        line = src.count(\"\\n\", 0, pos) + 1\n        if line == 1:\n            column = pos + 1\n        else:\n            column = pos - src.rindex(\"\\n\", 0, pos)\n        return f\"line {line}, column {column}\"\n\n    return TOMLDecodeError(f\"{msg} (at {coord_repr(src, pos)})\")\n\n\ndef is_unicode_scalar_value(codepoint: int) -> bool:\n    return (0 <= codepoint <= 55295) or (57344 <= codepoint <= 1114111)\n\n\ndef make_safe_parse_float(parse_float: ParseFloat) -> ParseFloat:\n    \"\"\"A decorator to make `parse_float` safe.\n\n    `parse_float` must not return dicts or lists, because these types\n    would be mixed with parsed TOML tables and arrays, thus confusing\n    the parser. The returned decorated callable raises `ValueError`\n    instead of returning illegal types.\n    \"\"\"\n    # The default `float` callable never returns illegal types. Optimize it.\n    if parse_float is float:  # type: ignore[comparison-overlap]\n        return float\n\n    def safe_parse_float(float_str: str) -> Any:\n        float_value = parse_float(float_str)\n        if isinstance(float_value, (dict, list)):\n            raise ValueError(\"parse_float must not return dicts or lists\")\n        return float_value\n\n    return safe_parse_float\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tomli/_re.py",
    "content": "# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\nfrom __future__ import annotations\n\nfrom datetime import date, datetime, time, timedelta, timezone, tzinfo\nfrom functools import lru_cache\nimport re\nfrom typing import Any\n\nfrom ._types import ParseFloat\n\n# E.g.\n# - 00:32:00.999999\n# - 00:32:00\n_TIME_RE_STR = r\"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\\.([0-9]{1,6})[0-9]*)?\"\n\nRE_NUMBER = re.compile(\n    r\"\"\"\n0\n(?:\n    x[0-9A-Fa-f](?:_?[0-9A-Fa-f])*   # hex\n    |\n    b[01](?:_?[01])*                 # bin\n    |\n    o[0-7](?:_?[0-7])*               # oct\n)\n|\n[+-]?(?:0|[1-9](?:_?[0-9])*)         # dec, integer part\n(?P<floatpart>\n    (?:\\.[0-9](?:_?[0-9])*)?         # optional fractional part\n    (?:[eE][+-]?[0-9](?:_?[0-9])*)?  # optional exponent part\n)\n\"\"\",\n    flags=re.VERBOSE,\n)\nRE_LOCALTIME = re.compile(_TIME_RE_STR)\nRE_DATETIME = re.compile(\n    rf\"\"\"\n([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])  # date, e.g. 1988-10-27\n(?:\n    [Tt ]\n    {_TIME_RE_STR}\n    (?:([Zz])|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))?  # optional time offset\n)?\n\"\"\",\n    flags=re.VERBOSE,\n)\n\n\ndef match_to_datetime(match: re.Match) -> datetime | date:\n    \"\"\"Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.\n\n    Raises ValueError if the match does not correspond to a valid date\n    or datetime.\n    \"\"\"\n    (\n        year_str,\n        month_str,\n        day_str,\n        hour_str,\n        minute_str,\n        sec_str,\n        micros_str,\n        zulu_time,\n        offset_sign_str,\n        offset_hour_str,\n        offset_minute_str,\n    ) = match.groups()\n    year, month, day = int(year_str), int(month_str), int(day_str)\n    if hour_str is None:\n        return date(year, month, day)\n    hour, minute, sec = int(hour_str), int(minute_str), int(sec_str)\n    micros = int(micros_str.ljust(6, \"0\")) if micros_str else 0\n    if offset_sign_str:\n        tz: tzinfo | None = cached_tz(\n            offset_hour_str, offset_minute_str, offset_sign_str\n        )\n    elif zulu_time:\n        tz = timezone.utc\n    else:  # local date-time\n        tz = None\n    return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz)\n\n\n@lru_cache(maxsize=None)\ndef cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone:\n    sign = 1 if sign_str == \"+\" else -1\n    return timezone(\n        timedelta(\n            hours=sign * int(hour_str),\n            minutes=sign * int(minute_str),\n        )\n    )\n\n\ndef match_to_localtime(match: re.Match) -> time:\n    hour_str, minute_str, sec_str, micros_str = match.groups()\n    micros = int(micros_str.ljust(6, \"0\")) if micros_str else 0\n    return time(int(hour_str), int(minute_str), int(sec_str), micros)\n\n\ndef match_to_number(match: re.Match, parse_float: ParseFloat) -> Any:\n    if match.group(\"floatpart\"):\n        return parse_float(match.group())\n    return int(match.group(), 0)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/tomli/_types.py",
    "content": "# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\nfrom typing import Any, Callable, Tuple\n\n# Type annotations\nParseFloat = Callable[[str], Any]\nKey = Tuple[str, ...]\nPos = int\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/typing_extensions.py",
    "content": "import abc\nimport collections\nimport collections.abc\nimport functools\nimport operator\nimport sys\nimport types as _types\nimport typing\n\n\n__all__ = [\n    # Super-special typing primitives.\n    'Any',\n    'ClassVar',\n    'Concatenate',\n    'Final',\n    'LiteralString',\n    'ParamSpec',\n    'ParamSpecArgs',\n    'ParamSpecKwargs',\n    'Self',\n    'Type',\n    'TypeVar',\n    'TypeVarTuple',\n    'Unpack',\n\n    # ABCs (from collections.abc).\n    'Awaitable',\n    'AsyncIterator',\n    'AsyncIterable',\n    'Coroutine',\n    'AsyncGenerator',\n    'AsyncContextManager',\n    'ChainMap',\n\n    # Concrete collection types.\n    'ContextManager',\n    'Counter',\n    'Deque',\n    'DefaultDict',\n    'NamedTuple',\n    'OrderedDict',\n    'TypedDict',\n\n    # Structural checks, a.k.a. protocols.\n    'SupportsIndex',\n\n    # One-off things.\n    'Annotated',\n    'assert_never',\n    'assert_type',\n    'clear_overloads',\n    'dataclass_transform',\n    'get_overloads',\n    'final',\n    'get_args',\n    'get_origin',\n    'get_type_hints',\n    'IntVar',\n    'is_typeddict',\n    'Literal',\n    'NewType',\n    'overload',\n    'override',\n    'Protocol',\n    'reveal_type',\n    'runtime',\n    'runtime_checkable',\n    'Text',\n    'TypeAlias',\n    'TypeGuard',\n    'TYPE_CHECKING',\n    'Never',\n    'NoReturn',\n    'Required',\n    'NotRequired',\n]\n\n# for backward compatibility\nPEP_560 = True\nGenericMeta = type\n\n# The functions below are modified copies of typing internal helpers.\n# They are needed by _ProtocolMeta and they provide support for PEP 646.\n\n_marker = object()\n\n\ndef _check_generic(cls, parameters, elen=_marker):\n    \"\"\"Check correct count for parameters of a generic cls (internal helper).\n    This gives a nice error message in case of count mismatch.\n    \"\"\"\n    if not elen:\n        raise TypeError(f\"{cls} is not a generic class\")\n    if elen is _marker:\n        if not hasattr(cls, \"__parameters__\") or not cls.__parameters__:\n            raise TypeError(f\"{cls} is not a generic class\")\n        elen = len(cls.__parameters__)\n    alen = len(parameters)\n    if alen != elen:\n        if hasattr(cls, \"__parameters__\"):\n            parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]\n            num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters)\n            if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples):\n                return\n        raise TypeError(f\"Too {'many' if alen > elen else 'few'} parameters for {cls};\"\n                        f\" actual {alen}, expected {elen}\")\n\n\nif sys.version_info >= (3, 10):\n    def _should_collect_from_parameters(t):\n        return isinstance(\n            t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)\n        )\nelif sys.version_info >= (3, 9):\n    def _should_collect_from_parameters(t):\n        return isinstance(t, (typing._GenericAlias, _types.GenericAlias))\nelse:\n    def _should_collect_from_parameters(t):\n        return isinstance(t, typing._GenericAlias) and not t._special\n\n\ndef _collect_type_vars(types, typevar_types=None):\n    \"\"\"Collect all type variable contained in types in order of\n    first appearance (lexicographic order). For example::\n\n        _collect_type_vars((T, List[S, T])) == (T, S)\n    \"\"\"\n    if typevar_types is None:\n        typevar_types = typing.TypeVar\n    tvars = []\n    for t in types:\n        if (\n            isinstance(t, typevar_types) and\n            t not in tvars and\n            not _is_unpack(t)\n        ):\n            tvars.append(t)\n        if _should_collect_from_parameters(t):\n            tvars.extend([t for t in t.__parameters__ if t not in tvars])\n    return tuple(tvars)\n\n\nNoReturn = typing.NoReturn\n\n# Some unconstrained type variables.  These are used by the container types.\n# (These are not for export.)\nT = typing.TypeVar('T')  # Any type.\nKT = typing.TypeVar('KT')  # Key type.\nVT = typing.TypeVar('VT')  # Value type.\nT_co = typing.TypeVar('T_co', covariant=True)  # Any type covariant containers.\nT_contra = typing.TypeVar('T_contra', contravariant=True)  # Ditto contravariant.\n\n\nif sys.version_info >= (3, 11):\n    from typing import Any\nelse:\n\n    class _AnyMeta(type):\n        def __instancecheck__(self, obj):\n            if self is Any:\n                raise TypeError(\"typing_extensions.Any cannot be used with isinstance()\")\n            return super().__instancecheck__(obj)\n\n        def __repr__(self):\n            if self is Any:\n                return \"typing_extensions.Any\"\n            return super().__repr__()\n\n    class Any(metaclass=_AnyMeta):\n        \"\"\"Special type indicating an unconstrained type.\n        - Any is compatible with every type.\n        - Any assumed to have all methods.\n        - All values assumed to be instances of Any.\n        Note that all the above statements are true from the point of view of\n        static type checkers. At runtime, Any should not be used with instance\n        checks.\n        \"\"\"\n        def __new__(cls, *args, **kwargs):\n            if cls is Any:\n                raise TypeError(\"Any cannot be instantiated\")\n            return super().__new__(cls, *args, **kwargs)\n\n\nClassVar = typing.ClassVar\n\n# On older versions of typing there is an internal class named \"Final\".\n# 3.8+\nif hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):\n    Final = typing.Final\n# 3.7\nelse:\n    class _FinalForm(typing._SpecialForm, _root=True):\n\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n        def __getitem__(self, parameters):\n            item = typing._type_check(parameters,\n                                      f'{self._name} accepts only a single type.')\n            return typing._GenericAlias(self, (item,))\n\n    Final = _FinalForm('Final',\n                       doc=\"\"\"A special typing construct to indicate that a name\n                       cannot be re-assigned or overridden in a subclass.\n                       For example:\n\n                           MAX_SIZE: Final = 9000\n                           MAX_SIZE += 1  # Error reported by type checker\n\n                           class Connection:\n                               TIMEOUT: Final[int] = 10\n                           class FastConnector(Connection):\n                               TIMEOUT = 1  # Error reported by type checker\n\n                       There is no runtime checking of these properties.\"\"\")\n\nif sys.version_info >= (3, 11):\n    final = typing.final\nelse:\n    # @final exists in 3.8+, but we backport it for all versions\n    # before 3.11 to keep support for the __final__ attribute.\n    # See https://bugs.python.org/issue46342\n    def final(f):\n        \"\"\"This decorator can be used to indicate to type checkers that\n        the decorated method cannot be overridden, and decorated class\n        cannot be subclassed. For example:\n\n            class Base:\n                @final\n                def done(self) -> None:\n                    ...\n            class Sub(Base):\n                def done(self) -> None:  # Error reported by type checker\n                    ...\n            @final\n            class Leaf:\n                ...\n            class Other(Leaf):  # Error reported by type checker\n                ...\n\n        There is no runtime checking of these properties. The decorator\n        sets the ``__final__`` attribute to ``True`` on the decorated object\n        to allow runtime introspection.\n        \"\"\"\n        try:\n            f.__final__ = True\n        except (AttributeError, TypeError):\n            # Skip the attribute silently if it is not writable.\n            # AttributeError happens if the object has __slots__ or a\n            # read-only property, TypeError if it's a builtin class.\n            pass\n        return f\n\n\ndef IntVar(name):\n    return typing.TypeVar(name)\n\n\n# 3.8+:\nif hasattr(typing, 'Literal'):\n    Literal = typing.Literal\n# 3.7:\nelse:\n    class _LiteralForm(typing._SpecialForm, _root=True):\n\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n        def __getitem__(self, parameters):\n            return typing._GenericAlias(self, parameters)\n\n    Literal = _LiteralForm('Literal',\n                           doc=\"\"\"A type that can be used to indicate to type checkers\n                           that the corresponding value has a value literally equivalent\n                           to the provided parameter. For example:\n\n                               var: Literal[4] = 4\n\n                           The type checker understands that 'var' is literally equal to\n                           the value 4 and no other value.\n\n                           Literal[...] cannot be subclassed. There is no runtime\n                           checking verifying that the parameter is actually a value\n                           instead of a type.\"\"\")\n\n\n_overload_dummy = typing._overload_dummy  # noqa\n\n\nif hasattr(typing, \"get_overloads\"):  # 3.11+\n    overload = typing.overload\n    get_overloads = typing.get_overloads\n    clear_overloads = typing.clear_overloads\nelse:\n    # {module: {qualname: {firstlineno: func}}}\n    _overload_registry = collections.defaultdict(\n        functools.partial(collections.defaultdict, dict)\n    )\n\n    def overload(func):\n        \"\"\"Decorator for overloaded functions/methods.\n\n        In a stub file, place two or more stub definitions for the same\n        function in a row, each decorated with @overload.  For example:\n\n        @overload\n        def utf8(value: None) -> None: ...\n        @overload\n        def utf8(value: bytes) -> bytes: ...\n        @overload\n        def utf8(value: str) -> bytes: ...\n\n        In a non-stub file (i.e. a regular .py file), do the same but\n        follow it with an implementation.  The implementation should *not*\n        be decorated with @overload.  For example:\n\n        @overload\n        def utf8(value: None) -> None: ...\n        @overload\n        def utf8(value: bytes) -> bytes: ...\n        @overload\n        def utf8(value: str) -> bytes: ...\n        def utf8(value):\n            # implementation goes here\n\n        The overloads for a function can be retrieved at runtime using the\n        get_overloads() function.\n        \"\"\"\n        # classmethod and staticmethod\n        f = getattr(func, \"__func__\", func)\n        try:\n            _overload_registry[f.__module__][f.__qualname__][\n                f.__code__.co_firstlineno\n            ] = func\n        except AttributeError:\n            # Not a normal function; ignore.\n            pass\n        return _overload_dummy\n\n    def get_overloads(func):\n        \"\"\"Return all defined overloads for *func* as a sequence.\"\"\"\n        # classmethod and staticmethod\n        f = getattr(func, \"__func__\", func)\n        if f.__module__ not in _overload_registry:\n            return []\n        mod_dict = _overload_registry[f.__module__]\n        if f.__qualname__ not in mod_dict:\n            return []\n        return list(mod_dict[f.__qualname__].values())\n\n    def clear_overloads():\n        \"\"\"Clear all overloads in the registry.\"\"\"\n        _overload_registry.clear()\n\n\n# This is not a real generic class.  Don't use outside annotations.\nType = typing.Type\n\n# Various ABCs mimicking those in collections.abc.\n# A few are simply re-exported for completeness.\n\n\nAwaitable = typing.Awaitable\nCoroutine = typing.Coroutine\nAsyncIterable = typing.AsyncIterable\nAsyncIterator = typing.AsyncIterator\nDeque = typing.Deque\nContextManager = typing.ContextManager\nAsyncContextManager = typing.AsyncContextManager\nDefaultDict = typing.DefaultDict\n\n# 3.7.2+\nif hasattr(typing, 'OrderedDict'):\n    OrderedDict = typing.OrderedDict\n# 3.7.0-3.7.2\nelse:\n    OrderedDict = typing._alias(collections.OrderedDict, (KT, VT))\n\nCounter = typing.Counter\nChainMap = typing.ChainMap\nAsyncGenerator = typing.AsyncGenerator\nNewType = typing.NewType\nText = typing.Text\nTYPE_CHECKING = typing.TYPE_CHECKING\n\n\n_PROTO_WHITELIST = ['Callable', 'Awaitable',\n                    'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',\n                    'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',\n                    'ContextManager', 'AsyncContextManager']\n\n\ndef _get_protocol_attrs(cls):\n    attrs = set()\n    for base in cls.__mro__[:-1]:  # without object\n        if base.__name__ in ('Protocol', 'Generic'):\n            continue\n        annotations = getattr(base, '__annotations__', {})\n        for attr in list(base.__dict__.keys()) + list(annotations.keys()):\n            if (not attr.startswith('_abc_') and attr not in (\n                    '__abstractmethods__', '__annotations__', '__weakref__',\n                    '_is_protocol', '_is_runtime_protocol', '__dict__',\n                    '__args__', '__slots__',\n                    '__next_in_mro__', '__parameters__', '__origin__',\n                    '__orig_bases__', '__extra__', '__tree_hash__',\n                    '__doc__', '__subclasshook__', '__init__', '__new__',\n                    '__module__', '_MutableMapping__marker', '_gorg')):\n                attrs.add(attr)\n    return attrs\n\n\ndef _is_callable_members_only(cls):\n    return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))\n\n\ndef _maybe_adjust_parameters(cls):\n    \"\"\"Helper function used in Protocol.__init_subclass__ and _TypedDictMeta.__new__.\n\n    The contents of this function are very similar\n    to logic found in typing.Generic.__init_subclass__\n    on the CPython main branch.\n    \"\"\"\n    tvars = []\n    if '__orig_bases__' in cls.__dict__:\n        tvars = typing._collect_type_vars(cls.__orig_bases__)\n        # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].\n        # If found, tvars must be a subset of it.\n        # If not found, tvars is it.\n        # Also check for and reject plain Generic,\n        # and reject multiple Generic[...] and/or Protocol[...].\n        gvars = None\n        for base in cls.__orig_bases__:\n            if (isinstance(base, typing._GenericAlias) and\n                    base.__origin__ in (typing.Generic, Protocol)):\n                # for error messages\n                the_base = base.__origin__.__name__\n                if gvars is not None:\n                    raise TypeError(\n                        \"Cannot inherit from Generic[...]\"\n                        \" and/or Protocol[...] multiple types.\")\n                gvars = base.__parameters__\n        if gvars is None:\n            gvars = tvars\n        else:\n            tvarset = set(tvars)\n            gvarset = set(gvars)\n            if not tvarset <= gvarset:\n                s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)\n                s_args = ', '.join(str(g) for g in gvars)\n                raise TypeError(f\"Some type variables ({s_vars}) are\"\n                                f\" not listed in {the_base}[{s_args}]\")\n            tvars = gvars\n    cls.__parameters__ = tuple(tvars)\n\n\n# 3.8+\nif hasattr(typing, 'Protocol'):\n    Protocol = typing.Protocol\n# 3.7\nelse:\n\n    def _no_init(self, *args, **kwargs):\n        if type(self)._is_protocol:\n            raise TypeError('Protocols cannot be instantiated')\n\n    class _ProtocolMeta(abc.ABCMeta):  # noqa: B024\n        # This metaclass is a bit unfortunate and exists only because of the lack\n        # of __instancehook__.\n        def __instancecheck__(cls, instance):\n            # We need this method for situations where attributes are\n            # assigned in __init__.\n            if ((not getattr(cls, '_is_protocol', False) or\n                 _is_callable_members_only(cls)) and\n                    issubclass(instance.__class__, cls)):\n                return True\n            if cls._is_protocol:\n                if all(hasattr(instance, attr) and\n                       (not callable(getattr(cls, attr, None)) or\n                        getattr(instance, attr) is not None)\n                       for attr in _get_protocol_attrs(cls)):\n                    return True\n            return super().__instancecheck__(instance)\n\n    class Protocol(metaclass=_ProtocolMeta):\n        # There is quite a lot of overlapping code with typing.Generic.\n        # Unfortunately it is hard to avoid this while these live in two different\n        # modules. The duplicated code will be removed when Protocol is moved to typing.\n        \"\"\"Base class for protocol classes. Protocol classes are defined as::\n\n            class Proto(Protocol):\n                def meth(self) -> int:\n                    ...\n\n        Such classes are primarily used with static type checkers that recognize\n        structural subtyping (static duck-typing), for example::\n\n            class C:\n                def meth(self) -> int:\n                    return 0\n\n            def func(x: Proto) -> int:\n                return x.meth()\n\n            func(C())  # Passes static type check\n\n        See PEP 544 for details. Protocol classes decorated with\n        @typing_extensions.runtime act as simple-minded runtime protocol that checks\n        only the presence of given attributes, ignoring their type signatures.\n\n        Protocol classes can be generic, they are defined as::\n\n            class GenProto(Protocol[T]):\n                def meth(self) -> T:\n                    ...\n        \"\"\"\n        __slots__ = ()\n        _is_protocol = True\n\n        def __new__(cls, *args, **kwds):\n            if cls is Protocol:\n                raise TypeError(\"Type Protocol cannot be instantiated; \"\n                                \"it can only be used as a base class\")\n            return super().__new__(cls)\n\n        @typing._tp_cache\n        def __class_getitem__(cls, params):\n            if not isinstance(params, tuple):\n                params = (params,)\n            if not params and cls is not typing.Tuple:\n                raise TypeError(\n                    f\"Parameter list to {cls.__qualname__}[...] cannot be empty\")\n            msg = \"Parameters to generic types must be types.\"\n            params = tuple(typing._type_check(p, msg) for p in params)  # noqa\n            if cls is Protocol:\n                # Generic can only be subscripted with unique type variables.\n                if not all(isinstance(p, typing.TypeVar) for p in params):\n                    i = 0\n                    while isinstance(params[i], typing.TypeVar):\n                        i += 1\n                    raise TypeError(\n                        \"Parameters to Protocol[...] must all be type variables.\"\n                        f\" Parameter {i + 1} is {params[i]}\")\n                if len(set(params)) != len(params):\n                    raise TypeError(\n                        \"Parameters to Protocol[...] must all be unique\")\n            else:\n                # Subscripting a regular Generic subclass.\n                _check_generic(cls, params, len(cls.__parameters__))\n            return typing._GenericAlias(cls, params)\n\n        def __init_subclass__(cls, *args, **kwargs):\n            if '__orig_bases__' in cls.__dict__:\n                error = typing.Generic in cls.__orig_bases__\n            else:\n                error = typing.Generic in cls.__bases__\n            if error:\n                raise TypeError(\"Cannot inherit from plain Generic\")\n            _maybe_adjust_parameters(cls)\n\n            # Determine if this is a protocol or a concrete subclass.\n            if not cls.__dict__.get('_is_protocol', None):\n                cls._is_protocol = any(b is Protocol for b in cls.__bases__)\n\n            # Set (or override) the protocol subclass hook.\n            def _proto_hook(other):\n                if not cls.__dict__.get('_is_protocol', None):\n                    return NotImplemented\n                if not getattr(cls, '_is_runtime_protocol', False):\n                    if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:\n                        return NotImplemented\n                    raise TypeError(\"Instance and class checks can only be used with\"\n                                    \" @runtime protocols\")\n                if not _is_callable_members_only(cls):\n                    if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:\n                        return NotImplemented\n                    raise TypeError(\"Protocols with non-method members\"\n                                    \" don't support issubclass()\")\n                if not isinstance(other, type):\n                    # Same error as for issubclass(1, int)\n                    raise TypeError('issubclass() arg 1 must be a class')\n                for attr in _get_protocol_attrs(cls):\n                    for base in other.__mro__:\n                        if attr in base.__dict__:\n                            if base.__dict__[attr] is None:\n                                return NotImplemented\n                            break\n                        annotations = getattr(base, '__annotations__', {})\n                        if (isinstance(annotations, typing.Mapping) and\n                                attr in annotations and\n                                isinstance(other, _ProtocolMeta) and\n                                other._is_protocol):\n                            break\n                    else:\n                        return NotImplemented\n                return True\n            if '__subclasshook__' not in cls.__dict__:\n                cls.__subclasshook__ = _proto_hook\n\n            # We have nothing more to do for non-protocols.\n            if not cls._is_protocol:\n                return\n\n            # Check consistency of bases.\n            for base in cls.__bases__:\n                if not (base in (object, typing.Generic) or\n                        base.__module__ == 'collections.abc' and\n                        base.__name__ in _PROTO_WHITELIST or\n                        isinstance(base, _ProtocolMeta) and base._is_protocol):\n                    raise TypeError('Protocols can only inherit from other'\n                                    f' protocols, got {repr(base)}')\n            cls.__init__ = _no_init\n\n\n# 3.8+\nif hasattr(typing, 'runtime_checkable'):\n    runtime_checkable = typing.runtime_checkable\n# 3.7\nelse:\n    def runtime_checkable(cls):\n        \"\"\"Mark a protocol class as a runtime protocol, so that it\n        can be used with isinstance() and issubclass(). Raise TypeError\n        if applied to a non-protocol class.\n\n        This allows a simple-minded structural check very similar to the\n        one-offs in collections.abc such as Hashable.\n        \"\"\"\n        if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol:\n            raise TypeError('@runtime_checkable can be only applied to protocol classes,'\n                            f' got {cls!r}')\n        cls._is_runtime_protocol = True\n        return cls\n\n\n# Exists for backwards compatibility.\nruntime = runtime_checkable\n\n\n# 3.8+\nif hasattr(typing, 'SupportsIndex'):\n    SupportsIndex = typing.SupportsIndex\n# 3.7\nelse:\n    @runtime_checkable\n    class SupportsIndex(Protocol):\n        __slots__ = ()\n\n        @abc.abstractmethod\n        def __index__(self) -> int:\n            pass\n\n\nif hasattr(typing, \"Required\"):\n    # The standard library TypedDict in Python 3.8 does not store runtime information\n    # about which (if any) keys are optional.  See https://bugs.python.org/issue38834\n    # The standard library TypedDict in Python 3.9.0/1 does not honour the \"total\"\n    # keyword with old-style TypedDict().  See https://bugs.python.org/issue42059\n    # The standard library TypedDict below Python 3.11 does not store runtime\n    # information about optional and required keys when using Required or NotRequired.\n    # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.\n    TypedDict = typing.TypedDict\n    _TypedDictMeta = typing._TypedDictMeta\n    is_typeddict = typing.is_typeddict\nelse:\n    def _check_fails(cls, other):\n        try:\n            if sys._getframe(1).f_globals['__name__'] not in ['abc',\n                                                              'functools',\n                                                              'typing']:\n                # Typed dicts are only for static structural subtyping.\n                raise TypeError('TypedDict does not support instance and class checks')\n        except (AttributeError, ValueError):\n            pass\n        return False\n\n    def _dict_new(*args, **kwargs):\n        if not args:\n            raise TypeError('TypedDict.__new__(): not enough arguments')\n        _, args = args[0], args[1:]  # allow the \"cls\" keyword be passed\n        return dict(*args, **kwargs)\n\n    _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)'\n\n    def _typeddict_new(*args, total=True, **kwargs):\n        if not args:\n            raise TypeError('TypedDict.__new__(): not enough arguments')\n        _, args = args[0], args[1:]  # allow the \"cls\" keyword be passed\n        if args:\n            typename, args = args[0], args[1:]  # allow the \"_typename\" keyword be passed\n        elif '_typename' in kwargs:\n            typename = kwargs.pop('_typename')\n            import warnings\n            warnings.warn(\"Passing '_typename' as keyword argument is deprecated\",\n                          DeprecationWarning, stacklevel=2)\n        else:\n            raise TypeError(\"TypedDict.__new__() missing 1 required positional \"\n                            \"argument: '_typename'\")\n        if args:\n            try:\n                fields, = args  # allow the \"_fields\" keyword be passed\n            except ValueError:\n                raise TypeError('TypedDict.__new__() takes from 2 to 3 '\n                                f'positional arguments but {len(args) + 2} '\n                                'were given')\n        elif '_fields' in kwargs and len(kwargs) == 1:\n            fields = kwargs.pop('_fields')\n            import warnings\n            warnings.warn(\"Passing '_fields' as keyword argument is deprecated\",\n                          DeprecationWarning, stacklevel=2)\n        else:\n            fields = None\n\n        if fields is None:\n            fields = kwargs\n        elif kwargs:\n            raise TypeError(\"TypedDict takes either a dict or keyword arguments,\"\n                            \" but not both\")\n\n        ns = {'__annotations__': dict(fields)}\n        try:\n            # Setting correct module is necessary to make typed dict classes pickleable.\n            ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')\n        except (AttributeError, ValueError):\n            pass\n\n        return _TypedDictMeta(typename, (), ns, total=total)\n\n    _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,'\n                                         ' /, *, total=True, **kwargs)')\n\n    class _TypedDictMeta(type):\n        def __init__(cls, name, bases, ns, total=True):\n            super().__init__(name, bases, ns)\n\n        def __new__(cls, name, bases, ns, total=True):\n            # Create new typed dict class object.\n            # This method is called directly when TypedDict is subclassed,\n            # or via _typeddict_new when TypedDict is instantiated. This way\n            # TypedDict supports all three syntaxes described in its docstring.\n            # Subclasses and instances of TypedDict return actual dictionaries\n            # via _dict_new.\n            ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new\n            # Don't insert typing.Generic into __bases__ here,\n            # or Generic.__init_subclass__ will raise TypeError\n            # in the super().__new__() call.\n            # Instead, monkey-patch __bases__ onto the class after it's been created.\n            tp_dict = super().__new__(cls, name, (dict,), ns)\n\n            if any(issubclass(base, typing.Generic) for base in bases):\n                tp_dict.__bases__ = (typing.Generic, dict)\n                _maybe_adjust_parameters(tp_dict)\n\n            annotations = {}\n            own_annotations = ns.get('__annotations__', {})\n            msg = \"TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type\"\n            own_annotations = {\n                n: typing._type_check(tp, msg) for n, tp in own_annotations.items()\n            }\n            required_keys = set()\n            optional_keys = set()\n\n            for base in bases:\n                annotations.update(base.__dict__.get('__annotations__', {}))\n                required_keys.update(base.__dict__.get('__required_keys__', ()))\n                optional_keys.update(base.__dict__.get('__optional_keys__', ()))\n\n            annotations.update(own_annotations)\n            for annotation_key, annotation_type in own_annotations.items():\n                annotation_origin = get_origin(annotation_type)\n                if annotation_origin is Annotated:\n                    annotation_args = get_args(annotation_type)\n                    if annotation_args:\n                        annotation_type = annotation_args[0]\n                        annotation_origin = get_origin(annotation_type)\n\n                if annotation_origin is Required:\n                    required_keys.add(annotation_key)\n                elif annotation_origin is NotRequired:\n                    optional_keys.add(annotation_key)\n                elif total:\n                    required_keys.add(annotation_key)\n                else:\n                    optional_keys.add(annotation_key)\n\n            tp_dict.__annotations__ = annotations\n            tp_dict.__required_keys__ = frozenset(required_keys)\n            tp_dict.__optional_keys__ = frozenset(optional_keys)\n            if not hasattr(tp_dict, '__total__'):\n                tp_dict.__total__ = total\n            return tp_dict\n\n        __instancecheck__ = __subclasscheck__ = _check_fails\n\n    TypedDict = _TypedDictMeta('TypedDict', (dict,), {})\n    TypedDict.__module__ = __name__\n    TypedDict.__doc__ = \\\n        \"\"\"A simple typed name space. At runtime it is equivalent to a plain dict.\n\n        TypedDict creates a dictionary type that expects all of its\n        instances to have a certain set of keys, with each key\n        associated with a value of a consistent type. This expectation\n        is not checked at runtime but is only enforced by type checkers.\n        Usage::\n\n            class Point2D(TypedDict):\n                x: int\n                y: int\n                label: str\n\n            a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK\n            b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check\n\n            assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')\n\n        The type info can be accessed via the Point2D.__annotations__ dict, and\n        the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.\n        TypedDict supports two additional equivalent forms::\n\n            Point2D = TypedDict('Point2D', x=int, y=int, label=str)\n            Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})\n\n        The class syntax is only supported in Python 3.6+, while two other\n        syntax forms work for Python 2.7 and 3.2+\n        \"\"\"\n\n    if hasattr(typing, \"_TypedDictMeta\"):\n        _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)\n    else:\n        _TYPEDDICT_TYPES = (_TypedDictMeta,)\n\n    def is_typeddict(tp):\n        \"\"\"Check if an annotation is a TypedDict class\n\n        For example::\n            class Film(TypedDict):\n                title: str\n                year: int\n\n            is_typeddict(Film)  # => True\n            is_typeddict(Union[list, str])  # => False\n        \"\"\"\n        return isinstance(tp, tuple(_TYPEDDICT_TYPES))\n\n\nif hasattr(typing, \"assert_type\"):\n    assert_type = typing.assert_type\n\nelse:\n    def assert_type(__val, __typ):\n        \"\"\"Assert (to the type checker) that the value is of the given type.\n\n        When the type checker encounters a call to assert_type(), it\n        emits an error if the value is not of the specified type::\n\n            def greet(name: str) -> None:\n                assert_type(name, str)  # ok\n                assert_type(name, int)  # type checker error\n\n        At runtime this returns the first argument unchanged and otherwise\n        does nothing.\n        \"\"\"\n        return __val\n\n\nif hasattr(typing, \"Required\"):\n    get_type_hints = typing.get_type_hints\nelse:\n    import functools\n    import types\n\n    # replaces _strip_annotations()\n    def _strip_extras(t):\n        \"\"\"Strips Annotated, Required and NotRequired from a given type.\"\"\"\n        if isinstance(t, _AnnotatedAlias):\n            return _strip_extras(t.__origin__)\n        if hasattr(t, \"__origin__\") and t.__origin__ in (Required, NotRequired):\n            return _strip_extras(t.__args__[0])\n        if isinstance(t, typing._GenericAlias):\n            stripped_args = tuple(_strip_extras(a) for a in t.__args__)\n            if stripped_args == t.__args__:\n                return t\n            return t.copy_with(stripped_args)\n        if hasattr(types, \"GenericAlias\") and isinstance(t, types.GenericAlias):\n            stripped_args = tuple(_strip_extras(a) for a in t.__args__)\n            if stripped_args == t.__args__:\n                return t\n            return types.GenericAlias(t.__origin__, stripped_args)\n        if hasattr(types, \"UnionType\") and isinstance(t, types.UnionType):\n            stripped_args = tuple(_strip_extras(a) for a in t.__args__)\n            if stripped_args == t.__args__:\n                return t\n            return functools.reduce(operator.or_, stripped_args)\n\n        return t\n\n    def get_type_hints(obj, globalns=None, localns=None, include_extras=False):\n        \"\"\"Return type hints for an object.\n\n        This is often the same as obj.__annotations__, but it handles\n        forward references encoded as string literals, adds Optional[t] if a\n        default value equal to None is set and recursively replaces all\n        'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'\n        (unless 'include_extras=True').\n\n        The argument may be a module, class, method, or function. The annotations\n        are returned as a dictionary. For classes, annotations include also\n        inherited members.\n\n        TypeError is raised if the argument is not of a type that can contain\n        annotations, and an empty dictionary is returned if no annotations are\n        present.\n\n        BEWARE -- the behavior of globalns and localns is counterintuitive\n        (unless you are familiar with how eval() and exec() work).  The\n        search order is locals first, then globals.\n\n        - If no dict arguments are passed, an attempt is made to use the\n          globals from obj (or the respective module's globals for classes),\n          and these are also used as the locals.  If the object does not appear\n          to have globals, an empty dictionary is used.\n\n        - If one dict argument is passed, it is used for both globals and\n          locals.\n\n        - If two dict arguments are passed, they specify globals and\n          locals, respectively.\n        \"\"\"\n        if hasattr(typing, \"Annotated\"):\n            hint = typing.get_type_hints(\n                obj, globalns=globalns, localns=localns, include_extras=True\n            )\n        else:\n            hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)\n        if include_extras:\n            return hint\n        return {k: _strip_extras(t) for k, t in hint.items()}\n\n\n# Python 3.9+ has PEP 593 (Annotated)\nif hasattr(typing, 'Annotated'):\n    Annotated = typing.Annotated\n    # Not exported and not a public API, but needed for get_origin() and get_args()\n    # to work.\n    _AnnotatedAlias = typing._AnnotatedAlias\n# 3.7-3.8\nelse:\n    class _AnnotatedAlias(typing._GenericAlias, _root=True):\n        \"\"\"Runtime representation of an annotated type.\n\n        At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'\n        with extra annotations. The alias behaves like a normal typing alias,\n        instantiating is the same as instantiating the underlying type, binding\n        it to types is also the same.\n        \"\"\"\n        def __init__(self, origin, metadata):\n            if isinstance(origin, _AnnotatedAlias):\n                metadata = origin.__metadata__ + metadata\n                origin = origin.__origin__\n            super().__init__(origin, origin)\n            self.__metadata__ = metadata\n\n        def copy_with(self, params):\n            assert len(params) == 1\n            new_type = params[0]\n            return _AnnotatedAlias(new_type, self.__metadata__)\n\n        def __repr__(self):\n            return (f\"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, \"\n                    f\"{', '.join(repr(a) for a in self.__metadata__)}]\")\n\n        def __reduce__(self):\n            return operator.getitem, (\n                Annotated, (self.__origin__,) + self.__metadata__\n            )\n\n        def __eq__(self, other):\n            if not isinstance(other, _AnnotatedAlias):\n                return NotImplemented\n            if self.__origin__ != other.__origin__:\n                return False\n            return self.__metadata__ == other.__metadata__\n\n        def __hash__(self):\n            return hash((self.__origin__, self.__metadata__))\n\n    class Annotated:\n        \"\"\"Add context specific metadata to a type.\n\n        Example: Annotated[int, runtime_check.Unsigned] indicates to the\n        hypothetical runtime_check module that this type is an unsigned int.\n        Every other consumer of this type can ignore this metadata and treat\n        this type as int.\n\n        The first argument to Annotated must be a valid type (and will be in\n        the __origin__ field), the remaining arguments are kept as a tuple in\n        the __extra__ field.\n\n        Details:\n\n        - It's an error to call `Annotated` with less than two arguments.\n        - Nested Annotated are flattened::\n\n            Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]\n\n        - Instantiating an annotated type is equivalent to instantiating the\n        underlying type::\n\n            Annotated[C, Ann1](5) == C(5)\n\n        - Annotated can be used as a generic type alias::\n\n            Optimized = Annotated[T, runtime.Optimize()]\n            Optimized[int] == Annotated[int, runtime.Optimize()]\n\n            OptimizedList = Annotated[List[T], runtime.Optimize()]\n            OptimizedList[int] == Annotated[List[int], runtime.Optimize()]\n        \"\"\"\n\n        __slots__ = ()\n\n        def __new__(cls, *args, **kwargs):\n            raise TypeError(\"Type Annotated cannot be instantiated.\")\n\n        @typing._tp_cache\n        def __class_getitem__(cls, params):\n            if not isinstance(params, tuple) or len(params) < 2:\n                raise TypeError(\"Annotated[...] should be used \"\n                                \"with at least two arguments (a type and an \"\n                                \"annotation).\")\n            allowed_special_forms = (ClassVar, Final)\n            if get_origin(params[0]) in allowed_special_forms:\n                origin = params[0]\n            else:\n                msg = \"Annotated[t, ...]: t must be a type.\"\n                origin = typing._type_check(params[0], msg)\n            metadata = tuple(params[1:])\n            return _AnnotatedAlias(origin, metadata)\n\n        def __init_subclass__(cls, *args, **kwargs):\n            raise TypeError(\n                f\"Cannot subclass {cls.__module__}.Annotated\"\n            )\n\n# Python 3.8 has get_origin() and get_args() but those implementations aren't\n# Annotated-aware, so we can't use those. Python 3.9's versions don't support\n# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.\nif sys.version_info[:2] >= (3, 10):\n    get_origin = typing.get_origin\n    get_args = typing.get_args\n# 3.7-3.9\nelse:\n    try:\n        # 3.9+\n        from typing import _BaseGenericAlias\n    except ImportError:\n        _BaseGenericAlias = typing._GenericAlias\n    try:\n        # 3.9+\n        from typing import GenericAlias as _typing_GenericAlias\n    except ImportError:\n        _typing_GenericAlias = typing._GenericAlias\n\n    def get_origin(tp):\n        \"\"\"Get the unsubscripted version of a type.\n\n        This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar\n        and Annotated. Return None for unsupported types. Examples::\n\n            get_origin(Literal[42]) is Literal\n            get_origin(int) is None\n            get_origin(ClassVar[int]) is ClassVar\n            get_origin(Generic) is Generic\n            get_origin(Generic[T]) is Generic\n            get_origin(Union[T, int]) is Union\n            get_origin(List[Tuple[T, T]][int]) == list\n            get_origin(P.args) is P\n        \"\"\"\n        if isinstance(tp, _AnnotatedAlias):\n            return Annotated\n        if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias,\n                           ParamSpecArgs, ParamSpecKwargs)):\n            return tp.__origin__\n        if tp is typing.Generic:\n            return typing.Generic\n        return None\n\n    def get_args(tp):\n        \"\"\"Get type arguments with all substitutions performed.\n\n        For unions, basic simplifications used by Union constructor are performed.\n        Examples::\n            get_args(Dict[str, int]) == (str, int)\n            get_args(int) == ()\n            get_args(Union[int, Union[T, int], str][int]) == (int, str)\n            get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])\n            get_args(Callable[[], T][int]) == ([], int)\n        \"\"\"\n        if isinstance(tp, _AnnotatedAlias):\n            return (tp.__origin__,) + tp.__metadata__\n        if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):\n            if getattr(tp, \"_special\", False):\n                return ()\n            res = tp.__args__\n            if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:\n                res = (list(res[:-1]), res[-1])\n            return res\n        return ()\n\n\n# 3.10+\nif hasattr(typing, 'TypeAlias'):\n    TypeAlias = typing.TypeAlias\n# 3.9\nelif sys.version_info[:2] >= (3, 9):\n    class _TypeAliasForm(typing._SpecialForm, _root=True):\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n    @_TypeAliasForm\n    def TypeAlias(self, parameters):\n        \"\"\"Special marker indicating that an assignment should\n        be recognized as a proper type alias definition by type\n        checkers.\n\n        For example::\n\n            Predicate: TypeAlias = Callable[..., bool]\n\n        It's invalid when used anywhere except as in the example above.\n        \"\"\"\n        raise TypeError(f\"{self} is not subscriptable\")\n# 3.7-3.8\nelse:\n    class _TypeAliasForm(typing._SpecialForm, _root=True):\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n    TypeAlias = _TypeAliasForm('TypeAlias',\n                               doc=\"\"\"Special marker indicating that an assignment should\n                               be recognized as a proper type alias definition by type\n                               checkers.\n\n                               For example::\n\n                                   Predicate: TypeAlias = Callable[..., bool]\n\n                               It's invalid when used anywhere except as in the example\n                               above.\"\"\")\n\n\nclass _DefaultMixin:\n    \"\"\"Mixin for TypeVarLike defaults.\"\"\"\n\n    __slots__ = ()\n\n    def __init__(self, default):\n        if isinstance(default, (tuple, list)):\n            self.__default__ = tuple((typing._type_check(d, \"Default must be a type\")\n                                      for d in default))\n        elif default:\n            self.__default__ = typing._type_check(default, \"Default must be a type\")\n        else:\n            self.__default__ = None\n\n\n# Add default and infer_variance parameters from PEP 696 and 695\nclass TypeVar(typing.TypeVar, _DefaultMixin, _root=True):\n    \"\"\"Type variable.\"\"\"\n\n    __module__ = 'typing'\n\n    def __init__(self, name, *constraints, bound=None,\n                 covariant=False, contravariant=False,\n                 default=None, infer_variance=False):\n        super().__init__(name, *constraints, bound=bound, covariant=covariant,\n                         contravariant=contravariant)\n        _DefaultMixin.__init__(self, default)\n        self.__infer_variance__ = infer_variance\n\n        # for pickling:\n        try:\n            def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')\n        except (AttributeError, ValueError):\n            def_mod = None\n        if def_mod != 'typing_extensions':\n            self.__module__ = def_mod\n\n\n# Python 3.10+ has PEP 612\nif hasattr(typing, 'ParamSpecArgs'):\n    ParamSpecArgs = typing.ParamSpecArgs\n    ParamSpecKwargs = typing.ParamSpecKwargs\n# 3.7-3.9\nelse:\n    class _Immutable:\n        \"\"\"Mixin to indicate that object should not be copied.\"\"\"\n        __slots__ = ()\n\n        def __copy__(self):\n            return self\n\n        def __deepcopy__(self, memo):\n            return self\n\n    class ParamSpecArgs(_Immutable):\n        \"\"\"The args for a ParamSpec object.\n\n        Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.\n\n        ParamSpecArgs objects have a reference back to their ParamSpec:\n\n        P.args.__origin__ is P\n\n        This type is meant for runtime introspection and has no special meaning to\n        static type checkers.\n        \"\"\"\n        def __init__(self, origin):\n            self.__origin__ = origin\n\n        def __repr__(self):\n            return f\"{self.__origin__.__name__}.args\"\n\n        def __eq__(self, other):\n            if not isinstance(other, ParamSpecArgs):\n                return NotImplemented\n            return self.__origin__ == other.__origin__\n\n    class ParamSpecKwargs(_Immutable):\n        \"\"\"The kwargs for a ParamSpec object.\n\n        Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.\n\n        ParamSpecKwargs objects have a reference back to their ParamSpec:\n\n        P.kwargs.__origin__ is P\n\n        This type is meant for runtime introspection and has no special meaning to\n        static type checkers.\n        \"\"\"\n        def __init__(self, origin):\n            self.__origin__ = origin\n\n        def __repr__(self):\n            return f\"{self.__origin__.__name__}.kwargs\"\n\n        def __eq__(self, other):\n            if not isinstance(other, ParamSpecKwargs):\n                return NotImplemented\n            return self.__origin__ == other.__origin__\n\n# 3.10+\nif hasattr(typing, 'ParamSpec'):\n\n    # Add default Parameter - PEP 696\n    class ParamSpec(typing.ParamSpec, _DefaultMixin, _root=True):\n        \"\"\"Parameter specification variable.\"\"\"\n\n        __module__ = 'typing'\n\n        def __init__(self, name, *, bound=None, covariant=False, contravariant=False,\n                     default=None):\n            super().__init__(name, bound=bound, covariant=covariant,\n                             contravariant=contravariant)\n            _DefaultMixin.__init__(self, default)\n\n            # for pickling:\n            try:\n                def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')\n            except (AttributeError, ValueError):\n                def_mod = None\n            if def_mod != 'typing_extensions':\n                self.__module__ = def_mod\n\n# 3.7-3.9\nelse:\n\n    # Inherits from list as a workaround for Callable checks in Python < 3.9.2.\n    class ParamSpec(list, _DefaultMixin):\n        \"\"\"Parameter specification variable.\n\n        Usage::\n\n           P = ParamSpec('P')\n\n        Parameter specification variables exist primarily for the benefit of static\n        type checkers.  They are used to forward the parameter types of one\n        callable to another callable, a pattern commonly found in higher order\n        functions and decorators.  They are only valid when used in ``Concatenate``,\n        or s the first argument to ``Callable``. In Python 3.10 and higher,\n        they are also supported in user-defined Generics at runtime.\n        See class Generic for more information on generic types.  An\n        example for annotating a decorator::\n\n           T = TypeVar('T')\n           P = ParamSpec('P')\n\n           def add_logging(f: Callable[P, T]) -> Callable[P, T]:\n               '''A type-safe decorator to add logging to a function.'''\n               def inner(*args: P.args, **kwargs: P.kwargs) -> T:\n                   logging.info(f'{f.__name__} was called')\n                   return f(*args, **kwargs)\n               return inner\n\n           @add_logging\n           def add_two(x: float, y: float) -> float:\n               '''Add two numbers together.'''\n               return x + y\n\n        Parameter specification variables defined with covariant=True or\n        contravariant=True can be used to declare covariant or contravariant\n        generic types.  These keyword arguments are valid, but their actual semantics\n        are yet to be decided.  See PEP 612 for details.\n\n        Parameter specification variables can be introspected. e.g.:\n\n           P.__name__ == 'T'\n           P.__bound__ == None\n           P.__covariant__ == False\n           P.__contravariant__ == False\n\n        Note that only parameter specification variables defined in global scope can\n        be pickled.\n        \"\"\"\n\n        # Trick Generic __parameters__.\n        __class__ = typing.TypeVar\n\n        @property\n        def args(self):\n            return ParamSpecArgs(self)\n\n        @property\n        def kwargs(self):\n            return ParamSpecKwargs(self)\n\n        def __init__(self, name, *, bound=None, covariant=False, contravariant=False,\n                     default=None):\n            super().__init__([self])\n            self.__name__ = name\n            self.__covariant__ = bool(covariant)\n            self.__contravariant__ = bool(contravariant)\n            if bound:\n                self.__bound__ = typing._type_check(bound, 'Bound must be a type.')\n            else:\n                self.__bound__ = None\n            _DefaultMixin.__init__(self, default)\n\n            # for pickling:\n            try:\n                def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')\n            except (AttributeError, ValueError):\n                def_mod = None\n            if def_mod != 'typing_extensions':\n                self.__module__ = def_mod\n\n        def __repr__(self):\n            if self.__covariant__:\n                prefix = '+'\n            elif self.__contravariant__:\n                prefix = '-'\n            else:\n                prefix = '~'\n            return prefix + self.__name__\n\n        def __hash__(self):\n            return object.__hash__(self)\n\n        def __eq__(self, other):\n            return self is other\n\n        def __reduce__(self):\n            return self.__name__\n\n        # Hack to get typing._type_check to pass.\n        def __call__(self, *args, **kwargs):\n            pass\n\n\n# 3.7-3.9\nif not hasattr(typing, 'Concatenate'):\n    # Inherits from list as a workaround for Callable checks in Python < 3.9.2.\n    class _ConcatenateGenericAlias(list):\n\n        # Trick Generic into looking into this for __parameters__.\n        __class__ = typing._GenericAlias\n\n        # Flag in 3.8.\n        _special = False\n\n        def __init__(self, origin, args):\n            super().__init__(args)\n            self.__origin__ = origin\n            self.__args__ = args\n\n        def __repr__(self):\n            _type_repr = typing._type_repr\n            return (f'{_type_repr(self.__origin__)}'\n                    f'[{\", \".join(_type_repr(arg) for arg in self.__args__)}]')\n\n        def __hash__(self):\n            return hash((self.__origin__, self.__args__))\n\n        # Hack to get typing._type_check to pass in Generic.\n        def __call__(self, *args, **kwargs):\n            pass\n\n        @property\n        def __parameters__(self):\n            return tuple(\n                tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))\n            )\n\n\n# 3.7-3.9\n@typing._tp_cache\ndef _concatenate_getitem(self, parameters):\n    if parameters == ():\n        raise TypeError(\"Cannot take a Concatenate of no types.\")\n    if not isinstance(parameters, tuple):\n        parameters = (parameters,)\n    if not isinstance(parameters[-1], ParamSpec):\n        raise TypeError(\"The last parameter to Concatenate should be a \"\n                        \"ParamSpec variable.\")\n    msg = \"Concatenate[arg, ...]: each arg must be a type.\"\n    parameters = tuple(typing._type_check(p, msg) for p in parameters)\n    return _ConcatenateGenericAlias(self, parameters)\n\n\n# 3.10+\nif hasattr(typing, 'Concatenate'):\n    Concatenate = typing.Concatenate\n    _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa\n# 3.9\nelif sys.version_info[:2] >= (3, 9):\n    @_TypeAliasForm\n    def Concatenate(self, parameters):\n        \"\"\"Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a\n        higher order function which adds, removes or transforms parameters of a\n        callable.\n\n        For example::\n\n           Callable[Concatenate[int, P], int]\n\n        See PEP 612 for detailed information.\n        \"\"\"\n        return _concatenate_getitem(self, parameters)\n# 3.7-8\nelse:\n    class _ConcatenateForm(typing._SpecialForm, _root=True):\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n        def __getitem__(self, parameters):\n            return _concatenate_getitem(self, parameters)\n\n    Concatenate = _ConcatenateForm(\n        'Concatenate',\n        doc=\"\"\"Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a\n        higher order function which adds, removes or transforms parameters of a\n        callable.\n\n        For example::\n\n           Callable[Concatenate[int, P], int]\n\n        See PEP 612 for detailed information.\n        \"\"\")\n\n# 3.10+\nif hasattr(typing, 'TypeGuard'):\n    TypeGuard = typing.TypeGuard\n# 3.9\nelif sys.version_info[:2] >= (3, 9):\n    class _TypeGuardForm(typing._SpecialForm, _root=True):\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n    @_TypeGuardForm\n    def TypeGuard(self, parameters):\n        \"\"\"Special typing form used to annotate the return type of a user-defined\n        type guard function.  ``TypeGuard`` only accepts a single type argument.\n        At runtime, functions marked this way should return a boolean.\n\n        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static\n        type checkers to determine a more precise type of an expression within a\n        program's code flow.  Usually type narrowing is done by analyzing\n        conditional code flow and applying the narrowing to a block of code.  The\n        conditional expression here is sometimes referred to as a \"type guard\".\n\n        Sometimes it would be convenient to use a user-defined boolean function\n        as a type guard.  Such a function should use ``TypeGuard[...]`` as its\n        return type to alert static type checkers to this intention.\n\n        Using  ``-> TypeGuard`` tells the static type checker that for a given\n        function:\n\n        1. The return value is a boolean.\n        2. If the return value is ``True``, the type of its argument\n        is the type inside ``TypeGuard``.\n\n        For example::\n\n            def is_str(val: Union[str, float]):\n                # \"isinstance\" type guard\n                if isinstance(val, str):\n                    # Type of ``val`` is narrowed to ``str``\n                    ...\n                else:\n                    # Else, type of ``val`` is narrowed to ``float``.\n                    ...\n\n        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower\n        form of ``TypeA`` (it can even be a wider form) and this may lead to\n        type-unsafe results.  The main reason is to allow for things like\n        narrowing ``List[object]`` to ``List[str]`` even though the latter is not\n        a subtype of the former, since ``List`` is invariant.  The responsibility of\n        writing type-safe type guards is left to the user.\n\n        ``TypeGuard`` also works with type variables.  For more information, see\n        PEP 647 (User-Defined Type Guards).\n        \"\"\"\n        item = typing._type_check(parameters, f'{self} accepts only a single type.')\n        return typing._GenericAlias(self, (item,))\n# 3.7-3.8\nelse:\n    class _TypeGuardForm(typing._SpecialForm, _root=True):\n\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n        def __getitem__(self, parameters):\n            item = typing._type_check(parameters,\n                                      f'{self._name} accepts only a single type')\n            return typing._GenericAlias(self, (item,))\n\n    TypeGuard = _TypeGuardForm(\n        'TypeGuard',\n        doc=\"\"\"Special typing form used to annotate the return type of a user-defined\n        type guard function.  ``TypeGuard`` only accepts a single type argument.\n        At runtime, functions marked this way should return a boolean.\n\n        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static\n        type checkers to determine a more precise type of an expression within a\n        program's code flow.  Usually type narrowing is done by analyzing\n        conditional code flow and applying the narrowing to a block of code.  The\n        conditional expression here is sometimes referred to as a \"type guard\".\n\n        Sometimes it would be convenient to use a user-defined boolean function\n        as a type guard.  Such a function should use ``TypeGuard[...]`` as its\n        return type to alert static type checkers to this intention.\n\n        Using  ``-> TypeGuard`` tells the static type checker that for a given\n        function:\n\n        1. The return value is a boolean.\n        2. If the return value is ``True``, the type of its argument\n        is the type inside ``TypeGuard``.\n\n        For example::\n\n            def is_str(val: Union[str, float]):\n                # \"isinstance\" type guard\n                if isinstance(val, str):\n                    # Type of ``val`` is narrowed to ``str``\n                    ...\n                else:\n                    # Else, type of ``val`` is narrowed to ``float``.\n                    ...\n\n        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower\n        form of ``TypeA`` (it can even be a wider form) and this may lead to\n        type-unsafe results.  The main reason is to allow for things like\n        narrowing ``List[object]`` to ``List[str]`` even though the latter is not\n        a subtype of the former, since ``List`` is invariant.  The responsibility of\n        writing type-safe type guards is left to the user.\n\n        ``TypeGuard`` also works with type variables.  For more information, see\n        PEP 647 (User-Defined Type Guards).\n        \"\"\")\n\n\n# Vendored from cpython typing._SpecialFrom\nclass _SpecialForm(typing._Final, _root=True):\n    __slots__ = ('_name', '__doc__', '_getitem')\n\n    def __init__(self, getitem):\n        self._getitem = getitem\n        self._name = getitem.__name__\n        self.__doc__ = getitem.__doc__\n\n    def __getattr__(self, item):\n        if item in {'__name__', '__qualname__'}:\n            return self._name\n\n        raise AttributeError(item)\n\n    def __mro_entries__(self, bases):\n        raise TypeError(f\"Cannot subclass {self!r}\")\n\n    def __repr__(self):\n        return f'typing_extensions.{self._name}'\n\n    def __reduce__(self):\n        return self._name\n\n    def __call__(self, *args, **kwds):\n        raise TypeError(f\"Cannot instantiate {self!r}\")\n\n    def __or__(self, other):\n        return typing.Union[self, other]\n\n    def __ror__(self, other):\n        return typing.Union[other, self]\n\n    def __instancecheck__(self, obj):\n        raise TypeError(f\"{self} cannot be used with isinstance()\")\n\n    def __subclasscheck__(self, cls):\n        raise TypeError(f\"{self} cannot be used with issubclass()\")\n\n    @typing._tp_cache\n    def __getitem__(self, parameters):\n        return self._getitem(self, parameters)\n\n\nif hasattr(typing, \"LiteralString\"):\n    LiteralString = typing.LiteralString\nelse:\n    @_SpecialForm\n    def LiteralString(self, params):\n        \"\"\"Represents an arbitrary literal string.\n\n        Example::\n\n          from pip._vendor.typing_extensions import LiteralString\n\n          def query(sql: LiteralString) -> ...:\n              ...\n\n          query(\"SELECT * FROM table\")  # ok\n          query(f\"SELECT * FROM {input()}\")  # not ok\n\n        See PEP 675 for details.\n\n        \"\"\"\n        raise TypeError(f\"{self} is not subscriptable\")\n\n\nif hasattr(typing, \"Self\"):\n    Self = typing.Self\nelse:\n    @_SpecialForm\n    def Self(self, params):\n        \"\"\"Used to spell the type of \"self\" in classes.\n\n        Example::\n\n          from typing import Self\n\n          class ReturnsSelf:\n              def parse(self, data: bytes) -> Self:\n                  ...\n                  return self\n\n        \"\"\"\n\n        raise TypeError(f\"{self} is not subscriptable\")\n\n\nif hasattr(typing, \"Never\"):\n    Never = typing.Never\nelse:\n    @_SpecialForm\n    def Never(self, params):\n        \"\"\"The bottom type, a type that has no members.\n\n        This can be used to define a function that should never be\n        called, or a function that never returns::\n\n            from pip._vendor.typing_extensions import Never\n\n            def never_call_me(arg: Never) -> None:\n                pass\n\n            def int_or_str(arg: int | str) -> None:\n                never_call_me(arg)  # type checker error\n                match arg:\n                    case int():\n                        print(\"It's an int\")\n                    case str():\n                        print(\"It's a str\")\n                    case _:\n                        never_call_me(arg)  # ok, arg is of type Never\n\n        \"\"\"\n\n        raise TypeError(f\"{self} is not subscriptable\")\n\n\nif hasattr(typing, 'Required'):\n    Required = typing.Required\n    NotRequired = typing.NotRequired\nelif sys.version_info[:2] >= (3, 9):\n    class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n    @_ExtensionsSpecialForm\n    def Required(self, parameters):\n        \"\"\"A special typing construct to mark a key of a total=False TypedDict\n        as required. For example:\n\n            class Movie(TypedDict, total=False):\n                title: Required[str]\n                year: int\n\n            m = Movie(\n                title='The Matrix',  # typechecker error if key is omitted\n                year=1999,\n            )\n\n        There is no runtime checking that a required key is actually provided\n        when instantiating a related TypedDict.\n        \"\"\"\n        item = typing._type_check(parameters, f'{self._name} accepts only a single type.')\n        return typing._GenericAlias(self, (item,))\n\n    @_ExtensionsSpecialForm\n    def NotRequired(self, parameters):\n        \"\"\"A special typing construct to mark a key of a TypedDict as\n        potentially missing. For example:\n\n            class Movie(TypedDict):\n                title: str\n                year: NotRequired[int]\n\n            m = Movie(\n                title='The Matrix',  # typechecker error if key is omitted\n                year=1999,\n            )\n        \"\"\"\n        item = typing._type_check(parameters, f'{self._name} accepts only a single type.')\n        return typing._GenericAlias(self, (item,))\n\nelse:\n    class _RequiredForm(typing._SpecialForm, _root=True):\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n        def __getitem__(self, parameters):\n            item = typing._type_check(parameters,\n                                      f'{self._name} accepts only a single type.')\n            return typing._GenericAlias(self, (item,))\n\n    Required = _RequiredForm(\n        'Required',\n        doc=\"\"\"A special typing construct to mark a key of a total=False TypedDict\n        as required. For example:\n\n            class Movie(TypedDict, total=False):\n                title: Required[str]\n                year: int\n\n            m = Movie(\n                title='The Matrix',  # typechecker error if key is omitted\n                year=1999,\n            )\n\n        There is no runtime checking that a required key is actually provided\n        when instantiating a related TypedDict.\n        \"\"\")\n    NotRequired = _RequiredForm(\n        'NotRequired',\n        doc=\"\"\"A special typing construct to mark a key of a TypedDict as\n        potentially missing. For example:\n\n            class Movie(TypedDict):\n                title: str\n                year: NotRequired[int]\n\n            m = Movie(\n                title='The Matrix',  # typechecker error if key is omitted\n                year=1999,\n            )\n        \"\"\")\n\n\nif hasattr(typing, \"Unpack\"):  # 3.11+\n    Unpack = typing.Unpack\nelif sys.version_info[:2] >= (3, 9):\n    class _UnpackSpecialForm(typing._SpecialForm, _root=True):\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n    class _UnpackAlias(typing._GenericAlias, _root=True):\n        __class__ = typing.TypeVar\n\n    @_UnpackSpecialForm\n    def Unpack(self, parameters):\n        \"\"\"A special typing construct to unpack a variadic type. For example:\n\n            Shape = TypeVarTuple('Shape')\n            Batch = NewType('Batch', int)\n\n            def add_batch_axis(\n                x: Array[Unpack[Shape]]\n            ) -> Array[Batch, Unpack[Shape]]: ...\n\n        \"\"\"\n        item = typing._type_check(parameters, f'{self._name} accepts only a single type.')\n        return _UnpackAlias(self, (item,))\n\n    def _is_unpack(obj):\n        return isinstance(obj, _UnpackAlias)\n\nelse:\n    class _UnpackAlias(typing._GenericAlias, _root=True):\n        __class__ = typing.TypeVar\n\n    class _UnpackForm(typing._SpecialForm, _root=True):\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n        def __getitem__(self, parameters):\n            item = typing._type_check(parameters,\n                                      f'{self._name} accepts only a single type.')\n            return _UnpackAlias(self, (item,))\n\n    Unpack = _UnpackForm(\n        'Unpack',\n        doc=\"\"\"A special typing construct to unpack a variadic type. For example:\n\n            Shape = TypeVarTuple('Shape')\n            Batch = NewType('Batch', int)\n\n            def add_batch_axis(\n                x: Array[Unpack[Shape]]\n            ) -> Array[Batch, Unpack[Shape]]: ...\n\n        \"\"\")\n\n    def _is_unpack(obj):\n        return isinstance(obj, _UnpackAlias)\n\n\nif hasattr(typing, \"TypeVarTuple\"):  # 3.11+\n\n    # Add default Parameter - PEP 696\n    class TypeVarTuple(typing.TypeVarTuple, _DefaultMixin, _root=True):\n        \"\"\"Type variable tuple.\"\"\"\n\n        def __init__(self, name, *, default=None):\n            super().__init__(name)\n            _DefaultMixin.__init__(self, default)\n\n            # for pickling:\n            try:\n                def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')\n            except (AttributeError, ValueError):\n                def_mod = None\n            if def_mod != 'typing_extensions':\n                self.__module__ = def_mod\n\nelse:\n    class TypeVarTuple(_DefaultMixin):\n        \"\"\"Type variable tuple.\n\n        Usage::\n\n            Ts = TypeVarTuple('Ts')\n\n        In the same way that a normal type variable is a stand-in for a single\n        type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*\n        type such as ``Tuple[int, str]``.\n\n        Type variable tuples can be used in ``Generic`` declarations.\n        Consider the following example::\n\n            class Array(Generic[*Ts]): ...\n\n        The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,\n        where ``T1`` and ``T2`` are type variables. To use these type variables\n        as type parameters of ``Array``, we must *unpack* the type variable tuple using\n        the star operator: ``*Ts``. The signature of ``Array`` then behaves\n        as if we had simply written ``class Array(Generic[T1, T2]): ...``.\n        In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows\n        us to parameterise the class with an *arbitrary* number of type parameters.\n\n        Type variable tuples can be used anywhere a normal ``TypeVar`` can.\n        This includes class definitions, as shown above, as well as function\n        signatures and variable annotations::\n\n            class Array(Generic[*Ts]):\n\n                def __init__(self, shape: Tuple[*Ts]):\n                    self._shape: Tuple[*Ts] = shape\n\n                def get_shape(self) -> Tuple[*Ts]:\n                    return self._shape\n\n            shape = (Height(480), Width(640))\n            x: Array[Height, Width] = Array(shape)\n            y = abs(x)  # Inferred type is Array[Height, Width]\n            z = x + x   #        ...    is Array[Height, Width]\n            x.get_shape()  #     ...    is tuple[Height, Width]\n\n        \"\"\"\n\n        # Trick Generic __parameters__.\n        __class__ = typing.TypeVar\n\n        def __iter__(self):\n            yield self.__unpacked__\n\n        def __init__(self, name, *, default=None):\n            self.__name__ = name\n            _DefaultMixin.__init__(self, default)\n\n            # for pickling:\n            try:\n                def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')\n            except (AttributeError, ValueError):\n                def_mod = None\n            if def_mod != 'typing_extensions':\n                self.__module__ = def_mod\n\n            self.__unpacked__ = Unpack[self]\n\n        def __repr__(self):\n            return self.__name__\n\n        def __hash__(self):\n            return object.__hash__(self)\n\n        def __eq__(self, other):\n            return self is other\n\n        def __reduce__(self):\n            return self.__name__\n\n        def __init_subclass__(self, *args, **kwds):\n            if '_root' not in kwds:\n                raise TypeError(\"Cannot subclass special typing classes\")\n\n\nif hasattr(typing, \"reveal_type\"):\n    reveal_type = typing.reveal_type\nelse:\n    def reveal_type(__obj: T) -> T:\n        \"\"\"Reveal the inferred type of a variable.\n\n        When a static type checker encounters a call to ``reveal_type()``,\n        it will emit the inferred type of the argument::\n\n            x: int = 1\n            reveal_type(x)\n\n        Running a static type checker (e.g., ``mypy``) on this example\n        will produce output similar to 'Revealed type is \"builtins.int\"'.\n\n        At runtime, the function prints the runtime type of the\n        argument and returns it unchanged.\n\n        \"\"\"\n        print(f\"Runtime type is {type(__obj).__name__!r}\", file=sys.stderr)\n        return __obj\n\n\nif hasattr(typing, \"assert_never\"):\n    assert_never = typing.assert_never\nelse:\n    def assert_never(__arg: Never) -> Never:\n        \"\"\"Assert to the type checker that a line of code is unreachable.\n\n        Example::\n\n            def int_or_str(arg: int | str) -> None:\n                match arg:\n                    case int():\n                        print(\"It's an int\")\n                    case str():\n                        print(\"It's a str\")\n                    case _:\n                        assert_never(arg)\n\n        If a type checker finds that a call to assert_never() is\n        reachable, it will emit an error.\n\n        At runtime, this throws an exception when called.\n\n        \"\"\"\n        raise AssertionError(\"Expected code to be unreachable\")\n\n\nif hasattr(typing, 'dataclass_transform'):\n    dataclass_transform = typing.dataclass_transform\nelse:\n    def dataclass_transform(\n        *,\n        eq_default: bool = True,\n        order_default: bool = False,\n        kw_only_default: bool = False,\n        field_specifiers: typing.Tuple[\n            typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],\n            ...\n        ] = (),\n        **kwargs: typing.Any,\n    ) -> typing.Callable[[T], T]:\n        \"\"\"Decorator that marks a function, class, or metaclass as providing\n        dataclass-like behavior.\n\n        Example:\n\n            from pip._vendor.typing_extensions import dataclass_transform\n\n            _T = TypeVar(\"_T\")\n\n            # Used on a decorator function\n            @dataclass_transform()\n            def create_model(cls: type[_T]) -> type[_T]:\n                ...\n                return cls\n\n            @create_model\n            class CustomerModel:\n                id: int\n                name: str\n\n            # Used on a base class\n            @dataclass_transform()\n            class ModelBase: ...\n\n            class CustomerModel(ModelBase):\n                id: int\n                name: str\n\n            # Used on a metaclass\n            @dataclass_transform()\n            class ModelMeta(type): ...\n\n            class ModelBase(metaclass=ModelMeta): ...\n\n            class CustomerModel(ModelBase):\n                id: int\n                name: str\n\n        Each of the ``CustomerModel`` classes defined in this example will now\n        behave similarly to a dataclass created with the ``@dataclasses.dataclass``\n        decorator. For example, the type checker will synthesize an ``__init__``\n        method.\n\n        The arguments to this decorator can be used to customize this behavior:\n        - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be\n          True or False if it is omitted by the caller.\n        - ``order_default`` indicates whether the ``order`` parameter is\n          assumed to be True or False if it is omitted by the caller.\n        - ``kw_only_default`` indicates whether the ``kw_only`` parameter is\n          assumed to be True or False if it is omitted by the caller.\n        - ``field_specifiers`` specifies a static list of supported classes\n          or functions that describe fields, similar to ``dataclasses.field()``.\n\n        At runtime, this decorator records its arguments in the\n        ``__dataclass_transform__`` attribute on the decorated object.\n\n        See PEP 681 for details.\n\n        \"\"\"\n        def decorator(cls_or_fn):\n            cls_or_fn.__dataclass_transform__ = {\n                \"eq_default\": eq_default,\n                \"order_default\": order_default,\n                \"kw_only_default\": kw_only_default,\n                \"field_specifiers\": field_specifiers,\n                \"kwargs\": kwargs,\n            }\n            return cls_or_fn\n        return decorator\n\n\nif hasattr(typing, \"override\"):\n    override = typing.override\nelse:\n    _F = typing.TypeVar(\"_F\", bound=typing.Callable[..., typing.Any])\n\n    def override(__arg: _F) -> _F:\n        \"\"\"Indicate that a method is intended to override a method in a base class.\n\n        Usage:\n\n            class Base:\n                def method(self) -> None: ...\n                    pass\n\n            class Child(Base):\n                @override\n                def method(self) -> None:\n                    super().method()\n\n        When this decorator is applied to a method, the type checker will\n        validate that it overrides a method with the same name on a base class.\n        This helps prevent bugs that may occur when a base class is changed\n        without an equivalent change to a child class.\n\n        See PEP 698 for details.\n\n        \"\"\"\n        return __arg\n\n\n# We have to do some monkey patching to deal with the dual nature of\n# Unpack/TypeVarTuple:\n# - We want Unpack to be a kind of TypeVar so it gets accepted in\n#   Generic[Unpack[Ts]]\n# - We want it to *not* be treated as a TypeVar for the purposes of\n#   counting generic parameters, so that when we subscript a generic,\n#   the runtime doesn't try to substitute the Unpack with the subscripted type.\nif not hasattr(typing, \"TypeVarTuple\"):\n    typing._collect_type_vars = _collect_type_vars\n    typing._check_generic = _check_generic\n\n\n# Backport typing.NamedTuple as it exists in Python 3.11.\n# In 3.11, the ability to define generic `NamedTuple`s was supported.\n# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8.\nif sys.version_info >= (3, 11):\n    NamedTuple = typing.NamedTuple\nelse:\n    def _caller():\n        try:\n            return sys._getframe(2).f_globals.get('__name__', '__main__')\n        except (AttributeError, ValueError):  # For platforms without _getframe()\n            return None\n\n    def _make_nmtuple(name, types, module, defaults=()):\n        fields = [n for n, t in types]\n        annotations = {n: typing._type_check(t, f\"field {n} annotation must be a type\")\n                       for n, t in types}\n        nm_tpl = collections.namedtuple(name, fields,\n                                        defaults=defaults, module=module)\n        nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations\n        # The `_field_types` attribute was removed in 3.9;\n        # in earlier versions, it is the same as the `__annotations__` attribute\n        if sys.version_info < (3, 9):\n            nm_tpl._field_types = annotations\n        return nm_tpl\n\n    _prohibited_namedtuple_fields = typing._prohibited\n    _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})\n\n    class _NamedTupleMeta(type):\n        def __new__(cls, typename, bases, ns):\n            assert _NamedTuple in bases\n            for base in bases:\n                if base is not _NamedTuple and base is not typing.Generic:\n                    raise TypeError(\n                        'can only inherit from a NamedTuple type and Generic')\n            bases = tuple(tuple if base is _NamedTuple else base for base in bases)\n            types = ns.get('__annotations__', {})\n            default_names = []\n            for field_name in types:\n                if field_name in ns:\n                    default_names.append(field_name)\n                elif default_names:\n                    raise TypeError(f\"Non-default namedtuple field {field_name} \"\n                                    f\"cannot follow default field\"\n                                    f\"{'s' if len(default_names) > 1 else ''} \"\n                                    f\"{', '.join(default_names)}\")\n            nm_tpl = _make_nmtuple(\n                typename, types.items(),\n                defaults=[ns[n] for n in default_names],\n                module=ns['__module__']\n            )\n            nm_tpl.__bases__ = bases\n            if typing.Generic in bases:\n                class_getitem = typing.Generic.__class_getitem__.__func__\n                nm_tpl.__class_getitem__ = classmethod(class_getitem)\n            # update from user namespace without overriding special namedtuple attributes\n            for key in ns:\n                if key in _prohibited_namedtuple_fields:\n                    raise AttributeError(\"Cannot overwrite NamedTuple attribute \" + key)\n                elif key not in _special_namedtuple_fields and key not in nm_tpl._fields:\n                    setattr(nm_tpl, key, ns[key])\n            if typing.Generic in bases:\n                nm_tpl.__init_subclass__()\n            return nm_tpl\n\n    def NamedTuple(__typename, __fields=None, **kwargs):\n        if __fields is None:\n            __fields = kwargs.items()\n        elif kwargs:\n            raise TypeError(\"Either list of fields or keywords\"\n                            \" can be provided to NamedTuple, not both\")\n        return _make_nmtuple(__typename, __fields, module=_caller())\n\n    NamedTuple.__doc__ = typing.NamedTuple.__doc__\n    _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {})\n\n    # On 3.8+, alter the signature so that it matches typing.NamedTuple.\n    # The signature of typing.NamedTuple on >=3.8 is invalid syntax in Python 3.7,\n    # so just leave the signature as it is on 3.7.\n    if sys.version_info >= (3, 8):\n        NamedTuple.__text_signature__ = '(typename, fields=None, /, **kwargs)'\n\n    def _namedtuple_mro_entries(bases):\n        assert NamedTuple in bases\n        return (_NamedTuple,)\n\n    NamedTuple.__mro_entries__ = _namedtuple_mro_entries\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/__init__.py",
    "content": "\"\"\"\nPython HTTP library with thread-safe connection pooling, file post support, user friendly, and more\n\"\"\"\nfrom __future__ import absolute_import\n\n# Set default logging handler to avoid \"No handler found\" warnings.\nimport logging\nimport warnings\nfrom logging import NullHandler\n\nfrom . import exceptions\nfrom ._version import __version__\nfrom .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, connection_from_url\nfrom .filepost import encode_multipart_formdata\nfrom .poolmanager import PoolManager, ProxyManager, proxy_from_url\nfrom .response import HTTPResponse\nfrom .util.request import make_headers\nfrom .util.retry import Retry\nfrom .util.timeout import Timeout\nfrom .util.url import get_host\n\n# === NOTE TO REPACKAGERS AND VENDORS ===\n# Please delete this block, this logic is only\n# for urllib3 being distributed via PyPI.\n# See: https://github.com/urllib3/urllib3/issues/2680\ntry:\n    import urllib3_secure_extra  # type: ignore # noqa: F401\nexcept ImportError:\n    pass\nelse:\n    warnings.warn(\n        \"'urllib3[secure]' extra is deprecated and will be removed \"\n        \"in a future release of urllib3 2.x. Read more in this issue: \"\n        \"https://github.com/urllib3/urllib3/issues/2680\",\n        category=DeprecationWarning,\n        stacklevel=2,\n    )\n\n__author__ = \"Andrey Petrov (andrey.petrov@shazow.net)\"\n__license__ = \"MIT\"\n__version__ = __version__\n\n__all__ = (\n    \"HTTPConnectionPool\",\n    \"HTTPSConnectionPool\",\n    \"PoolManager\",\n    \"ProxyManager\",\n    \"HTTPResponse\",\n    \"Retry\",\n    \"Timeout\",\n    \"add_stderr_logger\",\n    \"connection_from_url\",\n    \"disable_warnings\",\n    \"encode_multipart_formdata\",\n    \"get_host\",\n    \"make_headers\",\n    \"proxy_from_url\",\n)\n\nlogging.getLogger(__name__).addHandler(NullHandler())\n\n\ndef add_stderr_logger(level=logging.DEBUG):\n    \"\"\"\n    Helper for quickly adding a StreamHandler to the logger. Useful for\n    debugging.\n\n    Returns the handler after adding it.\n    \"\"\"\n    # This method needs to be in this __init__.py to get the __name__ correct\n    # even if urllib3 is vendored within another package.\n    logger = logging.getLogger(__name__)\n    handler = logging.StreamHandler()\n    handler.setFormatter(logging.Formatter(\"%(asctime)s %(levelname)s %(message)s\"))\n    logger.addHandler(handler)\n    logger.setLevel(level)\n    logger.debug(\"Added a stderr logging handler to logger: %s\", __name__)\n    return handler\n\n\n# ... Clean up.\ndel NullHandler\n\n\n# All warning filters *must* be appended unless you're really certain that they\n# shouldn't be: otherwise, it's very hard for users to use most Python\n# mechanisms to silence them.\n# SecurityWarning's always go off by default.\nwarnings.simplefilter(\"always\", exceptions.SecurityWarning, append=True)\n# SubjectAltNameWarning's should go off once per host\nwarnings.simplefilter(\"default\", exceptions.SubjectAltNameWarning, append=True)\n# InsecurePlatformWarning's don't vary between requests, so we keep it default.\nwarnings.simplefilter(\"default\", exceptions.InsecurePlatformWarning, append=True)\n# SNIMissingWarnings should go off only once.\nwarnings.simplefilter(\"default\", exceptions.SNIMissingWarning, append=True)\n\n\ndef disable_warnings(category=exceptions.HTTPWarning):\n    \"\"\"\n    Helper for quickly disabling all urllib3 warnings.\n    \"\"\"\n    warnings.simplefilter(\"ignore\", category)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/_collections.py",
    "content": "from __future__ import absolute_import\n\ntry:\n    from collections.abc import Mapping, MutableMapping\nexcept ImportError:\n    from collections import Mapping, MutableMapping\ntry:\n    from threading import RLock\nexcept ImportError:  # Platform-specific: No threads available\n\n    class RLock:\n        def __enter__(self):\n            pass\n\n        def __exit__(self, exc_type, exc_value, traceback):\n            pass\n\n\nfrom collections import OrderedDict\n\nfrom .exceptions import InvalidHeader\nfrom .packages import six\nfrom .packages.six import iterkeys, itervalues\n\n__all__ = [\"RecentlyUsedContainer\", \"HTTPHeaderDict\"]\n\n\n_Null = object()\n\n\nclass RecentlyUsedContainer(MutableMapping):\n    \"\"\"\n    Provides a thread-safe dict-like container which maintains up to\n    ``maxsize`` keys while throwing away the least-recently-used keys beyond\n    ``maxsize``.\n\n    :param maxsize:\n        Maximum number of recent elements to retain.\n\n    :param dispose_func:\n        Every time an item is evicted from the container,\n        ``dispose_func(value)`` is called.  Callback which will get called\n    \"\"\"\n\n    ContainerCls = OrderedDict\n\n    def __init__(self, maxsize=10, dispose_func=None):\n        self._maxsize = maxsize\n        self.dispose_func = dispose_func\n\n        self._container = self.ContainerCls()\n        self.lock = RLock()\n\n    def __getitem__(self, key):\n        # Re-insert the item, moving it to the end of the eviction line.\n        with self.lock:\n            item = self._container.pop(key)\n            self._container[key] = item\n            return item\n\n    def __setitem__(self, key, value):\n        evicted_value = _Null\n        with self.lock:\n            # Possibly evict the existing value of 'key'\n            evicted_value = self._container.get(key, _Null)\n            self._container[key] = value\n\n            # If we didn't evict an existing value, we might have to evict the\n            # least recently used item from the beginning of the container.\n            if len(self._container) > self._maxsize:\n                _key, evicted_value = self._container.popitem(last=False)\n\n        if self.dispose_func and evicted_value is not _Null:\n            self.dispose_func(evicted_value)\n\n    def __delitem__(self, key):\n        with self.lock:\n            value = self._container.pop(key)\n\n        if self.dispose_func:\n            self.dispose_func(value)\n\n    def __len__(self):\n        with self.lock:\n            return len(self._container)\n\n    def __iter__(self):\n        raise NotImplementedError(\n            \"Iteration over this class is unlikely to be threadsafe.\"\n        )\n\n    def clear(self):\n        with self.lock:\n            # Copy pointers to all values, then wipe the mapping\n            values = list(itervalues(self._container))\n            self._container.clear()\n\n        if self.dispose_func:\n            for value in values:\n                self.dispose_func(value)\n\n    def keys(self):\n        with self.lock:\n            return list(iterkeys(self._container))\n\n\nclass HTTPHeaderDict(MutableMapping):\n    \"\"\"\n    :param headers:\n        An iterable of field-value pairs. Must not contain multiple field names\n        when compared case-insensitively.\n\n    :param kwargs:\n        Additional field-value pairs to pass in to ``dict.update``.\n\n    A ``dict`` like container for storing HTTP Headers.\n\n    Field names are stored and compared case-insensitively in compliance with\n    RFC 7230. Iteration provides the first case-sensitive key seen for each\n    case-insensitive pair.\n\n    Using ``__setitem__`` syntax overwrites fields that compare equal\n    case-insensitively in order to maintain ``dict``'s api. For fields that\n    compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``\n    in a loop.\n\n    If multiple fields that are equal case-insensitively are passed to the\n    constructor or ``.update``, the behavior is undefined and some will be\n    lost.\n\n    >>> headers = HTTPHeaderDict()\n    >>> headers.add('Set-Cookie', 'foo=bar')\n    >>> headers.add('set-cookie', 'baz=quxx')\n    >>> headers['content-length'] = '7'\n    >>> headers['SET-cookie']\n    'foo=bar, baz=quxx'\n    >>> headers['Content-Length']\n    '7'\n    \"\"\"\n\n    def __init__(self, headers=None, **kwargs):\n        super(HTTPHeaderDict, self).__init__()\n        self._container = OrderedDict()\n        if headers is not None:\n            if isinstance(headers, HTTPHeaderDict):\n                self._copy_from(headers)\n            else:\n                self.extend(headers)\n        if kwargs:\n            self.extend(kwargs)\n\n    def __setitem__(self, key, val):\n        self._container[key.lower()] = [key, val]\n        return self._container[key.lower()]\n\n    def __getitem__(self, key):\n        val = self._container[key.lower()]\n        return \", \".join(val[1:])\n\n    def __delitem__(self, key):\n        del self._container[key.lower()]\n\n    def __contains__(self, key):\n        return key.lower() in self._container\n\n    def __eq__(self, other):\n        if not isinstance(other, Mapping) and not hasattr(other, \"keys\"):\n            return False\n        if not isinstance(other, type(self)):\n            other = type(self)(other)\n        return dict((k.lower(), v) for k, v in self.itermerged()) == dict(\n            (k.lower(), v) for k, v in other.itermerged()\n        )\n\n    def __ne__(self, other):\n        return not self.__eq__(other)\n\n    if six.PY2:  # Python 2\n        iterkeys = MutableMapping.iterkeys\n        itervalues = MutableMapping.itervalues\n\n    __marker = object()\n\n    def __len__(self):\n        return len(self._container)\n\n    def __iter__(self):\n        # Only provide the originally cased names\n        for vals in self._container.values():\n            yield vals[0]\n\n    def pop(self, key, default=__marker):\n        \"\"\"D.pop(k[,d]) -> v, remove specified key and return the corresponding value.\n        If key is not found, d is returned if given, otherwise KeyError is raised.\n        \"\"\"\n        # Using the MutableMapping function directly fails due to the private marker.\n        # Using ordinary dict.pop would expose the internal structures.\n        # So let's reinvent the wheel.\n        try:\n            value = self[key]\n        except KeyError:\n            if default is self.__marker:\n                raise\n            return default\n        else:\n            del self[key]\n            return value\n\n    def discard(self, key):\n        try:\n            del self[key]\n        except KeyError:\n            pass\n\n    def add(self, key, val):\n        \"\"\"Adds a (name, value) pair, doesn't overwrite the value if it already\n        exists.\n\n        >>> headers = HTTPHeaderDict(foo='bar')\n        >>> headers.add('Foo', 'baz')\n        >>> headers['foo']\n        'bar, baz'\n        \"\"\"\n        key_lower = key.lower()\n        new_vals = [key, val]\n        # Keep the common case aka no item present as fast as possible\n        vals = self._container.setdefault(key_lower, new_vals)\n        if new_vals is not vals:\n            vals.append(val)\n\n    def extend(self, *args, **kwargs):\n        \"\"\"Generic import function for any type of header-like object.\n        Adapted version of MutableMapping.update in order to insert items\n        with self.add instead of self.__setitem__\n        \"\"\"\n        if len(args) > 1:\n            raise TypeError(\n                \"extend() takes at most 1 positional \"\n                \"arguments ({0} given)\".format(len(args))\n            )\n        other = args[0] if len(args) >= 1 else ()\n\n        if isinstance(other, HTTPHeaderDict):\n            for key, val in other.iteritems():\n                self.add(key, val)\n        elif isinstance(other, Mapping):\n            for key in other:\n                self.add(key, other[key])\n        elif hasattr(other, \"keys\"):\n            for key in other.keys():\n                self.add(key, other[key])\n        else:\n            for key, value in other:\n                self.add(key, value)\n\n        for key, value in kwargs.items():\n            self.add(key, value)\n\n    def getlist(self, key, default=__marker):\n        \"\"\"Returns a list of all the values for the named field. Returns an\n        empty list if the key doesn't exist.\"\"\"\n        try:\n            vals = self._container[key.lower()]\n        except KeyError:\n            if default is self.__marker:\n                return []\n            return default\n        else:\n            return vals[1:]\n\n    # Backwards compatibility for httplib\n    getheaders = getlist\n    getallmatchingheaders = getlist\n    iget = getlist\n\n    # Backwards compatibility for http.cookiejar\n    get_all = getlist\n\n    def __repr__(self):\n        return \"%s(%s)\" % (type(self).__name__, dict(self.itermerged()))\n\n    def _copy_from(self, other):\n        for key in other:\n            val = other.getlist(key)\n            if isinstance(val, list):\n                # Don't need to convert tuples\n                val = list(val)\n            self._container[key.lower()] = [key] + val\n\n    def copy(self):\n        clone = type(self)()\n        clone._copy_from(self)\n        return clone\n\n    def iteritems(self):\n        \"\"\"Iterate over all header lines, including duplicate ones.\"\"\"\n        for key in self:\n            vals = self._container[key.lower()]\n            for val in vals[1:]:\n                yield vals[0], val\n\n    def itermerged(self):\n        \"\"\"Iterate over all headers, merging duplicate ones together.\"\"\"\n        for key in self:\n            val = self._container[key.lower()]\n            yield val[0], \", \".join(val[1:])\n\n    def items(self):\n        return list(self.iteritems())\n\n    @classmethod\n    def from_httplib(cls, message):  # Python 2\n        \"\"\"Read headers from a Python 2 httplib message object.\"\"\"\n        # python2.7 does not expose a proper API for exporting multiheaders\n        # efficiently. This function re-reads raw lines from the message\n        # object and extracts the multiheaders properly.\n        obs_fold_continued_leaders = (\" \", \"\\t\")\n        headers = []\n\n        for line in message.headers:\n            if line.startswith(obs_fold_continued_leaders):\n                if not headers:\n                    # We received a header line that starts with OWS as described\n                    # in RFC-7230 S3.2.4. This indicates a multiline header, but\n                    # there exists no previous header to which we can attach it.\n                    raise InvalidHeader(\n                        \"Header continuation with no previous header: %s\" % line\n                    )\n                else:\n                    key, value = headers[-1]\n                    headers[-1] = (key, value + \" \" + line.strip())\n                    continue\n\n            key, value = line.split(\":\", 1)\n            headers.append((key, value.strip()))\n\n        return cls(headers)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/_version.py",
    "content": "# This file is protected via CODEOWNERS\n__version__ = \"1.26.12\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/connection.py",
    "content": "from __future__ import absolute_import\n\nimport datetime\nimport logging\nimport os\nimport re\nimport socket\nimport warnings\nfrom socket import error as SocketError\nfrom socket import timeout as SocketTimeout\n\nfrom .packages import six\nfrom .packages.six.moves.http_client import HTTPConnection as _HTTPConnection\nfrom .packages.six.moves.http_client import HTTPException  # noqa: F401\nfrom .util.proxy import create_proxy_ssl_context\n\ntry:  # Compiled with SSL?\n    import ssl\n\n    BaseSSLError = ssl.SSLError\nexcept (ImportError, AttributeError):  # Platform-specific: No SSL.\n    ssl = None\n\n    class BaseSSLError(BaseException):\n        pass\n\n\ntry:\n    # Python 3: not a no-op, we're adding this to the namespace so it can be imported.\n    ConnectionError = ConnectionError\nexcept NameError:\n    # Python 2\n    class ConnectionError(Exception):\n        pass\n\n\ntry:  # Python 3:\n    # Not a no-op, we're adding this to the namespace so it can be imported.\n    BrokenPipeError = BrokenPipeError\nexcept NameError:  # Python 2:\n\n    class BrokenPipeError(Exception):\n        pass\n\n\nfrom ._collections import HTTPHeaderDict  # noqa (historical, removed in v2)\nfrom ._version import __version__\nfrom .exceptions import (\n    ConnectTimeoutError,\n    NewConnectionError,\n    SubjectAltNameWarning,\n    SystemTimeWarning,\n)\nfrom .util import SKIP_HEADER, SKIPPABLE_HEADERS, connection\nfrom .util.ssl_ import (\n    assert_fingerprint,\n    create_urllib3_context,\n    is_ipaddress,\n    resolve_cert_reqs,\n    resolve_ssl_version,\n    ssl_wrap_socket,\n)\nfrom .util.ssl_match_hostname import CertificateError, match_hostname\n\nlog = logging.getLogger(__name__)\n\nport_by_scheme = {\"http\": 80, \"https\": 443}\n\n# When it comes time to update this value as a part of regular maintenance\n# (ie test_recent_date is failing) update it to ~6 months before the current date.\nRECENT_DATE = datetime.date(2022, 1, 1)\n\n_CONTAINS_CONTROL_CHAR_RE = re.compile(r\"[^-!#$%&'*+.^_`|~0-9a-zA-Z]\")\n\n\nclass HTTPConnection(_HTTPConnection, object):\n    \"\"\"\n    Based on :class:`http.client.HTTPConnection` but provides an extra constructor\n    backwards-compatibility layer between older and newer Pythons.\n\n    Additional keyword parameters are used to configure attributes of the connection.\n    Accepted parameters include:\n\n    - ``strict``: See the documentation on :class:`urllib3.connectionpool.HTTPConnectionPool`\n    - ``source_address``: Set the source address for the current connection.\n    - ``socket_options``: Set specific options on the underlying socket. If not specified, then\n      defaults are loaded from ``HTTPConnection.default_socket_options`` which includes disabling\n      Nagle's algorithm (sets TCP_NODELAY to 1) unless the connection is behind a proxy.\n\n      For example, if you wish to enable TCP Keep Alive in addition to the defaults,\n      you might pass:\n\n      .. code-block:: python\n\n         HTTPConnection.default_socket_options + [\n             (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),\n         ]\n\n      Or you may want to disable the defaults by passing an empty list (e.g., ``[]``).\n    \"\"\"\n\n    default_port = port_by_scheme[\"http\"]\n\n    #: Disable Nagle's algorithm by default.\n    #: ``[(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]``\n    default_socket_options = [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]\n\n    #: Whether this connection verifies the host's certificate.\n    is_verified = False\n\n    #: Whether this proxy connection (if used) verifies the proxy host's\n    #: certificate.\n    proxy_is_verified = None\n\n    def __init__(self, *args, **kw):\n        if not six.PY2:\n            kw.pop(\"strict\", None)\n\n        # Pre-set source_address.\n        self.source_address = kw.get(\"source_address\")\n\n        #: The socket options provided by the user. If no options are\n        #: provided, we use the default options.\n        self.socket_options = kw.pop(\"socket_options\", self.default_socket_options)\n\n        # Proxy options provided by the user.\n        self.proxy = kw.pop(\"proxy\", None)\n        self.proxy_config = kw.pop(\"proxy_config\", None)\n\n        _HTTPConnection.__init__(self, *args, **kw)\n\n    @property\n    def host(self):\n        \"\"\"\n        Getter method to remove any trailing dots that indicate the hostname is an FQDN.\n\n        In general, SSL certificates don't include the trailing dot indicating a\n        fully-qualified domain name, and thus, they don't validate properly when\n        checked against a domain name that includes the dot. In addition, some\n        servers may not expect to receive the trailing dot when provided.\n\n        However, the hostname with trailing dot is critical to DNS resolution; doing a\n        lookup with the trailing dot will properly only resolve the appropriate FQDN,\n        whereas a lookup without a trailing dot will search the system's search domain\n        list. Thus, it's important to keep the original host around for use only in\n        those cases where it's appropriate (i.e., when doing DNS lookup to establish the\n        actual TCP connection across which we're going to send HTTP requests).\n        \"\"\"\n        return self._dns_host.rstrip(\".\")\n\n    @host.setter\n    def host(self, value):\n        \"\"\"\n        Setter for the `host` property.\n\n        We assume that only urllib3 uses the _dns_host attribute; httplib itself\n        only uses `host`, and it seems reasonable that other libraries follow suit.\n        \"\"\"\n        self._dns_host = value\n\n    def _new_conn(self):\n        \"\"\"Establish a socket connection and set nodelay settings on it.\n\n        :return: New socket connection.\n        \"\"\"\n        extra_kw = {}\n        if self.source_address:\n            extra_kw[\"source_address\"] = self.source_address\n\n        if self.socket_options:\n            extra_kw[\"socket_options\"] = self.socket_options\n\n        try:\n            conn = connection.create_connection(\n                (self._dns_host, self.port), self.timeout, **extra_kw\n            )\n\n        except SocketTimeout:\n            raise ConnectTimeoutError(\n                self,\n                \"Connection to %s timed out. (connect timeout=%s)\"\n                % (self.host, self.timeout),\n            )\n\n        except SocketError as e:\n            raise NewConnectionError(\n                self, \"Failed to establish a new connection: %s\" % e\n            )\n\n        return conn\n\n    def _is_using_tunnel(self):\n        # Google App Engine's httplib does not define _tunnel_host\n        return getattr(self, \"_tunnel_host\", None)\n\n    def _prepare_conn(self, conn):\n        self.sock = conn\n        if self._is_using_tunnel():\n            # TODO: Fix tunnel so it doesn't depend on self.sock state.\n            self._tunnel()\n            # Mark this connection as not reusable\n            self.auto_open = 0\n\n    def connect(self):\n        conn = self._new_conn()\n        self._prepare_conn(conn)\n\n    def putrequest(self, method, url, *args, **kwargs):\n        \"\"\" \"\"\"\n        # Empty docstring because the indentation of CPython's implementation\n        # is broken but we don't want this method in our documentation.\n        match = _CONTAINS_CONTROL_CHAR_RE.search(method)\n        if match:\n            raise ValueError(\n                \"Method cannot contain non-token characters %r (found at least %r)\"\n                % (method, match.group())\n            )\n\n        return _HTTPConnection.putrequest(self, method, url, *args, **kwargs)\n\n    def putheader(self, header, *values):\n        \"\"\" \"\"\"\n        if not any(isinstance(v, str) and v == SKIP_HEADER for v in values):\n            _HTTPConnection.putheader(self, header, *values)\n        elif six.ensure_str(header.lower()) not in SKIPPABLE_HEADERS:\n            raise ValueError(\n                \"urllib3.util.SKIP_HEADER only supports '%s'\"\n                % (\"', '\".join(map(str.title, sorted(SKIPPABLE_HEADERS))),)\n            )\n\n    def request(self, method, url, body=None, headers=None):\n        if headers is None:\n            headers = {}\n        else:\n            # Avoid modifying the headers passed into .request()\n            headers = headers.copy()\n        if \"user-agent\" not in (six.ensure_str(k.lower()) for k in headers):\n            headers[\"User-Agent\"] = _get_default_user_agent()\n        super(HTTPConnection, self).request(method, url, body=body, headers=headers)\n\n    def request_chunked(self, method, url, body=None, headers=None):\n        \"\"\"\n        Alternative to the common request method, which sends the\n        body with chunked encoding and not as one block\n        \"\"\"\n        headers = headers or {}\n        header_keys = set([six.ensure_str(k.lower()) for k in headers])\n        skip_accept_encoding = \"accept-encoding\" in header_keys\n        skip_host = \"host\" in header_keys\n        self.putrequest(\n            method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host\n        )\n        if \"user-agent\" not in header_keys:\n            self.putheader(\"User-Agent\", _get_default_user_agent())\n        for header, value in headers.items():\n            self.putheader(header, value)\n        if \"transfer-encoding\" not in header_keys:\n            self.putheader(\"Transfer-Encoding\", \"chunked\")\n        self.endheaders()\n\n        if body is not None:\n            stringish_types = six.string_types + (bytes,)\n            if isinstance(body, stringish_types):\n                body = (body,)\n            for chunk in body:\n                if not chunk:\n                    continue\n                if not isinstance(chunk, bytes):\n                    chunk = chunk.encode(\"utf8\")\n                len_str = hex(len(chunk))[2:]\n                to_send = bytearray(len_str.encode())\n                to_send += b\"\\r\\n\"\n                to_send += chunk\n                to_send += b\"\\r\\n\"\n                self.send(to_send)\n\n        # After the if clause, to always have a closed body\n        self.send(b\"0\\r\\n\\r\\n\")\n\n\nclass HTTPSConnection(HTTPConnection):\n    \"\"\"\n    Many of the parameters to this constructor are passed to the underlying SSL\n    socket by means of :py:func:`urllib3.util.ssl_wrap_socket`.\n    \"\"\"\n\n    default_port = port_by_scheme[\"https\"]\n\n    cert_reqs = None\n    ca_certs = None\n    ca_cert_dir = None\n    ca_cert_data = None\n    ssl_version = None\n    assert_fingerprint = None\n    tls_in_tls_required = False\n\n    def __init__(\n        self,\n        host,\n        port=None,\n        key_file=None,\n        cert_file=None,\n        key_password=None,\n        strict=None,\n        timeout=socket._GLOBAL_DEFAULT_TIMEOUT,\n        ssl_context=None,\n        server_hostname=None,\n        **kw\n    ):\n\n        HTTPConnection.__init__(self, host, port, strict=strict, timeout=timeout, **kw)\n\n        self.key_file = key_file\n        self.cert_file = cert_file\n        self.key_password = key_password\n        self.ssl_context = ssl_context\n        self.server_hostname = server_hostname\n\n        # Required property for Google AppEngine 1.9.0 which otherwise causes\n        # HTTPS requests to go out as HTTP. (See Issue #356)\n        self._protocol = \"https\"\n\n    def set_cert(\n        self,\n        key_file=None,\n        cert_file=None,\n        cert_reqs=None,\n        key_password=None,\n        ca_certs=None,\n        assert_hostname=None,\n        assert_fingerprint=None,\n        ca_cert_dir=None,\n        ca_cert_data=None,\n    ):\n        \"\"\"\n        This method should only be called once, before the connection is used.\n        \"\"\"\n        # If cert_reqs is not provided we'll assume CERT_REQUIRED unless we also\n        # have an SSLContext object in which case we'll use its verify_mode.\n        if cert_reqs is None:\n            if self.ssl_context is not None:\n                cert_reqs = self.ssl_context.verify_mode\n            else:\n                cert_reqs = resolve_cert_reqs(None)\n\n        self.key_file = key_file\n        self.cert_file = cert_file\n        self.cert_reqs = cert_reqs\n        self.key_password = key_password\n        self.assert_hostname = assert_hostname\n        self.assert_fingerprint = assert_fingerprint\n        self.ca_certs = ca_certs and os.path.expanduser(ca_certs)\n        self.ca_cert_dir = ca_cert_dir and os.path.expanduser(ca_cert_dir)\n        self.ca_cert_data = ca_cert_data\n\n    def connect(self):\n        # Add certificate verification\n        self.sock = conn = self._new_conn()\n        hostname = self.host\n        tls_in_tls = False\n\n        if self._is_using_tunnel():\n            if self.tls_in_tls_required:\n                self.sock = conn = self._connect_tls_proxy(hostname, conn)\n                tls_in_tls = True\n\n            # Calls self._set_hostport(), so self.host is\n            # self._tunnel_host below.\n            self._tunnel()\n            # Mark this connection as not reusable\n            self.auto_open = 0\n\n            # Override the host with the one we're requesting data from.\n            hostname = self._tunnel_host\n\n        server_hostname = hostname\n        if self.server_hostname is not None:\n            server_hostname = self.server_hostname\n\n        is_time_off = datetime.date.today() < RECENT_DATE\n        if is_time_off:\n            warnings.warn(\n                (\n                    \"System time is way off (before {0}). This will probably \"\n                    \"lead to SSL verification errors\"\n                ).format(RECENT_DATE),\n                SystemTimeWarning,\n            )\n\n        # Wrap socket using verification with the root certs in\n        # trusted_root_certs\n        default_ssl_context = False\n        if self.ssl_context is None:\n            default_ssl_context = True\n            self.ssl_context = create_urllib3_context(\n                ssl_version=resolve_ssl_version(self.ssl_version),\n                cert_reqs=resolve_cert_reqs(self.cert_reqs),\n            )\n\n        context = self.ssl_context\n        context.verify_mode = resolve_cert_reqs(self.cert_reqs)\n\n        # Try to load OS default certs if none are given.\n        # Works well on Windows (requires Python3.4+)\n        if (\n            not self.ca_certs\n            and not self.ca_cert_dir\n            and not self.ca_cert_data\n            and default_ssl_context\n            and hasattr(context, \"load_default_certs\")\n        ):\n            context.load_default_certs()\n\n        self.sock = ssl_wrap_socket(\n            sock=conn,\n            keyfile=self.key_file,\n            certfile=self.cert_file,\n            key_password=self.key_password,\n            ca_certs=self.ca_certs,\n            ca_cert_dir=self.ca_cert_dir,\n            ca_cert_data=self.ca_cert_data,\n            server_hostname=server_hostname,\n            ssl_context=context,\n            tls_in_tls=tls_in_tls,\n        )\n\n        # If we're using all defaults and the connection\n        # is TLSv1 or TLSv1.1 we throw a DeprecationWarning\n        # for the host.\n        if (\n            default_ssl_context\n            and self.ssl_version is None\n            and hasattr(self.sock, \"version\")\n            and self.sock.version() in {\"TLSv1\", \"TLSv1.1\"}\n        ):\n            warnings.warn(\n                \"Negotiating TLSv1/TLSv1.1 by default is deprecated \"\n                \"and will be disabled in urllib3 v2.0.0. Connecting to \"\n                \"'%s' with '%s' can be enabled by explicitly opting-in \"\n                \"with 'ssl_version'\" % (self.host, self.sock.version()),\n                DeprecationWarning,\n            )\n\n        if self.assert_fingerprint:\n            assert_fingerprint(\n                self.sock.getpeercert(binary_form=True), self.assert_fingerprint\n            )\n        elif (\n            context.verify_mode != ssl.CERT_NONE\n            and not getattr(context, \"check_hostname\", False)\n            and self.assert_hostname is not False\n        ):\n            # While urllib3 attempts to always turn off hostname matching from\n            # the TLS library, this cannot always be done. So we check whether\n            # the TLS Library still thinks it's matching hostnames.\n            cert = self.sock.getpeercert()\n            if not cert.get(\"subjectAltName\", ()):\n                warnings.warn(\n                    (\n                        \"Certificate for {0} has no `subjectAltName`, falling back to check for a \"\n                        \"`commonName` for now. This feature is being removed by major browsers and \"\n                        \"deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 \"\n                        \"for details.)\".format(hostname)\n                    ),\n                    SubjectAltNameWarning,\n                )\n            _match_hostname(cert, self.assert_hostname or server_hostname)\n\n        self.is_verified = (\n            context.verify_mode == ssl.CERT_REQUIRED\n            or self.assert_fingerprint is not None\n        )\n\n    def _connect_tls_proxy(self, hostname, conn):\n        \"\"\"\n        Establish a TLS connection to the proxy using the provided SSL context.\n        \"\"\"\n        proxy_config = self.proxy_config\n        ssl_context = proxy_config.ssl_context\n        if ssl_context:\n            # If the user provided a proxy context, we assume CA and client\n            # certificates have already been set\n            return ssl_wrap_socket(\n                sock=conn,\n                server_hostname=hostname,\n                ssl_context=ssl_context,\n            )\n\n        ssl_context = create_proxy_ssl_context(\n            self.ssl_version,\n            self.cert_reqs,\n            self.ca_certs,\n            self.ca_cert_dir,\n            self.ca_cert_data,\n        )\n\n        # If no cert was provided, use only the default options for server\n        # certificate validation\n        socket = ssl_wrap_socket(\n            sock=conn,\n            ca_certs=self.ca_certs,\n            ca_cert_dir=self.ca_cert_dir,\n            ca_cert_data=self.ca_cert_data,\n            server_hostname=hostname,\n            ssl_context=ssl_context,\n        )\n\n        if ssl_context.verify_mode != ssl.CERT_NONE and not getattr(\n            ssl_context, \"check_hostname\", False\n        ):\n            # While urllib3 attempts to always turn off hostname matching from\n            # the TLS library, this cannot always be done. So we check whether\n            # the TLS Library still thinks it's matching hostnames.\n            cert = socket.getpeercert()\n            if not cert.get(\"subjectAltName\", ()):\n                warnings.warn(\n                    (\n                        \"Certificate for {0} has no `subjectAltName`, falling back to check for a \"\n                        \"`commonName` for now. This feature is being removed by major browsers and \"\n                        \"deprecated by RFC 2818. (See https://github.com/urllib3/urllib3/issues/497 \"\n                        \"for details.)\".format(hostname)\n                    ),\n                    SubjectAltNameWarning,\n                )\n            _match_hostname(cert, hostname)\n\n        self.proxy_is_verified = ssl_context.verify_mode == ssl.CERT_REQUIRED\n        return socket\n\n\ndef _match_hostname(cert, asserted_hostname):\n    # Our upstream implementation of ssl.match_hostname()\n    # only applies this normalization to IP addresses so it doesn't\n    # match DNS SANs so we do the same thing!\n    stripped_hostname = asserted_hostname.strip(\"u[]\")\n    if is_ipaddress(stripped_hostname):\n        asserted_hostname = stripped_hostname\n\n    try:\n        match_hostname(cert, asserted_hostname)\n    except CertificateError as e:\n        log.warning(\n            \"Certificate did not match expected hostname: %s. Certificate: %s\",\n            asserted_hostname,\n            cert,\n        )\n        # Add cert to exception and reraise so client code can inspect\n        # the cert when catching the exception, if they want to\n        e._peer_cert = cert\n        raise\n\n\ndef _get_default_user_agent():\n    return \"python-urllib3/%s\" % __version__\n\n\nclass DummyConnection(object):\n    \"\"\"Used to detect a failed ConnectionCls import.\"\"\"\n\n    pass\n\n\nif not ssl:\n    HTTPSConnection = DummyConnection  # noqa: F811\n\n\nVerifiedHTTPSConnection = HTTPSConnection\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/connectionpool.py",
    "content": "from __future__ import absolute_import\n\nimport errno\nimport logging\nimport re\nimport socket\nimport sys\nimport warnings\nfrom socket import error as SocketError\nfrom socket import timeout as SocketTimeout\n\nfrom .connection import (\n    BaseSSLError,\n    BrokenPipeError,\n    DummyConnection,\n    HTTPConnection,\n    HTTPException,\n    HTTPSConnection,\n    VerifiedHTTPSConnection,\n    port_by_scheme,\n)\nfrom .exceptions import (\n    ClosedPoolError,\n    EmptyPoolError,\n    HeaderParsingError,\n    HostChangedError,\n    InsecureRequestWarning,\n    LocationValueError,\n    MaxRetryError,\n    NewConnectionError,\n    ProtocolError,\n    ProxyError,\n    ReadTimeoutError,\n    SSLError,\n    TimeoutError,\n)\nfrom .packages import six\nfrom .packages.six.moves import queue\nfrom .request import RequestMethods\nfrom .response import HTTPResponse\nfrom .util.connection import is_connection_dropped\nfrom .util.proxy import connection_requires_http_tunnel\nfrom .util.queue import LifoQueue\nfrom .util.request import set_file_position\nfrom .util.response import assert_header_parsing\nfrom .util.retry import Retry\nfrom .util.ssl_match_hostname import CertificateError\nfrom .util.timeout import Timeout\nfrom .util.url import Url, _encode_target\nfrom .util.url import _normalize_host as normalize_host\nfrom .util.url import get_host, parse_url\n\nxrange = six.moves.xrange\n\nlog = logging.getLogger(__name__)\n\n_Default = object()\n\n\n# Pool objects\nclass ConnectionPool(object):\n    \"\"\"\n    Base class for all connection pools, such as\n    :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.\n\n    .. note::\n       ConnectionPool.urlopen() does not normalize or percent-encode target URIs\n       which is useful if your target server doesn't support percent-encoded\n       target URIs.\n    \"\"\"\n\n    scheme = None\n    QueueCls = LifoQueue\n\n    def __init__(self, host, port=None):\n        if not host:\n            raise LocationValueError(\"No host specified.\")\n\n        self.host = _normalize_host(host, scheme=self.scheme)\n        self._proxy_host = host.lower()\n        self.port = port\n\n    def __str__(self):\n        return \"%s(host=%r, port=%r)\" % (type(self).__name__, self.host, self.port)\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        self.close()\n        # Return False to re-raise any potential exceptions\n        return False\n\n    def close(self):\n        \"\"\"\n        Close all pooled connections and disable the pool.\n        \"\"\"\n        pass\n\n\n# This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252\n_blocking_errnos = {errno.EAGAIN, errno.EWOULDBLOCK}\n\n\nclass HTTPConnectionPool(ConnectionPool, RequestMethods):\n    \"\"\"\n    Thread-safe connection pool for one host.\n\n    :param host:\n        Host used for this HTTP Connection (e.g. \"localhost\"), passed into\n        :class:`http.client.HTTPConnection`.\n\n    :param port:\n        Port used for this HTTP Connection (None is equivalent to 80), passed\n        into :class:`http.client.HTTPConnection`.\n\n    :param strict:\n        Causes BadStatusLine to be raised if the status line can't be parsed\n        as a valid HTTP/1.0 or 1.1 status line, passed into\n        :class:`http.client.HTTPConnection`.\n\n        .. note::\n           Only works in Python 2. This parameter is ignored in Python 3.\n\n    :param timeout:\n        Socket timeout in seconds for each individual connection. This can\n        be a float or integer, which sets the timeout for the HTTP request,\n        or an instance of :class:`urllib3.util.Timeout` which gives you more\n        fine-grained control over request timeouts. After the constructor has\n        been parsed, this is always a `urllib3.util.Timeout` object.\n\n    :param maxsize:\n        Number of connections to save that can be reused. More than 1 is useful\n        in multithreaded situations. If ``block`` is set to False, more\n        connections will be created but they will not be saved once they've\n        been used.\n\n    :param block:\n        If set to True, no more than ``maxsize`` connections will be used at\n        a time. When no free connections are available, the call will block\n        until a connection has been released. This is a useful side effect for\n        particular multithreaded situations where one does not want to use more\n        than maxsize connections per host to prevent flooding.\n\n    :param headers:\n        Headers to include with all requests, unless other headers are given\n        explicitly.\n\n    :param retries:\n        Retry configuration to use by default with requests in this pool.\n\n    :param _proxy:\n        Parsed proxy URL, should not be used directly, instead, see\n        :class:`urllib3.ProxyManager`\n\n    :param _proxy_headers:\n        A dictionary with proxy headers, should not be used directly,\n        instead, see :class:`urllib3.ProxyManager`\n\n    :param \\\\**conn_kw:\n        Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,\n        :class:`urllib3.connection.HTTPSConnection` instances.\n    \"\"\"\n\n    scheme = \"http\"\n    ConnectionCls = HTTPConnection\n    ResponseCls = HTTPResponse\n\n    def __init__(\n        self,\n        host,\n        port=None,\n        strict=False,\n        timeout=Timeout.DEFAULT_TIMEOUT,\n        maxsize=1,\n        block=False,\n        headers=None,\n        retries=None,\n        _proxy=None,\n        _proxy_headers=None,\n        _proxy_config=None,\n        **conn_kw\n    ):\n        ConnectionPool.__init__(self, host, port)\n        RequestMethods.__init__(self, headers)\n\n        self.strict = strict\n\n        if not isinstance(timeout, Timeout):\n            timeout = Timeout.from_float(timeout)\n\n        if retries is None:\n            retries = Retry.DEFAULT\n\n        self.timeout = timeout\n        self.retries = retries\n\n        self.pool = self.QueueCls(maxsize)\n        self.block = block\n\n        self.proxy = _proxy\n        self.proxy_headers = _proxy_headers or {}\n        self.proxy_config = _proxy_config\n\n        # Fill the queue up so that doing get() on it will block properly\n        for _ in xrange(maxsize):\n            self.pool.put(None)\n\n        # These are mostly for testing and debugging purposes.\n        self.num_connections = 0\n        self.num_requests = 0\n        self.conn_kw = conn_kw\n\n        if self.proxy:\n            # Enable Nagle's algorithm for proxies, to avoid packet fragmentation.\n            # We cannot know if the user has added default socket options, so we cannot replace the\n            # list.\n            self.conn_kw.setdefault(\"socket_options\", [])\n\n            self.conn_kw[\"proxy\"] = self.proxy\n            self.conn_kw[\"proxy_config\"] = self.proxy_config\n\n    def _new_conn(self):\n        \"\"\"\n        Return a fresh :class:`HTTPConnection`.\n        \"\"\"\n        self.num_connections += 1\n        log.debug(\n            \"Starting new HTTP connection (%d): %s:%s\",\n            self.num_connections,\n            self.host,\n            self.port or \"80\",\n        )\n\n        conn = self.ConnectionCls(\n            host=self.host,\n            port=self.port,\n            timeout=self.timeout.connect_timeout,\n            strict=self.strict,\n            **self.conn_kw\n        )\n        return conn\n\n    def _get_conn(self, timeout=None):\n        \"\"\"\n        Get a connection. Will return a pooled connection if one is available.\n\n        If no connections are available and :prop:`.block` is ``False``, then a\n        fresh connection is returned.\n\n        :param timeout:\n            Seconds to wait before giving up and raising\n            :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and\n            :prop:`.block` is ``True``.\n        \"\"\"\n        conn = None\n        try:\n            conn = self.pool.get(block=self.block, timeout=timeout)\n\n        except AttributeError:  # self.pool is None\n            raise ClosedPoolError(self, \"Pool is closed.\")\n\n        except queue.Empty:\n            if self.block:\n                raise EmptyPoolError(\n                    self,\n                    \"Pool reached maximum size and no more connections are allowed.\",\n                )\n            pass  # Oh well, we'll create a new connection then\n\n        # If this is a persistent connection, check if it got disconnected\n        if conn and is_connection_dropped(conn):\n            log.debug(\"Resetting dropped connection: %s\", self.host)\n            conn.close()\n            if getattr(conn, \"auto_open\", 1) == 0:\n                # This is a proxied connection that has been mutated by\n                # http.client._tunnel() and cannot be reused (since it would\n                # attempt to bypass the proxy)\n                conn = None\n\n        return conn or self._new_conn()\n\n    def _put_conn(self, conn):\n        \"\"\"\n        Put a connection back into the pool.\n\n        :param conn:\n            Connection object for the current host and port as returned by\n            :meth:`._new_conn` or :meth:`._get_conn`.\n\n        If the pool is already full, the connection is closed and discarded\n        because we exceeded maxsize. If connections are discarded frequently,\n        then maxsize should be increased.\n\n        If the pool is closed, then the connection will be closed and discarded.\n        \"\"\"\n        try:\n            self.pool.put(conn, block=False)\n            return  # Everything is dandy, done.\n        except AttributeError:\n            # self.pool is None.\n            pass\n        except queue.Full:\n            # This should never happen if self.block == True\n            log.warning(\n                \"Connection pool is full, discarding connection: %s. Connection pool size: %s\",\n                self.host,\n                self.pool.qsize(),\n            )\n        # Connection never got put back into the pool, close it.\n        if conn:\n            conn.close()\n\n    def _validate_conn(self, conn):\n        \"\"\"\n        Called right before a request is made, after the socket is created.\n        \"\"\"\n        pass\n\n    def _prepare_proxy(self, conn):\n        # Nothing to do for HTTP connections.\n        pass\n\n    def _get_timeout(self, timeout):\n        \"\"\"Helper that always returns a :class:`urllib3.util.Timeout`\"\"\"\n        if timeout is _Default:\n            return self.timeout.clone()\n\n        if isinstance(timeout, Timeout):\n            return timeout.clone()\n        else:\n            # User passed us an int/float. This is for backwards compatibility,\n            # can be removed later\n            return Timeout.from_float(timeout)\n\n    def _raise_timeout(self, err, url, timeout_value):\n        \"\"\"Is the error actually a timeout? Will raise a ReadTimeout or pass\"\"\"\n\n        if isinstance(err, SocketTimeout):\n            raise ReadTimeoutError(\n                self, url, \"Read timed out. (read timeout=%s)\" % timeout_value\n            )\n\n        # See the above comment about EAGAIN in Python 3. In Python 2 we have\n        # to specifically catch it and throw the timeout error\n        if hasattr(err, \"errno\") and err.errno in _blocking_errnos:\n            raise ReadTimeoutError(\n                self, url, \"Read timed out. (read timeout=%s)\" % timeout_value\n            )\n\n        # Catch possible read timeouts thrown as SSL errors. If not the\n        # case, rethrow the original. We need to do this because of:\n        # http://bugs.python.org/issue10272\n        if \"timed out\" in str(err) or \"did not complete (read)\" in str(\n            err\n        ):  # Python < 2.7.4\n            raise ReadTimeoutError(\n                self, url, \"Read timed out. (read timeout=%s)\" % timeout_value\n            )\n\n    def _make_request(\n        self, conn, method, url, timeout=_Default, chunked=False, **httplib_request_kw\n    ):\n        \"\"\"\n        Perform a request on a given urllib connection object taken from our\n        pool.\n\n        :param conn:\n            a connection from one of our connection pools\n\n        :param timeout:\n            Socket timeout in seconds for the request. This can be a\n            float or integer, which will set the same timeout value for\n            the socket connect and the socket read, or an instance of\n            :class:`urllib3.util.Timeout`, which gives you more fine-grained\n            control over your timeouts.\n        \"\"\"\n        self.num_requests += 1\n\n        timeout_obj = self._get_timeout(timeout)\n        timeout_obj.start_connect()\n        conn.timeout = timeout_obj.connect_timeout\n\n        # Trigger any extra validation we need to do.\n        try:\n            self._validate_conn(conn)\n        except (SocketTimeout, BaseSSLError) as e:\n            # Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.\n            self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)\n            raise\n\n        # conn.request() calls http.client.*.request, not the method in\n        # urllib3.request. It also calls makefile (recv) on the socket.\n        try:\n            if chunked:\n                conn.request_chunked(method, url, **httplib_request_kw)\n            else:\n                conn.request(method, url, **httplib_request_kw)\n\n        # We are swallowing BrokenPipeError (errno.EPIPE) since the server is\n        # legitimately able to close the connection after sending a valid response.\n        # With this behaviour, the received response is still readable.\n        except BrokenPipeError:\n            # Python 3\n            pass\n        except IOError as e:\n            # Python 2 and macOS/Linux\n            # EPIPE and ESHUTDOWN are BrokenPipeError on Python 2, and EPROTOTYPE is needed on macOS\n            # https://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/\n            if e.errno not in {\n                errno.EPIPE,\n                errno.ESHUTDOWN,\n                errno.EPROTOTYPE,\n            }:\n                raise\n\n        # Reset the timeout for the recv() on the socket\n        read_timeout = timeout_obj.read_timeout\n\n        # App Engine doesn't have a sock attr\n        if getattr(conn, \"sock\", None):\n            # In Python 3 socket.py will catch EAGAIN and return None when you\n            # try and read into the file pointer created by http.client, which\n            # instead raises a BadStatusLine exception. Instead of catching\n            # the exception and assuming all BadStatusLine exceptions are read\n            # timeouts, check for a zero timeout before making the request.\n            if read_timeout == 0:\n                raise ReadTimeoutError(\n                    self, url, \"Read timed out. (read timeout=%s)\" % read_timeout\n                )\n            if read_timeout is Timeout.DEFAULT_TIMEOUT:\n                conn.sock.settimeout(socket.getdefaulttimeout())\n            else:  # None or a value\n                conn.sock.settimeout(read_timeout)\n\n        # Receive the response from the server\n        try:\n            try:\n                # Python 2.7, use buffering of HTTP responses\n                httplib_response = conn.getresponse(buffering=True)\n            except TypeError:\n                # Python 3\n                try:\n                    httplib_response = conn.getresponse()\n                except BaseException as e:\n                    # Remove the TypeError from the exception chain in\n                    # Python 3 (including for exceptions like SystemExit).\n                    # Otherwise it looks like a bug in the code.\n                    six.raise_from(e, None)\n        except (SocketTimeout, BaseSSLError, SocketError) as e:\n            self._raise_timeout(err=e, url=url, timeout_value=read_timeout)\n            raise\n\n        # AppEngine doesn't have a version attr.\n        http_version = getattr(conn, \"_http_vsn_str\", \"HTTP/?\")\n        log.debug(\n            '%s://%s:%s \"%s %s %s\" %s %s',\n            self.scheme,\n            self.host,\n            self.port,\n            method,\n            url,\n            http_version,\n            httplib_response.status,\n            httplib_response.length,\n        )\n\n        try:\n            assert_header_parsing(httplib_response.msg)\n        except (HeaderParsingError, TypeError) as hpe:  # Platform-specific: Python 3\n            log.warning(\n                \"Failed to parse headers (url=%s): %s\",\n                self._absolute_url(url),\n                hpe,\n                exc_info=True,\n            )\n\n        return httplib_response\n\n    def _absolute_url(self, path):\n        return Url(scheme=self.scheme, host=self.host, port=self.port, path=path).url\n\n    def close(self):\n        \"\"\"\n        Close all pooled connections and disable the pool.\n        \"\"\"\n        if self.pool is None:\n            return\n        # Disable access to the pool\n        old_pool, self.pool = self.pool, None\n\n        try:\n            while True:\n                conn = old_pool.get(block=False)\n                if conn:\n                    conn.close()\n\n        except queue.Empty:\n            pass  # Done.\n\n    def is_same_host(self, url):\n        \"\"\"\n        Check if the given ``url`` is a member of the same host as this\n        connection pool.\n        \"\"\"\n        if url.startswith(\"/\"):\n            return True\n\n        # TODO: Add optional support for socket.gethostbyname checking.\n        scheme, host, port = get_host(url)\n        if host is not None:\n            host = _normalize_host(host, scheme=scheme)\n\n        # Use explicit default port for comparison when none is given\n        if self.port and not port:\n            port = port_by_scheme.get(scheme)\n        elif not self.port and port == port_by_scheme.get(scheme):\n            port = None\n\n        return (scheme, host, port) == (self.scheme, self.host, self.port)\n\n    def urlopen(\n        self,\n        method,\n        url,\n        body=None,\n        headers=None,\n        retries=None,\n        redirect=True,\n        assert_same_host=True,\n        timeout=_Default,\n        pool_timeout=None,\n        release_conn=None,\n        chunked=False,\n        body_pos=None,\n        **response_kw\n    ):\n        \"\"\"\n        Get a connection from the pool and perform an HTTP request. This is the\n        lowest level call for making a request, so you'll need to specify all\n        the raw details.\n\n        .. note::\n\n           More commonly, it's appropriate to use a convenience method provided\n           by :class:`.RequestMethods`, such as :meth:`request`.\n\n        .. note::\n\n           `release_conn` will only behave as expected if\n           `preload_content=False` because we want to make\n           `preload_content=False` the default behaviour someday soon without\n           breaking backwards compatibility.\n\n        :param method:\n            HTTP request method (such as GET, POST, PUT, etc.)\n\n        :param url:\n            The URL to perform the request on.\n\n        :param body:\n            Data to send in the request body, either :class:`str`, :class:`bytes`,\n            an iterable of :class:`str`/:class:`bytes`, or a file-like object.\n\n        :param headers:\n            Dictionary of custom headers to send, such as User-Agent,\n            If-None-Match, etc. If None, pool headers are used. If provided,\n            these headers completely replace any pool-specific headers.\n\n        :param retries:\n            Configure the number of retries to allow before raising a\n            :class:`~urllib3.exceptions.MaxRetryError` exception.\n\n            Pass ``None`` to retry until you receive a response. Pass a\n            :class:`~urllib3.util.retry.Retry` object for fine-grained control\n            over different types of retries.\n            Pass an integer number to retry connection errors that many times,\n            but no other types of errors. Pass zero to never retry.\n\n            If ``False``, then retries are disabled and any exception is raised\n            immediately. Also, instead of raising a MaxRetryError on redirects,\n            the redirect response will be returned.\n\n        :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.\n\n        :param redirect:\n            If True, automatically handle redirects (status codes 301, 302,\n            303, 307, 308). Each redirect counts as a retry. Disabling retries\n            will disable redirect, too.\n\n        :param assert_same_host:\n            If ``True``, will make sure that the host of the pool requests is\n            consistent else will raise HostChangedError. When ``False``, you can\n            use the pool on an HTTP proxy and request foreign hosts.\n\n        :param timeout:\n            If specified, overrides the default timeout for this one\n            request. It may be a float (in seconds) or an instance of\n            :class:`urllib3.util.Timeout`.\n\n        :param pool_timeout:\n            If set and the pool is set to block=True, then this method will\n            block for ``pool_timeout`` seconds and raise EmptyPoolError if no\n            connection is available within the time period.\n\n        :param release_conn:\n            If False, then the urlopen call will not release the connection\n            back into the pool once a response is received (but will release if\n            you read the entire contents of the response such as when\n            `preload_content=True`). This is useful if you're not preloading\n            the response's content immediately. You will need to call\n            ``r.release_conn()`` on the response ``r`` to return the connection\n            back into the pool. If None, it takes the value of\n            ``response_kw.get('preload_content', True)``.\n\n        :param chunked:\n            If True, urllib3 will send the body using chunked transfer\n            encoding. Otherwise, urllib3 will send the body using the standard\n            content-length form. Defaults to False.\n\n        :param int body_pos:\n            Position to seek to in file-like body in the event of a retry or\n            redirect. Typically this won't need to be set because urllib3 will\n            auto-populate the value when needed.\n\n        :param \\\\**response_kw:\n            Additional parameters are passed to\n            :meth:`urllib3.response.HTTPResponse.from_httplib`\n        \"\"\"\n\n        parsed_url = parse_url(url)\n        destination_scheme = parsed_url.scheme\n\n        if headers is None:\n            headers = self.headers\n\n        if not isinstance(retries, Retry):\n            retries = Retry.from_int(retries, redirect=redirect, default=self.retries)\n\n        if release_conn is None:\n            release_conn = response_kw.get(\"preload_content\", True)\n\n        # Check host\n        if assert_same_host and not self.is_same_host(url):\n            raise HostChangedError(self, url, retries)\n\n        # Ensure that the URL we're connecting to is properly encoded\n        if url.startswith(\"/\"):\n            url = six.ensure_str(_encode_target(url))\n        else:\n            url = six.ensure_str(parsed_url.url)\n\n        conn = None\n\n        # Track whether `conn` needs to be released before\n        # returning/raising/recursing. Update this variable if necessary, and\n        # leave `release_conn` constant throughout the function. That way, if\n        # the function recurses, the original value of `release_conn` will be\n        # passed down into the recursive call, and its value will be respected.\n        #\n        # See issue #651 [1] for details.\n        #\n        # [1] <https://github.com/urllib3/urllib3/issues/651>\n        release_this_conn = release_conn\n\n        http_tunnel_required = connection_requires_http_tunnel(\n            self.proxy, self.proxy_config, destination_scheme\n        )\n\n        # Merge the proxy headers. Only done when not using HTTP CONNECT. We\n        # have to copy the headers dict so we can safely change it without those\n        # changes being reflected in anyone else's copy.\n        if not http_tunnel_required:\n            headers = headers.copy()\n            headers.update(self.proxy_headers)\n\n        # Must keep the exception bound to a separate variable or else Python 3\n        # complains about UnboundLocalError.\n        err = None\n\n        # Keep track of whether we cleanly exited the except block. This\n        # ensures we do proper cleanup in finally.\n        clean_exit = False\n\n        # Rewind body position, if needed. Record current position\n        # for future rewinds in the event of a redirect/retry.\n        body_pos = set_file_position(body, body_pos)\n\n        try:\n            # Request a connection from the queue.\n            timeout_obj = self._get_timeout(timeout)\n            conn = self._get_conn(timeout=pool_timeout)\n\n            conn.timeout = timeout_obj.connect_timeout\n\n            is_new_proxy_conn = self.proxy is not None and not getattr(\n                conn, \"sock\", None\n            )\n            if is_new_proxy_conn and http_tunnel_required:\n                self._prepare_proxy(conn)\n\n            # Make the request on the httplib connection object.\n            httplib_response = self._make_request(\n                conn,\n                method,\n                url,\n                timeout=timeout_obj,\n                body=body,\n                headers=headers,\n                chunked=chunked,\n            )\n\n            # If we're going to release the connection in ``finally:``, then\n            # the response doesn't need to know about the connection. Otherwise\n            # it will also try to release it and we'll have a double-release\n            # mess.\n            response_conn = conn if not release_conn else None\n\n            # Pass method to Response for length checking\n            response_kw[\"request_method\"] = method\n\n            # Import httplib's response into our own wrapper object\n            response = self.ResponseCls.from_httplib(\n                httplib_response,\n                pool=self,\n                connection=response_conn,\n                retries=retries,\n                **response_kw\n            )\n\n            # Everything went great!\n            clean_exit = True\n\n        except EmptyPoolError:\n            # Didn't get a connection from the pool, no need to clean up\n            clean_exit = True\n            release_this_conn = False\n            raise\n\n        except (\n            TimeoutError,\n            HTTPException,\n            SocketError,\n            ProtocolError,\n            BaseSSLError,\n            SSLError,\n            CertificateError,\n        ) as e:\n            # Discard the connection for these exceptions. It will be\n            # replaced during the next _get_conn() call.\n            clean_exit = False\n\n            def _is_ssl_error_message_from_http_proxy(ssl_error):\n                # We're trying to detect the message 'WRONG_VERSION_NUMBER' but\n                # SSLErrors are kinda all over the place when it comes to the message,\n                # so we try to cover our bases here!\n                message = \" \".join(re.split(\"[^a-z]\", str(ssl_error).lower()))\n                return (\n                    \"wrong version number\" in message or \"unknown protocol\" in message\n                )\n\n            # Try to detect a common user error with proxies which is to\n            # set an HTTP proxy to be HTTPS when it should be 'http://'\n            # (ie {'http': 'http://proxy', 'https': 'https://proxy'})\n            # Instead we add a nice error message and point to a URL.\n            if (\n                isinstance(e, BaseSSLError)\n                and self.proxy\n                and _is_ssl_error_message_from_http_proxy(e)\n                and conn.proxy\n                and conn.proxy.scheme == \"https\"\n            ):\n                e = ProxyError(\n                    \"Your proxy appears to only use HTTP and not HTTPS, \"\n                    \"try changing your proxy URL to be HTTP. See: \"\n                    \"https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html\"\n                    \"#https-proxy-error-http-proxy\",\n                    SSLError(e),\n                )\n            elif isinstance(e, (BaseSSLError, CertificateError)):\n                e = SSLError(e)\n            elif isinstance(e, (SocketError, NewConnectionError)) and self.proxy:\n                e = ProxyError(\"Cannot connect to proxy.\", e)\n            elif isinstance(e, (SocketError, HTTPException)):\n                e = ProtocolError(\"Connection aborted.\", e)\n\n            retries = retries.increment(\n                method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2]\n            )\n            retries.sleep()\n\n            # Keep track of the error for the retry warning.\n            err = e\n\n        finally:\n            if not clean_exit:\n                # We hit some kind of exception, handled or otherwise. We need\n                # to throw the connection away unless explicitly told not to.\n                # Close the connection, set the variable to None, and make sure\n                # we put the None back in the pool to avoid leaking it.\n                conn = conn and conn.close()\n                release_this_conn = True\n\n            if release_this_conn:\n                # Put the connection back to be reused. If the connection is\n                # expired then it will be None, which will get replaced with a\n                # fresh connection during _get_conn.\n                self._put_conn(conn)\n\n        if not conn:\n            # Try again\n            log.warning(\n                \"Retrying (%r) after connection broken by '%r': %s\", retries, err, url\n            )\n            return self.urlopen(\n                method,\n                url,\n                body,\n                headers,\n                retries,\n                redirect,\n                assert_same_host,\n                timeout=timeout,\n                pool_timeout=pool_timeout,\n                release_conn=release_conn,\n                chunked=chunked,\n                body_pos=body_pos,\n                **response_kw\n            )\n\n        # Handle redirect?\n        redirect_location = redirect and response.get_redirect_location()\n        if redirect_location:\n            if response.status == 303:\n                method = \"GET\"\n\n            try:\n                retries = retries.increment(method, url, response=response, _pool=self)\n            except MaxRetryError:\n                if retries.raise_on_redirect:\n                    response.drain_conn()\n                    raise\n                return response\n\n            response.drain_conn()\n            retries.sleep_for_retry(response)\n            log.debug(\"Redirecting %s -> %s\", url, redirect_location)\n            return self.urlopen(\n                method,\n                redirect_location,\n                body,\n                headers,\n                retries=retries,\n                redirect=redirect,\n                assert_same_host=assert_same_host,\n                timeout=timeout,\n                pool_timeout=pool_timeout,\n                release_conn=release_conn,\n                chunked=chunked,\n                body_pos=body_pos,\n                **response_kw\n            )\n\n        # Check if we should retry the HTTP response.\n        has_retry_after = bool(response.getheader(\"Retry-After\"))\n        if retries.is_retry(method, response.status, has_retry_after):\n            try:\n                retries = retries.increment(method, url, response=response, _pool=self)\n            except MaxRetryError:\n                if retries.raise_on_status:\n                    response.drain_conn()\n                    raise\n                return response\n\n            response.drain_conn()\n            retries.sleep(response)\n            log.debug(\"Retry: %s\", url)\n            return self.urlopen(\n                method,\n                url,\n                body,\n                headers,\n                retries=retries,\n                redirect=redirect,\n                assert_same_host=assert_same_host,\n                timeout=timeout,\n                pool_timeout=pool_timeout,\n                release_conn=release_conn,\n                chunked=chunked,\n                body_pos=body_pos,\n                **response_kw\n            )\n\n        return response\n\n\nclass HTTPSConnectionPool(HTTPConnectionPool):\n    \"\"\"\n    Same as :class:`.HTTPConnectionPool`, but HTTPS.\n\n    :class:`.HTTPSConnection` uses one of ``assert_fingerprint``,\n    ``assert_hostname`` and ``host`` in this order to verify connections.\n    If ``assert_hostname`` is False, no verification is done.\n\n    The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``,\n    ``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl`\n    is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade\n    the connection socket into an SSL socket.\n    \"\"\"\n\n    scheme = \"https\"\n    ConnectionCls = HTTPSConnection\n\n    def __init__(\n        self,\n        host,\n        port=None,\n        strict=False,\n        timeout=Timeout.DEFAULT_TIMEOUT,\n        maxsize=1,\n        block=False,\n        headers=None,\n        retries=None,\n        _proxy=None,\n        _proxy_headers=None,\n        key_file=None,\n        cert_file=None,\n        cert_reqs=None,\n        key_password=None,\n        ca_certs=None,\n        ssl_version=None,\n        assert_hostname=None,\n        assert_fingerprint=None,\n        ca_cert_dir=None,\n        **conn_kw\n    ):\n\n        HTTPConnectionPool.__init__(\n            self,\n            host,\n            port,\n            strict,\n            timeout,\n            maxsize,\n            block,\n            headers,\n            retries,\n            _proxy,\n            _proxy_headers,\n            **conn_kw\n        )\n\n        self.key_file = key_file\n        self.cert_file = cert_file\n        self.cert_reqs = cert_reqs\n        self.key_password = key_password\n        self.ca_certs = ca_certs\n        self.ca_cert_dir = ca_cert_dir\n        self.ssl_version = ssl_version\n        self.assert_hostname = assert_hostname\n        self.assert_fingerprint = assert_fingerprint\n\n    def _prepare_conn(self, conn):\n        \"\"\"\n        Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`\n        and establish the tunnel if proxy is used.\n        \"\"\"\n\n        if isinstance(conn, VerifiedHTTPSConnection):\n            conn.set_cert(\n                key_file=self.key_file,\n                key_password=self.key_password,\n                cert_file=self.cert_file,\n                cert_reqs=self.cert_reqs,\n                ca_certs=self.ca_certs,\n                ca_cert_dir=self.ca_cert_dir,\n                assert_hostname=self.assert_hostname,\n                assert_fingerprint=self.assert_fingerprint,\n            )\n            conn.ssl_version = self.ssl_version\n        return conn\n\n    def _prepare_proxy(self, conn):\n        \"\"\"\n        Establishes a tunnel connection through HTTP CONNECT.\n\n        Tunnel connection is established early because otherwise httplib would\n        improperly set Host: header to proxy's IP:port.\n        \"\"\"\n\n        conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers)\n\n        if self.proxy.scheme == \"https\":\n            conn.tls_in_tls_required = True\n\n        conn.connect()\n\n    def _new_conn(self):\n        \"\"\"\n        Return a fresh :class:`http.client.HTTPSConnection`.\n        \"\"\"\n        self.num_connections += 1\n        log.debug(\n            \"Starting new HTTPS connection (%d): %s:%s\",\n            self.num_connections,\n            self.host,\n            self.port or \"443\",\n        )\n\n        if not self.ConnectionCls or self.ConnectionCls is DummyConnection:\n            raise SSLError(\n                \"Can't connect to HTTPS URL because the SSL module is not available.\"\n            )\n\n        actual_host = self.host\n        actual_port = self.port\n        if self.proxy is not None:\n            actual_host = self.proxy.host\n            actual_port = self.proxy.port\n\n        conn = self.ConnectionCls(\n            host=actual_host,\n            port=actual_port,\n            timeout=self.timeout.connect_timeout,\n            strict=self.strict,\n            cert_file=self.cert_file,\n            key_file=self.key_file,\n            key_password=self.key_password,\n            **self.conn_kw\n        )\n\n        return self._prepare_conn(conn)\n\n    def _validate_conn(self, conn):\n        \"\"\"\n        Called right before a request is made, after the socket is created.\n        \"\"\"\n        super(HTTPSConnectionPool, self)._validate_conn(conn)\n\n        # Force connect early to allow us to validate the connection.\n        if not getattr(conn, \"sock\", None):  # AppEngine might not have  `.sock`\n            conn.connect()\n\n        if not conn.is_verified:\n            warnings.warn(\n                (\n                    \"Unverified HTTPS request is being made to host '%s'. \"\n                    \"Adding certificate verification is strongly advised. See: \"\n                    \"https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html\"\n                    \"#ssl-warnings\" % conn.host\n                ),\n                InsecureRequestWarning,\n            )\n\n        if getattr(conn, \"proxy_is_verified\", None) is False:\n            warnings.warn(\n                (\n                    \"Unverified HTTPS connection done to an HTTPS proxy. \"\n                    \"Adding certificate verification is strongly advised. See: \"\n                    \"https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html\"\n                    \"#ssl-warnings\"\n                ),\n                InsecureRequestWarning,\n            )\n\n\ndef connection_from_url(url, **kw):\n    \"\"\"\n    Given a url, return an :class:`.ConnectionPool` instance of its host.\n\n    This is a shortcut for not having to parse out the scheme, host, and port\n    of the url before creating an :class:`.ConnectionPool` instance.\n\n    :param url:\n        Absolute URL string that must include the scheme. Port is optional.\n\n    :param \\\\**kw:\n        Passes additional parameters to the constructor of the appropriate\n        :class:`.ConnectionPool`. Useful for specifying things like\n        timeout, maxsize, headers, etc.\n\n    Example::\n\n        >>> conn = connection_from_url('http://google.com/')\n        >>> r = conn.request('GET', '/')\n    \"\"\"\n    scheme, host, port = get_host(url)\n    port = port or port_by_scheme.get(scheme, 80)\n    if scheme == \"https\":\n        return HTTPSConnectionPool(host, port=port, **kw)\n    else:\n        return HTTPConnectionPool(host, port=port, **kw)\n\n\ndef _normalize_host(host, scheme):\n    \"\"\"\n    Normalize hosts for comparisons and use with sockets.\n    \"\"\"\n\n    host = normalize_host(host, scheme)\n\n    # httplib doesn't like it when we include brackets in IPv6 addresses\n    # Specifically, if we include brackets but also pass the port then\n    # httplib crazily doubles up the square brackets on the Host header.\n    # Instead, we need to make sure we never pass ``None`` as the port.\n    # However, for backward compatibility reasons we can't actually\n    # *assert* that.  See http://bugs.python.org/issue28539\n    if host.startswith(\"[\") and host.endswith(\"]\"):\n        host = host[1:-1]\n    return host\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/_appengine_environ.py",
    "content": "\"\"\"\nThis module provides means to detect the App Engine environment.\n\"\"\"\n\nimport os\n\n\ndef is_appengine():\n    return is_local_appengine() or is_prod_appengine()\n\n\ndef is_appengine_sandbox():\n    \"\"\"Reports if the app is running in the first generation sandbox.\n\n    The second generation runtimes are technically still in a sandbox, but it\n    is much less restrictive, so generally you shouldn't need to check for it.\n    see https://cloud.google.com/appengine/docs/standard/runtimes\n    \"\"\"\n    return is_appengine() and os.environ[\"APPENGINE_RUNTIME\"] == \"python27\"\n\n\ndef is_local_appengine():\n    return \"APPENGINE_RUNTIME\" in os.environ and os.environ.get(\n        \"SERVER_SOFTWARE\", \"\"\n    ).startswith(\"Development/\")\n\n\ndef is_prod_appengine():\n    return \"APPENGINE_RUNTIME\" in os.environ and os.environ.get(\n        \"SERVER_SOFTWARE\", \"\"\n    ).startswith(\"Google App Engine/\")\n\n\ndef is_prod_appengine_mvms():\n    \"\"\"Deprecated.\"\"\"\n    return False\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/bindings.py",
    "content": "\"\"\"\nThis module uses ctypes to bind a whole bunch of functions and constants from\nSecureTransport. The goal here is to provide the low-level API to\nSecureTransport. These are essentially the C-level functions and constants, and\nthey're pretty gross to work with.\n\nThis code is a bastardised version of the code found in Will Bond's oscrypto\nlibrary. An enormous debt is owed to him for blazing this trail for us. For\nthat reason, this code should be considered to be covered both by urllib3's\nlicense and by oscrypto's:\n\n    Copyright (c) 2015-2016 Will Bond <will@wbond.net>\n\n    Permission is hereby granted, free of charge, to any person obtaining a\n    copy of this software and associated documentation files (the \"Software\"),\n    to deal in the Software without restriction, including without limitation\n    the rights to use, copy, modify, merge, publish, distribute, sublicense,\n    and/or sell copies of the Software, and to permit persons to whom the\n    Software is furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n    DEALINGS IN THE SOFTWARE.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport platform\nfrom ctypes import (\n    CDLL,\n    CFUNCTYPE,\n    POINTER,\n    c_bool,\n    c_byte,\n    c_char_p,\n    c_int32,\n    c_long,\n    c_size_t,\n    c_uint32,\n    c_ulong,\n    c_void_p,\n)\nfrom ctypes.util import find_library\n\nfrom ...packages.six import raise_from\n\nif platform.system() != \"Darwin\":\n    raise ImportError(\"Only macOS is supported\")\n\nversion = platform.mac_ver()[0]\nversion_info = tuple(map(int, version.split(\".\")))\nif version_info < (10, 8):\n    raise OSError(\n        \"Only OS X 10.8 and newer are supported, not %s.%s\"\n        % (version_info[0], version_info[1])\n    )\n\n\ndef load_cdll(name, macos10_16_path):\n    \"\"\"Loads a CDLL by name, falling back to known path on 10.16+\"\"\"\n    try:\n        # Big Sur is technically 11 but we use 10.16 due to the Big Sur\n        # beta being labeled as 10.16.\n        if version_info >= (10, 16):\n            path = macos10_16_path\n        else:\n            path = find_library(name)\n        if not path:\n            raise OSError  # Caught and reraised as 'ImportError'\n        return CDLL(path, use_errno=True)\n    except OSError:\n        raise_from(ImportError(\"The library %s failed to load\" % name), None)\n\n\nSecurity = load_cdll(\n    \"Security\", \"/System/Library/Frameworks/Security.framework/Security\"\n)\nCoreFoundation = load_cdll(\n    \"CoreFoundation\",\n    \"/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation\",\n)\n\n\nBoolean = c_bool\nCFIndex = c_long\nCFStringEncoding = c_uint32\nCFData = c_void_p\nCFString = c_void_p\nCFArray = c_void_p\nCFMutableArray = c_void_p\nCFDictionary = c_void_p\nCFError = c_void_p\nCFType = c_void_p\nCFTypeID = c_ulong\n\nCFTypeRef = POINTER(CFType)\nCFAllocatorRef = c_void_p\n\nOSStatus = c_int32\n\nCFDataRef = POINTER(CFData)\nCFStringRef = POINTER(CFString)\nCFArrayRef = POINTER(CFArray)\nCFMutableArrayRef = POINTER(CFMutableArray)\nCFDictionaryRef = POINTER(CFDictionary)\nCFArrayCallBacks = c_void_p\nCFDictionaryKeyCallBacks = c_void_p\nCFDictionaryValueCallBacks = c_void_p\n\nSecCertificateRef = POINTER(c_void_p)\nSecExternalFormat = c_uint32\nSecExternalItemType = c_uint32\nSecIdentityRef = POINTER(c_void_p)\nSecItemImportExportFlags = c_uint32\nSecItemImportExportKeyParameters = c_void_p\nSecKeychainRef = POINTER(c_void_p)\nSSLProtocol = c_uint32\nSSLCipherSuite = c_uint32\nSSLContextRef = POINTER(c_void_p)\nSecTrustRef = POINTER(c_void_p)\nSSLConnectionRef = c_uint32\nSecTrustResultType = c_uint32\nSecTrustOptionFlags = c_uint32\nSSLProtocolSide = c_uint32\nSSLConnectionType = c_uint32\nSSLSessionOption = c_uint32\n\n\ntry:\n    Security.SecItemImport.argtypes = [\n        CFDataRef,\n        CFStringRef,\n        POINTER(SecExternalFormat),\n        POINTER(SecExternalItemType),\n        SecItemImportExportFlags,\n        POINTER(SecItemImportExportKeyParameters),\n        SecKeychainRef,\n        POINTER(CFArrayRef),\n    ]\n    Security.SecItemImport.restype = OSStatus\n\n    Security.SecCertificateGetTypeID.argtypes = []\n    Security.SecCertificateGetTypeID.restype = CFTypeID\n\n    Security.SecIdentityGetTypeID.argtypes = []\n    Security.SecIdentityGetTypeID.restype = CFTypeID\n\n    Security.SecKeyGetTypeID.argtypes = []\n    Security.SecKeyGetTypeID.restype = CFTypeID\n\n    Security.SecCertificateCreateWithData.argtypes = [CFAllocatorRef, CFDataRef]\n    Security.SecCertificateCreateWithData.restype = SecCertificateRef\n\n    Security.SecCertificateCopyData.argtypes = [SecCertificateRef]\n    Security.SecCertificateCopyData.restype = CFDataRef\n\n    Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p]\n    Security.SecCopyErrorMessageString.restype = CFStringRef\n\n    Security.SecIdentityCreateWithCertificate.argtypes = [\n        CFTypeRef,\n        SecCertificateRef,\n        POINTER(SecIdentityRef),\n    ]\n    Security.SecIdentityCreateWithCertificate.restype = OSStatus\n\n    Security.SecKeychainCreate.argtypes = [\n        c_char_p,\n        c_uint32,\n        c_void_p,\n        Boolean,\n        c_void_p,\n        POINTER(SecKeychainRef),\n    ]\n    Security.SecKeychainCreate.restype = OSStatus\n\n    Security.SecKeychainDelete.argtypes = [SecKeychainRef]\n    Security.SecKeychainDelete.restype = OSStatus\n\n    Security.SecPKCS12Import.argtypes = [\n        CFDataRef,\n        CFDictionaryRef,\n        POINTER(CFArrayRef),\n    ]\n    Security.SecPKCS12Import.restype = OSStatus\n\n    SSLReadFunc = CFUNCTYPE(OSStatus, SSLConnectionRef, c_void_p, POINTER(c_size_t))\n    SSLWriteFunc = CFUNCTYPE(\n        OSStatus, SSLConnectionRef, POINTER(c_byte), POINTER(c_size_t)\n    )\n\n    Security.SSLSetIOFuncs.argtypes = [SSLContextRef, SSLReadFunc, SSLWriteFunc]\n    Security.SSLSetIOFuncs.restype = OSStatus\n\n    Security.SSLSetPeerID.argtypes = [SSLContextRef, c_char_p, c_size_t]\n    Security.SSLSetPeerID.restype = OSStatus\n\n    Security.SSLSetCertificate.argtypes = [SSLContextRef, CFArrayRef]\n    Security.SSLSetCertificate.restype = OSStatus\n\n    Security.SSLSetCertificateAuthorities.argtypes = [SSLContextRef, CFTypeRef, Boolean]\n    Security.SSLSetCertificateAuthorities.restype = OSStatus\n\n    Security.SSLSetConnection.argtypes = [SSLContextRef, SSLConnectionRef]\n    Security.SSLSetConnection.restype = OSStatus\n\n    Security.SSLSetPeerDomainName.argtypes = [SSLContextRef, c_char_p, c_size_t]\n    Security.SSLSetPeerDomainName.restype = OSStatus\n\n    Security.SSLHandshake.argtypes = [SSLContextRef]\n    Security.SSLHandshake.restype = OSStatus\n\n    Security.SSLRead.argtypes = [SSLContextRef, c_char_p, c_size_t, POINTER(c_size_t)]\n    Security.SSLRead.restype = OSStatus\n\n    Security.SSLWrite.argtypes = [SSLContextRef, c_char_p, c_size_t, POINTER(c_size_t)]\n    Security.SSLWrite.restype = OSStatus\n\n    Security.SSLClose.argtypes = [SSLContextRef]\n    Security.SSLClose.restype = OSStatus\n\n    Security.SSLGetNumberSupportedCiphers.argtypes = [SSLContextRef, POINTER(c_size_t)]\n    Security.SSLGetNumberSupportedCiphers.restype = OSStatus\n\n    Security.SSLGetSupportedCiphers.argtypes = [\n        SSLContextRef,\n        POINTER(SSLCipherSuite),\n        POINTER(c_size_t),\n    ]\n    Security.SSLGetSupportedCiphers.restype = OSStatus\n\n    Security.SSLSetEnabledCiphers.argtypes = [\n        SSLContextRef,\n        POINTER(SSLCipherSuite),\n        c_size_t,\n    ]\n    Security.SSLSetEnabledCiphers.restype = OSStatus\n\n    Security.SSLGetNumberEnabledCiphers.argtype = [SSLContextRef, POINTER(c_size_t)]\n    Security.SSLGetNumberEnabledCiphers.restype = OSStatus\n\n    Security.SSLGetEnabledCiphers.argtypes = [\n        SSLContextRef,\n        POINTER(SSLCipherSuite),\n        POINTER(c_size_t),\n    ]\n    Security.SSLGetEnabledCiphers.restype = OSStatus\n\n    Security.SSLGetNegotiatedCipher.argtypes = [SSLContextRef, POINTER(SSLCipherSuite)]\n    Security.SSLGetNegotiatedCipher.restype = OSStatus\n\n    Security.SSLGetNegotiatedProtocolVersion.argtypes = [\n        SSLContextRef,\n        POINTER(SSLProtocol),\n    ]\n    Security.SSLGetNegotiatedProtocolVersion.restype = OSStatus\n\n    Security.SSLCopyPeerTrust.argtypes = [SSLContextRef, POINTER(SecTrustRef)]\n    Security.SSLCopyPeerTrust.restype = OSStatus\n\n    Security.SecTrustSetAnchorCertificates.argtypes = [SecTrustRef, CFArrayRef]\n    Security.SecTrustSetAnchorCertificates.restype = OSStatus\n\n    Security.SecTrustSetAnchorCertificatesOnly.argstypes = [SecTrustRef, Boolean]\n    Security.SecTrustSetAnchorCertificatesOnly.restype = OSStatus\n\n    Security.SecTrustEvaluate.argtypes = [SecTrustRef, POINTER(SecTrustResultType)]\n    Security.SecTrustEvaluate.restype = OSStatus\n\n    Security.SecTrustGetCertificateCount.argtypes = [SecTrustRef]\n    Security.SecTrustGetCertificateCount.restype = CFIndex\n\n    Security.SecTrustGetCertificateAtIndex.argtypes = [SecTrustRef, CFIndex]\n    Security.SecTrustGetCertificateAtIndex.restype = SecCertificateRef\n\n    Security.SSLCreateContext.argtypes = [\n        CFAllocatorRef,\n        SSLProtocolSide,\n        SSLConnectionType,\n    ]\n    Security.SSLCreateContext.restype = SSLContextRef\n\n    Security.SSLSetSessionOption.argtypes = [SSLContextRef, SSLSessionOption, Boolean]\n    Security.SSLSetSessionOption.restype = OSStatus\n\n    Security.SSLSetProtocolVersionMin.argtypes = [SSLContextRef, SSLProtocol]\n    Security.SSLSetProtocolVersionMin.restype = OSStatus\n\n    Security.SSLSetProtocolVersionMax.argtypes = [SSLContextRef, SSLProtocol]\n    Security.SSLSetProtocolVersionMax.restype = OSStatus\n\n    try:\n        Security.SSLSetALPNProtocols.argtypes = [SSLContextRef, CFArrayRef]\n        Security.SSLSetALPNProtocols.restype = OSStatus\n    except AttributeError:\n        # Supported only in 10.12+\n        pass\n\n    Security.SecCopyErrorMessageString.argtypes = [OSStatus, c_void_p]\n    Security.SecCopyErrorMessageString.restype = CFStringRef\n\n    Security.SSLReadFunc = SSLReadFunc\n    Security.SSLWriteFunc = SSLWriteFunc\n    Security.SSLContextRef = SSLContextRef\n    Security.SSLProtocol = SSLProtocol\n    Security.SSLCipherSuite = SSLCipherSuite\n    Security.SecIdentityRef = SecIdentityRef\n    Security.SecKeychainRef = SecKeychainRef\n    Security.SecTrustRef = SecTrustRef\n    Security.SecTrustResultType = SecTrustResultType\n    Security.SecExternalFormat = SecExternalFormat\n    Security.OSStatus = OSStatus\n\n    Security.kSecImportExportPassphrase = CFStringRef.in_dll(\n        Security, \"kSecImportExportPassphrase\"\n    )\n    Security.kSecImportItemIdentity = CFStringRef.in_dll(\n        Security, \"kSecImportItemIdentity\"\n    )\n\n    # CoreFoundation time!\n    CoreFoundation.CFRetain.argtypes = [CFTypeRef]\n    CoreFoundation.CFRetain.restype = CFTypeRef\n\n    CoreFoundation.CFRelease.argtypes = [CFTypeRef]\n    CoreFoundation.CFRelease.restype = None\n\n    CoreFoundation.CFGetTypeID.argtypes = [CFTypeRef]\n    CoreFoundation.CFGetTypeID.restype = CFTypeID\n\n    CoreFoundation.CFStringCreateWithCString.argtypes = [\n        CFAllocatorRef,\n        c_char_p,\n        CFStringEncoding,\n    ]\n    CoreFoundation.CFStringCreateWithCString.restype = CFStringRef\n\n    CoreFoundation.CFStringGetCStringPtr.argtypes = [CFStringRef, CFStringEncoding]\n    CoreFoundation.CFStringGetCStringPtr.restype = c_char_p\n\n    CoreFoundation.CFStringGetCString.argtypes = [\n        CFStringRef,\n        c_char_p,\n        CFIndex,\n        CFStringEncoding,\n    ]\n    CoreFoundation.CFStringGetCString.restype = c_bool\n\n    CoreFoundation.CFDataCreate.argtypes = [CFAllocatorRef, c_char_p, CFIndex]\n    CoreFoundation.CFDataCreate.restype = CFDataRef\n\n    CoreFoundation.CFDataGetLength.argtypes = [CFDataRef]\n    CoreFoundation.CFDataGetLength.restype = CFIndex\n\n    CoreFoundation.CFDataGetBytePtr.argtypes = [CFDataRef]\n    CoreFoundation.CFDataGetBytePtr.restype = c_void_p\n\n    CoreFoundation.CFDictionaryCreate.argtypes = [\n        CFAllocatorRef,\n        POINTER(CFTypeRef),\n        POINTER(CFTypeRef),\n        CFIndex,\n        CFDictionaryKeyCallBacks,\n        CFDictionaryValueCallBacks,\n    ]\n    CoreFoundation.CFDictionaryCreate.restype = CFDictionaryRef\n\n    CoreFoundation.CFDictionaryGetValue.argtypes = [CFDictionaryRef, CFTypeRef]\n    CoreFoundation.CFDictionaryGetValue.restype = CFTypeRef\n\n    CoreFoundation.CFArrayCreate.argtypes = [\n        CFAllocatorRef,\n        POINTER(CFTypeRef),\n        CFIndex,\n        CFArrayCallBacks,\n    ]\n    CoreFoundation.CFArrayCreate.restype = CFArrayRef\n\n    CoreFoundation.CFArrayCreateMutable.argtypes = [\n        CFAllocatorRef,\n        CFIndex,\n        CFArrayCallBacks,\n    ]\n    CoreFoundation.CFArrayCreateMutable.restype = CFMutableArrayRef\n\n    CoreFoundation.CFArrayAppendValue.argtypes = [CFMutableArrayRef, c_void_p]\n    CoreFoundation.CFArrayAppendValue.restype = None\n\n    CoreFoundation.CFArrayGetCount.argtypes = [CFArrayRef]\n    CoreFoundation.CFArrayGetCount.restype = CFIndex\n\n    CoreFoundation.CFArrayGetValueAtIndex.argtypes = [CFArrayRef, CFIndex]\n    CoreFoundation.CFArrayGetValueAtIndex.restype = c_void_p\n\n    CoreFoundation.kCFAllocatorDefault = CFAllocatorRef.in_dll(\n        CoreFoundation, \"kCFAllocatorDefault\"\n    )\n    CoreFoundation.kCFTypeArrayCallBacks = c_void_p.in_dll(\n        CoreFoundation, \"kCFTypeArrayCallBacks\"\n    )\n    CoreFoundation.kCFTypeDictionaryKeyCallBacks = c_void_p.in_dll(\n        CoreFoundation, \"kCFTypeDictionaryKeyCallBacks\"\n    )\n    CoreFoundation.kCFTypeDictionaryValueCallBacks = c_void_p.in_dll(\n        CoreFoundation, \"kCFTypeDictionaryValueCallBacks\"\n    )\n\n    CoreFoundation.CFTypeRef = CFTypeRef\n    CoreFoundation.CFArrayRef = CFArrayRef\n    CoreFoundation.CFStringRef = CFStringRef\n    CoreFoundation.CFDictionaryRef = CFDictionaryRef\n\nexcept (AttributeError):\n    raise ImportError(\"Error initializing ctypes\")\n\n\nclass CFConst(object):\n    \"\"\"\n    A class object that acts as essentially a namespace for CoreFoundation\n    constants.\n    \"\"\"\n\n    kCFStringEncodingUTF8 = CFStringEncoding(0x08000100)\n\n\nclass SecurityConst(object):\n    \"\"\"\n    A class object that acts as essentially a namespace for Security constants.\n    \"\"\"\n\n    kSSLSessionOptionBreakOnServerAuth = 0\n\n    kSSLProtocol2 = 1\n    kSSLProtocol3 = 2\n    kTLSProtocol1 = 4\n    kTLSProtocol11 = 7\n    kTLSProtocol12 = 8\n    # SecureTransport does not support TLS 1.3 even if there's a constant for it\n    kTLSProtocol13 = 10\n    kTLSProtocolMaxSupported = 999\n\n    kSSLClientSide = 1\n    kSSLStreamType = 0\n\n    kSecFormatPEMSequence = 10\n\n    kSecTrustResultInvalid = 0\n    kSecTrustResultProceed = 1\n    # This gap is present on purpose: this was kSecTrustResultConfirm, which\n    # is deprecated.\n    kSecTrustResultDeny = 3\n    kSecTrustResultUnspecified = 4\n    kSecTrustResultRecoverableTrustFailure = 5\n    kSecTrustResultFatalTrustFailure = 6\n    kSecTrustResultOtherError = 7\n\n    errSSLProtocol = -9800\n    errSSLWouldBlock = -9803\n    errSSLClosedGraceful = -9805\n    errSSLClosedNoNotify = -9816\n    errSSLClosedAbort = -9806\n\n    errSSLXCertChainInvalid = -9807\n    errSSLCrypto = -9809\n    errSSLInternal = -9810\n    errSSLCertExpired = -9814\n    errSSLCertNotYetValid = -9815\n    errSSLUnknownRootCert = -9812\n    errSSLNoRootCert = -9813\n    errSSLHostNameMismatch = -9843\n    errSSLPeerHandshakeFail = -9824\n    errSSLPeerUserCancelled = -9839\n    errSSLWeakPeerEphemeralDHKey = -9850\n    errSSLServerAuthCompleted = -9841\n    errSSLRecordOverflow = -9847\n\n    errSecVerifyFailed = -67808\n    errSecNoTrustSettings = -25263\n    errSecItemNotFound = -25300\n    errSecInvalidTrustSettings = -25262\n\n    # Cipher suites. We only pick the ones our default cipher string allows.\n    # Source: https://developer.apple.com/documentation/security/1550981-ssl_cipher_suite_values\n    TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 = 0xC02C\n    TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 = 0xC030\n    TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 = 0xC02B\n    TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 = 0xC02F\n    TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA9\n    TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 = 0xCCA8\n    TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 = 0x009F\n    TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 = 0x009E\n    TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 = 0xC024\n    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 = 0xC028\n    TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA = 0xC00A\n    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA = 0xC014\n    TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 = 0x006B\n    TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039\n    TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 = 0xC023\n    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 = 0xC027\n    TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA = 0xC009\n    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA = 0xC013\n    TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 = 0x0067\n    TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033\n    TLS_RSA_WITH_AES_256_GCM_SHA384 = 0x009D\n    TLS_RSA_WITH_AES_128_GCM_SHA256 = 0x009C\n    TLS_RSA_WITH_AES_256_CBC_SHA256 = 0x003D\n    TLS_RSA_WITH_AES_128_CBC_SHA256 = 0x003C\n    TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035\n    TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F\n    TLS_AES_128_GCM_SHA256 = 0x1301\n    TLS_AES_256_GCM_SHA384 = 0x1302\n    TLS_AES_128_CCM_8_SHA256 = 0x1305\n    TLS_AES_128_CCM_SHA256 = 0x1304\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/_securetransport/low_level.py",
    "content": "\"\"\"\nLow-level helpers for the SecureTransport bindings.\n\nThese are Python functions that are not directly related to the high-level APIs\nbut are necessary to get them to work. They include a whole bunch of low-level\nCoreFoundation messing about and memory management. The concerns in this module\nare almost entirely about trying to avoid memory leaks and providing\nappropriate and useful assistance to the higher-level code.\n\"\"\"\nimport base64\nimport ctypes\nimport itertools\nimport os\nimport re\nimport ssl\nimport struct\nimport tempfile\n\nfrom .bindings import CFConst, CoreFoundation, Security\n\n# This regular expression is used to grab PEM data out of a PEM bundle.\n_PEM_CERTS_RE = re.compile(\n    b\"-----BEGIN CERTIFICATE-----\\n(.*?)\\n-----END CERTIFICATE-----\", re.DOTALL\n)\n\n\ndef _cf_data_from_bytes(bytestring):\n    \"\"\"\n    Given a bytestring, create a CFData object from it. This CFData object must\n    be CFReleased by the caller.\n    \"\"\"\n    return CoreFoundation.CFDataCreate(\n        CoreFoundation.kCFAllocatorDefault, bytestring, len(bytestring)\n    )\n\n\ndef _cf_dictionary_from_tuples(tuples):\n    \"\"\"\n    Given a list of Python tuples, create an associated CFDictionary.\n    \"\"\"\n    dictionary_size = len(tuples)\n\n    # We need to get the dictionary keys and values out in the same order.\n    keys = (t[0] for t in tuples)\n    values = (t[1] for t in tuples)\n    cf_keys = (CoreFoundation.CFTypeRef * dictionary_size)(*keys)\n    cf_values = (CoreFoundation.CFTypeRef * dictionary_size)(*values)\n\n    return CoreFoundation.CFDictionaryCreate(\n        CoreFoundation.kCFAllocatorDefault,\n        cf_keys,\n        cf_values,\n        dictionary_size,\n        CoreFoundation.kCFTypeDictionaryKeyCallBacks,\n        CoreFoundation.kCFTypeDictionaryValueCallBacks,\n    )\n\n\ndef _cfstr(py_bstr):\n    \"\"\"\n    Given a Python binary data, create a CFString.\n    The string must be CFReleased by the caller.\n    \"\"\"\n    c_str = ctypes.c_char_p(py_bstr)\n    cf_str = CoreFoundation.CFStringCreateWithCString(\n        CoreFoundation.kCFAllocatorDefault,\n        c_str,\n        CFConst.kCFStringEncodingUTF8,\n    )\n    return cf_str\n\n\ndef _create_cfstring_array(lst):\n    \"\"\"\n    Given a list of Python binary data, create an associated CFMutableArray.\n    The array must be CFReleased by the caller.\n\n    Raises an ssl.SSLError on failure.\n    \"\"\"\n    cf_arr = None\n    try:\n        cf_arr = CoreFoundation.CFArrayCreateMutable(\n            CoreFoundation.kCFAllocatorDefault,\n            0,\n            ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n        )\n        if not cf_arr:\n            raise MemoryError(\"Unable to allocate memory!\")\n        for item in lst:\n            cf_str = _cfstr(item)\n            if not cf_str:\n                raise MemoryError(\"Unable to allocate memory!\")\n            try:\n                CoreFoundation.CFArrayAppendValue(cf_arr, cf_str)\n            finally:\n                CoreFoundation.CFRelease(cf_str)\n    except BaseException as e:\n        if cf_arr:\n            CoreFoundation.CFRelease(cf_arr)\n        raise ssl.SSLError(\"Unable to allocate array: %s\" % (e,))\n    return cf_arr\n\n\ndef _cf_string_to_unicode(value):\n    \"\"\"\n    Creates a Unicode string from a CFString object. Used entirely for error\n    reporting.\n\n    Yes, it annoys me quite a lot that this function is this complex.\n    \"\"\"\n    value_as_void_p = ctypes.cast(value, ctypes.POINTER(ctypes.c_void_p))\n\n    string = CoreFoundation.CFStringGetCStringPtr(\n        value_as_void_p, CFConst.kCFStringEncodingUTF8\n    )\n    if string is None:\n        buffer = ctypes.create_string_buffer(1024)\n        result = CoreFoundation.CFStringGetCString(\n            value_as_void_p, buffer, 1024, CFConst.kCFStringEncodingUTF8\n        )\n        if not result:\n            raise OSError(\"Error copying C string from CFStringRef\")\n        string = buffer.value\n    if string is not None:\n        string = string.decode(\"utf-8\")\n    return string\n\n\ndef _assert_no_error(error, exception_class=None):\n    \"\"\"\n    Checks the return code and throws an exception if there is an error to\n    report\n    \"\"\"\n    if error == 0:\n        return\n\n    cf_error_string = Security.SecCopyErrorMessageString(error, None)\n    output = _cf_string_to_unicode(cf_error_string)\n    CoreFoundation.CFRelease(cf_error_string)\n\n    if output is None or output == u\"\":\n        output = u\"OSStatus %s\" % error\n\n    if exception_class is None:\n        exception_class = ssl.SSLError\n\n    raise exception_class(output)\n\n\ndef _cert_array_from_pem(pem_bundle):\n    \"\"\"\n    Given a bundle of certs in PEM format, turns them into a CFArray of certs\n    that can be used to validate a cert chain.\n    \"\"\"\n    # Normalize the PEM bundle's line endings.\n    pem_bundle = pem_bundle.replace(b\"\\r\\n\", b\"\\n\")\n\n    der_certs = [\n        base64.b64decode(match.group(1)) for match in _PEM_CERTS_RE.finditer(pem_bundle)\n    ]\n    if not der_certs:\n        raise ssl.SSLError(\"No root certificates specified\")\n\n    cert_array = CoreFoundation.CFArrayCreateMutable(\n        CoreFoundation.kCFAllocatorDefault,\n        0,\n        ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n    )\n    if not cert_array:\n        raise ssl.SSLError(\"Unable to allocate memory!\")\n\n    try:\n        for der_bytes in der_certs:\n            certdata = _cf_data_from_bytes(der_bytes)\n            if not certdata:\n                raise ssl.SSLError(\"Unable to allocate memory!\")\n            cert = Security.SecCertificateCreateWithData(\n                CoreFoundation.kCFAllocatorDefault, certdata\n            )\n            CoreFoundation.CFRelease(certdata)\n            if not cert:\n                raise ssl.SSLError(\"Unable to build cert object!\")\n\n            CoreFoundation.CFArrayAppendValue(cert_array, cert)\n            CoreFoundation.CFRelease(cert)\n    except Exception:\n        # We need to free the array before the exception bubbles further.\n        # We only want to do that if an error occurs: otherwise, the caller\n        # should free.\n        CoreFoundation.CFRelease(cert_array)\n        raise\n\n    return cert_array\n\n\ndef _is_cert(item):\n    \"\"\"\n    Returns True if a given CFTypeRef is a certificate.\n    \"\"\"\n    expected = Security.SecCertificateGetTypeID()\n    return CoreFoundation.CFGetTypeID(item) == expected\n\n\ndef _is_identity(item):\n    \"\"\"\n    Returns True if a given CFTypeRef is an identity.\n    \"\"\"\n    expected = Security.SecIdentityGetTypeID()\n    return CoreFoundation.CFGetTypeID(item) == expected\n\n\ndef _temporary_keychain():\n    \"\"\"\n    This function creates a temporary Mac keychain that we can use to work with\n    credentials. This keychain uses a one-time password and a temporary file to\n    store the data. We expect to have one keychain per socket. The returned\n    SecKeychainRef must be freed by the caller, including calling\n    SecKeychainDelete.\n\n    Returns a tuple of the SecKeychainRef and the path to the temporary\n    directory that contains it.\n    \"\"\"\n    # Unfortunately, SecKeychainCreate requires a path to a keychain. This\n    # means we cannot use mkstemp to use a generic temporary file. Instead,\n    # we're going to create a temporary directory and a filename to use there.\n    # This filename will be 8 random bytes expanded into base64. We also need\n    # some random bytes to password-protect the keychain we're creating, so we\n    # ask for 40 random bytes.\n    random_bytes = os.urandom(40)\n    filename = base64.b16encode(random_bytes[:8]).decode(\"utf-8\")\n    password = base64.b16encode(random_bytes[8:])  # Must be valid UTF-8\n    tempdirectory = tempfile.mkdtemp()\n\n    keychain_path = os.path.join(tempdirectory, filename).encode(\"utf-8\")\n\n    # We now want to create the keychain itself.\n    keychain = Security.SecKeychainRef()\n    status = Security.SecKeychainCreate(\n        keychain_path, len(password), password, False, None, ctypes.byref(keychain)\n    )\n    _assert_no_error(status)\n\n    # Having created the keychain, we want to pass it off to the caller.\n    return keychain, tempdirectory\n\n\ndef _load_items_from_file(keychain, path):\n    \"\"\"\n    Given a single file, loads all the trust objects from it into arrays and\n    the keychain.\n    Returns a tuple of lists: the first list is a list of identities, the\n    second a list of certs.\n    \"\"\"\n    certificates = []\n    identities = []\n    result_array = None\n\n    with open(path, \"rb\") as f:\n        raw_filedata = f.read()\n\n    try:\n        filedata = CoreFoundation.CFDataCreate(\n            CoreFoundation.kCFAllocatorDefault, raw_filedata, len(raw_filedata)\n        )\n        result_array = CoreFoundation.CFArrayRef()\n        result = Security.SecItemImport(\n            filedata,  # cert data\n            None,  # Filename, leaving it out for now\n            None,  # What the type of the file is, we don't care\n            None,  # what's in the file, we don't care\n            0,  # import flags\n            None,  # key params, can include passphrase in the future\n            keychain,  # The keychain to insert into\n            ctypes.byref(result_array),  # Results\n        )\n        _assert_no_error(result)\n\n        # A CFArray is not very useful to us as an intermediary\n        # representation, so we are going to extract the objects we want\n        # and then free the array. We don't need to keep hold of keys: the\n        # keychain already has them!\n        result_count = CoreFoundation.CFArrayGetCount(result_array)\n        for index in range(result_count):\n            item = CoreFoundation.CFArrayGetValueAtIndex(result_array, index)\n            item = ctypes.cast(item, CoreFoundation.CFTypeRef)\n\n            if _is_cert(item):\n                CoreFoundation.CFRetain(item)\n                certificates.append(item)\n            elif _is_identity(item):\n                CoreFoundation.CFRetain(item)\n                identities.append(item)\n    finally:\n        if result_array:\n            CoreFoundation.CFRelease(result_array)\n\n        CoreFoundation.CFRelease(filedata)\n\n    return (identities, certificates)\n\n\ndef _load_client_cert_chain(keychain, *paths):\n    \"\"\"\n    Load certificates and maybe keys from a number of files. Has the end goal\n    of returning a CFArray containing one SecIdentityRef, and then zero or more\n    SecCertificateRef objects, suitable for use as a client certificate trust\n    chain.\n    \"\"\"\n    # Ok, the strategy.\n    #\n    # This relies on knowing that macOS will not give you a SecIdentityRef\n    # unless you have imported a key into a keychain. This is a somewhat\n    # artificial limitation of macOS (for example, it doesn't necessarily\n    # affect iOS), but there is nothing inside Security.framework that lets you\n    # get a SecIdentityRef without having a key in a keychain.\n    #\n    # So the policy here is we take all the files and iterate them in order.\n    # Each one will use SecItemImport to have one or more objects loaded from\n    # it. We will also point at a keychain that macOS can use to work with the\n    # private key.\n    #\n    # Once we have all the objects, we'll check what we actually have. If we\n    # already have a SecIdentityRef in hand, fab: we'll use that. Otherwise,\n    # we'll take the first certificate (which we assume to be our leaf) and\n    # ask the keychain to give us a SecIdentityRef with that cert's associated\n    # key.\n    #\n    # We'll then return a CFArray containing the trust chain: one\n    # SecIdentityRef and then zero-or-more SecCertificateRef objects. The\n    # responsibility for freeing this CFArray will be with the caller. This\n    # CFArray must remain alive for the entire connection, so in practice it\n    # will be stored with a single SSLSocket, along with the reference to the\n    # keychain.\n    certificates = []\n    identities = []\n\n    # Filter out bad paths.\n    paths = (path for path in paths if path)\n\n    try:\n        for file_path in paths:\n            new_identities, new_certs = _load_items_from_file(keychain, file_path)\n            identities.extend(new_identities)\n            certificates.extend(new_certs)\n\n        # Ok, we have everything. The question is: do we have an identity? If\n        # not, we want to grab one from the first cert we have.\n        if not identities:\n            new_identity = Security.SecIdentityRef()\n            status = Security.SecIdentityCreateWithCertificate(\n                keychain, certificates[0], ctypes.byref(new_identity)\n            )\n            _assert_no_error(status)\n            identities.append(new_identity)\n\n            # We now want to release the original certificate, as we no longer\n            # need it.\n            CoreFoundation.CFRelease(certificates.pop(0))\n\n        # We now need to build a new CFArray that holds the trust chain.\n        trust_chain = CoreFoundation.CFArrayCreateMutable(\n            CoreFoundation.kCFAllocatorDefault,\n            0,\n            ctypes.byref(CoreFoundation.kCFTypeArrayCallBacks),\n        )\n        for item in itertools.chain(identities, certificates):\n            # ArrayAppendValue does a CFRetain on the item. That's fine,\n            # because the finally block will release our other refs to them.\n            CoreFoundation.CFArrayAppendValue(trust_chain, item)\n\n        return trust_chain\n    finally:\n        for obj in itertools.chain(identities, certificates):\n            CoreFoundation.CFRelease(obj)\n\n\nTLS_PROTOCOL_VERSIONS = {\n    \"SSLv2\": (0, 2),\n    \"SSLv3\": (3, 0),\n    \"TLSv1\": (3, 1),\n    \"TLSv1.1\": (3, 2),\n    \"TLSv1.2\": (3, 3),\n}\n\n\ndef _build_tls_unknown_ca_alert(version):\n    \"\"\"\n    Builds a TLS alert record for an unknown CA.\n    \"\"\"\n    ver_maj, ver_min = TLS_PROTOCOL_VERSIONS[version]\n    severity_fatal = 0x02\n    description_unknown_ca = 0x30\n    msg = struct.pack(\">BB\", severity_fatal, description_unknown_ca)\n    msg_len = len(msg)\n    record_type_alert = 0x15\n    record = struct.pack(\">BBBH\", record_type_alert, ver_maj, ver_min, msg_len) + msg\n    return record\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/appengine.py",
    "content": "\"\"\"\nThis module provides a pool manager that uses Google App Engine's\n`URLFetch Service <https://cloud.google.com/appengine/docs/python/urlfetch>`_.\n\nExample usage::\n\n    from pip._vendor.urllib3 import PoolManager\n    from pip._vendor.urllib3.contrib.appengine import AppEngineManager, is_appengine_sandbox\n\n    if is_appengine_sandbox():\n        # AppEngineManager uses AppEngine's URLFetch API behind the scenes\n        http = AppEngineManager()\n    else:\n        # PoolManager uses a socket-level API behind the scenes\n        http = PoolManager()\n\n    r = http.request('GET', 'https://google.com/')\n\nThere are `limitations <https://cloud.google.com/appengine/docs/python/\\\nurlfetch/#Python_Quotas_and_limits>`_ to the URLFetch service and it may not be\nthe best choice for your application. There are three options for using\nurllib3 on Google App Engine:\n\n1. You can use :class:`AppEngineManager` with URLFetch. URLFetch is\n   cost-effective in many circumstances as long as your usage is within the\n   limitations.\n2. You can use a normal :class:`~urllib3.PoolManager` by enabling sockets.\n   Sockets also have `limitations and restrictions\n   <https://cloud.google.com/appengine/docs/python/sockets/\\\n   #limitations-and-restrictions>`_ and have a lower free quota than URLFetch.\n   To use sockets, be sure to specify the following in your ``app.yaml``::\n\n        env_variables:\n            GAE_USE_SOCKETS_HTTPLIB : 'true'\n\n3. If you are using `App Engine Flexible\n<https://cloud.google.com/appengine/docs/flexible/>`_, you can use the standard\n:class:`PoolManager` without any configuration or special environment variables.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport io\nimport logging\nimport warnings\n\nfrom ..exceptions import (\n    HTTPError,\n    HTTPWarning,\n    MaxRetryError,\n    ProtocolError,\n    SSLError,\n    TimeoutError,\n)\nfrom ..packages.six.moves.urllib.parse import urljoin\nfrom ..request import RequestMethods\nfrom ..response import HTTPResponse\nfrom ..util.retry import Retry\nfrom ..util.timeout import Timeout\nfrom . import _appengine_environ\n\ntry:\n    from google.appengine.api import urlfetch\nexcept ImportError:\n    urlfetch = None\n\n\nlog = logging.getLogger(__name__)\n\n\nclass AppEnginePlatformWarning(HTTPWarning):\n    pass\n\n\nclass AppEnginePlatformError(HTTPError):\n    pass\n\n\nclass AppEngineManager(RequestMethods):\n    \"\"\"\n    Connection manager for Google App Engine sandbox applications.\n\n    This manager uses the URLFetch service directly instead of using the\n    emulated httplib, and is subject to URLFetch limitations as described in\n    the App Engine documentation `here\n    <https://cloud.google.com/appengine/docs/python/urlfetch>`_.\n\n    Notably it will raise an :class:`AppEnginePlatformError` if:\n        * URLFetch is not available.\n        * If you attempt to use this on App Engine Flexible, as full socket\n          support is available.\n        * If a request size is more than 10 megabytes.\n        * If a response size is more than 32 megabytes.\n        * If you use an unsupported request method such as OPTIONS.\n\n    Beyond those cases, it will raise normal urllib3 errors.\n    \"\"\"\n\n    def __init__(\n        self,\n        headers=None,\n        retries=None,\n        validate_certificate=True,\n        urlfetch_retries=True,\n    ):\n        if not urlfetch:\n            raise AppEnginePlatformError(\n                \"URLFetch is not available in this environment.\"\n            )\n\n        warnings.warn(\n            \"urllib3 is using URLFetch on Google App Engine sandbox instead \"\n            \"of sockets. To use sockets directly instead of URLFetch see \"\n            \"https://urllib3.readthedocs.io/en/1.26.x/reference/urllib3.contrib.html.\",\n            AppEnginePlatformWarning,\n        )\n\n        RequestMethods.__init__(self, headers)\n        self.validate_certificate = validate_certificate\n        self.urlfetch_retries = urlfetch_retries\n\n        self.retries = retries or Retry.DEFAULT\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        # Return False to re-raise any potential exceptions\n        return False\n\n    def urlopen(\n        self,\n        method,\n        url,\n        body=None,\n        headers=None,\n        retries=None,\n        redirect=True,\n        timeout=Timeout.DEFAULT_TIMEOUT,\n        **response_kw\n    ):\n\n        retries = self._get_retries(retries, redirect)\n\n        try:\n            follow_redirects = redirect and retries.redirect != 0 and retries.total\n            response = urlfetch.fetch(\n                url,\n                payload=body,\n                method=method,\n                headers=headers or {},\n                allow_truncated=False,\n                follow_redirects=self.urlfetch_retries and follow_redirects,\n                deadline=self._get_absolute_timeout(timeout),\n                validate_certificate=self.validate_certificate,\n            )\n        except urlfetch.DeadlineExceededError as e:\n            raise TimeoutError(self, e)\n\n        except urlfetch.InvalidURLError as e:\n            if \"too large\" in str(e):\n                raise AppEnginePlatformError(\n                    \"URLFetch request too large, URLFetch only \"\n                    \"supports requests up to 10mb in size.\",\n                    e,\n                )\n            raise ProtocolError(e)\n\n        except urlfetch.DownloadError as e:\n            if \"Too many redirects\" in str(e):\n                raise MaxRetryError(self, url, reason=e)\n            raise ProtocolError(e)\n\n        except urlfetch.ResponseTooLargeError as e:\n            raise AppEnginePlatformError(\n                \"URLFetch response too large, URLFetch only supports\"\n                \"responses up to 32mb in size.\",\n                e,\n            )\n\n        except urlfetch.SSLCertificateError as e:\n            raise SSLError(e)\n\n        except urlfetch.InvalidMethodError as e:\n            raise AppEnginePlatformError(\n                \"URLFetch does not support method: %s\" % method, e\n            )\n\n        http_response = self._urlfetch_response_to_http_response(\n            response, retries=retries, **response_kw\n        )\n\n        # Handle redirect?\n        redirect_location = redirect and http_response.get_redirect_location()\n        if redirect_location:\n            # Check for redirect response\n            if self.urlfetch_retries and retries.raise_on_redirect:\n                raise MaxRetryError(self, url, \"too many redirects\")\n            else:\n                if http_response.status == 303:\n                    method = \"GET\"\n\n                try:\n                    retries = retries.increment(\n                        method, url, response=http_response, _pool=self\n                    )\n                except MaxRetryError:\n                    if retries.raise_on_redirect:\n                        raise MaxRetryError(self, url, \"too many redirects\")\n                    return http_response\n\n                retries.sleep_for_retry(http_response)\n                log.debug(\"Redirecting %s -> %s\", url, redirect_location)\n                redirect_url = urljoin(url, redirect_location)\n                return self.urlopen(\n                    method,\n                    redirect_url,\n                    body,\n                    headers,\n                    retries=retries,\n                    redirect=redirect,\n                    timeout=timeout,\n                    **response_kw\n                )\n\n        # Check if we should retry the HTTP response.\n        has_retry_after = bool(http_response.getheader(\"Retry-After\"))\n        if retries.is_retry(method, http_response.status, has_retry_after):\n            retries = retries.increment(method, url, response=http_response, _pool=self)\n            log.debug(\"Retry: %s\", url)\n            retries.sleep(http_response)\n            return self.urlopen(\n                method,\n                url,\n                body=body,\n                headers=headers,\n                retries=retries,\n                redirect=redirect,\n                timeout=timeout,\n                **response_kw\n            )\n\n        return http_response\n\n    def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw):\n\n        if is_prod_appengine():\n            # Production GAE handles deflate encoding automatically, but does\n            # not remove the encoding header.\n            content_encoding = urlfetch_resp.headers.get(\"content-encoding\")\n\n            if content_encoding == \"deflate\":\n                del urlfetch_resp.headers[\"content-encoding\"]\n\n        transfer_encoding = urlfetch_resp.headers.get(\"transfer-encoding\")\n        # We have a full response's content,\n        # so let's make sure we don't report ourselves as chunked data.\n        if transfer_encoding == \"chunked\":\n            encodings = transfer_encoding.split(\",\")\n            encodings.remove(\"chunked\")\n            urlfetch_resp.headers[\"transfer-encoding\"] = \",\".join(encodings)\n\n        original_response = HTTPResponse(\n            # In order for decoding to work, we must present the content as\n            # a file-like object.\n            body=io.BytesIO(urlfetch_resp.content),\n            msg=urlfetch_resp.header_msg,\n            headers=urlfetch_resp.headers,\n            status=urlfetch_resp.status_code,\n            **response_kw\n        )\n\n        return HTTPResponse(\n            body=io.BytesIO(urlfetch_resp.content),\n            headers=urlfetch_resp.headers,\n            status=urlfetch_resp.status_code,\n            original_response=original_response,\n            **response_kw\n        )\n\n    def _get_absolute_timeout(self, timeout):\n        if timeout is Timeout.DEFAULT_TIMEOUT:\n            return None  # Defer to URLFetch's default.\n        if isinstance(timeout, Timeout):\n            if timeout._read is not None or timeout._connect is not None:\n                warnings.warn(\n                    \"URLFetch does not support granular timeout settings, \"\n                    \"reverting to total or default URLFetch timeout.\",\n                    AppEnginePlatformWarning,\n                )\n            return timeout.total\n        return timeout\n\n    def _get_retries(self, retries, redirect):\n        if not isinstance(retries, Retry):\n            retries = Retry.from_int(retries, redirect=redirect, default=self.retries)\n\n        if retries.connect or retries.read or retries.redirect:\n            warnings.warn(\n                \"URLFetch only supports total retries and does not \"\n                \"recognize connect, read, or redirect retry parameters.\",\n                AppEnginePlatformWarning,\n            )\n\n        return retries\n\n\n# Alias methods from _appengine_environ to maintain public API interface.\n\nis_appengine = _appengine_environ.is_appengine\nis_appengine_sandbox = _appengine_environ.is_appengine_sandbox\nis_local_appengine = _appengine_environ.is_local_appengine\nis_prod_appengine = _appengine_environ.is_prod_appengine\nis_prod_appengine_mvms = _appengine_environ.is_prod_appengine_mvms\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/ntlmpool.py",
    "content": "\"\"\"\nNTLM authenticating pool, contributed by erikcederstran\n\nIssue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10\n\"\"\"\nfrom __future__ import absolute_import\n\nimport warnings\nfrom logging import getLogger\n\nfrom ntlm import ntlm\n\nfrom .. import HTTPSConnectionPool\nfrom ..packages.six.moves.http_client import HTTPSConnection\n\nwarnings.warn(\n    \"The 'urllib3.contrib.ntlmpool' module is deprecated and will be removed \"\n    \"in urllib3 v2.0 release, urllib3 is not able to support it properly due \"\n    \"to reasons listed in issue: https://github.com/urllib3/urllib3/issues/2282. \"\n    \"If you are a user of this module please comment in the mentioned issue.\",\n    DeprecationWarning,\n)\n\nlog = getLogger(__name__)\n\n\nclass NTLMConnectionPool(HTTPSConnectionPool):\n    \"\"\"\n    Implements an NTLM authentication version of an urllib3 connection pool\n    \"\"\"\n\n    scheme = \"https\"\n\n    def __init__(self, user, pw, authurl, *args, **kwargs):\n        \"\"\"\n        authurl is a random URL on the server that is protected by NTLM.\n        user is the Windows user, probably in the DOMAIN\\\\username format.\n        pw is the password for the user.\n        \"\"\"\n        super(NTLMConnectionPool, self).__init__(*args, **kwargs)\n        self.authurl = authurl\n        self.rawuser = user\n        user_parts = user.split(\"\\\\\", 1)\n        self.domain = user_parts[0].upper()\n        self.user = user_parts[1]\n        self.pw = pw\n\n    def _new_conn(self):\n        # Performs the NTLM handshake that secures the connection. The socket\n        # must be kept open while requests are performed.\n        self.num_connections += 1\n        log.debug(\n            \"Starting NTLM HTTPS connection no. %d: https://%s%s\",\n            self.num_connections,\n            self.host,\n            self.authurl,\n        )\n\n        headers = {\"Connection\": \"Keep-Alive\"}\n        req_header = \"Authorization\"\n        resp_header = \"www-authenticate\"\n\n        conn = HTTPSConnection(host=self.host, port=self.port)\n\n        # Send negotiation message\n        headers[req_header] = \"NTLM %s\" % ntlm.create_NTLM_NEGOTIATE_MESSAGE(\n            self.rawuser\n        )\n        log.debug(\"Request headers: %s\", headers)\n        conn.request(\"GET\", self.authurl, None, headers)\n        res = conn.getresponse()\n        reshdr = dict(res.getheaders())\n        log.debug(\"Response status: %s %s\", res.status, res.reason)\n        log.debug(\"Response headers: %s\", reshdr)\n        log.debug(\"Response data: %s [...]\", res.read(100))\n\n        # Remove the reference to the socket, so that it can not be closed by\n        # the response object (we want to keep the socket open)\n        res.fp = None\n\n        # Server should respond with a challenge message\n        auth_header_values = reshdr[resp_header].split(\", \")\n        auth_header_value = None\n        for s in auth_header_values:\n            if s[:5] == \"NTLM \":\n                auth_header_value = s[5:]\n        if auth_header_value is None:\n            raise Exception(\n                \"Unexpected %s response header: %s\" % (resp_header, reshdr[resp_header])\n            )\n\n        # Send authentication message\n        ServerChallenge, NegotiateFlags = ntlm.parse_NTLM_CHALLENGE_MESSAGE(\n            auth_header_value\n        )\n        auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(\n            ServerChallenge, self.user, self.domain, self.pw, NegotiateFlags\n        )\n        headers[req_header] = \"NTLM %s\" % auth_msg\n        log.debug(\"Request headers: %s\", headers)\n        conn.request(\"GET\", self.authurl, None, headers)\n        res = conn.getresponse()\n        log.debug(\"Response status: %s %s\", res.status, res.reason)\n        log.debug(\"Response headers: %s\", dict(res.getheaders()))\n        log.debug(\"Response data: %s [...]\", res.read()[:100])\n        if res.status != 200:\n            if res.status == 401:\n                raise Exception(\"Server rejected request: wrong username or password\")\n            raise Exception(\"Wrong server response: %s %s\" % (res.status, res.reason))\n\n        res.fp = None\n        log.debug(\"Connection established\")\n        return conn\n\n    def urlopen(\n        self,\n        method,\n        url,\n        body=None,\n        headers=None,\n        retries=3,\n        redirect=True,\n        assert_same_host=True,\n    ):\n        if headers is None:\n            headers = {}\n        headers[\"Connection\"] = \"Keep-Alive\"\n        return super(NTLMConnectionPool, self).urlopen(\n            method, url, body, headers, retries, redirect, assert_same_host\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/pyopenssl.py",
    "content": "\"\"\"\nTLS with SNI_-support for Python 2. Follow these instructions if you would\nlike to verify TLS certificates in Python 2. Note, the default libraries do\n*not* do certificate checking; you need to do additional work to validate\ncertificates yourself.\n\nThis needs the following packages installed:\n\n* `pyOpenSSL`_ (tested with 16.0.0)\n* `cryptography`_ (minimum 1.3.4, from pyopenssl)\n* `idna`_ (minimum 2.0, from cryptography)\n\nHowever, pyopenssl depends on cryptography, which depends on idna, so while we\nuse all three directly here we end up having relatively few packages required.\n\nYou can install them with the following command:\n\n.. code-block:: bash\n\n    $ python -m pip install pyopenssl cryptography idna\n\nTo activate certificate checking, call\n:func:`~urllib3.contrib.pyopenssl.inject_into_urllib3` from your Python code\nbefore you begin making HTTP requests. This can be done in a ``sitecustomize``\nmodule, or at any other time before your application begins using ``urllib3``,\nlike this:\n\n.. code-block:: python\n\n    try:\n        import pip._vendor.urllib3.contrib.pyopenssl as pyopenssl\n        pyopenssl.inject_into_urllib3()\n    except ImportError:\n        pass\n\nNow you can use :mod:`urllib3` as you normally would, and it will support SNI\nwhen the required modules are installed.\n\nActivating this module also has the positive side effect of disabling SSL/TLS\ncompression in Python 2 (see `CRIME attack`_).\n\n.. _sni: https://en.wikipedia.org/wiki/Server_Name_Indication\n.. _crime attack: https://en.wikipedia.org/wiki/CRIME_(security_exploit)\n.. _pyopenssl: https://www.pyopenssl.org\n.. _cryptography: https://cryptography.io\n.. _idna: https://github.com/kjd/idna\n\"\"\"\nfrom __future__ import absolute_import\n\nimport OpenSSL.SSL\nfrom cryptography import x509\nfrom cryptography.hazmat.backends.openssl import backend as openssl_backend\nfrom cryptography.hazmat.backends.openssl.x509 import _Certificate\n\ntry:\n    from cryptography.x509 import UnsupportedExtension\nexcept ImportError:\n    # UnsupportedExtension is gone in cryptography >= 2.1.0\n    class UnsupportedExtension(Exception):\n        pass\n\n\nfrom io import BytesIO\nfrom socket import error as SocketError\nfrom socket import timeout\n\ntry:  # Platform-specific: Python 2\n    from socket import _fileobject\nexcept ImportError:  # Platform-specific: Python 3\n    _fileobject = None\n    from ..packages.backports.makefile import backport_makefile\n\nimport logging\nimport ssl\nimport sys\nimport warnings\n\nfrom .. import util\nfrom ..packages import six\nfrom ..util.ssl_ import PROTOCOL_TLS_CLIENT\n\nwarnings.warn(\n    \"'urllib3.contrib.pyopenssl' module is deprecated and will be removed \"\n    \"in a future release of urllib3 2.x. Read more in this issue: \"\n    \"https://github.com/urllib3/urllib3/issues/2680\",\n    category=DeprecationWarning,\n    stacklevel=2,\n)\n\n__all__ = [\"inject_into_urllib3\", \"extract_from_urllib3\"]\n\n# SNI always works.\nHAS_SNI = True\n\n# Map from urllib3 to PyOpenSSL compatible parameter-values.\n_openssl_versions = {\n    util.PROTOCOL_TLS: OpenSSL.SSL.SSLv23_METHOD,\n    PROTOCOL_TLS_CLIENT: OpenSSL.SSL.SSLv23_METHOD,\n    ssl.PROTOCOL_TLSv1: OpenSSL.SSL.TLSv1_METHOD,\n}\n\nif hasattr(ssl, \"PROTOCOL_SSLv3\") and hasattr(OpenSSL.SSL, \"SSLv3_METHOD\"):\n    _openssl_versions[ssl.PROTOCOL_SSLv3] = OpenSSL.SSL.SSLv3_METHOD\n\nif hasattr(ssl, \"PROTOCOL_TLSv1_1\") and hasattr(OpenSSL.SSL, \"TLSv1_1_METHOD\"):\n    _openssl_versions[ssl.PROTOCOL_TLSv1_1] = OpenSSL.SSL.TLSv1_1_METHOD\n\nif hasattr(ssl, \"PROTOCOL_TLSv1_2\") and hasattr(OpenSSL.SSL, \"TLSv1_2_METHOD\"):\n    _openssl_versions[ssl.PROTOCOL_TLSv1_2] = OpenSSL.SSL.TLSv1_2_METHOD\n\n\n_stdlib_to_openssl_verify = {\n    ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE,\n    ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER,\n    ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER\n    + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT,\n}\n_openssl_to_stdlib_verify = dict((v, k) for k, v in _stdlib_to_openssl_verify.items())\n\n# OpenSSL will only write 16K at a time\nSSL_WRITE_BLOCKSIZE = 16384\n\norig_util_HAS_SNI = util.HAS_SNI\norig_util_SSLContext = util.ssl_.SSLContext\n\n\nlog = logging.getLogger(__name__)\n\n\ndef inject_into_urllib3():\n    \"Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.\"\n\n    _validate_dependencies_met()\n\n    util.SSLContext = PyOpenSSLContext\n    util.ssl_.SSLContext = PyOpenSSLContext\n    util.HAS_SNI = HAS_SNI\n    util.ssl_.HAS_SNI = HAS_SNI\n    util.IS_PYOPENSSL = True\n    util.ssl_.IS_PYOPENSSL = True\n\n\ndef extract_from_urllib3():\n    \"Undo monkey-patching by :func:`inject_into_urllib3`.\"\n\n    util.SSLContext = orig_util_SSLContext\n    util.ssl_.SSLContext = orig_util_SSLContext\n    util.HAS_SNI = orig_util_HAS_SNI\n    util.ssl_.HAS_SNI = orig_util_HAS_SNI\n    util.IS_PYOPENSSL = False\n    util.ssl_.IS_PYOPENSSL = False\n\n\ndef _validate_dependencies_met():\n    \"\"\"\n    Verifies that PyOpenSSL's package-level dependencies have been met.\n    Throws `ImportError` if they are not met.\n    \"\"\"\n    # Method added in `cryptography==1.1`; not available in older versions\n    from cryptography.x509.extensions import Extensions\n\n    if getattr(Extensions, \"get_extension_for_class\", None) is None:\n        raise ImportError(\n            \"'cryptography' module missing required functionality.  \"\n            \"Try upgrading to v1.3.4 or newer.\"\n        )\n\n    # pyOpenSSL 0.14 and above use cryptography for OpenSSL bindings. The _x509\n    # attribute is only present on those versions.\n    from OpenSSL.crypto import X509\n\n    x509 = X509()\n    if getattr(x509, \"_x509\", None) is None:\n        raise ImportError(\n            \"'pyOpenSSL' module missing required functionality. \"\n            \"Try upgrading to v0.14 or newer.\"\n        )\n\n\ndef _dnsname_to_stdlib(name):\n    \"\"\"\n    Converts a dNSName SubjectAlternativeName field to the form used by the\n    standard library on the given Python version.\n\n    Cryptography produces a dNSName as a unicode string that was idna-decoded\n    from ASCII bytes. We need to idna-encode that string to get it back, and\n    then on Python 3 we also need to convert to unicode via UTF-8 (the stdlib\n    uses PyUnicode_FromStringAndSize on it, which decodes via UTF-8).\n\n    If the name cannot be idna-encoded then we return None signalling that\n    the name given should be skipped.\n    \"\"\"\n\n    def idna_encode(name):\n        \"\"\"\n        Borrowed wholesale from the Python Cryptography Project. It turns out\n        that we can't just safely call `idna.encode`: it can explode for\n        wildcard names. This avoids that problem.\n        \"\"\"\n        from pip._vendor import idna\n\n        try:\n            for prefix in [u\"*.\", u\".\"]:\n                if name.startswith(prefix):\n                    name = name[len(prefix) :]\n                    return prefix.encode(\"ascii\") + idna.encode(name)\n            return idna.encode(name)\n        except idna.core.IDNAError:\n            return None\n\n    # Don't send IPv6 addresses through the IDNA encoder.\n    if \":\" in name:\n        return name\n\n    name = idna_encode(name)\n    if name is None:\n        return None\n    elif sys.version_info >= (3, 0):\n        name = name.decode(\"utf-8\")\n    return name\n\n\ndef get_subj_alt_name(peer_cert):\n    \"\"\"\n    Given an PyOpenSSL certificate, provides all the subject alternative names.\n    \"\"\"\n    # Pass the cert to cryptography, which has much better APIs for this.\n    if hasattr(peer_cert, \"to_cryptography\"):\n        cert = peer_cert.to_cryptography()\n    else:\n        # This is technically using private APIs, but should work across all\n        # relevant versions before PyOpenSSL got a proper API for this.\n        cert = _Certificate(openssl_backend, peer_cert._x509)\n\n    # We want to find the SAN extension. Ask Cryptography to locate it (it's\n    # faster than looping in Python)\n    try:\n        ext = cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value\n    except x509.ExtensionNotFound:\n        # No such extension, return the empty list.\n        return []\n    except (\n        x509.DuplicateExtension,\n        UnsupportedExtension,\n        x509.UnsupportedGeneralNameType,\n        UnicodeError,\n    ) as e:\n        # A problem has been found with the quality of the certificate. Assume\n        # no SAN field is present.\n        log.warning(\n            \"A problem was encountered with the certificate that prevented \"\n            \"urllib3 from finding the SubjectAlternativeName field. This can \"\n            \"affect certificate validation. The error was %s\",\n            e,\n        )\n        return []\n\n    # We want to return dNSName and iPAddress fields. We need to cast the IPs\n    # back to strings because the match_hostname function wants them as\n    # strings.\n    # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8\n    # decoded. This is pretty frustrating, but that's what the standard library\n    # does with certificates, and so we need to attempt to do the same.\n    # We also want to skip over names which cannot be idna encoded.\n    names = [\n        (\"DNS\", name)\n        for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName))\n        if name is not None\n    ]\n    names.extend(\n        (\"IP Address\", str(name)) for name in ext.get_values_for_type(x509.IPAddress)\n    )\n\n    return names\n\n\nclass WrappedSocket(object):\n    \"\"\"API-compatibility wrapper for Python OpenSSL's Connection-class.\n\n    Note: _makefile_refs, _drop() and _reuse() are needed for the garbage\n    collector of pypy.\n    \"\"\"\n\n    def __init__(self, connection, socket, suppress_ragged_eofs=True):\n        self.connection = connection\n        self.socket = socket\n        self.suppress_ragged_eofs = suppress_ragged_eofs\n        self._makefile_refs = 0\n        self._closed = False\n\n    def fileno(self):\n        return self.socket.fileno()\n\n    # Copy-pasted from Python 3.5 source code\n    def _decref_socketios(self):\n        if self._makefile_refs > 0:\n            self._makefile_refs -= 1\n        if self._closed:\n            self.close()\n\n    def recv(self, *args, **kwargs):\n        try:\n            data = self.connection.recv(*args, **kwargs)\n        except OpenSSL.SSL.SysCallError as e:\n            if self.suppress_ragged_eofs and e.args == (-1, \"Unexpected EOF\"):\n                return b\"\"\n            else:\n                raise SocketError(str(e))\n        except OpenSSL.SSL.ZeroReturnError:\n            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:\n                return b\"\"\n            else:\n                raise\n        except OpenSSL.SSL.WantReadError:\n            if not util.wait_for_read(self.socket, self.socket.gettimeout()):\n                raise timeout(\"The read operation timed out\")\n            else:\n                return self.recv(*args, **kwargs)\n\n        # TLS 1.3 post-handshake authentication\n        except OpenSSL.SSL.Error as e:\n            raise ssl.SSLError(\"read error: %r\" % e)\n        else:\n            return data\n\n    def recv_into(self, *args, **kwargs):\n        try:\n            return self.connection.recv_into(*args, **kwargs)\n        except OpenSSL.SSL.SysCallError as e:\n            if self.suppress_ragged_eofs and e.args == (-1, \"Unexpected EOF\"):\n                return 0\n            else:\n                raise SocketError(str(e))\n        except OpenSSL.SSL.ZeroReturnError:\n            if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN:\n                return 0\n            else:\n                raise\n        except OpenSSL.SSL.WantReadError:\n            if not util.wait_for_read(self.socket, self.socket.gettimeout()):\n                raise timeout(\"The read operation timed out\")\n            else:\n                return self.recv_into(*args, **kwargs)\n\n        # TLS 1.3 post-handshake authentication\n        except OpenSSL.SSL.Error as e:\n            raise ssl.SSLError(\"read error: %r\" % e)\n\n    def settimeout(self, timeout):\n        return self.socket.settimeout(timeout)\n\n    def _send_until_done(self, data):\n        while True:\n            try:\n                return self.connection.send(data)\n            except OpenSSL.SSL.WantWriteError:\n                if not util.wait_for_write(self.socket, self.socket.gettimeout()):\n                    raise timeout()\n                continue\n            except OpenSSL.SSL.SysCallError as e:\n                raise SocketError(str(e))\n\n    def sendall(self, data):\n        total_sent = 0\n        while total_sent < len(data):\n            sent = self._send_until_done(\n                data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE]\n            )\n            total_sent += sent\n\n    def shutdown(self):\n        # FIXME rethrow compatible exceptions should we ever use this\n        self.connection.shutdown()\n\n    def close(self):\n        if self._makefile_refs < 1:\n            try:\n                self._closed = True\n                return self.connection.close()\n            except OpenSSL.SSL.Error:\n                return\n        else:\n            self._makefile_refs -= 1\n\n    def getpeercert(self, binary_form=False):\n        x509 = self.connection.get_peer_certificate()\n\n        if not x509:\n            return x509\n\n        if binary_form:\n            return OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_ASN1, x509)\n\n        return {\n            \"subject\": (((\"commonName\", x509.get_subject().CN),),),\n            \"subjectAltName\": get_subj_alt_name(x509),\n        }\n\n    def version(self):\n        return self.connection.get_protocol_version_name()\n\n    def _reuse(self):\n        self._makefile_refs += 1\n\n    def _drop(self):\n        if self._makefile_refs < 1:\n            self.close()\n        else:\n            self._makefile_refs -= 1\n\n\nif _fileobject:  # Platform-specific: Python 2\n\n    def makefile(self, mode, bufsize=-1):\n        self._makefile_refs += 1\n        return _fileobject(self, mode, bufsize, close=True)\n\nelse:  # Platform-specific: Python 3\n    makefile = backport_makefile\n\nWrappedSocket.makefile = makefile\n\n\nclass PyOpenSSLContext(object):\n    \"\"\"\n    I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible\n    for translating the interface of the standard library ``SSLContext`` object\n    to calls into PyOpenSSL.\n    \"\"\"\n\n    def __init__(self, protocol):\n        self.protocol = _openssl_versions[protocol]\n        self._ctx = OpenSSL.SSL.Context(self.protocol)\n        self._options = 0\n        self.check_hostname = False\n\n    @property\n    def options(self):\n        return self._options\n\n    @options.setter\n    def options(self, value):\n        self._options = value\n        self._ctx.set_options(value)\n\n    @property\n    def verify_mode(self):\n        return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()]\n\n    @verify_mode.setter\n    def verify_mode(self, value):\n        self._ctx.set_verify(_stdlib_to_openssl_verify[value], _verify_callback)\n\n    def set_default_verify_paths(self):\n        self._ctx.set_default_verify_paths()\n\n    def set_ciphers(self, ciphers):\n        if isinstance(ciphers, six.text_type):\n            ciphers = ciphers.encode(\"utf-8\")\n        self._ctx.set_cipher_list(ciphers)\n\n    def load_verify_locations(self, cafile=None, capath=None, cadata=None):\n        if cafile is not None:\n            cafile = cafile.encode(\"utf-8\")\n        if capath is not None:\n            capath = capath.encode(\"utf-8\")\n        try:\n            self._ctx.load_verify_locations(cafile, capath)\n            if cadata is not None:\n                self._ctx.load_verify_locations(BytesIO(cadata))\n        except OpenSSL.SSL.Error as e:\n            raise ssl.SSLError(\"unable to load trusted certificates: %r\" % e)\n\n    def load_cert_chain(self, certfile, keyfile=None, password=None):\n        self._ctx.use_certificate_chain_file(certfile)\n        if password is not None:\n            if not isinstance(password, six.binary_type):\n                password = password.encode(\"utf-8\")\n            self._ctx.set_passwd_cb(lambda *_: password)\n        self._ctx.use_privatekey_file(keyfile or certfile)\n\n    def set_alpn_protocols(self, protocols):\n        protocols = [six.ensure_binary(p) for p in protocols]\n        return self._ctx.set_alpn_protos(protocols)\n\n    def wrap_socket(\n        self,\n        sock,\n        server_side=False,\n        do_handshake_on_connect=True,\n        suppress_ragged_eofs=True,\n        server_hostname=None,\n    ):\n        cnx = OpenSSL.SSL.Connection(self._ctx, sock)\n\n        if isinstance(server_hostname, six.text_type):  # Platform-specific: Python 3\n            server_hostname = server_hostname.encode(\"utf-8\")\n\n        if server_hostname is not None:\n            cnx.set_tlsext_host_name(server_hostname)\n\n        cnx.set_connect_state()\n\n        while True:\n            try:\n                cnx.do_handshake()\n            except OpenSSL.SSL.WantReadError:\n                if not util.wait_for_read(sock, sock.gettimeout()):\n                    raise timeout(\"select timed out\")\n                continue\n            except OpenSSL.SSL.Error as e:\n                raise ssl.SSLError(\"bad handshake: %r\" % e)\n            break\n\n        return WrappedSocket(cnx, sock)\n\n\ndef _verify_callback(cnx, x509, err_no, err_depth, return_code):\n    return err_no == 0\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/securetransport.py",
    "content": "\"\"\"\nSecureTranport support for urllib3 via ctypes.\n\nThis makes platform-native TLS available to urllib3 users on macOS without the\nuse of a compiler. This is an important feature because the Python Package\nIndex is moving to become a TLSv1.2-or-higher server, and the default OpenSSL\nthat ships with macOS is not capable of doing TLSv1.2. The only way to resolve\nthis is to give macOS users an alternative solution to the problem, and that\nsolution is to use SecureTransport.\n\nWe use ctypes here because this solution must not require a compiler. That's\nbecause pip is not allowed to require a compiler either.\n\nThis is not intended to be a seriously long-term solution to this problem.\nThe hope is that PEP 543 will eventually solve this issue for us, at which\npoint we can retire this contrib module. But in the short term, we need to\nsolve the impending tire fire that is Python on Mac without this kind of\ncontrib module. So...here we are.\n\nTo use this module, simply import and inject it::\n\n    import pip._vendor.urllib3.contrib.securetransport as securetransport\n    securetransport.inject_into_urllib3()\n\nHappy TLSing!\n\nThis code is a bastardised version of the code found in Will Bond's oscrypto\nlibrary. An enormous debt is owed to him for blazing this trail for us. For\nthat reason, this code should be considered to be covered both by urllib3's\nlicense and by oscrypto's:\n\n.. code-block::\n\n    Copyright (c) 2015-2016 Will Bond <will@wbond.net>\n\n    Permission is hereby granted, free of charge, to any person obtaining a\n    copy of this software and associated documentation files (the \"Software\"),\n    to deal in the Software without restriction, including without limitation\n    the rights to use, copy, modify, merge, publish, distribute, sublicense,\n    and/or sell copies of the Software, and to permit persons to whom the\n    Software is furnished to do so, subject to the following conditions:\n\n    The above copyright notice and this permission notice shall be included in\n    all copies or substantial portions of the Software.\n\n    THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n    DEALINGS IN THE SOFTWARE.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport contextlib\nimport ctypes\nimport errno\nimport os.path\nimport shutil\nimport socket\nimport ssl\nimport struct\nimport threading\nimport weakref\n\nfrom pip._vendor import six\n\nfrom .. import util\nfrom ..util.ssl_ import PROTOCOL_TLS_CLIENT\nfrom ._securetransport.bindings import CoreFoundation, Security, SecurityConst\nfrom ._securetransport.low_level import (\n    _assert_no_error,\n    _build_tls_unknown_ca_alert,\n    _cert_array_from_pem,\n    _create_cfstring_array,\n    _load_client_cert_chain,\n    _temporary_keychain,\n)\n\ntry:  # Platform-specific: Python 2\n    from socket import _fileobject\nexcept ImportError:  # Platform-specific: Python 3\n    _fileobject = None\n    from ..packages.backports.makefile import backport_makefile\n\n__all__ = [\"inject_into_urllib3\", \"extract_from_urllib3\"]\n\n# SNI always works\nHAS_SNI = True\n\norig_util_HAS_SNI = util.HAS_SNI\norig_util_SSLContext = util.ssl_.SSLContext\n\n# This dictionary is used by the read callback to obtain a handle to the\n# calling wrapped socket. This is a pretty silly approach, but for now it'll\n# do. I feel like I should be able to smuggle a handle to the wrapped socket\n# directly in the SSLConnectionRef, but for now this approach will work I\n# guess.\n#\n# We need to lock around this structure for inserts, but we don't do it for\n# reads/writes in the callbacks. The reasoning here goes as follows:\n#\n#    1. It is not possible to call into the callbacks before the dictionary is\n#       populated, so once in the callback the id must be in the dictionary.\n#    2. The callbacks don't mutate the dictionary, they only read from it, and\n#       so cannot conflict with any of the insertions.\n#\n# This is good: if we had to lock in the callbacks we'd drastically slow down\n# the performance of this code.\n_connection_refs = weakref.WeakValueDictionary()\n_connection_ref_lock = threading.Lock()\n\n# Limit writes to 16kB. This is OpenSSL's limit, but we'll cargo-cult it over\n# for no better reason than we need *a* limit, and this one is right there.\nSSL_WRITE_BLOCKSIZE = 16384\n\n# This is our equivalent of util.ssl_.DEFAULT_CIPHERS, but expanded out to\n# individual cipher suites. We need to do this because this is how\n# SecureTransport wants them.\nCIPHER_SUITES = [\n    SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,\n    SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,\n    SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,\n    SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,\n    SecurityConst.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,\n    SecurityConst.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,\n    SecurityConst.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,\n    SecurityConst.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,\n    SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,\n    SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,\n    SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,\n    SecurityConst.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,\n    SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,\n    SecurityConst.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,\n    SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,\n    SecurityConst.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,\n    SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,\n    SecurityConst.TLS_DHE_RSA_WITH_AES_256_CBC_SHA,\n    SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,\n    SecurityConst.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,\n    SecurityConst.TLS_AES_256_GCM_SHA384,\n    SecurityConst.TLS_AES_128_GCM_SHA256,\n    SecurityConst.TLS_RSA_WITH_AES_256_GCM_SHA384,\n    SecurityConst.TLS_RSA_WITH_AES_128_GCM_SHA256,\n    SecurityConst.TLS_AES_128_CCM_8_SHA256,\n    SecurityConst.TLS_AES_128_CCM_SHA256,\n    SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA256,\n    SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA256,\n    SecurityConst.TLS_RSA_WITH_AES_256_CBC_SHA,\n    SecurityConst.TLS_RSA_WITH_AES_128_CBC_SHA,\n]\n\n# Basically this is simple: for PROTOCOL_SSLv23 we turn it into a low of\n# TLSv1 and a high of TLSv1.2. For everything else, we pin to that version.\n# TLSv1 to 1.2 are supported on macOS 10.8+\n_protocol_to_min_max = {\n    util.PROTOCOL_TLS: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12),\n    PROTOCOL_TLS_CLIENT: (SecurityConst.kTLSProtocol1, SecurityConst.kTLSProtocol12),\n}\n\nif hasattr(ssl, \"PROTOCOL_SSLv2\"):\n    _protocol_to_min_max[ssl.PROTOCOL_SSLv2] = (\n        SecurityConst.kSSLProtocol2,\n        SecurityConst.kSSLProtocol2,\n    )\nif hasattr(ssl, \"PROTOCOL_SSLv3\"):\n    _protocol_to_min_max[ssl.PROTOCOL_SSLv3] = (\n        SecurityConst.kSSLProtocol3,\n        SecurityConst.kSSLProtocol3,\n    )\nif hasattr(ssl, \"PROTOCOL_TLSv1\"):\n    _protocol_to_min_max[ssl.PROTOCOL_TLSv1] = (\n        SecurityConst.kTLSProtocol1,\n        SecurityConst.kTLSProtocol1,\n    )\nif hasattr(ssl, \"PROTOCOL_TLSv1_1\"):\n    _protocol_to_min_max[ssl.PROTOCOL_TLSv1_1] = (\n        SecurityConst.kTLSProtocol11,\n        SecurityConst.kTLSProtocol11,\n    )\nif hasattr(ssl, \"PROTOCOL_TLSv1_2\"):\n    _protocol_to_min_max[ssl.PROTOCOL_TLSv1_2] = (\n        SecurityConst.kTLSProtocol12,\n        SecurityConst.kTLSProtocol12,\n    )\n\n\ndef inject_into_urllib3():\n    \"\"\"\n    Monkey-patch urllib3 with SecureTransport-backed SSL-support.\n    \"\"\"\n    util.SSLContext = SecureTransportContext\n    util.ssl_.SSLContext = SecureTransportContext\n    util.HAS_SNI = HAS_SNI\n    util.ssl_.HAS_SNI = HAS_SNI\n    util.IS_SECURETRANSPORT = True\n    util.ssl_.IS_SECURETRANSPORT = True\n\n\ndef extract_from_urllib3():\n    \"\"\"\n    Undo monkey-patching by :func:`inject_into_urllib3`.\n    \"\"\"\n    util.SSLContext = orig_util_SSLContext\n    util.ssl_.SSLContext = orig_util_SSLContext\n    util.HAS_SNI = orig_util_HAS_SNI\n    util.ssl_.HAS_SNI = orig_util_HAS_SNI\n    util.IS_SECURETRANSPORT = False\n    util.ssl_.IS_SECURETRANSPORT = False\n\n\ndef _read_callback(connection_id, data_buffer, data_length_pointer):\n    \"\"\"\n    SecureTransport read callback. This is called by ST to request that data\n    be returned from the socket.\n    \"\"\"\n    wrapped_socket = None\n    try:\n        wrapped_socket = _connection_refs.get(connection_id)\n        if wrapped_socket is None:\n            return SecurityConst.errSSLInternal\n        base_socket = wrapped_socket.socket\n\n        requested_length = data_length_pointer[0]\n\n        timeout = wrapped_socket.gettimeout()\n        error = None\n        read_count = 0\n\n        try:\n            while read_count < requested_length:\n                if timeout is None or timeout >= 0:\n                    if not util.wait_for_read(base_socket, timeout):\n                        raise socket.error(errno.EAGAIN, \"timed out\")\n\n                remaining = requested_length - read_count\n                buffer = (ctypes.c_char * remaining).from_address(\n                    data_buffer + read_count\n                )\n                chunk_size = base_socket.recv_into(buffer, remaining)\n                read_count += chunk_size\n                if not chunk_size:\n                    if not read_count:\n                        return SecurityConst.errSSLClosedGraceful\n                    break\n        except (socket.error) as e:\n            error = e.errno\n\n            if error is not None and error != errno.EAGAIN:\n                data_length_pointer[0] = read_count\n                if error == errno.ECONNRESET or error == errno.EPIPE:\n                    return SecurityConst.errSSLClosedAbort\n                raise\n\n        data_length_pointer[0] = read_count\n\n        if read_count != requested_length:\n            return SecurityConst.errSSLWouldBlock\n\n        return 0\n    except Exception as e:\n        if wrapped_socket is not None:\n            wrapped_socket._exception = e\n        return SecurityConst.errSSLInternal\n\n\ndef _write_callback(connection_id, data_buffer, data_length_pointer):\n    \"\"\"\n    SecureTransport write callback. This is called by ST to request that data\n    actually be sent on the network.\n    \"\"\"\n    wrapped_socket = None\n    try:\n        wrapped_socket = _connection_refs.get(connection_id)\n        if wrapped_socket is None:\n            return SecurityConst.errSSLInternal\n        base_socket = wrapped_socket.socket\n\n        bytes_to_write = data_length_pointer[0]\n        data = ctypes.string_at(data_buffer, bytes_to_write)\n\n        timeout = wrapped_socket.gettimeout()\n        error = None\n        sent = 0\n\n        try:\n            while sent < bytes_to_write:\n                if timeout is None or timeout >= 0:\n                    if not util.wait_for_write(base_socket, timeout):\n                        raise socket.error(errno.EAGAIN, \"timed out\")\n                chunk_sent = base_socket.send(data)\n                sent += chunk_sent\n\n                # This has some needless copying here, but I'm not sure there's\n                # much value in optimising this data path.\n                data = data[chunk_sent:]\n        except (socket.error) as e:\n            error = e.errno\n\n            if error is not None and error != errno.EAGAIN:\n                data_length_pointer[0] = sent\n                if error == errno.ECONNRESET or error == errno.EPIPE:\n                    return SecurityConst.errSSLClosedAbort\n                raise\n\n        data_length_pointer[0] = sent\n\n        if sent != bytes_to_write:\n            return SecurityConst.errSSLWouldBlock\n\n        return 0\n    except Exception as e:\n        if wrapped_socket is not None:\n            wrapped_socket._exception = e\n        return SecurityConst.errSSLInternal\n\n\n# We need to keep these two objects references alive: if they get GC'd while\n# in use then SecureTransport could attempt to call a function that is in freed\n# memory. That would be...uh...bad. Yeah, that's the word. Bad.\n_read_callback_pointer = Security.SSLReadFunc(_read_callback)\n_write_callback_pointer = Security.SSLWriteFunc(_write_callback)\n\n\nclass WrappedSocket(object):\n    \"\"\"\n    API-compatibility wrapper for Python's OpenSSL wrapped socket object.\n\n    Note: _makefile_refs, _drop(), and _reuse() are needed for the garbage\n    collector of PyPy.\n    \"\"\"\n\n    def __init__(self, socket):\n        self.socket = socket\n        self.context = None\n        self._makefile_refs = 0\n        self._closed = False\n        self._exception = None\n        self._keychain = None\n        self._keychain_dir = None\n        self._client_cert_chain = None\n\n        # We save off the previously-configured timeout and then set it to\n        # zero. This is done because we use select and friends to handle the\n        # timeouts, but if we leave the timeout set on the lower socket then\n        # Python will \"kindly\" call select on that socket again for us. Avoid\n        # that by forcing the timeout to zero.\n        self._timeout = self.socket.gettimeout()\n        self.socket.settimeout(0)\n\n    @contextlib.contextmanager\n    def _raise_on_error(self):\n        \"\"\"\n        A context manager that can be used to wrap calls that do I/O from\n        SecureTransport. If any of the I/O callbacks hit an exception, this\n        context manager will correctly propagate the exception after the fact.\n        This avoids silently swallowing those exceptions.\n\n        It also correctly forces the socket closed.\n        \"\"\"\n        self._exception = None\n\n        # We explicitly don't catch around this yield because in the unlikely\n        # event that an exception was hit in the block we don't want to swallow\n        # it.\n        yield\n        if self._exception is not None:\n            exception, self._exception = self._exception, None\n            self.close()\n            raise exception\n\n    def _set_ciphers(self):\n        \"\"\"\n        Sets up the allowed ciphers. By default this matches the set in\n        util.ssl_.DEFAULT_CIPHERS, at least as supported by macOS. This is done\n        custom and doesn't allow changing at this time, mostly because parsing\n        OpenSSL cipher strings is going to be a freaking nightmare.\n        \"\"\"\n        ciphers = (Security.SSLCipherSuite * len(CIPHER_SUITES))(*CIPHER_SUITES)\n        result = Security.SSLSetEnabledCiphers(\n            self.context, ciphers, len(CIPHER_SUITES)\n        )\n        _assert_no_error(result)\n\n    def _set_alpn_protocols(self, protocols):\n        \"\"\"\n        Sets up the ALPN protocols on the context.\n        \"\"\"\n        if not protocols:\n            return\n        protocols_arr = _create_cfstring_array(protocols)\n        try:\n            result = Security.SSLSetALPNProtocols(self.context, protocols_arr)\n            _assert_no_error(result)\n        finally:\n            CoreFoundation.CFRelease(protocols_arr)\n\n    def _custom_validate(self, verify, trust_bundle):\n        \"\"\"\n        Called when we have set custom validation. We do this in two cases:\n        first, when cert validation is entirely disabled; and second, when\n        using a custom trust DB.\n        Raises an SSLError if the connection is not trusted.\n        \"\"\"\n        # If we disabled cert validation, just say: cool.\n        if not verify:\n            return\n\n        successes = (\n            SecurityConst.kSecTrustResultUnspecified,\n            SecurityConst.kSecTrustResultProceed,\n        )\n        try:\n            trust_result = self._evaluate_trust(trust_bundle)\n            if trust_result in successes:\n                return\n            reason = \"error code: %d\" % (trust_result,)\n        except Exception as e:\n            # Do not trust on error\n            reason = \"exception: %r\" % (e,)\n\n        # SecureTransport does not send an alert nor shuts down the connection.\n        rec = _build_tls_unknown_ca_alert(self.version())\n        self.socket.sendall(rec)\n        # close the connection immediately\n        # l_onoff = 1, activate linger\n        # l_linger = 0, linger for 0 seoncds\n        opts = struct.pack(\"ii\", 1, 0)\n        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, opts)\n        self.close()\n        raise ssl.SSLError(\"certificate verify failed, %s\" % reason)\n\n    def _evaluate_trust(self, trust_bundle):\n        # We want data in memory, so load it up.\n        if os.path.isfile(trust_bundle):\n            with open(trust_bundle, \"rb\") as f:\n                trust_bundle = f.read()\n\n        cert_array = None\n        trust = Security.SecTrustRef()\n\n        try:\n            # Get a CFArray that contains the certs we want.\n            cert_array = _cert_array_from_pem(trust_bundle)\n\n            # Ok, now the hard part. We want to get the SecTrustRef that ST has\n            # created for this connection, shove our CAs into it, tell ST to\n            # ignore everything else it knows, and then ask if it can build a\n            # chain. This is a buuuunch of code.\n            result = Security.SSLCopyPeerTrust(self.context, ctypes.byref(trust))\n            _assert_no_error(result)\n            if not trust:\n                raise ssl.SSLError(\"Failed to copy trust reference\")\n\n            result = Security.SecTrustSetAnchorCertificates(trust, cert_array)\n            _assert_no_error(result)\n\n            result = Security.SecTrustSetAnchorCertificatesOnly(trust, True)\n            _assert_no_error(result)\n\n            trust_result = Security.SecTrustResultType()\n            result = Security.SecTrustEvaluate(trust, ctypes.byref(trust_result))\n            _assert_no_error(result)\n        finally:\n            if trust:\n                CoreFoundation.CFRelease(trust)\n\n            if cert_array is not None:\n                CoreFoundation.CFRelease(cert_array)\n\n        return trust_result.value\n\n    def handshake(\n        self,\n        server_hostname,\n        verify,\n        trust_bundle,\n        min_version,\n        max_version,\n        client_cert,\n        client_key,\n        client_key_passphrase,\n        alpn_protocols,\n    ):\n        \"\"\"\n        Actually performs the TLS handshake. This is run automatically by\n        wrapped socket, and shouldn't be needed in user code.\n        \"\"\"\n        # First, we do the initial bits of connection setup. We need to create\n        # a context, set its I/O funcs, and set the connection reference.\n        self.context = Security.SSLCreateContext(\n            None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType\n        )\n        result = Security.SSLSetIOFuncs(\n            self.context, _read_callback_pointer, _write_callback_pointer\n        )\n        _assert_no_error(result)\n\n        # Here we need to compute the handle to use. We do this by taking the\n        # id of self modulo 2**31 - 1. If this is already in the dictionary, we\n        # just keep incrementing by one until we find a free space.\n        with _connection_ref_lock:\n            handle = id(self) % 2147483647\n            while handle in _connection_refs:\n                handle = (handle + 1) % 2147483647\n            _connection_refs[handle] = self\n\n        result = Security.SSLSetConnection(self.context, handle)\n        _assert_no_error(result)\n\n        # If we have a server hostname, we should set that too.\n        if server_hostname:\n            if not isinstance(server_hostname, bytes):\n                server_hostname = server_hostname.encode(\"utf-8\")\n\n            result = Security.SSLSetPeerDomainName(\n                self.context, server_hostname, len(server_hostname)\n            )\n            _assert_no_error(result)\n\n        # Setup the ciphers.\n        self._set_ciphers()\n\n        # Setup the ALPN protocols.\n        self._set_alpn_protocols(alpn_protocols)\n\n        # Set the minimum and maximum TLS versions.\n        result = Security.SSLSetProtocolVersionMin(self.context, min_version)\n        _assert_no_error(result)\n\n        result = Security.SSLSetProtocolVersionMax(self.context, max_version)\n        _assert_no_error(result)\n\n        # If there's a trust DB, we need to use it. We do that by telling\n        # SecureTransport to break on server auth. We also do that if we don't\n        # want to validate the certs at all: we just won't actually do any\n        # authing in that case.\n        if not verify or trust_bundle is not None:\n            result = Security.SSLSetSessionOption(\n                self.context, SecurityConst.kSSLSessionOptionBreakOnServerAuth, True\n            )\n            _assert_no_error(result)\n\n        # If there's a client cert, we need to use it.\n        if client_cert:\n            self._keychain, self._keychain_dir = _temporary_keychain()\n            self._client_cert_chain = _load_client_cert_chain(\n                self._keychain, client_cert, client_key\n            )\n            result = Security.SSLSetCertificate(self.context, self._client_cert_chain)\n            _assert_no_error(result)\n\n        while True:\n            with self._raise_on_error():\n                result = Security.SSLHandshake(self.context)\n\n                if result == SecurityConst.errSSLWouldBlock:\n                    raise socket.timeout(\"handshake timed out\")\n                elif result == SecurityConst.errSSLServerAuthCompleted:\n                    self._custom_validate(verify, trust_bundle)\n                    continue\n                else:\n                    _assert_no_error(result)\n                    break\n\n    def fileno(self):\n        return self.socket.fileno()\n\n    # Copy-pasted from Python 3.5 source code\n    def _decref_socketios(self):\n        if self._makefile_refs > 0:\n            self._makefile_refs -= 1\n        if self._closed:\n            self.close()\n\n    def recv(self, bufsiz):\n        buffer = ctypes.create_string_buffer(bufsiz)\n        bytes_read = self.recv_into(buffer, bufsiz)\n        data = buffer[:bytes_read]\n        return data\n\n    def recv_into(self, buffer, nbytes=None):\n        # Read short on EOF.\n        if self._closed:\n            return 0\n\n        if nbytes is None:\n            nbytes = len(buffer)\n\n        buffer = (ctypes.c_char * nbytes).from_buffer(buffer)\n        processed_bytes = ctypes.c_size_t(0)\n\n        with self._raise_on_error():\n            result = Security.SSLRead(\n                self.context, buffer, nbytes, ctypes.byref(processed_bytes)\n            )\n\n        # There are some result codes that we want to treat as \"not always\n        # errors\". Specifically, those are errSSLWouldBlock,\n        # errSSLClosedGraceful, and errSSLClosedNoNotify.\n        if result == SecurityConst.errSSLWouldBlock:\n            # If we didn't process any bytes, then this was just a time out.\n            # However, we can get errSSLWouldBlock in situations when we *did*\n            # read some data, and in those cases we should just read \"short\"\n            # and return.\n            if processed_bytes.value == 0:\n                # Timed out, no data read.\n                raise socket.timeout(\"recv timed out\")\n        elif result in (\n            SecurityConst.errSSLClosedGraceful,\n            SecurityConst.errSSLClosedNoNotify,\n        ):\n            # The remote peer has closed this connection. We should do so as\n            # well. Note that we don't actually return here because in\n            # principle this could actually be fired along with return data.\n            # It's unlikely though.\n            self.close()\n        else:\n            _assert_no_error(result)\n\n        # Ok, we read and probably succeeded. We should return whatever data\n        # was actually read.\n        return processed_bytes.value\n\n    def settimeout(self, timeout):\n        self._timeout = timeout\n\n    def gettimeout(self):\n        return self._timeout\n\n    def send(self, data):\n        processed_bytes = ctypes.c_size_t(0)\n\n        with self._raise_on_error():\n            result = Security.SSLWrite(\n                self.context, data, len(data), ctypes.byref(processed_bytes)\n            )\n\n        if result == SecurityConst.errSSLWouldBlock and processed_bytes.value == 0:\n            # Timed out\n            raise socket.timeout(\"send timed out\")\n        else:\n            _assert_no_error(result)\n\n        # We sent, and probably succeeded. Tell them how much we sent.\n        return processed_bytes.value\n\n    def sendall(self, data):\n        total_sent = 0\n        while total_sent < len(data):\n            sent = self.send(data[total_sent : total_sent + SSL_WRITE_BLOCKSIZE])\n            total_sent += sent\n\n    def shutdown(self):\n        with self._raise_on_error():\n            Security.SSLClose(self.context)\n\n    def close(self):\n        # TODO: should I do clean shutdown here? Do I have to?\n        if self._makefile_refs < 1:\n            self._closed = True\n            if self.context:\n                CoreFoundation.CFRelease(self.context)\n                self.context = None\n            if self._client_cert_chain:\n                CoreFoundation.CFRelease(self._client_cert_chain)\n                self._client_cert_chain = None\n            if self._keychain:\n                Security.SecKeychainDelete(self._keychain)\n                CoreFoundation.CFRelease(self._keychain)\n                shutil.rmtree(self._keychain_dir)\n                self._keychain = self._keychain_dir = None\n            return self.socket.close()\n        else:\n            self._makefile_refs -= 1\n\n    def getpeercert(self, binary_form=False):\n        # Urgh, annoying.\n        #\n        # Here's how we do this:\n        #\n        # 1. Call SSLCopyPeerTrust to get hold of the trust object for this\n        #    connection.\n        # 2. Call SecTrustGetCertificateAtIndex for index 0 to get the leaf.\n        # 3. To get the CN, call SecCertificateCopyCommonName and process that\n        #    string so that it's of the appropriate type.\n        # 4. To get the SAN, we need to do something a bit more complex:\n        #    a. Call SecCertificateCopyValues to get the data, requesting\n        #       kSecOIDSubjectAltName.\n        #    b. Mess about with this dictionary to try to get the SANs out.\n        #\n        # This is gross. Really gross. It's going to be a few hundred LoC extra\n        # just to repeat something that SecureTransport can *already do*. So my\n        # operating assumption at this time is that what we want to do is\n        # instead to just flag to urllib3 that it shouldn't do its own hostname\n        # validation when using SecureTransport.\n        if not binary_form:\n            raise ValueError(\"SecureTransport only supports dumping binary certs\")\n        trust = Security.SecTrustRef()\n        certdata = None\n        der_bytes = None\n\n        try:\n            # Grab the trust store.\n            result = Security.SSLCopyPeerTrust(self.context, ctypes.byref(trust))\n            _assert_no_error(result)\n            if not trust:\n                # Probably we haven't done the handshake yet. No biggie.\n                return None\n\n            cert_count = Security.SecTrustGetCertificateCount(trust)\n            if not cert_count:\n                # Also a case that might happen if we haven't handshaked.\n                # Handshook? Handshaken?\n                return None\n\n            leaf = Security.SecTrustGetCertificateAtIndex(trust, 0)\n            assert leaf\n\n            # Ok, now we want the DER bytes.\n            certdata = Security.SecCertificateCopyData(leaf)\n            assert certdata\n\n            data_length = CoreFoundation.CFDataGetLength(certdata)\n            data_buffer = CoreFoundation.CFDataGetBytePtr(certdata)\n            der_bytes = ctypes.string_at(data_buffer, data_length)\n        finally:\n            if certdata:\n                CoreFoundation.CFRelease(certdata)\n            if trust:\n                CoreFoundation.CFRelease(trust)\n\n        return der_bytes\n\n    def version(self):\n        protocol = Security.SSLProtocol()\n        result = Security.SSLGetNegotiatedProtocolVersion(\n            self.context, ctypes.byref(protocol)\n        )\n        _assert_no_error(result)\n        if protocol.value == SecurityConst.kTLSProtocol13:\n            raise ssl.SSLError(\"SecureTransport does not support TLS 1.3\")\n        elif protocol.value == SecurityConst.kTLSProtocol12:\n            return \"TLSv1.2\"\n        elif protocol.value == SecurityConst.kTLSProtocol11:\n            return \"TLSv1.1\"\n        elif protocol.value == SecurityConst.kTLSProtocol1:\n            return \"TLSv1\"\n        elif protocol.value == SecurityConst.kSSLProtocol3:\n            return \"SSLv3\"\n        elif protocol.value == SecurityConst.kSSLProtocol2:\n            return \"SSLv2\"\n        else:\n            raise ssl.SSLError(\"Unknown TLS version: %r\" % protocol)\n\n    def _reuse(self):\n        self._makefile_refs += 1\n\n    def _drop(self):\n        if self._makefile_refs < 1:\n            self.close()\n        else:\n            self._makefile_refs -= 1\n\n\nif _fileobject:  # Platform-specific: Python 2\n\n    def makefile(self, mode, bufsize=-1):\n        self._makefile_refs += 1\n        return _fileobject(self, mode, bufsize, close=True)\n\nelse:  # Platform-specific: Python 3\n\n    def makefile(self, mode=\"r\", buffering=None, *args, **kwargs):\n        # We disable buffering with SecureTransport because it conflicts with\n        # the buffering that ST does internally (see issue #1153 for more).\n        buffering = 0\n        return backport_makefile(self, mode, buffering, *args, **kwargs)\n\n\nWrappedSocket.makefile = makefile\n\n\nclass SecureTransportContext(object):\n    \"\"\"\n    I am a wrapper class for the SecureTransport library, to translate the\n    interface of the standard library ``SSLContext`` object to calls into\n    SecureTransport.\n    \"\"\"\n\n    def __init__(self, protocol):\n        self._min_version, self._max_version = _protocol_to_min_max[protocol]\n        self._options = 0\n        self._verify = False\n        self._trust_bundle = None\n        self._client_cert = None\n        self._client_key = None\n        self._client_key_passphrase = None\n        self._alpn_protocols = None\n\n    @property\n    def check_hostname(self):\n        \"\"\"\n        SecureTransport cannot have its hostname checking disabled. For more,\n        see the comment on getpeercert() in this file.\n        \"\"\"\n        return True\n\n    @check_hostname.setter\n    def check_hostname(self, value):\n        \"\"\"\n        SecureTransport cannot have its hostname checking disabled. For more,\n        see the comment on getpeercert() in this file.\n        \"\"\"\n        pass\n\n    @property\n    def options(self):\n        # TODO: Well, crap.\n        #\n        # So this is the bit of the code that is the most likely to cause us\n        # trouble. Essentially we need to enumerate all of the SSL options that\n        # users might want to use and try to see if we can sensibly translate\n        # them, or whether we should just ignore them.\n        return self._options\n\n    @options.setter\n    def options(self, value):\n        # TODO: Update in line with above.\n        self._options = value\n\n    @property\n    def verify_mode(self):\n        return ssl.CERT_REQUIRED if self._verify else ssl.CERT_NONE\n\n    @verify_mode.setter\n    def verify_mode(self, value):\n        self._verify = True if value == ssl.CERT_REQUIRED else False\n\n    def set_default_verify_paths(self):\n        # So, this has to do something a bit weird. Specifically, what it does\n        # is nothing.\n        #\n        # This means that, if we had previously had load_verify_locations\n        # called, this does not undo that. We need to do that because it turns\n        # out that the rest of the urllib3 code will attempt to load the\n        # default verify paths if it hasn't been told about any paths, even if\n        # the context itself was sometime earlier. We resolve that by just\n        # ignoring it.\n        pass\n\n    def load_default_certs(self):\n        return self.set_default_verify_paths()\n\n    def set_ciphers(self, ciphers):\n        # For now, we just require the default cipher string.\n        if ciphers != util.ssl_.DEFAULT_CIPHERS:\n            raise ValueError(\"SecureTransport doesn't support custom cipher strings\")\n\n    def load_verify_locations(self, cafile=None, capath=None, cadata=None):\n        # OK, we only really support cadata and cafile.\n        if capath is not None:\n            raise ValueError(\"SecureTransport does not support cert directories\")\n\n        # Raise if cafile does not exist.\n        if cafile is not None:\n            with open(cafile):\n                pass\n\n        self._trust_bundle = cafile or cadata\n\n    def load_cert_chain(self, certfile, keyfile=None, password=None):\n        self._client_cert = certfile\n        self._client_key = keyfile\n        self._client_cert_passphrase = password\n\n    def set_alpn_protocols(self, protocols):\n        \"\"\"\n        Sets the ALPN protocols that will later be set on the context.\n\n        Raises a NotImplementedError if ALPN is not supported.\n        \"\"\"\n        if not hasattr(Security, \"SSLSetALPNProtocols\"):\n            raise NotImplementedError(\n                \"SecureTransport supports ALPN only in macOS 10.12+\"\n            )\n        self._alpn_protocols = [six.ensure_binary(p) for p in protocols]\n\n    def wrap_socket(\n        self,\n        sock,\n        server_side=False,\n        do_handshake_on_connect=True,\n        suppress_ragged_eofs=True,\n        server_hostname=None,\n    ):\n        # So, what do we do here? Firstly, we assert some properties. This is a\n        # stripped down shim, so there is some functionality we don't support.\n        # See PEP 543 for the real deal.\n        assert not server_side\n        assert do_handshake_on_connect\n        assert suppress_ragged_eofs\n\n        # Ok, we're good to go. Now we want to create the wrapped socket object\n        # and store it in the appropriate place.\n        wrapped_socket = WrappedSocket(sock)\n\n        # Now we can handshake\n        wrapped_socket.handshake(\n            server_hostname,\n            self._verify,\n            self._trust_bundle,\n            self._min_version,\n            self._max_version,\n            self._client_cert,\n            self._client_key,\n            self._client_key_passphrase,\n            self._alpn_protocols,\n        )\n        return wrapped_socket\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/contrib/socks.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module contains provisional support for SOCKS proxies from within\nurllib3. This module supports SOCKS4, SOCKS4A (an extension of SOCKS4), and\nSOCKS5. To enable its functionality, either install PySocks or install this\nmodule with the ``socks`` extra.\n\nThe SOCKS implementation supports the full range of urllib3 features. It also\nsupports the following SOCKS features:\n\n- SOCKS4A (``proxy_url='socks4a://...``)\n- SOCKS4 (``proxy_url='socks4://...``)\n- SOCKS5 with remote DNS (``proxy_url='socks5h://...``)\n- SOCKS5 with local DNS (``proxy_url='socks5://...``)\n- Usernames and passwords for the SOCKS proxy\n\n.. note::\n   It is recommended to use ``socks5h://`` or ``socks4a://`` schemes in\n   your ``proxy_url`` to ensure that DNS resolution is done from the remote\n   server instead of client-side when connecting to a domain name.\n\nSOCKS4 supports IPv4 and domain names with the SOCKS4A extension. SOCKS5\nsupports IPv4, IPv6, and domain names.\n\nWhen connecting to a SOCKS4 proxy the ``username`` portion of the ``proxy_url``\nwill be sent as the ``userid`` section of the SOCKS request:\n\n.. code-block:: python\n\n    proxy_url=\"socks4a://<userid>@proxy-host\"\n\nWhen connecting to a SOCKS5 proxy the ``username`` and ``password`` portion\nof the ``proxy_url`` will be sent as the username/password to authenticate\nwith the proxy:\n\n.. code-block:: python\n\n    proxy_url=\"socks5h://<username>:<password>@proxy-host\"\n\n\"\"\"\nfrom __future__ import absolute_import\n\ntry:\n    import socks\nexcept ImportError:\n    import warnings\n\n    from ..exceptions import DependencyWarning\n\n    warnings.warn(\n        (\n            \"SOCKS support in urllib3 requires the installation of optional \"\n            \"dependencies: specifically, PySocks.  For more information, see \"\n            \"https://urllib3.readthedocs.io/en/1.26.x/contrib.html#socks-proxies\"\n        ),\n        DependencyWarning,\n    )\n    raise\n\nfrom socket import error as SocketError\nfrom socket import timeout as SocketTimeout\n\nfrom ..connection import HTTPConnection, HTTPSConnection\nfrom ..connectionpool import HTTPConnectionPool, HTTPSConnectionPool\nfrom ..exceptions import ConnectTimeoutError, NewConnectionError\nfrom ..poolmanager import PoolManager\nfrom ..util.url import parse_url\n\ntry:\n    import ssl\nexcept ImportError:\n    ssl = None\n\n\nclass SOCKSConnection(HTTPConnection):\n    \"\"\"\n    A plain-text HTTP connection that connects via a SOCKS proxy.\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        self._socks_options = kwargs.pop(\"_socks_options\")\n        super(SOCKSConnection, self).__init__(*args, **kwargs)\n\n    def _new_conn(self):\n        \"\"\"\n        Establish a new connection via the SOCKS proxy.\n        \"\"\"\n        extra_kw = {}\n        if self.source_address:\n            extra_kw[\"source_address\"] = self.source_address\n\n        if self.socket_options:\n            extra_kw[\"socket_options\"] = self.socket_options\n\n        try:\n            conn = socks.create_connection(\n                (self.host, self.port),\n                proxy_type=self._socks_options[\"socks_version\"],\n                proxy_addr=self._socks_options[\"proxy_host\"],\n                proxy_port=self._socks_options[\"proxy_port\"],\n                proxy_username=self._socks_options[\"username\"],\n                proxy_password=self._socks_options[\"password\"],\n                proxy_rdns=self._socks_options[\"rdns\"],\n                timeout=self.timeout,\n                **extra_kw\n            )\n\n        except SocketTimeout:\n            raise ConnectTimeoutError(\n                self,\n                \"Connection to %s timed out. (connect timeout=%s)\"\n                % (self.host, self.timeout),\n            )\n\n        except socks.ProxyError as e:\n            # This is fragile as hell, but it seems to be the only way to raise\n            # useful errors here.\n            if e.socket_err:\n                error = e.socket_err\n                if isinstance(error, SocketTimeout):\n                    raise ConnectTimeoutError(\n                        self,\n                        \"Connection to %s timed out. (connect timeout=%s)\"\n                        % (self.host, self.timeout),\n                    )\n                else:\n                    raise NewConnectionError(\n                        self, \"Failed to establish a new connection: %s\" % error\n                    )\n            else:\n                raise NewConnectionError(\n                    self, \"Failed to establish a new connection: %s\" % e\n                )\n\n        except SocketError as e:  # Defensive: PySocks should catch all these.\n            raise NewConnectionError(\n                self, \"Failed to establish a new connection: %s\" % e\n            )\n\n        return conn\n\n\n# We don't need to duplicate the Verified/Unverified distinction from\n# urllib3/connection.py here because the HTTPSConnection will already have been\n# correctly set to either the Verified or Unverified form by that module. This\n# means the SOCKSHTTPSConnection will automatically be the correct type.\nclass SOCKSHTTPSConnection(SOCKSConnection, HTTPSConnection):\n    pass\n\n\nclass SOCKSHTTPConnectionPool(HTTPConnectionPool):\n    ConnectionCls = SOCKSConnection\n\n\nclass SOCKSHTTPSConnectionPool(HTTPSConnectionPool):\n    ConnectionCls = SOCKSHTTPSConnection\n\n\nclass SOCKSProxyManager(PoolManager):\n    \"\"\"\n    A version of the urllib3 ProxyManager that routes connections via the\n    defined SOCKS proxy.\n    \"\"\"\n\n    pool_classes_by_scheme = {\n        \"http\": SOCKSHTTPConnectionPool,\n        \"https\": SOCKSHTTPSConnectionPool,\n    }\n\n    def __init__(\n        self,\n        proxy_url,\n        username=None,\n        password=None,\n        num_pools=10,\n        headers=None,\n        **connection_pool_kw\n    ):\n        parsed = parse_url(proxy_url)\n\n        if username is None and password is None and parsed.auth is not None:\n            split = parsed.auth.split(\":\")\n            if len(split) == 2:\n                username, password = split\n        if parsed.scheme == \"socks5\":\n            socks_version = socks.PROXY_TYPE_SOCKS5\n            rdns = False\n        elif parsed.scheme == \"socks5h\":\n            socks_version = socks.PROXY_TYPE_SOCKS5\n            rdns = True\n        elif parsed.scheme == \"socks4\":\n            socks_version = socks.PROXY_TYPE_SOCKS4\n            rdns = False\n        elif parsed.scheme == \"socks4a\":\n            socks_version = socks.PROXY_TYPE_SOCKS4\n            rdns = True\n        else:\n            raise ValueError(\"Unable to determine SOCKS version from %s\" % proxy_url)\n\n        self.proxy_url = proxy_url\n\n        socks_options = {\n            \"socks_version\": socks_version,\n            \"proxy_host\": parsed.host,\n            \"proxy_port\": parsed.port,\n            \"username\": username,\n            \"password\": password,\n            \"rdns\": rdns,\n        }\n        connection_pool_kw[\"_socks_options\"] = socks_options\n\n        super(SOCKSProxyManager, self).__init__(\n            num_pools, headers, **connection_pool_kw\n        )\n\n        self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/exceptions.py",
    "content": "from __future__ import absolute_import\n\nfrom .packages.six.moves.http_client import IncompleteRead as httplib_IncompleteRead\n\n# Base Exceptions\n\n\nclass HTTPError(Exception):\n    \"\"\"Base exception used by this module.\"\"\"\n\n    pass\n\n\nclass HTTPWarning(Warning):\n    \"\"\"Base warning used by this module.\"\"\"\n\n    pass\n\n\nclass PoolError(HTTPError):\n    \"\"\"Base exception for errors caused within a pool.\"\"\"\n\n    def __init__(self, pool, message):\n        self.pool = pool\n        HTTPError.__init__(self, \"%s: %s\" % (pool, message))\n\n    def __reduce__(self):\n        # For pickling purposes.\n        return self.__class__, (None, None)\n\n\nclass RequestError(PoolError):\n    \"\"\"Base exception for PoolErrors that have associated URLs.\"\"\"\n\n    def __init__(self, pool, url, message):\n        self.url = url\n        PoolError.__init__(self, pool, message)\n\n    def __reduce__(self):\n        # For pickling purposes.\n        return self.__class__, (None, self.url, None)\n\n\nclass SSLError(HTTPError):\n    \"\"\"Raised when SSL certificate fails in an HTTPS connection.\"\"\"\n\n    pass\n\n\nclass ProxyError(HTTPError):\n    \"\"\"Raised when the connection to a proxy fails.\"\"\"\n\n    def __init__(self, message, error, *args):\n        super(ProxyError, self).__init__(message, error, *args)\n        self.original_error = error\n\n\nclass DecodeError(HTTPError):\n    \"\"\"Raised when automatic decoding based on Content-Type fails.\"\"\"\n\n    pass\n\n\nclass ProtocolError(HTTPError):\n    \"\"\"Raised when something unexpected happens mid-request/response.\"\"\"\n\n    pass\n\n\n#: Renamed to ProtocolError but aliased for backwards compatibility.\nConnectionError = ProtocolError\n\n\n# Leaf Exceptions\n\n\nclass MaxRetryError(RequestError):\n    \"\"\"Raised when the maximum number of retries is exceeded.\n\n    :param pool: The connection pool\n    :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool`\n    :param string url: The requested Url\n    :param exceptions.Exception reason: The underlying error\n\n    \"\"\"\n\n    def __init__(self, pool, url, reason=None):\n        self.reason = reason\n\n        message = \"Max retries exceeded with url: %s (Caused by %r)\" % (url, reason)\n\n        RequestError.__init__(self, pool, url, message)\n\n\nclass HostChangedError(RequestError):\n    \"\"\"Raised when an existing pool gets a request for a foreign host.\"\"\"\n\n    def __init__(self, pool, url, retries=3):\n        message = \"Tried to open a foreign host with url: %s\" % url\n        RequestError.__init__(self, pool, url, message)\n        self.retries = retries\n\n\nclass TimeoutStateError(HTTPError):\n    \"\"\"Raised when passing an invalid state to a timeout\"\"\"\n\n    pass\n\n\nclass TimeoutError(HTTPError):\n    \"\"\"Raised when a socket timeout error occurs.\n\n    Catching this error will catch both :exc:`ReadTimeoutErrors\n    <ReadTimeoutError>` and :exc:`ConnectTimeoutErrors <ConnectTimeoutError>`.\n    \"\"\"\n\n    pass\n\n\nclass ReadTimeoutError(TimeoutError, RequestError):\n    \"\"\"Raised when a socket timeout occurs while receiving data from a server\"\"\"\n\n    pass\n\n\n# This timeout error does not have a URL attached and needs to inherit from the\n# base HTTPError\nclass ConnectTimeoutError(TimeoutError):\n    \"\"\"Raised when a socket timeout occurs while connecting to a server\"\"\"\n\n    pass\n\n\nclass NewConnectionError(ConnectTimeoutError, PoolError):\n    \"\"\"Raised when we fail to establish a new connection. Usually ECONNREFUSED.\"\"\"\n\n    pass\n\n\nclass EmptyPoolError(PoolError):\n    \"\"\"Raised when a pool runs out of connections and no more are allowed.\"\"\"\n\n    pass\n\n\nclass ClosedPoolError(PoolError):\n    \"\"\"Raised when a request enters a pool after the pool has been closed.\"\"\"\n\n    pass\n\n\nclass LocationValueError(ValueError, HTTPError):\n    \"\"\"Raised when there is something wrong with a given URL input.\"\"\"\n\n    pass\n\n\nclass LocationParseError(LocationValueError):\n    \"\"\"Raised when get_host or similar fails to parse the URL input.\"\"\"\n\n    def __init__(self, location):\n        message = \"Failed to parse: %s\" % location\n        HTTPError.__init__(self, message)\n\n        self.location = location\n\n\nclass URLSchemeUnknown(LocationValueError):\n    \"\"\"Raised when a URL input has an unsupported scheme.\"\"\"\n\n    def __init__(self, scheme):\n        message = \"Not supported URL scheme %s\" % scheme\n        super(URLSchemeUnknown, self).__init__(message)\n\n        self.scheme = scheme\n\n\nclass ResponseError(HTTPError):\n    \"\"\"Used as a container for an error reason supplied in a MaxRetryError.\"\"\"\n\n    GENERIC_ERROR = \"too many error responses\"\n    SPECIFIC_ERROR = \"too many {status_code} error responses\"\n\n\nclass SecurityWarning(HTTPWarning):\n    \"\"\"Warned when performing security reducing actions\"\"\"\n\n    pass\n\n\nclass SubjectAltNameWarning(SecurityWarning):\n    \"\"\"Warned when connecting to a host with a certificate missing a SAN.\"\"\"\n\n    pass\n\n\nclass InsecureRequestWarning(SecurityWarning):\n    \"\"\"Warned when making an unverified HTTPS request.\"\"\"\n\n    pass\n\n\nclass SystemTimeWarning(SecurityWarning):\n    \"\"\"Warned when system time is suspected to be wrong\"\"\"\n\n    pass\n\n\nclass InsecurePlatformWarning(SecurityWarning):\n    \"\"\"Warned when certain TLS/SSL configuration is not available on a platform.\"\"\"\n\n    pass\n\n\nclass SNIMissingWarning(HTTPWarning):\n    \"\"\"Warned when making a HTTPS request without SNI available.\"\"\"\n\n    pass\n\n\nclass DependencyWarning(HTTPWarning):\n    \"\"\"\n    Warned when an attempt is made to import a module with missing optional\n    dependencies.\n    \"\"\"\n\n    pass\n\n\nclass ResponseNotChunked(ProtocolError, ValueError):\n    \"\"\"Response needs to be chunked in order to read it as chunks.\"\"\"\n\n    pass\n\n\nclass BodyNotHttplibCompatible(HTTPError):\n    \"\"\"\n    Body should be :class:`http.client.HTTPResponse` like\n    (have an fp attribute which returns raw chunks) for read_chunked().\n    \"\"\"\n\n    pass\n\n\nclass IncompleteRead(HTTPError, httplib_IncompleteRead):\n    \"\"\"\n    Response length doesn't match expected Content-Length\n\n    Subclass of :class:`http.client.IncompleteRead` to allow int value\n    for ``partial`` to avoid creating large objects on streamed reads.\n    \"\"\"\n\n    def __init__(self, partial, expected):\n        super(IncompleteRead, self).__init__(partial, expected)\n\n    def __repr__(self):\n        return \"IncompleteRead(%i bytes read, %i more expected)\" % (\n            self.partial,\n            self.expected,\n        )\n\n\nclass InvalidChunkLength(HTTPError, httplib_IncompleteRead):\n    \"\"\"Invalid chunk length in a chunked response.\"\"\"\n\n    def __init__(self, response, length):\n        super(InvalidChunkLength, self).__init__(\n            response.tell(), response.length_remaining\n        )\n        self.response = response\n        self.length = length\n\n    def __repr__(self):\n        return \"InvalidChunkLength(got length %r, %i bytes read)\" % (\n            self.length,\n            self.partial,\n        )\n\n\nclass InvalidHeader(HTTPError):\n    \"\"\"The header provided was somehow invalid.\"\"\"\n\n    pass\n\n\nclass ProxySchemeUnknown(AssertionError, URLSchemeUnknown):\n    \"\"\"ProxyManager does not support the supplied scheme\"\"\"\n\n    # TODO(t-8ch): Stop inheriting from AssertionError in v2.0.\n\n    def __init__(self, scheme):\n        # 'localhost' is here because our URL parser parses\n        # localhost:8080 -> scheme=localhost, remove if we fix this.\n        if scheme == \"localhost\":\n            scheme = None\n        if scheme is None:\n            message = \"Proxy URL had no scheme, should start with http:// or https://\"\n        else:\n            message = (\n                \"Proxy URL had unsupported scheme %s, should use http:// or https://\"\n                % scheme\n            )\n        super(ProxySchemeUnknown, self).__init__(message)\n\n\nclass ProxySchemeUnsupported(ValueError):\n    \"\"\"Fetching HTTPS resources through HTTPS proxies is unsupported\"\"\"\n\n    pass\n\n\nclass HeaderParsingError(HTTPError):\n    \"\"\"Raised by assert_header_parsing, but we convert it to a log.warning statement.\"\"\"\n\n    def __init__(self, defects, unparsed_data):\n        message = \"%s, unparsed data: %r\" % (defects or \"Unknown\", unparsed_data)\n        super(HeaderParsingError, self).__init__(message)\n\n\nclass UnrewindableBodyError(HTTPError):\n    \"\"\"urllib3 encountered an error when trying to rewind a body\"\"\"\n\n    pass\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/fields.py",
    "content": "from __future__ import absolute_import\n\nimport email.utils\nimport mimetypes\nimport re\n\nfrom .packages import six\n\n\ndef guess_content_type(filename, default=\"application/octet-stream\"):\n    \"\"\"\n    Guess the \"Content-Type\" of a file.\n\n    :param filename:\n        The filename to guess the \"Content-Type\" of using :mod:`mimetypes`.\n    :param default:\n        If no \"Content-Type\" can be guessed, default to `default`.\n    \"\"\"\n    if filename:\n        return mimetypes.guess_type(filename)[0] or default\n    return default\n\n\ndef format_header_param_rfc2231(name, value):\n    \"\"\"\n    Helper function to format and quote a single header parameter using the\n    strategy defined in RFC 2231.\n\n    Particularly useful for header parameters which might contain\n    non-ASCII values, like file names. This follows\n    `RFC 2388 Section 4.4 <https://tools.ietf.org/html/rfc2388#section-4.4>`_.\n\n    :param name:\n        The name of the parameter, a string expected to be ASCII only.\n    :param value:\n        The value of the parameter, provided as ``bytes`` or `str``.\n    :ret:\n        An RFC-2231-formatted unicode string.\n    \"\"\"\n    if isinstance(value, six.binary_type):\n        value = value.decode(\"utf-8\")\n\n    if not any(ch in value for ch in '\"\\\\\\r\\n'):\n        result = u'%s=\"%s\"' % (name, value)\n        try:\n            result.encode(\"ascii\")\n        except (UnicodeEncodeError, UnicodeDecodeError):\n            pass\n        else:\n            return result\n\n    if six.PY2:  # Python 2:\n        value = value.encode(\"utf-8\")\n\n    # encode_rfc2231 accepts an encoded string and returns an ascii-encoded\n    # string in Python 2 but accepts and returns unicode strings in Python 3\n    value = email.utils.encode_rfc2231(value, \"utf-8\")\n    value = \"%s*=%s\" % (name, value)\n\n    if six.PY2:  # Python 2:\n        value = value.decode(\"utf-8\")\n\n    return value\n\n\n_HTML5_REPLACEMENTS = {\n    u\"\\u0022\": u\"%22\",\n    # Replace \"\\\" with \"\\\\\".\n    u\"\\u005C\": u\"\\u005C\\u005C\",\n}\n\n# All control characters from 0x00 to 0x1F *except* 0x1B.\n_HTML5_REPLACEMENTS.update(\n    {\n        six.unichr(cc): u\"%{:02X}\".format(cc)\n        for cc in range(0x00, 0x1F + 1)\n        if cc not in (0x1B,)\n    }\n)\n\n\ndef _replace_multiple(value, needles_and_replacements):\n    def replacer(match):\n        return needles_and_replacements[match.group(0)]\n\n    pattern = re.compile(\n        r\"|\".join([re.escape(needle) for needle in needles_and_replacements.keys()])\n    )\n\n    result = pattern.sub(replacer, value)\n\n    return result\n\n\ndef format_header_param_html5(name, value):\n    \"\"\"\n    Helper function to format and quote a single header parameter using the\n    HTML5 strategy.\n\n    Particularly useful for header parameters which might contain\n    non-ASCII values, like file names. This follows the `HTML5 Working Draft\n    Section 4.10.22.7`_ and matches the behavior of curl and modern browsers.\n\n    .. _HTML5 Working Draft Section 4.10.22.7:\n        https://w3c.github.io/html/sec-forms.html#multipart-form-data\n\n    :param name:\n        The name of the parameter, a string expected to be ASCII only.\n    :param value:\n        The value of the parameter, provided as ``bytes`` or `str``.\n    :ret:\n        A unicode string, stripped of troublesome characters.\n    \"\"\"\n    if isinstance(value, six.binary_type):\n        value = value.decode(\"utf-8\")\n\n    value = _replace_multiple(value, _HTML5_REPLACEMENTS)\n\n    return u'%s=\"%s\"' % (name, value)\n\n\n# For backwards-compatibility.\nformat_header_param = format_header_param_html5\n\n\nclass RequestField(object):\n    \"\"\"\n    A data container for request body parameters.\n\n    :param name:\n        The name of this request field. Must be unicode.\n    :param data:\n        The data/value body.\n    :param filename:\n        An optional filename of the request field. Must be unicode.\n    :param headers:\n        An optional dict-like object of headers to initially use for the field.\n    :param header_formatter:\n        An optional callable that is used to encode and format the headers. By\n        default, this is :func:`format_header_param_html5`.\n    \"\"\"\n\n    def __init__(\n        self,\n        name,\n        data,\n        filename=None,\n        headers=None,\n        header_formatter=format_header_param_html5,\n    ):\n        self._name = name\n        self._filename = filename\n        self.data = data\n        self.headers = {}\n        if headers:\n            self.headers = dict(headers)\n        self.header_formatter = header_formatter\n\n    @classmethod\n    def from_tuples(cls, fieldname, value, header_formatter=format_header_param_html5):\n        \"\"\"\n        A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.\n\n        Supports constructing :class:`~urllib3.fields.RequestField` from\n        parameter of key/value strings AND key/filetuple. A filetuple is a\n        (filename, data, MIME type) tuple where the MIME type is optional.\n        For example::\n\n            'foo': 'bar',\n            'fakefile': ('foofile.txt', 'contents of foofile'),\n            'realfile': ('barfile.txt', open('realfile').read()),\n            'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),\n            'nonamefile': 'contents of nonamefile field',\n\n        Field names and filenames must be unicode.\n        \"\"\"\n        if isinstance(value, tuple):\n            if len(value) == 3:\n                filename, data, content_type = value\n            else:\n                filename, data = value\n                content_type = guess_content_type(filename)\n        else:\n            filename = None\n            content_type = None\n            data = value\n\n        request_param = cls(\n            fieldname, data, filename=filename, header_formatter=header_formatter\n        )\n        request_param.make_multipart(content_type=content_type)\n\n        return request_param\n\n    def _render_part(self, name, value):\n        \"\"\"\n        Overridable helper function to format a single header parameter. By\n        default, this calls ``self.header_formatter``.\n\n        :param name:\n            The name of the parameter, a string expected to be ASCII only.\n        :param value:\n            The value of the parameter, provided as a unicode string.\n        \"\"\"\n\n        return self.header_formatter(name, value)\n\n    def _render_parts(self, header_parts):\n        \"\"\"\n        Helper function to format and quote a single header.\n\n        Useful for single headers that are composed of multiple items. E.g.,\n        'Content-Disposition' fields.\n\n        :param header_parts:\n            A sequence of (k, v) tuples or a :class:`dict` of (k, v) to format\n            as `k1=\"v1\"; k2=\"v2\"; ...`.\n        \"\"\"\n        parts = []\n        iterable = header_parts\n        if isinstance(header_parts, dict):\n            iterable = header_parts.items()\n\n        for name, value in iterable:\n            if value is not None:\n                parts.append(self._render_part(name, value))\n\n        return u\"; \".join(parts)\n\n    def render_headers(self):\n        \"\"\"\n        Renders the headers for this request field.\n        \"\"\"\n        lines = []\n\n        sort_keys = [\"Content-Disposition\", \"Content-Type\", \"Content-Location\"]\n        for sort_key in sort_keys:\n            if self.headers.get(sort_key, False):\n                lines.append(u\"%s: %s\" % (sort_key, self.headers[sort_key]))\n\n        for header_name, header_value in self.headers.items():\n            if header_name not in sort_keys:\n                if header_value:\n                    lines.append(u\"%s: %s\" % (header_name, header_value))\n\n        lines.append(u\"\\r\\n\")\n        return u\"\\r\\n\".join(lines)\n\n    def make_multipart(\n        self, content_disposition=None, content_type=None, content_location=None\n    ):\n        \"\"\"\n        Makes this request field into a multipart request field.\n\n        This method overrides \"Content-Disposition\", \"Content-Type\" and\n        \"Content-Location\" headers to the request parameter.\n\n        :param content_type:\n            The 'Content-Type' of the request body.\n        :param content_location:\n            The 'Content-Location' of the request body.\n\n        \"\"\"\n        self.headers[\"Content-Disposition\"] = content_disposition or u\"form-data\"\n        self.headers[\"Content-Disposition\"] += u\"; \".join(\n            [\n                u\"\",\n                self._render_parts(\n                    ((u\"name\", self._name), (u\"filename\", self._filename))\n                ),\n            ]\n        )\n        self.headers[\"Content-Type\"] = content_type\n        self.headers[\"Content-Location\"] = content_location\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/filepost.py",
    "content": "from __future__ import absolute_import\n\nimport binascii\nimport codecs\nimport os\nfrom io import BytesIO\n\nfrom .fields import RequestField\nfrom .packages import six\nfrom .packages.six import b\n\nwriter = codecs.lookup(\"utf-8\")[3]\n\n\ndef choose_boundary():\n    \"\"\"\n    Our embarrassingly-simple replacement for mimetools.choose_boundary.\n    \"\"\"\n    boundary = binascii.hexlify(os.urandom(16))\n    if not six.PY2:\n        boundary = boundary.decode(\"ascii\")\n    return boundary\n\n\ndef iter_field_objects(fields):\n    \"\"\"\n    Iterate over fields.\n\n    Supports list of (k, v) tuples and dicts, and lists of\n    :class:`~urllib3.fields.RequestField`.\n\n    \"\"\"\n    if isinstance(fields, dict):\n        i = six.iteritems(fields)\n    else:\n        i = iter(fields)\n\n    for field in i:\n        if isinstance(field, RequestField):\n            yield field\n        else:\n            yield RequestField.from_tuples(*field)\n\n\ndef iter_fields(fields):\n    \"\"\"\n    .. deprecated:: 1.6\n\n    Iterate over fields.\n\n    The addition of :class:`~urllib3.fields.RequestField` makes this function\n    obsolete. Instead, use :func:`iter_field_objects`, which returns\n    :class:`~urllib3.fields.RequestField` objects.\n\n    Supports list of (k, v) tuples and dicts.\n    \"\"\"\n    if isinstance(fields, dict):\n        return ((k, v) for k, v in six.iteritems(fields))\n\n    return ((k, v) for k, v in fields)\n\n\ndef encode_multipart_formdata(fields, boundary=None):\n    \"\"\"\n    Encode a dictionary of ``fields`` using the multipart/form-data MIME format.\n\n    :param fields:\n        Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).\n\n    :param boundary:\n        If not specified, then a random boundary will be generated using\n        :func:`urllib3.filepost.choose_boundary`.\n    \"\"\"\n    body = BytesIO()\n    if boundary is None:\n        boundary = choose_boundary()\n\n    for field in iter_field_objects(fields):\n        body.write(b(\"--%s\\r\\n\" % (boundary)))\n\n        writer(body).write(field.render_headers())\n        data = field.data\n\n        if isinstance(data, int):\n            data = str(data)  # Backwards compatibility\n\n        if isinstance(data, six.text_type):\n            writer(body).write(data)\n        else:\n            body.write(data)\n\n        body.write(b\"\\r\\n\")\n\n    body.write(b(\"--%s--\\r\\n\" % (boundary)))\n\n    content_type = str(\"multipart/form-data; boundary=%s\" % boundary)\n\n    return body.getvalue(), content_type\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/packages/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/packages/backports/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/packages/backports/makefile.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"\nbackports.makefile\n~~~~~~~~~~~~~~~~~~\n\nBackports the Python 3 ``socket.makefile`` method for use with anything that\nwants to create a \"fake\" socket object.\n\"\"\"\nimport io\nfrom socket import SocketIO\n\n\ndef backport_makefile(\n    self, mode=\"r\", buffering=None, encoding=None, errors=None, newline=None\n):\n    \"\"\"\n    Backport of ``socket.makefile`` from Python 3.5.\n    \"\"\"\n    if not set(mode) <= {\"r\", \"w\", \"b\"}:\n        raise ValueError(\"invalid mode %r (only r, w, b allowed)\" % (mode,))\n    writing = \"w\" in mode\n    reading = \"r\" in mode or not writing\n    assert reading or writing\n    binary = \"b\" in mode\n    rawmode = \"\"\n    if reading:\n        rawmode += \"r\"\n    if writing:\n        rawmode += \"w\"\n    raw = SocketIO(self, rawmode)\n    self._makefile_refs += 1\n    if buffering is None:\n        buffering = -1\n    if buffering < 0:\n        buffering = io.DEFAULT_BUFFER_SIZE\n    if buffering == 0:\n        if not binary:\n            raise ValueError(\"unbuffered streams must be binary\")\n        return raw\n    if reading and writing:\n        buffer = io.BufferedRWPair(raw, raw, buffering)\n    elif reading:\n        buffer = io.BufferedReader(raw, buffering)\n    else:\n        assert writing\n        buffer = io.BufferedWriter(raw, buffering)\n    if binary:\n        return buffer\n    text = io.TextIOWrapper(buffer, encoding, errors, newline)\n    text.mode = mode\n    return text\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/packages/six.py",
    "content": "# Copyright (c) 2010-2020 Benjamin Peterson\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\"\"\"Utilities for writing code that runs on Python 2 and 3\"\"\"\n\nfrom __future__ import absolute_import\n\nimport functools\nimport itertools\nimport operator\nimport sys\nimport types\n\n__author__ = \"Benjamin Peterson <benjamin@python.org>\"\n__version__ = \"1.16.0\"\n\n\n# Useful for very coarse version differentiation.\nPY2 = sys.version_info[0] == 2\nPY3 = sys.version_info[0] == 3\nPY34 = sys.version_info[0:2] >= (3, 4)\n\nif PY3:\n    string_types = (str,)\n    integer_types = (int,)\n    class_types = (type,)\n    text_type = str\n    binary_type = bytes\n\n    MAXSIZE = sys.maxsize\nelse:\n    string_types = (basestring,)\n    integer_types = (int, long)\n    class_types = (type, types.ClassType)\n    text_type = unicode\n    binary_type = str\n\n    if sys.platform.startswith(\"java\"):\n        # Jython always uses 32 bits.\n        MAXSIZE = int((1 << 31) - 1)\n    else:\n        # It's possible to have sizeof(long) != sizeof(Py_ssize_t).\n        class X(object):\n            def __len__(self):\n                return 1 << 31\n\n        try:\n            len(X())\n        except OverflowError:\n            # 32-bit\n            MAXSIZE = int((1 << 31) - 1)\n        else:\n            # 64-bit\n            MAXSIZE = int((1 << 63) - 1)\n        del X\n\nif PY34:\n    from importlib.util import spec_from_loader\nelse:\n    spec_from_loader = None\n\n\ndef _add_doc(func, doc):\n    \"\"\"Add documentation to a function.\"\"\"\n    func.__doc__ = doc\n\n\ndef _import_module(name):\n    \"\"\"Import module, returning the module after the last dot.\"\"\"\n    __import__(name)\n    return sys.modules[name]\n\n\nclass _LazyDescr(object):\n    def __init__(self, name):\n        self.name = name\n\n    def __get__(self, obj, tp):\n        result = self._resolve()\n        setattr(obj, self.name, result)  # Invokes __set__.\n        try:\n            # This is a bit ugly, but it avoids running this again by\n            # removing this descriptor.\n            delattr(obj.__class__, self.name)\n        except AttributeError:\n            pass\n        return result\n\n\nclass MovedModule(_LazyDescr):\n    def __init__(self, name, old, new=None):\n        super(MovedModule, self).__init__(name)\n        if PY3:\n            if new is None:\n                new = name\n            self.mod = new\n        else:\n            self.mod = old\n\n    def _resolve(self):\n        return _import_module(self.mod)\n\n    def __getattr__(self, attr):\n        _module = self._resolve()\n        value = getattr(_module, attr)\n        setattr(self, attr, value)\n        return value\n\n\nclass _LazyModule(types.ModuleType):\n    def __init__(self, name):\n        super(_LazyModule, self).__init__(name)\n        self.__doc__ = self.__class__.__doc__\n\n    def __dir__(self):\n        attrs = [\"__doc__\", \"__name__\"]\n        attrs += [attr.name for attr in self._moved_attributes]\n        return attrs\n\n    # Subclasses should override this\n    _moved_attributes = []\n\n\nclass MovedAttribute(_LazyDescr):\n    def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None):\n        super(MovedAttribute, self).__init__(name)\n        if PY3:\n            if new_mod is None:\n                new_mod = name\n            self.mod = new_mod\n            if new_attr is None:\n                if old_attr is None:\n                    new_attr = name\n                else:\n                    new_attr = old_attr\n            self.attr = new_attr\n        else:\n            self.mod = old_mod\n            if old_attr is None:\n                old_attr = name\n            self.attr = old_attr\n\n    def _resolve(self):\n        module = _import_module(self.mod)\n        return getattr(module, self.attr)\n\n\nclass _SixMetaPathImporter(object):\n\n    \"\"\"\n    A meta path importer to import six.moves and its submodules.\n\n    This class implements a PEP302 finder and loader. It should be compatible\n    with Python 2.5 and all existing versions of Python3\n    \"\"\"\n\n    def __init__(self, six_module_name):\n        self.name = six_module_name\n        self.known_modules = {}\n\n    def _add_module(self, mod, *fullnames):\n        for fullname in fullnames:\n            self.known_modules[self.name + \".\" + fullname] = mod\n\n    def _get_module(self, fullname):\n        return self.known_modules[self.name + \".\" + fullname]\n\n    def find_module(self, fullname, path=None):\n        if fullname in self.known_modules:\n            return self\n        return None\n\n    def find_spec(self, fullname, path, target=None):\n        if fullname in self.known_modules:\n            return spec_from_loader(fullname, self)\n        return None\n\n    def __get_module(self, fullname):\n        try:\n            return self.known_modules[fullname]\n        except KeyError:\n            raise ImportError(\"This loader does not know module \" + fullname)\n\n    def load_module(self, fullname):\n        try:\n            # in case of a reload\n            return sys.modules[fullname]\n        except KeyError:\n            pass\n        mod = self.__get_module(fullname)\n        if isinstance(mod, MovedModule):\n            mod = mod._resolve()\n        else:\n            mod.__loader__ = self\n        sys.modules[fullname] = mod\n        return mod\n\n    def is_package(self, fullname):\n        \"\"\"\n        Return true, if the named module is a package.\n\n        We need this method to get correct spec objects with\n        Python 3.4 (see PEP451)\n        \"\"\"\n        return hasattr(self.__get_module(fullname), \"__path__\")\n\n    def get_code(self, fullname):\n        \"\"\"Return None\n\n        Required, if is_package is implemented\"\"\"\n        self.__get_module(fullname)  # eventually raises ImportError\n        return None\n\n    get_source = get_code  # same as get_code\n\n    def create_module(self, spec):\n        return self.load_module(spec.name)\n\n    def exec_module(self, module):\n        pass\n\n\n_importer = _SixMetaPathImporter(__name__)\n\n\nclass _MovedItems(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects\"\"\"\n\n    __path__ = []  # mark as package\n\n\n_moved_attributes = [\n    MovedAttribute(\"cStringIO\", \"cStringIO\", \"io\", \"StringIO\"),\n    MovedAttribute(\"filter\", \"itertools\", \"builtins\", \"ifilter\", \"filter\"),\n    MovedAttribute(\n        \"filterfalse\", \"itertools\", \"itertools\", \"ifilterfalse\", \"filterfalse\"\n    ),\n    MovedAttribute(\"input\", \"__builtin__\", \"builtins\", \"raw_input\", \"input\"),\n    MovedAttribute(\"intern\", \"__builtin__\", \"sys\"),\n    MovedAttribute(\"map\", \"itertools\", \"builtins\", \"imap\", \"map\"),\n    MovedAttribute(\"getcwd\", \"os\", \"os\", \"getcwdu\", \"getcwd\"),\n    MovedAttribute(\"getcwdb\", \"os\", \"os\", \"getcwd\", \"getcwdb\"),\n    MovedAttribute(\"getoutput\", \"commands\", \"subprocess\"),\n    MovedAttribute(\"range\", \"__builtin__\", \"builtins\", \"xrange\", \"range\"),\n    MovedAttribute(\n        \"reload_module\", \"__builtin__\", \"importlib\" if PY34 else \"imp\", \"reload\"\n    ),\n    MovedAttribute(\"reduce\", \"__builtin__\", \"functools\"),\n    MovedAttribute(\"shlex_quote\", \"pipes\", \"shlex\", \"quote\"),\n    MovedAttribute(\"StringIO\", \"StringIO\", \"io\"),\n    MovedAttribute(\"UserDict\", \"UserDict\", \"collections\"),\n    MovedAttribute(\"UserList\", \"UserList\", \"collections\"),\n    MovedAttribute(\"UserString\", \"UserString\", \"collections\"),\n    MovedAttribute(\"xrange\", \"__builtin__\", \"builtins\", \"xrange\", \"range\"),\n    MovedAttribute(\"zip\", \"itertools\", \"builtins\", \"izip\", \"zip\"),\n    MovedAttribute(\n        \"zip_longest\", \"itertools\", \"itertools\", \"izip_longest\", \"zip_longest\"\n    ),\n    MovedModule(\"builtins\", \"__builtin__\"),\n    MovedModule(\"configparser\", \"ConfigParser\"),\n    MovedModule(\n        \"collections_abc\",\n        \"collections\",\n        \"collections.abc\" if sys.version_info >= (3, 3) else \"collections\",\n    ),\n    MovedModule(\"copyreg\", \"copy_reg\"),\n    MovedModule(\"dbm_gnu\", \"gdbm\", \"dbm.gnu\"),\n    MovedModule(\"dbm_ndbm\", \"dbm\", \"dbm.ndbm\"),\n    MovedModule(\n        \"_dummy_thread\",\n        \"dummy_thread\",\n        \"_dummy_thread\" if sys.version_info < (3, 9) else \"_thread\",\n    ),\n    MovedModule(\"http_cookiejar\", \"cookielib\", \"http.cookiejar\"),\n    MovedModule(\"http_cookies\", \"Cookie\", \"http.cookies\"),\n    MovedModule(\"html_entities\", \"htmlentitydefs\", \"html.entities\"),\n    MovedModule(\"html_parser\", \"HTMLParser\", \"html.parser\"),\n    MovedModule(\"http_client\", \"httplib\", \"http.client\"),\n    MovedModule(\"email_mime_base\", \"email.MIMEBase\", \"email.mime.base\"),\n    MovedModule(\"email_mime_image\", \"email.MIMEImage\", \"email.mime.image\"),\n    MovedModule(\"email_mime_multipart\", \"email.MIMEMultipart\", \"email.mime.multipart\"),\n    MovedModule(\n        \"email_mime_nonmultipart\", \"email.MIMENonMultipart\", \"email.mime.nonmultipart\"\n    ),\n    MovedModule(\"email_mime_text\", \"email.MIMEText\", \"email.mime.text\"),\n    MovedModule(\"BaseHTTPServer\", \"BaseHTTPServer\", \"http.server\"),\n    MovedModule(\"CGIHTTPServer\", \"CGIHTTPServer\", \"http.server\"),\n    MovedModule(\"SimpleHTTPServer\", \"SimpleHTTPServer\", \"http.server\"),\n    MovedModule(\"cPickle\", \"cPickle\", \"pickle\"),\n    MovedModule(\"queue\", \"Queue\"),\n    MovedModule(\"reprlib\", \"repr\"),\n    MovedModule(\"socketserver\", \"SocketServer\"),\n    MovedModule(\"_thread\", \"thread\", \"_thread\"),\n    MovedModule(\"tkinter\", \"Tkinter\"),\n    MovedModule(\"tkinter_dialog\", \"Dialog\", \"tkinter.dialog\"),\n    MovedModule(\"tkinter_filedialog\", \"FileDialog\", \"tkinter.filedialog\"),\n    MovedModule(\"tkinter_scrolledtext\", \"ScrolledText\", \"tkinter.scrolledtext\"),\n    MovedModule(\"tkinter_simpledialog\", \"SimpleDialog\", \"tkinter.simpledialog\"),\n    MovedModule(\"tkinter_tix\", \"Tix\", \"tkinter.tix\"),\n    MovedModule(\"tkinter_ttk\", \"ttk\", \"tkinter.ttk\"),\n    MovedModule(\"tkinter_constants\", \"Tkconstants\", \"tkinter.constants\"),\n    MovedModule(\"tkinter_dnd\", \"Tkdnd\", \"tkinter.dnd\"),\n    MovedModule(\"tkinter_colorchooser\", \"tkColorChooser\", \"tkinter.colorchooser\"),\n    MovedModule(\"tkinter_commondialog\", \"tkCommonDialog\", \"tkinter.commondialog\"),\n    MovedModule(\"tkinter_tkfiledialog\", \"tkFileDialog\", \"tkinter.filedialog\"),\n    MovedModule(\"tkinter_font\", \"tkFont\", \"tkinter.font\"),\n    MovedModule(\"tkinter_messagebox\", \"tkMessageBox\", \"tkinter.messagebox\"),\n    MovedModule(\"tkinter_tksimpledialog\", \"tkSimpleDialog\", \"tkinter.simpledialog\"),\n    MovedModule(\"urllib_parse\", __name__ + \".moves.urllib_parse\", \"urllib.parse\"),\n    MovedModule(\"urllib_error\", __name__ + \".moves.urllib_error\", \"urllib.error\"),\n    MovedModule(\"urllib\", __name__ + \".moves.urllib\", __name__ + \".moves.urllib\"),\n    MovedModule(\"urllib_robotparser\", \"robotparser\", \"urllib.robotparser\"),\n    MovedModule(\"xmlrpc_client\", \"xmlrpclib\", \"xmlrpc.client\"),\n    MovedModule(\"xmlrpc_server\", \"SimpleXMLRPCServer\", \"xmlrpc.server\"),\n]\n# Add windows specific modules.\nif sys.platform == \"win32\":\n    _moved_attributes += [\n        MovedModule(\"winreg\", \"_winreg\"),\n    ]\n\nfor attr in _moved_attributes:\n    setattr(_MovedItems, attr.name, attr)\n    if isinstance(attr, MovedModule):\n        _importer._add_module(attr, \"moves.\" + attr.name)\ndel attr\n\n_MovedItems._moved_attributes = _moved_attributes\n\nmoves = _MovedItems(__name__ + \".moves\")\n_importer._add_module(moves, \"moves\")\n\n\nclass Module_six_moves_urllib_parse(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_parse\"\"\"\n\n\n_urllib_parse_moved_attributes = [\n    MovedAttribute(\"ParseResult\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"SplitResult\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"parse_qs\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"parse_qsl\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urldefrag\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urljoin\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urlparse\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urlsplit\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urlunparse\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"urlunsplit\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"quote\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"quote_plus\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"unquote\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"unquote_plus\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\n        \"unquote_to_bytes\", \"urllib\", \"urllib.parse\", \"unquote\", \"unquote_to_bytes\"\n    ),\n    MovedAttribute(\"urlencode\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"splitquery\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"splittag\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"splituser\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"splitvalue\", \"urllib\", \"urllib.parse\"),\n    MovedAttribute(\"uses_fragment\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"uses_netloc\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"uses_params\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"uses_query\", \"urlparse\", \"urllib.parse\"),\n    MovedAttribute(\"uses_relative\", \"urlparse\", \"urllib.parse\"),\n]\nfor attr in _urllib_parse_moved_attributes:\n    setattr(Module_six_moves_urllib_parse, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes\n\n_importer._add_module(\n    Module_six_moves_urllib_parse(__name__ + \".moves.urllib_parse\"),\n    \"moves.urllib_parse\",\n    \"moves.urllib.parse\",\n)\n\n\nclass Module_six_moves_urllib_error(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_error\"\"\"\n\n\n_urllib_error_moved_attributes = [\n    MovedAttribute(\"URLError\", \"urllib2\", \"urllib.error\"),\n    MovedAttribute(\"HTTPError\", \"urllib2\", \"urllib.error\"),\n    MovedAttribute(\"ContentTooShortError\", \"urllib\", \"urllib.error\"),\n]\nfor attr in _urllib_error_moved_attributes:\n    setattr(Module_six_moves_urllib_error, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes\n\n_importer._add_module(\n    Module_six_moves_urllib_error(__name__ + \".moves.urllib.error\"),\n    \"moves.urllib_error\",\n    \"moves.urllib.error\",\n)\n\n\nclass Module_six_moves_urllib_request(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_request\"\"\"\n\n\n_urllib_request_moved_attributes = [\n    MovedAttribute(\"urlopen\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"install_opener\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"build_opener\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"pathname2url\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"url2pathname\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"getproxies\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"Request\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"OpenerDirector\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPDefaultErrorHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPRedirectHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPCookieProcessor\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"ProxyHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"BaseHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPPasswordMgr\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPPasswordMgrWithDefaultRealm\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"AbstractBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"ProxyBasicAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"AbstractDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"ProxyDigestAuthHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPSHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"FileHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"FTPHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"CacheFTPHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"UnknownHandler\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"HTTPErrorProcessor\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"urlretrieve\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"urlcleanup\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"URLopener\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"FancyURLopener\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"proxy_bypass\", \"urllib\", \"urllib.request\"),\n    MovedAttribute(\"parse_http_list\", \"urllib2\", \"urllib.request\"),\n    MovedAttribute(\"parse_keqv_list\", \"urllib2\", \"urllib.request\"),\n]\nfor attr in _urllib_request_moved_attributes:\n    setattr(Module_six_moves_urllib_request, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes\n\n_importer._add_module(\n    Module_six_moves_urllib_request(__name__ + \".moves.urllib.request\"),\n    \"moves.urllib_request\",\n    \"moves.urllib.request\",\n)\n\n\nclass Module_six_moves_urllib_response(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_response\"\"\"\n\n\n_urllib_response_moved_attributes = [\n    MovedAttribute(\"addbase\", \"urllib\", \"urllib.response\"),\n    MovedAttribute(\"addclosehook\", \"urllib\", \"urllib.response\"),\n    MovedAttribute(\"addinfo\", \"urllib\", \"urllib.response\"),\n    MovedAttribute(\"addinfourl\", \"urllib\", \"urllib.response\"),\n]\nfor attr in _urllib_response_moved_attributes:\n    setattr(Module_six_moves_urllib_response, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes\n\n_importer._add_module(\n    Module_six_moves_urllib_response(__name__ + \".moves.urllib.response\"),\n    \"moves.urllib_response\",\n    \"moves.urllib.response\",\n)\n\n\nclass Module_six_moves_urllib_robotparser(_LazyModule):\n\n    \"\"\"Lazy loading of moved objects in six.moves.urllib_robotparser\"\"\"\n\n\n_urllib_robotparser_moved_attributes = [\n    MovedAttribute(\"RobotFileParser\", \"robotparser\", \"urllib.robotparser\"),\n]\nfor attr in _urllib_robotparser_moved_attributes:\n    setattr(Module_six_moves_urllib_robotparser, attr.name, attr)\ndel attr\n\nModule_six_moves_urllib_robotparser._moved_attributes = (\n    _urllib_robotparser_moved_attributes\n)\n\n_importer._add_module(\n    Module_six_moves_urllib_robotparser(__name__ + \".moves.urllib.robotparser\"),\n    \"moves.urllib_robotparser\",\n    \"moves.urllib.robotparser\",\n)\n\n\nclass Module_six_moves_urllib(types.ModuleType):\n\n    \"\"\"Create a six.moves.urllib namespace that resembles the Python 3 namespace\"\"\"\n\n    __path__ = []  # mark as package\n    parse = _importer._get_module(\"moves.urllib_parse\")\n    error = _importer._get_module(\"moves.urllib_error\")\n    request = _importer._get_module(\"moves.urllib_request\")\n    response = _importer._get_module(\"moves.urllib_response\")\n    robotparser = _importer._get_module(\"moves.urllib_robotparser\")\n\n    def __dir__(self):\n        return [\"parse\", \"error\", \"request\", \"response\", \"robotparser\"]\n\n\n_importer._add_module(\n    Module_six_moves_urllib(__name__ + \".moves.urllib\"), \"moves.urllib\"\n)\n\n\ndef add_move(move):\n    \"\"\"Add an item to six.moves.\"\"\"\n    setattr(_MovedItems, move.name, move)\n\n\ndef remove_move(name):\n    \"\"\"Remove item from six.moves.\"\"\"\n    try:\n        delattr(_MovedItems, name)\n    except AttributeError:\n        try:\n            del moves.__dict__[name]\n        except KeyError:\n            raise AttributeError(\"no such move, %r\" % (name,))\n\n\nif PY3:\n    _meth_func = \"__func__\"\n    _meth_self = \"__self__\"\n\n    _func_closure = \"__closure__\"\n    _func_code = \"__code__\"\n    _func_defaults = \"__defaults__\"\n    _func_globals = \"__globals__\"\nelse:\n    _meth_func = \"im_func\"\n    _meth_self = \"im_self\"\n\n    _func_closure = \"func_closure\"\n    _func_code = \"func_code\"\n    _func_defaults = \"func_defaults\"\n    _func_globals = \"func_globals\"\n\n\ntry:\n    advance_iterator = next\nexcept NameError:\n\n    def advance_iterator(it):\n        return it.next()\n\n\nnext = advance_iterator\n\n\ntry:\n    callable = callable\nexcept NameError:\n\n    def callable(obj):\n        return any(\"__call__\" in klass.__dict__ for klass in type(obj).__mro__)\n\n\nif PY3:\n\n    def get_unbound_function(unbound):\n        return unbound\n\n    create_bound_method = types.MethodType\n\n    def create_unbound_method(func, cls):\n        return func\n\n    Iterator = object\nelse:\n\n    def get_unbound_function(unbound):\n        return unbound.im_func\n\n    def create_bound_method(func, obj):\n        return types.MethodType(func, obj, obj.__class__)\n\n    def create_unbound_method(func, cls):\n        return types.MethodType(func, None, cls)\n\n    class Iterator(object):\n        def next(self):\n            return type(self).__next__(self)\n\n    callable = callable\n_add_doc(\n    get_unbound_function, \"\"\"Get the function out of a possibly unbound function\"\"\"\n)\n\n\nget_method_function = operator.attrgetter(_meth_func)\nget_method_self = operator.attrgetter(_meth_self)\nget_function_closure = operator.attrgetter(_func_closure)\nget_function_code = operator.attrgetter(_func_code)\nget_function_defaults = operator.attrgetter(_func_defaults)\nget_function_globals = operator.attrgetter(_func_globals)\n\n\nif PY3:\n\n    def iterkeys(d, **kw):\n        return iter(d.keys(**kw))\n\n    def itervalues(d, **kw):\n        return iter(d.values(**kw))\n\n    def iteritems(d, **kw):\n        return iter(d.items(**kw))\n\n    def iterlists(d, **kw):\n        return iter(d.lists(**kw))\n\n    viewkeys = operator.methodcaller(\"keys\")\n\n    viewvalues = operator.methodcaller(\"values\")\n\n    viewitems = operator.methodcaller(\"items\")\nelse:\n\n    def iterkeys(d, **kw):\n        return d.iterkeys(**kw)\n\n    def itervalues(d, **kw):\n        return d.itervalues(**kw)\n\n    def iteritems(d, **kw):\n        return d.iteritems(**kw)\n\n    def iterlists(d, **kw):\n        return d.iterlists(**kw)\n\n    viewkeys = operator.methodcaller(\"viewkeys\")\n\n    viewvalues = operator.methodcaller(\"viewvalues\")\n\n    viewitems = operator.methodcaller(\"viewitems\")\n\n_add_doc(iterkeys, \"Return an iterator over the keys of a dictionary.\")\n_add_doc(itervalues, \"Return an iterator over the values of a dictionary.\")\n_add_doc(iteritems, \"Return an iterator over the (key, value) pairs of a dictionary.\")\n_add_doc(\n    iterlists, \"Return an iterator over the (key, [values]) pairs of a dictionary.\"\n)\n\n\nif PY3:\n\n    def b(s):\n        return s.encode(\"latin-1\")\n\n    def u(s):\n        return s\n\n    unichr = chr\n    import struct\n\n    int2byte = struct.Struct(\">B\").pack\n    del struct\n    byte2int = operator.itemgetter(0)\n    indexbytes = operator.getitem\n    iterbytes = iter\n    import io\n\n    StringIO = io.StringIO\n    BytesIO = io.BytesIO\n    del io\n    _assertCountEqual = \"assertCountEqual\"\n    if sys.version_info[1] <= 1:\n        _assertRaisesRegex = \"assertRaisesRegexp\"\n        _assertRegex = \"assertRegexpMatches\"\n        _assertNotRegex = \"assertNotRegexpMatches\"\n    else:\n        _assertRaisesRegex = \"assertRaisesRegex\"\n        _assertRegex = \"assertRegex\"\n        _assertNotRegex = \"assertNotRegex\"\nelse:\n\n    def b(s):\n        return s\n\n    # Workaround for standalone backslash\n\n    def u(s):\n        return unicode(s.replace(r\"\\\\\", r\"\\\\\\\\\"), \"unicode_escape\")\n\n    unichr = unichr\n    int2byte = chr\n\n    def byte2int(bs):\n        return ord(bs[0])\n\n    def indexbytes(buf, i):\n        return ord(buf[i])\n\n    iterbytes = functools.partial(itertools.imap, ord)\n    import StringIO\n\n    StringIO = BytesIO = StringIO.StringIO\n    _assertCountEqual = \"assertItemsEqual\"\n    _assertRaisesRegex = \"assertRaisesRegexp\"\n    _assertRegex = \"assertRegexpMatches\"\n    _assertNotRegex = \"assertNotRegexpMatches\"\n_add_doc(b, \"\"\"Byte literal\"\"\")\n_add_doc(u, \"\"\"Text literal\"\"\")\n\n\ndef assertCountEqual(self, *args, **kwargs):\n    return getattr(self, _assertCountEqual)(*args, **kwargs)\n\n\ndef assertRaisesRegex(self, *args, **kwargs):\n    return getattr(self, _assertRaisesRegex)(*args, **kwargs)\n\n\ndef assertRegex(self, *args, **kwargs):\n    return getattr(self, _assertRegex)(*args, **kwargs)\n\n\ndef assertNotRegex(self, *args, **kwargs):\n    return getattr(self, _assertNotRegex)(*args, **kwargs)\n\n\nif PY3:\n    exec_ = getattr(moves.builtins, \"exec\")\n\n    def reraise(tp, value, tb=None):\n        try:\n            if value is None:\n                value = tp()\n            if value.__traceback__ is not tb:\n                raise value.with_traceback(tb)\n            raise value\n        finally:\n            value = None\n            tb = None\n\nelse:\n\n    def exec_(_code_, _globs_=None, _locs_=None):\n        \"\"\"Execute code in a namespace.\"\"\"\n        if _globs_ is None:\n            frame = sys._getframe(1)\n            _globs_ = frame.f_globals\n            if _locs_ is None:\n                _locs_ = frame.f_locals\n            del frame\n        elif _locs_ is None:\n            _locs_ = _globs_\n        exec (\"\"\"exec _code_ in _globs_, _locs_\"\"\")\n\n    exec_(\n        \"\"\"def reraise(tp, value, tb=None):\n    try:\n        raise tp, value, tb\n    finally:\n        tb = None\n\"\"\"\n    )\n\n\nif sys.version_info[:2] > (3,):\n    exec_(\n        \"\"\"def raise_from(value, from_value):\n    try:\n        raise value from from_value\n    finally:\n        value = None\n\"\"\"\n    )\nelse:\n\n    def raise_from(value, from_value):\n        raise value\n\n\nprint_ = getattr(moves.builtins, \"print\", None)\nif print_ is None:\n\n    def print_(*args, **kwargs):\n        \"\"\"The new-style print function for Python 2.4 and 2.5.\"\"\"\n        fp = kwargs.pop(\"file\", sys.stdout)\n        if fp is None:\n            return\n\n        def write(data):\n            if not isinstance(data, basestring):\n                data = str(data)\n            # If the file has an encoding, encode unicode with it.\n            if (\n                isinstance(fp, file)\n                and isinstance(data, unicode)\n                and fp.encoding is not None\n            ):\n                errors = getattr(fp, \"errors\", None)\n                if errors is None:\n                    errors = \"strict\"\n                data = data.encode(fp.encoding, errors)\n            fp.write(data)\n\n        want_unicode = False\n        sep = kwargs.pop(\"sep\", None)\n        if sep is not None:\n            if isinstance(sep, unicode):\n                want_unicode = True\n            elif not isinstance(sep, str):\n                raise TypeError(\"sep must be None or a string\")\n        end = kwargs.pop(\"end\", None)\n        if end is not None:\n            if isinstance(end, unicode):\n                want_unicode = True\n            elif not isinstance(end, str):\n                raise TypeError(\"end must be None or a string\")\n        if kwargs:\n            raise TypeError(\"invalid keyword arguments to print()\")\n        if not want_unicode:\n            for arg in args:\n                if isinstance(arg, unicode):\n                    want_unicode = True\n                    break\n        if want_unicode:\n            newline = unicode(\"\\n\")\n            space = unicode(\" \")\n        else:\n            newline = \"\\n\"\n            space = \" \"\n        if sep is None:\n            sep = space\n        if end is None:\n            end = newline\n        for i, arg in enumerate(args):\n            if i:\n                write(sep)\n            write(arg)\n        write(end)\n\n\nif sys.version_info[:2] < (3, 3):\n    _print = print_\n\n    def print_(*args, **kwargs):\n        fp = kwargs.get(\"file\", sys.stdout)\n        flush = kwargs.pop(\"flush\", False)\n        _print(*args, **kwargs)\n        if flush and fp is not None:\n            fp.flush()\n\n\n_add_doc(reraise, \"\"\"Reraise an exception.\"\"\")\n\nif sys.version_info[0:2] < (3, 4):\n    # This does exactly the same what the :func:`py3:functools.update_wrapper`\n    # function does on Python versions after 3.2. It sets the ``__wrapped__``\n    # attribute on ``wrapper`` object and it doesn't raise an error if any of\n    # the attributes mentioned in ``assigned`` and ``updated`` are missing on\n    # ``wrapped`` object.\n    def _update_wrapper(\n        wrapper,\n        wrapped,\n        assigned=functools.WRAPPER_ASSIGNMENTS,\n        updated=functools.WRAPPER_UPDATES,\n    ):\n        for attr in assigned:\n            try:\n                value = getattr(wrapped, attr)\n            except AttributeError:\n                continue\n            else:\n                setattr(wrapper, attr, value)\n        for attr in updated:\n            getattr(wrapper, attr).update(getattr(wrapped, attr, {}))\n        wrapper.__wrapped__ = wrapped\n        return wrapper\n\n    _update_wrapper.__doc__ = functools.update_wrapper.__doc__\n\n    def wraps(\n        wrapped,\n        assigned=functools.WRAPPER_ASSIGNMENTS,\n        updated=functools.WRAPPER_UPDATES,\n    ):\n        return functools.partial(\n            _update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated\n        )\n\n    wraps.__doc__ = functools.wraps.__doc__\n\nelse:\n    wraps = functools.wraps\n\n\ndef with_metaclass(meta, *bases):\n    \"\"\"Create a base class with a metaclass.\"\"\"\n    # This requires a bit of explanation: the basic idea is to make a dummy\n    # metaclass for one level of class instantiation that replaces itself with\n    # the actual metaclass.\n    class metaclass(type):\n        def __new__(cls, name, this_bases, d):\n            if sys.version_info[:2] >= (3, 7):\n                # This version introduced PEP 560 that requires a bit\n                # of extra care (we mimic what is done by __build_class__).\n                resolved_bases = types.resolve_bases(bases)\n                if resolved_bases is not bases:\n                    d[\"__orig_bases__\"] = bases\n            else:\n                resolved_bases = bases\n            return meta(name, resolved_bases, d)\n\n        @classmethod\n        def __prepare__(cls, name, this_bases):\n            return meta.__prepare__(name, bases)\n\n    return type.__new__(metaclass, \"temporary_class\", (), {})\n\n\ndef add_metaclass(metaclass):\n    \"\"\"Class decorator for creating a class with a metaclass.\"\"\"\n\n    def wrapper(cls):\n        orig_vars = cls.__dict__.copy()\n        slots = orig_vars.get(\"__slots__\")\n        if slots is not None:\n            if isinstance(slots, str):\n                slots = [slots]\n            for slots_var in slots:\n                orig_vars.pop(slots_var)\n        orig_vars.pop(\"__dict__\", None)\n        orig_vars.pop(\"__weakref__\", None)\n        if hasattr(cls, \"__qualname__\"):\n            orig_vars[\"__qualname__\"] = cls.__qualname__\n        return metaclass(cls.__name__, cls.__bases__, orig_vars)\n\n    return wrapper\n\n\ndef ensure_binary(s, encoding=\"utf-8\", errors=\"strict\"):\n    \"\"\"Coerce **s** to six.binary_type.\n\n    For Python 2:\n      - `unicode` -> encoded to `str`\n      - `str` -> `str`\n\n    For Python 3:\n      - `str` -> encoded to `bytes`\n      - `bytes` -> `bytes`\n    \"\"\"\n    if isinstance(s, binary_type):\n        return s\n    if isinstance(s, text_type):\n        return s.encode(encoding, errors)\n    raise TypeError(\"not expecting type '%s'\" % type(s))\n\n\ndef ensure_str(s, encoding=\"utf-8\", errors=\"strict\"):\n    \"\"\"Coerce *s* to `str`.\n\n    For Python 2:\n      - `unicode` -> encoded to `str`\n      - `str` -> `str`\n\n    For Python 3:\n      - `str` -> `str`\n      - `bytes` -> decoded to `str`\n    \"\"\"\n    # Optimization: Fast return for the common case.\n    if type(s) is str:\n        return s\n    if PY2 and isinstance(s, text_type):\n        return s.encode(encoding, errors)\n    elif PY3 and isinstance(s, binary_type):\n        return s.decode(encoding, errors)\n    elif not isinstance(s, (text_type, binary_type)):\n        raise TypeError(\"not expecting type '%s'\" % type(s))\n    return s\n\n\ndef ensure_text(s, encoding=\"utf-8\", errors=\"strict\"):\n    \"\"\"Coerce *s* to six.text_type.\n\n    For Python 2:\n      - `unicode` -> `unicode`\n      - `str` -> `unicode`\n\n    For Python 3:\n      - `str` -> `str`\n      - `bytes` -> decoded to `str`\n    \"\"\"\n    if isinstance(s, binary_type):\n        return s.decode(encoding, errors)\n    elif isinstance(s, text_type):\n        return s\n    else:\n        raise TypeError(\"not expecting type '%s'\" % type(s))\n\n\ndef python_2_unicode_compatible(klass):\n    \"\"\"\n    A class decorator that defines __unicode__ and __str__ methods under Python 2.\n    Under Python 3 it does nothing.\n\n    To support Python 2 and 3 with a single code base, define a __str__ method\n    returning text and apply this decorator to the class.\n    \"\"\"\n    if PY2:\n        if \"__str__\" not in klass.__dict__:\n            raise ValueError(\n                \"@python_2_unicode_compatible cannot be applied \"\n                \"to %s because it doesn't define __str__().\" % klass.__name__\n            )\n        klass.__unicode__ = klass.__str__\n        klass.__str__ = lambda self: self.__unicode__().encode(\"utf-8\")\n    return klass\n\n\n# Complete the moves implementation.\n# This code is at the end of this module to speed up module loading.\n# Turn this module into a package.\n__path__ = []  # required for PEP 302 and PEP 451\n__package__ = __name__  # see PEP 366 @ReservedAssignment\nif globals().get(\"__spec__\") is not None:\n    __spec__.submodule_search_locations = []  # PEP 451 @UndefinedVariable\n# Remove other six meta path importers, since they cause problems. This can\n# happen if six is removed from sys.modules and then reloaded. (Setuptools does\n# this for some reason.)\nif sys.meta_path:\n    for i, importer in enumerate(sys.meta_path):\n        # Here's some real nastiness: Another \"instance\" of the six module might\n        # be floating around. Therefore, we can't use isinstance() to check for\n        # the six meta path importer, since the other six instance will have\n        # inserted an importer with different class.\n        if (\n            type(importer).__name__ == \"_SixMetaPathImporter\"\n            and importer.name == __name__\n        ):\n            del sys.meta_path[i]\n            break\n    del i, importer\n# Finally, add the importer to the meta path import hook.\nsys.meta_path.append(_importer)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/poolmanager.py",
    "content": "from __future__ import absolute_import\n\nimport collections\nimport functools\nimport logging\n\nfrom ._collections import RecentlyUsedContainer\nfrom .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme\nfrom .exceptions import (\n    LocationValueError,\n    MaxRetryError,\n    ProxySchemeUnknown,\n    ProxySchemeUnsupported,\n    URLSchemeUnknown,\n)\nfrom .packages import six\nfrom .packages.six.moves.urllib.parse import urljoin\nfrom .request import RequestMethods\nfrom .util.proxy import connection_requires_http_tunnel\nfrom .util.retry import Retry\nfrom .util.url import parse_url\n\n__all__ = [\"PoolManager\", \"ProxyManager\", \"proxy_from_url\"]\n\n\nlog = logging.getLogger(__name__)\n\nSSL_KEYWORDS = (\n    \"key_file\",\n    \"cert_file\",\n    \"cert_reqs\",\n    \"ca_certs\",\n    \"ssl_version\",\n    \"ca_cert_dir\",\n    \"ssl_context\",\n    \"key_password\",\n    \"server_hostname\",\n)\n\n# All known keyword arguments that could be provided to the pool manager, its\n# pools, or the underlying connections. This is used to construct a pool key.\n_key_fields = (\n    \"key_scheme\",  # str\n    \"key_host\",  # str\n    \"key_port\",  # int\n    \"key_timeout\",  # int or float or Timeout\n    \"key_retries\",  # int or Retry\n    \"key_strict\",  # bool\n    \"key_block\",  # bool\n    \"key_source_address\",  # str\n    \"key_key_file\",  # str\n    \"key_key_password\",  # str\n    \"key_cert_file\",  # str\n    \"key_cert_reqs\",  # str\n    \"key_ca_certs\",  # str\n    \"key_ssl_version\",  # str\n    \"key_ca_cert_dir\",  # str\n    \"key_ssl_context\",  # instance of ssl.SSLContext or urllib3.util.ssl_.SSLContext\n    \"key_maxsize\",  # int\n    \"key_headers\",  # dict\n    \"key__proxy\",  # parsed proxy url\n    \"key__proxy_headers\",  # dict\n    \"key__proxy_config\",  # class\n    \"key_socket_options\",  # list of (level (int), optname (int), value (int or str)) tuples\n    \"key__socks_options\",  # dict\n    \"key_assert_hostname\",  # bool or string\n    \"key_assert_fingerprint\",  # str\n    \"key_server_hostname\",  # str\n)\n\n#: The namedtuple class used to construct keys for the connection pool.\n#: All custom key schemes should include the fields in this key at a minimum.\nPoolKey = collections.namedtuple(\"PoolKey\", _key_fields)\n\n_proxy_config_fields = (\"ssl_context\", \"use_forwarding_for_https\")\nProxyConfig = collections.namedtuple(\"ProxyConfig\", _proxy_config_fields)\n\n\ndef _default_key_normalizer(key_class, request_context):\n    \"\"\"\n    Create a pool key out of a request context dictionary.\n\n    According to RFC 3986, both the scheme and host are case-insensitive.\n    Therefore, this function normalizes both before constructing the pool\n    key for an HTTPS request. If you wish to change this behaviour, provide\n    alternate callables to ``key_fn_by_scheme``.\n\n    :param key_class:\n        The class to use when constructing the key. This should be a namedtuple\n        with the ``scheme`` and ``host`` keys at a minimum.\n    :type  key_class: namedtuple\n    :param request_context:\n        A dictionary-like object that contain the context for a request.\n    :type  request_context: dict\n\n    :return: A namedtuple that can be used as a connection pool key.\n    :rtype:  PoolKey\n    \"\"\"\n    # Since we mutate the dictionary, make a copy first\n    context = request_context.copy()\n    context[\"scheme\"] = context[\"scheme\"].lower()\n    context[\"host\"] = context[\"host\"].lower()\n\n    # These are both dictionaries and need to be transformed into frozensets\n    for key in (\"headers\", \"_proxy_headers\", \"_socks_options\"):\n        if key in context and context[key] is not None:\n            context[key] = frozenset(context[key].items())\n\n    # The socket_options key may be a list and needs to be transformed into a\n    # tuple.\n    socket_opts = context.get(\"socket_options\")\n    if socket_opts is not None:\n        context[\"socket_options\"] = tuple(socket_opts)\n\n    # Map the kwargs to the names in the namedtuple - this is necessary since\n    # namedtuples can't have fields starting with '_'.\n    for key in list(context.keys()):\n        context[\"key_\" + key] = context.pop(key)\n\n    # Default to ``None`` for keys missing from the context\n    for field in key_class._fields:\n        if field not in context:\n            context[field] = None\n\n    return key_class(**context)\n\n\n#: A dictionary that maps a scheme to a callable that creates a pool key.\n#: This can be used to alter the way pool keys are constructed, if desired.\n#: Each PoolManager makes a copy of this dictionary so they can be configured\n#: globally here, or individually on the instance.\nkey_fn_by_scheme = {\n    \"http\": functools.partial(_default_key_normalizer, PoolKey),\n    \"https\": functools.partial(_default_key_normalizer, PoolKey),\n}\n\npool_classes_by_scheme = {\"http\": HTTPConnectionPool, \"https\": HTTPSConnectionPool}\n\n\nclass PoolManager(RequestMethods):\n    \"\"\"\n    Allows for arbitrary requests while transparently keeping track of\n    necessary connection pools for you.\n\n    :param num_pools:\n        Number of connection pools to cache before discarding the least\n        recently used pool.\n\n    :param headers:\n        Headers to include with all requests, unless other headers are given\n        explicitly.\n\n    :param \\\\**connection_pool_kw:\n        Additional parameters are used to create fresh\n        :class:`urllib3.connectionpool.ConnectionPool` instances.\n\n    Example::\n\n        >>> manager = PoolManager(num_pools=2)\n        >>> r = manager.request('GET', 'http://google.com/')\n        >>> r = manager.request('GET', 'http://google.com/mail')\n        >>> r = manager.request('GET', 'http://yahoo.com/')\n        >>> len(manager.pools)\n        2\n\n    \"\"\"\n\n    proxy = None\n    proxy_config = None\n\n    def __init__(self, num_pools=10, headers=None, **connection_pool_kw):\n        RequestMethods.__init__(self, headers)\n        self.connection_pool_kw = connection_pool_kw\n        self.pools = RecentlyUsedContainer(num_pools, dispose_func=lambda p: p.close())\n\n        # Locally set the pool classes and keys so other PoolManagers can\n        # override them.\n        self.pool_classes_by_scheme = pool_classes_by_scheme\n        self.key_fn_by_scheme = key_fn_by_scheme.copy()\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        self.clear()\n        # Return False to re-raise any potential exceptions\n        return False\n\n    def _new_pool(self, scheme, host, port, request_context=None):\n        \"\"\"\n        Create a new :class:`urllib3.connectionpool.ConnectionPool` based on host, port, scheme, and\n        any additional pool keyword arguments.\n\n        If ``request_context`` is provided, it is provided as keyword arguments\n        to the pool class used. This method is used to actually create the\n        connection pools handed out by :meth:`connection_from_url` and\n        companion methods. It is intended to be overridden for customization.\n        \"\"\"\n        pool_cls = self.pool_classes_by_scheme[scheme]\n        if request_context is None:\n            request_context = self.connection_pool_kw.copy()\n\n        # Although the context has everything necessary to create the pool,\n        # this function has historically only used the scheme, host, and port\n        # in the positional args. When an API change is acceptable these can\n        # be removed.\n        for key in (\"scheme\", \"host\", \"port\"):\n            request_context.pop(key, None)\n\n        if scheme == \"http\":\n            for kw in SSL_KEYWORDS:\n                request_context.pop(kw, None)\n\n        return pool_cls(host, port, **request_context)\n\n    def clear(self):\n        \"\"\"\n        Empty our store of pools and direct them all to close.\n\n        This will not affect in-flight connections, but they will not be\n        re-used after completion.\n        \"\"\"\n        self.pools.clear()\n\n    def connection_from_host(self, host, port=None, scheme=\"http\", pool_kwargs=None):\n        \"\"\"\n        Get a :class:`urllib3.connectionpool.ConnectionPool` based on the host, port, and scheme.\n\n        If ``port`` isn't given, it will be derived from the ``scheme`` using\n        ``urllib3.connectionpool.port_by_scheme``. If ``pool_kwargs`` is\n        provided, it is merged with the instance's ``connection_pool_kw``\n        variable and used to create the new connection pool, if one is\n        needed.\n        \"\"\"\n\n        if not host:\n            raise LocationValueError(\"No host specified.\")\n\n        request_context = self._merge_pool_kwargs(pool_kwargs)\n        request_context[\"scheme\"] = scheme or \"http\"\n        if not port:\n            port = port_by_scheme.get(request_context[\"scheme\"].lower(), 80)\n        request_context[\"port\"] = port\n        request_context[\"host\"] = host\n\n        return self.connection_from_context(request_context)\n\n    def connection_from_context(self, request_context):\n        \"\"\"\n        Get a :class:`urllib3.connectionpool.ConnectionPool` based on the request context.\n\n        ``request_context`` must at least contain the ``scheme`` key and its\n        value must be a key in ``key_fn_by_scheme`` instance variable.\n        \"\"\"\n        scheme = request_context[\"scheme\"].lower()\n        pool_key_constructor = self.key_fn_by_scheme.get(scheme)\n        if not pool_key_constructor:\n            raise URLSchemeUnknown(scheme)\n        pool_key = pool_key_constructor(request_context)\n\n        return self.connection_from_pool_key(pool_key, request_context=request_context)\n\n    def connection_from_pool_key(self, pool_key, request_context=None):\n        \"\"\"\n        Get a :class:`urllib3.connectionpool.ConnectionPool` based on the provided pool key.\n\n        ``pool_key`` should be a namedtuple that only contains immutable\n        objects. At a minimum it must have the ``scheme``, ``host``, and\n        ``port`` fields.\n        \"\"\"\n        with self.pools.lock:\n            # If the scheme, host, or port doesn't match existing open\n            # connections, open a new ConnectionPool.\n            pool = self.pools.get(pool_key)\n            if pool:\n                return pool\n\n            # Make a fresh ConnectionPool of the desired type\n            scheme = request_context[\"scheme\"]\n            host = request_context[\"host\"]\n            port = request_context[\"port\"]\n            pool = self._new_pool(scheme, host, port, request_context=request_context)\n            self.pools[pool_key] = pool\n\n        return pool\n\n    def connection_from_url(self, url, pool_kwargs=None):\n        \"\"\"\n        Similar to :func:`urllib3.connectionpool.connection_from_url`.\n\n        If ``pool_kwargs`` is not provided and a new pool needs to be\n        constructed, ``self.connection_pool_kw`` is used to initialize\n        the :class:`urllib3.connectionpool.ConnectionPool`. If ``pool_kwargs``\n        is provided, it is used instead. Note that if a new pool does not\n        need to be created for the request, the provided ``pool_kwargs`` are\n        not used.\n        \"\"\"\n        u = parse_url(url)\n        return self.connection_from_host(\n            u.host, port=u.port, scheme=u.scheme, pool_kwargs=pool_kwargs\n        )\n\n    def _merge_pool_kwargs(self, override):\n        \"\"\"\n        Merge a dictionary of override values for self.connection_pool_kw.\n\n        This does not modify self.connection_pool_kw and returns a new dict.\n        Any keys in the override dictionary with a value of ``None`` are\n        removed from the merged dictionary.\n        \"\"\"\n        base_pool_kwargs = self.connection_pool_kw.copy()\n        if override:\n            for key, value in override.items():\n                if value is None:\n                    try:\n                        del base_pool_kwargs[key]\n                    except KeyError:\n                        pass\n                else:\n                    base_pool_kwargs[key] = value\n        return base_pool_kwargs\n\n    def _proxy_requires_url_absolute_form(self, parsed_url):\n        \"\"\"\n        Indicates if the proxy requires the complete destination URL in the\n        request.  Normally this is only needed when not using an HTTP CONNECT\n        tunnel.\n        \"\"\"\n        if self.proxy is None:\n            return False\n\n        return not connection_requires_http_tunnel(\n            self.proxy, self.proxy_config, parsed_url.scheme\n        )\n\n    def _validate_proxy_scheme_url_selection(self, url_scheme):\n        \"\"\"\n        Validates that were not attempting to do TLS in TLS connections on\n        Python2 or with unsupported SSL implementations.\n        \"\"\"\n        if self.proxy is None or url_scheme != \"https\":\n            return\n\n        if self.proxy.scheme != \"https\":\n            return\n\n        if six.PY2 and not self.proxy_config.use_forwarding_for_https:\n            raise ProxySchemeUnsupported(\n                \"Contacting HTTPS destinations through HTTPS proxies \"\n                \"'via CONNECT tunnels' is not supported in Python 2\"\n            )\n\n    def urlopen(self, method, url, redirect=True, **kw):\n        \"\"\"\n        Same as :meth:`urllib3.HTTPConnectionPool.urlopen`\n        with custom cross-host redirect logic and only sends the request-uri\n        portion of the ``url``.\n\n        The given ``url`` parameter must be absolute, such that an appropriate\n        :class:`urllib3.connectionpool.ConnectionPool` can be chosen for it.\n        \"\"\"\n        u = parse_url(url)\n        self._validate_proxy_scheme_url_selection(u.scheme)\n\n        conn = self.connection_from_host(u.host, port=u.port, scheme=u.scheme)\n\n        kw[\"assert_same_host\"] = False\n        kw[\"redirect\"] = False\n\n        if \"headers\" not in kw:\n            kw[\"headers\"] = self.headers.copy()\n\n        if self._proxy_requires_url_absolute_form(u):\n            response = conn.urlopen(method, url, **kw)\n        else:\n            response = conn.urlopen(method, u.request_uri, **kw)\n\n        redirect_location = redirect and response.get_redirect_location()\n        if not redirect_location:\n            return response\n\n        # Support relative URLs for redirecting.\n        redirect_location = urljoin(url, redirect_location)\n\n        # RFC 7231, Section 6.4.4\n        if response.status == 303:\n            method = \"GET\"\n\n        retries = kw.get(\"retries\")\n        if not isinstance(retries, Retry):\n            retries = Retry.from_int(retries, redirect=redirect)\n\n        # Strip headers marked as unsafe to forward to the redirected location.\n        # Check remove_headers_on_redirect to avoid a potential network call within\n        # conn.is_same_host() which may use socket.gethostbyname() in the future.\n        if retries.remove_headers_on_redirect and not conn.is_same_host(\n            redirect_location\n        ):\n            headers = list(six.iterkeys(kw[\"headers\"]))\n            for header in headers:\n                if header.lower() in retries.remove_headers_on_redirect:\n                    kw[\"headers\"].pop(header, None)\n\n        try:\n            retries = retries.increment(method, url, response=response, _pool=conn)\n        except MaxRetryError:\n            if retries.raise_on_redirect:\n                response.drain_conn()\n                raise\n            return response\n\n        kw[\"retries\"] = retries\n        kw[\"redirect\"] = redirect\n\n        log.info(\"Redirecting %s -> %s\", url, redirect_location)\n\n        response.drain_conn()\n        return self.urlopen(method, redirect_location, **kw)\n\n\nclass ProxyManager(PoolManager):\n    \"\"\"\n    Behaves just like :class:`PoolManager`, but sends all requests through\n    the defined proxy, using the CONNECT method for HTTPS URLs.\n\n    :param proxy_url:\n        The URL of the proxy to be used.\n\n    :param proxy_headers:\n        A dictionary containing headers that will be sent to the proxy. In case\n        of HTTP they are being sent with each request, while in the\n        HTTPS/CONNECT case they are sent only once. Could be used for proxy\n        authentication.\n\n    :param proxy_ssl_context:\n        The proxy SSL context is used to establish the TLS connection to the\n        proxy when using HTTPS proxies.\n\n    :param use_forwarding_for_https:\n        (Defaults to False) If set to True will forward requests to the HTTPS\n        proxy to be made on behalf of the client instead of creating a TLS\n        tunnel via the CONNECT method. **Enabling this flag means that request\n        and response headers and content will be visible from the HTTPS proxy**\n        whereas tunneling keeps request and response headers and content\n        private.  IP address, target hostname, SNI, and port are always visible\n        to an HTTPS proxy even when this flag is disabled.\n\n    Example:\n        >>> proxy = urllib3.ProxyManager('http://localhost:3128/')\n        >>> r1 = proxy.request('GET', 'http://google.com/')\n        >>> r2 = proxy.request('GET', 'http://httpbin.org/')\n        >>> len(proxy.pools)\n        1\n        >>> r3 = proxy.request('GET', 'https://httpbin.org/')\n        >>> r4 = proxy.request('GET', 'https://twitter.com/')\n        >>> len(proxy.pools)\n        3\n\n    \"\"\"\n\n    def __init__(\n        self,\n        proxy_url,\n        num_pools=10,\n        headers=None,\n        proxy_headers=None,\n        proxy_ssl_context=None,\n        use_forwarding_for_https=False,\n        **connection_pool_kw\n    ):\n\n        if isinstance(proxy_url, HTTPConnectionPool):\n            proxy_url = \"%s://%s:%i\" % (\n                proxy_url.scheme,\n                proxy_url.host,\n                proxy_url.port,\n            )\n        proxy = parse_url(proxy_url)\n\n        if proxy.scheme not in (\"http\", \"https\"):\n            raise ProxySchemeUnknown(proxy.scheme)\n\n        if not proxy.port:\n            port = port_by_scheme.get(proxy.scheme, 80)\n            proxy = proxy._replace(port=port)\n\n        self.proxy = proxy\n        self.proxy_headers = proxy_headers or {}\n        self.proxy_ssl_context = proxy_ssl_context\n        self.proxy_config = ProxyConfig(proxy_ssl_context, use_forwarding_for_https)\n\n        connection_pool_kw[\"_proxy\"] = self.proxy\n        connection_pool_kw[\"_proxy_headers\"] = self.proxy_headers\n        connection_pool_kw[\"_proxy_config\"] = self.proxy_config\n\n        super(ProxyManager, self).__init__(num_pools, headers, **connection_pool_kw)\n\n    def connection_from_host(self, host, port=None, scheme=\"http\", pool_kwargs=None):\n        if scheme == \"https\":\n            return super(ProxyManager, self).connection_from_host(\n                host, port, scheme, pool_kwargs=pool_kwargs\n            )\n\n        return super(ProxyManager, self).connection_from_host(\n            self.proxy.host, self.proxy.port, self.proxy.scheme, pool_kwargs=pool_kwargs\n        )\n\n    def _set_proxy_headers(self, url, headers=None):\n        \"\"\"\n        Sets headers needed by proxies: specifically, the Accept and Host\n        headers. Only sets headers not provided by the user.\n        \"\"\"\n        headers_ = {\"Accept\": \"*/*\"}\n\n        netloc = parse_url(url).netloc\n        if netloc:\n            headers_[\"Host\"] = netloc\n\n        if headers:\n            headers_.update(headers)\n        return headers_\n\n    def urlopen(self, method, url, redirect=True, **kw):\n        \"Same as HTTP(S)ConnectionPool.urlopen, ``url`` must be absolute.\"\n        u = parse_url(url)\n        if not connection_requires_http_tunnel(self.proxy, self.proxy_config, u.scheme):\n            # For connections using HTTP CONNECT, httplib sets the necessary\n            # headers on the CONNECT to the proxy. If we're not using CONNECT,\n            # we'll definitely need to set 'Host' at the very least.\n            headers = kw.get(\"headers\", self.headers)\n            kw[\"headers\"] = self._set_proxy_headers(url, headers)\n\n        return super(ProxyManager, self).urlopen(method, url, redirect=redirect, **kw)\n\n\ndef proxy_from_url(url, **kw):\n    return ProxyManager(proxy_url=url, **kw)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/request.py",
    "content": "from __future__ import absolute_import\n\nfrom .filepost import encode_multipart_formdata\nfrom .packages.six.moves.urllib.parse import urlencode\n\n__all__ = [\"RequestMethods\"]\n\n\nclass RequestMethods(object):\n    \"\"\"\n    Convenience mixin for classes who implement a :meth:`urlopen` method, such\n    as :class:`urllib3.HTTPConnectionPool` and\n    :class:`urllib3.PoolManager`.\n\n    Provides behavior for making common types of HTTP request methods and\n    decides which type of request field encoding to use.\n\n    Specifically,\n\n    :meth:`.request_encode_url` is for sending requests whose fields are\n    encoded in the URL (such as GET, HEAD, DELETE).\n\n    :meth:`.request_encode_body` is for sending requests whose fields are\n    encoded in the *body* of the request using multipart or www-form-urlencoded\n    (such as for POST, PUT, PATCH).\n\n    :meth:`.request` is for making any kind of request, it will look up the\n    appropriate encoding format and use one of the above two methods to make\n    the request.\n\n    Initializer parameters:\n\n    :param headers:\n        Headers to include with all requests, unless other headers are given\n        explicitly.\n    \"\"\"\n\n    _encode_url_methods = {\"DELETE\", \"GET\", \"HEAD\", \"OPTIONS\"}\n\n    def __init__(self, headers=None):\n        self.headers = headers or {}\n\n    def urlopen(\n        self,\n        method,\n        url,\n        body=None,\n        headers=None,\n        encode_multipart=True,\n        multipart_boundary=None,\n        **kw\n    ):  # Abstract\n        raise NotImplementedError(\n            \"Classes extending RequestMethods must implement \"\n            \"their own ``urlopen`` method.\"\n        )\n\n    def request(self, method, url, fields=None, headers=None, **urlopen_kw):\n        \"\"\"\n        Make a request using :meth:`urlopen` with the appropriate encoding of\n        ``fields`` based on the ``method`` used.\n\n        This is a convenience method that requires the least amount of manual\n        effort. It can be used in most situations, while still having the\n        option to drop down to more specific methods when necessary, such as\n        :meth:`request_encode_url`, :meth:`request_encode_body`,\n        or even the lowest level :meth:`urlopen`.\n        \"\"\"\n        method = method.upper()\n\n        urlopen_kw[\"request_url\"] = url\n\n        if method in self._encode_url_methods:\n            return self.request_encode_url(\n                method, url, fields=fields, headers=headers, **urlopen_kw\n            )\n        else:\n            return self.request_encode_body(\n                method, url, fields=fields, headers=headers, **urlopen_kw\n            )\n\n    def request_encode_url(self, method, url, fields=None, headers=None, **urlopen_kw):\n        \"\"\"\n        Make a request using :meth:`urlopen` with the ``fields`` encoded in\n        the url. This is useful for request methods like GET, HEAD, DELETE, etc.\n        \"\"\"\n        if headers is None:\n            headers = self.headers\n\n        extra_kw = {\"headers\": headers}\n        extra_kw.update(urlopen_kw)\n\n        if fields:\n            url += \"?\" + urlencode(fields)\n\n        return self.urlopen(method, url, **extra_kw)\n\n    def request_encode_body(\n        self,\n        method,\n        url,\n        fields=None,\n        headers=None,\n        encode_multipart=True,\n        multipart_boundary=None,\n        **urlopen_kw\n    ):\n        \"\"\"\n        Make a request using :meth:`urlopen` with the ``fields`` encoded in\n        the body. This is useful for request methods like POST, PUT, PATCH, etc.\n\n        When ``encode_multipart=True`` (default), then\n        :func:`urllib3.encode_multipart_formdata` is used to encode\n        the payload with the appropriate content type. Otherwise\n        :func:`urllib.parse.urlencode` is used with the\n        'application/x-www-form-urlencoded' content type.\n\n        Multipart encoding must be used when posting files, and it's reasonably\n        safe to use it in other times too. However, it may break request\n        signing, such as with OAuth.\n\n        Supports an optional ``fields`` parameter of key/value strings AND\n        key/filetuple. A filetuple is a (filename, data, MIME type) tuple where\n        the MIME type is optional. For example::\n\n            fields = {\n                'foo': 'bar',\n                'fakefile': ('foofile.txt', 'contents of foofile'),\n                'realfile': ('barfile.txt', open('realfile').read()),\n                'typedfile': ('bazfile.bin', open('bazfile').read(),\n                              'image/jpeg'),\n                'nonamefile': 'contents of nonamefile field',\n            }\n\n        When uploading a file, providing a filename (the first parameter of the\n        tuple) is optional but recommended to best mimic behavior of browsers.\n\n        Note that if ``headers`` are supplied, the 'Content-Type' header will\n        be overwritten because it depends on the dynamic random boundary string\n        which is used to compose the body of the request. The random boundary\n        string can be explicitly set with the ``multipart_boundary`` parameter.\n        \"\"\"\n        if headers is None:\n            headers = self.headers\n\n        extra_kw = {\"headers\": {}}\n\n        if fields:\n            if \"body\" in urlopen_kw:\n                raise TypeError(\n                    \"request got values for both 'fields' and 'body', can only specify one.\"\n                )\n\n            if encode_multipart:\n                body, content_type = encode_multipart_formdata(\n                    fields, boundary=multipart_boundary\n                )\n            else:\n                body, content_type = (\n                    urlencode(fields),\n                    \"application/x-www-form-urlencoded\",\n                )\n\n            extra_kw[\"body\"] = body\n            extra_kw[\"headers\"] = {\"Content-Type\": content_type}\n\n        extra_kw[\"headers\"].update(headers)\n        extra_kw.update(urlopen_kw)\n\n        return self.urlopen(method, url, **extra_kw)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/response.py",
    "content": "from __future__ import absolute_import\n\nimport io\nimport logging\nimport sys\nimport zlib\nfrom contextlib import contextmanager\nfrom socket import error as SocketError\nfrom socket import timeout as SocketTimeout\n\nbrotli = None\n\nfrom . import util\nfrom ._collections import HTTPHeaderDict\nfrom .connection import BaseSSLError, HTTPException\nfrom .exceptions import (\n    BodyNotHttplibCompatible,\n    DecodeError,\n    HTTPError,\n    IncompleteRead,\n    InvalidChunkLength,\n    InvalidHeader,\n    ProtocolError,\n    ReadTimeoutError,\n    ResponseNotChunked,\n    SSLError,\n)\nfrom .packages import six\nfrom .util.response import is_fp_closed, is_response_to_head\n\nlog = logging.getLogger(__name__)\n\n\nclass DeflateDecoder(object):\n    def __init__(self):\n        self._first_try = True\n        self._data = b\"\"\n        self._obj = zlib.decompressobj()\n\n    def __getattr__(self, name):\n        return getattr(self._obj, name)\n\n    def decompress(self, data):\n        if not data:\n            return data\n\n        if not self._first_try:\n            return self._obj.decompress(data)\n\n        self._data += data\n        try:\n            decompressed = self._obj.decompress(data)\n            if decompressed:\n                self._first_try = False\n                self._data = None\n            return decompressed\n        except zlib.error:\n            self._first_try = False\n            self._obj = zlib.decompressobj(-zlib.MAX_WBITS)\n            try:\n                return self.decompress(self._data)\n            finally:\n                self._data = None\n\n\nclass GzipDecoderState(object):\n\n    FIRST_MEMBER = 0\n    OTHER_MEMBERS = 1\n    SWALLOW_DATA = 2\n\n\nclass GzipDecoder(object):\n    def __init__(self):\n        self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)\n        self._state = GzipDecoderState.FIRST_MEMBER\n\n    def __getattr__(self, name):\n        return getattr(self._obj, name)\n\n    def decompress(self, data):\n        ret = bytearray()\n        if self._state == GzipDecoderState.SWALLOW_DATA or not data:\n            return bytes(ret)\n        while True:\n            try:\n                ret += self._obj.decompress(data)\n            except zlib.error:\n                previous_state = self._state\n                # Ignore data after the first error\n                self._state = GzipDecoderState.SWALLOW_DATA\n                if previous_state == GzipDecoderState.OTHER_MEMBERS:\n                    # Allow trailing garbage acceptable in other gzip clients\n                    return bytes(ret)\n                raise\n            data = self._obj.unused_data\n            if not data:\n                return bytes(ret)\n            self._state = GzipDecoderState.OTHER_MEMBERS\n            self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n\nif brotli is not None:\n\n    class BrotliDecoder(object):\n        # Supports both 'brotlipy' and 'Brotli' packages\n        # since they share an import name. The top branches\n        # are for 'brotlipy' and bottom branches for 'Brotli'\n        def __init__(self):\n            self._obj = brotli.Decompressor()\n            if hasattr(self._obj, \"decompress\"):\n                self.decompress = self._obj.decompress\n            else:\n                self.decompress = self._obj.process\n\n        def flush(self):\n            if hasattr(self._obj, \"flush\"):\n                return self._obj.flush()\n            return b\"\"\n\n\nclass MultiDecoder(object):\n    \"\"\"\n    From RFC7231:\n        If one or more encodings have been applied to a representation, the\n        sender that applied the encodings MUST generate a Content-Encoding\n        header field that lists the content codings in the order in which\n        they were applied.\n    \"\"\"\n\n    def __init__(self, modes):\n        self._decoders = [_get_decoder(m.strip()) for m in modes.split(\",\")]\n\n    def flush(self):\n        return self._decoders[0].flush()\n\n    def decompress(self, data):\n        for d in reversed(self._decoders):\n            data = d.decompress(data)\n        return data\n\n\ndef _get_decoder(mode):\n    if \",\" in mode:\n        return MultiDecoder(mode)\n\n    if mode == \"gzip\":\n        return GzipDecoder()\n\n    if brotli is not None and mode == \"br\":\n        return BrotliDecoder()\n\n    return DeflateDecoder()\n\n\nclass HTTPResponse(io.IOBase):\n    \"\"\"\n    HTTP Response container.\n\n    Backwards-compatible with :class:`http.client.HTTPResponse` but the response ``body`` is\n    loaded and decoded on-demand when the ``data`` property is accessed.  This\n    class is also compatible with the Python standard library's :mod:`io`\n    module, and can hence be treated as a readable object in the context of that\n    framework.\n\n    Extra parameters for behaviour not present in :class:`http.client.HTTPResponse`:\n\n    :param preload_content:\n        If True, the response's body will be preloaded during construction.\n\n    :param decode_content:\n        If True, will attempt to decode the body based on the\n        'content-encoding' header.\n\n    :param original_response:\n        When this HTTPResponse wrapper is generated from an :class:`http.client.HTTPResponse`\n        object, it's convenient to include the original for debug purposes. It's\n        otherwise unused.\n\n    :param retries:\n        The retries contains the last :class:`~urllib3.util.retry.Retry` that\n        was used during the request.\n\n    :param enforce_content_length:\n        Enforce content length checking. Body returned by server must match\n        value of Content-Length header, if present. Otherwise, raise error.\n    \"\"\"\n\n    CONTENT_DECODERS = [\"gzip\", \"deflate\"]\n    if brotli is not None:\n        CONTENT_DECODERS += [\"br\"]\n    REDIRECT_STATUSES = [301, 302, 303, 307, 308]\n\n    def __init__(\n        self,\n        body=\"\",\n        headers=None,\n        status=0,\n        version=0,\n        reason=None,\n        strict=0,\n        preload_content=True,\n        decode_content=True,\n        original_response=None,\n        pool=None,\n        connection=None,\n        msg=None,\n        retries=None,\n        enforce_content_length=False,\n        request_method=None,\n        request_url=None,\n        auto_close=True,\n    ):\n\n        if isinstance(headers, HTTPHeaderDict):\n            self.headers = headers\n        else:\n            self.headers = HTTPHeaderDict(headers)\n        self.status = status\n        self.version = version\n        self.reason = reason\n        self.strict = strict\n        self.decode_content = decode_content\n        self.retries = retries\n        self.enforce_content_length = enforce_content_length\n        self.auto_close = auto_close\n\n        self._decoder = None\n        self._body = None\n        self._fp = None\n        self._original_response = original_response\n        self._fp_bytes_read = 0\n        self.msg = msg\n        self._request_url = request_url\n\n        if body and isinstance(body, (six.string_types, bytes)):\n            self._body = body\n\n        self._pool = pool\n        self._connection = connection\n\n        if hasattr(body, \"read\"):\n            self._fp = body\n\n        # Are we using the chunked-style of transfer encoding?\n        self.chunked = False\n        self.chunk_left = None\n        tr_enc = self.headers.get(\"transfer-encoding\", \"\").lower()\n        # Don't incur the penalty of creating a list and then discarding it\n        encodings = (enc.strip() for enc in tr_enc.split(\",\"))\n        if \"chunked\" in encodings:\n            self.chunked = True\n\n        # Determine length of response\n        self.length_remaining = self._init_length(request_method)\n\n        # If requested, preload the body.\n        if preload_content and not self._body:\n            self._body = self.read(decode_content=decode_content)\n\n    def get_redirect_location(self):\n        \"\"\"\n        Should we redirect and where to?\n\n        :returns: Truthy redirect location string if we got a redirect status\n            code and valid location. ``None`` if redirect status and no\n            location. ``False`` if not a redirect status code.\n        \"\"\"\n        if self.status in self.REDIRECT_STATUSES:\n            return self.headers.get(\"location\")\n\n        return False\n\n    def release_conn(self):\n        if not self._pool or not self._connection:\n            return\n\n        self._pool._put_conn(self._connection)\n        self._connection = None\n\n    def drain_conn(self):\n        \"\"\"\n        Read and discard any remaining HTTP response data in the response connection.\n\n        Unread data in the HTTPResponse connection blocks the connection from being released back to the pool.\n        \"\"\"\n        try:\n            self.read()\n        except (HTTPError, SocketError, BaseSSLError, HTTPException):\n            pass\n\n    @property\n    def data(self):\n        # For backwards-compat with earlier urllib3 0.4 and earlier.\n        if self._body:\n            return self._body\n\n        if self._fp:\n            return self.read(cache_content=True)\n\n    @property\n    def connection(self):\n        return self._connection\n\n    def isclosed(self):\n        return is_fp_closed(self._fp)\n\n    def tell(self):\n        \"\"\"\n        Obtain the number of bytes pulled over the wire so far. May differ from\n        the amount of content returned by :meth:``urllib3.response.HTTPResponse.read``\n        if bytes are encoded on the wire (e.g, compressed).\n        \"\"\"\n        return self._fp_bytes_read\n\n    def _init_length(self, request_method):\n        \"\"\"\n        Set initial length value for Response content if available.\n        \"\"\"\n        length = self.headers.get(\"content-length\")\n\n        if length is not None:\n            if self.chunked:\n                # This Response will fail with an IncompleteRead if it can't be\n                # received as chunked. This method falls back to attempt reading\n                # the response before raising an exception.\n                log.warning(\n                    \"Received response with both Content-Length and \"\n                    \"Transfer-Encoding set. This is expressly forbidden \"\n                    \"by RFC 7230 sec 3.3.2. Ignoring Content-Length and \"\n                    \"attempting to process response as Transfer-Encoding: \"\n                    \"chunked.\"\n                )\n                return None\n\n            try:\n                # RFC 7230 section 3.3.2 specifies multiple content lengths can\n                # be sent in a single Content-Length header\n                # (e.g. Content-Length: 42, 42). This line ensures the values\n                # are all valid ints and that as long as the `set` length is 1,\n                # all values are the same. Otherwise, the header is invalid.\n                lengths = set([int(val) for val in length.split(\",\")])\n                if len(lengths) > 1:\n                    raise InvalidHeader(\n                        \"Content-Length contained multiple \"\n                        \"unmatching values (%s)\" % length\n                    )\n                length = lengths.pop()\n            except ValueError:\n                length = None\n            else:\n                if length < 0:\n                    length = None\n\n        # Convert status to int for comparison\n        # In some cases, httplib returns a status of \"_UNKNOWN\"\n        try:\n            status = int(self.status)\n        except ValueError:\n            status = 0\n\n        # Check for responses that shouldn't include a body\n        if status in (204, 304) or 100 <= status < 200 or request_method == \"HEAD\":\n            length = 0\n\n        return length\n\n    def _init_decoder(self):\n        \"\"\"\n        Set-up the _decoder attribute if necessary.\n        \"\"\"\n        # Note: content-encoding value should be case-insensitive, per RFC 7230\n        # Section 3.2\n        content_encoding = self.headers.get(\"content-encoding\", \"\").lower()\n        if self._decoder is None:\n            if content_encoding in self.CONTENT_DECODERS:\n                self._decoder = _get_decoder(content_encoding)\n            elif \",\" in content_encoding:\n                encodings = [\n                    e.strip()\n                    for e in content_encoding.split(\",\")\n                    if e.strip() in self.CONTENT_DECODERS\n                ]\n                if len(encodings):\n                    self._decoder = _get_decoder(content_encoding)\n\n    DECODER_ERROR_CLASSES = (IOError, zlib.error)\n    if brotli is not None:\n        DECODER_ERROR_CLASSES += (brotli.error,)\n\n    def _decode(self, data, decode_content, flush_decoder):\n        \"\"\"\n        Decode the data passed in and potentially flush the decoder.\n        \"\"\"\n        if not decode_content:\n            return data\n\n        try:\n            if self._decoder:\n                data = self._decoder.decompress(data)\n        except self.DECODER_ERROR_CLASSES as e:\n            content_encoding = self.headers.get(\"content-encoding\", \"\").lower()\n            raise DecodeError(\n                \"Received response with content-encoding: %s, but \"\n                \"failed to decode it.\" % content_encoding,\n                e,\n            )\n        if flush_decoder:\n            data += self._flush_decoder()\n\n        return data\n\n    def _flush_decoder(self):\n        \"\"\"\n        Flushes the decoder. Should only be called if the decoder is actually\n        being used.\n        \"\"\"\n        if self._decoder:\n            buf = self._decoder.decompress(b\"\")\n            return buf + self._decoder.flush()\n\n        return b\"\"\n\n    @contextmanager\n    def _error_catcher(self):\n        \"\"\"\n        Catch low-level python exceptions, instead re-raising urllib3\n        variants, so that low-level exceptions are not leaked in the\n        high-level api.\n\n        On exit, release the connection back to the pool.\n        \"\"\"\n        clean_exit = False\n\n        try:\n            try:\n                yield\n\n            except SocketTimeout:\n                # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but\n                # there is yet no clean way to get at it from this context.\n                raise ReadTimeoutError(self._pool, None, \"Read timed out.\")\n\n            except BaseSSLError as e:\n                # FIXME: Is there a better way to differentiate between SSLErrors?\n                if \"read operation timed out\" not in str(e):\n                    # SSL errors related to framing/MAC get wrapped and reraised here\n                    raise SSLError(e)\n\n                raise ReadTimeoutError(self._pool, None, \"Read timed out.\")\n\n            except (HTTPException, SocketError) as e:\n                # This includes IncompleteRead.\n                raise ProtocolError(\"Connection broken: %r\" % e, e)\n\n            # If no exception is thrown, we should avoid cleaning up\n            # unnecessarily.\n            clean_exit = True\n        finally:\n            # If we didn't terminate cleanly, we need to throw away our\n            # connection.\n            if not clean_exit:\n                # The response may not be closed but we're not going to use it\n                # anymore so close it now to ensure that the connection is\n                # released back to the pool.\n                if self._original_response:\n                    self._original_response.close()\n\n                # Closing the response may not actually be sufficient to close\n                # everything, so if we have a hold of the connection close that\n                # too.\n                if self._connection:\n                    self._connection.close()\n\n            # If we hold the original response but it's closed now, we should\n            # return the connection back to the pool.\n            if self._original_response and self._original_response.isclosed():\n                self.release_conn()\n\n    def _fp_read(self, amt):\n        \"\"\"\n        Read a response with the thought that reading the number of bytes\n        larger than can fit in a 32-bit int at a time via SSL in some\n        known cases leads to an overflow error that has to be prevented\n        if `amt` or `self.length_remaining` indicate that a problem may\n        happen.\n\n        The known cases:\n          * 3.8 <= CPython < 3.9.7 because of a bug\n            https://github.com/urllib3/urllib3/issues/2513#issuecomment-1152559900.\n          * urllib3 injected with pyOpenSSL-backed SSL-support.\n          * CPython < 3.10 only when `amt` does not fit 32-bit int.\n        \"\"\"\n        assert self._fp\n        c_int_max = 2 ** 31 - 1\n        if (\n            (\n                (amt and amt > c_int_max)\n                or (self.length_remaining and self.length_remaining > c_int_max)\n            )\n            and not util.IS_SECURETRANSPORT\n            and (util.IS_PYOPENSSL or sys.version_info < (3, 10))\n        ):\n            buffer = io.BytesIO()\n            # Besides `max_chunk_amt` being a maximum chunk size, it\n            # affects memory overhead of reading a response by this\n            # method in CPython.\n            # `c_int_max` equal to 2 GiB - 1 byte is the actual maximum\n            # chunk size that does not lead to an overflow error, but\n            # 256 MiB is a compromise.\n            max_chunk_amt = 2 ** 28\n            while amt is None or amt != 0:\n                if amt is not None:\n                    chunk_amt = min(amt, max_chunk_amt)\n                    amt -= chunk_amt\n                else:\n                    chunk_amt = max_chunk_amt\n                data = self._fp.read(chunk_amt)\n                if not data:\n                    break\n                buffer.write(data)\n                del data  # to reduce peak memory usage by `max_chunk_amt`.\n            return buffer.getvalue()\n        else:\n            # StringIO doesn't like amt=None\n            return self._fp.read(amt) if amt is not None else self._fp.read()\n\n    def read(self, amt=None, decode_content=None, cache_content=False):\n        \"\"\"\n        Similar to :meth:`http.client.HTTPResponse.read`, but with two additional\n        parameters: ``decode_content`` and ``cache_content``.\n\n        :param amt:\n            How much of the content to read. If specified, caching is skipped\n            because it doesn't make sense to cache partial content as the full\n            response.\n\n        :param decode_content:\n            If True, will attempt to decode the body based on the\n            'content-encoding' header.\n\n        :param cache_content:\n            If True, will save the returned data such that the same result is\n            returned despite of the state of the underlying file object. This\n            is useful if you want the ``.data`` property to continue working\n            after having ``.read()`` the file object. (Overridden if ``amt`` is\n            set.)\n        \"\"\"\n        self._init_decoder()\n        if decode_content is None:\n            decode_content = self.decode_content\n\n        if self._fp is None:\n            return\n\n        flush_decoder = False\n        fp_closed = getattr(self._fp, \"closed\", False)\n\n        with self._error_catcher():\n            data = self._fp_read(amt) if not fp_closed else b\"\"\n            if amt is None:\n                flush_decoder = True\n            else:\n                cache_content = False\n                if (\n                    amt != 0 and not data\n                ):  # Platform-specific: Buggy versions of Python.\n                    # Close the connection when no data is returned\n                    #\n                    # This is redundant to what httplib/http.client _should_\n                    # already do.  However, versions of python released before\n                    # December 15, 2012 (http://bugs.python.org/issue16298) do\n                    # not properly close the connection in all cases. There is\n                    # no harm in redundantly calling close.\n                    self._fp.close()\n                    flush_decoder = True\n                    if self.enforce_content_length and self.length_remaining not in (\n                        0,\n                        None,\n                    ):\n                        # This is an edge case that httplib failed to cover due\n                        # to concerns of backward compatibility. We're\n                        # addressing it here to make sure IncompleteRead is\n                        # raised during streaming, so all calls with incorrect\n                        # Content-Length are caught.\n                        raise IncompleteRead(self._fp_bytes_read, self.length_remaining)\n\n        if data:\n            self._fp_bytes_read += len(data)\n            if self.length_remaining is not None:\n                self.length_remaining -= len(data)\n\n            data = self._decode(data, decode_content, flush_decoder)\n\n            if cache_content:\n                self._body = data\n\n        return data\n\n    def stream(self, amt=2 ** 16, decode_content=None):\n        \"\"\"\n        A generator wrapper for the read() method. A call will block until\n        ``amt`` bytes have been read from the connection or until the\n        connection is closed.\n\n        :param amt:\n            How much of the content to read. The generator will return up to\n            much data per iteration, but may return less. This is particularly\n            likely when using compressed data. However, the empty string will\n            never be returned.\n\n        :param decode_content:\n            If True, will attempt to decode the body based on the\n            'content-encoding' header.\n        \"\"\"\n        if self.chunked and self.supports_chunked_reads():\n            for line in self.read_chunked(amt, decode_content=decode_content):\n                yield line\n        else:\n            while not is_fp_closed(self._fp):\n                data = self.read(amt=amt, decode_content=decode_content)\n\n                if data:\n                    yield data\n\n    @classmethod\n    def from_httplib(ResponseCls, r, **response_kw):\n        \"\"\"\n        Given an :class:`http.client.HTTPResponse` instance ``r``, return a\n        corresponding :class:`urllib3.response.HTTPResponse` object.\n\n        Remaining parameters are passed to the HTTPResponse constructor, along\n        with ``original_response=r``.\n        \"\"\"\n        headers = r.msg\n\n        if not isinstance(headers, HTTPHeaderDict):\n            if six.PY2:\n                # Python 2.7\n                headers = HTTPHeaderDict.from_httplib(headers)\n            else:\n                headers = HTTPHeaderDict(headers.items())\n\n        # HTTPResponse objects in Python 3 don't have a .strict attribute\n        strict = getattr(r, \"strict\", 0)\n        resp = ResponseCls(\n            body=r,\n            headers=headers,\n            status=r.status,\n            version=r.version,\n            reason=r.reason,\n            strict=strict,\n            original_response=r,\n            **response_kw\n        )\n        return resp\n\n    # Backwards-compatibility methods for http.client.HTTPResponse\n    def getheaders(self):\n        return self.headers\n\n    def getheader(self, name, default=None):\n        return self.headers.get(name, default)\n\n    # Backwards compatibility for http.cookiejar\n    def info(self):\n        return self.headers\n\n    # Overrides from io.IOBase\n    def close(self):\n        if not self.closed:\n            self._fp.close()\n\n        if self._connection:\n            self._connection.close()\n\n        if not self.auto_close:\n            io.IOBase.close(self)\n\n    @property\n    def closed(self):\n        if not self.auto_close:\n            return io.IOBase.closed.__get__(self)\n        elif self._fp is None:\n            return True\n        elif hasattr(self._fp, \"isclosed\"):\n            return self._fp.isclosed()\n        elif hasattr(self._fp, \"closed\"):\n            return self._fp.closed\n        else:\n            return True\n\n    def fileno(self):\n        if self._fp is None:\n            raise IOError(\"HTTPResponse has no file to get a fileno from\")\n        elif hasattr(self._fp, \"fileno\"):\n            return self._fp.fileno()\n        else:\n            raise IOError(\n                \"The file-like object this HTTPResponse is wrapped \"\n                \"around has no file descriptor\"\n            )\n\n    def flush(self):\n        if (\n            self._fp is not None\n            and hasattr(self._fp, \"flush\")\n            and not getattr(self._fp, \"closed\", False)\n        ):\n            return self._fp.flush()\n\n    def readable(self):\n        # This method is required for `io` module compatibility.\n        return True\n\n    def readinto(self, b):\n        # This method is required for `io` module compatibility.\n        temp = self.read(len(b))\n        if len(temp) == 0:\n            return 0\n        else:\n            b[: len(temp)] = temp\n            return len(temp)\n\n    def supports_chunked_reads(self):\n        \"\"\"\n        Checks if the underlying file-like object looks like a\n        :class:`http.client.HTTPResponse` object. We do this by testing for\n        the fp attribute. If it is present we assume it returns raw chunks as\n        processed by read_chunked().\n        \"\"\"\n        return hasattr(self._fp, \"fp\")\n\n    def _update_chunk_length(self):\n        # First, we'll figure out length of a chunk and then\n        # we'll try to read it from socket.\n        if self.chunk_left is not None:\n            return\n        line = self._fp.fp.readline()\n        line = line.split(b\";\", 1)[0]\n        try:\n            self.chunk_left = int(line, 16)\n        except ValueError:\n            # Invalid chunked protocol response, abort.\n            self.close()\n            raise InvalidChunkLength(self, line)\n\n    def _handle_chunk(self, amt):\n        returned_chunk = None\n        if amt is None:\n            chunk = self._fp._safe_read(self.chunk_left)\n            returned_chunk = chunk\n            self._fp._safe_read(2)  # Toss the CRLF at the end of the chunk.\n            self.chunk_left = None\n        elif amt < self.chunk_left:\n            value = self._fp._safe_read(amt)\n            self.chunk_left = self.chunk_left - amt\n            returned_chunk = value\n        elif amt == self.chunk_left:\n            value = self._fp._safe_read(amt)\n            self._fp._safe_read(2)  # Toss the CRLF at the end of the chunk.\n            self.chunk_left = None\n            returned_chunk = value\n        else:  # amt > self.chunk_left\n            returned_chunk = self._fp._safe_read(self.chunk_left)\n            self._fp._safe_read(2)  # Toss the CRLF at the end of the chunk.\n            self.chunk_left = None\n        return returned_chunk\n\n    def read_chunked(self, amt=None, decode_content=None):\n        \"\"\"\n        Similar to :meth:`HTTPResponse.read`, but with an additional\n        parameter: ``decode_content``.\n\n        :param amt:\n            How much of the content to read. If specified, caching is skipped\n            because it doesn't make sense to cache partial content as the full\n            response.\n\n        :param decode_content:\n            If True, will attempt to decode the body based on the\n            'content-encoding' header.\n        \"\"\"\n        self._init_decoder()\n        # FIXME: Rewrite this method and make it a class with a better structured logic.\n        if not self.chunked:\n            raise ResponseNotChunked(\n                \"Response is not chunked. \"\n                \"Header 'transfer-encoding: chunked' is missing.\"\n            )\n        if not self.supports_chunked_reads():\n            raise BodyNotHttplibCompatible(\n                \"Body should be http.client.HTTPResponse like. \"\n                \"It should have have an fp attribute which returns raw chunks.\"\n            )\n\n        with self._error_catcher():\n            # Don't bother reading the body of a HEAD request.\n            if self._original_response and is_response_to_head(self._original_response):\n                self._original_response.close()\n                return\n\n            # If a response is already read and closed\n            # then return immediately.\n            if self._fp.fp is None:\n                return\n\n            while True:\n                self._update_chunk_length()\n                if self.chunk_left == 0:\n                    break\n                chunk = self._handle_chunk(amt)\n                decoded = self._decode(\n                    chunk, decode_content=decode_content, flush_decoder=False\n                )\n                if decoded:\n                    yield decoded\n\n            if decode_content:\n                # On CPython and PyPy, we should never need to flush the\n                # decoder. However, on Jython we *might* need to, so\n                # lets defensively do it anyway.\n                decoded = self._flush_decoder()\n                if decoded:  # Platform-specific: Jython.\n                    yield decoded\n\n            # Chunk content ends with \\r\\n: discard it.\n            while True:\n                line = self._fp.fp.readline()\n                if not line:\n                    # Some sites may not end with '\\r\\n'.\n                    break\n                if line == b\"\\r\\n\":\n                    break\n\n            # We read everything; close the \"file\".\n            if self._original_response:\n                self._original_response.close()\n\n    def geturl(self):\n        \"\"\"\n        Returns the URL that was the source of this response.\n        If the request that generated this response redirected, this method\n        will return the final redirect location.\n        \"\"\"\n        if self.retries is not None and len(self.retries.history):\n            return self.retries.history[-1].redirect_location\n        else:\n            return self._request_url\n\n    def __iter__(self):\n        buffer = []\n        for chunk in self.stream(decode_content=True):\n            if b\"\\n\" in chunk:\n                chunk = chunk.split(b\"\\n\")\n                yield b\"\".join(buffer) + chunk[0] + b\"\\n\"\n                for x in chunk[1:-1]:\n                    yield x + b\"\\n\"\n                if chunk[-1]:\n                    buffer = [chunk[-1]]\n                else:\n                    buffer = []\n            else:\n                buffer.append(chunk)\n        if buffer:\n            yield b\"\".join(buffer)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/util/__init__.py",
    "content": "from __future__ import absolute_import\n\n# For backwards compatibility, provide imports that used to be here.\nfrom .connection import is_connection_dropped\nfrom .request import SKIP_HEADER, SKIPPABLE_HEADERS, make_headers\nfrom .response import is_fp_closed\nfrom .retry import Retry\nfrom .ssl_ import (\n    ALPN_PROTOCOLS,\n    HAS_SNI,\n    IS_PYOPENSSL,\n    IS_SECURETRANSPORT,\n    PROTOCOL_TLS,\n    SSLContext,\n    assert_fingerprint,\n    resolve_cert_reqs,\n    resolve_ssl_version,\n    ssl_wrap_socket,\n)\nfrom .timeout import Timeout, current_time\nfrom .url import Url, get_host, parse_url, split_first\nfrom .wait import wait_for_read, wait_for_write\n\n__all__ = (\n    \"HAS_SNI\",\n    \"IS_PYOPENSSL\",\n    \"IS_SECURETRANSPORT\",\n    \"SSLContext\",\n    \"PROTOCOL_TLS\",\n    \"ALPN_PROTOCOLS\",\n    \"Retry\",\n    \"Timeout\",\n    \"Url\",\n    \"assert_fingerprint\",\n    \"current_time\",\n    \"is_connection_dropped\",\n    \"is_fp_closed\",\n    \"get_host\",\n    \"parse_url\",\n    \"make_headers\",\n    \"resolve_cert_reqs\",\n    \"resolve_ssl_version\",\n    \"split_first\",\n    \"ssl_wrap_socket\",\n    \"wait_for_read\",\n    \"wait_for_write\",\n    \"SKIP_HEADER\",\n    \"SKIPPABLE_HEADERS\",\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/util/connection.py",
    "content": "from __future__ import absolute_import\n\nimport socket\n\nfrom ..contrib import _appengine_environ\nfrom ..exceptions import LocationParseError\nfrom ..packages import six\nfrom .wait import NoWayToWaitForSocketError, wait_for_read\n\n\ndef is_connection_dropped(conn):  # Platform-specific\n    \"\"\"\n    Returns True if the connection is dropped and should be closed.\n\n    :param conn:\n        :class:`http.client.HTTPConnection` object.\n\n    Note: For platforms like AppEngine, this will always return ``False`` to\n    let the platform handle connection recycling transparently for us.\n    \"\"\"\n    sock = getattr(conn, \"sock\", False)\n    if sock is False:  # Platform-specific: AppEngine\n        return False\n    if sock is None:  # Connection already closed (such as by httplib).\n        return True\n    try:\n        # Returns True if readable, which here means it's been dropped\n        return wait_for_read(sock, timeout=0.0)\n    except NoWayToWaitForSocketError:  # Platform-specific: AppEngine\n        return False\n\n\n# This function is copied from socket.py in the Python 2.7 standard\n# library test suite. Added to its signature is only `socket_options`.\n# One additional modification is that we avoid binding to IPv6 servers\n# discovered in DNS if the system doesn't have IPv6 functionality.\ndef create_connection(\n    address,\n    timeout=socket._GLOBAL_DEFAULT_TIMEOUT,\n    source_address=None,\n    socket_options=None,\n):\n    \"\"\"Connect to *address* and return the socket object.\n\n    Convenience function.  Connect to *address* (a 2-tuple ``(host,\n    port)``) and return the socket object.  Passing the optional\n    *timeout* parameter will set the timeout on the socket instance\n    before attempting to connect.  If no *timeout* is supplied, the\n    global default timeout setting returned by :func:`socket.getdefaulttimeout`\n    is used.  If *source_address* is set it must be a tuple of (host, port)\n    for the socket to bind as a source address before making the connection.\n    An host of '' or port 0 tells the OS to use the default.\n    \"\"\"\n\n    host, port = address\n    if host.startswith(\"[\"):\n        host = host.strip(\"[]\")\n    err = None\n\n    # Using the value from allowed_gai_family() in the context of getaddrinfo lets\n    # us select whether to work with IPv4 DNS records, IPv6 records, or both.\n    # The original create_connection function always returns all records.\n    family = allowed_gai_family()\n\n    try:\n        host.encode(\"idna\")\n    except UnicodeError:\n        return six.raise_from(\n            LocationParseError(u\"'%s', label empty or too long\" % host), None\n        )\n\n    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):\n        af, socktype, proto, canonname, sa = res\n        sock = None\n        try:\n            sock = socket.socket(af, socktype, proto)\n\n            # If provided, set socket level options before connecting.\n            _set_socket_options(sock, socket_options)\n\n            if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:\n                sock.settimeout(timeout)\n            if source_address:\n                sock.bind(source_address)\n            sock.connect(sa)\n            return sock\n\n        except socket.error as e:\n            err = e\n            if sock is not None:\n                sock.close()\n                sock = None\n\n    if err is not None:\n        raise err\n\n    raise socket.error(\"getaddrinfo returns an empty list\")\n\n\ndef _set_socket_options(sock, options):\n    if options is None:\n        return\n\n    for opt in options:\n        sock.setsockopt(*opt)\n\n\ndef allowed_gai_family():\n    \"\"\"This function is designed to work in the context of\n    getaddrinfo, where family=socket.AF_UNSPEC is the default and\n    will perform a DNS search for both IPv6 and IPv4 records.\"\"\"\n\n    family = socket.AF_INET\n    if HAS_IPV6:\n        family = socket.AF_UNSPEC\n    return family\n\n\ndef _has_ipv6(host):\n    \"\"\"Returns True if the system can bind an IPv6 address.\"\"\"\n    sock = None\n    has_ipv6 = False\n\n    # App Engine doesn't support IPV6 sockets and actually has a quota on the\n    # number of sockets that can be used, so just early out here instead of\n    # creating a socket needlessly.\n    # See https://github.com/urllib3/urllib3/issues/1446\n    if _appengine_environ.is_appengine_sandbox():\n        return False\n\n    if socket.has_ipv6:\n        # has_ipv6 returns true if cPython was compiled with IPv6 support.\n        # It does not tell us if the system has IPv6 support enabled. To\n        # determine that we must bind to an IPv6 address.\n        # https://github.com/urllib3/urllib3/pull/611\n        # https://bugs.python.org/issue658327\n        try:\n            sock = socket.socket(socket.AF_INET6)\n            sock.bind((host, 0))\n            has_ipv6 = True\n        except Exception:\n            pass\n\n    if sock:\n        sock.close()\n    return has_ipv6\n\n\nHAS_IPV6 = _has_ipv6(\"::1\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/util/proxy.py",
    "content": "from .ssl_ import create_urllib3_context, resolve_cert_reqs, resolve_ssl_version\n\n\ndef connection_requires_http_tunnel(\n    proxy_url=None, proxy_config=None, destination_scheme=None\n):\n    \"\"\"\n    Returns True if the connection requires an HTTP CONNECT through the proxy.\n\n    :param URL proxy_url:\n        URL of the proxy.\n    :param ProxyConfig proxy_config:\n        Proxy configuration from poolmanager.py\n    :param str destination_scheme:\n        The scheme of the destination. (i.e https, http, etc)\n    \"\"\"\n    # If we're not using a proxy, no way to use a tunnel.\n    if proxy_url is None:\n        return False\n\n    # HTTP destinations never require tunneling, we always forward.\n    if destination_scheme == \"http\":\n        return False\n\n    # Support for forwarding with HTTPS proxies and HTTPS destinations.\n    if (\n        proxy_url.scheme == \"https\"\n        and proxy_config\n        and proxy_config.use_forwarding_for_https\n    ):\n        return False\n\n    # Otherwise always use a tunnel.\n    return True\n\n\ndef create_proxy_ssl_context(\n    ssl_version, cert_reqs, ca_certs=None, ca_cert_dir=None, ca_cert_data=None\n):\n    \"\"\"\n    Generates a default proxy ssl context if one hasn't been provided by the\n    user.\n    \"\"\"\n    ssl_context = create_urllib3_context(\n        ssl_version=resolve_ssl_version(ssl_version),\n        cert_reqs=resolve_cert_reqs(cert_reqs),\n    )\n\n    if (\n        not ca_certs\n        and not ca_cert_dir\n        and not ca_cert_data\n        and hasattr(ssl_context, \"load_default_certs\")\n    ):\n        ssl_context.load_default_certs()\n\n    return ssl_context\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/util/queue.py",
    "content": "import collections\n\nfrom ..packages import six\nfrom ..packages.six.moves import queue\n\nif six.PY2:\n    # Queue is imported for side effects on MS Windows. See issue #229.\n    import Queue as _unused_module_Queue  # noqa: F401\n\n\nclass LifoQueue(queue.Queue):\n    def _init(self, _):\n        self.queue = collections.deque()\n\n    def _qsize(self, len=len):\n        return len(self.queue)\n\n    def _put(self, item):\n        self.queue.append(item)\n\n    def _get(self):\n        return self.queue.pop()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/util/request.py",
    "content": "from __future__ import absolute_import\n\nfrom base64 import b64encode\n\nfrom ..exceptions import UnrewindableBodyError\nfrom ..packages.six import b, integer_types\n\n# Pass as a value within ``headers`` to skip\n# emitting some HTTP headers that are added automatically.\n# The only headers that are supported are ``Accept-Encoding``,\n# ``Host``, and ``User-Agent``.\nSKIP_HEADER = \"@@@SKIP_HEADER@@@\"\nSKIPPABLE_HEADERS = frozenset([\"accept-encoding\", \"host\", \"user-agent\"])\n\nACCEPT_ENCODING = \"gzip,deflate\"\n\n_FAILEDTELL = object()\n\n\ndef make_headers(\n    keep_alive=None,\n    accept_encoding=None,\n    user_agent=None,\n    basic_auth=None,\n    proxy_basic_auth=None,\n    disable_cache=None,\n):\n    \"\"\"\n    Shortcuts for generating request headers.\n\n    :param keep_alive:\n        If ``True``, adds 'connection: keep-alive' header.\n\n    :param accept_encoding:\n        Can be a boolean, list, or string.\n        ``True`` translates to 'gzip,deflate'.\n        List will get joined by comma.\n        String will be used as provided.\n\n    :param user_agent:\n        String representing the user-agent you want, such as\n        \"python-urllib3/0.6\"\n\n    :param basic_auth:\n        Colon-separated username:password string for 'authorization: basic ...'\n        auth header.\n\n    :param proxy_basic_auth:\n        Colon-separated username:password string for 'proxy-authorization: basic ...'\n        auth header.\n\n    :param disable_cache:\n        If ``True``, adds 'cache-control: no-cache' header.\n\n    Example::\n\n        >>> make_headers(keep_alive=True, user_agent=\"Batman/1.0\")\n        {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}\n        >>> make_headers(accept_encoding=True)\n        {'accept-encoding': 'gzip,deflate'}\n    \"\"\"\n    headers = {}\n    if accept_encoding:\n        if isinstance(accept_encoding, str):\n            pass\n        elif isinstance(accept_encoding, list):\n            accept_encoding = \",\".join(accept_encoding)\n        else:\n            accept_encoding = ACCEPT_ENCODING\n        headers[\"accept-encoding\"] = accept_encoding\n\n    if user_agent:\n        headers[\"user-agent\"] = user_agent\n\n    if keep_alive:\n        headers[\"connection\"] = \"keep-alive\"\n\n    if basic_auth:\n        headers[\"authorization\"] = \"Basic \" + b64encode(b(basic_auth)).decode(\"utf-8\")\n\n    if proxy_basic_auth:\n        headers[\"proxy-authorization\"] = \"Basic \" + b64encode(\n            b(proxy_basic_auth)\n        ).decode(\"utf-8\")\n\n    if disable_cache:\n        headers[\"cache-control\"] = \"no-cache\"\n\n    return headers\n\n\ndef set_file_position(body, pos):\n    \"\"\"\n    If a position is provided, move file to that point.\n    Otherwise, we'll attempt to record a position for future use.\n    \"\"\"\n    if pos is not None:\n        rewind_body(body, pos)\n    elif getattr(body, \"tell\", None) is not None:\n        try:\n            pos = body.tell()\n        except (IOError, OSError):\n            # This differentiates from None, allowing us to catch\n            # a failed `tell()` later when trying to rewind the body.\n            pos = _FAILEDTELL\n\n    return pos\n\n\ndef rewind_body(body, body_pos):\n    \"\"\"\n    Attempt to rewind body to a certain position.\n    Primarily used for request redirects and retries.\n\n    :param body:\n        File-like object that supports seek.\n\n    :param int pos:\n        Position to seek to in file.\n    \"\"\"\n    body_seek = getattr(body, \"seek\", None)\n    if body_seek is not None and isinstance(body_pos, integer_types):\n        try:\n            body_seek(body_pos)\n        except (IOError, OSError):\n            raise UnrewindableBodyError(\n                \"An error occurred when rewinding request body for redirect/retry.\"\n            )\n    elif body_pos is _FAILEDTELL:\n        raise UnrewindableBodyError(\n            \"Unable to record file position for rewinding \"\n            \"request body during a redirect/retry.\"\n        )\n    else:\n        raise ValueError(\n            \"body_pos must be of type integer, instead it was %s.\" % type(body_pos)\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/util/response.py",
    "content": "from __future__ import absolute_import\n\nfrom email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect\n\nfrom ..exceptions import HeaderParsingError\nfrom ..packages.six.moves import http_client as httplib\n\n\ndef is_fp_closed(obj):\n    \"\"\"\n    Checks whether a given file-like object is closed.\n\n    :param obj:\n        The file-like object to check.\n    \"\"\"\n\n    try:\n        # Check `isclosed()` first, in case Python3 doesn't set `closed`.\n        # GH Issue #928\n        return obj.isclosed()\n    except AttributeError:\n        pass\n\n    try:\n        # Check via the official file-like-object way.\n        return obj.closed\n    except AttributeError:\n        pass\n\n    try:\n        # Check if the object is a container for another file-like object that\n        # gets released on exhaustion (e.g. HTTPResponse).\n        return obj.fp is None\n    except AttributeError:\n        pass\n\n    raise ValueError(\"Unable to determine whether fp is closed.\")\n\n\ndef assert_header_parsing(headers):\n    \"\"\"\n    Asserts whether all headers have been successfully parsed.\n    Extracts encountered errors from the result of parsing headers.\n\n    Only works on Python 3.\n\n    :param http.client.HTTPMessage headers: Headers to verify.\n\n    :raises urllib3.exceptions.HeaderParsingError:\n        If parsing errors are found.\n    \"\"\"\n\n    # This will fail silently if we pass in the wrong kind of parameter.\n    # To make debugging easier add an explicit check.\n    if not isinstance(headers, httplib.HTTPMessage):\n        raise TypeError(\"expected httplib.Message, got {0}.\".format(type(headers)))\n\n    defects = getattr(headers, \"defects\", None)\n    get_payload = getattr(headers, \"get_payload\", None)\n\n    unparsed_data = None\n    if get_payload:\n        # get_payload is actually email.message.Message.get_payload;\n        # we're only interested in the result if it's not a multipart message\n        if not headers.is_multipart():\n            payload = get_payload()\n\n            if isinstance(payload, (bytes, str)):\n                unparsed_data = payload\n    if defects:\n        # httplib is assuming a response body is available\n        # when parsing headers even when httplib only sends\n        # header data to parse_headers() This results in\n        # defects on multipart responses in particular.\n        # See: https://github.com/urllib3/urllib3/issues/800\n\n        # So we ignore the following defects:\n        # - StartBoundaryNotFoundDefect:\n        #     The claimed start boundary was never found.\n        # - MultipartInvariantViolationDefect:\n        #     A message claimed to be a multipart but no subparts were found.\n        defects = [\n            defect\n            for defect in defects\n            if not isinstance(\n                defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect)\n            )\n        ]\n\n    if defects or unparsed_data:\n        raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)\n\n\ndef is_response_to_head(response):\n    \"\"\"\n    Checks whether the request of a response has been a HEAD-request.\n    Handles the quirks of AppEngine.\n\n    :param http.client.HTTPResponse response:\n        Response to check if the originating request\n        used 'HEAD' as a method.\n    \"\"\"\n    # FIXME: Can we do this somehow without accessing private httplib _method?\n    method = response._method\n    if isinstance(method, int):  # Platform-specific: Appengine\n        return method == 3\n    return method.upper() == \"HEAD\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/util/retry.py",
    "content": "from __future__ import absolute_import\n\nimport email\nimport logging\nimport re\nimport time\nimport warnings\nfrom collections import namedtuple\nfrom itertools import takewhile\n\nfrom ..exceptions import (\n    ConnectTimeoutError,\n    InvalidHeader,\n    MaxRetryError,\n    ProtocolError,\n    ProxyError,\n    ReadTimeoutError,\n    ResponseError,\n)\nfrom ..packages import six\n\nlog = logging.getLogger(__name__)\n\n\n# Data structure for representing the metadata of requests that result in a retry.\nRequestHistory = namedtuple(\n    \"RequestHistory\", [\"method\", \"url\", \"error\", \"status\", \"redirect_location\"]\n)\n\n\n# TODO: In v2 we can remove this sentinel and metaclass with deprecated options.\n_Default = object()\n\n\nclass _RetryMeta(type):\n    @property\n    def DEFAULT_METHOD_WHITELIST(cls):\n        warnings.warn(\n            \"Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and \"\n            \"will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead\",\n            DeprecationWarning,\n        )\n        return cls.DEFAULT_ALLOWED_METHODS\n\n    @DEFAULT_METHOD_WHITELIST.setter\n    def DEFAULT_METHOD_WHITELIST(cls, value):\n        warnings.warn(\n            \"Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and \"\n            \"will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead\",\n            DeprecationWarning,\n        )\n        cls.DEFAULT_ALLOWED_METHODS = value\n\n    @property\n    def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls):\n        warnings.warn(\n            \"Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and \"\n            \"will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead\",\n            DeprecationWarning,\n        )\n        return cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT\n\n    @DEFAULT_REDIRECT_HEADERS_BLACKLIST.setter\n    def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls, value):\n        warnings.warn(\n            \"Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and \"\n            \"will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead\",\n            DeprecationWarning,\n        )\n        cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT = value\n\n    @property\n    def BACKOFF_MAX(cls):\n        warnings.warn(\n            \"Using 'Retry.BACKOFF_MAX' is deprecated and \"\n            \"will be removed in v2.0. Use 'Retry.DEFAULT_BACKOFF_MAX' instead\",\n            DeprecationWarning,\n        )\n        return cls.DEFAULT_BACKOFF_MAX\n\n    @BACKOFF_MAX.setter\n    def BACKOFF_MAX(cls, value):\n        warnings.warn(\n            \"Using 'Retry.BACKOFF_MAX' is deprecated and \"\n            \"will be removed in v2.0. Use 'Retry.DEFAULT_BACKOFF_MAX' instead\",\n            DeprecationWarning,\n        )\n        cls.DEFAULT_BACKOFF_MAX = value\n\n\n@six.add_metaclass(_RetryMeta)\nclass Retry(object):\n    \"\"\"Retry configuration.\n\n    Each retry attempt will create a new Retry object with updated values, so\n    they can be safely reused.\n\n    Retries can be defined as a default for a pool::\n\n        retries = Retry(connect=5, read=2, redirect=5)\n        http = PoolManager(retries=retries)\n        response = http.request('GET', 'http://example.com/')\n\n    Or per-request (which overrides the default for the pool)::\n\n        response = http.request('GET', 'http://example.com/', retries=Retry(10))\n\n    Retries can be disabled by passing ``False``::\n\n        response = http.request('GET', 'http://example.com/', retries=False)\n\n    Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless\n    retries are disabled, in which case the causing exception will be raised.\n\n    :param int total:\n        Total number of retries to allow. Takes precedence over other counts.\n\n        Set to ``None`` to remove this constraint and fall back on other\n        counts.\n\n        Set to ``0`` to fail on the first retry.\n\n        Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n    :param int connect:\n        How many connection-related errors to retry on.\n\n        These are errors raised before the request is sent to the remote server,\n        which we assume has not triggered the server to process the request.\n\n        Set to ``0`` to fail on the first retry of this type.\n\n    :param int read:\n        How many times to retry on read errors.\n\n        These errors are raised after the request was sent to the server, so the\n        request may have side-effects.\n\n        Set to ``0`` to fail on the first retry of this type.\n\n    :param int redirect:\n        How many redirects to perform. Limit this to avoid infinite redirect\n        loops.\n\n        A redirect is a HTTP response with a status code 301, 302, 303, 307 or\n        308.\n\n        Set to ``0`` to fail on the first retry of this type.\n\n        Set to ``False`` to disable and imply ``raise_on_redirect=False``.\n\n    :param int status:\n        How many times to retry on bad status codes.\n\n        These are retries made on responses, where status code matches\n        ``status_forcelist``.\n\n        Set to ``0`` to fail on the first retry of this type.\n\n    :param int other:\n        How many times to retry on other errors.\n\n        Other errors are errors that are not connect, read, redirect or status errors.\n        These errors might be raised after the request was sent to the server, so the\n        request might have side-effects.\n\n        Set to ``0`` to fail on the first retry of this type.\n\n        If ``total`` is not set, it's a good idea to set this to 0 to account\n        for unexpected edge cases and avoid infinite retry loops.\n\n    :param iterable allowed_methods:\n        Set of uppercased HTTP method verbs that we should retry on.\n\n        By default, we only retry on methods which are considered to be\n        idempotent (multiple requests with the same parameters end with the\n        same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`.\n\n        Set to a ``False`` value to retry on any verb.\n\n        .. warning::\n\n            Previously this parameter was named ``method_whitelist``, that\n            usage is deprecated in v1.26.0 and will be removed in v2.0.\n\n    :param iterable status_forcelist:\n        A set of integer HTTP status codes that we should force a retry on.\n        A retry is initiated if the request method is in ``allowed_methods``\n        and the response status code is in ``status_forcelist``.\n\n        By default, this is disabled with ``None``.\n\n    :param float backoff_factor:\n        A backoff factor to apply between attempts after the second try\n        (most errors are resolved immediately by a second try without a\n        delay). urllib3 will sleep for::\n\n            {backoff factor} * (2 ** ({number of total retries} - 1))\n\n        seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep\n        for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer\n        than :attr:`Retry.DEFAULT_BACKOFF_MAX`.\n\n        By default, backoff is disabled (set to 0).\n\n    :param bool raise_on_redirect: Whether, if the number of redirects is\n        exhausted, to raise a MaxRetryError, or to return a response with a\n        response code in the 3xx range.\n\n    :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:\n        whether we should raise an exception, or return a response,\n        if status falls in ``status_forcelist`` range and retries have\n        been exhausted.\n\n    :param tuple history: The history of the request encountered during\n        each call to :meth:`~Retry.increment`. The list is in the order\n        the requests occurred. Each list item is of class :class:`RequestHistory`.\n\n    :param bool respect_retry_after_header:\n        Whether to respect Retry-After header on status codes defined as\n        :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.\n\n    :param iterable remove_headers_on_redirect:\n        Sequence of headers to remove from the request when a response\n        indicating a redirect is returned before firing off the redirected\n        request.\n    \"\"\"\n\n    #: Default methods to be used for ``allowed_methods``\n    DEFAULT_ALLOWED_METHODS = frozenset(\n        [\"HEAD\", \"GET\", \"PUT\", \"DELETE\", \"OPTIONS\", \"TRACE\"]\n    )\n\n    #: Default status codes to be used for ``status_forcelist``\n    RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])\n\n    #: Default headers to be used for ``remove_headers_on_redirect``\n    DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset([\"Authorization\"])\n\n    #: Maximum backoff time.\n    DEFAULT_BACKOFF_MAX = 120\n\n    def __init__(\n        self,\n        total=10,\n        connect=None,\n        read=None,\n        redirect=None,\n        status=None,\n        other=None,\n        allowed_methods=_Default,\n        status_forcelist=None,\n        backoff_factor=0,\n        raise_on_redirect=True,\n        raise_on_status=True,\n        history=None,\n        respect_retry_after_header=True,\n        remove_headers_on_redirect=_Default,\n        # TODO: Deprecated, remove in v2.0\n        method_whitelist=_Default,\n    ):\n\n        if method_whitelist is not _Default:\n            if allowed_methods is not _Default:\n                raise ValueError(\n                    \"Using both 'allowed_methods' and \"\n                    \"'method_whitelist' together is not allowed. \"\n                    \"Instead only use 'allowed_methods'\"\n                )\n            warnings.warn(\n                \"Using 'method_whitelist' with Retry is deprecated and \"\n                \"will be removed in v2.0. Use 'allowed_methods' instead\",\n                DeprecationWarning,\n                stacklevel=2,\n            )\n            allowed_methods = method_whitelist\n        if allowed_methods is _Default:\n            allowed_methods = self.DEFAULT_ALLOWED_METHODS\n        if remove_headers_on_redirect is _Default:\n            remove_headers_on_redirect = self.DEFAULT_REMOVE_HEADERS_ON_REDIRECT\n\n        self.total = total\n        self.connect = connect\n        self.read = read\n        self.status = status\n        self.other = other\n\n        if redirect is False or total is False:\n            redirect = 0\n            raise_on_redirect = False\n\n        self.redirect = redirect\n        self.status_forcelist = status_forcelist or set()\n        self.allowed_methods = allowed_methods\n        self.backoff_factor = backoff_factor\n        self.raise_on_redirect = raise_on_redirect\n        self.raise_on_status = raise_on_status\n        self.history = history or tuple()\n        self.respect_retry_after_header = respect_retry_after_header\n        self.remove_headers_on_redirect = frozenset(\n            [h.lower() for h in remove_headers_on_redirect]\n        )\n\n    def new(self, **kw):\n        params = dict(\n            total=self.total,\n            connect=self.connect,\n            read=self.read,\n            redirect=self.redirect,\n            status=self.status,\n            other=self.other,\n            status_forcelist=self.status_forcelist,\n            backoff_factor=self.backoff_factor,\n            raise_on_redirect=self.raise_on_redirect,\n            raise_on_status=self.raise_on_status,\n            history=self.history,\n            remove_headers_on_redirect=self.remove_headers_on_redirect,\n            respect_retry_after_header=self.respect_retry_after_header,\n        )\n\n        # TODO: If already given in **kw we use what's given to us\n        # If not given we need to figure out what to pass. We decide\n        # based on whether our class has the 'method_whitelist' property\n        # and if so we pass the deprecated 'method_whitelist' otherwise\n        # we use 'allowed_methods'. Remove in v2.0\n        if \"method_whitelist\" not in kw and \"allowed_methods\" not in kw:\n            if \"method_whitelist\" in self.__dict__:\n                warnings.warn(\n                    \"Using 'method_whitelist' with Retry is deprecated and \"\n                    \"will be removed in v2.0. Use 'allowed_methods' instead\",\n                    DeprecationWarning,\n                )\n                params[\"method_whitelist\"] = self.allowed_methods\n            else:\n                params[\"allowed_methods\"] = self.allowed_methods\n\n        params.update(kw)\n        return type(self)(**params)\n\n    @classmethod\n    def from_int(cls, retries, redirect=True, default=None):\n        \"\"\"Backwards-compatibility for the old retries format.\"\"\"\n        if retries is None:\n            retries = default if default is not None else cls.DEFAULT\n\n        if isinstance(retries, Retry):\n            return retries\n\n        redirect = bool(redirect) and None\n        new_retries = cls(retries, redirect=redirect)\n        log.debug(\"Converted retries value: %r -> %r\", retries, new_retries)\n        return new_retries\n\n    def get_backoff_time(self):\n        \"\"\"Formula for computing the current backoff\n\n        :rtype: float\n        \"\"\"\n        # We want to consider only the last consecutive errors sequence (Ignore redirects).\n        consecutive_errors_len = len(\n            list(\n                takewhile(lambda x: x.redirect_location is None, reversed(self.history))\n            )\n        )\n        if consecutive_errors_len <= 1:\n            return 0\n\n        backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))\n        return min(self.DEFAULT_BACKOFF_MAX, backoff_value)\n\n    def parse_retry_after(self, retry_after):\n        # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4\n        if re.match(r\"^\\s*[0-9]+\\s*$\", retry_after):\n            seconds = int(retry_after)\n        else:\n            retry_date_tuple = email.utils.parsedate_tz(retry_after)\n            if retry_date_tuple is None:\n                raise InvalidHeader(\"Invalid Retry-After header: %s\" % retry_after)\n            if retry_date_tuple[9] is None:  # Python 2\n                # Assume UTC if no timezone was specified\n                # On Python2.7, parsedate_tz returns None for a timezone offset\n                # instead of 0 if no timezone is given, where mktime_tz treats\n                # a None timezone offset as local time.\n                retry_date_tuple = retry_date_tuple[:9] + (0,) + retry_date_tuple[10:]\n\n            retry_date = email.utils.mktime_tz(retry_date_tuple)\n            seconds = retry_date - time.time()\n\n        if seconds < 0:\n            seconds = 0\n\n        return seconds\n\n    def get_retry_after(self, response):\n        \"\"\"Get the value of Retry-After in seconds.\"\"\"\n\n        retry_after = response.getheader(\"Retry-After\")\n\n        if retry_after is None:\n            return None\n\n        return self.parse_retry_after(retry_after)\n\n    def sleep_for_retry(self, response=None):\n        retry_after = self.get_retry_after(response)\n        if retry_after:\n            time.sleep(retry_after)\n            return True\n\n        return False\n\n    def _sleep_backoff(self):\n        backoff = self.get_backoff_time()\n        if backoff <= 0:\n            return\n        time.sleep(backoff)\n\n    def sleep(self, response=None):\n        \"\"\"Sleep between retry attempts.\n\n        This method will respect a server's ``Retry-After`` response header\n        and sleep the duration of the time requested. If that is not present, it\n        will use an exponential backoff. By default, the backoff factor is 0 and\n        this method will return immediately.\n        \"\"\"\n\n        if self.respect_retry_after_header and response:\n            slept = self.sleep_for_retry(response)\n            if slept:\n                return\n\n        self._sleep_backoff()\n\n    def _is_connection_error(self, err):\n        \"\"\"Errors when we're fairly sure that the server did not receive the\n        request, so it should be safe to retry.\n        \"\"\"\n        if isinstance(err, ProxyError):\n            err = err.original_error\n        return isinstance(err, ConnectTimeoutError)\n\n    def _is_read_error(self, err):\n        \"\"\"Errors that occur after the request has been started, so we should\n        assume that the server began processing it.\n        \"\"\"\n        return isinstance(err, (ReadTimeoutError, ProtocolError))\n\n    def _is_method_retryable(self, method):\n        \"\"\"Checks if a given HTTP method should be retried upon, depending if\n        it is included in the allowed_methods\n        \"\"\"\n        # TODO: For now favor if the Retry implementation sets its own method_whitelist\n        # property outside of our constructor to avoid breaking custom implementations.\n        if \"method_whitelist\" in self.__dict__:\n            warnings.warn(\n                \"Using 'method_whitelist' with Retry is deprecated and \"\n                \"will be removed in v2.0. Use 'allowed_methods' instead\",\n                DeprecationWarning,\n            )\n            allowed_methods = self.method_whitelist\n        else:\n            allowed_methods = self.allowed_methods\n\n        if allowed_methods and method.upper() not in allowed_methods:\n            return False\n        return True\n\n    def is_retry(self, method, status_code, has_retry_after=False):\n        \"\"\"Is this method/status code retryable? (Based on allowlists and control\n        variables such as the number of total retries to allow, whether to\n        respect the Retry-After header, whether this header is present, and\n        whether the returned status code is on the list of status codes to\n        be retried upon on the presence of the aforementioned header)\n        \"\"\"\n        if not self._is_method_retryable(method):\n            return False\n\n        if self.status_forcelist and status_code in self.status_forcelist:\n            return True\n\n        return (\n            self.total\n            and self.respect_retry_after_header\n            and has_retry_after\n            and (status_code in self.RETRY_AFTER_STATUS_CODES)\n        )\n\n    def is_exhausted(self):\n        \"\"\"Are we out of retries?\"\"\"\n        retry_counts = (\n            self.total,\n            self.connect,\n            self.read,\n            self.redirect,\n            self.status,\n            self.other,\n        )\n        retry_counts = list(filter(None, retry_counts))\n        if not retry_counts:\n            return False\n\n        return min(retry_counts) < 0\n\n    def increment(\n        self,\n        method=None,\n        url=None,\n        response=None,\n        error=None,\n        _pool=None,\n        _stacktrace=None,\n    ):\n        \"\"\"Return a new Retry object with incremented retry counters.\n\n        :param response: A response object, or None, if the server did not\n            return a response.\n        :type response: :class:`~urllib3.response.HTTPResponse`\n        :param Exception error: An error encountered during the request, or\n            None if the response was received successfully.\n\n        :return: A new ``Retry`` object.\n        \"\"\"\n        if self.total is False and error:\n            # Disabled, indicate to re-raise the error.\n            raise six.reraise(type(error), error, _stacktrace)\n\n        total = self.total\n        if total is not None:\n            total -= 1\n\n        connect = self.connect\n        read = self.read\n        redirect = self.redirect\n        status_count = self.status\n        other = self.other\n        cause = \"unknown\"\n        status = None\n        redirect_location = None\n\n        if error and self._is_connection_error(error):\n            # Connect retry?\n            if connect is False:\n                raise six.reraise(type(error), error, _stacktrace)\n            elif connect is not None:\n                connect -= 1\n\n        elif error and self._is_read_error(error):\n            # Read retry?\n            if read is False or not self._is_method_retryable(method):\n                raise six.reraise(type(error), error, _stacktrace)\n            elif read is not None:\n                read -= 1\n\n        elif error:\n            # Other retry?\n            if other is not None:\n                other -= 1\n\n        elif response and response.get_redirect_location():\n            # Redirect retry?\n            if redirect is not None:\n                redirect -= 1\n            cause = \"too many redirects\"\n            redirect_location = response.get_redirect_location()\n            status = response.status\n\n        else:\n            # Incrementing because of a server error like a 500 in\n            # status_forcelist and the given method is in the allowed_methods\n            cause = ResponseError.GENERIC_ERROR\n            if response and response.status:\n                if status_count is not None:\n                    status_count -= 1\n                cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status)\n                status = response.status\n\n        history = self.history + (\n            RequestHistory(method, url, error, status, redirect_location),\n        )\n\n        new_retry = self.new(\n            total=total,\n            connect=connect,\n            read=read,\n            redirect=redirect,\n            status=status_count,\n            other=other,\n            history=history,\n        )\n\n        if new_retry.is_exhausted():\n            raise MaxRetryError(_pool, url, error or ResponseError(cause))\n\n        log.debug(\"Incremented Retry for (url='%s'): %r\", url, new_retry)\n\n        return new_retry\n\n    def __repr__(self):\n        return (\n            \"{cls.__name__}(total={self.total}, connect={self.connect}, \"\n            \"read={self.read}, redirect={self.redirect}, status={self.status})\"\n        ).format(cls=type(self), self=self)\n\n    def __getattr__(self, item):\n        if item == \"method_whitelist\":\n            # TODO: Remove this deprecated alias in v2.0\n            warnings.warn(\n                \"Using 'method_whitelist' with Retry is deprecated and \"\n                \"will be removed in v2.0. Use 'allowed_methods' instead\",\n                DeprecationWarning,\n            )\n            return self.allowed_methods\n        try:\n            return getattr(super(Retry, self), item)\n        except AttributeError:\n            return getattr(Retry, item)\n\n\n# For backwards compatibility (equivalent to pre-v1.9):\nRetry.DEFAULT = Retry(3)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/util/ssl_.py",
    "content": "from __future__ import absolute_import\n\nimport hmac\nimport os\nimport sys\nimport warnings\nfrom binascii import hexlify, unhexlify\nfrom hashlib import md5, sha1, sha256\n\nfrom ..exceptions import (\n    InsecurePlatformWarning,\n    ProxySchemeUnsupported,\n    SNIMissingWarning,\n    SSLError,\n)\nfrom ..packages import six\nfrom .url import BRACELESS_IPV6_ADDRZ_RE, IPV4_RE\n\nSSLContext = None\nSSLTransport = None\nHAS_SNI = False\nIS_PYOPENSSL = False\nIS_SECURETRANSPORT = False\nALPN_PROTOCOLS = [\"http/1.1\"]\n\n# Maps the length of a digest to a possible hash function producing this digest\nHASHFUNC_MAP = {32: md5, 40: sha1, 64: sha256}\n\n\ndef _const_compare_digest_backport(a, b):\n    \"\"\"\n    Compare two digests of equal length in constant time.\n\n    The digests must be of type str/bytes.\n    Returns True if the digests match, and False otherwise.\n    \"\"\"\n    result = abs(len(a) - len(b))\n    for left, right in zip(bytearray(a), bytearray(b)):\n        result |= left ^ right\n    return result == 0\n\n\n_const_compare_digest = getattr(hmac, \"compare_digest\", _const_compare_digest_backport)\n\ntry:  # Test for SSL features\n    import ssl\n    from ssl import CERT_REQUIRED, wrap_socket\nexcept ImportError:\n    pass\n\ntry:\n    from ssl import HAS_SNI  # Has SNI?\nexcept ImportError:\n    pass\n\ntry:\n    from .ssltransport import SSLTransport\nexcept ImportError:\n    pass\n\n\ntry:  # Platform-specific: Python 3.6\n    from ssl import PROTOCOL_TLS\n\n    PROTOCOL_SSLv23 = PROTOCOL_TLS\nexcept ImportError:\n    try:\n        from ssl import PROTOCOL_SSLv23 as PROTOCOL_TLS\n\n        PROTOCOL_SSLv23 = PROTOCOL_TLS\n    except ImportError:\n        PROTOCOL_SSLv23 = PROTOCOL_TLS = 2\n\ntry:\n    from ssl import PROTOCOL_TLS_CLIENT\nexcept ImportError:\n    PROTOCOL_TLS_CLIENT = PROTOCOL_TLS\n\n\ntry:\n    from ssl import OP_NO_COMPRESSION, OP_NO_SSLv2, OP_NO_SSLv3\nexcept ImportError:\n    OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000\n    OP_NO_COMPRESSION = 0x20000\n\n\ntry:  # OP_NO_TICKET was added in Python 3.6\n    from ssl import OP_NO_TICKET\nexcept ImportError:\n    OP_NO_TICKET = 0x4000\n\n\n# A secure default.\n# Sources for more information on TLS ciphers:\n#\n# - https://wiki.mozilla.org/Security/Server_Side_TLS\n# - https://www.ssllabs.com/projects/best-practices/index.html\n# - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/\n#\n# The general intent is:\n# - prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),\n# - prefer ECDHE over DHE for better performance,\n# - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and\n#   security,\n# - prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common,\n# - disable NULL authentication, MD5 MACs, DSS, and other\n#   insecure ciphers for security reasons.\n# - NOTE: TLS 1.3 cipher suites are managed through a different interface\n#   not exposed by CPython (yet!) and are enabled by default if they're available.\nDEFAULT_CIPHERS = \":\".join(\n    [\n        \"ECDHE+AESGCM\",\n        \"ECDHE+CHACHA20\",\n        \"DHE+AESGCM\",\n        \"DHE+CHACHA20\",\n        \"ECDH+AESGCM\",\n        \"DH+AESGCM\",\n        \"ECDH+AES\",\n        \"DH+AES\",\n        \"RSA+AESGCM\",\n        \"RSA+AES\",\n        \"!aNULL\",\n        \"!eNULL\",\n        \"!MD5\",\n        \"!DSS\",\n    ]\n)\n\ntry:\n    from ssl import SSLContext  # Modern SSL?\nexcept ImportError:\n\n    class SSLContext(object):  # Platform-specific: Python 2\n        def __init__(self, protocol_version):\n            self.protocol = protocol_version\n            # Use default values from a real SSLContext\n            self.check_hostname = False\n            self.verify_mode = ssl.CERT_NONE\n            self.ca_certs = None\n            self.options = 0\n            self.certfile = None\n            self.keyfile = None\n            self.ciphers = None\n\n        def load_cert_chain(self, certfile, keyfile):\n            self.certfile = certfile\n            self.keyfile = keyfile\n\n        def load_verify_locations(self, cafile=None, capath=None, cadata=None):\n            self.ca_certs = cafile\n\n            if capath is not None:\n                raise SSLError(\"CA directories not supported in older Pythons\")\n\n            if cadata is not None:\n                raise SSLError(\"CA data not supported in older Pythons\")\n\n        def set_ciphers(self, cipher_suite):\n            self.ciphers = cipher_suite\n\n        def wrap_socket(self, socket, server_hostname=None, server_side=False):\n            warnings.warn(\n                \"A true SSLContext object is not available. This prevents \"\n                \"urllib3 from configuring SSL appropriately and may cause \"\n                \"certain SSL connections to fail. You can upgrade to a newer \"\n                \"version of Python to solve this. For more information, see \"\n                \"https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html\"\n                \"#ssl-warnings\",\n                InsecurePlatformWarning,\n            )\n            kwargs = {\n                \"keyfile\": self.keyfile,\n                \"certfile\": self.certfile,\n                \"ca_certs\": self.ca_certs,\n                \"cert_reqs\": self.verify_mode,\n                \"ssl_version\": self.protocol,\n                \"server_side\": server_side,\n            }\n            return wrap_socket(socket, ciphers=self.ciphers, **kwargs)\n\n\ndef assert_fingerprint(cert, fingerprint):\n    \"\"\"\n    Checks if given fingerprint matches the supplied certificate.\n\n    :param cert:\n        Certificate as bytes object.\n    :param fingerprint:\n        Fingerprint as string of hexdigits, can be interspersed by colons.\n    \"\"\"\n\n    fingerprint = fingerprint.replace(\":\", \"\").lower()\n    digest_length = len(fingerprint)\n    hashfunc = HASHFUNC_MAP.get(digest_length)\n    if not hashfunc:\n        raise SSLError(\"Fingerprint of invalid length: {0}\".format(fingerprint))\n\n    # We need encode() here for py32; works on py2 and p33.\n    fingerprint_bytes = unhexlify(fingerprint.encode())\n\n    cert_digest = hashfunc(cert).digest()\n\n    if not _const_compare_digest(cert_digest, fingerprint_bytes):\n        raise SSLError(\n            'Fingerprints did not match. Expected \"{0}\", got \"{1}\".'.format(\n                fingerprint, hexlify(cert_digest)\n            )\n        )\n\n\ndef resolve_cert_reqs(candidate):\n    \"\"\"\n    Resolves the argument to a numeric constant, which can be passed to\n    the wrap_socket function/method from the ssl module.\n    Defaults to :data:`ssl.CERT_REQUIRED`.\n    If given a string it is assumed to be the name of the constant in the\n    :mod:`ssl` module or its abbreviation.\n    (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.\n    If it's neither `None` nor a string we assume it is already the numeric\n    constant which can directly be passed to wrap_socket.\n    \"\"\"\n    if candidate is None:\n        return CERT_REQUIRED\n\n    if isinstance(candidate, str):\n        res = getattr(ssl, candidate, None)\n        if res is None:\n            res = getattr(ssl, \"CERT_\" + candidate)\n        return res\n\n    return candidate\n\n\ndef resolve_ssl_version(candidate):\n    \"\"\"\n    like resolve_cert_reqs\n    \"\"\"\n    if candidate is None:\n        return PROTOCOL_TLS\n\n    if isinstance(candidate, str):\n        res = getattr(ssl, candidate, None)\n        if res is None:\n            res = getattr(ssl, \"PROTOCOL_\" + candidate)\n        return res\n\n    return candidate\n\n\ndef create_urllib3_context(\n    ssl_version=None, cert_reqs=None, options=None, ciphers=None\n):\n    \"\"\"All arguments have the same meaning as ``ssl_wrap_socket``.\n\n    By default, this function does a lot of the same work that\n    ``ssl.create_default_context`` does on Python 3.4+. It:\n\n    - Disables SSLv2, SSLv3, and compression\n    - Sets a restricted set of server ciphers\n\n    If you wish to enable SSLv3, you can do::\n\n        from pip._vendor.urllib3.util import ssl_\n        context = ssl_.create_urllib3_context()\n        context.options &= ~ssl_.OP_NO_SSLv3\n\n    You can do the same to enable compression (substituting ``COMPRESSION``\n    for ``SSLv3`` in the last line above).\n\n    :param ssl_version:\n        The desired protocol version to use. This will default to\n        PROTOCOL_SSLv23 which will negotiate the highest protocol that both\n        the server and your installation of OpenSSL support.\n    :param cert_reqs:\n        Whether to require the certificate verification. This defaults to\n        ``ssl.CERT_REQUIRED``.\n    :param options:\n        Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,\n        ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``.\n    :param ciphers:\n        Which cipher suites to allow the server to select.\n    :returns:\n        Constructed SSLContext object with specified options\n    :rtype: SSLContext\n    \"\"\"\n    # PROTOCOL_TLS is deprecated in Python 3.10\n    if not ssl_version or ssl_version == PROTOCOL_TLS:\n        ssl_version = PROTOCOL_TLS_CLIENT\n\n    context = SSLContext(ssl_version)\n\n    context.set_ciphers(ciphers or DEFAULT_CIPHERS)\n\n    # Setting the default here, as we may have no ssl module on import\n    cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs\n\n    if options is None:\n        options = 0\n        # SSLv2 is easily broken and is considered harmful and dangerous\n        options |= OP_NO_SSLv2\n        # SSLv3 has several problems and is now dangerous\n        options |= OP_NO_SSLv3\n        # Disable compression to prevent CRIME attacks for OpenSSL 1.0+\n        # (issue #309)\n        options |= OP_NO_COMPRESSION\n        # TLSv1.2 only. Unless set explicitly, do not request tickets.\n        # This may save some bandwidth on wire, and although the ticket is encrypted,\n        # there is a risk associated with it being on wire,\n        # if the server is not rotating its ticketing keys properly.\n        options |= OP_NO_TICKET\n\n    context.options |= options\n\n    # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is\n    # necessary for conditional client cert authentication with TLS 1.3.\n    # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older\n    # versions of Python.  We only enable on Python 3.7.4+ or if certificate\n    # verification is enabled to work around Python issue #37428\n    # See: https://bugs.python.org/issue37428\n    if (cert_reqs == ssl.CERT_REQUIRED or sys.version_info >= (3, 7, 4)) and getattr(\n        context, \"post_handshake_auth\", None\n    ) is not None:\n        context.post_handshake_auth = True\n\n    def disable_check_hostname():\n        if (\n            getattr(context, \"check_hostname\", None) is not None\n        ):  # Platform-specific: Python 3.2\n            # We do our own verification, including fingerprints and alternative\n            # hostnames. So disable it here\n            context.check_hostname = False\n\n    # The order of the below lines setting verify_mode and check_hostname\n    # matter due to safe-guards SSLContext has to prevent an SSLContext with\n    # check_hostname=True, verify_mode=NONE/OPTIONAL. This is made even more\n    # complex because we don't know whether PROTOCOL_TLS_CLIENT will be used\n    # or not so we don't know the initial state of the freshly created SSLContext.\n    if cert_reqs == ssl.CERT_REQUIRED:\n        context.verify_mode = cert_reqs\n        disable_check_hostname()\n    else:\n        disable_check_hostname()\n        context.verify_mode = cert_reqs\n\n    # Enable logging of TLS session keys via defacto standard environment variable\n    # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values.\n    if hasattr(context, \"keylog_filename\"):\n        sslkeylogfile = os.environ.get(\"SSLKEYLOGFILE\")\n        if sslkeylogfile:\n            context.keylog_filename = sslkeylogfile\n\n    return context\n\n\ndef ssl_wrap_socket(\n    sock,\n    keyfile=None,\n    certfile=None,\n    cert_reqs=None,\n    ca_certs=None,\n    server_hostname=None,\n    ssl_version=None,\n    ciphers=None,\n    ssl_context=None,\n    ca_cert_dir=None,\n    key_password=None,\n    ca_cert_data=None,\n    tls_in_tls=False,\n):\n    \"\"\"\n    All arguments except for server_hostname, ssl_context, and ca_cert_dir have\n    the same meaning as they do when using :func:`ssl.wrap_socket`.\n\n    :param server_hostname:\n        When SNI is supported, the expected hostname of the certificate\n    :param ssl_context:\n        A pre-made :class:`SSLContext` object. If none is provided, one will\n        be created using :func:`create_urllib3_context`.\n    :param ciphers:\n        A string of ciphers we wish the client to support.\n    :param ca_cert_dir:\n        A directory containing CA certificates in multiple separate files, as\n        supported by OpenSSL's -CApath flag or the capath argument to\n        SSLContext.load_verify_locations().\n    :param key_password:\n        Optional password if the keyfile is encrypted.\n    :param ca_cert_data:\n        Optional string containing CA certificates in PEM format suitable for\n        passing as the cadata parameter to SSLContext.load_verify_locations()\n    :param tls_in_tls:\n        Use SSLTransport to wrap the existing socket.\n    \"\"\"\n    context = ssl_context\n    if context is None:\n        # Note: This branch of code and all the variables in it are no longer\n        # used by urllib3 itself. We should consider deprecating and removing\n        # this code.\n        context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers)\n\n    if ca_certs or ca_cert_dir or ca_cert_data:\n        try:\n            context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data)\n        except (IOError, OSError) as e:\n            raise SSLError(e)\n\n    elif ssl_context is None and hasattr(context, \"load_default_certs\"):\n        # try to load OS default certs; works well on Windows (require Python3.4+)\n        context.load_default_certs()\n\n    # Attempt to detect if we get the goofy behavior of the\n    # keyfile being encrypted and OpenSSL asking for the\n    # passphrase via the terminal and instead error out.\n    if keyfile and key_password is None and _is_key_file_encrypted(keyfile):\n        raise SSLError(\"Client private key is encrypted, password is required\")\n\n    if certfile:\n        if key_password is None:\n            context.load_cert_chain(certfile, keyfile)\n        else:\n            context.load_cert_chain(certfile, keyfile, key_password)\n\n    try:\n        if hasattr(context, \"set_alpn_protocols\"):\n            context.set_alpn_protocols(ALPN_PROTOCOLS)\n    except NotImplementedError:  # Defensive: in CI, we always have set_alpn_protocols\n        pass\n\n    # If we detect server_hostname is an IP address then the SNI\n    # extension should not be used according to RFC3546 Section 3.1\n    use_sni_hostname = server_hostname and not is_ipaddress(server_hostname)\n    # SecureTransport uses server_hostname in certificate verification.\n    send_sni = (use_sni_hostname and HAS_SNI) or (\n        IS_SECURETRANSPORT and server_hostname\n    )\n    # Do not warn the user if server_hostname is an invalid SNI hostname.\n    if not HAS_SNI and use_sni_hostname:\n        warnings.warn(\n            \"An HTTPS request has been made, but the SNI (Server Name \"\n            \"Indication) extension to TLS is not available on this platform. \"\n            \"This may cause the server to present an incorrect TLS \"\n            \"certificate, which can cause validation failures. You can upgrade to \"\n            \"a newer version of Python to solve this. For more information, see \"\n            \"https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html\"\n            \"#ssl-warnings\",\n            SNIMissingWarning,\n        )\n\n    if send_sni:\n        ssl_sock = _ssl_wrap_socket_impl(\n            sock, context, tls_in_tls, server_hostname=server_hostname\n        )\n    else:\n        ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)\n    return ssl_sock\n\n\ndef is_ipaddress(hostname):\n    \"\"\"Detects whether the hostname given is an IPv4 or IPv6 address.\n    Also detects IPv6 addresses with Zone IDs.\n\n    :param str hostname: Hostname to examine.\n    :return: True if the hostname is an IP address, False otherwise.\n    \"\"\"\n    if not six.PY2 and isinstance(hostname, bytes):\n        # IDN A-label bytes are ASCII compatible.\n        hostname = hostname.decode(\"ascii\")\n    return bool(IPV4_RE.match(hostname) or BRACELESS_IPV6_ADDRZ_RE.match(hostname))\n\n\ndef _is_key_file_encrypted(key_file):\n    \"\"\"Detects if a key file is encrypted or not.\"\"\"\n    with open(key_file, \"r\") as f:\n        for line in f:\n            # Look for Proc-Type: 4,ENCRYPTED\n            if \"ENCRYPTED\" in line:\n                return True\n\n    return False\n\n\ndef _ssl_wrap_socket_impl(sock, ssl_context, tls_in_tls, server_hostname=None):\n    if tls_in_tls:\n        if not SSLTransport:\n            # Import error, ssl is not available.\n            raise ProxySchemeUnsupported(\n                \"TLS in TLS requires support for the 'ssl' module\"\n            )\n\n        SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context)\n        return SSLTransport(sock, ssl_context, server_hostname)\n\n    if server_hostname:\n        return ssl_context.wrap_socket(sock, server_hostname=server_hostname)\n    else:\n        return ssl_context.wrap_socket(sock)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/util/ssl_match_hostname.py",
    "content": "\"\"\"The match_hostname() function from Python 3.3.3, essential when using SSL.\"\"\"\n\n# Note: This file is under the PSF license as the code comes from the python\n# stdlib.   http://docs.python.org/3/license.html\n\nimport re\nimport sys\n\n# ipaddress has been backported to 2.6+ in pypi.  If it is installed on the\n# system, use it to handle IPAddress ServerAltnames (this was added in\n# python-3.5) otherwise only do DNS matching.  This allows\n# util.ssl_match_hostname to continue to be used in Python 2.7.\ntry:\n    import ipaddress\nexcept ImportError:\n    ipaddress = None\n\n__version__ = \"3.5.0.1\"\n\n\nclass CertificateError(ValueError):\n    pass\n\n\ndef _dnsname_match(dn, hostname, max_wildcards=1):\n    \"\"\"Matching according to RFC 6125, section 6.4.3\n\n    http://tools.ietf.org/html/rfc6125#section-6.4.3\n    \"\"\"\n    pats = []\n    if not dn:\n        return False\n\n    # Ported from python3-syntax:\n    # leftmost, *remainder = dn.split(r'.')\n    parts = dn.split(r\".\")\n    leftmost = parts[0]\n    remainder = parts[1:]\n\n    wildcards = leftmost.count(\"*\")\n    if wildcards > max_wildcards:\n        # Issue #17980: avoid denials of service by refusing more\n        # than one wildcard per fragment.  A survey of established\n        # policy among SSL implementations showed it to be a\n        # reasonable choice.\n        raise CertificateError(\n            \"too many wildcards in certificate DNS name: \" + repr(dn)\n        )\n\n    # speed up common case w/o wildcards\n    if not wildcards:\n        return dn.lower() == hostname.lower()\n\n    # RFC 6125, section 6.4.3, subitem 1.\n    # The client SHOULD NOT attempt to match a presented identifier in which\n    # the wildcard character comprises a label other than the left-most label.\n    if leftmost == \"*\":\n        # When '*' is a fragment by itself, it matches a non-empty dotless\n        # fragment.\n        pats.append(\"[^.]+\")\n    elif leftmost.startswith(\"xn--\") or hostname.startswith(\"xn--\"):\n        # RFC 6125, section 6.4.3, subitem 3.\n        # The client SHOULD NOT attempt to match a presented identifier\n        # where the wildcard character is embedded within an A-label or\n        # U-label of an internationalized domain name.\n        pats.append(re.escape(leftmost))\n    else:\n        # Otherwise, '*' matches any dotless string, e.g. www*\n        pats.append(re.escape(leftmost).replace(r\"\\*\", \"[^.]*\"))\n\n    # add the remaining fragments, ignore any wildcards\n    for frag in remainder:\n        pats.append(re.escape(frag))\n\n    pat = re.compile(r\"\\A\" + r\"\\.\".join(pats) + r\"\\Z\", re.IGNORECASE)\n    return pat.match(hostname)\n\n\ndef _to_unicode(obj):\n    if isinstance(obj, str) and sys.version_info < (3,):\n        # ignored flake8 # F821 to support python 2.7 function\n        obj = unicode(obj, encoding=\"ascii\", errors=\"strict\")  # noqa: F821\n    return obj\n\n\ndef _ipaddress_match(ipname, host_ip):\n    \"\"\"Exact matching of IP addresses.\n\n    RFC 6125 explicitly doesn't define an algorithm for this\n    (section 1.7.2 - \"Out of Scope\").\n    \"\"\"\n    # OpenSSL may add a trailing newline to a subjectAltName's IP address\n    # Divergence from upstream: ipaddress can't handle byte str\n    ip = ipaddress.ip_address(_to_unicode(ipname).rstrip())\n    return ip == host_ip\n\n\ndef match_hostname(cert, hostname):\n    \"\"\"Verify that *cert* (in decoded format as returned by\n    SSLSocket.getpeercert()) matches the *hostname*.  RFC 2818 and RFC 6125\n    rules are followed, but IP addresses are not accepted for *hostname*.\n\n    CertificateError is raised on failure. On success, the function\n    returns nothing.\n    \"\"\"\n    if not cert:\n        raise ValueError(\n            \"empty or no certificate, match_hostname needs a \"\n            \"SSL socket or SSL context with either \"\n            \"CERT_OPTIONAL or CERT_REQUIRED\"\n        )\n    try:\n        # Divergence from upstream: ipaddress can't handle byte str\n        host_ip = ipaddress.ip_address(_to_unicode(hostname))\n    except (UnicodeError, ValueError):\n        # ValueError: Not an IP address (common case)\n        # UnicodeError: Divergence from upstream: Have to deal with ipaddress not taking\n        # byte strings.  addresses should be all ascii, so we consider it not\n        # an ipaddress in this case\n        host_ip = None\n    except AttributeError:\n        # Divergence from upstream: Make ipaddress library optional\n        if ipaddress is None:\n            host_ip = None\n        else:  # Defensive\n            raise\n    dnsnames = []\n    san = cert.get(\"subjectAltName\", ())\n    for key, value in san:\n        if key == \"DNS\":\n            if host_ip is None and _dnsname_match(value, hostname):\n                return\n            dnsnames.append(value)\n        elif key == \"IP Address\":\n            if host_ip is not None and _ipaddress_match(value, host_ip):\n                return\n            dnsnames.append(value)\n    if not dnsnames:\n        # The subject is only checked when there is no dNSName entry\n        # in subjectAltName\n        for sub in cert.get(\"subject\", ()):\n            for key, value in sub:\n                # XXX according to RFC 2818, the most specific Common Name\n                # must be used.\n                if key == \"commonName\":\n                    if _dnsname_match(value, hostname):\n                        return\n                    dnsnames.append(value)\n    if len(dnsnames) > 1:\n        raise CertificateError(\n            \"hostname %r \"\n            \"doesn't match either of %s\" % (hostname, \", \".join(map(repr, dnsnames)))\n        )\n    elif len(dnsnames) == 1:\n        raise CertificateError(\"hostname %r doesn't match %r\" % (hostname, dnsnames[0]))\n    else:\n        raise CertificateError(\n            \"no appropriate commonName or subjectAltName fields were found\"\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/util/ssltransport.py",
    "content": "import io\nimport socket\nimport ssl\n\nfrom ..exceptions import ProxySchemeUnsupported\nfrom ..packages import six\n\nSSL_BLOCKSIZE = 16384\n\n\nclass SSLTransport:\n    \"\"\"\n    The SSLTransport wraps an existing socket and establishes an SSL connection.\n\n    Contrary to Python's implementation of SSLSocket, it allows you to chain\n    multiple TLS connections together. It's particularly useful if you need to\n    implement TLS within TLS.\n\n    The class supports most of the socket API operations.\n    \"\"\"\n\n    @staticmethod\n    def _validate_ssl_context_for_tls_in_tls(ssl_context):\n        \"\"\"\n        Raises a ProxySchemeUnsupported if the provided ssl_context can't be used\n        for TLS in TLS.\n\n        The only requirement is that the ssl_context provides the 'wrap_bio'\n        methods.\n        \"\"\"\n\n        if not hasattr(ssl_context, \"wrap_bio\"):\n            if six.PY2:\n                raise ProxySchemeUnsupported(\n                    \"TLS in TLS requires SSLContext.wrap_bio() which isn't \"\n                    \"supported on Python 2\"\n                )\n            else:\n                raise ProxySchemeUnsupported(\n                    \"TLS in TLS requires SSLContext.wrap_bio() which isn't \"\n                    \"available on non-native SSLContext\"\n                )\n\n    def __init__(\n        self, socket, ssl_context, server_hostname=None, suppress_ragged_eofs=True\n    ):\n        \"\"\"\n        Create an SSLTransport around socket using the provided ssl_context.\n        \"\"\"\n        self.incoming = ssl.MemoryBIO()\n        self.outgoing = ssl.MemoryBIO()\n\n        self.suppress_ragged_eofs = suppress_ragged_eofs\n        self.socket = socket\n\n        self.sslobj = ssl_context.wrap_bio(\n            self.incoming, self.outgoing, server_hostname=server_hostname\n        )\n\n        # Perform initial handshake.\n        self._ssl_io_loop(self.sslobj.do_handshake)\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, *_):\n        self.close()\n\n    def fileno(self):\n        return self.socket.fileno()\n\n    def read(self, len=1024, buffer=None):\n        return self._wrap_ssl_read(len, buffer)\n\n    def recv(self, len=1024, flags=0):\n        if flags != 0:\n            raise ValueError(\"non-zero flags not allowed in calls to recv\")\n        return self._wrap_ssl_read(len)\n\n    def recv_into(self, buffer, nbytes=None, flags=0):\n        if flags != 0:\n            raise ValueError(\"non-zero flags not allowed in calls to recv_into\")\n        if buffer and (nbytes is None):\n            nbytes = len(buffer)\n        elif nbytes is None:\n            nbytes = 1024\n        return self.read(nbytes, buffer)\n\n    def sendall(self, data, flags=0):\n        if flags != 0:\n            raise ValueError(\"non-zero flags not allowed in calls to sendall\")\n        count = 0\n        with memoryview(data) as view, view.cast(\"B\") as byte_view:\n            amount = len(byte_view)\n            while count < amount:\n                v = self.send(byte_view[count:])\n                count += v\n\n    def send(self, data, flags=0):\n        if flags != 0:\n            raise ValueError(\"non-zero flags not allowed in calls to send\")\n        response = self._ssl_io_loop(self.sslobj.write, data)\n        return response\n\n    def makefile(\n        self, mode=\"r\", buffering=None, encoding=None, errors=None, newline=None\n    ):\n        \"\"\"\n        Python's httpclient uses makefile and buffered io when reading HTTP\n        messages and we need to support it.\n\n        This is unfortunately a copy and paste of socket.py makefile with small\n        changes to point to the socket directly.\n        \"\"\"\n        if not set(mode) <= {\"r\", \"w\", \"b\"}:\n            raise ValueError(\"invalid mode %r (only r, w, b allowed)\" % (mode,))\n\n        writing = \"w\" in mode\n        reading = \"r\" in mode or not writing\n        assert reading or writing\n        binary = \"b\" in mode\n        rawmode = \"\"\n        if reading:\n            rawmode += \"r\"\n        if writing:\n            rawmode += \"w\"\n        raw = socket.SocketIO(self, rawmode)\n        self.socket._io_refs += 1\n        if buffering is None:\n            buffering = -1\n        if buffering < 0:\n            buffering = io.DEFAULT_BUFFER_SIZE\n        if buffering == 0:\n            if not binary:\n                raise ValueError(\"unbuffered streams must be binary\")\n            return raw\n        if reading and writing:\n            buffer = io.BufferedRWPair(raw, raw, buffering)\n        elif reading:\n            buffer = io.BufferedReader(raw, buffering)\n        else:\n            assert writing\n            buffer = io.BufferedWriter(raw, buffering)\n        if binary:\n            return buffer\n        text = io.TextIOWrapper(buffer, encoding, errors, newline)\n        text.mode = mode\n        return text\n\n    def unwrap(self):\n        self._ssl_io_loop(self.sslobj.unwrap)\n\n    def close(self):\n        self.socket.close()\n\n    def getpeercert(self, binary_form=False):\n        return self.sslobj.getpeercert(binary_form)\n\n    def version(self):\n        return self.sslobj.version()\n\n    def cipher(self):\n        return self.sslobj.cipher()\n\n    def selected_alpn_protocol(self):\n        return self.sslobj.selected_alpn_protocol()\n\n    def selected_npn_protocol(self):\n        return self.sslobj.selected_npn_protocol()\n\n    def shared_ciphers(self):\n        return self.sslobj.shared_ciphers()\n\n    def compression(self):\n        return self.sslobj.compression()\n\n    def settimeout(self, value):\n        self.socket.settimeout(value)\n\n    def gettimeout(self):\n        return self.socket.gettimeout()\n\n    def _decref_socketios(self):\n        self.socket._decref_socketios()\n\n    def _wrap_ssl_read(self, len, buffer=None):\n        try:\n            return self._ssl_io_loop(self.sslobj.read, len, buffer)\n        except ssl.SSLError as e:\n            if e.errno == ssl.SSL_ERROR_EOF and self.suppress_ragged_eofs:\n                return 0  # eof, return 0.\n            else:\n                raise\n\n    def _ssl_io_loop(self, func, *args):\n        \"\"\"Performs an I/O loop between incoming/outgoing and the socket.\"\"\"\n        should_loop = True\n        ret = None\n\n        while should_loop:\n            errno = None\n            try:\n                ret = func(*args)\n            except ssl.SSLError as e:\n                if e.errno not in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE):\n                    # WANT_READ, and WANT_WRITE are expected, others are not.\n                    raise e\n                errno = e.errno\n\n            buf = self.outgoing.read()\n            self.socket.sendall(buf)\n\n            if errno is None:\n                should_loop = False\n            elif errno == ssl.SSL_ERROR_WANT_READ:\n                buf = self.socket.recv(SSL_BLOCKSIZE)\n                if buf:\n                    self.incoming.write(buf)\n                else:\n                    self.incoming.write_eof()\n        return ret\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/util/timeout.py",
    "content": "from __future__ import absolute_import\n\nimport time\n\n# The default socket timeout, used by httplib to indicate that no timeout was\n# specified by the user\nfrom socket import _GLOBAL_DEFAULT_TIMEOUT\n\nfrom ..exceptions import TimeoutStateError\n\n# A sentinel value to indicate that no timeout was specified by the user in\n# urllib3\n_Default = object()\n\n\n# Use time.monotonic if available.\ncurrent_time = getattr(time, \"monotonic\", time.time)\n\n\nclass Timeout(object):\n    \"\"\"Timeout configuration.\n\n    Timeouts can be defined as a default for a pool:\n\n    .. code-block:: python\n\n       timeout = Timeout(connect=2.0, read=7.0)\n       http = PoolManager(timeout=timeout)\n       response = http.request('GET', 'http://example.com/')\n\n    Or per-request (which overrides the default for the pool):\n\n    .. code-block:: python\n\n       response = http.request('GET', 'http://example.com/', timeout=Timeout(10))\n\n    Timeouts can be disabled by setting all the parameters to ``None``:\n\n    .. code-block:: python\n\n       no_timeout = Timeout(connect=None, read=None)\n       response = http.request('GET', 'http://example.com/, timeout=no_timeout)\n\n\n    :param total:\n        This combines the connect and read timeouts into one; the read timeout\n        will be set to the time leftover from the connect attempt. In the\n        event that both a connect timeout and a total are specified, or a read\n        timeout and a total are specified, the shorter timeout will be applied.\n\n        Defaults to None.\n\n    :type total: int, float, or None\n\n    :param connect:\n        The maximum amount of time (in seconds) to wait for a connection\n        attempt to a server to succeed. Omitting the parameter will default the\n        connect timeout to the system default, probably `the global default\n        timeout in socket.py\n        <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.\n        None will set an infinite timeout for connection attempts.\n\n    :type connect: int, float, or None\n\n    :param read:\n        The maximum amount of time (in seconds) to wait between consecutive\n        read operations for a response from the server. Omitting the parameter\n        will default the read timeout to the system default, probably `the\n        global default timeout in socket.py\n        <http://hg.python.org/cpython/file/603b4d593758/Lib/socket.py#l535>`_.\n        None will set an infinite timeout.\n\n    :type read: int, float, or None\n\n    .. note::\n\n        Many factors can affect the total amount of time for urllib3 to return\n        an HTTP response.\n\n        For example, Python's DNS resolver does not obey the timeout specified\n        on the socket. Other factors that can affect total request time include\n        high CPU load, high swap, the program running at a low priority level,\n        or other behaviors.\n\n        In addition, the read and total timeouts only measure the time between\n        read operations on the socket connecting the client and the server,\n        not the total amount of time for the request to return a complete\n        response. For most requests, the timeout is raised because the server\n        has not sent the first byte in the specified time. This is not always\n        the case; if a server streams one byte every fifteen seconds, a timeout\n        of 20 seconds will not trigger, even though the request will take\n        several minutes to complete.\n\n        If your goal is to cut off any request after a set amount of wall clock\n        time, consider having a second \"watcher\" thread to cut off a slow\n        request.\n    \"\"\"\n\n    #: A sentinel object representing the default timeout value\n    DEFAULT_TIMEOUT = _GLOBAL_DEFAULT_TIMEOUT\n\n    def __init__(self, total=None, connect=_Default, read=_Default):\n        self._connect = self._validate_timeout(connect, \"connect\")\n        self._read = self._validate_timeout(read, \"read\")\n        self.total = self._validate_timeout(total, \"total\")\n        self._start_connect = None\n\n    def __repr__(self):\n        return \"%s(connect=%r, read=%r, total=%r)\" % (\n            type(self).__name__,\n            self._connect,\n            self._read,\n            self.total,\n        )\n\n    # __str__ provided for backwards compatibility\n    __str__ = __repr__\n\n    @classmethod\n    def _validate_timeout(cls, value, name):\n        \"\"\"Check that a timeout attribute is valid.\n\n        :param value: The timeout value to validate\n        :param name: The name of the timeout attribute to validate. This is\n            used to specify in error messages.\n        :return: The validated and casted version of the given value.\n        :raises ValueError: If it is a numeric value less than or equal to\n            zero, or the type is not an integer, float, or None.\n        \"\"\"\n        if value is _Default:\n            return cls.DEFAULT_TIMEOUT\n\n        if value is None or value is cls.DEFAULT_TIMEOUT:\n            return value\n\n        if isinstance(value, bool):\n            raise ValueError(\n                \"Timeout cannot be a boolean value. It must \"\n                \"be an int, float or None.\"\n            )\n        try:\n            float(value)\n        except (TypeError, ValueError):\n            raise ValueError(\n                \"Timeout value %s was %s, but it must be an \"\n                \"int, float or None.\" % (name, value)\n            )\n\n        try:\n            if value <= 0:\n                raise ValueError(\n                    \"Attempted to set %s timeout to %s, but the \"\n                    \"timeout cannot be set to a value less \"\n                    \"than or equal to 0.\" % (name, value)\n                )\n        except TypeError:\n            # Python 3\n            raise ValueError(\n                \"Timeout value %s was %s, but it must be an \"\n                \"int, float or None.\" % (name, value)\n            )\n\n        return value\n\n    @classmethod\n    def from_float(cls, timeout):\n        \"\"\"Create a new Timeout from a legacy timeout value.\n\n        The timeout value used by httplib.py sets the same timeout on the\n        connect(), and recv() socket requests. This creates a :class:`Timeout`\n        object that sets the individual timeouts to the ``timeout`` value\n        passed to this function.\n\n        :param timeout: The legacy timeout value.\n        :type timeout: integer, float, sentinel default object, or None\n        :return: Timeout object\n        :rtype: :class:`Timeout`\n        \"\"\"\n        return Timeout(read=timeout, connect=timeout)\n\n    def clone(self):\n        \"\"\"Create a copy of the timeout object\n\n        Timeout properties are stored per-pool but each request needs a fresh\n        Timeout object to ensure each one has its own start/stop configured.\n\n        :return: a copy of the timeout object\n        :rtype: :class:`Timeout`\n        \"\"\"\n        # We can't use copy.deepcopy because that will also create a new object\n        # for _GLOBAL_DEFAULT_TIMEOUT, which socket.py uses as a sentinel to\n        # detect the user default.\n        return Timeout(connect=self._connect, read=self._read, total=self.total)\n\n    def start_connect(self):\n        \"\"\"Start the timeout clock, used during a connect() attempt\n\n        :raises urllib3.exceptions.TimeoutStateError: if you attempt\n            to start a timer that has been started already.\n        \"\"\"\n        if self._start_connect is not None:\n            raise TimeoutStateError(\"Timeout timer has already been started.\")\n        self._start_connect = current_time()\n        return self._start_connect\n\n    def get_connect_duration(self):\n        \"\"\"Gets the time elapsed since the call to :meth:`start_connect`.\n\n        :return: Elapsed time in seconds.\n        :rtype: float\n        :raises urllib3.exceptions.TimeoutStateError: if you attempt\n            to get duration for a timer that hasn't been started.\n        \"\"\"\n        if self._start_connect is None:\n            raise TimeoutStateError(\n                \"Can't get connect duration for timer that has not started.\"\n            )\n        return current_time() - self._start_connect\n\n    @property\n    def connect_timeout(self):\n        \"\"\"Get the value to use when setting a connection timeout.\n\n        This will be a positive float or integer, the value None\n        (never timeout), or the default system timeout.\n\n        :return: Connect timeout.\n        :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None\n        \"\"\"\n        if self.total is None:\n            return self._connect\n\n        if self._connect is None or self._connect is self.DEFAULT_TIMEOUT:\n            return self.total\n\n        return min(self._connect, self.total)\n\n    @property\n    def read_timeout(self):\n        \"\"\"Get the value for the read timeout.\n\n        This assumes some time has elapsed in the connection timeout and\n        computes the read timeout appropriately.\n\n        If self.total is set, the read timeout is dependent on the amount of\n        time taken by the connect timeout. If the connection time has not been\n        established, a :exc:`~urllib3.exceptions.TimeoutStateError` will be\n        raised.\n\n        :return: Value to use for the read timeout.\n        :rtype: int, float, :attr:`Timeout.DEFAULT_TIMEOUT` or None\n        :raises urllib3.exceptions.TimeoutStateError: If :meth:`start_connect`\n            has not yet been called on this object.\n        \"\"\"\n        if (\n            self.total is not None\n            and self.total is not self.DEFAULT_TIMEOUT\n            and self._read is not None\n            and self._read is not self.DEFAULT_TIMEOUT\n        ):\n            # In case the connect timeout has not yet been established.\n            if self._start_connect is None:\n                return self._read\n            return max(0, min(self.total - self.get_connect_duration(), self._read))\n        elif self.total is not None and self.total is not self.DEFAULT_TIMEOUT:\n            return max(0, self.total - self.get_connect_duration())\n        else:\n            return self._read\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/util/url.py",
    "content": "from __future__ import absolute_import\n\nimport re\nfrom collections import namedtuple\n\nfrom ..exceptions import LocationParseError\nfrom ..packages import six\n\nurl_attrs = [\"scheme\", \"auth\", \"host\", \"port\", \"path\", \"query\", \"fragment\"]\n\n# We only want to normalize urls with an HTTP(S) scheme.\n# urllib3 infers URLs without a scheme (None) to be http.\nNORMALIZABLE_SCHEMES = (\"http\", \"https\", None)\n\n# Almost all of these patterns were derived from the\n# 'rfc3986' module: https://github.com/python-hyper/rfc3986\nPERCENT_RE = re.compile(r\"%[a-fA-F0-9]{2}\")\nSCHEME_RE = re.compile(r\"^(?:[a-zA-Z][a-zA-Z0-9+-]*:|/)\")\nURI_RE = re.compile(\n    r\"^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?\"\n    r\"(?://([^\\\\/?#]*))?\"\n    r\"([^?#]*)\"\n    r\"(?:\\?([^#]*))?\"\n    r\"(?:#(.*))?$\",\n    re.UNICODE | re.DOTALL,\n)\n\nIPV4_PAT = r\"(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\"\nHEX_PAT = \"[0-9A-Fa-f]{1,4}\"\nLS32_PAT = \"(?:{hex}:{hex}|{ipv4})\".format(hex=HEX_PAT, ipv4=IPV4_PAT)\n_subs = {\"hex\": HEX_PAT, \"ls32\": LS32_PAT}\n_variations = [\n    #                            6( h16 \":\" ) ls32\n    \"(?:%(hex)s:){6}%(ls32)s\",\n    #                       \"::\" 5( h16 \":\" ) ls32\n    \"::(?:%(hex)s:){5}%(ls32)s\",\n    # [               h16 ] \"::\" 4( h16 \":\" ) ls32\n    \"(?:%(hex)s)?::(?:%(hex)s:){4}%(ls32)s\",\n    # [ *1( h16 \":\" ) h16 ] \"::\" 3( h16 \":\" ) ls32\n    \"(?:(?:%(hex)s:)?%(hex)s)?::(?:%(hex)s:){3}%(ls32)s\",\n    # [ *2( h16 \":\" ) h16 ] \"::\" 2( h16 \":\" ) ls32\n    \"(?:(?:%(hex)s:){0,2}%(hex)s)?::(?:%(hex)s:){2}%(ls32)s\",\n    # [ *3( h16 \":\" ) h16 ] \"::\"    h16 \":\"   ls32\n    \"(?:(?:%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s\",\n    # [ *4( h16 \":\" ) h16 ] \"::\"              ls32\n    \"(?:(?:%(hex)s:){0,4}%(hex)s)?::%(ls32)s\",\n    # [ *5( h16 \":\" ) h16 ] \"::\"              h16\n    \"(?:(?:%(hex)s:){0,5}%(hex)s)?::%(hex)s\",\n    # [ *6( h16 \":\" ) h16 ] \"::\"\n    \"(?:(?:%(hex)s:){0,6}%(hex)s)?::\",\n]\n\nUNRESERVED_PAT = r\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._!\\-~\"\nIPV6_PAT = \"(?:\" + \"|\".join([x % _subs for x in _variations]) + \")\"\nZONE_ID_PAT = \"(?:%25|%)(?:[\" + UNRESERVED_PAT + \"]|%[a-fA-F0-9]{2})+\"\nIPV6_ADDRZ_PAT = r\"\\[\" + IPV6_PAT + r\"(?:\" + ZONE_ID_PAT + r\")?\\]\"\nREG_NAME_PAT = r\"(?:[^\\[\\]%:/?#]|%[a-fA-F0-9]{2})*\"\nTARGET_RE = re.compile(r\"^(/[^?#]*)(?:\\?([^#]*))?(?:#.*)?$\")\n\nIPV4_RE = re.compile(\"^\" + IPV4_PAT + \"$\")\nIPV6_RE = re.compile(\"^\" + IPV6_PAT + \"$\")\nIPV6_ADDRZ_RE = re.compile(\"^\" + IPV6_ADDRZ_PAT + \"$\")\nBRACELESS_IPV6_ADDRZ_RE = re.compile(\"^\" + IPV6_ADDRZ_PAT[2:-2] + \"$\")\nZONE_ID_RE = re.compile(\"(\" + ZONE_ID_PAT + r\")\\]$\")\n\n_HOST_PORT_PAT = (\"^(%s|%s|%s)(?::([0-9]{0,5}))?$\") % (\n    REG_NAME_PAT,\n    IPV4_PAT,\n    IPV6_ADDRZ_PAT,\n)\n_HOST_PORT_RE = re.compile(_HOST_PORT_PAT, re.UNICODE | re.DOTALL)\n\nUNRESERVED_CHARS = set(\n    \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~\"\n)\nSUB_DELIM_CHARS = set(\"!$&'()*+,;=\")\nUSERINFO_CHARS = UNRESERVED_CHARS | SUB_DELIM_CHARS | {\":\"}\nPATH_CHARS = USERINFO_CHARS | {\"@\", \"/\"}\nQUERY_CHARS = FRAGMENT_CHARS = PATH_CHARS | {\"?\"}\n\n\nclass Url(namedtuple(\"Url\", url_attrs)):\n    \"\"\"\n    Data structure for representing an HTTP URL. Used as a return value for\n    :func:`parse_url`. Both the scheme and host are normalized as they are\n    both case-insensitive according to RFC 3986.\n    \"\"\"\n\n    __slots__ = ()\n\n    def __new__(\n        cls,\n        scheme=None,\n        auth=None,\n        host=None,\n        port=None,\n        path=None,\n        query=None,\n        fragment=None,\n    ):\n        if path and not path.startswith(\"/\"):\n            path = \"/\" + path\n        if scheme is not None:\n            scheme = scheme.lower()\n        return super(Url, cls).__new__(\n            cls, scheme, auth, host, port, path, query, fragment\n        )\n\n    @property\n    def hostname(self):\n        \"\"\"For backwards-compatibility with urlparse. We're nice like that.\"\"\"\n        return self.host\n\n    @property\n    def request_uri(self):\n        \"\"\"Absolute path including the query string.\"\"\"\n        uri = self.path or \"/\"\n\n        if self.query is not None:\n            uri += \"?\" + self.query\n\n        return uri\n\n    @property\n    def netloc(self):\n        \"\"\"Network location including host and port\"\"\"\n        if self.port:\n            return \"%s:%d\" % (self.host, self.port)\n        return self.host\n\n    @property\n    def url(self):\n        \"\"\"\n        Convert self into a url\n\n        This function should more or less round-trip with :func:`.parse_url`. The\n        returned url may not be exactly the same as the url inputted to\n        :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls\n        with a blank port will have : removed).\n\n        Example: ::\n\n            >>> U = parse_url('http://google.com/mail/')\n            >>> U.url\n            'http://google.com/mail/'\n            >>> Url('http', 'username:password', 'host.com', 80,\n            ... '/path', 'query', 'fragment').url\n            'http://username:password@host.com:80/path?query#fragment'\n        \"\"\"\n        scheme, auth, host, port, path, query, fragment = self\n        url = u\"\"\n\n        # We use \"is not None\" we want things to happen with empty strings (or 0 port)\n        if scheme is not None:\n            url += scheme + u\"://\"\n        if auth is not None:\n            url += auth + u\"@\"\n        if host is not None:\n            url += host\n        if port is not None:\n            url += u\":\" + str(port)\n        if path is not None:\n            url += path\n        if query is not None:\n            url += u\"?\" + query\n        if fragment is not None:\n            url += u\"#\" + fragment\n\n        return url\n\n    def __str__(self):\n        return self.url\n\n\ndef split_first(s, delims):\n    \"\"\"\n    .. deprecated:: 1.25\n\n    Given a string and an iterable of delimiters, split on the first found\n    delimiter. Return two split parts and the matched delimiter.\n\n    If not found, then the first part is the full input string.\n\n    Example::\n\n        >>> split_first('foo/bar?baz', '?/=')\n        ('foo', 'bar?baz', '/')\n        >>> split_first('foo/bar?baz', '123')\n        ('foo/bar?baz', '', None)\n\n    Scales linearly with number of delims. Not ideal for large number of delims.\n    \"\"\"\n    min_idx = None\n    min_delim = None\n    for d in delims:\n        idx = s.find(d)\n        if idx < 0:\n            continue\n\n        if min_idx is None or idx < min_idx:\n            min_idx = idx\n            min_delim = d\n\n    if min_idx is None or min_idx < 0:\n        return s, \"\", None\n\n    return s[:min_idx], s[min_idx + 1 :], min_delim\n\n\ndef _encode_invalid_chars(component, allowed_chars, encoding=\"utf-8\"):\n    \"\"\"Percent-encodes a URI component without reapplying\n    onto an already percent-encoded component.\n    \"\"\"\n    if component is None:\n        return component\n\n    component = six.ensure_text(component)\n\n    # Normalize existing percent-encoded bytes.\n    # Try to see if the component we're encoding is already percent-encoded\n    # so we can skip all '%' characters but still encode all others.\n    component, percent_encodings = PERCENT_RE.subn(\n        lambda match: match.group(0).upper(), component\n    )\n\n    uri_bytes = component.encode(\"utf-8\", \"surrogatepass\")\n    is_percent_encoded = percent_encodings == uri_bytes.count(b\"%\")\n    encoded_component = bytearray()\n\n    for i in range(0, len(uri_bytes)):\n        # Will return a single character bytestring on both Python 2 & 3\n        byte = uri_bytes[i : i + 1]\n        byte_ord = ord(byte)\n        if (is_percent_encoded and byte == b\"%\") or (\n            byte_ord < 128 and byte.decode() in allowed_chars\n        ):\n            encoded_component += byte\n            continue\n        encoded_component.extend(b\"%\" + (hex(byte_ord)[2:].encode().zfill(2).upper()))\n\n    return encoded_component.decode(encoding)\n\n\ndef _remove_path_dot_segments(path):\n    # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code\n    segments = path.split(\"/\")  # Turn the path into a list of segments\n    output = []  # Initialize the variable to use to store output\n\n    for segment in segments:\n        # '.' is the current directory, so ignore it, it is superfluous\n        if segment == \".\":\n            continue\n        # Anything other than '..', should be appended to the output\n        elif segment != \"..\":\n            output.append(segment)\n        # In this case segment == '..', if we can, we should pop the last\n        # element\n        elif output:\n            output.pop()\n\n    # If the path starts with '/' and the output is empty or the first string\n    # is non-empty\n    if path.startswith(\"/\") and (not output or output[0]):\n        output.insert(0, \"\")\n\n    # If the path starts with '/.' or '/..' ensure we add one more empty\n    # string to add a trailing '/'\n    if path.endswith((\"/.\", \"/..\")):\n        output.append(\"\")\n\n    return \"/\".join(output)\n\n\ndef _normalize_host(host, scheme):\n    if host:\n        if isinstance(host, six.binary_type):\n            host = six.ensure_str(host)\n\n        if scheme in NORMALIZABLE_SCHEMES:\n            is_ipv6 = IPV6_ADDRZ_RE.match(host)\n            if is_ipv6:\n                # IPv6 hosts of the form 'a::b%zone' are encoded in a URL as\n                # such per RFC 6874: 'a::b%25zone'. Unquote the ZoneID\n                # separator as necessary to return a valid RFC 4007 scoped IP.\n                match = ZONE_ID_RE.search(host)\n                if match:\n                    start, end = match.span(1)\n                    zone_id = host[start:end]\n\n                    if zone_id.startswith(\"%25\") and zone_id != \"%25\":\n                        zone_id = zone_id[3:]\n                    else:\n                        zone_id = zone_id[1:]\n                    zone_id = \"%\" + _encode_invalid_chars(zone_id, UNRESERVED_CHARS)\n                    return host[:start].lower() + zone_id + host[end:]\n                else:\n                    return host.lower()\n            elif not IPV4_RE.match(host):\n                return six.ensure_str(\n                    b\".\".join([_idna_encode(label) for label in host.split(\".\")])\n                )\n    return host\n\n\ndef _idna_encode(name):\n    if name and any([ord(x) > 128 for x in name]):\n        try:\n            from pip._vendor import idna\n        except ImportError:\n            six.raise_from(\n                LocationParseError(\"Unable to parse URL without the 'idna' module\"),\n                None,\n            )\n        try:\n            return idna.encode(name.lower(), strict=True, std3_rules=True)\n        except idna.IDNAError:\n            six.raise_from(\n                LocationParseError(u\"Name '%s' is not a valid IDNA label\" % name), None\n            )\n    return name.lower().encode(\"ascii\")\n\n\ndef _encode_target(target):\n    \"\"\"Percent-encodes a request target so that there are no invalid characters\"\"\"\n    path, query = TARGET_RE.match(target).groups()\n    target = _encode_invalid_chars(path, PATH_CHARS)\n    query = _encode_invalid_chars(query, QUERY_CHARS)\n    if query is not None:\n        target += \"?\" + query\n    return target\n\n\ndef parse_url(url):\n    \"\"\"\n    Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is\n    performed to parse incomplete urls. Fields not provided will be None.\n    This parser is RFC 3986 and RFC 6874 compliant.\n\n    The parser logic and helper functions are based heavily on\n    work done in the ``rfc3986`` module.\n\n    :param str url: URL to parse into a :class:`.Url` namedtuple.\n\n    Partly backwards-compatible with :mod:`urlparse`.\n\n    Example::\n\n        >>> parse_url('http://google.com/mail/')\n        Url(scheme='http', host='google.com', port=None, path='/mail/', ...)\n        >>> parse_url('google.com:80')\n        Url(scheme=None, host='google.com', port=80, path=None, ...)\n        >>> parse_url('/foo?bar')\n        Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)\n    \"\"\"\n    if not url:\n        # Empty\n        return Url()\n\n    source_url = url\n    if not SCHEME_RE.search(url):\n        url = \"//\" + url\n\n    try:\n        scheme, authority, path, query, fragment = URI_RE.match(url).groups()\n        normalize_uri = scheme is None or scheme.lower() in NORMALIZABLE_SCHEMES\n\n        if scheme:\n            scheme = scheme.lower()\n\n        if authority:\n            auth, _, host_port = authority.rpartition(\"@\")\n            auth = auth or None\n            host, port = _HOST_PORT_RE.match(host_port).groups()\n            if auth and normalize_uri:\n                auth = _encode_invalid_chars(auth, USERINFO_CHARS)\n            if port == \"\":\n                port = None\n        else:\n            auth, host, port = None, None, None\n\n        if port is not None:\n            port = int(port)\n            if not (0 <= port <= 65535):\n                raise LocationParseError(url)\n\n        host = _normalize_host(host, scheme)\n\n        if normalize_uri and path:\n            path = _remove_path_dot_segments(path)\n            path = _encode_invalid_chars(path, PATH_CHARS)\n        if normalize_uri and query:\n            query = _encode_invalid_chars(query, QUERY_CHARS)\n        if normalize_uri and fragment:\n            fragment = _encode_invalid_chars(fragment, FRAGMENT_CHARS)\n\n    except (ValueError, AttributeError):\n        return six.raise_from(LocationParseError(source_url), None)\n\n    # For the sake of backwards compatibility we put empty\n    # string values for path if there are any defined values\n    # beyond the path in the URL.\n    # TODO: Remove this when we break backwards compatibility.\n    if not path:\n        if query is not None or fragment is not None:\n            path = \"\"\n        else:\n            path = None\n\n    # Ensure that each part of the URL is a `str` for\n    # backwards compatibility.\n    if isinstance(url, six.text_type):\n        ensure_func = six.ensure_text\n    else:\n        ensure_func = six.ensure_str\n\n    def ensure_type(x):\n        return x if x is None else ensure_func(x)\n\n    return Url(\n        scheme=ensure_type(scheme),\n        auth=ensure_type(auth),\n        host=ensure_type(host),\n        port=port,\n        path=ensure_type(path),\n        query=ensure_type(query),\n        fragment=ensure_type(fragment),\n    )\n\n\ndef get_host(url):\n    \"\"\"\n    Deprecated. Use :func:`parse_url` instead.\n    \"\"\"\n    p = parse_url(url)\n    return p.scheme or \"http\", p.hostname, p.port\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/urllib3/util/wait.py",
    "content": "import errno\nimport select\nimport sys\nfrom functools import partial\n\ntry:\n    from time import monotonic\nexcept ImportError:\n    from time import time as monotonic\n\n__all__ = [\"NoWayToWaitForSocketError\", \"wait_for_read\", \"wait_for_write\"]\n\n\nclass NoWayToWaitForSocketError(Exception):\n    pass\n\n\n# How should we wait on sockets?\n#\n# There are two types of APIs you can use for waiting on sockets: the fancy\n# modern stateful APIs like epoll/kqueue, and the older stateless APIs like\n# select/poll. The stateful APIs are more efficient when you have a lots of\n# sockets to keep track of, because you can set them up once and then use them\n# lots of times. But we only ever want to wait on a single socket at a time\n# and don't want to keep track of state, so the stateless APIs are actually\n# more efficient. So we want to use select() or poll().\n#\n# Now, how do we choose between select() and poll()? On traditional Unixes,\n# select() has a strange calling convention that makes it slow, or fail\n# altogether, for high-numbered file descriptors. The point of poll() is to fix\n# that, so on Unixes, we prefer poll().\n#\n# On Windows, there is no poll() (or at least Python doesn't provide a wrapper\n# for it), but that's OK, because on Windows, select() doesn't have this\n# strange calling convention; plain select() works fine.\n#\n# So: on Windows we use select(), and everywhere else we use poll(). We also\n# fall back to select() in case poll() is somehow broken or missing.\n\nif sys.version_info >= (3, 5):\n    # Modern Python, that retries syscalls by default\n    def _retry_on_intr(fn, timeout):\n        return fn(timeout)\n\nelse:\n    # Old and broken Pythons.\n    def _retry_on_intr(fn, timeout):\n        if timeout is None:\n            deadline = float(\"inf\")\n        else:\n            deadline = monotonic() + timeout\n\n        while True:\n            try:\n                return fn(timeout)\n            # OSError for 3 <= pyver < 3.5, select.error for pyver <= 2.7\n            except (OSError, select.error) as e:\n                # 'e.args[0]' incantation works for both OSError and select.error\n                if e.args[0] != errno.EINTR:\n                    raise\n                else:\n                    timeout = deadline - monotonic()\n                    if timeout < 0:\n                        timeout = 0\n                    if timeout == float(\"inf\"):\n                        timeout = None\n                    continue\n\n\ndef select_wait_for_socket(sock, read=False, write=False, timeout=None):\n    if not read and not write:\n        raise RuntimeError(\"must specify at least one of read=True, write=True\")\n    rcheck = []\n    wcheck = []\n    if read:\n        rcheck.append(sock)\n    if write:\n        wcheck.append(sock)\n    # When doing a non-blocking connect, most systems signal success by\n    # marking the socket writable. Windows, though, signals success by marked\n    # it as \"exceptional\". We paper over the difference by checking the write\n    # sockets for both conditions. (The stdlib selectors module does the same\n    # thing.)\n    fn = partial(select.select, rcheck, wcheck, wcheck)\n    rready, wready, xready = _retry_on_intr(fn, timeout)\n    return bool(rready or wready or xready)\n\n\ndef poll_wait_for_socket(sock, read=False, write=False, timeout=None):\n    if not read and not write:\n        raise RuntimeError(\"must specify at least one of read=True, write=True\")\n    mask = 0\n    if read:\n        mask |= select.POLLIN\n    if write:\n        mask |= select.POLLOUT\n    poll_obj = select.poll()\n    poll_obj.register(sock, mask)\n\n    # For some reason, poll() takes timeout in milliseconds\n    def do_poll(t):\n        if t is not None:\n            t *= 1000\n        return poll_obj.poll(t)\n\n    return bool(_retry_on_intr(do_poll, timeout))\n\n\ndef null_wait_for_socket(*args, **kwargs):\n    raise NoWayToWaitForSocketError(\"no select-equivalent available\")\n\n\ndef _have_working_poll():\n    # Apparently some systems have a select.poll that fails as soon as you try\n    # to use it, either due to strange configuration or broken monkeypatching\n    # from libraries like eventlet/greenlet.\n    try:\n        poll_obj = select.poll()\n        _retry_on_intr(poll_obj.poll, 0)\n    except (AttributeError, OSError):\n        return False\n    else:\n        return True\n\n\ndef wait_for_socket(*args, **kwargs):\n    # We delay choosing which implementation to use until the first time we're\n    # called. We could do it at import time, but then we might make the wrong\n    # decision if someone goes wild with monkeypatching select.poll after\n    # we're imported.\n    global wait_for_socket\n    if _have_working_poll():\n        wait_for_socket = poll_wait_for_socket\n    elif hasattr(select, \"select\"):\n        wait_for_socket = select_wait_for_socket\n    else:  # Platform-specific: Appengine.\n        wait_for_socket = null_wait_for_socket\n    return wait_for_socket(*args, **kwargs)\n\n\ndef wait_for_read(sock, timeout=None):\n    \"\"\"Waits for reading to be available on a given socket.\n    Returns True if the socket is readable, or False if the timeout expired.\n    \"\"\"\n    return wait_for_socket(sock, read=True, timeout=timeout)\n\n\ndef wait_for_write(sock, timeout=None):\n    \"\"\"Waits for writing to be available on a given socket.\n    Returns True if the socket is readable, or False if the timeout expired.\n    \"\"\"\n    return wait_for_socket(sock, write=True, timeout=timeout)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/vendor.txt",
    "content": "CacheControl==0.12.11  # Make sure to update the license in pyproject.toml for this.\ncolorama==0.4.5\ndistlib==0.3.6\ndistro==1.7.0\nmsgpack==1.0.4\npackaging==21.3\npep517==0.13.0\nplatformdirs==2.5.2\npyparsing==3.0.9\nrequests==2.28.1\n    certifi==2022.09.24\n    chardet==5.0.0\n    idna==3.4\n    urllib3==1.26.12\nrich==12.5.1\n    pygments==2.13.0\n    typing_extensions==4.4.0\nresolvelib==0.8.1\nsetuptools==44.0.0\nsix==1.16.0\ntenacity==8.1.0\ntomli==2.0.1\nwebencodings==0.5.1\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/webencodings/__init__.py",
    "content": "# coding: utf-8\n\"\"\"\n\n    webencodings\n    ~~~~~~~~~~~~\n\n    This is a Python implementation of the `WHATWG Encoding standard\n    <http://encoding.spec.whatwg.org/>`. See README for details.\n\n    :copyright: Copyright 2012 by Simon Sapin\n    :license: BSD, see LICENSE for details.\n\n\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport codecs\n\nfrom .labels import LABELS\n\n\nVERSION = '0.5.1'\n\n\n# Some names in Encoding are not valid Python aliases. Remap these.\nPYTHON_NAMES = {\n    'iso-8859-8-i': 'iso-8859-8',\n    'x-mac-cyrillic': 'mac-cyrillic',\n    'macintosh': 'mac-roman',\n    'windows-874': 'cp874'}\n\nCACHE = {}\n\n\ndef ascii_lower(string):\n    r\"\"\"Transform (only) ASCII letters to lower case: A-Z is mapped to a-z.\n\n    :param string: An Unicode string.\n    :returns: A new Unicode string.\n\n    This is used for `ASCII case-insensitive\n    <http://encoding.spec.whatwg.org/#ascii-case-insensitive>`_\n    matching of encoding labels.\n    The same matching is also used, among other things,\n    for `CSS keywords <http://dev.w3.org/csswg/css-values/#keywords>`_.\n\n    This is different from the :meth:`~py:str.lower` method of Unicode strings\n    which also affect non-ASCII characters,\n    sometimes mapping them into the ASCII range:\n\n        >>> keyword = u'Bac\\N{KELVIN SIGN}ground'\n        >>> assert keyword.lower() == u'background'\n        >>> assert ascii_lower(keyword) != keyword.lower()\n        >>> assert ascii_lower(keyword) == u'bac\\N{KELVIN SIGN}ground'\n\n    \"\"\"\n    # This turns out to be faster than unicode.translate()\n    return string.encode('utf8').lower().decode('utf8')\n\n\ndef lookup(label):\n    \"\"\"\n    Look for an encoding by its label.\n    This is the spec’s `get an encoding\n    <http://encoding.spec.whatwg.org/#concept-encoding-get>`_ algorithm.\n    Supported labels are listed there.\n\n    :param label: A string.\n    :returns:\n        An :class:`Encoding` object, or :obj:`None` for an unknown label.\n\n    \"\"\"\n    # Only strip ASCII whitespace: U+0009, U+000A, U+000C, U+000D, and U+0020.\n    label = ascii_lower(label.strip('\\t\\n\\f\\r '))\n    name = LABELS.get(label)\n    if name is None:\n        return None\n    encoding = CACHE.get(name)\n    if encoding is None:\n        if name == 'x-user-defined':\n            from .x_user_defined import codec_info\n        else:\n            python_name = PYTHON_NAMES.get(name, name)\n            # Any python_name value that gets to here should be valid.\n            codec_info = codecs.lookup(python_name)\n        encoding = Encoding(name, codec_info)\n        CACHE[name] = encoding\n    return encoding\n\n\ndef _get_encoding(encoding_or_label):\n    \"\"\"\n    Accept either an encoding object or label.\n\n    :param encoding: An :class:`Encoding` object or a label string.\n    :returns: An :class:`Encoding` object.\n    :raises: :exc:`~exceptions.LookupError` for an unknown label.\n\n    \"\"\"\n    if hasattr(encoding_or_label, 'codec_info'):\n        return encoding_or_label\n\n    encoding = lookup(encoding_or_label)\n    if encoding is None:\n        raise LookupError('Unknown encoding label: %r' % encoding_or_label)\n    return encoding\n\n\nclass Encoding(object):\n    \"\"\"Reresents a character encoding such as UTF-8,\n    that can be used for decoding or encoding.\n\n    .. attribute:: name\n\n        Canonical name of the encoding\n\n    .. attribute:: codec_info\n\n        The actual implementation of the encoding,\n        a stdlib :class:`~codecs.CodecInfo` object.\n        See :func:`codecs.register`.\n\n    \"\"\"\n    def __init__(self, name, codec_info):\n        self.name = name\n        self.codec_info = codec_info\n\n    def __repr__(self):\n        return '<Encoding %s>' % self.name\n\n\n#: The UTF-8 encoding. Should be used for new content and formats.\nUTF8 = lookup('utf-8')\n\n_UTF16LE = lookup('utf-16le')\n_UTF16BE = lookup('utf-16be')\n\n\ndef decode(input, fallback_encoding, errors='replace'):\n    \"\"\"\n    Decode a single string.\n\n    :param input: A byte string\n    :param fallback_encoding:\n        An :class:`Encoding` object or a label string.\n        The encoding to use if :obj:`input` does note have a BOM.\n    :param errors: Type of error handling. See :func:`codecs.register`.\n    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.\n    :return:\n        A ``(output, encoding)`` tuple of an Unicode string\n        and an :obj:`Encoding`.\n\n    \"\"\"\n    # Fail early if `encoding` is an invalid label.\n    fallback_encoding = _get_encoding(fallback_encoding)\n    bom_encoding, input = _detect_bom(input)\n    encoding = bom_encoding or fallback_encoding\n    return encoding.codec_info.decode(input, errors)[0], encoding\n\n\ndef _detect_bom(input):\n    \"\"\"Return (bom_encoding, input), with any BOM removed from the input.\"\"\"\n    if input.startswith(b'\\xFF\\xFE'):\n        return _UTF16LE, input[2:]\n    if input.startswith(b'\\xFE\\xFF'):\n        return _UTF16BE, input[2:]\n    if input.startswith(b'\\xEF\\xBB\\xBF'):\n        return UTF8, input[3:]\n    return None, input\n\n\ndef encode(input, encoding=UTF8, errors='strict'):\n    \"\"\"\n    Encode a single string.\n\n    :param input: An Unicode string.\n    :param encoding: An :class:`Encoding` object or a label string.\n    :param errors: Type of error handling. See :func:`codecs.register`.\n    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.\n    :return: A byte string.\n\n    \"\"\"\n    return _get_encoding(encoding).codec_info.encode(input, errors)[0]\n\n\ndef iter_decode(input, fallback_encoding, errors='replace'):\n    \"\"\"\n    \"Pull\"-based decoder.\n\n    :param input:\n        An iterable of byte strings.\n\n        The input is first consumed just enough to determine the encoding\n        based on the precense of a BOM,\n        then consumed on demand when the return value is.\n    :param fallback_encoding:\n        An :class:`Encoding` object or a label string.\n        The encoding to use if :obj:`input` does note have a BOM.\n    :param errors: Type of error handling. See :func:`codecs.register`.\n    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.\n    :returns:\n        An ``(output, encoding)`` tuple.\n        :obj:`output` is an iterable of Unicode strings,\n        :obj:`encoding` is the :obj:`Encoding` that is being used.\n\n    \"\"\"\n\n    decoder = IncrementalDecoder(fallback_encoding, errors)\n    generator = _iter_decode_generator(input, decoder)\n    encoding = next(generator)\n    return generator, encoding\n\n\ndef _iter_decode_generator(input, decoder):\n    \"\"\"Return a generator that first yields the :obj:`Encoding`,\n    then yields output chukns as Unicode strings.\n\n    \"\"\"\n    decode = decoder.decode\n    input = iter(input)\n    for chunck in input:\n        output = decode(chunck)\n        if output:\n            assert decoder.encoding is not None\n            yield decoder.encoding\n            yield output\n            break\n    else:\n        # Input exhausted without determining the encoding\n        output = decode(b'', final=True)\n        assert decoder.encoding is not None\n        yield decoder.encoding\n        if output:\n            yield output\n        return\n\n    for chunck in input:\n        output = decode(chunck)\n        if output:\n            yield output\n    output = decode(b'', final=True)\n    if output:\n        yield output\n\n\ndef iter_encode(input, encoding=UTF8, errors='strict'):\n    \"\"\"\n    “Pull”-based encoder.\n\n    :param input: An iterable of Unicode strings.\n    :param encoding: An :class:`Encoding` object or a label string.\n    :param errors: Type of error handling. See :func:`codecs.register`.\n    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.\n    :returns: An iterable of byte strings.\n\n    \"\"\"\n    # Fail early if `encoding` is an invalid label.\n    encode = IncrementalEncoder(encoding, errors).encode\n    return _iter_encode_generator(input, encode)\n\n\ndef _iter_encode_generator(input, encode):\n    for chunck in input:\n        output = encode(chunck)\n        if output:\n            yield output\n    output = encode('', final=True)\n    if output:\n        yield output\n\n\nclass IncrementalDecoder(object):\n    \"\"\"\n    “Push”-based decoder.\n\n    :param fallback_encoding:\n        An :class:`Encoding` object or a label string.\n        The encoding to use if :obj:`input` does note have a BOM.\n    :param errors: Type of error handling. See :func:`codecs.register`.\n    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.\n\n    \"\"\"\n    def __init__(self, fallback_encoding, errors='replace'):\n        # Fail early if `encoding` is an invalid label.\n        self._fallback_encoding = _get_encoding(fallback_encoding)\n        self._errors = errors\n        self._buffer = b''\n        self._decoder = None\n        #: The actual :class:`Encoding` that is being used,\n        #: or :obj:`None` if that is not determined yet.\n        #: (Ie. if there is not enough input yet to determine\n        #: if there is a BOM.)\n        self.encoding = None  # Not known yet.\n\n    def decode(self, input, final=False):\n        \"\"\"Decode one chunk of the input.\n\n        :param input: A byte string.\n        :param final:\n            Indicate that no more input is available.\n            Must be :obj:`True` if this is the last call.\n        :returns: An Unicode string.\n\n        \"\"\"\n        decoder = self._decoder\n        if decoder is not None:\n            return decoder(input, final)\n\n        input = self._buffer + input\n        encoding, input = _detect_bom(input)\n        if encoding is None:\n            if len(input) < 3 and not final:  # Not enough data yet.\n                self._buffer = input\n                return ''\n            else:  # No BOM\n                encoding = self._fallback_encoding\n        decoder = encoding.codec_info.incrementaldecoder(self._errors).decode\n        self._decoder = decoder\n        self.encoding = encoding\n        return decoder(input, final)\n\n\nclass IncrementalEncoder(object):\n    \"\"\"\n    “Push”-based encoder.\n\n    :param encoding: An :class:`Encoding` object or a label string.\n    :param errors: Type of error handling. See :func:`codecs.register`.\n    :raises: :exc:`~exceptions.LookupError` for an unknown encoding label.\n\n    .. method:: encode(input, final=False)\n\n        :param input: An Unicode string.\n        :param final:\n            Indicate that no more input is available.\n            Must be :obj:`True` if this is the last call.\n        :returns: A byte string.\n\n    \"\"\"\n    def __init__(self, encoding=UTF8, errors='strict'):\n        encoding = _get_encoding(encoding)\n        self.encode = encoding.codec_info.incrementalencoder(errors).encode\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/webencodings/labels.py",
    "content": "\"\"\"\n\n    webencodings.labels\n    ~~~~~~~~~~~~~~~~~~~\n\n    Map encoding labels to their name.\n\n    :copyright: Copyright 2012 by Simon Sapin\n    :license: BSD, see LICENSE for details.\n\n\"\"\"\n\n# XXX Do not edit!\n# This file is automatically generated by mklabels.py\n\nLABELS = {\n    'unicode-1-1-utf-8':   'utf-8',\n    'utf-8':               'utf-8',\n    'utf8':                'utf-8',\n    '866':                 'ibm866',\n    'cp866':               'ibm866',\n    'csibm866':            'ibm866',\n    'ibm866':              'ibm866',\n    'csisolatin2':         'iso-8859-2',\n    'iso-8859-2':          'iso-8859-2',\n    'iso-ir-101':          'iso-8859-2',\n    'iso8859-2':           'iso-8859-2',\n    'iso88592':            'iso-8859-2',\n    'iso_8859-2':          'iso-8859-2',\n    'iso_8859-2:1987':     'iso-8859-2',\n    'l2':                  'iso-8859-2',\n    'latin2':              'iso-8859-2',\n    'csisolatin3':         'iso-8859-3',\n    'iso-8859-3':          'iso-8859-3',\n    'iso-ir-109':          'iso-8859-3',\n    'iso8859-3':           'iso-8859-3',\n    'iso88593':            'iso-8859-3',\n    'iso_8859-3':          'iso-8859-3',\n    'iso_8859-3:1988':     'iso-8859-3',\n    'l3':                  'iso-8859-3',\n    'latin3':              'iso-8859-3',\n    'csisolatin4':         'iso-8859-4',\n    'iso-8859-4':          'iso-8859-4',\n    'iso-ir-110':          'iso-8859-4',\n    'iso8859-4':           'iso-8859-4',\n    'iso88594':            'iso-8859-4',\n    'iso_8859-4':          'iso-8859-4',\n    'iso_8859-4:1988':     'iso-8859-4',\n    'l4':                  'iso-8859-4',\n    'latin4':              'iso-8859-4',\n    'csisolatincyrillic':  'iso-8859-5',\n    'cyrillic':            'iso-8859-5',\n    'iso-8859-5':          'iso-8859-5',\n    'iso-ir-144':          'iso-8859-5',\n    'iso8859-5':           'iso-8859-5',\n    'iso88595':            'iso-8859-5',\n    'iso_8859-5':          'iso-8859-5',\n    'iso_8859-5:1988':     'iso-8859-5',\n    'arabic':              'iso-8859-6',\n    'asmo-708':            'iso-8859-6',\n    'csiso88596e':         'iso-8859-6',\n    'csiso88596i':         'iso-8859-6',\n    'csisolatinarabic':    'iso-8859-6',\n    'ecma-114':            'iso-8859-6',\n    'iso-8859-6':          'iso-8859-6',\n    'iso-8859-6-e':        'iso-8859-6',\n    'iso-8859-6-i':        'iso-8859-6',\n    'iso-ir-127':          'iso-8859-6',\n    'iso8859-6':           'iso-8859-6',\n    'iso88596':            'iso-8859-6',\n    'iso_8859-6':          'iso-8859-6',\n    'iso_8859-6:1987':     'iso-8859-6',\n    'csisolatingreek':     'iso-8859-7',\n    'ecma-118':            'iso-8859-7',\n    'elot_928':            'iso-8859-7',\n    'greek':               'iso-8859-7',\n    'greek8':              'iso-8859-7',\n    'iso-8859-7':          'iso-8859-7',\n    'iso-ir-126':          'iso-8859-7',\n    'iso8859-7':           'iso-8859-7',\n    'iso88597':            'iso-8859-7',\n    'iso_8859-7':          'iso-8859-7',\n    'iso_8859-7:1987':     'iso-8859-7',\n    'sun_eu_greek':        'iso-8859-7',\n    'csiso88598e':         'iso-8859-8',\n    'csisolatinhebrew':    'iso-8859-8',\n    'hebrew':              'iso-8859-8',\n    'iso-8859-8':          'iso-8859-8',\n    'iso-8859-8-e':        'iso-8859-8',\n    'iso-ir-138':          'iso-8859-8',\n    'iso8859-8':           'iso-8859-8',\n    'iso88598':            'iso-8859-8',\n    'iso_8859-8':          'iso-8859-8',\n    'iso_8859-8:1988':     'iso-8859-8',\n    'visual':              'iso-8859-8',\n    'csiso88598i':         'iso-8859-8-i',\n    'iso-8859-8-i':        'iso-8859-8-i',\n    'logical':             'iso-8859-8-i',\n    'csisolatin6':         'iso-8859-10',\n    'iso-8859-10':         'iso-8859-10',\n    'iso-ir-157':          'iso-8859-10',\n    'iso8859-10':          'iso-8859-10',\n    'iso885910':           'iso-8859-10',\n    'l6':                  'iso-8859-10',\n    'latin6':              'iso-8859-10',\n    'iso-8859-13':         'iso-8859-13',\n    'iso8859-13':          'iso-8859-13',\n    'iso885913':           'iso-8859-13',\n    'iso-8859-14':         'iso-8859-14',\n    'iso8859-14':          'iso-8859-14',\n    'iso885914':           'iso-8859-14',\n    'csisolatin9':         'iso-8859-15',\n    'iso-8859-15':         'iso-8859-15',\n    'iso8859-15':          'iso-8859-15',\n    'iso885915':           'iso-8859-15',\n    'iso_8859-15':         'iso-8859-15',\n    'l9':                  'iso-8859-15',\n    'iso-8859-16':         'iso-8859-16',\n    'cskoi8r':             'koi8-r',\n    'koi':                 'koi8-r',\n    'koi8':                'koi8-r',\n    'koi8-r':              'koi8-r',\n    'koi8_r':              'koi8-r',\n    'koi8-u':              'koi8-u',\n    'csmacintosh':         'macintosh',\n    'mac':                 'macintosh',\n    'macintosh':           'macintosh',\n    'x-mac-roman':         'macintosh',\n    'dos-874':             'windows-874',\n    'iso-8859-11':         'windows-874',\n    'iso8859-11':          'windows-874',\n    'iso885911':           'windows-874',\n    'tis-620':             'windows-874',\n    'windows-874':         'windows-874',\n    'cp1250':              'windows-1250',\n    'windows-1250':        'windows-1250',\n    'x-cp1250':            'windows-1250',\n    'cp1251':              'windows-1251',\n    'windows-1251':        'windows-1251',\n    'x-cp1251':            'windows-1251',\n    'ansi_x3.4-1968':      'windows-1252',\n    'ascii':               'windows-1252',\n    'cp1252':              'windows-1252',\n    'cp819':               'windows-1252',\n    'csisolatin1':         'windows-1252',\n    'ibm819':              'windows-1252',\n    'iso-8859-1':          'windows-1252',\n    'iso-ir-100':          'windows-1252',\n    'iso8859-1':           'windows-1252',\n    'iso88591':            'windows-1252',\n    'iso_8859-1':          'windows-1252',\n    'iso_8859-1:1987':     'windows-1252',\n    'l1':                  'windows-1252',\n    'latin1':              'windows-1252',\n    'us-ascii':            'windows-1252',\n    'windows-1252':        'windows-1252',\n    'x-cp1252':            'windows-1252',\n    'cp1253':              'windows-1253',\n    'windows-1253':        'windows-1253',\n    'x-cp1253':            'windows-1253',\n    'cp1254':              'windows-1254',\n    'csisolatin5':         'windows-1254',\n    'iso-8859-9':          'windows-1254',\n    'iso-ir-148':          'windows-1254',\n    'iso8859-9':           'windows-1254',\n    'iso88599':            'windows-1254',\n    'iso_8859-9':          'windows-1254',\n    'iso_8859-9:1989':     'windows-1254',\n    'l5':                  'windows-1254',\n    'latin5':              'windows-1254',\n    'windows-1254':        'windows-1254',\n    'x-cp1254':            'windows-1254',\n    'cp1255':              'windows-1255',\n    'windows-1255':        'windows-1255',\n    'x-cp1255':            'windows-1255',\n    'cp1256':              'windows-1256',\n    'windows-1256':        'windows-1256',\n    'x-cp1256':            'windows-1256',\n    'cp1257':              'windows-1257',\n    'windows-1257':        'windows-1257',\n    'x-cp1257':            'windows-1257',\n    'cp1258':              'windows-1258',\n    'windows-1258':        'windows-1258',\n    'x-cp1258':            'windows-1258',\n    'x-mac-cyrillic':      'x-mac-cyrillic',\n    'x-mac-ukrainian':     'x-mac-cyrillic',\n    'chinese':             'gbk',\n    'csgb2312':            'gbk',\n    'csiso58gb231280':     'gbk',\n    'gb2312':              'gbk',\n    'gb_2312':             'gbk',\n    'gb_2312-80':          'gbk',\n    'gbk':                 'gbk',\n    'iso-ir-58':           'gbk',\n    'x-gbk':               'gbk',\n    'gb18030':             'gb18030',\n    'hz-gb-2312':          'hz-gb-2312',\n    'big5':                'big5',\n    'big5-hkscs':          'big5',\n    'cn-big5':             'big5',\n    'csbig5':              'big5',\n    'x-x-big5':            'big5',\n    'cseucpkdfmtjapanese': 'euc-jp',\n    'euc-jp':              'euc-jp',\n    'x-euc-jp':            'euc-jp',\n    'csiso2022jp':         'iso-2022-jp',\n    'iso-2022-jp':         'iso-2022-jp',\n    'csshiftjis':          'shift_jis',\n    'ms_kanji':            'shift_jis',\n    'shift-jis':           'shift_jis',\n    'shift_jis':           'shift_jis',\n    'sjis':                'shift_jis',\n    'windows-31j':         'shift_jis',\n    'x-sjis':              'shift_jis',\n    'cseuckr':             'euc-kr',\n    'csksc56011987':       'euc-kr',\n    'euc-kr':              'euc-kr',\n    'iso-ir-149':          'euc-kr',\n    'korean':              'euc-kr',\n    'ks_c_5601-1987':      'euc-kr',\n    'ks_c_5601-1989':      'euc-kr',\n    'ksc5601':             'euc-kr',\n    'ksc_5601':            'euc-kr',\n    'windows-949':         'euc-kr',\n    'csiso2022kr':         'iso-2022-kr',\n    'iso-2022-kr':         'iso-2022-kr',\n    'utf-16be':            'utf-16be',\n    'utf-16':              'utf-16le',\n    'utf-16le':            'utf-16le',\n    'x-user-defined':      'x-user-defined',\n}\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/webencodings/mklabels.py",
    "content": "\"\"\"\n\n    webencodings.mklabels\n    ~~~~~~~~~~~~~~~~~~~~~\n\n    Regenarate the webencodings.labels module.\n\n    :copyright: Copyright 2012 by Simon Sapin\n    :license: BSD, see LICENSE for details.\n\n\"\"\"\n\nimport json\ntry:\n    from urllib import urlopen\nexcept ImportError:\n    from urllib.request import urlopen\n\n\ndef assert_lower(string):\n    assert string == string.lower()\n    return string\n\n\ndef generate(url):\n    parts = ['''\\\n\"\"\"\n\n    webencodings.labels\n    ~~~~~~~~~~~~~~~~~~~\n\n    Map encoding labels to their name.\n\n    :copyright: Copyright 2012 by Simon Sapin\n    :license: BSD, see LICENSE for details.\n\n\"\"\"\n\n# XXX Do not edit!\n# This file is automatically generated by mklabels.py\n\nLABELS = {\n''']\n    labels = [\n        (repr(assert_lower(label)).lstrip('u'),\n         repr(encoding['name']).lstrip('u'))\n        for category in json.loads(urlopen(url).read().decode('ascii'))\n        for encoding in category['encodings']\n        for label in encoding['labels']]\n    max_len = max(len(label) for label, name in labels)\n    parts.extend(\n        '    %s:%s %s,\\n' % (label, ' ' * (max_len - len(label)), name)\n        for label, name in labels)\n    parts.append('}')\n    return ''.join(parts)\n\n\nif __name__ == '__main__':\n    print(generate('http://encoding.spec.whatwg.org/encodings.json'))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/webencodings/tests.py",
    "content": "# coding: utf-8\n\"\"\"\n\n    webencodings.tests\n    ~~~~~~~~~~~~~~~~~~\n\n    A basic test suite for Encoding.\n\n    :copyright: Copyright 2012 by Simon Sapin\n    :license: BSD, see LICENSE for details.\n\n\"\"\"\n\nfrom __future__ import unicode_literals\n\nfrom . import (lookup, LABELS, decode, encode, iter_decode, iter_encode,\n               IncrementalDecoder, IncrementalEncoder, UTF8)\n\n\ndef assert_raises(exception, function, *args, **kwargs):\n    try:\n        function(*args, **kwargs)\n    except exception:\n        return\n    else:  # pragma: no cover\n        raise AssertionError('Did not raise %s.' % exception)\n\n\ndef test_labels():\n    assert lookup('utf-8').name == 'utf-8'\n    assert lookup('Utf-8').name == 'utf-8'\n    assert lookup('UTF-8').name == 'utf-8'\n    assert lookup('utf8').name == 'utf-8'\n    assert lookup('utf8').name == 'utf-8'\n    assert lookup('utf8 ').name == 'utf-8'\n    assert lookup(' \\r\\nutf8\\t').name == 'utf-8'\n    assert lookup('u8') is None  # Python label.\n    assert lookup('utf-8 ') is None  # Non-ASCII white space.\n\n    assert lookup('US-ASCII').name == 'windows-1252'\n    assert lookup('iso-8859-1').name == 'windows-1252'\n    assert lookup('latin1').name == 'windows-1252'\n    assert lookup('LATIN1').name == 'windows-1252'\n    assert lookup('latin-1') is None\n    assert lookup('LATİN1') is None  # ASCII-only case insensitivity.\n\n\ndef test_all_labels():\n    for label in LABELS:\n        assert decode(b'', label) == ('', lookup(label))\n        assert encode('', label) == b''\n        for repeat in [0, 1, 12]:\n            output, _ = iter_decode([b''] * repeat, label)\n            assert list(output) == []\n            assert list(iter_encode([''] * repeat, label)) == []\n        decoder = IncrementalDecoder(label)\n        assert decoder.decode(b'') == ''\n        assert decoder.decode(b'', final=True) == ''\n        encoder = IncrementalEncoder(label)\n        assert encoder.encode('') == b''\n        assert encoder.encode('', final=True) == b''\n    # All encoding names are valid labels too:\n    for name in set(LABELS.values()):\n        assert lookup(name).name == name\n\n\ndef test_invalid_label():\n    assert_raises(LookupError, decode, b'\\xEF\\xBB\\xBF\\xc3\\xa9', 'invalid')\n    assert_raises(LookupError, encode, 'é', 'invalid')\n    assert_raises(LookupError, iter_decode, [], 'invalid')\n    assert_raises(LookupError, iter_encode, [], 'invalid')\n    assert_raises(LookupError, IncrementalDecoder, 'invalid')\n    assert_raises(LookupError, IncrementalEncoder, 'invalid')\n\n\ndef test_decode():\n    assert decode(b'\\x80', 'latin1') == ('€', lookup('latin1'))\n    assert decode(b'\\x80', lookup('latin1')) == ('€', lookup('latin1'))\n    assert decode(b'\\xc3\\xa9', 'utf8') == ('é', lookup('utf8'))\n    assert decode(b'\\xc3\\xa9', UTF8) == ('é', lookup('utf8'))\n    assert decode(b'\\xc3\\xa9', 'ascii') == ('Ã©', lookup('ascii'))\n    assert decode(b'\\xEF\\xBB\\xBF\\xc3\\xa9', 'ascii') == ('é', lookup('utf8'))  # UTF-8 with BOM\n\n    assert decode(b'\\xFE\\xFF\\x00\\xe9', 'ascii') == ('é', lookup('utf-16be'))  # UTF-16-BE with BOM\n    assert decode(b'\\xFF\\xFE\\xe9\\x00', 'ascii') == ('é', lookup('utf-16le'))  # UTF-16-LE with BOM\n    assert decode(b'\\xFE\\xFF\\xe9\\x00', 'ascii') == ('\\ue900', lookup('utf-16be'))\n    assert decode(b'\\xFF\\xFE\\x00\\xe9', 'ascii') == ('\\ue900', lookup('utf-16le'))\n\n    assert decode(b'\\x00\\xe9', 'UTF-16BE') == ('é', lookup('utf-16be'))\n    assert decode(b'\\xe9\\x00', 'UTF-16LE') == ('é', lookup('utf-16le'))\n    assert decode(b'\\xe9\\x00', 'UTF-16') == ('é', lookup('utf-16le'))\n\n    assert decode(b'\\xe9\\x00', 'UTF-16BE') == ('\\ue900', lookup('utf-16be'))\n    assert decode(b'\\x00\\xe9', 'UTF-16LE') == ('\\ue900', lookup('utf-16le'))\n    assert decode(b'\\x00\\xe9', 'UTF-16') == ('\\ue900', lookup('utf-16le'))\n\n\ndef test_encode():\n    assert encode('é', 'latin1') == b'\\xe9'\n    assert encode('é', 'utf8') == b'\\xc3\\xa9'\n    assert encode('é', 'utf8') == b'\\xc3\\xa9'\n    assert encode('é', 'utf-16') == b'\\xe9\\x00'\n    assert encode('é', 'utf-16le') == b'\\xe9\\x00'\n    assert encode('é', 'utf-16be') == b'\\x00\\xe9'\n\n\ndef test_iter_decode():\n    def iter_decode_to_string(input, fallback_encoding):\n        output, _encoding = iter_decode(input, fallback_encoding)\n        return ''.join(output)\n    assert iter_decode_to_string([], 'latin1') == ''\n    assert iter_decode_to_string([b''], 'latin1') == ''\n    assert iter_decode_to_string([b'\\xe9'], 'latin1') == 'é'\n    assert iter_decode_to_string([b'hello'], 'latin1') == 'hello'\n    assert iter_decode_to_string([b'he', b'llo'], 'latin1') == 'hello'\n    assert iter_decode_to_string([b'hell', b'o'], 'latin1') == 'hello'\n    assert iter_decode_to_string([b'\\xc3\\xa9'], 'latin1') == 'Ã©'\n    assert iter_decode_to_string([b'\\xEF\\xBB\\xBF\\xc3\\xa9'], 'latin1') == 'é'\n    assert iter_decode_to_string([\n        b'\\xEF\\xBB\\xBF', b'\\xc3', b'\\xa9'], 'latin1') == 'é'\n    assert iter_decode_to_string([\n        b'\\xEF\\xBB\\xBF', b'a', b'\\xc3'], 'latin1') == 'a\\uFFFD'\n    assert iter_decode_to_string([\n        b'', b'\\xEF', b'', b'', b'\\xBB\\xBF\\xc3', b'\\xa9'], 'latin1') == 'é'\n    assert iter_decode_to_string([b'\\xEF\\xBB\\xBF'], 'latin1') == ''\n    assert iter_decode_to_string([b'\\xEF\\xBB'], 'latin1') == 'ï»'\n    assert iter_decode_to_string([b'\\xFE\\xFF\\x00\\xe9'], 'latin1') == 'é'\n    assert iter_decode_to_string([b'\\xFF\\xFE\\xe9\\x00'], 'latin1') == 'é'\n    assert iter_decode_to_string([\n        b'', b'\\xFF', b'', b'', b'\\xFE\\xe9', b'\\x00'], 'latin1') == 'é'\n    assert iter_decode_to_string([\n        b'', b'h\\xe9', b'llo'], 'x-user-defined') == 'h\\uF7E9llo'\n\n\ndef test_iter_encode():\n    assert b''.join(iter_encode([], 'latin1')) == b''\n    assert b''.join(iter_encode([''], 'latin1')) == b''\n    assert b''.join(iter_encode(['é'], 'latin1')) == b'\\xe9'\n    assert b''.join(iter_encode(['', 'é', '', ''], 'latin1')) == b'\\xe9'\n    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16')) == b'\\xe9\\x00'\n    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16le')) == b'\\xe9\\x00'\n    assert b''.join(iter_encode(['', 'é', '', ''], 'utf-16be')) == b'\\x00\\xe9'\n    assert b''.join(iter_encode([\n        '', 'h\\uF7E9', '', 'llo'], 'x-user-defined')) == b'h\\xe9llo'\n\n\ndef test_x_user_defined():\n    encoded = b'2,\\x0c\\x0b\\x1aO\\xd9#\\xcb\\x0f\\xc9\\xbbt\\xcf\\xa8\\xca'\n    decoded = '2,\\x0c\\x0b\\x1aO\\uf7d9#\\uf7cb\\x0f\\uf7c9\\uf7bbt\\uf7cf\\uf7a8\\uf7ca'\n    encoded = b'aa'\n    decoded = 'aa'\n    assert decode(encoded, 'x-user-defined') == (decoded, lookup('x-user-defined'))\n    assert encode(decoded, 'x-user-defined') == encoded\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/_vendor/webencodings/x_user_defined.py",
    "content": "# coding: utf-8\n\"\"\"\n\n    webencodings.x_user_defined\n    ~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n    An implementation of the x-user-defined encoding.\n\n    :copyright: Copyright 2012 by Simon Sapin\n    :license: BSD, see LICENSE for details.\n\n\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport codecs\n\n\n### Codec APIs\n\nclass Codec(codecs.Codec):\n\n    def encode(self, input, errors='strict'):\n        return codecs.charmap_encode(input, errors, encoding_table)\n\n    def decode(self, input, errors='strict'):\n        return codecs.charmap_decode(input, errors, decoding_table)\n\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input, final=False):\n        return codecs.charmap_encode(input, self.errors, encoding_table)[0]\n\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input, final=False):\n        return codecs.charmap_decode(input, self.errors, decoding_table)[0]\n\n\nclass StreamWriter(Codec, codecs.StreamWriter):\n    pass\n\n\nclass StreamReader(Codec, codecs.StreamReader):\n    pass\n\n\n### encodings module API\n\ncodec_info = codecs.CodecInfo(\n    name='x-user-defined',\n    encode=Codec().encode,\n    decode=Codec().decode,\n    incrementalencoder=IncrementalEncoder,\n    incrementaldecoder=IncrementalDecoder,\n    streamreader=StreamReader,\n    streamwriter=StreamWriter,\n)\n\n\n### Decoding Table\n\n# Python 3:\n# for c in range(256): print('    %r' % chr(c if c < 128 else c + 0xF700))\ndecoding_table = (\n    '\\x00'\n    '\\x01'\n    '\\x02'\n    '\\x03'\n    '\\x04'\n    '\\x05'\n    '\\x06'\n    '\\x07'\n    '\\x08'\n    '\\t'\n    '\\n'\n    '\\x0b'\n    '\\x0c'\n    '\\r'\n    '\\x0e'\n    '\\x0f'\n    '\\x10'\n    '\\x11'\n    '\\x12'\n    '\\x13'\n    '\\x14'\n    '\\x15'\n    '\\x16'\n    '\\x17'\n    '\\x18'\n    '\\x19'\n    '\\x1a'\n    '\\x1b'\n    '\\x1c'\n    '\\x1d'\n    '\\x1e'\n    '\\x1f'\n    ' '\n    '!'\n    '\"'\n    '#'\n    '$'\n    '%'\n    '&'\n    \"'\"\n    '('\n    ')'\n    '*'\n    '+'\n    ','\n    '-'\n    '.'\n    '/'\n    '0'\n    '1'\n    '2'\n    '3'\n    '4'\n    '5'\n    '6'\n    '7'\n    '8'\n    '9'\n    ':'\n    ';'\n    '<'\n    '='\n    '>'\n    '?'\n    '@'\n    'A'\n    'B'\n    'C'\n    'D'\n    'E'\n    'F'\n    'G'\n    'H'\n    'I'\n    'J'\n    'K'\n    'L'\n    'M'\n    'N'\n    'O'\n    'P'\n    'Q'\n    'R'\n    'S'\n    'T'\n    'U'\n    'V'\n    'W'\n    'X'\n    'Y'\n    'Z'\n    '['\n    '\\\\'\n    ']'\n    '^'\n    '_'\n    '`'\n    'a'\n    'b'\n    'c'\n    'd'\n    'e'\n    'f'\n    'g'\n    'h'\n    'i'\n    'j'\n    'k'\n    'l'\n    'm'\n    'n'\n    'o'\n    'p'\n    'q'\n    'r'\n    's'\n    't'\n    'u'\n    'v'\n    'w'\n    'x'\n    'y'\n    'z'\n    '{'\n    '|'\n    '}'\n    '~'\n    '\\x7f'\n    '\\uf780'\n    '\\uf781'\n    '\\uf782'\n    '\\uf783'\n    '\\uf784'\n    '\\uf785'\n    '\\uf786'\n    '\\uf787'\n    '\\uf788'\n    '\\uf789'\n    '\\uf78a'\n    '\\uf78b'\n    '\\uf78c'\n    '\\uf78d'\n    '\\uf78e'\n    '\\uf78f'\n    '\\uf790'\n    '\\uf791'\n    '\\uf792'\n    '\\uf793'\n    '\\uf794'\n    '\\uf795'\n    '\\uf796'\n    '\\uf797'\n    '\\uf798'\n    '\\uf799'\n    '\\uf79a'\n    '\\uf79b'\n    '\\uf79c'\n    '\\uf79d'\n    '\\uf79e'\n    '\\uf79f'\n    '\\uf7a0'\n    '\\uf7a1'\n    '\\uf7a2'\n    '\\uf7a3'\n    '\\uf7a4'\n    '\\uf7a5'\n    '\\uf7a6'\n    '\\uf7a7'\n    '\\uf7a8'\n    '\\uf7a9'\n    '\\uf7aa'\n    '\\uf7ab'\n    '\\uf7ac'\n    '\\uf7ad'\n    '\\uf7ae'\n    '\\uf7af'\n    '\\uf7b0'\n    '\\uf7b1'\n    '\\uf7b2'\n    '\\uf7b3'\n    '\\uf7b4'\n    '\\uf7b5'\n    '\\uf7b6'\n    '\\uf7b7'\n    '\\uf7b8'\n    '\\uf7b9'\n    '\\uf7ba'\n    '\\uf7bb'\n    '\\uf7bc'\n    '\\uf7bd'\n    '\\uf7be'\n    '\\uf7bf'\n    '\\uf7c0'\n    '\\uf7c1'\n    '\\uf7c2'\n    '\\uf7c3'\n    '\\uf7c4'\n    '\\uf7c5'\n    '\\uf7c6'\n    '\\uf7c7'\n    '\\uf7c8'\n    '\\uf7c9'\n    '\\uf7ca'\n    '\\uf7cb'\n    '\\uf7cc'\n    '\\uf7cd'\n    '\\uf7ce'\n    '\\uf7cf'\n    '\\uf7d0'\n    '\\uf7d1'\n    '\\uf7d2'\n    '\\uf7d3'\n    '\\uf7d4'\n    '\\uf7d5'\n    '\\uf7d6'\n    '\\uf7d7'\n    '\\uf7d8'\n    '\\uf7d9'\n    '\\uf7da'\n    '\\uf7db'\n    '\\uf7dc'\n    '\\uf7dd'\n    '\\uf7de'\n    '\\uf7df'\n    '\\uf7e0'\n    '\\uf7e1'\n    '\\uf7e2'\n    '\\uf7e3'\n    '\\uf7e4'\n    '\\uf7e5'\n    '\\uf7e6'\n    '\\uf7e7'\n    '\\uf7e8'\n    '\\uf7e9'\n    '\\uf7ea'\n    '\\uf7eb'\n    '\\uf7ec'\n    '\\uf7ed'\n    '\\uf7ee'\n    '\\uf7ef'\n    '\\uf7f0'\n    '\\uf7f1'\n    '\\uf7f2'\n    '\\uf7f3'\n    '\\uf7f4'\n    '\\uf7f5'\n    '\\uf7f6'\n    '\\uf7f7'\n    '\\uf7f8'\n    '\\uf7f9'\n    '\\uf7fa'\n    '\\uf7fb'\n    '\\uf7fc'\n    '\\uf7fd'\n    '\\uf7fe'\n    '\\uf7ff'\n)\n\n### Encoding table\nencoding_table = codecs.charmap_build(decoding_table)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip/py.typed",
    "content": "pip is a command line program. While it is implemented in Python, and so is\navailable for import, you must not use pip's internal APIs in this way. Typing\ninformation is provided as a convenience only and is not a guarantee. Expect\nunannounced changes to the API and types in releases.\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip-22.3.1.dist-info/INSTALLER",
    "content": "pip\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip-22.3.1.dist-info/LICENSE.txt",
    "content": "Copyright (c) 2008-present The pip developers (see AUTHORS.txt file)\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip-22.3.1.dist-info/METADATA",
    "content": "Metadata-Version: 2.1\nName: pip\nVersion: 22.3.1\nSummary: The PyPA recommended tool for installing Python packages.\nHome-page: https://pip.pypa.io/\nAuthor: The pip developers\nAuthor-email: distutils-sig@python.org\nLicense: MIT\nProject-URL: Documentation, https://pip.pypa.io\nProject-URL: Source, https://github.com/pypa/pip\nProject-URL: Changelog, https://pip.pypa.io/en/stable/news/\nClassifier: Development Status :: 5 - Production/Stable\nClassifier: Intended Audience :: Developers\nClassifier: License :: OSI Approved :: MIT License\nClassifier: Topic :: Software Development :: Build Tools\nClassifier: Programming Language :: Python\nClassifier: Programming Language :: Python :: 3\nClassifier: Programming Language :: Python :: 3 :: Only\nClassifier: Programming Language :: Python :: 3.7\nClassifier: Programming Language :: Python :: 3.8\nClassifier: Programming Language :: Python :: 3.9\nClassifier: Programming Language :: Python :: 3.10\nClassifier: Programming Language :: Python :: 3.11\nClassifier: Programming Language :: Python :: Implementation :: CPython\nClassifier: Programming Language :: Python :: Implementation :: PyPy\nRequires-Python: >=3.7\nLicense-File: LICENSE.txt\n\npip - The Python Package Installer\n==================================\n\n.. image:: https://img.shields.io/pypi/v/pip.svg\n   :target: https://pypi.org/project/pip/\n\n.. image:: https://readthedocs.org/projects/pip/badge/?version=latest\n   :target: https://pip.pypa.io/en/latest\n\npip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes.\n\nPlease take a look at our documentation for how to install and use pip:\n\n* `Installation`_\n* `Usage`_\n\nWe release updates regularly, with a new version every 3 months. Find more details in our documentation:\n\n* `Release notes`_\n* `Release process`_\n\nIn pip 20.3, we've `made a big improvement to the heart of pip`_; `learn more`_. We want your input, so `sign up for our user experience research studies`_ to help us do it right.\n\n**Note**: pip 21.0, in January 2021, removed Python 2 support, per pip's `Python 2 support policy`_. Please migrate to Python 3.\n\nIf you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms:\n\n* `Issue tracking`_\n* `Discourse channel`_\n* `User IRC`_\n\nIf you want to get involved head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms:\n\n* `GitHub page`_\n* `Development documentation`_\n* `Development IRC`_\n\nCode of Conduct\n---------------\n\nEveryone interacting in the pip project's codebases, issue trackers, chat\nrooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.\n\n.. _package installer: https://packaging.python.org/guides/tool-recommendations/\n.. _Python Package Index: https://pypi.org\n.. _Installation: https://pip.pypa.io/en/stable/installation/\n.. _Usage: https://pip.pypa.io/en/stable/\n.. _Release notes: https://pip.pypa.io/en/stable/news.html\n.. _Release process: https://pip.pypa.io/en/latest/development/release-process/\n.. _GitHub page: https://github.com/pypa/pip\n.. _Development documentation: https://pip.pypa.io/en/latest/development\n.. _made a big improvement to the heart of pip: https://pyfound.blogspot.com/2020/11/pip-20-3-new-resolver.html\n.. _learn more: https://pip.pypa.io/en/latest/user_guide/#changes-to-the-pip-dependency-resolver-in-20-3-2020\n.. _sign up for our user experience research studies: https://pyfound.blogspot.com/2020/03/new-pip-resolver-to-roll-out-this-year.html\n.. _Python 2 support policy: https://pip.pypa.io/en/latest/development/release-process/#python-2-support\n.. _Issue tracking: https://github.com/pypa/pip/issues\n.. _Discourse channel: https://discuss.python.org/c/packaging\n.. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa\n.. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev\n.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip-22.3.1.dist-info/RECORD",
    "content": "pip/__init__.py,sha256=Z2hXGRMvmdhpmmqr0OW1fA2Jje8tnmU0uzibRoUF-w8,357\npip/__main__.py,sha256=mXwWDftNLMKfwVqKFWGE_uuBZvGSIiUELhLkeysIuZc,1198\npip/__pip-runner__.py,sha256=EnrfKmKMzWAdqg_JicLCOP9Y95Ux7zHh4ObvqLtQcjo,1444\npip/py.typed,sha256=EBVvvPRTn_eIpz5e5QztSCdrMX7Qwd7VP93RSoIlZ2I,286\npip/_internal/__init__.py,sha256=nnFCuxrPMgALrIDxSoy-H6Zj4W4UY60D-uL1aJyq0pc,573\npip/_internal/build_env.py,sha256=gEAT8R6SuWbg2mcrsmOTKWMw_x5pedMzvSTxQS57JZs,10234\npip/_internal/cache.py,sha256=C3n78VnBga9rjPXZqht_4A4d-T25poC7K0qBM7FHDhU,10734\npip/_internal/configuration.py,sha256=uBKTus43pDIO6IzT2mLWQeROmHhtnoabhniKNjPYvD0,13529\npip/_internal/exceptions.py,sha256=BfvcyN2iEv3Sf00SVmSk59lEeZEBHELqkuoN2KeIWKc,20942\npip/_internal/main.py,sha256=r-UnUe8HLo5XFJz8inTcOOTiu_sxNhgHb6VwlGUllOI,340\npip/_internal/pyproject.py,sha256=ob0Gb0l12YLZNxjdpZGRfWHgjqhZTnSVv96RuJyNOfs,7074\npip/_internal/self_outdated_check.py,sha256=R3MmjCyUt_lkUNMc6p3xVSx7vX28XiDh3VDs5OrYn6Q,8020\npip/_internal/wheel_builder.py,sha256=8cObBCu4mIsMJqZM7xXI9DO3vldiAnRNa1Gt6izPPTs,13079\npip/_internal/cli/__init__.py,sha256=FkHBgpxxb-_gd6r1FjnNhfMOzAUYyXoXKJ6abijfcFU,132\npip/_internal/cli/autocompletion.py,sha256=wY2JPZY2Eji1vhR7bVo-yCBPJ9LCy6P80iOAhZD1Vi8,6676\npip/_internal/cli/base_command.py,sha256=t1D5x40Hfn9HnPnMt-iSxvqL14nht2olBCacW74pc-k,7842\npip/_internal/cli/cmdoptions.py,sha256=Jlarlzz9qv9tC_tCaEbcc_jVvrPreFLBBUnDgoyWflw,29381\npip/_internal/cli/command_context.py,sha256=RHgIPwtObh5KhMrd3YZTkl8zbVG-6Okml7YbFX4Ehg0,774\npip/_internal/cli/main.py,sha256=ioJ8IVlb2K1qLOxR-tXkee9lURhYV89CDM71MKag7YY,2472\npip/_internal/cli/main_parser.py,sha256=laDpsuBDl6kyfywp9eMMA9s84jfH2TJJn-vmL0GG90w,4338\npip/_internal/cli/parser.py,sha256=tWP-K1uSxnJyXu3WE0kkH3niAYRBeuUaxeydhzOdhL4,10817\npip/_internal/cli/progress_bars.py,sha256=So4mPoSjXkXiSHiTzzquH3VVyVD_njXlHJSExYPXAow,1968\npip/_internal/cli/req_command.py,sha256=ypTutLv4j_efxC2f6C6aCQufxre-zaJdi5m_tWlLeBk,18172\npip/_internal/cli/spinners.py,sha256=hIJ83GerdFgFCdobIA23Jggetegl_uC4Sp586nzFbPE,5118\npip/_internal/cli/status_codes.py,sha256=sEFHUaUJbqv8iArL3HAtcztWZmGOFX01hTesSytDEh0,116\npip/_internal/commands/__init__.py,sha256=5oRO9O3dM2vGuh0bFw4HOVletryrz5HHMmmPWwJrH9U,3882\npip/_internal/commands/cache.py,sha256=muaT0mbL-ZUpn6AaushVAipzTiMwE4nV2BLbJBwt_KQ,7582\npip/_internal/commands/check.py,sha256=0gjXR7j36xJT5cs2heYU_dfOfpnFfzX8OoPNNoKhqdM,1685\npip/_internal/commands/completion.py,sha256=H0TJvGrdsoleuIyQKzJbicLFppYx2OZA0BLNpQDeFjI,4129\npip/_internal/commands/configuration.py,sha256=NB5uf8HIX8-li95YLoZO09nALIWlLCHDF5aifSKcBn8,9815\npip/_internal/commands/debug.py,sha256=kVjn-O1ixLk0webD0w9vfFFq_GCTUTd2hmLOnYtDCig,6573\npip/_internal/commands/download.py,sha256=LwKEyYMG2L67nQRyGo8hQdNEeMU2bmGWqJfcB8JDXas,5289\npip/_internal/commands/freeze.py,sha256=gCjoD6foBZPBAAYx5t8zZLkJhsF_ZRtnb3dPuD7beO8,2951\npip/_internal/commands/hash.py,sha256=EVVOuvGtoPEdFi8SNnmdqlCQrhCxV-kJsdwtdcCnXGQ,1703\npip/_internal/commands/help.py,sha256=gcc6QDkcgHMOuAn5UxaZwAStsRBrnGSn_yxjS57JIoM,1132\npip/_internal/commands/index.py,sha256=1VVXXj5MsI2qH-N7uniQQyVkg-KCn_RdjiyiUmkUS5U,4762\npip/_internal/commands/inspect.py,sha256=mRJ9aIkBQN0IJ7Um8pzaxAzVPIgL8KfWHx1fWKJgUAQ,3374\npip/_internal/commands/install.py,sha256=_XbW0PyxtZCMMNqo8mDaOq3TBRiJNFM-94CR27mburc,31726\npip/_internal/commands/list.py,sha256=Fk1TSxB33NlRS4qlLQ0xwnytnF9-zkQJbKQYv2xc4Q4,12343\npip/_internal/commands/search.py,sha256=sbBZiARRc050QquOKcCvOr2K3XLsoYebLKZGRi__iUI,5697\npip/_internal/commands/show.py,sha256=CJI8q4SSY0X346K1hi4Th8Nbyhl4nxPTBJUuzOlTaYE,6129\npip/_internal/commands/uninstall.py,sha256=0JQhifYxecNrJAwoILFwjm9V1V3liXzNT-y4bgRXXPw,3680\npip/_internal/commands/wheel.py,sha256=mbFJd4dmUfrVFJkQbK8n2zHyRcD3AI91f7EUo9l3KYg,7396\npip/_internal/distributions/__init__.py,sha256=Hq6kt6gXBgjNit5hTTWLAzeCNOKoB-N0pGYSqehrli8,858\npip/_internal/distributions/base.py,sha256=jrF1Vi7eGyqFqMHrieh1PIOrGU7KeCxhYPZnbvtmvGY,1221\npip/_internal/distributions/installed.py,sha256=NI2OgsgH9iBq9l5vB-56vOg5YsybOy-AU4VE5CSCO2I,729\npip/_internal/distributions/sdist.py,sha256=SQBdkatXSigKGG_SaD0U0p1Jwdfrg26UCNcHgkXZfdA,6494\npip/_internal/distributions/wheel.py,sha256=m-J4XO-gvFerlYsFzzSXYDvrx8tLZlJFTCgDxctn8ig,1164\npip/_internal/index/__init__.py,sha256=vpt-JeTZefh8a-FC22ZeBSXFVbuBcXSGiILhQZJaNpQ,30\npip/_internal/index/collector.py,sha256=Pb9FW9STH2lwaApCIdMCivsbPP5pSYQp5bh3nLQBkDU,16503\npip/_internal/index/package_finder.py,sha256=kmcMu5_i-BP6v3NQGY0_am1ezxM2Gk4t00arZMmm4sc,37596\npip/_internal/index/sources.py,sha256=SVyPitv08-Qalh2_Bk5diAJ9GAA_d-a93koouQodAG0,6557\npip/_internal/locations/__init__.py,sha256=QhB-Y6TNyaU010cimm2T4wM5loe8oRdjLwJ6xmsGc-k,17552\npip/_internal/locations/_distutils.py,sha256=wgHDvHGNZHtlcHkQjYovHzkEUBzisR0iOh7OqCIkB5g,6302\npip/_internal/locations/_sysconfig.py,sha256=nM-DiVHXWTxippdmN0MGVl5r7OIfIMy3vgDMlo8c_oo,7867\npip/_internal/locations/base.py,sha256=ufyDqPwZ4jLbScD44u8AwTVI-3ft8O78UGrroQI5f68,2573\npip/_internal/metadata/__init__.py,sha256=84j1dPJaIoz5Q2ZTPi0uB1iaDAHiUNfKtYSGQCfFKpo,4280\npip/_internal/metadata/_json.py,sha256=BTkWfFDrWFwuSodImjtbAh8wCL3isecbnjTb5E6UUDI,2595\npip/_internal/metadata/base.py,sha256=vIwIo1BtoqegehWMAXhNrpLGYBq245rcaCNkBMPnTU8,25277\npip/_internal/metadata/pkg_resources.py,sha256=WjwiNdRsvxqxL4MA5Tb5a_q3Q3sUhdpbZF8wGLtPMI0,9773\npip/_internal/metadata/importlib/__init__.py,sha256=9ZVO8BoE7NEZPmoHp5Ap_NJo0HgNIezXXg-TFTtt3Z4,107\npip/_internal/metadata/importlib/_compat.py,sha256=GAe_prIfCE4iUylrnr_2dJRlkkBVRUbOidEoID7LPoE,1882\npip/_internal/metadata/importlib/_dists.py,sha256=BUV8y6D0PePZrEN3vfJL-m1FDqZ6YPRgAiBeBinHhNg,8181\npip/_internal/metadata/importlib/_envs.py,sha256=7BxanCh3T7arusys__O2ZHJdnmDhQXFmfU7x1-jB5xI,7457\npip/_internal/models/__init__.py,sha256=3DHUd_qxpPozfzouoqa9g9ts1Czr5qaHfFxbnxriepM,63\npip/_internal/models/candidate.py,sha256=6pcABsaR7CfIHlbJbr2_kMkVJFL_yrYjTx6SVWUnCPQ,990\npip/_internal/models/direct_url.py,sha256=HLO0sL2aYB6n45bwmd72TDN05sLHJlOQI8M01l2SH3I,5877\npip/_internal/models/format_control.py,sha256=DJpMYjxeYKKQdwNcML2_F0vtAh-qnKTYe-CpTxQe-4g,2520\npip/_internal/models/index.py,sha256=tYnL8oxGi4aSNWur0mG8DAP7rC6yuha_MwJO8xw0crI,1030\npip/_internal/models/installation_report.py,sha256=ad1arqtxrSFBvWnm6mRqmG12HLV3pZZcZcHrlTFIiqU,2617\npip/_internal/models/link.py,sha256=9HWL14UQTMxRCnY6dmAz09rGElJrMAcHn2OJZCBx0tk,18083\npip/_internal/models/scheme.py,sha256=3EFQp_ICu_shH1-TBqhl0QAusKCPDFOlgHFeN4XowWs,738\npip/_internal/models/search_scope.py,sha256=iGPQQ6a4Lau8oGQ_FWj8aRLik8A21o03SMO5KnSt-Cg,4644\npip/_internal/models/selection_prefs.py,sha256=KZdi66gsR-_RUXUr9uejssk3rmTHrQVJWeNA2sV-VSY,1907\npip/_internal/models/target_python.py,sha256=qKpZox7J8NAaPmDs5C_aniwfPDxzvpkrCKqfwndG87k,3858\npip/_internal/models/wheel.py,sha256=YqazoIZyma_Q1ejFa1C7NHKQRRWlvWkdK96VRKmDBeI,3600\npip/_internal/network/__init__.py,sha256=jf6Tt5nV_7zkARBrKojIXItgejvoegVJVKUbhAa5Ioc,50\npip/_internal/network/auth.py,sha256=a3C7Xaa8kTJjXkdi_wrUjqaySc8Z9Yz7U6QIbXfzMyc,12190\npip/_internal/network/cache.py,sha256=hgXftU-eau4MWxHSLquTMzepYq5BPC2zhCkhN3glBy8,2145\npip/_internal/network/download.py,sha256=HvDDq9bVqaN3jcS3DyVJHP7uTqFzbShdkf7NFSoHfkw,6096\npip/_internal/network/lazy_wheel.py,sha256=PbPyuleNhtEq6b2S7rufoGXZWMD15FAGL4XeiAQ8FxA,7638\npip/_internal/network/session.py,sha256=BpDOJ7_Xw5VkgPYWsePzcaqOfcyRZcB2AW7W0HGBST0,18443\npip/_internal/network/utils.py,sha256=6A5SrUJEEUHxbGtbscwU2NpCyz-3ztiDlGWHpRRhsJ8,4073\npip/_internal/network/xmlrpc.py,sha256=AzQgG4GgS152_cqmGr_Oz2MIXsCal-xfsis7fA7nmU0,1791\npip/_internal/operations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_internal/operations/check.py,sha256=ca4O9CkPt9Em9sLCf3H0iVt1GIcW7M8C0U5XooaBuT4,5109\npip/_internal/operations/freeze.py,sha256=mwTZ2uML8aQgo3k8MR79a7SZmmmvdAJqdyaknKbavmg,9784\npip/_internal/operations/prepare.py,sha256=BeYXrLFpRoV5XBnRXQHxRA2plyC36kK9Pms5D9wjCo4,25091\npip/_internal/operations/build/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_internal/operations/build/build_tracker.py,sha256=vf81EwomN3xe9G8qRJED0VGqNikmRQRQoobNsxi5Xrs,4133\npip/_internal/operations/build/metadata.py,sha256=ES_uRmAvhrNm_nDTpZxshBfUsvnXtkj-g_4rZrH9Rww,1404\npip/_internal/operations/build/metadata_editable.py,sha256=_Rai0VZjxoeJUkjkuICrq45LtjwFoDOveosMYH43rKc,1456\npip/_internal/operations/build/metadata_legacy.py,sha256=o-eU21As175hDC7dluM1fJJ_FqokTIShyWpjKaIpHZw,2198\npip/_internal/operations/build/wheel.py,sha256=AO9XnTGhTgHtZmU8Dkbfo1OGr41rBuSDjIgAa4zUKgE,1063\npip/_internal/operations/build/wheel_editable.py,sha256=TVETY-L_M_dSEKBhTIcQOP75zKVXw8tuq1U354Mm30A,1405\npip/_internal/operations/build/wheel_legacy.py,sha256=C9j6rukgQI1n_JeQLoZGuDdfUwzCXShyIdPTp6edbMQ,3064\npip/_internal/operations/install/__init__.py,sha256=mX7hyD2GNBO2mFGokDQ30r_GXv7Y_PLdtxcUv144e-s,51\npip/_internal/operations/install/editable_legacy.py,sha256=ee4kfJHNuzTdKItbfAsNOSEwq_vD7DRPGkBdK48yBhU,1354\npip/_internal/operations/install/legacy.py,sha256=cHdcHebyzf8w7OaOLwcsTNSMSSV8WBoAPFLay_9CjE8,4105\npip/_internal/operations/install/wheel.py,sha256=CxzEg2wTPX4SxNTPIx0ozTqF1X7LhpCyP3iM2FjcKUE,27407\npip/_internal/req/__init__.py,sha256=rUQ9d_Sh3E5kNYqX9pkN0D06YL-LrtcbJQ-LiIonq08,2807\npip/_internal/req/constructors.py,sha256=ypjtq1mOQ3d2mFkFPMf_6Mr8SLKeHQk3tUKHA1ddG0U,16611\npip/_internal/req/req_file.py,sha256=N6lPO3c0to_G73YyGAnk7VUYmed5jV4Qxgmt1xtlXVg,17646\npip/_internal/req/req_install.py,sha256=4tzyVGPHJ1-GXowm6PBT52BGIlbc4w7fhVqf-55bmRg,35600\npip/_internal/req/req_set.py,sha256=j3esG0s6SzoVReX9rWn4rpYNtyET_fwxbwJPRimvRxo,2858\npip/_internal/req/req_uninstall.py,sha256=ZFQfgSNz6H1BMsgl87nQNr2iaQCcbFcmXpW8rKVQcic,24045\npip/_internal/resolution/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_internal/resolution/base.py,sha256=qlmh325SBVfvG6Me9gc5Nsh5sdwHBwzHBq6aEXtKsLA,583\npip/_internal/resolution/legacy/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_internal/resolution/legacy/resolver.py,sha256=9em8D5TcSsEN4xZM1WreaRShOnyM4LlvhMSHpUPsocE,24129\npip/_internal/resolution/resolvelib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_internal/resolution/resolvelib/base.py,sha256=u1O4fkvCO4mhmu5i32xrDv9AX5NgUci_eYVyBDQhTIM,5220\npip/_internal/resolution/resolvelib/candidates.py,sha256=6kQZeMzwibnL4lO6bW0hUQQjNEvXfADdFphRRkRvOtc,18963\npip/_internal/resolution/resolvelib/factory.py,sha256=OnjkLIgyk5Tol7uOOqapA1D4qiRHWmPU18DF1yN5N8o,27878\npip/_internal/resolution/resolvelib/found_candidates.py,sha256=hvL3Hoa9VaYo-qEOZkBi2Iqw251UDxPz-uMHVaWmLpE,5705\npip/_internal/resolution/resolvelib/provider.py,sha256=Vd4jW_NnyifB-HMkPYtZIO70M3_RM0MbL5YV6XyBM-w,9914\npip/_internal/resolution/resolvelib/reporter.py,sha256=3ZVVYrs5PqvLFJkGLcuXoMK5mTInFzl31xjUpDBpZZk,2526\npip/_internal/resolution/resolvelib/requirements.py,sha256=B1ndvKPSuyyyTEXt9sKhbwminViSWnBrJa7qO2ln4Z0,5455\npip/_internal/resolution/resolvelib/resolver.py,sha256=nYZ9bTFXj5c1ILKnkSgU7tUCTYyo5V5J-J0sKoA7Wzg,11533\npip/_internal/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_internal/utils/_log.py,sha256=-jHLOE_THaZz5BFcCnoSL9EYAtJ0nXem49s9of4jvKw,1015\npip/_internal/utils/appdirs.py,sha256=swgcTKOm3daLeXTW6v5BUS2Ti2RvEnGRQYH_yDXklAo,1665\npip/_internal/utils/compat.py,sha256=ACyBfLgj3_XG-iA5omEDrXqDM0cQKzi8h8HRBInzG6Q,1884\npip/_internal/utils/compatibility_tags.py,sha256=ydin8QG8BHqYRsPY4OL6cmb44CbqXl1T0xxS97VhHkk,5377\npip/_internal/utils/datetime.py,sha256=m21Y3wAtQc-ji6Veb6k_M5g6A0ZyFI4egchTdnwh-pQ,242\npip/_internal/utils/deprecation.py,sha256=OLc7GzDwPob9y8jscDYCKUNBV-9CWwqFplBOJPLOpBM,5764\npip/_internal/utils/direct_url_helpers.py,sha256=6F1tc2rcKaCZmgfVwsE6ObIe_Pux23mUVYA-2D9wCFc,3206\npip/_internal/utils/distutils_args.py,sha256=bYUt4wfFJRaeGO4VHia6FNaA8HlYXMcKuEq1zYijY5g,1115\npip/_internal/utils/egg_link.py,sha256=5MVlpz5LirT4iLQq86OYzjXaYF0D4Qk1dprEI7ThST4,2203\npip/_internal/utils/encoding.py,sha256=qqsXDtiwMIjXMEiIVSaOjwH5YmirCaK-dIzb6-XJsL0,1169\npip/_internal/utils/entrypoints.py,sha256=YlhLTRl2oHBAuqhc-zmL7USS67TPWVHImjeAQHreZTQ,3064\npip/_internal/utils/filesystem.py,sha256=RhMIXUaNVMGjc3rhsDahWQ4MavvEQDdqXqgq-F6fpw8,5122\npip/_internal/utils/filetypes.py,sha256=i8XAQ0eFCog26Fw9yV0Yb1ygAqKYB1w9Cz9n0fj8gZU,716\npip/_internal/utils/glibc.py,sha256=tDfwVYnJCOC0BNVpItpy8CGLP9BjkxFHdl0mTS0J7fc,3110\npip/_internal/utils/hashes.py,sha256=1WhkVNIHNfuYLafBHThIjVKGplxFJXSlQtuG2mXNlJI,4831\npip/_internal/utils/inject_securetransport.py,sha256=o-QRVMGiENrTJxw3fAhA7uxpdEdw6M41TjHYtSVRrcg,795\npip/_internal/utils/logging.py,sha256=U2q0i1n8hPS2gQh8qcocAg5dovGAa_bR24akmXMzrk4,11632\npip/_internal/utils/misc.py,sha256=49Rs2NgrD4JGTKFt0farCm7FIAi-rjyoxgioArhCW_0,21617\npip/_internal/utils/models.py,sha256=5GoYU586SrxURMvDn_jBMJInitviJg4O5-iOU-6I0WY,1193\npip/_internal/utils/packaging.py,sha256=5Wm6_x7lKrlqVjPI5MBN_RurcRHwVYoQ7Ksrs84de7s,2108\npip/_internal/utils/setuptools_build.py,sha256=4i3CuS34yNrkePnZ73rR47pyDzpZBo-SX9V5PNDSSHY,5662\npip/_internal/utils/subprocess.py,sha256=MYySbvY7qBevRxq_RFfOsDqG4vMqrB4vDoL_eyPE6Bo,9197\npip/_internal/utils/temp_dir.py,sha256=aCX489gRa4Nu0dMKRFyGhV6maJr60uEynu5uCbKR4Qg,7702\npip/_internal/utils/unpacking.py,sha256=SBb2iV1crb89MDRTEKY86R4A_UOWApTQn9VQVcMDOlE,8821\npip/_internal/utils/urls.py,sha256=AhaesUGl-9it6uvG6fsFPOr9ynFpGaTMk4t5XTX7Z_Q,1759\npip/_internal/utils/virtualenv.py,sha256=4_48qMzCwB_F5jIK5BC_ua7uiAMVifmQWU9NdaGUoVA,3459\npip/_internal/utils/wheel.py,sha256=lXOgZyTlOm5HmK8tw5iw0A3_5A6wRzsXHOaQkIvvloU,4549\npip/_internal/vcs/__init__.py,sha256=UAqvzpbi0VbZo3Ub6skEeZAw-ooIZR-zX_WpCbxyCoU,596\npip/_internal/vcs/bazaar.py,sha256=zq-Eu2NtJffc6kOsyv2kmRTnKg9qeIXE-KH5JeKck70,3518\npip/_internal/vcs/git.py,sha256=mjhwudCx9WlLNkxZ6_kOKmueF0rLoU2i1xeASKF6yiQ,18116\npip/_internal/vcs/mercurial.py,sha256=Bzbd518Jsx-EJI0IhIobiQqiRsUv5TWYnrmRIFWE0Gw,5238\npip/_internal/vcs/subversion.py,sha256=AeUVE9d9qp-0QSOMiUvuFHy1TK950E3QglN7ipP13sI,11728\npip/_internal/vcs/versioncontrol.py,sha256=KUOc-hN51em9jrqxKwUR3JnkgSE-xSOqMiiJcSaL6B8,22811\npip/_vendor/__init__.py,sha256=fNxOSVD0auElsD8fN9tuq5psfgMQ-RFBtD4X5gjlRkg,4966\npip/_vendor/six.py,sha256=TOOfQi7nFGfMrIvtdr6wX4wyHH8M7aknmuLfo2cBBrM,34549\npip/_vendor/typing_extensions.py,sha256=VKZ_nHsuzDbKOVUY2CTdavwBgfZ2EXRyluZHRzUYAbg,80114\npip/_vendor/vendor.txt,sha256=07gLL_CcEHdl1XM0g4PH2L4gsTTMlJr8WWIC11yEyMo,469\npip/_vendor/cachecontrol/__init__.py,sha256=hrxlv3q7upsfyMw8k3gQ9vagBax1pYHSGGqYlZ0Zk0M,465\npip/_vendor/cachecontrol/_cmd.py,sha256=lxUXqfNTVx84zf6tcWbkLZHA6WVBRtJRpfeA9ZqhaAY,1379\npip/_vendor/cachecontrol/adapter.py,sha256=ew9OYEQHEOjvGl06ZsuX8W3DAvHWsQKHwWAxISyGug8,5033\npip/_vendor/cachecontrol/cache.py,sha256=Tty45fOjH40fColTGkqKQvQQmbYsMpk-nCyfLcv2vG4,1535\npip/_vendor/cachecontrol/compat.py,sha256=LNx7vqBndYdHU8YuJt53ab_8rzMGTXVrvMb7CZJkxG0,778\npip/_vendor/cachecontrol/controller.py,sha256=bAYrt7x_VH4toNpI066LQxbHpYGpY1MxxmZAhspplvw,16416\npip/_vendor/cachecontrol/filewrapper.py,sha256=X4BAQOO26GNOR7nH_fhTzAfeuct2rBQcx_15MyFBpcs,3946\npip/_vendor/cachecontrol/heuristics.py,sha256=8kAyuZLSCyEIgQr6vbUwfhpqg9ows4mM0IV6DWazevI,4154\npip/_vendor/cachecontrol/serialize.py,sha256=_U1NU_C-SDgFzkbAxAsPDgMTHeTWZZaHCQnZN_jh0U8,7105\npip/_vendor/cachecontrol/wrapper.py,sha256=X3-KMZ20Ho3VtqyVaXclpeQpFzokR5NE8tZSfvKVaB8,774\npip/_vendor/cachecontrol/caches/__init__.py,sha256=h-1cUmOz6mhLsjTjOrJ8iPejpGdLCyG4lzTftfGZvLg,242\npip/_vendor/cachecontrol/caches/file_cache.py,sha256=GpexcE29LoY4MaZwPUTcUBZaDdcsjqyLxZFznk8Hbr4,5271\npip/_vendor/cachecontrol/caches/redis_cache.py,sha256=mp-QWonP40I3xJGK3XVO-Gs9a3UjzlqqEmp9iLJH9F4,1033\npip/_vendor/certifi/__init__.py,sha256=luDjIGxDSrQ9O0zthdz5Lnt069Z_7eR1GIEefEaf-Ys,94\npip/_vendor/certifi/__main__.py,sha256=1k3Cr95vCxxGRGDljrW3wMdpZdL3Nhf0u1n-k2qdsCY,255\npip/_vendor/certifi/cacert.pem,sha256=3l8CcWt_qL42030rGieD3SLufICFX0bYtGhDl_EXVPI,286370\npip/_vendor/certifi/core.py,sha256=ZwiOsv-sD_ouU1ft8wy_xZ3LQ7UbcVzyqj2XNyrsZis,4279\npip/_vendor/chardet/__init__.py,sha256=9-r0i294avRciob2HKVcKf6GJmXPHpgMqIijVrqHBDU,3705\npip/_vendor/chardet/big5freq.py,sha256=ltcfP-3PjlNHCoo5e4a7C4z-2DhBTXRfY6jbMbB7P30,31274\npip/_vendor/chardet/big5prober.py,sha256=neUXIlq35507yibstiznZWFzyNcMn6EXrqJaUJVPWKg,1741\npip/_vendor/chardet/chardistribution.py,sha256=M9NTKdM72KieFKy4TT5eml4PP0WaVcXuY5PpWSFD0FA,9608\npip/_vendor/chardet/charsetgroupprober.py,sha256=CaIBAmNitEsYuSgMvgAsMREN4cLxMj5OYwMhVo6MAxk,3817\npip/_vendor/chardet/charsetprober.py,sha256=Eo3w8sCmbvnVKOGNW1iy50KATVs8xV-gF7cQ0VG85dQ,4801\npip/_vendor/chardet/codingstatemachine.py,sha256=BiGR9kgTYbS4gJI5qBmE52HMOBOR_roDvXf7aIehdEk,3559\npip/_vendor/chardet/cp949prober.py,sha256=kCQEaOCzMntqv7pAyXEobWTRgIUxYfoiUr0btXO1nI8,1838\npip/_vendor/chardet/enums.py,sha256=Rodw4p61Vg9U-oCo6eUuT7uDzKwIbCaA15HwbvCoCNk,1619\npip/_vendor/chardet/escprober.py,sha256=girD61r3NsQLnMQXsWWBU4hHuRJzTH3V7-VfTUr-nQY,3864\npip/_vendor/chardet/escsm.py,sha256=0Vs4iPPovberMoSxxnK5pI161Xf-mtKgOl14g5Xc7zg,12021\npip/_vendor/chardet/eucjpprober.py,sha256=pGgs4lINwCEDV2bxqIZ6hXpaj2j4l2oLsMx6kuOK_zQ,3676\npip/_vendor/chardet/euckrfreq.py,sha256=3mHuRvXfsq_QcQysDQFb8qSudvTiol71C6Ic2w57tKM,13566\npip/_vendor/chardet/euckrprober.py,sha256=qBuSS2zXWaoUmGdzz3owAnD1GNhuKR_8bYzDC3yxe6I,1731\npip/_vendor/chardet/euctwfreq.py,sha256=2alILE1Lh5eqiFJZjzRkMQXolNJRHY5oBQd-vmZYFFM,36913\npip/_vendor/chardet/euctwprober.py,sha256=SLnCoJC94jZL8PJio60Q8PZACJA1rVPtUdWMa1W8Pwk,1731\npip/_vendor/chardet/gb2312freq.py,sha256=49OrdXzD-HXqwavkqjo8Z7gvs58hONNzDhAyMENNkvY,20735\npip/_vendor/chardet/gb2312prober.py,sha256=NS_i52jZE0TnWGkKqFduvu9fzW0nMcS2XbYJ8qSX8hY,1737\npip/_vendor/chardet/hebrewprober.py,sha256=1l1hXF8-2IWDrPkf85UvAO1GVtMfY1r11kDgOqa-gU4,13919\npip/_vendor/chardet/jisfreq.py,sha256=mm8tfrwqhpOd3wzZKS4NJqkYBQVcDfTM2JiQ5aW932E,25796\npip/_vendor/chardet/johabfreq.py,sha256=dBpOYG34GRX6SL8k_LbS9rxZPMjLjoMlgZ03Pz5Hmqc,42498\npip/_vendor/chardet/johabprober.py,sha256=C18osd4vMPfy9facw-Y1Lor_9UrW0PeV-zxM2fu441c,1730\npip/_vendor/chardet/jpcntx.py,sha256=m1gDpPkRca4EDwym8XSL5YdoILFnFsDbNBYMQV7_-NE,26797\npip/_vendor/chardet/langbulgarianmodel.py,sha256=vmbvYFP8SZkSxoBvLkFqKiH1sjma5ihk3PTpdy71Rr4,104562\npip/_vendor/chardet/langgreekmodel.py,sha256=JfB7bupjjJH2w3X_mYnQr9cJA_7EuITC2cRW13fUjeI,98484\npip/_vendor/chardet/langhebrewmodel.py,sha256=3HXHaLQPNAGcXnJjkIJfozNZLTvTJmf4W5Awi6zRRKc,98196\npip/_vendor/chardet/langhungarianmodel.py,sha256=WxbeQIxkv8YtApiNqxQcvj-tMycsoI4Xy-fwkDHpP_Y,101363\npip/_vendor/chardet/langrussianmodel.py,sha256=s395bTZ87ESTrZCOdgXbEjZ9P1iGPwCl_8xSsac_DLY,128035\npip/_vendor/chardet/langthaimodel.py,sha256=7bJlQitRpTnVGABmbSznHnJwOHDy3InkTvtFUx13WQI,102774\npip/_vendor/chardet/langturkishmodel.py,sha256=XY0eGdTIy4eQ9Xg1LVPZacb-UBhHBR-cq0IpPVHowKc,95372\npip/_vendor/chardet/latin1prober.py,sha256=u_iGcQMUcZLXvj4B_WXx4caA0C5oaE2Qj1KTpz_RQ1I,5260\npip/_vendor/chardet/mbcharsetprober.py,sha256=iKKuB6o_FF80NynRLBDT0UtwOnpLqmL_OspRPMib7CM,3367\npip/_vendor/chardet/mbcsgroupprober.py,sha256=1D_kp9nv2_NQRddq9I2WDvB35OJh7Tfpo-OYTnL3B5o,2056\npip/_vendor/chardet/mbcssm.py,sha256=EfORNu1WXgnFvpFarU8uJHS8KFif63xmgrHOB4DdDdY,30068\npip/_vendor/chardet/sbcharsetprober.py,sha256=VvtWiNRLbHDZ5xgnofsmP1u8VQIkkaAuw3Ir9m1zDzQ,6199\npip/_vendor/chardet/sbcsgroupprober.py,sha256=mekr4E3hgT4onmwi8oi1iEGW1CN-Z-BArG6kOtCunJw,4129\npip/_vendor/chardet/sjisprober.py,sha256=sLfWS25PVFr5cDGhEf6h_s-RJsyeSteA-4ynsTl_UvA,3749\npip/_vendor/chardet/universaldetector.py,sha256=BHeNWt1kn0yQgnR6xNtLAjiNmEQpSHYlKEvuZ9QyR1k,13288\npip/_vendor/chardet/utf1632prober.py,sha256=N42YJEOkVDB67c38t5aJhXMG1QvnyWWDMNY5ERzniU0,8289\npip/_vendor/chardet/utf8prober.py,sha256=mnLaSBV4gg-amt2WmxKFKWy4vVBedMNgjdbvgzBo0Dc,2709\npip/_vendor/chardet/version.py,sha256=u_QYi-DXU1s7fyC_Rwa0I0-UcxMVmH7Co6c7QGKbe3g,242\npip/_vendor/chardet/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/chardet/cli/chardetect.py,sha256=1qMxT3wrp5vP6ugSf1-Zz3BWwlbCWJ0jzeCuhgX85vw,2406\npip/_vendor/chardet/metadata/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/chardet/metadata/languages.py,sha256=HcaBygWtZq3gR8prIkJp_etvkhm2V4pUIToqjPZhgrc,13280\npip/_vendor/colorama/__init__.py,sha256=ihDoWQOkapwF7sqQ99AoDoEF3vGYm40OtmgW211cLZw,239\npip/_vendor/colorama/ansi.py,sha256=Top4EeEuaQdBWdteKMEcGOTeKeF19Q-Wo_6_Cj5kOzQ,2522\npip/_vendor/colorama/ansitowin32.py,sha256=gGrO7MVtwc-j1Sq3jKfZpERT1JWmYSOsTVDiTnFbZU4,10830\npip/_vendor/colorama/initialise.py,sha256=PprovDNxMTrvoNHFcL2NZjpH2XzDc8BLxLxiErfUl4k,1915\npip/_vendor/colorama/win32.py,sha256=bJ8Il9jwaBN5BJ8bmN6FoYZ1QYuMKv2j8fGrXh7TJjw,5404\npip/_vendor/colorama/winterm.py,sha256=2y_2b7Zsv34feAsP67mLOVc-Bgq51mdYGo571VprlrM,6438\npip/_vendor/distlib/__init__.py,sha256=acgfseOC55dNrVAzaBKpUiH3Z6V7Q1CaxsiQ3K7pC-E,581\npip/_vendor/distlib/compat.py,sha256=tfoMrj6tujk7G4UC2owL6ArgDuCKabgBxuJRGZSmpko,41259\npip/_vendor/distlib/database.py,sha256=o_mw0fAr93NDAHHHfqG54Y1Hi9Rkfrp2BX15XWZYK50,51697\npip/_vendor/distlib/index.py,sha256=HFiDG7LMoaBs829WuotrfIwcErOOExUOR_AeBtw_TCU,20834\npip/_vendor/distlib/locators.py,sha256=wNzG-zERzS_XGls-nBPVVyLRHa2skUlkn0-5n0trMWA,51991\npip/_vendor/distlib/manifest.py,sha256=nQEhYmgoreaBZzyFzwYsXxJARu3fo4EkunU163U16iE,14811\npip/_vendor/distlib/markers.py,sha256=TpHHHLgkzyT7YHbwj-2i6weRaq-Ivy2-MUnrDkjau-U,5058\npip/_vendor/distlib/metadata.py,sha256=g_DIiu8nBXRzA-mWPRpatHGbmFZqaFoss7z9TG7QSUU,39801\npip/_vendor/distlib/resources.py,sha256=LwbPksc0A1JMbi6XnuPdMBUn83X7BPuFNWqPGEKI698,10820\npip/_vendor/distlib/scripts.py,sha256=BmkTKmiTk4m2cj-iueliatwz3ut_9SsABBW51vnQnZU,18102\npip/_vendor/distlib/t32.exe,sha256=a0GV5kCoWsMutvliiCKmIgV98eRZ33wXoS-XrqvJQVs,97792\npip/_vendor/distlib/t64-arm.exe,sha256=68TAa32V504xVBnufojh0PcenpR3U4wAqTqf-MZqbPw,182784\npip/_vendor/distlib/t64.exe,sha256=gaYY8hy4fbkHYTTnA4i26ct8IQZzkBG2pRdy0iyuBrc,108032\npip/_vendor/distlib/util.py,sha256=31dPXn3Rfat0xZLeVoFpuniyhe6vsbl9_QN-qd9Lhlk,66262\npip/_vendor/distlib/version.py,sha256=WG__LyAa2GwmA6qSoEJtvJE8REA1LZpbSizy8WvhJLk,23513\npip/_vendor/distlib/w32.exe,sha256=R4csx3-OGM9kL4aPIzQKRo5TfmRSHZo6QWyLhDhNBks,91648\npip/_vendor/distlib/w64-arm.exe,sha256=xdyYhKj0WDcVUOCb05blQYvzdYIKMbmJn2SZvzkcey4,168448\npip/_vendor/distlib/w64.exe,sha256=ejGf-rojoBfXseGLpya6bFTFPWRG21X5KvU8J5iU-K0,101888\npip/_vendor/distlib/wheel.py,sha256=Rgqs658VsJ3R2845qwnZD8XQryV2CzWw2mghwLvxxsI,43898\npip/_vendor/distro/__init__.py,sha256=2fHjF-SfgPvjyNZ1iHh_wjqWdR_Yo5ODHwZC0jLBPhc,981\npip/_vendor/distro/__main__.py,sha256=bu9d3TifoKciZFcqRBuygV3GSuThnVD_m2IK4cz96Vs,64\npip/_vendor/distro/distro.py,sha256=UYQG_9H_iSOt422uasA92HlY7aXeTnWKdV-IhsSAdwQ,48841\npip/_vendor/idna/__init__.py,sha256=KJQN1eQBr8iIK5SKrJ47lXvxG0BJ7Lm38W4zT0v_8lk,849\npip/_vendor/idna/codec.py,sha256=6ly5odKfqrytKT9_7UrlGklHnf1DSK2r9C6cSM4sa28,3374\npip/_vendor/idna/compat.py,sha256=0_sOEUMT4CVw9doD3vyRhX80X19PwqFoUBs7gWsFME4,321\npip/_vendor/idna/core.py,sha256=1JxchwKzkxBSn7R_oCE12oBu3eVux0VzdxolmIad24M,12950\npip/_vendor/idna/idnadata.py,sha256=xUjqKqiJV8Ho_XzBpAtv5JFoVPSupK-SUXvtjygUHqw,44375\npip/_vendor/idna/intranges.py,sha256=YBr4fRYuWH7kTKS2tXlFjM24ZF1Pdvcir-aywniInqg,1881\npip/_vendor/idna/package_data.py,sha256=C_jHJzmX8PI4xq0jpzmcTMxpb5lDsq4o5VyxQzlVrZE,21\npip/_vendor/idna/uts46data.py,sha256=zvjZU24s58_uAS850Mcd0NnD0X7_gCMAMjzWNIeUJdc,206539\npip/_vendor/msgpack/__init__.py,sha256=NryGaKLDk_Egd58ZxXpnuI7OWO27AXz7S6CBFRM3sAY,1132\npip/_vendor/msgpack/exceptions.py,sha256=dCTWei8dpkrMsQDcjQk74ATl9HsIBH0ybt8zOPNqMYc,1081\npip/_vendor/msgpack/ext.py,sha256=TuldJPkYu8Wo_Xh0tFGL2l06-gY88NSR8tOje9fo2Wg,6080\npip/_vendor/msgpack/fallback.py,sha256=OORDn86-fHBPlu-rPlMdM10KzkH6S_Rx9CHN1b7o4cg,34557\npip/_vendor/packaging/__about__.py,sha256=ugASIO2w1oUyH8_COqQ2X_s0rDhjbhQC3yJocD03h2c,661\npip/_vendor/packaging/__init__.py,sha256=b9Kk5MF7KxhhLgcDmiUWukN-LatWFxPdNug0joPhHSk,497\npip/_vendor/packaging/_manylinux.py,sha256=XcbiXB-qcjv3bcohp6N98TMpOP4_j3m-iOA8ptK2GWY,11488\npip/_vendor/packaging/_musllinux.py,sha256=_KGgY_qc7vhMGpoqss25n2hiLCNKRtvz9mCrS7gkqyc,4378\npip/_vendor/packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431\npip/_vendor/packaging/markers.py,sha256=AJBOcY8Oq0kYc570KuuPTkvuqjAlhufaE2c9sCUbm64,8487\npip/_vendor/packaging/requirements.py,sha256=NtDlPBtojpn1IUC85iMjPNsUmufjpSlwnNA-Xb4m5NA,4676\npip/_vendor/packaging/specifiers.py,sha256=LRQ0kFsHrl5qfcFNEEJrIFYsnIHQUJXY9fIsakTrrqE,30110\npip/_vendor/packaging/tags.py,sha256=lmsnGNiJ8C4D_Pf9PbM0qgbZvD9kmB9lpZBQUZa3R_Y,15699\npip/_vendor/packaging/utils.py,sha256=dJjeat3BS-TYn1RrUFVwufUMasbtzLfYRoy_HXENeFQ,4200\npip/_vendor/packaging/version.py,sha256=_fLRNrFrxYcHVfyo8vk9j8s6JM8N_xsSxVFr6RJyco8,14665\npip/_vendor/pep517/__init__.py,sha256=QJpRfzTpk6YSPgjcxp9-MCAiS5dEdzf9Bh0UXophG6c,130\npip/_vendor/pep517/_compat.py,sha256=by6evrYnqkisiM-MQcvOKs5bgDMzlOSgZqRHNqf04zE,138\npip/_vendor/pep517/build.py,sha256=VLtq0hOvNWCfX0FkdvTKEr-TmyrbaX0UqghpU7bHO1w,3443\npip/_vendor/pep517/check.py,sha256=o0Mp_PX1yOM2WNq1ZdDph3YA7RObj2UGQUCUF-46RaU,6083\npip/_vendor/pep517/colorlog.py,sha256=eCV1W52xzBjA-sOlKzUcvabRiFa11Y7hA791u-85_c8,3994\npip/_vendor/pep517/dirtools.py,sha256=JiZ1Hlt2LNaLZEhNa_pm1YyG3MUoRh7KxY6hJ8ac-w0,607\npip/_vendor/pep517/envbuild.py,sha256=nkTt1ZY7MXVgYOhPTyTr-VOxQ-q_Qc1touXfQgM56Bs,6081\npip/_vendor/pep517/meta.py,sha256=budDWsV3I2OnnpSvXQ_ycuTqxh8G7DABoazAq-j8OlQ,2520\npip/_vendor/pep517/wrappers.py,sha256=jcxIy-1Kl8I2xAZgbr6qNjF5b_6Q5gTndf9cxF0p5gM,12721\npip/_vendor/pep517/in_process/__init__.py,sha256=4yDanGyKTXQtLhqRo9eEZ1CsLFezEAEZMfqEd88xrvY,872\npip/_vendor/pep517/in_process/_in_process.py,sha256=JDpTxlKMDN1QfN_ey4IDtE6ZVSWtzP0_WLSqt1TyGaA,10801\npip/_vendor/pkg_resources/__init__.py,sha256=NnpQ3g6BCHzpMgOR_OLBmYtniY4oOzdKpwqghfq_6ug,108287\npip/_vendor/pkg_resources/py31compat.py,sha256=CRk8fkiPRDLsbi5pZcKsHI__Pbmh_94L8mr9Qy9Ab2U,562\npip/_vendor/platformdirs/__init__.py,sha256=x0aUmmovXXuRFVrVQBtwIiovX12B7rUkdV4F9UlLz0Y,12831\npip/_vendor/platformdirs/__main__.py,sha256=ZmsnTxEOxtTvwa-Y_Vfab_JN3X4XCVeN8X0yyy9-qnc,1176\npip/_vendor/platformdirs/android.py,sha256=GKizhyS7ESRiU67u8UnBJLm46goau9937EchXWbPBlk,4068\npip/_vendor/platformdirs/api.py,sha256=MXKHXOL3eh_-trSok-JUTjAR_zjmmKF3rjREVABjP8s,4910\npip/_vendor/platformdirs/macos.py,sha256=-3UXQewbT0yMhMdkzRXfXGAntmLIH7Qt4a9Hlf8I5_Y,2655\npip/_vendor/platformdirs/unix.py,sha256=b4aVYTz0qZ50HntwOXo8r6tp82jAa3qTjxw-WlnC2yc,6910\npip/_vendor/platformdirs/version.py,sha256=tsBKKPDX3LLh39yHXeTYauGRbRd-AmOJr9SwKldlFIU,78\npip/_vendor/platformdirs/windows.py,sha256=ISruopR5UGBePC0BxCxXevkZYfjJsIZc49YWU5iYfQ4,6439\npip/_vendor/pygments/__init__.py,sha256=5oLcMLXD0cTG8YcHBPITtK1fS0JBASILEvEnWkTezgE,2999\npip/_vendor/pygments/__main__.py,sha256=p0_rz3JZmNZMNZBOqDojaEx1cr9wmA9FQZX_TYl74lQ,353\npip/_vendor/pygments/cmdline.py,sha256=rc0fah4eknRqFgn1wKNEwkq0yWnSqYOGaA4PaIeOxVY,23685\npip/_vendor/pygments/console.py,sha256=hQfqCFuOlGk7DW2lPQYepsw-wkOH1iNt9ylNA1eRymM,1697\npip/_vendor/pygments/filter.py,sha256=NglMmMPTRRv-zuRSE_QbWid7JXd2J4AvwjCW2yWALXU,1938\npip/_vendor/pygments/formatter.py,sha256=6-TS2Y8pUMeWIUolWwr1O8ruC-U6HydWDwOdbAiJgJQ,2917\npip/_vendor/pygments/lexer.py,sha256=ZPB_TGn_qzrXodRFwEdPzzJk6LZBo9BlfSy3lacc6zg,32005\npip/_vendor/pygments/modeline.py,sha256=gIbMSYrjSWPk0oATz7W9vMBYkUyTK2OcdVyKjioDRvA,986\npip/_vendor/pygments/plugin.py,sha256=5rPxEoB_89qQMpOs0nI4KyLOzAHNlbQiwEMOKxqNmv8,2591\npip/_vendor/pygments/regexopt.py,sha256=c6xcXGpGgvCET_3VWawJJqAnOp0QttFpQEdOPNY2Py0,3072\npip/_vendor/pygments/scanner.py,sha256=F2T2G6cpkj-yZtzGQr-sOBw5w5-96UrJWveZN6va2aM,3092\npip/_vendor/pygments/sphinxext.py,sha256=F8L0211sPnXaiWutN0lkSUajWBwlgDMIEFFAbMWOvZY,4630\npip/_vendor/pygments/style.py,sha256=RRnussX1YiK9Z7HipIvKorImxu3-HnkdpPCO4u925T0,6257\npip/_vendor/pygments/token.py,sha256=vA2yNHGJBHfq4jNQSah7C9DmIOp34MmYHPA8P-cYAHI,6184\npip/_vendor/pygments/unistring.py,sha256=gP3gK-6C4oAFjjo9HvoahsqzuV4Qz0jl0E0OxfDerHI,63187\npip/_vendor/pygments/util.py,sha256=KgwpWWC3By5AiNwxGTI7oI9aXupH2TyZWukafBJe0Mg,9110\npip/_vendor/pygments/filters/__init__.py,sha256=b5YuXB9rampSy2-cMtKxGQoMDfrG4_DcvVwZrzTlB6w,40386\npip/_vendor/pygments/formatters/__init__.py,sha256=YTqGeHS17fNXCLMZpf7oCxBCKLB9YLsZ8IAsjGhawyg,4810\npip/_vendor/pygments/formatters/_mapping.py,sha256=fCZgvsM6UEuZUG7J6lr47eVss5owKd_JyaNbDfxeqmQ,4104\npip/_vendor/pygments/formatters/bbcode.py,sha256=JrL4ITjN-KzPcuQpPMBf1pm33eW2sDUNr8WzSoAJsJA,3314\npip/_vendor/pygments/formatters/groff.py,sha256=xrOFoLbafSA9uHsSLRogy79_Zc4GWJ8tMK2hCdTJRsw,5086\npip/_vendor/pygments/formatters/html.py,sha256=QNt9prPgxmbKx2M-nfDwoR1bIg06-sNouQuWnE434Wc,35441\npip/_vendor/pygments/formatters/img.py,sha256=h75Y7IRZLZxDEIwyoOsdRLTwm7kLVPbODKkgEiJ0iKI,21938\npip/_vendor/pygments/formatters/irc.py,sha256=iwk5tDJOxbCV64SCmOFyvk__x6RD60ay0nUn7ko9n7U,5871\npip/_vendor/pygments/formatters/latex.py,sha256=thPbytJCIs2AUXsO3NZwqKtXJ-upOlcXP4CXsx94G4w,19351\npip/_vendor/pygments/formatters/other.py,sha256=PczqK1Rms43lz6iucOLPeBMxIncPKOGBt-195w1ynII,5073\npip/_vendor/pygments/formatters/pangomarkup.py,sha256=ZZzMsKJKXrsDniFeMTkIpe7aQ4VZYRHu0idWmSiUJ2U,2212\npip/_vendor/pygments/formatters/rtf.py,sha256=abrKlWjipBkQvhIICxtjYTUNv6WME0iJJObFvqVuudE,5014\npip/_vendor/pygments/formatters/svg.py,sha256=6MM9YyO8NhU42RTQfTWBiagWMnsf9iG5gwhqSriHORE,7335\npip/_vendor/pygments/formatters/terminal.py,sha256=NpEGvwkC6LgMLQTjVzGrJXji3XcET1sb5JCunSCzoRo,4674\npip/_vendor/pygments/formatters/terminal256.py,sha256=4v4OVizvsxtwWBpIy_Po30zeOzE5oJg_mOc1-rCjMDk,11753\npip/_vendor/pygments/lexers/__init__.py,sha256=8d80-XfL5UKDCC1wRD1a_ZBZDkZ2HOe7Zul8SsnNYFE,11174\npip/_vendor/pygments/lexers/_mapping.py,sha256=zEiCV5FPiBioMJQJjw9kk7IJ5Y9GwknS4VJPYlcNchs,70232\npip/_vendor/pygments/lexers/python.py,sha256=gZROs9iNSOA18YyVghP1cUCD0OwYZ04a6PCwgSOCeSA,53376\npip/_vendor/pygments/styles/__init__.py,sha256=iZDZ7PBKb55SpGlE1--cx9cbmWx5lVTH4bXO87t2Vok,3419\npip/_vendor/pyparsing/__init__.py,sha256=ZPdI7pPo4IYXcABw-51AcqOzsxVvDtqnQbyn_qYWZvo,9171\npip/_vendor/pyparsing/actions.py,sha256=wU9i32e0y1ymxKE3OUwSHO-SFIrt1h_wv6Ws0GQjpNU,6426\npip/_vendor/pyparsing/common.py,sha256=lFL97ooIeR75CmW5hjURZqwDCTgruqltcTCZ-ulLO2Q,12936\npip/_vendor/pyparsing/core.py,sha256=AzTm1KFT1FIhiw2zvXZJmrpQoAwB0wOmeDCiR6SYytw,213344\npip/_vendor/pyparsing/exceptions.py,sha256=3LbSafD32NYb1Tzt85GHNkhEAU1eZkTtNSk24cPMemo,9023\npip/_vendor/pyparsing/helpers.py,sha256=QpUOjW0-psvueMwWb9bQpU2noqKCv98_wnw1VSzSdVo,39129\npip/_vendor/pyparsing/results.py,sha256=HgNvWVXBdQP-Q6PtJfoCEeOJk2nwEvG-2KVKC5sGA30,25341\npip/_vendor/pyparsing/testing.py,sha256=7tu4Abp4uSeJV0N_yEPRmmNUhpd18ZQP3CrX41DM814,13402\npip/_vendor/pyparsing/unicode.py,sha256=fwuhMj30SQ165Cv7HJpu-rSxGbRm93kN9L4Ei7VGc1Y,10787\npip/_vendor/pyparsing/util.py,sha256=kq772O5YSeXOSdP-M31EWpbH_ayj7BMHImBYo9xPD5M,6805\npip/_vendor/pyparsing/diagram/__init__.py,sha256=KW0PV_TvWKnL7jysz0pQbZ24nzWWu2ZfNaeyUIIywIg,23685\npip/_vendor/requests/__init__.py,sha256=3XN75ZS4slWy3TQsEGF7-Q6l2R146teU-s2_rXNhxhU,5178\npip/_vendor/requests/__version__.py,sha256=nJVa3ef2yRyeYMhy7yHnRyjjpnNTDykZsE4Sp9irBC4,440\npip/_vendor/requests/_internal_utils.py,sha256=aSPlF4uDhtfKxEayZJJ7KkAxtormeTfpwKSBSwtmAUw,1397\npip/_vendor/requests/adapters.py,sha256=GFEz5koZaMZD86v0SHXKVB5SE9MgslEjkCQzldkNwVM,21443\npip/_vendor/requests/api.py,sha256=dyvkDd5itC9z2g0wHl_YfD1yf6YwpGWLO7__8e21nks,6377\npip/_vendor/requests/auth.py,sha256=h-HLlVx9j8rKV5hfSAycP2ApOSglTz77R0tz7qCbbEE,10187\npip/_vendor/requests/certs.py,sha256=PVPooB0jP5hkZEULSCwC074532UFbR2Ptgu0I5zwmCs,575\npip/_vendor/requests/compat.py,sha256=IhK9quyX0RRuWTNcg6d2JGSAOUbM6mym2p_2XjLTwf4,1286\npip/_vendor/requests/cookies.py,sha256=kD3kNEcCj-mxbtf5fJsSaT86eGoEYpD3X0CSgpzl7BM,18560\npip/_vendor/requests/exceptions.py,sha256=FA-_kVwBZ2jhXauRctN_ewHVK25b-fj0Azyz1THQ0Kk,3823\npip/_vendor/requests/help.py,sha256=FnAAklv8MGm_qb2UilDQgS6l0cUttiCFKUjx0zn2XNA,3879\npip/_vendor/requests/hooks.py,sha256=CiuysiHA39V5UfcCBXFIx83IrDpuwfN9RcTUgv28ftQ,733\npip/_vendor/requests/models.py,sha256=GZRMMrGwDOLVvVfFHLUq0qTfIWDla3NcFHa1f5xs9Q8,35287\npip/_vendor/requests/packages.py,sha256=njJmVifY4aSctuW3PP5EFRCxjEwMRDO6J_feG2dKWsI,695\npip/_vendor/requests/sessions.py,sha256=KUqJcRRLovNefUs7ScOXSUVCcfSayTFWtbiJ7gOSlTI,30180\npip/_vendor/requests/status_codes.py,sha256=FvHmT5uH-_uimtRz5hH9VCbt7VV-Nei2J9upbej6j8g,4235\npip/_vendor/requests/structures.py,sha256=-IbmhVz06S-5aPSZuUthZ6-6D9XOjRuTXHOabY041XM,2912\npip/_vendor/requests/utils.py,sha256=0gzSOcx9Ya4liAbHnHuwt4jM78lzCZZoDFgkmsInNUg,33240\npip/_vendor/resolvelib/__init__.py,sha256=UL-B2BDI0_TRIqkfGwLHKLxY-LjBlomz7941wDqzB1I,537\npip/_vendor/resolvelib/providers.py,sha256=roVmFBItQJ0TkhNua65h8LdNny7rmeqVEXZu90QiP4o,5872\npip/_vendor/resolvelib/reporters.py,sha256=fW91NKf-lK8XN7i6Yd_rczL5QeOT3sc6AKhpaTEnP3E,1583\npip/_vendor/resolvelib/resolvers.py,sha256=2wYzVGBGerbmcIpH8cFmgSKgLSETz8jmwBMGjCBMHG4,17592\npip/_vendor/resolvelib/structs.py,sha256=IVIYof6sA_N4ZEiE1C1UhzTX495brCNnyCdgq6CYq28,4794\npip/_vendor/resolvelib/compat/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/resolvelib/compat/collections_abc.py,sha256=uy8xUZ-NDEw916tugUXm8HgwCGiMO0f-RcdnpkfXfOs,156\npip/_vendor/rich/__init__.py,sha256=zREyQ22R3zKg8gMdhiikczdVQYtZNeayHNrbBg5scm0,5944\npip/_vendor/rich/__main__.py,sha256=BmTmBWI93ytq75IEPi1uAAdeRYzFfDbgaAXjsX1ogig,8808\npip/_vendor/rich/_cell_widths.py,sha256=2n4EiJi3X9sqIq0O16kUZ_zy6UYMd3xFfChlKfnW1Hc,10096\npip/_vendor/rich/_emoji_codes.py,sha256=hu1VL9nbVdppJrVoijVshRlcRRe_v3dju3Mmd2sKZdY,140235\npip/_vendor/rich/_emoji_replace.py,sha256=n-kcetsEUx2ZUmhQrfeMNc-teeGhpuSQ5F8VPBsyvDo,1064\npip/_vendor/rich/_export_format.py,sha256=nHArqOljIlYn6NruhWsAsh-fHo7oJC3y9BDJyAa-QYQ,2114\npip/_vendor/rich/_extension.py,sha256=Xt47QacCKwYruzjDi-gOBq724JReDj9Cm9xUi5fr-34,265\npip/_vendor/rich/_inspect.py,sha256=oZJGw31e64dwXSCmrDnvZbwVb1ZKhWfU8wI3VWohjJk,9695\npip/_vendor/rich/_log_render.py,sha256=1ByI0PA1ZpxZY3CGJOK54hjlq4X-Bz_boIjIqCd8Kns,3225\npip/_vendor/rich/_loop.py,sha256=hV_6CLdoPm0va22Wpw4zKqM0RYsz3TZxXj0PoS-9eDQ,1236\npip/_vendor/rich/_palettes.py,sha256=cdev1JQKZ0JvlguV9ipHgznTdnvlIzUFDBb0It2PzjI,7063\npip/_vendor/rich/_pick.py,sha256=evDt8QN4lF5CiwrUIXlOJCntitBCOsI3ZLPEIAVRLJU,423\npip/_vendor/rich/_ratio.py,sha256=2lLSliL025Y-YMfdfGbutkQDevhcyDqc-DtUYW9mU70,5472\npip/_vendor/rich/_spinners.py,sha256=U2r1_g_1zSjsjiUdAESc2iAMc3i4ri_S8PYP6kQ5z1I,19919\npip/_vendor/rich/_stack.py,sha256=-C8OK7rxn3sIUdVwxZBBpeHhIzX0eI-VM3MemYfaXm0,351\npip/_vendor/rich/_timer.py,sha256=zelxbT6oPFZnNrwWPpc1ktUeAT-Vc4fuFcRZLQGLtMI,417\npip/_vendor/rich/_win32_console.py,sha256=P0vxI2fcndym1UU1S37XAzQzQnkyY7YqAKmxm24_gug,22820\npip/_vendor/rich/_windows.py,sha256=dvNl9TmfPzNVxiKk5WDFihErZ5796g2UC9-KGGyfXmk,1926\npip/_vendor/rich/_windows_renderer.py,sha256=t74ZL3xuDCP3nmTp9pH1L5LiI2cakJuQRQleHCJerlk,2783\npip/_vendor/rich/_wrap.py,sha256=xfV_9t0Sg6rzimmrDru8fCVmUlalYAcHLDfrJZnbbwQ,1840\npip/_vendor/rich/abc.py,sha256=ON-E-ZqSSheZ88VrKX2M3PXpFbGEUUZPMa_Af0l-4f0,890\npip/_vendor/rich/align.py,sha256=FV6_GS-8uhIyViMng3hkIWSFaTgMohK1Oqyjl8I8mGE,10368\npip/_vendor/rich/ansi.py,sha256=HtaPG7dvgL6_yo0sQmx5CM05DJ4_1goY5SWXXOYNaKs,6820\npip/_vendor/rich/bar.py,sha256=a7UD303BccRCrEhGjfMElpv5RFYIinaAhAuqYqhUvmw,3264\npip/_vendor/rich/box.py,sha256=1Iv1sUWqjtp5XwLwGH-AJ8HgyXZ7dRFUkO0z3M_bRl8,9864\npip/_vendor/rich/cells.py,sha256=zMjFI15wCpgjLR14lHdfFMVC6qMDi5OsKIB0PYZBBMk,4503\npip/_vendor/rich/color.py,sha256=kp87L8V4-3qayE6CUxtW_nP8Ujfew_-DAhNwYMXBMOY,17957\npip/_vendor/rich/color_triplet.py,sha256=3lhQkdJbvWPoLDO-AnYImAWmJvV5dlgYNCVZ97ORaN4,1054\npip/_vendor/rich/columns.py,sha256=HUX0KcMm9dsKNi11fTbiM_h2iDtl8ySCaVcxlalEzq8,7131\npip/_vendor/rich/console.py,sha256=bTT9DNX03V4cQXefg22d-gLSs_e_ZY2zdCvLIlEyU2Q,95885\npip/_vendor/rich/constrain.py,sha256=1VIPuC8AgtKWrcncQrjBdYqA3JVWysu6jZo1rrh7c7Q,1288\npip/_vendor/rich/containers.py,sha256=aKgm5UDHn5Nmui6IJaKdsZhbHClh_X7D-_Wg8Ehrr7s,5497\npip/_vendor/rich/control.py,sha256=DSkHTUQLorfSERAKE_oTAEUFefZnZp4bQb4q8rHbKws,6630\npip/_vendor/rich/default_styles.py,sha256=WqVh-RPNEsx0Wxf3fhS_fCn-wVqgJ6Qfo-Zg7CoCsLE,7954\npip/_vendor/rich/diagnose.py,sha256=an6uouwhKPAlvQhYpNNpGq9EJysfMIOvvCbO3oSoR24,972\npip/_vendor/rich/emoji.py,sha256=omTF9asaAnsM4yLY94eR_9dgRRSm1lHUszX20D1yYCQ,2501\npip/_vendor/rich/errors.py,sha256=5pP3Kc5d4QJ_c0KFsxrfyhjiPVe7J1zOqSFbFAzcV-Y,642\npip/_vendor/rich/file_proxy.py,sha256=4gCbGRXg0rW35Plaf0UVvj3dfENHuzc_n8I_dBqxI7o,1616\npip/_vendor/rich/filesize.py,sha256=yShoVpARafJBreyZFaAhC4OhnJ6ydC1WXR-Ez4wU_YQ,2507\npip/_vendor/rich/highlighter.py,sha256=3WW6PACGlq0e3YDjfqiMBQ0dYZwu7pcoFYUgJy01nb0,9585\npip/_vendor/rich/json.py,sha256=RCm4lXBXrjvXHpqrWPH8wdGP0jEo4IohLmkddlhRY18,5051\npip/_vendor/rich/jupyter.py,sha256=QyoKoE_8IdCbrtiSHp9TsTSNyTHY0FO5whE7jOTd9UE,3252\npip/_vendor/rich/layout.py,sha256=E3xJ4fomizUADwime3VA0lBXoMSPl9blEokIzVBjO0Q,14074\npip/_vendor/rich/live.py,sha256=emVaLUua-FKSYqZXmtJJjBIstO99CqMOuA6vMAKVkO0,14172\npip/_vendor/rich/live_render.py,sha256=zElm3PrfSIvjOce28zETHMIUf9pFYSUA5o0AflgUP64,3667\npip/_vendor/rich/logging.py,sha256=10j13lPr-QuYqEEBz_2aRJp8gNYvSN2wmCUlUqJcPLM,11471\npip/_vendor/rich/markup.py,sha256=xzF4uAafiEeEYDJYt_vUnJOGoTU8RrH-PH7WcWYXjCg,8198\npip/_vendor/rich/measure.py,sha256=HmrIJX8sWRTHbgh8MxEay_83VkqNW_70s8aKP5ZcYI8,5305\npip/_vendor/rich/padding.py,sha256=kTFGsdGe0os7tXLnHKpwTI90CXEvrceeZGCshmJy5zw,4970\npip/_vendor/rich/pager.py,sha256=SO_ETBFKbg3n_AgOzXm41Sv36YxXAyI3_R-KOY2_uSc,828\npip/_vendor/rich/palette.py,sha256=lInvR1ODDT2f3UZMfL1grq7dY_pDdKHw4bdUgOGaM4Y,3396\npip/_vendor/rich/panel.py,sha256=CzdojkDAjxAKgvDxis47nWzUh1V2NniOqkJJQajosG8,8744\npip/_vendor/rich/pretty.py,sha256=CalVLVW3mvTn1hvI9Pgi2v-y4S-5zUWBK-PH7SlVs-U,36576\npip/_vendor/rich/progress.py,sha256=zjQRwd3TmDnAvSjTPsNPHFjmqE9GOEX3bf0Lj56hIL8,59746\npip/_vendor/rich/progress_bar.py,sha256=zHHaFPEfIhW2fq6Fnl5vBY7AUpP1N0HVGElISUHsnqw,8161\npip/_vendor/rich/prompt.py,sha256=x0mW-pIPodJM4ry6grgmmLrl8VZp99kqcmdnBe70YYA,11303\npip/_vendor/rich/protocol.py,sha256=5hHHDDNHckdk8iWH5zEbi-zuIVSF5hbU2jIo47R7lTE,1391\npip/_vendor/rich/region.py,sha256=rNT9xZrVZTYIXZC0NYn41CJQwYNbR-KecPOxTgQvB8Y,166\npip/_vendor/rich/repr.py,sha256=Je91CIrZN_av9L3FRCKCs5yoX2LvczrCNKqUbVsjUvQ,4449\npip/_vendor/rich/rule.py,sha256=V6AWI0wCb6DB0rvN967FRMlQrdlG7HoZdfEAHyeG8CM,4773\npip/_vendor/rich/scope.py,sha256=HX13XsJfqzQHpPfw4Jn9JmJjCsRj9uhHxXQEqjkwyLA,2842\npip/_vendor/rich/screen.py,sha256=YoeReESUhx74grqb0mSSb9lghhysWmFHYhsbMVQjXO8,1591\npip/_vendor/rich/segment.py,sha256=6XdX0MfL18tUCaUWDWncIqx0wpq3GiaqzhYP779JvRA,24224\npip/_vendor/rich/spinner.py,sha256=7b8MCleS4fa46HX0AzF98zfu6ZM6fAL0UgYzPOoakF4,4374\npip/_vendor/rich/status.py,sha256=gJsIXIZeSo3urOyxRUjs6VrhX5CZrA0NxIQ-dxhCnwo,4425\npip/_vendor/rich/style.py,sha256=4WnUEkHNMp9Tfmd8cmbxWGby7QeTk2LUTQzFSs46EQc,26240\npip/_vendor/rich/styled.py,sha256=eZNnzGrI4ki_54pgY3Oj0T-x3lxdXTYh4_ryDB24wBU,1258\npip/_vendor/rich/syntax.py,sha256=_M08KbE11nNWNBPooFLKAA7lWkThPzlGUsuesxQYsuA,34697\npip/_vendor/rich/table.py,sha256=r_lahmj45cINCWLYaIjq9yEv3gve8E6bkYTP8NDqApE,39515\npip/_vendor/rich/terminal_theme.py,sha256=1j5-ufJfnvlAo5Qsi_ACZiXDmwMXzqgmFByObT9-yJY,3370\npip/_vendor/rich/text.py,sha256=oajdGIeHcLcSdOwbC48_20ylDsHAS5fsPZD_Ih0clyA,44666\npip/_vendor/rich/theme.py,sha256=GKNtQhDBZKAzDaY0vQVQQFzbc0uWfFe6CJXA-syT7zQ,3627\npip/_vendor/rich/themes.py,sha256=0xgTLozfabebYtcJtDdC5QkX5IVUEaviqDUJJh4YVFk,102\npip/_vendor/rich/traceback.py,sha256=MORQpXH7AvhAAThW8oIbtwffXb8M6XRkSkcJ52JuA3g,26060\npip/_vendor/rich/tree.py,sha256=BMbUYNjS9uodNPfvtY_odmU09GA5QzcMbQ5cJZhllQI,9169\npip/_vendor/tenacity/__init__.py,sha256=rjcWJVq5PcNJNC42rt-TAGGskM-RUEkZbDKu1ra7IPo,18364\npip/_vendor/tenacity/_asyncio.py,sha256=HEb0BVJEeBJE9P-m9XBxh1KcaF96BwoeqkJCL5sbVcQ,3314\npip/_vendor/tenacity/_utils.py,sha256=-y68scDcyoqvTJuJJ0GTfjdSCljEYlbCYvgk7nM4NdM,1944\npip/_vendor/tenacity/after.py,sha256=dlmyxxFy2uqpLXDr838DiEd7jgv2AGthsWHGYcGYsaI,1496\npip/_vendor/tenacity/before.py,sha256=7XtvRmO0dRWUp8SVn24OvIiGFj8-4OP5muQRUiWgLh0,1376\npip/_vendor/tenacity/before_sleep.py,sha256=ThyDvqKU5yle_IvYQz_b6Tp6UjUS0PhVp6zgqYl9U6Y,1908\npip/_vendor/tenacity/nap.py,sha256=fRWvnz1aIzbIq9Ap3gAkAZgDH6oo5zxMrU6ZOVByq0I,1383\npip/_vendor/tenacity/retry.py,sha256=Cy504Ss3UrRV7lnYgvymF66WD1wJ2dbM869kDcjuDes,7550\npip/_vendor/tenacity/stop.py,sha256=sKHmHaoSaW6sKu3dTxUVKr1-stVkY7lw4Y9yjZU30zQ,2790\npip/_vendor/tenacity/tornadoweb.py,sha256=E8lWO2nwe6dJgoB-N2HhQprYLDLB_UdSgFnv-EN6wKE,2145\npip/_vendor/tenacity/wait.py,sha256=tdLTESRm5E237VHG0SxCDXRa0DHKPKVq285kslHVURc,8011\npip/_vendor/tomli/__init__.py,sha256=JhUwV66DB1g4Hvt1UQCVMdfCu-IgAV8FXmvDU9onxd4,396\npip/_vendor/tomli/_parser.py,sha256=g9-ENaALS-B8dokYpCuzUFalWlog7T-SIYMjLZSWrtM,22633\npip/_vendor/tomli/_re.py,sha256=dbjg5ChZT23Ka9z9DHOXfdtSpPwUfdgMXnj8NOoly-w,2943\npip/_vendor/tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254\npip/_vendor/urllib3/__init__.py,sha256=iXLcYiJySn0GNbWOOZDDApgBL1JgP44EZ8i1760S8Mc,3333\npip/_vendor/urllib3/_collections.py,sha256=Rp1mVyBgc_UlAcp6M3at1skJBXR5J43NawRTvW2g_XY,10811\npip/_vendor/urllib3/_version.py,sha256=GhuGBUT_MtRxHEHDb-LYs5yLPeYWlCwFBPjGZmVJbVg,64\npip/_vendor/urllib3/connection.py,sha256=8976wL6sGeVMW0JnXvx5mD00yXu87uQjxtB9_VL8dx8,20070\npip/_vendor/urllib3/connectionpool.py,sha256=vEzk1iJEw1qR2vHBo7m3Y98iDfna6rKkUz3AyK5lJKQ,39093\npip/_vendor/urllib3/exceptions.py,sha256=0Mnno3KHTNfXRfY7638NufOPkUb6mXOm-Lqj-4x2w8A,8217\npip/_vendor/urllib3/fields.py,sha256=kvLDCg_JmH1lLjUUEY_FLS8UhY7hBvDPuVETbY8mdrM,8579\npip/_vendor/urllib3/filepost.py,sha256=5b_qqgRHVlL7uLtdAYBzBh-GHmU5AfJVt_2N0XS3PeY,2440\npip/_vendor/urllib3/poolmanager.py,sha256=0KOOJECoeLYVjUHvv-0h4Oq3FFQQ2yb-Fnjkbj8gJO0,19786\npip/_vendor/urllib3/request.py,sha256=ZFSIqX0C6WizixecChZ3_okyu7BEv0lZu1VT0s6h4SM,5985\npip/_vendor/urllib3/response.py,sha256=p3VBYPhwBca77wCZfmoXvEDVVC3SdF7yxQ6TXuxy1BI,30109\npip/_vendor/urllib3/contrib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/urllib3/contrib/_appengine_environ.py,sha256=bDbyOEhW2CKLJcQqAKAyrEHN-aklsyHFKq6vF8ZFsmk,957\npip/_vendor/urllib3/contrib/appengine.py,sha256=lfzpHFmJiO82shClLEm3QB62SYgHWnjpZOH_2JhU5Tc,11034\npip/_vendor/urllib3/contrib/ntlmpool.py,sha256=ej9gGvfAb2Gt00lafFp45SIoRz-QwrQ4WChm6gQmAlM,4538\npip/_vendor/urllib3/contrib/pyopenssl.py,sha256=rt9NEIP8iMBLxxRhH0jLnmshW-OFP83jEayxMSqu2MU,17182\npip/_vendor/urllib3/contrib/securetransport.py,sha256=yhZdmVjY6PI6EeFbp7qYOp6-vp1Rkv2NMuOGaEj7pmc,34448\npip/_vendor/urllib3/contrib/socks.py,sha256=aRi9eWXo9ZEb95XUxef4Z21CFlnnjbEiAo9HOseoMt4,7097\npip/_vendor/urllib3/contrib/_securetransport/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/urllib3/contrib/_securetransport/bindings.py,sha256=4Xk64qIkPBt09A5q-RIFUuDhNc9mXilVapm7WnYnzRw,17632\npip/_vendor/urllib3/contrib/_securetransport/low_level.py,sha256=B2JBB2_NRP02xK6DCa1Pa9IuxrPwxzDzZbixQkb7U9M,13922\npip/_vendor/urllib3/packages/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/urllib3/packages/six.py,sha256=b9LM0wBXv7E7SrbCjAm4wwN-hrH-iNxv18LgWNMMKPo,34665\npip/_vendor/urllib3/packages/backports/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npip/_vendor/urllib3/packages/backports/makefile.py,sha256=nbzt3i0agPVP07jqqgjhaYjMmuAi_W5E0EywZivVO8E,1417\npip/_vendor/urllib3/util/__init__.py,sha256=JEmSmmqqLyaw8P51gUImZh8Gwg9i1zSe-DoqAitn2nc,1155\npip/_vendor/urllib3/util/connection.py,sha256=5Lx2B1PW29KxBn2T0xkN1CBgRBa3gGVJBKoQoRogEVk,4901\npip/_vendor/urllib3/util/proxy.py,sha256=zUvPPCJrp6dOF0N4GAVbOcl6o-4uXKSrGiTkkr5vUS4,1605\npip/_vendor/urllib3/util/queue.py,sha256=nRgX8_eX-_VkvxoX096QWoz8Ps0QHUAExILCY_7PncM,498\npip/_vendor/urllib3/util/request.py,sha256=C0OUt2tcU6LRiQJ7YYNP9GvPrSvl7ziIBekQ-5nlBZk,3997\npip/_vendor/urllib3/util/response.py,sha256=GJpg3Egi9qaJXRwBh5wv-MNuRWan5BIu40oReoxWP28,3510\npip/_vendor/urllib3/util/retry.py,sha256=iESg2PvViNdXBRY4MpL4h0kqwOOkHkxmLn1kkhFHPU8,22001\npip/_vendor/urllib3/util/ssl_.py,sha256=X4-AqW91aYPhPx6-xbf66yHFQKbqqfC_5Zt4WkLX1Hc,17177\npip/_vendor/urllib3/util/ssl_match_hostname.py,sha256=Ir4cZVEjmAk8gUAIHWSi7wtOO83UCYABY2xFD1Ql_WA,5758\npip/_vendor/urllib3/util/ssltransport.py,sha256=NA-u5rMTrDFDFC8QzRKUEKMG0561hOD4qBTr3Z4pv6E,6895\npip/_vendor/urllib3/util/timeout.py,sha256=QSbBUNOB9yh6AnDn61SrLQ0hg5oz0I9-uXEG91AJuIg,10003\npip/_vendor/urllib3/util/url.py,sha256=49HwObaTUUjqVe4qvSUvIjZyf3ghgNA6-OLm3kmkFKM,14287\npip/_vendor/urllib3/util/wait.py,sha256=fOX0_faozG2P7iVojQoE1mbydweNyTcm-hXEfFrTtLI,5403\npip/_vendor/webencodings/__init__.py,sha256=qOBJIuPy_4ByYH6W_bNgJF-qYQ2DoU-dKsDu5yRWCXg,10579\npip/_vendor/webencodings/labels.py,sha256=4AO_KxTddqGtrL9ns7kAPjb0CcN6xsCIxbK37HY9r3E,8979\npip/_vendor/webencodings/mklabels.py,sha256=GYIeywnpaLnP0GSic8LFWgd0UVvO_l1Nc6YoF-87R_4,1305\npip/_vendor/webencodings/tests.py,sha256=OtGLyjhNY1fvkW1GvLJ_FV9ZoqC9Anyjr7q3kxTbzNs,6563\npip/_vendor/webencodings/x_user_defined.py,sha256=yOqWSdmpytGfUgh_Z6JYgDNhoc-BAHyyeeT15Fr42tM,4307\npip-22.3.1.dist-info/LICENSE.txt,sha256=Y0MApmnUmurmWxLGxIySTFGkzfPR_whtw0VtyLyqIQQ,1093\npip-22.3.1.dist-info/METADATA,sha256=a9COYc5qzklDgbGlrKYkypMXon4A6IDgpeUTWLr7zzY,4072\npip-22.3.1.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92\npip-22.3.1.dist-info/entry_points.txt,sha256=ynZN1_707_L23Oa8_O5LOxEoccj1nDa4xHT5galfN7o,125\npip-22.3.1.dist-info/top_level.txt,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4\npip-22.3.1.dist-info/RECORD,,\npip/_vendor/pep517/check.cpython-37.pyc,,\npip/_internal/network/download.cpython-37.pyc,,\npip/_vendor/pygments/__init__.cpython-37.pyc,,\npip/_internal/configuration.cpython-37.pyc,,\npip/_vendor/chardet/hebrewprober.cpython-37.pyc,,\npip/_vendor/pygments/lexer.cpython-37.pyc,,\npip/_vendor/chardet/mbcssm.cpython-37.pyc,,\npip/_vendor/urllib3/contrib/__pycache__,,\npip/_internal/cli/status_codes.cpython-37.pyc,,\npip/_internal/resolution/resolvelib/factory.cpython-37.pyc,,\npip/_vendor/tenacity/__pycache__,,\npip/_vendor/platformdirs/__init__.cpython-37.pyc,,\npip/_internal/network/__init__.cpython-37.pyc,,\npip/_vendor/resolvelib/__pycache__,,\npip/_vendor/chardet/sbcharsetprober.cpython-37.pyc,,\npip/_vendor/distro/distro.cpython-37.pyc,,\npip/_internal/vcs/git.cpython-37.pyc,,\npip/_internal/commands/cache.cpython-37.pyc,,\npip/_vendor/rich/constrain.cpython-37.pyc,,\npip/_internal/utils/direct_url_helpers.cpython-37.pyc,,\npip/_vendor/chardet/gb2312freq.cpython-37.pyc,,\npip/_internal/req/req_install.cpython-37.pyc,,\n../../../bin/pip3.7,,\npip/_vendor/platformdirs/unix.cpython-37.pyc,,\npip/_internal/models/selection_prefs.cpython-37.pyc,,\npip/_vendor/chardet/__init__.cpython-37.pyc,,\npip/_vendor/distlib/wheel.cpython-37.pyc,,\npip/_vendor/chardet/langhungarianmodel.cpython-37.pyc,,\npip/_internal/distributions/wheel.cpython-37.pyc,,\npip/_vendor/pep517/__pycache__,,\npip/_vendor/urllib3/fields.cpython-37.pyc,,\npip/_vendor/msgpack/exceptions.cpython-37.pyc,,\npip/_vendor/certifi/__pycache__,,\npip/_internal/distributions/__init__.cpython-37.pyc,,\npip/_vendor/urllib3/util/queue.cpython-37.pyc,,\npip/_vendor/chardet/mbcsgroupprober.cpython-37.pyc,,\npip/_vendor/requests/auth.cpython-37.pyc,,\npip/_vendor/webencodings/__init__.cpython-37.pyc,,\npip/_vendor/packaging/utils.cpython-37.pyc,,\npip/_vendor/chardet/langthaimodel.cpython-37.pyc,,\npip/_vendor/pep517/_compat.cpython-37.pyc,,\npip/_vendor/distlib/markers.cpython-37.pyc,,\npip/_vendor/rich/logging.cpython-37.pyc,,\npip/_vendor/pygments/formatters/other.cpython-37.pyc,,\npip/_internal/req/__init__.cpython-37.pyc,,\npip/_internal/operations/build/metadata_legacy.cpython-37.pyc,,\npip/_vendor/msgpack/ext.cpython-37.pyc,,\npip/_vendor/pep517/in_process/__pycache__,,\npip/_vendor/tomli/__init__.cpython-37.pyc,,\npip/_vendor/rich/_timer.cpython-37.pyc,,\npip/_internal/build_env.cpython-37.pyc,,\npip/_internal/models/scheme.cpython-37.pyc,,\npip/_vendor/tenacity/after.cpython-37.pyc,,\npip/_vendor/rich/prompt.cpython-37.pyc,,\npip/_vendor/rich/styled.cpython-37.pyc,,\npip/_vendor/urllib3/_version.cpython-37.pyc,,\npip/_vendor/idna/core.cpython-37.pyc,,\npip/_vendor/chardet/big5prober.cpython-37.pyc,,\npip/_vendor/rich/default_styles.cpython-37.pyc,,\npip/_vendor/chardet/sbcsgroupprober.cpython-37.pyc,,\npip/_vendor/packaging/__pycache__,,\npip/_vendor/rich/_win32_console.cpython-37.pyc,,\npip/_internal/metadata/importlib/_compat.cpython-37.pyc,,\npip/_vendor/rich/padding.cpython-37.pyc,,\npip/_vendor/urllib3/poolmanager.cpython-37.pyc,,\npip/_internal/commands/download.cpython-37.pyc,,\npip/_internal/index/__init__.cpython-37.pyc,,\npip/_vendor/pep517/dirtools.cpython-37.pyc,,\npip/_vendor/rich/_extension.cpython-37.pyc,,\npip/_internal/req/req_set.cpython-37.pyc,,\npip/_internal/commands/__init__.cpython-37.pyc,,\npip/_vendor/pyparsing/common.cpython-37.pyc,,\npip/_vendor/pep517/__init__.cpython-37.pyc,,\npip/_internal/utils/temp_dir.cpython-37.pyc,,\npip/_internal/resolution/resolvelib/provider.cpython-37.pyc,,\npip/_vendor/cachecontrol/caches/__pycache__,,\npip/_vendor/chardet/metadata/languages.cpython-37.pyc,,\npip/_vendor/pygments/formatters/latex.cpython-37.pyc,,\npip/_vendor/rich/segment.cpython-37.pyc,,\npip/_vendor/webencodings/mklabels.cpython-37.pyc,,\npip/_vendor/rich/live.cpython-37.pyc,,\npip/_internal/cli/main_parser.cpython-37.pyc,,\npip/_vendor/rich/pager.cpython-37.pyc,,\npip/_vendor/chardet/langbulgarianmodel.cpython-37.pyc,,\npip/_vendor/distlib/manifest.cpython-37.pyc,,\npip/_vendor/rich/themes.cpython-37.pyc,,\npip/_vendor/webencodings/labels.cpython-37.pyc,,\npip/_vendor/chardet/big5freq.cpython-37.pyc,,\npip/_vendor/packaging/version.cpython-37.pyc,,\npip/_vendor/__pycache__,,\npip-22.3.1.dist-info/INSTALLER,,\npip/_vendor/urllib3/contrib/_securetransport/__pycache__,,\npip/_vendor/urllib3/util/ssl_.cpython-37.pyc,,\npip/_vendor/colorama/win32.cpython-37.pyc,,\npip/_vendor/urllib3/util/__init__.cpython-37.pyc,,\npip/_vendor/requests/__version__.cpython-37.pyc,,\npip/_vendor/rich/scope.cpython-37.pyc,,\npip/_internal/network/lazy_wheel.cpython-37.pyc,,\npip/_vendor/rich/color_triplet.cpython-37.pyc,,\npip/_vendor/rich/abc.cpython-37.pyc,,\npip/_internal/metadata/pkg_resources.cpython-37.pyc,,\npip/_vendor/urllib3/packages/backports/makefile.cpython-37.pyc,,\npip/_internal/resolution/resolvelib/__pycache__,,\npip/_internal/utils/wheel.cpython-37.pyc,,\npip/_vendor/colorama/__pycache__,,\npip/_internal/models/wheel.cpython-37.pyc,,\npip/_vendor/pygments/formatters/_mapping.cpython-37.pyc,,\npip/_internal/utils/encoding.cpython-37.pyc,,\npip/_vendor/pygments/formatters/irc.cpython-37.pyc,,\npip/_vendor/rich/console.cpython-37.pyc,,\n../../../bin/pip,,\npip/_vendor/chardet/langturkishmodel.cpython-37.pyc,,\npip/_vendor/urllib3/_collections.cpython-37.pyc,,\npip/_vendor/requests/hooks.cpython-37.pyc,,\npip/_vendor/rich/cells.cpython-37.pyc,,\npip/_vendor/pygments/__pycache__,,\npip/_internal/resolution/legacy/__pycache__,,\npip/_vendor/cachecontrol/serialize.cpython-37.pyc,,\npip/_internal/commands/show.cpython-37.pyc,,\npip/_vendor/rich/markup.cpython-37.pyc,,\npip/_vendor/rich/_emoji_replace.cpython-37.pyc,,\npip/_vendor/tenacity/_asyncio.cpython-37.pyc,,\npip/_vendor/pyparsing/exceptions.cpython-37.pyc,,\npip/_internal/cli/req_command.cpython-37.pyc,,\npip/_vendor/urllib3/util/ssl_match_hostname.cpython-37.pyc,,\npip/_internal/utils/distutils_args.cpython-37.pyc,,\npip/_vendor/tenacity/__init__.cpython-37.pyc,,\npip/_vendor/urllib3/contrib/socks.cpython-37.pyc,,\npip/_internal/resolution/__pycache__,,\npip/_internal/utils/urls.cpython-37.pyc,,\npip/_internal/utils/logging.cpython-37.pyc,,\npip/_vendor/chardet/euctwprober.cpython-37.pyc,,\npip/_internal/distributions/installed.cpython-37.pyc,,\npip/_vendor/distlib/__init__.cpython-37.pyc,,\npip/_vendor/urllib3/__init__.cpython-37.pyc,,\npip/_vendor/requests/exceptions.cpython-37.pyc,,\npip/_internal/cli/base_command.cpython-37.pyc,,\npip/_vendor/chardet/enums.cpython-37.pyc,,\npip/_internal/utils/inject_securetransport.cpython-37.pyc,,\npip/_vendor/pep517/meta.cpython-37.pyc,,\npip/_vendor/packaging/_manylinux.cpython-37.pyc,,\npip/_vendor/urllib3/util/proxy.cpython-37.pyc,,\npip/_internal/models/__pycache__,,\npip/_vendor/chardet/euctwfreq.cpython-37.pyc,,\npip/_vendor/pygments/formatters/terminal256.cpython-37.pyc,,\npip/_vendor/urllib3/contrib/appengine.cpython-37.pyc,,\npip/_vendor/pygments/lexers/__pycache__,,\npip/_vendor/packaging/requirements.cpython-37.pyc,,\npip/_vendor/pygments/token.cpython-37.pyc,,\npip/_vendor/chardet/euckrprober.cpython-37.pyc,,\npip/_vendor/chardet/__pycache__,,\npip/_internal/network/cache.cpython-37.pyc,,\npip/_vendor/idna/compat.cpython-37.pyc,,\npip/_vendor/distlib/index.cpython-37.pyc,,\npip/_vendor/colorama/__init__.cpython-37.pyc,,\npip/_internal/req/req_file.cpython-37.pyc,,\npip/_internal/utils/subprocess.cpython-37.pyc,,\npip/_internal/distributions/__pycache__,,\npip/_internal/commands/check.cpython-37.pyc,,\npip/_vendor/rich/align.cpython-37.pyc,,\npip/_vendor/requests/help.cpython-37.pyc,,\npip/_internal/self_outdated_check.cpython-37.pyc,,\npip/_vendor/tenacity/before.cpython-37.pyc,,\npip/_internal/resolution/resolvelib/base.cpython-37.pyc,,\npip/_vendor/pep517/wrappers.cpython-37.pyc,,\npip/_vendor/urllib3/util/connection.cpython-37.pyc,,\npip/_vendor/chardet/sjisprober.cpython-37.pyc,,\npip/_internal/operations/install/legacy.cpython-37.pyc,,\npip/_internal/commands/inspect.cpython-37.pyc,,\npip/_vendor/pygments/formatters/groff.cpython-37.pyc,,\npip/_internal/models/format_control.cpython-37.pyc,,\npip/_internal/network/auth.cpython-37.pyc,,\npip/_vendor/distlib/util.cpython-37.pyc,,\npip/_vendor/pyparsing/results.cpython-37.pyc,,\npip/_vendor/pyparsing/diagram/__pycache__,,\npip/_vendor/urllib3/response.cpython-37.pyc,,\npip/_vendor/distlib/locators.cpython-37.pyc,,\npip/_internal/utils/appdirs.cpython-37.pyc,,\npip/_vendor/rich/rule.cpython-37.pyc,,\npip/_vendor/pyparsing/unicode.cpython-37.pyc,,\npip/_internal/operations/build/wheel.cpython-37.pyc,,\npip/_vendor/__init__.cpython-37.pyc,,\npip/_vendor/pkg_resources/__init__.cpython-37.pyc,,\npip/_internal/utils/unpacking.cpython-37.pyc,,\npip/_vendor/rich/_export_format.cpython-37.pyc,,\npip/_vendor/colorama/ansi.cpython-37.pyc,,\npip/_vendor/pep517/in_process/__init__.cpython-37.pyc,,\npip/_vendor/distlib/scripts.cpython-37.pyc,,\npip/_vendor/rich/highlighter.cpython-37.pyc,,\npip/_vendor/distlib/version.cpython-37.pyc,,\npip/__main__.cpython-37.pyc,,\npip/_vendor/rich/containers.cpython-37.pyc,,\npip/_vendor/chardet/codingstatemachine.cpython-37.pyc,,\npip/_vendor/platformdirs/version.cpython-37.pyc,,\npip/_vendor/rich/_windows_renderer.cpython-37.pyc,,\npip/_vendor/pygments/formatters/__pycache__,,\npip/_internal/exceptions.cpython-37.pyc,,\npip/_vendor/chardet/chardistribution.cpython-37.pyc,,\npip/_vendor/platformdirs/macos.cpython-37.pyc,,\npip/_vendor/pygments/formatters/svg.cpython-37.pyc,,\npip/_vendor/packaging/markers.cpython-37.pyc,,\npip/_internal/metadata/_json.cpython-37.pyc,,\npip/_vendor/idna/codec.cpython-37.pyc,,\npip/_vendor/colorama/winterm.cpython-37.pyc,,\npip/_vendor/chardet/johabfreq.cpython-37.pyc,,\npip/_internal/vcs/mercurial.cpython-37.pyc,,\npip/_internal/cli/spinners.cpython-37.pyc,,\npip/_internal/utils/virtualenv.cpython-37.pyc,,\npip/_vendor/chardet/eucjpprober.cpython-37.pyc,,\npip/_vendor/tenacity/_utils.cpython-37.pyc,,\npip/_internal/resolution/resolvelib/candidates.cpython-37.pyc,,\npip/_vendor/webencodings/tests.cpython-37.pyc,,\npip/_vendor/rich/progress_bar.cpython-37.pyc,,\npip/_vendor/msgpack/__init__.cpython-37.pyc,,\npip/_vendor/tenacity/nap.cpython-37.pyc,,\npip/_vendor/rich/theme.cpython-37.pyc,,\npip/_vendor/webencodings/x_user_defined.cpython-37.pyc,,\npip/_vendor/resolvelib/structs.cpython-37.pyc,,\npip/_vendor/pkg_resources/__pycache__,,\npip/_vendor/pep517/envbuild.cpython-37.pyc,,\npip/_internal/cli/main.cpython-37.pyc,,\npip/_vendor/rich/region.cpython-37.pyc,,\npip/_internal/req/constructors.cpython-37.pyc,,\npip/_internal/commands/list.cpython-37.pyc,,\npip/_vendor/rich/spinner.cpython-37.pyc,,\npip/_vendor/urllib3/contrib/securetransport.cpython-37.pyc,,\npip/_internal/distributions/base.cpython-37.pyc,,\npip/_vendor/chardet/escprober.cpython-37.pyc,,\npip/_internal/commands/configuration.cpython-37.pyc,,\npip/_vendor/pyparsing/actions.cpython-37.pyc,,\n../../../bin/pip3,,\npip/_vendor/idna/idnadata.cpython-37.pyc,,\npip/_vendor/six.cpython-37.pyc,,\npip/_vendor/urllib3/util/response.cpython-37.pyc,,\npip/_vendor/rich/_ratio.cpython-37.pyc,,\npip/_vendor/pygments/formatters/bbcode.cpython-37.pyc,,\npip/_vendor/requests/certs.cpython-37.pyc,,\npip/_vendor/cachecontrol/caches/redis_cache.cpython-37.pyc,,\npip/_vendor/pygments/scanner.cpython-37.pyc,,\npip/_vendor/resolvelib/resolvers.cpython-37.pyc,,\npip/_vendor/urllib3/util/__pycache__,,\npip/_vendor/rich/_loop.cpython-37.pyc,,\npip/_vendor/pygments/lexers/python.cpython-37.pyc,,\npip/_vendor/tenacity/before_sleep.cpython-37.pyc,,\npip/_vendor/rich/progress.cpython-37.pyc,,\npip/_vendor/pep517/in_process/_in_process.cpython-37.pyc,,\npip/_vendor/chardet/charsetprober.cpython-37.pyc,,\npip/_vendor/tenacity/retry.cpython-37.pyc,,\npip-22.3.1.virtualenv,,\npip/_internal/cli/__pycache__,,\npip/_vendor/urllib3/packages/backports/__pycache__,,\npip/_internal/operations/build/wheel_legacy.cpython-37.pyc,,\npip/_internal/resolution/__init__.cpython-37.pyc,,\npip/_internal/commands/debug.cpython-37.pyc,,\npip/_vendor/pkg_resources/py31compat.cpython-37.pyc,,\npip/_vendor/rich/measure.cpython-37.pyc,,\npip/_internal/cli/autocompletion.cpython-37.pyc,,\npip/_vendor/cachecontrol/filewrapper.cpython-37.pyc,,\npip/_vendor/pyparsing/__init__.cpython-37.pyc,,\npip/_vendor/resolvelib/compat/__init__.cpython-37.pyc,,\npip/_vendor/urllib3/filepost.cpython-37.pyc,,\npip/_vendor/urllib3/util/request.cpython-37.pyc,,\npip/_vendor/certifi/__init__.cpython-37.pyc,,\npip/_vendor/pygments/console.cpython-37.pyc,,\npip/_internal/resolution/resolvelib/reporter.cpython-37.pyc,,\npip/_vendor/colorama/initialise.cpython-37.pyc,,\npip/_internal/vcs/__init__.cpython-37.pyc,,\npip/_internal/utils/compat.cpython-37.pyc,,\npip/_vendor/rich/__main__.cpython-37.pyc,,\npip/_vendor/cachecontrol/__init__.cpython-37.pyc,,\npip/_vendor/packaging/_musllinux.cpython-37.pyc,,\npip/_vendor/pygments/formatters/img.cpython-37.pyc,,\npip/_vendor/packaging/_structures.cpython-37.pyc,,\npip/_vendor/urllib3/util/timeout.cpython-37.pyc,,\npip/_internal/metadata/base.cpython-37.pyc,,\npip/_vendor/urllib3/exceptions.cpython-37.pyc,,\npip/_vendor/rich/__pycache__,,\npip/_internal/operations/build/build_tracker.cpython-37.pyc,,\npip/_vendor/requests/__init__.cpython-37.pyc,,\npip/_internal/resolution/base.cpython-37.pyc,,\npip/_internal/req/req_uninstall.cpython-37.pyc,,\npip/_internal/models/link.cpython-37.pyc,,\npip/_internal/utils/__init__.cpython-37.pyc,,\npip/_vendor/rich/live_render.cpython-37.pyc,,\npip/_vendor/rich/traceback.cpython-37.pyc,,\npip/_internal/network/xmlrpc.cpython-37.pyc,,\npip/_vendor/rich/_inspect.cpython-37.pyc,,\npip/_vendor/pygments/filters/__init__.cpython-37.pyc,,\npip/_vendor/resolvelib/reporters.cpython-37.pyc,,\npip/_vendor/packaging/specifiers.cpython-37.pyc,,\npip/_vendor/urllib3/contrib/ntlmpool.cpython-37.pyc,,\npip/_vendor/packaging/__about__.cpython-37.pyc,,\npip/_internal/models/direct_url.cpython-37.pyc,,\npip/_internal/locations/__pycache__,,\npip/_vendor/rich/bar.cpython-37.pyc,,\npip/_vendor/pyparsing/testing.cpython-37.pyc,,\npip/_vendor/requests/utils.cpython-37.pyc,,\npip/_vendor/distlib/database.cpython-37.pyc,,\npip/_internal/operations/install/__init__.cpython-37.pyc,,\npip/_vendor/pygments/styles/__pycache__,,\npip/_vendor/tomli/_re.cpython-37.pyc,,\npip/_internal/commands/uninstall.cpython-37.pyc,,\npip/_vendor/urllib3/util/wait.cpython-37.pyc,,\npip/_vendor/idna/__init__.cpython-37.pyc,,\npip/_vendor/distro/__pycache__,,\npip/_internal/index/collector.cpython-37.pyc,,\npip/_vendor/idna/intranges.cpython-37.pyc,,\npip/_vendor/pyparsing/__pycache__,,\npip/_vendor/rich/panel.cpython-37.pyc,,\npip/_internal/models/candidate.cpython-37.pyc,,\npip/_vendor/rich/color.cpython-37.pyc,,\npip/_internal/network/utils.cpython-37.pyc,,\npip/_vendor/idna/package_data.cpython-37.pyc,,\npip/_vendor/rich/filesize.cpython-37.pyc,,\npip/_internal/metadata/__init__.cpython-37.pyc,,\npip/_internal/commands/wheel.cpython-37.pyc,,\npip/_vendor/distlib/metadata.cpython-37.pyc,,\npip/_vendor/pygments/formatters/terminal.cpython-37.pyc,,\npip/_internal/operations/freeze.cpython-37.pyc,,\npip/_vendor/chardet/escsm.cpython-37.pyc,,\npip/_vendor/chardet/metadata/__init__.cpython-37.pyc,,\npip/_vendor/urllib3/request.cpython-37.pyc,,\npip/_vendor/rich/file_proxy.cpython-37.pyc,,\npip/_vendor/platformdirs/android.cpython-37.pyc,,\npip/_vendor/cachecontrol/heuristics.cpython-37.pyc,,\npip/_internal/operations/build/__pycache__,,\npip/_internal/distributions/sdist.cpython-37.pyc,,\npip/_internal/commands/index.cpython-37.pyc,,\npip/_vendor/platformdirs/__pycache__,,\npip/_vendor/pep517/colorlog.cpython-37.pyc,,\npip/_internal/utils/hashes.cpython-37.pyc,,\npip/_internal/network/__pycache__,,\npip/_vendor/rich/layout.cpython-37.pyc,,\npip/_internal/operations/install/editable_legacy.cpython-37.pyc,,\npip/_vendor/chardet/cli/__pycache__,,\npip/_vendor/cachecontrol/caches/file_cache.cpython-37.pyc,,\npip/_vendor/pyparsing/helpers.cpython-37.pyc,,\npip/_vendor/chardet/universaldetector.cpython-37.pyc,,\npip/_internal/network/session.cpython-37.pyc,,\npip/_vendor/rich/repr.cpython-37.pyc,,\npip/_vendor/cachecontrol/controller.cpython-37.pyc,,\npip/_internal/vcs/subversion.cpython-37.pyc,,\npip/_internal/cli/progress_bars.cpython-37.pyc,,\npip/_vendor/pygments/plugin.cpython-37.pyc,,\npip/_vendor/chardet/johabprober.cpython-37.pyc,,\npip/_vendor/tenacity/tornadoweb.cpython-37.pyc,,\npip/_vendor/rich/text.cpython-37.pyc,,\npip/_internal/metadata/importlib/__init__.cpython-37.pyc,,\npip/_vendor/pygments/lexers/_mapping.cpython-37.pyc,,\npip/_vendor/chardet/latin1prober.cpython-37.pyc,,\npip/_vendor/pygments/formatters/html.cpython-37.pyc,,\npip/_vendor/certifi/__main__.cpython-37.pyc,,\npip/_internal/locations/base.cpython-37.pyc,,\npip/_vendor/urllib3/util/retry.cpython-37.pyc,,\npip/_vendor/requests/_internal_utils.cpython-37.pyc,,\npip/_internal/cli/parser.cpython-37.pyc,,\npip/_internal/models/search_scope.cpython-37.pyc,,\npip/__init__.cpython-37.pyc,,\npip/__pycache__,,\npip/_internal/resolution/resolvelib/found_candidates.cpython-37.pyc,,\npip/_internal/resolution/legacy/__init__.cpython-37.pyc,,\npip/_internal/commands/completion.cpython-37.pyc,,\npip/_vendor/packaging/tags.cpython-37.pyc,,\npip/_vendor/chardet/mbcharsetprober.cpython-37.pyc,,\npip/_vendor/pygments/modeline.cpython-37.pyc,,\npip/_vendor/urllib3/packages/backports/__init__.cpython-37.pyc,,\npip/_vendor/rich/_log_render.cpython-37.pyc,,\npip/_vendor/urllib3/packages/six.cpython-37.pyc,,\npip/_internal/req/__pycache__,,\npip/_internal/utils/filesystem.cpython-37.pyc,,\npip/_vendor/colorama/ansitowin32.cpython-37.pyc,,\npip/_internal/pyproject.cpython-37.pyc,,\npip/_vendor/pygments/formatters/pangomarkup.cpython-37.pyc,,\npip/_vendor/chardet/cli/chardetect.cpython-37.pyc,,\npip/_vendor/rich/_pick.cpython-37.pyc,,\npip/_internal/operations/check.cpython-37.pyc,,\npip/_internal/models/__init__.cpython-37.pyc,,\npip/_vendor/cachecontrol/cache.cpython-37.pyc,,\npip/_vendor/chardet/jisfreq.cpython-37.pyc,,\npip/_vendor/urllib3/contrib/_securetransport/__init__.cpython-37.pyc,,\npip/_internal/commands/search.cpython-37.pyc,,\npip/_internal/metadata/importlib/__pycache__,,\npip/_vendor/tomli/_types.cpython-37.pyc,,\npip/_internal/index/package_finder.cpython-37.pyc,,\npip/_vendor/idna/uts46data.cpython-37.pyc,,\npip/_vendor/pep517/build.cpython-37.pyc,,\npip/_vendor/requests/compat.cpython-37.pyc,,\npip/_internal/vcs/bazaar.cpython-37.pyc,,\npip/_vendor/chardet/gb2312prober.cpython-37.pyc,,\npip/_internal/index/__pycache__,,\npip/_vendor/tenacity/stop.cpython-37.pyc,,\npip/_vendor/resolvelib/compat/collections_abc.cpython-37.pyc,,\npip/_internal/vcs/__pycache__,,\npip/_vendor/rich/_stack.cpython-37.pyc,,\npip/_vendor/chardet/version.cpython-37.pyc,,\npip/_vendor/urllib3/connection.cpython-37.pyc,,\npip/_vendor/chardet/utf1632prober.cpython-37.pyc,,\npip/_vendor/rich/jupyter.cpython-37.pyc,,\npip/_vendor/cachecontrol/caches/__init__.cpython-37.pyc,,\npip/_vendor/pygments/unistring.cpython-37.pyc,,\npip/_vendor/pygments/sphinxext.cpython-37.pyc,,\npip/_vendor/pygments/cmdline.cpython-37.pyc,,\npip/_vendor/cachecontrol/compat.cpython-37.pyc,,\npip/_vendor/pyparsing/util.cpython-37.pyc,,\npip/_internal/commands/__pycache__,,\npip/_internal/resolution/legacy/resolver.cpython-37.pyc,,\npip/_internal/models/target_python.cpython-37.pyc,,\npip/_vendor/pygments/__main__.cpython-37.pyc,,\npip/_vendor/resolvelib/providers.cpython-37.pyc,,\npip/_internal/utils/setuptools_build.cpython-37.pyc,,\npip/_internal/cli/__init__.cpython-37.pyc,,\npip/_vendor/resolvelib/compat/__pycache__,,\npip/_internal/utils/filetypes.cpython-37.pyc,,\npip/_vendor/pygments/util.cpython-37.pyc,,\npip/_vendor/tenacity/wait.cpython-37.pyc,,\npip/_vendor/urllib3/contrib/__init__.cpython-37.pyc,,\npip/_vendor/pyparsing/diagram/__init__.cpython-37.pyc,,\npip/_vendor/requests/packages.cpython-37.pyc,,\npip/_vendor/urllib3/contrib/_securetransport/bindings.cpython-37.pyc,,\npip/_vendor/cachecontrol/__pycache__,,\npip/_vendor/urllib3/connectionpool.cpython-37.pyc,,\n../../../bin/pip-3.7,,\npip/_vendor/platformdirs/__main__.cpython-37.pyc,,\npip/_vendor/rich/screen.cpython-37.pyc,,\npip/_vendor/rich/control.cpython-37.pyc,,\npip/_vendor/msgpack/fallback.cpython-37.pyc,,\npip/_internal/models/installation_report.cpython-37.pyc,,\npip/_internal/resolution/resolvelib/__init__.cpython-37.pyc,,\npip/_vendor/requests/cookies.cpython-37.pyc,,\npip/_internal/cache.cpython-37.pyc,,\npip/_vendor/requests/status_codes.cpython-37.pyc,,\npip/_internal/operations/__init__.cpython-37.pyc,,\npip/_internal/locations/_distutils.cpython-37.pyc,,\npip/_vendor/rich/table.cpython-37.pyc,,\npip/_vendor/requests/api.cpython-37.pyc,,\npip/_vendor/rich/emoji.cpython-37.pyc,,\npip/_vendor/chardet/jpcntx.cpython-37.pyc,,\npip/_vendor/pygments/styles/__init__.cpython-37.pyc,,\npip/_vendor/cachecontrol/wrapper.cpython-37.pyc,,\npip/_internal/commands/install.cpython-37.pyc,,\npip/_vendor/resolvelib/__init__.cpython-37.pyc,,\npip/_vendor/pygments/style.cpython-37.pyc,,\npip/_vendor/pygments/formatters/__init__.cpython-37.pyc,,\npip/_internal/metadata/importlib/_envs.cpython-37.pyc,,\npip/_vendor/urllib3/util/ssltransport.cpython-37.pyc,,\npip/_vendor/distlib/compat.cpython-37.pyc,,\npip/_vendor/rich/ansi.cpython-37.pyc,,\npip/_internal/metadata/__pycache__,,\npip/_vendor/requests/adapters.cpython-37.pyc,,\npip/_vendor/chardet/langgreekmodel.cpython-37.pyc,,\npip/_internal/locations/__init__.cpython-37.pyc,,\npip/_vendor/rich/_palettes.cpython-37.pyc,,\npip/_vendor/rich/_spinners.cpython-37.pyc,,\npip/_internal/metadata/importlib/_dists.cpython-37.pyc,,\npip/_internal/operations/build/metadata.cpython-37.pyc,,\npip/_vendor/rich/status.cpython-37.pyc,,\npip/_vendor/chardet/cp949prober.cpython-37.pyc,,\npip/_internal/utils/glibc.cpython-37.pyc,,\npip/_vendor/chardet/langhebrewmodel.cpython-37.pyc,,\npip/_vendor/distro/__init__.cpython-37.pyc,,\npip/_vendor/distlib/__pycache__,,\npip/_internal/operations/build/__init__.cpython-37.pyc,,\npip/_vendor/rich/palette.cpython-37.pyc,,\npip/_internal/index/sources.cpython-37.pyc,,\npip/_vendor/urllib3/__pycache__,,\npip/_vendor/packaging/__init__.cpython-37.pyc,,\npip/_vendor/chardet/metadata/__pycache__,,\npip/_vendor/rich/syntax.cpython-37.pyc,,\npip/_internal/resolution/resolvelib/requirements.cpython-37.pyc,,\npip/_vendor/urllib3/util/url.cpython-37.pyc,,\npip/_internal/utils/entrypoints.cpython-37.pyc,,\npip/_vendor/urllib3/contrib/pyopenssl.cpython-37.pyc,,\npip/_vendor/webencodings/__pycache__,,\npip/_internal/utils/packaging.cpython-37.pyc,,\npip/_vendor/pygments/lexers/__init__.cpython-37.pyc,,\npip/_vendor/cachecontrol/_cmd.cpython-37.pyc,,\npip/_vendor/urllib3/packages/__pycache__,,\npip/_internal/models/index.cpython-37.pyc,,\npip/_vendor/chardet/cli/__init__.cpython-37.pyc,,\npip/_vendor/urllib3/contrib/_securetransport/low_level.cpython-37.pyc,,\npip/_vendor/chardet/charsetgroupprober.cpython-37.pyc,,\npip/_internal/operations/build/metadata_editable.cpython-37.pyc,,\npip/_vendor/typing_extensions.cpython-37.pyc,,\npip/_internal/operations/__pycache__,,\npip/_vendor/rich/tree.cpython-37.pyc,,\npip/_vendor/tomli/__pycache__,,\npip/_vendor/rich/style.cpython-37.pyc,,\npip/_vendor/platformdirs/windows.cpython-37.pyc,,\npip/_vendor/rich/_emoji_codes.cpython-37.pyc,,\npip/_internal/cli/cmdoptions.cpython-37.pyc,,\npip/_internal/operations/build/wheel_editable.cpython-37.pyc,,\npip/_internal/__init__.cpython-37.pyc,,\npip/_vendor/pygments/formatters/rtf.cpython-37.pyc,,\npip/_internal/utils/egg_link.cpython-37.pyc,,\npip/_internal/utils/misc.cpython-37.pyc,,\npip/_internal/commands/help.cpython-37.pyc,,\npip/_vendor/rich/protocol.cpython-37.pyc,,\npip/_internal/utils/models.cpython-37.pyc,,\npip/_vendor/distro/__main__.cpython-37.pyc,,\npip/_vendor/rich/columns.cpython-37.pyc,,\npip/_vendor/rich/terminal_theme.cpython-37.pyc,,\npip/_vendor/rich/_windows.cpython-37.pyc,,\npip/_vendor/rich/_wrap.cpython-37.pyc,,\npip/_vendor/requests/structures.cpython-37.pyc,,\npip/_vendor/chardet/utf8prober.cpython-37.pyc,,\npip/_vendor/platformdirs/api.cpython-37.pyc,,\npip/_vendor/rich/_cell_widths.cpython-37.pyc,,\npip-22.3.1.dist-info/__pycache__,,\npip/_vendor/rich/__init__.cpython-37.pyc,,\npip/_internal/operations/install/wheel.cpython-37.pyc,,\npip/_vendor/requests/__pycache__,,\npip/_vendor/rich/errors.cpython-37.pyc,,\npip/_internal/commands/freeze.cpython-37.pyc,,\npip/_vendor/tomli/_parser.cpython-37.pyc,,\npip/_vendor/pygments/regexopt.cpython-37.pyc,,\npip/_vendor/urllib3/packages/__init__.cpython-37.pyc,,\npip/_vendor/urllib3/contrib/_appengine_environ.cpython-37.pyc,,\npip/_internal/utils/__pycache__,,\npip/_internal/locations/_sysconfig.cpython-37.pyc,,\npip/_internal/operations/prepare.cpython-37.pyc,,\npip/_internal/__pycache__,,\npip/_internal/utils/compatibility_tags.cpython-37.pyc,,\npip/__pip-runner__.cpython-37.pyc,,\npip/_internal/commands/hash.cpython-37.pyc,,\npip/_vendor/chardet/euckrfreq.cpython-37.pyc,,\npip/_vendor/pyparsing/core.cpython-37.pyc,,\npip/_vendor/certifi/core.cpython-37.pyc,,\npip/_internal/main.cpython-37.pyc,,\npip/_vendor/rich/pretty.cpython-37.pyc,,\npip/_internal/resolution/resolvelib/resolver.cpython-37.pyc,,\npip/_vendor/rich/box.cpython-37.pyc,,\npip/_vendor/requests/models.cpython-37.pyc,,\npip/_vendor/rich/json.cpython-37.pyc,,\npip/_vendor/pygments/filters/__pycache__,,\npip/_internal/utils/deprecation.cpython-37.pyc,,\npip/_internal/utils/_log.cpython-37.pyc,,\npip/_internal/cli/command_context.cpython-37.pyc,,\npip/_vendor/requests/sessions.cpython-37.pyc,,\npip/_internal/wheel_builder.cpython-37.pyc,,\npip/_vendor/cachecontrol/adapter.cpython-37.pyc,,\npip/_vendor/rich/diagnose.cpython-37.pyc,,\npip/_internal/utils/datetime.cpython-37.pyc,,\npip/_vendor/idna/__pycache__,,\npip/_vendor/distlib/resources.cpython-37.pyc,,\npip/_vendor/chardet/langrussianmodel.cpython-37.pyc,,\npip/_vendor/pygments/formatter.cpython-37.pyc,,\npip/_internal/operations/install/__pycache__,,\npip/_internal/vcs/versioncontrol.cpython-37.pyc,,\npip/_vendor/pygments/filter.cpython-37.pyc,,\npip/_vendor/msgpack/__pycache__,,"
  },
  {
    "path": "lib/python3.7/site-packages/pip-22.3.1.dist-info/WHEEL",
    "content": "Wheel-Version: 1.0\nGenerator: bdist_wheel (0.37.1)\nRoot-Is-Purelib: true\nTag: py3-none-any\n\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip-22.3.1.dist-info/entry_points.txt",
    "content": "[console_scripts]\npip = pip._internal.cli.main:main\npip3 = pip._internal.cli.main:main\npip3.10 = pip._internal.cli.main:main\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip-22.3.1.dist-info/top_level.txt",
    "content": "pip\n"
  },
  {
    "path": "lib/python3.7/site-packages/pip-22.3.1.virtualenv",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/__init__.py",
    "content": "\"\"\"\nPackage resource API\n--------------------\n\nA resource is a logical file contained within a package, or a logical\nsubdirectory thereof.  The package resource API expects resource names\nto have their path parts separated with ``/``, *not* whatever the local\npath separator is.  Do not use os.path operations to manipulate resource\nnames being passed into the API.\n\nThe package resource API is designed to work with normal filesystem packages,\n.egg files, and unpacked .egg files.  It can also work in a limited way with\n.zip files and with custom PEP 302 loaders that support the ``get_data()``\nmethod.\n\"\"\"\n\nimport sys\nimport os\nimport io\nimport time\nimport re\nimport types\nimport zipfile\nimport zipimport\nimport warnings\nimport stat\nimport functools\nimport pkgutil\nimport operator\nimport platform\nimport collections\nimport plistlib\nimport email.parser\nimport errno\nimport tempfile\nimport textwrap\nimport itertools\nimport inspect\nimport ntpath\nimport posixpath\nimport importlib\nfrom pkgutil import get_importer\n\ntry:\n    import _imp\nexcept ImportError:\n    # Python 3.2 compatibility\n    import imp as _imp\n\ntry:\n    FileExistsError\nexcept NameError:\n    FileExistsError = OSError\n\n# capture these to bypass sandboxing\nfrom os import utime\ntry:\n    from os import mkdir, rename, unlink\n    WRITE_SUPPORT = True\nexcept ImportError:\n    # no write support, probably under GAE\n    WRITE_SUPPORT = False\n\nfrom os import open as os_open\nfrom os.path import isdir, split\n\ntry:\n    import importlib.machinery as importlib_machinery\n    # access attribute to force import under delayed import mechanisms.\n    importlib_machinery.__name__\nexcept ImportError:\n    importlib_machinery = None\n\nfrom pkg_resources.extern.jaraco.text import (\n    yield_lines,\n    drop_comment,\n    join_continuation,\n)\n\nfrom pkg_resources.extern import appdirs\nfrom pkg_resources.extern import packaging\n__import__('pkg_resources.extern.packaging.version')\n__import__('pkg_resources.extern.packaging.specifiers')\n__import__('pkg_resources.extern.packaging.requirements')\n__import__('pkg_resources.extern.packaging.markers')\n__import__('pkg_resources.extern.packaging.utils')\n\nif sys.version_info < (3, 5):\n    raise RuntimeError(\"Python 3.5 or later is required\")\n\n# declare some globals that will be defined later to\n# satisfy the linters.\nrequire = None\nworking_set = None\nadd_activation_listener = None\nresources_stream = None\ncleanup_resources = None\nresource_dir = None\nresource_stream = None\nset_extraction_path = None\nresource_isdir = None\nresource_string = None\niter_entry_points = None\nresource_listdir = None\nresource_filename = None\nresource_exists = None\n_distribution_finders = None\n_namespace_handlers = None\n_namespace_packages = None\n\n\nclass PEP440Warning(RuntimeWarning):\n    \"\"\"\n    Used when there is an issue with a version or specifier not complying with\n    PEP 440.\n    \"\"\"\n\n\ndef parse_version(v):\n    try:\n        return packaging.version.Version(v)\n    except packaging.version.InvalidVersion:\n        warnings.warn(\n            f\"{v} is an invalid version and will not be supported in \"\n            \"a future release\",\n            PkgResourcesDeprecationWarning,\n        )\n        return packaging.version.LegacyVersion(v)\n\n\n_state_vars = {}\n\n\ndef _declare_state(vartype, **kw):\n    globals().update(kw)\n    _state_vars.update(dict.fromkeys(kw, vartype))\n\n\ndef __getstate__():\n    state = {}\n    g = globals()\n    for k, v in _state_vars.items():\n        state[k] = g['_sget_' + v](g[k])\n    return state\n\n\ndef __setstate__(state):\n    g = globals()\n    for k, v in state.items():\n        g['_sset_' + _state_vars[k]](k, g[k], v)\n    return state\n\n\ndef _sget_dict(val):\n    return val.copy()\n\n\ndef _sset_dict(key, ob, state):\n    ob.clear()\n    ob.update(state)\n\n\ndef _sget_object(val):\n    return val.__getstate__()\n\n\ndef _sset_object(key, ob, state):\n    ob.__setstate__(state)\n\n\n_sget_none = _sset_none = lambda *args: None\n\n\ndef get_supported_platform():\n    \"\"\"Return this platform's maximum compatible version.\n\n    distutils.util.get_platform() normally reports the minimum version\n    of macOS that would be required to *use* extensions produced by\n    distutils.  But what we want when checking compatibility is to know the\n    version of macOS that we are *running*.  To allow usage of packages that\n    explicitly require a newer version of macOS, we must also know the\n    current version of the OS.\n\n    If this condition occurs for any other platform with a version in its\n    platform strings, this function should be extended accordingly.\n    \"\"\"\n    plat = get_build_platform()\n    m = macosVersionString.match(plat)\n    if m is not None and sys.platform == \"darwin\":\n        try:\n            plat = 'macosx-%s-%s' % ('.'.join(_macos_vers()[:2]), m.group(3))\n        except ValueError:\n            # not macOS\n            pass\n    return plat\n\n\n__all__ = [\n    # Basic resource access and distribution/entry point discovery\n    'require', 'run_script', 'get_provider', 'get_distribution',\n    'load_entry_point', 'get_entry_map', 'get_entry_info',\n    'iter_entry_points',\n    'resource_string', 'resource_stream', 'resource_filename',\n    'resource_listdir', 'resource_exists', 'resource_isdir',\n\n    # Environmental control\n    'declare_namespace', 'working_set', 'add_activation_listener',\n    'find_distributions', 'set_extraction_path', 'cleanup_resources',\n    'get_default_cache',\n\n    # Primary implementation classes\n    'Environment', 'WorkingSet', 'ResourceManager',\n    'Distribution', 'Requirement', 'EntryPoint',\n\n    # Exceptions\n    'ResolutionError', 'VersionConflict', 'DistributionNotFound',\n    'UnknownExtra', 'ExtractionError',\n\n    # Warnings\n    'PEP440Warning',\n\n    # Parsing functions and string utilities\n    'parse_requirements', 'parse_version', 'safe_name', 'safe_version',\n    'get_platform', 'compatible_platforms', 'yield_lines', 'split_sections',\n    'safe_extra', 'to_filename', 'invalid_marker', 'evaluate_marker',\n\n    # filesystem utilities\n    'ensure_directory', 'normalize_path',\n\n    # Distribution \"precedence\" constants\n    'EGG_DIST', 'BINARY_DIST', 'SOURCE_DIST', 'CHECKOUT_DIST', 'DEVELOP_DIST',\n\n    # \"Provider\" interfaces, implementations, and registration/lookup APIs\n    'IMetadataProvider', 'IResourceProvider', 'FileMetadata',\n    'PathMetadata', 'EggMetadata', 'EmptyProvider', 'empty_provider',\n    'NullProvider', 'EggProvider', 'DefaultProvider', 'ZipProvider',\n    'register_finder', 'register_namespace_handler', 'register_loader_type',\n    'fixup_namespace_packages', 'get_importer',\n\n    # Warnings\n    'PkgResourcesDeprecationWarning',\n\n    # Deprecated/backward compatibility only\n    'run_main', 'AvailableDistributions',\n]\n\n\nclass ResolutionError(Exception):\n    \"\"\"Abstract base for dependency resolution errors\"\"\"\n\n    def __repr__(self):\n        return self.__class__.__name__ + repr(self.args)\n\n\nclass VersionConflict(ResolutionError):\n    \"\"\"\n    An already-installed version conflicts with the requested version.\n\n    Should be initialized with the installed Distribution and the requested\n    Requirement.\n    \"\"\"\n\n    _template = \"{self.dist} is installed but {self.req} is required\"\n\n    @property\n    def dist(self):\n        return self.args[0]\n\n    @property\n    def req(self):\n        return self.args[1]\n\n    def report(self):\n        return self._template.format(**locals())\n\n    def with_context(self, required_by):\n        \"\"\"\n        If required_by is non-empty, return a version of self that is a\n        ContextualVersionConflict.\n        \"\"\"\n        if not required_by:\n            return self\n        args = self.args + (required_by,)\n        return ContextualVersionConflict(*args)\n\n\nclass ContextualVersionConflict(VersionConflict):\n    \"\"\"\n    A VersionConflict that accepts a third parameter, the set of the\n    requirements that required the installed Distribution.\n    \"\"\"\n\n    _template = VersionConflict._template + ' by {self.required_by}'\n\n    @property\n    def required_by(self):\n        return self.args[2]\n\n\nclass DistributionNotFound(ResolutionError):\n    \"\"\"A requested distribution was not found\"\"\"\n\n    _template = (\"The '{self.req}' distribution was not found \"\n                 \"and is required by {self.requirers_str}\")\n\n    @property\n    def req(self):\n        return self.args[0]\n\n    @property\n    def requirers(self):\n        return self.args[1]\n\n    @property\n    def requirers_str(self):\n        if not self.requirers:\n            return 'the application'\n        return ', '.join(self.requirers)\n\n    def report(self):\n        return self._template.format(**locals())\n\n    def __str__(self):\n        return self.report()\n\n\nclass UnknownExtra(ResolutionError):\n    \"\"\"Distribution doesn't have an \"extra feature\" of the given name\"\"\"\n\n\n_provider_factories = {}\n\nPY_MAJOR = '{}.{}'.format(*sys.version_info)\nEGG_DIST = 3\nBINARY_DIST = 2\nSOURCE_DIST = 1\nCHECKOUT_DIST = 0\nDEVELOP_DIST = -1\n\n\ndef register_loader_type(loader_type, provider_factory):\n    \"\"\"Register `provider_factory` to make providers for `loader_type`\n\n    `loader_type` is the type or class of a PEP 302 ``module.__loader__``,\n    and `provider_factory` is a function that, passed a *module* object,\n    returns an ``IResourceProvider`` for that module.\n    \"\"\"\n    _provider_factories[loader_type] = provider_factory\n\n\ndef get_provider(moduleOrReq):\n    \"\"\"Return an IResourceProvider for the named module or requirement\"\"\"\n    if isinstance(moduleOrReq, Requirement):\n        return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]\n    try:\n        module = sys.modules[moduleOrReq]\n    except KeyError:\n        __import__(moduleOrReq)\n        module = sys.modules[moduleOrReq]\n    loader = getattr(module, '__loader__', None)\n    return _find_adapter(_provider_factories, loader)(module)\n\n\ndef _macos_vers(_cache=[]):\n    if not _cache:\n        version = platform.mac_ver()[0]\n        # fallback for MacPorts\n        if version == '':\n            plist = '/System/Library/CoreServices/SystemVersion.plist'\n            if os.path.exists(plist):\n                if hasattr(plistlib, 'readPlist'):\n                    plist_content = plistlib.readPlist(plist)\n                    if 'ProductVersion' in plist_content:\n                        version = plist_content['ProductVersion']\n\n        _cache.append(version.split('.'))\n    return _cache[0]\n\n\ndef _macos_arch(machine):\n    return {'PowerPC': 'ppc', 'Power_Macintosh': 'ppc'}.get(machine, machine)\n\n\ndef get_build_platform():\n    \"\"\"Return this platform's string for platform-specific distributions\n\n    XXX Currently this is the same as ``distutils.util.get_platform()``, but it\n    needs some hacks for Linux and macOS.\n    \"\"\"\n    from sysconfig import get_platform\n\n    plat = get_platform()\n    if sys.platform == \"darwin\" and not plat.startswith('macosx-'):\n        try:\n            version = _macos_vers()\n            machine = os.uname()[4].replace(\" \", \"_\")\n            return \"macosx-%d.%d-%s\" % (\n                int(version[0]), int(version[1]),\n                _macos_arch(machine),\n            )\n        except ValueError:\n            # if someone is running a non-Mac darwin system, this will fall\n            # through to the default implementation\n            pass\n    return plat\n\n\nmacosVersionString = re.compile(r\"macosx-(\\d+)\\.(\\d+)-(.*)\")\ndarwinVersionString = re.compile(r\"darwin-(\\d+)\\.(\\d+)\\.(\\d+)-(.*)\")\n# XXX backward compat\nget_platform = get_build_platform\n\n\ndef compatible_platforms(provided, required):\n    \"\"\"Can code for the `provided` platform run on the `required` platform?\n\n    Returns true if either platform is ``None``, or the platforms are equal.\n\n    XXX Needs compatibility checks for Linux and other unixy OSes.\n    \"\"\"\n    if provided is None or required is None or provided == required:\n        # easy case\n        return True\n\n    # macOS special cases\n    reqMac = macosVersionString.match(required)\n    if reqMac:\n        provMac = macosVersionString.match(provided)\n\n        # is this a Mac package?\n        if not provMac:\n            # this is backwards compatibility for packages built before\n            # setuptools 0.6. All packages built after this point will\n            # use the new macOS designation.\n            provDarwin = darwinVersionString.match(provided)\n            if provDarwin:\n                dversion = int(provDarwin.group(1))\n                macosversion = \"%s.%s\" % (reqMac.group(1), reqMac.group(2))\n                if dversion == 7 and macosversion >= \"10.3\" or \\\n                        dversion == 8 and macosversion >= \"10.4\":\n                    return True\n            # egg isn't macOS or legacy darwin\n            return False\n\n        # are they the same major version and machine type?\n        if provMac.group(1) != reqMac.group(1) or \\\n                provMac.group(3) != reqMac.group(3):\n            return False\n\n        # is the required OS major update >= the provided one?\n        if int(provMac.group(2)) > int(reqMac.group(2)):\n            return False\n\n        return True\n\n    # XXX Linux and other platforms' special cases should go here\n    return False\n\n\ndef run_script(dist_spec, script_name):\n    \"\"\"Locate distribution `dist_spec` and run its `script_name` script\"\"\"\n    ns = sys._getframe(1).f_globals\n    name = ns['__name__']\n    ns.clear()\n    ns['__name__'] = name\n    require(dist_spec)[0].run_script(script_name, ns)\n\n\n# backward compatibility\nrun_main = run_script\n\n\ndef get_distribution(dist):\n    \"\"\"Return a current distribution object for a Requirement or string\"\"\"\n    if isinstance(dist, str):\n        dist = Requirement.parse(dist)\n    if isinstance(dist, Requirement):\n        dist = get_provider(dist)\n    if not isinstance(dist, Distribution):\n        raise TypeError(\"Expected string, Requirement, or Distribution\", dist)\n    return dist\n\n\ndef load_entry_point(dist, group, name):\n    \"\"\"Return `name` entry point of `group` for `dist` or raise ImportError\"\"\"\n    return get_distribution(dist).load_entry_point(group, name)\n\n\ndef get_entry_map(dist, group=None):\n    \"\"\"Return the entry point map for `group`, or the full entry map\"\"\"\n    return get_distribution(dist).get_entry_map(group)\n\n\ndef get_entry_info(dist, group, name):\n    \"\"\"Return the EntryPoint object for `group`+`name`, or ``None``\"\"\"\n    return get_distribution(dist).get_entry_info(group, name)\n\n\nclass IMetadataProvider:\n    def has_metadata(name):\n        \"\"\"Does the package's distribution contain the named metadata?\"\"\"\n\n    def get_metadata(name):\n        \"\"\"The named metadata resource as a string\"\"\"\n\n    def get_metadata_lines(name):\n        \"\"\"Yield named metadata resource as list of non-blank non-comment lines\n\n       Leading and trailing whitespace is stripped from each line, and lines\n       with ``#`` as the first non-blank character are omitted.\"\"\"\n\n    def metadata_isdir(name):\n        \"\"\"Is the named metadata a directory?  (like ``os.path.isdir()``)\"\"\"\n\n    def metadata_listdir(name):\n        \"\"\"List of metadata names in the directory (like ``os.listdir()``)\"\"\"\n\n    def run_script(script_name, namespace):\n        \"\"\"Execute the named script in the supplied namespace dictionary\"\"\"\n\n\nclass IResourceProvider(IMetadataProvider):\n    \"\"\"An object that provides access to package resources\"\"\"\n\n    def get_resource_filename(manager, resource_name):\n        \"\"\"Return a true filesystem path for `resource_name`\n\n        `manager` must be an ``IResourceManager``\"\"\"\n\n    def get_resource_stream(manager, resource_name):\n        \"\"\"Return a readable file-like object for `resource_name`\n\n        `manager` must be an ``IResourceManager``\"\"\"\n\n    def get_resource_string(manager, resource_name):\n        \"\"\"Return a string containing the contents of `resource_name`\n\n        `manager` must be an ``IResourceManager``\"\"\"\n\n    def has_resource(resource_name):\n        \"\"\"Does the package contain the named resource?\"\"\"\n\n    def resource_isdir(resource_name):\n        \"\"\"Is the named resource a directory?  (like ``os.path.isdir()``)\"\"\"\n\n    def resource_listdir(resource_name):\n        \"\"\"List of resource names in the directory (like ``os.listdir()``)\"\"\"\n\n\nclass WorkingSet:\n    \"\"\"A collection of active distributions on sys.path (or a similar list)\"\"\"\n\n    def __init__(self, entries=None):\n        \"\"\"Create working set from list of path entries (default=sys.path)\"\"\"\n        self.entries = []\n        self.entry_keys = {}\n        self.by_key = {}\n        self.normalized_to_canonical_keys = {}\n        self.callbacks = []\n\n        if entries is None:\n            entries = sys.path\n\n        for entry in entries:\n            self.add_entry(entry)\n\n    @classmethod\n    def _build_master(cls):\n        \"\"\"\n        Prepare the master working set.\n        \"\"\"\n        ws = cls()\n        try:\n            from __main__ import __requires__\n        except ImportError:\n            # The main program does not list any requirements\n            return ws\n\n        # ensure the requirements are met\n        try:\n            ws.require(__requires__)\n        except VersionConflict:\n            return cls._build_from_requirements(__requires__)\n\n        return ws\n\n    @classmethod\n    def _build_from_requirements(cls, req_spec):\n        \"\"\"\n        Build a working set from a requirement spec. Rewrites sys.path.\n        \"\"\"\n        # try it without defaults already on sys.path\n        # by starting with an empty path\n        ws = cls([])\n        reqs = parse_requirements(req_spec)\n        dists = ws.resolve(reqs, Environment())\n        for dist in dists:\n            ws.add(dist)\n\n        # add any missing entries from sys.path\n        for entry in sys.path:\n            if entry not in ws.entries:\n                ws.add_entry(entry)\n\n        # then copy back to sys.path\n        sys.path[:] = ws.entries\n        return ws\n\n    def add_entry(self, entry):\n        \"\"\"Add a path item to ``.entries``, finding any distributions on it\n\n        ``find_distributions(entry, True)`` is used to find distributions\n        corresponding to the path entry, and they are added.  `entry` is\n        always appended to ``.entries``, even if it is already present.\n        (This is because ``sys.path`` can contain the same value more than\n        once, and the ``.entries`` of the ``sys.path`` WorkingSet should always\n        equal ``sys.path``.)\n        \"\"\"\n        self.entry_keys.setdefault(entry, [])\n        self.entries.append(entry)\n        for dist in find_distributions(entry, True):\n            self.add(dist, entry, False)\n\n    def __contains__(self, dist):\n        \"\"\"True if `dist` is the active distribution for its project\"\"\"\n        return self.by_key.get(dist.key) == dist\n\n    def find(self, req):\n        \"\"\"Find a distribution matching requirement `req`\n\n        If there is an active distribution for the requested project, this\n        returns it as long as it meets the version requirement specified by\n        `req`.  But, if there is an active distribution for the project and it\n        does *not* meet the `req` requirement, ``VersionConflict`` is raised.\n        If there is no active distribution for the requested project, ``None``\n        is returned.\n        \"\"\"\n        dist = self.by_key.get(req.key)\n\n        if dist is None:\n            canonical_key = self.normalized_to_canonical_keys.get(req.key)\n\n            if canonical_key is not None:\n                req.key = canonical_key\n                dist = self.by_key.get(canonical_key)\n\n        if dist is not None and dist not in req:\n            # XXX add more info\n            raise VersionConflict(dist, req)\n        return dist\n\n    def iter_entry_points(self, group, name=None):\n        \"\"\"Yield entry point objects from `group` matching `name`\n\n        If `name` is None, yields all entry points in `group` from all\n        distributions in the working set, otherwise only ones matching\n        both `group` and `name` are yielded (in distribution order).\n        \"\"\"\n        return (\n            entry\n            for dist in self\n            for entry in dist.get_entry_map(group).values()\n            if name is None or name == entry.name\n        )\n\n    def run_script(self, requires, script_name):\n        \"\"\"Locate distribution for `requires` and run `script_name` script\"\"\"\n        ns = sys._getframe(1).f_globals\n        name = ns['__name__']\n        ns.clear()\n        ns['__name__'] = name\n        self.require(requires)[0].run_script(script_name, ns)\n\n    def __iter__(self):\n        \"\"\"Yield distributions for non-duplicate projects in the working set\n\n        The yield order is the order in which the items' path entries were\n        added to the working set.\n        \"\"\"\n        seen = {}\n        for item in self.entries:\n            if item not in self.entry_keys:\n                # workaround a cache issue\n                continue\n\n            for key in self.entry_keys[item]:\n                if key not in seen:\n                    seen[key] = 1\n                    yield self.by_key[key]\n\n    def add(self, dist, entry=None, insert=True, replace=False):\n        \"\"\"Add `dist` to working set, associated with `entry`\n\n        If `entry` is unspecified, it defaults to the ``.location`` of `dist`.\n        On exit from this routine, `entry` is added to the end of the working\n        set's ``.entries`` (if it wasn't already present).\n\n        `dist` is only added to the working set if it's for a project that\n        doesn't already have a distribution in the set, unless `replace=True`.\n        If it's added, any callbacks registered with the ``subscribe()`` method\n        will be called.\n        \"\"\"\n        if insert:\n            dist.insert_on(self.entries, entry, replace=replace)\n\n        if entry is None:\n            entry = dist.location\n        keys = self.entry_keys.setdefault(entry, [])\n        keys2 = self.entry_keys.setdefault(dist.location, [])\n        if not replace and dist.key in self.by_key:\n            # ignore hidden distros\n            return\n\n        self.by_key[dist.key] = dist\n        normalized_name = packaging.utils.canonicalize_name(dist.key)\n        self.normalized_to_canonical_keys[normalized_name] = dist.key\n        if dist.key not in keys:\n            keys.append(dist.key)\n        if dist.key not in keys2:\n            keys2.append(dist.key)\n        self._added_new(dist)\n\n    # FIXME: 'WorkingSet.resolve' is too complex (11)\n    def resolve(self, requirements, env=None, installer=None,  # noqa: C901\n                replace_conflicting=False, extras=None):\n        \"\"\"List all distributions needed to (recursively) meet `requirements`\n\n        `requirements` must be a sequence of ``Requirement`` objects.  `env`,\n        if supplied, should be an ``Environment`` instance.  If\n        not supplied, it defaults to all distributions available within any\n        entry or distribution in the working set.  `installer`, if supplied,\n        will be invoked with each requirement that cannot be met by an\n        already-installed distribution; it should return a ``Distribution`` or\n        ``None``.\n\n        Unless `replace_conflicting=True`, raises a VersionConflict exception\n        if\n        any requirements are found on the path that have the correct name but\n        the wrong version.  Otherwise, if an `installer` is supplied it will be\n        invoked to obtain the correct version of the requirement and activate\n        it.\n\n        `extras` is a list of the extras to be used with these requirements.\n        This is important because extra requirements may look like `my_req;\n        extra = \"my_extra\"`, which would otherwise be interpreted as a purely\n        optional requirement.  Instead, we want to be able to assert that these\n        requirements are truly required.\n        \"\"\"\n\n        # set up the stack\n        requirements = list(requirements)[::-1]\n        # set of processed requirements\n        processed = {}\n        # key -> dist\n        best = {}\n        to_activate = []\n\n        req_extras = _ReqExtras()\n\n        # Mapping of requirement to set of distributions that required it;\n        # useful for reporting info about conflicts.\n        required_by = collections.defaultdict(set)\n\n        while requirements:\n            # process dependencies breadth-first\n            req = requirements.pop(0)\n            if req in processed:\n                # Ignore cyclic or redundant dependencies\n                continue\n\n            if not req_extras.markers_pass(req, extras):\n                continue\n\n            dist = best.get(req.key)\n            if dist is None:\n                # Find the best distribution and add it to the map\n                dist = self.by_key.get(req.key)\n                if dist is None or (dist not in req and replace_conflicting):\n                    ws = self\n                    if env is None:\n                        if dist is None:\n                            env = Environment(self.entries)\n                        else:\n                            # Use an empty environment and workingset to avoid\n                            # any further conflicts with the conflicting\n                            # distribution\n                            env = Environment([])\n                            ws = WorkingSet([])\n                    dist = best[req.key] = env.best_match(\n                        req, ws, installer,\n                        replace_conflicting=replace_conflicting\n                    )\n                    if dist is None:\n                        requirers = required_by.get(req, None)\n                        raise DistributionNotFound(req, requirers)\n                to_activate.append(dist)\n            if dist not in req:\n                # Oops, the \"best\" so far conflicts with a dependency\n                dependent_req = required_by[req]\n                raise VersionConflict(dist, req).with_context(dependent_req)\n\n            # push the new requirements onto the stack\n            new_requirements = dist.requires(req.extras)[::-1]\n            requirements.extend(new_requirements)\n\n            # Register the new requirements needed by req\n            for new_requirement in new_requirements:\n                required_by[new_requirement].add(req.project_name)\n                req_extras[new_requirement] = req.extras\n\n            processed[req] = True\n\n        # return list of distros to activate\n        return to_activate\n\n    def find_plugins(\n            self, plugin_env, full_env=None, installer=None, fallback=True):\n        \"\"\"Find all activatable distributions in `plugin_env`\n\n        Example usage::\n\n            distributions, errors = working_set.find_plugins(\n                Environment(plugin_dirlist)\n            )\n            # add plugins+libs to sys.path\n            map(working_set.add, distributions)\n            # display errors\n            print('Could not load', errors)\n\n        The `plugin_env` should be an ``Environment`` instance that contains\n        only distributions that are in the project's \"plugin directory\" or\n        directories. The `full_env`, if supplied, should be an ``Environment``\n        contains all currently-available distributions.  If `full_env` is not\n        supplied, one is created automatically from the ``WorkingSet`` this\n        method is called on, which will typically mean that every directory on\n        ``sys.path`` will be scanned for distributions.\n\n        `installer` is a standard installer callback as used by the\n        ``resolve()`` method. The `fallback` flag indicates whether we should\n        attempt to resolve older versions of a plugin if the newest version\n        cannot be resolved.\n\n        This method returns a 2-tuple: (`distributions`, `error_info`), where\n        `distributions` is a list of the distributions found in `plugin_env`\n        that were loadable, along with any other distributions that are needed\n        to resolve their dependencies.  `error_info` is a dictionary mapping\n        unloadable plugin distributions to an exception instance describing the\n        error that occurred. Usually this will be a ``DistributionNotFound`` or\n        ``VersionConflict`` instance.\n        \"\"\"\n\n        plugin_projects = list(plugin_env)\n        # scan project names in alphabetic order\n        plugin_projects.sort()\n\n        error_info = {}\n        distributions = {}\n\n        if full_env is None:\n            env = Environment(self.entries)\n            env += plugin_env\n        else:\n            env = full_env + plugin_env\n\n        shadow_set = self.__class__([])\n        # put all our entries in shadow_set\n        list(map(shadow_set.add, self))\n\n        for project_name in plugin_projects:\n\n            for dist in plugin_env[project_name]:\n\n                req = [dist.as_requirement()]\n\n                try:\n                    resolvees = shadow_set.resolve(req, env, installer)\n\n                except ResolutionError as v:\n                    # save error info\n                    error_info[dist] = v\n                    if fallback:\n                        # try the next older version of project\n                        continue\n                    else:\n                        # give up on this project, keep going\n                        break\n\n                else:\n                    list(map(shadow_set.add, resolvees))\n                    distributions.update(dict.fromkeys(resolvees))\n\n                    # success, no need to try any more versions of this project\n                    break\n\n        distributions = list(distributions)\n        distributions.sort()\n\n        return distributions, error_info\n\n    def require(self, *requirements):\n        \"\"\"Ensure that distributions matching `requirements` are activated\n\n        `requirements` must be a string or a (possibly-nested) sequence\n        thereof, specifying the distributions and versions required.  The\n        return value is a sequence of the distributions that needed to be\n        activated to fulfill the requirements; all relevant distributions are\n        included, even if they were already activated in this working set.\n        \"\"\"\n        needed = self.resolve(parse_requirements(requirements))\n\n        for dist in needed:\n            self.add(dist)\n\n        return needed\n\n    def subscribe(self, callback, existing=True):\n        \"\"\"Invoke `callback` for all distributions\n\n        If `existing=True` (default),\n        call on all existing ones, as well.\n        \"\"\"\n        if callback in self.callbacks:\n            return\n        self.callbacks.append(callback)\n        if not existing:\n            return\n        for dist in self:\n            callback(dist)\n\n    def _added_new(self, dist):\n        for callback in self.callbacks:\n            callback(dist)\n\n    def __getstate__(self):\n        return (\n            self.entries[:], self.entry_keys.copy(), self.by_key.copy(),\n            self.normalized_to_canonical_keys.copy(), self.callbacks[:]\n        )\n\n    def __setstate__(self, e_k_b_n_c):\n        entries, keys, by_key, normalized_to_canonical_keys, callbacks = e_k_b_n_c\n        self.entries = entries[:]\n        self.entry_keys = keys.copy()\n        self.by_key = by_key.copy()\n        self.normalized_to_canonical_keys = normalized_to_canonical_keys.copy()\n        self.callbacks = callbacks[:]\n\n\nclass _ReqExtras(dict):\n    \"\"\"\n    Map each requirement to the extras that demanded it.\n    \"\"\"\n\n    def markers_pass(self, req, extras=None):\n        \"\"\"\n        Evaluate markers for req against each extra that\n        demanded it.\n\n        Return False if the req has a marker and fails\n        evaluation. Otherwise, return True.\n        \"\"\"\n        extra_evals = (\n            req.marker.evaluate({'extra': extra})\n            for extra in self.get(req, ()) + (extras or (None,))\n        )\n        return not req.marker or any(extra_evals)\n\n\nclass Environment:\n    \"\"\"Searchable snapshot of distributions on a search path\"\"\"\n\n    def __init__(\n            self, search_path=None, platform=get_supported_platform(),\n            python=PY_MAJOR):\n        \"\"\"Snapshot distributions available on a search path\n\n        Any distributions found on `search_path` are added to the environment.\n        `search_path` should be a sequence of ``sys.path`` items.  If not\n        supplied, ``sys.path`` is used.\n\n        `platform` is an optional string specifying the name of the platform\n        that platform-specific distributions must be compatible with.  If\n        unspecified, it defaults to the current platform.  `python` is an\n        optional string naming the desired version of Python (e.g. ``'3.6'``);\n        it defaults to the current version.\n\n        You may explicitly set `platform` (and/or `python`) to ``None`` if you\n        wish to map *all* distributions, not just those compatible with the\n        running platform or Python version.\n        \"\"\"\n        self._distmap = {}\n        self.platform = platform\n        self.python = python\n        self.scan(search_path)\n\n    def can_add(self, dist):\n        \"\"\"Is distribution `dist` acceptable for this environment?\n\n        The distribution must match the platform and python version\n        requirements specified when this environment was created, or False\n        is returned.\n        \"\"\"\n        py_compat = (\n            self.python is None\n            or dist.py_version is None\n            or dist.py_version == self.python\n        )\n        return py_compat and compatible_platforms(dist.platform, self.platform)\n\n    def remove(self, dist):\n        \"\"\"Remove `dist` from the environment\"\"\"\n        self._distmap[dist.key].remove(dist)\n\n    def scan(self, search_path=None):\n        \"\"\"Scan `search_path` for distributions usable in this environment\n\n        Any distributions found are added to the environment.\n        `search_path` should be a sequence of ``sys.path`` items.  If not\n        supplied, ``sys.path`` is used.  Only distributions conforming to\n        the platform/python version defined at initialization are added.\n        \"\"\"\n        if search_path is None:\n            search_path = sys.path\n\n        for item in search_path:\n            for dist in find_distributions(item):\n                self.add(dist)\n\n    def __getitem__(self, project_name):\n        \"\"\"Return a newest-to-oldest list of distributions for `project_name`\n\n        Uses case-insensitive `project_name` comparison, assuming all the\n        project's distributions use their project's name converted to all\n        lowercase as their key.\n\n        \"\"\"\n        distribution_key = project_name.lower()\n        return self._distmap.get(distribution_key, [])\n\n    def add(self, dist):\n        \"\"\"Add `dist` if we ``can_add()`` it and it has not already been added\n        \"\"\"\n        if self.can_add(dist) and dist.has_version():\n            dists = self._distmap.setdefault(dist.key, [])\n            if dist not in dists:\n                dists.append(dist)\n                dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)\n\n    def best_match(\n            self, req, working_set, installer=None, replace_conflicting=False):\n        \"\"\"Find distribution best matching `req` and usable on `working_set`\n\n        This calls the ``find(req)`` method of the `working_set` to see if a\n        suitable distribution is already active.  (This may raise\n        ``VersionConflict`` if an unsuitable version of the project is already\n        active in the specified `working_set`.)  If a suitable distribution\n        isn't active, this method returns the newest distribution in the\n        environment that meets the ``Requirement`` in `req`.  If no suitable\n        distribution is found, and `installer` is supplied, then the result of\n        calling the environment's ``obtain(req, installer)`` method will be\n        returned.\n        \"\"\"\n        try:\n            dist = working_set.find(req)\n        except VersionConflict:\n            if not replace_conflicting:\n                raise\n            dist = None\n        if dist is not None:\n            return dist\n        for dist in self[req.key]:\n            if dist in req:\n                return dist\n        # try to download/install\n        return self.obtain(req, installer)\n\n    def obtain(self, requirement, installer=None):\n        \"\"\"Obtain a distribution matching `requirement` (e.g. via download)\n\n        Obtain a distro that matches requirement (e.g. via download).  In the\n        base ``Environment`` class, this routine just returns\n        ``installer(requirement)``, unless `installer` is None, in which case\n        None is returned instead.  This method is a hook that allows subclasses\n        to attempt other ways of obtaining a distribution before falling back\n        to the `installer` argument.\"\"\"\n        if installer is not None:\n            return installer(requirement)\n\n    def __iter__(self):\n        \"\"\"Yield the unique project names of the available distributions\"\"\"\n        for key in self._distmap.keys():\n            if self[key]:\n                yield key\n\n    def __iadd__(self, other):\n        \"\"\"In-place addition of a distribution or environment\"\"\"\n        if isinstance(other, Distribution):\n            self.add(other)\n        elif isinstance(other, Environment):\n            for project in other:\n                for dist in other[project]:\n                    self.add(dist)\n        else:\n            raise TypeError(\"Can't add %r to environment\" % (other,))\n        return self\n\n    def __add__(self, other):\n        \"\"\"Add an environment or distribution to an environment\"\"\"\n        new = self.__class__([], platform=None, python=None)\n        for env in self, other:\n            new += env\n        return new\n\n\n# XXX backward compatibility\nAvailableDistributions = Environment\n\n\nclass ExtractionError(RuntimeError):\n    \"\"\"An error occurred extracting a resource\n\n    The following attributes are available from instances of this exception:\n\n    manager\n        The resource manager that raised this exception\n\n    cache_path\n        The base directory for resource extraction\n\n    original_error\n        The exception instance that caused extraction to fail\n    \"\"\"\n\n\nclass ResourceManager:\n    \"\"\"Manage resource extraction and packages\"\"\"\n    extraction_path = None\n\n    def __init__(self):\n        self.cached_files = {}\n\n    def resource_exists(self, package_or_requirement, resource_name):\n        \"\"\"Does the named resource exist?\"\"\"\n        return get_provider(package_or_requirement).has_resource(resource_name)\n\n    def resource_isdir(self, package_or_requirement, resource_name):\n        \"\"\"Is the named resource an existing directory?\"\"\"\n        return get_provider(package_or_requirement).resource_isdir(\n            resource_name\n        )\n\n    def resource_filename(self, package_or_requirement, resource_name):\n        \"\"\"Return a true filesystem path for specified resource\"\"\"\n        return get_provider(package_or_requirement).get_resource_filename(\n            self, resource_name\n        )\n\n    def resource_stream(self, package_or_requirement, resource_name):\n        \"\"\"Return a readable file-like object for specified resource\"\"\"\n        return get_provider(package_or_requirement).get_resource_stream(\n            self, resource_name\n        )\n\n    def resource_string(self, package_or_requirement, resource_name):\n        \"\"\"Return specified resource as a string\"\"\"\n        return get_provider(package_or_requirement).get_resource_string(\n            self, resource_name\n        )\n\n    def resource_listdir(self, package_or_requirement, resource_name):\n        \"\"\"List the contents of the named resource directory\"\"\"\n        return get_provider(package_or_requirement).resource_listdir(\n            resource_name\n        )\n\n    def extraction_error(self):\n        \"\"\"Give an error message for problems extracting file(s)\"\"\"\n\n        old_exc = sys.exc_info()[1]\n        cache_path = self.extraction_path or get_default_cache()\n\n        tmpl = textwrap.dedent(\"\"\"\n            Can't extract file(s) to egg cache\n\n            The following error occurred while trying to extract file(s)\n            to the Python egg cache:\n\n              {old_exc}\n\n            The Python egg cache directory is currently set to:\n\n              {cache_path}\n\n            Perhaps your account does not have write access to this directory?\n            You can change the cache directory by setting the PYTHON_EGG_CACHE\n            environment variable to point to an accessible directory.\n            \"\"\").lstrip()\n        err = ExtractionError(tmpl.format(**locals()))\n        err.manager = self\n        err.cache_path = cache_path\n        err.original_error = old_exc\n        raise err\n\n    def get_cache_path(self, archive_name, names=()):\n        \"\"\"Return absolute location in cache for `archive_name` and `names`\n\n        The parent directory of the resulting path will be created if it does\n        not already exist.  `archive_name` should be the base filename of the\n        enclosing egg (which may not be the name of the enclosing zipfile!),\n        including its \".egg\" extension.  `names`, if provided, should be a\n        sequence of path name parts \"under\" the egg's extraction location.\n\n        This method should only be called by resource providers that need to\n        obtain an extraction location, and only for names they intend to\n        extract, as it tracks the generated names for possible cleanup later.\n        \"\"\"\n        extract_path = self.extraction_path or get_default_cache()\n        target_path = os.path.join(extract_path, archive_name + '-tmp', *names)\n        try:\n            _bypass_ensure_directory(target_path)\n        except Exception:\n            self.extraction_error()\n\n        self._warn_unsafe_extraction_path(extract_path)\n\n        self.cached_files[target_path] = 1\n        return target_path\n\n    @staticmethod\n    def _warn_unsafe_extraction_path(path):\n        \"\"\"\n        If the default extraction path is overridden and set to an insecure\n        location, such as /tmp, it opens up an opportunity for an attacker to\n        replace an extracted file with an unauthorized payload. Warn the user\n        if a known insecure location is used.\n\n        See Distribute #375 for more details.\n        \"\"\"\n        if os.name == 'nt' and not path.startswith(os.environ['windir']):\n            # On Windows, permissions are generally restrictive by default\n            #  and temp directories are not writable by other users, so\n            #  bypass the warning.\n            return\n        mode = os.stat(path).st_mode\n        if mode & stat.S_IWOTH or mode & stat.S_IWGRP:\n            msg = (\n                \"Extraction path is writable by group/others \"\n                \"and vulnerable to attack when \"\n                \"used with get_resource_filename ({path}). \"\n                \"Consider a more secure \"\n                \"location (set with .set_extraction_path or the \"\n                \"PYTHON_EGG_CACHE environment variable).\"\n            ).format(**locals())\n            warnings.warn(msg, UserWarning)\n\n    def postprocess(self, tempname, filename):\n        \"\"\"Perform any platform-specific postprocessing of `tempname`\n\n        This is where Mac header rewrites should be done; other platforms don't\n        have anything special they should do.\n\n        Resource providers should call this method ONLY after successfully\n        extracting a compressed resource.  They must NOT call it on resources\n        that are already in the filesystem.\n\n        `tempname` is the current (temporary) name of the file, and `filename`\n        is the name it will be renamed to by the caller after this routine\n        returns.\n        \"\"\"\n\n        if os.name == 'posix':\n            # Make the resource executable\n            mode = ((os.stat(tempname).st_mode) | 0o555) & 0o7777\n            os.chmod(tempname, mode)\n\n    def set_extraction_path(self, path):\n        \"\"\"Set the base path where resources will be extracted to, if needed.\n\n        If you do not call this routine before any extractions take place, the\n        path defaults to the return value of ``get_default_cache()``.  (Which\n        is based on the ``PYTHON_EGG_CACHE`` environment variable, with various\n        platform-specific fallbacks.  See that routine's documentation for more\n        details.)\n\n        Resources are extracted to subdirectories of this path based upon\n        information given by the ``IResourceProvider``.  You may set this to a\n        temporary directory, but then you must call ``cleanup_resources()`` to\n        delete the extracted files when done.  There is no guarantee that\n        ``cleanup_resources()`` will be able to remove all extracted files.\n\n        (Note: you may not change the extraction path for a given resource\n        manager once resources have been extracted, unless you first call\n        ``cleanup_resources()``.)\n        \"\"\"\n        if self.cached_files:\n            raise ValueError(\n                \"Can't change extraction path, files already extracted\"\n            )\n\n        self.extraction_path = path\n\n    def cleanup_resources(self, force=False):\n        \"\"\"\n        Delete all extracted resource files and directories, returning a list\n        of the file and directory names that could not be successfully removed.\n        This function does not have any concurrency protection, so it should\n        generally only be called when the extraction path is a temporary\n        directory exclusive to a single process.  This method is not\n        automatically called; you must call it explicitly or register it as an\n        ``atexit`` function if you wish to ensure cleanup of a temporary\n        directory used for extractions.\n        \"\"\"\n        # XXX\n\n\ndef get_default_cache():\n    \"\"\"\n    Return the ``PYTHON_EGG_CACHE`` environment variable\n    or a platform-relevant user cache dir for an app\n    named \"Python-Eggs\".\n    \"\"\"\n    return (\n        os.environ.get('PYTHON_EGG_CACHE')\n        or appdirs.user_cache_dir(appname='Python-Eggs')\n    )\n\n\ndef safe_name(name):\n    \"\"\"Convert an arbitrary string to a standard distribution name\n\n    Any runs of non-alphanumeric/. characters are replaced with a single '-'.\n    \"\"\"\n    return re.sub('[^A-Za-z0-9.]+', '-', name)\n\n\ndef safe_version(version):\n    \"\"\"\n    Convert an arbitrary string to a standard version string\n    \"\"\"\n    try:\n        # normalize the version\n        return str(packaging.version.Version(version))\n    except packaging.version.InvalidVersion:\n        version = version.replace(' ', '.')\n        return re.sub('[^A-Za-z0-9.]+', '-', version)\n\n\ndef safe_extra(extra):\n    \"\"\"Convert an arbitrary string to a standard 'extra' name\n\n    Any runs of non-alphanumeric characters are replaced with a single '_',\n    and the result is always lowercased.\n    \"\"\"\n    return re.sub('[^A-Za-z0-9.-]+', '_', extra).lower()\n\n\ndef to_filename(name):\n    \"\"\"Convert a project or version name to its filename-escaped form\n\n    Any '-' characters are currently replaced with '_'.\n    \"\"\"\n    return name.replace('-', '_')\n\n\ndef invalid_marker(text):\n    \"\"\"\n    Validate text as a PEP 508 environment marker; return an exception\n    if invalid or False otherwise.\n    \"\"\"\n    try:\n        evaluate_marker(text)\n    except SyntaxError as e:\n        e.filename = None\n        e.lineno = None\n        return e\n    return False\n\n\ndef evaluate_marker(text, extra=None):\n    \"\"\"\n    Evaluate a PEP 508 environment marker.\n    Return a boolean indicating the marker result in this environment.\n    Raise SyntaxError if marker is invalid.\n\n    This implementation uses the 'pyparsing' module.\n    \"\"\"\n    try:\n        marker = packaging.markers.Marker(text)\n        return marker.evaluate()\n    except packaging.markers.InvalidMarker as e:\n        raise SyntaxError(e) from e\n\n\nclass NullProvider:\n    \"\"\"Try to implement resources and metadata for arbitrary PEP 302 loaders\"\"\"\n\n    egg_name = None\n    egg_info = None\n    loader = None\n\n    def __init__(self, module):\n        self.loader = getattr(module, '__loader__', None)\n        self.module_path = os.path.dirname(getattr(module, '__file__', ''))\n\n    def get_resource_filename(self, manager, resource_name):\n        return self._fn(self.module_path, resource_name)\n\n    def get_resource_stream(self, manager, resource_name):\n        return io.BytesIO(self.get_resource_string(manager, resource_name))\n\n    def get_resource_string(self, manager, resource_name):\n        return self._get(self._fn(self.module_path, resource_name))\n\n    def has_resource(self, resource_name):\n        return self._has(self._fn(self.module_path, resource_name))\n\n    def _get_metadata_path(self, name):\n        return self._fn(self.egg_info, name)\n\n    def has_metadata(self, name):\n        if not self.egg_info:\n            return self.egg_info\n\n        path = self._get_metadata_path(name)\n        return self._has(path)\n\n    def get_metadata(self, name):\n        if not self.egg_info:\n            return \"\"\n        path = self._get_metadata_path(name)\n        value = self._get(path)\n        try:\n            return value.decode('utf-8')\n        except UnicodeDecodeError as exc:\n            # Include the path in the error message to simplify\n            # troubleshooting, and without changing the exception type.\n            exc.reason += ' in {} file at path: {}'.format(name, path)\n            raise\n\n    def get_metadata_lines(self, name):\n        return yield_lines(self.get_metadata(name))\n\n    def resource_isdir(self, resource_name):\n        return self._isdir(self._fn(self.module_path, resource_name))\n\n    def metadata_isdir(self, name):\n        return self.egg_info and self._isdir(self._fn(self.egg_info, name))\n\n    def resource_listdir(self, resource_name):\n        return self._listdir(self._fn(self.module_path, resource_name))\n\n    def metadata_listdir(self, name):\n        if self.egg_info:\n            return self._listdir(self._fn(self.egg_info, name))\n        return []\n\n    def run_script(self, script_name, namespace):\n        script = 'scripts/' + script_name\n        if not self.has_metadata(script):\n            raise ResolutionError(\n                \"Script {script!r} not found in metadata at {self.egg_info!r}\"\n                .format(**locals()),\n            )\n        script_text = self.get_metadata(script).replace('\\r\\n', '\\n')\n        script_text = script_text.replace('\\r', '\\n')\n        script_filename = self._fn(self.egg_info, script)\n        namespace['__file__'] = script_filename\n        if os.path.exists(script_filename):\n            with open(script_filename) as fid:\n                source = fid.read()\n            code = compile(source, script_filename, 'exec')\n            exec(code, namespace, namespace)\n        else:\n            from linecache import cache\n            cache[script_filename] = (\n                len(script_text), 0, script_text.split('\\n'), script_filename\n            )\n            script_code = compile(script_text, script_filename, 'exec')\n            exec(script_code, namespace, namespace)\n\n    def _has(self, path):\n        raise NotImplementedError(\n            \"Can't perform this operation for unregistered loader type\"\n        )\n\n    def _isdir(self, path):\n        raise NotImplementedError(\n            \"Can't perform this operation for unregistered loader type\"\n        )\n\n    def _listdir(self, path):\n        raise NotImplementedError(\n            \"Can't perform this operation for unregistered loader type\"\n        )\n\n    def _fn(self, base, resource_name):\n        self._validate_resource_path(resource_name)\n        if resource_name:\n            return os.path.join(base, *resource_name.split('/'))\n        return base\n\n    @staticmethod\n    def _validate_resource_path(path):\n        \"\"\"\n        Validate the resource paths according to the docs.\n        https://setuptools.pypa.io/en/latest/pkg_resources.html#basic-resource-access\n\n        >>> warned = getfixture('recwarn')\n        >>> warnings.simplefilter('always')\n        >>> vrp = NullProvider._validate_resource_path\n        >>> vrp('foo/bar.txt')\n        >>> bool(warned)\n        False\n        >>> vrp('../foo/bar.txt')\n        >>> bool(warned)\n        True\n        >>> warned.clear()\n        >>> vrp('/foo/bar.txt')\n        >>> bool(warned)\n        True\n        >>> vrp('foo/../../bar.txt')\n        >>> bool(warned)\n        True\n        >>> warned.clear()\n        >>> vrp('foo/f../bar.txt')\n        >>> bool(warned)\n        False\n\n        Windows path separators are straight-up disallowed.\n        >>> vrp(r'\\\\foo/bar.txt')\n        Traceback (most recent call last):\n        ...\n        ValueError: Use of .. or absolute path in a resource path \\\nis not allowed.\n\n        >>> vrp(r'C:\\\\foo/bar.txt')\n        Traceback (most recent call last):\n        ...\n        ValueError: Use of .. or absolute path in a resource path \\\nis not allowed.\n\n        Blank values are allowed\n\n        >>> vrp('')\n        >>> bool(warned)\n        False\n\n        Non-string values are not.\n\n        >>> vrp(None)\n        Traceback (most recent call last):\n        ...\n        AttributeError: ...\n        \"\"\"\n        invalid = (\n            os.path.pardir in path.split(posixpath.sep) or\n            posixpath.isabs(path) or\n            ntpath.isabs(path)\n        )\n        if not invalid:\n            return\n\n        msg = \"Use of .. or absolute path in a resource path is not allowed.\"\n\n        # Aggressively disallow Windows absolute paths\n        if ntpath.isabs(path) and not posixpath.isabs(path):\n            raise ValueError(msg)\n\n        # for compatibility, warn; in future\n        # raise ValueError(msg)\n        warnings.warn(\n            msg[:-1] + \" and will raise exceptions in a future release.\",\n            DeprecationWarning,\n            stacklevel=4,\n        )\n\n    def _get(self, path):\n        if hasattr(self.loader, 'get_data'):\n            return self.loader.get_data(path)\n        raise NotImplementedError(\n            \"Can't perform this operation for loaders without 'get_data()'\"\n        )\n\n\nregister_loader_type(object, NullProvider)\n\n\ndef _parents(path):\n    \"\"\"\n    yield all parents of path including path\n    \"\"\"\n    last = None\n    while path != last:\n        yield path\n        last = path\n        path, _ = os.path.split(path)\n\n\nclass EggProvider(NullProvider):\n    \"\"\"Provider based on a virtual filesystem\"\"\"\n\n    def __init__(self, module):\n        super().__init__(module)\n        self._setup_prefix()\n\n    def _setup_prefix(self):\n        # Assume that metadata may be nested inside a \"basket\"\n        # of multiple eggs and use module_path instead of .archive.\n        eggs = filter(_is_egg_path, _parents(self.module_path))\n        egg = next(eggs, None)\n        egg and self._set_egg(egg)\n\n    def _set_egg(self, path):\n        self.egg_name = os.path.basename(path)\n        self.egg_info = os.path.join(path, 'EGG-INFO')\n        self.egg_root = path\n\n\nclass DefaultProvider(EggProvider):\n    \"\"\"Provides access to package resources in the filesystem\"\"\"\n\n    def _has(self, path):\n        return os.path.exists(path)\n\n    def _isdir(self, path):\n        return os.path.isdir(path)\n\n    def _listdir(self, path):\n        return os.listdir(path)\n\n    def get_resource_stream(self, manager, resource_name):\n        return open(self._fn(self.module_path, resource_name), 'rb')\n\n    def _get(self, path):\n        with open(path, 'rb') as stream:\n            return stream.read()\n\n    @classmethod\n    def _register(cls):\n        loader_names = 'SourceFileLoader', 'SourcelessFileLoader',\n        for name in loader_names:\n            loader_cls = getattr(importlib_machinery, name, type(None))\n            register_loader_type(loader_cls, cls)\n\n\nDefaultProvider._register()\n\n\nclass EmptyProvider(NullProvider):\n    \"\"\"Provider that returns nothing for all requests\"\"\"\n\n    module_path = None\n\n    _isdir = _has = lambda self, path: False\n\n    def _get(self, path):\n        return ''\n\n    def _listdir(self, path):\n        return []\n\n    def __init__(self):\n        pass\n\n\nempty_provider = EmptyProvider()\n\n\nclass ZipManifests(dict):\n    \"\"\"\n    zip manifest builder\n    \"\"\"\n\n    @classmethod\n    def build(cls, path):\n        \"\"\"\n        Build a dictionary similar to the zipimport directory\n        caches, except instead of tuples, store ZipInfo objects.\n\n        Use a platform-specific path separator (os.sep) for the path keys\n        for compatibility with pypy on Windows.\n        \"\"\"\n        with zipfile.ZipFile(path) as zfile:\n            items = (\n                (\n                    name.replace('/', os.sep),\n                    zfile.getinfo(name),\n                )\n                for name in zfile.namelist()\n            )\n            return dict(items)\n\n    load = build\n\n\nclass MemoizedZipManifests(ZipManifests):\n    \"\"\"\n    Memoized zipfile manifests.\n    \"\"\"\n    manifest_mod = collections.namedtuple('manifest_mod', 'manifest mtime')\n\n    def load(self, path):\n        \"\"\"\n        Load a manifest at path or return a suitable manifest already loaded.\n        \"\"\"\n        path = os.path.normpath(path)\n        mtime = os.stat(path).st_mtime\n\n        if path not in self or self[path].mtime != mtime:\n            manifest = self.build(path)\n            self[path] = self.manifest_mod(manifest, mtime)\n\n        return self[path].manifest\n\n\nclass ZipProvider(EggProvider):\n    \"\"\"Resource support for zips and eggs\"\"\"\n\n    eagers = None\n    _zip_manifests = MemoizedZipManifests()\n\n    def __init__(self, module):\n        super().__init__(module)\n        self.zip_pre = self.loader.archive + os.sep\n\n    def _zipinfo_name(self, fspath):\n        # Convert a virtual filename (full path to file) into a zipfile subpath\n        # usable with the zipimport directory cache for our target archive\n        fspath = fspath.rstrip(os.sep)\n        if fspath == self.loader.archive:\n            return ''\n        if fspath.startswith(self.zip_pre):\n            return fspath[len(self.zip_pre):]\n        raise AssertionError(\n            \"%s is not a subpath of %s\" % (fspath, self.zip_pre)\n        )\n\n    def _parts(self, zip_path):\n        # Convert a zipfile subpath into an egg-relative path part list.\n        # pseudo-fs path\n        fspath = self.zip_pre + zip_path\n        if fspath.startswith(self.egg_root + os.sep):\n            return fspath[len(self.egg_root) + 1:].split(os.sep)\n        raise AssertionError(\n            \"%s is not a subpath of %s\" % (fspath, self.egg_root)\n        )\n\n    @property\n    def zipinfo(self):\n        return self._zip_manifests.load(self.loader.archive)\n\n    def get_resource_filename(self, manager, resource_name):\n        if not self.egg_name:\n            raise NotImplementedError(\n                \"resource_filename() only supported for .egg, not .zip\"\n            )\n        # no need to lock for extraction, since we use temp names\n        zip_path = self._resource_to_zip(resource_name)\n        eagers = self._get_eager_resources()\n        if '/'.join(self._parts(zip_path)) in eagers:\n            for name in eagers:\n                self._extract_resource(manager, self._eager_to_zip(name))\n        return self._extract_resource(manager, zip_path)\n\n    @staticmethod\n    def _get_date_and_size(zip_stat):\n        size = zip_stat.file_size\n        # ymdhms+wday, yday, dst\n        date_time = zip_stat.date_time + (0, 0, -1)\n        # 1980 offset already done\n        timestamp = time.mktime(date_time)\n        return timestamp, size\n\n    # FIXME: 'ZipProvider._extract_resource' is too complex (12)\n    def _extract_resource(self, manager, zip_path):  # noqa: C901\n\n        if zip_path in self._index():\n            for name in self._index()[zip_path]:\n                last = self._extract_resource(\n                    manager, os.path.join(zip_path, name)\n                )\n            # return the extracted directory name\n            return os.path.dirname(last)\n\n        timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])\n\n        if not WRITE_SUPPORT:\n            raise IOError('\"os.rename\" and \"os.unlink\" are not supported '\n                          'on this platform')\n        try:\n\n            real_path = manager.get_cache_path(\n                self.egg_name, self._parts(zip_path)\n            )\n\n            if self._is_current(real_path, zip_path):\n                return real_path\n\n            outf, tmpnam = _mkstemp(\n                \".$extract\",\n                dir=os.path.dirname(real_path),\n            )\n            os.write(outf, self.loader.get_data(zip_path))\n            os.close(outf)\n            utime(tmpnam, (timestamp, timestamp))\n            manager.postprocess(tmpnam, real_path)\n\n            try:\n                rename(tmpnam, real_path)\n\n            except os.error:\n                if os.path.isfile(real_path):\n                    if self._is_current(real_path, zip_path):\n                        # the file became current since it was checked above,\n                        #  so proceed.\n                        return real_path\n                    # Windows, del old file and retry\n                    elif os.name == 'nt':\n                        unlink(real_path)\n                        rename(tmpnam, real_path)\n                        return real_path\n                raise\n\n        except os.error:\n            # report a user-friendly error\n            manager.extraction_error()\n\n        return real_path\n\n    def _is_current(self, file_path, zip_path):\n        \"\"\"\n        Return True if the file_path is current for this zip_path\n        \"\"\"\n        timestamp, size = self._get_date_and_size(self.zipinfo[zip_path])\n        if not os.path.isfile(file_path):\n            return False\n        stat = os.stat(file_path)\n        if stat.st_size != size or stat.st_mtime != timestamp:\n            return False\n        # check that the contents match\n        zip_contents = self.loader.get_data(zip_path)\n        with open(file_path, 'rb') as f:\n            file_contents = f.read()\n        return zip_contents == file_contents\n\n    def _get_eager_resources(self):\n        if self.eagers is None:\n            eagers = []\n            for name in ('native_libs.txt', 'eager_resources.txt'):\n                if self.has_metadata(name):\n                    eagers.extend(self.get_metadata_lines(name))\n            self.eagers = eagers\n        return self.eagers\n\n    def _index(self):\n        try:\n            return self._dirindex\n        except AttributeError:\n            ind = {}\n            for path in self.zipinfo:\n                parts = path.split(os.sep)\n                while parts:\n                    parent = os.sep.join(parts[:-1])\n                    if parent in ind:\n                        ind[parent].append(parts[-1])\n                        break\n                    else:\n                        ind[parent] = [parts.pop()]\n            self._dirindex = ind\n            return ind\n\n    def _has(self, fspath):\n        zip_path = self._zipinfo_name(fspath)\n        return zip_path in self.zipinfo or zip_path in self._index()\n\n    def _isdir(self, fspath):\n        return self._zipinfo_name(fspath) in self._index()\n\n    def _listdir(self, fspath):\n        return list(self._index().get(self._zipinfo_name(fspath), ()))\n\n    def _eager_to_zip(self, resource_name):\n        return self._zipinfo_name(self._fn(self.egg_root, resource_name))\n\n    def _resource_to_zip(self, resource_name):\n        return self._zipinfo_name(self._fn(self.module_path, resource_name))\n\n\nregister_loader_type(zipimport.zipimporter, ZipProvider)\n\n\nclass FileMetadata(EmptyProvider):\n    \"\"\"Metadata handler for standalone PKG-INFO files\n\n    Usage::\n\n        metadata = FileMetadata(\"/path/to/PKG-INFO\")\n\n    This provider rejects all data and metadata requests except for PKG-INFO,\n    which is treated as existing, and will be the contents of the file at\n    the provided location.\n    \"\"\"\n\n    def __init__(self, path):\n        self.path = path\n\n    def _get_metadata_path(self, name):\n        return self.path\n\n    def has_metadata(self, name):\n        return name == 'PKG-INFO' and os.path.isfile(self.path)\n\n    def get_metadata(self, name):\n        if name != 'PKG-INFO':\n            raise KeyError(\"No metadata except PKG-INFO is available\")\n\n        with io.open(self.path, encoding='utf-8', errors=\"replace\") as f:\n            metadata = f.read()\n        self._warn_on_replacement(metadata)\n        return metadata\n\n    def _warn_on_replacement(self, metadata):\n        replacement_char = '�'\n        if replacement_char in metadata:\n            tmpl = \"{self.path} could not be properly decoded in UTF-8\"\n            msg = tmpl.format(**locals())\n            warnings.warn(msg)\n\n    def get_metadata_lines(self, name):\n        return yield_lines(self.get_metadata(name))\n\n\nclass PathMetadata(DefaultProvider):\n    \"\"\"Metadata provider for egg directories\n\n    Usage::\n\n        # Development eggs:\n\n        egg_info = \"/path/to/PackageName.egg-info\"\n        base_dir = os.path.dirname(egg_info)\n        metadata = PathMetadata(base_dir, egg_info)\n        dist_name = os.path.splitext(os.path.basename(egg_info))[0]\n        dist = Distribution(basedir, project_name=dist_name, metadata=metadata)\n\n        # Unpacked egg directories:\n\n        egg_path = \"/path/to/PackageName-ver-pyver-etc.egg\"\n        metadata = PathMetadata(egg_path, os.path.join(egg_path,'EGG-INFO'))\n        dist = Distribution.from_filename(egg_path, metadata=metadata)\n    \"\"\"\n\n    def __init__(self, path, egg_info):\n        self.module_path = path\n        self.egg_info = egg_info\n\n\nclass EggMetadata(ZipProvider):\n    \"\"\"Metadata provider for .egg files\"\"\"\n\n    def __init__(self, importer):\n        \"\"\"Create a metadata provider from a zipimporter\"\"\"\n\n        self.zip_pre = importer.archive + os.sep\n        self.loader = importer\n        if importer.prefix:\n            self.module_path = os.path.join(importer.archive, importer.prefix)\n        else:\n            self.module_path = importer.archive\n        self._setup_prefix()\n\n\n_declare_state('dict', _distribution_finders={})\n\n\ndef register_finder(importer_type, distribution_finder):\n    \"\"\"Register `distribution_finder` to find distributions in sys.path items\n\n    `importer_type` is the type or class of a PEP 302 \"Importer\" (sys.path item\n    handler), and `distribution_finder` is a callable that, passed a path\n    item and the importer instance, yields ``Distribution`` instances found on\n    that path item.  See ``pkg_resources.find_on_path`` for an example.\"\"\"\n    _distribution_finders[importer_type] = distribution_finder\n\n\ndef find_distributions(path_item, only=False):\n    \"\"\"Yield distributions accessible via `path_item`\"\"\"\n    importer = get_importer(path_item)\n    finder = _find_adapter(_distribution_finders, importer)\n    return finder(importer, path_item, only)\n\n\ndef find_eggs_in_zip(importer, path_item, only=False):\n    \"\"\"\n    Find eggs in zip files; possibly multiple nested eggs.\n    \"\"\"\n    if importer.archive.endswith('.whl'):\n        # wheels are not supported with this finder\n        # they don't have PKG-INFO metadata, and won't ever contain eggs\n        return\n    metadata = EggMetadata(importer)\n    if metadata.has_metadata('PKG-INFO'):\n        yield Distribution.from_filename(path_item, metadata=metadata)\n    if only:\n        # don't yield nested distros\n        return\n    for subitem in metadata.resource_listdir(''):\n        if _is_egg_path(subitem):\n            subpath = os.path.join(path_item, subitem)\n            dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)\n            for dist in dists:\n                yield dist\n        elif subitem.lower().endswith(('.dist-info', '.egg-info')):\n            subpath = os.path.join(path_item, subitem)\n            submeta = EggMetadata(zipimport.zipimporter(subpath))\n            submeta.egg_info = subpath\n            yield Distribution.from_location(path_item, subitem, submeta)\n\n\nregister_finder(zipimport.zipimporter, find_eggs_in_zip)\n\n\ndef find_nothing(importer, path_item, only=False):\n    return ()\n\n\nregister_finder(object, find_nothing)\n\n\ndef _by_version_descending(names):\n    \"\"\"\n    Given a list of filenames, return them in descending order\n    by version number.\n\n    >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'\n    >>> _by_version_descending(names)\n    ['Python-2.7.10.egg', 'Python-2.7.2.egg', 'bar', 'foo']\n    >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.egg'\n    >>> _by_version_descending(names)\n    ['Setuptools-1.2.3.egg', 'Setuptools-1.2.3b1.egg']\n    >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptools-1.2.3.post1.egg'\n    >>> _by_version_descending(names)\n    ['Setuptools-1.2.3.post1.egg', 'Setuptools-1.2.3b1.egg']\n    \"\"\"\n    def try_parse(name):\n        \"\"\"\n        Attempt to parse as a version or return a null version.\n        \"\"\"\n        try:\n            return packaging.version.Version(name)\n        except Exception:\n            return packaging.version.Version('0')\n\n    def _by_version(name):\n        \"\"\"\n        Parse each component of the filename\n        \"\"\"\n        name, ext = os.path.splitext(name)\n        parts = itertools.chain(name.split('-'), [ext])\n        return [try_parse(part) for part in parts]\n\n    return sorted(names, key=_by_version, reverse=True)\n\n\ndef find_on_path(importer, path_item, only=False):\n    \"\"\"Yield distributions accessible on a sys.path directory\"\"\"\n    path_item = _normalize_cached(path_item)\n\n    if _is_unpacked_egg(path_item):\n        yield Distribution.from_filename(\n            path_item, metadata=PathMetadata(\n                path_item, os.path.join(path_item, 'EGG-INFO')\n            )\n        )\n        return\n\n    entries = (\n        os.path.join(path_item, child)\n        for child in safe_listdir(path_item)\n    )\n\n    # for performance, before sorting by version,\n    # screen entries for only those that will yield\n    # distributions\n    filtered = (\n        entry\n        for entry in entries\n        if dist_factory(path_item, entry, only)\n    )\n\n    # scan for .egg and .egg-info in directory\n    path_item_entries = _by_version_descending(filtered)\n    for entry in path_item_entries:\n        fullpath = os.path.join(path_item, entry)\n        factory = dist_factory(path_item, entry, only)\n        for dist in factory(fullpath):\n            yield dist\n\n\ndef dist_factory(path_item, entry, only):\n    \"\"\"Return a dist_factory for the given entry.\"\"\"\n    lower = entry.lower()\n    is_egg_info = lower.endswith('.egg-info')\n    is_dist_info = (\n        lower.endswith('.dist-info') and\n        os.path.isdir(os.path.join(path_item, entry))\n    )\n    is_meta = is_egg_info or is_dist_info\n    return (\n        distributions_from_metadata\n        if is_meta else\n        find_distributions\n        if not only and _is_egg_path(entry) else\n        resolve_egg_link\n        if not only and lower.endswith('.egg-link') else\n        NoDists()\n    )\n\n\nclass NoDists:\n    \"\"\"\n    >>> bool(NoDists())\n    False\n\n    >>> list(NoDists()('anything'))\n    []\n    \"\"\"\n    def __bool__(self):\n        return False\n\n    def __call__(self, fullpath):\n        return iter(())\n\n\ndef safe_listdir(path):\n    \"\"\"\n    Attempt to list contents of path, but suppress some exceptions.\n    \"\"\"\n    try:\n        return os.listdir(path)\n    except (PermissionError, NotADirectoryError):\n        pass\n    except OSError as e:\n        # Ignore the directory if does not exist, not a directory or\n        # permission denied\n        if e.errno not in (errno.ENOTDIR, errno.EACCES, errno.ENOENT):\n            raise\n    return ()\n\n\ndef distributions_from_metadata(path):\n    root = os.path.dirname(path)\n    if os.path.isdir(path):\n        if len(os.listdir(path)) == 0:\n            # empty metadata dir; skip\n            return\n        metadata = PathMetadata(root, path)\n    else:\n        metadata = FileMetadata(path)\n    entry = os.path.basename(path)\n    yield Distribution.from_location(\n        root, entry, metadata, precedence=DEVELOP_DIST,\n    )\n\n\ndef non_empty_lines(path):\n    \"\"\"\n    Yield non-empty lines from file at path\n    \"\"\"\n    with open(path) as f:\n        for line in f:\n            line = line.strip()\n            if line:\n                yield line\n\n\ndef resolve_egg_link(path):\n    \"\"\"\n    Given a path to an .egg-link, resolve distributions\n    present in the referenced path.\n    \"\"\"\n    referenced_paths = non_empty_lines(path)\n    resolved_paths = (\n        os.path.join(os.path.dirname(path), ref)\n        for ref in referenced_paths\n    )\n    dist_groups = map(find_distributions, resolved_paths)\n    return next(dist_groups, ())\n\n\nregister_finder(pkgutil.ImpImporter, find_on_path)\n\nif hasattr(importlib_machinery, 'FileFinder'):\n    register_finder(importlib_machinery.FileFinder, find_on_path)\n\n_declare_state('dict', _namespace_handlers={})\n_declare_state('dict', _namespace_packages={})\n\n\ndef register_namespace_handler(importer_type, namespace_handler):\n    \"\"\"Register `namespace_handler` to declare namespace packages\n\n    `importer_type` is the type or class of a PEP 302 \"Importer\" (sys.path item\n    handler), and `namespace_handler` is a callable like this::\n\n        def namespace_handler(importer, path_entry, moduleName, module):\n            # return a path_entry to use for child packages\n\n    Namespace handlers are only called if the importer object has already\n    agreed that it can handle the relevant path item, and they should only\n    return a subpath if the module __path__ does not already contain an\n    equivalent subpath.  For an example namespace handler, see\n    ``pkg_resources.file_ns_handler``.\n    \"\"\"\n    _namespace_handlers[importer_type] = namespace_handler\n\n\ndef _handle_ns(packageName, path_item):\n    \"\"\"Ensure that named package includes a subpath of path_item (if needed)\"\"\"\n\n    importer = get_importer(path_item)\n    if importer is None:\n        return None\n\n    # use find_spec (PEP 451) and fall-back to find_module (PEP 302)\n    try:\n        spec = importer.find_spec(packageName)\n    except AttributeError:\n        # capture warnings due to #1111\n        with warnings.catch_warnings():\n            warnings.simplefilter(\"ignore\")\n            loader = importer.find_module(packageName)\n    else:\n        loader = spec.loader if spec else None\n\n    if loader is None:\n        return None\n    module = sys.modules.get(packageName)\n    if module is None:\n        module = sys.modules[packageName] = types.ModuleType(packageName)\n        module.__path__ = []\n        _set_parent_ns(packageName)\n    elif not hasattr(module, '__path__'):\n        raise TypeError(\"Not a package:\", packageName)\n    handler = _find_adapter(_namespace_handlers, importer)\n    subpath = handler(importer, path_item, packageName, module)\n    if subpath is not None:\n        path = module.__path__\n        path.append(subpath)\n        importlib.import_module(packageName)\n        _rebuild_mod_path(path, packageName, module)\n    return subpath\n\n\ndef _rebuild_mod_path(orig_path, package_name, module):\n    \"\"\"\n    Rebuild module.__path__ ensuring that all entries are ordered\n    corresponding to their sys.path order\n    \"\"\"\n    sys_path = [_normalize_cached(p) for p in sys.path]\n\n    def safe_sys_path_index(entry):\n        \"\"\"\n        Workaround for #520 and #513.\n        \"\"\"\n        try:\n            return sys_path.index(entry)\n        except ValueError:\n            return float('inf')\n\n    def position_in_sys_path(path):\n        \"\"\"\n        Return the ordinal of the path based on its position in sys.path\n        \"\"\"\n        path_parts = path.split(os.sep)\n        module_parts = package_name.count('.') + 1\n        parts = path_parts[:-module_parts]\n        return safe_sys_path_index(_normalize_cached(os.sep.join(parts)))\n\n    new_path = sorted(orig_path, key=position_in_sys_path)\n    new_path = [_normalize_cached(p) for p in new_path]\n\n    if isinstance(module.__path__, list):\n        module.__path__[:] = new_path\n    else:\n        module.__path__ = new_path\n\n\ndef declare_namespace(packageName):\n    \"\"\"Declare that package 'packageName' is a namespace package\"\"\"\n\n    _imp.acquire_lock()\n    try:\n        if packageName in _namespace_packages:\n            return\n\n        path = sys.path\n        parent, _, _ = packageName.rpartition('.')\n\n        if parent:\n            declare_namespace(parent)\n            if parent not in _namespace_packages:\n                __import__(parent)\n            try:\n                path = sys.modules[parent].__path__\n            except AttributeError as e:\n                raise TypeError(\"Not a package:\", parent) from e\n\n        # Track what packages are namespaces, so when new path items are added,\n        # they can be updated\n        _namespace_packages.setdefault(parent or None, []).append(packageName)\n        _namespace_packages.setdefault(packageName, [])\n\n        for path_item in path:\n            # Ensure all the parent's path items are reflected in the child,\n            # if they apply\n            _handle_ns(packageName, path_item)\n\n    finally:\n        _imp.release_lock()\n\n\ndef fixup_namespace_packages(path_item, parent=None):\n    \"\"\"Ensure that previously-declared namespace packages include path_item\"\"\"\n    _imp.acquire_lock()\n    try:\n        for package in _namespace_packages.get(parent, ()):\n            subpath = _handle_ns(package, path_item)\n            if subpath:\n                fixup_namespace_packages(subpath, package)\n    finally:\n        _imp.release_lock()\n\n\ndef file_ns_handler(importer, path_item, packageName, module):\n    \"\"\"Compute an ns-package subpath for a filesystem or zipfile importer\"\"\"\n\n    subpath = os.path.join(path_item, packageName.split('.')[-1])\n    normalized = _normalize_cached(subpath)\n    for item in module.__path__:\n        if _normalize_cached(item) == normalized:\n            break\n    else:\n        # Only return the path if it's not already there\n        return subpath\n\n\nregister_namespace_handler(pkgutil.ImpImporter, file_ns_handler)\nregister_namespace_handler(zipimport.zipimporter, file_ns_handler)\n\nif hasattr(importlib_machinery, 'FileFinder'):\n    register_namespace_handler(importlib_machinery.FileFinder, file_ns_handler)\n\n\ndef null_ns_handler(importer, path_item, packageName, module):\n    return None\n\n\nregister_namespace_handler(object, null_ns_handler)\n\n\ndef normalize_path(filename):\n    \"\"\"Normalize a file/dir name for comparison purposes\"\"\"\n    return os.path.normcase(os.path.realpath(os.path.normpath(\n        _cygwin_patch(filename))))\n\n\ndef _cygwin_patch(filename):  # pragma: nocover\n    \"\"\"\n    Contrary to POSIX 2008, on Cygwin, getcwd (3) contains\n    symlink components. Using\n    os.path.abspath() works around this limitation. A fix in os.getcwd()\n    would probably better, in Cygwin even more so, except\n    that this seems to be by design...\n    \"\"\"\n    return os.path.abspath(filename) if sys.platform == 'cygwin' else filename\n\n\ndef _normalize_cached(filename, _cache={}):\n    try:\n        return _cache[filename]\n    except KeyError:\n        _cache[filename] = result = normalize_path(filename)\n        return result\n\n\ndef _is_egg_path(path):\n    \"\"\"\n    Determine if given path appears to be an egg.\n    \"\"\"\n    return _is_zip_egg(path) or _is_unpacked_egg(path)\n\n\ndef _is_zip_egg(path):\n    return (\n        path.lower().endswith('.egg') and\n        os.path.isfile(path) and\n        zipfile.is_zipfile(path)\n    )\n\n\ndef _is_unpacked_egg(path):\n    \"\"\"\n    Determine if given path appears to be an unpacked egg.\n    \"\"\"\n    return (\n        path.lower().endswith('.egg') and\n        os.path.isfile(os.path.join(path, 'EGG-INFO', 'PKG-INFO'))\n    )\n\n\ndef _set_parent_ns(packageName):\n    parts = packageName.split('.')\n    name = parts.pop()\n    if parts:\n        parent = '.'.join(parts)\n        setattr(sys.modules[parent], name, sys.modules[packageName])\n\n\nMODULE = re.compile(r\"\\w+(\\.\\w+)*$\").match\nEGG_NAME = re.compile(\n    r\"\"\"\n    (?P<name>[^-]+) (\n        -(?P<ver>[^-]+) (\n            -py(?P<pyver>[^-]+) (\n                -(?P<plat>.+)\n            )?\n        )?\n    )?\n    \"\"\",\n    re.VERBOSE | re.IGNORECASE,\n).match\n\n\nclass EntryPoint:\n    \"\"\"Object representing an advertised importable object\"\"\"\n\n    def __init__(self, name, module_name, attrs=(), extras=(), dist=None):\n        if not MODULE(module_name):\n            raise ValueError(\"Invalid module name\", module_name)\n        self.name = name\n        self.module_name = module_name\n        self.attrs = tuple(attrs)\n        self.extras = tuple(extras)\n        self.dist = dist\n\n    def __str__(self):\n        s = \"%s = %s\" % (self.name, self.module_name)\n        if self.attrs:\n            s += ':' + '.'.join(self.attrs)\n        if self.extras:\n            s += ' [%s]' % ','.join(self.extras)\n        return s\n\n    def __repr__(self):\n        return \"EntryPoint.parse(%r)\" % str(self)\n\n    def load(self, require=True, *args, **kwargs):\n        \"\"\"\n        Require packages for this EntryPoint, then resolve it.\n        \"\"\"\n        if not require or args or kwargs:\n            warnings.warn(\n                \"Parameters to load are deprecated.  Call .resolve and \"\n                \".require separately.\",\n                PkgResourcesDeprecationWarning,\n                stacklevel=2,\n            )\n        if require:\n            self.require(*args, **kwargs)\n        return self.resolve()\n\n    def resolve(self):\n        \"\"\"\n        Resolve the entry point from its module and attrs.\n        \"\"\"\n        module = __import__(self.module_name, fromlist=['__name__'], level=0)\n        try:\n            return functools.reduce(getattr, self.attrs, module)\n        except AttributeError as exc:\n            raise ImportError(str(exc)) from exc\n\n    def require(self, env=None, installer=None):\n        if self.extras and not self.dist:\n            raise UnknownExtra(\"Can't require() without a distribution\", self)\n\n        # Get the requirements for this entry point with all its extras and\n        # then resolve them. We have to pass `extras` along when resolving so\n        # that the working set knows what extras we want. Otherwise, for\n        # dist-info distributions, the working set will assume that the\n        # requirements for that extra are purely optional and skip over them.\n        reqs = self.dist.requires(self.extras)\n        items = working_set.resolve(reqs, env, installer, extras=self.extras)\n        list(map(working_set.add, items))\n\n    pattern = re.compile(\n        r'\\s*'\n        r'(?P<name>.+?)\\s*'\n        r'=\\s*'\n        r'(?P<module>[\\w.]+)\\s*'\n        r'(:\\s*(?P<attr>[\\w.]+))?\\s*'\n        r'(?P<extras>\\[.*\\])?\\s*$'\n    )\n\n    @classmethod\n    def parse(cls, src, dist=None):\n        \"\"\"Parse a single entry point from string `src`\n\n        Entry point syntax follows the form::\n\n            name = some.module:some.attr [extra1, extra2]\n\n        The entry name and module name are required, but the ``:attrs`` and\n        ``[extras]`` parts are optional\n        \"\"\"\n        m = cls.pattern.match(src)\n        if not m:\n            msg = \"EntryPoint must be in 'name=module:attrs [extras]' format\"\n            raise ValueError(msg, src)\n        res = m.groupdict()\n        extras = cls._parse_extras(res['extras'])\n        attrs = res['attr'].split('.') if res['attr'] else ()\n        return cls(res['name'], res['module'], attrs, extras, dist)\n\n    @classmethod\n    def _parse_extras(cls, extras_spec):\n        if not extras_spec:\n            return ()\n        req = Requirement.parse('x' + extras_spec)\n        if req.specs:\n            raise ValueError()\n        return req.extras\n\n    @classmethod\n    def parse_group(cls, group, lines, dist=None):\n        \"\"\"Parse an entry point group\"\"\"\n        if not MODULE(group):\n            raise ValueError(\"Invalid group name\", group)\n        this = {}\n        for line in yield_lines(lines):\n            ep = cls.parse(line, dist)\n            if ep.name in this:\n                raise ValueError(\"Duplicate entry point\", group, ep.name)\n            this[ep.name] = ep\n        return this\n\n    @classmethod\n    def parse_map(cls, data, dist=None):\n        \"\"\"Parse a map of entry point groups\"\"\"\n        if isinstance(data, dict):\n            data = data.items()\n        else:\n            data = split_sections(data)\n        maps = {}\n        for group, lines in data:\n            if group is None:\n                if not lines:\n                    continue\n                raise ValueError(\"Entry points must be listed in groups\")\n            group = group.strip()\n            if group in maps:\n                raise ValueError(\"Duplicate group name\", group)\n            maps[group] = cls.parse_group(group, lines, dist)\n        return maps\n\n\ndef _version_from_file(lines):\n    \"\"\"\n    Given an iterable of lines from a Metadata file, return\n    the value of the Version field, if present, or None otherwise.\n    \"\"\"\n    def is_version_line(line):\n        return line.lower().startswith('version:')\n    version_lines = filter(is_version_line, lines)\n    line = next(iter(version_lines), '')\n    _, _, value = line.partition(':')\n    return safe_version(value.strip()) or None\n\n\nclass Distribution:\n    \"\"\"Wrap an actual or potential sys.path entry w/metadata\"\"\"\n    PKG_INFO = 'PKG-INFO'\n\n    def __init__(\n            self, location=None, metadata=None, project_name=None,\n            version=None, py_version=PY_MAJOR, platform=None,\n            precedence=EGG_DIST):\n        self.project_name = safe_name(project_name or 'Unknown')\n        if version is not None:\n            self._version = safe_version(version)\n        self.py_version = py_version\n        self.platform = platform\n        self.location = location\n        self.precedence = precedence\n        self._provider = metadata or empty_provider\n\n    @classmethod\n    def from_location(cls, location, basename, metadata=None, **kw):\n        project_name, version, py_version, platform = [None] * 4\n        basename, ext = os.path.splitext(basename)\n        if ext.lower() in _distributionImpl:\n            cls = _distributionImpl[ext.lower()]\n\n            match = EGG_NAME(basename)\n            if match:\n                project_name, version, py_version, platform = match.group(\n                    'name', 'ver', 'pyver', 'plat'\n                )\n        return cls(\n            location, metadata, project_name=project_name, version=version,\n            py_version=py_version, platform=platform, **kw\n        )._reload_version()\n\n    def _reload_version(self):\n        return self\n\n    @property\n    def hashcmp(self):\n        return (\n            self.parsed_version,\n            self.precedence,\n            self.key,\n            self.location,\n            self.py_version or '',\n            self.platform or '',\n        )\n\n    def __hash__(self):\n        return hash(self.hashcmp)\n\n    def __lt__(self, other):\n        return self.hashcmp < other.hashcmp\n\n    def __le__(self, other):\n        return self.hashcmp <= other.hashcmp\n\n    def __gt__(self, other):\n        return self.hashcmp > other.hashcmp\n\n    def __ge__(self, other):\n        return self.hashcmp >= other.hashcmp\n\n    def __eq__(self, other):\n        if not isinstance(other, self.__class__):\n            # It's not a Distribution, so they are not equal\n            return False\n        return self.hashcmp == other.hashcmp\n\n    def __ne__(self, other):\n        return not self == other\n\n    # These properties have to be lazy so that we don't have to load any\n    # metadata until/unless it's actually needed.  (i.e., some distributions\n    # may not know their name or version without loading PKG-INFO)\n\n    @property\n    def key(self):\n        try:\n            return self._key\n        except AttributeError:\n            self._key = key = self.project_name.lower()\n            return key\n\n    @property\n    def parsed_version(self):\n        if not hasattr(self, \"_parsed_version\"):\n            self._parsed_version = parse_version(self.version)\n\n        return self._parsed_version\n\n    def _warn_legacy_version(self):\n        LV = packaging.version.LegacyVersion\n        is_legacy = isinstance(self._parsed_version, LV)\n        if not is_legacy:\n            return\n\n        # While an empty version is technically a legacy version and\n        # is not a valid PEP 440 version, it's also unlikely to\n        # actually come from someone and instead it is more likely that\n        # it comes from setuptools attempting to parse a filename and\n        # including it in the list. So for that we'll gate this warning\n        # on if the version is anything at all or not.\n        if not self.version:\n            return\n\n        tmpl = textwrap.dedent(\"\"\"\n            '{project_name} ({version})' is being parsed as a legacy,\n            non PEP 440,\n            version. You may find odd behavior and sort order.\n            In particular it will be sorted as less than 0.0. It\n            is recommended to migrate to PEP 440 compatible\n            versions.\n            \"\"\").strip().replace('\\n', ' ')\n\n        warnings.warn(tmpl.format(**vars(self)), PEP440Warning)\n\n    @property\n    def version(self):\n        try:\n            return self._version\n        except AttributeError as e:\n            version = self._get_version()\n            if version is None:\n                path = self._get_metadata_path_for_display(self.PKG_INFO)\n                msg = (\n                    \"Missing 'Version:' header and/or {} file at path: {}\"\n                ).format(self.PKG_INFO, path)\n                raise ValueError(msg, self) from e\n\n            return version\n\n    @property\n    def _dep_map(self):\n        \"\"\"\n        A map of extra to its list of (direct) requirements\n        for this distribution, including the null extra.\n        \"\"\"\n        try:\n            return self.__dep_map\n        except AttributeError:\n            self.__dep_map = self._filter_extras(self._build_dep_map())\n        return self.__dep_map\n\n    @staticmethod\n    def _filter_extras(dm):\n        \"\"\"\n        Given a mapping of extras to dependencies, strip off\n        environment markers and filter out any dependencies\n        not matching the markers.\n        \"\"\"\n        for extra in list(filter(None, dm)):\n            new_extra = extra\n            reqs = dm.pop(extra)\n            new_extra, _, marker = extra.partition(':')\n            fails_marker = marker and (\n                invalid_marker(marker)\n                or not evaluate_marker(marker)\n            )\n            if fails_marker:\n                reqs = []\n            new_extra = safe_extra(new_extra) or None\n\n            dm.setdefault(new_extra, []).extend(reqs)\n        return dm\n\n    def _build_dep_map(self):\n        dm = {}\n        for name in 'requires.txt', 'depends.txt':\n            for extra, reqs in split_sections(self._get_metadata(name)):\n                dm.setdefault(extra, []).extend(parse_requirements(reqs))\n        return dm\n\n    def requires(self, extras=()):\n        \"\"\"List of Requirements needed for this distro if `extras` are used\"\"\"\n        dm = self._dep_map\n        deps = []\n        deps.extend(dm.get(None, ()))\n        for ext in extras:\n            try:\n                deps.extend(dm[safe_extra(ext)])\n            except KeyError as e:\n                raise UnknownExtra(\n                    \"%s has no such extra feature %r\" % (self, ext)\n                ) from e\n        return deps\n\n    def _get_metadata_path_for_display(self, name):\n        \"\"\"\n        Return the path to the given metadata file, if available.\n        \"\"\"\n        try:\n            # We need to access _get_metadata_path() on the provider object\n            # directly rather than through this class's __getattr__()\n            # since _get_metadata_path() is marked private.\n            path = self._provider._get_metadata_path(name)\n\n        # Handle exceptions e.g. in case the distribution's metadata\n        # provider doesn't support _get_metadata_path().\n        except Exception:\n            return '[could not detect]'\n\n        return path\n\n    def _get_metadata(self, name):\n        if self.has_metadata(name):\n            for line in self.get_metadata_lines(name):\n                yield line\n\n    def _get_version(self):\n        lines = self._get_metadata(self.PKG_INFO)\n        version = _version_from_file(lines)\n\n        return version\n\n    def activate(self, path=None, replace=False):\n        \"\"\"Ensure distribution is importable on `path` (default=sys.path)\"\"\"\n        if path is None:\n            path = sys.path\n        self.insert_on(path, replace=replace)\n        if path is sys.path:\n            fixup_namespace_packages(self.location)\n            for pkg in self._get_metadata('namespace_packages.txt'):\n                if pkg in sys.modules:\n                    declare_namespace(pkg)\n\n    def egg_name(self):\n        \"\"\"Return what this distribution's standard .egg filename should be\"\"\"\n        filename = \"%s-%s-py%s\" % (\n            to_filename(self.project_name), to_filename(self.version),\n            self.py_version or PY_MAJOR\n        )\n\n        if self.platform:\n            filename += '-' + self.platform\n        return filename\n\n    def __repr__(self):\n        if self.location:\n            return \"%s (%s)\" % (self, self.location)\n        else:\n            return str(self)\n\n    def __str__(self):\n        try:\n            version = getattr(self, 'version', None)\n        except ValueError:\n            version = None\n        version = version or \"[unknown version]\"\n        return \"%s %s\" % (self.project_name, version)\n\n    def __getattr__(self, attr):\n        \"\"\"Delegate all unrecognized public attributes to .metadata provider\"\"\"\n        if attr.startswith('_'):\n            raise AttributeError(attr)\n        return getattr(self._provider, attr)\n\n    def __dir__(self):\n        return list(\n            set(super(Distribution, self).__dir__())\n            | set(\n                attr for attr in self._provider.__dir__()\n                if not attr.startswith('_')\n            )\n        )\n\n    @classmethod\n    def from_filename(cls, filename, metadata=None, **kw):\n        return cls.from_location(\n            _normalize_cached(filename), os.path.basename(filename), metadata,\n            **kw\n        )\n\n    def as_requirement(self):\n        \"\"\"Return a ``Requirement`` that matches this distribution exactly\"\"\"\n        if isinstance(self.parsed_version, packaging.version.Version):\n            spec = \"%s==%s\" % (self.project_name, self.parsed_version)\n        else:\n            spec = \"%s===%s\" % (self.project_name, self.parsed_version)\n\n        return Requirement.parse(spec)\n\n    def load_entry_point(self, group, name):\n        \"\"\"Return the `name` entry point of `group` or raise ImportError\"\"\"\n        ep = self.get_entry_info(group, name)\n        if ep is None:\n            raise ImportError(\"Entry point %r not found\" % ((group, name),))\n        return ep.load()\n\n    def get_entry_map(self, group=None):\n        \"\"\"Return the entry point map for `group`, or the full entry map\"\"\"\n        try:\n            ep_map = self._ep_map\n        except AttributeError:\n            ep_map = self._ep_map = EntryPoint.parse_map(\n                self._get_metadata('entry_points.txt'), self\n            )\n        if group is not None:\n            return ep_map.get(group, {})\n        return ep_map\n\n    def get_entry_info(self, group, name):\n        \"\"\"Return the EntryPoint object for `group`+`name`, or ``None``\"\"\"\n        return self.get_entry_map(group).get(name)\n\n    # FIXME: 'Distribution.insert_on' is too complex (13)\n    def insert_on(self, path, loc=None, replace=False):  # noqa: C901\n        \"\"\"Ensure self.location is on path\n\n        If replace=False (default):\n            - If location is already in path anywhere, do nothing.\n            - Else:\n              - If it's an egg and its parent directory is on path,\n                insert just ahead of the parent.\n              - Else: add to the end of path.\n        If replace=True:\n            - If location is already on path anywhere (not eggs)\n              or higher priority than its parent (eggs)\n              do nothing.\n            - Else:\n              - If it's an egg and its parent directory is on path,\n                insert just ahead of the parent,\n                removing any lower-priority entries.\n              - Else: add it to the front of path.\n        \"\"\"\n\n        loc = loc or self.location\n        if not loc:\n            return\n\n        nloc = _normalize_cached(loc)\n        bdir = os.path.dirname(nloc)\n        npath = [(p and _normalize_cached(p) or p) for p in path]\n\n        for p, item in enumerate(npath):\n            if item == nloc:\n                if replace:\n                    break\n                else:\n                    # don't modify path (even removing duplicates) if\n                    # found and not replace\n                    return\n            elif item == bdir and self.precedence == EGG_DIST:\n                # if it's an .egg, give it precedence over its directory\n                # UNLESS it's already been added to sys.path and replace=False\n                if (not replace) and nloc in npath[p:]:\n                    return\n                if path is sys.path:\n                    self.check_version_conflict()\n                path.insert(p, loc)\n                npath.insert(p, nloc)\n                break\n        else:\n            if path is sys.path:\n                self.check_version_conflict()\n            if replace:\n                path.insert(0, loc)\n            else:\n                path.append(loc)\n            return\n\n        # p is the spot where we found or inserted loc; now remove duplicates\n        while True:\n            try:\n                np = npath.index(nloc, p + 1)\n            except ValueError:\n                break\n            else:\n                del npath[np], path[np]\n                # ha!\n                p = np\n\n        return\n\n    def check_version_conflict(self):\n        if self.key == 'setuptools':\n            # ignore the inevitable setuptools self-conflicts  :(\n            return\n\n        nsp = dict.fromkeys(self._get_metadata('namespace_packages.txt'))\n        loc = normalize_path(self.location)\n        for modname in self._get_metadata('top_level.txt'):\n            if (modname not in sys.modules or modname in nsp\n                    or modname in _namespace_packages):\n                continue\n            if modname in ('pkg_resources', 'setuptools', 'site'):\n                continue\n            fn = getattr(sys.modules[modname], '__file__', None)\n            if fn and (normalize_path(fn).startswith(loc) or\n                       fn.startswith(self.location)):\n                continue\n            issue_warning(\n                \"Module %s was already imported from %s, but %s is being added\"\n                \" to sys.path\" % (modname, fn, self.location),\n            )\n\n    def has_version(self):\n        try:\n            self.version\n        except ValueError:\n            issue_warning(\"Unbuilt egg for \" + repr(self))\n            return False\n        return True\n\n    def clone(self, **kw):\n        \"\"\"Copy this distribution, substituting in any changed keyword args\"\"\"\n        names = 'project_name version py_version platform location precedence'\n        for attr in names.split():\n            kw.setdefault(attr, getattr(self, attr, None))\n        kw.setdefault('metadata', self._provider)\n        return self.__class__(**kw)\n\n    @property\n    def extras(self):\n        return [dep for dep in self._dep_map if dep]\n\n\nclass EggInfoDistribution(Distribution):\n    def _reload_version(self):\n        \"\"\"\n        Packages installed by distutils (e.g. numpy or scipy),\n        which uses an old safe_version, and so\n        their version numbers can get mangled when\n        converted to filenames (e.g., 1.11.0.dev0+2329eae to\n        1.11.0.dev0_2329eae). These distributions will not be\n        parsed properly\n        downstream by Distribution and safe_version, so\n        take an extra step and try to get the version number from\n        the metadata file itself instead of the filename.\n        \"\"\"\n        md_version = self._get_version()\n        if md_version:\n            self._version = md_version\n        return self\n\n\nclass DistInfoDistribution(Distribution):\n    \"\"\"\n    Wrap an actual or potential sys.path entry\n    w/metadata, .dist-info style.\n    \"\"\"\n    PKG_INFO = 'METADATA'\n    EQEQ = re.compile(r\"([\\(,])\\s*(\\d.*?)\\s*([,\\)])\")\n\n    @property\n    def _parsed_pkg_info(self):\n        \"\"\"Parse and cache metadata\"\"\"\n        try:\n            return self._pkg_info\n        except AttributeError:\n            metadata = self.get_metadata(self.PKG_INFO)\n            self._pkg_info = email.parser.Parser().parsestr(metadata)\n            return self._pkg_info\n\n    @property\n    def _dep_map(self):\n        try:\n            return self.__dep_map\n        except AttributeError:\n            self.__dep_map = self._compute_dependencies()\n            return self.__dep_map\n\n    def _compute_dependencies(self):\n        \"\"\"Recompute this distribution's dependencies.\"\"\"\n        dm = self.__dep_map = {None: []}\n\n        reqs = []\n        # Including any condition expressions\n        for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:\n            reqs.extend(parse_requirements(req))\n\n        def reqs_for_extra(extra):\n            for req in reqs:\n                if not req.marker or req.marker.evaluate({'extra': extra}):\n                    yield req\n\n        common = types.MappingProxyType(dict.fromkeys(reqs_for_extra(None)))\n        dm[None].extend(common)\n\n        for extra in self._parsed_pkg_info.get_all('Provides-Extra') or []:\n            s_extra = safe_extra(extra.strip())\n            dm[s_extra] = [r for r in reqs_for_extra(extra) if r not in common]\n\n        return dm\n\n\n_distributionImpl = {\n    '.egg': Distribution,\n    '.egg-info': EggInfoDistribution,\n    '.dist-info': DistInfoDistribution,\n}\n\n\ndef issue_warning(*args, **kw):\n    level = 1\n    g = globals()\n    try:\n        # find the first stack frame that is *not* code in\n        # the pkg_resources module, to use for the warning\n        while sys._getframe(level).f_globals is g:\n            level += 1\n    except ValueError:\n        pass\n    warnings.warn(stacklevel=level + 1, *args, **kw)\n\n\ndef parse_requirements(strs):\n    \"\"\"\n    Yield ``Requirement`` objects for each specification in `strs`.\n\n    `strs` must be a string, or a (possibly-nested) iterable thereof.\n    \"\"\"\n    return map(Requirement, join_continuation(map(drop_comment, yield_lines(strs))))\n\n\nclass RequirementParseError(packaging.requirements.InvalidRequirement):\n    \"Compatibility wrapper for InvalidRequirement\"\n\n\nclass Requirement(packaging.requirements.Requirement):\n    def __init__(self, requirement_string):\n        \"\"\"DO NOT CALL THIS UNDOCUMENTED METHOD; use Requirement.parse()!\"\"\"\n        super(Requirement, self).__init__(requirement_string)\n        self.unsafe_name = self.name\n        project_name = safe_name(self.name)\n        self.project_name, self.key = project_name, project_name.lower()\n        self.specs = [\n            (spec.operator, spec.version) for spec in self.specifier]\n        self.extras = tuple(map(safe_extra, self.extras))\n        self.hashCmp = (\n            self.key,\n            self.url,\n            self.specifier,\n            frozenset(self.extras),\n            str(self.marker) if self.marker else None,\n        )\n        self.__hash = hash(self.hashCmp)\n\n    def __eq__(self, other):\n        return (\n            isinstance(other, Requirement) and\n            self.hashCmp == other.hashCmp\n        )\n\n    def __ne__(self, other):\n        return not self == other\n\n    def __contains__(self, item):\n        if isinstance(item, Distribution):\n            if item.key != self.key:\n                return False\n\n            item = item.version\n\n        # Allow prereleases always in order to match the previous behavior of\n        # this method. In the future this should be smarter and follow PEP 440\n        # more accurately.\n        return self.specifier.contains(item, prereleases=True)\n\n    def __hash__(self):\n        return self.__hash\n\n    def __repr__(self):\n        return \"Requirement.parse(%r)\" % str(self)\n\n    @staticmethod\n    def parse(s):\n        req, = parse_requirements(s)\n        return req\n\n\ndef _always_object(classes):\n    \"\"\"\n    Ensure object appears in the mro even\n    for old-style classes.\n    \"\"\"\n    if object not in classes:\n        return classes + (object,)\n    return classes\n\n\ndef _find_adapter(registry, ob):\n    \"\"\"Return an adapter factory for `ob` from `registry`\"\"\"\n    types = _always_object(inspect.getmro(getattr(ob, '__class__', type(ob))))\n    for t in types:\n        if t in registry:\n            return registry[t]\n\n\ndef ensure_directory(path):\n    \"\"\"Ensure that the parent directory of `path` exists\"\"\"\n    dirname = os.path.dirname(path)\n    os.makedirs(dirname, exist_ok=True)\n\n\ndef _bypass_ensure_directory(path):\n    \"\"\"Sandbox-bypassing version of ensure_directory()\"\"\"\n    if not WRITE_SUPPORT:\n        raise IOError('\"os.mkdir\" not supported on this platform.')\n    dirname, filename = split(path)\n    if dirname and filename and not isdir(dirname):\n        _bypass_ensure_directory(dirname)\n        try:\n            mkdir(dirname, 0o755)\n        except FileExistsError:\n            pass\n\n\ndef split_sections(s):\n    \"\"\"Split a string or iterable thereof into (section, content) pairs\n\n    Each ``section`` is a stripped version of the section header (\"[section]\")\n    and each ``content`` is a list of stripped lines excluding blank lines and\n    comment-only lines.  If there are any such lines before the first section\n    header, they're returned in a first ``section`` of ``None``.\n    \"\"\"\n    section = None\n    content = []\n    for line in yield_lines(s):\n        if line.startswith(\"[\"):\n            if line.endswith(\"]\"):\n                if section or content:\n                    yield section, content\n                section = line[1:-1].strip()\n                content = []\n            else:\n                raise ValueError(\"Invalid section heading\", line)\n        else:\n            content.append(line)\n\n    # wrap up last segment\n    yield section, content\n\n\ndef _mkstemp(*args, **kw):\n    old_open = os.open\n    try:\n        # temporarily bypass sandboxing\n        os.open = os_open\n        return tempfile.mkstemp(*args, **kw)\n    finally:\n        # and then put it back\n        os.open = old_open\n\n\n# Silence the PEP440Warning by default, so that end users don't get hit by it\n# randomly just because they use pkg_resources. We want to append the rule\n# because we want earlier uses of filterwarnings to take precedence over this\n# one.\nwarnings.filterwarnings(\"ignore\", category=PEP440Warning, append=True)\n\n\n# from jaraco.functools 1.3\ndef _call_aside(f, *args, **kwargs):\n    f(*args, **kwargs)\n    return f\n\n\n@_call_aside\ndef _initialize(g=globals()):\n    \"Set up global resource manager (deliberately not state-saved)\"\n    manager = ResourceManager()\n    g['_manager'] = manager\n    g.update(\n        (name, getattr(manager, name))\n        for name in dir(manager)\n        if not name.startswith('_')\n    )\n\n\nclass PkgResourcesDeprecationWarning(Warning):\n    \"\"\"\n    Base class for warning about deprecations in ``pkg_resources``\n\n    This class is not derived from ``DeprecationWarning``, and as such is\n    visible by default.\n    \"\"\"\n\n\n@_call_aside\ndef _initialize_master_working_set():\n    \"\"\"\n    Prepare the master working set and make the ``require()``\n    API available.\n\n    This function has explicit effects on the global state\n    of pkg_resources. It is intended to be invoked once at\n    the initialization of this module.\n\n    Invocation by other packages is unsupported and done\n    at their own risk.\n    \"\"\"\n    working_set = WorkingSet._build_master()\n    _declare_state('object', working_set=working_set)\n\n    require = working_set.require\n    iter_entry_points = working_set.iter_entry_points\n    add_activation_listener = working_set.subscribe\n    run_script = working_set.run_script\n    # backward compatibility\n    run_main = run_script\n    # Activate all distributions already on sys.path with replace=False and\n    # ensure that all distributions added to the working set in the future\n    # (e.g. by calling ``require()``) will get activated as well,\n    # with higher priority (replace=True).\n    tuple(\n        dist.activate(replace=False)\n        for dist in working_set\n    )\n    add_activation_listener(\n        lambda dist: dist.activate(replace=True),\n        existing=False,\n    )\n    working_set.entries = []\n    # match order\n    list(map(working_set.add_entry, sys.path))\n    globals().update(locals())\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/appdirs.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright (c) 2005-2010 ActiveState Software Inc.\n# Copyright (c) 2013 Eddy Petrișor\n\n\"\"\"Utilities for determining application-specific dirs.\n\nSee <http://github.com/ActiveState/appdirs> for details and usage.\n\"\"\"\n# Dev Notes:\n# - MSDN on where to store app data files:\n#   http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120\n# - Mac OS X: http://developer.apple.com/documentation/MacOSX/Conceptual/BPFileSystem/index.html\n# - XDG spec for Un*x: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html\n\n__version_info__ = (1, 4, 3)\n__version__ = '.'.join(map(str, __version_info__))\n\n\nimport sys\nimport os\n\nPY3 = sys.version_info[0] == 3\n\nif PY3:\n    unicode = str\n\nif sys.platform.startswith('java'):\n    import platform\n    os_name = platform.java_ver()[3][0]\n    if os_name.startswith('Windows'): # \"Windows XP\", \"Windows 7\", etc.\n        system = 'win32'\n    elif os_name.startswith('Mac'): # \"Mac OS X\", etc.\n        system = 'darwin'\n    else: # \"Linux\", \"SunOS\", \"FreeBSD\", etc.\n        # Setting this to \"linux2\" is not ideal, but only Windows or Mac\n        # are actually checked for and the rest of the module expects\n        # *sys.platform* style strings.\n        system = 'linux2'\nelse:\n    system = sys.platform\n\n\n\ndef user_data_dir(appname=None, appauthor=None, version=None, roaming=False):\n    r\"\"\"Return full path to the user-specific data dir for this application.\n\n        \"appname\" is the name of application.\n            If None, just the system directory is returned.\n        \"appauthor\" (only used on Windows) is the name of the\n            appauthor or distributing body for this application. Typically\n            it is the owning company name. This falls back to appname. You may\n            pass False to disable it.\n        \"version\" is an optional version path element to append to the\n            path. You might want to use this if you want multiple versions\n            of your app to be able to run independently. If used, this\n            would typically be \"<major>.<minor>\".\n            Only applied when appname is present.\n        \"roaming\" (boolean, default False) can be set True to use the Windows\n            roaming appdata directory. That means that for users on a Windows\n            network setup for roaming profiles, this user data will be\n            sync'd on login. See\n            <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>\n            for a discussion of issues.\n\n    Typical user data directories are:\n        Mac OS X:               ~/Library/Application Support/<AppName>\n        Unix:                   ~/.local/share/<AppName>    # or in $XDG_DATA_HOME, if defined\n        Win XP (not roaming):   C:\\Documents and Settings\\<username>\\Application Data\\<AppAuthor>\\<AppName>\n        Win XP (roaming):       C:\\Documents and Settings\\<username>\\Local Settings\\Application Data\\<AppAuthor>\\<AppName>\n        Win 7  (not roaming):   C:\\Users\\<username>\\AppData\\Local\\<AppAuthor>\\<AppName>\n        Win 7  (roaming):       C:\\Users\\<username>\\AppData\\Roaming\\<AppAuthor>\\<AppName>\n\n    For Unix, we follow the XDG spec and support $XDG_DATA_HOME.\n    That means, by default \"~/.local/share/<AppName>\".\n    \"\"\"\n    if system == \"win32\":\n        if appauthor is None:\n            appauthor = appname\n        const = roaming and \"CSIDL_APPDATA\" or \"CSIDL_LOCAL_APPDATA\"\n        path = os.path.normpath(_get_win_folder(const))\n        if appname:\n            if appauthor is not False:\n                path = os.path.join(path, appauthor, appname)\n            else:\n                path = os.path.join(path, appname)\n    elif system == 'darwin':\n        path = os.path.expanduser('~/Library/Application Support/')\n        if appname:\n            path = os.path.join(path, appname)\n    else:\n        path = os.getenv('XDG_DATA_HOME', os.path.expanduser(\"~/.local/share\"))\n        if appname:\n            path = os.path.join(path, appname)\n    if appname and version:\n        path = os.path.join(path, version)\n    return path\n\n\ndef site_data_dir(appname=None, appauthor=None, version=None, multipath=False):\n    r\"\"\"Return full path to the user-shared data dir for this application.\n\n        \"appname\" is the name of application.\n            If None, just the system directory is returned.\n        \"appauthor\" (only used on Windows) is the name of the\n            appauthor or distributing body for this application. Typically\n            it is the owning company name. This falls back to appname. You may\n            pass False to disable it.\n        \"version\" is an optional version path element to append to the\n            path. You might want to use this if you want multiple versions\n            of your app to be able to run independently. If used, this\n            would typically be \"<major>.<minor>\".\n            Only applied when appname is present.\n        \"multipath\" is an optional parameter only applicable to *nix\n            which indicates that the entire list of data dirs should be\n            returned. By default, the first item from XDG_DATA_DIRS is\n            returned, or '/usr/local/share/<AppName>',\n            if XDG_DATA_DIRS is not set\n\n    Typical site data directories are:\n        Mac OS X:   /Library/Application Support/<AppName>\n        Unix:       /usr/local/share/<AppName> or /usr/share/<AppName>\n        Win XP:     C:\\Documents and Settings\\All Users\\Application Data\\<AppAuthor>\\<AppName>\n        Vista:      (Fail! \"C:\\ProgramData\" is a hidden *system* directory on Vista.)\n        Win 7:      C:\\ProgramData\\<AppAuthor>\\<AppName>   # Hidden, but writeable on Win 7.\n\n    For Unix, this is using the $XDG_DATA_DIRS[0] default.\n\n    WARNING: Do not use this on Windows. See the Vista-Fail note above for why.\n    \"\"\"\n    if system == \"win32\":\n        if appauthor is None:\n            appauthor = appname\n        path = os.path.normpath(_get_win_folder(\"CSIDL_COMMON_APPDATA\"))\n        if appname:\n            if appauthor is not False:\n                path = os.path.join(path, appauthor, appname)\n            else:\n                path = os.path.join(path, appname)\n    elif system == 'darwin':\n        path = os.path.expanduser('/Library/Application Support')\n        if appname:\n            path = os.path.join(path, appname)\n    else:\n        # XDG default for $XDG_DATA_DIRS\n        # only first, if multipath is False\n        path = os.getenv('XDG_DATA_DIRS',\n                         os.pathsep.join(['/usr/local/share', '/usr/share']))\n        pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)]\n        if appname:\n            if version:\n                appname = os.path.join(appname, version)\n            pathlist = [os.sep.join([x, appname]) for x in pathlist]\n\n        if multipath:\n            path = os.pathsep.join(pathlist)\n        else:\n            path = pathlist[0]\n        return path\n\n    if appname and version:\n        path = os.path.join(path, version)\n    return path\n\n\ndef user_config_dir(appname=None, appauthor=None, version=None, roaming=False):\n    r\"\"\"Return full path to the user-specific config dir for this application.\n\n        \"appname\" is the name of application.\n            If None, just the system directory is returned.\n        \"appauthor\" (only used on Windows) is the name of the\n            appauthor or distributing body for this application. Typically\n            it is the owning company name. This falls back to appname. You may\n            pass False to disable it.\n        \"version\" is an optional version path element to append to the\n            path. You might want to use this if you want multiple versions\n            of your app to be able to run independently. If used, this\n            would typically be \"<major>.<minor>\".\n            Only applied when appname is present.\n        \"roaming\" (boolean, default False) can be set True to use the Windows\n            roaming appdata directory. That means that for users on a Windows\n            network setup for roaming profiles, this user data will be\n            sync'd on login. See\n            <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>\n            for a discussion of issues.\n\n    Typical user config directories are:\n        Mac OS X:               same as user_data_dir\n        Unix:                   ~/.config/<AppName>     # or in $XDG_CONFIG_HOME, if defined\n        Win *:                  same as user_data_dir\n\n    For Unix, we follow the XDG spec and support $XDG_CONFIG_HOME.\n    That means, by default \"~/.config/<AppName>\".\n    \"\"\"\n    if system in [\"win32\", \"darwin\"]:\n        path = user_data_dir(appname, appauthor, None, roaming)\n    else:\n        path = os.getenv('XDG_CONFIG_HOME', os.path.expanduser(\"~/.config\"))\n        if appname:\n            path = os.path.join(path, appname)\n    if appname and version:\n        path = os.path.join(path, version)\n    return path\n\n\ndef site_config_dir(appname=None, appauthor=None, version=None, multipath=False):\n    r\"\"\"Return full path to the user-shared data dir for this application.\n\n        \"appname\" is the name of application.\n            If None, just the system directory is returned.\n        \"appauthor\" (only used on Windows) is the name of the\n            appauthor or distributing body for this application. Typically\n            it is the owning company name. This falls back to appname. You may\n            pass False to disable it.\n        \"version\" is an optional version path element to append to the\n            path. You might want to use this if you want multiple versions\n            of your app to be able to run independently. If used, this\n            would typically be \"<major>.<minor>\".\n            Only applied when appname is present.\n        \"multipath\" is an optional parameter only applicable to *nix\n            which indicates that the entire list of config dirs should be\n            returned. By default, the first item from XDG_CONFIG_DIRS is\n            returned, or '/etc/xdg/<AppName>', if XDG_CONFIG_DIRS is not set\n\n    Typical site config directories are:\n        Mac OS X:   same as site_data_dir\n        Unix:       /etc/xdg/<AppName> or $XDG_CONFIG_DIRS[i]/<AppName> for each value in\n                    $XDG_CONFIG_DIRS\n        Win *:      same as site_data_dir\n        Vista:      (Fail! \"C:\\ProgramData\" is a hidden *system* directory on Vista.)\n\n    For Unix, this is using the $XDG_CONFIG_DIRS[0] default, if multipath=False\n\n    WARNING: Do not use this on Windows. See the Vista-Fail note above for why.\n    \"\"\"\n    if system in [\"win32\", \"darwin\"]:\n        path = site_data_dir(appname, appauthor)\n        if appname and version:\n            path = os.path.join(path, version)\n    else:\n        # XDG default for $XDG_CONFIG_DIRS\n        # only first, if multipath is False\n        path = os.getenv('XDG_CONFIG_DIRS', '/etc/xdg')\n        pathlist = [os.path.expanduser(x.rstrip(os.sep)) for x in path.split(os.pathsep)]\n        if appname:\n            if version:\n                appname = os.path.join(appname, version)\n            pathlist = [os.sep.join([x, appname]) for x in pathlist]\n\n        if multipath:\n            path = os.pathsep.join(pathlist)\n        else:\n            path = pathlist[0]\n    return path\n\n\ndef user_cache_dir(appname=None, appauthor=None, version=None, opinion=True):\n    r\"\"\"Return full path to the user-specific cache dir for this application.\n\n        \"appname\" is the name of application.\n            If None, just the system directory is returned.\n        \"appauthor\" (only used on Windows) is the name of the\n            appauthor or distributing body for this application. Typically\n            it is the owning company name. This falls back to appname. You may\n            pass False to disable it.\n        \"version\" is an optional version path element to append to the\n            path. You might want to use this if you want multiple versions\n            of your app to be able to run independently. If used, this\n            would typically be \"<major>.<minor>\".\n            Only applied when appname is present.\n        \"opinion\" (boolean) can be False to disable the appending of\n            \"Cache\" to the base app data dir for Windows. See\n            discussion below.\n\n    Typical user cache directories are:\n        Mac OS X:   ~/Library/Caches/<AppName>\n        Unix:       ~/.cache/<AppName> (XDG default)\n        Win XP:     C:\\Documents and Settings\\<username>\\Local Settings\\Application Data\\<AppAuthor>\\<AppName>\\Cache\n        Vista:      C:\\Users\\<username>\\AppData\\Local\\<AppAuthor>\\<AppName>\\Cache\n\n    On Windows the only suggestion in the MSDN docs is that local settings go in\n    the `CSIDL_LOCAL_APPDATA` directory. This is identical to the non-roaming\n    app data dir (the default returned by `user_data_dir` above). Apps typically\n    put cache data somewhere *under* the given dir here. Some examples:\n        ...\\Mozilla\\Firefox\\Profiles\\<ProfileName>\\Cache\n        ...\\Acme\\SuperApp\\Cache\\1.0\n    OPINION: This function appends \"Cache\" to the `CSIDL_LOCAL_APPDATA` value.\n    This can be disabled with the `opinion=False` option.\n    \"\"\"\n    if system == \"win32\":\n        if appauthor is None:\n            appauthor = appname\n        path = os.path.normpath(_get_win_folder(\"CSIDL_LOCAL_APPDATA\"))\n        if appname:\n            if appauthor is not False:\n                path = os.path.join(path, appauthor, appname)\n            else:\n                path = os.path.join(path, appname)\n            if opinion:\n                path = os.path.join(path, \"Cache\")\n    elif system == 'darwin':\n        path = os.path.expanduser('~/Library/Caches')\n        if appname:\n            path = os.path.join(path, appname)\n    else:\n        path = os.getenv('XDG_CACHE_HOME', os.path.expanduser('~/.cache'))\n        if appname:\n            path = os.path.join(path, appname)\n    if appname and version:\n        path = os.path.join(path, version)\n    return path\n\n\ndef user_state_dir(appname=None, appauthor=None, version=None, roaming=False):\n    r\"\"\"Return full path to the user-specific state dir for this application.\n\n        \"appname\" is the name of application.\n            If None, just the system directory is returned.\n        \"appauthor\" (only used on Windows) is the name of the\n            appauthor or distributing body for this application. Typically\n            it is the owning company name. This falls back to appname. You may\n            pass False to disable it.\n        \"version\" is an optional version path element to append to the\n            path. You might want to use this if you want multiple versions\n            of your app to be able to run independently. If used, this\n            would typically be \"<major>.<minor>\".\n            Only applied when appname is present.\n        \"roaming\" (boolean, default False) can be set True to use the Windows\n            roaming appdata directory. That means that for users on a Windows\n            network setup for roaming profiles, this user data will be\n            sync'd on login. See\n            <http://technet.microsoft.com/en-us/library/cc766489(WS.10).aspx>\n            for a discussion of issues.\n\n    Typical user state directories are:\n        Mac OS X:  same as user_data_dir\n        Unix:      ~/.local/state/<AppName>   # or in $XDG_STATE_HOME, if defined\n        Win *:     same as user_data_dir\n\n    For Unix, we follow this Debian proposal <https://wiki.debian.org/XDGBaseDirectorySpecification#state>\n    to extend the XDG spec and support $XDG_STATE_HOME.\n\n    That means, by default \"~/.local/state/<AppName>\".\n    \"\"\"\n    if system in [\"win32\", \"darwin\"]:\n        path = user_data_dir(appname, appauthor, None, roaming)\n    else:\n        path = os.getenv('XDG_STATE_HOME', os.path.expanduser(\"~/.local/state\"))\n        if appname:\n            path = os.path.join(path, appname)\n    if appname and version:\n        path = os.path.join(path, version)\n    return path\n\n\ndef user_log_dir(appname=None, appauthor=None, version=None, opinion=True):\n    r\"\"\"Return full path to the user-specific log dir for this application.\n\n        \"appname\" is the name of application.\n            If None, just the system directory is returned.\n        \"appauthor\" (only used on Windows) is the name of the\n            appauthor or distributing body for this application. Typically\n            it is the owning company name. This falls back to appname. You may\n            pass False to disable it.\n        \"version\" is an optional version path element to append to the\n            path. You might want to use this if you want multiple versions\n            of your app to be able to run independently. If used, this\n            would typically be \"<major>.<minor>\".\n            Only applied when appname is present.\n        \"opinion\" (boolean) can be False to disable the appending of\n            \"Logs\" to the base app data dir for Windows, and \"log\" to the\n            base cache dir for Unix. See discussion below.\n\n    Typical user log directories are:\n        Mac OS X:   ~/Library/Logs/<AppName>\n        Unix:       ~/.cache/<AppName>/log  # or under $XDG_CACHE_HOME if defined\n        Win XP:     C:\\Documents and Settings\\<username>\\Local Settings\\Application Data\\<AppAuthor>\\<AppName>\\Logs\n        Vista:      C:\\Users\\<username>\\AppData\\Local\\<AppAuthor>\\<AppName>\\Logs\n\n    On Windows the only suggestion in the MSDN docs is that local settings\n    go in the `CSIDL_LOCAL_APPDATA` directory. (Note: I'm interested in\n    examples of what some windows apps use for a logs dir.)\n\n    OPINION: This function appends \"Logs\" to the `CSIDL_LOCAL_APPDATA`\n    value for Windows and appends \"log\" to the user cache dir for Unix.\n    This can be disabled with the `opinion=False` option.\n    \"\"\"\n    if system == \"darwin\":\n        path = os.path.join(\n            os.path.expanduser('~/Library/Logs'),\n            appname)\n    elif system == \"win32\":\n        path = user_data_dir(appname, appauthor, version)\n        version = False\n        if opinion:\n            path = os.path.join(path, \"Logs\")\n    else:\n        path = user_cache_dir(appname, appauthor, version)\n        version = False\n        if opinion:\n            path = os.path.join(path, \"log\")\n    if appname and version:\n        path = os.path.join(path, version)\n    return path\n\n\nclass AppDirs(object):\n    \"\"\"Convenience wrapper for getting application dirs.\"\"\"\n    def __init__(self, appname=None, appauthor=None, version=None,\n            roaming=False, multipath=False):\n        self.appname = appname\n        self.appauthor = appauthor\n        self.version = version\n        self.roaming = roaming\n        self.multipath = multipath\n\n    @property\n    def user_data_dir(self):\n        return user_data_dir(self.appname, self.appauthor,\n                             version=self.version, roaming=self.roaming)\n\n    @property\n    def site_data_dir(self):\n        return site_data_dir(self.appname, self.appauthor,\n                             version=self.version, multipath=self.multipath)\n\n    @property\n    def user_config_dir(self):\n        return user_config_dir(self.appname, self.appauthor,\n                               version=self.version, roaming=self.roaming)\n\n    @property\n    def site_config_dir(self):\n        return site_config_dir(self.appname, self.appauthor,\n                             version=self.version, multipath=self.multipath)\n\n    @property\n    def user_cache_dir(self):\n        return user_cache_dir(self.appname, self.appauthor,\n                              version=self.version)\n\n    @property\n    def user_state_dir(self):\n        return user_state_dir(self.appname, self.appauthor,\n                              version=self.version)\n\n    @property\n    def user_log_dir(self):\n        return user_log_dir(self.appname, self.appauthor,\n                            version=self.version)\n\n\n#---- internal support stuff\n\ndef _get_win_folder_from_registry(csidl_name):\n    \"\"\"This is a fallback technique at best. I'm not sure if using the\n    registry for this guarantees us the correct answer for all CSIDL_*\n    names.\n    \"\"\"\n    if PY3:\n      import winreg as _winreg\n    else:\n      import _winreg\n\n    shell_folder_name = {\n        \"CSIDL_APPDATA\": \"AppData\",\n        \"CSIDL_COMMON_APPDATA\": \"Common AppData\",\n        \"CSIDL_LOCAL_APPDATA\": \"Local AppData\",\n    }[csidl_name]\n\n    key = _winreg.OpenKey(\n        _winreg.HKEY_CURRENT_USER,\n        r\"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\"\n    )\n    dir, type = _winreg.QueryValueEx(key, shell_folder_name)\n    return dir\n\n\ndef _get_win_folder_with_pywin32(csidl_name):\n    from win32com.shell import shellcon, shell\n    dir = shell.SHGetFolderPath(0, getattr(shellcon, csidl_name), 0, 0)\n    # Try to make this a unicode path because SHGetFolderPath does\n    # not return unicode strings when there is unicode data in the\n    # path.\n    try:\n        dir = unicode(dir)\n\n        # Downgrade to short path name if have highbit chars. See\n        # <http://bugs.activestate.com/show_bug.cgi?id=85099>.\n        has_high_char = False\n        for c in dir:\n            if ord(c) > 255:\n                has_high_char = True\n                break\n        if has_high_char:\n            try:\n                import win32api\n                dir = win32api.GetShortPathName(dir)\n            except ImportError:\n                pass\n    except UnicodeError:\n        pass\n    return dir\n\n\ndef _get_win_folder_with_ctypes(csidl_name):\n    import ctypes\n\n    csidl_const = {\n        \"CSIDL_APPDATA\": 26,\n        \"CSIDL_COMMON_APPDATA\": 35,\n        \"CSIDL_LOCAL_APPDATA\": 28,\n    }[csidl_name]\n\n    buf = ctypes.create_unicode_buffer(1024)\n    ctypes.windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)\n\n    # Downgrade to short path name if have highbit chars. See\n    # <http://bugs.activestate.com/show_bug.cgi?id=85099>.\n    has_high_char = False\n    for c in buf:\n        if ord(c) > 255:\n            has_high_char = True\n            break\n    if has_high_char:\n        buf2 = ctypes.create_unicode_buffer(1024)\n        if ctypes.windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):\n            buf = buf2\n\n    return buf.value\n\ndef _get_win_folder_with_jna(csidl_name):\n    import array\n    from com.sun import jna\n    from com.sun.jna.platform import win32\n\n    buf_size = win32.WinDef.MAX_PATH * 2\n    buf = array.zeros('c', buf_size)\n    shell = win32.Shell32.INSTANCE\n    shell.SHGetFolderPath(None, getattr(win32.ShlObj, csidl_name), None, win32.ShlObj.SHGFP_TYPE_CURRENT, buf)\n    dir = jna.Native.toString(buf.tostring()).rstrip(\"\\0\")\n\n    # Downgrade to short path name if have highbit chars. See\n    # <http://bugs.activestate.com/show_bug.cgi?id=85099>.\n    has_high_char = False\n    for c in dir:\n        if ord(c) > 255:\n            has_high_char = True\n            break\n    if has_high_char:\n        buf = array.zeros('c', buf_size)\n        kernel = win32.Kernel32.INSTANCE\n        if kernel.GetShortPathName(dir, buf, buf_size):\n            dir = jna.Native.toString(buf.tostring()).rstrip(\"\\0\")\n\n    return dir\n\nif system == \"win32\":\n    try:\n        import win32com.shell\n        _get_win_folder = _get_win_folder_with_pywin32\n    except ImportError:\n        try:\n            from ctypes import windll\n            _get_win_folder = _get_win_folder_with_ctypes\n        except ImportError:\n            try:\n                import com.sun.jna\n                _get_win_folder = _get_win_folder_with_jna\n            except ImportError:\n                _get_win_folder = _get_win_folder_from_registry\n\n\n#---- self test code\n\nif __name__ == \"__main__\":\n    appname = \"MyApp\"\n    appauthor = \"MyCompany\"\n\n    props = (\"user_data_dir\",\n             \"user_config_dir\",\n             \"user_cache_dir\",\n             \"user_state_dir\",\n             \"user_log_dir\",\n             \"site_data_dir\",\n             \"site_config_dir\")\n\n    print(\"-- app dirs %s --\" % __version__)\n\n    print(\"-- app dirs (with optional 'version')\")\n    dirs = AppDirs(appname, appauthor, version=\"1.0\")\n    for prop in props:\n        print(\"%s: %s\" % (prop, getattr(dirs, prop)))\n\n    print(\"\\n-- app dirs (without optional 'version')\")\n    dirs = AppDirs(appname, appauthor)\n    for prop in props:\n        print(\"%s: %s\" % (prop, getattr(dirs, prop)))\n\n    print(\"\\n-- app dirs (without optional 'appauthor')\")\n    dirs = AppDirs(appname)\n    for prop in props:\n        print(\"%s: %s\" % (prop, getattr(dirs, prop)))\n\n    print(\"\\n-- app dirs (with disabled 'appauthor')\")\n    dirs = AppDirs(appname, appauthor=False)\n    for prop in props:\n        print(\"%s: %s\" % (prop, getattr(dirs, prop)))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/importlib_resources/__init__.py",
    "content": "\"\"\"Read resources contained within a package.\"\"\"\n\nfrom ._common import (\n    as_file,\n    files,\n    Package,\n)\n\nfrom ._legacy import (\n    contents,\n    open_binary,\n    read_binary,\n    open_text,\n    read_text,\n    is_resource,\n    path,\n    Resource,\n)\n\nfrom .abc import ResourceReader\n\n\n__all__ = [\n    'Package',\n    'Resource',\n    'ResourceReader',\n    'as_file',\n    'contents',\n    'files',\n    'is_resource',\n    'open_binary',\n    'open_text',\n    'path',\n    'read_binary',\n    'read_text',\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/importlib_resources/_adapters.py",
    "content": "from contextlib import suppress\nfrom io import TextIOWrapper\n\nfrom . import abc\n\n\nclass SpecLoaderAdapter:\n    \"\"\"\n    Adapt a package spec to adapt the underlying loader.\n    \"\"\"\n\n    def __init__(self, spec, adapter=lambda spec: spec.loader):\n        self.spec = spec\n        self.loader = adapter(spec)\n\n    def __getattr__(self, name):\n        return getattr(self.spec, name)\n\n\nclass TraversableResourcesLoader:\n    \"\"\"\n    Adapt a loader to provide TraversableResources.\n    \"\"\"\n\n    def __init__(self, spec):\n        self.spec = spec\n\n    def get_resource_reader(self, name):\n        return CompatibilityFiles(self.spec)._native()\n\n\ndef _io_wrapper(file, mode='r', *args, **kwargs):\n    if mode == 'r':\n        return TextIOWrapper(file, *args, **kwargs)\n    elif mode == 'rb':\n        return file\n    raise ValueError(\n        \"Invalid mode value '{}', only 'r' and 'rb' are supported\".format(mode)\n    )\n\n\nclass CompatibilityFiles:\n    \"\"\"\n    Adapter for an existing or non-existent resource reader\n    to provide a compatibility .files().\n    \"\"\"\n\n    class SpecPath(abc.Traversable):\n        \"\"\"\n        Path tied to a module spec.\n        Can be read and exposes the resource reader children.\n        \"\"\"\n\n        def __init__(self, spec, reader):\n            self._spec = spec\n            self._reader = reader\n\n        def iterdir(self):\n            if not self._reader:\n                return iter(())\n            return iter(\n                CompatibilityFiles.ChildPath(self._reader, path)\n                for path in self._reader.contents()\n            )\n\n        def is_file(self):\n            return False\n\n        is_dir = is_file\n\n        def joinpath(self, other):\n            if not self._reader:\n                return CompatibilityFiles.OrphanPath(other)\n            return CompatibilityFiles.ChildPath(self._reader, other)\n\n        @property\n        def name(self):\n            return self._spec.name\n\n        def open(self, mode='r', *args, **kwargs):\n            return _io_wrapper(self._reader.open_resource(None), mode, *args, **kwargs)\n\n    class ChildPath(abc.Traversable):\n        \"\"\"\n        Path tied to a resource reader child.\n        Can be read but doesn't expose any meaningful children.\n        \"\"\"\n\n        def __init__(self, reader, name):\n            self._reader = reader\n            self._name = name\n\n        def iterdir(self):\n            return iter(())\n\n        def is_file(self):\n            return self._reader.is_resource(self.name)\n\n        def is_dir(self):\n            return not self.is_file()\n\n        def joinpath(self, other):\n            return CompatibilityFiles.OrphanPath(self.name, other)\n\n        @property\n        def name(self):\n            return self._name\n\n        def open(self, mode='r', *args, **kwargs):\n            return _io_wrapper(\n                self._reader.open_resource(self.name), mode, *args, **kwargs\n            )\n\n    class OrphanPath(abc.Traversable):\n        \"\"\"\n        Orphan path, not tied to a module spec or resource reader.\n        Can't be read and doesn't expose any meaningful children.\n        \"\"\"\n\n        def __init__(self, *path_parts):\n            if len(path_parts) < 1:\n                raise ValueError('Need at least one path part to construct a path')\n            self._path = path_parts\n\n        def iterdir(self):\n            return iter(())\n\n        def is_file(self):\n            return False\n\n        is_dir = is_file\n\n        def joinpath(self, other):\n            return CompatibilityFiles.OrphanPath(*self._path, other)\n\n        @property\n        def name(self):\n            return self._path[-1]\n\n        def open(self, mode='r', *args, **kwargs):\n            raise FileNotFoundError(\"Can't open orphan path\")\n\n    def __init__(self, spec):\n        self.spec = spec\n\n    @property\n    def _reader(self):\n        with suppress(AttributeError):\n            return self.spec.loader.get_resource_reader(self.spec.name)\n\n    def _native(self):\n        \"\"\"\n        Return the native reader if it supports files().\n        \"\"\"\n        reader = self._reader\n        return reader if hasattr(reader, 'files') else self\n\n    def __getattr__(self, attr):\n        return getattr(self._reader, attr)\n\n    def files(self):\n        return CompatibilityFiles.SpecPath(self.spec, self._reader)\n\n\ndef wrap_spec(package):\n    \"\"\"\n    Construct a package spec with traversable compatibility\n    on the spec/loader/reader.\n    \"\"\"\n    return SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/importlib_resources/_common.py",
    "content": "import os\nimport pathlib\nimport tempfile\nimport functools\nimport contextlib\nimport types\nimport importlib\n\nfrom typing import Union, Optional\nfrom .abc import ResourceReader, Traversable\n\nfrom ._compat import wrap_spec\n\nPackage = Union[types.ModuleType, str]\n\n\ndef files(package):\n    # type: (Package) -> Traversable\n    \"\"\"\n    Get a Traversable resource from a package\n    \"\"\"\n    return from_package(get_package(package))\n\n\ndef get_resource_reader(package):\n    # type: (types.ModuleType) -> Optional[ResourceReader]\n    \"\"\"\n    Return the package's loader if it's a ResourceReader.\n    \"\"\"\n    # We can't use\n    # a issubclass() check here because apparently abc.'s __subclasscheck__()\n    # hook wants to create a weak reference to the object, but\n    # zipimport.zipimporter does not support weak references, resulting in a\n    # TypeError.  That seems terrible.\n    spec = package.__spec__\n    reader = getattr(spec.loader, 'get_resource_reader', None)  # type: ignore\n    if reader is None:\n        return None\n    return reader(spec.name)  # type: ignore\n\n\ndef resolve(cand):\n    # type: (Package) -> types.ModuleType\n    return cand if isinstance(cand, types.ModuleType) else importlib.import_module(cand)\n\n\ndef get_package(package):\n    # type: (Package) -> types.ModuleType\n    \"\"\"Take a package name or module object and return the module.\n\n    Raise an exception if the resolved module is not a package.\n    \"\"\"\n    resolved = resolve(package)\n    if wrap_spec(resolved).submodule_search_locations is None:\n        raise TypeError(f'{package!r} is not a package')\n    return resolved\n\n\ndef from_package(package):\n    \"\"\"\n    Return a Traversable object for the given package.\n\n    \"\"\"\n    spec = wrap_spec(package)\n    reader = spec.loader.get_resource_reader(spec.name)\n    return reader.files()\n\n\n@contextlib.contextmanager\ndef _tempfile(reader, suffix=''):\n    # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try'\n    # blocks due to the need to close the temporary file to work on Windows\n    # properly.\n    fd, raw_path = tempfile.mkstemp(suffix=suffix)\n    try:\n        try:\n            os.write(fd, reader())\n        finally:\n            os.close(fd)\n        del reader\n        yield pathlib.Path(raw_path)\n    finally:\n        try:\n            os.remove(raw_path)\n        except FileNotFoundError:\n            pass\n\n\n@functools.singledispatch\ndef as_file(path):\n    \"\"\"\n    Given a Traversable object, return that object as a\n    path on the local file system in a context manager.\n    \"\"\"\n    return _tempfile(path.read_bytes, suffix=path.name)\n\n\n@as_file.register(pathlib.Path)\n@contextlib.contextmanager\ndef _(path):\n    \"\"\"\n    Degenerate behavior for pathlib.Path objects.\n    \"\"\"\n    yield path\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/importlib_resources/_compat.py",
    "content": "# flake8: noqa\n\nimport abc\nimport sys\nimport pathlib\nfrom contextlib import suppress\n\nif sys.version_info >= (3, 10):\n    from zipfile import Path as ZipPath  # type: ignore\nelse:\n    from ..zipp import Path as ZipPath  # type: ignore\n\n\ntry:\n    from typing import runtime_checkable  # type: ignore\nexcept ImportError:\n\n    def runtime_checkable(cls):  # type: ignore\n        return cls\n\n\ntry:\n    from typing import Protocol  # type: ignore\nexcept ImportError:\n    Protocol = abc.ABC  # type: ignore\n\n\nclass TraversableResourcesLoader:\n    \"\"\"\n    Adapt loaders to provide TraversableResources and other\n    compatibility.\n\n    Used primarily for Python 3.9 and earlier where the native\n    loaders do not yet implement TraversableResources.\n    \"\"\"\n\n    def __init__(self, spec):\n        self.spec = spec\n\n    @property\n    def path(self):\n        return self.spec.origin\n\n    def get_resource_reader(self, name):\n        from . import readers, _adapters\n\n        def _zip_reader(spec):\n            with suppress(AttributeError):\n                return readers.ZipReader(spec.loader, spec.name)\n\n        def _namespace_reader(spec):\n            with suppress(AttributeError, ValueError):\n                return readers.NamespaceReader(spec.submodule_search_locations)\n\n        def _available_reader(spec):\n            with suppress(AttributeError):\n                return spec.loader.get_resource_reader(spec.name)\n\n        def _native_reader(spec):\n            reader = _available_reader(spec)\n            return reader if hasattr(reader, 'files') else None\n\n        def _file_reader(spec):\n            try:\n                path = pathlib.Path(self.path)\n            except TypeError:\n                return None\n            if path.exists():\n                return readers.FileReader(self)\n\n        return (\n            # native reader if it supplies 'files'\n            _native_reader(self.spec)\n            or\n            # local ZipReader if a zip module\n            _zip_reader(self.spec)\n            or\n            # local NamespaceReader if a namespace module\n            _namespace_reader(self.spec)\n            or\n            # local FileReader\n            _file_reader(self.spec)\n            # fallback - adapt the spec ResourceReader to TraversableReader\n            or _adapters.CompatibilityFiles(self.spec)\n        )\n\n\ndef wrap_spec(package):\n    \"\"\"\n    Construct a package spec with traversable compatibility\n    on the spec/loader/reader.\n\n    Supersedes _adapters.wrap_spec to use TraversableResourcesLoader\n    from above for older Python compatibility (<3.10).\n    \"\"\"\n    from . import _adapters\n\n    return _adapters.SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/importlib_resources/_itertools.py",
    "content": "from itertools import filterfalse\n\nfrom typing import (\n    Callable,\n    Iterable,\n    Iterator,\n    Optional,\n    Set,\n    TypeVar,\n    Union,\n)\n\n# Type and type variable definitions\n_T = TypeVar('_T')\n_U = TypeVar('_U')\n\n\ndef unique_everseen(\n    iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = None\n) -> Iterator[_T]:\n    \"List unique elements, preserving order. Remember all elements ever seen.\"\n    # unique_everseen('AAAABBBCCDAABBB') --> A B C D\n    # unique_everseen('ABBCcAD', str.lower) --> A B C D\n    seen: Set[Union[_T, _U]] = set()\n    seen_add = seen.add\n    if key is None:\n        for element in filterfalse(seen.__contains__, iterable):\n            seen_add(element)\n            yield element\n    else:\n        for element in iterable:\n            k = key(element)\n            if k not in seen:\n                seen_add(k)\n                yield element\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/importlib_resources/_legacy.py",
    "content": "import functools\nimport os\nimport pathlib\nimport types\nimport warnings\n\nfrom typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any\n\nfrom . import _common\n\nPackage = Union[types.ModuleType, str]\nResource = str\n\n\ndef deprecated(func):\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        warnings.warn(\n            f\"{func.__name__} is deprecated. Use files() instead. \"\n            \"Refer to https://importlib-resources.readthedocs.io\"\n            \"/en/latest/using.html#migrating-from-legacy for migration advice.\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        return func(*args, **kwargs)\n\n    return wrapper\n\n\ndef normalize_path(path):\n    # type: (Any) -> str\n    \"\"\"Normalize a path by ensuring it is a string.\n\n    If the resulting string contains path separators, an exception is raised.\n    \"\"\"\n    str_path = str(path)\n    parent, file_name = os.path.split(str_path)\n    if parent:\n        raise ValueError(f'{path!r} must be only a file name')\n    return file_name\n\n\n@deprecated\ndef open_binary(package: Package, resource: Resource) -> BinaryIO:\n    \"\"\"Return a file-like object opened for binary reading of the resource.\"\"\"\n    return (_common.files(package) / normalize_path(resource)).open('rb')\n\n\n@deprecated\ndef read_binary(package: Package, resource: Resource) -> bytes:\n    \"\"\"Return the binary contents of the resource.\"\"\"\n    return (_common.files(package) / normalize_path(resource)).read_bytes()\n\n\n@deprecated\ndef open_text(\n    package: Package,\n    resource: Resource,\n    encoding: str = 'utf-8',\n    errors: str = 'strict',\n) -> TextIO:\n    \"\"\"Return a file-like object opened for text reading of the resource.\"\"\"\n    return (_common.files(package) / normalize_path(resource)).open(\n        'r', encoding=encoding, errors=errors\n    )\n\n\n@deprecated\ndef read_text(\n    package: Package,\n    resource: Resource,\n    encoding: str = 'utf-8',\n    errors: str = 'strict',\n) -> str:\n    \"\"\"Return the decoded string of the resource.\n\n    The decoding-related arguments have the same semantics as those of\n    bytes.decode().\n    \"\"\"\n    with open_text(package, resource, encoding, errors) as fp:\n        return fp.read()\n\n\n@deprecated\ndef contents(package: Package) -> Iterable[str]:\n    \"\"\"Return an iterable of entries in `package`.\n\n    Note that not all entries are resources.  Specifically, directories are\n    not considered resources.  Use `is_resource()` on each entry returned here\n    to check if it is a resource or not.\n    \"\"\"\n    return [path.name for path in _common.files(package).iterdir()]\n\n\n@deprecated\ndef is_resource(package: Package, name: str) -> bool:\n    \"\"\"True if `name` is a resource inside `package`.\n\n    Directories are *not* resources.\n    \"\"\"\n    resource = normalize_path(name)\n    return any(\n        traversable.name == resource and traversable.is_file()\n        for traversable in _common.files(package).iterdir()\n    )\n\n\n@deprecated\ndef path(\n    package: Package,\n    resource: Resource,\n) -> ContextManager[pathlib.Path]:\n    \"\"\"A context manager providing a file path object to the resource.\n\n    If the resource does not already exist on its own on the file system,\n    a temporary file will be created. If the file was created, the file\n    will be deleted upon exiting the context manager (no exception is\n    raised if the file was deleted prior to the context manager\n    exiting).\n    \"\"\"\n    return _common.as_file(_common.files(package) / normalize_path(resource))\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/importlib_resources/abc.py",
    "content": "import abc\nfrom typing import BinaryIO, Iterable, Text\n\nfrom ._compat import runtime_checkable, Protocol\n\n\nclass ResourceReader(metaclass=abc.ABCMeta):\n    \"\"\"Abstract base class for loaders to provide resource reading support.\"\"\"\n\n    @abc.abstractmethod\n    def open_resource(self, resource: Text) -> BinaryIO:\n        \"\"\"Return an opened, file-like object for binary reading.\n\n        The 'resource' argument is expected to represent only a file name.\n        If the resource cannot be found, FileNotFoundError is raised.\n        \"\"\"\n        # This deliberately raises FileNotFoundError instead of\n        # NotImplementedError so that if this method is accidentally called,\n        # it'll still do the right thing.\n        raise FileNotFoundError\n\n    @abc.abstractmethod\n    def resource_path(self, resource: Text) -> Text:\n        \"\"\"Return the file system path to the specified resource.\n\n        The 'resource' argument is expected to represent only a file name.\n        If the resource does not exist on the file system, raise\n        FileNotFoundError.\n        \"\"\"\n        # This deliberately raises FileNotFoundError instead of\n        # NotImplementedError so that if this method is accidentally called,\n        # it'll still do the right thing.\n        raise FileNotFoundError\n\n    @abc.abstractmethod\n    def is_resource(self, path: Text) -> bool:\n        \"\"\"Return True if the named 'path' is a resource.\n\n        Files are resources, directories are not.\n        \"\"\"\n        raise FileNotFoundError\n\n    @abc.abstractmethod\n    def contents(self) -> Iterable[str]:\n        \"\"\"Return an iterable of entries in `package`.\"\"\"\n        raise FileNotFoundError\n\n\n@runtime_checkable\nclass Traversable(Protocol):\n    \"\"\"\n    An object with a subset of pathlib.Path methods suitable for\n    traversing directories and opening files.\n    \"\"\"\n\n    @abc.abstractmethod\n    def iterdir(self):\n        \"\"\"\n        Yield Traversable objects in self\n        \"\"\"\n\n    def read_bytes(self):\n        \"\"\"\n        Read contents of self as bytes\n        \"\"\"\n        with self.open('rb') as strm:\n            return strm.read()\n\n    def read_text(self, encoding=None):\n        \"\"\"\n        Read contents of self as text\n        \"\"\"\n        with self.open(encoding=encoding) as strm:\n            return strm.read()\n\n    @abc.abstractmethod\n    def is_dir(self) -> bool:\n        \"\"\"\n        Return True if self is a directory\n        \"\"\"\n\n    @abc.abstractmethod\n    def is_file(self) -> bool:\n        \"\"\"\n        Return True if self is a file\n        \"\"\"\n\n    @abc.abstractmethod\n    def joinpath(self, child):\n        \"\"\"\n        Return Traversable child in self\n        \"\"\"\n\n    def __truediv__(self, child):\n        \"\"\"\n        Return Traversable child in self\n        \"\"\"\n        return self.joinpath(child)\n\n    @abc.abstractmethod\n    def open(self, mode='r', *args, **kwargs):\n        \"\"\"\n        mode may be 'r' or 'rb' to open as text or binary. Return a handle\n        suitable for reading (same as pathlib.Path.open).\n\n        When opening as text, accepts encoding parameters such as those\n        accepted by io.TextIOWrapper.\n        \"\"\"\n\n    @abc.abstractproperty\n    def name(self) -> str:\n        \"\"\"\n        The base name of this object without any parent references.\n        \"\"\"\n\n\nclass TraversableResources(ResourceReader):\n    \"\"\"\n    The required interface for providing traversable\n    resources.\n    \"\"\"\n\n    @abc.abstractmethod\n    def files(self):\n        \"\"\"Return a Traversable object for the loaded package.\"\"\"\n\n    def open_resource(self, resource):\n        return self.files().joinpath(resource).open('rb')\n\n    def resource_path(self, resource):\n        raise FileNotFoundError(resource)\n\n    def is_resource(self, path):\n        return self.files().joinpath(path).is_file()\n\n    def contents(self):\n        return (item.name for item in self.files().iterdir())\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/importlib_resources/readers.py",
    "content": "import collections\nimport pathlib\nimport operator\n\nfrom . import abc\n\nfrom ._itertools import unique_everseen\nfrom ._compat import ZipPath\n\n\ndef remove_duplicates(items):\n    return iter(collections.OrderedDict.fromkeys(items))\n\n\nclass FileReader(abc.TraversableResources):\n    def __init__(self, loader):\n        self.path = pathlib.Path(loader.path).parent\n\n    def resource_path(self, resource):\n        \"\"\"\n        Return the file system path to prevent\n        `resources.path()` from creating a temporary\n        copy.\n        \"\"\"\n        return str(self.path.joinpath(resource))\n\n    def files(self):\n        return self.path\n\n\nclass ZipReader(abc.TraversableResources):\n    def __init__(self, loader, module):\n        _, _, name = module.rpartition('.')\n        self.prefix = loader.prefix.replace('\\\\', '/') + name + '/'\n        self.archive = loader.archive\n\n    def open_resource(self, resource):\n        try:\n            return super().open_resource(resource)\n        except KeyError as exc:\n            raise FileNotFoundError(exc.args[0])\n\n    def is_resource(self, path):\n        # workaround for `zipfile.Path.is_file` returning true\n        # for non-existent paths.\n        target = self.files().joinpath(path)\n        return target.is_file() and target.exists()\n\n    def files(self):\n        return ZipPath(self.archive, self.prefix)\n\n\nclass MultiplexedPath(abc.Traversable):\n    \"\"\"\n    Given a series of Traversable objects, implement a merged\n    version of the interface across all objects. Useful for\n    namespace packages which may be multihomed at a single\n    name.\n    \"\"\"\n\n    def __init__(self, *paths):\n        self._paths = list(map(pathlib.Path, remove_duplicates(paths)))\n        if not self._paths:\n            message = 'MultiplexedPath must contain at least one path'\n            raise FileNotFoundError(message)\n        if not all(path.is_dir() for path in self._paths):\n            raise NotADirectoryError('MultiplexedPath only supports directories')\n\n    def iterdir(self):\n        files = (file for path in self._paths for file in path.iterdir())\n        return unique_everseen(files, key=operator.attrgetter('name'))\n\n    def read_bytes(self):\n        raise FileNotFoundError(f'{self} is not a file')\n\n    def read_text(self, *args, **kwargs):\n        raise FileNotFoundError(f'{self} is not a file')\n\n    def is_dir(self):\n        return True\n\n    def is_file(self):\n        return False\n\n    def joinpath(self, child):\n        # first try to find child in current paths\n        for file in self.iterdir():\n            if file.name == child:\n                return file\n        # if it does not exist, construct it with the first path\n        return self._paths[0] / child\n\n    __truediv__ = joinpath\n\n    def open(self, *args, **kwargs):\n        raise FileNotFoundError(f'{self} is not a file')\n\n    @property\n    def name(self):\n        return self._paths[0].name\n\n    def __repr__(self):\n        paths = ', '.join(f\"'{path}'\" for path in self._paths)\n        return f'MultiplexedPath({paths})'\n\n\nclass NamespaceReader(abc.TraversableResources):\n    def __init__(self, namespace_path):\n        if 'NamespacePath' not in str(namespace_path):\n            raise ValueError('Invalid path')\n        self.path = MultiplexedPath(*list(namespace_path))\n\n    def resource_path(self, resource):\n        \"\"\"\n        Return the file system path to prevent\n        `resources.path()` from creating a temporary\n        copy.\n        \"\"\"\n        return str(self.path.joinpath(resource))\n\n    def files(self):\n        return self.path\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/importlib_resources/simple.py",
    "content": "\"\"\"\nInterface adapters for low-level readers.\n\"\"\"\n\nimport abc\nimport io\nimport itertools\nfrom typing import BinaryIO, List\n\nfrom .abc import Traversable, TraversableResources\n\n\nclass SimpleReader(abc.ABC):\n    \"\"\"\n    The minimum, low-level interface required from a resource\n    provider.\n    \"\"\"\n\n    @abc.abstractproperty\n    def package(self):\n        # type: () -> str\n        \"\"\"\n        The name of the package for which this reader loads resources.\n        \"\"\"\n\n    @abc.abstractmethod\n    def children(self):\n        # type: () -> List['SimpleReader']\n        \"\"\"\n        Obtain an iterable of SimpleReader for available\n        child containers (e.g. directories).\n        \"\"\"\n\n    @abc.abstractmethod\n    def resources(self):\n        # type: () -> List[str]\n        \"\"\"\n        Obtain available named resources for this virtual package.\n        \"\"\"\n\n    @abc.abstractmethod\n    def open_binary(self, resource):\n        # type: (str) -> BinaryIO\n        \"\"\"\n        Obtain a File-like for a named resource.\n        \"\"\"\n\n    @property\n    def name(self):\n        return self.package.split('.')[-1]\n\n\nclass ResourceHandle(Traversable):\n    \"\"\"\n    Handle to a named resource in a ResourceReader.\n    \"\"\"\n\n    def __init__(self, parent, name):\n        # type: (ResourceContainer, str) -> None\n        self.parent = parent\n        self.name = name  # type: ignore\n\n    def is_file(self):\n        return True\n\n    def is_dir(self):\n        return False\n\n    def open(self, mode='r', *args, **kwargs):\n        stream = self.parent.reader.open_binary(self.name)\n        if 'b' not in mode:\n            stream = io.TextIOWrapper(*args, **kwargs)\n        return stream\n\n    def joinpath(self, name):\n        raise RuntimeError(\"Cannot traverse into a resource\")\n\n\nclass ResourceContainer(Traversable):\n    \"\"\"\n    Traversable container for a package's resources via its reader.\n    \"\"\"\n\n    def __init__(self, reader):\n        # type: (SimpleReader) -> None\n        self.reader = reader\n\n    def is_dir(self):\n        return True\n\n    def is_file(self):\n        return False\n\n    def iterdir(self):\n        files = (ResourceHandle(self, name) for name in self.reader.resources)\n        dirs = map(ResourceContainer, self.reader.children())\n        return itertools.chain(files, dirs)\n\n    def open(self, *args, **kwargs):\n        raise IsADirectoryError()\n\n    def joinpath(self, name):\n        return next(\n            traversable for traversable in self.iterdir() if traversable.name == name\n        )\n\n\nclass TraversableReader(TraversableResources, SimpleReader):\n    \"\"\"\n    A TraversableResources based on SimpleReader. Resource providers\n    may derive from this class to provide the TraversableResources\n    interface by supplying the SimpleReader interface.\n    \"\"\"\n\n    def files(self):\n        return ResourceContainer(self)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/jaraco/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/jaraco/context.py",
    "content": "import os\nimport subprocess\nimport contextlib\nimport functools\nimport tempfile\nimport shutil\nimport operator\n\n\n@contextlib.contextmanager\ndef pushd(dir):\n    orig = os.getcwd()\n    os.chdir(dir)\n    try:\n        yield dir\n    finally:\n        os.chdir(orig)\n\n\n@contextlib.contextmanager\ndef tarball_context(url, target_dir=None, runner=None, pushd=pushd):\n    \"\"\"\n    Get a tarball, extract it, change to that directory, yield, then\n    clean up.\n    `runner` is the function to invoke commands.\n    `pushd` is a context manager for changing the directory.\n    \"\"\"\n    if target_dir is None:\n        target_dir = os.path.basename(url).replace('.tar.gz', '').replace('.tgz', '')\n    if runner is None:\n        runner = functools.partial(subprocess.check_call, shell=True)\n    # In the tar command, use --strip-components=1 to strip the first path and\n    #  then\n    #  use -C to cause the files to be extracted to {target_dir}. This ensures\n    #  that we always know where the files were extracted.\n    runner('mkdir {target_dir}'.format(**vars()))\n    try:\n        getter = 'wget {url} -O -'\n        extract = 'tar x{compression} --strip-components=1 -C {target_dir}'\n        cmd = ' | '.join((getter, extract))\n        runner(cmd.format(compression=infer_compression(url), **vars()))\n        with pushd(target_dir):\n            yield target_dir\n    finally:\n        runner('rm -Rf {target_dir}'.format(**vars()))\n\n\ndef infer_compression(url):\n    \"\"\"\n    Given a URL or filename, infer the compression code for tar.\n    \"\"\"\n    # cheat and just assume it's the last two characters\n    compression_indicator = url[-2:]\n    mapping = dict(gz='z', bz='j', xz='J')\n    # Assume 'z' (gzip) if no match\n    return mapping.get(compression_indicator, 'z')\n\n\n@contextlib.contextmanager\ndef temp_dir(remover=shutil.rmtree):\n    \"\"\"\n    Create a temporary directory context. Pass a custom remover\n    to override the removal behavior.\n    \"\"\"\n    temp_dir = tempfile.mkdtemp()\n    try:\n        yield temp_dir\n    finally:\n        remover(temp_dir)\n\n\n@contextlib.contextmanager\ndef repo_context(url, branch=None, quiet=True, dest_ctx=temp_dir):\n    \"\"\"\n    Check out the repo indicated by url.\n\n    If dest_ctx is supplied, it should be a context manager\n    to yield the target directory for the check out.\n    \"\"\"\n    exe = 'git' if 'git' in url else 'hg'\n    with dest_ctx() as repo_dir:\n        cmd = [exe, 'clone', url, repo_dir]\n        if branch:\n            cmd.extend(['--branch', branch])\n        devnull = open(os.path.devnull, 'w')\n        stdout = devnull if quiet else None\n        subprocess.check_call(cmd, stdout=stdout)\n        yield repo_dir\n\n\n@contextlib.contextmanager\ndef null():\n    yield\n\n\nclass ExceptionTrap:\n    \"\"\"\n    A context manager that will catch certain exceptions and provide an\n    indication they occurred.\n\n    >>> with ExceptionTrap() as trap:\n    ...     raise Exception()\n    >>> bool(trap)\n    True\n\n    >>> with ExceptionTrap() as trap:\n    ...     pass\n    >>> bool(trap)\n    False\n\n    >>> with ExceptionTrap(ValueError) as trap:\n    ...     raise ValueError(\"1 + 1 is not 3\")\n    >>> bool(trap)\n    True\n\n    >>> with ExceptionTrap(ValueError) as trap:\n    ...     raise Exception()\n    Traceback (most recent call last):\n    ...\n    Exception\n\n    >>> bool(trap)\n    False\n    \"\"\"\n\n    exc_info = None, None, None\n\n    def __init__(self, exceptions=(Exception,)):\n        self.exceptions = exceptions\n\n    def __enter__(self):\n        return self\n\n    @property\n    def type(self):\n        return self.exc_info[0]\n\n    @property\n    def value(self):\n        return self.exc_info[1]\n\n    @property\n    def tb(self):\n        return self.exc_info[2]\n\n    def __exit__(self, *exc_info):\n        type = exc_info[0]\n        matches = type and issubclass(type, self.exceptions)\n        if matches:\n            self.exc_info = exc_info\n        return matches\n\n    def __bool__(self):\n        return bool(self.type)\n\n    def raises(self, func, *, _test=bool):\n        \"\"\"\n        Wrap func and replace the result with the truth\n        value of the trap (True if an exception occurred).\n\n        First, give the decorator an alias to support Python 3.8\n        Syntax.\n\n        >>> raises = ExceptionTrap(ValueError).raises\n\n        Now decorate a function that always fails.\n\n        >>> @raises\n        ... def fail():\n        ...     raise ValueError('failed')\n        >>> fail()\n        True\n        \"\"\"\n\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            with ExceptionTrap(self.exceptions) as trap:\n                func(*args, **kwargs)\n            return _test(trap)\n\n        return wrapper\n\n    def passes(self, func):\n        \"\"\"\n        Wrap func and replace the result with the truth\n        value of the trap (True if no exception).\n\n        First, give the decorator an alias to support Python 3.8\n        Syntax.\n\n        >>> passes = ExceptionTrap(ValueError).passes\n\n        Now decorate a function that always fails.\n\n        >>> @passes\n        ... def fail():\n        ...     raise ValueError('failed')\n\n        >>> fail()\n        False\n        \"\"\"\n        return self.raises(func, _test=operator.not_)\n\n\nclass suppress(contextlib.suppress, contextlib.ContextDecorator):\n    \"\"\"\n    A version of contextlib.suppress with decorator support.\n\n    >>> @suppress(KeyError)\n    ... def key_error():\n    ...     {}['']\n    >>> key_error()\n    \"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/jaraco/functools.py",
    "content": "import functools\nimport time\nimport inspect\nimport collections\nimport types\nimport itertools\n\nimport pkg_resources.extern.more_itertools\n\nfrom typing import Callable, TypeVar\n\n\nCallableT = TypeVar(\"CallableT\", bound=Callable[..., object])\n\n\ndef compose(*funcs):\n    \"\"\"\n    Compose any number of unary functions into a single unary function.\n\n    >>> import textwrap\n    >>> expected = str.strip(textwrap.dedent(compose.__doc__))\n    >>> strip_and_dedent = compose(str.strip, textwrap.dedent)\n    >>> strip_and_dedent(compose.__doc__) == expected\n    True\n\n    Compose also allows the innermost function to take arbitrary arguments.\n\n    >>> round_three = lambda x: round(x, ndigits=3)\n    >>> f = compose(round_three, int.__truediv__)\n    >>> [f(3*x, x+1) for x in range(1,10)]\n    [1.5, 2.0, 2.25, 2.4, 2.5, 2.571, 2.625, 2.667, 2.7]\n    \"\"\"\n\n    def compose_two(f1, f2):\n        return lambda *args, **kwargs: f1(f2(*args, **kwargs))\n\n    return functools.reduce(compose_two, funcs)\n\n\ndef method_caller(method_name, *args, **kwargs):\n    \"\"\"\n    Return a function that will call a named method on the\n    target object with optional positional and keyword\n    arguments.\n\n    >>> lower = method_caller('lower')\n    >>> lower('MyString')\n    'mystring'\n    \"\"\"\n\n    def call_method(target):\n        func = getattr(target, method_name)\n        return func(*args, **kwargs)\n\n    return call_method\n\n\ndef once(func):\n    \"\"\"\n    Decorate func so it's only ever called the first time.\n\n    This decorator can ensure that an expensive or non-idempotent function\n    will not be expensive on subsequent calls and is idempotent.\n\n    >>> add_three = once(lambda a: a+3)\n    >>> add_three(3)\n    6\n    >>> add_three(9)\n    6\n    >>> add_three('12')\n    6\n\n    To reset the stored value, simply clear the property ``saved_result``.\n\n    >>> del add_three.saved_result\n    >>> add_three(9)\n    12\n    >>> add_three(8)\n    12\n\n    Or invoke 'reset()' on it.\n\n    >>> add_three.reset()\n    >>> add_three(-3)\n    0\n    >>> add_three(0)\n    0\n    \"\"\"\n\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        if not hasattr(wrapper, 'saved_result'):\n            wrapper.saved_result = func(*args, **kwargs)\n        return wrapper.saved_result\n\n    wrapper.reset = lambda: vars(wrapper).__delitem__('saved_result')\n    return wrapper\n\n\ndef method_cache(\n    method: CallableT,\n    cache_wrapper: Callable[\n        [CallableT], CallableT\n    ] = functools.lru_cache(),  # type: ignore[assignment]\n) -> CallableT:\n    \"\"\"\n    Wrap lru_cache to support storing the cache data in the object instances.\n\n    Abstracts the common paradigm where the method explicitly saves an\n    underscore-prefixed protected property on first call and returns that\n    subsequently.\n\n    >>> class MyClass:\n    ...     calls = 0\n    ...\n    ...     @method_cache\n    ...     def method(self, value):\n    ...         self.calls += 1\n    ...         return value\n\n    >>> a = MyClass()\n    >>> a.method(3)\n    3\n    >>> for x in range(75):\n    ...     res = a.method(x)\n    >>> a.calls\n    75\n\n    Note that the apparent behavior will be exactly like that of lru_cache\n    except that the cache is stored on each instance, so values in one\n    instance will not flush values from another, and when an instance is\n    deleted, so are the cached values for that instance.\n\n    >>> b = MyClass()\n    >>> for x in range(35):\n    ...     res = b.method(x)\n    >>> b.calls\n    35\n    >>> a.method(0)\n    0\n    >>> a.calls\n    75\n\n    Note that if method had been decorated with ``functools.lru_cache()``,\n    a.calls would have been 76 (due to the cached value of 0 having been\n    flushed by the 'b' instance).\n\n    Clear the cache with ``.cache_clear()``\n\n    >>> a.method.cache_clear()\n\n    Same for a method that hasn't yet been called.\n\n    >>> c = MyClass()\n    >>> c.method.cache_clear()\n\n    Another cache wrapper may be supplied:\n\n    >>> cache = functools.lru_cache(maxsize=2)\n    >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache)\n    >>> a = MyClass()\n    >>> a.method2()\n    3\n\n    Caution - do not subsequently wrap the method with another decorator, such\n    as ``@property``, which changes the semantics of the function.\n\n    See also\n    http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/\n    for another implementation and additional justification.\n    \"\"\"\n\n    def wrapper(self: object, *args: object, **kwargs: object) -> object:\n        # it's the first call, replace the method with a cached, bound method\n        bound_method: CallableT = types.MethodType(  # type: ignore[assignment]\n            method, self\n        )\n        cached_method = cache_wrapper(bound_method)\n        setattr(self, method.__name__, cached_method)\n        return cached_method(*args, **kwargs)\n\n    # Support cache clear even before cache has been created.\n    wrapper.cache_clear = lambda: None  # type: ignore[attr-defined]\n\n    return (  # type: ignore[return-value]\n        _special_method_cache(method, cache_wrapper) or wrapper\n    )\n\n\ndef _special_method_cache(method, cache_wrapper):\n    \"\"\"\n    Because Python treats special methods differently, it's not\n    possible to use instance attributes to implement the cached\n    methods.\n\n    Instead, install the wrapper method under a different name\n    and return a simple proxy to that wrapper.\n\n    https://github.com/jaraco/jaraco.functools/issues/5\n    \"\"\"\n    name = method.__name__\n    special_names = '__getattr__', '__getitem__'\n    if name not in special_names:\n        return\n\n    wrapper_name = '__cached' + name\n\n    def proxy(self, *args, **kwargs):\n        if wrapper_name not in vars(self):\n            bound = types.MethodType(method, self)\n            cache = cache_wrapper(bound)\n            setattr(self, wrapper_name, cache)\n        else:\n            cache = getattr(self, wrapper_name)\n        return cache(*args, **kwargs)\n\n    return proxy\n\n\ndef apply(transform):\n    \"\"\"\n    Decorate a function with a transform function that is\n    invoked on results returned from the decorated function.\n\n    >>> @apply(reversed)\n    ... def get_numbers(start):\n    ...     \"doc for get_numbers\"\n    ...     return range(start, start+3)\n    >>> list(get_numbers(4))\n    [6, 5, 4]\n    >>> get_numbers.__doc__\n    'doc for get_numbers'\n    \"\"\"\n\n    def wrap(func):\n        return functools.wraps(func)(compose(transform, func))\n\n    return wrap\n\n\ndef result_invoke(action):\n    r\"\"\"\n    Decorate a function with an action function that is\n    invoked on the results returned from the decorated\n    function (for its side-effect), then return the original\n    result.\n\n    >>> @result_invoke(print)\n    ... def add_two(a, b):\n    ...     return a + b\n    >>> x = add_two(2, 3)\n    5\n    >>> x\n    5\n    \"\"\"\n\n    def wrap(func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            result = func(*args, **kwargs)\n            action(result)\n            return result\n\n        return wrapper\n\n    return wrap\n\n\ndef call_aside(f, *args, **kwargs):\n    \"\"\"\n    Call a function for its side effect after initialization.\n\n    >>> @call_aside\n    ... def func(): print(\"called\")\n    called\n    >>> func()\n    called\n\n    Use functools.partial to pass parameters to the initial call\n\n    >>> @functools.partial(call_aside, name='bingo')\n    ... def func(name): print(\"called with\", name)\n    called with bingo\n    \"\"\"\n    f(*args, **kwargs)\n    return f\n\n\nclass Throttler:\n    \"\"\"\n    Rate-limit a function (or other callable)\n    \"\"\"\n\n    def __init__(self, func, max_rate=float('Inf')):\n        if isinstance(func, Throttler):\n            func = func.func\n        self.func = func\n        self.max_rate = max_rate\n        self.reset()\n\n    def reset(self):\n        self.last_called = 0\n\n    def __call__(self, *args, **kwargs):\n        self._wait()\n        return self.func(*args, **kwargs)\n\n    def _wait(self):\n        \"ensure at least 1/max_rate seconds from last call\"\n        elapsed = time.time() - self.last_called\n        must_wait = 1 / self.max_rate - elapsed\n        time.sleep(max(0, must_wait))\n        self.last_called = time.time()\n\n    def __get__(self, obj, type=None):\n        return first_invoke(self._wait, functools.partial(self.func, obj))\n\n\ndef first_invoke(func1, func2):\n    \"\"\"\n    Return a function that when invoked will invoke func1 without\n    any parameters (for its side-effect) and then invoke func2\n    with whatever parameters were passed, returning its result.\n    \"\"\"\n\n    def wrapper(*args, **kwargs):\n        func1()\n        return func2(*args, **kwargs)\n\n    return wrapper\n\n\ndef retry_call(func, cleanup=lambda: None, retries=0, trap=()):\n    \"\"\"\n    Given a callable func, trap the indicated exceptions\n    for up to 'retries' times, invoking cleanup on the\n    exception. On the final attempt, allow any exceptions\n    to propagate.\n    \"\"\"\n    attempts = itertools.count() if retries == float('inf') else range(retries)\n    for attempt in attempts:\n        try:\n            return func()\n        except trap:\n            cleanup()\n\n    return func()\n\n\ndef retry(*r_args, **r_kwargs):\n    \"\"\"\n    Decorator wrapper for retry_call. Accepts arguments to retry_call\n    except func and then returns a decorator for the decorated function.\n\n    Ex:\n\n    >>> @retry(retries=3)\n    ... def my_func(a, b):\n    ...     \"this is my funk\"\n    ...     print(a, b)\n    >>> my_func.__doc__\n    'this is my funk'\n    \"\"\"\n\n    def decorate(func):\n        @functools.wraps(func)\n        def wrapper(*f_args, **f_kwargs):\n            bound = functools.partial(func, *f_args, **f_kwargs)\n            return retry_call(bound, *r_args, **r_kwargs)\n\n        return wrapper\n\n    return decorate\n\n\ndef print_yielded(func):\n    \"\"\"\n    Convert a generator into a function that prints all yielded elements\n\n    >>> @print_yielded\n    ... def x():\n    ...     yield 3; yield None\n    >>> x()\n    3\n    None\n    \"\"\"\n    print_all = functools.partial(map, print)\n    print_results = compose(more_itertools.consume, print_all, func)\n    return functools.wraps(func)(print_results)\n\n\ndef pass_none(func):\n    \"\"\"\n    Wrap func so it's not called if its first param is None\n\n    >>> print_text = pass_none(print)\n    >>> print_text('text')\n    text\n    >>> print_text(None)\n    \"\"\"\n\n    @functools.wraps(func)\n    def wrapper(param, *args, **kwargs):\n        if param is not None:\n            return func(param, *args, **kwargs)\n\n    return wrapper\n\n\ndef assign_params(func, namespace):\n    \"\"\"\n    Assign parameters from namespace where func solicits.\n\n    >>> def func(x, y=3):\n    ...     print(x, y)\n    >>> assigned = assign_params(func, dict(x=2, z=4))\n    >>> assigned()\n    2 3\n\n    The usual errors are raised if a function doesn't receive\n    its required parameters:\n\n    >>> assigned = assign_params(func, dict(y=3, z=4))\n    >>> assigned()\n    Traceback (most recent call last):\n    TypeError: func() ...argument...\n\n    It even works on methods:\n\n    >>> class Handler:\n    ...     def meth(self, arg):\n    ...         print(arg)\n    >>> assign_params(Handler().meth, dict(arg='crystal', foo='clear'))()\n    crystal\n    \"\"\"\n    sig = inspect.signature(func)\n    params = sig.parameters.keys()\n    call_ns = {k: namespace[k] for k in params if k in namespace}\n    return functools.partial(func, **call_ns)\n\n\ndef save_method_args(method):\n    \"\"\"\n    Wrap a method such that when it is called, the args and kwargs are\n    saved on the method.\n\n    >>> class MyClass:\n    ...     @save_method_args\n    ...     def method(self, a, b):\n    ...         print(a, b)\n    >>> my_ob = MyClass()\n    >>> my_ob.method(1, 2)\n    1 2\n    >>> my_ob._saved_method.args\n    (1, 2)\n    >>> my_ob._saved_method.kwargs\n    {}\n    >>> my_ob.method(a=3, b='foo')\n    3 foo\n    >>> my_ob._saved_method.args\n    ()\n    >>> my_ob._saved_method.kwargs == dict(a=3, b='foo')\n    True\n\n    The arguments are stored on the instance, allowing for\n    different instance to save different args.\n\n    >>> your_ob = MyClass()\n    >>> your_ob.method({str('x'): 3}, b=[4])\n    {'x': 3} [4]\n    >>> your_ob._saved_method.args\n    ({'x': 3},)\n    >>> my_ob._saved_method.args\n    ()\n    \"\"\"\n    args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')\n\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        attr_name = '_saved_' + method.__name__\n        attr = args_and_kwargs(args, kwargs)\n        setattr(self, attr_name, attr)\n        return method(self, *args, **kwargs)\n\n    return wrapper\n\n\ndef except_(*exceptions, replace=None, use=None):\n    \"\"\"\n    Replace the indicated exceptions, if raised, with the indicated\n    literal replacement or evaluated expression (if present).\n\n    >>> safe_int = except_(ValueError)(int)\n    >>> safe_int('five')\n    >>> safe_int('5')\n    5\n\n    Specify a literal replacement with ``replace``.\n\n    >>> safe_int_r = except_(ValueError, replace=0)(int)\n    >>> safe_int_r('five')\n    0\n\n    Provide an expression to ``use`` to pass through particular parameters.\n\n    >>> safe_int_pt = except_(ValueError, use='args[0]')(int)\n    >>> safe_int_pt('five')\n    'five'\n\n    \"\"\"\n\n    def decorate(func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            try:\n                return func(*args, **kwargs)\n            except exceptions:\n                try:\n                    return eval(use)\n                except TypeError:\n                    return replace\n\n        return wrapper\n\n    return decorate\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/jaraco/text/__init__.py",
    "content": "import re\nimport itertools\nimport textwrap\nimport functools\n\ntry:\n    from importlib.resources import files  # type: ignore\nexcept ImportError:  # pragma: nocover\n    from pkg_resources.extern.importlib_resources import files  # type: ignore\n\nfrom pkg_resources.extern.jaraco.functools import compose, method_cache\nfrom pkg_resources.extern.jaraco.context import ExceptionTrap\n\n\ndef substitution(old, new):\n    \"\"\"\n    Return a function that will perform a substitution on a string\n    \"\"\"\n    return lambda s: s.replace(old, new)\n\n\ndef multi_substitution(*substitutions):\n    \"\"\"\n    Take a sequence of pairs specifying substitutions, and create\n    a function that performs those substitutions.\n\n    >>> multi_substitution(('foo', 'bar'), ('bar', 'baz'))('foo')\n    'baz'\n    \"\"\"\n    substitutions = itertools.starmap(substitution, substitutions)\n    # compose function applies last function first, so reverse the\n    #  substitutions to get the expected order.\n    substitutions = reversed(tuple(substitutions))\n    return compose(*substitutions)\n\n\nclass FoldedCase(str):\n    \"\"\"\n    A case insensitive string class; behaves just like str\n    except compares equal when the only variation is case.\n\n    >>> s = FoldedCase('hello world')\n\n    >>> s == 'Hello World'\n    True\n\n    >>> 'Hello World' == s\n    True\n\n    >>> s != 'Hello World'\n    False\n\n    >>> s.index('O')\n    4\n\n    >>> s.split('O')\n    ['hell', ' w', 'rld']\n\n    >>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta']))\n    ['alpha', 'Beta', 'GAMMA']\n\n    Sequence membership is straightforward.\n\n    >>> \"Hello World\" in [s]\n    True\n    >>> s in [\"Hello World\"]\n    True\n\n    You may test for set inclusion, but candidate and elements\n    must both be folded.\n\n    >>> FoldedCase(\"Hello World\") in {s}\n    True\n    >>> s in {FoldedCase(\"Hello World\")}\n    True\n\n    String inclusion works as long as the FoldedCase object\n    is on the right.\n\n    >>> \"hello\" in FoldedCase(\"Hello World\")\n    True\n\n    But not if the FoldedCase object is on the left:\n\n    >>> FoldedCase('hello') in 'Hello World'\n    False\n\n    In that case, use ``in_``:\n\n    >>> FoldedCase('hello').in_('Hello World')\n    True\n\n    >>> FoldedCase('hello') > FoldedCase('Hello')\n    False\n    \"\"\"\n\n    def __lt__(self, other):\n        return self.lower() < other.lower()\n\n    def __gt__(self, other):\n        return self.lower() > other.lower()\n\n    def __eq__(self, other):\n        return self.lower() == other.lower()\n\n    def __ne__(self, other):\n        return self.lower() != other.lower()\n\n    def __hash__(self):\n        return hash(self.lower())\n\n    def __contains__(self, other):\n        return super().lower().__contains__(other.lower())\n\n    def in_(self, other):\n        \"Does self appear in other?\"\n        return self in FoldedCase(other)\n\n    # cache lower since it's likely to be called frequently.\n    @method_cache\n    def lower(self):\n        return super().lower()\n\n    def index(self, sub):\n        return self.lower().index(sub.lower())\n\n    def split(self, splitter=' ', maxsplit=0):\n        pattern = re.compile(re.escape(splitter), re.I)\n        return pattern.split(self, maxsplit)\n\n\n# Python 3.8 compatibility\n_unicode_trap = ExceptionTrap(UnicodeDecodeError)\n\n\n@_unicode_trap.passes\ndef is_decodable(value):\n    r\"\"\"\n    Return True if the supplied value is decodable (using the default\n    encoding).\n\n    >>> is_decodable(b'\\xff')\n    False\n    >>> is_decodable(b'\\x32')\n    True\n    \"\"\"\n    value.decode()\n\n\ndef is_binary(value):\n    r\"\"\"\n    Return True if the value appears to be binary (that is, it's a byte\n    string and isn't decodable).\n\n    >>> is_binary(b'\\xff')\n    True\n    >>> is_binary('\\xff')\n    False\n    \"\"\"\n    return isinstance(value, bytes) and not is_decodable(value)\n\n\ndef trim(s):\n    r\"\"\"\n    Trim something like a docstring to remove the whitespace that\n    is common due to indentation and formatting.\n\n    >>> trim(\"\\n\\tfoo = bar\\n\\t\\tbar = baz\\n\")\n    'foo = bar\\n\\tbar = baz'\n    \"\"\"\n    return textwrap.dedent(s).strip()\n\n\ndef wrap(s):\n    \"\"\"\n    Wrap lines of text, retaining existing newlines as\n    paragraph markers.\n\n    >>> print(wrap(lorem_ipsum))\n    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do\n    eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad\n    minim veniam, quis nostrud exercitation ullamco laboris nisi ut\n    aliquip ex ea commodo consequat. Duis aute irure dolor in\n    reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla\n    pariatur. Excepteur sint occaecat cupidatat non proident, sunt in\n    culpa qui officia deserunt mollit anim id est laborum.\n    <BLANKLINE>\n    Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam\n    varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus\n    magna felis sollicitudin mauris. Integer in mauris eu nibh euismod\n    gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis\n    risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue,\n    eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas\n    fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla\n    a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis,\n    neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing\n    sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque\n    nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus\n    quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis,\n    molestie eu, feugiat in, orci. In hac habitasse platea dictumst.\n    \"\"\"\n    paragraphs = s.splitlines()\n    wrapped = ('\\n'.join(textwrap.wrap(para)) for para in paragraphs)\n    return '\\n\\n'.join(wrapped)\n\n\ndef unwrap(s):\n    r\"\"\"\n    Given a multi-line string, return an unwrapped version.\n\n    >>> wrapped = wrap(lorem_ipsum)\n    >>> wrapped.count('\\n')\n    20\n    >>> unwrapped = unwrap(wrapped)\n    >>> unwrapped.count('\\n')\n    1\n    >>> print(unwrapped)\n    Lorem ipsum dolor sit amet, consectetur adipiscing ...\n    Curabitur pretium tincidunt lacus. Nulla gravida orci ...\n\n    \"\"\"\n    paragraphs = re.split(r'\\n\\n+', s)\n    cleaned = (para.replace('\\n', ' ') for para in paragraphs)\n    return '\\n'.join(cleaned)\n\n\n\n\nclass Splitter(object):\n    \"\"\"object that will split a string with the given arguments for each call\n\n    >>> s = Splitter(',')\n    >>> s('hello, world, this is your, master calling')\n    ['hello', ' world', ' this is your', ' master calling']\n    \"\"\"\n\n    def __init__(self, *args):\n        self.args = args\n\n    def __call__(self, s):\n        return s.split(*self.args)\n\n\ndef indent(string, prefix=' ' * 4):\n    \"\"\"\n    >>> indent('foo')\n    '    foo'\n    \"\"\"\n    return prefix + string\n\n\nclass WordSet(tuple):\n    \"\"\"\n    Given an identifier, return the words that identifier represents,\n    whether in camel case, underscore-separated, etc.\n\n    >>> WordSet.parse(\"camelCase\")\n    ('camel', 'Case')\n\n    >>> WordSet.parse(\"under_sep\")\n    ('under', 'sep')\n\n    Acronyms should be retained\n\n    >>> WordSet.parse(\"firstSNL\")\n    ('first', 'SNL')\n\n    >>> WordSet.parse(\"you_and_I\")\n    ('you', 'and', 'I')\n\n    >>> WordSet.parse(\"A simple test\")\n    ('A', 'simple', 'test')\n\n    Multiple caps should not interfere with the first cap of another word.\n\n    >>> WordSet.parse(\"myABCClass\")\n    ('my', 'ABC', 'Class')\n\n    The result is a WordSet, so you can get the form you need.\n\n    >>> WordSet.parse(\"myABCClass\").underscore_separated()\n    'my_ABC_Class'\n\n    >>> WordSet.parse('a-command').camel_case()\n    'ACommand'\n\n    >>> WordSet.parse('someIdentifier').lowered().space_separated()\n    'some identifier'\n\n    Slices of the result should return another WordSet.\n\n    >>> WordSet.parse('taken-out-of-context')[1:].underscore_separated()\n    'out_of_context'\n\n    >>> WordSet.from_class_name(WordSet()).lowered().space_separated()\n    'word set'\n\n    >>> example = WordSet.parse('figured it out')\n    >>> example.headless_camel_case()\n    'figuredItOut'\n    >>> example.dash_separated()\n    'figured-it-out'\n\n    \"\"\"\n\n    _pattern = re.compile('([A-Z]?[a-z]+)|([A-Z]+(?![a-z]))')\n\n    def capitalized(self):\n        return WordSet(word.capitalize() for word in self)\n\n    def lowered(self):\n        return WordSet(word.lower() for word in self)\n\n    def camel_case(self):\n        return ''.join(self.capitalized())\n\n    def headless_camel_case(self):\n        words = iter(self)\n        first = next(words).lower()\n        new_words = itertools.chain((first,), WordSet(words).camel_case())\n        return ''.join(new_words)\n\n    def underscore_separated(self):\n        return '_'.join(self)\n\n    def dash_separated(self):\n        return '-'.join(self)\n\n    def space_separated(self):\n        return ' '.join(self)\n\n    def trim_right(self, item):\n        \"\"\"\n        Remove the item from the end of the set.\n\n        >>> WordSet.parse('foo bar').trim_right('foo')\n        ('foo', 'bar')\n        >>> WordSet.parse('foo bar').trim_right('bar')\n        ('foo',)\n        >>> WordSet.parse('').trim_right('bar')\n        ()\n        \"\"\"\n        return self[:-1] if self and self[-1] == item else self\n\n    def trim_left(self, item):\n        \"\"\"\n        Remove the item from the beginning of the set.\n\n        >>> WordSet.parse('foo bar').trim_left('foo')\n        ('bar',)\n        >>> WordSet.parse('foo bar').trim_left('bar')\n        ('foo', 'bar')\n        >>> WordSet.parse('').trim_left('bar')\n        ()\n        \"\"\"\n        return self[1:] if self and self[0] == item else self\n\n    def trim(self, item):\n        \"\"\"\n        >>> WordSet.parse('foo bar').trim('foo')\n        ('bar',)\n        \"\"\"\n        return self.trim_left(item).trim_right(item)\n\n    def __getitem__(self, item):\n        result = super(WordSet, self).__getitem__(item)\n        if isinstance(item, slice):\n            result = WordSet(result)\n        return result\n\n    @classmethod\n    def parse(cls, identifier):\n        matches = cls._pattern.finditer(identifier)\n        return WordSet(match.group(0) for match in matches)\n\n    @classmethod\n    def from_class_name(cls, subject):\n        return cls.parse(subject.__class__.__name__)\n\n\n# for backward compatibility\nwords = WordSet.parse\n\n\ndef simple_html_strip(s):\n    r\"\"\"\n    Remove HTML from the string `s`.\n\n    >>> str(simple_html_strip(''))\n    ''\n\n    >>> print(simple_html_strip('A <bold>stormy</bold> day in paradise'))\n    A stormy day in paradise\n\n    >>> print(simple_html_strip('Somebody <!-- do not --> tell the truth.'))\n    Somebody  tell the truth.\n\n    >>> print(simple_html_strip('What about<br/>\\nmultiple lines?'))\n    What about\n    multiple lines?\n    \"\"\"\n    html_stripper = re.compile('(<!--.*?-->)|(<[^>]*>)|([^<]+)', re.DOTALL)\n    texts = (match.group(3) or '' for match in html_stripper.finditer(s))\n    return ''.join(texts)\n\n\nclass SeparatedValues(str):\n    \"\"\"\n    A string separated by a separator. Overrides __iter__ for getting\n    the values.\n\n    >>> list(SeparatedValues('a,b,c'))\n    ['a', 'b', 'c']\n\n    Whitespace is stripped and empty values are discarded.\n\n    >>> list(SeparatedValues(' a,   b   , c,  '))\n    ['a', 'b', 'c']\n    \"\"\"\n\n    separator = ','\n\n    def __iter__(self):\n        parts = self.split(self.separator)\n        return filter(None, (part.strip() for part in parts))\n\n\nclass Stripper:\n    r\"\"\"\n    Given a series of lines, find the common prefix and strip it from them.\n\n    >>> lines = [\n    ...     'abcdefg\\n',\n    ...     'abc\\n',\n    ...     'abcde\\n',\n    ... ]\n    >>> res = Stripper.strip_prefix(lines)\n    >>> res.prefix\n    'abc'\n    >>> list(res.lines)\n    ['defg\\n', '\\n', 'de\\n']\n\n    If no prefix is common, nothing should be stripped.\n\n    >>> lines = [\n    ...     'abcd\\n',\n    ...     '1234\\n',\n    ... ]\n    >>> res = Stripper.strip_prefix(lines)\n    >>> res.prefix = ''\n    >>> list(res.lines)\n    ['abcd\\n', '1234\\n']\n    \"\"\"\n\n    def __init__(self, prefix, lines):\n        self.prefix = prefix\n        self.lines = map(self, lines)\n\n    @classmethod\n    def strip_prefix(cls, lines):\n        prefix_lines, lines = itertools.tee(lines)\n        prefix = functools.reduce(cls.common_prefix, prefix_lines)\n        return cls(prefix, lines)\n\n    def __call__(self, line):\n        if not self.prefix:\n            return line\n        null, prefix, rest = line.partition(self.prefix)\n        return rest\n\n    @staticmethod\n    def common_prefix(s1, s2):\n        \"\"\"\n        Return the common prefix of two lines.\n        \"\"\"\n        index = min(len(s1), len(s2))\n        while s1[:index] != s2[:index]:\n            index -= 1\n        return s1[:index]\n\n\ndef remove_prefix(text, prefix):\n    \"\"\"\n    Remove the prefix from the text if it exists.\n\n    >>> remove_prefix('underwhelming performance', 'underwhelming ')\n    'performance'\n\n    >>> remove_prefix('something special', 'sample')\n    'something special'\n    \"\"\"\n    null, prefix, rest = text.rpartition(prefix)\n    return rest\n\n\ndef remove_suffix(text, suffix):\n    \"\"\"\n    Remove the suffix from the text if it exists.\n\n    >>> remove_suffix('name.git', '.git')\n    'name'\n\n    >>> remove_suffix('something special', 'sample')\n    'something special'\n    \"\"\"\n    rest, suffix, null = text.partition(suffix)\n    return rest\n\n\ndef normalize_newlines(text):\n    r\"\"\"\n    Replace alternate newlines with the canonical newline.\n\n    >>> normalize_newlines('Lorem Ipsum\\u2029')\n    'Lorem Ipsum\\n'\n    >>> normalize_newlines('Lorem Ipsum\\r\\n')\n    'Lorem Ipsum\\n'\n    >>> normalize_newlines('Lorem Ipsum\\x85')\n    'Lorem Ipsum\\n'\n    \"\"\"\n    newlines = ['\\r\\n', '\\r', '\\n', '\\u0085', '\\u2028', '\\u2029']\n    pattern = '|'.join(newlines)\n    return re.sub(pattern, '\\n', text)\n\n\ndef _nonblank(str):\n    return str and not str.startswith('#')\n\n\n@functools.singledispatch\ndef yield_lines(iterable):\n    r\"\"\"\n    Yield valid lines of a string or iterable.\n\n    >>> list(yield_lines(''))\n    []\n    >>> list(yield_lines(['foo', 'bar']))\n    ['foo', 'bar']\n    >>> list(yield_lines('foo\\nbar'))\n    ['foo', 'bar']\n    >>> list(yield_lines('\\nfoo\\n#bar\\nbaz #comment'))\n    ['foo', 'baz #comment']\n    >>> list(yield_lines(['foo\\nbar', 'baz', 'bing\\n\\n\\n']))\n    ['foo', 'bar', 'baz', 'bing']\n    \"\"\"\n    return itertools.chain.from_iterable(map(yield_lines, iterable))\n\n\n@yield_lines.register(str)\ndef _(text):\n    return filter(_nonblank, map(str.strip, text.splitlines()))\n\n\ndef drop_comment(line):\n    \"\"\"\n    Drop comments.\n\n    >>> drop_comment('foo # bar')\n    'foo'\n\n    A hash without a space may be in a URL.\n\n    >>> drop_comment('http://example.com/foo#bar')\n    'http://example.com/foo#bar'\n    \"\"\"\n    return line.partition(' #')[0]\n\n\ndef join_continuation(lines):\n    r\"\"\"\n    Join lines continued by a trailing backslash.\n\n    >>> list(join_continuation(['foo \\\\', 'bar', 'baz']))\n    ['foobar', 'baz']\n    >>> list(join_continuation(['foo \\\\', 'bar', 'baz']))\n    ['foobar', 'baz']\n    >>> list(join_continuation(['foo \\\\', 'bar \\\\', 'baz']))\n    ['foobarbaz']\n\n    Not sure why, but...\n    The character preceeding the backslash is also elided.\n\n    >>> list(join_continuation(['goo\\\\', 'dly']))\n    ['godly']\n\n    A terrible idea, but...\n    If no line is available to continue, suppress the lines.\n\n    >>> list(join_continuation(['foo', 'bar\\\\', 'baz\\\\']))\n    ['foo']\n    \"\"\"\n    lines = iter(lines)\n    for item in lines:\n        while item.endswith('\\\\'):\n            try:\n                item = item[:-2].strip() + next(lines)\n            except StopIteration:\n                return\n        yield item\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/more_itertools/__init__.py",
    "content": "from .more import *  # noqa\nfrom .recipes import *  # noqa\n\n__version__ = '8.12.0'\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/more_itertools/more.py",
    "content": "import warnings\n\nfrom collections import Counter, defaultdict, deque, abc\nfrom collections.abc import Sequence\nfrom functools import partial, reduce, wraps\nfrom heapq import merge, heapify, heapreplace, heappop\nfrom itertools import (\n    chain,\n    compress,\n    count,\n    cycle,\n    dropwhile,\n    groupby,\n    islice,\n    repeat,\n    starmap,\n    takewhile,\n    tee,\n    zip_longest,\n)\nfrom math import exp, factorial, floor, log\nfrom queue import Empty, Queue\nfrom random import random, randrange, uniform\nfrom operator import itemgetter, mul, sub, gt, lt, ge, le\nfrom sys import hexversion, maxsize\nfrom time import monotonic\n\nfrom .recipes import (\n    consume,\n    flatten,\n    pairwise,\n    powerset,\n    take,\n    unique_everseen,\n)\n\n__all__ = [\n    'AbortThread',\n    'SequenceView',\n    'UnequalIterablesError',\n    'adjacent',\n    'all_unique',\n    'always_iterable',\n    'always_reversible',\n    'bucket',\n    'callback_iter',\n    'chunked',\n    'chunked_even',\n    'circular_shifts',\n    'collapse',\n    'collate',\n    'combination_index',\n    'consecutive_groups',\n    'consumer',\n    'count_cycle',\n    'countable',\n    'difference',\n    'distinct_combinations',\n    'distinct_permutations',\n    'distribute',\n    'divide',\n    'duplicates_everseen',\n    'duplicates_justseen',\n    'exactly_n',\n    'filter_except',\n    'first',\n    'groupby_transform',\n    'ichunked',\n    'ilen',\n    'interleave',\n    'interleave_evenly',\n    'interleave_longest',\n    'intersperse',\n    'is_sorted',\n    'islice_extended',\n    'iterate',\n    'last',\n    'locate',\n    'lstrip',\n    'make_decorator',\n    'map_except',\n    'map_if',\n    'map_reduce',\n    'mark_ends',\n    'minmax',\n    'nth_or_last',\n    'nth_permutation',\n    'nth_product',\n    'numeric_range',\n    'one',\n    'only',\n    'padded',\n    'partitions',\n    'peekable',\n    'permutation_index',\n    'product_index',\n    'raise_',\n    'repeat_each',\n    'repeat_last',\n    'replace',\n    'rlocate',\n    'rstrip',\n    'run_length',\n    'sample',\n    'seekable',\n    'set_partitions',\n    'side_effect',\n    'sliced',\n    'sort_together',\n    'split_after',\n    'split_at',\n    'split_before',\n    'split_into',\n    'split_when',\n    'spy',\n    'stagger',\n    'strip',\n    'strictly_n',\n    'substrings',\n    'substrings_indexes',\n    'time_limited',\n    'unique_in_window',\n    'unique_to_each',\n    'unzip',\n    'value_chain',\n    'windowed',\n    'windowed_complete',\n    'with_iter',\n    'zip_broadcast',\n    'zip_equal',\n    'zip_offset',\n]\n\n\n_marker = object()\n\n\ndef chunked(iterable, n, strict=False):\n    \"\"\"Break *iterable* into lists of length *n*:\n\n        >>> list(chunked([1, 2, 3, 4, 5, 6], 3))\n        [[1, 2, 3], [4, 5, 6]]\n\n    By the default, the last yielded list will have fewer than *n* elements\n    if the length of *iterable* is not divisible by *n*:\n\n        >>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3))\n        [[1, 2, 3], [4, 5, 6], [7, 8]]\n\n    To use a fill-in value instead, see the :func:`grouper` recipe.\n\n    If the length of *iterable* is not divisible by *n* and *strict* is\n    ``True``, then ``ValueError`` will be raised before the last\n    list is yielded.\n\n    \"\"\"\n    iterator = iter(partial(take, n, iter(iterable)), [])\n    if strict:\n        if n is None:\n            raise ValueError('n must not be None when using strict mode.')\n\n        def ret():\n            for chunk in iterator:\n                if len(chunk) != n:\n                    raise ValueError('iterable is not divisible by n.')\n                yield chunk\n\n        return iter(ret())\n    else:\n        return iterator\n\n\ndef first(iterable, default=_marker):\n    \"\"\"Return the first item of *iterable*, or *default* if *iterable* is\n    empty.\n\n        >>> first([0, 1, 2, 3])\n        0\n        >>> first([], 'some default')\n        'some default'\n\n    If *default* is not provided and there are no items in the iterable,\n    raise ``ValueError``.\n\n    :func:`first` is useful when you have a generator of expensive-to-retrieve\n    values and want any arbitrary one. It is marginally shorter than\n    ``next(iter(iterable), default)``.\n\n    \"\"\"\n    try:\n        return next(iter(iterable))\n    except StopIteration as e:\n        if default is _marker:\n            raise ValueError(\n                'first() was called on an empty iterable, and no '\n                'default value was provided.'\n            ) from e\n        return default\n\n\ndef last(iterable, default=_marker):\n    \"\"\"Return the last item of *iterable*, or *default* if *iterable* is\n    empty.\n\n        >>> last([0, 1, 2, 3])\n        3\n        >>> last([], 'some default')\n        'some default'\n\n    If *default* is not provided and there are no items in the iterable,\n    raise ``ValueError``.\n    \"\"\"\n    try:\n        if isinstance(iterable, Sequence):\n            return iterable[-1]\n        # Work around https://bugs.python.org/issue38525\n        elif hasattr(iterable, '__reversed__') and (hexversion != 0x030800F0):\n            return next(reversed(iterable))\n        else:\n            return deque(iterable, maxlen=1)[-1]\n    except (IndexError, TypeError, StopIteration):\n        if default is _marker:\n            raise ValueError(\n                'last() was called on an empty iterable, and no default was '\n                'provided.'\n            )\n        return default\n\n\ndef nth_or_last(iterable, n, default=_marker):\n    \"\"\"Return the nth or the last item of *iterable*,\n    or *default* if *iterable* is empty.\n\n        >>> nth_or_last([0, 1, 2, 3], 2)\n        2\n        >>> nth_or_last([0, 1], 2)\n        1\n        >>> nth_or_last([], 0, 'some default')\n        'some default'\n\n    If *default* is not provided and there are no items in the iterable,\n    raise ``ValueError``.\n    \"\"\"\n    return last(islice(iterable, n + 1), default=default)\n\n\nclass peekable:\n    \"\"\"Wrap an iterator to allow lookahead and prepending elements.\n\n    Call :meth:`peek` on the result to get the value that will be returned\n    by :func:`next`. This won't advance the iterator:\n\n        >>> p = peekable(['a', 'b'])\n        >>> p.peek()\n        'a'\n        >>> next(p)\n        'a'\n\n    Pass :meth:`peek` a default value to return that instead of raising\n    ``StopIteration`` when the iterator is exhausted.\n\n        >>> p = peekable([])\n        >>> p.peek('hi')\n        'hi'\n\n    peekables also offer a :meth:`prepend` method, which \"inserts\" items\n    at the head of the iterable:\n\n        >>> p = peekable([1, 2, 3])\n        >>> p.prepend(10, 11, 12)\n        >>> next(p)\n        10\n        >>> p.peek()\n        11\n        >>> list(p)\n        [11, 12, 1, 2, 3]\n\n    peekables can be indexed. Index 0 is the item that will be returned by\n    :func:`next`, index 1 is the item after that, and so on:\n    The values up to the given index will be cached.\n\n        >>> p = peekable(['a', 'b', 'c', 'd'])\n        >>> p[0]\n        'a'\n        >>> p[1]\n        'b'\n        >>> next(p)\n        'a'\n\n    Negative indexes are supported, but be aware that they will cache the\n    remaining items in the source iterator, which may require significant\n    storage.\n\n    To check whether a peekable is exhausted, check its truth value:\n\n        >>> p = peekable(['a', 'b'])\n        >>> if p:  # peekable has items\n        ...     list(p)\n        ['a', 'b']\n        >>> if not p:  # peekable is exhausted\n        ...     list(p)\n        []\n\n    \"\"\"\n\n    def __init__(self, iterable):\n        self._it = iter(iterable)\n        self._cache = deque()\n\n    def __iter__(self):\n        return self\n\n    def __bool__(self):\n        try:\n            self.peek()\n        except StopIteration:\n            return False\n        return True\n\n    def peek(self, default=_marker):\n        \"\"\"Return the item that will be next returned from ``next()``.\n\n        Return ``default`` if there are no items left. If ``default`` is not\n        provided, raise ``StopIteration``.\n\n        \"\"\"\n        if not self._cache:\n            try:\n                self._cache.append(next(self._it))\n            except StopIteration:\n                if default is _marker:\n                    raise\n                return default\n        return self._cache[0]\n\n    def prepend(self, *items):\n        \"\"\"Stack up items to be the next ones returned from ``next()`` or\n        ``self.peek()``. The items will be returned in\n        first in, first out order::\n\n            >>> p = peekable([1, 2, 3])\n            >>> p.prepend(10, 11, 12)\n            >>> next(p)\n            10\n            >>> list(p)\n            [11, 12, 1, 2, 3]\n\n        It is possible, by prepending items, to \"resurrect\" a peekable that\n        previously raised ``StopIteration``.\n\n            >>> p = peekable([])\n            >>> next(p)\n            Traceback (most recent call last):\n              ...\n            StopIteration\n            >>> p.prepend(1)\n            >>> next(p)\n            1\n            >>> next(p)\n            Traceback (most recent call last):\n              ...\n            StopIteration\n\n        \"\"\"\n        self._cache.extendleft(reversed(items))\n\n    def __next__(self):\n        if self._cache:\n            return self._cache.popleft()\n\n        return next(self._it)\n\n    def _get_slice(self, index):\n        # Normalize the slice's arguments\n        step = 1 if (index.step is None) else index.step\n        if step > 0:\n            start = 0 if (index.start is None) else index.start\n            stop = maxsize if (index.stop is None) else index.stop\n        elif step < 0:\n            start = -1 if (index.start is None) else index.start\n            stop = (-maxsize - 1) if (index.stop is None) else index.stop\n        else:\n            raise ValueError('slice step cannot be zero')\n\n        # If either the start or stop index is negative, we'll need to cache\n        # the rest of the iterable in order to slice from the right side.\n        if (start < 0) or (stop < 0):\n            self._cache.extend(self._it)\n        # Otherwise we'll need to find the rightmost index and cache to that\n        # point.\n        else:\n            n = min(max(start, stop) + 1, maxsize)\n            cache_len = len(self._cache)\n            if n >= cache_len:\n                self._cache.extend(islice(self._it, n - cache_len))\n\n        return list(self._cache)[index]\n\n    def __getitem__(self, index):\n        if isinstance(index, slice):\n            return self._get_slice(index)\n\n        cache_len = len(self._cache)\n        if index < 0:\n            self._cache.extend(self._it)\n        elif index >= cache_len:\n            self._cache.extend(islice(self._it, index + 1 - cache_len))\n\n        return self._cache[index]\n\n\ndef collate(*iterables, **kwargs):\n    \"\"\"Return a sorted merge of the items from each of several already-sorted\n    *iterables*.\n\n        >>> list(collate('ACDZ', 'AZ', 'JKL'))\n        ['A', 'A', 'C', 'D', 'J', 'K', 'L', 'Z', 'Z']\n\n    Works lazily, keeping only the next value from each iterable in memory. Use\n    :func:`collate` to, for example, perform a n-way mergesort of items that\n    don't fit in memory.\n\n    If a *key* function is specified, the iterables will be sorted according\n    to its result:\n\n        >>> key = lambda s: int(s)  # Sort by numeric value, not by string\n        >>> list(collate(['1', '10'], ['2', '11'], key=key))\n        ['1', '2', '10', '11']\n\n\n    If the *iterables* are sorted in descending order, set *reverse* to\n    ``True``:\n\n        >>> list(collate([5, 3, 1], [4, 2, 0], reverse=True))\n        [5, 4, 3, 2, 1, 0]\n\n    If the elements of the passed-in iterables are out of order, you might get\n    unexpected results.\n\n    On Python 3.5+, this function is an alias for :func:`heapq.merge`.\n\n    \"\"\"\n    warnings.warn(\n        \"collate is no longer part of more_itertools, use heapq.merge\",\n        DeprecationWarning,\n    )\n    return merge(*iterables, **kwargs)\n\n\ndef consumer(func):\n    \"\"\"Decorator that automatically advances a PEP-342-style \"reverse iterator\"\n    to its first yield point so you don't have to call ``next()`` on it\n    manually.\n\n        >>> @consumer\n        ... def tally():\n        ...     i = 0\n        ...     while True:\n        ...         print('Thing number %s is %s.' % (i, (yield)))\n        ...         i += 1\n        ...\n        >>> t = tally()\n        >>> t.send('red')\n        Thing number 0 is red.\n        >>> t.send('fish')\n        Thing number 1 is fish.\n\n    Without the decorator, you would have to call ``next(t)`` before\n    ``t.send()`` could be used.\n\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        gen = func(*args, **kwargs)\n        next(gen)\n        return gen\n\n    return wrapper\n\n\ndef ilen(iterable):\n    \"\"\"Return the number of items in *iterable*.\n\n        >>> ilen(x for x in range(1000000) if x % 3 == 0)\n        333334\n\n    This consumes the iterable, so handle with care.\n\n    \"\"\"\n    # This approach was selected because benchmarks showed it's likely the\n    # fastest of the known implementations at the time of writing.\n    # See GitHub tracker: #236, #230.\n    counter = count()\n    deque(zip(iterable, counter), maxlen=0)\n    return next(counter)\n\n\ndef iterate(func, start):\n    \"\"\"Return ``start``, ``func(start)``, ``func(func(start))``, ...\n\n    >>> from itertools import islice\n    >>> list(islice(iterate(lambda x: 2*x, 1), 10))\n    [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]\n\n    \"\"\"\n    while True:\n        yield start\n        start = func(start)\n\n\ndef with_iter(context_manager):\n    \"\"\"Wrap an iterable in a ``with`` statement, so it closes once exhausted.\n\n    For example, this will close the file when the iterator is exhausted::\n\n        upper_lines = (line.upper() for line in with_iter(open('foo')))\n\n    Any context manager which returns an iterable is a candidate for\n    ``with_iter``.\n\n    \"\"\"\n    with context_manager as iterable:\n        yield from iterable\n\n\ndef one(iterable, too_short=None, too_long=None):\n    \"\"\"Return the first item from *iterable*, which is expected to contain only\n    that item. Raise an exception if *iterable* is empty or has more than one\n    item.\n\n    :func:`one` is useful for ensuring that an iterable contains only one item.\n    For example, it can be used to retrieve the result of a database query\n    that is expected to return a single row.\n\n    If *iterable* is empty, ``ValueError`` will be raised. You may specify a\n    different exception with the *too_short* keyword:\n\n        >>> it = []\n        >>> one(it)  # doctest: +IGNORE_EXCEPTION_DETAIL\n        Traceback (most recent call last):\n        ...\n        ValueError: too many items in iterable (expected 1)'\n        >>> too_short = IndexError('too few items')\n        >>> one(it, too_short=too_short)  # doctest: +IGNORE_EXCEPTION_DETAIL\n        Traceback (most recent call last):\n        ...\n        IndexError: too few items\n\n    Similarly, if *iterable* contains more than one item, ``ValueError`` will\n    be raised. You may specify a different exception with the *too_long*\n    keyword:\n\n        >>> it = ['too', 'many']\n        >>> one(it)  # doctest: +IGNORE_EXCEPTION_DETAIL\n        Traceback (most recent call last):\n        ...\n        ValueError: Expected exactly one item in iterable, but got 'too',\n        'many', and perhaps more.\n        >>> too_long = RuntimeError\n        >>> one(it, too_long=too_long)  # doctest: +IGNORE_EXCEPTION_DETAIL\n        Traceback (most recent call last):\n        ...\n        RuntimeError\n\n    Note that :func:`one` attempts to advance *iterable* twice to ensure there\n    is only one item. See :func:`spy` or :func:`peekable` to check iterable\n    contents less destructively.\n\n    \"\"\"\n    it = iter(iterable)\n\n    try:\n        first_value = next(it)\n    except StopIteration as e:\n        raise (\n            too_short or ValueError('too few items in iterable (expected 1)')\n        ) from e\n\n    try:\n        second_value = next(it)\n    except StopIteration:\n        pass\n    else:\n        msg = (\n            'Expected exactly one item in iterable, but got {!r}, {!r}, '\n            'and perhaps more.'.format(first_value, second_value)\n        )\n        raise too_long or ValueError(msg)\n\n    return first_value\n\n\ndef raise_(exception, *args):\n    raise exception(*args)\n\n\ndef strictly_n(iterable, n, too_short=None, too_long=None):\n    \"\"\"Validate that *iterable* has exactly *n* items and return them if\n    it does. If it has fewer than *n* items, call function *too_short*\n    with those items. If it has more than *n* items, call function\n    *too_long* with the first ``n + 1`` items.\n\n        >>> iterable = ['a', 'b', 'c', 'd']\n        >>> n = 4\n        >>> list(strictly_n(iterable, n))\n        ['a', 'b', 'c', 'd']\n\n    By default, *too_short* and *too_long* are functions that raise\n    ``ValueError``.\n\n        >>> list(strictly_n('ab', 3))  # doctest: +IGNORE_EXCEPTION_DETAIL\n        Traceback (most recent call last):\n        ...\n        ValueError: too few items in iterable (got 2)\n\n        >>> list(strictly_n('abc', 2))  # doctest: +IGNORE_EXCEPTION_DETAIL\n        Traceback (most recent call last):\n        ...\n        ValueError: too many items in iterable (got at least 3)\n\n    You can instead supply functions that do something else.\n    *too_short* will be called with the number of items in *iterable*.\n    *too_long* will be called with `n + 1`.\n\n        >>> def too_short(item_count):\n        ...     raise RuntimeError\n        >>> it = strictly_n('abcd', 6, too_short=too_short)\n        >>> list(it)  # doctest: +IGNORE_EXCEPTION_DETAIL\n        Traceback (most recent call last):\n        ...\n        RuntimeError\n\n        >>> def too_long(item_count):\n        ...     print('The boss is going to hear about this')\n        >>> it = strictly_n('abcdef', 4, too_long=too_long)\n        >>> list(it)\n        The boss is going to hear about this\n        ['a', 'b', 'c', 'd']\n\n    \"\"\"\n    if too_short is None:\n        too_short = lambda item_count: raise_(\n            ValueError,\n            'Too few items in iterable (got {})'.format(item_count),\n        )\n\n    if too_long is None:\n        too_long = lambda item_count: raise_(\n            ValueError,\n            'Too many items in iterable (got at least {})'.format(item_count),\n        )\n\n    it = iter(iterable)\n    for i in range(n):\n        try:\n            item = next(it)\n        except StopIteration:\n            too_short(i)\n            return\n        else:\n            yield item\n\n    try:\n        next(it)\n    except StopIteration:\n        pass\n    else:\n        too_long(n + 1)\n\n\ndef distinct_permutations(iterable, r=None):\n    \"\"\"Yield successive distinct permutations of the elements in *iterable*.\n\n        >>> sorted(distinct_permutations([1, 0, 1]))\n        [(0, 1, 1), (1, 0, 1), (1, 1, 0)]\n\n    Equivalent to ``set(permutations(iterable))``, except duplicates are not\n    generated and thrown away. For larger input sequences this is much more\n    efficient.\n\n    Duplicate permutations arise when there are duplicated elements in the\n    input iterable. The number of items returned is\n    `n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of\n    items input, and each `x_i` is the count of a distinct item in the input\n    sequence.\n\n    If *r* is given, only the *r*-length permutations are yielded.\n\n        >>> sorted(distinct_permutations([1, 0, 1], r=2))\n        [(0, 1), (1, 0), (1, 1)]\n        >>> sorted(distinct_permutations(range(3), r=2))\n        [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]\n\n    \"\"\"\n    # Algorithm: https://w.wiki/Qai\n    def _full(A):\n        while True:\n            # Yield the permutation we have\n            yield tuple(A)\n\n            # Find the largest index i such that A[i] < A[i + 1]\n            for i in range(size - 2, -1, -1):\n                if A[i] < A[i + 1]:\n                    break\n            #  If no such index exists, this permutation is the last one\n            else:\n                return\n\n            # Find the largest index j greater than j such that A[i] < A[j]\n            for j in range(size - 1, i, -1):\n                if A[i] < A[j]:\n                    break\n\n            # Swap the value of A[i] with that of A[j], then reverse the\n            # sequence from A[i + 1] to form the new permutation\n            A[i], A[j] = A[j], A[i]\n            A[i + 1 :] = A[: i - size : -1]  # A[i + 1:][::-1]\n\n    # Algorithm: modified from the above\n    def _partial(A, r):\n        # Split A into the first r items and the last r items\n        head, tail = A[:r], A[r:]\n        right_head_indexes = range(r - 1, -1, -1)\n        left_tail_indexes = range(len(tail))\n\n        while True:\n            # Yield the permutation we have\n            yield tuple(head)\n\n            # Starting from the right, find the first index of the head with\n            # value smaller than the maximum value of the tail - call it i.\n            pivot = tail[-1]\n            for i in right_head_indexes:\n                if head[i] < pivot:\n                    break\n                pivot = head[i]\n            else:\n                return\n\n            # Starting from the left, find the first value of the tail\n            # with a value greater than head[i] and swap.\n            for j in left_tail_indexes:\n                if tail[j] > head[i]:\n                    head[i], tail[j] = tail[j], head[i]\n                    break\n            # If we didn't find one, start from the right and find the first\n            # index of the head with a value greater than head[i] and swap.\n            else:\n                for j in right_head_indexes:\n                    if head[j] > head[i]:\n                        head[i], head[j] = head[j], head[i]\n                        break\n\n            # Reverse head[i + 1:] and swap it with tail[:r - (i + 1)]\n            tail += head[: i - r : -1]  # head[i + 1:][::-1]\n            i += 1\n            head[i:], tail[:] = tail[: r - i], tail[r - i :]\n\n    items = sorted(iterable)\n\n    size = len(items)\n    if r is None:\n        r = size\n\n    if 0 < r <= size:\n        return _full(items) if (r == size) else _partial(items, r)\n\n    return iter(() if r else ((),))\n\n\ndef intersperse(e, iterable, n=1):\n    \"\"\"Intersperse filler element *e* among the items in *iterable*, leaving\n    *n* items between each filler element.\n\n        >>> list(intersperse('!', [1, 2, 3, 4, 5]))\n        [1, '!', 2, '!', 3, '!', 4, '!', 5]\n\n        >>> list(intersperse(None, [1, 2, 3, 4, 5], n=2))\n        [1, 2, None, 3, 4, None, 5]\n\n    \"\"\"\n    if n == 0:\n        raise ValueError('n must be > 0')\n    elif n == 1:\n        # interleave(repeat(e), iterable) -> e, x_0, e, x_1, e, x_2...\n        # islice(..., 1, None) -> x_0, e, x_1, e, x_2...\n        return islice(interleave(repeat(e), iterable), 1, None)\n    else:\n        # interleave(filler, chunks) -> [e], [x_0, x_1], [e], [x_2, x_3]...\n        # islice(..., 1, None) -> [x_0, x_1], [e], [x_2, x_3]...\n        # flatten(...) -> x_0, x_1, e, x_2, x_3...\n        filler = repeat([e])\n        chunks = chunked(iterable, n)\n        return flatten(islice(interleave(filler, chunks), 1, None))\n\n\ndef unique_to_each(*iterables):\n    \"\"\"Return the elements from each of the input iterables that aren't in the\n    other input iterables.\n\n    For example, suppose you have a set of packages, each with a set of\n    dependencies::\n\n        {'pkg_1': {'A', 'B'}, 'pkg_2': {'B', 'C'}, 'pkg_3': {'B', 'D'}}\n\n    If you remove one package, which dependencies can also be removed?\n\n    If ``pkg_1`` is removed, then ``A`` is no longer necessary - it is not\n    associated with ``pkg_2`` or ``pkg_3``. Similarly, ``C`` is only needed for\n    ``pkg_2``, and ``D`` is only needed for ``pkg_3``::\n\n        >>> unique_to_each({'A', 'B'}, {'B', 'C'}, {'B', 'D'})\n        [['A'], ['C'], ['D']]\n\n    If there are duplicates in one input iterable that aren't in the others\n    they will be duplicated in the output. Input order is preserved::\n\n        >>> unique_to_each(\"mississippi\", \"missouri\")\n        [['p', 'p'], ['o', 'u', 'r']]\n\n    It is assumed that the elements of each iterable are hashable.\n\n    \"\"\"\n    pool = [list(it) for it in iterables]\n    counts = Counter(chain.from_iterable(map(set, pool)))\n    uniques = {element for element in counts if counts[element] == 1}\n    return [list(filter(uniques.__contains__, it)) for it in pool]\n\n\ndef windowed(seq, n, fillvalue=None, step=1):\n    \"\"\"Return a sliding window of width *n* over the given iterable.\n\n        >>> all_windows = windowed([1, 2, 3, 4, 5], 3)\n        >>> list(all_windows)\n        [(1, 2, 3), (2, 3, 4), (3, 4, 5)]\n\n    When the window is larger than the iterable, *fillvalue* is used in place\n    of missing values:\n\n        >>> list(windowed([1, 2, 3], 4))\n        [(1, 2, 3, None)]\n\n    Each window will advance in increments of *step*:\n\n        >>> list(windowed([1, 2, 3, 4, 5, 6], 3, fillvalue='!', step=2))\n        [(1, 2, 3), (3, 4, 5), (5, 6, '!')]\n\n    To slide into the iterable's items, use :func:`chain` to add filler items\n    to the left:\n\n        >>> iterable = [1, 2, 3, 4]\n        >>> n = 3\n        >>> padding = [None] * (n - 1)\n        >>> list(windowed(chain(padding, iterable), 3))\n        [(None, None, 1), (None, 1, 2), (1, 2, 3), (2, 3, 4)]\n    \"\"\"\n    if n < 0:\n        raise ValueError('n must be >= 0')\n    if n == 0:\n        yield tuple()\n        return\n    if step < 1:\n        raise ValueError('step must be >= 1')\n\n    window = deque(maxlen=n)\n    i = n\n    for _ in map(window.append, seq):\n        i -= 1\n        if not i:\n            i = step\n            yield tuple(window)\n\n    size = len(window)\n    if size < n:\n        yield tuple(chain(window, repeat(fillvalue, n - size)))\n    elif 0 < i < min(step, n):\n        window += (fillvalue,) * i\n        yield tuple(window)\n\n\ndef substrings(iterable):\n    \"\"\"Yield all of the substrings of *iterable*.\n\n        >>> [''.join(s) for s in substrings('more')]\n        ['m', 'o', 'r', 'e', 'mo', 'or', 're', 'mor', 'ore', 'more']\n\n    Note that non-string iterables can also be subdivided.\n\n        >>> list(substrings([0, 1, 2]))\n        [(0,), (1,), (2,), (0, 1), (1, 2), (0, 1, 2)]\n\n    \"\"\"\n    # The length-1 substrings\n    seq = []\n    for item in iter(iterable):\n        seq.append(item)\n        yield (item,)\n    seq = tuple(seq)\n    item_count = len(seq)\n\n    # And the rest\n    for n in range(2, item_count + 1):\n        for i in range(item_count - n + 1):\n            yield seq[i : i + n]\n\n\ndef substrings_indexes(seq, reverse=False):\n    \"\"\"Yield all substrings and their positions in *seq*\n\n    The items yielded will be a tuple of the form ``(substr, i, j)``, where\n    ``substr == seq[i:j]``.\n\n    This function only works for iterables that support slicing, such as\n    ``str`` objects.\n\n    >>> for item in substrings_indexes('more'):\n    ...    print(item)\n    ('m', 0, 1)\n    ('o', 1, 2)\n    ('r', 2, 3)\n    ('e', 3, 4)\n    ('mo', 0, 2)\n    ('or', 1, 3)\n    ('re', 2, 4)\n    ('mor', 0, 3)\n    ('ore', 1, 4)\n    ('more', 0, 4)\n\n    Set *reverse* to ``True`` to yield the same items in the opposite order.\n\n\n    \"\"\"\n    r = range(1, len(seq) + 1)\n    if reverse:\n        r = reversed(r)\n    return (\n        (seq[i : i + L], i, i + L) for L in r for i in range(len(seq) - L + 1)\n    )\n\n\nclass bucket:\n    \"\"\"Wrap *iterable* and return an object that buckets it iterable into\n    child iterables based on a *key* function.\n\n        >>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3']\n        >>> s = bucket(iterable, key=lambda x: x[0])  # Bucket by 1st character\n        >>> sorted(list(s))  # Get the keys\n        ['a', 'b', 'c']\n        >>> a_iterable = s['a']\n        >>> next(a_iterable)\n        'a1'\n        >>> next(a_iterable)\n        'a2'\n        >>> list(s['b'])\n        ['b1', 'b2', 'b3']\n\n    The original iterable will be advanced and its items will be cached until\n    they are used by the child iterables. This may require significant storage.\n\n    By default, attempting to select a bucket to which no items belong  will\n    exhaust the iterable and cache all values.\n    If you specify a *validator* function, selected buckets will instead be\n    checked against it.\n\n        >>> from itertools import count\n        >>> it = count(1, 2)  # Infinite sequence of odd numbers\n        >>> key = lambda x: x % 10  # Bucket by last digit\n        >>> validator = lambda x: x in {1, 3, 5, 7, 9}  # Odd digits only\n        >>> s = bucket(it, key=key, validator=validator)\n        >>> 2 in s\n        False\n        >>> list(s[2])\n        []\n\n    \"\"\"\n\n    def __init__(self, iterable, key, validator=None):\n        self._it = iter(iterable)\n        self._key = key\n        self._cache = defaultdict(deque)\n        self._validator = validator or (lambda x: True)\n\n    def __contains__(self, value):\n        if not self._validator(value):\n            return False\n\n        try:\n            item = next(self[value])\n        except StopIteration:\n            return False\n        else:\n            self._cache[value].appendleft(item)\n\n        return True\n\n    def _get_values(self, value):\n        \"\"\"\n        Helper to yield items from the parent iterator that match *value*.\n        Items that don't match are stored in the local cache as they\n        are encountered.\n        \"\"\"\n        while True:\n            # If we've cached some items that match the target value, emit\n            # the first one and evict it from the cache.\n            if self._cache[value]:\n                yield self._cache[value].popleft()\n            # Otherwise we need to advance the parent iterator to search for\n            # a matching item, caching the rest.\n            else:\n                while True:\n                    try:\n                        item = next(self._it)\n                    except StopIteration:\n                        return\n                    item_value = self._key(item)\n                    if item_value == value:\n                        yield item\n                        break\n                    elif self._validator(item_value):\n                        self._cache[item_value].append(item)\n\n    def __iter__(self):\n        for item in self._it:\n            item_value = self._key(item)\n            if self._validator(item_value):\n                self._cache[item_value].append(item)\n\n        yield from self._cache.keys()\n\n    def __getitem__(self, value):\n        if not self._validator(value):\n            return iter(())\n\n        return self._get_values(value)\n\n\ndef spy(iterable, n=1):\n    \"\"\"Return a 2-tuple with a list containing the first *n* elements of\n    *iterable*, and an iterator with the same items as *iterable*.\n    This allows you to \"look ahead\" at the items in the iterable without\n    advancing it.\n\n    There is one item in the list by default:\n\n        >>> iterable = 'abcdefg'\n        >>> head, iterable = spy(iterable)\n        >>> head\n        ['a']\n        >>> list(iterable)\n        ['a', 'b', 'c', 'd', 'e', 'f', 'g']\n\n    You may use unpacking to retrieve items instead of lists:\n\n        >>> (head,), iterable = spy('abcdefg')\n        >>> head\n        'a'\n        >>> (first, second), iterable = spy('abcdefg', 2)\n        >>> first\n        'a'\n        >>> second\n        'b'\n\n    The number of items requested can be larger than the number of items in\n    the iterable:\n\n        >>> iterable = [1, 2, 3, 4, 5]\n        >>> head, iterable = spy(iterable, 10)\n        >>> head\n        [1, 2, 3, 4, 5]\n        >>> list(iterable)\n        [1, 2, 3, 4, 5]\n\n    \"\"\"\n    it = iter(iterable)\n    head = take(n, it)\n\n    return head.copy(), chain(head, it)\n\n\ndef interleave(*iterables):\n    \"\"\"Return a new iterable yielding from each iterable in turn,\n    until the shortest is exhausted.\n\n        >>> list(interleave([1, 2, 3], [4, 5], [6, 7, 8]))\n        [1, 4, 6, 2, 5, 7]\n\n    For a version that doesn't terminate after the shortest iterable is\n    exhausted, see :func:`interleave_longest`.\n\n    \"\"\"\n    return chain.from_iterable(zip(*iterables))\n\n\ndef interleave_longest(*iterables):\n    \"\"\"Return a new iterable yielding from each iterable in turn,\n    skipping any that are exhausted.\n\n        >>> list(interleave_longest([1, 2, 3], [4, 5], [6, 7, 8]))\n        [1, 4, 6, 2, 5, 7, 3, 8]\n\n    This function produces the same output as :func:`roundrobin`, but may\n    perform better for some inputs (in particular when the number of iterables\n    is large).\n\n    \"\"\"\n    i = chain.from_iterable(zip_longest(*iterables, fillvalue=_marker))\n    return (x for x in i if x is not _marker)\n\n\ndef interleave_evenly(iterables, lengths=None):\n    \"\"\"\n    Interleave multiple iterables so that their elements are evenly distributed\n    throughout the output sequence.\n\n    >>> iterables = [1, 2, 3, 4, 5], ['a', 'b']\n    >>> list(interleave_evenly(iterables))\n    [1, 2, 'a', 3, 4, 'b', 5]\n\n    >>> iterables = [[1, 2, 3], [4, 5], [6, 7, 8]]\n    >>> list(interleave_evenly(iterables))\n    [1, 6, 4, 2, 7, 3, 8, 5]\n\n    This function requires iterables of known length. Iterables without\n    ``__len__()`` can be used by manually specifying lengths with *lengths*:\n\n    >>> from itertools import combinations, repeat\n    >>> iterables = [combinations(range(4), 2), ['a', 'b', 'c']]\n    >>> lengths = [4 * (4 - 1) // 2, 3]\n    >>> list(interleave_evenly(iterables, lengths=lengths))\n    [(0, 1), (0, 2), 'a', (0, 3), (1, 2), 'b', (1, 3), (2, 3), 'c']\n\n    Based on Bresenham's algorithm.\n    \"\"\"\n    if lengths is None:\n        try:\n            lengths = [len(it) for it in iterables]\n        except TypeError:\n            raise ValueError(\n                'Iterable lengths could not be determined automatically. '\n                'Specify them with the lengths keyword.'\n            )\n    elif len(iterables) != len(lengths):\n        raise ValueError('Mismatching number of iterables and lengths.')\n\n    dims = len(lengths)\n\n    # sort iterables by length, descending\n    lengths_permute = sorted(\n        range(dims), key=lambda i: lengths[i], reverse=True\n    )\n    lengths_desc = [lengths[i] for i in lengths_permute]\n    iters_desc = [iter(iterables[i]) for i in lengths_permute]\n\n    # the longest iterable is the primary one (Bresenham: the longest\n    # distance along an axis)\n    delta_primary, deltas_secondary = lengths_desc[0], lengths_desc[1:]\n    iter_primary, iters_secondary = iters_desc[0], iters_desc[1:]\n    errors = [delta_primary // dims] * len(deltas_secondary)\n\n    to_yield = sum(lengths)\n    while to_yield:\n        yield next(iter_primary)\n        to_yield -= 1\n        # update errors for each secondary iterable\n        errors = [e - delta for e, delta in zip(errors, deltas_secondary)]\n\n        # those iterables for which the error is negative are yielded\n        # (\"diagonal step\" in Bresenham)\n        for i, e in enumerate(errors):\n            if e < 0:\n                yield next(iters_secondary[i])\n                to_yield -= 1\n                errors[i] += delta_primary\n\n\ndef collapse(iterable, base_type=None, levels=None):\n    \"\"\"Flatten an iterable with multiple levels of nesting (e.g., a list of\n    lists of tuples) into non-iterable types.\n\n        >>> iterable = [(1, 2), ([3, 4], [[5], [6]])]\n        >>> list(collapse(iterable))\n        [1, 2, 3, 4, 5, 6]\n\n    Binary and text strings are not considered iterable and\n    will not be collapsed.\n\n    To avoid collapsing other types, specify *base_type*:\n\n        >>> iterable = ['ab', ('cd', 'ef'), ['gh', 'ij']]\n        >>> list(collapse(iterable, base_type=tuple))\n        ['ab', ('cd', 'ef'), 'gh', 'ij']\n\n    Specify *levels* to stop flattening after a certain level:\n\n    >>> iterable = [('a', ['b']), ('c', ['d'])]\n    >>> list(collapse(iterable))  # Fully flattened\n    ['a', 'b', 'c', 'd']\n    >>> list(collapse(iterable, levels=1))  # Only one level flattened\n    ['a', ['b'], 'c', ['d']]\n\n    \"\"\"\n\n    def walk(node, level):\n        if (\n            ((levels is not None) and (level > levels))\n            or isinstance(node, (str, bytes))\n            or ((base_type is not None) and isinstance(node, base_type))\n        ):\n            yield node\n            return\n\n        try:\n            tree = iter(node)\n        except TypeError:\n            yield node\n            return\n        else:\n            for child in tree:\n                yield from walk(child, level + 1)\n\n    yield from walk(iterable, 0)\n\n\ndef side_effect(func, iterable, chunk_size=None, before=None, after=None):\n    \"\"\"Invoke *func* on each item in *iterable* (or on each *chunk_size* group\n    of items) before yielding the item.\n\n    `func` must be a function that takes a single argument. Its return value\n    will be discarded.\n\n    *before* and *after* are optional functions that take no arguments. They\n    will be executed before iteration starts and after it ends, respectively.\n\n    `side_effect` can be used for logging, updating progress bars, or anything\n    that is not functionally \"pure.\"\n\n    Emitting a status message:\n\n        >>> from more_itertools import consume\n        >>> func = lambda item: print('Received {}'.format(item))\n        >>> consume(side_effect(func, range(2)))\n        Received 0\n        Received 1\n\n    Operating on chunks of items:\n\n        >>> pair_sums = []\n        >>> func = lambda chunk: pair_sums.append(sum(chunk))\n        >>> list(side_effect(func, [0, 1, 2, 3, 4, 5], 2))\n        [0, 1, 2, 3, 4, 5]\n        >>> list(pair_sums)\n        [1, 5, 9]\n\n    Writing to a file-like object:\n\n        >>> from io import StringIO\n        >>> from more_itertools import consume\n        >>> f = StringIO()\n        >>> func = lambda x: print(x, file=f)\n        >>> before = lambda: print(u'HEADER', file=f)\n        >>> after = f.close\n        >>> it = [u'a', u'b', u'c']\n        >>> consume(side_effect(func, it, before=before, after=after))\n        >>> f.closed\n        True\n\n    \"\"\"\n    try:\n        if before is not None:\n            before()\n\n        if chunk_size is None:\n            for item in iterable:\n                func(item)\n                yield item\n        else:\n            for chunk in chunked(iterable, chunk_size):\n                func(chunk)\n                yield from chunk\n    finally:\n        if after is not None:\n            after()\n\n\ndef sliced(seq, n, strict=False):\n    \"\"\"Yield slices of length *n* from the sequence *seq*.\n\n    >>> list(sliced((1, 2, 3, 4, 5, 6), 3))\n    [(1, 2, 3), (4, 5, 6)]\n\n    By the default, the last yielded slice will have fewer than *n* elements\n    if the length of *seq* is not divisible by *n*:\n\n    >>> list(sliced((1, 2, 3, 4, 5, 6, 7, 8), 3))\n    [(1, 2, 3), (4, 5, 6), (7, 8)]\n\n    If the length of *seq* is not divisible by *n* and *strict* is\n    ``True``, then ``ValueError`` will be raised before the last\n    slice is yielded.\n\n    This function will only work for iterables that support slicing.\n    For non-sliceable iterables, see :func:`chunked`.\n\n    \"\"\"\n    iterator = takewhile(len, (seq[i : i + n] for i in count(0, n)))\n    if strict:\n\n        def ret():\n            for _slice in iterator:\n                if len(_slice) != n:\n                    raise ValueError(\"seq is not divisible by n.\")\n                yield _slice\n\n        return iter(ret())\n    else:\n        return iterator\n\n\ndef split_at(iterable, pred, maxsplit=-1, keep_separator=False):\n    \"\"\"Yield lists of items from *iterable*, where each list is delimited by\n    an item where callable *pred* returns ``True``.\n\n        >>> list(split_at('abcdcba', lambda x: x == 'b'))\n        [['a'], ['c', 'd', 'c'], ['a']]\n\n        >>> list(split_at(range(10), lambda n: n % 2 == 1))\n        [[0], [2], [4], [6], [8], []]\n\n    At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,\n    then there is no limit on the number of splits:\n\n        >>> list(split_at(range(10), lambda n: n % 2 == 1, maxsplit=2))\n        [[0], [2], [4, 5, 6, 7, 8, 9]]\n\n    By default, the delimiting items are not included in the output.\n    The include them, set *keep_separator* to ``True``.\n\n        >>> list(split_at('abcdcba', lambda x: x == 'b', keep_separator=True))\n        [['a'], ['b'], ['c', 'd', 'c'], ['b'], ['a']]\n\n    \"\"\"\n    if maxsplit == 0:\n        yield list(iterable)\n        return\n\n    buf = []\n    it = iter(iterable)\n    for item in it:\n        if pred(item):\n            yield buf\n            if keep_separator:\n                yield [item]\n            if maxsplit == 1:\n                yield list(it)\n                return\n            buf = []\n            maxsplit -= 1\n        else:\n            buf.append(item)\n    yield buf\n\n\ndef split_before(iterable, pred, maxsplit=-1):\n    \"\"\"Yield lists of items from *iterable*, where each list ends just before\n    an item for which callable *pred* returns ``True``:\n\n        >>> list(split_before('OneTwo', lambda s: s.isupper()))\n        [['O', 'n', 'e'], ['T', 'w', 'o']]\n\n        >>> list(split_before(range(10), lambda n: n % 3 == 0))\n        [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]\n\n    At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,\n    then there is no limit on the number of splits:\n\n        >>> list(split_before(range(10), lambda n: n % 3 == 0, maxsplit=2))\n        [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]\n    \"\"\"\n    if maxsplit == 0:\n        yield list(iterable)\n        return\n\n    buf = []\n    it = iter(iterable)\n    for item in it:\n        if pred(item) and buf:\n            yield buf\n            if maxsplit == 1:\n                yield [item] + list(it)\n                return\n            buf = []\n            maxsplit -= 1\n        buf.append(item)\n    if buf:\n        yield buf\n\n\ndef split_after(iterable, pred, maxsplit=-1):\n    \"\"\"Yield lists of items from *iterable*, where each list ends with an\n    item where callable *pred* returns ``True``:\n\n        >>> list(split_after('one1two2', lambda s: s.isdigit()))\n        [['o', 'n', 'e', '1'], ['t', 'w', 'o', '2']]\n\n        >>> list(split_after(range(10), lambda n: n % 3 == 0))\n        [[0], [1, 2, 3], [4, 5, 6], [7, 8, 9]]\n\n    At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,\n    then there is no limit on the number of splits:\n\n        >>> list(split_after(range(10), lambda n: n % 3 == 0, maxsplit=2))\n        [[0], [1, 2, 3], [4, 5, 6, 7, 8, 9]]\n\n    \"\"\"\n    if maxsplit == 0:\n        yield list(iterable)\n        return\n\n    buf = []\n    it = iter(iterable)\n    for item in it:\n        buf.append(item)\n        if pred(item) and buf:\n            yield buf\n            if maxsplit == 1:\n                yield list(it)\n                return\n            buf = []\n            maxsplit -= 1\n    if buf:\n        yield buf\n\n\ndef split_when(iterable, pred, maxsplit=-1):\n    \"\"\"Split *iterable* into pieces based on the output of *pred*.\n    *pred* should be a function that takes successive pairs of items and\n    returns ``True`` if the iterable should be split in between them.\n\n    For example, to find runs of increasing numbers, split the iterable when\n    element ``i`` is larger than element ``i + 1``:\n\n        >>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2], lambda x, y: x > y))\n        [[1, 2, 3, 3], [2, 5], [2, 4], [2]]\n\n    At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,\n    then there is no limit on the number of splits:\n\n        >>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2],\n        ...                 lambda x, y: x > y, maxsplit=2))\n        [[1, 2, 3, 3], [2, 5], [2, 4, 2]]\n\n    \"\"\"\n    if maxsplit == 0:\n        yield list(iterable)\n        return\n\n    it = iter(iterable)\n    try:\n        cur_item = next(it)\n    except StopIteration:\n        return\n\n    buf = [cur_item]\n    for next_item in it:\n        if pred(cur_item, next_item):\n            yield buf\n            if maxsplit == 1:\n                yield [next_item] + list(it)\n                return\n            buf = []\n            maxsplit -= 1\n\n        buf.append(next_item)\n        cur_item = next_item\n\n    yield buf\n\n\ndef split_into(iterable, sizes):\n    \"\"\"Yield a list of sequential items from *iterable* of length 'n' for each\n    integer 'n' in *sizes*.\n\n        >>> list(split_into([1,2,3,4,5,6], [1,2,3]))\n        [[1], [2, 3], [4, 5, 6]]\n\n    If the sum of *sizes* is smaller than the length of *iterable*, then the\n    remaining items of *iterable* will not be returned.\n\n        >>> list(split_into([1,2,3,4,5,6], [2,3]))\n        [[1, 2], [3, 4, 5]]\n\n    If the sum of *sizes* is larger than the length of *iterable*, fewer items\n    will be returned in the iteration that overruns *iterable* and further\n    lists will be empty:\n\n        >>> list(split_into([1,2,3,4], [1,2,3,4]))\n        [[1], [2, 3], [4], []]\n\n    When a ``None`` object is encountered in *sizes*, the returned list will\n    contain items up to the end of *iterable* the same way that itertools.slice\n    does:\n\n        >>> list(split_into([1,2,3,4,5,6,7,8,9,0], [2,3,None]))\n        [[1, 2], [3, 4, 5], [6, 7, 8, 9, 0]]\n\n    :func:`split_into` can be useful for grouping a series of items where the\n    sizes of the groups are not uniform. An example would be where in a row\n    from a table, multiple columns represent elements of the same feature\n    (e.g. a point represented by x,y,z) but, the format is not the same for\n    all columns.\n    \"\"\"\n    # convert the iterable argument into an iterator so its contents can\n    # be consumed by islice in case it is a generator\n    it = iter(iterable)\n\n    for size in sizes:\n        if size is None:\n            yield list(it)\n            return\n        else:\n            yield list(islice(it, size))\n\n\ndef padded(iterable, fillvalue=None, n=None, next_multiple=False):\n    \"\"\"Yield the elements from *iterable*, followed by *fillvalue*, such that\n    at least *n* items are emitted.\n\n        >>> list(padded([1, 2, 3], '?', 5))\n        [1, 2, 3, '?', '?']\n\n    If *next_multiple* is ``True``, *fillvalue* will be emitted until the\n    number of items emitted is a multiple of *n*::\n\n        >>> list(padded([1, 2, 3, 4], n=3, next_multiple=True))\n        [1, 2, 3, 4, None, None]\n\n    If *n* is ``None``, *fillvalue* will be emitted indefinitely.\n\n    \"\"\"\n    it = iter(iterable)\n    if n is None:\n        yield from chain(it, repeat(fillvalue))\n    elif n < 1:\n        raise ValueError('n must be at least 1')\n    else:\n        item_count = 0\n        for item in it:\n            yield item\n            item_count += 1\n\n        remaining = (n - item_count) % n if next_multiple else n - item_count\n        for _ in range(remaining):\n            yield fillvalue\n\n\ndef repeat_each(iterable, n=2):\n    \"\"\"Repeat each element in *iterable* *n* times.\n\n    >>> list(repeat_each('ABC', 3))\n    ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C']\n    \"\"\"\n    return chain.from_iterable(map(repeat, iterable, repeat(n)))\n\n\ndef repeat_last(iterable, default=None):\n    \"\"\"After the *iterable* is exhausted, keep yielding its last element.\n\n        >>> list(islice(repeat_last(range(3)), 5))\n        [0, 1, 2, 2, 2]\n\n    If the iterable is empty, yield *default* forever::\n\n        >>> list(islice(repeat_last(range(0), 42), 5))\n        [42, 42, 42, 42, 42]\n\n    \"\"\"\n    item = _marker\n    for item in iterable:\n        yield item\n    final = default if item is _marker else item\n    yield from repeat(final)\n\n\ndef distribute(n, iterable):\n    \"\"\"Distribute the items from *iterable* among *n* smaller iterables.\n\n        >>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6])\n        >>> list(group_1)\n        [1, 3, 5]\n        >>> list(group_2)\n        [2, 4, 6]\n\n    If the length of *iterable* is not evenly divisible by *n*, then the\n    length of the returned iterables will not be identical:\n\n        >>> children = distribute(3, [1, 2, 3, 4, 5, 6, 7])\n        >>> [list(c) for c in children]\n        [[1, 4, 7], [2, 5], [3, 6]]\n\n    If the length of *iterable* is smaller than *n*, then the last returned\n    iterables will be empty:\n\n        >>> children = distribute(5, [1, 2, 3])\n        >>> [list(c) for c in children]\n        [[1], [2], [3], [], []]\n\n    This function uses :func:`itertools.tee` and may require significant\n    storage. If you need the order items in the smaller iterables to match the\n    original iterable, see :func:`divide`.\n\n    \"\"\"\n    if n < 1:\n        raise ValueError('n must be at least 1')\n\n    children = tee(iterable, n)\n    return [islice(it, index, None, n) for index, it in enumerate(children)]\n\n\ndef stagger(iterable, offsets=(-1, 0, 1), longest=False, fillvalue=None):\n    \"\"\"Yield tuples whose elements are offset from *iterable*.\n    The amount by which the `i`-th item in each tuple is offset is given by\n    the `i`-th item in *offsets*.\n\n        >>> list(stagger([0, 1, 2, 3]))\n        [(None, 0, 1), (0, 1, 2), (1, 2, 3)]\n        >>> list(stagger(range(8), offsets=(0, 2, 4)))\n        [(0, 2, 4), (1, 3, 5), (2, 4, 6), (3, 5, 7)]\n\n    By default, the sequence will end when the final element of a tuple is the\n    last item in the iterable. To continue until the first element of a tuple\n    is the last item in the iterable, set *longest* to ``True``::\n\n        >>> list(stagger([0, 1, 2, 3], longest=True))\n        [(None, 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, None), (3, None, None)]\n\n    By default, ``None`` will be used to replace offsets beyond the end of the\n    sequence. Specify *fillvalue* to use some other value.\n\n    \"\"\"\n    children = tee(iterable, len(offsets))\n\n    return zip_offset(\n        *children, offsets=offsets, longest=longest, fillvalue=fillvalue\n    )\n\n\nclass UnequalIterablesError(ValueError):\n    def __init__(self, details=None):\n        msg = 'Iterables have different lengths'\n        if details is not None:\n            msg += (': index 0 has length {}; index {} has length {}').format(\n                *details\n            )\n\n        super().__init__(msg)\n\n\ndef _zip_equal_generator(iterables):\n    for combo in zip_longest(*iterables, fillvalue=_marker):\n        for val in combo:\n            if val is _marker:\n                raise UnequalIterablesError()\n        yield combo\n\n\ndef _zip_equal(*iterables):\n    # Check whether the iterables are all the same size.\n    try:\n        first_size = len(iterables[0])\n        for i, it in enumerate(iterables[1:], 1):\n            size = len(it)\n            if size != first_size:\n                break\n        else:\n            # If we didn't break out, we can use the built-in zip.\n            return zip(*iterables)\n\n        # If we did break out, there was a mismatch.\n        raise UnequalIterablesError(details=(first_size, i, size))\n    # If any one of the iterables didn't have a length, start reading\n    # them until one runs out.\n    except TypeError:\n        return _zip_equal_generator(iterables)\n\n\ndef zip_equal(*iterables):\n    \"\"\"``zip`` the input *iterables* together, but raise\n    ``UnequalIterablesError`` if they aren't all the same length.\n\n        >>> it_1 = range(3)\n        >>> it_2 = iter('abc')\n        >>> list(zip_equal(it_1, it_2))\n        [(0, 'a'), (1, 'b'), (2, 'c')]\n\n        >>> it_1 = range(3)\n        >>> it_2 = iter('abcd')\n        >>> list(zip_equal(it_1, it_2)) # doctest: +IGNORE_EXCEPTION_DETAIL\n        Traceback (most recent call last):\n        ...\n        more_itertools.more.UnequalIterablesError: Iterables have different\n        lengths\n\n    \"\"\"\n    if hexversion >= 0x30A00A6:\n        warnings.warn(\n            (\n                'zip_equal will be removed in a future version of '\n                'more-itertools. Use the builtin zip function with '\n                'strict=True instead.'\n            ),\n            DeprecationWarning,\n        )\n\n    return _zip_equal(*iterables)\n\n\ndef zip_offset(*iterables, offsets, longest=False, fillvalue=None):\n    \"\"\"``zip`` the input *iterables* together, but offset the `i`-th iterable\n    by the `i`-th item in *offsets*.\n\n        >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1)))\n        [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e')]\n\n    This can be used as a lightweight alternative to SciPy or pandas to analyze\n    data sets in which some series have a lead or lag relationship.\n\n    By default, the sequence will end when the shortest iterable is exhausted.\n    To continue until the longest iterable is exhausted, set *longest* to\n    ``True``.\n\n        >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1), longest=True))\n        [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e'), (None, 'f')]\n\n    By default, ``None`` will be used to replace offsets beyond the end of the\n    sequence. Specify *fillvalue* to use some other value.\n\n    \"\"\"\n    if len(iterables) != len(offsets):\n        raise ValueError(\"Number of iterables and offsets didn't match\")\n\n    staggered = []\n    for it, n in zip(iterables, offsets):\n        if n < 0:\n            staggered.append(chain(repeat(fillvalue, -n), it))\n        elif n > 0:\n            staggered.append(islice(it, n, None))\n        else:\n            staggered.append(it)\n\n    if longest:\n        return zip_longest(*staggered, fillvalue=fillvalue)\n\n    return zip(*staggered)\n\n\ndef sort_together(iterables, key_list=(0,), key=None, reverse=False):\n    \"\"\"Return the input iterables sorted together, with *key_list* as the\n    priority for sorting. All iterables are trimmed to the length of the\n    shortest one.\n\n    This can be used like the sorting function in a spreadsheet. If each\n    iterable represents a column of data, the key list determines which\n    columns are used for sorting.\n\n    By default, all iterables are sorted using the ``0``-th iterable::\n\n        >>> iterables = [(4, 3, 2, 1), ('a', 'b', 'c', 'd')]\n        >>> sort_together(iterables)\n        [(1, 2, 3, 4), ('d', 'c', 'b', 'a')]\n\n    Set a different key list to sort according to another iterable.\n    Specifying multiple keys dictates how ties are broken::\n\n        >>> iterables = [(3, 1, 2), (0, 1, 0), ('c', 'b', 'a')]\n        >>> sort_together(iterables, key_list=(1, 2))\n        [(2, 3, 1), (0, 0, 1), ('a', 'c', 'b')]\n\n    To sort by a function of the elements of the iterable, pass a *key*\n    function. Its arguments are the elements of the iterables corresponding to\n    the key list::\n\n        >>> names = ('a', 'b', 'c')\n        >>> lengths = (1, 2, 3)\n        >>> widths = (5, 2, 1)\n        >>> def area(length, width):\n        ...     return length * width\n        >>> sort_together([names, lengths, widths], key_list=(1, 2), key=area)\n        [('c', 'b', 'a'), (3, 2, 1), (1, 2, 5)]\n\n    Set *reverse* to ``True`` to sort in descending order.\n\n        >>> sort_together([(1, 2, 3), ('c', 'b', 'a')], reverse=True)\n        [(3, 2, 1), ('a', 'b', 'c')]\n\n    \"\"\"\n    if key is None:\n        # if there is no key function, the key argument to sorted is an\n        # itemgetter\n        key_argument = itemgetter(*key_list)\n    else:\n        # if there is a key function, call it with the items at the offsets\n        # specified by the key function as arguments\n        key_list = list(key_list)\n        if len(key_list) == 1:\n            # if key_list contains a single item, pass the item at that offset\n            # as the only argument to the key function\n            key_offset = key_list[0]\n            key_argument = lambda zipped_items: key(zipped_items[key_offset])\n        else:\n            # if key_list contains multiple items, use itemgetter to return a\n            # tuple of items, which we pass as *args to the key function\n            get_key_items = itemgetter(*key_list)\n            key_argument = lambda zipped_items: key(\n                *get_key_items(zipped_items)\n            )\n\n    return list(\n        zip(*sorted(zip(*iterables), key=key_argument, reverse=reverse))\n    )\n\n\ndef unzip(iterable):\n    \"\"\"The inverse of :func:`zip`, this function disaggregates the elements\n    of the zipped *iterable*.\n\n    The ``i``-th iterable contains the ``i``-th element from each element\n    of the zipped iterable. The first element is used to to determine the\n    length of the remaining elements.\n\n        >>> iterable = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n        >>> letters, numbers = unzip(iterable)\n        >>> list(letters)\n        ['a', 'b', 'c', 'd']\n        >>> list(numbers)\n        [1, 2, 3, 4]\n\n    This is similar to using ``zip(*iterable)``, but it avoids reading\n    *iterable* into memory. Note, however, that this function uses\n    :func:`itertools.tee` and thus may require significant storage.\n\n    \"\"\"\n    head, iterable = spy(iter(iterable))\n    if not head:\n        # empty iterable, e.g. zip([], [], [])\n        return ()\n    # spy returns a one-length iterable as head\n    head = head[0]\n    iterables = tee(iterable, len(head))\n\n    def itemgetter(i):\n        def getter(obj):\n            try:\n                return obj[i]\n            except IndexError:\n                # basically if we have an iterable like\n                # iter([(1, 2, 3), (4, 5), (6,)])\n                # the second unzipped iterable would fail at the third tuple\n                # since it would try to access tup[1]\n                # same with the third unzipped iterable and the second tuple\n                # to support these \"improperly zipped\" iterables,\n                # we create a custom itemgetter\n                # which just stops the unzipped iterables\n                # at first length mismatch\n                raise StopIteration\n\n        return getter\n\n    return tuple(map(itemgetter(i), it) for i, it in enumerate(iterables))\n\n\ndef divide(n, iterable):\n    \"\"\"Divide the elements from *iterable* into *n* parts, maintaining\n    order.\n\n        >>> group_1, group_2 = divide(2, [1, 2, 3, 4, 5, 6])\n        >>> list(group_1)\n        [1, 2, 3]\n        >>> list(group_2)\n        [4, 5, 6]\n\n    If the length of *iterable* is not evenly divisible by *n*, then the\n    length of the returned iterables will not be identical:\n\n        >>> children = divide(3, [1, 2, 3, 4, 5, 6, 7])\n        >>> [list(c) for c in children]\n        [[1, 2, 3], [4, 5], [6, 7]]\n\n    If the length of the iterable is smaller than n, then the last returned\n    iterables will be empty:\n\n        >>> children = divide(5, [1, 2, 3])\n        >>> [list(c) for c in children]\n        [[1], [2], [3], [], []]\n\n    This function will exhaust the iterable before returning and may require\n    significant storage. If order is not important, see :func:`distribute`,\n    which does not first pull the iterable into memory.\n\n    \"\"\"\n    if n < 1:\n        raise ValueError('n must be at least 1')\n\n    try:\n        iterable[:0]\n    except TypeError:\n        seq = tuple(iterable)\n    else:\n        seq = iterable\n\n    q, r = divmod(len(seq), n)\n\n    ret = []\n    stop = 0\n    for i in range(1, n + 1):\n        start = stop\n        stop += q + 1 if i <= r else q\n        ret.append(iter(seq[start:stop]))\n\n    return ret\n\n\ndef always_iterable(obj, base_type=(str, bytes)):\n    \"\"\"If *obj* is iterable, return an iterator over its items::\n\n        >>> obj = (1, 2, 3)\n        >>> list(always_iterable(obj))\n        [1, 2, 3]\n\n    If *obj* is not iterable, return a one-item iterable containing *obj*::\n\n        >>> obj = 1\n        >>> list(always_iterable(obj))\n        [1]\n\n    If *obj* is ``None``, return an empty iterable:\n\n        >>> obj = None\n        >>> list(always_iterable(None))\n        []\n\n    By default, binary and text strings are not considered iterable::\n\n        >>> obj = 'foo'\n        >>> list(always_iterable(obj))\n        ['foo']\n\n    If *base_type* is set, objects for which ``isinstance(obj, base_type)``\n    returns ``True`` won't be considered iterable.\n\n        >>> obj = {'a': 1}\n        >>> list(always_iterable(obj))  # Iterate over the dict's keys\n        ['a']\n        >>> list(always_iterable(obj, base_type=dict))  # Treat dicts as a unit\n        [{'a': 1}]\n\n    Set *base_type* to ``None`` to avoid any special handling and treat objects\n    Python considers iterable as iterable:\n\n        >>> obj = 'foo'\n        >>> list(always_iterable(obj, base_type=None))\n        ['f', 'o', 'o']\n    \"\"\"\n    if obj is None:\n        return iter(())\n\n    if (base_type is not None) and isinstance(obj, base_type):\n        return iter((obj,))\n\n    try:\n        return iter(obj)\n    except TypeError:\n        return iter((obj,))\n\n\ndef adjacent(predicate, iterable, distance=1):\n    \"\"\"Return an iterable over `(bool, item)` tuples where the `item` is\n    drawn from *iterable* and the `bool` indicates whether\n    that item satisfies the *predicate* or is adjacent to an item that does.\n\n    For example, to find whether items are adjacent to a ``3``::\n\n        >>> list(adjacent(lambda x: x == 3, range(6)))\n        [(False, 0), (False, 1), (True, 2), (True, 3), (True, 4), (False, 5)]\n\n    Set *distance* to change what counts as adjacent. For example, to find\n    whether items are two places away from a ``3``:\n\n        >>> list(adjacent(lambda x: x == 3, range(6), distance=2))\n        [(False, 0), (True, 1), (True, 2), (True, 3), (True, 4), (True, 5)]\n\n    This is useful for contextualizing the results of a search function.\n    For example, a code comparison tool might want to identify lines that\n    have changed, but also surrounding lines to give the viewer of the diff\n    context.\n\n    The predicate function will only be called once for each item in the\n    iterable.\n\n    See also :func:`groupby_transform`, which can be used with this function\n    to group ranges of items with the same `bool` value.\n\n    \"\"\"\n    # Allow distance=0 mainly for testing that it reproduces results with map()\n    if distance < 0:\n        raise ValueError('distance must be at least 0')\n\n    i1, i2 = tee(iterable)\n    padding = [False] * distance\n    selected = chain(padding, map(predicate, i1), padding)\n    adjacent_to_selected = map(any, windowed(selected, 2 * distance + 1))\n    return zip(adjacent_to_selected, i2)\n\n\ndef groupby_transform(iterable, keyfunc=None, valuefunc=None, reducefunc=None):\n    \"\"\"An extension of :func:`itertools.groupby` that can apply transformations\n    to the grouped data.\n\n    * *keyfunc* is a function computing a key value for each item in *iterable*\n    * *valuefunc* is a function that transforms the individual items from\n      *iterable* after grouping\n    * *reducefunc* is a function that transforms each group of items\n\n    >>> iterable = 'aAAbBBcCC'\n    >>> keyfunc = lambda k: k.upper()\n    >>> valuefunc = lambda v: v.lower()\n    >>> reducefunc = lambda g: ''.join(g)\n    >>> list(groupby_transform(iterable, keyfunc, valuefunc, reducefunc))\n    [('A', 'aaa'), ('B', 'bbb'), ('C', 'ccc')]\n\n    Each optional argument defaults to an identity function if not specified.\n\n    :func:`groupby_transform` is useful when grouping elements of an iterable\n    using a separate iterable as the key. To do this, :func:`zip` the iterables\n    and pass a *keyfunc* that extracts the first element and a *valuefunc*\n    that extracts the second element::\n\n        >>> from operator import itemgetter\n        >>> keys = [0, 0, 1, 1, 1, 2, 2, 2, 3]\n        >>> values = 'abcdefghi'\n        >>> iterable = zip(keys, values)\n        >>> grouper = groupby_transform(iterable, itemgetter(0), itemgetter(1))\n        >>> [(k, ''.join(g)) for k, g in grouper]\n        [(0, 'ab'), (1, 'cde'), (2, 'fgh'), (3, 'i')]\n\n    Note that the order of items in the iterable is significant.\n    Only adjacent items are grouped together, so if you don't want any\n    duplicate groups, you should sort the iterable by the key function.\n\n    \"\"\"\n    ret = groupby(iterable, keyfunc)\n    if valuefunc:\n        ret = ((k, map(valuefunc, g)) for k, g in ret)\n    if reducefunc:\n        ret = ((k, reducefunc(g)) for k, g in ret)\n\n    return ret\n\n\nclass numeric_range(abc.Sequence, abc.Hashable):\n    \"\"\"An extension of the built-in ``range()`` function whose arguments can\n    be any orderable numeric type.\n\n    With only *stop* specified, *start* defaults to ``0`` and *step*\n    defaults to ``1``. The output items will match the type of *stop*:\n\n        >>> list(numeric_range(3.5))\n        [0.0, 1.0, 2.0, 3.0]\n\n    With only *start* and *stop* specified, *step* defaults to ``1``. The\n    output items will match the type of *start*:\n\n        >>> from decimal import Decimal\n        >>> start = Decimal('2.1')\n        >>> stop = Decimal('5.1')\n        >>> list(numeric_range(start, stop))\n        [Decimal('2.1'), Decimal('3.1'), Decimal('4.1')]\n\n    With *start*, *stop*, and *step*  specified the output items will match\n    the type of ``start + step``:\n\n        >>> from fractions import Fraction\n        >>> start = Fraction(1, 2)  # Start at 1/2\n        >>> stop = Fraction(5, 2)  # End at 5/2\n        >>> step = Fraction(1, 2)  # Count by 1/2\n        >>> list(numeric_range(start, stop, step))\n        [Fraction(1, 2), Fraction(1, 1), Fraction(3, 2), Fraction(2, 1)]\n\n    If *step* is zero, ``ValueError`` is raised. Negative steps are supported:\n\n        >>> list(numeric_range(3, -1, -1.0))\n        [3.0, 2.0, 1.0, 0.0]\n\n    Be aware of the limitations of floating point numbers; the representation\n    of the yielded numbers may be surprising.\n\n    ``datetime.datetime`` objects can be used for *start* and *stop*, if *step*\n    is a ``datetime.timedelta`` object:\n\n        >>> import datetime\n        >>> start = datetime.datetime(2019, 1, 1)\n        >>> stop = datetime.datetime(2019, 1, 3)\n        >>> step = datetime.timedelta(days=1)\n        >>> items = iter(numeric_range(start, stop, step))\n        >>> next(items)\n        datetime.datetime(2019, 1, 1, 0, 0)\n        >>> next(items)\n        datetime.datetime(2019, 1, 2, 0, 0)\n\n    \"\"\"\n\n    _EMPTY_HASH = hash(range(0, 0))\n\n    def __init__(self, *args):\n        argc = len(args)\n        if argc == 1:\n            (self._stop,) = args\n            self._start = type(self._stop)(0)\n            self._step = type(self._stop - self._start)(1)\n        elif argc == 2:\n            self._start, self._stop = args\n            self._step = type(self._stop - self._start)(1)\n        elif argc == 3:\n            self._start, self._stop, self._step = args\n        elif argc == 0:\n            raise TypeError(\n                'numeric_range expected at least '\n                '1 argument, got {}'.format(argc)\n            )\n        else:\n            raise TypeError(\n                'numeric_range expected at most '\n                '3 arguments, got {}'.format(argc)\n            )\n\n        self._zero = type(self._step)(0)\n        if self._step == self._zero:\n            raise ValueError('numeric_range() arg 3 must not be zero')\n        self._growing = self._step > self._zero\n        self._init_len()\n\n    def __bool__(self):\n        if self._growing:\n            return self._start < self._stop\n        else:\n            return self._start > self._stop\n\n    def __contains__(self, elem):\n        if self._growing:\n            if self._start <= elem < self._stop:\n                return (elem - self._start) % self._step == self._zero\n        else:\n            if self._start >= elem > self._stop:\n                return (self._start - elem) % (-self._step) == self._zero\n\n        return False\n\n    def __eq__(self, other):\n        if isinstance(other, numeric_range):\n            empty_self = not bool(self)\n            empty_other = not bool(other)\n            if empty_self or empty_other:\n                return empty_self and empty_other  # True if both empty\n            else:\n                return (\n                    self._start == other._start\n                    and self._step == other._step\n                    and self._get_by_index(-1) == other._get_by_index(-1)\n                )\n        else:\n            return False\n\n    def __getitem__(self, key):\n        if isinstance(key, int):\n            return self._get_by_index(key)\n        elif isinstance(key, slice):\n            step = self._step if key.step is None else key.step * self._step\n\n            if key.start is None or key.start <= -self._len:\n                start = self._start\n            elif key.start >= self._len:\n                start = self._stop\n            else:  # -self._len < key.start < self._len\n                start = self._get_by_index(key.start)\n\n            if key.stop is None or key.stop >= self._len:\n                stop = self._stop\n            elif key.stop <= -self._len:\n                stop = self._start\n            else:  # -self._len < key.stop < self._len\n                stop = self._get_by_index(key.stop)\n\n            return numeric_range(start, stop, step)\n        else:\n            raise TypeError(\n                'numeric range indices must be '\n                'integers or slices, not {}'.format(type(key).__name__)\n            )\n\n    def __hash__(self):\n        if self:\n            return hash((self._start, self._get_by_index(-1), self._step))\n        else:\n            return self._EMPTY_HASH\n\n    def __iter__(self):\n        values = (self._start + (n * self._step) for n in count())\n        if self._growing:\n            return takewhile(partial(gt, self._stop), values)\n        else:\n            return takewhile(partial(lt, self._stop), values)\n\n    def __len__(self):\n        return self._len\n\n    def _init_len(self):\n        if self._growing:\n            start = self._start\n            stop = self._stop\n            step = self._step\n        else:\n            start = self._stop\n            stop = self._start\n            step = -self._step\n        distance = stop - start\n        if distance <= self._zero:\n            self._len = 0\n        else:  # distance > 0 and step > 0: regular euclidean division\n            q, r = divmod(distance, step)\n            self._len = int(q) + int(r != self._zero)\n\n    def __reduce__(self):\n        return numeric_range, (self._start, self._stop, self._step)\n\n    def __repr__(self):\n        if self._step == 1:\n            return \"numeric_range({}, {})\".format(\n                repr(self._start), repr(self._stop)\n            )\n        else:\n            return \"numeric_range({}, {}, {})\".format(\n                repr(self._start), repr(self._stop), repr(self._step)\n            )\n\n    def __reversed__(self):\n        return iter(\n            numeric_range(\n                self._get_by_index(-1), self._start - self._step, -self._step\n            )\n        )\n\n    def count(self, value):\n        return int(value in self)\n\n    def index(self, value):\n        if self._growing:\n            if self._start <= value < self._stop:\n                q, r = divmod(value - self._start, self._step)\n                if r == self._zero:\n                    return int(q)\n        else:\n            if self._start >= value > self._stop:\n                q, r = divmod(self._start - value, -self._step)\n                if r == self._zero:\n                    return int(q)\n\n        raise ValueError(\"{} is not in numeric range\".format(value))\n\n    def _get_by_index(self, i):\n        if i < 0:\n            i += self._len\n        if i < 0 or i >= self._len:\n            raise IndexError(\"numeric range object index out of range\")\n        return self._start + i * self._step\n\n\ndef count_cycle(iterable, n=None):\n    \"\"\"Cycle through the items from *iterable* up to *n* times, yielding\n    the number of completed cycles along with each item. If *n* is omitted the\n    process repeats indefinitely.\n\n    >>> list(count_cycle('AB', 3))\n    [(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]\n\n    \"\"\"\n    iterable = tuple(iterable)\n    if not iterable:\n        return iter(())\n    counter = count() if n is None else range(n)\n    return ((i, item) for i in counter for item in iterable)\n\n\ndef mark_ends(iterable):\n    \"\"\"Yield 3-tuples of the form ``(is_first, is_last, item)``.\n\n    >>> list(mark_ends('ABC'))\n    [(True, False, 'A'), (False, False, 'B'), (False, True, 'C')]\n\n    Use this when looping over an iterable to take special action on its first\n    and/or last items:\n\n    >>> iterable = ['Header', 100, 200, 'Footer']\n    >>> total = 0\n    >>> for is_first, is_last, item in mark_ends(iterable):\n    ...     if is_first:\n    ...         continue  # Skip the header\n    ...     if is_last:\n    ...         continue  # Skip the footer\n    ...     total += item\n    >>> print(total)\n    300\n    \"\"\"\n    it = iter(iterable)\n\n    try:\n        b = next(it)\n    except StopIteration:\n        return\n\n    try:\n        for i in count():\n            a = b\n            b = next(it)\n            yield i == 0, False, a\n\n    except StopIteration:\n        yield i == 0, True, a\n\n\ndef locate(iterable, pred=bool, window_size=None):\n    \"\"\"Yield the index of each item in *iterable* for which *pred* returns\n    ``True``.\n\n    *pred* defaults to :func:`bool`, which will select truthy items:\n\n        >>> list(locate([0, 1, 1, 0, 1, 0, 0]))\n        [1, 2, 4]\n\n    Set *pred* to a custom function to, e.g., find the indexes for a particular\n    item.\n\n        >>> list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b'))\n        [1, 3]\n\n    If *window_size* is given, then the *pred* function will be called with\n    that many items. This enables searching for sub-sequences:\n\n        >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]\n        >>> pred = lambda *args: args == (1, 2, 3)\n        >>> list(locate(iterable, pred=pred, window_size=3))\n        [1, 5, 9]\n\n    Use with :func:`seekable` to find indexes and then retrieve the associated\n    items:\n\n        >>> from itertools import count\n        >>> from more_itertools import seekable\n        >>> source = (3 * n + 1 if (n % 2) else n // 2 for n in count())\n        >>> it = seekable(source)\n        >>> pred = lambda x: x > 100\n        >>> indexes = locate(it, pred=pred)\n        >>> i = next(indexes)\n        >>> it.seek(i)\n        >>> next(it)\n        106\n\n    \"\"\"\n    if window_size is None:\n        return compress(count(), map(pred, iterable))\n\n    if window_size < 1:\n        raise ValueError('window size must be at least 1')\n\n    it = windowed(iterable, window_size, fillvalue=_marker)\n    return compress(count(), starmap(pred, it))\n\n\ndef lstrip(iterable, pred):\n    \"\"\"Yield the items from *iterable*, but strip any from the beginning\n    for which *pred* returns ``True``.\n\n    For example, to remove a set of items from the start of an iterable:\n\n        >>> iterable = (None, False, None, 1, 2, None, 3, False, None)\n        >>> pred = lambda x: x in {None, False, ''}\n        >>> list(lstrip(iterable, pred))\n        [1, 2, None, 3, False, None]\n\n    This function is analogous to to :func:`str.lstrip`, and is essentially\n    an wrapper for :func:`itertools.dropwhile`.\n\n    \"\"\"\n    return dropwhile(pred, iterable)\n\n\ndef rstrip(iterable, pred):\n    \"\"\"Yield the items from *iterable*, but strip any from the end\n    for which *pred* returns ``True``.\n\n    For example, to remove a set of items from the end of an iterable:\n\n        >>> iterable = (None, False, None, 1, 2, None, 3, False, None)\n        >>> pred = lambda x: x in {None, False, ''}\n        >>> list(rstrip(iterable, pred))\n        [None, False, None, 1, 2, None, 3]\n\n    This function is analogous to :func:`str.rstrip`.\n\n    \"\"\"\n    cache = []\n    cache_append = cache.append\n    cache_clear = cache.clear\n    for x in iterable:\n        if pred(x):\n            cache_append(x)\n        else:\n            yield from cache\n            cache_clear()\n            yield x\n\n\ndef strip(iterable, pred):\n    \"\"\"Yield the items from *iterable*, but strip any from the\n    beginning and end for which *pred* returns ``True``.\n\n    For example, to remove a set of items from both ends of an iterable:\n\n        >>> iterable = (None, False, None, 1, 2, None, 3, False, None)\n        >>> pred = lambda x: x in {None, False, ''}\n        >>> list(strip(iterable, pred))\n        [1, 2, None, 3]\n\n    This function is analogous to :func:`str.strip`.\n\n    \"\"\"\n    return rstrip(lstrip(iterable, pred), pred)\n\n\nclass islice_extended:\n    \"\"\"An extension of :func:`itertools.islice` that supports negative values\n    for *stop*, *start*, and *step*.\n\n        >>> iterable = iter('abcdefgh')\n        >>> list(islice_extended(iterable, -4, -1))\n        ['e', 'f', 'g']\n\n    Slices with negative values require some caching of *iterable*, but this\n    function takes care to minimize the amount of memory required.\n\n    For example, you can use a negative step with an infinite iterator:\n\n        >>> from itertools import count\n        >>> list(islice_extended(count(), 110, 99, -2))\n        [110, 108, 106, 104, 102, 100]\n\n    You can also use slice notation directly:\n\n        >>> iterable = map(str, count())\n        >>> it = islice_extended(iterable)[10:20:2]\n        >>> list(it)\n        ['10', '12', '14', '16', '18']\n\n    \"\"\"\n\n    def __init__(self, iterable, *args):\n        it = iter(iterable)\n        if args:\n            self._iterable = _islice_helper(it, slice(*args))\n        else:\n            self._iterable = it\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        return next(self._iterable)\n\n    def __getitem__(self, key):\n        if isinstance(key, slice):\n            return islice_extended(_islice_helper(self._iterable, key))\n\n        raise TypeError('islice_extended.__getitem__ argument must be a slice')\n\n\ndef _islice_helper(it, s):\n    start = s.start\n    stop = s.stop\n    if s.step == 0:\n        raise ValueError('step argument must be a non-zero integer or None.')\n    step = s.step or 1\n\n    if step > 0:\n        start = 0 if (start is None) else start\n\n        if start < 0:\n            # Consume all but the last -start items\n            cache = deque(enumerate(it, 1), maxlen=-start)\n            len_iter = cache[-1][0] if cache else 0\n\n            # Adjust start to be positive\n            i = max(len_iter + start, 0)\n\n            # Adjust stop to be positive\n            if stop is None:\n                j = len_iter\n            elif stop >= 0:\n                j = min(stop, len_iter)\n            else:\n                j = max(len_iter + stop, 0)\n\n            # Slice the cache\n            n = j - i\n            if n <= 0:\n                return\n\n            for index, item in islice(cache, 0, n, step):\n                yield item\n        elif (stop is not None) and (stop < 0):\n            # Advance to the start position\n            next(islice(it, start, start), None)\n\n            # When stop is negative, we have to carry -stop items while\n            # iterating\n            cache = deque(islice(it, -stop), maxlen=-stop)\n\n            for index, item in enumerate(it):\n                cached_item = cache.popleft()\n                if index % step == 0:\n                    yield cached_item\n                cache.append(item)\n        else:\n            # When both start and stop are positive we have the normal case\n            yield from islice(it, start, stop, step)\n    else:\n        start = -1 if (start is None) else start\n\n        if (stop is not None) and (stop < 0):\n            # Consume all but the last items\n            n = -stop - 1\n            cache = deque(enumerate(it, 1), maxlen=n)\n            len_iter = cache[-1][0] if cache else 0\n\n            # If start and stop are both negative they are comparable and\n            # we can just slice. Otherwise we can adjust start to be negative\n            # and then slice.\n            if start < 0:\n                i, j = start, stop\n            else:\n                i, j = min(start - len_iter, -1), None\n\n            for index, item in list(cache)[i:j:step]:\n                yield item\n        else:\n            # Advance to the stop position\n            if stop is not None:\n                m = stop + 1\n                next(islice(it, m, m), None)\n\n            # stop is positive, so if start is negative they are not comparable\n            # and we need the rest of the items.\n            if start < 0:\n                i = start\n                n = None\n            # stop is None and start is positive, so we just need items up to\n            # the start index.\n            elif stop is None:\n                i = None\n                n = start + 1\n            # Both stop and start are positive, so they are comparable.\n            else:\n                i = None\n                n = start - stop\n                if n <= 0:\n                    return\n\n            cache = list(islice(it, n))\n\n            yield from cache[i::step]\n\n\ndef always_reversible(iterable):\n    \"\"\"An extension of :func:`reversed` that supports all iterables, not\n    just those which implement the ``Reversible`` or ``Sequence`` protocols.\n\n        >>> print(*always_reversible(x for x in range(3)))\n        2 1 0\n\n    If the iterable is already reversible, this function returns the\n    result of :func:`reversed()`. If the iterable is not reversible,\n    this function will cache the remaining items in the iterable and\n    yield them in reverse order, which may require significant storage.\n    \"\"\"\n    try:\n        return reversed(iterable)\n    except TypeError:\n        return reversed(list(iterable))\n\n\ndef consecutive_groups(iterable, ordering=lambda x: x):\n    \"\"\"Yield groups of consecutive items using :func:`itertools.groupby`.\n    The *ordering* function determines whether two items are adjacent by\n    returning their position.\n\n    By default, the ordering function is the identity function. This is\n    suitable for finding runs of numbers:\n\n        >>> iterable = [1, 10, 11, 12, 20, 30, 31, 32, 33, 40]\n        >>> for group in consecutive_groups(iterable):\n        ...     print(list(group))\n        [1]\n        [10, 11, 12]\n        [20]\n        [30, 31, 32, 33]\n        [40]\n\n    For finding runs of adjacent letters, try using the :meth:`index` method\n    of a string of letters:\n\n        >>> from string import ascii_lowercase\n        >>> iterable = 'abcdfgilmnop'\n        >>> ordering = ascii_lowercase.index\n        >>> for group in consecutive_groups(iterable, ordering):\n        ...     print(list(group))\n        ['a', 'b', 'c', 'd']\n        ['f', 'g']\n        ['i']\n        ['l', 'm', 'n', 'o', 'p']\n\n    Each group of consecutive items is an iterator that shares it source with\n    *iterable*. When an an output group is advanced, the previous group is\n    no longer available unless its elements are copied (e.g., into a ``list``).\n\n        >>> iterable = [1, 2, 11, 12, 21, 22]\n        >>> saved_groups = []\n        >>> for group in consecutive_groups(iterable):\n        ...     saved_groups.append(list(group))  # Copy group elements\n        >>> saved_groups\n        [[1, 2], [11, 12], [21, 22]]\n\n    \"\"\"\n    for k, g in groupby(\n        enumerate(iterable), key=lambda x: x[0] - ordering(x[1])\n    ):\n        yield map(itemgetter(1), g)\n\n\ndef difference(iterable, func=sub, *, initial=None):\n    \"\"\"This function is the inverse of :func:`itertools.accumulate`. By default\n    it will compute the first difference of *iterable* using\n    :func:`operator.sub`:\n\n        >>> from itertools import accumulate\n        >>> iterable = accumulate([0, 1, 2, 3, 4])  # produces 0, 1, 3, 6, 10\n        >>> list(difference(iterable))\n        [0, 1, 2, 3, 4]\n\n    *func* defaults to :func:`operator.sub`, but other functions can be\n    specified. They will be applied as follows::\n\n        A, B, C, D, ... --> A, func(B, A), func(C, B), func(D, C), ...\n\n    For example, to do progressive division:\n\n        >>> iterable = [1, 2, 6, 24, 120]\n        >>> func = lambda x, y: x // y\n        >>> list(difference(iterable, func))\n        [1, 2, 3, 4, 5]\n\n    If the *initial* keyword is set, the first element will be skipped when\n    computing successive differences.\n\n        >>> it = [10, 11, 13, 16]  # from accumulate([1, 2, 3], initial=10)\n        >>> list(difference(it, initial=10))\n        [1, 2, 3]\n\n    \"\"\"\n    a, b = tee(iterable)\n    try:\n        first = [next(b)]\n    except StopIteration:\n        return iter([])\n\n    if initial is not None:\n        first = []\n\n    return chain(first, starmap(func, zip(b, a)))\n\n\nclass SequenceView(Sequence):\n    \"\"\"Return a read-only view of the sequence object *target*.\n\n    :class:`SequenceView` objects are analogous to Python's built-in\n    \"dictionary view\" types. They provide a dynamic view of a sequence's items,\n    meaning that when the sequence updates, so does the view.\n\n        >>> seq = ['0', '1', '2']\n        >>> view = SequenceView(seq)\n        >>> view\n        SequenceView(['0', '1', '2'])\n        >>> seq.append('3')\n        >>> view\n        SequenceView(['0', '1', '2', '3'])\n\n    Sequence views support indexing, slicing, and length queries. They act\n    like the underlying sequence, except they don't allow assignment:\n\n        >>> view[1]\n        '1'\n        >>> view[1:-1]\n        ['1', '2']\n        >>> len(view)\n        4\n\n    Sequence views are useful as an alternative to copying, as they don't\n    require (much) extra storage.\n\n    \"\"\"\n\n    def __init__(self, target):\n        if not isinstance(target, Sequence):\n            raise TypeError\n        self._target = target\n\n    def __getitem__(self, index):\n        return self._target[index]\n\n    def __len__(self):\n        return len(self._target)\n\n    def __repr__(self):\n        return '{}({})'.format(self.__class__.__name__, repr(self._target))\n\n\nclass seekable:\n    \"\"\"Wrap an iterator to allow for seeking backward and forward. This\n    progressively caches the items in the source iterable so they can be\n    re-visited.\n\n    Call :meth:`seek` with an index to seek to that position in the source\n    iterable.\n\n    To \"reset\" an iterator, seek to ``0``:\n\n        >>> from itertools import count\n        >>> it = seekable((str(n) for n in count()))\n        >>> next(it), next(it), next(it)\n        ('0', '1', '2')\n        >>> it.seek(0)\n        >>> next(it), next(it), next(it)\n        ('0', '1', '2')\n        >>> next(it)\n        '3'\n\n    You can also seek forward:\n\n        >>> it = seekable((str(n) for n in range(20)))\n        >>> it.seek(10)\n        >>> next(it)\n        '10'\n        >>> it.seek(20)  # Seeking past the end of the source isn't a problem\n        >>> list(it)\n        []\n        >>> it.seek(0)  # Resetting works even after hitting the end\n        >>> next(it), next(it), next(it)\n        ('0', '1', '2')\n\n    Call :meth:`peek` to look ahead one item without advancing the iterator:\n\n        >>> it = seekable('1234')\n        >>> it.peek()\n        '1'\n        >>> list(it)\n        ['1', '2', '3', '4']\n        >>> it.peek(default='empty')\n        'empty'\n\n    Before the iterator is at its end, calling :func:`bool` on it will return\n    ``True``. After it will return ``False``:\n\n        >>> it = seekable('5678')\n        >>> bool(it)\n        True\n        >>> list(it)\n        ['5', '6', '7', '8']\n        >>> bool(it)\n        False\n\n    You may view the contents of the cache with the :meth:`elements` method.\n    That returns a :class:`SequenceView`, a view that updates automatically:\n\n        >>> it = seekable((str(n) for n in range(10)))\n        >>> next(it), next(it), next(it)\n        ('0', '1', '2')\n        >>> elements = it.elements()\n        >>> elements\n        SequenceView(['0', '1', '2'])\n        >>> next(it)\n        '3'\n        >>> elements\n        SequenceView(['0', '1', '2', '3'])\n\n    By default, the cache grows as the source iterable progresses, so beware of\n    wrapping very large or infinite iterables. Supply *maxlen* to limit the\n    size of the cache (this of course limits how far back you can seek).\n\n        >>> from itertools import count\n        >>> it = seekable((str(n) for n in count()), maxlen=2)\n        >>> next(it), next(it), next(it), next(it)\n        ('0', '1', '2', '3')\n        >>> list(it.elements())\n        ['2', '3']\n        >>> it.seek(0)\n        >>> next(it), next(it), next(it), next(it)\n        ('2', '3', '4', '5')\n        >>> next(it)\n        '6'\n\n    \"\"\"\n\n    def __init__(self, iterable, maxlen=None):\n        self._source = iter(iterable)\n        if maxlen is None:\n            self._cache = []\n        else:\n            self._cache = deque([], maxlen)\n        self._index = None\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        if self._index is not None:\n            try:\n                item = self._cache[self._index]\n            except IndexError:\n                self._index = None\n            else:\n                self._index += 1\n                return item\n\n        item = next(self._source)\n        self._cache.append(item)\n        return item\n\n    def __bool__(self):\n        try:\n            self.peek()\n        except StopIteration:\n            return False\n        return True\n\n    def peek(self, default=_marker):\n        try:\n            peeked = next(self)\n        except StopIteration:\n            if default is _marker:\n                raise\n            return default\n        if self._index is None:\n            self._index = len(self._cache)\n        self._index -= 1\n        return peeked\n\n    def elements(self):\n        return SequenceView(self._cache)\n\n    def seek(self, index):\n        self._index = index\n        remainder = index - len(self._cache)\n        if remainder > 0:\n            consume(self, remainder)\n\n\nclass run_length:\n    \"\"\"\n    :func:`run_length.encode` compresses an iterable with run-length encoding.\n    It yields groups of repeated items with the count of how many times they\n    were repeated:\n\n        >>> uncompressed = 'abbcccdddd'\n        >>> list(run_length.encode(uncompressed))\n        [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n\n    :func:`run_length.decode` decompresses an iterable that was previously\n    compressed with run-length encoding. It yields the items of the\n    decompressed iterable:\n\n        >>> compressed = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n        >>> list(run_length.decode(compressed))\n        ['a', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'd']\n\n    \"\"\"\n\n    @staticmethod\n    def encode(iterable):\n        return ((k, ilen(g)) for k, g in groupby(iterable))\n\n    @staticmethod\n    def decode(iterable):\n        return chain.from_iterable(repeat(k, n) for k, n in iterable)\n\n\ndef exactly_n(iterable, n, predicate=bool):\n    \"\"\"Return ``True`` if exactly ``n`` items in the iterable are ``True``\n    according to the *predicate* function.\n\n        >>> exactly_n([True, True, False], 2)\n        True\n        >>> exactly_n([True, True, False], 1)\n        False\n        >>> exactly_n([0, 1, 2, 3, 4, 5], 3, lambda x: x < 3)\n        True\n\n    The iterable will be advanced until ``n + 1`` truthy items are encountered,\n    so avoid calling it on infinite iterables.\n\n    \"\"\"\n    return len(take(n + 1, filter(predicate, iterable))) == n\n\n\ndef circular_shifts(iterable):\n    \"\"\"Return a list of circular shifts of *iterable*.\n\n    >>> circular_shifts(range(4))\n    [(0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2)]\n    \"\"\"\n    lst = list(iterable)\n    return take(len(lst), windowed(cycle(lst), len(lst)))\n\n\ndef make_decorator(wrapping_func, result_index=0):\n    \"\"\"Return a decorator version of *wrapping_func*, which is a function that\n    modifies an iterable. *result_index* is the position in that function's\n    signature where the iterable goes.\n\n    This lets you use itertools on the \"production end,\" i.e. at function\n    definition. This can augment what the function returns without changing the\n    function's code.\n\n    For example, to produce a decorator version of :func:`chunked`:\n\n        >>> from more_itertools import chunked\n        >>> chunker = make_decorator(chunked, result_index=0)\n        >>> @chunker(3)\n        ... def iter_range(n):\n        ...     return iter(range(n))\n        ...\n        >>> list(iter_range(9))\n        [[0, 1, 2], [3, 4, 5], [6, 7, 8]]\n\n    To only allow truthy items to be returned:\n\n        >>> truth_serum = make_decorator(filter, result_index=1)\n        >>> @truth_serum(bool)\n        ... def boolean_test():\n        ...     return [0, 1, '', ' ', False, True]\n        ...\n        >>> list(boolean_test())\n        [1, ' ', True]\n\n    The :func:`peekable` and :func:`seekable` wrappers make for practical\n    decorators:\n\n        >>> from more_itertools import peekable\n        >>> peekable_function = make_decorator(peekable)\n        >>> @peekable_function()\n        ... def str_range(*args):\n        ...     return (str(x) for x in range(*args))\n        ...\n        >>> it = str_range(1, 20, 2)\n        >>> next(it), next(it), next(it)\n        ('1', '3', '5')\n        >>> it.peek()\n        '7'\n        >>> next(it)\n        '7'\n\n    \"\"\"\n    # See https://sites.google.com/site/bbayles/index/decorator_factory for\n    # notes on how this works.\n    def decorator(*wrapping_args, **wrapping_kwargs):\n        def outer_wrapper(f):\n            def inner_wrapper(*args, **kwargs):\n                result = f(*args, **kwargs)\n                wrapping_args_ = list(wrapping_args)\n                wrapping_args_.insert(result_index, result)\n                return wrapping_func(*wrapping_args_, **wrapping_kwargs)\n\n            return inner_wrapper\n\n        return outer_wrapper\n\n    return decorator\n\n\ndef map_reduce(iterable, keyfunc, valuefunc=None, reducefunc=None):\n    \"\"\"Return a dictionary that maps the items in *iterable* to categories\n    defined by *keyfunc*, transforms them with *valuefunc*, and\n    then summarizes them by category with *reducefunc*.\n\n    *valuefunc* defaults to the identity function if it is unspecified.\n    If *reducefunc* is unspecified, no summarization takes place:\n\n        >>> keyfunc = lambda x: x.upper()\n        >>> result = map_reduce('abbccc', keyfunc)\n        >>> sorted(result.items())\n        [('A', ['a']), ('B', ['b', 'b']), ('C', ['c', 'c', 'c'])]\n\n    Specifying *valuefunc* transforms the categorized items:\n\n        >>> keyfunc = lambda x: x.upper()\n        >>> valuefunc = lambda x: 1\n        >>> result = map_reduce('abbccc', keyfunc, valuefunc)\n        >>> sorted(result.items())\n        [('A', [1]), ('B', [1, 1]), ('C', [1, 1, 1])]\n\n    Specifying *reducefunc* summarizes the categorized items:\n\n        >>> keyfunc = lambda x: x.upper()\n        >>> valuefunc = lambda x: 1\n        >>> reducefunc = sum\n        >>> result = map_reduce('abbccc', keyfunc, valuefunc, reducefunc)\n        >>> sorted(result.items())\n        [('A', 1), ('B', 2), ('C', 3)]\n\n    You may want to filter the input iterable before applying the map/reduce\n    procedure:\n\n        >>> all_items = range(30)\n        >>> items = [x for x in all_items if 10 <= x <= 20]  # Filter\n        >>> keyfunc = lambda x: x % 2  # Evens map to 0; odds to 1\n        >>> categories = map_reduce(items, keyfunc=keyfunc)\n        >>> sorted(categories.items())\n        [(0, [10, 12, 14, 16, 18, 20]), (1, [11, 13, 15, 17, 19])]\n        >>> summaries = map_reduce(items, keyfunc=keyfunc, reducefunc=sum)\n        >>> sorted(summaries.items())\n        [(0, 90), (1, 75)]\n\n    Note that all items in the iterable are gathered into a list before the\n    summarization step, which may require significant storage.\n\n    The returned object is a :obj:`collections.defaultdict` with the\n    ``default_factory`` set to ``None``, such that it behaves like a normal\n    dictionary.\n\n    \"\"\"\n    valuefunc = (lambda x: x) if (valuefunc is None) else valuefunc\n\n    ret = defaultdict(list)\n    for item in iterable:\n        key = keyfunc(item)\n        value = valuefunc(item)\n        ret[key].append(value)\n\n    if reducefunc is not None:\n        for key, value_list in ret.items():\n            ret[key] = reducefunc(value_list)\n\n    ret.default_factory = None\n    return ret\n\n\ndef rlocate(iterable, pred=bool, window_size=None):\n    \"\"\"Yield the index of each item in *iterable* for which *pred* returns\n    ``True``, starting from the right and moving left.\n\n    *pred* defaults to :func:`bool`, which will select truthy items:\n\n        >>> list(rlocate([0, 1, 1, 0, 1, 0, 0]))  # Truthy at 1, 2, and 4\n        [4, 2, 1]\n\n    Set *pred* to a custom function to, e.g., find the indexes for a particular\n    item:\n\n        >>> iterable = iter('abcb')\n        >>> pred = lambda x: x == 'b'\n        >>> list(rlocate(iterable, pred))\n        [3, 1]\n\n    If *window_size* is given, then the *pred* function will be called with\n    that many items. This enables searching for sub-sequences:\n\n        >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]\n        >>> pred = lambda *args: args == (1, 2, 3)\n        >>> list(rlocate(iterable, pred=pred, window_size=3))\n        [9, 5, 1]\n\n    Beware, this function won't return anything for infinite iterables.\n    If *iterable* is reversible, ``rlocate`` will reverse it and search from\n    the right. Otherwise, it will search from the left and return the results\n    in reverse order.\n\n    See :func:`locate` to for other example applications.\n\n    \"\"\"\n    if window_size is None:\n        try:\n            len_iter = len(iterable)\n            return (len_iter - i - 1 for i in locate(reversed(iterable), pred))\n        except TypeError:\n            pass\n\n    return reversed(list(locate(iterable, pred, window_size)))\n\n\ndef replace(iterable, pred, substitutes, count=None, window_size=1):\n    \"\"\"Yield the items from *iterable*, replacing the items for which *pred*\n    returns ``True`` with the items from the iterable *substitutes*.\n\n        >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1]\n        >>> pred = lambda x: x == 0\n        >>> substitutes = (2, 3)\n        >>> list(replace(iterable, pred, substitutes))\n        [1, 1, 2, 3, 1, 1, 2, 3, 1, 1]\n\n    If *count* is given, the number of replacements will be limited:\n\n        >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1, 0]\n        >>> pred = lambda x: x == 0\n        >>> substitutes = [None]\n        >>> list(replace(iterable, pred, substitutes, count=2))\n        [1, 1, None, 1, 1, None, 1, 1, 0]\n\n    Use *window_size* to control the number of items passed as arguments to\n    *pred*. This allows for locating and replacing subsequences.\n\n        >>> iterable = [0, 1, 2, 5, 0, 1, 2, 5]\n        >>> window_size = 3\n        >>> pred = lambda *args: args == (0, 1, 2)  # 3 items passed to pred\n        >>> substitutes = [3, 4] # Splice in these items\n        >>> list(replace(iterable, pred, substitutes, window_size=window_size))\n        [3, 4, 5, 3, 4, 5]\n\n    \"\"\"\n    if window_size < 1:\n        raise ValueError('window_size must be at least 1')\n\n    # Save the substitutes iterable, since it's used more than once\n    substitutes = tuple(substitutes)\n\n    # Add padding such that the number of windows matches the length of the\n    # iterable\n    it = chain(iterable, [_marker] * (window_size - 1))\n    windows = windowed(it, window_size)\n\n    n = 0\n    for w in windows:\n        # If the current window matches our predicate (and we haven't hit\n        # our maximum number of replacements), splice in the substitutes\n        # and then consume the following windows that overlap with this one.\n        # For example, if the iterable is (0, 1, 2, 3, 4...)\n        # and the window size is 2, we have (0, 1), (1, 2), (2, 3)...\n        # If the predicate matches on (0, 1), we need to zap (0, 1) and (1, 2)\n        if pred(*w):\n            if (count is None) or (n < count):\n                n += 1\n                yield from substitutes\n                consume(windows, window_size - 1)\n                continue\n\n        # If there was no match (or we've reached the replacement limit),\n        # yield the first item from the window.\n        if w and (w[0] is not _marker):\n            yield w[0]\n\n\ndef partitions(iterable):\n    \"\"\"Yield all possible order-preserving partitions of *iterable*.\n\n    >>> iterable = 'abc'\n    >>> for part in partitions(iterable):\n    ...     print([''.join(p) for p in part])\n    ['abc']\n    ['a', 'bc']\n    ['ab', 'c']\n    ['a', 'b', 'c']\n\n    This is unrelated to :func:`partition`.\n\n    \"\"\"\n    sequence = list(iterable)\n    n = len(sequence)\n    for i in powerset(range(1, n)):\n        yield [sequence[i:j] for i, j in zip((0,) + i, i + (n,))]\n\n\ndef set_partitions(iterable, k=None):\n    \"\"\"\n    Yield the set partitions of *iterable* into *k* parts. Set partitions are\n    not order-preserving.\n\n    >>> iterable = 'abc'\n    >>> for part in set_partitions(iterable, 2):\n    ...     print([''.join(p) for p in part])\n    ['a', 'bc']\n    ['ab', 'c']\n    ['b', 'ac']\n\n\n    If *k* is not given, every set partition is generated.\n\n    >>> iterable = 'abc'\n    >>> for part in set_partitions(iterable):\n    ...     print([''.join(p) for p in part])\n    ['abc']\n    ['a', 'bc']\n    ['ab', 'c']\n    ['b', 'ac']\n    ['a', 'b', 'c']\n\n    \"\"\"\n    L = list(iterable)\n    n = len(L)\n    if k is not None:\n        if k < 1:\n            raise ValueError(\n                \"Can't partition in a negative or zero number of groups\"\n            )\n        elif k > n:\n            return\n\n    def set_partitions_helper(L, k):\n        n = len(L)\n        if k == 1:\n            yield [L]\n        elif n == k:\n            yield [[s] for s in L]\n        else:\n            e, *M = L\n            for p in set_partitions_helper(M, k - 1):\n                yield [[e], *p]\n            for p in set_partitions_helper(M, k):\n                for i in range(len(p)):\n                    yield p[:i] + [[e] + p[i]] + p[i + 1 :]\n\n    if k is None:\n        for k in range(1, n + 1):\n            yield from set_partitions_helper(L, k)\n    else:\n        yield from set_partitions_helper(L, k)\n\n\nclass time_limited:\n    \"\"\"\n    Yield items from *iterable* until *limit_seconds* have passed.\n    If the time limit expires before all items have been yielded, the\n    ``timed_out`` parameter will be set to ``True``.\n\n    >>> from time import sleep\n    >>> def generator():\n    ...     yield 1\n    ...     yield 2\n    ...     sleep(0.2)\n    ...     yield 3\n    >>> iterable = time_limited(0.1, generator())\n    >>> list(iterable)\n    [1, 2]\n    >>> iterable.timed_out\n    True\n\n    Note that the time is checked before each item is yielded, and iteration\n    stops if  the time elapsed is greater than *limit_seconds*. If your time\n    limit is 1 second, but it takes 2 seconds to generate the first item from\n    the iterable, the function will run for 2 seconds and not yield anything.\n\n    \"\"\"\n\n    def __init__(self, limit_seconds, iterable):\n        if limit_seconds < 0:\n            raise ValueError('limit_seconds must be positive')\n        self.limit_seconds = limit_seconds\n        self._iterable = iter(iterable)\n        self._start_time = monotonic()\n        self.timed_out = False\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        item = next(self._iterable)\n        if monotonic() - self._start_time > self.limit_seconds:\n            self.timed_out = True\n            raise StopIteration\n\n        return item\n\n\ndef only(iterable, default=None, too_long=None):\n    \"\"\"If *iterable* has only one item, return it.\n    If it has zero items, return *default*.\n    If it has more than one item, raise the exception given by *too_long*,\n    which is ``ValueError`` by default.\n\n    >>> only([], default='missing')\n    'missing'\n    >>> only([1])\n    1\n    >>> only([1, 2])  # doctest: +IGNORE_EXCEPTION_DETAIL\n    Traceback (most recent call last):\n    ...\n    ValueError: Expected exactly one item in iterable, but got 1, 2,\n     and perhaps more.'\n    >>> only([1, 2], too_long=TypeError)  # doctest: +IGNORE_EXCEPTION_DETAIL\n    Traceback (most recent call last):\n    ...\n    TypeError\n\n    Note that :func:`only` attempts to advance *iterable* twice to ensure there\n    is only one item.  See :func:`spy` or :func:`peekable` to check\n    iterable contents less destructively.\n    \"\"\"\n    it = iter(iterable)\n    first_value = next(it, default)\n\n    try:\n        second_value = next(it)\n    except StopIteration:\n        pass\n    else:\n        msg = (\n            'Expected exactly one item in iterable, but got {!r}, {!r}, '\n            'and perhaps more.'.format(first_value, second_value)\n        )\n        raise too_long or ValueError(msg)\n\n    return first_value\n\n\ndef ichunked(iterable, n):\n    \"\"\"Break *iterable* into sub-iterables with *n* elements each.\n    :func:`ichunked` is like :func:`chunked`, but it yields iterables\n    instead of lists.\n\n    If the sub-iterables are read in order, the elements of *iterable*\n    won't be stored in memory.\n    If they are read out of order, :func:`itertools.tee` is used to cache\n    elements as necessary.\n\n    >>> from itertools import count\n    >>> all_chunks = ichunked(count(), 4)\n    >>> c_1, c_2, c_3 = next(all_chunks), next(all_chunks), next(all_chunks)\n    >>> list(c_2)  # c_1's elements have been cached; c_3's haven't been\n    [4, 5, 6, 7]\n    >>> list(c_1)\n    [0, 1, 2, 3]\n    >>> list(c_3)\n    [8, 9, 10, 11]\n\n    \"\"\"\n    source = iter(iterable)\n\n    while True:\n        # Check to see whether we're at the end of the source iterable\n        item = next(source, _marker)\n        if item is _marker:\n            return\n\n        # Clone the source and yield an n-length slice\n        source, it = tee(chain([item], source))\n        yield islice(it, n)\n\n        # Advance the source iterable\n        consume(source, n)\n\n\ndef distinct_combinations(iterable, r):\n    \"\"\"Yield the distinct combinations of *r* items taken from *iterable*.\n\n        >>> list(distinct_combinations([0, 0, 1], 2))\n        [(0, 0), (0, 1)]\n\n    Equivalent to ``set(combinations(iterable))``, except duplicates are not\n    generated and thrown away. For larger input sequences this is much more\n    efficient.\n\n    \"\"\"\n    if r < 0:\n        raise ValueError('r must be non-negative')\n    elif r == 0:\n        yield ()\n        return\n    pool = tuple(iterable)\n    generators = [unique_everseen(enumerate(pool), key=itemgetter(1))]\n    current_combo = [None] * r\n    level = 0\n    while generators:\n        try:\n            cur_idx, p = next(generators[-1])\n        except StopIteration:\n            generators.pop()\n            level -= 1\n            continue\n        current_combo[level] = p\n        if level + 1 == r:\n            yield tuple(current_combo)\n        else:\n            generators.append(\n                unique_everseen(\n                    enumerate(pool[cur_idx + 1 :], cur_idx + 1),\n                    key=itemgetter(1),\n                )\n            )\n            level += 1\n\n\ndef filter_except(validator, iterable, *exceptions):\n    \"\"\"Yield the items from *iterable* for which the *validator* function does\n    not raise one of the specified *exceptions*.\n\n    *validator* is called for each item in *iterable*.\n    It should be a function that accepts one argument and raises an exception\n    if that item is not valid.\n\n    >>> iterable = ['1', '2', 'three', '4', None]\n    >>> list(filter_except(int, iterable, ValueError, TypeError))\n    ['1', '2', '4']\n\n    If an exception other than one given by *exceptions* is raised by\n    *validator*, it is raised like normal.\n    \"\"\"\n    for item in iterable:\n        try:\n            validator(item)\n        except exceptions:\n            pass\n        else:\n            yield item\n\n\ndef map_except(function, iterable, *exceptions):\n    \"\"\"Transform each item from *iterable* with *function* and yield the\n    result, unless *function* raises one of the specified *exceptions*.\n\n    *function* is called to transform each item in *iterable*.\n    It should accept one argument.\n\n    >>> iterable = ['1', '2', 'three', '4', None]\n    >>> list(map_except(int, iterable, ValueError, TypeError))\n    [1, 2, 4]\n\n    If an exception other than one given by *exceptions* is raised by\n    *function*, it is raised like normal.\n    \"\"\"\n    for item in iterable:\n        try:\n            yield function(item)\n        except exceptions:\n            pass\n\n\ndef map_if(iterable, pred, func, func_else=lambda x: x):\n    \"\"\"Evaluate each item from *iterable* using *pred*. If the result is\n    equivalent to ``True``, transform the item with *func* and yield it.\n    Otherwise, transform the item with *func_else* and yield it.\n\n    *pred*, *func*, and *func_else* should each be functions that accept\n    one argument. By default, *func_else* is the identity function.\n\n    >>> from math import sqrt\n    >>> iterable = list(range(-5, 5))\n    >>> iterable\n    [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]\n    >>> list(map_if(iterable, lambda x: x > 3, lambda x: 'toobig'))\n    [-5, -4, -3, -2, -1, 0, 1, 2, 3, 'toobig']\n    >>> list(map_if(iterable, lambda x: x >= 0,\n    ... lambda x: f'{sqrt(x):.2f}', lambda x: None))\n    [None, None, None, None, None, '0.00', '1.00', '1.41', '1.73', '2.00']\n    \"\"\"\n    for item in iterable:\n        yield func(item) if pred(item) else func_else(item)\n\n\ndef _sample_unweighted(iterable, k):\n    # Implementation of \"Algorithm L\" from the 1994 paper by Kim-Hung Li:\n    # \"Reservoir-Sampling Algorithms of Time Complexity O(n(1+log(N/n)))\".\n\n    # Fill up the reservoir (collection of samples) with the first `k` samples\n    reservoir = take(k, iterable)\n\n    # Generate random number that's the largest in a sample of k U(0,1) numbers\n    # Largest order statistic: https://en.wikipedia.org/wiki/Order_statistic\n    W = exp(log(random()) / k)\n\n    # The number of elements to skip before changing the reservoir is a random\n    # number with a geometric distribution. Sample it using random() and logs.\n    next_index = k + floor(log(random()) / log(1 - W))\n\n    for index, element in enumerate(iterable, k):\n\n        if index == next_index:\n            reservoir[randrange(k)] = element\n            # The new W is the largest in a sample of k U(0, `old_W`) numbers\n            W *= exp(log(random()) / k)\n            next_index += floor(log(random()) / log(1 - W)) + 1\n\n    return reservoir\n\n\ndef _sample_weighted(iterable, k, weights):\n    # Implementation of \"A-ExpJ\" from the 2006 paper by Efraimidis et al. :\n    # \"Weighted random sampling with a reservoir\".\n\n    # Log-transform for numerical stability for weights that are small/large\n    weight_keys = (log(random()) / weight for weight in weights)\n\n    # Fill up the reservoir (collection of samples) with the first `k`\n    # weight-keys and elements, then heapify the list.\n    reservoir = take(k, zip(weight_keys, iterable))\n    heapify(reservoir)\n\n    # The number of jumps before changing the reservoir is a random variable\n    # with an exponential distribution. Sample it using random() and logs.\n    smallest_weight_key, _ = reservoir[0]\n    weights_to_skip = log(random()) / smallest_weight_key\n\n    for weight, element in zip(weights, iterable):\n        if weight >= weights_to_skip:\n            # The notation here is consistent with the paper, but we store\n            # the weight-keys in log-space for better numerical stability.\n            smallest_weight_key, _ = reservoir[0]\n            t_w = exp(weight * smallest_weight_key)\n            r_2 = uniform(t_w, 1)  # generate U(t_w, 1)\n            weight_key = log(r_2) / weight\n            heapreplace(reservoir, (weight_key, element))\n            smallest_weight_key, _ = reservoir[0]\n            weights_to_skip = log(random()) / smallest_weight_key\n        else:\n            weights_to_skip -= weight\n\n    # Equivalent to [element for weight_key, element in sorted(reservoir)]\n    return [heappop(reservoir)[1] for _ in range(k)]\n\n\ndef sample(iterable, k, weights=None):\n    \"\"\"Return a *k*-length list of elements chosen (without replacement)\n    from the *iterable*. Like :func:`random.sample`, but works on iterables\n    of unknown length.\n\n    >>> iterable = range(100)\n    >>> sample(iterable, 5)  # doctest: +SKIP\n    [81, 60, 96, 16, 4]\n\n    An iterable with *weights* may also be given:\n\n    >>> iterable = range(100)\n    >>> weights = (i * i + 1 for i in range(100))\n    >>> sampled = sample(iterable, 5, weights=weights)  # doctest: +SKIP\n    [79, 67, 74, 66, 78]\n\n    The algorithm can also be used to generate weighted random permutations.\n    The relative weight of each item determines the probability that it\n    appears late in the permutation.\n\n    >>> data = \"abcdefgh\"\n    >>> weights = range(1, len(data) + 1)\n    >>> sample(data, k=len(data), weights=weights)  # doctest: +SKIP\n    ['c', 'a', 'b', 'e', 'g', 'd', 'h', 'f']\n    \"\"\"\n    if k == 0:\n        return []\n\n    iterable = iter(iterable)\n    if weights is None:\n        return _sample_unweighted(iterable, k)\n    else:\n        weights = iter(weights)\n        return _sample_weighted(iterable, k, weights)\n\n\ndef is_sorted(iterable, key=None, reverse=False, strict=False):\n    \"\"\"Returns ``True`` if the items of iterable are in sorted order, and\n    ``False`` otherwise. *key* and *reverse* have the same meaning that they do\n    in the built-in :func:`sorted` function.\n\n    >>> is_sorted(['1', '2', '3', '4', '5'], key=int)\n    True\n    >>> is_sorted([5, 4, 3, 1, 2], reverse=True)\n    False\n\n    If *strict*, tests for strict sorting, that is, returns ``False`` if equal\n    elements are found:\n\n    >>> is_sorted([1, 2, 2])\n    True\n    >>> is_sorted([1, 2, 2], strict=True)\n    False\n\n    The function returns ``False`` after encountering the first out-of-order\n    item. If there are no out-of-order items, the iterable is exhausted.\n    \"\"\"\n\n    compare = (le if reverse else ge) if strict else (lt if reverse else gt)\n    it = iterable if key is None else map(key, iterable)\n    return not any(starmap(compare, pairwise(it)))\n\n\nclass AbortThread(BaseException):\n    pass\n\n\nclass callback_iter:\n    \"\"\"Convert a function that uses callbacks to an iterator.\n\n    Let *func* be a function that takes a `callback` keyword argument.\n    For example:\n\n    >>> def func(callback=None):\n    ...     for i, c in [(1, 'a'), (2, 'b'), (3, 'c')]:\n    ...         if callback:\n    ...             callback(i, c)\n    ...     return 4\n\n\n    Use ``with callback_iter(func)`` to get an iterator over the parameters\n    that are delivered to the callback.\n\n    >>> with callback_iter(func) as it:\n    ...     for args, kwargs in it:\n    ...         print(args)\n    (1, 'a')\n    (2, 'b')\n    (3, 'c')\n\n    The function will be called in a background thread. The ``done`` property\n    indicates whether it has completed execution.\n\n    >>> it.done\n    True\n\n    If it completes successfully, its return value will be available\n    in the ``result`` property.\n\n    >>> it.result\n    4\n\n    Notes:\n\n    * If the function uses some keyword argument besides ``callback``, supply\n      *callback_kwd*.\n    * If it finished executing, but raised an exception, accessing the\n      ``result`` property will raise the same exception.\n    * If it hasn't finished executing, accessing the ``result``\n      property from within the ``with`` block will raise ``RuntimeError``.\n    * If it hasn't finished executing, accessing the ``result`` property from\n      outside the ``with`` block will raise a\n      ``more_itertools.AbortThread`` exception.\n    * Provide *wait_seconds* to adjust how frequently the it is polled for\n      output.\n\n    \"\"\"\n\n    def __init__(self, func, callback_kwd='callback', wait_seconds=0.1):\n        self._func = func\n        self._callback_kwd = callback_kwd\n        self._aborted = False\n        self._future = None\n        self._wait_seconds = wait_seconds\n        self._executor = __import__(\"concurrent.futures\").futures.ThreadPoolExecutor(max_workers=1)\n        self._iterator = self._reader()\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        self._aborted = True\n        self._executor.shutdown()\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        return next(self._iterator)\n\n    @property\n    def done(self):\n        if self._future is None:\n            return False\n        return self._future.done()\n\n    @property\n    def result(self):\n        if not self.done:\n            raise RuntimeError('Function has not yet completed')\n\n        return self._future.result()\n\n    def _reader(self):\n        q = Queue()\n\n        def callback(*args, **kwargs):\n            if self._aborted:\n                raise AbortThread('canceled by user')\n\n            q.put((args, kwargs))\n\n        self._future = self._executor.submit(\n            self._func, **{self._callback_kwd: callback}\n        )\n\n        while True:\n            try:\n                item = q.get(timeout=self._wait_seconds)\n            except Empty:\n                pass\n            else:\n                q.task_done()\n                yield item\n\n            if self._future.done():\n                break\n\n        remaining = []\n        while True:\n            try:\n                item = q.get_nowait()\n            except Empty:\n                break\n            else:\n                q.task_done()\n                remaining.append(item)\n        q.join()\n        yield from remaining\n\n\ndef windowed_complete(iterable, n):\n    \"\"\"\n    Yield ``(beginning, middle, end)`` tuples, where:\n\n    * Each ``middle`` has *n* items from *iterable*\n    * Each ``beginning`` has the items before the ones in ``middle``\n    * Each ``end`` has the items after the ones in ``middle``\n\n    >>> iterable = range(7)\n    >>> n = 3\n    >>> for beginning, middle, end in windowed_complete(iterable, n):\n    ...     print(beginning, middle, end)\n    () (0, 1, 2) (3, 4, 5, 6)\n    (0,) (1, 2, 3) (4, 5, 6)\n    (0, 1) (2, 3, 4) (5, 6)\n    (0, 1, 2) (3, 4, 5) (6,)\n    (0, 1, 2, 3) (4, 5, 6) ()\n\n    Note that *n* must be at least 0 and most equal to the length of\n    *iterable*.\n\n    This function will exhaust the iterable and may require significant\n    storage.\n    \"\"\"\n    if n < 0:\n        raise ValueError('n must be >= 0')\n\n    seq = tuple(iterable)\n    size = len(seq)\n\n    if n > size:\n        raise ValueError('n must be <= len(seq)')\n\n    for i in range(size - n + 1):\n        beginning = seq[:i]\n        middle = seq[i : i + n]\n        end = seq[i + n :]\n        yield beginning, middle, end\n\n\ndef all_unique(iterable, key=None):\n    \"\"\"\n    Returns ``True`` if all the elements of *iterable* are unique (no two\n    elements are equal).\n\n        >>> all_unique('ABCB')\n        False\n\n    If a *key* function is specified, it will be used to make comparisons.\n\n        >>> all_unique('ABCb')\n        True\n        >>> all_unique('ABCb', str.lower)\n        False\n\n    The function returns as soon as the first non-unique element is\n    encountered. Iterables with a mix of hashable and unhashable items can\n    be used, but the function will be slower for unhashable items.\n    \"\"\"\n    seenset = set()\n    seenset_add = seenset.add\n    seenlist = []\n    seenlist_add = seenlist.append\n    for element in map(key, iterable) if key else iterable:\n        try:\n            if element in seenset:\n                return False\n            seenset_add(element)\n        except TypeError:\n            if element in seenlist:\n                return False\n            seenlist_add(element)\n    return True\n\n\ndef nth_product(index, *args):\n    \"\"\"Equivalent to ``list(product(*args))[index]``.\n\n    The products of *args* can be ordered lexicographically.\n    :func:`nth_product` computes the product at sort position *index* without\n    computing the previous products.\n\n        >>> nth_product(8, range(2), range(2), range(2), range(2))\n        (1, 0, 0, 0)\n\n    ``IndexError`` will be raised if the given *index* is invalid.\n    \"\"\"\n    pools = list(map(tuple, reversed(args)))\n    ns = list(map(len, pools))\n\n    c = reduce(mul, ns)\n\n    if index < 0:\n        index += c\n\n    if not 0 <= index < c:\n        raise IndexError\n\n    result = []\n    for pool, n in zip(pools, ns):\n        result.append(pool[index % n])\n        index //= n\n\n    return tuple(reversed(result))\n\n\ndef nth_permutation(iterable, r, index):\n    \"\"\"Equivalent to ``list(permutations(iterable, r))[index]```\n\n    The subsequences of *iterable* that are of length *r* where order is\n    important can be ordered lexicographically. :func:`nth_permutation`\n    computes the subsequence at sort position *index* directly, without\n    computing the previous subsequences.\n\n        >>> nth_permutation('ghijk', 2, 5)\n        ('h', 'i')\n\n    ``ValueError`` will be raised If *r* is negative or greater than the length\n    of *iterable*.\n    ``IndexError`` will be raised if the given *index* is invalid.\n    \"\"\"\n    pool = list(iterable)\n    n = len(pool)\n\n    if r is None or r == n:\n        r, c = n, factorial(n)\n    elif not 0 <= r < n:\n        raise ValueError\n    else:\n        c = factorial(n) // factorial(n - r)\n\n    if index < 0:\n        index += c\n\n    if not 0 <= index < c:\n        raise IndexError\n\n    if c == 0:\n        return tuple()\n\n    result = [0] * r\n    q = index * factorial(n) // c if r < n else index\n    for d in range(1, n + 1):\n        q, i = divmod(q, d)\n        if 0 <= n - d < r:\n            result[n - d] = i\n        if q == 0:\n            break\n\n    return tuple(map(pool.pop, result))\n\n\ndef value_chain(*args):\n    \"\"\"Yield all arguments passed to the function in the same order in which\n    they were passed. If an argument itself is iterable then iterate over its\n    values.\n\n        >>> list(value_chain(1, 2, 3, [4, 5, 6]))\n        [1, 2, 3, 4, 5, 6]\n\n    Binary and text strings are not considered iterable and are emitted\n    as-is:\n\n        >>> list(value_chain('12', '34', ['56', '78']))\n        ['12', '34', '56', '78']\n\n\n    Multiple levels of nesting are not flattened.\n\n    \"\"\"\n    for value in args:\n        if isinstance(value, (str, bytes)):\n            yield value\n            continue\n        try:\n            yield from value\n        except TypeError:\n            yield value\n\n\ndef product_index(element, *args):\n    \"\"\"Equivalent to ``list(product(*args)).index(element)``\n\n    The products of *args* can be ordered lexicographically.\n    :func:`product_index` computes the first index of *element* without\n    computing the previous products.\n\n        >>> product_index([8, 2], range(10), range(5))\n        42\n\n    ``ValueError`` will be raised if the given *element* isn't in the product\n    of *args*.\n    \"\"\"\n    index = 0\n\n    for x, pool in zip_longest(element, args, fillvalue=_marker):\n        if x is _marker or pool is _marker:\n            raise ValueError('element is not a product of args')\n\n        pool = tuple(pool)\n        index = index * len(pool) + pool.index(x)\n\n    return index\n\n\ndef combination_index(element, iterable):\n    \"\"\"Equivalent to ``list(combinations(iterable, r)).index(element)``\n\n    The subsequences of *iterable* that are of length *r* can be ordered\n    lexicographically. :func:`combination_index` computes the index of the\n    first *element*, without computing the previous combinations.\n\n        >>> combination_index('adf', 'abcdefg')\n        10\n\n    ``ValueError`` will be raised if the given *element* isn't one of the\n    combinations of *iterable*.\n    \"\"\"\n    element = enumerate(element)\n    k, y = next(element, (None, None))\n    if k is None:\n        return 0\n\n    indexes = []\n    pool = enumerate(iterable)\n    for n, x in pool:\n        if x == y:\n            indexes.append(n)\n            tmp, y = next(element, (None, None))\n            if tmp is None:\n                break\n            else:\n                k = tmp\n    else:\n        raise ValueError('element is not a combination of iterable')\n\n    n, _ = last(pool, default=(n, None))\n\n    # Python versiosn below 3.8 don't have math.comb\n    index = 1\n    for i, j in enumerate(reversed(indexes), start=1):\n        j = n - j\n        if i <= j:\n            index += factorial(j) // (factorial(i) * factorial(j - i))\n\n    return factorial(n + 1) // (factorial(k + 1) * factorial(n - k)) - index\n\n\ndef permutation_index(element, iterable):\n    \"\"\"Equivalent to ``list(permutations(iterable, r)).index(element)```\n\n    The subsequences of *iterable* that are of length *r* where order is\n    important can be ordered lexicographically. :func:`permutation_index`\n    computes the index of the first *element* directly, without computing\n    the previous permutations.\n\n        >>> permutation_index([1, 3, 2], range(5))\n        19\n\n    ``ValueError`` will be raised if the given *element* isn't one of the\n    permutations of *iterable*.\n    \"\"\"\n    index = 0\n    pool = list(iterable)\n    for i, x in zip(range(len(pool), -1, -1), element):\n        r = pool.index(x)\n        index = index * i + r\n        del pool[r]\n\n    return index\n\n\nclass countable:\n    \"\"\"Wrap *iterable* and keep a count of how many items have been consumed.\n\n    The ``items_seen`` attribute starts at ``0`` and increments as the iterable\n    is consumed:\n\n        >>> iterable = map(str, range(10))\n        >>> it = countable(iterable)\n        >>> it.items_seen\n        0\n        >>> next(it), next(it)\n        ('0', '1')\n        >>> list(it)\n        ['2', '3', '4', '5', '6', '7', '8', '9']\n        >>> it.items_seen\n        10\n    \"\"\"\n\n    def __init__(self, iterable):\n        self._it = iter(iterable)\n        self.items_seen = 0\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        item = next(self._it)\n        self.items_seen += 1\n\n        return item\n\n\ndef chunked_even(iterable, n):\n    \"\"\"Break *iterable* into lists of approximately length *n*.\n    Items are distributed such the lengths of the lists differ by at most\n    1 item.\n\n    >>> iterable = [1, 2, 3, 4, 5, 6, 7]\n    >>> n = 3\n    >>> list(chunked_even(iterable, n))  # List lengths: 3, 2, 2\n    [[1, 2, 3], [4, 5], [6, 7]]\n    >>> list(chunked(iterable, n))  # List lengths: 3, 3, 1\n    [[1, 2, 3], [4, 5, 6], [7]]\n\n    \"\"\"\n\n    len_method = getattr(iterable, '__len__', None)\n\n    if len_method is None:\n        return _chunked_even_online(iterable, n)\n    else:\n        return _chunked_even_finite(iterable, len_method(), n)\n\n\ndef _chunked_even_online(iterable, n):\n    buffer = []\n    maxbuf = n + (n - 2) * (n - 1)\n    for x in iterable:\n        buffer.append(x)\n        if len(buffer) == maxbuf:\n            yield buffer[:n]\n            buffer = buffer[n:]\n    yield from _chunked_even_finite(buffer, len(buffer), n)\n\n\ndef _chunked_even_finite(iterable, N, n):\n    if N < 1:\n        return\n\n    # Lists are either size `full_size <= n` or `partial_size = full_size - 1`\n    q, r = divmod(N, n)\n    num_lists = q + (1 if r > 0 else 0)\n    q, r = divmod(N, num_lists)\n    full_size = q + (1 if r > 0 else 0)\n    partial_size = full_size - 1\n    num_full = N - partial_size * num_lists\n    num_partial = num_lists - num_full\n\n    buffer = []\n    iterator = iter(iterable)\n\n    # Yield num_full lists of full_size\n    for x in iterator:\n        buffer.append(x)\n        if len(buffer) == full_size:\n            yield buffer\n            buffer = []\n            num_full -= 1\n            if num_full <= 0:\n                break\n\n    # Yield num_partial lists of partial_size\n    for x in iterator:\n        buffer.append(x)\n        if len(buffer) == partial_size:\n            yield buffer\n            buffer = []\n            num_partial -= 1\n\n\ndef zip_broadcast(*objects, scalar_types=(str, bytes), strict=False):\n    \"\"\"A version of :func:`zip` that \"broadcasts\" any scalar\n    (i.e., non-iterable) items into output tuples.\n\n    >>> iterable_1 = [1, 2, 3]\n    >>> iterable_2 = ['a', 'b', 'c']\n    >>> scalar = '_'\n    >>> list(zip_broadcast(iterable_1, iterable_2, scalar))\n    [(1, 'a', '_'), (2, 'b', '_'), (3, 'c', '_')]\n\n    The *scalar_types* keyword argument determines what types are considered\n    scalar. It is set to ``(str, bytes)`` by default. Set it to ``None`` to\n    treat strings and byte strings as iterable:\n\n    >>> list(zip_broadcast('abc', 0, 'xyz', scalar_types=None))\n    [('a', 0, 'x'), ('b', 0, 'y'), ('c', 0, 'z')]\n\n    If the *strict* keyword argument is ``True``, then\n    ``UnequalIterablesError`` will be raised if any of the iterables have\n    different lengthss.\n    \"\"\"\n\n    def is_scalar(obj):\n        if scalar_types and isinstance(obj, scalar_types):\n            return True\n        try:\n            iter(obj)\n        except TypeError:\n            return True\n        else:\n            return False\n\n    size = len(objects)\n    if not size:\n        return\n\n    iterables, iterable_positions = [], []\n    scalars, scalar_positions = [], []\n    for i, obj in enumerate(objects):\n        if is_scalar(obj):\n            scalars.append(obj)\n            scalar_positions.append(i)\n        else:\n            iterables.append(iter(obj))\n            iterable_positions.append(i)\n\n    if len(scalars) == size:\n        yield tuple(objects)\n        return\n\n    zipper = _zip_equal if strict else zip\n    for item in zipper(*iterables):\n        new_item = [None] * size\n\n        for i, elem in zip(iterable_positions, item):\n            new_item[i] = elem\n\n        for i, elem in zip(scalar_positions, scalars):\n            new_item[i] = elem\n\n        yield tuple(new_item)\n\n\ndef unique_in_window(iterable, n, key=None):\n    \"\"\"Yield the items from *iterable* that haven't been seen recently.\n    *n* is the size of the lookback window.\n\n        >>> iterable = [0, 1, 0, 2, 3, 0]\n        >>> n = 3\n        >>> list(unique_in_window(iterable, n))\n        [0, 1, 2, 3, 0]\n\n    The *key* function, if provided, will be used to determine uniqueness:\n\n        >>> list(unique_in_window('abAcda', 3, key=lambda x: x.lower()))\n        ['a', 'b', 'c', 'd', 'a']\n\n    The items in *iterable* must be hashable.\n\n    \"\"\"\n    if n <= 0:\n        raise ValueError('n must be greater than 0')\n\n    window = deque(maxlen=n)\n    uniques = set()\n    use_key = key is not None\n\n    for item in iterable:\n        k = key(item) if use_key else item\n        if k in uniques:\n            continue\n\n        if len(uniques) == n:\n            uniques.discard(window[0])\n\n        uniques.add(k)\n        window.append(k)\n\n        yield item\n\n\ndef duplicates_everseen(iterable, key=None):\n    \"\"\"Yield duplicate elements after their first appearance.\n\n    >>> list(duplicates_everseen('mississippi'))\n    ['s', 'i', 's', 's', 'i', 'p', 'i']\n    >>> list(duplicates_everseen('AaaBbbCccAaa', str.lower))\n    ['a', 'a', 'b', 'b', 'c', 'c', 'A', 'a', 'a']\n\n    This function is analagous to :func:`unique_everseen` and is subject to\n    the same performance considerations.\n\n    \"\"\"\n    seen_set = set()\n    seen_list = []\n    use_key = key is not None\n\n    for element in iterable:\n        k = key(element) if use_key else element\n        try:\n            if k not in seen_set:\n                seen_set.add(k)\n            else:\n                yield element\n        except TypeError:\n            if k not in seen_list:\n                seen_list.append(k)\n            else:\n                yield element\n\n\ndef duplicates_justseen(iterable, key=None):\n    \"\"\"Yields serially-duplicate elements after their first appearance.\n\n    >>> list(duplicates_justseen('mississippi'))\n    ['s', 's', 'p']\n    >>> list(duplicates_justseen('AaaBbbCccAaa', str.lower))\n    ['a', 'a', 'b', 'b', 'c', 'c', 'a', 'a']\n\n    This function is analagous to :func:`unique_justseen`.\n\n    \"\"\"\n    return flatten(\n        map(\n            lambda group_tuple: islice_extended(group_tuple[1])[1:],\n            groupby(iterable, key),\n        )\n    )\n\n\ndef minmax(iterable_or_value, *others, key=None, default=_marker):\n    \"\"\"Returns both the smallest and largest items in an iterable\n    or the largest of two or more arguments.\n\n        >>> minmax([3, 1, 5])\n        (1, 5)\n\n        >>> minmax(4, 2, 6)\n        (2, 6)\n\n    If a *key* function is provided, it will be used to transform the input\n    items for comparison.\n\n        >>> minmax([5, 30], key=str)  # '30' sorts before '5'\n        (30, 5)\n\n    If a *default* value is provided, it will be returned if there are no\n    input items.\n\n        >>> minmax([], default=(0, 0))\n        (0, 0)\n\n    Otherwise ``ValueError`` is raised.\n\n    This function is based on the\n    `recipe <http://code.activestate.com/recipes/577916/>`__ by\n    Raymond Hettinger and takes care to minimize the number of comparisons\n    performed.\n    \"\"\"\n    iterable = (iterable_or_value, *others) if others else iterable_or_value\n\n    it = iter(iterable)\n\n    try:\n        lo = hi = next(it)\n    except StopIteration as e:\n        if default is _marker:\n            raise ValueError(\n                '`minmax()` argument is an empty iterable. '\n                'Provide a `default` value to suppress this error.'\n            ) from e\n        return default\n\n    # Different branches depending on the presence of key. This saves a lot\n    # of unimportant copies which would slow the \"key=None\" branch\n    # significantly down.\n    if key is None:\n        for x, y in zip_longest(it, it, fillvalue=lo):\n            if y < x:\n                x, y = y, x\n            if x < lo:\n                lo = x\n            if hi < y:\n                hi = y\n\n    else:\n        lo_key = hi_key = key(lo)\n\n        for x, y in zip_longest(it, it, fillvalue=lo):\n\n            x_key, y_key = key(x), key(y)\n\n            if y_key < x_key:\n                x, y, x_key, y_key = y, x, y_key, x_key\n            if x_key < lo_key:\n                lo, lo_key = x, x_key\n            if hi_key < y_key:\n                hi, hi_key = y, y_key\n\n    return lo, hi\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/more_itertools/recipes.py",
    "content": "\"\"\"Imported from the recipes section of the itertools documentation.\n\nAll functions taken from the recipes section of the itertools library docs\n[1]_.\nSome backward-compatible usability improvements have been made.\n\n.. [1] http://docs.python.org/library/itertools.html#recipes\n\n\"\"\"\nimport warnings\nfrom collections import deque\nfrom itertools import (\n    chain,\n    combinations,\n    count,\n    cycle,\n    groupby,\n    islice,\n    repeat,\n    starmap,\n    tee,\n    zip_longest,\n)\nimport operator\nfrom random import randrange, sample, choice\n\n__all__ = [\n    'all_equal',\n    'before_and_after',\n    'consume',\n    'convolve',\n    'dotproduct',\n    'first_true',\n    'flatten',\n    'grouper',\n    'iter_except',\n    'ncycles',\n    'nth',\n    'nth_combination',\n    'padnone',\n    'pad_none',\n    'pairwise',\n    'partition',\n    'powerset',\n    'prepend',\n    'quantify',\n    'random_combination_with_replacement',\n    'random_combination',\n    'random_permutation',\n    'random_product',\n    'repeatfunc',\n    'roundrobin',\n    'sliding_window',\n    'tabulate',\n    'tail',\n    'take',\n    'triplewise',\n    'unique_everseen',\n    'unique_justseen',\n]\n\n\ndef take(n, iterable):\n    \"\"\"Return first *n* items of the iterable as a list.\n\n        >>> take(3, range(10))\n        [0, 1, 2]\n\n    If there are fewer than *n* items in the iterable, all of them are\n    returned.\n\n        >>> take(10, range(3))\n        [0, 1, 2]\n\n    \"\"\"\n    return list(islice(iterable, n))\n\n\ndef tabulate(function, start=0):\n    \"\"\"Return an iterator over the results of ``func(start)``,\n    ``func(start + 1)``, ``func(start + 2)``...\n\n    *func* should be a function that accepts one integer argument.\n\n    If *start* is not specified it defaults to 0. It will be incremented each\n    time the iterator is advanced.\n\n        >>> square = lambda x: x ** 2\n        >>> iterator = tabulate(square, -3)\n        >>> take(4, iterator)\n        [9, 4, 1, 0]\n\n    \"\"\"\n    return map(function, count(start))\n\n\ndef tail(n, iterable):\n    \"\"\"Return an iterator over the last *n* items of *iterable*.\n\n    >>> t = tail(3, 'ABCDEFG')\n    >>> list(t)\n    ['E', 'F', 'G']\n\n    \"\"\"\n    return iter(deque(iterable, maxlen=n))\n\n\ndef consume(iterator, n=None):\n    \"\"\"Advance *iterable* by *n* steps. If *n* is ``None``, consume it\n    entirely.\n\n    Efficiently exhausts an iterator without returning values. Defaults to\n    consuming the whole iterator, but an optional second argument may be\n    provided to limit consumption.\n\n        >>> i = (x for x in range(10))\n        >>> next(i)\n        0\n        >>> consume(i, 3)\n        >>> next(i)\n        4\n        >>> consume(i)\n        >>> next(i)\n        Traceback (most recent call last):\n          File \"<stdin>\", line 1, in <module>\n        StopIteration\n\n    If the iterator has fewer items remaining than the provided limit, the\n    whole iterator will be consumed.\n\n        >>> i = (x for x in range(3))\n        >>> consume(i, 5)\n        >>> next(i)\n        Traceback (most recent call last):\n          File \"<stdin>\", line 1, in <module>\n        StopIteration\n\n    \"\"\"\n    # Use functions that consume iterators at C speed.\n    if n is None:\n        # feed the entire iterator into a zero-length deque\n        deque(iterator, maxlen=0)\n    else:\n        # advance to the empty slice starting at position n\n        next(islice(iterator, n, n), None)\n\n\ndef nth(iterable, n, default=None):\n    \"\"\"Returns the nth item or a default value.\n\n    >>> l = range(10)\n    >>> nth(l, 3)\n    3\n    >>> nth(l, 20, \"zebra\")\n    'zebra'\n\n    \"\"\"\n    return next(islice(iterable, n, None), default)\n\n\ndef all_equal(iterable):\n    \"\"\"\n    Returns ``True`` if all the elements are equal to each other.\n\n        >>> all_equal('aaaa')\n        True\n        >>> all_equal('aaab')\n        False\n\n    \"\"\"\n    g = groupby(iterable)\n    return next(g, True) and not next(g, False)\n\n\ndef quantify(iterable, pred=bool):\n    \"\"\"Return the how many times the predicate is true.\n\n    >>> quantify([True, False, True])\n    2\n\n    \"\"\"\n    return sum(map(pred, iterable))\n\n\ndef pad_none(iterable):\n    \"\"\"Returns the sequence of elements and then returns ``None`` indefinitely.\n\n        >>> take(5, pad_none(range(3)))\n        [0, 1, 2, None, None]\n\n    Useful for emulating the behavior of the built-in :func:`map` function.\n\n    See also :func:`padded`.\n\n    \"\"\"\n    return chain(iterable, repeat(None))\n\n\npadnone = pad_none\n\n\ndef ncycles(iterable, n):\n    \"\"\"Returns the sequence elements *n* times\n\n    >>> list(ncycles([\"a\", \"b\"], 3))\n    ['a', 'b', 'a', 'b', 'a', 'b']\n\n    \"\"\"\n    return chain.from_iterable(repeat(tuple(iterable), n))\n\n\ndef dotproduct(vec1, vec2):\n    \"\"\"Returns the dot product of the two iterables.\n\n    >>> dotproduct([10, 10], [20, 20])\n    400\n\n    \"\"\"\n    return sum(map(operator.mul, vec1, vec2))\n\n\ndef flatten(listOfLists):\n    \"\"\"Return an iterator flattening one level of nesting in a list of lists.\n\n        >>> list(flatten([[0, 1], [2, 3]]))\n        [0, 1, 2, 3]\n\n    See also :func:`collapse`, which can flatten multiple levels of nesting.\n\n    \"\"\"\n    return chain.from_iterable(listOfLists)\n\n\ndef repeatfunc(func, times=None, *args):\n    \"\"\"Call *func* with *args* repeatedly, returning an iterable over the\n    results.\n\n    If *times* is specified, the iterable will terminate after that many\n    repetitions:\n\n        >>> from operator import add\n        >>> times = 4\n        >>> args = 3, 5\n        >>> list(repeatfunc(add, times, *args))\n        [8, 8, 8, 8]\n\n    If *times* is ``None`` the iterable will not terminate:\n\n        >>> from random import randrange\n        >>> times = None\n        >>> args = 1, 11\n        >>> take(6, repeatfunc(randrange, times, *args))  # doctest:+SKIP\n        [2, 4, 8, 1, 8, 4]\n\n    \"\"\"\n    if times is None:\n        return starmap(func, repeat(args))\n    return starmap(func, repeat(args, times))\n\n\ndef _pairwise(iterable):\n    \"\"\"Returns an iterator of paired items, overlapping, from the original\n\n    >>> take(4, pairwise(count()))\n    [(0, 1), (1, 2), (2, 3), (3, 4)]\n\n    On Python 3.10 and above, this is an alias for :func:`itertools.pairwise`.\n\n    \"\"\"\n    a, b = tee(iterable)\n    next(b, None)\n    yield from zip(a, b)\n\n\ntry:\n    from itertools import pairwise as itertools_pairwise\nexcept ImportError:\n    pairwise = _pairwise\nelse:\n\n    def pairwise(iterable):\n        yield from itertools_pairwise(iterable)\n\n    pairwise.__doc__ = _pairwise.__doc__\n\n\ndef grouper(iterable, n, fillvalue=None):\n    \"\"\"Collect data into fixed-length chunks or blocks.\n\n    >>> list(grouper('ABCDEFG', 3, 'x'))\n    [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')]\n\n    \"\"\"\n    if isinstance(iterable, int):\n        warnings.warn(\n            \"grouper expects iterable as first parameter\", DeprecationWarning\n        )\n        n, iterable = iterable, n\n    args = [iter(iterable)] * n\n    return zip_longest(fillvalue=fillvalue, *args)\n\n\ndef roundrobin(*iterables):\n    \"\"\"Yields an item from each iterable, alternating between them.\n\n        >>> list(roundrobin('ABC', 'D', 'EF'))\n        ['A', 'D', 'E', 'B', 'F', 'C']\n\n    This function produces the same output as :func:`interleave_longest`, but\n    may perform better for some inputs (in particular when the number of\n    iterables is small).\n\n    \"\"\"\n    # Recipe credited to George Sakkis\n    pending = len(iterables)\n    nexts = cycle(iter(it).__next__ for it in iterables)\n    while pending:\n        try:\n            for next in nexts:\n                yield next()\n        except StopIteration:\n            pending -= 1\n            nexts = cycle(islice(nexts, pending))\n\n\ndef partition(pred, iterable):\n    \"\"\"\n    Returns a 2-tuple of iterables derived from the input iterable.\n    The first yields the items that have ``pred(item) == False``.\n    The second yields the items that have ``pred(item) == True``.\n\n        >>> is_odd = lambda x: x % 2 != 0\n        >>> iterable = range(10)\n        >>> even_items, odd_items = partition(is_odd, iterable)\n        >>> list(even_items), list(odd_items)\n        ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9])\n\n    If *pred* is None, :func:`bool` is used.\n\n        >>> iterable = [0, 1, False, True, '', ' ']\n        >>> false_items, true_items = partition(None, iterable)\n        >>> list(false_items), list(true_items)\n        ([0, False, ''], [1, True, ' '])\n\n    \"\"\"\n    if pred is None:\n        pred = bool\n\n    evaluations = ((pred(x), x) for x in iterable)\n    t1, t2 = tee(evaluations)\n    return (\n        (x for (cond, x) in t1 if not cond),\n        (x for (cond, x) in t2 if cond),\n    )\n\n\ndef powerset(iterable):\n    \"\"\"Yields all possible subsets of the iterable.\n\n        >>> list(powerset([1, 2, 3]))\n        [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]\n\n    :func:`powerset` will operate on iterables that aren't :class:`set`\n    instances, so repeated elements in the input will produce repeated elements\n    in the output. Use :func:`unique_everseen` on the input to avoid generating\n    duplicates:\n\n        >>> seq = [1, 1, 0]\n        >>> list(powerset(seq))\n        [(), (1,), (1,), (0,), (1, 1), (1, 0), (1, 0), (1, 1, 0)]\n        >>> from more_itertools import unique_everseen\n        >>> list(powerset(unique_everseen(seq)))\n        [(), (1,), (0,), (1, 0)]\n\n    \"\"\"\n    s = list(iterable)\n    return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))\n\n\ndef unique_everseen(iterable, key=None):\n    \"\"\"\n    Yield unique elements, preserving order.\n\n        >>> list(unique_everseen('AAAABBBCCDAABBB'))\n        ['A', 'B', 'C', 'D']\n        >>> list(unique_everseen('ABBCcAD', str.lower))\n        ['A', 'B', 'C', 'D']\n\n    Sequences with a mix of hashable and unhashable items can be used.\n    The function will be slower (i.e., `O(n^2)`) for unhashable items.\n\n    Remember that ``list`` objects are unhashable - you can use the *key*\n    parameter to transform the list to a tuple (which is hashable) to\n    avoid a slowdown.\n\n        >>> iterable = ([1, 2], [2, 3], [1, 2])\n        >>> list(unique_everseen(iterable))  # Slow\n        [[1, 2], [2, 3]]\n        >>> list(unique_everseen(iterable, key=tuple))  # Faster\n        [[1, 2], [2, 3]]\n\n    Similary, you may want to convert unhashable ``set`` objects with\n    ``key=frozenset``. For ``dict`` objects,\n    ``key=lambda x: frozenset(x.items())`` can be used.\n\n    \"\"\"\n    seenset = set()\n    seenset_add = seenset.add\n    seenlist = []\n    seenlist_add = seenlist.append\n    use_key = key is not None\n\n    for element in iterable:\n        k = key(element) if use_key else element\n        try:\n            if k not in seenset:\n                seenset_add(k)\n                yield element\n        except TypeError:\n            if k not in seenlist:\n                seenlist_add(k)\n                yield element\n\n\ndef unique_justseen(iterable, key=None):\n    \"\"\"Yields elements in order, ignoring serial duplicates\n\n    >>> list(unique_justseen('AAAABBBCCDAABBB'))\n    ['A', 'B', 'C', 'D', 'A', 'B']\n    >>> list(unique_justseen('ABBCcAD', str.lower))\n    ['A', 'B', 'C', 'A', 'D']\n\n    \"\"\"\n    return map(next, map(operator.itemgetter(1), groupby(iterable, key)))\n\n\ndef iter_except(func, exception, first=None):\n    \"\"\"Yields results from a function repeatedly until an exception is raised.\n\n    Converts a call-until-exception interface to an iterator interface.\n    Like ``iter(func, sentinel)``, but uses an exception instead of a sentinel\n    to end the loop.\n\n        >>> l = [0, 1, 2]\n        >>> list(iter_except(l.pop, IndexError))\n        [2, 1, 0]\n\n    Multiple exceptions can be specified as a stopping condition:\n\n        >>> l = [1, 2, 3, '...', 4, 5, 6]\n        >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError)))\n        [7, 6, 5]\n        >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError)))\n        [4, 3, 2]\n        >>> list(iter_except(lambda: 1 + l.pop(), (IndexError, TypeError)))\n        []\n\n    \"\"\"\n    try:\n        if first is not None:\n            yield first()\n        while 1:\n            yield func()\n    except exception:\n        pass\n\n\ndef first_true(iterable, default=None, pred=None):\n    \"\"\"\n    Returns the first true value in the iterable.\n\n    If no true value is found, returns *default*\n\n    If *pred* is not None, returns the first item for which\n    ``pred(item) == True`` .\n\n        >>> first_true(range(10))\n        1\n        >>> first_true(range(10), pred=lambda x: x > 5)\n        6\n        >>> first_true(range(10), default='missing', pred=lambda x: x > 9)\n        'missing'\n\n    \"\"\"\n    return next(filter(pred, iterable), default)\n\n\ndef random_product(*args, repeat=1):\n    \"\"\"Draw an item at random from each of the input iterables.\n\n        >>> random_product('abc', range(4), 'XYZ')  # doctest:+SKIP\n        ('c', 3, 'Z')\n\n    If *repeat* is provided as a keyword argument, that many items will be\n    drawn from each iterable.\n\n        >>> random_product('abcd', range(4), repeat=2)  # doctest:+SKIP\n        ('a', 2, 'd', 3)\n\n    This equivalent to taking a random selection from\n    ``itertools.product(*args, **kwarg)``.\n\n    \"\"\"\n    pools = [tuple(pool) for pool in args] * repeat\n    return tuple(choice(pool) for pool in pools)\n\n\ndef random_permutation(iterable, r=None):\n    \"\"\"Return a random *r* length permutation of the elements in *iterable*.\n\n    If *r* is not specified or is ``None``, then *r* defaults to the length of\n    *iterable*.\n\n        >>> random_permutation(range(5))  # doctest:+SKIP\n        (3, 4, 0, 1, 2)\n\n    This equivalent to taking a random selection from\n    ``itertools.permutations(iterable, r)``.\n\n    \"\"\"\n    pool = tuple(iterable)\n    r = len(pool) if r is None else r\n    return tuple(sample(pool, r))\n\n\ndef random_combination(iterable, r):\n    \"\"\"Return a random *r* length subsequence of the elements in *iterable*.\n\n        >>> random_combination(range(5), 3)  # doctest:+SKIP\n        (2, 3, 4)\n\n    This equivalent to taking a random selection from\n    ``itertools.combinations(iterable, r)``.\n\n    \"\"\"\n    pool = tuple(iterable)\n    n = len(pool)\n    indices = sorted(sample(range(n), r))\n    return tuple(pool[i] for i in indices)\n\n\ndef random_combination_with_replacement(iterable, r):\n    \"\"\"Return a random *r* length subsequence of elements in *iterable*,\n    allowing individual elements to be repeated.\n\n        >>> random_combination_with_replacement(range(3), 5) # doctest:+SKIP\n        (0, 0, 1, 2, 2)\n\n    This equivalent to taking a random selection from\n    ``itertools.combinations_with_replacement(iterable, r)``.\n\n    \"\"\"\n    pool = tuple(iterable)\n    n = len(pool)\n    indices = sorted(randrange(n) for i in range(r))\n    return tuple(pool[i] for i in indices)\n\n\ndef nth_combination(iterable, r, index):\n    \"\"\"Equivalent to ``list(combinations(iterable, r))[index]``.\n\n    The subsequences of *iterable* that are of length *r* can be ordered\n    lexicographically. :func:`nth_combination` computes the subsequence at\n    sort position *index* directly, without computing the previous\n    subsequences.\n\n        >>> nth_combination(range(5), 3, 5)\n        (0, 3, 4)\n\n    ``ValueError`` will be raised If *r* is negative or greater than the length\n    of *iterable*.\n    ``IndexError`` will be raised if the given *index* is invalid.\n    \"\"\"\n    pool = tuple(iterable)\n    n = len(pool)\n    if (r < 0) or (r > n):\n        raise ValueError\n\n    c = 1\n    k = min(r, n - r)\n    for i in range(1, k + 1):\n        c = c * (n - k + i) // i\n\n    if index < 0:\n        index += c\n\n    if (index < 0) or (index >= c):\n        raise IndexError\n\n    result = []\n    while r:\n        c, n, r = c * r // n, n - 1, r - 1\n        while index >= c:\n            index -= c\n            c, n = c * (n - r) // n, n - 1\n        result.append(pool[-1 - n])\n\n    return tuple(result)\n\n\ndef prepend(value, iterator):\n    \"\"\"Yield *value*, followed by the elements in *iterator*.\n\n        >>> value = '0'\n        >>> iterator = ['1', '2', '3']\n        >>> list(prepend(value, iterator))\n        ['0', '1', '2', '3']\n\n    To prepend multiple values, see :func:`itertools.chain`\n    or :func:`value_chain`.\n\n    \"\"\"\n    return chain([value], iterator)\n\n\ndef convolve(signal, kernel):\n    \"\"\"Convolve the iterable *signal* with the iterable *kernel*.\n\n        >>> signal = (1, 2, 3, 4, 5)\n        >>> kernel = [3, 2, 1]\n        >>> list(convolve(signal, kernel))\n        [3, 8, 14, 20, 26, 14, 5]\n\n    Note: the input arguments are not interchangeable, as the *kernel*\n    is immediately consumed and stored.\n\n    \"\"\"\n    kernel = tuple(kernel)[::-1]\n    n = len(kernel)\n    window = deque([0], maxlen=n) * n\n    for x in chain(signal, repeat(0, n - 1)):\n        window.append(x)\n        yield sum(map(operator.mul, kernel, window))\n\n\ndef before_and_after(predicate, it):\n    \"\"\"A variant of :func:`takewhile` that allows complete access to the\n    remainder of the iterator.\n\n         >>> it = iter('ABCdEfGhI')\n         >>> all_upper, remainder = before_and_after(str.isupper, it)\n         >>> ''.join(all_upper)\n         'ABC'\n         >>> ''.join(remainder) # takewhile() would lose the 'd'\n         'dEfGhI'\n\n    Note that the first iterator must be fully consumed before the second\n    iterator can generate valid results.\n    \"\"\"\n    it = iter(it)\n    transition = []\n\n    def true_iterator():\n        for elem in it:\n            if predicate(elem):\n                yield elem\n            else:\n                transition.append(elem)\n                return\n\n    def remainder_iterator():\n        yield from transition\n        yield from it\n\n    return true_iterator(), remainder_iterator()\n\n\ndef triplewise(iterable):\n    \"\"\"Return overlapping triplets from *iterable*.\n\n    >>> list(triplewise('ABCDE'))\n    [('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E')]\n\n    \"\"\"\n    for (a, _), (b, c) in pairwise(pairwise(iterable)):\n        yield a, b, c\n\n\ndef sliding_window(iterable, n):\n    \"\"\"Return a sliding window of width *n* over *iterable*.\n\n        >>> list(sliding_window(range(6), 4))\n        [(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5)]\n\n    If *iterable* has fewer than *n* items, then nothing is yielded:\n\n        >>> list(sliding_window(range(3), 4))\n        []\n\n    For a variant with more features, see :func:`windowed`.\n    \"\"\"\n    it = iter(iterable)\n    window = deque(islice(it, n), maxlen=n)\n    if len(window) == n:\n        yield tuple(window)\n    for x in it:\n        window.append(x)\n        yield tuple(window)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/packaging/__about__.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\n__all__ = [\n    \"__title__\",\n    \"__summary__\",\n    \"__uri__\",\n    \"__version__\",\n    \"__author__\",\n    \"__email__\",\n    \"__license__\",\n    \"__copyright__\",\n]\n\n__title__ = \"packaging\"\n__summary__ = \"Core utilities for Python packages\"\n__uri__ = \"https://github.com/pypa/packaging\"\n\n__version__ = \"21.3\"\n\n__author__ = \"Donald Stufft and individual contributors\"\n__email__ = \"donald@stufft.io\"\n\n__license__ = \"BSD-2-Clause or Apache-2.0\"\n__copyright__ = \"2014-2019 %s\" % __author__\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/packaging/__init__.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nfrom .__about__ import (\n    __author__,\n    __copyright__,\n    __email__,\n    __license__,\n    __summary__,\n    __title__,\n    __uri__,\n    __version__,\n)\n\n__all__ = [\n    \"__title__\",\n    \"__summary__\",\n    \"__uri__\",\n    \"__version__\",\n    \"__author__\",\n    \"__email__\",\n    \"__license__\",\n    \"__copyright__\",\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/packaging/_manylinux.py",
    "content": "import collections\nimport functools\nimport os\nimport re\nimport struct\nimport sys\nimport warnings\nfrom typing import IO, Dict, Iterator, NamedTuple, Optional, Tuple\n\n\n# Python does not provide platform information at sufficient granularity to\n# identify the architecture of the running executable in some cases, so we\n# determine it dynamically by reading the information from the running\n# process. This only applies on Linux, which uses the ELF format.\nclass _ELFFileHeader:\n    # https://en.wikipedia.org/wiki/Executable_and_Linkable_Format#File_header\n    class _InvalidELFFileHeader(ValueError):\n        \"\"\"\n        An invalid ELF file header was found.\n        \"\"\"\n\n    ELF_MAGIC_NUMBER = 0x7F454C46\n    ELFCLASS32 = 1\n    ELFCLASS64 = 2\n    ELFDATA2LSB = 1\n    ELFDATA2MSB = 2\n    EM_386 = 3\n    EM_S390 = 22\n    EM_ARM = 40\n    EM_X86_64 = 62\n    EF_ARM_ABIMASK = 0xFF000000\n    EF_ARM_ABI_VER5 = 0x05000000\n    EF_ARM_ABI_FLOAT_HARD = 0x00000400\n\n    def __init__(self, file: IO[bytes]) -> None:\n        def unpack(fmt: str) -> int:\n            try:\n                data = file.read(struct.calcsize(fmt))\n                result: Tuple[int, ...] = struct.unpack(fmt, data)\n            except struct.error:\n                raise _ELFFileHeader._InvalidELFFileHeader()\n            return result[0]\n\n        self.e_ident_magic = unpack(\">I\")\n        if self.e_ident_magic != self.ELF_MAGIC_NUMBER:\n            raise _ELFFileHeader._InvalidELFFileHeader()\n        self.e_ident_class = unpack(\"B\")\n        if self.e_ident_class not in {self.ELFCLASS32, self.ELFCLASS64}:\n            raise _ELFFileHeader._InvalidELFFileHeader()\n        self.e_ident_data = unpack(\"B\")\n        if self.e_ident_data not in {self.ELFDATA2LSB, self.ELFDATA2MSB}:\n            raise _ELFFileHeader._InvalidELFFileHeader()\n        self.e_ident_version = unpack(\"B\")\n        self.e_ident_osabi = unpack(\"B\")\n        self.e_ident_abiversion = unpack(\"B\")\n        self.e_ident_pad = file.read(7)\n        format_h = \"<H\" if self.e_ident_data == self.ELFDATA2LSB else \">H\"\n        format_i = \"<I\" if self.e_ident_data == self.ELFDATA2LSB else \">I\"\n        format_q = \"<Q\" if self.e_ident_data == self.ELFDATA2LSB else \">Q\"\n        format_p = format_i if self.e_ident_class == self.ELFCLASS32 else format_q\n        self.e_type = unpack(format_h)\n        self.e_machine = unpack(format_h)\n        self.e_version = unpack(format_i)\n        self.e_entry = unpack(format_p)\n        self.e_phoff = unpack(format_p)\n        self.e_shoff = unpack(format_p)\n        self.e_flags = unpack(format_i)\n        self.e_ehsize = unpack(format_h)\n        self.e_phentsize = unpack(format_h)\n        self.e_phnum = unpack(format_h)\n        self.e_shentsize = unpack(format_h)\n        self.e_shnum = unpack(format_h)\n        self.e_shstrndx = unpack(format_h)\n\n\ndef _get_elf_header() -> Optional[_ELFFileHeader]:\n    try:\n        with open(sys.executable, \"rb\") as f:\n            elf_header = _ELFFileHeader(f)\n    except (OSError, TypeError, _ELFFileHeader._InvalidELFFileHeader):\n        return None\n    return elf_header\n\n\ndef _is_linux_armhf() -> bool:\n    # hard-float ABI can be detected from the ELF header of the running\n    # process\n    # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf\n    elf_header = _get_elf_header()\n    if elf_header is None:\n        return False\n    result = elf_header.e_ident_class == elf_header.ELFCLASS32\n    result &= elf_header.e_ident_data == elf_header.ELFDATA2LSB\n    result &= elf_header.e_machine == elf_header.EM_ARM\n    result &= (\n        elf_header.e_flags & elf_header.EF_ARM_ABIMASK\n    ) == elf_header.EF_ARM_ABI_VER5\n    result &= (\n        elf_header.e_flags & elf_header.EF_ARM_ABI_FLOAT_HARD\n    ) == elf_header.EF_ARM_ABI_FLOAT_HARD\n    return result\n\n\ndef _is_linux_i686() -> bool:\n    elf_header = _get_elf_header()\n    if elf_header is None:\n        return False\n    result = elf_header.e_ident_class == elf_header.ELFCLASS32\n    result &= elf_header.e_ident_data == elf_header.ELFDATA2LSB\n    result &= elf_header.e_machine == elf_header.EM_386\n    return result\n\n\ndef _have_compatible_abi(arch: str) -> bool:\n    if arch == \"armv7l\":\n        return _is_linux_armhf()\n    if arch == \"i686\":\n        return _is_linux_i686()\n    return arch in {\"x86_64\", \"aarch64\", \"ppc64\", \"ppc64le\", \"s390x\"}\n\n\n# If glibc ever changes its major version, we need to know what the last\n# minor version was, so we can build the complete list of all versions.\n# For now, guess what the highest minor version might be, assume it will\n# be 50 for testing. Once this actually happens, update the dictionary\n# with the actual value.\n_LAST_GLIBC_MINOR: Dict[int, int] = collections.defaultdict(lambda: 50)\n\n\nclass _GLibCVersion(NamedTuple):\n    major: int\n    minor: int\n\n\ndef _glibc_version_string_confstr() -> Optional[str]:\n    \"\"\"\n    Primary implementation of glibc_version_string using os.confstr.\n    \"\"\"\n    # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely\n    # to be broken or missing. This strategy is used in the standard library\n    # platform module.\n    # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183\n    try:\n        # os.confstr(\"CS_GNU_LIBC_VERSION\") returns a string like \"glibc 2.17\".\n        version_string = os.confstr(\"CS_GNU_LIBC_VERSION\")\n        assert version_string is not None\n        _, version = version_string.split()\n    except (AssertionError, AttributeError, OSError, ValueError):\n        # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...\n        return None\n    return version\n\n\ndef _glibc_version_string_ctypes() -> Optional[str]:\n    \"\"\"\n    Fallback implementation of glibc_version_string using ctypes.\n    \"\"\"\n    try:\n        import ctypes\n    except ImportError:\n        return None\n\n    # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen\n    # manpage says, \"If filename is NULL, then the returned handle is for the\n    # main program\". This way we can let the linker do the work to figure out\n    # which libc our process is actually using.\n    #\n    # We must also handle the special case where the executable is not a\n    # dynamically linked executable. This can occur when using musl libc,\n    # for example. In this situation, dlopen() will error, leading to an\n    # OSError. Interestingly, at least in the case of musl, there is no\n    # errno set on the OSError. The single string argument used to construct\n    # OSError comes from libc itself and is therefore not portable to\n    # hard code here. In any case, failure to call dlopen() means we\n    # can proceed, so we bail on our attempt.\n    try:\n        process_namespace = ctypes.CDLL(None)\n    except OSError:\n        return None\n\n    try:\n        gnu_get_libc_version = process_namespace.gnu_get_libc_version\n    except AttributeError:\n        # Symbol doesn't exist -> therefore, we are not linked to\n        # glibc.\n        return None\n\n    # Call gnu_get_libc_version, which returns a string like \"2.5\"\n    gnu_get_libc_version.restype = ctypes.c_char_p\n    version_str: str = gnu_get_libc_version()\n    # py2 / py3 compatibility:\n    if not isinstance(version_str, str):\n        version_str = version_str.decode(\"ascii\")\n\n    return version_str\n\n\ndef _glibc_version_string() -> Optional[str]:\n    \"\"\"Returns glibc version string, or None if not using glibc.\"\"\"\n    return _glibc_version_string_confstr() or _glibc_version_string_ctypes()\n\n\ndef _parse_glibc_version(version_str: str) -> Tuple[int, int]:\n    \"\"\"Parse glibc version.\n\n    We use a regexp instead of str.split because we want to discard any\n    random junk that might come after the minor version -- this might happen\n    in patched/forked versions of glibc (e.g. Linaro's version of glibc\n    uses version strings like \"2.20-2014.11\"). See gh-3588.\n    \"\"\"\n    m = re.match(r\"(?P<major>[0-9]+)\\.(?P<minor>[0-9]+)\", version_str)\n    if not m:\n        warnings.warn(\n            \"Expected glibc version with 2 components major.minor,\"\n            \" got: %s\" % version_str,\n            RuntimeWarning,\n        )\n        return -1, -1\n    return int(m.group(\"major\")), int(m.group(\"minor\"))\n\n\n@functools.lru_cache()\ndef _get_glibc_version() -> Tuple[int, int]:\n    version_str = _glibc_version_string()\n    if version_str is None:\n        return (-1, -1)\n    return _parse_glibc_version(version_str)\n\n\n# From PEP 513, PEP 600\ndef _is_compatible(name: str, arch: str, version: _GLibCVersion) -> bool:\n    sys_glibc = _get_glibc_version()\n    if sys_glibc < version:\n        return False\n    # Check for presence of _manylinux module.\n    try:\n        import _manylinux  # noqa\n    except ImportError:\n        return True\n    if hasattr(_manylinux, \"manylinux_compatible\"):\n        result = _manylinux.manylinux_compatible(version[0], version[1], arch)\n        if result is not None:\n            return bool(result)\n        return True\n    if version == _GLibCVersion(2, 5):\n        if hasattr(_manylinux, \"manylinux1_compatible\"):\n            return bool(_manylinux.manylinux1_compatible)\n    if version == _GLibCVersion(2, 12):\n        if hasattr(_manylinux, \"manylinux2010_compatible\"):\n            return bool(_manylinux.manylinux2010_compatible)\n    if version == _GLibCVersion(2, 17):\n        if hasattr(_manylinux, \"manylinux2014_compatible\"):\n            return bool(_manylinux.manylinux2014_compatible)\n    return True\n\n\n_LEGACY_MANYLINUX_MAP = {\n    # CentOS 7 w/ glibc 2.17 (PEP 599)\n    (2, 17): \"manylinux2014\",\n    # CentOS 6 w/ glibc 2.12 (PEP 571)\n    (2, 12): \"manylinux2010\",\n    # CentOS 5 w/ glibc 2.5 (PEP 513)\n    (2, 5): \"manylinux1\",\n}\n\n\ndef platform_tags(linux: str, arch: str) -> Iterator[str]:\n    if not _have_compatible_abi(arch):\n        return\n    # Oldest glibc to be supported regardless of architecture is (2, 17).\n    too_old_glibc2 = _GLibCVersion(2, 16)\n    if arch in {\"x86_64\", \"i686\"}:\n        # On x86/i686 also oldest glibc to be supported is (2, 5).\n        too_old_glibc2 = _GLibCVersion(2, 4)\n    current_glibc = _GLibCVersion(*_get_glibc_version())\n    glibc_max_list = [current_glibc]\n    # We can assume compatibility across glibc major versions.\n    # https://sourceware.org/bugzilla/show_bug.cgi?id=24636\n    #\n    # Build a list of maximum glibc versions so that we can\n    # output the canonical list of all glibc from current_glibc\n    # down to too_old_glibc2, including all intermediary versions.\n    for glibc_major in range(current_glibc.major - 1, 1, -1):\n        glibc_minor = _LAST_GLIBC_MINOR[glibc_major]\n        glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))\n    for glibc_max in glibc_max_list:\n        if glibc_max.major == too_old_glibc2.major:\n            min_minor = too_old_glibc2.minor\n        else:\n            # For other glibc major versions oldest supported is (x, 0).\n            min_minor = -1\n        for glibc_minor in range(glibc_max.minor, min_minor, -1):\n            glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)\n            tag = \"manylinux_{}_{}\".format(*glibc_version)\n            if _is_compatible(tag, arch, glibc_version):\n                yield linux.replace(\"linux\", tag)\n            # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.\n            if glibc_version in _LEGACY_MANYLINUX_MAP:\n                legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version]\n                if _is_compatible(legacy_tag, arch, glibc_version):\n                    yield linux.replace(\"linux\", legacy_tag)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/packaging/_musllinux.py",
    "content": "\"\"\"PEP 656 support.\n\nThis module implements logic to detect if the currently running Python is\nlinked against musl, and what musl version is used.\n\"\"\"\n\nimport contextlib\nimport functools\nimport operator\nimport os\nimport re\nimport struct\nimport subprocess\nimport sys\nfrom typing import IO, Iterator, NamedTuple, Optional, Tuple\n\n\ndef _read_unpacked(f: IO[bytes], fmt: str) -> Tuple[int, ...]:\n    return struct.unpack(fmt, f.read(struct.calcsize(fmt)))\n\n\ndef _parse_ld_musl_from_elf(f: IO[bytes]) -> Optional[str]:\n    \"\"\"Detect musl libc location by parsing the Python executable.\n\n    Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca\n    ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html\n    \"\"\"\n    f.seek(0)\n    try:\n        ident = _read_unpacked(f, \"16B\")\n    except struct.error:\n        return None\n    if ident[:4] != tuple(b\"\\x7fELF\"):  # Invalid magic, not ELF.\n        return None\n    f.seek(struct.calcsize(\"HHI\"), 1)  # Skip file type, machine, and version.\n\n    try:\n        # e_fmt: Format for program header.\n        # p_fmt: Format for section header.\n        # p_idx: Indexes to find p_type, p_offset, and p_filesz.\n        e_fmt, p_fmt, p_idx = {\n            1: (\"IIIIHHH\", \"IIIIIIII\", (0, 1, 4)),  # 32-bit.\n            2: (\"QQQIHHH\", \"IIQQQQQQ\", (0, 2, 5)),  # 64-bit.\n        }[ident[4]]\n    except KeyError:\n        return None\n    else:\n        p_get = operator.itemgetter(*p_idx)\n\n    # Find the interpreter section and return its content.\n    try:\n        _, e_phoff, _, _, _, e_phentsize, e_phnum = _read_unpacked(f, e_fmt)\n    except struct.error:\n        return None\n    for i in range(e_phnum + 1):\n        f.seek(e_phoff + e_phentsize * i)\n        try:\n            p_type, p_offset, p_filesz = p_get(_read_unpacked(f, p_fmt))\n        except struct.error:\n            return None\n        if p_type != 3:  # Not PT_INTERP.\n            continue\n        f.seek(p_offset)\n        interpreter = os.fsdecode(f.read(p_filesz)).strip(\"\\0\")\n        if \"musl\" not in interpreter:\n            return None\n        return interpreter\n    return None\n\n\nclass _MuslVersion(NamedTuple):\n    major: int\n    minor: int\n\n\ndef _parse_musl_version(output: str) -> Optional[_MuslVersion]:\n    lines = [n for n in (n.strip() for n in output.splitlines()) if n]\n    if len(lines) < 2 or lines[0][:4] != \"musl\":\n        return None\n    m = re.match(r\"Version (\\d+)\\.(\\d+)\", lines[1])\n    if not m:\n        return None\n    return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))\n\n\n@functools.lru_cache()\ndef _get_musl_version(executable: str) -> Optional[_MuslVersion]:\n    \"\"\"Detect currently-running musl runtime version.\n\n    This is done by checking the specified executable's dynamic linking\n    information, and invoking the loader to parse its output for a version\n    string. If the loader is musl, the output would be something like::\n\n        musl libc (x86_64)\n        Version 1.2.2\n        Dynamic Program Loader\n    \"\"\"\n    with contextlib.ExitStack() as stack:\n        try:\n            f = stack.enter_context(open(executable, \"rb\"))\n        except OSError:\n            return None\n        ld = _parse_ld_musl_from_elf(f)\n    if not ld:\n        return None\n    proc = subprocess.run([ld], stderr=subprocess.PIPE, universal_newlines=True)\n    return _parse_musl_version(proc.stderr)\n\n\ndef platform_tags(arch: str) -> Iterator[str]:\n    \"\"\"Generate musllinux tags compatible to the current platform.\n\n    :param arch: Should be the part of platform tag after the ``linux_``\n        prefix, e.g. ``x86_64``. The ``linux_`` prefix is assumed as a\n        prerequisite for the current platform to be musllinux-compatible.\n\n    :returns: An iterator of compatible musllinux tags.\n    \"\"\"\n    sys_musl = _get_musl_version(sys.executable)\n    if sys_musl is None:  # Python not dynamically linked against musl.\n        return\n    for minor in range(sys_musl.minor, -1, -1):\n        yield f\"musllinux_{sys_musl.major}_{minor}_{arch}\"\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import sysconfig\n\n    plat = sysconfig.get_platform()\n    assert plat.startswith(\"linux-\"), \"not linux\"\n\n    print(\"plat:\", plat)\n    print(\"musl:\", _get_musl_version(sys.executable))\n    print(\"tags:\", end=\" \")\n    for t in platform_tags(re.sub(r\"[.-]\", \"_\", plat.split(\"-\", 1)[-1])):\n        print(t, end=\"\\n      \")\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/packaging/_structures.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\n\nclass InfinityType:\n    def __repr__(self) -> str:\n        return \"Infinity\"\n\n    def __hash__(self) -> int:\n        return hash(repr(self))\n\n    def __lt__(self, other: object) -> bool:\n        return False\n\n    def __le__(self, other: object) -> bool:\n        return False\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, self.__class__)\n\n    def __gt__(self, other: object) -> bool:\n        return True\n\n    def __ge__(self, other: object) -> bool:\n        return True\n\n    def __neg__(self: object) -> \"NegativeInfinityType\":\n        return NegativeInfinity\n\n\nInfinity = InfinityType()\n\n\nclass NegativeInfinityType:\n    def __repr__(self) -> str:\n        return \"-Infinity\"\n\n    def __hash__(self) -> int:\n        return hash(repr(self))\n\n    def __lt__(self, other: object) -> bool:\n        return True\n\n    def __le__(self, other: object) -> bool:\n        return True\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, self.__class__)\n\n    def __gt__(self, other: object) -> bool:\n        return False\n\n    def __ge__(self, other: object) -> bool:\n        return False\n\n    def __neg__(self: object) -> InfinityType:\n        return Infinity\n\n\nNegativeInfinity = NegativeInfinityType()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/packaging/markers.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport operator\nimport os\nimport platform\nimport sys\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union\n\nfrom pkg_resources.extern.pyparsing import (  # noqa: N817\n    Forward,\n    Group,\n    Literal as L,\n    ParseException,\n    ParseResults,\n    QuotedString,\n    ZeroOrMore,\n    stringEnd,\n    stringStart,\n)\n\nfrom .specifiers import InvalidSpecifier, Specifier\n\n__all__ = [\n    \"InvalidMarker\",\n    \"UndefinedComparison\",\n    \"UndefinedEnvironmentName\",\n    \"Marker\",\n    \"default_environment\",\n]\n\nOperator = Callable[[str, str], bool]\n\n\nclass InvalidMarker(ValueError):\n    \"\"\"\n    An invalid marker was found, users should refer to PEP 508.\n    \"\"\"\n\n\nclass UndefinedComparison(ValueError):\n    \"\"\"\n    An invalid operation was attempted on a value that doesn't support it.\n    \"\"\"\n\n\nclass UndefinedEnvironmentName(ValueError):\n    \"\"\"\n    A name was attempted to be used that does not exist inside of the\n    environment.\n    \"\"\"\n\n\nclass Node:\n    def __init__(self, value: Any) -> None:\n        self.value = value\n\n    def __str__(self) -> str:\n        return str(self.value)\n\n    def __repr__(self) -> str:\n        return f\"<{self.__class__.__name__}('{self}')>\"\n\n    def serialize(self) -> str:\n        raise NotImplementedError\n\n\nclass Variable(Node):\n    def serialize(self) -> str:\n        return str(self)\n\n\nclass Value(Node):\n    def serialize(self) -> str:\n        return f'\"{self}\"'\n\n\nclass Op(Node):\n    def serialize(self) -> str:\n        return str(self)\n\n\nVARIABLE = (\n    L(\"implementation_version\")\n    | L(\"platform_python_implementation\")\n    | L(\"implementation_name\")\n    | L(\"python_full_version\")\n    | L(\"platform_release\")\n    | L(\"platform_version\")\n    | L(\"platform_machine\")\n    | L(\"platform_system\")\n    | L(\"python_version\")\n    | L(\"sys_platform\")\n    | L(\"os_name\")\n    | L(\"os.name\")  # PEP-345\n    | L(\"sys.platform\")  # PEP-345\n    | L(\"platform.version\")  # PEP-345\n    | L(\"platform.machine\")  # PEP-345\n    | L(\"platform.python_implementation\")  # PEP-345\n    | L(\"python_implementation\")  # undocumented setuptools legacy\n    | L(\"extra\")  # PEP-508\n)\nALIASES = {\n    \"os.name\": \"os_name\",\n    \"sys.platform\": \"sys_platform\",\n    \"platform.version\": \"platform_version\",\n    \"platform.machine\": \"platform_machine\",\n    \"platform.python_implementation\": \"platform_python_implementation\",\n    \"python_implementation\": \"platform_python_implementation\",\n}\nVARIABLE.setParseAction(lambda s, l, t: Variable(ALIASES.get(t[0], t[0])))\n\nVERSION_CMP = (\n    L(\"===\") | L(\"==\") | L(\">=\") | L(\"<=\") | L(\"!=\") | L(\"~=\") | L(\">\") | L(\"<\")\n)\n\nMARKER_OP = VERSION_CMP | L(\"not in\") | L(\"in\")\nMARKER_OP.setParseAction(lambda s, l, t: Op(t[0]))\n\nMARKER_VALUE = QuotedString(\"'\") | QuotedString('\"')\nMARKER_VALUE.setParseAction(lambda s, l, t: Value(t[0]))\n\nBOOLOP = L(\"and\") | L(\"or\")\n\nMARKER_VAR = VARIABLE | MARKER_VALUE\n\nMARKER_ITEM = Group(MARKER_VAR + MARKER_OP + MARKER_VAR)\nMARKER_ITEM.setParseAction(lambda s, l, t: tuple(t[0]))\n\nLPAREN = L(\"(\").suppress()\nRPAREN = L(\")\").suppress()\n\nMARKER_EXPR = Forward()\nMARKER_ATOM = MARKER_ITEM | Group(LPAREN + MARKER_EXPR + RPAREN)\nMARKER_EXPR << MARKER_ATOM + ZeroOrMore(BOOLOP + MARKER_EXPR)\n\nMARKER = stringStart + MARKER_EXPR + stringEnd\n\n\ndef _coerce_parse_result(results: Union[ParseResults, List[Any]]) -> List[Any]:\n    if isinstance(results, ParseResults):\n        return [_coerce_parse_result(i) for i in results]\n    else:\n        return results\n\n\ndef _format_marker(\n    marker: Union[List[str], Tuple[Node, ...], str], first: Optional[bool] = True\n) -> str:\n\n    assert isinstance(marker, (list, tuple, str))\n\n    # Sometimes we have a structure like [[...]] which is a single item list\n    # where the single item is itself it's own list. In that case we want skip\n    # the rest of this function so that we don't get extraneous () on the\n    # outside.\n    if (\n        isinstance(marker, list)\n        and len(marker) == 1\n        and isinstance(marker[0], (list, tuple))\n    ):\n        return _format_marker(marker[0])\n\n    if isinstance(marker, list):\n        inner = (_format_marker(m, first=False) for m in marker)\n        if first:\n            return \" \".join(inner)\n        else:\n            return \"(\" + \" \".join(inner) + \")\"\n    elif isinstance(marker, tuple):\n        return \" \".join([m.serialize() for m in marker])\n    else:\n        return marker\n\n\n_operators: Dict[str, Operator] = {\n    \"in\": lambda lhs, rhs: lhs in rhs,\n    \"not in\": lambda lhs, rhs: lhs not in rhs,\n    \"<\": operator.lt,\n    \"<=\": operator.le,\n    \"==\": operator.eq,\n    \"!=\": operator.ne,\n    \">=\": operator.ge,\n    \">\": operator.gt,\n}\n\n\ndef _eval_op(lhs: str, op: Op, rhs: str) -> bool:\n    try:\n        spec = Specifier(\"\".join([op.serialize(), rhs]))\n    except InvalidSpecifier:\n        pass\n    else:\n        return spec.contains(lhs)\n\n    oper: Optional[Operator] = _operators.get(op.serialize())\n    if oper is None:\n        raise UndefinedComparison(f\"Undefined {op!r} on {lhs!r} and {rhs!r}.\")\n\n    return oper(lhs, rhs)\n\n\nclass Undefined:\n    pass\n\n\n_undefined = Undefined()\n\n\ndef _get_env(environment: Dict[str, str], name: str) -> str:\n    value: Union[str, Undefined] = environment.get(name, _undefined)\n\n    if isinstance(value, Undefined):\n        raise UndefinedEnvironmentName(\n            f\"{name!r} does not exist in evaluation environment.\"\n        )\n\n    return value\n\n\ndef _evaluate_markers(markers: List[Any], environment: Dict[str, str]) -> bool:\n    groups: List[List[bool]] = [[]]\n\n    for marker in markers:\n        assert isinstance(marker, (list, tuple, str))\n\n        if isinstance(marker, list):\n            groups[-1].append(_evaluate_markers(marker, environment))\n        elif isinstance(marker, tuple):\n            lhs, op, rhs = marker\n\n            if isinstance(lhs, Variable):\n                lhs_value = _get_env(environment, lhs.value)\n                rhs_value = rhs.value\n            else:\n                lhs_value = lhs.value\n                rhs_value = _get_env(environment, rhs.value)\n\n            groups[-1].append(_eval_op(lhs_value, op, rhs_value))\n        else:\n            assert marker in [\"and\", \"or\"]\n            if marker == \"or\":\n                groups.append([])\n\n    return any(all(item) for item in groups)\n\n\ndef format_full_version(info: \"sys._version_info\") -> str:\n    version = \"{0.major}.{0.minor}.{0.micro}\".format(info)\n    kind = info.releaselevel\n    if kind != \"final\":\n        version += kind[0] + str(info.serial)\n    return version\n\n\ndef default_environment() -> Dict[str, str]:\n    iver = format_full_version(sys.implementation.version)\n    implementation_name = sys.implementation.name\n    return {\n        \"implementation_name\": implementation_name,\n        \"implementation_version\": iver,\n        \"os_name\": os.name,\n        \"platform_machine\": platform.machine(),\n        \"platform_release\": platform.release(),\n        \"platform_system\": platform.system(),\n        \"platform_version\": platform.version(),\n        \"python_full_version\": platform.python_version(),\n        \"platform_python_implementation\": platform.python_implementation(),\n        \"python_version\": \".\".join(platform.python_version_tuple()[:2]),\n        \"sys_platform\": sys.platform,\n    }\n\n\nclass Marker:\n    def __init__(self, marker: str) -> None:\n        try:\n            self._markers = _coerce_parse_result(MARKER.parseString(marker))\n        except ParseException as e:\n            raise InvalidMarker(\n                f\"Invalid marker: {marker!r}, parse error at \"\n                f\"{marker[e.loc : e.loc + 8]!r}\"\n            )\n\n    def __str__(self) -> str:\n        return _format_marker(self._markers)\n\n    def __repr__(self) -> str:\n        return f\"<Marker('{self}')>\"\n\n    def evaluate(self, environment: Optional[Dict[str, str]] = None) -> bool:\n        \"\"\"Evaluate a marker.\n\n        Return the boolean from evaluating the given marker against the\n        environment. environment is an optional argument to override all or\n        part of the determined environment.\n\n        The environment is determined from the current Python process.\n        \"\"\"\n        current_environment = default_environment()\n        if environment is not None:\n            current_environment.update(environment)\n\n        return _evaluate_markers(self._markers, current_environment)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/packaging/requirements.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport re\nimport string\nimport urllib.parse\nfrom typing import List, Optional as TOptional, Set\n\nfrom pkg_resources.extern.pyparsing import (  # noqa\n    Combine,\n    Literal as L,\n    Optional,\n    ParseException,\n    Regex,\n    Word,\n    ZeroOrMore,\n    originalTextFor,\n    stringEnd,\n    stringStart,\n)\n\nfrom .markers import MARKER_EXPR, Marker\nfrom .specifiers import LegacySpecifier, Specifier, SpecifierSet\n\n\nclass InvalidRequirement(ValueError):\n    \"\"\"\n    An invalid requirement was found, users should refer to PEP 508.\n    \"\"\"\n\n\nALPHANUM = Word(string.ascii_letters + string.digits)\n\nLBRACKET = L(\"[\").suppress()\nRBRACKET = L(\"]\").suppress()\nLPAREN = L(\"(\").suppress()\nRPAREN = L(\")\").suppress()\nCOMMA = L(\",\").suppress()\nSEMICOLON = L(\";\").suppress()\nAT = L(\"@\").suppress()\n\nPUNCTUATION = Word(\"-_.\")\nIDENTIFIER_END = ALPHANUM | (ZeroOrMore(PUNCTUATION) + ALPHANUM)\nIDENTIFIER = Combine(ALPHANUM + ZeroOrMore(IDENTIFIER_END))\n\nNAME = IDENTIFIER(\"name\")\nEXTRA = IDENTIFIER\n\nURI = Regex(r\"[^ ]+\")(\"url\")\nURL = AT + URI\n\nEXTRAS_LIST = EXTRA + ZeroOrMore(COMMA + EXTRA)\nEXTRAS = (LBRACKET + Optional(EXTRAS_LIST) + RBRACKET)(\"extras\")\n\nVERSION_PEP440 = Regex(Specifier._regex_str, re.VERBOSE | re.IGNORECASE)\nVERSION_LEGACY = Regex(LegacySpecifier._regex_str, re.VERBOSE | re.IGNORECASE)\n\nVERSION_ONE = VERSION_PEP440 ^ VERSION_LEGACY\nVERSION_MANY = Combine(\n    VERSION_ONE + ZeroOrMore(COMMA + VERSION_ONE), joinString=\",\", adjacent=False\n)(\"_raw_spec\")\n_VERSION_SPEC = Optional((LPAREN + VERSION_MANY + RPAREN) | VERSION_MANY)\n_VERSION_SPEC.setParseAction(lambda s, l, t: t._raw_spec or \"\")\n\nVERSION_SPEC = originalTextFor(_VERSION_SPEC)(\"specifier\")\nVERSION_SPEC.setParseAction(lambda s, l, t: t[1])\n\nMARKER_EXPR = originalTextFor(MARKER_EXPR())(\"marker\")\nMARKER_EXPR.setParseAction(\n    lambda s, l, t: Marker(s[t._original_start : t._original_end])\n)\nMARKER_SEPARATOR = SEMICOLON\nMARKER = MARKER_SEPARATOR + MARKER_EXPR\n\nVERSION_AND_MARKER = VERSION_SPEC + Optional(MARKER)\nURL_AND_MARKER = URL + Optional(MARKER)\n\nNAMED_REQUIREMENT = NAME + Optional(EXTRAS) + (URL_AND_MARKER | VERSION_AND_MARKER)\n\nREQUIREMENT = stringStart + NAMED_REQUIREMENT + stringEnd\n# pkg_resources.extern.pyparsing isn't thread safe during initialization, so we do it eagerly, see\n# issue #104\nREQUIREMENT.parseString(\"x[]\")\n\n\nclass Requirement:\n    \"\"\"Parse a requirement.\n\n    Parse a given requirement string into its parts, such as name, specifier,\n    URL, and extras. Raises InvalidRequirement on a badly-formed requirement\n    string.\n    \"\"\"\n\n    # TODO: Can we test whether something is contained within a requirement?\n    #       If so how do we do that? Do we need to test against the _name_ of\n    #       the thing as well as the version? What about the markers?\n    # TODO: Can we normalize the name and extra name?\n\n    def __init__(self, requirement_string: str) -> None:\n        try:\n            req = REQUIREMENT.parseString(requirement_string)\n        except ParseException as e:\n            raise InvalidRequirement(\n                f'Parse error at \"{ requirement_string[e.loc : e.loc + 8]!r}\": {e.msg}'\n            )\n\n        self.name: str = req.name\n        if req.url:\n            parsed_url = urllib.parse.urlparse(req.url)\n            if parsed_url.scheme == \"file\":\n                if urllib.parse.urlunparse(parsed_url) != req.url:\n                    raise InvalidRequirement(\"Invalid URL given\")\n            elif not (parsed_url.scheme and parsed_url.netloc) or (\n                not parsed_url.scheme and not parsed_url.netloc\n            ):\n                raise InvalidRequirement(f\"Invalid URL: {req.url}\")\n            self.url: TOptional[str] = req.url\n        else:\n            self.url = None\n        self.extras: Set[str] = set(req.extras.asList() if req.extras else [])\n        self.specifier: SpecifierSet = SpecifierSet(req.specifier)\n        self.marker: TOptional[Marker] = req.marker if req.marker else None\n\n    def __str__(self) -> str:\n        parts: List[str] = [self.name]\n\n        if self.extras:\n            formatted_extras = \",\".join(sorted(self.extras))\n            parts.append(f\"[{formatted_extras}]\")\n\n        if self.specifier:\n            parts.append(str(self.specifier))\n\n        if self.url:\n            parts.append(f\"@ {self.url}\")\n            if self.marker:\n                parts.append(\" \")\n\n        if self.marker:\n            parts.append(f\"; {self.marker}\")\n\n        return \"\".join(parts)\n\n    def __repr__(self) -> str:\n        return f\"<Requirement('{self}')>\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/packaging/specifiers.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport abc\nimport functools\nimport itertools\nimport re\nimport warnings\nfrom typing import (\n    Callable,\n    Dict,\n    Iterable,\n    Iterator,\n    List,\n    Optional,\n    Pattern,\n    Set,\n    Tuple,\n    TypeVar,\n    Union,\n)\n\nfrom .utils import canonicalize_version\nfrom .version import LegacyVersion, Version, parse\n\nParsedVersion = Union[Version, LegacyVersion]\nUnparsedVersion = Union[Version, LegacyVersion, str]\nVersionTypeVar = TypeVar(\"VersionTypeVar\", bound=UnparsedVersion)\nCallableOperator = Callable[[ParsedVersion, str], bool]\n\n\nclass InvalidSpecifier(ValueError):\n    \"\"\"\n    An invalid specifier was found, users should refer to PEP 440.\n    \"\"\"\n\n\nclass BaseSpecifier(metaclass=abc.ABCMeta):\n    @abc.abstractmethod\n    def __str__(self) -> str:\n        \"\"\"\n        Returns the str representation of this Specifier like object. This\n        should be representative of the Specifier itself.\n        \"\"\"\n\n    @abc.abstractmethod\n    def __hash__(self) -> int:\n        \"\"\"\n        Returns a hash value for this Specifier like object.\n        \"\"\"\n\n    @abc.abstractmethod\n    def __eq__(self, other: object) -> bool:\n        \"\"\"\n        Returns a boolean representing whether or not the two Specifier like\n        objects are equal.\n        \"\"\"\n\n    @abc.abstractproperty\n    def prereleases(self) -> Optional[bool]:\n        \"\"\"\n        Returns whether or not pre-releases as a whole are allowed by this\n        specifier.\n        \"\"\"\n\n    @prereleases.setter\n    def prereleases(self, value: bool) -> None:\n        \"\"\"\n        Sets whether or not pre-releases as a whole are allowed by this\n        specifier.\n        \"\"\"\n\n    @abc.abstractmethod\n    def contains(self, item: str, prereleases: Optional[bool] = None) -> bool:\n        \"\"\"\n        Determines if the given item is contained within this specifier.\n        \"\"\"\n\n    @abc.abstractmethod\n    def filter(\n        self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None\n    ) -> Iterable[VersionTypeVar]:\n        \"\"\"\n        Takes an iterable of items and filters them so that only items which\n        are contained within this specifier are allowed in it.\n        \"\"\"\n\n\nclass _IndividualSpecifier(BaseSpecifier):\n\n    _operators: Dict[str, str] = {}\n    _regex: Pattern[str]\n\n    def __init__(self, spec: str = \"\", prereleases: Optional[bool] = None) -> None:\n        match = self._regex.search(spec)\n        if not match:\n            raise InvalidSpecifier(f\"Invalid specifier: '{spec}'\")\n\n        self._spec: Tuple[str, str] = (\n            match.group(\"operator\").strip(),\n            match.group(\"version\").strip(),\n        )\n\n        # Store whether or not this Specifier should accept prereleases\n        self._prereleases = prereleases\n\n    def __repr__(self) -> str:\n        pre = (\n            f\", prereleases={self.prereleases!r}\"\n            if self._prereleases is not None\n            else \"\"\n        )\n\n        return f\"<{self.__class__.__name__}({str(self)!r}{pre})>\"\n\n    def __str__(self) -> str:\n        return \"{}{}\".format(*self._spec)\n\n    @property\n    def _canonical_spec(self) -> Tuple[str, str]:\n        return self._spec[0], canonicalize_version(self._spec[1])\n\n    def __hash__(self) -> int:\n        return hash(self._canonical_spec)\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, str):\n            try:\n                other = self.__class__(str(other))\n            except InvalidSpecifier:\n                return NotImplemented\n        elif not isinstance(other, self.__class__):\n            return NotImplemented\n\n        return self._canonical_spec == other._canonical_spec\n\n    def _get_operator(self, op: str) -> CallableOperator:\n        operator_callable: CallableOperator = getattr(\n            self, f\"_compare_{self._operators[op]}\"\n        )\n        return operator_callable\n\n    def _coerce_version(self, version: UnparsedVersion) -> ParsedVersion:\n        if not isinstance(version, (LegacyVersion, Version)):\n            version = parse(version)\n        return version\n\n    @property\n    def operator(self) -> str:\n        return self._spec[0]\n\n    @property\n    def version(self) -> str:\n        return self._spec[1]\n\n    @property\n    def prereleases(self) -> Optional[bool]:\n        return self._prereleases\n\n    @prereleases.setter\n    def prereleases(self, value: bool) -> None:\n        self._prereleases = value\n\n    def __contains__(self, item: str) -> bool:\n        return self.contains(item)\n\n    def contains(\n        self, item: UnparsedVersion, prereleases: Optional[bool] = None\n    ) -> bool:\n\n        # Determine if prereleases are to be allowed or not.\n        if prereleases is None:\n            prereleases = self.prereleases\n\n        # Normalize item to a Version or LegacyVersion, this allows us to have\n        # a shortcut for ``\"2.0\" in Specifier(\">=2\")\n        normalized_item = self._coerce_version(item)\n\n        # Determine if we should be supporting prereleases in this specifier\n        # or not, if we do not support prereleases than we can short circuit\n        # logic if this version is a prereleases.\n        if normalized_item.is_prerelease and not prereleases:\n            return False\n\n        # Actually do the comparison to determine if this item is contained\n        # within this Specifier or not.\n        operator_callable: CallableOperator = self._get_operator(self.operator)\n        return operator_callable(normalized_item, self.version)\n\n    def filter(\n        self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None\n    ) -> Iterable[VersionTypeVar]:\n\n        yielded = False\n        found_prereleases = []\n\n        kw = {\"prereleases\": prereleases if prereleases is not None else True}\n\n        # Attempt to iterate over all the values in the iterable and if any of\n        # them match, yield them.\n        for version in iterable:\n            parsed_version = self._coerce_version(version)\n\n            if self.contains(parsed_version, **kw):\n                # If our version is a prerelease, and we were not set to allow\n                # prereleases, then we'll store it for later in case nothing\n                # else matches this specifier.\n                if parsed_version.is_prerelease and not (\n                    prereleases or self.prereleases\n                ):\n                    found_prereleases.append(version)\n                # Either this is not a prerelease, or we should have been\n                # accepting prereleases from the beginning.\n                else:\n                    yielded = True\n                    yield version\n\n        # Now that we've iterated over everything, determine if we've yielded\n        # any values, and if we have not and we have any prereleases stored up\n        # then we will go ahead and yield the prereleases.\n        if not yielded and found_prereleases:\n            for version in found_prereleases:\n                yield version\n\n\nclass LegacySpecifier(_IndividualSpecifier):\n\n    _regex_str = r\"\"\"\n        (?P<operator>(==|!=|<=|>=|<|>))\n        \\s*\n        (?P<version>\n            [^,;\\s)]* # Since this is a \"legacy\" specifier, and the version\n                      # string can be just about anything, we match everything\n                      # except for whitespace, a semi-colon for marker support,\n                      # a closing paren since versions can be enclosed in\n                      # them, and a comma since it's a version separator.\n        )\n        \"\"\"\n\n    _regex = re.compile(r\"^\\s*\" + _regex_str + r\"\\s*$\", re.VERBOSE | re.IGNORECASE)\n\n    _operators = {\n        \"==\": \"equal\",\n        \"!=\": \"not_equal\",\n        \"<=\": \"less_than_equal\",\n        \">=\": \"greater_than_equal\",\n        \"<\": \"less_than\",\n        \">\": \"greater_than\",\n    }\n\n    def __init__(self, spec: str = \"\", prereleases: Optional[bool] = None) -> None:\n        super().__init__(spec, prereleases)\n\n        warnings.warn(\n            \"Creating a LegacyVersion has been deprecated and will be \"\n            \"removed in the next major release\",\n            DeprecationWarning,\n        )\n\n    def _coerce_version(self, version: UnparsedVersion) -> LegacyVersion:\n        if not isinstance(version, LegacyVersion):\n            version = LegacyVersion(str(version))\n        return version\n\n    def _compare_equal(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective == self._coerce_version(spec)\n\n    def _compare_not_equal(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective != self._coerce_version(spec)\n\n    def _compare_less_than_equal(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective <= self._coerce_version(spec)\n\n    def _compare_greater_than_equal(\n        self, prospective: LegacyVersion, spec: str\n    ) -> bool:\n        return prospective >= self._coerce_version(spec)\n\n    def _compare_less_than(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective < self._coerce_version(spec)\n\n    def _compare_greater_than(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective > self._coerce_version(spec)\n\n\ndef _require_version_compare(\n    fn: Callable[[\"Specifier\", ParsedVersion, str], bool]\n) -> Callable[[\"Specifier\", ParsedVersion, str], bool]:\n    @functools.wraps(fn)\n    def wrapped(self: \"Specifier\", prospective: ParsedVersion, spec: str) -> bool:\n        if not isinstance(prospective, Version):\n            return False\n        return fn(self, prospective, spec)\n\n    return wrapped\n\n\nclass Specifier(_IndividualSpecifier):\n\n    _regex_str = r\"\"\"\n        (?P<operator>(~=|==|!=|<=|>=|<|>|===))\n        (?P<version>\n            (?:\n                # The identity operators allow for an escape hatch that will\n                # do an exact string match of the version you wish to install.\n                # This will not be parsed by PEP 440 and we cannot determine\n                # any semantic meaning from it. This operator is discouraged\n                # but included entirely as an escape hatch.\n                (?<====)  # Only match for the identity operator\n                \\s*\n                [^\\s]*    # We just match everything, except for whitespace\n                          # since we are only testing for strict identity.\n            )\n            |\n            (?:\n                # The (non)equality operators allow for wild card and local\n                # versions to be specified so we have to define these two\n                # operators separately to enable that.\n                (?<===|!=)            # Only match for equals and not equals\n\n                \\s*\n                v?\n                (?:[0-9]+!)?          # epoch\n                [0-9]+(?:\\.[0-9]+)*   # release\n                (?:                   # pre release\n                    [-_\\.]?\n                    (a|b|c|rc|alpha|beta|pre|preview)\n                    [-_\\.]?\n                    [0-9]*\n                )?\n                (?:                   # post release\n                    (?:-[0-9]+)|(?:[-_\\.]?(post|rev|r)[-_\\.]?[0-9]*)\n                )?\n\n                # You cannot use a wild card and a dev or local version\n                # together so group them with a | and make them optional.\n                (?:\n                    (?:[-_\\.]?dev[-_\\.]?[0-9]*)?         # dev release\n                    (?:\\+[a-z0-9]+(?:[-_\\.][a-z0-9]+)*)? # local\n                    |\n                    \\.\\*  # Wild card syntax of .*\n                )?\n            )\n            |\n            (?:\n                # The compatible operator requires at least two digits in the\n                # release segment.\n                (?<=~=)               # Only match for the compatible operator\n\n                \\s*\n                v?\n                (?:[0-9]+!)?          # epoch\n                [0-9]+(?:\\.[0-9]+)+   # release  (We have a + instead of a *)\n                (?:                   # pre release\n                    [-_\\.]?\n                    (a|b|c|rc|alpha|beta|pre|preview)\n                    [-_\\.]?\n                    [0-9]*\n                )?\n                (?:                                   # post release\n                    (?:-[0-9]+)|(?:[-_\\.]?(post|rev|r)[-_\\.]?[0-9]*)\n                )?\n                (?:[-_\\.]?dev[-_\\.]?[0-9]*)?          # dev release\n            )\n            |\n            (?:\n                # All other operators only allow a sub set of what the\n                # (non)equality operators do. Specifically they do not allow\n                # local versions to be specified nor do they allow the prefix\n                # matching wild cards.\n                (?<!==|!=|~=)         # We have special cases for these\n                                      # operators so we want to make sure they\n                                      # don't match here.\n\n                \\s*\n                v?\n                (?:[0-9]+!)?          # epoch\n                [0-9]+(?:\\.[0-9]+)*   # release\n                (?:                   # pre release\n                    [-_\\.]?\n                    (a|b|c|rc|alpha|beta|pre|preview)\n                    [-_\\.]?\n                    [0-9]*\n                )?\n                (?:                                   # post release\n                    (?:-[0-9]+)|(?:[-_\\.]?(post|rev|r)[-_\\.]?[0-9]*)\n                )?\n                (?:[-_\\.]?dev[-_\\.]?[0-9]*)?          # dev release\n            )\n        )\n        \"\"\"\n\n    _regex = re.compile(r\"^\\s*\" + _regex_str + r\"\\s*$\", re.VERBOSE | re.IGNORECASE)\n\n    _operators = {\n        \"~=\": \"compatible\",\n        \"==\": \"equal\",\n        \"!=\": \"not_equal\",\n        \"<=\": \"less_than_equal\",\n        \">=\": \"greater_than_equal\",\n        \"<\": \"less_than\",\n        \">\": \"greater_than\",\n        \"===\": \"arbitrary\",\n    }\n\n    @_require_version_compare\n    def _compare_compatible(self, prospective: ParsedVersion, spec: str) -> bool:\n\n        # Compatible releases have an equivalent combination of >= and ==. That\n        # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to\n        # implement this in terms of the other specifiers instead of\n        # implementing it ourselves. The only thing we need to do is construct\n        # the other specifiers.\n\n        # We want everything but the last item in the version, but we want to\n        # ignore suffix segments.\n        prefix = \".\".join(\n            list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1]\n        )\n\n        # Add the prefix notation to the end of our string\n        prefix += \".*\"\n\n        return self._get_operator(\">=\")(prospective, spec) and self._get_operator(\"==\")(\n            prospective, prefix\n        )\n\n    @_require_version_compare\n    def _compare_equal(self, prospective: ParsedVersion, spec: str) -> bool:\n\n        # We need special logic to handle prefix matching\n        if spec.endswith(\".*\"):\n            # In the case of prefix matching we want to ignore local segment.\n            prospective = Version(prospective.public)\n            # Split the spec out by dots, and pretend that there is an implicit\n            # dot in between a release segment and a pre-release segment.\n            split_spec = _version_split(spec[:-2])  # Remove the trailing .*\n\n            # Split the prospective version out by dots, and pretend that there\n            # is an implicit dot in between a release segment and a pre-release\n            # segment.\n            split_prospective = _version_split(str(prospective))\n\n            # Shorten the prospective version to be the same length as the spec\n            # so that we can determine if the specifier is a prefix of the\n            # prospective version or not.\n            shortened_prospective = split_prospective[: len(split_spec)]\n\n            # Pad out our two sides with zeros so that they both equal the same\n            # length.\n            padded_spec, padded_prospective = _pad_version(\n                split_spec, shortened_prospective\n            )\n\n            return padded_prospective == padded_spec\n        else:\n            # Convert our spec string into a Version\n            spec_version = Version(spec)\n\n            # If the specifier does not have a local segment, then we want to\n            # act as if the prospective version also does not have a local\n            # segment.\n            if not spec_version.local:\n                prospective = Version(prospective.public)\n\n            return prospective == spec_version\n\n    @_require_version_compare\n    def _compare_not_equal(self, prospective: ParsedVersion, spec: str) -> bool:\n        return not self._compare_equal(prospective, spec)\n\n    @_require_version_compare\n    def _compare_less_than_equal(self, prospective: ParsedVersion, spec: str) -> bool:\n\n        # NB: Local version identifiers are NOT permitted in the version\n        # specifier, so local version labels can be universally removed from\n        # the prospective version.\n        return Version(prospective.public) <= Version(spec)\n\n    @_require_version_compare\n    def _compare_greater_than_equal(\n        self, prospective: ParsedVersion, spec: str\n    ) -> bool:\n\n        # NB: Local version identifiers are NOT permitted in the version\n        # specifier, so local version labels can be universally removed from\n        # the prospective version.\n        return Version(prospective.public) >= Version(spec)\n\n    @_require_version_compare\n    def _compare_less_than(self, prospective: ParsedVersion, spec_str: str) -> bool:\n\n        # Convert our spec to a Version instance, since we'll want to work with\n        # it as a version.\n        spec = Version(spec_str)\n\n        # Check to see if the prospective version is less than the spec\n        # version. If it's not we can short circuit and just return False now\n        # instead of doing extra unneeded work.\n        if not prospective < spec:\n            return False\n\n        # This special case is here so that, unless the specifier itself\n        # includes is a pre-release version, that we do not accept pre-release\n        # versions for the version mentioned in the specifier (e.g. <3.1 should\n        # not match 3.1.dev0, but should match 3.0.dev0).\n        if not spec.is_prerelease and prospective.is_prerelease:\n            if Version(prospective.base_version) == Version(spec.base_version):\n                return False\n\n        # If we've gotten to here, it means that prospective version is both\n        # less than the spec version *and* it's not a pre-release of the same\n        # version in the spec.\n        return True\n\n    @_require_version_compare\n    def _compare_greater_than(self, prospective: ParsedVersion, spec_str: str) -> bool:\n\n        # Convert our spec to a Version instance, since we'll want to work with\n        # it as a version.\n        spec = Version(spec_str)\n\n        # Check to see if the prospective version is greater than the spec\n        # version. If it's not we can short circuit and just return False now\n        # instead of doing extra unneeded work.\n        if not prospective > spec:\n            return False\n\n        # This special case is here so that, unless the specifier itself\n        # includes is a post-release version, that we do not accept\n        # post-release versions for the version mentioned in the specifier\n        # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).\n        if not spec.is_postrelease and prospective.is_postrelease:\n            if Version(prospective.base_version) == Version(spec.base_version):\n                return False\n\n        # Ensure that we do not allow a local version of the version mentioned\n        # in the specifier, which is technically greater than, to match.\n        if prospective.local is not None:\n            if Version(prospective.base_version) == Version(spec.base_version):\n                return False\n\n        # If we've gotten to here, it means that prospective version is both\n        # greater than the spec version *and* it's not a pre-release of the\n        # same version in the spec.\n        return True\n\n    def _compare_arbitrary(self, prospective: Version, spec: str) -> bool:\n        return str(prospective).lower() == str(spec).lower()\n\n    @property\n    def prereleases(self) -> bool:\n\n        # If there is an explicit prereleases set for this, then we'll just\n        # blindly use that.\n        if self._prereleases is not None:\n            return self._prereleases\n\n        # Look at all of our specifiers and determine if they are inclusive\n        # operators, and if they are if they are including an explicit\n        # prerelease.\n        operator, version = self._spec\n        if operator in [\"==\", \">=\", \"<=\", \"~=\", \"===\"]:\n            # The == specifier can include a trailing .*, if it does we\n            # want to remove before parsing.\n            if operator == \"==\" and version.endswith(\".*\"):\n                version = version[:-2]\n\n            # Parse the version, and if it is a pre-release than this\n            # specifier allows pre-releases.\n            if parse(version).is_prerelease:\n                return True\n\n        return False\n\n    @prereleases.setter\n    def prereleases(self, value: bool) -> None:\n        self._prereleases = value\n\n\n_prefix_regex = re.compile(r\"^([0-9]+)((?:a|b|c|rc)[0-9]+)$\")\n\n\ndef _version_split(version: str) -> List[str]:\n    result: List[str] = []\n    for item in version.split(\".\"):\n        match = _prefix_regex.search(item)\n        if match:\n            result.extend(match.groups())\n        else:\n            result.append(item)\n    return result\n\n\ndef _is_not_suffix(segment: str) -> bool:\n    return not any(\n        segment.startswith(prefix) for prefix in (\"dev\", \"a\", \"b\", \"rc\", \"post\")\n    )\n\n\ndef _pad_version(left: List[str], right: List[str]) -> Tuple[List[str], List[str]]:\n    left_split, right_split = [], []\n\n    # Get the release segment of our versions\n    left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left)))\n    right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right)))\n\n    # Get the rest of our versions\n    left_split.append(left[len(left_split[0]) :])\n    right_split.append(right[len(right_split[0]) :])\n\n    # Insert our padding\n    left_split.insert(1, [\"0\"] * max(0, len(right_split[0]) - len(left_split[0])))\n    right_split.insert(1, [\"0\"] * max(0, len(left_split[0]) - len(right_split[0])))\n\n    return (list(itertools.chain(*left_split)), list(itertools.chain(*right_split)))\n\n\nclass SpecifierSet(BaseSpecifier):\n    def __init__(\n        self, specifiers: str = \"\", prereleases: Optional[bool] = None\n    ) -> None:\n\n        # Split on , to break each individual specifier into it's own item, and\n        # strip each item to remove leading/trailing whitespace.\n        split_specifiers = [s.strip() for s in specifiers.split(\",\") if s.strip()]\n\n        # Parsed each individual specifier, attempting first to make it a\n        # Specifier and falling back to a LegacySpecifier.\n        parsed: Set[_IndividualSpecifier] = set()\n        for specifier in split_specifiers:\n            try:\n                parsed.add(Specifier(specifier))\n            except InvalidSpecifier:\n                parsed.add(LegacySpecifier(specifier))\n\n        # Turn our parsed specifiers into a frozen set and save them for later.\n        self._specs = frozenset(parsed)\n\n        # Store our prereleases value so we can use it later to determine if\n        # we accept prereleases or not.\n        self._prereleases = prereleases\n\n    def __repr__(self) -> str:\n        pre = (\n            f\", prereleases={self.prereleases!r}\"\n            if self._prereleases is not None\n            else \"\"\n        )\n\n        return f\"<SpecifierSet({str(self)!r}{pre})>\"\n\n    def __str__(self) -> str:\n        return \",\".join(sorted(str(s) for s in self._specs))\n\n    def __hash__(self) -> int:\n        return hash(self._specs)\n\n    def __and__(self, other: Union[\"SpecifierSet\", str]) -> \"SpecifierSet\":\n        if isinstance(other, str):\n            other = SpecifierSet(other)\n        elif not isinstance(other, SpecifierSet):\n            return NotImplemented\n\n        specifier = SpecifierSet()\n        specifier._specs = frozenset(self._specs | other._specs)\n\n        if self._prereleases is None and other._prereleases is not None:\n            specifier._prereleases = other._prereleases\n        elif self._prereleases is not None and other._prereleases is None:\n            specifier._prereleases = self._prereleases\n        elif self._prereleases == other._prereleases:\n            specifier._prereleases = self._prereleases\n        else:\n            raise ValueError(\n                \"Cannot combine SpecifierSets with True and False prerelease \"\n                \"overrides.\"\n            )\n\n        return specifier\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, (str, _IndividualSpecifier)):\n            other = SpecifierSet(str(other))\n        elif not isinstance(other, SpecifierSet):\n            return NotImplemented\n\n        return self._specs == other._specs\n\n    def __len__(self) -> int:\n        return len(self._specs)\n\n    def __iter__(self) -> Iterator[_IndividualSpecifier]:\n        return iter(self._specs)\n\n    @property\n    def prereleases(self) -> Optional[bool]:\n\n        # If we have been given an explicit prerelease modifier, then we'll\n        # pass that through here.\n        if self._prereleases is not None:\n            return self._prereleases\n\n        # If we don't have any specifiers, and we don't have a forced value,\n        # then we'll just return None since we don't know if this should have\n        # pre-releases or not.\n        if not self._specs:\n            return None\n\n        # Otherwise we'll see if any of the given specifiers accept\n        # prereleases, if any of them do we'll return True, otherwise False.\n        return any(s.prereleases for s in self._specs)\n\n    @prereleases.setter\n    def prereleases(self, value: bool) -> None:\n        self._prereleases = value\n\n    def __contains__(self, item: UnparsedVersion) -> bool:\n        return self.contains(item)\n\n    def contains(\n        self, item: UnparsedVersion, prereleases: Optional[bool] = None\n    ) -> bool:\n\n        # Ensure that our item is a Version or LegacyVersion instance.\n        if not isinstance(item, (LegacyVersion, Version)):\n            item = parse(item)\n\n        # Determine if we're forcing a prerelease or not, if we're not forcing\n        # one for this particular filter call, then we'll use whatever the\n        # SpecifierSet thinks for whether or not we should support prereleases.\n        if prereleases is None:\n            prereleases = self.prereleases\n\n        # We can determine if we're going to allow pre-releases by looking to\n        # see if any of the underlying items supports them. If none of them do\n        # and this item is a pre-release then we do not allow it and we can\n        # short circuit that here.\n        # Note: This means that 1.0.dev1 would not be contained in something\n        #       like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0\n        if not prereleases and item.is_prerelease:\n            return False\n\n        # We simply dispatch to the underlying specs here to make sure that the\n        # given version is contained within all of them.\n        # Note: This use of all() here means that an empty set of specifiers\n        #       will always return True, this is an explicit design decision.\n        return all(s.contains(item, prereleases=prereleases) for s in self._specs)\n\n    def filter(\n        self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None\n    ) -> Iterable[VersionTypeVar]:\n\n        # Determine if we're forcing a prerelease or not, if we're not forcing\n        # one for this particular filter call, then we'll use whatever the\n        # SpecifierSet thinks for whether or not we should support prereleases.\n        if prereleases is None:\n            prereleases = self.prereleases\n\n        # If we have any specifiers, then we want to wrap our iterable in the\n        # filter method for each one, this will act as a logical AND amongst\n        # each specifier.\n        if self._specs:\n            for spec in self._specs:\n                iterable = spec.filter(iterable, prereleases=bool(prereleases))\n            return iterable\n        # If we do not have any specifiers, then we need to have a rough filter\n        # which will filter out any pre-releases, unless there are no final\n        # releases, and which will filter out LegacyVersion in general.\n        else:\n            filtered: List[VersionTypeVar] = []\n            found_prereleases: List[VersionTypeVar] = []\n\n            item: UnparsedVersion\n            parsed_version: Union[Version, LegacyVersion]\n\n            for item in iterable:\n                # Ensure that we some kind of Version class for this item.\n                if not isinstance(item, (LegacyVersion, Version)):\n                    parsed_version = parse(item)\n                else:\n                    parsed_version = item\n\n                # Filter out any item which is parsed as a LegacyVersion\n                if isinstance(parsed_version, LegacyVersion):\n                    continue\n\n                # Store any item which is a pre-release for later unless we've\n                # already found a final version or we are accepting prereleases\n                if parsed_version.is_prerelease and not prereleases:\n                    if not filtered:\n                        found_prereleases.append(item)\n                else:\n                    filtered.append(item)\n\n            # If we've found no items except for pre-releases, then we'll go\n            # ahead and use the pre-releases\n            if not filtered and found_prereleases and prereleases is None:\n                return found_prereleases\n\n            return filtered\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/packaging/tags.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport logging\nimport platform\nimport sys\nimport sysconfig\nfrom importlib.machinery import EXTENSION_SUFFIXES\nfrom typing import (\n    Dict,\n    FrozenSet,\n    Iterable,\n    Iterator,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n    cast,\n)\n\nfrom . import _manylinux, _musllinux\n\nlogger = logging.getLogger(__name__)\n\nPythonVersion = Sequence[int]\nMacVersion = Tuple[int, int]\n\nINTERPRETER_SHORT_NAMES: Dict[str, str] = {\n    \"python\": \"py\",  # Generic.\n    \"cpython\": \"cp\",\n    \"pypy\": \"pp\",\n    \"ironpython\": \"ip\",\n    \"jython\": \"jy\",\n}\n\n\n_32_BIT_INTERPRETER = sys.maxsize <= 2 ** 32\n\n\nclass Tag:\n    \"\"\"\n    A representation of the tag triple for a wheel.\n\n    Instances are considered immutable and thus are hashable. Equality checking\n    is also supported.\n    \"\"\"\n\n    __slots__ = [\"_interpreter\", \"_abi\", \"_platform\", \"_hash\"]\n\n    def __init__(self, interpreter: str, abi: str, platform: str) -> None:\n        self._interpreter = interpreter.lower()\n        self._abi = abi.lower()\n        self._platform = platform.lower()\n        # The __hash__ of every single element in a Set[Tag] will be evaluated each time\n        # that a set calls its `.disjoint()` method, which may be called hundreds of\n        # times when scanning a page of links for packages with tags matching that\n        # Set[Tag]. Pre-computing the value here produces significant speedups for\n        # downstream consumers.\n        self._hash = hash((self._interpreter, self._abi, self._platform))\n\n    @property\n    def interpreter(self) -> str:\n        return self._interpreter\n\n    @property\n    def abi(self) -> str:\n        return self._abi\n\n    @property\n    def platform(self) -> str:\n        return self._platform\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Tag):\n            return NotImplemented\n\n        return (\n            (self._hash == other._hash)  # Short-circuit ASAP for perf reasons.\n            and (self._platform == other._platform)\n            and (self._abi == other._abi)\n            and (self._interpreter == other._interpreter)\n        )\n\n    def __hash__(self) -> int:\n        return self._hash\n\n    def __str__(self) -> str:\n        return f\"{self._interpreter}-{self._abi}-{self._platform}\"\n\n    def __repr__(self) -> str:\n        return f\"<{self} @ {id(self)}>\"\n\n\ndef parse_tag(tag: str) -> FrozenSet[Tag]:\n    \"\"\"\n    Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.\n\n    Returning a set is required due to the possibility that the tag is a\n    compressed tag set.\n    \"\"\"\n    tags = set()\n    interpreters, abis, platforms = tag.split(\"-\")\n    for interpreter in interpreters.split(\".\"):\n        for abi in abis.split(\".\"):\n            for platform_ in platforms.split(\".\"):\n                tags.add(Tag(interpreter, abi, platform_))\n    return frozenset(tags)\n\n\ndef _get_config_var(name: str, warn: bool = False) -> Union[int, str, None]:\n    value = sysconfig.get_config_var(name)\n    if value is None and warn:\n        logger.debug(\n            \"Config variable '%s' is unset, Python ABI tag may be incorrect\", name\n        )\n    return value\n\n\ndef _normalize_string(string: str) -> str:\n    return string.replace(\".\", \"_\").replace(\"-\", \"_\")\n\n\ndef _abi3_applies(python_version: PythonVersion) -> bool:\n    \"\"\"\n    Determine if the Python version supports abi3.\n\n    PEP 384 was first implemented in Python 3.2.\n    \"\"\"\n    return len(python_version) > 1 and tuple(python_version) >= (3, 2)\n\n\ndef _cpython_abis(py_version: PythonVersion, warn: bool = False) -> List[str]:\n    py_version = tuple(py_version)  # To allow for version comparison.\n    abis = []\n    version = _version_nodot(py_version[:2])\n    debug = pymalloc = ucs4 = \"\"\n    with_debug = _get_config_var(\"Py_DEBUG\", warn)\n    has_refcount = hasattr(sys, \"gettotalrefcount\")\n    # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled\n    # extension modules is the best option.\n    # https://github.com/pypa/pip/issues/3383#issuecomment-173267692\n    has_ext = \"_d.pyd\" in EXTENSION_SUFFIXES\n    if with_debug or (with_debug is None and (has_refcount or has_ext)):\n        debug = \"d\"\n    if py_version < (3, 8):\n        with_pymalloc = _get_config_var(\"WITH_PYMALLOC\", warn)\n        if with_pymalloc or with_pymalloc is None:\n            pymalloc = \"m\"\n        if py_version < (3, 3):\n            unicode_size = _get_config_var(\"Py_UNICODE_SIZE\", warn)\n            if unicode_size == 4 or (\n                unicode_size is None and sys.maxunicode == 0x10FFFF\n            ):\n                ucs4 = \"u\"\n    elif debug:\n        # Debug builds can also load \"normal\" extension modules.\n        # We can also assume no UCS-4 or pymalloc requirement.\n        abis.append(f\"cp{version}\")\n    abis.insert(\n        0,\n        \"cp{version}{debug}{pymalloc}{ucs4}\".format(\n            version=version, debug=debug, pymalloc=pymalloc, ucs4=ucs4\n        ),\n    )\n    return abis\n\n\ndef cpython_tags(\n    python_version: Optional[PythonVersion] = None,\n    abis: Optional[Iterable[str]] = None,\n    platforms: Optional[Iterable[str]] = None,\n    *,\n    warn: bool = False,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the tags for a CPython interpreter.\n\n    The tags consist of:\n    - cp<python_version>-<abi>-<platform>\n    - cp<python_version>-abi3-<platform>\n    - cp<python_version>-none-<platform>\n    - cp<less than python_version>-abi3-<platform>  # Older Python versions down to 3.2.\n\n    If python_version only specifies a major version then user-provided ABIs and\n    the 'none' ABItag will be used.\n\n    If 'abi3' or 'none' are specified in 'abis' then they will be yielded at\n    their normal position and not at the beginning.\n    \"\"\"\n    if not python_version:\n        python_version = sys.version_info[:2]\n\n    interpreter = f\"cp{_version_nodot(python_version[:2])}\"\n\n    if abis is None:\n        if len(python_version) > 1:\n            abis = _cpython_abis(python_version, warn)\n        else:\n            abis = []\n    abis = list(abis)\n    # 'abi3' and 'none' are explicitly handled later.\n    for explicit_abi in (\"abi3\", \"none\"):\n        try:\n            abis.remove(explicit_abi)\n        except ValueError:\n            pass\n\n    platforms = list(platforms or platform_tags())\n    for abi in abis:\n        for platform_ in platforms:\n            yield Tag(interpreter, abi, platform_)\n    if _abi3_applies(python_version):\n        yield from (Tag(interpreter, \"abi3\", platform_) for platform_ in platforms)\n    yield from (Tag(interpreter, \"none\", platform_) for platform_ in platforms)\n\n    if _abi3_applies(python_version):\n        for minor_version in range(python_version[1] - 1, 1, -1):\n            for platform_ in platforms:\n                interpreter = \"cp{version}\".format(\n                    version=_version_nodot((python_version[0], minor_version))\n                )\n                yield Tag(interpreter, \"abi3\", platform_)\n\n\ndef _generic_abi() -> Iterator[str]:\n    abi = sysconfig.get_config_var(\"SOABI\")\n    if abi:\n        yield _normalize_string(abi)\n\n\ndef generic_tags(\n    interpreter: Optional[str] = None,\n    abis: Optional[Iterable[str]] = None,\n    platforms: Optional[Iterable[str]] = None,\n    *,\n    warn: bool = False,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the tags for a generic interpreter.\n\n    The tags consist of:\n    - <interpreter>-<abi>-<platform>\n\n    The \"none\" ABI will be added if it was not explicitly provided.\n    \"\"\"\n    if not interpreter:\n        interp_name = interpreter_name()\n        interp_version = interpreter_version(warn=warn)\n        interpreter = \"\".join([interp_name, interp_version])\n    if abis is None:\n        abis = _generic_abi()\n    platforms = list(platforms or platform_tags())\n    abis = list(abis)\n    if \"none\" not in abis:\n        abis.append(\"none\")\n    for abi in abis:\n        for platform_ in platforms:\n            yield Tag(interpreter, abi, platform_)\n\n\ndef _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]:\n    \"\"\"\n    Yields Python versions in descending order.\n\n    After the latest version, the major-only version will be yielded, and then\n    all previous versions of that major version.\n    \"\"\"\n    if len(py_version) > 1:\n        yield f\"py{_version_nodot(py_version[:2])}\"\n    yield f\"py{py_version[0]}\"\n    if len(py_version) > 1:\n        for minor in range(py_version[1] - 1, -1, -1):\n            yield f\"py{_version_nodot((py_version[0], minor))}\"\n\n\ndef compatible_tags(\n    python_version: Optional[PythonVersion] = None,\n    interpreter: Optional[str] = None,\n    platforms: Optional[Iterable[str]] = None,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the sequence of tags that are compatible with a specific version of Python.\n\n    The tags consist of:\n    - py*-none-<platform>\n    - <interpreter>-none-any  # ... if `interpreter` is provided.\n    - py*-none-any\n    \"\"\"\n    if not python_version:\n        python_version = sys.version_info[:2]\n    platforms = list(platforms or platform_tags())\n    for version in _py_interpreter_range(python_version):\n        for platform_ in platforms:\n            yield Tag(version, \"none\", platform_)\n    if interpreter:\n        yield Tag(interpreter, \"none\", \"any\")\n    for version in _py_interpreter_range(python_version):\n        yield Tag(version, \"none\", \"any\")\n\n\ndef _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str:\n    if not is_32bit:\n        return arch\n\n    if arch.startswith(\"ppc\"):\n        return \"ppc\"\n\n    return \"i386\"\n\n\ndef _mac_binary_formats(version: MacVersion, cpu_arch: str) -> List[str]:\n    formats = [cpu_arch]\n    if cpu_arch == \"x86_64\":\n        if version < (10, 4):\n            return []\n        formats.extend([\"intel\", \"fat64\", \"fat32\"])\n\n    elif cpu_arch == \"i386\":\n        if version < (10, 4):\n            return []\n        formats.extend([\"intel\", \"fat32\", \"fat\"])\n\n    elif cpu_arch == \"ppc64\":\n        # TODO: Need to care about 32-bit PPC for ppc64 through 10.2?\n        if version > (10, 5) or version < (10, 4):\n            return []\n        formats.append(\"fat64\")\n\n    elif cpu_arch == \"ppc\":\n        if version > (10, 6):\n            return []\n        formats.extend([\"fat32\", \"fat\"])\n\n    if cpu_arch in {\"arm64\", \"x86_64\"}:\n        formats.append(\"universal2\")\n\n    if cpu_arch in {\"x86_64\", \"i386\", \"ppc64\", \"ppc\", \"intel\"}:\n        formats.append(\"universal\")\n\n    return formats\n\n\ndef mac_platforms(\n    version: Optional[MacVersion] = None, arch: Optional[str] = None\n) -> Iterator[str]:\n    \"\"\"\n    Yields the platform tags for a macOS system.\n\n    The `version` parameter is a two-item tuple specifying the macOS version to\n    generate platform tags for. The `arch` parameter is the CPU architecture to\n    generate platform tags for. Both parameters default to the appropriate value\n    for the current system.\n    \"\"\"\n    version_str, _, cpu_arch = platform.mac_ver()\n    if version is None:\n        version = cast(\"MacVersion\", tuple(map(int, version_str.split(\".\")[:2])))\n    else:\n        version = version\n    if arch is None:\n        arch = _mac_arch(cpu_arch)\n    else:\n        arch = arch\n\n    if (10, 0) <= version and version < (11, 0):\n        # Prior to Mac OS 11, each yearly release of Mac OS bumped the\n        # \"minor\" version number.  The major version was always 10.\n        for minor_version in range(version[1], -1, -1):\n            compat_version = 10, minor_version\n            binary_formats = _mac_binary_formats(compat_version, arch)\n            for binary_format in binary_formats:\n                yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                    major=10, minor=minor_version, binary_format=binary_format\n                )\n\n    if version >= (11, 0):\n        # Starting with Mac OS 11, each yearly release bumps the major version\n        # number.   The minor versions are now the midyear updates.\n        for major_version in range(version[0], 10, -1):\n            compat_version = major_version, 0\n            binary_formats = _mac_binary_formats(compat_version, arch)\n            for binary_format in binary_formats:\n                yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                    major=major_version, minor=0, binary_format=binary_format\n                )\n\n    if version >= (11, 0):\n        # Mac OS 11 on x86_64 is compatible with binaries from previous releases.\n        # Arm64 support was introduced in 11.0, so no Arm binaries from previous\n        # releases exist.\n        #\n        # However, the \"universal2\" binary format can have a\n        # macOS version earlier than 11.0 when the x86_64 part of the binary supports\n        # that version of macOS.\n        if arch == \"x86_64\":\n            for minor_version in range(16, 3, -1):\n                compat_version = 10, minor_version\n                binary_formats = _mac_binary_formats(compat_version, arch)\n                for binary_format in binary_formats:\n                    yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                        major=compat_version[0],\n                        minor=compat_version[1],\n                        binary_format=binary_format,\n                    )\n        else:\n            for minor_version in range(16, 3, -1):\n                compat_version = 10, minor_version\n                binary_format = \"universal2\"\n                yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                    major=compat_version[0],\n                    minor=compat_version[1],\n                    binary_format=binary_format,\n                )\n\n\ndef _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]:\n    linux = _normalize_string(sysconfig.get_platform())\n    if is_32bit:\n        if linux == \"linux_x86_64\":\n            linux = \"linux_i686\"\n        elif linux == \"linux_aarch64\":\n            linux = \"linux_armv7l\"\n    _, arch = linux.split(\"_\", 1)\n    yield from _manylinux.platform_tags(linux, arch)\n    yield from _musllinux.platform_tags(arch)\n    yield linux\n\n\ndef _generic_platforms() -> Iterator[str]:\n    yield _normalize_string(sysconfig.get_platform())\n\n\ndef platform_tags() -> Iterator[str]:\n    \"\"\"\n    Provides the platform tags for this installation.\n    \"\"\"\n    if platform.system() == \"Darwin\":\n        return mac_platforms()\n    elif platform.system() == \"Linux\":\n        return _linux_platforms()\n    else:\n        return _generic_platforms()\n\n\ndef interpreter_name() -> str:\n    \"\"\"\n    Returns the name of the running interpreter.\n    \"\"\"\n    name = sys.implementation.name\n    return INTERPRETER_SHORT_NAMES.get(name) or name\n\n\ndef interpreter_version(*, warn: bool = False) -> str:\n    \"\"\"\n    Returns the version of the running interpreter.\n    \"\"\"\n    version = _get_config_var(\"py_version_nodot\", warn=warn)\n    if version:\n        version = str(version)\n    else:\n        version = _version_nodot(sys.version_info[:2])\n    return version\n\n\ndef _version_nodot(version: PythonVersion) -> str:\n    return \"\".join(map(str, version))\n\n\ndef sys_tags(*, warn: bool = False) -> Iterator[Tag]:\n    \"\"\"\n    Returns the sequence of tag triples for the running interpreter.\n\n    The order of the sequence corresponds to priority order for the\n    interpreter, from most to least important.\n    \"\"\"\n\n    interp_name = interpreter_name()\n    if interp_name == \"cp\":\n        yield from cpython_tags(warn=warn)\n    else:\n        yield from generic_tags()\n\n    if interp_name == \"pp\":\n        yield from compatible_tags(interpreter=\"pp3\")\n    else:\n        yield from compatible_tags()\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/packaging/utils.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport re\nfrom typing import FrozenSet, NewType, Tuple, Union, cast\n\nfrom .tags import Tag, parse_tag\nfrom .version import InvalidVersion, Version\n\nBuildTag = Union[Tuple[()], Tuple[int, str]]\nNormalizedName = NewType(\"NormalizedName\", str)\n\n\nclass InvalidWheelFilename(ValueError):\n    \"\"\"\n    An invalid wheel filename was found, users should refer to PEP 427.\n    \"\"\"\n\n\nclass InvalidSdistFilename(ValueError):\n    \"\"\"\n    An invalid sdist filename was found, users should refer to the packaging user guide.\n    \"\"\"\n\n\n_canonicalize_regex = re.compile(r\"[-_.]+\")\n# PEP 427: The build number must start with a digit.\n_build_tag_regex = re.compile(r\"(\\d+)(.*)\")\n\n\ndef canonicalize_name(name: str) -> NormalizedName:\n    # This is taken from PEP 503.\n    value = _canonicalize_regex.sub(\"-\", name).lower()\n    return cast(NormalizedName, value)\n\n\ndef canonicalize_version(version: Union[Version, str]) -> str:\n    \"\"\"\n    This is very similar to Version.__str__, but has one subtle difference\n    with the way it handles the release segment.\n    \"\"\"\n    if isinstance(version, str):\n        try:\n            parsed = Version(version)\n        except InvalidVersion:\n            # Legacy versions cannot be normalized\n            return version\n    else:\n        parsed = version\n\n    parts = []\n\n    # Epoch\n    if parsed.epoch != 0:\n        parts.append(f\"{parsed.epoch}!\")\n\n    # Release segment\n    # NB: This strips trailing '.0's to normalize\n    parts.append(re.sub(r\"(\\.0)+$\", \"\", \".\".join(str(x) for x in parsed.release)))\n\n    # Pre-release\n    if parsed.pre is not None:\n        parts.append(\"\".join(str(x) for x in parsed.pre))\n\n    # Post-release\n    if parsed.post is not None:\n        parts.append(f\".post{parsed.post}\")\n\n    # Development release\n    if parsed.dev is not None:\n        parts.append(f\".dev{parsed.dev}\")\n\n    # Local version segment\n    if parsed.local is not None:\n        parts.append(f\"+{parsed.local}\")\n\n    return \"\".join(parts)\n\n\ndef parse_wheel_filename(\n    filename: str,\n) -> Tuple[NormalizedName, Version, BuildTag, FrozenSet[Tag]]:\n    if not filename.endswith(\".whl\"):\n        raise InvalidWheelFilename(\n            f\"Invalid wheel filename (extension must be '.whl'): {filename}\"\n        )\n\n    filename = filename[:-4]\n    dashes = filename.count(\"-\")\n    if dashes not in (4, 5):\n        raise InvalidWheelFilename(\n            f\"Invalid wheel filename (wrong number of parts): {filename}\"\n        )\n\n    parts = filename.split(\"-\", dashes - 2)\n    name_part = parts[0]\n    # See PEP 427 for the rules on escaping the project name\n    if \"__\" in name_part or re.match(r\"^[\\w\\d._]*$\", name_part, re.UNICODE) is None:\n        raise InvalidWheelFilename(f\"Invalid project name: {filename}\")\n    name = canonicalize_name(name_part)\n    version = Version(parts[1])\n    if dashes == 5:\n        build_part = parts[2]\n        build_match = _build_tag_regex.match(build_part)\n        if build_match is None:\n            raise InvalidWheelFilename(\n                f\"Invalid build number: {build_part} in '{filename}'\"\n            )\n        build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2)))\n    else:\n        build = ()\n    tags = parse_tag(parts[-1])\n    return (name, version, build, tags)\n\n\ndef parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]:\n    if filename.endswith(\".tar.gz\"):\n        file_stem = filename[: -len(\".tar.gz\")]\n    elif filename.endswith(\".zip\"):\n        file_stem = filename[: -len(\".zip\")]\n    else:\n        raise InvalidSdistFilename(\n            f\"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):\"\n            f\" {filename}\"\n        )\n\n    # We are requiring a PEP 440 version, which cannot contain dashes,\n    # so we split on the last dash.\n    name_part, sep, version_part = file_stem.rpartition(\"-\")\n    if not sep:\n        raise InvalidSdistFilename(f\"Invalid sdist filename: {filename}\")\n\n    name = canonicalize_name(name_part)\n    version = Version(version_part)\n    return (name, version)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/packaging/version.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport collections\nimport itertools\nimport re\nimport warnings\nfrom typing import Callable, Iterator, List, Optional, SupportsInt, Tuple, Union\n\nfrom ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType\n\n__all__ = [\"parse\", \"Version\", \"LegacyVersion\", \"InvalidVersion\", \"VERSION_PATTERN\"]\n\nInfiniteTypes = Union[InfinityType, NegativeInfinityType]\nPrePostDevType = Union[InfiniteTypes, Tuple[str, int]]\nSubLocalType = Union[InfiniteTypes, int, str]\nLocalType = Union[\n    NegativeInfinityType,\n    Tuple[\n        Union[\n            SubLocalType,\n            Tuple[SubLocalType, str],\n            Tuple[NegativeInfinityType, SubLocalType],\n        ],\n        ...,\n    ],\n]\nCmpKey = Tuple[\n    int, Tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType\n]\nLegacyCmpKey = Tuple[int, Tuple[str, ...]]\nVersionComparisonMethod = Callable[\n    [Union[CmpKey, LegacyCmpKey], Union[CmpKey, LegacyCmpKey]], bool\n]\n\n_Version = collections.namedtuple(\n    \"_Version\", [\"epoch\", \"release\", \"dev\", \"pre\", \"post\", \"local\"]\n)\n\n\ndef parse(version: str) -> Union[\"LegacyVersion\", \"Version\"]:\n    \"\"\"\n    Parse the given version string and return either a :class:`Version` object\n    or a :class:`LegacyVersion` object depending on if the given version is\n    a valid PEP 440 version or a legacy version.\n    \"\"\"\n    try:\n        return Version(version)\n    except InvalidVersion:\n        return LegacyVersion(version)\n\n\nclass InvalidVersion(ValueError):\n    \"\"\"\n    An invalid version was found, users should refer to PEP 440.\n    \"\"\"\n\n\nclass _BaseVersion:\n    _key: Union[CmpKey, LegacyCmpKey]\n\n    def __hash__(self) -> int:\n        return hash(self._key)\n\n    # Please keep the duplicated `isinstance` check\n    # in the six comparisons hereunder\n    # unless you find a way to avoid adding overhead function calls.\n    def __lt__(self, other: \"_BaseVersion\") -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key < other._key\n\n    def __le__(self, other: \"_BaseVersion\") -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key <= other._key\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key == other._key\n\n    def __ge__(self, other: \"_BaseVersion\") -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key >= other._key\n\n    def __gt__(self, other: \"_BaseVersion\") -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key > other._key\n\n    def __ne__(self, other: object) -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key != other._key\n\n\nclass LegacyVersion(_BaseVersion):\n    def __init__(self, version: str) -> None:\n        self._version = str(version)\n        self._key = _legacy_cmpkey(self._version)\n\n        warnings.warn(\n            \"Creating a LegacyVersion has been deprecated and will be \"\n            \"removed in the next major release\",\n            DeprecationWarning,\n        )\n\n    def __str__(self) -> str:\n        return self._version\n\n    def __repr__(self) -> str:\n        return f\"<LegacyVersion('{self}')>\"\n\n    @property\n    def public(self) -> str:\n        return self._version\n\n    @property\n    def base_version(self) -> str:\n        return self._version\n\n    @property\n    def epoch(self) -> int:\n        return -1\n\n    @property\n    def release(self) -> None:\n        return None\n\n    @property\n    def pre(self) -> None:\n        return None\n\n    @property\n    def post(self) -> None:\n        return None\n\n    @property\n    def dev(self) -> None:\n        return None\n\n    @property\n    def local(self) -> None:\n        return None\n\n    @property\n    def is_prerelease(self) -> bool:\n        return False\n\n    @property\n    def is_postrelease(self) -> bool:\n        return False\n\n    @property\n    def is_devrelease(self) -> bool:\n        return False\n\n\n_legacy_version_component_re = re.compile(r\"(\\d+ | [a-z]+ | \\.| -)\", re.VERBOSE)\n\n_legacy_version_replacement_map = {\n    \"pre\": \"c\",\n    \"preview\": \"c\",\n    \"-\": \"final-\",\n    \"rc\": \"c\",\n    \"dev\": \"@\",\n}\n\n\ndef _parse_version_parts(s: str) -> Iterator[str]:\n    for part in _legacy_version_component_re.split(s):\n        part = _legacy_version_replacement_map.get(part, part)\n\n        if not part or part == \".\":\n            continue\n\n        if part[:1] in \"0123456789\":\n            # pad for numeric comparison\n            yield part.zfill(8)\n        else:\n            yield \"*\" + part\n\n    # ensure that alpha/beta/candidate are before final\n    yield \"*final\"\n\n\ndef _legacy_cmpkey(version: str) -> LegacyCmpKey:\n\n    # We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch\n    # greater than or equal to 0. This will effectively put the LegacyVersion,\n    # which uses the defacto standard originally implemented by setuptools,\n    # as before all PEP 440 versions.\n    epoch = -1\n\n    # This scheme is taken from pkg_resources.parse_version setuptools prior to\n    # it's adoption of the packaging library.\n    parts: List[str] = []\n    for part in _parse_version_parts(version.lower()):\n        if part.startswith(\"*\"):\n            # remove \"-\" before a prerelease tag\n            if part < \"*final\":\n                while parts and parts[-1] == \"*final-\":\n                    parts.pop()\n\n            # remove trailing zeros from each series of numeric parts\n            while parts and parts[-1] == \"00000000\":\n                parts.pop()\n\n        parts.append(part)\n\n    return epoch, tuple(parts)\n\n\n# Deliberately not anchored to the start and end of the string, to make it\n# easier for 3rd party code to reuse\nVERSION_PATTERN = r\"\"\"\n    v?\n    (?:\n        (?:(?P<epoch>[0-9]+)!)?                           # epoch\n        (?P<release>[0-9]+(?:\\.[0-9]+)*)                  # release segment\n        (?P<pre>                                          # pre-release\n            [-_\\.]?\n            (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))\n            [-_\\.]?\n            (?P<pre_n>[0-9]+)?\n        )?\n        (?P<post>                                         # post release\n            (?:-(?P<post_n1>[0-9]+))\n            |\n            (?:\n                [-_\\.]?\n                (?P<post_l>post|rev|r)\n                [-_\\.]?\n                (?P<post_n2>[0-9]+)?\n            )\n        )?\n        (?P<dev>                                          # dev release\n            [-_\\.]?\n            (?P<dev_l>dev)\n            [-_\\.]?\n            (?P<dev_n>[0-9]+)?\n        )?\n    )\n    (?:\\+(?P<local>[a-z0-9]+(?:[-_\\.][a-z0-9]+)*))?       # local version\n\"\"\"\n\n\nclass Version(_BaseVersion):\n\n    _regex = re.compile(r\"^\\s*\" + VERSION_PATTERN + r\"\\s*$\", re.VERBOSE | re.IGNORECASE)\n\n    def __init__(self, version: str) -> None:\n\n        # Validate the version and parse it into pieces\n        match = self._regex.search(version)\n        if not match:\n            raise InvalidVersion(f\"Invalid version: '{version}'\")\n\n        # Store the parsed out pieces of the version\n        self._version = _Version(\n            epoch=int(match.group(\"epoch\")) if match.group(\"epoch\") else 0,\n            release=tuple(int(i) for i in match.group(\"release\").split(\".\")),\n            pre=_parse_letter_version(match.group(\"pre_l\"), match.group(\"pre_n\")),\n            post=_parse_letter_version(\n                match.group(\"post_l\"), match.group(\"post_n1\") or match.group(\"post_n2\")\n            ),\n            dev=_parse_letter_version(match.group(\"dev_l\"), match.group(\"dev_n\")),\n            local=_parse_local_version(match.group(\"local\")),\n        )\n\n        # Generate a key which will be used for sorting\n        self._key = _cmpkey(\n            self._version.epoch,\n            self._version.release,\n            self._version.pre,\n            self._version.post,\n            self._version.dev,\n            self._version.local,\n        )\n\n    def __repr__(self) -> str:\n        return f\"<Version('{self}')>\"\n\n    def __str__(self) -> str:\n        parts = []\n\n        # Epoch\n        if self.epoch != 0:\n            parts.append(f\"{self.epoch}!\")\n\n        # Release segment\n        parts.append(\".\".join(str(x) for x in self.release))\n\n        # Pre-release\n        if self.pre is not None:\n            parts.append(\"\".join(str(x) for x in self.pre))\n\n        # Post-release\n        if self.post is not None:\n            parts.append(f\".post{self.post}\")\n\n        # Development release\n        if self.dev is not None:\n            parts.append(f\".dev{self.dev}\")\n\n        # Local version segment\n        if self.local is not None:\n            parts.append(f\"+{self.local}\")\n\n        return \"\".join(parts)\n\n    @property\n    def epoch(self) -> int:\n        _epoch: int = self._version.epoch\n        return _epoch\n\n    @property\n    def release(self) -> Tuple[int, ...]:\n        _release: Tuple[int, ...] = self._version.release\n        return _release\n\n    @property\n    def pre(self) -> Optional[Tuple[str, int]]:\n        _pre: Optional[Tuple[str, int]] = self._version.pre\n        return _pre\n\n    @property\n    def post(self) -> Optional[int]:\n        return self._version.post[1] if self._version.post else None\n\n    @property\n    def dev(self) -> Optional[int]:\n        return self._version.dev[1] if self._version.dev else None\n\n    @property\n    def local(self) -> Optional[str]:\n        if self._version.local:\n            return \".\".join(str(x) for x in self._version.local)\n        else:\n            return None\n\n    @property\n    def public(self) -> str:\n        return str(self).split(\"+\", 1)[0]\n\n    @property\n    def base_version(self) -> str:\n        parts = []\n\n        # Epoch\n        if self.epoch != 0:\n            parts.append(f\"{self.epoch}!\")\n\n        # Release segment\n        parts.append(\".\".join(str(x) for x in self.release))\n\n        return \"\".join(parts)\n\n    @property\n    def is_prerelease(self) -> bool:\n        return self.dev is not None or self.pre is not None\n\n    @property\n    def is_postrelease(self) -> bool:\n        return self.post is not None\n\n    @property\n    def is_devrelease(self) -> bool:\n        return self.dev is not None\n\n    @property\n    def major(self) -> int:\n        return self.release[0] if len(self.release) >= 1 else 0\n\n    @property\n    def minor(self) -> int:\n        return self.release[1] if len(self.release) >= 2 else 0\n\n    @property\n    def micro(self) -> int:\n        return self.release[2] if len(self.release) >= 3 else 0\n\n\ndef _parse_letter_version(\n    letter: str, number: Union[str, bytes, SupportsInt]\n) -> Optional[Tuple[str, int]]:\n\n    if letter:\n        # We consider there to be an implicit 0 in a pre-release if there is\n        # not a numeral associated with it.\n        if number is None:\n            number = 0\n\n        # We normalize any letters to their lower case form\n        letter = letter.lower()\n\n        # We consider some words to be alternate spellings of other words and\n        # in those cases we want to normalize the spellings to our preferred\n        # spelling.\n        if letter == \"alpha\":\n            letter = \"a\"\n        elif letter == \"beta\":\n            letter = \"b\"\n        elif letter in [\"c\", \"pre\", \"preview\"]:\n            letter = \"rc\"\n        elif letter in [\"rev\", \"r\"]:\n            letter = \"post\"\n\n        return letter, int(number)\n    if not letter and number:\n        # We assume if we are given a number, but we are not given a letter\n        # then this is using the implicit post release syntax (e.g. 1.0-1)\n        letter = \"post\"\n\n        return letter, int(number)\n\n    return None\n\n\n_local_version_separators = re.compile(r\"[\\._-]\")\n\n\ndef _parse_local_version(local: str) -> Optional[LocalType]:\n    \"\"\"\n    Takes a string like abc.1.twelve and turns it into (\"abc\", 1, \"twelve\").\n    \"\"\"\n    if local is not None:\n        return tuple(\n            part.lower() if not part.isdigit() else int(part)\n            for part in _local_version_separators.split(local)\n        )\n    return None\n\n\ndef _cmpkey(\n    epoch: int,\n    release: Tuple[int, ...],\n    pre: Optional[Tuple[str, int]],\n    post: Optional[Tuple[str, int]],\n    dev: Optional[Tuple[str, int]],\n    local: Optional[Tuple[SubLocalType]],\n) -> CmpKey:\n\n    # When we compare a release version, we want to compare it with all of the\n    # trailing zeros removed. So we'll use a reverse the list, drop all the now\n    # leading zeros until we come to something non zero, then take the rest\n    # re-reverse it back into the correct order and make it a tuple and use\n    # that for our sorting key.\n    _release = tuple(\n        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))\n    )\n\n    # We need to \"trick\" the sorting algorithm to put 1.0.dev0 before 1.0a0.\n    # We'll do this by abusing the pre segment, but we _only_ want to do this\n    # if there is not a pre or a post segment. If we have one of those then\n    # the normal sorting rules will handle this case correctly.\n    if pre is None and post is None and dev is not None:\n        _pre: PrePostDevType = NegativeInfinity\n    # Versions without a pre-release (except as noted above) should sort after\n    # those with one.\n    elif pre is None:\n        _pre = Infinity\n    else:\n        _pre = pre\n\n    # Versions without a post segment should sort before those with one.\n    if post is None:\n        _post: PrePostDevType = NegativeInfinity\n\n    else:\n        _post = post\n\n    # Versions without a development segment should sort after those with one.\n    if dev is None:\n        _dev: PrePostDevType = Infinity\n\n    else:\n        _dev = dev\n\n    if local is None:\n        # Versions without a local segment should sort before those with one.\n        _local: LocalType = NegativeInfinity\n    else:\n        # Versions with a local segment need that segment parsed to implement\n        # the sorting rules in PEP440.\n        # - Alpha numeric segments sort before numeric segments\n        # - Alpha numeric segments sort lexicographically\n        # - Numeric segments sort numerically\n        # - Shorter versions sort before longer versions when the prefixes\n        #   match exactly\n        _local = tuple(\n            (i, \"\") if isinstance(i, int) else (NegativeInfinity, i) for i in local\n        )\n\n    return epoch, _release, _pre, _post, _dev, _local\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing/__init__.py",
    "content": "# module pyparsing.py\n#\n# Copyright (c) 2003-2022  Paul T. McGuire\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n\n__doc__ = \"\"\"\npyparsing module - Classes and methods to define and execute parsing grammars\n=============================================================================\n\nThe pyparsing module is an alternative approach to creating and\nexecuting simple grammars, vs. the traditional lex/yacc approach, or the\nuse of regular expressions.  With pyparsing, you don't need to learn\na new syntax for defining grammars or matching expressions - the parsing\nmodule provides a library of classes that you use to construct the\ngrammar directly in Python.\n\nHere is a program to parse \"Hello, World!\" (or any greeting of the form\n``\"<salutation>, <addressee>!\"``), built up using :class:`Word`,\n:class:`Literal`, and :class:`And` elements\n(the :meth:`'+'<ParserElement.__add__>` operators create :class:`And` expressions,\nand the strings are auto-converted to :class:`Literal` expressions)::\n\n    from pyparsing import Word, alphas\n\n    # define grammar of a greeting\n    greet = Word(alphas) + \",\" + Word(alphas) + \"!\"\n\n    hello = \"Hello, World!\"\n    print(hello, \"->\", greet.parse_string(hello))\n\nThe program outputs the following::\n\n    Hello, World! -> ['Hello', ',', 'World', '!']\n\nThe Python representation of the grammar is quite readable, owing to the\nself-explanatory class names, and the use of :class:`'+'<And>`,\n:class:`'|'<MatchFirst>`, :class:`'^'<Or>` and :class:`'&'<Each>` operators.\n\nThe :class:`ParseResults` object returned from\n:class:`ParserElement.parseString` can be\naccessed as a nested list, a dictionary, or an object with named\nattributes.\n\nThe pyparsing module handles some of the problems that are typically\nvexing when writing text parsers:\n\n  - extra or missing whitespace (the above program will also handle\n    \"Hello,World!\", \"Hello  ,  World  !\", etc.)\n  - quoted strings\n  - embedded comments\n\n\nGetting Started -\n-----------------\nVisit the classes :class:`ParserElement` and :class:`ParseResults` to\nsee the base classes that most other pyparsing\nclasses inherit from. Use the docstrings for examples of how to:\n\n - construct literal match expressions from :class:`Literal` and\n   :class:`CaselessLiteral` classes\n - construct character word-group expressions using the :class:`Word`\n   class\n - see how to create repetitive expressions using :class:`ZeroOrMore`\n   and :class:`OneOrMore` classes\n - use :class:`'+'<And>`, :class:`'|'<MatchFirst>`, :class:`'^'<Or>`,\n   and :class:`'&'<Each>` operators to combine simple expressions into\n   more complex ones\n - associate names with your parsed results using\n   :class:`ParserElement.setResultsName`\n - access the parsed data, which is returned as a :class:`ParseResults`\n   object\n - find some helpful expression short-cuts like :class:`delimitedList`\n   and :class:`oneOf`\n - find more useful common expressions in the :class:`pyparsing_common`\n   namespace class\n\"\"\"\nfrom typing import NamedTuple\n\n\nclass version_info(NamedTuple):\n    major: int\n    minor: int\n    micro: int\n    releaselevel: str\n    serial: int\n\n    @property\n    def __version__(self):\n        return (\n            \"{}.{}.{}\".format(self.major, self.minor, self.micro)\n            + (\n                \"{}{}{}\".format(\n                    \"r\" if self.releaselevel[0] == \"c\" else \"\",\n                    self.releaselevel[0],\n                    self.serial,\n                ),\n                \"\",\n            )[self.releaselevel == \"final\"]\n        )\n\n    def __str__(self):\n        return \"{} {} / {}\".format(__name__, self.__version__, __version_time__)\n\n    def __repr__(self):\n        return \"{}.{}({})\".format(\n            __name__,\n            type(self).__name__,\n            \", \".join(\"{}={!r}\".format(*nv) for nv in zip(self._fields, self)),\n        )\n\n\n__version_info__ = version_info(3, 0, 9, \"final\", 0)\n__version_time__ = \"05 May 2022 07:02 UTC\"\n__version__ = __version_info__.__version__\n__versionTime__ = __version_time__\n__author__ = \"Paul McGuire <ptmcg.gm+pyparsing@gmail.com>\"\n\nfrom .util import *\nfrom .exceptions import *\nfrom .actions import *\nfrom .core import __diag__, __compat__\nfrom .results import *\nfrom .core import *\nfrom .core import _builtin_exprs as core_builtin_exprs\nfrom .helpers import *\nfrom .helpers import _builtin_exprs as helper_builtin_exprs\n\nfrom .unicode import unicode_set, UnicodeRangeList, pyparsing_unicode as unicode\nfrom .testing import pyparsing_test as testing\nfrom .common import (\n    pyparsing_common as common,\n    _builtin_exprs as common_builtin_exprs,\n)\n\n# define backward compat synonyms\nif \"pyparsing_unicode\" not in globals():\n    pyparsing_unicode = unicode\nif \"pyparsing_common\" not in globals():\n    pyparsing_common = common\nif \"pyparsing_test\" not in globals():\n    pyparsing_test = testing\n\ncore_builtin_exprs += common_builtin_exprs + helper_builtin_exprs\n\n\n__all__ = [\n    \"__version__\",\n    \"__version_time__\",\n    \"__author__\",\n    \"__compat__\",\n    \"__diag__\",\n    \"And\",\n    \"AtLineStart\",\n    \"AtStringStart\",\n    \"CaselessKeyword\",\n    \"CaselessLiteral\",\n    \"CharsNotIn\",\n    \"Combine\",\n    \"Dict\",\n    \"Each\",\n    \"Empty\",\n    \"FollowedBy\",\n    \"Forward\",\n    \"GoToColumn\",\n    \"Group\",\n    \"IndentedBlock\",\n    \"Keyword\",\n    \"LineEnd\",\n    \"LineStart\",\n    \"Literal\",\n    \"Located\",\n    \"PrecededBy\",\n    \"MatchFirst\",\n    \"NoMatch\",\n    \"NotAny\",\n    \"OneOrMore\",\n    \"OnlyOnce\",\n    \"OpAssoc\",\n    \"Opt\",\n    \"Optional\",\n    \"Or\",\n    \"ParseBaseException\",\n    \"ParseElementEnhance\",\n    \"ParseException\",\n    \"ParseExpression\",\n    \"ParseFatalException\",\n    \"ParseResults\",\n    \"ParseSyntaxException\",\n    \"ParserElement\",\n    \"PositionToken\",\n    \"QuotedString\",\n    \"RecursiveGrammarException\",\n    \"Regex\",\n    \"SkipTo\",\n    \"StringEnd\",\n    \"StringStart\",\n    \"Suppress\",\n    \"Token\",\n    \"TokenConverter\",\n    \"White\",\n    \"Word\",\n    \"WordEnd\",\n    \"WordStart\",\n    \"ZeroOrMore\",\n    \"Char\",\n    \"alphanums\",\n    \"alphas\",\n    \"alphas8bit\",\n    \"any_close_tag\",\n    \"any_open_tag\",\n    \"c_style_comment\",\n    \"col\",\n    \"common_html_entity\",\n    \"counted_array\",\n    \"cpp_style_comment\",\n    \"dbl_quoted_string\",\n    \"dbl_slash_comment\",\n    \"delimited_list\",\n    \"dict_of\",\n    \"empty\",\n    \"hexnums\",\n    \"html_comment\",\n    \"identchars\",\n    \"identbodychars\",\n    \"java_style_comment\",\n    \"line\",\n    \"line_end\",\n    \"line_start\",\n    \"lineno\",\n    \"make_html_tags\",\n    \"make_xml_tags\",\n    \"match_only_at_col\",\n    \"match_previous_expr\",\n    \"match_previous_literal\",\n    \"nested_expr\",\n    \"null_debug_action\",\n    \"nums\",\n    \"one_of\",\n    \"printables\",\n    \"punc8bit\",\n    \"python_style_comment\",\n    \"quoted_string\",\n    \"remove_quotes\",\n    \"replace_with\",\n    \"replace_html_entity\",\n    \"rest_of_line\",\n    \"sgl_quoted_string\",\n    \"srange\",\n    \"string_end\",\n    \"string_start\",\n    \"trace_parse_action\",\n    \"unicode_string\",\n    \"with_attribute\",\n    \"indentedBlock\",\n    \"original_text_for\",\n    \"ungroup\",\n    \"infix_notation\",\n    \"locatedExpr\",\n    \"with_class\",\n    \"CloseMatch\",\n    \"token_map\",\n    \"pyparsing_common\",\n    \"pyparsing_unicode\",\n    \"unicode_set\",\n    \"condition_as_parse_action\",\n    \"pyparsing_test\",\n    # pre-PEP8 compatibility names\n    \"__versionTime__\",\n    \"anyCloseTag\",\n    \"anyOpenTag\",\n    \"cStyleComment\",\n    \"commonHTMLEntity\",\n    \"countedArray\",\n    \"cppStyleComment\",\n    \"dblQuotedString\",\n    \"dblSlashComment\",\n    \"delimitedList\",\n    \"dictOf\",\n    \"htmlComment\",\n    \"javaStyleComment\",\n    \"lineEnd\",\n    \"lineStart\",\n    \"makeHTMLTags\",\n    \"makeXMLTags\",\n    \"matchOnlyAtCol\",\n    \"matchPreviousExpr\",\n    \"matchPreviousLiteral\",\n    \"nestedExpr\",\n    \"nullDebugAction\",\n    \"oneOf\",\n    \"opAssoc\",\n    \"pythonStyleComment\",\n    \"quotedString\",\n    \"removeQuotes\",\n    \"replaceHTMLEntity\",\n    \"replaceWith\",\n    \"restOfLine\",\n    \"sglQuotedString\",\n    \"stringEnd\",\n    \"stringStart\",\n    \"traceParseAction\",\n    \"unicodeString\",\n    \"withAttribute\",\n    \"indentedBlock\",\n    \"originalTextFor\",\n    \"infixNotation\",\n    \"locatedExpr\",\n    \"withClass\",\n    \"tokenMap\",\n    \"conditionAsParseAction\",\n    \"autoname_elements\",\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing/actions.py",
    "content": "# actions.py\n\nfrom .exceptions import ParseException\nfrom .util import col\n\n\nclass OnlyOnce:\n    \"\"\"\n    Wrapper for parse actions, to ensure they are only called once.\n    \"\"\"\n\n    def __init__(self, method_call):\n        from .core import _trim_arity\n\n        self.callable = _trim_arity(method_call)\n        self.called = False\n\n    def __call__(self, s, l, t):\n        if not self.called:\n            results = self.callable(s, l, t)\n            self.called = True\n            return results\n        raise ParseException(s, l, \"OnlyOnce obj called multiple times w/out reset\")\n\n    def reset(self):\n        \"\"\"\n        Allow the associated parse action to be called once more.\n        \"\"\"\n\n        self.called = False\n\n\ndef match_only_at_col(n):\n    \"\"\"\n    Helper method for defining parse actions that require matching at\n    a specific column in the input text.\n    \"\"\"\n\n    def verify_col(strg, locn, toks):\n        if col(locn, strg) != n:\n            raise ParseException(strg, locn, \"matched token not at column {}\".format(n))\n\n    return verify_col\n\n\ndef replace_with(repl_str):\n    \"\"\"\n    Helper method for common parse actions that simply return\n    a literal value.  Especially useful when used with\n    :class:`transform_string<ParserElement.transform_string>` ().\n\n    Example::\n\n        num = Word(nums).set_parse_action(lambda toks: int(toks[0]))\n        na = one_of(\"N/A NA\").set_parse_action(replace_with(math.nan))\n        term = na | num\n\n        term[1, ...].parse_string(\"324 234 N/A 234\") # -> [324, 234, nan, 234]\n    \"\"\"\n    return lambda s, l, t: [repl_str]\n\n\ndef remove_quotes(s, l, t):\n    \"\"\"\n    Helper parse action for removing quotation marks from parsed\n    quoted strings.\n\n    Example::\n\n        # by default, quotation marks are included in parsed results\n        quoted_string.parse_string(\"'Now is the Winter of our Discontent'\") # -> [\"'Now is the Winter of our Discontent'\"]\n\n        # use remove_quotes to strip quotation marks from parsed results\n        quoted_string.set_parse_action(remove_quotes)\n        quoted_string.parse_string(\"'Now is the Winter of our Discontent'\") # -> [\"Now is the Winter of our Discontent\"]\n    \"\"\"\n    return t[0][1:-1]\n\n\ndef with_attribute(*args, **attr_dict):\n    \"\"\"\n    Helper to create a validating parse action to be used with start\n    tags created with :class:`make_xml_tags` or\n    :class:`make_html_tags`. Use ``with_attribute`` to qualify\n    a starting tag with a required attribute value, to avoid false\n    matches on common tags such as ``<TD>`` or ``<DIV>``.\n\n    Call ``with_attribute`` with a series of attribute names and\n    values. Specify the list of filter attributes names and values as:\n\n    - keyword arguments, as in ``(align=\"right\")``, or\n    - as an explicit dict with ``**`` operator, when an attribute\n      name is also a Python reserved word, as in ``**{\"class\":\"Customer\", \"align\":\"right\"}``\n    - a list of name-value tuples, as in ``((\"ns1:class\", \"Customer\"), (\"ns2:align\", \"right\"))``\n\n    For attribute names with a namespace prefix, you must use the second\n    form.  Attribute names are matched insensitive to upper/lower case.\n\n    If just testing for ``class`` (with or without a namespace), use\n    :class:`with_class`.\n\n    To verify that the attribute exists, but without specifying a value,\n    pass ``with_attribute.ANY_VALUE`` as the value.\n\n    Example::\n\n        html = '''\n            <div>\n            Some text\n            <div type=\"grid\">1 4 0 1 0</div>\n            <div type=\"graph\">1,3 2,3 1,1</div>\n            <div>this has no type</div>\n            </div>\n\n        '''\n        div,div_end = make_html_tags(\"div\")\n\n        # only match div tag having a type attribute with value \"grid\"\n        div_grid = div().set_parse_action(with_attribute(type=\"grid\"))\n        grid_expr = div_grid + SkipTo(div | div_end)(\"body\")\n        for grid_header in grid_expr.search_string(html):\n            print(grid_header.body)\n\n        # construct a match with any div tag having a type attribute, regardless of the value\n        div_any_type = div().set_parse_action(with_attribute(type=with_attribute.ANY_VALUE))\n        div_expr = div_any_type + SkipTo(div | div_end)(\"body\")\n        for div_header in div_expr.search_string(html):\n            print(div_header.body)\n\n    prints::\n\n        1 4 0 1 0\n\n        1 4 0 1 0\n        1,3 2,3 1,1\n    \"\"\"\n    if args:\n        attrs = args[:]\n    else:\n        attrs = attr_dict.items()\n    attrs = [(k, v) for k, v in attrs]\n\n    def pa(s, l, tokens):\n        for attrName, attrValue in attrs:\n            if attrName not in tokens:\n                raise ParseException(s, l, \"no matching attribute \" + attrName)\n            if attrValue != with_attribute.ANY_VALUE and tokens[attrName] != attrValue:\n                raise ParseException(\n                    s,\n                    l,\n                    \"attribute {!r} has value {!r}, must be {!r}\".format(\n                        attrName, tokens[attrName], attrValue\n                    ),\n                )\n\n    return pa\n\n\nwith_attribute.ANY_VALUE = object()\n\n\ndef with_class(classname, namespace=\"\"):\n    \"\"\"\n    Simplified version of :class:`with_attribute` when\n    matching on a div class - made difficult because ``class`` is\n    a reserved word in Python.\n\n    Example::\n\n        html = '''\n            <div>\n            Some text\n            <div class=\"grid\">1 4 0 1 0</div>\n            <div class=\"graph\">1,3 2,3 1,1</div>\n            <div>this &lt;div&gt; has no class</div>\n            </div>\n\n        '''\n        div,div_end = make_html_tags(\"div\")\n        div_grid = div().set_parse_action(with_class(\"grid\"))\n\n        grid_expr = div_grid + SkipTo(div | div_end)(\"body\")\n        for grid_header in grid_expr.search_string(html):\n            print(grid_header.body)\n\n        div_any_type = div().set_parse_action(with_class(withAttribute.ANY_VALUE))\n        div_expr = div_any_type + SkipTo(div | div_end)(\"body\")\n        for div_header in div_expr.search_string(html):\n            print(div_header.body)\n\n    prints::\n\n        1 4 0 1 0\n\n        1 4 0 1 0\n        1,3 2,3 1,1\n    \"\"\"\n    classattr = \"{}:class\".format(namespace) if namespace else \"class\"\n    return with_attribute(**{classattr: classname})\n\n\n# pre-PEP8 compatibility symbols\nreplaceWith = replace_with\nremoveQuotes = remove_quotes\nwithAttribute = with_attribute\nwithClass = with_class\nmatchOnlyAtCol = match_only_at_col\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing/common.py",
    "content": "# common.py\nfrom .core import *\nfrom .helpers import delimited_list, any_open_tag, any_close_tag\nfrom datetime import datetime\n\n\n# some other useful expressions - using lower-case class name since we are really using this as a namespace\nclass pyparsing_common:\n    \"\"\"Here are some common low-level expressions that may be useful in\n    jump-starting parser development:\n\n    - numeric forms (:class:`integers<integer>`, :class:`reals<real>`,\n      :class:`scientific notation<sci_real>`)\n    - common :class:`programming identifiers<identifier>`\n    - network addresses (:class:`MAC<mac_address>`,\n      :class:`IPv4<ipv4_address>`, :class:`IPv6<ipv6_address>`)\n    - ISO8601 :class:`dates<iso8601_date>` and\n      :class:`datetime<iso8601_datetime>`\n    - :class:`UUID<uuid>`\n    - :class:`comma-separated list<comma_separated_list>`\n    - :class:`url`\n\n    Parse actions:\n\n    - :class:`convertToInteger`\n    - :class:`convertToFloat`\n    - :class:`convertToDate`\n    - :class:`convertToDatetime`\n    - :class:`stripHTMLTags`\n    - :class:`upcaseTokens`\n    - :class:`downcaseTokens`\n\n    Example::\n\n        pyparsing_common.number.runTests('''\n            # any int or real number, returned as the appropriate type\n            100\n            -100\n            +100\n            3.14159\n            6.02e23\n            1e-12\n            ''')\n\n        pyparsing_common.fnumber.runTests('''\n            # any int or real number, returned as float\n            100\n            -100\n            +100\n            3.14159\n            6.02e23\n            1e-12\n            ''')\n\n        pyparsing_common.hex_integer.runTests('''\n            # hex numbers\n            100\n            FF\n            ''')\n\n        pyparsing_common.fraction.runTests('''\n            # fractions\n            1/2\n            -3/4\n            ''')\n\n        pyparsing_common.mixed_integer.runTests('''\n            # mixed fractions\n            1\n            1/2\n            -3/4\n            1-3/4\n            ''')\n\n        import uuid\n        pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID))\n        pyparsing_common.uuid.runTests('''\n            # uuid\n            12345678-1234-5678-1234-567812345678\n            ''')\n\n    prints::\n\n        # any int or real number, returned as the appropriate type\n        100\n        [100]\n\n        -100\n        [-100]\n\n        +100\n        [100]\n\n        3.14159\n        [3.14159]\n\n        6.02e23\n        [6.02e+23]\n\n        1e-12\n        [1e-12]\n\n        # any int or real number, returned as float\n        100\n        [100.0]\n\n        -100\n        [-100.0]\n\n        +100\n        [100.0]\n\n        3.14159\n        [3.14159]\n\n        6.02e23\n        [6.02e+23]\n\n        1e-12\n        [1e-12]\n\n        # hex numbers\n        100\n        [256]\n\n        FF\n        [255]\n\n        # fractions\n        1/2\n        [0.5]\n\n        -3/4\n        [-0.75]\n\n        # mixed fractions\n        1\n        [1]\n\n        1/2\n        [0.5]\n\n        -3/4\n        [-0.75]\n\n        1-3/4\n        [1.75]\n\n        # uuid\n        12345678-1234-5678-1234-567812345678\n        [UUID('12345678-1234-5678-1234-567812345678')]\n    \"\"\"\n\n    convert_to_integer = token_map(int)\n    \"\"\"\n    Parse action for converting parsed integers to Python int\n    \"\"\"\n\n    convert_to_float = token_map(float)\n    \"\"\"\n    Parse action for converting parsed numbers to Python float\n    \"\"\"\n\n    integer = Word(nums).set_name(\"integer\").set_parse_action(convert_to_integer)\n    \"\"\"expression that parses an unsigned integer, returns an int\"\"\"\n\n    hex_integer = (\n        Word(hexnums).set_name(\"hex integer\").set_parse_action(token_map(int, 16))\n    )\n    \"\"\"expression that parses a hexadecimal integer, returns an int\"\"\"\n\n    signed_integer = (\n        Regex(r\"[+-]?\\d+\")\n        .set_name(\"signed integer\")\n        .set_parse_action(convert_to_integer)\n    )\n    \"\"\"expression that parses an integer with optional leading sign, returns an int\"\"\"\n\n    fraction = (\n        signed_integer().set_parse_action(convert_to_float)\n        + \"/\"\n        + signed_integer().set_parse_action(convert_to_float)\n    ).set_name(\"fraction\")\n    \"\"\"fractional expression of an integer divided by an integer, returns a float\"\"\"\n    fraction.add_parse_action(lambda tt: tt[0] / tt[-1])\n\n    mixed_integer = (\n        fraction | signed_integer + Opt(Opt(\"-\").suppress() + fraction)\n    ).set_name(\"fraction or mixed integer-fraction\")\n    \"\"\"mixed integer of the form 'integer - fraction', with optional leading integer, returns float\"\"\"\n    mixed_integer.add_parse_action(sum)\n\n    real = (\n        Regex(r\"[+-]?(?:\\d+\\.\\d*|\\.\\d+)\")\n        .set_name(\"real number\")\n        .set_parse_action(convert_to_float)\n    )\n    \"\"\"expression that parses a floating point number and returns a float\"\"\"\n\n    sci_real = (\n        Regex(r\"[+-]?(?:\\d+(?:[eE][+-]?\\d+)|(?:\\d+\\.\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?)\")\n        .set_name(\"real number with scientific notation\")\n        .set_parse_action(convert_to_float)\n    )\n    \"\"\"expression that parses a floating point number with optional\n    scientific notation and returns a float\"\"\"\n\n    # streamlining this expression makes the docs nicer-looking\n    number = (sci_real | real | signed_integer).setName(\"number\").streamline()\n    \"\"\"any numeric expression, returns the corresponding Python type\"\"\"\n\n    fnumber = (\n        Regex(r\"[+-]?\\d+\\.?\\d*([eE][+-]?\\d+)?\")\n        .set_name(\"fnumber\")\n        .set_parse_action(convert_to_float)\n    )\n    \"\"\"any int or real number, returned as float\"\"\"\n\n    identifier = Word(identchars, identbodychars).set_name(\"identifier\")\n    \"\"\"typical code identifier (leading alpha or '_', followed by 0 or more alphas, nums, or '_')\"\"\"\n\n    ipv4_address = Regex(\n        r\"(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}\"\n    ).set_name(\"IPv4 address\")\n    \"IPv4 address (``0.0.0.0 - 255.255.255.255``)\"\n\n    _ipv6_part = Regex(r\"[0-9a-fA-F]{1,4}\").set_name(\"hex_integer\")\n    _full_ipv6_address = (_ipv6_part + (\":\" + _ipv6_part) * 7).set_name(\n        \"full IPv6 address\"\n    )\n    _short_ipv6_address = (\n        Opt(_ipv6_part + (\":\" + _ipv6_part) * (0, 6))\n        + \"::\"\n        + Opt(_ipv6_part + (\":\" + _ipv6_part) * (0, 6))\n    ).set_name(\"short IPv6 address\")\n    _short_ipv6_address.add_condition(\n        lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8\n    )\n    _mixed_ipv6_address = (\"::ffff:\" + ipv4_address).set_name(\"mixed IPv6 address\")\n    ipv6_address = Combine(\n        (_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).set_name(\n            \"IPv6 address\"\n        )\n    ).set_name(\"IPv6 address\")\n    \"IPv6 address (long, short, or mixed form)\"\n\n    mac_address = Regex(\n        r\"[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\\1[0-9a-fA-F]{2}){4}\"\n    ).set_name(\"MAC address\")\n    \"MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)\"\n\n    @staticmethod\n    def convert_to_date(fmt: str = \"%Y-%m-%d\"):\n        \"\"\"\n        Helper to create a parse action for converting parsed date string to Python datetime.date\n\n        Params -\n        - fmt - format to be passed to datetime.strptime (default= ``\"%Y-%m-%d\"``)\n\n        Example::\n\n            date_expr = pyparsing_common.iso8601_date.copy()\n            date_expr.setParseAction(pyparsing_common.convertToDate())\n            print(date_expr.parseString(\"1999-12-31\"))\n\n        prints::\n\n            [datetime.date(1999, 12, 31)]\n        \"\"\"\n\n        def cvt_fn(ss, ll, tt):\n            try:\n                return datetime.strptime(tt[0], fmt).date()\n            except ValueError as ve:\n                raise ParseException(ss, ll, str(ve))\n\n        return cvt_fn\n\n    @staticmethod\n    def convert_to_datetime(fmt: str = \"%Y-%m-%dT%H:%M:%S.%f\"):\n        \"\"\"Helper to create a parse action for converting parsed\n        datetime string to Python datetime.datetime\n\n        Params -\n        - fmt - format to be passed to datetime.strptime (default= ``\"%Y-%m-%dT%H:%M:%S.%f\"``)\n\n        Example::\n\n            dt_expr = pyparsing_common.iso8601_datetime.copy()\n            dt_expr.setParseAction(pyparsing_common.convertToDatetime())\n            print(dt_expr.parseString(\"1999-12-31T23:59:59.999\"))\n\n        prints::\n\n            [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]\n        \"\"\"\n\n        def cvt_fn(s, l, t):\n            try:\n                return datetime.strptime(t[0], fmt)\n            except ValueError as ve:\n                raise ParseException(s, l, str(ve))\n\n        return cvt_fn\n\n    iso8601_date = Regex(\n        r\"(?P<year>\\d{4})(?:-(?P<month>\\d\\d)(?:-(?P<day>\\d\\d))?)?\"\n    ).set_name(\"ISO8601 date\")\n    \"ISO8601 date (``yyyy-mm-dd``)\"\n\n    iso8601_datetime = Regex(\n        r\"(?P<year>\\d{4})-(?P<month>\\d\\d)-(?P<day>\\d\\d)[T ](?P<hour>\\d\\d):(?P<minute>\\d\\d)(:(?P<second>\\d\\d(\\.\\d*)?)?)?(?P<tz>Z|[+-]\\d\\d:?\\d\\d)?\"\n    ).set_name(\"ISO8601 datetime\")\n    \"ISO8601 datetime (``yyyy-mm-ddThh:mm:ss.s(Z|+-00:00)``) - trailing seconds, milliseconds, and timezone optional; accepts separating ``'T'`` or ``' '``\"\n\n    uuid = Regex(r\"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}\").set_name(\"UUID\")\n    \"UUID (``xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx``)\"\n\n    _html_stripper = any_open_tag.suppress() | any_close_tag.suppress()\n\n    @staticmethod\n    def strip_html_tags(s: str, l: int, tokens: ParseResults):\n        \"\"\"Parse action to remove HTML tags from web page HTML source\n\n        Example::\n\n            # strip HTML links from normal text\n            text = '<td>More info at the <a href=\"https://github.com/pyparsing/pyparsing/wiki\">pyparsing</a> wiki page</td>'\n            td, td_end = makeHTMLTags(\"TD\")\n            table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)(\"body\") + td_end\n            print(table_text.parseString(text).body)\n\n        Prints::\n\n            More info at the pyparsing wiki page\n        \"\"\"\n        return pyparsing_common._html_stripper.transform_string(tokens[0])\n\n    _commasepitem = (\n        Combine(\n            OneOrMore(\n                ~Literal(\",\")\n                + ~LineEnd()\n                + Word(printables, exclude_chars=\",\")\n                + Opt(White(\" \\t\") + ~FollowedBy(LineEnd() | \",\"))\n            )\n        )\n        .streamline()\n        .set_name(\"commaItem\")\n    )\n    comma_separated_list = delimited_list(\n        Opt(quoted_string.copy() | _commasepitem, default=\"\")\n    ).set_name(\"comma separated list\")\n    \"\"\"Predefined expression of 1 or more printable words or quoted strings, separated by commas.\"\"\"\n\n    upcase_tokens = staticmethod(token_map(lambda t: t.upper()))\n    \"\"\"Parse action to convert tokens to upper case.\"\"\"\n\n    downcase_tokens = staticmethod(token_map(lambda t: t.lower()))\n    \"\"\"Parse action to convert tokens to lower case.\"\"\"\n\n    # fmt: off\n    url = Regex(\n        # https://mathiasbynens.be/demo/url-regex\n        # https://gist.github.com/dperini/729294\n        r\"^\" +\n        # protocol identifier (optional)\n        # short syntax // still required\n        r\"(?:(?:(?P<scheme>https?|ftp):)?\\/\\/)\" +\n        # user:pass BasicAuth (optional)\n        r\"(?:(?P<auth>\\S+(?::\\S*)?)@)?\" +\n        r\"(?P<host>\" +\n        # IP address exclusion\n        # private & local networks\n        r\"(?!(?:10|127)(?:\\.\\d{1,3}){3})\" +\n        r\"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})\" +\n        r\"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})\" +\n        # IP address dotted notation octets\n        # excludes loopback network 0.0.0.0\n        # excludes reserved space >= 224.0.0.0\n        # excludes network & broadcast addresses\n        # (first & last IP address of each class)\n        r\"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])\" +\n        r\"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}\" +\n        r\"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))\" +\n        r\"|\" +\n        # host & domain names, may end with dot\n        # can be replaced by a shortest alternative\n        # (?![-_])(?:[-\\w\\u00a1-\\uffff]{0,63}[^-_]\\.)+\n        r\"(?:\" +\n        r\"(?:\" +\n        r\"[a-z0-9\\u00a1-\\uffff]\" +\n        r\"[a-z0-9\\u00a1-\\uffff_-]{0,62}\" +\n        r\")?\" +\n        r\"[a-z0-9\\u00a1-\\uffff]\\.\" +\n        r\")+\" +\n        # TLD identifier name, may end with dot\n        r\"(?:[a-z\\u00a1-\\uffff]{2,}\\.?)\" +\n        r\")\" +\n        # port number (optional)\n        r\"(:(?P<port>\\d{2,5}))?\" +\n        # resource path (optional)\n        r\"(?P<path>\\/[^?# ]*)?\" +\n        # query string (optional)\n        r\"(\\?(?P<query>[^#]*))?\" +\n        # fragment (optional)\n        r\"(#(?P<fragment>\\S*))?\" +\n        r\"$\"\n    ).set_name(\"url\")\n    # fmt: on\n\n    # pre-PEP8 compatibility names\n    convertToInteger = convert_to_integer\n    convertToFloat = convert_to_float\n    convertToDate = convert_to_date\n    convertToDatetime = convert_to_datetime\n    stripHTMLTags = strip_html_tags\n    upcaseTokens = upcase_tokens\n    downcaseTokens = downcase_tokens\n\n\n_builtin_exprs = [\n    v for v in vars(pyparsing_common).values() if isinstance(v, ParserElement)\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing/core.py",
    "content": "#\n# core.py\n#\nimport os\nimport typing\nfrom typing import (\n    NamedTuple,\n    Union,\n    Callable,\n    Any,\n    Generator,\n    Tuple,\n    List,\n    TextIO,\n    Set,\n    Sequence,\n)\nfrom abc import ABC, abstractmethod\nfrom enum import Enum\nimport string\nimport copy\nimport warnings\nimport re\nimport sys\nfrom collections.abc import Iterable\nimport traceback\nimport types\nfrom operator import itemgetter\nfrom functools import wraps\nfrom threading import RLock\nfrom pathlib import Path\n\nfrom .util import (\n    _FifoCache,\n    _UnboundedCache,\n    __config_flags,\n    _collapse_string_to_ranges,\n    _escape_regex_range_chars,\n    _bslash,\n    _flatten,\n    LRUMemo as _LRUMemo,\n    UnboundedMemo as _UnboundedMemo,\n)\nfrom .exceptions import *\nfrom .actions import *\nfrom .results import ParseResults, _ParseResultsWithOffset\nfrom .unicode import pyparsing_unicode\n\n_MAX_INT = sys.maxsize\nstr_type: Tuple[type, ...] = (str, bytes)\n\n#\n# Copyright (c) 2003-2022  Paul T. McGuire\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n\n\nif sys.version_info >= (3, 8):\n    from functools import cached_property\nelse:\n\n    class cached_property:\n        def __init__(self, func):\n            self._func = func\n\n        def __get__(self, instance, owner=None):\n            ret = instance.__dict__[self._func.__name__] = self._func(instance)\n            return ret\n\n\nclass __compat__(__config_flags):\n    \"\"\"\n    A cross-version compatibility configuration for pyparsing features that will be\n    released in a future version. By setting values in this configuration to True,\n    those features can be enabled in prior versions for compatibility development\n    and testing.\n\n    - ``collect_all_And_tokens`` - flag to enable fix for Issue #63 that fixes erroneous grouping\n      of results names when an :class:`And` expression is nested within an :class:`Or` or :class:`MatchFirst`;\n      maintained for compatibility, but setting to ``False`` no longer restores pre-2.3.1\n      behavior\n    \"\"\"\n\n    _type_desc = \"compatibility\"\n\n    collect_all_And_tokens = True\n\n    _all_names = [__ for __ in locals() if not __.startswith(\"_\")]\n    _fixed_names = \"\"\"\n        collect_all_And_tokens\n        \"\"\".split()\n\n\nclass __diag__(__config_flags):\n    _type_desc = \"diagnostic\"\n\n    warn_multiple_tokens_in_named_alternation = False\n    warn_ungrouped_named_tokens_in_collection = False\n    warn_name_set_on_empty_Forward = False\n    warn_on_parse_using_empty_Forward = False\n    warn_on_assignment_to_Forward = False\n    warn_on_multiple_string_args_to_oneof = False\n    warn_on_match_first_with_lshift_operator = False\n    enable_debug_on_named_expressions = False\n\n    _all_names = [__ for __ in locals() if not __.startswith(\"_\")]\n    _warning_names = [name for name in _all_names if name.startswith(\"warn\")]\n    _debug_names = [name for name in _all_names if name.startswith(\"enable_debug\")]\n\n    @classmethod\n    def enable_all_warnings(cls) -> None:\n        for name in cls._warning_names:\n            cls.enable(name)\n\n\nclass Diagnostics(Enum):\n    \"\"\"\n    Diagnostic configuration (all default to disabled)\n    - ``warn_multiple_tokens_in_named_alternation`` - flag to enable warnings when a results\n      name is defined on a :class:`MatchFirst` or :class:`Or` expression with one or more :class:`And` subexpressions\n    - ``warn_ungrouped_named_tokens_in_collection`` - flag to enable warnings when a results\n      name is defined on a containing expression with ungrouped subexpressions that also\n      have results names\n    - ``warn_name_set_on_empty_Forward`` - flag to enable warnings when a :class:`Forward` is defined\n      with a results name, but has no contents defined\n    - ``warn_on_parse_using_empty_Forward`` - flag to enable warnings when a :class:`Forward` is\n      defined in a grammar but has never had an expression attached to it\n    - ``warn_on_assignment_to_Forward`` - flag to enable warnings when a :class:`Forward` is defined\n      but is overwritten by assigning using ``'='`` instead of ``'<<='`` or ``'<<'``\n    - ``warn_on_multiple_string_args_to_oneof`` - flag to enable warnings when :class:`one_of` is\n      incorrectly called with multiple str arguments\n    - ``enable_debug_on_named_expressions`` - flag to auto-enable debug on all subsequent\n      calls to :class:`ParserElement.set_name`\n\n    Diagnostics are enabled/disabled by calling :class:`enable_diag` and :class:`disable_diag`.\n    All warnings can be enabled by calling :class:`enable_all_warnings`.\n    \"\"\"\n\n    warn_multiple_tokens_in_named_alternation = 0\n    warn_ungrouped_named_tokens_in_collection = 1\n    warn_name_set_on_empty_Forward = 2\n    warn_on_parse_using_empty_Forward = 3\n    warn_on_assignment_to_Forward = 4\n    warn_on_multiple_string_args_to_oneof = 5\n    warn_on_match_first_with_lshift_operator = 6\n    enable_debug_on_named_expressions = 7\n\n\ndef enable_diag(diag_enum: Diagnostics) -> None:\n    \"\"\"\n    Enable a global pyparsing diagnostic flag (see :class:`Diagnostics`).\n    \"\"\"\n    __diag__.enable(diag_enum.name)\n\n\ndef disable_diag(diag_enum: Diagnostics) -> None:\n    \"\"\"\n    Disable a global pyparsing diagnostic flag (see :class:`Diagnostics`).\n    \"\"\"\n    __diag__.disable(diag_enum.name)\n\n\ndef enable_all_warnings() -> None:\n    \"\"\"\n    Enable all global pyparsing diagnostic warnings (see :class:`Diagnostics`).\n    \"\"\"\n    __diag__.enable_all_warnings()\n\n\n# hide abstract class\ndel __config_flags\n\n\ndef _should_enable_warnings(\n    cmd_line_warn_options: typing.Iterable[str], warn_env_var: typing.Optional[str]\n) -> bool:\n    enable = bool(warn_env_var)\n    for warn_opt in cmd_line_warn_options:\n        w_action, w_message, w_category, w_module, w_line = (warn_opt + \"::::\").split(\n            \":\"\n        )[:5]\n        if not w_action.lower().startswith(\"i\") and (\n            not (w_message or w_category or w_module) or w_module == \"pyparsing\"\n        ):\n            enable = True\n        elif w_action.lower().startswith(\"i\") and w_module in (\"pyparsing\", \"\"):\n            enable = False\n    return enable\n\n\nif _should_enable_warnings(\n    sys.warnoptions, os.environ.get(\"PYPARSINGENABLEALLWARNINGS\")\n):\n    enable_all_warnings()\n\n\n# build list of single arg builtins, that can be used as parse actions\n_single_arg_builtins = {\n    sum,\n    len,\n    sorted,\n    reversed,\n    list,\n    tuple,\n    set,\n    any,\n    all,\n    min,\n    max,\n}\n\n_generatorType = types.GeneratorType\nParseAction = Union[\n    Callable[[], Any],\n    Callable[[ParseResults], Any],\n    Callable[[int, ParseResults], Any],\n    Callable[[str, int, ParseResults], Any],\n]\nParseCondition = Union[\n    Callable[[], bool],\n    Callable[[ParseResults], bool],\n    Callable[[int, ParseResults], bool],\n    Callable[[str, int, ParseResults], bool],\n]\nParseFailAction = Callable[[str, int, \"ParserElement\", Exception], None]\nDebugStartAction = Callable[[str, int, \"ParserElement\", bool], None]\nDebugSuccessAction = Callable[\n    [str, int, int, \"ParserElement\", ParseResults, bool], None\n]\nDebugExceptionAction = Callable[[str, int, \"ParserElement\", Exception, bool], None]\n\n\nalphas = string.ascii_uppercase + string.ascii_lowercase\nidentchars = pyparsing_unicode.Latin1.identchars\nidentbodychars = pyparsing_unicode.Latin1.identbodychars\nnums = \"0123456789\"\nhexnums = nums + \"ABCDEFabcdef\"\nalphanums = alphas + nums\nprintables = \"\".join([c for c in string.printable if c not in string.whitespace])\n\n_trim_arity_call_line: traceback.StackSummary = None\n\n\ndef _trim_arity(func, max_limit=3):\n    \"\"\"decorator to trim function calls to match the arity of the target\"\"\"\n    global _trim_arity_call_line\n\n    if func in _single_arg_builtins:\n        return lambda s, l, t: func(t)\n\n    limit = 0\n    found_arity = False\n\n    def extract_tb(tb, limit=0):\n        frames = traceback.extract_tb(tb, limit=limit)\n        frame_summary = frames[-1]\n        return [frame_summary[:2]]\n\n    # synthesize what would be returned by traceback.extract_stack at the call to\n    # user's parse action 'func', so that we don't incur call penalty at parse time\n\n    # fmt: off\n    LINE_DIFF = 7\n    # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND\n    # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!!\n    _trim_arity_call_line = (_trim_arity_call_line or traceback.extract_stack(limit=2)[-1])\n    pa_call_line_synth = (_trim_arity_call_line[0], _trim_arity_call_line[1] + LINE_DIFF)\n\n    def wrapper(*args):\n        nonlocal found_arity, limit\n        while 1:\n            try:\n                ret = func(*args[limit:])\n                found_arity = True\n                return ret\n            except TypeError as te:\n                # re-raise TypeErrors if they did not come from our arity testing\n                if found_arity:\n                    raise\n                else:\n                    tb = te.__traceback__\n                    trim_arity_type_error = (\n                        extract_tb(tb, limit=2)[-1][:2] == pa_call_line_synth\n                    )\n                    del tb\n\n                    if trim_arity_type_error:\n                        if limit < max_limit:\n                            limit += 1\n                            continue\n\n                    raise\n    # fmt: on\n\n    # copy func name to wrapper for sensible debug output\n    # (can't use functools.wraps, since that messes with function signature)\n    func_name = getattr(func, \"__name__\", getattr(func, \"__class__\").__name__)\n    wrapper.__name__ = func_name\n    wrapper.__doc__ = func.__doc__\n\n    return wrapper\n\n\ndef condition_as_parse_action(\n    fn: ParseCondition, message: str = None, fatal: bool = False\n) -> ParseAction:\n    \"\"\"\n    Function to convert a simple predicate function that returns ``True`` or ``False``\n    into a parse action. Can be used in places when a parse action is required\n    and :class:`ParserElement.add_condition` cannot be used (such as when adding a condition\n    to an operator level in :class:`infix_notation`).\n\n    Optional keyword arguments:\n\n    - ``message`` - define a custom message to be used in the raised exception\n    - ``fatal`` - if True, will raise :class:`ParseFatalException` to stop parsing immediately;\n      otherwise will raise :class:`ParseException`\n\n    \"\"\"\n    msg = message if message is not None else \"failed user-defined condition\"\n    exc_type = ParseFatalException if fatal else ParseException\n    fn = _trim_arity(fn)\n\n    @wraps(fn)\n    def pa(s, l, t):\n        if not bool(fn(s, l, t)):\n            raise exc_type(s, l, msg)\n\n    return pa\n\n\ndef _default_start_debug_action(\n    instring: str, loc: int, expr: \"ParserElement\", cache_hit: bool = False\n):\n    cache_hit_str = \"*\" if cache_hit else \"\"\n    print(\n        (\n            \"{}Match {} at loc {}({},{})\\n  {}\\n  {}^\".format(\n                cache_hit_str,\n                expr,\n                loc,\n                lineno(loc, instring),\n                col(loc, instring),\n                line(loc, instring),\n                \" \" * (col(loc, instring) - 1),\n            )\n        )\n    )\n\n\ndef _default_success_debug_action(\n    instring: str,\n    startloc: int,\n    endloc: int,\n    expr: \"ParserElement\",\n    toks: ParseResults,\n    cache_hit: bool = False,\n):\n    cache_hit_str = \"*\" if cache_hit else \"\"\n    print(\"{}Matched {} -> {}\".format(cache_hit_str, expr, toks.as_list()))\n\n\ndef _default_exception_debug_action(\n    instring: str,\n    loc: int,\n    expr: \"ParserElement\",\n    exc: Exception,\n    cache_hit: bool = False,\n):\n    cache_hit_str = \"*\" if cache_hit else \"\"\n    print(\n        \"{}Match {} failed, {} raised: {}\".format(\n            cache_hit_str, expr, type(exc).__name__, exc\n        )\n    )\n\n\ndef null_debug_action(*args):\n    \"\"\"'Do-nothing' debug action, to suppress debugging output during parsing.\"\"\"\n\n\nclass ParserElement(ABC):\n    \"\"\"Abstract base level parser element class.\"\"\"\n\n    DEFAULT_WHITE_CHARS: str = \" \\n\\t\\r\"\n    verbose_stacktrace: bool = False\n    _literalStringClass: typing.Optional[type] = None\n\n    @staticmethod\n    def set_default_whitespace_chars(chars: str) -> None:\n        r\"\"\"\n        Overrides the default whitespace chars\n\n        Example::\n\n            # default whitespace chars are space, <TAB> and newline\n            Word(alphas)[1, ...].parse_string(\"abc def\\nghi jkl\")  # -> ['abc', 'def', 'ghi', 'jkl']\n\n            # change to just treat newline as significant\n            ParserElement.set_default_whitespace_chars(\" \\t\")\n            Word(alphas)[1, ...].parse_string(\"abc def\\nghi jkl\")  # -> ['abc', 'def']\n        \"\"\"\n        ParserElement.DEFAULT_WHITE_CHARS = chars\n\n        # update whitespace all parse expressions defined in this module\n        for expr in _builtin_exprs:\n            if expr.copyDefaultWhiteChars:\n                expr.whiteChars = set(chars)\n\n    @staticmethod\n    def inline_literals_using(cls: type) -> None:\n        \"\"\"\n        Set class to be used for inclusion of string literals into a parser.\n\n        Example::\n\n            # default literal class used is Literal\n            integer = Word(nums)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            date_str.parse_string(\"1999/12/31\")  # -> ['1999', '/', '12', '/', '31']\n\n\n            # change to Suppress\n            ParserElement.inline_literals_using(Suppress)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            date_str.parse_string(\"1999/12/31\")  # -> ['1999', '12', '31']\n        \"\"\"\n        ParserElement._literalStringClass = cls\n\n    class DebugActions(NamedTuple):\n        debug_try: typing.Optional[DebugStartAction]\n        debug_match: typing.Optional[DebugSuccessAction]\n        debug_fail: typing.Optional[DebugExceptionAction]\n\n    def __init__(self, savelist: bool = False):\n        self.parseAction: List[ParseAction] = list()\n        self.failAction: typing.Optional[ParseFailAction] = None\n        self.customName = None\n        self._defaultName = None\n        self.resultsName = None\n        self.saveAsList = savelist\n        self.skipWhitespace = True\n        self.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS)\n        self.copyDefaultWhiteChars = True\n        # used when checking for left-recursion\n        self.mayReturnEmpty = False\n        self.keepTabs = False\n        self.ignoreExprs: List[\"ParserElement\"] = list()\n        self.debug = False\n        self.streamlined = False\n        # optimize exception handling for subclasses that don't advance parse index\n        self.mayIndexError = True\n        self.errmsg = \"\"\n        # mark results names as modal (report only last) or cumulative (list all)\n        self.modalResults = True\n        # custom debug actions\n        self.debugActions = self.DebugActions(None, None, None)\n        # avoid redundant calls to preParse\n        self.callPreparse = True\n        self.callDuringTry = False\n        self.suppress_warnings_: List[Diagnostics] = []\n\n    def suppress_warning(self, warning_type: Diagnostics) -> \"ParserElement\":\n        \"\"\"\n        Suppress warnings emitted for a particular diagnostic on this expression.\n\n        Example::\n\n            base = pp.Forward()\n            base.suppress_warning(Diagnostics.warn_on_parse_using_empty_Forward)\n\n            # statement would normally raise a warning, but is now suppressed\n            print(base.parseString(\"x\"))\n\n        \"\"\"\n        self.suppress_warnings_.append(warning_type)\n        return self\n\n    def copy(self) -> \"ParserElement\":\n        \"\"\"\n        Make a copy of this :class:`ParserElement`.  Useful for defining\n        different parse actions for the same parsing pattern, using copies of\n        the original parse element.\n\n        Example::\n\n            integer = Word(nums).set_parse_action(lambda toks: int(toks[0]))\n            integerK = integer.copy().add_parse_action(lambda toks: toks[0] * 1024) + Suppress(\"K\")\n            integerM = integer.copy().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress(\"M\")\n\n            print((integerK | integerM | integer)[1, ...].parse_string(\"5K 100 640K 256M\"))\n\n        prints::\n\n            [5120, 100, 655360, 268435456]\n\n        Equivalent form of ``expr.copy()`` is just ``expr()``::\n\n            integerM = integer().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress(\"M\")\n        \"\"\"\n        cpy = copy.copy(self)\n        cpy.parseAction = self.parseAction[:]\n        cpy.ignoreExprs = self.ignoreExprs[:]\n        if self.copyDefaultWhiteChars:\n            cpy.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS)\n        return cpy\n\n    def set_results_name(\n        self, name: str, list_all_matches: bool = False, *, listAllMatches: bool = False\n    ) -> \"ParserElement\":\n        \"\"\"\n        Define name for referencing matching tokens as a nested attribute\n        of the returned parse results.\n\n        Normally, results names are assigned as you would assign keys in a dict:\n        any existing value is overwritten by later values. If it is necessary to\n        keep all values captured for a particular results name, call ``set_results_name``\n        with ``list_all_matches`` = True.\n\n        NOTE: ``set_results_name`` returns a *copy* of the original :class:`ParserElement` object;\n        this is so that the client can define a basic element, such as an\n        integer, and reference it in multiple places with different names.\n\n        You can also set results names using the abbreviated syntax,\n        ``expr(\"name\")`` in place of ``expr.set_results_name(\"name\")``\n        - see :class:`__call__`. If ``list_all_matches`` is required, use\n        ``expr(\"name*\")``.\n\n        Example::\n\n            date_str = (integer.set_results_name(\"year\") + '/'\n                        + integer.set_results_name(\"month\") + '/'\n                        + integer.set_results_name(\"day\"))\n\n            # equivalent form:\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n        \"\"\"\n        listAllMatches = listAllMatches or list_all_matches\n        return self._setResultsName(name, listAllMatches)\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if name is None:\n            return self\n        newself = self.copy()\n        if name.endswith(\"*\"):\n            name = name[:-1]\n            listAllMatches = True\n        newself.resultsName = name\n        newself.modalResults = not listAllMatches\n        return newself\n\n    def set_break(self, break_flag: bool = True) -> \"ParserElement\":\n        \"\"\"\n        Method to invoke the Python pdb debugger when this element is\n        about to be parsed. Set ``break_flag`` to ``True`` to enable, ``False`` to\n        disable.\n        \"\"\"\n        if break_flag:\n            _parseMethod = self._parse\n\n            def breaker(instring, loc, doActions=True, callPreParse=True):\n                import pdb\n\n                # this call to pdb.set_trace() is intentional, not a checkin error\n                pdb.set_trace()\n                return _parseMethod(instring, loc, doActions, callPreParse)\n\n            breaker._originalParseMethod = _parseMethod\n            self._parse = breaker\n        else:\n            if hasattr(self._parse, \"_originalParseMethod\"):\n                self._parse = self._parse._originalParseMethod\n        return self\n\n    def set_parse_action(self, *fns: ParseAction, **kwargs) -> \"ParserElement\":\n        \"\"\"\n        Define one or more actions to perform when successfully matching parse element definition.\n\n        Parse actions can be called to perform data conversions, do extra validation,\n        update external data structures, or enhance or replace the parsed tokens.\n        Each parse action ``fn`` is a callable method with 0-3 arguments, called as\n        ``fn(s, loc, toks)`` , ``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where:\n\n        - s   = the original string being parsed (see note below)\n        - loc = the location of the matching substring\n        - toks = a list of the matched tokens, packaged as a :class:`ParseResults` object\n\n        The parsed tokens are passed to the parse action as ParseResults. They can be\n        modified in place using list-style append, extend, and pop operations to update\n        the parsed list elements; and with dictionary-style item set and del operations\n        to add, update, or remove any named results. If the tokens are modified in place,\n        it is not necessary to return them with a return statement.\n\n        Parse actions can also completely replace the given tokens, with another ``ParseResults``\n        object, or with some entirely different object (common for parse actions that perform data\n        conversions). A convenient way to build a new parse result is to define the values\n        using a dict, and then create the return value using :class:`ParseResults.from_dict`.\n\n        If None is passed as the ``fn`` parse action, all previously added parse actions for this\n        expression are cleared.\n\n        Optional keyword arguments:\n\n        - call_during_try = (default= ``False``) indicate if parse action should be run during\n          lookaheads and alternate testing. For parse actions that have side effects, it is\n          important to only call the parse action once it is determined that it is being\n          called as part of a successful parse. For parse actions that perform additional\n          validation, then call_during_try should be passed as True, so that the validation\n          code is included in the preliminary \"try\" parses.\n\n        Note: the default parsing behavior is to expand tabs in the input string\n        before starting the parsing process.  See :class:`parse_string` for more\n        information on parsing strings containing ``<TAB>`` s, and suggested\n        methods to maintain a consistent view of the parsed string, the parse\n        location, and line and column positions within the parsed string.\n\n        Example::\n\n            # parse dates in the form YYYY/MM/DD\n\n            # use parse action to convert toks from str to int at parse time\n            def convert_to_int(toks):\n                return int(toks[0])\n\n            # use a parse action to verify that the date is a valid date\n            def is_valid_date(instring, loc, toks):\n                from datetime import date\n                year, month, day = toks[::2]\n                try:\n                    date(year, month, day)\n                except ValueError:\n                    raise ParseException(instring, loc, \"invalid date given\")\n\n            integer = Word(nums)\n            date_str = integer + '/' + integer + '/' + integer\n\n            # add parse actions\n            integer.set_parse_action(convert_to_int)\n            date_str.set_parse_action(is_valid_date)\n\n            # note that integer fields are now ints, not strings\n            date_str.run_tests('''\n                # successful parse - note that integer fields were converted to ints\n                1999/12/31\n\n                # fail - invalid date\n                1999/13/31\n                ''')\n        \"\"\"\n        if list(fns) == [None]:\n            self.parseAction = []\n        else:\n            if not all(callable(fn) for fn in fns):\n                raise TypeError(\"parse actions must be callable\")\n            self.parseAction = [_trim_arity(fn) for fn in fns]\n            self.callDuringTry = kwargs.get(\n                \"call_during_try\", kwargs.get(\"callDuringTry\", False)\n            )\n        return self\n\n    def add_parse_action(self, *fns: ParseAction, **kwargs) -> \"ParserElement\":\n        \"\"\"\n        Add one or more parse actions to expression's list of parse actions. See :class:`set_parse_action`.\n\n        See examples in :class:`copy`.\n        \"\"\"\n        self.parseAction += [_trim_arity(fn) for fn in fns]\n        self.callDuringTry = self.callDuringTry or kwargs.get(\n            \"call_during_try\", kwargs.get(\"callDuringTry\", False)\n        )\n        return self\n\n    def add_condition(self, *fns: ParseCondition, **kwargs) -> \"ParserElement\":\n        \"\"\"Add a boolean predicate function to expression's list of parse actions. See\n        :class:`set_parse_action` for function call signatures. Unlike ``set_parse_action``,\n        functions passed to ``add_condition`` need to return boolean success/fail of the condition.\n\n        Optional keyword arguments:\n\n        - message = define a custom message to be used in the raised exception\n        - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise\n          ParseException\n        - call_during_try = boolean to indicate if this method should be called during internal tryParse calls,\n          default=False\n\n        Example::\n\n            integer = Word(nums).set_parse_action(lambda toks: int(toks[0]))\n            year_int = integer.copy()\n            year_int.add_condition(lambda toks: toks[0] >= 2000, message=\"Only support years 2000 and later\")\n            date_str = year_int + '/' + integer + '/' + integer\n\n            result = date_str.parse_string(\"1999/12/31\")  # -> Exception: Only support years 2000 and later (at char 0),\n                                                                         (line:1, col:1)\n        \"\"\"\n        for fn in fns:\n            self.parseAction.append(\n                condition_as_parse_action(\n                    fn, message=kwargs.get(\"message\"), fatal=kwargs.get(\"fatal\", False)\n                )\n            )\n\n        self.callDuringTry = self.callDuringTry or kwargs.get(\n            \"call_during_try\", kwargs.get(\"callDuringTry\", False)\n        )\n        return self\n\n    def set_fail_action(self, fn: ParseFailAction) -> \"ParserElement\":\n        \"\"\"\n        Define action to perform if parsing fails at this expression.\n        Fail acton fn is a callable function that takes the arguments\n        ``fn(s, loc, expr, err)`` where:\n\n        - s = string being parsed\n        - loc = location where expression match was attempted and failed\n        - expr = the parse expression that failed\n        - err = the exception thrown\n\n        The function returns no value.  It may throw :class:`ParseFatalException`\n        if it is desired to stop parsing immediately.\"\"\"\n        self.failAction = fn\n        return self\n\n    def _skipIgnorables(self, instring, loc):\n        exprsFound = True\n        while exprsFound:\n            exprsFound = False\n            for e in self.ignoreExprs:\n                try:\n                    while 1:\n                        loc, dummy = e._parse(instring, loc)\n                        exprsFound = True\n                except ParseException:\n                    pass\n        return loc\n\n    def preParse(self, instring, loc):\n        if self.ignoreExprs:\n            loc = self._skipIgnorables(instring, loc)\n\n        if self.skipWhitespace:\n            instrlen = len(instring)\n            white_chars = self.whiteChars\n            while loc < instrlen and instring[loc] in white_chars:\n                loc += 1\n\n        return loc\n\n    def parseImpl(self, instring, loc, doActions=True):\n        return loc, []\n\n    def postParse(self, instring, loc, tokenlist):\n        return tokenlist\n\n    # @profile\n    def _parseNoCache(\n        self, instring, loc, doActions=True, callPreParse=True\n    ) -> Tuple[int, ParseResults]:\n        TRY, MATCH, FAIL = 0, 1, 2\n        debugging = self.debug  # and doActions)\n        len_instring = len(instring)\n\n        if debugging or self.failAction:\n            # print(\"Match {} at loc {}({}, {})\".format(self, loc, lineno(loc, instring), col(loc, instring)))\n            try:\n                if callPreParse and self.callPreparse:\n                    pre_loc = self.preParse(instring, loc)\n                else:\n                    pre_loc = loc\n                tokens_start = pre_loc\n                if self.debugActions.debug_try:\n                    self.debugActions.debug_try(instring, tokens_start, self, False)\n                if self.mayIndexError or pre_loc >= len_instring:\n                    try:\n                        loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n                    except IndexError:\n                        raise ParseException(instring, len_instring, self.errmsg, self)\n                else:\n                    loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n            except Exception as err:\n                # print(\"Exception raised:\", err)\n                if self.debugActions.debug_fail:\n                    self.debugActions.debug_fail(\n                        instring, tokens_start, self, err, False\n                    )\n                if self.failAction:\n                    self.failAction(instring, tokens_start, self, err)\n                raise\n        else:\n            if callPreParse and self.callPreparse:\n                pre_loc = self.preParse(instring, loc)\n            else:\n                pre_loc = loc\n            tokens_start = pre_loc\n            if self.mayIndexError or pre_loc >= len_instring:\n                try:\n                    loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n                except IndexError:\n                    raise ParseException(instring, len_instring, self.errmsg, self)\n            else:\n                loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n\n        tokens = self.postParse(instring, loc, tokens)\n\n        ret_tokens = ParseResults(\n            tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults\n        )\n        if self.parseAction and (doActions or self.callDuringTry):\n            if debugging:\n                try:\n                    for fn in self.parseAction:\n                        try:\n                            tokens = fn(instring, tokens_start, ret_tokens)\n                        except IndexError as parse_action_exc:\n                            exc = ParseException(\"exception raised in parse action\")\n                            raise exc from parse_action_exc\n\n                        if tokens is not None and tokens is not ret_tokens:\n                            ret_tokens = ParseResults(\n                                tokens,\n                                self.resultsName,\n                                asList=self.saveAsList\n                                and isinstance(tokens, (ParseResults, list)),\n                                modal=self.modalResults,\n                            )\n                except Exception as err:\n                    # print \"Exception raised in user parse action:\", err\n                    if self.debugActions.debug_fail:\n                        self.debugActions.debug_fail(\n                            instring, tokens_start, self, err, False\n                        )\n                    raise\n            else:\n                for fn in self.parseAction:\n                    try:\n                        tokens = fn(instring, tokens_start, ret_tokens)\n                    except IndexError as parse_action_exc:\n                        exc = ParseException(\"exception raised in parse action\")\n                        raise exc from parse_action_exc\n\n                    if tokens is not None and tokens is not ret_tokens:\n                        ret_tokens = ParseResults(\n                            tokens,\n                            self.resultsName,\n                            asList=self.saveAsList\n                            and isinstance(tokens, (ParseResults, list)),\n                            modal=self.modalResults,\n                        )\n        if debugging:\n            # print(\"Matched\", self, \"->\", ret_tokens.as_list())\n            if self.debugActions.debug_match:\n                self.debugActions.debug_match(\n                    instring, tokens_start, loc, self, ret_tokens, False\n                )\n\n        return loc, ret_tokens\n\n    def try_parse(self, instring: str, loc: int, raise_fatal: bool = False) -> int:\n        try:\n            return self._parse(instring, loc, doActions=False)[0]\n        except ParseFatalException:\n            if raise_fatal:\n                raise\n            raise ParseException(instring, loc, self.errmsg, self)\n\n    def can_parse_next(self, instring: str, loc: int) -> bool:\n        try:\n            self.try_parse(instring, loc)\n        except (ParseException, IndexError):\n            return False\n        else:\n            return True\n\n    # cache for left-recursion in Forward references\n    recursion_lock = RLock()\n    recursion_memos: typing.Dict[\n        Tuple[int, \"Forward\", bool], Tuple[int, Union[ParseResults, Exception]]\n    ] = {}\n\n    # argument cache for optimizing repeated calls when backtracking through recursive expressions\n    packrat_cache = (\n        {}\n    )  # this is set later by enabled_packrat(); this is here so that reset_cache() doesn't fail\n    packrat_cache_lock = RLock()\n    packrat_cache_stats = [0, 0]\n\n    # this method gets repeatedly called during backtracking with the same arguments -\n    # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression\n    def _parseCache(\n        self, instring, loc, doActions=True, callPreParse=True\n    ) -> Tuple[int, ParseResults]:\n        HIT, MISS = 0, 1\n        TRY, MATCH, FAIL = 0, 1, 2\n        lookup = (self, instring, loc, callPreParse, doActions)\n        with ParserElement.packrat_cache_lock:\n            cache = ParserElement.packrat_cache\n            value = cache.get(lookup)\n            if value is cache.not_in_cache:\n                ParserElement.packrat_cache_stats[MISS] += 1\n                try:\n                    value = self._parseNoCache(instring, loc, doActions, callPreParse)\n                except ParseBaseException as pe:\n                    # cache a copy of the exception, without the traceback\n                    cache.set(lookup, pe.__class__(*pe.args))\n                    raise\n                else:\n                    cache.set(lookup, (value[0], value[1].copy(), loc))\n                    return value\n            else:\n                ParserElement.packrat_cache_stats[HIT] += 1\n                if self.debug and self.debugActions.debug_try:\n                    try:\n                        self.debugActions.debug_try(instring, loc, self, cache_hit=True)\n                    except TypeError:\n                        pass\n                if isinstance(value, Exception):\n                    if self.debug and self.debugActions.debug_fail:\n                        try:\n                            self.debugActions.debug_fail(\n                                instring, loc, self, value, cache_hit=True\n                            )\n                        except TypeError:\n                            pass\n                    raise value\n\n                loc_, result, endloc = value[0], value[1].copy(), value[2]\n                if self.debug and self.debugActions.debug_match:\n                    try:\n                        self.debugActions.debug_match(\n                            instring, loc_, endloc, self, result, cache_hit=True\n                        )\n                    except TypeError:\n                        pass\n\n                return loc_, result\n\n    _parse = _parseNoCache\n\n    @staticmethod\n    def reset_cache() -> None:\n        ParserElement.packrat_cache.clear()\n        ParserElement.packrat_cache_stats[:] = [0] * len(\n            ParserElement.packrat_cache_stats\n        )\n        ParserElement.recursion_memos.clear()\n\n    _packratEnabled = False\n    _left_recursion_enabled = False\n\n    @staticmethod\n    def disable_memoization() -> None:\n        \"\"\"\n        Disables active Packrat or Left Recursion parsing and their memoization\n\n        This method also works if neither Packrat nor Left Recursion are enabled.\n        This makes it safe to call before activating Packrat nor Left Recursion\n        to clear any previous settings.\n        \"\"\"\n        ParserElement.reset_cache()\n        ParserElement._left_recursion_enabled = False\n        ParserElement._packratEnabled = False\n        ParserElement._parse = ParserElement._parseNoCache\n\n    @staticmethod\n    def enable_left_recursion(\n        cache_size_limit: typing.Optional[int] = None, *, force=False\n    ) -> None:\n        \"\"\"\n        Enables \"bounded recursion\" parsing, which allows for both direct and indirect\n        left-recursion. During parsing, left-recursive :class:`Forward` elements are\n        repeatedly matched with a fixed recursion depth that is gradually increased\n        until finding the longest match.\n\n        Example::\n\n            import pyparsing as pp\n            pp.ParserElement.enable_left_recursion()\n\n            E = pp.Forward(\"E\")\n            num = pp.Word(pp.nums)\n            # match `num`, or `num '+' num`, or `num '+' num '+' num`, ...\n            E <<= E + '+' - num | num\n\n            print(E.parse_string(\"1+2+3\"))\n\n        Recursion search naturally memoizes matches of ``Forward`` elements and may\n        thus skip reevaluation of parse actions during backtracking. This may break\n        programs with parse actions which rely on strict ordering of side-effects.\n\n        Parameters:\n\n        - cache_size_limit - (default=``None``) - memoize at most this many\n          ``Forward`` elements during matching; if ``None`` (the default),\n          memoize all ``Forward`` elements.\n\n        Bounded Recursion parsing works similar but not identical to Packrat parsing,\n        thus the two cannot be used together. Use ``force=True`` to disable any\n        previous, conflicting settings.\n        \"\"\"\n        if force:\n            ParserElement.disable_memoization()\n        elif ParserElement._packratEnabled:\n            raise RuntimeError(\"Packrat and Bounded Recursion are not compatible\")\n        if cache_size_limit is None:\n            ParserElement.recursion_memos = _UnboundedMemo()\n        elif cache_size_limit > 0:\n            ParserElement.recursion_memos = _LRUMemo(capacity=cache_size_limit)\n        else:\n            raise NotImplementedError(\"Memo size of %s\" % cache_size_limit)\n        ParserElement._left_recursion_enabled = True\n\n    @staticmethod\n    def enable_packrat(cache_size_limit: int = 128, *, force: bool = False) -> None:\n        \"\"\"\n        Enables \"packrat\" parsing, which adds memoizing to the parsing logic.\n        Repeated parse attempts at the same string location (which happens\n        often in many complex grammars) can immediately return a cached value,\n        instead of re-executing parsing/validating code.  Memoizing is done of\n        both valid results and parsing exceptions.\n\n        Parameters:\n\n        - cache_size_limit - (default= ``128``) - if an integer value is provided\n          will limit the size of the packrat cache; if None is passed, then\n          the cache size will be unbounded; if 0 is passed, the cache will\n          be effectively disabled.\n\n        This speedup may break existing programs that use parse actions that\n        have side-effects.  For this reason, packrat parsing is disabled when\n        you first import pyparsing.  To activate the packrat feature, your\n        program must call the class method :class:`ParserElement.enable_packrat`.\n        For best results, call ``enable_packrat()`` immediately after\n        importing pyparsing.\n\n        Example::\n\n            import pyparsing\n            pyparsing.ParserElement.enable_packrat()\n\n        Packrat parsing works similar but not identical to Bounded Recursion parsing,\n        thus the two cannot be used together. Use ``force=True`` to disable any\n        previous, conflicting settings.\n        \"\"\"\n        if force:\n            ParserElement.disable_memoization()\n        elif ParserElement._left_recursion_enabled:\n            raise RuntimeError(\"Packrat and Bounded Recursion are not compatible\")\n        if not ParserElement._packratEnabled:\n            ParserElement._packratEnabled = True\n            if cache_size_limit is None:\n                ParserElement.packrat_cache = _UnboundedCache()\n            else:\n                ParserElement.packrat_cache = _FifoCache(cache_size_limit)\n            ParserElement._parse = ParserElement._parseCache\n\n    def parse_string(\n        self, instring: str, parse_all: bool = False, *, parseAll: bool = False\n    ) -> ParseResults:\n        \"\"\"\n        Parse a string with respect to the parser definition. This function is intended as the primary interface to the\n        client code.\n\n        :param instring: The input string to be parsed.\n        :param parse_all: If set, the entire input string must match the grammar.\n        :param parseAll: retained for pre-PEP8 compatibility, will be removed in a future release.\n        :raises ParseException: Raised if ``parse_all`` is set and the input string does not match the whole grammar.\n        :returns: the parsed data as a :class:`ParseResults` object, which may be accessed as a `list`, a `dict`, or\n          an object with attributes if the given parser includes results names.\n\n        If the input string is required to match the entire grammar, ``parse_all`` flag must be set to ``True``. This\n        is also equivalent to ending the grammar with :class:`StringEnd`().\n\n        To report proper column numbers, ``parse_string`` operates on a copy of the input string where all tabs are\n        converted to spaces (8 spaces per tab, as per the default in ``string.expandtabs``). If the input string\n        contains tabs and the grammar uses parse actions that use the ``loc`` argument to index into the string\n        being parsed, one can ensure a consistent view of the input string by doing one of the following:\n\n        - calling ``parse_with_tabs`` on your grammar before calling ``parse_string`` (see :class:`parse_with_tabs`),\n        - define your parse action using the full ``(s,loc,toks)`` signature, and reference the input string using the\n          parse action's ``s`` argument, or\n        - explicitly expand the tabs in your input string before calling ``parse_string``.\n\n        Examples:\n\n        By default, partial matches are OK.\n\n        >>> res = Word('a').parse_string('aaaaabaaa')\n        >>> print(res)\n        ['aaaaa']\n\n        The parsing behavior varies by the inheriting class of this abstract class. Please refer to the children\n        directly to see more examples.\n\n        It raises an exception if parse_all flag is set and instring does not match the whole grammar.\n\n        >>> res = Word('a').parse_string('aaaaabaaa', parse_all=True)\n        Traceback (most recent call last):\n        ...\n        pyparsing.ParseException: Expected end of text, found 'b'  (at char 5), (line:1, col:6)\n        \"\"\"\n        parseAll = parse_all or parseAll\n\n        ParserElement.reset_cache()\n        if not self.streamlined:\n            self.streamline()\n        for e in self.ignoreExprs:\n            e.streamline()\n        if not self.keepTabs:\n            instring = instring.expandtabs()\n        try:\n            loc, tokens = self._parse(instring, 0)\n            if parseAll:\n                loc = self.preParse(instring, loc)\n                se = Empty() + StringEnd()\n                se._parse(instring, loc)\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clearing out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n        else:\n            return tokens\n\n    def scan_string(\n        self,\n        instring: str,\n        max_matches: int = _MAX_INT,\n        overlap: bool = False,\n        *,\n        debug: bool = False,\n        maxMatches: int = _MAX_INT,\n    ) -> Generator[Tuple[ParseResults, int, int], None, None]:\n        \"\"\"\n        Scan the input string for expression matches.  Each match will return the\n        matching tokens, start location, and end location.  May be called with optional\n        ``max_matches`` argument, to clip scanning after 'n' matches are found.  If\n        ``overlap`` is specified, then overlapping matches will be reported.\n\n        Note that the start and end locations are reported relative to the string\n        being parsed.  See :class:`parse_string` for more information on parsing\n        strings with embedded tabs.\n\n        Example::\n\n            source = \"sldjf123lsdjjkf345sldkjf879lkjsfd987\"\n            print(source)\n            for tokens, start, end in Word(alphas).scan_string(source):\n                print(' '*start + '^'*(end-start))\n                print(' '*start + tokens[0])\n\n        prints::\n\n            sldjf123lsdjjkf345sldkjf879lkjsfd987\n            ^^^^^\n            sldjf\n                    ^^^^^^^\n                    lsdjjkf\n                              ^^^^^^\n                              sldkjf\n                                       ^^^^^^\n                                       lkjsfd\n        \"\"\"\n        maxMatches = min(maxMatches, max_matches)\n        if not self.streamlined:\n            self.streamline()\n        for e in self.ignoreExprs:\n            e.streamline()\n\n        if not self.keepTabs:\n            instring = str(instring).expandtabs()\n        instrlen = len(instring)\n        loc = 0\n        preparseFn = self.preParse\n        parseFn = self._parse\n        ParserElement.resetCache()\n        matches = 0\n        try:\n            while loc <= instrlen and matches < maxMatches:\n                try:\n                    preloc = preparseFn(instring, loc)\n                    nextLoc, tokens = parseFn(instring, preloc, callPreParse=False)\n                except ParseException:\n                    loc = preloc + 1\n                else:\n                    if nextLoc > loc:\n                        matches += 1\n                        if debug:\n                            print(\n                                {\n                                    \"tokens\": tokens.asList(),\n                                    \"start\": preloc,\n                                    \"end\": nextLoc,\n                                }\n                            )\n                        yield tokens, preloc, nextLoc\n                        if overlap:\n                            nextloc = preparseFn(instring, loc)\n                            if nextloc > loc:\n                                loc = nextLoc\n                            else:\n                                loc += 1\n                        else:\n                            loc = nextLoc\n                    else:\n                        loc = preloc + 1\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clears out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n\n    def transform_string(self, instring: str, *, debug: bool = False) -> str:\n        \"\"\"\n        Extension to :class:`scan_string`, to modify matching text with modified tokens that may\n        be returned from a parse action.  To use ``transform_string``, define a grammar and\n        attach a parse action to it that modifies the returned token list.\n        Invoking ``transform_string()`` on a target string will then scan for matches,\n        and replace the matched text patterns according to the logic in the parse\n        action.  ``transform_string()`` returns the resulting transformed string.\n\n        Example::\n\n            wd = Word(alphas)\n            wd.set_parse_action(lambda toks: toks[0].title())\n\n            print(wd.transform_string(\"now is the winter of our discontent made glorious summer by this sun of york.\"))\n\n        prints::\n\n            Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.\n        \"\"\"\n        out: List[str] = []\n        lastE = 0\n        # force preservation of <TAB>s, to minimize unwanted transformation of string, and to\n        # keep string locs straight between transform_string and scan_string\n        self.keepTabs = True\n        try:\n            for t, s, e in self.scan_string(instring, debug=debug):\n                out.append(instring[lastE:s])\n                if t:\n                    if isinstance(t, ParseResults):\n                        out += t.as_list()\n                    elif isinstance(t, Iterable) and not isinstance(t, str_type):\n                        out.extend(t)\n                    else:\n                        out.append(t)\n                lastE = e\n            out.append(instring[lastE:])\n            out = [o for o in out if o]\n            return \"\".join([str(s) for s in _flatten(out)])\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clears out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n\n    def search_string(\n        self,\n        instring: str,\n        max_matches: int = _MAX_INT,\n        *,\n        debug: bool = False,\n        maxMatches: int = _MAX_INT,\n    ) -> ParseResults:\n        \"\"\"\n        Another extension to :class:`scan_string`, simplifying the access to the tokens found\n        to match the given parse expression.  May be called with optional\n        ``max_matches`` argument, to clip searching after 'n' matches are found.\n\n        Example::\n\n            # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters\n            cap_word = Word(alphas.upper(), alphas.lower())\n\n            print(cap_word.search_string(\"More than Iron, more than Lead, more than Gold I need Electricity\"))\n\n            # the sum() builtin can be used to merge results into a single ParseResults object\n            print(sum(cap_word.search_string(\"More than Iron, more than Lead, more than Gold I need Electricity\")))\n\n        prints::\n\n            [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']]\n            ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity']\n        \"\"\"\n        maxMatches = min(maxMatches, max_matches)\n        try:\n            return ParseResults(\n                [t for t, s, e in self.scan_string(instring, maxMatches, debug=debug)]\n            )\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clears out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n\n    def split(\n        self,\n        instring: str,\n        maxsplit: int = _MAX_INT,\n        include_separators: bool = False,\n        *,\n        includeSeparators=False,\n    ) -> Generator[str, None, None]:\n        \"\"\"\n        Generator method to split a string using the given expression as a separator.\n        May be called with optional ``maxsplit`` argument, to limit the number of splits;\n        and the optional ``include_separators`` argument (default= ``False``), if the separating\n        matching text should be included in the split results.\n\n        Example::\n\n            punc = one_of(list(\".,;:/-!?\"))\n            print(list(punc.split(\"This, this?, this sentence, is badly punctuated!\")))\n\n        prints::\n\n            ['This', ' this', '', ' this sentence', ' is badly punctuated', '']\n        \"\"\"\n        includeSeparators = includeSeparators or include_separators\n        last = 0\n        for t, s, e in self.scan_string(instring, max_matches=maxsplit):\n            yield instring[last:s]\n            if includeSeparators:\n                yield t[0]\n            last = e\n        yield instring[last:]\n\n    def __add__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``+`` operator - returns :class:`And`. Adding strings to a :class:`ParserElement`\n        converts them to :class:`Literal`s by default.\n\n        Example::\n\n            greet = Word(alphas) + \",\" + Word(alphas) + \"!\"\n            hello = \"Hello, World!\"\n            print(hello, \"->\", greet.parse_string(hello))\n\n        prints::\n\n            Hello, World! -> ['Hello', ',', 'World', '!']\n\n        ``...`` may be used as a parse expression as a short form of :class:`SkipTo`.\n\n            Literal('start') + ... + Literal('end')\n\n        is equivalent to:\n\n            Literal('start') + SkipTo('end')(\"_skipped*\") + Literal('end')\n\n        Note that the skipped text is returned with '_skipped' as a results name,\n        and to support having multiple skips in the same parser, the value returned is\n        a list of all skipped text.\n        \"\"\"\n        if other is Ellipsis:\n            return _PendingSkip(self)\n\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return And([self, other])\n\n    def __radd__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``+`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if other is Ellipsis:\n            return SkipTo(self)(\"_skipped*\") + self\n\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other + self\n\n    def __sub__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``-`` operator, returns :class:`And` with error stop\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return self + And._ErrorStop() + other\n\n    def __rsub__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``-`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other - self\n\n    def __mul__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``*`` operator, allows use of ``expr * 3`` in place of\n        ``expr + expr + expr``.  Expressions may also be multiplied by a 2-integer\n        tuple, similar to ``{min, max}`` multipliers in regular expressions.  Tuples\n        may also include ``None`` as in:\n        - ``expr*(n, None)`` or ``expr*(n, )`` is equivalent\n             to ``expr*n + ZeroOrMore(expr)``\n             (read as \"at least n instances of ``expr``\")\n        - ``expr*(None, n)`` is equivalent to ``expr*(0, n)``\n             (read as \"0 to n instances of ``expr``\")\n        - ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)``\n        - ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)``\n\n        Note that ``expr*(None, n)`` does not raise an exception if\n        more than n exprs exist in the input stream; that is,\n        ``expr*(None, n)`` does not enforce a maximum number of expr\n        occurrences.  If this behavior is desired, then write\n        ``expr*(None, n) + ~expr``\n        \"\"\"\n        if other is Ellipsis:\n            other = (0, None)\n        elif isinstance(other, tuple) and other[:1] == (Ellipsis,):\n            other = ((0,) + other[1:] + (None,))[:2]\n\n        if isinstance(other, int):\n            minElements, optElements = other, 0\n        elif isinstance(other, tuple):\n            other = tuple(o if o is not Ellipsis else None for o in other)\n            other = (other + (None, None))[:2]\n            if other[0] is None:\n                other = (0, other[1])\n            if isinstance(other[0], int) and other[1] is None:\n                if other[0] == 0:\n                    return ZeroOrMore(self)\n                if other[0] == 1:\n                    return OneOrMore(self)\n                else:\n                    return self * other[0] + ZeroOrMore(self)\n            elif isinstance(other[0], int) and isinstance(other[1], int):\n                minElements, optElements = other\n                optElements -= minElements\n            else:\n                raise TypeError(\n                    \"cannot multiply ParserElement and ({}) objects\".format(\n                        \",\".join(type(item).__name__ for item in other)\n                    )\n                )\n        else:\n            raise TypeError(\n                \"cannot multiply ParserElement and {} objects\".format(\n                    type(other).__name__\n                )\n            )\n\n        if minElements < 0:\n            raise ValueError(\"cannot multiply ParserElement by negative value\")\n        if optElements < 0:\n            raise ValueError(\n                \"second tuple value must be greater or equal to first tuple value\"\n            )\n        if minElements == optElements == 0:\n            return And([])\n\n        if optElements:\n\n            def makeOptionalList(n):\n                if n > 1:\n                    return Opt(self + makeOptionalList(n - 1))\n                else:\n                    return Opt(self)\n\n            if minElements:\n                if minElements == 1:\n                    ret = self + makeOptionalList(optElements)\n                else:\n                    ret = And([self] * minElements) + makeOptionalList(optElements)\n            else:\n                ret = makeOptionalList(optElements)\n        else:\n            if minElements == 1:\n                ret = self\n            else:\n                ret = And([self] * minElements)\n        return ret\n\n    def __rmul__(self, other) -> \"ParserElement\":\n        return self.__mul__(other)\n\n    def __or__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``|`` operator - returns :class:`MatchFirst`\n        \"\"\"\n        if other is Ellipsis:\n            return _PendingSkip(self, must_skip=True)\n\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return MatchFirst([self, other])\n\n    def __ror__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``|`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other | self\n\n    def __xor__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``^`` operator - returns :class:`Or`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return Or([self, other])\n\n    def __rxor__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``^`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other ^ self\n\n    def __and__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``&`` operator - returns :class:`Each`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return Each([self, other])\n\n    def __rand__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``&`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other & self\n\n    def __invert__(self) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``~`` operator - returns :class:`NotAny`\n        \"\"\"\n        return NotAny(self)\n\n    # disable __iter__ to override legacy use of sequential access to __getitem__ to\n    # iterate over a sequence\n    __iter__ = None\n\n    def __getitem__(self, key):\n        \"\"\"\n        use ``[]`` indexing notation as a short form for expression repetition:\n\n        - ``expr[n]`` is equivalent to ``expr*n``\n        - ``expr[m, n]`` is equivalent to ``expr*(m, n)``\n        - ``expr[n, ...]`` or ``expr[n,]`` is equivalent\n             to ``expr*n + ZeroOrMore(expr)``\n             (read as \"at least n instances of ``expr``\")\n        - ``expr[..., n]`` is equivalent to ``expr*(0, n)``\n             (read as \"0 to n instances of ``expr``\")\n        - ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)``\n        - ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)``\n\n        ``None`` may be used in place of ``...``.\n\n        Note that ``expr[..., n]`` and ``expr[m, n]``do not raise an exception\n        if more than ``n`` ``expr``s exist in the input stream.  If this behavior is\n        desired, then write ``expr[..., n] + ~expr``.\n        \"\"\"\n\n        # convert single arg keys to tuples\n        try:\n            if isinstance(key, str_type):\n                key = (key,)\n            iter(key)\n        except TypeError:\n            key = (key, key)\n\n        if len(key) > 2:\n            raise TypeError(\n                \"only 1 or 2 index arguments supported ({}{})\".format(\n                    key[:5], \"... [{}]\".format(len(key)) if len(key) > 5 else \"\"\n                )\n            )\n\n        # clip to 2 elements\n        ret = self * tuple(key[:2])\n        return ret\n\n    def __call__(self, name: str = None) -> \"ParserElement\":\n        \"\"\"\n        Shortcut for :class:`set_results_name`, with ``list_all_matches=False``.\n\n        If ``name`` is given with a trailing ``'*'`` character, then ``list_all_matches`` will be\n        passed as ``True``.\n\n        If ``name` is omitted, same as calling :class:`copy`.\n\n        Example::\n\n            # these are equivalent\n            userdata = Word(alphas).set_results_name(\"name\") + Word(nums + \"-\").set_results_name(\"socsecno\")\n            userdata = Word(alphas)(\"name\") + Word(nums + \"-\")(\"socsecno\")\n        \"\"\"\n        if name is not None:\n            return self._setResultsName(name)\n        else:\n            return self.copy()\n\n    def suppress(self) -> \"ParserElement\":\n        \"\"\"\n        Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from\n        cluttering up returned output.\n        \"\"\"\n        return Suppress(self)\n\n    def ignore_whitespace(self, recursive: bool = True) -> \"ParserElement\":\n        \"\"\"\n        Enables the skipping of whitespace before matching the characters in the\n        :class:`ParserElement`'s defined pattern.\n\n        :param recursive: If ``True`` (the default), also enable whitespace skipping in child elements (if any)\n        \"\"\"\n        self.skipWhitespace = True\n        return self\n\n    def leave_whitespace(self, recursive: bool = True) -> \"ParserElement\":\n        \"\"\"\n        Disables the skipping of whitespace before matching the characters in the\n        :class:`ParserElement`'s defined pattern.  This is normally only used internally by\n        the pyparsing module, but may be needed in some whitespace-sensitive grammars.\n\n        :param recursive: If true (the default), also disable whitespace skipping in child elements (if any)\n        \"\"\"\n        self.skipWhitespace = False\n        return self\n\n    def set_whitespace_chars(\n        self, chars: Union[Set[str], str], copy_defaults: bool = False\n    ) -> \"ParserElement\":\n        \"\"\"\n        Overrides the default whitespace chars\n        \"\"\"\n        self.skipWhitespace = True\n        self.whiteChars = set(chars)\n        self.copyDefaultWhiteChars = copy_defaults\n        return self\n\n    def parse_with_tabs(self) -> \"ParserElement\":\n        \"\"\"\n        Overrides default behavior to expand ``<TAB>`` s to spaces before parsing the input string.\n        Must be called before ``parse_string`` when the input grammar contains elements that\n        match ``<TAB>`` characters.\n        \"\"\"\n        self.keepTabs = True\n        return self\n\n    def ignore(self, other: \"ParserElement\") -> \"ParserElement\":\n        \"\"\"\n        Define expression to be ignored (e.g., comments) while doing pattern\n        matching; may be called repeatedly, to define multiple comment or other\n        ignorable patterns.\n\n        Example::\n\n            patt = Word(alphas)[1, ...]\n            patt.parse_string('ablaj /* comment */ lskjd')\n            # -> ['ablaj']\n\n            patt.ignore(c_style_comment)\n            patt.parse_string('ablaj /* comment */ lskjd')\n            # -> ['ablaj', 'lskjd']\n        \"\"\"\n        import typing\n\n        if isinstance(other, str_type):\n            other = Suppress(other)\n\n        if isinstance(other, Suppress):\n            if other not in self.ignoreExprs:\n                self.ignoreExprs.append(other)\n        else:\n            self.ignoreExprs.append(Suppress(other.copy()))\n        return self\n\n    def set_debug_actions(\n        self,\n        start_action: DebugStartAction,\n        success_action: DebugSuccessAction,\n        exception_action: DebugExceptionAction,\n    ) -> \"ParserElement\":\n        \"\"\"\n        Customize display of debugging messages while doing pattern matching:\n\n        - ``start_action`` - method to be called when an expression is about to be parsed;\n          should have the signature ``fn(input_string: str, location: int, expression: ParserElement, cache_hit: bool)``\n\n        - ``success_action`` - method to be called when an expression has successfully parsed;\n          should have the signature ``fn(input_string: str, start_location: int, end_location: int, expression: ParserELement, parsed_tokens: ParseResults, cache_hit: bool)``\n\n        - ``exception_action`` - method to be called when expression fails to parse;\n          should have the signature ``fn(input_string: str, location: int, expression: ParserElement, exception: Exception, cache_hit: bool)``\n        \"\"\"\n        self.debugActions = self.DebugActions(\n            start_action or _default_start_debug_action,\n            success_action or _default_success_debug_action,\n            exception_action or _default_exception_debug_action,\n        )\n        self.debug = True\n        return self\n\n    def set_debug(self, flag: bool = True) -> \"ParserElement\":\n        \"\"\"\n        Enable display of debugging messages while doing pattern matching.\n        Set ``flag`` to ``True`` to enable, ``False`` to disable.\n\n        Example::\n\n            wd = Word(alphas).set_name(\"alphaword\")\n            integer = Word(nums).set_name(\"numword\")\n            term = wd | integer\n\n            # turn on debugging for wd\n            wd.set_debug()\n\n            term[1, ...].parse_string(\"abc 123 xyz 890\")\n\n        prints::\n\n            Match alphaword at loc 0(1,1)\n            Matched alphaword -> ['abc']\n            Match alphaword at loc 3(1,4)\n            Exception raised:Expected alphaword (at char 4), (line:1, col:5)\n            Match alphaword at loc 7(1,8)\n            Matched alphaword -> ['xyz']\n            Match alphaword at loc 11(1,12)\n            Exception raised:Expected alphaword (at char 12), (line:1, col:13)\n            Match alphaword at loc 15(1,16)\n            Exception raised:Expected alphaword (at char 15), (line:1, col:16)\n\n        The output shown is that produced by the default debug actions - custom debug actions can be\n        specified using :class:`set_debug_actions`. Prior to attempting\n        to match the ``wd`` expression, the debugging message ``\"Match <exprname> at loc <n>(<line>,<col>)\"``\n        is shown. Then if the parse succeeds, a ``\"Matched\"`` message is shown, or an ``\"Exception raised\"``\n        message is shown. Also note the use of :class:`set_name` to assign a human-readable name to the expression,\n        which makes debugging and exception messages easier to understand - for instance, the default\n        name created for the :class:`Word` expression without calling ``set_name`` is ``\"W:(A-Za-z)\"``.\n        \"\"\"\n        if flag:\n            self.set_debug_actions(\n                _default_start_debug_action,\n                _default_success_debug_action,\n                _default_exception_debug_action,\n            )\n        else:\n            self.debug = False\n        return self\n\n    @property\n    def default_name(self) -> str:\n        if self._defaultName is None:\n            self._defaultName = self._generateDefaultName()\n        return self._defaultName\n\n    @abstractmethod\n    def _generateDefaultName(self):\n        \"\"\"\n        Child classes must define this method, which defines how the ``default_name`` is set.\n        \"\"\"\n\n    def set_name(self, name: str) -> \"ParserElement\":\n        \"\"\"\n        Define name for this expression, makes debugging and exception messages clearer.\n        Example::\n            Word(nums).parse_string(\"ABC\")  # -> Exception: Expected W:(0-9) (at char 0), (line:1, col:1)\n            Word(nums).set_name(\"integer\").parse_string(\"ABC\")  # -> Exception: Expected integer (at char 0), (line:1, col:1)\n        \"\"\"\n        self.customName = name\n        self.errmsg = \"Expected \" + self.name\n        if __diag__.enable_debug_on_named_expressions:\n            self.set_debug()\n        return self\n\n    @property\n    def name(self) -> str:\n        # This will use a user-defined name if available, but otherwise defaults back to the auto-generated name\n        return self.customName if self.customName is not None else self.default_name\n\n    def __str__(self) -> str:\n        return self.name\n\n    def __repr__(self) -> str:\n        return str(self)\n\n    def streamline(self) -> \"ParserElement\":\n        self.streamlined = True\n        self._defaultName = None\n        return self\n\n    def recurse(self) -> Sequence[\"ParserElement\"]:\n        return []\n\n    def _checkRecursion(self, parseElementList):\n        subRecCheckList = parseElementList[:] + [self]\n        for e in self.recurse():\n            e._checkRecursion(subRecCheckList)\n\n    def validate(self, validateTrace=None) -> None:\n        \"\"\"\n        Check defined expressions for valid structure, check for infinite recursive definitions.\n        \"\"\"\n        self._checkRecursion([])\n\n    def parse_file(\n        self,\n        file_or_filename: Union[str, Path, TextIO],\n        encoding: str = \"utf-8\",\n        parse_all: bool = False,\n        *,\n        parseAll: bool = False,\n    ) -> ParseResults:\n        \"\"\"\n        Execute the parse expression on the given file or filename.\n        If a filename is specified (instead of a file object),\n        the entire file is opened, read, and closed before parsing.\n        \"\"\"\n        parseAll = parseAll or parse_all\n        try:\n            file_contents = file_or_filename.read()\n        except AttributeError:\n            with open(file_or_filename, \"r\", encoding=encoding) as f:\n                file_contents = f.read()\n        try:\n            return self.parse_string(file_contents, parseAll)\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clears out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif isinstance(other, str_type):\n            return self.matches(other, parse_all=True)\n        elif isinstance(other, ParserElement):\n            return vars(self) == vars(other)\n        return False\n\n    def __hash__(self):\n        return id(self)\n\n    def matches(\n        self, test_string: str, parse_all: bool = True, *, parseAll: bool = True\n    ) -> bool:\n        \"\"\"\n        Method for quick testing of a parser against a test string. Good for simple\n        inline microtests of sub expressions while building up larger parser.\n\n        Parameters:\n        - ``test_string`` - to test against this expression for a match\n        - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests\n\n        Example::\n\n            expr = Word(nums)\n            assert expr.matches(\"100\")\n        \"\"\"\n        parseAll = parseAll and parse_all\n        try:\n            self.parse_string(str(test_string), parse_all=parseAll)\n            return True\n        except ParseBaseException:\n            return False\n\n    def run_tests(\n        self,\n        tests: Union[str, List[str]],\n        parse_all: bool = True,\n        comment: typing.Optional[Union[\"ParserElement\", str]] = \"#\",\n        full_dump: bool = True,\n        print_results: bool = True,\n        failure_tests: bool = False,\n        post_parse: Callable[[str, ParseResults], str] = None,\n        file: typing.Optional[TextIO] = None,\n        with_line_numbers: bool = False,\n        *,\n        parseAll: bool = True,\n        fullDump: bool = True,\n        printResults: bool = True,\n        failureTests: bool = False,\n        postParse: Callable[[str, ParseResults], str] = None,\n    ) -> Tuple[bool, List[Tuple[str, Union[ParseResults, Exception]]]]:\n        \"\"\"\n        Execute the parse expression on a series of test strings, showing each\n        test, the parsed results or where the parse failed. Quick and easy way to\n        run a parse expression against a list of sample strings.\n\n        Parameters:\n        - ``tests`` - a list of separate test strings, or a multiline string of test strings\n        - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests\n        - ``comment`` - (default= ``'#'``) - expression for indicating embedded comments in the test\n          string; pass None to disable comment filtering\n        - ``full_dump`` - (default= ``True``) - dump results as list followed by results names in nested outline;\n          if False, only dump nested list\n        - ``print_results`` - (default= ``True``) prints test output to stdout\n        - ``failure_tests`` - (default= ``False``) indicates if these tests are expected to fail parsing\n        - ``post_parse`` - (default= ``None``) optional callback for successful parse results; called as\n          `fn(test_string, parse_results)` and returns a string to be added to the test output\n        - ``file`` - (default= ``None``) optional file-like object to which test output will be written;\n          if None, will default to ``sys.stdout``\n        - ``with_line_numbers`` - default= ``False``) show test strings with line and column numbers\n\n        Returns: a (success, results) tuple, where success indicates that all tests succeeded\n        (or failed if ``failure_tests`` is True), and the results contain a list of lines of each\n        test's output\n\n        Example::\n\n            number_expr = pyparsing_common.number.copy()\n\n            result = number_expr.run_tests('''\n                # unsigned integer\n                100\n                # negative integer\n                -100\n                # float with scientific notation\n                6.02e23\n                # integer with scientific notation\n                1e-12\n                ''')\n            print(\"Success\" if result[0] else \"Failed!\")\n\n            result = number_expr.run_tests('''\n                # stray character\n                100Z\n                # missing leading digit before '.'\n                -.100\n                # too many '.'\n                3.14.159\n                ''', failure_tests=True)\n            print(\"Success\" if result[0] else \"Failed!\")\n\n        prints::\n\n            # unsigned integer\n            100\n            [100]\n\n            # negative integer\n            -100\n            [-100]\n\n            # float with scientific notation\n            6.02e23\n            [6.02e+23]\n\n            # integer with scientific notation\n            1e-12\n            [1e-12]\n\n            Success\n\n            # stray character\n            100Z\n               ^\n            FAIL: Expected end of text (at char 3), (line:1, col:4)\n\n            # missing leading digit before '.'\n            -.100\n            ^\n            FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)\n\n            # too many '.'\n            3.14.159\n                ^\n            FAIL: Expected end of text (at char 4), (line:1, col:5)\n\n            Success\n\n        Each test string must be on a single line. If you want to test a string that spans multiple\n        lines, create a test like this::\n\n            expr.run_tests(r\"this is a test\\\\n of strings that spans \\\\n 3 lines\")\n\n        (Note that this is a raw string literal, you must include the leading ``'r'``.)\n        \"\"\"\n        from .testing import pyparsing_test\n\n        parseAll = parseAll and parse_all\n        fullDump = fullDump and full_dump\n        printResults = printResults and print_results\n        failureTests = failureTests or failure_tests\n        postParse = postParse or post_parse\n        if isinstance(tests, str_type):\n            line_strip = type(tests).strip\n            tests = [line_strip(test_line) for test_line in tests.rstrip().splitlines()]\n        if isinstance(comment, str_type):\n            comment = Literal(comment)\n        if file is None:\n            file = sys.stdout\n        print_ = file.write\n\n        result: Union[ParseResults, Exception]\n        allResults = []\n        comments = []\n        success = True\n        NL = Literal(r\"\\n\").add_parse_action(replace_with(\"\\n\")).ignore(quoted_string)\n        BOM = \"\\ufeff\"\n        for t in tests:\n            if comment is not None and comment.matches(t, False) or comments and not t:\n                comments.append(\n                    pyparsing_test.with_line_numbers(t) if with_line_numbers else t\n                )\n                continue\n            if not t:\n                continue\n            out = [\n                \"\\n\" + \"\\n\".join(comments) if comments else \"\",\n                pyparsing_test.with_line_numbers(t) if with_line_numbers else t,\n            ]\n            comments = []\n            try:\n                # convert newline marks to actual newlines, and strip leading BOM if present\n                t = NL.transform_string(t.lstrip(BOM))\n                result = self.parse_string(t, parse_all=parseAll)\n            except ParseBaseException as pe:\n                fatal = \"(FATAL)\" if isinstance(pe, ParseFatalException) else \"\"\n                out.append(pe.explain())\n                out.append(\"FAIL: \" + str(pe))\n                if ParserElement.verbose_stacktrace:\n                    out.extend(traceback.format_tb(pe.__traceback__))\n                success = success and failureTests\n                result = pe\n            except Exception as exc:\n                out.append(\"FAIL-EXCEPTION: {}: {}\".format(type(exc).__name__, exc))\n                if ParserElement.verbose_stacktrace:\n                    out.extend(traceback.format_tb(exc.__traceback__))\n                success = success and failureTests\n                result = exc\n            else:\n                success = success and not failureTests\n                if postParse is not None:\n                    try:\n                        pp_value = postParse(t, result)\n                        if pp_value is not None:\n                            if isinstance(pp_value, ParseResults):\n                                out.append(pp_value.dump())\n                            else:\n                                out.append(str(pp_value))\n                        else:\n                            out.append(result.dump())\n                    except Exception as e:\n                        out.append(result.dump(full=fullDump))\n                        out.append(\n                            \"{} failed: {}: {}\".format(\n                                postParse.__name__, type(e).__name__, e\n                            )\n                        )\n                else:\n                    out.append(result.dump(full=fullDump))\n            out.append(\"\")\n\n            if printResults:\n                print_(\"\\n\".join(out))\n\n            allResults.append((t, result))\n\n        return success, allResults\n\n    def create_diagram(\n        self,\n        output_html: Union[TextIO, Path, str],\n        vertical: int = 3,\n        show_results_names: bool = False,\n        show_groups: bool = False,\n        **kwargs,\n    ) -> None:\n        \"\"\"\n        Create a railroad diagram for the parser.\n\n        Parameters:\n        - output_html (str or file-like object) - output target for generated\n          diagram HTML\n        - vertical (int) - threshold for formatting multiple alternatives vertically\n          instead of horizontally (default=3)\n        - show_results_names - bool flag whether diagram should show annotations for\n          defined results names\n        - show_groups - bool flag whether groups should be highlighted with an unlabeled surrounding box\n        Additional diagram-formatting keyword arguments can also be included;\n        see railroad.Diagram class.\n        \"\"\"\n\n        try:\n            from .diagram import to_railroad, railroad_to_html\n        except ImportError as ie:\n            raise Exception(\n                \"must ``pip install pyparsing[diagrams]`` to generate parser railroad diagrams\"\n            ) from ie\n\n        self.streamline()\n\n        railroad = to_railroad(\n            self,\n            vertical=vertical,\n            show_results_names=show_results_names,\n            show_groups=show_groups,\n            diagram_kwargs=kwargs,\n        )\n        if isinstance(output_html, (str, Path)):\n            with open(output_html, \"w\", encoding=\"utf-8\") as diag_file:\n                diag_file.write(railroad_to_html(railroad))\n        else:\n            # we were passed a file-like object, just write to it\n            output_html.write(railroad_to_html(railroad))\n\n    setDefaultWhitespaceChars = set_default_whitespace_chars\n    inlineLiteralsUsing = inline_literals_using\n    setResultsName = set_results_name\n    setBreak = set_break\n    setParseAction = set_parse_action\n    addParseAction = add_parse_action\n    addCondition = add_condition\n    setFailAction = set_fail_action\n    tryParse = try_parse\n    canParseNext = can_parse_next\n    resetCache = reset_cache\n    enableLeftRecursion = enable_left_recursion\n    enablePackrat = enable_packrat\n    parseString = parse_string\n    scanString = scan_string\n    searchString = search_string\n    transformString = transform_string\n    setWhitespaceChars = set_whitespace_chars\n    parseWithTabs = parse_with_tabs\n    setDebugActions = set_debug_actions\n    setDebug = set_debug\n    defaultName = default_name\n    setName = set_name\n    parseFile = parse_file\n    runTests = run_tests\n    ignoreWhitespace = ignore_whitespace\n    leaveWhitespace = leave_whitespace\n\n\nclass _PendingSkip(ParserElement):\n    # internal placeholder class to hold a place were '...' is added to a parser element,\n    # once another ParserElement is added, this placeholder will be replaced with a SkipTo\n    def __init__(self, expr: ParserElement, must_skip: bool = False):\n        super().__init__()\n        self.anchor = expr\n        self.must_skip = must_skip\n\n    def _generateDefaultName(self):\n        return str(self.anchor + Empty()).replace(\"Empty\", \"...\")\n\n    def __add__(self, other) -> \"ParserElement\":\n        skipper = SkipTo(other).set_name(\"...\")(\"_skipped*\")\n        if self.must_skip:\n\n            def must_skip(t):\n                if not t._skipped or t._skipped.as_list() == [\"\"]:\n                    del t[0]\n                    t.pop(\"_skipped\", None)\n\n            def show_skip(t):\n                if t._skipped.as_list()[-1:] == [\"\"]:\n                    t.pop(\"_skipped\")\n                    t[\"_skipped\"] = \"missing <\" + repr(self.anchor) + \">\"\n\n            return (\n                self.anchor + skipper().add_parse_action(must_skip)\n                | skipper().add_parse_action(show_skip)\n            ) + other\n\n        return self.anchor + skipper + other\n\n    def __repr__(self):\n        return self.defaultName\n\n    def parseImpl(self, *args):\n        raise Exception(\n            \"use of `...` expression without following SkipTo target expression\"\n        )\n\n\nclass Token(ParserElement):\n    \"\"\"Abstract :class:`ParserElement` subclass, for defining atomic\n    matching patterns.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__(savelist=False)\n\n    def _generateDefaultName(self):\n        return type(self).__name__\n\n\nclass Empty(Token):\n    \"\"\"\n    An empty token, will always match.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n\n\nclass NoMatch(Token):\n    \"\"\"\n    A token that will never match.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n        self.errmsg = \"Unmatchable token\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass Literal(Token):\n    \"\"\"\n    Token to exactly match a specified string.\n\n    Example::\n\n        Literal('blah').parse_string('blah')  # -> ['blah']\n        Literal('blah').parse_string('blahfooblah')  # -> ['blah']\n        Literal('blah').parse_string('bla')  # -> Exception: Expected \"blah\"\n\n    For case-insensitive matching, use :class:`CaselessLiteral`.\n\n    For keyword matching (force word break before and after the matched string),\n    use :class:`Keyword` or :class:`CaselessKeyword`.\n    \"\"\"\n\n    def __init__(self, match_string: str = \"\", *, matchString: str = \"\"):\n        super().__init__()\n        match_string = matchString or match_string\n        self.match = match_string\n        self.matchLen = len(match_string)\n        try:\n            self.firstMatchChar = match_string[0]\n        except IndexError:\n            raise ValueError(\"null string passed to Literal; use Empty() instead\")\n        self.errmsg = \"Expected \" + self.name\n        self.mayReturnEmpty = False\n        self.mayIndexError = False\n\n        # Performance tuning: modify __class__ to select\n        # a parseImpl optimized for single-character check\n        if self.matchLen == 1 and type(self) is Literal:\n            self.__class__ = _SingleCharLiteral\n\n    def _generateDefaultName(self):\n        return repr(self.match)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc] == self.firstMatchChar and instring.startswith(\n            self.match, loc\n        ):\n            return loc + self.matchLen, self.match\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass _SingleCharLiteral(Literal):\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc] == self.firstMatchChar:\n            return loc + 1, self.match\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nParserElement._literalStringClass = Literal\n\n\nclass Keyword(Token):\n    \"\"\"\n    Token to exactly match a specified string as a keyword, that is,\n    it must be immediately followed by a non-keyword character.  Compare\n    with :class:`Literal`:\n\n    - ``Literal(\"if\")`` will match the leading ``'if'`` in\n      ``'ifAndOnlyIf'``.\n    - ``Keyword(\"if\")`` will not; it will only match the leading\n      ``'if'`` in ``'if x=1'``, or ``'if(y==2)'``\n\n    Accepts two optional constructor arguments in addition to the\n    keyword string:\n\n    - ``identChars`` is a string of characters that would be valid\n      identifier characters, defaulting to all alphanumerics + \"_\" and\n      \"$\"\n    - ``caseless`` allows case-insensitive matching, default is ``False``.\n\n    Example::\n\n        Keyword(\"start\").parse_string(\"start\")  # -> ['start']\n        Keyword(\"start\").parse_string(\"starting\")  # -> Exception\n\n    For case-insensitive matching, use :class:`CaselessKeyword`.\n    \"\"\"\n\n    DEFAULT_KEYWORD_CHARS = alphanums + \"_$\"\n\n    def __init__(\n        self,\n        match_string: str = \"\",\n        ident_chars: typing.Optional[str] = None,\n        caseless: bool = False,\n        *,\n        matchString: str = \"\",\n        identChars: typing.Optional[str] = None,\n    ):\n        super().__init__()\n        identChars = identChars or ident_chars\n        if identChars is None:\n            identChars = Keyword.DEFAULT_KEYWORD_CHARS\n        match_string = matchString or match_string\n        self.match = match_string\n        self.matchLen = len(match_string)\n        try:\n            self.firstMatchChar = match_string[0]\n        except IndexError:\n            raise ValueError(\"null string passed to Keyword; use Empty() instead\")\n        self.errmsg = \"Expected {} {}\".format(type(self).__name__, self.name)\n        self.mayReturnEmpty = False\n        self.mayIndexError = False\n        self.caseless = caseless\n        if caseless:\n            self.caselessmatch = match_string.upper()\n            identChars = identChars.upper()\n        self.identChars = set(identChars)\n\n    def _generateDefaultName(self):\n        return repr(self.match)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        errmsg = self.errmsg\n        errloc = loc\n        if self.caseless:\n            if instring[loc : loc + self.matchLen].upper() == self.caselessmatch:\n                if loc == 0 or instring[loc - 1].upper() not in self.identChars:\n                    if (\n                        loc >= len(instring) - self.matchLen\n                        or instring[loc + self.matchLen].upper() not in self.identChars\n                    ):\n                        return loc + self.matchLen, self.match\n                    else:\n                        # followed by keyword char\n                        errmsg += \", was immediately followed by keyword character\"\n                        errloc = loc + self.matchLen\n                else:\n                    # preceded by keyword char\n                    errmsg += \", keyword was immediately preceded by keyword character\"\n                    errloc = loc - 1\n            # else no match just raise plain exception\n\n        else:\n            if (\n                instring[loc] == self.firstMatchChar\n                and self.matchLen == 1\n                or instring.startswith(self.match, loc)\n            ):\n                if loc == 0 or instring[loc - 1] not in self.identChars:\n                    if (\n                        loc >= len(instring) - self.matchLen\n                        or instring[loc + self.matchLen] not in self.identChars\n                    ):\n                        return loc + self.matchLen, self.match\n                    else:\n                        # followed by keyword char\n                        errmsg += (\n                            \", keyword was immediately followed by keyword character\"\n                        )\n                        errloc = loc + self.matchLen\n                else:\n                    # preceded by keyword char\n                    errmsg += \", keyword was immediately preceded by keyword character\"\n                    errloc = loc - 1\n            # else no match just raise plain exception\n\n        raise ParseException(instring, errloc, errmsg, self)\n\n    @staticmethod\n    def set_default_keyword_chars(chars) -> None:\n        \"\"\"\n        Overrides the default characters used by :class:`Keyword` expressions.\n        \"\"\"\n        Keyword.DEFAULT_KEYWORD_CHARS = chars\n\n    setDefaultKeywordChars = set_default_keyword_chars\n\n\nclass CaselessLiteral(Literal):\n    \"\"\"\n    Token to match a specified string, ignoring case of letters.\n    Note: the matched results will always be in the case of the given\n    match string, NOT the case of the input text.\n\n    Example::\n\n        CaselessLiteral(\"CMD\")[1, ...].parse_string(\"cmd CMD Cmd10\")\n        # -> ['CMD', 'CMD', 'CMD']\n\n    (Contrast with example for :class:`CaselessKeyword`.)\n    \"\"\"\n\n    def __init__(self, match_string: str = \"\", *, matchString: str = \"\"):\n        match_string = matchString or match_string\n        super().__init__(match_string.upper())\n        # Preserve the defining literal.\n        self.returnString = match_string\n        self.errmsg = \"Expected \" + self.name\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc : loc + self.matchLen].upper() == self.match:\n            return loc + self.matchLen, self.returnString\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass CaselessKeyword(Keyword):\n    \"\"\"\n    Caseless version of :class:`Keyword`.\n\n    Example::\n\n        CaselessKeyword(\"CMD\")[1, ...].parse_string(\"cmd CMD Cmd10\")\n        # -> ['CMD', 'CMD']\n\n    (Contrast with example for :class:`CaselessLiteral`.)\n    \"\"\"\n\n    def __init__(\n        self,\n        match_string: str = \"\",\n        ident_chars: typing.Optional[str] = None,\n        *,\n        matchString: str = \"\",\n        identChars: typing.Optional[str] = None,\n    ):\n        identChars = identChars or ident_chars\n        match_string = matchString or match_string\n        super().__init__(match_string, identChars, caseless=True)\n\n\nclass CloseMatch(Token):\n    \"\"\"A variation on :class:`Literal` which matches \"close\" matches,\n    that is, strings with at most 'n' mismatching characters.\n    :class:`CloseMatch` takes parameters:\n\n    - ``match_string`` - string to be matched\n    - ``caseless`` - a boolean indicating whether to ignore casing when comparing characters\n    - ``max_mismatches`` - (``default=1``) maximum number of\n      mismatches allowed to count as a match\n\n    The results from a successful parse will contain the matched text\n    from the input string and the following named results:\n\n    - ``mismatches`` - a list of the positions within the\n      match_string where mismatches were found\n    - ``original`` - the original match_string used to compare\n      against the input string\n\n    If ``mismatches`` is an empty list, then the match was an exact\n    match.\n\n    Example::\n\n        patt = CloseMatch(\"ATCATCGAATGGA\")\n        patt.parse_string(\"ATCATCGAAXGGA\") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']})\n        patt.parse_string(\"ATCAXCGAAXGGA\") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1)\n\n        # exact match\n        patt.parse_string(\"ATCATCGAATGGA\") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']})\n\n        # close match allowing up to 2 mismatches\n        patt = CloseMatch(\"ATCATCGAATGGA\", max_mismatches=2)\n        patt.parse_string(\"ATCAXCGAAXGGA\") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']})\n    \"\"\"\n\n    def __init__(\n        self,\n        match_string: str,\n        max_mismatches: int = None,\n        *,\n        maxMismatches: int = 1,\n        caseless=False,\n    ):\n        maxMismatches = max_mismatches if max_mismatches is not None else maxMismatches\n        super().__init__()\n        self.match_string = match_string\n        self.maxMismatches = maxMismatches\n        self.errmsg = \"Expected {!r} (with up to {} mismatches)\".format(\n            self.match_string, self.maxMismatches\n        )\n        self.caseless = caseless\n        self.mayIndexError = False\n        self.mayReturnEmpty = False\n\n    def _generateDefaultName(self):\n        return \"{}:{!r}\".format(type(self).__name__, self.match_string)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        start = loc\n        instrlen = len(instring)\n        maxloc = start + len(self.match_string)\n\n        if maxloc <= instrlen:\n            match_string = self.match_string\n            match_stringloc = 0\n            mismatches = []\n            maxMismatches = self.maxMismatches\n\n            for match_stringloc, s_m in enumerate(\n                zip(instring[loc:maxloc], match_string)\n            ):\n                src, mat = s_m\n                if self.caseless:\n                    src, mat = src.lower(), mat.lower()\n\n                if src != mat:\n                    mismatches.append(match_stringloc)\n                    if len(mismatches) > maxMismatches:\n                        break\n            else:\n                loc = start + match_stringloc + 1\n                results = ParseResults([instring[start:loc]])\n                results[\"original\"] = match_string\n                results[\"mismatches\"] = mismatches\n                return loc, results\n\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass Word(Token):\n    \"\"\"Token for matching words composed of allowed character sets.\n    Parameters:\n    - ``init_chars`` - string of all characters that should be used to\n      match as a word; \"ABC\" will match \"AAA\", \"ABAB\", \"CBAC\", etc.;\n      if ``body_chars`` is also specified, then this is the string of\n      initial characters\n    - ``body_chars`` - string of characters that\n      can be used for matching after a matched initial character as\n      given in ``init_chars``; if omitted, same as the initial characters\n      (default=``None``)\n    - ``min`` - minimum number of characters to match (default=1)\n    - ``max`` - maximum number of characters to match (default=0)\n    - ``exact`` - exact number of characters to match (default=0)\n    - ``as_keyword`` - match as a keyword (default=``False``)\n    - ``exclude_chars`` - characters that might be\n      found in the input ``body_chars`` string but which should not be\n      accepted for matching ;useful to define a word of all\n      printables except for one or two characters, for instance\n      (default=``None``)\n\n    :class:`srange` is useful for defining custom character set strings\n    for defining :class:`Word` expressions, using range notation from\n    regular expression character sets.\n\n    A common mistake is to use :class:`Word` to match a specific literal\n    string, as in ``Word(\"Address\")``. Remember that :class:`Word`\n    uses the string argument to define *sets* of matchable characters.\n    This expression would match \"Add\", \"AAA\", \"dAred\", or any other word\n    made up of the characters 'A', 'd', 'r', 'e', and 's'. To match an\n    exact literal string, use :class:`Literal` or :class:`Keyword`.\n\n    pyparsing includes helper strings for building Words:\n\n    - :class:`alphas`\n    - :class:`nums`\n    - :class:`alphanums`\n    - :class:`hexnums`\n    - :class:`alphas8bit` (alphabetic characters in ASCII range 128-255\n      - accented, tilded, umlauted, etc.)\n    - :class:`punc8bit` (non-alphabetic characters in ASCII range\n      128-255 - currency, symbols, superscripts, diacriticals, etc.)\n    - :class:`printables` (any non-whitespace character)\n\n    ``alphas``, ``nums``, and ``printables`` are also defined in several\n    Unicode sets - see :class:`pyparsing_unicode``.\n\n    Example::\n\n        # a word composed of digits\n        integer = Word(nums) # equivalent to Word(\"0123456789\") or Word(srange(\"0-9\"))\n\n        # a word with a leading capital, and zero or more lowercase\n        capital_word = Word(alphas.upper(), alphas.lower())\n\n        # hostnames are alphanumeric, with leading alpha, and '-'\n        hostname = Word(alphas, alphanums + '-')\n\n        # roman numeral (not a strict parser, accepts invalid mix of characters)\n        roman = Word(\"IVXLCDM\")\n\n        # any string of non-whitespace characters, except for ','\n        csv_value = Word(printables, exclude_chars=\",\")\n    \"\"\"\n\n    def __init__(\n        self,\n        init_chars: str = \"\",\n        body_chars: typing.Optional[str] = None,\n        min: int = 1,\n        max: int = 0,\n        exact: int = 0,\n        as_keyword: bool = False,\n        exclude_chars: typing.Optional[str] = None,\n        *,\n        initChars: typing.Optional[str] = None,\n        bodyChars: typing.Optional[str] = None,\n        asKeyword: bool = False,\n        excludeChars: typing.Optional[str] = None,\n    ):\n        initChars = initChars or init_chars\n        bodyChars = bodyChars or body_chars\n        asKeyword = asKeyword or as_keyword\n        excludeChars = excludeChars or exclude_chars\n        super().__init__()\n        if not initChars:\n            raise ValueError(\n                \"invalid {}, initChars cannot be empty string\".format(\n                    type(self).__name__\n                )\n            )\n\n        initChars = set(initChars)\n        self.initChars = initChars\n        if excludeChars:\n            excludeChars = set(excludeChars)\n            initChars -= excludeChars\n            if bodyChars:\n                bodyChars = set(bodyChars) - excludeChars\n        self.initCharsOrig = \"\".join(sorted(initChars))\n\n        if bodyChars:\n            self.bodyCharsOrig = \"\".join(sorted(bodyChars))\n            self.bodyChars = set(bodyChars)\n        else:\n            self.bodyCharsOrig = \"\".join(sorted(initChars))\n            self.bodyChars = set(initChars)\n\n        self.maxSpecified = max > 0\n\n        if min < 1:\n            raise ValueError(\n                \"cannot specify a minimum length < 1; use Opt(Word()) if zero-length word is permitted\"\n            )\n\n        self.minLen = min\n\n        if max > 0:\n            self.maxLen = max\n        else:\n            self.maxLen = _MAX_INT\n\n        if exact > 0:\n            self.maxLen = exact\n            self.minLen = exact\n\n        self.errmsg = \"Expected \" + self.name\n        self.mayIndexError = False\n        self.asKeyword = asKeyword\n\n        # see if we can make a regex for this Word\n        if \" \" not in self.initChars | self.bodyChars and (min == 1 and exact == 0):\n            if self.bodyChars == self.initChars:\n                if max == 0:\n                    repeat = \"+\"\n                elif max == 1:\n                    repeat = \"\"\n                else:\n                    repeat = \"{{{},{}}}\".format(\n                        self.minLen, \"\" if self.maxLen == _MAX_INT else self.maxLen\n                    )\n                self.reString = \"[{}]{}\".format(\n                    _collapse_string_to_ranges(self.initChars),\n                    repeat,\n                )\n            elif len(self.initChars) == 1:\n                if max == 0:\n                    repeat = \"*\"\n                else:\n                    repeat = \"{{0,{}}}\".format(max - 1)\n                self.reString = \"{}[{}]{}\".format(\n                    re.escape(self.initCharsOrig),\n                    _collapse_string_to_ranges(self.bodyChars),\n                    repeat,\n                )\n            else:\n                if max == 0:\n                    repeat = \"*\"\n                elif max == 2:\n                    repeat = \"\"\n                else:\n                    repeat = \"{{0,{}}}\".format(max - 1)\n                self.reString = \"[{}][{}]{}\".format(\n                    _collapse_string_to_ranges(self.initChars),\n                    _collapse_string_to_ranges(self.bodyChars),\n                    repeat,\n                )\n            if self.asKeyword:\n                self.reString = r\"\\b\" + self.reString + r\"\\b\"\n\n            try:\n                self.re = re.compile(self.reString)\n            except re.error:\n                self.re = None\n            else:\n                self.re_match = self.re.match\n                self.__class__ = _WordRegex\n\n    def _generateDefaultName(self):\n        def charsAsStr(s):\n            max_repr_len = 16\n            s = _collapse_string_to_ranges(s, re_escape=False)\n            if len(s) > max_repr_len:\n                return s[: max_repr_len - 3] + \"...\"\n            else:\n                return s\n\n        if self.initChars != self.bodyChars:\n            base = \"W:({}, {})\".format(\n                charsAsStr(self.initChars), charsAsStr(self.bodyChars)\n            )\n        else:\n            base = \"W:({})\".format(charsAsStr(self.initChars))\n\n        # add length specification\n        if self.minLen > 1 or self.maxLen != _MAX_INT:\n            if self.minLen == self.maxLen:\n                if self.minLen == 1:\n                    return base[2:]\n                else:\n                    return base + \"{{{}}}\".format(self.minLen)\n            elif self.maxLen == _MAX_INT:\n                return base + \"{{{},...}}\".format(self.minLen)\n            else:\n                return base + \"{{{},{}}}\".format(self.minLen, self.maxLen)\n        return base\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc] not in self.initChars:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        start = loc\n        loc += 1\n        instrlen = len(instring)\n        bodychars = self.bodyChars\n        maxloc = start + self.maxLen\n        maxloc = min(maxloc, instrlen)\n        while loc < maxloc and instring[loc] in bodychars:\n            loc += 1\n\n        throwException = False\n        if loc - start < self.minLen:\n            throwException = True\n        elif self.maxSpecified and loc < instrlen and instring[loc] in bodychars:\n            throwException = True\n        elif self.asKeyword:\n            if (\n                start > 0\n                and instring[start - 1] in bodychars\n                or loc < instrlen\n                and instring[loc] in bodychars\n            ):\n                throwException = True\n\n        if throwException:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        return loc, instring[start:loc]\n\n\nclass _WordRegex(Word):\n    def parseImpl(self, instring, loc, doActions=True):\n        result = self.re_match(instring, loc)\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        return loc, result.group()\n\n\nclass Char(_WordRegex):\n    \"\"\"A short-cut class for defining :class:`Word` ``(characters, exact=1)``,\n    when defining a match of any single character in a string of\n    characters.\n    \"\"\"\n\n    def __init__(\n        self,\n        charset: str,\n        as_keyword: bool = False,\n        exclude_chars: typing.Optional[str] = None,\n        *,\n        asKeyword: bool = False,\n        excludeChars: typing.Optional[str] = None,\n    ):\n        asKeyword = asKeyword or as_keyword\n        excludeChars = excludeChars or exclude_chars\n        super().__init__(\n            charset, exact=1, asKeyword=asKeyword, excludeChars=excludeChars\n        )\n        self.reString = \"[{}]\".format(_collapse_string_to_ranges(self.initChars))\n        if asKeyword:\n            self.reString = r\"\\b{}\\b\".format(self.reString)\n        self.re = re.compile(self.reString)\n        self.re_match = self.re.match\n\n\nclass Regex(Token):\n    r\"\"\"Token for matching strings that match a given regular\n    expression. Defined with string specifying the regular expression in\n    a form recognized by the stdlib Python  `re module <https://docs.python.org/3/library/re.html>`_.\n    If the given regex contains named groups (defined using ``(?P<name>...)``),\n    these will be preserved as named :class:`ParseResults`.\n\n    If instead of the Python stdlib ``re`` module you wish to use a different RE module\n    (such as the ``regex`` module), you can do so by building your ``Regex`` object with\n    a compiled RE that was compiled using ``regex``.\n\n    Example::\n\n        realnum = Regex(r\"[+-]?\\d+\\.\\d*\")\n        # ref: https://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression\n        roman = Regex(r\"M{0,4}(CM|CD|D?{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\")\n\n        # named fields in a regex will be returned as named results\n        date = Regex(r'(?P<year>\\d{4})-(?P<month>\\d\\d?)-(?P<day>\\d\\d?)')\n\n        # the Regex class will accept re's compiled using the regex module\n        import regex\n        parser = pp.Regex(regex.compile(r'[0-9]'))\n    \"\"\"\n\n    def __init__(\n        self,\n        pattern: Any,\n        flags: Union[re.RegexFlag, int] = 0,\n        as_group_list: bool = False,\n        as_match: bool = False,\n        *,\n        asGroupList: bool = False,\n        asMatch: bool = False,\n    ):\n        \"\"\"The parameters ``pattern`` and ``flags`` are passed\n        to the ``re.compile()`` function as-is. See the Python\n        `re module <https://docs.python.org/3/library/re.html>`_ module for an\n        explanation of the acceptable patterns and flags.\n        \"\"\"\n        super().__init__()\n        asGroupList = asGroupList or as_group_list\n        asMatch = asMatch or as_match\n\n        if isinstance(pattern, str_type):\n            if not pattern:\n                raise ValueError(\"null string passed to Regex; use Empty() instead\")\n\n            self._re = None\n            self.reString = self.pattern = pattern\n            self.flags = flags\n\n        elif hasattr(pattern, \"pattern\") and hasattr(pattern, \"match\"):\n            self._re = pattern\n            self.pattern = self.reString = pattern.pattern\n            self.flags = flags\n\n        else:\n            raise TypeError(\n                \"Regex may only be constructed with a string or a compiled RE object\"\n            )\n\n        self.errmsg = \"Expected \" + self.name\n        self.mayIndexError = False\n        self.asGroupList = asGroupList\n        self.asMatch = asMatch\n        if self.asGroupList:\n            self.parseImpl = self.parseImplAsGroupList\n        if self.asMatch:\n            self.parseImpl = self.parseImplAsMatch\n\n    @cached_property\n    def re(self):\n        if self._re:\n            return self._re\n        else:\n            try:\n                return re.compile(self.pattern, self.flags)\n            except re.error:\n                raise ValueError(\n                    \"invalid pattern ({!r}) passed to Regex\".format(self.pattern)\n                )\n\n    @cached_property\n    def re_match(self):\n        return self.re.match\n\n    @cached_property\n    def mayReturnEmpty(self):\n        return self.re_match(\"\") is not None\n\n    def _generateDefaultName(self):\n        return \"Re:({})\".format(repr(self.pattern).replace(\"\\\\\\\\\", \"\\\\\"))\n\n    def parseImpl(self, instring, loc, doActions=True):\n        result = self.re_match(instring, loc)\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        ret = ParseResults(result.group())\n        d = result.groupdict()\n        if d:\n            for k, v in d.items():\n                ret[k] = v\n        return loc, ret\n\n    def parseImplAsGroupList(self, instring, loc, doActions=True):\n        result = self.re_match(instring, loc)\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        ret = result.groups()\n        return loc, ret\n\n    def parseImplAsMatch(self, instring, loc, doActions=True):\n        result = self.re_match(instring, loc)\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        ret = result\n        return loc, ret\n\n    def sub(self, repl: str) -> ParserElement:\n        r\"\"\"\n        Return :class:`Regex` with an attached parse action to transform the parsed\n        result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_.\n\n        Example::\n\n            make_html = Regex(r\"(\\w+):(.*?):\").sub(r\"<\\1>\\2</\\1>\")\n            print(make_html.transform_string(\"h1:main title:\"))\n            # prints \"<h1>main title</h1>\"\n        \"\"\"\n        if self.asGroupList:\n            raise TypeError(\"cannot use sub() with Regex(asGroupList=True)\")\n\n        if self.asMatch and callable(repl):\n            raise TypeError(\"cannot use sub() with a callable with Regex(asMatch=True)\")\n\n        if self.asMatch:\n\n            def pa(tokens):\n                return tokens[0].expand(repl)\n\n        else:\n\n            def pa(tokens):\n                return self.re.sub(repl, tokens[0])\n\n        return self.add_parse_action(pa)\n\n\nclass QuotedString(Token):\n    r\"\"\"\n    Token for matching strings that are delimited by quoting characters.\n\n    Defined with the following parameters:\n\n    - ``quote_char`` - string of one or more characters defining the\n      quote delimiting string\n    - ``esc_char`` - character to re_escape quotes, typically backslash\n      (default= ``None``)\n    - ``esc_quote`` - special quote sequence to re_escape an embedded quote\n      string (such as SQL's ``\"\"`` to re_escape an embedded ``\"``)\n      (default= ``None``)\n    - ``multiline`` - boolean indicating whether quotes can span\n      multiple lines (default= ``False``)\n    - ``unquote_results`` - boolean indicating whether the matched text\n      should be unquoted (default= ``True``)\n    - ``end_quote_char`` - string of one or more characters defining the\n      end of the quote delimited string (default= ``None``  => same as\n      quote_char)\n    - ``convert_whitespace_escapes`` - convert escaped whitespace\n      (``'\\t'``, ``'\\n'``, etc.) to actual whitespace\n      (default= ``True``)\n\n    Example::\n\n        qs = QuotedString('\"')\n        print(qs.search_string('lsjdf \"This is the quote\" sldjf'))\n        complex_qs = QuotedString('{{', end_quote_char='}}')\n        print(complex_qs.search_string('lsjdf {{This is the \"quote\"}} sldjf'))\n        sql_qs = QuotedString('\"', esc_quote='\"\"')\n        print(sql_qs.search_string('lsjdf \"This is the quote with \"\"embedded\"\" quotes\" sldjf'))\n\n    prints::\n\n        [['This is the quote']]\n        [['This is the \"quote\"']]\n        [['This is the quote with \"embedded\" quotes']]\n    \"\"\"\n    ws_map = ((r\"\\t\", \"\\t\"), (r\"\\n\", \"\\n\"), (r\"\\f\", \"\\f\"), (r\"\\r\", \"\\r\"))\n\n    def __init__(\n        self,\n        quote_char: str = \"\",\n        esc_char: typing.Optional[str] = None,\n        esc_quote: typing.Optional[str] = None,\n        multiline: bool = False,\n        unquote_results: bool = True,\n        end_quote_char: typing.Optional[str] = None,\n        convert_whitespace_escapes: bool = True,\n        *,\n        quoteChar: str = \"\",\n        escChar: typing.Optional[str] = None,\n        escQuote: typing.Optional[str] = None,\n        unquoteResults: bool = True,\n        endQuoteChar: typing.Optional[str] = None,\n        convertWhitespaceEscapes: bool = True,\n    ):\n        super().__init__()\n        escChar = escChar or esc_char\n        escQuote = escQuote or esc_quote\n        unquoteResults = unquoteResults and unquote_results\n        endQuoteChar = endQuoteChar or end_quote_char\n        convertWhitespaceEscapes = (\n            convertWhitespaceEscapes and convert_whitespace_escapes\n        )\n        quote_char = quoteChar or quote_char\n\n        # remove white space from quote chars - wont work anyway\n        quote_char = quote_char.strip()\n        if not quote_char:\n            raise ValueError(\"quote_char cannot be the empty string\")\n\n        if endQuoteChar is None:\n            endQuoteChar = quote_char\n        else:\n            endQuoteChar = endQuoteChar.strip()\n            if not endQuoteChar:\n                raise ValueError(\"endQuoteChar cannot be the empty string\")\n\n        self.quoteChar = quote_char\n        self.quoteCharLen = len(quote_char)\n        self.firstQuoteChar = quote_char[0]\n        self.endQuoteChar = endQuoteChar\n        self.endQuoteCharLen = len(endQuoteChar)\n        self.escChar = escChar\n        self.escQuote = escQuote\n        self.unquoteResults = unquoteResults\n        self.convertWhitespaceEscapes = convertWhitespaceEscapes\n\n        sep = \"\"\n        inner_pattern = \"\"\n\n        if escQuote:\n            inner_pattern += r\"{}(?:{})\".format(sep, re.escape(escQuote))\n            sep = \"|\"\n\n        if escChar:\n            inner_pattern += r\"{}(?:{}.)\".format(sep, re.escape(escChar))\n            sep = \"|\"\n            self.escCharReplacePattern = re.escape(self.escChar) + \"(.)\"\n\n        if len(self.endQuoteChar) > 1:\n            inner_pattern += (\n                \"{}(?:\".format(sep)\n                + \"|\".join(\n                    \"(?:{}(?!{}))\".format(\n                        re.escape(self.endQuoteChar[:i]),\n                        re.escape(self.endQuoteChar[i:]),\n                    )\n                    for i in range(len(self.endQuoteChar) - 1, 0, -1)\n                )\n                + \")\"\n            )\n            sep = \"|\"\n\n        if multiline:\n            self.flags = re.MULTILINE | re.DOTALL\n            inner_pattern += r\"{}(?:[^{}{}])\".format(\n                sep,\n                _escape_regex_range_chars(self.endQuoteChar[0]),\n                (_escape_regex_range_chars(escChar) if escChar is not None else \"\"),\n            )\n        else:\n            self.flags = 0\n            inner_pattern += r\"{}(?:[^{}\\n\\r{}])\".format(\n                sep,\n                _escape_regex_range_chars(self.endQuoteChar[0]),\n                (_escape_regex_range_chars(escChar) if escChar is not None else \"\"),\n            )\n\n        self.pattern = \"\".join(\n            [\n                re.escape(self.quoteChar),\n                \"(?:\",\n                inner_pattern,\n                \")*\",\n                re.escape(self.endQuoteChar),\n            ]\n        )\n\n        try:\n            self.re = re.compile(self.pattern, self.flags)\n            self.reString = self.pattern\n            self.re_match = self.re.match\n        except re.error:\n            raise ValueError(\n                \"invalid pattern {!r} passed to Regex\".format(self.pattern)\n            )\n\n        self.errmsg = \"Expected \" + self.name\n        self.mayIndexError = False\n        self.mayReturnEmpty = True\n\n    def _generateDefaultName(self):\n        if self.quoteChar == self.endQuoteChar and isinstance(self.quoteChar, str_type):\n            return \"string enclosed in {!r}\".format(self.quoteChar)\n\n        return \"quoted string, starting with {} ending with {}\".format(\n            self.quoteChar, self.endQuoteChar\n        )\n\n    def parseImpl(self, instring, loc, doActions=True):\n        result = (\n            instring[loc] == self.firstQuoteChar\n            and self.re_match(instring, loc)\n            or None\n        )\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        ret = result.group()\n\n        if self.unquoteResults:\n\n            # strip off quotes\n            ret = ret[self.quoteCharLen : -self.endQuoteCharLen]\n\n            if isinstance(ret, str_type):\n                # replace escaped whitespace\n                if \"\\\\\" in ret and self.convertWhitespaceEscapes:\n                    for wslit, wschar in self.ws_map:\n                        ret = ret.replace(wslit, wschar)\n\n                # replace escaped characters\n                if self.escChar:\n                    ret = re.sub(self.escCharReplacePattern, r\"\\g<1>\", ret)\n\n                # replace escaped quotes\n                if self.escQuote:\n                    ret = ret.replace(self.escQuote, self.endQuoteChar)\n\n        return loc, ret\n\n\nclass CharsNotIn(Token):\n    \"\"\"Token for matching words composed of characters *not* in a given\n    set (will include whitespace in matched characters if not listed in\n    the provided exclusion set - see example). Defined with string\n    containing all disallowed characters, and an optional minimum,\n    maximum, and/or exact length.  The default value for ``min`` is\n    1 (a minimum value < 1 is not valid); the default values for\n    ``max`` and ``exact`` are 0, meaning no maximum or exact\n    length restriction.\n\n    Example::\n\n        # define a comma-separated-value as anything that is not a ','\n        csv_value = CharsNotIn(',')\n        print(delimited_list(csv_value).parse_string(\"dkls,lsdkjf,s12 34,@!#,213\"))\n\n    prints::\n\n        ['dkls', 'lsdkjf', 's12 34', '@!#', '213']\n    \"\"\"\n\n    def __init__(\n        self,\n        not_chars: str = \"\",\n        min: int = 1,\n        max: int = 0,\n        exact: int = 0,\n        *,\n        notChars: str = \"\",\n    ):\n        super().__init__()\n        self.skipWhitespace = False\n        self.notChars = not_chars or notChars\n        self.notCharsSet = set(self.notChars)\n\n        if min < 1:\n            raise ValueError(\n                \"cannot specify a minimum length < 1; use \"\n                \"Opt(CharsNotIn()) if zero-length char group is permitted\"\n            )\n\n        self.minLen = min\n\n        if max > 0:\n            self.maxLen = max\n        else:\n            self.maxLen = _MAX_INT\n\n        if exact > 0:\n            self.maxLen = exact\n            self.minLen = exact\n\n        self.errmsg = \"Expected \" + self.name\n        self.mayReturnEmpty = self.minLen == 0\n        self.mayIndexError = False\n\n    def _generateDefaultName(self):\n        not_chars_str = _collapse_string_to_ranges(self.notChars)\n        if len(not_chars_str) > 16:\n            return \"!W:({}...)\".format(self.notChars[: 16 - 3])\n        else:\n            return \"!W:({})\".format(self.notChars)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        notchars = self.notCharsSet\n        if instring[loc] in notchars:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        start = loc\n        loc += 1\n        maxlen = min(start + self.maxLen, len(instring))\n        while loc < maxlen and instring[loc] not in notchars:\n            loc += 1\n\n        if loc - start < self.minLen:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        return loc, instring[start:loc]\n\n\nclass White(Token):\n    \"\"\"Special matching class for matching whitespace.  Normally,\n    whitespace is ignored by pyparsing grammars.  This class is included\n    when some whitespace structures are significant.  Define with\n    a string containing the whitespace characters to be matched; default\n    is ``\" \\\\t\\\\r\\\\n\"``.  Also takes optional ``min``,\n    ``max``, and ``exact`` arguments, as defined for the\n    :class:`Word` class.\n    \"\"\"\n\n    whiteStrs = {\n        \" \": \"<SP>\",\n        \"\\t\": \"<TAB>\",\n        \"\\n\": \"<LF>\",\n        \"\\r\": \"<CR>\",\n        \"\\f\": \"<FF>\",\n        \"\\u00A0\": \"<NBSP>\",\n        \"\\u1680\": \"<OGHAM_SPACE_MARK>\",\n        \"\\u180E\": \"<MONGOLIAN_VOWEL_SEPARATOR>\",\n        \"\\u2000\": \"<EN_QUAD>\",\n        \"\\u2001\": \"<EM_QUAD>\",\n        \"\\u2002\": \"<EN_SPACE>\",\n        \"\\u2003\": \"<EM_SPACE>\",\n        \"\\u2004\": \"<THREE-PER-EM_SPACE>\",\n        \"\\u2005\": \"<FOUR-PER-EM_SPACE>\",\n        \"\\u2006\": \"<SIX-PER-EM_SPACE>\",\n        \"\\u2007\": \"<FIGURE_SPACE>\",\n        \"\\u2008\": \"<PUNCTUATION_SPACE>\",\n        \"\\u2009\": \"<THIN_SPACE>\",\n        \"\\u200A\": \"<HAIR_SPACE>\",\n        \"\\u200B\": \"<ZERO_WIDTH_SPACE>\",\n        \"\\u202F\": \"<NNBSP>\",\n        \"\\u205F\": \"<MMSP>\",\n        \"\\u3000\": \"<IDEOGRAPHIC_SPACE>\",\n    }\n\n    def __init__(self, ws: str = \" \\t\\r\\n\", min: int = 1, max: int = 0, exact: int = 0):\n        super().__init__()\n        self.matchWhite = ws\n        self.set_whitespace_chars(\n            \"\".join(c for c in self.whiteStrs if c not in self.matchWhite),\n            copy_defaults=True,\n        )\n        # self.leave_whitespace()\n        self.mayReturnEmpty = True\n        self.errmsg = \"Expected \" + self.name\n\n        self.minLen = min\n\n        if max > 0:\n            self.maxLen = max\n        else:\n            self.maxLen = _MAX_INT\n\n        if exact > 0:\n            self.maxLen = exact\n            self.minLen = exact\n\n    def _generateDefaultName(self):\n        return \"\".join(White.whiteStrs[c] for c in self.matchWhite)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc] not in self.matchWhite:\n            raise ParseException(instring, loc, self.errmsg, self)\n        start = loc\n        loc += 1\n        maxloc = start + self.maxLen\n        maxloc = min(maxloc, len(instring))\n        while loc < maxloc and instring[loc] in self.matchWhite:\n            loc += 1\n\n        if loc - start < self.minLen:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        return loc, instring[start:loc]\n\n\nclass PositionToken(Token):\n    def __init__(self):\n        super().__init__()\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n\n\nclass GoToColumn(PositionToken):\n    \"\"\"Token to advance to a specific column of input text; useful for\n    tabular report scraping.\n    \"\"\"\n\n    def __init__(self, colno: int):\n        super().__init__()\n        self.col = colno\n\n    def preParse(self, instring, loc):\n        if col(loc, instring) != self.col:\n            instrlen = len(instring)\n            if self.ignoreExprs:\n                loc = self._skipIgnorables(instring, loc)\n            while (\n                loc < instrlen\n                and instring[loc].isspace()\n                and col(loc, instring) != self.col\n            ):\n                loc += 1\n        return loc\n\n    def parseImpl(self, instring, loc, doActions=True):\n        thiscol = col(loc, instring)\n        if thiscol > self.col:\n            raise ParseException(instring, loc, \"Text not in expected column\", self)\n        newloc = loc + self.col - thiscol\n        ret = instring[loc:newloc]\n        return newloc, ret\n\n\nclass LineStart(PositionToken):\n    r\"\"\"Matches if current position is at the beginning of a line within\n    the parse string\n\n    Example::\n\n        test = '''\\\n        AAA this line\n        AAA and this line\n          AAA but not this one\n        B AAA and definitely not this one\n        '''\n\n        for t in (LineStart() + 'AAA' + restOfLine).search_string(test):\n            print(t)\n\n    prints::\n\n        ['AAA', ' this line']\n        ['AAA', ' and this line']\n\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.leave_whitespace()\n        self.orig_whiteChars = set() | self.whiteChars\n        self.whiteChars.discard(\"\\n\")\n        self.skipper = Empty().set_whitespace_chars(self.whiteChars)\n        self.errmsg = \"Expected start of line\"\n\n    def preParse(self, instring, loc):\n        if loc == 0:\n            return loc\n        else:\n            ret = self.skipper.preParse(instring, loc)\n            if \"\\n\" in self.orig_whiteChars:\n                while instring[ret : ret + 1] == \"\\n\":\n                    ret = self.skipper.preParse(instring, ret + 1)\n            return ret\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if col(loc, instring) == 1:\n            return loc, []\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass LineEnd(PositionToken):\n    \"\"\"Matches if current position is at the end of a line within the\n    parse string\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.whiteChars.discard(\"\\n\")\n        self.set_whitespace_chars(self.whiteChars, copy_defaults=False)\n        self.errmsg = \"Expected end of line\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc < len(instring):\n            if instring[loc] == \"\\n\":\n                return loc + 1, \"\\n\"\n            else:\n                raise ParseException(instring, loc, self.errmsg, self)\n        elif loc == len(instring):\n            return loc + 1, []\n        else:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass StringStart(PositionToken):\n    \"\"\"Matches if current position is at the beginning of the parse\n    string\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.errmsg = \"Expected start of text\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc != 0:\n            # see if entire string up to here is just whitespace and ignoreables\n            if loc != self.preParse(instring, 0):\n                raise ParseException(instring, loc, self.errmsg, self)\n        return loc, []\n\n\nclass StringEnd(PositionToken):\n    \"\"\"\n    Matches if current position is at the end of the parse string\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.errmsg = \"Expected end of text\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc < len(instring):\n            raise ParseException(instring, loc, self.errmsg, self)\n        elif loc == len(instring):\n            return loc + 1, []\n        elif loc > len(instring):\n            return loc, []\n        else:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass WordStart(PositionToken):\n    \"\"\"Matches if the current position is at the beginning of a\n    :class:`Word`, and is not preceded by any character in a given\n    set of ``word_chars`` (default= ``printables``). To emulate the\n    ``\\b`` behavior of regular expressions, use\n    ``WordStart(alphanums)``. ``WordStart`` will also match at\n    the beginning of the string being parsed, or at the beginning of\n    a line.\n    \"\"\"\n\n    def __init__(self, word_chars: str = printables, *, wordChars: str = printables):\n        wordChars = word_chars if wordChars == printables else wordChars\n        super().__init__()\n        self.wordChars = set(wordChars)\n        self.errmsg = \"Not at the start of a word\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc != 0:\n            if (\n                instring[loc - 1] in self.wordChars\n                or instring[loc] not in self.wordChars\n            ):\n                raise ParseException(instring, loc, self.errmsg, self)\n        return loc, []\n\n\nclass WordEnd(PositionToken):\n    \"\"\"Matches if the current position is at the end of a :class:`Word`,\n    and is not followed by any character in a given set of ``word_chars``\n    (default= ``printables``). To emulate the ``\\b`` behavior of\n    regular expressions, use ``WordEnd(alphanums)``. ``WordEnd``\n    will also match at the end of the string being parsed, or at the end\n    of a line.\n    \"\"\"\n\n    def __init__(self, word_chars: str = printables, *, wordChars: str = printables):\n        wordChars = word_chars if wordChars == printables else wordChars\n        super().__init__()\n        self.wordChars = set(wordChars)\n        self.skipWhitespace = False\n        self.errmsg = \"Not at the end of a word\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        instrlen = len(instring)\n        if instrlen > 0 and loc < instrlen:\n            if (\n                instring[loc] in self.wordChars\n                or instring[loc - 1] not in self.wordChars\n            ):\n                raise ParseException(instring, loc, self.errmsg, self)\n        return loc, []\n\n\nclass ParseExpression(ParserElement):\n    \"\"\"Abstract subclass of ParserElement, for combining and\n    post-processing parsed tokens.\n    \"\"\"\n\n    def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False):\n        super().__init__(savelist)\n        self.exprs: List[ParserElement]\n        if isinstance(exprs, _generatorType):\n            exprs = list(exprs)\n\n        if isinstance(exprs, str_type):\n            self.exprs = [self._literalStringClass(exprs)]\n        elif isinstance(exprs, ParserElement):\n            self.exprs = [exprs]\n        elif isinstance(exprs, Iterable):\n            exprs = list(exprs)\n            # if sequence of strings provided, wrap with Literal\n            if any(isinstance(expr, str_type) for expr in exprs):\n                exprs = (\n                    self._literalStringClass(e) if isinstance(e, str_type) else e\n                    for e in exprs\n                )\n            self.exprs = list(exprs)\n        else:\n            try:\n                self.exprs = list(exprs)\n            except TypeError:\n                self.exprs = [exprs]\n        self.callPreparse = False\n\n    def recurse(self) -> Sequence[ParserElement]:\n        return self.exprs[:]\n\n    def append(self, other) -> ParserElement:\n        self.exprs.append(other)\n        self._defaultName = None\n        return self\n\n    def leave_whitespace(self, recursive: bool = True) -> ParserElement:\n        \"\"\"\n        Extends ``leave_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on\n           all contained expressions.\n        \"\"\"\n        super().leave_whitespace(recursive)\n\n        if recursive:\n            self.exprs = [e.copy() for e in self.exprs]\n            for e in self.exprs:\n                e.leave_whitespace(recursive)\n        return self\n\n    def ignore_whitespace(self, recursive: bool = True) -> ParserElement:\n        \"\"\"\n        Extends ``ignore_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on\n           all contained expressions.\n        \"\"\"\n        super().ignore_whitespace(recursive)\n        if recursive:\n            self.exprs = [e.copy() for e in self.exprs]\n            for e in self.exprs:\n                e.ignore_whitespace(recursive)\n        return self\n\n    def ignore(self, other) -> ParserElement:\n        if isinstance(other, Suppress):\n            if other not in self.ignoreExprs:\n                super().ignore(other)\n                for e in self.exprs:\n                    e.ignore(self.ignoreExprs[-1])\n        else:\n            super().ignore(other)\n            for e in self.exprs:\n                e.ignore(self.ignoreExprs[-1])\n        return self\n\n    def _generateDefaultName(self):\n        return \"{}:({})\".format(self.__class__.__name__, str(self.exprs))\n\n    def streamline(self) -> ParserElement:\n        if self.streamlined:\n            return self\n\n        super().streamline()\n\n        for e in self.exprs:\n            e.streamline()\n\n        # collapse nested :class:`And`'s of the form ``And(And(And(a, b), c), d)`` to ``And(a, b, c, d)``\n        # but only if there are no parse actions or resultsNames on the nested And's\n        # (likewise for :class:`Or`'s and :class:`MatchFirst`'s)\n        if len(self.exprs) == 2:\n            other = self.exprs[0]\n            if (\n                isinstance(other, self.__class__)\n                and not other.parseAction\n                and other.resultsName is None\n                and not other.debug\n            ):\n                self.exprs = other.exprs[:] + [self.exprs[1]]\n                self._defaultName = None\n                self.mayReturnEmpty |= other.mayReturnEmpty\n                self.mayIndexError |= other.mayIndexError\n\n            other = self.exprs[-1]\n            if (\n                isinstance(other, self.__class__)\n                and not other.parseAction\n                and other.resultsName is None\n                and not other.debug\n            ):\n                self.exprs = self.exprs[:-1] + other.exprs[:]\n                self._defaultName = None\n                self.mayReturnEmpty |= other.mayReturnEmpty\n                self.mayIndexError |= other.mayIndexError\n\n        self.errmsg = \"Expected \" + str(self)\n\n        return self\n\n    def validate(self, validateTrace=None) -> None:\n        tmp = (validateTrace if validateTrace is not None else [])[:] + [self]\n        for e in self.exprs:\n            e.validate(tmp)\n        self._checkRecursion([])\n\n    def copy(self) -> ParserElement:\n        ret = super().copy()\n        ret.exprs = [e.copy() for e in self.exprs]\n        return ret\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if (\n            __diag__.warn_ungrouped_named_tokens_in_collection\n            and Diagnostics.warn_ungrouped_named_tokens_in_collection\n            not in self.suppress_warnings_\n        ):\n            for e in self.exprs:\n                if (\n                    isinstance(e, ParserElement)\n                    and e.resultsName\n                    and Diagnostics.warn_ungrouped_named_tokens_in_collection\n                    not in e.suppress_warnings_\n                ):\n                    warnings.warn(\n                        \"{}: setting results name {!r} on {} expression \"\n                        \"collides with {!r} on contained expression\".format(\n                            \"warn_ungrouped_named_tokens_in_collection\",\n                            name,\n                            type(self).__name__,\n                            e.resultsName,\n                        ),\n                        stacklevel=3,\n                    )\n\n        return super()._setResultsName(name, listAllMatches)\n\n    ignoreWhitespace = ignore_whitespace\n    leaveWhitespace = leave_whitespace\n\n\nclass And(ParseExpression):\n    \"\"\"\n    Requires all given :class:`ParseExpression` s to be found in the given order.\n    Expressions may be separated by whitespace.\n    May be constructed using the ``'+'`` operator.\n    May also be constructed using the ``'-'`` operator, which will\n    suppress backtracking.\n\n    Example::\n\n        integer = Word(nums)\n        name_expr = Word(alphas)[1, ...]\n\n        expr = And([integer(\"id\"), name_expr(\"name\"), integer(\"age\")])\n        # more easily written as:\n        expr = integer(\"id\") + name_expr(\"name\") + integer(\"age\")\n    \"\"\"\n\n    class _ErrorStop(Empty):\n        def __init__(self, *args, **kwargs):\n            super().__init__(*args, **kwargs)\n            self.leave_whitespace()\n\n        def _generateDefaultName(self):\n            return \"-\"\n\n    def __init__(\n        self, exprs_arg: typing.Iterable[ParserElement], savelist: bool = True\n    ):\n        exprs: List[ParserElement] = list(exprs_arg)\n        if exprs and Ellipsis in exprs:\n            tmp = []\n            for i, expr in enumerate(exprs):\n                if expr is Ellipsis:\n                    if i < len(exprs) - 1:\n                        skipto_arg: ParserElement = (Empty() + exprs[i + 1]).exprs[-1]\n                        tmp.append(SkipTo(skipto_arg)(\"_skipped*\"))\n                    else:\n                        raise Exception(\n                            \"cannot construct And with sequence ending in ...\"\n                        )\n                else:\n                    tmp.append(expr)\n            exprs[:] = tmp\n        super().__init__(exprs, savelist)\n        if self.exprs:\n            self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)\n            if not isinstance(self.exprs[0], White):\n                self.set_whitespace_chars(\n                    self.exprs[0].whiteChars,\n                    copy_defaults=self.exprs[0].copyDefaultWhiteChars,\n                )\n                self.skipWhitespace = self.exprs[0].skipWhitespace\n            else:\n                self.skipWhitespace = False\n        else:\n            self.mayReturnEmpty = True\n        self.callPreparse = True\n\n    def streamline(self) -> ParserElement:\n        # collapse any _PendingSkip's\n        if self.exprs:\n            if any(\n                isinstance(e, ParseExpression)\n                and e.exprs\n                and isinstance(e.exprs[-1], _PendingSkip)\n                for e in self.exprs[:-1]\n            ):\n                for i, e in enumerate(self.exprs[:-1]):\n                    if e is None:\n                        continue\n                    if (\n                        isinstance(e, ParseExpression)\n                        and e.exprs\n                        and isinstance(e.exprs[-1], _PendingSkip)\n                    ):\n                        e.exprs[-1] = e.exprs[-1] + self.exprs[i + 1]\n                        self.exprs[i + 1] = None\n                self.exprs = [e for e in self.exprs if e is not None]\n\n        super().streamline()\n\n        # link any IndentedBlocks to the prior expression\n        for prev, cur in zip(self.exprs, self.exprs[1:]):\n            # traverse cur or any first embedded expr of cur looking for an IndentedBlock\n            # (but watch out for recursive grammar)\n            seen = set()\n            while cur:\n                if id(cur) in seen:\n                    break\n                seen.add(id(cur))\n                if isinstance(cur, IndentedBlock):\n                    prev.add_parse_action(\n                        lambda s, l, t, cur_=cur: setattr(\n                            cur_, \"parent_anchor\", col(l, s)\n                        )\n                    )\n                    break\n                subs = cur.recurse()\n                cur = next(iter(subs), None)\n\n        self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        # pass False as callPreParse arg to _parse for first element, since we already\n        # pre-parsed the string as part of our And pre-parsing\n        loc, resultlist = self.exprs[0]._parse(\n            instring, loc, doActions, callPreParse=False\n        )\n        errorStop = False\n        for e in self.exprs[1:]:\n            # if isinstance(e, And._ErrorStop):\n            if type(e) is And._ErrorStop:\n                errorStop = True\n                continue\n            if errorStop:\n                try:\n                    loc, exprtokens = e._parse(instring, loc, doActions)\n                except ParseSyntaxException:\n                    raise\n                except ParseBaseException as pe:\n                    pe.__traceback__ = None\n                    raise ParseSyntaxException._from_exception(pe)\n                except IndexError:\n                    raise ParseSyntaxException(\n                        instring, len(instring), self.errmsg, self\n                    )\n            else:\n                loc, exprtokens = e._parse(instring, loc, doActions)\n            if exprtokens or exprtokens.haskeys():\n                resultlist += exprtokens\n        return loc, resultlist\n\n    def __iadd__(self, other):\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        return self.append(other)  # And([self, other])\n\n    def _checkRecursion(self, parseElementList):\n        subRecCheckList = parseElementList[:] + [self]\n        for e in self.exprs:\n            e._checkRecursion(subRecCheckList)\n            if not e.mayReturnEmpty:\n                break\n\n    def _generateDefaultName(self):\n        inner = \" \".join(str(e) for e in self.exprs)\n        # strip off redundant inner {}'s\n        while len(inner) > 1 and inner[0 :: len(inner) - 1] == \"{}\":\n            inner = inner[1:-1]\n        return \"{\" + inner + \"}\"\n\n\nclass Or(ParseExpression):\n    \"\"\"Requires that at least one :class:`ParseExpression` is found. If\n    two expressions match, the expression that matches the longest\n    string will be used. May be constructed using the ``'^'``\n    operator.\n\n    Example::\n\n        # construct Or using '^' operator\n\n        number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums))\n        print(number.search_string(\"123 3.1416 789\"))\n\n    prints::\n\n        [['123'], ['3.1416'], ['789']]\n    \"\"\"\n\n    def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False):\n        super().__init__(exprs, savelist)\n        if self.exprs:\n            self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)\n            self.skipWhitespace = all(e.skipWhitespace for e in self.exprs)\n        else:\n            self.mayReturnEmpty = True\n\n    def streamline(self) -> ParserElement:\n        super().streamline()\n        if self.exprs:\n            self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)\n            self.saveAsList = any(e.saveAsList for e in self.exprs)\n            self.skipWhitespace = all(\n                e.skipWhitespace and not isinstance(e, White) for e in self.exprs\n            )\n        else:\n            self.saveAsList = False\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        maxExcLoc = -1\n        maxException = None\n        matches = []\n        fatals = []\n        if all(e.callPreparse for e in self.exprs):\n            loc = self.preParse(instring, loc)\n        for e in self.exprs:\n            try:\n                loc2 = e.try_parse(instring, loc, raise_fatal=True)\n            except ParseFatalException as pfe:\n                pfe.__traceback__ = None\n                pfe.parserElement = e\n                fatals.append(pfe)\n                maxException = None\n                maxExcLoc = -1\n            except ParseException as err:\n                if not fatals:\n                    err.__traceback__ = None\n                    if err.loc > maxExcLoc:\n                        maxException = err\n                        maxExcLoc = err.loc\n            except IndexError:\n                if len(instring) > maxExcLoc:\n                    maxException = ParseException(\n                        instring, len(instring), e.errmsg, self\n                    )\n                    maxExcLoc = len(instring)\n            else:\n                # save match among all matches, to retry longest to shortest\n                matches.append((loc2, e))\n\n        if matches:\n            # re-evaluate all matches in descending order of length of match, in case attached actions\n            # might change whether or how much they match of the input.\n            matches.sort(key=itemgetter(0), reverse=True)\n\n            if not doActions:\n                # no further conditions or parse actions to change the selection of\n                # alternative, so the first match will be the best match\n                best_expr = matches[0][1]\n                return best_expr._parse(instring, loc, doActions)\n\n            longest = -1, None\n            for loc1, expr1 in matches:\n                if loc1 <= longest[0]:\n                    # already have a longer match than this one will deliver, we are done\n                    return longest\n\n                try:\n                    loc2, toks = expr1._parse(instring, loc, doActions)\n                except ParseException as err:\n                    err.__traceback__ = None\n                    if err.loc > maxExcLoc:\n                        maxException = err\n                        maxExcLoc = err.loc\n                else:\n                    if loc2 >= loc1:\n                        return loc2, toks\n                    # didn't match as much as before\n                    elif loc2 > longest[0]:\n                        longest = loc2, toks\n\n            if longest != (-1, None):\n                return longest\n\n        if fatals:\n            if len(fatals) > 1:\n                fatals.sort(key=lambda e: -e.loc)\n                if fatals[0].loc == fatals[1].loc:\n                    fatals.sort(key=lambda e: (-e.loc, -len(str(e.parserElement))))\n            max_fatal = fatals[0]\n            raise max_fatal\n\n        if maxException is not None:\n            maxException.msg = self.errmsg\n            raise maxException\n        else:\n            raise ParseException(\n                instring, loc, \"no defined alternatives to match\", self\n            )\n\n    def __ixor__(self, other):\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        return self.append(other)  # Or([self, other])\n\n    def _generateDefaultName(self):\n        return \"{\" + \" ^ \".join(str(e) for e in self.exprs) + \"}\"\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if (\n            __diag__.warn_multiple_tokens_in_named_alternation\n            and Diagnostics.warn_multiple_tokens_in_named_alternation\n            not in self.suppress_warnings_\n        ):\n            if any(\n                isinstance(e, And)\n                and Diagnostics.warn_multiple_tokens_in_named_alternation\n                not in e.suppress_warnings_\n                for e in self.exprs\n            ):\n                warnings.warn(\n                    \"{}: setting results name {!r} on {} expression \"\n                    \"will return a list of all parsed tokens in an And alternative, \"\n                    \"in prior versions only the first token was returned; enclose \"\n                    \"contained argument in Group\".format(\n                        \"warn_multiple_tokens_in_named_alternation\",\n                        name,\n                        type(self).__name__,\n                    ),\n                    stacklevel=3,\n                )\n\n        return super()._setResultsName(name, listAllMatches)\n\n\nclass MatchFirst(ParseExpression):\n    \"\"\"Requires that at least one :class:`ParseExpression` is found. If\n    more than one expression matches, the first one listed is the one that will\n    match. May be constructed using the ``'|'`` operator.\n\n    Example::\n\n        # construct MatchFirst using '|' operator\n\n        # watch the order of expressions to match\n        number = Word(nums) | Combine(Word(nums) + '.' + Word(nums))\n        print(number.search_string(\"123 3.1416 789\")) #  Fail! -> [['123'], ['3'], ['1416'], ['789']]\n\n        # put more selective expression first\n        number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums)\n        print(number.search_string(\"123 3.1416 789\")) #  Better -> [['123'], ['3.1416'], ['789']]\n    \"\"\"\n\n    def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False):\n        super().__init__(exprs, savelist)\n        if self.exprs:\n            self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)\n            self.skipWhitespace = all(e.skipWhitespace for e in self.exprs)\n        else:\n            self.mayReturnEmpty = True\n\n    def streamline(self) -> ParserElement:\n        if self.streamlined:\n            return self\n\n        super().streamline()\n        if self.exprs:\n            self.saveAsList = any(e.saveAsList for e in self.exprs)\n            self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)\n            self.skipWhitespace = all(\n                e.skipWhitespace and not isinstance(e, White) for e in self.exprs\n            )\n        else:\n            self.saveAsList = False\n            self.mayReturnEmpty = True\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        maxExcLoc = -1\n        maxException = None\n\n        for e in self.exprs:\n            try:\n                return e._parse(\n                    instring,\n                    loc,\n                    doActions,\n                )\n            except ParseFatalException as pfe:\n                pfe.__traceback__ = None\n                pfe.parserElement = e\n                raise\n            except ParseException as err:\n                if err.loc > maxExcLoc:\n                    maxException = err\n                    maxExcLoc = err.loc\n            except IndexError:\n                if len(instring) > maxExcLoc:\n                    maxException = ParseException(\n                        instring, len(instring), e.errmsg, self\n                    )\n                    maxExcLoc = len(instring)\n\n        if maxException is not None:\n            maxException.msg = self.errmsg\n            raise maxException\n        else:\n            raise ParseException(\n                instring, loc, \"no defined alternatives to match\", self\n            )\n\n    def __ior__(self, other):\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        return self.append(other)  # MatchFirst([self, other])\n\n    def _generateDefaultName(self):\n        return \"{\" + \" | \".join(str(e) for e in self.exprs) + \"}\"\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if (\n            __diag__.warn_multiple_tokens_in_named_alternation\n            and Diagnostics.warn_multiple_tokens_in_named_alternation\n            not in self.suppress_warnings_\n        ):\n            if any(\n                isinstance(e, And)\n                and Diagnostics.warn_multiple_tokens_in_named_alternation\n                not in e.suppress_warnings_\n                for e in self.exprs\n            ):\n                warnings.warn(\n                    \"{}: setting results name {!r} on {} expression \"\n                    \"will return a list of all parsed tokens in an And alternative, \"\n                    \"in prior versions only the first token was returned; enclose \"\n                    \"contained argument in Group\".format(\n                        \"warn_multiple_tokens_in_named_alternation\",\n                        name,\n                        type(self).__name__,\n                    ),\n                    stacklevel=3,\n                )\n\n        return super()._setResultsName(name, listAllMatches)\n\n\nclass Each(ParseExpression):\n    \"\"\"Requires all given :class:`ParseExpression` s to be found, but in\n    any order. Expressions may be separated by whitespace.\n\n    May be constructed using the ``'&'`` operator.\n\n    Example::\n\n        color = one_of(\"RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN\")\n        shape_type = one_of(\"SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON\")\n        integer = Word(nums)\n        shape_attr = \"shape:\" + shape_type(\"shape\")\n        posn_attr = \"posn:\" + Group(integer(\"x\") + ',' + integer(\"y\"))(\"posn\")\n        color_attr = \"color:\" + color(\"color\")\n        size_attr = \"size:\" + integer(\"size\")\n\n        # use Each (using operator '&') to accept attributes in any order\n        # (shape and posn are required, color and size are optional)\n        shape_spec = shape_attr & posn_attr & Opt(color_attr) & Opt(size_attr)\n\n        shape_spec.run_tests('''\n            shape: SQUARE color: BLACK posn: 100, 120\n            shape: CIRCLE size: 50 color: BLUE posn: 50,80\n            color:GREEN size:20 shape:TRIANGLE posn:20,40\n            '''\n            )\n\n    prints::\n\n        shape: SQUARE color: BLACK posn: 100, 120\n        ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']]\n        - color: BLACK\n        - posn: ['100', ',', '120']\n          - x: 100\n          - y: 120\n        - shape: SQUARE\n\n\n        shape: CIRCLE size: 50 color: BLUE posn: 50,80\n        ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']]\n        - color: BLUE\n        - posn: ['50', ',', '80']\n          - x: 50\n          - y: 80\n        - shape: CIRCLE\n        - size: 50\n\n\n        color: GREEN size: 20 shape: TRIANGLE posn: 20,40\n        ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']]\n        - color: GREEN\n        - posn: ['20', ',', '40']\n          - x: 20\n          - y: 40\n        - shape: TRIANGLE\n        - size: 20\n    \"\"\"\n\n    def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = True):\n        super().__init__(exprs, savelist)\n        if self.exprs:\n            self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)\n        else:\n            self.mayReturnEmpty = True\n        self.skipWhitespace = True\n        self.initExprGroups = True\n        self.saveAsList = True\n\n    def streamline(self) -> ParserElement:\n        super().streamline()\n        if self.exprs:\n            self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)\n        else:\n            self.mayReturnEmpty = True\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if self.initExprGroups:\n            self.opt1map = dict(\n                (id(e.expr), e) for e in self.exprs if isinstance(e, Opt)\n            )\n            opt1 = [e.expr for e in self.exprs if isinstance(e, Opt)]\n            opt2 = [\n                e\n                for e in self.exprs\n                if e.mayReturnEmpty and not isinstance(e, (Opt, Regex, ZeroOrMore))\n            ]\n            self.optionals = opt1 + opt2\n            self.multioptionals = [\n                e.expr.set_results_name(e.resultsName, list_all_matches=True)\n                for e in self.exprs\n                if isinstance(e, _MultipleMatch)\n            ]\n            self.multirequired = [\n                e.expr.set_results_name(e.resultsName, list_all_matches=True)\n                for e in self.exprs\n                if isinstance(e, OneOrMore)\n            ]\n            self.required = [\n                e for e in self.exprs if not isinstance(e, (Opt, ZeroOrMore, OneOrMore))\n            ]\n            self.required += self.multirequired\n            self.initExprGroups = False\n\n        tmpLoc = loc\n        tmpReqd = self.required[:]\n        tmpOpt = self.optionals[:]\n        multis = self.multioptionals[:]\n        matchOrder = []\n\n        keepMatching = True\n        failed = []\n        fatals = []\n        while keepMatching:\n            tmpExprs = tmpReqd + tmpOpt + multis\n            failed.clear()\n            fatals.clear()\n            for e in tmpExprs:\n                try:\n                    tmpLoc = e.try_parse(instring, tmpLoc, raise_fatal=True)\n                except ParseFatalException as pfe:\n                    pfe.__traceback__ = None\n                    pfe.parserElement = e\n                    fatals.append(pfe)\n                    failed.append(e)\n                except ParseException:\n                    failed.append(e)\n                else:\n                    matchOrder.append(self.opt1map.get(id(e), e))\n                    if e in tmpReqd:\n                        tmpReqd.remove(e)\n                    elif e in tmpOpt:\n                        tmpOpt.remove(e)\n            if len(failed) == len(tmpExprs):\n                keepMatching = False\n\n        # look for any ParseFatalExceptions\n        if fatals:\n            if len(fatals) > 1:\n                fatals.sort(key=lambda e: -e.loc)\n                if fatals[0].loc == fatals[1].loc:\n                    fatals.sort(key=lambda e: (-e.loc, -len(str(e.parserElement))))\n            max_fatal = fatals[0]\n            raise max_fatal\n\n        if tmpReqd:\n            missing = \", \".join([str(e) for e in tmpReqd])\n            raise ParseException(\n                instring,\n                loc,\n                \"Missing one or more required elements ({})\".format(missing),\n            )\n\n        # add any unmatched Opts, in case they have default values defined\n        matchOrder += [e for e in self.exprs if isinstance(e, Opt) and e.expr in tmpOpt]\n\n        total_results = ParseResults([])\n        for e in matchOrder:\n            loc, results = e._parse(instring, loc, doActions)\n            total_results += results\n\n        return loc, total_results\n\n    def _generateDefaultName(self):\n        return \"{\" + \" & \".join(str(e) for e in self.exprs) + \"}\"\n\n\nclass ParseElementEnhance(ParserElement):\n    \"\"\"Abstract subclass of :class:`ParserElement`, for combining and\n    post-processing parsed tokens.\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str], savelist: bool = False):\n        super().__init__(savelist)\n        if isinstance(expr, str_type):\n            if issubclass(self._literalStringClass, Token):\n                expr = self._literalStringClass(expr)\n            elif issubclass(type(self), self._literalStringClass):\n                expr = Literal(expr)\n            else:\n                expr = self._literalStringClass(Literal(expr))\n        self.expr = expr\n        if expr is not None:\n            self.mayIndexError = expr.mayIndexError\n            self.mayReturnEmpty = expr.mayReturnEmpty\n            self.set_whitespace_chars(\n                expr.whiteChars, copy_defaults=expr.copyDefaultWhiteChars\n            )\n            self.skipWhitespace = expr.skipWhitespace\n            self.saveAsList = expr.saveAsList\n            self.callPreparse = expr.callPreparse\n            self.ignoreExprs.extend(expr.ignoreExprs)\n\n    def recurse(self) -> Sequence[ParserElement]:\n        return [self.expr] if self.expr is not None else []\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if self.expr is not None:\n            return self.expr._parse(instring, loc, doActions, callPreParse=False)\n        else:\n            raise ParseException(instring, loc, \"No expression defined\", self)\n\n    def leave_whitespace(self, recursive: bool = True) -> ParserElement:\n        super().leave_whitespace(recursive)\n\n        if recursive:\n            self.expr = self.expr.copy()\n            if self.expr is not None:\n                self.expr.leave_whitespace(recursive)\n        return self\n\n    def ignore_whitespace(self, recursive: bool = True) -> ParserElement:\n        super().ignore_whitespace(recursive)\n\n        if recursive:\n            self.expr = self.expr.copy()\n            if self.expr is not None:\n                self.expr.ignore_whitespace(recursive)\n        return self\n\n    def ignore(self, other) -> ParserElement:\n        if isinstance(other, Suppress):\n            if other not in self.ignoreExprs:\n                super().ignore(other)\n                if self.expr is not None:\n                    self.expr.ignore(self.ignoreExprs[-1])\n        else:\n            super().ignore(other)\n            if self.expr is not None:\n                self.expr.ignore(self.ignoreExprs[-1])\n        return self\n\n    def streamline(self) -> ParserElement:\n        super().streamline()\n        if self.expr is not None:\n            self.expr.streamline()\n        return self\n\n    def _checkRecursion(self, parseElementList):\n        if self in parseElementList:\n            raise RecursiveGrammarException(parseElementList + [self])\n        subRecCheckList = parseElementList[:] + [self]\n        if self.expr is not None:\n            self.expr._checkRecursion(subRecCheckList)\n\n    def validate(self, validateTrace=None) -> None:\n        if validateTrace is None:\n            validateTrace = []\n        tmp = validateTrace[:] + [self]\n        if self.expr is not None:\n            self.expr.validate(tmp)\n        self._checkRecursion([])\n\n    def _generateDefaultName(self):\n        return \"{}:({})\".format(self.__class__.__name__, str(self.expr))\n\n    ignoreWhitespace = ignore_whitespace\n    leaveWhitespace = leave_whitespace\n\n\nclass IndentedBlock(ParseElementEnhance):\n    \"\"\"\n    Expression to match one or more expressions at a given indentation level.\n    Useful for parsing text where structure is implied by indentation (like Python source code).\n    \"\"\"\n\n    class _Indent(Empty):\n        def __init__(self, ref_col: int):\n            super().__init__()\n            self.errmsg = \"expected indent at column {}\".format(ref_col)\n            self.add_condition(lambda s, l, t: col(l, s) == ref_col)\n\n    class _IndentGreater(Empty):\n        def __init__(self, ref_col: int):\n            super().__init__()\n            self.errmsg = \"expected indent at column greater than {}\".format(ref_col)\n            self.add_condition(lambda s, l, t: col(l, s) > ref_col)\n\n    def __init__(\n        self, expr: ParserElement, *, recursive: bool = False, grouped: bool = True\n    ):\n        super().__init__(expr, savelist=True)\n        # if recursive:\n        #     raise NotImplementedError(\"IndentedBlock with recursive is not implemented\")\n        self._recursive = recursive\n        self._grouped = grouped\n        self.parent_anchor = 1\n\n    def parseImpl(self, instring, loc, doActions=True):\n        # advance parse position to non-whitespace by using an Empty()\n        # this should be the column to be used for all subsequent indented lines\n        anchor_loc = Empty().preParse(instring, loc)\n\n        # see if self.expr matches at the current location - if not it will raise an exception\n        # and no further work is necessary\n        self.expr.try_parse(instring, anchor_loc, doActions)\n\n        indent_col = col(anchor_loc, instring)\n        peer_detect_expr = self._Indent(indent_col)\n\n        inner_expr = Empty() + peer_detect_expr + self.expr\n        if self._recursive:\n            sub_indent = self._IndentGreater(indent_col)\n            nested_block = IndentedBlock(\n                self.expr, recursive=self._recursive, grouped=self._grouped\n            )\n            nested_block.set_debug(self.debug)\n            nested_block.parent_anchor = indent_col\n            inner_expr += Opt(sub_indent + nested_block)\n\n        inner_expr.set_name(f\"inner {hex(id(inner_expr))[-4:].upper()}@{indent_col}\")\n        block = OneOrMore(inner_expr)\n\n        trailing_undent = self._Indent(self.parent_anchor) | StringEnd()\n\n        if self._grouped:\n            wrapper = Group\n        else:\n            wrapper = lambda expr: expr\n        return (wrapper(block) + Optional(trailing_undent)).parseImpl(\n            instring, anchor_loc, doActions\n        )\n\n\nclass AtStringStart(ParseElementEnhance):\n    \"\"\"Matches if expression matches at the beginning of the parse\n    string::\n\n        AtStringStart(Word(nums)).parse_string(\"123\")\n        # prints [\"123\"]\n\n        AtStringStart(Word(nums)).parse_string(\"    123\")\n        # raises ParseException\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str]):\n        super().__init__(expr)\n        self.callPreparse = False\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc != 0:\n            raise ParseException(instring, loc, \"not found at string start\")\n        return super().parseImpl(instring, loc, doActions)\n\n\nclass AtLineStart(ParseElementEnhance):\n    r\"\"\"Matches if an expression matches at the beginning of a line within\n    the parse string\n\n    Example::\n\n        test = '''\\\n        AAA this line\n        AAA and this line\n          AAA but not this one\n        B AAA and definitely not this one\n        '''\n\n        for t in (AtLineStart('AAA') + restOfLine).search_string(test):\n            print(t)\n\n    prints::\n\n        ['AAA', ' this line']\n        ['AAA', ' and this line']\n\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str]):\n        super().__init__(expr)\n        self.callPreparse = False\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if col(loc, instring) != 1:\n            raise ParseException(instring, loc, \"not found at line start\")\n        return super().parseImpl(instring, loc, doActions)\n\n\nclass FollowedBy(ParseElementEnhance):\n    \"\"\"Lookahead matching of the given parse expression.\n    ``FollowedBy`` does *not* advance the parsing position within\n    the input string, it only verifies that the specified parse\n    expression matches at the current position.  ``FollowedBy``\n    always returns a null token list. If any results names are defined\n    in the lookahead expression, those *will* be returned for access by\n    name.\n\n    Example::\n\n        # use FollowedBy to match a label only if it is followed by a ':'\n        data_word = Word(alphas)\n        label = data_word + FollowedBy(':')\n        attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))\n\n        attr_expr[1, ...].parse_string(\"shape: SQUARE color: BLACK posn: upper left\").pprint()\n\n    prints::\n\n        [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']]\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str]):\n        super().__init__(expr)\n        self.mayReturnEmpty = True\n\n    def parseImpl(self, instring, loc, doActions=True):\n        # by using self._expr.parse and deleting the contents of the returned ParseResults list\n        # we keep any named results that were defined in the FollowedBy expression\n        _, ret = self.expr._parse(instring, loc, doActions=doActions)\n        del ret[:]\n\n        return loc, ret\n\n\nclass PrecededBy(ParseElementEnhance):\n    \"\"\"Lookbehind matching of the given parse expression.\n    ``PrecededBy`` does not advance the parsing position within the\n    input string, it only verifies that the specified parse expression\n    matches prior to the current position.  ``PrecededBy`` always\n    returns a null token list, but if a results name is defined on the\n    given expression, it is returned.\n\n    Parameters:\n\n    - expr - expression that must match prior to the current parse\n      location\n    - retreat - (default= ``None``) - (int) maximum number of characters\n      to lookbehind prior to the current parse location\n\n    If the lookbehind expression is a string, :class:`Literal`,\n    :class:`Keyword`, or a :class:`Word` or :class:`CharsNotIn`\n    with a specified exact or maximum length, then the retreat\n    parameter is not required. Otherwise, retreat must be specified to\n    give a maximum number of characters to look back from\n    the current parse position for a lookbehind match.\n\n    Example::\n\n        # VB-style variable names with type prefixes\n        int_var = PrecededBy(\"#\") + pyparsing_common.identifier\n        str_var = PrecededBy(\"$\") + pyparsing_common.identifier\n\n    \"\"\"\n\n    def __init__(\n        self, expr: Union[ParserElement, str], retreat: typing.Optional[int] = None\n    ):\n        super().__init__(expr)\n        self.expr = self.expr().leave_whitespace()\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n        self.exact = False\n        if isinstance(expr, str_type):\n            retreat = len(expr)\n            self.exact = True\n        elif isinstance(expr, (Literal, Keyword)):\n            retreat = expr.matchLen\n            self.exact = True\n        elif isinstance(expr, (Word, CharsNotIn)) and expr.maxLen != _MAX_INT:\n            retreat = expr.maxLen\n            self.exact = True\n        elif isinstance(expr, PositionToken):\n            retreat = 0\n            self.exact = True\n        self.retreat = retreat\n        self.errmsg = \"not preceded by \" + str(expr)\n        self.skipWhitespace = False\n        self.parseAction.append(lambda s, l, t: t.__delitem__(slice(None, None)))\n\n    def parseImpl(self, instring, loc=0, doActions=True):\n        if self.exact:\n            if loc < self.retreat:\n                raise ParseException(instring, loc, self.errmsg)\n            start = loc - self.retreat\n            _, ret = self.expr._parse(instring, start)\n        else:\n            # retreat specified a maximum lookbehind window, iterate\n            test_expr = self.expr + StringEnd()\n            instring_slice = instring[max(0, loc - self.retreat) : loc]\n            last_expr = ParseException(instring, loc, self.errmsg)\n            for offset in range(1, min(loc, self.retreat + 1) + 1):\n                try:\n                    # print('trying', offset, instring_slice, repr(instring_slice[loc - offset:]))\n                    _, ret = test_expr._parse(\n                        instring_slice, len(instring_slice) - offset\n                    )\n                except ParseBaseException as pbe:\n                    last_expr = pbe\n                else:\n                    break\n            else:\n                raise last_expr\n        return loc, ret\n\n\nclass Located(ParseElementEnhance):\n    \"\"\"\n    Decorates a returned token with its starting and ending\n    locations in the input string.\n\n    This helper adds the following results names:\n\n    - ``locn_start`` - location where matched expression begins\n    - ``locn_end`` - location where matched expression ends\n    - ``value`` - the actual parsed results\n\n    Be careful if the input text contains ``<TAB>`` characters, you\n    may want to call :class:`ParserElement.parse_with_tabs`\n\n    Example::\n\n        wd = Word(alphas)\n        for match in Located(wd).search_string(\"ljsdf123lksdjjf123lkkjj1222\"):\n            print(match)\n\n    prints::\n\n        [0, ['ljsdf'], 5]\n        [8, ['lksdjjf'], 15]\n        [18, ['lkkjj'], 23]\n\n    \"\"\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        start = loc\n        loc, tokens = self.expr._parse(instring, start, doActions, callPreParse=False)\n        ret_tokens = ParseResults([start, tokens, loc])\n        ret_tokens[\"locn_start\"] = start\n        ret_tokens[\"value\"] = tokens\n        ret_tokens[\"locn_end\"] = loc\n        if self.resultsName:\n            # must return as a list, so that the name will be attached to the complete group\n            return loc, [ret_tokens]\n        else:\n            return loc, ret_tokens\n\n\nclass NotAny(ParseElementEnhance):\n    \"\"\"\n    Lookahead to disallow matching with the given parse expression.\n    ``NotAny`` does *not* advance the parsing position within the\n    input string, it only verifies that the specified parse expression\n    does *not* match at the current position.  Also, ``NotAny`` does\n    *not* skip over leading whitespace. ``NotAny`` always returns\n    a null token list.  May be constructed using the ``'~'`` operator.\n\n    Example::\n\n        AND, OR, NOT = map(CaselessKeyword, \"AND OR NOT\".split())\n\n        # take care not to mistake keywords for identifiers\n        ident = ~(AND | OR | NOT) + Word(alphas)\n        boolean_term = Opt(NOT) + ident\n\n        # very crude boolean expression - to support parenthesis groups and\n        # operation hierarchy, use infix_notation\n        boolean_expr = boolean_term + ((AND | OR) + boolean_term)[...]\n\n        # integers that are followed by \".\" are actually floats\n        integer = Word(nums) + ~Char(\".\")\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str]):\n        super().__init__(expr)\n        # do NOT use self.leave_whitespace(), don't want to propagate to exprs\n        # self.leave_whitespace()\n        self.skipWhitespace = False\n\n        self.mayReturnEmpty = True\n        self.errmsg = \"Found unwanted token, \" + str(self.expr)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if self.expr.can_parse_next(instring, loc):\n            raise ParseException(instring, loc, self.errmsg, self)\n        return loc, []\n\n    def _generateDefaultName(self):\n        return \"~{\" + str(self.expr) + \"}\"\n\n\nclass _MultipleMatch(ParseElementEnhance):\n    def __init__(\n        self,\n        expr: ParserElement,\n        stop_on: typing.Optional[Union[ParserElement, str]] = None,\n        *,\n        stopOn: typing.Optional[Union[ParserElement, str]] = None,\n    ):\n        super().__init__(expr)\n        stopOn = stopOn or stop_on\n        self.saveAsList = True\n        ender = stopOn\n        if isinstance(ender, str_type):\n            ender = self._literalStringClass(ender)\n        self.stopOn(ender)\n\n    def stopOn(self, ender) -> ParserElement:\n        if isinstance(ender, str_type):\n            ender = self._literalStringClass(ender)\n        self.not_ender = ~ender if ender is not None else None\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        self_expr_parse = self.expr._parse\n        self_skip_ignorables = self._skipIgnorables\n        check_ender = self.not_ender is not None\n        if check_ender:\n            try_not_ender = self.not_ender.tryParse\n\n        # must be at least one (but first see if we are the stopOn sentinel;\n        # if so, fail)\n        if check_ender:\n            try_not_ender(instring, loc)\n        loc, tokens = self_expr_parse(instring, loc, doActions)\n        try:\n            hasIgnoreExprs = not not self.ignoreExprs\n            while 1:\n                if check_ender:\n                    try_not_ender(instring, loc)\n                if hasIgnoreExprs:\n                    preloc = self_skip_ignorables(instring, loc)\n                else:\n                    preloc = loc\n                loc, tmptokens = self_expr_parse(instring, preloc, doActions)\n                if tmptokens or tmptokens.haskeys():\n                    tokens += tmptokens\n        except (ParseException, IndexError):\n            pass\n\n        return loc, tokens\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if (\n            __diag__.warn_ungrouped_named_tokens_in_collection\n            and Diagnostics.warn_ungrouped_named_tokens_in_collection\n            not in self.suppress_warnings_\n        ):\n            for e in [self.expr] + self.expr.recurse():\n                if (\n                    isinstance(e, ParserElement)\n                    and e.resultsName\n                    and Diagnostics.warn_ungrouped_named_tokens_in_collection\n                    not in e.suppress_warnings_\n                ):\n                    warnings.warn(\n                        \"{}: setting results name {!r} on {} expression \"\n                        \"collides with {!r} on contained expression\".format(\n                            \"warn_ungrouped_named_tokens_in_collection\",\n                            name,\n                            type(self).__name__,\n                            e.resultsName,\n                        ),\n                        stacklevel=3,\n                    )\n\n        return super()._setResultsName(name, listAllMatches)\n\n\nclass OneOrMore(_MultipleMatch):\n    \"\"\"\n    Repetition of one or more of the given expression.\n\n    Parameters:\n    - expr - expression that must match one or more times\n    - stop_on - (default= ``None``) - expression for a terminating sentinel\n         (only required if the sentinel would ordinarily match the repetition\n         expression)\n\n    Example::\n\n        data_word = Word(alphas)\n        label = data_word + FollowedBy(':')\n        attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).set_parse_action(' '.join))\n\n        text = \"shape: SQUARE posn: upper left color: BLACK\"\n        attr_expr[1, ...].parse_string(text).pprint()  # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']]\n\n        # use stop_on attribute for OneOrMore to avoid reading label string as part of the data\n        attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))\n        OneOrMore(attr_expr).parse_string(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']]\n\n        # could also be written as\n        (attr_expr * (1,)).parse_string(text).pprint()\n    \"\"\"\n\n    def _generateDefaultName(self):\n        return \"{\" + str(self.expr) + \"}...\"\n\n\nclass ZeroOrMore(_MultipleMatch):\n    \"\"\"\n    Optional repetition of zero or more of the given expression.\n\n    Parameters:\n    - ``expr`` - expression that must match zero or more times\n    - ``stop_on`` - expression for a terminating sentinel\n      (only required if the sentinel would ordinarily match the repetition\n      expression) - (default= ``None``)\n\n    Example: similar to :class:`OneOrMore`\n    \"\"\"\n\n    def __init__(\n        self,\n        expr: ParserElement,\n        stop_on: typing.Optional[Union[ParserElement, str]] = None,\n        *,\n        stopOn: typing.Optional[Union[ParserElement, str]] = None,\n    ):\n        super().__init__(expr, stopOn=stopOn or stop_on)\n        self.mayReturnEmpty = True\n\n    def parseImpl(self, instring, loc, doActions=True):\n        try:\n            return super().parseImpl(instring, loc, doActions)\n        except (ParseException, IndexError):\n            return loc, ParseResults([], name=self.resultsName)\n\n    def _generateDefaultName(self):\n        return \"[\" + str(self.expr) + \"]...\"\n\n\nclass _NullToken:\n    def __bool__(self):\n        return False\n\n    def __str__(self):\n        return \"\"\n\n\nclass Opt(ParseElementEnhance):\n    \"\"\"\n    Optional matching of the given expression.\n\n    Parameters:\n    - ``expr`` - expression that must match zero or more times\n    - ``default`` (optional) - value to be returned if the optional expression is not found.\n\n    Example::\n\n        # US postal code can be a 5-digit zip, plus optional 4-digit qualifier\n        zip = Combine(Word(nums, exact=5) + Opt('-' + Word(nums, exact=4)))\n        zip.run_tests('''\n            # traditional ZIP code\n            12345\n\n            # ZIP+4 form\n            12101-0001\n\n            # invalid ZIP\n            98765-\n            ''')\n\n    prints::\n\n        # traditional ZIP code\n        12345\n        ['12345']\n\n        # ZIP+4 form\n        12101-0001\n        ['12101-0001']\n\n        # invalid ZIP\n        98765-\n             ^\n        FAIL: Expected end of text (at char 5), (line:1, col:6)\n    \"\"\"\n\n    __optionalNotMatched = _NullToken()\n\n    def __init__(\n        self, expr: Union[ParserElement, str], default: Any = __optionalNotMatched\n    ):\n        super().__init__(expr, savelist=False)\n        self.saveAsList = self.expr.saveAsList\n        self.defaultValue = default\n        self.mayReturnEmpty = True\n\n    def parseImpl(self, instring, loc, doActions=True):\n        self_expr = self.expr\n        try:\n            loc, tokens = self_expr._parse(instring, loc, doActions, callPreParse=False)\n        except (ParseException, IndexError):\n            default_value = self.defaultValue\n            if default_value is not self.__optionalNotMatched:\n                if self_expr.resultsName:\n                    tokens = ParseResults([default_value])\n                    tokens[self_expr.resultsName] = default_value\n                else:\n                    tokens = [default_value]\n            else:\n                tokens = []\n        return loc, tokens\n\n    def _generateDefaultName(self):\n        inner = str(self.expr)\n        # strip off redundant inner {}'s\n        while len(inner) > 1 and inner[0 :: len(inner) - 1] == \"{}\":\n            inner = inner[1:-1]\n        return \"[\" + inner + \"]\"\n\n\nOptional = Opt\n\n\nclass SkipTo(ParseElementEnhance):\n    \"\"\"\n    Token for skipping over all undefined text until the matched\n    expression is found.\n\n    Parameters:\n    - ``expr`` - target expression marking the end of the data to be skipped\n    - ``include`` - if ``True``, the target expression is also parsed\n      (the skipped text and target expression are returned as a 2-element\n      list) (default= ``False``).\n    - ``ignore`` - (default= ``None``) used to define grammars (typically quoted strings and\n      comments) that might contain false matches to the target expression\n    - ``fail_on`` - (default= ``None``) define expressions that are not allowed to be\n      included in the skipped test; if found before the target expression is found,\n      the :class:`SkipTo` is not a match\n\n    Example::\n\n        report = '''\n            Outstanding Issues Report - 1 Jan 2000\n\n               # | Severity | Description                               |  Days Open\n            -----+----------+-------------------------------------------+-----------\n             101 | Critical | Intermittent system crash                 |          6\n              94 | Cosmetic | Spelling error on Login ('log|n')         |         14\n              79 | Minor    | System slow when running too many reports |         47\n            '''\n        integer = Word(nums)\n        SEP = Suppress('|')\n        # use SkipTo to simply match everything up until the next SEP\n        # - ignore quoted strings, so that a '|' character inside a quoted string does not match\n        # - parse action will call token.strip() for each matched token, i.e., the description body\n        string_data = SkipTo(SEP, ignore=quoted_string)\n        string_data.set_parse_action(token_map(str.strip))\n        ticket_expr = (integer(\"issue_num\") + SEP\n                      + string_data(\"sev\") + SEP\n                      + string_data(\"desc\") + SEP\n                      + integer(\"days_open\"))\n\n        for tkt in ticket_expr.search_string(report):\n            print tkt.dump()\n\n    prints::\n\n        ['101', 'Critical', 'Intermittent system crash', '6']\n        - days_open: '6'\n        - desc: 'Intermittent system crash'\n        - issue_num: '101'\n        - sev: 'Critical'\n        ['94', 'Cosmetic', \"Spelling error on Login ('log|n')\", '14']\n        - days_open: '14'\n        - desc: \"Spelling error on Login ('log|n')\"\n        - issue_num: '94'\n        - sev: 'Cosmetic'\n        ['79', 'Minor', 'System slow when running too many reports', '47']\n        - days_open: '47'\n        - desc: 'System slow when running too many reports'\n        - issue_num: '79'\n        - sev: 'Minor'\n    \"\"\"\n\n    def __init__(\n        self,\n        other: Union[ParserElement, str],\n        include: bool = False,\n        ignore: bool = None,\n        fail_on: typing.Optional[Union[ParserElement, str]] = None,\n        *,\n        failOn: Union[ParserElement, str] = None,\n    ):\n        super().__init__(other)\n        failOn = failOn or fail_on\n        self.ignoreExpr = ignore\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n        self.includeMatch = include\n        self.saveAsList = False\n        if isinstance(failOn, str_type):\n            self.failOn = self._literalStringClass(failOn)\n        else:\n            self.failOn = failOn\n        self.errmsg = \"No match found for \" + str(self.expr)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        startloc = loc\n        instrlen = len(instring)\n        self_expr_parse = self.expr._parse\n        self_failOn_canParseNext = (\n            self.failOn.canParseNext if self.failOn is not None else None\n        )\n        self_ignoreExpr_tryParse = (\n            self.ignoreExpr.tryParse if self.ignoreExpr is not None else None\n        )\n\n        tmploc = loc\n        while tmploc <= instrlen:\n            if self_failOn_canParseNext is not None:\n                # break if failOn expression matches\n                if self_failOn_canParseNext(instring, tmploc):\n                    break\n\n            if self_ignoreExpr_tryParse is not None:\n                # advance past ignore expressions\n                while 1:\n                    try:\n                        tmploc = self_ignoreExpr_tryParse(instring, tmploc)\n                    except ParseBaseException:\n                        break\n\n            try:\n                self_expr_parse(instring, tmploc, doActions=False, callPreParse=False)\n            except (ParseException, IndexError):\n                # no match, advance loc in string\n                tmploc += 1\n            else:\n                # matched skipto expr, done\n                break\n\n        else:\n            # ran off the end of the input string without matching skipto expr, fail\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        # build up return values\n        loc = tmploc\n        skiptext = instring[startloc:loc]\n        skipresult = ParseResults(skiptext)\n\n        if self.includeMatch:\n            loc, mat = self_expr_parse(instring, loc, doActions, callPreParse=False)\n            skipresult += mat\n\n        return loc, skipresult\n\n\nclass Forward(ParseElementEnhance):\n    \"\"\"\n    Forward declaration of an expression to be defined later -\n    used for recursive grammars, such as algebraic infix notation.\n    When the expression is known, it is assigned to the ``Forward``\n    variable using the ``'<<'`` operator.\n\n    Note: take care when assigning to ``Forward`` not to overlook\n    precedence of operators.\n\n    Specifically, ``'|'`` has a lower precedence than ``'<<'``, so that::\n\n        fwd_expr << a | b | c\n\n    will actually be evaluated as::\n\n        (fwd_expr << a) | b | c\n\n    thereby leaving b and c out as parseable alternatives.  It is recommended that you\n    explicitly group the values inserted into the ``Forward``::\n\n        fwd_expr << (a | b | c)\n\n    Converting to use the ``'<<='`` operator instead will avoid this problem.\n\n    See :class:`ParseResults.pprint` for an example of a recursive\n    parser created using ``Forward``.\n    \"\"\"\n\n    def __init__(self, other: typing.Optional[Union[ParserElement, str]] = None):\n        self.caller_frame = traceback.extract_stack(limit=2)[0]\n        super().__init__(other, savelist=False)\n        self.lshift_line = None\n\n    def __lshift__(self, other):\n        if hasattr(self, \"caller_frame\"):\n            del self.caller_frame\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        self.expr = other\n        self.mayIndexError = self.expr.mayIndexError\n        self.mayReturnEmpty = self.expr.mayReturnEmpty\n        self.set_whitespace_chars(\n            self.expr.whiteChars, copy_defaults=self.expr.copyDefaultWhiteChars\n        )\n        self.skipWhitespace = self.expr.skipWhitespace\n        self.saveAsList = self.expr.saveAsList\n        self.ignoreExprs.extend(self.expr.ignoreExprs)\n        self.lshift_line = traceback.extract_stack(limit=2)[-2]\n        return self\n\n    def __ilshift__(self, other):\n        return self << other\n\n    def __or__(self, other):\n        caller_line = traceback.extract_stack(limit=2)[-2]\n        if (\n            __diag__.warn_on_match_first_with_lshift_operator\n            and caller_line == self.lshift_line\n            and Diagnostics.warn_on_match_first_with_lshift_operator\n            not in self.suppress_warnings_\n        ):\n            warnings.warn(\n                \"using '<<' operator with '|' is probably an error, use '<<='\",\n                stacklevel=2,\n            )\n        ret = super().__or__(other)\n        return ret\n\n    def __del__(self):\n        # see if we are getting dropped because of '=' reassignment of var instead of '<<=' or '<<'\n        if (\n            self.expr is None\n            and __diag__.warn_on_assignment_to_Forward\n            and Diagnostics.warn_on_assignment_to_Forward not in self.suppress_warnings_\n        ):\n            warnings.warn_explicit(\n                \"Forward defined here but no expression attached later using '<<=' or '<<'\",\n                UserWarning,\n                filename=self.caller_frame.filename,\n                lineno=self.caller_frame.lineno,\n            )\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if (\n            self.expr is None\n            and __diag__.warn_on_parse_using_empty_Forward\n            and Diagnostics.warn_on_parse_using_empty_Forward\n            not in self.suppress_warnings_\n        ):\n            # walk stack until parse_string, scan_string, search_string, or transform_string is found\n            parse_fns = [\n                \"parse_string\",\n                \"scan_string\",\n                \"search_string\",\n                \"transform_string\",\n            ]\n            tb = traceback.extract_stack(limit=200)\n            for i, frm in enumerate(reversed(tb), start=1):\n                if frm.name in parse_fns:\n                    stacklevel = i + 1\n                    break\n            else:\n                stacklevel = 2\n            warnings.warn(\n                \"Forward expression was never assigned a value, will not parse any input\",\n                stacklevel=stacklevel,\n            )\n        if not ParserElement._left_recursion_enabled:\n            return super().parseImpl(instring, loc, doActions)\n        # ## Bounded Recursion algorithm ##\n        # Recursion only needs to be processed at ``Forward`` elements, since they are\n        # the only ones that can actually refer to themselves. The general idea is\n        # to handle recursion stepwise: We start at no recursion, then recurse once,\n        # recurse twice, ..., until more recursion offers no benefit (we hit the bound).\n        #\n        # The \"trick\" here is that each ``Forward`` gets evaluated in two contexts\n        # - to *match* a specific recursion level, and\n        # - to *search* the bounded recursion level\n        # and the two run concurrently. The *search* must *match* each recursion level\n        # to find the best possible match. This is handled by a memo table, which\n        # provides the previous match to the next level match attempt.\n        #\n        # See also \"Left Recursion in Parsing Expression Grammars\", Medeiros et al.\n        #\n        # There is a complication since we not only *parse* but also *transform* via\n        # actions: We do not want to run the actions too often while expanding. Thus,\n        # we expand using `doActions=False` and only run `doActions=True` if the next\n        # recursion level is acceptable.\n        with ParserElement.recursion_lock:\n            memo = ParserElement.recursion_memos\n            try:\n                # we are parsing at a specific recursion expansion - use it as-is\n                prev_loc, prev_result = memo[loc, self, doActions]\n                if isinstance(prev_result, Exception):\n                    raise prev_result\n                return prev_loc, prev_result.copy()\n            except KeyError:\n                act_key = (loc, self, True)\n                peek_key = (loc, self, False)\n                # we are searching for the best recursion expansion - keep on improving\n                # both `doActions` cases must be tracked separately here!\n                prev_loc, prev_peek = memo[peek_key] = (\n                    loc - 1,\n                    ParseException(\n                        instring, loc, \"Forward recursion without base case\", self\n                    ),\n                )\n                if doActions:\n                    memo[act_key] = memo[peek_key]\n                while True:\n                    try:\n                        new_loc, new_peek = super().parseImpl(instring, loc, False)\n                    except ParseException:\n                        # we failed before getting any match – do not hide the error\n                        if isinstance(prev_peek, Exception):\n                            raise\n                        new_loc, new_peek = prev_loc, prev_peek\n                    # the match did not get better: we are done\n                    if new_loc <= prev_loc:\n                        if doActions:\n                            # replace the match for doActions=False as well,\n                            # in case the action did backtrack\n                            prev_loc, prev_result = memo[peek_key] = memo[act_key]\n                            del memo[peek_key], memo[act_key]\n                            return prev_loc, prev_result.copy()\n                        del memo[peek_key]\n                        return prev_loc, prev_peek.copy()\n                    # the match did get better: see if we can improve further\n                    else:\n                        if doActions:\n                            try:\n                                memo[act_key] = super().parseImpl(instring, loc, True)\n                            except ParseException as e:\n                                memo[peek_key] = memo[act_key] = (new_loc, e)\n                                raise\n                        prev_loc, prev_peek = memo[peek_key] = new_loc, new_peek\n\n    def leave_whitespace(self, recursive: bool = True) -> ParserElement:\n        self.skipWhitespace = False\n        return self\n\n    def ignore_whitespace(self, recursive: bool = True) -> ParserElement:\n        self.skipWhitespace = True\n        return self\n\n    def streamline(self) -> ParserElement:\n        if not self.streamlined:\n            self.streamlined = True\n            if self.expr is not None:\n                self.expr.streamline()\n        return self\n\n    def validate(self, validateTrace=None) -> None:\n        if validateTrace is None:\n            validateTrace = []\n\n        if self not in validateTrace:\n            tmp = validateTrace[:] + [self]\n            if self.expr is not None:\n                self.expr.validate(tmp)\n        self._checkRecursion([])\n\n    def _generateDefaultName(self):\n        # Avoid infinite recursion by setting a temporary _defaultName\n        self._defaultName = \": ...\"\n\n        # Use the string representation of main expression.\n        retString = \"...\"\n        try:\n            if self.expr is not None:\n                retString = str(self.expr)[:1000]\n            else:\n                retString = \"None\"\n        finally:\n            return self.__class__.__name__ + \": \" + retString\n\n    def copy(self) -> ParserElement:\n        if self.expr is not None:\n            return super().copy()\n        else:\n            ret = Forward()\n            ret <<= self\n            return ret\n\n    def _setResultsName(self, name, list_all_matches=False):\n        if (\n            __diag__.warn_name_set_on_empty_Forward\n            and Diagnostics.warn_name_set_on_empty_Forward\n            not in self.suppress_warnings_\n        ):\n            if self.expr is None:\n                warnings.warn(\n                    \"{}: setting results name {!r} on {} expression \"\n                    \"that has no contained expression\".format(\n                        \"warn_name_set_on_empty_Forward\", name, type(self).__name__\n                    ),\n                    stacklevel=3,\n                )\n\n        return super()._setResultsName(name, list_all_matches)\n\n    ignoreWhitespace = ignore_whitespace\n    leaveWhitespace = leave_whitespace\n\n\nclass TokenConverter(ParseElementEnhance):\n    \"\"\"\n    Abstract subclass of :class:`ParseExpression`, for converting parsed results.\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str], savelist=False):\n        super().__init__(expr)  # , savelist)\n        self.saveAsList = False\n\n\nclass Combine(TokenConverter):\n    \"\"\"Converter to concatenate all matching tokens to a single string.\n    By default, the matching patterns must also be contiguous in the\n    input string; this can be disabled by specifying\n    ``'adjacent=False'`` in the constructor.\n\n    Example::\n\n        real = Word(nums) + '.' + Word(nums)\n        print(real.parse_string('3.1416')) # -> ['3', '.', '1416']\n        # will also erroneously match the following\n        print(real.parse_string('3. 1416')) # -> ['3', '.', '1416']\n\n        real = Combine(Word(nums) + '.' + Word(nums))\n        print(real.parse_string('3.1416')) # -> ['3.1416']\n        # no match when there are internal spaces\n        print(real.parse_string('3. 1416')) # -> Exception: Expected W:(0123...)\n    \"\"\"\n\n    def __init__(\n        self,\n        expr: ParserElement,\n        join_string: str = \"\",\n        adjacent: bool = True,\n        *,\n        joinString: typing.Optional[str] = None,\n    ):\n        super().__init__(expr)\n        joinString = joinString if joinString is not None else join_string\n        # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself\n        if adjacent:\n            self.leave_whitespace()\n        self.adjacent = adjacent\n        self.skipWhitespace = True\n        self.joinString = joinString\n        self.callPreparse = True\n\n    def ignore(self, other) -> ParserElement:\n        if self.adjacent:\n            ParserElement.ignore(self, other)\n        else:\n            super().ignore(other)\n        return self\n\n    def postParse(self, instring, loc, tokenlist):\n        retToks = tokenlist.copy()\n        del retToks[:]\n        retToks += ParseResults(\n            [\"\".join(tokenlist._asStringList(self.joinString))], modal=self.modalResults\n        )\n\n        if self.resultsName and retToks.haskeys():\n            return [retToks]\n        else:\n            return retToks\n\n\nclass Group(TokenConverter):\n    \"\"\"Converter to return the matched tokens as a list - useful for\n    returning tokens of :class:`ZeroOrMore` and :class:`OneOrMore` expressions.\n\n    The optional ``aslist`` argument when set to True will return the\n    parsed tokens as a Python list instead of a pyparsing ParseResults.\n\n    Example::\n\n        ident = Word(alphas)\n        num = Word(nums)\n        term = ident | num\n        func = ident + Opt(delimited_list(term))\n        print(func.parse_string(\"fn a, b, 100\"))\n        # -> ['fn', 'a', 'b', '100']\n\n        func = ident + Group(Opt(delimited_list(term)))\n        print(func.parse_string(\"fn a, b, 100\"))\n        # -> ['fn', ['a', 'b', '100']]\n    \"\"\"\n\n    def __init__(self, expr: ParserElement, aslist: bool = False):\n        super().__init__(expr)\n        self.saveAsList = True\n        self._asPythonList = aslist\n\n    def postParse(self, instring, loc, tokenlist):\n        if self._asPythonList:\n            return ParseResults.List(\n                tokenlist.asList()\n                if isinstance(tokenlist, ParseResults)\n                else list(tokenlist)\n            )\n        else:\n            return [tokenlist]\n\n\nclass Dict(TokenConverter):\n    \"\"\"Converter to return a repetitive expression as a list, but also\n    as a dictionary. Each element can also be referenced using the first\n    token in the expression as its key. Useful for tabular report\n    scraping when the first column can be used as a item key.\n\n    The optional ``asdict`` argument when set to True will return the\n    parsed tokens as a Python dict instead of a pyparsing ParseResults.\n\n    Example::\n\n        data_word = Word(alphas)\n        label = data_word + FollowedBy(':')\n\n        text = \"shape: SQUARE posn: upper left color: light blue texture: burlap\"\n        attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))\n\n        # print attributes as plain groups\n        print(attr_expr[1, ...].parse_string(text).dump())\n\n        # instead of OneOrMore(expr), parse using Dict(Group(expr)[1, ...]) - Dict will auto-assign names\n        result = Dict(Group(attr_expr)[1, ...]).parse_string(text)\n        print(result.dump())\n\n        # access named fields as dict entries, or output as dict\n        print(result['shape'])\n        print(result.as_dict())\n\n    prints::\n\n        ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap']\n        [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]\n        - color: 'light blue'\n        - posn: 'upper left'\n        - shape: 'SQUARE'\n        - texture: 'burlap'\n        SQUARE\n        {'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'}\n\n    See more examples at :class:`ParseResults` of accessing fields by results name.\n    \"\"\"\n\n    def __init__(self, expr: ParserElement, asdict: bool = False):\n        super().__init__(expr)\n        self.saveAsList = True\n        self._asPythonDict = asdict\n\n    def postParse(self, instring, loc, tokenlist):\n        for i, tok in enumerate(tokenlist):\n            if len(tok) == 0:\n                continue\n\n            ikey = tok[0]\n            if isinstance(ikey, int):\n                ikey = str(ikey).strip()\n\n            if len(tok) == 1:\n                tokenlist[ikey] = _ParseResultsWithOffset(\"\", i)\n\n            elif len(tok) == 2 and not isinstance(tok[1], ParseResults):\n                tokenlist[ikey] = _ParseResultsWithOffset(tok[1], i)\n\n            else:\n                try:\n                    dictvalue = tok.copy()  # ParseResults(i)\n                except Exception:\n                    exc = TypeError(\n                        \"could not extract dict values from parsed results\"\n                        \" - Dict expression must contain Grouped expressions\"\n                    )\n                    raise exc from None\n\n                del dictvalue[0]\n\n                if len(dictvalue) != 1 or (\n                    isinstance(dictvalue, ParseResults) and dictvalue.haskeys()\n                ):\n                    tokenlist[ikey] = _ParseResultsWithOffset(dictvalue, i)\n                else:\n                    tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0], i)\n\n        if self._asPythonDict:\n            return [tokenlist.as_dict()] if self.resultsName else tokenlist.as_dict()\n        else:\n            return [tokenlist] if self.resultsName else tokenlist\n\n\nclass Suppress(TokenConverter):\n    \"\"\"Converter for ignoring the results of a parsed expression.\n\n    Example::\n\n        source = \"a, b, c,d\"\n        wd = Word(alphas)\n        wd_list1 = wd + (',' + wd)[...]\n        print(wd_list1.parse_string(source))\n\n        # often, delimiters that are useful during parsing are just in the\n        # way afterward - use Suppress to keep them out of the parsed output\n        wd_list2 = wd + (Suppress(',') + wd)[...]\n        print(wd_list2.parse_string(source))\n\n        # Skipped text (using '...') can be suppressed as well\n        source = \"lead in START relevant text END trailing text\"\n        start_marker = Keyword(\"START\")\n        end_marker = Keyword(\"END\")\n        find_body = Suppress(...) + start_marker + ... + end_marker\n        print(find_body.parse_string(source)\n\n    prints::\n\n        ['a', ',', 'b', ',', 'c', ',', 'd']\n        ['a', 'b', 'c', 'd']\n        ['START', 'relevant text ', 'END']\n\n    (See also :class:`delimited_list`.)\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str], savelist: bool = False):\n        if expr is ...:\n            expr = _PendingSkip(NoMatch())\n        super().__init__(expr)\n\n    def __add__(self, other) -> \"ParserElement\":\n        if isinstance(self.expr, _PendingSkip):\n            return Suppress(SkipTo(other)) + other\n        else:\n            return super().__add__(other)\n\n    def __sub__(self, other) -> \"ParserElement\":\n        if isinstance(self.expr, _PendingSkip):\n            return Suppress(SkipTo(other)) - other\n        else:\n            return super().__sub__(other)\n\n    def postParse(self, instring, loc, tokenlist):\n        return []\n\n    def suppress(self) -> ParserElement:\n        return self\n\n\ndef trace_parse_action(f: ParseAction) -> ParseAction:\n    \"\"\"Decorator for debugging parse actions.\n\n    When the parse action is called, this decorator will print\n    ``\">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)\"``.\n    When the parse action completes, the decorator will print\n    ``\"<<\"`` followed by the returned value, or any exception that the parse action raised.\n\n    Example::\n\n        wd = Word(alphas)\n\n        @trace_parse_action\n        def remove_duplicate_chars(tokens):\n            return ''.join(sorted(set(''.join(tokens))))\n\n        wds = wd[1, ...].set_parse_action(remove_duplicate_chars)\n        print(wds.parse_string(\"slkdjs sld sldd sdlf sdljf\"))\n\n    prints::\n\n        >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {}))\n        <<leaving remove_duplicate_chars (ret: 'dfjkls')\n        ['dfjkls']\n    \"\"\"\n    f = _trim_arity(f)\n\n    def z(*paArgs):\n        thisFunc = f.__name__\n        s, l, t = paArgs[-3:]\n        if len(paArgs) > 3:\n            thisFunc = paArgs[0].__class__.__name__ + \".\" + thisFunc\n        sys.stderr.write(\n            \">>entering {}(line: {!r}, {}, {!r})\\n\".format(thisFunc, line(l, s), l, t)\n        )\n        try:\n            ret = f(*paArgs)\n        except Exception as exc:\n            sys.stderr.write(\"<<leaving {} (exception: {})\\n\".format(thisFunc, exc))\n            raise\n        sys.stderr.write(\"<<leaving {} (ret: {!r})\\n\".format(thisFunc, ret))\n        return ret\n\n    z.__name__ = f.__name__\n    return z\n\n\n# convenience constants for positional expressions\nempty = Empty().set_name(\"empty\")\nline_start = LineStart().set_name(\"line_start\")\nline_end = LineEnd().set_name(\"line_end\")\nstring_start = StringStart().set_name(\"string_start\")\nstring_end = StringEnd().set_name(\"string_end\")\n\n_escapedPunc = Word(_bslash, r\"\\[]-*.$+^?()~ \", exact=2).set_parse_action(\n    lambda s, l, t: t[0][1]\n)\n_escapedHexChar = Regex(r\"\\\\0?[xX][0-9a-fA-F]+\").set_parse_action(\n    lambda s, l, t: chr(int(t[0].lstrip(r\"\\0x\"), 16))\n)\n_escapedOctChar = Regex(r\"\\\\0[0-7]+\").set_parse_action(\n    lambda s, l, t: chr(int(t[0][1:], 8))\n)\n_singleChar = (\n    _escapedPunc | _escapedHexChar | _escapedOctChar | CharsNotIn(r\"\\]\", exact=1)\n)\n_charRange = Group(_singleChar + Suppress(\"-\") + _singleChar)\n_reBracketExpr = (\n    Literal(\"[\")\n    + Opt(\"^\").set_results_name(\"negate\")\n    + Group(OneOrMore(_charRange | _singleChar)).set_results_name(\"body\")\n    + \"]\"\n)\n\n\ndef srange(s: str) -> str:\n    r\"\"\"Helper to easily define string ranges for use in :class:`Word`\n    construction. Borrows syntax from regexp ``'[]'`` string range\n    definitions::\n\n        srange(\"[0-9]\")   -> \"0123456789\"\n        srange(\"[a-z]\")   -> \"abcdefghijklmnopqrstuvwxyz\"\n        srange(\"[a-z$_]\") -> \"abcdefghijklmnopqrstuvwxyz$_\"\n\n    The input string must be enclosed in []'s, and the returned string\n    is the expanded character set joined into a single string. The\n    values enclosed in the []'s may be:\n\n    - a single character\n    - an escaped character with a leading backslash (such as ``\\-``\n      or ``\\]``)\n    - an escaped hex character with a leading ``'\\x'``\n      (``\\x21``, which is a ``'!'`` character) (``\\0x##``\n      is also supported for backwards compatibility)\n    - an escaped octal character with a leading ``'\\0'``\n      (``\\041``, which is a ``'!'`` character)\n    - a range of any of the above, separated by a dash (``'a-z'``,\n      etc.)\n    - any combination of the above (``'aeiouy'``,\n      ``'a-zA-Z0-9_$'``, etc.)\n    \"\"\"\n    _expanded = (\n        lambda p: p\n        if not isinstance(p, ParseResults)\n        else \"\".join(chr(c) for c in range(ord(p[0]), ord(p[1]) + 1))\n    )\n    try:\n        return \"\".join(_expanded(part) for part in _reBracketExpr.parse_string(s).body)\n    except Exception:\n        return \"\"\n\n\ndef token_map(func, *args) -> ParseAction:\n    \"\"\"Helper to define a parse action by mapping a function to all\n    elements of a :class:`ParseResults` list. If any additional args are passed,\n    they are forwarded to the given function as additional arguments\n    after the token, as in\n    ``hex_integer = Word(hexnums).set_parse_action(token_map(int, 16))``,\n    which will convert the parsed data to an integer using base 16.\n\n    Example (compare the last to example in :class:`ParserElement.transform_string`::\n\n        hex_ints = Word(hexnums)[1, ...].set_parse_action(token_map(int, 16))\n        hex_ints.run_tests('''\n            00 11 22 aa FF 0a 0d 1a\n            ''')\n\n        upperword = Word(alphas).set_parse_action(token_map(str.upper))\n        upperword[1, ...].run_tests('''\n            my kingdom for a horse\n            ''')\n\n        wd = Word(alphas).set_parse_action(token_map(str.title))\n        wd[1, ...].set_parse_action(' '.join).run_tests('''\n            now is the winter of our discontent made glorious summer by this sun of york\n            ''')\n\n    prints::\n\n        00 11 22 aa FF 0a 0d 1a\n        [0, 17, 34, 170, 255, 10, 13, 26]\n\n        my kingdom for a horse\n        ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE']\n\n        now is the winter of our discontent made glorious summer by this sun of york\n        ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York']\n    \"\"\"\n\n    def pa(s, l, t):\n        return [func(tokn, *args) for tokn in t]\n\n    func_name = getattr(func, \"__name__\", getattr(func, \"__class__\").__name__)\n    pa.__name__ = func_name\n\n    return pa\n\n\ndef autoname_elements() -> None:\n    \"\"\"\n    Utility to simplify mass-naming of parser elements, for\n    generating railroad diagram with named subdiagrams.\n    \"\"\"\n    for name, var in sys._getframe().f_back.f_locals.items():\n        if isinstance(var, ParserElement) and not var.customName:\n            var.set_name(name)\n\n\ndbl_quoted_string = Combine(\n    Regex(r'\"(?:[^\"\\n\\r\\\\]|(?:\"\")|(?:\\\\(?:[^x]|x[0-9a-fA-F]+)))*') + '\"'\n).set_name(\"string enclosed in double quotes\")\n\nsgl_quoted_string = Combine(\n    Regex(r\"'(?:[^'\\n\\r\\\\]|(?:'')|(?:\\\\(?:[^x]|x[0-9a-fA-F]+)))*\") + \"'\"\n).set_name(\"string enclosed in single quotes\")\n\nquoted_string = Combine(\n    Regex(r'\"(?:[^\"\\n\\r\\\\]|(?:\"\")|(?:\\\\(?:[^x]|x[0-9a-fA-F]+)))*') + '\"'\n    | Regex(r\"'(?:[^'\\n\\r\\\\]|(?:'')|(?:\\\\(?:[^x]|x[0-9a-fA-F]+)))*\") + \"'\"\n).set_name(\"quotedString using single or double quotes\")\n\nunicode_string = Combine(\"u\" + quoted_string.copy()).set_name(\"unicode string literal\")\n\n\nalphas8bit = srange(r\"[\\0xc0-\\0xd6\\0xd8-\\0xf6\\0xf8-\\0xff]\")\npunc8bit = srange(r\"[\\0xa1-\\0xbf\\0xd7\\0xf7]\")\n\n# build list of built-in expressions, for future reference if a global default value\n# gets updated\n_builtin_exprs: List[ParserElement] = [\n    v for v in vars().values() if isinstance(v, ParserElement)\n]\n\n# backward compatibility names\ntokenMap = token_map\nconditionAsParseAction = condition_as_parse_action\nnullDebugAction = null_debug_action\nsglQuotedString = sgl_quoted_string\ndblQuotedString = dbl_quoted_string\nquotedString = quoted_string\nunicodeString = unicode_string\nlineStart = line_start\nlineEnd = line_end\nstringStart = string_start\nstringEnd = string_end\ntraceParseAction = trace_parse_action\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing/diagram/__init__.py",
    "content": "import railroad\nimport pyparsing\nimport typing\nfrom typing import (\n    List,\n    NamedTuple,\n    Generic,\n    TypeVar,\n    Dict,\n    Callable,\n    Set,\n    Iterable,\n)\nfrom jinja2 import Template\nfrom io import StringIO\nimport inspect\n\n\njinja2_template_source = \"\"\"\\\n<!DOCTYPE html>\n<html>\n<head>\n    {% if not head %}\n        <style type=\"text/css\">\n            .railroad-heading {\n                font-family: monospace;\n            }\n        </style>\n    {% else %}\n        {{ head | safe }}\n    {% endif %}\n</head>\n<body>\n{{ body | safe }}\n{% for diagram in diagrams %}\n    <div class=\"railroad-group\">\n        <h1 class=\"railroad-heading\">{{ diagram.title }}</h1>\n        <div class=\"railroad-description\">{{ diagram.text }}</div>\n        <div class=\"railroad-svg\">\n            {{ diagram.svg }}\n        </div>\n    </div>\n{% endfor %}\n</body>\n</html>\n\"\"\"\n\ntemplate = Template(jinja2_template_source)\n\n# Note: ideally this would be a dataclass, but we're supporting Python 3.5+ so we can't do this yet\nNamedDiagram = NamedTuple(\n    \"NamedDiagram\",\n    [(\"name\", str), (\"diagram\", typing.Optional[railroad.DiagramItem]), (\"index\", int)],\n)\n\"\"\"\nA simple structure for associating a name with a railroad diagram\n\"\"\"\n\nT = TypeVar(\"T\")\n\n\nclass EachItem(railroad.Group):\n    \"\"\"\n    Custom railroad item to compose a:\n    - Group containing a\n      - OneOrMore containing a\n        - Choice of the elements in the Each\n    with the group label indicating that all must be matched\n    \"\"\"\n\n    all_label = \"[ALL]\"\n\n    def __init__(self, *items):\n        choice_item = railroad.Choice(len(items) - 1, *items)\n        one_or_more_item = railroad.OneOrMore(item=choice_item)\n        super().__init__(one_or_more_item, label=self.all_label)\n\n\nclass AnnotatedItem(railroad.Group):\n    \"\"\"\n    Simple subclass of Group that creates an annotation label\n    \"\"\"\n\n    def __init__(self, label: str, item):\n        super().__init__(item=item, label=\"[{}]\".format(label) if label else label)\n\n\nclass EditablePartial(Generic[T]):\n    \"\"\"\n    Acts like a functools.partial, but can be edited. In other words, it represents a type that hasn't yet been\n    constructed.\n    \"\"\"\n\n    # We need this here because the railroad constructors actually transform the data, so can't be called until the\n    # entire tree is assembled\n\n    def __init__(self, func: Callable[..., T], args: list, kwargs: dict):\n        self.func = func\n        self.args = args\n        self.kwargs = kwargs\n\n    @classmethod\n    def from_call(cls, func: Callable[..., T], *args, **kwargs) -> \"EditablePartial[T]\":\n        \"\"\"\n        If you call this function in the same way that you would call the constructor, it will store the arguments\n        as you expect. For example EditablePartial.from_call(Fraction, 1, 3)() == Fraction(1, 3)\n        \"\"\"\n        return EditablePartial(func=func, args=list(args), kwargs=kwargs)\n\n    @property\n    def name(self):\n        return self.kwargs[\"name\"]\n\n    def __call__(self) -> T:\n        \"\"\"\n        Evaluate the partial and return the result\n        \"\"\"\n        args = self.args.copy()\n        kwargs = self.kwargs.copy()\n\n        # This is a helpful hack to allow you to specify varargs parameters (e.g. *args) as keyword args (e.g.\n        # args=['list', 'of', 'things'])\n        arg_spec = inspect.getfullargspec(self.func)\n        if arg_spec.varargs in self.kwargs:\n            args += kwargs.pop(arg_spec.varargs)\n\n        return self.func(*args, **kwargs)\n\n\ndef railroad_to_html(diagrams: List[NamedDiagram], **kwargs) -> str:\n    \"\"\"\n    Given a list of NamedDiagram, produce a single HTML string that visualises those diagrams\n    :params kwargs: kwargs to be passed in to the template\n    \"\"\"\n    data = []\n    for diagram in diagrams:\n        if diagram.diagram is None:\n            continue\n        io = StringIO()\n        diagram.diagram.writeSvg(io.write)\n        title = diagram.name\n        if diagram.index == 0:\n            title += \" (root)\"\n        data.append({\"title\": title, \"text\": \"\", \"svg\": io.getvalue()})\n\n    return template.render(diagrams=data, **kwargs)\n\n\ndef resolve_partial(partial: \"EditablePartial[T]\") -> T:\n    \"\"\"\n    Recursively resolves a collection of Partials into whatever type they are\n    \"\"\"\n    if isinstance(partial, EditablePartial):\n        partial.args = resolve_partial(partial.args)\n        partial.kwargs = resolve_partial(partial.kwargs)\n        return partial()\n    elif isinstance(partial, list):\n        return [resolve_partial(x) for x in partial]\n    elif isinstance(partial, dict):\n        return {key: resolve_partial(x) for key, x in partial.items()}\n    else:\n        return partial\n\n\ndef to_railroad(\n    element: pyparsing.ParserElement,\n    diagram_kwargs: typing.Optional[dict] = None,\n    vertical: int = 3,\n    show_results_names: bool = False,\n    show_groups: bool = False,\n) -> List[NamedDiagram]:\n    \"\"\"\n    Convert a pyparsing element tree into a list of diagrams. This is the recommended entrypoint to diagram\n    creation if you want to access the Railroad tree before it is converted to HTML\n    :param element: base element of the parser being diagrammed\n    :param diagram_kwargs: kwargs to pass to the Diagram() constructor\n    :param vertical: (optional) - int - limit at which number of alternatives should be\n       shown vertically instead of horizontally\n    :param show_results_names - bool to indicate whether results name annotations should be\n       included in the diagram\n    :param show_groups - bool to indicate whether groups should be highlighted with an unlabeled\n       surrounding box\n    \"\"\"\n    # Convert the whole tree underneath the root\n    lookup = ConverterState(diagram_kwargs=diagram_kwargs or {})\n    _to_diagram_element(\n        element,\n        lookup=lookup,\n        parent=None,\n        vertical=vertical,\n        show_results_names=show_results_names,\n        show_groups=show_groups,\n    )\n\n    root_id = id(element)\n    # Convert the root if it hasn't been already\n    if root_id in lookup:\n        if not element.customName:\n            lookup[root_id].name = \"\"\n        lookup[root_id].mark_for_extraction(root_id, lookup, force=True)\n\n    # Now that we're finished, we can convert from intermediate structures into Railroad elements\n    diags = list(lookup.diagrams.values())\n    if len(diags) > 1:\n        # collapse out duplicate diags with the same name\n        seen = set()\n        deduped_diags = []\n        for d in diags:\n            # don't extract SkipTo elements, they are uninformative as subdiagrams\n            if d.name == \"...\":\n                continue\n            if d.name is not None and d.name not in seen:\n                seen.add(d.name)\n                deduped_diags.append(d)\n        resolved = [resolve_partial(partial) for partial in deduped_diags]\n    else:\n        # special case - if just one diagram, always display it, even if\n        # it has no name\n        resolved = [resolve_partial(partial) for partial in diags]\n    return sorted(resolved, key=lambda diag: diag.index)\n\n\ndef _should_vertical(\n    specification: int, exprs: Iterable[pyparsing.ParserElement]\n) -> bool:\n    \"\"\"\n    Returns true if we should return a vertical list of elements\n    \"\"\"\n    if specification is None:\n        return False\n    else:\n        return len(_visible_exprs(exprs)) >= specification\n\n\nclass ElementState:\n    \"\"\"\n    State recorded for an individual pyparsing Element\n    \"\"\"\n\n    # Note: this should be a dataclass, but we have to support Python 3.5\n    def __init__(\n        self,\n        element: pyparsing.ParserElement,\n        converted: EditablePartial,\n        parent: EditablePartial,\n        number: int,\n        name: str = None,\n        parent_index: typing.Optional[int] = None,\n    ):\n        #: The pyparsing element that this represents\n        self.element: pyparsing.ParserElement = element\n        #: The name of the element\n        self.name: typing.Optional[str] = name\n        #: The output Railroad element in an unconverted state\n        self.converted: EditablePartial = converted\n        #: The parent Railroad element, which we store so that we can extract this if it's duplicated\n        self.parent: EditablePartial = parent\n        #: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram\n        self.number: int = number\n        #: The index of this inside its parent\n        self.parent_index: typing.Optional[int] = parent_index\n        #: If true, we should extract this out into a subdiagram\n        self.extract: bool = False\n        #: If true, all of this element's children have been filled out\n        self.complete: bool = False\n\n    def mark_for_extraction(\n        self, el_id: int, state: \"ConverterState\", name: str = None, force: bool = False\n    ):\n        \"\"\"\n        Called when this instance has been seen twice, and thus should eventually be extracted into a sub-diagram\n        :param el_id: id of the element\n        :param state: element/diagram state tracker\n        :param name: name to use for this element's text\n        :param force: If true, force extraction now, regardless of the state of this. Only useful for extracting the\n        root element when we know we're finished\n        \"\"\"\n        self.extract = True\n\n        # Set the name\n        if not self.name:\n            if name:\n                # Allow forcing a custom name\n                self.name = name\n            elif self.element.customName:\n                self.name = self.element.customName\n            else:\n                self.name = \"\"\n\n        # Just because this is marked for extraction doesn't mean we can do it yet. We may have to wait for children\n        # to be added\n        # Also, if this is just a string literal etc, don't bother extracting it\n        if force or (self.complete and _worth_extracting(self.element)):\n            state.extract_into_diagram(el_id)\n\n\nclass ConverterState:\n    \"\"\"\n    Stores some state that persists between recursions into the element tree\n    \"\"\"\n\n    def __init__(self, diagram_kwargs: typing.Optional[dict] = None):\n        #: A dictionary mapping ParserElements to state relating to them\n        self._element_diagram_states: Dict[int, ElementState] = {}\n        #: A dictionary mapping ParserElement IDs to subdiagrams generated from them\n        self.diagrams: Dict[int, EditablePartial[NamedDiagram]] = {}\n        #: The index of the next unnamed element\n        self.unnamed_index: int = 1\n        #: The index of the next element. This is used for sorting\n        self.index: int = 0\n        #: Shared kwargs that are used to customize the construction of diagrams\n        self.diagram_kwargs: dict = diagram_kwargs or {}\n        self.extracted_diagram_names: Set[str] = set()\n\n    def __setitem__(self, key: int, value: ElementState):\n        self._element_diagram_states[key] = value\n\n    def __getitem__(self, key: int) -> ElementState:\n        return self._element_diagram_states[key]\n\n    def __delitem__(self, key: int):\n        del self._element_diagram_states[key]\n\n    def __contains__(self, key: int):\n        return key in self._element_diagram_states\n\n    def generate_unnamed(self) -> int:\n        \"\"\"\n        Generate a number used in the name of an otherwise unnamed diagram\n        \"\"\"\n        self.unnamed_index += 1\n        return self.unnamed_index\n\n    def generate_index(self) -> int:\n        \"\"\"\n        Generate a number used to index a diagram\n        \"\"\"\n        self.index += 1\n        return self.index\n\n    def extract_into_diagram(self, el_id: int):\n        \"\"\"\n        Used when we encounter the same token twice in the same tree. When this\n        happens, we replace all instances of that token with a terminal, and\n        create a new subdiagram for the token\n        \"\"\"\n        position = self[el_id]\n\n        # Replace the original definition of this element with a regular block\n        if position.parent:\n            ret = EditablePartial.from_call(railroad.NonTerminal, text=position.name)\n            if \"item\" in position.parent.kwargs:\n                position.parent.kwargs[\"item\"] = ret\n            elif \"items\" in position.parent.kwargs:\n                position.parent.kwargs[\"items\"][position.parent_index] = ret\n\n        # If the element we're extracting is a group, skip to its content but keep the title\n        if position.converted.func == railroad.Group:\n            content = position.converted.kwargs[\"item\"]\n        else:\n            content = position.converted\n\n        self.diagrams[el_id] = EditablePartial.from_call(\n            NamedDiagram,\n            name=position.name,\n            diagram=EditablePartial.from_call(\n                railroad.Diagram, content, **self.diagram_kwargs\n            ),\n            index=position.number,\n        )\n\n        del self[el_id]\n\n\ndef _worth_extracting(element: pyparsing.ParserElement) -> bool:\n    \"\"\"\n    Returns true if this element is worth having its own sub-diagram. Simply, if any of its children\n    themselves have children, then its complex enough to extract\n    \"\"\"\n    children = element.recurse()\n    return any(child.recurse() for child in children)\n\n\ndef _apply_diagram_item_enhancements(fn):\n    \"\"\"\n    decorator to ensure enhancements to a diagram item (such as results name annotations)\n    get applied on return from _to_diagram_element (we do this since there are several\n    returns in _to_diagram_element)\n    \"\"\"\n\n    def _inner(\n        element: pyparsing.ParserElement,\n        parent: typing.Optional[EditablePartial],\n        lookup: ConverterState = None,\n        vertical: int = None,\n        index: int = 0,\n        name_hint: str = None,\n        show_results_names: bool = False,\n        show_groups: bool = False,\n    ) -> typing.Optional[EditablePartial]:\n\n        ret = fn(\n            element,\n            parent,\n            lookup,\n            vertical,\n            index,\n            name_hint,\n            show_results_names,\n            show_groups,\n        )\n\n        # apply annotation for results name, if present\n        if show_results_names and ret is not None:\n            element_results_name = element.resultsName\n            if element_results_name:\n                # add \"*\" to indicate if this is a \"list all results\" name\n                element_results_name += \"\" if element.modalResults else \"*\"\n                ret = EditablePartial.from_call(\n                    railroad.Group, item=ret, label=element_results_name\n                )\n\n        return ret\n\n    return _inner\n\n\ndef _visible_exprs(exprs: Iterable[pyparsing.ParserElement]):\n    non_diagramming_exprs = (\n        pyparsing.ParseElementEnhance,\n        pyparsing.PositionToken,\n        pyparsing.And._ErrorStop,\n    )\n    return [\n        e\n        for e in exprs\n        if not (e.customName or e.resultsName or isinstance(e, non_diagramming_exprs))\n    ]\n\n\n@_apply_diagram_item_enhancements\ndef _to_diagram_element(\n    element: pyparsing.ParserElement,\n    parent: typing.Optional[EditablePartial],\n    lookup: ConverterState = None,\n    vertical: int = None,\n    index: int = 0,\n    name_hint: str = None,\n    show_results_names: bool = False,\n    show_groups: bool = False,\n) -> typing.Optional[EditablePartial]:\n    \"\"\"\n    Recursively converts a PyParsing Element to a railroad Element\n    :param lookup: The shared converter state that keeps track of useful things\n    :param index: The index of this element within the parent\n    :param parent: The parent of this element in the output tree\n    :param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default),\n    it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never\n    do so\n    :param name_hint: If provided, this will override the generated name\n    :param show_results_names: bool flag indicating whether to add annotations for results names\n    :returns: The converted version of the input element, but as a Partial that hasn't yet been constructed\n    :param show_groups: bool flag indicating whether to show groups using bounding box\n    \"\"\"\n    exprs = element.recurse()\n    name = name_hint or element.customName or element.__class__.__name__\n\n    # Python's id() is used to provide a unique identifier for elements\n    el_id = id(element)\n\n    element_results_name = element.resultsName\n\n    # Here we basically bypass processing certain wrapper elements if they contribute nothing to the diagram\n    if not element.customName:\n        if isinstance(\n            element,\n            (\n                # pyparsing.TokenConverter,\n                # pyparsing.Forward,\n                pyparsing.Located,\n            ),\n        ):\n            # However, if this element has a useful custom name, and its child does not, we can pass it on to the child\n            if exprs:\n                if not exprs[0].customName:\n                    propagated_name = name\n                else:\n                    propagated_name = None\n\n                return _to_diagram_element(\n                    element.expr,\n                    parent=parent,\n                    lookup=lookup,\n                    vertical=vertical,\n                    index=index,\n                    name_hint=propagated_name,\n                    show_results_names=show_results_names,\n                    show_groups=show_groups,\n                )\n\n    # If the element isn't worth extracting, we always treat it as the first time we say it\n    if _worth_extracting(element):\n        if el_id in lookup:\n            # If we've seen this element exactly once before, we are only just now finding out that it's a duplicate,\n            # so we have to extract it into a new diagram.\n            looked_up = lookup[el_id]\n            looked_up.mark_for_extraction(el_id, lookup, name=name_hint)\n            ret = EditablePartial.from_call(railroad.NonTerminal, text=looked_up.name)\n            return ret\n\n        elif el_id in lookup.diagrams:\n            # If we have seen the element at least twice before, and have already extracted it into a subdiagram, we\n            # just put in a marker element that refers to the sub-diagram\n            ret = EditablePartial.from_call(\n                railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs[\"name\"]\n            )\n            return ret\n\n    # Recursively convert child elements\n    # Here we find the most relevant Railroad element for matching pyparsing Element\n    # We use ``items=[]`` here to hold the place for where the child elements will go once created\n    if isinstance(element, pyparsing.And):\n        # detect And's created with ``expr*N`` notation - for these use a OneOrMore with a repeat\n        # (all will have the same name, and resultsName)\n        if not exprs:\n            return None\n        if len(set((e.name, e.resultsName) for e in exprs)) == 1:\n            ret = EditablePartial.from_call(\n                railroad.OneOrMore, item=\"\", repeat=str(len(exprs))\n            )\n        elif _should_vertical(vertical, exprs):\n            ret = EditablePartial.from_call(railroad.Stack, items=[])\n        else:\n            ret = EditablePartial.from_call(railroad.Sequence, items=[])\n    elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)):\n        if not exprs:\n            return None\n        if _should_vertical(vertical, exprs):\n            ret = EditablePartial.from_call(railroad.Choice, 0, items=[])\n        else:\n            ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[])\n    elif isinstance(element, pyparsing.Each):\n        if not exprs:\n            return None\n        ret = EditablePartial.from_call(EachItem, items=[])\n    elif isinstance(element, pyparsing.NotAny):\n        ret = EditablePartial.from_call(AnnotatedItem, label=\"NOT\", item=\"\")\n    elif isinstance(element, pyparsing.FollowedBy):\n        ret = EditablePartial.from_call(AnnotatedItem, label=\"LOOKAHEAD\", item=\"\")\n    elif isinstance(element, pyparsing.PrecededBy):\n        ret = EditablePartial.from_call(AnnotatedItem, label=\"LOOKBEHIND\", item=\"\")\n    elif isinstance(element, pyparsing.Group):\n        if show_groups:\n            ret = EditablePartial.from_call(AnnotatedItem, label=\"\", item=\"\")\n        else:\n            ret = EditablePartial.from_call(railroad.Group, label=\"\", item=\"\")\n    elif isinstance(element, pyparsing.TokenConverter):\n        ret = EditablePartial.from_call(\n            AnnotatedItem, label=type(element).__name__.lower(), item=\"\"\n        )\n    elif isinstance(element, pyparsing.Opt):\n        ret = EditablePartial.from_call(railroad.Optional, item=\"\")\n    elif isinstance(element, pyparsing.OneOrMore):\n        ret = EditablePartial.from_call(railroad.OneOrMore, item=\"\")\n    elif isinstance(element, pyparsing.ZeroOrMore):\n        ret = EditablePartial.from_call(railroad.ZeroOrMore, item=\"\")\n    elif isinstance(element, pyparsing.Group):\n        ret = EditablePartial.from_call(\n            railroad.Group, item=None, label=element_results_name\n        )\n    elif isinstance(element, pyparsing.Empty) and not element.customName:\n        # Skip unnamed \"Empty\" elements\n        ret = None\n    elif len(exprs) > 1:\n        ret = EditablePartial.from_call(railroad.Sequence, items=[])\n    elif len(exprs) > 0 and not element_results_name:\n        ret = EditablePartial.from_call(railroad.Group, item=\"\", label=name)\n    else:\n        terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName)\n        ret = terminal\n\n    if ret is None:\n        return\n\n    # Indicate this element's position in the tree so we can extract it if necessary\n    lookup[el_id] = ElementState(\n        element=element,\n        converted=ret,\n        parent=parent,\n        parent_index=index,\n        number=lookup.generate_index(),\n    )\n    if element.customName:\n        lookup[el_id].mark_for_extraction(el_id, lookup, element.customName)\n\n    i = 0\n    for expr in exprs:\n        # Add a placeholder index in case we have to extract the child before we even add it to the parent\n        if \"items\" in ret.kwargs:\n            ret.kwargs[\"items\"].insert(i, None)\n\n        item = _to_diagram_element(\n            expr,\n            parent=ret,\n            lookup=lookup,\n            vertical=vertical,\n            index=i,\n            show_results_names=show_results_names,\n            show_groups=show_groups,\n        )\n\n        # Some elements don't need to be shown in the diagram\n        if item is not None:\n            if \"item\" in ret.kwargs:\n                ret.kwargs[\"item\"] = item\n            elif \"items\" in ret.kwargs:\n                # If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal\n                ret.kwargs[\"items\"][i] = item\n                i += 1\n        elif \"items\" in ret.kwargs:\n            # If we're supposed to skip this element, remove it from the parent\n            del ret.kwargs[\"items\"][i]\n\n    # If all this items children are none, skip this item\n    if ret and (\n        (\"items\" in ret.kwargs and len(ret.kwargs[\"items\"]) == 0)\n        or (\"item\" in ret.kwargs and ret.kwargs[\"item\"] is None)\n    ):\n        ret = EditablePartial.from_call(railroad.Terminal, name)\n\n    # Mark this element as \"complete\", ie it has all of its children\n    if el_id in lookup:\n        lookup[el_id].complete = True\n\n    if el_id in lookup and lookup[el_id].extract and lookup[el_id].complete:\n        lookup.extract_into_diagram(el_id)\n        if ret is not None:\n            ret = EditablePartial.from_call(\n                railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs[\"name\"]\n            )\n\n    return ret\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing/exceptions.py",
    "content": "# exceptions.py\n\nimport re\nimport sys\nimport typing\n\nfrom .util import col, line, lineno, _collapse_string_to_ranges\nfrom .unicode import pyparsing_unicode as ppu\n\n\nclass ExceptionWordUnicode(ppu.Latin1, ppu.LatinA, ppu.LatinB, ppu.Greek, ppu.Cyrillic):\n    pass\n\n\n_extract_alphanums = _collapse_string_to_ranges(ExceptionWordUnicode.alphanums)\n_exception_word_extractor = re.compile(\"([\" + _extract_alphanums + \"]{1,16})|.\")\n\n\nclass ParseBaseException(Exception):\n    \"\"\"base exception class for all parsing runtime exceptions\"\"\"\n\n    # Performance tuning: we construct a *lot* of these, so keep this\n    # constructor as small and fast as possible\n    def __init__(\n        self,\n        pstr: str,\n        loc: int = 0,\n        msg: typing.Optional[str] = None,\n        elem=None,\n    ):\n        self.loc = loc\n        if msg is None:\n            self.msg = pstr\n            self.pstr = \"\"\n        else:\n            self.msg = msg\n            self.pstr = pstr\n        self.parser_element = self.parserElement = elem\n        self.args = (pstr, loc, msg)\n\n    @staticmethod\n    def explain_exception(exc, depth=16):\n        \"\"\"\n        Method to take an exception and translate the Python internal traceback into a list\n        of the pyparsing expressions that caused the exception to be raised.\n\n        Parameters:\n\n        - exc - exception raised during parsing (need not be a ParseException, in support\n          of Python exceptions that might be raised in a parse action)\n        - depth (default=16) - number of levels back in the stack trace to list expression\n          and function names; if None, the full stack trace names will be listed; if 0, only\n          the failing input line, marker, and exception string will be shown\n\n        Returns a multi-line string listing the ParserElements and/or function names in the\n        exception's stack trace.\n        \"\"\"\n        import inspect\n        from .core import ParserElement\n\n        if depth is None:\n            depth = sys.getrecursionlimit()\n        ret = []\n        if isinstance(exc, ParseBaseException):\n            ret.append(exc.line)\n            ret.append(\" \" * (exc.column - 1) + \"^\")\n        ret.append(\"{}: {}\".format(type(exc).__name__, exc))\n\n        if depth > 0:\n            callers = inspect.getinnerframes(exc.__traceback__, context=depth)\n            seen = set()\n            for i, ff in enumerate(callers[-depth:]):\n                frm = ff[0]\n\n                f_self = frm.f_locals.get(\"self\", None)\n                if isinstance(f_self, ParserElement):\n                    if frm.f_code.co_name not in (\"parseImpl\", \"_parseNoCache\"):\n                        continue\n                    if id(f_self) in seen:\n                        continue\n                    seen.add(id(f_self))\n\n                    self_type = type(f_self)\n                    ret.append(\n                        \"{}.{} - {}\".format(\n                            self_type.__module__, self_type.__name__, f_self\n                        )\n                    )\n\n                elif f_self is not None:\n                    self_type = type(f_self)\n                    ret.append(\"{}.{}\".format(self_type.__module__, self_type.__name__))\n\n                else:\n                    code = frm.f_code\n                    if code.co_name in (\"wrapper\", \"<module>\"):\n                        continue\n\n                    ret.append(\"{}\".format(code.co_name))\n\n                depth -= 1\n                if not depth:\n                    break\n\n        return \"\\n\".join(ret)\n\n    @classmethod\n    def _from_exception(cls, pe):\n        \"\"\"\n        internal factory method to simplify creating one type of ParseException\n        from another - avoids having __init__ signature conflicts among subclasses\n        \"\"\"\n        return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)\n\n    @property\n    def line(self) -> str:\n        \"\"\"\n        Return the line of text where the exception occurred.\n        \"\"\"\n        return line(self.loc, self.pstr)\n\n    @property\n    def lineno(self) -> int:\n        \"\"\"\n        Return the 1-based line number of text where the exception occurred.\n        \"\"\"\n        return lineno(self.loc, self.pstr)\n\n    @property\n    def col(self) -> int:\n        \"\"\"\n        Return the 1-based column on the line of text where the exception occurred.\n        \"\"\"\n        return col(self.loc, self.pstr)\n\n    @property\n    def column(self) -> int:\n        \"\"\"\n        Return the 1-based column on the line of text where the exception occurred.\n        \"\"\"\n        return col(self.loc, self.pstr)\n\n    def __str__(self) -> str:\n        if self.pstr:\n            if self.loc >= len(self.pstr):\n                foundstr = \", found end of text\"\n            else:\n                # pull out next word at error location\n                found_match = _exception_word_extractor.match(self.pstr, self.loc)\n                if found_match is not None:\n                    found = found_match.group(0)\n                else:\n                    found = self.pstr[self.loc : self.loc + 1]\n                foundstr = (\", found %r\" % found).replace(r\"\\\\\", \"\\\\\")\n        else:\n            foundstr = \"\"\n        return \"{}{}  (at char {}), (line:{}, col:{})\".format(\n            self.msg, foundstr, self.loc, self.lineno, self.column\n        )\n\n    def __repr__(self):\n        return str(self)\n\n    def mark_input_line(self, marker_string: str = None, *, markerString=\">!<\") -> str:\n        \"\"\"\n        Extracts the exception line from the input string, and marks\n        the location of the exception with a special symbol.\n        \"\"\"\n        markerString = marker_string if marker_string is not None else markerString\n        line_str = self.line\n        line_column = self.column - 1\n        if markerString:\n            line_str = \"\".join(\n                (line_str[:line_column], markerString, line_str[line_column:])\n            )\n        return line_str.strip()\n\n    def explain(self, depth=16) -> str:\n        \"\"\"\n        Method to translate the Python internal traceback into a list\n        of the pyparsing expressions that caused the exception to be raised.\n\n        Parameters:\n\n        - depth (default=16) - number of levels back in the stack trace to list expression\n          and function names; if None, the full stack trace names will be listed; if 0, only\n          the failing input line, marker, and exception string will be shown\n\n        Returns a multi-line string listing the ParserElements and/or function names in the\n        exception's stack trace.\n\n        Example::\n\n            expr = pp.Word(pp.nums) * 3\n            try:\n                expr.parse_string(\"123 456 A789\")\n            except pp.ParseException as pe:\n                print(pe.explain(depth=0))\n\n        prints::\n\n            123 456 A789\n                    ^\n            ParseException: Expected W:(0-9), found 'A'  (at char 8), (line:1, col:9)\n\n        Note: the diagnostic output will include string representations of the expressions\n        that failed to parse. These representations will be more helpful if you use `set_name` to\n        give identifiable names to your expressions. Otherwise they will use the default string\n        forms, which may be cryptic to read.\n\n        Note: pyparsing's default truncation of exception tracebacks may also truncate the\n        stack of expressions that are displayed in the ``explain`` output. To get the full listing\n        of parser expressions, you may have to set ``ParserElement.verbose_stacktrace = True``\n        \"\"\"\n        return self.explain_exception(self, depth)\n\n    markInputline = mark_input_line\n\n\nclass ParseException(ParseBaseException):\n    \"\"\"\n    Exception thrown when a parse expression doesn't match the input string\n\n    Example::\n\n        try:\n            Word(nums).set_name(\"integer\").parse_string(\"ABC\")\n        except ParseException as pe:\n            print(pe)\n            print(\"column: {}\".format(pe.column))\n\n    prints::\n\n       Expected integer (at char 0), (line:1, col:1)\n        column: 1\n\n    \"\"\"\n\n\nclass ParseFatalException(ParseBaseException):\n    \"\"\"\n    User-throwable exception thrown when inconsistent parse content\n    is found; stops all parsing immediately\n    \"\"\"\n\n\nclass ParseSyntaxException(ParseFatalException):\n    \"\"\"\n    Just like :class:`ParseFatalException`, but thrown internally\n    when an :class:`ErrorStop<And._ErrorStop>` ('-' operator) indicates\n    that parsing is to stop immediately because an unbacktrackable\n    syntax error has been found.\n    \"\"\"\n\n\nclass RecursiveGrammarException(Exception):\n    \"\"\"\n    Exception thrown by :class:`ParserElement.validate` if the\n    grammar could be left-recursive; parser may need to enable\n    left recursion using :class:`ParserElement.enable_left_recursion<ParserElement.enable_left_recursion>`\n    \"\"\"\n\n    def __init__(self, parseElementList):\n        self.parseElementTrace = parseElementList\n\n    def __str__(self) -> str:\n        return \"RecursiveGrammarException: {}\".format(self.parseElementTrace)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing/helpers.py",
    "content": "# helpers.py\nimport html.entities\nimport re\nimport typing\n\nfrom . import __diag__\nfrom .core import *\nfrom .util import _bslash, _flatten, _escape_regex_range_chars\n\n\n#\n# global helpers\n#\ndef delimited_list(\n    expr: Union[str, ParserElement],\n    delim: Union[str, ParserElement] = \",\",\n    combine: bool = False,\n    min: typing.Optional[int] = None,\n    max: typing.Optional[int] = None,\n    *,\n    allow_trailing_delim: bool = False,\n) -> ParserElement:\n    \"\"\"Helper to define a delimited list of expressions - the delimiter\n    defaults to ','. By default, the list elements and delimiters can\n    have intervening whitespace, and comments, but this can be\n    overridden by passing ``combine=True`` in the constructor. If\n    ``combine`` is set to ``True``, the matching tokens are\n    returned as a single token string, with the delimiters included;\n    otherwise, the matching tokens are returned as a list of tokens,\n    with the delimiters suppressed.\n\n    If ``allow_trailing_delim`` is set to True, then the list may end with\n    a delimiter.\n\n    Example::\n\n        delimited_list(Word(alphas)).parse_string(\"aa,bb,cc\") # -> ['aa', 'bb', 'cc']\n        delimited_list(Word(hexnums), delim=':', combine=True).parse_string(\"AA:BB:CC:DD:EE\") # -> ['AA:BB:CC:DD:EE']\n    \"\"\"\n    if isinstance(expr, str_type):\n        expr = ParserElement._literalStringClass(expr)\n\n    dlName = \"{expr} [{delim} {expr}]...{end}\".format(\n        expr=str(expr.copy().streamline()),\n        delim=str(delim),\n        end=\" [{}]\".format(str(delim)) if allow_trailing_delim else \"\",\n    )\n\n    if not combine:\n        delim = Suppress(delim)\n\n    if min is not None:\n        if min < 1:\n            raise ValueError(\"min must be greater than 0\")\n        min -= 1\n    if max is not None:\n        if min is not None and max <= min:\n            raise ValueError(\"max must be greater than, or equal to min\")\n        max -= 1\n    delimited_list_expr = expr + (delim + expr)[min, max]\n\n    if allow_trailing_delim:\n        delimited_list_expr += Opt(delim)\n\n    if combine:\n        return Combine(delimited_list_expr).set_name(dlName)\n    else:\n        return delimited_list_expr.set_name(dlName)\n\n\ndef counted_array(\n    expr: ParserElement,\n    int_expr: typing.Optional[ParserElement] = None,\n    *,\n    intExpr: typing.Optional[ParserElement] = None,\n) -> ParserElement:\n    \"\"\"Helper to define a counted list of expressions.\n\n    This helper defines a pattern of the form::\n\n        integer expr expr expr...\n\n    where the leading integer tells how many expr expressions follow.\n    The matched tokens returns the array of expr tokens as a list - the\n    leading count token is suppressed.\n\n    If ``int_expr`` is specified, it should be a pyparsing expression\n    that produces an integer value.\n\n    Example::\n\n        counted_array(Word(alphas)).parse_string('2 ab cd ef')  # -> ['ab', 'cd']\n\n        # in this parser, the leading integer value is given in binary,\n        # '10' indicating that 2 values are in the array\n        binary_constant = Word('01').set_parse_action(lambda t: int(t[0], 2))\n        counted_array(Word(alphas), int_expr=binary_constant).parse_string('10 ab cd ef')  # -> ['ab', 'cd']\n\n        # if other fields must be parsed after the count but before the\n        # list items, give the fields results names and they will\n        # be preserved in the returned ParseResults:\n        count_with_metadata = integer + Word(alphas)(\"type\")\n        typed_array = counted_array(Word(alphanums), int_expr=count_with_metadata)(\"items\")\n        result = typed_array.parse_string(\"3 bool True True False\")\n        print(result.dump())\n\n        # prints\n        # ['True', 'True', 'False']\n        # - items: ['True', 'True', 'False']\n        # - type: 'bool'\n    \"\"\"\n    intExpr = intExpr or int_expr\n    array_expr = Forward()\n\n    def count_field_parse_action(s, l, t):\n        nonlocal array_expr\n        n = t[0]\n        array_expr <<= (expr * n) if n else Empty()\n        # clear list contents, but keep any named results\n        del t[:]\n\n    if intExpr is None:\n        intExpr = Word(nums).set_parse_action(lambda t: int(t[0]))\n    else:\n        intExpr = intExpr.copy()\n    intExpr.set_name(\"arrayLen\")\n    intExpr.add_parse_action(count_field_parse_action, call_during_try=True)\n    return (intExpr + array_expr).set_name(\"(len) \" + str(expr) + \"...\")\n\n\ndef match_previous_literal(expr: ParserElement) -> ParserElement:\n    \"\"\"Helper to define an expression that is indirectly defined from\n    the tokens matched in a previous expression, that is, it looks for\n    a 'repeat' of a previous expression.  For example::\n\n        first = Word(nums)\n        second = match_previous_literal(first)\n        match_expr = first + \":\" + second\n\n    will match ``\"1:1\"``, but not ``\"1:2\"``.  Because this\n    matches a previous literal, will also match the leading\n    ``\"1:1\"`` in ``\"1:10\"``. If this is not desired, use\n    :class:`match_previous_expr`. Do *not* use with packrat parsing\n    enabled.\n    \"\"\"\n    rep = Forward()\n\n    def copy_token_to_repeater(s, l, t):\n        if t:\n            if len(t) == 1:\n                rep << t[0]\n            else:\n                # flatten t tokens\n                tflat = _flatten(t.as_list())\n                rep << And(Literal(tt) for tt in tflat)\n        else:\n            rep << Empty()\n\n    expr.add_parse_action(copy_token_to_repeater, callDuringTry=True)\n    rep.set_name(\"(prev) \" + str(expr))\n    return rep\n\n\ndef match_previous_expr(expr: ParserElement) -> ParserElement:\n    \"\"\"Helper to define an expression that is indirectly defined from\n    the tokens matched in a previous expression, that is, it looks for\n    a 'repeat' of a previous expression.  For example::\n\n        first = Word(nums)\n        second = match_previous_expr(first)\n        match_expr = first + \":\" + second\n\n    will match ``\"1:1\"``, but not ``\"1:2\"``.  Because this\n    matches by expressions, will *not* match the leading ``\"1:1\"``\n    in ``\"1:10\"``; the expressions are evaluated first, and then\n    compared, so ``\"1\"`` is compared with ``\"10\"``. Do *not* use\n    with packrat parsing enabled.\n    \"\"\"\n    rep = Forward()\n    e2 = expr.copy()\n    rep <<= e2\n\n    def copy_token_to_repeater(s, l, t):\n        matchTokens = _flatten(t.as_list())\n\n        def must_match_these_tokens(s, l, t):\n            theseTokens = _flatten(t.as_list())\n            if theseTokens != matchTokens:\n                raise ParseException(\n                    s, l, \"Expected {}, found{}\".format(matchTokens, theseTokens)\n                )\n\n        rep.set_parse_action(must_match_these_tokens, callDuringTry=True)\n\n    expr.add_parse_action(copy_token_to_repeater, callDuringTry=True)\n    rep.set_name(\"(prev) \" + str(expr))\n    return rep\n\n\ndef one_of(\n    strs: Union[typing.Iterable[str], str],\n    caseless: bool = False,\n    use_regex: bool = True,\n    as_keyword: bool = False,\n    *,\n    useRegex: bool = True,\n    asKeyword: bool = False,\n) -> ParserElement:\n    \"\"\"Helper to quickly define a set of alternative :class:`Literal` s,\n    and makes sure to do longest-first testing when there is a conflict,\n    regardless of the input order, but returns\n    a :class:`MatchFirst` for best performance.\n\n    Parameters:\n\n    - ``strs`` - a string of space-delimited literals, or a collection of\n      string literals\n    - ``caseless`` - treat all literals as caseless - (default= ``False``)\n    - ``use_regex`` - as an optimization, will\n      generate a :class:`Regex` object; otherwise, will generate\n      a :class:`MatchFirst` object (if ``caseless=True`` or ``asKeyword=True``, or if\n      creating a :class:`Regex` raises an exception) - (default= ``True``)\n    - ``as_keyword`` - enforce :class:`Keyword`-style matching on the\n      generated expressions - (default= ``False``)\n    - ``asKeyword`` and ``useRegex`` are retained for pre-PEP8 compatibility,\n      but will be removed in a future release\n\n    Example::\n\n        comp_oper = one_of(\"< = > <= >= !=\")\n        var = Word(alphas)\n        number = Word(nums)\n        term = var | number\n        comparison_expr = term + comp_oper + term\n        print(comparison_expr.search_string(\"B = 12  AA=23 B<=AA AA>12\"))\n\n    prints::\n\n        [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']]\n    \"\"\"\n    asKeyword = asKeyword or as_keyword\n    useRegex = useRegex and use_regex\n\n    if (\n        isinstance(caseless, str_type)\n        and __diag__.warn_on_multiple_string_args_to_oneof\n    ):\n        warnings.warn(\n            \"More than one string argument passed to one_of, pass\"\n            \" choices as a list or space-delimited string\",\n            stacklevel=2,\n        )\n\n    if caseless:\n        isequal = lambda a, b: a.upper() == b.upper()\n        masks = lambda a, b: b.upper().startswith(a.upper())\n        parseElementClass = CaselessKeyword if asKeyword else CaselessLiteral\n    else:\n        isequal = lambda a, b: a == b\n        masks = lambda a, b: b.startswith(a)\n        parseElementClass = Keyword if asKeyword else Literal\n\n    symbols: List[str] = []\n    if isinstance(strs, str_type):\n        symbols = strs.split()\n    elif isinstance(strs, Iterable):\n        symbols = list(strs)\n    else:\n        raise TypeError(\"Invalid argument to one_of, expected string or iterable\")\n    if not symbols:\n        return NoMatch()\n\n    # reorder given symbols to take care to avoid masking longer choices with shorter ones\n    # (but only if the given symbols are not just single characters)\n    if any(len(sym) > 1 for sym in symbols):\n        i = 0\n        while i < len(symbols) - 1:\n            cur = symbols[i]\n            for j, other in enumerate(symbols[i + 1 :]):\n                if isequal(other, cur):\n                    del symbols[i + j + 1]\n                    break\n                elif masks(cur, other):\n                    del symbols[i + j + 1]\n                    symbols.insert(i, other)\n                    break\n            else:\n                i += 1\n\n    if useRegex:\n        re_flags: int = re.IGNORECASE if caseless else 0\n\n        try:\n            if all(len(sym) == 1 for sym in symbols):\n                # symbols are just single characters, create range regex pattern\n                patt = \"[{}]\".format(\n                    \"\".join(_escape_regex_range_chars(sym) for sym in symbols)\n                )\n            else:\n                patt = \"|\".join(re.escape(sym) for sym in symbols)\n\n            # wrap with \\b word break markers if defining as keywords\n            if asKeyword:\n                patt = r\"\\b(?:{})\\b\".format(patt)\n\n            ret = Regex(patt, flags=re_flags).set_name(\" | \".join(symbols))\n\n            if caseless:\n                # add parse action to return symbols as specified, not in random\n                # casing as found in input string\n                symbol_map = {sym.lower(): sym for sym in symbols}\n                ret.add_parse_action(lambda s, l, t: symbol_map[t[0].lower()])\n\n            return ret\n\n        except re.error:\n            warnings.warn(\n                \"Exception creating Regex for one_of, building MatchFirst\", stacklevel=2\n            )\n\n    # last resort, just use MatchFirst\n    return MatchFirst(parseElementClass(sym) for sym in symbols).set_name(\n        \" | \".join(symbols)\n    )\n\n\ndef dict_of(key: ParserElement, value: ParserElement) -> ParserElement:\n    \"\"\"Helper to easily and clearly define a dictionary by specifying\n    the respective patterns for the key and value.  Takes care of\n    defining the :class:`Dict`, :class:`ZeroOrMore`, and\n    :class:`Group` tokens in the proper order.  The key pattern\n    can include delimiting markers or punctuation, as long as they are\n    suppressed, thereby leaving the significant key text.  The value\n    pattern can include named results, so that the :class:`Dict` results\n    can include named token fields.\n\n    Example::\n\n        text = \"shape: SQUARE posn: upper left color: light blue texture: burlap\"\n        attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))\n        print(attr_expr[1, ...].parse_string(text).dump())\n\n        attr_label = label\n        attr_value = Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)\n\n        # similar to Dict, but simpler call format\n        result = dict_of(attr_label, attr_value).parse_string(text)\n        print(result.dump())\n        print(result['shape'])\n        print(result.shape)  # object attribute access works too\n        print(result.as_dict())\n\n    prints::\n\n        [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]\n        - color: 'light blue'\n        - posn: 'upper left'\n        - shape: 'SQUARE'\n        - texture: 'burlap'\n        SQUARE\n        SQUARE\n        {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}\n    \"\"\"\n    return Dict(OneOrMore(Group(key + value)))\n\n\ndef original_text_for(\n    expr: ParserElement, as_string: bool = True, *, asString: bool = True\n) -> ParserElement:\n    \"\"\"Helper to return the original, untokenized text for a given\n    expression.  Useful to restore the parsed fields of an HTML start\n    tag into the raw tag text itself, or to revert separate tokens with\n    intervening whitespace back to the original matching input text. By\n    default, returns astring containing the original parsed text.\n\n    If the optional ``as_string`` argument is passed as\n    ``False``, then the return value is\n    a :class:`ParseResults` containing any results names that\n    were originally matched, and a single token containing the original\n    matched text from the input string.  So if the expression passed to\n    :class:`original_text_for` contains expressions with defined\n    results names, you must set ``as_string`` to ``False`` if you\n    want to preserve those results name values.\n\n    The ``asString`` pre-PEP8 argument is retained for compatibility,\n    but will be removed in a future release.\n\n    Example::\n\n        src = \"this is test <b> bold <i>text</i> </b> normal text \"\n        for tag in (\"b\", \"i\"):\n            opener, closer = make_html_tags(tag)\n            patt = original_text_for(opener + SkipTo(closer) + closer)\n            print(patt.search_string(src)[0])\n\n    prints::\n\n        ['<b> bold <i>text</i> </b>']\n        ['<i>text</i>']\n    \"\"\"\n    asString = asString and as_string\n\n    locMarker = Empty().set_parse_action(lambda s, loc, t: loc)\n    endlocMarker = locMarker.copy()\n    endlocMarker.callPreparse = False\n    matchExpr = locMarker(\"_original_start\") + expr + endlocMarker(\"_original_end\")\n    if asString:\n        extractText = lambda s, l, t: s[t._original_start : t._original_end]\n    else:\n\n        def extractText(s, l, t):\n            t[:] = [s[t.pop(\"_original_start\") : t.pop(\"_original_end\")]]\n\n    matchExpr.set_parse_action(extractText)\n    matchExpr.ignoreExprs = expr.ignoreExprs\n    matchExpr.suppress_warning(Diagnostics.warn_ungrouped_named_tokens_in_collection)\n    return matchExpr\n\n\ndef ungroup(expr: ParserElement) -> ParserElement:\n    \"\"\"Helper to undo pyparsing's default grouping of And expressions,\n    even if all but one are non-empty.\n    \"\"\"\n    return TokenConverter(expr).add_parse_action(lambda t: t[0])\n\n\ndef locatedExpr(expr: ParserElement) -> ParserElement:\n    \"\"\"\n    (DEPRECATED - future code should use the Located class)\n    Helper to decorate a returned token with its starting and ending\n    locations in the input string.\n\n    This helper adds the following results names:\n\n    - ``locn_start`` - location where matched expression begins\n    - ``locn_end`` - location where matched expression ends\n    - ``value`` - the actual parsed results\n\n    Be careful if the input text contains ``<TAB>`` characters, you\n    may want to call :class:`ParserElement.parseWithTabs`\n\n    Example::\n\n        wd = Word(alphas)\n        for match in locatedExpr(wd).searchString(\"ljsdf123lksdjjf123lkkjj1222\"):\n            print(match)\n\n    prints::\n\n        [[0, 'ljsdf', 5]]\n        [[8, 'lksdjjf', 15]]\n        [[18, 'lkkjj', 23]]\n    \"\"\"\n    locator = Empty().set_parse_action(lambda ss, ll, tt: ll)\n    return Group(\n        locator(\"locn_start\")\n        + expr(\"value\")\n        + locator.copy().leaveWhitespace()(\"locn_end\")\n    )\n\n\ndef nested_expr(\n    opener: Union[str, ParserElement] = \"(\",\n    closer: Union[str, ParserElement] = \")\",\n    content: typing.Optional[ParserElement] = None,\n    ignore_expr: ParserElement = quoted_string(),\n    *,\n    ignoreExpr: ParserElement = quoted_string(),\n) -> ParserElement:\n    \"\"\"Helper method for defining nested lists enclosed in opening and\n    closing delimiters (``\"(\"`` and ``\")\"`` are the default).\n\n    Parameters:\n    - ``opener`` - opening character for a nested list\n      (default= ``\"(\"``); can also be a pyparsing expression\n    - ``closer`` - closing character for a nested list\n      (default= ``\")\"``); can also be a pyparsing expression\n    - ``content`` - expression for items within the nested lists\n      (default= ``None``)\n    - ``ignore_expr`` - expression for ignoring opening and closing delimiters\n      (default= :class:`quoted_string`)\n    - ``ignoreExpr`` - this pre-PEP8 argument is retained for compatibility\n      but will be removed in a future release\n\n    If an expression is not provided for the content argument, the\n    nested expression will capture all whitespace-delimited content\n    between delimiters as a list of separate values.\n\n    Use the ``ignore_expr`` argument to define expressions that may\n    contain opening or closing characters that should not be treated as\n    opening or closing characters for nesting, such as quoted_string or\n    a comment expression.  Specify multiple expressions using an\n    :class:`Or` or :class:`MatchFirst`. The default is\n    :class:`quoted_string`, but if no expressions are to be ignored, then\n    pass ``None`` for this argument.\n\n    Example::\n\n        data_type = one_of(\"void int short long char float double\")\n        decl_data_type = Combine(data_type + Opt(Word('*')))\n        ident = Word(alphas+'_', alphanums+'_')\n        number = pyparsing_common.number\n        arg = Group(decl_data_type + ident)\n        LPAR, RPAR = map(Suppress, \"()\")\n\n        code_body = nested_expr('{', '}', ignore_expr=(quoted_string | c_style_comment))\n\n        c_function = (decl_data_type(\"type\")\n                      + ident(\"name\")\n                      + LPAR + Opt(delimited_list(arg), [])(\"args\") + RPAR\n                      + code_body(\"body\"))\n        c_function.ignore(c_style_comment)\n\n        source_code = '''\n            int is_odd(int x) {\n                return (x%2);\n            }\n\n            int dec_to_hex(char hchar) {\n                if (hchar >= '0' && hchar <= '9') {\n                    return (ord(hchar)-ord('0'));\n                } else {\n                    return (10+ord(hchar)-ord('A'));\n                }\n            }\n        '''\n        for func in c_function.search_string(source_code):\n            print(\"%(name)s (%(type)s) args: %(args)s\" % func)\n\n\n    prints::\n\n        is_odd (int) args: [['int', 'x']]\n        dec_to_hex (int) args: [['char', 'hchar']]\n    \"\"\"\n    if ignoreExpr != ignore_expr:\n        ignoreExpr = ignore_expr if ignoreExpr == quoted_string() else ignoreExpr\n    if opener == closer:\n        raise ValueError(\"opening and closing strings cannot be the same\")\n    if content is None:\n        if isinstance(opener, str_type) and isinstance(closer, str_type):\n            if len(opener) == 1 and len(closer) == 1:\n                if ignoreExpr is not None:\n                    content = Combine(\n                        OneOrMore(\n                            ~ignoreExpr\n                            + CharsNotIn(\n                                opener + closer + ParserElement.DEFAULT_WHITE_CHARS,\n                                exact=1,\n                            )\n                        )\n                    ).set_parse_action(lambda t: t[0].strip())\n                else:\n                    content = empty.copy() + CharsNotIn(\n                        opener + closer + ParserElement.DEFAULT_WHITE_CHARS\n                    ).set_parse_action(lambda t: t[0].strip())\n            else:\n                if ignoreExpr is not None:\n                    content = Combine(\n                        OneOrMore(\n                            ~ignoreExpr\n                            + ~Literal(opener)\n                            + ~Literal(closer)\n                            + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1)\n                        )\n                    ).set_parse_action(lambda t: t[0].strip())\n                else:\n                    content = Combine(\n                        OneOrMore(\n                            ~Literal(opener)\n                            + ~Literal(closer)\n                            + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1)\n                        )\n                    ).set_parse_action(lambda t: t[0].strip())\n        else:\n            raise ValueError(\n                \"opening and closing arguments must be strings if no content expression is given\"\n            )\n    ret = Forward()\n    if ignoreExpr is not None:\n        ret <<= Group(\n            Suppress(opener) + ZeroOrMore(ignoreExpr | ret | content) + Suppress(closer)\n        )\n    else:\n        ret <<= Group(Suppress(opener) + ZeroOrMore(ret | content) + Suppress(closer))\n    ret.set_name(\"nested %s%s expression\" % (opener, closer))\n    return ret\n\n\ndef _makeTags(tagStr, xml, suppress_LT=Suppress(\"<\"), suppress_GT=Suppress(\">\")):\n    \"\"\"Internal helper to construct opening and closing tag expressions, given a tag name\"\"\"\n    if isinstance(tagStr, str_type):\n        resname = tagStr\n        tagStr = Keyword(tagStr, caseless=not xml)\n    else:\n        resname = tagStr.name\n\n    tagAttrName = Word(alphas, alphanums + \"_-:\")\n    if xml:\n        tagAttrValue = dbl_quoted_string.copy().set_parse_action(remove_quotes)\n        openTag = (\n            suppress_LT\n            + tagStr(\"tag\")\n            + Dict(ZeroOrMore(Group(tagAttrName + Suppress(\"=\") + tagAttrValue)))\n            + Opt(\"/\", default=[False])(\"empty\").set_parse_action(\n                lambda s, l, t: t[0] == \"/\"\n            )\n            + suppress_GT\n        )\n    else:\n        tagAttrValue = quoted_string.copy().set_parse_action(remove_quotes) | Word(\n            printables, exclude_chars=\">\"\n        )\n        openTag = (\n            suppress_LT\n            + tagStr(\"tag\")\n            + Dict(\n                ZeroOrMore(\n                    Group(\n                        tagAttrName.set_parse_action(lambda t: t[0].lower())\n                        + Opt(Suppress(\"=\") + tagAttrValue)\n                    )\n                )\n            )\n            + Opt(\"/\", default=[False])(\"empty\").set_parse_action(\n                lambda s, l, t: t[0] == \"/\"\n            )\n            + suppress_GT\n        )\n    closeTag = Combine(Literal(\"</\") + tagStr + \">\", adjacent=False)\n\n    openTag.set_name(\"<%s>\" % resname)\n    # add start<tagname> results name in parse action now that ungrouped names are not reported at two levels\n    openTag.add_parse_action(\n        lambda t: t.__setitem__(\n            \"start\" + \"\".join(resname.replace(\":\", \" \").title().split()), t.copy()\n        )\n    )\n    closeTag = closeTag(\n        \"end\" + \"\".join(resname.replace(\":\", \" \").title().split())\n    ).set_name(\"</%s>\" % resname)\n    openTag.tag = resname\n    closeTag.tag = resname\n    openTag.tag_body = SkipTo(closeTag())\n    return openTag, closeTag\n\n\ndef make_html_tags(\n    tag_str: Union[str, ParserElement]\n) -> Tuple[ParserElement, ParserElement]:\n    \"\"\"Helper to construct opening and closing tag expressions for HTML,\n    given a tag name. Matches tags in either upper or lower case,\n    attributes with namespaces and with quoted or unquoted values.\n\n    Example::\n\n        text = '<td>More info at the <a href=\"https://github.com/pyparsing/pyparsing/wiki\">pyparsing</a> wiki page</td>'\n        # make_html_tags returns pyparsing expressions for the opening and\n        # closing tags as a 2-tuple\n        a, a_end = make_html_tags(\"A\")\n        link_expr = a + SkipTo(a_end)(\"link_text\") + a_end\n\n        for link in link_expr.search_string(text):\n            # attributes in the <A> tag (like \"href\" shown here) are\n            # also accessible as named results\n            print(link.link_text, '->', link.href)\n\n    prints::\n\n        pyparsing -> https://github.com/pyparsing/pyparsing/wiki\n    \"\"\"\n    return _makeTags(tag_str, False)\n\n\ndef make_xml_tags(\n    tag_str: Union[str, ParserElement]\n) -> Tuple[ParserElement, ParserElement]:\n    \"\"\"Helper to construct opening and closing tag expressions for XML,\n    given a tag name. Matches tags only in the given upper/lower case.\n\n    Example: similar to :class:`make_html_tags`\n    \"\"\"\n    return _makeTags(tag_str, True)\n\n\nany_open_tag: ParserElement\nany_close_tag: ParserElement\nany_open_tag, any_close_tag = make_html_tags(\n    Word(alphas, alphanums + \"_:\").set_name(\"any tag\")\n)\n\n_htmlEntityMap = {k.rstrip(\";\"): v for k, v in html.entities.html5.items()}\ncommon_html_entity = Regex(\"&(?P<entity>\" + \"|\".join(_htmlEntityMap) + \");\").set_name(\n    \"common HTML entity\"\n)\n\n\ndef replace_html_entity(t):\n    \"\"\"Helper parser action to replace common HTML entities with their special characters\"\"\"\n    return _htmlEntityMap.get(t.entity)\n\n\nclass OpAssoc(Enum):\n    LEFT = 1\n    RIGHT = 2\n\n\nInfixNotationOperatorArgType = Union[\n    ParserElement, str, Tuple[Union[ParserElement, str], Union[ParserElement, str]]\n]\nInfixNotationOperatorSpec = Union[\n    Tuple[\n        InfixNotationOperatorArgType,\n        int,\n        OpAssoc,\n        typing.Optional[ParseAction],\n    ],\n    Tuple[\n        InfixNotationOperatorArgType,\n        int,\n        OpAssoc,\n    ],\n]\n\n\ndef infix_notation(\n    base_expr: ParserElement,\n    op_list: List[InfixNotationOperatorSpec],\n    lpar: Union[str, ParserElement] = Suppress(\"(\"),\n    rpar: Union[str, ParserElement] = Suppress(\")\"),\n) -> ParserElement:\n    \"\"\"Helper method for constructing grammars of expressions made up of\n    operators working in a precedence hierarchy.  Operators may be unary\n    or binary, left- or right-associative.  Parse actions can also be\n    attached to operator expressions. The generated parser will also\n    recognize the use of parentheses to override operator precedences\n    (see example below).\n\n    Note: if you define a deep operator list, you may see performance\n    issues when using infix_notation. See\n    :class:`ParserElement.enable_packrat` for a mechanism to potentially\n    improve your parser performance.\n\n    Parameters:\n    - ``base_expr`` - expression representing the most basic operand to\n      be used in the expression\n    - ``op_list`` - list of tuples, one for each operator precedence level\n      in the expression grammar; each tuple is of the form ``(op_expr,\n      num_operands, right_left_assoc, (optional)parse_action)``, where:\n\n      - ``op_expr`` is the pyparsing expression for the operator; may also\n        be a string, which will be converted to a Literal; if ``num_operands``\n        is 3, ``op_expr`` is a tuple of two expressions, for the two\n        operators separating the 3 terms\n      - ``num_operands`` is the number of terms for this operator (must be 1,\n        2, or 3)\n      - ``right_left_assoc`` is the indicator whether the operator is right\n        or left associative, using the pyparsing-defined constants\n        ``OpAssoc.RIGHT`` and ``OpAssoc.LEFT``.\n      - ``parse_action`` is the parse action to be associated with\n        expressions matching this operator expression (the parse action\n        tuple member may be omitted); if the parse action is passed\n        a tuple or list of functions, this is equivalent to calling\n        ``set_parse_action(*fn)``\n        (:class:`ParserElement.set_parse_action`)\n    - ``lpar`` - expression for matching left-parentheses; if passed as a\n      str, then will be parsed as Suppress(lpar). If lpar is passed as\n      an expression (such as ``Literal('(')``), then it will be kept in\n      the parsed results, and grouped with them. (default= ``Suppress('(')``)\n    - ``rpar`` - expression for matching right-parentheses; if passed as a\n      str, then will be parsed as Suppress(rpar). If rpar is passed as\n      an expression (such as ``Literal(')')``), then it will be kept in\n      the parsed results, and grouped with them. (default= ``Suppress(')')``)\n\n    Example::\n\n        # simple example of four-function arithmetic with ints and\n        # variable names\n        integer = pyparsing_common.signed_integer\n        varname = pyparsing_common.identifier\n\n        arith_expr = infix_notation(integer | varname,\n            [\n            ('-', 1, OpAssoc.RIGHT),\n            (one_of('* /'), 2, OpAssoc.LEFT),\n            (one_of('+ -'), 2, OpAssoc.LEFT),\n            ])\n\n        arith_expr.run_tests('''\n            5+3*6\n            (5+3)*6\n            -2--11\n            ''', full_dump=False)\n\n    prints::\n\n        5+3*6\n        [[5, '+', [3, '*', 6]]]\n\n        (5+3)*6\n        [[[5, '+', 3], '*', 6]]\n\n        -2--11\n        [[['-', 2], '-', ['-', 11]]]\n    \"\"\"\n    # captive version of FollowedBy that does not do parse actions or capture results names\n    class _FB(FollowedBy):\n        def parseImpl(self, instring, loc, doActions=True):\n            self.expr.try_parse(instring, loc)\n            return loc, []\n\n    _FB.__name__ = \"FollowedBy>\"\n\n    ret = Forward()\n    if isinstance(lpar, str):\n        lpar = Suppress(lpar)\n    if isinstance(rpar, str):\n        rpar = Suppress(rpar)\n\n    # if lpar and rpar are not suppressed, wrap in group\n    if not (isinstance(rpar, Suppress) and isinstance(rpar, Suppress)):\n        lastExpr = base_expr | Group(lpar + ret + rpar)\n    else:\n        lastExpr = base_expr | (lpar + ret + rpar)\n\n    for i, operDef in enumerate(op_list):\n        opExpr, arity, rightLeftAssoc, pa = (operDef + (None,))[:4]\n        if isinstance(opExpr, str_type):\n            opExpr = ParserElement._literalStringClass(opExpr)\n        if arity == 3:\n            if not isinstance(opExpr, (tuple, list)) or len(opExpr) != 2:\n                raise ValueError(\n                    \"if numterms=3, opExpr must be a tuple or list of two expressions\"\n                )\n            opExpr1, opExpr2 = opExpr\n            term_name = \"{}{} term\".format(opExpr1, opExpr2)\n        else:\n            term_name = \"{} term\".format(opExpr)\n\n        if not 1 <= arity <= 3:\n            raise ValueError(\"operator must be unary (1), binary (2), or ternary (3)\")\n\n        if rightLeftAssoc not in (OpAssoc.LEFT, OpAssoc.RIGHT):\n            raise ValueError(\"operator must indicate right or left associativity\")\n\n        thisExpr: Forward = Forward().set_name(term_name)\n        if rightLeftAssoc is OpAssoc.LEFT:\n            if arity == 1:\n                matchExpr = _FB(lastExpr + opExpr) + Group(lastExpr + opExpr[1, ...])\n            elif arity == 2:\n                if opExpr is not None:\n                    matchExpr = _FB(lastExpr + opExpr + lastExpr) + Group(\n                        lastExpr + (opExpr + lastExpr)[1, ...]\n                    )\n                else:\n                    matchExpr = _FB(lastExpr + lastExpr) + Group(lastExpr[2, ...])\n            elif arity == 3:\n                matchExpr = _FB(\n                    lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr\n                ) + Group(lastExpr + OneOrMore(opExpr1 + lastExpr + opExpr2 + lastExpr))\n        elif rightLeftAssoc is OpAssoc.RIGHT:\n            if arity == 1:\n                # try to avoid LR with this extra test\n                if not isinstance(opExpr, Opt):\n                    opExpr = Opt(opExpr)\n                matchExpr = _FB(opExpr.expr + thisExpr) + Group(opExpr + thisExpr)\n            elif arity == 2:\n                if opExpr is not None:\n                    matchExpr = _FB(lastExpr + opExpr + thisExpr) + Group(\n                        lastExpr + (opExpr + thisExpr)[1, ...]\n                    )\n                else:\n                    matchExpr = _FB(lastExpr + thisExpr) + Group(\n                        lastExpr + thisExpr[1, ...]\n                    )\n            elif arity == 3:\n                matchExpr = _FB(\n                    lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr\n                ) + Group(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr)\n        if pa:\n            if isinstance(pa, (tuple, list)):\n                matchExpr.set_parse_action(*pa)\n            else:\n                matchExpr.set_parse_action(pa)\n        thisExpr <<= (matchExpr | lastExpr).setName(term_name)\n        lastExpr = thisExpr\n    ret <<= lastExpr\n    return ret\n\n\ndef indentedBlock(blockStatementExpr, indentStack, indent=True, backup_stacks=[]):\n    \"\"\"\n    (DEPRECATED - use IndentedBlock class instead)\n    Helper method for defining space-delimited indentation blocks,\n    such as those used to define block statements in Python source code.\n\n    Parameters:\n\n    - ``blockStatementExpr`` - expression defining syntax of statement that\n      is repeated within the indented block\n    - ``indentStack`` - list created by caller to manage indentation stack\n      (multiple ``statementWithIndentedBlock`` expressions within a single\n      grammar should share a common ``indentStack``)\n    - ``indent`` - boolean indicating whether block must be indented beyond\n      the current level; set to ``False`` for block of left-most statements\n      (default= ``True``)\n\n    A valid block must contain at least one ``blockStatement``.\n\n    (Note that indentedBlock uses internal parse actions which make it\n    incompatible with packrat parsing.)\n\n    Example::\n\n        data = '''\n        def A(z):\n          A1\n          B = 100\n          G = A2\n          A2\n          A3\n        B\n        def BB(a,b,c):\n          BB1\n          def BBA():\n            bba1\n            bba2\n            bba3\n        C\n        D\n        def spam(x,y):\n             def eggs(z):\n                 pass\n        '''\n\n\n        indentStack = [1]\n        stmt = Forward()\n\n        identifier = Word(alphas, alphanums)\n        funcDecl = (\"def\" + identifier + Group(\"(\" + Opt(delimitedList(identifier)) + \")\") + \":\")\n        func_body = indentedBlock(stmt, indentStack)\n        funcDef = Group(funcDecl + func_body)\n\n        rvalue = Forward()\n        funcCall = Group(identifier + \"(\" + Opt(delimitedList(rvalue)) + \")\")\n        rvalue << (funcCall | identifier | Word(nums))\n        assignment = Group(identifier + \"=\" + rvalue)\n        stmt << (funcDef | assignment | identifier)\n\n        module_body = stmt[1, ...]\n\n        parseTree = module_body.parseString(data)\n        parseTree.pprint()\n\n    prints::\n\n        [['def',\n          'A',\n          ['(', 'z', ')'],\n          ':',\n          [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],\n         'B',\n         ['def',\n          'BB',\n          ['(', 'a', 'b', 'c', ')'],\n          ':',\n          [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],\n         'C',\n         'D',\n         ['def',\n          'spam',\n          ['(', 'x', 'y', ')'],\n          ':',\n          [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]]\n    \"\"\"\n    backup_stacks.append(indentStack[:])\n\n    def reset_stack():\n        indentStack[:] = backup_stacks[-1]\n\n    def checkPeerIndent(s, l, t):\n        if l >= len(s):\n            return\n        curCol = col(l, s)\n        if curCol != indentStack[-1]:\n            if curCol > indentStack[-1]:\n                raise ParseException(s, l, \"illegal nesting\")\n            raise ParseException(s, l, \"not a peer entry\")\n\n    def checkSubIndent(s, l, t):\n        curCol = col(l, s)\n        if curCol > indentStack[-1]:\n            indentStack.append(curCol)\n        else:\n            raise ParseException(s, l, \"not a subentry\")\n\n    def checkUnindent(s, l, t):\n        if l >= len(s):\n            return\n        curCol = col(l, s)\n        if not (indentStack and curCol in indentStack):\n            raise ParseException(s, l, \"not an unindent\")\n        if curCol < indentStack[-1]:\n            indentStack.pop()\n\n    NL = OneOrMore(LineEnd().set_whitespace_chars(\"\\t \").suppress())\n    INDENT = (Empty() + Empty().set_parse_action(checkSubIndent)).set_name(\"INDENT\")\n    PEER = Empty().set_parse_action(checkPeerIndent).set_name(\"\")\n    UNDENT = Empty().set_parse_action(checkUnindent).set_name(\"UNINDENT\")\n    if indent:\n        smExpr = Group(\n            Opt(NL)\n            + INDENT\n            + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL))\n            + UNDENT\n        )\n    else:\n        smExpr = Group(\n            Opt(NL)\n            + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL))\n            + Opt(UNDENT)\n        )\n\n    # add a parse action to remove backup_stack from list of backups\n    smExpr.add_parse_action(\n        lambda: backup_stacks.pop(-1) and None if backup_stacks else None\n    )\n    smExpr.set_fail_action(lambda a, b, c, d: reset_stack())\n    blockStatementExpr.ignore(_bslash + LineEnd())\n    return smExpr.set_name(\"indented block\")\n\n\n# it's easy to get these comment structures wrong - they're very common, so may as well make them available\nc_style_comment = Combine(Regex(r\"/\\*(?:[^*]|\\*(?!/))*\") + \"*/\").set_name(\n    \"C style comment\"\n)\n\"Comment of the form ``/* ... */``\"\n\nhtml_comment = Regex(r\"<!--[\\s\\S]*?-->\").set_name(\"HTML comment\")\n\"Comment of the form ``<!-- ... -->``\"\n\nrest_of_line = Regex(r\".*\").leave_whitespace().set_name(\"rest of line\")\ndbl_slash_comment = Regex(r\"//(?:\\\\\\n|[^\\n])*\").set_name(\"// comment\")\n\"Comment of the form ``// ... (to end of line)``\"\n\ncpp_style_comment = Combine(\n    Regex(r\"/\\*(?:[^*]|\\*(?!/))*\") + \"*/\" | dbl_slash_comment\n).set_name(\"C++ style comment\")\n\"Comment of either form :class:`c_style_comment` or :class:`dbl_slash_comment`\"\n\njava_style_comment = cpp_style_comment\n\"Same as :class:`cpp_style_comment`\"\n\npython_style_comment = Regex(r\"#.*\").set_name(\"Python style comment\")\n\"Comment of the form ``# ... (to end of line)``\"\n\n\n# build list of built-in expressions, for future reference if a global default value\n# gets updated\n_builtin_exprs: List[ParserElement] = [\n    v for v in vars().values() if isinstance(v, ParserElement)\n]\n\n\n# pre-PEP8 compatible names\ndelimitedList = delimited_list\ncountedArray = counted_array\nmatchPreviousLiteral = match_previous_literal\nmatchPreviousExpr = match_previous_expr\noneOf = one_of\ndictOf = dict_of\noriginalTextFor = original_text_for\nnestedExpr = nested_expr\nmakeHTMLTags = make_html_tags\nmakeXMLTags = make_xml_tags\nanyOpenTag, anyCloseTag = any_open_tag, any_close_tag\ncommonHTMLEntity = common_html_entity\nreplaceHTMLEntity = replace_html_entity\nopAssoc = OpAssoc\ninfixNotation = infix_notation\ncStyleComment = c_style_comment\nhtmlComment = html_comment\nrestOfLine = rest_of_line\ndblSlashComment = dbl_slash_comment\ncppStyleComment = cpp_style_comment\njavaStyleComment = java_style_comment\npythonStyleComment = python_style_comment\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing/results.py",
    "content": "# results.py\nfrom collections.abc import MutableMapping, Mapping, MutableSequence, Iterator\nimport pprint\nfrom weakref import ref as wkref\nfrom typing import Tuple, Any\n\nstr_type: Tuple[type, ...] = (str, bytes)\n_generator_type = type((_ for _ in ()))\n\n\nclass _ParseResultsWithOffset:\n    __slots__ = [\"tup\"]\n\n    def __init__(self, p1, p2):\n        self.tup = (p1, p2)\n\n    def __getitem__(self, i):\n        return self.tup[i]\n\n    def __getstate__(self):\n        return self.tup\n\n    def __setstate__(self, *args):\n        self.tup = args[0]\n\n\nclass ParseResults:\n    \"\"\"Structured parse results, to provide multiple means of access to\n    the parsed data:\n\n    - as a list (``len(results)``)\n    - by list index (``results[0], results[1]``, etc.)\n    - by attribute (``results.<results_name>`` - see :class:`ParserElement.set_results_name`)\n\n    Example::\n\n        integer = Word(nums)\n        date_str = (integer.set_results_name(\"year\") + '/'\n                    + integer.set_results_name(\"month\") + '/'\n                    + integer.set_results_name(\"day\"))\n        # equivalent form:\n        # date_str = (integer(\"year\") + '/'\n        #             + integer(\"month\") + '/'\n        #             + integer(\"day\"))\n\n        # parse_string returns a ParseResults object\n        result = date_str.parse_string(\"1999/12/31\")\n\n        def test(s, fn=repr):\n            print(\"{} -> {}\".format(s, fn(eval(s))))\n        test(\"list(result)\")\n        test(\"result[0]\")\n        test(\"result['month']\")\n        test(\"result.day\")\n        test(\"'month' in result\")\n        test(\"'minutes' in result\")\n        test(\"result.dump()\", str)\n\n    prints::\n\n        list(result) -> ['1999', '/', '12', '/', '31']\n        result[0] -> '1999'\n        result['month'] -> '12'\n        result.day -> '31'\n        'month' in result -> True\n        'minutes' in result -> False\n        result.dump() -> ['1999', '/', '12', '/', '31']\n        - day: '31'\n        - month: '12'\n        - year: '1999'\n    \"\"\"\n\n    _null_values: Tuple[Any, ...] = (None, [], \"\", ())\n\n    __slots__ = [\n        \"_name\",\n        \"_parent\",\n        \"_all_names\",\n        \"_modal\",\n        \"_toklist\",\n        \"_tokdict\",\n        \"__weakref__\",\n    ]\n\n    class List(list):\n        \"\"\"\n        Simple wrapper class to distinguish parsed list results that should be preserved\n        as actual Python lists, instead of being converted to :class:`ParseResults`:\n\n            LBRACK, RBRACK = map(pp.Suppress, \"[]\")\n            element = pp.Forward()\n            item = ppc.integer\n            element_list = LBRACK + pp.delimited_list(element) + RBRACK\n\n            # add parse actions to convert from ParseResults to actual Python collection types\n            def as_python_list(t):\n                return pp.ParseResults.List(t.as_list())\n            element_list.add_parse_action(as_python_list)\n\n            element <<= item | element_list\n\n            element.run_tests('''\n                100\n                [2,3,4]\n                [[2, 1],3,4]\n                [(2, 1),3,4]\n                (2,3,4)\n                ''', post_parse=lambda s, r: (r[0], type(r[0])))\n\n        prints:\n\n            100\n            (100, <class 'int'>)\n\n            [2,3,4]\n            ([2, 3, 4], <class 'list'>)\n\n            [[2, 1],3,4]\n            ([[2, 1], 3, 4], <class 'list'>)\n\n        (Used internally by :class:`Group` when `aslist=True`.)\n        \"\"\"\n\n        def __new__(cls, contained=None):\n            if contained is None:\n                contained = []\n\n            if not isinstance(contained, list):\n                raise TypeError(\n                    \"{} may only be constructed with a list,\"\n                    \" not {}\".format(cls.__name__, type(contained).__name__)\n                )\n\n            return list.__new__(cls)\n\n    def __new__(cls, toklist=None, name=None, **kwargs):\n        if isinstance(toklist, ParseResults):\n            return toklist\n        self = object.__new__(cls)\n        self._name = None\n        self._parent = None\n        self._all_names = set()\n\n        if toklist is None:\n            self._toklist = []\n        elif isinstance(toklist, (list, _generator_type)):\n            self._toklist = (\n                [toklist[:]]\n                if isinstance(toklist, ParseResults.List)\n                else list(toklist)\n            )\n        else:\n            self._toklist = [toklist]\n        self._tokdict = dict()\n        return self\n\n    # Performance tuning: we construct a *lot* of these, so keep this\n    # constructor as small and fast as possible\n    def __init__(\n        self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance\n    ):\n        self._modal = modal\n        if name is not None and name != \"\":\n            if isinstance(name, int):\n                name = str(name)\n            if not modal:\n                self._all_names = {name}\n            self._name = name\n            if toklist not in self._null_values:\n                if isinstance(toklist, (str_type, type)):\n                    toklist = [toklist]\n                if asList:\n                    if isinstance(toklist, ParseResults):\n                        self[name] = _ParseResultsWithOffset(\n                            ParseResults(toklist._toklist), 0\n                        )\n                    else:\n                        self[name] = _ParseResultsWithOffset(\n                            ParseResults(toklist[0]), 0\n                        )\n                    self[name]._name = name\n                else:\n                    try:\n                        self[name] = toklist[0]\n                    except (KeyError, TypeError, IndexError):\n                        if toklist is not self:\n                            self[name] = toklist\n                        else:\n                            self._name = name\n\n    def __getitem__(self, i):\n        if isinstance(i, (int, slice)):\n            return self._toklist[i]\n        else:\n            if i not in self._all_names:\n                return self._tokdict[i][-1][0]\n            else:\n                return ParseResults([v[0] for v in self._tokdict[i]])\n\n    def __setitem__(self, k, v, isinstance=isinstance):\n        if isinstance(v, _ParseResultsWithOffset):\n            self._tokdict[k] = self._tokdict.get(k, list()) + [v]\n            sub = v[0]\n        elif isinstance(k, (int, slice)):\n            self._toklist[k] = v\n            sub = v\n        else:\n            self._tokdict[k] = self._tokdict.get(k, list()) + [\n                _ParseResultsWithOffset(v, 0)\n            ]\n            sub = v\n        if isinstance(sub, ParseResults):\n            sub._parent = wkref(self)\n\n    def __delitem__(self, i):\n        if isinstance(i, (int, slice)):\n            mylen = len(self._toklist)\n            del self._toklist[i]\n\n            # convert int to slice\n            if isinstance(i, int):\n                if i < 0:\n                    i += mylen\n                i = slice(i, i + 1)\n            # get removed indices\n            removed = list(range(*i.indices(mylen)))\n            removed.reverse()\n            # fixup indices in token dictionary\n            for name, occurrences in self._tokdict.items():\n                for j in removed:\n                    for k, (value, position) in enumerate(occurrences):\n                        occurrences[k] = _ParseResultsWithOffset(\n                            value, position - (position > j)\n                        )\n        else:\n            del self._tokdict[i]\n\n    def __contains__(self, k) -> bool:\n        return k in self._tokdict\n\n    def __len__(self) -> int:\n        return len(self._toklist)\n\n    def __bool__(self) -> bool:\n        return not not (self._toklist or self._tokdict)\n\n    def __iter__(self) -> Iterator:\n        return iter(self._toklist)\n\n    def __reversed__(self) -> Iterator:\n        return iter(self._toklist[::-1])\n\n    def keys(self):\n        return iter(self._tokdict)\n\n    def values(self):\n        return (self[k] for k in self.keys())\n\n    def items(self):\n        return ((k, self[k]) for k in self.keys())\n\n    def haskeys(self) -> bool:\n        \"\"\"\n        Since ``keys()`` returns an iterator, this method is helpful in bypassing\n        code that looks for the existence of any defined results names.\"\"\"\n        return bool(self._tokdict)\n\n    def pop(self, *args, **kwargs):\n        \"\"\"\n        Removes and returns item at specified index (default= ``last``).\n        Supports both ``list`` and ``dict`` semantics for ``pop()``. If\n        passed no argument or an integer argument, it will use ``list``\n        semantics and pop tokens from the list of parsed tokens. If passed\n        a non-integer argument (most likely a string), it will use ``dict``\n        semantics and pop the corresponding value from any defined results\n        names. A second default return value argument is supported, just as in\n        ``dict.pop()``.\n\n        Example::\n\n            numlist = Word(nums)[...]\n            print(numlist.parse_string(\"0 123 321\")) # -> ['0', '123', '321']\n\n            def remove_first(tokens):\n                tokens.pop(0)\n            numlist.add_parse_action(remove_first)\n            print(numlist.parse_string(\"0 123 321\")) # -> ['123', '321']\n\n            label = Word(alphas)\n            patt = label(\"LABEL\") + Word(nums)[1, ...]\n            print(patt.parse_string(\"AAB 123 321\").dump())\n\n            # Use pop() in a parse action to remove named result (note that corresponding value is not\n            # removed from list form of results)\n            def remove_LABEL(tokens):\n                tokens.pop(\"LABEL\")\n                return tokens\n            patt.add_parse_action(remove_LABEL)\n            print(patt.parse_string(\"AAB 123 321\").dump())\n\n        prints::\n\n            ['AAB', '123', '321']\n            - LABEL: 'AAB'\n\n            ['AAB', '123', '321']\n        \"\"\"\n        if not args:\n            args = [-1]\n        for k, v in kwargs.items():\n            if k == \"default\":\n                args = (args[0], v)\n            else:\n                raise TypeError(\n                    \"pop() got an unexpected keyword argument {!r}\".format(k)\n                )\n        if isinstance(args[0], int) or len(args) == 1 or args[0] in self:\n            index = args[0]\n            ret = self[index]\n            del self[index]\n            return ret\n        else:\n            defaultvalue = args[1]\n            return defaultvalue\n\n    def get(self, key, default_value=None):\n        \"\"\"\n        Returns named result matching the given key, or if there is no\n        such name, then returns the given ``default_value`` or ``None`` if no\n        ``default_value`` is specified.\n\n        Similar to ``dict.get()``.\n\n        Example::\n\n            integer = Word(nums)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            result = date_str.parse_string(\"1999/12/31\")\n            print(result.get(\"year\")) # -> '1999'\n            print(result.get(\"hour\", \"not specified\")) # -> 'not specified'\n            print(result.get(\"hour\")) # -> None\n        \"\"\"\n        if key in self:\n            return self[key]\n        else:\n            return default_value\n\n    def insert(self, index, ins_string):\n        \"\"\"\n        Inserts new element at location index in the list of parsed tokens.\n\n        Similar to ``list.insert()``.\n\n        Example::\n\n            numlist = Word(nums)[...]\n            print(numlist.parse_string(\"0 123 321\")) # -> ['0', '123', '321']\n\n            # use a parse action to insert the parse location in the front of the parsed results\n            def insert_locn(locn, tokens):\n                tokens.insert(0, locn)\n            numlist.add_parse_action(insert_locn)\n            print(numlist.parse_string(\"0 123 321\")) # -> [0, '0', '123', '321']\n        \"\"\"\n        self._toklist.insert(index, ins_string)\n        # fixup indices in token dictionary\n        for name, occurrences in self._tokdict.items():\n            for k, (value, position) in enumerate(occurrences):\n                occurrences[k] = _ParseResultsWithOffset(\n                    value, position + (position > index)\n                )\n\n    def append(self, item):\n        \"\"\"\n        Add single element to end of ``ParseResults`` list of elements.\n\n        Example::\n\n            numlist = Word(nums)[...]\n            print(numlist.parse_string(\"0 123 321\")) # -> ['0', '123', '321']\n\n            # use a parse action to compute the sum of the parsed integers, and add it to the end\n            def append_sum(tokens):\n                tokens.append(sum(map(int, tokens)))\n            numlist.add_parse_action(append_sum)\n            print(numlist.parse_string(\"0 123 321\")) # -> ['0', '123', '321', 444]\n        \"\"\"\n        self._toklist.append(item)\n\n    def extend(self, itemseq):\n        \"\"\"\n        Add sequence of elements to end of ``ParseResults`` list of elements.\n\n        Example::\n\n            patt = Word(alphas)[1, ...]\n\n            # use a parse action to append the reverse of the matched strings, to make a palindrome\n            def make_palindrome(tokens):\n                tokens.extend(reversed([t[::-1] for t in tokens]))\n                return ''.join(tokens)\n            patt.add_parse_action(make_palindrome)\n            print(patt.parse_string(\"lskdj sdlkjf lksd\")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'\n        \"\"\"\n        if isinstance(itemseq, ParseResults):\n            self.__iadd__(itemseq)\n        else:\n            self._toklist.extend(itemseq)\n\n    def clear(self):\n        \"\"\"\n        Clear all elements and results names.\n        \"\"\"\n        del self._toklist[:]\n        self._tokdict.clear()\n\n    def __getattr__(self, name):\n        try:\n            return self[name]\n        except KeyError:\n            if name.startswith(\"__\"):\n                raise AttributeError(name)\n            return \"\"\n\n    def __add__(self, other) -> \"ParseResults\":\n        ret = self.copy()\n        ret += other\n        return ret\n\n    def __iadd__(self, other) -> \"ParseResults\":\n        if other._tokdict:\n            offset = len(self._toklist)\n            addoffset = lambda a: offset if a < 0 else a + offset\n            otheritems = other._tokdict.items()\n            otherdictitems = [\n                (k, _ParseResultsWithOffset(v[0], addoffset(v[1])))\n                for k, vlist in otheritems\n                for v in vlist\n            ]\n            for k, v in otherdictitems:\n                self[k] = v\n                if isinstance(v[0], ParseResults):\n                    v[0]._parent = wkref(self)\n\n        self._toklist += other._toklist\n        self._all_names |= other._all_names\n        return self\n\n    def __radd__(self, other) -> \"ParseResults\":\n        if isinstance(other, int) and other == 0:\n            # useful for merging many ParseResults using sum() builtin\n            return self.copy()\n        else:\n            # this may raise a TypeError - so be it\n            return other + self\n\n    def __repr__(self) -> str:\n        return \"{}({!r}, {})\".format(type(self).__name__, self._toklist, self.as_dict())\n\n    def __str__(self) -> str:\n        return (\n            \"[\"\n            + \", \".join(\n                [\n                    str(i) if isinstance(i, ParseResults) else repr(i)\n                    for i in self._toklist\n                ]\n            )\n            + \"]\"\n        )\n\n    def _asStringList(self, sep=\"\"):\n        out = []\n        for item in self._toklist:\n            if out and sep:\n                out.append(sep)\n            if isinstance(item, ParseResults):\n                out += item._asStringList()\n            else:\n                out.append(str(item))\n        return out\n\n    def as_list(self) -> list:\n        \"\"\"\n        Returns the parse results as a nested list of matching tokens, all converted to strings.\n\n        Example::\n\n            patt = Word(alphas)[1, ...]\n            result = patt.parse_string(\"sldkj lsdkj sldkj\")\n            # even though the result prints in string-like form, it is actually a pyparsing ParseResults\n            print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']\n\n            # Use as_list() to create an actual list\n            result_list = result.as_list()\n            print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']\n        \"\"\"\n        return [\n            res.as_list() if isinstance(res, ParseResults) else res\n            for res in self._toklist\n        ]\n\n    def as_dict(self) -> dict:\n        \"\"\"\n        Returns the named parse results as a nested dictionary.\n\n        Example::\n\n            integer = Word(nums)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            result = date_str.parse_string('12/31/1999')\n            print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})\n\n            result_dict = result.as_dict()\n            print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}\n\n            # even though a ParseResults supports dict-like access, sometime you just need to have a dict\n            import json\n            print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable\n            print(json.dumps(result.as_dict())) # -> {\"month\": \"31\", \"day\": \"1999\", \"year\": \"12\"}\n        \"\"\"\n\n        def to_item(obj):\n            if isinstance(obj, ParseResults):\n                return obj.as_dict() if obj.haskeys() else [to_item(v) for v in obj]\n            else:\n                return obj\n\n        return dict((k, to_item(v)) for k, v in self.items())\n\n    def copy(self) -> \"ParseResults\":\n        \"\"\"\n        Returns a new copy of a :class:`ParseResults` object.\n        \"\"\"\n        ret = ParseResults(self._toklist)\n        ret._tokdict = self._tokdict.copy()\n        ret._parent = self._parent\n        ret._all_names |= self._all_names\n        ret._name = self._name\n        return ret\n\n    def get_name(self):\n        r\"\"\"\n        Returns the results name for this token expression. Useful when several\n        different expressions might match at a particular location.\n\n        Example::\n\n            integer = Word(nums)\n            ssn_expr = Regex(r\"\\d\\d\\d-\\d\\d-\\d\\d\\d\\d\")\n            house_number_expr = Suppress('#') + Word(nums, alphanums)\n            user_data = (Group(house_number_expr)(\"house_number\")\n                        | Group(ssn_expr)(\"ssn\")\n                        | Group(integer)(\"age\"))\n            user_info = user_data[1, ...]\n\n            result = user_info.parse_string(\"22 111-22-3333 #221B\")\n            for item in result:\n                print(item.get_name(), ':', item[0])\n\n        prints::\n\n            age : 22\n            ssn : 111-22-3333\n            house_number : 221B\n        \"\"\"\n        if self._name:\n            return self._name\n        elif self._parent:\n            par = self._parent()\n\n            def find_in_parent(sub):\n                return next(\n                    (\n                        k\n                        for k, vlist in par._tokdict.items()\n                        for v, loc in vlist\n                        if sub is v\n                    ),\n                    None,\n                )\n\n            return find_in_parent(self) if par else None\n        elif (\n            len(self) == 1\n            and len(self._tokdict) == 1\n            and next(iter(self._tokdict.values()))[0][1] in (0, -1)\n        ):\n            return next(iter(self._tokdict.keys()))\n        else:\n            return None\n\n    def dump(self, indent=\"\", full=True, include_list=True, _depth=0) -> str:\n        \"\"\"\n        Diagnostic method for listing out the contents of\n        a :class:`ParseResults`. Accepts an optional ``indent`` argument so\n        that this string can be embedded in a nested display of other data.\n\n        Example::\n\n            integer = Word(nums)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            result = date_str.parse_string('1999/12/31')\n            print(result.dump())\n\n        prints::\n\n            ['1999', '/', '12', '/', '31']\n            - day: '31'\n            - month: '12'\n            - year: '1999'\n        \"\"\"\n        out = []\n        NL = \"\\n\"\n        out.append(indent + str(self.as_list()) if include_list else \"\")\n\n        if full:\n            if self.haskeys():\n                items = sorted((str(k), v) for k, v in self.items())\n                for k, v in items:\n                    if out:\n                        out.append(NL)\n                    out.append(\"{}{}- {}: \".format(indent, (\"  \" * _depth), k))\n                    if isinstance(v, ParseResults):\n                        if v:\n                            out.append(\n                                v.dump(\n                                    indent=indent,\n                                    full=full,\n                                    include_list=include_list,\n                                    _depth=_depth + 1,\n                                )\n                            )\n                        else:\n                            out.append(str(v))\n                    else:\n                        out.append(repr(v))\n            if any(isinstance(vv, ParseResults) for vv in self):\n                v = self\n                for i, vv in enumerate(v):\n                    if isinstance(vv, ParseResults):\n                        out.append(\n                            \"\\n{}{}[{}]:\\n{}{}{}\".format(\n                                indent,\n                                (\"  \" * (_depth)),\n                                i,\n                                indent,\n                                (\"  \" * (_depth + 1)),\n                                vv.dump(\n                                    indent=indent,\n                                    full=full,\n                                    include_list=include_list,\n                                    _depth=_depth + 1,\n                                ),\n                            )\n                        )\n                    else:\n                        out.append(\n                            \"\\n%s%s[%d]:\\n%s%s%s\"\n                            % (\n                                indent,\n                                (\"  \" * (_depth)),\n                                i,\n                                indent,\n                                (\"  \" * (_depth + 1)),\n                                str(vv),\n                            )\n                        )\n\n        return \"\".join(out)\n\n    def pprint(self, *args, **kwargs):\n        \"\"\"\n        Pretty-printer for parsed results as a list, using the\n        `pprint <https://docs.python.org/3/library/pprint.html>`_ module.\n        Accepts additional positional or keyword args as defined for\n        `pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ .\n\n        Example::\n\n            ident = Word(alphas, alphanums)\n            num = Word(nums)\n            func = Forward()\n            term = ident | num | Group('(' + func + ')')\n            func <<= ident + Group(Optional(delimited_list(term)))\n            result = func.parse_string(\"fna a,b,(fnb c,d,200),100\")\n            result.pprint(width=40)\n\n        prints::\n\n            ['fna',\n             ['a',\n              'b',\n              ['(', 'fnb', ['c', 'd', '200'], ')'],\n              '100']]\n        \"\"\"\n        pprint.pprint(self.as_list(), *args, **kwargs)\n\n    # add support for pickle protocol\n    def __getstate__(self):\n        return (\n            self._toklist,\n            (\n                self._tokdict.copy(),\n                self._parent is not None and self._parent() or None,\n                self._all_names,\n                self._name,\n            ),\n        )\n\n    def __setstate__(self, state):\n        self._toklist, (self._tokdict, par, inAccumNames, self._name) = state\n        self._all_names = set(inAccumNames)\n        if par is not None:\n            self._parent = wkref(par)\n        else:\n            self._parent = None\n\n    def __getnewargs__(self):\n        return self._toklist, self._name\n\n    def __dir__(self):\n        return dir(type(self)) + list(self.keys())\n\n    @classmethod\n    def from_dict(cls, other, name=None) -> \"ParseResults\":\n        \"\"\"\n        Helper classmethod to construct a ``ParseResults`` from a ``dict``, preserving the\n        name-value relations as results names. If an optional ``name`` argument is\n        given, a nested ``ParseResults`` will be returned.\n        \"\"\"\n\n        def is_iterable(obj):\n            try:\n                iter(obj)\n            except Exception:\n                return False\n            else:\n                return not isinstance(obj, str_type)\n\n        ret = cls([])\n        for k, v in other.items():\n            if isinstance(v, Mapping):\n                ret += cls.from_dict(v, name=k)\n            else:\n                ret += cls([v], name=k, asList=is_iterable(v))\n        if name is not None:\n            ret = cls([ret], name=name)\n        return ret\n\n    asList = as_list\n    asDict = as_dict\n    getName = get_name\n\n\nMutableMapping.register(ParseResults)\nMutableSequence.register(ParseResults)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing/testing.py",
    "content": "# testing.py\n\nfrom contextlib import contextmanager\nimport typing\n\nfrom .core import (\n    ParserElement,\n    ParseException,\n    Keyword,\n    __diag__,\n    __compat__,\n)\n\n\nclass pyparsing_test:\n    \"\"\"\n    namespace class for classes useful in writing unit tests\n    \"\"\"\n\n    class reset_pyparsing_context:\n        \"\"\"\n        Context manager to be used when writing unit tests that modify pyparsing config values:\n        - packrat parsing\n        - bounded recursion parsing\n        - default whitespace characters.\n        - default keyword characters\n        - literal string auto-conversion class\n        - __diag__ settings\n\n        Example::\n\n            with reset_pyparsing_context():\n                # test that literals used to construct a grammar are automatically suppressed\n                ParserElement.inlineLiteralsUsing(Suppress)\n\n                term = Word(alphas) | Word(nums)\n                group = Group('(' + term[...] + ')')\n\n                # assert that the '()' characters are not included in the parsed tokens\n                self.assertParseAndCheckList(group, \"(abc 123 def)\", ['abc', '123', 'def'])\n\n            # after exiting context manager, literals are converted to Literal expressions again\n        \"\"\"\n\n        def __init__(self):\n            self._save_context = {}\n\n        def save(self):\n            self._save_context[\"default_whitespace\"] = ParserElement.DEFAULT_WHITE_CHARS\n            self._save_context[\"default_keyword_chars\"] = Keyword.DEFAULT_KEYWORD_CHARS\n\n            self._save_context[\n                \"literal_string_class\"\n            ] = ParserElement._literalStringClass\n\n            self._save_context[\"verbose_stacktrace\"] = ParserElement.verbose_stacktrace\n\n            self._save_context[\"packrat_enabled\"] = ParserElement._packratEnabled\n            if ParserElement._packratEnabled:\n                self._save_context[\n                    \"packrat_cache_size\"\n                ] = ParserElement.packrat_cache.size\n            else:\n                self._save_context[\"packrat_cache_size\"] = None\n            self._save_context[\"packrat_parse\"] = ParserElement._parse\n            self._save_context[\n                \"recursion_enabled\"\n            ] = ParserElement._left_recursion_enabled\n\n            self._save_context[\"__diag__\"] = {\n                name: getattr(__diag__, name) for name in __diag__._all_names\n            }\n\n            self._save_context[\"__compat__\"] = {\n                \"collect_all_And_tokens\": __compat__.collect_all_And_tokens\n            }\n\n            return self\n\n        def restore(self):\n            # reset pyparsing global state\n            if (\n                ParserElement.DEFAULT_WHITE_CHARS\n                != self._save_context[\"default_whitespace\"]\n            ):\n                ParserElement.set_default_whitespace_chars(\n                    self._save_context[\"default_whitespace\"]\n                )\n\n            ParserElement.verbose_stacktrace = self._save_context[\"verbose_stacktrace\"]\n\n            Keyword.DEFAULT_KEYWORD_CHARS = self._save_context[\"default_keyword_chars\"]\n            ParserElement.inlineLiteralsUsing(\n                self._save_context[\"literal_string_class\"]\n            )\n\n            for name, value in self._save_context[\"__diag__\"].items():\n                (__diag__.enable if value else __diag__.disable)(name)\n\n            ParserElement._packratEnabled = False\n            if self._save_context[\"packrat_enabled\"]:\n                ParserElement.enable_packrat(self._save_context[\"packrat_cache_size\"])\n            else:\n                ParserElement._parse = self._save_context[\"packrat_parse\"]\n            ParserElement._left_recursion_enabled = self._save_context[\n                \"recursion_enabled\"\n            ]\n\n            __compat__.collect_all_And_tokens = self._save_context[\"__compat__\"]\n\n            return self\n\n        def copy(self):\n            ret = type(self)()\n            ret._save_context.update(self._save_context)\n            return ret\n\n        def __enter__(self):\n            return self.save()\n\n        def __exit__(self, *args):\n            self.restore()\n\n    class TestParseResultsAsserts:\n        \"\"\"\n        A mixin class to add parse results assertion methods to normal unittest.TestCase classes.\n        \"\"\"\n\n        def assertParseResultsEquals(\n            self, result, expected_list=None, expected_dict=None, msg=None\n        ):\n            \"\"\"\n            Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``,\n            and compare any defined results names with an optional ``expected_dict``.\n            \"\"\"\n            if expected_list is not None:\n                self.assertEqual(expected_list, result.as_list(), msg=msg)\n            if expected_dict is not None:\n                self.assertEqual(expected_dict, result.as_dict(), msg=msg)\n\n        def assertParseAndCheckList(\n            self, expr, test_string, expected_list, msg=None, verbose=True\n        ):\n            \"\"\"\n            Convenience wrapper assert to test a parser element and input string, and assert that\n            the resulting ``ParseResults.asList()`` is equal to the ``expected_list``.\n            \"\"\"\n            result = expr.parse_string(test_string, parse_all=True)\n            if verbose:\n                print(result.dump())\n            else:\n                print(result.as_list())\n            self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg)\n\n        def assertParseAndCheckDict(\n            self, expr, test_string, expected_dict, msg=None, verbose=True\n        ):\n            \"\"\"\n            Convenience wrapper assert to test a parser element and input string, and assert that\n            the resulting ``ParseResults.asDict()`` is equal to the ``expected_dict``.\n            \"\"\"\n            result = expr.parse_string(test_string, parseAll=True)\n            if verbose:\n                print(result.dump())\n            else:\n                print(result.as_list())\n            self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg)\n\n        def assertRunTestResults(\n            self, run_tests_report, expected_parse_results=None, msg=None\n        ):\n            \"\"\"\n            Unit test assertion to evaluate output of ``ParserElement.runTests()``. If a list of\n            list-dict tuples is given as the ``expected_parse_results`` argument, then these are zipped\n            with the report tuples returned by ``runTests`` and evaluated using ``assertParseResultsEquals``.\n            Finally, asserts that the overall ``runTests()`` success value is ``True``.\n\n            :param run_tests_report: tuple(bool, [tuple(str, ParseResults or Exception)]) returned from runTests\n            :param expected_parse_results (optional): [tuple(str, list, dict, Exception)]\n            \"\"\"\n            run_test_success, run_test_results = run_tests_report\n\n            if expected_parse_results is not None:\n                merged = [\n                    (*rpt, expected)\n                    for rpt, expected in zip(run_test_results, expected_parse_results)\n                ]\n                for test_string, result, expected in merged:\n                    # expected should be a tuple containing a list and/or a dict or an exception,\n                    # and optional failure message string\n                    # an empty tuple will skip any result validation\n                    fail_msg = next(\n                        (exp for exp in expected if isinstance(exp, str)), None\n                    )\n                    expected_exception = next(\n                        (\n                            exp\n                            for exp in expected\n                            if isinstance(exp, type) and issubclass(exp, Exception)\n                        ),\n                        None,\n                    )\n                    if expected_exception is not None:\n                        with self.assertRaises(\n                            expected_exception=expected_exception, msg=fail_msg or msg\n                        ):\n                            if isinstance(result, Exception):\n                                raise result\n                    else:\n                        expected_list = next(\n                            (exp for exp in expected if isinstance(exp, list)), None\n                        )\n                        expected_dict = next(\n                            (exp for exp in expected if isinstance(exp, dict)), None\n                        )\n                        if (expected_list, expected_dict) != (None, None):\n                            self.assertParseResultsEquals(\n                                result,\n                                expected_list=expected_list,\n                                expected_dict=expected_dict,\n                                msg=fail_msg or msg,\n                            )\n                        else:\n                            # warning here maybe?\n                            print(\"no validation for {!r}\".format(test_string))\n\n            # do this last, in case some specific test results can be reported instead\n            self.assertTrue(\n                run_test_success, msg=msg if msg is not None else \"failed runTests\"\n            )\n\n        @contextmanager\n        def assertRaisesParseException(self, exc_type=ParseException, msg=None):\n            with self.assertRaises(exc_type, msg=msg):\n                yield\n\n    @staticmethod\n    def with_line_numbers(\n        s: str,\n        start_line: typing.Optional[int] = None,\n        end_line: typing.Optional[int] = None,\n        expand_tabs: bool = True,\n        eol_mark: str = \"|\",\n        mark_spaces: typing.Optional[str] = None,\n        mark_control: typing.Optional[str] = None,\n    ) -> str:\n        \"\"\"\n        Helpful method for debugging a parser - prints a string with line and column numbers.\n        (Line and column numbers are 1-based.)\n\n        :param s: tuple(bool, str - string to be printed with line and column numbers\n        :param start_line: int - (optional) starting line number in s to print (default=1)\n        :param end_line: int - (optional) ending line number in s to print (default=len(s))\n        :param expand_tabs: bool - (optional) expand tabs to spaces, to match the pyparsing default\n        :param eol_mark: str - (optional) string to mark the end of lines, helps visualize trailing spaces (default=\"|\")\n        :param mark_spaces: str - (optional) special character to display in place of spaces\n        :param mark_control: str - (optional) convert non-printing control characters to a placeholding\n                                 character; valid values:\n                                 - \"unicode\" - replaces control chars with Unicode symbols, such as \"␍\" and \"␊\"\n                                 - any single character string - replace control characters with given string\n                                 - None (default) - string is displayed as-is\n\n        :return: str - input string with leading line numbers and column number headers\n        \"\"\"\n        if expand_tabs:\n            s = s.expandtabs()\n        if mark_control is not None:\n            if mark_control == \"unicode\":\n                tbl = str.maketrans(\n                    {c: u for c, u in zip(range(0, 33), range(0x2400, 0x2433))}\n                    | {127: 0x2421}\n                )\n                eol_mark = \"\"\n            else:\n                tbl = str.maketrans(\n                    {c: mark_control for c in list(range(0, 32)) + [127]}\n                )\n            s = s.translate(tbl)\n        if mark_spaces is not None and mark_spaces != \" \":\n            if mark_spaces == \"unicode\":\n                tbl = str.maketrans({9: 0x2409, 32: 0x2423})\n                s = s.translate(tbl)\n            else:\n                s = s.replace(\" \", mark_spaces)\n        if start_line is None:\n            start_line = 1\n        if end_line is None:\n            end_line = len(s)\n        end_line = min(end_line, len(s))\n        start_line = min(max(1, start_line), end_line)\n\n        if mark_control != \"unicode\":\n            s_lines = s.splitlines()[start_line - 1 : end_line]\n        else:\n            s_lines = [line + \"␊\" for line in s.split(\"␊\")[start_line - 1 : end_line]]\n        if not s_lines:\n            return \"\"\n\n        lineno_width = len(str(end_line))\n        max_line_len = max(len(line) for line in s_lines)\n        lead = \" \" * (lineno_width + 1)\n        if max_line_len >= 99:\n            header0 = (\n                lead\n                + \"\".join(\n                    \"{}{}\".format(\" \" * 99, (i + 1) % 100)\n                    for i in range(max(max_line_len // 100, 1))\n                )\n                + \"\\n\"\n            )\n        else:\n            header0 = \"\"\n        header1 = (\n            header0\n            + lead\n            + \"\".join(\n                \"         {}\".format((i + 1) % 10)\n                for i in range(-(-max_line_len // 10))\n            )\n            + \"\\n\"\n        )\n        header2 = lead + \"1234567890\" * (-(-max_line_len // 10)) + \"\\n\"\n        return (\n            header1\n            + header2\n            + \"\\n\".join(\n                \"{:{}d}:{}{}\".format(i, lineno_width, line, eol_mark)\n                for i, line in enumerate(s_lines, start=start_line)\n            )\n            + \"\\n\"\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing/unicode.py",
    "content": "# unicode.py\n\nimport sys\nfrom itertools import filterfalse\nfrom typing import List, Tuple, Union\n\n\nclass _lazyclassproperty:\n    def __init__(self, fn):\n        self.fn = fn\n        self.__doc__ = fn.__doc__\n        self.__name__ = fn.__name__\n\n    def __get__(self, obj, cls):\n        if cls is None:\n            cls = type(obj)\n        if not hasattr(cls, \"_intern\") or any(\n            cls._intern is getattr(superclass, \"_intern\", [])\n            for superclass in cls.__mro__[1:]\n        ):\n            cls._intern = {}\n        attrname = self.fn.__name__\n        if attrname not in cls._intern:\n            cls._intern[attrname] = self.fn(cls)\n        return cls._intern[attrname]\n\n\nUnicodeRangeList = List[Union[Tuple[int, int], Tuple[int]]]\n\n\nclass unicode_set:\n    \"\"\"\n    A set of Unicode characters, for language-specific strings for\n    ``alphas``, ``nums``, ``alphanums``, and ``printables``.\n    A unicode_set is defined by a list of ranges in the Unicode character\n    set, in a class attribute ``_ranges``. Ranges can be specified using\n    2-tuples or a 1-tuple, such as::\n\n        _ranges = [\n            (0x0020, 0x007e),\n            (0x00a0, 0x00ff),\n            (0x0100,),\n            ]\n\n    Ranges are left- and right-inclusive. A 1-tuple of (x,) is treated as (x, x).\n\n    A unicode set can also be defined using multiple inheritance of other unicode sets::\n\n        class CJK(Chinese, Japanese, Korean):\n            pass\n    \"\"\"\n\n    _ranges: UnicodeRangeList = []\n\n    @_lazyclassproperty\n    def _chars_for_ranges(cls):\n        ret = []\n        for cc in cls.__mro__:\n            if cc is unicode_set:\n                break\n            for rr in getattr(cc, \"_ranges\", ()):\n                ret.extend(range(rr[0], rr[-1] + 1))\n        return [chr(c) for c in sorted(set(ret))]\n\n    @_lazyclassproperty\n    def printables(cls):\n        \"all non-whitespace characters in this range\"\n        return \"\".join(filterfalse(str.isspace, cls._chars_for_ranges))\n\n    @_lazyclassproperty\n    def alphas(cls):\n        \"all alphabetic characters in this range\"\n        return \"\".join(filter(str.isalpha, cls._chars_for_ranges))\n\n    @_lazyclassproperty\n    def nums(cls):\n        \"all numeric digit characters in this range\"\n        return \"\".join(filter(str.isdigit, cls._chars_for_ranges))\n\n    @_lazyclassproperty\n    def alphanums(cls):\n        \"all alphanumeric characters in this range\"\n        return cls.alphas + cls.nums\n\n    @_lazyclassproperty\n    def identchars(cls):\n        \"all characters in this range that are valid identifier characters, plus underscore '_'\"\n        return \"\".join(\n            sorted(\n                set(\n                    \"\".join(filter(str.isidentifier, cls._chars_for_ranges))\n                    + \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzªµº\"\n                    + \"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\"\n                    + \"_\"\n                )\n            )\n        )\n\n    @_lazyclassproperty\n    def identbodychars(cls):\n        \"\"\"\n        all characters in this range that are valid identifier body characters,\n        plus the digits 0-9\n        \"\"\"\n        return \"\".join(\n            sorted(\n                set(\n                    cls.identchars\n                    + \"0123456789\"\n                    + \"\".join(\n                        [c for c in cls._chars_for_ranges if (\"_\" + c).isidentifier()]\n                    )\n                )\n            )\n        )\n\n\nclass pyparsing_unicode(unicode_set):\n    \"\"\"\n    A namespace class for defining common language unicode_sets.\n    \"\"\"\n\n    # fmt: off\n\n    # define ranges in language character sets\n    _ranges: UnicodeRangeList = [\n        (0x0020, sys.maxunicode),\n    ]\n\n    class BasicMultilingualPlane(unicode_set):\n        \"Unicode set for the Basic Multilingual Plane\"\n        _ranges: UnicodeRangeList = [\n            (0x0020, 0xFFFF),\n        ]\n\n    class Latin1(unicode_set):\n        \"Unicode set for Latin-1 Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0020, 0x007E),\n            (0x00A0, 0x00FF),\n        ]\n\n    class LatinA(unicode_set):\n        \"Unicode set for Latin-A Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0100, 0x017F),\n        ]\n\n    class LatinB(unicode_set):\n        \"Unicode set for Latin-B Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0180, 0x024F),\n        ]\n\n    class Greek(unicode_set):\n        \"Unicode set for Greek Unicode Character Ranges\"\n        _ranges: UnicodeRangeList = [\n            (0x0342, 0x0345),\n            (0x0370, 0x0377),\n            (0x037A, 0x037F),\n            (0x0384, 0x038A),\n            (0x038C,),\n            (0x038E, 0x03A1),\n            (0x03A3, 0x03E1),\n            (0x03F0, 0x03FF),\n            (0x1D26, 0x1D2A),\n            (0x1D5E,),\n            (0x1D60,),\n            (0x1D66, 0x1D6A),\n            (0x1F00, 0x1F15),\n            (0x1F18, 0x1F1D),\n            (0x1F20, 0x1F45),\n            (0x1F48, 0x1F4D),\n            (0x1F50, 0x1F57),\n            (0x1F59,),\n            (0x1F5B,),\n            (0x1F5D,),\n            (0x1F5F, 0x1F7D),\n            (0x1F80, 0x1FB4),\n            (0x1FB6, 0x1FC4),\n            (0x1FC6, 0x1FD3),\n            (0x1FD6, 0x1FDB),\n            (0x1FDD, 0x1FEF),\n            (0x1FF2, 0x1FF4),\n            (0x1FF6, 0x1FFE),\n            (0x2129,),\n            (0x2719, 0x271A),\n            (0xAB65,),\n            (0x10140, 0x1018D),\n            (0x101A0,),\n            (0x1D200, 0x1D245),\n            (0x1F7A1, 0x1F7A7),\n        ]\n\n    class Cyrillic(unicode_set):\n        \"Unicode set for Cyrillic Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0400, 0x052F),\n            (0x1C80, 0x1C88),\n            (0x1D2B,),\n            (0x1D78,),\n            (0x2DE0, 0x2DFF),\n            (0xA640, 0xA672),\n            (0xA674, 0xA69F),\n            (0xFE2E, 0xFE2F),\n        ]\n\n    class Chinese(unicode_set):\n        \"Unicode set for Chinese Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x2E80, 0x2E99),\n            (0x2E9B, 0x2EF3),\n            (0x31C0, 0x31E3),\n            (0x3400, 0x4DB5),\n            (0x4E00, 0x9FEF),\n            (0xA700, 0xA707),\n            (0xF900, 0xFA6D),\n            (0xFA70, 0xFAD9),\n            (0x16FE2, 0x16FE3),\n            (0x1F210, 0x1F212),\n            (0x1F214, 0x1F23B),\n            (0x1F240, 0x1F248),\n            (0x20000, 0x2A6D6),\n            (0x2A700, 0x2B734),\n            (0x2B740, 0x2B81D),\n            (0x2B820, 0x2CEA1),\n            (0x2CEB0, 0x2EBE0),\n            (0x2F800, 0x2FA1D),\n        ]\n\n    class Japanese(unicode_set):\n        \"Unicode set for Japanese Unicode Character Range, combining Kanji, Hiragana, and Katakana ranges\"\n        _ranges: UnicodeRangeList = []\n\n        class Kanji(unicode_set):\n            \"Unicode set for Kanji Unicode Character Range\"\n            _ranges: UnicodeRangeList = [\n                (0x4E00, 0x9FBF),\n                (0x3000, 0x303F),\n            ]\n\n        class Hiragana(unicode_set):\n            \"Unicode set for Hiragana Unicode Character Range\"\n            _ranges: UnicodeRangeList = [\n                (0x3041, 0x3096),\n                (0x3099, 0x30A0),\n                (0x30FC,),\n                (0xFF70,),\n                (0x1B001,),\n                (0x1B150, 0x1B152),\n                (0x1F200,),\n            ]\n\n        class Katakana(unicode_set):\n            \"Unicode set for Katakana  Unicode Character Range\"\n            _ranges: UnicodeRangeList = [\n                (0x3099, 0x309C),\n                (0x30A0, 0x30FF),\n                (0x31F0, 0x31FF),\n                (0x32D0, 0x32FE),\n                (0xFF65, 0xFF9F),\n                (0x1B000,),\n                (0x1B164, 0x1B167),\n                (0x1F201, 0x1F202),\n                (0x1F213,),\n            ]\n\n    class Hangul(unicode_set):\n        \"Unicode set for Hangul (Korean) Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x1100, 0x11FF),\n            (0x302E, 0x302F),\n            (0x3131, 0x318E),\n            (0x3200, 0x321C),\n            (0x3260, 0x327B),\n            (0x327E,),\n            (0xA960, 0xA97C),\n            (0xAC00, 0xD7A3),\n            (0xD7B0, 0xD7C6),\n            (0xD7CB, 0xD7FB),\n            (0xFFA0, 0xFFBE),\n            (0xFFC2, 0xFFC7),\n            (0xFFCA, 0xFFCF),\n            (0xFFD2, 0xFFD7),\n            (0xFFDA, 0xFFDC),\n        ]\n\n    Korean = Hangul\n\n    class CJK(Chinese, Japanese, Hangul):\n        \"Unicode set for combined Chinese, Japanese, and Korean (CJK) Unicode Character Range\"\n\n    class Thai(unicode_set):\n        \"Unicode set for Thai Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0E01, 0x0E3A),\n            (0x0E3F, 0x0E5B)\n        ]\n\n    class Arabic(unicode_set):\n        \"Unicode set for Arabic Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0600, 0x061B),\n            (0x061E, 0x06FF),\n            (0x0700, 0x077F),\n        ]\n\n    class Hebrew(unicode_set):\n        \"Unicode set for Hebrew Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0591, 0x05C7),\n            (0x05D0, 0x05EA),\n            (0x05EF, 0x05F4),\n            (0xFB1D, 0xFB36),\n            (0xFB38, 0xFB3C),\n            (0xFB3E,),\n            (0xFB40, 0xFB41),\n            (0xFB43, 0xFB44),\n            (0xFB46, 0xFB4F),\n        ]\n\n    class Devanagari(unicode_set):\n        \"Unicode set for Devanagari Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0900, 0x097F),\n            (0xA8E0, 0xA8FF)\n        ]\n\n    # fmt: on\n\n\npyparsing_unicode.Japanese._ranges = (\n    pyparsing_unicode.Japanese.Kanji._ranges\n    + pyparsing_unicode.Japanese.Hiragana._ranges\n    + pyparsing_unicode.Japanese.Katakana._ranges\n)\n\npyparsing_unicode.BMP = pyparsing_unicode.BasicMultilingualPlane\n\n# add language identifiers using language Unicode\npyparsing_unicode.العربية = pyparsing_unicode.Arabic\npyparsing_unicode.中文 = pyparsing_unicode.Chinese\npyparsing_unicode.кириллица = pyparsing_unicode.Cyrillic\npyparsing_unicode.Ελληνικά = pyparsing_unicode.Greek\npyparsing_unicode.עִברִית = pyparsing_unicode.Hebrew\npyparsing_unicode.日本語 = pyparsing_unicode.Japanese\npyparsing_unicode.Japanese.漢字 = pyparsing_unicode.Japanese.Kanji\npyparsing_unicode.Japanese.カタカナ = pyparsing_unicode.Japanese.Katakana\npyparsing_unicode.Japanese.ひらがな = pyparsing_unicode.Japanese.Hiragana\npyparsing_unicode.한국어 = pyparsing_unicode.Korean\npyparsing_unicode.ไทย = pyparsing_unicode.Thai\npyparsing_unicode.देवनागरी = pyparsing_unicode.Devanagari\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/pyparsing/util.py",
    "content": "# util.py\nimport warnings\nimport types\nimport collections\nimport itertools\nfrom functools import lru_cache\nfrom typing import List, Union, Iterable\n\n_bslash = chr(92)\n\n\nclass __config_flags:\n    \"\"\"Internal class for defining compatibility and debugging flags\"\"\"\n\n    _all_names: List[str] = []\n    _fixed_names: List[str] = []\n    _type_desc = \"configuration\"\n\n    @classmethod\n    def _set(cls, dname, value):\n        if dname in cls._fixed_names:\n            warnings.warn(\n                \"{}.{} {} is {} and cannot be overridden\".format(\n                    cls.__name__,\n                    dname,\n                    cls._type_desc,\n                    str(getattr(cls, dname)).upper(),\n                )\n            )\n            return\n        if dname in cls._all_names:\n            setattr(cls, dname, value)\n        else:\n            raise ValueError(\"no such {} {!r}\".format(cls._type_desc, dname))\n\n    enable = classmethod(lambda cls, name: cls._set(name, True))\n    disable = classmethod(lambda cls, name: cls._set(name, False))\n\n\n@lru_cache(maxsize=128)\ndef col(loc: int, strg: str) -> int:\n    \"\"\"\n    Returns current column within a string, counting newlines as line separators.\n    The first column is number 1.\n\n    Note: the default parsing behavior is to expand tabs in the input string\n    before starting the parsing process.  See\n    :class:`ParserElement.parseString` for more\n    information on parsing strings containing ``<TAB>`` s, and suggested\n    methods to maintain a consistent view of the parsed string, the parse\n    location, and line and column positions within the parsed string.\n    \"\"\"\n    s = strg\n    return 1 if 0 < loc < len(s) and s[loc - 1] == \"\\n\" else loc - s.rfind(\"\\n\", 0, loc)\n\n\n@lru_cache(maxsize=128)\ndef lineno(loc: int, strg: str) -> int:\n    \"\"\"Returns current line number within a string, counting newlines as line separators.\n    The first line is number 1.\n\n    Note - the default parsing behavior is to expand tabs in the input string\n    before starting the parsing process.  See :class:`ParserElement.parseString`\n    for more information on parsing strings containing ``<TAB>`` s, and\n    suggested methods to maintain a consistent view of the parsed string, the\n    parse location, and line and column positions within the parsed string.\n    \"\"\"\n    return strg.count(\"\\n\", 0, loc) + 1\n\n\n@lru_cache(maxsize=128)\ndef line(loc: int, strg: str) -> str:\n    \"\"\"\n    Returns the line of text containing loc within a string, counting newlines as line separators.\n    \"\"\"\n    last_cr = strg.rfind(\"\\n\", 0, loc)\n    next_cr = strg.find(\"\\n\", loc)\n    return strg[last_cr + 1 : next_cr] if next_cr >= 0 else strg[last_cr + 1 :]\n\n\nclass _UnboundedCache:\n    def __init__(self):\n        cache = {}\n        cache_get = cache.get\n        self.not_in_cache = not_in_cache = object()\n\n        def get(_, key):\n            return cache_get(key, not_in_cache)\n\n        def set_(_, key, value):\n            cache[key] = value\n\n        def clear(_):\n            cache.clear()\n\n        self.size = None\n        self.get = types.MethodType(get, self)\n        self.set = types.MethodType(set_, self)\n        self.clear = types.MethodType(clear, self)\n\n\nclass _FifoCache:\n    def __init__(self, size):\n        self.not_in_cache = not_in_cache = object()\n        cache = collections.OrderedDict()\n        cache_get = cache.get\n\n        def get(_, key):\n            return cache_get(key, not_in_cache)\n\n        def set_(_, key, value):\n            cache[key] = value\n            while len(cache) > size:\n                cache.popitem(last=False)\n\n        def clear(_):\n            cache.clear()\n\n        self.size = size\n        self.get = types.MethodType(get, self)\n        self.set = types.MethodType(set_, self)\n        self.clear = types.MethodType(clear, self)\n\n\nclass LRUMemo:\n    \"\"\"\n    A memoizing mapping that retains `capacity` deleted items\n\n    The memo tracks retained items by their access order; once `capacity` items\n    are retained, the least recently used item is discarded.\n    \"\"\"\n\n    def __init__(self, capacity):\n        self._capacity = capacity\n        self._active = {}\n        self._memory = collections.OrderedDict()\n\n    def __getitem__(self, key):\n        try:\n            return self._active[key]\n        except KeyError:\n            self._memory.move_to_end(key)\n            return self._memory[key]\n\n    def __setitem__(self, key, value):\n        self._memory.pop(key, None)\n        self._active[key] = value\n\n    def __delitem__(self, key):\n        try:\n            value = self._active.pop(key)\n        except KeyError:\n            pass\n        else:\n            while len(self._memory) >= self._capacity:\n                self._memory.popitem(last=False)\n            self._memory[key] = value\n\n    def clear(self):\n        self._active.clear()\n        self._memory.clear()\n\n\nclass UnboundedMemo(dict):\n    \"\"\"\n    A memoizing mapping that retains all deleted items\n    \"\"\"\n\n    def __delitem__(self, key):\n        pass\n\n\ndef _escape_regex_range_chars(s: str) -> str:\n    # escape these chars: ^-[]\n    for c in r\"\\^-[]\":\n        s = s.replace(c, _bslash + c)\n    s = s.replace(\"\\n\", r\"\\n\")\n    s = s.replace(\"\\t\", r\"\\t\")\n    return str(s)\n\n\ndef _collapse_string_to_ranges(\n    s: Union[str, Iterable[str]], re_escape: bool = True\n) -> str:\n    def is_consecutive(c):\n        c_int = ord(c)\n        is_consecutive.prev, prev = c_int, is_consecutive.prev\n        if c_int - prev > 1:\n            is_consecutive.value = next(is_consecutive.counter)\n        return is_consecutive.value\n\n    is_consecutive.prev = 0\n    is_consecutive.counter = itertools.count()\n    is_consecutive.value = -1\n\n    def escape_re_range_char(c):\n        return \"\\\\\" + c if c in r\"\\^-][\" else c\n\n    def no_escape_re_range_char(c):\n        return c\n\n    if not re_escape:\n        escape_re_range_char = no_escape_re_range_char\n\n    ret = []\n    s = \"\".join(sorted(set(s)))\n    if len(s) > 3:\n        for _, chars in itertools.groupby(s, key=is_consecutive):\n            first = last = next(chars)\n            last = collections.deque(\n                itertools.chain(iter([last]), chars), maxlen=1\n            ).pop()\n            if first == last:\n                ret.append(escape_re_range_char(first))\n            else:\n                sep = \"\" if ord(last) == ord(first) + 1 else \"-\"\n                ret.append(\n                    \"{}{}{}\".format(\n                        escape_re_range_char(first), sep, escape_re_range_char(last)\n                    )\n                )\n    else:\n        ret = [escape_re_range_char(c) for c in s]\n\n    return \"\".join(ret)\n\n\ndef _flatten(ll: list) -> list:\n    ret = []\n    for i in ll:\n        if isinstance(i, list):\n            ret.extend(_flatten(i))\n        else:\n            ret.append(i)\n    return ret\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/_vendor/zipp.py",
    "content": "import io\nimport posixpath\nimport zipfile\nimport itertools\nimport contextlib\nimport sys\nimport pathlib\n\nif sys.version_info < (3, 7):\n    from collections import OrderedDict\nelse:\n    OrderedDict = dict\n\n\n__all__ = ['Path']\n\n\ndef _parents(path):\n    \"\"\"\n    Given a path with elements separated by\n    posixpath.sep, generate all parents of that path.\n\n    >>> list(_parents('b/d'))\n    ['b']\n    >>> list(_parents('/b/d/'))\n    ['/b']\n    >>> list(_parents('b/d/f/'))\n    ['b/d', 'b']\n    >>> list(_parents('b'))\n    []\n    >>> list(_parents(''))\n    []\n    \"\"\"\n    return itertools.islice(_ancestry(path), 1, None)\n\n\ndef _ancestry(path):\n    \"\"\"\n    Given a path with elements separated by\n    posixpath.sep, generate all elements of that path\n\n    >>> list(_ancestry('b/d'))\n    ['b/d', 'b']\n    >>> list(_ancestry('/b/d/'))\n    ['/b/d', '/b']\n    >>> list(_ancestry('b/d/f/'))\n    ['b/d/f', 'b/d', 'b']\n    >>> list(_ancestry('b'))\n    ['b']\n    >>> list(_ancestry(''))\n    []\n    \"\"\"\n    path = path.rstrip(posixpath.sep)\n    while path and path != posixpath.sep:\n        yield path\n        path, tail = posixpath.split(path)\n\n\n_dedupe = OrderedDict.fromkeys\n\"\"\"Deduplicate an iterable in original order\"\"\"\n\n\ndef _difference(minuend, subtrahend):\n    \"\"\"\n    Return items in minuend not in subtrahend, retaining order\n    with O(1) lookup.\n    \"\"\"\n    return itertools.filterfalse(set(subtrahend).__contains__, minuend)\n\n\nclass CompleteDirs(zipfile.ZipFile):\n    \"\"\"\n    A ZipFile subclass that ensures that implied directories\n    are always included in the namelist.\n    \"\"\"\n\n    @staticmethod\n    def _implied_dirs(names):\n        parents = itertools.chain.from_iterable(map(_parents, names))\n        as_dirs = (p + posixpath.sep for p in parents)\n        return _dedupe(_difference(as_dirs, names))\n\n    def namelist(self):\n        names = super(CompleteDirs, self).namelist()\n        return names + list(self._implied_dirs(names))\n\n    def _name_set(self):\n        return set(self.namelist())\n\n    def resolve_dir(self, name):\n        \"\"\"\n        If the name represents a directory, return that name\n        as a directory (with the trailing slash).\n        \"\"\"\n        names = self._name_set()\n        dirname = name + '/'\n        dir_match = name not in names and dirname in names\n        return dirname if dir_match else name\n\n    @classmethod\n    def make(cls, source):\n        \"\"\"\n        Given a source (filename or zipfile), return an\n        appropriate CompleteDirs subclass.\n        \"\"\"\n        if isinstance(source, CompleteDirs):\n            return source\n\n        if not isinstance(source, zipfile.ZipFile):\n            return cls(_pathlib_compat(source))\n\n        # Only allow for FastLookup when supplied zipfile is read-only\n        if 'r' not in source.mode:\n            cls = CompleteDirs\n\n        source.__class__ = cls\n        return source\n\n\nclass FastLookup(CompleteDirs):\n    \"\"\"\n    ZipFile subclass to ensure implicit\n    dirs exist and are resolved rapidly.\n    \"\"\"\n\n    def namelist(self):\n        with contextlib.suppress(AttributeError):\n            return self.__names\n        self.__names = super(FastLookup, self).namelist()\n        return self.__names\n\n    def _name_set(self):\n        with contextlib.suppress(AttributeError):\n            return self.__lookup\n        self.__lookup = super(FastLookup, self)._name_set()\n        return self.__lookup\n\n\ndef _pathlib_compat(path):\n    \"\"\"\n    For path-like objects, convert to a filename for compatibility\n    on Python 3.6.1 and earlier.\n    \"\"\"\n    try:\n        return path.__fspath__()\n    except AttributeError:\n        return str(path)\n\n\nclass Path:\n    \"\"\"\n    A pathlib-compatible interface for zip files.\n\n    Consider a zip file with this structure::\n\n        .\n        ├── a.txt\n        └── b\n            ├── c.txt\n            └── d\n                └── e.txt\n\n    >>> data = io.BytesIO()\n    >>> zf = zipfile.ZipFile(data, 'w')\n    >>> zf.writestr('a.txt', 'content of a')\n    >>> zf.writestr('b/c.txt', 'content of c')\n    >>> zf.writestr('b/d/e.txt', 'content of e')\n    >>> zf.filename = 'mem/abcde.zip'\n\n    Path accepts the zipfile object itself or a filename\n\n    >>> root = Path(zf)\n\n    From there, several path operations are available.\n\n    Directory iteration (including the zip file itself):\n\n    >>> a, b = root.iterdir()\n    >>> a\n    Path('mem/abcde.zip', 'a.txt')\n    >>> b\n    Path('mem/abcde.zip', 'b/')\n\n    name property:\n\n    >>> b.name\n    'b'\n\n    join with divide operator:\n\n    >>> c = b / 'c.txt'\n    >>> c\n    Path('mem/abcde.zip', 'b/c.txt')\n    >>> c.name\n    'c.txt'\n\n    Read text:\n\n    >>> c.read_text()\n    'content of c'\n\n    existence:\n\n    >>> c.exists()\n    True\n    >>> (b / 'missing.txt').exists()\n    False\n\n    Coercion to string:\n\n    >>> import os\n    >>> str(c).replace(os.sep, posixpath.sep)\n    'mem/abcde.zip/b/c.txt'\n\n    At the root, ``name``, ``filename``, and ``parent``\n    resolve to the zipfile. Note these attributes are not\n    valid and will raise a ``ValueError`` if the zipfile\n    has no filename.\n\n    >>> root.name\n    'abcde.zip'\n    >>> str(root.filename).replace(os.sep, posixpath.sep)\n    'mem/abcde.zip'\n    >>> str(root.parent)\n    'mem'\n    \"\"\"\n\n    __repr = \"{self.__class__.__name__}({self.root.filename!r}, {self.at!r})\"\n\n    def __init__(self, root, at=\"\"):\n        \"\"\"\n        Construct a Path from a ZipFile or filename.\n\n        Note: When the source is an existing ZipFile object,\n        its type (__class__) will be mutated to a\n        specialized type. If the caller wishes to retain the\n        original type, the caller should either create a\n        separate ZipFile object or pass a filename.\n        \"\"\"\n        self.root = FastLookup.make(root)\n        self.at = at\n\n    def open(self, mode='r', *args, pwd=None, **kwargs):\n        \"\"\"\n        Open this entry as text or binary following the semantics\n        of ``pathlib.Path.open()`` by passing arguments through\n        to io.TextIOWrapper().\n        \"\"\"\n        if self.is_dir():\n            raise IsADirectoryError(self)\n        zip_mode = mode[0]\n        if not self.exists() and zip_mode == 'r':\n            raise FileNotFoundError(self)\n        stream = self.root.open(self.at, zip_mode, pwd=pwd)\n        if 'b' in mode:\n            if args or kwargs:\n                raise ValueError(\"encoding args invalid for binary operation\")\n            return stream\n        return io.TextIOWrapper(stream, *args, **kwargs)\n\n    @property\n    def name(self):\n        return pathlib.Path(self.at).name or self.filename.name\n\n    @property\n    def suffix(self):\n        return pathlib.Path(self.at).suffix or self.filename.suffix\n\n    @property\n    def suffixes(self):\n        return pathlib.Path(self.at).suffixes or self.filename.suffixes\n\n    @property\n    def stem(self):\n        return pathlib.Path(self.at).stem or self.filename.stem\n\n    @property\n    def filename(self):\n        return pathlib.Path(self.root.filename).joinpath(self.at)\n\n    def read_text(self, *args, **kwargs):\n        with self.open('r', *args, **kwargs) as strm:\n            return strm.read()\n\n    def read_bytes(self):\n        with self.open('rb') as strm:\n            return strm.read()\n\n    def _is_child(self, path):\n        return posixpath.dirname(path.at.rstrip(\"/\")) == self.at.rstrip(\"/\")\n\n    def _next(self, at):\n        return self.__class__(self.root, at)\n\n    def is_dir(self):\n        return not self.at or self.at.endswith(\"/\")\n\n    def is_file(self):\n        return self.exists() and not self.is_dir()\n\n    def exists(self):\n        return self.at in self.root._name_set()\n\n    def iterdir(self):\n        if not self.is_dir():\n            raise ValueError(\"Can't listdir a file\")\n        subs = map(self._next, self.root.namelist())\n        return filter(self._is_child, subs)\n\n    def __str__(self):\n        return posixpath.join(self.root.filename, self.at)\n\n    def __repr__(self):\n        return self.__repr.format(self=self)\n\n    def joinpath(self, *other):\n        next = posixpath.join(self.at, *map(_pathlib_compat, other))\n        return self._next(self.root.resolve_dir(next))\n\n    __truediv__ = joinpath\n\n    @property\n    def parent(self):\n        if not self.at:\n            return self.filename.parent\n        parent_at = posixpath.dirname(self.at.rstrip('/'))\n        if parent_at:\n            parent_at += '/'\n        return self._next(parent_at)\n"
  },
  {
    "path": "lib/python3.7/site-packages/pkg_resources/extern/__init__.py",
    "content": "import importlib.util\nimport sys\n\n\nclass VendorImporter:\n    \"\"\"\n    A PEP 302 meta path importer for finding optionally-vendored\n    or otherwise naturally-installed packages from root_name.\n    \"\"\"\n\n    def __init__(self, root_name, vendored_names=(), vendor_pkg=None):\n        self.root_name = root_name\n        self.vendored_names = set(vendored_names)\n        self.vendor_pkg = vendor_pkg or root_name.replace('extern', '_vendor')\n\n    @property\n    def search_path(self):\n        \"\"\"\n        Search first the vendor package then as a natural package.\n        \"\"\"\n        yield self.vendor_pkg + '.'\n        yield ''\n\n    def _module_matches_namespace(self, fullname):\n        \"\"\"Figure out if the target module is vendored.\"\"\"\n        root, base, target = fullname.partition(self.root_name + '.')\n        return not root and any(map(target.startswith, self.vendored_names))\n\n    def load_module(self, fullname):\n        \"\"\"\n        Iterate over the search path to locate and load fullname.\n        \"\"\"\n        root, base, target = fullname.partition(self.root_name + '.')\n        for prefix in self.search_path:\n            try:\n                extant = prefix + target\n                __import__(extant)\n                mod = sys.modules[extant]\n                sys.modules[fullname] = mod\n                return mod\n            except ImportError:\n                pass\n        else:\n            raise ImportError(\n                \"The '{target}' package is required; \"\n                \"normally this is bundled with this package so if you get \"\n                \"this warning, consult the packager of your \"\n                \"distribution.\".format(**locals())\n            )\n\n    def create_module(self, spec):\n        return self.load_module(spec.name)\n\n    def exec_module(self, module):\n        pass\n\n    def find_spec(self, fullname, path=None, target=None):\n        \"\"\"Return a module spec for vendored names.\"\"\"\n        return (\n            importlib.util.spec_from_loader(fullname, self)\n            if self._module_matches_namespace(fullname) else None\n        )\n\n    def install(self):\n        \"\"\"\n        Install this importer into sys.meta_path if not already present.\n        \"\"\"\n        if self not in sys.meta_path:\n            sys.meta_path.append(self)\n\n\nnames = (\n    'packaging', 'pyparsing', 'appdirs', 'jaraco', 'importlib_resources',\n    'more_itertools',\n)\nVendorImporter(__name__, names).install()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/__init__.py",
    "content": "\"\"\"Extensions to the 'distutils' for large or complex distributions\"\"\"\n\nimport functools\nimport os\nimport re\nimport warnings\n\nimport _distutils_hack.override  # noqa: F401\n\nimport distutils.core\nfrom distutils.errors import DistutilsOptionError\nfrom distutils.util import convert_path as _convert_path\n\nfrom ._deprecation_warning import SetuptoolsDeprecationWarning\n\nimport setuptools.version\nfrom setuptools.extension import Extension\nfrom setuptools.dist import Distribution\nfrom setuptools.depends import Require\nfrom setuptools.discovery import PackageFinder, PEP420PackageFinder\nfrom . import monkey\nfrom . import logging\n\n\n__all__ = [\n    'setup',\n    'Distribution',\n    'Command',\n    'Extension',\n    'Require',\n    'SetuptoolsDeprecationWarning',\n    'find_packages',\n    'find_namespace_packages',\n]\n\n__version__ = setuptools.version.__version__\n\nbootstrap_install_from = None\n\n\nfind_packages = PackageFinder.find\nfind_namespace_packages = PEP420PackageFinder.find\n\n\ndef _install_setup_requires(attrs):\n    # Note: do not use `setuptools.Distribution` directly, as\n    # our PEP 517 backend patch `distutils.core.Distribution`.\n    class MinimalDistribution(distutils.core.Distribution):\n        \"\"\"\n        A minimal version of a distribution for supporting the\n        fetch_build_eggs interface.\n        \"\"\"\n\n        def __init__(self, attrs):\n            _incl = 'dependency_links', 'setup_requires'\n            filtered = {k: attrs[k] for k in set(_incl) & set(attrs)}\n            super().__init__(filtered)\n            # Prevent accidentally triggering discovery with incomplete set of attrs\n            self.set_defaults._disable()\n\n        def _get_project_config_files(self, filenames=None):\n            \"\"\"Ignore ``pyproject.toml``, they are not related to setup_requires\"\"\"\n            try:\n                cfg, toml = super()._split_standard_project_metadata(filenames)\n                return cfg, ()\n            except Exception:\n                return filenames, ()\n\n        def finalize_options(self):\n            \"\"\"\n            Disable finalize_options to avoid building the working set.\n            Ref #2158.\n            \"\"\"\n\n    dist = MinimalDistribution(attrs)\n\n    # Honor setup.cfg's options.\n    dist.parse_config_files(ignore_option_errors=True)\n    if dist.setup_requires:\n        dist.fetch_build_eggs(dist.setup_requires)\n\n\ndef setup(**attrs):\n    # Make sure we have any requirements needed to interpret 'attrs'.\n    logging.configure()\n    _install_setup_requires(attrs)\n    return distutils.core.setup(**attrs)\n\n\nsetup.__doc__ = distutils.core.setup.__doc__\n\n\n_Command = monkey.get_unpatched(distutils.core.Command)\n\n\nclass Command(_Command):\n    \"\"\"\n    Setuptools internal actions are organized using a *command design pattern*.\n    This means that each action (or group of closely related actions) executed during\n    the build should be implemented as a ``Command`` subclass.\n\n    These commands are abstractions and do not necessarily correspond to a command that\n    can (or should) be executed via a terminal, in a CLI fashion (although historically\n    they would).\n\n    When creating a new command from scratch, custom defined classes **SHOULD** inherit\n    from ``setuptools.Command`` and implement a few mandatory methods.\n    Between these mandatory methods, are listed:\n\n    .. method:: initialize_options(self)\n\n        Set or (reset) all options/attributes/caches used by the command\n        to their default values. Note that these values may be overwritten during\n        the build.\n\n    .. method:: finalize_options(self)\n\n        Set final values for all options/attributes used by the command.\n        Most of the time, each option/attribute/cache should only be set if it does not\n        have any value yet (e.g. ``if self.attr is None: self.attr = val``).\n\n    .. method:: run(self)\n\n        Execute the actions intended by the command.\n        (Side effects **SHOULD** only take place when ``run`` is executed,\n        for example, creating new files or writing to the terminal output).\n\n    A useful analogy for command classes is to think of them as subroutines with local\n    variables called \"options\".  The options are \"declared\" in ``initialize_options()``\n    and \"defined\" (given their final values, aka \"finalized\") in ``finalize_options()``,\n    both of which must be defined by every command class. The \"body\" of the subroutine,\n    (where it does all the work) is the ``run()`` method.\n    Between ``initialize_options()`` and ``finalize_options()``, ``setuptools`` may set\n    the values for options/attributes based on user's input (or circumstance),\n    which means that the implementation should be careful to not overwrite values in\n    ``finalize_options`` unless necessary.\n\n    Please note that other commands (or other parts of setuptools) may also overwrite\n    the values of the command's options/attributes multiple times during the build\n    process.\n    Therefore it is important to consistently implement ``initialize_options()`` and\n    ``finalize_options()``. For example, all derived attributes (or attributes that\n    depend on the value of other attributes) **SHOULD** be recomputed in\n    ``finalize_options``.\n\n    When overwriting existing commands, custom defined classes **MUST** abide by the\n    same APIs implemented by the original class. They also **SHOULD** inherit from the\n    original class.\n    \"\"\"\n\n    command_consumes_arguments = False\n\n    def __init__(self, dist, **kw):\n        \"\"\"\n        Construct the command for dist, updating\n        vars(self) with any keyword parameters.\n        \"\"\"\n        super().__init__(dist)\n        vars(self).update(kw)\n\n    def _ensure_stringlike(self, option, what, default=None):\n        val = getattr(self, option)\n        if val is None:\n            setattr(self, option, default)\n            return default\n        elif not isinstance(val, str):\n            raise DistutilsOptionError(\n                \"'%s' must be a %s (got `%s`)\" % (option, what, val)\n            )\n        return val\n\n    def ensure_string_list(self, option):\n        r\"\"\"Ensure that 'option' is a list of strings.  If 'option' is\n        currently a string, we split it either on /,\\s*/ or /\\s+/, so\n        \"foo bar baz\", \"foo,bar,baz\", and \"foo,   bar baz\" all become\n        [\"foo\", \"bar\", \"baz\"].\n\n        ..\n           TODO: This method seems to be similar to the one in ``distutils.cmd``\n           Probably it is just here for backward compatibility with old Python versions?\n\n        :meta private:\n        \"\"\"\n        val = getattr(self, option)\n        if val is None:\n            return\n        elif isinstance(val, str):\n            setattr(self, option, re.split(r',\\s*|\\s+', val))\n        else:\n            if isinstance(val, list):\n                ok = all(isinstance(v, str) for v in val)\n            else:\n                ok = False\n            if not ok:\n                raise DistutilsOptionError(\n                    \"'%s' must be a list of strings (got %r)\" % (option, val)\n                )\n\n    def reinitialize_command(self, command, reinit_subcommands=0, **kw):\n        cmd = _Command.reinitialize_command(self, command, reinit_subcommands)\n        vars(cmd).update(kw)\n        return cmd\n\n\ndef _find_all_simple(path):\n    \"\"\"\n    Find all files under 'path'\n    \"\"\"\n    results = (\n        os.path.join(base, file)\n        for base, dirs, files in os.walk(path, followlinks=True)\n        for file in files\n    )\n    return filter(os.path.isfile, results)\n\n\ndef findall(dir=os.curdir):\n    \"\"\"\n    Find all files under 'dir' and return the list of full filenames.\n    Unless dir is '.', return full filenames with dir prepended.\n    \"\"\"\n    files = _find_all_simple(dir)\n    if dir == os.curdir:\n        make_rel = functools.partial(os.path.relpath, start=dir)\n        files = map(make_rel, files)\n    return list(files)\n\n\n@functools.wraps(_convert_path)\ndef convert_path(pathname):\n    from inspect import cleandoc\n\n    msg = \"\"\"\n    The function `convert_path` is considered internal and not part of the public API.\n    Its direct usage by 3rd-party packages is considered deprecated and the function\n    may be removed in the future.\n    \"\"\"\n    warnings.warn(cleandoc(msg), SetuptoolsDeprecationWarning)\n    return _convert_path(pathname)\n\n\nclass sic(str):\n    \"\"\"Treat this string as-is (https://en.wikipedia.org/wiki/Sic)\"\"\"\n\n\n# Apply monkey patches\nmonkey.patch_all()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_deprecation_warning.py",
    "content": "class SetuptoolsDeprecationWarning(Warning):\n    \"\"\"\n    Base class for warning deprecations in ``setuptools``\n\n    This class is not derived from ``DeprecationWarning``, and as such is\n    visible by default.\n    \"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/__init__.py",
    "content": "\"\"\"distutils\n\nThe main package for the Python Module Distribution Utilities.  Normally\nused from a setup script as\n\n   from distutils.core import setup\n\n   setup (...)\n\"\"\"\n\nimport sys\nimport importlib\n\n__version__ = sys.version[: sys.version.index(' ')]\n\n\ntry:\n    # Allow Debian and pkgsrc (only) to customize system\n    # behavior. Ref pypa/distutils#2 and pypa/distutils#16.\n    # This hook is deprecated and no other environments\n    # should use it.\n    importlib.import_module('_distutils_system_mod')\nexcept ImportError:\n    pass\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/_collections.py",
    "content": "import collections\nimport itertools\n\n\n# from jaraco.collections 3.5.1\nclass DictStack(list, collections.abc.Mapping):\n    \"\"\"\n    A stack of dictionaries that behaves as a view on those dictionaries,\n    giving preference to the last.\n\n    >>> stack = DictStack([dict(a=1, c=2), dict(b=2, a=2)])\n    >>> stack['a']\n    2\n    >>> stack['b']\n    2\n    >>> stack['c']\n    2\n    >>> len(stack)\n    3\n    >>> stack.push(dict(a=3))\n    >>> stack['a']\n    3\n    >>> set(stack.keys()) == set(['a', 'b', 'c'])\n    True\n    >>> set(stack.items()) == set([('a', 3), ('b', 2), ('c', 2)])\n    True\n    >>> dict(**stack) == dict(stack) == dict(a=3, c=2, b=2)\n    True\n    >>> d = stack.pop()\n    >>> stack['a']\n    2\n    >>> d = stack.pop()\n    >>> stack['a']\n    1\n    >>> stack.get('b', None)\n    >>> 'c' in stack\n    True\n    \"\"\"\n\n    def __iter__(self):\n        dicts = list.__iter__(self)\n        return iter(set(itertools.chain.from_iterable(c.keys() for c in dicts)))\n\n    def __getitem__(self, key):\n        for scope in reversed(tuple(list.__iter__(self))):\n            if key in scope:\n                return scope[key]\n        raise KeyError(key)\n\n    push = list.append\n\n    def __contains__(self, other):\n        return collections.abc.Mapping.__contains__(self, other)\n\n    def __len__(self):\n        return len(list(iter(self)))\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/_functools.py",
    "content": "import functools\n\n\n# from jaraco.functools 3.5\ndef pass_none(func):\n    \"\"\"\n    Wrap func so it's not called if its first param is None\n\n    >>> print_text = pass_none(print)\n    >>> print_text('text')\n    text\n    >>> print_text(None)\n    \"\"\"\n\n    @functools.wraps(func)\n    def wrapper(param, *args, **kwargs):\n        if param is not None:\n            return func(param, *args, **kwargs)\n\n    return wrapper\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/_macos_compat.py",
    "content": "import sys\nimport importlib\n\n\ndef bypass_compiler_fixup(cmd, args):\n    return cmd\n\n\nif sys.platform == 'darwin':\n    compiler_fixup = importlib.import_module('_osx_support').compiler_fixup\nelse:\n    compiler_fixup = bypass_compiler_fixup\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/_msvccompiler.py",
    "content": "\"\"\"distutils._msvccompiler\n\nContains MSVCCompiler, an implementation of the abstract CCompiler class\nfor Microsoft Visual Studio 2015.\n\nThe module is compatible with VS 2015 and later. You can find legacy support\nfor older versions in distutils.msvc9compiler and distutils.msvccompiler.\n\"\"\"\n\n# Written by Perry Stoll\n# hacked by Robin Becker and Thomas Heller to do a better job of\n#   finding DevStudio (through the registry)\n# ported to VS 2005 and VS 2008 by Christian Heimes\n# ported to VS 2015 by Steve Dower\n\nimport os\nimport subprocess\nimport contextlib\nimport warnings\nimport unittest.mock as mock\n\nwith contextlib.suppress(ImportError):\n    import winreg\n\nfrom distutils.errors import (\n    DistutilsExecError,\n    DistutilsPlatformError,\n    CompileError,\n    LibError,\n    LinkError,\n)\nfrom distutils.ccompiler import CCompiler, gen_lib_options\nfrom distutils import log\nfrom distutils.util import get_platform\n\nfrom itertools import count\n\n\ndef _find_vc2015():\n    try:\n        key = winreg.OpenKeyEx(\n            winreg.HKEY_LOCAL_MACHINE,\n            r\"Software\\Microsoft\\VisualStudio\\SxS\\VC7\",\n            access=winreg.KEY_READ | winreg.KEY_WOW64_32KEY,\n        )\n    except OSError:\n        log.debug(\"Visual C++ is not registered\")\n        return None, None\n\n    best_version = 0\n    best_dir = None\n    with key:\n        for i in count():\n            try:\n                v, vc_dir, vt = winreg.EnumValue(key, i)\n            except OSError:\n                break\n            if v and vt == winreg.REG_SZ and os.path.isdir(vc_dir):\n                try:\n                    version = int(float(v))\n                except (ValueError, TypeError):\n                    continue\n                if version >= 14 and version > best_version:\n                    best_version, best_dir = version, vc_dir\n    return best_version, best_dir\n\n\ndef _find_vc2017():\n    \"\"\"Returns \"15, path\" based on the result of invoking vswhere.exe\n    If no install is found, returns \"None, None\"\n\n    The version is returned to avoid unnecessarily changing the function\n    result. It may be ignored when the path is not None.\n\n    If vswhere.exe is not available, by definition, VS 2017 is not\n    installed.\n    \"\"\"\n    root = os.environ.get(\"ProgramFiles(x86)\") or os.environ.get(\"ProgramFiles\")\n    if not root:\n        return None, None\n\n    try:\n        path = subprocess.check_output(\n            [\n                os.path.join(\n                    root, \"Microsoft Visual Studio\", \"Installer\", \"vswhere.exe\"\n                ),\n                \"-latest\",\n                \"-prerelease\",\n                \"-requires\",\n                \"Microsoft.VisualStudio.Component.VC.Tools.x86.x64\",\n                \"-property\",\n                \"installationPath\",\n                \"-products\",\n                \"*\",\n            ],\n            encoding=\"mbcs\",\n            errors=\"strict\",\n        ).strip()\n    except (subprocess.CalledProcessError, OSError, UnicodeDecodeError):\n        return None, None\n\n    path = os.path.join(path, \"VC\", \"Auxiliary\", \"Build\")\n    if os.path.isdir(path):\n        return 15, path\n\n    return None, None\n\n\nPLAT_SPEC_TO_RUNTIME = {\n    'x86': 'x86',\n    'x86_amd64': 'x64',\n    'x86_arm': 'arm',\n    'x86_arm64': 'arm64',\n}\n\n\ndef _find_vcvarsall(plat_spec):\n    # bpo-38597: Removed vcruntime return value\n    _, best_dir = _find_vc2017()\n\n    if not best_dir:\n        best_version, best_dir = _find_vc2015()\n\n    if not best_dir:\n        log.debug(\"No suitable Visual C++ version found\")\n        return None, None\n\n    vcvarsall = os.path.join(best_dir, \"vcvarsall.bat\")\n    if not os.path.isfile(vcvarsall):\n        log.debug(\"%s cannot be found\", vcvarsall)\n        return None, None\n\n    return vcvarsall, None\n\n\ndef _get_vc_env(plat_spec):\n    if os.getenv(\"DISTUTILS_USE_SDK\"):\n        return {key.lower(): value for key, value in os.environ.items()}\n\n    vcvarsall, _ = _find_vcvarsall(plat_spec)\n    if not vcvarsall:\n        raise DistutilsPlatformError(\"Unable to find vcvarsall.bat\")\n\n    try:\n        out = subprocess.check_output(\n            f'cmd /u /c \"{vcvarsall}\" {plat_spec} && set',\n            stderr=subprocess.STDOUT,\n        ).decode('utf-16le', errors='replace')\n    except subprocess.CalledProcessError as exc:\n        log.error(exc.output)\n        raise DistutilsPlatformError(f\"Error executing {exc.cmd}\")\n\n    env = {\n        key.lower(): value\n        for key, _, value in (line.partition('=') for line in out.splitlines())\n        if key and value\n    }\n\n    return env\n\n\ndef _find_exe(exe, paths=None):\n    \"\"\"Return path to an MSVC executable program.\n\n    Tries to find the program in several places: first, one of the\n    MSVC program search paths from the registry; next, the directories\n    in the PATH environment variable.  If any of those work, return an\n    absolute path that is known to exist.  If none of them work, just\n    return the original program name, 'exe'.\n    \"\"\"\n    if not paths:\n        paths = os.getenv('path').split(os.pathsep)\n    for p in paths:\n        fn = os.path.join(os.path.abspath(p), exe)\n        if os.path.isfile(fn):\n            return fn\n    return exe\n\n\n# A map keyed by get_platform() return values to values accepted by\n# 'vcvarsall.bat'. Always cross-compile from x86 to work with the\n# lighter-weight MSVC installs that do not include native 64-bit tools.\nPLAT_TO_VCVARS = {\n    'win32': 'x86',\n    'win-amd64': 'x86_amd64',\n    'win-arm32': 'x86_arm',\n    'win-arm64': 'x86_arm64',\n}\n\n\nclass MSVCCompiler(CCompiler):\n    \"\"\"Concrete class that implements an interface to Microsoft Visual C++,\n    as defined by the CCompiler abstract class.\"\"\"\n\n    compiler_type = 'msvc'\n\n    # Just set this so CCompiler's constructor doesn't barf.  We currently\n    # don't use the 'set_executables()' bureaucracy provided by CCompiler,\n    # as it really isn't necessary for this sort of single-compiler class.\n    # Would be nice to have a consistent interface with UnixCCompiler,\n    # though, so it's worth thinking about.\n    executables = {}\n\n    # Private class data (need to distinguish C from C++ source for compiler)\n    _c_extensions = ['.c']\n    _cpp_extensions = ['.cc', '.cpp', '.cxx']\n    _rc_extensions = ['.rc']\n    _mc_extensions = ['.mc']\n\n    # Needed for the filename generation methods provided by the\n    # base class, CCompiler.\n    src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions\n    res_extension = '.res'\n    obj_extension = '.obj'\n    static_lib_extension = '.lib'\n    shared_lib_extension = '.dll'\n    static_lib_format = shared_lib_format = '%s%s'\n    exe_extension = '.exe'\n\n    def __init__(self, verbose=0, dry_run=0, force=0):\n        super().__init__(verbose, dry_run, force)\n        # target platform (.plat_name is consistent with 'bdist')\n        self.plat_name = None\n        self.initialized = False\n\n    @classmethod\n    def _configure(cls, vc_env):\n        \"\"\"\n        Set class-level include/lib dirs.\n        \"\"\"\n        cls.include_dirs = cls._parse_path(vc_env.get('include', ''))\n        cls.library_dirs = cls._parse_path(vc_env.get('lib', ''))\n\n    @staticmethod\n    def _parse_path(val):\n        return [dir.rstrip(os.sep) for dir in val.split(os.pathsep) if dir]\n\n    def initialize(self, plat_name=None):\n        # multi-init means we would need to check platform same each time...\n        assert not self.initialized, \"don't init multiple times\"\n        if plat_name is None:\n            plat_name = get_platform()\n        # sanity check for platforms to prevent obscure errors later.\n        if plat_name not in PLAT_TO_VCVARS:\n            raise DistutilsPlatformError(\n                f\"--plat-name must be one of {tuple(PLAT_TO_VCVARS)}\"\n            )\n\n        # Get the vcvarsall.bat spec for the requested platform.\n        plat_spec = PLAT_TO_VCVARS[plat_name]\n\n        vc_env = _get_vc_env(plat_spec)\n        if not vc_env:\n            raise DistutilsPlatformError(\n                \"Unable to find a compatible \" \"Visual Studio installation.\"\n            )\n        self._configure(vc_env)\n\n        self._paths = vc_env.get('path', '')\n        paths = self._paths.split(os.pathsep)\n        self.cc = _find_exe(\"cl.exe\", paths)\n        self.linker = _find_exe(\"link.exe\", paths)\n        self.lib = _find_exe(\"lib.exe\", paths)\n        self.rc = _find_exe(\"rc.exe\", paths)  # resource compiler\n        self.mc = _find_exe(\"mc.exe\", paths)  # message compiler\n        self.mt = _find_exe(\"mt.exe\", paths)  # message compiler\n\n        self.preprocess_options = None\n        # bpo-38597: Always compile with dynamic linking\n        # Future releases of Python 3.x will include all past\n        # versions of vcruntime*.dll for compatibility.\n        self.compile_options = ['/nologo', '/O2', '/W3', '/GL', '/DNDEBUG', '/MD']\n\n        self.compile_options_debug = [\n            '/nologo',\n            '/Od',\n            '/MDd',\n            '/Zi',\n            '/W3',\n            '/D_DEBUG',\n        ]\n\n        ldflags = ['/nologo', '/INCREMENTAL:NO', '/LTCG']\n\n        ldflags_debug = ['/nologo', '/INCREMENTAL:NO', '/LTCG', '/DEBUG:FULL']\n\n        self.ldflags_exe = [*ldflags, '/MANIFEST:EMBED,ID=1']\n        self.ldflags_exe_debug = [*ldflags_debug, '/MANIFEST:EMBED,ID=1']\n        self.ldflags_shared = [\n            *ldflags,\n            '/DLL',\n            '/MANIFEST:EMBED,ID=2',\n            '/MANIFESTUAC:NO',\n        ]\n        self.ldflags_shared_debug = [\n            *ldflags_debug,\n            '/DLL',\n            '/MANIFEST:EMBED,ID=2',\n            '/MANIFESTUAC:NO',\n        ]\n        self.ldflags_static = [*ldflags]\n        self.ldflags_static_debug = [*ldflags_debug]\n\n        self._ldflags = {\n            (CCompiler.EXECUTABLE, None): self.ldflags_exe,\n            (CCompiler.EXECUTABLE, False): self.ldflags_exe,\n            (CCompiler.EXECUTABLE, True): self.ldflags_exe_debug,\n            (CCompiler.SHARED_OBJECT, None): self.ldflags_shared,\n            (CCompiler.SHARED_OBJECT, False): self.ldflags_shared,\n            (CCompiler.SHARED_OBJECT, True): self.ldflags_shared_debug,\n            (CCompiler.SHARED_LIBRARY, None): self.ldflags_static,\n            (CCompiler.SHARED_LIBRARY, False): self.ldflags_static,\n            (CCompiler.SHARED_LIBRARY, True): self.ldflags_static_debug,\n        }\n\n        self.initialized = True\n\n    # -- Worker methods ------------------------------------------------\n\n    @property\n    def out_extensions(self):\n        return {\n            **super().out_extensions,\n            **{\n                ext: self.res_extension\n                for ext in self._rc_extensions + self._mc_extensions\n            },\n        }\n\n    def compile(  # noqa: C901\n        self,\n        sources,\n        output_dir=None,\n        macros=None,\n        include_dirs=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        depends=None,\n    ):\n\n        if not self.initialized:\n            self.initialize()\n        compile_info = self._setup_compile(\n            output_dir, macros, include_dirs, sources, depends, extra_postargs\n        )\n        macros, objects, extra_postargs, pp_opts, build = compile_info\n\n        compile_opts = extra_preargs or []\n        compile_opts.append('/c')\n        if debug:\n            compile_opts.extend(self.compile_options_debug)\n        else:\n            compile_opts.extend(self.compile_options)\n\n        add_cpp_opts = False\n\n        for obj in objects:\n            try:\n                src, ext = build[obj]\n            except KeyError:\n                continue\n            if debug:\n                # pass the full pathname to MSVC in debug mode,\n                # this allows the debugger to find the source file\n                # without asking the user to browse for it\n                src = os.path.abspath(src)\n\n            if ext in self._c_extensions:\n                input_opt = \"/Tc\" + src\n            elif ext in self._cpp_extensions:\n                input_opt = \"/Tp\" + src\n                add_cpp_opts = True\n            elif ext in self._rc_extensions:\n                # compile .RC to .RES file\n                input_opt = src\n                output_opt = \"/fo\" + obj\n                try:\n                    self.spawn([self.rc] + pp_opts + [output_opt, input_opt])\n                except DistutilsExecError as msg:\n                    raise CompileError(msg)\n                continue\n            elif ext in self._mc_extensions:\n                # Compile .MC to .RC file to .RES file.\n                #   * '-h dir' specifies the directory for the\n                #     generated include file\n                #   * '-r dir' specifies the target directory of the\n                #     generated RC file and the binary message resource\n                #     it includes\n                #\n                # For now (since there are no options to change this),\n                # we use the source-directory for the include file and\n                # the build directory for the RC file and message\n                # resources. This works at least for win32all.\n                h_dir = os.path.dirname(src)\n                rc_dir = os.path.dirname(obj)\n                try:\n                    # first compile .MC to .RC and .H file\n                    self.spawn([self.mc, '-h', h_dir, '-r', rc_dir, src])\n                    base, _ = os.path.splitext(os.path.basename(src))\n                    rc_file = os.path.join(rc_dir, base + '.rc')\n                    # then compile .RC to .RES file\n                    self.spawn([self.rc, \"/fo\" + obj, rc_file])\n\n                except DistutilsExecError as msg:\n                    raise CompileError(msg)\n                continue\n            else:\n                # how to handle this file?\n                raise CompileError(f\"Don't know how to compile {src} to {obj}\")\n\n            args = [self.cc] + compile_opts + pp_opts\n            if add_cpp_opts:\n                args.append('/EHsc')\n            args.append(input_opt)\n            args.append(\"/Fo\" + obj)\n            args.extend(extra_postargs)\n\n            try:\n                self.spawn(args)\n            except DistutilsExecError as msg:\n                raise CompileError(msg)\n\n        return objects\n\n    def create_static_lib(\n        self, objects, output_libname, output_dir=None, debug=0, target_lang=None\n    ):\n\n        if not self.initialized:\n            self.initialize()\n        objects, output_dir = self._fix_object_args(objects, output_dir)\n        output_filename = self.library_filename(output_libname, output_dir=output_dir)\n\n        if self._need_link(objects, output_filename):\n            lib_args = objects + ['/OUT:' + output_filename]\n            if debug:\n                pass  # XXX what goes here?\n            try:\n                log.debug('Executing \"%s\" %s', self.lib, ' '.join(lib_args))\n                self.spawn([self.lib] + lib_args)\n            except DistutilsExecError as msg:\n                raise LibError(msg)\n        else:\n            log.debug(\"skipping %s (up-to-date)\", output_filename)\n\n    def link(\n        self,\n        target_desc,\n        objects,\n        output_filename,\n        output_dir=None,\n        libraries=None,\n        library_dirs=None,\n        runtime_library_dirs=None,\n        export_symbols=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        build_temp=None,\n        target_lang=None,\n    ):\n\n        if not self.initialized:\n            self.initialize()\n        objects, output_dir = self._fix_object_args(objects, output_dir)\n        fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)\n        libraries, library_dirs, runtime_library_dirs = fixed_args\n\n        if runtime_library_dirs:\n            self.warn(\n                \"I don't know what to do with 'runtime_library_dirs': \"\n                + str(runtime_library_dirs)\n            )\n\n        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)\n        if output_dir is not None:\n            output_filename = os.path.join(output_dir, output_filename)\n\n        if self._need_link(objects, output_filename):\n            ldflags = self._ldflags[target_desc, debug]\n\n            export_opts = [\"/EXPORT:\" + sym for sym in (export_symbols or [])]\n\n            ld_args = (\n                ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]\n            )\n\n            # The MSVC linker generates .lib and .exp files, which cannot be\n            # suppressed by any linker switches. The .lib files may even be\n            # needed! Make sure they are generated in the temporary build\n            # directory. Since they have different names for debug and release\n            # builds, they can go into the same directory.\n            build_temp = os.path.dirname(objects[0])\n            if export_symbols is not None:\n                (dll_name, dll_ext) = os.path.splitext(\n                    os.path.basename(output_filename)\n                )\n                implib_file = os.path.join(build_temp, self.library_filename(dll_name))\n                ld_args.append('/IMPLIB:' + implib_file)\n\n            if extra_preargs:\n                ld_args[:0] = extra_preargs\n            if extra_postargs:\n                ld_args.extend(extra_postargs)\n\n            output_dir = os.path.dirname(os.path.abspath(output_filename))\n            self.mkpath(output_dir)\n            try:\n                log.debug('Executing \"%s\" %s', self.linker, ' '.join(ld_args))\n                self.spawn([self.linker] + ld_args)\n            except DistutilsExecError as msg:\n                raise LinkError(msg)\n        else:\n            log.debug(\"skipping %s (up-to-date)\", output_filename)\n\n    def spawn(self, cmd):\n        env = dict(os.environ, PATH=self._paths)\n        with self._fallback_spawn(cmd, env) as fallback:\n            return super().spawn(cmd, env=env)\n        return fallback.value\n\n    @contextlib.contextmanager\n    def _fallback_spawn(self, cmd, env):\n        \"\"\"\n        Discovered in pypa/distutils#15, some tools monkeypatch the compiler,\n        so the 'env' kwarg causes a TypeError. Detect this condition and\n        restore the legacy, unsafe behavior.\n        \"\"\"\n        bag = type('Bag', (), {})()\n        try:\n            yield bag\n        except TypeError as exc:\n            if \"unexpected keyword argument 'env'\" not in str(exc):\n                raise\n        else:\n            return\n        warnings.warn(\"Fallback spawn triggered. Please update distutils monkeypatch.\")\n        with mock.patch.dict('os.environ', env):\n            bag.value = super().spawn(cmd)\n\n    # -- Miscellaneous methods -----------------------------------------\n    # These are all used by the 'gen_lib_options() function, in\n    # ccompiler.py.\n\n    def library_dir_option(self, dir):\n        return \"/LIBPATH:\" + dir\n\n    def runtime_library_dir_option(self, dir):\n        raise DistutilsPlatformError(\n            \"don't know how to set runtime library search path for MSVC\"\n        )\n\n    def library_option(self, lib):\n        return self.library_filename(lib)\n\n    def find_library_file(self, dirs, lib, debug=0):\n        # Prefer a debugging library if found (and requested), but deal\n        # with it if we don't have one.\n        if debug:\n            try_names = [lib + \"_d\", lib]\n        else:\n            try_names = [lib]\n        for dir in dirs:\n            for name in try_names:\n                libfile = os.path.join(dir, self.library_filename(name))\n                if os.path.isfile(libfile):\n                    return libfile\n        else:\n            # Oops, didn't find it in *any* of 'dirs'\n            return None\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/archive_util.py",
    "content": "\"\"\"distutils.archive_util\n\nUtility functions for creating archive files (tarballs, zip files,\nthat sort of thing).\"\"\"\n\nimport os\nfrom warnings import warn\nimport sys\n\ntry:\n    import zipfile\nexcept ImportError:\n    zipfile = None\n\n\nfrom distutils.errors import DistutilsExecError\nfrom distutils.spawn import spawn\nfrom distutils.dir_util import mkpath\nfrom distutils import log\n\ntry:\n    from pwd import getpwnam\nexcept ImportError:\n    getpwnam = None\n\ntry:\n    from grp import getgrnam\nexcept ImportError:\n    getgrnam = None\n\n\ndef _get_gid(name):\n    \"\"\"Returns a gid, given a group name.\"\"\"\n    if getgrnam is None or name is None:\n        return None\n    try:\n        result = getgrnam(name)\n    except KeyError:\n        result = None\n    if result is not None:\n        return result[2]\n    return None\n\n\ndef _get_uid(name):\n    \"\"\"Returns an uid, given a user name.\"\"\"\n    if getpwnam is None or name is None:\n        return None\n    try:\n        result = getpwnam(name)\n    except KeyError:\n        result = None\n    if result is not None:\n        return result[2]\n    return None\n\n\ndef make_tarball(\n    base_name, base_dir, compress=\"gzip\", verbose=0, dry_run=0, owner=None, group=None\n):\n    \"\"\"Create a (possibly compressed) tar file from all the files under\n    'base_dir'.\n\n    'compress' must be \"gzip\" (the default), \"bzip2\", \"xz\", \"compress\", or\n    None.  (\"compress\" will be deprecated in Python 3.2)\n\n    'owner' and 'group' can be used to define an owner and a group for the\n    archive that is being built. If not provided, the current owner and group\n    will be used.\n\n    The output tar file will be named 'base_dir' +  \".tar\", possibly plus\n    the appropriate compression extension (\".gz\", \".bz2\", \".xz\" or \".Z\").\n\n    Returns the output filename.\n    \"\"\"\n    tar_compression = {\n        'gzip': 'gz',\n        'bzip2': 'bz2',\n        'xz': 'xz',\n        None: '',\n        'compress': '',\n    }\n    compress_ext = {'gzip': '.gz', 'bzip2': '.bz2', 'xz': '.xz', 'compress': '.Z'}\n\n    # flags for compression program, each element of list will be an argument\n    if compress is not None and compress not in compress_ext.keys():\n        raise ValueError(\n            \"bad value for 'compress': must be None, 'gzip', 'bzip2', \"\n            \"'xz' or 'compress'\"\n        )\n\n    archive_name = base_name + '.tar'\n    if compress != 'compress':\n        archive_name += compress_ext.get(compress, '')\n\n    mkpath(os.path.dirname(archive_name), dry_run=dry_run)\n\n    # creating the tarball\n    import tarfile  # late import so Python build itself doesn't break\n\n    log.info('Creating tar archive')\n\n    uid = _get_uid(owner)\n    gid = _get_gid(group)\n\n    def _set_uid_gid(tarinfo):\n        if gid is not None:\n            tarinfo.gid = gid\n            tarinfo.gname = group\n        if uid is not None:\n            tarinfo.uid = uid\n            tarinfo.uname = owner\n        return tarinfo\n\n    if not dry_run:\n        tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])\n        try:\n            tar.add(base_dir, filter=_set_uid_gid)\n        finally:\n            tar.close()\n\n    # compression using `compress`\n    if compress == 'compress':\n        warn(\"'compress' is deprecated.\", DeprecationWarning)\n        # the option varies depending on the platform\n        compressed_name = archive_name + compress_ext[compress]\n        if sys.platform == 'win32':\n            cmd = [compress, archive_name, compressed_name]\n        else:\n            cmd = [compress, '-f', archive_name]\n        spawn(cmd, dry_run=dry_run)\n        return compressed_name\n\n    return archive_name\n\n\ndef make_zipfile(base_name, base_dir, verbose=0, dry_run=0):  # noqa: C901\n    \"\"\"Create a zip file from all the files under 'base_dir'.\n\n    The output zip file will be named 'base_name' + \".zip\".  Uses either the\n    \"zipfile\" Python module (if available) or the InfoZIP \"zip\" utility\n    (if installed and found on the default search path).  If neither tool is\n    available, raises DistutilsExecError.  Returns the name of the output zip\n    file.\n    \"\"\"\n    zip_filename = base_name + \".zip\"\n    mkpath(os.path.dirname(zip_filename), dry_run=dry_run)\n\n    # If zipfile module is not available, try spawning an external\n    # 'zip' command.\n    if zipfile is None:\n        if verbose:\n            zipoptions = \"-r\"\n        else:\n            zipoptions = \"-rq\"\n\n        try:\n            spawn([\"zip\", zipoptions, zip_filename, base_dir], dry_run=dry_run)\n        except DistutilsExecError:\n            # XXX really should distinguish between \"couldn't find\n            # external 'zip' command\" and \"zip failed\".\n            raise DistutilsExecError(\n                (\n                    \"unable to create zip file '%s': \"\n                    \"could neither import the 'zipfile' module nor \"\n                    \"find a standalone zip utility\"\n                )\n                % zip_filename\n            )\n\n    else:\n        log.info(\"creating '%s' and adding '%s' to it\", zip_filename, base_dir)\n\n        if not dry_run:\n            try:\n                zip = zipfile.ZipFile(\n                    zip_filename, \"w\", compression=zipfile.ZIP_DEFLATED\n                )\n            except RuntimeError:\n                zip = zipfile.ZipFile(zip_filename, \"w\", compression=zipfile.ZIP_STORED)\n\n            with zip:\n                if base_dir != os.curdir:\n                    path = os.path.normpath(os.path.join(base_dir, ''))\n                    zip.write(path, path)\n                    log.info(\"adding '%s'\", path)\n                for dirpath, dirnames, filenames in os.walk(base_dir):\n                    for name in dirnames:\n                        path = os.path.normpath(os.path.join(dirpath, name, ''))\n                        zip.write(path, path)\n                        log.info(\"adding '%s'\", path)\n                    for name in filenames:\n                        path = os.path.normpath(os.path.join(dirpath, name))\n                        if os.path.isfile(path):\n                            zip.write(path, path)\n                            log.info(\"adding '%s'\", path)\n\n    return zip_filename\n\n\nARCHIVE_FORMATS = {\n    'gztar': (make_tarball, [('compress', 'gzip')], \"gzip'ed tar-file\"),\n    'bztar': (make_tarball, [('compress', 'bzip2')], \"bzip2'ed tar-file\"),\n    'xztar': (make_tarball, [('compress', 'xz')], \"xz'ed tar-file\"),\n    'ztar': (make_tarball, [('compress', 'compress')], \"compressed tar file\"),\n    'tar': (make_tarball, [('compress', None)], \"uncompressed tar file\"),\n    'zip': (make_zipfile, [], \"ZIP file\"),\n}\n\n\ndef check_archive_formats(formats):\n    \"\"\"Returns the first format from the 'format' list that is unknown.\n\n    If all formats are known, returns None\n    \"\"\"\n    for format in formats:\n        if format not in ARCHIVE_FORMATS:\n            return format\n    return None\n\n\ndef make_archive(\n    base_name,\n    format,\n    root_dir=None,\n    base_dir=None,\n    verbose=0,\n    dry_run=0,\n    owner=None,\n    group=None,\n):\n    \"\"\"Create an archive file (eg. zip or tar).\n\n    'base_name' is the name of the file to create, minus any format-specific\n    extension; 'format' is the archive format: one of \"zip\", \"tar\", \"gztar\",\n    \"bztar\", \"xztar\", or \"ztar\".\n\n    'root_dir' is a directory that will be the root directory of the\n    archive; ie. we typically chdir into 'root_dir' before creating the\n    archive.  'base_dir' is the directory where we start archiving from;\n    ie. 'base_dir' will be the common prefix of all files and\n    directories in the archive.  'root_dir' and 'base_dir' both default\n    to the current directory.  Returns the name of the archive file.\n\n    'owner' and 'group' are used when creating a tar archive. By default,\n    uses the current owner and group.\n    \"\"\"\n    save_cwd = os.getcwd()\n    if root_dir is not None:\n        log.debug(\"changing into '%s'\", root_dir)\n        base_name = os.path.abspath(base_name)\n        if not dry_run:\n            os.chdir(root_dir)\n\n    if base_dir is None:\n        base_dir = os.curdir\n\n    kwargs = {'dry_run': dry_run}\n\n    try:\n        format_info = ARCHIVE_FORMATS[format]\n    except KeyError:\n        raise ValueError(\"unknown archive format '%s'\" % format)\n\n    func = format_info[0]\n    for arg, val in format_info[1]:\n        kwargs[arg] = val\n\n    if format != 'zip':\n        kwargs['owner'] = owner\n        kwargs['group'] = group\n\n    try:\n        filename = func(base_name, base_dir, **kwargs)\n    finally:\n        if root_dir is not None:\n            log.debug(\"changing back to '%s'\", save_cwd)\n            os.chdir(save_cwd)\n\n    return filename\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/bcppcompiler.py",
    "content": "\"\"\"distutils.bcppcompiler\n\nContains BorlandCCompiler, an implementation of the abstract CCompiler class\nfor the Borland C++ compiler.\n\"\"\"\n\n# This implementation by Lyle Johnson, based on the original msvccompiler.py\n# module and using the directions originally published by Gordon Williams.\n\n# XXX looks like there's a LOT of overlap between these two classes:\n# someone should sit down and factor out the common code as\n# WindowsCCompiler!  --GPW\n\n\nimport os\nimport warnings\n\nfrom distutils.errors import (\n    DistutilsExecError,\n    CompileError,\n    LibError,\n    LinkError,\n    UnknownFileError,\n)\nfrom distutils.ccompiler import CCompiler, gen_preprocess_options\nfrom distutils.file_util import write_file\nfrom distutils.dep_util import newer\nfrom distutils import log\n\n\nwarnings.warn(\n    \"bcppcompiler is deprecated and slated to be removed \"\n    \"in the future. Please discontinue use or file an issue \"\n    \"with pypa/distutils describing your use case.\",\n    DeprecationWarning,\n)\n\n\nclass BCPPCompiler(CCompiler):\n    \"\"\"Concrete class that implements an interface to the Borland C/C++\n    compiler, as defined by the CCompiler abstract class.\n    \"\"\"\n\n    compiler_type = 'bcpp'\n\n    # Just set this so CCompiler's constructor doesn't barf.  We currently\n    # don't use the 'set_executables()' bureaucracy provided by CCompiler,\n    # as it really isn't necessary for this sort of single-compiler class.\n    # Would be nice to have a consistent interface with UnixCCompiler,\n    # though, so it's worth thinking about.\n    executables = {}\n\n    # Private class data (need to distinguish C from C++ source for compiler)\n    _c_extensions = ['.c']\n    _cpp_extensions = ['.cc', '.cpp', '.cxx']\n\n    # Needed for the filename generation methods provided by the\n    # base class, CCompiler.\n    src_extensions = _c_extensions + _cpp_extensions\n    obj_extension = '.obj'\n    static_lib_extension = '.lib'\n    shared_lib_extension = '.dll'\n    static_lib_format = shared_lib_format = '%s%s'\n    exe_extension = '.exe'\n\n    def __init__(self, verbose=0, dry_run=0, force=0):\n\n        super().__init__(verbose, dry_run, force)\n\n        # These executables are assumed to all be in the path.\n        # Borland doesn't seem to use any special registry settings to\n        # indicate their installation locations.\n\n        self.cc = \"bcc32.exe\"\n        self.linker = \"ilink32.exe\"\n        self.lib = \"tlib.exe\"\n\n        self.preprocess_options = None\n        self.compile_options = ['/tWM', '/O2', '/q', '/g0']\n        self.compile_options_debug = ['/tWM', '/Od', '/q', '/g0']\n\n        self.ldflags_shared = ['/Tpd', '/Gn', '/q', '/x']\n        self.ldflags_shared_debug = ['/Tpd', '/Gn', '/q', '/x']\n        self.ldflags_static = []\n        self.ldflags_exe = ['/Gn', '/q', '/x']\n        self.ldflags_exe_debug = ['/Gn', '/q', '/x', '/r']\n\n    # -- Worker methods ------------------------------------------------\n\n    def compile(  # noqa: C901\n        self,\n        sources,\n        output_dir=None,\n        macros=None,\n        include_dirs=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        depends=None,\n    ):\n\n        macros, objects, extra_postargs, pp_opts, build = self._setup_compile(\n            output_dir, macros, include_dirs, sources, depends, extra_postargs\n        )\n        compile_opts = extra_preargs or []\n        compile_opts.append('-c')\n        if debug:\n            compile_opts.extend(self.compile_options_debug)\n        else:\n            compile_opts.extend(self.compile_options)\n\n        for obj in objects:\n            try:\n                src, ext = build[obj]\n            except KeyError:\n                continue\n            # XXX why do the normpath here?\n            src = os.path.normpath(src)\n            obj = os.path.normpath(obj)\n            # XXX _setup_compile() did a mkpath() too but before the normpath.\n            # Is it possible to skip the normpath?\n            self.mkpath(os.path.dirname(obj))\n\n            if ext == '.res':\n                # This is already a binary file -- skip it.\n                continue  # the 'for' loop\n            if ext == '.rc':\n                # This needs to be compiled to a .res file -- do it now.\n                try:\n                    self.spawn([\"brcc32\", \"-fo\", obj, src])\n                except DistutilsExecError as msg:\n                    raise CompileError(msg)\n                continue  # the 'for' loop\n\n            # The next two are both for the real compiler.\n            if ext in self._c_extensions:\n                input_opt = \"\"\n            elif ext in self._cpp_extensions:\n                input_opt = \"-P\"\n            else:\n                # Unknown file type -- no extra options.  The compiler\n                # will probably fail, but let it just in case this is a\n                # file the compiler recognizes even if we don't.\n                input_opt = \"\"\n\n            output_opt = \"-o\" + obj\n\n            # Compiler command line syntax is: \"bcc32 [options] file(s)\".\n            # Note that the source file names must appear at the end of\n            # the command line.\n            try:\n                self.spawn(\n                    [self.cc]\n                    + compile_opts\n                    + pp_opts\n                    + [input_opt, output_opt]\n                    + extra_postargs\n                    + [src]\n                )\n            except DistutilsExecError as msg:\n                raise CompileError(msg)\n\n        return objects\n\n    # compile ()\n\n    def create_static_lib(\n        self, objects, output_libname, output_dir=None, debug=0, target_lang=None\n    ):\n\n        (objects, output_dir) = self._fix_object_args(objects, output_dir)\n        output_filename = self.library_filename(output_libname, output_dir=output_dir)\n\n        if self._need_link(objects, output_filename):\n            lib_args = [output_filename, '/u'] + objects\n            if debug:\n                pass  # XXX what goes here?\n            try:\n                self.spawn([self.lib] + lib_args)\n            except DistutilsExecError as msg:\n                raise LibError(msg)\n        else:\n            log.debug(\"skipping %s (up-to-date)\", output_filename)\n\n    # create_static_lib ()\n\n    def link(  # noqa: C901\n        self,\n        target_desc,\n        objects,\n        output_filename,\n        output_dir=None,\n        libraries=None,\n        library_dirs=None,\n        runtime_library_dirs=None,\n        export_symbols=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        build_temp=None,\n        target_lang=None,\n    ):\n\n        # XXX this ignores 'build_temp'!  should follow the lead of\n        # msvccompiler.py\n\n        (objects, output_dir) = self._fix_object_args(objects, output_dir)\n        (libraries, library_dirs, runtime_library_dirs) = self._fix_lib_args(\n            libraries, library_dirs, runtime_library_dirs\n        )\n\n        if runtime_library_dirs:\n            log.warn(\n                \"I don't know what to do with 'runtime_library_dirs': %s\",\n                str(runtime_library_dirs),\n            )\n\n        if output_dir is not None:\n            output_filename = os.path.join(output_dir, output_filename)\n\n        if self._need_link(objects, output_filename):\n\n            # Figure out linker args based on type of target.\n            if target_desc == CCompiler.EXECUTABLE:\n                startup_obj = 'c0w32'\n                if debug:\n                    ld_args = self.ldflags_exe_debug[:]\n                else:\n                    ld_args = self.ldflags_exe[:]\n            else:\n                startup_obj = 'c0d32'\n                if debug:\n                    ld_args = self.ldflags_shared_debug[:]\n                else:\n                    ld_args = self.ldflags_shared[:]\n\n            # Create a temporary exports file for use by the linker\n            if export_symbols is None:\n                def_file = ''\n            else:\n                head, tail = os.path.split(output_filename)\n                modname, ext = os.path.splitext(tail)\n                temp_dir = os.path.dirname(objects[0])  # preserve tree structure\n                def_file = os.path.join(temp_dir, '%s.def' % modname)\n                contents = ['EXPORTS']\n                for sym in export_symbols or []:\n                    contents.append('  {}=_{}'.format(sym, sym))\n                self.execute(write_file, (def_file, contents), \"writing %s\" % def_file)\n\n            # Borland C++ has problems with '/' in paths\n            objects2 = map(os.path.normpath, objects)\n            # split objects in .obj and .res files\n            # Borland C++ needs them at different positions in the command line\n            objects = [startup_obj]\n            resources = []\n            for file in objects2:\n                (base, ext) = os.path.splitext(os.path.normcase(file))\n                if ext == '.res':\n                    resources.append(file)\n                else:\n                    objects.append(file)\n\n            for ell in library_dirs:\n                ld_args.append(\"/L%s\" % os.path.normpath(ell))\n            ld_args.append(\"/L.\")  # we sometimes use relative paths\n\n            # list of object files\n            ld_args.extend(objects)\n\n            # XXX the command-line syntax for Borland C++ is a bit wonky;\n            # certain filenames are jammed together in one big string, but\n            # comma-delimited.  This doesn't mesh too well with the\n            # Unix-centric attitude (with a DOS/Windows quoting hack) of\n            # 'spawn()', so constructing the argument list is a bit\n            # awkward.  Note that doing the obvious thing and jamming all\n            # the filenames and commas into one argument would be wrong,\n            # because 'spawn()' would quote any filenames with spaces in\n            # them.  Arghghh!.  Apparently it works fine as coded...\n\n            # name of dll/exe file\n            ld_args.extend([',', output_filename])\n            # no map file and start libraries\n            ld_args.append(',,')\n\n            for lib in libraries:\n                # see if we find it and if there is a bcpp specific lib\n                # (xxx_bcpp.lib)\n                libfile = self.find_library_file(library_dirs, lib, debug)\n                if libfile is None:\n                    ld_args.append(lib)\n                    # probably a BCPP internal library -- don't warn\n                else:\n                    # full name which prefers bcpp_xxx.lib over xxx.lib\n                    ld_args.append(libfile)\n\n            # some default libraries\n            ld_args.append('import32')\n            ld_args.append('cw32mt')\n\n            # def file for export symbols\n            ld_args.extend([',', def_file])\n            # add resource files\n            ld_args.append(',')\n            ld_args.extend(resources)\n\n            if extra_preargs:\n                ld_args[:0] = extra_preargs\n            if extra_postargs:\n                ld_args.extend(extra_postargs)\n\n            self.mkpath(os.path.dirname(output_filename))\n            try:\n                self.spawn([self.linker] + ld_args)\n            except DistutilsExecError as msg:\n                raise LinkError(msg)\n\n        else:\n            log.debug(\"skipping %s (up-to-date)\", output_filename)\n\n    # link ()\n\n    # -- Miscellaneous methods -----------------------------------------\n\n    def find_library_file(self, dirs, lib, debug=0):\n        # List of effective library names to try, in order of preference:\n        # xxx_bcpp.lib is better than xxx.lib\n        # and xxx_d.lib is better than xxx.lib if debug is set\n        #\n        # The \"_bcpp\" suffix is to handle a Python installation for people\n        # with multiple compilers (primarily Distutils hackers, I suspect\n        # ;-).  The idea is they'd have one static library for each\n        # compiler they care about, since (almost?) every Windows compiler\n        # seems to have a different format for static libraries.\n        if debug:\n            dlib = lib + \"_d\"\n            try_names = (dlib + \"_bcpp\", lib + \"_bcpp\", dlib, lib)\n        else:\n            try_names = (lib + \"_bcpp\", lib)\n\n        for dir in dirs:\n            for name in try_names:\n                libfile = os.path.join(dir, self.library_filename(name))\n                if os.path.exists(libfile):\n                    return libfile\n        else:\n            # Oops, didn't find it in *any* of 'dirs'\n            return None\n\n    # overwrite the one from CCompiler to support rc and res-files\n    def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):\n        if output_dir is None:\n            output_dir = ''\n        obj_names = []\n        for src_name in source_filenames:\n            # use normcase to make sure '.rc' is really '.rc' and not '.RC'\n            (base, ext) = os.path.splitext(os.path.normcase(src_name))\n            if ext not in (self.src_extensions + ['.rc', '.res']):\n                raise UnknownFileError(\n                    \"unknown file type '{}' (from '{}')\".format(ext, src_name)\n                )\n            if strip_dir:\n                base = os.path.basename(base)\n            if ext == '.res':\n                # these can go unchanged\n                obj_names.append(os.path.join(output_dir, base + ext))\n            elif ext == '.rc':\n                # these need to be compiled to .res-files\n                obj_names.append(os.path.join(output_dir, base + '.res'))\n            else:\n                obj_names.append(os.path.join(output_dir, base + self.obj_extension))\n        return obj_names\n\n    # object_filenames ()\n\n    def preprocess(\n        self,\n        source,\n        output_file=None,\n        macros=None,\n        include_dirs=None,\n        extra_preargs=None,\n        extra_postargs=None,\n    ):\n\n        (_, macros, include_dirs) = self._fix_compile_args(None, macros, include_dirs)\n        pp_opts = gen_preprocess_options(macros, include_dirs)\n        pp_args = ['cpp32.exe'] + pp_opts\n        if output_file is not None:\n            pp_args.append('-o' + output_file)\n        if extra_preargs:\n            pp_args[:0] = extra_preargs\n        if extra_postargs:\n            pp_args.extend(extra_postargs)\n        pp_args.append(source)\n\n        # We need to preprocess: either we're being forced to, or the\n        # source file is newer than the target (or the target doesn't\n        # exist).\n        if self.force or output_file is None or newer(source, output_file):\n            if output_file:\n                self.mkpath(os.path.dirname(output_file))\n            try:\n                self.spawn(pp_args)\n            except DistutilsExecError as msg:\n                print(msg)\n                raise CompileError(msg)\n\n    # preprocess()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/ccompiler.py",
    "content": "\"\"\"distutils.ccompiler\n\nContains CCompiler, an abstract base class that defines the interface\nfor the Distutils compiler abstraction model.\"\"\"\n\nimport sys\nimport os\nimport re\n\nfrom distutils.errors import (\n    CompileError,\n    LinkError,\n    UnknownFileError,\n    DistutilsPlatformError,\n    DistutilsModuleError,\n)\nfrom distutils.spawn import spawn\nfrom distutils.file_util import move_file\nfrom distutils.dir_util import mkpath\nfrom distutils.dep_util import newer_group\nfrom distutils.util import split_quoted, execute\nfrom distutils import log\n\n\nclass CCompiler:\n    \"\"\"Abstract base class to define the interface that must be implemented\n    by real compiler classes.  Also has some utility methods used by\n    several compiler classes.\n\n    The basic idea behind a compiler abstraction class is that each\n    instance can be used for all the compile/link steps in building a\n    single project.  Thus, attributes common to all of those compile and\n    link steps -- include directories, macros to define, libraries to link\n    against, etc. -- are attributes of the compiler instance.  To allow for\n    variability in how individual files are treated, most of those\n    attributes may be varied on a per-compilation or per-link basis.\n    \"\"\"\n\n    # 'compiler_type' is a class attribute that identifies this class.  It\n    # keeps code that wants to know what kind of compiler it's dealing with\n    # from having to import all possible compiler classes just to do an\n    # 'isinstance'.  In concrete CCompiler subclasses, 'compiler_type'\n    # should really, really be one of the keys of the 'compiler_class'\n    # dictionary (see below -- used by the 'new_compiler()' factory\n    # function) -- authors of new compiler interface classes are\n    # responsible for updating 'compiler_class'!\n    compiler_type = None\n\n    # XXX things not handled by this compiler abstraction model:\n    #   * client can't provide additional options for a compiler,\n    #     e.g. warning, optimization, debugging flags.  Perhaps this\n    #     should be the domain of concrete compiler abstraction classes\n    #     (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base\n    #     class should have methods for the common ones.\n    #   * can't completely override the include or library searchg\n    #     path, ie. no \"cc -I -Idir1 -Idir2\" or \"cc -L -Ldir1 -Ldir2\".\n    #     I'm not sure how widely supported this is even by Unix\n    #     compilers, much less on other platforms.  And I'm even less\n    #     sure how useful it is; maybe for cross-compiling, but\n    #     support for that is a ways off.  (And anyways, cross\n    #     compilers probably have a dedicated binary with the\n    #     right paths compiled in.  I hope.)\n    #   * can't do really freaky things with the library list/library\n    #     dirs, e.g. \"-Ldir1 -lfoo -Ldir2 -lfoo\" to link against\n    #     different versions of libfoo.a in different locations.  I\n    #     think this is useless without the ability to null out the\n    #     library search path anyways.\n\n    # Subclasses that rely on the standard filename generation methods\n    # implemented below should override these; see the comment near\n    # those methods ('object_filenames()' et. al.) for details:\n    src_extensions = None  # list of strings\n    obj_extension = None  # string\n    static_lib_extension = None\n    shared_lib_extension = None  # string\n    static_lib_format = None  # format string\n    shared_lib_format = None  # prob. same as static_lib_format\n    exe_extension = None  # string\n\n    # Default language settings. language_map is used to detect a source\n    # file or Extension target language, checking source filenames.\n    # language_order is used to detect the language precedence, when deciding\n    # what language to use when mixing source types. For example, if some\n    # extension has two files with \".c\" extension, and one with \".cpp\", it\n    # is still linked as c++.\n    language_map = {\n        \".c\": \"c\",\n        \".cc\": \"c++\",\n        \".cpp\": \"c++\",\n        \".cxx\": \"c++\",\n        \".m\": \"objc\",\n    }\n    language_order = [\"c++\", \"objc\", \"c\"]\n\n    include_dirs = []\n    \"\"\"\n    include dirs specific to this compiler class\n    \"\"\"\n\n    library_dirs = []\n    \"\"\"\n    library dirs specific to this compiler class\n    \"\"\"\n\n    def __init__(self, verbose=0, dry_run=0, force=0):\n        self.dry_run = dry_run\n        self.force = force\n        self.verbose = verbose\n\n        # 'output_dir': a common output directory for object, library,\n        # shared object, and shared library files\n        self.output_dir = None\n\n        # 'macros': a list of macro definitions (or undefinitions).  A\n        # macro definition is a 2-tuple (name, value), where the value is\n        # either a string or None (no explicit value).  A macro\n        # undefinition is a 1-tuple (name,).\n        self.macros = []\n\n        # 'include_dirs': a list of directories to search for include files\n        self.include_dirs = []\n\n        # 'libraries': a list of libraries to include in any link\n        # (library names, not filenames: eg. \"foo\" not \"libfoo.a\")\n        self.libraries = []\n\n        # 'library_dirs': a list of directories to search for libraries\n        self.library_dirs = []\n\n        # 'runtime_library_dirs': a list of directories to search for\n        # shared libraries/objects at runtime\n        self.runtime_library_dirs = []\n\n        # 'objects': a list of object files (or similar, such as explicitly\n        # named library files) to include on any link\n        self.objects = []\n\n        for key in self.executables.keys():\n            self.set_executable(key, self.executables[key])\n\n    def set_executables(self, **kwargs):\n        \"\"\"Define the executables (and options for them) that will be run\n        to perform the various stages of compilation.  The exact set of\n        executables that may be specified here depends on the compiler\n        class (via the 'executables' class attribute), but most will have:\n          compiler      the C/C++ compiler\n          linker_so     linker used to create shared objects and libraries\n          linker_exe    linker used to create binary executables\n          archiver      static library creator\n\n        On platforms with a command-line (Unix, DOS/Windows), each of these\n        is a string that will be split into executable name and (optional)\n        list of arguments.  (Splitting the string is done similarly to how\n        Unix shells operate: words are delimited by spaces, but quotes and\n        backslashes can override this.  See\n        'distutils.util.split_quoted()'.)\n        \"\"\"\n\n        # Note that some CCompiler implementation classes will define class\n        # attributes 'cpp', 'cc', etc. with hard-coded executable names;\n        # this is appropriate when a compiler class is for exactly one\n        # compiler/OS combination (eg. MSVCCompiler).  Other compiler\n        # classes (UnixCCompiler, in particular) are driven by information\n        # discovered at run-time, since there are many different ways to do\n        # basically the same things with Unix C compilers.\n\n        for key in kwargs:\n            if key not in self.executables:\n                raise ValueError(\n                    \"unknown executable '%s' for class %s\"\n                    % (key, self.__class__.__name__)\n                )\n            self.set_executable(key, kwargs[key])\n\n    def set_executable(self, key, value):\n        if isinstance(value, str):\n            setattr(self, key, split_quoted(value))\n        else:\n            setattr(self, key, value)\n\n    def _find_macro(self, name):\n        i = 0\n        for defn in self.macros:\n            if defn[0] == name:\n                return i\n            i += 1\n        return None\n\n    def _check_macro_definitions(self, definitions):\n        \"\"\"Ensures that every element of 'definitions' is a valid macro\n        definition, ie. either (name,value) 2-tuple or a (name,) tuple.  Do\n        nothing if all definitions are OK, raise TypeError otherwise.\n        \"\"\"\n        for defn in definitions:\n            if not (\n                isinstance(defn, tuple)\n                and (\n                    len(defn) in (1, 2)\n                    and (isinstance(defn[1], str) or defn[1] is None)\n                )\n                and isinstance(defn[0], str)\n            ):\n                raise TypeError(\n                    (\"invalid macro definition '%s': \" % defn)\n                    + \"must be tuple (string,), (string, string), or \"\n                    + \"(string, None)\"\n                )\n\n    # -- Bookkeeping methods -------------------------------------------\n\n    def define_macro(self, name, value=None):\n        \"\"\"Define a preprocessor macro for all compilations driven by this\n        compiler object.  The optional parameter 'value' should be a\n        string; if it is not supplied, then the macro will be defined\n        without an explicit value and the exact outcome depends on the\n        compiler used (XXX true? does ANSI say anything about this?)\n        \"\"\"\n        # Delete from the list of macro definitions/undefinitions if\n        # already there (so that this one will take precedence).\n        i = self._find_macro(name)\n        if i is not None:\n            del self.macros[i]\n\n        self.macros.append((name, value))\n\n    def undefine_macro(self, name):\n        \"\"\"Undefine a preprocessor macro for all compilations driven by\n        this compiler object.  If the same macro is defined by\n        'define_macro()' and undefined by 'undefine_macro()' the last call\n        takes precedence (including multiple redefinitions or\n        undefinitions).  If the macro is redefined/undefined on a\n        per-compilation basis (ie. in the call to 'compile()'), then that\n        takes precedence.\n        \"\"\"\n        # Delete from the list of macro definitions/undefinitions if\n        # already there (so that this one will take precedence).\n        i = self._find_macro(name)\n        if i is not None:\n            del self.macros[i]\n\n        undefn = (name,)\n        self.macros.append(undefn)\n\n    def add_include_dir(self, dir):\n        \"\"\"Add 'dir' to the list of directories that will be searched for\n        header files.  The compiler is instructed to search directories in\n        the order in which they are supplied by successive calls to\n        'add_include_dir()'.\n        \"\"\"\n        self.include_dirs.append(dir)\n\n    def set_include_dirs(self, dirs):\n        \"\"\"Set the list of directories that will be searched to 'dirs' (a\n        list of strings).  Overrides any preceding calls to\n        'add_include_dir()'; subsequence calls to 'add_include_dir()' add\n        to the list passed to 'set_include_dirs()'.  This does not affect\n        any list of standard include directories that the compiler may\n        search by default.\n        \"\"\"\n        self.include_dirs = dirs[:]\n\n    def add_library(self, libname):\n        \"\"\"Add 'libname' to the list of libraries that will be included in\n        all links driven by this compiler object.  Note that 'libname'\n        should *not* be the name of a file containing a library, but the\n        name of the library itself: the actual filename will be inferred by\n        the linker, the compiler, or the compiler class (depending on the\n        platform).\n\n        The linker will be instructed to link against libraries in the\n        order they were supplied to 'add_library()' and/or\n        'set_libraries()'.  It is perfectly valid to duplicate library\n        names; the linker will be instructed to link against libraries as\n        many times as they are mentioned.\n        \"\"\"\n        self.libraries.append(libname)\n\n    def set_libraries(self, libnames):\n        \"\"\"Set the list of libraries to be included in all links driven by\n        this compiler object to 'libnames' (a list of strings).  This does\n        not affect any standard system libraries that the linker may\n        include by default.\n        \"\"\"\n        self.libraries = libnames[:]\n\n    def add_library_dir(self, dir):\n        \"\"\"Add 'dir' to the list of directories that will be searched for\n        libraries specified to 'add_library()' and 'set_libraries()'.  The\n        linker will be instructed to search for libraries in the order they\n        are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.\n        \"\"\"\n        self.library_dirs.append(dir)\n\n    def set_library_dirs(self, dirs):\n        \"\"\"Set the list of library search directories to 'dirs' (a list of\n        strings).  This does not affect any standard library search path\n        that the linker may search by default.\n        \"\"\"\n        self.library_dirs = dirs[:]\n\n    def add_runtime_library_dir(self, dir):\n        \"\"\"Add 'dir' to the list of directories that will be searched for\n        shared libraries at runtime.\n        \"\"\"\n        self.runtime_library_dirs.append(dir)\n\n    def set_runtime_library_dirs(self, dirs):\n        \"\"\"Set the list of directories to search for shared libraries at\n        runtime to 'dirs' (a list of strings).  This does not affect any\n        standard search path that the runtime linker may search by\n        default.\n        \"\"\"\n        self.runtime_library_dirs = dirs[:]\n\n    def add_link_object(self, object):\n        \"\"\"Add 'object' to the list of object files (or analogues, such as\n        explicitly named library files or the output of \"resource\n        compilers\") to be included in every link driven by this compiler\n        object.\n        \"\"\"\n        self.objects.append(object)\n\n    def set_link_objects(self, objects):\n        \"\"\"Set the list of object files (or analogues) to be included in\n        every link to 'objects'.  This does not affect any standard object\n        files that the linker may include by default (such as system\n        libraries).\n        \"\"\"\n        self.objects = objects[:]\n\n    # -- Private utility methods --------------------------------------\n    # (here for the convenience of subclasses)\n\n    # Helper method to prep compiler in subclass compile() methods\n\n    def _setup_compile(self, outdir, macros, incdirs, sources, depends, extra):\n        \"\"\"Process arguments and decide which source files to compile.\"\"\"\n        outdir, macros, incdirs = self._fix_compile_args(outdir, macros, incdirs)\n\n        if extra is None:\n            extra = []\n\n        # Get the list of expected output (object) files\n        objects = self.object_filenames(sources, strip_dir=0, output_dir=outdir)\n        assert len(objects) == len(sources)\n\n        pp_opts = gen_preprocess_options(macros, incdirs)\n\n        build = {}\n        for i in range(len(sources)):\n            src = sources[i]\n            obj = objects[i]\n            ext = os.path.splitext(src)[1]\n            self.mkpath(os.path.dirname(obj))\n            build[obj] = (src, ext)\n\n        return macros, objects, extra, pp_opts, build\n\n    def _get_cc_args(self, pp_opts, debug, before):\n        # works for unixccompiler, cygwinccompiler\n        cc_args = pp_opts + ['-c']\n        if debug:\n            cc_args[:0] = ['-g']\n        if before:\n            cc_args[:0] = before\n        return cc_args\n\n    def _fix_compile_args(self, output_dir, macros, include_dirs):\n        \"\"\"Typecheck and fix-up some of the arguments to the 'compile()'\n        method, and return fixed-up values.  Specifically: if 'output_dir'\n        is None, replaces it with 'self.output_dir'; ensures that 'macros'\n        is a list, and augments it with 'self.macros'; ensures that\n        'include_dirs' is a list, and augments it with 'self.include_dirs'.\n        Guarantees that the returned values are of the correct type,\n        i.e. for 'output_dir' either string or None, and for 'macros' and\n        'include_dirs' either list or None.\n        \"\"\"\n        if output_dir is None:\n            output_dir = self.output_dir\n        elif not isinstance(output_dir, str):\n            raise TypeError(\"'output_dir' must be a string or None\")\n\n        if macros is None:\n            macros = self.macros\n        elif isinstance(macros, list):\n            macros = macros + (self.macros or [])\n        else:\n            raise TypeError(\"'macros' (if supplied) must be a list of tuples\")\n\n        if include_dirs is None:\n            include_dirs = self.include_dirs\n        elif isinstance(include_dirs, (list, tuple)):\n            include_dirs = list(include_dirs) + (self.include_dirs or [])\n        else:\n            raise TypeError(\"'include_dirs' (if supplied) must be a list of strings\")\n\n        # add include dirs for class\n        include_dirs += self.__class__.include_dirs\n\n        return output_dir, macros, include_dirs\n\n    def _prep_compile(self, sources, output_dir, depends=None):\n        \"\"\"Decide which source files must be recompiled.\n\n        Determine the list of object files corresponding to 'sources',\n        and figure out which ones really need to be recompiled.\n        Return a list of all object files and a dictionary telling\n        which source files can be skipped.\n        \"\"\"\n        # Get the list of expected output (object) files\n        objects = self.object_filenames(sources, output_dir=output_dir)\n        assert len(objects) == len(sources)\n\n        # Return an empty dict for the \"which source files can be skipped\"\n        # return value to preserve API compatibility.\n        return objects, {}\n\n    def _fix_object_args(self, objects, output_dir):\n        \"\"\"Typecheck and fix up some arguments supplied to various methods.\n        Specifically: ensure that 'objects' is a list; if output_dir is\n        None, replace with self.output_dir.  Return fixed versions of\n        'objects' and 'output_dir'.\n        \"\"\"\n        if not isinstance(objects, (list, tuple)):\n            raise TypeError(\"'objects' must be a list or tuple of strings\")\n        objects = list(objects)\n\n        if output_dir is None:\n            output_dir = self.output_dir\n        elif not isinstance(output_dir, str):\n            raise TypeError(\"'output_dir' must be a string or None\")\n\n        return (objects, output_dir)\n\n    def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):\n        \"\"\"Typecheck and fix up some of the arguments supplied to the\n        'link_*' methods.  Specifically: ensure that all arguments are\n        lists, and augment them with their permanent versions\n        (eg. 'self.libraries' augments 'libraries').  Return a tuple with\n        fixed versions of all arguments.\n        \"\"\"\n        if libraries is None:\n            libraries = self.libraries\n        elif isinstance(libraries, (list, tuple)):\n            libraries = list(libraries) + (self.libraries or [])\n        else:\n            raise TypeError(\"'libraries' (if supplied) must be a list of strings\")\n\n        if library_dirs is None:\n            library_dirs = self.library_dirs\n        elif isinstance(library_dirs, (list, tuple)):\n            library_dirs = list(library_dirs) + (self.library_dirs or [])\n        else:\n            raise TypeError(\"'library_dirs' (if supplied) must be a list of strings\")\n\n        # add library dirs for class\n        library_dirs += self.__class__.library_dirs\n\n        if runtime_library_dirs is None:\n            runtime_library_dirs = self.runtime_library_dirs\n        elif isinstance(runtime_library_dirs, (list, tuple)):\n            runtime_library_dirs = list(runtime_library_dirs) + (\n                self.runtime_library_dirs or []\n            )\n        else:\n            raise TypeError(\n                \"'runtime_library_dirs' (if supplied) \" \"must be a list of strings\"\n            )\n\n        return (libraries, library_dirs, runtime_library_dirs)\n\n    def _need_link(self, objects, output_file):\n        \"\"\"Return true if we need to relink the files listed in 'objects'\n        to recreate 'output_file'.\n        \"\"\"\n        if self.force:\n            return True\n        else:\n            if self.dry_run:\n                newer = newer_group(objects, output_file, missing='newer')\n            else:\n                newer = newer_group(objects, output_file)\n            return newer\n\n    def detect_language(self, sources):\n        \"\"\"Detect the language of a given file, or list of files. Uses\n        language_map, and language_order to do the job.\n        \"\"\"\n        if not isinstance(sources, list):\n            sources = [sources]\n        lang = None\n        index = len(self.language_order)\n        for source in sources:\n            base, ext = os.path.splitext(source)\n            extlang = self.language_map.get(ext)\n            try:\n                extindex = self.language_order.index(extlang)\n                if extindex < index:\n                    lang = extlang\n                    index = extindex\n            except ValueError:\n                pass\n        return lang\n\n    # -- Worker methods ------------------------------------------------\n    # (must be implemented by subclasses)\n\n    def preprocess(\n        self,\n        source,\n        output_file=None,\n        macros=None,\n        include_dirs=None,\n        extra_preargs=None,\n        extra_postargs=None,\n    ):\n        \"\"\"Preprocess a single C/C++ source file, named in 'source'.\n        Output will be written to file named 'output_file', or stdout if\n        'output_file' not supplied.  'macros' is a list of macro\n        definitions as for 'compile()', which will augment the macros set\n        with 'define_macro()' and 'undefine_macro()'.  'include_dirs' is a\n        list of directory names that will be added to the default list.\n\n        Raises PreprocessError on failure.\n        \"\"\"\n        pass\n\n    def compile(\n        self,\n        sources,\n        output_dir=None,\n        macros=None,\n        include_dirs=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        depends=None,\n    ):\n        \"\"\"Compile one or more source files.\n\n        'sources' must be a list of filenames, most likely C/C++\n        files, but in reality anything that can be handled by a\n        particular compiler and compiler class (eg. MSVCCompiler can\n        handle resource files in 'sources').  Return a list of object\n        filenames, one per source filename in 'sources'.  Depending on\n        the implementation, not all source files will necessarily be\n        compiled, but all corresponding object filenames will be\n        returned.\n\n        If 'output_dir' is given, object files will be put under it, while\n        retaining their original path component.  That is, \"foo/bar.c\"\n        normally compiles to \"foo/bar.o\" (for a Unix implementation); if\n        'output_dir' is \"build\", then it would compile to\n        \"build/foo/bar.o\".\n\n        'macros', if given, must be a list of macro definitions.  A macro\n        definition is either a (name, value) 2-tuple or a (name,) 1-tuple.\n        The former defines a macro; if the value is None, the macro is\n        defined without an explicit value.  The 1-tuple case undefines a\n        macro.  Later definitions/redefinitions/ undefinitions take\n        precedence.\n\n        'include_dirs', if given, must be a list of strings, the\n        directories to add to the default include file search path for this\n        compilation only.\n\n        'debug' is a boolean; if true, the compiler will be instructed to\n        output debug symbols in (or alongside) the object file(s).\n\n        'extra_preargs' and 'extra_postargs' are implementation- dependent.\n        On platforms that have the notion of a command-line (e.g. Unix,\n        DOS/Windows), they are most likely lists of strings: extra\n        command-line arguments to prepend/append to the compiler command\n        line.  On other platforms, consult the implementation class\n        documentation.  In any event, they are intended as an escape hatch\n        for those occasions when the abstract compiler framework doesn't\n        cut the mustard.\n\n        'depends', if given, is a list of filenames that all targets\n        depend on.  If a source file is older than any file in\n        depends, then the source file will be recompiled.  This\n        supports dependency tracking, but only at a coarse\n        granularity.\n\n        Raises CompileError on failure.\n        \"\"\"\n        # A concrete compiler class can either override this method\n        # entirely or implement _compile().\n        macros, objects, extra_postargs, pp_opts, build = self._setup_compile(\n            output_dir, macros, include_dirs, sources, depends, extra_postargs\n        )\n        cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)\n\n        for obj in objects:\n            try:\n                src, ext = build[obj]\n            except KeyError:\n                continue\n            self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)\n\n        # Return *all* object filenames, not just the ones we just built.\n        return objects\n\n    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):\n        \"\"\"Compile 'src' to product 'obj'.\"\"\"\n        # A concrete compiler class that does not override compile()\n        # should implement _compile().\n        pass\n\n    def create_static_lib(\n        self, objects, output_libname, output_dir=None, debug=0, target_lang=None\n    ):\n        \"\"\"Link a bunch of stuff together to create a static library file.\n        The \"bunch of stuff\" consists of the list of object files supplied\n        as 'objects', the extra object files supplied to\n        'add_link_object()' and/or 'set_link_objects()', the libraries\n        supplied to 'add_library()' and/or 'set_libraries()', and the\n        libraries supplied as 'libraries' (if any).\n\n        'output_libname' should be a library name, not a filename; the\n        filename will be inferred from the library name.  'output_dir' is\n        the directory where the library file will be put.\n\n        'debug' is a boolean; if true, debugging information will be\n        included in the library (note that on most platforms, it is the\n        compile step where this matters: the 'debug' flag is included here\n        just for consistency).\n\n        'target_lang' is the target language for which the given objects\n        are being compiled. This allows specific linkage time treatment of\n        certain languages.\n\n        Raises LibError on failure.\n        \"\"\"\n        pass\n\n    # values for target_desc parameter in link()\n    SHARED_OBJECT = \"shared_object\"\n    SHARED_LIBRARY = \"shared_library\"\n    EXECUTABLE = \"executable\"\n\n    def link(\n        self,\n        target_desc,\n        objects,\n        output_filename,\n        output_dir=None,\n        libraries=None,\n        library_dirs=None,\n        runtime_library_dirs=None,\n        export_symbols=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        build_temp=None,\n        target_lang=None,\n    ):\n        \"\"\"Link a bunch of stuff together to create an executable or\n        shared library file.\n\n        The \"bunch of stuff\" consists of the list of object files supplied\n        as 'objects'.  'output_filename' should be a filename.  If\n        'output_dir' is supplied, 'output_filename' is relative to it\n        (i.e. 'output_filename' can provide directory components if\n        needed).\n\n        'libraries' is a list of libraries to link against.  These are\n        library names, not filenames, since they're translated into\n        filenames in a platform-specific way (eg. \"foo\" becomes \"libfoo.a\"\n        on Unix and \"foo.lib\" on DOS/Windows).  However, they can include a\n        directory component, which means the linker will look in that\n        specific directory rather than searching all the normal locations.\n\n        'library_dirs', if supplied, should be a list of directories to\n        search for libraries that were specified as bare library names\n        (ie. no directory component).  These are on top of the system\n        default and those supplied to 'add_library_dir()' and/or\n        'set_library_dirs()'.  'runtime_library_dirs' is a list of\n        directories that will be embedded into the shared library and used\n        to search for other shared libraries that *it* depends on at\n        run-time.  (This may only be relevant on Unix.)\n\n        'export_symbols' is a list of symbols that the shared library will\n        export.  (This appears to be relevant only on Windows.)\n\n        'debug' is as for 'compile()' and 'create_static_lib()', with the\n        slight distinction that it actually matters on most platforms (as\n        opposed to 'create_static_lib()', which includes a 'debug' flag\n        mostly for form's sake).\n\n        'extra_preargs' and 'extra_postargs' are as for 'compile()' (except\n        of course that they supply command-line arguments for the\n        particular linker being used).\n\n        'target_lang' is the target language for which the given objects\n        are being compiled. This allows specific linkage time treatment of\n        certain languages.\n\n        Raises LinkError on failure.\n        \"\"\"\n        raise NotImplementedError\n\n    # Old 'link_*()' methods, rewritten to use the new 'link()' method.\n\n    def link_shared_lib(\n        self,\n        objects,\n        output_libname,\n        output_dir=None,\n        libraries=None,\n        library_dirs=None,\n        runtime_library_dirs=None,\n        export_symbols=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        build_temp=None,\n        target_lang=None,\n    ):\n        self.link(\n            CCompiler.SHARED_LIBRARY,\n            objects,\n            self.library_filename(output_libname, lib_type='shared'),\n            output_dir,\n            libraries,\n            library_dirs,\n            runtime_library_dirs,\n            export_symbols,\n            debug,\n            extra_preargs,\n            extra_postargs,\n            build_temp,\n            target_lang,\n        )\n\n    def link_shared_object(\n        self,\n        objects,\n        output_filename,\n        output_dir=None,\n        libraries=None,\n        library_dirs=None,\n        runtime_library_dirs=None,\n        export_symbols=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        build_temp=None,\n        target_lang=None,\n    ):\n        self.link(\n            CCompiler.SHARED_OBJECT,\n            objects,\n            output_filename,\n            output_dir,\n            libraries,\n            library_dirs,\n            runtime_library_dirs,\n            export_symbols,\n            debug,\n            extra_preargs,\n            extra_postargs,\n            build_temp,\n            target_lang,\n        )\n\n    def link_executable(\n        self,\n        objects,\n        output_progname,\n        output_dir=None,\n        libraries=None,\n        library_dirs=None,\n        runtime_library_dirs=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        target_lang=None,\n    ):\n        self.link(\n            CCompiler.EXECUTABLE,\n            objects,\n            self.executable_filename(output_progname),\n            output_dir,\n            libraries,\n            library_dirs,\n            runtime_library_dirs,\n            None,\n            debug,\n            extra_preargs,\n            extra_postargs,\n            None,\n            target_lang,\n        )\n\n    # -- Miscellaneous methods -----------------------------------------\n    # These are all used by the 'gen_lib_options() function; there is\n    # no appropriate default implementation so subclasses should\n    # implement all of these.\n\n    def library_dir_option(self, dir):\n        \"\"\"Return the compiler option to add 'dir' to the list of\n        directories searched for libraries.\n        \"\"\"\n        raise NotImplementedError\n\n    def runtime_library_dir_option(self, dir):\n        \"\"\"Return the compiler option to add 'dir' to the list of\n        directories searched for runtime libraries.\n        \"\"\"\n        raise NotImplementedError\n\n    def library_option(self, lib):\n        \"\"\"Return the compiler option to add 'lib' to the list of libraries\n        linked into the shared library or executable.\n        \"\"\"\n        raise NotImplementedError\n\n    def has_function(  # noqa: C901\n        self,\n        funcname,\n        includes=None,\n        include_dirs=None,\n        libraries=None,\n        library_dirs=None,\n    ):\n        \"\"\"Return a boolean indicating whether funcname is supported on\n        the current platform.  The optional arguments can be used to\n        augment the compilation environment.\n        \"\"\"\n        # this can't be included at module scope because it tries to\n        # import math which might not be available at that point - maybe\n        # the necessary logic should just be inlined?\n        import tempfile\n\n        if includes is None:\n            includes = []\n        if include_dirs is None:\n            include_dirs = []\n        if libraries is None:\n            libraries = []\n        if library_dirs is None:\n            library_dirs = []\n        fd, fname = tempfile.mkstemp(\".c\", funcname, text=True)\n        f = os.fdopen(fd, \"w\")\n        try:\n            for incl in includes:\n                f.write(\"\"\"#include \"%s\"\\n\"\"\" % incl)\n            f.write(\n                \"\"\"\\\nint main (int argc, char **argv) {\n    %s();\n    return 0;\n}\n\"\"\"\n                % funcname\n            )\n        finally:\n            f.close()\n        try:\n            objects = self.compile([fname], include_dirs=include_dirs)\n        except CompileError:\n            return False\n        finally:\n            os.remove(fname)\n\n        try:\n            self.link_executable(\n                objects, \"a.out\", libraries=libraries, library_dirs=library_dirs\n            )\n        except (LinkError, TypeError):\n            return False\n        else:\n            os.remove(os.path.join(self.output_dir or '', \"a.out\"))\n        finally:\n            for fn in objects:\n                os.remove(fn)\n        return True\n\n    def find_library_file(self, dirs, lib, debug=0):\n        \"\"\"Search the specified list of directories for a static or shared\n        library file 'lib' and return the full path to that file.  If\n        'debug' true, look for a debugging version (if that makes sense on\n        the current platform).  Return None if 'lib' wasn't found in any of\n        the specified directories.\n        \"\"\"\n        raise NotImplementedError\n\n    # -- Filename generation methods -----------------------------------\n\n    # The default implementation of the filename generating methods are\n    # prejudiced towards the Unix/DOS/Windows view of the world:\n    #   * object files are named by replacing the source file extension\n    #     (eg. .c/.cpp -> .o/.obj)\n    #   * library files (shared or static) are named by plugging the\n    #     library name and extension into a format string, eg.\n    #     \"lib%s.%s\" % (lib_name, \".a\") for Unix static libraries\n    #   * executables are named by appending an extension (possibly\n    #     empty) to the program name: eg. progname + \".exe\" for\n    #     Windows\n    #\n    # To reduce redundant code, these methods expect to find\n    # several attributes in the current object (presumably defined\n    # as class attributes):\n    #   * src_extensions -\n    #     list of C/C++ source file extensions, eg. ['.c', '.cpp']\n    #   * obj_extension -\n    #     object file extension, eg. '.o' or '.obj'\n    #   * static_lib_extension -\n    #     extension for static library files, eg. '.a' or '.lib'\n    #   * shared_lib_extension -\n    #     extension for shared library/object files, eg. '.so', '.dll'\n    #   * static_lib_format -\n    #     format string for generating static library filenames,\n    #     eg. 'lib%s.%s' or '%s.%s'\n    #   * shared_lib_format\n    #     format string for generating shared library filenames\n    #     (probably same as static_lib_format, since the extension\n    #     is one of the intended parameters to the format string)\n    #   * exe_extension -\n    #     extension for executable files, eg. '' or '.exe'\n\n    def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):\n        if output_dir is None:\n            output_dir = ''\n        return list(\n            self._make_out_path(output_dir, strip_dir, src_name)\n            for src_name in source_filenames\n        )\n\n    @property\n    def out_extensions(self):\n        return dict.fromkeys(self.src_extensions, self.obj_extension)\n\n    def _make_out_path(self, output_dir, strip_dir, src_name):\n        base, ext = os.path.splitext(src_name)\n        base = self._make_relative(base)\n        try:\n            new_ext = self.out_extensions[ext]\n        except LookupError:\n            raise UnknownFileError(\n                \"unknown file type '{}' (from '{}')\".format(ext, src_name)\n            )\n        if strip_dir:\n            base = os.path.basename(base)\n        return os.path.join(output_dir, base + new_ext)\n\n    @staticmethod\n    def _make_relative(base):\n        \"\"\"\n        In order to ensure that a filename always honors the\n        indicated output_dir, make sure it's relative.\n        Ref python/cpython#37775.\n        \"\"\"\n        # Chop off the drive\n        no_drive = os.path.splitdrive(base)[1]\n        # If abs, chop off leading /\n        return no_drive[os.path.isabs(no_drive) :]\n\n    def shared_object_filename(self, basename, strip_dir=0, output_dir=''):\n        assert output_dir is not None\n        if strip_dir:\n            basename = os.path.basename(basename)\n        return os.path.join(output_dir, basename + self.shared_lib_extension)\n\n    def executable_filename(self, basename, strip_dir=0, output_dir=''):\n        assert output_dir is not None\n        if strip_dir:\n            basename = os.path.basename(basename)\n        return os.path.join(output_dir, basename + (self.exe_extension or ''))\n\n    def library_filename(\n        self, libname, lib_type='static', strip_dir=0, output_dir=''  # or 'shared'\n    ):\n        assert output_dir is not None\n        expected = '\"static\", \"shared\", \"dylib\", \"xcode_stub\"'\n        if lib_type not in eval(expected):\n            raise ValueError(f\"'lib_type' must be {expected}\")\n        fmt = getattr(self, lib_type + \"_lib_format\")\n        ext = getattr(self, lib_type + \"_lib_extension\")\n\n        dir, base = os.path.split(libname)\n        filename = fmt % (base, ext)\n        if strip_dir:\n            dir = ''\n\n        return os.path.join(output_dir, dir, filename)\n\n    # -- Utility methods -----------------------------------------------\n\n    def announce(self, msg, level=1):\n        log.debug(msg)\n\n    def debug_print(self, msg):\n        from distutils.debug import DEBUG\n\n        if DEBUG:\n            print(msg)\n\n    def warn(self, msg):\n        sys.stderr.write(\"warning: %s\\n\" % msg)\n\n    def execute(self, func, args, msg=None, level=1):\n        execute(func, args, msg, self.dry_run)\n\n    def spawn(self, cmd, **kwargs):\n        spawn(cmd, dry_run=self.dry_run, **kwargs)\n\n    def move_file(self, src, dst):\n        return move_file(src, dst, dry_run=self.dry_run)\n\n    def mkpath(self, name, mode=0o777):\n        mkpath(name, mode, dry_run=self.dry_run)\n\n\n# Map a sys.platform/os.name ('posix', 'nt') to the default compiler\n# type for that platform. Keys are interpreted as re match\n# patterns. Order is important; platform mappings are preferred over\n# OS names.\n_default_compilers = (\n    # Platform string mappings\n    # on a cygwin built python we can use gcc like an ordinary UNIXish\n    # compiler\n    ('cygwin.*', 'unix'),\n    # OS name mappings\n    ('posix', 'unix'),\n    ('nt', 'msvc'),\n)\n\n\ndef get_default_compiler(osname=None, platform=None):\n    \"\"\"Determine the default compiler to use for the given platform.\n\n    osname should be one of the standard Python OS names (i.e. the\n    ones returned by os.name) and platform the common value\n    returned by sys.platform for the platform in question.\n\n    The default values are os.name and sys.platform in case the\n    parameters are not given.\n    \"\"\"\n    if osname is None:\n        osname = os.name\n    if platform is None:\n        platform = sys.platform\n    for pattern, compiler in _default_compilers:\n        if (\n            re.match(pattern, platform) is not None\n            or re.match(pattern, osname) is not None\n        ):\n            return compiler\n    # Default to Unix compiler\n    return 'unix'\n\n\n# Map compiler types to (module_name, class_name) pairs -- ie. where to\n# find the code that implements an interface to this compiler.  (The module\n# is assumed to be in the 'distutils' package.)\ncompiler_class = {\n    'unix': ('unixccompiler', 'UnixCCompiler', \"standard UNIX-style compiler\"),\n    'msvc': ('_msvccompiler', 'MSVCCompiler', \"Microsoft Visual C++\"),\n    'cygwin': (\n        'cygwinccompiler',\n        'CygwinCCompiler',\n        \"Cygwin port of GNU C Compiler for Win32\",\n    ),\n    'mingw32': (\n        'cygwinccompiler',\n        'Mingw32CCompiler',\n        \"Mingw32 port of GNU C Compiler for Win32\",\n    ),\n    'bcpp': ('bcppcompiler', 'BCPPCompiler', \"Borland C++ Compiler\"),\n}\n\n\ndef show_compilers():\n    \"\"\"Print list of available compilers (used by the \"--help-compiler\"\n    options to \"build\", \"build_ext\", \"build_clib\").\n    \"\"\"\n    # XXX this \"knows\" that the compiler option it's describing is\n    # \"--compiler\", which just happens to be the case for the three\n    # commands that use it.\n    from distutils.fancy_getopt import FancyGetopt\n\n    compilers = []\n    for compiler in compiler_class.keys():\n        compilers.append((\"compiler=\" + compiler, None, compiler_class[compiler][2]))\n    compilers.sort()\n    pretty_printer = FancyGetopt(compilers)\n    pretty_printer.print_help(\"List of available compilers:\")\n\n\ndef new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0):\n    \"\"\"Generate an instance of some CCompiler subclass for the supplied\n    platform/compiler combination.  'plat' defaults to 'os.name'\n    (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler\n    for that platform.  Currently only 'posix' and 'nt' are supported, and\n    the default compilers are \"traditional Unix interface\" (UnixCCompiler\n    class) and Visual C++ (MSVCCompiler class).  Note that it's perfectly\n    possible to ask for a Unix compiler object under Windows, and a\n    Microsoft compiler object under Unix -- if you supply a value for\n    'compiler', 'plat' is ignored.\n    \"\"\"\n    if plat is None:\n        plat = os.name\n\n    try:\n        if compiler is None:\n            compiler = get_default_compiler(plat)\n\n        (module_name, class_name, long_description) = compiler_class[compiler]\n    except KeyError:\n        msg = \"don't know how to compile C/C++ code on platform '%s'\" % plat\n        if compiler is not None:\n            msg = msg + \" with '%s' compiler\" % compiler\n        raise DistutilsPlatformError(msg)\n\n    try:\n        module_name = \"distutils.\" + module_name\n        __import__(module_name)\n        module = sys.modules[module_name]\n        klass = vars(module)[class_name]\n    except ImportError:\n        raise DistutilsModuleError(\n            \"can't compile C/C++ code: unable to load module '%s'\" % module_name\n        )\n    except KeyError:\n        raise DistutilsModuleError(\n            \"can't compile C/C++ code: unable to find class '%s' \"\n            \"in module '%s'\" % (class_name, module_name)\n        )\n\n    # XXX The None is necessary to preserve backwards compatibility\n    # with classes that expect verbose to be the first positional\n    # argument.\n    return klass(None, dry_run, force)\n\n\ndef gen_preprocess_options(macros, include_dirs):\n    \"\"\"Generate C pre-processor options (-D, -U, -I) as used by at least\n    two types of compilers: the typical Unix compiler and Visual C++.\n    'macros' is the usual thing, a list of 1- or 2-tuples, where (name,)\n    means undefine (-U) macro 'name', and (name,value) means define (-D)\n    macro 'name' to 'value'.  'include_dirs' is just a list of directory\n    names to be added to the header file search path (-I).  Returns a list\n    of command-line options suitable for either Unix compilers or Visual\n    C++.\n    \"\"\"\n    # XXX it would be nice (mainly aesthetic, and so we don't generate\n    # stupid-looking command lines) to go over 'macros' and eliminate\n    # redundant definitions/undefinitions (ie. ensure that only the\n    # latest mention of a particular macro winds up on the command\n    # line).  I don't think it's essential, though, since most (all?)\n    # Unix C compilers only pay attention to the latest -D or -U\n    # mention of a macro on their command line.  Similar situation for\n    # 'include_dirs'.  I'm punting on both for now.  Anyways, weeding out\n    # redundancies like this should probably be the province of\n    # CCompiler, since the data structures used are inherited from it\n    # and therefore common to all CCompiler classes.\n    pp_opts = []\n    for macro in macros:\n        if not (isinstance(macro, tuple) and 1 <= len(macro) <= 2):\n            raise TypeError(\n                \"bad macro definition '%s': \"\n                \"each element of 'macros' list must be a 1- or 2-tuple\" % macro\n            )\n\n        if len(macro) == 1:  # undefine this macro\n            pp_opts.append(\"-U%s\" % macro[0])\n        elif len(macro) == 2:\n            if macro[1] is None:  # define with no explicit value\n                pp_opts.append(\"-D%s\" % macro[0])\n            else:\n                # XXX *don't* need to be clever about quoting the\n                # macro value here, because we're going to avoid the\n                # shell at all costs when we spawn the command!\n                pp_opts.append(\"-D%s=%s\" % macro)\n\n    for dir in include_dirs:\n        pp_opts.append(\"-I%s\" % dir)\n    return pp_opts\n\n\ndef gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):\n    \"\"\"Generate linker options for searching library directories and\n    linking with specific libraries.  'libraries' and 'library_dirs' are,\n    respectively, lists of library names (not filenames!) and search\n    directories.  Returns a list of command-line options suitable for use\n    with some compiler (depending on the two format strings passed in).\n    \"\"\"\n    lib_opts = []\n\n    for dir in library_dirs:\n        lib_opts.append(compiler.library_dir_option(dir))\n\n    for dir in runtime_library_dirs:\n        opt = compiler.runtime_library_dir_option(dir)\n        if isinstance(opt, list):\n            lib_opts = lib_opts + opt\n        else:\n            lib_opts.append(opt)\n\n    # XXX it's important that we *not* remove redundant library mentions!\n    # sometimes you really do have to say \"-lfoo -lbar -lfoo\" in order to\n    # resolve all symbols.  I just hope we never have to say \"-lfoo obj.o\n    # -lbar\" to get things to work -- that's certainly a possibility, but a\n    # pretty nasty way to arrange your C code.\n\n    for lib in libraries:\n        (lib_dir, lib_name) = os.path.split(lib)\n        if lib_dir:\n            lib_file = compiler.find_library_file([lib_dir], lib_name)\n            if lib_file:\n                lib_opts.append(lib_file)\n            else:\n                compiler.warn(\n                    \"no library file corresponding to \" \"'%s' found (skipping)\" % lib\n                )\n        else:\n            lib_opts.append(compiler.library_option(lib))\n    return lib_opts\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/cmd.py",
    "content": "\"\"\"distutils.cmd\n\nProvides the Command class, the base class for the command classes\nin the distutils.command package.\n\"\"\"\n\nimport sys\nimport os\nimport re\nfrom distutils.errors import DistutilsOptionError\nfrom distutils import util, dir_util, file_util, archive_util, dep_util\nfrom distutils import log\n\n\nclass Command:\n    \"\"\"Abstract base class for defining command classes, the \"worker bees\"\n    of the Distutils.  A useful analogy for command classes is to think of\n    them as subroutines with local variables called \"options\".  The options\n    are \"declared\" in 'initialize_options()' and \"defined\" (given their\n    final values, aka \"finalized\") in 'finalize_options()', both of which\n    must be defined by every command class.  The distinction between the\n    two is necessary because option values might come from the outside\n    world (command line, config file, ...), and any options dependent on\n    other options must be computed *after* these outside influences have\n    been processed -- hence 'finalize_options()'.  The \"body\" of the\n    subroutine, where it does all its work based on the values of its\n    options, is the 'run()' method, which must also be implemented by every\n    command class.\n    \"\"\"\n\n    # 'sub_commands' formalizes the notion of a \"family\" of commands,\n    # eg. \"install\" as the parent with sub-commands \"install_lib\",\n    # \"install_headers\", etc.  The parent of a family of commands\n    # defines 'sub_commands' as a class attribute; it's a list of\n    #    (command_name : string, predicate : unbound_method | string | None)\n    # tuples, where 'predicate' is a method of the parent command that\n    # determines whether the corresponding command is applicable in the\n    # current situation.  (Eg. we \"install_headers\" is only applicable if\n    # we have any C header files to install.)  If 'predicate' is None,\n    # that command is always applicable.\n    #\n    # 'sub_commands' is usually defined at the *end* of a class, because\n    # predicates can be unbound methods, so they must already have been\n    # defined.  The canonical example is the \"install\" command.\n    sub_commands = []\n\n    # -- Creation/initialization methods -------------------------------\n\n    def __init__(self, dist):\n        \"\"\"Create and initialize a new Command object.  Most importantly,\n        invokes the 'initialize_options()' method, which is the real\n        initializer and depends on the actual command being\n        instantiated.\n        \"\"\"\n        # late import because of mutual dependence between these classes\n        from distutils.dist import Distribution\n\n        if not isinstance(dist, Distribution):\n            raise TypeError(\"dist must be a Distribution instance\")\n        if self.__class__ is Command:\n            raise RuntimeError(\"Command is an abstract class\")\n\n        self.distribution = dist\n        self.initialize_options()\n\n        # Per-command versions of the global flags, so that the user can\n        # customize Distutils' behaviour command-by-command and let some\n        # commands fall back on the Distribution's behaviour.  None means\n        # \"not defined, check self.distribution's copy\", while 0 or 1 mean\n        # false and true (duh).  Note that this means figuring out the real\n        # value of each flag is a touch complicated -- hence \"self._dry_run\"\n        # will be handled by __getattr__, below.\n        # XXX This needs to be fixed.\n        self._dry_run = None\n\n        # verbose is largely ignored, but needs to be set for\n        # backwards compatibility (I think)?\n        self.verbose = dist.verbose\n\n        # Some commands define a 'self.force' option to ignore file\n        # timestamps, but methods defined *here* assume that\n        # 'self.force' exists for all commands.  So define it here\n        # just to be safe.\n        self.force = None\n\n        # The 'help' flag is just used for command-line parsing, so\n        # none of that complicated bureaucracy is needed.\n        self.help = 0\n\n        # 'finalized' records whether or not 'finalize_options()' has been\n        # called.  'finalize_options()' itself should not pay attention to\n        # this flag: it is the business of 'ensure_finalized()', which\n        # always calls 'finalize_options()', to respect/update it.\n        self.finalized = 0\n\n    # XXX A more explicit way to customize dry_run would be better.\n    def __getattr__(self, attr):\n        if attr == 'dry_run':\n            myval = getattr(self, \"_\" + attr)\n            if myval is None:\n                return getattr(self.distribution, attr)\n            else:\n                return myval\n        else:\n            raise AttributeError(attr)\n\n    def ensure_finalized(self):\n        if not self.finalized:\n            self.finalize_options()\n        self.finalized = 1\n\n    # Subclasses must define:\n    #   initialize_options()\n    #     provide default values for all options; may be customized by\n    #     setup script, by options from config file(s), or by command-line\n    #     options\n    #   finalize_options()\n    #     decide on the final values for all options; this is called\n    #     after all possible intervention from the outside world\n    #     (command-line, option file, etc.) has been processed\n    #   run()\n    #     run the command: do whatever it is we're here to do,\n    #     controlled by the command's various option values\n\n    def initialize_options(self):\n        \"\"\"Set default values for all the options that this command\n        supports.  Note that these defaults may be overridden by other\n        commands, by the setup script, by config files, or by the\n        command-line.  Thus, this is not the place to code dependencies\n        between options; generally, 'initialize_options()' implementations\n        are just a bunch of \"self.foo = None\" assignments.\n\n        This method must be implemented by all command classes.\n        \"\"\"\n        raise RuntimeError(\n            \"abstract method -- subclass %s must override\" % self.__class__\n        )\n\n    def finalize_options(self):\n        \"\"\"Set final values for all the options that this command supports.\n        This is always called as late as possible, ie.  after any option\n        assignments from the command-line or from other commands have been\n        done.  Thus, this is the place to code option dependencies: if\n        'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as\n        long as 'foo' still has the same value it was assigned in\n        'initialize_options()'.\n\n        This method must be implemented by all command classes.\n        \"\"\"\n        raise RuntimeError(\n            \"abstract method -- subclass %s must override\" % self.__class__\n        )\n\n    def dump_options(self, header=None, indent=\"\"):\n        from distutils.fancy_getopt import longopt_xlate\n\n        if header is None:\n            header = \"command options for '%s':\" % self.get_command_name()\n        self.announce(indent + header, level=log.INFO)\n        indent = indent + \"  \"\n        for (option, _, _) in self.user_options:\n            option = option.translate(longopt_xlate)\n            if option[-1] == \"=\":\n                option = option[:-1]\n            value = getattr(self, option)\n            self.announce(indent + \"{} = {}\".format(option, value), level=log.INFO)\n\n    def run(self):\n        \"\"\"A command's raison d'etre: carry out the action it exists to\n        perform, controlled by the options initialized in\n        'initialize_options()', customized by other commands, the setup\n        script, the command-line, and config files, and finalized in\n        'finalize_options()'.  All terminal output and filesystem\n        interaction should be done by 'run()'.\n\n        This method must be implemented by all command classes.\n        \"\"\"\n        raise RuntimeError(\n            \"abstract method -- subclass %s must override\" % self.__class__\n        )\n\n    def announce(self, msg, level=1):\n        \"\"\"If the current verbosity level is of greater than or equal to\n        'level' print 'msg' to stdout.\n        \"\"\"\n        log.log(level, msg)\n\n    def debug_print(self, msg):\n        \"\"\"Print 'msg' to stdout if the global DEBUG (taken from the\n        DISTUTILS_DEBUG environment variable) flag is true.\n        \"\"\"\n        from distutils.debug import DEBUG\n\n        if DEBUG:\n            print(msg)\n            sys.stdout.flush()\n\n    # -- Option validation methods -------------------------------------\n    # (these are very handy in writing the 'finalize_options()' method)\n    #\n    # NB. the general philosophy here is to ensure that a particular option\n    # value meets certain type and value constraints.  If not, we try to\n    # force it into conformance (eg. if we expect a list but have a string,\n    # split the string on comma and/or whitespace).  If we can't force the\n    # option into conformance, raise DistutilsOptionError.  Thus, command\n    # classes need do nothing more than (eg.)\n    #   self.ensure_string_list('foo')\n    # and they can be guaranteed that thereafter, self.foo will be\n    # a list of strings.\n\n    def _ensure_stringlike(self, option, what, default=None):\n        val = getattr(self, option)\n        if val is None:\n            setattr(self, option, default)\n            return default\n        elif not isinstance(val, str):\n            raise DistutilsOptionError(\n                \"'{}' must be a {} (got `{}`)\".format(option, what, val)\n            )\n        return val\n\n    def ensure_string(self, option, default=None):\n        \"\"\"Ensure that 'option' is a string; if not defined, set it to\n        'default'.\n        \"\"\"\n        self._ensure_stringlike(option, \"string\", default)\n\n    def ensure_string_list(self, option):\n        r\"\"\"Ensure that 'option' is a list of strings.  If 'option' is\n        currently a string, we split it either on /,\\s*/ or /\\s+/, so\n        \"foo bar baz\", \"foo,bar,baz\", and \"foo,   bar baz\" all become\n        [\"foo\", \"bar\", \"baz\"].\n        \"\"\"\n        val = getattr(self, option)\n        if val is None:\n            return\n        elif isinstance(val, str):\n            setattr(self, option, re.split(r',\\s*|\\s+', val))\n        else:\n            if isinstance(val, list):\n                ok = all(isinstance(v, str) for v in val)\n            else:\n                ok = False\n            if not ok:\n                raise DistutilsOptionError(\n                    \"'{}' must be a list of strings (got {!r})\".format(option, val)\n                )\n\n    def _ensure_tested_string(self, option, tester, what, error_fmt, default=None):\n        val = self._ensure_stringlike(option, what, default)\n        if val is not None and not tester(val):\n            raise DistutilsOptionError(\n                (\"error in '%s' option: \" + error_fmt) % (option, val)\n            )\n\n    def ensure_filename(self, option):\n        \"\"\"Ensure that 'option' is the name of an existing file.\"\"\"\n        self._ensure_tested_string(\n            option, os.path.isfile, \"filename\", \"'%s' does not exist or is not a file\"\n        )\n\n    def ensure_dirname(self, option):\n        self._ensure_tested_string(\n            option,\n            os.path.isdir,\n            \"directory name\",\n            \"'%s' does not exist or is not a directory\",\n        )\n\n    # -- Convenience methods for commands ------------------------------\n\n    def get_command_name(self):\n        if hasattr(self, 'command_name'):\n            return self.command_name\n        else:\n            return self.__class__.__name__\n\n    def set_undefined_options(self, src_cmd, *option_pairs):\n        \"\"\"Set the values of any \"undefined\" options from corresponding\n        option values in some other command object.  \"Undefined\" here means\n        \"is None\", which is the convention used to indicate that an option\n        has not been changed between 'initialize_options()' and\n        'finalize_options()'.  Usually called from 'finalize_options()' for\n        options that depend on some other command rather than another\n        option of the same command.  'src_cmd' is the other command from\n        which option values will be taken (a command object will be created\n        for it if necessary); the remaining arguments are\n        '(src_option,dst_option)' tuples which mean \"take the value of\n        'src_option' in the 'src_cmd' command object, and copy it to\n        'dst_option' in the current command object\".\n        \"\"\"\n        # Option_pairs: list of (src_option, dst_option) tuples\n        src_cmd_obj = self.distribution.get_command_obj(src_cmd)\n        src_cmd_obj.ensure_finalized()\n        for (src_option, dst_option) in option_pairs:\n            if getattr(self, dst_option) is None:\n                setattr(self, dst_option, getattr(src_cmd_obj, src_option))\n\n    def get_finalized_command(self, command, create=1):\n        \"\"\"Wrapper around Distribution's 'get_command_obj()' method: find\n        (create if necessary and 'create' is true) the command object for\n        'command', call its 'ensure_finalized()' method, and return the\n        finalized command object.\n        \"\"\"\n        cmd_obj = self.distribution.get_command_obj(command, create)\n        cmd_obj.ensure_finalized()\n        return cmd_obj\n\n    # XXX rename to 'get_reinitialized_command()'? (should do the\n    # same in dist.py, if so)\n    def reinitialize_command(self, command, reinit_subcommands=0):\n        return self.distribution.reinitialize_command(command, reinit_subcommands)\n\n    def run_command(self, command):\n        \"\"\"Run some other command: uses the 'run_command()' method of\n        Distribution, which creates and finalizes the command object if\n        necessary and then invokes its 'run()' method.\n        \"\"\"\n        self.distribution.run_command(command)\n\n    def get_sub_commands(self):\n        \"\"\"Determine the sub-commands that are relevant in the current\n        distribution (ie., that need to be run).  This is based on the\n        'sub_commands' class attribute: each tuple in that list may include\n        a method that we call to determine if the subcommand needs to be\n        run for the current distribution.  Return a list of command names.\n        \"\"\"\n        commands = []\n        for (cmd_name, method) in self.sub_commands:\n            if method is None or method(self):\n                commands.append(cmd_name)\n        return commands\n\n    # -- External world manipulation -----------------------------------\n\n    def warn(self, msg):\n        log.warn(\"warning: %s: %s\\n\", self.get_command_name(), msg)\n\n    def execute(self, func, args, msg=None, level=1):\n        util.execute(func, args, msg, dry_run=self.dry_run)\n\n    def mkpath(self, name, mode=0o777):\n        dir_util.mkpath(name, mode, dry_run=self.dry_run)\n\n    def copy_file(\n        self, infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1\n    ):\n        \"\"\"Copy a file respecting verbose, dry-run and force flags.  (The\n        former two default to whatever is in the Distribution object, and\n        the latter defaults to false for commands that don't define it.)\"\"\"\n        return file_util.copy_file(\n            infile,\n            outfile,\n            preserve_mode,\n            preserve_times,\n            not self.force,\n            link,\n            dry_run=self.dry_run,\n        )\n\n    def copy_tree(\n        self,\n        infile,\n        outfile,\n        preserve_mode=1,\n        preserve_times=1,\n        preserve_symlinks=0,\n        level=1,\n    ):\n        \"\"\"Copy an entire directory tree respecting verbose, dry-run,\n        and force flags.\n        \"\"\"\n        return dir_util.copy_tree(\n            infile,\n            outfile,\n            preserve_mode,\n            preserve_times,\n            preserve_symlinks,\n            not self.force,\n            dry_run=self.dry_run,\n        )\n\n    def move_file(self, src, dst, level=1):\n        \"\"\"Move a file respecting dry-run flag.\"\"\"\n        return file_util.move_file(src, dst, dry_run=self.dry_run)\n\n    def spawn(self, cmd, search_path=1, level=1):\n        \"\"\"Spawn an external command respecting dry-run flag.\"\"\"\n        from distutils.spawn import spawn\n\n        spawn(cmd, search_path, dry_run=self.dry_run)\n\n    def make_archive(\n        self, base_name, format, root_dir=None, base_dir=None, owner=None, group=None\n    ):\n        return archive_util.make_archive(\n            base_name,\n            format,\n            root_dir,\n            base_dir,\n            dry_run=self.dry_run,\n            owner=owner,\n            group=group,\n        )\n\n    def make_file(\n        self, infiles, outfile, func, args, exec_msg=None, skip_msg=None, level=1\n    ):\n        \"\"\"Special case of 'execute()' for operations that process one or\n        more input files and generate one output file.  Works just like\n        'execute()', except the operation is skipped and a different\n        message printed if 'outfile' already exists and is newer than all\n        files listed in 'infiles'.  If the command defined 'self.force',\n        and it is true, then the command is unconditionally run -- does no\n        timestamp checks.\n        \"\"\"\n        if skip_msg is None:\n            skip_msg = \"skipping %s (inputs unchanged)\" % outfile\n\n        # Allow 'infiles' to be a single string\n        if isinstance(infiles, str):\n            infiles = (infiles,)\n        elif not isinstance(infiles, (list, tuple)):\n            raise TypeError(\"'infiles' must be a string, or a list or tuple of strings\")\n\n        if exec_msg is None:\n            exec_msg = \"generating {} from {}\".format(outfile, ', '.join(infiles))\n\n        # If 'outfile' must be regenerated (either because it doesn't\n        # exist, is out-of-date, or the 'force' flag is true) then\n        # perform the action that presumably regenerates it\n        if self.force or dep_util.newer_group(infiles, outfile):\n            self.execute(func, args, exec_msg, level)\n        # Otherwise, print the \"skip\" message\n        else:\n            log.debug(skip_msg)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/__init__.py",
    "content": "\"\"\"distutils.command\n\nPackage containing implementation of all the standard Distutils\ncommands.\"\"\"\n\n__all__ = [  # noqa: F822\n    'build',\n    'build_py',\n    'build_ext',\n    'build_clib',\n    'build_scripts',\n    'clean',\n    'install',\n    'install_lib',\n    'install_headers',\n    'install_scripts',\n    'install_data',\n    'sdist',\n    'register',\n    'bdist',\n    'bdist_dumb',\n    'bdist_rpm',\n    'check',\n    'upload',\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/_framework_compat.py",
    "content": "\"\"\"\nBackward compatibility for homebrew builds on macOS.\n\"\"\"\n\n\nimport sys\nimport os\nimport functools\nimport subprocess\nimport sysconfig\n\n\n@functools.lru_cache()\ndef enabled():\n    \"\"\"\n    Only enabled for Python 3.9 framework homebrew builds\n    except ensurepip and venv.\n    \"\"\"\n    PY39 = (3, 9) < sys.version_info < (3, 10)\n    framework = sys.platform == 'darwin' and sys._framework\n    homebrew = \"Cellar\" in sysconfig.get_config_var('projectbase')\n    venv = sys.prefix != sys.base_prefix\n    ensurepip = os.environ.get(\"ENSUREPIP_OPTIONS\")\n    return PY39 and framework and homebrew and not venv and not ensurepip\n\n\nschemes = dict(\n    osx_framework_library=dict(\n        stdlib='{installed_base}/{platlibdir}/python{py_version_short}',\n        platstdlib='{platbase}/{platlibdir}/python{py_version_short}',\n        purelib='{homebrew_prefix}/lib/python{py_version_short}/site-packages',\n        platlib='{homebrew_prefix}/{platlibdir}/python{py_version_short}/site-packages',\n        include='{installed_base}/include/python{py_version_short}{abiflags}',\n        platinclude='{installed_platbase}/include/python{py_version_short}{abiflags}',\n        scripts='{homebrew_prefix}/bin',\n        data='{homebrew_prefix}',\n    )\n)\n\n\n@functools.lru_cache()\ndef vars():\n    if not enabled():\n        return {}\n    homebrew_prefix = subprocess.check_output(['brew', '--prefix'], text=True).strip()\n    return locals()\n\n\ndef scheme(name):\n    \"\"\"\n    Override the selected scheme for posix_prefix.\n    \"\"\"\n    if not enabled() or not name.endswith('_prefix'):\n        return name\n    return 'osx_framework_library'\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/bdist.py",
    "content": "\"\"\"distutils.command.bdist\n\nImplements the Distutils 'bdist' command (create a built [binary]\ndistribution).\"\"\"\n\nimport os\nimport warnings\n\nfrom distutils.core import Command\nfrom distutils.errors import DistutilsPlatformError, DistutilsOptionError\nfrom distutils.util import get_platform\n\n\ndef show_formats():\n    \"\"\"Print list of available formats (arguments to \"--format\" option).\"\"\"\n    from distutils.fancy_getopt import FancyGetopt\n\n    formats = []\n    for format in bdist.format_commands:\n        formats.append((\"formats=\" + format, None, bdist.format_commands[format][1]))\n    pretty_printer = FancyGetopt(formats)\n    pretty_printer.print_help(\"List of available distribution formats:\")\n\n\nclass ListCompat(dict):\n    # adapter to allow for Setuptools compatibility in format_commands\n    def append(self, item):\n        warnings.warn(\n            \"\"\"format_commands is now a dict. append is deprecated.\"\"\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n\nclass bdist(Command):\n\n    description = \"create a built (binary) distribution\"\n\n    user_options = [\n        ('bdist-base=', 'b', \"temporary directory for creating built distributions\"),\n        (\n            'plat-name=',\n            'p',\n            \"platform name to embed in generated filenames \"\n            \"(default: %s)\" % get_platform(),\n        ),\n        ('formats=', None, \"formats for distribution (comma-separated list)\"),\n        (\n            'dist-dir=',\n            'd',\n            \"directory to put final built distributions in \" \"[default: dist]\",\n        ),\n        ('skip-build', None, \"skip rebuilding everything (for testing/debugging)\"),\n        (\n            'owner=',\n            'u',\n            \"Owner name used when creating a tar file\" \" [default: current user]\",\n        ),\n        (\n            'group=',\n            'g',\n            \"Group name used when creating a tar file\" \" [default: current group]\",\n        ),\n    ]\n\n    boolean_options = ['skip-build']\n\n    help_options = [\n        ('help-formats', None, \"lists available distribution formats\", show_formats),\n    ]\n\n    # The following commands do not take a format option from bdist\n    no_format_option = ('bdist_rpm',)\n\n    # This won't do in reality: will need to distinguish RPM-ish Linux,\n    # Debian-ish Linux, Solaris, FreeBSD, ..., Windows, Mac OS.\n    default_format = {'posix': 'gztar', 'nt': 'zip'}\n\n    # Define commands in preferred order for the --help-formats option\n    format_commands = ListCompat(\n        {\n            'rpm': ('bdist_rpm', \"RPM distribution\"),\n            'gztar': ('bdist_dumb', \"gzip'ed tar file\"),\n            'bztar': ('bdist_dumb', \"bzip2'ed tar file\"),\n            'xztar': ('bdist_dumb', \"xz'ed tar file\"),\n            'ztar': ('bdist_dumb', \"compressed tar file\"),\n            'tar': ('bdist_dumb', \"tar file\"),\n            'zip': ('bdist_dumb', \"ZIP file\"),\n        }\n    )\n\n    # for compatibility until consumers only reference format_commands\n    format_command = format_commands\n\n    def initialize_options(self):\n        self.bdist_base = None\n        self.plat_name = None\n        self.formats = None\n        self.dist_dir = None\n        self.skip_build = 0\n        self.group = None\n        self.owner = None\n\n    def finalize_options(self):\n        # have to finalize 'plat_name' before 'bdist_base'\n        if self.plat_name is None:\n            if self.skip_build:\n                self.plat_name = get_platform()\n            else:\n                self.plat_name = self.get_finalized_command('build').plat_name\n\n        # 'bdist_base' -- parent of per-built-distribution-format\n        # temporary directories (eg. we'll probably have\n        # \"build/bdist.<plat>/dumb\", \"build/bdist.<plat>/rpm\", etc.)\n        if self.bdist_base is None:\n            build_base = self.get_finalized_command('build').build_base\n            self.bdist_base = os.path.join(build_base, 'bdist.' + self.plat_name)\n\n        self.ensure_string_list('formats')\n        if self.formats is None:\n            try:\n                self.formats = [self.default_format[os.name]]\n            except KeyError:\n                raise DistutilsPlatformError(\n                    \"don't know how to create built distributions \"\n                    \"on platform %s\" % os.name\n                )\n\n        if self.dist_dir is None:\n            self.dist_dir = \"dist\"\n\n    def run(self):\n        # Figure out which sub-commands we need to run.\n        commands = []\n        for format in self.formats:\n            try:\n                commands.append(self.format_commands[format][0])\n            except KeyError:\n                raise DistutilsOptionError(\"invalid format '%s'\" % format)\n\n        # Reinitialize and run each command.\n        for i in range(len(self.formats)):\n            cmd_name = commands[i]\n            sub_cmd = self.reinitialize_command(cmd_name)\n            if cmd_name not in self.no_format_option:\n                sub_cmd.format = self.formats[i]\n\n            # passing the owner and group names for tar archiving\n            if cmd_name == 'bdist_dumb':\n                sub_cmd.owner = self.owner\n                sub_cmd.group = self.group\n\n            # If we're going to need to run this command again, tell it to\n            # keep its temporary files around so subsequent runs go faster.\n            if cmd_name in commands[i + 1 :]:\n                sub_cmd.keep_temp = 1\n            self.run_command(cmd_name)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/bdist_dumb.py",
    "content": "\"\"\"distutils.command.bdist_dumb\n\nImplements the Distutils 'bdist_dumb' command (create a \"dumb\" built\ndistribution -- i.e., just an archive to be unpacked under $prefix or\n$exec_prefix).\"\"\"\n\nimport os\nfrom distutils.core import Command\nfrom distutils.util import get_platform\nfrom distutils.dir_util import remove_tree, ensure_relative\nfrom distutils.errors import DistutilsPlatformError\nfrom distutils.sysconfig import get_python_version\nfrom distutils import log\n\n\nclass bdist_dumb(Command):\n\n    description = \"create a \\\"dumb\\\" built distribution\"\n\n    user_options = [\n        ('bdist-dir=', 'd', \"temporary directory for creating the distribution\"),\n        (\n            'plat-name=',\n            'p',\n            \"platform name to embed in generated filenames \"\n            \"(default: %s)\" % get_platform(),\n        ),\n        (\n            'format=',\n            'f',\n            \"archive format to create (tar, gztar, bztar, xztar, \" \"ztar, zip)\",\n        ),\n        (\n            'keep-temp',\n            'k',\n            \"keep the pseudo-installation tree around after \"\n            + \"creating the distribution archive\",\n        ),\n        ('dist-dir=', 'd', \"directory to put final built distributions in\"),\n        ('skip-build', None, \"skip rebuilding everything (for testing/debugging)\"),\n        (\n            'relative',\n            None,\n            \"build the archive using relative paths \" \"(default: false)\",\n        ),\n        (\n            'owner=',\n            'u',\n            \"Owner name used when creating a tar file\" \" [default: current user]\",\n        ),\n        (\n            'group=',\n            'g',\n            \"Group name used when creating a tar file\" \" [default: current group]\",\n        ),\n    ]\n\n    boolean_options = ['keep-temp', 'skip-build', 'relative']\n\n    default_format = {'posix': 'gztar', 'nt': 'zip'}\n\n    def initialize_options(self):\n        self.bdist_dir = None\n        self.plat_name = None\n        self.format = None\n        self.keep_temp = 0\n        self.dist_dir = None\n        self.skip_build = None\n        self.relative = 0\n        self.owner = None\n        self.group = None\n\n    def finalize_options(self):\n        if self.bdist_dir is None:\n            bdist_base = self.get_finalized_command('bdist').bdist_base\n            self.bdist_dir = os.path.join(bdist_base, 'dumb')\n\n        if self.format is None:\n            try:\n                self.format = self.default_format[os.name]\n            except KeyError:\n                raise DistutilsPlatformError(\n                    \"don't know how to create dumb built distributions \"\n                    \"on platform %s\" % os.name\n                )\n\n        self.set_undefined_options(\n            'bdist',\n            ('dist_dir', 'dist_dir'),\n            ('plat_name', 'plat_name'),\n            ('skip_build', 'skip_build'),\n        )\n\n    def run(self):\n        if not self.skip_build:\n            self.run_command('build')\n\n        install = self.reinitialize_command('install', reinit_subcommands=1)\n        install.root = self.bdist_dir\n        install.skip_build = self.skip_build\n        install.warn_dir = 0\n\n        log.info(\"installing to %s\", self.bdist_dir)\n        self.run_command('install')\n\n        # And make an archive relative to the root of the\n        # pseudo-installation tree.\n        archive_basename = \"{}.{}\".format(\n            self.distribution.get_fullname(), self.plat_name\n        )\n\n        pseudoinstall_root = os.path.join(self.dist_dir, archive_basename)\n        if not self.relative:\n            archive_root = self.bdist_dir\n        else:\n            if self.distribution.has_ext_modules() and (\n                install.install_base != install.install_platbase\n            ):\n                raise DistutilsPlatformError(\n                    \"can't make a dumb built distribution where \"\n                    \"base and platbase are different (%s, %s)\"\n                    % (repr(install.install_base), repr(install.install_platbase))\n                )\n            else:\n                archive_root = os.path.join(\n                    self.bdist_dir, ensure_relative(install.install_base)\n                )\n\n        # Make the archive\n        filename = self.make_archive(\n            pseudoinstall_root,\n            self.format,\n            root_dir=archive_root,\n            owner=self.owner,\n            group=self.group,\n        )\n        if self.distribution.has_ext_modules():\n            pyversion = get_python_version()\n        else:\n            pyversion = 'any'\n        self.distribution.dist_files.append(('bdist_dumb', pyversion, filename))\n\n        if not self.keep_temp:\n            remove_tree(self.bdist_dir, dry_run=self.dry_run)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/bdist_rpm.py",
    "content": "\"\"\"distutils.command.bdist_rpm\n\nImplements the Distutils 'bdist_rpm' command (create RPM source and binary\ndistributions).\"\"\"\n\nimport subprocess\nimport sys\nimport os\n\nfrom distutils.core import Command\nfrom distutils.debug import DEBUG\nfrom distutils.file_util import write_file\nfrom distutils.errors import (\n    DistutilsOptionError,\n    DistutilsPlatformError,\n    DistutilsFileError,\n    DistutilsExecError,\n)\nfrom distutils.sysconfig import get_python_version\nfrom distutils import log\n\n\nclass bdist_rpm(Command):\n\n    description = \"create an RPM distribution\"\n\n    user_options = [\n        ('bdist-base=', None, \"base directory for creating built distributions\"),\n        (\n            'rpm-base=',\n            None,\n            \"base directory for creating RPMs (defaults to \\\"rpm\\\" under \"\n            \"--bdist-base; must be specified for RPM 2)\",\n        ),\n        (\n            'dist-dir=',\n            'd',\n            \"directory to put final RPM files in \" \"(and .spec files if --spec-only)\",\n        ),\n        (\n            'python=',\n            None,\n            \"path to Python interpreter to hard-code in the .spec file \"\n            \"(default: \\\"python\\\")\",\n        ),\n        (\n            'fix-python',\n            None,\n            \"hard-code the exact path to the current Python interpreter in \"\n            \"the .spec file\",\n        ),\n        ('spec-only', None, \"only regenerate spec file\"),\n        ('source-only', None, \"only generate source RPM\"),\n        ('binary-only', None, \"only generate binary RPM\"),\n        ('use-bzip2', None, \"use bzip2 instead of gzip to create source distribution\"),\n        # More meta-data: too RPM-specific to put in the setup script,\n        # but needs to go in the .spec file -- so we make these options\n        # to \"bdist_rpm\".  The idea is that packagers would put this\n        # info in setup.cfg, although they are of course free to\n        # supply it on the command line.\n        (\n            'distribution-name=',\n            None,\n            \"name of the (Linux) distribution to which this \"\n            \"RPM applies (*not* the name of the module distribution!)\",\n        ),\n        ('group=', None, \"package classification [default: \\\"Development/Libraries\\\"]\"),\n        ('release=', None, \"RPM release number\"),\n        ('serial=', None, \"RPM serial number\"),\n        (\n            'vendor=',\n            None,\n            \"RPM \\\"vendor\\\" (eg. \\\"Joe Blow <joe@example.com>\\\") \"\n            \"[default: maintainer or author from setup script]\",\n        ),\n        (\n            'packager=',\n            None,\n            \"RPM packager (eg. \\\"Jane Doe <jane@example.net>\\\") \" \"[default: vendor]\",\n        ),\n        ('doc-files=', None, \"list of documentation files (space or comma-separated)\"),\n        ('changelog=', None, \"RPM changelog\"),\n        ('icon=', None, \"name of icon file\"),\n        ('provides=', None, \"capabilities provided by this package\"),\n        ('requires=', None, \"capabilities required by this package\"),\n        ('conflicts=', None, \"capabilities which conflict with this package\"),\n        ('build-requires=', None, \"capabilities required to build this package\"),\n        ('obsoletes=', None, \"capabilities made obsolete by this package\"),\n        ('no-autoreq', None, \"do not automatically calculate dependencies\"),\n        # Actions to take when building RPM\n        ('keep-temp', 'k', \"don't clean up RPM build directory\"),\n        ('no-keep-temp', None, \"clean up RPM build directory [default]\"),\n        (\n            'use-rpm-opt-flags',\n            None,\n            \"compile with RPM_OPT_FLAGS when building from source RPM\",\n        ),\n        ('no-rpm-opt-flags', None, \"do not pass any RPM CFLAGS to compiler\"),\n        ('rpm3-mode', None, \"RPM 3 compatibility mode (default)\"),\n        ('rpm2-mode', None, \"RPM 2 compatibility mode\"),\n        # Add the hooks necessary for specifying custom scripts\n        ('prep-script=', None, \"Specify a script for the PREP phase of RPM building\"),\n        ('build-script=', None, \"Specify a script for the BUILD phase of RPM building\"),\n        (\n            'pre-install=',\n            None,\n            \"Specify a script for the pre-INSTALL phase of RPM building\",\n        ),\n        (\n            'install-script=',\n            None,\n            \"Specify a script for the INSTALL phase of RPM building\",\n        ),\n        (\n            'post-install=',\n            None,\n            \"Specify a script for the post-INSTALL phase of RPM building\",\n        ),\n        (\n            'pre-uninstall=',\n            None,\n            \"Specify a script for the pre-UNINSTALL phase of RPM building\",\n        ),\n        (\n            'post-uninstall=',\n            None,\n            \"Specify a script for the post-UNINSTALL phase of RPM building\",\n        ),\n        ('clean-script=', None, \"Specify a script for the CLEAN phase of RPM building\"),\n        (\n            'verify-script=',\n            None,\n            \"Specify a script for the VERIFY phase of the RPM build\",\n        ),\n        # Allow a packager to explicitly force an architecture\n        ('force-arch=', None, \"Force an architecture onto the RPM build process\"),\n        ('quiet', 'q', \"Run the INSTALL phase of RPM building in quiet mode\"),\n    ]\n\n    boolean_options = [\n        'keep-temp',\n        'use-rpm-opt-flags',\n        'rpm3-mode',\n        'no-autoreq',\n        'quiet',\n    ]\n\n    negative_opt = {\n        'no-keep-temp': 'keep-temp',\n        'no-rpm-opt-flags': 'use-rpm-opt-flags',\n        'rpm2-mode': 'rpm3-mode',\n    }\n\n    def initialize_options(self):\n        self.bdist_base = None\n        self.rpm_base = None\n        self.dist_dir = None\n        self.python = None\n        self.fix_python = None\n        self.spec_only = None\n        self.binary_only = None\n        self.source_only = None\n        self.use_bzip2 = None\n\n        self.distribution_name = None\n        self.group = None\n        self.release = None\n        self.serial = None\n        self.vendor = None\n        self.packager = None\n        self.doc_files = None\n        self.changelog = None\n        self.icon = None\n\n        self.prep_script = None\n        self.build_script = None\n        self.install_script = None\n        self.clean_script = None\n        self.verify_script = None\n        self.pre_install = None\n        self.post_install = None\n        self.pre_uninstall = None\n        self.post_uninstall = None\n        self.prep = None\n        self.provides = None\n        self.requires = None\n        self.conflicts = None\n        self.build_requires = None\n        self.obsoletes = None\n\n        self.keep_temp = 0\n        self.use_rpm_opt_flags = 1\n        self.rpm3_mode = 1\n        self.no_autoreq = 0\n\n        self.force_arch = None\n        self.quiet = 0\n\n    def finalize_options(self):\n        self.set_undefined_options('bdist', ('bdist_base', 'bdist_base'))\n        if self.rpm_base is None:\n            if not self.rpm3_mode:\n                raise DistutilsOptionError(\"you must specify --rpm-base in RPM 2 mode\")\n            self.rpm_base = os.path.join(self.bdist_base, \"rpm\")\n\n        if self.python is None:\n            if self.fix_python:\n                self.python = sys.executable\n            else:\n                self.python = \"python3\"\n        elif self.fix_python:\n            raise DistutilsOptionError(\n                \"--python and --fix-python are mutually exclusive options\"\n            )\n\n        if os.name != 'posix':\n            raise DistutilsPlatformError(\n                \"don't know how to create RPM \" \"distributions on platform %s\" % os.name\n            )\n        if self.binary_only and self.source_only:\n            raise DistutilsOptionError(\n                \"cannot supply both '--source-only' and '--binary-only'\"\n            )\n\n        # don't pass CFLAGS to pure python distributions\n        if not self.distribution.has_ext_modules():\n            self.use_rpm_opt_flags = 0\n\n        self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))\n        self.finalize_package_data()\n\n    def finalize_package_data(self):\n        self.ensure_string('group', \"Development/Libraries\")\n        self.ensure_string(\n            'vendor',\n            \"%s <%s>\"\n            % (self.distribution.get_contact(), self.distribution.get_contact_email()),\n        )\n        self.ensure_string('packager')\n        self.ensure_string_list('doc_files')\n        if isinstance(self.doc_files, list):\n            for readme in ('README', 'README.txt'):\n                if os.path.exists(readme) and readme not in self.doc_files:\n                    self.doc_files.append(readme)\n\n        self.ensure_string('release', \"1\")\n        self.ensure_string('serial')  # should it be an int?\n\n        self.ensure_string('distribution_name')\n\n        self.ensure_string('changelog')\n        # Format changelog correctly\n        self.changelog = self._format_changelog(self.changelog)\n\n        self.ensure_filename('icon')\n\n        self.ensure_filename('prep_script')\n        self.ensure_filename('build_script')\n        self.ensure_filename('install_script')\n        self.ensure_filename('clean_script')\n        self.ensure_filename('verify_script')\n        self.ensure_filename('pre_install')\n        self.ensure_filename('post_install')\n        self.ensure_filename('pre_uninstall')\n        self.ensure_filename('post_uninstall')\n\n        # XXX don't forget we punted on summaries and descriptions -- they\n        # should be handled here eventually!\n\n        # Now *this* is some meta-data that belongs in the setup script...\n        self.ensure_string_list('provides')\n        self.ensure_string_list('requires')\n        self.ensure_string_list('conflicts')\n        self.ensure_string_list('build_requires')\n        self.ensure_string_list('obsoletes')\n\n        self.ensure_string('force_arch')\n\n    def run(self):  # noqa: C901\n        if DEBUG:\n            print(\"before _get_package_data():\")\n            print(\"vendor =\", self.vendor)\n            print(\"packager =\", self.packager)\n            print(\"doc_files =\", self.doc_files)\n            print(\"changelog =\", self.changelog)\n\n        # make directories\n        if self.spec_only:\n            spec_dir = self.dist_dir\n            self.mkpath(spec_dir)\n        else:\n            rpm_dir = {}\n            for d in ('SOURCES', 'SPECS', 'BUILD', 'RPMS', 'SRPMS'):\n                rpm_dir[d] = os.path.join(self.rpm_base, d)\n                self.mkpath(rpm_dir[d])\n            spec_dir = rpm_dir['SPECS']\n\n        # Spec file goes into 'dist_dir' if '--spec-only specified',\n        # build/rpm.<plat> otherwise.\n        spec_path = os.path.join(spec_dir, \"%s.spec\" % self.distribution.get_name())\n        self.execute(\n            write_file, (spec_path, self._make_spec_file()), \"writing '%s'\" % spec_path\n        )\n\n        if self.spec_only:  # stop if requested\n            return\n\n        # Make a source distribution and copy to SOURCES directory with\n        # optional icon.\n        saved_dist_files = self.distribution.dist_files[:]\n        sdist = self.reinitialize_command('sdist')\n        if self.use_bzip2:\n            sdist.formats = ['bztar']\n        else:\n            sdist.formats = ['gztar']\n        self.run_command('sdist')\n        self.distribution.dist_files = saved_dist_files\n\n        source = sdist.get_archive_files()[0]\n        source_dir = rpm_dir['SOURCES']\n        self.copy_file(source, source_dir)\n\n        if self.icon:\n            if os.path.exists(self.icon):\n                self.copy_file(self.icon, source_dir)\n            else:\n                raise DistutilsFileError(\"icon file '%s' does not exist\" % self.icon)\n\n        # build package\n        log.info(\"building RPMs\")\n        rpm_cmd = ['rpmbuild']\n\n        if self.source_only:  # what kind of RPMs?\n            rpm_cmd.append('-bs')\n        elif self.binary_only:\n            rpm_cmd.append('-bb')\n        else:\n            rpm_cmd.append('-ba')\n        rpm_cmd.extend(['--define', '__python %s' % self.python])\n        if self.rpm3_mode:\n            rpm_cmd.extend(['--define', '_topdir %s' % os.path.abspath(self.rpm_base)])\n        if not self.keep_temp:\n            rpm_cmd.append('--clean')\n\n        if self.quiet:\n            rpm_cmd.append('--quiet')\n\n        rpm_cmd.append(spec_path)\n        # Determine the binary rpm names that should be built out of this spec\n        # file\n        # Note that some of these may not be really built (if the file\n        # list is empty)\n        nvr_string = \"%{name}-%{version}-%{release}\"\n        src_rpm = nvr_string + \".src.rpm\"\n        non_src_rpm = \"%{arch}/\" + nvr_string + \".%{arch}.rpm\"\n        q_cmd = r\"rpm -q --qf '{} {}\\n' --specfile '{}'\".format(\n            src_rpm,\n            non_src_rpm,\n            spec_path,\n        )\n\n        out = os.popen(q_cmd)\n        try:\n            binary_rpms = []\n            source_rpm = None\n            while True:\n                line = out.readline()\n                if not line:\n                    break\n                ell = line.strip().split()\n                assert len(ell) == 2\n                binary_rpms.append(ell[1])\n                # The source rpm is named after the first entry in the spec file\n                if source_rpm is None:\n                    source_rpm = ell[0]\n\n            status = out.close()\n            if status:\n                raise DistutilsExecError(\"Failed to execute: %s\" % repr(q_cmd))\n\n        finally:\n            out.close()\n\n        self.spawn(rpm_cmd)\n\n        if not self.dry_run:\n            if self.distribution.has_ext_modules():\n                pyversion = get_python_version()\n            else:\n                pyversion = 'any'\n\n            if not self.binary_only:\n                srpm = os.path.join(rpm_dir['SRPMS'], source_rpm)\n                assert os.path.exists(srpm)\n                self.move_file(srpm, self.dist_dir)\n                filename = os.path.join(self.dist_dir, source_rpm)\n                self.distribution.dist_files.append(('bdist_rpm', pyversion, filename))\n\n            if not self.source_only:\n                for rpm in binary_rpms:\n                    rpm = os.path.join(rpm_dir['RPMS'], rpm)\n                    if os.path.exists(rpm):\n                        self.move_file(rpm, self.dist_dir)\n                        filename = os.path.join(self.dist_dir, os.path.basename(rpm))\n                        self.distribution.dist_files.append(\n                            ('bdist_rpm', pyversion, filename)\n                        )\n\n    def _dist_path(self, path):\n        return os.path.join(self.dist_dir, os.path.basename(path))\n\n    def _make_spec_file(self):  # noqa: C901\n        \"\"\"Generate the text of an RPM spec file and return it as a\n        list of strings (one per line).\n        \"\"\"\n        # definitions and headers\n        spec_file = [\n            '%define name ' + self.distribution.get_name(),\n            '%define version ' + self.distribution.get_version().replace('-', '_'),\n            '%define unmangled_version ' + self.distribution.get_version(),\n            '%define release ' + self.release.replace('-', '_'),\n            '',\n            'Summary: ' + (self.distribution.get_description() or \"UNKNOWN\"),\n        ]\n\n        # Workaround for #14443 which affects some RPM based systems such as\n        # RHEL6 (and probably derivatives)\n        vendor_hook = subprocess.getoutput('rpm --eval %{__os_install_post}')\n        # Generate a potential replacement value for __os_install_post (whilst\n        # normalizing the whitespace to simplify the test for whether the\n        # invocation of brp-python-bytecompile passes in __python):\n        vendor_hook = '\\n'.join(\n            ['  %s \\\\' % line.strip() for line in vendor_hook.splitlines()]\n        )\n        problem = \"brp-python-bytecompile \\\\\\n\"\n        fixed = \"brp-python-bytecompile %{__python} \\\\\\n\"\n        fixed_hook = vendor_hook.replace(problem, fixed)\n        if fixed_hook != vendor_hook:\n            spec_file.append('# Workaround for http://bugs.python.org/issue14443')\n            spec_file.append('%define __os_install_post ' + fixed_hook + '\\n')\n\n        # put locale summaries into spec file\n        # XXX not supported for now (hard to put a dictionary\n        # in a config file -- arg!)\n        # for locale in self.summaries.keys():\n        #    spec_file.append('Summary(%s): %s' % (locale,\n        #                                          self.summaries[locale]))\n\n        spec_file.extend(\n            [\n                'Name: %{name}',\n                'Version: %{version}',\n                'Release: %{release}',\n            ]\n        )\n\n        # XXX yuck! this filename is available from the \"sdist\" command,\n        # but only after it has run: and we create the spec file before\n        # running \"sdist\", in case of --spec-only.\n        if self.use_bzip2:\n            spec_file.append('Source0: %{name}-%{unmangled_version}.tar.bz2')\n        else:\n            spec_file.append('Source0: %{name}-%{unmangled_version}.tar.gz')\n\n        spec_file.extend(\n            [\n                'License: ' + (self.distribution.get_license() or \"UNKNOWN\"),\n                'Group: ' + self.group,\n                'BuildRoot: %{_tmppath}/%{name}-%{version}-%{release}-buildroot',\n                'Prefix: %{_prefix}',\n            ]\n        )\n\n        if not self.force_arch:\n            # noarch if no extension modules\n            if not self.distribution.has_ext_modules():\n                spec_file.append('BuildArch: noarch')\n        else:\n            spec_file.append('BuildArch: %s' % self.force_arch)\n\n        for field in (\n            'Vendor',\n            'Packager',\n            'Provides',\n            'Requires',\n            'Conflicts',\n            'Obsoletes',\n        ):\n            val = getattr(self, field.lower())\n            if isinstance(val, list):\n                spec_file.append('{}: {}'.format(field, ' '.join(val)))\n            elif val is not None:\n                spec_file.append('{}: {}'.format(field, val))\n\n        if self.distribution.get_url():\n            spec_file.append('Url: ' + self.distribution.get_url())\n\n        if self.distribution_name:\n            spec_file.append('Distribution: ' + self.distribution_name)\n\n        if self.build_requires:\n            spec_file.append('BuildRequires: ' + ' '.join(self.build_requires))\n\n        if self.icon:\n            spec_file.append('Icon: ' + os.path.basename(self.icon))\n\n        if self.no_autoreq:\n            spec_file.append('AutoReq: 0')\n\n        spec_file.extend(\n            [\n                '',\n                '%description',\n                self.distribution.get_long_description() or \"\",\n            ]\n        )\n\n        # put locale descriptions into spec file\n        # XXX again, suppressed because config file syntax doesn't\n        # easily support this ;-(\n        # for locale in self.descriptions.keys():\n        #    spec_file.extend([\n        #        '',\n        #        '%description -l ' + locale,\n        #        self.descriptions[locale],\n        #        ])\n\n        # rpm scripts\n        # figure out default build script\n        def_setup_call = \"{} {}\".format(self.python, os.path.basename(sys.argv[0]))\n        def_build = \"%s build\" % def_setup_call\n        if self.use_rpm_opt_flags:\n            def_build = 'env CFLAGS=\"$RPM_OPT_FLAGS\" ' + def_build\n\n        # insert contents of files\n\n        # XXX this is kind of misleading: user-supplied options are files\n        # that we open and interpolate into the spec file, but the defaults\n        # are just text that we drop in as-is.  Hmmm.\n\n        install_cmd = (\n            '%s install -O1 --root=$RPM_BUILD_ROOT ' '--record=INSTALLED_FILES'\n        ) % def_setup_call\n\n        script_options = [\n            ('prep', 'prep_script', \"%setup -n %{name}-%{unmangled_version}\"),\n            ('build', 'build_script', def_build),\n            ('install', 'install_script', install_cmd),\n            ('clean', 'clean_script', \"rm -rf $RPM_BUILD_ROOT\"),\n            ('verifyscript', 'verify_script', None),\n            ('pre', 'pre_install', None),\n            ('post', 'post_install', None),\n            ('preun', 'pre_uninstall', None),\n            ('postun', 'post_uninstall', None),\n        ]\n\n        for (rpm_opt, attr, default) in script_options:\n            # Insert contents of file referred to, if no file is referred to\n            # use 'default' as contents of script\n            val = getattr(self, attr)\n            if val or default:\n                spec_file.extend(\n                    [\n                        '',\n                        '%' + rpm_opt,\n                    ]\n                )\n                if val:\n                    with open(val) as f:\n                        spec_file.extend(f.read().split('\\n'))\n                else:\n                    spec_file.append(default)\n\n        # files section\n        spec_file.extend(\n            [\n                '',\n                '%files -f INSTALLED_FILES',\n                '%defattr(-,root,root)',\n            ]\n        )\n\n        if self.doc_files:\n            spec_file.append('%doc ' + ' '.join(self.doc_files))\n\n        if self.changelog:\n            spec_file.extend(\n                [\n                    '',\n                    '%changelog',\n                ]\n            )\n            spec_file.extend(self.changelog)\n\n        return spec_file\n\n    def _format_changelog(self, changelog):\n        \"\"\"Format the changelog correctly and convert it to a list of strings\"\"\"\n        if not changelog:\n            return changelog\n        new_changelog = []\n        for line in changelog.strip().split('\\n'):\n            line = line.strip()\n            if line[0] == '*':\n                new_changelog.extend(['', line])\n            elif line[0] == '-':\n                new_changelog.append(line)\n            else:\n                new_changelog.append('  ' + line)\n\n        # strip trailing newline inserted by first changelog entry\n        if not new_changelog[0]:\n            del new_changelog[0]\n\n        return new_changelog\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/build.py",
    "content": "\"\"\"distutils.command.build\n\nImplements the Distutils 'build' command.\"\"\"\n\nimport sys\nimport os\nfrom distutils.core import Command\nfrom distutils.errors import DistutilsOptionError\nfrom distutils.util import get_platform\n\n\ndef show_compilers():\n    from distutils.ccompiler import show_compilers\n\n    show_compilers()\n\n\nclass build(Command):\n\n    description = \"build everything needed to install\"\n\n    user_options = [\n        ('build-base=', 'b', \"base directory for build library\"),\n        ('build-purelib=', None, \"build directory for platform-neutral distributions\"),\n        ('build-platlib=', None, \"build directory for platform-specific distributions\"),\n        (\n            'build-lib=',\n            None,\n            \"build directory for all distribution (defaults to either \"\n            + \"build-purelib or build-platlib\",\n        ),\n        ('build-scripts=', None, \"build directory for scripts\"),\n        ('build-temp=', 't', \"temporary build directory\"),\n        (\n            'plat-name=',\n            'p',\n            \"platform name to build for, if supported \"\n            \"(default: %s)\" % get_platform(),\n        ),\n        ('compiler=', 'c', \"specify the compiler type\"),\n        ('parallel=', 'j', \"number of parallel build jobs\"),\n        ('debug', 'g', \"compile extensions and libraries with debugging information\"),\n        ('force', 'f', \"forcibly build everything (ignore file timestamps)\"),\n        ('executable=', 'e', \"specify final destination interpreter path (build.py)\"),\n    ]\n\n    boolean_options = ['debug', 'force']\n\n    help_options = [\n        ('help-compiler', None, \"list available compilers\", show_compilers),\n    ]\n\n    def initialize_options(self):\n        self.build_base = 'build'\n        # these are decided only after 'build_base' has its final value\n        # (unless overridden by the user or client)\n        self.build_purelib = None\n        self.build_platlib = None\n        self.build_lib = None\n        self.build_temp = None\n        self.build_scripts = None\n        self.compiler = None\n        self.plat_name = None\n        self.debug = None\n        self.force = 0\n        self.executable = None\n        self.parallel = None\n\n    def finalize_options(self):  # noqa: C901\n        if self.plat_name is None:\n            self.plat_name = get_platform()\n        else:\n            # plat-name only supported for windows (other platforms are\n            # supported via ./configure flags, if at all).  Avoid misleading\n            # other platforms.\n            if os.name != 'nt':\n                raise DistutilsOptionError(\n                    \"--plat-name only supported on Windows (try \"\n                    \"using './configure --help' on your platform)\"\n                )\n\n        plat_specifier = \".{}-{}\".format(self.plat_name, sys.implementation.cache_tag)\n\n        # Make it so Python 2.x and Python 2.x with --with-pydebug don't\n        # share the same build directories. Doing so confuses the build\n        # process for C modules\n        if hasattr(sys, 'gettotalrefcount'):\n            plat_specifier += '-pydebug'\n\n        # 'build_purelib' and 'build_platlib' just default to 'lib' and\n        # 'lib.<plat>' under the base build directory.  We only use one of\n        # them for a given distribution, though --\n        if self.build_purelib is None:\n            self.build_purelib = os.path.join(self.build_base, 'lib')\n        if self.build_platlib is None:\n            self.build_platlib = os.path.join(self.build_base, 'lib' + plat_specifier)\n\n        # 'build_lib' is the actual directory that we will use for this\n        # particular module distribution -- if user didn't supply it, pick\n        # one of 'build_purelib' or 'build_platlib'.\n        if self.build_lib is None:\n            if self.distribution.has_ext_modules():\n                self.build_lib = self.build_platlib\n            else:\n                self.build_lib = self.build_purelib\n\n        # 'build_temp' -- temporary directory for compiler turds,\n        # \"build/temp.<plat>\"\n        if self.build_temp is None:\n            self.build_temp = os.path.join(self.build_base, 'temp' + plat_specifier)\n        if self.build_scripts is None:\n            self.build_scripts = os.path.join(\n                self.build_base, 'scripts-%d.%d' % sys.version_info[:2]\n            )\n\n        if self.executable is None and sys.executable:\n            self.executable = os.path.normpath(sys.executable)\n\n        if isinstance(self.parallel, str):\n            try:\n                self.parallel = int(self.parallel)\n            except ValueError:\n                raise DistutilsOptionError(\"parallel should be an integer\")\n\n    def run(self):\n        # Run all relevant sub-commands.  This will be some subset of:\n        #  - build_py      - pure Python modules\n        #  - build_clib    - standalone C libraries\n        #  - build_ext     - Python extensions\n        #  - build_scripts - (Python) scripts\n        for cmd_name in self.get_sub_commands():\n            self.run_command(cmd_name)\n\n    # -- Predicates for the sub-command list ---------------------------\n\n    def has_pure_modules(self):\n        return self.distribution.has_pure_modules()\n\n    def has_c_libraries(self):\n        return self.distribution.has_c_libraries()\n\n    def has_ext_modules(self):\n        return self.distribution.has_ext_modules()\n\n    def has_scripts(self):\n        return self.distribution.has_scripts()\n\n    sub_commands = [\n        ('build_py', has_pure_modules),\n        ('build_clib', has_c_libraries),\n        ('build_ext', has_ext_modules),\n        ('build_scripts', has_scripts),\n    ]\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/build_clib.py",
    "content": "\"\"\"distutils.command.build_clib\n\nImplements the Distutils 'build_clib' command, to build a C/C++ library\nthat is included in the module distribution and needed by an extension\nmodule.\"\"\"\n\n\n# XXX this module has *lots* of code ripped-off quite transparently from\n# build_ext.py -- not surprisingly really, as the work required to build\n# a static library from a collection of C source files is not really all\n# that different from what's required to build a shared object file from\n# a collection of C source files.  Nevertheless, I haven't done the\n# necessary refactoring to account for the overlap in code between the\n# two modules, mainly because a number of subtle details changed in the\n# cut 'n paste.  Sigh.\n\nimport os\nfrom distutils.core import Command\nfrom distutils.errors import DistutilsSetupError\nfrom distutils.sysconfig import customize_compiler\nfrom distutils import log\n\n\ndef show_compilers():\n    from distutils.ccompiler import show_compilers\n\n    show_compilers()\n\n\nclass build_clib(Command):\n\n    description = \"build C/C++ libraries used by Python extensions\"\n\n    user_options = [\n        ('build-clib=', 'b', \"directory to build C/C++ libraries to\"),\n        ('build-temp=', 't', \"directory to put temporary build by-products\"),\n        ('debug', 'g', \"compile with debugging information\"),\n        ('force', 'f', \"forcibly build everything (ignore file timestamps)\"),\n        ('compiler=', 'c', \"specify the compiler type\"),\n    ]\n\n    boolean_options = ['debug', 'force']\n\n    help_options = [\n        ('help-compiler', None, \"list available compilers\", show_compilers),\n    ]\n\n    def initialize_options(self):\n        self.build_clib = None\n        self.build_temp = None\n\n        # List of libraries to build\n        self.libraries = None\n\n        # Compilation options for all libraries\n        self.include_dirs = None\n        self.define = None\n        self.undef = None\n        self.debug = None\n        self.force = 0\n        self.compiler = None\n\n    def finalize_options(self):\n        # This might be confusing: both build-clib and build-temp default\n        # to build-temp as defined by the \"build\" command.  This is because\n        # I think that C libraries are really just temporary build\n        # by-products, at least from the point of view of building Python\n        # extensions -- but I want to keep my options open.\n        self.set_undefined_options(\n            'build',\n            ('build_temp', 'build_clib'),\n            ('build_temp', 'build_temp'),\n            ('compiler', 'compiler'),\n            ('debug', 'debug'),\n            ('force', 'force'),\n        )\n\n        self.libraries = self.distribution.libraries\n        if self.libraries:\n            self.check_library_list(self.libraries)\n\n        if self.include_dirs is None:\n            self.include_dirs = self.distribution.include_dirs or []\n        if isinstance(self.include_dirs, str):\n            self.include_dirs = self.include_dirs.split(os.pathsep)\n\n        # XXX same as for build_ext -- what about 'self.define' and\n        # 'self.undef' ?\n\n    def run(self):\n        if not self.libraries:\n            return\n\n        # Yech -- this is cut 'n pasted from build_ext.py!\n        from distutils.ccompiler import new_compiler\n\n        self.compiler = new_compiler(\n            compiler=self.compiler, dry_run=self.dry_run, force=self.force\n        )\n        customize_compiler(self.compiler)\n\n        if self.include_dirs is not None:\n            self.compiler.set_include_dirs(self.include_dirs)\n        if self.define is not None:\n            # 'define' option is a list of (name,value) tuples\n            for (name, value) in self.define:\n                self.compiler.define_macro(name, value)\n        if self.undef is not None:\n            for macro in self.undef:\n                self.compiler.undefine_macro(macro)\n\n        self.build_libraries(self.libraries)\n\n    def check_library_list(self, libraries):\n        \"\"\"Ensure that the list of libraries is valid.\n\n        `library` is presumably provided as a command option 'libraries'.\n        This method checks that it is a list of 2-tuples, where the tuples\n        are (library_name, build_info_dict).\n\n        Raise DistutilsSetupError if the structure is invalid anywhere;\n        just returns otherwise.\n        \"\"\"\n        if not isinstance(libraries, list):\n            raise DistutilsSetupError(\"'libraries' option must be a list of tuples\")\n\n        for lib in libraries:\n            if not isinstance(lib, tuple) and len(lib) != 2:\n                raise DistutilsSetupError(\"each element of 'libraries' must a 2-tuple\")\n\n            name, build_info = lib\n\n            if not isinstance(name, str):\n                raise DistutilsSetupError(\n                    \"first element of each tuple in 'libraries' \"\n                    \"must be a string (the library name)\"\n                )\n\n            if '/' in name or (os.sep != '/' and os.sep in name):\n                raise DistutilsSetupError(\n                    \"bad library name '%s': \"\n                    \"may not contain directory separators\" % lib[0]\n                )\n\n            if not isinstance(build_info, dict):\n                raise DistutilsSetupError(\n                    \"second element of each tuple in 'libraries' \"\n                    \"must be a dictionary (build info)\"\n                )\n\n    def get_library_names(self):\n        # Assume the library list is valid -- 'check_library_list()' is\n        # called from 'finalize_options()', so it should be!\n        if not self.libraries:\n            return None\n\n        lib_names = []\n        for (lib_name, build_info) in self.libraries:\n            lib_names.append(lib_name)\n        return lib_names\n\n    def get_source_files(self):\n        self.check_library_list(self.libraries)\n        filenames = []\n        for (lib_name, build_info) in self.libraries:\n            sources = build_info.get('sources')\n            if sources is None or not isinstance(sources, (list, tuple)):\n                raise DistutilsSetupError(\n                    \"in 'libraries' option (library '%s'), \"\n                    \"'sources' must be present and must be \"\n                    \"a list of source filenames\" % lib_name\n                )\n\n            filenames.extend(sources)\n        return filenames\n\n    def build_libraries(self, libraries):\n        for (lib_name, build_info) in libraries:\n            sources = build_info.get('sources')\n            if sources is None or not isinstance(sources, (list, tuple)):\n                raise DistutilsSetupError(\n                    \"in 'libraries' option (library '%s'), \"\n                    \"'sources' must be present and must be \"\n                    \"a list of source filenames\" % lib_name\n                )\n            sources = list(sources)\n\n            log.info(\"building '%s' library\", lib_name)\n\n            # First, compile the source code to object files in the library\n            # directory.  (This should probably change to putting object\n            # files in a temporary build directory.)\n            macros = build_info.get('macros')\n            include_dirs = build_info.get('include_dirs')\n            objects = self.compiler.compile(\n                sources,\n                output_dir=self.build_temp,\n                macros=macros,\n                include_dirs=include_dirs,\n                debug=self.debug,\n            )\n\n            # Now \"link\" the object files together into a static library.\n            # (On Unix at least, this isn't really linking -- it just\n            # builds an archive.  Whatever.)\n            self.compiler.create_static_lib(\n                objects, lib_name, output_dir=self.build_clib, debug=self.debug\n            )\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/build_ext.py",
    "content": "\"\"\"distutils.command.build_ext\n\nImplements the Distutils 'build_ext' command, for building extension\nmodules (currently limited to C extensions, should accommodate C++\nextensions ASAP).\"\"\"\n\nimport contextlib\nimport os\nimport re\nimport sys\nfrom distutils.core import Command\nfrom distutils.errors import (\n    DistutilsOptionError,\n    DistutilsSetupError,\n    CCompilerError,\n    DistutilsError,\n    CompileError,\n    DistutilsPlatformError,\n)\nfrom distutils.sysconfig import customize_compiler, get_python_version\nfrom distutils.sysconfig import get_config_h_filename\nfrom distutils.dep_util import newer_group\nfrom distutils.extension import Extension\nfrom distutils.util import get_platform\nfrom distutils import log\nfrom . import py37compat\n\nfrom site import USER_BASE\n\n# An extension name is just a dot-separated list of Python NAMEs (ie.\n# the same as a fully-qualified module name).\nextension_name_re = re.compile(r'^[a-zA-Z_][a-zA-Z_0-9]*(\\.[a-zA-Z_][a-zA-Z_0-9]*)*$')\n\n\ndef show_compilers():\n    from distutils.ccompiler import show_compilers\n\n    show_compilers()\n\n\nclass build_ext(Command):\n\n    description = \"build C/C++ extensions (compile/link to build directory)\"\n\n    # XXX thoughts on how to deal with complex command-line options like\n    # these, i.e. how to make it so fancy_getopt can suck them off the\n    # command line and make it look like setup.py defined the appropriate\n    # lists of tuples of what-have-you.\n    #   - each command needs a callback to process its command-line options\n    #   - Command.__init__() needs access to its share of the whole\n    #     command line (must ultimately come from\n    #     Distribution.parse_command_line())\n    #   - it then calls the current command class' option-parsing\n    #     callback to deal with weird options like -D, which have to\n    #     parse the option text and churn out some custom data\n    #     structure\n    #   - that data structure (in this case, a list of 2-tuples)\n    #     will then be present in the command object by the time\n    #     we get to finalize_options() (i.e. the constructor\n    #     takes care of both command-line and client options\n    #     in between initialize_options() and finalize_options())\n\n    sep_by = \" (separated by '%s')\" % os.pathsep\n    user_options = [\n        ('build-lib=', 'b', \"directory for compiled extension modules\"),\n        ('build-temp=', 't', \"directory for temporary files (build by-products)\"),\n        (\n            'plat-name=',\n            'p',\n            \"platform name to cross-compile for, if supported \"\n            \"(default: %s)\" % get_platform(),\n        ),\n        (\n            'inplace',\n            'i',\n            \"ignore build-lib and put compiled extensions into the source \"\n            + \"directory alongside your pure Python modules\",\n        ),\n        (\n            'include-dirs=',\n            'I',\n            \"list of directories to search for header files\" + sep_by,\n        ),\n        ('define=', 'D', \"C preprocessor macros to define\"),\n        ('undef=', 'U', \"C preprocessor macros to undefine\"),\n        ('libraries=', 'l', \"external C libraries to link with\"),\n        (\n            'library-dirs=',\n            'L',\n            \"directories to search for external C libraries\" + sep_by,\n        ),\n        ('rpath=', 'R', \"directories to search for shared C libraries at runtime\"),\n        ('link-objects=', 'O', \"extra explicit link objects to include in the link\"),\n        ('debug', 'g', \"compile/link with debugging information\"),\n        ('force', 'f', \"forcibly build everything (ignore file timestamps)\"),\n        ('compiler=', 'c', \"specify the compiler type\"),\n        ('parallel=', 'j', \"number of parallel build jobs\"),\n        ('swig-cpp', None, \"make SWIG create C++ files (default is C)\"),\n        ('swig-opts=', None, \"list of SWIG command line options\"),\n        ('swig=', None, \"path to the SWIG executable\"),\n        ('user', None, \"add user include, library and rpath\"),\n    ]\n\n    boolean_options = ['inplace', 'debug', 'force', 'swig-cpp', 'user']\n\n    help_options = [\n        ('help-compiler', None, \"list available compilers\", show_compilers),\n    ]\n\n    def initialize_options(self):\n        self.extensions = None\n        self.build_lib = None\n        self.plat_name = None\n        self.build_temp = None\n        self.inplace = 0\n        self.package = None\n\n        self.include_dirs = None\n        self.define = None\n        self.undef = None\n        self.libraries = None\n        self.library_dirs = None\n        self.rpath = None\n        self.link_objects = None\n        self.debug = None\n        self.force = None\n        self.compiler = None\n        self.swig = None\n        self.swig_cpp = None\n        self.swig_opts = None\n        self.user = None\n        self.parallel = None\n\n    def finalize_options(self):  # noqa: C901\n        from distutils import sysconfig\n\n        self.set_undefined_options(\n            'build',\n            ('build_lib', 'build_lib'),\n            ('build_temp', 'build_temp'),\n            ('compiler', 'compiler'),\n            ('debug', 'debug'),\n            ('force', 'force'),\n            ('parallel', 'parallel'),\n            ('plat_name', 'plat_name'),\n        )\n\n        if self.package is None:\n            self.package = self.distribution.ext_package\n\n        self.extensions = self.distribution.ext_modules\n\n        # Make sure Python's include directories (for Python.h, pyconfig.h,\n        # etc.) are in the include search path.\n        py_include = sysconfig.get_python_inc()\n        plat_py_include = sysconfig.get_python_inc(plat_specific=1)\n        if self.include_dirs is None:\n            self.include_dirs = self.distribution.include_dirs or []\n        if isinstance(self.include_dirs, str):\n            self.include_dirs = self.include_dirs.split(os.pathsep)\n\n        # If in a virtualenv, add its include directory\n        # Issue 16116\n        if sys.exec_prefix != sys.base_exec_prefix:\n            self.include_dirs.append(os.path.join(sys.exec_prefix, 'include'))\n\n        # Put the Python \"system\" include dir at the end, so that\n        # any local include dirs take precedence.\n        self.include_dirs.extend(py_include.split(os.path.pathsep))\n        if plat_py_include != py_include:\n            self.include_dirs.extend(plat_py_include.split(os.path.pathsep))\n\n        self.ensure_string_list('libraries')\n        self.ensure_string_list('link_objects')\n\n        # Life is easier if we're not forever checking for None, so\n        # simplify these options to empty lists if unset\n        if self.libraries is None:\n            self.libraries = []\n        if self.library_dirs is None:\n            self.library_dirs = []\n        elif isinstance(self.library_dirs, str):\n            self.library_dirs = self.library_dirs.split(os.pathsep)\n\n        if self.rpath is None:\n            self.rpath = []\n        elif isinstance(self.rpath, str):\n            self.rpath = self.rpath.split(os.pathsep)\n\n        # for extensions under windows use different directories\n        # for Release and Debug builds.\n        # also Python's library directory must be appended to library_dirs\n        if os.name == 'nt':\n            # the 'libs' directory is for binary installs - we assume that\n            # must be the *native* platform.  But we don't really support\n            # cross-compiling via a binary install anyway, so we let it go.\n            self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs'))\n            if sys.base_exec_prefix != sys.prefix:  # Issue 16116\n                self.library_dirs.append(os.path.join(sys.base_exec_prefix, 'libs'))\n            if self.debug:\n                self.build_temp = os.path.join(self.build_temp, \"Debug\")\n            else:\n                self.build_temp = os.path.join(self.build_temp, \"Release\")\n\n            # Append the source distribution include and library directories,\n            # this allows distutils on windows to work in the source tree\n            self.include_dirs.append(os.path.dirname(get_config_h_filename()))\n            self.library_dirs.append(sys.base_exec_prefix)\n\n            # Use the .lib files for the correct architecture\n            if self.plat_name == 'win32':\n                suffix = 'win32'\n            else:\n                # win-amd64\n                suffix = self.plat_name[4:]\n            new_lib = os.path.join(sys.exec_prefix, 'PCbuild')\n            if suffix:\n                new_lib = os.path.join(new_lib, suffix)\n            self.library_dirs.append(new_lib)\n\n        # For extensions under Cygwin, Python's library directory must be\n        # appended to library_dirs\n        if sys.platform[:6] == 'cygwin':\n            if not sysconfig.python_build:\n                # building third party extensions\n                self.library_dirs.append(\n                    os.path.join(\n                        sys.prefix, \"lib\", \"python\" + get_python_version(), \"config\"\n                    )\n                )\n            else:\n                # building python standard extensions\n                self.library_dirs.append('.')\n\n        # For building extensions with a shared Python library,\n        # Python's library directory must be appended to library_dirs\n        # See Issues: #1600860, #4366\n        if sysconfig.get_config_var('Py_ENABLE_SHARED'):\n            if not sysconfig.python_build:\n                # building third party extensions\n                self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))\n            else:\n                # building python standard extensions\n                self.library_dirs.append('.')\n\n        # The argument parsing will result in self.define being a string, but\n        # it has to be a list of 2-tuples.  All the preprocessor symbols\n        # specified by the 'define' option will be set to '1'.  Multiple\n        # symbols can be separated with commas.\n\n        if self.define:\n            defines = self.define.split(',')\n            self.define = [(symbol, '1') for symbol in defines]\n\n        # The option for macros to undefine is also a string from the\n        # option parsing, but has to be a list.  Multiple symbols can also\n        # be separated with commas here.\n        if self.undef:\n            self.undef = self.undef.split(',')\n\n        if self.swig_opts is None:\n            self.swig_opts = []\n        else:\n            self.swig_opts = self.swig_opts.split(' ')\n\n        # Finally add the user include and library directories if requested\n        if self.user:\n            user_include = os.path.join(USER_BASE, \"include\")\n            user_lib = os.path.join(USER_BASE, \"lib\")\n            if os.path.isdir(user_include):\n                self.include_dirs.append(user_include)\n            if os.path.isdir(user_lib):\n                self.library_dirs.append(user_lib)\n                self.rpath.append(user_lib)\n\n        if isinstance(self.parallel, str):\n            try:\n                self.parallel = int(self.parallel)\n            except ValueError:\n                raise DistutilsOptionError(\"parallel should be an integer\")\n\n    def run(self):  # noqa: C901\n        from distutils.ccompiler import new_compiler\n\n        # 'self.extensions', as supplied by setup.py, is a list of\n        # Extension instances.  See the documentation for Extension (in\n        # distutils.extension) for details.\n        #\n        # For backwards compatibility with Distutils 0.8.2 and earlier, we\n        # also allow the 'extensions' list to be a list of tuples:\n        #    (ext_name, build_info)\n        # where build_info is a dictionary containing everything that\n        # Extension instances do except the name, with a few things being\n        # differently named.  We convert these 2-tuples to Extension\n        # instances as needed.\n\n        if not self.extensions:\n            return\n\n        # If we were asked to build any C/C++ libraries, make sure that the\n        # directory where we put them is in the library search path for\n        # linking extensions.\n        if self.distribution.has_c_libraries():\n            build_clib = self.get_finalized_command('build_clib')\n            self.libraries.extend(build_clib.get_library_names() or [])\n            self.library_dirs.append(build_clib.build_clib)\n\n        # Setup the CCompiler object that we'll use to do all the\n        # compiling and linking\n        self.compiler = new_compiler(\n            compiler=self.compiler,\n            verbose=self.verbose,\n            dry_run=self.dry_run,\n            force=self.force,\n        )\n        customize_compiler(self.compiler)\n        # If we are cross-compiling, init the compiler now (if we are not\n        # cross-compiling, init would not hurt, but people may rely on\n        # late initialization of compiler even if they shouldn't...)\n        if os.name == 'nt' and self.plat_name != get_platform():\n            self.compiler.initialize(self.plat_name)\n\n        # And make sure that any compile/link-related options (which might\n        # come from the command-line or from the setup script) are set in\n        # that CCompiler object -- that way, they automatically apply to\n        # all compiling and linking done here.\n        if self.include_dirs is not None:\n            self.compiler.set_include_dirs(self.include_dirs)\n        if self.define is not None:\n            # 'define' option is a list of (name,value) tuples\n            for (name, value) in self.define:\n                self.compiler.define_macro(name, value)\n        if self.undef is not None:\n            for macro in self.undef:\n                self.compiler.undefine_macro(macro)\n        if self.libraries is not None:\n            self.compiler.set_libraries(self.libraries)\n        if self.library_dirs is not None:\n            self.compiler.set_library_dirs(self.library_dirs)\n        if self.rpath is not None:\n            self.compiler.set_runtime_library_dirs(self.rpath)\n        if self.link_objects is not None:\n            self.compiler.set_link_objects(self.link_objects)\n\n        # Now actually compile and link everything.\n        self.build_extensions()\n\n    def check_extensions_list(self, extensions):  # noqa: C901\n        \"\"\"Ensure that the list of extensions (presumably provided as a\n        command option 'extensions') is valid, i.e. it is a list of\n        Extension objects.  We also support the old-style list of 2-tuples,\n        where the tuples are (ext_name, build_info), which are converted to\n        Extension instances here.\n\n        Raise DistutilsSetupError if the structure is invalid anywhere;\n        just returns otherwise.\n        \"\"\"\n        if not isinstance(extensions, list):\n            raise DistutilsSetupError(\n                \"'ext_modules' option must be a list of Extension instances\"\n            )\n\n        for i, ext in enumerate(extensions):\n            if isinstance(ext, Extension):\n                continue  # OK! (assume type-checking done\n                # by Extension constructor)\n\n            if not isinstance(ext, tuple) or len(ext) != 2:\n                raise DistutilsSetupError(\n                    \"each element of 'ext_modules' option must be an \"\n                    \"Extension instance or 2-tuple\"\n                )\n\n            ext_name, build_info = ext\n\n            log.warn(\n                \"old-style (ext_name, build_info) tuple found in \"\n                \"ext_modules for extension '%s' \"\n                \"-- please convert to Extension instance\",\n                ext_name,\n            )\n\n            if not (isinstance(ext_name, str) and extension_name_re.match(ext_name)):\n                raise DistutilsSetupError(\n                    \"first element of each tuple in 'ext_modules' \"\n                    \"must be the extension name (a string)\"\n                )\n\n            if not isinstance(build_info, dict):\n                raise DistutilsSetupError(\n                    \"second element of each tuple in 'ext_modules' \"\n                    \"must be a dictionary (build info)\"\n                )\n\n            # OK, the (ext_name, build_info) dict is type-safe: convert it\n            # to an Extension instance.\n            ext = Extension(ext_name, build_info['sources'])\n\n            # Easy stuff: one-to-one mapping from dict elements to\n            # instance attributes.\n            for key in (\n                'include_dirs',\n                'library_dirs',\n                'libraries',\n                'extra_objects',\n                'extra_compile_args',\n                'extra_link_args',\n            ):\n                val = build_info.get(key)\n                if val is not None:\n                    setattr(ext, key, val)\n\n            # Medium-easy stuff: same syntax/semantics, different names.\n            ext.runtime_library_dirs = build_info.get('rpath')\n            if 'def_file' in build_info:\n                log.warn(\"'def_file' element of build info dict \" \"no longer supported\")\n\n            # Non-trivial stuff: 'macros' split into 'define_macros'\n            # and 'undef_macros'.\n            macros = build_info.get('macros')\n            if macros:\n                ext.define_macros = []\n                ext.undef_macros = []\n                for macro in macros:\n                    if not (isinstance(macro, tuple) and len(macro) in (1, 2)):\n                        raise DistutilsSetupError(\n                            \"'macros' element of build info dict \"\n                            \"must be 1- or 2-tuple\"\n                        )\n                    if len(macro) == 1:\n                        ext.undef_macros.append(macro[0])\n                    elif len(macro) == 2:\n                        ext.define_macros.append(macro)\n\n            extensions[i] = ext\n\n    def get_source_files(self):\n        self.check_extensions_list(self.extensions)\n        filenames = []\n\n        # Wouldn't it be neat if we knew the names of header files too...\n        for ext in self.extensions:\n            filenames.extend(ext.sources)\n        return filenames\n\n    def get_outputs(self):\n        # Sanity check the 'extensions' list -- can't assume this is being\n        # done in the same run as a 'build_extensions()' call (in fact, we\n        # can probably assume that it *isn't*!).\n        self.check_extensions_list(self.extensions)\n\n        # And build the list of output (built) filenames.  Note that this\n        # ignores the 'inplace' flag, and assumes everything goes in the\n        # \"build\" tree.\n        outputs = []\n        for ext in self.extensions:\n            outputs.append(self.get_ext_fullpath(ext.name))\n        return outputs\n\n    def build_extensions(self):\n        # First, sanity-check the 'extensions' list\n        self.check_extensions_list(self.extensions)\n        if self.parallel:\n            self._build_extensions_parallel()\n        else:\n            self._build_extensions_serial()\n\n    def _build_extensions_parallel(self):\n        workers = self.parallel\n        if self.parallel is True:\n            workers = os.cpu_count()  # may return None\n        try:\n            from concurrent.futures import ThreadPoolExecutor\n        except ImportError:\n            workers = None\n\n        if workers is None:\n            self._build_extensions_serial()\n            return\n\n        with ThreadPoolExecutor(max_workers=workers) as executor:\n            futures = [\n                executor.submit(self.build_extension, ext) for ext in self.extensions\n            ]\n            for ext, fut in zip(self.extensions, futures):\n                with self._filter_build_errors(ext):\n                    fut.result()\n\n    def _build_extensions_serial(self):\n        for ext in self.extensions:\n            with self._filter_build_errors(ext):\n                self.build_extension(ext)\n\n    @contextlib.contextmanager\n    def _filter_build_errors(self, ext):\n        try:\n            yield\n        except (CCompilerError, DistutilsError, CompileError) as e:\n            if not ext.optional:\n                raise\n            self.warn('building extension \"{}\" failed: {}'.format(ext.name, e))\n\n    def build_extension(self, ext):\n        sources = ext.sources\n        if sources is None or not isinstance(sources, (list, tuple)):\n            raise DistutilsSetupError(\n                \"in 'ext_modules' option (extension '%s'), \"\n                \"'sources' must be present and must be \"\n                \"a list of source filenames\" % ext.name\n            )\n        # sort to make the resulting .so file build reproducible\n        sources = sorted(sources)\n\n        ext_path = self.get_ext_fullpath(ext.name)\n        depends = sources + ext.depends\n        if not (self.force or newer_group(depends, ext_path, 'newer')):\n            log.debug(\"skipping '%s' extension (up-to-date)\", ext.name)\n            return\n        else:\n            log.info(\"building '%s' extension\", ext.name)\n\n        # First, scan the sources for SWIG definition files (.i), run\n        # SWIG on 'em to create .c files, and modify the sources list\n        # accordingly.\n        sources = self.swig_sources(sources, ext)\n\n        # Next, compile the source code to object files.\n\n        # XXX not honouring 'define_macros' or 'undef_macros' -- the\n        # CCompiler API needs to change to accommodate this, and I\n        # want to do one thing at a time!\n\n        # Two possible sources for extra compiler arguments:\n        #   - 'extra_compile_args' in Extension object\n        #   - CFLAGS environment variable (not particularly\n        #     elegant, but people seem to expect it and I\n        #     guess it's useful)\n        # The environment variable should take precedence, and\n        # any sensible compiler will give precedence to later\n        # command line args.  Hence we combine them in order:\n        extra_args = ext.extra_compile_args or []\n\n        macros = ext.define_macros[:]\n        for undef in ext.undef_macros:\n            macros.append((undef,))\n\n        objects = self.compiler.compile(\n            sources,\n            output_dir=self.build_temp,\n            macros=macros,\n            include_dirs=ext.include_dirs,\n            debug=self.debug,\n            extra_postargs=extra_args,\n            depends=ext.depends,\n        )\n\n        # XXX outdated variable, kept here in case third-part code\n        # needs it.\n        self._built_objects = objects[:]\n\n        # Now link the object files together into a \"shared object\" --\n        # of course, first we have to figure out all the other things\n        # that go into the mix.\n        if ext.extra_objects:\n            objects.extend(ext.extra_objects)\n        extra_args = ext.extra_link_args or []\n\n        # Detect target language, if not provided\n        language = ext.language or self.compiler.detect_language(sources)\n\n        self.compiler.link_shared_object(\n            objects,\n            ext_path,\n            libraries=self.get_libraries(ext),\n            library_dirs=ext.library_dirs,\n            runtime_library_dirs=ext.runtime_library_dirs,\n            extra_postargs=extra_args,\n            export_symbols=self.get_export_symbols(ext),\n            debug=self.debug,\n            build_temp=self.build_temp,\n            target_lang=language,\n        )\n\n    def swig_sources(self, sources, extension):\n        \"\"\"Walk the list of source files in 'sources', looking for SWIG\n        interface (.i) files.  Run SWIG on all that are found, and\n        return a modified 'sources' list with SWIG source files replaced\n        by the generated C (or C++) files.\n        \"\"\"\n        new_sources = []\n        swig_sources = []\n        swig_targets = {}\n\n        # XXX this drops generated C/C++ files into the source tree, which\n        # is fine for developers who want to distribute the generated\n        # source -- but there should be an option to put SWIG output in\n        # the temp dir.\n\n        if self.swig_cpp:\n            log.warn(\"--swig-cpp is deprecated - use --swig-opts=-c++\")\n\n        if (\n            self.swig_cpp\n            or ('-c++' in self.swig_opts)\n            or ('-c++' in extension.swig_opts)\n        ):\n            target_ext = '.cpp'\n        else:\n            target_ext = '.c'\n\n        for source in sources:\n            (base, ext) = os.path.splitext(source)\n            if ext == \".i\":  # SWIG interface file\n                new_sources.append(base + '_wrap' + target_ext)\n                swig_sources.append(source)\n                swig_targets[source] = new_sources[-1]\n            else:\n                new_sources.append(source)\n\n        if not swig_sources:\n            return new_sources\n\n        swig = self.swig or self.find_swig()\n        swig_cmd = [swig, \"-python\"]\n        swig_cmd.extend(self.swig_opts)\n        if self.swig_cpp:\n            swig_cmd.append(\"-c++\")\n\n        # Do not override commandline arguments\n        if not self.swig_opts:\n            for o in extension.swig_opts:\n                swig_cmd.append(o)\n\n        for source in swig_sources:\n            target = swig_targets[source]\n            log.info(\"swigging %s to %s\", source, target)\n            self.spawn(swig_cmd + [\"-o\", target, source])\n\n        return new_sources\n\n    def find_swig(self):\n        \"\"\"Return the name of the SWIG executable.  On Unix, this is\n        just \"swig\" -- it should be in the PATH.  Tries a bit harder on\n        Windows.\n        \"\"\"\n        if os.name == \"posix\":\n            return \"swig\"\n        elif os.name == \"nt\":\n            # Look for SWIG in its standard installation directory on\n            # Windows (or so I presume!).  If we find it there, great;\n            # if not, act like Unix and assume it's in the PATH.\n            for vers in (\"1.3\", \"1.2\", \"1.1\"):\n                fn = os.path.join(\"c:\\\\swig%s\" % vers, \"swig.exe\")\n                if os.path.isfile(fn):\n                    return fn\n            else:\n                return \"swig.exe\"\n        else:\n            raise DistutilsPlatformError(\n                \"I don't know how to find (much less run) SWIG \"\n                \"on platform '%s'\" % os.name\n            )\n\n    # -- Name generators -----------------------------------------------\n    # (extension names, filenames, whatever)\n    def get_ext_fullpath(self, ext_name):\n        \"\"\"Returns the path of the filename for a given extension.\n\n        The file is located in `build_lib` or directly in the package\n        (inplace option).\n        \"\"\"\n        fullname = self.get_ext_fullname(ext_name)\n        modpath = fullname.split('.')\n        filename = self.get_ext_filename(modpath[-1])\n\n        if not self.inplace:\n            # no further work needed\n            # returning :\n            #   build_dir/package/path/filename\n            filename = os.path.join(*modpath[:-1] + [filename])\n            return os.path.join(self.build_lib, filename)\n\n        # the inplace option requires to find the package directory\n        # using the build_py command for that\n        package = '.'.join(modpath[0:-1])\n        build_py = self.get_finalized_command('build_py')\n        package_dir = os.path.abspath(build_py.get_package_dir(package))\n\n        # returning\n        #   package_dir/filename\n        return os.path.join(package_dir, filename)\n\n    def get_ext_fullname(self, ext_name):\n        \"\"\"Returns the fullname of a given extension name.\n\n        Adds the `package.` prefix\"\"\"\n        if self.package is None:\n            return ext_name\n        else:\n            return self.package + '.' + ext_name\n\n    def get_ext_filename(self, ext_name):\n        r\"\"\"Convert the name of an extension (eg. \"foo.bar\") into the name\n        of the file from which it will be loaded (eg. \"foo/bar.so\", or\n        \"foo\\bar.pyd\").\n        \"\"\"\n        from distutils.sysconfig import get_config_var\n\n        ext_path = ext_name.split('.')\n        ext_suffix = get_config_var('EXT_SUFFIX')\n        return os.path.join(*ext_path) + ext_suffix\n\n    def get_export_symbols(self, ext):\n        \"\"\"Return the list of symbols that a shared extension has to\n        export.  This either uses 'ext.export_symbols' or, if it's not\n        provided, \"PyInit_\" + module_name.  Only relevant on Windows, where\n        the .pyd file (DLL) must export the module \"PyInit_\" function.\n        \"\"\"\n        name = ext.name.split('.')[-1]\n        try:\n            # Unicode module name support as defined in PEP-489\n            # https://www.python.org/dev/peps/pep-0489/#export-hook-name\n            name.encode('ascii')\n        except UnicodeEncodeError:\n            suffix = 'U_' + name.encode('punycode').replace(b'-', b'_').decode('ascii')\n        else:\n            suffix = \"_\" + name\n\n        initfunc_name = \"PyInit\" + suffix\n        if initfunc_name not in ext.export_symbols:\n            ext.export_symbols.append(initfunc_name)\n        return ext.export_symbols\n\n    def get_libraries(self, ext):  # noqa: C901\n        \"\"\"Return the list of libraries to link against when building a\n        shared extension.  On most platforms, this is just 'ext.libraries';\n        on Windows, we add the Python library (eg. python20.dll).\n        \"\"\"\n        # The python library is always needed on Windows.  For MSVC, this\n        # is redundant, since the library is mentioned in a pragma in\n        # pyconfig.h that MSVC groks.  The other Windows compilers all seem\n        # to need it mentioned explicitly, though, so that's what we do.\n        # Append '_d' to the python import library on debug builds.\n        if sys.platform == \"win32\":\n            from distutils._msvccompiler import MSVCCompiler\n\n            if not isinstance(self.compiler, MSVCCompiler):\n                template = \"python%d%d\"\n                if self.debug:\n                    template = template + '_d'\n                pythonlib = template % (\n                    sys.hexversion >> 24,\n                    (sys.hexversion >> 16) & 0xFF,\n                )\n                # don't extend ext.libraries, it may be shared with other\n                # extensions, it is a reference to the original list\n                return ext.libraries + [pythonlib]\n        else:\n            # On Android only the main executable and LD_PRELOADs are considered\n            # to be RTLD_GLOBAL, all the dependencies of the main executable\n            # remain RTLD_LOCAL and so the shared libraries must be linked with\n            # libpython when python is built with a shared python library (issue\n            # bpo-21536).\n            # On Cygwin (and if required, other POSIX-like platforms based on\n            # Windows like MinGW) it is simply necessary that all symbols in\n            # shared libraries are resolved at link time.\n            from distutils.sysconfig import get_config_var\n\n            link_libpython = False\n            if get_config_var('Py_ENABLE_SHARED'):\n                # A native build on an Android device or on Cygwin\n                if hasattr(sys, 'getandroidapilevel'):\n                    link_libpython = True\n                elif sys.platform == 'cygwin':\n                    link_libpython = True\n                elif '_PYTHON_HOST_PLATFORM' in os.environ:\n                    # We are cross-compiling for one of the relevant platforms\n                    if get_config_var('ANDROID_API_LEVEL') != 0:\n                        link_libpython = True\n                    elif get_config_var('MACHDEP') == 'cygwin':\n                        link_libpython = True\n\n            if link_libpython:\n                ldversion = get_config_var('LDVERSION')\n                return ext.libraries + ['python' + ldversion]\n\n        return ext.libraries + py37compat.pythonlib()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/build_py.py",
    "content": "\"\"\"distutils.command.build_py\n\nImplements the Distutils 'build_py' command.\"\"\"\n\nimport os\nimport importlib.util\nimport sys\nimport glob\n\nfrom distutils.core import Command\nfrom distutils.errors import DistutilsOptionError, DistutilsFileError\nfrom distutils.util import convert_path\nfrom distutils import log\n\n\nclass build_py(Command):\n\n    description = \"\\\"build\\\" pure Python modules (copy to build directory)\"\n\n    user_options = [\n        ('build-lib=', 'd', \"directory to \\\"build\\\" (copy) to\"),\n        ('compile', 'c', \"compile .py to .pyc\"),\n        ('no-compile', None, \"don't compile .py files [default]\"),\n        (\n            'optimize=',\n            'O',\n            \"also compile with optimization: -O1 for \\\"python -O\\\", \"\n            \"-O2 for \\\"python -OO\\\", and -O0 to disable [default: -O0]\",\n        ),\n        ('force', 'f', \"forcibly build everything (ignore file timestamps)\"),\n    ]\n\n    boolean_options = ['compile', 'force']\n    negative_opt = {'no-compile': 'compile'}\n\n    def initialize_options(self):\n        self.build_lib = None\n        self.py_modules = None\n        self.package = None\n        self.package_data = None\n        self.package_dir = None\n        self.compile = 0\n        self.optimize = 0\n        self.force = None\n\n    def finalize_options(self):\n        self.set_undefined_options(\n            'build', ('build_lib', 'build_lib'), ('force', 'force')\n        )\n\n        # Get the distribution options that are aliases for build_py\n        # options -- list of packages and list of modules.\n        self.packages = self.distribution.packages\n        self.py_modules = self.distribution.py_modules\n        self.package_data = self.distribution.package_data\n        self.package_dir = {}\n        if self.distribution.package_dir:\n            for name, path in self.distribution.package_dir.items():\n                self.package_dir[name] = convert_path(path)\n        self.data_files = self.get_data_files()\n\n        # Ick, copied straight from install_lib.py (fancy_getopt needs a\n        # type system!  Hell, *everything* needs a type system!!!)\n        if not isinstance(self.optimize, int):\n            try:\n                self.optimize = int(self.optimize)\n                assert 0 <= self.optimize <= 2\n            except (ValueError, AssertionError):\n                raise DistutilsOptionError(\"optimize must be 0, 1, or 2\")\n\n    def run(self):\n        # XXX copy_file by default preserves atime and mtime.  IMHO this is\n        # the right thing to do, but perhaps it should be an option -- in\n        # particular, a site administrator might want installed files to\n        # reflect the time of installation rather than the last\n        # modification time before the installed release.\n\n        # XXX copy_file by default preserves mode, which appears to be the\n        # wrong thing to do: if a file is read-only in the working\n        # directory, we want it to be installed read/write so that the next\n        # installation of the same module distribution can overwrite it\n        # without problems.  (This might be a Unix-specific issue.)  Thus\n        # we turn off 'preserve_mode' when copying to the build directory,\n        # since the build directory is supposed to be exactly what the\n        # installation will look like (ie. we preserve mode when\n        # installing).\n\n        # Two options control which modules will be installed: 'packages'\n        # and 'py_modules'.  The former lets us work with whole packages, not\n        # specifying individual modules at all; the latter is for\n        # specifying modules one-at-a-time.\n\n        if self.py_modules:\n            self.build_modules()\n        if self.packages:\n            self.build_packages()\n            self.build_package_data()\n\n        self.byte_compile(self.get_outputs(include_bytecode=0))\n\n    def get_data_files(self):\n        \"\"\"Generate list of '(package,src_dir,build_dir,filenames)' tuples\"\"\"\n        data = []\n        if not self.packages:\n            return data\n        for package in self.packages:\n            # Locate package source directory\n            src_dir = self.get_package_dir(package)\n\n            # Compute package build directory\n            build_dir = os.path.join(*([self.build_lib] + package.split('.')))\n\n            # Length of path to strip from found files\n            plen = 0\n            if src_dir:\n                plen = len(src_dir) + 1\n\n            # Strip directory from globbed filenames\n            filenames = [file[plen:] for file in self.find_data_files(package, src_dir)]\n            data.append((package, src_dir, build_dir, filenames))\n        return data\n\n    def find_data_files(self, package, src_dir):\n        \"\"\"Return filenames for package's data files in 'src_dir'\"\"\"\n        globs = self.package_data.get('', []) + self.package_data.get(package, [])\n        files = []\n        for pattern in globs:\n            # Each pattern has to be converted to a platform-specific path\n            filelist = glob.glob(\n                os.path.join(glob.escape(src_dir), convert_path(pattern))\n            )\n            # Files that match more than one pattern are only added once\n            files.extend(\n                [fn for fn in filelist if fn not in files and os.path.isfile(fn)]\n            )\n        return files\n\n    def build_package_data(self):\n        \"\"\"Copy data files into build directory\"\"\"\n        for package, src_dir, build_dir, filenames in self.data_files:\n            for filename in filenames:\n                target = os.path.join(build_dir, filename)\n                self.mkpath(os.path.dirname(target))\n                self.copy_file(\n                    os.path.join(src_dir, filename), target, preserve_mode=False\n                )\n\n    def get_package_dir(self, package):\n        \"\"\"Return the directory, relative to the top of the source\n        distribution, where package 'package' should be found\n        (at least according to the 'package_dir' option, if any).\"\"\"\n        path = package.split('.')\n\n        if not self.package_dir:\n            if path:\n                return os.path.join(*path)\n            else:\n                return ''\n        else:\n            tail = []\n            while path:\n                try:\n                    pdir = self.package_dir['.'.join(path)]\n                except KeyError:\n                    tail.insert(0, path[-1])\n                    del path[-1]\n                else:\n                    tail.insert(0, pdir)\n                    return os.path.join(*tail)\n            else:\n                # Oops, got all the way through 'path' without finding a\n                # match in package_dir.  If package_dir defines a directory\n                # for the root (nameless) package, then fallback on it;\n                # otherwise, we might as well have not consulted\n                # package_dir at all, as we just use the directory implied\n                # by 'tail' (which should be the same as the original value\n                # of 'path' at this point).\n                pdir = self.package_dir.get('')\n                if pdir is not None:\n                    tail.insert(0, pdir)\n\n                if tail:\n                    return os.path.join(*tail)\n                else:\n                    return ''\n\n    def check_package(self, package, package_dir):\n        # Empty dir name means current directory, which we can probably\n        # assume exists.  Also, os.path.exists and isdir don't know about\n        # my \"empty string means current dir\" convention, so we have to\n        # circumvent them.\n        if package_dir != \"\":\n            if not os.path.exists(package_dir):\n                raise DistutilsFileError(\n                    \"package directory '%s' does not exist\" % package_dir\n                )\n            if not os.path.isdir(package_dir):\n                raise DistutilsFileError(\n                    \"supposed package directory '%s' exists, \"\n                    \"but is not a directory\" % package_dir\n                )\n\n        # Directories without __init__.py are namespace packages (PEP 420).\n        if package:\n            init_py = os.path.join(package_dir, \"__init__.py\")\n            if os.path.isfile(init_py):\n                return init_py\n\n        # Either not in a package at all (__init__.py not expected), or\n        # __init__.py doesn't exist -- so don't return the filename.\n        return None\n\n    def check_module(self, module, module_file):\n        if not os.path.isfile(module_file):\n            log.warn(\"file %s (for module %s) not found\", module_file, module)\n            return False\n        else:\n            return True\n\n    def find_package_modules(self, package, package_dir):\n        self.check_package(package, package_dir)\n        module_files = glob.glob(os.path.join(glob.escape(package_dir), \"*.py\"))\n        modules = []\n        setup_script = os.path.abspath(self.distribution.script_name)\n\n        for f in module_files:\n            abs_f = os.path.abspath(f)\n            if abs_f != setup_script:\n                module = os.path.splitext(os.path.basename(f))[0]\n                modules.append((package, module, f))\n            else:\n                self.debug_print(\"excluding %s\" % setup_script)\n        return modules\n\n    def find_modules(self):\n        \"\"\"Finds individually-specified Python modules, ie. those listed by\n        module name in 'self.py_modules'.  Returns a list of tuples (package,\n        module_base, filename): 'package' is a tuple of the path through\n        package-space to the module; 'module_base' is the bare (no\n        packages, no dots) module name, and 'filename' is the path to the\n        \".py\" file (relative to the distribution root) that implements the\n        module.\n        \"\"\"\n        # Map package names to tuples of useful info about the package:\n        #    (package_dir, checked)\n        # package_dir - the directory where we'll find source files for\n        #   this package\n        # checked - true if we have checked that the package directory\n        #   is valid (exists, contains __init__.py, ... ?)\n        packages = {}\n\n        # List of (package, module, filename) tuples to return\n        modules = []\n\n        # We treat modules-in-packages almost the same as toplevel modules,\n        # just the \"package\" for a toplevel is empty (either an empty\n        # string or empty list, depending on context).  Differences:\n        #   - don't check for __init__.py in directory for empty package\n        for module in self.py_modules:\n            path = module.split('.')\n            package = '.'.join(path[0:-1])\n            module_base = path[-1]\n\n            try:\n                (package_dir, checked) = packages[package]\n            except KeyError:\n                package_dir = self.get_package_dir(package)\n                checked = 0\n\n            if not checked:\n                init_py = self.check_package(package, package_dir)\n                packages[package] = (package_dir, 1)\n                if init_py:\n                    modules.append((package, \"__init__\", init_py))\n\n            # XXX perhaps we should also check for just .pyc files\n            # (so greedy closed-source bastards can distribute Python\n            # modules too)\n            module_file = os.path.join(package_dir, module_base + \".py\")\n            if not self.check_module(module, module_file):\n                continue\n\n            modules.append((package, module_base, module_file))\n\n        return modules\n\n    def find_all_modules(self):\n        \"\"\"Compute the list of all modules that will be built, whether\n        they are specified one-module-at-a-time ('self.py_modules') or\n        by whole packages ('self.packages').  Return a list of tuples\n        (package, module, module_file), just like 'find_modules()' and\n        'find_package_modules()' do.\"\"\"\n        modules = []\n        if self.py_modules:\n            modules.extend(self.find_modules())\n        if self.packages:\n            for package in self.packages:\n                package_dir = self.get_package_dir(package)\n                m = self.find_package_modules(package, package_dir)\n                modules.extend(m)\n        return modules\n\n    def get_source_files(self):\n        return [module[-1] for module in self.find_all_modules()]\n\n    def get_module_outfile(self, build_dir, package, module):\n        outfile_path = [build_dir] + list(package) + [module + \".py\"]\n        return os.path.join(*outfile_path)\n\n    def get_outputs(self, include_bytecode=1):\n        modules = self.find_all_modules()\n        outputs = []\n        for (package, module, module_file) in modules:\n            package = package.split('.')\n            filename = self.get_module_outfile(self.build_lib, package, module)\n            outputs.append(filename)\n            if include_bytecode:\n                if self.compile:\n                    outputs.append(\n                        importlib.util.cache_from_source(filename, optimization='')\n                    )\n                if self.optimize > 0:\n                    outputs.append(\n                        importlib.util.cache_from_source(\n                            filename, optimization=self.optimize\n                        )\n                    )\n\n        outputs += [\n            os.path.join(build_dir, filename)\n            for package, src_dir, build_dir, filenames in self.data_files\n            for filename in filenames\n        ]\n\n        return outputs\n\n    def build_module(self, module, module_file, package):\n        if isinstance(package, str):\n            package = package.split('.')\n        elif not isinstance(package, (list, tuple)):\n            raise TypeError(\n                \"'package' must be a string (dot-separated), list, or tuple\"\n            )\n\n        # Now put the module source file into the \"build\" area -- this is\n        # easy, we just copy it somewhere under self.build_lib (the build\n        # directory for Python source).\n        outfile = self.get_module_outfile(self.build_lib, package, module)\n        dir = os.path.dirname(outfile)\n        self.mkpath(dir)\n        return self.copy_file(module_file, outfile, preserve_mode=0)\n\n    def build_modules(self):\n        modules = self.find_modules()\n        for (package, module, module_file) in modules:\n            # Now \"build\" the module -- ie. copy the source file to\n            # self.build_lib (the build directory for Python source).\n            # (Actually, it gets copied to the directory for this package\n            # under self.build_lib.)\n            self.build_module(module, module_file, package)\n\n    def build_packages(self):\n        for package in self.packages:\n            # Get list of (package, module, module_file) tuples based on\n            # scanning the package directory.  'package' is only included\n            # in the tuple so that 'find_modules()' and\n            # 'find_package_tuples()' have a consistent interface; it's\n            # ignored here (apart from a sanity check).  Also, 'module' is\n            # the *unqualified* module name (ie. no dots, no package -- we\n            # already know its package!), and 'module_file' is the path to\n            # the .py file, relative to the current directory\n            # (ie. including 'package_dir').\n            package_dir = self.get_package_dir(package)\n            modules = self.find_package_modules(package, package_dir)\n\n            # Now loop over the modules we found, \"building\" each one (just\n            # copy it to self.build_lib).\n            for (package_, module, module_file) in modules:\n                assert package == package_\n                self.build_module(module, module_file, package)\n\n    def byte_compile(self, files):\n        if sys.dont_write_bytecode:\n            self.warn('byte-compiling is disabled, skipping.')\n            return\n\n        from distutils.util import byte_compile\n\n        prefix = self.build_lib\n        if prefix[-1] != os.sep:\n            prefix = prefix + os.sep\n\n        # XXX this code is essentially the same as the 'byte_compile()\n        # method of the \"install_lib\" command, except for the determination\n        # of the 'prefix' string.  Hmmm.\n        if self.compile:\n            byte_compile(\n                files, optimize=0, force=self.force, prefix=prefix, dry_run=self.dry_run\n            )\n        if self.optimize > 0:\n            byte_compile(\n                files,\n                optimize=self.optimize,\n                force=self.force,\n                prefix=prefix,\n                dry_run=self.dry_run,\n            )\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/build_scripts.py",
    "content": "\"\"\"distutils.command.build_scripts\n\nImplements the Distutils 'build_scripts' command.\"\"\"\n\nimport os\nimport re\nfrom stat import ST_MODE\nfrom distutils import sysconfig\nfrom distutils.core import Command\nfrom distutils.dep_util import newer\nfrom distutils.util import convert_path\nfrom distutils import log\nimport tokenize\n\nshebang_pattern = re.compile('^#!.*python[0-9.]*([ \\t].*)?$')\n\"\"\"\nPattern matching a Python interpreter indicated in first line of a script.\n\"\"\"\n\n# for Setuptools compatibility\nfirst_line_re = shebang_pattern\n\n\nclass build_scripts(Command):\n\n    description = \"\\\"build\\\" scripts (copy and fixup #! line)\"\n\n    user_options = [\n        ('build-dir=', 'd', \"directory to \\\"build\\\" (copy) to\"),\n        ('force', 'f', \"forcibly build everything (ignore file timestamps\"),\n        ('executable=', 'e', \"specify final destination interpreter path\"),\n    ]\n\n    boolean_options = ['force']\n\n    def initialize_options(self):\n        self.build_dir = None\n        self.scripts = None\n        self.force = None\n        self.executable = None\n\n    def finalize_options(self):\n        self.set_undefined_options(\n            'build',\n            ('build_scripts', 'build_dir'),\n            ('force', 'force'),\n            ('executable', 'executable'),\n        )\n        self.scripts = self.distribution.scripts\n\n    def get_source_files(self):\n        return self.scripts\n\n    def run(self):\n        if not self.scripts:\n            return\n        self.copy_scripts()\n\n    def copy_scripts(self):\n        \"\"\"\n        Copy each script listed in ``self.scripts``.\n\n        If a script is marked as a Python script (first line matches\n        'shebang_pattern', i.e. starts with ``#!`` and contains\n        \"python\"), then adjust in the copy the first line to refer to\n        the current Python interpreter.\n        \"\"\"\n        self.mkpath(self.build_dir)\n        outfiles = []\n        updated_files = []\n        for script in self.scripts:\n            self._copy_script(script, outfiles, updated_files)\n\n        self._change_modes(outfiles)\n\n        return outfiles, updated_files\n\n    def _copy_script(self, script, outfiles, updated_files):  # noqa: C901\n        shebang_match = None\n        script = convert_path(script)\n        outfile = os.path.join(self.build_dir, os.path.basename(script))\n        outfiles.append(outfile)\n\n        if not self.force and not newer(script, outfile):\n            log.debug(\"not copying %s (up-to-date)\", script)\n            return\n\n        # Always open the file, but ignore failures in dry-run mode\n        # in order to attempt to copy directly.\n        try:\n            f = tokenize.open(script)\n        except OSError:\n            if not self.dry_run:\n                raise\n            f = None\n        else:\n            first_line = f.readline()\n            if not first_line:\n                self.warn(\"%s is an empty file (skipping)\" % script)\n                return\n\n            shebang_match = shebang_pattern.match(first_line)\n\n        updated_files.append(outfile)\n        if shebang_match:\n            log.info(\"copying and adjusting %s -> %s\", script, self.build_dir)\n            if not self.dry_run:\n                if not sysconfig.python_build:\n                    executable = self.executable\n                else:\n                    executable = os.path.join(\n                        sysconfig.get_config_var(\"BINDIR\"),\n                        \"python%s%s\"\n                        % (\n                            sysconfig.get_config_var(\"VERSION\"),\n                            sysconfig.get_config_var(\"EXE\"),\n                        ),\n                    )\n                post_interp = shebang_match.group(1) or ''\n                shebang = \"#!\" + executable + post_interp + \"\\n\"\n                self._validate_shebang(shebang, f.encoding)\n                with open(outfile, \"w\", encoding=f.encoding) as outf:\n                    outf.write(shebang)\n                    outf.writelines(f.readlines())\n            if f:\n                f.close()\n        else:\n            if f:\n                f.close()\n            self.copy_file(script, outfile)\n\n    def _change_modes(self, outfiles):\n        if os.name != 'posix':\n            return\n\n        for file in outfiles:\n            self._change_mode(file)\n\n    def _change_mode(self, file):\n        if self.dry_run:\n            log.info(\"changing mode of %s\", file)\n            return\n\n        oldmode = os.stat(file)[ST_MODE] & 0o7777\n        newmode = (oldmode | 0o555) & 0o7777\n        if newmode != oldmode:\n            log.info(\"changing mode of %s from %o to %o\", file, oldmode, newmode)\n            os.chmod(file, newmode)\n\n    @staticmethod\n    def _validate_shebang(shebang, encoding):\n        # Python parser starts to read a script using UTF-8 until\n        # it gets a #coding:xxx cookie. The shebang has to be the\n        # first line of a file, the #coding:xxx cookie cannot be\n        # written before. So the shebang has to be encodable to\n        # UTF-8.\n        try:\n            shebang.encode('utf-8')\n        except UnicodeEncodeError:\n            raise ValueError(\n                \"The shebang ({!r}) is not encodable \" \"to utf-8\".format(shebang)\n            )\n\n        # If the script is encoded to a custom encoding (use a\n        # #coding:xxx cookie), the shebang has to be encodable to\n        # the script encoding too.\n        try:\n            shebang.encode(encoding)\n        except UnicodeEncodeError:\n            raise ValueError(\n                \"The shebang ({!r}) is not encodable \"\n                \"to the script encoding ({})\".format(shebang, encoding)\n            )\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/check.py",
    "content": "\"\"\"distutils.command.check\n\nImplements the Distutils 'check' command.\n\"\"\"\nimport contextlib\n\nfrom distutils.core import Command\nfrom distutils.errors import DistutilsSetupError\n\nwith contextlib.suppress(ImportError):\n    import docutils.utils\n    import docutils.parsers.rst\n    import docutils.frontend\n    import docutils.nodes\n\n    class SilentReporter(docutils.utils.Reporter):\n        def __init__(\n            self,\n            source,\n            report_level,\n            halt_level,\n            stream=None,\n            debug=0,\n            encoding='ascii',\n            error_handler='replace',\n        ):\n            self.messages = []\n            super().__init__(\n                source, report_level, halt_level, stream, debug, encoding, error_handler\n            )\n\n        def system_message(self, level, message, *children, **kwargs):\n            self.messages.append((level, message, children, kwargs))\n            return docutils.nodes.system_message(\n                message, level=level, type=self.levels[level], *children, **kwargs\n            )\n\n\nclass check(Command):\n    \"\"\"This command checks the meta-data of the package.\"\"\"\n\n    description = \"perform some checks on the package\"\n    user_options = [\n        ('metadata', 'm', 'Verify meta-data'),\n        (\n            'restructuredtext',\n            'r',\n            (\n                'Checks if long string meta-data syntax '\n                'are reStructuredText-compliant'\n            ),\n        ),\n        ('strict', 's', 'Will exit with an error if a check fails'),\n    ]\n\n    boolean_options = ['metadata', 'restructuredtext', 'strict']\n\n    def initialize_options(self):\n        \"\"\"Sets default values for options.\"\"\"\n        self.restructuredtext = 0\n        self.metadata = 1\n        self.strict = 0\n        self._warnings = 0\n\n    def finalize_options(self):\n        pass\n\n    def warn(self, msg):\n        \"\"\"Counts the number of warnings that occurs.\"\"\"\n        self._warnings += 1\n        return Command.warn(self, msg)\n\n    def run(self):\n        \"\"\"Runs the command.\"\"\"\n        # perform the various tests\n        if self.metadata:\n            self.check_metadata()\n        if self.restructuredtext:\n            if 'docutils' in globals():\n                try:\n                    self.check_restructuredtext()\n                except TypeError as exc:\n                    raise DistutilsSetupError(str(exc))\n            elif self.strict:\n                raise DistutilsSetupError('The docutils package is needed.')\n\n        # let's raise an error in strict mode, if we have at least\n        # one warning\n        if self.strict and self._warnings > 0:\n            raise DistutilsSetupError('Please correct your package.')\n\n    def check_metadata(self):\n        \"\"\"Ensures that all required elements of meta-data are supplied.\n\n        Required fields:\n            name, version\n\n        Warns if any are missing.\n        \"\"\"\n        metadata = self.distribution.metadata\n\n        missing = []\n        for attr in 'name', 'version':\n            if not getattr(metadata, attr, None):\n                missing.append(attr)\n\n        if missing:\n            self.warn(\"missing required meta-data: %s\" % ', '.join(missing))\n\n    def check_restructuredtext(self):\n        \"\"\"Checks if the long string fields are reST-compliant.\"\"\"\n        data = self.distribution.get_long_description()\n        for warning in self._check_rst_data(data):\n            line = warning[-1].get('line')\n            if line is None:\n                warning = warning[1]\n            else:\n                warning = '{} (line {})'.format(warning[1], line)\n            self.warn(warning)\n\n    def _check_rst_data(self, data):\n        \"\"\"Returns warnings when the provided data doesn't compile.\"\"\"\n        # the include and csv_table directives need this to be a path\n        source_path = self.distribution.script_name or 'setup.py'\n        parser = docutils.parsers.rst.Parser()\n        settings = docutils.frontend.OptionParser(\n            components=(docutils.parsers.rst.Parser,)\n        ).get_default_values()\n        settings.tab_width = 4\n        settings.pep_references = None\n        settings.rfc_references = None\n        reporter = SilentReporter(\n            source_path,\n            settings.report_level,\n            settings.halt_level,\n            stream=settings.warning_stream,\n            debug=settings.debug,\n            encoding=settings.error_encoding,\n            error_handler=settings.error_encoding_error_handler,\n        )\n\n        document = docutils.nodes.document(settings, reporter, source=source_path)\n        document.note_source(source_path, -1)\n        try:\n            parser.parse(data, document)\n        except AttributeError as e:\n            reporter.messages.append(\n                (-1, 'Could not finish the parsing: %s.' % e, '', {})\n            )\n\n        return reporter.messages\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/clean.py",
    "content": "\"\"\"distutils.command.clean\n\nImplements the Distutils 'clean' command.\"\"\"\n\n# contributed by Bastian Kleineidam <calvin@cs.uni-sb.de>, added 2000-03-18\n\nimport os\nfrom distutils.core import Command\nfrom distutils.dir_util import remove_tree\nfrom distutils import log\n\n\nclass clean(Command):\n\n    description = \"clean up temporary files from 'build' command\"\n    user_options = [\n        ('build-base=', 'b', \"base build directory (default: 'build.build-base')\"),\n        (\n            'build-lib=',\n            None,\n            \"build directory for all modules (default: 'build.build-lib')\",\n        ),\n        ('build-temp=', 't', \"temporary build directory (default: 'build.build-temp')\"),\n        (\n            'build-scripts=',\n            None,\n            \"build directory for scripts (default: 'build.build-scripts')\",\n        ),\n        ('bdist-base=', None, \"temporary directory for built distributions\"),\n        ('all', 'a', \"remove all build output, not just temporary by-products\"),\n    ]\n\n    boolean_options = ['all']\n\n    def initialize_options(self):\n        self.build_base = None\n        self.build_lib = None\n        self.build_temp = None\n        self.build_scripts = None\n        self.bdist_base = None\n        self.all = None\n\n    def finalize_options(self):\n        self.set_undefined_options(\n            'build',\n            ('build_base', 'build_base'),\n            ('build_lib', 'build_lib'),\n            ('build_scripts', 'build_scripts'),\n            ('build_temp', 'build_temp'),\n        )\n        self.set_undefined_options('bdist', ('bdist_base', 'bdist_base'))\n\n    def run(self):\n        # remove the build/temp.<plat> directory (unless it's already\n        # gone)\n        if os.path.exists(self.build_temp):\n            remove_tree(self.build_temp, dry_run=self.dry_run)\n        else:\n            log.debug(\"'%s' does not exist -- can't clean it\", self.build_temp)\n\n        if self.all:\n            # remove build directories\n            for directory in (self.build_lib, self.bdist_base, self.build_scripts):\n                if os.path.exists(directory):\n                    remove_tree(directory, dry_run=self.dry_run)\n                else:\n                    log.warn(\"'%s' does not exist -- can't clean it\", directory)\n\n        # just for the heck of it, try to remove the base build directory:\n        # we might have emptied it right now, but if not we don't care\n        if not self.dry_run:\n            try:\n                os.rmdir(self.build_base)\n                log.info(\"removing '%s'\", self.build_base)\n            except OSError:\n                pass\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/config.py",
    "content": "\"\"\"distutils.command.config\n\nImplements the Distutils 'config' command, a (mostly) empty command class\nthat exists mainly to be sub-classed by specific module distributions and\napplications.  The idea is that while every \"config\" command is different,\nat least they're all named the same, and users always see \"config\" in the\nlist of standard commands.  Also, this is a good place to put common\nconfigure-like tasks: \"try to compile this C code\", or \"figure out where\nthis header file lives\".\n\"\"\"\n\nimport os\nimport re\n\nfrom distutils.core import Command\nfrom distutils.errors import DistutilsExecError\nfrom distutils.sysconfig import customize_compiler\nfrom distutils import log\n\nLANG_EXT = {\"c\": \".c\", \"c++\": \".cxx\"}\n\n\nclass config(Command):\n\n    description = \"prepare to build\"\n\n    user_options = [\n        ('compiler=', None, \"specify the compiler type\"),\n        ('cc=', None, \"specify the compiler executable\"),\n        ('include-dirs=', 'I', \"list of directories to search for header files\"),\n        ('define=', 'D', \"C preprocessor macros to define\"),\n        ('undef=', 'U', \"C preprocessor macros to undefine\"),\n        ('libraries=', 'l', \"external C libraries to link with\"),\n        ('library-dirs=', 'L', \"directories to search for external C libraries\"),\n        ('noisy', None, \"show every action (compile, link, run, ...) taken\"),\n        (\n            'dump-source',\n            None,\n            \"dump generated source files before attempting to compile them\",\n        ),\n    ]\n\n    # The three standard command methods: since the \"config\" command\n    # does nothing by default, these are empty.\n\n    def initialize_options(self):\n        self.compiler = None\n        self.cc = None\n        self.include_dirs = None\n        self.libraries = None\n        self.library_dirs = None\n\n        # maximal output for now\n        self.noisy = 1\n        self.dump_source = 1\n\n        # list of temporary files generated along-the-way that we have\n        # to clean at some point\n        self.temp_files = []\n\n    def finalize_options(self):\n        if self.include_dirs is None:\n            self.include_dirs = self.distribution.include_dirs or []\n        elif isinstance(self.include_dirs, str):\n            self.include_dirs = self.include_dirs.split(os.pathsep)\n\n        if self.libraries is None:\n            self.libraries = []\n        elif isinstance(self.libraries, str):\n            self.libraries = [self.libraries]\n\n        if self.library_dirs is None:\n            self.library_dirs = []\n        elif isinstance(self.library_dirs, str):\n            self.library_dirs = self.library_dirs.split(os.pathsep)\n\n    def run(self):\n        pass\n\n    # Utility methods for actual \"config\" commands.  The interfaces are\n    # loosely based on Autoconf macros of similar names.  Sub-classes\n    # may use these freely.\n\n    def _check_compiler(self):\n        \"\"\"Check that 'self.compiler' really is a CCompiler object;\n        if not, make it one.\n        \"\"\"\n        # We do this late, and only on-demand, because this is an expensive\n        # import.\n        from distutils.ccompiler import CCompiler, new_compiler\n\n        if not isinstance(self.compiler, CCompiler):\n            self.compiler = new_compiler(\n                compiler=self.compiler, dry_run=self.dry_run, force=1\n            )\n            customize_compiler(self.compiler)\n            if self.include_dirs:\n                self.compiler.set_include_dirs(self.include_dirs)\n            if self.libraries:\n                self.compiler.set_libraries(self.libraries)\n            if self.library_dirs:\n                self.compiler.set_library_dirs(self.library_dirs)\n\n    def _gen_temp_sourcefile(self, body, headers, lang):\n        filename = \"_configtest\" + LANG_EXT[lang]\n        with open(filename, \"w\") as file:\n            if headers:\n                for header in headers:\n                    file.write(\"#include <%s>\\n\" % header)\n                file.write(\"\\n\")\n            file.write(body)\n            if body[-1] != \"\\n\":\n                file.write(\"\\n\")\n        return filename\n\n    def _preprocess(self, body, headers, include_dirs, lang):\n        src = self._gen_temp_sourcefile(body, headers, lang)\n        out = \"_configtest.i\"\n        self.temp_files.extend([src, out])\n        self.compiler.preprocess(src, out, include_dirs=include_dirs)\n        return (src, out)\n\n    def _compile(self, body, headers, include_dirs, lang):\n        src = self._gen_temp_sourcefile(body, headers, lang)\n        if self.dump_source:\n            dump_file(src, \"compiling '%s':\" % src)\n        (obj,) = self.compiler.object_filenames([src])\n        self.temp_files.extend([src, obj])\n        self.compiler.compile([src], include_dirs=include_dirs)\n        return (src, obj)\n\n    def _link(self, body, headers, include_dirs, libraries, library_dirs, lang):\n        (src, obj) = self._compile(body, headers, include_dirs, lang)\n        prog = os.path.splitext(os.path.basename(src))[0]\n        self.compiler.link_executable(\n            [obj],\n            prog,\n            libraries=libraries,\n            library_dirs=library_dirs,\n            target_lang=lang,\n        )\n\n        if self.compiler.exe_extension is not None:\n            prog = prog + self.compiler.exe_extension\n        self.temp_files.append(prog)\n\n        return (src, obj, prog)\n\n    def _clean(self, *filenames):\n        if not filenames:\n            filenames = self.temp_files\n            self.temp_files = []\n        log.info(\"removing: %s\", ' '.join(filenames))\n        for filename in filenames:\n            try:\n                os.remove(filename)\n            except OSError:\n                pass\n\n    # XXX these ignore the dry-run flag: what to do, what to do? even if\n    # you want a dry-run build, you still need some sort of configuration\n    # info.  My inclination is to make it up to the real config command to\n    # consult 'dry_run', and assume a default (minimal) configuration if\n    # true.  The problem with trying to do it here is that you'd have to\n    # return either true or false from all the 'try' methods, neither of\n    # which is correct.\n\n    # XXX need access to the header search path and maybe default macros.\n\n    def try_cpp(self, body=None, headers=None, include_dirs=None, lang=\"c\"):\n        \"\"\"Construct a source file from 'body' (a string containing lines\n        of C/C++ code) and 'headers' (a list of header files to include)\n        and run it through the preprocessor.  Return true if the\n        preprocessor succeeded, false if there were any errors.\n        ('body' probably isn't of much use, but what the heck.)\n        \"\"\"\n        from distutils.ccompiler import CompileError\n\n        self._check_compiler()\n        ok = True\n        try:\n            self._preprocess(body, headers, include_dirs, lang)\n        except CompileError:\n            ok = False\n\n        self._clean()\n        return ok\n\n    def search_cpp(self, pattern, body=None, headers=None, include_dirs=None, lang=\"c\"):\n        \"\"\"Construct a source file (just like 'try_cpp()'), run it through\n        the preprocessor, and return true if any line of the output matches\n        'pattern'.  'pattern' should either be a compiled regex object or a\n        string containing a regex.  If both 'body' and 'headers' are None,\n        preprocesses an empty file -- which can be useful to determine the\n        symbols the preprocessor and compiler set by default.\n        \"\"\"\n        self._check_compiler()\n        src, out = self._preprocess(body, headers, include_dirs, lang)\n\n        if isinstance(pattern, str):\n            pattern = re.compile(pattern)\n\n        with open(out) as file:\n            match = False\n            while True:\n                line = file.readline()\n                if line == '':\n                    break\n                if pattern.search(line):\n                    match = True\n                    break\n\n        self._clean()\n        return match\n\n    def try_compile(self, body, headers=None, include_dirs=None, lang=\"c\"):\n        \"\"\"Try to compile a source file built from 'body' and 'headers'.\n        Return true on success, false otherwise.\n        \"\"\"\n        from distutils.ccompiler import CompileError\n\n        self._check_compiler()\n        try:\n            self._compile(body, headers, include_dirs, lang)\n            ok = True\n        except CompileError:\n            ok = False\n\n        log.info(ok and \"success!\" or \"failure.\")\n        self._clean()\n        return ok\n\n    def try_link(\n        self,\n        body,\n        headers=None,\n        include_dirs=None,\n        libraries=None,\n        library_dirs=None,\n        lang=\"c\",\n    ):\n        \"\"\"Try to compile and link a source file, built from 'body' and\n        'headers', to executable form.  Return true on success, false\n        otherwise.\n        \"\"\"\n        from distutils.ccompiler import CompileError, LinkError\n\n        self._check_compiler()\n        try:\n            self._link(body, headers, include_dirs, libraries, library_dirs, lang)\n            ok = True\n        except (CompileError, LinkError):\n            ok = False\n\n        log.info(ok and \"success!\" or \"failure.\")\n        self._clean()\n        return ok\n\n    def try_run(\n        self,\n        body,\n        headers=None,\n        include_dirs=None,\n        libraries=None,\n        library_dirs=None,\n        lang=\"c\",\n    ):\n        \"\"\"Try to compile, link to an executable, and run a program\n        built from 'body' and 'headers'.  Return true on success, false\n        otherwise.\n        \"\"\"\n        from distutils.ccompiler import CompileError, LinkError\n\n        self._check_compiler()\n        try:\n            src, obj, exe = self._link(\n                body, headers, include_dirs, libraries, library_dirs, lang\n            )\n            self.spawn([exe])\n            ok = True\n        except (CompileError, LinkError, DistutilsExecError):\n            ok = False\n\n        log.info(ok and \"success!\" or \"failure.\")\n        self._clean()\n        return ok\n\n    # -- High-level methods --------------------------------------------\n    # (these are the ones that are actually likely to be useful\n    # when implementing a real-world config command!)\n\n    def check_func(\n        self,\n        func,\n        headers=None,\n        include_dirs=None,\n        libraries=None,\n        library_dirs=None,\n        decl=0,\n        call=0,\n    ):\n        \"\"\"Determine if function 'func' is available by constructing a\n        source file that refers to 'func', and compiles and links it.\n        If everything succeeds, returns true; otherwise returns false.\n\n        The constructed source file starts out by including the header\n        files listed in 'headers'.  If 'decl' is true, it then declares\n        'func' (as \"int func()\"); you probably shouldn't supply 'headers'\n        and set 'decl' true in the same call, or you might get errors about\n        a conflicting declarations for 'func'.  Finally, the constructed\n        'main()' function either references 'func' or (if 'call' is true)\n        calls it.  'libraries' and 'library_dirs' are used when\n        linking.\n        \"\"\"\n        self._check_compiler()\n        body = []\n        if decl:\n            body.append(\"int %s ();\" % func)\n        body.append(\"int main () {\")\n        if call:\n            body.append(\"  %s();\" % func)\n        else:\n            body.append(\"  %s;\" % func)\n        body.append(\"}\")\n        body = \"\\n\".join(body) + \"\\n\"\n\n        return self.try_link(body, headers, include_dirs, libraries, library_dirs)\n\n    def check_lib(\n        self,\n        library,\n        library_dirs=None,\n        headers=None,\n        include_dirs=None,\n        other_libraries=[],\n    ):\n        \"\"\"Determine if 'library' is available to be linked against,\n        without actually checking that any particular symbols are provided\n        by it.  'headers' will be used in constructing the source file to\n        be compiled, but the only effect of this is to check if all the\n        header files listed are available.  Any libraries listed in\n        'other_libraries' will be included in the link, in case 'library'\n        has symbols that depend on other libraries.\n        \"\"\"\n        self._check_compiler()\n        return self.try_link(\n            \"int main (void) { }\",\n            headers,\n            include_dirs,\n            [library] + other_libraries,\n            library_dirs,\n        )\n\n    def check_header(self, header, include_dirs=None, library_dirs=None, lang=\"c\"):\n        \"\"\"Determine if the system header file named by 'header_file'\n        exists and can be found by the preprocessor; return true if so,\n        false otherwise.\n        \"\"\"\n        return self.try_cpp(\n            body=\"/* No body */\", headers=[header], include_dirs=include_dirs\n        )\n\n\ndef dump_file(filename, head=None):\n    \"\"\"Dumps a file content into log.info.\n\n    If head is not None, will be dumped before the file content.\n    \"\"\"\n    if head is None:\n        log.info('%s', filename)\n    else:\n        log.info(head)\n    file = open(filename)\n    try:\n        log.info(file.read())\n    finally:\n        file.close()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/install.py",
    "content": "\"\"\"distutils.command.install\n\nImplements the Distutils 'install' command.\"\"\"\n\nimport sys\nimport os\nimport contextlib\nimport sysconfig\nimport itertools\n\nfrom distutils import log\nfrom distutils.core import Command\nfrom distutils.debug import DEBUG\nfrom distutils.sysconfig import get_config_vars\nfrom distutils.file_util import write_file\nfrom distutils.util import convert_path, subst_vars, change_root\nfrom distutils.util import get_platform\nfrom distutils.errors import DistutilsOptionError, DistutilsPlatformError\nfrom . import _framework_compat as fw\nfrom .. import _collections\n\nfrom site import USER_BASE\nfrom site import USER_SITE\n\nHAS_USER_SITE = True\n\nWINDOWS_SCHEME = {\n    'purelib': '{base}/Lib/site-packages',\n    'platlib': '{base}/Lib/site-packages',\n    'headers': '{base}/Include/{dist_name}',\n    'scripts': '{base}/Scripts',\n    'data': '{base}',\n}\n\nINSTALL_SCHEMES = {\n    'posix_prefix': {\n        'purelib': '{base}/lib/{implementation_lower}{py_version_short}/site-packages',\n        'platlib': '{platbase}/{platlibdir}/{implementation_lower}'\n        '{py_version_short}/site-packages',\n        'headers': '{base}/include/{implementation_lower}'\n        '{py_version_short}{abiflags}/{dist_name}',\n        'scripts': '{base}/bin',\n        'data': '{base}',\n    },\n    'posix_home': {\n        'purelib': '{base}/lib/{implementation_lower}',\n        'platlib': '{base}/{platlibdir}/{implementation_lower}',\n        'headers': '{base}/include/{implementation_lower}/{dist_name}',\n        'scripts': '{base}/bin',\n        'data': '{base}',\n    },\n    'nt': WINDOWS_SCHEME,\n    'pypy': {\n        'purelib': '{base}/site-packages',\n        'platlib': '{base}/site-packages',\n        'headers': '{base}/include/{dist_name}',\n        'scripts': '{base}/bin',\n        'data': '{base}',\n    },\n    'pypy_nt': {\n        'purelib': '{base}/site-packages',\n        'platlib': '{base}/site-packages',\n        'headers': '{base}/include/{dist_name}',\n        'scripts': '{base}/Scripts',\n        'data': '{base}',\n    },\n}\n\n# user site schemes\nif HAS_USER_SITE:\n    INSTALL_SCHEMES['nt_user'] = {\n        'purelib': '{usersite}',\n        'platlib': '{usersite}',\n        'headers': '{userbase}/{implementation}{py_version_nodot_plat}'\n        '/Include/{dist_name}',\n        'scripts': '{userbase}/{implementation}{py_version_nodot_plat}/Scripts',\n        'data': '{userbase}',\n    }\n\n    INSTALL_SCHEMES['posix_user'] = {\n        'purelib': '{usersite}',\n        'platlib': '{usersite}',\n        'headers': '{userbase}/include/{implementation_lower}'\n        '{py_version_short}{abiflags}/{dist_name}',\n        'scripts': '{userbase}/bin',\n        'data': '{userbase}',\n    }\n\n\nINSTALL_SCHEMES.update(fw.schemes)\n\n\n# The keys to an installation scheme; if any new types of files are to be\n# installed, be sure to add an entry to every installation scheme above,\n# and to SCHEME_KEYS here.\nSCHEME_KEYS = ('purelib', 'platlib', 'headers', 'scripts', 'data')\n\n\ndef _load_sysconfig_schemes():\n    with contextlib.suppress(AttributeError):\n        return {\n            scheme: sysconfig.get_paths(scheme, expand=False)\n            for scheme in sysconfig.get_scheme_names()\n        }\n\n\ndef _load_schemes():\n    \"\"\"\n    Extend default schemes with schemes from sysconfig.\n    \"\"\"\n\n    sysconfig_schemes = _load_sysconfig_schemes() or {}\n\n    return {\n        scheme: {\n            **INSTALL_SCHEMES.get(scheme, {}),\n            **sysconfig_schemes.get(scheme, {}),\n        }\n        for scheme in set(itertools.chain(INSTALL_SCHEMES, sysconfig_schemes))\n    }\n\n\ndef _get_implementation():\n    if hasattr(sys, 'pypy_version_info'):\n        return 'PyPy'\n    else:\n        return 'Python'\n\n\ndef _select_scheme(ob, name):\n    scheme = _inject_headers(name, _load_scheme(_resolve_scheme(name)))\n    vars(ob).update(_remove_set(ob, _scheme_attrs(scheme)))\n\n\ndef _remove_set(ob, attrs):\n    \"\"\"\n    Include only attrs that are None in ob.\n    \"\"\"\n    return {key: value for key, value in attrs.items() if getattr(ob, key) is None}\n\n\ndef _resolve_scheme(name):\n    os_name, sep, key = name.partition('_')\n    try:\n        resolved = sysconfig.get_preferred_scheme(key)\n    except Exception:\n        resolved = fw.scheme(_pypy_hack(name))\n    return resolved\n\n\ndef _load_scheme(name):\n    return _load_schemes()[name]\n\n\ndef _inject_headers(name, scheme):\n    \"\"\"\n    Given a scheme name and the resolved scheme,\n    if the scheme does not include headers, resolve\n    the fallback scheme for the name and use headers\n    from it. pypa/distutils#88\n    \"\"\"\n    # Bypass the preferred scheme, which may not\n    # have defined headers.\n    fallback = _load_scheme(_pypy_hack(name))\n    scheme.setdefault('headers', fallback['headers'])\n    return scheme\n\n\ndef _scheme_attrs(scheme):\n    \"\"\"Resolve install directories by applying the install schemes.\"\"\"\n    return {f'install_{key}': scheme[key] for key in SCHEME_KEYS}\n\n\ndef _pypy_hack(name):\n    PY37 = sys.version_info < (3, 8)\n    old_pypy = hasattr(sys, 'pypy_version_info') and PY37\n    prefix = not name.endswith(('_user', '_home'))\n    pypy_name = 'pypy' + '_nt' * (os.name == 'nt')\n    return pypy_name if old_pypy and prefix else name\n\n\nclass install(Command):\n\n    description = \"install everything from build directory\"\n\n    user_options = [\n        # Select installation scheme and set base director(y|ies)\n        ('prefix=', None, \"installation prefix\"),\n        ('exec-prefix=', None, \"(Unix only) prefix for platform-specific files\"),\n        ('home=', None, \"(Unix only) home directory to install under\"),\n        # Or, just set the base director(y|ies)\n        (\n            'install-base=',\n            None,\n            \"base installation directory (instead of --prefix or --home)\",\n        ),\n        (\n            'install-platbase=',\n            None,\n            \"base installation directory for platform-specific files \"\n            + \"(instead of --exec-prefix or --home)\",\n        ),\n        ('root=', None, \"install everything relative to this alternate root directory\"),\n        # Or, explicitly set the installation scheme\n        (\n            'install-purelib=',\n            None,\n            \"installation directory for pure Python module distributions\",\n        ),\n        (\n            'install-platlib=',\n            None,\n            \"installation directory for non-pure module distributions\",\n        ),\n        (\n            'install-lib=',\n            None,\n            \"installation directory for all module distributions \"\n            + \"(overrides --install-purelib and --install-platlib)\",\n        ),\n        ('install-headers=', None, \"installation directory for C/C++ headers\"),\n        ('install-scripts=', None, \"installation directory for Python scripts\"),\n        ('install-data=', None, \"installation directory for data files\"),\n        # Byte-compilation options -- see install_lib.py for details, as\n        # these are duplicated from there (but only install_lib does\n        # anything with them).\n        ('compile', 'c', \"compile .py to .pyc [default]\"),\n        ('no-compile', None, \"don't compile .py files\"),\n        (\n            'optimize=',\n            'O',\n            \"also compile with optimization: -O1 for \\\"python -O\\\", \"\n            \"-O2 for \\\"python -OO\\\", and -O0 to disable [default: -O0]\",\n        ),\n        # Miscellaneous control options\n        ('force', 'f', \"force installation (overwrite any existing files)\"),\n        ('skip-build', None, \"skip rebuilding everything (for testing/debugging)\"),\n        # Where to install documentation (eventually!)\n        # ('doc-format=', None, \"format of documentation to generate\"),\n        # ('install-man=', None, \"directory for Unix man pages\"),\n        # ('install-html=', None, \"directory for HTML documentation\"),\n        # ('install-info=', None, \"directory for GNU info files\"),\n        ('record=', None, \"filename in which to record list of installed files\"),\n    ]\n\n    boolean_options = ['compile', 'force', 'skip-build']\n\n    if HAS_USER_SITE:\n        user_options.append(\n            ('user', None, \"install in user site-package '%s'\" % USER_SITE)\n        )\n        boolean_options.append('user')\n\n    negative_opt = {'no-compile': 'compile'}\n\n    def initialize_options(self):\n        \"\"\"Initializes options.\"\"\"\n        # High-level options: these select both an installation base\n        # and scheme.\n        self.prefix = None\n        self.exec_prefix = None\n        self.home = None\n        self.user = 0\n\n        # These select only the installation base; it's up to the user to\n        # specify the installation scheme (currently, that means supplying\n        # the --install-{platlib,purelib,scripts,data} options).\n        self.install_base = None\n        self.install_platbase = None\n        self.root = None\n\n        # These options are the actual installation directories; if not\n        # supplied by the user, they are filled in using the installation\n        # scheme implied by prefix/exec-prefix/home and the contents of\n        # that installation scheme.\n        self.install_purelib = None  # for pure module distributions\n        self.install_platlib = None  # non-pure (dists w/ extensions)\n        self.install_headers = None  # for C/C++ headers\n        self.install_lib = None  # set to either purelib or platlib\n        self.install_scripts = None\n        self.install_data = None\n        self.install_userbase = USER_BASE\n        self.install_usersite = USER_SITE\n\n        self.compile = None\n        self.optimize = None\n\n        # Deprecated\n        # These two are for putting non-packagized distributions into their\n        # own directory and creating a .pth file if it makes sense.\n        # 'extra_path' comes from the setup file; 'install_path_file' can\n        # be turned off if it makes no sense to install a .pth file.  (But\n        # better to install it uselessly than to guess wrong and not\n        # install it when it's necessary and would be used!)  Currently,\n        # 'install_path_file' is always true unless some outsider meddles\n        # with it.\n        self.extra_path = None\n        self.install_path_file = 1\n\n        # 'force' forces installation, even if target files are not\n        # out-of-date.  'skip_build' skips running the \"build\" command,\n        # handy if you know it's not necessary.  'warn_dir' (which is *not*\n        # a user option, it's just there so the bdist_* commands can turn\n        # it off) determines whether we warn about installing to a\n        # directory not in sys.path.\n        self.force = 0\n        self.skip_build = 0\n        self.warn_dir = 1\n\n        # These are only here as a conduit from the 'build' command to the\n        # 'install_*' commands that do the real work.  ('build_base' isn't\n        # actually used anywhere, but it might be useful in future.)  They\n        # are not user options, because if the user told the install\n        # command where the build directory is, that wouldn't affect the\n        # build command.\n        self.build_base = None\n        self.build_lib = None\n\n        # Not defined yet because we don't know anything about\n        # documentation yet.\n        # self.install_man = None\n        # self.install_html = None\n        # self.install_info = None\n\n        self.record = None\n\n    # -- Option finalizing methods -------------------------------------\n    # (This is rather more involved than for most commands,\n    # because this is where the policy for installing third-\n    # party Python modules on various platforms given a wide\n    # array of user input is decided.  Yes, it's quite complex!)\n\n    def finalize_options(self):  # noqa: C901\n        \"\"\"Finalizes options.\"\"\"\n        # This method (and its helpers, like 'finalize_unix()',\n        # 'finalize_other()', and 'select_scheme()') is where the default\n        # installation directories for modules, extension modules, and\n        # anything else we care to install from a Python module\n        # distribution.  Thus, this code makes a pretty important policy\n        # statement about how third-party stuff is added to a Python\n        # installation!  Note that the actual work of installation is done\n        # by the relatively simple 'install_*' commands; they just take\n        # their orders from the installation directory options determined\n        # here.\n\n        # Check for errors/inconsistencies in the options; first, stuff\n        # that's wrong on any platform.\n\n        if (self.prefix or self.exec_prefix or self.home) and (\n            self.install_base or self.install_platbase\n        ):\n            raise DistutilsOptionError(\n                \"must supply either prefix/exec-prefix/home or \"\n                + \"install-base/install-platbase -- not both\"\n            )\n\n        if self.home and (self.prefix or self.exec_prefix):\n            raise DistutilsOptionError(\n                \"must supply either home or prefix/exec-prefix -- not both\"\n            )\n\n        if self.user and (\n            self.prefix\n            or self.exec_prefix\n            or self.home\n            or self.install_base\n            or self.install_platbase\n        ):\n            raise DistutilsOptionError(\n                \"can't combine user with prefix, \"\n                \"exec_prefix/home, or install_(plat)base\"\n            )\n\n        # Next, stuff that's wrong (or dubious) only on certain platforms.\n        if os.name != \"posix\":\n            if self.exec_prefix:\n                self.warn(\"exec-prefix option ignored on this platform\")\n                self.exec_prefix = None\n\n        # Now the interesting logic -- so interesting that we farm it out\n        # to other methods.  The goal of these methods is to set the final\n        # values for the install_{lib,scripts,data,...}  options, using as\n        # input a heady brew of prefix, exec_prefix, home, install_base,\n        # install_platbase, user-supplied versions of\n        # install_{purelib,platlib,lib,scripts,data,...}, and the\n        # install schemes.  Phew!\n\n        self.dump_dirs(\"pre-finalize_{unix,other}\")\n\n        if os.name == 'posix':\n            self.finalize_unix()\n        else:\n            self.finalize_other()\n\n        self.dump_dirs(\"post-finalize_{unix,other}()\")\n\n        # Expand configuration variables, tilde, etc. in self.install_base\n        # and self.install_platbase -- that way, we can use $base or\n        # $platbase in the other installation directories and not worry\n        # about needing recursive variable expansion (shudder).\n\n        py_version = sys.version.split()[0]\n        (prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')\n        try:\n            abiflags = sys.abiflags\n        except AttributeError:\n            # sys.abiflags may not be defined on all platforms.\n            abiflags = ''\n        local_vars = {\n            'dist_name': self.distribution.get_name(),\n            'dist_version': self.distribution.get_version(),\n            'dist_fullname': self.distribution.get_fullname(),\n            'py_version': py_version,\n            'py_version_short': '%d.%d' % sys.version_info[:2],\n            'py_version_nodot': '%d%d' % sys.version_info[:2],\n            'sys_prefix': prefix,\n            'prefix': prefix,\n            'sys_exec_prefix': exec_prefix,\n            'exec_prefix': exec_prefix,\n            'abiflags': abiflags,\n            'platlibdir': getattr(sys, 'platlibdir', 'lib'),\n            'implementation_lower': _get_implementation().lower(),\n            'implementation': _get_implementation(),\n        }\n\n        # vars for compatibility on older Pythons\n        compat_vars = dict(\n            # Python 3.9 and earlier\n            py_version_nodot_plat=getattr(sys, 'winver', '').replace('.', ''),\n        )\n\n        if HAS_USER_SITE:\n            local_vars['userbase'] = self.install_userbase\n            local_vars['usersite'] = self.install_usersite\n\n        self.config_vars = _collections.DictStack(\n            [fw.vars(), compat_vars, sysconfig.get_config_vars(), local_vars]\n        )\n\n        self.expand_basedirs()\n\n        self.dump_dirs(\"post-expand_basedirs()\")\n\n        # Now define config vars for the base directories so we can expand\n        # everything else.\n        local_vars['base'] = self.install_base\n        local_vars['platbase'] = self.install_platbase\n\n        if DEBUG:\n            from pprint import pprint\n\n            print(\"config vars:\")\n            pprint(dict(self.config_vars))\n\n        # Expand \"~\" and configuration variables in the installation\n        # directories.\n        self.expand_dirs()\n\n        self.dump_dirs(\"post-expand_dirs()\")\n\n        # Create directories in the home dir:\n        if self.user:\n            self.create_home_path()\n\n        # Pick the actual directory to install all modules to: either\n        # install_purelib or install_platlib, depending on whether this\n        # module distribution is pure or not.  Of course, if the user\n        # already specified install_lib, use their selection.\n        if self.install_lib is None:\n            if self.distribution.has_ext_modules():  # has extensions: non-pure\n                self.install_lib = self.install_platlib\n            else:\n                self.install_lib = self.install_purelib\n\n        # Convert directories from Unix /-separated syntax to the local\n        # convention.\n        self.convert_paths(\n            'lib',\n            'purelib',\n            'platlib',\n            'scripts',\n            'data',\n            'headers',\n            'userbase',\n            'usersite',\n        )\n\n        # Deprecated\n        # Well, we're not actually fully completely finalized yet: we still\n        # have to deal with 'extra_path', which is the hack for allowing\n        # non-packagized module distributions (hello, Numerical Python!) to\n        # get their own directories.\n        self.handle_extra_path()\n        self.install_libbase = self.install_lib  # needed for .pth file\n        self.install_lib = os.path.join(self.install_lib, self.extra_dirs)\n\n        # If a new root directory was supplied, make all the installation\n        # dirs relative to it.\n        if self.root is not None:\n            self.change_roots(\n                'libbase', 'lib', 'purelib', 'platlib', 'scripts', 'data', 'headers'\n            )\n\n        self.dump_dirs(\"after prepending root\")\n\n        # Find out the build directories, ie. where to install from.\n        self.set_undefined_options(\n            'build', ('build_base', 'build_base'), ('build_lib', 'build_lib')\n        )\n\n        # Punt on doc directories for now -- after all, we're punting on\n        # documentation completely!\n\n    def dump_dirs(self, msg):\n        \"\"\"Dumps the list of user options.\"\"\"\n        if not DEBUG:\n            return\n        from distutils.fancy_getopt import longopt_xlate\n\n        log.debug(msg + \":\")\n        for opt in self.user_options:\n            opt_name = opt[0]\n            if opt_name[-1] == \"=\":\n                opt_name = opt_name[0:-1]\n            if opt_name in self.negative_opt:\n                opt_name = self.negative_opt[opt_name]\n                opt_name = opt_name.translate(longopt_xlate)\n                val = not getattr(self, opt_name)\n            else:\n                opt_name = opt_name.translate(longopt_xlate)\n                val = getattr(self, opt_name)\n            log.debug(\"  %s: %s\", opt_name, val)\n\n    def finalize_unix(self):\n        \"\"\"Finalizes options for posix platforms.\"\"\"\n        if self.install_base is not None or self.install_platbase is not None:\n            incomplete_scheme = (\n                (\n                    self.install_lib is None\n                    and self.install_purelib is None\n                    and self.install_platlib is None\n                )\n                or self.install_headers is None\n                or self.install_scripts is None\n                or self.install_data is None\n            )\n            if incomplete_scheme:\n                raise DistutilsOptionError(\n                    \"install-base or install-platbase supplied, but \"\n                    \"installation scheme is incomplete\"\n                )\n            return\n\n        if self.user:\n            if self.install_userbase is None:\n                raise DistutilsPlatformError(\"User base directory is not specified\")\n            self.install_base = self.install_platbase = self.install_userbase\n            self.select_scheme(\"posix_user\")\n        elif self.home is not None:\n            self.install_base = self.install_platbase = self.home\n            self.select_scheme(\"posix_home\")\n        else:\n            if self.prefix is None:\n                if self.exec_prefix is not None:\n                    raise DistutilsOptionError(\n                        \"must not supply exec-prefix without prefix\"\n                    )\n\n                # Allow Fedora to add components to the prefix\n                _prefix_addition = getattr(sysconfig, '_prefix_addition', \"\")\n\n                self.prefix = os.path.normpath(sys.prefix) + _prefix_addition\n                self.exec_prefix = os.path.normpath(sys.exec_prefix) + _prefix_addition\n\n            else:\n                if self.exec_prefix is None:\n                    self.exec_prefix = self.prefix\n\n            self.install_base = self.prefix\n            self.install_platbase = self.exec_prefix\n            self.select_scheme(\"posix_prefix\")\n\n    def finalize_other(self):\n        \"\"\"Finalizes options for non-posix platforms\"\"\"\n        if self.user:\n            if self.install_userbase is None:\n                raise DistutilsPlatformError(\"User base directory is not specified\")\n            self.install_base = self.install_platbase = self.install_userbase\n            self.select_scheme(os.name + \"_user\")\n        elif self.home is not None:\n            self.install_base = self.install_platbase = self.home\n            self.select_scheme(\"posix_home\")\n        else:\n            if self.prefix is None:\n                self.prefix = os.path.normpath(sys.prefix)\n\n            self.install_base = self.install_platbase = self.prefix\n            try:\n                self.select_scheme(os.name)\n            except KeyError:\n                raise DistutilsPlatformError(\n                    \"I don't know how to install stuff on '%s'\" % os.name\n                )\n\n    def select_scheme(self, name):\n        _select_scheme(self, name)\n\n    def _expand_attrs(self, attrs):\n        for attr in attrs:\n            val = getattr(self, attr)\n            if val is not None:\n                if os.name == 'posix' or os.name == 'nt':\n                    val = os.path.expanduser(val)\n                val = subst_vars(val, self.config_vars)\n                setattr(self, attr, val)\n\n    def expand_basedirs(self):\n        \"\"\"Calls `os.path.expanduser` on install_base, install_platbase and\n        root.\"\"\"\n        self._expand_attrs(['install_base', 'install_platbase', 'root'])\n\n    def expand_dirs(self):\n        \"\"\"Calls `os.path.expanduser` on install dirs.\"\"\"\n        self._expand_attrs(\n            [\n                'install_purelib',\n                'install_platlib',\n                'install_lib',\n                'install_headers',\n                'install_scripts',\n                'install_data',\n            ]\n        )\n\n    def convert_paths(self, *names):\n        \"\"\"Call `convert_path` over `names`.\"\"\"\n        for name in names:\n            attr = \"install_\" + name\n            setattr(self, attr, convert_path(getattr(self, attr)))\n\n    def handle_extra_path(self):\n        \"\"\"Set `path_file` and `extra_dirs` using `extra_path`.\"\"\"\n        if self.extra_path is None:\n            self.extra_path = self.distribution.extra_path\n\n        if self.extra_path is not None:\n            log.warn(\n                \"Distribution option extra_path is deprecated. \"\n                \"See issue27919 for details.\"\n            )\n            if isinstance(self.extra_path, str):\n                self.extra_path = self.extra_path.split(',')\n\n            if len(self.extra_path) == 1:\n                path_file = extra_dirs = self.extra_path[0]\n            elif len(self.extra_path) == 2:\n                path_file, extra_dirs = self.extra_path\n            else:\n                raise DistutilsOptionError(\n                    \"'extra_path' option must be a list, tuple, or \"\n                    \"comma-separated string with 1 or 2 elements\"\n                )\n\n            # convert to local form in case Unix notation used (as it\n            # should be in setup scripts)\n            extra_dirs = convert_path(extra_dirs)\n        else:\n            path_file = None\n            extra_dirs = ''\n\n        # XXX should we warn if path_file and not extra_dirs? (in which\n        # case the path file would be harmless but pointless)\n        self.path_file = path_file\n        self.extra_dirs = extra_dirs\n\n    def change_roots(self, *names):\n        \"\"\"Change the install directories pointed by name using root.\"\"\"\n        for name in names:\n            attr = \"install_\" + name\n            setattr(self, attr, change_root(self.root, getattr(self, attr)))\n\n    def create_home_path(self):\n        \"\"\"Create directories under ~.\"\"\"\n        if not self.user:\n            return\n        home = convert_path(os.path.expanduser(\"~\"))\n        for name, path in self.config_vars.items():\n            if str(path).startswith(home) and not os.path.isdir(path):\n                self.debug_print(\"os.makedirs('%s', 0o700)\" % path)\n                os.makedirs(path, 0o700)\n\n    # -- Command execution methods -------------------------------------\n\n    def run(self):\n        \"\"\"Runs the command.\"\"\"\n        # Obviously have to build before we can install\n        if not self.skip_build:\n            self.run_command('build')\n            # If we built for any other platform, we can't install.\n            build_plat = self.distribution.get_command_obj('build').plat_name\n            # check warn_dir - it is a clue that the 'install' is happening\n            # internally, and not to sys.path, so we don't check the platform\n            # matches what we are running.\n            if self.warn_dir and build_plat != get_platform():\n                raise DistutilsPlatformError(\"Can't install when \" \"cross-compiling\")\n\n        # Run all sub-commands (at least those that need to be run)\n        for cmd_name in self.get_sub_commands():\n            self.run_command(cmd_name)\n\n        if self.path_file:\n            self.create_path_file()\n\n        # write list of installed files, if requested.\n        if self.record:\n            outputs = self.get_outputs()\n            if self.root:  # strip any package prefix\n                root_len = len(self.root)\n                for counter in range(len(outputs)):\n                    outputs[counter] = outputs[counter][root_len:]\n            self.execute(\n                write_file,\n                (self.record, outputs),\n                \"writing list of installed files to '%s'\" % self.record,\n            )\n\n        sys_path = map(os.path.normpath, sys.path)\n        sys_path = map(os.path.normcase, sys_path)\n        install_lib = os.path.normcase(os.path.normpath(self.install_lib))\n        if (\n            self.warn_dir\n            and not (self.path_file and self.install_path_file)\n            and install_lib not in sys_path\n        ):\n            log.debug(\n                (\n                    \"modules installed to '%s', which is not in \"\n                    \"Python's module search path (sys.path) -- \"\n                    \"you'll have to change the search path yourself\"\n                ),\n                self.install_lib,\n            )\n\n    def create_path_file(self):\n        \"\"\"Creates the .pth file\"\"\"\n        filename = os.path.join(self.install_libbase, self.path_file + \".pth\")\n        if self.install_path_file:\n            self.execute(\n                write_file, (filename, [self.extra_dirs]), \"creating %s\" % filename\n            )\n        else:\n            self.warn(\"path file '%s' not created\" % filename)\n\n    # -- Reporting methods ---------------------------------------------\n\n    def get_outputs(self):\n        \"\"\"Assembles the outputs of all the sub-commands.\"\"\"\n        outputs = []\n        for cmd_name in self.get_sub_commands():\n            cmd = self.get_finalized_command(cmd_name)\n            # Add the contents of cmd.get_outputs(), ensuring\n            # that outputs doesn't contain duplicate entries\n            for filename in cmd.get_outputs():\n                if filename not in outputs:\n                    outputs.append(filename)\n\n        if self.path_file and self.install_path_file:\n            outputs.append(os.path.join(self.install_libbase, self.path_file + \".pth\"))\n\n        return outputs\n\n    def get_inputs(self):\n        \"\"\"Returns the inputs of all the sub-commands\"\"\"\n        # XXX gee, this looks familiar ;-(\n        inputs = []\n        for cmd_name in self.get_sub_commands():\n            cmd = self.get_finalized_command(cmd_name)\n            inputs.extend(cmd.get_inputs())\n\n        return inputs\n\n    # -- Predicates for sub-command list -------------------------------\n\n    def has_lib(self):\n        \"\"\"Returns true if the current distribution has any Python\n        modules to install.\"\"\"\n        return (\n            self.distribution.has_pure_modules() or self.distribution.has_ext_modules()\n        )\n\n    def has_headers(self):\n        \"\"\"Returns true if the current distribution has any headers to\n        install.\"\"\"\n        return self.distribution.has_headers()\n\n    def has_scripts(self):\n        \"\"\"Returns true if the current distribution has any scripts to.\n        install.\"\"\"\n        return self.distribution.has_scripts()\n\n    def has_data(self):\n        \"\"\"Returns true if the current distribution has any data to.\n        install.\"\"\"\n        return self.distribution.has_data_files()\n\n    # 'sub_commands': a list of commands this command might have to run to\n    # get its work done.  See cmd.py for more info.\n    sub_commands = [\n        ('install_lib', has_lib),\n        ('install_headers', has_headers),\n        ('install_scripts', has_scripts),\n        ('install_data', has_data),\n        ('install_egg_info', lambda self: True),\n    ]\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/install_data.py",
    "content": "\"\"\"distutils.command.install_data\n\nImplements the Distutils 'install_data' command, for installing\nplatform-independent data files.\"\"\"\n\n# contributed by Bastian Kleineidam\n\nimport os\nfrom distutils.core import Command\nfrom distutils.util import change_root, convert_path\n\n\nclass install_data(Command):\n\n    description = \"install data files\"\n\n    user_options = [\n        (\n            'install-dir=',\n            'd',\n            \"base directory for installing data files \"\n            \"(default: installation base dir)\",\n        ),\n        ('root=', None, \"install everything relative to this alternate root directory\"),\n        ('force', 'f', \"force installation (overwrite existing files)\"),\n    ]\n\n    boolean_options = ['force']\n\n    def initialize_options(self):\n        self.install_dir = None\n        self.outfiles = []\n        self.root = None\n        self.force = 0\n        self.data_files = self.distribution.data_files\n        self.warn_dir = 1\n\n    def finalize_options(self):\n        self.set_undefined_options(\n            'install',\n            ('install_data', 'install_dir'),\n            ('root', 'root'),\n            ('force', 'force'),\n        )\n\n    def run(self):\n        self.mkpath(self.install_dir)\n        for f in self.data_files:\n            if isinstance(f, str):\n                # it's a simple file, so copy it\n                f = convert_path(f)\n                if self.warn_dir:\n                    self.warn(\n                        \"setup script did not provide a directory for \"\n                        \"'%s' -- installing right in '%s'\" % (f, self.install_dir)\n                    )\n                (out, _) = self.copy_file(f, self.install_dir)\n                self.outfiles.append(out)\n            else:\n                # it's a tuple with path to install to and a list of files\n                dir = convert_path(f[0])\n                if not os.path.isabs(dir):\n                    dir = os.path.join(self.install_dir, dir)\n                elif self.root:\n                    dir = change_root(self.root, dir)\n                self.mkpath(dir)\n\n                if f[1] == []:\n                    # If there are no files listed, the user must be\n                    # trying to create an empty directory, so add the\n                    # directory to the list of output files.\n                    self.outfiles.append(dir)\n                else:\n                    # Copy files, adding them to the list of output files.\n                    for data in f[1]:\n                        data = convert_path(data)\n                        (out, _) = self.copy_file(data, dir)\n                        self.outfiles.append(out)\n\n    def get_inputs(self):\n        return self.data_files or []\n\n    def get_outputs(self):\n        return self.outfiles\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/install_egg_info.py",
    "content": "\"\"\"\ndistutils.command.install_egg_info\n\nImplements the Distutils 'install_egg_info' command, for installing\na package's PKG-INFO metadata.\n\"\"\"\n\nimport os\nimport sys\nimport re\n\nfrom distutils.cmd import Command\nfrom distutils import log, dir_util\n\n\nclass install_egg_info(Command):\n    \"\"\"Install an .egg-info file for the package\"\"\"\n\n    description = \"Install package's PKG-INFO metadata as an .egg-info file\"\n    user_options = [\n        ('install-dir=', 'd', \"directory to install to\"),\n    ]\n\n    def initialize_options(self):\n        self.install_dir = None\n\n    @property\n    def basename(self):\n        \"\"\"\n        Allow basename to be overridden by child class.\n        Ref pypa/distutils#2.\n        \"\"\"\n        return \"%s-%s-py%d.%d.egg-info\" % (\n            to_filename(safe_name(self.distribution.get_name())),\n            to_filename(safe_version(self.distribution.get_version())),\n            *sys.version_info[:2],\n        )\n\n    def finalize_options(self):\n        self.set_undefined_options('install_lib', ('install_dir', 'install_dir'))\n        self.target = os.path.join(self.install_dir, self.basename)\n        self.outputs = [self.target]\n\n    def run(self):\n        target = self.target\n        if os.path.isdir(target) and not os.path.islink(target):\n            dir_util.remove_tree(target, dry_run=self.dry_run)\n        elif os.path.exists(target):\n            self.execute(os.unlink, (self.target,), \"Removing \" + target)\n        elif not os.path.isdir(self.install_dir):\n            self.execute(\n                os.makedirs, (self.install_dir,), \"Creating \" + self.install_dir\n            )\n        log.info(\"Writing %s\", target)\n        if not self.dry_run:\n            with open(target, 'w', encoding='UTF-8') as f:\n                self.distribution.metadata.write_pkg_file(f)\n\n    def get_outputs(self):\n        return self.outputs\n\n\n# The following routines are taken from setuptools' pkg_resources module and\n# can be replaced by importing them from pkg_resources once it is included\n# in the stdlib.\n\n\ndef safe_name(name):\n    \"\"\"Convert an arbitrary string to a standard distribution name\n\n    Any runs of non-alphanumeric/. characters are replaced with a single '-'.\n    \"\"\"\n    return re.sub('[^A-Za-z0-9.]+', '-', name)\n\n\ndef safe_version(version):\n    \"\"\"Convert an arbitrary string to a standard version string\n\n    Spaces become dots, and all other non-alphanumeric characters become\n    dashes, with runs of multiple dashes condensed to a single dash.\n    \"\"\"\n    version = version.replace(' ', '.')\n    return re.sub('[^A-Za-z0-9.]+', '-', version)\n\n\ndef to_filename(name):\n    \"\"\"Convert a project or version name to its filename-escaped form\n\n    Any '-' characters are currently replaced with '_'.\n    \"\"\"\n    return name.replace('-', '_')\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/install_headers.py",
    "content": "\"\"\"distutils.command.install_headers\n\nImplements the Distutils 'install_headers' command, to install C/C++ header\nfiles to the Python include directory.\"\"\"\n\nfrom distutils.core import Command\n\n\n# XXX force is never used\nclass install_headers(Command):\n\n    description = \"install C/C++ header files\"\n\n    user_options = [\n        ('install-dir=', 'd', \"directory to install header files to\"),\n        ('force', 'f', \"force installation (overwrite existing files)\"),\n    ]\n\n    boolean_options = ['force']\n\n    def initialize_options(self):\n        self.install_dir = None\n        self.force = 0\n        self.outfiles = []\n\n    def finalize_options(self):\n        self.set_undefined_options(\n            'install', ('install_headers', 'install_dir'), ('force', 'force')\n        )\n\n    def run(self):\n        headers = self.distribution.headers\n        if not headers:\n            return\n\n        self.mkpath(self.install_dir)\n        for header in headers:\n            (out, _) = self.copy_file(header, self.install_dir)\n            self.outfiles.append(out)\n\n    def get_inputs(self):\n        return self.distribution.headers or []\n\n    def get_outputs(self):\n        return self.outfiles\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/install_lib.py",
    "content": "\"\"\"distutils.command.install_lib\n\nImplements the Distutils 'install_lib' command\n(install all Python modules).\"\"\"\n\nimport os\nimport importlib.util\nimport sys\n\nfrom distutils.core import Command\nfrom distutils.errors import DistutilsOptionError\n\n\n# Extension for Python source files.\nPYTHON_SOURCE_EXTENSION = \".py\"\n\n\nclass install_lib(Command):\n\n    description = \"install all Python modules (extensions and pure Python)\"\n\n    # The byte-compilation options are a tad confusing.  Here are the\n    # possible scenarios:\n    #   1) no compilation at all (--no-compile --no-optimize)\n    #   2) compile .pyc only (--compile --no-optimize; default)\n    #   3) compile .pyc and \"opt-1\" .pyc (--compile --optimize)\n    #   4) compile \"opt-1\" .pyc only (--no-compile --optimize)\n    #   5) compile .pyc and \"opt-2\" .pyc (--compile --optimize-more)\n    #   6) compile \"opt-2\" .pyc only (--no-compile --optimize-more)\n    #\n    # The UI for this is two options, 'compile' and 'optimize'.\n    # 'compile' is strictly boolean, and only decides whether to\n    # generate .pyc files.  'optimize' is three-way (0, 1, or 2), and\n    # decides both whether to generate .pyc files and what level of\n    # optimization to use.\n\n    user_options = [\n        ('install-dir=', 'd', \"directory to install to\"),\n        ('build-dir=', 'b', \"build directory (where to install from)\"),\n        ('force', 'f', \"force installation (overwrite existing files)\"),\n        ('compile', 'c', \"compile .py to .pyc [default]\"),\n        ('no-compile', None, \"don't compile .py files\"),\n        (\n            'optimize=',\n            'O',\n            \"also compile with optimization: -O1 for \\\"python -O\\\", \"\n            \"-O2 for \\\"python -OO\\\", and -O0 to disable [default: -O0]\",\n        ),\n        ('skip-build', None, \"skip the build steps\"),\n    ]\n\n    boolean_options = ['force', 'compile', 'skip-build']\n    negative_opt = {'no-compile': 'compile'}\n\n    def initialize_options(self):\n        # let the 'install' command dictate our installation directory\n        self.install_dir = None\n        self.build_dir = None\n        self.force = 0\n        self.compile = None\n        self.optimize = None\n        self.skip_build = None\n\n    def finalize_options(self):\n        # Get all the information we need to install pure Python modules\n        # from the umbrella 'install' command -- build (source) directory,\n        # install (target) directory, and whether to compile .py files.\n        self.set_undefined_options(\n            'install',\n            ('build_lib', 'build_dir'),\n            ('install_lib', 'install_dir'),\n            ('force', 'force'),\n            ('compile', 'compile'),\n            ('optimize', 'optimize'),\n            ('skip_build', 'skip_build'),\n        )\n\n        if self.compile is None:\n            self.compile = True\n        if self.optimize is None:\n            self.optimize = False\n\n        if not isinstance(self.optimize, int):\n            try:\n                self.optimize = int(self.optimize)\n                if self.optimize not in (0, 1, 2):\n                    raise AssertionError\n            except (ValueError, AssertionError):\n                raise DistutilsOptionError(\"optimize must be 0, 1, or 2\")\n\n    def run(self):\n        # Make sure we have built everything we need first\n        self.build()\n\n        # Install everything: simply dump the entire contents of the build\n        # directory to the installation directory (that's the beauty of\n        # having a build directory!)\n        outfiles = self.install()\n\n        # (Optionally) compile .py to .pyc\n        if outfiles is not None and self.distribution.has_pure_modules():\n            self.byte_compile(outfiles)\n\n    # -- Top-level worker functions ------------------------------------\n    # (called from 'run()')\n\n    def build(self):\n        if not self.skip_build:\n            if self.distribution.has_pure_modules():\n                self.run_command('build_py')\n            if self.distribution.has_ext_modules():\n                self.run_command('build_ext')\n\n    def install(self):\n        if os.path.isdir(self.build_dir):\n            outfiles = self.copy_tree(self.build_dir, self.install_dir)\n        else:\n            self.warn(\n                \"'%s' does not exist -- no Python modules to install\" % self.build_dir\n            )\n            return\n        return outfiles\n\n    def byte_compile(self, files):\n        if sys.dont_write_bytecode:\n            self.warn('byte-compiling is disabled, skipping.')\n            return\n\n        from distutils.util import byte_compile\n\n        # Get the \"--root\" directory supplied to the \"install\" command,\n        # and use it as a prefix to strip off the purported filename\n        # encoded in bytecode files.  This is far from complete, but it\n        # should at least generate usable bytecode in RPM distributions.\n        install_root = self.get_finalized_command('install').root\n\n        if self.compile:\n            byte_compile(\n                files,\n                optimize=0,\n                force=self.force,\n                prefix=install_root,\n                dry_run=self.dry_run,\n            )\n        if self.optimize > 0:\n            byte_compile(\n                files,\n                optimize=self.optimize,\n                force=self.force,\n                prefix=install_root,\n                verbose=self.verbose,\n                dry_run=self.dry_run,\n            )\n\n    # -- Utility methods -----------------------------------------------\n\n    def _mutate_outputs(self, has_any, build_cmd, cmd_option, output_dir):\n        if not has_any:\n            return []\n\n        build_cmd = self.get_finalized_command(build_cmd)\n        build_files = build_cmd.get_outputs()\n        build_dir = getattr(build_cmd, cmd_option)\n\n        prefix_len = len(build_dir) + len(os.sep)\n        outputs = []\n        for file in build_files:\n            outputs.append(os.path.join(output_dir, file[prefix_len:]))\n\n        return outputs\n\n    def _bytecode_filenames(self, py_filenames):\n        bytecode_files = []\n        for py_file in py_filenames:\n            # Since build_py handles package data installation, the\n            # list of outputs can contain more than just .py files.\n            # Make sure we only report bytecode for the .py files.\n            ext = os.path.splitext(os.path.normcase(py_file))[1]\n            if ext != PYTHON_SOURCE_EXTENSION:\n                continue\n            if self.compile:\n                bytecode_files.append(\n                    importlib.util.cache_from_source(py_file, optimization='')\n                )\n            if self.optimize > 0:\n                bytecode_files.append(\n                    importlib.util.cache_from_source(\n                        py_file, optimization=self.optimize\n                    )\n                )\n\n        return bytecode_files\n\n    # -- External interface --------------------------------------------\n    # (called by outsiders)\n\n    def get_outputs(self):\n        \"\"\"Return the list of files that would be installed if this command\n        were actually run.  Not affected by the \"dry-run\" flag or whether\n        modules have actually been built yet.\n        \"\"\"\n        pure_outputs = self._mutate_outputs(\n            self.distribution.has_pure_modules(),\n            'build_py',\n            'build_lib',\n            self.install_dir,\n        )\n        if self.compile:\n            bytecode_outputs = self._bytecode_filenames(pure_outputs)\n        else:\n            bytecode_outputs = []\n\n        ext_outputs = self._mutate_outputs(\n            self.distribution.has_ext_modules(),\n            'build_ext',\n            'build_lib',\n            self.install_dir,\n        )\n\n        return pure_outputs + bytecode_outputs + ext_outputs\n\n    def get_inputs(self):\n        \"\"\"Get the list of files that are input to this command, ie. the\n        files that get installed as they are named in the build tree.\n        The files in this list correspond one-to-one to the output\n        filenames returned by 'get_outputs()'.\n        \"\"\"\n        inputs = []\n\n        if self.distribution.has_pure_modules():\n            build_py = self.get_finalized_command('build_py')\n            inputs.extend(build_py.get_outputs())\n\n        if self.distribution.has_ext_modules():\n            build_ext = self.get_finalized_command('build_ext')\n            inputs.extend(build_ext.get_outputs())\n\n        return inputs\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/install_scripts.py",
    "content": "\"\"\"distutils.command.install_scripts\n\nImplements the Distutils 'install_scripts' command, for installing\nPython scripts.\"\"\"\n\n# contributed by Bastian Kleineidam\n\nimport os\nfrom distutils.core import Command\nfrom distutils import log\nfrom stat import ST_MODE\n\n\nclass install_scripts(Command):\n\n    description = \"install scripts (Python or otherwise)\"\n\n    user_options = [\n        ('install-dir=', 'd', \"directory to install scripts to\"),\n        ('build-dir=', 'b', \"build directory (where to install from)\"),\n        ('force', 'f', \"force installation (overwrite existing files)\"),\n        ('skip-build', None, \"skip the build steps\"),\n    ]\n\n    boolean_options = ['force', 'skip-build']\n\n    def initialize_options(self):\n        self.install_dir = None\n        self.force = 0\n        self.build_dir = None\n        self.skip_build = None\n\n    def finalize_options(self):\n        self.set_undefined_options('build', ('build_scripts', 'build_dir'))\n        self.set_undefined_options(\n            'install',\n            ('install_scripts', 'install_dir'),\n            ('force', 'force'),\n            ('skip_build', 'skip_build'),\n        )\n\n    def run(self):\n        if not self.skip_build:\n            self.run_command('build_scripts')\n        self.outfiles = self.copy_tree(self.build_dir, self.install_dir)\n        if os.name == 'posix':\n            # Set the executable bits (owner, group, and world) on\n            # all the scripts we just installed.\n            for file in self.get_outputs():\n                if self.dry_run:\n                    log.info(\"changing mode of %s\", file)\n                else:\n                    mode = ((os.stat(file)[ST_MODE]) | 0o555) & 0o7777\n                    log.info(\"changing mode of %s to %o\", file, mode)\n                    os.chmod(file, mode)\n\n    def get_inputs(self):\n        return self.distribution.scripts or []\n\n    def get_outputs(self):\n        return self.outfiles or []\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/py37compat.py",
    "content": "import sys\n\n\ndef _pythonlib_compat():\n    \"\"\"\n    On Python 3.7 and earlier, distutils would include the Python\n    library. See pypa/distutils#9.\n    \"\"\"\n    from distutils import sysconfig\n\n    if not sysconfig.get_config_var('Py_ENABLED_SHARED'):\n        return\n\n    yield 'python{}.{}{}'.format(\n        sys.hexversion >> 24,\n        (sys.hexversion >> 16) & 0xFF,\n        sysconfig.get_config_var('ABIFLAGS'),\n    )\n\n\ndef compose(f1, f2):\n    return lambda *args, **kwargs: f1(f2(*args, **kwargs))\n\n\npythonlib = (\n    compose(list, _pythonlib_compat)\n    if sys.version_info < (3, 8)\n    and sys.platform != 'darwin'\n    and sys.platform[:3] != 'aix'\n    else list\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/register.py",
    "content": "\"\"\"distutils.command.register\n\nImplements the Distutils 'register' command (register with the repository).\n\"\"\"\n\n# created 2002/10/21, Richard Jones\n\nimport getpass\nimport io\nimport urllib.parse\nimport urllib.request\nfrom warnings import warn\n\nfrom distutils.core import PyPIRCCommand\nfrom distutils import log\n\n\nclass register(PyPIRCCommand):\n\n    description = \"register the distribution with the Python package index\"\n    user_options = PyPIRCCommand.user_options + [\n        ('list-classifiers', None, 'list the valid Trove classifiers'),\n        (\n            'strict',\n            None,\n            'Will stop the registering if the meta-data are not fully compliant',\n        ),\n    ]\n    boolean_options = PyPIRCCommand.boolean_options + [\n        'verify',\n        'list-classifiers',\n        'strict',\n    ]\n\n    sub_commands = [('check', lambda self: True)]\n\n    def initialize_options(self):\n        PyPIRCCommand.initialize_options(self)\n        self.list_classifiers = 0\n        self.strict = 0\n\n    def finalize_options(self):\n        PyPIRCCommand.finalize_options(self)\n        # setting options for the `check` subcommand\n        check_options = {\n            'strict': ('register', self.strict),\n            'restructuredtext': ('register', 1),\n        }\n        self.distribution.command_options['check'] = check_options\n\n    def run(self):\n        self.finalize_options()\n        self._set_config()\n\n        # Run sub commands\n        for cmd_name in self.get_sub_commands():\n            self.run_command(cmd_name)\n\n        if self.dry_run:\n            self.verify_metadata()\n        elif self.list_classifiers:\n            self.classifiers()\n        else:\n            self.send_metadata()\n\n    def check_metadata(self):\n        \"\"\"Deprecated API.\"\"\"\n        warn(\n            \"distutils.command.register.check_metadata is deprecated; \"\n            \"use the check command instead\",\n            DeprecationWarning,\n        )\n        check = self.distribution.get_command_obj('check')\n        check.ensure_finalized()\n        check.strict = self.strict\n        check.restructuredtext = 1\n        check.run()\n\n    def _set_config(self):\n        '''Reads the configuration file and set attributes.'''\n        config = self._read_pypirc()\n        if config != {}:\n            self.username = config['username']\n            self.password = config['password']\n            self.repository = config['repository']\n            self.realm = config['realm']\n            self.has_config = True\n        else:\n            if self.repository not in ('pypi', self.DEFAULT_REPOSITORY):\n                raise ValueError('%s not found in .pypirc' % self.repository)\n            if self.repository == 'pypi':\n                self.repository = self.DEFAULT_REPOSITORY\n            self.has_config = False\n\n    def classifiers(self):\n        '''Fetch the list of classifiers from the server.'''\n        url = self.repository + '?:action=list_classifiers'\n        response = urllib.request.urlopen(url)\n        log.info(self._read_pypi_response(response))\n\n    def verify_metadata(self):\n        '''Send the metadata to the package index server to be checked.'''\n        # send the info to the server and report the result\n        (code, result) = self.post_to_server(self.build_post_data('verify'))\n        log.info('Server response (%s): %s', code, result)\n\n    def send_metadata(self):  # noqa: C901\n        '''Send the metadata to the package index server.\n\n        Well, do the following:\n        1. figure who the user is, and then\n        2. send the data as a Basic auth'ed POST.\n\n        First we try to read the username/password from $HOME/.pypirc,\n        which is a ConfigParser-formatted file with a section\n        [distutils] containing username and password entries (both\n        in clear text). Eg:\n\n            [distutils]\n            index-servers =\n                pypi\n\n            [pypi]\n            username: fred\n            password: sekrit\n\n        Otherwise, to figure who the user is, we offer the user three\n        choices:\n\n         1. use existing login,\n         2. register as a new user, or\n         3. set the password to a random string and email the user.\n\n        '''\n        # see if we can short-cut and get the username/password from the\n        # config\n        if self.has_config:\n            choice = '1'\n            username = self.username\n            password = self.password\n        else:\n            choice = 'x'\n            username = password = ''\n\n        # get the user's login info\n        choices = '1 2 3 4'.split()\n        while choice not in choices:\n            self.announce(\n                '''\\\nWe need to know who you are, so please choose either:\n 1. use your existing login,\n 2. register as a new user,\n 3. have the server generate a new password for you (and email it to you), or\n 4. quit\nYour selection [default 1]: ''',\n                log.INFO,\n            )\n            choice = input()\n            if not choice:\n                choice = '1'\n            elif choice not in choices:\n                print('Please choose one of the four options!')\n\n        if choice == '1':\n            # get the username and password\n            while not username:\n                username = input('Username: ')\n            while not password:\n                password = getpass.getpass('Password: ')\n\n            # set up the authentication\n            auth = urllib.request.HTTPPasswordMgr()\n            host = urllib.parse.urlparse(self.repository)[1]\n            auth.add_password(self.realm, host, username, password)\n            # send the info to the server and report the result\n            code, result = self.post_to_server(self.build_post_data('submit'), auth)\n            self.announce('Server response ({}): {}'.format(code, result), log.INFO)\n\n            # possibly save the login\n            if code == 200:\n                if self.has_config:\n                    # sharing the password in the distribution instance\n                    # so the upload command can reuse it\n                    self.distribution.password = password\n                else:\n                    self.announce(\n                        (\n                            'I can store your PyPI login so future '\n                            'submissions will be faster.'\n                        ),\n                        log.INFO,\n                    )\n                    self.announce(\n                        '(the login will be stored in %s)' % self._get_rc_file(),\n                        log.INFO,\n                    )\n                    choice = 'X'\n                    while choice.lower() not in 'yn':\n                        choice = input('Save your login (y/N)?')\n                        if not choice:\n                            choice = 'n'\n                    if choice.lower() == 'y':\n                        self._store_pypirc(username, password)\n\n        elif choice == '2':\n            data = {':action': 'user'}\n            data['name'] = data['password'] = data['email'] = ''\n            data['confirm'] = None\n            while not data['name']:\n                data['name'] = input('Username: ')\n            while data['password'] != data['confirm']:\n                while not data['password']:\n                    data['password'] = getpass.getpass('Password: ')\n                while not data['confirm']:\n                    data['confirm'] = getpass.getpass(' Confirm: ')\n                if data['password'] != data['confirm']:\n                    data['password'] = ''\n                    data['confirm'] = None\n                    print(\"Password and confirm don't match!\")\n            while not data['email']:\n                data['email'] = input('   EMail: ')\n            code, result = self.post_to_server(data)\n            if code != 200:\n                log.info('Server response (%s): %s', code, result)\n            else:\n                log.info('You will receive an email shortly.')\n                log.info('Follow the instructions in it to ' 'complete registration.')\n        elif choice == '3':\n            data = {':action': 'password_reset'}\n            data['email'] = ''\n            while not data['email']:\n                data['email'] = input('Your email address: ')\n            code, result = self.post_to_server(data)\n            log.info('Server response (%s): %s', code, result)\n\n    def build_post_data(self, action):\n        # figure the data to send - the metadata plus some additional\n        # information used by the package server\n        meta = self.distribution.metadata\n        data = {\n            ':action': action,\n            'metadata_version': '1.0',\n            'name': meta.get_name(),\n            'version': meta.get_version(),\n            'summary': meta.get_description(),\n            'home_page': meta.get_url(),\n            'author': meta.get_contact(),\n            'author_email': meta.get_contact_email(),\n            'license': meta.get_licence(),\n            'description': meta.get_long_description(),\n            'keywords': meta.get_keywords(),\n            'platform': meta.get_platforms(),\n            'classifiers': meta.get_classifiers(),\n            'download_url': meta.get_download_url(),\n            # PEP 314\n            'provides': meta.get_provides(),\n            'requires': meta.get_requires(),\n            'obsoletes': meta.get_obsoletes(),\n        }\n        if data['provides'] or data['requires'] or data['obsoletes']:\n            data['metadata_version'] = '1.1'\n        return data\n\n    def post_to_server(self, data, auth=None):  # noqa: C901\n        '''Post a query to the server, and return a string response.'''\n        if 'name' in data:\n            self.announce(\n                'Registering {} to {}'.format(data['name'], self.repository), log.INFO\n            )\n        # Build up the MIME payload for the urllib2 POST data\n        boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'\n        sep_boundary = '\\n--' + boundary\n        end_boundary = sep_boundary + '--'\n        body = io.StringIO()\n        for key, value in data.items():\n            # handle multiple entries for the same name\n            if type(value) not in (type([]), type(())):\n                value = [value]\n            for value in value:\n                value = str(value)\n                body.write(sep_boundary)\n                body.write('\\nContent-Disposition: form-data; name=\"%s\"' % key)\n                body.write(\"\\n\\n\")\n                body.write(value)\n                if value and value[-1] == '\\r':\n                    body.write('\\n')  # write an extra newline (lurve Macs)\n        body.write(end_boundary)\n        body.write(\"\\n\")\n        body = body.getvalue().encode(\"utf-8\")\n\n        # build the Request\n        headers = {\n            'Content-type': 'multipart/form-data; boundary=%s; charset=utf-8'\n            % boundary,\n            'Content-length': str(len(body)),\n        }\n        req = urllib.request.Request(self.repository, body, headers)\n\n        # handle HTTP and include the Basic Auth handler\n        opener = urllib.request.build_opener(\n            urllib.request.HTTPBasicAuthHandler(password_mgr=auth)\n        )\n        data = ''\n        try:\n            result = opener.open(req)\n        except urllib.error.HTTPError as e:\n            if self.show_response:\n                data = e.fp.read()\n            result = e.code, e.msg\n        except urllib.error.URLError as e:\n            result = 500, str(e)\n        else:\n            if self.show_response:\n                data = self._read_pypi_response(result)\n            result = 200, 'OK'\n        if self.show_response:\n            msg = '\\n'.join(('-' * 75, data, '-' * 75))\n            self.announce(msg, log.INFO)\n        return result\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/sdist.py",
    "content": "\"\"\"distutils.command.sdist\n\nImplements the Distutils 'sdist' command (create a source distribution).\"\"\"\n\nimport os\nimport sys\nfrom glob import glob\nfrom warnings import warn\n\nfrom distutils.core import Command\nfrom distutils import dir_util\nfrom distutils import file_util\nfrom distutils import archive_util\nfrom distutils.text_file import TextFile\nfrom distutils.filelist import FileList\nfrom distutils import log\nfrom distutils.util import convert_path\nfrom distutils.errors import DistutilsOptionError, DistutilsTemplateError\n\n\ndef show_formats():\n    \"\"\"Print all possible values for the 'formats' option (used by\n    the \"--help-formats\" command-line option).\n    \"\"\"\n    from distutils.fancy_getopt import FancyGetopt\n    from distutils.archive_util import ARCHIVE_FORMATS\n\n    formats = []\n    for format in ARCHIVE_FORMATS.keys():\n        formats.append((\"formats=\" + format, None, ARCHIVE_FORMATS[format][2]))\n    formats.sort()\n    FancyGetopt(formats).print_help(\"List of available source distribution formats:\")\n\n\nclass sdist(Command):\n\n    description = \"create a source distribution (tarball, zip file, etc.)\"\n\n    def checking_metadata(self):\n        \"\"\"Callable used for the check sub-command.\n\n        Placed here so user_options can view it\"\"\"\n        return self.metadata_check\n\n    user_options = [\n        ('template=', 't', \"name of manifest template file [default: MANIFEST.in]\"),\n        ('manifest=', 'm', \"name of manifest file [default: MANIFEST]\"),\n        (\n            'use-defaults',\n            None,\n            \"include the default file set in the manifest \"\n            \"[default; disable with --no-defaults]\",\n        ),\n        ('no-defaults', None, \"don't include the default file set\"),\n        (\n            'prune',\n            None,\n            \"specifically exclude files/directories that should not be \"\n            \"distributed (build tree, RCS/CVS dirs, etc.) \"\n            \"[default; disable with --no-prune]\",\n        ),\n        ('no-prune', None, \"don't automatically exclude anything\"),\n        (\n            'manifest-only',\n            'o',\n            \"just regenerate the manifest and then stop \" \"(implies --force-manifest)\",\n        ),\n        (\n            'force-manifest',\n            'f',\n            \"forcibly regenerate the manifest and carry on as usual. \"\n            \"Deprecated: now the manifest is always regenerated.\",\n        ),\n        ('formats=', None, \"formats for source distribution (comma-separated list)\"),\n        (\n            'keep-temp',\n            'k',\n            \"keep the distribution tree around after creating \" + \"archive file(s)\",\n        ),\n        (\n            'dist-dir=',\n            'd',\n            \"directory to put the source distribution archive(s) in \" \"[default: dist]\",\n        ),\n        (\n            'metadata-check',\n            None,\n            \"Ensure that all required elements of meta-data \"\n            \"are supplied. Warn if any missing. [default]\",\n        ),\n        (\n            'owner=',\n            'u',\n            \"Owner name used when creating a tar file [default: current user]\",\n        ),\n        (\n            'group=',\n            'g',\n            \"Group name used when creating a tar file [default: current group]\",\n        ),\n    ]\n\n    boolean_options = [\n        'use-defaults',\n        'prune',\n        'manifest-only',\n        'force-manifest',\n        'keep-temp',\n        'metadata-check',\n    ]\n\n    help_options = [\n        ('help-formats', None, \"list available distribution formats\", show_formats),\n    ]\n\n    negative_opt = {'no-defaults': 'use-defaults', 'no-prune': 'prune'}\n\n    sub_commands = [('check', checking_metadata)]\n\n    READMES = ('README', 'README.txt', 'README.rst')\n\n    def initialize_options(self):\n        # 'template' and 'manifest' are, respectively, the names of\n        # the manifest template and manifest file.\n        self.template = None\n        self.manifest = None\n\n        # 'use_defaults': if true, we will include the default file set\n        # in the manifest\n        self.use_defaults = 1\n        self.prune = 1\n\n        self.manifest_only = 0\n        self.force_manifest = 0\n\n        self.formats = ['gztar']\n        self.keep_temp = 0\n        self.dist_dir = None\n\n        self.archive_files = None\n        self.metadata_check = 1\n        self.owner = None\n        self.group = None\n\n    def finalize_options(self):\n        if self.manifest is None:\n            self.manifest = \"MANIFEST\"\n        if self.template is None:\n            self.template = \"MANIFEST.in\"\n\n        self.ensure_string_list('formats')\n\n        bad_format = archive_util.check_archive_formats(self.formats)\n        if bad_format:\n            raise DistutilsOptionError(\"unknown archive format '%s'\" % bad_format)\n\n        if self.dist_dir is None:\n            self.dist_dir = \"dist\"\n\n    def run(self):\n        # 'filelist' contains the list of files that will make up the\n        # manifest\n        self.filelist = FileList()\n\n        # Run sub commands\n        for cmd_name in self.get_sub_commands():\n            self.run_command(cmd_name)\n\n        # Do whatever it takes to get the list of files to process\n        # (process the manifest template, read an existing manifest,\n        # whatever).  File list is accumulated in 'self.filelist'.\n        self.get_file_list()\n\n        # If user just wanted us to regenerate the manifest, stop now.\n        if self.manifest_only:\n            return\n\n        # Otherwise, go ahead and create the source distribution tarball,\n        # or zipfile, or whatever.\n        self.make_distribution()\n\n    def check_metadata(self):\n        \"\"\"Deprecated API.\"\"\"\n        warn(\n            \"distutils.command.sdist.check_metadata is deprecated, \\\n              use the check command instead\",\n            PendingDeprecationWarning,\n        )\n        check = self.distribution.get_command_obj('check')\n        check.ensure_finalized()\n        check.run()\n\n    def get_file_list(self):\n        \"\"\"Figure out the list of files to include in the source\n        distribution, and put it in 'self.filelist'.  This might involve\n        reading the manifest template (and writing the manifest), or just\n        reading the manifest, or just using the default file set -- it all\n        depends on the user's options.\n        \"\"\"\n        # new behavior when using a template:\n        # the file list is recalculated every time because\n        # even if MANIFEST.in or setup.py are not changed\n        # the user might have added some files in the tree that\n        # need to be included.\n        #\n        #  This makes --force the default and only behavior with templates.\n        template_exists = os.path.isfile(self.template)\n        if not template_exists and self._manifest_is_not_generated():\n            self.read_manifest()\n            self.filelist.sort()\n            self.filelist.remove_duplicates()\n            return\n\n        if not template_exists:\n            self.warn(\n                (\"manifest template '%s' does not exist \" + \"(using default file list)\")\n                % self.template\n            )\n        self.filelist.findall()\n\n        if self.use_defaults:\n            self.add_defaults()\n\n        if template_exists:\n            self.read_template()\n\n        if self.prune:\n            self.prune_file_list()\n\n        self.filelist.sort()\n        self.filelist.remove_duplicates()\n        self.write_manifest()\n\n    def add_defaults(self):\n        \"\"\"Add all the default files to self.filelist:\n          - README or README.txt\n          - setup.py\n          - test/test*.py\n          - all pure Python modules mentioned in setup script\n          - all files pointed by package_data (build_py)\n          - all files defined in data_files.\n          - all files defined as scripts.\n          - all C sources listed as part of extensions or C libraries\n            in the setup script (doesn't catch C headers!)\n        Warns if (README or README.txt) or setup.py are missing; everything\n        else is optional.\n        \"\"\"\n        self._add_defaults_standards()\n        self._add_defaults_optional()\n        self._add_defaults_python()\n        self._add_defaults_data_files()\n        self._add_defaults_ext()\n        self._add_defaults_c_libs()\n        self._add_defaults_scripts()\n\n    @staticmethod\n    def _cs_path_exists(fspath):\n        \"\"\"\n        Case-sensitive path existence check\n\n        >>> sdist._cs_path_exists(__file__)\n        True\n        >>> sdist._cs_path_exists(__file__.upper())\n        False\n        \"\"\"\n        if not os.path.exists(fspath):\n            return False\n        # make absolute so we always have a directory\n        abspath = os.path.abspath(fspath)\n        directory, filename = os.path.split(abspath)\n        return filename in os.listdir(directory)\n\n    def _add_defaults_standards(self):\n        standards = [self.READMES, self.distribution.script_name]\n        for fn in standards:\n            if isinstance(fn, tuple):\n                alts = fn\n                got_it = False\n                for fn in alts:\n                    if self._cs_path_exists(fn):\n                        got_it = True\n                        self.filelist.append(fn)\n                        break\n\n                if not got_it:\n                    self.warn(\n                        \"standard file not found: should have one of \" + ', '.join(alts)\n                    )\n            else:\n                if self._cs_path_exists(fn):\n                    self.filelist.append(fn)\n                else:\n                    self.warn(\"standard file '%s' not found\" % fn)\n\n    def _add_defaults_optional(self):\n        optional = ['test/test*.py', 'setup.cfg']\n        for pattern in optional:\n            files = filter(os.path.isfile, glob(pattern))\n            self.filelist.extend(files)\n\n    def _add_defaults_python(self):\n        # build_py is used to get:\n        #  - python modules\n        #  - files defined in package_data\n        build_py = self.get_finalized_command('build_py')\n\n        # getting python files\n        if self.distribution.has_pure_modules():\n            self.filelist.extend(build_py.get_source_files())\n\n        # getting package_data files\n        # (computed in build_py.data_files by build_py.finalize_options)\n        for pkg, src_dir, build_dir, filenames in build_py.data_files:\n            for filename in filenames:\n                self.filelist.append(os.path.join(src_dir, filename))\n\n    def _add_defaults_data_files(self):\n        # getting distribution.data_files\n        if self.distribution.has_data_files():\n            for item in self.distribution.data_files:\n                if isinstance(item, str):\n                    # plain file\n                    item = convert_path(item)\n                    if os.path.isfile(item):\n                        self.filelist.append(item)\n                else:\n                    # a (dirname, filenames) tuple\n                    dirname, filenames = item\n                    for f in filenames:\n                        f = convert_path(f)\n                        if os.path.isfile(f):\n                            self.filelist.append(f)\n\n    def _add_defaults_ext(self):\n        if self.distribution.has_ext_modules():\n            build_ext = self.get_finalized_command('build_ext')\n            self.filelist.extend(build_ext.get_source_files())\n\n    def _add_defaults_c_libs(self):\n        if self.distribution.has_c_libraries():\n            build_clib = self.get_finalized_command('build_clib')\n            self.filelist.extend(build_clib.get_source_files())\n\n    def _add_defaults_scripts(self):\n        if self.distribution.has_scripts():\n            build_scripts = self.get_finalized_command('build_scripts')\n            self.filelist.extend(build_scripts.get_source_files())\n\n    def read_template(self):\n        \"\"\"Read and parse manifest template file named by self.template.\n\n        (usually \"MANIFEST.in\") The parsing and processing is done by\n        'self.filelist', which updates itself accordingly.\n        \"\"\"\n        log.info(\"reading manifest template '%s'\", self.template)\n        template = TextFile(\n            self.template,\n            strip_comments=1,\n            skip_blanks=1,\n            join_lines=1,\n            lstrip_ws=1,\n            rstrip_ws=1,\n            collapse_join=1,\n        )\n\n        try:\n            while True:\n                line = template.readline()\n                if line is None:  # end of file\n                    break\n\n                try:\n                    self.filelist.process_template_line(line)\n                # the call above can raise a DistutilsTemplateError for\n                # malformed lines, or a ValueError from the lower-level\n                # convert_path function\n                except (DistutilsTemplateError, ValueError) as msg:\n                    self.warn(\n                        \"%s, line %d: %s\"\n                        % (template.filename, template.current_line, msg)\n                    )\n        finally:\n            template.close()\n\n    def prune_file_list(self):\n        \"\"\"Prune off branches that might slip into the file list as created\n        by 'read_template()', but really don't belong there:\n          * the build tree (typically \"build\")\n          * the release tree itself (only an issue if we ran \"sdist\"\n            previously with --keep-temp, or it aborted)\n          * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories\n        \"\"\"\n        build = self.get_finalized_command('build')\n        base_dir = self.distribution.get_fullname()\n\n        self.filelist.exclude_pattern(None, prefix=build.build_base)\n        self.filelist.exclude_pattern(None, prefix=base_dir)\n\n        if sys.platform == 'win32':\n            seps = r'/|\\\\'\n        else:\n            seps = '/'\n\n        vcs_dirs = ['RCS', 'CVS', r'\\.svn', r'\\.hg', r'\\.git', r'\\.bzr', '_darcs']\n        vcs_ptrn = r'(^|{})({})({}).*'.format(seps, '|'.join(vcs_dirs), seps)\n        self.filelist.exclude_pattern(vcs_ptrn, is_regex=1)\n\n    def write_manifest(self):\n        \"\"\"Write the file list in 'self.filelist' (presumably as filled in\n        by 'add_defaults()' and 'read_template()') to the manifest file\n        named by 'self.manifest'.\n        \"\"\"\n        if self._manifest_is_not_generated():\n            log.info(\n                \"not writing to manually maintained \"\n                \"manifest file '%s'\" % self.manifest\n            )\n            return\n\n        content = self.filelist.files[:]\n        content.insert(0, '# file GENERATED by distutils, do NOT edit')\n        self.execute(\n            file_util.write_file,\n            (self.manifest, content),\n            \"writing manifest file '%s'\" % self.manifest,\n        )\n\n    def _manifest_is_not_generated(self):\n        # check for special comment used in 3.1.3 and higher\n        if not os.path.isfile(self.manifest):\n            return False\n\n        fp = open(self.manifest)\n        try:\n            first_line = fp.readline()\n        finally:\n            fp.close()\n        return first_line != '# file GENERATED by distutils, do NOT edit\\n'\n\n    def read_manifest(self):\n        \"\"\"Read the manifest file (named by 'self.manifest') and use it to\n        fill in 'self.filelist', the list of files to include in the source\n        distribution.\n        \"\"\"\n        log.info(\"reading manifest file '%s'\", self.manifest)\n        with open(self.manifest) as manifest:\n            for line in manifest:\n                # ignore comments and blank lines\n                line = line.strip()\n                if line.startswith('#') or not line:\n                    continue\n                self.filelist.append(line)\n\n    def make_release_tree(self, base_dir, files):\n        \"\"\"Create the directory tree that will become the source\n        distribution archive.  All directories implied by the filenames in\n        'files' are created under 'base_dir', and then we hard link or copy\n        (if hard linking is unavailable) those files into place.\n        Essentially, this duplicates the developer's source tree, but in a\n        directory named after the distribution, containing only the files\n        to be distributed.\n        \"\"\"\n        # Create all the directories under 'base_dir' necessary to\n        # put 'files' there; the 'mkpath()' is just so we don't die\n        # if the manifest happens to be empty.\n        self.mkpath(base_dir)\n        dir_util.create_tree(base_dir, files, dry_run=self.dry_run)\n\n        # And walk over the list of files, either making a hard link (if\n        # os.link exists) to each one that doesn't already exist in its\n        # corresponding location under 'base_dir', or copying each file\n        # that's out-of-date in 'base_dir'.  (Usually, all files will be\n        # out-of-date, because by default we blow away 'base_dir' when\n        # we're done making the distribution archives.)\n\n        if hasattr(os, 'link'):  # can make hard links on this system\n            link = 'hard'\n            msg = \"making hard links in %s...\" % base_dir\n        else:  # nope, have to copy\n            link = None\n            msg = \"copying files to %s...\" % base_dir\n\n        if not files:\n            log.warn(\"no files to distribute -- empty manifest?\")\n        else:\n            log.info(msg)\n        for file in files:\n            if not os.path.isfile(file):\n                log.warn(\"'%s' not a regular file -- skipping\", file)\n            else:\n                dest = os.path.join(base_dir, file)\n                self.copy_file(file, dest, link=link)\n\n        self.distribution.metadata.write_pkg_info(base_dir)\n\n    def make_distribution(self):\n        \"\"\"Create the source distribution(s).  First, we create the release\n        tree with 'make_release_tree()'; then, we create all required\n        archive files (according to 'self.formats') from the release tree.\n        Finally, we clean up by blowing away the release tree (unless\n        'self.keep_temp' is true).  The list of archive files created is\n        stored so it can be retrieved later by 'get_archive_files()'.\n        \"\"\"\n        # Don't warn about missing meta-data here -- should be (and is!)\n        # done elsewhere.\n        base_dir = self.distribution.get_fullname()\n        base_name = os.path.join(self.dist_dir, base_dir)\n\n        self.make_release_tree(base_dir, self.filelist.files)\n        archive_files = []  # remember names of files we create\n        # tar archive must be created last to avoid overwrite and remove\n        if 'tar' in self.formats:\n            self.formats.append(self.formats.pop(self.formats.index('tar')))\n\n        for fmt in self.formats:\n            file = self.make_archive(\n                base_name, fmt, base_dir=base_dir, owner=self.owner, group=self.group\n            )\n            archive_files.append(file)\n            self.distribution.dist_files.append(('sdist', '', file))\n\n        self.archive_files = archive_files\n\n        if not self.keep_temp:\n            dir_util.remove_tree(base_dir, dry_run=self.dry_run)\n\n    def get_archive_files(self):\n        \"\"\"Return the list of archive files created when the command\n        was run, or None if the command hasn't run yet.\n        \"\"\"\n        return self.archive_files\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/command/upload.py",
    "content": "\"\"\"\ndistutils.command.upload\n\nImplements the Distutils 'upload' subcommand (upload package to a package\nindex).\n\"\"\"\n\nimport os\nimport io\nimport hashlib\nfrom base64 import standard_b64encode\nfrom urllib.request import urlopen, Request, HTTPError\nfrom urllib.parse import urlparse\nfrom distutils.errors import DistutilsError, DistutilsOptionError\nfrom distutils.core import PyPIRCCommand\nfrom distutils.spawn import spawn\nfrom distutils import log\n\n\n# PyPI Warehouse supports MD5, SHA256, and Blake2 (blake2-256)\n# https://bugs.python.org/issue40698\n_FILE_CONTENT_DIGESTS = {\n    \"md5_digest\": getattr(hashlib, \"md5\", None),\n    \"sha256_digest\": getattr(hashlib, \"sha256\", None),\n    \"blake2_256_digest\": getattr(hashlib, \"blake2b\", None),\n}\n\n\nclass upload(PyPIRCCommand):\n\n    description = \"upload binary package to PyPI\"\n\n    user_options = PyPIRCCommand.user_options + [\n        ('sign', 's', 'sign files to upload using gpg'),\n        ('identity=', 'i', 'GPG identity used to sign files'),\n    ]\n\n    boolean_options = PyPIRCCommand.boolean_options + ['sign']\n\n    def initialize_options(self):\n        PyPIRCCommand.initialize_options(self)\n        self.username = ''\n        self.password = ''\n        self.show_response = 0\n        self.sign = False\n        self.identity = None\n\n    def finalize_options(self):\n        PyPIRCCommand.finalize_options(self)\n        if self.identity and not self.sign:\n            raise DistutilsOptionError(\"Must use --sign for --identity to have meaning\")\n        config = self._read_pypirc()\n        if config != {}:\n            self.username = config['username']\n            self.password = config['password']\n            self.repository = config['repository']\n            self.realm = config['realm']\n\n        # getting the password from the distribution\n        # if previously set by the register command\n        if not self.password and self.distribution.password:\n            self.password = self.distribution.password\n\n    def run(self):\n        if not self.distribution.dist_files:\n            msg = (\n                \"Must create and upload files in one command \"\n                \"(e.g. setup.py sdist upload)\"\n            )\n            raise DistutilsOptionError(msg)\n        for command, pyversion, filename in self.distribution.dist_files:\n            self.upload_file(command, pyversion, filename)\n\n    def upload_file(self, command, pyversion, filename):  # noqa: C901\n        # Makes sure the repository URL is compliant\n        schema, netloc, url, params, query, fragments = urlparse(self.repository)\n        if params or query or fragments:\n            raise AssertionError(\"Incompatible url %s\" % self.repository)\n\n        if schema not in ('http', 'https'):\n            raise AssertionError(\"unsupported schema \" + schema)\n\n        # Sign if requested\n        if self.sign:\n            gpg_args = [\"gpg\", \"--detach-sign\", \"-a\", filename]\n            if self.identity:\n                gpg_args[2:2] = [\"--local-user\", self.identity]\n            spawn(gpg_args, dry_run=self.dry_run)\n\n        # Fill in the data - send all the meta-data in case we need to\n        # register a new release\n        f = open(filename, 'rb')\n        try:\n            content = f.read()\n        finally:\n            f.close()\n\n        meta = self.distribution.metadata\n        data = {\n            # action\n            ':action': 'file_upload',\n            'protocol_version': '1',\n            # identify release\n            'name': meta.get_name(),\n            'version': meta.get_version(),\n            # file content\n            'content': (os.path.basename(filename), content),\n            'filetype': command,\n            'pyversion': pyversion,\n            # additional meta-data\n            'metadata_version': '1.0',\n            'summary': meta.get_description(),\n            'home_page': meta.get_url(),\n            'author': meta.get_contact(),\n            'author_email': meta.get_contact_email(),\n            'license': meta.get_licence(),\n            'description': meta.get_long_description(),\n            'keywords': meta.get_keywords(),\n            'platform': meta.get_platforms(),\n            'classifiers': meta.get_classifiers(),\n            'download_url': meta.get_download_url(),\n            # PEP 314\n            'provides': meta.get_provides(),\n            'requires': meta.get_requires(),\n            'obsoletes': meta.get_obsoletes(),\n        }\n\n        data['comment'] = ''\n\n        # file content digests\n        for digest_name, digest_cons in _FILE_CONTENT_DIGESTS.items():\n            if digest_cons is None:\n                continue\n            try:\n                data[digest_name] = digest_cons(content).hexdigest()\n            except ValueError:\n                # hash digest not available or blocked by security policy\n                pass\n\n        if self.sign:\n            with open(filename + \".asc\", \"rb\") as f:\n                data['gpg_signature'] = (os.path.basename(filename) + \".asc\", f.read())\n\n        # set up the authentication\n        user_pass = (self.username + \":\" + self.password).encode('ascii')\n        # The exact encoding of the authentication string is debated.\n        # Anyway PyPI only accepts ascii for both username or password.\n        auth = \"Basic \" + standard_b64encode(user_pass).decode('ascii')\n\n        # Build up the MIME payload for the POST data\n        boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'\n        sep_boundary = b'\\r\\n--' + boundary.encode('ascii')\n        end_boundary = sep_boundary + b'--\\r\\n'\n        body = io.BytesIO()\n        for key, value in data.items():\n            title = '\\r\\nContent-Disposition: form-data; name=\"%s\"' % key\n            # handle multiple entries for the same name\n            if not isinstance(value, list):\n                value = [value]\n            for value in value:\n                if type(value) is tuple:\n                    title += '; filename=\"%s\"' % value[0]\n                    value = value[1]\n                else:\n                    value = str(value).encode('utf-8')\n                body.write(sep_boundary)\n                body.write(title.encode('utf-8'))\n                body.write(b\"\\r\\n\\r\\n\")\n                body.write(value)\n        body.write(end_boundary)\n        body = body.getvalue()\n\n        msg = \"Submitting {} to {}\".format(filename, self.repository)\n        self.announce(msg, log.INFO)\n\n        # build the Request\n        headers = {\n            'Content-type': 'multipart/form-data; boundary=%s' % boundary,\n            'Content-length': str(len(body)),\n            'Authorization': auth,\n        }\n\n        request = Request(self.repository, data=body, headers=headers)\n        # send the data\n        try:\n            result = urlopen(request)\n            status = result.getcode()\n            reason = result.msg\n        except HTTPError as e:\n            status = e.code\n            reason = e.msg\n        except OSError as e:\n            self.announce(str(e), log.ERROR)\n            raise\n\n        if status == 200:\n            self.announce('Server response ({}): {}'.format(status, reason), log.INFO)\n            if self.show_response:\n                text = self._read_pypi_response(result)\n                msg = '\\n'.join(('-' * 75, text, '-' * 75))\n                self.announce(msg, log.INFO)\n        else:\n            msg = 'Upload failed ({}): {}'.format(status, reason)\n            self.announce(msg, log.ERROR)\n            raise DistutilsError(msg)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/config.py",
    "content": "\"\"\"distutils.pypirc\n\nProvides the PyPIRCCommand class, the base class for the command classes\nthat uses .pypirc in the distutils.command package.\n\"\"\"\nimport os\nfrom configparser import RawConfigParser\n\nfrom distutils.cmd import Command\n\nDEFAULT_PYPIRC = \"\"\"\\\n[distutils]\nindex-servers =\n    pypi\n\n[pypi]\nusername:%s\npassword:%s\n\"\"\"\n\n\nclass PyPIRCCommand(Command):\n    \"\"\"Base command that knows how to handle the .pypirc file\"\"\"\n\n    DEFAULT_REPOSITORY = 'https://upload.pypi.org/legacy/'\n    DEFAULT_REALM = 'pypi'\n    repository = None\n    realm = None\n\n    user_options = [\n        ('repository=', 'r', \"url of repository [default: %s]\" % DEFAULT_REPOSITORY),\n        ('show-response', None, 'display full response text from server'),\n    ]\n\n    boolean_options = ['show-response']\n\n    def _get_rc_file(self):\n        \"\"\"Returns rc file path.\"\"\"\n        return os.path.join(os.path.expanduser('~'), '.pypirc')\n\n    def _store_pypirc(self, username, password):\n        \"\"\"Creates a default .pypirc file.\"\"\"\n        rc = self._get_rc_file()\n        with os.fdopen(os.open(rc, os.O_CREAT | os.O_WRONLY, 0o600), 'w') as f:\n            f.write(DEFAULT_PYPIRC % (username, password))\n\n    def _read_pypirc(self):  # noqa: C901\n        \"\"\"Reads the .pypirc file.\"\"\"\n        rc = self._get_rc_file()\n        if os.path.exists(rc):\n            self.announce('Using PyPI login from %s' % rc)\n            repository = self.repository or self.DEFAULT_REPOSITORY\n\n            config = RawConfigParser()\n            config.read(rc)\n            sections = config.sections()\n            if 'distutils' in sections:\n                # let's get the list of servers\n                index_servers = config.get('distutils', 'index-servers')\n                _servers = [\n                    server.strip()\n                    for server in index_servers.split('\\n')\n                    if server.strip() != ''\n                ]\n                if _servers == []:\n                    # nothing set, let's try to get the default pypi\n                    if 'pypi' in sections:\n                        _servers = ['pypi']\n                    else:\n                        # the file is not properly defined, returning\n                        # an empty dict\n                        return {}\n                for server in _servers:\n                    current = {'server': server}\n                    current['username'] = config.get(server, 'username')\n\n                    # optional params\n                    for key, default in (\n                        ('repository', self.DEFAULT_REPOSITORY),\n                        ('realm', self.DEFAULT_REALM),\n                        ('password', None),\n                    ):\n                        if config.has_option(server, key):\n                            current[key] = config.get(server, key)\n                        else:\n                            current[key] = default\n\n                    # work around people having \"repository\" for the \"pypi\"\n                    # section of their config set to the HTTP (rather than\n                    # HTTPS) URL\n                    if server == 'pypi' and repository in (\n                        self.DEFAULT_REPOSITORY,\n                        'pypi',\n                    ):\n                        current['repository'] = self.DEFAULT_REPOSITORY\n                        return current\n\n                    if (\n                        current['server'] == repository\n                        or current['repository'] == repository\n                    ):\n                        return current\n            elif 'server-login' in sections:\n                # old format\n                server = 'server-login'\n                if config.has_option(server, 'repository'):\n                    repository = config.get(server, 'repository')\n                else:\n                    repository = self.DEFAULT_REPOSITORY\n                return {\n                    'username': config.get(server, 'username'),\n                    'password': config.get(server, 'password'),\n                    'repository': repository,\n                    'server': server,\n                    'realm': self.DEFAULT_REALM,\n                }\n\n        return {}\n\n    def _read_pypi_response(self, response):\n        \"\"\"Read and decode a PyPI HTTP response.\"\"\"\n        import cgi\n\n        content_type = response.getheader('content-type', 'text/plain')\n        encoding = cgi.parse_header(content_type)[1].get('charset', 'ascii')\n        return response.read().decode(encoding)\n\n    def initialize_options(self):\n        \"\"\"Initialize options.\"\"\"\n        self.repository = None\n        self.realm = None\n        self.show_response = 0\n\n    def finalize_options(self):\n        \"\"\"Finalizes options.\"\"\"\n        if self.repository is None:\n            self.repository = self.DEFAULT_REPOSITORY\n        if self.realm is None:\n            self.realm = self.DEFAULT_REALM\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/core.py",
    "content": "\"\"\"distutils.core\n\nThe only module that needs to be imported to use the Distutils; provides\nthe 'setup' function (which is to be called from the setup script).  Also\nindirectly provides the Distribution and Command classes, although they are\nreally defined in distutils.dist and distutils.cmd.\n\"\"\"\n\nimport os\nimport sys\nimport tokenize\n\nfrom distutils.debug import DEBUG\nfrom distutils.errors import (\n    DistutilsSetupError,\n    DistutilsError,\n    CCompilerError,\n    DistutilsArgError,\n)\n\n# Mainly import these so setup scripts can \"from distutils.core import\" them.\nfrom distutils.dist import Distribution\nfrom distutils.cmd import Command\nfrom distutils.config import PyPIRCCommand\nfrom distutils.extension import Extension\n\n\n__all__ = ['Distribution', 'Command', 'PyPIRCCommand', 'Extension', 'setup']\n\n# This is a barebones help message generated displayed when the user\n# runs the setup script with no arguments at all.  More useful help\n# is generated with various --help options: global help, list commands,\n# and per-command help.\nUSAGE = \"\"\"\\\nusage: %(script)s [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]\n   or: %(script)s --help [cmd1 cmd2 ...]\n   or: %(script)s --help-commands\n   or: %(script)s cmd --help\n\"\"\"\n\n\ndef gen_usage(script_name):\n    script = os.path.basename(script_name)\n    return USAGE % locals()\n\n\n# Some mild magic to control the behaviour of 'setup()' from 'run_setup()'.\n_setup_stop_after = None\n_setup_distribution = None\n\n# Legal keyword arguments for the setup() function\nsetup_keywords = (\n    'distclass',\n    'script_name',\n    'script_args',\n    'options',\n    'name',\n    'version',\n    'author',\n    'author_email',\n    'maintainer',\n    'maintainer_email',\n    'url',\n    'license',\n    'description',\n    'long_description',\n    'keywords',\n    'platforms',\n    'classifiers',\n    'download_url',\n    'requires',\n    'provides',\n    'obsoletes',\n)\n\n# Legal keyword arguments for the Extension constructor\nextension_keywords = (\n    'name',\n    'sources',\n    'include_dirs',\n    'define_macros',\n    'undef_macros',\n    'library_dirs',\n    'libraries',\n    'runtime_library_dirs',\n    'extra_objects',\n    'extra_compile_args',\n    'extra_link_args',\n    'swig_opts',\n    'export_symbols',\n    'depends',\n    'language',\n)\n\n\ndef setup(**attrs):  # noqa: C901\n    \"\"\"The gateway to the Distutils: do everything your setup script needs\n    to do, in a highly flexible and user-driven way.  Briefly: create a\n    Distribution instance; find and parse config files; parse the command\n    line; run each Distutils command found there, customized by the options\n    supplied to 'setup()' (as keyword arguments), in config files, and on\n    the command line.\n\n    The Distribution instance might be an instance of a class supplied via\n    the 'distclass' keyword argument to 'setup'; if no such class is\n    supplied, then the Distribution class (in dist.py) is instantiated.\n    All other arguments to 'setup' (except for 'cmdclass') are used to set\n    attributes of the Distribution instance.\n\n    The 'cmdclass' argument, if supplied, is a dictionary mapping command\n    names to command classes.  Each command encountered on the command line\n    will be turned into a command class, which is in turn instantiated; any\n    class found in 'cmdclass' is used in place of the default, which is\n    (for command 'foo_bar') class 'foo_bar' in module\n    'distutils.command.foo_bar'.  The command class must provide a\n    'user_options' attribute which is a list of option specifiers for\n    'distutils.fancy_getopt'.  Any command-line options between the current\n    and the next command are used to set attributes of the current command\n    object.\n\n    When the entire command-line has been successfully parsed, calls the\n    'run()' method on each command object in turn.  This method will be\n    driven entirely by the Distribution object (which each command object\n    has a reference to, thanks to its constructor), and the\n    command-specific options that became attributes of each command\n    object.\n    \"\"\"\n\n    global _setup_stop_after, _setup_distribution\n\n    # Determine the distribution class -- either caller-supplied or\n    # our Distribution (see below).\n    klass = attrs.get('distclass')\n    if klass:\n        del attrs['distclass']\n    else:\n        klass = Distribution\n\n    if 'script_name' not in attrs:\n        attrs['script_name'] = os.path.basename(sys.argv[0])\n    if 'script_args' not in attrs:\n        attrs['script_args'] = sys.argv[1:]\n\n    # Create the Distribution instance, using the remaining arguments\n    # (ie. everything except distclass) to initialize it\n    try:\n        _setup_distribution = dist = klass(attrs)\n    except DistutilsSetupError as msg:\n        if 'name' not in attrs:\n            raise SystemExit(\"error in setup command: %s\" % msg)\n        else:\n            raise SystemExit(\"error in {} setup command: {}\".format(attrs['name'], msg))\n\n    if _setup_stop_after == \"init\":\n        return dist\n\n    # Find and parse the config file(s): they will override options from\n    # the setup script, but be overridden by the command line.\n    dist.parse_config_files()\n\n    if DEBUG:\n        print(\"options (after parsing config files):\")\n        dist.dump_option_dicts()\n\n    if _setup_stop_after == \"config\":\n        return dist\n\n    # Parse the command line and override config files; any\n    # command-line errors are the end user's fault, so turn them into\n    # SystemExit to suppress tracebacks.\n    try:\n        ok = dist.parse_command_line()\n    except DistutilsArgError as msg:\n        raise SystemExit(gen_usage(dist.script_name) + \"\\nerror: %s\" % msg)\n\n    if DEBUG:\n        print(\"options (after parsing command line):\")\n        dist.dump_option_dicts()\n\n    if _setup_stop_after == \"commandline\":\n        return dist\n\n    # And finally, run all the commands found on the command line.\n    if ok:\n        return run_commands(dist)\n\n    return dist\n\n\n# setup ()\n\n\ndef run_commands(dist):\n    \"\"\"Given a Distribution object run all the commands,\n    raising ``SystemExit`` errors in the case of failure.\n\n    This function assumes that either ``sys.argv`` or ``dist.script_args``\n    is already set accordingly.\n    \"\"\"\n    try:\n        dist.run_commands()\n    except KeyboardInterrupt:\n        raise SystemExit(\"interrupted\")\n    except OSError as exc:\n        if DEBUG:\n            sys.stderr.write(\"error: {}\\n\".format(exc))\n            raise\n        else:\n            raise SystemExit(\"error: {}\".format(exc))\n\n    except (DistutilsError, CCompilerError) as msg:\n        if DEBUG:\n            raise\n        else:\n            raise SystemExit(\"error: \" + str(msg))\n\n    return dist\n\n\ndef run_setup(script_name, script_args=None, stop_after=\"run\"):\n    \"\"\"Run a setup script in a somewhat controlled environment, and\n    return the Distribution instance that drives things.  This is useful\n    if you need to find out the distribution meta-data (passed as\n    keyword args from 'script' to 'setup()', or the contents of the\n    config files or command-line.\n\n    'script_name' is a file that will be read and run with 'exec()';\n    'sys.argv[0]' will be replaced with 'script' for the duration of the\n    call.  'script_args' is a list of strings; if supplied,\n    'sys.argv[1:]' will be replaced by 'script_args' for the duration of\n    the call.\n\n    'stop_after' tells 'setup()' when to stop processing; possible\n    values:\n      init\n        stop after the Distribution instance has been created and\n        populated with the keyword arguments to 'setup()'\n      config\n        stop after config files have been parsed (and their data\n        stored in the Distribution instance)\n      commandline\n        stop after the command-line ('sys.argv[1:]' or 'script_args')\n        have been parsed (and the data stored in the Distribution)\n      run [default]\n        stop after all commands have been run (the same as if 'setup()'\n        had been called in the usual way\n\n    Returns the Distribution instance, which provides all information\n    used to drive the Distutils.\n    \"\"\"\n    if stop_after not in ('init', 'config', 'commandline', 'run'):\n        raise ValueError(\"invalid value for 'stop_after': {!r}\".format(stop_after))\n\n    global _setup_stop_after, _setup_distribution\n    _setup_stop_after = stop_after\n\n    save_argv = sys.argv.copy()\n    g = {'__file__': script_name, '__name__': '__main__'}\n    try:\n        try:\n            sys.argv[0] = script_name\n            if script_args is not None:\n                sys.argv[1:] = script_args\n            # tokenize.open supports automatic encoding detection\n            with tokenize.open(script_name) as f:\n                code = f.read().replace(r'\\r\\n', r'\\n')\n                exec(code, g)\n        finally:\n            sys.argv = save_argv\n            _setup_stop_after = None\n    except SystemExit:\n        # Hmm, should we do something if exiting with a non-zero code\n        # (ie. error)?\n        pass\n\n    if _setup_distribution is None:\n        raise RuntimeError(\n            (\n                \"'distutils.core.setup()' was never called -- \"\n                \"perhaps '%s' is not a Distutils setup script?\"\n            )\n            % script_name\n        )\n\n    # I wonder if the setup script's namespace -- g and l -- would be of\n    # any interest to callers?\n    # print \"_setup_distribution:\", _setup_distribution\n    return _setup_distribution\n\n\n# run_setup ()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/cygwinccompiler.py",
    "content": "\"\"\"distutils.cygwinccompiler\n\nProvides the CygwinCCompiler class, a subclass of UnixCCompiler that\nhandles the Cygwin port of the GNU C compiler to Windows.  It also contains\nthe Mingw32CCompiler class which handles the mingw32 port of GCC (same as\ncygwin in no-cygwin mode).\n\"\"\"\n\nimport os\nimport sys\nimport copy\nimport shlex\nimport warnings\nfrom subprocess import check_output\n\nfrom distutils.unixccompiler import UnixCCompiler\nfrom distutils.file_util import write_file\nfrom distutils.errors import (\n    DistutilsExecError,\n    DistutilsPlatformError,\n    CCompilerError,\n    CompileError,\n)\nfrom distutils.version import LooseVersion, suppress_known_deprecation\n\n\ndef get_msvcr():\n    \"\"\"Include the appropriate MSVC runtime library if Python was built\n    with MSVC 7.0 or later.\n    \"\"\"\n    msc_pos = sys.version.find('MSC v.')\n    if msc_pos != -1:\n        msc_ver = sys.version[msc_pos + 6 : msc_pos + 10]\n        if msc_ver == '1300':\n            # MSVC 7.0\n            return ['msvcr70']\n        elif msc_ver == '1310':\n            # MSVC 7.1\n            return ['msvcr71']\n        elif msc_ver == '1400':\n            # VS2005 / MSVC 8.0\n            return ['msvcr80']\n        elif msc_ver == '1500':\n            # VS2008 / MSVC 9.0\n            return ['msvcr90']\n        elif msc_ver == '1600':\n            # VS2010 / MSVC 10.0\n            return ['msvcr100']\n        elif msc_ver == '1700':\n            # VS2012 / MSVC 11.0\n            return ['msvcr110']\n        elif msc_ver == '1800':\n            # VS2013 / MSVC 12.0\n            return ['msvcr120']\n        elif 1900 <= int(msc_ver) < 2000:\n            # VS2015 / MSVC 14.0\n            return ['ucrt', 'vcruntime140']\n        else:\n            raise ValueError(\"Unknown MS Compiler version %s \" % msc_ver)\n\n\n_runtime_library_dirs_msg = (\n    \"Unable to set runtime library search path on Windows, \"\n    \"usually indicated by `runtime_library_dirs` parameter to Extension\"\n)\n\n\nclass CygwinCCompiler(UnixCCompiler):\n    \"\"\"Handles the Cygwin port of the GNU C compiler to Windows.\"\"\"\n\n    compiler_type = 'cygwin'\n    obj_extension = \".o\"\n    static_lib_extension = \".a\"\n    shared_lib_extension = \".dll.a\"\n    dylib_lib_extension = \".dll\"\n    static_lib_format = \"lib%s%s\"\n    shared_lib_format = \"lib%s%s\"\n    dylib_lib_format = \"cyg%s%s\"\n    exe_extension = \".exe\"\n\n    def __init__(self, verbose=0, dry_run=0, force=0):\n\n        super().__init__(verbose, dry_run, force)\n\n        status, details = check_config_h()\n        self.debug_print(\n            \"Python's GCC status: {} (details: {})\".format(status, details)\n        )\n        if status is not CONFIG_H_OK:\n            self.warn(\n                \"Python's pyconfig.h doesn't seem to support your compiler. \"\n                \"Reason: %s. \"\n                \"Compiling may fail because of undefined preprocessor macros.\" % details\n            )\n\n        self.cc = os.environ.get('CC', 'gcc')\n        self.cxx = os.environ.get('CXX', 'g++')\n\n        self.linker_dll = self.cc\n        shared_option = \"-shared\"\n\n        self.set_executables(\n            compiler='%s -mcygwin -O -Wall' % self.cc,\n            compiler_so='%s -mcygwin -mdll -O -Wall' % self.cc,\n            compiler_cxx='%s -mcygwin -O -Wall' % self.cxx,\n            linker_exe='%s -mcygwin' % self.cc,\n            linker_so=('{} -mcygwin {}'.format(self.linker_dll, shared_option)),\n        )\n\n        # Include the appropriate MSVC runtime library if Python was built\n        # with MSVC 7.0 or later.\n        self.dll_libraries = get_msvcr()\n\n    @property\n    def gcc_version(self):\n        # Older numpy dependend on this existing to check for ancient\n        # gcc versions. This doesn't make much sense with clang etc so\n        # just hardcode to something recent.\n        # https://github.com/numpy/numpy/pull/20333\n        warnings.warn(\n            \"gcc_version attribute of CygwinCCompiler is deprecated. \"\n            \"Instead of returning actual gcc version a fixed value 11.2.0 is returned.\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        with suppress_known_deprecation():\n            return LooseVersion(\"11.2.0\")\n\n    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):\n        \"\"\"Compiles the source by spawning GCC and windres if needed.\"\"\"\n        if ext == '.rc' or ext == '.res':\n            # gcc needs '.res' and '.rc' compiled to object files !!!\n            try:\n                self.spawn([\"windres\", \"-i\", src, \"-o\", obj])\n            except DistutilsExecError as msg:\n                raise CompileError(msg)\n        else:  # for other files use the C-compiler\n            try:\n                self.spawn(\n                    self.compiler_so + cc_args + [src, '-o', obj] + extra_postargs\n                )\n            except DistutilsExecError as msg:\n                raise CompileError(msg)\n\n    def link(\n        self,\n        target_desc,\n        objects,\n        output_filename,\n        output_dir=None,\n        libraries=None,\n        library_dirs=None,\n        runtime_library_dirs=None,\n        export_symbols=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        build_temp=None,\n        target_lang=None,\n    ):\n        \"\"\"Link the objects.\"\"\"\n        # use separate copies, so we can modify the lists\n        extra_preargs = copy.copy(extra_preargs or [])\n        libraries = copy.copy(libraries or [])\n        objects = copy.copy(objects or [])\n\n        if runtime_library_dirs:\n            self.warn(_runtime_library_dirs_msg)\n\n        # Additional libraries\n        libraries.extend(self.dll_libraries)\n\n        # handle export symbols by creating a def-file\n        # with executables this only works with gcc/ld as linker\n        if (export_symbols is not None) and (\n            target_desc != self.EXECUTABLE or self.linker_dll == \"gcc\"\n        ):\n            # (The linker doesn't do anything if output is up-to-date.\n            # So it would probably better to check if we really need this,\n            # but for this we had to insert some unchanged parts of\n            # UnixCCompiler, and this is not what we want.)\n\n            # we want to put some files in the same directory as the\n            # object files are, build_temp doesn't help much\n            # where are the object files\n            temp_dir = os.path.dirname(objects[0])\n            # name of dll to give the helper files the same base name\n            (dll_name, dll_extension) = os.path.splitext(\n                os.path.basename(output_filename)\n            )\n\n            # generate the filenames for these files\n            def_file = os.path.join(temp_dir, dll_name + \".def\")\n\n            # Generate .def file\n            contents = [\"LIBRARY %s\" % os.path.basename(output_filename), \"EXPORTS\"]\n            for sym in export_symbols:\n                contents.append(sym)\n            self.execute(write_file, (def_file, contents), \"writing %s\" % def_file)\n\n            # next add options for def-file\n\n            # for gcc/ld the def-file is specified as any object files\n            objects.append(def_file)\n\n        # end: if ((export_symbols is not None) and\n        #        (target_desc != self.EXECUTABLE or self.linker_dll == \"gcc\")):\n\n        # who wants symbols and a many times larger output file\n        # should explicitly switch the debug mode on\n        # otherwise we let ld strip the output file\n        # (On my machine: 10KiB < stripped_file < ??100KiB\n        #   unstripped_file = stripped_file + XXX KiB\n        #  ( XXX=254 for a typical python extension))\n        if not debug:\n            extra_preargs.append(\"-s\")\n\n        UnixCCompiler.link(\n            self,\n            target_desc,\n            objects,\n            output_filename,\n            output_dir,\n            libraries,\n            library_dirs,\n            runtime_library_dirs,\n            None,  # export_symbols, we do this in our def-file\n            debug,\n            extra_preargs,\n            extra_postargs,\n            build_temp,\n            target_lang,\n        )\n\n    def runtime_library_dir_option(self, dir):\n        # cygwin doesn't support rpath. While in theory we could error\n        # out like MSVC does, code might expect it to work like on Unix, so\n        # just warn and hope for the best.\n        self.warn(_runtime_library_dirs_msg)\n        return []\n\n    # -- Miscellaneous methods -----------------------------------------\n\n    def _make_out_path(self, output_dir, strip_dir, src_name):\n        # use normcase to make sure '.rc' is really '.rc' and not '.RC'\n        norm_src_name = os.path.normcase(src_name)\n        return super()._make_out_path(output_dir, strip_dir, norm_src_name)\n\n    @property\n    def out_extensions(self):\n        \"\"\"\n        Add support for rc and res files.\n        \"\"\"\n        return {\n            **super().out_extensions,\n            **{ext: ext + self.obj_extension for ext in ('.res', '.rc')},\n        }\n\n\n# the same as cygwin plus some additional parameters\nclass Mingw32CCompiler(CygwinCCompiler):\n    \"\"\"Handles the Mingw32 port of the GNU C compiler to Windows.\"\"\"\n\n    compiler_type = 'mingw32'\n\n    def __init__(self, verbose=0, dry_run=0, force=0):\n\n        super().__init__(verbose, dry_run, force)\n\n        shared_option = \"-shared\"\n\n        if is_cygwincc(self.cc):\n            raise CCompilerError('Cygwin gcc cannot be used with --compiler=mingw32')\n\n        self.set_executables(\n            compiler='%s -O -Wall' % self.cc,\n            compiler_so='%s -mdll -O -Wall' % self.cc,\n            compiler_cxx='%s -O -Wall' % self.cxx,\n            linker_exe='%s' % self.cc,\n            linker_so='{} {}'.format(self.linker_dll, shared_option),\n        )\n\n        # Maybe we should also append -mthreads, but then the finished\n        # dlls need another dll (mingwm10.dll see Mingw32 docs)\n        # (-mthreads: Support thread-safe exception handling on `Mingw32')\n\n        # no additional libraries needed\n        self.dll_libraries = []\n\n        # Include the appropriate MSVC runtime library if Python was built\n        # with MSVC 7.0 or later.\n        self.dll_libraries = get_msvcr()\n\n    def runtime_library_dir_option(self, dir):\n        raise DistutilsPlatformError(_runtime_library_dirs_msg)\n\n\n# Because these compilers aren't configured in Python's pyconfig.h file by\n# default, we should at least warn the user if he is using an unmodified\n# version.\n\nCONFIG_H_OK = \"ok\"\nCONFIG_H_NOTOK = \"not ok\"\nCONFIG_H_UNCERTAIN = \"uncertain\"\n\n\ndef check_config_h():\n    \"\"\"Check if the current Python installation appears amenable to building\n    extensions with GCC.\n\n    Returns a tuple (status, details), where 'status' is one of the following\n    constants:\n\n    - CONFIG_H_OK: all is well, go ahead and compile\n    - CONFIG_H_NOTOK: doesn't look good\n    - CONFIG_H_UNCERTAIN: not sure -- unable to read pyconfig.h\n\n    'details' is a human-readable string explaining the situation.\n\n    Note there are two ways to conclude \"OK\": either 'sys.version' contains\n    the string \"GCC\" (implying that this Python was built with GCC), or the\n    installed \"pyconfig.h\" contains the string \"__GNUC__\".\n    \"\"\"\n\n    # XXX since this function also checks sys.version, it's not strictly a\n    # \"pyconfig.h\" check -- should probably be renamed...\n\n    from distutils import sysconfig\n\n    # if sys.version contains GCC then python was compiled with GCC, and the\n    # pyconfig.h file should be OK\n    if \"GCC\" in sys.version:\n        return CONFIG_H_OK, \"sys.version mentions 'GCC'\"\n\n    # Clang would also work\n    if \"Clang\" in sys.version:\n        return CONFIG_H_OK, \"sys.version mentions 'Clang'\"\n\n    # let's see if __GNUC__ is mentioned in python.h\n    fn = sysconfig.get_config_h_filename()\n    try:\n        config_h = open(fn)\n        try:\n            if \"__GNUC__\" in config_h.read():\n                return CONFIG_H_OK, \"'%s' mentions '__GNUC__'\" % fn\n            else:\n                return CONFIG_H_NOTOK, \"'%s' does not mention '__GNUC__'\" % fn\n        finally:\n            config_h.close()\n    except OSError as exc:\n        return (CONFIG_H_UNCERTAIN, \"couldn't read '{}': {}\".format(fn, exc.strerror))\n\n\ndef is_cygwincc(cc):\n    '''Try to determine if the compiler that would be used is from cygwin.'''\n    out_string = check_output(shlex.split(cc) + ['-dumpmachine'])\n    return out_string.strip().endswith(b'cygwin')\n\n\nget_versions = None\n\"\"\"\nA stand-in for the previous get_versions() function to prevent failures\nwhen monkeypatched. See pypa/setuptools#2969.\n\"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/debug.py",
    "content": "import os\n\n# If DISTUTILS_DEBUG is anything other than the empty string, we run in\n# debug mode.\nDEBUG = os.environ.get('DISTUTILS_DEBUG')\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/dep_util.py",
    "content": "\"\"\"distutils.dep_util\n\nUtility functions for simple, timestamp-based dependency of files\nand groups of files; also, function based entirely on such\ntimestamp dependency analysis.\"\"\"\n\nimport os\nfrom distutils.errors import DistutilsFileError\n\n\ndef newer(source, target):\n    \"\"\"Return true if 'source' exists and is more recently modified than\n    'target', or if 'source' exists and 'target' doesn't.  Return false if\n    both exist and 'target' is the same age or younger than 'source'.\n    Raise DistutilsFileError if 'source' does not exist.\n    \"\"\"\n    if not os.path.exists(source):\n        raise DistutilsFileError(\"file '%s' does not exist\" % os.path.abspath(source))\n    if not os.path.exists(target):\n        return 1\n\n    from stat import ST_MTIME\n\n    mtime1 = os.stat(source)[ST_MTIME]\n    mtime2 = os.stat(target)[ST_MTIME]\n\n    return mtime1 > mtime2\n\n\n# newer ()\n\n\ndef newer_pairwise(sources, targets):\n    \"\"\"Walk two filename lists in parallel, testing if each source is newer\n    than its corresponding target.  Return a pair of lists (sources,\n    targets) where source is newer than target, according to the semantics\n    of 'newer()'.\n    \"\"\"\n    if len(sources) != len(targets):\n        raise ValueError(\"'sources' and 'targets' must be same length\")\n\n    # build a pair of lists (sources, targets) where  source is newer\n    n_sources = []\n    n_targets = []\n    for i in range(len(sources)):\n        if newer(sources[i], targets[i]):\n            n_sources.append(sources[i])\n            n_targets.append(targets[i])\n\n    return (n_sources, n_targets)\n\n\n# newer_pairwise ()\n\n\ndef newer_group(sources, target, missing='error'):\n    \"\"\"Return true if 'target' is out-of-date with respect to any file\n    listed in 'sources'.  In other words, if 'target' exists and is newer\n    than every file in 'sources', return false; otherwise return true.\n    'missing' controls what we do when a source file is missing; the\n    default (\"error\") is to blow up with an OSError from inside 'stat()';\n    if it is \"ignore\", we silently drop any missing source files; if it is\n    \"newer\", any missing source files make us assume that 'target' is\n    out-of-date (this is handy in \"dry-run\" mode: it'll make you pretend to\n    carry out commands that wouldn't work because inputs are missing, but\n    that doesn't matter because you're not actually going to run the\n    commands).\n    \"\"\"\n    # If the target doesn't even exist, then it's definitely out-of-date.\n    if not os.path.exists(target):\n        return 1\n\n    # Otherwise we have to find out the hard way: if *any* source file\n    # is more recent than 'target', then 'target' is out-of-date and\n    # we can immediately return true.  If we fall through to the end\n    # of the loop, then 'target' is up-to-date and we return false.\n    from stat import ST_MTIME\n\n    target_mtime = os.stat(target)[ST_MTIME]\n    for source in sources:\n        if not os.path.exists(source):\n            if missing == 'error':  # blow up when we stat() the file\n                pass\n            elif missing == 'ignore':  # missing source dropped from\n                continue  # target's dependency list\n            elif missing == 'newer':  # missing source means target is\n                return 1  # out-of-date\n\n        source_mtime = os.stat(source)[ST_MTIME]\n        if source_mtime > target_mtime:\n            return 1\n    else:\n        return 0\n\n\n# newer_group ()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/dir_util.py",
    "content": "\"\"\"distutils.dir_util\n\nUtility functions for manipulating directories and directory trees.\"\"\"\n\nimport os\nimport errno\nfrom distutils.errors import DistutilsInternalError, DistutilsFileError\nfrom distutils import log\n\n# cache for by mkpath() -- in addition to cheapening redundant calls,\n# eliminates redundant \"creating /foo/bar/baz\" messages in dry-run mode\n_path_created = {}\n\n\ndef mkpath(name, mode=0o777, verbose=1, dry_run=0):  # noqa: C901\n    \"\"\"Create a directory and any missing ancestor directories.\n\n    If the directory already exists (or if 'name' is the empty string, which\n    means the current directory, which of course exists), then do nothing.\n    Raise DistutilsFileError if unable to create some directory along the way\n    (eg. some sub-path exists, but is a file rather than a directory).\n    If 'verbose' is true, print a one-line summary of each mkdir to stdout.\n    Return the list of directories actually created.\n\n    os.makedirs is not used because:\n\n    a) It's new to Python 1.5.2, and\n    b) it blows up if the directory already exists (in which case it should\n       silently succeed).\n    \"\"\"\n\n    global _path_created\n\n    # Detect a common bug -- name is None\n    if not isinstance(name, str):\n        raise DistutilsInternalError(\n            \"mkpath: 'name' must be a string (got {!r})\".format(name)\n        )\n\n    # XXX what's the better way to handle verbosity? print as we create\n    # each directory in the path (the current behaviour), or only announce\n    # the creation of the whole path? (quite easy to do the latter since\n    # we're not using a recursive algorithm)\n\n    name = os.path.normpath(name)\n    created_dirs = []\n    if os.path.isdir(name) or name == '':\n        return created_dirs\n    if _path_created.get(os.path.abspath(name)):\n        return created_dirs\n\n    (head, tail) = os.path.split(name)\n    tails = [tail]  # stack of lone dirs to create\n\n    while head and tail and not os.path.isdir(head):\n        (head, tail) = os.path.split(head)\n        tails.insert(0, tail)  # push next higher dir onto stack\n\n    # now 'head' contains the deepest directory that already exists\n    # (that is, the child of 'head' in 'name' is the highest directory\n    # that does *not* exist)\n    for d in tails:\n        # print \"head = %s, d = %s: \" % (head, d),\n        head = os.path.join(head, d)\n        abs_head = os.path.abspath(head)\n\n        if _path_created.get(abs_head):\n            continue\n\n        if verbose >= 1:\n            log.info(\"creating %s\", head)\n\n        if not dry_run:\n            try:\n                os.mkdir(head, mode)\n            except OSError as exc:\n                if not (exc.errno == errno.EEXIST and os.path.isdir(head)):\n                    raise DistutilsFileError(\n                        \"could not create '{}': {}\".format(head, exc.args[-1])\n                    )\n            created_dirs.append(head)\n\n        _path_created[abs_head] = 1\n    return created_dirs\n\n\ndef create_tree(base_dir, files, mode=0o777, verbose=1, dry_run=0):\n    \"\"\"Create all the empty directories under 'base_dir' needed to put 'files'\n    there.\n\n    'base_dir' is just the name of a directory which doesn't necessarily\n    exist yet; 'files' is a list of filenames to be interpreted relative to\n    'base_dir'.  'base_dir' + the directory portion of every file in 'files'\n    will be created if it doesn't already exist.  'mode', 'verbose' and\n    'dry_run' flags are as for 'mkpath()'.\n    \"\"\"\n    # First get the list of directories to create\n    need_dir = set()\n    for file in files:\n        need_dir.add(os.path.join(base_dir, os.path.dirname(file)))\n\n    # Now create them\n    for dir in sorted(need_dir):\n        mkpath(dir, mode, verbose=verbose, dry_run=dry_run)\n\n\ndef copy_tree(  # noqa: C901\n    src,\n    dst,\n    preserve_mode=1,\n    preserve_times=1,\n    preserve_symlinks=0,\n    update=0,\n    verbose=1,\n    dry_run=0,\n):\n    \"\"\"Copy an entire directory tree 'src' to a new location 'dst'.\n\n    Both 'src' and 'dst' must be directory names.  If 'src' is not a\n    directory, raise DistutilsFileError.  If 'dst' does not exist, it is\n    created with 'mkpath()'.  The end result of the copy is that every\n    file in 'src' is copied to 'dst', and directories under 'src' are\n    recursively copied to 'dst'.  Return the list of files that were\n    copied or might have been copied, using their output name.  The\n    return value is unaffected by 'update' or 'dry_run': it is simply\n    the list of all files under 'src', with the names changed to be\n    under 'dst'.\n\n    'preserve_mode' and 'preserve_times' are the same as for\n    'copy_file'; note that they only apply to regular files, not to\n    directories.  If 'preserve_symlinks' is true, symlinks will be\n    copied as symlinks (on platforms that support them!); otherwise\n    (the default), the destination of the symlink will be copied.\n    'update' and 'verbose' are the same as for 'copy_file'.\n    \"\"\"\n    from distutils.file_util import copy_file\n\n    if not dry_run and not os.path.isdir(src):\n        raise DistutilsFileError(\"cannot copy tree '%s': not a directory\" % src)\n    try:\n        names = os.listdir(src)\n    except OSError as e:\n        if dry_run:\n            names = []\n        else:\n            raise DistutilsFileError(\n                \"error listing files in '{}': {}\".format(src, e.strerror)\n            )\n\n    if not dry_run:\n        mkpath(dst, verbose=verbose)\n\n    outputs = []\n\n    for n in names:\n        src_name = os.path.join(src, n)\n        dst_name = os.path.join(dst, n)\n\n        if n.startswith('.nfs'):\n            # skip NFS rename files\n            continue\n\n        if preserve_symlinks and os.path.islink(src_name):\n            link_dest = os.readlink(src_name)\n            if verbose >= 1:\n                log.info(\"linking %s -> %s\", dst_name, link_dest)\n            if not dry_run:\n                os.symlink(link_dest, dst_name)\n            outputs.append(dst_name)\n\n        elif os.path.isdir(src_name):\n            outputs.extend(\n                copy_tree(\n                    src_name,\n                    dst_name,\n                    preserve_mode,\n                    preserve_times,\n                    preserve_symlinks,\n                    update,\n                    verbose=verbose,\n                    dry_run=dry_run,\n                )\n            )\n        else:\n            copy_file(\n                src_name,\n                dst_name,\n                preserve_mode,\n                preserve_times,\n                update,\n                verbose=verbose,\n                dry_run=dry_run,\n            )\n            outputs.append(dst_name)\n\n    return outputs\n\n\ndef _build_cmdtuple(path, cmdtuples):\n    \"\"\"Helper for remove_tree().\"\"\"\n    for f in os.listdir(path):\n        real_f = os.path.join(path, f)\n        if os.path.isdir(real_f) and not os.path.islink(real_f):\n            _build_cmdtuple(real_f, cmdtuples)\n        else:\n            cmdtuples.append((os.remove, real_f))\n    cmdtuples.append((os.rmdir, path))\n\n\ndef remove_tree(directory, verbose=1, dry_run=0):\n    \"\"\"Recursively remove an entire directory tree.\n\n    Any errors are ignored (apart from being reported to stdout if 'verbose'\n    is true).\n    \"\"\"\n    global _path_created\n\n    if verbose >= 1:\n        log.info(\"removing '%s' (and everything under it)\", directory)\n    if dry_run:\n        return\n    cmdtuples = []\n    _build_cmdtuple(directory, cmdtuples)\n    for cmd in cmdtuples:\n        try:\n            cmd[0](cmd[1])\n            # remove dir from cache if it's already there\n            abspath = os.path.abspath(cmd[1])\n            if abspath in _path_created:\n                del _path_created[abspath]\n        except OSError as exc:\n            log.warn(\"error removing %s: %s\", directory, exc)\n\n\ndef ensure_relative(path):\n    \"\"\"Take the full path 'path', and make it a relative path.\n\n    This is useful to make 'path' the second argument to os.path.join().\n    \"\"\"\n    drive, path = os.path.splitdrive(path)\n    if path[0:1] == os.sep:\n        path = drive + path[1:]\n    return path\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/dist.py",
    "content": "\"\"\"distutils.dist\n\nProvides the Distribution class, which represents the module distribution\nbeing built/installed/distributed.\n\"\"\"\n\nimport sys\nimport os\nimport re\nimport pathlib\nimport contextlib\nfrom email import message_from_file\n\ntry:\n    import warnings\nexcept ImportError:\n    warnings = None\n\nfrom distutils.errors import (\n    DistutilsOptionError,\n    DistutilsModuleError,\n    DistutilsArgError,\n    DistutilsClassError,\n)\nfrom distutils.fancy_getopt import FancyGetopt, translate_longopt\nfrom distutils.util import check_environ, strtobool, rfc822_escape\nfrom distutils import log\nfrom distutils.debug import DEBUG\n\n# Regex to define acceptable Distutils command names.  This is not *quite*\n# the same as a Python NAME -- I don't allow leading underscores.  The fact\n# that they're very similar is no coincidence; the default naming scheme is\n# to look for a Python module named after the command.\ncommand_re = re.compile(r'^[a-zA-Z]([a-zA-Z0-9_]*)$')\n\n\ndef _ensure_list(value, fieldname):\n    if isinstance(value, str):\n        # a string containing comma separated values is okay.  It will\n        # be converted to a list by Distribution.finalize_options().\n        pass\n    elif not isinstance(value, list):\n        # passing a tuple or an iterator perhaps, warn and convert\n        typename = type(value).__name__\n        msg = \"Warning: '{fieldname}' should be a list, got type '{typename}'\"\n        msg = msg.format(**locals())\n        log.log(log.WARN, msg)\n        value = list(value)\n    return value\n\n\nclass Distribution:\n    \"\"\"The core of the Distutils.  Most of the work hiding behind 'setup'\n    is really done within a Distribution instance, which farms the work out\n    to the Distutils commands specified on the command line.\n\n    Setup scripts will almost never instantiate Distribution directly,\n    unless the 'setup()' function is totally inadequate to their needs.\n    However, it is conceivable that a setup script might wish to subclass\n    Distribution for some specialized purpose, and then pass the subclass\n    to 'setup()' as the 'distclass' keyword argument.  If so, it is\n    necessary to respect the expectations that 'setup' has of Distribution.\n    See the code for 'setup()', in core.py, for details.\n    \"\"\"\n\n    # 'global_options' describes the command-line options that may be\n    # supplied to the setup script prior to any actual commands.\n    # Eg. \"./setup.py -n\" or \"./setup.py --quiet\" both take advantage of\n    # these global options.  This list should be kept to a bare minimum,\n    # since every global option is also valid as a command option -- and we\n    # don't want to pollute the commands with too many options that they\n    # have minimal control over.\n    # The fourth entry for verbose means that it can be repeated.\n    global_options = [\n        ('verbose', 'v', \"run verbosely (default)\", 1),\n        ('quiet', 'q', \"run quietly (turns verbosity off)\"),\n        ('dry-run', 'n', \"don't actually do anything\"),\n        ('help', 'h', \"show detailed help message\"),\n        ('no-user-cfg', None, 'ignore pydistutils.cfg in your home directory'),\n    ]\n\n    # 'common_usage' is a short (2-3 line) string describing the common\n    # usage of the setup script.\n    common_usage = \"\"\"\\\nCommon commands: (see '--help-commands' for more)\n\n  setup.py build      will build the package underneath 'build/'\n  setup.py install    will install the package\n\"\"\"\n\n    # options that are not propagated to the commands\n    display_options = [\n        ('help-commands', None, \"list all available commands\"),\n        ('name', None, \"print package name\"),\n        ('version', 'V', \"print package version\"),\n        ('fullname', None, \"print <package name>-<version>\"),\n        ('author', None, \"print the author's name\"),\n        ('author-email', None, \"print the author's email address\"),\n        ('maintainer', None, \"print the maintainer's name\"),\n        ('maintainer-email', None, \"print the maintainer's email address\"),\n        ('contact', None, \"print the maintainer's name if known, else the author's\"),\n        (\n            'contact-email',\n            None,\n            \"print the maintainer's email address if known, else the author's\",\n        ),\n        ('url', None, \"print the URL for this package\"),\n        ('license', None, \"print the license of the package\"),\n        ('licence', None, \"alias for --license\"),\n        ('description', None, \"print the package description\"),\n        ('long-description', None, \"print the long package description\"),\n        ('platforms', None, \"print the list of platforms\"),\n        ('classifiers', None, \"print the list of classifiers\"),\n        ('keywords', None, \"print the list of keywords\"),\n        ('provides', None, \"print the list of packages/modules provided\"),\n        ('requires', None, \"print the list of packages/modules required\"),\n        ('obsoletes', None, \"print the list of packages/modules made obsolete\"),\n    ]\n    display_option_names = [translate_longopt(x[0]) for x in display_options]\n\n    # negative options are options that exclude other options\n    negative_opt = {'quiet': 'verbose'}\n\n    # -- Creation/initialization methods -------------------------------\n\n    def __init__(self, attrs=None):  # noqa: C901\n        \"\"\"Construct a new Distribution instance: initialize all the\n        attributes of a Distribution, and then use 'attrs' (a dictionary\n        mapping attribute names to values) to assign some of those\n        attributes their \"real\" values.  (Any attributes not mentioned in\n        'attrs' will be assigned to some null value: 0, None, an empty list\n        or dictionary, etc.)  Most importantly, initialize the\n        'command_obj' attribute to the empty dictionary; this will be\n        filled in with real command objects by 'parse_command_line()'.\n        \"\"\"\n\n        # Default values for our command-line options\n        self.verbose = 1\n        self.dry_run = 0\n        self.help = 0\n        for attr in self.display_option_names:\n            setattr(self, attr, 0)\n\n        # Store the distribution meta-data (name, version, author, and so\n        # forth) in a separate object -- we're getting to have enough\n        # information here (and enough command-line options) that it's\n        # worth it.  Also delegate 'get_XXX()' methods to the 'metadata'\n        # object in a sneaky and underhanded (but efficient!) way.\n        self.metadata = DistributionMetadata()\n        for basename in self.metadata._METHOD_BASENAMES:\n            method_name = \"get_\" + basename\n            setattr(self, method_name, getattr(self.metadata, method_name))\n\n        # 'cmdclass' maps command names to class objects, so we\n        # can 1) quickly figure out which class to instantiate when\n        # we need to create a new command object, and 2) have a way\n        # for the setup script to override command classes\n        self.cmdclass = {}\n\n        # 'command_packages' is a list of packages in which commands\n        # are searched for.  The factory for command 'foo' is expected\n        # to be named 'foo' in the module 'foo' in one of the packages\n        # named here.  This list is searched from the left; an error\n        # is raised if no named package provides the command being\n        # searched for.  (Always access using get_command_packages().)\n        self.command_packages = None\n\n        # 'script_name' and 'script_args' are usually set to sys.argv[0]\n        # and sys.argv[1:], but they can be overridden when the caller is\n        # not necessarily a setup script run from the command-line.\n        self.script_name = None\n        self.script_args = None\n\n        # 'command_options' is where we store command options between\n        # parsing them (from config files, the command-line, etc.) and when\n        # they are actually needed -- ie. when the command in question is\n        # instantiated.  It is a dictionary of dictionaries of 2-tuples:\n        #   command_options = { command_name : { option : (source, value) } }\n        self.command_options = {}\n\n        # 'dist_files' is the list of (command, pyversion, file) that\n        # have been created by any dist commands run so far. This is\n        # filled regardless of whether the run is dry or not. pyversion\n        # gives sysconfig.get_python_version() if the dist file is\n        # specific to a Python version, 'any' if it is good for all\n        # Python versions on the target platform, and '' for a source\n        # file. pyversion should not be used to specify minimum or\n        # maximum required Python versions; use the metainfo for that\n        # instead.\n        self.dist_files = []\n\n        # These options are really the business of various commands, rather\n        # than of the Distribution itself.  We provide aliases for them in\n        # Distribution as a convenience to the developer.\n        self.packages = None\n        self.package_data = {}\n        self.package_dir = None\n        self.py_modules = None\n        self.libraries = None\n        self.headers = None\n        self.ext_modules = None\n        self.ext_package = None\n        self.include_dirs = None\n        self.extra_path = None\n        self.scripts = None\n        self.data_files = None\n        self.password = ''\n\n        # And now initialize bookkeeping stuff that can't be supplied by\n        # the caller at all.  'command_obj' maps command names to\n        # Command instances -- that's how we enforce that every command\n        # class is a singleton.\n        self.command_obj = {}\n\n        # 'have_run' maps command names to boolean values; it keeps track\n        # of whether we have actually run a particular command, to make it\n        # cheap to \"run\" a command whenever we think we might need to -- if\n        # it's already been done, no need for expensive filesystem\n        # operations, we just check the 'have_run' dictionary and carry on.\n        # It's only safe to query 'have_run' for a command class that has\n        # been instantiated -- a false value will be inserted when the\n        # command object is created, and replaced with a true value when\n        # the command is successfully run.  Thus it's probably best to use\n        # '.get()' rather than a straight lookup.\n        self.have_run = {}\n\n        # Now we'll use the attrs dictionary (ultimately, keyword args from\n        # the setup script) to possibly override any or all of these\n        # distribution options.\n\n        if attrs:\n            # Pull out the set of command options and work on them\n            # specifically.  Note that this order guarantees that aliased\n            # command options will override any supplied redundantly\n            # through the general options dictionary.\n            options = attrs.get('options')\n            if options is not None:\n                del attrs['options']\n                for (command, cmd_options) in options.items():\n                    opt_dict = self.get_option_dict(command)\n                    for (opt, val) in cmd_options.items():\n                        opt_dict[opt] = (\"setup script\", val)\n\n            if 'licence' in attrs:\n                attrs['license'] = attrs['licence']\n                del attrs['licence']\n                msg = \"'licence' distribution option is deprecated; use 'license'\"\n                if warnings is not None:\n                    warnings.warn(msg)\n                else:\n                    sys.stderr.write(msg + \"\\n\")\n\n            # Now work on the rest of the attributes.  Any attribute that's\n            # not already defined is invalid!\n            for (key, val) in attrs.items():\n                if hasattr(self.metadata, \"set_\" + key):\n                    getattr(self.metadata, \"set_\" + key)(val)\n                elif hasattr(self.metadata, key):\n                    setattr(self.metadata, key, val)\n                elif hasattr(self, key):\n                    setattr(self, key, val)\n                else:\n                    msg = \"Unknown distribution option: %s\" % repr(key)\n                    warnings.warn(msg)\n\n        # no-user-cfg is handled before other command line args\n        # because other args override the config files, and this\n        # one is needed before we can load the config files.\n        # If attrs['script_args'] wasn't passed, assume false.\n        #\n        # This also make sure we just look at the global options\n        self.want_user_cfg = True\n\n        if self.script_args is not None:\n            for arg in self.script_args:\n                if not arg.startswith('-'):\n                    break\n                if arg == '--no-user-cfg':\n                    self.want_user_cfg = False\n                    break\n\n        self.finalize_options()\n\n    def get_option_dict(self, command):\n        \"\"\"Get the option dictionary for a given command.  If that\n        command's option dictionary hasn't been created yet, then create it\n        and return the new dictionary; otherwise, return the existing\n        option dictionary.\n        \"\"\"\n        dict = self.command_options.get(command)\n        if dict is None:\n            dict = self.command_options[command] = {}\n        return dict\n\n    def dump_option_dicts(self, header=None, commands=None, indent=\"\"):\n        from pprint import pformat\n\n        if commands is None:  # dump all command option dicts\n            commands = sorted(self.command_options.keys())\n\n        if header is not None:\n            self.announce(indent + header)\n            indent = indent + \"  \"\n\n        if not commands:\n            self.announce(indent + \"no commands known yet\")\n            return\n\n        for cmd_name in commands:\n            opt_dict = self.command_options.get(cmd_name)\n            if opt_dict is None:\n                self.announce(indent + \"no option dict for '%s' command\" % cmd_name)\n            else:\n                self.announce(indent + \"option dict for '%s' command:\" % cmd_name)\n                out = pformat(opt_dict)\n                for line in out.split('\\n'):\n                    self.announce(indent + \"  \" + line)\n\n    # -- Config file finding/parsing methods ---------------------------\n\n    def find_config_files(self):\n        \"\"\"Find as many configuration files as should be processed for this\n        platform, and return a list of filenames in the order in which they\n        should be parsed.  The filenames returned are guaranteed to exist\n        (modulo nasty race conditions).\n\n        There are multiple possible config files:\n        - distutils.cfg in the Distutils installation directory (i.e.\n          where the top-level Distutils __inst__.py file lives)\n        - a file in the user's home directory named .pydistutils.cfg\n          on Unix and pydistutils.cfg on Windows/Mac; may be disabled\n          with the ``--no-user-cfg`` option\n        - setup.cfg in the current directory\n        - a file named by an environment variable\n        \"\"\"\n        check_environ()\n        files = [str(path) for path in self._gen_paths() if os.path.isfile(path)]\n\n        if DEBUG:\n            self.announce(\"using config files: %s\" % ', '.join(files))\n\n        return files\n\n    def _gen_paths(self):\n        # The system-wide Distutils config file\n        sys_dir = pathlib.Path(sys.modules['distutils'].__file__).parent\n        yield sys_dir / \"distutils.cfg\"\n\n        # The per-user config file\n        prefix = '.' * (os.name == 'posix')\n        filename = prefix + 'pydistutils.cfg'\n        if self.want_user_cfg:\n            yield pathlib.Path('~').expanduser() / filename\n\n        # All platforms support local setup.cfg\n        yield pathlib.Path('setup.cfg')\n\n        # Additional config indicated in the environment\n        with contextlib.suppress(TypeError):\n            yield pathlib.Path(os.getenv(\"DIST_EXTRA_CONFIG\"))\n\n    def parse_config_files(self, filenames=None):  # noqa: C901\n        from configparser import ConfigParser\n\n        # Ignore install directory options if we have a venv\n        if sys.prefix != sys.base_prefix:\n            ignore_options = [\n                'install-base',\n                'install-platbase',\n                'install-lib',\n                'install-platlib',\n                'install-purelib',\n                'install-headers',\n                'install-scripts',\n                'install-data',\n                'prefix',\n                'exec-prefix',\n                'home',\n                'user',\n                'root',\n            ]\n        else:\n            ignore_options = []\n\n        ignore_options = frozenset(ignore_options)\n\n        if filenames is None:\n            filenames = self.find_config_files()\n\n        if DEBUG:\n            self.announce(\"Distribution.parse_config_files():\")\n\n        parser = ConfigParser()\n        for filename in filenames:\n            if DEBUG:\n                self.announce(\"  reading %s\" % filename)\n            parser.read(filename)\n            for section in parser.sections():\n                options = parser.options(section)\n                opt_dict = self.get_option_dict(section)\n\n                for opt in options:\n                    if opt != '__name__' and opt not in ignore_options:\n                        val = parser.get(section, opt)\n                        opt = opt.replace('-', '_')\n                        opt_dict[opt] = (filename, val)\n\n            # Make the ConfigParser forget everything (so we retain\n            # the original filenames that options come from)\n            parser.__init__()\n\n        # If there was a \"global\" section in the config file, use it\n        # to set Distribution options.\n\n        if 'global' in self.command_options:\n            for (opt, (src, val)) in self.command_options['global'].items():\n                alias = self.negative_opt.get(opt)\n                try:\n                    if alias:\n                        setattr(self, alias, not strtobool(val))\n                    elif opt in ('verbose', 'dry_run'):  # ugh!\n                        setattr(self, opt, strtobool(val))\n                    else:\n                        setattr(self, opt, val)\n                except ValueError as msg:\n                    raise DistutilsOptionError(msg)\n\n    # -- Command-line parsing methods ----------------------------------\n\n    def parse_command_line(self):\n        \"\"\"Parse the setup script's command line, taken from the\n        'script_args' instance attribute (which defaults to 'sys.argv[1:]'\n        -- see 'setup()' in core.py).  This list is first processed for\n        \"global options\" -- options that set attributes of the Distribution\n        instance.  Then, it is alternately scanned for Distutils commands\n        and options for that command.  Each new command terminates the\n        options for the previous command.  The allowed options for a\n        command are determined by the 'user_options' attribute of the\n        command class -- thus, we have to be able to load command classes\n        in order to parse the command line.  Any error in that 'options'\n        attribute raises DistutilsGetoptError; any error on the\n        command-line raises DistutilsArgError.  If no Distutils commands\n        were found on the command line, raises DistutilsArgError.  Return\n        true if command-line was successfully parsed and we should carry\n        on with executing commands; false if no errors but we shouldn't\n        execute commands (currently, this only happens if user asks for\n        help).\n        \"\"\"\n        #\n        # We now have enough information to show the Macintosh dialog\n        # that allows the user to interactively specify the \"command line\".\n        #\n        toplevel_options = self._get_toplevel_options()\n\n        # We have to parse the command line a bit at a time -- global\n        # options, then the first command, then its options, and so on --\n        # because each command will be handled by a different class, and\n        # the options that are valid for a particular class aren't known\n        # until we have loaded the command class, which doesn't happen\n        # until we know what the command is.\n\n        self.commands = []\n        parser = FancyGetopt(toplevel_options + self.display_options)\n        parser.set_negative_aliases(self.negative_opt)\n        parser.set_aliases({'licence': 'license'})\n        args = parser.getopt(args=self.script_args, object=self)\n        option_order = parser.get_option_order()\n        log.set_verbosity(self.verbose)\n\n        # for display options we return immediately\n        if self.handle_display_options(option_order):\n            return\n        while args:\n            args = self._parse_command_opts(parser, args)\n            if args is None:  # user asked for help (and got it)\n                return\n\n        # Handle the cases of --help as a \"global\" option, ie.\n        # \"setup.py --help\" and \"setup.py --help command ...\".  For the\n        # former, we show global options (--verbose, --dry-run, etc.)\n        # and display-only options (--name, --version, etc.); for the\n        # latter, we omit the display-only options and show help for\n        # each command listed on the command line.\n        if self.help:\n            self._show_help(\n                parser, display_options=len(self.commands) == 0, commands=self.commands\n            )\n            return\n\n        # Oops, no commands found -- an end-user error\n        if not self.commands:\n            raise DistutilsArgError(\"no commands supplied\")\n\n        # All is well: return true\n        return True\n\n    def _get_toplevel_options(self):\n        \"\"\"Return the non-display options recognized at the top level.\n\n        This includes options that are recognized *only* at the top\n        level as well as options recognized for commands.\n        \"\"\"\n        return self.global_options + [\n            (\n                \"command-packages=\",\n                None,\n                \"list of packages that provide distutils commands\",\n            ),\n        ]\n\n    def _parse_command_opts(self, parser, args):  # noqa: C901\n        \"\"\"Parse the command-line options for a single command.\n        'parser' must be a FancyGetopt instance; 'args' must be the list\n        of arguments, starting with the current command (whose options\n        we are about to parse).  Returns a new version of 'args' with\n        the next command at the front of the list; will be the empty\n        list if there are no more commands on the command line.  Returns\n        None if the user asked for help on this command.\n        \"\"\"\n        # late import because of mutual dependence between these modules\n        from distutils.cmd import Command\n\n        # Pull the current command from the head of the command line\n        command = args[0]\n        if not command_re.match(command):\n            raise SystemExit(\"invalid command name '%s'\" % command)\n        self.commands.append(command)\n\n        # Dig up the command class that implements this command, so we\n        # 1) know that it's a valid command, and 2) know which options\n        # it takes.\n        try:\n            cmd_class = self.get_command_class(command)\n        except DistutilsModuleError as msg:\n            raise DistutilsArgError(msg)\n\n        # Require that the command class be derived from Command -- want\n        # to be sure that the basic \"command\" interface is implemented.\n        if not issubclass(cmd_class, Command):\n            raise DistutilsClassError(\n                \"command class %s must subclass Command\" % cmd_class\n            )\n\n        # Also make sure that the command object provides a list of its\n        # known options.\n        if not (\n            hasattr(cmd_class, 'user_options')\n            and isinstance(cmd_class.user_options, list)\n        ):\n            msg = (\n                \"command class %s must provide \"\n                \"'user_options' attribute (a list of tuples)\"\n            )\n            raise DistutilsClassError(msg % cmd_class)\n\n        # If the command class has a list of negative alias options,\n        # merge it in with the global negative aliases.\n        negative_opt = self.negative_opt\n        if hasattr(cmd_class, 'negative_opt'):\n            negative_opt = negative_opt.copy()\n            negative_opt.update(cmd_class.negative_opt)\n\n        # Check for help_options in command class.  They have a different\n        # format (tuple of four) so we need to preprocess them here.\n        if hasattr(cmd_class, 'help_options') and isinstance(\n            cmd_class.help_options, list\n        ):\n            help_options = fix_help_options(cmd_class.help_options)\n        else:\n            help_options = []\n\n        # All commands support the global options too, just by adding\n        # in 'global_options'.\n        parser.set_option_table(\n            self.global_options + cmd_class.user_options + help_options\n        )\n        parser.set_negative_aliases(negative_opt)\n        (args, opts) = parser.getopt(args[1:])\n        if hasattr(opts, 'help') and opts.help:\n            self._show_help(parser, display_options=0, commands=[cmd_class])\n            return\n\n        if hasattr(cmd_class, 'help_options') and isinstance(\n            cmd_class.help_options, list\n        ):\n            help_option_found = 0\n            for (help_option, short, desc, func) in cmd_class.help_options:\n                if hasattr(opts, parser.get_attr_name(help_option)):\n                    help_option_found = 1\n                    if callable(func):\n                        func()\n                    else:\n                        raise DistutilsClassError(\n                            \"invalid help function %r for help option '%s': \"\n                            \"must be a callable object (function, etc.)\"\n                            % (func, help_option)\n                        )\n\n            if help_option_found:\n                return\n\n        # Put the options from the command-line into their official\n        # holding pen, the 'command_options' dictionary.\n        opt_dict = self.get_option_dict(command)\n        for (name, value) in vars(opts).items():\n            opt_dict[name] = (\"command line\", value)\n\n        return args\n\n    def finalize_options(self):\n        \"\"\"Set final values for all the options on the Distribution\n        instance, analogous to the .finalize_options() method of Command\n        objects.\n        \"\"\"\n        for attr in ('keywords', 'platforms'):\n            value = getattr(self.metadata, attr)\n            if value is None:\n                continue\n            if isinstance(value, str):\n                value = [elm.strip() for elm in value.split(',')]\n                setattr(self.metadata, attr, value)\n\n    def _show_help(self, parser, global_options=1, display_options=1, commands=[]):\n        \"\"\"Show help for the setup script command-line in the form of\n        several lists of command-line options.  'parser' should be a\n        FancyGetopt instance; do not expect it to be returned in the\n        same state, as its option table will be reset to make it\n        generate the correct help text.\n\n        If 'global_options' is true, lists the global options:\n        --verbose, --dry-run, etc.  If 'display_options' is true, lists\n        the \"display-only\" options: --name, --version, etc.  Finally,\n        lists per-command help for every command name or command class\n        in 'commands'.\n        \"\"\"\n        # late import because of mutual dependence between these modules\n        from distutils.core import gen_usage\n        from distutils.cmd import Command\n\n        if global_options:\n            if display_options:\n                options = self._get_toplevel_options()\n            else:\n                options = self.global_options\n            parser.set_option_table(options)\n            parser.print_help(self.common_usage + \"\\nGlobal options:\")\n            print('')\n\n        if display_options:\n            parser.set_option_table(self.display_options)\n            parser.print_help(\n                \"Information display options (just display \"\n                + \"information, ignore any commands)\"\n            )\n            print('')\n\n        for command in self.commands:\n            if isinstance(command, type) and issubclass(command, Command):\n                klass = command\n            else:\n                klass = self.get_command_class(command)\n            if hasattr(klass, 'help_options') and isinstance(klass.help_options, list):\n                parser.set_option_table(\n                    klass.user_options + fix_help_options(klass.help_options)\n                )\n            else:\n                parser.set_option_table(klass.user_options)\n            parser.print_help(\"Options for '%s' command:\" % klass.__name__)\n            print('')\n\n        print(gen_usage(self.script_name))\n\n    def handle_display_options(self, option_order):\n        \"\"\"If there were any non-global \"display-only\" options\n        (--help-commands or the metadata display options) on the command\n        line, display the requested info and return true; else return\n        false.\n        \"\"\"\n        from distutils.core import gen_usage\n\n        # User just wants a list of commands -- we'll print it out and stop\n        # processing now (ie. if they ran \"setup --help-commands foo bar\",\n        # we ignore \"foo bar\").\n        if self.help_commands:\n            self.print_commands()\n            print('')\n            print(gen_usage(self.script_name))\n            return 1\n\n        # If user supplied any of the \"display metadata\" options, then\n        # display that metadata in the order in which the user supplied the\n        # metadata options.\n        any_display_options = 0\n        is_display_option = {}\n        for option in self.display_options:\n            is_display_option[option[0]] = 1\n\n        for (opt, val) in option_order:\n            if val and is_display_option.get(opt):\n                opt = translate_longopt(opt)\n                value = getattr(self.metadata, \"get_\" + opt)()\n                if opt in ['keywords', 'platforms']:\n                    print(','.join(value))\n                elif opt in ('classifiers', 'provides', 'requires', 'obsoletes'):\n                    print('\\n'.join(value))\n                else:\n                    print(value)\n                any_display_options = 1\n\n        return any_display_options\n\n    def print_command_list(self, commands, header, max_length):\n        \"\"\"Print a subset of the list of all commands -- used by\n        'print_commands()'.\n        \"\"\"\n        print(header + \":\")\n\n        for cmd in commands:\n            klass = self.cmdclass.get(cmd)\n            if not klass:\n                klass = self.get_command_class(cmd)\n            try:\n                description = klass.description\n            except AttributeError:\n                description = \"(no description available)\"\n\n            print(\"  %-*s  %s\" % (max_length, cmd, description))\n\n    def print_commands(self):\n        \"\"\"Print out a help message listing all available commands with a\n        description of each.  The list is divided into \"standard commands\"\n        (listed in distutils.command.__all__) and \"extra commands\"\n        (mentioned in self.cmdclass, but not a standard command).  The\n        descriptions come from the command class attribute\n        'description'.\n        \"\"\"\n        import distutils.command\n\n        std_commands = distutils.command.__all__\n        is_std = {}\n        for cmd in std_commands:\n            is_std[cmd] = 1\n\n        extra_commands = []\n        for cmd in self.cmdclass.keys():\n            if not is_std.get(cmd):\n                extra_commands.append(cmd)\n\n        max_length = 0\n        for cmd in std_commands + extra_commands:\n            if len(cmd) > max_length:\n                max_length = len(cmd)\n\n        self.print_command_list(std_commands, \"Standard commands\", max_length)\n        if extra_commands:\n            print()\n            self.print_command_list(extra_commands, \"Extra commands\", max_length)\n\n    def get_command_list(self):\n        \"\"\"Get a list of (command, description) tuples.\n        The list is divided into \"standard commands\" (listed in\n        distutils.command.__all__) and \"extra commands\" (mentioned in\n        self.cmdclass, but not a standard command).  The descriptions come\n        from the command class attribute 'description'.\n        \"\"\"\n        # Currently this is only used on Mac OS, for the Mac-only GUI\n        # Distutils interface (by Jack Jansen)\n        import distutils.command\n\n        std_commands = distutils.command.__all__\n        is_std = {}\n        for cmd in std_commands:\n            is_std[cmd] = 1\n\n        extra_commands = []\n        for cmd in self.cmdclass.keys():\n            if not is_std.get(cmd):\n                extra_commands.append(cmd)\n\n        rv = []\n        for cmd in std_commands + extra_commands:\n            klass = self.cmdclass.get(cmd)\n            if not klass:\n                klass = self.get_command_class(cmd)\n            try:\n                description = klass.description\n            except AttributeError:\n                description = \"(no description available)\"\n            rv.append((cmd, description))\n        return rv\n\n    # -- Command class/object methods ----------------------------------\n\n    def get_command_packages(self):\n        \"\"\"Return a list of packages from which commands are loaded.\"\"\"\n        pkgs = self.command_packages\n        if not isinstance(pkgs, list):\n            if pkgs is None:\n                pkgs = ''\n            pkgs = [pkg.strip() for pkg in pkgs.split(',') if pkg != '']\n            if \"distutils.command\" not in pkgs:\n                pkgs.insert(0, \"distutils.command\")\n            self.command_packages = pkgs\n        return pkgs\n\n    def get_command_class(self, command):\n        \"\"\"Return the class that implements the Distutils command named by\n        'command'.  First we check the 'cmdclass' dictionary; if the\n        command is mentioned there, we fetch the class object from the\n        dictionary and return it.  Otherwise we load the command module\n        (\"distutils.command.\" + command) and fetch the command class from\n        the module.  The loaded class is also stored in 'cmdclass'\n        to speed future calls to 'get_command_class()'.\n\n        Raises DistutilsModuleError if the expected module could not be\n        found, or if that module does not define the expected class.\n        \"\"\"\n        klass = self.cmdclass.get(command)\n        if klass:\n            return klass\n\n        for pkgname in self.get_command_packages():\n            module_name = \"{}.{}\".format(pkgname, command)\n            klass_name = command\n\n            try:\n                __import__(module_name)\n                module = sys.modules[module_name]\n            except ImportError:\n                continue\n\n            try:\n                klass = getattr(module, klass_name)\n            except AttributeError:\n                raise DistutilsModuleError(\n                    \"invalid command '%s' (no class '%s' in module '%s')\"\n                    % (command, klass_name, module_name)\n                )\n\n            self.cmdclass[command] = klass\n            return klass\n\n        raise DistutilsModuleError(\"invalid command '%s'\" % command)\n\n    def get_command_obj(self, command, create=1):\n        \"\"\"Return the command object for 'command'.  Normally this object\n        is cached on a previous call to 'get_command_obj()'; if no command\n        object for 'command' is in the cache, then we either create and\n        return it (if 'create' is true) or return None.\n        \"\"\"\n        cmd_obj = self.command_obj.get(command)\n        if not cmd_obj and create:\n            if DEBUG:\n                self.announce(\n                    \"Distribution.get_command_obj(): \"\n                    \"creating '%s' command object\" % command\n                )\n\n            klass = self.get_command_class(command)\n            cmd_obj = self.command_obj[command] = klass(self)\n            self.have_run[command] = 0\n\n            # Set any options that were supplied in config files\n            # or on the command line.  (NB. support for error\n            # reporting is lame here: any errors aren't reported\n            # until 'finalize_options()' is called, which means\n            # we won't report the source of the error.)\n            options = self.command_options.get(command)\n            if options:\n                self._set_command_options(cmd_obj, options)\n\n        return cmd_obj\n\n    def _set_command_options(self, command_obj, option_dict=None):  # noqa: C901\n        \"\"\"Set the options for 'command_obj' from 'option_dict'.  Basically\n        this means copying elements of a dictionary ('option_dict') to\n        attributes of an instance ('command').\n\n        'command_obj' must be a Command instance.  If 'option_dict' is not\n        supplied, uses the standard option dictionary for this command\n        (from 'self.command_options').\n        \"\"\"\n        command_name = command_obj.get_command_name()\n        if option_dict is None:\n            option_dict = self.get_option_dict(command_name)\n\n        if DEBUG:\n            self.announce(\"  setting options for '%s' command:\" % command_name)\n        for (option, (source, value)) in option_dict.items():\n            if DEBUG:\n                self.announce(\"    {} = {} (from {})\".format(option, value, source))\n            try:\n                bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]\n            except AttributeError:\n                bool_opts = []\n            try:\n                neg_opt = command_obj.negative_opt\n            except AttributeError:\n                neg_opt = {}\n\n            try:\n                is_string = isinstance(value, str)\n                if option in neg_opt and is_string:\n                    setattr(command_obj, neg_opt[option], not strtobool(value))\n                elif option in bool_opts and is_string:\n                    setattr(command_obj, option, strtobool(value))\n                elif hasattr(command_obj, option):\n                    setattr(command_obj, option, value)\n                else:\n                    raise DistutilsOptionError(\n                        \"error in %s: command '%s' has no such option '%s'\"\n                        % (source, command_name, option)\n                    )\n            except ValueError as msg:\n                raise DistutilsOptionError(msg)\n\n    def reinitialize_command(self, command, reinit_subcommands=0):\n        \"\"\"Reinitializes a command to the state it was in when first\n        returned by 'get_command_obj()': ie., initialized but not yet\n        finalized.  This provides the opportunity to sneak option\n        values in programmatically, overriding or supplementing\n        user-supplied values from the config files and command line.\n        You'll have to re-finalize the command object (by calling\n        'finalize_options()' or 'ensure_finalized()') before using it for\n        real.\n\n        'command' should be a command name (string) or command object.  If\n        'reinit_subcommands' is true, also reinitializes the command's\n        sub-commands, as declared by the 'sub_commands' class attribute (if\n        it has one).  See the \"install\" command for an example.  Only\n        reinitializes the sub-commands that actually matter, ie. those\n        whose test predicates return true.\n\n        Returns the reinitialized command object.\n        \"\"\"\n        from distutils.cmd import Command\n\n        if not isinstance(command, Command):\n            command_name = command\n            command = self.get_command_obj(command_name)\n        else:\n            command_name = command.get_command_name()\n\n        if not command.finalized:\n            return command\n        command.initialize_options()\n        command.finalized = 0\n        self.have_run[command_name] = 0\n        self._set_command_options(command)\n\n        if reinit_subcommands:\n            for sub in command.get_sub_commands():\n                self.reinitialize_command(sub, reinit_subcommands)\n\n        return command\n\n    # -- Methods that operate on the Distribution ----------------------\n\n    def announce(self, msg, level=log.INFO):\n        log.log(level, msg)\n\n    def run_commands(self):\n        \"\"\"Run each command that was seen on the setup script command line.\n        Uses the list of commands found and cache of command objects\n        created by 'get_command_obj()'.\n        \"\"\"\n        for cmd in self.commands:\n            self.run_command(cmd)\n\n    # -- Methods that operate on its Commands --------------------------\n\n    def run_command(self, command):\n        \"\"\"Do whatever it takes to run a command (including nothing at all,\n        if the command has already been run).  Specifically: if we have\n        already created and run the command named by 'command', return\n        silently without doing anything.  If the command named by 'command'\n        doesn't even have a command object yet, create one.  Then invoke\n        'run()' on that command object (or an existing one).\n        \"\"\"\n        # Already been here, done that? then return silently.\n        if self.have_run.get(command):\n            return\n\n        log.info(\"running %s\", command)\n        cmd_obj = self.get_command_obj(command)\n        cmd_obj.ensure_finalized()\n        cmd_obj.run()\n        self.have_run[command] = 1\n\n    # -- Distribution query methods ------------------------------------\n\n    def has_pure_modules(self):\n        return len(self.packages or self.py_modules or []) > 0\n\n    def has_ext_modules(self):\n        return self.ext_modules and len(self.ext_modules) > 0\n\n    def has_c_libraries(self):\n        return self.libraries and len(self.libraries) > 0\n\n    def has_modules(self):\n        return self.has_pure_modules() or self.has_ext_modules()\n\n    def has_headers(self):\n        return self.headers and len(self.headers) > 0\n\n    def has_scripts(self):\n        return self.scripts and len(self.scripts) > 0\n\n    def has_data_files(self):\n        return self.data_files and len(self.data_files) > 0\n\n    def is_pure(self):\n        return (\n            self.has_pure_modules()\n            and not self.has_ext_modules()\n            and not self.has_c_libraries()\n        )\n\n    # -- Metadata query methods ----------------------------------------\n\n    # If you're looking for 'get_name()', 'get_version()', and so forth,\n    # they are defined in a sneaky way: the constructor binds self.get_XXX\n    # to self.metadata.get_XXX.  The actual code is in the\n    # DistributionMetadata class, below.\n\n\nclass DistributionMetadata:\n    \"\"\"Dummy class to hold the distribution meta-data: name, version,\n    author, and so forth.\n    \"\"\"\n\n    _METHOD_BASENAMES = (\n        \"name\",\n        \"version\",\n        \"author\",\n        \"author_email\",\n        \"maintainer\",\n        \"maintainer_email\",\n        \"url\",\n        \"license\",\n        \"description\",\n        \"long_description\",\n        \"keywords\",\n        \"platforms\",\n        \"fullname\",\n        \"contact\",\n        \"contact_email\",\n        \"classifiers\",\n        \"download_url\",\n        # PEP 314\n        \"provides\",\n        \"requires\",\n        \"obsoletes\",\n    )\n\n    def __init__(self, path=None):\n        if path is not None:\n            self.read_pkg_file(open(path))\n        else:\n            self.name = None\n            self.version = None\n            self.author = None\n            self.author_email = None\n            self.maintainer = None\n            self.maintainer_email = None\n            self.url = None\n            self.license = None\n            self.description = None\n            self.long_description = None\n            self.keywords = None\n            self.platforms = None\n            self.classifiers = None\n            self.download_url = None\n            # PEP 314\n            self.provides = None\n            self.requires = None\n            self.obsoletes = None\n\n    def read_pkg_file(self, file):\n        \"\"\"Reads the metadata values from a file object.\"\"\"\n        msg = message_from_file(file)\n\n        def _read_field(name):\n            value = msg[name]\n            if value and value != \"UNKNOWN\":\n                return value\n\n        def _read_list(name):\n            values = msg.get_all(name, None)\n            if values == []:\n                return None\n            return values\n\n        metadata_version = msg['metadata-version']\n        self.name = _read_field('name')\n        self.version = _read_field('version')\n        self.description = _read_field('summary')\n        # we are filling author only.\n        self.author = _read_field('author')\n        self.maintainer = None\n        self.author_email = _read_field('author-email')\n        self.maintainer_email = None\n        self.url = _read_field('home-page')\n        self.license = _read_field('license')\n\n        if 'download-url' in msg:\n            self.download_url = _read_field('download-url')\n        else:\n            self.download_url = None\n\n        self.long_description = _read_field('description')\n        self.description = _read_field('summary')\n\n        if 'keywords' in msg:\n            self.keywords = _read_field('keywords').split(',')\n\n        self.platforms = _read_list('platform')\n        self.classifiers = _read_list('classifier')\n\n        # PEP 314 - these fields only exist in 1.1\n        if metadata_version == '1.1':\n            self.requires = _read_list('requires')\n            self.provides = _read_list('provides')\n            self.obsoletes = _read_list('obsoletes')\n        else:\n            self.requires = None\n            self.provides = None\n            self.obsoletes = None\n\n    def write_pkg_info(self, base_dir):\n        \"\"\"Write the PKG-INFO file into the release tree.\"\"\"\n        with open(\n            os.path.join(base_dir, 'PKG-INFO'), 'w', encoding='UTF-8'\n        ) as pkg_info:\n            self.write_pkg_file(pkg_info)\n\n    def write_pkg_file(self, file):\n        \"\"\"Write the PKG-INFO format data to a file object.\"\"\"\n        version = '1.0'\n        if (\n            self.provides\n            or self.requires\n            or self.obsoletes\n            or self.classifiers\n            or self.download_url\n        ):\n            version = '1.1'\n\n        # required fields\n        file.write('Metadata-Version: %s\\n' % version)\n        file.write('Name: %s\\n' % self.get_name())\n        file.write('Version: %s\\n' % self.get_version())\n\n        def maybe_write(header, val):\n            if val:\n                file.write(f\"{header}: {val}\\n\")\n\n        # optional fields\n        maybe_write(\"Summary\", self.get_description())\n        maybe_write(\"Home-page\", self.get_url())\n        maybe_write(\"Author\", self.get_contact())\n        maybe_write(\"Author-email\", self.get_contact_email())\n        maybe_write(\"License\", self.get_license())\n        maybe_write(\"Download-URL\", self.download_url)\n        maybe_write(\"Description\", rfc822_escape(self.get_long_description() or \"\"))\n        maybe_write(\"Keywords\", \",\".join(self.get_keywords()))\n\n        self._write_list(file, 'Platform', self.get_platforms())\n        self._write_list(file, 'Classifier', self.get_classifiers())\n\n        # PEP 314\n        self._write_list(file, 'Requires', self.get_requires())\n        self._write_list(file, 'Provides', self.get_provides())\n        self._write_list(file, 'Obsoletes', self.get_obsoletes())\n\n    def _write_list(self, file, name, values):\n        values = values or []\n        for value in values:\n            file.write('{}: {}\\n'.format(name, value))\n\n    # -- Metadata query methods ----------------------------------------\n\n    def get_name(self):\n        return self.name or \"UNKNOWN\"\n\n    def get_version(self):\n        return self.version or \"0.0.0\"\n\n    def get_fullname(self):\n        return \"{}-{}\".format(self.get_name(), self.get_version())\n\n    def get_author(self):\n        return self.author\n\n    def get_author_email(self):\n        return self.author_email\n\n    def get_maintainer(self):\n        return self.maintainer\n\n    def get_maintainer_email(self):\n        return self.maintainer_email\n\n    def get_contact(self):\n        return self.maintainer or self.author\n\n    def get_contact_email(self):\n        return self.maintainer_email or self.author_email\n\n    def get_url(self):\n        return self.url\n\n    def get_license(self):\n        return self.license\n\n    get_licence = get_license\n\n    def get_description(self):\n        return self.description\n\n    def get_long_description(self):\n        return self.long_description\n\n    def get_keywords(self):\n        return self.keywords or []\n\n    def set_keywords(self, value):\n        self.keywords = _ensure_list(value, 'keywords')\n\n    def get_platforms(self):\n        return self.platforms\n\n    def set_platforms(self, value):\n        self.platforms = _ensure_list(value, 'platforms')\n\n    def get_classifiers(self):\n        return self.classifiers or []\n\n    def set_classifiers(self, value):\n        self.classifiers = _ensure_list(value, 'classifiers')\n\n    def get_download_url(self):\n        return self.download_url\n\n    # PEP 314\n    def get_requires(self):\n        return self.requires or []\n\n    def set_requires(self, value):\n        import distutils.versionpredicate\n\n        for v in value:\n            distutils.versionpredicate.VersionPredicate(v)\n        self.requires = list(value)\n\n    def get_provides(self):\n        return self.provides or []\n\n    def set_provides(self, value):\n        value = [v.strip() for v in value]\n        for v in value:\n            import distutils.versionpredicate\n\n            distutils.versionpredicate.split_provision(v)\n        self.provides = value\n\n    def get_obsoletes(self):\n        return self.obsoletes or []\n\n    def set_obsoletes(self, value):\n        import distutils.versionpredicate\n\n        for v in value:\n            distutils.versionpredicate.VersionPredicate(v)\n        self.obsoletes = list(value)\n\n\ndef fix_help_options(options):\n    \"\"\"Convert a 4-tuple 'help_options' list as found in various command\n    classes to the 3-tuple form required by FancyGetopt.\n    \"\"\"\n    new_options = []\n    for help_tuple in options:\n        new_options.append(help_tuple[0:3])\n    return new_options\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/errors.py",
    "content": "\"\"\"distutils.errors\n\nProvides exceptions used by the Distutils modules.  Note that Distutils\nmodules may raise standard exceptions; in particular, SystemExit is\nusually raised for errors that are obviously the end-user's fault\n(eg. bad command-line arguments).\n\nThis module is safe to use in \"from ... import *\" mode; it only exports\nsymbols whose names start with \"Distutils\" and end with \"Error\".\"\"\"\n\n\nclass DistutilsError(Exception):\n    \"\"\"The root of all Distutils evil.\"\"\"\n\n    pass\n\n\nclass DistutilsModuleError(DistutilsError):\n    \"\"\"Unable to load an expected module, or to find an expected class\n    within some module (in particular, command modules and classes).\"\"\"\n\n    pass\n\n\nclass DistutilsClassError(DistutilsError):\n    \"\"\"Some command class (or possibly distribution class, if anyone\n    feels a need to subclass Distribution) is found not to be holding\n    up its end of the bargain, ie. implementing some part of the\n    \"command \"interface.\"\"\"\n\n    pass\n\n\nclass DistutilsGetoptError(DistutilsError):\n    \"\"\"The option table provided to 'fancy_getopt()' is bogus.\"\"\"\n\n    pass\n\n\nclass DistutilsArgError(DistutilsError):\n    \"\"\"Raised by fancy_getopt in response to getopt.error -- ie. an\n    error in the command line usage.\"\"\"\n\n    pass\n\n\nclass DistutilsFileError(DistutilsError):\n    \"\"\"Any problems in the filesystem: expected file not found, etc.\n    Typically this is for problems that we detect before OSError\n    could be raised.\"\"\"\n\n    pass\n\n\nclass DistutilsOptionError(DistutilsError):\n    \"\"\"Syntactic/semantic errors in command options, such as use of\n    mutually conflicting options, or inconsistent options,\n    badly-spelled values, etc.  No distinction is made between option\n    values originating in the setup script, the command line, config\n    files, or what-have-you -- but if we *know* something originated in\n    the setup script, we'll raise DistutilsSetupError instead.\"\"\"\n\n    pass\n\n\nclass DistutilsSetupError(DistutilsError):\n    \"\"\"For errors that can be definitely blamed on the setup script,\n    such as invalid keyword arguments to 'setup()'.\"\"\"\n\n    pass\n\n\nclass DistutilsPlatformError(DistutilsError):\n    \"\"\"We don't know how to do something on the current platform (but\n    we do know how to do it on some platform) -- eg. trying to compile\n    C files on a platform not supported by a CCompiler subclass.\"\"\"\n\n    pass\n\n\nclass DistutilsExecError(DistutilsError):\n    \"\"\"Any problems executing an external program (such as the C\n    compiler, when compiling C files).\"\"\"\n\n    pass\n\n\nclass DistutilsInternalError(DistutilsError):\n    \"\"\"Internal inconsistencies or impossibilities (obviously, this\n    should never be seen if the code is working!).\"\"\"\n\n    pass\n\n\nclass DistutilsTemplateError(DistutilsError):\n    \"\"\"Syntax error in a file list template.\"\"\"\n\n\nclass DistutilsByteCompileError(DistutilsError):\n    \"\"\"Byte compile error.\"\"\"\n\n\n# Exception classes used by the CCompiler implementation classes\nclass CCompilerError(Exception):\n    \"\"\"Some compile/link operation failed.\"\"\"\n\n\nclass PreprocessError(CCompilerError):\n    \"\"\"Failure to preprocess one or more C/C++ files.\"\"\"\n\n\nclass CompileError(CCompilerError):\n    \"\"\"Failure to compile one or more C/C++ source files.\"\"\"\n\n\nclass LibError(CCompilerError):\n    \"\"\"Failure to create a static library from one or more C/C++ object\n    files.\"\"\"\n\n\nclass LinkError(CCompilerError):\n    \"\"\"Failure to link one or more C/C++ object files into an executable\n    or shared library file.\"\"\"\n\n\nclass UnknownFileError(CCompilerError):\n    \"\"\"Attempt to process an unknown file type.\"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/extension.py",
    "content": "\"\"\"distutils.extension\n\nProvides the Extension class, used to describe C/C++ extension\nmodules in setup scripts.\"\"\"\n\nimport os\nimport warnings\n\n# This class is really only used by the \"build_ext\" command, so it might\n# make sense to put it in distutils.command.build_ext.  However, that\n# module is already big enough, and I want to make this class a bit more\n# complex to simplify some common cases (\"foo\" module in \"foo.c\") and do\n# better error-checking (\"foo.c\" actually exists).\n#\n# Also, putting this in build_ext.py means every setup script would have to\n# import that large-ish module (indirectly, through distutils.core) in\n# order to do anything.\n\n\nclass Extension:\n    \"\"\"Just a collection of attributes that describes an extension\n    module and everything needed to build it (hopefully in a portable\n    way, but there are hooks that let you be as unportable as you need).\n\n    Instance attributes:\n      name : string\n        the full name of the extension, including any packages -- ie.\n        *not* a filename or pathname, but Python dotted name\n      sources : [string]\n        list of source filenames, relative to the distribution root\n        (where the setup script lives), in Unix form (slash-separated)\n        for portability.  Source files may be C, C++, SWIG (.i),\n        platform-specific resource files, or whatever else is recognized\n        by the \"build_ext\" command as source for a Python extension.\n      include_dirs : [string]\n        list of directories to search for C/C++ header files (in Unix\n        form for portability)\n      define_macros : [(name : string, value : string|None)]\n        list of macros to define; each macro is defined using a 2-tuple,\n        where 'value' is either the string to define it to or None to\n        define it without a particular value (equivalent of \"#define\n        FOO\" in source or -DFOO on Unix C compiler command line)\n      undef_macros : [string]\n        list of macros to undefine explicitly\n      library_dirs : [string]\n        list of directories to search for C/C++ libraries at link time\n      libraries : [string]\n        list of library names (not filenames or paths) to link against\n      runtime_library_dirs : [string]\n        list of directories to search for C/C++ libraries at run time\n        (for shared extensions, this is when the extension is loaded)\n      extra_objects : [string]\n        list of extra files to link with (eg. object files not implied\n        by 'sources', static library that must be explicitly specified,\n        binary resource files, etc.)\n      extra_compile_args : [string]\n        any extra platform- and compiler-specific information to use\n        when compiling the source files in 'sources'.  For platforms and\n        compilers where \"command line\" makes sense, this is typically a\n        list of command-line arguments, but for other platforms it could\n        be anything.\n      extra_link_args : [string]\n        any extra platform- and compiler-specific information to use\n        when linking object files together to create the extension (or\n        to create a new static Python interpreter).  Similar\n        interpretation as for 'extra_compile_args'.\n      export_symbols : [string]\n        list of symbols to be exported from a shared extension.  Not\n        used on all platforms, and not generally necessary for Python\n        extensions, which typically export exactly one symbol: \"init\" +\n        extension_name.\n      swig_opts : [string]\n        any extra options to pass to SWIG if a source file has the .i\n        extension.\n      depends : [string]\n        list of files that the extension depends on\n      language : string\n        extension language (i.e. \"c\", \"c++\", \"objc\"). Will be detected\n        from the source extensions if not provided.\n      optional : boolean\n        specifies that a build failure in the extension should not abort the\n        build process, but simply not install the failing extension.\n    \"\"\"\n\n    # When adding arguments to this constructor, be sure to update\n    # setup_keywords in core.py.\n    def __init__(\n        self,\n        name,\n        sources,\n        include_dirs=None,\n        define_macros=None,\n        undef_macros=None,\n        library_dirs=None,\n        libraries=None,\n        runtime_library_dirs=None,\n        extra_objects=None,\n        extra_compile_args=None,\n        extra_link_args=None,\n        export_symbols=None,\n        swig_opts=None,\n        depends=None,\n        language=None,\n        optional=None,\n        **kw  # To catch unknown keywords\n    ):\n        if not isinstance(name, str):\n            raise AssertionError(\"'name' must be a string\")\n        if not (isinstance(sources, list) and all(isinstance(v, str) for v in sources)):\n            raise AssertionError(\"'sources' must be a list of strings\")\n\n        self.name = name\n        self.sources = sources\n        self.include_dirs = include_dirs or []\n        self.define_macros = define_macros or []\n        self.undef_macros = undef_macros or []\n        self.library_dirs = library_dirs or []\n        self.libraries = libraries or []\n        self.runtime_library_dirs = runtime_library_dirs or []\n        self.extra_objects = extra_objects or []\n        self.extra_compile_args = extra_compile_args or []\n        self.extra_link_args = extra_link_args or []\n        self.export_symbols = export_symbols or []\n        self.swig_opts = swig_opts or []\n        self.depends = depends or []\n        self.language = language\n        self.optional = optional\n\n        # If there are unknown keyword options, warn about them\n        if len(kw) > 0:\n            options = [repr(option) for option in kw]\n            options = ', '.join(sorted(options))\n            msg = \"Unknown Extension options: %s\" % options\n            warnings.warn(msg)\n\n    def __repr__(self):\n        return '<{}.{}({!r}) at {:#x}>'.format(\n            self.__class__.__module__,\n            self.__class__.__qualname__,\n            self.name,\n            id(self),\n        )\n\n\ndef read_setup_file(filename):  # noqa: C901\n    \"\"\"Reads a Setup file and returns Extension instances.\"\"\"\n    from distutils.sysconfig import parse_makefile, expand_makefile_vars, _variable_rx\n\n    from distutils.text_file import TextFile\n    from distutils.util import split_quoted\n\n    # First pass over the file to gather \"VAR = VALUE\" assignments.\n    vars = parse_makefile(filename)\n\n    # Second pass to gobble up the real content: lines of the form\n    #   <module> ... [<sourcefile> ...] [<cpparg> ...] [<library> ...]\n    file = TextFile(\n        filename,\n        strip_comments=1,\n        skip_blanks=1,\n        join_lines=1,\n        lstrip_ws=1,\n        rstrip_ws=1,\n    )\n    try:\n        extensions = []\n\n        while True:\n            line = file.readline()\n            if line is None:  # eof\n                break\n            if _variable_rx.match(line):  # VAR=VALUE, handled in first pass\n                continue\n\n            if line[0] == line[-1] == \"*\":\n                file.warn(\"'%s' lines not handled yet\" % line)\n                continue\n\n            line = expand_makefile_vars(line, vars)\n            words = split_quoted(line)\n\n            # NB. this parses a slightly different syntax than the old\n            # makesetup script: here, there must be exactly one extension per\n            # line, and it must be the first word of the line.  I have no idea\n            # why the old syntax supported multiple extensions per line, as\n            # they all wind up being the same.\n\n            module = words[0]\n            ext = Extension(module, [])\n            append_next_word = None\n\n            for word in words[1:]:\n                if append_next_word is not None:\n                    append_next_word.append(word)\n                    append_next_word = None\n                    continue\n\n                suffix = os.path.splitext(word)[1]\n                switch = word[0:2]\n                value = word[2:]\n\n                if suffix in (\".c\", \".cc\", \".cpp\", \".cxx\", \".c++\", \".m\", \".mm\"):\n                    # hmm, should we do something about C vs. C++ sources?\n                    # or leave it up to the CCompiler implementation to\n                    # worry about?\n                    ext.sources.append(word)\n                elif switch == \"-I\":\n                    ext.include_dirs.append(value)\n                elif switch == \"-D\":\n                    equals = value.find(\"=\")\n                    if equals == -1:  # bare \"-DFOO\" -- no value\n                        ext.define_macros.append((value, None))\n                    else:  # \"-DFOO=blah\"\n                        ext.define_macros.append((value[0:equals], value[equals + 2 :]))\n                elif switch == \"-U\":\n                    ext.undef_macros.append(value)\n                elif switch == \"-C\":  # only here 'cause makesetup has it!\n                    ext.extra_compile_args.append(word)\n                elif switch == \"-l\":\n                    ext.libraries.append(value)\n                elif switch == \"-L\":\n                    ext.library_dirs.append(value)\n                elif switch == \"-R\":\n                    ext.runtime_library_dirs.append(value)\n                elif word == \"-rpath\":\n                    append_next_word = ext.runtime_library_dirs\n                elif word == \"-Xlinker\":\n                    append_next_word = ext.extra_link_args\n                elif word == \"-Xcompiler\":\n                    append_next_word = ext.extra_compile_args\n                elif switch == \"-u\":\n                    ext.extra_link_args.append(word)\n                    if not value:\n                        append_next_word = ext.extra_link_args\n                elif suffix in (\".a\", \".so\", \".sl\", \".o\", \".dylib\"):\n                    # NB. a really faithful emulation of makesetup would\n                    # append a .o file to extra_objects only if it\n                    # had a slash in it; otherwise, it would s/.o/.c/\n                    # and append it to sources.  Hmmmm.\n                    ext.extra_objects.append(word)\n                else:\n                    file.warn(\"unrecognized argument '%s'\" % word)\n\n            extensions.append(ext)\n    finally:\n        file.close()\n\n    return extensions\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/fancy_getopt.py",
    "content": "\"\"\"distutils.fancy_getopt\n\nWrapper around the standard getopt module that provides the following\nadditional features:\n  * short and long options are tied together\n  * options have help strings, so fancy_getopt could potentially\n    create a complete usage summary\n  * options set attributes of a passed-in object\n\"\"\"\n\nimport sys\nimport string\nimport re\nimport getopt\nfrom distutils.errors import DistutilsGetoptError, DistutilsArgError\n\n# Much like command_re in distutils.core, this is close to but not quite\n# the same as a Python NAME -- except, in the spirit of most GNU\n# utilities, we use '-' in place of '_'.  (The spirit of LISP lives on!)\n# The similarities to NAME are again not a coincidence...\nlongopt_pat = r'[a-zA-Z](?:[a-zA-Z0-9-]*)'\nlongopt_re = re.compile(r'^%s$' % longopt_pat)\n\n# For recognizing \"negative alias\" options, eg. \"quiet=!verbose\"\nneg_alias_re = re.compile(\"^({})=!({})$\".format(longopt_pat, longopt_pat))\n\n# This is used to translate long options to legitimate Python identifiers\n# (for use as attributes of some object).\nlongopt_xlate = str.maketrans('-', '_')\n\n\nclass FancyGetopt:\n    \"\"\"Wrapper around the standard 'getopt()' module that provides some\n    handy extra functionality:\n      * short and long options are tied together\n      * options have help strings, and help text can be assembled\n        from them\n      * options set attributes of a passed-in object\n      * boolean options can have \"negative aliases\" -- eg. if\n        --quiet is the \"negative alias\" of --verbose, then \"--quiet\"\n        on the command line sets 'verbose' to false\n    \"\"\"\n\n    def __init__(self, option_table=None):\n        # The option table is (currently) a list of tuples.  The\n        # tuples may have 3 or four values:\n        #   (long_option, short_option, help_string [, repeatable])\n        # if an option takes an argument, its long_option should have '='\n        # appended; short_option should just be a single character, no ':'\n        # in any case.  If a long_option doesn't have a corresponding\n        # short_option, short_option should be None.  All option tuples\n        # must have long options.\n        self.option_table = option_table\n\n        # 'option_index' maps long option names to entries in the option\n        # table (ie. those 3-tuples).\n        self.option_index = {}\n        if self.option_table:\n            self._build_index()\n\n        # 'alias' records (duh) alias options; {'foo': 'bar'} means\n        # --foo is an alias for --bar\n        self.alias = {}\n\n        # 'negative_alias' keeps track of options that are the boolean\n        # opposite of some other option\n        self.negative_alias = {}\n\n        # These keep track of the information in the option table.  We\n        # don't actually populate these structures until we're ready to\n        # parse the command-line, since the 'option_table' passed in here\n        # isn't necessarily the final word.\n        self.short_opts = []\n        self.long_opts = []\n        self.short2long = {}\n        self.attr_name = {}\n        self.takes_arg = {}\n\n        # And 'option_order' is filled up in 'getopt()'; it records the\n        # original order of options (and their values) on the command-line,\n        # but expands short options, converts aliases, etc.\n        self.option_order = []\n\n    def _build_index(self):\n        self.option_index.clear()\n        for option in self.option_table:\n            self.option_index[option[0]] = option\n\n    def set_option_table(self, option_table):\n        self.option_table = option_table\n        self._build_index()\n\n    def add_option(self, long_option, short_option=None, help_string=None):\n        if long_option in self.option_index:\n            raise DistutilsGetoptError(\n                \"option conflict: already an option '%s'\" % long_option\n            )\n        else:\n            option = (long_option, short_option, help_string)\n            self.option_table.append(option)\n            self.option_index[long_option] = option\n\n    def has_option(self, long_option):\n        \"\"\"Return true if the option table for this parser has an\n        option with long name 'long_option'.\"\"\"\n        return long_option in self.option_index\n\n    def get_attr_name(self, long_option):\n        \"\"\"Translate long option name 'long_option' to the form it\n        has as an attribute of some object: ie., translate hyphens\n        to underscores.\"\"\"\n        return long_option.translate(longopt_xlate)\n\n    def _check_alias_dict(self, aliases, what):\n        assert isinstance(aliases, dict)\n        for (alias, opt) in aliases.items():\n            if alias not in self.option_index:\n                raise DistutilsGetoptError(\n                    (\"invalid %s '%s': \" \"option '%s' not defined\")\n                    % (what, alias, alias)\n                )\n            if opt not in self.option_index:\n                raise DistutilsGetoptError(\n                    (\"invalid %s '%s': \" \"aliased option '%s' not defined\")\n                    % (what, alias, opt)\n                )\n\n    def set_aliases(self, alias):\n        \"\"\"Set the aliases for this option parser.\"\"\"\n        self._check_alias_dict(alias, \"alias\")\n        self.alias = alias\n\n    def set_negative_aliases(self, negative_alias):\n        \"\"\"Set the negative aliases for this option parser.\n        'negative_alias' should be a dictionary mapping option names to\n        option names, both the key and value must already be defined\n        in the option table.\"\"\"\n        self._check_alias_dict(negative_alias, \"negative alias\")\n        self.negative_alias = negative_alias\n\n    def _grok_option_table(self):  # noqa: C901\n        \"\"\"Populate the various data structures that keep tabs on the\n        option table.  Called by 'getopt()' before it can do anything\n        worthwhile.\n        \"\"\"\n        self.long_opts = []\n        self.short_opts = []\n        self.short2long.clear()\n        self.repeat = {}\n\n        for option in self.option_table:\n            if len(option) == 3:\n                long, short, help = option\n                repeat = 0\n            elif len(option) == 4:\n                long, short, help, repeat = option\n            else:\n                # the option table is part of the code, so simply\n                # assert that it is correct\n                raise ValueError(\"invalid option tuple: {!r}\".format(option))\n\n            # Type- and value-check the option names\n            if not isinstance(long, str) or len(long) < 2:\n                raise DistutilsGetoptError(\n                    (\"invalid long option '%s': \" \"must be a string of length >= 2\")\n                    % long\n                )\n\n            if not ((short is None) or (isinstance(short, str) and len(short) == 1)):\n                raise DistutilsGetoptError(\n                    \"invalid short option '%s': \"\n                    \"must a single character or None\" % short\n                )\n\n            self.repeat[long] = repeat\n            self.long_opts.append(long)\n\n            if long[-1] == '=':  # option takes an argument?\n                if short:\n                    short = short + ':'\n                long = long[0:-1]\n                self.takes_arg[long] = 1\n            else:\n                # Is option is a \"negative alias\" for some other option (eg.\n                # \"quiet\" == \"!verbose\")?\n                alias_to = self.negative_alias.get(long)\n                if alias_to is not None:\n                    if self.takes_arg[alias_to]:\n                        raise DistutilsGetoptError(\n                            \"invalid negative alias '%s': \"\n                            \"aliased option '%s' takes a value\" % (long, alias_to)\n                        )\n\n                    self.long_opts[-1] = long  # XXX redundant?!\n                self.takes_arg[long] = 0\n\n            # If this is an alias option, make sure its \"takes arg\" flag is\n            # the same as the option it's aliased to.\n            alias_to = self.alias.get(long)\n            if alias_to is not None:\n                if self.takes_arg[long] != self.takes_arg[alias_to]:\n                    raise DistutilsGetoptError(\n                        \"invalid alias '%s': inconsistent with \"\n                        \"aliased option '%s' (one of them takes a value, \"\n                        \"the other doesn't\" % (long, alias_to)\n                    )\n\n            # Now enforce some bondage on the long option name, so we can\n            # later translate it to an attribute name on some object.  Have\n            # to do this a bit late to make sure we've removed any trailing\n            # '='.\n            if not longopt_re.match(long):\n                raise DistutilsGetoptError(\n                    \"invalid long option name '%s' \"\n                    \"(must be letters, numbers, hyphens only\" % long\n                )\n\n            self.attr_name[long] = self.get_attr_name(long)\n            if short:\n                self.short_opts.append(short)\n                self.short2long[short[0]] = long\n\n    def getopt(self, args=None, object=None):  # noqa: C901\n        \"\"\"Parse command-line options in args. Store as attributes on object.\n\n        If 'args' is None or not supplied, uses 'sys.argv[1:]'.  If\n        'object' is None or not supplied, creates a new OptionDummy\n        object, stores option values there, and returns a tuple (args,\n        object).  If 'object' is supplied, it is modified in place and\n        'getopt()' just returns 'args'; in both cases, the returned\n        'args' is a modified copy of the passed-in 'args' list, which\n        is left untouched.\n        \"\"\"\n        if args is None:\n            args = sys.argv[1:]\n        if object is None:\n            object = OptionDummy()\n            created_object = True\n        else:\n            created_object = False\n\n        self._grok_option_table()\n\n        short_opts = ' '.join(self.short_opts)\n        try:\n            opts, args = getopt.getopt(args, short_opts, self.long_opts)\n        except getopt.error as msg:\n            raise DistutilsArgError(msg)\n\n        for opt, val in opts:\n            if len(opt) == 2 and opt[0] == '-':  # it's a short option\n                opt = self.short2long[opt[1]]\n            else:\n                assert len(opt) > 2 and opt[:2] == '--'\n                opt = opt[2:]\n\n            alias = self.alias.get(opt)\n            if alias:\n                opt = alias\n\n            if not self.takes_arg[opt]:  # boolean option?\n                assert val == '', \"boolean option can't have value\"\n                alias = self.negative_alias.get(opt)\n                if alias:\n                    opt = alias\n                    val = 0\n                else:\n                    val = 1\n\n            attr = self.attr_name[opt]\n            # The only repeating option at the moment is 'verbose'.\n            # It has a negative option -q quiet, which should set verbose = 0.\n            if val and self.repeat.get(attr) is not None:\n                val = getattr(object, attr, 0) + 1\n            setattr(object, attr, val)\n            self.option_order.append((opt, val))\n\n        # for opts\n        if created_object:\n            return args, object\n        else:\n            return args\n\n    def get_option_order(self):\n        \"\"\"Returns the list of (option, value) tuples processed by the\n        previous run of 'getopt()'.  Raises RuntimeError if\n        'getopt()' hasn't been called yet.\n        \"\"\"\n        if self.option_order is None:\n            raise RuntimeError(\"'getopt()' hasn't been called yet\")\n        else:\n            return self.option_order\n\n    def generate_help(self, header=None):  # noqa: C901\n        \"\"\"Generate help text (a list of strings, one per suggested line of\n        output) from the option table for this FancyGetopt object.\n        \"\"\"\n        # Blithely assume the option table is good: probably wouldn't call\n        # 'generate_help()' unless you've already called 'getopt()'.\n\n        # First pass: determine maximum length of long option names\n        max_opt = 0\n        for option in self.option_table:\n            long = option[0]\n            short = option[1]\n            ell = len(long)\n            if long[-1] == '=':\n                ell = ell - 1\n            if short is not None:\n                ell = ell + 5  # \" (-x)\" where short == 'x'\n            if ell > max_opt:\n                max_opt = ell\n\n        opt_width = max_opt + 2 + 2 + 2  # room for indent + dashes + gutter\n\n        # Typical help block looks like this:\n        #   --foo       controls foonabulation\n        # Help block for longest option looks like this:\n        #   --flimflam  set the flim-flam level\n        # and with wrapped text:\n        #   --flimflam  set the flim-flam level (must be between\n        #               0 and 100, except on Tuesdays)\n        # Options with short names will have the short name shown (but\n        # it doesn't contribute to max_opt):\n        #   --foo (-f)  controls foonabulation\n        # If adding the short option would make the left column too wide,\n        # we push the explanation off to the next line\n        #   --flimflam (-l)\n        #               set the flim-flam level\n        # Important parameters:\n        #   - 2 spaces before option block start lines\n        #   - 2 dashes for each long option name\n        #   - min. 2 spaces between option and explanation (gutter)\n        #   - 5 characters (incl. space) for short option name\n\n        # Now generate lines of help text.  (If 80 columns were good enough\n        # for Jesus, then 78 columns are good enough for me!)\n        line_width = 78\n        text_width = line_width - opt_width\n        big_indent = ' ' * opt_width\n        if header:\n            lines = [header]\n        else:\n            lines = ['Option summary:']\n\n        for option in self.option_table:\n            long, short, help = option[:3]\n            text = wrap_text(help, text_width)\n            if long[-1] == '=':\n                long = long[0:-1]\n\n            # Case 1: no short option at all (makes life easy)\n            if short is None:\n                if text:\n                    lines.append(\"  --%-*s  %s\" % (max_opt, long, text[0]))\n                else:\n                    lines.append(\"  --%-*s  \" % (max_opt, long))\n\n            # Case 2: we have a short option, so we have to include it\n            # just after the long option\n            else:\n                opt_names = \"{} (-{})\".format(long, short)\n                if text:\n                    lines.append(\"  --%-*s  %s\" % (max_opt, opt_names, text[0]))\n                else:\n                    lines.append(\"  --%-*s\" % opt_names)\n\n            for ell in text[1:]:\n                lines.append(big_indent + ell)\n        return lines\n\n    def print_help(self, header=None, file=None):\n        if file is None:\n            file = sys.stdout\n        for line in self.generate_help(header):\n            file.write(line + \"\\n\")\n\n\ndef fancy_getopt(options, negative_opt, object, args):\n    parser = FancyGetopt(options)\n    parser.set_negative_aliases(negative_opt)\n    return parser.getopt(args, object)\n\n\nWS_TRANS = {ord(_wschar): ' ' for _wschar in string.whitespace}\n\n\ndef wrap_text(text, width):\n    \"\"\"wrap_text(text : string, width : int) -> [string]\n\n    Split 'text' into multiple lines of no more than 'width' characters\n    each, and return the list of strings that results.\n    \"\"\"\n    if text is None:\n        return []\n    if len(text) <= width:\n        return [text]\n\n    text = text.expandtabs()\n    text = text.translate(WS_TRANS)\n    chunks = re.split(r'( +|-+)', text)\n    chunks = [ch for ch in chunks if ch]  # ' - ' results in empty strings\n    lines = []\n\n    while chunks:\n        cur_line = []  # list of chunks (to-be-joined)\n        cur_len = 0  # length of current line\n\n        while chunks:\n            ell = len(chunks[0])\n            if cur_len + ell <= width:  # can squeeze (at least) this chunk in\n                cur_line.append(chunks[0])\n                del chunks[0]\n                cur_len = cur_len + ell\n            else:  # this line is full\n                # drop last chunk if all space\n                if cur_line and cur_line[-1][0] == ' ':\n                    del cur_line[-1]\n                break\n\n        if chunks:  # any chunks left to process?\n            # if the current line is still empty, then we had a single\n            # chunk that's too big too fit on a line -- so we break\n            # down and break it up at the line width\n            if cur_len == 0:\n                cur_line.append(chunks[0][0:width])\n                chunks[0] = chunks[0][width:]\n\n            # all-whitespace chunks at the end of a line can be discarded\n            # (and we know from the re.split above that if a chunk has\n            # *any* whitespace, it is *all* whitespace)\n            if chunks[0][0] == ' ':\n                del chunks[0]\n\n        # and store this line in the list-of-all-lines -- as a single\n        # string, of course!\n        lines.append(''.join(cur_line))\n\n    return lines\n\n\ndef translate_longopt(opt):\n    \"\"\"Convert a long option name to a valid Python identifier by\n    changing \"-\" to \"_\".\n    \"\"\"\n    return opt.translate(longopt_xlate)\n\n\nclass OptionDummy:\n    \"\"\"Dummy class just used as a place to hold command-line option\n    values as instance attributes.\"\"\"\n\n    def __init__(self, options=[]):\n        \"\"\"Create a new OptionDummy instance.  The attributes listed in\n        'options' will be initialized to None.\"\"\"\n        for opt in options:\n            setattr(self, opt, None)\n\n\nif __name__ == \"__main__\":\n    text = \"\"\"\\\nTra-la-la, supercalifragilisticexpialidocious.\nHow *do* you spell that odd word, anyways?\n(Someone ask Mary -- she'll know [or she'll\nsay, \"How should I know?\"].)\"\"\"\n\n    for w in (10, 20, 30, 40):\n        print(\"width: %d\" % w)\n        print(\"\\n\".join(wrap_text(text, w)))\n        print()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/file_util.py",
    "content": "\"\"\"distutils.file_util\n\nUtility functions for operating on single files.\n\"\"\"\n\nimport os\nfrom distutils.errors import DistutilsFileError\nfrom distutils import log\n\n# for generating verbose output in 'copy_file()'\n_copy_action = {None: 'copying', 'hard': 'hard linking', 'sym': 'symbolically linking'}\n\n\ndef _copy_file_contents(src, dst, buffer_size=16 * 1024):  # noqa: C901\n    \"\"\"Copy the file 'src' to 'dst'; both must be filenames.  Any error\n    opening either file, reading from 'src', or writing to 'dst', raises\n    DistutilsFileError.  Data is read/written in chunks of 'buffer_size'\n    bytes (default 16k).  No attempt is made to handle anything apart from\n    regular files.\n    \"\"\"\n    # Stolen from shutil module in the standard library, but with\n    # custom error-handling added.\n    fsrc = None\n    fdst = None\n    try:\n        try:\n            fsrc = open(src, 'rb')\n        except OSError as e:\n            raise DistutilsFileError(\"could not open '{}': {}\".format(src, e.strerror))\n\n        if os.path.exists(dst):\n            try:\n                os.unlink(dst)\n            except OSError as e:\n                raise DistutilsFileError(\n                    \"could not delete '{}': {}\".format(dst, e.strerror)\n                )\n\n        try:\n            fdst = open(dst, 'wb')\n        except OSError as e:\n            raise DistutilsFileError(\n                \"could not create '{}': {}\".format(dst, e.strerror)\n            )\n\n        while True:\n            try:\n                buf = fsrc.read(buffer_size)\n            except OSError as e:\n                raise DistutilsFileError(\n                    \"could not read from '{}': {}\".format(src, e.strerror)\n                )\n\n            if not buf:\n                break\n\n            try:\n                fdst.write(buf)\n            except OSError as e:\n                raise DistutilsFileError(\n                    \"could not write to '{}': {}\".format(dst, e.strerror)\n                )\n    finally:\n        if fdst:\n            fdst.close()\n        if fsrc:\n            fsrc.close()\n\n\ndef copy_file(  # noqa: C901\n    src,\n    dst,\n    preserve_mode=1,\n    preserve_times=1,\n    update=0,\n    link=None,\n    verbose=1,\n    dry_run=0,\n):\n    \"\"\"Copy a file 'src' to 'dst'.  If 'dst' is a directory, then 'src' is\n    copied there with the same name; otherwise, it must be a filename.  (If\n    the file exists, it will be ruthlessly clobbered.)  If 'preserve_mode'\n    is true (the default), the file's mode (type and permission bits, or\n    whatever is analogous on the current platform) is copied.  If\n    'preserve_times' is true (the default), the last-modified and\n    last-access times are copied as well.  If 'update' is true, 'src' will\n    only be copied if 'dst' does not exist, or if 'dst' does exist but is\n    older than 'src'.\n\n    'link' allows you to make hard links (os.link) or symbolic links\n    (os.symlink) instead of copying: set it to \"hard\" or \"sym\"; if it is\n    None (the default), files are copied.  Don't set 'link' on systems that\n    don't support it: 'copy_file()' doesn't check if hard or symbolic\n    linking is available. If hardlink fails, falls back to\n    _copy_file_contents().\n\n    Under Mac OS, uses the native file copy function in macostools; on\n    other systems, uses '_copy_file_contents()' to copy file contents.\n\n    Return a tuple (dest_name, copied): 'dest_name' is the actual name of\n    the output file, and 'copied' is true if the file was copied (or would\n    have been copied, if 'dry_run' true).\n    \"\"\"\n    # XXX if the destination file already exists, we clobber it if\n    # copying, but blow up if linking.  Hmmm.  And I don't know what\n    # macostools.copyfile() does.  Should definitely be consistent, and\n    # should probably blow up if destination exists and we would be\n    # changing it (ie. it's not already a hard/soft link to src OR\n    # (not update) and (src newer than dst).\n\n    from distutils.dep_util import newer\n    from stat import ST_ATIME, ST_MTIME, ST_MODE, S_IMODE\n\n    if not os.path.isfile(src):\n        raise DistutilsFileError(\n            \"can't copy '%s': doesn't exist or not a regular file\" % src\n        )\n\n    if os.path.isdir(dst):\n        dir = dst\n        dst = os.path.join(dst, os.path.basename(src))\n    else:\n        dir = os.path.dirname(dst)\n\n    if update and not newer(src, dst):\n        if verbose >= 1:\n            log.debug(\"not copying %s (output up-to-date)\", src)\n        return (dst, 0)\n\n    try:\n        action = _copy_action[link]\n    except KeyError:\n        raise ValueError(\"invalid value '%s' for 'link' argument\" % link)\n\n    if verbose >= 1:\n        if os.path.basename(dst) == os.path.basename(src):\n            log.info(\"%s %s -> %s\", action, src, dir)\n        else:\n            log.info(\"%s %s -> %s\", action, src, dst)\n\n    if dry_run:\n        return (dst, 1)\n\n    # If linking (hard or symbolic), use the appropriate system call\n    # (Unix only, of course, but that's the caller's responsibility)\n    elif link == 'hard':\n        if not (os.path.exists(dst) and os.path.samefile(src, dst)):\n            try:\n                os.link(src, dst)\n                return (dst, 1)\n            except OSError:\n                # If hard linking fails, fall back on copying file\n                # (some special filesystems don't support hard linking\n                #  even under Unix, see issue #8876).\n                pass\n    elif link == 'sym':\n        if not (os.path.exists(dst) and os.path.samefile(src, dst)):\n            os.symlink(src, dst)\n            return (dst, 1)\n\n    # Otherwise (non-Mac, not linking), copy the file contents and\n    # (optionally) copy the times and mode.\n    _copy_file_contents(src, dst)\n    if preserve_mode or preserve_times:\n        st = os.stat(src)\n\n        # According to David Ascher <da@ski.org>, utime() should be done\n        # before chmod() (at least under NT).\n        if preserve_times:\n            os.utime(dst, (st[ST_ATIME], st[ST_MTIME]))\n        if preserve_mode:\n            os.chmod(dst, S_IMODE(st[ST_MODE]))\n\n    return (dst, 1)\n\n\n# XXX I suspect this is Unix-specific -- need porting help!\ndef move_file(src, dst, verbose=1, dry_run=0):  # noqa: C901\n\n    \"\"\"Move a file 'src' to 'dst'.  If 'dst' is a directory, the file will\n    be moved into it with the same name; otherwise, 'src' is just renamed\n    to 'dst'.  Return the new full name of the file.\n\n    Handles cross-device moves on Unix using 'copy_file()'.  What about\n    other systems???\n    \"\"\"\n    from os.path import exists, isfile, isdir, basename, dirname\n    import errno\n\n    if verbose >= 1:\n        log.info(\"moving %s -> %s\", src, dst)\n\n    if dry_run:\n        return dst\n\n    if not isfile(src):\n        raise DistutilsFileError(\"can't move '%s': not a regular file\" % src)\n\n    if isdir(dst):\n        dst = os.path.join(dst, basename(src))\n    elif exists(dst):\n        raise DistutilsFileError(\n            \"can't move '{}': destination '{}' already exists\".format(src, dst)\n        )\n\n    if not isdir(dirname(dst)):\n        raise DistutilsFileError(\n            \"can't move '{}': destination '{}' not a valid path\".format(src, dst)\n        )\n\n    copy_it = False\n    try:\n        os.rename(src, dst)\n    except OSError as e:\n        (num, msg) = e.args\n        if num == errno.EXDEV:\n            copy_it = True\n        else:\n            raise DistutilsFileError(\n                \"couldn't move '{}' to '{}': {}\".format(src, dst, msg)\n            )\n\n    if copy_it:\n        copy_file(src, dst, verbose=verbose)\n        try:\n            os.unlink(src)\n        except OSError as e:\n            (num, msg) = e.args\n            try:\n                os.unlink(dst)\n            except OSError:\n                pass\n            raise DistutilsFileError(\n                \"couldn't move '%s' to '%s' by copy/delete: \"\n                \"delete '%s' failed: %s\" % (src, dst, src, msg)\n            )\n    return dst\n\n\ndef write_file(filename, contents):\n    \"\"\"Create a file with the specified name and write 'contents' (a\n    sequence of strings without line terminators) to it.\n    \"\"\"\n    f = open(filename, \"w\")\n    try:\n        for line in contents:\n            f.write(line + \"\\n\")\n    finally:\n        f.close()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/filelist.py",
    "content": "\"\"\"distutils.filelist\n\nProvides the FileList class, used for poking about the filesystem\nand building lists of files.\n\"\"\"\n\nimport os\nimport re\nimport fnmatch\nimport functools\n\nfrom distutils.util import convert_path\nfrom distutils.errors import DistutilsTemplateError, DistutilsInternalError\nfrom distutils import log\n\n\nclass FileList:\n    \"\"\"A list of files built by on exploring the filesystem and filtered by\n    applying various patterns to what we find there.\n\n    Instance attributes:\n      dir\n        directory from which files will be taken -- only used if\n        'allfiles' not supplied to constructor\n      files\n        list of filenames currently being built/filtered/manipulated\n      allfiles\n        complete list of files under consideration (ie. without any\n        filtering applied)\n    \"\"\"\n\n    def __init__(self, warn=None, debug_print=None):\n        # ignore argument to FileList, but keep them for backwards\n        # compatibility\n        self.allfiles = None\n        self.files = []\n\n    def set_allfiles(self, allfiles):\n        self.allfiles = allfiles\n\n    def findall(self, dir=os.curdir):\n        self.allfiles = findall(dir)\n\n    def debug_print(self, msg):\n        \"\"\"Print 'msg' to stdout if the global DEBUG (taken from the\n        DISTUTILS_DEBUG environment variable) flag is true.\n        \"\"\"\n        from distutils.debug import DEBUG\n\n        if DEBUG:\n            print(msg)\n\n    # Collection methods\n\n    def append(self, item):\n        self.files.append(item)\n\n    def extend(self, items):\n        self.files.extend(items)\n\n    def sort(self):\n        # Not a strict lexical sort!\n        sortable_files = sorted(map(os.path.split, self.files))\n        self.files = []\n        for sort_tuple in sortable_files:\n            self.files.append(os.path.join(*sort_tuple))\n\n    # Other miscellaneous utility methods\n\n    def remove_duplicates(self):\n        # Assumes list has been sorted!\n        for i in range(len(self.files) - 1, 0, -1):\n            if self.files[i] == self.files[i - 1]:\n                del self.files[i]\n\n    # \"File template\" methods\n\n    def _parse_template_line(self, line):\n        words = line.split()\n        action = words[0]\n\n        patterns = dir = dir_pattern = None\n\n        if action in ('include', 'exclude', 'global-include', 'global-exclude'):\n            if len(words) < 2:\n                raise DistutilsTemplateError(\n                    \"'%s' expects <pattern1> <pattern2> ...\" % action\n                )\n            patterns = [convert_path(w) for w in words[1:]]\n        elif action in ('recursive-include', 'recursive-exclude'):\n            if len(words) < 3:\n                raise DistutilsTemplateError(\n                    \"'%s' expects <dir> <pattern1> <pattern2> ...\" % action\n                )\n            dir = convert_path(words[1])\n            patterns = [convert_path(w) for w in words[2:]]\n        elif action in ('graft', 'prune'):\n            if len(words) != 2:\n                raise DistutilsTemplateError(\n                    \"'%s' expects a single <dir_pattern>\" % action\n                )\n            dir_pattern = convert_path(words[1])\n        else:\n            raise DistutilsTemplateError(\"unknown action '%s'\" % action)\n\n        return (action, patterns, dir, dir_pattern)\n\n    def process_template_line(self, line):  # noqa: C901\n        # Parse the line: split it up, make sure the right number of words\n        # is there, and return the relevant words.  'action' is always\n        # defined: it's the first word of the line.  Which of the other\n        # three are defined depends on the action; it'll be either\n        # patterns, (dir and patterns), or (dir_pattern).\n        (action, patterns, dir, dir_pattern) = self._parse_template_line(line)\n\n        # OK, now we know that the action is valid and we have the\n        # right number of words on the line for that action -- so we\n        # can proceed with minimal error-checking.\n        if action == 'include':\n            self.debug_print(\"include \" + ' '.join(patterns))\n            for pattern in patterns:\n                if not self.include_pattern(pattern, anchor=1):\n                    log.warn(\"warning: no files found matching '%s'\", pattern)\n\n        elif action == 'exclude':\n            self.debug_print(\"exclude \" + ' '.join(patterns))\n            for pattern in patterns:\n                if not self.exclude_pattern(pattern, anchor=1):\n                    log.warn(\n                        (\n                            \"warning: no previously-included files \"\n                            \"found matching '%s'\"\n                        ),\n                        pattern,\n                    )\n\n        elif action == 'global-include':\n            self.debug_print(\"global-include \" + ' '.join(patterns))\n            for pattern in patterns:\n                if not self.include_pattern(pattern, anchor=0):\n                    log.warn(\n                        (\n                            \"warning: no files found matching '%s' \"\n                            \"anywhere in distribution\"\n                        ),\n                        pattern,\n                    )\n\n        elif action == 'global-exclude':\n            self.debug_print(\"global-exclude \" + ' '.join(patterns))\n            for pattern in patterns:\n                if not self.exclude_pattern(pattern, anchor=0):\n                    log.warn(\n                        (\n                            \"warning: no previously-included files matching \"\n                            \"'%s' found anywhere in distribution\"\n                        ),\n                        pattern,\n                    )\n\n        elif action == 'recursive-include':\n            self.debug_print(\"recursive-include {} {}\".format(dir, ' '.join(patterns)))\n            for pattern in patterns:\n                if not self.include_pattern(pattern, prefix=dir):\n                    msg = (\n                        \"warning: no files found matching '%s' \" \"under directory '%s'\"\n                    )\n                    log.warn(msg, pattern, dir)\n\n        elif action == 'recursive-exclude':\n            self.debug_print(\"recursive-exclude {} {}\".format(dir, ' '.join(patterns)))\n            for pattern in patterns:\n                if not self.exclude_pattern(pattern, prefix=dir):\n                    log.warn(\n                        (\n                            \"warning: no previously-included files matching \"\n                            \"'%s' found under directory '%s'\"\n                        ),\n                        pattern,\n                        dir,\n                    )\n\n        elif action == 'graft':\n            self.debug_print(\"graft \" + dir_pattern)\n            if not self.include_pattern(None, prefix=dir_pattern):\n                log.warn(\"warning: no directories found matching '%s'\", dir_pattern)\n\n        elif action == 'prune':\n            self.debug_print(\"prune \" + dir_pattern)\n            if not self.exclude_pattern(None, prefix=dir_pattern):\n                log.warn(\n                    (\"no previously-included directories found \" \"matching '%s'\"),\n                    dir_pattern,\n                )\n        else:\n            raise DistutilsInternalError(\n                \"this cannot happen: invalid action '%s'\" % action\n            )\n\n    # Filtering/selection methods\n\n    def include_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):\n        \"\"\"Select strings (presumably filenames) from 'self.files' that\n        match 'pattern', a Unix-style wildcard (glob) pattern.  Patterns\n        are not quite the same as implemented by the 'fnmatch' module: '*'\n        and '?'  match non-special characters, where \"special\" is platform-\n        dependent: slash on Unix; colon, slash, and backslash on\n        DOS/Windows; and colon on Mac OS.\n\n        If 'anchor' is true (the default), then the pattern match is more\n        stringent: \"*.py\" will match \"foo.py\" but not \"foo/bar.py\".  If\n        'anchor' is false, both of these will match.\n\n        If 'prefix' is supplied, then only filenames starting with 'prefix'\n        (itself a pattern) and ending with 'pattern', with anything in between\n        them, will match.  'anchor' is ignored in this case.\n\n        If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and\n        'pattern' is assumed to be either a string containing a regex or a\n        regex object -- no translation is done, the regex is just compiled\n        and used as-is.\n\n        Selected strings will be added to self.files.\n\n        Return True if files are found, False otherwise.\n        \"\"\"\n        # XXX docstring lying about what the special chars are?\n        files_found = False\n        pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)\n        self.debug_print(\"include_pattern: applying regex r'%s'\" % pattern_re.pattern)\n\n        # delayed loading of allfiles list\n        if self.allfiles is None:\n            self.findall()\n\n        for name in self.allfiles:\n            if pattern_re.search(name):\n                self.debug_print(\" adding \" + name)\n                self.files.append(name)\n                files_found = True\n        return files_found\n\n    def exclude_pattern(self, pattern, anchor=1, prefix=None, is_regex=0):\n        \"\"\"Remove strings (presumably filenames) from 'files' that match\n        'pattern'.  Other parameters are the same as for\n        'include_pattern()', above.\n        The list 'self.files' is modified in place.\n        Return True if files are found, False otherwise.\n        \"\"\"\n        files_found = False\n        pattern_re = translate_pattern(pattern, anchor, prefix, is_regex)\n        self.debug_print(\"exclude_pattern: applying regex r'%s'\" % pattern_re.pattern)\n        for i in range(len(self.files) - 1, -1, -1):\n            if pattern_re.search(self.files[i]):\n                self.debug_print(\" removing \" + self.files[i])\n                del self.files[i]\n                files_found = True\n        return files_found\n\n\n# Utility functions\n\n\ndef _find_all_simple(path):\n    \"\"\"\n    Find all files under 'path'\n    \"\"\"\n    all_unique = _UniqueDirs.filter(os.walk(path, followlinks=True))\n    results = (\n        os.path.join(base, file) for base, dirs, files in all_unique for file in files\n    )\n    return filter(os.path.isfile, results)\n\n\nclass _UniqueDirs(set):\n    \"\"\"\n    Exclude previously-seen dirs from walk results,\n    avoiding infinite recursion.\n    Ref https://bugs.python.org/issue44497.\n    \"\"\"\n\n    def __call__(self, walk_item):\n        \"\"\"\n        Given an item from an os.walk result, determine\n        if the item represents a unique dir for this instance\n        and if not, prevent further traversal.\n        \"\"\"\n        base, dirs, files = walk_item\n        stat = os.stat(base)\n        candidate = stat.st_dev, stat.st_ino\n        found = candidate in self\n        if found:\n            del dirs[:]\n        self.add(candidate)\n        return not found\n\n    @classmethod\n    def filter(cls, items):\n        return filter(cls(), items)\n\n\ndef findall(dir=os.curdir):\n    \"\"\"\n    Find all files under 'dir' and return the list of full filenames.\n    Unless dir is '.', return full filenames with dir prepended.\n    \"\"\"\n    files = _find_all_simple(dir)\n    if dir == os.curdir:\n        make_rel = functools.partial(os.path.relpath, start=dir)\n        files = map(make_rel, files)\n    return list(files)\n\n\ndef glob_to_re(pattern):\n    \"\"\"Translate a shell-like glob pattern to a regular expression; return\n    a string containing the regex.  Differs from 'fnmatch.translate()' in\n    that '*' does not match \"special characters\" (which are\n    platform-specific).\n    \"\"\"\n    pattern_re = fnmatch.translate(pattern)\n\n    # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which\n    # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,\n    # and by extension they shouldn't match such \"special characters\" under\n    # any OS.  So change all non-escaped dots in the RE to match any\n    # character except the special characters (currently: just os.sep).\n    sep = os.sep\n    if os.sep == '\\\\':\n        # we're using a regex to manipulate a regex, so we need\n        # to escape the backslash twice\n        sep = r'\\\\\\\\'\n    escaped = r'\\1[^%s]' % sep\n    pattern_re = re.sub(r'((?<!\\\\)(\\\\\\\\)*)\\.', escaped, pattern_re)\n    return pattern_re\n\n\ndef translate_pattern(pattern, anchor=1, prefix=None, is_regex=0):\n    \"\"\"Translate a shell-like wildcard pattern to a compiled regular\n    expression.  Return the compiled regex.  If 'is_regex' true,\n    then 'pattern' is directly compiled to a regex (if it's a string)\n    or just returned as-is (assumes it's a regex object).\n    \"\"\"\n    if is_regex:\n        if isinstance(pattern, str):\n            return re.compile(pattern)\n        else:\n            return pattern\n\n    # ditch start and end characters\n    start, _, end = glob_to_re('_').partition('_')\n\n    if pattern:\n        pattern_re = glob_to_re(pattern)\n        assert pattern_re.startswith(start) and pattern_re.endswith(end)\n    else:\n        pattern_re = ''\n\n    if prefix is not None:\n        prefix_re = glob_to_re(prefix)\n        assert prefix_re.startswith(start) and prefix_re.endswith(end)\n        prefix_re = prefix_re[len(start) : len(prefix_re) - len(end)]\n        sep = os.sep\n        if os.sep == '\\\\':\n            sep = r'\\\\'\n        pattern_re = pattern_re[len(start) : len(pattern_re) - len(end)]\n        pattern_re = r'{}\\A{}{}.*{}{}'.format(start, prefix_re, sep, pattern_re, end)\n    else:  # no prefix -- respect anchor flag\n        if anchor:\n            pattern_re = r'{}\\A{}'.format(start, pattern_re[len(start) :])\n\n    return re.compile(pattern_re)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/log.py",
    "content": "\"\"\"A simple log mechanism styled after PEP 282.\"\"\"\n\n# The class here is styled after PEP 282 so that it could later be\n# replaced with a standard Python logging implementation.\n\nimport sys\n\nDEBUG = 1\nINFO = 2\nWARN = 3\nERROR = 4\nFATAL = 5\n\n\nclass Log:\n    def __init__(self, threshold=WARN):\n        self.threshold = threshold\n\n    def _log(self, level, msg, args):\n        if level not in (DEBUG, INFO, WARN, ERROR, FATAL):\n            raise ValueError('%s wrong log level' % str(level))\n\n        if level >= self.threshold:\n            if args:\n                msg = msg % args\n            if level in (WARN, ERROR, FATAL):\n                stream = sys.stderr\n            else:\n                stream = sys.stdout\n            try:\n                stream.write('%s\\n' % msg)\n            except UnicodeEncodeError:\n                # emulate backslashreplace error handler\n                encoding = stream.encoding\n                msg = msg.encode(encoding, \"backslashreplace\").decode(encoding)\n                stream.write('%s\\n' % msg)\n            stream.flush()\n\n    def log(self, level, msg, *args):\n        self._log(level, msg, args)\n\n    def debug(self, msg, *args):\n        self._log(DEBUG, msg, args)\n\n    def info(self, msg, *args):\n        self._log(INFO, msg, args)\n\n    def warn(self, msg, *args):\n        self._log(WARN, msg, args)\n\n    def error(self, msg, *args):\n        self._log(ERROR, msg, args)\n\n    def fatal(self, msg, *args):\n        self._log(FATAL, msg, args)\n\n\n_global_log = Log()\nlog = _global_log.log\ndebug = _global_log.debug\ninfo = _global_log.info\nwarn = _global_log.warn\nerror = _global_log.error\nfatal = _global_log.fatal\n\n\ndef set_threshold(level):\n    # return the old threshold for use from tests\n    old = _global_log.threshold\n    _global_log.threshold = level\n    return old\n\n\ndef set_verbosity(v):\n    if v <= 0:\n        set_threshold(WARN)\n    elif v == 1:\n        set_threshold(INFO)\n    elif v >= 2:\n        set_threshold(DEBUG)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/msvc9compiler.py",
    "content": "\"\"\"distutils.msvc9compiler\n\nContains MSVCCompiler, an implementation of the abstract CCompiler class\nfor the Microsoft Visual Studio 2008.\n\nThe module is compatible with VS 2005 and VS 2008. You can find legacy support\nfor older versions of VS in distutils.msvccompiler.\n\"\"\"\n\n# Written by Perry Stoll\n# hacked by Robin Becker and Thomas Heller to do a better job of\n#   finding DevStudio (through the registry)\n# ported to VS2005 and VS 2008 by Christian Heimes\n\nimport os\nimport subprocess\nimport sys\nimport re\nimport warnings\n\nfrom distutils.errors import (\n    DistutilsExecError,\n    DistutilsPlatformError,\n    CompileError,\n    LibError,\n    LinkError,\n)\nfrom distutils.ccompiler import CCompiler, gen_lib_options\nfrom distutils import log\nfrom distutils.util import get_platform\n\nimport winreg\n\nwarnings.warn(\n    \"msvc9compiler is deprecated and slated to be removed \"\n    \"in the future. Please discontinue use or file an issue \"\n    \"with pypa/distutils describing your use case.\",\n    DeprecationWarning,\n)\n\nRegOpenKeyEx = winreg.OpenKeyEx\nRegEnumKey = winreg.EnumKey\nRegEnumValue = winreg.EnumValue\nRegError = winreg.error\n\nHKEYS = (\n    winreg.HKEY_USERS,\n    winreg.HKEY_CURRENT_USER,\n    winreg.HKEY_LOCAL_MACHINE,\n    winreg.HKEY_CLASSES_ROOT,\n)\n\nNATIVE_WIN64 = sys.platform == 'win32' and sys.maxsize > 2**32\nif NATIVE_WIN64:\n    # Visual C++ is a 32-bit application, so we need to look in\n    # the corresponding registry branch, if we're running a\n    # 64-bit Python on Win64\n    VS_BASE = r\"Software\\Wow6432Node\\Microsoft\\VisualStudio\\%0.1f\"\n    WINSDK_BASE = r\"Software\\Wow6432Node\\Microsoft\\Microsoft SDKs\\Windows\"\n    NET_BASE = r\"Software\\Wow6432Node\\Microsoft\\.NETFramework\"\nelse:\n    VS_BASE = r\"Software\\Microsoft\\VisualStudio\\%0.1f\"\n    WINSDK_BASE = r\"Software\\Microsoft\\Microsoft SDKs\\Windows\"\n    NET_BASE = r\"Software\\Microsoft\\.NETFramework\"\n\n# A map keyed by get_platform() return values to values accepted by\n# 'vcvarsall.bat'.  Note a cross-compile may combine these (eg, 'x86_amd64' is\n# the param to cross-compile on x86 targeting amd64.)\nPLAT_TO_VCVARS = {\n    'win32': 'x86',\n    'win-amd64': 'amd64',\n}\n\n\nclass Reg:\n    \"\"\"Helper class to read values from the registry\"\"\"\n\n    def get_value(cls, path, key):\n        for base in HKEYS:\n            d = cls.read_values(base, path)\n            if d and key in d:\n                return d[key]\n        raise KeyError(key)\n\n    get_value = classmethod(get_value)\n\n    def read_keys(cls, base, key):\n        \"\"\"Return list of registry keys.\"\"\"\n        try:\n            handle = RegOpenKeyEx(base, key)\n        except RegError:\n            return None\n        L = []\n        i = 0\n        while True:\n            try:\n                k = RegEnumKey(handle, i)\n            except RegError:\n                break\n            L.append(k)\n            i += 1\n        return L\n\n    read_keys = classmethod(read_keys)\n\n    def read_values(cls, base, key):\n        \"\"\"Return dict of registry keys and values.\n\n        All names are converted to lowercase.\n        \"\"\"\n        try:\n            handle = RegOpenKeyEx(base, key)\n        except RegError:\n            return None\n        d = {}\n        i = 0\n        while True:\n            try:\n                name, value, type = RegEnumValue(handle, i)\n            except RegError:\n                break\n            name = name.lower()\n            d[cls.convert_mbcs(name)] = cls.convert_mbcs(value)\n            i += 1\n        return d\n\n    read_values = classmethod(read_values)\n\n    def convert_mbcs(s):\n        dec = getattr(s, \"decode\", None)\n        if dec is not None:\n            try:\n                s = dec(\"mbcs\")\n            except UnicodeError:\n                pass\n        return s\n\n    convert_mbcs = staticmethod(convert_mbcs)\n\n\nclass MacroExpander:\n    def __init__(self, version):\n        self.macros = {}\n        self.vsbase = VS_BASE % version\n        self.load_macros(version)\n\n    def set_macro(self, macro, path, key):\n        self.macros[\"$(%s)\" % macro] = Reg.get_value(path, key)\n\n    def load_macros(self, version):\n        self.set_macro(\"VCInstallDir\", self.vsbase + r\"\\Setup\\VC\", \"productdir\")\n        self.set_macro(\"VSInstallDir\", self.vsbase + r\"\\Setup\\VS\", \"productdir\")\n        self.set_macro(\"FrameworkDir\", NET_BASE, \"installroot\")\n        try:\n            if version >= 8.0:\n                self.set_macro(\"FrameworkSDKDir\", NET_BASE, \"sdkinstallrootv2.0\")\n            else:\n                raise KeyError(\"sdkinstallrootv2.0\")\n        except KeyError:\n            raise DistutilsPlatformError(\n                \"\"\"Python was built with Visual Studio 2008;\nextensions must be built with a compiler than can generate compatible binaries.\nVisual Studio 2008 was not found on this system. If you have Cygwin installed,\nyou can try compiling with MingW32, by passing \"-c mingw32\" to setup.py.\"\"\"\n            )\n\n        if version >= 9.0:\n            self.set_macro(\"FrameworkVersion\", self.vsbase, \"clr version\")\n            self.set_macro(\"WindowsSdkDir\", WINSDK_BASE, \"currentinstallfolder\")\n        else:\n            p = r\"Software\\Microsoft\\NET Framework Setup\\Product\"\n            for base in HKEYS:\n                try:\n                    h = RegOpenKeyEx(base, p)\n                except RegError:\n                    continue\n                key = RegEnumKey(h, 0)\n                d = Reg.get_value(base, r\"{}\\{}\".format(p, key))\n                self.macros[\"$(FrameworkVersion)\"] = d[\"version\"]\n\n    def sub(self, s):\n        for k, v in self.macros.items():\n            s = s.replace(k, v)\n        return s\n\n\ndef get_build_version():\n    \"\"\"Return the version of MSVC that was used to build Python.\n\n    For Python 2.3 and up, the version number is included in\n    sys.version.  For earlier versions, assume the compiler is MSVC 6.\n    \"\"\"\n    prefix = \"MSC v.\"\n    i = sys.version.find(prefix)\n    if i == -1:\n        return 6\n    i = i + len(prefix)\n    s, rest = sys.version[i:].split(\" \", 1)\n    majorVersion = int(s[:-2]) - 6\n    if majorVersion >= 13:\n        # v13 was skipped and should be v14\n        majorVersion += 1\n    minorVersion = int(s[2:3]) / 10.0\n    # I don't think paths are affected by minor version in version 6\n    if majorVersion == 6:\n        minorVersion = 0\n    if majorVersion >= 6:\n        return majorVersion + minorVersion\n    # else we don't know what version of the compiler this is\n    return None\n\n\ndef normalize_and_reduce_paths(paths):\n    \"\"\"Return a list of normalized paths with duplicates removed.\n\n    The current order of paths is maintained.\n    \"\"\"\n    # Paths are normalized so things like:  /a and /a/ aren't both preserved.\n    reduced_paths = []\n    for p in paths:\n        np = os.path.normpath(p)\n        # XXX(nnorwitz): O(n**2), if reduced_paths gets long perhaps use a set.\n        if np not in reduced_paths:\n            reduced_paths.append(np)\n    return reduced_paths\n\n\ndef removeDuplicates(variable):\n    \"\"\"Remove duplicate values of an environment variable.\"\"\"\n    oldList = variable.split(os.pathsep)\n    newList = []\n    for i in oldList:\n        if i not in newList:\n            newList.append(i)\n    newVariable = os.pathsep.join(newList)\n    return newVariable\n\n\ndef find_vcvarsall(version):\n    \"\"\"Find the vcvarsall.bat file\n\n    At first it tries to find the productdir of VS 2008 in the registry. If\n    that fails it falls back to the VS90COMNTOOLS env var.\n    \"\"\"\n    vsbase = VS_BASE % version\n    try:\n        productdir = Reg.get_value(r\"%s\\Setup\\VC\" % vsbase, \"productdir\")\n    except KeyError:\n        log.debug(\"Unable to find productdir in registry\")\n        productdir = None\n\n    if not productdir or not os.path.isdir(productdir):\n        toolskey = \"VS%0.f0COMNTOOLS\" % version\n        toolsdir = os.environ.get(toolskey, None)\n\n        if toolsdir and os.path.isdir(toolsdir):\n            productdir = os.path.join(toolsdir, os.pardir, os.pardir, \"VC\")\n            productdir = os.path.abspath(productdir)\n            if not os.path.isdir(productdir):\n                log.debug(\"%s is not a valid directory\" % productdir)\n                return None\n        else:\n            log.debug(\"Env var %s is not set or invalid\" % toolskey)\n    if not productdir:\n        log.debug(\"No productdir found\")\n        return None\n    vcvarsall = os.path.join(productdir, \"vcvarsall.bat\")\n    if os.path.isfile(vcvarsall):\n        return vcvarsall\n    log.debug(\"Unable to find vcvarsall.bat\")\n    return None\n\n\ndef query_vcvarsall(version, arch=\"x86\"):\n    \"\"\"Launch vcvarsall.bat and read the settings from its environment\"\"\"\n    vcvarsall = find_vcvarsall(version)\n    interesting = {\"include\", \"lib\", \"libpath\", \"path\"}\n    result = {}\n\n    if vcvarsall is None:\n        raise DistutilsPlatformError(\"Unable to find vcvarsall.bat\")\n    log.debug(\"Calling 'vcvarsall.bat %s' (version=%s)\", arch, version)\n    popen = subprocess.Popen(\n        '\"{}\" {} & set'.format(vcvarsall, arch),\n        stdout=subprocess.PIPE,\n        stderr=subprocess.PIPE,\n    )\n    try:\n        stdout, stderr = popen.communicate()\n        if popen.wait() != 0:\n            raise DistutilsPlatformError(stderr.decode(\"mbcs\"))\n\n        stdout = stdout.decode(\"mbcs\")\n        for line in stdout.split(\"\\n\"):\n            line = Reg.convert_mbcs(line)\n            if '=' not in line:\n                continue\n            line = line.strip()\n            key, value = line.split('=', 1)\n            key = key.lower()\n            if key in interesting:\n                if value.endswith(os.pathsep):\n                    value = value[:-1]\n                result[key] = removeDuplicates(value)\n\n    finally:\n        popen.stdout.close()\n        popen.stderr.close()\n\n    if len(result) != len(interesting):\n        raise ValueError(str(list(result.keys())))\n\n    return result\n\n\n# More globals\nVERSION = get_build_version()\n# MACROS = MacroExpander(VERSION)\n\n\nclass MSVCCompiler(CCompiler):\n    \"\"\"Concrete class that implements an interface to Microsoft Visual C++,\n    as defined by the CCompiler abstract class.\"\"\"\n\n    compiler_type = 'msvc'\n\n    # Just set this so CCompiler's constructor doesn't barf.  We currently\n    # don't use the 'set_executables()' bureaucracy provided by CCompiler,\n    # as it really isn't necessary for this sort of single-compiler class.\n    # Would be nice to have a consistent interface with UnixCCompiler,\n    # though, so it's worth thinking about.\n    executables = {}\n\n    # Private class data (need to distinguish C from C++ source for compiler)\n    _c_extensions = ['.c']\n    _cpp_extensions = ['.cc', '.cpp', '.cxx']\n    _rc_extensions = ['.rc']\n    _mc_extensions = ['.mc']\n\n    # Needed for the filename generation methods provided by the\n    # base class, CCompiler.\n    src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions\n    res_extension = '.res'\n    obj_extension = '.obj'\n    static_lib_extension = '.lib'\n    shared_lib_extension = '.dll'\n    static_lib_format = shared_lib_format = '%s%s'\n    exe_extension = '.exe'\n\n    def __init__(self, verbose=0, dry_run=0, force=0):\n        super().__init__(verbose, dry_run, force)\n        self.__version = VERSION\n        self.__root = r\"Software\\Microsoft\\VisualStudio\"\n        # self.__macros = MACROS\n        self.__paths = []\n        # target platform (.plat_name is consistent with 'bdist')\n        self.plat_name = None\n        self.__arch = None  # deprecated name\n        self.initialized = False\n\n    def initialize(self, plat_name=None):  # noqa: C901\n        # multi-init means we would need to check platform same each time...\n        assert not self.initialized, \"don't init multiple times\"\n        if self.__version < 8.0:\n            raise DistutilsPlatformError(\n                \"VC %0.1f is not supported by this module\" % self.__version\n            )\n        if plat_name is None:\n            plat_name = get_platform()\n        # sanity check for platforms to prevent obscure errors later.\n        ok_plats = 'win32', 'win-amd64'\n        if plat_name not in ok_plats:\n            raise DistutilsPlatformError(\n                \"--plat-name must be one of {}\".format(ok_plats)\n            )\n\n        if (\n            \"DISTUTILS_USE_SDK\" in os.environ\n            and \"MSSdk\" in os.environ\n            and self.find_exe(\"cl.exe\")\n        ):\n            # Assume that the SDK set up everything alright; don't try to be\n            # smarter\n            self.cc = \"cl.exe\"\n            self.linker = \"link.exe\"\n            self.lib = \"lib.exe\"\n            self.rc = \"rc.exe\"\n            self.mc = \"mc.exe\"\n        else:\n            # On x86, 'vcvars32.bat amd64' creates an env that doesn't work;\n            # to cross compile, you use 'x86_amd64'.\n            # On AMD64, 'vcvars32.bat amd64' is a native build env; to cross\n            # compile use 'x86' (ie, it runs the x86 compiler directly)\n            if plat_name == get_platform() or plat_name == 'win32':\n                # native build or cross-compile to win32\n                plat_spec = PLAT_TO_VCVARS[plat_name]\n            else:\n                # cross compile from win32 -> some 64bit\n                plat_spec = (\n                    PLAT_TO_VCVARS[get_platform()] + '_' + PLAT_TO_VCVARS[plat_name]\n                )\n\n            vc_env = query_vcvarsall(VERSION, plat_spec)\n\n            self.__paths = vc_env['path'].split(os.pathsep)\n            os.environ['lib'] = vc_env['lib']\n            os.environ['include'] = vc_env['include']\n\n            if len(self.__paths) == 0:\n                raise DistutilsPlatformError(\n                    \"Python was built with %s, \"\n                    \"and extensions need to be built with the same \"\n                    \"version of the compiler, but it isn't installed.\" % self.__product\n                )\n\n            self.cc = self.find_exe(\"cl.exe\")\n            self.linker = self.find_exe(\"link.exe\")\n            self.lib = self.find_exe(\"lib.exe\")\n            self.rc = self.find_exe(\"rc.exe\")  # resource compiler\n            self.mc = self.find_exe(\"mc.exe\")  # message compiler\n            # self.set_path_env_var('lib')\n            # self.set_path_env_var('include')\n\n        # extend the MSVC path with the current path\n        try:\n            for p in os.environ['path'].split(';'):\n                self.__paths.append(p)\n        except KeyError:\n            pass\n        self.__paths = normalize_and_reduce_paths(self.__paths)\n        os.environ['path'] = \";\".join(self.__paths)\n\n        self.preprocess_options = None\n        if self.__arch == \"x86\":\n            self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/DNDEBUG']\n            self.compile_options_debug = [\n                '/nologo',\n                '/Od',\n                '/MDd',\n                '/W3',\n                '/Z7',\n                '/D_DEBUG',\n            ]\n        else:\n            # Win64\n            self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/GS-', '/DNDEBUG']\n            self.compile_options_debug = [\n                '/nologo',\n                '/Od',\n                '/MDd',\n                '/W3',\n                '/GS-',\n                '/Z7',\n                '/D_DEBUG',\n            ]\n\n        self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']\n        if self.__version >= 7:\n            self.ldflags_shared_debug = ['/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG']\n        self.ldflags_static = ['/nologo']\n\n        self.initialized = True\n\n    # -- Worker methods ------------------------------------------------\n\n    def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):\n        # Copied from ccompiler.py, extended to return .res as 'object'-file\n        # for .rc input file\n        if output_dir is None:\n            output_dir = ''\n        obj_names = []\n        for src_name in source_filenames:\n            (base, ext) = os.path.splitext(src_name)\n            base = os.path.splitdrive(base)[1]  # Chop off the drive\n            base = base[os.path.isabs(base) :]  # If abs, chop off leading /\n            if ext not in self.src_extensions:\n                # Better to raise an exception instead of silently continuing\n                # and later complain about sources and targets having\n                # different lengths\n                raise CompileError(\"Don't know how to compile %s\" % src_name)\n            if strip_dir:\n                base = os.path.basename(base)\n            if ext in self._rc_extensions:\n                obj_names.append(os.path.join(output_dir, base + self.res_extension))\n            elif ext in self._mc_extensions:\n                obj_names.append(os.path.join(output_dir, base + self.res_extension))\n            else:\n                obj_names.append(os.path.join(output_dir, base + self.obj_extension))\n        return obj_names\n\n    def compile(  # noqa: C901\n        self,\n        sources,\n        output_dir=None,\n        macros=None,\n        include_dirs=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        depends=None,\n    ):\n\n        if not self.initialized:\n            self.initialize()\n        compile_info = self._setup_compile(\n            output_dir, macros, include_dirs, sources, depends, extra_postargs\n        )\n        macros, objects, extra_postargs, pp_opts, build = compile_info\n\n        compile_opts = extra_preargs or []\n        compile_opts.append('/c')\n        if debug:\n            compile_opts.extend(self.compile_options_debug)\n        else:\n            compile_opts.extend(self.compile_options)\n\n        for obj in objects:\n            try:\n                src, ext = build[obj]\n            except KeyError:\n                continue\n            if debug:\n                # pass the full pathname to MSVC in debug mode,\n                # this allows the debugger to find the source file\n                # without asking the user to browse for it\n                src = os.path.abspath(src)\n\n            if ext in self._c_extensions:\n                input_opt = \"/Tc\" + src\n            elif ext in self._cpp_extensions:\n                input_opt = \"/Tp\" + src\n            elif ext in self._rc_extensions:\n                # compile .RC to .RES file\n                input_opt = src\n                output_opt = \"/fo\" + obj\n                try:\n                    self.spawn([self.rc] + pp_opts + [output_opt] + [input_opt])\n                except DistutilsExecError as msg:\n                    raise CompileError(msg)\n                continue\n            elif ext in self._mc_extensions:\n                # Compile .MC to .RC file to .RES file.\n                #   * '-h dir' specifies the directory for the\n                #     generated include file\n                #   * '-r dir' specifies the target directory of the\n                #     generated RC file and the binary message resource\n                #     it includes\n                #\n                # For now (since there are no options to change this),\n                # we use the source-directory for the include file and\n                # the build directory for the RC file and message\n                # resources. This works at least for win32all.\n                h_dir = os.path.dirname(src)\n                rc_dir = os.path.dirname(obj)\n                try:\n                    # first compile .MC to .RC and .H file\n                    self.spawn([self.mc] + ['-h', h_dir, '-r', rc_dir] + [src])\n                    base, _ = os.path.splitext(os.path.basename(src))\n                    rc_file = os.path.join(rc_dir, base + '.rc')\n                    # then compile .RC to .RES file\n                    self.spawn([self.rc] + [\"/fo\" + obj] + [rc_file])\n\n                except DistutilsExecError as msg:\n                    raise CompileError(msg)\n                continue\n            else:\n                # how to handle this file?\n                raise CompileError(\n                    \"Don't know how to compile {} to {}\".format(src, obj)\n                )\n\n            output_opt = \"/Fo\" + obj\n            try:\n                self.spawn(\n                    [self.cc]\n                    + compile_opts\n                    + pp_opts\n                    + [input_opt, output_opt]\n                    + extra_postargs\n                )\n            except DistutilsExecError as msg:\n                raise CompileError(msg)\n\n        return objects\n\n    def create_static_lib(\n        self, objects, output_libname, output_dir=None, debug=0, target_lang=None\n    ):\n\n        if not self.initialized:\n            self.initialize()\n        (objects, output_dir) = self._fix_object_args(objects, output_dir)\n        output_filename = self.library_filename(output_libname, output_dir=output_dir)\n\n        if self._need_link(objects, output_filename):\n            lib_args = objects + ['/OUT:' + output_filename]\n            if debug:\n                pass  # XXX what goes here?\n            try:\n                self.spawn([self.lib] + lib_args)\n            except DistutilsExecError as msg:\n                raise LibError(msg)\n        else:\n            log.debug(\"skipping %s (up-to-date)\", output_filename)\n\n    def link(  # noqa: C901\n        self,\n        target_desc,\n        objects,\n        output_filename,\n        output_dir=None,\n        libraries=None,\n        library_dirs=None,\n        runtime_library_dirs=None,\n        export_symbols=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        build_temp=None,\n        target_lang=None,\n    ):\n\n        if not self.initialized:\n            self.initialize()\n        (objects, output_dir) = self._fix_object_args(objects, output_dir)\n        fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)\n        (libraries, library_dirs, runtime_library_dirs) = fixed_args\n\n        if runtime_library_dirs:\n            self.warn(\n                \"I don't know what to do with 'runtime_library_dirs': \"\n                + str(runtime_library_dirs)\n            )\n\n        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)\n        if output_dir is not None:\n            output_filename = os.path.join(output_dir, output_filename)\n\n        if self._need_link(objects, output_filename):\n            if target_desc == CCompiler.EXECUTABLE:\n                if debug:\n                    ldflags = self.ldflags_shared_debug[1:]\n                else:\n                    ldflags = self.ldflags_shared[1:]\n            else:\n                if debug:\n                    ldflags = self.ldflags_shared_debug\n                else:\n                    ldflags = self.ldflags_shared\n\n            export_opts = []\n            for sym in export_symbols or []:\n                export_opts.append(\"/EXPORT:\" + sym)\n\n            ld_args = (\n                ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]\n            )\n\n            # The MSVC linker generates .lib and .exp files, which cannot be\n            # suppressed by any linker switches. The .lib files may even be\n            # needed! Make sure they are generated in the temporary build\n            # directory. Since they have different names for debug and release\n            # builds, they can go into the same directory.\n            build_temp = os.path.dirname(objects[0])\n            if export_symbols is not None:\n                (dll_name, dll_ext) = os.path.splitext(\n                    os.path.basename(output_filename)\n                )\n                implib_file = os.path.join(build_temp, self.library_filename(dll_name))\n                ld_args.append('/IMPLIB:' + implib_file)\n\n            self.manifest_setup_ldargs(output_filename, build_temp, ld_args)\n\n            if extra_preargs:\n                ld_args[:0] = extra_preargs\n            if extra_postargs:\n                ld_args.extend(extra_postargs)\n\n            self.mkpath(os.path.dirname(output_filename))\n            try:\n                self.spawn([self.linker] + ld_args)\n            except DistutilsExecError as msg:\n                raise LinkError(msg)\n\n            # embed the manifest\n            # XXX - this is somewhat fragile - if mt.exe fails, distutils\n            # will still consider the DLL up-to-date, but it will not have a\n            # manifest.  Maybe we should link to a temp file?  OTOH, that\n            # implies a build environment error that shouldn't go undetected.\n            mfinfo = self.manifest_get_embed_info(target_desc, ld_args)\n            if mfinfo is not None:\n                mffilename, mfid = mfinfo\n                out_arg = '-outputresource:{};{}'.format(output_filename, mfid)\n                try:\n                    self.spawn(['mt.exe', '-nologo', '-manifest', mffilename, out_arg])\n                except DistutilsExecError as msg:\n                    raise LinkError(msg)\n        else:\n            log.debug(\"skipping %s (up-to-date)\", output_filename)\n\n    def manifest_setup_ldargs(self, output_filename, build_temp, ld_args):\n        # If we need a manifest at all, an embedded manifest is recommended.\n        # See MSDN article titled\n        # \"How to: Embed a Manifest Inside a C/C++ Application\"\n        # (currently at http://msdn2.microsoft.com/en-us/library/ms235591(VS.80).aspx)\n        # Ask the linker to generate the manifest in the temp dir, so\n        # we can check it, and possibly embed it, later.\n        temp_manifest = os.path.join(\n            build_temp, os.path.basename(output_filename) + \".manifest\"\n        )\n        ld_args.append('/MANIFESTFILE:' + temp_manifest)\n\n    def manifest_get_embed_info(self, target_desc, ld_args):\n        # If a manifest should be embedded, return a tuple of\n        # (manifest_filename, resource_id).  Returns None if no manifest\n        # should be embedded.  See http://bugs.python.org/issue7833 for why\n        # we want to avoid any manifest for extension modules if we can)\n        for arg in ld_args:\n            if arg.startswith(\"/MANIFESTFILE:\"):\n                temp_manifest = arg.split(\":\", 1)[1]\n                break\n        else:\n            # no /MANIFESTFILE so nothing to do.\n            return None\n        if target_desc == CCompiler.EXECUTABLE:\n            # by default, executables always get the manifest with the\n            # CRT referenced.\n            mfid = 1\n        else:\n            # Extension modules try and avoid any manifest if possible.\n            mfid = 2\n            temp_manifest = self._remove_visual_c_ref(temp_manifest)\n        if temp_manifest is None:\n            return None\n        return temp_manifest, mfid\n\n    def _remove_visual_c_ref(self, manifest_file):\n        try:\n            # Remove references to the Visual C runtime, so they will\n            # fall through to the Visual C dependency of Python.exe.\n            # This way, when installed for a restricted user (e.g.\n            # runtimes are not in WinSxS folder, but in Python's own\n            # folder), the runtimes do not need to be in every folder\n            # with .pyd's.\n            # Returns either the filename of the modified manifest or\n            # None if no manifest should be embedded.\n            manifest_f = open(manifest_file)\n            try:\n                manifest_buf = manifest_f.read()\n            finally:\n                manifest_f.close()\n            pattern = re.compile(\n                r\"\"\"<assemblyIdentity.*?name=(\"|')Microsoft\\.\"\"\"\n                r\"\"\"VC\\d{2}\\.CRT(\"|').*?(/>|</assemblyIdentity>)\"\"\",\n                re.DOTALL,\n            )\n            manifest_buf = re.sub(pattern, \"\", manifest_buf)\n            pattern = r\"<dependentAssembly>\\s*</dependentAssembly>\"\n            manifest_buf = re.sub(pattern, \"\", manifest_buf)\n            # Now see if any other assemblies are referenced - if not, we\n            # don't want a manifest embedded.\n            pattern = re.compile(\n                r\"\"\"<assemblyIdentity.*?name=(?:\"|')(.+?)(?:\"|')\"\"\"\n                r\"\"\".*?(?:/>|</assemblyIdentity>)\"\"\",\n                re.DOTALL,\n            )\n            if re.search(pattern, manifest_buf) is None:\n                return None\n\n            manifest_f = open(manifest_file, 'w')\n            try:\n                manifest_f.write(manifest_buf)\n                return manifest_file\n            finally:\n                manifest_f.close()\n        except OSError:\n            pass\n\n    # -- Miscellaneous methods -----------------------------------------\n    # These are all used by the 'gen_lib_options() function, in\n    # ccompiler.py.\n\n    def library_dir_option(self, dir):\n        return \"/LIBPATH:\" + dir\n\n    def runtime_library_dir_option(self, dir):\n        raise DistutilsPlatformError(\n            \"don't know how to set runtime library search path for MSVC++\"\n        )\n\n    def library_option(self, lib):\n        return self.library_filename(lib)\n\n    def find_library_file(self, dirs, lib, debug=0):\n        # Prefer a debugging library if found (and requested), but deal\n        # with it if we don't have one.\n        if debug:\n            try_names = [lib + \"_d\", lib]\n        else:\n            try_names = [lib]\n        for dir in dirs:\n            for name in try_names:\n                libfile = os.path.join(dir, self.library_filename(name))\n                if os.path.exists(libfile):\n                    return libfile\n        else:\n            # Oops, didn't find it in *any* of 'dirs'\n            return None\n\n    # Helper methods for using the MSVC registry settings\n\n    def find_exe(self, exe):\n        \"\"\"Return path to an MSVC executable program.\n\n        Tries to find the program in several places: first, one of the\n        MSVC program search paths from the registry; next, the directories\n        in the PATH environment variable.  If any of those work, return an\n        absolute path that is known to exist.  If none of them work, just\n        return the original program name, 'exe'.\n        \"\"\"\n        for p in self.__paths:\n            fn = os.path.join(os.path.abspath(p), exe)\n            if os.path.isfile(fn):\n                return fn\n\n        # didn't find it; try existing path\n        for p in os.environ['Path'].split(';'):\n            fn = os.path.join(os.path.abspath(p), exe)\n            if os.path.isfile(fn):\n                return fn\n\n        return exe\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/msvccompiler.py",
    "content": "\"\"\"distutils.msvccompiler\n\nContains MSVCCompiler, an implementation of the abstract CCompiler class\nfor the Microsoft Visual Studio.\n\"\"\"\n\n# Written by Perry Stoll\n# hacked by Robin Becker and Thomas Heller to do a better job of\n#   finding DevStudio (through the registry)\n\nimport sys\nimport os\nimport warnings\nfrom distutils.errors import (\n    DistutilsExecError,\n    DistutilsPlatformError,\n    CompileError,\n    LibError,\n    LinkError,\n)\nfrom distutils.ccompiler import CCompiler, gen_lib_options\nfrom distutils import log\n\n_can_read_reg = False\ntry:\n    import winreg\n\n    _can_read_reg = True\n    hkey_mod = winreg\n\n    RegOpenKeyEx = winreg.OpenKeyEx\n    RegEnumKey = winreg.EnumKey\n    RegEnumValue = winreg.EnumValue\n    RegError = winreg.error\n\nexcept ImportError:\n    try:\n        import win32api\n        import win32con\n\n        _can_read_reg = True\n        hkey_mod = win32con\n\n        RegOpenKeyEx = win32api.RegOpenKeyEx\n        RegEnumKey = win32api.RegEnumKey\n        RegEnumValue = win32api.RegEnumValue\n        RegError = win32api.error\n    except ImportError:\n        log.info(\n            \"Warning: Can't read registry to find the \"\n            \"necessary compiler setting\\n\"\n            \"Make sure that Python modules winreg, \"\n            \"win32api or win32con are installed.\"\n        )\n        pass\n\nif _can_read_reg:\n    HKEYS = (\n        hkey_mod.HKEY_USERS,\n        hkey_mod.HKEY_CURRENT_USER,\n        hkey_mod.HKEY_LOCAL_MACHINE,\n        hkey_mod.HKEY_CLASSES_ROOT,\n    )\n\n\nwarnings.warn(\n    \"msvccompiler is deprecated and slated to be removed \"\n    \"in the future. Please discontinue use or file an issue \"\n    \"with pypa/distutils describing your use case.\",\n    DeprecationWarning,\n)\n\n\ndef read_keys(base, key):\n    \"\"\"Return list of registry keys.\"\"\"\n    try:\n        handle = RegOpenKeyEx(base, key)\n    except RegError:\n        return None\n    L = []\n    i = 0\n    while True:\n        try:\n            k = RegEnumKey(handle, i)\n        except RegError:\n            break\n        L.append(k)\n        i += 1\n    return L\n\n\ndef read_values(base, key):\n    \"\"\"Return dict of registry keys and values.\n\n    All names are converted to lowercase.\n    \"\"\"\n    try:\n        handle = RegOpenKeyEx(base, key)\n    except RegError:\n        return None\n    d = {}\n    i = 0\n    while True:\n        try:\n            name, value, type = RegEnumValue(handle, i)\n        except RegError:\n            break\n        name = name.lower()\n        d[convert_mbcs(name)] = convert_mbcs(value)\n        i += 1\n    return d\n\n\ndef convert_mbcs(s):\n    dec = getattr(s, \"decode\", None)\n    if dec is not None:\n        try:\n            s = dec(\"mbcs\")\n        except UnicodeError:\n            pass\n    return s\n\n\nclass MacroExpander:\n    def __init__(self, version):\n        self.macros = {}\n        self.load_macros(version)\n\n    def set_macro(self, macro, path, key):\n        for base in HKEYS:\n            d = read_values(base, path)\n            if d:\n                self.macros[\"$(%s)\" % macro] = d[key]\n                break\n\n    def load_macros(self, version):\n        vsbase = r\"Software\\Microsoft\\VisualStudio\\%0.1f\" % version\n        self.set_macro(\"VCInstallDir\", vsbase + r\"\\Setup\\VC\", \"productdir\")\n        self.set_macro(\"VSInstallDir\", vsbase + r\"\\Setup\\VS\", \"productdir\")\n        net = r\"Software\\Microsoft\\.NETFramework\"\n        self.set_macro(\"FrameworkDir\", net, \"installroot\")\n        try:\n            if version > 7.0:\n                self.set_macro(\"FrameworkSDKDir\", net, \"sdkinstallrootv1.1\")\n            else:\n                self.set_macro(\"FrameworkSDKDir\", net, \"sdkinstallroot\")\n        except KeyError:\n            raise DistutilsPlatformError(\n                \"\"\"Python was built with Visual Studio 2003;\nextensions must be built with a compiler than can generate compatible binaries.\nVisual Studio 2003 was not found on this system. If you have Cygwin installed,\nyou can try compiling with MingW32, by passing \"-c mingw32\" to setup.py.\"\"\"\n            )\n\n        p = r\"Software\\Microsoft\\NET Framework Setup\\Product\"\n        for base in HKEYS:\n            try:\n                h = RegOpenKeyEx(base, p)\n            except RegError:\n                continue\n            key = RegEnumKey(h, 0)\n            d = read_values(base, r\"{}\\{}\".format(p, key))\n            self.macros[\"$(FrameworkVersion)\"] = d[\"version\"]\n\n    def sub(self, s):\n        for k, v in self.macros.items():\n            s = s.replace(k, v)\n        return s\n\n\ndef get_build_version():\n    \"\"\"Return the version of MSVC that was used to build Python.\n\n    For Python 2.3 and up, the version number is included in\n    sys.version.  For earlier versions, assume the compiler is MSVC 6.\n    \"\"\"\n    prefix = \"MSC v.\"\n    i = sys.version.find(prefix)\n    if i == -1:\n        return 6\n    i = i + len(prefix)\n    s, rest = sys.version[i:].split(\" \", 1)\n    majorVersion = int(s[:-2]) - 6\n    if majorVersion >= 13:\n        # v13 was skipped and should be v14\n        majorVersion += 1\n    minorVersion = int(s[2:3]) / 10.0\n    # I don't think paths are affected by minor version in version 6\n    if majorVersion == 6:\n        minorVersion = 0\n    if majorVersion >= 6:\n        return majorVersion + minorVersion\n    # else we don't know what version of the compiler this is\n    return None\n\n\ndef get_build_architecture():\n    \"\"\"Return the processor architecture.\n\n    Possible results are \"Intel\" or \"AMD64\".\n    \"\"\"\n\n    prefix = \" bit (\"\n    i = sys.version.find(prefix)\n    if i == -1:\n        return \"Intel\"\n    j = sys.version.find(\")\", i)\n    return sys.version[i + len(prefix) : j]\n\n\ndef normalize_and_reduce_paths(paths):\n    \"\"\"Return a list of normalized paths with duplicates removed.\n\n    The current order of paths is maintained.\n    \"\"\"\n    # Paths are normalized so things like:  /a and /a/ aren't both preserved.\n    reduced_paths = []\n    for p in paths:\n        np = os.path.normpath(p)\n        # XXX(nnorwitz): O(n**2), if reduced_paths gets long perhaps use a set.\n        if np not in reduced_paths:\n            reduced_paths.append(np)\n    return reduced_paths\n\n\nclass MSVCCompiler(CCompiler):\n    \"\"\"Concrete class that implements an interface to Microsoft Visual C++,\n    as defined by the CCompiler abstract class.\"\"\"\n\n    compiler_type = 'msvc'\n\n    # Just set this so CCompiler's constructor doesn't barf.  We currently\n    # don't use the 'set_executables()' bureaucracy provided by CCompiler,\n    # as it really isn't necessary for this sort of single-compiler class.\n    # Would be nice to have a consistent interface with UnixCCompiler,\n    # though, so it's worth thinking about.\n    executables = {}\n\n    # Private class data (need to distinguish C from C++ source for compiler)\n    _c_extensions = ['.c']\n    _cpp_extensions = ['.cc', '.cpp', '.cxx']\n    _rc_extensions = ['.rc']\n    _mc_extensions = ['.mc']\n\n    # Needed for the filename generation methods provided by the\n    # base class, CCompiler.\n    src_extensions = _c_extensions + _cpp_extensions + _rc_extensions + _mc_extensions\n    res_extension = '.res'\n    obj_extension = '.obj'\n    static_lib_extension = '.lib'\n    shared_lib_extension = '.dll'\n    static_lib_format = shared_lib_format = '%s%s'\n    exe_extension = '.exe'\n\n    def __init__(self, verbose=0, dry_run=0, force=0):\n        super().__init__(verbose, dry_run, force)\n        self.__version = get_build_version()\n        self.__arch = get_build_architecture()\n        if self.__arch == \"Intel\":\n            # x86\n            if self.__version >= 7:\n                self.__root = r\"Software\\Microsoft\\VisualStudio\"\n                self.__macros = MacroExpander(self.__version)\n            else:\n                self.__root = r\"Software\\Microsoft\\Devstudio\"\n            self.__product = \"Visual Studio version %s\" % self.__version\n        else:\n            # Win64. Assume this was built with the platform SDK\n            self.__product = \"Microsoft SDK compiler %s\" % (self.__version + 6)\n\n        self.initialized = False\n\n    def initialize(self):\n        self.__paths = []\n        if (\n            \"DISTUTILS_USE_SDK\" in os.environ\n            and \"MSSdk\" in os.environ\n            and self.find_exe(\"cl.exe\")\n        ):\n            # Assume that the SDK set up everything alright; don't try to be\n            # smarter\n            self.cc = \"cl.exe\"\n            self.linker = \"link.exe\"\n            self.lib = \"lib.exe\"\n            self.rc = \"rc.exe\"\n            self.mc = \"mc.exe\"\n        else:\n            self.__paths = self.get_msvc_paths(\"path\")\n\n            if len(self.__paths) == 0:\n                raise DistutilsPlatformError(\n                    \"Python was built with %s, \"\n                    \"and extensions need to be built with the same \"\n                    \"version of the compiler, but it isn't installed.\" % self.__product\n                )\n\n            self.cc = self.find_exe(\"cl.exe\")\n            self.linker = self.find_exe(\"link.exe\")\n            self.lib = self.find_exe(\"lib.exe\")\n            self.rc = self.find_exe(\"rc.exe\")  # resource compiler\n            self.mc = self.find_exe(\"mc.exe\")  # message compiler\n            self.set_path_env_var('lib')\n            self.set_path_env_var('include')\n\n        # extend the MSVC path with the current path\n        try:\n            for p in os.environ['path'].split(';'):\n                self.__paths.append(p)\n        except KeyError:\n            pass\n        self.__paths = normalize_and_reduce_paths(self.__paths)\n        os.environ['path'] = \";\".join(self.__paths)\n\n        self.preprocess_options = None\n        if self.__arch == \"Intel\":\n            self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/GX', '/DNDEBUG']\n            self.compile_options_debug = [\n                '/nologo',\n                '/Od',\n                '/MDd',\n                '/W3',\n                '/GX',\n                '/Z7',\n                '/D_DEBUG',\n            ]\n        else:\n            # Win64\n            self.compile_options = ['/nologo', '/O2', '/MD', '/W3', '/GS-', '/DNDEBUG']\n            self.compile_options_debug = [\n                '/nologo',\n                '/Od',\n                '/MDd',\n                '/W3',\n                '/GS-',\n                '/Z7',\n                '/D_DEBUG',\n            ]\n\n        self.ldflags_shared = ['/DLL', '/nologo', '/INCREMENTAL:NO']\n        if self.__version >= 7:\n            self.ldflags_shared_debug = ['/DLL', '/nologo', '/INCREMENTAL:no', '/DEBUG']\n        else:\n            self.ldflags_shared_debug = [\n                '/DLL',\n                '/nologo',\n                '/INCREMENTAL:no',\n                '/pdb:None',\n                '/DEBUG',\n            ]\n        self.ldflags_static = ['/nologo']\n\n        self.initialized = True\n\n    # -- Worker methods ------------------------------------------------\n\n    def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):\n        # Copied from ccompiler.py, extended to return .res as 'object'-file\n        # for .rc input file\n        if output_dir is None:\n            output_dir = ''\n        obj_names = []\n        for src_name in source_filenames:\n            (base, ext) = os.path.splitext(src_name)\n            base = os.path.splitdrive(base)[1]  # Chop off the drive\n            base = base[os.path.isabs(base) :]  # If abs, chop off leading /\n            if ext not in self.src_extensions:\n                # Better to raise an exception instead of silently continuing\n                # and later complain about sources and targets having\n                # different lengths\n                raise CompileError(\"Don't know how to compile %s\" % src_name)\n            if strip_dir:\n                base = os.path.basename(base)\n            if ext in self._rc_extensions:\n                obj_names.append(os.path.join(output_dir, base + self.res_extension))\n            elif ext in self._mc_extensions:\n                obj_names.append(os.path.join(output_dir, base + self.res_extension))\n            else:\n                obj_names.append(os.path.join(output_dir, base + self.obj_extension))\n        return obj_names\n\n    def compile(  # noqa: C901\n        self,\n        sources,\n        output_dir=None,\n        macros=None,\n        include_dirs=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        depends=None,\n    ):\n\n        if not self.initialized:\n            self.initialize()\n        compile_info = self._setup_compile(\n            output_dir, macros, include_dirs, sources, depends, extra_postargs\n        )\n        macros, objects, extra_postargs, pp_opts, build = compile_info\n\n        compile_opts = extra_preargs or []\n        compile_opts.append('/c')\n        if debug:\n            compile_opts.extend(self.compile_options_debug)\n        else:\n            compile_opts.extend(self.compile_options)\n\n        for obj in objects:\n            try:\n                src, ext = build[obj]\n            except KeyError:\n                continue\n            if debug:\n                # pass the full pathname to MSVC in debug mode,\n                # this allows the debugger to find the source file\n                # without asking the user to browse for it\n                src = os.path.abspath(src)\n\n            if ext in self._c_extensions:\n                input_opt = \"/Tc\" + src\n            elif ext in self._cpp_extensions:\n                input_opt = \"/Tp\" + src\n            elif ext in self._rc_extensions:\n                # compile .RC to .RES file\n                input_opt = src\n                output_opt = \"/fo\" + obj\n                try:\n                    self.spawn([self.rc] + pp_opts + [output_opt] + [input_opt])\n                except DistutilsExecError as msg:\n                    raise CompileError(msg)\n                continue\n            elif ext in self._mc_extensions:\n                # Compile .MC to .RC file to .RES file.\n                #   * '-h dir' specifies the directory for the\n                #     generated include file\n                #   * '-r dir' specifies the target directory of the\n                #     generated RC file and the binary message resource\n                #     it includes\n                #\n                # For now (since there are no options to change this),\n                # we use the source-directory for the include file and\n                # the build directory for the RC file and message\n                # resources. This works at least for win32all.\n                h_dir = os.path.dirname(src)\n                rc_dir = os.path.dirname(obj)\n                try:\n                    # first compile .MC to .RC and .H file\n                    self.spawn([self.mc] + ['-h', h_dir, '-r', rc_dir] + [src])\n                    base, _ = os.path.splitext(os.path.basename(src))\n                    rc_file = os.path.join(rc_dir, base + '.rc')\n                    # then compile .RC to .RES file\n                    self.spawn([self.rc] + [\"/fo\" + obj] + [rc_file])\n\n                except DistutilsExecError as msg:\n                    raise CompileError(msg)\n                continue\n            else:\n                # how to handle this file?\n                raise CompileError(\n                    \"Don't know how to compile {} to {}\".format(src, obj)\n                )\n\n            output_opt = \"/Fo\" + obj\n            try:\n                self.spawn(\n                    [self.cc]\n                    + compile_opts\n                    + pp_opts\n                    + [input_opt, output_opt]\n                    + extra_postargs\n                )\n            except DistutilsExecError as msg:\n                raise CompileError(msg)\n\n        return objects\n\n    def create_static_lib(\n        self, objects, output_libname, output_dir=None, debug=0, target_lang=None\n    ):\n\n        if not self.initialized:\n            self.initialize()\n        (objects, output_dir) = self._fix_object_args(objects, output_dir)\n        output_filename = self.library_filename(output_libname, output_dir=output_dir)\n\n        if self._need_link(objects, output_filename):\n            lib_args = objects + ['/OUT:' + output_filename]\n            if debug:\n                pass  # XXX what goes here?\n            try:\n                self.spawn([self.lib] + lib_args)\n            except DistutilsExecError as msg:\n                raise LibError(msg)\n        else:\n            log.debug(\"skipping %s (up-to-date)\", output_filename)\n\n    def link(  # noqa: C901\n        self,\n        target_desc,\n        objects,\n        output_filename,\n        output_dir=None,\n        libraries=None,\n        library_dirs=None,\n        runtime_library_dirs=None,\n        export_symbols=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        build_temp=None,\n        target_lang=None,\n    ):\n\n        if not self.initialized:\n            self.initialize()\n        (objects, output_dir) = self._fix_object_args(objects, output_dir)\n        fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)\n        (libraries, library_dirs, runtime_library_dirs) = fixed_args\n\n        if runtime_library_dirs:\n            self.warn(\n                \"I don't know what to do with 'runtime_library_dirs': \"\n                + str(runtime_library_dirs)\n            )\n\n        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)\n        if output_dir is not None:\n            output_filename = os.path.join(output_dir, output_filename)\n\n        if self._need_link(objects, output_filename):\n            if target_desc == CCompiler.EXECUTABLE:\n                if debug:\n                    ldflags = self.ldflags_shared_debug[1:]\n                else:\n                    ldflags = self.ldflags_shared[1:]\n            else:\n                if debug:\n                    ldflags = self.ldflags_shared_debug\n                else:\n                    ldflags = self.ldflags_shared\n\n            export_opts = []\n            for sym in export_symbols or []:\n                export_opts.append(\"/EXPORT:\" + sym)\n\n            ld_args = (\n                ldflags + lib_opts + export_opts + objects + ['/OUT:' + output_filename]\n            )\n\n            # The MSVC linker generates .lib and .exp files, which cannot be\n            # suppressed by any linker switches. The .lib files may even be\n            # needed! Make sure they are generated in the temporary build\n            # directory. Since they have different names for debug and release\n            # builds, they can go into the same directory.\n            if export_symbols is not None:\n                (dll_name, dll_ext) = os.path.splitext(\n                    os.path.basename(output_filename)\n                )\n                implib_file = os.path.join(\n                    os.path.dirname(objects[0]), self.library_filename(dll_name)\n                )\n                ld_args.append('/IMPLIB:' + implib_file)\n\n            if extra_preargs:\n                ld_args[:0] = extra_preargs\n            if extra_postargs:\n                ld_args.extend(extra_postargs)\n\n            self.mkpath(os.path.dirname(output_filename))\n            try:\n                self.spawn([self.linker] + ld_args)\n            except DistutilsExecError as msg:\n                raise LinkError(msg)\n\n        else:\n            log.debug(\"skipping %s (up-to-date)\", output_filename)\n\n    # -- Miscellaneous methods -----------------------------------------\n    # These are all used by the 'gen_lib_options() function, in\n    # ccompiler.py.\n\n    def library_dir_option(self, dir):\n        return \"/LIBPATH:\" + dir\n\n    def runtime_library_dir_option(self, dir):\n        raise DistutilsPlatformError(\n            \"don't know how to set runtime library search path for MSVC++\"\n        )\n\n    def library_option(self, lib):\n        return self.library_filename(lib)\n\n    def find_library_file(self, dirs, lib, debug=0):\n        # Prefer a debugging library if found (and requested), but deal\n        # with it if we don't have one.\n        if debug:\n            try_names = [lib + \"_d\", lib]\n        else:\n            try_names = [lib]\n        for dir in dirs:\n            for name in try_names:\n                libfile = os.path.join(dir, self.library_filename(name))\n                if os.path.exists(libfile):\n                    return libfile\n        else:\n            # Oops, didn't find it in *any* of 'dirs'\n            return None\n\n    # Helper methods for using the MSVC registry settings\n\n    def find_exe(self, exe):\n        \"\"\"Return path to an MSVC executable program.\n\n        Tries to find the program in several places: first, one of the\n        MSVC program search paths from the registry; next, the directories\n        in the PATH environment variable.  If any of those work, return an\n        absolute path that is known to exist.  If none of them work, just\n        return the original program name, 'exe'.\n        \"\"\"\n        for p in self.__paths:\n            fn = os.path.join(os.path.abspath(p), exe)\n            if os.path.isfile(fn):\n                return fn\n\n        # didn't find it; try existing path\n        for p in os.environ['Path'].split(';'):\n            fn = os.path.join(os.path.abspath(p), exe)\n            if os.path.isfile(fn):\n                return fn\n\n        return exe\n\n    def get_msvc_paths(self, path, platform='x86'):\n        \"\"\"Get a list of devstudio directories (include, lib or path).\n\n        Return a list of strings.  The list will be empty if unable to\n        access the registry or appropriate registry keys not found.\n        \"\"\"\n        if not _can_read_reg:\n            return []\n\n        path = path + \" dirs\"\n        if self.__version >= 7:\n            key = r\"{}\\{:0.1f}\\VC\\VC_OBJECTS_PLATFORM_INFO\\Win32\\Directories\".format(\n                self.__root,\n                self.__version,\n            )\n        else:\n            key = (\n                r\"%s\\6.0\\Build System\\Components\\Platforms\"\n                r\"\\Win32 (%s)\\Directories\" % (self.__root, platform)\n            )\n\n        for base in HKEYS:\n            d = read_values(base, key)\n            if d:\n                if self.__version >= 7:\n                    return self.__macros.sub(d[path]).split(\";\")\n                else:\n                    return d[path].split(\";\")\n        # MSVC 6 seems to create the registry entries we need only when\n        # the GUI is run.\n        if self.__version == 6:\n            for base in HKEYS:\n                if read_values(base, r\"%s\\6.0\" % self.__root) is not None:\n                    self.warn(\n                        \"It seems you have Visual Studio 6 installed, \"\n                        \"but the expected registry settings are not present.\\n\"\n                        \"You must at least run the Visual Studio GUI once \"\n                        \"so that these entries are created.\"\n                    )\n                    break\n        return []\n\n    def set_path_env_var(self, name):\n        \"\"\"Set environment variable 'name' to an MSVC path type value.\n\n        This is equivalent to a SET command prior to execution of spawned\n        commands.\n        \"\"\"\n\n        if name == \"lib\":\n            p = self.get_msvc_paths(\"library\")\n        else:\n            p = self.get_msvc_paths(name)\n        if p:\n            os.environ[name] = ';'.join(p)\n\n\nif get_build_version() >= 8.0:\n    log.debug(\"Importing new compiler from distutils.msvc9compiler\")\n    OldMSVCCompiler = MSVCCompiler\n    from distutils.msvc9compiler import MSVCCompiler\n\n    # get_build_architecture not really relevant now we support cross-compile\n    from distutils.msvc9compiler import MacroExpander  # noqa: F811\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/py38compat.py",
    "content": "def aix_platform(osname, version, release):\n    try:\n        import _aix_support\n\n        return _aix_support.aix_platform()\n    except ImportError:\n        pass\n    return \"{}-{}.{}\".format(osname, version, release)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/py39compat.py",
    "content": "import sys\nimport platform\n\n\ndef add_ext_suffix_39(vars):\n    \"\"\"\n    Ensure vars contains 'EXT_SUFFIX'. pypa/distutils#130\n    \"\"\"\n    import _imp\n\n    ext_suffix = _imp.extension_suffixes()[0]\n    vars.update(\n        EXT_SUFFIX=ext_suffix,\n        # sysconfig sets SO to match EXT_SUFFIX, so maintain\n        # that expectation.\n        # https://github.com/python/cpython/blob/785cc6770588de087d09e89a69110af2542be208/Lib/sysconfig.py#L671-L673\n        SO=ext_suffix,\n    )\n\n\nneeds_ext_suffix = sys.version_info < (3, 10) and platform.system() == 'Windows'\nadd_ext_suffix = add_ext_suffix_39 if needs_ext_suffix else lambda vars: None\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/spawn.py",
    "content": "\"\"\"distutils.spawn\n\nProvides the 'spawn()' function, a front-end to various platform-\nspecific functions for launching another program in a sub-process.\nAlso provides the 'find_executable()' to search the path for a given\nexecutable name.\n\"\"\"\n\nimport sys\nimport os\nimport subprocess\n\nfrom distutils.errors import DistutilsExecError\nfrom distutils.debug import DEBUG\nfrom distutils import log\n\n\ndef spawn(cmd, search_path=1, verbose=0, dry_run=0, env=None):  # noqa: C901\n    \"\"\"Run another program, specified as a command list 'cmd', in a new process.\n\n    'cmd' is just the argument list for the new process, ie.\n    cmd[0] is the program to run and cmd[1:] are the rest of its arguments.\n    There is no way to run a program with a name different from that of its\n    executable.\n\n    If 'search_path' is true (the default), the system's executable\n    search path will be used to find the program; otherwise, cmd[0]\n    must be the exact path to the executable.  If 'dry_run' is true,\n    the command will not actually be run.\n\n    Raise DistutilsExecError if running the program fails in any way; just\n    return on success.\n    \"\"\"\n    # cmd is documented as a list, but just in case some code passes a tuple\n    # in, protect our %-formatting code against horrible death\n    cmd = list(cmd)\n\n    log.info(subprocess.list2cmdline(cmd))\n    if dry_run:\n        return\n\n    if search_path:\n        executable = find_executable(cmd[0])\n        if executable is not None:\n            cmd[0] = executable\n\n    env = env if env is not None else dict(os.environ)\n\n    if sys.platform == 'darwin':\n        from distutils.util import MACOSX_VERSION_VAR, get_macosx_target_ver\n\n        macosx_target_ver = get_macosx_target_ver()\n        if macosx_target_ver:\n            env[MACOSX_VERSION_VAR] = macosx_target_ver\n\n    try:\n        proc = subprocess.Popen(cmd, env=env)\n        proc.wait()\n        exitcode = proc.returncode\n    except OSError as exc:\n        if not DEBUG:\n            cmd = cmd[0]\n        raise DistutilsExecError(\n            \"command {!r} failed: {}\".format(cmd, exc.args[-1])\n        ) from exc\n\n    if exitcode:\n        if not DEBUG:\n            cmd = cmd[0]\n        raise DistutilsExecError(\n            \"command {!r} failed with exit code {}\".format(cmd, exitcode)\n        )\n\n\ndef find_executable(executable, path=None):\n    \"\"\"Tries to find 'executable' in the directories listed in 'path'.\n\n    A string listing directories separated by 'os.pathsep'; defaults to\n    os.environ['PATH'].  Returns the complete filename or None if not found.\n    \"\"\"\n    _, ext = os.path.splitext(executable)\n    if (sys.platform == 'win32') and (ext != '.exe'):\n        executable = executable + '.exe'\n\n    if os.path.isfile(executable):\n        return executable\n\n    if path is None:\n        path = os.environ.get('PATH', None)\n        if path is None:\n            try:\n                path = os.confstr(\"CS_PATH\")\n            except (AttributeError, ValueError):\n                # os.confstr() or CS_PATH is not available\n                path = os.defpath\n        # bpo-35755: Don't use os.defpath if the PATH environment variable is\n        # set to an empty string\n\n    # PATH='' doesn't match, whereas PATH=':' looks in the current directory\n    if not path:\n        return None\n\n    paths = path.split(os.pathsep)\n    for p in paths:\n        f = os.path.join(p, executable)\n        if os.path.isfile(f):\n            # the file exists, we have a shot at spawn working\n            return f\n    return None\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/sysconfig.py",
    "content": "\"\"\"Provide access to Python's configuration information.  The specific\nconfiguration variables available depend heavily on the platform and\nconfiguration.  The values may be retrieved using\nget_config_var(name), and the list of variables is available via\nget_config_vars().keys().  Additional convenience functions are also\navailable.\n\nWritten by:   Fred L. Drake, Jr.\nEmail:        <fdrake@acm.org>\n\"\"\"\n\nimport os\nimport re\nimport sys\nimport sysconfig\nimport pathlib\n\nfrom .errors import DistutilsPlatformError\nfrom . import py39compat\nfrom ._functools import pass_none\n\nIS_PYPY = '__pypy__' in sys.builtin_module_names\n\n# These are needed in a couple of spots, so just compute them once.\nPREFIX = os.path.normpath(sys.prefix)\nEXEC_PREFIX = os.path.normpath(sys.exec_prefix)\nBASE_PREFIX = os.path.normpath(sys.base_prefix)\nBASE_EXEC_PREFIX = os.path.normpath(sys.base_exec_prefix)\n\n# Path to the base directory of the project. On Windows the binary may\n# live in project/PCbuild/win32 or project/PCbuild/amd64.\n# set for cross builds\nif \"_PYTHON_PROJECT_BASE\" in os.environ:\n    project_base = os.path.abspath(os.environ[\"_PYTHON_PROJECT_BASE\"])\nelse:\n    if sys.executable:\n        project_base = os.path.dirname(os.path.abspath(sys.executable))\n    else:\n        # sys.executable can be empty if argv[0] has been changed and Python is\n        # unable to retrieve the real program name\n        project_base = os.getcwd()\n\n\ndef _is_python_source_dir(d):\n    \"\"\"\n    Return True if the target directory appears to point to an\n    un-installed Python.\n    \"\"\"\n    modules = pathlib.Path(d).joinpath('Modules')\n    return any(modules.joinpath(fn).is_file() for fn in ('Setup', 'Setup.local'))\n\n\n_sys_home = getattr(sys, '_home', None)\n\n\ndef _is_parent(dir_a, dir_b):\n    \"\"\"\n    Return True if a is a parent of b.\n    \"\"\"\n    return os.path.normcase(dir_a).startswith(os.path.normcase(dir_b))\n\n\nif os.name == 'nt':\n\n    @pass_none\n    def _fix_pcbuild(d):\n        # In a venv, sys._home will be inside BASE_PREFIX rather than PREFIX.\n        prefixes = PREFIX, BASE_PREFIX\n        matched = (\n            prefix\n            for prefix in prefixes\n            if _is_parent(d, os.path.join(prefix, \"PCbuild\"))\n        )\n        return next(matched, d)\n\n    project_base = _fix_pcbuild(project_base)\n    _sys_home = _fix_pcbuild(_sys_home)\n\n\ndef _python_build():\n    if _sys_home:\n        return _is_python_source_dir(_sys_home)\n    return _is_python_source_dir(project_base)\n\n\npython_build = _python_build()\n\n\n# Calculate the build qualifier flags if they are defined.  Adding the flags\n# to the include and lib directories only makes sense for an installation, not\n# an in-source build.\nbuild_flags = ''\ntry:\n    if not python_build:\n        build_flags = sys.abiflags\nexcept AttributeError:\n    # It's not a configure-based build, so the sys module doesn't have\n    # this attribute, which is fine.\n    pass\n\n\ndef get_python_version():\n    \"\"\"Return a string containing the major and minor Python version,\n    leaving off the patchlevel.  Sample return values could be '1.5'\n    or '2.2'.\n    \"\"\"\n    return '%d.%d' % sys.version_info[:2]\n\n\ndef get_python_inc(plat_specific=0, prefix=None):\n    \"\"\"Return the directory containing installed Python header files.\n\n    If 'plat_specific' is false (the default), this is the path to the\n    non-platform-specific header files, i.e. Python.h and so on;\n    otherwise, this is the path to platform-specific header files\n    (namely pyconfig.h).\n\n    If 'prefix' is supplied, use it instead of sys.base_prefix or\n    sys.base_exec_prefix -- i.e., ignore 'plat_specific'.\n    \"\"\"\n    default_prefix = BASE_EXEC_PREFIX if plat_specific else BASE_PREFIX\n    resolved_prefix = prefix if prefix is not None else default_prefix\n    try:\n        getter = globals()[f'_get_python_inc_{os.name}']\n    except KeyError:\n        raise DistutilsPlatformError(\n            \"I don't know where Python installs its C header files \"\n            \"on platform '%s'\" % os.name\n        )\n    return getter(resolved_prefix, prefix, plat_specific)\n\n\ndef _get_python_inc_posix(prefix, spec_prefix, plat_specific):\n    if IS_PYPY and sys.version_info < (3, 8):\n        return os.path.join(prefix, 'include')\n    return (\n        _get_python_inc_posix_python(plat_specific)\n        or _get_python_inc_from_config(plat_specific, spec_prefix)\n        or _get_python_inc_posix_prefix(prefix)\n    )\n\n\ndef _get_python_inc_posix_python(plat_specific):\n    \"\"\"\n    Assume the executable is in the build directory. The\n    pyconfig.h file should be in the same directory. Since\n    the build directory may not be the source directory,\n    use \"srcdir\" from the makefile to find the \"Include\"\n    directory.\n    \"\"\"\n    if not python_build:\n        return\n    if plat_specific:\n        return _sys_home or project_base\n    incdir = os.path.join(get_config_var('srcdir'), 'Include')\n    return os.path.normpath(incdir)\n\n\ndef _get_python_inc_from_config(plat_specific, spec_prefix):\n    \"\"\"\n    If no prefix was explicitly specified, provide the include\n    directory from the config vars. Useful when\n    cross-compiling, since the config vars may come from\n    the host\n    platform Python installation, while the current Python\n    executable is from the build platform installation.\n\n    >>> monkeypatch = getfixture('monkeypatch')\n    >>> gpifc = _get_python_inc_from_config\n    >>> monkeypatch.setitem(gpifc.__globals__, 'get_config_var', str.lower)\n    >>> gpifc(False, '/usr/bin/')\n    >>> gpifc(False, '')\n    >>> gpifc(False, None)\n    'includepy'\n    >>> gpifc(True, None)\n    'confincludepy'\n    \"\"\"\n    if spec_prefix is None:\n        return get_config_var('CONF' * plat_specific + 'INCLUDEPY')\n\n\ndef _get_python_inc_posix_prefix(prefix):\n    implementation = 'pypy' if IS_PYPY else 'python'\n    python_dir = implementation + get_python_version() + build_flags\n    return os.path.join(prefix, \"include\", python_dir)\n\n\ndef _get_python_inc_nt(prefix, spec_prefix, plat_specific):\n    if python_build:\n        # Include both the include and PC dir to ensure we can find\n        # pyconfig.h\n        return (\n            os.path.join(prefix, \"include\")\n            + os.path.pathsep\n            + os.path.join(prefix, \"PC\")\n        )\n    return os.path.join(prefix, \"include\")\n\n\n# allow this behavior to be monkey-patched. Ref pypa/distutils#2.\ndef _posix_lib(standard_lib, libpython, early_prefix, prefix):\n    if standard_lib:\n        return libpython\n    else:\n        return os.path.join(libpython, \"site-packages\")\n\n\ndef get_python_lib(plat_specific=0, standard_lib=0, prefix=None):\n    \"\"\"Return the directory containing the Python library (standard or\n    site additions).\n\n    If 'plat_specific' is true, return the directory containing\n    platform-specific modules, i.e. any module from a non-pure-Python\n    module distribution; otherwise, return the platform-shared library\n    directory.  If 'standard_lib' is true, return the directory\n    containing standard Python library modules; otherwise, return the\n    directory for site-specific modules.\n\n    If 'prefix' is supplied, use it instead of sys.base_prefix or\n    sys.base_exec_prefix -- i.e., ignore 'plat_specific'.\n    \"\"\"\n\n    if IS_PYPY and sys.version_info < (3, 8):\n        # PyPy-specific schema\n        if prefix is None:\n            prefix = PREFIX\n        if standard_lib:\n            return os.path.join(prefix, \"lib-python\", sys.version[0])\n        return os.path.join(prefix, 'site-packages')\n\n    early_prefix = prefix\n\n    if prefix is None:\n        if standard_lib:\n            prefix = plat_specific and BASE_EXEC_PREFIX or BASE_PREFIX\n        else:\n            prefix = plat_specific and EXEC_PREFIX or PREFIX\n\n    if os.name == \"posix\":\n        if plat_specific or standard_lib:\n            # Platform-specific modules (any module from a non-pure-Python\n            # module distribution) or standard Python library modules.\n            libdir = getattr(sys, \"platlibdir\", \"lib\")\n        else:\n            # Pure Python\n            libdir = \"lib\"\n        implementation = 'pypy' if IS_PYPY else 'python'\n        libpython = os.path.join(prefix, libdir, implementation + get_python_version())\n        return _posix_lib(standard_lib, libpython, early_prefix, prefix)\n    elif os.name == \"nt\":\n        if standard_lib:\n            return os.path.join(prefix, \"Lib\")\n        else:\n            return os.path.join(prefix, \"Lib\", \"site-packages\")\n    else:\n        raise DistutilsPlatformError(\n            \"I don't know where Python installs its library \"\n            \"on platform '%s'\" % os.name\n        )\n\n\ndef customize_compiler(compiler):  # noqa: C901\n    \"\"\"Do any platform-specific customization of a CCompiler instance.\n\n    Mainly needed on Unix, so we can plug in the information that\n    varies across Unices and is stored in Python's Makefile.\n    \"\"\"\n    if compiler.compiler_type == \"unix\":\n        if sys.platform == \"darwin\":\n            # Perform first-time customization of compiler-related\n            # config vars on OS X now that we know we need a compiler.\n            # This is primarily to support Pythons from binary\n            # installers.  The kind and paths to build tools on\n            # the user system may vary significantly from the system\n            # that Python itself was built on.  Also the user OS\n            # version and build tools may not support the same set\n            # of CPU architectures for universal builds.\n            global _config_vars\n            # Use get_config_var() to ensure _config_vars is initialized.\n            if not get_config_var('CUSTOMIZED_OSX_COMPILER'):\n                import _osx_support\n\n                _osx_support.customize_compiler(_config_vars)\n                _config_vars['CUSTOMIZED_OSX_COMPILER'] = 'True'\n\n        (\n            cc,\n            cxx,\n            cflags,\n            ccshared,\n            ldshared,\n            shlib_suffix,\n            ar,\n            ar_flags,\n        ) = get_config_vars(\n            'CC',\n            'CXX',\n            'CFLAGS',\n            'CCSHARED',\n            'LDSHARED',\n            'SHLIB_SUFFIX',\n            'AR',\n            'ARFLAGS',\n        )\n\n        if 'CC' in os.environ:\n            newcc = os.environ['CC']\n            if 'LDSHARED' not in os.environ and ldshared.startswith(cc):\n                # If CC is overridden, use that as the default\n                #       command for LDSHARED as well\n                ldshared = newcc + ldshared[len(cc) :]\n            cc = newcc\n        if 'CXX' in os.environ:\n            cxx = os.environ['CXX']\n        if 'LDSHARED' in os.environ:\n            ldshared = os.environ['LDSHARED']\n        if 'CPP' in os.environ:\n            cpp = os.environ['CPP']\n        else:\n            cpp = cc + \" -E\"  # not always\n        if 'LDFLAGS' in os.environ:\n            ldshared = ldshared + ' ' + os.environ['LDFLAGS']\n        if 'CFLAGS' in os.environ:\n            cflags = cflags + ' ' + os.environ['CFLAGS']\n            ldshared = ldshared + ' ' + os.environ['CFLAGS']\n        if 'CPPFLAGS' in os.environ:\n            cpp = cpp + ' ' + os.environ['CPPFLAGS']\n            cflags = cflags + ' ' + os.environ['CPPFLAGS']\n            ldshared = ldshared + ' ' + os.environ['CPPFLAGS']\n        if 'AR' in os.environ:\n            ar = os.environ['AR']\n        if 'ARFLAGS' in os.environ:\n            archiver = ar + ' ' + os.environ['ARFLAGS']\n        else:\n            archiver = ar + ' ' + ar_flags\n\n        cc_cmd = cc + ' ' + cflags\n        compiler.set_executables(\n            preprocessor=cpp,\n            compiler=cc_cmd,\n            compiler_so=cc_cmd + ' ' + ccshared,\n            compiler_cxx=cxx,\n            linker_so=ldshared,\n            linker_exe=cc,\n            archiver=archiver,\n        )\n\n        if 'RANLIB' in os.environ and compiler.executables.get('ranlib', None):\n            compiler.set_executables(ranlib=os.environ['RANLIB'])\n\n        compiler.shared_lib_extension = shlib_suffix\n\n\ndef get_config_h_filename():\n    \"\"\"Return full pathname of installed pyconfig.h file.\"\"\"\n    if python_build:\n        if os.name == \"nt\":\n            inc_dir = os.path.join(_sys_home or project_base, \"PC\")\n        else:\n            inc_dir = _sys_home or project_base\n        return os.path.join(inc_dir, 'pyconfig.h')\n    else:\n        return sysconfig.get_config_h_filename()\n\n\ndef get_makefile_filename():\n    \"\"\"Return full pathname of installed Makefile from the Python build.\"\"\"\n    return sysconfig.get_makefile_filename()\n\n\ndef parse_config_h(fp, g=None):\n    \"\"\"Parse a config.h-style file.\n\n    A dictionary containing name/value pairs is returned.  If an\n    optional dictionary is passed in as the second argument, it is\n    used instead of a new dictionary.\n    \"\"\"\n    return sysconfig.parse_config_h(fp, vars=g)\n\n\n# Regexes needed for parsing Makefile (and similar syntaxes,\n# like old-style Setup files).\n_variable_rx = re.compile(r\"([a-zA-Z][a-zA-Z0-9_]+)\\s*=\\s*(.*)\")\n_findvar1_rx = re.compile(r\"\\$\\(([A-Za-z][A-Za-z0-9_]*)\\)\")\n_findvar2_rx = re.compile(r\"\\${([A-Za-z][A-Za-z0-9_]*)}\")\n\n\ndef parse_makefile(fn, g=None):  # noqa: C901\n    \"\"\"Parse a Makefile-style file.\n\n    A dictionary containing name/value pairs is returned.  If an\n    optional dictionary is passed in as the second argument, it is\n    used instead of a new dictionary.\n    \"\"\"\n    from distutils.text_file import TextFile\n\n    fp = TextFile(\n        fn, strip_comments=1, skip_blanks=1, join_lines=1, errors=\"surrogateescape\"\n    )\n\n    if g is None:\n        g = {}\n    done = {}\n    notdone = {}\n\n    while True:\n        line = fp.readline()\n        if line is None:  # eof\n            break\n        m = _variable_rx.match(line)\n        if m:\n            n, v = m.group(1, 2)\n            v = v.strip()\n            # `$$' is a literal `$' in make\n            tmpv = v.replace('$$', '')\n\n            if \"$\" in tmpv:\n                notdone[n] = v\n            else:\n                try:\n                    v = int(v)\n                except ValueError:\n                    # insert literal `$'\n                    done[n] = v.replace('$$', '$')\n                else:\n                    done[n] = v\n\n    # Variables with a 'PY_' prefix in the makefile. These need to\n    # be made available without that prefix through sysconfig.\n    # Special care is needed to ensure that variable expansion works, even\n    # if the expansion uses the name without a prefix.\n    renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS')\n\n    # do variable interpolation here\n    while notdone:\n        for name in list(notdone):\n            value = notdone[name]\n            m = _findvar1_rx.search(value) or _findvar2_rx.search(value)\n            if m:\n                n = m.group(1)\n                found = True\n                if n in done:\n                    item = str(done[n])\n                elif n in notdone:\n                    # get it on a subsequent round\n                    found = False\n                elif n in os.environ:\n                    # do it like make: fall back to environment\n                    item = os.environ[n]\n\n                elif n in renamed_variables:\n                    if name.startswith('PY_') and name[3:] in renamed_variables:\n                        item = \"\"\n\n                    elif 'PY_' + n in notdone:\n                        found = False\n\n                    else:\n                        item = str(done['PY_' + n])\n                else:\n                    done[n] = item = \"\"\n                if found:\n                    after = value[m.end() :]\n                    value = value[: m.start()] + item + after\n                    if \"$\" in after:\n                        notdone[name] = value\n                    else:\n                        try:\n                            value = int(value)\n                        except ValueError:\n                            done[name] = value.strip()\n                        else:\n                            done[name] = value\n                        del notdone[name]\n\n                        if name.startswith('PY_') and name[3:] in renamed_variables:\n\n                            name = name[3:]\n                            if name not in done:\n                                done[name] = value\n            else:\n                # bogus variable reference; just drop it since we can't deal\n                del notdone[name]\n\n    fp.close()\n\n    # strip spurious spaces\n    for k, v in done.items():\n        if isinstance(v, str):\n            done[k] = v.strip()\n\n    # save the results in the global dictionary\n    g.update(done)\n    return g\n\n\ndef expand_makefile_vars(s, vars):\n    \"\"\"Expand Makefile-style variables -- \"${foo}\" or \"$(foo)\" -- in\n    'string' according to 'vars' (a dictionary mapping variable names to\n    values).  Variables not present in 'vars' are silently expanded to the\n    empty string.  The variable values in 'vars' should not contain further\n    variable expansions; if 'vars' is the output of 'parse_makefile()',\n    you're fine.  Returns a variable-expanded version of 's'.\n    \"\"\"\n\n    # This algorithm does multiple expansion, so if vars['foo'] contains\n    # \"${bar}\", it will expand ${foo} to ${bar}, and then expand\n    # ${bar}... and so forth.  This is fine as long as 'vars' comes from\n    # 'parse_makefile()', which takes care of such expansions eagerly,\n    # according to make's variable expansion semantics.\n\n    while True:\n        m = _findvar1_rx.search(s) or _findvar2_rx.search(s)\n        if m:\n            (beg, end) = m.span()\n            s = s[0:beg] + vars.get(m.group(1)) + s[end:]\n        else:\n            break\n    return s\n\n\n_config_vars = None\n\n\ndef get_config_vars(*args):\n    \"\"\"With no arguments, return a dictionary of all configuration\n    variables relevant for the current platform.  Generally this includes\n    everything needed to build extensions and install both pure modules and\n    extensions.  On Unix, this means every variable defined in Python's\n    installed Makefile; on Windows it's a much smaller set.\n\n    With arguments, return a list of values that result from looking up\n    each argument in the configuration variable dictionary.\n    \"\"\"\n    global _config_vars\n    if _config_vars is None:\n        _config_vars = sysconfig.get_config_vars().copy()\n        py39compat.add_ext_suffix(_config_vars)\n\n    if args:\n        vals = []\n        for name in args:\n            vals.append(_config_vars.get(name))\n        return vals\n    else:\n        return _config_vars\n\n\ndef get_config_var(name):\n    \"\"\"Return the value of a single variable using the dictionary\n    returned by 'get_config_vars()'.  Equivalent to\n    get_config_vars().get(name)\n    \"\"\"\n    if name == 'SO':\n        import warnings\n\n        warnings.warn('SO is deprecated, use EXT_SUFFIX', DeprecationWarning, 2)\n    return get_config_vars().get(name)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/text_file.py",
    "content": "\"\"\"text_file\n\nprovides the TextFile class, which gives an interface to text files\nthat (optionally) takes care of stripping comments, ignoring blank\nlines, and joining lines with backslashes.\"\"\"\n\nimport sys\n\n\nclass TextFile:\n    \"\"\"Provides a file-like object that takes care of all the things you\n    commonly want to do when processing a text file that has some\n    line-by-line syntax: strip comments (as long as \"#\" is your\n    comment character), skip blank lines, join adjacent lines by\n    escaping the newline (ie. backslash at end of line), strip\n    leading and/or trailing whitespace.  All of these are optional\n    and independently controllable.\n\n    Provides a 'warn()' method so you can generate warning messages that\n    report physical line number, even if the logical line in question\n    spans multiple physical lines.  Also provides 'unreadline()' for\n    implementing line-at-a-time lookahead.\n\n    Constructor is called as:\n\n        TextFile (filename=None, file=None, **options)\n\n    It bombs (RuntimeError) if both 'filename' and 'file' are None;\n    'filename' should be a string, and 'file' a file object (or\n    something that provides 'readline()' and 'close()' methods).  It is\n    recommended that you supply at least 'filename', so that TextFile\n    can include it in warning messages.  If 'file' is not supplied,\n    TextFile creates its own using 'io.open()'.\n\n    The options are all boolean, and affect the value returned by\n    'readline()':\n      strip_comments [default: true]\n        strip from \"#\" to end-of-line, as well as any whitespace\n        leading up to the \"#\" -- unless it is escaped by a backslash\n      lstrip_ws [default: false]\n        strip leading whitespace from each line before returning it\n      rstrip_ws [default: true]\n        strip trailing whitespace (including line terminator!) from\n        each line before returning it\n      skip_blanks [default: true}\n        skip lines that are empty *after* stripping comments and\n        whitespace.  (If both lstrip_ws and rstrip_ws are false,\n        then some lines may consist of solely whitespace: these will\n        *not* be skipped, even if 'skip_blanks' is true.)\n      join_lines [default: false]\n        if a backslash is the last non-newline character on a line\n        after stripping comments and whitespace, join the following line\n        to it to form one \"logical line\"; if N consecutive lines end\n        with a backslash, then N+1 physical lines will be joined to\n        form one logical line.\n      collapse_join [default: false]\n        strip leading whitespace from lines that are joined to their\n        predecessor; only matters if (join_lines and not lstrip_ws)\n      errors [default: 'strict']\n        error handler used to decode the file content\n\n    Note that since 'rstrip_ws' can strip the trailing newline, the\n    semantics of 'readline()' must differ from those of the builtin file\n    object's 'readline()' method!  In particular, 'readline()' returns\n    None for end-of-file: an empty string might just be a blank line (or\n    an all-whitespace line), if 'rstrip_ws' is true but 'skip_blanks' is\n    not.\"\"\"\n\n    default_options = {\n        'strip_comments': 1,\n        'skip_blanks': 1,\n        'lstrip_ws': 0,\n        'rstrip_ws': 1,\n        'join_lines': 0,\n        'collapse_join': 0,\n        'errors': 'strict',\n    }\n\n    def __init__(self, filename=None, file=None, **options):\n        \"\"\"Construct a new TextFile object.  At least one of 'filename'\n        (a string) and 'file' (a file-like object) must be supplied.\n        They keyword argument options are described above and affect\n        the values returned by 'readline()'.\"\"\"\n        if filename is None and file is None:\n            raise RuntimeError(\n                \"you must supply either or both of 'filename' and 'file'\"\n            )\n\n        # set values for all options -- either from client option hash\n        # or fallback to default_options\n        for opt in self.default_options.keys():\n            if opt in options:\n                setattr(self, opt, options[opt])\n            else:\n                setattr(self, opt, self.default_options[opt])\n\n        # sanity check client option hash\n        for opt in options.keys():\n            if opt not in self.default_options:\n                raise KeyError(\"invalid TextFile option '%s'\" % opt)\n\n        if file is None:\n            self.open(filename)\n        else:\n            self.filename = filename\n            self.file = file\n            self.current_line = 0  # assuming that file is at BOF!\n\n        # 'linebuf' is a stack of lines that will be emptied before we\n        # actually read from the file; it's only populated by an\n        # 'unreadline()' operation\n        self.linebuf = []\n\n    def open(self, filename):\n        \"\"\"Open a new file named 'filename'.  This overrides both the\n        'filename' and 'file' arguments to the constructor.\"\"\"\n        self.filename = filename\n        self.file = open(self.filename, errors=self.errors)\n        self.current_line = 0\n\n    def close(self):\n        \"\"\"Close the current file and forget everything we know about it\n        (filename, current line number).\"\"\"\n        file = self.file\n        self.file = None\n        self.filename = None\n        self.current_line = None\n        file.close()\n\n    def gen_error(self, msg, line=None):\n        outmsg = []\n        if line is None:\n            line = self.current_line\n        outmsg.append(self.filename + \", \")\n        if isinstance(line, (list, tuple)):\n            outmsg.append(\"lines %d-%d: \" % tuple(line))\n        else:\n            outmsg.append(\"line %d: \" % line)\n        outmsg.append(str(msg))\n        return \"\".join(outmsg)\n\n    def error(self, msg, line=None):\n        raise ValueError(\"error: \" + self.gen_error(msg, line))\n\n    def warn(self, msg, line=None):\n        \"\"\"Print (to stderr) a warning message tied to the current logical\n        line in the current file.  If the current logical line in the\n        file spans multiple physical lines, the warning refers to the\n        whole range, eg. \"lines 3-5\".  If 'line' supplied, it overrides\n        the current line number; it may be a list or tuple to indicate a\n        range of physical lines, or an integer for a single physical\n        line.\"\"\"\n        sys.stderr.write(\"warning: \" + self.gen_error(msg, line) + \"\\n\")\n\n    def readline(self):  # noqa: C901\n        \"\"\"Read and return a single logical line from the current file (or\n        from an internal buffer if lines have previously been \"unread\"\n        with 'unreadline()').  If the 'join_lines' option is true, this\n        may involve reading multiple physical lines concatenated into a\n        single string.  Updates the current line number, so calling\n        'warn()' after 'readline()' emits a warning about the physical\n        line(s) just read.  Returns None on end-of-file, since the empty\n        string can occur if 'rstrip_ws' is true but 'strip_blanks' is\n        not.\"\"\"\n        # If any \"unread\" lines waiting in 'linebuf', return the top\n        # one.  (We don't actually buffer read-ahead data -- lines only\n        # get put in 'linebuf' if the client explicitly does an\n        # 'unreadline()'.\n        if self.linebuf:\n            line = self.linebuf[-1]\n            del self.linebuf[-1]\n            return line\n\n        buildup_line = ''\n\n        while True:\n            # read the line, make it None if EOF\n            line = self.file.readline()\n            if line == '':\n                line = None\n\n            if self.strip_comments and line:\n\n                # Look for the first \"#\" in the line.  If none, never\n                # mind.  If we find one and it's the first character, or\n                # is not preceded by \"\\\", then it starts a comment --\n                # strip the comment, strip whitespace before it, and\n                # carry on.  Otherwise, it's just an escaped \"#\", so\n                # unescape it (and any other escaped \"#\"'s that might be\n                # lurking in there) and otherwise leave the line alone.\n\n                pos = line.find(\"#\")\n                if pos == -1:  # no \"#\" -- no comments\n                    pass\n\n                # It's definitely a comment -- either \"#\" is the first\n                # character, or it's elsewhere and unescaped.\n                elif pos == 0 or line[pos - 1] != \"\\\\\":\n                    # Have to preserve the trailing newline, because it's\n                    # the job of a later step (rstrip_ws) to remove it --\n                    # and if rstrip_ws is false, we'd better preserve it!\n                    # (NB. this means that if the final line is all comment\n                    # and has no trailing newline, we will think that it's\n                    # EOF; I think that's OK.)\n                    eol = (line[-1] == '\\n') and '\\n' or ''\n                    line = line[0:pos] + eol\n\n                    # If all that's left is whitespace, then skip line\n                    # *now*, before we try to join it to 'buildup_line' --\n                    # that way constructs like\n                    #   hello \\\\\n                    #   # comment that should be ignored\n                    #   there\n                    # result in \"hello there\".\n                    if line.strip() == \"\":\n                        continue\n                else:  # it's an escaped \"#\"\n                    line = line.replace(\"\\\\#\", \"#\")\n\n            # did previous line end with a backslash? then accumulate\n            if self.join_lines and buildup_line:\n                # oops: end of file\n                if line is None:\n                    self.warn(\"continuation line immediately precedes \" \"end-of-file\")\n                    return buildup_line\n\n                if self.collapse_join:\n                    line = line.lstrip()\n                line = buildup_line + line\n\n                # careful: pay attention to line number when incrementing it\n                if isinstance(self.current_line, list):\n                    self.current_line[1] = self.current_line[1] + 1\n                else:\n                    self.current_line = [self.current_line, self.current_line + 1]\n            # just an ordinary line, read it as usual\n            else:\n                if line is None:  # eof\n                    return None\n\n                # still have to be careful about incrementing the line number!\n                if isinstance(self.current_line, list):\n                    self.current_line = self.current_line[1] + 1\n                else:\n                    self.current_line = self.current_line + 1\n\n            # strip whitespace however the client wants (leading and\n            # trailing, or one or the other, or neither)\n            if self.lstrip_ws and self.rstrip_ws:\n                line = line.strip()\n            elif self.lstrip_ws:\n                line = line.lstrip()\n            elif self.rstrip_ws:\n                line = line.rstrip()\n\n            # blank line (whether we rstrip'ed or not)? skip to next line\n            # if appropriate\n            if (line == '' or line == '\\n') and self.skip_blanks:\n                continue\n\n            if self.join_lines:\n                if line[-1] == '\\\\':\n                    buildup_line = line[:-1]\n                    continue\n\n                if line[-2:] == '\\\\\\n':\n                    buildup_line = line[0:-2] + '\\n'\n                    continue\n\n            # well, I guess there's some actual content there: return it\n            return line\n\n    def readlines(self):\n        \"\"\"Read and return the list of all logical lines remaining in the\n        current file.\"\"\"\n        lines = []\n        while True:\n            line = self.readline()\n            if line is None:\n                return lines\n            lines.append(line)\n\n    def unreadline(self, line):\n        \"\"\"Push 'line' (a string) onto an internal buffer that will be\n        checked by future 'readline()' calls.  Handy for implementing\n        a parser with line-at-a-time lookahead.\"\"\"\n        self.linebuf.append(line)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/unixccompiler.py",
    "content": "\"\"\"distutils.unixccompiler\n\nContains the UnixCCompiler class, a subclass of CCompiler that handles\nthe \"typical\" Unix-style command-line C compiler:\n  * macros defined with -Dname[=value]\n  * macros undefined with -Uname\n  * include search directories specified with -Idir\n  * libraries specified with -lllib\n  * library search directories specified with -Ldir\n  * compile handled by 'cc' (or similar) executable with -c option:\n    compiles .c to .o\n  * link static library handled by 'ar' command (possibly with 'ranlib')\n  * link shared library handled by 'cc -shared'\n\"\"\"\n\nimport os\nimport sys\nimport re\nimport shlex\nimport itertools\n\nfrom distutils import sysconfig\nfrom distutils.dep_util import newer\nfrom distutils.ccompiler import CCompiler, gen_preprocess_options, gen_lib_options\nfrom distutils.errors import DistutilsExecError, CompileError, LibError, LinkError\nfrom distutils import log\nfrom ._macos_compat import compiler_fixup\n\n# XXX Things not currently handled:\n#   * optimization/debug/warning flags; we just use whatever's in Python's\n#     Makefile and live with it.  Is this adequate?  If not, we might\n#     have to have a bunch of subclasses GNUCCompiler, SGICCompiler,\n#     SunCCompiler, and I suspect down that road lies madness.\n#   * even if we don't know a warning flag from an optimization flag,\n#     we need some way for outsiders to feed preprocessor/compiler/linker\n#     flags in to us -- eg. a sysadmin might want to mandate certain flags\n#     via a site config file, or a user might want to set something for\n#     compiling this module distribution only via the setup.py command\n#     line, whatever.  As long as these options come from something on the\n#     current system, they can be as system-dependent as they like, and we\n#     should just happily stuff them into the preprocessor/compiler/linker\n#     options and carry on.\n\n\ndef _split_env(cmd):\n    \"\"\"\n    For macOS, split command into 'env' portion (if any)\n    and the rest of the linker command.\n\n    >>> _split_env(['a', 'b', 'c'])\n    ([], ['a', 'b', 'c'])\n    >>> _split_env(['/usr/bin/env', 'A=3', 'gcc'])\n    (['/usr/bin/env', 'A=3'], ['gcc'])\n    \"\"\"\n    pivot = 0\n    if os.path.basename(cmd[0]) == \"env\":\n        pivot = 1\n        while '=' in cmd[pivot]:\n            pivot += 1\n    return cmd[:pivot], cmd[pivot:]\n\n\ndef _split_aix(cmd):\n    \"\"\"\n    AIX platforms prefix the compiler with the ld_so_aix\n    script, so split that from the linker command.\n\n    >>> _split_aix(['a', 'b', 'c'])\n    ([], ['a', 'b', 'c'])\n    >>> _split_aix(['/bin/foo/ld_so_aix', 'gcc'])\n    (['/bin/foo/ld_so_aix'], ['gcc'])\n    \"\"\"\n    pivot = os.path.basename(cmd[0]) == 'ld_so_aix'\n    return cmd[:pivot], cmd[pivot:]\n\n\ndef _linker_params(linker_cmd, compiler_cmd):\n    \"\"\"\n    The linker command usually begins with the compiler\n    command (possibly multiple elements), followed by zero or more\n    params for shared library building.\n\n    If the LDSHARED env variable overrides the linker command,\n    however, the commands may not match.\n\n    Return the best guess of the linker parameters by stripping\n    the linker command. If the compiler command does not\n    match the linker command, assume the linker command is\n    just the first element.\n\n    >>> _linker_params('gcc foo bar'.split(), ['gcc'])\n    ['foo', 'bar']\n    >>> _linker_params('gcc foo bar'.split(), ['other'])\n    ['foo', 'bar']\n    >>> _linker_params('ccache gcc foo bar'.split(), 'ccache gcc'.split())\n    ['foo', 'bar']\n    >>> _linker_params(['gcc'], ['gcc'])\n    []\n    \"\"\"\n    c_len = len(compiler_cmd)\n    pivot = c_len if linker_cmd[:c_len] == compiler_cmd else 1\n    return linker_cmd[pivot:]\n\n\nclass UnixCCompiler(CCompiler):\n\n    compiler_type = 'unix'\n\n    # These are used by CCompiler in two places: the constructor sets\n    # instance attributes 'preprocessor', 'compiler', etc. from them, and\n    # 'set_executable()' allows any of these to be set.  The defaults here\n    # are pretty generic; they will probably have to be set by an outsider\n    # (eg. using information discovered by the sysconfig about building\n    # Python extensions).\n    executables = {\n        'preprocessor': None,\n        'compiler': [\"cc\"],\n        'compiler_so': [\"cc\"],\n        'compiler_cxx': [\"cc\"],\n        'linker_so': [\"cc\", \"-shared\"],\n        'linker_exe': [\"cc\"],\n        'archiver': [\"ar\", \"-cr\"],\n        'ranlib': None,\n    }\n\n    if sys.platform[:6] == \"darwin\":\n        executables['ranlib'] = [\"ranlib\"]\n\n    # Needed for the filename generation methods provided by the base\n    # class, CCompiler.  NB. whoever instantiates/uses a particular\n    # UnixCCompiler instance should set 'shared_lib_ext' -- we set a\n    # reasonable common default here, but it's not necessarily used on all\n    # Unices!\n\n    src_extensions = [\".c\", \".C\", \".cc\", \".cxx\", \".cpp\", \".m\"]\n    obj_extension = \".o\"\n    static_lib_extension = \".a\"\n    shared_lib_extension = \".so\"\n    dylib_lib_extension = \".dylib\"\n    xcode_stub_lib_extension = \".tbd\"\n    static_lib_format = shared_lib_format = dylib_lib_format = \"lib%s%s\"\n    xcode_stub_lib_format = dylib_lib_format\n    if sys.platform == \"cygwin\":\n        exe_extension = \".exe\"\n\n    def preprocess(\n        self,\n        source,\n        output_file=None,\n        macros=None,\n        include_dirs=None,\n        extra_preargs=None,\n        extra_postargs=None,\n    ):\n        fixed_args = self._fix_compile_args(None, macros, include_dirs)\n        ignore, macros, include_dirs = fixed_args\n        pp_opts = gen_preprocess_options(macros, include_dirs)\n        pp_args = self.preprocessor + pp_opts\n        if output_file:\n            pp_args.extend(['-o', output_file])\n        if extra_preargs:\n            pp_args[:0] = extra_preargs\n        if extra_postargs:\n            pp_args.extend(extra_postargs)\n        pp_args.append(source)\n\n        # reasons to preprocess:\n        # - force is indicated\n        # - output is directed to stdout\n        # - source file is newer than the target\n        preprocess = self.force or output_file is None or newer(source, output_file)\n        if not preprocess:\n            return\n\n        if output_file:\n            self.mkpath(os.path.dirname(output_file))\n\n        try:\n            self.spawn(pp_args)\n        except DistutilsExecError as msg:\n            raise CompileError(msg)\n\n    def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):\n        compiler_so = compiler_fixup(self.compiler_so, cc_args + extra_postargs)\n        try:\n            self.spawn(compiler_so + cc_args + [src, '-o', obj] + extra_postargs)\n        except DistutilsExecError as msg:\n            raise CompileError(msg)\n\n    def create_static_lib(\n        self, objects, output_libname, output_dir=None, debug=0, target_lang=None\n    ):\n        objects, output_dir = self._fix_object_args(objects, output_dir)\n\n        output_filename = self.library_filename(output_libname, output_dir=output_dir)\n\n        if self._need_link(objects, output_filename):\n            self.mkpath(os.path.dirname(output_filename))\n            self.spawn(self.archiver + [output_filename] + objects + self.objects)\n\n            # Not many Unices required ranlib anymore -- SunOS 4.x is, I\n            # think the only major Unix that does.  Maybe we need some\n            # platform intelligence here to skip ranlib if it's not\n            # needed -- or maybe Python's configure script took care of\n            # it for us, hence the check for leading colon.\n            if self.ranlib:\n                try:\n                    self.spawn(self.ranlib + [output_filename])\n                except DistutilsExecError as msg:\n                    raise LibError(msg)\n        else:\n            log.debug(\"skipping %s (up-to-date)\", output_filename)\n\n    def link(\n        self,\n        target_desc,\n        objects,\n        output_filename,\n        output_dir=None,\n        libraries=None,\n        library_dirs=None,\n        runtime_library_dirs=None,\n        export_symbols=None,\n        debug=0,\n        extra_preargs=None,\n        extra_postargs=None,\n        build_temp=None,\n        target_lang=None,\n    ):\n        objects, output_dir = self._fix_object_args(objects, output_dir)\n        fixed_args = self._fix_lib_args(libraries, library_dirs, runtime_library_dirs)\n        libraries, library_dirs, runtime_library_dirs = fixed_args\n\n        lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, libraries)\n        if not isinstance(output_dir, (str, type(None))):\n            raise TypeError(\"'output_dir' must be a string or None\")\n        if output_dir is not None:\n            output_filename = os.path.join(output_dir, output_filename)\n\n        if self._need_link(objects, output_filename):\n            ld_args = objects + self.objects + lib_opts + ['-o', output_filename]\n            if debug:\n                ld_args[:0] = ['-g']\n            if extra_preargs:\n                ld_args[:0] = extra_preargs\n            if extra_postargs:\n                ld_args.extend(extra_postargs)\n            self.mkpath(os.path.dirname(output_filename))\n            try:\n                # Select a linker based on context: linker_exe when\n                # building an executable or linker_so (with shared options)\n                # when building a shared library.\n                building_exe = target_desc == CCompiler.EXECUTABLE\n                linker = (self.linker_exe if building_exe else self.linker_so)[:]\n\n                if target_lang == \"c++\" and self.compiler_cxx:\n                    env, linker_ne = _split_env(linker)\n                    aix, linker_na = _split_aix(linker_ne)\n                    _, compiler_cxx_ne = _split_env(self.compiler_cxx)\n                    _, linker_exe_ne = _split_env(self.linker_exe)\n\n                    params = _linker_params(linker_na, linker_exe_ne)\n                    linker = env + aix + compiler_cxx_ne + params\n\n                linker = compiler_fixup(linker, ld_args)\n\n                self.spawn(linker + ld_args)\n            except DistutilsExecError as msg:\n                raise LinkError(msg)\n        else:\n            log.debug(\"skipping %s (up-to-date)\", output_filename)\n\n    # -- Miscellaneous methods -----------------------------------------\n    # These are all used by the 'gen_lib_options() function, in\n    # ccompiler.py.\n\n    def library_dir_option(self, dir):\n        return \"-L\" + dir\n\n    def _is_gcc(self):\n        cc_var = sysconfig.get_config_var(\"CC\")\n        compiler = os.path.basename(shlex.split(cc_var)[0])\n        return \"gcc\" in compiler or \"g++\" in compiler\n\n    def runtime_library_dir_option(self, dir):\n        # XXX Hackish, at the very least.  See Python bug #445902:\n        # http://sourceforge.net/tracker/index.php\n        #   ?func=detail&aid=445902&group_id=5470&atid=105470\n        # Linkers on different platforms need different options to\n        # specify that directories need to be added to the list of\n        # directories searched for dependencies when a dynamic library\n        # is sought.  GCC on GNU systems (Linux, FreeBSD, ...) has to\n        # be told to pass the -R option through to the linker, whereas\n        # other compilers and gcc on other systems just know this.\n        # Other compilers may need something slightly different.  At\n        # this time, there's no way to determine this information from\n        # the configuration data stored in the Python installation, so\n        # we use this hack.\n        if sys.platform[:6] == \"darwin\":\n            from distutils.util import get_macosx_target_ver, split_version\n\n            macosx_target_ver = get_macosx_target_ver()\n            if macosx_target_ver and split_version(macosx_target_ver) >= [10, 5]:\n                return \"-Wl,-rpath,\" + dir\n            else:  # no support for -rpath on earlier macOS versions\n                return \"-L\" + dir\n        elif sys.platform[:7] == \"freebsd\":\n            return \"-Wl,-rpath=\" + dir\n        elif sys.platform[:5] == \"hp-ux\":\n            return [\n                \"-Wl,+s\" if self._is_gcc() else \"+s\",\n                \"-L\" + dir,\n            ]\n\n        # For all compilers, `-Wl` is the presumed way to\n        # pass a compiler option to the linker and `-R` is\n        # the way to pass an RPATH.\n        if sysconfig.get_config_var(\"GNULD\") == \"yes\":\n            # GNU ld needs an extra option to get a RUNPATH\n            # instead of just an RPATH.\n            return \"-Wl,--enable-new-dtags,-R\" + dir\n        else:\n            return \"-Wl,-R\" + dir\n\n    def library_option(self, lib):\n        return \"-l\" + lib\n\n    @staticmethod\n    def _library_root(dir):\n        \"\"\"\n        macOS users can specify an alternate SDK using'-isysroot'.\n        Calculate the SDK root if it is specified.\n\n        Note that, as of Xcode 7, Apple SDKs may contain textual stub\n        libraries with .tbd extensions rather than the normal .dylib\n        shared libraries installed in /.  The Apple compiler tool\n        chain handles this transparently but it can cause problems\n        for programs that are being built with an SDK and searching\n        for specific libraries.  Callers of find_library_file need to\n        keep in mind that the base filename of the returned SDK library\n        file might have a different extension from that of the library\n        file installed on the running system, for example:\n          /Applications/Xcode.app/Contents/Developer/Platforms/\n              MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/\n              usr/lib/libedit.tbd\n        vs\n          /usr/lib/libedit.dylib\n        \"\"\"\n        cflags = sysconfig.get_config_var('CFLAGS')\n        match = re.search(r'-isysroot\\s*(\\S+)', cflags)\n\n        apply_root = (\n            sys.platform == 'darwin'\n            and match\n            and (\n                dir.startswith('/System/')\n                or (dir.startswith('/usr/') and not dir.startswith('/usr/local/'))\n            )\n        )\n\n        return os.path.join(match.group(1), dir[1:]) if apply_root else dir\n\n    def find_library_file(self, dirs, lib, debug=0):\n        r\"\"\"\n        Second-guess the linker with not much hard\n        data to go on: GCC seems to prefer the shared library, so\n        assume that *all* Unix C compilers do,\n        ignoring even GCC's \"-static\" option.\n\n        >>> compiler = UnixCCompiler()\n        >>> compiler._library_root = lambda dir: dir\n        >>> monkeypatch = getfixture('monkeypatch')\n        >>> monkeypatch.setattr(os.path, 'exists', lambda d: 'existing' in d)\n        >>> dirs = ('/foo/bar/missing', '/foo/bar/existing')\n        >>> compiler.find_library_file(dirs, 'abc').replace('\\\\', '/')\n        '/foo/bar/existing/libabc.dylib'\n        >>> compiler.find_library_file(reversed(dirs), 'abc').replace('\\\\', '/')\n        '/foo/bar/existing/libabc.dylib'\n        >>> monkeypatch.setattr(os.path, 'exists',\n        ...     lambda d: 'existing' in d and '.a' in d)\n        >>> compiler.find_library_file(dirs, 'abc').replace('\\\\', '/')\n        '/foo/bar/existing/libabc.a'\n        >>> compiler.find_library_file(reversed(dirs), 'abc').replace('\\\\', '/')\n        '/foo/bar/existing/libabc.a'\n        \"\"\"\n        lib_names = (\n            self.library_filename(lib, lib_type=type)\n            for type in 'dylib xcode_stub shared static'.split()\n        )\n\n        roots = map(self._library_root, dirs)\n\n        searched = (\n            os.path.join(root, lib_name)\n            for root, lib_name in itertools.product(roots, lib_names)\n        )\n\n        found = filter(os.path.exists, searched)\n\n        # Return None if it could not be found in any dir.\n        return next(found, None)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/util.py",
    "content": "\"\"\"distutils.util\n\nMiscellaneous utility functions -- anything that doesn't fit into\none of the other *util.py modules.\n\"\"\"\n\nimport importlib.util\nimport os\nimport re\nimport string\nimport subprocess\nimport sys\nimport sysconfig\nimport functools\n\nfrom distutils.errors import DistutilsPlatformError, DistutilsByteCompileError\nfrom distutils.dep_util import newer\nfrom distutils.spawn import spawn\nfrom distutils import log\n\n\ndef get_host_platform():\n    \"\"\"\n    Return a string that identifies the current platform. Use this\n    function to distinguish platform-specific build directories and\n    platform-specific built distributions.\n    \"\"\"\n\n    # This function initially exposed platforms as defined in Python 3.9\n    # even with older Python versions when distutils was split out.\n    # Now it delegates to stdlib sysconfig, but maintains compatibility.\n\n    if sys.version_info < (3, 8):\n        if os.name == 'nt':\n            if '(arm)' in sys.version.lower():\n                return 'win-arm32'\n            if '(arm64)' in sys.version.lower():\n                return 'win-arm64'\n\n    if sys.version_info < (3, 9):\n        if os.name == \"posix\" and hasattr(os, 'uname'):\n            osname, host, release, version, machine = os.uname()\n            if osname[:3] == \"aix\":\n                from .py38compat import aix_platform\n\n                return aix_platform(osname, version, release)\n\n    return sysconfig.get_platform()\n\n\ndef get_platform():\n    if os.name == 'nt':\n        TARGET_TO_PLAT = {\n            'x86': 'win32',\n            'x64': 'win-amd64',\n            'arm': 'win-arm32',\n            'arm64': 'win-arm64',\n        }\n        target = os.environ.get('VSCMD_ARG_TGT_ARCH')\n        return TARGET_TO_PLAT.get(target) or get_host_platform()\n    return get_host_platform()\n\n\nif sys.platform == 'darwin':\n    _syscfg_macosx_ver = None  # cache the version pulled from sysconfig\nMACOSX_VERSION_VAR = 'MACOSX_DEPLOYMENT_TARGET'\n\n\ndef _clear_cached_macosx_ver():\n    \"\"\"For testing only. Do not call.\"\"\"\n    global _syscfg_macosx_ver\n    _syscfg_macosx_ver = None\n\n\ndef get_macosx_target_ver_from_syscfg():\n    \"\"\"Get the version of macOS latched in the Python interpreter configuration.\n    Returns the version as a string or None if can't obtain one. Cached.\"\"\"\n    global _syscfg_macosx_ver\n    if _syscfg_macosx_ver is None:\n        from distutils import sysconfig\n\n        ver = sysconfig.get_config_var(MACOSX_VERSION_VAR) or ''\n        if ver:\n            _syscfg_macosx_ver = ver\n    return _syscfg_macosx_ver\n\n\ndef get_macosx_target_ver():\n    \"\"\"Return the version of macOS for which we are building.\n\n    The target version defaults to the version in sysconfig latched at time\n    the Python interpreter was built, unless overridden by an environment\n    variable. If neither source has a value, then None is returned\"\"\"\n\n    syscfg_ver = get_macosx_target_ver_from_syscfg()\n    env_ver = os.environ.get(MACOSX_VERSION_VAR)\n\n    if env_ver:\n        # Validate overridden version against sysconfig version, if have both.\n        # Ensure that the deployment target of the build process is not less\n        # than 10.3 if the interpreter was built for 10.3 or later.  This\n        # ensures extension modules are built with correct compatibility\n        # values, specifically LDSHARED which can use\n        # '-undefined dynamic_lookup' which only works on >= 10.3.\n        if (\n            syscfg_ver\n            and split_version(syscfg_ver) >= [10, 3]\n            and split_version(env_ver) < [10, 3]\n        ):\n            my_msg = (\n                '$' + MACOSX_VERSION_VAR + ' mismatch: '\n                'now \"%s\" but \"%s\" during configure; '\n                'must use 10.3 or later' % (env_ver, syscfg_ver)\n            )\n            raise DistutilsPlatformError(my_msg)\n        return env_ver\n    return syscfg_ver\n\n\ndef split_version(s):\n    \"\"\"Convert a dot-separated string into a list of numbers for comparisons\"\"\"\n    return [int(n) for n in s.split('.')]\n\n\ndef convert_path(pathname):\n    \"\"\"Return 'pathname' as a name that will work on the native filesystem,\n    i.e. split it on '/' and put it back together again using the current\n    directory separator.  Needed because filenames in the setup script are\n    always supplied in Unix style, and have to be converted to the local\n    convention before we can actually use them in the filesystem.  Raises\n    ValueError on non-Unix-ish systems if 'pathname' either starts or\n    ends with a slash.\n    \"\"\"\n    if os.sep == '/':\n        return pathname\n    if not pathname:\n        return pathname\n    if pathname[0] == '/':\n        raise ValueError(\"path '%s' cannot be absolute\" % pathname)\n    if pathname[-1] == '/':\n        raise ValueError(\"path '%s' cannot end with '/'\" % pathname)\n\n    paths = pathname.split('/')\n    while '.' in paths:\n        paths.remove('.')\n    if not paths:\n        return os.curdir\n    return os.path.join(*paths)\n\n\n# convert_path ()\n\n\ndef change_root(new_root, pathname):\n    \"\"\"Return 'pathname' with 'new_root' prepended.  If 'pathname' is\n    relative, this is equivalent to \"os.path.join(new_root,pathname)\".\n    Otherwise, it requires making 'pathname' relative and then joining the\n    two, which is tricky on DOS/Windows and Mac OS.\n    \"\"\"\n    if os.name == 'posix':\n        if not os.path.isabs(pathname):\n            return os.path.join(new_root, pathname)\n        else:\n            return os.path.join(new_root, pathname[1:])\n\n    elif os.name == 'nt':\n        (drive, path) = os.path.splitdrive(pathname)\n        if path[0] == '\\\\':\n            path = path[1:]\n        return os.path.join(new_root, path)\n\n    raise DistutilsPlatformError(f\"nothing known about platform '{os.name}'\")\n\n\n@functools.lru_cache()\ndef check_environ():\n    \"\"\"Ensure that 'os.environ' has all the environment variables we\n    guarantee that users can use in config files, command-line options,\n    etc.  Currently this includes:\n      HOME - user's home directory (Unix only)\n      PLAT - description of the current platform, including hardware\n             and OS (see 'get_platform()')\n    \"\"\"\n    if os.name == 'posix' and 'HOME' not in os.environ:\n        try:\n            import pwd\n\n            os.environ['HOME'] = pwd.getpwuid(os.getuid())[5]\n        except (ImportError, KeyError):\n            # bpo-10496: if the current user identifier doesn't exist in the\n            # password database, do nothing\n            pass\n\n    if 'PLAT' not in os.environ:\n        os.environ['PLAT'] = get_platform()\n\n\ndef subst_vars(s, local_vars):\n    \"\"\"\n    Perform variable substitution on 'string'.\n    Variables are indicated by format-style braces (\"{var}\").\n    Variable is substituted by the value found in the 'local_vars'\n    dictionary or in 'os.environ' if it's not in 'local_vars'.\n    'os.environ' is first checked/augmented to guarantee that it contains\n    certain values: see 'check_environ()'.  Raise ValueError for any\n    variables not found in either 'local_vars' or 'os.environ'.\n    \"\"\"\n    check_environ()\n    lookup = dict(os.environ)\n    lookup.update((name, str(value)) for name, value in local_vars.items())\n    try:\n        return _subst_compat(s).format_map(lookup)\n    except KeyError as var:\n        raise ValueError(f\"invalid variable {var}\")\n\n\ndef _subst_compat(s):\n    \"\"\"\n    Replace shell/Perl-style variable substitution with\n    format-style. For compatibility.\n    \"\"\"\n\n    def _subst(match):\n        return f'{{{match.group(1)}}}'\n\n    repl = re.sub(r'\\$([a-zA-Z_][a-zA-Z_0-9]*)', _subst, s)\n    if repl != s:\n        import warnings\n\n        warnings.warn(\n            \"shell/Perl-style substitions are deprecated\",\n            DeprecationWarning,\n        )\n    return repl\n\n\ndef grok_environment_error(exc, prefix=\"error: \"):\n    # Function kept for backward compatibility.\n    # Used to try clever things with EnvironmentErrors,\n    # but nowadays str(exception) produces good messages.\n    return prefix + str(exc)\n\n\n# Needed by 'split_quoted()'\n_wordchars_re = _squote_re = _dquote_re = None\n\n\ndef _init_regex():\n    global _wordchars_re, _squote_re, _dquote_re\n    _wordchars_re = re.compile(r'[^\\\\\\'\\\"%s ]*' % string.whitespace)\n    _squote_re = re.compile(r\"'(?:[^'\\\\]|\\\\.)*'\")\n    _dquote_re = re.compile(r'\"(?:[^\"\\\\]|\\\\.)*\"')\n\n\ndef split_quoted(s):\n    \"\"\"Split a string up according to Unix shell-like rules for quotes and\n    backslashes.  In short: words are delimited by spaces, as long as those\n    spaces are not escaped by a backslash, or inside a quoted string.\n    Single and double quotes are equivalent, and the quote characters can\n    be backslash-escaped.  The backslash is stripped from any two-character\n    escape sequence, leaving only the escaped character.  The quote\n    characters are stripped from any quoted string.  Returns a list of\n    words.\n    \"\"\"\n\n    # This is a nice algorithm for splitting up a single string, since it\n    # doesn't require character-by-character examination.  It was a little\n    # bit of a brain-bender to get it working right, though...\n    if _wordchars_re is None:\n        _init_regex()\n\n    s = s.strip()\n    words = []\n    pos = 0\n\n    while s:\n        m = _wordchars_re.match(s, pos)\n        end = m.end()\n        if end == len(s):\n            words.append(s[:end])\n            break\n\n        if s[end] in string.whitespace:\n            # unescaped, unquoted whitespace: now\n            # we definitely have a word delimiter\n            words.append(s[:end])\n            s = s[end:].lstrip()\n            pos = 0\n\n        elif s[end] == '\\\\':\n            # preserve whatever is being escaped;\n            # will become part of the current word\n            s = s[:end] + s[end + 1 :]\n            pos = end + 1\n\n        else:\n            if s[end] == \"'\":  # slurp singly-quoted string\n                m = _squote_re.match(s, end)\n            elif s[end] == '\"':  # slurp doubly-quoted string\n                m = _dquote_re.match(s, end)\n            else:\n                raise RuntimeError(\"this can't happen (bad char '%c')\" % s[end])\n\n            if m is None:\n                raise ValueError(\"bad string (mismatched %s quotes?)\" % s[end])\n\n            (beg, end) = m.span()\n            s = s[:beg] + s[beg + 1 : end - 1] + s[end:]\n            pos = m.end() - 2\n\n        if pos >= len(s):\n            words.append(s)\n            break\n\n    return words\n\n\n# split_quoted ()\n\n\ndef execute(func, args, msg=None, verbose=0, dry_run=0):\n    \"\"\"Perform some action that affects the outside world (eg.  by\n    writing to the filesystem).  Such actions are special because they\n    are disabled by the 'dry_run' flag.  This method takes care of all\n    that bureaucracy for you; all you have to do is supply the\n    function to call and an argument tuple for it (to embody the\n    \"external action\" being performed), and an optional message to\n    print.\n    \"\"\"\n    if msg is None:\n        msg = \"{}{!r}\".format(func.__name__, args)\n        if msg[-2:] == ',)':  # correct for singleton tuple\n            msg = msg[0:-2] + ')'\n\n    log.info(msg)\n    if not dry_run:\n        func(*args)\n\n\ndef strtobool(val):\n    \"\"\"Convert a string representation of truth to true (1) or false (0).\n\n    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values\n    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if\n    'val' is anything else.\n    \"\"\"\n    val = val.lower()\n    if val in ('y', 'yes', 't', 'true', 'on', '1'):\n        return 1\n    elif val in ('n', 'no', 'f', 'false', 'off', '0'):\n        return 0\n    else:\n        raise ValueError(\"invalid truth value {!r}\".format(val))\n\n\ndef byte_compile(  # noqa: C901\n    py_files,\n    optimize=0,\n    force=0,\n    prefix=None,\n    base_dir=None,\n    verbose=1,\n    dry_run=0,\n    direct=None,\n):\n    \"\"\"Byte-compile a collection of Python source files to .pyc\n    files in a __pycache__ subdirectory.  'py_files' is a list\n    of files to compile; any files that don't end in \".py\" are silently\n    skipped.  'optimize' must be one of the following:\n      0 - don't optimize\n      1 - normal optimization (like \"python -O\")\n      2 - extra optimization (like \"python -OO\")\n    If 'force' is true, all files are recompiled regardless of\n    timestamps.\n\n    The source filename encoded in each bytecode file defaults to the\n    filenames listed in 'py_files'; you can modify these with 'prefix' and\n    'basedir'.  'prefix' is a string that will be stripped off of each\n    source filename, and 'base_dir' is a directory name that will be\n    prepended (after 'prefix' is stripped).  You can supply either or both\n    (or neither) of 'prefix' and 'base_dir', as you wish.\n\n    If 'dry_run' is true, doesn't actually do anything that would\n    affect the filesystem.\n\n    Byte-compilation is either done directly in this interpreter process\n    with the standard py_compile module, or indirectly by writing a\n    temporary script and executing it.  Normally, you should let\n    'byte_compile()' figure out to use direct compilation or not (see\n    the source for details).  The 'direct' flag is used by the script\n    generated in indirect mode; unless you know what you're doing, leave\n    it set to None.\n    \"\"\"\n\n    # nothing is done if sys.dont_write_bytecode is True\n    if sys.dont_write_bytecode:\n        raise DistutilsByteCompileError('byte-compiling is disabled.')\n\n    # First, if the caller didn't force us into direct or indirect mode,\n    # figure out which mode we should be in.  We take a conservative\n    # approach: choose direct mode *only* if the current interpreter is\n    # in debug mode and optimize is 0.  If we're not in debug mode (-O\n    # or -OO), we don't know which level of optimization this\n    # interpreter is running with, so we can't do direct\n    # byte-compilation and be certain that it's the right thing.  Thus,\n    # always compile indirectly if the current interpreter is in either\n    # optimize mode, or if either optimization level was requested by\n    # the caller.\n    if direct is None:\n        direct = __debug__ and optimize == 0\n\n    # \"Indirect\" byte-compilation: write a temporary script and then\n    # run it with the appropriate flags.\n    if not direct:\n        try:\n            from tempfile import mkstemp\n\n            (script_fd, script_name) = mkstemp(\".py\")\n        except ImportError:\n            from tempfile import mktemp\n\n            (script_fd, script_name) = None, mktemp(\".py\")\n        log.info(\"writing byte-compilation script '%s'\", script_name)\n        if not dry_run:\n            if script_fd is not None:\n                script = os.fdopen(script_fd, \"w\")\n            else:\n                script = open(script_name, \"w\")\n\n            with script:\n                script.write(\n                    \"\"\"\\\nfrom distutils.util import byte_compile\nfiles = [\n\"\"\"\n                )\n\n                # XXX would be nice to write absolute filenames, just for\n                # safety's sake (script should be more robust in the face of\n                # chdir'ing before running it).  But this requires abspath'ing\n                # 'prefix' as well, and that breaks the hack in build_lib's\n                # 'byte_compile()' method that carefully tacks on a trailing\n                # slash (os.sep really) to make sure the prefix here is \"just\n                # right\".  This whole prefix business is rather delicate -- the\n                # problem is that it's really a directory, but I'm treating it\n                # as a dumb string, so trailing slashes and so forth matter.\n\n                script.write(\",\\n\".join(map(repr, py_files)) + \"]\\n\")\n                script.write(\n                    \"\"\"\nbyte_compile(files, optimize=%r, force=%r,\n             prefix=%r, base_dir=%r,\n             verbose=%r, dry_run=0,\n             direct=1)\n\"\"\"\n                    % (optimize, force, prefix, base_dir, verbose)\n                )\n\n        cmd = [sys.executable]\n        cmd.extend(subprocess._optim_args_from_interpreter_flags())\n        cmd.append(script_name)\n        spawn(cmd, dry_run=dry_run)\n        execute(os.remove, (script_name,), \"removing %s\" % script_name, dry_run=dry_run)\n\n    # \"Direct\" byte-compilation: use the py_compile module to compile\n    # right here, right now.  Note that the script generated in indirect\n    # mode simply calls 'byte_compile()' in direct mode, a weird sort of\n    # cross-process recursion.  Hey, it works!\n    else:\n        from py_compile import compile\n\n        for file in py_files:\n            if file[-3:] != \".py\":\n                # This lets us be lazy and not filter filenames in\n                # the \"install_lib\" command.\n                continue\n\n            # Terminology from the py_compile module:\n            #   cfile - byte-compiled file\n            #   dfile - purported source filename (same as 'file' by default)\n            if optimize >= 0:\n                opt = '' if optimize == 0 else optimize\n                cfile = importlib.util.cache_from_source(file, optimization=opt)\n            else:\n                cfile = importlib.util.cache_from_source(file)\n            dfile = file\n            if prefix:\n                if file[: len(prefix)] != prefix:\n                    raise ValueError(\n                        \"invalid prefix: filename %r doesn't start with %r\"\n                        % (file, prefix)\n                    )\n                dfile = dfile[len(prefix) :]\n            if base_dir:\n                dfile = os.path.join(base_dir, dfile)\n\n            cfile_base = os.path.basename(cfile)\n            if direct:\n                if force or newer(file, cfile):\n                    log.info(\"byte-compiling %s to %s\", file, cfile_base)\n                    if not dry_run:\n                        compile(file, cfile, dfile)\n                else:\n                    log.debug(\"skipping byte-compilation of %s to %s\", file, cfile_base)\n\n\ndef rfc822_escape(header):\n    \"\"\"Return a version of the string escaped for inclusion in an\n    RFC-822 header, by ensuring there are 8 spaces space after each newline.\n    \"\"\"\n    lines = header.split('\\n')\n    sep = '\\n' + 8 * ' '\n    return sep.join(lines)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/version.py",
    "content": "#\n# distutils/version.py\n#\n# Implements multiple version numbering conventions for the\n# Python Module Distribution Utilities.\n#\n# $Id$\n#\n\n\"\"\"Provides classes to represent module version numbers (one class for\neach style of version numbering).  There are currently two such classes\nimplemented: StrictVersion and LooseVersion.\n\nEvery version number class implements the following interface:\n  * the 'parse' method takes a string and parses it to some internal\n    representation; if the string is an invalid version number,\n    'parse' raises a ValueError exception\n  * the class constructor takes an optional string argument which,\n    if supplied, is passed to 'parse'\n  * __str__ reconstructs the string that was passed to 'parse' (or\n    an equivalent string -- ie. one that will generate an equivalent\n    version number instance)\n  * __repr__ generates Python code to recreate the version number instance\n  * _cmp compares the current instance with either another instance\n    of the same class or a string (which will be parsed to an instance\n    of the same class, thus must follow the same rules)\n\"\"\"\n\nimport re\nimport warnings\nimport contextlib\n\n\n@contextlib.contextmanager\ndef suppress_known_deprecation():\n    with warnings.catch_warnings(record=True) as ctx:\n        warnings.filterwarnings(\n            action='default',\n            category=DeprecationWarning,\n            message=\"distutils Version classes are deprecated.\",\n        )\n        yield ctx\n\n\nclass Version:\n    \"\"\"Abstract base class for version numbering classes.  Just provides\n    constructor (__init__) and reproducer (__repr__), because those\n    seem to be the same for all version numbering classes; and route\n    rich comparisons to _cmp.\n    \"\"\"\n\n    def __init__(self, vstring=None):\n        if vstring:\n            self.parse(vstring)\n        warnings.warn(\n            \"distutils Version classes are deprecated. \"\n            \"Use packaging.version instead.\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n\n    def __repr__(self):\n        return \"{} ('{}')\".format(self.__class__.__name__, str(self))\n\n    def __eq__(self, other):\n        c = self._cmp(other)\n        if c is NotImplemented:\n            return c\n        return c == 0\n\n    def __lt__(self, other):\n        c = self._cmp(other)\n        if c is NotImplemented:\n            return c\n        return c < 0\n\n    def __le__(self, other):\n        c = self._cmp(other)\n        if c is NotImplemented:\n            return c\n        return c <= 0\n\n    def __gt__(self, other):\n        c = self._cmp(other)\n        if c is NotImplemented:\n            return c\n        return c > 0\n\n    def __ge__(self, other):\n        c = self._cmp(other)\n        if c is NotImplemented:\n            return c\n        return c >= 0\n\n\n# Interface for version-number classes -- must be implemented\n# by the following classes (the concrete ones -- Version should\n# be treated as an abstract class).\n#    __init__ (string) - create and take same action as 'parse'\n#                        (string parameter is optional)\n#    parse (string)    - convert a string representation to whatever\n#                        internal representation is appropriate for\n#                        this style of version numbering\n#    __str__ (self)    - convert back to a string; should be very similar\n#                        (if not identical to) the string supplied to parse\n#    __repr__ (self)   - generate Python code to recreate\n#                        the instance\n#    _cmp (self, other) - compare two version numbers ('other' may\n#                        be an unparsed version string, or another\n#                        instance of your version class)\n\n\nclass StrictVersion(Version):\n\n    \"\"\"Version numbering for anal retentives and software idealists.\n    Implements the standard interface for version number classes as\n    described above.  A version number consists of two or three\n    dot-separated numeric components, with an optional \"pre-release\" tag\n    on the end.  The pre-release tag consists of the letter 'a' or 'b'\n    followed by a number.  If the numeric components of two version\n    numbers are equal, then one with a pre-release tag will always\n    be deemed earlier (lesser) than one without.\n\n    The following are valid version numbers (shown in the order that\n    would be obtained by sorting according to the supplied cmp function):\n\n        0.4       0.4.0  (these two are equivalent)\n        0.4.1\n        0.5a1\n        0.5b3\n        0.5\n        0.9.6\n        1.0\n        1.0.4a3\n        1.0.4b1\n        1.0.4\n\n    The following are examples of invalid version numbers:\n\n        1\n        2.7.2.2\n        1.3.a4\n        1.3pl1\n        1.3c4\n\n    The rationale for this version numbering system will be explained\n    in the distutils documentation.\n    \"\"\"\n\n    version_re = re.compile(\n        r'^(\\d+) \\. (\\d+) (\\. (\\d+))? ([ab](\\d+))?$', re.VERBOSE | re.ASCII\n    )\n\n    def parse(self, vstring):\n        match = self.version_re.match(vstring)\n        if not match:\n            raise ValueError(\"invalid version number '%s'\" % vstring)\n\n        (major, minor, patch, prerelease, prerelease_num) = match.group(1, 2, 4, 5, 6)\n\n        if patch:\n            self.version = tuple(map(int, [major, minor, patch]))\n        else:\n            self.version = tuple(map(int, [major, minor])) + (0,)\n\n        if prerelease:\n            self.prerelease = (prerelease[0], int(prerelease_num))\n        else:\n            self.prerelease = None\n\n    def __str__(self):\n\n        if self.version[2] == 0:\n            vstring = '.'.join(map(str, self.version[0:2]))\n        else:\n            vstring = '.'.join(map(str, self.version))\n\n        if self.prerelease:\n            vstring = vstring + self.prerelease[0] + str(self.prerelease[1])\n\n        return vstring\n\n    def _cmp(self, other):  # noqa: C901\n        if isinstance(other, str):\n            with suppress_known_deprecation():\n                other = StrictVersion(other)\n        elif not isinstance(other, StrictVersion):\n            return NotImplemented\n\n        if self.version != other.version:\n            # numeric versions don't match\n            # prerelease stuff doesn't matter\n            if self.version < other.version:\n                return -1\n            else:\n                return 1\n\n        # have to compare prerelease\n        # case 1: neither has prerelease; they're equal\n        # case 2: self has prerelease, other doesn't; other is greater\n        # case 3: self doesn't have prerelease, other does: self is greater\n        # case 4: both have prerelease: must compare them!\n\n        if not self.prerelease and not other.prerelease:\n            return 0\n        elif self.prerelease and not other.prerelease:\n            return -1\n        elif not self.prerelease and other.prerelease:\n            return 1\n        elif self.prerelease and other.prerelease:\n            if self.prerelease == other.prerelease:\n                return 0\n            elif self.prerelease < other.prerelease:\n                return -1\n            else:\n                return 1\n        else:\n            assert False, \"never get here\"\n\n\n# end class StrictVersion\n\n\n# The rules according to Greg Stein:\n# 1) a version number has 1 or more numbers separated by a period or by\n#    sequences of letters. If only periods, then these are compared\n#    left-to-right to determine an ordering.\n# 2) sequences of letters are part of the tuple for comparison and are\n#    compared lexicographically\n# 3) recognize the numeric components may have leading zeroes\n#\n# The LooseVersion class below implements these rules: a version number\n# string is split up into a tuple of integer and string components, and\n# comparison is a simple tuple comparison.  This means that version\n# numbers behave in a predictable and obvious way, but a way that might\n# not necessarily be how people *want* version numbers to behave.  There\n# wouldn't be a problem if people could stick to purely numeric version\n# numbers: just split on period and compare the numbers as tuples.\n# However, people insist on putting letters into their version numbers;\n# the most common purpose seems to be:\n#   - indicating a \"pre-release\" version\n#     ('alpha', 'beta', 'a', 'b', 'pre', 'p')\n#   - indicating a post-release patch ('p', 'pl', 'patch')\n# but of course this can't cover all version number schemes, and there's\n# no way to know what a programmer means without asking him.\n#\n# The problem is what to do with letters (and other non-numeric\n# characters) in a version number.  The current implementation does the\n# obvious and predictable thing: keep them as strings and compare\n# lexically within a tuple comparison.  This has the desired effect if\n# an appended letter sequence implies something \"post-release\":\n# eg. \"0.99\" < \"0.99pl14\" < \"1.0\", and \"5.001\" < \"5.001m\" < \"5.002\".\n#\n# However, if letters in a version number imply a pre-release version,\n# the \"obvious\" thing isn't correct.  Eg. you would expect that\n# \"1.5.1\" < \"1.5.2a2\" < \"1.5.2\", but under the tuple/lexical comparison\n# implemented here, this just isn't so.\n#\n# Two possible solutions come to mind.  The first is to tie the\n# comparison algorithm to a particular set of semantic rules, as has\n# been done in the StrictVersion class above.  This works great as long\n# as everyone can go along with bondage and discipline.  Hopefully a\n# (large) subset of Python module programmers will agree that the\n# particular flavour of bondage and discipline provided by StrictVersion\n# provides enough benefit to be worth using, and will submit their\n# version numbering scheme to its domination.  The free-thinking\n# anarchists in the lot will never give in, though, and something needs\n# to be done to accommodate them.\n#\n# Perhaps a \"moderately strict\" version class could be implemented that\n# lets almost anything slide (syntactically), and makes some heuristic\n# assumptions about non-digits in version number strings.  This could\n# sink into special-case-hell, though; if I was as talented and\n# idiosyncratic as Larry Wall, I'd go ahead and implement a class that\n# somehow knows that \"1.2.1\" < \"1.2.2a2\" < \"1.2.2\" < \"1.2.2pl3\", and is\n# just as happy dealing with things like \"2g6\" and \"1.13++\".  I don't\n# think I'm smart enough to do it right though.\n#\n# In any case, I've coded the test suite for this module (see\n# ../test/test_version.py) specifically to fail on things like comparing\n# \"1.2a2\" and \"1.2\".  That's not because the *code* is doing anything\n# wrong, it's because the simple, obvious design doesn't match my\n# complicated, hairy expectations for real-world version numbers.  It\n# would be a snap to fix the test suite to say, \"Yep, LooseVersion does\n# the Right Thing\" (ie. the code matches the conception).  But I'd rather\n# have a conception that matches common notions about version numbers.\n\n\nclass LooseVersion(Version):\n\n    \"\"\"Version numbering for anarchists and software realists.\n    Implements the standard interface for version number classes as\n    described above.  A version number consists of a series of numbers,\n    separated by either periods or strings of letters.  When comparing\n    version numbers, the numeric components will be compared\n    numerically, and the alphabetic components lexically.  The following\n    are all valid version numbers, in no particular order:\n\n        1.5.1\n        1.5.2b2\n        161\n        3.10a\n        8.02\n        3.4j\n        1996.07.12\n        3.2.pl0\n        3.1.1.6\n        2g6\n        11g\n        0.960923\n        2.2beta29\n        1.13++\n        5.5.kw\n        2.0b1pl0\n\n    In fact, there is no such thing as an invalid version number under\n    this scheme; the rules for comparison are simple and predictable,\n    but may not always give the results you want (for some definition\n    of \"want\").\n    \"\"\"\n\n    component_re = re.compile(r'(\\d+ | [a-z]+ | \\.)', re.VERBOSE)\n\n    def parse(self, vstring):\n        # I've given up on thinking I can reconstruct the version string\n        # from the parsed tuple -- so I just store the string here for\n        # use by __str__\n        self.vstring = vstring\n        components = [x for x in self.component_re.split(vstring) if x and x != '.']\n        for i, obj in enumerate(components):\n            try:\n                components[i] = int(obj)\n            except ValueError:\n                pass\n\n        self.version = components\n\n    def __str__(self):\n        return self.vstring\n\n    def __repr__(self):\n        return \"LooseVersion ('%s')\" % str(self)\n\n    def _cmp(self, other):\n        if isinstance(other, str):\n            other = LooseVersion(other)\n        elif not isinstance(other, LooseVersion):\n            return NotImplemented\n\n        if self.version == other.version:\n            return 0\n        if self.version < other.version:\n            return -1\n        if self.version > other.version:\n            return 1\n\n\n# end class LooseVersion\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_distutils/versionpredicate.py",
    "content": "\"\"\"Module for parsing and testing package version predicate strings.\n\"\"\"\nimport re\nimport distutils.version\nimport operator\n\n\nre_validPackage = re.compile(r\"(?i)^\\s*([a-z_]\\w*(?:\\.[a-z_]\\w*)*)(.*)\", re.ASCII)\n# (package) (rest)\n\nre_paren = re.compile(r\"^\\s*\\((.*)\\)\\s*$\")  # (list) inside of parentheses\nre_splitComparison = re.compile(r\"^\\s*(<=|>=|<|>|!=|==)\\s*([^\\s,]+)\\s*$\")\n# (comp) (version)\n\n\ndef splitUp(pred):\n    \"\"\"Parse a single version comparison.\n\n    Return (comparison string, StrictVersion)\n    \"\"\"\n    res = re_splitComparison.match(pred)\n    if not res:\n        raise ValueError(\"bad package restriction syntax: %r\" % pred)\n    comp, verStr = res.groups()\n    with distutils.version.suppress_known_deprecation():\n        other = distutils.version.StrictVersion(verStr)\n    return (comp, other)\n\n\ncompmap = {\n    \"<\": operator.lt,\n    \"<=\": operator.le,\n    \"==\": operator.eq,\n    \">\": operator.gt,\n    \">=\": operator.ge,\n    \"!=\": operator.ne,\n}\n\n\nclass VersionPredicate:\n    \"\"\"Parse and test package version predicates.\n\n    >>> v = VersionPredicate('pyepat.abc (>1.0, <3333.3a1, !=1555.1b3)')\n\n    The `name` attribute provides the full dotted name that is given::\n\n    >>> v.name\n    'pyepat.abc'\n\n    The str() of a `VersionPredicate` provides a normalized\n    human-readable version of the expression::\n\n    >>> print(v)\n    pyepat.abc (> 1.0, < 3333.3a1, != 1555.1b3)\n\n    The `satisfied_by()` method can be used to determine with a given\n    version number is included in the set described by the version\n    restrictions::\n\n    >>> v.satisfied_by('1.1')\n    True\n    >>> v.satisfied_by('1.4')\n    True\n    >>> v.satisfied_by('1.0')\n    False\n    >>> v.satisfied_by('4444.4')\n    False\n    >>> v.satisfied_by('1555.1b3')\n    False\n\n    `VersionPredicate` is flexible in accepting extra whitespace::\n\n    >>> v = VersionPredicate(' pat( ==  0.1  )  ')\n    >>> v.name\n    'pat'\n    >>> v.satisfied_by('0.1')\n    True\n    >>> v.satisfied_by('0.2')\n    False\n\n    If any version numbers passed in do not conform to the\n    restrictions of `StrictVersion`, a `ValueError` is raised::\n\n    >>> v = VersionPredicate('p1.p2.p3.p4(>=1.0, <=1.3a1, !=1.2zb3)')\n    Traceback (most recent call last):\n      ...\n    ValueError: invalid version number '1.2zb3'\n\n    It the module or package name given does not conform to what's\n    allowed as a legal module or package name, `ValueError` is\n    raised::\n\n    >>> v = VersionPredicate('foo-bar')\n    Traceback (most recent call last):\n      ...\n    ValueError: expected parenthesized list: '-bar'\n\n    >>> v = VersionPredicate('foo bar (12.21)')\n    Traceback (most recent call last):\n      ...\n    ValueError: expected parenthesized list: 'bar (12.21)'\n\n    \"\"\"\n\n    def __init__(self, versionPredicateStr):\n        \"\"\"Parse a version predicate string.\"\"\"\n        # Fields:\n        #    name:  package name\n        #    pred:  list of (comparison string, StrictVersion)\n\n        versionPredicateStr = versionPredicateStr.strip()\n        if not versionPredicateStr:\n            raise ValueError(\"empty package restriction\")\n        match = re_validPackage.match(versionPredicateStr)\n        if not match:\n            raise ValueError(\"bad package name in %r\" % versionPredicateStr)\n        self.name, paren = match.groups()\n        paren = paren.strip()\n        if paren:\n            match = re_paren.match(paren)\n            if not match:\n                raise ValueError(\"expected parenthesized list: %r\" % paren)\n            str = match.groups()[0]\n            self.pred = [splitUp(aPred) for aPred in str.split(\",\")]\n            if not self.pred:\n                raise ValueError(\"empty parenthesized list in %r\" % versionPredicateStr)\n        else:\n            self.pred = []\n\n    def __str__(self):\n        if self.pred:\n            seq = [cond + \" \" + str(ver) for cond, ver in self.pred]\n            return self.name + \" (\" + \", \".join(seq) + \")\"\n        else:\n            return self.name\n\n    def satisfied_by(self, version):\n        \"\"\"True if version is compatible with all the predicates in self.\n        The parameter version must be acceptable to the StrictVersion\n        constructor.  It may be either a string or StrictVersion.\n        \"\"\"\n        for cond, ver in self.pred:\n            if not compmap[cond](version, ver):\n                return False\n        return True\n\n\n_provision_rx = None\n\n\ndef split_provision(value):\n    \"\"\"Return the name and optional version number of a provision.\n\n    The version number, if given, will be returned as a `StrictVersion`\n    instance, otherwise it will be `None`.\n\n    >>> split_provision('mypkg')\n    ('mypkg', None)\n    >>> split_provision(' mypkg( 1.2 ) ')\n    ('mypkg', StrictVersion ('1.2'))\n    \"\"\"\n    global _provision_rx\n    if _provision_rx is None:\n        _provision_rx = re.compile(\n            r\"([a-zA-Z_]\\w*(?:\\.[a-zA-Z_]\\w*)*)(?:\\s*\\(\\s*([^)\\s]+)\\s*\\))?$\", re.ASCII\n        )\n    value = value.strip()\n    m = _provision_rx.match(value)\n    if not m:\n        raise ValueError(\"illegal provides specification: %r\" % value)\n    ver = m.group(2) or None\n    if ver:\n        with distutils.version.suppress_known_deprecation():\n            ver = distutils.version.StrictVersion(ver)\n    return m.group(1), ver\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_entry_points.py",
    "content": "import functools\nimport operator\nimport itertools\n\nfrom .extern.jaraco.text import yield_lines\nfrom .extern.jaraco.functools import pass_none\nfrom ._importlib import metadata\nfrom ._itertools import ensure_unique\nfrom .extern.more_itertools import consume\n\n\ndef ensure_valid(ep):\n    \"\"\"\n    Exercise one of the dynamic properties to trigger\n    the pattern match.\n    \"\"\"\n    ep.extras\n\n\ndef load_group(value, group):\n    \"\"\"\n    Given a value of an entry point or series of entry points,\n    return each as an EntryPoint.\n    \"\"\"\n    # normalize to a single sequence of lines\n    lines = yield_lines(value)\n    text = f'[{group}]\\n' + '\\n'.join(lines)\n    return metadata.EntryPoints._from_text(text)\n\n\ndef by_group_and_name(ep):\n    return ep.group, ep.name\n\n\ndef validate(eps: metadata.EntryPoints):\n    \"\"\"\n    Ensure entry points are unique by group and name and validate each.\n    \"\"\"\n    consume(map(ensure_valid, ensure_unique(eps, key=by_group_and_name)))\n    return eps\n\n\n@functools.singledispatch\ndef load(eps):\n    \"\"\"\n    Given a Distribution.entry_points, produce EntryPoints.\n    \"\"\"\n    groups = itertools.chain.from_iterable(\n        load_group(value, group)\n        for group, value in eps.items())\n    return validate(metadata.EntryPoints(groups))\n\n\n@load.register(str)\ndef _(eps):\n    r\"\"\"\n    >>> ep, = load('[console_scripts]\\nfoo=bar')\n    >>> ep.group\n    'console_scripts'\n    >>> ep.name\n    'foo'\n    >>> ep.value\n    'bar'\n    \"\"\"\n    return validate(metadata.EntryPoints(metadata.EntryPoints._from_text(eps)))\n\n\nload.register(type(None), lambda x: x)\n\n\n@pass_none\ndef render(eps: metadata.EntryPoints):\n    by_group = operator.attrgetter('group')\n    groups = itertools.groupby(sorted(eps, key=by_group), by_group)\n\n    return '\\n'.join(\n        f'[{group}]\\n{render_items(items)}\\n'\n        for group, items in groups\n    )\n\n\ndef render_items(eps):\n    return '\\n'.join(\n        f'{ep.name} = {ep.value}'\n        for ep in sorted(eps)\n    )\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_imp.py",
    "content": "\"\"\"\nRe-implementation of find_module and get_frozen_object\nfrom the deprecated imp module.\n\"\"\"\n\nimport os\nimport importlib.util\nimport importlib.machinery\n\nfrom .py34compat import module_from_spec\n\n\nPY_SOURCE = 1\nPY_COMPILED = 2\nC_EXTENSION = 3\nC_BUILTIN = 6\nPY_FROZEN = 7\n\n\ndef find_spec(module, paths):\n    finder = (\n        importlib.machinery.PathFinder().find_spec\n        if isinstance(paths, list) else\n        importlib.util.find_spec\n    )\n    return finder(module, paths)\n\n\ndef find_module(module, paths=None):\n    \"\"\"Just like 'imp.find_module()', but with package support\"\"\"\n    spec = find_spec(module, paths)\n    if spec is None:\n        raise ImportError(\"Can't find %s\" % module)\n    if not spec.has_location and hasattr(spec, 'submodule_search_locations'):\n        spec = importlib.util.spec_from_loader('__init__.py', spec.loader)\n\n    kind = -1\n    file = None\n    static = isinstance(spec.loader, type)\n    if spec.origin == 'frozen' or static and issubclass(\n            spec.loader, importlib.machinery.FrozenImporter):\n        kind = PY_FROZEN\n        path = None  # imp compabilty\n        suffix = mode = ''  # imp compatibility\n    elif spec.origin == 'built-in' or static and issubclass(\n            spec.loader, importlib.machinery.BuiltinImporter):\n        kind = C_BUILTIN\n        path = None  # imp compabilty\n        suffix = mode = ''  # imp compatibility\n    elif spec.has_location:\n        path = spec.origin\n        suffix = os.path.splitext(path)[1]\n        mode = 'r' if suffix in importlib.machinery.SOURCE_SUFFIXES else 'rb'\n\n        if suffix in importlib.machinery.SOURCE_SUFFIXES:\n            kind = PY_SOURCE\n        elif suffix in importlib.machinery.BYTECODE_SUFFIXES:\n            kind = PY_COMPILED\n        elif suffix in importlib.machinery.EXTENSION_SUFFIXES:\n            kind = C_EXTENSION\n\n        if kind in {PY_SOURCE, PY_COMPILED}:\n            file = open(path, mode)\n    else:\n        path = None\n        suffix = mode = ''\n\n    return file, path, (suffix, mode, kind)\n\n\ndef get_frozen_object(module, paths=None):\n    spec = find_spec(module, paths)\n    if not spec:\n        raise ImportError(\"Can't find %s\" % module)\n    return spec.loader.get_code(module)\n\n\ndef get_module(module, paths, info):\n    spec = find_spec(module, paths)\n    if not spec:\n        raise ImportError(\"Can't find %s\" % module)\n    return module_from_spec(spec)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_importlib.py",
    "content": "import sys\n\n\ndef disable_importlib_metadata_finder(metadata):\n    \"\"\"\n    Ensure importlib_metadata doesn't provide older, incompatible\n    Distributions.\n\n    Workaround for #3102.\n    \"\"\"\n    try:\n        import importlib_metadata\n    except ImportError:\n        return\n    except AttributeError:\n        import warnings\n\n        msg = (\n            \"`importlib-metadata` version is incompatible with `setuptools`.\\n\"\n            \"This problem is likely to be solved by installing an updated version of \"\n            \"`importlib-metadata`.\"\n        )\n        warnings.warn(msg)  # Ensure a descriptive message is shown.\n        raise  # This exception can be suppressed by _distutils_hack\n\n    if importlib_metadata is metadata:\n        return\n    to_remove = [\n        ob\n        for ob in sys.meta_path\n        if isinstance(ob, importlib_metadata.MetadataPathFinder)\n    ]\n    for item in to_remove:\n        sys.meta_path.remove(item)\n\n\nif sys.version_info < (3, 10):\n    from setuptools.extern import importlib_metadata as metadata\n    disable_importlib_metadata_finder(metadata)\nelse:\n    import importlib.metadata as metadata  # noqa: F401\n\n\nif sys.version_info < (3, 9):\n    from setuptools.extern import importlib_resources as resources\nelse:\n    import importlib.resources as resources  # noqa: F401\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_itertools.py",
    "content": "from setuptools.extern.more_itertools import consume  # noqa: F401\n\n\n# copied from jaraco.itertools 6.1\ndef ensure_unique(iterable, key=lambda x: x):\n    \"\"\"\n    Wrap an iterable to raise a ValueError if non-unique values are encountered.\n\n    >>> list(ensure_unique('abc'))\n    ['a', 'b', 'c']\n    >>> consume(ensure_unique('abca'))\n    Traceback (most recent call last):\n    ...\n    ValueError: Duplicate element 'a' encountered.\n    \"\"\"\n    seen = set()\n    seen_add = seen.add\n    for element in iterable:\n        k = key(element)\n        if k in seen:\n            raise ValueError(f\"Duplicate element {element!r} encountered.\")\n        seen_add(k)\n        yield element\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_path.py",
    "content": "import os\nfrom typing import Union\n\n_Path = Union[str, os.PathLike]\n\n\ndef ensure_directory(path):\n    \"\"\"Ensure that the parent directory of `path` exists\"\"\"\n    dirname = os.path.dirname(path)\n    os.makedirs(dirname, exist_ok=True)\n\n\ndef same_path(p1: _Path, p2: _Path) -> bool:\n    \"\"\"Differs from os.path.samefile because it does not require paths to exist.\n    Purely string based (no comparison between i-nodes).\n    >>> same_path(\"a/b\", \"./a/b\")\n    True\n    >>> same_path(\"a/b\", \"a/./b\")\n    True\n    >>> same_path(\"a/b\", \"././a/b\")\n    True\n    >>> same_path(\"a/b\", \"./a/b/c/..\")\n    True\n    >>> same_path(\"a/b\", \"../a/b/c\")\n    False\n    >>> same_path(\"a\", \"a/b\")\n    False\n    \"\"\"\n    return os.path.normpath(p1) == os.path.normpath(p2)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_reqs.py",
    "content": "import setuptools.extern.jaraco.text as text\n\nfrom pkg_resources import Requirement\n\n\ndef parse_strings(strs):\n    \"\"\"\n    Yield requirement strings for each specification in `strs`.\n\n    `strs` must be a string, or a (possibly-nested) iterable thereof.\n    \"\"\"\n    return text.join_continuation(map(text.drop_comment, text.yield_lines(strs)))\n\n\ndef parse(strs):\n    \"\"\"\n    Deprecated drop-in replacement for pkg_resources.parse_requirements.\n    \"\"\"\n    return map(Requirement, parse_strings(strs))\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_metadata/__init__.py",
    "content": "import os\nimport re\nimport abc\nimport csv\nimport sys\nfrom .. import zipp\nimport email\nimport pathlib\nimport operator\nimport textwrap\nimport warnings\nimport functools\nimport itertools\nimport posixpath\nimport collections\n\nfrom . import _adapters, _meta\nfrom ._collections import FreezableDefaultDict, Pair\nfrom ._compat import (\n    NullFinder,\n    install,\n    pypy_partial,\n)\nfrom ._functools import method_cache, pass_none\nfrom ._itertools import always_iterable, unique_everseen\nfrom ._meta import PackageMetadata, SimplePath\n\nfrom contextlib import suppress\nfrom importlib import import_module\nfrom importlib.abc import MetaPathFinder\nfrom itertools import starmap\nfrom typing import List, Mapping, Optional, Union\n\n\n__all__ = [\n    'Distribution',\n    'DistributionFinder',\n    'PackageMetadata',\n    'PackageNotFoundError',\n    'distribution',\n    'distributions',\n    'entry_points',\n    'files',\n    'metadata',\n    'packages_distributions',\n    'requires',\n    'version',\n]\n\n\nclass PackageNotFoundError(ModuleNotFoundError):\n    \"\"\"The package was not found.\"\"\"\n\n    def __str__(self):\n        return f\"No package metadata was found for {self.name}\"\n\n    @property\n    def name(self):\n        (name,) = self.args\n        return name\n\n\nclass Sectioned:\n    \"\"\"\n    A simple entry point config parser for performance\n\n    >>> for item in Sectioned.read(Sectioned._sample):\n    ...     print(item)\n    Pair(name='sec1', value='# comments ignored')\n    Pair(name='sec1', value='a = 1')\n    Pair(name='sec1', value='b = 2')\n    Pair(name='sec2', value='a = 2')\n\n    >>> res = Sectioned.section_pairs(Sectioned._sample)\n    >>> item = next(res)\n    >>> item.name\n    'sec1'\n    >>> item.value\n    Pair(name='a', value='1')\n    >>> item = next(res)\n    >>> item.value\n    Pair(name='b', value='2')\n    >>> item = next(res)\n    >>> item.name\n    'sec2'\n    >>> item.value\n    Pair(name='a', value='2')\n    >>> list(res)\n    []\n    \"\"\"\n\n    _sample = textwrap.dedent(\n        \"\"\"\n        [sec1]\n        # comments ignored\n        a = 1\n        b = 2\n\n        [sec2]\n        a = 2\n        \"\"\"\n    ).lstrip()\n\n    @classmethod\n    def section_pairs(cls, text):\n        return (\n            section._replace(value=Pair.parse(section.value))\n            for section in cls.read(text, filter_=cls.valid)\n            if section.name is not None\n        )\n\n    @staticmethod\n    def read(text, filter_=None):\n        lines = filter(filter_, map(str.strip, text.splitlines()))\n        name = None\n        for value in lines:\n            section_match = value.startswith('[') and value.endswith(']')\n            if section_match:\n                name = value.strip('[]')\n                continue\n            yield Pair(name, value)\n\n    @staticmethod\n    def valid(line):\n        return line and not line.startswith('#')\n\n\nclass DeprecatedTuple:\n    \"\"\"\n    Provide subscript item access for backward compatibility.\n\n    >>> recwarn = getfixture('recwarn')\n    >>> ep = EntryPoint(name='name', value='value', group='group')\n    >>> ep[:]\n    ('name', 'value', 'group')\n    >>> ep[0]\n    'name'\n    >>> len(recwarn)\n    1\n    \"\"\"\n\n    _warn = functools.partial(\n        warnings.warn,\n        \"EntryPoint tuple interface is deprecated. Access members by name.\",\n        DeprecationWarning,\n        stacklevel=pypy_partial(2),\n    )\n\n    def __getitem__(self, item):\n        self._warn()\n        return self._key()[item]\n\n\nclass EntryPoint(DeprecatedTuple):\n    \"\"\"An entry point as defined by Python packaging conventions.\n\n    See `the packaging docs on entry points\n    <https://packaging.python.org/specifications/entry-points/>`_\n    for more information.\n    \"\"\"\n\n    pattern = re.compile(\n        r'(?P<module>[\\w.]+)\\s*'\n        r'(:\\s*(?P<attr>[\\w.]+)\\s*)?'\n        r'((?P<extras>\\[.*\\])\\s*)?$'\n    )\n    \"\"\"\n    A regular expression describing the syntax for an entry point,\n    which might look like:\n\n        - module\n        - package.module\n        - package.module:attribute\n        - package.module:object.attribute\n        - package.module:attr [extra1, extra2]\n\n    Other combinations are possible as well.\n\n    The expression is lenient about whitespace around the ':',\n    following the attr, and following any extras.\n    \"\"\"\n\n    dist: Optional['Distribution'] = None\n\n    def __init__(self, name, value, group):\n        vars(self).update(name=name, value=value, group=group)\n\n    def load(self):\n        \"\"\"Load the entry point from its definition. If only a module\n        is indicated by the value, return that module. Otherwise,\n        return the named object.\n        \"\"\"\n        match = self.pattern.match(self.value)\n        module = import_module(match.group('module'))\n        attrs = filter(None, (match.group('attr') or '').split('.'))\n        return functools.reduce(getattr, attrs, module)\n\n    @property\n    def module(self):\n        match = self.pattern.match(self.value)\n        return match.group('module')\n\n    @property\n    def attr(self):\n        match = self.pattern.match(self.value)\n        return match.group('attr')\n\n    @property\n    def extras(self):\n        match = self.pattern.match(self.value)\n        return list(re.finditer(r'\\w+', match.group('extras') or ''))\n\n    def _for(self, dist):\n        vars(self).update(dist=dist)\n        return self\n\n    def __iter__(self):\n        \"\"\"\n        Supply iter so one may construct dicts of EntryPoints by name.\n        \"\"\"\n        msg = (\n            \"Construction of dict of EntryPoints is deprecated in \"\n            \"favor of EntryPoints.\"\n        )\n        warnings.warn(msg, DeprecationWarning)\n        return iter((self.name, self))\n\n    def matches(self, **params):\n        attrs = (getattr(self, param) for param in params)\n        return all(map(operator.eq, params.values(), attrs))\n\n    def _key(self):\n        return self.name, self.value, self.group\n\n    def __lt__(self, other):\n        return self._key() < other._key()\n\n    def __eq__(self, other):\n        return self._key() == other._key()\n\n    def __setattr__(self, name, value):\n        raise AttributeError(\"EntryPoint objects are immutable.\")\n\n    def __repr__(self):\n        return (\n            f'EntryPoint(name={self.name!r}, value={self.value!r}, '\n            f'group={self.group!r})'\n        )\n\n    def __hash__(self):\n        return hash(self._key())\n\n\nclass DeprecatedList(list):\n    \"\"\"\n    Allow an otherwise immutable object to implement mutability\n    for compatibility.\n\n    >>> recwarn = getfixture('recwarn')\n    >>> dl = DeprecatedList(range(3))\n    >>> dl[0] = 1\n    >>> dl.append(3)\n    >>> del dl[3]\n    >>> dl.reverse()\n    >>> dl.sort()\n    >>> dl.extend([4])\n    >>> dl.pop(-1)\n    4\n    >>> dl.remove(1)\n    >>> dl += [5]\n    >>> dl + [6]\n    [1, 2, 5, 6]\n    >>> dl + (6,)\n    [1, 2, 5, 6]\n    >>> dl.insert(0, 0)\n    >>> dl\n    [0, 1, 2, 5]\n    >>> dl == [0, 1, 2, 5]\n    True\n    >>> dl == (0, 1, 2, 5)\n    True\n    >>> len(recwarn)\n    1\n    \"\"\"\n\n    __slots__ = ()\n\n    _warn = functools.partial(\n        warnings.warn,\n        \"EntryPoints list interface is deprecated. Cast to list if needed.\",\n        DeprecationWarning,\n        stacklevel=pypy_partial(2),\n    )\n\n    def _wrap_deprecated_method(method_name: str):  # type: ignore\n        def wrapped(self, *args, **kwargs):\n            self._warn()\n            return getattr(super(), method_name)(*args, **kwargs)\n\n        return method_name, wrapped\n\n    locals().update(\n        map(\n            _wrap_deprecated_method,\n            '__setitem__ __delitem__ append reverse extend pop remove '\n            '__iadd__ insert sort'.split(),\n        )\n    )\n\n    def __add__(self, other):\n        if not isinstance(other, tuple):\n            self._warn()\n            other = tuple(other)\n        return self.__class__(tuple(self) + other)\n\n    def __eq__(self, other):\n        if not isinstance(other, tuple):\n            self._warn()\n            other = tuple(other)\n\n        return tuple(self).__eq__(other)\n\n\nclass EntryPoints(DeprecatedList):\n    \"\"\"\n    An immutable collection of selectable EntryPoint objects.\n    \"\"\"\n\n    __slots__ = ()\n\n    def __getitem__(self, name):  # -> EntryPoint:\n        \"\"\"\n        Get the EntryPoint in self matching name.\n        \"\"\"\n        if isinstance(name, int):\n            warnings.warn(\n                \"Accessing entry points by index is deprecated. \"\n                \"Cast to tuple if needed.\",\n                DeprecationWarning,\n                stacklevel=2,\n            )\n            return super().__getitem__(name)\n        try:\n            return next(iter(self.select(name=name)))\n        except StopIteration:\n            raise KeyError(name)\n\n    def select(self, **params):\n        \"\"\"\n        Select entry points from self that match the\n        given parameters (typically group and/or name).\n        \"\"\"\n        return EntryPoints(ep for ep in self if ep.matches(**params))\n\n    @property\n    def names(self):\n        \"\"\"\n        Return the set of all names of all entry points.\n        \"\"\"\n        return {ep.name for ep in self}\n\n    @property\n    def groups(self):\n        \"\"\"\n        Return the set of all groups of all entry points.\n\n        For coverage while SelectableGroups is present.\n        >>> EntryPoints().groups\n        set()\n        \"\"\"\n        return {ep.group for ep in self}\n\n    @classmethod\n    def _from_text_for(cls, text, dist):\n        return cls(ep._for(dist) for ep in cls._from_text(text))\n\n    @staticmethod\n    def _from_text(text):\n        return (\n            EntryPoint(name=item.value.name, value=item.value.value, group=item.name)\n            for item in Sectioned.section_pairs(text or '')\n        )\n\n\nclass Deprecated:\n    \"\"\"\n    Compatibility add-in for mapping to indicate that\n    mapping behavior is deprecated.\n\n    >>> recwarn = getfixture('recwarn')\n    >>> class DeprecatedDict(Deprecated, dict): pass\n    >>> dd = DeprecatedDict(foo='bar')\n    >>> dd.get('baz', None)\n    >>> dd['foo']\n    'bar'\n    >>> list(dd)\n    ['foo']\n    >>> list(dd.keys())\n    ['foo']\n    >>> 'foo' in dd\n    True\n    >>> list(dd.values())\n    ['bar']\n    >>> len(recwarn)\n    1\n    \"\"\"\n\n    _warn = functools.partial(\n        warnings.warn,\n        \"SelectableGroups dict interface is deprecated. Use select.\",\n        DeprecationWarning,\n        stacklevel=pypy_partial(2),\n    )\n\n    def __getitem__(self, name):\n        self._warn()\n        return super().__getitem__(name)\n\n    def get(self, name, default=None):\n        self._warn()\n        return super().get(name, default)\n\n    def __iter__(self):\n        self._warn()\n        return super().__iter__()\n\n    def __contains__(self, *args):\n        self._warn()\n        return super().__contains__(*args)\n\n    def keys(self):\n        self._warn()\n        return super().keys()\n\n    def values(self):\n        self._warn()\n        return super().values()\n\n\nclass SelectableGroups(Deprecated, dict):\n    \"\"\"\n    A backward- and forward-compatible result from\n    entry_points that fully implements the dict interface.\n    \"\"\"\n\n    @classmethod\n    def load(cls, eps):\n        by_group = operator.attrgetter('group')\n        ordered = sorted(eps, key=by_group)\n        grouped = itertools.groupby(ordered, by_group)\n        return cls((group, EntryPoints(eps)) for group, eps in grouped)\n\n    @property\n    def _all(self):\n        \"\"\"\n        Reconstruct a list of all entrypoints from the groups.\n        \"\"\"\n        groups = super(Deprecated, self).values()\n        return EntryPoints(itertools.chain.from_iterable(groups))\n\n    @property\n    def groups(self):\n        return self._all.groups\n\n    @property\n    def names(self):\n        \"\"\"\n        for coverage:\n        >>> SelectableGroups().names\n        set()\n        \"\"\"\n        return self._all.names\n\n    def select(self, **params):\n        if not params:\n            return self\n        return self._all.select(**params)\n\n\nclass PackagePath(pathlib.PurePosixPath):\n    \"\"\"A reference to a path in a package\"\"\"\n\n    def read_text(self, encoding='utf-8'):\n        with self.locate().open(encoding=encoding) as stream:\n            return stream.read()\n\n    def read_binary(self):\n        with self.locate().open('rb') as stream:\n            return stream.read()\n\n    def locate(self):\n        \"\"\"Return a path-like object for this path\"\"\"\n        return self.dist.locate_file(self)\n\n\nclass FileHash:\n    def __init__(self, spec):\n        self.mode, _, self.value = spec.partition('=')\n\n    def __repr__(self):\n        return f'<FileHash mode: {self.mode} value: {self.value}>'\n\n\nclass Distribution:\n    \"\"\"A Python distribution package.\"\"\"\n\n    @abc.abstractmethod\n    def read_text(self, filename):\n        \"\"\"Attempt to load metadata file given by the name.\n\n        :param filename: The name of the file in the distribution info.\n        :return: The text if found, otherwise None.\n        \"\"\"\n\n    @abc.abstractmethod\n    def locate_file(self, path):\n        \"\"\"\n        Given a path to a file in this distribution, return a path\n        to it.\n        \"\"\"\n\n    @classmethod\n    def from_name(cls, name):\n        \"\"\"Return the Distribution for the given package name.\n\n        :param name: The name of the distribution package to search for.\n        :return: The Distribution instance (or subclass thereof) for the named\n            package, if found.\n        :raises PackageNotFoundError: When the named package's distribution\n            metadata cannot be found.\n        \"\"\"\n        for resolver in cls._discover_resolvers():\n            dists = resolver(DistributionFinder.Context(name=name))\n            dist = next(iter(dists), None)\n            if dist is not None:\n                return dist\n        else:\n            raise PackageNotFoundError(name)\n\n    @classmethod\n    def discover(cls, **kwargs):\n        \"\"\"Return an iterable of Distribution objects for all packages.\n\n        Pass a ``context`` or pass keyword arguments for constructing\n        a context.\n\n        :context: A ``DistributionFinder.Context`` object.\n        :return: Iterable of Distribution objects for all packages.\n        \"\"\"\n        context = kwargs.pop('context', None)\n        if context and kwargs:\n            raise ValueError(\"cannot accept context and kwargs\")\n        context = context or DistributionFinder.Context(**kwargs)\n        return itertools.chain.from_iterable(\n            resolver(context) for resolver in cls._discover_resolvers()\n        )\n\n    @staticmethod\n    def at(path):\n        \"\"\"Return a Distribution for the indicated metadata path\n\n        :param path: a string or path-like object\n        :return: a concrete Distribution instance for the path\n        \"\"\"\n        return PathDistribution(pathlib.Path(path))\n\n    @staticmethod\n    def _discover_resolvers():\n        \"\"\"Search the meta_path for resolvers.\"\"\"\n        declared = (\n            getattr(finder, 'find_distributions', None) for finder in sys.meta_path\n        )\n        return filter(None, declared)\n\n    @property\n    def metadata(self) -> _meta.PackageMetadata:\n        \"\"\"Return the parsed metadata for this Distribution.\n\n        The returned object will have keys that name the various bits of\n        metadata.  See PEP 566 for details.\n        \"\"\"\n        text = (\n            self.read_text('METADATA')\n            or self.read_text('PKG-INFO')\n            # This last clause is here to support old egg-info files.  Its\n            # effect is to just end up using the PathDistribution's self._path\n            # (which points to the egg-info file) attribute unchanged.\n            or self.read_text('')\n        )\n        return _adapters.Message(email.message_from_string(text))\n\n    @property\n    def name(self):\n        \"\"\"Return the 'Name' metadata for the distribution package.\"\"\"\n        return self.metadata['Name']\n\n    @property\n    def _normalized_name(self):\n        \"\"\"Return a normalized version of the name.\"\"\"\n        return Prepared.normalize(self.name)\n\n    @property\n    def version(self):\n        \"\"\"Return the 'Version' metadata for the distribution package.\"\"\"\n        return self.metadata['Version']\n\n    @property\n    def entry_points(self):\n        return EntryPoints._from_text_for(self.read_text('entry_points.txt'), self)\n\n    @property\n    def files(self):\n        \"\"\"Files in this distribution.\n\n        :return: List of PackagePath for this distribution or None\n\n        Result is `None` if the metadata file that enumerates files\n        (i.e. RECORD for dist-info or SOURCES.txt for egg-info) is\n        missing.\n        Result may be empty if the metadata exists but is empty.\n        \"\"\"\n\n        def make_file(name, hash=None, size_str=None):\n            result = PackagePath(name)\n            result.hash = FileHash(hash) if hash else None\n            result.size = int(size_str) if size_str else None\n            result.dist = self\n            return result\n\n        @pass_none\n        def make_files(lines):\n            return list(starmap(make_file, csv.reader(lines)))\n\n        return make_files(self._read_files_distinfo() or self._read_files_egginfo())\n\n    def _read_files_distinfo(self):\n        \"\"\"\n        Read the lines of RECORD\n        \"\"\"\n        text = self.read_text('RECORD')\n        return text and text.splitlines()\n\n    def _read_files_egginfo(self):\n        \"\"\"\n        SOURCES.txt might contain literal commas, so wrap each line\n        in quotes.\n        \"\"\"\n        text = self.read_text('SOURCES.txt')\n        return text and map('\"{}\"'.format, text.splitlines())\n\n    @property\n    def requires(self):\n        \"\"\"Generated requirements specified for this Distribution\"\"\"\n        reqs = self._read_dist_info_reqs() or self._read_egg_info_reqs()\n        return reqs and list(reqs)\n\n    def _read_dist_info_reqs(self):\n        return self.metadata.get_all('Requires-Dist')\n\n    def _read_egg_info_reqs(self):\n        source = self.read_text('requires.txt')\n        return pass_none(self._deps_from_requires_text)(source)\n\n    @classmethod\n    def _deps_from_requires_text(cls, source):\n        return cls._convert_egg_info_reqs_to_simple_reqs(Sectioned.read(source))\n\n    @staticmethod\n    def _convert_egg_info_reqs_to_simple_reqs(sections):\n        \"\"\"\n        Historically, setuptools would solicit and store 'extra'\n        requirements, including those with environment markers,\n        in separate sections. More modern tools expect each\n        dependency to be defined separately, with any relevant\n        extras and environment markers attached directly to that\n        requirement. This method converts the former to the\n        latter. See _test_deps_from_requires_text for an example.\n        \"\"\"\n\n        def make_condition(name):\n            return name and f'extra == \"{name}\"'\n\n        def quoted_marker(section):\n            section = section or ''\n            extra, sep, markers = section.partition(':')\n            if extra and markers:\n                markers = f'({markers})'\n            conditions = list(filter(None, [markers, make_condition(extra)]))\n            return '; ' + ' and '.join(conditions) if conditions else ''\n\n        def url_req_space(req):\n            \"\"\"\n            PEP 508 requires a space between the url_spec and the quoted_marker.\n            Ref python/importlib_metadata#357.\n            \"\"\"\n            # '@' is uniquely indicative of a url_req.\n            return ' ' * ('@' in req)\n\n        for section in sections:\n            space = url_req_space(section.value)\n            yield section.value + space + quoted_marker(section.name)\n\n\nclass DistributionFinder(MetaPathFinder):\n    \"\"\"\n    A MetaPathFinder capable of discovering installed distributions.\n    \"\"\"\n\n    class Context:\n        \"\"\"\n        Keyword arguments presented by the caller to\n        ``distributions()`` or ``Distribution.discover()``\n        to narrow the scope of a search for distributions\n        in all DistributionFinders.\n\n        Each DistributionFinder may expect any parameters\n        and should attempt to honor the canonical\n        parameters defined below when appropriate.\n        \"\"\"\n\n        name = None\n        \"\"\"\n        Specific name for which a distribution finder should match.\n        A name of ``None`` matches all distributions.\n        \"\"\"\n\n        def __init__(self, **kwargs):\n            vars(self).update(kwargs)\n\n        @property\n        def path(self):\n            \"\"\"\n            The sequence of directory path that a distribution finder\n            should search.\n\n            Typically refers to Python installed package paths such as\n            \"site-packages\" directories and defaults to ``sys.path``.\n            \"\"\"\n            return vars(self).get('path', sys.path)\n\n    @abc.abstractmethod\n    def find_distributions(self, context=Context()):\n        \"\"\"\n        Find distributions.\n\n        Return an iterable of all Distribution instances capable of\n        loading the metadata for packages matching the ``context``,\n        a DistributionFinder.Context instance.\n        \"\"\"\n\n\nclass FastPath:\n    \"\"\"\n    Micro-optimized class for searching a path for\n    children.\n\n    >>> FastPath('').children()\n    ['...']\n    \"\"\"\n\n    @functools.lru_cache()  # type: ignore\n    def __new__(cls, root):\n        return super().__new__(cls)\n\n    def __init__(self, root):\n        self.root = str(root)\n\n    def joinpath(self, child):\n        return pathlib.Path(self.root, child)\n\n    def children(self):\n        with suppress(Exception):\n            return os.listdir(self.root or '.')\n        with suppress(Exception):\n            return self.zip_children()\n        return []\n\n    def zip_children(self):\n        zip_path = zipp.Path(self.root)\n        names = zip_path.root.namelist()\n        self.joinpath = zip_path.joinpath\n\n        return dict.fromkeys(child.split(posixpath.sep, 1)[0] for child in names)\n\n    def search(self, name):\n        return self.lookup(self.mtime).search(name)\n\n    @property\n    def mtime(self):\n        with suppress(OSError):\n            return os.stat(self.root).st_mtime\n        self.lookup.cache_clear()\n\n    @method_cache\n    def lookup(self, mtime):\n        return Lookup(self)\n\n\nclass Lookup:\n    def __init__(self, path: FastPath):\n        base = os.path.basename(path.root).lower()\n        base_is_egg = base.endswith(\".egg\")\n        self.infos = FreezableDefaultDict(list)\n        self.eggs = FreezableDefaultDict(list)\n\n        for child in path.children():\n            low = child.lower()\n            if low.endswith((\".dist-info\", \".egg-info\")):\n                # rpartition is faster than splitext and suitable for this purpose.\n                name = low.rpartition(\".\")[0].partition(\"-\")[0]\n                normalized = Prepared.normalize(name)\n                self.infos[normalized].append(path.joinpath(child))\n            elif base_is_egg and low == \"egg-info\":\n                name = base.rpartition(\".\")[0].partition(\"-\")[0]\n                legacy_normalized = Prepared.legacy_normalize(name)\n                self.eggs[legacy_normalized].append(path.joinpath(child))\n\n        self.infos.freeze()\n        self.eggs.freeze()\n\n    def search(self, prepared):\n        infos = (\n            self.infos[prepared.normalized]\n            if prepared\n            else itertools.chain.from_iterable(self.infos.values())\n        )\n        eggs = (\n            self.eggs[prepared.legacy_normalized]\n            if prepared\n            else itertools.chain.from_iterable(self.eggs.values())\n        )\n        return itertools.chain(infos, eggs)\n\n\nclass Prepared:\n    \"\"\"\n    A prepared search for metadata on a possibly-named package.\n    \"\"\"\n\n    normalized = None\n    legacy_normalized = None\n\n    def __init__(self, name):\n        self.name = name\n        if name is None:\n            return\n        self.normalized = self.normalize(name)\n        self.legacy_normalized = self.legacy_normalize(name)\n\n    @staticmethod\n    def normalize(name):\n        \"\"\"\n        PEP 503 normalization plus dashes as underscores.\n        \"\"\"\n        return re.sub(r\"[-_.]+\", \"-\", name).lower().replace('-', '_')\n\n    @staticmethod\n    def legacy_normalize(name):\n        \"\"\"\n        Normalize the package name as found in the convention in\n        older packaging tools versions and specs.\n        \"\"\"\n        return name.lower().replace('-', '_')\n\n    def __bool__(self):\n        return bool(self.name)\n\n\n@install\nclass MetadataPathFinder(NullFinder, DistributionFinder):\n    \"\"\"A degenerate finder for distribution packages on the file system.\n\n    This finder supplies only a find_distributions() method for versions\n    of Python that do not have a PathFinder find_distributions().\n    \"\"\"\n\n    def find_distributions(self, context=DistributionFinder.Context()):\n        \"\"\"\n        Find distributions.\n\n        Return an iterable of all Distribution instances capable of\n        loading the metadata for packages matching ``context.name``\n        (or all names if ``None`` indicated) along the paths in the list\n        of directories ``context.path``.\n        \"\"\"\n        found = self._search_paths(context.name, context.path)\n        return map(PathDistribution, found)\n\n    @classmethod\n    def _search_paths(cls, name, paths):\n        \"\"\"Find metadata directories in paths heuristically.\"\"\"\n        prepared = Prepared(name)\n        return itertools.chain.from_iterable(\n            path.search(prepared) for path in map(FastPath, paths)\n        )\n\n    def invalidate_caches(cls):\n        FastPath.__new__.cache_clear()\n\n\nclass PathDistribution(Distribution):\n    def __init__(self, path: SimplePath):\n        \"\"\"Construct a distribution.\n\n        :param path: SimplePath indicating the metadata directory.\n        \"\"\"\n        self._path = path\n\n    def read_text(self, filename):\n        with suppress(\n            FileNotFoundError,\n            IsADirectoryError,\n            KeyError,\n            NotADirectoryError,\n            PermissionError,\n        ):\n            return self._path.joinpath(filename).read_text(encoding='utf-8')\n\n    read_text.__doc__ = Distribution.read_text.__doc__\n\n    def locate_file(self, path):\n        return self._path.parent / path\n\n    @property\n    def _normalized_name(self):\n        \"\"\"\n        Performance optimization: where possible, resolve the\n        normalized name from the file system path.\n        \"\"\"\n        stem = os.path.basename(str(self._path))\n        return self._name_from_stem(stem) or super()._normalized_name\n\n    def _name_from_stem(self, stem):\n        name, ext = os.path.splitext(stem)\n        if ext not in ('.dist-info', '.egg-info'):\n            return\n        name, sep, rest = stem.partition('-')\n        return name\n\n\ndef distribution(distribution_name):\n    \"\"\"Get the ``Distribution`` instance for the named package.\n\n    :param distribution_name: The name of the distribution package as a string.\n    :return: A ``Distribution`` instance (or subclass thereof).\n    \"\"\"\n    return Distribution.from_name(distribution_name)\n\n\ndef distributions(**kwargs):\n    \"\"\"Get all ``Distribution`` instances in the current environment.\n\n    :return: An iterable of ``Distribution`` instances.\n    \"\"\"\n    return Distribution.discover(**kwargs)\n\n\ndef metadata(distribution_name) -> _meta.PackageMetadata:\n    \"\"\"Get the metadata for the named package.\n\n    :param distribution_name: The name of the distribution package to query.\n    :return: A PackageMetadata containing the parsed metadata.\n    \"\"\"\n    return Distribution.from_name(distribution_name).metadata\n\n\ndef version(distribution_name):\n    \"\"\"Get the version string for the named package.\n\n    :param distribution_name: The name of the distribution package to query.\n    :return: The version string for the package as defined in the package's\n        \"Version\" metadata key.\n    \"\"\"\n    return distribution(distribution_name).version\n\n\ndef entry_points(**params) -> Union[EntryPoints, SelectableGroups]:\n    \"\"\"Return EntryPoint objects for all installed packages.\n\n    Pass selection parameters (group or name) to filter the\n    result to entry points matching those properties (see\n    EntryPoints.select()).\n\n    For compatibility, returns ``SelectableGroups`` object unless\n    selection parameters are supplied. In the future, this function\n    will return ``EntryPoints`` instead of ``SelectableGroups``\n    even when no selection parameters are supplied.\n\n    For maximum future compatibility, pass selection parameters\n    or invoke ``.select`` with parameters on the result.\n\n    :return: EntryPoints or SelectableGroups for all installed packages.\n    \"\"\"\n    norm_name = operator.attrgetter('_normalized_name')\n    unique = functools.partial(unique_everseen, key=norm_name)\n    eps = itertools.chain.from_iterable(\n        dist.entry_points for dist in unique(distributions())\n    )\n    return SelectableGroups.load(eps).select(**params)\n\n\ndef files(distribution_name):\n    \"\"\"Return a list of files for the named package.\n\n    :param distribution_name: The name of the distribution package to query.\n    :return: List of files composing the distribution.\n    \"\"\"\n    return distribution(distribution_name).files\n\n\ndef requires(distribution_name):\n    \"\"\"\n    Return a list of requirements for the named package.\n\n    :return: An iterator of requirements, suitable for\n        packaging.requirement.Requirement.\n    \"\"\"\n    return distribution(distribution_name).requires\n\n\ndef packages_distributions() -> Mapping[str, List[str]]:\n    \"\"\"\n    Return a mapping of top-level packages to their\n    distributions.\n\n    >>> import collections.abc\n    >>> pkgs = packages_distributions()\n    >>> all(isinstance(dist, collections.abc.Sequence) for dist in pkgs.values())\n    True\n    \"\"\"\n    pkg_to_dist = collections.defaultdict(list)\n    for dist in distributions():\n        for pkg in _top_level_declared(dist) or _top_level_inferred(dist):\n            pkg_to_dist[pkg].append(dist.metadata['Name'])\n    return dict(pkg_to_dist)\n\n\ndef _top_level_declared(dist):\n    return (dist.read_text('top_level.txt') or '').split()\n\n\ndef _top_level_inferred(dist):\n    return {\n        f.parts[0] if len(f.parts) > 1 else f.with_suffix('').name\n        for f in always_iterable(dist.files)\n        if f.suffix == \".py\"\n    }\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_metadata/_adapters.py",
    "content": "import re\nimport textwrap\nimport email.message\n\nfrom ._text import FoldedCase\n\n\nclass Message(email.message.Message):\n    multiple_use_keys = set(\n        map(\n            FoldedCase,\n            [\n                'Classifier',\n                'Obsoletes-Dist',\n                'Platform',\n                'Project-URL',\n                'Provides-Dist',\n                'Provides-Extra',\n                'Requires-Dist',\n                'Requires-External',\n                'Supported-Platform',\n                'Dynamic',\n            ],\n        )\n    )\n    \"\"\"\n    Keys that may be indicated multiple times per PEP 566.\n    \"\"\"\n\n    def __new__(cls, orig: email.message.Message):\n        res = super().__new__(cls)\n        vars(res).update(vars(orig))\n        return res\n\n    def __init__(self, *args, **kwargs):\n        self._headers = self._repair_headers()\n\n    # suppress spurious error from mypy\n    def __iter__(self):\n        return super().__iter__()\n\n    def _repair_headers(self):\n        def redent(value):\n            \"Correct for RFC822 indentation\"\n            if not value or '\\n' not in value:\n                return value\n            return textwrap.dedent(' ' * 8 + value)\n\n        headers = [(key, redent(value)) for key, value in vars(self)['_headers']]\n        if self._payload:\n            headers.append(('Description', self.get_payload()))\n        return headers\n\n    @property\n    def json(self):\n        \"\"\"\n        Convert PackageMetadata to a JSON-compatible format\n        per PEP 0566.\n        \"\"\"\n\n        def transform(key):\n            value = self.get_all(key) if key in self.multiple_use_keys else self[key]\n            if key == 'Keywords':\n                value = re.split(r'\\s+', value)\n            tk = key.lower().replace('-', '_')\n            return tk, value\n\n        return dict(map(transform, map(FoldedCase, self)))\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_metadata/_collections.py",
    "content": "import collections\n\n\n# from jaraco.collections 3.3\nclass FreezableDefaultDict(collections.defaultdict):\n    \"\"\"\n    Often it is desirable to prevent the mutation of\n    a default dict after its initial construction, such\n    as to prevent mutation during iteration.\n\n    >>> dd = FreezableDefaultDict(list)\n    >>> dd[0].append('1')\n    >>> dd.freeze()\n    >>> dd[1]\n    []\n    >>> len(dd)\n    1\n    \"\"\"\n\n    def __missing__(self, key):\n        return getattr(self, '_frozen', super().__missing__)(key)\n\n    def freeze(self):\n        self._frozen = lambda key: self.default_factory()\n\n\nclass Pair(collections.namedtuple('Pair', 'name value')):\n    @classmethod\n    def parse(cls, text):\n        return cls(*map(str.strip, text.split(\"=\", 1)))\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_metadata/_compat.py",
    "content": "import sys\nimport platform\n\n\n__all__ = ['install', 'NullFinder', 'Protocol']\n\n\ntry:\n    from typing import Protocol\nexcept ImportError:  # pragma: no cover\n    from ..typing_extensions import Protocol  # type: ignore\n\n\ndef install(cls):\n    \"\"\"\n    Class decorator for installation on sys.meta_path.\n\n    Adds the backport DistributionFinder to sys.meta_path and\n    attempts to disable the finder functionality of the stdlib\n    DistributionFinder.\n    \"\"\"\n    sys.meta_path.append(cls())\n    disable_stdlib_finder()\n    return cls\n\n\ndef disable_stdlib_finder():\n    \"\"\"\n    Give the backport primacy for discovering path-based distributions\n    by monkey-patching the stdlib O_O.\n\n    See #91 for more background for rationale on this sketchy\n    behavior.\n    \"\"\"\n\n    def matches(finder):\n        return getattr(\n            finder, '__module__', None\n        ) == '_frozen_importlib_external' and hasattr(finder, 'find_distributions')\n\n    for finder in filter(matches, sys.meta_path):  # pragma: nocover\n        del finder.find_distributions\n\n\nclass NullFinder:\n    \"\"\"\n    A \"Finder\" (aka \"MetaClassFinder\") that never finds any modules,\n    but may find distributions.\n    \"\"\"\n\n    @staticmethod\n    def find_spec(*args, **kwargs):\n        return None\n\n    # In Python 2, the import system requires finders\n    # to have a find_module() method, but this usage\n    # is deprecated in Python 3 in favor of find_spec().\n    # For the purposes of this finder (i.e. being present\n    # on sys.meta_path but having no other import\n    # system functionality), the two methods are identical.\n    find_module = find_spec\n\n\ndef pypy_partial(val):\n    \"\"\"\n    Adjust for variable stacklevel on partial under PyPy.\n\n    Workaround for #327.\n    \"\"\"\n    is_pypy = platform.python_implementation() == 'PyPy'\n    return val + is_pypy\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_metadata/_functools.py",
    "content": "import types\nimport functools\n\n\n# from jaraco.functools 3.3\ndef method_cache(method, cache_wrapper=None):\n    \"\"\"\n    Wrap lru_cache to support storing the cache data in the object instances.\n\n    Abstracts the common paradigm where the method explicitly saves an\n    underscore-prefixed protected property on first call and returns that\n    subsequently.\n\n    >>> class MyClass:\n    ...     calls = 0\n    ...\n    ...     @method_cache\n    ...     def method(self, value):\n    ...         self.calls += 1\n    ...         return value\n\n    >>> a = MyClass()\n    >>> a.method(3)\n    3\n    >>> for x in range(75):\n    ...     res = a.method(x)\n    >>> a.calls\n    75\n\n    Note that the apparent behavior will be exactly like that of lru_cache\n    except that the cache is stored on each instance, so values in one\n    instance will not flush values from another, and when an instance is\n    deleted, so are the cached values for that instance.\n\n    >>> b = MyClass()\n    >>> for x in range(35):\n    ...     res = b.method(x)\n    >>> b.calls\n    35\n    >>> a.method(0)\n    0\n    >>> a.calls\n    75\n\n    Note that if method had been decorated with ``functools.lru_cache()``,\n    a.calls would have been 76 (due to the cached value of 0 having been\n    flushed by the 'b' instance).\n\n    Clear the cache with ``.cache_clear()``\n\n    >>> a.method.cache_clear()\n\n    Same for a method that hasn't yet been called.\n\n    >>> c = MyClass()\n    >>> c.method.cache_clear()\n\n    Another cache wrapper may be supplied:\n\n    >>> cache = functools.lru_cache(maxsize=2)\n    >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache)\n    >>> a = MyClass()\n    >>> a.method2()\n    3\n\n    Caution - do not subsequently wrap the method with another decorator, such\n    as ``@property``, which changes the semantics of the function.\n\n    See also\n    http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/\n    for another implementation and additional justification.\n    \"\"\"\n    cache_wrapper = cache_wrapper or functools.lru_cache()\n\n    def wrapper(self, *args, **kwargs):\n        # it's the first call, replace the method with a cached, bound method\n        bound_method = types.MethodType(method, self)\n        cached_method = cache_wrapper(bound_method)\n        setattr(self, method.__name__, cached_method)\n        return cached_method(*args, **kwargs)\n\n    # Support cache clear even before cache has been created.\n    wrapper.cache_clear = lambda: None\n\n    return wrapper\n\n\n# From jaraco.functools 3.3\ndef pass_none(func):\n    \"\"\"\n    Wrap func so it's not called if its first param is None\n\n    >>> print_text = pass_none(print)\n    >>> print_text('text')\n    text\n    >>> print_text(None)\n    \"\"\"\n\n    @functools.wraps(func)\n    def wrapper(param, *args, **kwargs):\n        if param is not None:\n            return func(param, *args, **kwargs)\n\n    return wrapper\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_metadata/_itertools.py",
    "content": "from itertools import filterfalse\n\n\ndef unique_everseen(iterable, key=None):\n    \"List unique elements, preserving order. Remember all elements ever seen.\"\n    # unique_everseen('AAAABBBCCDAABBB') --> A B C D\n    # unique_everseen('ABBCcAD', str.lower) --> A B C D\n    seen = set()\n    seen_add = seen.add\n    if key is None:\n        for element in filterfalse(seen.__contains__, iterable):\n            seen_add(element)\n            yield element\n    else:\n        for element in iterable:\n            k = key(element)\n            if k not in seen:\n                seen_add(k)\n                yield element\n\n\n# copied from more_itertools 8.8\ndef always_iterable(obj, base_type=(str, bytes)):\n    \"\"\"If *obj* is iterable, return an iterator over its items::\n\n        >>> obj = (1, 2, 3)\n        >>> list(always_iterable(obj))\n        [1, 2, 3]\n\n    If *obj* is not iterable, return a one-item iterable containing *obj*::\n\n        >>> obj = 1\n        >>> list(always_iterable(obj))\n        [1]\n\n    If *obj* is ``None``, return an empty iterable:\n\n        >>> obj = None\n        >>> list(always_iterable(None))\n        []\n\n    By default, binary and text strings are not considered iterable::\n\n        >>> obj = 'foo'\n        >>> list(always_iterable(obj))\n        ['foo']\n\n    If *base_type* is set, objects for which ``isinstance(obj, base_type)``\n    returns ``True`` won't be considered iterable.\n\n        >>> obj = {'a': 1}\n        >>> list(always_iterable(obj))  # Iterate over the dict's keys\n        ['a']\n        >>> list(always_iterable(obj, base_type=dict))  # Treat dicts as a unit\n        [{'a': 1}]\n\n    Set *base_type* to ``None`` to avoid any special handling and treat objects\n    Python considers iterable as iterable:\n\n        >>> obj = 'foo'\n        >>> list(always_iterable(obj, base_type=None))\n        ['f', 'o', 'o']\n    \"\"\"\n    if obj is None:\n        return iter(())\n\n    if (base_type is not None) and isinstance(obj, base_type):\n        return iter((obj,))\n\n    try:\n        return iter(obj)\n    except TypeError:\n        return iter((obj,))\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_metadata/_meta.py",
    "content": "from ._compat import Protocol\nfrom typing import Any, Dict, Iterator, List, TypeVar, Union\n\n\n_T = TypeVar(\"_T\")\n\n\nclass PackageMetadata(Protocol):\n    def __len__(self) -> int:\n        ...  # pragma: no cover\n\n    def __contains__(self, item: str) -> bool:\n        ...  # pragma: no cover\n\n    def __getitem__(self, key: str) -> str:\n        ...  # pragma: no cover\n\n    def __iter__(self) -> Iterator[str]:\n        ...  # pragma: no cover\n\n    def get_all(self, name: str, failobj: _T = ...) -> Union[List[Any], _T]:\n        \"\"\"\n        Return all values associated with a possibly multi-valued key.\n        \"\"\"\n\n    @property\n    def json(self) -> Dict[str, Union[str, List[str]]]:\n        \"\"\"\n        A JSON-compatible form of the metadata.\n        \"\"\"\n\n\nclass SimplePath(Protocol):\n    \"\"\"\n    A minimal subset of pathlib.Path required by PathDistribution.\n    \"\"\"\n\n    def joinpath(self) -> 'SimplePath':\n        ...  # pragma: no cover\n\n    def __truediv__(self) -> 'SimplePath':\n        ...  # pragma: no cover\n\n    def parent(self) -> 'SimplePath':\n        ...  # pragma: no cover\n\n    def read_text(self) -> str:\n        ...  # pragma: no cover\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_metadata/_text.py",
    "content": "import re\n\nfrom ._functools import method_cache\n\n\n# from jaraco.text 3.5\nclass FoldedCase(str):\n    \"\"\"\n    A case insensitive string class; behaves just like str\n    except compares equal when the only variation is case.\n\n    >>> s = FoldedCase('hello world')\n\n    >>> s == 'Hello World'\n    True\n\n    >>> 'Hello World' == s\n    True\n\n    >>> s != 'Hello World'\n    False\n\n    >>> s.index('O')\n    4\n\n    >>> s.split('O')\n    ['hell', ' w', 'rld']\n\n    >>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta']))\n    ['alpha', 'Beta', 'GAMMA']\n\n    Sequence membership is straightforward.\n\n    >>> \"Hello World\" in [s]\n    True\n    >>> s in [\"Hello World\"]\n    True\n\n    You may test for set inclusion, but candidate and elements\n    must both be folded.\n\n    >>> FoldedCase(\"Hello World\") in {s}\n    True\n    >>> s in {FoldedCase(\"Hello World\")}\n    True\n\n    String inclusion works as long as the FoldedCase object\n    is on the right.\n\n    >>> \"hello\" in FoldedCase(\"Hello World\")\n    True\n\n    But not if the FoldedCase object is on the left:\n\n    >>> FoldedCase('hello') in 'Hello World'\n    False\n\n    In that case, use in_:\n\n    >>> FoldedCase('hello').in_('Hello World')\n    True\n\n    >>> FoldedCase('hello') > FoldedCase('Hello')\n    False\n    \"\"\"\n\n    def __lt__(self, other):\n        return self.lower() < other.lower()\n\n    def __gt__(self, other):\n        return self.lower() > other.lower()\n\n    def __eq__(self, other):\n        return self.lower() == other.lower()\n\n    def __ne__(self, other):\n        return self.lower() != other.lower()\n\n    def __hash__(self):\n        return hash(self.lower())\n\n    def __contains__(self, other):\n        return super().lower().__contains__(other.lower())\n\n    def in_(self, other):\n        \"Does self appear in other?\"\n        return self in FoldedCase(other)\n\n    # cache lower since it's likely to be called frequently.\n    @method_cache\n    def lower(self):\n        return super().lower()\n\n    def index(self, sub):\n        return self.lower().index(sub.lower())\n\n    def split(self, splitter=' ', maxsplit=0):\n        pattern = re.compile(re.escape(splitter), re.I)\n        return pattern.split(self, maxsplit)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_resources/__init__.py",
    "content": "\"\"\"Read resources contained within a package.\"\"\"\n\nfrom ._common import (\n    as_file,\n    files,\n    Package,\n)\n\nfrom ._legacy import (\n    contents,\n    open_binary,\n    read_binary,\n    open_text,\n    read_text,\n    is_resource,\n    path,\n    Resource,\n)\n\nfrom .abc import ResourceReader\n\n\n__all__ = [\n    'Package',\n    'Resource',\n    'ResourceReader',\n    'as_file',\n    'contents',\n    'files',\n    'is_resource',\n    'open_binary',\n    'open_text',\n    'path',\n    'read_binary',\n    'read_text',\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_resources/_adapters.py",
    "content": "from contextlib import suppress\nfrom io import TextIOWrapper\n\nfrom . import abc\n\n\nclass SpecLoaderAdapter:\n    \"\"\"\n    Adapt a package spec to adapt the underlying loader.\n    \"\"\"\n\n    def __init__(self, spec, adapter=lambda spec: spec.loader):\n        self.spec = spec\n        self.loader = adapter(spec)\n\n    def __getattr__(self, name):\n        return getattr(self.spec, name)\n\n\nclass TraversableResourcesLoader:\n    \"\"\"\n    Adapt a loader to provide TraversableResources.\n    \"\"\"\n\n    def __init__(self, spec):\n        self.spec = spec\n\n    def get_resource_reader(self, name):\n        return CompatibilityFiles(self.spec)._native()\n\n\ndef _io_wrapper(file, mode='r', *args, **kwargs):\n    if mode == 'r':\n        return TextIOWrapper(file, *args, **kwargs)\n    elif mode == 'rb':\n        return file\n    raise ValueError(\n        \"Invalid mode value '{}', only 'r' and 'rb' are supported\".format(mode)\n    )\n\n\nclass CompatibilityFiles:\n    \"\"\"\n    Adapter for an existing or non-existent resource reader\n    to provide a compatibility .files().\n    \"\"\"\n\n    class SpecPath(abc.Traversable):\n        \"\"\"\n        Path tied to a module spec.\n        Can be read and exposes the resource reader children.\n        \"\"\"\n\n        def __init__(self, spec, reader):\n            self._spec = spec\n            self._reader = reader\n\n        def iterdir(self):\n            if not self._reader:\n                return iter(())\n            return iter(\n                CompatibilityFiles.ChildPath(self._reader, path)\n                for path in self._reader.contents()\n            )\n\n        def is_file(self):\n            return False\n\n        is_dir = is_file\n\n        def joinpath(self, other):\n            if not self._reader:\n                return CompatibilityFiles.OrphanPath(other)\n            return CompatibilityFiles.ChildPath(self._reader, other)\n\n        @property\n        def name(self):\n            return self._spec.name\n\n        def open(self, mode='r', *args, **kwargs):\n            return _io_wrapper(self._reader.open_resource(None), mode, *args, **kwargs)\n\n    class ChildPath(abc.Traversable):\n        \"\"\"\n        Path tied to a resource reader child.\n        Can be read but doesn't expose any meaningful children.\n        \"\"\"\n\n        def __init__(self, reader, name):\n            self._reader = reader\n            self._name = name\n\n        def iterdir(self):\n            return iter(())\n\n        def is_file(self):\n            return self._reader.is_resource(self.name)\n\n        def is_dir(self):\n            return not self.is_file()\n\n        def joinpath(self, other):\n            return CompatibilityFiles.OrphanPath(self.name, other)\n\n        @property\n        def name(self):\n            return self._name\n\n        def open(self, mode='r', *args, **kwargs):\n            return _io_wrapper(\n                self._reader.open_resource(self.name), mode, *args, **kwargs\n            )\n\n    class OrphanPath(abc.Traversable):\n        \"\"\"\n        Orphan path, not tied to a module spec or resource reader.\n        Can't be read and doesn't expose any meaningful children.\n        \"\"\"\n\n        def __init__(self, *path_parts):\n            if len(path_parts) < 1:\n                raise ValueError('Need at least one path part to construct a path')\n            self._path = path_parts\n\n        def iterdir(self):\n            return iter(())\n\n        def is_file(self):\n            return False\n\n        is_dir = is_file\n\n        def joinpath(self, other):\n            return CompatibilityFiles.OrphanPath(*self._path, other)\n\n        @property\n        def name(self):\n            return self._path[-1]\n\n        def open(self, mode='r', *args, **kwargs):\n            raise FileNotFoundError(\"Can't open orphan path\")\n\n    def __init__(self, spec):\n        self.spec = spec\n\n    @property\n    def _reader(self):\n        with suppress(AttributeError):\n            return self.spec.loader.get_resource_reader(self.spec.name)\n\n    def _native(self):\n        \"\"\"\n        Return the native reader if it supports files().\n        \"\"\"\n        reader = self._reader\n        return reader if hasattr(reader, 'files') else self\n\n    def __getattr__(self, attr):\n        return getattr(self._reader, attr)\n\n    def files(self):\n        return CompatibilityFiles.SpecPath(self.spec, self._reader)\n\n\ndef wrap_spec(package):\n    \"\"\"\n    Construct a package spec with traversable compatibility\n    on the spec/loader/reader.\n    \"\"\"\n    return SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_resources/_common.py",
    "content": "import os\nimport pathlib\nimport tempfile\nimport functools\nimport contextlib\nimport types\nimport importlib\n\nfrom typing import Union, Optional\nfrom .abc import ResourceReader, Traversable\n\nfrom ._compat import wrap_spec\n\nPackage = Union[types.ModuleType, str]\n\n\ndef files(package):\n    # type: (Package) -> Traversable\n    \"\"\"\n    Get a Traversable resource from a package\n    \"\"\"\n    return from_package(get_package(package))\n\n\ndef get_resource_reader(package):\n    # type: (types.ModuleType) -> Optional[ResourceReader]\n    \"\"\"\n    Return the package's loader if it's a ResourceReader.\n    \"\"\"\n    # We can't use\n    # a issubclass() check here because apparently abc.'s __subclasscheck__()\n    # hook wants to create a weak reference to the object, but\n    # zipimport.zipimporter does not support weak references, resulting in a\n    # TypeError.  That seems terrible.\n    spec = package.__spec__\n    reader = getattr(spec.loader, 'get_resource_reader', None)  # type: ignore\n    if reader is None:\n        return None\n    return reader(spec.name)  # type: ignore\n\n\ndef resolve(cand):\n    # type: (Package) -> types.ModuleType\n    return cand if isinstance(cand, types.ModuleType) else importlib.import_module(cand)\n\n\ndef get_package(package):\n    # type: (Package) -> types.ModuleType\n    \"\"\"Take a package name or module object and return the module.\n\n    Raise an exception if the resolved module is not a package.\n    \"\"\"\n    resolved = resolve(package)\n    if wrap_spec(resolved).submodule_search_locations is None:\n        raise TypeError(f'{package!r} is not a package')\n    return resolved\n\n\ndef from_package(package):\n    \"\"\"\n    Return a Traversable object for the given package.\n\n    \"\"\"\n    spec = wrap_spec(package)\n    reader = spec.loader.get_resource_reader(spec.name)\n    return reader.files()\n\n\n@contextlib.contextmanager\ndef _tempfile(reader, suffix=''):\n    # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try'\n    # blocks due to the need to close the temporary file to work on Windows\n    # properly.\n    fd, raw_path = tempfile.mkstemp(suffix=suffix)\n    try:\n        try:\n            os.write(fd, reader())\n        finally:\n            os.close(fd)\n        del reader\n        yield pathlib.Path(raw_path)\n    finally:\n        try:\n            os.remove(raw_path)\n        except FileNotFoundError:\n            pass\n\n\n@functools.singledispatch\ndef as_file(path):\n    \"\"\"\n    Given a Traversable object, return that object as a\n    path on the local file system in a context manager.\n    \"\"\"\n    return _tempfile(path.read_bytes, suffix=path.name)\n\n\n@as_file.register(pathlib.Path)\n@contextlib.contextmanager\ndef _(path):\n    \"\"\"\n    Degenerate behavior for pathlib.Path objects.\n    \"\"\"\n    yield path\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_resources/_compat.py",
    "content": "# flake8: noqa\n\nimport abc\nimport sys\nimport pathlib\nfrom contextlib import suppress\n\nif sys.version_info >= (3, 10):\n    from zipfile import Path as ZipPath  # type: ignore\nelse:\n    from ..zipp import Path as ZipPath  # type: ignore\n\n\ntry:\n    from typing import runtime_checkable  # type: ignore\nexcept ImportError:\n\n    def runtime_checkable(cls):  # type: ignore\n        return cls\n\n\ntry:\n    from typing import Protocol  # type: ignore\nexcept ImportError:\n    Protocol = abc.ABC  # type: ignore\n\n\nclass TraversableResourcesLoader:\n    \"\"\"\n    Adapt loaders to provide TraversableResources and other\n    compatibility.\n\n    Used primarily for Python 3.9 and earlier where the native\n    loaders do not yet implement TraversableResources.\n    \"\"\"\n\n    def __init__(self, spec):\n        self.spec = spec\n\n    @property\n    def path(self):\n        return self.spec.origin\n\n    def get_resource_reader(self, name):\n        from . import readers, _adapters\n\n        def _zip_reader(spec):\n            with suppress(AttributeError):\n                return readers.ZipReader(spec.loader, spec.name)\n\n        def _namespace_reader(spec):\n            with suppress(AttributeError, ValueError):\n                return readers.NamespaceReader(spec.submodule_search_locations)\n\n        def _available_reader(spec):\n            with suppress(AttributeError):\n                return spec.loader.get_resource_reader(spec.name)\n\n        def _native_reader(spec):\n            reader = _available_reader(spec)\n            return reader if hasattr(reader, 'files') else None\n\n        def _file_reader(spec):\n            try:\n                path = pathlib.Path(self.path)\n            except TypeError:\n                return None\n            if path.exists():\n                return readers.FileReader(self)\n\n        return (\n            # native reader if it supplies 'files'\n            _native_reader(self.spec)\n            or\n            # local ZipReader if a zip module\n            _zip_reader(self.spec)\n            or\n            # local NamespaceReader if a namespace module\n            _namespace_reader(self.spec)\n            or\n            # local FileReader\n            _file_reader(self.spec)\n            # fallback - adapt the spec ResourceReader to TraversableReader\n            or _adapters.CompatibilityFiles(self.spec)\n        )\n\n\ndef wrap_spec(package):\n    \"\"\"\n    Construct a package spec with traversable compatibility\n    on the spec/loader/reader.\n\n    Supersedes _adapters.wrap_spec to use TraversableResourcesLoader\n    from above for older Python compatibility (<3.10).\n    \"\"\"\n    from . import _adapters\n\n    return _adapters.SpecLoaderAdapter(package.__spec__, TraversableResourcesLoader)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_resources/_itertools.py",
    "content": "from itertools import filterfalse\n\nfrom typing import (\n    Callable,\n    Iterable,\n    Iterator,\n    Optional,\n    Set,\n    TypeVar,\n    Union,\n)\n\n# Type and type variable definitions\n_T = TypeVar('_T')\n_U = TypeVar('_U')\n\n\ndef unique_everseen(\n    iterable: Iterable[_T], key: Optional[Callable[[_T], _U]] = None\n) -> Iterator[_T]:\n    \"List unique elements, preserving order. Remember all elements ever seen.\"\n    # unique_everseen('AAAABBBCCDAABBB') --> A B C D\n    # unique_everseen('ABBCcAD', str.lower) --> A B C D\n    seen: Set[Union[_T, _U]] = set()\n    seen_add = seen.add\n    if key is None:\n        for element in filterfalse(seen.__contains__, iterable):\n            seen_add(element)\n            yield element\n    else:\n        for element in iterable:\n            k = key(element)\n            if k not in seen:\n                seen_add(k)\n                yield element\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_resources/_legacy.py",
    "content": "import functools\nimport os\nimport pathlib\nimport types\nimport warnings\n\nfrom typing import Union, Iterable, ContextManager, BinaryIO, TextIO, Any\n\nfrom . import _common\n\nPackage = Union[types.ModuleType, str]\nResource = str\n\n\ndef deprecated(func):\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        warnings.warn(\n            f\"{func.__name__} is deprecated. Use files() instead. \"\n            \"Refer to https://importlib-resources.readthedocs.io\"\n            \"/en/latest/using.html#migrating-from-legacy for migration advice.\",\n            DeprecationWarning,\n            stacklevel=2,\n        )\n        return func(*args, **kwargs)\n\n    return wrapper\n\n\ndef normalize_path(path):\n    # type: (Any) -> str\n    \"\"\"Normalize a path by ensuring it is a string.\n\n    If the resulting string contains path separators, an exception is raised.\n    \"\"\"\n    str_path = str(path)\n    parent, file_name = os.path.split(str_path)\n    if parent:\n        raise ValueError(f'{path!r} must be only a file name')\n    return file_name\n\n\n@deprecated\ndef open_binary(package: Package, resource: Resource) -> BinaryIO:\n    \"\"\"Return a file-like object opened for binary reading of the resource.\"\"\"\n    return (_common.files(package) / normalize_path(resource)).open('rb')\n\n\n@deprecated\ndef read_binary(package: Package, resource: Resource) -> bytes:\n    \"\"\"Return the binary contents of the resource.\"\"\"\n    return (_common.files(package) / normalize_path(resource)).read_bytes()\n\n\n@deprecated\ndef open_text(\n    package: Package,\n    resource: Resource,\n    encoding: str = 'utf-8',\n    errors: str = 'strict',\n) -> TextIO:\n    \"\"\"Return a file-like object opened for text reading of the resource.\"\"\"\n    return (_common.files(package) / normalize_path(resource)).open(\n        'r', encoding=encoding, errors=errors\n    )\n\n\n@deprecated\ndef read_text(\n    package: Package,\n    resource: Resource,\n    encoding: str = 'utf-8',\n    errors: str = 'strict',\n) -> str:\n    \"\"\"Return the decoded string of the resource.\n\n    The decoding-related arguments have the same semantics as those of\n    bytes.decode().\n    \"\"\"\n    with open_text(package, resource, encoding, errors) as fp:\n        return fp.read()\n\n\n@deprecated\ndef contents(package: Package) -> Iterable[str]:\n    \"\"\"Return an iterable of entries in `package`.\n\n    Note that not all entries are resources.  Specifically, directories are\n    not considered resources.  Use `is_resource()` on each entry returned here\n    to check if it is a resource or not.\n    \"\"\"\n    return [path.name for path in _common.files(package).iterdir()]\n\n\n@deprecated\ndef is_resource(package: Package, name: str) -> bool:\n    \"\"\"True if `name` is a resource inside `package`.\n\n    Directories are *not* resources.\n    \"\"\"\n    resource = normalize_path(name)\n    return any(\n        traversable.name == resource and traversable.is_file()\n        for traversable in _common.files(package).iterdir()\n    )\n\n\n@deprecated\ndef path(\n    package: Package,\n    resource: Resource,\n) -> ContextManager[pathlib.Path]:\n    \"\"\"A context manager providing a file path object to the resource.\n\n    If the resource does not already exist on its own on the file system,\n    a temporary file will be created. If the file was created, the file\n    will be deleted upon exiting the context manager (no exception is\n    raised if the file was deleted prior to the context manager\n    exiting).\n    \"\"\"\n    return _common.as_file(_common.files(package) / normalize_path(resource))\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_resources/abc.py",
    "content": "import abc\nfrom typing import BinaryIO, Iterable, Text\n\nfrom ._compat import runtime_checkable, Protocol\n\n\nclass ResourceReader(metaclass=abc.ABCMeta):\n    \"\"\"Abstract base class for loaders to provide resource reading support.\"\"\"\n\n    @abc.abstractmethod\n    def open_resource(self, resource: Text) -> BinaryIO:\n        \"\"\"Return an opened, file-like object for binary reading.\n\n        The 'resource' argument is expected to represent only a file name.\n        If the resource cannot be found, FileNotFoundError is raised.\n        \"\"\"\n        # This deliberately raises FileNotFoundError instead of\n        # NotImplementedError so that if this method is accidentally called,\n        # it'll still do the right thing.\n        raise FileNotFoundError\n\n    @abc.abstractmethod\n    def resource_path(self, resource: Text) -> Text:\n        \"\"\"Return the file system path to the specified resource.\n\n        The 'resource' argument is expected to represent only a file name.\n        If the resource does not exist on the file system, raise\n        FileNotFoundError.\n        \"\"\"\n        # This deliberately raises FileNotFoundError instead of\n        # NotImplementedError so that if this method is accidentally called,\n        # it'll still do the right thing.\n        raise FileNotFoundError\n\n    @abc.abstractmethod\n    def is_resource(self, path: Text) -> bool:\n        \"\"\"Return True if the named 'path' is a resource.\n\n        Files are resources, directories are not.\n        \"\"\"\n        raise FileNotFoundError\n\n    @abc.abstractmethod\n    def contents(self) -> Iterable[str]:\n        \"\"\"Return an iterable of entries in `package`.\"\"\"\n        raise FileNotFoundError\n\n\n@runtime_checkable\nclass Traversable(Protocol):\n    \"\"\"\n    An object with a subset of pathlib.Path methods suitable for\n    traversing directories and opening files.\n    \"\"\"\n\n    @abc.abstractmethod\n    def iterdir(self):\n        \"\"\"\n        Yield Traversable objects in self\n        \"\"\"\n\n    def read_bytes(self):\n        \"\"\"\n        Read contents of self as bytes\n        \"\"\"\n        with self.open('rb') as strm:\n            return strm.read()\n\n    def read_text(self, encoding=None):\n        \"\"\"\n        Read contents of self as text\n        \"\"\"\n        with self.open(encoding=encoding) as strm:\n            return strm.read()\n\n    @abc.abstractmethod\n    def is_dir(self) -> bool:\n        \"\"\"\n        Return True if self is a directory\n        \"\"\"\n\n    @abc.abstractmethod\n    def is_file(self) -> bool:\n        \"\"\"\n        Return True if self is a file\n        \"\"\"\n\n    @abc.abstractmethod\n    def joinpath(self, child):\n        \"\"\"\n        Return Traversable child in self\n        \"\"\"\n\n    def __truediv__(self, child):\n        \"\"\"\n        Return Traversable child in self\n        \"\"\"\n        return self.joinpath(child)\n\n    @abc.abstractmethod\n    def open(self, mode='r', *args, **kwargs):\n        \"\"\"\n        mode may be 'r' or 'rb' to open as text or binary. Return a handle\n        suitable for reading (same as pathlib.Path.open).\n\n        When opening as text, accepts encoding parameters such as those\n        accepted by io.TextIOWrapper.\n        \"\"\"\n\n    @abc.abstractproperty\n    def name(self) -> str:\n        \"\"\"\n        The base name of this object without any parent references.\n        \"\"\"\n\n\nclass TraversableResources(ResourceReader):\n    \"\"\"\n    The required interface for providing traversable\n    resources.\n    \"\"\"\n\n    @abc.abstractmethod\n    def files(self):\n        \"\"\"Return a Traversable object for the loaded package.\"\"\"\n\n    def open_resource(self, resource):\n        return self.files().joinpath(resource).open('rb')\n\n    def resource_path(self, resource):\n        raise FileNotFoundError(resource)\n\n    def is_resource(self, path):\n        return self.files().joinpath(path).is_file()\n\n    def contents(self):\n        return (item.name for item in self.files().iterdir())\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_resources/readers.py",
    "content": "import collections\nimport pathlib\nimport operator\n\nfrom . import abc\n\nfrom ._itertools import unique_everseen\nfrom ._compat import ZipPath\n\n\ndef remove_duplicates(items):\n    return iter(collections.OrderedDict.fromkeys(items))\n\n\nclass FileReader(abc.TraversableResources):\n    def __init__(self, loader):\n        self.path = pathlib.Path(loader.path).parent\n\n    def resource_path(self, resource):\n        \"\"\"\n        Return the file system path to prevent\n        `resources.path()` from creating a temporary\n        copy.\n        \"\"\"\n        return str(self.path.joinpath(resource))\n\n    def files(self):\n        return self.path\n\n\nclass ZipReader(abc.TraversableResources):\n    def __init__(self, loader, module):\n        _, _, name = module.rpartition('.')\n        self.prefix = loader.prefix.replace('\\\\', '/') + name + '/'\n        self.archive = loader.archive\n\n    def open_resource(self, resource):\n        try:\n            return super().open_resource(resource)\n        except KeyError as exc:\n            raise FileNotFoundError(exc.args[0])\n\n    def is_resource(self, path):\n        # workaround for `zipfile.Path.is_file` returning true\n        # for non-existent paths.\n        target = self.files().joinpath(path)\n        return target.is_file() and target.exists()\n\n    def files(self):\n        return ZipPath(self.archive, self.prefix)\n\n\nclass MultiplexedPath(abc.Traversable):\n    \"\"\"\n    Given a series of Traversable objects, implement a merged\n    version of the interface across all objects. Useful for\n    namespace packages which may be multihomed at a single\n    name.\n    \"\"\"\n\n    def __init__(self, *paths):\n        self._paths = list(map(pathlib.Path, remove_duplicates(paths)))\n        if not self._paths:\n            message = 'MultiplexedPath must contain at least one path'\n            raise FileNotFoundError(message)\n        if not all(path.is_dir() for path in self._paths):\n            raise NotADirectoryError('MultiplexedPath only supports directories')\n\n    def iterdir(self):\n        files = (file for path in self._paths for file in path.iterdir())\n        return unique_everseen(files, key=operator.attrgetter('name'))\n\n    def read_bytes(self):\n        raise FileNotFoundError(f'{self} is not a file')\n\n    def read_text(self, *args, **kwargs):\n        raise FileNotFoundError(f'{self} is not a file')\n\n    def is_dir(self):\n        return True\n\n    def is_file(self):\n        return False\n\n    def joinpath(self, child):\n        # first try to find child in current paths\n        for file in self.iterdir():\n            if file.name == child:\n                return file\n        # if it does not exist, construct it with the first path\n        return self._paths[0] / child\n\n    __truediv__ = joinpath\n\n    def open(self, *args, **kwargs):\n        raise FileNotFoundError(f'{self} is not a file')\n\n    @property\n    def name(self):\n        return self._paths[0].name\n\n    def __repr__(self):\n        paths = ', '.join(f\"'{path}'\" for path in self._paths)\n        return f'MultiplexedPath({paths})'\n\n\nclass NamespaceReader(abc.TraversableResources):\n    def __init__(self, namespace_path):\n        if 'NamespacePath' not in str(namespace_path):\n            raise ValueError('Invalid path')\n        self.path = MultiplexedPath(*list(namespace_path))\n\n    def resource_path(self, resource):\n        \"\"\"\n        Return the file system path to prevent\n        `resources.path()` from creating a temporary\n        copy.\n        \"\"\"\n        return str(self.path.joinpath(resource))\n\n    def files(self):\n        return self.path\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/importlib_resources/simple.py",
    "content": "\"\"\"\nInterface adapters for low-level readers.\n\"\"\"\n\nimport abc\nimport io\nimport itertools\nfrom typing import BinaryIO, List\n\nfrom .abc import Traversable, TraversableResources\n\n\nclass SimpleReader(abc.ABC):\n    \"\"\"\n    The minimum, low-level interface required from a resource\n    provider.\n    \"\"\"\n\n    @abc.abstractproperty\n    def package(self):\n        # type: () -> str\n        \"\"\"\n        The name of the package for which this reader loads resources.\n        \"\"\"\n\n    @abc.abstractmethod\n    def children(self):\n        # type: () -> List['SimpleReader']\n        \"\"\"\n        Obtain an iterable of SimpleReader for available\n        child containers (e.g. directories).\n        \"\"\"\n\n    @abc.abstractmethod\n    def resources(self):\n        # type: () -> List[str]\n        \"\"\"\n        Obtain available named resources for this virtual package.\n        \"\"\"\n\n    @abc.abstractmethod\n    def open_binary(self, resource):\n        # type: (str) -> BinaryIO\n        \"\"\"\n        Obtain a File-like for a named resource.\n        \"\"\"\n\n    @property\n    def name(self):\n        return self.package.split('.')[-1]\n\n\nclass ResourceHandle(Traversable):\n    \"\"\"\n    Handle to a named resource in a ResourceReader.\n    \"\"\"\n\n    def __init__(self, parent, name):\n        # type: (ResourceContainer, str) -> None\n        self.parent = parent\n        self.name = name  # type: ignore\n\n    def is_file(self):\n        return True\n\n    def is_dir(self):\n        return False\n\n    def open(self, mode='r', *args, **kwargs):\n        stream = self.parent.reader.open_binary(self.name)\n        if 'b' not in mode:\n            stream = io.TextIOWrapper(*args, **kwargs)\n        return stream\n\n    def joinpath(self, name):\n        raise RuntimeError(\"Cannot traverse into a resource\")\n\n\nclass ResourceContainer(Traversable):\n    \"\"\"\n    Traversable container for a package's resources via its reader.\n    \"\"\"\n\n    def __init__(self, reader):\n        # type: (SimpleReader) -> None\n        self.reader = reader\n\n    def is_dir(self):\n        return True\n\n    def is_file(self):\n        return False\n\n    def iterdir(self):\n        files = (ResourceHandle(self, name) for name in self.reader.resources)\n        dirs = map(ResourceContainer, self.reader.children())\n        return itertools.chain(files, dirs)\n\n    def open(self, *args, **kwargs):\n        raise IsADirectoryError()\n\n    def joinpath(self, name):\n        return next(\n            traversable for traversable in self.iterdir() if traversable.name == name\n        )\n\n\nclass TraversableReader(TraversableResources, SimpleReader):\n    \"\"\"\n    A TraversableResources based on SimpleReader. Resource providers\n    may derive from this class to provide the TraversableResources\n    interface by supplying the SimpleReader interface.\n    \"\"\"\n\n    def files(self):\n        return ResourceContainer(self)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/jaraco/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/jaraco/context.py",
    "content": "import os\nimport subprocess\nimport contextlib\nimport functools\nimport tempfile\nimport shutil\nimport operator\n\n\n@contextlib.contextmanager\ndef pushd(dir):\n    orig = os.getcwd()\n    os.chdir(dir)\n    try:\n        yield dir\n    finally:\n        os.chdir(orig)\n\n\n@contextlib.contextmanager\ndef tarball_context(url, target_dir=None, runner=None, pushd=pushd):\n    \"\"\"\n    Get a tarball, extract it, change to that directory, yield, then\n    clean up.\n    `runner` is the function to invoke commands.\n    `pushd` is a context manager for changing the directory.\n    \"\"\"\n    if target_dir is None:\n        target_dir = os.path.basename(url).replace('.tar.gz', '').replace('.tgz', '')\n    if runner is None:\n        runner = functools.partial(subprocess.check_call, shell=True)\n    # In the tar command, use --strip-components=1 to strip the first path and\n    #  then\n    #  use -C to cause the files to be extracted to {target_dir}. This ensures\n    #  that we always know where the files were extracted.\n    runner('mkdir {target_dir}'.format(**vars()))\n    try:\n        getter = 'wget {url} -O -'\n        extract = 'tar x{compression} --strip-components=1 -C {target_dir}'\n        cmd = ' | '.join((getter, extract))\n        runner(cmd.format(compression=infer_compression(url), **vars()))\n        with pushd(target_dir):\n            yield target_dir\n    finally:\n        runner('rm -Rf {target_dir}'.format(**vars()))\n\n\ndef infer_compression(url):\n    \"\"\"\n    Given a URL or filename, infer the compression code for tar.\n    \"\"\"\n    # cheat and just assume it's the last two characters\n    compression_indicator = url[-2:]\n    mapping = dict(gz='z', bz='j', xz='J')\n    # Assume 'z' (gzip) if no match\n    return mapping.get(compression_indicator, 'z')\n\n\n@contextlib.contextmanager\ndef temp_dir(remover=shutil.rmtree):\n    \"\"\"\n    Create a temporary directory context. Pass a custom remover\n    to override the removal behavior.\n    \"\"\"\n    temp_dir = tempfile.mkdtemp()\n    try:\n        yield temp_dir\n    finally:\n        remover(temp_dir)\n\n\n@contextlib.contextmanager\ndef repo_context(url, branch=None, quiet=True, dest_ctx=temp_dir):\n    \"\"\"\n    Check out the repo indicated by url.\n\n    If dest_ctx is supplied, it should be a context manager\n    to yield the target directory for the check out.\n    \"\"\"\n    exe = 'git' if 'git' in url else 'hg'\n    with dest_ctx() as repo_dir:\n        cmd = [exe, 'clone', url, repo_dir]\n        if branch:\n            cmd.extend(['--branch', branch])\n        devnull = open(os.path.devnull, 'w')\n        stdout = devnull if quiet else None\n        subprocess.check_call(cmd, stdout=stdout)\n        yield repo_dir\n\n\n@contextlib.contextmanager\ndef null():\n    yield\n\n\nclass ExceptionTrap:\n    \"\"\"\n    A context manager that will catch certain exceptions and provide an\n    indication they occurred.\n\n    >>> with ExceptionTrap() as trap:\n    ...     raise Exception()\n    >>> bool(trap)\n    True\n\n    >>> with ExceptionTrap() as trap:\n    ...     pass\n    >>> bool(trap)\n    False\n\n    >>> with ExceptionTrap(ValueError) as trap:\n    ...     raise ValueError(\"1 + 1 is not 3\")\n    >>> bool(trap)\n    True\n\n    >>> with ExceptionTrap(ValueError) as trap:\n    ...     raise Exception()\n    Traceback (most recent call last):\n    ...\n    Exception\n\n    >>> bool(trap)\n    False\n    \"\"\"\n\n    exc_info = None, None, None\n\n    def __init__(self, exceptions=(Exception,)):\n        self.exceptions = exceptions\n\n    def __enter__(self):\n        return self\n\n    @property\n    def type(self):\n        return self.exc_info[0]\n\n    @property\n    def value(self):\n        return self.exc_info[1]\n\n    @property\n    def tb(self):\n        return self.exc_info[2]\n\n    def __exit__(self, *exc_info):\n        type = exc_info[0]\n        matches = type and issubclass(type, self.exceptions)\n        if matches:\n            self.exc_info = exc_info\n        return matches\n\n    def __bool__(self):\n        return bool(self.type)\n\n    def raises(self, func, *, _test=bool):\n        \"\"\"\n        Wrap func and replace the result with the truth\n        value of the trap (True if an exception occurred).\n\n        First, give the decorator an alias to support Python 3.8\n        Syntax.\n\n        >>> raises = ExceptionTrap(ValueError).raises\n\n        Now decorate a function that always fails.\n\n        >>> @raises\n        ... def fail():\n        ...     raise ValueError('failed')\n        >>> fail()\n        True\n        \"\"\"\n\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            with ExceptionTrap(self.exceptions) as trap:\n                func(*args, **kwargs)\n            return _test(trap)\n\n        return wrapper\n\n    def passes(self, func):\n        \"\"\"\n        Wrap func and replace the result with the truth\n        value of the trap (True if no exception).\n\n        First, give the decorator an alias to support Python 3.8\n        Syntax.\n\n        >>> passes = ExceptionTrap(ValueError).passes\n\n        Now decorate a function that always fails.\n\n        >>> @passes\n        ... def fail():\n        ...     raise ValueError('failed')\n\n        >>> fail()\n        False\n        \"\"\"\n        return self.raises(func, _test=operator.not_)\n\n\nclass suppress(contextlib.suppress, contextlib.ContextDecorator):\n    \"\"\"\n    A version of contextlib.suppress with decorator support.\n\n    >>> @suppress(KeyError)\n    ... def key_error():\n    ...     {}['']\n    >>> key_error()\n    \"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/jaraco/functools.py",
    "content": "import functools\nimport time\nimport inspect\nimport collections\nimport types\nimport itertools\n\nimport setuptools.extern.more_itertools\n\nfrom typing import Callable, TypeVar\n\n\nCallableT = TypeVar(\"CallableT\", bound=Callable[..., object])\n\n\ndef compose(*funcs):\n    \"\"\"\n    Compose any number of unary functions into a single unary function.\n\n    >>> import textwrap\n    >>> expected = str.strip(textwrap.dedent(compose.__doc__))\n    >>> strip_and_dedent = compose(str.strip, textwrap.dedent)\n    >>> strip_and_dedent(compose.__doc__) == expected\n    True\n\n    Compose also allows the innermost function to take arbitrary arguments.\n\n    >>> round_three = lambda x: round(x, ndigits=3)\n    >>> f = compose(round_three, int.__truediv__)\n    >>> [f(3*x, x+1) for x in range(1,10)]\n    [1.5, 2.0, 2.25, 2.4, 2.5, 2.571, 2.625, 2.667, 2.7]\n    \"\"\"\n\n    def compose_two(f1, f2):\n        return lambda *args, **kwargs: f1(f2(*args, **kwargs))\n\n    return functools.reduce(compose_two, funcs)\n\n\ndef method_caller(method_name, *args, **kwargs):\n    \"\"\"\n    Return a function that will call a named method on the\n    target object with optional positional and keyword\n    arguments.\n\n    >>> lower = method_caller('lower')\n    >>> lower('MyString')\n    'mystring'\n    \"\"\"\n\n    def call_method(target):\n        func = getattr(target, method_name)\n        return func(*args, **kwargs)\n\n    return call_method\n\n\ndef once(func):\n    \"\"\"\n    Decorate func so it's only ever called the first time.\n\n    This decorator can ensure that an expensive or non-idempotent function\n    will not be expensive on subsequent calls and is idempotent.\n\n    >>> add_three = once(lambda a: a+3)\n    >>> add_three(3)\n    6\n    >>> add_three(9)\n    6\n    >>> add_three('12')\n    6\n\n    To reset the stored value, simply clear the property ``saved_result``.\n\n    >>> del add_three.saved_result\n    >>> add_three(9)\n    12\n    >>> add_three(8)\n    12\n\n    Or invoke 'reset()' on it.\n\n    >>> add_three.reset()\n    >>> add_three(-3)\n    0\n    >>> add_three(0)\n    0\n    \"\"\"\n\n    @functools.wraps(func)\n    def wrapper(*args, **kwargs):\n        if not hasattr(wrapper, 'saved_result'):\n            wrapper.saved_result = func(*args, **kwargs)\n        return wrapper.saved_result\n\n    wrapper.reset = lambda: vars(wrapper).__delitem__('saved_result')\n    return wrapper\n\n\ndef method_cache(\n    method: CallableT,\n    cache_wrapper: Callable[\n        [CallableT], CallableT\n    ] = functools.lru_cache(),  # type: ignore[assignment]\n) -> CallableT:\n    \"\"\"\n    Wrap lru_cache to support storing the cache data in the object instances.\n\n    Abstracts the common paradigm where the method explicitly saves an\n    underscore-prefixed protected property on first call and returns that\n    subsequently.\n\n    >>> class MyClass:\n    ...     calls = 0\n    ...\n    ...     @method_cache\n    ...     def method(self, value):\n    ...         self.calls += 1\n    ...         return value\n\n    >>> a = MyClass()\n    >>> a.method(3)\n    3\n    >>> for x in range(75):\n    ...     res = a.method(x)\n    >>> a.calls\n    75\n\n    Note that the apparent behavior will be exactly like that of lru_cache\n    except that the cache is stored on each instance, so values in one\n    instance will not flush values from another, and when an instance is\n    deleted, so are the cached values for that instance.\n\n    >>> b = MyClass()\n    >>> for x in range(35):\n    ...     res = b.method(x)\n    >>> b.calls\n    35\n    >>> a.method(0)\n    0\n    >>> a.calls\n    75\n\n    Note that if method had been decorated with ``functools.lru_cache()``,\n    a.calls would have been 76 (due to the cached value of 0 having been\n    flushed by the 'b' instance).\n\n    Clear the cache with ``.cache_clear()``\n\n    >>> a.method.cache_clear()\n\n    Same for a method that hasn't yet been called.\n\n    >>> c = MyClass()\n    >>> c.method.cache_clear()\n\n    Another cache wrapper may be supplied:\n\n    >>> cache = functools.lru_cache(maxsize=2)\n    >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache)\n    >>> a = MyClass()\n    >>> a.method2()\n    3\n\n    Caution - do not subsequently wrap the method with another decorator, such\n    as ``@property``, which changes the semantics of the function.\n\n    See also\n    http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/\n    for another implementation and additional justification.\n    \"\"\"\n\n    def wrapper(self: object, *args: object, **kwargs: object) -> object:\n        # it's the first call, replace the method with a cached, bound method\n        bound_method: CallableT = types.MethodType(  # type: ignore[assignment]\n            method, self\n        )\n        cached_method = cache_wrapper(bound_method)\n        setattr(self, method.__name__, cached_method)\n        return cached_method(*args, **kwargs)\n\n    # Support cache clear even before cache has been created.\n    wrapper.cache_clear = lambda: None  # type: ignore[attr-defined]\n\n    return (  # type: ignore[return-value]\n        _special_method_cache(method, cache_wrapper) or wrapper\n    )\n\n\ndef _special_method_cache(method, cache_wrapper):\n    \"\"\"\n    Because Python treats special methods differently, it's not\n    possible to use instance attributes to implement the cached\n    methods.\n\n    Instead, install the wrapper method under a different name\n    and return a simple proxy to that wrapper.\n\n    https://github.com/jaraco/jaraco.functools/issues/5\n    \"\"\"\n    name = method.__name__\n    special_names = '__getattr__', '__getitem__'\n    if name not in special_names:\n        return\n\n    wrapper_name = '__cached' + name\n\n    def proxy(self, *args, **kwargs):\n        if wrapper_name not in vars(self):\n            bound = types.MethodType(method, self)\n            cache = cache_wrapper(bound)\n            setattr(self, wrapper_name, cache)\n        else:\n            cache = getattr(self, wrapper_name)\n        return cache(*args, **kwargs)\n\n    return proxy\n\n\ndef apply(transform):\n    \"\"\"\n    Decorate a function with a transform function that is\n    invoked on results returned from the decorated function.\n\n    >>> @apply(reversed)\n    ... def get_numbers(start):\n    ...     \"doc for get_numbers\"\n    ...     return range(start, start+3)\n    >>> list(get_numbers(4))\n    [6, 5, 4]\n    >>> get_numbers.__doc__\n    'doc for get_numbers'\n    \"\"\"\n\n    def wrap(func):\n        return functools.wraps(func)(compose(transform, func))\n\n    return wrap\n\n\ndef result_invoke(action):\n    r\"\"\"\n    Decorate a function with an action function that is\n    invoked on the results returned from the decorated\n    function (for its side-effect), then return the original\n    result.\n\n    >>> @result_invoke(print)\n    ... def add_two(a, b):\n    ...     return a + b\n    >>> x = add_two(2, 3)\n    5\n    >>> x\n    5\n    \"\"\"\n\n    def wrap(func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            result = func(*args, **kwargs)\n            action(result)\n            return result\n\n        return wrapper\n\n    return wrap\n\n\ndef call_aside(f, *args, **kwargs):\n    \"\"\"\n    Call a function for its side effect after initialization.\n\n    >>> @call_aside\n    ... def func(): print(\"called\")\n    called\n    >>> func()\n    called\n\n    Use functools.partial to pass parameters to the initial call\n\n    >>> @functools.partial(call_aside, name='bingo')\n    ... def func(name): print(\"called with\", name)\n    called with bingo\n    \"\"\"\n    f(*args, **kwargs)\n    return f\n\n\nclass Throttler:\n    \"\"\"\n    Rate-limit a function (or other callable)\n    \"\"\"\n\n    def __init__(self, func, max_rate=float('Inf')):\n        if isinstance(func, Throttler):\n            func = func.func\n        self.func = func\n        self.max_rate = max_rate\n        self.reset()\n\n    def reset(self):\n        self.last_called = 0\n\n    def __call__(self, *args, **kwargs):\n        self._wait()\n        return self.func(*args, **kwargs)\n\n    def _wait(self):\n        \"ensure at least 1/max_rate seconds from last call\"\n        elapsed = time.time() - self.last_called\n        must_wait = 1 / self.max_rate - elapsed\n        time.sleep(max(0, must_wait))\n        self.last_called = time.time()\n\n    def __get__(self, obj, type=None):\n        return first_invoke(self._wait, functools.partial(self.func, obj))\n\n\ndef first_invoke(func1, func2):\n    \"\"\"\n    Return a function that when invoked will invoke func1 without\n    any parameters (for its side-effect) and then invoke func2\n    with whatever parameters were passed, returning its result.\n    \"\"\"\n\n    def wrapper(*args, **kwargs):\n        func1()\n        return func2(*args, **kwargs)\n\n    return wrapper\n\n\ndef retry_call(func, cleanup=lambda: None, retries=0, trap=()):\n    \"\"\"\n    Given a callable func, trap the indicated exceptions\n    for up to 'retries' times, invoking cleanup on the\n    exception. On the final attempt, allow any exceptions\n    to propagate.\n    \"\"\"\n    attempts = itertools.count() if retries == float('inf') else range(retries)\n    for attempt in attempts:\n        try:\n            return func()\n        except trap:\n            cleanup()\n\n    return func()\n\n\ndef retry(*r_args, **r_kwargs):\n    \"\"\"\n    Decorator wrapper for retry_call. Accepts arguments to retry_call\n    except func and then returns a decorator for the decorated function.\n\n    Ex:\n\n    >>> @retry(retries=3)\n    ... def my_func(a, b):\n    ...     \"this is my funk\"\n    ...     print(a, b)\n    >>> my_func.__doc__\n    'this is my funk'\n    \"\"\"\n\n    def decorate(func):\n        @functools.wraps(func)\n        def wrapper(*f_args, **f_kwargs):\n            bound = functools.partial(func, *f_args, **f_kwargs)\n            return retry_call(bound, *r_args, **r_kwargs)\n\n        return wrapper\n\n    return decorate\n\n\ndef print_yielded(func):\n    \"\"\"\n    Convert a generator into a function that prints all yielded elements\n\n    >>> @print_yielded\n    ... def x():\n    ...     yield 3; yield None\n    >>> x()\n    3\n    None\n    \"\"\"\n    print_all = functools.partial(map, print)\n    print_results = compose(more_itertools.consume, print_all, func)\n    return functools.wraps(func)(print_results)\n\n\ndef pass_none(func):\n    \"\"\"\n    Wrap func so it's not called if its first param is None\n\n    >>> print_text = pass_none(print)\n    >>> print_text('text')\n    text\n    >>> print_text(None)\n    \"\"\"\n\n    @functools.wraps(func)\n    def wrapper(param, *args, **kwargs):\n        if param is not None:\n            return func(param, *args, **kwargs)\n\n    return wrapper\n\n\ndef assign_params(func, namespace):\n    \"\"\"\n    Assign parameters from namespace where func solicits.\n\n    >>> def func(x, y=3):\n    ...     print(x, y)\n    >>> assigned = assign_params(func, dict(x=2, z=4))\n    >>> assigned()\n    2 3\n\n    The usual errors are raised if a function doesn't receive\n    its required parameters:\n\n    >>> assigned = assign_params(func, dict(y=3, z=4))\n    >>> assigned()\n    Traceback (most recent call last):\n    TypeError: func() ...argument...\n\n    It even works on methods:\n\n    >>> class Handler:\n    ...     def meth(self, arg):\n    ...         print(arg)\n    >>> assign_params(Handler().meth, dict(arg='crystal', foo='clear'))()\n    crystal\n    \"\"\"\n    sig = inspect.signature(func)\n    params = sig.parameters.keys()\n    call_ns = {k: namespace[k] for k in params if k in namespace}\n    return functools.partial(func, **call_ns)\n\n\ndef save_method_args(method):\n    \"\"\"\n    Wrap a method such that when it is called, the args and kwargs are\n    saved on the method.\n\n    >>> class MyClass:\n    ...     @save_method_args\n    ...     def method(self, a, b):\n    ...         print(a, b)\n    >>> my_ob = MyClass()\n    >>> my_ob.method(1, 2)\n    1 2\n    >>> my_ob._saved_method.args\n    (1, 2)\n    >>> my_ob._saved_method.kwargs\n    {}\n    >>> my_ob.method(a=3, b='foo')\n    3 foo\n    >>> my_ob._saved_method.args\n    ()\n    >>> my_ob._saved_method.kwargs == dict(a=3, b='foo')\n    True\n\n    The arguments are stored on the instance, allowing for\n    different instance to save different args.\n\n    >>> your_ob = MyClass()\n    >>> your_ob.method({str('x'): 3}, b=[4])\n    {'x': 3} [4]\n    >>> your_ob._saved_method.args\n    ({'x': 3},)\n    >>> my_ob._saved_method.args\n    ()\n    \"\"\"\n    args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs')\n\n    @functools.wraps(method)\n    def wrapper(self, *args, **kwargs):\n        attr_name = '_saved_' + method.__name__\n        attr = args_and_kwargs(args, kwargs)\n        setattr(self, attr_name, attr)\n        return method(self, *args, **kwargs)\n\n    return wrapper\n\n\ndef except_(*exceptions, replace=None, use=None):\n    \"\"\"\n    Replace the indicated exceptions, if raised, with the indicated\n    literal replacement or evaluated expression (if present).\n\n    >>> safe_int = except_(ValueError)(int)\n    >>> safe_int('five')\n    >>> safe_int('5')\n    5\n\n    Specify a literal replacement with ``replace``.\n\n    >>> safe_int_r = except_(ValueError, replace=0)(int)\n    >>> safe_int_r('five')\n    0\n\n    Provide an expression to ``use`` to pass through particular parameters.\n\n    >>> safe_int_pt = except_(ValueError, use='args[0]')(int)\n    >>> safe_int_pt('five')\n    'five'\n\n    \"\"\"\n\n    def decorate(func):\n        @functools.wraps(func)\n        def wrapper(*args, **kwargs):\n            try:\n                return func(*args, **kwargs)\n            except exceptions:\n                try:\n                    return eval(use)\n                except TypeError:\n                    return replace\n\n        return wrapper\n\n    return decorate\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/jaraco/text/__init__.py",
    "content": "import re\nimport itertools\nimport textwrap\nimport functools\n\ntry:\n    from importlib.resources import files  # type: ignore\nexcept ImportError:  # pragma: nocover\n    from setuptools.extern.importlib_resources import files  # type: ignore\n\nfrom setuptools.extern.jaraco.functools import compose, method_cache\nfrom setuptools.extern.jaraco.context import ExceptionTrap\n\n\ndef substitution(old, new):\n    \"\"\"\n    Return a function that will perform a substitution on a string\n    \"\"\"\n    return lambda s: s.replace(old, new)\n\n\ndef multi_substitution(*substitutions):\n    \"\"\"\n    Take a sequence of pairs specifying substitutions, and create\n    a function that performs those substitutions.\n\n    >>> multi_substitution(('foo', 'bar'), ('bar', 'baz'))('foo')\n    'baz'\n    \"\"\"\n    substitutions = itertools.starmap(substitution, substitutions)\n    # compose function applies last function first, so reverse the\n    #  substitutions to get the expected order.\n    substitutions = reversed(tuple(substitutions))\n    return compose(*substitutions)\n\n\nclass FoldedCase(str):\n    \"\"\"\n    A case insensitive string class; behaves just like str\n    except compares equal when the only variation is case.\n\n    >>> s = FoldedCase('hello world')\n\n    >>> s == 'Hello World'\n    True\n\n    >>> 'Hello World' == s\n    True\n\n    >>> s != 'Hello World'\n    False\n\n    >>> s.index('O')\n    4\n\n    >>> s.split('O')\n    ['hell', ' w', 'rld']\n\n    >>> sorted(map(FoldedCase, ['GAMMA', 'alpha', 'Beta']))\n    ['alpha', 'Beta', 'GAMMA']\n\n    Sequence membership is straightforward.\n\n    >>> \"Hello World\" in [s]\n    True\n    >>> s in [\"Hello World\"]\n    True\n\n    You may test for set inclusion, but candidate and elements\n    must both be folded.\n\n    >>> FoldedCase(\"Hello World\") in {s}\n    True\n    >>> s in {FoldedCase(\"Hello World\")}\n    True\n\n    String inclusion works as long as the FoldedCase object\n    is on the right.\n\n    >>> \"hello\" in FoldedCase(\"Hello World\")\n    True\n\n    But not if the FoldedCase object is on the left:\n\n    >>> FoldedCase('hello') in 'Hello World'\n    False\n\n    In that case, use ``in_``:\n\n    >>> FoldedCase('hello').in_('Hello World')\n    True\n\n    >>> FoldedCase('hello') > FoldedCase('Hello')\n    False\n    \"\"\"\n\n    def __lt__(self, other):\n        return self.lower() < other.lower()\n\n    def __gt__(self, other):\n        return self.lower() > other.lower()\n\n    def __eq__(self, other):\n        return self.lower() == other.lower()\n\n    def __ne__(self, other):\n        return self.lower() != other.lower()\n\n    def __hash__(self):\n        return hash(self.lower())\n\n    def __contains__(self, other):\n        return super().lower().__contains__(other.lower())\n\n    def in_(self, other):\n        \"Does self appear in other?\"\n        return self in FoldedCase(other)\n\n    # cache lower since it's likely to be called frequently.\n    @method_cache\n    def lower(self):\n        return super().lower()\n\n    def index(self, sub):\n        return self.lower().index(sub.lower())\n\n    def split(self, splitter=' ', maxsplit=0):\n        pattern = re.compile(re.escape(splitter), re.I)\n        return pattern.split(self, maxsplit)\n\n\n# Python 3.8 compatibility\n_unicode_trap = ExceptionTrap(UnicodeDecodeError)\n\n\n@_unicode_trap.passes\ndef is_decodable(value):\n    r\"\"\"\n    Return True if the supplied value is decodable (using the default\n    encoding).\n\n    >>> is_decodable(b'\\xff')\n    False\n    >>> is_decodable(b'\\x32')\n    True\n    \"\"\"\n    value.decode()\n\n\ndef is_binary(value):\n    r\"\"\"\n    Return True if the value appears to be binary (that is, it's a byte\n    string and isn't decodable).\n\n    >>> is_binary(b'\\xff')\n    True\n    >>> is_binary('\\xff')\n    False\n    \"\"\"\n    return isinstance(value, bytes) and not is_decodable(value)\n\n\ndef trim(s):\n    r\"\"\"\n    Trim something like a docstring to remove the whitespace that\n    is common due to indentation and formatting.\n\n    >>> trim(\"\\n\\tfoo = bar\\n\\t\\tbar = baz\\n\")\n    'foo = bar\\n\\tbar = baz'\n    \"\"\"\n    return textwrap.dedent(s).strip()\n\n\ndef wrap(s):\n    \"\"\"\n    Wrap lines of text, retaining existing newlines as\n    paragraph markers.\n\n    >>> print(wrap(lorem_ipsum))\n    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do\n    eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad\n    minim veniam, quis nostrud exercitation ullamco laboris nisi ut\n    aliquip ex ea commodo consequat. Duis aute irure dolor in\n    reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla\n    pariatur. Excepteur sint occaecat cupidatat non proident, sunt in\n    culpa qui officia deserunt mollit anim id est laborum.\n    <BLANKLINE>\n    Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam\n    varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus\n    magna felis sollicitudin mauris. Integer in mauris eu nibh euismod\n    gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis\n    risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue,\n    eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas\n    fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla\n    a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis,\n    neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing\n    sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque\n    nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus\n    quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis,\n    molestie eu, feugiat in, orci. In hac habitasse platea dictumst.\n    \"\"\"\n    paragraphs = s.splitlines()\n    wrapped = ('\\n'.join(textwrap.wrap(para)) for para in paragraphs)\n    return '\\n\\n'.join(wrapped)\n\n\ndef unwrap(s):\n    r\"\"\"\n    Given a multi-line string, return an unwrapped version.\n\n    >>> wrapped = wrap(lorem_ipsum)\n    >>> wrapped.count('\\n')\n    20\n    >>> unwrapped = unwrap(wrapped)\n    >>> unwrapped.count('\\n')\n    1\n    >>> print(unwrapped)\n    Lorem ipsum dolor sit amet, consectetur adipiscing ...\n    Curabitur pretium tincidunt lacus. Nulla gravida orci ...\n\n    \"\"\"\n    paragraphs = re.split(r'\\n\\n+', s)\n    cleaned = (para.replace('\\n', ' ') for para in paragraphs)\n    return '\\n'.join(cleaned)\n\n\n\n\nclass Splitter(object):\n    \"\"\"object that will split a string with the given arguments for each call\n\n    >>> s = Splitter(',')\n    >>> s('hello, world, this is your, master calling')\n    ['hello', ' world', ' this is your', ' master calling']\n    \"\"\"\n\n    def __init__(self, *args):\n        self.args = args\n\n    def __call__(self, s):\n        return s.split(*self.args)\n\n\ndef indent(string, prefix=' ' * 4):\n    \"\"\"\n    >>> indent('foo')\n    '    foo'\n    \"\"\"\n    return prefix + string\n\n\nclass WordSet(tuple):\n    \"\"\"\n    Given an identifier, return the words that identifier represents,\n    whether in camel case, underscore-separated, etc.\n\n    >>> WordSet.parse(\"camelCase\")\n    ('camel', 'Case')\n\n    >>> WordSet.parse(\"under_sep\")\n    ('under', 'sep')\n\n    Acronyms should be retained\n\n    >>> WordSet.parse(\"firstSNL\")\n    ('first', 'SNL')\n\n    >>> WordSet.parse(\"you_and_I\")\n    ('you', 'and', 'I')\n\n    >>> WordSet.parse(\"A simple test\")\n    ('A', 'simple', 'test')\n\n    Multiple caps should not interfere with the first cap of another word.\n\n    >>> WordSet.parse(\"myABCClass\")\n    ('my', 'ABC', 'Class')\n\n    The result is a WordSet, so you can get the form you need.\n\n    >>> WordSet.parse(\"myABCClass\").underscore_separated()\n    'my_ABC_Class'\n\n    >>> WordSet.parse('a-command').camel_case()\n    'ACommand'\n\n    >>> WordSet.parse('someIdentifier').lowered().space_separated()\n    'some identifier'\n\n    Slices of the result should return another WordSet.\n\n    >>> WordSet.parse('taken-out-of-context')[1:].underscore_separated()\n    'out_of_context'\n\n    >>> WordSet.from_class_name(WordSet()).lowered().space_separated()\n    'word set'\n\n    >>> example = WordSet.parse('figured it out')\n    >>> example.headless_camel_case()\n    'figuredItOut'\n    >>> example.dash_separated()\n    'figured-it-out'\n\n    \"\"\"\n\n    _pattern = re.compile('([A-Z]?[a-z]+)|([A-Z]+(?![a-z]))')\n\n    def capitalized(self):\n        return WordSet(word.capitalize() for word in self)\n\n    def lowered(self):\n        return WordSet(word.lower() for word in self)\n\n    def camel_case(self):\n        return ''.join(self.capitalized())\n\n    def headless_camel_case(self):\n        words = iter(self)\n        first = next(words).lower()\n        new_words = itertools.chain((first,), WordSet(words).camel_case())\n        return ''.join(new_words)\n\n    def underscore_separated(self):\n        return '_'.join(self)\n\n    def dash_separated(self):\n        return '-'.join(self)\n\n    def space_separated(self):\n        return ' '.join(self)\n\n    def trim_right(self, item):\n        \"\"\"\n        Remove the item from the end of the set.\n\n        >>> WordSet.parse('foo bar').trim_right('foo')\n        ('foo', 'bar')\n        >>> WordSet.parse('foo bar').trim_right('bar')\n        ('foo',)\n        >>> WordSet.parse('').trim_right('bar')\n        ()\n        \"\"\"\n        return self[:-1] if self and self[-1] == item else self\n\n    def trim_left(self, item):\n        \"\"\"\n        Remove the item from the beginning of the set.\n\n        >>> WordSet.parse('foo bar').trim_left('foo')\n        ('bar',)\n        >>> WordSet.parse('foo bar').trim_left('bar')\n        ('foo', 'bar')\n        >>> WordSet.parse('').trim_left('bar')\n        ()\n        \"\"\"\n        return self[1:] if self and self[0] == item else self\n\n    def trim(self, item):\n        \"\"\"\n        >>> WordSet.parse('foo bar').trim('foo')\n        ('bar',)\n        \"\"\"\n        return self.trim_left(item).trim_right(item)\n\n    def __getitem__(self, item):\n        result = super(WordSet, self).__getitem__(item)\n        if isinstance(item, slice):\n            result = WordSet(result)\n        return result\n\n    @classmethod\n    def parse(cls, identifier):\n        matches = cls._pattern.finditer(identifier)\n        return WordSet(match.group(0) for match in matches)\n\n    @classmethod\n    def from_class_name(cls, subject):\n        return cls.parse(subject.__class__.__name__)\n\n\n# for backward compatibility\nwords = WordSet.parse\n\n\ndef simple_html_strip(s):\n    r\"\"\"\n    Remove HTML from the string `s`.\n\n    >>> str(simple_html_strip(''))\n    ''\n\n    >>> print(simple_html_strip('A <bold>stormy</bold> day in paradise'))\n    A stormy day in paradise\n\n    >>> print(simple_html_strip('Somebody <!-- do not --> tell the truth.'))\n    Somebody  tell the truth.\n\n    >>> print(simple_html_strip('What about<br/>\\nmultiple lines?'))\n    What about\n    multiple lines?\n    \"\"\"\n    html_stripper = re.compile('(<!--.*?-->)|(<[^>]*>)|([^<]+)', re.DOTALL)\n    texts = (match.group(3) or '' for match in html_stripper.finditer(s))\n    return ''.join(texts)\n\n\nclass SeparatedValues(str):\n    \"\"\"\n    A string separated by a separator. Overrides __iter__ for getting\n    the values.\n\n    >>> list(SeparatedValues('a,b,c'))\n    ['a', 'b', 'c']\n\n    Whitespace is stripped and empty values are discarded.\n\n    >>> list(SeparatedValues(' a,   b   , c,  '))\n    ['a', 'b', 'c']\n    \"\"\"\n\n    separator = ','\n\n    def __iter__(self):\n        parts = self.split(self.separator)\n        return filter(None, (part.strip() for part in parts))\n\n\nclass Stripper:\n    r\"\"\"\n    Given a series of lines, find the common prefix and strip it from them.\n\n    >>> lines = [\n    ...     'abcdefg\\n',\n    ...     'abc\\n',\n    ...     'abcde\\n',\n    ... ]\n    >>> res = Stripper.strip_prefix(lines)\n    >>> res.prefix\n    'abc'\n    >>> list(res.lines)\n    ['defg\\n', '\\n', 'de\\n']\n\n    If no prefix is common, nothing should be stripped.\n\n    >>> lines = [\n    ...     'abcd\\n',\n    ...     '1234\\n',\n    ... ]\n    >>> res = Stripper.strip_prefix(lines)\n    >>> res.prefix = ''\n    >>> list(res.lines)\n    ['abcd\\n', '1234\\n']\n    \"\"\"\n\n    def __init__(self, prefix, lines):\n        self.prefix = prefix\n        self.lines = map(self, lines)\n\n    @classmethod\n    def strip_prefix(cls, lines):\n        prefix_lines, lines = itertools.tee(lines)\n        prefix = functools.reduce(cls.common_prefix, prefix_lines)\n        return cls(prefix, lines)\n\n    def __call__(self, line):\n        if not self.prefix:\n            return line\n        null, prefix, rest = line.partition(self.prefix)\n        return rest\n\n    @staticmethod\n    def common_prefix(s1, s2):\n        \"\"\"\n        Return the common prefix of two lines.\n        \"\"\"\n        index = min(len(s1), len(s2))\n        while s1[:index] != s2[:index]:\n            index -= 1\n        return s1[:index]\n\n\ndef remove_prefix(text, prefix):\n    \"\"\"\n    Remove the prefix from the text if it exists.\n\n    >>> remove_prefix('underwhelming performance', 'underwhelming ')\n    'performance'\n\n    >>> remove_prefix('something special', 'sample')\n    'something special'\n    \"\"\"\n    null, prefix, rest = text.rpartition(prefix)\n    return rest\n\n\ndef remove_suffix(text, suffix):\n    \"\"\"\n    Remove the suffix from the text if it exists.\n\n    >>> remove_suffix('name.git', '.git')\n    'name'\n\n    >>> remove_suffix('something special', 'sample')\n    'something special'\n    \"\"\"\n    rest, suffix, null = text.partition(suffix)\n    return rest\n\n\ndef normalize_newlines(text):\n    r\"\"\"\n    Replace alternate newlines with the canonical newline.\n\n    >>> normalize_newlines('Lorem Ipsum\\u2029')\n    'Lorem Ipsum\\n'\n    >>> normalize_newlines('Lorem Ipsum\\r\\n')\n    'Lorem Ipsum\\n'\n    >>> normalize_newlines('Lorem Ipsum\\x85')\n    'Lorem Ipsum\\n'\n    \"\"\"\n    newlines = ['\\r\\n', '\\r', '\\n', '\\u0085', '\\u2028', '\\u2029']\n    pattern = '|'.join(newlines)\n    return re.sub(pattern, '\\n', text)\n\n\ndef _nonblank(str):\n    return str and not str.startswith('#')\n\n\n@functools.singledispatch\ndef yield_lines(iterable):\n    r\"\"\"\n    Yield valid lines of a string or iterable.\n\n    >>> list(yield_lines(''))\n    []\n    >>> list(yield_lines(['foo', 'bar']))\n    ['foo', 'bar']\n    >>> list(yield_lines('foo\\nbar'))\n    ['foo', 'bar']\n    >>> list(yield_lines('\\nfoo\\n#bar\\nbaz #comment'))\n    ['foo', 'baz #comment']\n    >>> list(yield_lines(['foo\\nbar', 'baz', 'bing\\n\\n\\n']))\n    ['foo', 'bar', 'baz', 'bing']\n    \"\"\"\n    return itertools.chain.from_iterable(map(yield_lines, iterable))\n\n\n@yield_lines.register(str)\ndef _(text):\n    return filter(_nonblank, map(str.strip, text.splitlines()))\n\n\ndef drop_comment(line):\n    \"\"\"\n    Drop comments.\n\n    >>> drop_comment('foo # bar')\n    'foo'\n\n    A hash without a space may be in a URL.\n\n    >>> drop_comment('http://example.com/foo#bar')\n    'http://example.com/foo#bar'\n    \"\"\"\n    return line.partition(' #')[0]\n\n\ndef join_continuation(lines):\n    r\"\"\"\n    Join lines continued by a trailing backslash.\n\n    >>> list(join_continuation(['foo \\\\', 'bar', 'baz']))\n    ['foobar', 'baz']\n    >>> list(join_continuation(['foo \\\\', 'bar', 'baz']))\n    ['foobar', 'baz']\n    >>> list(join_continuation(['foo \\\\', 'bar \\\\', 'baz']))\n    ['foobarbaz']\n\n    Not sure why, but...\n    The character preceeding the backslash is also elided.\n\n    >>> list(join_continuation(['goo\\\\', 'dly']))\n    ['godly']\n\n    A terrible idea, but...\n    If no line is available to continue, suppress the lines.\n\n    >>> list(join_continuation(['foo', 'bar\\\\', 'baz\\\\']))\n    ['foo']\n    \"\"\"\n    lines = iter(lines)\n    for item in lines:\n        while item.endswith('\\\\'):\n            try:\n                item = item[:-2].strip() + next(lines)\n            except StopIteration:\n                return\n        yield item\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/more_itertools/__init__.py",
    "content": "from .more import *  # noqa\nfrom .recipes import *  # noqa\n\n__version__ = '8.8.0'\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/more_itertools/more.py",
    "content": "import warnings\n\nfrom collections import Counter, defaultdict, deque, abc\nfrom collections.abc import Sequence\nfrom functools import partial, reduce, wraps\nfrom heapq import merge, heapify, heapreplace, heappop\nfrom itertools import (\n    chain,\n    compress,\n    count,\n    cycle,\n    dropwhile,\n    groupby,\n    islice,\n    repeat,\n    starmap,\n    takewhile,\n    tee,\n    zip_longest,\n)\nfrom math import exp, factorial, floor, log\nfrom queue import Empty, Queue\nfrom random import random, randrange, uniform\nfrom operator import itemgetter, mul, sub, gt, lt\nfrom sys import hexversion, maxsize\nfrom time import monotonic\n\nfrom .recipes import (\n    consume,\n    flatten,\n    pairwise,\n    powerset,\n    take,\n    unique_everseen,\n)\n\n__all__ = [\n    'AbortThread',\n    'adjacent',\n    'always_iterable',\n    'always_reversible',\n    'bucket',\n    'callback_iter',\n    'chunked',\n    'circular_shifts',\n    'collapse',\n    'collate',\n    'consecutive_groups',\n    'consumer',\n    'countable',\n    'count_cycle',\n    'mark_ends',\n    'difference',\n    'distinct_combinations',\n    'distinct_permutations',\n    'distribute',\n    'divide',\n    'exactly_n',\n    'filter_except',\n    'first',\n    'groupby_transform',\n    'ilen',\n    'interleave_longest',\n    'interleave',\n    'intersperse',\n    'islice_extended',\n    'iterate',\n    'ichunked',\n    'is_sorted',\n    'last',\n    'locate',\n    'lstrip',\n    'make_decorator',\n    'map_except',\n    'map_reduce',\n    'nth_or_last',\n    'nth_permutation',\n    'nth_product',\n    'numeric_range',\n    'one',\n    'only',\n    'padded',\n    'partitions',\n    'set_partitions',\n    'peekable',\n    'repeat_last',\n    'replace',\n    'rlocate',\n    'rstrip',\n    'run_length',\n    'sample',\n    'seekable',\n    'SequenceView',\n    'side_effect',\n    'sliced',\n    'sort_together',\n    'split_at',\n    'split_after',\n    'split_before',\n    'split_when',\n    'split_into',\n    'spy',\n    'stagger',\n    'strip',\n    'substrings',\n    'substrings_indexes',\n    'time_limited',\n    'unique_to_each',\n    'unzip',\n    'windowed',\n    'with_iter',\n    'UnequalIterablesError',\n    'zip_equal',\n    'zip_offset',\n    'windowed_complete',\n    'all_unique',\n    'value_chain',\n    'product_index',\n    'combination_index',\n    'permutation_index',\n]\n\n_marker = object()\n\n\ndef chunked(iterable, n, strict=False):\n    \"\"\"Break *iterable* into lists of length *n*:\n\n        >>> list(chunked([1, 2, 3, 4, 5, 6], 3))\n        [[1, 2, 3], [4, 5, 6]]\n\n    By the default, the last yielded list will have fewer than *n* elements\n    if the length of *iterable* is not divisible by *n*:\n\n        >>> list(chunked([1, 2, 3, 4, 5, 6, 7, 8], 3))\n        [[1, 2, 3], [4, 5, 6], [7, 8]]\n\n    To use a fill-in value instead, see the :func:`grouper` recipe.\n\n    If the length of *iterable* is not divisible by *n* and *strict* is\n    ``True``, then ``ValueError`` will be raised before the last\n    list is yielded.\n\n    \"\"\"\n    iterator = iter(partial(take, n, iter(iterable)), [])\n    if strict:\n\n        def ret():\n            for chunk in iterator:\n                if len(chunk) != n:\n                    raise ValueError('iterable is not divisible by n.')\n                yield chunk\n\n        return iter(ret())\n    else:\n        return iterator\n\n\ndef first(iterable, default=_marker):\n    \"\"\"Return the first item of *iterable*, or *default* if *iterable* is\n    empty.\n\n        >>> first([0, 1, 2, 3])\n        0\n        >>> first([], 'some default')\n        'some default'\n\n    If *default* is not provided and there are no items in the iterable,\n    raise ``ValueError``.\n\n    :func:`first` is useful when you have a generator of expensive-to-retrieve\n    values and want any arbitrary one. It is marginally shorter than\n    ``next(iter(iterable), default)``.\n\n    \"\"\"\n    try:\n        return next(iter(iterable))\n    except StopIteration as e:\n        if default is _marker:\n            raise ValueError(\n                'first() was called on an empty iterable, and no '\n                'default value was provided.'\n            ) from e\n        return default\n\n\ndef last(iterable, default=_marker):\n    \"\"\"Return the last item of *iterable*, or *default* if *iterable* is\n    empty.\n\n        >>> last([0, 1, 2, 3])\n        3\n        >>> last([], 'some default')\n        'some default'\n\n    If *default* is not provided and there are no items in the iterable,\n    raise ``ValueError``.\n    \"\"\"\n    try:\n        if isinstance(iterable, Sequence):\n            return iterable[-1]\n        # Work around https://bugs.python.org/issue38525\n        elif hasattr(iterable, '__reversed__') and (hexversion != 0x030800F0):\n            return next(reversed(iterable))\n        else:\n            return deque(iterable, maxlen=1)[-1]\n    except (IndexError, TypeError, StopIteration):\n        if default is _marker:\n            raise ValueError(\n                'last() was called on an empty iterable, and no default was '\n                'provided.'\n            )\n        return default\n\n\ndef nth_or_last(iterable, n, default=_marker):\n    \"\"\"Return the nth or the last item of *iterable*,\n    or *default* if *iterable* is empty.\n\n        >>> nth_or_last([0, 1, 2, 3], 2)\n        2\n        >>> nth_or_last([0, 1], 2)\n        1\n        >>> nth_or_last([], 0, 'some default')\n        'some default'\n\n    If *default* is not provided and there are no items in the iterable,\n    raise ``ValueError``.\n    \"\"\"\n    return last(islice(iterable, n + 1), default=default)\n\n\nclass peekable:\n    \"\"\"Wrap an iterator to allow lookahead and prepending elements.\n\n    Call :meth:`peek` on the result to get the value that will be returned\n    by :func:`next`. This won't advance the iterator:\n\n        >>> p = peekable(['a', 'b'])\n        >>> p.peek()\n        'a'\n        >>> next(p)\n        'a'\n\n    Pass :meth:`peek` a default value to return that instead of raising\n    ``StopIteration`` when the iterator is exhausted.\n\n        >>> p = peekable([])\n        >>> p.peek('hi')\n        'hi'\n\n    peekables also offer a :meth:`prepend` method, which \"inserts\" items\n    at the head of the iterable:\n\n        >>> p = peekable([1, 2, 3])\n        >>> p.prepend(10, 11, 12)\n        >>> next(p)\n        10\n        >>> p.peek()\n        11\n        >>> list(p)\n        [11, 12, 1, 2, 3]\n\n    peekables can be indexed. Index 0 is the item that will be returned by\n    :func:`next`, index 1 is the item after that, and so on:\n    The values up to the given index will be cached.\n\n        >>> p = peekable(['a', 'b', 'c', 'd'])\n        >>> p[0]\n        'a'\n        >>> p[1]\n        'b'\n        >>> next(p)\n        'a'\n\n    Negative indexes are supported, but be aware that they will cache the\n    remaining items in the source iterator, which may require significant\n    storage.\n\n    To check whether a peekable is exhausted, check its truth value:\n\n        >>> p = peekable(['a', 'b'])\n        >>> if p:  # peekable has items\n        ...     list(p)\n        ['a', 'b']\n        >>> if not p:  # peekable is exhausted\n        ...     list(p)\n        []\n\n    \"\"\"\n\n    def __init__(self, iterable):\n        self._it = iter(iterable)\n        self._cache = deque()\n\n    def __iter__(self):\n        return self\n\n    def __bool__(self):\n        try:\n            self.peek()\n        except StopIteration:\n            return False\n        return True\n\n    def peek(self, default=_marker):\n        \"\"\"Return the item that will be next returned from ``next()``.\n\n        Return ``default`` if there are no items left. If ``default`` is not\n        provided, raise ``StopIteration``.\n\n        \"\"\"\n        if not self._cache:\n            try:\n                self._cache.append(next(self._it))\n            except StopIteration:\n                if default is _marker:\n                    raise\n                return default\n        return self._cache[0]\n\n    def prepend(self, *items):\n        \"\"\"Stack up items to be the next ones returned from ``next()`` or\n        ``self.peek()``. The items will be returned in\n        first in, first out order::\n\n            >>> p = peekable([1, 2, 3])\n            >>> p.prepend(10, 11, 12)\n            >>> next(p)\n            10\n            >>> list(p)\n            [11, 12, 1, 2, 3]\n\n        It is possible, by prepending items, to \"resurrect\" a peekable that\n        previously raised ``StopIteration``.\n\n            >>> p = peekable([])\n            >>> next(p)\n            Traceback (most recent call last):\n              ...\n            StopIteration\n            >>> p.prepend(1)\n            >>> next(p)\n            1\n            >>> next(p)\n            Traceback (most recent call last):\n              ...\n            StopIteration\n\n        \"\"\"\n        self._cache.extendleft(reversed(items))\n\n    def __next__(self):\n        if self._cache:\n            return self._cache.popleft()\n\n        return next(self._it)\n\n    def _get_slice(self, index):\n        # Normalize the slice's arguments\n        step = 1 if (index.step is None) else index.step\n        if step > 0:\n            start = 0 if (index.start is None) else index.start\n            stop = maxsize if (index.stop is None) else index.stop\n        elif step < 0:\n            start = -1 if (index.start is None) else index.start\n            stop = (-maxsize - 1) if (index.stop is None) else index.stop\n        else:\n            raise ValueError('slice step cannot be zero')\n\n        # If either the start or stop index is negative, we'll need to cache\n        # the rest of the iterable in order to slice from the right side.\n        if (start < 0) or (stop < 0):\n            self._cache.extend(self._it)\n        # Otherwise we'll need to find the rightmost index and cache to that\n        # point.\n        else:\n            n = min(max(start, stop) + 1, maxsize)\n            cache_len = len(self._cache)\n            if n >= cache_len:\n                self._cache.extend(islice(self._it, n - cache_len))\n\n        return list(self._cache)[index]\n\n    def __getitem__(self, index):\n        if isinstance(index, slice):\n            return self._get_slice(index)\n\n        cache_len = len(self._cache)\n        if index < 0:\n            self._cache.extend(self._it)\n        elif index >= cache_len:\n            self._cache.extend(islice(self._it, index + 1 - cache_len))\n\n        return self._cache[index]\n\n\ndef collate(*iterables, **kwargs):\n    \"\"\"Return a sorted merge of the items from each of several already-sorted\n    *iterables*.\n\n        >>> list(collate('ACDZ', 'AZ', 'JKL'))\n        ['A', 'A', 'C', 'D', 'J', 'K', 'L', 'Z', 'Z']\n\n    Works lazily, keeping only the next value from each iterable in memory. Use\n    :func:`collate` to, for example, perform a n-way mergesort of items that\n    don't fit in memory.\n\n    If a *key* function is specified, the iterables will be sorted according\n    to its result:\n\n        >>> key = lambda s: int(s)  # Sort by numeric value, not by string\n        >>> list(collate(['1', '10'], ['2', '11'], key=key))\n        ['1', '2', '10', '11']\n\n\n    If the *iterables* are sorted in descending order, set *reverse* to\n    ``True``:\n\n        >>> list(collate([5, 3, 1], [4, 2, 0], reverse=True))\n        [5, 4, 3, 2, 1, 0]\n\n    If the elements of the passed-in iterables are out of order, you might get\n    unexpected results.\n\n    On Python 3.5+, this function is an alias for :func:`heapq.merge`.\n\n    \"\"\"\n    warnings.warn(\n        \"collate is no longer part of more_itertools, use heapq.merge\",\n        DeprecationWarning,\n    )\n    return merge(*iterables, **kwargs)\n\n\ndef consumer(func):\n    \"\"\"Decorator that automatically advances a PEP-342-style \"reverse iterator\"\n    to its first yield point so you don't have to call ``next()`` on it\n    manually.\n\n        >>> @consumer\n        ... def tally():\n        ...     i = 0\n        ...     while True:\n        ...         print('Thing number %s is %s.' % (i, (yield)))\n        ...         i += 1\n        ...\n        >>> t = tally()\n        >>> t.send('red')\n        Thing number 0 is red.\n        >>> t.send('fish')\n        Thing number 1 is fish.\n\n    Without the decorator, you would have to call ``next(t)`` before\n    ``t.send()`` could be used.\n\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        gen = func(*args, **kwargs)\n        next(gen)\n        return gen\n\n    return wrapper\n\n\ndef ilen(iterable):\n    \"\"\"Return the number of items in *iterable*.\n\n        >>> ilen(x for x in range(1000000) if x % 3 == 0)\n        333334\n\n    This consumes the iterable, so handle with care.\n\n    \"\"\"\n    # This approach was selected because benchmarks showed it's likely the\n    # fastest of the known implementations at the time of writing.\n    # See GitHub tracker: #236, #230.\n    counter = count()\n    deque(zip(iterable, counter), maxlen=0)\n    return next(counter)\n\n\ndef iterate(func, start):\n    \"\"\"Return ``start``, ``func(start)``, ``func(func(start))``, ...\n\n    >>> from itertools import islice\n    >>> list(islice(iterate(lambda x: 2*x, 1), 10))\n    [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]\n\n    \"\"\"\n    while True:\n        yield start\n        start = func(start)\n\n\ndef with_iter(context_manager):\n    \"\"\"Wrap an iterable in a ``with`` statement, so it closes once exhausted.\n\n    For example, this will close the file when the iterator is exhausted::\n\n        upper_lines = (line.upper() for line in with_iter(open('foo')))\n\n    Any context manager which returns an iterable is a candidate for\n    ``with_iter``.\n\n    \"\"\"\n    with context_manager as iterable:\n        yield from iterable\n\n\ndef one(iterable, too_short=None, too_long=None):\n    \"\"\"Return the first item from *iterable*, which is expected to contain only\n    that item. Raise an exception if *iterable* is empty or has more than one\n    item.\n\n    :func:`one` is useful for ensuring that an iterable contains only one item.\n    For example, it can be used to retrieve the result of a database query\n    that is expected to return a single row.\n\n    If *iterable* is empty, ``ValueError`` will be raised. You may specify a\n    different exception with the *too_short* keyword:\n\n        >>> it = []\n        >>> one(it)  # doctest: +IGNORE_EXCEPTION_DETAIL\n        Traceback (most recent call last):\n        ...\n        ValueError: too many items in iterable (expected 1)'\n        >>> too_short = IndexError('too few items')\n        >>> one(it, too_short=too_short)  # doctest: +IGNORE_EXCEPTION_DETAIL\n        Traceback (most recent call last):\n        ...\n        IndexError: too few items\n\n    Similarly, if *iterable* contains more than one item, ``ValueError`` will\n    be raised. You may specify a different exception with the *too_long*\n    keyword:\n\n        >>> it = ['too', 'many']\n        >>> one(it)  # doctest: +IGNORE_EXCEPTION_DETAIL\n        Traceback (most recent call last):\n        ...\n        ValueError: Expected exactly one item in iterable, but got 'too',\n        'many', and perhaps more.\n        >>> too_long = RuntimeError\n        >>> one(it, too_long=too_long)  # doctest: +IGNORE_EXCEPTION_DETAIL\n        Traceback (most recent call last):\n        ...\n        RuntimeError\n\n    Note that :func:`one` attempts to advance *iterable* twice to ensure there\n    is only one item. See :func:`spy` or :func:`peekable` to check iterable\n    contents less destructively.\n\n    \"\"\"\n    it = iter(iterable)\n\n    try:\n        first_value = next(it)\n    except StopIteration as e:\n        raise (\n            too_short or ValueError('too few items in iterable (expected 1)')\n        ) from e\n\n    try:\n        second_value = next(it)\n    except StopIteration:\n        pass\n    else:\n        msg = (\n            'Expected exactly one item in iterable, but got {!r}, {!r}, '\n            'and perhaps more.'.format(first_value, second_value)\n        )\n        raise too_long or ValueError(msg)\n\n    return first_value\n\n\ndef distinct_permutations(iterable, r=None):\n    \"\"\"Yield successive distinct permutations of the elements in *iterable*.\n\n        >>> sorted(distinct_permutations([1, 0, 1]))\n        [(0, 1, 1), (1, 0, 1), (1, 1, 0)]\n\n    Equivalent to ``set(permutations(iterable))``, except duplicates are not\n    generated and thrown away. For larger input sequences this is much more\n    efficient.\n\n    Duplicate permutations arise when there are duplicated elements in the\n    input iterable. The number of items returned is\n    `n! / (x_1! * x_2! * ... * x_n!)`, where `n` is the total number of\n    items input, and each `x_i` is the count of a distinct item in the input\n    sequence.\n\n    If *r* is given, only the *r*-length permutations are yielded.\n\n        >>> sorted(distinct_permutations([1, 0, 1], r=2))\n        [(0, 1), (1, 0), (1, 1)]\n        >>> sorted(distinct_permutations(range(3), r=2))\n        [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]\n\n    \"\"\"\n    # Algorithm: https://w.wiki/Qai\n    def _full(A):\n        while True:\n            # Yield the permutation we have\n            yield tuple(A)\n\n            # Find the largest index i such that A[i] < A[i + 1]\n            for i in range(size - 2, -1, -1):\n                if A[i] < A[i + 1]:\n                    break\n            #  If no such index exists, this permutation is the last one\n            else:\n                return\n\n            # Find the largest index j greater than j such that A[i] < A[j]\n            for j in range(size - 1, i, -1):\n                if A[i] < A[j]:\n                    break\n\n            # Swap the value of A[i] with that of A[j], then reverse the\n            # sequence from A[i + 1] to form the new permutation\n            A[i], A[j] = A[j], A[i]\n            A[i + 1 :] = A[: i - size : -1]  # A[i + 1:][::-1]\n\n    # Algorithm: modified from the above\n    def _partial(A, r):\n        # Split A into the first r items and the last r items\n        head, tail = A[:r], A[r:]\n        right_head_indexes = range(r - 1, -1, -1)\n        left_tail_indexes = range(len(tail))\n\n        while True:\n            # Yield the permutation we have\n            yield tuple(head)\n\n            # Starting from the right, find the first index of the head with\n            # value smaller than the maximum value of the tail - call it i.\n            pivot = tail[-1]\n            for i in right_head_indexes:\n                if head[i] < pivot:\n                    break\n                pivot = head[i]\n            else:\n                return\n\n            # Starting from the left, find the first value of the tail\n            # with a value greater than head[i] and swap.\n            for j in left_tail_indexes:\n                if tail[j] > head[i]:\n                    head[i], tail[j] = tail[j], head[i]\n                    break\n            # If we didn't find one, start from the right and find the first\n            # index of the head with a value greater than head[i] and swap.\n            else:\n                for j in right_head_indexes:\n                    if head[j] > head[i]:\n                        head[i], head[j] = head[j], head[i]\n                        break\n\n            # Reverse head[i + 1:] and swap it with tail[:r - (i + 1)]\n            tail += head[: i - r : -1]  # head[i + 1:][::-1]\n            i += 1\n            head[i:], tail[:] = tail[: r - i], tail[r - i :]\n\n    items = sorted(iterable)\n\n    size = len(items)\n    if r is None:\n        r = size\n\n    if 0 < r <= size:\n        return _full(items) if (r == size) else _partial(items, r)\n\n    return iter(() if r else ((),))\n\n\ndef intersperse(e, iterable, n=1):\n    \"\"\"Intersperse filler element *e* among the items in *iterable*, leaving\n    *n* items between each filler element.\n\n        >>> list(intersperse('!', [1, 2, 3, 4, 5]))\n        [1, '!', 2, '!', 3, '!', 4, '!', 5]\n\n        >>> list(intersperse(None, [1, 2, 3, 4, 5], n=2))\n        [1, 2, None, 3, 4, None, 5]\n\n    \"\"\"\n    if n == 0:\n        raise ValueError('n must be > 0')\n    elif n == 1:\n        # interleave(repeat(e), iterable) -> e, x_0, e, e, x_1, e, x_2...\n        # islice(..., 1, None) -> x_0, e, e, x_1, e, x_2...\n        return islice(interleave(repeat(e), iterable), 1, None)\n    else:\n        # interleave(filler, chunks) -> [e], [x_0, x_1], [e], [x_2, x_3]...\n        # islice(..., 1, None) -> [x_0, x_1], [e], [x_2, x_3]...\n        # flatten(...) -> x_0, x_1, e, x_2, x_3...\n        filler = repeat([e])\n        chunks = chunked(iterable, n)\n        return flatten(islice(interleave(filler, chunks), 1, None))\n\n\ndef unique_to_each(*iterables):\n    \"\"\"Return the elements from each of the input iterables that aren't in the\n    other input iterables.\n\n    For example, suppose you have a set of packages, each with a set of\n    dependencies::\n\n        {'pkg_1': {'A', 'B'}, 'pkg_2': {'B', 'C'}, 'pkg_3': {'B', 'D'}}\n\n    If you remove one package, which dependencies can also be removed?\n\n    If ``pkg_1`` is removed, then ``A`` is no longer necessary - it is not\n    associated with ``pkg_2`` or ``pkg_3``. Similarly, ``C`` is only needed for\n    ``pkg_2``, and ``D`` is only needed for ``pkg_3``::\n\n        >>> unique_to_each({'A', 'B'}, {'B', 'C'}, {'B', 'D'})\n        [['A'], ['C'], ['D']]\n\n    If there are duplicates in one input iterable that aren't in the others\n    they will be duplicated in the output. Input order is preserved::\n\n        >>> unique_to_each(\"mississippi\", \"missouri\")\n        [['p', 'p'], ['o', 'u', 'r']]\n\n    It is assumed that the elements of each iterable are hashable.\n\n    \"\"\"\n    pool = [list(it) for it in iterables]\n    counts = Counter(chain.from_iterable(map(set, pool)))\n    uniques = {element for element in counts if counts[element] == 1}\n    return [list(filter(uniques.__contains__, it)) for it in pool]\n\n\ndef windowed(seq, n, fillvalue=None, step=1):\n    \"\"\"Return a sliding window of width *n* over the given iterable.\n\n        >>> all_windows = windowed([1, 2, 3, 4, 5], 3)\n        >>> list(all_windows)\n        [(1, 2, 3), (2, 3, 4), (3, 4, 5)]\n\n    When the window is larger than the iterable, *fillvalue* is used in place\n    of missing values:\n\n        >>> list(windowed([1, 2, 3], 4))\n        [(1, 2, 3, None)]\n\n    Each window will advance in increments of *step*:\n\n        >>> list(windowed([1, 2, 3, 4, 5, 6], 3, fillvalue='!', step=2))\n        [(1, 2, 3), (3, 4, 5), (5, 6, '!')]\n\n    To slide into the iterable's items, use :func:`chain` to add filler items\n    to the left:\n\n        >>> iterable = [1, 2, 3, 4]\n        >>> n = 3\n        >>> padding = [None] * (n - 1)\n        >>> list(windowed(chain(padding, iterable), 3))\n        [(None, None, 1), (None, 1, 2), (1, 2, 3), (2, 3, 4)]\n    \"\"\"\n    if n < 0:\n        raise ValueError('n must be >= 0')\n    if n == 0:\n        yield tuple()\n        return\n    if step < 1:\n        raise ValueError('step must be >= 1')\n\n    window = deque(maxlen=n)\n    i = n\n    for _ in map(window.append, seq):\n        i -= 1\n        if not i:\n            i = step\n            yield tuple(window)\n\n    size = len(window)\n    if size < n:\n        yield tuple(chain(window, repeat(fillvalue, n - size)))\n    elif 0 < i < min(step, n):\n        window += (fillvalue,) * i\n        yield tuple(window)\n\n\ndef substrings(iterable):\n    \"\"\"Yield all of the substrings of *iterable*.\n\n        >>> [''.join(s) for s in substrings('more')]\n        ['m', 'o', 'r', 'e', 'mo', 'or', 're', 'mor', 'ore', 'more']\n\n    Note that non-string iterables can also be subdivided.\n\n        >>> list(substrings([0, 1, 2]))\n        [(0,), (1,), (2,), (0, 1), (1, 2), (0, 1, 2)]\n\n    \"\"\"\n    # The length-1 substrings\n    seq = []\n    for item in iter(iterable):\n        seq.append(item)\n        yield (item,)\n    seq = tuple(seq)\n    item_count = len(seq)\n\n    # And the rest\n    for n in range(2, item_count + 1):\n        for i in range(item_count - n + 1):\n            yield seq[i : i + n]\n\n\ndef substrings_indexes(seq, reverse=False):\n    \"\"\"Yield all substrings and their positions in *seq*\n\n    The items yielded will be a tuple of the form ``(substr, i, j)``, where\n    ``substr == seq[i:j]``.\n\n    This function only works for iterables that support slicing, such as\n    ``str`` objects.\n\n    >>> for item in substrings_indexes('more'):\n    ...    print(item)\n    ('m', 0, 1)\n    ('o', 1, 2)\n    ('r', 2, 3)\n    ('e', 3, 4)\n    ('mo', 0, 2)\n    ('or', 1, 3)\n    ('re', 2, 4)\n    ('mor', 0, 3)\n    ('ore', 1, 4)\n    ('more', 0, 4)\n\n    Set *reverse* to ``True`` to yield the same items in the opposite order.\n\n\n    \"\"\"\n    r = range(1, len(seq) + 1)\n    if reverse:\n        r = reversed(r)\n    return (\n        (seq[i : i + L], i, i + L) for L in r for i in range(len(seq) - L + 1)\n    )\n\n\nclass bucket:\n    \"\"\"Wrap *iterable* and return an object that buckets it iterable into\n    child iterables based on a *key* function.\n\n        >>> iterable = ['a1', 'b1', 'c1', 'a2', 'b2', 'c2', 'b3']\n        >>> s = bucket(iterable, key=lambda x: x[0])  # Bucket by 1st character\n        >>> sorted(list(s))  # Get the keys\n        ['a', 'b', 'c']\n        >>> a_iterable = s['a']\n        >>> next(a_iterable)\n        'a1'\n        >>> next(a_iterable)\n        'a2'\n        >>> list(s['b'])\n        ['b1', 'b2', 'b3']\n\n    The original iterable will be advanced and its items will be cached until\n    they are used by the child iterables. This may require significant storage.\n\n    By default, attempting to select a bucket to which no items belong  will\n    exhaust the iterable and cache all values.\n    If you specify a *validator* function, selected buckets will instead be\n    checked against it.\n\n        >>> from itertools import count\n        >>> it = count(1, 2)  # Infinite sequence of odd numbers\n        >>> key = lambda x: x % 10  # Bucket by last digit\n        >>> validator = lambda x: x in {1, 3, 5, 7, 9}  # Odd digits only\n        >>> s = bucket(it, key=key, validator=validator)\n        >>> 2 in s\n        False\n        >>> list(s[2])\n        []\n\n    \"\"\"\n\n    def __init__(self, iterable, key, validator=None):\n        self._it = iter(iterable)\n        self._key = key\n        self._cache = defaultdict(deque)\n        self._validator = validator or (lambda x: True)\n\n    def __contains__(self, value):\n        if not self._validator(value):\n            return False\n\n        try:\n            item = next(self[value])\n        except StopIteration:\n            return False\n        else:\n            self._cache[value].appendleft(item)\n\n        return True\n\n    def _get_values(self, value):\n        \"\"\"\n        Helper to yield items from the parent iterator that match *value*.\n        Items that don't match are stored in the local cache as they\n        are encountered.\n        \"\"\"\n        while True:\n            # If we've cached some items that match the target value, emit\n            # the first one and evict it from the cache.\n            if self._cache[value]:\n                yield self._cache[value].popleft()\n            # Otherwise we need to advance the parent iterator to search for\n            # a matching item, caching the rest.\n            else:\n                while True:\n                    try:\n                        item = next(self._it)\n                    except StopIteration:\n                        return\n                    item_value = self._key(item)\n                    if item_value == value:\n                        yield item\n                        break\n                    elif self._validator(item_value):\n                        self._cache[item_value].append(item)\n\n    def __iter__(self):\n        for item in self._it:\n            item_value = self._key(item)\n            if self._validator(item_value):\n                self._cache[item_value].append(item)\n\n        yield from self._cache.keys()\n\n    def __getitem__(self, value):\n        if not self._validator(value):\n            return iter(())\n\n        return self._get_values(value)\n\n\ndef spy(iterable, n=1):\n    \"\"\"Return a 2-tuple with a list containing the first *n* elements of\n    *iterable*, and an iterator with the same items as *iterable*.\n    This allows you to \"look ahead\" at the items in the iterable without\n    advancing it.\n\n    There is one item in the list by default:\n\n        >>> iterable = 'abcdefg'\n        >>> head, iterable = spy(iterable)\n        >>> head\n        ['a']\n        >>> list(iterable)\n        ['a', 'b', 'c', 'd', 'e', 'f', 'g']\n\n    You may use unpacking to retrieve items instead of lists:\n\n        >>> (head,), iterable = spy('abcdefg')\n        >>> head\n        'a'\n        >>> (first, second), iterable = spy('abcdefg', 2)\n        >>> first\n        'a'\n        >>> second\n        'b'\n\n    The number of items requested can be larger than the number of items in\n    the iterable:\n\n        >>> iterable = [1, 2, 3, 4, 5]\n        >>> head, iterable = spy(iterable, 10)\n        >>> head\n        [1, 2, 3, 4, 5]\n        >>> list(iterable)\n        [1, 2, 3, 4, 5]\n\n    \"\"\"\n    it = iter(iterable)\n    head = take(n, it)\n\n    return head.copy(), chain(head, it)\n\n\ndef interleave(*iterables):\n    \"\"\"Return a new iterable yielding from each iterable in turn,\n    until the shortest is exhausted.\n\n        >>> list(interleave([1, 2, 3], [4, 5], [6, 7, 8]))\n        [1, 4, 6, 2, 5, 7]\n\n    For a version that doesn't terminate after the shortest iterable is\n    exhausted, see :func:`interleave_longest`.\n\n    \"\"\"\n    return chain.from_iterable(zip(*iterables))\n\n\ndef interleave_longest(*iterables):\n    \"\"\"Return a new iterable yielding from each iterable in turn,\n    skipping any that are exhausted.\n\n        >>> list(interleave_longest([1, 2, 3], [4, 5], [6, 7, 8]))\n        [1, 4, 6, 2, 5, 7, 3, 8]\n\n    This function produces the same output as :func:`roundrobin`, but may\n    perform better for some inputs (in particular when the number of iterables\n    is large).\n\n    \"\"\"\n    i = chain.from_iterable(zip_longest(*iterables, fillvalue=_marker))\n    return (x for x in i if x is not _marker)\n\n\ndef collapse(iterable, base_type=None, levels=None):\n    \"\"\"Flatten an iterable with multiple levels of nesting (e.g., a list of\n    lists of tuples) into non-iterable types.\n\n        >>> iterable = [(1, 2), ([3, 4], [[5], [6]])]\n        >>> list(collapse(iterable))\n        [1, 2, 3, 4, 5, 6]\n\n    Binary and text strings are not considered iterable and\n    will not be collapsed.\n\n    To avoid collapsing other types, specify *base_type*:\n\n        >>> iterable = ['ab', ('cd', 'ef'), ['gh', 'ij']]\n        >>> list(collapse(iterable, base_type=tuple))\n        ['ab', ('cd', 'ef'), 'gh', 'ij']\n\n    Specify *levels* to stop flattening after a certain level:\n\n    >>> iterable = [('a', ['b']), ('c', ['d'])]\n    >>> list(collapse(iterable))  # Fully flattened\n    ['a', 'b', 'c', 'd']\n    >>> list(collapse(iterable, levels=1))  # Only one level flattened\n    ['a', ['b'], 'c', ['d']]\n\n    \"\"\"\n\n    def walk(node, level):\n        if (\n            ((levels is not None) and (level > levels))\n            or isinstance(node, (str, bytes))\n            or ((base_type is not None) and isinstance(node, base_type))\n        ):\n            yield node\n            return\n\n        try:\n            tree = iter(node)\n        except TypeError:\n            yield node\n            return\n        else:\n            for child in tree:\n                yield from walk(child, level + 1)\n\n    yield from walk(iterable, 0)\n\n\ndef side_effect(func, iterable, chunk_size=None, before=None, after=None):\n    \"\"\"Invoke *func* on each item in *iterable* (or on each *chunk_size* group\n    of items) before yielding the item.\n\n    `func` must be a function that takes a single argument. Its return value\n    will be discarded.\n\n    *before* and *after* are optional functions that take no arguments. They\n    will be executed before iteration starts and after it ends, respectively.\n\n    `side_effect` can be used for logging, updating progress bars, or anything\n    that is not functionally \"pure.\"\n\n    Emitting a status message:\n\n        >>> from more_itertools import consume\n        >>> func = lambda item: print('Received {}'.format(item))\n        >>> consume(side_effect(func, range(2)))\n        Received 0\n        Received 1\n\n    Operating on chunks of items:\n\n        >>> pair_sums = []\n        >>> func = lambda chunk: pair_sums.append(sum(chunk))\n        >>> list(side_effect(func, [0, 1, 2, 3, 4, 5], 2))\n        [0, 1, 2, 3, 4, 5]\n        >>> list(pair_sums)\n        [1, 5, 9]\n\n    Writing to a file-like object:\n\n        >>> from io import StringIO\n        >>> from more_itertools import consume\n        >>> f = StringIO()\n        >>> func = lambda x: print(x, file=f)\n        >>> before = lambda: print(u'HEADER', file=f)\n        >>> after = f.close\n        >>> it = [u'a', u'b', u'c']\n        >>> consume(side_effect(func, it, before=before, after=after))\n        >>> f.closed\n        True\n\n    \"\"\"\n    try:\n        if before is not None:\n            before()\n\n        if chunk_size is None:\n            for item in iterable:\n                func(item)\n                yield item\n        else:\n            for chunk in chunked(iterable, chunk_size):\n                func(chunk)\n                yield from chunk\n    finally:\n        if after is not None:\n            after()\n\n\ndef sliced(seq, n, strict=False):\n    \"\"\"Yield slices of length *n* from the sequence *seq*.\n\n    >>> list(sliced((1, 2, 3, 4, 5, 6), 3))\n    [(1, 2, 3), (4, 5, 6)]\n\n    By the default, the last yielded slice will have fewer than *n* elements\n    if the length of *seq* is not divisible by *n*:\n\n    >>> list(sliced((1, 2, 3, 4, 5, 6, 7, 8), 3))\n    [(1, 2, 3), (4, 5, 6), (7, 8)]\n\n    If the length of *seq* is not divisible by *n* and *strict* is\n    ``True``, then ``ValueError`` will be raised before the last\n    slice is yielded.\n\n    This function will only work for iterables that support slicing.\n    For non-sliceable iterables, see :func:`chunked`.\n\n    \"\"\"\n    iterator = takewhile(len, (seq[i : i + n] for i in count(0, n)))\n    if strict:\n\n        def ret():\n            for _slice in iterator:\n                if len(_slice) != n:\n                    raise ValueError(\"seq is not divisible by n.\")\n                yield _slice\n\n        return iter(ret())\n    else:\n        return iterator\n\n\ndef split_at(iterable, pred, maxsplit=-1, keep_separator=False):\n    \"\"\"Yield lists of items from *iterable*, where each list is delimited by\n    an item where callable *pred* returns ``True``.\n\n        >>> list(split_at('abcdcba', lambda x: x == 'b'))\n        [['a'], ['c', 'd', 'c'], ['a']]\n\n        >>> list(split_at(range(10), lambda n: n % 2 == 1))\n        [[0], [2], [4], [6], [8], []]\n\n    At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,\n    then there is no limit on the number of splits:\n\n        >>> list(split_at(range(10), lambda n: n % 2 == 1, maxsplit=2))\n        [[0], [2], [4, 5, 6, 7, 8, 9]]\n\n    By default, the delimiting items are not included in the output.\n    The include them, set *keep_separator* to ``True``.\n\n        >>> list(split_at('abcdcba', lambda x: x == 'b', keep_separator=True))\n        [['a'], ['b'], ['c', 'd', 'c'], ['b'], ['a']]\n\n    \"\"\"\n    if maxsplit == 0:\n        yield list(iterable)\n        return\n\n    buf = []\n    it = iter(iterable)\n    for item in it:\n        if pred(item):\n            yield buf\n            if keep_separator:\n                yield [item]\n            if maxsplit == 1:\n                yield list(it)\n                return\n            buf = []\n            maxsplit -= 1\n        else:\n            buf.append(item)\n    yield buf\n\n\ndef split_before(iterable, pred, maxsplit=-1):\n    \"\"\"Yield lists of items from *iterable*, where each list ends just before\n    an item for which callable *pred* returns ``True``:\n\n        >>> list(split_before('OneTwo', lambda s: s.isupper()))\n        [['O', 'n', 'e'], ['T', 'w', 'o']]\n\n        >>> list(split_before(range(10), lambda n: n % 3 == 0))\n        [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]\n\n    At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,\n    then there is no limit on the number of splits:\n\n        >>> list(split_before(range(10), lambda n: n % 3 == 0, maxsplit=2))\n        [[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]\n    \"\"\"\n    if maxsplit == 0:\n        yield list(iterable)\n        return\n\n    buf = []\n    it = iter(iterable)\n    for item in it:\n        if pred(item) and buf:\n            yield buf\n            if maxsplit == 1:\n                yield [item] + list(it)\n                return\n            buf = []\n            maxsplit -= 1\n        buf.append(item)\n    if buf:\n        yield buf\n\n\ndef split_after(iterable, pred, maxsplit=-1):\n    \"\"\"Yield lists of items from *iterable*, where each list ends with an\n    item where callable *pred* returns ``True``:\n\n        >>> list(split_after('one1two2', lambda s: s.isdigit()))\n        [['o', 'n', 'e', '1'], ['t', 'w', 'o', '2']]\n\n        >>> list(split_after(range(10), lambda n: n % 3 == 0))\n        [[0], [1, 2, 3], [4, 5, 6], [7, 8, 9]]\n\n    At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,\n    then there is no limit on the number of splits:\n\n        >>> list(split_after(range(10), lambda n: n % 3 == 0, maxsplit=2))\n        [[0], [1, 2, 3], [4, 5, 6, 7, 8, 9]]\n\n    \"\"\"\n    if maxsplit == 0:\n        yield list(iterable)\n        return\n\n    buf = []\n    it = iter(iterable)\n    for item in it:\n        buf.append(item)\n        if pred(item) and buf:\n            yield buf\n            if maxsplit == 1:\n                yield list(it)\n                return\n            buf = []\n            maxsplit -= 1\n    if buf:\n        yield buf\n\n\ndef split_when(iterable, pred, maxsplit=-1):\n    \"\"\"Split *iterable* into pieces based on the output of *pred*.\n    *pred* should be a function that takes successive pairs of items and\n    returns ``True`` if the iterable should be split in between them.\n\n    For example, to find runs of increasing numbers, split the iterable when\n    element ``i`` is larger than element ``i + 1``:\n\n        >>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2], lambda x, y: x > y))\n        [[1, 2, 3, 3], [2, 5], [2, 4], [2]]\n\n    At most *maxsplit* splits are done. If *maxsplit* is not specified or -1,\n    then there is no limit on the number of splits:\n\n        >>> list(split_when([1, 2, 3, 3, 2, 5, 2, 4, 2],\n        ...                 lambda x, y: x > y, maxsplit=2))\n        [[1, 2, 3, 3], [2, 5], [2, 4, 2]]\n\n    \"\"\"\n    if maxsplit == 0:\n        yield list(iterable)\n        return\n\n    it = iter(iterable)\n    try:\n        cur_item = next(it)\n    except StopIteration:\n        return\n\n    buf = [cur_item]\n    for next_item in it:\n        if pred(cur_item, next_item):\n            yield buf\n            if maxsplit == 1:\n                yield [next_item] + list(it)\n                return\n            buf = []\n            maxsplit -= 1\n\n        buf.append(next_item)\n        cur_item = next_item\n\n    yield buf\n\n\ndef split_into(iterable, sizes):\n    \"\"\"Yield a list of sequential items from *iterable* of length 'n' for each\n    integer 'n' in *sizes*.\n\n        >>> list(split_into([1,2,3,4,5,6], [1,2,3]))\n        [[1], [2, 3], [4, 5, 6]]\n\n    If the sum of *sizes* is smaller than the length of *iterable*, then the\n    remaining items of *iterable* will not be returned.\n\n        >>> list(split_into([1,2,3,4,5,6], [2,3]))\n        [[1, 2], [3, 4, 5]]\n\n    If the sum of *sizes* is larger than the length of *iterable*, fewer items\n    will be returned in the iteration that overruns *iterable* and further\n    lists will be empty:\n\n        >>> list(split_into([1,2,3,4], [1,2,3,4]))\n        [[1], [2, 3], [4], []]\n\n    When a ``None`` object is encountered in *sizes*, the returned list will\n    contain items up to the end of *iterable* the same way that itertools.slice\n    does:\n\n        >>> list(split_into([1,2,3,4,5,6,7,8,9,0], [2,3,None]))\n        [[1, 2], [3, 4, 5], [6, 7, 8, 9, 0]]\n\n    :func:`split_into` can be useful for grouping a series of items where the\n    sizes of the groups are not uniform. An example would be where in a row\n    from a table, multiple columns represent elements of the same feature\n    (e.g. a point represented by x,y,z) but, the format is not the same for\n    all columns.\n    \"\"\"\n    # convert the iterable argument into an iterator so its contents can\n    # be consumed by islice in case it is a generator\n    it = iter(iterable)\n\n    for size in sizes:\n        if size is None:\n            yield list(it)\n            return\n        else:\n            yield list(islice(it, size))\n\n\ndef padded(iterable, fillvalue=None, n=None, next_multiple=False):\n    \"\"\"Yield the elements from *iterable*, followed by *fillvalue*, such that\n    at least *n* items are emitted.\n\n        >>> list(padded([1, 2, 3], '?', 5))\n        [1, 2, 3, '?', '?']\n\n    If *next_multiple* is ``True``, *fillvalue* will be emitted until the\n    number of items emitted is a multiple of *n*::\n\n        >>> list(padded([1, 2, 3, 4], n=3, next_multiple=True))\n        [1, 2, 3, 4, None, None]\n\n    If *n* is ``None``, *fillvalue* will be emitted indefinitely.\n\n    \"\"\"\n    it = iter(iterable)\n    if n is None:\n        yield from chain(it, repeat(fillvalue))\n    elif n < 1:\n        raise ValueError('n must be at least 1')\n    else:\n        item_count = 0\n        for item in it:\n            yield item\n            item_count += 1\n\n        remaining = (n - item_count) % n if next_multiple else n - item_count\n        for _ in range(remaining):\n            yield fillvalue\n\n\ndef repeat_last(iterable, default=None):\n    \"\"\"After the *iterable* is exhausted, keep yielding its last element.\n\n        >>> list(islice(repeat_last(range(3)), 5))\n        [0, 1, 2, 2, 2]\n\n    If the iterable is empty, yield *default* forever::\n\n        >>> list(islice(repeat_last(range(0), 42), 5))\n        [42, 42, 42, 42, 42]\n\n    \"\"\"\n    item = _marker\n    for item in iterable:\n        yield item\n    final = default if item is _marker else item\n    yield from repeat(final)\n\n\ndef distribute(n, iterable):\n    \"\"\"Distribute the items from *iterable* among *n* smaller iterables.\n\n        >>> group_1, group_2 = distribute(2, [1, 2, 3, 4, 5, 6])\n        >>> list(group_1)\n        [1, 3, 5]\n        >>> list(group_2)\n        [2, 4, 6]\n\n    If the length of *iterable* is not evenly divisible by *n*, then the\n    length of the returned iterables will not be identical:\n\n        >>> children = distribute(3, [1, 2, 3, 4, 5, 6, 7])\n        >>> [list(c) for c in children]\n        [[1, 4, 7], [2, 5], [3, 6]]\n\n    If the length of *iterable* is smaller than *n*, then the last returned\n    iterables will be empty:\n\n        >>> children = distribute(5, [1, 2, 3])\n        >>> [list(c) for c in children]\n        [[1], [2], [3], [], []]\n\n    This function uses :func:`itertools.tee` and may require significant\n    storage. If you need the order items in the smaller iterables to match the\n    original iterable, see :func:`divide`.\n\n    \"\"\"\n    if n < 1:\n        raise ValueError('n must be at least 1')\n\n    children = tee(iterable, n)\n    return [islice(it, index, None, n) for index, it in enumerate(children)]\n\n\ndef stagger(iterable, offsets=(-1, 0, 1), longest=False, fillvalue=None):\n    \"\"\"Yield tuples whose elements are offset from *iterable*.\n    The amount by which the `i`-th item in each tuple is offset is given by\n    the `i`-th item in *offsets*.\n\n        >>> list(stagger([0, 1, 2, 3]))\n        [(None, 0, 1), (0, 1, 2), (1, 2, 3)]\n        >>> list(stagger(range(8), offsets=(0, 2, 4)))\n        [(0, 2, 4), (1, 3, 5), (2, 4, 6), (3, 5, 7)]\n\n    By default, the sequence will end when the final element of a tuple is the\n    last item in the iterable. To continue until the first element of a tuple\n    is the last item in the iterable, set *longest* to ``True``::\n\n        >>> list(stagger([0, 1, 2, 3], longest=True))\n        [(None, 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, None), (3, None, None)]\n\n    By default, ``None`` will be used to replace offsets beyond the end of the\n    sequence. Specify *fillvalue* to use some other value.\n\n    \"\"\"\n    children = tee(iterable, len(offsets))\n\n    return zip_offset(\n        *children, offsets=offsets, longest=longest, fillvalue=fillvalue\n    )\n\n\nclass UnequalIterablesError(ValueError):\n    def __init__(self, details=None):\n        msg = 'Iterables have different lengths'\n        if details is not None:\n            msg += (': index 0 has length {}; index {} has length {}').format(\n                *details\n            )\n\n        super().__init__(msg)\n\n\ndef _zip_equal_generator(iterables):\n    for combo in zip_longest(*iterables, fillvalue=_marker):\n        for val in combo:\n            if val is _marker:\n                raise UnequalIterablesError()\n        yield combo\n\n\ndef zip_equal(*iterables):\n    \"\"\"``zip`` the input *iterables* together, but raise\n    ``UnequalIterablesError`` if they aren't all the same length.\n\n        >>> it_1 = range(3)\n        >>> it_2 = iter('abc')\n        >>> list(zip_equal(it_1, it_2))\n        [(0, 'a'), (1, 'b'), (2, 'c')]\n\n        >>> it_1 = range(3)\n        >>> it_2 = iter('abcd')\n        >>> list(zip_equal(it_1, it_2)) # doctest: +IGNORE_EXCEPTION_DETAIL\n        Traceback (most recent call last):\n        ...\n        more_itertools.more.UnequalIterablesError: Iterables have different\n        lengths\n\n    \"\"\"\n    if hexversion >= 0x30A00A6:\n        warnings.warn(\n            (\n                'zip_equal will be removed in a future version of '\n                'more-itertools. Use the builtin zip function with '\n                'strict=True instead.'\n            ),\n            DeprecationWarning,\n        )\n    # Check whether the iterables are all the same size.\n    try:\n        first_size = len(iterables[0])\n        for i, it in enumerate(iterables[1:], 1):\n            size = len(it)\n            if size != first_size:\n                break\n        else:\n            # If we didn't break out, we can use the built-in zip.\n            return zip(*iterables)\n\n        # If we did break out, there was a mismatch.\n        raise UnequalIterablesError(details=(first_size, i, size))\n    # If any one of the iterables didn't have a length, start reading\n    # them until one runs out.\n    except TypeError:\n        return _zip_equal_generator(iterables)\n\n\ndef zip_offset(*iterables, offsets, longest=False, fillvalue=None):\n    \"\"\"``zip`` the input *iterables* together, but offset the `i`-th iterable\n    by the `i`-th item in *offsets*.\n\n        >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1)))\n        [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e')]\n\n    This can be used as a lightweight alternative to SciPy or pandas to analyze\n    data sets in which some series have a lead or lag relationship.\n\n    By default, the sequence will end when the shortest iterable is exhausted.\n    To continue until the longest iterable is exhausted, set *longest* to\n    ``True``.\n\n        >>> list(zip_offset('0123', 'abcdef', offsets=(0, 1), longest=True))\n        [('0', 'b'), ('1', 'c'), ('2', 'd'), ('3', 'e'), (None, 'f')]\n\n    By default, ``None`` will be used to replace offsets beyond the end of the\n    sequence. Specify *fillvalue* to use some other value.\n\n    \"\"\"\n    if len(iterables) != len(offsets):\n        raise ValueError(\"Number of iterables and offsets didn't match\")\n\n    staggered = []\n    for it, n in zip(iterables, offsets):\n        if n < 0:\n            staggered.append(chain(repeat(fillvalue, -n), it))\n        elif n > 0:\n            staggered.append(islice(it, n, None))\n        else:\n            staggered.append(it)\n\n    if longest:\n        return zip_longest(*staggered, fillvalue=fillvalue)\n\n    return zip(*staggered)\n\n\ndef sort_together(iterables, key_list=(0,), key=None, reverse=False):\n    \"\"\"Return the input iterables sorted together, with *key_list* as the\n    priority for sorting. All iterables are trimmed to the length of the\n    shortest one.\n\n    This can be used like the sorting function in a spreadsheet. If each\n    iterable represents a column of data, the key list determines which\n    columns are used for sorting.\n\n    By default, all iterables are sorted using the ``0``-th iterable::\n\n        >>> iterables = [(4, 3, 2, 1), ('a', 'b', 'c', 'd')]\n        >>> sort_together(iterables)\n        [(1, 2, 3, 4), ('d', 'c', 'b', 'a')]\n\n    Set a different key list to sort according to another iterable.\n    Specifying multiple keys dictates how ties are broken::\n\n        >>> iterables = [(3, 1, 2), (0, 1, 0), ('c', 'b', 'a')]\n        >>> sort_together(iterables, key_list=(1, 2))\n        [(2, 3, 1), (0, 0, 1), ('a', 'c', 'b')]\n\n    To sort by a function of the elements of the iterable, pass a *key*\n    function. Its arguments are the elements of the iterables corresponding to\n    the key list::\n\n        >>> names = ('a', 'b', 'c')\n        >>> lengths = (1, 2, 3)\n        >>> widths = (5, 2, 1)\n        >>> def area(length, width):\n        ...     return length * width\n        >>> sort_together([names, lengths, widths], key_list=(1, 2), key=area)\n        [('c', 'b', 'a'), (3, 2, 1), (1, 2, 5)]\n\n    Set *reverse* to ``True`` to sort in descending order.\n\n        >>> sort_together([(1, 2, 3), ('c', 'b', 'a')], reverse=True)\n        [(3, 2, 1), ('a', 'b', 'c')]\n\n    \"\"\"\n    if key is None:\n        # if there is no key function, the key argument to sorted is an\n        # itemgetter\n        key_argument = itemgetter(*key_list)\n    else:\n        # if there is a key function, call it with the items at the offsets\n        # specified by the key function as arguments\n        key_list = list(key_list)\n        if len(key_list) == 1:\n            # if key_list contains a single item, pass the item at that offset\n            # as the only argument to the key function\n            key_offset = key_list[0]\n            key_argument = lambda zipped_items: key(zipped_items[key_offset])\n        else:\n            # if key_list contains multiple items, use itemgetter to return a\n            # tuple of items, which we pass as *args to the key function\n            get_key_items = itemgetter(*key_list)\n            key_argument = lambda zipped_items: key(\n                *get_key_items(zipped_items)\n            )\n\n    return list(\n        zip(*sorted(zip(*iterables), key=key_argument, reverse=reverse))\n    )\n\n\ndef unzip(iterable):\n    \"\"\"The inverse of :func:`zip`, this function disaggregates the elements\n    of the zipped *iterable*.\n\n    The ``i``-th iterable contains the ``i``-th element from each element\n    of the zipped iterable. The first element is used to to determine the\n    length of the remaining elements.\n\n        >>> iterable = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n        >>> letters, numbers = unzip(iterable)\n        >>> list(letters)\n        ['a', 'b', 'c', 'd']\n        >>> list(numbers)\n        [1, 2, 3, 4]\n\n    This is similar to using ``zip(*iterable)``, but it avoids reading\n    *iterable* into memory. Note, however, that this function uses\n    :func:`itertools.tee` and thus may require significant storage.\n\n    \"\"\"\n    head, iterable = spy(iter(iterable))\n    if not head:\n        # empty iterable, e.g. zip([], [], [])\n        return ()\n    # spy returns a one-length iterable as head\n    head = head[0]\n    iterables = tee(iterable, len(head))\n\n    def itemgetter(i):\n        def getter(obj):\n            try:\n                return obj[i]\n            except IndexError:\n                # basically if we have an iterable like\n                # iter([(1, 2, 3), (4, 5), (6,)])\n                # the second unzipped iterable would fail at the third tuple\n                # since it would try to access tup[1]\n                # same with the third unzipped iterable and the second tuple\n                # to support these \"improperly zipped\" iterables,\n                # we create a custom itemgetter\n                # which just stops the unzipped iterables\n                # at first length mismatch\n                raise StopIteration\n\n        return getter\n\n    return tuple(map(itemgetter(i), it) for i, it in enumerate(iterables))\n\n\ndef divide(n, iterable):\n    \"\"\"Divide the elements from *iterable* into *n* parts, maintaining\n    order.\n\n        >>> group_1, group_2 = divide(2, [1, 2, 3, 4, 5, 6])\n        >>> list(group_1)\n        [1, 2, 3]\n        >>> list(group_2)\n        [4, 5, 6]\n\n    If the length of *iterable* is not evenly divisible by *n*, then the\n    length of the returned iterables will not be identical:\n\n        >>> children = divide(3, [1, 2, 3, 4, 5, 6, 7])\n        >>> [list(c) for c in children]\n        [[1, 2, 3], [4, 5], [6, 7]]\n\n    If the length of the iterable is smaller than n, then the last returned\n    iterables will be empty:\n\n        >>> children = divide(5, [1, 2, 3])\n        >>> [list(c) for c in children]\n        [[1], [2], [3], [], []]\n\n    This function will exhaust the iterable before returning and may require\n    significant storage. If order is not important, see :func:`distribute`,\n    which does not first pull the iterable into memory.\n\n    \"\"\"\n    if n < 1:\n        raise ValueError('n must be at least 1')\n\n    try:\n        iterable[:0]\n    except TypeError:\n        seq = tuple(iterable)\n    else:\n        seq = iterable\n\n    q, r = divmod(len(seq), n)\n\n    ret = []\n    stop = 0\n    for i in range(1, n + 1):\n        start = stop\n        stop += q + 1 if i <= r else q\n        ret.append(iter(seq[start:stop]))\n\n    return ret\n\n\ndef always_iterable(obj, base_type=(str, bytes)):\n    \"\"\"If *obj* is iterable, return an iterator over its items::\n\n        >>> obj = (1, 2, 3)\n        >>> list(always_iterable(obj))\n        [1, 2, 3]\n\n    If *obj* is not iterable, return a one-item iterable containing *obj*::\n\n        >>> obj = 1\n        >>> list(always_iterable(obj))\n        [1]\n\n    If *obj* is ``None``, return an empty iterable:\n\n        >>> obj = None\n        >>> list(always_iterable(None))\n        []\n\n    By default, binary and text strings are not considered iterable::\n\n        >>> obj = 'foo'\n        >>> list(always_iterable(obj))\n        ['foo']\n\n    If *base_type* is set, objects for which ``isinstance(obj, base_type)``\n    returns ``True`` won't be considered iterable.\n\n        >>> obj = {'a': 1}\n        >>> list(always_iterable(obj))  # Iterate over the dict's keys\n        ['a']\n        >>> list(always_iterable(obj, base_type=dict))  # Treat dicts as a unit\n        [{'a': 1}]\n\n    Set *base_type* to ``None`` to avoid any special handling and treat objects\n    Python considers iterable as iterable:\n\n        >>> obj = 'foo'\n        >>> list(always_iterable(obj, base_type=None))\n        ['f', 'o', 'o']\n    \"\"\"\n    if obj is None:\n        return iter(())\n\n    if (base_type is not None) and isinstance(obj, base_type):\n        return iter((obj,))\n\n    try:\n        return iter(obj)\n    except TypeError:\n        return iter((obj,))\n\n\ndef adjacent(predicate, iterable, distance=1):\n    \"\"\"Return an iterable over `(bool, item)` tuples where the `item` is\n    drawn from *iterable* and the `bool` indicates whether\n    that item satisfies the *predicate* or is adjacent to an item that does.\n\n    For example, to find whether items are adjacent to a ``3``::\n\n        >>> list(adjacent(lambda x: x == 3, range(6)))\n        [(False, 0), (False, 1), (True, 2), (True, 3), (True, 4), (False, 5)]\n\n    Set *distance* to change what counts as adjacent. For example, to find\n    whether items are two places away from a ``3``:\n\n        >>> list(adjacent(lambda x: x == 3, range(6), distance=2))\n        [(False, 0), (True, 1), (True, 2), (True, 3), (True, 4), (True, 5)]\n\n    This is useful for contextualizing the results of a search function.\n    For example, a code comparison tool might want to identify lines that\n    have changed, but also surrounding lines to give the viewer of the diff\n    context.\n\n    The predicate function will only be called once for each item in the\n    iterable.\n\n    See also :func:`groupby_transform`, which can be used with this function\n    to group ranges of items with the same `bool` value.\n\n    \"\"\"\n    # Allow distance=0 mainly for testing that it reproduces results with map()\n    if distance < 0:\n        raise ValueError('distance must be at least 0')\n\n    i1, i2 = tee(iterable)\n    padding = [False] * distance\n    selected = chain(padding, map(predicate, i1), padding)\n    adjacent_to_selected = map(any, windowed(selected, 2 * distance + 1))\n    return zip(adjacent_to_selected, i2)\n\n\ndef groupby_transform(iterable, keyfunc=None, valuefunc=None, reducefunc=None):\n    \"\"\"An extension of :func:`itertools.groupby` that can apply transformations\n    to the grouped data.\n\n    * *keyfunc* is a function computing a key value for each item in *iterable*\n    * *valuefunc* is a function that transforms the individual items from\n      *iterable* after grouping\n    * *reducefunc* is a function that transforms each group of items\n\n    >>> iterable = 'aAAbBBcCC'\n    >>> keyfunc = lambda k: k.upper()\n    >>> valuefunc = lambda v: v.lower()\n    >>> reducefunc = lambda g: ''.join(g)\n    >>> list(groupby_transform(iterable, keyfunc, valuefunc, reducefunc))\n    [('A', 'aaa'), ('B', 'bbb'), ('C', 'ccc')]\n\n    Each optional argument defaults to an identity function if not specified.\n\n    :func:`groupby_transform` is useful when grouping elements of an iterable\n    using a separate iterable as the key. To do this, :func:`zip` the iterables\n    and pass a *keyfunc* that extracts the first element and a *valuefunc*\n    that extracts the second element::\n\n        >>> from operator import itemgetter\n        >>> keys = [0, 0, 1, 1, 1, 2, 2, 2, 3]\n        >>> values = 'abcdefghi'\n        >>> iterable = zip(keys, values)\n        >>> grouper = groupby_transform(iterable, itemgetter(0), itemgetter(1))\n        >>> [(k, ''.join(g)) for k, g in grouper]\n        [(0, 'ab'), (1, 'cde'), (2, 'fgh'), (3, 'i')]\n\n    Note that the order of items in the iterable is significant.\n    Only adjacent items are grouped together, so if you don't want any\n    duplicate groups, you should sort the iterable by the key function.\n\n    \"\"\"\n    ret = groupby(iterable, keyfunc)\n    if valuefunc:\n        ret = ((k, map(valuefunc, g)) for k, g in ret)\n    if reducefunc:\n        ret = ((k, reducefunc(g)) for k, g in ret)\n\n    return ret\n\n\nclass numeric_range(abc.Sequence, abc.Hashable):\n    \"\"\"An extension of the built-in ``range()`` function whose arguments can\n    be any orderable numeric type.\n\n    With only *stop* specified, *start* defaults to ``0`` and *step*\n    defaults to ``1``. The output items will match the type of *stop*:\n\n        >>> list(numeric_range(3.5))\n        [0.0, 1.0, 2.0, 3.0]\n\n    With only *start* and *stop* specified, *step* defaults to ``1``. The\n    output items will match the type of *start*:\n\n        >>> from decimal import Decimal\n        >>> start = Decimal('2.1')\n        >>> stop = Decimal('5.1')\n        >>> list(numeric_range(start, stop))\n        [Decimal('2.1'), Decimal('3.1'), Decimal('4.1')]\n\n    With *start*, *stop*, and *step*  specified the output items will match\n    the type of ``start + step``:\n\n        >>> from fractions import Fraction\n        >>> start = Fraction(1, 2)  # Start at 1/2\n        >>> stop = Fraction(5, 2)  # End at 5/2\n        >>> step = Fraction(1, 2)  # Count by 1/2\n        >>> list(numeric_range(start, stop, step))\n        [Fraction(1, 2), Fraction(1, 1), Fraction(3, 2), Fraction(2, 1)]\n\n    If *step* is zero, ``ValueError`` is raised. Negative steps are supported:\n\n        >>> list(numeric_range(3, -1, -1.0))\n        [3.0, 2.0, 1.0, 0.0]\n\n    Be aware of the limitations of floating point numbers; the representation\n    of the yielded numbers may be surprising.\n\n    ``datetime.datetime`` objects can be used for *start* and *stop*, if *step*\n    is a ``datetime.timedelta`` object:\n\n        >>> import datetime\n        >>> start = datetime.datetime(2019, 1, 1)\n        >>> stop = datetime.datetime(2019, 1, 3)\n        >>> step = datetime.timedelta(days=1)\n        >>> items = iter(numeric_range(start, stop, step))\n        >>> next(items)\n        datetime.datetime(2019, 1, 1, 0, 0)\n        >>> next(items)\n        datetime.datetime(2019, 1, 2, 0, 0)\n\n    \"\"\"\n\n    _EMPTY_HASH = hash(range(0, 0))\n\n    def __init__(self, *args):\n        argc = len(args)\n        if argc == 1:\n            (self._stop,) = args\n            self._start = type(self._stop)(0)\n            self._step = type(self._stop - self._start)(1)\n        elif argc == 2:\n            self._start, self._stop = args\n            self._step = type(self._stop - self._start)(1)\n        elif argc == 3:\n            self._start, self._stop, self._step = args\n        elif argc == 0:\n            raise TypeError(\n                'numeric_range expected at least '\n                '1 argument, got {}'.format(argc)\n            )\n        else:\n            raise TypeError(\n                'numeric_range expected at most '\n                '3 arguments, got {}'.format(argc)\n            )\n\n        self._zero = type(self._step)(0)\n        if self._step == self._zero:\n            raise ValueError('numeric_range() arg 3 must not be zero')\n        self._growing = self._step > self._zero\n        self._init_len()\n\n    def __bool__(self):\n        if self._growing:\n            return self._start < self._stop\n        else:\n            return self._start > self._stop\n\n    def __contains__(self, elem):\n        if self._growing:\n            if self._start <= elem < self._stop:\n                return (elem - self._start) % self._step == self._zero\n        else:\n            if self._start >= elem > self._stop:\n                return (self._start - elem) % (-self._step) == self._zero\n\n        return False\n\n    def __eq__(self, other):\n        if isinstance(other, numeric_range):\n            empty_self = not bool(self)\n            empty_other = not bool(other)\n            if empty_self or empty_other:\n                return empty_self and empty_other  # True if both empty\n            else:\n                return (\n                    self._start == other._start\n                    and self._step == other._step\n                    and self._get_by_index(-1) == other._get_by_index(-1)\n                )\n        else:\n            return False\n\n    def __getitem__(self, key):\n        if isinstance(key, int):\n            return self._get_by_index(key)\n        elif isinstance(key, slice):\n            step = self._step if key.step is None else key.step * self._step\n\n            if key.start is None or key.start <= -self._len:\n                start = self._start\n            elif key.start >= self._len:\n                start = self._stop\n            else:  # -self._len < key.start < self._len\n                start = self._get_by_index(key.start)\n\n            if key.stop is None or key.stop >= self._len:\n                stop = self._stop\n            elif key.stop <= -self._len:\n                stop = self._start\n            else:  # -self._len < key.stop < self._len\n                stop = self._get_by_index(key.stop)\n\n            return numeric_range(start, stop, step)\n        else:\n            raise TypeError(\n                'numeric range indices must be '\n                'integers or slices, not {}'.format(type(key).__name__)\n            )\n\n    def __hash__(self):\n        if self:\n            return hash((self._start, self._get_by_index(-1), self._step))\n        else:\n            return self._EMPTY_HASH\n\n    def __iter__(self):\n        values = (self._start + (n * self._step) for n in count())\n        if self._growing:\n            return takewhile(partial(gt, self._stop), values)\n        else:\n            return takewhile(partial(lt, self._stop), values)\n\n    def __len__(self):\n        return self._len\n\n    def _init_len(self):\n        if self._growing:\n            start = self._start\n            stop = self._stop\n            step = self._step\n        else:\n            start = self._stop\n            stop = self._start\n            step = -self._step\n        distance = stop - start\n        if distance <= self._zero:\n            self._len = 0\n        else:  # distance > 0 and step > 0: regular euclidean division\n            q, r = divmod(distance, step)\n            self._len = int(q) + int(r != self._zero)\n\n    def __reduce__(self):\n        return numeric_range, (self._start, self._stop, self._step)\n\n    def __repr__(self):\n        if self._step == 1:\n            return \"numeric_range({}, {})\".format(\n                repr(self._start), repr(self._stop)\n            )\n        else:\n            return \"numeric_range({}, {}, {})\".format(\n                repr(self._start), repr(self._stop), repr(self._step)\n            )\n\n    def __reversed__(self):\n        return iter(\n            numeric_range(\n                self._get_by_index(-1), self._start - self._step, -self._step\n            )\n        )\n\n    def count(self, value):\n        return int(value in self)\n\n    def index(self, value):\n        if self._growing:\n            if self._start <= value < self._stop:\n                q, r = divmod(value - self._start, self._step)\n                if r == self._zero:\n                    return int(q)\n        else:\n            if self._start >= value > self._stop:\n                q, r = divmod(self._start - value, -self._step)\n                if r == self._zero:\n                    return int(q)\n\n        raise ValueError(\"{} is not in numeric range\".format(value))\n\n    def _get_by_index(self, i):\n        if i < 0:\n            i += self._len\n        if i < 0 or i >= self._len:\n            raise IndexError(\"numeric range object index out of range\")\n        return self._start + i * self._step\n\n\ndef count_cycle(iterable, n=None):\n    \"\"\"Cycle through the items from *iterable* up to *n* times, yielding\n    the number of completed cycles along with each item. If *n* is omitted the\n    process repeats indefinitely.\n\n    >>> list(count_cycle('AB', 3))\n    [(0, 'A'), (0, 'B'), (1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]\n\n    \"\"\"\n    iterable = tuple(iterable)\n    if not iterable:\n        return iter(())\n    counter = count() if n is None else range(n)\n    return ((i, item) for i in counter for item in iterable)\n\n\ndef mark_ends(iterable):\n    \"\"\"Yield 3-tuples of the form ``(is_first, is_last, item)``.\n\n    >>> list(mark_ends('ABC'))\n    [(True, False, 'A'), (False, False, 'B'), (False, True, 'C')]\n\n    Use this when looping over an iterable to take special action on its first\n    and/or last items:\n\n    >>> iterable = ['Header', 100, 200, 'Footer']\n    >>> total = 0\n    >>> for is_first, is_last, item in mark_ends(iterable):\n    ...     if is_first:\n    ...         continue  # Skip the header\n    ...     if is_last:\n    ...         continue  # Skip the footer\n    ...     total += item\n    >>> print(total)\n    300\n    \"\"\"\n    it = iter(iterable)\n\n    try:\n        b = next(it)\n    except StopIteration:\n        return\n\n    try:\n        for i in count():\n            a = b\n            b = next(it)\n            yield i == 0, False, a\n\n    except StopIteration:\n        yield i == 0, True, a\n\n\ndef locate(iterable, pred=bool, window_size=None):\n    \"\"\"Yield the index of each item in *iterable* for which *pred* returns\n    ``True``.\n\n    *pred* defaults to :func:`bool`, which will select truthy items:\n\n        >>> list(locate([0, 1, 1, 0, 1, 0, 0]))\n        [1, 2, 4]\n\n    Set *pred* to a custom function to, e.g., find the indexes for a particular\n    item.\n\n        >>> list(locate(['a', 'b', 'c', 'b'], lambda x: x == 'b'))\n        [1, 3]\n\n    If *window_size* is given, then the *pred* function will be called with\n    that many items. This enables searching for sub-sequences:\n\n        >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]\n        >>> pred = lambda *args: args == (1, 2, 3)\n        >>> list(locate(iterable, pred=pred, window_size=3))\n        [1, 5, 9]\n\n    Use with :func:`seekable` to find indexes and then retrieve the associated\n    items:\n\n        >>> from itertools import count\n        >>> from more_itertools import seekable\n        >>> source = (3 * n + 1 if (n % 2) else n // 2 for n in count())\n        >>> it = seekable(source)\n        >>> pred = lambda x: x > 100\n        >>> indexes = locate(it, pred=pred)\n        >>> i = next(indexes)\n        >>> it.seek(i)\n        >>> next(it)\n        106\n\n    \"\"\"\n    if window_size is None:\n        return compress(count(), map(pred, iterable))\n\n    if window_size < 1:\n        raise ValueError('window size must be at least 1')\n\n    it = windowed(iterable, window_size, fillvalue=_marker)\n    return compress(count(), starmap(pred, it))\n\n\ndef lstrip(iterable, pred):\n    \"\"\"Yield the items from *iterable*, but strip any from the beginning\n    for which *pred* returns ``True``.\n\n    For example, to remove a set of items from the start of an iterable:\n\n        >>> iterable = (None, False, None, 1, 2, None, 3, False, None)\n        >>> pred = lambda x: x in {None, False, ''}\n        >>> list(lstrip(iterable, pred))\n        [1, 2, None, 3, False, None]\n\n    This function is analogous to to :func:`str.lstrip`, and is essentially\n    an wrapper for :func:`itertools.dropwhile`.\n\n    \"\"\"\n    return dropwhile(pred, iterable)\n\n\ndef rstrip(iterable, pred):\n    \"\"\"Yield the items from *iterable*, but strip any from the end\n    for which *pred* returns ``True``.\n\n    For example, to remove a set of items from the end of an iterable:\n\n        >>> iterable = (None, False, None, 1, 2, None, 3, False, None)\n        >>> pred = lambda x: x in {None, False, ''}\n        >>> list(rstrip(iterable, pred))\n        [None, False, None, 1, 2, None, 3]\n\n    This function is analogous to :func:`str.rstrip`.\n\n    \"\"\"\n    cache = []\n    cache_append = cache.append\n    cache_clear = cache.clear\n    for x in iterable:\n        if pred(x):\n            cache_append(x)\n        else:\n            yield from cache\n            cache_clear()\n            yield x\n\n\ndef strip(iterable, pred):\n    \"\"\"Yield the items from *iterable*, but strip any from the\n    beginning and end for which *pred* returns ``True``.\n\n    For example, to remove a set of items from both ends of an iterable:\n\n        >>> iterable = (None, False, None, 1, 2, None, 3, False, None)\n        >>> pred = lambda x: x in {None, False, ''}\n        >>> list(strip(iterable, pred))\n        [1, 2, None, 3]\n\n    This function is analogous to :func:`str.strip`.\n\n    \"\"\"\n    return rstrip(lstrip(iterable, pred), pred)\n\n\nclass islice_extended:\n    \"\"\"An extension of :func:`itertools.islice` that supports negative values\n    for *stop*, *start*, and *step*.\n\n        >>> iterable = iter('abcdefgh')\n        >>> list(islice_extended(iterable, -4, -1))\n        ['e', 'f', 'g']\n\n    Slices with negative values require some caching of *iterable*, but this\n    function takes care to minimize the amount of memory required.\n\n    For example, you can use a negative step with an infinite iterator:\n\n        >>> from itertools import count\n        >>> list(islice_extended(count(), 110, 99, -2))\n        [110, 108, 106, 104, 102, 100]\n\n    You can also use slice notation directly:\n\n        >>> iterable = map(str, count())\n        >>> it = islice_extended(iterable)[10:20:2]\n        >>> list(it)\n        ['10', '12', '14', '16', '18']\n\n    \"\"\"\n\n    def __init__(self, iterable, *args):\n        it = iter(iterable)\n        if args:\n            self._iterable = _islice_helper(it, slice(*args))\n        else:\n            self._iterable = it\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        return next(self._iterable)\n\n    def __getitem__(self, key):\n        if isinstance(key, slice):\n            return islice_extended(_islice_helper(self._iterable, key))\n\n        raise TypeError('islice_extended.__getitem__ argument must be a slice')\n\n\ndef _islice_helper(it, s):\n    start = s.start\n    stop = s.stop\n    if s.step == 0:\n        raise ValueError('step argument must be a non-zero integer or None.')\n    step = s.step or 1\n\n    if step > 0:\n        start = 0 if (start is None) else start\n\n        if start < 0:\n            # Consume all but the last -start items\n            cache = deque(enumerate(it, 1), maxlen=-start)\n            len_iter = cache[-1][0] if cache else 0\n\n            # Adjust start to be positive\n            i = max(len_iter + start, 0)\n\n            # Adjust stop to be positive\n            if stop is None:\n                j = len_iter\n            elif stop >= 0:\n                j = min(stop, len_iter)\n            else:\n                j = max(len_iter + stop, 0)\n\n            # Slice the cache\n            n = j - i\n            if n <= 0:\n                return\n\n            for index, item in islice(cache, 0, n, step):\n                yield item\n        elif (stop is not None) and (stop < 0):\n            # Advance to the start position\n            next(islice(it, start, start), None)\n\n            # When stop is negative, we have to carry -stop items while\n            # iterating\n            cache = deque(islice(it, -stop), maxlen=-stop)\n\n            for index, item in enumerate(it):\n                cached_item = cache.popleft()\n                if index % step == 0:\n                    yield cached_item\n                cache.append(item)\n        else:\n            # When both start and stop are positive we have the normal case\n            yield from islice(it, start, stop, step)\n    else:\n        start = -1 if (start is None) else start\n\n        if (stop is not None) and (stop < 0):\n            # Consume all but the last items\n            n = -stop - 1\n            cache = deque(enumerate(it, 1), maxlen=n)\n            len_iter = cache[-1][0] if cache else 0\n\n            # If start and stop are both negative they are comparable and\n            # we can just slice. Otherwise we can adjust start to be negative\n            # and then slice.\n            if start < 0:\n                i, j = start, stop\n            else:\n                i, j = min(start - len_iter, -1), None\n\n            for index, item in list(cache)[i:j:step]:\n                yield item\n        else:\n            # Advance to the stop position\n            if stop is not None:\n                m = stop + 1\n                next(islice(it, m, m), None)\n\n            # stop is positive, so if start is negative they are not comparable\n            # and we need the rest of the items.\n            if start < 0:\n                i = start\n                n = None\n            # stop is None and start is positive, so we just need items up to\n            # the start index.\n            elif stop is None:\n                i = None\n                n = start + 1\n            # Both stop and start are positive, so they are comparable.\n            else:\n                i = None\n                n = start - stop\n                if n <= 0:\n                    return\n\n            cache = list(islice(it, n))\n\n            yield from cache[i::step]\n\n\ndef always_reversible(iterable):\n    \"\"\"An extension of :func:`reversed` that supports all iterables, not\n    just those which implement the ``Reversible`` or ``Sequence`` protocols.\n\n        >>> print(*always_reversible(x for x in range(3)))\n        2 1 0\n\n    If the iterable is already reversible, this function returns the\n    result of :func:`reversed()`. If the iterable is not reversible,\n    this function will cache the remaining items in the iterable and\n    yield them in reverse order, which may require significant storage.\n    \"\"\"\n    try:\n        return reversed(iterable)\n    except TypeError:\n        return reversed(list(iterable))\n\n\ndef consecutive_groups(iterable, ordering=lambda x: x):\n    \"\"\"Yield groups of consecutive items using :func:`itertools.groupby`.\n    The *ordering* function determines whether two items are adjacent by\n    returning their position.\n\n    By default, the ordering function is the identity function. This is\n    suitable for finding runs of numbers:\n\n        >>> iterable = [1, 10, 11, 12, 20, 30, 31, 32, 33, 40]\n        >>> for group in consecutive_groups(iterable):\n        ...     print(list(group))\n        [1]\n        [10, 11, 12]\n        [20]\n        [30, 31, 32, 33]\n        [40]\n\n    For finding runs of adjacent letters, try using the :meth:`index` method\n    of a string of letters:\n\n        >>> from string import ascii_lowercase\n        >>> iterable = 'abcdfgilmnop'\n        >>> ordering = ascii_lowercase.index\n        >>> for group in consecutive_groups(iterable, ordering):\n        ...     print(list(group))\n        ['a', 'b', 'c', 'd']\n        ['f', 'g']\n        ['i']\n        ['l', 'm', 'n', 'o', 'p']\n\n    Each group of consecutive items is an iterator that shares it source with\n    *iterable*. When an an output group is advanced, the previous group is\n    no longer available unless its elements are copied (e.g., into a ``list``).\n\n        >>> iterable = [1, 2, 11, 12, 21, 22]\n        >>> saved_groups = []\n        >>> for group in consecutive_groups(iterable):\n        ...     saved_groups.append(list(group))  # Copy group elements\n        >>> saved_groups\n        [[1, 2], [11, 12], [21, 22]]\n\n    \"\"\"\n    for k, g in groupby(\n        enumerate(iterable), key=lambda x: x[0] - ordering(x[1])\n    ):\n        yield map(itemgetter(1), g)\n\n\ndef difference(iterable, func=sub, *, initial=None):\n    \"\"\"This function is the inverse of :func:`itertools.accumulate`. By default\n    it will compute the first difference of *iterable* using\n    :func:`operator.sub`:\n\n        >>> from itertools import accumulate\n        >>> iterable = accumulate([0, 1, 2, 3, 4])  # produces 0, 1, 3, 6, 10\n        >>> list(difference(iterable))\n        [0, 1, 2, 3, 4]\n\n    *func* defaults to :func:`operator.sub`, but other functions can be\n    specified. They will be applied as follows::\n\n        A, B, C, D, ... --> A, func(B, A), func(C, B), func(D, C), ...\n\n    For example, to do progressive division:\n\n        >>> iterable = [1, 2, 6, 24, 120]\n        >>> func = lambda x, y: x // y\n        >>> list(difference(iterable, func))\n        [1, 2, 3, 4, 5]\n\n    If the *initial* keyword is set, the first element will be skipped when\n    computing successive differences.\n\n        >>> it = [10, 11, 13, 16]  # from accumulate([1, 2, 3], initial=10)\n        >>> list(difference(it, initial=10))\n        [1, 2, 3]\n\n    \"\"\"\n    a, b = tee(iterable)\n    try:\n        first = [next(b)]\n    except StopIteration:\n        return iter([])\n\n    if initial is not None:\n        first = []\n\n    return chain(first, starmap(func, zip(b, a)))\n\n\nclass SequenceView(Sequence):\n    \"\"\"Return a read-only view of the sequence object *target*.\n\n    :class:`SequenceView` objects are analogous to Python's built-in\n    \"dictionary view\" types. They provide a dynamic view of a sequence's items,\n    meaning that when the sequence updates, so does the view.\n\n        >>> seq = ['0', '1', '2']\n        >>> view = SequenceView(seq)\n        >>> view\n        SequenceView(['0', '1', '2'])\n        >>> seq.append('3')\n        >>> view\n        SequenceView(['0', '1', '2', '3'])\n\n    Sequence views support indexing, slicing, and length queries. They act\n    like the underlying sequence, except they don't allow assignment:\n\n        >>> view[1]\n        '1'\n        >>> view[1:-1]\n        ['1', '2']\n        >>> len(view)\n        4\n\n    Sequence views are useful as an alternative to copying, as they don't\n    require (much) extra storage.\n\n    \"\"\"\n\n    def __init__(self, target):\n        if not isinstance(target, Sequence):\n            raise TypeError\n        self._target = target\n\n    def __getitem__(self, index):\n        return self._target[index]\n\n    def __len__(self):\n        return len(self._target)\n\n    def __repr__(self):\n        return '{}({})'.format(self.__class__.__name__, repr(self._target))\n\n\nclass seekable:\n    \"\"\"Wrap an iterator to allow for seeking backward and forward. This\n    progressively caches the items in the source iterable so they can be\n    re-visited.\n\n    Call :meth:`seek` with an index to seek to that position in the source\n    iterable.\n\n    To \"reset\" an iterator, seek to ``0``:\n\n        >>> from itertools import count\n        >>> it = seekable((str(n) for n in count()))\n        >>> next(it), next(it), next(it)\n        ('0', '1', '2')\n        >>> it.seek(0)\n        >>> next(it), next(it), next(it)\n        ('0', '1', '2')\n        >>> next(it)\n        '3'\n\n    You can also seek forward:\n\n        >>> it = seekable((str(n) for n in range(20)))\n        >>> it.seek(10)\n        >>> next(it)\n        '10'\n        >>> it.seek(20)  # Seeking past the end of the source isn't a problem\n        >>> list(it)\n        []\n        >>> it.seek(0)  # Resetting works even after hitting the end\n        >>> next(it), next(it), next(it)\n        ('0', '1', '2')\n\n    Call :meth:`peek` to look ahead one item without advancing the iterator:\n\n        >>> it = seekable('1234')\n        >>> it.peek()\n        '1'\n        >>> list(it)\n        ['1', '2', '3', '4']\n        >>> it.peek(default='empty')\n        'empty'\n\n    Before the iterator is at its end, calling :func:`bool` on it will return\n    ``True``. After it will return ``False``:\n\n        >>> it = seekable('5678')\n        >>> bool(it)\n        True\n        >>> list(it)\n        ['5', '6', '7', '8']\n        >>> bool(it)\n        False\n\n    You may view the contents of the cache with the :meth:`elements` method.\n    That returns a :class:`SequenceView`, a view that updates automatically:\n\n        >>> it = seekable((str(n) for n in range(10)))\n        >>> next(it), next(it), next(it)\n        ('0', '1', '2')\n        >>> elements = it.elements()\n        >>> elements\n        SequenceView(['0', '1', '2'])\n        >>> next(it)\n        '3'\n        >>> elements\n        SequenceView(['0', '1', '2', '3'])\n\n    By default, the cache grows as the source iterable progresses, so beware of\n    wrapping very large or infinite iterables. Supply *maxlen* to limit the\n    size of the cache (this of course limits how far back you can seek).\n\n        >>> from itertools import count\n        >>> it = seekable((str(n) for n in count()), maxlen=2)\n        >>> next(it), next(it), next(it), next(it)\n        ('0', '1', '2', '3')\n        >>> list(it.elements())\n        ['2', '3']\n        >>> it.seek(0)\n        >>> next(it), next(it), next(it), next(it)\n        ('2', '3', '4', '5')\n        >>> next(it)\n        '6'\n\n    \"\"\"\n\n    def __init__(self, iterable, maxlen=None):\n        self._source = iter(iterable)\n        if maxlen is None:\n            self._cache = []\n        else:\n            self._cache = deque([], maxlen)\n        self._index = None\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        if self._index is not None:\n            try:\n                item = self._cache[self._index]\n            except IndexError:\n                self._index = None\n            else:\n                self._index += 1\n                return item\n\n        item = next(self._source)\n        self._cache.append(item)\n        return item\n\n    def __bool__(self):\n        try:\n            self.peek()\n        except StopIteration:\n            return False\n        return True\n\n    def peek(self, default=_marker):\n        try:\n            peeked = next(self)\n        except StopIteration:\n            if default is _marker:\n                raise\n            return default\n        if self._index is None:\n            self._index = len(self._cache)\n        self._index -= 1\n        return peeked\n\n    def elements(self):\n        return SequenceView(self._cache)\n\n    def seek(self, index):\n        self._index = index\n        remainder = index - len(self._cache)\n        if remainder > 0:\n            consume(self, remainder)\n\n\nclass run_length:\n    \"\"\"\n    :func:`run_length.encode` compresses an iterable with run-length encoding.\n    It yields groups of repeated items with the count of how many times they\n    were repeated:\n\n        >>> uncompressed = 'abbcccdddd'\n        >>> list(run_length.encode(uncompressed))\n        [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n\n    :func:`run_length.decode` decompresses an iterable that was previously\n    compressed with run-length encoding. It yields the items of the\n    decompressed iterable:\n\n        >>> compressed = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n        >>> list(run_length.decode(compressed))\n        ['a', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd', 'd']\n\n    \"\"\"\n\n    @staticmethod\n    def encode(iterable):\n        return ((k, ilen(g)) for k, g in groupby(iterable))\n\n    @staticmethod\n    def decode(iterable):\n        return chain.from_iterable(repeat(k, n) for k, n in iterable)\n\n\ndef exactly_n(iterable, n, predicate=bool):\n    \"\"\"Return ``True`` if exactly ``n`` items in the iterable are ``True``\n    according to the *predicate* function.\n\n        >>> exactly_n([True, True, False], 2)\n        True\n        >>> exactly_n([True, True, False], 1)\n        False\n        >>> exactly_n([0, 1, 2, 3, 4, 5], 3, lambda x: x < 3)\n        True\n\n    The iterable will be advanced until ``n + 1`` truthy items are encountered,\n    so avoid calling it on infinite iterables.\n\n    \"\"\"\n    return len(take(n + 1, filter(predicate, iterable))) == n\n\n\ndef circular_shifts(iterable):\n    \"\"\"Return a list of circular shifts of *iterable*.\n\n    >>> circular_shifts(range(4))\n    [(0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2)]\n    \"\"\"\n    lst = list(iterable)\n    return take(len(lst), windowed(cycle(lst), len(lst)))\n\n\ndef make_decorator(wrapping_func, result_index=0):\n    \"\"\"Return a decorator version of *wrapping_func*, which is a function that\n    modifies an iterable. *result_index* is the position in that function's\n    signature where the iterable goes.\n\n    This lets you use itertools on the \"production end,\" i.e. at function\n    definition. This can augment what the function returns without changing the\n    function's code.\n\n    For example, to produce a decorator version of :func:`chunked`:\n\n        >>> from more_itertools import chunked\n        >>> chunker = make_decorator(chunked, result_index=0)\n        >>> @chunker(3)\n        ... def iter_range(n):\n        ...     return iter(range(n))\n        ...\n        >>> list(iter_range(9))\n        [[0, 1, 2], [3, 4, 5], [6, 7, 8]]\n\n    To only allow truthy items to be returned:\n\n        >>> truth_serum = make_decorator(filter, result_index=1)\n        >>> @truth_serum(bool)\n        ... def boolean_test():\n        ...     return [0, 1, '', ' ', False, True]\n        ...\n        >>> list(boolean_test())\n        [1, ' ', True]\n\n    The :func:`peekable` and :func:`seekable` wrappers make for practical\n    decorators:\n\n        >>> from more_itertools import peekable\n        >>> peekable_function = make_decorator(peekable)\n        >>> @peekable_function()\n        ... def str_range(*args):\n        ...     return (str(x) for x in range(*args))\n        ...\n        >>> it = str_range(1, 20, 2)\n        >>> next(it), next(it), next(it)\n        ('1', '3', '5')\n        >>> it.peek()\n        '7'\n        >>> next(it)\n        '7'\n\n    \"\"\"\n    # See https://sites.google.com/site/bbayles/index/decorator_factory for\n    # notes on how this works.\n    def decorator(*wrapping_args, **wrapping_kwargs):\n        def outer_wrapper(f):\n            def inner_wrapper(*args, **kwargs):\n                result = f(*args, **kwargs)\n                wrapping_args_ = list(wrapping_args)\n                wrapping_args_.insert(result_index, result)\n                return wrapping_func(*wrapping_args_, **wrapping_kwargs)\n\n            return inner_wrapper\n\n        return outer_wrapper\n\n    return decorator\n\n\ndef map_reduce(iterable, keyfunc, valuefunc=None, reducefunc=None):\n    \"\"\"Return a dictionary that maps the items in *iterable* to categories\n    defined by *keyfunc*, transforms them with *valuefunc*, and\n    then summarizes them by category with *reducefunc*.\n\n    *valuefunc* defaults to the identity function if it is unspecified.\n    If *reducefunc* is unspecified, no summarization takes place:\n\n        >>> keyfunc = lambda x: x.upper()\n        >>> result = map_reduce('abbccc', keyfunc)\n        >>> sorted(result.items())\n        [('A', ['a']), ('B', ['b', 'b']), ('C', ['c', 'c', 'c'])]\n\n    Specifying *valuefunc* transforms the categorized items:\n\n        >>> keyfunc = lambda x: x.upper()\n        >>> valuefunc = lambda x: 1\n        >>> result = map_reduce('abbccc', keyfunc, valuefunc)\n        >>> sorted(result.items())\n        [('A', [1]), ('B', [1, 1]), ('C', [1, 1, 1])]\n\n    Specifying *reducefunc* summarizes the categorized items:\n\n        >>> keyfunc = lambda x: x.upper()\n        >>> valuefunc = lambda x: 1\n        >>> reducefunc = sum\n        >>> result = map_reduce('abbccc', keyfunc, valuefunc, reducefunc)\n        >>> sorted(result.items())\n        [('A', 1), ('B', 2), ('C', 3)]\n\n    You may want to filter the input iterable before applying the map/reduce\n    procedure:\n\n        >>> all_items = range(30)\n        >>> items = [x for x in all_items if 10 <= x <= 20]  # Filter\n        >>> keyfunc = lambda x: x % 2  # Evens map to 0; odds to 1\n        >>> categories = map_reduce(items, keyfunc=keyfunc)\n        >>> sorted(categories.items())\n        [(0, [10, 12, 14, 16, 18, 20]), (1, [11, 13, 15, 17, 19])]\n        >>> summaries = map_reduce(items, keyfunc=keyfunc, reducefunc=sum)\n        >>> sorted(summaries.items())\n        [(0, 90), (1, 75)]\n\n    Note that all items in the iterable are gathered into a list before the\n    summarization step, which may require significant storage.\n\n    The returned object is a :obj:`collections.defaultdict` with the\n    ``default_factory`` set to ``None``, such that it behaves like a normal\n    dictionary.\n\n    \"\"\"\n    valuefunc = (lambda x: x) if (valuefunc is None) else valuefunc\n\n    ret = defaultdict(list)\n    for item in iterable:\n        key = keyfunc(item)\n        value = valuefunc(item)\n        ret[key].append(value)\n\n    if reducefunc is not None:\n        for key, value_list in ret.items():\n            ret[key] = reducefunc(value_list)\n\n    ret.default_factory = None\n    return ret\n\n\ndef rlocate(iterable, pred=bool, window_size=None):\n    \"\"\"Yield the index of each item in *iterable* for which *pred* returns\n    ``True``, starting from the right and moving left.\n\n    *pred* defaults to :func:`bool`, which will select truthy items:\n\n        >>> list(rlocate([0, 1, 1, 0, 1, 0, 0]))  # Truthy at 1, 2, and 4\n        [4, 2, 1]\n\n    Set *pred* to a custom function to, e.g., find the indexes for a particular\n    item:\n\n        >>> iterable = iter('abcb')\n        >>> pred = lambda x: x == 'b'\n        >>> list(rlocate(iterable, pred))\n        [3, 1]\n\n    If *window_size* is given, then the *pred* function will be called with\n    that many items. This enables searching for sub-sequences:\n\n        >>> iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]\n        >>> pred = lambda *args: args == (1, 2, 3)\n        >>> list(rlocate(iterable, pred=pred, window_size=3))\n        [9, 5, 1]\n\n    Beware, this function won't return anything for infinite iterables.\n    If *iterable* is reversible, ``rlocate`` will reverse it and search from\n    the right. Otherwise, it will search from the left and return the results\n    in reverse order.\n\n    See :func:`locate` to for other example applications.\n\n    \"\"\"\n    if window_size is None:\n        try:\n            len_iter = len(iterable)\n            return (len_iter - i - 1 for i in locate(reversed(iterable), pred))\n        except TypeError:\n            pass\n\n    return reversed(list(locate(iterable, pred, window_size)))\n\n\ndef replace(iterable, pred, substitutes, count=None, window_size=1):\n    \"\"\"Yield the items from *iterable*, replacing the items for which *pred*\n    returns ``True`` with the items from the iterable *substitutes*.\n\n        >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1]\n        >>> pred = lambda x: x == 0\n        >>> substitutes = (2, 3)\n        >>> list(replace(iterable, pred, substitutes))\n        [1, 1, 2, 3, 1, 1, 2, 3, 1, 1]\n\n    If *count* is given, the number of replacements will be limited:\n\n        >>> iterable = [1, 1, 0, 1, 1, 0, 1, 1, 0]\n        >>> pred = lambda x: x == 0\n        >>> substitutes = [None]\n        >>> list(replace(iterable, pred, substitutes, count=2))\n        [1, 1, None, 1, 1, None, 1, 1, 0]\n\n    Use *window_size* to control the number of items passed as arguments to\n    *pred*. This allows for locating and replacing subsequences.\n\n        >>> iterable = [0, 1, 2, 5, 0, 1, 2, 5]\n        >>> window_size = 3\n        >>> pred = lambda *args: args == (0, 1, 2)  # 3 items passed to pred\n        >>> substitutes = [3, 4] # Splice in these items\n        >>> list(replace(iterable, pred, substitutes, window_size=window_size))\n        [3, 4, 5, 3, 4, 5]\n\n    \"\"\"\n    if window_size < 1:\n        raise ValueError('window_size must be at least 1')\n\n    # Save the substitutes iterable, since it's used more than once\n    substitutes = tuple(substitutes)\n\n    # Add padding such that the number of windows matches the length of the\n    # iterable\n    it = chain(iterable, [_marker] * (window_size - 1))\n    windows = windowed(it, window_size)\n\n    n = 0\n    for w in windows:\n        # If the current window matches our predicate (and we haven't hit\n        # our maximum number of replacements), splice in the substitutes\n        # and then consume the following windows that overlap with this one.\n        # For example, if the iterable is (0, 1, 2, 3, 4...)\n        # and the window size is 2, we have (0, 1), (1, 2), (2, 3)...\n        # If the predicate matches on (0, 1), we need to zap (0, 1) and (1, 2)\n        if pred(*w):\n            if (count is None) or (n < count):\n                n += 1\n                yield from substitutes\n                consume(windows, window_size - 1)\n                continue\n\n        # If there was no match (or we've reached the replacement limit),\n        # yield the first item from the window.\n        if w and (w[0] is not _marker):\n            yield w[0]\n\n\ndef partitions(iterable):\n    \"\"\"Yield all possible order-preserving partitions of *iterable*.\n\n    >>> iterable = 'abc'\n    >>> for part in partitions(iterable):\n    ...     print([''.join(p) for p in part])\n    ['abc']\n    ['a', 'bc']\n    ['ab', 'c']\n    ['a', 'b', 'c']\n\n    This is unrelated to :func:`partition`.\n\n    \"\"\"\n    sequence = list(iterable)\n    n = len(sequence)\n    for i in powerset(range(1, n)):\n        yield [sequence[i:j] for i, j in zip((0,) + i, i + (n,))]\n\n\ndef set_partitions(iterable, k=None):\n    \"\"\"\n    Yield the set partitions of *iterable* into *k* parts. Set partitions are\n    not order-preserving.\n\n    >>> iterable = 'abc'\n    >>> for part in set_partitions(iterable, 2):\n    ...     print([''.join(p) for p in part])\n    ['a', 'bc']\n    ['ab', 'c']\n    ['b', 'ac']\n\n\n    If *k* is not given, every set partition is generated.\n\n    >>> iterable = 'abc'\n    >>> for part in set_partitions(iterable):\n    ...     print([''.join(p) for p in part])\n    ['abc']\n    ['a', 'bc']\n    ['ab', 'c']\n    ['b', 'ac']\n    ['a', 'b', 'c']\n\n    \"\"\"\n    L = list(iterable)\n    n = len(L)\n    if k is not None:\n        if k < 1:\n            raise ValueError(\n                \"Can't partition in a negative or zero number of groups\"\n            )\n        elif k > n:\n            return\n\n    def set_partitions_helper(L, k):\n        n = len(L)\n        if k == 1:\n            yield [L]\n        elif n == k:\n            yield [[s] for s in L]\n        else:\n            e, *M = L\n            for p in set_partitions_helper(M, k - 1):\n                yield [[e], *p]\n            for p in set_partitions_helper(M, k):\n                for i in range(len(p)):\n                    yield p[:i] + [[e] + p[i]] + p[i + 1 :]\n\n    if k is None:\n        for k in range(1, n + 1):\n            yield from set_partitions_helper(L, k)\n    else:\n        yield from set_partitions_helper(L, k)\n\n\nclass time_limited:\n    \"\"\"\n    Yield items from *iterable* until *limit_seconds* have passed.\n    If the time limit expires before all items have been yielded, the\n    ``timed_out`` parameter will be set to ``True``.\n\n    >>> from time import sleep\n    >>> def generator():\n    ...     yield 1\n    ...     yield 2\n    ...     sleep(0.2)\n    ...     yield 3\n    >>> iterable = time_limited(0.1, generator())\n    >>> list(iterable)\n    [1, 2]\n    >>> iterable.timed_out\n    True\n\n    Note that the time is checked before each item is yielded, and iteration\n    stops if  the time elapsed is greater than *limit_seconds*. If your time\n    limit is 1 second, but it takes 2 seconds to generate the first item from\n    the iterable, the function will run for 2 seconds and not yield anything.\n\n    \"\"\"\n\n    def __init__(self, limit_seconds, iterable):\n        if limit_seconds < 0:\n            raise ValueError('limit_seconds must be positive')\n        self.limit_seconds = limit_seconds\n        self._iterable = iter(iterable)\n        self._start_time = monotonic()\n        self.timed_out = False\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        item = next(self._iterable)\n        if monotonic() - self._start_time > self.limit_seconds:\n            self.timed_out = True\n            raise StopIteration\n\n        return item\n\n\ndef only(iterable, default=None, too_long=None):\n    \"\"\"If *iterable* has only one item, return it.\n    If it has zero items, return *default*.\n    If it has more than one item, raise the exception given by *too_long*,\n    which is ``ValueError`` by default.\n\n    >>> only([], default='missing')\n    'missing'\n    >>> only([1])\n    1\n    >>> only([1, 2])  # doctest: +IGNORE_EXCEPTION_DETAIL\n    Traceback (most recent call last):\n    ...\n    ValueError: Expected exactly one item in iterable, but got 1, 2,\n     and perhaps more.'\n    >>> only([1, 2], too_long=TypeError)  # doctest: +IGNORE_EXCEPTION_DETAIL\n    Traceback (most recent call last):\n    ...\n    TypeError\n\n    Note that :func:`only` attempts to advance *iterable* twice to ensure there\n    is only one item.  See :func:`spy` or :func:`peekable` to check\n    iterable contents less destructively.\n    \"\"\"\n    it = iter(iterable)\n    first_value = next(it, default)\n\n    try:\n        second_value = next(it)\n    except StopIteration:\n        pass\n    else:\n        msg = (\n            'Expected exactly one item in iterable, but got {!r}, {!r}, '\n            'and perhaps more.'.format(first_value, second_value)\n        )\n        raise too_long or ValueError(msg)\n\n    return first_value\n\n\ndef ichunked(iterable, n):\n    \"\"\"Break *iterable* into sub-iterables with *n* elements each.\n    :func:`ichunked` is like :func:`chunked`, but it yields iterables\n    instead of lists.\n\n    If the sub-iterables are read in order, the elements of *iterable*\n    won't be stored in memory.\n    If they are read out of order, :func:`itertools.tee` is used to cache\n    elements as necessary.\n\n    >>> from itertools import count\n    >>> all_chunks = ichunked(count(), 4)\n    >>> c_1, c_2, c_3 = next(all_chunks), next(all_chunks), next(all_chunks)\n    >>> list(c_2)  # c_1's elements have been cached; c_3's haven't been\n    [4, 5, 6, 7]\n    >>> list(c_1)\n    [0, 1, 2, 3]\n    >>> list(c_3)\n    [8, 9, 10, 11]\n\n    \"\"\"\n    source = iter(iterable)\n\n    while True:\n        # Check to see whether we're at the end of the source iterable\n        item = next(source, _marker)\n        if item is _marker:\n            return\n\n        # Clone the source and yield an n-length slice\n        source, it = tee(chain([item], source))\n        yield islice(it, n)\n\n        # Advance the source iterable\n        consume(source, n)\n\n\ndef distinct_combinations(iterable, r):\n    \"\"\"Yield the distinct combinations of *r* items taken from *iterable*.\n\n        >>> list(distinct_combinations([0, 0, 1], 2))\n        [(0, 0), (0, 1)]\n\n    Equivalent to ``set(combinations(iterable))``, except duplicates are not\n    generated and thrown away. For larger input sequences this is much more\n    efficient.\n\n    \"\"\"\n    if r < 0:\n        raise ValueError('r must be non-negative')\n    elif r == 0:\n        yield ()\n        return\n    pool = tuple(iterable)\n    generators = [unique_everseen(enumerate(pool), key=itemgetter(1))]\n    current_combo = [None] * r\n    level = 0\n    while generators:\n        try:\n            cur_idx, p = next(generators[-1])\n        except StopIteration:\n            generators.pop()\n            level -= 1\n            continue\n        current_combo[level] = p\n        if level + 1 == r:\n            yield tuple(current_combo)\n        else:\n            generators.append(\n                unique_everseen(\n                    enumerate(pool[cur_idx + 1 :], cur_idx + 1),\n                    key=itemgetter(1),\n                )\n            )\n            level += 1\n\n\ndef filter_except(validator, iterable, *exceptions):\n    \"\"\"Yield the items from *iterable* for which the *validator* function does\n    not raise one of the specified *exceptions*.\n\n    *validator* is called for each item in *iterable*.\n    It should be a function that accepts one argument and raises an exception\n    if that item is not valid.\n\n    >>> iterable = ['1', '2', 'three', '4', None]\n    >>> list(filter_except(int, iterable, ValueError, TypeError))\n    ['1', '2', '4']\n\n    If an exception other than one given by *exceptions* is raised by\n    *validator*, it is raised like normal.\n    \"\"\"\n    for item in iterable:\n        try:\n            validator(item)\n        except exceptions:\n            pass\n        else:\n            yield item\n\n\ndef map_except(function, iterable, *exceptions):\n    \"\"\"Transform each item from *iterable* with *function* and yield the\n    result, unless *function* raises one of the specified *exceptions*.\n\n    *function* is called to transform each item in *iterable*.\n    It should be a accept one argument.\n\n    >>> iterable = ['1', '2', 'three', '4', None]\n    >>> list(map_except(int, iterable, ValueError, TypeError))\n    [1, 2, 4]\n\n    If an exception other than one given by *exceptions* is raised by\n    *function*, it is raised like normal.\n    \"\"\"\n    for item in iterable:\n        try:\n            yield function(item)\n        except exceptions:\n            pass\n\n\ndef _sample_unweighted(iterable, k):\n    # Implementation of \"Algorithm L\" from the 1994 paper by Kim-Hung Li:\n    # \"Reservoir-Sampling Algorithms of Time Complexity O(n(1+log(N/n)))\".\n\n    # Fill up the reservoir (collection of samples) with the first `k` samples\n    reservoir = take(k, iterable)\n\n    # Generate random number that's the largest in a sample of k U(0,1) numbers\n    # Largest order statistic: https://en.wikipedia.org/wiki/Order_statistic\n    W = exp(log(random()) / k)\n\n    # The number of elements to skip before changing the reservoir is a random\n    # number with a geometric distribution. Sample it using random() and logs.\n    next_index = k + floor(log(random()) / log(1 - W))\n\n    for index, element in enumerate(iterable, k):\n\n        if index == next_index:\n            reservoir[randrange(k)] = element\n            # The new W is the largest in a sample of k U(0, `old_W`) numbers\n            W *= exp(log(random()) / k)\n            next_index += floor(log(random()) / log(1 - W)) + 1\n\n    return reservoir\n\n\ndef _sample_weighted(iterable, k, weights):\n    # Implementation of \"A-ExpJ\" from the 2006 paper by Efraimidis et al. :\n    # \"Weighted random sampling with a reservoir\".\n\n    # Log-transform for numerical stability for weights that are small/large\n    weight_keys = (log(random()) / weight for weight in weights)\n\n    # Fill up the reservoir (collection of samples) with the first `k`\n    # weight-keys and elements, then heapify the list.\n    reservoir = take(k, zip(weight_keys, iterable))\n    heapify(reservoir)\n\n    # The number of jumps before changing the reservoir is a random variable\n    # with an exponential distribution. Sample it using random() and logs.\n    smallest_weight_key, _ = reservoir[0]\n    weights_to_skip = log(random()) / smallest_weight_key\n\n    for weight, element in zip(weights, iterable):\n        if weight >= weights_to_skip:\n            # The notation here is consistent with the paper, but we store\n            # the weight-keys in log-space for better numerical stability.\n            smallest_weight_key, _ = reservoir[0]\n            t_w = exp(weight * smallest_weight_key)\n            r_2 = uniform(t_w, 1)  # generate U(t_w, 1)\n            weight_key = log(r_2) / weight\n            heapreplace(reservoir, (weight_key, element))\n            smallest_weight_key, _ = reservoir[0]\n            weights_to_skip = log(random()) / smallest_weight_key\n        else:\n            weights_to_skip -= weight\n\n    # Equivalent to [element for weight_key, element in sorted(reservoir)]\n    return [heappop(reservoir)[1] for _ in range(k)]\n\n\ndef sample(iterable, k, weights=None):\n    \"\"\"Return a *k*-length list of elements chosen (without replacement)\n    from the *iterable*. Like :func:`random.sample`, but works on iterables\n    of unknown length.\n\n    >>> iterable = range(100)\n    >>> sample(iterable, 5)  # doctest: +SKIP\n    [81, 60, 96, 16, 4]\n\n    An iterable with *weights* may also be given:\n\n    >>> iterable = range(100)\n    >>> weights = (i * i + 1 for i in range(100))\n    >>> sampled = sample(iterable, 5, weights=weights)  # doctest: +SKIP\n    [79, 67, 74, 66, 78]\n\n    The algorithm can also be used to generate weighted random permutations.\n    The relative weight of each item determines the probability that it\n    appears late in the permutation.\n\n    >>> data = \"abcdefgh\"\n    >>> weights = range(1, len(data) + 1)\n    >>> sample(data, k=len(data), weights=weights)  # doctest: +SKIP\n    ['c', 'a', 'b', 'e', 'g', 'd', 'h', 'f']\n    \"\"\"\n    if k == 0:\n        return []\n\n    iterable = iter(iterable)\n    if weights is None:\n        return _sample_unweighted(iterable, k)\n    else:\n        weights = iter(weights)\n        return _sample_weighted(iterable, k, weights)\n\n\ndef is_sorted(iterable, key=None, reverse=False):\n    \"\"\"Returns ``True`` if the items of iterable are in sorted order, and\n    ``False`` otherwise. *key* and *reverse* have the same meaning that they do\n    in the built-in :func:`sorted` function.\n\n    >>> is_sorted(['1', '2', '3', '4', '5'], key=int)\n    True\n    >>> is_sorted([5, 4, 3, 1, 2], reverse=True)\n    False\n\n    The function returns ``False`` after encountering the first out-of-order\n    item. If there are no out-of-order items, the iterable is exhausted.\n    \"\"\"\n\n    compare = lt if reverse else gt\n    it = iterable if (key is None) else map(key, iterable)\n    return not any(starmap(compare, pairwise(it)))\n\n\nclass AbortThread(BaseException):\n    pass\n\n\nclass callback_iter:\n    \"\"\"Convert a function that uses callbacks to an iterator.\n\n    Let *func* be a function that takes a `callback` keyword argument.\n    For example:\n\n    >>> def func(callback=None):\n    ...     for i, c in [(1, 'a'), (2, 'b'), (3, 'c')]:\n    ...         if callback:\n    ...             callback(i, c)\n    ...     return 4\n\n\n    Use ``with callback_iter(func)`` to get an iterator over the parameters\n    that are delivered to the callback.\n\n    >>> with callback_iter(func) as it:\n    ...     for args, kwargs in it:\n    ...         print(args)\n    (1, 'a')\n    (2, 'b')\n    (3, 'c')\n\n    The function will be called in a background thread. The ``done`` property\n    indicates whether it has completed execution.\n\n    >>> it.done\n    True\n\n    If it completes successfully, its return value will be available\n    in the ``result`` property.\n\n    >>> it.result\n    4\n\n    Notes:\n\n    * If the function uses some keyword argument besides ``callback``, supply\n      *callback_kwd*.\n    * If it finished executing, but raised an exception, accessing the\n      ``result`` property will raise the same exception.\n    * If it hasn't finished executing, accessing the ``result``\n      property from within the ``with`` block will raise ``RuntimeError``.\n    * If it hasn't finished executing, accessing the ``result`` property from\n      outside the ``with`` block will raise a\n      ``more_itertools.AbortThread`` exception.\n    * Provide *wait_seconds* to adjust how frequently the it is polled for\n      output.\n\n    \"\"\"\n\n    def __init__(self, func, callback_kwd='callback', wait_seconds=0.1):\n        self._func = func\n        self._callback_kwd = callback_kwd\n        self._aborted = False\n        self._future = None\n        self._wait_seconds = wait_seconds\n        self._executor = __import__(\"concurrent.futures\").futures.ThreadPoolExecutor(max_workers=1)\n        self._iterator = self._reader()\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        self._aborted = True\n        self._executor.shutdown()\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        return next(self._iterator)\n\n    @property\n    def done(self):\n        if self._future is None:\n            return False\n        return self._future.done()\n\n    @property\n    def result(self):\n        if not self.done:\n            raise RuntimeError('Function has not yet completed')\n\n        return self._future.result()\n\n    def _reader(self):\n        q = Queue()\n\n        def callback(*args, **kwargs):\n            if self._aborted:\n                raise AbortThread('canceled by user')\n\n            q.put((args, kwargs))\n\n        self._future = self._executor.submit(\n            self._func, **{self._callback_kwd: callback}\n        )\n\n        while True:\n            try:\n                item = q.get(timeout=self._wait_seconds)\n            except Empty:\n                pass\n            else:\n                q.task_done()\n                yield item\n\n            if self._future.done():\n                break\n\n        remaining = []\n        while True:\n            try:\n                item = q.get_nowait()\n            except Empty:\n                break\n            else:\n                q.task_done()\n                remaining.append(item)\n        q.join()\n        yield from remaining\n\n\ndef windowed_complete(iterable, n):\n    \"\"\"\n    Yield ``(beginning, middle, end)`` tuples, where:\n\n    * Each ``middle`` has *n* items from *iterable*\n    * Each ``beginning`` has the items before the ones in ``middle``\n    * Each ``end`` has the items after the ones in ``middle``\n\n    >>> iterable = range(7)\n    >>> n = 3\n    >>> for beginning, middle, end in windowed_complete(iterable, n):\n    ...     print(beginning, middle, end)\n    () (0, 1, 2) (3, 4, 5, 6)\n    (0,) (1, 2, 3) (4, 5, 6)\n    (0, 1) (2, 3, 4) (5, 6)\n    (0, 1, 2) (3, 4, 5) (6,)\n    (0, 1, 2, 3) (4, 5, 6) ()\n\n    Note that *n* must be at least 0 and most equal to the length of\n    *iterable*.\n\n    This function will exhaust the iterable and may require significant\n    storage.\n    \"\"\"\n    if n < 0:\n        raise ValueError('n must be >= 0')\n\n    seq = tuple(iterable)\n    size = len(seq)\n\n    if n > size:\n        raise ValueError('n must be <= len(seq)')\n\n    for i in range(size - n + 1):\n        beginning = seq[:i]\n        middle = seq[i : i + n]\n        end = seq[i + n :]\n        yield beginning, middle, end\n\n\ndef all_unique(iterable, key=None):\n    \"\"\"\n    Returns ``True`` if all the elements of *iterable* are unique (no two\n    elements are equal).\n\n        >>> all_unique('ABCB')\n        False\n\n    If a *key* function is specified, it will be used to make comparisons.\n\n        >>> all_unique('ABCb')\n        True\n        >>> all_unique('ABCb', str.lower)\n        False\n\n    The function returns as soon as the first non-unique element is\n    encountered. Iterables with a mix of hashable and unhashable items can\n    be used, but the function will be slower for unhashable items.\n    \"\"\"\n    seenset = set()\n    seenset_add = seenset.add\n    seenlist = []\n    seenlist_add = seenlist.append\n    for element in map(key, iterable) if key else iterable:\n        try:\n            if element in seenset:\n                return False\n            seenset_add(element)\n        except TypeError:\n            if element in seenlist:\n                return False\n            seenlist_add(element)\n    return True\n\n\ndef nth_product(index, *args):\n    \"\"\"Equivalent to ``list(product(*args))[index]``.\n\n    The products of *args* can be ordered lexicographically.\n    :func:`nth_product` computes the product at sort position *index* without\n    computing the previous products.\n\n        >>> nth_product(8, range(2), range(2), range(2), range(2))\n        (1, 0, 0, 0)\n\n    ``IndexError`` will be raised if the given *index* is invalid.\n    \"\"\"\n    pools = list(map(tuple, reversed(args)))\n    ns = list(map(len, pools))\n\n    c = reduce(mul, ns)\n\n    if index < 0:\n        index += c\n\n    if not 0 <= index < c:\n        raise IndexError\n\n    result = []\n    for pool, n in zip(pools, ns):\n        result.append(pool[index % n])\n        index //= n\n\n    return tuple(reversed(result))\n\n\ndef nth_permutation(iterable, r, index):\n    \"\"\"Equivalent to ``list(permutations(iterable, r))[index]```\n\n    The subsequences of *iterable* that are of length *r* where order is\n    important can be ordered lexicographically. :func:`nth_permutation`\n    computes the subsequence at sort position *index* directly, without\n    computing the previous subsequences.\n\n        >>> nth_permutation('ghijk', 2, 5)\n        ('h', 'i')\n\n    ``ValueError`` will be raised If *r* is negative or greater than the length\n    of *iterable*.\n    ``IndexError`` will be raised if the given *index* is invalid.\n    \"\"\"\n    pool = list(iterable)\n    n = len(pool)\n\n    if r is None or r == n:\n        r, c = n, factorial(n)\n    elif not 0 <= r < n:\n        raise ValueError\n    else:\n        c = factorial(n) // factorial(n - r)\n\n    if index < 0:\n        index += c\n\n    if not 0 <= index < c:\n        raise IndexError\n\n    if c == 0:\n        return tuple()\n\n    result = [0] * r\n    q = index * factorial(n) // c if r < n else index\n    for d in range(1, n + 1):\n        q, i = divmod(q, d)\n        if 0 <= n - d < r:\n            result[n - d] = i\n        if q == 0:\n            break\n\n    return tuple(map(pool.pop, result))\n\n\ndef value_chain(*args):\n    \"\"\"Yield all arguments passed to the function in the same order in which\n    they were passed. If an argument itself is iterable then iterate over its\n    values.\n\n        >>> list(value_chain(1, 2, 3, [4, 5, 6]))\n        [1, 2, 3, 4, 5, 6]\n\n    Binary and text strings are not considered iterable and are emitted\n    as-is:\n\n        >>> list(value_chain('12', '34', ['56', '78']))\n        ['12', '34', '56', '78']\n\n\n    Multiple levels of nesting are not flattened.\n\n    \"\"\"\n    for value in args:\n        if isinstance(value, (str, bytes)):\n            yield value\n            continue\n        try:\n            yield from value\n        except TypeError:\n            yield value\n\n\ndef product_index(element, *args):\n    \"\"\"Equivalent to ``list(product(*args)).index(element)``\n\n    The products of *args* can be ordered lexicographically.\n    :func:`product_index` computes the first index of *element* without\n    computing the previous products.\n\n        >>> product_index([8, 2], range(10), range(5))\n        42\n\n    ``ValueError`` will be raised if the given *element* isn't in the product\n    of *args*.\n    \"\"\"\n    index = 0\n\n    for x, pool in zip_longest(element, args, fillvalue=_marker):\n        if x is _marker or pool is _marker:\n            raise ValueError('element is not a product of args')\n\n        pool = tuple(pool)\n        index = index * len(pool) + pool.index(x)\n\n    return index\n\n\ndef combination_index(element, iterable):\n    \"\"\"Equivalent to ``list(combinations(iterable, r)).index(element)``\n\n    The subsequences of *iterable* that are of length *r* can be ordered\n    lexicographically. :func:`combination_index` computes the index of the\n    first *element*, without computing the previous combinations.\n\n        >>> combination_index('adf', 'abcdefg')\n        10\n\n    ``ValueError`` will be raised if the given *element* isn't one of the\n    combinations of *iterable*.\n    \"\"\"\n    element = enumerate(element)\n    k, y = next(element, (None, None))\n    if k is None:\n        return 0\n\n    indexes = []\n    pool = enumerate(iterable)\n    for n, x in pool:\n        if x == y:\n            indexes.append(n)\n            tmp, y = next(element, (None, None))\n            if tmp is None:\n                break\n            else:\n                k = tmp\n    else:\n        raise ValueError('element is not a combination of iterable')\n\n    n, _ = last(pool, default=(n, None))\n\n    # Python versiosn below 3.8 don't have math.comb\n    index = 1\n    for i, j in enumerate(reversed(indexes), start=1):\n        j = n - j\n        if i <= j:\n            index += factorial(j) // (factorial(i) * factorial(j - i))\n\n    return factorial(n + 1) // (factorial(k + 1) * factorial(n - k)) - index\n\n\ndef permutation_index(element, iterable):\n    \"\"\"Equivalent to ``list(permutations(iterable, r)).index(element)```\n\n    The subsequences of *iterable* that are of length *r* where order is\n    important can be ordered lexicographically. :func:`permutation_index`\n    computes the index of the first *element* directly, without computing\n    the previous permutations.\n\n        >>> permutation_index([1, 3, 2], range(5))\n        19\n\n    ``ValueError`` will be raised if the given *element* isn't one of the\n    permutations of *iterable*.\n    \"\"\"\n    index = 0\n    pool = list(iterable)\n    for i, x in zip(range(len(pool), -1, -1), element):\n        r = pool.index(x)\n        index = index * i + r\n        del pool[r]\n\n    return index\n\n\nclass countable:\n    \"\"\"Wrap *iterable* and keep a count of how many items have been consumed.\n\n    The ``items_seen`` attribute starts at ``0`` and increments as the iterable\n    is consumed:\n\n        >>> iterable = map(str, range(10))\n        >>> it = countable(iterable)\n        >>> it.items_seen\n        0\n        >>> next(it), next(it)\n        ('0', '1')\n        >>> list(it)\n        ['2', '3', '4', '5', '6', '7', '8', '9']\n        >>> it.items_seen\n        10\n    \"\"\"\n\n    def __init__(self, iterable):\n        self._it = iter(iterable)\n        self.items_seen = 0\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        item = next(self._it)\n        self.items_seen += 1\n\n        return item\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/more_itertools/recipes.py",
    "content": "\"\"\"Imported from the recipes section of the itertools documentation.\n\nAll functions taken from the recipes section of the itertools library docs\n[1]_.\nSome backward-compatible usability improvements have been made.\n\n.. [1] http://docs.python.org/library/itertools.html#recipes\n\n\"\"\"\nimport warnings\nfrom collections import deque\nfrom itertools import (\n    chain,\n    combinations,\n    count,\n    cycle,\n    groupby,\n    islice,\n    repeat,\n    starmap,\n    tee,\n    zip_longest,\n)\nimport operator\nfrom random import randrange, sample, choice\n\n__all__ = [\n    'all_equal',\n    'consume',\n    'convolve',\n    'dotproduct',\n    'first_true',\n    'flatten',\n    'grouper',\n    'iter_except',\n    'ncycles',\n    'nth',\n    'nth_combination',\n    'padnone',\n    'pad_none',\n    'pairwise',\n    'partition',\n    'powerset',\n    'prepend',\n    'quantify',\n    'random_combination_with_replacement',\n    'random_combination',\n    'random_permutation',\n    'random_product',\n    'repeatfunc',\n    'roundrobin',\n    'tabulate',\n    'tail',\n    'take',\n    'unique_everseen',\n    'unique_justseen',\n]\n\n\ndef take(n, iterable):\n    \"\"\"Return first *n* items of the iterable as a list.\n\n        >>> take(3, range(10))\n        [0, 1, 2]\n\n    If there are fewer than *n* items in the iterable, all of them are\n    returned.\n\n        >>> take(10, range(3))\n        [0, 1, 2]\n\n    \"\"\"\n    return list(islice(iterable, n))\n\n\ndef tabulate(function, start=0):\n    \"\"\"Return an iterator over the results of ``func(start)``,\n    ``func(start + 1)``, ``func(start + 2)``...\n\n    *func* should be a function that accepts one integer argument.\n\n    If *start* is not specified it defaults to 0. It will be incremented each\n    time the iterator is advanced.\n\n        >>> square = lambda x: x ** 2\n        >>> iterator = tabulate(square, -3)\n        >>> take(4, iterator)\n        [9, 4, 1, 0]\n\n    \"\"\"\n    return map(function, count(start))\n\n\ndef tail(n, iterable):\n    \"\"\"Return an iterator over the last *n* items of *iterable*.\n\n    >>> t = tail(3, 'ABCDEFG')\n    >>> list(t)\n    ['E', 'F', 'G']\n\n    \"\"\"\n    return iter(deque(iterable, maxlen=n))\n\n\ndef consume(iterator, n=None):\n    \"\"\"Advance *iterable* by *n* steps. If *n* is ``None``, consume it\n    entirely.\n\n    Efficiently exhausts an iterator without returning values. Defaults to\n    consuming the whole iterator, but an optional second argument may be\n    provided to limit consumption.\n\n        >>> i = (x for x in range(10))\n        >>> next(i)\n        0\n        >>> consume(i, 3)\n        >>> next(i)\n        4\n        >>> consume(i)\n        >>> next(i)\n        Traceback (most recent call last):\n          File \"<stdin>\", line 1, in <module>\n        StopIteration\n\n    If the iterator has fewer items remaining than the provided limit, the\n    whole iterator will be consumed.\n\n        >>> i = (x for x in range(3))\n        >>> consume(i, 5)\n        >>> next(i)\n        Traceback (most recent call last):\n          File \"<stdin>\", line 1, in <module>\n        StopIteration\n\n    \"\"\"\n    # Use functions that consume iterators at C speed.\n    if n is None:\n        # feed the entire iterator into a zero-length deque\n        deque(iterator, maxlen=0)\n    else:\n        # advance to the empty slice starting at position n\n        next(islice(iterator, n, n), None)\n\n\ndef nth(iterable, n, default=None):\n    \"\"\"Returns the nth item or a default value.\n\n    >>> l = range(10)\n    >>> nth(l, 3)\n    3\n    >>> nth(l, 20, \"zebra\")\n    'zebra'\n\n    \"\"\"\n    return next(islice(iterable, n, None), default)\n\n\ndef all_equal(iterable):\n    \"\"\"\n    Returns ``True`` if all the elements are equal to each other.\n\n        >>> all_equal('aaaa')\n        True\n        >>> all_equal('aaab')\n        False\n\n    \"\"\"\n    g = groupby(iterable)\n    return next(g, True) and not next(g, False)\n\n\ndef quantify(iterable, pred=bool):\n    \"\"\"Return the how many times the predicate is true.\n\n    >>> quantify([True, False, True])\n    2\n\n    \"\"\"\n    return sum(map(pred, iterable))\n\n\ndef pad_none(iterable):\n    \"\"\"Returns the sequence of elements and then returns ``None`` indefinitely.\n\n        >>> take(5, pad_none(range(3)))\n        [0, 1, 2, None, None]\n\n    Useful for emulating the behavior of the built-in :func:`map` function.\n\n    See also :func:`padded`.\n\n    \"\"\"\n    return chain(iterable, repeat(None))\n\n\npadnone = pad_none\n\n\ndef ncycles(iterable, n):\n    \"\"\"Returns the sequence elements *n* times\n\n    >>> list(ncycles([\"a\", \"b\"], 3))\n    ['a', 'b', 'a', 'b', 'a', 'b']\n\n    \"\"\"\n    return chain.from_iterable(repeat(tuple(iterable), n))\n\n\ndef dotproduct(vec1, vec2):\n    \"\"\"Returns the dot product of the two iterables.\n\n    >>> dotproduct([10, 10], [20, 20])\n    400\n\n    \"\"\"\n    return sum(map(operator.mul, vec1, vec2))\n\n\ndef flatten(listOfLists):\n    \"\"\"Return an iterator flattening one level of nesting in a list of lists.\n\n        >>> list(flatten([[0, 1], [2, 3]]))\n        [0, 1, 2, 3]\n\n    See also :func:`collapse`, which can flatten multiple levels of nesting.\n\n    \"\"\"\n    return chain.from_iterable(listOfLists)\n\n\ndef repeatfunc(func, times=None, *args):\n    \"\"\"Call *func* with *args* repeatedly, returning an iterable over the\n    results.\n\n    If *times* is specified, the iterable will terminate after that many\n    repetitions:\n\n        >>> from operator import add\n        >>> times = 4\n        >>> args = 3, 5\n        >>> list(repeatfunc(add, times, *args))\n        [8, 8, 8, 8]\n\n    If *times* is ``None`` the iterable will not terminate:\n\n        >>> from random import randrange\n        >>> times = None\n        >>> args = 1, 11\n        >>> take(6, repeatfunc(randrange, times, *args))  # doctest:+SKIP\n        [2, 4, 8, 1, 8, 4]\n\n    \"\"\"\n    if times is None:\n        return starmap(func, repeat(args))\n    return starmap(func, repeat(args, times))\n\n\ndef _pairwise(iterable):\n    \"\"\"Returns an iterator of paired items, overlapping, from the original\n\n    >>> take(4, pairwise(count()))\n    [(0, 1), (1, 2), (2, 3), (3, 4)]\n\n    On Python 3.10 and above, this is an alias for :func:`itertools.pairwise`.\n\n    \"\"\"\n    a, b = tee(iterable)\n    next(b, None)\n    yield from zip(a, b)\n\n\ntry:\n    from itertools import pairwise as itertools_pairwise\nexcept ImportError:\n    pairwise = _pairwise\nelse:\n\n    def pairwise(iterable):\n        yield from itertools_pairwise(iterable)\n\n    pairwise.__doc__ = _pairwise.__doc__\n\n\ndef grouper(iterable, n, fillvalue=None):\n    \"\"\"Collect data into fixed-length chunks or blocks.\n\n    >>> list(grouper('ABCDEFG', 3, 'x'))\n    [('A', 'B', 'C'), ('D', 'E', 'F'), ('G', 'x', 'x')]\n\n    \"\"\"\n    if isinstance(iterable, int):\n        warnings.warn(\n            \"grouper expects iterable as first parameter\", DeprecationWarning\n        )\n        n, iterable = iterable, n\n    args = [iter(iterable)] * n\n    return zip_longest(fillvalue=fillvalue, *args)\n\n\ndef roundrobin(*iterables):\n    \"\"\"Yields an item from each iterable, alternating between them.\n\n        >>> list(roundrobin('ABC', 'D', 'EF'))\n        ['A', 'D', 'E', 'B', 'F', 'C']\n\n    This function produces the same output as :func:`interleave_longest`, but\n    may perform better for some inputs (in particular when the number of\n    iterables is small).\n\n    \"\"\"\n    # Recipe credited to George Sakkis\n    pending = len(iterables)\n    nexts = cycle(iter(it).__next__ for it in iterables)\n    while pending:\n        try:\n            for next in nexts:\n                yield next()\n        except StopIteration:\n            pending -= 1\n            nexts = cycle(islice(nexts, pending))\n\n\ndef partition(pred, iterable):\n    \"\"\"\n    Returns a 2-tuple of iterables derived from the input iterable.\n    The first yields the items that have ``pred(item) == False``.\n    The second yields the items that have ``pred(item) == True``.\n\n        >>> is_odd = lambda x: x % 2 != 0\n        >>> iterable = range(10)\n        >>> even_items, odd_items = partition(is_odd, iterable)\n        >>> list(even_items), list(odd_items)\n        ([0, 2, 4, 6, 8], [1, 3, 5, 7, 9])\n\n    If *pred* is None, :func:`bool` is used.\n\n        >>> iterable = [0, 1, False, True, '', ' ']\n        >>> false_items, true_items = partition(None, iterable)\n        >>> list(false_items), list(true_items)\n        ([0, False, ''], [1, True, ' '])\n\n    \"\"\"\n    if pred is None:\n        pred = bool\n\n    evaluations = ((pred(x), x) for x in iterable)\n    t1, t2 = tee(evaluations)\n    return (\n        (x for (cond, x) in t1 if not cond),\n        (x for (cond, x) in t2 if cond),\n    )\n\n\ndef powerset(iterable):\n    \"\"\"Yields all possible subsets of the iterable.\n\n        >>> list(powerset([1, 2, 3]))\n        [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]\n\n    :func:`powerset` will operate on iterables that aren't :class:`set`\n    instances, so repeated elements in the input will produce repeated elements\n    in the output. Use :func:`unique_everseen` on the input to avoid generating\n    duplicates:\n\n        >>> seq = [1, 1, 0]\n        >>> list(powerset(seq))\n        [(), (1,), (1,), (0,), (1, 1), (1, 0), (1, 0), (1, 1, 0)]\n        >>> from more_itertools import unique_everseen\n        >>> list(powerset(unique_everseen(seq)))\n        [(), (1,), (0,), (1, 0)]\n\n    \"\"\"\n    s = list(iterable)\n    return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))\n\n\ndef unique_everseen(iterable, key=None):\n    \"\"\"\n    Yield unique elements, preserving order.\n\n        >>> list(unique_everseen('AAAABBBCCDAABBB'))\n        ['A', 'B', 'C', 'D']\n        >>> list(unique_everseen('ABBCcAD', str.lower))\n        ['A', 'B', 'C', 'D']\n\n    Sequences with a mix of hashable and unhashable items can be used.\n    The function will be slower (i.e., `O(n^2)`) for unhashable items.\n\n    Remember that ``list`` objects are unhashable - you can use the *key*\n    parameter to transform the list to a tuple (which is hashable) to\n    avoid a slowdown.\n\n        >>> iterable = ([1, 2], [2, 3], [1, 2])\n        >>> list(unique_everseen(iterable))  # Slow\n        [[1, 2], [2, 3]]\n        >>> list(unique_everseen(iterable, key=tuple))  # Faster\n        [[1, 2], [2, 3]]\n\n    Similary, you may want to convert unhashable ``set`` objects with\n    ``key=frozenset``. For ``dict`` objects,\n    ``key=lambda x: frozenset(x.items())`` can be used.\n\n    \"\"\"\n    seenset = set()\n    seenset_add = seenset.add\n    seenlist = []\n    seenlist_add = seenlist.append\n    use_key = key is not None\n\n    for element in iterable:\n        k = key(element) if use_key else element\n        try:\n            if k not in seenset:\n                seenset_add(k)\n                yield element\n        except TypeError:\n            if k not in seenlist:\n                seenlist_add(k)\n                yield element\n\n\ndef unique_justseen(iterable, key=None):\n    \"\"\"Yields elements in order, ignoring serial duplicates\n\n    >>> list(unique_justseen('AAAABBBCCDAABBB'))\n    ['A', 'B', 'C', 'D', 'A', 'B']\n    >>> list(unique_justseen('ABBCcAD', str.lower))\n    ['A', 'B', 'C', 'A', 'D']\n\n    \"\"\"\n    return map(next, map(operator.itemgetter(1), groupby(iterable, key)))\n\n\ndef iter_except(func, exception, first=None):\n    \"\"\"Yields results from a function repeatedly until an exception is raised.\n\n    Converts a call-until-exception interface to an iterator interface.\n    Like ``iter(func, sentinel)``, but uses an exception instead of a sentinel\n    to end the loop.\n\n        >>> l = [0, 1, 2]\n        >>> list(iter_except(l.pop, IndexError))\n        [2, 1, 0]\n\n    \"\"\"\n    try:\n        if first is not None:\n            yield first()\n        while 1:\n            yield func()\n    except exception:\n        pass\n\n\ndef first_true(iterable, default=None, pred=None):\n    \"\"\"\n    Returns the first true value in the iterable.\n\n    If no true value is found, returns *default*\n\n    If *pred* is not None, returns the first item for which\n    ``pred(item) == True`` .\n\n        >>> first_true(range(10))\n        1\n        >>> first_true(range(10), pred=lambda x: x > 5)\n        6\n        >>> first_true(range(10), default='missing', pred=lambda x: x > 9)\n        'missing'\n\n    \"\"\"\n    return next(filter(pred, iterable), default)\n\n\ndef random_product(*args, repeat=1):\n    \"\"\"Draw an item at random from each of the input iterables.\n\n        >>> random_product('abc', range(4), 'XYZ')  # doctest:+SKIP\n        ('c', 3, 'Z')\n\n    If *repeat* is provided as a keyword argument, that many items will be\n    drawn from each iterable.\n\n        >>> random_product('abcd', range(4), repeat=2)  # doctest:+SKIP\n        ('a', 2, 'd', 3)\n\n    This equivalent to taking a random selection from\n    ``itertools.product(*args, **kwarg)``.\n\n    \"\"\"\n    pools = [tuple(pool) for pool in args] * repeat\n    return tuple(choice(pool) for pool in pools)\n\n\ndef random_permutation(iterable, r=None):\n    \"\"\"Return a random *r* length permutation of the elements in *iterable*.\n\n    If *r* is not specified or is ``None``, then *r* defaults to the length of\n    *iterable*.\n\n        >>> random_permutation(range(5))  # doctest:+SKIP\n        (3, 4, 0, 1, 2)\n\n    This equivalent to taking a random selection from\n    ``itertools.permutations(iterable, r)``.\n\n    \"\"\"\n    pool = tuple(iterable)\n    r = len(pool) if r is None else r\n    return tuple(sample(pool, r))\n\n\ndef random_combination(iterable, r):\n    \"\"\"Return a random *r* length subsequence of the elements in *iterable*.\n\n        >>> random_combination(range(5), 3)  # doctest:+SKIP\n        (2, 3, 4)\n\n    This equivalent to taking a random selection from\n    ``itertools.combinations(iterable, r)``.\n\n    \"\"\"\n    pool = tuple(iterable)\n    n = len(pool)\n    indices = sorted(sample(range(n), r))\n    return tuple(pool[i] for i in indices)\n\n\ndef random_combination_with_replacement(iterable, r):\n    \"\"\"Return a random *r* length subsequence of elements in *iterable*,\n    allowing individual elements to be repeated.\n\n        >>> random_combination_with_replacement(range(3), 5) # doctest:+SKIP\n        (0, 0, 1, 2, 2)\n\n    This equivalent to taking a random selection from\n    ``itertools.combinations_with_replacement(iterable, r)``.\n\n    \"\"\"\n    pool = tuple(iterable)\n    n = len(pool)\n    indices = sorted(randrange(n) for i in range(r))\n    return tuple(pool[i] for i in indices)\n\n\ndef nth_combination(iterable, r, index):\n    \"\"\"Equivalent to ``list(combinations(iterable, r))[index]``.\n\n    The subsequences of *iterable* that are of length *r* can be ordered\n    lexicographically. :func:`nth_combination` computes the subsequence at\n    sort position *index* directly, without computing the previous\n    subsequences.\n\n        >>> nth_combination(range(5), 3, 5)\n        (0, 3, 4)\n\n    ``ValueError`` will be raised If *r* is negative or greater than the length\n    of *iterable*.\n    ``IndexError`` will be raised if the given *index* is invalid.\n    \"\"\"\n    pool = tuple(iterable)\n    n = len(pool)\n    if (r < 0) or (r > n):\n        raise ValueError\n\n    c = 1\n    k = min(r, n - r)\n    for i in range(1, k + 1):\n        c = c * (n - k + i) // i\n\n    if index < 0:\n        index += c\n\n    if (index < 0) or (index >= c):\n        raise IndexError\n\n    result = []\n    while r:\n        c, n, r = c * r // n, n - 1, r - 1\n        while index >= c:\n            index -= c\n            c, n = c * (n - r) // n, n - 1\n        result.append(pool[-1 - n])\n\n    return tuple(result)\n\n\ndef prepend(value, iterator):\n    \"\"\"Yield *value*, followed by the elements in *iterator*.\n\n        >>> value = '0'\n        >>> iterator = ['1', '2', '3']\n        >>> list(prepend(value, iterator))\n        ['0', '1', '2', '3']\n\n    To prepend multiple values, see :func:`itertools.chain`\n    or :func:`value_chain`.\n\n    \"\"\"\n    return chain([value], iterator)\n\n\ndef convolve(signal, kernel):\n    \"\"\"Convolve the iterable *signal* with the iterable *kernel*.\n\n        >>> signal = (1, 2, 3, 4, 5)\n        >>> kernel = [3, 2, 1]\n        >>> list(convolve(signal, kernel))\n        [3, 8, 14, 20, 26, 14, 5]\n\n    Note: the input arguments are not interchangeable, as the *kernel*\n    is immediately consumed and stored.\n\n    \"\"\"\n    kernel = tuple(kernel)[::-1]\n    n = len(kernel)\n    window = deque([0], maxlen=n) * n\n    for x in chain(signal, repeat(0, n - 1)):\n        window.append(x)\n        yield sum(map(operator.mul, kernel, window))\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/ordered_set.py",
    "content": "\"\"\"\nAn OrderedSet is a custom MutableSet that remembers its order, so that every\nentry has an index that can be looked up.\n\nBased on a recipe originally posted to ActiveState Recipes by Raymond Hettiger,\nand released under the MIT license.\n\"\"\"\nimport itertools as it\nfrom collections import deque\n\ntry:\n    # Python 3\n    from collections.abc import MutableSet, Sequence\nexcept ImportError:\n    # Python 2.7\n    from collections import MutableSet, Sequence\n\nSLICE_ALL = slice(None)\n__version__ = \"3.1\"\n\n\ndef is_iterable(obj):\n    \"\"\"\n    Are we being asked to look up a list of things, instead of a single thing?\n    We check for the `__iter__` attribute so that this can cover types that\n    don't have to be known by this module, such as NumPy arrays.\n\n    Strings, however, should be considered as atomic values to look up, not\n    iterables. The same goes for tuples, since they are immutable and therefore\n    valid entries.\n\n    We don't need to check for the Python 2 `unicode` type, because it doesn't\n    have an `__iter__` attribute anyway.\n    \"\"\"\n    return (\n        hasattr(obj, \"__iter__\")\n        and not isinstance(obj, str)\n        and not isinstance(obj, tuple)\n    )\n\n\nclass OrderedSet(MutableSet, Sequence):\n    \"\"\"\n    An OrderedSet is a custom MutableSet that remembers its order, so that\n    every entry has an index that can be looked up.\n\n    Example:\n        >>> OrderedSet([1, 1, 2, 3, 2])\n        OrderedSet([1, 2, 3])\n    \"\"\"\n\n    def __init__(self, iterable=None):\n        self.items = []\n        self.map = {}\n        if iterable is not None:\n            self |= iterable\n\n    def __len__(self):\n        \"\"\"\n        Returns the number of unique elements in the ordered set\n\n        Example:\n            >>> len(OrderedSet([]))\n            0\n            >>> len(OrderedSet([1, 2]))\n            2\n        \"\"\"\n        return len(self.items)\n\n    def __getitem__(self, index):\n        \"\"\"\n        Get the item at a given index.\n\n        If `index` is a slice, you will get back that slice of items, as a\n        new OrderedSet.\n\n        If `index` is a list or a similar iterable, you'll get a list of\n        items corresponding to those indices. This is similar to NumPy's\n        \"fancy indexing\". The result is not an OrderedSet because you may ask\n        for duplicate indices, and the number of elements returned should be\n        the number of elements asked for.\n\n        Example:\n            >>> oset = OrderedSet([1, 2, 3])\n            >>> oset[1]\n            2\n        \"\"\"\n        if isinstance(index, slice) and index == SLICE_ALL:\n            return self.copy()\n        elif is_iterable(index):\n            return [self.items[i] for i in index]\n        elif hasattr(index, \"__index__\") or isinstance(index, slice):\n            result = self.items[index]\n            if isinstance(result, list):\n                return self.__class__(result)\n            else:\n                return result\n        else:\n            raise TypeError(\"Don't know how to index an OrderedSet by %r\" % index)\n\n    def copy(self):\n        \"\"\"\n        Return a shallow copy of this object.\n\n        Example:\n            >>> this = OrderedSet([1, 2, 3])\n            >>> other = this.copy()\n            >>> this == other\n            True\n            >>> this is other\n            False\n        \"\"\"\n        return self.__class__(self)\n\n    def __getstate__(self):\n        if len(self) == 0:\n            # The state can't be an empty list.\n            # We need to return a truthy value, or else __setstate__ won't be run.\n            #\n            # This could have been done more gracefully by always putting the state\n            # in a tuple, but this way is backwards- and forwards- compatible with\n            # previous versions of OrderedSet.\n            return (None,)\n        else:\n            return list(self)\n\n    def __setstate__(self, state):\n        if state == (None,):\n            self.__init__([])\n        else:\n            self.__init__(state)\n\n    def __contains__(self, key):\n        \"\"\"\n        Test if the item is in this ordered set\n\n        Example:\n            >>> 1 in OrderedSet([1, 3, 2])\n            True\n            >>> 5 in OrderedSet([1, 3, 2])\n            False\n        \"\"\"\n        return key in self.map\n\n    def add(self, key):\n        \"\"\"\n        Add `key` as an item to this OrderedSet, then return its index.\n\n        If `key` is already in the OrderedSet, return the index it already\n        had.\n\n        Example:\n            >>> oset = OrderedSet()\n            >>> oset.append(3)\n            0\n            >>> print(oset)\n            OrderedSet([3])\n        \"\"\"\n        if key not in self.map:\n            self.map[key] = len(self.items)\n            self.items.append(key)\n        return self.map[key]\n\n    append = add\n\n    def update(self, sequence):\n        \"\"\"\n        Update the set with the given iterable sequence, then return the index\n        of the last element inserted.\n\n        Example:\n            >>> oset = OrderedSet([1, 2, 3])\n            >>> oset.update([3, 1, 5, 1, 4])\n            4\n            >>> print(oset)\n            OrderedSet([1, 2, 3, 5, 4])\n        \"\"\"\n        item_index = None\n        try:\n            for item in sequence:\n                item_index = self.add(item)\n        except TypeError:\n            raise ValueError(\n                \"Argument needs to be an iterable, got %s\" % type(sequence)\n            )\n        return item_index\n\n    def index(self, key):\n        \"\"\"\n        Get the index of a given entry, raising an IndexError if it's not\n        present.\n\n        `key` can be an iterable of entries that is not a string, in which case\n        this returns a list of indices.\n\n        Example:\n            >>> oset = OrderedSet([1, 2, 3])\n            >>> oset.index(2)\n            1\n        \"\"\"\n        if is_iterable(key):\n            return [self.index(subkey) for subkey in key]\n        return self.map[key]\n\n    # Provide some compatibility with pd.Index\n    get_loc = index\n    get_indexer = index\n\n    def pop(self):\n        \"\"\"\n        Remove and return the last element from the set.\n\n        Raises KeyError if the set is empty.\n\n        Example:\n            >>> oset = OrderedSet([1, 2, 3])\n            >>> oset.pop()\n            3\n        \"\"\"\n        if not self.items:\n            raise KeyError(\"Set is empty\")\n\n        elem = self.items[-1]\n        del self.items[-1]\n        del self.map[elem]\n        return elem\n\n    def discard(self, key):\n        \"\"\"\n        Remove an element.  Do not raise an exception if absent.\n\n        The MutableSet mixin uses this to implement the .remove() method, which\n        *does* raise an error when asked to remove a non-existent item.\n\n        Example:\n            >>> oset = OrderedSet([1, 2, 3])\n            >>> oset.discard(2)\n            >>> print(oset)\n            OrderedSet([1, 3])\n            >>> oset.discard(2)\n            >>> print(oset)\n            OrderedSet([1, 3])\n        \"\"\"\n        if key in self:\n            i = self.map[key]\n            del self.items[i]\n            del self.map[key]\n            for k, v in self.map.items():\n                if v >= i:\n                    self.map[k] = v - 1\n\n    def clear(self):\n        \"\"\"\n        Remove all items from this OrderedSet.\n        \"\"\"\n        del self.items[:]\n        self.map.clear()\n\n    def __iter__(self):\n        \"\"\"\n        Example:\n            >>> list(iter(OrderedSet([1, 2, 3])))\n            [1, 2, 3]\n        \"\"\"\n        return iter(self.items)\n\n    def __reversed__(self):\n        \"\"\"\n        Example:\n            >>> list(reversed(OrderedSet([1, 2, 3])))\n            [3, 2, 1]\n        \"\"\"\n        return reversed(self.items)\n\n    def __repr__(self):\n        if not self:\n            return \"%s()\" % (self.__class__.__name__,)\n        return \"%s(%r)\" % (self.__class__.__name__, list(self))\n\n    def __eq__(self, other):\n        \"\"\"\n        Returns true if the containers have the same items. If `other` is a\n        Sequence, then order is checked, otherwise it is ignored.\n\n        Example:\n            >>> oset = OrderedSet([1, 3, 2])\n            >>> oset == [1, 3, 2]\n            True\n            >>> oset == [1, 2, 3]\n            False\n            >>> oset == [2, 3]\n            False\n            >>> oset == OrderedSet([3, 2, 1])\n            False\n        \"\"\"\n        # In Python 2 deque is not a Sequence, so treat it as one for\n        # consistent behavior with Python 3.\n        if isinstance(other, (Sequence, deque)):\n            # Check that this OrderedSet contains the same elements, in the\n            # same order, as the other object.\n            return list(self) == list(other)\n        try:\n            other_as_set = set(other)\n        except TypeError:\n            # If `other` can't be converted into a set, it's not equal.\n            return False\n        else:\n            return set(self) == other_as_set\n\n    def union(self, *sets):\n        \"\"\"\n        Combines all unique items.\n        Each items order is defined by its first appearance.\n\n        Example:\n            >>> oset = OrderedSet.union(OrderedSet([3, 1, 4, 1, 5]), [1, 3], [2, 0])\n            >>> print(oset)\n            OrderedSet([3, 1, 4, 5, 2, 0])\n            >>> oset.union([8, 9])\n            OrderedSet([3, 1, 4, 5, 2, 0, 8, 9])\n            >>> oset | {10}\n            OrderedSet([3, 1, 4, 5, 2, 0, 10])\n        \"\"\"\n        cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet\n        containers = map(list, it.chain([self], sets))\n        items = it.chain.from_iterable(containers)\n        return cls(items)\n\n    def __and__(self, other):\n        # the parent implementation of this is backwards\n        return self.intersection(other)\n\n    def intersection(self, *sets):\n        \"\"\"\n        Returns elements in common between all sets. Order is defined only\n        by the first set.\n\n        Example:\n            >>> oset = OrderedSet.intersection(OrderedSet([0, 1, 2, 3]), [1, 2, 3])\n            >>> print(oset)\n            OrderedSet([1, 2, 3])\n            >>> oset.intersection([2, 4, 5], [1, 2, 3, 4])\n            OrderedSet([2])\n            >>> oset.intersection()\n            OrderedSet([1, 2, 3])\n        \"\"\"\n        cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet\n        if sets:\n            common = set.intersection(*map(set, sets))\n            items = (item for item in self if item in common)\n        else:\n            items = self\n        return cls(items)\n\n    def difference(self, *sets):\n        \"\"\"\n        Returns all elements that are in this set but not the others.\n\n        Example:\n            >>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]))\n            OrderedSet([1, 3])\n            >>> OrderedSet([1, 2, 3]).difference(OrderedSet([2]), OrderedSet([3]))\n            OrderedSet([1])\n            >>> OrderedSet([1, 2, 3]) - OrderedSet([2])\n            OrderedSet([1, 3])\n            >>> OrderedSet([1, 2, 3]).difference()\n            OrderedSet([1, 2, 3])\n        \"\"\"\n        cls = self.__class__\n        if sets:\n            other = set.union(*map(set, sets))\n            items = (item for item in self if item not in other)\n        else:\n            items = self\n        return cls(items)\n\n    def issubset(self, other):\n        \"\"\"\n        Report whether another set contains this set.\n\n        Example:\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2})\n            False\n            >>> OrderedSet([1, 2, 3]).issubset({1, 2, 3, 4})\n            True\n            >>> OrderedSet([1, 2, 3]).issubset({1, 4, 3, 5})\n            False\n        \"\"\"\n        if len(self) > len(other):  # Fast check for obvious cases\n            return False\n        return all(item in other for item in self)\n\n    def issuperset(self, other):\n        \"\"\"\n        Report whether this set contains another set.\n\n        Example:\n            >>> OrderedSet([1, 2]).issuperset([1, 2, 3])\n            False\n            >>> OrderedSet([1, 2, 3, 4]).issuperset({1, 2, 3})\n            True\n            >>> OrderedSet([1, 4, 3, 5]).issuperset({1, 2, 3})\n            False\n        \"\"\"\n        if len(self) < len(other):  # Fast check for obvious cases\n            return False\n        return all(item in self for item in other)\n\n    def symmetric_difference(self, other):\n        \"\"\"\n        Return the symmetric difference of two OrderedSets as a new set.\n        That is, the new set will contain all elements that are in exactly\n        one of the sets.\n\n        Their order will be preserved, with elements from `self` preceding\n        elements from `other`.\n\n        Example:\n            >>> this = OrderedSet([1, 4, 3, 5, 7])\n            >>> other = OrderedSet([9, 7, 1, 3, 2])\n            >>> this.symmetric_difference(other)\n            OrderedSet([4, 5, 9, 2])\n        \"\"\"\n        cls = self.__class__ if isinstance(self, OrderedSet) else OrderedSet\n        diff1 = cls(self).difference(other)\n        diff2 = cls(other).difference(self)\n        return diff1.union(diff2)\n\n    def _update_items(self, items):\n        \"\"\"\n        Replace the 'items' list of this OrderedSet with a new one, updating\n        self.map accordingly.\n        \"\"\"\n        self.items = items\n        self.map = {item: idx for (idx, item) in enumerate(items)}\n\n    def difference_update(self, *sets):\n        \"\"\"\n        Update this OrderedSet to remove items from one or more other sets.\n\n        Example:\n            >>> this = OrderedSet([1, 2, 3])\n            >>> this.difference_update(OrderedSet([2, 4]))\n            >>> print(this)\n            OrderedSet([1, 3])\n\n            >>> this = OrderedSet([1, 2, 3, 4, 5])\n            >>> this.difference_update(OrderedSet([2, 4]), OrderedSet([1, 4, 6]))\n            >>> print(this)\n            OrderedSet([3, 5])\n        \"\"\"\n        items_to_remove = set()\n        for other in sets:\n            items_to_remove |= set(other)\n        self._update_items([item for item in self.items if item not in items_to_remove])\n\n    def intersection_update(self, other):\n        \"\"\"\n        Update this OrderedSet to keep only items in another set, preserving\n        their order in this set.\n\n        Example:\n            >>> this = OrderedSet([1, 4, 3, 5, 7])\n            >>> other = OrderedSet([9, 7, 1, 3, 2])\n            >>> this.intersection_update(other)\n            >>> print(this)\n            OrderedSet([1, 3, 7])\n        \"\"\"\n        other = set(other)\n        self._update_items([item for item in self.items if item in other])\n\n    def symmetric_difference_update(self, other):\n        \"\"\"\n        Update this OrderedSet to remove items from another set, then\n        add items from the other set that were not present in this set.\n\n        Example:\n            >>> this = OrderedSet([1, 4, 3, 5, 7])\n            >>> other = OrderedSet([9, 7, 1, 3, 2])\n            >>> this.symmetric_difference_update(other)\n            >>> print(this)\n            OrderedSet([4, 5, 9, 2])\n        \"\"\"\n        items_to_add = [item for item in other if item not in self]\n        items_to_remove = set(other)\n        self._update_items(\n            [item for item in self.items if item not in items_to_remove] + items_to_add\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/packaging/__about__.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\n__all__ = [\n    \"__title__\",\n    \"__summary__\",\n    \"__uri__\",\n    \"__version__\",\n    \"__author__\",\n    \"__email__\",\n    \"__license__\",\n    \"__copyright__\",\n]\n\n__title__ = \"packaging\"\n__summary__ = \"Core utilities for Python packages\"\n__uri__ = \"https://github.com/pypa/packaging\"\n\n__version__ = \"21.3\"\n\n__author__ = \"Donald Stufft and individual contributors\"\n__email__ = \"donald@stufft.io\"\n\n__license__ = \"BSD-2-Clause or Apache-2.0\"\n__copyright__ = \"2014-2019 %s\" % __author__\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/packaging/__init__.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nfrom .__about__ import (\n    __author__,\n    __copyright__,\n    __email__,\n    __license__,\n    __summary__,\n    __title__,\n    __uri__,\n    __version__,\n)\n\n__all__ = [\n    \"__title__\",\n    \"__summary__\",\n    \"__uri__\",\n    \"__version__\",\n    \"__author__\",\n    \"__email__\",\n    \"__license__\",\n    \"__copyright__\",\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/packaging/_manylinux.py",
    "content": "import collections\nimport functools\nimport os\nimport re\nimport struct\nimport sys\nimport warnings\nfrom typing import IO, Dict, Iterator, NamedTuple, Optional, Tuple\n\n\n# Python does not provide platform information at sufficient granularity to\n# identify the architecture of the running executable in some cases, so we\n# determine it dynamically by reading the information from the running\n# process. This only applies on Linux, which uses the ELF format.\nclass _ELFFileHeader:\n    # https://en.wikipedia.org/wiki/Executable_and_Linkable_Format#File_header\n    class _InvalidELFFileHeader(ValueError):\n        \"\"\"\n        An invalid ELF file header was found.\n        \"\"\"\n\n    ELF_MAGIC_NUMBER = 0x7F454C46\n    ELFCLASS32 = 1\n    ELFCLASS64 = 2\n    ELFDATA2LSB = 1\n    ELFDATA2MSB = 2\n    EM_386 = 3\n    EM_S390 = 22\n    EM_ARM = 40\n    EM_X86_64 = 62\n    EF_ARM_ABIMASK = 0xFF000000\n    EF_ARM_ABI_VER5 = 0x05000000\n    EF_ARM_ABI_FLOAT_HARD = 0x00000400\n\n    def __init__(self, file: IO[bytes]) -> None:\n        def unpack(fmt: str) -> int:\n            try:\n                data = file.read(struct.calcsize(fmt))\n                result: Tuple[int, ...] = struct.unpack(fmt, data)\n            except struct.error:\n                raise _ELFFileHeader._InvalidELFFileHeader()\n            return result[0]\n\n        self.e_ident_magic = unpack(\">I\")\n        if self.e_ident_magic != self.ELF_MAGIC_NUMBER:\n            raise _ELFFileHeader._InvalidELFFileHeader()\n        self.e_ident_class = unpack(\"B\")\n        if self.e_ident_class not in {self.ELFCLASS32, self.ELFCLASS64}:\n            raise _ELFFileHeader._InvalidELFFileHeader()\n        self.e_ident_data = unpack(\"B\")\n        if self.e_ident_data not in {self.ELFDATA2LSB, self.ELFDATA2MSB}:\n            raise _ELFFileHeader._InvalidELFFileHeader()\n        self.e_ident_version = unpack(\"B\")\n        self.e_ident_osabi = unpack(\"B\")\n        self.e_ident_abiversion = unpack(\"B\")\n        self.e_ident_pad = file.read(7)\n        format_h = \"<H\" if self.e_ident_data == self.ELFDATA2LSB else \">H\"\n        format_i = \"<I\" if self.e_ident_data == self.ELFDATA2LSB else \">I\"\n        format_q = \"<Q\" if self.e_ident_data == self.ELFDATA2LSB else \">Q\"\n        format_p = format_i if self.e_ident_class == self.ELFCLASS32 else format_q\n        self.e_type = unpack(format_h)\n        self.e_machine = unpack(format_h)\n        self.e_version = unpack(format_i)\n        self.e_entry = unpack(format_p)\n        self.e_phoff = unpack(format_p)\n        self.e_shoff = unpack(format_p)\n        self.e_flags = unpack(format_i)\n        self.e_ehsize = unpack(format_h)\n        self.e_phentsize = unpack(format_h)\n        self.e_phnum = unpack(format_h)\n        self.e_shentsize = unpack(format_h)\n        self.e_shnum = unpack(format_h)\n        self.e_shstrndx = unpack(format_h)\n\n\ndef _get_elf_header() -> Optional[_ELFFileHeader]:\n    try:\n        with open(sys.executable, \"rb\") as f:\n            elf_header = _ELFFileHeader(f)\n    except (OSError, TypeError, _ELFFileHeader._InvalidELFFileHeader):\n        return None\n    return elf_header\n\n\ndef _is_linux_armhf() -> bool:\n    # hard-float ABI can be detected from the ELF header of the running\n    # process\n    # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf\n    elf_header = _get_elf_header()\n    if elf_header is None:\n        return False\n    result = elf_header.e_ident_class == elf_header.ELFCLASS32\n    result &= elf_header.e_ident_data == elf_header.ELFDATA2LSB\n    result &= elf_header.e_machine == elf_header.EM_ARM\n    result &= (\n        elf_header.e_flags & elf_header.EF_ARM_ABIMASK\n    ) == elf_header.EF_ARM_ABI_VER5\n    result &= (\n        elf_header.e_flags & elf_header.EF_ARM_ABI_FLOAT_HARD\n    ) == elf_header.EF_ARM_ABI_FLOAT_HARD\n    return result\n\n\ndef _is_linux_i686() -> bool:\n    elf_header = _get_elf_header()\n    if elf_header is None:\n        return False\n    result = elf_header.e_ident_class == elf_header.ELFCLASS32\n    result &= elf_header.e_ident_data == elf_header.ELFDATA2LSB\n    result &= elf_header.e_machine == elf_header.EM_386\n    return result\n\n\ndef _have_compatible_abi(arch: str) -> bool:\n    if arch == \"armv7l\":\n        return _is_linux_armhf()\n    if arch == \"i686\":\n        return _is_linux_i686()\n    return arch in {\"x86_64\", \"aarch64\", \"ppc64\", \"ppc64le\", \"s390x\"}\n\n\n# If glibc ever changes its major version, we need to know what the last\n# minor version was, so we can build the complete list of all versions.\n# For now, guess what the highest minor version might be, assume it will\n# be 50 for testing. Once this actually happens, update the dictionary\n# with the actual value.\n_LAST_GLIBC_MINOR: Dict[int, int] = collections.defaultdict(lambda: 50)\n\n\nclass _GLibCVersion(NamedTuple):\n    major: int\n    minor: int\n\n\ndef _glibc_version_string_confstr() -> Optional[str]:\n    \"\"\"\n    Primary implementation of glibc_version_string using os.confstr.\n    \"\"\"\n    # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely\n    # to be broken or missing. This strategy is used in the standard library\n    # platform module.\n    # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183\n    try:\n        # os.confstr(\"CS_GNU_LIBC_VERSION\") returns a string like \"glibc 2.17\".\n        version_string = os.confstr(\"CS_GNU_LIBC_VERSION\")\n        assert version_string is not None\n        _, version = version_string.split()\n    except (AssertionError, AttributeError, OSError, ValueError):\n        # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...\n        return None\n    return version\n\n\ndef _glibc_version_string_ctypes() -> Optional[str]:\n    \"\"\"\n    Fallback implementation of glibc_version_string using ctypes.\n    \"\"\"\n    try:\n        import ctypes\n    except ImportError:\n        return None\n\n    # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen\n    # manpage says, \"If filename is NULL, then the returned handle is for the\n    # main program\". This way we can let the linker do the work to figure out\n    # which libc our process is actually using.\n    #\n    # We must also handle the special case where the executable is not a\n    # dynamically linked executable. This can occur when using musl libc,\n    # for example. In this situation, dlopen() will error, leading to an\n    # OSError. Interestingly, at least in the case of musl, there is no\n    # errno set on the OSError. The single string argument used to construct\n    # OSError comes from libc itself and is therefore not portable to\n    # hard code here. In any case, failure to call dlopen() means we\n    # can proceed, so we bail on our attempt.\n    try:\n        process_namespace = ctypes.CDLL(None)\n    except OSError:\n        return None\n\n    try:\n        gnu_get_libc_version = process_namespace.gnu_get_libc_version\n    except AttributeError:\n        # Symbol doesn't exist -> therefore, we are not linked to\n        # glibc.\n        return None\n\n    # Call gnu_get_libc_version, which returns a string like \"2.5\"\n    gnu_get_libc_version.restype = ctypes.c_char_p\n    version_str: str = gnu_get_libc_version()\n    # py2 / py3 compatibility:\n    if not isinstance(version_str, str):\n        version_str = version_str.decode(\"ascii\")\n\n    return version_str\n\n\ndef _glibc_version_string() -> Optional[str]:\n    \"\"\"Returns glibc version string, or None if not using glibc.\"\"\"\n    return _glibc_version_string_confstr() or _glibc_version_string_ctypes()\n\n\ndef _parse_glibc_version(version_str: str) -> Tuple[int, int]:\n    \"\"\"Parse glibc version.\n\n    We use a regexp instead of str.split because we want to discard any\n    random junk that might come after the minor version -- this might happen\n    in patched/forked versions of glibc (e.g. Linaro's version of glibc\n    uses version strings like \"2.20-2014.11\"). See gh-3588.\n    \"\"\"\n    m = re.match(r\"(?P<major>[0-9]+)\\.(?P<minor>[0-9]+)\", version_str)\n    if not m:\n        warnings.warn(\n            \"Expected glibc version with 2 components major.minor,\"\n            \" got: %s\" % version_str,\n            RuntimeWarning,\n        )\n        return -1, -1\n    return int(m.group(\"major\")), int(m.group(\"minor\"))\n\n\n@functools.lru_cache()\ndef _get_glibc_version() -> Tuple[int, int]:\n    version_str = _glibc_version_string()\n    if version_str is None:\n        return (-1, -1)\n    return _parse_glibc_version(version_str)\n\n\n# From PEP 513, PEP 600\ndef _is_compatible(name: str, arch: str, version: _GLibCVersion) -> bool:\n    sys_glibc = _get_glibc_version()\n    if sys_glibc < version:\n        return False\n    # Check for presence of _manylinux module.\n    try:\n        import _manylinux  # noqa\n    except ImportError:\n        return True\n    if hasattr(_manylinux, \"manylinux_compatible\"):\n        result = _manylinux.manylinux_compatible(version[0], version[1], arch)\n        if result is not None:\n            return bool(result)\n        return True\n    if version == _GLibCVersion(2, 5):\n        if hasattr(_manylinux, \"manylinux1_compatible\"):\n            return bool(_manylinux.manylinux1_compatible)\n    if version == _GLibCVersion(2, 12):\n        if hasattr(_manylinux, \"manylinux2010_compatible\"):\n            return bool(_manylinux.manylinux2010_compatible)\n    if version == _GLibCVersion(2, 17):\n        if hasattr(_manylinux, \"manylinux2014_compatible\"):\n            return bool(_manylinux.manylinux2014_compatible)\n    return True\n\n\n_LEGACY_MANYLINUX_MAP = {\n    # CentOS 7 w/ glibc 2.17 (PEP 599)\n    (2, 17): \"manylinux2014\",\n    # CentOS 6 w/ glibc 2.12 (PEP 571)\n    (2, 12): \"manylinux2010\",\n    # CentOS 5 w/ glibc 2.5 (PEP 513)\n    (2, 5): \"manylinux1\",\n}\n\n\ndef platform_tags(linux: str, arch: str) -> Iterator[str]:\n    if not _have_compatible_abi(arch):\n        return\n    # Oldest glibc to be supported regardless of architecture is (2, 17).\n    too_old_glibc2 = _GLibCVersion(2, 16)\n    if arch in {\"x86_64\", \"i686\"}:\n        # On x86/i686 also oldest glibc to be supported is (2, 5).\n        too_old_glibc2 = _GLibCVersion(2, 4)\n    current_glibc = _GLibCVersion(*_get_glibc_version())\n    glibc_max_list = [current_glibc]\n    # We can assume compatibility across glibc major versions.\n    # https://sourceware.org/bugzilla/show_bug.cgi?id=24636\n    #\n    # Build a list of maximum glibc versions so that we can\n    # output the canonical list of all glibc from current_glibc\n    # down to too_old_glibc2, including all intermediary versions.\n    for glibc_major in range(current_glibc.major - 1, 1, -1):\n        glibc_minor = _LAST_GLIBC_MINOR[glibc_major]\n        glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))\n    for glibc_max in glibc_max_list:\n        if glibc_max.major == too_old_glibc2.major:\n            min_minor = too_old_glibc2.minor\n        else:\n            # For other glibc major versions oldest supported is (x, 0).\n            min_minor = -1\n        for glibc_minor in range(glibc_max.minor, min_minor, -1):\n            glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)\n            tag = \"manylinux_{}_{}\".format(*glibc_version)\n            if _is_compatible(tag, arch, glibc_version):\n                yield linux.replace(\"linux\", tag)\n            # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.\n            if glibc_version in _LEGACY_MANYLINUX_MAP:\n                legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version]\n                if _is_compatible(legacy_tag, arch, glibc_version):\n                    yield linux.replace(\"linux\", legacy_tag)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/packaging/_musllinux.py",
    "content": "\"\"\"PEP 656 support.\n\nThis module implements logic to detect if the currently running Python is\nlinked against musl, and what musl version is used.\n\"\"\"\n\nimport contextlib\nimport functools\nimport operator\nimport os\nimport re\nimport struct\nimport subprocess\nimport sys\nfrom typing import IO, Iterator, NamedTuple, Optional, Tuple\n\n\ndef _read_unpacked(f: IO[bytes], fmt: str) -> Tuple[int, ...]:\n    return struct.unpack(fmt, f.read(struct.calcsize(fmt)))\n\n\ndef _parse_ld_musl_from_elf(f: IO[bytes]) -> Optional[str]:\n    \"\"\"Detect musl libc location by parsing the Python executable.\n\n    Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca\n    ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html\n    \"\"\"\n    f.seek(0)\n    try:\n        ident = _read_unpacked(f, \"16B\")\n    except struct.error:\n        return None\n    if ident[:4] != tuple(b\"\\x7fELF\"):  # Invalid magic, not ELF.\n        return None\n    f.seek(struct.calcsize(\"HHI\"), 1)  # Skip file type, machine, and version.\n\n    try:\n        # e_fmt: Format for program header.\n        # p_fmt: Format for section header.\n        # p_idx: Indexes to find p_type, p_offset, and p_filesz.\n        e_fmt, p_fmt, p_idx = {\n            1: (\"IIIIHHH\", \"IIIIIIII\", (0, 1, 4)),  # 32-bit.\n            2: (\"QQQIHHH\", \"IIQQQQQQ\", (0, 2, 5)),  # 64-bit.\n        }[ident[4]]\n    except KeyError:\n        return None\n    else:\n        p_get = operator.itemgetter(*p_idx)\n\n    # Find the interpreter section and return its content.\n    try:\n        _, e_phoff, _, _, _, e_phentsize, e_phnum = _read_unpacked(f, e_fmt)\n    except struct.error:\n        return None\n    for i in range(e_phnum + 1):\n        f.seek(e_phoff + e_phentsize * i)\n        try:\n            p_type, p_offset, p_filesz = p_get(_read_unpacked(f, p_fmt))\n        except struct.error:\n            return None\n        if p_type != 3:  # Not PT_INTERP.\n            continue\n        f.seek(p_offset)\n        interpreter = os.fsdecode(f.read(p_filesz)).strip(\"\\0\")\n        if \"musl\" not in interpreter:\n            return None\n        return interpreter\n    return None\n\n\nclass _MuslVersion(NamedTuple):\n    major: int\n    minor: int\n\n\ndef _parse_musl_version(output: str) -> Optional[_MuslVersion]:\n    lines = [n for n in (n.strip() for n in output.splitlines()) if n]\n    if len(lines) < 2 or lines[0][:4] != \"musl\":\n        return None\n    m = re.match(r\"Version (\\d+)\\.(\\d+)\", lines[1])\n    if not m:\n        return None\n    return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))\n\n\n@functools.lru_cache()\ndef _get_musl_version(executable: str) -> Optional[_MuslVersion]:\n    \"\"\"Detect currently-running musl runtime version.\n\n    This is done by checking the specified executable's dynamic linking\n    information, and invoking the loader to parse its output for a version\n    string. If the loader is musl, the output would be something like::\n\n        musl libc (x86_64)\n        Version 1.2.2\n        Dynamic Program Loader\n    \"\"\"\n    with contextlib.ExitStack() as stack:\n        try:\n            f = stack.enter_context(open(executable, \"rb\"))\n        except OSError:\n            return None\n        ld = _parse_ld_musl_from_elf(f)\n    if not ld:\n        return None\n    proc = subprocess.run([ld], stderr=subprocess.PIPE, universal_newlines=True)\n    return _parse_musl_version(proc.stderr)\n\n\ndef platform_tags(arch: str) -> Iterator[str]:\n    \"\"\"Generate musllinux tags compatible to the current platform.\n\n    :param arch: Should be the part of platform tag after the ``linux_``\n        prefix, e.g. ``x86_64``. The ``linux_`` prefix is assumed as a\n        prerequisite for the current platform to be musllinux-compatible.\n\n    :returns: An iterator of compatible musllinux tags.\n    \"\"\"\n    sys_musl = _get_musl_version(sys.executable)\n    if sys_musl is None:  # Python not dynamically linked against musl.\n        return\n    for minor in range(sys_musl.minor, -1, -1):\n        yield f\"musllinux_{sys_musl.major}_{minor}_{arch}\"\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import sysconfig\n\n    plat = sysconfig.get_platform()\n    assert plat.startswith(\"linux-\"), \"not linux\"\n\n    print(\"plat:\", plat)\n    print(\"musl:\", _get_musl_version(sys.executable))\n    print(\"tags:\", end=\" \")\n    for t in platform_tags(re.sub(r\"[.-]\", \"_\", plat.split(\"-\", 1)[-1])):\n        print(t, end=\"\\n      \")\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/packaging/_structures.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\n\nclass InfinityType:\n    def __repr__(self) -> str:\n        return \"Infinity\"\n\n    def __hash__(self) -> int:\n        return hash(repr(self))\n\n    def __lt__(self, other: object) -> bool:\n        return False\n\n    def __le__(self, other: object) -> bool:\n        return False\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, self.__class__)\n\n    def __gt__(self, other: object) -> bool:\n        return True\n\n    def __ge__(self, other: object) -> bool:\n        return True\n\n    def __neg__(self: object) -> \"NegativeInfinityType\":\n        return NegativeInfinity\n\n\nInfinity = InfinityType()\n\n\nclass NegativeInfinityType:\n    def __repr__(self) -> str:\n        return \"-Infinity\"\n\n    def __hash__(self) -> int:\n        return hash(repr(self))\n\n    def __lt__(self, other: object) -> bool:\n        return True\n\n    def __le__(self, other: object) -> bool:\n        return True\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, self.__class__)\n\n    def __gt__(self, other: object) -> bool:\n        return False\n\n    def __ge__(self, other: object) -> bool:\n        return False\n\n    def __neg__(self: object) -> InfinityType:\n        return Infinity\n\n\nNegativeInfinity = NegativeInfinityType()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/packaging/markers.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport operator\nimport os\nimport platform\nimport sys\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union\n\nfrom setuptools.extern.pyparsing import (  # noqa: N817\n    Forward,\n    Group,\n    Literal as L,\n    ParseException,\n    ParseResults,\n    QuotedString,\n    ZeroOrMore,\n    stringEnd,\n    stringStart,\n)\n\nfrom .specifiers import InvalidSpecifier, Specifier\n\n__all__ = [\n    \"InvalidMarker\",\n    \"UndefinedComparison\",\n    \"UndefinedEnvironmentName\",\n    \"Marker\",\n    \"default_environment\",\n]\n\nOperator = Callable[[str, str], bool]\n\n\nclass InvalidMarker(ValueError):\n    \"\"\"\n    An invalid marker was found, users should refer to PEP 508.\n    \"\"\"\n\n\nclass UndefinedComparison(ValueError):\n    \"\"\"\n    An invalid operation was attempted on a value that doesn't support it.\n    \"\"\"\n\n\nclass UndefinedEnvironmentName(ValueError):\n    \"\"\"\n    A name was attempted to be used that does not exist inside of the\n    environment.\n    \"\"\"\n\n\nclass Node:\n    def __init__(self, value: Any) -> None:\n        self.value = value\n\n    def __str__(self) -> str:\n        return str(self.value)\n\n    def __repr__(self) -> str:\n        return f\"<{self.__class__.__name__}('{self}')>\"\n\n    def serialize(self) -> str:\n        raise NotImplementedError\n\n\nclass Variable(Node):\n    def serialize(self) -> str:\n        return str(self)\n\n\nclass Value(Node):\n    def serialize(self) -> str:\n        return f'\"{self}\"'\n\n\nclass Op(Node):\n    def serialize(self) -> str:\n        return str(self)\n\n\nVARIABLE = (\n    L(\"implementation_version\")\n    | L(\"platform_python_implementation\")\n    | L(\"implementation_name\")\n    | L(\"python_full_version\")\n    | L(\"platform_release\")\n    | L(\"platform_version\")\n    | L(\"platform_machine\")\n    | L(\"platform_system\")\n    | L(\"python_version\")\n    | L(\"sys_platform\")\n    | L(\"os_name\")\n    | L(\"os.name\")  # PEP-345\n    | L(\"sys.platform\")  # PEP-345\n    | L(\"platform.version\")  # PEP-345\n    | L(\"platform.machine\")  # PEP-345\n    | L(\"platform.python_implementation\")  # PEP-345\n    | L(\"python_implementation\")  # undocumented setuptools legacy\n    | L(\"extra\")  # PEP-508\n)\nALIASES = {\n    \"os.name\": \"os_name\",\n    \"sys.platform\": \"sys_platform\",\n    \"platform.version\": \"platform_version\",\n    \"platform.machine\": \"platform_machine\",\n    \"platform.python_implementation\": \"platform_python_implementation\",\n    \"python_implementation\": \"platform_python_implementation\",\n}\nVARIABLE.setParseAction(lambda s, l, t: Variable(ALIASES.get(t[0], t[0])))\n\nVERSION_CMP = (\n    L(\"===\") | L(\"==\") | L(\">=\") | L(\"<=\") | L(\"!=\") | L(\"~=\") | L(\">\") | L(\"<\")\n)\n\nMARKER_OP = VERSION_CMP | L(\"not in\") | L(\"in\")\nMARKER_OP.setParseAction(lambda s, l, t: Op(t[0]))\n\nMARKER_VALUE = QuotedString(\"'\") | QuotedString('\"')\nMARKER_VALUE.setParseAction(lambda s, l, t: Value(t[0]))\n\nBOOLOP = L(\"and\") | L(\"or\")\n\nMARKER_VAR = VARIABLE | MARKER_VALUE\n\nMARKER_ITEM = Group(MARKER_VAR + MARKER_OP + MARKER_VAR)\nMARKER_ITEM.setParseAction(lambda s, l, t: tuple(t[0]))\n\nLPAREN = L(\"(\").suppress()\nRPAREN = L(\")\").suppress()\n\nMARKER_EXPR = Forward()\nMARKER_ATOM = MARKER_ITEM | Group(LPAREN + MARKER_EXPR + RPAREN)\nMARKER_EXPR << MARKER_ATOM + ZeroOrMore(BOOLOP + MARKER_EXPR)\n\nMARKER = stringStart + MARKER_EXPR + stringEnd\n\n\ndef _coerce_parse_result(results: Union[ParseResults, List[Any]]) -> List[Any]:\n    if isinstance(results, ParseResults):\n        return [_coerce_parse_result(i) for i in results]\n    else:\n        return results\n\n\ndef _format_marker(\n    marker: Union[List[str], Tuple[Node, ...], str], first: Optional[bool] = True\n) -> str:\n\n    assert isinstance(marker, (list, tuple, str))\n\n    # Sometimes we have a structure like [[...]] which is a single item list\n    # where the single item is itself it's own list. In that case we want skip\n    # the rest of this function so that we don't get extraneous () on the\n    # outside.\n    if (\n        isinstance(marker, list)\n        and len(marker) == 1\n        and isinstance(marker[0], (list, tuple))\n    ):\n        return _format_marker(marker[0])\n\n    if isinstance(marker, list):\n        inner = (_format_marker(m, first=False) for m in marker)\n        if first:\n            return \" \".join(inner)\n        else:\n            return \"(\" + \" \".join(inner) + \")\"\n    elif isinstance(marker, tuple):\n        return \" \".join([m.serialize() for m in marker])\n    else:\n        return marker\n\n\n_operators: Dict[str, Operator] = {\n    \"in\": lambda lhs, rhs: lhs in rhs,\n    \"not in\": lambda lhs, rhs: lhs not in rhs,\n    \"<\": operator.lt,\n    \"<=\": operator.le,\n    \"==\": operator.eq,\n    \"!=\": operator.ne,\n    \">=\": operator.ge,\n    \">\": operator.gt,\n}\n\n\ndef _eval_op(lhs: str, op: Op, rhs: str) -> bool:\n    try:\n        spec = Specifier(\"\".join([op.serialize(), rhs]))\n    except InvalidSpecifier:\n        pass\n    else:\n        return spec.contains(lhs)\n\n    oper: Optional[Operator] = _operators.get(op.serialize())\n    if oper is None:\n        raise UndefinedComparison(f\"Undefined {op!r} on {lhs!r} and {rhs!r}.\")\n\n    return oper(lhs, rhs)\n\n\nclass Undefined:\n    pass\n\n\n_undefined = Undefined()\n\n\ndef _get_env(environment: Dict[str, str], name: str) -> str:\n    value: Union[str, Undefined] = environment.get(name, _undefined)\n\n    if isinstance(value, Undefined):\n        raise UndefinedEnvironmentName(\n            f\"{name!r} does not exist in evaluation environment.\"\n        )\n\n    return value\n\n\ndef _evaluate_markers(markers: List[Any], environment: Dict[str, str]) -> bool:\n    groups: List[List[bool]] = [[]]\n\n    for marker in markers:\n        assert isinstance(marker, (list, tuple, str))\n\n        if isinstance(marker, list):\n            groups[-1].append(_evaluate_markers(marker, environment))\n        elif isinstance(marker, tuple):\n            lhs, op, rhs = marker\n\n            if isinstance(lhs, Variable):\n                lhs_value = _get_env(environment, lhs.value)\n                rhs_value = rhs.value\n            else:\n                lhs_value = lhs.value\n                rhs_value = _get_env(environment, rhs.value)\n\n            groups[-1].append(_eval_op(lhs_value, op, rhs_value))\n        else:\n            assert marker in [\"and\", \"or\"]\n            if marker == \"or\":\n                groups.append([])\n\n    return any(all(item) for item in groups)\n\n\ndef format_full_version(info: \"sys._version_info\") -> str:\n    version = \"{0.major}.{0.minor}.{0.micro}\".format(info)\n    kind = info.releaselevel\n    if kind != \"final\":\n        version += kind[0] + str(info.serial)\n    return version\n\n\ndef default_environment() -> Dict[str, str]:\n    iver = format_full_version(sys.implementation.version)\n    implementation_name = sys.implementation.name\n    return {\n        \"implementation_name\": implementation_name,\n        \"implementation_version\": iver,\n        \"os_name\": os.name,\n        \"platform_machine\": platform.machine(),\n        \"platform_release\": platform.release(),\n        \"platform_system\": platform.system(),\n        \"platform_version\": platform.version(),\n        \"python_full_version\": platform.python_version(),\n        \"platform_python_implementation\": platform.python_implementation(),\n        \"python_version\": \".\".join(platform.python_version_tuple()[:2]),\n        \"sys_platform\": sys.platform,\n    }\n\n\nclass Marker:\n    def __init__(self, marker: str) -> None:\n        try:\n            self._markers = _coerce_parse_result(MARKER.parseString(marker))\n        except ParseException as e:\n            raise InvalidMarker(\n                f\"Invalid marker: {marker!r}, parse error at \"\n                f\"{marker[e.loc : e.loc + 8]!r}\"\n            )\n\n    def __str__(self) -> str:\n        return _format_marker(self._markers)\n\n    def __repr__(self) -> str:\n        return f\"<Marker('{self}')>\"\n\n    def evaluate(self, environment: Optional[Dict[str, str]] = None) -> bool:\n        \"\"\"Evaluate a marker.\n\n        Return the boolean from evaluating the given marker against the\n        environment. environment is an optional argument to override all or\n        part of the determined environment.\n\n        The environment is determined from the current Python process.\n        \"\"\"\n        current_environment = default_environment()\n        if environment is not None:\n            current_environment.update(environment)\n\n        return _evaluate_markers(self._markers, current_environment)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/packaging/requirements.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport re\nimport string\nimport urllib.parse\nfrom typing import List, Optional as TOptional, Set\n\nfrom setuptools.extern.pyparsing import (  # noqa\n    Combine,\n    Literal as L,\n    Optional,\n    ParseException,\n    Regex,\n    Word,\n    ZeroOrMore,\n    originalTextFor,\n    stringEnd,\n    stringStart,\n)\n\nfrom .markers import MARKER_EXPR, Marker\nfrom .specifiers import LegacySpecifier, Specifier, SpecifierSet\n\n\nclass InvalidRequirement(ValueError):\n    \"\"\"\n    An invalid requirement was found, users should refer to PEP 508.\n    \"\"\"\n\n\nALPHANUM = Word(string.ascii_letters + string.digits)\n\nLBRACKET = L(\"[\").suppress()\nRBRACKET = L(\"]\").suppress()\nLPAREN = L(\"(\").suppress()\nRPAREN = L(\")\").suppress()\nCOMMA = L(\",\").suppress()\nSEMICOLON = L(\";\").suppress()\nAT = L(\"@\").suppress()\n\nPUNCTUATION = Word(\"-_.\")\nIDENTIFIER_END = ALPHANUM | (ZeroOrMore(PUNCTUATION) + ALPHANUM)\nIDENTIFIER = Combine(ALPHANUM + ZeroOrMore(IDENTIFIER_END))\n\nNAME = IDENTIFIER(\"name\")\nEXTRA = IDENTIFIER\n\nURI = Regex(r\"[^ ]+\")(\"url\")\nURL = AT + URI\n\nEXTRAS_LIST = EXTRA + ZeroOrMore(COMMA + EXTRA)\nEXTRAS = (LBRACKET + Optional(EXTRAS_LIST) + RBRACKET)(\"extras\")\n\nVERSION_PEP440 = Regex(Specifier._regex_str, re.VERBOSE | re.IGNORECASE)\nVERSION_LEGACY = Regex(LegacySpecifier._regex_str, re.VERBOSE | re.IGNORECASE)\n\nVERSION_ONE = VERSION_PEP440 ^ VERSION_LEGACY\nVERSION_MANY = Combine(\n    VERSION_ONE + ZeroOrMore(COMMA + VERSION_ONE), joinString=\",\", adjacent=False\n)(\"_raw_spec\")\n_VERSION_SPEC = Optional((LPAREN + VERSION_MANY + RPAREN) | VERSION_MANY)\n_VERSION_SPEC.setParseAction(lambda s, l, t: t._raw_spec or \"\")\n\nVERSION_SPEC = originalTextFor(_VERSION_SPEC)(\"specifier\")\nVERSION_SPEC.setParseAction(lambda s, l, t: t[1])\n\nMARKER_EXPR = originalTextFor(MARKER_EXPR())(\"marker\")\nMARKER_EXPR.setParseAction(\n    lambda s, l, t: Marker(s[t._original_start : t._original_end])\n)\nMARKER_SEPARATOR = SEMICOLON\nMARKER = MARKER_SEPARATOR + MARKER_EXPR\n\nVERSION_AND_MARKER = VERSION_SPEC + Optional(MARKER)\nURL_AND_MARKER = URL + Optional(MARKER)\n\nNAMED_REQUIREMENT = NAME + Optional(EXTRAS) + (URL_AND_MARKER | VERSION_AND_MARKER)\n\nREQUIREMENT = stringStart + NAMED_REQUIREMENT + stringEnd\n# setuptools.extern.pyparsing isn't thread safe during initialization, so we do it eagerly, see\n# issue #104\nREQUIREMENT.parseString(\"x[]\")\n\n\nclass Requirement:\n    \"\"\"Parse a requirement.\n\n    Parse a given requirement string into its parts, such as name, specifier,\n    URL, and extras. Raises InvalidRequirement on a badly-formed requirement\n    string.\n    \"\"\"\n\n    # TODO: Can we test whether something is contained within a requirement?\n    #       If so how do we do that? Do we need to test against the _name_ of\n    #       the thing as well as the version? What about the markers?\n    # TODO: Can we normalize the name and extra name?\n\n    def __init__(self, requirement_string: str) -> None:\n        try:\n            req = REQUIREMENT.parseString(requirement_string)\n        except ParseException as e:\n            raise InvalidRequirement(\n                f'Parse error at \"{ requirement_string[e.loc : e.loc + 8]!r}\": {e.msg}'\n            )\n\n        self.name: str = req.name\n        if req.url:\n            parsed_url = urllib.parse.urlparse(req.url)\n            if parsed_url.scheme == \"file\":\n                if urllib.parse.urlunparse(parsed_url) != req.url:\n                    raise InvalidRequirement(\"Invalid URL given\")\n            elif not (parsed_url.scheme and parsed_url.netloc) or (\n                not parsed_url.scheme and not parsed_url.netloc\n            ):\n                raise InvalidRequirement(f\"Invalid URL: {req.url}\")\n            self.url: TOptional[str] = req.url\n        else:\n            self.url = None\n        self.extras: Set[str] = set(req.extras.asList() if req.extras else [])\n        self.specifier: SpecifierSet = SpecifierSet(req.specifier)\n        self.marker: TOptional[Marker] = req.marker if req.marker else None\n\n    def __str__(self) -> str:\n        parts: List[str] = [self.name]\n\n        if self.extras:\n            formatted_extras = \",\".join(sorted(self.extras))\n            parts.append(f\"[{formatted_extras}]\")\n\n        if self.specifier:\n            parts.append(str(self.specifier))\n\n        if self.url:\n            parts.append(f\"@ {self.url}\")\n            if self.marker:\n                parts.append(\" \")\n\n        if self.marker:\n            parts.append(f\"; {self.marker}\")\n\n        return \"\".join(parts)\n\n    def __repr__(self) -> str:\n        return f\"<Requirement('{self}')>\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/packaging/specifiers.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport abc\nimport functools\nimport itertools\nimport re\nimport warnings\nfrom typing import (\n    Callable,\n    Dict,\n    Iterable,\n    Iterator,\n    List,\n    Optional,\n    Pattern,\n    Set,\n    Tuple,\n    TypeVar,\n    Union,\n)\n\nfrom .utils import canonicalize_version\nfrom .version import LegacyVersion, Version, parse\n\nParsedVersion = Union[Version, LegacyVersion]\nUnparsedVersion = Union[Version, LegacyVersion, str]\nVersionTypeVar = TypeVar(\"VersionTypeVar\", bound=UnparsedVersion)\nCallableOperator = Callable[[ParsedVersion, str], bool]\n\n\nclass InvalidSpecifier(ValueError):\n    \"\"\"\n    An invalid specifier was found, users should refer to PEP 440.\n    \"\"\"\n\n\nclass BaseSpecifier(metaclass=abc.ABCMeta):\n    @abc.abstractmethod\n    def __str__(self) -> str:\n        \"\"\"\n        Returns the str representation of this Specifier like object. This\n        should be representative of the Specifier itself.\n        \"\"\"\n\n    @abc.abstractmethod\n    def __hash__(self) -> int:\n        \"\"\"\n        Returns a hash value for this Specifier like object.\n        \"\"\"\n\n    @abc.abstractmethod\n    def __eq__(self, other: object) -> bool:\n        \"\"\"\n        Returns a boolean representing whether or not the two Specifier like\n        objects are equal.\n        \"\"\"\n\n    @abc.abstractproperty\n    def prereleases(self) -> Optional[bool]:\n        \"\"\"\n        Returns whether or not pre-releases as a whole are allowed by this\n        specifier.\n        \"\"\"\n\n    @prereleases.setter\n    def prereleases(self, value: bool) -> None:\n        \"\"\"\n        Sets whether or not pre-releases as a whole are allowed by this\n        specifier.\n        \"\"\"\n\n    @abc.abstractmethod\n    def contains(self, item: str, prereleases: Optional[bool] = None) -> bool:\n        \"\"\"\n        Determines if the given item is contained within this specifier.\n        \"\"\"\n\n    @abc.abstractmethod\n    def filter(\n        self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None\n    ) -> Iterable[VersionTypeVar]:\n        \"\"\"\n        Takes an iterable of items and filters them so that only items which\n        are contained within this specifier are allowed in it.\n        \"\"\"\n\n\nclass _IndividualSpecifier(BaseSpecifier):\n\n    _operators: Dict[str, str] = {}\n    _regex: Pattern[str]\n\n    def __init__(self, spec: str = \"\", prereleases: Optional[bool] = None) -> None:\n        match = self._regex.search(spec)\n        if not match:\n            raise InvalidSpecifier(f\"Invalid specifier: '{spec}'\")\n\n        self._spec: Tuple[str, str] = (\n            match.group(\"operator\").strip(),\n            match.group(\"version\").strip(),\n        )\n\n        # Store whether or not this Specifier should accept prereleases\n        self._prereleases = prereleases\n\n    def __repr__(self) -> str:\n        pre = (\n            f\", prereleases={self.prereleases!r}\"\n            if self._prereleases is not None\n            else \"\"\n        )\n\n        return f\"<{self.__class__.__name__}({str(self)!r}{pre})>\"\n\n    def __str__(self) -> str:\n        return \"{}{}\".format(*self._spec)\n\n    @property\n    def _canonical_spec(self) -> Tuple[str, str]:\n        return self._spec[0], canonicalize_version(self._spec[1])\n\n    def __hash__(self) -> int:\n        return hash(self._canonical_spec)\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, str):\n            try:\n                other = self.__class__(str(other))\n            except InvalidSpecifier:\n                return NotImplemented\n        elif not isinstance(other, self.__class__):\n            return NotImplemented\n\n        return self._canonical_spec == other._canonical_spec\n\n    def _get_operator(self, op: str) -> CallableOperator:\n        operator_callable: CallableOperator = getattr(\n            self, f\"_compare_{self._operators[op]}\"\n        )\n        return operator_callable\n\n    def _coerce_version(self, version: UnparsedVersion) -> ParsedVersion:\n        if not isinstance(version, (LegacyVersion, Version)):\n            version = parse(version)\n        return version\n\n    @property\n    def operator(self) -> str:\n        return self._spec[0]\n\n    @property\n    def version(self) -> str:\n        return self._spec[1]\n\n    @property\n    def prereleases(self) -> Optional[bool]:\n        return self._prereleases\n\n    @prereleases.setter\n    def prereleases(self, value: bool) -> None:\n        self._prereleases = value\n\n    def __contains__(self, item: str) -> bool:\n        return self.contains(item)\n\n    def contains(\n        self, item: UnparsedVersion, prereleases: Optional[bool] = None\n    ) -> bool:\n\n        # Determine if prereleases are to be allowed or not.\n        if prereleases is None:\n            prereleases = self.prereleases\n\n        # Normalize item to a Version or LegacyVersion, this allows us to have\n        # a shortcut for ``\"2.0\" in Specifier(\">=2\")\n        normalized_item = self._coerce_version(item)\n\n        # Determine if we should be supporting prereleases in this specifier\n        # or not, if we do not support prereleases than we can short circuit\n        # logic if this version is a prereleases.\n        if normalized_item.is_prerelease and not prereleases:\n            return False\n\n        # Actually do the comparison to determine if this item is contained\n        # within this Specifier or not.\n        operator_callable: CallableOperator = self._get_operator(self.operator)\n        return operator_callable(normalized_item, self.version)\n\n    def filter(\n        self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None\n    ) -> Iterable[VersionTypeVar]:\n\n        yielded = False\n        found_prereleases = []\n\n        kw = {\"prereleases\": prereleases if prereleases is not None else True}\n\n        # Attempt to iterate over all the values in the iterable and if any of\n        # them match, yield them.\n        for version in iterable:\n            parsed_version = self._coerce_version(version)\n\n            if self.contains(parsed_version, **kw):\n                # If our version is a prerelease, and we were not set to allow\n                # prereleases, then we'll store it for later in case nothing\n                # else matches this specifier.\n                if parsed_version.is_prerelease and not (\n                    prereleases or self.prereleases\n                ):\n                    found_prereleases.append(version)\n                # Either this is not a prerelease, or we should have been\n                # accepting prereleases from the beginning.\n                else:\n                    yielded = True\n                    yield version\n\n        # Now that we've iterated over everything, determine if we've yielded\n        # any values, and if we have not and we have any prereleases stored up\n        # then we will go ahead and yield the prereleases.\n        if not yielded and found_prereleases:\n            for version in found_prereleases:\n                yield version\n\n\nclass LegacySpecifier(_IndividualSpecifier):\n\n    _regex_str = r\"\"\"\n        (?P<operator>(==|!=|<=|>=|<|>))\n        \\s*\n        (?P<version>\n            [^,;\\s)]* # Since this is a \"legacy\" specifier, and the version\n                      # string can be just about anything, we match everything\n                      # except for whitespace, a semi-colon for marker support,\n                      # a closing paren since versions can be enclosed in\n                      # them, and a comma since it's a version separator.\n        )\n        \"\"\"\n\n    _regex = re.compile(r\"^\\s*\" + _regex_str + r\"\\s*$\", re.VERBOSE | re.IGNORECASE)\n\n    _operators = {\n        \"==\": \"equal\",\n        \"!=\": \"not_equal\",\n        \"<=\": \"less_than_equal\",\n        \">=\": \"greater_than_equal\",\n        \"<\": \"less_than\",\n        \">\": \"greater_than\",\n    }\n\n    def __init__(self, spec: str = \"\", prereleases: Optional[bool] = None) -> None:\n        super().__init__(spec, prereleases)\n\n        warnings.warn(\n            \"Creating a LegacyVersion has been deprecated and will be \"\n            \"removed in the next major release\",\n            DeprecationWarning,\n        )\n\n    def _coerce_version(self, version: UnparsedVersion) -> LegacyVersion:\n        if not isinstance(version, LegacyVersion):\n            version = LegacyVersion(str(version))\n        return version\n\n    def _compare_equal(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective == self._coerce_version(spec)\n\n    def _compare_not_equal(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective != self._coerce_version(spec)\n\n    def _compare_less_than_equal(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective <= self._coerce_version(spec)\n\n    def _compare_greater_than_equal(\n        self, prospective: LegacyVersion, spec: str\n    ) -> bool:\n        return prospective >= self._coerce_version(spec)\n\n    def _compare_less_than(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective < self._coerce_version(spec)\n\n    def _compare_greater_than(self, prospective: LegacyVersion, spec: str) -> bool:\n        return prospective > self._coerce_version(spec)\n\n\ndef _require_version_compare(\n    fn: Callable[[\"Specifier\", ParsedVersion, str], bool]\n) -> Callable[[\"Specifier\", ParsedVersion, str], bool]:\n    @functools.wraps(fn)\n    def wrapped(self: \"Specifier\", prospective: ParsedVersion, spec: str) -> bool:\n        if not isinstance(prospective, Version):\n            return False\n        return fn(self, prospective, spec)\n\n    return wrapped\n\n\nclass Specifier(_IndividualSpecifier):\n\n    _regex_str = r\"\"\"\n        (?P<operator>(~=|==|!=|<=|>=|<|>|===))\n        (?P<version>\n            (?:\n                # The identity operators allow for an escape hatch that will\n                # do an exact string match of the version you wish to install.\n                # This will not be parsed by PEP 440 and we cannot determine\n                # any semantic meaning from it. This operator is discouraged\n                # but included entirely as an escape hatch.\n                (?<====)  # Only match for the identity operator\n                \\s*\n                [^\\s]*    # We just match everything, except for whitespace\n                          # since we are only testing for strict identity.\n            )\n            |\n            (?:\n                # The (non)equality operators allow for wild card and local\n                # versions to be specified so we have to define these two\n                # operators separately to enable that.\n                (?<===|!=)            # Only match for equals and not equals\n\n                \\s*\n                v?\n                (?:[0-9]+!)?          # epoch\n                [0-9]+(?:\\.[0-9]+)*   # release\n                (?:                   # pre release\n                    [-_\\.]?\n                    (a|b|c|rc|alpha|beta|pre|preview)\n                    [-_\\.]?\n                    [0-9]*\n                )?\n                (?:                   # post release\n                    (?:-[0-9]+)|(?:[-_\\.]?(post|rev|r)[-_\\.]?[0-9]*)\n                )?\n\n                # You cannot use a wild card and a dev or local version\n                # together so group them with a | and make them optional.\n                (?:\n                    (?:[-_\\.]?dev[-_\\.]?[0-9]*)?         # dev release\n                    (?:\\+[a-z0-9]+(?:[-_\\.][a-z0-9]+)*)? # local\n                    |\n                    \\.\\*  # Wild card syntax of .*\n                )?\n            )\n            |\n            (?:\n                # The compatible operator requires at least two digits in the\n                # release segment.\n                (?<=~=)               # Only match for the compatible operator\n\n                \\s*\n                v?\n                (?:[0-9]+!)?          # epoch\n                [0-9]+(?:\\.[0-9]+)+   # release  (We have a + instead of a *)\n                (?:                   # pre release\n                    [-_\\.]?\n                    (a|b|c|rc|alpha|beta|pre|preview)\n                    [-_\\.]?\n                    [0-9]*\n                )?\n                (?:                                   # post release\n                    (?:-[0-9]+)|(?:[-_\\.]?(post|rev|r)[-_\\.]?[0-9]*)\n                )?\n                (?:[-_\\.]?dev[-_\\.]?[0-9]*)?          # dev release\n            )\n            |\n            (?:\n                # All other operators only allow a sub set of what the\n                # (non)equality operators do. Specifically they do not allow\n                # local versions to be specified nor do they allow the prefix\n                # matching wild cards.\n                (?<!==|!=|~=)         # We have special cases for these\n                                      # operators so we want to make sure they\n                                      # don't match here.\n\n                \\s*\n                v?\n                (?:[0-9]+!)?          # epoch\n                [0-9]+(?:\\.[0-9]+)*   # release\n                (?:                   # pre release\n                    [-_\\.]?\n                    (a|b|c|rc|alpha|beta|pre|preview)\n                    [-_\\.]?\n                    [0-9]*\n                )?\n                (?:                                   # post release\n                    (?:-[0-9]+)|(?:[-_\\.]?(post|rev|r)[-_\\.]?[0-9]*)\n                )?\n                (?:[-_\\.]?dev[-_\\.]?[0-9]*)?          # dev release\n            )\n        )\n        \"\"\"\n\n    _regex = re.compile(r\"^\\s*\" + _regex_str + r\"\\s*$\", re.VERBOSE | re.IGNORECASE)\n\n    _operators = {\n        \"~=\": \"compatible\",\n        \"==\": \"equal\",\n        \"!=\": \"not_equal\",\n        \"<=\": \"less_than_equal\",\n        \">=\": \"greater_than_equal\",\n        \"<\": \"less_than\",\n        \">\": \"greater_than\",\n        \"===\": \"arbitrary\",\n    }\n\n    @_require_version_compare\n    def _compare_compatible(self, prospective: ParsedVersion, spec: str) -> bool:\n\n        # Compatible releases have an equivalent combination of >= and ==. That\n        # is that ~=2.2 is equivalent to >=2.2,==2.*. This allows us to\n        # implement this in terms of the other specifiers instead of\n        # implementing it ourselves. The only thing we need to do is construct\n        # the other specifiers.\n\n        # We want everything but the last item in the version, but we want to\n        # ignore suffix segments.\n        prefix = \".\".join(\n            list(itertools.takewhile(_is_not_suffix, _version_split(spec)))[:-1]\n        )\n\n        # Add the prefix notation to the end of our string\n        prefix += \".*\"\n\n        return self._get_operator(\">=\")(prospective, spec) and self._get_operator(\"==\")(\n            prospective, prefix\n        )\n\n    @_require_version_compare\n    def _compare_equal(self, prospective: ParsedVersion, spec: str) -> bool:\n\n        # We need special logic to handle prefix matching\n        if spec.endswith(\".*\"):\n            # In the case of prefix matching we want to ignore local segment.\n            prospective = Version(prospective.public)\n            # Split the spec out by dots, and pretend that there is an implicit\n            # dot in between a release segment and a pre-release segment.\n            split_spec = _version_split(spec[:-2])  # Remove the trailing .*\n\n            # Split the prospective version out by dots, and pretend that there\n            # is an implicit dot in between a release segment and a pre-release\n            # segment.\n            split_prospective = _version_split(str(prospective))\n\n            # Shorten the prospective version to be the same length as the spec\n            # so that we can determine if the specifier is a prefix of the\n            # prospective version or not.\n            shortened_prospective = split_prospective[: len(split_spec)]\n\n            # Pad out our two sides with zeros so that they both equal the same\n            # length.\n            padded_spec, padded_prospective = _pad_version(\n                split_spec, shortened_prospective\n            )\n\n            return padded_prospective == padded_spec\n        else:\n            # Convert our spec string into a Version\n            spec_version = Version(spec)\n\n            # If the specifier does not have a local segment, then we want to\n            # act as if the prospective version also does not have a local\n            # segment.\n            if not spec_version.local:\n                prospective = Version(prospective.public)\n\n            return prospective == spec_version\n\n    @_require_version_compare\n    def _compare_not_equal(self, prospective: ParsedVersion, spec: str) -> bool:\n        return not self._compare_equal(prospective, spec)\n\n    @_require_version_compare\n    def _compare_less_than_equal(self, prospective: ParsedVersion, spec: str) -> bool:\n\n        # NB: Local version identifiers are NOT permitted in the version\n        # specifier, so local version labels can be universally removed from\n        # the prospective version.\n        return Version(prospective.public) <= Version(spec)\n\n    @_require_version_compare\n    def _compare_greater_than_equal(\n        self, prospective: ParsedVersion, spec: str\n    ) -> bool:\n\n        # NB: Local version identifiers are NOT permitted in the version\n        # specifier, so local version labels can be universally removed from\n        # the prospective version.\n        return Version(prospective.public) >= Version(spec)\n\n    @_require_version_compare\n    def _compare_less_than(self, prospective: ParsedVersion, spec_str: str) -> bool:\n\n        # Convert our spec to a Version instance, since we'll want to work with\n        # it as a version.\n        spec = Version(spec_str)\n\n        # Check to see if the prospective version is less than the spec\n        # version. If it's not we can short circuit and just return False now\n        # instead of doing extra unneeded work.\n        if not prospective < spec:\n            return False\n\n        # This special case is here so that, unless the specifier itself\n        # includes is a pre-release version, that we do not accept pre-release\n        # versions for the version mentioned in the specifier (e.g. <3.1 should\n        # not match 3.1.dev0, but should match 3.0.dev0).\n        if not spec.is_prerelease and prospective.is_prerelease:\n            if Version(prospective.base_version) == Version(spec.base_version):\n                return False\n\n        # If we've gotten to here, it means that prospective version is both\n        # less than the spec version *and* it's not a pre-release of the same\n        # version in the spec.\n        return True\n\n    @_require_version_compare\n    def _compare_greater_than(self, prospective: ParsedVersion, spec_str: str) -> bool:\n\n        # Convert our spec to a Version instance, since we'll want to work with\n        # it as a version.\n        spec = Version(spec_str)\n\n        # Check to see if the prospective version is greater than the spec\n        # version. If it's not we can short circuit and just return False now\n        # instead of doing extra unneeded work.\n        if not prospective > spec:\n            return False\n\n        # This special case is here so that, unless the specifier itself\n        # includes is a post-release version, that we do not accept\n        # post-release versions for the version mentioned in the specifier\n        # (e.g. >3.1 should not match 3.0.post0, but should match 3.2.post0).\n        if not spec.is_postrelease and prospective.is_postrelease:\n            if Version(prospective.base_version) == Version(spec.base_version):\n                return False\n\n        # Ensure that we do not allow a local version of the version mentioned\n        # in the specifier, which is technically greater than, to match.\n        if prospective.local is not None:\n            if Version(prospective.base_version) == Version(spec.base_version):\n                return False\n\n        # If we've gotten to here, it means that prospective version is both\n        # greater than the spec version *and* it's not a pre-release of the\n        # same version in the spec.\n        return True\n\n    def _compare_arbitrary(self, prospective: Version, spec: str) -> bool:\n        return str(prospective).lower() == str(spec).lower()\n\n    @property\n    def prereleases(self) -> bool:\n\n        # If there is an explicit prereleases set for this, then we'll just\n        # blindly use that.\n        if self._prereleases is not None:\n            return self._prereleases\n\n        # Look at all of our specifiers and determine if they are inclusive\n        # operators, and if they are if they are including an explicit\n        # prerelease.\n        operator, version = self._spec\n        if operator in [\"==\", \">=\", \"<=\", \"~=\", \"===\"]:\n            # The == specifier can include a trailing .*, if it does we\n            # want to remove before parsing.\n            if operator == \"==\" and version.endswith(\".*\"):\n                version = version[:-2]\n\n            # Parse the version, and if it is a pre-release than this\n            # specifier allows pre-releases.\n            if parse(version).is_prerelease:\n                return True\n\n        return False\n\n    @prereleases.setter\n    def prereleases(self, value: bool) -> None:\n        self._prereleases = value\n\n\n_prefix_regex = re.compile(r\"^([0-9]+)((?:a|b|c|rc)[0-9]+)$\")\n\n\ndef _version_split(version: str) -> List[str]:\n    result: List[str] = []\n    for item in version.split(\".\"):\n        match = _prefix_regex.search(item)\n        if match:\n            result.extend(match.groups())\n        else:\n            result.append(item)\n    return result\n\n\ndef _is_not_suffix(segment: str) -> bool:\n    return not any(\n        segment.startswith(prefix) for prefix in (\"dev\", \"a\", \"b\", \"rc\", \"post\")\n    )\n\n\ndef _pad_version(left: List[str], right: List[str]) -> Tuple[List[str], List[str]]:\n    left_split, right_split = [], []\n\n    # Get the release segment of our versions\n    left_split.append(list(itertools.takewhile(lambda x: x.isdigit(), left)))\n    right_split.append(list(itertools.takewhile(lambda x: x.isdigit(), right)))\n\n    # Get the rest of our versions\n    left_split.append(left[len(left_split[0]) :])\n    right_split.append(right[len(right_split[0]) :])\n\n    # Insert our padding\n    left_split.insert(1, [\"0\"] * max(0, len(right_split[0]) - len(left_split[0])))\n    right_split.insert(1, [\"0\"] * max(0, len(left_split[0]) - len(right_split[0])))\n\n    return (list(itertools.chain(*left_split)), list(itertools.chain(*right_split)))\n\n\nclass SpecifierSet(BaseSpecifier):\n    def __init__(\n        self, specifiers: str = \"\", prereleases: Optional[bool] = None\n    ) -> None:\n\n        # Split on , to break each individual specifier into it's own item, and\n        # strip each item to remove leading/trailing whitespace.\n        split_specifiers = [s.strip() for s in specifiers.split(\",\") if s.strip()]\n\n        # Parsed each individual specifier, attempting first to make it a\n        # Specifier and falling back to a LegacySpecifier.\n        parsed: Set[_IndividualSpecifier] = set()\n        for specifier in split_specifiers:\n            try:\n                parsed.add(Specifier(specifier))\n            except InvalidSpecifier:\n                parsed.add(LegacySpecifier(specifier))\n\n        # Turn our parsed specifiers into a frozen set and save them for later.\n        self._specs = frozenset(parsed)\n\n        # Store our prereleases value so we can use it later to determine if\n        # we accept prereleases or not.\n        self._prereleases = prereleases\n\n    def __repr__(self) -> str:\n        pre = (\n            f\", prereleases={self.prereleases!r}\"\n            if self._prereleases is not None\n            else \"\"\n        )\n\n        return f\"<SpecifierSet({str(self)!r}{pre})>\"\n\n    def __str__(self) -> str:\n        return \",\".join(sorted(str(s) for s in self._specs))\n\n    def __hash__(self) -> int:\n        return hash(self._specs)\n\n    def __and__(self, other: Union[\"SpecifierSet\", str]) -> \"SpecifierSet\":\n        if isinstance(other, str):\n            other = SpecifierSet(other)\n        elif not isinstance(other, SpecifierSet):\n            return NotImplemented\n\n        specifier = SpecifierSet()\n        specifier._specs = frozenset(self._specs | other._specs)\n\n        if self._prereleases is None and other._prereleases is not None:\n            specifier._prereleases = other._prereleases\n        elif self._prereleases is not None and other._prereleases is None:\n            specifier._prereleases = self._prereleases\n        elif self._prereleases == other._prereleases:\n            specifier._prereleases = self._prereleases\n        else:\n            raise ValueError(\n                \"Cannot combine SpecifierSets with True and False prerelease \"\n                \"overrides.\"\n            )\n\n        return specifier\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, (str, _IndividualSpecifier)):\n            other = SpecifierSet(str(other))\n        elif not isinstance(other, SpecifierSet):\n            return NotImplemented\n\n        return self._specs == other._specs\n\n    def __len__(self) -> int:\n        return len(self._specs)\n\n    def __iter__(self) -> Iterator[_IndividualSpecifier]:\n        return iter(self._specs)\n\n    @property\n    def prereleases(self) -> Optional[bool]:\n\n        # If we have been given an explicit prerelease modifier, then we'll\n        # pass that through here.\n        if self._prereleases is not None:\n            return self._prereleases\n\n        # If we don't have any specifiers, and we don't have a forced value,\n        # then we'll just return None since we don't know if this should have\n        # pre-releases or not.\n        if not self._specs:\n            return None\n\n        # Otherwise we'll see if any of the given specifiers accept\n        # prereleases, if any of them do we'll return True, otherwise False.\n        return any(s.prereleases for s in self._specs)\n\n    @prereleases.setter\n    def prereleases(self, value: bool) -> None:\n        self._prereleases = value\n\n    def __contains__(self, item: UnparsedVersion) -> bool:\n        return self.contains(item)\n\n    def contains(\n        self, item: UnparsedVersion, prereleases: Optional[bool] = None\n    ) -> bool:\n\n        # Ensure that our item is a Version or LegacyVersion instance.\n        if not isinstance(item, (LegacyVersion, Version)):\n            item = parse(item)\n\n        # Determine if we're forcing a prerelease or not, if we're not forcing\n        # one for this particular filter call, then we'll use whatever the\n        # SpecifierSet thinks for whether or not we should support prereleases.\n        if prereleases is None:\n            prereleases = self.prereleases\n\n        # We can determine if we're going to allow pre-releases by looking to\n        # see if any of the underlying items supports them. If none of them do\n        # and this item is a pre-release then we do not allow it and we can\n        # short circuit that here.\n        # Note: This means that 1.0.dev1 would not be contained in something\n        #       like >=1.0.devabc however it would be in >=1.0.debabc,>0.0.dev0\n        if not prereleases and item.is_prerelease:\n            return False\n\n        # We simply dispatch to the underlying specs here to make sure that the\n        # given version is contained within all of them.\n        # Note: This use of all() here means that an empty set of specifiers\n        #       will always return True, this is an explicit design decision.\n        return all(s.contains(item, prereleases=prereleases) for s in self._specs)\n\n    def filter(\n        self, iterable: Iterable[VersionTypeVar], prereleases: Optional[bool] = None\n    ) -> Iterable[VersionTypeVar]:\n\n        # Determine if we're forcing a prerelease or not, if we're not forcing\n        # one for this particular filter call, then we'll use whatever the\n        # SpecifierSet thinks for whether or not we should support prereleases.\n        if prereleases is None:\n            prereleases = self.prereleases\n\n        # If we have any specifiers, then we want to wrap our iterable in the\n        # filter method for each one, this will act as a logical AND amongst\n        # each specifier.\n        if self._specs:\n            for spec in self._specs:\n                iterable = spec.filter(iterable, prereleases=bool(prereleases))\n            return iterable\n        # If we do not have any specifiers, then we need to have a rough filter\n        # which will filter out any pre-releases, unless there are no final\n        # releases, and which will filter out LegacyVersion in general.\n        else:\n            filtered: List[VersionTypeVar] = []\n            found_prereleases: List[VersionTypeVar] = []\n\n            item: UnparsedVersion\n            parsed_version: Union[Version, LegacyVersion]\n\n            for item in iterable:\n                # Ensure that we some kind of Version class for this item.\n                if not isinstance(item, (LegacyVersion, Version)):\n                    parsed_version = parse(item)\n                else:\n                    parsed_version = item\n\n                # Filter out any item which is parsed as a LegacyVersion\n                if isinstance(parsed_version, LegacyVersion):\n                    continue\n\n                # Store any item which is a pre-release for later unless we've\n                # already found a final version or we are accepting prereleases\n                if parsed_version.is_prerelease and not prereleases:\n                    if not filtered:\n                        found_prereleases.append(item)\n                else:\n                    filtered.append(item)\n\n            # If we've found no items except for pre-releases, then we'll go\n            # ahead and use the pre-releases\n            if not filtered and found_prereleases and prereleases is None:\n                return found_prereleases\n\n            return filtered\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/packaging/tags.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport logging\nimport platform\nimport sys\nimport sysconfig\nfrom importlib.machinery import EXTENSION_SUFFIXES\nfrom typing import (\n    Dict,\n    FrozenSet,\n    Iterable,\n    Iterator,\n    List,\n    Optional,\n    Sequence,\n    Tuple,\n    Union,\n    cast,\n)\n\nfrom . import _manylinux, _musllinux\n\nlogger = logging.getLogger(__name__)\n\nPythonVersion = Sequence[int]\nMacVersion = Tuple[int, int]\n\nINTERPRETER_SHORT_NAMES: Dict[str, str] = {\n    \"python\": \"py\",  # Generic.\n    \"cpython\": \"cp\",\n    \"pypy\": \"pp\",\n    \"ironpython\": \"ip\",\n    \"jython\": \"jy\",\n}\n\n\n_32_BIT_INTERPRETER = sys.maxsize <= 2 ** 32\n\n\nclass Tag:\n    \"\"\"\n    A representation of the tag triple for a wheel.\n\n    Instances are considered immutable and thus are hashable. Equality checking\n    is also supported.\n    \"\"\"\n\n    __slots__ = [\"_interpreter\", \"_abi\", \"_platform\", \"_hash\"]\n\n    def __init__(self, interpreter: str, abi: str, platform: str) -> None:\n        self._interpreter = interpreter.lower()\n        self._abi = abi.lower()\n        self._platform = platform.lower()\n        # The __hash__ of every single element in a Set[Tag] will be evaluated each time\n        # that a set calls its `.disjoint()` method, which may be called hundreds of\n        # times when scanning a page of links for packages with tags matching that\n        # Set[Tag]. Pre-computing the value here produces significant speedups for\n        # downstream consumers.\n        self._hash = hash((self._interpreter, self._abi, self._platform))\n\n    @property\n    def interpreter(self) -> str:\n        return self._interpreter\n\n    @property\n    def abi(self) -> str:\n        return self._abi\n\n    @property\n    def platform(self) -> str:\n        return self._platform\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Tag):\n            return NotImplemented\n\n        return (\n            (self._hash == other._hash)  # Short-circuit ASAP for perf reasons.\n            and (self._platform == other._platform)\n            and (self._abi == other._abi)\n            and (self._interpreter == other._interpreter)\n        )\n\n    def __hash__(self) -> int:\n        return self._hash\n\n    def __str__(self) -> str:\n        return f\"{self._interpreter}-{self._abi}-{self._platform}\"\n\n    def __repr__(self) -> str:\n        return f\"<{self} @ {id(self)}>\"\n\n\ndef parse_tag(tag: str) -> FrozenSet[Tag]:\n    \"\"\"\n    Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.\n\n    Returning a set is required due to the possibility that the tag is a\n    compressed tag set.\n    \"\"\"\n    tags = set()\n    interpreters, abis, platforms = tag.split(\"-\")\n    for interpreter in interpreters.split(\".\"):\n        for abi in abis.split(\".\"):\n            for platform_ in platforms.split(\".\"):\n                tags.add(Tag(interpreter, abi, platform_))\n    return frozenset(tags)\n\n\ndef _get_config_var(name: str, warn: bool = False) -> Union[int, str, None]:\n    value = sysconfig.get_config_var(name)\n    if value is None and warn:\n        logger.debug(\n            \"Config variable '%s' is unset, Python ABI tag may be incorrect\", name\n        )\n    return value\n\n\ndef _normalize_string(string: str) -> str:\n    return string.replace(\".\", \"_\").replace(\"-\", \"_\")\n\n\ndef _abi3_applies(python_version: PythonVersion) -> bool:\n    \"\"\"\n    Determine if the Python version supports abi3.\n\n    PEP 384 was first implemented in Python 3.2.\n    \"\"\"\n    return len(python_version) > 1 and tuple(python_version) >= (3, 2)\n\n\ndef _cpython_abis(py_version: PythonVersion, warn: bool = False) -> List[str]:\n    py_version = tuple(py_version)  # To allow for version comparison.\n    abis = []\n    version = _version_nodot(py_version[:2])\n    debug = pymalloc = ucs4 = \"\"\n    with_debug = _get_config_var(\"Py_DEBUG\", warn)\n    has_refcount = hasattr(sys, \"gettotalrefcount\")\n    # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled\n    # extension modules is the best option.\n    # https://github.com/pypa/pip/issues/3383#issuecomment-173267692\n    has_ext = \"_d.pyd\" in EXTENSION_SUFFIXES\n    if with_debug or (with_debug is None and (has_refcount or has_ext)):\n        debug = \"d\"\n    if py_version < (3, 8):\n        with_pymalloc = _get_config_var(\"WITH_PYMALLOC\", warn)\n        if with_pymalloc or with_pymalloc is None:\n            pymalloc = \"m\"\n        if py_version < (3, 3):\n            unicode_size = _get_config_var(\"Py_UNICODE_SIZE\", warn)\n            if unicode_size == 4 or (\n                unicode_size is None and sys.maxunicode == 0x10FFFF\n            ):\n                ucs4 = \"u\"\n    elif debug:\n        # Debug builds can also load \"normal\" extension modules.\n        # We can also assume no UCS-4 or pymalloc requirement.\n        abis.append(f\"cp{version}\")\n    abis.insert(\n        0,\n        \"cp{version}{debug}{pymalloc}{ucs4}\".format(\n            version=version, debug=debug, pymalloc=pymalloc, ucs4=ucs4\n        ),\n    )\n    return abis\n\n\ndef cpython_tags(\n    python_version: Optional[PythonVersion] = None,\n    abis: Optional[Iterable[str]] = None,\n    platforms: Optional[Iterable[str]] = None,\n    *,\n    warn: bool = False,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the tags for a CPython interpreter.\n\n    The tags consist of:\n    - cp<python_version>-<abi>-<platform>\n    - cp<python_version>-abi3-<platform>\n    - cp<python_version>-none-<platform>\n    - cp<less than python_version>-abi3-<platform>  # Older Python versions down to 3.2.\n\n    If python_version only specifies a major version then user-provided ABIs and\n    the 'none' ABItag will be used.\n\n    If 'abi3' or 'none' are specified in 'abis' then they will be yielded at\n    their normal position and not at the beginning.\n    \"\"\"\n    if not python_version:\n        python_version = sys.version_info[:2]\n\n    interpreter = f\"cp{_version_nodot(python_version[:2])}\"\n\n    if abis is None:\n        if len(python_version) > 1:\n            abis = _cpython_abis(python_version, warn)\n        else:\n            abis = []\n    abis = list(abis)\n    # 'abi3' and 'none' are explicitly handled later.\n    for explicit_abi in (\"abi3\", \"none\"):\n        try:\n            abis.remove(explicit_abi)\n        except ValueError:\n            pass\n\n    platforms = list(platforms or platform_tags())\n    for abi in abis:\n        for platform_ in platforms:\n            yield Tag(interpreter, abi, platform_)\n    if _abi3_applies(python_version):\n        yield from (Tag(interpreter, \"abi3\", platform_) for platform_ in platforms)\n    yield from (Tag(interpreter, \"none\", platform_) for platform_ in platforms)\n\n    if _abi3_applies(python_version):\n        for minor_version in range(python_version[1] - 1, 1, -1):\n            for platform_ in platforms:\n                interpreter = \"cp{version}\".format(\n                    version=_version_nodot((python_version[0], minor_version))\n                )\n                yield Tag(interpreter, \"abi3\", platform_)\n\n\ndef _generic_abi() -> Iterator[str]:\n    abi = sysconfig.get_config_var(\"SOABI\")\n    if abi:\n        yield _normalize_string(abi)\n\n\ndef generic_tags(\n    interpreter: Optional[str] = None,\n    abis: Optional[Iterable[str]] = None,\n    platforms: Optional[Iterable[str]] = None,\n    *,\n    warn: bool = False,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the tags for a generic interpreter.\n\n    The tags consist of:\n    - <interpreter>-<abi>-<platform>\n\n    The \"none\" ABI will be added if it was not explicitly provided.\n    \"\"\"\n    if not interpreter:\n        interp_name = interpreter_name()\n        interp_version = interpreter_version(warn=warn)\n        interpreter = \"\".join([interp_name, interp_version])\n    if abis is None:\n        abis = _generic_abi()\n    platforms = list(platforms or platform_tags())\n    abis = list(abis)\n    if \"none\" not in abis:\n        abis.append(\"none\")\n    for abi in abis:\n        for platform_ in platforms:\n            yield Tag(interpreter, abi, platform_)\n\n\ndef _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]:\n    \"\"\"\n    Yields Python versions in descending order.\n\n    After the latest version, the major-only version will be yielded, and then\n    all previous versions of that major version.\n    \"\"\"\n    if len(py_version) > 1:\n        yield f\"py{_version_nodot(py_version[:2])}\"\n    yield f\"py{py_version[0]}\"\n    if len(py_version) > 1:\n        for minor in range(py_version[1] - 1, -1, -1):\n            yield f\"py{_version_nodot((py_version[0], minor))}\"\n\n\ndef compatible_tags(\n    python_version: Optional[PythonVersion] = None,\n    interpreter: Optional[str] = None,\n    platforms: Optional[Iterable[str]] = None,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the sequence of tags that are compatible with a specific version of Python.\n\n    The tags consist of:\n    - py*-none-<platform>\n    - <interpreter>-none-any  # ... if `interpreter` is provided.\n    - py*-none-any\n    \"\"\"\n    if not python_version:\n        python_version = sys.version_info[:2]\n    platforms = list(platforms or platform_tags())\n    for version in _py_interpreter_range(python_version):\n        for platform_ in platforms:\n            yield Tag(version, \"none\", platform_)\n    if interpreter:\n        yield Tag(interpreter, \"none\", \"any\")\n    for version in _py_interpreter_range(python_version):\n        yield Tag(version, \"none\", \"any\")\n\n\ndef _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str:\n    if not is_32bit:\n        return arch\n\n    if arch.startswith(\"ppc\"):\n        return \"ppc\"\n\n    return \"i386\"\n\n\ndef _mac_binary_formats(version: MacVersion, cpu_arch: str) -> List[str]:\n    formats = [cpu_arch]\n    if cpu_arch == \"x86_64\":\n        if version < (10, 4):\n            return []\n        formats.extend([\"intel\", \"fat64\", \"fat32\"])\n\n    elif cpu_arch == \"i386\":\n        if version < (10, 4):\n            return []\n        formats.extend([\"intel\", \"fat32\", \"fat\"])\n\n    elif cpu_arch == \"ppc64\":\n        # TODO: Need to care about 32-bit PPC for ppc64 through 10.2?\n        if version > (10, 5) or version < (10, 4):\n            return []\n        formats.append(\"fat64\")\n\n    elif cpu_arch == \"ppc\":\n        if version > (10, 6):\n            return []\n        formats.extend([\"fat32\", \"fat\"])\n\n    if cpu_arch in {\"arm64\", \"x86_64\"}:\n        formats.append(\"universal2\")\n\n    if cpu_arch in {\"x86_64\", \"i386\", \"ppc64\", \"ppc\", \"intel\"}:\n        formats.append(\"universal\")\n\n    return formats\n\n\ndef mac_platforms(\n    version: Optional[MacVersion] = None, arch: Optional[str] = None\n) -> Iterator[str]:\n    \"\"\"\n    Yields the platform tags for a macOS system.\n\n    The `version` parameter is a two-item tuple specifying the macOS version to\n    generate platform tags for. The `arch` parameter is the CPU architecture to\n    generate platform tags for. Both parameters default to the appropriate value\n    for the current system.\n    \"\"\"\n    version_str, _, cpu_arch = platform.mac_ver()\n    if version is None:\n        version = cast(\"MacVersion\", tuple(map(int, version_str.split(\".\")[:2])))\n    else:\n        version = version\n    if arch is None:\n        arch = _mac_arch(cpu_arch)\n    else:\n        arch = arch\n\n    if (10, 0) <= version and version < (11, 0):\n        # Prior to Mac OS 11, each yearly release of Mac OS bumped the\n        # \"minor\" version number.  The major version was always 10.\n        for minor_version in range(version[1], -1, -1):\n            compat_version = 10, minor_version\n            binary_formats = _mac_binary_formats(compat_version, arch)\n            for binary_format in binary_formats:\n                yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                    major=10, minor=minor_version, binary_format=binary_format\n                )\n\n    if version >= (11, 0):\n        # Starting with Mac OS 11, each yearly release bumps the major version\n        # number.   The minor versions are now the midyear updates.\n        for major_version in range(version[0], 10, -1):\n            compat_version = major_version, 0\n            binary_formats = _mac_binary_formats(compat_version, arch)\n            for binary_format in binary_formats:\n                yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                    major=major_version, minor=0, binary_format=binary_format\n                )\n\n    if version >= (11, 0):\n        # Mac OS 11 on x86_64 is compatible with binaries from previous releases.\n        # Arm64 support was introduced in 11.0, so no Arm binaries from previous\n        # releases exist.\n        #\n        # However, the \"universal2\" binary format can have a\n        # macOS version earlier than 11.0 when the x86_64 part of the binary supports\n        # that version of macOS.\n        if arch == \"x86_64\":\n            for minor_version in range(16, 3, -1):\n                compat_version = 10, minor_version\n                binary_formats = _mac_binary_formats(compat_version, arch)\n                for binary_format in binary_formats:\n                    yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                        major=compat_version[0],\n                        minor=compat_version[1],\n                        binary_format=binary_format,\n                    )\n        else:\n            for minor_version in range(16, 3, -1):\n                compat_version = 10, minor_version\n                binary_format = \"universal2\"\n                yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                    major=compat_version[0],\n                    minor=compat_version[1],\n                    binary_format=binary_format,\n                )\n\n\ndef _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]:\n    linux = _normalize_string(sysconfig.get_platform())\n    if is_32bit:\n        if linux == \"linux_x86_64\":\n            linux = \"linux_i686\"\n        elif linux == \"linux_aarch64\":\n            linux = \"linux_armv7l\"\n    _, arch = linux.split(\"_\", 1)\n    yield from _manylinux.platform_tags(linux, arch)\n    yield from _musllinux.platform_tags(arch)\n    yield linux\n\n\ndef _generic_platforms() -> Iterator[str]:\n    yield _normalize_string(sysconfig.get_platform())\n\n\ndef platform_tags() -> Iterator[str]:\n    \"\"\"\n    Provides the platform tags for this installation.\n    \"\"\"\n    if platform.system() == \"Darwin\":\n        return mac_platforms()\n    elif platform.system() == \"Linux\":\n        return _linux_platforms()\n    else:\n        return _generic_platforms()\n\n\ndef interpreter_name() -> str:\n    \"\"\"\n    Returns the name of the running interpreter.\n    \"\"\"\n    name = sys.implementation.name\n    return INTERPRETER_SHORT_NAMES.get(name) or name\n\n\ndef interpreter_version(*, warn: bool = False) -> str:\n    \"\"\"\n    Returns the version of the running interpreter.\n    \"\"\"\n    version = _get_config_var(\"py_version_nodot\", warn=warn)\n    if version:\n        version = str(version)\n    else:\n        version = _version_nodot(sys.version_info[:2])\n    return version\n\n\ndef _version_nodot(version: PythonVersion) -> str:\n    return \"\".join(map(str, version))\n\n\ndef sys_tags(*, warn: bool = False) -> Iterator[Tag]:\n    \"\"\"\n    Returns the sequence of tag triples for the running interpreter.\n\n    The order of the sequence corresponds to priority order for the\n    interpreter, from most to least important.\n    \"\"\"\n\n    interp_name = interpreter_name()\n    if interp_name == \"cp\":\n        yield from cpython_tags(warn=warn)\n    else:\n        yield from generic_tags()\n\n    if interp_name == \"pp\":\n        yield from compatible_tags(interpreter=\"pp3\")\n    else:\n        yield from compatible_tags()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/packaging/utils.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport re\nfrom typing import FrozenSet, NewType, Tuple, Union, cast\n\nfrom .tags import Tag, parse_tag\nfrom .version import InvalidVersion, Version\n\nBuildTag = Union[Tuple[()], Tuple[int, str]]\nNormalizedName = NewType(\"NormalizedName\", str)\n\n\nclass InvalidWheelFilename(ValueError):\n    \"\"\"\n    An invalid wheel filename was found, users should refer to PEP 427.\n    \"\"\"\n\n\nclass InvalidSdistFilename(ValueError):\n    \"\"\"\n    An invalid sdist filename was found, users should refer to the packaging user guide.\n    \"\"\"\n\n\n_canonicalize_regex = re.compile(r\"[-_.]+\")\n# PEP 427: The build number must start with a digit.\n_build_tag_regex = re.compile(r\"(\\d+)(.*)\")\n\n\ndef canonicalize_name(name: str) -> NormalizedName:\n    # This is taken from PEP 503.\n    value = _canonicalize_regex.sub(\"-\", name).lower()\n    return cast(NormalizedName, value)\n\n\ndef canonicalize_version(version: Union[Version, str]) -> str:\n    \"\"\"\n    This is very similar to Version.__str__, but has one subtle difference\n    with the way it handles the release segment.\n    \"\"\"\n    if isinstance(version, str):\n        try:\n            parsed = Version(version)\n        except InvalidVersion:\n            # Legacy versions cannot be normalized\n            return version\n    else:\n        parsed = version\n\n    parts = []\n\n    # Epoch\n    if parsed.epoch != 0:\n        parts.append(f\"{parsed.epoch}!\")\n\n    # Release segment\n    # NB: This strips trailing '.0's to normalize\n    parts.append(re.sub(r\"(\\.0)+$\", \"\", \".\".join(str(x) for x in parsed.release)))\n\n    # Pre-release\n    if parsed.pre is not None:\n        parts.append(\"\".join(str(x) for x in parsed.pre))\n\n    # Post-release\n    if parsed.post is not None:\n        parts.append(f\".post{parsed.post}\")\n\n    # Development release\n    if parsed.dev is not None:\n        parts.append(f\".dev{parsed.dev}\")\n\n    # Local version segment\n    if parsed.local is not None:\n        parts.append(f\"+{parsed.local}\")\n\n    return \"\".join(parts)\n\n\ndef parse_wheel_filename(\n    filename: str,\n) -> Tuple[NormalizedName, Version, BuildTag, FrozenSet[Tag]]:\n    if not filename.endswith(\".whl\"):\n        raise InvalidWheelFilename(\n            f\"Invalid wheel filename (extension must be '.whl'): {filename}\"\n        )\n\n    filename = filename[:-4]\n    dashes = filename.count(\"-\")\n    if dashes not in (4, 5):\n        raise InvalidWheelFilename(\n            f\"Invalid wheel filename (wrong number of parts): {filename}\"\n        )\n\n    parts = filename.split(\"-\", dashes - 2)\n    name_part = parts[0]\n    # See PEP 427 for the rules on escaping the project name\n    if \"__\" in name_part or re.match(r\"^[\\w\\d._]*$\", name_part, re.UNICODE) is None:\n        raise InvalidWheelFilename(f\"Invalid project name: {filename}\")\n    name = canonicalize_name(name_part)\n    version = Version(parts[1])\n    if dashes == 5:\n        build_part = parts[2]\n        build_match = _build_tag_regex.match(build_part)\n        if build_match is None:\n            raise InvalidWheelFilename(\n                f\"Invalid build number: {build_part} in '{filename}'\"\n            )\n        build = cast(BuildTag, (int(build_match.group(1)), build_match.group(2)))\n    else:\n        build = ()\n    tags = parse_tag(parts[-1])\n    return (name, version, build, tags)\n\n\ndef parse_sdist_filename(filename: str) -> Tuple[NormalizedName, Version]:\n    if filename.endswith(\".tar.gz\"):\n        file_stem = filename[: -len(\".tar.gz\")]\n    elif filename.endswith(\".zip\"):\n        file_stem = filename[: -len(\".zip\")]\n    else:\n        raise InvalidSdistFilename(\n            f\"Invalid sdist filename (extension must be '.tar.gz' or '.zip'):\"\n            f\" {filename}\"\n        )\n\n    # We are requiring a PEP 440 version, which cannot contain dashes,\n    # so we split on the last dash.\n    name_part, sep, version_part = file_stem.rpartition(\"-\")\n    if not sep:\n        raise InvalidSdistFilename(f\"Invalid sdist filename: {filename}\")\n\n    name = canonicalize_name(name_part)\n    version = Version(version_part)\n    return (name, version)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/packaging/version.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nimport collections\nimport itertools\nimport re\nimport warnings\nfrom typing import Callable, Iterator, List, Optional, SupportsInt, Tuple, Union\n\nfrom ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType\n\n__all__ = [\"parse\", \"Version\", \"LegacyVersion\", \"InvalidVersion\", \"VERSION_PATTERN\"]\n\nInfiniteTypes = Union[InfinityType, NegativeInfinityType]\nPrePostDevType = Union[InfiniteTypes, Tuple[str, int]]\nSubLocalType = Union[InfiniteTypes, int, str]\nLocalType = Union[\n    NegativeInfinityType,\n    Tuple[\n        Union[\n            SubLocalType,\n            Tuple[SubLocalType, str],\n            Tuple[NegativeInfinityType, SubLocalType],\n        ],\n        ...,\n    ],\n]\nCmpKey = Tuple[\n    int, Tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType\n]\nLegacyCmpKey = Tuple[int, Tuple[str, ...]]\nVersionComparisonMethod = Callable[\n    [Union[CmpKey, LegacyCmpKey], Union[CmpKey, LegacyCmpKey]], bool\n]\n\n_Version = collections.namedtuple(\n    \"_Version\", [\"epoch\", \"release\", \"dev\", \"pre\", \"post\", \"local\"]\n)\n\n\ndef parse(version: str) -> Union[\"LegacyVersion\", \"Version\"]:\n    \"\"\"\n    Parse the given version string and return either a :class:`Version` object\n    or a :class:`LegacyVersion` object depending on if the given version is\n    a valid PEP 440 version or a legacy version.\n    \"\"\"\n    try:\n        return Version(version)\n    except InvalidVersion:\n        return LegacyVersion(version)\n\n\nclass InvalidVersion(ValueError):\n    \"\"\"\n    An invalid version was found, users should refer to PEP 440.\n    \"\"\"\n\n\nclass _BaseVersion:\n    _key: Union[CmpKey, LegacyCmpKey]\n\n    def __hash__(self) -> int:\n        return hash(self._key)\n\n    # Please keep the duplicated `isinstance` check\n    # in the six comparisons hereunder\n    # unless you find a way to avoid adding overhead function calls.\n    def __lt__(self, other: \"_BaseVersion\") -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key < other._key\n\n    def __le__(self, other: \"_BaseVersion\") -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key <= other._key\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key == other._key\n\n    def __ge__(self, other: \"_BaseVersion\") -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key >= other._key\n\n    def __gt__(self, other: \"_BaseVersion\") -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key > other._key\n\n    def __ne__(self, other: object) -> bool:\n        if not isinstance(other, _BaseVersion):\n            return NotImplemented\n\n        return self._key != other._key\n\n\nclass LegacyVersion(_BaseVersion):\n    def __init__(self, version: str) -> None:\n        self._version = str(version)\n        self._key = _legacy_cmpkey(self._version)\n\n        warnings.warn(\n            \"Creating a LegacyVersion has been deprecated and will be \"\n            \"removed in the next major release\",\n            DeprecationWarning,\n        )\n\n    def __str__(self) -> str:\n        return self._version\n\n    def __repr__(self) -> str:\n        return f\"<LegacyVersion('{self}')>\"\n\n    @property\n    def public(self) -> str:\n        return self._version\n\n    @property\n    def base_version(self) -> str:\n        return self._version\n\n    @property\n    def epoch(self) -> int:\n        return -1\n\n    @property\n    def release(self) -> None:\n        return None\n\n    @property\n    def pre(self) -> None:\n        return None\n\n    @property\n    def post(self) -> None:\n        return None\n\n    @property\n    def dev(self) -> None:\n        return None\n\n    @property\n    def local(self) -> None:\n        return None\n\n    @property\n    def is_prerelease(self) -> bool:\n        return False\n\n    @property\n    def is_postrelease(self) -> bool:\n        return False\n\n    @property\n    def is_devrelease(self) -> bool:\n        return False\n\n\n_legacy_version_component_re = re.compile(r\"(\\d+ | [a-z]+ | \\.| -)\", re.VERBOSE)\n\n_legacy_version_replacement_map = {\n    \"pre\": \"c\",\n    \"preview\": \"c\",\n    \"-\": \"final-\",\n    \"rc\": \"c\",\n    \"dev\": \"@\",\n}\n\n\ndef _parse_version_parts(s: str) -> Iterator[str]:\n    for part in _legacy_version_component_re.split(s):\n        part = _legacy_version_replacement_map.get(part, part)\n\n        if not part or part == \".\":\n            continue\n\n        if part[:1] in \"0123456789\":\n            # pad for numeric comparison\n            yield part.zfill(8)\n        else:\n            yield \"*\" + part\n\n    # ensure that alpha/beta/candidate are before final\n    yield \"*final\"\n\n\ndef _legacy_cmpkey(version: str) -> LegacyCmpKey:\n\n    # We hardcode an epoch of -1 here. A PEP 440 version can only have a epoch\n    # greater than or equal to 0. This will effectively put the LegacyVersion,\n    # which uses the defacto standard originally implemented by setuptools,\n    # as before all PEP 440 versions.\n    epoch = -1\n\n    # This scheme is taken from pkg_resources.parse_version setuptools prior to\n    # it's adoption of the packaging library.\n    parts: List[str] = []\n    for part in _parse_version_parts(version.lower()):\n        if part.startswith(\"*\"):\n            # remove \"-\" before a prerelease tag\n            if part < \"*final\":\n                while parts and parts[-1] == \"*final-\":\n                    parts.pop()\n\n            # remove trailing zeros from each series of numeric parts\n            while parts and parts[-1] == \"00000000\":\n                parts.pop()\n\n        parts.append(part)\n\n    return epoch, tuple(parts)\n\n\n# Deliberately not anchored to the start and end of the string, to make it\n# easier for 3rd party code to reuse\nVERSION_PATTERN = r\"\"\"\n    v?\n    (?:\n        (?:(?P<epoch>[0-9]+)!)?                           # epoch\n        (?P<release>[0-9]+(?:\\.[0-9]+)*)                  # release segment\n        (?P<pre>                                          # pre-release\n            [-_\\.]?\n            (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))\n            [-_\\.]?\n            (?P<pre_n>[0-9]+)?\n        )?\n        (?P<post>                                         # post release\n            (?:-(?P<post_n1>[0-9]+))\n            |\n            (?:\n                [-_\\.]?\n                (?P<post_l>post|rev|r)\n                [-_\\.]?\n                (?P<post_n2>[0-9]+)?\n            )\n        )?\n        (?P<dev>                                          # dev release\n            [-_\\.]?\n            (?P<dev_l>dev)\n            [-_\\.]?\n            (?P<dev_n>[0-9]+)?\n        )?\n    )\n    (?:\\+(?P<local>[a-z0-9]+(?:[-_\\.][a-z0-9]+)*))?       # local version\n\"\"\"\n\n\nclass Version(_BaseVersion):\n\n    _regex = re.compile(r\"^\\s*\" + VERSION_PATTERN + r\"\\s*$\", re.VERBOSE | re.IGNORECASE)\n\n    def __init__(self, version: str) -> None:\n\n        # Validate the version and parse it into pieces\n        match = self._regex.search(version)\n        if not match:\n            raise InvalidVersion(f\"Invalid version: '{version}'\")\n\n        # Store the parsed out pieces of the version\n        self._version = _Version(\n            epoch=int(match.group(\"epoch\")) if match.group(\"epoch\") else 0,\n            release=tuple(int(i) for i in match.group(\"release\").split(\".\")),\n            pre=_parse_letter_version(match.group(\"pre_l\"), match.group(\"pre_n\")),\n            post=_parse_letter_version(\n                match.group(\"post_l\"), match.group(\"post_n1\") or match.group(\"post_n2\")\n            ),\n            dev=_parse_letter_version(match.group(\"dev_l\"), match.group(\"dev_n\")),\n            local=_parse_local_version(match.group(\"local\")),\n        )\n\n        # Generate a key which will be used for sorting\n        self._key = _cmpkey(\n            self._version.epoch,\n            self._version.release,\n            self._version.pre,\n            self._version.post,\n            self._version.dev,\n            self._version.local,\n        )\n\n    def __repr__(self) -> str:\n        return f\"<Version('{self}')>\"\n\n    def __str__(self) -> str:\n        parts = []\n\n        # Epoch\n        if self.epoch != 0:\n            parts.append(f\"{self.epoch}!\")\n\n        # Release segment\n        parts.append(\".\".join(str(x) for x in self.release))\n\n        # Pre-release\n        if self.pre is not None:\n            parts.append(\"\".join(str(x) for x in self.pre))\n\n        # Post-release\n        if self.post is not None:\n            parts.append(f\".post{self.post}\")\n\n        # Development release\n        if self.dev is not None:\n            parts.append(f\".dev{self.dev}\")\n\n        # Local version segment\n        if self.local is not None:\n            parts.append(f\"+{self.local}\")\n\n        return \"\".join(parts)\n\n    @property\n    def epoch(self) -> int:\n        _epoch: int = self._version.epoch\n        return _epoch\n\n    @property\n    def release(self) -> Tuple[int, ...]:\n        _release: Tuple[int, ...] = self._version.release\n        return _release\n\n    @property\n    def pre(self) -> Optional[Tuple[str, int]]:\n        _pre: Optional[Tuple[str, int]] = self._version.pre\n        return _pre\n\n    @property\n    def post(self) -> Optional[int]:\n        return self._version.post[1] if self._version.post else None\n\n    @property\n    def dev(self) -> Optional[int]:\n        return self._version.dev[1] if self._version.dev else None\n\n    @property\n    def local(self) -> Optional[str]:\n        if self._version.local:\n            return \".\".join(str(x) for x in self._version.local)\n        else:\n            return None\n\n    @property\n    def public(self) -> str:\n        return str(self).split(\"+\", 1)[0]\n\n    @property\n    def base_version(self) -> str:\n        parts = []\n\n        # Epoch\n        if self.epoch != 0:\n            parts.append(f\"{self.epoch}!\")\n\n        # Release segment\n        parts.append(\".\".join(str(x) for x in self.release))\n\n        return \"\".join(parts)\n\n    @property\n    def is_prerelease(self) -> bool:\n        return self.dev is not None or self.pre is not None\n\n    @property\n    def is_postrelease(self) -> bool:\n        return self.post is not None\n\n    @property\n    def is_devrelease(self) -> bool:\n        return self.dev is not None\n\n    @property\n    def major(self) -> int:\n        return self.release[0] if len(self.release) >= 1 else 0\n\n    @property\n    def minor(self) -> int:\n        return self.release[1] if len(self.release) >= 2 else 0\n\n    @property\n    def micro(self) -> int:\n        return self.release[2] if len(self.release) >= 3 else 0\n\n\ndef _parse_letter_version(\n    letter: str, number: Union[str, bytes, SupportsInt]\n) -> Optional[Tuple[str, int]]:\n\n    if letter:\n        # We consider there to be an implicit 0 in a pre-release if there is\n        # not a numeral associated with it.\n        if number is None:\n            number = 0\n\n        # We normalize any letters to their lower case form\n        letter = letter.lower()\n\n        # We consider some words to be alternate spellings of other words and\n        # in those cases we want to normalize the spellings to our preferred\n        # spelling.\n        if letter == \"alpha\":\n            letter = \"a\"\n        elif letter == \"beta\":\n            letter = \"b\"\n        elif letter in [\"c\", \"pre\", \"preview\"]:\n            letter = \"rc\"\n        elif letter in [\"rev\", \"r\"]:\n            letter = \"post\"\n\n        return letter, int(number)\n    if not letter and number:\n        # We assume if we are given a number, but we are not given a letter\n        # then this is using the implicit post release syntax (e.g. 1.0-1)\n        letter = \"post\"\n\n        return letter, int(number)\n\n    return None\n\n\n_local_version_separators = re.compile(r\"[\\._-]\")\n\n\ndef _parse_local_version(local: str) -> Optional[LocalType]:\n    \"\"\"\n    Takes a string like abc.1.twelve and turns it into (\"abc\", 1, \"twelve\").\n    \"\"\"\n    if local is not None:\n        return tuple(\n            part.lower() if not part.isdigit() else int(part)\n            for part in _local_version_separators.split(local)\n        )\n    return None\n\n\ndef _cmpkey(\n    epoch: int,\n    release: Tuple[int, ...],\n    pre: Optional[Tuple[str, int]],\n    post: Optional[Tuple[str, int]],\n    dev: Optional[Tuple[str, int]],\n    local: Optional[Tuple[SubLocalType]],\n) -> CmpKey:\n\n    # When we compare a release version, we want to compare it with all of the\n    # trailing zeros removed. So we'll use a reverse the list, drop all the now\n    # leading zeros until we come to something non zero, then take the rest\n    # re-reverse it back into the correct order and make it a tuple and use\n    # that for our sorting key.\n    _release = tuple(\n        reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))\n    )\n\n    # We need to \"trick\" the sorting algorithm to put 1.0.dev0 before 1.0a0.\n    # We'll do this by abusing the pre segment, but we _only_ want to do this\n    # if there is not a pre or a post segment. If we have one of those then\n    # the normal sorting rules will handle this case correctly.\n    if pre is None and post is None and dev is not None:\n        _pre: PrePostDevType = NegativeInfinity\n    # Versions without a pre-release (except as noted above) should sort after\n    # those with one.\n    elif pre is None:\n        _pre = Infinity\n    else:\n        _pre = pre\n\n    # Versions without a post segment should sort before those with one.\n    if post is None:\n        _post: PrePostDevType = NegativeInfinity\n\n    else:\n        _post = post\n\n    # Versions without a development segment should sort after those with one.\n    if dev is None:\n        _dev: PrePostDevType = Infinity\n\n    else:\n        _dev = dev\n\n    if local is None:\n        # Versions without a local segment should sort before those with one.\n        _local: LocalType = NegativeInfinity\n    else:\n        # Versions with a local segment need that segment parsed to implement\n        # the sorting rules in PEP440.\n        # - Alpha numeric segments sort before numeric segments\n        # - Alpha numeric segments sort lexicographically\n        # - Numeric segments sort numerically\n        # - Shorter versions sort before longer versions when the prefixes\n        #   match exactly\n        _local = tuple(\n            (i, \"\") if isinstance(i, int) else (NegativeInfinity, i) for i in local\n        )\n\n    return epoch, _release, _pre, _post, _dev, _local\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/pyparsing/__init__.py",
    "content": "# module pyparsing.py\n#\n# Copyright (c) 2003-2022  Paul T. McGuire\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n\n__doc__ = \"\"\"\npyparsing module - Classes and methods to define and execute parsing grammars\n=============================================================================\n\nThe pyparsing module is an alternative approach to creating and\nexecuting simple grammars, vs. the traditional lex/yacc approach, or the\nuse of regular expressions.  With pyparsing, you don't need to learn\na new syntax for defining grammars or matching expressions - the parsing\nmodule provides a library of classes that you use to construct the\ngrammar directly in Python.\n\nHere is a program to parse \"Hello, World!\" (or any greeting of the form\n``\"<salutation>, <addressee>!\"``), built up using :class:`Word`,\n:class:`Literal`, and :class:`And` elements\n(the :meth:`'+'<ParserElement.__add__>` operators create :class:`And` expressions,\nand the strings are auto-converted to :class:`Literal` expressions)::\n\n    from pyparsing import Word, alphas\n\n    # define grammar of a greeting\n    greet = Word(alphas) + \",\" + Word(alphas) + \"!\"\n\n    hello = \"Hello, World!\"\n    print(hello, \"->\", greet.parse_string(hello))\n\nThe program outputs the following::\n\n    Hello, World! -> ['Hello', ',', 'World', '!']\n\nThe Python representation of the grammar is quite readable, owing to the\nself-explanatory class names, and the use of :class:`'+'<And>`,\n:class:`'|'<MatchFirst>`, :class:`'^'<Or>` and :class:`'&'<Each>` operators.\n\nThe :class:`ParseResults` object returned from\n:class:`ParserElement.parseString` can be\naccessed as a nested list, a dictionary, or an object with named\nattributes.\n\nThe pyparsing module handles some of the problems that are typically\nvexing when writing text parsers:\n\n  - extra or missing whitespace (the above program will also handle\n    \"Hello,World!\", \"Hello  ,  World  !\", etc.)\n  - quoted strings\n  - embedded comments\n\n\nGetting Started -\n-----------------\nVisit the classes :class:`ParserElement` and :class:`ParseResults` to\nsee the base classes that most other pyparsing\nclasses inherit from. Use the docstrings for examples of how to:\n\n - construct literal match expressions from :class:`Literal` and\n   :class:`CaselessLiteral` classes\n - construct character word-group expressions using the :class:`Word`\n   class\n - see how to create repetitive expressions using :class:`ZeroOrMore`\n   and :class:`OneOrMore` classes\n - use :class:`'+'<And>`, :class:`'|'<MatchFirst>`, :class:`'^'<Or>`,\n   and :class:`'&'<Each>` operators to combine simple expressions into\n   more complex ones\n - associate names with your parsed results using\n   :class:`ParserElement.setResultsName`\n - access the parsed data, which is returned as a :class:`ParseResults`\n   object\n - find some helpful expression short-cuts like :class:`delimitedList`\n   and :class:`oneOf`\n - find more useful common expressions in the :class:`pyparsing_common`\n   namespace class\n\"\"\"\nfrom typing import NamedTuple\n\n\nclass version_info(NamedTuple):\n    major: int\n    minor: int\n    micro: int\n    releaselevel: str\n    serial: int\n\n    @property\n    def __version__(self):\n        return (\n            \"{}.{}.{}\".format(self.major, self.minor, self.micro)\n            + (\n                \"{}{}{}\".format(\n                    \"r\" if self.releaselevel[0] == \"c\" else \"\",\n                    self.releaselevel[0],\n                    self.serial,\n                ),\n                \"\",\n            )[self.releaselevel == \"final\"]\n        )\n\n    def __str__(self):\n        return \"{} {} / {}\".format(__name__, self.__version__, __version_time__)\n\n    def __repr__(self):\n        return \"{}.{}({})\".format(\n            __name__,\n            type(self).__name__,\n            \", \".join(\"{}={!r}\".format(*nv) for nv in zip(self._fields, self)),\n        )\n\n\n__version_info__ = version_info(3, 0, 9, \"final\", 0)\n__version_time__ = \"05 May 2022 07:02 UTC\"\n__version__ = __version_info__.__version__\n__versionTime__ = __version_time__\n__author__ = \"Paul McGuire <ptmcg.gm+pyparsing@gmail.com>\"\n\nfrom .util import *\nfrom .exceptions import *\nfrom .actions import *\nfrom .core import __diag__, __compat__\nfrom .results import *\nfrom .core import *\nfrom .core import _builtin_exprs as core_builtin_exprs\nfrom .helpers import *\nfrom .helpers import _builtin_exprs as helper_builtin_exprs\n\nfrom .unicode import unicode_set, UnicodeRangeList, pyparsing_unicode as unicode\nfrom .testing import pyparsing_test as testing\nfrom .common import (\n    pyparsing_common as common,\n    _builtin_exprs as common_builtin_exprs,\n)\n\n# define backward compat synonyms\nif \"pyparsing_unicode\" not in globals():\n    pyparsing_unicode = unicode\nif \"pyparsing_common\" not in globals():\n    pyparsing_common = common\nif \"pyparsing_test\" not in globals():\n    pyparsing_test = testing\n\ncore_builtin_exprs += common_builtin_exprs + helper_builtin_exprs\n\n\n__all__ = [\n    \"__version__\",\n    \"__version_time__\",\n    \"__author__\",\n    \"__compat__\",\n    \"__diag__\",\n    \"And\",\n    \"AtLineStart\",\n    \"AtStringStart\",\n    \"CaselessKeyword\",\n    \"CaselessLiteral\",\n    \"CharsNotIn\",\n    \"Combine\",\n    \"Dict\",\n    \"Each\",\n    \"Empty\",\n    \"FollowedBy\",\n    \"Forward\",\n    \"GoToColumn\",\n    \"Group\",\n    \"IndentedBlock\",\n    \"Keyword\",\n    \"LineEnd\",\n    \"LineStart\",\n    \"Literal\",\n    \"Located\",\n    \"PrecededBy\",\n    \"MatchFirst\",\n    \"NoMatch\",\n    \"NotAny\",\n    \"OneOrMore\",\n    \"OnlyOnce\",\n    \"OpAssoc\",\n    \"Opt\",\n    \"Optional\",\n    \"Or\",\n    \"ParseBaseException\",\n    \"ParseElementEnhance\",\n    \"ParseException\",\n    \"ParseExpression\",\n    \"ParseFatalException\",\n    \"ParseResults\",\n    \"ParseSyntaxException\",\n    \"ParserElement\",\n    \"PositionToken\",\n    \"QuotedString\",\n    \"RecursiveGrammarException\",\n    \"Regex\",\n    \"SkipTo\",\n    \"StringEnd\",\n    \"StringStart\",\n    \"Suppress\",\n    \"Token\",\n    \"TokenConverter\",\n    \"White\",\n    \"Word\",\n    \"WordEnd\",\n    \"WordStart\",\n    \"ZeroOrMore\",\n    \"Char\",\n    \"alphanums\",\n    \"alphas\",\n    \"alphas8bit\",\n    \"any_close_tag\",\n    \"any_open_tag\",\n    \"c_style_comment\",\n    \"col\",\n    \"common_html_entity\",\n    \"counted_array\",\n    \"cpp_style_comment\",\n    \"dbl_quoted_string\",\n    \"dbl_slash_comment\",\n    \"delimited_list\",\n    \"dict_of\",\n    \"empty\",\n    \"hexnums\",\n    \"html_comment\",\n    \"identchars\",\n    \"identbodychars\",\n    \"java_style_comment\",\n    \"line\",\n    \"line_end\",\n    \"line_start\",\n    \"lineno\",\n    \"make_html_tags\",\n    \"make_xml_tags\",\n    \"match_only_at_col\",\n    \"match_previous_expr\",\n    \"match_previous_literal\",\n    \"nested_expr\",\n    \"null_debug_action\",\n    \"nums\",\n    \"one_of\",\n    \"printables\",\n    \"punc8bit\",\n    \"python_style_comment\",\n    \"quoted_string\",\n    \"remove_quotes\",\n    \"replace_with\",\n    \"replace_html_entity\",\n    \"rest_of_line\",\n    \"sgl_quoted_string\",\n    \"srange\",\n    \"string_end\",\n    \"string_start\",\n    \"trace_parse_action\",\n    \"unicode_string\",\n    \"with_attribute\",\n    \"indentedBlock\",\n    \"original_text_for\",\n    \"ungroup\",\n    \"infix_notation\",\n    \"locatedExpr\",\n    \"with_class\",\n    \"CloseMatch\",\n    \"token_map\",\n    \"pyparsing_common\",\n    \"pyparsing_unicode\",\n    \"unicode_set\",\n    \"condition_as_parse_action\",\n    \"pyparsing_test\",\n    # pre-PEP8 compatibility names\n    \"__versionTime__\",\n    \"anyCloseTag\",\n    \"anyOpenTag\",\n    \"cStyleComment\",\n    \"commonHTMLEntity\",\n    \"countedArray\",\n    \"cppStyleComment\",\n    \"dblQuotedString\",\n    \"dblSlashComment\",\n    \"delimitedList\",\n    \"dictOf\",\n    \"htmlComment\",\n    \"javaStyleComment\",\n    \"lineEnd\",\n    \"lineStart\",\n    \"makeHTMLTags\",\n    \"makeXMLTags\",\n    \"matchOnlyAtCol\",\n    \"matchPreviousExpr\",\n    \"matchPreviousLiteral\",\n    \"nestedExpr\",\n    \"nullDebugAction\",\n    \"oneOf\",\n    \"opAssoc\",\n    \"pythonStyleComment\",\n    \"quotedString\",\n    \"removeQuotes\",\n    \"replaceHTMLEntity\",\n    \"replaceWith\",\n    \"restOfLine\",\n    \"sglQuotedString\",\n    \"stringEnd\",\n    \"stringStart\",\n    \"traceParseAction\",\n    \"unicodeString\",\n    \"withAttribute\",\n    \"indentedBlock\",\n    \"originalTextFor\",\n    \"infixNotation\",\n    \"locatedExpr\",\n    \"withClass\",\n    \"tokenMap\",\n    \"conditionAsParseAction\",\n    \"autoname_elements\",\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/pyparsing/actions.py",
    "content": "# actions.py\n\nfrom .exceptions import ParseException\nfrom .util import col\n\n\nclass OnlyOnce:\n    \"\"\"\n    Wrapper for parse actions, to ensure they are only called once.\n    \"\"\"\n\n    def __init__(self, method_call):\n        from .core import _trim_arity\n\n        self.callable = _trim_arity(method_call)\n        self.called = False\n\n    def __call__(self, s, l, t):\n        if not self.called:\n            results = self.callable(s, l, t)\n            self.called = True\n            return results\n        raise ParseException(s, l, \"OnlyOnce obj called multiple times w/out reset\")\n\n    def reset(self):\n        \"\"\"\n        Allow the associated parse action to be called once more.\n        \"\"\"\n\n        self.called = False\n\n\ndef match_only_at_col(n):\n    \"\"\"\n    Helper method for defining parse actions that require matching at\n    a specific column in the input text.\n    \"\"\"\n\n    def verify_col(strg, locn, toks):\n        if col(locn, strg) != n:\n            raise ParseException(strg, locn, \"matched token not at column {}\".format(n))\n\n    return verify_col\n\n\ndef replace_with(repl_str):\n    \"\"\"\n    Helper method for common parse actions that simply return\n    a literal value.  Especially useful when used with\n    :class:`transform_string<ParserElement.transform_string>` ().\n\n    Example::\n\n        num = Word(nums).set_parse_action(lambda toks: int(toks[0]))\n        na = one_of(\"N/A NA\").set_parse_action(replace_with(math.nan))\n        term = na | num\n\n        term[1, ...].parse_string(\"324 234 N/A 234\") # -> [324, 234, nan, 234]\n    \"\"\"\n    return lambda s, l, t: [repl_str]\n\n\ndef remove_quotes(s, l, t):\n    \"\"\"\n    Helper parse action for removing quotation marks from parsed\n    quoted strings.\n\n    Example::\n\n        # by default, quotation marks are included in parsed results\n        quoted_string.parse_string(\"'Now is the Winter of our Discontent'\") # -> [\"'Now is the Winter of our Discontent'\"]\n\n        # use remove_quotes to strip quotation marks from parsed results\n        quoted_string.set_parse_action(remove_quotes)\n        quoted_string.parse_string(\"'Now is the Winter of our Discontent'\") # -> [\"Now is the Winter of our Discontent\"]\n    \"\"\"\n    return t[0][1:-1]\n\n\ndef with_attribute(*args, **attr_dict):\n    \"\"\"\n    Helper to create a validating parse action to be used with start\n    tags created with :class:`make_xml_tags` or\n    :class:`make_html_tags`. Use ``with_attribute`` to qualify\n    a starting tag with a required attribute value, to avoid false\n    matches on common tags such as ``<TD>`` or ``<DIV>``.\n\n    Call ``with_attribute`` with a series of attribute names and\n    values. Specify the list of filter attributes names and values as:\n\n    - keyword arguments, as in ``(align=\"right\")``, or\n    - as an explicit dict with ``**`` operator, when an attribute\n      name is also a Python reserved word, as in ``**{\"class\":\"Customer\", \"align\":\"right\"}``\n    - a list of name-value tuples, as in ``((\"ns1:class\", \"Customer\"), (\"ns2:align\", \"right\"))``\n\n    For attribute names with a namespace prefix, you must use the second\n    form.  Attribute names are matched insensitive to upper/lower case.\n\n    If just testing for ``class`` (with or without a namespace), use\n    :class:`with_class`.\n\n    To verify that the attribute exists, but without specifying a value,\n    pass ``with_attribute.ANY_VALUE`` as the value.\n\n    Example::\n\n        html = '''\n            <div>\n            Some text\n            <div type=\"grid\">1 4 0 1 0</div>\n            <div type=\"graph\">1,3 2,3 1,1</div>\n            <div>this has no type</div>\n            </div>\n\n        '''\n        div,div_end = make_html_tags(\"div\")\n\n        # only match div tag having a type attribute with value \"grid\"\n        div_grid = div().set_parse_action(with_attribute(type=\"grid\"))\n        grid_expr = div_grid + SkipTo(div | div_end)(\"body\")\n        for grid_header in grid_expr.search_string(html):\n            print(grid_header.body)\n\n        # construct a match with any div tag having a type attribute, regardless of the value\n        div_any_type = div().set_parse_action(with_attribute(type=with_attribute.ANY_VALUE))\n        div_expr = div_any_type + SkipTo(div | div_end)(\"body\")\n        for div_header in div_expr.search_string(html):\n            print(div_header.body)\n\n    prints::\n\n        1 4 0 1 0\n\n        1 4 0 1 0\n        1,3 2,3 1,1\n    \"\"\"\n    if args:\n        attrs = args[:]\n    else:\n        attrs = attr_dict.items()\n    attrs = [(k, v) for k, v in attrs]\n\n    def pa(s, l, tokens):\n        for attrName, attrValue in attrs:\n            if attrName not in tokens:\n                raise ParseException(s, l, \"no matching attribute \" + attrName)\n            if attrValue != with_attribute.ANY_VALUE and tokens[attrName] != attrValue:\n                raise ParseException(\n                    s,\n                    l,\n                    \"attribute {!r} has value {!r}, must be {!r}\".format(\n                        attrName, tokens[attrName], attrValue\n                    ),\n                )\n\n    return pa\n\n\nwith_attribute.ANY_VALUE = object()\n\n\ndef with_class(classname, namespace=\"\"):\n    \"\"\"\n    Simplified version of :class:`with_attribute` when\n    matching on a div class - made difficult because ``class`` is\n    a reserved word in Python.\n\n    Example::\n\n        html = '''\n            <div>\n            Some text\n            <div class=\"grid\">1 4 0 1 0</div>\n            <div class=\"graph\">1,3 2,3 1,1</div>\n            <div>this &lt;div&gt; has no class</div>\n            </div>\n\n        '''\n        div,div_end = make_html_tags(\"div\")\n        div_grid = div().set_parse_action(with_class(\"grid\"))\n\n        grid_expr = div_grid + SkipTo(div | div_end)(\"body\")\n        for grid_header in grid_expr.search_string(html):\n            print(grid_header.body)\n\n        div_any_type = div().set_parse_action(with_class(withAttribute.ANY_VALUE))\n        div_expr = div_any_type + SkipTo(div | div_end)(\"body\")\n        for div_header in div_expr.search_string(html):\n            print(div_header.body)\n\n    prints::\n\n        1 4 0 1 0\n\n        1 4 0 1 0\n        1,3 2,3 1,1\n    \"\"\"\n    classattr = \"{}:class\".format(namespace) if namespace else \"class\"\n    return with_attribute(**{classattr: classname})\n\n\n# pre-PEP8 compatibility symbols\nreplaceWith = replace_with\nremoveQuotes = remove_quotes\nwithAttribute = with_attribute\nwithClass = with_class\nmatchOnlyAtCol = match_only_at_col\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/pyparsing/common.py",
    "content": "# common.py\nfrom .core import *\nfrom .helpers import delimited_list, any_open_tag, any_close_tag\nfrom datetime import datetime\n\n\n# some other useful expressions - using lower-case class name since we are really using this as a namespace\nclass pyparsing_common:\n    \"\"\"Here are some common low-level expressions that may be useful in\n    jump-starting parser development:\n\n    - numeric forms (:class:`integers<integer>`, :class:`reals<real>`,\n      :class:`scientific notation<sci_real>`)\n    - common :class:`programming identifiers<identifier>`\n    - network addresses (:class:`MAC<mac_address>`,\n      :class:`IPv4<ipv4_address>`, :class:`IPv6<ipv6_address>`)\n    - ISO8601 :class:`dates<iso8601_date>` and\n      :class:`datetime<iso8601_datetime>`\n    - :class:`UUID<uuid>`\n    - :class:`comma-separated list<comma_separated_list>`\n    - :class:`url`\n\n    Parse actions:\n\n    - :class:`convertToInteger`\n    - :class:`convertToFloat`\n    - :class:`convertToDate`\n    - :class:`convertToDatetime`\n    - :class:`stripHTMLTags`\n    - :class:`upcaseTokens`\n    - :class:`downcaseTokens`\n\n    Example::\n\n        pyparsing_common.number.runTests('''\n            # any int or real number, returned as the appropriate type\n            100\n            -100\n            +100\n            3.14159\n            6.02e23\n            1e-12\n            ''')\n\n        pyparsing_common.fnumber.runTests('''\n            # any int or real number, returned as float\n            100\n            -100\n            +100\n            3.14159\n            6.02e23\n            1e-12\n            ''')\n\n        pyparsing_common.hex_integer.runTests('''\n            # hex numbers\n            100\n            FF\n            ''')\n\n        pyparsing_common.fraction.runTests('''\n            # fractions\n            1/2\n            -3/4\n            ''')\n\n        pyparsing_common.mixed_integer.runTests('''\n            # mixed fractions\n            1\n            1/2\n            -3/4\n            1-3/4\n            ''')\n\n        import uuid\n        pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID))\n        pyparsing_common.uuid.runTests('''\n            # uuid\n            12345678-1234-5678-1234-567812345678\n            ''')\n\n    prints::\n\n        # any int or real number, returned as the appropriate type\n        100\n        [100]\n\n        -100\n        [-100]\n\n        +100\n        [100]\n\n        3.14159\n        [3.14159]\n\n        6.02e23\n        [6.02e+23]\n\n        1e-12\n        [1e-12]\n\n        # any int or real number, returned as float\n        100\n        [100.0]\n\n        -100\n        [-100.0]\n\n        +100\n        [100.0]\n\n        3.14159\n        [3.14159]\n\n        6.02e23\n        [6.02e+23]\n\n        1e-12\n        [1e-12]\n\n        # hex numbers\n        100\n        [256]\n\n        FF\n        [255]\n\n        # fractions\n        1/2\n        [0.5]\n\n        -3/4\n        [-0.75]\n\n        # mixed fractions\n        1\n        [1]\n\n        1/2\n        [0.5]\n\n        -3/4\n        [-0.75]\n\n        1-3/4\n        [1.75]\n\n        # uuid\n        12345678-1234-5678-1234-567812345678\n        [UUID('12345678-1234-5678-1234-567812345678')]\n    \"\"\"\n\n    convert_to_integer = token_map(int)\n    \"\"\"\n    Parse action for converting parsed integers to Python int\n    \"\"\"\n\n    convert_to_float = token_map(float)\n    \"\"\"\n    Parse action for converting parsed numbers to Python float\n    \"\"\"\n\n    integer = Word(nums).set_name(\"integer\").set_parse_action(convert_to_integer)\n    \"\"\"expression that parses an unsigned integer, returns an int\"\"\"\n\n    hex_integer = (\n        Word(hexnums).set_name(\"hex integer\").set_parse_action(token_map(int, 16))\n    )\n    \"\"\"expression that parses a hexadecimal integer, returns an int\"\"\"\n\n    signed_integer = (\n        Regex(r\"[+-]?\\d+\")\n        .set_name(\"signed integer\")\n        .set_parse_action(convert_to_integer)\n    )\n    \"\"\"expression that parses an integer with optional leading sign, returns an int\"\"\"\n\n    fraction = (\n        signed_integer().set_parse_action(convert_to_float)\n        + \"/\"\n        + signed_integer().set_parse_action(convert_to_float)\n    ).set_name(\"fraction\")\n    \"\"\"fractional expression of an integer divided by an integer, returns a float\"\"\"\n    fraction.add_parse_action(lambda tt: tt[0] / tt[-1])\n\n    mixed_integer = (\n        fraction | signed_integer + Opt(Opt(\"-\").suppress() + fraction)\n    ).set_name(\"fraction or mixed integer-fraction\")\n    \"\"\"mixed integer of the form 'integer - fraction', with optional leading integer, returns float\"\"\"\n    mixed_integer.add_parse_action(sum)\n\n    real = (\n        Regex(r\"[+-]?(?:\\d+\\.\\d*|\\.\\d+)\")\n        .set_name(\"real number\")\n        .set_parse_action(convert_to_float)\n    )\n    \"\"\"expression that parses a floating point number and returns a float\"\"\"\n\n    sci_real = (\n        Regex(r\"[+-]?(?:\\d+(?:[eE][+-]?\\d+)|(?:\\d+\\.\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?)\")\n        .set_name(\"real number with scientific notation\")\n        .set_parse_action(convert_to_float)\n    )\n    \"\"\"expression that parses a floating point number with optional\n    scientific notation and returns a float\"\"\"\n\n    # streamlining this expression makes the docs nicer-looking\n    number = (sci_real | real | signed_integer).setName(\"number\").streamline()\n    \"\"\"any numeric expression, returns the corresponding Python type\"\"\"\n\n    fnumber = (\n        Regex(r\"[+-]?\\d+\\.?\\d*([eE][+-]?\\d+)?\")\n        .set_name(\"fnumber\")\n        .set_parse_action(convert_to_float)\n    )\n    \"\"\"any int or real number, returned as float\"\"\"\n\n    identifier = Word(identchars, identbodychars).set_name(\"identifier\")\n    \"\"\"typical code identifier (leading alpha or '_', followed by 0 or more alphas, nums, or '_')\"\"\"\n\n    ipv4_address = Regex(\n        r\"(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}\"\n    ).set_name(\"IPv4 address\")\n    \"IPv4 address (``0.0.0.0 - 255.255.255.255``)\"\n\n    _ipv6_part = Regex(r\"[0-9a-fA-F]{1,4}\").set_name(\"hex_integer\")\n    _full_ipv6_address = (_ipv6_part + (\":\" + _ipv6_part) * 7).set_name(\n        \"full IPv6 address\"\n    )\n    _short_ipv6_address = (\n        Opt(_ipv6_part + (\":\" + _ipv6_part) * (0, 6))\n        + \"::\"\n        + Opt(_ipv6_part + (\":\" + _ipv6_part) * (0, 6))\n    ).set_name(\"short IPv6 address\")\n    _short_ipv6_address.add_condition(\n        lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8\n    )\n    _mixed_ipv6_address = (\"::ffff:\" + ipv4_address).set_name(\"mixed IPv6 address\")\n    ipv6_address = Combine(\n        (_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).set_name(\n            \"IPv6 address\"\n        )\n    ).set_name(\"IPv6 address\")\n    \"IPv6 address (long, short, or mixed form)\"\n\n    mac_address = Regex(\n        r\"[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\\1[0-9a-fA-F]{2}){4}\"\n    ).set_name(\"MAC address\")\n    \"MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)\"\n\n    @staticmethod\n    def convert_to_date(fmt: str = \"%Y-%m-%d\"):\n        \"\"\"\n        Helper to create a parse action for converting parsed date string to Python datetime.date\n\n        Params -\n        - fmt - format to be passed to datetime.strptime (default= ``\"%Y-%m-%d\"``)\n\n        Example::\n\n            date_expr = pyparsing_common.iso8601_date.copy()\n            date_expr.setParseAction(pyparsing_common.convertToDate())\n            print(date_expr.parseString(\"1999-12-31\"))\n\n        prints::\n\n            [datetime.date(1999, 12, 31)]\n        \"\"\"\n\n        def cvt_fn(ss, ll, tt):\n            try:\n                return datetime.strptime(tt[0], fmt).date()\n            except ValueError as ve:\n                raise ParseException(ss, ll, str(ve))\n\n        return cvt_fn\n\n    @staticmethod\n    def convert_to_datetime(fmt: str = \"%Y-%m-%dT%H:%M:%S.%f\"):\n        \"\"\"Helper to create a parse action for converting parsed\n        datetime string to Python datetime.datetime\n\n        Params -\n        - fmt - format to be passed to datetime.strptime (default= ``\"%Y-%m-%dT%H:%M:%S.%f\"``)\n\n        Example::\n\n            dt_expr = pyparsing_common.iso8601_datetime.copy()\n            dt_expr.setParseAction(pyparsing_common.convertToDatetime())\n            print(dt_expr.parseString(\"1999-12-31T23:59:59.999\"))\n\n        prints::\n\n            [datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]\n        \"\"\"\n\n        def cvt_fn(s, l, t):\n            try:\n                return datetime.strptime(t[0], fmt)\n            except ValueError as ve:\n                raise ParseException(s, l, str(ve))\n\n        return cvt_fn\n\n    iso8601_date = Regex(\n        r\"(?P<year>\\d{4})(?:-(?P<month>\\d\\d)(?:-(?P<day>\\d\\d))?)?\"\n    ).set_name(\"ISO8601 date\")\n    \"ISO8601 date (``yyyy-mm-dd``)\"\n\n    iso8601_datetime = Regex(\n        r\"(?P<year>\\d{4})-(?P<month>\\d\\d)-(?P<day>\\d\\d)[T ](?P<hour>\\d\\d):(?P<minute>\\d\\d)(:(?P<second>\\d\\d(\\.\\d*)?)?)?(?P<tz>Z|[+-]\\d\\d:?\\d\\d)?\"\n    ).set_name(\"ISO8601 datetime\")\n    \"ISO8601 datetime (``yyyy-mm-ddThh:mm:ss.s(Z|+-00:00)``) - trailing seconds, milliseconds, and timezone optional; accepts separating ``'T'`` or ``' '``\"\n\n    uuid = Regex(r\"[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}\").set_name(\"UUID\")\n    \"UUID (``xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx``)\"\n\n    _html_stripper = any_open_tag.suppress() | any_close_tag.suppress()\n\n    @staticmethod\n    def strip_html_tags(s: str, l: int, tokens: ParseResults):\n        \"\"\"Parse action to remove HTML tags from web page HTML source\n\n        Example::\n\n            # strip HTML links from normal text\n            text = '<td>More info at the <a href=\"https://github.com/pyparsing/pyparsing/wiki\">pyparsing</a> wiki page</td>'\n            td, td_end = makeHTMLTags(\"TD\")\n            table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)(\"body\") + td_end\n            print(table_text.parseString(text).body)\n\n        Prints::\n\n            More info at the pyparsing wiki page\n        \"\"\"\n        return pyparsing_common._html_stripper.transform_string(tokens[0])\n\n    _commasepitem = (\n        Combine(\n            OneOrMore(\n                ~Literal(\",\")\n                + ~LineEnd()\n                + Word(printables, exclude_chars=\",\")\n                + Opt(White(\" \\t\") + ~FollowedBy(LineEnd() | \",\"))\n            )\n        )\n        .streamline()\n        .set_name(\"commaItem\")\n    )\n    comma_separated_list = delimited_list(\n        Opt(quoted_string.copy() | _commasepitem, default=\"\")\n    ).set_name(\"comma separated list\")\n    \"\"\"Predefined expression of 1 or more printable words or quoted strings, separated by commas.\"\"\"\n\n    upcase_tokens = staticmethod(token_map(lambda t: t.upper()))\n    \"\"\"Parse action to convert tokens to upper case.\"\"\"\n\n    downcase_tokens = staticmethod(token_map(lambda t: t.lower()))\n    \"\"\"Parse action to convert tokens to lower case.\"\"\"\n\n    # fmt: off\n    url = Regex(\n        # https://mathiasbynens.be/demo/url-regex\n        # https://gist.github.com/dperini/729294\n        r\"^\" +\n        # protocol identifier (optional)\n        # short syntax // still required\n        r\"(?:(?:(?P<scheme>https?|ftp):)?\\/\\/)\" +\n        # user:pass BasicAuth (optional)\n        r\"(?:(?P<auth>\\S+(?::\\S*)?)@)?\" +\n        r\"(?P<host>\" +\n        # IP address exclusion\n        # private & local networks\n        r\"(?!(?:10|127)(?:\\.\\d{1,3}){3})\" +\n        r\"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})\" +\n        r\"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})\" +\n        # IP address dotted notation octets\n        # excludes loopback network 0.0.0.0\n        # excludes reserved space >= 224.0.0.0\n        # excludes network & broadcast addresses\n        # (first & last IP address of each class)\n        r\"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])\" +\n        r\"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}\" +\n        r\"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))\" +\n        r\"|\" +\n        # host & domain names, may end with dot\n        # can be replaced by a shortest alternative\n        # (?![-_])(?:[-\\w\\u00a1-\\uffff]{0,63}[^-_]\\.)+\n        r\"(?:\" +\n        r\"(?:\" +\n        r\"[a-z0-9\\u00a1-\\uffff]\" +\n        r\"[a-z0-9\\u00a1-\\uffff_-]{0,62}\" +\n        r\")?\" +\n        r\"[a-z0-9\\u00a1-\\uffff]\\.\" +\n        r\")+\" +\n        # TLD identifier name, may end with dot\n        r\"(?:[a-z\\u00a1-\\uffff]{2,}\\.?)\" +\n        r\")\" +\n        # port number (optional)\n        r\"(:(?P<port>\\d{2,5}))?\" +\n        # resource path (optional)\n        r\"(?P<path>\\/[^?# ]*)?\" +\n        # query string (optional)\n        r\"(\\?(?P<query>[^#]*))?\" +\n        # fragment (optional)\n        r\"(#(?P<fragment>\\S*))?\" +\n        r\"$\"\n    ).set_name(\"url\")\n    # fmt: on\n\n    # pre-PEP8 compatibility names\n    convertToInteger = convert_to_integer\n    convertToFloat = convert_to_float\n    convertToDate = convert_to_date\n    convertToDatetime = convert_to_datetime\n    stripHTMLTags = strip_html_tags\n    upcaseTokens = upcase_tokens\n    downcaseTokens = downcase_tokens\n\n\n_builtin_exprs = [\n    v for v in vars(pyparsing_common).values() if isinstance(v, ParserElement)\n]\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/pyparsing/core.py",
    "content": "#\n# core.py\n#\nimport os\nimport typing\nfrom typing import (\n    NamedTuple,\n    Union,\n    Callable,\n    Any,\n    Generator,\n    Tuple,\n    List,\n    TextIO,\n    Set,\n    Sequence,\n)\nfrom abc import ABC, abstractmethod\nfrom enum import Enum\nimport string\nimport copy\nimport warnings\nimport re\nimport sys\nfrom collections.abc import Iterable\nimport traceback\nimport types\nfrom operator import itemgetter\nfrom functools import wraps\nfrom threading import RLock\nfrom pathlib import Path\n\nfrom .util import (\n    _FifoCache,\n    _UnboundedCache,\n    __config_flags,\n    _collapse_string_to_ranges,\n    _escape_regex_range_chars,\n    _bslash,\n    _flatten,\n    LRUMemo as _LRUMemo,\n    UnboundedMemo as _UnboundedMemo,\n)\nfrom .exceptions import *\nfrom .actions import *\nfrom .results import ParseResults, _ParseResultsWithOffset\nfrom .unicode import pyparsing_unicode\n\n_MAX_INT = sys.maxsize\nstr_type: Tuple[type, ...] = (str, bytes)\n\n#\n# Copyright (c) 2003-2022  Paul T. McGuire\n#\n# Permission is hereby granted, free of charge, to any person obtaining\n# a copy of this software and associated documentation files (the\n# \"Software\"), to deal in the Software without restriction, including\n# without limitation the rights to use, copy, modify, merge, publish,\n# distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so, subject to\n# the following conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n\n\nif sys.version_info >= (3, 8):\n    from functools import cached_property\nelse:\n\n    class cached_property:\n        def __init__(self, func):\n            self._func = func\n\n        def __get__(self, instance, owner=None):\n            ret = instance.__dict__[self._func.__name__] = self._func(instance)\n            return ret\n\n\nclass __compat__(__config_flags):\n    \"\"\"\n    A cross-version compatibility configuration for pyparsing features that will be\n    released in a future version. By setting values in this configuration to True,\n    those features can be enabled in prior versions for compatibility development\n    and testing.\n\n    - ``collect_all_And_tokens`` - flag to enable fix for Issue #63 that fixes erroneous grouping\n      of results names when an :class:`And` expression is nested within an :class:`Or` or :class:`MatchFirst`;\n      maintained for compatibility, but setting to ``False`` no longer restores pre-2.3.1\n      behavior\n    \"\"\"\n\n    _type_desc = \"compatibility\"\n\n    collect_all_And_tokens = True\n\n    _all_names = [__ for __ in locals() if not __.startswith(\"_\")]\n    _fixed_names = \"\"\"\n        collect_all_And_tokens\n        \"\"\".split()\n\n\nclass __diag__(__config_flags):\n    _type_desc = \"diagnostic\"\n\n    warn_multiple_tokens_in_named_alternation = False\n    warn_ungrouped_named_tokens_in_collection = False\n    warn_name_set_on_empty_Forward = False\n    warn_on_parse_using_empty_Forward = False\n    warn_on_assignment_to_Forward = False\n    warn_on_multiple_string_args_to_oneof = False\n    warn_on_match_first_with_lshift_operator = False\n    enable_debug_on_named_expressions = False\n\n    _all_names = [__ for __ in locals() if not __.startswith(\"_\")]\n    _warning_names = [name for name in _all_names if name.startswith(\"warn\")]\n    _debug_names = [name for name in _all_names if name.startswith(\"enable_debug\")]\n\n    @classmethod\n    def enable_all_warnings(cls) -> None:\n        for name in cls._warning_names:\n            cls.enable(name)\n\n\nclass Diagnostics(Enum):\n    \"\"\"\n    Diagnostic configuration (all default to disabled)\n    - ``warn_multiple_tokens_in_named_alternation`` - flag to enable warnings when a results\n      name is defined on a :class:`MatchFirst` or :class:`Or` expression with one or more :class:`And` subexpressions\n    - ``warn_ungrouped_named_tokens_in_collection`` - flag to enable warnings when a results\n      name is defined on a containing expression with ungrouped subexpressions that also\n      have results names\n    - ``warn_name_set_on_empty_Forward`` - flag to enable warnings when a :class:`Forward` is defined\n      with a results name, but has no contents defined\n    - ``warn_on_parse_using_empty_Forward`` - flag to enable warnings when a :class:`Forward` is\n      defined in a grammar but has never had an expression attached to it\n    - ``warn_on_assignment_to_Forward`` - flag to enable warnings when a :class:`Forward` is defined\n      but is overwritten by assigning using ``'='`` instead of ``'<<='`` or ``'<<'``\n    - ``warn_on_multiple_string_args_to_oneof`` - flag to enable warnings when :class:`one_of` is\n      incorrectly called with multiple str arguments\n    - ``enable_debug_on_named_expressions`` - flag to auto-enable debug on all subsequent\n      calls to :class:`ParserElement.set_name`\n\n    Diagnostics are enabled/disabled by calling :class:`enable_diag` and :class:`disable_diag`.\n    All warnings can be enabled by calling :class:`enable_all_warnings`.\n    \"\"\"\n\n    warn_multiple_tokens_in_named_alternation = 0\n    warn_ungrouped_named_tokens_in_collection = 1\n    warn_name_set_on_empty_Forward = 2\n    warn_on_parse_using_empty_Forward = 3\n    warn_on_assignment_to_Forward = 4\n    warn_on_multiple_string_args_to_oneof = 5\n    warn_on_match_first_with_lshift_operator = 6\n    enable_debug_on_named_expressions = 7\n\n\ndef enable_diag(diag_enum: Diagnostics) -> None:\n    \"\"\"\n    Enable a global pyparsing diagnostic flag (see :class:`Diagnostics`).\n    \"\"\"\n    __diag__.enable(diag_enum.name)\n\n\ndef disable_diag(diag_enum: Diagnostics) -> None:\n    \"\"\"\n    Disable a global pyparsing diagnostic flag (see :class:`Diagnostics`).\n    \"\"\"\n    __diag__.disable(diag_enum.name)\n\n\ndef enable_all_warnings() -> None:\n    \"\"\"\n    Enable all global pyparsing diagnostic warnings (see :class:`Diagnostics`).\n    \"\"\"\n    __diag__.enable_all_warnings()\n\n\n# hide abstract class\ndel __config_flags\n\n\ndef _should_enable_warnings(\n    cmd_line_warn_options: typing.Iterable[str], warn_env_var: typing.Optional[str]\n) -> bool:\n    enable = bool(warn_env_var)\n    for warn_opt in cmd_line_warn_options:\n        w_action, w_message, w_category, w_module, w_line = (warn_opt + \"::::\").split(\n            \":\"\n        )[:5]\n        if not w_action.lower().startswith(\"i\") and (\n            not (w_message or w_category or w_module) or w_module == \"pyparsing\"\n        ):\n            enable = True\n        elif w_action.lower().startswith(\"i\") and w_module in (\"pyparsing\", \"\"):\n            enable = False\n    return enable\n\n\nif _should_enable_warnings(\n    sys.warnoptions, os.environ.get(\"PYPARSINGENABLEALLWARNINGS\")\n):\n    enable_all_warnings()\n\n\n# build list of single arg builtins, that can be used as parse actions\n_single_arg_builtins = {\n    sum,\n    len,\n    sorted,\n    reversed,\n    list,\n    tuple,\n    set,\n    any,\n    all,\n    min,\n    max,\n}\n\n_generatorType = types.GeneratorType\nParseAction = Union[\n    Callable[[], Any],\n    Callable[[ParseResults], Any],\n    Callable[[int, ParseResults], Any],\n    Callable[[str, int, ParseResults], Any],\n]\nParseCondition = Union[\n    Callable[[], bool],\n    Callable[[ParseResults], bool],\n    Callable[[int, ParseResults], bool],\n    Callable[[str, int, ParseResults], bool],\n]\nParseFailAction = Callable[[str, int, \"ParserElement\", Exception], None]\nDebugStartAction = Callable[[str, int, \"ParserElement\", bool], None]\nDebugSuccessAction = Callable[\n    [str, int, int, \"ParserElement\", ParseResults, bool], None\n]\nDebugExceptionAction = Callable[[str, int, \"ParserElement\", Exception, bool], None]\n\n\nalphas = string.ascii_uppercase + string.ascii_lowercase\nidentchars = pyparsing_unicode.Latin1.identchars\nidentbodychars = pyparsing_unicode.Latin1.identbodychars\nnums = \"0123456789\"\nhexnums = nums + \"ABCDEFabcdef\"\nalphanums = alphas + nums\nprintables = \"\".join([c for c in string.printable if c not in string.whitespace])\n\n_trim_arity_call_line: traceback.StackSummary = None\n\n\ndef _trim_arity(func, max_limit=3):\n    \"\"\"decorator to trim function calls to match the arity of the target\"\"\"\n    global _trim_arity_call_line\n\n    if func in _single_arg_builtins:\n        return lambda s, l, t: func(t)\n\n    limit = 0\n    found_arity = False\n\n    def extract_tb(tb, limit=0):\n        frames = traceback.extract_tb(tb, limit=limit)\n        frame_summary = frames[-1]\n        return [frame_summary[:2]]\n\n    # synthesize what would be returned by traceback.extract_stack at the call to\n    # user's parse action 'func', so that we don't incur call penalty at parse time\n\n    # fmt: off\n    LINE_DIFF = 7\n    # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND\n    # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!!\n    _trim_arity_call_line = (_trim_arity_call_line or traceback.extract_stack(limit=2)[-1])\n    pa_call_line_synth = (_trim_arity_call_line[0], _trim_arity_call_line[1] + LINE_DIFF)\n\n    def wrapper(*args):\n        nonlocal found_arity, limit\n        while 1:\n            try:\n                ret = func(*args[limit:])\n                found_arity = True\n                return ret\n            except TypeError as te:\n                # re-raise TypeErrors if they did not come from our arity testing\n                if found_arity:\n                    raise\n                else:\n                    tb = te.__traceback__\n                    trim_arity_type_error = (\n                        extract_tb(tb, limit=2)[-1][:2] == pa_call_line_synth\n                    )\n                    del tb\n\n                    if trim_arity_type_error:\n                        if limit < max_limit:\n                            limit += 1\n                            continue\n\n                    raise\n    # fmt: on\n\n    # copy func name to wrapper for sensible debug output\n    # (can't use functools.wraps, since that messes with function signature)\n    func_name = getattr(func, \"__name__\", getattr(func, \"__class__\").__name__)\n    wrapper.__name__ = func_name\n    wrapper.__doc__ = func.__doc__\n\n    return wrapper\n\n\ndef condition_as_parse_action(\n    fn: ParseCondition, message: str = None, fatal: bool = False\n) -> ParseAction:\n    \"\"\"\n    Function to convert a simple predicate function that returns ``True`` or ``False``\n    into a parse action. Can be used in places when a parse action is required\n    and :class:`ParserElement.add_condition` cannot be used (such as when adding a condition\n    to an operator level in :class:`infix_notation`).\n\n    Optional keyword arguments:\n\n    - ``message`` - define a custom message to be used in the raised exception\n    - ``fatal`` - if True, will raise :class:`ParseFatalException` to stop parsing immediately;\n      otherwise will raise :class:`ParseException`\n\n    \"\"\"\n    msg = message if message is not None else \"failed user-defined condition\"\n    exc_type = ParseFatalException if fatal else ParseException\n    fn = _trim_arity(fn)\n\n    @wraps(fn)\n    def pa(s, l, t):\n        if not bool(fn(s, l, t)):\n            raise exc_type(s, l, msg)\n\n    return pa\n\n\ndef _default_start_debug_action(\n    instring: str, loc: int, expr: \"ParserElement\", cache_hit: bool = False\n):\n    cache_hit_str = \"*\" if cache_hit else \"\"\n    print(\n        (\n            \"{}Match {} at loc {}({},{})\\n  {}\\n  {}^\".format(\n                cache_hit_str,\n                expr,\n                loc,\n                lineno(loc, instring),\n                col(loc, instring),\n                line(loc, instring),\n                \" \" * (col(loc, instring) - 1),\n            )\n        )\n    )\n\n\ndef _default_success_debug_action(\n    instring: str,\n    startloc: int,\n    endloc: int,\n    expr: \"ParserElement\",\n    toks: ParseResults,\n    cache_hit: bool = False,\n):\n    cache_hit_str = \"*\" if cache_hit else \"\"\n    print(\"{}Matched {} -> {}\".format(cache_hit_str, expr, toks.as_list()))\n\n\ndef _default_exception_debug_action(\n    instring: str,\n    loc: int,\n    expr: \"ParserElement\",\n    exc: Exception,\n    cache_hit: bool = False,\n):\n    cache_hit_str = \"*\" if cache_hit else \"\"\n    print(\n        \"{}Match {} failed, {} raised: {}\".format(\n            cache_hit_str, expr, type(exc).__name__, exc\n        )\n    )\n\n\ndef null_debug_action(*args):\n    \"\"\"'Do-nothing' debug action, to suppress debugging output during parsing.\"\"\"\n\n\nclass ParserElement(ABC):\n    \"\"\"Abstract base level parser element class.\"\"\"\n\n    DEFAULT_WHITE_CHARS: str = \" \\n\\t\\r\"\n    verbose_stacktrace: bool = False\n    _literalStringClass: typing.Optional[type] = None\n\n    @staticmethod\n    def set_default_whitespace_chars(chars: str) -> None:\n        r\"\"\"\n        Overrides the default whitespace chars\n\n        Example::\n\n            # default whitespace chars are space, <TAB> and newline\n            Word(alphas)[1, ...].parse_string(\"abc def\\nghi jkl\")  # -> ['abc', 'def', 'ghi', 'jkl']\n\n            # change to just treat newline as significant\n            ParserElement.set_default_whitespace_chars(\" \\t\")\n            Word(alphas)[1, ...].parse_string(\"abc def\\nghi jkl\")  # -> ['abc', 'def']\n        \"\"\"\n        ParserElement.DEFAULT_WHITE_CHARS = chars\n\n        # update whitespace all parse expressions defined in this module\n        for expr in _builtin_exprs:\n            if expr.copyDefaultWhiteChars:\n                expr.whiteChars = set(chars)\n\n    @staticmethod\n    def inline_literals_using(cls: type) -> None:\n        \"\"\"\n        Set class to be used for inclusion of string literals into a parser.\n\n        Example::\n\n            # default literal class used is Literal\n            integer = Word(nums)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            date_str.parse_string(\"1999/12/31\")  # -> ['1999', '/', '12', '/', '31']\n\n\n            # change to Suppress\n            ParserElement.inline_literals_using(Suppress)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            date_str.parse_string(\"1999/12/31\")  # -> ['1999', '12', '31']\n        \"\"\"\n        ParserElement._literalStringClass = cls\n\n    class DebugActions(NamedTuple):\n        debug_try: typing.Optional[DebugStartAction]\n        debug_match: typing.Optional[DebugSuccessAction]\n        debug_fail: typing.Optional[DebugExceptionAction]\n\n    def __init__(self, savelist: bool = False):\n        self.parseAction: List[ParseAction] = list()\n        self.failAction: typing.Optional[ParseFailAction] = None\n        self.customName = None\n        self._defaultName = None\n        self.resultsName = None\n        self.saveAsList = savelist\n        self.skipWhitespace = True\n        self.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS)\n        self.copyDefaultWhiteChars = True\n        # used when checking for left-recursion\n        self.mayReturnEmpty = False\n        self.keepTabs = False\n        self.ignoreExprs: List[\"ParserElement\"] = list()\n        self.debug = False\n        self.streamlined = False\n        # optimize exception handling for subclasses that don't advance parse index\n        self.mayIndexError = True\n        self.errmsg = \"\"\n        # mark results names as modal (report only last) or cumulative (list all)\n        self.modalResults = True\n        # custom debug actions\n        self.debugActions = self.DebugActions(None, None, None)\n        # avoid redundant calls to preParse\n        self.callPreparse = True\n        self.callDuringTry = False\n        self.suppress_warnings_: List[Diagnostics] = []\n\n    def suppress_warning(self, warning_type: Diagnostics) -> \"ParserElement\":\n        \"\"\"\n        Suppress warnings emitted for a particular diagnostic on this expression.\n\n        Example::\n\n            base = pp.Forward()\n            base.suppress_warning(Diagnostics.warn_on_parse_using_empty_Forward)\n\n            # statement would normally raise a warning, but is now suppressed\n            print(base.parseString(\"x\"))\n\n        \"\"\"\n        self.suppress_warnings_.append(warning_type)\n        return self\n\n    def copy(self) -> \"ParserElement\":\n        \"\"\"\n        Make a copy of this :class:`ParserElement`.  Useful for defining\n        different parse actions for the same parsing pattern, using copies of\n        the original parse element.\n\n        Example::\n\n            integer = Word(nums).set_parse_action(lambda toks: int(toks[0]))\n            integerK = integer.copy().add_parse_action(lambda toks: toks[0] * 1024) + Suppress(\"K\")\n            integerM = integer.copy().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress(\"M\")\n\n            print((integerK | integerM | integer)[1, ...].parse_string(\"5K 100 640K 256M\"))\n\n        prints::\n\n            [5120, 100, 655360, 268435456]\n\n        Equivalent form of ``expr.copy()`` is just ``expr()``::\n\n            integerM = integer().add_parse_action(lambda toks: toks[0] * 1024 * 1024) + Suppress(\"M\")\n        \"\"\"\n        cpy = copy.copy(self)\n        cpy.parseAction = self.parseAction[:]\n        cpy.ignoreExprs = self.ignoreExprs[:]\n        if self.copyDefaultWhiteChars:\n            cpy.whiteChars = set(ParserElement.DEFAULT_WHITE_CHARS)\n        return cpy\n\n    def set_results_name(\n        self, name: str, list_all_matches: bool = False, *, listAllMatches: bool = False\n    ) -> \"ParserElement\":\n        \"\"\"\n        Define name for referencing matching tokens as a nested attribute\n        of the returned parse results.\n\n        Normally, results names are assigned as you would assign keys in a dict:\n        any existing value is overwritten by later values. If it is necessary to\n        keep all values captured for a particular results name, call ``set_results_name``\n        with ``list_all_matches`` = True.\n\n        NOTE: ``set_results_name`` returns a *copy* of the original :class:`ParserElement` object;\n        this is so that the client can define a basic element, such as an\n        integer, and reference it in multiple places with different names.\n\n        You can also set results names using the abbreviated syntax,\n        ``expr(\"name\")`` in place of ``expr.set_results_name(\"name\")``\n        - see :class:`__call__`. If ``list_all_matches`` is required, use\n        ``expr(\"name*\")``.\n\n        Example::\n\n            date_str = (integer.set_results_name(\"year\") + '/'\n                        + integer.set_results_name(\"month\") + '/'\n                        + integer.set_results_name(\"day\"))\n\n            # equivalent form:\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n        \"\"\"\n        listAllMatches = listAllMatches or list_all_matches\n        return self._setResultsName(name, listAllMatches)\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if name is None:\n            return self\n        newself = self.copy()\n        if name.endswith(\"*\"):\n            name = name[:-1]\n            listAllMatches = True\n        newself.resultsName = name\n        newself.modalResults = not listAllMatches\n        return newself\n\n    def set_break(self, break_flag: bool = True) -> \"ParserElement\":\n        \"\"\"\n        Method to invoke the Python pdb debugger when this element is\n        about to be parsed. Set ``break_flag`` to ``True`` to enable, ``False`` to\n        disable.\n        \"\"\"\n        if break_flag:\n            _parseMethod = self._parse\n\n            def breaker(instring, loc, doActions=True, callPreParse=True):\n                import pdb\n\n                # this call to pdb.set_trace() is intentional, not a checkin error\n                pdb.set_trace()\n                return _parseMethod(instring, loc, doActions, callPreParse)\n\n            breaker._originalParseMethod = _parseMethod\n            self._parse = breaker\n        else:\n            if hasattr(self._parse, \"_originalParseMethod\"):\n                self._parse = self._parse._originalParseMethod\n        return self\n\n    def set_parse_action(self, *fns: ParseAction, **kwargs) -> \"ParserElement\":\n        \"\"\"\n        Define one or more actions to perform when successfully matching parse element definition.\n\n        Parse actions can be called to perform data conversions, do extra validation,\n        update external data structures, or enhance or replace the parsed tokens.\n        Each parse action ``fn`` is a callable method with 0-3 arguments, called as\n        ``fn(s, loc, toks)`` , ``fn(loc, toks)`` , ``fn(toks)`` , or just ``fn()`` , where:\n\n        - s   = the original string being parsed (see note below)\n        - loc = the location of the matching substring\n        - toks = a list of the matched tokens, packaged as a :class:`ParseResults` object\n\n        The parsed tokens are passed to the parse action as ParseResults. They can be\n        modified in place using list-style append, extend, and pop operations to update\n        the parsed list elements; and with dictionary-style item set and del operations\n        to add, update, or remove any named results. If the tokens are modified in place,\n        it is not necessary to return them with a return statement.\n\n        Parse actions can also completely replace the given tokens, with another ``ParseResults``\n        object, or with some entirely different object (common for parse actions that perform data\n        conversions). A convenient way to build a new parse result is to define the values\n        using a dict, and then create the return value using :class:`ParseResults.from_dict`.\n\n        If None is passed as the ``fn`` parse action, all previously added parse actions for this\n        expression are cleared.\n\n        Optional keyword arguments:\n\n        - call_during_try = (default= ``False``) indicate if parse action should be run during\n          lookaheads and alternate testing. For parse actions that have side effects, it is\n          important to only call the parse action once it is determined that it is being\n          called as part of a successful parse. For parse actions that perform additional\n          validation, then call_during_try should be passed as True, so that the validation\n          code is included in the preliminary \"try\" parses.\n\n        Note: the default parsing behavior is to expand tabs in the input string\n        before starting the parsing process.  See :class:`parse_string` for more\n        information on parsing strings containing ``<TAB>`` s, and suggested\n        methods to maintain a consistent view of the parsed string, the parse\n        location, and line and column positions within the parsed string.\n\n        Example::\n\n            # parse dates in the form YYYY/MM/DD\n\n            # use parse action to convert toks from str to int at parse time\n            def convert_to_int(toks):\n                return int(toks[0])\n\n            # use a parse action to verify that the date is a valid date\n            def is_valid_date(instring, loc, toks):\n                from datetime import date\n                year, month, day = toks[::2]\n                try:\n                    date(year, month, day)\n                except ValueError:\n                    raise ParseException(instring, loc, \"invalid date given\")\n\n            integer = Word(nums)\n            date_str = integer + '/' + integer + '/' + integer\n\n            # add parse actions\n            integer.set_parse_action(convert_to_int)\n            date_str.set_parse_action(is_valid_date)\n\n            # note that integer fields are now ints, not strings\n            date_str.run_tests('''\n                # successful parse - note that integer fields were converted to ints\n                1999/12/31\n\n                # fail - invalid date\n                1999/13/31\n                ''')\n        \"\"\"\n        if list(fns) == [None]:\n            self.parseAction = []\n        else:\n            if not all(callable(fn) for fn in fns):\n                raise TypeError(\"parse actions must be callable\")\n            self.parseAction = [_trim_arity(fn) for fn in fns]\n            self.callDuringTry = kwargs.get(\n                \"call_during_try\", kwargs.get(\"callDuringTry\", False)\n            )\n        return self\n\n    def add_parse_action(self, *fns: ParseAction, **kwargs) -> \"ParserElement\":\n        \"\"\"\n        Add one or more parse actions to expression's list of parse actions. See :class:`set_parse_action`.\n\n        See examples in :class:`copy`.\n        \"\"\"\n        self.parseAction += [_trim_arity(fn) for fn in fns]\n        self.callDuringTry = self.callDuringTry or kwargs.get(\n            \"call_during_try\", kwargs.get(\"callDuringTry\", False)\n        )\n        return self\n\n    def add_condition(self, *fns: ParseCondition, **kwargs) -> \"ParserElement\":\n        \"\"\"Add a boolean predicate function to expression's list of parse actions. See\n        :class:`set_parse_action` for function call signatures. Unlike ``set_parse_action``,\n        functions passed to ``add_condition`` need to return boolean success/fail of the condition.\n\n        Optional keyword arguments:\n\n        - message = define a custom message to be used in the raised exception\n        - fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise\n          ParseException\n        - call_during_try = boolean to indicate if this method should be called during internal tryParse calls,\n          default=False\n\n        Example::\n\n            integer = Word(nums).set_parse_action(lambda toks: int(toks[0]))\n            year_int = integer.copy()\n            year_int.add_condition(lambda toks: toks[0] >= 2000, message=\"Only support years 2000 and later\")\n            date_str = year_int + '/' + integer + '/' + integer\n\n            result = date_str.parse_string(\"1999/12/31\")  # -> Exception: Only support years 2000 and later (at char 0),\n                                                                         (line:1, col:1)\n        \"\"\"\n        for fn in fns:\n            self.parseAction.append(\n                condition_as_parse_action(\n                    fn, message=kwargs.get(\"message\"), fatal=kwargs.get(\"fatal\", False)\n                )\n            )\n\n        self.callDuringTry = self.callDuringTry or kwargs.get(\n            \"call_during_try\", kwargs.get(\"callDuringTry\", False)\n        )\n        return self\n\n    def set_fail_action(self, fn: ParseFailAction) -> \"ParserElement\":\n        \"\"\"\n        Define action to perform if parsing fails at this expression.\n        Fail acton fn is a callable function that takes the arguments\n        ``fn(s, loc, expr, err)`` where:\n\n        - s = string being parsed\n        - loc = location where expression match was attempted and failed\n        - expr = the parse expression that failed\n        - err = the exception thrown\n\n        The function returns no value.  It may throw :class:`ParseFatalException`\n        if it is desired to stop parsing immediately.\"\"\"\n        self.failAction = fn\n        return self\n\n    def _skipIgnorables(self, instring, loc):\n        exprsFound = True\n        while exprsFound:\n            exprsFound = False\n            for e in self.ignoreExprs:\n                try:\n                    while 1:\n                        loc, dummy = e._parse(instring, loc)\n                        exprsFound = True\n                except ParseException:\n                    pass\n        return loc\n\n    def preParse(self, instring, loc):\n        if self.ignoreExprs:\n            loc = self._skipIgnorables(instring, loc)\n\n        if self.skipWhitespace:\n            instrlen = len(instring)\n            white_chars = self.whiteChars\n            while loc < instrlen and instring[loc] in white_chars:\n                loc += 1\n\n        return loc\n\n    def parseImpl(self, instring, loc, doActions=True):\n        return loc, []\n\n    def postParse(self, instring, loc, tokenlist):\n        return tokenlist\n\n    # @profile\n    def _parseNoCache(\n        self, instring, loc, doActions=True, callPreParse=True\n    ) -> Tuple[int, ParseResults]:\n        TRY, MATCH, FAIL = 0, 1, 2\n        debugging = self.debug  # and doActions)\n        len_instring = len(instring)\n\n        if debugging or self.failAction:\n            # print(\"Match {} at loc {}({}, {})\".format(self, loc, lineno(loc, instring), col(loc, instring)))\n            try:\n                if callPreParse and self.callPreparse:\n                    pre_loc = self.preParse(instring, loc)\n                else:\n                    pre_loc = loc\n                tokens_start = pre_loc\n                if self.debugActions.debug_try:\n                    self.debugActions.debug_try(instring, tokens_start, self, False)\n                if self.mayIndexError or pre_loc >= len_instring:\n                    try:\n                        loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n                    except IndexError:\n                        raise ParseException(instring, len_instring, self.errmsg, self)\n                else:\n                    loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n            except Exception as err:\n                # print(\"Exception raised:\", err)\n                if self.debugActions.debug_fail:\n                    self.debugActions.debug_fail(\n                        instring, tokens_start, self, err, False\n                    )\n                if self.failAction:\n                    self.failAction(instring, tokens_start, self, err)\n                raise\n        else:\n            if callPreParse and self.callPreparse:\n                pre_loc = self.preParse(instring, loc)\n            else:\n                pre_loc = loc\n            tokens_start = pre_loc\n            if self.mayIndexError or pre_loc >= len_instring:\n                try:\n                    loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n                except IndexError:\n                    raise ParseException(instring, len_instring, self.errmsg, self)\n            else:\n                loc, tokens = self.parseImpl(instring, pre_loc, doActions)\n\n        tokens = self.postParse(instring, loc, tokens)\n\n        ret_tokens = ParseResults(\n            tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults\n        )\n        if self.parseAction and (doActions or self.callDuringTry):\n            if debugging:\n                try:\n                    for fn in self.parseAction:\n                        try:\n                            tokens = fn(instring, tokens_start, ret_tokens)\n                        except IndexError as parse_action_exc:\n                            exc = ParseException(\"exception raised in parse action\")\n                            raise exc from parse_action_exc\n\n                        if tokens is not None and tokens is not ret_tokens:\n                            ret_tokens = ParseResults(\n                                tokens,\n                                self.resultsName,\n                                asList=self.saveAsList\n                                and isinstance(tokens, (ParseResults, list)),\n                                modal=self.modalResults,\n                            )\n                except Exception as err:\n                    # print \"Exception raised in user parse action:\", err\n                    if self.debugActions.debug_fail:\n                        self.debugActions.debug_fail(\n                            instring, tokens_start, self, err, False\n                        )\n                    raise\n            else:\n                for fn in self.parseAction:\n                    try:\n                        tokens = fn(instring, tokens_start, ret_tokens)\n                    except IndexError as parse_action_exc:\n                        exc = ParseException(\"exception raised in parse action\")\n                        raise exc from parse_action_exc\n\n                    if tokens is not None and tokens is not ret_tokens:\n                        ret_tokens = ParseResults(\n                            tokens,\n                            self.resultsName,\n                            asList=self.saveAsList\n                            and isinstance(tokens, (ParseResults, list)),\n                            modal=self.modalResults,\n                        )\n        if debugging:\n            # print(\"Matched\", self, \"->\", ret_tokens.as_list())\n            if self.debugActions.debug_match:\n                self.debugActions.debug_match(\n                    instring, tokens_start, loc, self, ret_tokens, False\n                )\n\n        return loc, ret_tokens\n\n    def try_parse(self, instring: str, loc: int, raise_fatal: bool = False) -> int:\n        try:\n            return self._parse(instring, loc, doActions=False)[0]\n        except ParseFatalException:\n            if raise_fatal:\n                raise\n            raise ParseException(instring, loc, self.errmsg, self)\n\n    def can_parse_next(self, instring: str, loc: int) -> bool:\n        try:\n            self.try_parse(instring, loc)\n        except (ParseException, IndexError):\n            return False\n        else:\n            return True\n\n    # cache for left-recursion in Forward references\n    recursion_lock = RLock()\n    recursion_memos: typing.Dict[\n        Tuple[int, \"Forward\", bool], Tuple[int, Union[ParseResults, Exception]]\n    ] = {}\n\n    # argument cache for optimizing repeated calls when backtracking through recursive expressions\n    packrat_cache = (\n        {}\n    )  # this is set later by enabled_packrat(); this is here so that reset_cache() doesn't fail\n    packrat_cache_lock = RLock()\n    packrat_cache_stats = [0, 0]\n\n    # this method gets repeatedly called during backtracking with the same arguments -\n    # we can cache these arguments and save ourselves the trouble of re-parsing the contained expression\n    def _parseCache(\n        self, instring, loc, doActions=True, callPreParse=True\n    ) -> Tuple[int, ParseResults]:\n        HIT, MISS = 0, 1\n        TRY, MATCH, FAIL = 0, 1, 2\n        lookup = (self, instring, loc, callPreParse, doActions)\n        with ParserElement.packrat_cache_lock:\n            cache = ParserElement.packrat_cache\n            value = cache.get(lookup)\n            if value is cache.not_in_cache:\n                ParserElement.packrat_cache_stats[MISS] += 1\n                try:\n                    value = self._parseNoCache(instring, loc, doActions, callPreParse)\n                except ParseBaseException as pe:\n                    # cache a copy of the exception, without the traceback\n                    cache.set(lookup, pe.__class__(*pe.args))\n                    raise\n                else:\n                    cache.set(lookup, (value[0], value[1].copy(), loc))\n                    return value\n            else:\n                ParserElement.packrat_cache_stats[HIT] += 1\n                if self.debug and self.debugActions.debug_try:\n                    try:\n                        self.debugActions.debug_try(instring, loc, self, cache_hit=True)\n                    except TypeError:\n                        pass\n                if isinstance(value, Exception):\n                    if self.debug and self.debugActions.debug_fail:\n                        try:\n                            self.debugActions.debug_fail(\n                                instring, loc, self, value, cache_hit=True\n                            )\n                        except TypeError:\n                            pass\n                    raise value\n\n                loc_, result, endloc = value[0], value[1].copy(), value[2]\n                if self.debug and self.debugActions.debug_match:\n                    try:\n                        self.debugActions.debug_match(\n                            instring, loc_, endloc, self, result, cache_hit=True\n                        )\n                    except TypeError:\n                        pass\n\n                return loc_, result\n\n    _parse = _parseNoCache\n\n    @staticmethod\n    def reset_cache() -> None:\n        ParserElement.packrat_cache.clear()\n        ParserElement.packrat_cache_stats[:] = [0] * len(\n            ParserElement.packrat_cache_stats\n        )\n        ParserElement.recursion_memos.clear()\n\n    _packratEnabled = False\n    _left_recursion_enabled = False\n\n    @staticmethod\n    def disable_memoization() -> None:\n        \"\"\"\n        Disables active Packrat or Left Recursion parsing and their memoization\n\n        This method also works if neither Packrat nor Left Recursion are enabled.\n        This makes it safe to call before activating Packrat nor Left Recursion\n        to clear any previous settings.\n        \"\"\"\n        ParserElement.reset_cache()\n        ParserElement._left_recursion_enabled = False\n        ParserElement._packratEnabled = False\n        ParserElement._parse = ParserElement._parseNoCache\n\n    @staticmethod\n    def enable_left_recursion(\n        cache_size_limit: typing.Optional[int] = None, *, force=False\n    ) -> None:\n        \"\"\"\n        Enables \"bounded recursion\" parsing, which allows for both direct and indirect\n        left-recursion. During parsing, left-recursive :class:`Forward` elements are\n        repeatedly matched with a fixed recursion depth that is gradually increased\n        until finding the longest match.\n\n        Example::\n\n            import pyparsing as pp\n            pp.ParserElement.enable_left_recursion()\n\n            E = pp.Forward(\"E\")\n            num = pp.Word(pp.nums)\n            # match `num`, or `num '+' num`, or `num '+' num '+' num`, ...\n            E <<= E + '+' - num | num\n\n            print(E.parse_string(\"1+2+3\"))\n\n        Recursion search naturally memoizes matches of ``Forward`` elements and may\n        thus skip reevaluation of parse actions during backtracking. This may break\n        programs with parse actions which rely on strict ordering of side-effects.\n\n        Parameters:\n\n        - cache_size_limit - (default=``None``) - memoize at most this many\n          ``Forward`` elements during matching; if ``None`` (the default),\n          memoize all ``Forward`` elements.\n\n        Bounded Recursion parsing works similar but not identical to Packrat parsing,\n        thus the two cannot be used together. Use ``force=True`` to disable any\n        previous, conflicting settings.\n        \"\"\"\n        if force:\n            ParserElement.disable_memoization()\n        elif ParserElement._packratEnabled:\n            raise RuntimeError(\"Packrat and Bounded Recursion are not compatible\")\n        if cache_size_limit is None:\n            ParserElement.recursion_memos = _UnboundedMemo()\n        elif cache_size_limit > 0:\n            ParserElement.recursion_memos = _LRUMemo(capacity=cache_size_limit)\n        else:\n            raise NotImplementedError(\"Memo size of %s\" % cache_size_limit)\n        ParserElement._left_recursion_enabled = True\n\n    @staticmethod\n    def enable_packrat(cache_size_limit: int = 128, *, force: bool = False) -> None:\n        \"\"\"\n        Enables \"packrat\" parsing, which adds memoizing to the parsing logic.\n        Repeated parse attempts at the same string location (which happens\n        often in many complex grammars) can immediately return a cached value,\n        instead of re-executing parsing/validating code.  Memoizing is done of\n        both valid results and parsing exceptions.\n\n        Parameters:\n\n        - cache_size_limit - (default= ``128``) - if an integer value is provided\n          will limit the size of the packrat cache; if None is passed, then\n          the cache size will be unbounded; if 0 is passed, the cache will\n          be effectively disabled.\n\n        This speedup may break existing programs that use parse actions that\n        have side-effects.  For this reason, packrat parsing is disabled when\n        you first import pyparsing.  To activate the packrat feature, your\n        program must call the class method :class:`ParserElement.enable_packrat`.\n        For best results, call ``enable_packrat()`` immediately after\n        importing pyparsing.\n\n        Example::\n\n            import pyparsing\n            pyparsing.ParserElement.enable_packrat()\n\n        Packrat parsing works similar but not identical to Bounded Recursion parsing,\n        thus the two cannot be used together. Use ``force=True`` to disable any\n        previous, conflicting settings.\n        \"\"\"\n        if force:\n            ParserElement.disable_memoization()\n        elif ParserElement._left_recursion_enabled:\n            raise RuntimeError(\"Packrat and Bounded Recursion are not compatible\")\n        if not ParserElement._packratEnabled:\n            ParserElement._packratEnabled = True\n            if cache_size_limit is None:\n                ParserElement.packrat_cache = _UnboundedCache()\n            else:\n                ParserElement.packrat_cache = _FifoCache(cache_size_limit)\n            ParserElement._parse = ParserElement._parseCache\n\n    def parse_string(\n        self, instring: str, parse_all: bool = False, *, parseAll: bool = False\n    ) -> ParseResults:\n        \"\"\"\n        Parse a string with respect to the parser definition. This function is intended as the primary interface to the\n        client code.\n\n        :param instring: The input string to be parsed.\n        :param parse_all: If set, the entire input string must match the grammar.\n        :param parseAll: retained for pre-PEP8 compatibility, will be removed in a future release.\n        :raises ParseException: Raised if ``parse_all`` is set and the input string does not match the whole grammar.\n        :returns: the parsed data as a :class:`ParseResults` object, which may be accessed as a `list`, a `dict`, or\n          an object with attributes if the given parser includes results names.\n\n        If the input string is required to match the entire grammar, ``parse_all`` flag must be set to ``True``. This\n        is also equivalent to ending the grammar with :class:`StringEnd`().\n\n        To report proper column numbers, ``parse_string`` operates on a copy of the input string where all tabs are\n        converted to spaces (8 spaces per tab, as per the default in ``string.expandtabs``). If the input string\n        contains tabs and the grammar uses parse actions that use the ``loc`` argument to index into the string\n        being parsed, one can ensure a consistent view of the input string by doing one of the following:\n\n        - calling ``parse_with_tabs`` on your grammar before calling ``parse_string`` (see :class:`parse_with_tabs`),\n        - define your parse action using the full ``(s,loc,toks)`` signature, and reference the input string using the\n          parse action's ``s`` argument, or\n        - explicitly expand the tabs in your input string before calling ``parse_string``.\n\n        Examples:\n\n        By default, partial matches are OK.\n\n        >>> res = Word('a').parse_string('aaaaabaaa')\n        >>> print(res)\n        ['aaaaa']\n\n        The parsing behavior varies by the inheriting class of this abstract class. Please refer to the children\n        directly to see more examples.\n\n        It raises an exception if parse_all flag is set and instring does not match the whole grammar.\n\n        >>> res = Word('a').parse_string('aaaaabaaa', parse_all=True)\n        Traceback (most recent call last):\n        ...\n        pyparsing.ParseException: Expected end of text, found 'b'  (at char 5), (line:1, col:6)\n        \"\"\"\n        parseAll = parse_all or parseAll\n\n        ParserElement.reset_cache()\n        if not self.streamlined:\n            self.streamline()\n        for e in self.ignoreExprs:\n            e.streamline()\n        if not self.keepTabs:\n            instring = instring.expandtabs()\n        try:\n            loc, tokens = self._parse(instring, 0)\n            if parseAll:\n                loc = self.preParse(instring, loc)\n                se = Empty() + StringEnd()\n                se._parse(instring, loc)\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clearing out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n        else:\n            return tokens\n\n    def scan_string(\n        self,\n        instring: str,\n        max_matches: int = _MAX_INT,\n        overlap: bool = False,\n        *,\n        debug: bool = False,\n        maxMatches: int = _MAX_INT,\n    ) -> Generator[Tuple[ParseResults, int, int], None, None]:\n        \"\"\"\n        Scan the input string for expression matches.  Each match will return the\n        matching tokens, start location, and end location.  May be called with optional\n        ``max_matches`` argument, to clip scanning after 'n' matches are found.  If\n        ``overlap`` is specified, then overlapping matches will be reported.\n\n        Note that the start and end locations are reported relative to the string\n        being parsed.  See :class:`parse_string` for more information on parsing\n        strings with embedded tabs.\n\n        Example::\n\n            source = \"sldjf123lsdjjkf345sldkjf879lkjsfd987\"\n            print(source)\n            for tokens, start, end in Word(alphas).scan_string(source):\n                print(' '*start + '^'*(end-start))\n                print(' '*start + tokens[0])\n\n        prints::\n\n            sldjf123lsdjjkf345sldkjf879lkjsfd987\n            ^^^^^\n            sldjf\n                    ^^^^^^^\n                    lsdjjkf\n                              ^^^^^^\n                              sldkjf\n                                       ^^^^^^\n                                       lkjsfd\n        \"\"\"\n        maxMatches = min(maxMatches, max_matches)\n        if not self.streamlined:\n            self.streamline()\n        for e in self.ignoreExprs:\n            e.streamline()\n\n        if not self.keepTabs:\n            instring = str(instring).expandtabs()\n        instrlen = len(instring)\n        loc = 0\n        preparseFn = self.preParse\n        parseFn = self._parse\n        ParserElement.resetCache()\n        matches = 0\n        try:\n            while loc <= instrlen and matches < maxMatches:\n                try:\n                    preloc = preparseFn(instring, loc)\n                    nextLoc, tokens = parseFn(instring, preloc, callPreParse=False)\n                except ParseException:\n                    loc = preloc + 1\n                else:\n                    if nextLoc > loc:\n                        matches += 1\n                        if debug:\n                            print(\n                                {\n                                    \"tokens\": tokens.asList(),\n                                    \"start\": preloc,\n                                    \"end\": nextLoc,\n                                }\n                            )\n                        yield tokens, preloc, nextLoc\n                        if overlap:\n                            nextloc = preparseFn(instring, loc)\n                            if nextloc > loc:\n                                loc = nextLoc\n                            else:\n                                loc += 1\n                        else:\n                            loc = nextLoc\n                    else:\n                        loc = preloc + 1\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clears out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n\n    def transform_string(self, instring: str, *, debug: bool = False) -> str:\n        \"\"\"\n        Extension to :class:`scan_string`, to modify matching text with modified tokens that may\n        be returned from a parse action.  To use ``transform_string``, define a grammar and\n        attach a parse action to it that modifies the returned token list.\n        Invoking ``transform_string()`` on a target string will then scan for matches,\n        and replace the matched text patterns according to the logic in the parse\n        action.  ``transform_string()`` returns the resulting transformed string.\n\n        Example::\n\n            wd = Word(alphas)\n            wd.set_parse_action(lambda toks: toks[0].title())\n\n            print(wd.transform_string(\"now is the winter of our discontent made glorious summer by this sun of york.\"))\n\n        prints::\n\n            Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.\n        \"\"\"\n        out: List[str] = []\n        lastE = 0\n        # force preservation of <TAB>s, to minimize unwanted transformation of string, and to\n        # keep string locs straight between transform_string and scan_string\n        self.keepTabs = True\n        try:\n            for t, s, e in self.scan_string(instring, debug=debug):\n                out.append(instring[lastE:s])\n                if t:\n                    if isinstance(t, ParseResults):\n                        out += t.as_list()\n                    elif isinstance(t, Iterable) and not isinstance(t, str_type):\n                        out.extend(t)\n                    else:\n                        out.append(t)\n                lastE = e\n            out.append(instring[lastE:])\n            out = [o for o in out if o]\n            return \"\".join([str(s) for s in _flatten(out)])\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clears out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n\n    def search_string(\n        self,\n        instring: str,\n        max_matches: int = _MAX_INT,\n        *,\n        debug: bool = False,\n        maxMatches: int = _MAX_INT,\n    ) -> ParseResults:\n        \"\"\"\n        Another extension to :class:`scan_string`, simplifying the access to the tokens found\n        to match the given parse expression.  May be called with optional\n        ``max_matches`` argument, to clip searching after 'n' matches are found.\n\n        Example::\n\n            # a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters\n            cap_word = Word(alphas.upper(), alphas.lower())\n\n            print(cap_word.search_string(\"More than Iron, more than Lead, more than Gold I need Electricity\"))\n\n            # the sum() builtin can be used to merge results into a single ParseResults object\n            print(sum(cap_word.search_string(\"More than Iron, more than Lead, more than Gold I need Electricity\")))\n\n        prints::\n\n            [['More'], ['Iron'], ['Lead'], ['Gold'], ['I'], ['Electricity']]\n            ['More', 'Iron', 'Lead', 'Gold', 'I', 'Electricity']\n        \"\"\"\n        maxMatches = min(maxMatches, max_matches)\n        try:\n            return ParseResults(\n                [t for t, s, e in self.scan_string(instring, maxMatches, debug=debug)]\n            )\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clears out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n\n    def split(\n        self,\n        instring: str,\n        maxsplit: int = _MAX_INT,\n        include_separators: bool = False,\n        *,\n        includeSeparators=False,\n    ) -> Generator[str, None, None]:\n        \"\"\"\n        Generator method to split a string using the given expression as a separator.\n        May be called with optional ``maxsplit`` argument, to limit the number of splits;\n        and the optional ``include_separators`` argument (default= ``False``), if the separating\n        matching text should be included in the split results.\n\n        Example::\n\n            punc = one_of(list(\".,;:/-!?\"))\n            print(list(punc.split(\"This, this?, this sentence, is badly punctuated!\")))\n\n        prints::\n\n            ['This', ' this', '', ' this sentence', ' is badly punctuated', '']\n        \"\"\"\n        includeSeparators = includeSeparators or include_separators\n        last = 0\n        for t, s, e in self.scan_string(instring, max_matches=maxsplit):\n            yield instring[last:s]\n            if includeSeparators:\n                yield t[0]\n            last = e\n        yield instring[last:]\n\n    def __add__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``+`` operator - returns :class:`And`. Adding strings to a :class:`ParserElement`\n        converts them to :class:`Literal`s by default.\n\n        Example::\n\n            greet = Word(alphas) + \",\" + Word(alphas) + \"!\"\n            hello = \"Hello, World!\"\n            print(hello, \"->\", greet.parse_string(hello))\n\n        prints::\n\n            Hello, World! -> ['Hello', ',', 'World', '!']\n\n        ``...`` may be used as a parse expression as a short form of :class:`SkipTo`.\n\n            Literal('start') + ... + Literal('end')\n\n        is equivalent to:\n\n            Literal('start') + SkipTo('end')(\"_skipped*\") + Literal('end')\n\n        Note that the skipped text is returned with '_skipped' as a results name,\n        and to support having multiple skips in the same parser, the value returned is\n        a list of all skipped text.\n        \"\"\"\n        if other is Ellipsis:\n            return _PendingSkip(self)\n\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return And([self, other])\n\n    def __radd__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``+`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if other is Ellipsis:\n            return SkipTo(self)(\"_skipped*\") + self\n\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other + self\n\n    def __sub__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``-`` operator, returns :class:`And` with error stop\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return self + And._ErrorStop() + other\n\n    def __rsub__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``-`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other - self\n\n    def __mul__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``*`` operator, allows use of ``expr * 3`` in place of\n        ``expr + expr + expr``.  Expressions may also be multiplied by a 2-integer\n        tuple, similar to ``{min, max}`` multipliers in regular expressions.  Tuples\n        may also include ``None`` as in:\n        - ``expr*(n, None)`` or ``expr*(n, )`` is equivalent\n             to ``expr*n + ZeroOrMore(expr)``\n             (read as \"at least n instances of ``expr``\")\n        - ``expr*(None, n)`` is equivalent to ``expr*(0, n)``\n             (read as \"0 to n instances of ``expr``\")\n        - ``expr*(None, None)`` is equivalent to ``ZeroOrMore(expr)``\n        - ``expr*(1, None)`` is equivalent to ``OneOrMore(expr)``\n\n        Note that ``expr*(None, n)`` does not raise an exception if\n        more than n exprs exist in the input stream; that is,\n        ``expr*(None, n)`` does not enforce a maximum number of expr\n        occurrences.  If this behavior is desired, then write\n        ``expr*(None, n) + ~expr``\n        \"\"\"\n        if other is Ellipsis:\n            other = (0, None)\n        elif isinstance(other, tuple) and other[:1] == (Ellipsis,):\n            other = ((0,) + other[1:] + (None,))[:2]\n\n        if isinstance(other, int):\n            minElements, optElements = other, 0\n        elif isinstance(other, tuple):\n            other = tuple(o if o is not Ellipsis else None for o in other)\n            other = (other + (None, None))[:2]\n            if other[0] is None:\n                other = (0, other[1])\n            if isinstance(other[0], int) and other[1] is None:\n                if other[0] == 0:\n                    return ZeroOrMore(self)\n                if other[0] == 1:\n                    return OneOrMore(self)\n                else:\n                    return self * other[0] + ZeroOrMore(self)\n            elif isinstance(other[0], int) and isinstance(other[1], int):\n                minElements, optElements = other\n                optElements -= minElements\n            else:\n                raise TypeError(\n                    \"cannot multiply ParserElement and ({}) objects\".format(\n                        \",\".join(type(item).__name__ for item in other)\n                    )\n                )\n        else:\n            raise TypeError(\n                \"cannot multiply ParserElement and {} objects\".format(\n                    type(other).__name__\n                )\n            )\n\n        if minElements < 0:\n            raise ValueError(\"cannot multiply ParserElement by negative value\")\n        if optElements < 0:\n            raise ValueError(\n                \"second tuple value must be greater or equal to first tuple value\"\n            )\n        if minElements == optElements == 0:\n            return And([])\n\n        if optElements:\n\n            def makeOptionalList(n):\n                if n > 1:\n                    return Opt(self + makeOptionalList(n - 1))\n                else:\n                    return Opt(self)\n\n            if minElements:\n                if minElements == 1:\n                    ret = self + makeOptionalList(optElements)\n                else:\n                    ret = And([self] * minElements) + makeOptionalList(optElements)\n            else:\n                ret = makeOptionalList(optElements)\n        else:\n            if minElements == 1:\n                ret = self\n            else:\n                ret = And([self] * minElements)\n        return ret\n\n    def __rmul__(self, other) -> \"ParserElement\":\n        return self.__mul__(other)\n\n    def __or__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``|`` operator - returns :class:`MatchFirst`\n        \"\"\"\n        if other is Ellipsis:\n            return _PendingSkip(self, must_skip=True)\n\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return MatchFirst([self, other])\n\n    def __ror__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``|`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other | self\n\n    def __xor__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``^`` operator - returns :class:`Or`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return Or([self, other])\n\n    def __rxor__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``^`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other ^ self\n\n    def __and__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``&`` operator - returns :class:`Each`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return Each([self, other])\n\n    def __rand__(self, other) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``&`` operator when left operand is not a :class:`ParserElement`\n        \"\"\"\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        if not isinstance(other, ParserElement):\n            raise TypeError(\n                \"Cannot combine element of type {} with ParserElement\".format(\n                    type(other).__name__\n                )\n            )\n        return other & self\n\n    def __invert__(self) -> \"ParserElement\":\n        \"\"\"\n        Implementation of ``~`` operator - returns :class:`NotAny`\n        \"\"\"\n        return NotAny(self)\n\n    # disable __iter__ to override legacy use of sequential access to __getitem__ to\n    # iterate over a sequence\n    __iter__ = None\n\n    def __getitem__(self, key):\n        \"\"\"\n        use ``[]`` indexing notation as a short form for expression repetition:\n\n        - ``expr[n]`` is equivalent to ``expr*n``\n        - ``expr[m, n]`` is equivalent to ``expr*(m, n)``\n        - ``expr[n, ...]`` or ``expr[n,]`` is equivalent\n             to ``expr*n + ZeroOrMore(expr)``\n             (read as \"at least n instances of ``expr``\")\n        - ``expr[..., n]`` is equivalent to ``expr*(0, n)``\n             (read as \"0 to n instances of ``expr``\")\n        - ``expr[...]`` and ``expr[0, ...]`` are equivalent to ``ZeroOrMore(expr)``\n        - ``expr[1, ...]`` is equivalent to ``OneOrMore(expr)``\n\n        ``None`` may be used in place of ``...``.\n\n        Note that ``expr[..., n]`` and ``expr[m, n]``do not raise an exception\n        if more than ``n`` ``expr``s exist in the input stream.  If this behavior is\n        desired, then write ``expr[..., n] + ~expr``.\n        \"\"\"\n\n        # convert single arg keys to tuples\n        try:\n            if isinstance(key, str_type):\n                key = (key,)\n            iter(key)\n        except TypeError:\n            key = (key, key)\n\n        if len(key) > 2:\n            raise TypeError(\n                \"only 1 or 2 index arguments supported ({}{})\".format(\n                    key[:5], \"... [{}]\".format(len(key)) if len(key) > 5 else \"\"\n                )\n            )\n\n        # clip to 2 elements\n        ret = self * tuple(key[:2])\n        return ret\n\n    def __call__(self, name: str = None) -> \"ParserElement\":\n        \"\"\"\n        Shortcut for :class:`set_results_name`, with ``list_all_matches=False``.\n\n        If ``name`` is given with a trailing ``'*'`` character, then ``list_all_matches`` will be\n        passed as ``True``.\n\n        If ``name` is omitted, same as calling :class:`copy`.\n\n        Example::\n\n            # these are equivalent\n            userdata = Word(alphas).set_results_name(\"name\") + Word(nums + \"-\").set_results_name(\"socsecno\")\n            userdata = Word(alphas)(\"name\") + Word(nums + \"-\")(\"socsecno\")\n        \"\"\"\n        if name is not None:\n            return self._setResultsName(name)\n        else:\n            return self.copy()\n\n    def suppress(self) -> \"ParserElement\":\n        \"\"\"\n        Suppresses the output of this :class:`ParserElement`; useful to keep punctuation from\n        cluttering up returned output.\n        \"\"\"\n        return Suppress(self)\n\n    def ignore_whitespace(self, recursive: bool = True) -> \"ParserElement\":\n        \"\"\"\n        Enables the skipping of whitespace before matching the characters in the\n        :class:`ParserElement`'s defined pattern.\n\n        :param recursive: If ``True`` (the default), also enable whitespace skipping in child elements (if any)\n        \"\"\"\n        self.skipWhitespace = True\n        return self\n\n    def leave_whitespace(self, recursive: bool = True) -> \"ParserElement\":\n        \"\"\"\n        Disables the skipping of whitespace before matching the characters in the\n        :class:`ParserElement`'s defined pattern.  This is normally only used internally by\n        the pyparsing module, but may be needed in some whitespace-sensitive grammars.\n\n        :param recursive: If true (the default), also disable whitespace skipping in child elements (if any)\n        \"\"\"\n        self.skipWhitespace = False\n        return self\n\n    def set_whitespace_chars(\n        self, chars: Union[Set[str], str], copy_defaults: bool = False\n    ) -> \"ParserElement\":\n        \"\"\"\n        Overrides the default whitespace chars\n        \"\"\"\n        self.skipWhitespace = True\n        self.whiteChars = set(chars)\n        self.copyDefaultWhiteChars = copy_defaults\n        return self\n\n    def parse_with_tabs(self) -> \"ParserElement\":\n        \"\"\"\n        Overrides default behavior to expand ``<TAB>`` s to spaces before parsing the input string.\n        Must be called before ``parse_string`` when the input grammar contains elements that\n        match ``<TAB>`` characters.\n        \"\"\"\n        self.keepTabs = True\n        return self\n\n    def ignore(self, other: \"ParserElement\") -> \"ParserElement\":\n        \"\"\"\n        Define expression to be ignored (e.g., comments) while doing pattern\n        matching; may be called repeatedly, to define multiple comment or other\n        ignorable patterns.\n\n        Example::\n\n            patt = Word(alphas)[1, ...]\n            patt.parse_string('ablaj /* comment */ lskjd')\n            # -> ['ablaj']\n\n            patt.ignore(c_style_comment)\n            patt.parse_string('ablaj /* comment */ lskjd')\n            # -> ['ablaj', 'lskjd']\n        \"\"\"\n        import typing\n\n        if isinstance(other, str_type):\n            other = Suppress(other)\n\n        if isinstance(other, Suppress):\n            if other not in self.ignoreExprs:\n                self.ignoreExprs.append(other)\n        else:\n            self.ignoreExprs.append(Suppress(other.copy()))\n        return self\n\n    def set_debug_actions(\n        self,\n        start_action: DebugStartAction,\n        success_action: DebugSuccessAction,\n        exception_action: DebugExceptionAction,\n    ) -> \"ParserElement\":\n        \"\"\"\n        Customize display of debugging messages while doing pattern matching:\n\n        - ``start_action`` - method to be called when an expression is about to be parsed;\n          should have the signature ``fn(input_string: str, location: int, expression: ParserElement, cache_hit: bool)``\n\n        - ``success_action`` - method to be called when an expression has successfully parsed;\n          should have the signature ``fn(input_string: str, start_location: int, end_location: int, expression: ParserELement, parsed_tokens: ParseResults, cache_hit: bool)``\n\n        - ``exception_action`` - method to be called when expression fails to parse;\n          should have the signature ``fn(input_string: str, location: int, expression: ParserElement, exception: Exception, cache_hit: bool)``\n        \"\"\"\n        self.debugActions = self.DebugActions(\n            start_action or _default_start_debug_action,\n            success_action or _default_success_debug_action,\n            exception_action or _default_exception_debug_action,\n        )\n        self.debug = True\n        return self\n\n    def set_debug(self, flag: bool = True) -> \"ParserElement\":\n        \"\"\"\n        Enable display of debugging messages while doing pattern matching.\n        Set ``flag`` to ``True`` to enable, ``False`` to disable.\n\n        Example::\n\n            wd = Word(alphas).set_name(\"alphaword\")\n            integer = Word(nums).set_name(\"numword\")\n            term = wd | integer\n\n            # turn on debugging for wd\n            wd.set_debug()\n\n            term[1, ...].parse_string(\"abc 123 xyz 890\")\n\n        prints::\n\n            Match alphaword at loc 0(1,1)\n            Matched alphaword -> ['abc']\n            Match alphaword at loc 3(1,4)\n            Exception raised:Expected alphaword (at char 4), (line:1, col:5)\n            Match alphaword at loc 7(1,8)\n            Matched alphaword -> ['xyz']\n            Match alphaword at loc 11(1,12)\n            Exception raised:Expected alphaword (at char 12), (line:1, col:13)\n            Match alphaword at loc 15(1,16)\n            Exception raised:Expected alphaword (at char 15), (line:1, col:16)\n\n        The output shown is that produced by the default debug actions - custom debug actions can be\n        specified using :class:`set_debug_actions`. Prior to attempting\n        to match the ``wd`` expression, the debugging message ``\"Match <exprname> at loc <n>(<line>,<col>)\"``\n        is shown. Then if the parse succeeds, a ``\"Matched\"`` message is shown, or an ``\"Exception raised\"``\n        message is shown. Also note the use of :class:`set_name` to assign a human-readable name to the expression,\n        which makes debugging and exception messages easier to understand - for instance, the default\n        name created for the :class:`Word` expression without calling ``set_name`` is ``\"W:(A-Za-z)\"``.\n        \"\"\"\n        if flag:\n            self.set_debug_actions(\n                _default_start_debug_action,\n                _default_success_debug_action,\n                _default_exception_debug_action,\n            )\n        else:\n            self.debug = False\n        return self\n\n    @property\n    def default_name(self) -> str:\n        if self._defaultName is None:\n            self._defaultName = self._generateDefaultName()\n        return self._defaultName\n\n    @abstractmethod\n    def _generateDefaultName(self):\n        \"\"\"\n        Child classes must define this method, which defines how the ``default_name`` is set.\n        \"\"\"\n\n    def set_name(self, name: str) -> \"ParserElement\":\n        \"\"\"\n        Define name for this expression, makes debugging and exception messages clearer.\n        Example::\n            Word(nums).parse_string(\"ABC\")  # -> Exception: Expected W:(0-9) (at char 0), (line:1, col:1)\n            Word(nums).set_name(\"integer\").parse_string(\"ABC\")  # -> Exception: Expected integer (at char 0), (line:1, col:1)\n        \"\"\"\n        self.customName = name\n        self.errmsg = \"Expected \" + self.name\n        if __diag__.enable_debug_on_named_expressions:\n            self.set_debug()\n        return self\n\n    @property\n    def name(self) -> str:\n        # This will use a user-defined name if available, but otherwise defaults back to the auto-generated name\n        return self.customName if self.customName is not None else self.default_name\n\n    def __str__(self) -> str:\n        return self.name\n\n    def __repr__(self) -> str:\n        return str(self)\n\n    def streamline(self) -> \"ParserElement\":\n        self.streamlined = True\n        self._defaultName = None\n        return self\n\n    def recurse(self) -> Sequence[\"ParserElement\"]:\n        return []\n\n    def _checkRecursion(self, parseElementList):\n        subRecCheckList = parseElementList[:] + [self]\n        for e in self.recurse():\n            e._checkRecursion(subRecCheckList)\n\n    def validate(self, validateTrace=None) -> None:\n        \"\"\"\n        Check defined expressions for valid structure, check for infinite recursive definitions.\n        \"\"\"\n        self._checkRecursion([])\n\n    def parse_file(\n        self,\n        file_or_filename: Union[str, Path, TextIO],\n        encoding: str = \"utf-8\",\n        parse_all: bool = False,\n        *,\n        parseAll: bool = False,\n    ) -> ParseResults:\n        \"\"\"\n        Execute the parse expression on the given file or filename.\n        If a filename is specified (instead of a file object),\n        the entire file is opened, read, and closed before parsing.\n        \"\"\"\n        parseAll = parseAll or parse_all\n        try:\n            file_contents = file_or_filename.read()\n        except AttributeError:\n            with open(file_or_filename, \"r\", encoding=encoding) as f:\n                file_contents = f.read()\n        try:\n            return self.parse_string(file_contents, parseAll)\n        except ParseBaseException as exc:\n            if ParserElement.verbose_stacktrace:\n                raise\n            else:\n                # catch and re-raise exception from here, clears out pyparsing internal stack trace\n                raise exc.with_traceback(None)\n\n    def __eq__(self, other):\n        if self is other:\n            return True\n        elif isinstance(other, str_type):\n            return self.matches(other, parse_all=True)\n        elif isinstance(other, ParserElement):\n            return vars(self) == vars(other)\n        return False\n\n    def __hash__(self):\n        return id(self)\n\n    def matches(\n        self, test_string: str, parse_all: bool = True, *, parseAll: bool = True\n    ) -> bool:\n        \"\"\"\n        Method for quick testing of a parser against a test string. Good for simple\n        inline microtests of sub expressions while building up larger parser.\n\n        Parameters:\n        - ``test_string`` - to test against this expression for a match\n        - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests\n\n        Example::\n\n            expr = Word(nums)\n            assert expr.matches(\"100\")\n        \"\"\"\n        parseAll = parseAll and parse_all\n        try:\n            self.parse_string(str(test_string), parse_all=parseAll)\n            return True\n        except ParseBaseException:\n            return False\n\n    def run_tests(\n        self,\n        tests: Union[str, List[str]],\n        parse_all: bool = True,\n        comment: typing.Optional[Union[\"ParserElement\", str]] = \"#\",\n        full_dump: bool = True,\n        print_results: bool = True,\n        failure_tests: bool = False,\n        post_parse: Callable[[str, ParseResults], str] = None,\n        file: typing.Optional[TextIO] = None,\n        with_line_numbers: bool = False,\n        *,\n        parseAll: bool = True,\n        fullDump: bool = True,\n        printResults: bool = True,\n        failureTests: bool = False,\n        postParse: Callable[[str, ParseResults], str] = None,\n    ) -> Tuple[bool, List[Tuple[str, Union[ParseResults, Exception]]]]:\n        \"\"\"\n        Execute the parse expression on a series of test strings, showing each\n        test, the parsed results or where the parse failed. Quick and easy way to\n        run a parse expression against a list of sample strings.\n\n        Parameters:\n        - ``tests`` - a list of separate test strings, or a multiline string of test strings\n        - ``parse_all`` - (default= ``True``) - flag to pass to :class:`parse_string` when running tests\n        - ``comment`` - (default= ``'#'``) - expression for indicating embedded comments in the test\n          string; pass None to disable comment filtering\n        - ``full_dump`` - (default= ``True``) - dump results as list followed by results names in nested outline;\n          if False, only dump nested list\n        - ``print_results`` - (default= ``True``) prints test output to stdout\n        - ``failure_tests`` - (default= ``False``) indicates if these tests are expected to fail parsing\n        - ``post_parse`` - (default= ``None``) optional callback for successful parse results; called as\n          `fn(test_string, parse_results)` and returns a string to be added to the test output\n        - ``file`` - (default= ``None``) optional file-like object to which test output will be written;\n          if None, will default to ``sys.stdout``\n        - ``with_line_numbers`` - default= ``False``) show test strings with line and column numbers\n\n        Returns: a (success, results) tuple, where success indicates that all tests succeeded\n        (or failed if ``failure_tests`` is True), and the results contain a list of lines of each\n        test's output\n\n        Example::\n\n            number_expr = pyparsing_common.number.copy()\n\n            result = number_expr.run_tests('''\n                # unsigned integer\n                100\n                # negative integer\n                -100\n                # float with scientific notation\n                6.02e23\n                # integer with scientific notation\n                1e-12\n                ''')\n            print(\"Success\" if result[0] else \"Failed!\")\n\n            result = number_expr.run_tests('''\n                # stray character\n                100Z\n                # missing leading digit before '.'\n                -.100\n                # too many '.'\n                3.14.159\n                ''', failure_tests=True)\n            print(\"Success\" if result[0] else \"Failed!\")\n\n        prints::\n\n            # unsigned integer\n            100\n            [100]\n\n            # negative integer\n            -100\n            [-100]\n\n            # float with scientific notation\n            6.02e23\n            [6.02e+23]\n\n            # integer with scientific notation\n            1e-12\n            [1e-12]\n\n            Success\n\n            # stray character\n            100Z\n               ^\n            FAIL: Expected end of text (at char 3), (line:1, col:4)\n\n            # missing leading digit before '.'\n            -.100\n            ^\n            FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)\n\n            # too many '.'\n            3.14.159\n                ^\n            FAIL: Expected end of text (at char 4), (line:1, col:5)\n\n            Success\n\n        Each test string must be on a single line. If you want to test a string that spans multiple\n        lines, create a test like this::\n\n            expr.run_tests(r\"this is a test\\\\n of strings that spans \\\\n 3 lines\")\n\n        (Note that this is a raw string literal, you must include the leading ``'r'``.)\n        \"\"\"\n        from .testing import pyparsing_test\n\n        parseAll = parseAll and parse_all\n        fullDump = fullDump and full_dump\n        printResults = printResults and print_results\n        failureTests = failureTests or failure_tests\n        postParse = postParse or post_parse\n        if isinstance(tests, str_type):\n            line_strip = type(tests).strip\n            tests = [line_strip(test_line) for test_line in tests.rstrip().splitlines()]\n        if isinstance(comment, str_type):\n            comment = Literal(comment)\n        if file is None:\n            file = sys.stdout\n        print_ = file.write\n\n        result: Union[ParseResults, Exception]\n        allResults = []\n        comments = []\n        success = True\n        NL = Literal(r\"\\n\").add_parse_action(replace_with(\"\\n\")).ignore(quoted_string)\n        BOM = \"\\ufeff\"\n        for t in tests:\n            if comment is not None and comment.matches(t, False) or comments and not t:\n                comments.append(\n                    pyparsing_test.with_line_numbers(t) if with_line_numbers else t\n                )\n                continue\n            if not t:\n                continue\n            out = [\n                \"\\n\" + \"\\n\".join(comments) if comments else \"\",\n                pyparsing_test.with_line_numbers(t) if with_line_numbers else t,\n            ]\n            comments = []\n            try:\n                # convert newline marks to actual newlines, and strip leading BOM if present\n                t = NL.transform_string(t.lstrip(BOM))\n                result = self.parse_string(t, parse_all=parseAll)\n            except ParseBaseException as pe:\n                fatal = \"(FATAL)\" if isinstance(pe, ParseFatalException) else \"\"\n                out.append(pe.explain())\n                out.append(\"FAIL: \" + str(pe))\n                if ParserElement.verbose_stacktrace:\n                    out.extend(traceback.format_tb(pe.__traceback__))\n                success = success and failureTests\n                result = pe\n            except Exception as exc:\n                out.append(\"FAIL-EXCEPTION: {}: {}\".format(type(exc).__name__, exc))\n                if ParserElement.verbose_stacktrace:\n                    out.extend(traceback.format_tb(exc.__traceback__))\n                success = success and failureTests\n                result = exc\n            else:\n                success = success and not failureTests\n                if postParse is not None:\n                    try:\n                        pp_value = postParse(t, result)\n                        if pp_value is not None:\n                            if isinstance(pp_value, ParseResults):\n                                out.append(pp_value.dump())\n                            else:\n                                out.append(str(pp_value))\n                        else:\n                            out.append(result.dump())\n                    except Exception as e:\n                        out.append(result.dump(full=fullDump))\n                        out.append(\n                            \"{} failed: {}: {}\".format(\n                                postParse.__name__, type(e).__name__, e\n                            )\n                        )\n                else:\n                    out.append(result.dump(full=fullDump))\n            out.append(\"\")\n\n            if printResults:\n                print_(\"\\n\".join(out))\n\n            allResults.append((t, result))\n\n        return success, allResults\n\n    def create_diagram(\n        self,\n        output_html: Union[TextIO, Path, str],\n        vertical: int = 3,\n        show_results_names: bool = False,\n        show_groups: bool = False,\n        **kwargs,\n    ) -> None:\n        \"\"\"\n        Create a railroad diagram for the parser.\n\n        Parameters:\n        - output_html (str or file-like object) - output target for generated\n          diagram HTML\n        - vertical (int) - threshold for formatting multiple alternatives vertically\n          instead of horizontally (default=3)\n        - show_results_names - bool flag whether diagram should show annotations for\n          defined results names\n        - show_groups - bool flag whether groups should be highlighted with an unlabeled surrounding box\n        Additional diagram-formatting keyword arguments can also be included;\n        see railroad.Diagram class.\n        \"\"\"\n\n        try:\n            from .diagram import to_railroad, railroad_to_html\n        except ImportError as ie:\n            raise Exception(\n                \"must ``pip install pyparsing[diagrams]`` to generate parser railroad diagrams\"\n            ) from ie\n\n        self.streamline()\n\n        railroad = to_railroad(\n            self,\n            vertical=vertical,\n            show_results_names=show_results_names,\n            show_groups=show_groups,\n            diagram_kwargs=kwargs,\n        )\n        if isinstance(output_html, (str, Path)):\n            with open(output_html, \"w\", encoding=\"utf-8\") as diag_file:\n                diag_file.write(railroad_to_html(railroad))\n        else:\n            # we were passed a file-like object, just write to it\n            output_html.write(railroad_to_html(railroad))\n\n    setDefaultWhitespaceChars = set_default_whitespace_chars\n    inlineLiteralsUsing = inline_literals_using\n    setResultsName = set_results_name\n    setBreak = set_break\n    setParseAction = set_parse_action\n    addParseAction = add_parse_action\n    addCondition = add_condition\n    setFailAction = set_fail_action\n    tryParse = try_parse\n    canParseNext = can_parse_next\n    resetCache = reset_cache\n    enableLeftRecursion = enable_left_recursion\n    enablePackrat = enable_packrat\n    parseString = parse_string\n    scanString = scan_string\n    searchString = search_string\n    transformString = transform_string\n    setWhitespaceChars = set_whitespace_chars\n    parseWithTabs = parse_with_tabs\n    setDebugActions = set_debug_actions\n    setDebug = set_debug\n    defaultName = default_name\n    setName = set_name\n    parseFile = parse_file\n    runTests = run_tests\n    ignoreWhitespace = ignore_whitespace\n    leaveWhitespace = leave_whitespace\n\n\nclass _PendingSkip(ParserElement):\n    # internal placeholder class to hold a place were '...' is added to a parser element,\n    # once another ParserElement is added, this placeholder will be replaced with a SkipTo\n    def __init__(self, expr: ParserElement, must_skip: bool = False):\n        super().__init__()\n        self.anchor = expr\n        self.must_skip = must_skip\n\n    def _generateDefaultName(self):\n        return str(self.anchor + Empty()).replace(\"Empty\", \"...\")\n\n    def __add__(self, other) -> \"ParserElement\":\n        skipper = SkipTo(other).set_name(\"...\")(\"_skipped*\")\n        if self.must_skip:\n\n            def must_skip(t):\n                if not t._skipped or t._skipped.as_list() == [\"\"]:\n                    del t[0]\n                    t.pop(\"_skipped\", None)\n\n            def show_skip(t):\n                if t._skipped.as_list()[-1:] == [\"\"]:\n                    t.pop(\"_skipped\")\n                    t[\"_skipped\"] = \"missing <\" + repr(self.anchor) + \">\"\n\n            return (\n                self.anchor + skipper().add_parse_action(must_skip)\n                | skipper().add_parse_action(show_skip)\n            ) + other\n\n        return self.anchor + skipper + other\n\n    def __repr__(self):\n        return self.defaultName\n\n    def parseImpl(self, *args):\n        raise Exception(\n            \"use of `...` expression without following SkipTo target expression\"\n        )\n\n\nclass Token(ParserElement):\n    \"\"\"Abstract :class:`ParserElement` subclass, for defining atomic\n    matching patterns.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__(savelist=False)\n\n    def _generateDefaultName(self):\n        return type(self).__name__\n\n\nclass Empty(Token):\n    \"\"\"\n    An empty token, will always match.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n\n\nclass NoMatch(Token):\n    \"\"\"\n    A token that will never match.\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n        self.errmsg = \"Unmatchable token\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass Literal(Token):\n    \"\"\"\n    Token to exactly match a specified string.\n\n    Example::\n\n        Literal('blah').parse_string('blah')  # -> ['blah']\n        Literal('blah').parse_string('blahfooblah')  # -> ['blah']\n        Literal('blah').parse_string('bla')  # -> Exception: Expected \"blah\"\n\n    For case-insensitive matching, use :class:`CaselessLiteral`.\n\n    For keyword matching (force word break before and after the matched string),\n    use :class:`Keyword` or :class:`CaselessKeyword`.\n    \"\"\"\n\n    def __init__(self, match_string: str = \"\", *, matchString: str = \"\"):\n        super().__init__()\n        match_string = matchString or match_string\n        self.match = match_string\n        self.matchLen = len(match_string)\n        try:\n            self.firstMatchChar = match_string[0]\n        except IndexError:\n            raise ValueError(\"null string passed to Literal; use Empty() instead\")\n        self.errmsg = \"Expected \" + self.name\n        self.mayReturnEmpty = False\n        self.mayIndexError = False\n\n        # Performance tuning: modify __class__ to select\n        # a parseImpl optimized for single-character check\n        if self.matchLen == 1 and type(self) is Literal:\n            self.__class__ = _SingleCharLiteral\n\n    def _generateDefaultName(self):\n        return repr(self.match)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc] == self.firstMatchChar and instring.startswith(\n            self.match, loc\n        ):\n            return loc + self.matchLen, self.match\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass _SingleCharLiteral(Literal):\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc] == self.firstMatchChar:\n            return loc + 1, self.match\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nParserElement._literalStringClass = Literal\n\n\nclass Keyword(Token):\n    \"\"\"\n    Token to exactly match a specified string as a keyword, that is,\n    it must be immediately followed by a non-keyword character.  Compare\n    with :class:`Literal`:\n\n    - ``Literal(\"if\")`` will match the leading ``'if'`` in\n      ``'ifAndOnlyIf'``.\n    - ``Keyword(\"if\")`` will not; it will only match the leading\n      ``'if'`` in ``'if x=1'``, or ``'if(y==2)'``\n\n    Accepts two optional constructor arguments in addition to the\n    keyword string:\n\n    - ``identChars`` is a string of characters that would be valid\n      identifier characters, defaulting to all alphanumerics + \"_\" and\n      \"$\"\n    - ``caseless`` allows case-insensitive matching, default is ``False``.\n\n    Example::\n\n        Keyword(\"start\").parse_string(\"start\")  # -> ['start']\n        Keyword(\"start\").parse_string(\"starting\")  # -> Exception\n\n    For case-insensitive matching, use :class:`CaselessKeyword`.\n    \"\"\"\n\n    DEFAULT_KEYWORD_CHARS = alphanums + \"_$\"\n\n    def __init__(\n        self,\n        match_string: str = \"\",\n        ident_chars: typing.Optional[str] = None,\n        caseless: bool = False,\n        *,\n        matchString: str = \"\",\n        identChars: typing.Optional[str] = None,\n    ):\n        super().__init__()\n        identChars = identChars or ident_chars\n        if identChars is None:\n            identChars = Keyword.DEFAULT_KEYWORD_CHARS\n        match_string = matchString or match_string\n        self.match = match_string\n        self.matchLen = len(match_string)\n        try:\n            self.firstMatchChar = match_string[0]\n        except IndexError:\n            raise ValueError(\"null string passed to Keyword; use Empty() instead\")\n        self.errmsg = \"Expected {} {}\".format(type(self).__name__, self.name)\n        self.mayReturnEmpty = False\n        self.mayIndexError = False\n        self.caseless = caseless\n        if caseless:\n            self.caselessmatch = match_string.upper()\n            identChars = identChars.upper()\n        self.identChars = set(identChars)\n\n    def _generateDefaultName(self):\n        return repr(self.match)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        errmsg = self.errmsg\n        errloc = loc\n        if self.caseless:\n            if instring[loc : loc + self.matchLen].upper() == self.caselessmatch:\n                if loc == 0 or instring[loc - 1].upper() not in self.identChars:\n                    if (\n                        loc >= len(instring) - self.matchLen\n                        or instring[loc + self.matchLen].upper() not in self.identChars\n                    ):\n                        return loc + self.matchLen, self.match\n                    else:\n                        # followed by keyword char\n                        errmsg += \", was immediately followed by keyword character\"\n                        errloc = loc + self.matchLen\n                else:\n                    # preceded by keyword char\n                    errmsg += \", keyword was immediately preceded by keyword character\"\n                    errloc = loc - 1\n            # else no match just raise plain exception\n\n        else:\n            if (\n                instring[loc] == self.firstMatchChar\n                and self.matchLen == 1\n                or instring.startswith(self.match, loc)\n            ):\n                if loc == 0 or instring[loc - 1] not in self.identChars:\n                    if (\n                        loc >= len(instring) - self.matchLen\n                        or instring[loc + self.matchLen] not in self.identChars\n                    ):\n                        return loc + self.matchLen, self.match\n                    else:\n                        # followed by keyword char\n                        errmsg += (\n                            \", keyword was immediately followed by keyword character\"\n                        )\n                        errloc = loc + self.matchLen\n                else:\n                    # preceded by keyword char\n                    errmsg += \", keyword was immediately preceded by keyword character\"\n                    errloc = loc - 1\n            # else no match just raise plain exception\n\n        raise ParseException(instring, errloc, errmsg, self)\n\n    @staticmethod\n    def set_default_keyword_chars(chars) -> None:\n        \"\"\"\n        Overrides the default characters used by :class:`Keyword` expressions.\n        \"\"\"\n        Keyword.DEFAULT_KEYWORD_CHARS = chars\n\n    setDefaultKeywordChars = set_default_keyword_chars\n\n\nclass CaselessLiteral(Literal):\n    \"\"\"\n    Token to match a specified string, ignoring case of letters.\n    Note: the matched results will always be in the case of the given\n    match string, NOT the case of the input text.\n\n    Example::\n\n        CaselessLiteral(\"CMD\")[1, ...].parse_string(\"cmd CMD Cmd10\")\n        # -> ['CMD', 'CMD', 'CMD']\n\n    (Contrast with example for :class:`CaselessKeyword`.)\n    \"\"\"\n\n    def __init__(self, match_string: str = \"\", *, matchString: str = \"\"):\n        match_string = matchString or match_string\n        super().__init__(match_string.upper())\n        # Preserve the defining literal.\n        self.returnString = match_string\n        self.errmsg = \"Expected \" + self.name\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc : loc + self.matchLen].upper() == self.match:\n            return loc + self.matchLen, self.returnString\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass CaselessKeyword(Keyword):\n    \"\"\"\n    Caseless version of :class:`Keyword`.\n\n    Example::\n\n        CaselessKeyword(\"CMD\")[1, ...].parse_string(\"cmd CMD Cmd10\")\n        # -> ['CMD', 'CMD']\n\n    (Contrast with example for :class:`CaselessLiteral`.)\n    \"\"\"\n\n    def __init__(\n        self,\n        match_string: str = \"\",\n        ident_chars: typing.Optional[str] = None,\n        *,\n        matchString: str = \"\",\n        identChars: typing.Optional[str] = None,\n    ):\n        identChars = identChars or ident_chars\n        match_string = matchString or match_string\n        super().__init__(match_string, identChars, caseless=True)\n\n\nclass CloseMatch(Token):\n    \"\"\"A variation on :class:`Literal` which matches \"close\" matches,\n    that is, strings with at most 'n' mismatching characters.\n    :class:`CloseMatch` takes parameters:\n\n    - ``match_string`` - string to be matched\n    - ``caseless`` - a boolean indicating whether to ignore casing when comparing characters\n    - ``max_mismatches`` - (``default=1``) maximum number of\n      mismatches allowed to count as a match\n\n    The results from a successful parse will contain the matched text\n    from the input string and the following named results:\n\n    - ``mismatches`` - a list of the positions within the\n      match_string where mismatches were found\n    - ``original`` - the original match_string used to compare\n      against the input string\n\n    If ``mismatches`` is an empty list, then the match was an exact\n    match.\n\n    Example::\n\n        patt = CloseMatch(\"ATCATCGAATGGA\")\n        patt.parse_string(\"ATCATCGAAXGGA\") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']})\n        patt.parse_string(\"ATCAXCGAAXGGA\") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1)\n\n        # exact match\n        patt.parse_string(\"ATCATCGAATGGA\") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']})\n\n        # close match allowing up to 2 mismatches\n        patt = CloseMatch(\"ATCATCGAATGGA\", max_mismatches=2)\n        patt.parse_string(\"ATCAXCGAAXGGA\") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']})\n    \"\"\"\n\n    def __init__(\n        self,\n        match_string: str,\n        max_mismatches: int = None,\n        *,\n        maxMismatches: int = 1,\n        caseless=False,\n    ):\n        maxMismatches = max_mismatches if max_mismatches is not None else maxMismatches\n        super().__init__()\n        self.match_string = match_string\n        self.maxMismatches = maxMismatches\n        self.errmsg = \"Expected {!r} (with up to {} mismatches)\".format(\n            self.match_string, self.maxMismatches\n        )\n        self.caseless = caseless\n        self.mayIndexError = False\n        self.mayReturnEmpty = False\n\n    def _generateDefaultName(self):\n        return \"{}:{!r}\".format(type(self).__name__, self.match_string)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        start = loc\n        instrlen = len(instring)\n        maxloc = start + len(self.match_string)\n\n        if maxloc <= instrlen:\n            match_string = self.match_string\n            match_stringloc = 0\n            mismatches = []\n            maxMismatches = self.maxMismatches\n\n            for match_stringloc, s_m in enumerate(\n                zip(instring[loc:maxloc], match_string)\n            ):\n                src, mat = s_m\n                if self.caseless:\n                    src, mat = src.lower(), mat.lower()\n\n                if src != mat:\n                    mismatches.append(match_stringloc)\n                    if len(mismatches) > maxMismatches:\n                        break\n            else:\n                loc = start + match_stringloc + 1\n                results = ParseResults([instring[start:loc]])\n                results[\"original\"] = match_string\n                results[\"mismatches\"] = mismatches\n                return loc, results\n\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass Word(Token):\n    \"\"\"Token for matching words composed of allowed character sets.\n    Parameters:\n    - ``init_chars`` - string of all characters that should be used to\n      match as a word; \"ABC\" will match \"AAA\", \"ABAB\", \"CBAC\", etc.;\n      if ``body_chars`` is also specified, then this is the string of\n      initial characters\n    - ``body_chars`` - string of characters that\n      can be used for matching after a matched initial character as\n      given in ``init_chars``; if omitted, same as the initial characters\n      (default=``None``)\n    - ``min`` - minimum number of characters to match (default=1)\n    - ``max`` - maximum number of characters to match (default=0)\n    - ``exact`` - exact number of characters to match (default=0)\n    - ``as_keyword`` - match as a keyword (default=``False``)\n    - ``exclude_chars`` - characters that might be\n      found in the input ``body_chars`` string but which should not be\n      accepted for matching ;useful to define a word of all\n      printables except for one or two characters, for instance\n      (default=``None``)\n\n    :class:`srange` is useful for defining custom character set strings\n    for defining :class:`Word` expressions, using range notation from\n    regular expression character sets.\n\n    A common mistake is to use :class:`Word` to match a specific literal\n    string, as in ``Word(\"Address\")``. Remember that :class:`Word`\n    uses the string argument to define *sets* of matchable characters.\n    This expression would match \"Add\", \"AAA\", \"dAred\", or any other word\n    made up of the characters 'A', 'd', 'r', 'e', and 's'. To match an\n    exact literal string, use :class:`Literal` or :class:`Keyword`.\n\n    pyparsing includes helper strings for building Words:\n\n    - :class:`alphas`\n    - :class:`nums`\n    - :class:`alphanums`\n    - :class:`hexnums`\n    - :class:`alphas8bit` (alphabetic characters in ASCII range 128-255\n      - accented, tilded, umlauted, etc.)\n    - :class:`punc8bit` (non-alphabetic characters in ASCII range\n      128-255 - currency, symbols, superscripts, diacriticals, etc.)\n    - :class:`printables` (any non-whitespace character)\n\n    ``alphas``, ``nums``, and ``printables`` are also defined in several\n    Unicode sets - see :class:`pyparsing_unicode``.\n\n    Example::\n\n        # a word composed of digits\n        integer = Word(nums) # equivalent to Word(\"0123456789\") or Word(srange(\"0-9\"))\n\n        # a word with a leading capital, and zero or more lowercase\n        capital_word = Word(alphas.upper(), alphas.lower())\n\n        # hostnames are alphanumeric, with leading alpha, and '-'\n        hostname = Word(alphas, alphanums + '-')\n\n        # roman numeral (not a strict parser, accepts invalid mix of characters)\n        roman = Word(\"IVXLCDM\")\n\n        # any string of non-whitespace characters, except for ','\n        csv_value = Word(printables, exclude_chars=\",\")\n    \"\"\"\n\n    def __init__(\n        self,\n        init_chars: str = \"\",\n        body_chars: typing.Optional[str] = None,\n        min: int = 1,\n        max: int = 0,\n        exact: int = 0,\n        as_keyword: bool = False,\n        exclude_chars: typing.Optional[str] = None,\n        *,\n        initChars: typing.Optional[str] = None,\n        bodyChars: typing.Optional[str] = None,\n        asKeyword: bool = False,\n        excludeChars: typing.Optional[str] = None,\n    ):\n        initChars = initChars or init_chars\n        bodyChars = bodyChars or body_chars\n        asKeyword = asKeyword or as_keyword\n        excludeChars = excludeChars or exclude_chars\n        super().__init__()\n        if not initChars:\n            raise ValueError(\n                \"invalid {}, initChars cannot be empty string\".format(\n                    type(self).__name__\n                )\n            )\n\n        initChars = set(initChars)\n        self.initChars = initChars\n        if excludeChars:\n            excludeChars = set(excludeChars)\n            initChars -= excludeChars\n            if bodyChars:\n                bodyChars = set(bodyChars) - excludeChars\n        self.initCharsOrig = \"\".join(sorted(initChars))\n\n        if bodyChars:\n            self.bodyCharsOrig = \"\".join(sorted(bodyChars))\n            self.bodyChars = set(bodyChars)\n        else:\n            self.bodyCharsOrig = \"\".join(sorted(initChars))\n            self.bodyChars = set(initChars)\n\n        self.maxSpecified = max > 0\n\n        if min < 1:\n            raise ValueError(\n                \"cannot specify a minimum length < 1; use Opt(Word()) if zero-length word is permitted\"\n            )\n\n        self.minLen = min\n\n        if max > 0:\n            self.maxLen = max\n        else:\n            self.maxLen = _MAX_INT\n\n        if exact > 0:\n            self.maxLen = exact\n            self.minLen = exact\n\n        self.errmsg = \"Expected \" + self.name\n        self.mayIndexError = False\n        self.asKeyword = asKeyword\n\n        # see if we can make a regex for this Word\n        if \" \" not in self.initChars | self.bodyChars and (min == 1 and exact == 0):\n            if self.bodyChars == self.initChars:\n                if max == 0:\n                    repeat = \"+\"\n                elif max == 1:\n                    repeat = \"\"\n                else:\n                    repeat = \"{{{},{}}}\".format(\n                        self.minLen, \"\" if self.maxLen == _MAX_INT else self.maxLen\n                    )\n                self.reString = \"[{}]{}\".format(\n                    _collapse_string_to_ranges(self.initChars),\n                    repeat,\n                )\n            elif len(self.initChars) == 1:\n                if max == 0:\n                    repeat = \"*\"\n                else:\n                    repeat = \"{{0,{}}}\".format(max - 1)\n                self.reString = \"{}[{}]{}\".format(\n                    re.escape(self.initCharsOrig),\n                    _collapse_string_to_ranges(self.bodyChars),\n                    repeat,\n                )\n            else:\n                if max == 0:\n                    repeat = \"*\"\n                elif max == 2:\n                    repeat = \"\"\n                else:\n                    repeat = \"{{0,{}}}\".format(max - 1)\n                self.reString = \"[{}][{}]{}\".format(\n                    _collapse_string_to_ranges(self.initChars),\n                    _collapse_string_to_ranges(self.bodyChars),\n                    repeat,\n                )\n            if self.asKeyword:\n                self.reString = r\"\\b\" + self.reString + r\"\\b\"\n\n            try:\n                self.re = re.compile(self.reString)\n            except re.error:\n                self.re = None\n            else:\n                self.re_match = self.re.match\n                self.__class__ = _WordRegex\n\n    def _generateDefaultName(self):\n        def charsAsStr(s):\n            max_repr_len = 16\n            s = _collapse_string_to_ranges(s, re_escape=False)\n            if len(s) > max_repr_len:\n                return s[: max_repr_len - 3] + \"...\"\n            else:\n                return s\n\n        if self.initChars != self.bodyChars:\n            base = \"W:({}, {})\".format(\n                charsAsStr(self.initChars), charsAsStr(self.bodyChars)\n            )\n        else:\n            base = \"W:({})\".format(charsAsStr(self.initChars))\n\n        # add length specification\n        if self.minLen > 1 or self.maxLen != _MAX_INT:\n            if self.minLen == self.maxLen:\n                if self.minLen == 1:\n                    return base[2:]\n                else:\n                    return base + \"{{{}}}\".format(self.minLen)\n            elif self.maxLen == _MAX_INT:\n                return base + \"{{{},...}}\".format(self.minLen)\n            else:\n                return base + \"{{{},{}}}\".format(self.minLen, self.maxLen)\n        return base\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc] not in self.initChars:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        start = loc\n        loc += 1\n        instrlen = len(instring)\n        bodychars = self.bodyChars\n        maxloc = start + self.maxLen\n        maxloc = min(maxloc, instrlen)\n        while loc < maxloc and instring[loc] in bodychars:\n            loc += 1\n\n        throwException = False\n        if loc - start < self.minLen:\n            throwException = True\n        elif self.maxSpecified and loc < instrlen and instring[loc] in bodychars:\n            throwException = True\n        elif self.asKeyword:\n            if (\n                start > 0\n                and instring[start - 1] in bodychars\n                or loc < instrlen\n                and instring[loc] in bodychars\n            ):\n                throwException = True\n\n        if throwException:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        return loc, instring[start:loc]\n\n\nclass _WordRegex(Word):\n    def parseImpl(self, instring, loc, doActions=True):\n        result = self.re_match(instring, loc)\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        return loc, result.group()\n\n\nclass Char(_WordRegex):\n    \"\"\"A short-cut class for defining :class:`Word` ``(characters, exact=1)``,\n    when defining a match of any single character in a string of\n    characters.\n    \"\"\"\n\n    def __init__(\n        self,\n        charset: str,\n        as_keyword: bool = False,\n        exclude_chars: typing.Optional[str] = None,\n        *,\n        asKeyword: bool = False,\n        excludeChars: typing.Optional[str] = None,\n    ):\n        asKeyword = asKeyword or as_keyword\n        excludeChars = excludeChars or exclude_chars\n        super().__init__(\n            charset, exact=1, asKeyword=asKeyword, excludeChars=excludeChars\n        )\n        self.reString = \"[{}]\".format(_collapse_string_to_ranges(self.initChars))\n        if asKeyword:\n            self.reString = r\"\\b{}\\b\".format(self.reString)\n        self.re = re.compile(self.reString)\n        self.re_match = self.re.match\n\n\nclass Regex(Token):\n    r\"\"\"Token for matching strings that match a given regular\n    expression. Defined with string specifying the regular expression in\n    a form recognized by the stdlib Python  `re module <https://docs.python.org/3/library/re.html>`_.\n    If the given regex contains named groups (defined using ``(?P<name>...)``),\n    these will be preserved as named :class:`ParseResults`.\n\n    If instead of the Python stdlib ``re`` module you wish to use a different RE module\n    (such as the ``regex`` module), you can do so by building your ``Regex`` object with\n    a compiled RE that was compiled using ``regex``.\n\n    Example::\n\n        realnum = Regex(r\"[+-]?\\d+\\.\\d*\")\n        # ref: https://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression\n        roman = Regex(r\"M{0,4}(CM|CD|D?{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\")\n\n        # named fields in a regex will be returned as named results\n        date = Regex(r'(?P<year>\\d{4})-(?P<month>\\d\\d?)-(?P<day>\\d\\d?)')\n\n        # the Regex class will accept re's compiled using the regex module\n        import regex\n        parser = pp.Regex(regex.compile(r'[0-9]'))\n    \"\"\"\n\n    def __init__(\n        self,\n        pattern: Any,\n        flags: Union[re.RegexFlag, int] = 0,\n        as_group_list: bool = False,\n        as_match: bool = False,\n        *,\n        asGroupList: bool = False,\n        asMatch: bool = False,\n    ):\n        \"\"\"The parameters ``pattern`` and ``flags`` are passed\n        to the ``re.compile()`` function as-is. See the Python\n        `re module <https://docs.python.org/3/library/re.html>`_ module for an\n        explanation of the acceptable patterns and flags.\n        \"\"\"\n        super().__init__()\n        asGroupList = asGroupList or as_group_list\n        asMatch = asMatch or as_match\n\n        if isinstance(pattern, str_type):\n            if not pattern:\n                raise ValueError(\"null string passed to Regex; use Empty() instead\")\n\n            self._re = None\n            self.reString = self.pattern = pattern\n            self.flags = flags\n\n        elif hasattr(pattern, \"pattern\") and hasattr(pattern, \"match\"):\n            self._re = pattern\n            self.pattern = self.reString = pattern.pattern\n            self.flags = flags\n\n        else:\n            raise TypeError(\n                \"Regex may only be constructed with a string or a compiled RE object\"\n            )\n\n        self.errmsg = \"Expected \" + self.name\n        self.mayIndexError = False\n        self.asGroupList = asGroupList\n        self.asMatch = asMatch\n        if self.asGroupList:\n            self.parseImpl = self.parseImplAsGroupList\n        if self.asMatch:\n            self.parseImpl = self.parseImplAsMatch\n\n    @cached_property\n    def re(self):\n        if self._re:\n            return self._re\n        else:\n            try:\n                return re.compile(self.pattern, self.flags)\n            except re.error:\n                raise ValueError(\n                    \"invalid pattern ({!r}) passed to Regex\".format(self.pattern)\n                )\n\n    @cached_property\n    def re_match(self):\n        return self.re.match\n\n    @cached_property\n    def mayReturnEmpty(self):\n        return self.re_match(\"\") is not None\n\n    def _generateDefaultName(self):\n        return \"Re:({})\".format(repr(self.pattern).replace(\"\\\\\\\\\", \"\\\\\"))\n\n    def parseImpl(self, instring, loc, doActions=True):\n        result = self.re_match(instring, loc)\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        ret = ParseResults(result.group())\n        d = result.groupdict()\n        if d:\n            for k, v in d.items():\n                ret[k] = v\n        return loc, ret\n\n    def parseImplAsGroupList(self, instring, loc, doActions=True):\n        result = self.re_match(instring, loc)\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        ret = result.groups()\n        return loc, ret\n\n    def parseImplAsMatch(self, instring, loc, doActions=True):\n        result = self.re_match(instring, loc)\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        ret = result\n        return loc, ret\n\n    def sub(self, repl: str) -> ParserElement:\n        r\"\"\"\n        Return :class:`Regex` with an attached parse action to transform the parsed\n        result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_.\n\n        Example::\n\n            make_html = Regex(r\"(\\w+):(.*?):\").sub(r\"<\\1>\\2</\\1>\")\n            print(make_html.transform_string(\"h1:main title:\"))\n            # prints \"<h1>main title</h1>\"\n        \"\"\"\n        if self.asGroupList:\n            raise TypeError(\"cannot use sub() with Regex(asGroupList=True)\")\n\n        if self.asMatch and callable(repl):\n            raise TypeError(\"cannot use sub() with a callable with Regex(asMatch=True)\")\n\n        if self.asMatch:\n\n            def pa(tokens):\n                return tokens[0].expand(repl)\n\n        else:\n\n            def pa(tokens):\n                return self.re.sub(repl, tokens[0])\n\n        return self.add_parse_action(pa)\n\n\nclass QuotedString(Token):\n    r\"\"\"\n    Token for matching strings that are delimited by quoting characters.\n\n    Defined with the following parameters:\n\n    - ``quote_char`` - string of one or more characters defining the\n      quote delimiting string\n    - ``esc_char`` - character to re_escape quotes, typically backslash\n      (default= ``None``)\n    - ``esc_quote`` - special quote sequence to re_escape an embedded quote\n      string (such as SQL's ``\"\"`` to re_escape an embedded ``\"``)\n      (default= ``None``)\n    - ``multiline`` - boolean indicating whether quotes can span\n      multiple lines (default= ``False``)\n    - ``unquote_results`` - boolean indicating whether the matched text\n      should be unquoted (default= ``True``)\n    - ``end_quote_char`` - string of one or more characters defining the\n      end of the quote delimited string (default= ``None``  => same as\n      quote_char)\n    - ``convert_whitespace_escapes`` - convert escaped whitespace\n      (``'\\t'``, ``'\\n'``, etc.) to actual whitespace\n      (default= ``True``)\n\n    Example::\n\n        qs = QuotedString('\"')\n        print(qs.search_string('lsjdf \"This is the quote\" sldjf'))\n        complex_qs = QuotedString('{{', end_quote_char='}}')\n        print(complex_qs.search_string('lsjdf {{This is the \"quote\"}} sldjf'))\n        sql_qs = QuotedString('\"', esc_quote='\"\"')\n        print(sql_qs.search_string('lsjdf \"This is the quote with \"\"embedded\"\" quotes\" sldjf'))\n\n    prints::\n\n        [['This is the quote']]\n        [['This is the \"quote\"']]\n        [['This is the quote with \"embedded\" quotes']]\n    \"\"\"\n    ws_map = ((r\"\\t\", \"\\t\"), (r\"\\n\", \"\\n\"), (r\"\\f\", \"\\f\"), (r\"\\r\", \"\\r\"))\n\n    def __init__(\n        self,\n        quote_char: str = \"\",\n        esc_char: typing.Optional[str] = None,\n        esc_quote: typing.Optional[str] = None,\n        multiline: bool = False,\n        unquote_results: bool = True,\n        end_quote_char: typing.Optional[str] = None,\n        convert_whitespace_escapes: bool = True,\n        *,\n        quoteChar: str = \"\",\n        escChar: typing.Optional[str] = None,\n        escQuote: typing.Optional[str] = None,\n        unquoteResults: bool = True,\n        endQuoteChar: typing.Optional[str] = None,\n        convertWhitespaceEscapes: bool = True,\n    ):\n        super().__init__()\n        escChar = escChar or esc_char\n        escQuote = escQuote or esc_quote\n        unquoteResults = unquoteResults and unquote_results\n        endQuoteChar = endQuoteChar or end_quote_char\n        convertWhitespaceEscapes = (\n            convertWhitespaceEscapes and convert_whitespace_escapes\n        )\n        quote_char = quoteChar or quote_char\n\n        # remove white space from quote chars - wont work anyway\n        quote_char = quote_char.strip()\n        if not quote_char:\n            raise ValueError(\"quote_char cannot be the empty string\")\n\n        if endQuoteChar is None:\n            endQuoteChar = quote_char\n        else:\n            endQuoteChar = endQuoteChar.strip()\n            if not endQuoteChar:\n                raise ValueError(\"endQuoteChar cannot be the empty string\")\n\n        self.quoteChar = quote_char\n        self.quoteCharLen = len(quote_char)\n        self.firstQuoteChar = quote_char[0]\n        self.endQuoteChar = endQuoteChar\n        self.endQuoteCharLen = len(endQuoteChar)\n        self.escChar = escChar\n        self.escQuote = escQuote\n        self.unquoteResults = unquoteResults\n        self.convertWhitespaceEscapes = convertWhitespaceEscapes\n\n        sep = \"\"\n        inner_pattern = \"\"\n\n        if escQuote:\n            inner_pattern += r\"{}(?:{})\".format(sep, re.escape(escQuote))\n            sep = \"|\"\n\n        if escChar:\n            inner_pattern += r\"{}(?:{}.)\".format(sep, re.escape(escChar))\n            sep = \"|\"\n            self.escCharReplacePattern = re.escape(self.escChar) + \"(.)\"\n\n        if len(self.endQuoteChar) > 1:\n            inner_pattern += (\n                \"{}(?:\".format(sep)\n                + \"|\".join(\n                    \"(?:{}(?!{}))\".format(\n                        re.escape(self.endQuoteChar[:i]),\n                        re.escape(self.endQuoteChar[i:]),\n                    )\n                    for i in range(len(self.endQuoteChar) - 1, 0, -1)\n                )\n                + \")\"\n            )\n            sep = \"|\"\n\n        if multiline:\n            self.flags = re.MULTILINE | re.DOTALL\n            inner_pattern += r\"{}(?:[^{}{}])\".format(\n                sep,\n                _escape_regex_range_chars(self.endQuoteChar[0]),\n                (_escape_regex_range_chars(escChar) if escChar is not None else \"\"),\n            )\n        else:\n            self.flags = 0\n            inner_pattern += r\"{}(?:[^{}\\n\\r{}])\".format(\n                sep,\n                _escape_regex_range_chars(self.endQuoteChar[0]),\n                (_escape_regex_range_chars(escChar) if escChar is not None else \"\"),\n            )\n\n        self.pattern = \"\".join(\n            [\n                re.escape(self.quoteChar),\n                \"(?:\",\n                inner_pattern,\n                \")*\",\n                re.escape(self.endQuoteChar),\n            ]\n        )\n\n        try:\n            self.re = re.compile(self.pattern, self.flags)\n            self.reString = self.pattern\n            self.re_match = self.re.match\n        except re.error:\n            raise ValueError(\n                \"invalid pattern {!r} passed to Regex\".format(self.pattern)\n            )\n\n        self.errmsg = \"Expected \" + self.name\n        self.mayIndexError = False\n        self.mayReturnEmpty = True\n\n    def _generateDefaultName(self):\n        if self.quoteChar == self.endQuoteChar and isinstance(self.quoteChar, str_type):\n            return \"string enclosed in {!r}\".format(self.quoteChar)\n\n        return \"quoted string, starting with {} ending with {}\".format(\n            self.quoteChar, self.endQuoteChar\n        )\n\n    def parseImpl(self, instring, loc, doActions=True):\n        result = (\n            instring[loc] == self.firstQuoteChar\n            and self.re_match(instring, loc)\n            or None\n        )\n        if not result:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        loc = result.end()\n        ret = result.group()\n\n        if self.unquoteResults:\n\n            # strip off quotes\n            ret = ret[self.quoteCharLen : -self.endQuoteCharLen]\n\n            if isinstance(ret, str_type):\n                # replace escaped whitespace\n                if \"\\\\\" in ret and self.convertWhitespaceEscapes:\n                    for wslit, wschar in self.ws_map:\n                        ret = ret.replace(wslit, wschar)\n\n                # replace escaped characters\n                if self.escChar:\n                    ret = re.sub(self.escCharReplacePattern, r\"\\g<1>\", ret)\n\n                # replace escaped quotes\n                if self.escQuote:\n                    ret = ret.replace(self.escQuote, self.endQuoteChar)\n\n        return loc, ret\n\n\nclass CharsNotIn(Token):\n    \"\"\"Token for matching words composed of characters *not* in a given\n    set (will include whitespace in matched characters if not listed in\n    the provided exclusion set - see example). Defined with string\n    containing all disallowed characters, and an optional minimum,\n    maximum, and/or exact length.  The default value for ``min`` is\n    1 (a minimum value < 1 is not valid); the default values for\n    ``max`` and ``exact`` are 0, meaning no maximum or exact\n    length restriction.\n\n    Example::\n\n        # define a comma-separated-value as anything that is not a ','\n        csv_value = CharsNotIn(',')\n        print(delimited_list(csv_value).parse_string(\"dkls,lsdkjf,s12 34,@!#,213\"))\n\n    prints::\n\n        ['dkls', 'lsdkjf', 's12 34', '@!#', '213']\n    \"\"\"\n\n    def __init__(\n        self,\n        not_chars: str = \"\",\n        min: int = 1,\n        max: int = 0,\n        exact: int = 0,\n        *,\n        notChars: str = \"\",\n    ):\n        super().__init__()\n        self.skipWhitespace = False\n        self.notChars = not_chars or notChars\n        self.notCharsSet = set(self.notChars)\n\n        if min < 1:\n            raise ValueError(\n                \"cannot specify a minimum length < 1; use \"\n                \"Opt(CharsNotIn()) if zero-length char group is permitted\"\n            )\n\n        self.minLen = min\n\n        if max > 0:\n            self.maxLen = max\n        else:\n            self.maxLen = _MAX_INT\n\n        if exact > 0:\n            self.maxLen = exact\n            self.minLen = exact\n\n        self.errmsg = \"Expected \" + self.name\n        self.mayReturnEmpty = self.minLen == 0\n        self.mayIndexError = False\n\n    def _generateDefaultName(self):\n        not_chars_str = _collapse_string_to_ranges(self.notChars)\n        if len(not_chars_str) > 16:\n            return \"!W:({}...)\".format(self.notChars[: 16 - 3])\n        else:\n            return \"!W:({})\".format(self.notChars)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        notchars = self.notCharsSet\n        if instring[loc] in notchars:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        start = loc\n        loc += 1\n        maxlen = min(start + self.maxLen, len(instring))\n        while loc < maxlen and instring[loc] not in notchars:\n            loc += 1\n\n        if loc - start < self.minLen:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        return loc, instring[start:loc]\n\n\nclass White(Token):\n    \"\"\"Special matching class for matching whitespace.  Normally,\n    whitespace is ignored by pyparsing grammars.  This class is included\n    when some whitespace structures are significant.  Define with\n    a string containing the whitespace characters to be matched; default\n    is ``\" \\\\t\\\\r\\\\n\"``.  Also takes optional ``min``,\n    ``max``, and ``exact`` arguments, as defined for the\n    :class:`Word` class.\n    \"\"\"\n\n    whiteStrs = {\n        \" \": \"<SP>\",\n        \"\\t\": \"<TAB>\",\n        \"\\n\": \"<LF>\",\n        \"\\r\": \"<CR>\",\n        \"\\f\": \"<FF>\",\n        \"\\u00A0\": \"<NBSP>\",\n        \"\\u1680\": \"<OGHAM_SPACE_MARK>\",\n        \"\\u180E\": \"<MONGOLIAN_VOWEL_SEPARATOR>\",\n        \"\\u2000\": \"<EN_QUAD>\",\n        \"\\u2001\": \"<EM_QUAD>\",\n        \"\\u2002\": \"<EN_SPACE>\",\n        \"\\u2003\": \"<EM_SPACE>\",\n        \"\\u2004\": \"<THREE-PER-EM_SPACE>\",\n        \"\\u2005\": \"<FOUR-PER-EM_SPACE>\",\n        \"\\u2006\": \"<SIX-PER-EM_SPACE>\",\n        \"\\u2007\": \"<FIGURE_SPACE>\",\n        \"\\u2008\": \"<PUNCTUATION_SPACE>\",\n        \"\\u2009\": \"<THIN_SPACE>\",\n        \"\\u200A\": \"<HAIR_SPACE>\",\n        \"\\u200B\": \"<ZERO_WIDTH_SPACE>\",\n        \"\\u202F\": \"<NNBSP>\",\n        \"\\u205F\": \"<MMSP>\",\n        \"\\u3000\": \"<IDEOGRAPHIC_SPACE>\",\n    }\n\n    def __init__(self, ws: str = \" \\t\\r\\n\", min: int = 1, max: int = 0, exact: int = 0):\n        super().__init__()\n        self.matchWhite = ws\n        self.set_whitespace_chars(\n            \"\".join(c for c in self.whiteStrs if c not in self.matchWhite),\n            copy_defaults=True,\n        )\n        # self.leave_whitespace()\n        self.mayReturnEmpty = True\n        self.errmsg = \"Expected \" + self.name\n\n        self.minLen = min\n\n        if max > 0:\n            self.maxLen = max\n        else:\n            self.maxLen = _MAX_INT\n\n        if exact > 0:\n            self.maxLen = exact\n            self.minLen = exact\n\n    def _generateDefaultName(self):\n        return \"\".join(White.whiteStrs[c] for c in self.matchWhite)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if instring[loc] not in self.matchWhite:\n            raise ParseException(instring, loc, self.errmsg, self)\n        start = loc\n        loc += 1\n        maxloc = start + self.maxLen\n        maxloc = min(maxloc, len(instring))\n        while loc < maxloc and instring[loc] in self.matchWhite:\n            loc += 1\n\n        if loc - start < self.minLen:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        return loc, instring[start:loc]\n\n\nclass PositionToken(Token):\n    def __init__(self):\n        super().__init__()\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n\n\nclass GoToColumn(PositionToken):\n    \"\"\"Token to advance to a specific column of input text; useful for\n    tabular report scraping.\n    \"\"\"\n\n    def __init__(self, colno: int):\n        super().__init__()\n        self.col = colno\n\n    def preParse(self, instring, loc):\n        if col(loc, instring) != self.col:\n            instrlen = len(instring)\n            if self.ignoreExprs:\n                loc = self._skipIgnorables(instring, loc)\n            while (\n                loc < instrlen\n                and instring[loc].isspace()\n                and col(loc, instring) != self.col\n            ):\n                loc += 1\n        return loc\n\n    def parseImpl(self, instring, loc, doActions=True):\n        thiscol = col(loc, instring)\n        if thiscol > self.col:\n            raise ParseException(instring, loc, \"Text not in expected column\", self)\n        newloc = loc + self.col - thiscol\n        ret = instring[loc:newloc]\n        return newloc, ret\n\n\nclass LineStart(PositionToken):\n    r\"\"\"Matches if current position is at the beginning of a line within\n    the parse string\n\n    Example::\n\n        test = '''\\\n        AAA this line\n        AAA and this line\n          AAA but not this one\n        B AAA and definitely not this one\n        '''\n\n        for t in (LineStart() + 'AAA' + restOfLine).search_string(test):\n            print(t)\n\n    prints::\n\n        ['AAA', ' this line']\n        ['AAA', ' and this line']\n\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.leave_whitespace()\n        self.orig_whiteChars = set() | self.whiteChars\n        self.whiteChars.discard(\"\\n\")\n        self.skipper = Empty().set_whitespace_chars(self.whiteChars)\n        self.errmsg = \"Expected start of line\"\n\n    def preParse(self, instring, loc):\n        if loc == 0:\n            return loc\n        else:\n            ret = self.skipper.preParse(instring, loc)\n            if \"\\n\" in self.orig_whiteChars:\n                while instring[ret : ret + 1] == \"\\n\":\n                    ret = self.skipper.preParse(instring, ret + 1)\n            return ret\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if col(loc, instring) == 1:\n            return loc, []\n        raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass LineEnd(PositionToken):\n    \"\"\"Matches if current position is at the end of a line within the\n    parse string\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.whiteChars.discard(\"\\n\")\n        self.set_whitespace_chars(self.whiteChars, copy_defaults=False)\n        self.errmsg = \"Expected end of line\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc < len(instring):\n            if instring[loc] == \"\\n\":\n                return loc + 1, \"\\n\"\n            else:\n                raise ParseException(instring, loc, self.errmsg, self)\n        elif loc == len(instring):\n            return loc + 1, []\n        else:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass StringStart(PositionToken):\n    \"\"\"Matches if current position is at the beginning of the parse\n    string\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.errmsg = \"Expected start of text\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc != 0:\n            # see if entire string up to here is just whitespace and ignoreables\n            if loc != self.preParse(instring, 0):\n                raise ParseException(instring, loc, self.errmsg, self)\n        return loc, []\n\n\nclass StringEnd(PositionToken):\n    \"\"\"\n    Matches if current position is at the end of the parse string\n    \"\"\"\n\n    def __init__(self):\n        super().__init__()\n        self.errmsg = \"Expected end of text\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc < len(instring):\n            raise ParseException(instring, loc, self.errmsg, self)\n        elif loc == len(instring):\n            return loc + 1, []\n        elif loc > len(instring):\n            return loc, []\n        else:\n            raise ParseException(instring, loc, self.errmsg, self)\n\n\nclass WordStart(PositionToken):\n    \"\"\"Matches if the current position is at the beginning of a\n    :class:`Word`, and is not preceded by any character in a given\n    set of ``word_chars`` (default= ``printables``). To emulate the\n    ``\\b`` behavior of regular expressions, use\n    ``WordStart(alphanums)``. ``WordStart`` will also match at\n    the beginning of the string being parsed, or at the beginning of\n    a line.\n    \"\"\"\n\n    def __init__(self, word_chars: str = printables, *, wordChars: str = printables):\n        wordChars = word_chars if wordChars == printables else wordChars\n        super().__init__()\n        self.wordChars = set(wordChars)\n        self.errmsg = \"Not at the start of a word\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc != 0:\n            if (\n                instring[loc - 1] in self.wordChars\n                or instring[loc] not in self.wordChars\n            ):\n                raise ParseException(instring, loc, self.errmsg, self)\n        return loc, []\n\n\nclass WordEnd(PositionToken):\n    \"\"\"Matches if the current position is at the end of a :class:`Word`,\n    and is not followed by any character in a given set of ``word_chars``\n    (default= ``printables``). To emulate the ``\\b`` behavior of\n    regular expressions, use ``WordEnd(alphanums)``. ``WordEnd``\n    will also match at the end of the string being parsed, or at the end\n    of a line.\n    \"\"\"\n\n    def __init__(self, word_chars: str = printables, *, wordChars: str = printables):\n        wordChars = word_chars if wordChars == printables else wordChars\n        super().__init__()\n        self.wordChars = set(wordChars)\n        self.skipWhitespace = False\n        self.errmsg = \"Not at the end of a word\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        instrlen = len(instring)\n        if instrlen > 0 and loc < instrlen:\n            if (\n                instring[loc] in self.wordChars\n                or instring[loc - 1] not in self.wordChars\n            ):\n                raise ParseException(instring, loc, self.errmsg, self)\n        return loc, []\n\n\nclass ParseExpression(ParserElement):\n    \"\"\"Abstract subclass of ParserElement, for combining and\n    post-processing parsed tokens.\n    \"\"\"\n\n    def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False):\n        super().__init__(savelist)\n        self.exprs: List[ParserElement]\n        if isinstance(exprs, _generatorType):\n            exprs = list(exprs)\n\n        if isinstance(exprs, str_type):\n            self.exprs = [self._literalStringClass(exprs)]\n        elif isinstance(exprs, ParserElement):\n            self.exprs = [exprs]\n        elif isinstance(exprs, Iterable):\n            exprs = list(exprs)\n            # if sequence of strings provided, wrap with Literal\n            if any(isinstance(expr, str_type) for expr in exprs):\n                exprs = (\n                    self._literalStringClass(e) if isinstance(e, str_type) else e\n                    for e in exprs\n                )\n            self.exprs = list(exprs)\n        else:\n            try:\n                self.exprs = list(exprs)\n            except TypeError:\n                self.exprs = [exprs]\n        self.callPreparse = False\n\n    def recurse(self) -> Sequence[ParserElement]:\n        return self.exprs[:]\n\n    def append(self, other) -> ParserElement:\n        self.exprs.append(other)\n        self._defaultName = None\n        return self\n\n    def leave_whitespace(self, recursive: bool = True) -> ParserElement:\n        \"\"\"\n        Extends ``leave_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on\n           all contained expressions.\n        \"\"\"\n        super().leave_whitespace(recursive)\n\n        if recursive:\n            self.exprs = [e.copy() for e in self.exprs]\n            for e in self.exprs:\n                e.leave_whitespace(recursive)\n        return self\n\n    def ignore_whitespace(self, recursive: bool = True) -> ParserElement:\n        \"\"\"\n        Extends ``ignore_whitespace`` defined in base class, and also invokes ``leave_whitespace`` on\n           all contained expressions.\n        \"\"\"\n        super().ignore_whitespace(recursive)\n        if recursive:\n            self.exprs = [e.copy() for e in self.exprs]\n            for e in self.exprs:\n                e.ignore_whitespace(recursive)\n        return self\n\n    def ignore(self, other) -> ParserElement:\n        if isinstance(other, Suppress):\n            if other not in self.ignoreExprs:\n                super().ignore(other)\n                for e in self.exprs:\n                    e.ignore(self.ignoreExprs[-1])\n        else:\n            super().ignore(other)\n            for e in self.exprs:\n                e.ignore(self.ignoreExprs[-1])\n        return self\n\n    def _generateDefaultName(self):\n        return \"{}:({})\".format(self.__class__.__name__, str(self.exprs))\n\n    def streamline(self) -> ParserElement:\n        if self.streamlined:\n            return self\n\n        super().streamline()\n\n        for e in self.exprs:\n            e.streamline()\n\n        # collapse nested :class:`And`'s of the form ``And(And(And(a, b), c), d)`` to ``And(a, b, c, d)``\n        # but only if there are no parse actions or resultsNames on the nested And's\n        # (likewise for :class:`Or`'s and :class:`MatchFirst`'s)\n        if len(self.exprs) == 2:\n            other = self.exprs[0]\n            if (\n                isinstance(other, self.__class__)\n                and not other.parseAction\n                and other.resultsName is None\n                and not other.debug\n            ):\n                self.exprs = other.exprs[:] + [self.exprs[1]]\n                self._defaultName = None\n                self.mayReturnEmpty |= other.mayReturnEmpty\n                self.mayIndexError |= other.mayIndexError\n\n            other = self.exprs[-1]\n            if (\n                isinstance(other, self.__class__)\n                and not other.parseAction\n                and other.resultsName is None\n                and not other.debug\n            ):\n                self.exprs = self.exprs[:-1] + other.exprs[:]\n                self._defaultName = None\n                self.mayReturnEmpty |= other.mayReturnEmpty\n                self.mayIndexError |= other.mayIndexError\n\n        self.errmsg = \"Expected \" + str(self)\n\n        return self\n\n    def validate(self, validateTrace=None) -> None:\n        tmp = (validateTrace if validateTrace is not None else [])[:] + [self]\n        for e in self.exprs:\n            e.validate(tmp)\n        self._checkRecursion([])\n\n    def copy(self) -> ParserElement:\n        ret = super().copy()\n        ret.exprs = [e.copy() for e in self.exprs]\n        return ret\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if (\n            __diag__.warn_ungrouped_named_tokens_in_collection\n            and Diagnostics.warn_ungrouped_named_tokens_in_collection\n            not in self.suppress_warnings_\n        ):\n            for e in self.exprs:\n                if (\n                    isinstance(e, ParserElement)\n                    and e.resultsName\n                    and Diagnostics.warn_ungrouped_named_tokens_in_collection\n                    not in e.suppress_warnings_\n                ):\n                    warnings.warn(\n                        \"{}: setting results name {!r} on {} expression \"\n                        \"collides with {!r} on contained expression\".format(\n                            \"warn_ungrouped_named_tokens_in_collection\",\n                            name,\n                            type(self).__name__,\n                            e.resultsName,\n                        ),\n                        stacklevel=3,\n                    )\n\n        return super()._setResultsName(name, listAllMatches)\n\n    ignoreWhitespace = ignore_whitespace\n    leaveWhitespace = leave_whitespace\n\n\nclass And(ParseExpression):\n    \"\"\"\n    Requires all given :class:`ParseExpression` s to be found in the given order.\n    Expressions may be separated by whitespace.\n    May be constructed using the ``'+'`` operator.\n    May also be constructed using the ``'-'`` operator, which will\n    suppress backtracking.\n\n    Example::\n\n        integer = Word(nums)\n        name_expr = Word(alphas)[1, ...]\n\n        expr = And([integer(\"id\"), name_expr(\"name\"), integer(\"age\")])\n        # more easily written as:\n        expr = integer(\"id\") + name_expr(\"name\") + integer(\"age\")\n    \"\"\"\n\n    class _ErrorStop(Empty):\n        def __init__(self, *args, **kwargs):\n            super().__init__(*args, **kwargs)\n            self.leave_whitespace()\n\n        def _generateDefaultName(self):\n            return \"-\"\n\n    def __init__(\n        self, exprs_arg: typing.Iterable[ParserElement], savelist: bool = True\n    ):\n        exprs: List[ParserElement] = list(exprs_arg)\n        if exprs and Ellipsis in exprs:\n            tmp = []\n            for i, expr in enumerate(exprs):\n                if expr is Ellipsis:\n                    if i < len(exprs) - 1:\n                        skipto_arg: ParserElement = (Empty() + exprs[i + 1]).exprs[-1]\n                        tmp.append(SkipTo(skipto_arg)(\"_skipped*\"))\n                    else:\n                        raise Exception(\n                            \"cannot construct And with sequence ending in ...\"\n                        )\n                else:\n                    tmp.append(expr)\n            exprs[:] = tmp\n        super().__init__(exprs, savelist)\n        if self.exprs:\n            self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)\n            if not isinstance(self.exprs[0], White):\n                self.set_whitespace_chars(\n                    self.exprs[0].whiteChars,\n                    copy_defaults=self.exprs[0].copyDefaultWhiteChars,\n                )\n                self.skipWhitespace = self.exprs[0].skipWhitespace\n            else:\n                self.skipWhitespace = False\n        else:\n            self.mayReturnEmpty = True\n        self.callPreparse = True\n\n    def streamline(self) -> ParserElement:\n        # collapse any _PendingSkip's\n        if self.exprs:\n            if any(\n                isinstance(e, ParseExpression)\n                and e.exprs\n                and isinstance(e.exprs[-1], _PendingSkip)\n                for e in self.exprs[:-1]\n            ):\n                for i, e in enumerate(self.exprs[:-1]):\n                    if e is None:\n                        continue\n                    if (\n                        isinstance(e, ParseExpression)\n                        and e.exprs\n                        and isinstance(e.exprs[-1], _PendingSkip)\n                    ):\n                        e.exprs[-1] = e.exprs[-1] + self.exprs[i + 1]\n                        self.exprs[i + 1] = None\n                self.exprs = [e for e in self.exprs if e is not None]\n\n        super().streamline()\n\n        # link any IndentedBlocks to the prior expression\n        for prev, cur in zip(self.exprs, self.exprs[1:]):\n            # traverse cur or any first embedded expr of cur looking for an IndentedBlock\n            # (but watch out for recursive grammar)\n            seen = set()\n            while cur:\n                if id(cur) in seen:\n                    break\n                seen.add(id(cur))\n                if isinstance(cur, IndentedBlock):\n                    prev.add_parse_action(\n                        lambda s, l, t, cur_=cur: setattr(\n                            cur_, \"parent_anchor\", col(l, s)\n                        )\n                    )\n                    break\n                subs = cur.recurse()\n                cur = next(iter(subs), None)\n\n        self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        # pass False as callPreParse arg to _parse for first element, since we already\n        # pre-parsed the string as part of our And pre-parsing\n        loc, resultlist = self.exprs[0]._parse(\n            instring, loc, doActions, callPreParse=False\n        )\n        errorStop = False\n        for e in self.exprs[1:]:\n            # if isinstance(e, And._ErrorStop):\n            if type(e) is And._ErrorStop:\n                errorStop = True\n                continue\n            if errorStop:\n                try:\n                    loc, exprtokens = e._parse(instring, loc, doActions)\n                except ParseSyntaxException:\n                    raise\n                except ParseBaseException as pe:\n                    pe.__traceback__ = None\n                    raise ParseSyntaxException._from_exception(pe)\n                except IndexError:\n                    raise ParseSyntaxException(\n                        instring, len(instring), self.errmsg, self\n                    )\n            else:\n                loc, exprtokens = e._parse(instring, loc, doActions)\n            if exprtokens or exprtokens.haskeys():\n                resultlist += exprtokens\n        return loc, resultlist\n\n    def __iadd__(self, other):\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        return self.append(other)  # And([self, other])\n\n    def _checkRecursion(self, parseElementList):\n        subRecCheckList = parseElementList[:] + [self]\n        for e in self.exprs:\n            e._checkRecursion(subRecCheckList)\n            if not e.mayReturnEmpty:\n                break\n\n    def _generateDefaultName(self):\n        inner = \" \".join(str(e) for e in self.exprs)\n        # strip off redundant inner {}'s\n        while len(inner) > 1 and inner[0 :: len(inner) - 1] == \"{}\":\n            inner = inner[1:-1]\n        return \"{\" + inner + \"}\"\n\n\nclass Or(ParseExpression):\n    \"\"\"Requires that at least one :class:`ParseExpression` is found. If\n    two expressions match, the expression that matches the longest\n    string will be used. May be constructed using the ``'^'``\n    operator.\n\n    Example::\n\n        # construct Or using '^' operator\n\n        number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums))\n        print(number.search_string(\"123 3.1416 789\"))\n\n    prints::\n\n        [['123'], ['3.1416'], ['789']]\n    \"\"\"\n\n    def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False):\n        super().__init__(exprs, savelist)\n        if self.exprs:\n            self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)\n            self.skipWhitespace = all(e.skipWhitespace for e in self.exprs)\n        else:\n            self.mayReturnEmpty = True\n\n    def streamline(self) -> ParserElement:\n        super().streamline()\n        if self.exprs:\n            self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)\n            self.saveAsList = any(e.saveAsList for e in self.exprs)\n            self.skipWhitespace = all(\n                e.skipWhitespace and not isinstance(e, White) for e in self.exprs\n            )\n        else:\n            self.saveAsList = False\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        maxExcLoc = -1\n        maxException = None\n        matches = []\n        fatals = []\n        if all(e.callPreparse for e in self.exprs):\n            loc = self.preParse(instring, loc)\n        for e in self.exprs:\n            try:\n                loc2 = e.try_parse(instring, loc, raise_fatal=True)\n            except ParseFatalException as pfe:\n                pfe.__traceback__ = None\n                pfe.parserElement = e\n                fatals.append(pfe)\n                maxException = None\n                maxExcLoc = -1\n            except ParseException as err:\n                if not fatals:\n                    err.__traceback__ = None\n                    if err.loc > maxExcLoc:\n                        maxException = err\n                        maxExcLoc = err.loc\n            except IndexError:\n                if len(instring) > maxExcLoc:\n                    maxException = ParseException(\n                        instring, len(instring), e.errmsg, self\n                    )\n                    maxExcLoc = len(instring)\n            else:\n                # save match among all matches, to retry longest to shortest\n                matches.append((loc2, e))\n\n        if matches:\n            # re-evaluate all matches in descending order of length of match, in case attached actions\n            # might change whether or how much they match of the input.\n            matches.sort(key=itemgetter(0), reverse=True)\n\n            if not doActions:\n                # no further conditions or parse actions to change the selection of\n                # alternative, so the first match will be the best match\n                best_expr = matches[0][1]\n                return best_expr._parse(instring, loc, doActions)\n\n            longest = -1, None\n            for loc1, expr1 in matches:\n                if loc1 <= longest[0]:\n                    # already have a longer match than this one will deliver, we are done\n                    return longest\n\n                try:\n                    loc2, toks = expr1._parse(instring, loc, doActions)\n                except ParseException as err:\n                    err.__traceback__ = None\n                    if err.loc > maxExcLoc:\n                        maxException = err\n                        maxExcLoc = err.loc\n                else:\n                    if loc2 >= loc1:\n                        return loc2, toks\n                    # didn't match as much as before\n                    elif loc2 > longest[0]:\n                        longest = loc2, toks\n\n            if longest != (-1, None):\n                return longest\n\n        if fatals:\n            if len(fatals) > 1:\n                fatals.sort(key=lambda e: -e.loc)\n                if fatals[0].loc == fatals[1].loc:\n                    fatals.sort(key=lambda e: (-e.loc, -len(str(e.parserElement))))\n            max_fatal = fatals[0]\n            raise max_fatal\n\n        if maxException is not None:\n            maxException.msg = self.errmsg\n            raise maxException\n        else:\n            raise ParseException(\n                instring, loc, \"no defined alternatives to match\", self\n            )\n\n    def __ixor__(self, other):\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        return self.append(other)  # Or([self, other])\n\n    def _generateDefaultName(self):\n        return \"{\" + \" ^ \".join(str(e) for e in self.exprs) + \"}\"\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if (\n            __diag__.warn_multiple_tokens_in_named_alternation\n            and Diagnostics.warn_multiple_tokens_in_named_alternation\n            not in self.suppress_warnings_\n        ):\n            if any(\n                isinstance(e, And)\n                and Diagnostics.warn_multiple_tokens_in_named_alternation\n                not in e.suppress_warnings_\n                for e in self.exprs\n            ):\n                warnings.warn(\n                    \"{}: setting results name {!r} on {} expression \"\n                    \"will return a list of all parsed tokens in an And alternative, \"\n                    \"in prior versions only the first token was returned; enclose \"\n                    \"contained argument in Group\".format(\n                        \"warn_multiple_tokens_in_named_alternation\",\n                        name,\n                        type(self).__name__,\n                    ),\n                    stacklevel=3,\n                )\n\n        return super()._setResultsName(name, listAllMatches)\n\n\nclass MatchFirst(ParseExpression):\n    \"\"\"Requires that at least one :class:`ParseExpression` is found. If\n    more than one expression matches, the first one listed is the one that will\n    match. May be constructed using the ``'|'`` operator.\n\n    Example::\n\n        # construct MatchFirst using '|' operator\n\n        # watch the order of expressions to match\n        number = Word(nums) | Combine(Word(nums) + '.' + Word(nums))\n        print(number.search_string(\"123 3.1416 789\")) #  Fail! -> [['123'], ['3'], ['1416'], ['789']]\n\n        # put more selective expression first\n        number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums)\n        print(number.search_string(\"123 3.1416 789\")) #  Better -> [['123'], ['3.1416'], ['789']]\n    \"\"\"\n\n    def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = False):\n        super().__init__(exprs, savelist)\n        if self.exprs:\n            self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)\n            self.skipWhitespace = all(e.skipWhitespace for e in self.exprs)\n        else:\n            self.mayReturnEmpty = True\n\n    def streamline(self) -> ParserElement:\n        if self.streamlined:\n            return self\n\n        super().streamline()\n        if self.exprs:\n            self.saveAsList = any(e.saveAsList for e in self.exprs)\n            self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)\n            self.skipWhitespace = all(\n                e.skipWhitespace and not isinstance(e, White) for e in self.exprs\n            )\n        else:\n            self.saveAsList = False\n            self.mayReturnEmpty = True\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        maxExcLoc = -1\n        maxException = None\n\n        for e in self.exprs:\n            try:\n                return e._parse(\n                    instring,\n                    loc,\n                    doActions,\n                )\n            except ParseFatalException as pfe:\n                pfe.__traceback__ = None\n                pfe.parserElement = e\n                raise\n            except ParseException as err:\n                if err.loc > maxExcLoc:\n                    maxException = err\n                    maxExcLoc = err.loc\n            except IndexError:\n                if len(instring) > maxExcLoc:\n                    maxException = ParseException(\n                        instring, len(instring), e.errmsg, self\n                    )\n                    maxExcLoc = len(instring)\n\n        if maxException is not None:\n            maxException.msg = self.errmsg\n            raise maxException\n        else:\n            raise ParseException(\n                instring, loc, \"no defined alternatives to match\", self\n            )\n\n    def __ior__(self, other):\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        return self.append(other)  # MatchFirst([self, other])\n\n    def _generateDefaultName(self):\n        return \"{\" + \" | \".join(str(e) for e in self.exprs) + \"}\"\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if (\n            __diag__.warn_multiple_tokens_in_named_alternation\n            and Diagnostics.warn_multiple_tokens_in_named_alternation\n            not in self.suppress_warnings_\n        ):\n            if any(\n                isinstance(e, And)\n                and Diagnostics.warn_multiple_tokens_in_named_alternation\n                not in e.suppress_warnings_\n                for e in self.exprs\n            ):\n                warnings.warn(\n                    \"{}: setting results name {!r} on {} expression \"\n                    \"will return a list of all parsed tokens in an And alternative, \"\n                    \"in prior versions only the first token was returned; enclose \"\n                    \"contained argument in Group\".format(\n                        \"warn_multiple_tokens_in_named_alternation\",\n                        name,\n                        type(self).__name__,\n                    ),\n                    stacklevel=3,\n                )\n\n        return super()._setResultsName(name, listAllMatches)\n\n\nclass Each(ParseExpression):\n    \"\"\"Requires all given :class:`ParseExpression` s to be found, but in\n    any order. Expressions may be separated by whitespace.\n\n    May be constructed using the ``'&'`` operator.\n\n    Example::\n\n        color = one_of(\"RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN\")\n        shape_type = one_of(\"SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON\")\n        integer = Word(nums)\n        shape_attr = \"shape:\" + shape_type(\"shape\")\n        posn_attr = \"posn:\" + Group(integer(\"x\") + ',' + integer(\"y\"))(\"posn\")\n        color_attr = \"color:\" + color(\"color\")\n        size_attr = \"size:\" + integer(\"size\")\n\n        # use Each (using operator '&') to accept attributes in any order\n        # (shape and posn are required, color and size are optional)\n        shape_spec = shape_attr & posn_attr & Opt(color_attr) & Opt(size_attr)\n\n        shape_spec.run_tests('''\n            shape: SQUARE color: BLACK posn: 100, 120\n            shape: CIRCLE size: 50 color: BLUE posn: 50,80\n            color:GREEN size:20 shape:TRIANGLE posn:20,40\n            '''\n            )\n\n    prints::\n\n        shape: SQUARE color: BLACK posn: 100, 120\n        ['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']]\n        - color: BLACK\n        - posn: ['100', ',', '120']\n          - x: 100\n          - y: 120\n        - shape: SQUARE\n\n\n        shape: CIRCLE size: 50 color: BLUE posn: 50,80\n        ['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']]\n        - color: BLUE\n        - posn: ['50', ',', '80']\n          - x: 50\n          - y: 80\n        - shape: CIRCLE\n        - size: 50\n\n\n        color: GREEN size: 20 shape: TRIANGLE posn: 20,40\n        ['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']]\n        - color: GREEN\n        - posn: ['20', ',', '40']\n          - x: 20\n          - y: 40\n        - shape: TRIANGLE\n        - size: 20\n    \"\"\"\n\n    def __init__(self, exprs: typing.Iterable[ParserElement], savelist: bool = True):\n        super().__init__(exprs, savelist)\n        if self.exprs:\n            self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)\n        else:\n            self.mayReturnEmpty = True\n        self.skipWhitespace = True\n        self.initExprGroups = True\n        self.saveAsList = True\n\n    def streamline(self) -> ParserElement:\n        super().streamline()\n        if self.exprs:\n            self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)\n        else:\n            self.mayReturnEmpty = True\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if self.initExprGroups:\n            self.opt1map = dict(\n                (id(e.expr), e) for e in self.exprs if isinstance(e, Opt)\n            )\n            opt1 = [e.expr for e in self.exprs if isinstance(e, Opt)]\n            opt2 = [\n                e\n                for e in self.exprs\n                if e.mayReturnEmpty and not isinstance(e, (Opt, Regex, ZeroOrMore))\n            ]\n            self.optionals = opt1 + opt2\n            self.multioptionals = [\n                e.expr.set_results_name(e.resultsName, list_all_matches=True)\n                for e in self.exprs\n                if isinstance(e, _MultipleMatch)\n            ]\n            self.multirequired = [\n                e.expr.set_results_name(e.resultsName, list_all_matches=True)\n                for e in self.exprs\n                if isinstance(e, OneOrMore)\n            ]\n            self.required = [\n                e for e in self.exprs if not isinstance(e, (Opt, ZeroOrMore, OneOrMore))\n            ]\n            self.required += self.multirequired\n            self.initExprGroups = False\n\n        tmpLoc = loc\n        tmpReqd = self.required[:]\n        tmpOpt = self.optionals[:]\n        multis = self.multioptionals[:]\n        matchOrder = []\n\n        keepMatching = True\n        failed = []\n        fatals = []\n        while keepMatching:\n            tmpExprs = tmpReqd + tmpOpt + multis\n            failed.clear()\n            fatals.clear()\n            for e in tmpExprs:\n                try:\n                    tmpLoc = e.try_parse(instring, tmpLoc, raise_fatal=True)\n                except ParseFatalException as pfe:\n                    pfe.__traceback__ = None\n                    pfe.parserElement = e\n                    fatals.append(pfe)\n                    failed.append(e)\n                except ParseException:\n                    failed.append(e)\n                else:\n                    matchOrder.append(self.opt1map.get(id(e), e))\n                    if e in tmpReqd:\n                        tmpReqd.remove(e)\n                    elif e in tmpOpt:\n                        tmpOpt.remove(e)\n            if len(failed) == len(tmpExprs):\n                keepMatching = False\n\n        # look for any ParseFatalExceptions\n        if fatals:\n            if len(fatals) > 1:\n                fatals.sort(key=lambda e: -e.loc)\n                if fatals[0].loc == fatals[1].loc:\n                    fatals.sort(key=lambda e: (-e.loc, -len(str(e.parserElement))))\n            max_fatal = fatals[0]\n            raise max_fatal\n\n        if tmpReqd:\n            missing = \", \".join([str(e) for e in tmpReqd])\n            raise ParseException(\n                instring,\n                loc,\n                \"Missing one or more required elements ({})\".format(missing),\n            )\n\n        # add any unmatched Opts, in case they have default values defined\n        matchOrder += [e for e in self.exprs if isinstance(e, Opt) and e.expr in tmpOpt]\n\n        total_results = ParseResults([])\n        for e in matchOrder:\n            loc, results = e._parse(instring, loc, doActions)\n            total_results += results\n\n        return loc, total_results\n\n    def _generateDefaultName(self):\n        return \"{\" + \" & \".join(str(e) for e in self.exprs) + \"}\"\n\n\nclass ParseElementEnhance(ParserElement):\n    \"\"\"Abstract subclass of :class:`ParserElement`, for combining and\n    post-processing parsed tokens.\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str], savelist: bool = False):\n        super().__init__(savelist)\n        if isinstance(expr, str_type):\n            if issubclass(self._literalStringClass, Token):\n                expr = self._literalStringClass(expr)\n            elif issubclass(type(self), self._literalStringClass):\n                expr = Literal(expr)\n            else:\n                expr = self._literalStringClass(Literal(expr))\n        self.expr = expr\n        if expr is not None:\n            self.mayIndexError = expr.mayIndexError\n            self.mayReturnEmpty = expr.mayReturnEmpty\n            self.set_whitespace_chars(\n                expr.whiteChars, copy_defaults=expr.copyDefaultWhiteChars\n            )\n            self.skipWhitespace = expr.skipWhitespace\n            self.saveAsList = expr.saveAsList\n            self.callPreparse = expr.callPreparse\n            self.ignoreExprs.extend(expr.ignoreExprs)\n\n    def recurse(self) -> Sequence[ParserElement]:\n        return [self.expr] if self.expr is not None else []\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if self.expr is not None:\n            return self.expr._parse(instring, loc, doActions, callPreParse=False)\n        else:\n            raise ParseException(instring, loc, \"No expression defined\", self)\n\n    def leave_whitespace(self, recursive: bool = True) -> ParserElement:\n        super().leave_whitespace(recursive)\n\n        if recursive:\n            self.expr = self.expr.copy()\n            if self.expr is not None:\n                self.expr.leave_whitespace(recursive)\n        return self\n\n    def ignore_whitespace(self, recursive: bool = True) -> ParserElement:\n        super().ignore_whitespace(recursive)\n\n        if recursive:\n            self.expr = self.expr.copy()\n            if self.expr is not None:\n                self.expr.ignore_whitespace(recursive)\n        return self\n\n    def ignore(self, other) -> ParserElement:\n        if isinstance(other, Suppress):\n            if other not in self.ignoreExprs:\n                super().ignore(other)\n                if self.expr is not None:\n                    self.expr.ignore(self.ignoreExprs[-1])\n        else:\n            super().ignore(other)\n            if self.expr is not None:\n                self.expr.ignore(self.ignoreExprs[-1])\n        return self\n\n    def streamline(self) -> ParserElement:\n        super().streamline()\n        if self.expr is not None:\n            self.expr.streamline()\n        return self\n\n    def _checkRecursion(self, parseElementList):\n        if self in parseElementList:\n            raise RecursiveGrammarException(parseElementList + [self])\n        subRecCheckList = parseElementList[:] + [self]\n        if self.expr is not None:\n            self.expr._checkRecursion(subRecCheckList)\n\n    def validate(self, validateTrace=None) -> None:\n        if validateTrace is None:\n            validateTrace = []\n        tmp = validateTrace[:] + [self]\n        if self.expr is not None:\n            self.expr.validate(tmp)\n        self._checkRecursion([])\n\n    def _generateDefaultName(self):\n        return \"{}:({})\".format(self.__class__.__name__, str(self.expr))\n\n    ignoreWhitespace = ignore_whitespace\n    leaveWhitespace = leave_whitespace\n\n\nclass IndentedBlock(ParseElementEnhance):\n    \"\"\"\n    Expression to match one or more expressions at a given indentation level.\n    Useful for parsing text where structure is implied by indentation (like Python source code).\n    \"\"\"\n\n    class _Indent(Empty):\n        def __init__(self, ref_col: int):\n            super().__init__()\n            self.errmsg = \"expected indent at column {}\".format(ref_col)\n            self.add_condition(lambda s, l, t: col(l, s) == ref_col)\n\n    class _IndentGreater(Empty):\n        def __init__(self, ref_col: int):\n            super().__init__()\n            self.errmsg = \"expected indent at column greater than {}\".format(ref_col)\n            self.add_condition(lambda s, l, t: col(l, s) > ref_col)\n\n    def __init__(\n        self, expr: ParserElement, *, recursive: bool = False, grouped: bool = True\n    ):\n        super().__init__(expr, savelist=True)\n        # if recursive:\n        #     raise NotImplementedError(\"IndentedBlock with recursive is not implemented\")\n        self._recursive = recursive\n        self._grouped = grouped\n        self.parent_anchor = 1\n\n    def parseImpl(self, instring, loc, doActions=True):\n        # advance parse position to non-whitespace by using an Empty()\n        # this should be the column to be used for all subsequent indented lines\n        anchor_loc = Empty().preParse(instring, loc)\n\n        # see if self.expr matches at the current location - if not it will raise an exception\n        # and no further work is necessary\n        self.expr.try_parse(instring, anchor_loc, doActions)\n\n        indent_col = col(anchor_loc, instring)\n        peer_detect_expr = self._Indent(indent_col)\n\n        inner_expr = Empty() + peer_detect_expr + self.expr\n        if self._recursive:\n            sub_indent = self._IndentGreater(indent_col)\n            nested_block = IndentedBlock(\n                self.expr, recursive=self._recursive, grouped=self._grouped\n            )\n            nested_block.set_debug(self.debug)\n            nested_block.parent_anchor = indent_col\n            inner_expr += Opt(sub_indent + nested_block)\n\n        inner_expr.set_name(f\"inner {hex(id(inner_expr))[-4:].upper()}@{indent_col}\")\n        block = OneOrMore(inner_expr)\n\n        trailing_undent = self._Indent(self.parent_anchor) | StringEnd()\n\n        if self._grouped:\n            wrapper = Group\n        else:\n            wrapper = lambda expr: expr\n        return (wrapper(block) + Optional(trailing_undent)).parseImpl(\n            instring, anchor_loc, doActions\n        )\n\n\nclass AtStringStart(ParseElementEnhance):\n    \"\"\"Matches if expression matches at the beginning of the parse\n    string::\n\n        AtStringStart(Word(nums)).parse_string(\"123\")\n        # prints [\"123\"]\n\n        AtStringStart(Word(nums)).parse_string(\"    123\")\n        # raises ParseException\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str]):\n        super().__init__(expr)\n        self.callPreparse = False\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if loc != 0:\n            raise ParseException(instring, loc, \"not found at string start\")\n        return super().parseImpl(instring, loc, doActions)\n\n\nclass AtLineStart(ParseElementEnhance):\n    r\"\"\"Matches if an expression matches at the beginning of a line within\n    the parse string\n\n    Example::\n\n        test = '''\\\n        AAA this line\n        AAA and this line\n          AAA but not this one\n        B AAA and definitely not this one\n        '''\n\n        for t in (AtLineStart('AAA') + restOfLine).search_string(test):\n            print(t)\n\n    prints::\n\n        ['AAA', ' this line']\n        ['AAA', ' and this line']\n\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str]):\n        super().__init__(expr)\n        self.callPreparse = False\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if col(loc, instring) != 1:\n            raise ParseException(instring, loc, \"not found at line start\")\n        return super().parseImpl(instring, loc, doActions)\n\n\nclass FollowedBy(ParseElementEnhance):\n    \"\"\"Lookahead matching of the given parse expression.\n    ``FollowedBy`` does *not* advance the parsing position within\n    the input string, it only verifies that the specified parse\n    expression matches at the current position.  ``FollowedBy``\n    always returns a null token list. If any results names are defined\n    in the lookahead expression, those *will* be returned for access by\n    name.\n\n    Example::\n\n        # use FollowedBy to match a label only if it is followed by a ':'\n        data_word = Word(alphas)\n        label = data_word + FollowedBy(':')\n        attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))\n\n        attr_expr[1, ...].parse_string(\"shape: SQUARE color: BLACK posn: upper left\").pprint()\n\n    prints::\n\n        [['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']]\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str]):\n        super().__init__(expr)\n        self.mayReturnEmpty = True\n\n    def parseImpl(self, instring, loc, doActions=True):\n        # by using self._expr.parse and deleting the contents of the returned ParseResults list\n        # we keep any named results that were defined in the FollowedBy expression\n        _, ret = self.expr._parse(instring, loc, doActions=doActions)\n        del ret[:]\n\n        return loc, ret\n\n\nclass PrecededBy(ParseElementEnhance):\n    \"\"\"Lookbehind matching of the given parse expression.\n    ``PrecededBy`` does not advance the parsing position within the\n    input string, it only verifies that the specified parse expression\n    matches prior to the current position.  ``PrecededBy`` always\n    returns a null token list, but if a results name is defined on the\n    given expression, it is returned.\n\n    Parameters:\n\n    - expr - expression that must match prior to the current parse\n      location\n    - retreat - (default= ``None``) - (int) maximum number of characters\n      to lookbehind prior to the current parse location\n\n    If the lookbehind expression is a string, :class:`Literal`,\n    :class:`Keyword`, or a :class:`Word` or :class:`CharsNotIn`\n    with a specified exact or maximum length, then the retreat\n    parameter is not required. Otherwise, retreat must be specified to\n    give a maximum number of characters to look back from\n    the current parse position for a lookbehind match.\n\n    Example::\n\n        # VB-style variable names with type prefixes\n        int_var = PrecededBy(\"#\") + pyparsing_common.identifier\n        str_var = PrecededBy(\"$\") + pyparsing_common.identifier\n\n    \"\"\"\n\n    def __init__(\n        self, expr: Union[ParserElement, str], retreat: typing.Optional[int] = None\n    ):\n        super().__init__(expr)\n        self.expr = self.expr().leave_whitespace()\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n        self.exact = False\n        if isinstance(expr, str_type):\n            retreat = len(expr)\n            self.exact = True\n        elif isinstance(expr, (Literal, Keyword)):\n            retreat = expr.matchLen\n            self.exact = True\n        elif isinstance(expr, (Word, CharsNotIn)) and expr.maxLen != _MAX_INT:\n            retreat = expr.maxLen\n            self.exact = True\n        elif isinstance(expr, PositionToken):\n            retreat = 0\n            self.exact = True\n        self.retreat = retreat\n        self.errmsg = \"not preceded by \" + str(expr)\n        self.skipWhitespace = False\n        self.parseAction.append(lambda s, l, t: t.__delitem__(slice(None, None)))\n\n    def parseImpl(self, instring, loc=0, doActions=True):\n        if self.exact:\n            if loc < self.retreat:\n                raise ParseException(instring, loc, self.errmsg)\n            start = loc - self.retreat\n            _, ret = self.expr._parse(instring, start)\n        else:\n            # retreat specified a maximum lookbehind window, iterate\n            test_expr = self.expr + StringEnd()\n            instring_slice = instring[max(0, loc - self.retreat) : loc]\n            last_expr = ParseException(instring, loc, self.errmsg)\n            for offset in range(1, min(loc, self.retreat + 1) + 1):\n                try:\n                    # print('trying', offset, instring_slice, repr(instring_slice[loc - offset:]))\n                    _, ret = test_expr._parse(\n                        instring_slice, len(instring_slice) - offset\n                    )\n                except ParseBaseException as pbe:\n                    last_expr = pbe\n                else:\n                    break\n            else:\n                raise last_expr\n        return loc, ret\n\n\nclass Located(ParseElementEnhance):\n    \"\"\"\n    Decorates a returned token with its starting and ending\n    locations in the input string.\n\n    This helper adds the following results names:\n\n    - ``locn_start`` - location where matched expression begins\n    - ``locn_end`` - location where matched expression ends\n    - ``value`` - the actual parsed results\n\n    Be careful if the input text contains ``<TAB>`` characters, you\n    may want to call :class:`ParserElement.parse_with_tabs`\n\n    Example::\n\n        wd = Word(alphas)\n        for match in Located(wd).search_string(\"ljsdf123lksdjjf123lkkjj1222\"):\n            print(match)\n\n    prints::\n\n        [0, ['ljsdf'], 5]\n        [8, ['lksdjjf'], 15]\n        [18, ['lkkjj'], 23]\n\n    \"\"\"\n\n    def parseImpl(self, instring, loc, doActions=True):\n        start = loc\n        loc, tokens = self.expr._parse(instring, start, doActions, callPreParse=False)\n        ret_tokens = ParseResults([start, tokens, loc])\n        ret_tokens[\"locn_start\"] = start\n        ret_tokens[\"value\"] = tokens\n        ret_tokens[\"locn_end\"] = loc\n        if self.resultsName:\n            # must return as a list, so that the name will be attached to the complete group\n            return loc, [ret_tokens]\n        else:\n            return loc, ret_tokens\n\n\nclass NotAny(ParseElementEnhance):\n    \"\"\"\n    Lookahead to disallow matching with the given parse expression.\n    ``NotAny`` does *not* advance the parsing position within the\n    input string, it only verifies that the specified parse expression\n    does *not* match at the current position.  Also, ``NotAny`` does\n    *not* skip over leading whitespace. ``NotAny`` always returns\n    a null token list.  May be constructed using the ``'~'`` operator.\n\n    Example::\n\n        AND, OR, NOT = map(CaselessKeyword, \"AND OR NOT\".split())\n\n        # take care not to mistake keywords for identifiers\n        ident = ~(AND | OR | NOT) + Word(alphas)\n        boolean_term = Opt(NOT) + ident\n\n        # very crude boolean expression - to support parenthesis groups and\n        # operation hierarchy, use infix_notation\n        boolean_expr = boolean_term + ((AND | OR) + boolean_term)[...]\n\n        # integers that are followed by \".\" are actually floats\n        integer = Word(nums) + ~Char(\".\")\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str]):\n        super().__init__(expr)\n        # do NOT use self.leave_whitespace(), don't want to propagate to exprs\n        # self.leave_whitespace()\n        self.skipWhitespace = False\n\n        self.mayReturnEmpty = True\n        self.errmsg = \"Found unwanted token, \" + str(self.expr)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if self.expr.can_parse_next(instring, loc):\n            raise ParseException(instring, loc, self.errmsg, self)\n        return loc, []\n\n    def _generateDefaultName(self):\n        return \"~{\" + str(self.expr) + \"}\"\n\n\nclass _MultipleMatch(ParseElementEnhance):\n    def __init__(\n        self,\n        expr: ParserElement,\n        stop_on: typing.Optional[Union[ParserElement, str]] = None,\n        *,\n        stopOn: typing.Optional[Union[ParserElement, str]] = None,\n    ):\n        super().__init__(expr)\n        stopOn = stopOn or stop_on\n        self.saveAsList = True\n        ender = stopOn\n        if isinstance(ender, str_type):\n            ender = self._literalStringClass(ender)\n        self.stopOn(ender)\n\n    def stopOn(self, ender) -> ParserElement:\n        if isinstance(ender, str_type):\n            ender = self._literalStringClass(ender)\n        self.not_ender = ~ender if ender is not None else None\n        return self\n\n    def parseImpl(self, instring, loc, doActions=True):\n        self_expr_parse = self.expr._parse\n        self_skip_ignorables = self._skipIgnorables\n        check_ender = self.not_ender is not None\n        if check_ender:\n            try_not_ender = self.not_ender.tryParse\n\n        # must be at least one (but first see if we are the stopOn sentinel;\n        # if so, fail)\n        if check_ender:\n            try_not_ender(instring, loc)\n        loc, tokens = self_expr_parse(instring, loc, doActions)\n        try:\n            hasIgnoreExprs = not not self.ignoreExprs\n            while 1:\n                if check_ender:\n                    try_not_ender(instring, loc)\n                if hasIgnoreExprs:\n                    preloc = self_skip_ignorables(instring, loc)\n                else:\n                    preloc = loc\n                loc, tmptokens = self_expr_parse(instring, preloc, doActions)\n                if tmptokens or tmptokens.haskeys():\n                    tokens += tmptokens\n        except (ParseException, IndexError):\n            pass\n\n        return loc, tokens\n\n    def _setResultsName(self, name, listAllMatches=False):\n        if (\n            __diag__.warn_ungrouped_named_tokens_in_collection\n            and Diagnostics.warn_ungrouped_named_tokens_in_collection\n            not in self.suppress_warnings_\n        ):\n            for e in [self.expr] + self.expr.recurse():\n                if (\n                    isinstance(e, ParserElement)\n                    and e.resultsName\n                    and Diagnostics.warn_ungrouped_named_tokens_in_collection\n                    not in e.suppress_warnings_\n                ):\n                    warnings.warn(\n                        \"{}: setting results name {!r} on {} expression \"\n                        \"collides with {!r} on contained expression\".format(\n                            \"warn_ungrouped_named_tokens_in_collection\",\n                            name,\n                            type(self).__name__,\n                            e.resultsName,\n                        ),\n                        stacklevel=3,\n                    )\n\n        return super()._setResultsName(name, listAllMatches)\n\n\nclass OneOrMore(_MultipleMatch):\n    \"\"\"\n    Repetition of one or more of the given expression.\n\n    Parameters:\n    - expr - expression that must match one or more times\n    - stop_on - (default= ``None``) - expression for a terminating sentinel\n         (only required if the sentinel would ordinarily match the repetition\n         expression)\n\n    Example::\n\n        data_word = Word(alphas)\n        label = data_word + FollowedBy(':')\n        attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).set_parse_action(' '.join))\n\n        text = \"shape: SQUARE posn: upper left color: BLACK\"\n        attr_expr[1, ...].parse_string(text).pprint()  # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']]\n\n        # use stop_on attribute for OneOrMore to avoid reading label string as part of the data\n        attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))\n        OneOrMore(attr_expr).parse_string(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']]\n\n        # could also be written as\n        (attr_expr * (1,)).parse_string(text).pprint()\n    \"\"\"\n\n    def _generateDefaultName(self):\n        return \"{\" + str(self.expr) + \"}...\"\n\n\nclass ZeroOrMore(_MultipleMatch):\n    \"\"\"\n    Optional repetition of zero or more of the given expression.\n\n    Parameters:\n    - ``expr`` - expression that must match zero or more times\n    - ``stop_on`` - expression for a terminating sentinel\n      (only required if the sentinel would ordinarily match the repetition\n      expression) - (default= ``None``)\n\n    Example: similar to :class:`OneOrMore`\n    \"\"\"\n\n    def __init__(\n        self,\n        expr: ParserElement,\n        stop_on: typing.Optional[Union[ParserElement, str]] = None,\n        *,\n        stopOn: typing.Optional[Union[ParserElement, str]] = None,\n    ):\n        super().__init__(expr, stopOn=stopOn or stop_on)\n        self.mayReturnEmpty = True\n\n    def parseImpl(self, instring, loc, doActions=True):\n        try:\n            return super().parseImpl(instring, loc, doActions)\n        except (ParseException, IndexError):\n            return loc, ParseResults([], name=self.resultsName)\n\n    def _generateDefaultName(self):\n        return \"[\" + str(self.expr) + \"]...\"\n\n\nclass _NullToken:\n    def __bool__(self):\n        return False\n\n    def __str__(self):\n        return \"\"\n\n\nclass Opt(ParseElementEnhance):\n    \"\"\"\n    Optional matching of the given expression.\n\n    Parameters:\n    - ``expr`` - expression that must match zero or more times\n    - ``default`` (optional) - value to be returned if the optional expression is not found.\n\n    Example::\n\n        # US postal code can be a 5-digit zip, plus optional 4-digit qualifier\n        zip = Combine(Word(nums, exact=5) + Opt('-' + Word(nums, exact=4)))\n        zip.run_tests('''\n            # traditional ZIP code\n            12345\n\n            # ZIP+4 form\n            12101-0001\n\n            # invalid ZIP\n            98765-\n            ''')\n\n    prints::\n\n        # traditional ZIP code\n        12345\n        ['12345']\n\n        # ZIP+4 form\n        12101-0001\n        ['12101-0001']\n\n        # invalid ZIP\n        98765-\n             ^\n        FAIL: Expected end of text (at char 5), (line:1, col:6)\n    \"\"\"\n\n    __optionalNotMatched = _NullToken()\n\n    def __init__(\n        self, expr: Union[ParserElement, str], default: Any = __optionalNotMatched\n    ):\n        super().__init__(expr, savelist=False)\n        self.saveAsList = self.expr.saveAsList\n        self.defaultValue = default\n        self.mayReturnEmpty = True\n\n    def parseImpl(self, instring, loc, doActions=True):\n        self_expr = self.expr\n        try:\n            loc, tokens = self_expr._parse(instring, loc, doActions, callPreParse=False)\n        except (ParseException, IndexError):\n            default_value = self.defaultValue\n            if default_value is not self.__optionalNotMatched:\n                if self_expr.resultsName:\n                    tokens = ParseResults([default_value])\n                    tokens[self_expr.resultsName] = default_value\n                else:\n                    tokens = [default_value]\n            else:\n                tokens = []\n        return loc, tokens\n\n    def _generateDefaultName(self):\n        inner = str(self.expr)\n        # strip off redundant inner {}'s\n        while len(inner) > 1 and inner[0 :: len(inner) - 1] == \"{}\":\n            inner = inner[1:-1]\n        return \"[\" + inner + \"]\"\n\n\nOptional = Opt\n\n\nclass SkipTo(ParseElementEnhance):\n    \"\"\"\n    Token for skipping over all undefined text until the matched\n    expression is found.\n\n    Parameters:\n    - ``expr`` - target expression marking the end of the data to be skipped\n    - ``include`` - if ``True``, the target expression is also parsed\n      (the skipped text and target expression are returned as a 2-element\n      list) (default= ``False``).\n    - ``ignore`` - (default= ``None``) used to define grammars (typically quoted strings and\n      comments) that might contain false matches to the target expression\n    - ``fail_on`` - (default= ``None``) define expressions that are not allowed to be\n      included in the skipped test; if found before the target expression is found,\n      the :class:`SkipTo` is not a match\n\n    Example::\n\n        report = '''\n            Outstanding Issues Report - 1 Jan 2000\n\n               # | Severity | Description                               |  Days Open\n            -----+----------+-------------------------------------------+-----------\n             101 | Critical | Intermittent system crash                 |          6\n              94 | Cosmetic | Spelling error on Login ('log|n')         |         14\n              79 | Minor    | System slow when running too many reports |         47\n            '''\n        integer = Word(nums)\n        SEP = Suppress('|')\n        # use SkipTo to simply match everything up until the next SEP\n        # - ignore quoted strings, so that a '|' character inside a quoted string does not match\n        # - parse action will call token.strip() for each matched token, i.e., the description body\n        string_data = SkipTo(SEP, ignore=quoted_string)\n        string_data.set_parse_action(token_map(str.strip))\n        ticket_expr = (integer(\"issue_num\") + SEP\n                      + string_data(\"sev\") + SEP\n                      + string_data(\"desc\") + SEP\n                      + integer(\"days_open\"))\n\n        for tkt in ticket_expr.search_string(report):\n            print tkt.dump()\n\n    prints::\n\n        ['101', 'Critical', 'Intermittent system crash', '6']\n        - days_open: '6'\n        - desc: 'Intermittent system crash'\n        - issue_num: '101'\n        - sev: 'Critical'\n        ['94', 'Cosmetic', \"Spelling error on Login ('log|n')\", '14']\n        - days_open: '14'\n        - desc: \"Spelling error on Login ('log|n')\"\n        - issue_num: '94'\n        - sev: 'Cosmetic'\n        ['79', 'Minor', 'System slow when running too many reports', '47']\n        - days_open: '47'\n        - desc: 'System slow when running too many reports'\n        - issue_num: '79'\n        - sev: 'Minor'\n    \"\"\"\n\n    def __init__(\n        self,\n        other: Union[ParserElement, str],\n        include: bool = False,\n        ignore: bool = None,\n        fail_on: typing.Optional[Union[ParserElement, str]] = None,\n        *,\n        failOn: Union[ParserElement, str] = None,\n    ):\n        super().__init__(other)\n        failOn = failOn or fail_on\n        self.ignoreExpr = ignore\n        self.mayReturnEmpty = True\n        self.mayIndexError = False\n        self.includeMatch = include\n        self.saveAsList = False\n        if isinstance(failOn, str_type):\n            self.failOn = self._literalStringClass(failOn)\n        else:\n            self.failOn = failOn\n        self.errmsg = \"No match found for \" + str(self.expr)\n\n    def parseImpl(self, instring, loc, doActions=True):\n        startloc = loc\n        instrlen = len(instring)\n        self_expr_parse = self.expr._parse\n        self_failOn_canParseNext = (\n            self.failOn.canParseNext if self.failOn is not None else None\n        )\n        self_ignoreExpr_tryParse = (\n            self.ignoreExpr.tryParse if self.ignoreExpr is not None else None\n        )\n\n        tmploc = loc\n        while tmploc <= instrlen:\n            if self_failOn_canParseNext is not None:\n                # break if failOn expression matches\n                if self_failOn_canParseNext(instring, tmploc):\n                    break\n\n            if self_ignoreExpr_tryParse is not None:\n                # advance past ignore expressions\n                while 1:\n                    try:\n                        tmploc = self_ignoreExpr_tryParse(instring, tmploc)\n                    except ParseBaseException:\n                        break\n\n            try:\n                self_expr_parse(instring, tmploc, doActions=False, callPreParse=False)\n            except (ParseException, IndexError):\n                # no match, advance loc in string\n                tmploc += 1\n            else:\n                # matched skipto expr, done\n                break\n\n        else:\n            # ran off the end of the input string without matching skipto expr, fail\n            raise ParseException(instring, loc, self.errmsg, self)\n\n        # build up return values\n        loc = tmploc\n        skiptext = instring[startloc:loc]\n        skipresult = ParseResults(skiptext)\n\n        if self.includeMatch:\n            loc, mat = self_expr_parse(instring, loc, doActions, callPreParse=False)\n            skipresult += mat\n\n        return loc, skipresult\n\n\nclass Forward(ParseElementEnhance):\n    \"\"\"\n    Forward declaration of an expression to be defined later -\n    used for recursive grammars, such as algebraic infix notation.\n    When the expression is known, it is assigned to the ``Forward``\n    variable using the ``'<<'`` operator.\n\n    Note: take care when assigning to ``Forward`` not to overlook\n    precedence of operators.\n\n    Specifically, ``'|'`` has a lower precedence than ``'<<'``, so that::\n\n        fwd_expr << a | b | c\n\n    will actually be evaluated as::\n\n        (fwd_expr << a) | b | c\n\n    thereby leaving b and c out as parseable alternatives.  It is recommended that you\n    explicitly group the values inserted into the ``Forward``::\n\n        fwd_expr << (a | b | c)\n\n    Converting to use the ``'<<='`` operator instead will avoid this problem.\n\n    See :class:`ParseResults.pprint` for an example of a recursive\n    parser created using ``Forward``.\n    \"\"\"\n\n    def __init__(self, other: typing.Optional[Union[ParserElement, str]] = None):\n        self.caller_frame = traceback.extract_stack(limit=2)[0]\n        super().__init__(other, savelist=False)\n        self.lshift_line = None\n\n    def __lshift__(self, other):\n        if hasattr(self, \"caller_frame\"):\n            del self.caller_frame\n        if isinstance(other, str_type):\n            other = self._literalStringClass(other)\n        self.expr = other\n        self.mayIndexError = self.expr.mayIndexError\n        self.mayReturnEmpty = self.expr.mayReturnEmpty\n        self.set_whitespace_chars(\n            self.expr.whiteChars, copy_defaults=self.expr.copyDefaultWhiteChars\n        )\n        self.skipWhitespace = self.expr.skipWhitespace\n        self.saveAsList = self.expr.saveAsList\n        self.ignoreExprs.extend(self.expr.ignoreExprs)\n        self.lshift_line = traceback.extract_stack(limit=2)[-2]\n        return self\n\n    def __ilshift__(self, other):\n        return self << other\n\n    def __or__(self, other):\n        caller_line = traceback.extract_stack(limit=2)[-2]\n        if (\n            __diag__.warn_on_match_first_with_lshift_operator\n            and caller_line == self.lshift_line\n            and Diagnostics.warn_on_match_first_with_lshift_operator\n            not in self.suppress_warnings_\n        ):\n            warnings.warn(\n                \"using '<<' operator with '|' is probably an error, use '<<='\",\n                stacklevel=2,\n            )\n        ret = super().__or__(other)\n        return ret\n\n    def __del__(self):\n        # see if we are getting dropped because of '=' reassignment of var instead of '<<=' or '<<'\n        if (\n            self.expr is None\n            and __diag__.warn_on_assignment_to_Forward\n            and Diagnostics.warn_on_assignment_to_Forward not in self.suppress_warnings_\n        ):\n            warnings.warn_explicit(\n                \"Forward defined here but no expression attached later using '<<=' or '<<'\",\n                UserWarning,\n                filename=self.caller_frame.filename,\n                lineno=self.caller_frame.lineno,\n            )\n\n    def parseImpl(self, instring, loc, doActions=True):\n        if (\n            self.expr is None\n            and __diag__.warn_on_parse_using_empty_Forward\n            and Diagnostics.warn_on_parse_using_empty_Forward\n            not in self.suppress_warnings_\n        ):\n            # walk stack until parse_string, scan_string, search_string, or transform_string is found\n            parse_fns = [\n                \"parse_string\",\n                \"scan_string\",\n                \"search_string\",\n                \"transform_string\",\n            ]\n            tb = traceback.extract_stack(limit=200)\n            for i, frm in enumerate(reversed(tb), start=1):\n                if frm.name in parse_fns:\n                    stacklevel = i + 1\n                    break\n            else:\n                stacklevel = 2\n            warnings.warn(\n                \"Forward expression was never assigned a value, will not parse any input\",\n                stacklevel=stacklevel,\n            )\n        if not ParserElement._left_recursion_enabled:\n            return super().parseImpl(instring, loc, doActions)\n        # ## Bounded Recursion algorithm ##\n        # Recursion only needs to be processed at ``Forward`` elements, since they are\n        # the only ones that can actually refer to themselves. The general idea is\n        # to handle recursion stepwise: We start at no recursion, then recurse once,\n        # recurse twice, ..., until more recursion offers no benefit (we hit the bound).\n        #\n        # The \"trick\" here is that each ``Forward`` gets evaluated in two contexts\n        # - to *match* a specific recursion level, and\n        # - to *search* the bounded recursion level\n        # and the two run concurrently. The *search* must *match* each recursion level\n        # to find the best possible match. This is handled by a memo table, which\n        # provides the previous match to the next level match attempt.\n        #\n        # See also \"Left Recursion in Parsing Expression Grammars\", Medeiros et al.\n        #\n        # There is a complication since we not only *parse* but also *transform* via\n        # actions: We do not want to run the actions too often while expanding. Thus,\n        # we expand using `doActions=False` and only run `doActions=True` if the next\n        # recursion level is acceptable.\n        with ParserElement.recursion_lock:\n            memo = ParserElement.recursion_memos\n            try:\n                # we are parsing at a specific recursion expansion - use it as-is\n                prev_loc, prev_result = memo[loc, self, doActions]\n                if isinstance(prev_result, Exception):\n                    raise prev_result\n                return prev_loc, prev_result.copy()\n            except KeyError:\n                act_key = (loc, self, True)\n                peek_key = (loc, self, False)\n                # we are searching for the best recursion expansion - keep on improving\n                # both `doActions` cases must be tracked separately here!\n                prev_loc, prev_peek = memo[peek_key] = (\n                    loc - 1,\n                    ParseException(\n                        instring, loc, \"Forward recursion without base case\", self\n                    ),\n                )\n                if doActions:\n                    memo[act_key] = memo[peek_key]\n                while True:\n                    try:\n                        new_loc, new_peek = super().parseImpl(instring, loc, False)\n                    except ParseException:\n                        # we failed before getting any match – do not hide the error\n                        if isinstance(prev_peek, Exception):\n                            raise\n                        new_loc, new_peek = prev_loc, prev_peek\n                    # the match did not get better: we are done\n                    if new_loc <= prev_loc:\n                        if doActions:\n                            # replace the match for doActions=False as well,\n                            # in case the action did backtrack\n                            prev_loc, prev_result = memo[peek_key] = memo[act_key]\n                            del memo[peek_key], memo[act_key]\n                            return prev_loc, prev_result.copy()\n                        del memo[peek_key]\n                        return prev_loc, prev_peek.copy()\n                    # the match did get better: see if we can improve further\n                    else:\n                        if doActions:\n                            try:\n                                memo[act_key] = super().parseImpl(instring, loc, True)\n                            except ParseException as e:\n                                memo[peek_key] = memo[act_key] = (new_loc, e)\n                                raise\n                        prev_loc, prev_peek = memo[peek_key] = new_loc, new_peek\n\n    def leave_whitespace(self, recursive: bool = True) -> ParserElement:\n        self.skipWhitespace = False\n        return self\n\n    def ignore_whitespace(self, recursive: bool = True) -> ParserElement:\n        self.skipWhitespace = True\n        return self\n\n    def streamline(self) -> ParserElement:\n        if not self.streamlined:\n            self.streamlined = True\n            if self.expr is not None:\n                self.expr.streamline()\n        return self\n\n    def validate(self, validateTrace=None) -> None:\n        if validateTrace is None:\n            validateTrace = []\n\n        if self not in validateTrace:\n            tmp = validateTrace[:] + [self]\n            if self.expr is not None:\n                self.expr.validate(tmp)\n        self._checkRecursion([])\n\n    def _generateDefaultName(self):\n        # Avoid infinite recursion by setting a temporary _defaultName\n        self._defaultName = \": ...\"\n\n        # Use the string representation of main expression.\n        retString = \"...\"\n        try:\n            if self.expr is not None:\n                retString = str(self.expr)[:1000]\n            else:\n                retString = \"None\"\n        finally:\n            return self.__class__.__name__ + \": \" + retString\n\n    def copy(self) -> ParserElement:\n        if self.expr is not None:\n            return super().copy()\n        else:\n            ret = Forward()\n            ret <<= self\n            return ret\n\n    def _setResultsName(self, name, list_all_matches=False):\n        if (\n            __diag__.warn_name_set_on_empty_Forward\n            and Diagnostics.warn_name_set_on_empty_Forward\n            not in self.suppress_warnings_\n        ):\n            if self.expr is None:\n                warnings.warn(\n                    \"{}: setting results name {!r} on {} expression \"\n                    \"that has no contained expression\".format(\n                        \"warn_name_set_on_empty_Forward\", name, type(self).__name__\n                    ),\n                    stacklevel=3,\n                )\n\n        return super()._setResultsName(name, list_all_matches)\n\n    ignoreWhitespace = ignore_whitespace\n    leaveWhitespace = leave_whitespace\n\n\nclass TokenConverter(ParseElementEnhance):\n    \"\"\"\n    Abstract subclass of :class:`ParseExpression`, for converting parsed results.\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str], savelist=False):\n        super().__init__(expr)  # , savelist)\n        self.saveAsList = False\n\n\nclass Combine(TokenConverter):\n    \"\"\"Converter to concatenate all matching tokens to a single string.\n    By default, the matching patterns must also be contiguous in the\n    input string; this can be disabled by specifying\n    ``'adjacent=False'`` in the constructor.\n\n    Example::\n\n        real = Word(nums) + '.' + Word(nums)\n        print(real.parse_string('3.1416')) # -> ['3', '.', '1416']\n        # will also erroneously match the following\n        print(real.parse_string('3. 1416')) # -> ['3', '.', '1416']\n\n        real = Combine(Word(nums) + '.' + Word(nums))\n        print(real.parse_string('3.1416')) # -> ['3.1416']\n        # no match when there are internal spaces\n        print(real.parse_string('3. 1416')) # -> Exception: Expected W:(0123...)\n    \"\"\"\n\n    def __init__(\n        self,\n        expr: ParserElement,\n        join_string: str = \"\",\n        adjacent: bool = True,\n        *,\n        joinString: typing.Optional[str] = None,\n    ):\n        super().__init__(expr)\n        joinString = joinString if joinString is not None else join_string\n        # suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself\n        if adjacent:\n            self.leave_whitespace()\n        self.adjacent = adjacent\n        self.skipWhitespace = True\n        self.joinString = joinString\n        self.callPreparse = True\n\n    def ignore(self, other) -> ParserElement:\n        if self.adjacent:\n            ParserElement.ignore(self, other)\n        else:\n            super().ignore(other)\n        return self\n\n    def postParse(self, instring, loc, tokenlist):\n        retToks = tokenlist.copy()\n        del retToks[:]\n        retToks += ParseResults(\n            [\"\".join(tokenlist._asStringList(self.joinString))], modal=self.modalResults\n        )\n\n        if self.resultsName and retToks.haskeys():\n            return [retToks]\n        else:\n            return retToks\n\n\nclass Group(TokenConverter):\n    \"\"\"Converter to return the matched tokens as a list - useful for\n    returning tokens of :class:`ZeroOrMore` and :class:`OneOrMore` expressions.\n\n    The optional ``aslist`` argument when set to True will return the\n    parsed tokens as a Python list instead of a pyparsing ParseResults.\n\n    Example::\n\n        ident = Word(alphas)\n        num = Word(nums)\n        term = ident | num\n        func = ident + Opt(delimited_list(term))\n        print(func.parse_string(\"fn a, b, 100\"))\n        # -> ['fn', 'a', 'b', '100']\n\n        func = ident + Group(Opt(delimited_list(term)))\n        print(func.parse_string(\"fn a, b, 100\"))\n        # -> ['fn', ['a', 'b', '100']]\n    \"\"\"\n\n    def __init__(self, expr: ParserElement, aslist: bool = False):\n        super().__init__(expr)\n        self.saveAsList = True\n        self._asPythonList = aslist\n\n    def postParse(self, instring, loc, tokenlist):\n        if self._asPythonList:\n            return ParseResults.List(\n                tokenlist.asList()\n                if isinstance(tokenlist, ParseResults)\n                else list(tokenlist)\n            )\n        else:\n            return [tokenlist]\n\n\nclass Dict(TokenConverter):\n    \"\"\"Converter to return a repetitive expression as a list, but also\n    as a dictionary. Each element can also be referenced using the first\n    token in the expression as its key. Useful for tabular report\n    scraping when the first column can be used as a item key.\n\n    The optional ``asdict`` argument when set to True will return the\n    parsed tokens as a Python dict instead of a pyparsing ParseResults.\n\n    Example::\n\n        data_word = Word(alphas)\n        label = data_word + FollowedBy(':')\n\n        text = \"shape: SQUARE posn: upper left color: light blue texture: burlap\"\n        attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))\n\n        # print attributes as plain groups\n        print(attr_expr[1, ...].parse_string(text).dump())\n\n        # instead of OneOrMore(expr), parse using Dict(Group(expr)[1, ...]) - Dict will auto-assign names\n        result = Dict(Group(attr_expr)[1, ...]).parse_string(text)\n        print(result.dump())\n\n        # access named fields as dict entries, or output as dict\n        print(result['shape'])\n        print(result.as_dict())\n\n    prints::\n\n        ['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap']\n        [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]\n        - color: 'light blue'\n        - posn: 'upper left'\n        - shape: 'SQUARE'\n        - texture: 'burlap'\n        SQUARE\n        {'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'}\n\n    See more examples at :class:`ParseResults` of accessing fields by results name.\n    \"\"\"\n\n    def __init__(self, expr: ParserElement, asdict: bool = False):\n        super().__init__(expr)\n        self.saveAsList = True\n        self._asPythonDict = asdict\n\n    def postParse(self, instring, loc, tokenlist):\n        for i, tok in enumerate(tokenlist):\n            if len(tok) == 0:\n                continue\n\n            ikey = tok[0]\n            if isinstance(ikey, int):\n                ikey = str(ikey).strip()\n\n            if len(tok) == 1:\n                tokenlist[ikey] = _ParseResultsWithOffset(\"\", i)\n\n            elif len(tok) == 2 and not isinstance(tok[1], ParseResults):\n                tokenlist[ikey] = _ParseResultsWithOffset(tok[1], i)\n\n            else:\n                try:\n                    dictvalue = tok.copy()  # ParseResults(i)\n                except Exception:\n                    exc = TypeError(\n                        \"could not extract dict values from parsed results\"\n                        \" - Dict expression must contain Grouped expressions\"\n                    )\n                    raise exc from None\n\n                del dictvalue[0]\n\n                if len(dictvalue) != 1 or (\n                    isinstance(dictvalue, ParseResults) and dictvalue.haskeys()\n                ):\n                    tokenlist[ikey] = _ParseResultsWithOffset(dictvalue, i)\n                else:\n                    tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0], i)\n\n        if self._asPythonDict:\n            return [tokenlist.as_dict()] if self.resultsName else tokenlist.as_dict()\n        else:\n            return [tokenlist] if self.resultsName else tokenlist\n\n\nclass Suppress(TokenConverter):\n    \"\"\"Converter for ignoring the results of a parsed expression.\n\n    Example::\n\n        source = \"a, b, c,d\"\n        wd = Word(alphas)\n        wd_list1 = wd + (',' + wd)[...]\n        print(wd_list1.parse_string(source))\n\n        # often, delimiters that are useful during parsing are just in the\n        # way afterward - use Suppress to keep them out of the parsed output\n        wd_list2 = wd + (Suppress(',') + wd)[...]\n        print(wd_list2.parse_string(source))\n\n        # Skipped text (using '...') can be suppressed as well\n        source = \"lead in START relevant text END trailing text\"\n        start_marker = Keyword(\"START\")\n        end_marker = Keyword(\"END\")\n        find_body = Suppress(...) + start_marker + ... + end_marker\n        print(find_body.parse_string(source)\n\n    prints::\n\n        ['a', ',', 'b', ',', 'c', ',', 'd']\n        ['a', 'b', 'c', 'd']\n        ['START', 'relevant text ', 'END']\n\n    (See also :class:`delimited_list`.)\n    \"\"\"\n\n    def __init__(self, expr: Union[ParserElement, str], savelist: bool = False):\n        if expr is ...:\n            expr = _PendingSkip(NoMatch())\n        super().__init__(expr)\n\n    def __add__(self, other) -> \"ParserElement\":\n        if isinstance(self.expr, _PendingSkip):\n            return Suppress(SkipTo(other)) + other\n        else:\n            return super().__add__(other)\n\n    def __sub__(self, other) -> \"ParserElement\":\n        if isinstance(self.expr, _PendingSkip):\n            return Suppress(SkipTo(other)) - other\n        else:\n            return super().__sub__(other)\n\n    def postParse(self, instring, loc, tokenlist):\n        return []\n\n    def suppress(self) -> ParserElement:\n        return self\n\n\ndef trace_parse_action(f: ParseAction) -> ParseAction:\n    \"\"\"Decorator for debugging parse actions.\n\n    When the parse action is called, this decorator will print\n    ``\">> entering method-name(line:<current_source_line>, <parse_location>, <matched_tokens>)\"``.\n    When the parse action completes, the decorator will print\n    ``\"<<\"`` followed by the returned value, or any exception that the parse action raised.\n\n    Example::\n\n        wd = Word(alphas)\n\n        @trace_parse_action\n        def remove_duplicate_chars(tokens):\n            return ''.join(sorted(set(''.join(tokens))))\n\n        wds = wd[1, ...].set_parse_action(remove_duplicate_chars)\n        print(wds.parse_string(\"slkdjs sld sldd sdlf sdljf\"))\n\n    prints::\n\n        >>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {}))\n        <<leaving remove_duplicate_chars (ret: 'dfjkls')\n        ['dfjkls']\n    \"\"\"\n    f = _trim_arity(f)\n\n    def z(*paArgs):\n        thisFunc = f.__name__\n        s, l, t = paArgs[-3:]\n        if len(paArgs) > 3:\n            thisFunc = paArgs[0].__class__.__name__ + \".\" + thisFunc\n        sys.stderr.write(\n            \">>entering {}(line: {!r}, {}, {!r})\\n\".format(thisFunc, line(l, s), l, t)\n        )\n        try:\n            ret = f(*paArgs)\n        except Exception as exc:\n            sys.stderr.write(\"<<leaving {} (exception: {})\\n\".format(thisFunc, exc))\n            raise\n        sys.stderr.write(\"<<leaving {} (ret: {!r})\\n\".format(thisFunc, ret))\n        return ret\n\n    z.__name__ = f.__name__\n    return z\n\n\n# convenience constants for positional expressions\nempty = Empty().set_name(\"empty\")\nline_start = LineStart().set_name(\"line_start\")\nline_end = LineEnd().set_name(\"line_end\")\nstring_start = StringStart().set_name(\"string_start\")\nstring_end = StringEnd().set_name(\"string_end\")\n\n_escapedPunc = Word(_bslash, r\"\\[]-*.$+^?()~ \", exact=2).set_parse_action(\n    lambda s, l, t: t[0][1]\n)\n_escapedHexChar = Regex(r\"\\\\0?[xX][0-9a-fA-F]+\").set_parse_action(\n    lambda s, l, t: chr(int(t[0].lstrip(r\"\\0x\"), 16))\n)\n_escapedOctChar = Regex(r\"\\\\0[0-7]+\").set_parse_action(\n    lambda s, l, t: chr(int(t[0][1:], 8))\n)\n_singleChar = (\n    _escapedPunc | _escapedHexChar | _escapedOctChar | CharsNotIn(r\"\\]\", exact=1)\n)\n_charRange = Group(_singleChar + Suppress(\"-\") + _singleChar)\n_reBracketExpr = (\n    Literal(\"[\")\n    + Opt(\"^\").set_results_name(\"negate\")\n    + Group(OneOrMore(_charRange | _singleChar)).set_results_name(\"body\")\n    + \"]\"\n)\n\n\ndef srange(s: str) -> str:\n    r\"\"\"Helper to easily define string ranges for use in :class:`Word`\n    construction. Borrows syntax from regexp ``'[]'`` string range\n    definitions::\n\n        srange(\"[0-9]\")   -> \"0123456789\"\n        srange(\"[a-z]\")   -> \"abcdefghijklmnopqrstuvwxyz\"\n        srange(\"[a-z$_]\") -> \"abcdefghijklmnopqrstuvwxyz$_\"\n\n    The input string must be enclosed in []'s, and the returned string\n    is the expanded character set joined into a single string. The\n    values enclosed in the []'s may be:\n\n    - a single character\n    - an escaped character with a leading backslash (such as ``\\-``\n      or ``\\]``)\n    - an escaped hex character with a leading ``'\\x'``\n      (``\\x21``, which is a ``'!'`` character) (``\\0x##``\n      is also supported for backwards compatibility)\n    - an escaped octal character with a leading ``'\\0'``\n      (``\\041``, which is a ``'!'`` character)\n    - a range of any of the above, separated by a dash (``'a-z'``,\n      etc.)\n    - any combination of the above (``'aeiouy'``,\n      ``'a-zA-Z0-9_$'``, etc.)\n    \"\"\"\n    _expanded = (\n        lambda p: p\n        if not isinstance(p, ParseResults)\n        else \"\".join(chr(c) for c in range(ord(p[0]), ord(p[1]) + 1))\n    )\n    try:\n        return \"\".join(_expanded(part) for part in _reBracketExpr.parse_string(s).body)\n    except Exception:\n        return \"\"\n\n\ndef token_map(func, *args) -> ParseAction:\n    \"\"\"Helper to define a parse action by mapping a function to all\n    elements of a :class:`ParseResults` list. If any additional args are passed,\n    they are forwarded to the given function as additional arguments\n    after the token, as in\n    ``hex_integer = Word(hexnums).set_parse_action(token_map(int, 16))``,\n    which will convert the parsed data to an integer using base 16.\n\n    Example (compare the last to example in :class:`ParserElement.transform_string`::\n\n        hex_ints = Word(hexnums)[1, ...].set_parse_action(token_map(int, 16))\n        hex_ints.run_tests('''\n            00 11 22 aa FF 0a 0d 1a\n            ''')\n\n        upperword = Word(alphas).set_parse_action(token_map(str.upper))\n        upperword[1, ...].run_tests('''\n            my kingdom for a horse\n            ''')\n\n        wd = Word(alphas).set_parse_action(token_map(str.title))\n        wd[1, ...].set_parse_action(' '.join).run_tests('''\n            now is the winter of our discontent made glorious summer by this sun of york\n            ''')\n\n    prints::\n\n        00 11 22 aa FF 0a 0d 1a\n        [0, 17, 34, 170, 255, 10, 13, 26]\n\n        my kingdom for a horse\n        ['MY', 'KINGDOM', 'FOR', 'A', 'HORSE']\n\n        now is the winter of our discontent made glorious summer by this sun of york\n        ['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York']\n    \"\"\"\n\n    def pa(s, l, t):\n        return [func(tokn, *args) for tokn in t]\n\n    func_name = getattr(func, \"__name__\", getattr(func, \"__class__\").__name__)\n    pa.__name__ = func_name\n\n    return pa\n\n\ndef autoname_elements() -> None:\n    \"\"\"\n    Utility to simplify mass-naming of parser elements, for\n    generating railroad diagram with named subdiagrams.\n    \"\"\"\n    for name, var in sys._getframe().f_back.f_locals.items():\n        if isinstance(var, ParserElement) and not var.customName:\n            var.set_name(name)\n\n\ndbl_quoted_string = Combine(\n    Regex(r'\"(?:[^\"\\n\\r\\\\]|(?:\"\")|(?:\\\\(?:[^x]|x[0-9a-fA-F]+)))*') + '\"'\n).set_name(\"string enclosed in double quotes\")\n\nsgl_quoted_string = Combine(\n    Regex(r\"'(?:[^'\\n\\r\\\\]|(?:'')|(?:\\\\(?:[^x]|x[0-9a-fA-F]+)))*\") + \"'\"\n).set_name(\"string enclosed in single quotes\")\n\nquoted_string = Combine(\n    Regex(r'\"(?:[^\"\\n\\r\\\\]|(?:\"\")|(?:\\\\(?:[^x]|x[0-9a-fA-F]+)))*') + '\"'\n    | Regex(r\"'(?:[^'\\n\\r\\\\]|(?:'')|(?:\\\\(?:[^x]|x[0-9a-fA-F]+)))*\") + \"'\"\n).set_name(\"quotedString using single or double quotes\")\n\nunicode_string = Combine(\"u\" + quoted_string.copy()).set_name(\"unicode string literal\")\n\n\nalphas8bit = srange(r\"[\\0xc0-\\0xd6\\0xd8-\\0xf6\\0xf8-\\0xff]\")\npunc8bit = srange(r\"[\\0xa1-\\0xbf\\0xd7\\0xf7]\")\n\n# build list of built-in expressions, for future reference if a global default value\n# gets updated\n_builtin_exprs: List[ParserElement] = [\n    v for v in vars().values() if isinstance(v, ParserElement)\n]\n\n# backward compatibility names\ntokenMap = token_map\nconditionAsParseAction = condition_as_parse_action\nnullDebugAction = null_debug_action\nsglQuotedString = sgl_quoted_string\ndblQuotedString = dbl_quoted_string\nquotedString = quoted_string\nunicodeString = unicode_string\nlineStart = line_start\nlineEnd = line_end\nstringStart = string_start\nstringEnd = string_end\ntraceParseAction = trace_parse_action\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/pyparsing/diagram/__init__.py",
    "content": "import railroad\nimport pyparsing\nimport typing\nfrom typing import (\n    List,\n    NamedTuple,\n    Generic,\n    TypeVar,\n    Dict,\n    Callable,\n    Set,\n    Iterable,\n)\nfrom jinja2 import Template\nfrom io import StringIO\nimport inspect\n\n\njinja2_template_source = \"\"\"\\\n<!DOCTYPE html>\n<html>\n<head>\n    {% if not head %}\n        <style type=\"text/css\">\n            .railroad-heading {\n                font-family: monospace;\n            }\n        </style>\n    {% else %}\n        {{ head | safe }}\n    {% endif %}\n</head>\n<body>\n{{ body | safe }}\n{% for diagram in diagrams %}\n    <div class=\"railroad-group\">\n        <h1 class=\"railroad-heading\">{{ diagram.title }}</h1>\n        <div class=\"railroad-description\">{{ diagram.text }}</div>\n        <div class=\"railroad-svg\">\n            {{ diagram.svg }}\n        </div>\n    </div>\n{% endfor %}\n</body>\n</html>\n\"\"\"\n\ntemplate = Template(jinja2_template_source)\n\n# Note: ideally this would be a dataclass, but we're supporting Python 3.5+ so we can't do this yet\nNamedDiagram = NamedTuple(\n    \"NamedDiagram\",\n    [(\"name\", str), (\"diagram\", typing.Optional[railroad.DiagramItem]), (\"index\", int)],\n)\n\"\"\"\nA simple structure for associating a name with a railroad diagram\n\"\"\"\n\nT = TypeVar(\"T\")\n\n\nclass EachItem(railroad.Group):\n    \"\"\"\n    Custom railroad item to compose a:\n    - Group containing a\n      - OneOrMore containing a\n        - Choice of the elements in the Each\n    with the group label indicating that all must be matched\n    \"\"\"\n\n    all_label = \"[ALL]\"\n\n    def __init__(self, *items):\n        choice_item = railroad.Choice(len(items) - 1, *items)\n        one_or_more_item = railroad.OneOrMore(item=choice_item)\n        super().__init__(one_or_more_item, label=self.all_label)\n\n\nclass AnnotatedItem(railroad.Group):\n    \"\"\"\n    Simple subclass of Group that creates an annotation label\n    \"\"\"\n\n    def __init__(self, label: str, item):\n        super().__init__(item=item, label=\"[{}]\".format(label) if label else label)\n\n\nclass EditablePartial(Generic[T]):\n    \"\"\"\n    Acts like a functools.partial, but can be edited. In other words, it represents a type that hasn't yet been\n    constructed.\n    \"\"\"\n\n    # We need this here because the railroad constructors actually transform the data, so can't be called until the\n    # entire tree is assembled\n\n    def __init__(self, func: Callable[..., T], args: list, kwargs: dict):\n        self.func = func\n        self.args = args\n        self.kwargs = kwargs\n\n    @classmethod\n    def from_call(cls, func: Callable[..., T], *args, **kwargs) -> \"EditablePartial[T]\":\n        \"\"\"\n        If you call this function in the same way that you would call the constructor, it will store the arguments\n        as you expect. For example EditablePartial.from_call(Fraction, 1, 3)() == Fraction(1, 3)\n        \"\"\"\n        return EditablePartial(func=func, args=list(args), kwargs=kwargs)\n\n    @property\n    def name(self):\n        return self.kwargs[\"name\"]\n\n    def __call__(self) -> T:\n        \"\"\"\n        Evaluate the partial and return the result\n        \"\"\"\n        args = self.args.copy()\n        kwargs = self.kwargs.copy()\n\n        # This is a helpful hack to allow you to specify varargs parameters (e.g. *args) as keyword args (e.g.\n        # args=['list', 'of', 'things'])\n        arg_spec = inspect.getfullargspec(self.func)\n        if arg_spec.varargs in self.kwargs:\n            args += kwargs.pop(arg_spec.varargs)\n\n        return self.func(*args, **kwargs)\n\n\ndef railroad_to_html(diagrams: List[NamedDiagram], **kwargs) -> str:\n    \"\"\"\n    Given a list of NamedDiagram, produce a single HTML string that visualises those diagrams\n    :params kwargs: kwargs to be passed in to the template\n    \"\"\"\n    data = []\n    for diagram in diagrams:\n        if diagram.diagram is None:\n            continue\n        io = StringIO()\n        diagram.diagram.writeSvg(io.write)\n        title = diagram.name\n        if diagram.index == 0:\n            title += \" (root)\"\n        data.append({\"title\": title, \"text\": \"\", \"svg\": io.getvalue()})\n\n    return template.render(diagrams=data, **kwargs)\n\n\ndef resolve_partial(partial: \"EditablePartial[T]\") -> T:\n    \"\"\"\n    Recursively resolves a collection of Partials into whatever type they are\n    \"\"\"\n    if isinstance(partial, EditablePartial):\n        partial.args = resolve_partial(partial.args)\n        partial.kwargs = resolve_partial(partial.kwargs)\n        return partial()\n    elif isinstance(partial, list):\n        return [resolve_partial(x) for x in partial]\n    elif isinstance(partial, dict):\n        return {key: resolve_partial(x) for key, x in partial.items()}\n    else:\n        return partial\n\n\ndef to_railroad(\n    element: pyparsing.ParserElement,\n    diagram_kwargs: typing.Optional[dict] = None,\n    vertical: int = 3,\n    show_results_names: bool = False,\n    show_groups: bool = False,\n) -> List[NamedDiagram]:\n    \"\"\"\n    Convert a pyparsing element tree into a list of diagrams. This is the recommended entrypoint to diagram\n    creation if you want to access the Railroad tree before it is converted to HTML\n    :param element: base element of the parser being diagrammed\n    :param diagram_kwargs: kwargs to pass to the Diagram() constructor\n    :param vertical: (optional) - int - limit at which number of alternatives should be\n       shown vertically instead of horizontally\n    :param show_results_names - bool to indicate whether results name annotations should be\n       included in the diagram\n    :param show_groups - bool to indicate whether groups should be highlighted with an unlabeled\n       surrounding box\n    \"\"\"\n    # Convert the whole tree underneath the root\n    lookup = ConverterState(diagram_kwargs=diagram_kwargs or {})\n    _to_diagram_element(\n        element,\n        lookup=lookup,\n        parent=None,\n        vertical=vertical,\n        show_results_names=show_results_names,\n        show_groups=show_groups,\n    )\n\n    root_id = id(element)\n    # Convert the root if it hasn't been already\n    if root_id in lookup:\n        if not element.customName:\n            lookup[root_id].name = \"\"\n        lookup[root_id].mark_for_extraction(root_id, lookup, force=True)\n\n    # Now that we're finished, we can convert from intermediate structures into Railroad elements\n    diags = list(lookup.diagrams.values())\n    if len(diags) > 1:\n        # collapse out duplicate diags with the same name\n        seen = set()\n        deduped_diags = []\n        for d in diags:\n            # don't extract SkipTo elements, they are uninformative as subdiagrams\n            if d.name == \"...\":\n                continue\n            if d.name is not None and d.name not in seen:\n                seen.add(d.name)\n                deduped_diags.append(d)\n        resolved = [resolve_partial(partial) for partial in deduped_diags]\n    else:\n        # special case - if just one diagram, always display it, even if\n        # it has no name\n        resolved = [resolve_partial(partial) for partial in diags]\n    return sorted(resolved, key=lambda diag: diag.index)\n\n\ndef _should_vertical(\n    specification: int, exprs: Iterable[pyparsing.ParserElement]\n) -> bool:\n    \"\"\"\n    Returns true if we should return a vertical list of elements\n    \"\"\"\n    if specification is None:\n        return False\n    else:\n        return len(_visible_exprs(exprs)) >= specification\n\n\nclass ElementState:\n    \"\"\"\n    State recorded for an individual pyparsing Element\n    \"\"\"\n\n    # Note: this should be a dataclass, but we have to support Python 3.5\n    def __init__(\n        self,\n        element: pyparsing.ParserElement,\n        converted: EditablePartial,\n        parent: EditablePartial,\n        number: int,\n        name: str = None,\n        parent_index: typing.Optional[int] = None,\n    ):\n        #: The pyparsing element that this represents\n        self.element: pyparsing.ParserElement = element\n        #: The name of the element\n        self.name: typing.Optional[str] = name\n        #: The output Railroad element in an unconverted state\n        self.converted: EditablePartial = converted\n        #: The parent Railroad element, which we store so that we can extract this if it's duplicated\n        self.parent: EditablePartial = parent\n        #: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram\n        self.number: int = number\n        #: The index of this inside its parent\n        self.parent_index: typing.Optional[int] = parent_index\n        #: If true, we should extract this out into a subdiagram\n        self.extract: bool = False\n        #: If true, all of this element's children have been filled out\n        self.complete: bool = False\n\n    def mark_for_extraction(\n        self, el_id: int, state: \"ConverterState\", name: str = None, force: bool = False\n    ):\n        \"\"\"\n        Called when this instance has been seen twice, and thus should eventually be extracted into a sub-diagram\n        :param el_id: id of the element\n        :param state: element/diagram state tracker\n        :param name: name to use for this element's text\n        :param force: If true, force extraction now, regardless of the state of this. Only useful for extracting the\n        root element when we know we're finished\n        \"\"\"\n        self.extract = True\n\n        # Set the name\n        if not self.name:\n            if name:\n                # Allow forcing a custom name\n                self.name = name\n            elif self.element.customName:\n                self.name = self.element.customName\n            else:\n                self.name = \"\"\n\n        # Just because this is marked for extraction doesn't mean we can do it yet. We may have to wait for children\n        # to be added\n        # Also, if this is just a string literal etc, don't bother extracting it\n        if force or (self.complete and _worth_extracting(self.element)):\n            state.extract_into_diagram(el_id)\n\n\nclass ConverterState:\n    \"\"\"\n    Stores some state that persists between recursions into the element tree\n    \"\"\"\n\n    def __init__(self, diagram_kwargs: typing.Optional[dict] = None):\n        #: A dictionary mapping ParserElements to state relating to them\n        self._element_diagram_states: Dict[int, ElementState] = {}\n        #: A dictionary mapping ParserElement IDs to subdiagrams generated from them\n        self.diagrams: Dict[int, EditablePartial[NamedDiagram]] = {}\n        #: The index of the next unnamed element\n        self.unnamed_index: int = 1\n        #: The index of the next element. This is used for sorting\n        self.index: int = 0\n        #: Shared kwargs that are used to customize the construction of diagrams\n        self.diagram_kwargs: dict = diagram_kwargs or {}\n        self.extracted_diagram_names: Set[str] = set()\n\n    def __setitem__(self, key: int, value: ElementState):\n        self._element_diagram_states[key] = value\n\n    def __getitem__(self, key: int) -> ElementState:\n        return self._element_diagram_states[key]\n\n    def __delitem__(self, key: int):\n        del self._element_diagram_states[key]\n\n    def __contains__(self, key: int):\n        return key in self._element_diagram_states\n\n    def generate_unnamed(self) -> int:\n        \"\"\"\n        Generate a number used in the name of an otherwise unnamed diagram\n        \"\"\"\n        self.unnamed_index += 1\n        return self.unnamed_index\n\n    def generate_index(self) -> int:\n        \"\"\"\n        Generate a number used to index a diagram\n        \"\"\"\n        self.index += 1\n        return self.index\n\n    def extract_into_diagram(self, el_id: int):\n        \"\"\"\n        Used when we encounter the same token twice in the same tree. When this\n        happens, we replace all instances of that token with a terminal, and\n        create a new subdiagram for the token\n        \"\"\"\n        position = self[el_id]\n\n        # Replace the original definition of this element with a regular block\n        if position.parent:\n            ret = EditablePartial.from_call(railroad.NonTerminal, text=position.name)\n            if \"item\" in position.parent.kwargs:\n                position.parent.kwargs[\"item\"] = ret\n            elif \"items\" in position.parent.kwargs:\n                position.parent.kwargs[\"items\"][position.parent_index] = ret\n\n        # If the element we're extracting is a group, skip to its content but keep the title\n        if position.converted.func == railroad.Group:\n            content = position.converted.kwargs[\"item\"]\n        else:\n            content = position.converted\n\n        self.diagrams[el_id] = EditablePartial.from_call(\n            NamedDiagram,\n            name=position.name,\n            diagram=EditablePartial.from_call(\n                railroad.Diagram, content, **self.diagram_kwargs\n            ),\n            index=position.number,\n        )\n\n        del self[el_id]\n\n\ndef _worth_extracting(element: pyparsing.ParserElement) -> bool:\n    \"\"\"\n    Returns true if this element is worth having its own sub-diagram. Simply, if any of its children\n    themselves have children, then its complex enough to extract\n    \"\"\"\n    children = element.recurse()\n    return any(child.recurse() for child in children)\n\n\ndef _apply_diagram_item_enhancements(fn):\n    \"\"\"\n    decorator to ensure enhancements to a diagram item (such as results name annotations)\n    get applied on return from _to_diagram_element (we do this since there are several\n    returns in _to_diagram_element)\n    \"\"\"\n\n    def _inner(\n        element: pyparsing.ParserElement,\n        parent: typing.Optional[EditablePartial],\n        lookup: ConverterState = None,\n        vertical: int = None,\n        index: int = 0,\n        name_hint: str = None,\n        show_results_names: bool = False,\n        show_groups: bool = False,\n    ) -> typing.Optional[EditablePartial]:\n\n        ret = fn(\n            element,\n            parent,\n            lookup,\n            vertical,\n            index,\n            name_hint,\n            show_results_names,\n            show_groups,\n        )\n\n        # apply annotation for results name, if present\n        if show_results_names and ret is not None:\n            element_results_name = element.resultsName\n            if element_results_name:\n                # add \"*\" to indicate if this is a \"list all results\" name\n                element_results_name += \"\" if element.modalResults else \"*\"\n                ret = EditablePartial.from_call(\n                    railroad.Group, item=ret, label=element_results_name\n                )\n\n        return ret\n\n    return _inner\n\n\ndef _visible_exprs(exprs: Iterable[pyparsing.ParserElement]):\n    non_diagramming_exprs = (\n        pyparsing.ParseElementEnhance,\n        pyparsing.PositionToken,\n        pyparsing.And._ErrorStop,\n    )\n    return [\n        e\n        for e in exprs\n        if not (e.customName or e.resultsName or isinstance(e, non_diagramming_exprs))\n    ]\n\n\n@_apply_diagram_item_enhancements\ndef _to_diagram_element(\n    element: pyparsing.ParserElement,\n    parent: typing.Optional[EditablePartial],\n    lookup: ConverterState = None,\n    vertical: int = None,\n    index: int = 0,\n    name_hint: str = None,\n    show_results_names: bool = False,\n    show_groups: bool = False,\n) -> typing.Optional[EditablePartial]:\n    \"\"\"\n    Recursively converts a PyParsing Element to a railroad Element\n    :param lookup: The shared converter state that keeps track of useful things\n    :param index: The index of this element within the parent\n    :param parent: The parent of this element in the output tree\n    :param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default),\n    it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never\n    do so\n    :param name_hint: If provided, this will override the generated name\n    :param show_results_names: bool flag indicating whether to add annotations for results names\n    :returns: The converted version of the input element, but as a Partial that hasn't yet been constructed\n    :param show_groups: bool flag indicating whether to show groups using bounding box\n    \"\"\"\n    exprs = element.recurse()\n    name = name_hint or element.customName or element.__class__.__name__\n\n    # Python's id() is used to provide a unique identifier for elements\n    el_id = id(element)\n\n    element_results_name = element.resultsName\n\n    # Here we basically bypass processing certain wrapper elements if they contribute nothing to the diagram\n    if not element.customName:\n        if isinstance(\n            element,\n            (\n                # pyparsing.TokenConverter,\n                # pyparsing.Forward,\n                pyparsing.Located,\n            ),\n        ):\n            # However, if this element has a useful custom name, and its child does not, we can pass it on to the child\n            if exprs:\n                if not exprs[0].customName:\n                    propagated_name = name\n                else:\n                    propagated_name = None\n\n                return _to_diagram_element(\n                    element.expr,\n                    parent=parent,\n                    lookup=lookup,\n                    vertical=vertical,\n                    index=index,\n                    name_hint=propagated_name,\n                    show_results_names=show_results_names,\n                    show_groups=show_groups,\n                )\n\n    # If the element isn't worth extracting, we always treat it as the first time we say it\n    if _worth_extracting(element):\n        if el_id in lookup:\n            # If we've seen this element exactly once before, we are only just now finding out that it's a duplicate,\n            # so we have to extract it into a new diagram.\n            looked_up = lookup[el_id]\n            looked_up.mark_for_extraction(el_id, lookup, name=name_hint)\n            ret = EditablePartial.from_call(railroad.NonTerminal, text=looked_up.name)\n            return ret\n\n        elif el_id in lookup.diagrams:\n            # If we have seen the element at least twice before, and have already extracted it into a subdiagram, we\n            # just put in a marker element that refers to the sub-diagram\n            ret = EditablePartial.from_call(\n                railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs[\"name\"]\n            )\n            return ret\n\n    # Recursively convert child elements\n    # Here we find the most relevant Railroad element for matching pyparsing Element\n    # We use ``items=[]`` here to hold the place for where the child elements will go once created\n    if isinstance(element, pyparsing.And):\n        # detect And's created with ``expr*N`` notation - for these use a OneOrMore with a repeat\n        # (all will have the same name, and resultsName)\n        if not exprs:\n            return None\n        if len(set((e.name, e.resultsName) for e in exprs)) == 1:\n            ret = EditablePartial.from_call(\n                railroad.OneOrMore, item=\"\", repeat=str(len(exprs))\n            )\n        elif _should_vertical(vertical, exprs):\n            ret = EditablePartial.from_call(railroad.Stack, items=[])\n        else:\n            ret = EditablePartial.from_call(railroad.Sequence, items=[])\n    elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)):\n        if not exprs:\n            return None\n        if _should_vertical(vertical, exprs):\n            ret = EditablePartial.from_call(railroad.Choice, 0, items=[])\n        else:\n            ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[])\n    elif isinstance(element, pyparsing.Each):\n        if not exprs:\n            return None\n        ret = EditablePartial.from_call(EachItem, items=[])\n    elif isinstance(element, pyparsing.NotAny):\n        ret = EditablePartial.from_call(AnnotatedItem, label=\"NOT\", item=\"\")\n    elif isinstance(element, pyparsing.FollowedBy):\n        ret = EditablePartial.from_call(AnnotatedItem, label=\"LOOKAHEAD\", item=\"\")\n    elif isinstance(element, pyparsing.PrecededBy):\n        ret = EditablePartial.from_call(AnnotatedItem, label=\"LOOKBEHIND\", item=\"\")\n    elif isinstance(element, pyparsing.Group):\n        if show_groups:\n            ret = EditablePartial.from_call(AnnotatedItem, label=\"\", item=\"\")\n        else:\n            ret = EditablePartial.from_call(railroad.Group, label=\"\", item=\"\")\n    elif isinstance(element, pyparsing.TokenConverter):\n        ret = EditablePartial.from_call(\n            AnnotatedItem, label=type(element).__name__.lower(), item=\"\"\n        )\n    elif isinstance(element, pyparsing.Opt):\n        ret = EditablePartial.from_call(railroad.Optional, item=\"\")\n    elif isinstance(element, pyparsing.OneOrMore):\n        ret = EditablePartial.from_call(railroad.OneOrMore, item=\"\")\n    elif isinstance(element, pyparsing.ZeroOrMore):\n        ret = EditablePartial.from_call(railroad.ZeroOrMore, item=\"\")\n    elif isinstance(element, pyparsing.Group):\n        ret = EditablePartial.from_call(\n            railroad.Group, item=None, label=element_results_name\n        )\n    elif isinstance(element, pyparsing.Empty) and not element.customName:\n        # Skip unnamed \"Empty\" elements\n        ret = None\n    elif len(exprs) > 1:\n        ret = EditablePartial.from_call(railroad.Sequence, items=[])\n    elif len(exprs) > 0 and not element_results_name:\n        ret = EditablePartial.from_call(railroad.Group, item=\"\", label=name)\n    else:\n        terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName)\n        ret = terminal\n\n    if ret is None:\n        return\n\n    # Indicate this element's position in the tree so we can extract it if necessary\n    lookup[el_id] = ElementState(\n        element=element,\n        converted=ret,\n        parent=parent,\n        parent_index=index,\n        number=lookup.generate_index(),\n    )\n    if element.customName:\n        lookup[el_id].mark_for_extraction(el_id, lookup, element.customName)\n\n    i = 0\n    for expr in exprs:\n        # Add a placeholder index in case we have to extract the child before we even add it to the parent\n        if \"items\" in ret.kwargs:\n            ret.kwargs[\"items\"].insert(i, None)\n\n        item = _to_diagram_element(\n            expr,\n            parent=ret,\n            lookup=lookup,\n            vertical=vertical,\n            index=i,\n            show_results_names=show_results_names,\n            show_groups=show_groups,\n        )\n\n        # Some elements don't need to be shown in the diagram\n        if item is not None:\n            if \"item\" in ret.kwargs:\n                ret.kwargs[\"item\"] = item\n            elif \"items\" in ret.kwargs:\n                # If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal\n                ret.kwargs[\"items\"][i] = item\n                i += 1\n        elif \"items\" in ret.kwargs:\n            # If we're supposed to skip this element, remove it from the parent\n            del ret.kwargs[\"items\"][i]\n\n    # If all this items children are none, skip this item\n    if ret and (\n        (\"items\" in ret.kwargs and len(ret.kwargs[\"items\"]) == 0)\n        or (\"item\" in ret.kwargs and ret.kwargs[\"item\"] is None)\n    ):\n        ret = EditablePartial.from_call(railroad.Terminal, name)\n\n    # Mark this element as \"complete\", ie it has all of its children\n    if el_id in lookup:\n        lookup[el_id].complete = True\n\n    if el_id in lookup and lookup[el_id].extract and lookup[el_id].complete:\n        lookup.extract_into_diagram(el_id)\n        if ret is not None:\n            ret = EditablePartial.from_call(\n                railroad.NonTerminal, text=lookup.diagrams[el_id].kwargs[\"name\"]\n            )\n\n    return ret\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/pyparsing/exceptions.py",
    "content": "# exceptions.py\n\nimport re\nimport sys\nimport typing\n\nfrom .util import col, line, lineno, _collapse_string_to_ranges\nfrom .unicode import pyparsing_unicode as ppu\n\n\nclass ExceptionWordUnicode(ppu.Latin1, ppu.LatinA, ppu.LatinB, ppu.Greek, ppu.Cyrillic):\n    pass\n\n\n_extract_alphanums = _collapse_string_to_ranges(ExceptionWordUnicode.alphanums)\n_exception_word_extractor = re.compile(\"([\" + _extract_alphanums + \"]{1,16})|.\")\n\n\nclass ParseBaseException(Exception):\n    \"\"\"base exception class for all parsing runtime exceptions\"\"\"\n\n    # Performance tuning: we construct a *lot* of these, so keep this\n    # constructor as small and fast as possible\n    def __init__(\n        self,\n        pstr: str,\n        loc: int = 0,\n        msg: typing.Optional[str] = None,\n        elem=None,\n    ):\n        self.loc = loc\n        if msg is None:\n            self.msg = pstr\n            self.pstr = \"\"\n        else:\n            self.msg = msg\n            self.pstr = pstr\n        self.parser_element = self.parserElement = elem\n        self.args = (pstr, loc, msg)\n\n    @staticmethod\n    def explain_exception(exc, depth=16):\n        \"\"\"\n        Method to take an exception and translate the Python internal traceback into a list\n        of the pyparsing expressions that caused the exception to be raised.\n\n        Parameters:\n\n        - exc - exception raised during parsing (need not be a ParseException, in support\n          of Python exceptions that might be raised in a parse action)\n        - depth (default=16) - number of levels back in the stack trace to list expression\n          and function names; if None, the full stack trace names will be listed; if 0, only\n          the failing input line, marker, and exception string will be shown\n\n        Returns a multi-line string listing the ParserElements and/or function names in the\n        exception's stack trace.\n        \"\"\"\n        import inspect\n        from .core import ParserElement\n\n        if depth is None:\n            depth = sys.getrecursionlimit()\n        ret = []\n        if isinstance(exc, ParseBaseException):\n            ret.append(exc.line)\n            ret.append(\" \" * (exc.column - 1) + \"^\")\n        ret.append(\"{}: {}\".format(type(exc).__name__, exc))\n\n        if depth > 0:\n            callers = inspect.getinnerframes(exc.__traceback__, context=depth)\n            seen = set()\n            for i, ff in enumerate(callers[-depth:]):\n                frm = ff[0]\n\n                f_self = frm.f_locals.get(\"self\", None)\n                if isinstance(f_self, ParserElement):\n                    if frm.f_code.co_name not in (\"parseImpl\", \"_parseNoCache\"):\n                        continue\n                    if id(f_self) in seen:\n                        continue\n                    seen.add(id(f_self))\n\n                    self_type = type(f_self)\n                    ret.append(\n                        \"{}.{} - {}\".format(\n                            self_type.__module__, self_type.__name__, f_self\n                        )\n                    )\n\n                elif f_self is not None:\n                    self_type = type(f_self)\n                    ret.append(\"{}.{}\".format(self_type.__module__, self_type.__name__))\n\n                else:\n                    code = frm.f_code\n                    if code.co_name in (\"wrapper\", \"<module>\"):\n                        continue\n\n                    ret.append(\"{}\".format(code.co_name))\n\n                depth -= 1\n                if not depth:\n                    break\n\n        return \"\\n\".join(ret)\n\n    @classmethod\n    def _from_exception(cls, pe):\n        \"\"\"\n        internal factory method to simplify creating one type of ParseException\n        from another - avoids having __init__ signature conflicts among subclasses\n        \"\"\"\n        return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)\n\n    @property\n    def line(self) -> str:\n        \"\"\"\n        Return the line of text where the exception occurred.\n        \"\"\"\n        return line(self.loc, self.pstr)\n\n    @property\n    def lineno(self) -> int:\n        \"\"\"\n        Return the 1-based line number of text where the exception occurred.\n        \"\"\"\n        return lineno(self.loc, self.pstr)\n\n    @property\n    def col(self) -> int:\n        \"\"\"\n        Return the 1-based column on the line of text where the exception occurred.\n        \"\"\"\n        return col(self.loc, self.pstr)\n\n    @property\n    def column(self) -> int:\n        \"\"\"\n        Return the 1-based column on the line of text where the exception occurred.\n        \"\"\"\n        return col(self.loc, self.pstr)\n\n    def __str__(self) -> str:\n        if self.pstr:\n            if self.loc >= len(self.pstr):\n                foundstr = \", found end of text\"\n            else:\n                # pull out next word at error location\n                found_match = _exception_word_extractor.match(self.pstr, self.loc)\n                if found_match is not None:\n                    found = found_match.group(0)\n                else:\n                    found = self.pstr[self.loc : self.loc + 1]\n                foundstr = (\", found %r\" % found).replace(r\"\\\\\", \"\\\\\")\n        else:\n            foundstr = \"\"\n        return \"{}{}  (at char {}), (line:{}, col:{})\".format(\n            self.msg, foundstr, self.loc, self.lineno, self.column\n        )\n\n    def __repr__(self):\n        return str(self)\n\n    def mark_input_line(self, marker_string: str = None, *, markerString=\">!<\") -> str:\n        \"\"\"\n        Extracts the exception line from the input string, and marks\n        the location of the exception with a special symbol.\n        \"\"\"\n        markerString = marker_string if marker_string is not None else markerString\n        line_str = self.line\n        line_column = self.column - 1\n        if markerString:\n            line_str = \"\".join(\n                (line_str[:line_column], markerString, line_str[line_column:])\n            )\n        return line_str.strip()\n\n    def explain(self, depth=16) -> str:\n        \"\"\"\n        Method to translate the Python internal traceback into a list\n        of the pyparsing expressions that caused the exception to be raised.\n\n        Parameters:\n\n        - depth (default=16) - number of levels back in the stack trace to list expression\n          and function names; if None, the full stack trace names will be listed; if 0, only\n          the failing input line, marker, and exception string will be shown\n\n        Returns a multi-line string listing the ParserElements and/or function names in the\n        exception's stack trace.\n\n        Example::\n\n            expr = pp.Word(pp.nums) * 3\n            try:\n                expr.parse_string(\"123 456 A789\")\n            except pp.ParseException as pe:\n                print(pe.explain(depth=0))\n\n        prints::\n\n            123 456 A789\n                    ^\n            ParseException: Expected W:(0-9), found 'A'  (at char 8), (line:1, col:9)\n\n        Note: the diagnostic output will include string representations of the expressions\n        that failed to parse. These representations will be more helpful if you use `set_name` to\n        give identifiable names to your expressions. Otherwise they will use the default string\n        forms, which may be cryptic to read.\n\n        Note: pyparsing's default truncation of exception tracebacks may also truncate the\n        stack of expressions that are displayed in the ``explain`` output. To get the full listing\n        of parser expressions, you may have to set ``ParserElement.verbose_stacktrace = True``\n        \"\"\"\n        return self.explain_exception(self, depth)\n\n    markInputline = mark_input_line\n\n\nclass ParseException(ParseBaseException):\n    \"\"\"\n    Exception thrown when a parse expression doesn't match the input string\n\n    Example::\n\n        try:\n            Word(nums).set_name(\"integer\").parse_string(\"ABC\")\n        except ParseException as pe:\n            print(pe)\n            print(\"column: {}\".format(pe.column))\n\n    prints::\n\n       Expected integer (at char 0), (line:1, col:1)\n        column: 1\n\n    \"\"\"\n\n\nclass ParseFatalException(ParseBaseException):\n    \"\"\"\n    User-throwable exception thrown when inconsistent parse content\n    is found; stops all parsing immediately\n    \"\"\"\n\n\nclass ParseSyntaxException(ParseFatalException):\n    \"\"\"\n    Just like :class:`ParseFatalException`, but thrown internally\n    when an :class:`ErrorStop<And._ErrorStop>` ('-' operator) indicates\n    that parsing is to stop immediately because an unbacktrackable\n    syntax error has been found.\n    \"\"\"\n\n\nclass RecursiveGrammarException(Exception):\n    \"\"\"\n    Exception thrown by :class:`ParserElement.validate` if the\n    grammar could be left-recursive; parser may need to enable\n    left recursion using :class:`ParserElement.enable_left_recursion<ParserElement.enable_left_recursion>`\n    \"\"\"\n\n    def __init__(self, parseElementList):\n        self.parseElementTrace = parseElementList\n\n    def __str__(self) -> str:\n        return \"RecursiveGrammarException: {}\".format(self.parseElementTrace)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/pyparsing/helpers.py",
    "content": "# helpers.py\nimport html.entities\nimport re\nimport typing\n\nfrom . import __diag__\nfrom .core import *\nfrom .util import _bslash, _flatten, _escape_regex_range_chars\n\n\n#\n# global helpers\n#\ndef delimited_list(\n    expr: Union[str, ParserElement],\n    delim: Union[str, ParserElement] = \",\",\n    combine: bool = False,\n    min: typing.Optional[int] = None,\n    max: typing.Optional[int] = None,\n    *,\n    allow_trailing_delim: bool = False,\n) -> ParserElement:\n    \"\"\"Helper to define a delimited list of expressions - the delimiter\n    defaults to ','. By default, the list elements and delimiters can\n    have intervening whitespace, and comments, but this can be\n    overridden by passing ``combine=True`` in the constructor. If\n    ``combine`` is set to ``True``, the matching tokens are\n    returned as a single token string, with the delimiters included;\n    otherwise, the matching tokens are returned as a list of tokens,\n    with the delimiters suppressed.\n\n    If ``allow_trailing_delim`` is set to True, then the list may end with\n    a delimiter.\n\n    Example::\n\n        delimited_list(Word(alphas)).parse_string(\"aa,bb,cc\") # -> ['aa', 'bb', 'cc']\n        delimited_list(Word(hexnums), delim=':', combine=True).parse_string(\"AA:BB:CC:DD:EE\") # -> ['AA:BB:CC:DD:EE']\n    \"\"\"\n    if isinstance(expr, str_type):\n        expr = ParserElement._literalStringClass(expr)\n\n    dlName = \"{expr} [{delim} {expr}]...{end}\".format(\n        expr=str(expr.copy().streamline()),\n        delim=str(delim),\n        end=\" [{}]\".format(str(delim)) if allow_trailing_delim else \"\",\n    )\n\n    if not combine:\n        delim = Suppress(delim)\n\n    if min is not None:\n        if min < 1:\n            raise ValueError(\"min must be greater than 0\")\n        min -= 1\n    if max is not None:\n        if min is not None and max <= min:\n            raise ValueError(\"max must be greater than, or equal to min\")\n        max -= 1\n    delimited_list_expr = expr + (delim + expr)[min, max]\n\n    if allow_trailing_delim:\n        delimited_list_expr += Opt(delim)\n\n    if combine:\n        return Combine(delimited_list_expr).set_name(dlName)\n    else:\n        return delimited_list_expr.set_name(dlName)\n\n\ndef counted_array(\n    expr: ParserElement,\n    int_expr: typing.Optional[ParserElement] = None,\n    *,\n    intExpr: typing.Optional[ParserElement] = None,\n) -> ParserElement:\n    \"\"\"Helper to define a counted list of expressions.\n\n    This helper defines a pattern of the form::\n\n        integer expr expr expr...\n\n    where the leading integer tells how many expr expressions follow.\n    The matched tokens returns the array of expr tokens as a list - the\n    leading count token is suppressed.\n\n    If ``int_expr`` is specified, it should be a pyparsing expression\n    that produces an integer value.\n\n    Example::\n\n        counted_array(Word(alphas)).parse_string('2 ab cd ef')  # -> ['ab', 'cd']\n\n        # in this parser, the leading integer value is given in binary,\n        # '10' indicating that 2 values are in the array\n        binary_constant = Word('01').set_parse_action(lambda t: int(t[0], 2))\n        counted_array(Word(alphas), int_expr=binary_constant).parse_string('10 ab cd ef')  # -> ['ab', 'cd']\n\n        # if other fields must be parsed after the count but before the\n        # list items, give the fields results names and they will\n        # be preserved in the returned ParseResults:\n        count_with_metadata = integer + Word(alphas)(\"type\")\n        typed_array = counted_array(Word(alphanums), int_expr=count_with_metadata)(\"items\")\n        result = typed_array.parse_string(\"3 bool True True False\")\n        print(result.dump())\n\n        # prints\n        # ['True', 'True', 'False']\n        # - items: ['True', 'True', 'False']\n        # - type: 'bool'\n    \"\"\"\n    intExpr = intExpr or int_expr\n    array_expr = Forward()\n\n    def count_field_parse_action(s, l, t):\n        nonlocal array_expr\n        n = t[0]\n        array_expr <<= (expr * n) if n else Empty()\n        # clear list contents, but keep any named results\n        del t[:]\n\n    if intExpr is None:\n        intExpr = Word(nums).set_parse_action(lambda t: int(t[0]))\n    else:\n        intExpr = intExpr.copy()\n    intExpr.set_name(\"arrayLen\")\n    intExpr.add_parse_action(count_field_parse_action, call_during_try=True)\n    return (intExpr + array_expr).set_name(\"(len) \" + str(expr) + \"...\")\n\n\ndef match_previous_literal(expr: ParserElement) -> ParserElement:\n    \"\"\"Helper to define an expression that is indirectly defined from\n    the tokens matched in a previous expression, that is, it looks for\n    a 'repeat' of a previous expression.  For example::\n\n        first = Word(nums)\n        second = match_previous_literal(first)\n        match_expr = first + \":\" + second\n\n    will match ``\"1:1\"``, but not ``\"1:2\"``.  Because this\n    matches a previous literal, will also match the leading\n    ``\"1:1\"`` in ``\"1:10\"``. If this is not desired, use\n    :class:`match_previous_expr`. Do *not* use with packrat parsing\n    enabled.\n    \"\"\"\n    rep = Forward()\n\n    def copy_token_to_repeater(s, l, t):\n        if t:\n            if len(t) == 1:\n                rep << t[0]\n            else:\n                # flatten t tokens\n                tflat = _flatten(t.as_list())\n                rep << And(Literal(tt) for tt in tflat)\n        else:\n            rep << Empty()\n\n    expr.add_parse_action(copy_token_to_repeater, callDuringTry=True)\n    rep.set_name(\"(prev) \" + str(expr))\n    return rep\n\n\ndef match_previous_expr(expr: ParserElement) -> ParserElement:\n    \"\"\"Helper to define an expression that is indirectly defined from\n    the tokens matched in a previous expression, that is, it looks for\n    a 'repeat' of a previous expression.  For example::\n\n        first = Word(nums)\n        second = match_previous_expr(first)\n        match_expr = first + \":\" + second\n\n    will match ``\"1:1\"``, but not ``\"1:2\"``.  Because this\n    matches by expressions, will *not* match the leading ``\"1:1\"``\n    in ``\"1:10\"``; the expressions are evaluated first, and then\n    compared, so ``\"1\"`` is compared with ``\"10\"``. Do *not* use\n    with packrat parsing enabled.\n    \"\"\"\n    rep = Forward()\n    e2 = expr.copy()\n    rep <<= e2\n\n    def copy_token_to_repeater(s, l, t):\n        matchTokens = _flatten(t.as_list())\n\n        def must_match_these_tokens(s, l, t):\n            theseTokens = _flatten(t.as_list())\n            if theseTokens != matchTokens:\n                raise ParseException(\n                    s, l, \"Expected {}, found{}\".format(matchTokens, theseTokens)\n                )\n\n        rep.set_parse_action(must_match_these_tokens, callDuringTry=True)\n\n    expr.add_parse_action(copy_token_to_repeater, callDuringTry=True)\n    rep.set_name(\"(prev) \" + str(expr))\n    return rep\n\n\ndef one_of(\n    strs: Union[typing.Iterable[str], str],\n    caseless: bool = False,\n    use_regex: bool = True,\n    as_keyword: bool = False,\n    *,\n    useRegex: bool = True,\n    asKeyword: bool = False,\n) -> ParserElement:\n    \"\"\"Helper to quickly define a set of alternative :class:`Literal` s,\n    and makes sure to do longest-first testing when there is a conflict,\n    regardless of the input order, but returns\n    a :class:`MatchFirst` for best performance.\n\n    Parameters:\n\n    - ``strs`` - a string of space-delimited literals, or a collection of\n      string literals\n    - ``caseless`` - treat all literals as caseless - (default= ``False``)\n    - ``use_regex`` - as an optimization, will\n      generate a :class:`Regex` object; otherwise, will generate\n      a :class:`MatchFirst` object (if ``caseless=True`` or ``asKeyword=True``, or if\n      creating a :class:`Regex` raises an exception) - (default= ``True``)\n    - ``as_keyword`` - enforce :class:`Keyword`-style matching on the\n      generated expressions - (default= ``False``)\n    - ``asKeyword`` and ``useRegex`` are retained for pre-PEP8 compatibility,\n      but will be removed in a future release\n\n    Example::\n\n        comp_oper = one_of(\"< = > <= >= !=\")\n        var = Word(alphas)\n        number = Word(nums)\n        term = var | number\n        comparison_expr = term + comp_oper + term\n        print(comparison_expr.search_string(\"B = 12  AA=23 B<=AA AA>12\"))\n\n    prints::\n\n        [['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']]\n    \"\"\"\n    asKeyword = asKeyword or as_keyword\n    useRegex = useRegex and use_regex\n\n    if (\n        isinstance(caseless, str_type)\n        and __diag__.warn_on_multiple_string_args_to_oneof\n    ):\n        warnings.warn(\n            \"More than one string argument passed to one_of, pass\"\n            \" choices as a list or space-delimited string\",\n            stacklevel=2,\n        )\n\n    if caseless:\n        isequal = lambda a, b: a.upper() == b.upper()\n        masks = lambda a, b: b.upper().startswith(a.upper())\n        parseElementClass = CaselessKeyword if asKeyword else CaselessLiteral\n    else:\n        isequal = lambda a, b: a == b\n        masks = lambda a, b: b.startswith(a)\n        parseElementClass = Keyword if asKeyword else Literal\n\n    symbols: List[str] = []\n    if isinstance(strs, str_type):\n        symbols = strs.split()\n    elif isinstance(strs, Iterable):\n        symbols = list(strs)\n    else:\n        raise TypeError(\"Invalid argument to one_of, expected string or iterable\")\n    if not symbols:\n        return NoMatch()\n\n    # reorder given symbols to take care to avoid masking longer choices with shorter ones\n    # (but only if the given symbols are not just single characters)\n    if any(len(sym) > 1 for sym in symbols):\n        i = 0\n        while i < len(symbols) - 1:\n            cur = symbols[i]\n            for j, other in enumerate(symbols[i + 1 :]):\n                if isequal(other, cur):\n                    del symbols[i + j + 1]\n                    break\n                elif masks(cur, other):\n                    del symbols[i + j + 1]\n                    symbols.insert(i, other)\n                    break\n            else:\n                i += 1\n\n    if useRegex:\n        re_flags: int = re.IGNORECASE if caseless else 0\n\n        try:\n            if all(len(sym) == 1 for sym in symbols):\n                # symbols are just single characters, create range regex pattern\n                patt = \"[{}]\".format(\n                    \"\".join(_escape_regex_range_chars(sym) for sym in symbols)\n                )\n            else:\n                patt = \"|\".join(re.escape(sym) for sym in symbols)\n\n            # wrap with \\b word break markers if defining as keywords\n            if asKeyword:\n                patt = r\"\\b(?:{})\\b\".format(patt)\n\n            ret = Regex(patt, flags=re_flags).set_name(\" | \".join(symbols))\n\n            if caseless:\n                # add parse action to return symbols as specified, not in random\n                # casing as found in input string\n                symbol_map = {sym.lower(): sym for sym in symbols}\n                ret.add_parse_action(lambda s, l, t: symbol_map[t[0].lower()])\n\n            return ret\n\n        except re.error:\n            warnings.warn(\n                \"Exception creating Regex for one_of, building MatchFirst\", stacklevel=2\n            )\n\n    # last resort, just use MatchFirst\n    return MatchFirst(parseElementClass(sym) for sym in symbols).set_name(\n        \" | \".join(symbols)\n    )\n\n\ndef dict_of(key: ParserElement, value: ParserElement) -> ParserElement:\n    \"\"\"Helper to easily and clearly define a dictionary by specifying\n    the respective patterns for the key and value.  Takes care of\n    defining the :class:`Dict`, :class:`ZeroOrMore`, and\n    :class:`Group` tokens in the proper order.  The key pattern\n    can include delimiting markers or punctuation, as long as they are\n    suppressed, thereby leaving the significant key text.  The value\n    pattern can include named results, so that the :class:`Dict` results\n    can include named token fields.\n\n    Example::\n\n        text = \"shape: SQUARE posn: upper left color: light blue texture: burlap\"\n        attr_expr = (label + Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join))\n        print(attr_expr[1, ...].parse_string(text).dump())\n\n        attr_label = label\n        attr_value = Suppress(':') + OneOrMore(data_word, stop_on=label).set_parse_action(' '.join)\n\n        # similar to Dict, but simpler call format\n        result = dict_of(attr_label, attr_value).parse_string(text)\n        print(result.dump())\n        print(result['shape'])\n        print(result.shape)  # object attribute access works too\n        print(result.as_dict())\n\n    prints::\n\n        [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]\n        - color: 'light blue'\n        - posn: 'upper left'\n        - shape: 'SQUARE'\n        - texture: 'burlap'\n        SQUARE\n        SQUARE\n        {'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}\n    \"\"\"\n    return Dict(OneOrMore(Group(key + value)))\n\n\ndef original_text_for(\n    expr: ParserElement, as_string: bool = True, *, asString: bool = True\n) -> ParserElement:\n    \"\"\"Helper to return the original, untokenized text for a given\n    expression.  Useful to restore the parsed fields of an HTML start\n    tag into the raw tag text itself, or to revert separate tokens with\n    intervening whitespace back to the original matching input text. By\n    default, returns astring containing the original parsed text.\n\n    If the optional ``as_string`` argument is passed as\n    ``False``, then the return value is\n    a :class:`ParseResults` containing any results names that\n    were originally matched, and a single token containing the original\n    matched text from the input string.  So if the expression passed to\n    :class:`original_text_for` contains expressions with defined\n    results names, you must set ``as_string`` to ``False`` if you\n    want to preserve those results name values.\n\n    The ``asString`` pre-PEP8 argument is retained for compatibility,\n    but will be removed in a future release.\n\n    Example::\n\n        src = \"this is test <b> bold <i>text</i> </b> normal text \"\n        for tag in (\"b\", \"i\"):\n            opener, closer = make_html_tags(tag)\n            patt = original_text_for(opener + SkipTo(closer) + closer)\n            print(patt.search_string(src)[0])\n\n    prints::\n\n        ['<b> bold <i>text</i> </b>']\n        ['<i>text</i>']\n    \"\"\"\n    asString = asString and as_string\n\n    locMarker = Empty().set_parse_action(lambda s, loc, t: loc)\n    endlocMarker = locMarker.copy()\n    endlocMarker.callPreparse = False\n    matchExpr = locMarker(\"_original_start\") + expr + endlocMarker(\"_original_end\")\n    if asString:\n        extractText = lambda s, l, t: s[t._original_start : t._original_end]\n    else:\n\n        def extractText(s, l, t):\n            t[:] = [s[t.pop(\"_original_start\") : t.pop(\"_original_end\")]]\n\n    matchExpr.set_parse_action(extractText)\n    matchExpr.ignoreExprs = expr.ignoreExprs\n    matchExpr.suppress_warning(Diagnostics.warn_ungrouped_named_tokens_in_collection)\n    return matchExpr\n\n\ndef ungroup(expr: ParserElement) -> ParserElement:\n    \"\"\"Helper to undo pyparsing's default grouping of And expressions,\n    even if all but one are non-empty.\n    \"\"\"\n    return TokenConverter(expr).add_parse_action(lambda t: t[0])\n\n\ndef locatedExpr(expr: ParserElement) -> ParserElement:\n    \"\"\"\n    (DEPRECATED - future code should use the Located class)\n    Helper to decorate a returned token with its starting and ending\n    locations in the input string.\n\n    This helper adds the following results names:\n\n    - ``locn_start`` - location where matched expression begins\n    - ``locn_end`` - location where matched expression ends\n    - ``value`` - the actual parsed results\n\n    Be careful if the input text contains ``<TAB>`` characters, you\n    may want to call :class:`ParserElement.parseWithTabs`\n\n    Example::\n\n        wd = Word(alphas)\n        for match in locatedExpr(wd).searchString(\"ljsdf123lksdjjf123lkkjj1222\"):\n            print(match)\n\n    prints::\n\n        [[0, 'ljsdf', 5]]\n        [[8, 'lksdjjf', 15]]\n        [[18, 'lkkjj', 23]]\n    \"\"\"\n    locator = Empty().set_parse_action(lambda ss, ll, tt: ll)\n    return Group(\n        locator(\"locn_start\")\n        + expr(\"value\")\n        + locator.copy().leaveWhitespace()(\"locn_end\")\n    )\n\n\ndef nested_expr(\n    opener: Union[str, ParserElement] = \"(\",\n    closer: Union[str, ParserElement] = \")\",\n    content: typing.Optional[ParserElement] = None,\n    ignore_expr: ParserElement = quoted_string(),\n    *,\n    ignoreExpr: ParserElement = quoted_string(),\n) -> ParserElement:\n    \"\"\"Helper method for defining nested lists enclosed in opening and\n    closing delimiters (``\"(\"`` and ``\")\"`` are the default).\n\n    Parameters:\n    - ``opener`` - opening character for a nested list\n      (default= ``\"(\"``); can also be a pyparsing expression\n    - ``closer`` - closing character for a nested list\n      (default= ``\")\"``); can also be a pyparsing expression\n    - ``content`` - expression for items within the nested lists\n      (default= ``None``)\n    - ``ignore_expr`` - expression for ignoring opening and closing delimiters\n      (default= :class:`quoted_string`)\n    - ``ignoreExpr`` - this pre-PEP8 argument is retained for compatibility\n      but will be removed in a future release\n\n    If an expression is not provided for the content argument, the\n    nested expression will capture all whitespace-delimited content\n    between delimiters as a list of separate values.\n\n    Use the ``ignore_expr`` argument to define expressions that may\n    contain opening or closing characters that should not be treated as\n    opening or closing characters for nesting, such as quoted_string or\n    a comment expression.  Specify multiple expressions using an\n    :class:`Or` or :class:`MatchFirst`. The default is\n    :class:`quoted_string`, but if no expressions are to be ignored, then\n    pass ``None`` for this argument.\n\n    Example::\n\n        data_type = one_of(\"void int short long char float double\")\n        decl_data_type = Combine(data_type + Opt(Word('*')))\n        ident = Word(alphas+'_', alphanums+'_')\n        number = pyparsing_common.number\n        arg = Group(decl_data_type + ident)\n        LPAR, RPAR = map(Suppress, \"()\")\n\n        code_body = nested_expr('{', '}', ignore_expr=(quoted_string | c_style_comment))\n\n        c_function = (decl_data_type(\"type\")\n                      + ident(\"name\")\n                      + LPAR + Opt(delimited_list(arg), [])(\"args\") + RPAR\n                      + code_body(\"body\"))\n        c_function.ignore(c_style_comment)\n\n        source_code = '''\n            int is_odd(int x) {\n                return (x%2);\n            }\n\n            int dec_to_hex(char hchar) {\n                if (hchar >= '0' && hchar <= '9') {\n                    return (ord(hchar)-ord('0'));\n                } else {\n                    return (10+ord(hchar)-ord('A'));\n                }\n            }\n        '''\n        for func in c_function.search_string(source_code):\n            print(\"%(name)s (%(type)s) args: %(args)s\" % func)\n\n\n    prints::\n\n        is_odd (int) args: [['int', 'x']]\n        dec_to_hex (int) args: [['char', 'hchar']]\n    \"\"\"\n    if ignoreExpr != ignore_expr:\n        ignoreExpr = ignore_expr if ignoreExpr == quoted_string() else ignoreExpr\n    if opener == closer:\n        raise ValueError(\"opening and closing strings cannot be the same\")\n    if content is None:\n        if isinstance(opener, str_type) and isinstance(closer, str_type):\n            if len(opener) == 1 and len(closer) == 1:\n                if ignoreExpr is not None:\n                    content = Combine(\n                        OneOrMore(\n                            ~ignoreExpr\n                            + CharsNotIn(\n                                opener + closer + ParserElement.DEFAULT_WHITE_CHARS,\n                                exact=1,\n                            )\n                        )\n                    ).set_parse_action(lambda t: t[0].strip())\n                else:\n                    content = empty.copy() + CharsNotIn(\n                        opener + closer + ParserElement.DEFAULT_WHITE_CHARS\n                    ).set_parse_action(lambda t: t[0].strip())\n            else:\n                if ignoreExpr is not None:\n                    content = Combine(\n                        OneOrMore(\n                            ~ignoreExpr\n                            + ~Literal(opener)\n                            + ~Literal(closer)\n                            + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1)\n                        )\n                    ).set_parse_action(lambda t: t[0].strip())\n                else:\n                    content = Combine(\n                        OneOrMore(\n                            ~Literal(opener)\n                            + ~Literal(closer)\n                            + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS, exact=1)\n                        )\n                    ).set_parse_action(lambda t: t[0].strip())\n        else:\n            raise ValueError(\n                \"opening and closing arguments must be strings if no content expression is given\"\n            )\n    ret = Forward()\n    if ignoreExpr is not None:\n        ret <<= Group(\n            Suppress(opener) + ZeroOrMore(ignoreExpr | ret | content) + Suppress(closer)\n        )\n    else:\n        ret <<= Group(Suppress(opener) + ZeroOrMore(ret | content) + Suppress(closer))\n    ret.set_name(\"nested %s%s expression\" % (opener, closer))\n    return ret\n\n\ndef _makeTags(tagStr, xml, suppress_LT=Suppress(\"<\"), suppress_GT=Suppress(\">\")):\n    \"\"\"Internal helper to construct opening and closing tag expressions, given a tag name\"\"\"\n    if isinstance(tagStr, str_type):\n        resname = tagStr\n        tagStr = Keyword(tagStr, caseless=not xml)\n    else:\n        resname = tagStr.name\n\n    tagAttrName = Word(alphas, alphanums + \"_-:\")\n    if xml:\n        tagAttrValue = dbl_quoted_string.copy().set_parse_action(remove_quotes)\n        openTag = (\n            suppress_LT\n            + tagStr(\"tag\")\n            + Dict(ZeroOrMore(Group(tagAttrName + Suppress(\"=\") + tagAttrValue)))\n            + Opt(\"/\", default=[False])(\"empty\").set_parse_action(\n                lambda s, l, t: t[0] == \"/\"\n            )\n            + suppress_GT\n        )\n    else:\n        tagAttrValue = quoted_string.copy().set_parse_action(remove_quotes) | Word(\n            printables, exclude_chars=\">\"\n        )\n        openTag = (\n            suppress_LT\n            + tagStr(\"tag\")\n            + Dict(\n                ZeroOrMore(\n                    Group(\n                        tagAttrName.set_parse_action(lambda t: t[0].lower())\n                        + Opt(Suppress(\"=\") + tagAttrValue)\n                    )\n                )\n            )\n            + Opt(\"/\", default=[False])(\"empty\").set_parse_action(\n                lambda s, l, t: t[0] == \"/\"\n            )\n            + suppress_GT\n        )\n    closeTag = Combine(Literal(\"</\") + tagStr + \">\", adjacent=False)\n\n    openTag.set_name(\"<%s>\" % resname)\n    # add start<tagname> results name in parse action now that ungrouped names are not reported at two levels\n    openTag.add_parse_action(\n        lambda t: t.__setitem__(\n            \"start\" + \"\".join(resname.replace(\":\", \" \").title().split()), t.copy()\n        )\n    )\n    closeTag = closeTag(\n        \"end\" + \"\".join(resname.replace(\":\", \" \").title().split())\n    ).set_name(\"</%s>\" % resname)\n    openTag.tag = resname\n    closeTag.tag = resname\n    openTag.tag_body = SkipTo(closeTag())\n    return openTag, closeTag\n\n\ndef make_html_tags(\n    tag_str: Union[str, ParserElement]\n) -> Tuple[ParserElement, ParserElement]:\n    \"\"\"Helper to construct opening and closing tag expressions for HTML,\n    given a tag name. Matches tags in either upper or lower case,\n    attributes with namespaces and with quoted or unquoted values.\n\n    Example::\n\n        text = '<td>More info at the <a href=\"https://github.com/pyparsing/pyparsing/wiki\">pyparsing</a> wiki page</td>'\n        # make_html_tags returns pyparsing expressions for the opening and\n        # closing tags as a 2-tuple\n        a, a_end = make_html_tags(\"A\")\n        link_expr = a + SkipTo(a_end)(\"link_text\") + a_end\n\n        for link in link_expr.search_string(text):\n            # attributes in the <A> tag (like \"href\" shown here) are\n            # also accessible as named results\n            print(link.link_text, '->', link.href)\n\n    prints::\n\n        pyparsing -> https://github.com/pyparsing/pyparsing/wiki\n    \"\"\"\n    return _makeTags(tag_str, False)\n\n\ndef make_xml_tags(\n    tag_str: Union[str, ParserElement]\n) -> Tuple[ParserElement, ParserElement]:\n    \"\"\"Helper to construct opening and closing tag expressions for XML,\n    given a tag name. Matches tags only in the given upper/lower case.\n\n    Example: similar to :class:`make_html_tags`\n    \"\"\"\n    return _makeTags(tag_str, True)\n\n\nany_open_tag: ParserElement\nany_close_tag: ParserElement\nany_open_tag, any_close_tag = make_html_tags(\n    Word(alphas, alphanums + \"_:\").set_name(\"any tag\")\n)\n\n_htmlEntityMap = {k.rstrip(\";\"): v for k, v in html.entities.html5.items()}\ncommon_html_entity = Regex(\"&(?P<entity>\" + \"|\".join(_htmlEntityMap) + \");\").set_name(\n    \"common HTML entity\"\n)\n\n\ndef replace_html_entity(t):\n    \"\"\"Helper parser action to replace common HTML entities with their special characters\"\"\"\n    return _htmlEntityMap.get(t.entity)\n\n\nclass OpAssoc(Enum):\n    LEFT = 1\n    RIGHT = 2\n\n\nInfixNotationOperatorArgType = Union[\n    ParserElement, str, Tuple[Union[ParserElement, str], Union[ParserElement, str]]\n]\nInfixNotationOperatorSpec = Union[\n    Tuple[\n        InfixNotationOperatorArgType,\n        int,\n        OpAssoc,\n        typing.Optional[ParseAction],\n    ],\n    Tuple[\n        InfixNotationOperatorArgType,\n        int,\n        OpAssoc,\n    ],\n]\n\n\ndef infix_notation(\n    base_expr: ParserElement,\n    op_list: List[InfixNotationOperatorSpec],\n    lpar: Union[str, ParserElement] = Suppress(\"(\"),\n    rpar: Union[str, ParserElement] = Suppress(\")\"),\n) -> ParserElement:\n    \"\"\"Helper method for constructing grammars of expressions made up of\n    operators working in a precedence hierarchy.  Operators may be unary\n    or binary, left- or right-associative.  Parse actions can also be\n    attached to operator expressions. The generated parser will also\n    recognize the use of parentheses to override operator precedences\n    (see example below).\n\n    Note: if you define a deep operator list, you may see performance\n    issues when using infix_notation. See\n    :class:`ParserElement.enable_packrat` for a mechanism to potentially\n    improve your parser performance.\n\n    Parameters:\n    - ``base_expr`` - expression representing the most basic operand to\n      be used in the expression\n    - ``op_list`` - list of tuples, one for each operator precedence level\n      in the expression grammar; each tuple is of the form ``(op_expr,\n      num_operands, right_left_assoc, (optional)parse_action)``, where:\n\n      - ``op_expr`` is the pyparsing expression for the operator; may also\n        be a string, which will be converted to a Literal; if ``num_operands``\n        is 3, ``op_expr`` is a tuple of two expressions, for the two\n        operators separating the 3 terms\n      - ``num_operands`` is the number of terms for this operator (must be 1,\n        2, or 3)\n      - ``right_left_assoc`` is the indicator whether the operator is right\n        or left associative, using the pyparsing-defined constants\n        ``OpAssoc.RIGHT`` and ``OpAssoc.LEFT``.\n      - ``parse_action`` is the parse action to be associated with\n        expressions matching this operator expression (the parse action\n        tuple member may be omitted); if the parse action is passed\n        a tuple or list of functions, this is equivalent to calling\n        ``set_parse_action(*fn)``\n        (:class:`ParserElement.set_parse_action`)\n    - ``lpar`` - expression for matching left-parentheses; if passed as a\n      str, then will be parsed as Suppress(lpar). If lpar is passed as\n      an expression (such as ``Literal('(')``), then it will be kept in\n      the parsed results, and grouped with them. (default= ``Suppress('(')``)\n    - ``rpar`` - expression for matching right-parentheses; if passed as a\n      str, then will be parsed as Suppress(rpar). If rpar is passed as\n      an expression (such as ``Literal(')')``), then it will be kept in\n      the parsed results, and grouped with them. (default= ``Suppress(')')``)\n\n    Example::\n\n        # simple example of four-function arithmetic with ints and\n        # variable names\n        integer = pyparsing_common.signed_integer\n        varname = pyparsing_common.identifier\n\n        arith_expr = infix_notation(integer | varname,\n            [\n            ('-', 1, OpAssoc.RIGHT),\n            (one_of('* /'), 2, OpAssoc.LEFT),\n            (one_of('+ -'), 2, OpAssoc.LEFT),\n            ])\n\n        arith_expr.run_tests('''\n            5+3*6\n            (5+3)*6\n            -2--11\n            ''', full_dump=False)\n\n    prints::\n\n        5+3*6\n        [[5, '+', [3, '*', 6]]]\n\n        (5+3)*6\n        [[[5, '+', 3], '*', 6]]\n\n        -2--11\n        [[['-', 2], '-', ['-', 11]]]\n    \"\"\"\n    # captive version of FollowedBy that does not do parse actions or capture results names\n    class _FB(FollowedBy):\n        def parseImpl(self, instring, loc, doActions=True):\n            self.expr.try_parse(instring, loc)\n            return loc, []\n\n    _FB.__name__ = \"FollowedBy>\"\n\n    ret = Forward()\n    if isinstance(lpar, str):\n        lpar = Suppress(lpar)\n    if isinstance(rpar, str):\n        rpar = Suppress(rpar)\n\n    # if lpar and rpar are not suppressed, wrap in group\n    if not (isinstance(rpar, Suppress) and isinstance(rpar, Suppress)):\n        lastExpr = base_expr | Group(lpar + ret + rpar)\n    else:\n        lastExpr = base_expr | (lpar + ret + rpar)\n\n    for i, operDef in enumerate(op_list):\n        opExpr, arity, rightLeftAssoc, pa = (operDef + (None,))[:4]\n        if isinstance(opExpr, str_type):\n            opExpr = ParserElement._literalStringClass(opExpr)\n        if arity == 3:\n            if not isinstance(opExpr, (tuple, list)) or len(opExpr) != 2:\n                raise ValueError(\n                    \"if numterms=3, opExpr must be a tuple or list of two expressions\"\n                )\n            opExpr1, opExpr2 = opExpr\n            term_name = \"{}{} term\".format(opExpr1, opExpr2)\n        else:\n            term_name = \"{} term\".format(opExpr)\n\n        if not 1 <= arity <= 3:\n            raise ValueError(\"operator must be unary (1), binary (2), or ternary (3)\")\n\n        if rightLeftAssoc not in (OpAssoc.LEFT, OpAssoc.RIGHT):\n            raise ValueError(\"operator must indicate right or left associativity\")\n\n        thisExpr: Forward = Forward().set_name(term_name)\n        if rightLeftAssoc is OpAssoc.LEFT:\n            if arity == 1:\n                matchExpr = _FB(lastExpr + opExpr) + Group(lastExpr + opExpr[1, ...])\n            elif arity == 2:\n                if opExpr is not None:\n                    matchExpr = _FB(lastExpr + opExpr + lastExpr) + Group(\n                        lastExpr + (opExpr + lastExpr)[1, ...]\n                    )\n                else:\n                    matchExpr = _FB(lastExpr + lastExpr) + Group(lastExpr[2, ...])\n            elif arity == 3:\n                matchExpr = _FB(\n                    lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr\n                ) + Group(lastExpr + OneOrMore(opExpr1 + lastExpr + opExpr2 + lastExpr))\n        elif rightLeftAssoc is OpAssoc.RIGHT:\n            if arity == 1:\n                # try to avoid LR with this extra test\n                if not isinstance(opExpr, Opt):\n                    opExpr = Opt(opExpr)\n                matchExpr = _FB(opExpr.expr + thisExpr) + Group(opExpr + thisExpr)\n            elif arity == 2:\n                if opExpr is not None:\n                    matchExpr = _FB(lastExpr + opExpr + thisExpr) + Group(\n                        lastExpr + (opExpr + thisExpr)[1, ...]\n                    )\n                else:\n                    matchExpr = _FB(lastExpr + thisExpr) + Group(\n                        lastExpr + thisExpr[1, ...]\n                    )\n            elif arity == 3:\n                matchExpr = _FB(\n                    lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr\n                ) + Group(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr)\n        if pa:\n            if isinstance(pa, (tuple, list)):\n                matchExpr.set_parse_action(*pa)\n            else:\n                matchExpr.set_parse_action(pa)\n        thisExpr <<= (matchExpr | lastExpr).setName(term_name)\n        lastExpr = thisExpr\n    ret <<= lastExpr\n    return ret\n\n\ndef indentedBlock(blockStatementExpr, indentStack, indent=True, backup_stacks=[]):\n    \"\"\"\n    (DEPRECATED - use IndentedBlock class instead)\n    Helper method for defining space-delimited indentation blocks,\n    such as those used to define block statements in Python source code.\n\n    Parameters:\n\n    - ``blockStatementExpr`` - expression defining syntax of statement that\n      is repeated within the indented block\n    - ``indentStack`` - list created by caller to manage indentation stack\n      (multiple ``statementWithIndentedBlock`` expressions within a single\n      grammar should share a common ``indentStack``)\n    - ``indent`` - boolean indicating whether block must be indented beyond\n      the current level; set to ``False`` for block of left-most statements\n      (default= ``True``)\n\n    A valid block must contain at least one ``blockStatement``.\n\n    (Note that indentedBlock uses internal parse actions which make it\n    incompatible with packrat parsing.)\n\n    Example::\n\n        data = '''\n        def A(z):\n          A1\n          B = 100\n          G = A2\n          A2\n          A3\n        B\n        def BB(a,b,c):\n          BB1\n          def BBA():\n            bba1\n            bba2\n            bba3\n        C\n        D\n        def spam(x,y):\n             def eggs(z):\n                 pass\n        '''\n\n\n        indentStack = [1]\n        stmt = Forward()\n\n        identifier = Word(alphas, alphanums)\n        funcDecl = (\"def\" + identifier + Group(\"(\" + Opt(delimitedList(identifier)) + \")\") + \":\")\n        func_body = indentedBlock(stmt, indentStack)\n        funcDef = Group(funcDecl + func_body)\n\n        rvalue = Forward()\n        funcCall = Group(identifier + \"(\" + Opt(delimitedList(rvalue)) + \")\")\n        rvalue << (funcCall | identifier | Word(nums))\n        assignment = Group(identifier + \"=\" + rvalue)\n        stmt << (funcDef | assignment | identifier)\n\n        module_body = stmt[1, ...]\n\n        parseTree = module_body.parseString(data)\n        parseTree.pprint()\n\n    prints::\n\n        [['def',\n          'A',\n          ['(', 'z', ')'],\n          ':',\n          [['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],\n         'B',\n         ['def',\n          'BB',\n          ['(', 'a', 'b', 'c', ')'],\n          ':',\n          [['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],\n         'C',\n         'D',\n         ['def',\n          'spam',\n          ['(', 'x', 'y', ')'],\n          ':',\n          [[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]]\n    \"\"\"\n    backup_stacks.append(indentStack[:])\n\n    def reset_stack():\n        indentStack[:] = backup_stacks[-1]\n\n    def checkPeerIndent(s, l, t):\n        if l >= len(s):\n            return\n        curCol = col(l, s)\n        if curCol != indentStack[-1]:\n            if curCol > indentStack[-1]:\n                raise ParseException(s, l, \"illegal nesting\")\n            raise ParseException(s, l, \"not a peer entry\")\n\n    def checkSubIndent(s, l, t):\n        curCol = col(l, s)\n        if curCol > indentStack[-1]:\n            indentStack.append(curCol)\n        else:\n            raise ParseException(s, l, \"not a subentry\")\n\n    def checkUnindent(s, l, t):\n        if l >= len(s):\n            return\n        curCol = col(l, s)\n        if not (indentStack and curCol in indentStack):\n            raise ParseException(s, l, \"not an unindent\")\n        if curCol < indentStack[-1]:\n            indentStack.pop()\n\n    NL = OneOrMore(LineEnd().set_whitespace_chars(\"\\t \").suppress())\n    INDENT = (Empty() + Empty().set_parse_action(checkSubIndent)).set_name(\"INDENT\")\n    PEER = Empty().set_parse_action(checkPeerIndent).set_name(\"\")\n    UNDENT = Empty().set_parse_action(checkUnindent).set_name(\"UNINDENT\")\n    if indent:\n        smExpr = Group(\n            Opt(NL)\n            + INDENT\n            + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL))\n            + UNDENT\n        )\n    else:\n        smExpr = Group(\n            Opt(NL)\n            + OneOrMore(PEER + Group(blockStatementExpr) + Opt(NL))\n            + Opt(UNDENT)\n        )\n\n    # add a parse action to remove backup_stack from list of backups\n    smExpr.add_parse_action(\n        lambda: backup_stacks.pop(-1) and None if backup_stacks else None\n    )\n    smExpr.set_fail_action(lambda a, b, c, d: reset_stack())\n    blockStatementExpr.ignore(_bslash + LineEnd())\n    return smExpr.set_name(\"indented block\")\n\n\n# it's easy to get these comment structures wrong - they're very common, so may as well make them available\nc_style_comment = Combine(Regex(r\"/\\*(?:[^*]|\\*(?!/))*\") + \"*/\").set_name(\n    \"C style comment\"\n)\n\"Comment of the form ``/* ... */``\"\n\nhtml_comment = Regex(r\"<!--[\\s\\S]*?-->\").set_name(\"HTML comment\")\n\"Comment of the form ``<!-- ... -->``\"\n\nrest_of_line = Regex(r\".*\").leave_whitespace().set_name(\"rest of line\")\ndbl_slash_comment = Regex(r\"//(?:\\\\\\n|[^\\n])*\").set_name(\"// comment\")\n\"Comment of the form ``// ... (to end of line)``\"\n\ncpp_style_comment = Combine(\n    Regex(r\"/\\*(?:[^*]|\\*(?!/))*\") + \"*/\" | dbl_slash_comment\n).set_name(\"C++ style comment\")\n\"Comment of either form :class:`c_style_comment` or :class:`dbl_slash_comment`\"\n\njava_style_comment = cpp_style_comment\n\"Same as :class:`cpp_style_comment`\"\n\npython_style_comment = Regex(r\"#.*\").set_name(\"Python style comment\")\n\"Comment of the form ``# ... (to end of line)``\"\n\n\n# build list of built-in expressions, for future reference if a global default value\n# gets updated\n_builtin_exprs: List[ParserElement] = [\n    v for v in vars().values() if isinstance(v, ParserElement)\n]\n\n\n# pre-PEP8 compatible names\ndelimitedList = delimited_list\ncountedArray = counted_array\nmatchPreviousLiteral = match_previous_literal\nmatchPreviousExpr = match_previous_expr\noneOf = one_of\ndictOf = dict_of\noriginalTextFor = original_text_for\nnestedExpr = nested_expr\nmakeHTMLTags = make_html_tags\nmakeXMLTags = make_xml_tags\nanyOpenTag, anyCloseTag = any_open_tag, any_close_tag\ncommonHTMLEntity = common_html_entity\nreplaceHTMLEntity = replace_html_entity\nopAssoc = OpAssoc\ninfixNotation = infix_notation\ncStyleComment = c_style_comment\nhtmlComment = html_comment\nrestOfLine = rest_of_line\ndblSlashComment = dbl_slash_comment\ncppStyleComment = cpp_style_comment\njavaStyleComment = java_style_comment\npythonStyleComment = python_style_comment\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/pyparsing/results.py",
    "content": "# results.py\nfrom collections.abc import MutableMapping, Mapping, MutableSequence, Iterator\nimport pprint\nfrom weakref import ref as wkref\nfrom typing import Tuple, Any\n\nstr_type: Tuple[type, ...] = (str, bytes)\n_generator_type = type((_ for _ in ()))\n\n\nclass _ParseResultsWithOffset:\n    __slots__ = [\"tup\"]\n\n    def __init__(self, p1, p2):\n        self.tup = (p1, p2)\n\n    def __getitem__(self, i):\n        return self.tup[i]\n\n    def __getstate__(self):\n        return self.tup\n\n    def __setstate__(self, *args):\n        self.tup = args[0]\n\n\nclass ParseResults:\n    \"\"\"Structured parse results, to provide multiple means of access to\n    the parsed data:\n\n    - as a list (``len(results)``)\n    - by list index (``results[0], results[1]``, etc.)\n    - by attribute (``results.<results_name>`` - see :class:`ParserElement.set_results_name`)\n\n    Example::\n\n        integer = Word(nums)\n        date_str = (integer.set_results_name(\"year\") + '/'\n                    + integer.set_results_name(\"month\") + '/'\n                    + integer.set_results_name(\"day\"))\n        # equivalent form:\n        # date_str = (integer(\"year\") + '/'\n        #             + integer(\"month\") + '/'\n        #             + integer(\"day\"))\n\n        # parse_string returns a ParseResults object\n        result = date_str.parse_string(\"1999/12/31\")\n\n        def test(s, fn=repr):\n            print(\"{} -> {}\".format(s, fn(eval(s))))\n        test(\"list(result)\")\n        test(\"result[0]\")\n        test(\"result['month']\")\n        test(\"result.day\")\n        test(\"'month' in result\")\n        test(\"'minutes' in result\")\n        test(\"result.dump()\", str)\n\n    prints::\n\n        list(result) -> ['1999', '/', '12', '/', '31']\n        result[0] -> '1999'\n        result['month'] -> '12'\n        result.day -> '31'\n        'month' in result -> True\n        'minutes' in result -> False\n        result.dump() -> ['1999', '/', '12', '/', '31']\n        - day: '31'\n        - month: '12'\n        - year: '1999'\n    \"\"\"\n\n    _null_values: Tuple[Any, ...] = (None, [], \"\", ())\n\n    __slots__ = [\n        \"_name\",\n        \"_parent\",\n        \"_all_names\",\n        \"_modal\",\n        \"_toklist\",\n        \"_tokdict\",\n        \"__weakref__\",\n    ]\n\n    class List(list):\n        \"\"\"\n        Simple wrapper class to distinguish parsed list results that should be preserved\n        as actual Python lists, instead of being converted to :class:`ParseResults`:\n\n            LBRACK, RBRACK = map(pp.Suppress, \"[]\")\n            element = pp.Forward()\n            item = ppc.integer\n            element_list = LBRACK + pp.delimited_list(element) + RBRACK\n\n            # add parse actions to convert from ParseResults to actual Python collection types\n            def as_python_list(t):\n                return pp.ParseResults.List(t.as_list())\n            element_list.add_parse_action(as_python_list)\n\n            element <<= item | element_list\n\n            element.run_tests('''\n                100\n                [2,3,4]\n                [[2, 1],3,4]\n                [(2, 1),3,4]\n                (2,3,4)\n                ''', post_parse=lambda s, r: (r[0], type(r[0])))\n\n        prints:\n\n            100\n            (100, <class 'int'>)\n\n            [2,3,4]\n            ([2, 3, 4], <class 'list'>)\n\n            [[2, 1],3,4]\n            ([[2, 1], 3, 4], <class 'list'>)\n\n        (Used internally by :class:`Group` when `aslist=True`.)\n        \"\"\"\n\n        def __new__(cls, contained=None):\n            if contained is None:\n                contained = []\n\n            if not isinstance(contained, list):\n                raise TypeError(\n                    \"{} may only be constructed with a list,\"\n                    \" not {}\".format(cls.__name__, type(contained).__name__)\n                )\n\n            return list.__new__(cls)\n\n    def __new__(cls, toklist=None, name=None, **kwargs):\n        if isinstance(toklist, ParseResults):\n            return toklist\n        self = object.__new__(cls)\n        self._name = None\n        self._parent = None\n        self._all_names = set()\n\n        if toklist is None:\n            self._toklist = []\n        elif isinstance(toklist, (list, _generator_type)):\n            self._toklist = (\n                [toklist[:]]\n                if isinstance(toklist, ParseResults.List)\n                else list(toklist)\n            )\n        else:\n            self._toklist = [toklist]\n        self._tokdict = dict()\n        return self\n\n    # Performance tuning: we construct a *lot* of these, so keep this\n    # constructor as small and fast as possible\n    def __init__(\n        self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance\n    ):\n        self._modal = modal\n        if name is not None and name != \"\":\n            if isinstance(name, int):\n                name = str(name)\n            if not modal:\n                self._all_names = {name}\n            self._name = name\n            if toklist not in self._null_values:\n                if isinstance(toklist, (str_type, type)):\n                    toklist = [toklist]\n                if asList:\n                    if isinstance(toklist, ParseResults):\n                        self[name] = _ParseResultsWithOffset(\n                            ParseResults(toklist._toklist), 0\n                        )\n                    else:\n                        self[name] = _ParseResultsWithOffset(\n                            ParseResults(toklist[0]), 0\n                        )\n                    self[name]._name = name\n                else:\n                    try:\n                        self[name] = toklist[0]\n                    except (KeyError, TypeError, IndexError):\n                        if toklist is not self:\n                            self[name] = toklist\n                        else:\n                            self._name = name\n\n    def __getitem__(self, i):\n        if isinstance(i, (int, slice)):\n            return self._toklist[i]\n        else:\n            if i not in self._all_names:\n                return self._tokdict[i][-1][0]\n            else:\n                return ParseResults([v[0] for v in self._tokdict[i]])\n\n    def __setitem__(self, k, v, isinstance=isinstance):\n        if isinstance(v, _ParseResultsWithOffset):\n            self._tokdict[k] = self._tokdict.get(k, list()) + [v]\n            sub = v[0]\n        elif isinstance(k, (int, slice)):\n            self._toklist[k] = v\n            sub = v\n        else:\n            self._tokdict[k] = self._tokdict.get(k, list()) + [\n                _ParseResultsWithOffset(v, 0)\n            ]\n            sub = v\n        if isinstance(sub, ParseResults):\n            sub._parent = wkref(self)\n\n    def __delitem__(self, i):\n        if isinstance(i, (int, slice)):\n            mylen = len(self._toklist)\n            del self._toklist[i]\n\n            # convert int to slice\n            if isinstance(i, int):\n                if i < 0:\n                    i += mylen\n                i = slice(i, i + 1)\n            # get removed indices\n            removed = list(range(*i.indices(mylen)))\n            removed.reverse()\n            # fixup indices in token dictionary\n            for name, occurrences in self._tokdict.items():\n                for j in removed:\n                    for k, (value, position) in enumerate(occurrences):\n                        occurrences[k] = _ParseResultsWithOffset(\n                            value, position - (position > j)\n                        )\n        else:\n            del self._tokdict[i]\n\n    def __contains__(self, k) -> bool:\n        return k in self._tokdict\n\n    def __len__(self) -> int:\n        return len(self._toklist)\n\n    def __bool__(self) -> bool:\n        return not not (self._toklist or self._tokdict)\n\n    def __iter__(self) -> Iterator:\n        return iter(self._toklist)\n\n    def __reversed__(self) -> Iterator:\n        return iter(self._toklist[::-1])\n\n    def keys(self):\n        return iter(self._tokdict)\n\n    def values(self):\n        return (self[k] for k in self.keys())\n\n    def items(self):\n        return ((k, self[k]) for k in self.keys())\n\n    def haskeys(self) -> bool:\n        \"\"\"\n        Since ``keys()`` returns an iterator, this method is helpful in bypassing\n        code that looks for the existence of any defined results names.\"\"\"\n        return bool(self._tokdict)\n\n    def pop(self, *args, **kwargs):\n        \"\"\"\n        Removes and returns item at specified index (default= ``last``).\n        Supports both ``list`` and ``dict`` semantics for ``pop()``. If\n        passed no argument or an integer argument, it will use ``list``\n        semantics and pop tokens from the list of parsed tokens. If passed\n        a non-integer argument (most likely a string), it will use ``dict``\n        semantics and pop the corresponding value from any defined results\n        names. A second default return value argument is supported, just as in\n        ``dict.pop()``.\n\n        Example::\n\n            numlist = Word(nums)[...]\n            print(numlist.parse_string(\"0 123 321\")) # -> ['0', '123', '321']\n\n            def remove_first(tokens):\n                tokens.pop(0)\n            numlist.add_parse_action(remove_first)\n            print(numlist.parse_string(\"0 123 321\")) # -> ['123', '321']\n\n            label = Word(alphas)\n            patt = label(\"LABEL\") + Word(nums)[1, ...]\n            print(patt.parse_string(\"AAB 123 321\").dump())\n\n            # Use pop() in a parse action to remove named result (note that corresponding value is not\n            # removed from list form of results)\n            def remove_LABEL(tokens):\n                tokens.pop(\"LABEL\")\n                return tokens\n            patt.add_parse_action(remove_LABEL)\n            print(patt.parse_string(\"AAB 123 321\").dump())\n\n        prints::\n\n            ['AAB', '123', '321']\n            - LABEL: 'AAB'\n\n            ['AAB', '123', '321']\n        \"\"\"\n        if not args:\n            args = [-1]\n        for k, v in kwargs.items():\n            if k == \"default\":\n                args = (args[0], v)\n            else:\n                raise TypeError(\n                    \"pop() got an unexpected keyword argument {!r}\".format(k)\n                )\n        if isinstance(args[0], int) or len(args) == 1 or args[0] in self:\n            index = args[0]\n            ret = self[index]\n            del self[index]\n            return ret\n        else:\n            defaultvalue = args[1]\n            return defaultvalue\n\n    def get(self, key, default_value=None):\n        \"\"\"\n        Returns named result matching the given key, or if there is no\n        such name, then returns the given ``default_value`` or ``None`` if no\n        ``default_value`` is specified.\n\n        Similar to ``dict.get()``.\n\n        Example::\n\n            integer = Word(nums)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            result = date_str.parse_string(\"1999/12/31\")\n            print(result.get(\"year\")) # -> '1999'\n            print(result.get(\"hour\", \"not specified\")) # -> 'not specified'\n            print(result.get(\"hour\")) # -> None\n        \"\"\"\n        if key in self:\n            return self[key]\n        else:\n            return default_value\n\n    def insert(self, index, ins_string):\n        \"\"\"\n        Inserts new element at location index in the list of parsed tokens.\n\n        Similar to ``list.insert()``.\n\n        Example::\n\n            numlist = Word(nums)[...]\n            print(numlist.parse_string(\"0 123 321\")) # -> ['0', '123', '321']\n\n            # use a parse action to insert the parse location in the front of the parsed results\n            def insert_locn(locn, tokens):\n                tokens.insert(0, locn)\n            numlist.add_parse_action(insert_locn)\n            print(numlist.parse_string(\"0 123 321\")) # -> [0, '0', '123', '321']\n        \"\"\"\n        self._toklist.insert(index, ins_string)\n        # fixup indices in token dictionary\n        for name, occurrences in self._tokdict.items():\n            for k, (value, position) in enumerate(occurrences):\n                occurrences[k] = _ParseResultsWithOffset(\n                    value, position + (position > index)\n                )\n\n    def append(self, item):\n        \"\"\"\n        Add single element to end of ``ParseResults`` list of elements.\n\n        Example::\n\n            numlist = Word(nums)[...]\n            print(numlist.parse_string(\"0 123 321\")) # -> ['0', '123', '321']\n\n            # use a parse action to compute the sum of the parsed integers, and add it to the end\n            def append_sum(tokens):\n                tokens.append(sum(map(int, tokens)))\n            numlist.add_parse_action(append_sum)\n            print(numlist.parse_string(\"0 123 321\")) # -> ['0', '123', '321', 444]\n        \"\"\"\n        self._toklist.append(item)\n\n    def extend(self, itemseq):\n        \"\"\"\n        Add sequence of elements to end of ``ParseResults`` list of elements.\n\n        Example::\n\n            patt = Word(alphas)[1, ...]\n\n            # use a parse action to append the reverse of the matched strings, to make a palindrome\n            def make_palindrome(tokens):\n                tokens.extend(reversed([t[::-1] for t in tokens]))\n                return ''.join(tokens)\n            patt.add_parse_action(make_palindrome)\n            print(patt.parse_string(\"lskdj sdlkjf lksd\")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'\n        \"\"\"\n        if isinstance(itemseq, ParseResults):\n            self.__iadd__(itemseq)\n        else:\n            self._toklist.extend(itemseq)\n\n    def clear(self):\n        \"\"\"\n        Clear all elements and results names.\n        \"\"\"\n        del self._toklist[:]\n        self._tokdict.clear()\n\n    def __getattr__(self, name):\n        try:\n            return self[name]\n        except KeyError:\n            if name.startswith(\"__\"):\n                raise AttributeError(name)\n            return \"\"\n\n    def __add__(self, other) -> \"ParseResults\":\n        ret = self.copy()\n        ret += other\n        return ret\n\n    def __iadd__(self, other) -> \"ParseResults\":\n        if other._tokdict:\n            offset = len(self._toklist)\n            addoffset = lambda a: offset if a < 0 else a + offset\n            otheritems = other._tokdict.items()\n            otherdictitems = [\n                (k, _ParseResultsWithOffset(v[0], addoffset(v[1])))\n                for k, vlist in otheritems\n                for v in vlist\n            ]\n            for k, v in otherdictitems:\n                self[k] = v\n                if isinstance(v[0], ParseResults):\n                    v[0]._parent = wkref(self)\n\n        self._toklist += other._toklist\n        self._all_names |= other._all_names\n        return self\n\n    def __radd__(self, other) -> \"ParseResults\":\n        if isinstance(other, int) and other == 0:\n            # useful for merging many ParseResults using sum() builtin\n            return self.copy()\n        else:\n            # this may raise a TypeError - so be it\n            return other + self\n\n    def __repr__(self) -> str:\n        return \"{}({!r}, {})\".format(type(self).__name__, self._toklist, self.as_dict())\n\n    def __str__(self) -> str:\n        return (\n            \"[\"\n            + \", \".join(\n                [\n                    str(i) if isinstance(i, ParseResults) else repr(i)\n                    for i in self._toklist\n                ]\n            )\n            + \"]\"\n        )\n\n    def _asStringList(self, sep=\"\"):\n        out = []\n        for item in self._toklist:\n            if out and sep:\n                out.append(sep)\n            if isinstance(item, ParseResults):\n                out += item._asStringList()\n            else:\n                out.append(str(item))\n        return out\n\n    def as_list(self) -> list:\n        \"\"\"\n        Returns the parse results as a nested list of matching tokens, all converted to strings.\n\n        Example::\n\n            patt = Word(alphas)[1, ...]\n            result = patt.parse_string(\"sldkj lsdkj sldkj\")\n            # even though the result prints in string-like form, it is actually a pyparsing ParseResults\n            print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']\n\n            # Use as_list() to create an actual list\n            result_list = result.as_list()\n            print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']\n        \"\"\"\n        return [\n            res.as_list() if isinstance(res, ParseResults) else res\n            for res in self._toklist\n        ]\n\n    def as_dict(self) -> dict:\n        \"\"\"\n        Returns the named parse results as a nested dictionary.\n\n        Example::\n\n            integer = Word(nums)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            result = date_str.parse_string('12/31/1999')\n            print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})\n\n            result_dict = result.as_dict()\n            print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}\n\n            # even though a ParseResults supports dict-like access, sometime you just need to have a dict\n            import json\n            print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable\n            print(json.dumps(result.as_dict())) # -> {\"month\": \"31\", \"day\": \"1999\", \"year\": \"12\"}\n        \"\"\"\n\n        def to_item(obj):\n            if isinstance(obj, ParseResults):\n                return obj.as_dict() if obj.haskeys() else [to_item(v) for v in obj]\n            else:\n                return obj\n\n        return dict((k, to_item(v)) for k, v in self.items())\n\n    def copy(self) -> \"ParseResults\":\n        \"\"\"\n        Returns a new copy of a :class:`ParseResults` object.\n        \"\"\"\n        ret = ParseResults(self._toklist)\n        ret._tokdict = self._tokdict.copy()\n        ret._parent = self._parent\n        ret._all_names |= self._all_names\n        ret._name = self._name\n        return ret\n\n    def get_name(self):\n        r\"\"\"\n        Returns the results name for this token expression. Useful when several\n        different expressions might match at a particular location.\n\n        Example::\n\n            integer = Word(nums)\n            ssn_expr = Regex(r\"\\d\\d\\d-\\d\\d-\\d\\d\\d\\d\")\n            house_number_expr = Suppress('#') + Word(nums, alphanums)\n            user_data = (Group(house_number_expr)(\"house_number\")\n                        | Group(ssn_expr)(\"ssn\")\n                        | Group(integer)(\"age\"))\n            user_info = user_data[1, ...]\n\n            result = user_info.parse_string(\"22 111-22-3333 #221B\")\n            for item in result:\n                print(item.get_name(), ':', item[0])\n\n        prints::\n\n            age : 22\n            ssn : 111-22-3333\n            house_number : 221B\n        \"\"\"\n        if self._name:\n            return self._name\n        elif self._parent:\n            par = self._parent()\n\n            def find_in_parent(sub):\n                return next(\n                    (\n                        k\n                        for k, vlist in par._tokdict.items()\n                        for v, loc in vlist\n                        if sub is v\n                    ),\n                    None,\n                )\n\n            return find_in_parent(self) if par else None\n        elif (\n            len(self) == 1\n            and len(self._tokdict) == 1\n            and next(iter(self._tokdict.values()))[0][1] in (0, -1)\n        ):\n            return next(iter(self._tokdict.keys()))\n        else:\n            return None\n\n    def dump(self, indent=\"\", full=True, include_list=True, _depth=0) -> str:\n        \"\"\"\n        Diagnostic method for listing out the contents of\n        a :class:`ParseResults`. Accepts an optional ``indent`` argument so\n        that this string can be embedded in a nested display of other data.\n\n        Example::\n\n            integer = Word(nums)\n            date_str = integer(\"year\") + '/' + integer(\"month\") + '/' + integer(\"day\")\n\n            result = date_str.parse_string('1999/12/31')\n            print(result.dump())\n\n        prints::\n\n            ['1999', '/', '12', '/', '31']\n            - day: '31'\n            - month: '12'\n            - year: '1999'\n        \"\"\"\n        out = []\n        NL = \"\\n\"\n        out.append(indent + str(self.as_list()) if include_list else \"\")\n\n        if full:\n            if self.haskeys():\n                items = sorted((str(k), v) for k, v in self.items())\n                for k, v in items:\n                    if out:\n                        out.append(NL)\n                    out.append(\"{}{}- {}: \".format(indent, (\"  \" * _depth), k))\n                    if isinstance(v, ParseResults):\n                        if v:\n                            out.append(\n                                v.dump(\n                                    indent=indent,\n                                    full=full,\n                                    include_list=include_list,\n                                    _depth=_depth + 1,\n                                )\n                            )\n                        else:\n                            out.append(str(v))\n                    else:\n                        out.append(repr(v))\n            if any(isinstance(vv, ParseResults) for vv in self):\n                v = self\n                for i, vv in enumerate(v):\n                    if isinstance(vv, ParseResults):\n                        out.append(\n                            \"\\n{}{}[{}]:\\n{}{}{}\".format(\n                                indent,\n                                (\"  \" * (_depth)),\n                                i,\n                                indent,\n                                (\"  \" * (_depth + 1)),\n                                vv.dump(\n                                    indent=indent,\n                                    full=full,\n                                    include_list=include_list,\n                                    _depth=_depth + 1,\n                                ),\n                            )\n                        )\n                    else:\n                        out.append(\n                            \"\\n%s%s[%d]:\\n%s%s%s\"\n                            % (\n                                indent,\n                                (\"  \" * (_depth)),\n                                i,\n                                indent,\n                                (\"  \" * (_depth + 1)),\n                                str(vv),\n                            )\n                        )\n\n        return \"\".join(out)\n\n    def pprint(self, *args, **kwargs):\n        \"\"\"\n        Pretty-printer for parsed results as a list, using the\n        `pprint <https://docs.python.org/3/library/pprint.html>`_ module.\n        Accepts additional positional or keyword args as defined for\n        `pprint.pprint <https://docs.python.org/3/library/pprint.html#pprint.pprint>`_ .\n\n        Example::\n\n            ident = Word(alphas, alphanums)\n            num = Word(nums)\n            func = Forward()\n            term = ident | num | Group('(' + func + ')')\n            func <<= ident + Group(Optional(delimited_list(term)))\n            result = func.parse_string(\"fna a,b,(fnb c,d,200),100\")\n            result.pprint(width=40)\n\n        prints::\n\n            ['fna',\n             ['a',\n              'b',\n              ['(', 'fnb', ['c', 'd', '200'], ')'],\n              '100']]\n        \"\"\"\n        pprint.pprint(self.as_list(), *args, **kwargs)\n\n    # add support for pickle protocol\n    def __getstate__(self):\n        return (\n            self._toklist,\n            (\n                self._tokdict.copy(),\n                self._parent is not None and self._parent() or None,\n                self._all_names,\n                self._name,\n            ),\n        )\n\n    def __setstate__(self, state):\n        self._toklist, (self._tokdict, par, inAccumNames, self._name) = state\n        self._all_names = set(inAccumNames)\n        if par is not None:\n            self._parent = wkref(par)\n        else:\n            self._parent = None\n\n    def __getnewargs__(self):\n        return self._toklist, self._name\n\n    def __dir__(self):\n        return dir(type(self)) + list(self.keys())\n\n    @classmethod\n    def from_dict(cls, other, name=None) -> \"ParseResults\":\n        \"\"\"\n        Helper classmethod to construct a ``ParseResults`` from a ``dict``, preserving the\n        name-value relations as results names. If an optional ``name`` argument is\n        given, a nested ``ParseResults`` will be returned.\n        \"\"\"\n\n        def is_iterable(obj):\n            try:\n                iter(obj)\n            except Exception:\n                return False\n            else:\n                return not isinstance(obj, str_type)\n\n        ret = cls([])\n        for k, v in other.items():\n            if isinstance(v, Mapping):\n                ret += cls.from_dict(v, name=k)\n            else:\n                ret += cls([v], name=k, asList=is_iterable(v))\n        if name is not None:\n            ret = cls([ret], name=name)\n        return ret\n\n    asList = as_list\n    asDict = as_dict\n    getName = get_name\n\n\nMutableMapping.register(ParseResults)\nMutableSequence.register(ParseResults)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/pyparsing/testing.py",
    "content": "# testing.py\n\nfrom contextlib import contextmanager\nimport typing\n\nfrom .core import (\n    ParserElement,\n    ParseException,\n    Keyword,\n    __diag__,\n    __compat__,\n)\n\n\nclass pyparsing_test:\n    \"\"\"\n    namespace class for classes useful in writing unit tests\n    \"\"\"\n\n    class reset_pyparsing_context:\n        \"\"\"\n        Context manager to be used when writing unit tests that modify pyparsing config values:\n        - packrat parsing\n        - bounded recursion parsing\n        - default whitespace characters.\n        - default keyword characters\n        - literal string auto-conversion class\n        - __diag__ settings\n\n        Example::\n\n            with reset_pyparsing_context():\n                # test that literals used to construct a grammar are automatically suppressed\n                ParserElement.inlineLiteralsUsing(Suppress)\n\n                term = Word(alphas) | Word(nums)\n                group = Group('(' + term[...] + ')')\n\n                # assert that the '()' characters are not included in the parsed tokens\n                self.assertParseAndCheckList(group, \"(abc 123 def)\", ['abc', '123', 'def'])\n\n            # after exiting context manager, literals are converted to Literal expressions again\n        \"\"\"\n\n        def __init__(self):\n            self._save_context = {}\n\n        def save(self):\n            self._save_context[\"default_whitespace\"] = ParserElement.DEFAULT_WHITE_CHARS\n            self._save_context[\"default_keyword_chars\"] = Keyword.DEFAULT_KEYWORD_CHARS\n\n            self._save_context[\n                \"literal_string_class\"\n            ] = ParserElement._literalStringClass\n\n            self._save_context[\"verbose_stacktrace\"] = ParserElement.verbose_stacktrace\n\n            self._save_context[\"packrat_enabled\"] = ParserElement._packratEnabled\n            if ParserElement._packratEnabled:\n                self._save_context[\n                    \"packrat_cache_size\"\n                ] = ParserElement.packrat_cache.size\n            else:\n                self._save_context[\"packrat_cache_size\"] = None\n            self._save_context[\"packrat_parse\"] = ParserElement._parse\n            self._save_context[\n                \"recursion_enabled\"\n            ] = ParserElement._left_recursion_enabled\n\n            self._save_context[\"__diag__\"] = {\n                name: getattr(__diag__, name) for name in __diag__._all_names\n            }\n\n            self._save_context[\"__compat__\"] = {\n                \"collect_all_And_tokens\": __compat__.collect_all_And_tokens\n            }\n\n            return self\n\n        def restore(self):\n            # reset pyparsing global state\n            if (\n                ParserElement.DEFAULT_WHITE_CHARS\n                != self._save_context[\"default_whitespace\"]\n            ):\n                ParserElement.set_default_whitespace_chars(\n                    self._save_context[\"default_whitespace\"]\n                )\n\n            ParserElement.verbose_stacktrace = self._save_context[\"verbose_stacktrace\"]\n\n            Keyword.DEFAULT_KEYWORD_CHARS = self._save_context[\"default_keyword_chars\"]\n            ParserElement.inlineLiteralsUsing(\n                self._save_context[\"literal_string_class\"]\n            )\n\n            for name, value in self._save_context[\"__diag__\"].items():\n                (__diag__.enable if value else __diag__.disable)(name)\n\n            ParserElement._packratEnabled = False\n            if self._save_context[\"packrat_enabled\"]:\n                ParserElement.enable_packrat(self._save_context[\"packrat_cache_size\"])\n            else:\n                ParserElement._parse = self._save_context[\"packrat_parse\"]\n            ParserElement._left_recursion_enabled = self._save_context[\n                \"recursion_enabled\"\n            ]\n\n            __compat__.collect_all_And_tokens = self._save_context[\"__compat__\"]\n\n            return self\n\n        def copy(self):\n            ret = type(self)()\n            ret._save_context.update(self._save_context)\n            return ret\n\n        def __enter__(self):\n            return self.save()\n\n        def __exit__(self, *args):\n            self.restore()\n\n    class TestParseResultsAsserts:\n        \"\"\"\n        A mixin class to add parse results assertion methods to normal unittest.TestCase classes.\n        \"\"\"\n\n        def assertParseResultsEquals(\n            self, result, expected_list=None, expected_dict=None, msg=None\n        ):\n            \"\"\"\n            Unit test assertion to compare a :class:`ParseResults` object with an optional ``expected_list``,\n            and compare any defined results names with an optional ``expected_dict``.\n            \"\"\"\n            if expected_list is not None:\n                self.assertEqual(expected_list, result.as_list(), msg=msg)\n            if expected_dict is not None:\n                self.assertEqual(expected_dict, result.as_dict(), msg=msg)\n\n        def assertParseAndCheckList(\n            self, expr, test_string, expected_list, msg=None, verbose=True\n        ):\n            \"\"\"\n            Convenience wrapper assert to test a parser element and input string, and assert that\n            the resulting ``ParseResults.asList()`` is equal to the ``expected_list``.\n            \"\"\"\n            result = expr.parse_string(test_string, parse_all=True)\n            if verbose:\n                print(result.dump())\n            else:\n                print(result.as_list())\n            self.assertParseResultsEquals(result, expected_list=expected_list, msg=msg)\n\n        def assertParseAndCheckDict(\n            self, expr, test_string, expected_dict, msg=None, verbose=True\n        ):\n            \"\"\"\n            Convenience wrapper assert to test a parser element and input string, and assert that\n            the resulting ``ParseResults.asDict()`` is equal to the ``expected_dict``.\n            \"\"\"\n            result = expr.parse_string(test_string, parseAll=True)\n            if verbose:\n                print(result.dump())\n            else:\n                print(result.as_list())\n            self.assertParseResultsEquals(result, expected_dict=expected_dict, msg=msg)\n\n        def assertRunTestResults(\n            self, run_tests_report, expected_parse_results=None, msg=None\n        ):\n            \"\"\"\n            Unit test assertion to evaluate output of ``ParserElement.runTests()``. If a list of\n            list-dict tuples is given as the ``expected_parse_results`` argument, then these are zipped\n            with the report tuples returned by ``runTests`` and evaluated using ``assertParseResultsEquals``.\n            Finally, asserts that the overall ``runTests()`` success value is ``True``.\n\n            :param run_tests_report: tuple(bool, [tuple(str, ParseResults or Exception)]) returned from runTests\n            :param expected_parse_results (optional): [tuple(str, list, dict, Exception)]\n            \"\"\"\n            run_test_success, run_test_results = run_tests_report\n\n            if expected_parse_results is not None:\n                merged = [\n                    (*rpt, expected)\n                    for rpt, expected in zip(run_test_results, expected_parse_results)\n                ]\n                for test_string, result, expected in merged:\n                    # expected should be a tuple containing a list and/or a dict or an exception,\n                    # and optional failure message string\n                    # an empty tuple will skip any result validation\n                    fail_msg = next(\n                        (exp for exp in expected if isinstance(exp, str)), None\n                    )\n                    expected_exception = next(\n                        (\n                            exp\n                            for exp in expected\n                            if isinstance(exp, type) and issubclass(exp, Exception)\n                        ),\n                        None,\n                    )\n                    if expected_exception is not None:\n                        with self.assertRaises(\n                            expected_exception=expected_exception, msg=fail_msg or msg\n                        ):\n                            if isinstance(result, Exception):\n                                raise result\n                    else:\n                        expected_list = next(\n                            (exp for exp in expected if isinstance(exp, list)), None\n                        )\n                        expected_dict = next(\n                            (exp for exp in expected if isinstance(exp, dict)), None\n                        )\n                        if (expected_list, expected_dict) != (None, None):\n                            self.assertParseResultsEquals(\n                                result,\n                                expected_list=expected_list,\n                                expected_dict=expected_dict,\n                                msg=fail_msg or msg,\n                            )\n                        else:\n                            # warning here maybe?\n                            print(\"no validation for {!r}\".format(test_string))\n\n            # do this last, in case some specific test results can be reported instead\n            self.assertTrue(\n                run_test_success, msg=msg if msg is not None else \"failed runTests\"\n            )\n\n        @contextmanager\n        def assertRaisesParseException(self, exc_type=ParseException, msg=None):\n            with self.assertRaises(exc_type, msg=msg):\n                yield\n\n    @staticmethod\n    def with_line_numbers(\n        s: str,\n        start_line: typing.Optional[int] = None,\n        end_line: typing.Optional[int] = None,\n        expand_tabs: bool = True,\n        eol_mark: str = \"|\",\n        mark_spaces: typing.Optional[str] = None,\n        mark_control: typing.Optional[str] = None,\n    ) -> str:\n        \"\"\"\n        Helpful method for debugging a parser - prints a string with line and column numbers.\n        (Line and column numbers are 1-based.)\n\n        :param s: tuple(bool, str - string to be printed with line and column numbers\n        :param start_line: int - (optional) starting line number in s to print (default=1)\n        :param end_line: int - (optional) ending line number in s to print (default=len(s))\n        :param expand_tabs: bool - (optional) expand tabs to spaces, to match the pyparsing default\n        :param eol_mark: str - (optional) string to mark the end of lines, helps visualize trailing spaces (default=\"|\")\n        :param mark_spaces: str - (optional) special character to display in place of spaces\n        :param mark_control: str - (optional) convert non-printing control characters to a placeholding\n                                 character; valid values:\n                                 - \"unicode\" - replaces control chars with Unicode symbols, such as \"␍\" and \"␊\"\n                                 - any single character string - replace control characters with given string\n                                 - None (default) - string is displayed as-is\n\n        :return: str - input string with leading line numbers and column number headers\n        \"\"\"\n        if expand_tabs:\n            s = s.expandtabs()\n        if mark_control is not None:\n            if mark_control == \"unicode\":\n                tbl = str.maketrans(\n                    {c: u for c, u in zip(range(0, 33), range(0x2400, 0x2433))}\n                    | {127: 0x2421}\n                )\n                eol_mark = \"\"\n            else:\n                tbl = str.maketrans(\n                    {c: mark_control for c in list(range(0, 32)) + [127]}\n                )\n            s = s.translate(tbl)\n        if mark_spaces is not None and mark_spaces != \" \":\n            if mark_spaces == \"unicode\":\n                tbl = str.maketrans({9: 0x2409, 32: 0x2423})\n                s = s.translate(tbl)\n            else:\n                s = s.replace(\" \", mark_spaces)\n        if start_line is None:\n            start_line = 1\n        if end_line is None:\n            end_line = len(s)\n        end_line = min(end_line, len(s))\n        start_line = min(max(1, start_line), end_line)\n\n        if mark_control != \"unicode\":\n            s_lines = s.splitlines()[start_line - 1 : end_line]\n        else:\n            s_lines = [line + \"␊\" for line in s.split(\"␊\")[start_line - 1 : end_line]]\n        if not s_lines:\n            return \"\"\n\n        lineno_width = len(str(end_line))\n        max_line_len = max(len(line) for line in s_lines)\n        lead = \" \" * (lineno_width + 1)\n        if max_line_len >= 99:\n            header0 = (\n                lead\n                + \"\".join(\n                    \"{}{}\".format(\" \" * 99, (i + 1) % 100)\n                    for i in range(max(max_line_len // 100, 1))\n                )\n                + \"\\n\"\n            )\n        else:\n            header0 = \"\"\n        header1 = (\n            header0\n            + lead\n            + \"\".join(\n                \"         {}\".format((i + 1) % 10)\n                for i in range(-(-max_line_len // 10))\n            )\n            + \"\\n\"\n        )\n        header2 = lead + \"1234567890\" * (-(-max_line_len // 10)) + \"\\n\"\n        return (\n            header1\n            + header2\n            + \"\\n\".join(\n                \"{:{}d}:{}{}\".format(i, lineno_width, line, eol_mark)\n                for i, line in enumerate(s_lines, start=start_line)\n            )\n            + \"\\n\"\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/pyparsing/unicode.py",
    "content": "# unicode.py\n\nimport sys\nfrom itertools import filterfalse\nfrom typing import List, Tuple, Union\n\n\nclass _lazyclassproperty:\n    def __init__(self, fn):\n        self.fn = fn\n        self.__doc__ = fn.__doc__\n        self.__name__ = fn.__name__\n\n    def __get__(self, obj, cls):\n        if cls is None:\n            cls = type(obj)\n        if not hasattr(cls, \"_intern\") or any(\n            cls._intern is getattr(superclass, \"_intern\", [])\n            for superclass in cls.__mro__[1:]\n        ):\n            cls._intern = {}\n        attrname = self.fn.__name__\n        if attrname not in cls._intern:\n            cls._intern[attrname] = self.fn(cls)\n        return cls._intern[attrname]\n\n\nUnicodeRangeList = List[Union[Tuple[int, int], Tuple[int]]]\n\n\nclass unicode_set:\n    \"\"\"\n    A set of Unicode characters, for language-specific strings for\n    ``alphas``, ``nums``, ``alphanums``, and ``printables``.\n    A unicode_set is defined by a list of ranges in the Unicode character\n    set, in a class attribute ``_ranges``. Ranges can be specified using\n    2-tuples or a 1-tuple, such as::\n\n        _ranges = [\n            (0x0020, 0x007e),\n            (0x00a0, 0x00ff),\n            (0x0100,),\n            ]\n\n    Ranges are left- and right-inclusive. A 1-tuple of (x,) is treated as (x, x).\n\n    A unicode set can also be defined using multiple inheritance of other unicode sets::\n\n        class CJK(Chinese, Japanese, Korean):\n            pass\n    \"\"\"\n\n    _ranges: UnicodeRangeList = []\n\n    @_lazyclassproperty\n    def _chars_for_ranges(cls):\n        ret = []\n        for cc in cls.__mro__:\n            if cc is unicode_set:\n                break\n            for rr in getattr(cc, \"_ranges\", ()):\n                ret.extend(range(rr[0], rr[-1] + 1))\n        return [chr(c) for c in sorted(set(ret))]\n\n    @_lazyclassproperty\n    def printables(cls):\n        \"all non-whitespace characters in this range\"\n        return \"\".join(filterfalse(str.isspace, cls._chars_for_ranges))\n\n    @_lazyclassproperty\n    def alphas(cls):\n        \"all alphabetic characters in this range\"\n        return \"\".join(filter(str.isalpha, cls._chars_for_ranges))\n\n    @_lazyclassproperty\n    def nums(cls):\n        \"all numeric digit characters in this range\"\n        return \"\".join(filter(str.isdigit, cls._chars_for_ranges))\n\n    @_lazyclassproperty\n    def alphanums(cls):\n        \"all alphanumeric characters in this range\"\n        return cls.alphas + cls.nums\n\n    @_lazyclassproperty\n    def identchars(cls):\n        \"all characters in this range that are valid identifier characters, plus underscore '_'\"\n        return \"\".join(\n            sorted(\n                set(\n                    \"\".join(filter(str.isidentifier, cls._chars_for_ranges))\n                    + \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzªµº\"\n                    + \"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\"\n                    + \"_\"\n                )\n            )\n        )\n\n    @_lazyclassproperty\n    def identbodychars(cls):\n        \"\"\"\n        all characters in this range that are valid identifier body characters,\n        plus the digits 0-9\n        \"\"\"\n        return \"\".join(\n            sorted(\n                set(\n                    cls.identchars\n                    + \"0123456789\"\n                    + \"\".join(\n                        [c for c in cls._chars_for_ranges if (\"_\" + c).isidentifier()]\n                    )\n                )\n            )\n        )\n\n\nclass pyparsing_unicode(unicode_set):\n    \"\"\"\n    A namespace class for defining common language unicode_sets.\n    \"\"\"\n\n    # fmt: off\n\n    # define ranges in language character sets\n    _ranges: UnicodeRangeList = [\n        (0x0020, sys.maxunicode),\n    ]\n\n    class BasicMultilingualPlane(unicode_set):\n        \"Unicode set for the Basic Multilingual Plane\"\n        _ranges: UnicodeRangeList = [\n            (0x0020, 0xFFFF),\n        ]\n\n    class Latin1(unicode_set):\n        \"Unicode set for Latin-1 Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0020, 0x007E),\n            (0x00A0, 0x00FF),\n        ]\n\n    class LatinA(unicode_set):\n        \"Unicode set for Latin-A Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0100, 0x017F),\n        ]\n\n    class LatinB(unicode_set):\n        \"Unicode set for Latin-B Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0180, 0x024F),\n        ]\n\n    class Greek(unicode_set):\n        \"Unicode set for Greek Unicode Character Ranges\"\n        _ranges: UnicodeRangeList = [\n            (0x0342, 0x0345),\n            (0x0370, 0x0377),\n            (0x037A, 0x037F),\n            (0x0384, 0x038A),\n            (0x038C,),\n            (0x038E, 0x03A1),\n            (0x03A3, 0x03E1),\n            (0x03F0, 0x03FF),\n            (0x1D26, 0x1D2A),\n            (0x1D5E,),\n            (0x1D60,),\n            (0x1D66, 0x1D6A),\n            (0x1F00, 0x1F15),\n            (0x1F18, 0x1F1D),\n            (0x1F20, 0x1F45),\n            (0x1F48, 0x1F4D),\n            (0x1F50, 0x1F57),\n            (0x1F59,),\n            (0x1F5B,),\n            (0x1F5D,),\n            (0x1F5F, 0x1F7D),\n            (0x1F80, 0x1FB4),\n            (0x1FB6, 0x1FC4),\n            (0x1FC6, 0x1FD3),\n            (0x1FD6, 0x1FDB),\n            (0x1FDD, 0x1FEF),\n            (0x1FF2, 0x1FF4),\n            (0x1FF6, 0x1FFE),\n            (0x2129,),\n            (0x2719, 0x271A),\n            (0xAB65,),\n            (0x10140, 0x1018D),\n            (0x101A0,),\n            (0x1D200, 0x1D245),\n            (0x1F7A1, 0x1F7A7),\n        ]\n\n    class Cyrillic(unicode_set):\n        \"Unicode set for Cyrillic Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0400, 0x052F),\n            (0x1C80, 0x1C88),\n            (0x1D2B,),\n            (0x1D78,),\n            (0x2DE0, 0x2DFF),\n            (0xA640, 0xA672),\n            (0xA674, 0xA69F),\n            (0xFE2E, 0xFE2F),\n        ]\n\n    class Chinese(unicode_set):\n        \"Unicode set for Chinese Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x2E80, 0x2E99),\n            (0x2E9B, 0x2EF3),\n            (0x31C0, 0x31E3),\n            (0x3400, 0x4DB5),\n            (0x4E00, 0x9FEF),\n            (0xA700, 0xA707),\n            (0xF900, 0xFA6D),\n            (0xFA70, 0xFAD9),\n            (0x16FE2, 0x16FE3),\n            (0x1F210, 0x1F212),\n            (0x1F214, 0x1F23B),\n            (0x1F240, 0x1F248),\n            (0x20000, 0x2A6D6),\n            (0x2A700, 0x2B734),\n            (0x2B740, 0x2B81D),\n            (0x2B820, 0x2CEA1),\n            (0x2CEB0, 0x2EBE0),\n            (0x2F800, 0x2FA1D),\n        ]\n\n    class Japanese(unicode_set):\n        \"Unicode set for Japanese Unicode Character Range, combining Kanji, Hiragana, and Katakana ranges\"\n        _ranges: UnicodeRangeList = []\n\n        class Kanji(unicode_set):\n            \"Unicode set for Kanji Unicode Character Range\"\n            _ranges: UnicodeRangeList = [\n                (0x4E00, 0x9FBF),\n                (0x3000, 0x303F),\n            ]\n\n        class Hiragana(unicode_set):\n            \"Unicode set for Hiragana Unicode Character Range\"\n            _ranges: UnicodeRangeList = [\n                (0x3041, 0x3096),\n                (0x3099, 0x30A0),\n                (0x30FC,),\n                (0xFF70,),\n                (0x1B001,),\n                (0x1B150, 0x1B152),\n                (0x1F200,),\n            ]\n\n        class Katakana(unicode_set):\n            \"Unicode set for Katakana  Unicode Character Range\"\n            _ranges: UnicodeRangeList = [\n                (0x3099, 0x309C),\n                (0x30A0, 0x30FF),\n                (0x31F0, 0x31FF),\n                (0x32D0, 0x32FE),\n                (0xFF65, 0xFF9F),\n                (0x1B000,),\n                (0x1B164, 0x1B167),\n                (0x1F201, 0x1F202),\n                (0x1F213,),\n            ]\n\n    class Hangul(unicode_set):\n        \"Unicode set for Hangul (Korean) Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x1100, 0x11FF),\n            (0x302E, 0x302F),\n            (0x3131, 0x318E),\n            (0x3200, 0x321C),\n            (0x3260, 0x327B),\n            (0x327E,),\n            (0xA960, 0xA97C),\n            (0xAC00, 0xD7A3),\n            (0xD7B0, 0xD7C6),\n            (0xD7CB, 0xD7FB),\n            (0xFFA0, 0xFFBE),\n            (0xFFC2, 0xFFC7),\n            (0xFFCA, 0xFFCF),\n            (0xFFD2, 0xFFD7),\n            (0xFFDA, 0xFFDC),\n        ]\n\n    Korean = Hangul\n\n    class CJK(Chinese, Japanese, Hangul):\n        \"Unicode set for combined Chinese, Japanese, and Korean (CJK) Unicode Character Range\"\n\n    class Thai(unicode_set):\n        \"Unicode set for Thai Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0E01, 0x0E3A),\n            (0x0E3F, 0x0E5B)\n        ]\n\n    class Arabic(unicode_set):\n        \"Unicode set for Arabic Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0600, 0x061B),\n            (0x061E, 0x06FF),\n            (0x0700, 0x077F),\n        ]\n\n    class Hebrew(unicode_set):\n        \"Unicode set for Hebrew Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0591, 0x05C7),\n            (0x05D0, 0x05EA),\n            (0x05EF, 0x05F4),\n            (0xFB1D, 0xFB36),\n            (0xFB38, 0xFB3C),\n            (0xFB3E,),\n            (0xFB40, 0xFB41),\n            (0xFB43, 0xFB44),\n            (0xFB46, 0xFB4F),\n        ]\n\n    class Devanagari(unicode_set):\n        \"Unicode set for Devanagari Unicode Character Range\"\n        _ranges: UnicodeRangeList = [\n            (0x0900, 0x097F),\n            (0xA8E0, 0xA8FF)\n        ]\n\n    # fmt: on\n\n\npyparsing_unicode.Japanese._ranges = (\n    pyparsing_unicode.Japanese.Kanji._ranges\n    + pyparsing_unicode.Japanese.Hiragana._ranges\n    + pyparsing_unicode.Japanese.Katakana._ranges\n)\n\npyparsing_unicode.BMP = pyparsing_unicode.BasicMultilingualPlane\n\n# add language identifiers using language Unicode\npyparsing_unicode.العربية = pyparsing_unicode.Arabic\npyparsing_unicode.中文 = pyparsing_unicode.Chinese\npyparsing_unicode.кириллица = pyparsing_unicode.Cyrillic\npyparsing_unicode.Ελληνικά = pyparsing_unicode.Greek\npyparsing_unicode.עִברִית = pyparsing_unicode.Hebrew\npyparsing_unicode.日本語 = pyparsing_unicode.Japanese\npyparsing_unicode.Japanese.漢字 = pyparsing_unicode.Japanese.Kanji\npyparsing_unicode.Japanese.カタカナ = pyparsing_unicode.Japanese.Katakana\npyparsing_unicode.Japanese.ひらがな = pyparsing_unicode.Japanese.Hiragana\npyparsing_unicode.한국어 = pyparsing_unicode.Korean\npyparsing_unicode.ไทย = pyparsing_unicode.Thai\npyparsing_unicode.देवनागरी = pyparsing_unicode.Devanagari\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/pyparsing/util.py",
    "content": "# util.py\nimport warnings\nimport types\nimport collections\nimport itertools\nfrom functools import lru_cache\nfrom typing import List, Union, Iterable\n\n_bslash = chr(92)\n\n\nclass __config_flags:\n    \"\"\"Internal class for defining compatibility and debugging flags\"\"\"\n\n    _all_names: List[str] = []\n    _fixed_names: List[str] = []\n    _type_desc = \"configuration\"\n\n    @classmethod\n    def _set(cls, dname, value):\n        if dname in cls._fixed_names:\n            warnings.warn(\n                \"{}.{} {} is {} and cannot be overridden\".format(\n                    cls.__name__,\n                    dname,\n                    cls._type_desc,\n                    str(getattr(cls, dname)).upper(),\n                )\n            )\n            return\n        if dname in cls._all_names:\n            setattr(cls, dname, value)\n        else:\n            raise ValueError(\"no such {} {!r}\".format(cls._type_desc, dname))\n\n    enable = classmethod(lambda cls, name: cls._set(name, True))\n    disable = classmethod(lambda cls, name: cls._set(name, False))\n\n\n@lru_cache(maxsize=128)\ndef col(loc: int, strg: str) -> int:\n    \"\"\"\n    Returns current column within a string, counting newlines as line separators.\n    The first column is number 1.\n\n    Note: the default parsing behavior is to expand tabs in the input string\n    before starting the parsing process.  See\n    :class:`ParserElement.parseString` for more\n    information on parsing strings containing ``<TAB>`` s, and suggested\n    methods to maintain a consistent view of the parsed string, the parse\n    location, and line and column positions within the parsed string.\n    \"\"\"\n    s = strg\n    return 1 if 0 < loc < len(s) and s[loc - 1] == \"\\n\" else loc - s.rfind(\"\\n\", 0, loc)\n\n\n@lru_cache(maxsize=128)\ndef lineno(loc: int, strg: str) -> int:\n    \"\"\"Returns current line number within a string, counting newlines as line separators.\n    The first line is number 1.\n\n    Note - the default parsing behavior is to expand tabs in the input string\n    before starting the parsing process.  See :class:`ParserElement.parseString`\n    for more information on parsing strings containing ``<TAB>`` s, and\n    suggested methods to maintain a consistent view of the parsed string, the\n    parse location, and line and column positions within the parsed string.\n    \"\"\"\n    return strg.count(\"\\n\", 0, loc) + 1\n\n\n@lru_cache(maxsize=128)\ndef line(loc: int, strg: str) -> str:\n    \"\"\"\n    Returns the line of text containing loc within a string, counting newlines as line separators.\n    \"\"\"\n    last_cr = strg.rfind(\"\\n\", 0, loc)\n    next_cr = strg.find(\"\\n\", loc)\n    return strg[last_cr + 1 : next_cr] if next_cr >= 0 else strg[last_cr + 1 :]\n\n\nclass _UnboundedCache:\n    def __init__(self):\n        cache = {}\n        cache_get = cache.get\n        self.not_in_cache = not_in_cache = object()\n\n        def get(_, key):\n            return cache_get(key, not_in_cache)\n\n        def set_(_, key, value):\n            cache[key] = value\n\n        def clear(_):\n            cache.clear()\n\n        self.size = None\n        self.get = types.MethodType(get, self)\n        self.set = types.MethodType(set_, self)\n        self.clear = types.MethodType(clear, self)\n\n\nclass _FifoCache:\n    def __init__(self, size):\n        self.not_in_cache = not_in_cache = object()\n        cache = collections.OrderedDict()\n        cache_get = cache.get\n\n        def get(_, key):\n            return cache_get(key, not_in_cache)\n\n        def set_(_, key, value):\n            cache[key] = value\n            while len(cache) > size:\n                cache.popitem(last=False)\n\n        def clear(_):\n            cache.clear()\n\n        self.size = size\n        self.get = types.MethodType(get, self)\n        self.set = types.MethodType(set_, self)\n        self.clear = types.MethodType(clear, self)\n\n\nclass LRUMemo:\n    \"\"\"\n    A memoizing mapping that retains `capacity` deleted items\n\n    The memo tracks retained items by their access order; once `capacity` items\n    are retained, the least recently used item is discarded.\n    \"\"\"\n\n    def __init__(self, capacity):\n        self._capacity = capacity\n        self._active = {}\n        self._memory = collections.OrderedDict()\n\n    def __getitem__(self, key):\n        try:\n            return self._active[key]\n        except KeyError:\n            self._memory.move_to_end(key)\n            return self._memory[key]\n\n    def __setitem__(self, key, value):\n        self._memory.pop(key, None)\n        self._active[key] = value\n\n    def __delitem__(self, key):\n        try:\n            value = self._active.pop(key)\n        except KeyError:\n            pass\n        else:\n            while len(self._memory) >= self._capacity:\n                self._memory.popitem(last=False)\n            self._memory[key] = value\n\n    def clear(self):\n        self._active.clear()\n        self._memory.clear()\n\n\nclass UnboundedMemo(dict):\n    \"\"\"\n    A memoizing mapping that retains all deleted items\n    \"\"\"\n\n    def __delitem__(self, key):\n        pass\n\n\ndef _escape_regex_range_chars(s: str) -> str:\n    # escape these chars: ^-[]\n    for c in r\"\\^-[]\":\n        s = s.replace(c, _bslash + c)\n    s = s.replace(\"\\n\", r\"\\n\")\n    s = s.replace(\"\\t\", r\"\\t\")\n    return str(s)\n\n\ndef _collapse_string_to_ranges(\n    s: Union[str, Iterable[str]], re_escape: bool = True\n) -> str:\n    def is_consecutive(c):\n        c_int = ord(c)\n        is_consecutive.prev, prev = c_int, is_consecutive.prev\n        if c_int - prev > 1:\n            is_consecutive.value = next(is_consecutive.counter)\n        return is_consecutive.value\n\n    is_consecutive.prev = 0\n    is_consecutive.counter = itertools.count()\n    is_consecutive.value = -1\n\n    def escape_re_range_char(c):\n        return \"\\\\\" + c if c in r\"\\^-][\" else c\n\n    def no_escape_re_range_char(c):\n        return c\n\n    if not re_escape:\n        escape_re_range_char = no_escape_re_range_char\n\n    ret = []\n    s = \"\".join(sorted(set(s)))\n    if len(s) > 3:\n        for _, chars in itertools.groupby(s, key=is_consecutive):\n            first = last = next(chars)\n            last = collections.deque(\n                itertools.chain(iter([last]), chars), maxlen=1\n            ).pop()\n            if first == last:\n                ret.append(escape_re_range_char(first))\n            else:\n                sep = \"\" if ord(last) == ord(first) + 1 else \"-\"\n                ret.append(\n                    \"{}{}{}\".format(\n                        escape_re_range_char(first), sep, escape_re_range_char(last)\n                    )\n                )\n    else:\n        ret = [escape_re_range_char(c) for c in s]\n\n    return \"\".join(ret)\n\n\ndef _flatten(ll: list) -> list:\n    ret = []\n    for i in ll:\n        if isinstance(i, list):\n            ret.extend(_flatten(i))\n        else:\n            ret.append(i)\n    return ret\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/tomli/__init__.py",
    "content": "# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\n__all__ = (\"loads\", \"load\", \"TOMLDecodeError\")\n__version__ = \"2.0.1\"  # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT\n\nfrom ._parser import TOMLDecodeError, load, loads\n\n# Pretend this exception was created here.\nTOMLDecodeError.__module__ = __name__\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/tomli/_parser.py",
    "content": "# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterable\nimport string\nfrom types import MappingProxyType\nfrom typing import Any, BinaryIO, NamedTuple\n\nfrom ._re import (\n    RE_DATETIME,\n    RE_LOCALTIME,\n    RE_NUMBER,\n    match_to_datetime,\n    match_to_localtime,\n    match_to_number,\n)\nfrom ._types import Key, ParseFloat, Pos\n\nASCII_CTRL = frozenset(chr(i) for i in range(32)) | frozenset(chr(127))\n\n# Neither of these sets include quotation mark or backslash. They are\n# currently handled as separate cases in the parser functions.\nILLEGAL_BASIC_STR_CHARS = ASCII_CTRL - frozenset(\"\\t\")\nILLEGAL_MULTILINE_BASIC_STR_CHARS = ASCII_CTRL - frozenset(\"\\t\\n\")\n\nILLEGAL_LITERAL_STR_CHARS = ILLEGAL_BASIC_STR_CHARS\nILLEGAL_MULTILINE_LITERAL_STR_CHARS = ILLEGAL_MULTILINE_BASIC_STR_CHARS\n\nILLEGAL_COMMENT_CHARS = ILLEGAL_BASIC_STR_CHARS\n\nTOML_WS = frozenset(\" \\t\")\nTOML_WS_AND_NEWLINE = TOML_WS | frozenset(\"\\n\")\nBARE_KEY_CHARS = frozenset(string.ascii_letters + string.digits + \"-_\")\nKEY_INITIAL_CHARS = BARE_KEY_CHARS | frozenset(\"\\\"'\")\nHEXDIGIT_CHARS = frozenset(string.hexdigits)\n\nBASIC_STR_ESCAPE_REPLACEMENTS = MappingProxyType(\n    {\n        \"\\\\b\": \"\\u0008\",  # backspace\n        \"\\\\t\": \"\\u0009\",  # tab\n        \"\\\\n\": \"\\u000A\",  # linefeed\n        \"\\\\f\": \"\\u000C\",  # form feed\n        \"\\\\r\": \"\\u000D\",  # carriage return\n        '\\\\\"': \"\\u0022\",  # quote\n        \"\\\\\\\\\": \"\\u005C\",  # backslash\n    }\n)\n\n\nclass TOMLDecodeError(ValueError):\n    \"\"\"An error raised if a document is not valid TOML.\"\"\"\n\n\ndef load(__fp: BinaryIO, *, parse_float: ParseFloat = float) -> dict[str, Any]:\n    \"\"\"Parse TOML from a binary file object.\"\"\"\n    b = __fp.read()\n    try:\n        s = b.decode()\n    except AttributeError:\n        raise TypeError(\n            \"File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`\"\n        ) from None\n    return loads(s, parse_float=parse_float)\n\n\ndef loads(__s: str, *, parse_float: ParseFloat = float) -> dict[str, Any]:  # noqa: C901\n    \"\"\"Parse TOML from a string.\"\"\"\n\n    # The spec allows converting \"\\r\\n\" to \"\\n\", even in string\n    # literals. Let's do so to simplify parsing.\n    src = __s.replace(\"\\r\\n\", \"\\n\")\n    pos = 0\n    out = Output(NestedDict(), Flags())\n    header: Key = ()\n    parse_float = make_safe_parse_float(parse_float)\n\n    # Parse one statement at a time\n    # (typically means one line in TOML source)\n    while True:\n        # 1. Skip line leading whitespace\n        pos = skip_chars(src, pos, TOML_WS)\n\n        # 2. Parse rules. Expect one of the following:\n        #    - end of file\n        #    - end of line\n        #    - comment\n        #    - key/value pair\n        #    - append dict to list (and move to its namespace)\n        #    - create dict (and move to its namespace)\n        # Skip trailing whitespace when applicable.\n        try:\n            char = src[pos]\n        except IndexError:\n            break\n        if char == \"\\n\":\n            pos += 1\n            continue\n        if char in KEY_INITIAL_CHARS:\n            pos = key_value_rule(src, pos, out, header, parse_float)\n            pos = skip_chars(src, pos, TOML_WS)\n        elif char == \"[\":\n            try:\n                second_char: str | None = src[pos + 1]\n            except IndexError:\n                second_char = None\n            out.flags.finalize_pending()\n            if second_char == \"[\":\n                pos, header = create_list_rule(src, pos, out)\n            else:\n                pos, header = create_dict_rule(src, pos, out)\n            pos = skip_chars(src, pos, TOML_WS)\n        elif char != \"#\":\n            raise suffixed_err(src, pos, \"Invalid statement\")\n\n        # 3. Skip comment\n        pos = skip_comment(src, pos)\n\n        # 4. Expect end of line or end of file\n        try:\n            char = src[pos]\n        except IndexError:\n            break\n        if char != \"\\n\":\n            raise suffixed_err(\n                src, pos, \"Expected newline or end of document after a statement\"\n            )\n        pos += 1\n\n    return out.data.dict\n\n\nclass Flags:\n    \"\"\"Flags that map to parsed keys/namespaces.\"\"\"\n\n    # Marks an immutable namespace (inline array or inline table).\n    FROZEN = 0\n    # Marks a nest that has been explicitly created and can no longer\n    # be opened using the \"[table]\" syntax.\n    EXPLICIT_NEST = 1\n\n    def __init__(self) -> None:\n        self._flags: dict[str, dict] = {}\n        self._pending_flags: set[tuple[Key, int]] = set()\n\n    def add_pending(self, key: Key, flag: int) -> None:\n        self._pending_flags.add((key, flag))\n\n    def finalize_pending(self) -> None:\n        for key, flag in self._pending_flags:\n            self.set(key, flag, recursive=False)\n        self._pending_flags.clear()\n\n    def unset_all(self, key: Key) -> None:\n        cont = self._flags\n        for k in key[:-1]:\n            if k not in cont:\n                return\n            cont = cont[k][\"nested\"]\n        cont.pop(key[-1], None)\n\n    def set(self, key: Key, flag: int, *, recursive: bool) -> None:  # noqa: A003\n        cont = self._flags\n        key_parent, key_stem = key[:-1], key[-1]\n        for k in key_parent:\n            if k not in cont:\n                cont[k] = {\"flags\": set(), \"recursive_flags\": set(), \"nested\": {}}\n            cont = cont[k][\"nested\"]\n        if key_stem not in cont:\n            cont[key_stem] = {\"flags\": set(), \"recursive_flags\": set(), \"nested\": {}}\n        cont[key_stem][\"recursive_flags\" if recursive else \"flags\"].add(flag)\n\n    def is_(self, key: Key, flag: int) -> bool:\n        if not key:\n            return False  # document root has no flags\n        cont = self._flags\n        for k in key[:-1]:\n            if k not in cont:\n                return False\n            inner_cont = cont[k]\n            if flag in inner_cont[\"recursive_flags\"]:\n                return True\n            cont = inner_cont[\"nested\"]\n        key_stem = key[-1]\n        if key_stem in cont:\n            cont = cont[key_stem]\n            return flag in cont[\"flags\"] or flag in cont[\"recursive_flags\"]\n        return False\n\n\nclass NestedDict:\n    def __init__(self) -> None:\n        # The parsed content of the TOML document\n        self.dict: dict[str, Any] = {}\n\n    def get_or_create_nest(\n        self,\n        key: Key,\n        *,\n        access_lists: bool = True,\n    ) -> dict:\n        cont: Any = self.dict\n        for k in key:\n            if k not in cont:\n                cont[k] = {}\n            cont = cont[k]\n            if access_lists and isinstance(cont, list):\n                cont = cont[-1]\n            if not isinstance(cont, dict):\n                raise KeyError(\"There is no nest behind this key\")\n        return cont\n\n    def append_nest_to_list(self, key: Key) -> None:\n        cont = self.get_or_create_nest(key[:-1])\n        last_key = key[-1]\n        if last_key in cont:\n            list_ = cont[last_key]\n            if not isinstance(list_, list):\n                raise KeyError(\"An object other than list found behind this key\")\n            list_.append({})\n        else:\n            cont[last_key] = [{}]\n\n\nclass Output(NamedTuple):\n    data: NestedDict\n    flags: Flags\n\n\ndef skip_chars(src: str, pos: Pos, chars: Iterable[str]) -> Pos:\n    try:\n        while src[pos] in chars:\n            pos += 1\n    except IndexError:\n        pass\n    return pos\n\n\ndef skip_until(\n    src: str,\n    pos: Pos,\n    expect: str,\n    *,\n    error_on: frozenset[str],\n    error_on_eof: bool,\n) -> Pos:\n    try:\n        new_pos = src.index(expect, pos)\n    except ValueError:\n        new_pos = len(src)\n        if error_on_eof:\n            raise suffixed_err(src, new_pos, f\"Expected {expect!r}\") from None\n\n    if not error_on.isdisjoint(src[pos:new_pos]):\n        while src[pos] not in error_on:\n            pos += 1\n        raise suffixed_err(src, pos, f\"Found invalid character {src[pos]!r}\")\n    return new_pos\n\n\ndef skip_comment(src: str, pos: Pos) -> Pos:\n    try:\n        char: str | None = src[pos]\n    except IndexError:\n        char = None\n    if char == \"#\":\n        return skip_until(\n            src, pos + 1, \"\\n\", error_on=ILLEGAL_COMMENT_CHARS, error_on_eof=False\n        )\n    return pos\n\n\ndef skip_comments_and_array_ws(src: str, pos: Pos) -> Pos:\n    while True:\n        pos_before_skip = pos\n        pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)\n        pos = skip_comment(src, pos)\n        if pos == pos_before_skip:\n            return pos\n\n\ndef create_dict_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:\n    pos += 1  # Skip \"[\"\n    pos = skip_chars(src, pos, TOML_WS)\n    pos, key = parse_key(src, pos)\n\n    if out.flags.is_(key, Flags.EXPLICIT_NEST) or out.flags.is_(key, Flags.FROZEN):\n        raise suffixed_err(src, pos, f\"Cannot declare {key} twice\")\n    out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)\n    try:\n        out.data.get_or_create_nest(key)\n    except KeyError:\n        raise suffixed_err(src, pos, \"Cannot overwrite a value\") from None\n\n    if not src.startswith(\"]\", pos):\n        raise suffixed_err(src, pos, \"Expected ']' at the end of a table declaration\")\n    return pos + 1, key\n\n\ndef create_list_rule(src: str, pos: Pos, out: Output) -> tuple[Pos, Key]:\n    pos += 2  # Skip \"[[\"\n    pos = skip_chars(src, pos, TOML_WS)\n    pos, key = parse_key(src, pos)\n\n    if out.flags.is_(key, Flags.FROZEN):\n        raise suffixed_err(src, pos, f\"Cannot mutate immutable namespace {key}\")\n    # Free the namespace now that it points to another empty list item...\n    out.flags.unset_all(key)\n    # ...but this key precisely is still prohibited from table declaration\n    out.flags.set(key, Flags.EXPLICIT_NEST, recursive=False)\n    try:\n        out.data.append_nest_to_list(key)\n    except KeyError:\n        raise suffixed_err(src, pos, \"Cannot overwrite a value\") from None\n\n    if not src.startswith(\"]]\", pos):\n        raise suffixed_err(src, pos, \"Expected ']]' at the end of an array declaration\")\n    return pos + 2, key\n\n\ndef key_value_rule(\n    src: str, pos: Pos, out: Output, header: Key, parse_float: ParseFloat\n) -> Pos:\n    pos, key, value = parse_key_value_pair(src, pos, parse_float)\n    key_parent, key_stem = key[:-1], key[-1]\n    abs_key_parent = header + key_parent\n\n    relative_path_cont_keys = (header + key[:i] for i in range(1, len(key)))\n    for cont_key in relative_path_cont_keys:\n        # Check that dotted key syntax does not redefine an existing table\n        if out.flags.is_(cont_key, Flags.EXPLICIT_NEST):\n            raise suffixed_err(src, pos, f\"Cannot redefine namespace {cont_key}\")\n        # Containers in the relative path can't be opened with the table syntax or\n        # dotted key/value syntax in following table sections.\n        out.flags.add_pending(cont_key, Flags.EXPLICIT_NEST)\n\n    if out.flags.is_(abs_key_parent, Flags.FROZEN):\n        raise suffixed_err(\n            src, pos, f\"Cannot mutate immutable namespace {abs_key_parent}\"\n        )\n\n    try:\n        nest = out.data.get_or_create_nest(abs_key_parent)\n    except KeyError:\n        raise suffixed_err(src, pos, \"Cannot overwrite a value\") from None\n    if key_stem in nest:\n        raise suffixed_err(src, pos, \"Cannot overwrite a value\")\n    # Mark inline table and array namespaces recursively immutable\n    if isinstance(value, (dict, list)):\n        out.flags.set(header + key, Flags.FROZEN, recursive=True)\n    nest[key_stem] = value\n    return pos\n\n\ndef parse_key_value_pair(\n    src: str, pos: Pos, parse_float: ParseFloat\n) -> tuple[Pos, Key, Any]:\n    pos, key = parse_key(src, pos)\n    try:\n        char: str | None = src[pos]\n    except IndexError:\n        char = None\n    if char != \"=\":\n        raise suffixed_err(src, pos, \"Expected '=' after a key in a key/value pair\")\n    pos += 1\n    pos = skip_chars(src, pos, TOML_WS)\n    pos, value = parse_value(src, pos, parse_float)\n    return pos, key, value\n\n\ndef parse_key(src: str, pos: Pos) -> tuple[Pos, Key]:\n    pos, key_part = parse_key_part(src, pos)\n    key: Key = (key_part,)\n    pos = skip_chars(src, pos, TOML_WS)\n    while True:\n        try:\n            char: str | None = src[pos]\n        except IndexError:\n            char = None\n        if char != \".\":\n            return pos, key\n        pos += 1\n        pos = skip_chars(src, pos, TOML_WS)\n        pos, key_part = parse_key_part(src, pos)\n        key += (key_part,)\n        pos = skip_chars(src, pos, TOML_WS)\n\n\ndef parse_key_part(src: str, pos: Pos) -> tuple[Pos, str]:\n    try:\n        char: str | None = src[pos]\n    except IndexError:\n        char = None\n    if char in BARE_KEY_CHARS:\n        start_pos = pos\n        pos = skip_chars(src, pos, BARE_KEY_CHARS)\n        return pos, src[start_pos:pos]\n    if char == \"'\":\n        return parse_literal_str(src, pos)\n    if char == '\"':\n        return parse_one_line_basic_str(src, pos)\n    raise suffixed_err(src, pos, \"Invalid initial character for a key part\")\n\n\ndef parse_one_line_basic_str(src: str, pos: Pos) -> tuple[Pos, str]:\n    pos += 1\n    return parse_basic_str(src, pos, multiline=False)\n\n\ndef parse_array(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos, list]:\n    pos += 1\n    array: list = []\n\n    pos = skip_comments_and_array_ws(src, pos)\n    if src.startswith(\"]\", pos):\n        return pos + 1, array\n    while True:\n        pos, val = parse_value(src, pos, parse_float)\n        array.append(val)\n        pos = skip_comments_and_array_ws(src, pos)\n\n        c = src[pos : pos + 1]\n        if c == \"]\":\n            return pos + 1, array\n        if c != \",\":\n            raise suffixed_err(src, pos, \"Unclosed array\")\n        pos += 1\n\n        pos = skip_comments_and_array_ws(src, pos)\n        if src.startswith(\"]\", pos):\n            return pos + 1, array\n\n\ndef parse_inline_table(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos, dict]:\n    pos += 1\n    nested_dict = NestedDict()\n    flags = Flags()\n\n    pos = skip_chars(src, pos, TOML_WS)\n    if src.startswith(\"}\", pos):\n        return pos + 1, nested_dict.dict\n    while True:\n        pos, key, value = parse_key_value_pair(src, pos, parse_float)\n        key_parent, key_stem = key[:-1], key[-1]\n        if flags.is_(key, Flags.FROZEN):\n            raise suffixed_err(src, pos, f\"Cannot mutate immutable namespace {key}\")\n        try:\n            nest = nested_dict.get_or_create_nest(key_parent, access_lists=False)\n        except KeyError:\n            raise suffixed_err(src, pos, \"Cannot overwrite a value\") from None\n        if key_stem in nest:\n            raise suffixed_err(src, pos, f\"Duplicate inline table key {key_stem!r}\")\n        nest[key_stem] = value\n        pos = skip_chars(src, pos, TOML_WS)\n        c = src[pos : pos + 1]\n        if c == \"}\":\n            return pos + 1, nested_dict.dict\n        if c != \",\":\n            raise suffixed_err(src, pos, \"Unclosed inline table\")\n        if isinstance(value, (dict, list)):\n            flags.set(key, Flags.FROZEN, recursive=True)\n        pos += 1\n        pos = skip_chars(src, pos, TOML_WS)\n\n\ndef parse_basic_str_escape(\n    src: str, pos: Pos, *, multiline: bool = False\n) -> tuple[Pos, str]:\n    escape_id = src[pos : pos + 2]\n    pos += 2\n    if multiline and escape_id in {\"\\\\ \", \"\\\\\\t\", \"\\\\\\n\"}:\n        # Skip whitespace until next non-whitespace character or end of\n        # the doc. Error if non-whitespace is found before newline.\n        if escape_id != \"\\\\\\n\":\n            pos = skip_chars(src, pos, TOML_WS)\n            try:\n                char = src[pos]\n            except IndexError:\n                return pos, \"\"\n            if char != \"\\n\":\n                raise suffixed_err(src, pos, \"Unescaped '\\\\' in a string\")\n            pos += 1\n        pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE)\n        return pos, \"\"\n    if escape_id == \"\\\\u\":\n        return parse_hex_char(src, pos, 4)\n    if escape_id == \"\\\\U\":\n        return parse_hex_char(src, pos, 8)\n    try:\n        return pos, BASIC_STR_ESCAPE_REPLACEMENTS[escape_id]\n    except KeyError:\n        raise suffixed_err(src, pos, \"Unescaped '\\\\' in a string\") from None\n\n\ndef parse_basic_str_escape_multiline(src: str, pos: Pos) -> tuple[Pos, str]:\n    return parse_basic_str_escape(src, pos, multiline=True)\n\n\ndef parse_hex_char(src: str, pos: Pos, hex_len: int) -> tuple[Pos, str]:\n    hex_str = src[pos : pos + hex_len]\n    if len(hex_str) != hex_len or not HEXDIGIT_CHARS.issuperset(hex_str):\n        raise suffixed_err(src, pos, \"Invalid hex value\")\n    pos += hex_len\n    hex_int = int(hex_str, 16)\n    if not is_unicode_scalar_value(hex_int):\n        raise suffixed_err(src, pos, \"Escaped character is not a Unicode scalar value\")\n    return pos, chr(hex_int)\n\n\ndef parse_literal_str(src: str, pos: Pos) -> tuple[Pos, str]:\n    pos += 1  # Skip starting apostrophe\n    start_pos = pos\n    pos = skip_until(\n        src, pos, \"'\", error_on=ILLEGAL_LITERAL_STR_CHARS, error_on_eof=True\n    )\n    return pos + 1, src[start_pos:pos]  # Skip ending apostrophe\n\n\ndef parse_multiline_str(src: str, pos: Pos, *, literal: bool) -> tuple[Pos, str]:\n    pos += 3\n    if src.startswith(\"\\n\", pos):\n        pos += 1\n\n    if literal:\n        delim = \"'\"\n        end_pos = skip_until(\n            src,\n            pos,\n            \"'''\",\n            error_on=ILLEGAL_MULTILINE_LITERAL_STR_CHARS,\n            error_on_eof=True,\n        )\n        result = src[pos:end_pos]\n        pos = end_pos + 3\n    else:\n        delim = '\"'\n        pos, result = parse_basic_str(src, pos, multiline=True)\n\n    # Add at maximum two extra apostrophes/quotes if the end sequence\n    # is 4 or 5 chars long instead of just 3.\n    if not src.startswith(delim, pos):\n        return pos, result\n    pos += 1\n    if not src.startswith(delim, pos):\n        return pos, result + delim\n    pos += 1\n    return pos, result + (delim * 2)\n\n\ndef parse_basic_str(src: str, pos: Pos, *, multiline: bool) -> tuple[Pos, str]:\n    if multiline:\n        error_on = ILLEGAL_MULTILINE_BASIC_STR_CHARS\n        parse_escapes = parse_basic_str_escape_multiline\n    else:\n        error_on = ILLEGAL_BASIC_STR_CHARS\n        parse_escapes = parse_basic_str_escape\n    result = \"\"\n    start_pos = pos\n    while True:\n        try:\n            char = src[pos]\n        except IndexError:\n            raise suffixed_err(src, pos, \"Unterminated string\") from None\n        if char == '\"':\n            if not multiline:\n                return pos + 1, result + src[start_pos:pos]\n            if src.startswith('\"\"\"', pos):\n                return pos + 3, result + src[start_pos:pos]\n            pos += 1\n            continue\n        if char == \"\\\\\":\n            result += src[start_pos:pos]\n            pos, parsed_escape = parse_escapes(src, pos)\n            result += parsed_escape\n            start_pos = pos\n            continue\n        if char in error_on:\n            raise suffixed_err(src, pos, f\"Illegal character {char!r}\")\n        pos += 1\n\n\ndef parse_value(  # noqa: C901\n    src: str, pos: Pos, parse_float: ParseFloat\n) -> tuple[Pos, Any]:\n    try:\n        char: str | None = src[pos]\n    except IndexError:\n        char = None\n\n    # IMPORTANT: order conditions based on speed of checking and likelihood\n\n    # Basic strings\n    if char == '\"':\n        if src.startswith('\"\"\"', pos):\n            return parse_multiline_str(src, pos, literal=False)\n        return parse_one_line_basic_str(src, pos)\n\n    # Literal strings\n    if char == \"'\":\n        if src.startswith(\"'''\", pos):\n            return parse_multiline_str(src, pos, literal=True)\n        return parse_literal_str(src, pos)\n\n    # Booleans\n    if char == \"t\":\n        if src.startswith(\"true\", pos):\n            return pos + 4, True\n    if char == \"f\":\n        if src.startswith(\"false\", pos):\n            return pos + 5, False\n\n    # Arrays\n    if char == \"[\":\n        return parse_array(src, pos, parse_float)\n\n    # Inline tables\n    if char == \"{\":\n        return parse_inline_table(src, pos, parse_float)\n\n    # Dates and times\n    datetime_match = RE_DATETIME.match(src, pos)\n    if datetime_match:\n        try:\n            datetime_obj = match_to_datetime(datetime_match)\n        except ValueError as e:\n            raise suffixed_err(src, pos, \"Invalid date or datetime\") from e\n        return datetime_match.end(), datetime_obj\n    localtime_match = RE_LOCALTIME.match(src, pos)\n    if localtime_match:\n        return localtime_match.end(), match_to_localtime(localtime_match)\n\n    # Integers and \"normal\" floats.\n    # The regex will greedily match any type starting with a decimal\n    # char, so needs to be located after handling of dates and times.\n    number_match = RE_NUMBER.match(src, pos)\n    if number_match:\n        return number_match.end(), match_to_number(number_match, parse_float)\n\n    # Special floats\n    first_three = src[pos : pos + 3]\n    if first_three in {\"inf\", \"nan\"}:\n        return pos + 3, parse_float(first_three)\n    first_four = src[pos : pos + 4]\n    if first_four in {\"-inf\", \"+inf\", \"-nan\", \"+nan\"}:\n        return pos + 4, parse_float(first_four)\n\n    raise suffixed_err(src, pos, \"Invalid value\")\n\n\ndef suffixed_err(src: str, pos: Pos, msg: str) -> TOMLDecodeError:\n    \"\"\"Return a `TOMLDecodeError` where error message is suffixed with\n    coordinates in source.\"\"\"\n\n    def coord_repr(src: str, pos: Pos) -> str:\n        if pos >= len(src):\n            return \"end of document\"\n        line = src.count(\"\\n\", 0, pos) + 1\n        if line == 1:\n            column = pos + 1\n        else:\n            column = pos - src.rindex(\"\\n\", 0, pos)\n        return f\"line {line}, column {column}\"\n\n    return TOMLDecodeError(f\"{msg} (at {coord_repr(src, pos)})\")\n\n\ndef is_unicode_scalar_value(codepoint: int) -> bool:\n    return (0 <= codepoint <= 55295) or (57344 <= codepoint <= 1114111)\n\n\ndef make_safe_parse_float(parse_float: ParseFloat) -> ParseFloat:\n    \"\"\"A decorator to make `parse_float` safe.\n\n    `parse_float` must not return dicts or lists, because these types\n    would be mixed with parsed TOML tables and arrays, thus confusing\n    the parser. The returned decorated callable raises `ValueError`\n    instead of returning illegal types.\n    \"\"\"\n    # The default `float` callable never returns illegal types. Optimize it.\n    if parse_float is float:  # type: ignore[comparison-overlap]\n        return float\n\n    def safe_parse_float(float_str: str) -> Any:\n        float_value = parse_float(float_str)\n        if isinstance(float_value, (dict, list)):\n            raise ValueError(\"parse_float must not return dicts or lists\")\n        return float_value\n\n    return safe_parse_float\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/tomli/_re.py",
    "content": "# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\nfrom __future__ import annotations\n\nfrom datetime import date, datetime, time, timedelta, timezone, tzinfo\nfrom functools import lru_cache\nimport re\nfrom typing import Any\n\nfrom ._types import ParseFloat\n\n# E.g.\n# - 00:32:00.999999\n# - 00:32:00\n_TIME_RE_STR = r\"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\\.([0-9]{1,6})[0-9]*)?\"\n\nRE_NUMBER = re.compile(\n    r\"\"\"\n0\n(?:\n    x[0-9A-Fa-f](?:_?[0-9A-Fa-f])*   # hex\n    |\n    b[01](?:_?[01])*                 # bin\n    |\n    o[0-7](?:_?[0-7])*               # oct\n)\n|\n[+-]?(?:0|[1-9](?:_?[0-9])*)         # dec, integer part\n(?P<floatpart>\n    (?:\\.[0-9](?:_?[0-9])*)?         # optional fractional part\n    (?:[eE][+-]?[0-9](?:_?[0-9])*)?  # optional exponent part\n)\n\"\"\",\n    flags=re.VERBOSE,\n)\nRE_LOCALTIME = re.compile(_TIME_RE_STR)\nRE_DATETIME = re.compile(\n    rf\"\"\"\n([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])  # date, e.g. 1988-10-27\n(?:\n    [Tt ]\n    {_TIME_RE_STR}\n    (?:([Zz])|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))?  # optional time offset\n)?\n\"\"\",\n    flags=re.VERBOSE,\n)\n\n\ndef match_to_datetime(match: re.Match) -> datetime | date:\n    \"\"\"Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.\n\n    Raises ValueError if the match does not correspond to a valid date\n    or datetime.\n    \"\"\"\n    (\n        year_str,\n        month_str,\n        day_str,\n        hour_str,\n        minute_str,\n        sec_str,\n        micros_str,\n        zulu_time,\n        offset_sign_str,\n        offset_hour_str,\n        offset_minute_str,\n    ) = match.groups()\n    year, month, day = int(year_str), int(month_str), int(day_str)\n    if hour_str is None:\n        return date(year, month, day)\n    hour, minute, sec = int(hour_str), int(minute_str), int(sec_str)\n    micros = int(micros_str.ljust(6, \"0\")) if micros_str else 0\n    if offset_sign_str:\n        tz: tzinfo | None = cached_tz(\n            offset_hour_str, offset_minute_str, offset_sign_str\n        )\n    elif zulu_time:\n        tz = timezone.utc\n    else:  # local date-time\n        tz = None\n    return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz)\n\n\n@lru_cache(maxsize=None)\ndef cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone:\n    sign = 1 if sign_str == \"+\" else -1\n    return timezone(\n        timedelta(\n            hours=sign * int(hour_str),\n            minutes=sign * int(minute_str),\n        )\n    )\n\n\ndef match_to_localtime(match: re.Match) -> time:\n    hour_str, minute_str, sec_str, micros_str = match.groups()\n    micros = int(micros_str.ljust(6, \"0\")) if micros_str else 0\n    return time(int(hour_str), int(minute_str), int(sec_str), micros)\n\n\ndef match_to_number(match: re.Match, parse_float: ParseFloat) -> Any:\n    if match.group(\"floatpart\"):\n        return parse_float(match.group())\n    return int(match.group(), 0)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/tomli/_types.py",
    "content": "# SPDX-License-Identifier: MIT\n# SPDX-FileCopyrightText: 2021 Taneli Hukkinen\n# Licensed to PSF under a Contributor Agreement.\n\nfrom typing import Any, Callable, Tuple\n\n# Type annotations\nParseFloat = Callable[[str], Any]\nKey = Tuple[str, ...]\nPos = int\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/typing_extensions.py",
    "content": "import abc\nimport collections\nimport collections.abc\nimport operator\nimport sys\nimport typing\n\n# After PEP 560, internal typing API was substantially reworked.\n# This is especially important for Protocol class which uses internal APIs\n# quite extensively.\nPEP_560 = sys.version_info[:3] >= (3, 7, 0)\n\nif PEP_560:\n    GenericMeta = type\nelse:\n    # 3.6\n    from typing import GenericMeta, _type_vars  # noqa\n\n# The two functions below are copies of typing internal helpers.\n# They are needed by _ProtocolMeta\n\n\ndef _no_slots_copy(dct):\n    dict_copy = dict(dct)\n    if '__slots__' in dict_copy:\n        for slot in dict_copy['__slots__']:\n            dict_copy.pop(slot, None)\n    return dict_copy\n\n\ndef _check_generic(cls, parameters):\n    if not cls.__parameters__:\n        raise TypeError(f\"{cls} is not a generic class\")\n    alen = len(parameters)\n    elen = len(cls.__parameters__)\n    if alen != elen:\n        raise TypeError(f\"Too {'many' if alen > elen else 'few'} arguments for {cls};\"\n                        f\" actual {alen}, expected {elen}\")\n\n\n# Please keep __all__ alphabetized within each category.\n__all__ = [\n    # Super-special typing primitives.\n    'ClassVar',\n    'Concatenate',\n    'Final',\n    'ParamSpec',\n    'Self',\n    'Type',\n\n    # ABCs (from collections.abc).\n    'Awaitable',\n    'AsyncIterator',\n    'AsyncIterable',\n    'Coroutine',\n    'AsyncGenerator',\n    'AsyncContextManager',\n    'ChainMap',\n\n    # Concrete collection types.\n    'ContextManager',\n    'Counter',\n    'Deque',\n    'DefaultDict',\n    'OrderedDict',\n    'TypedDict',\n\n    # Structural checks, a.k.a. protocols.\n    'SupportsIndex',\n\n    # One-off things.\n    'Annotated',\n    'final',\n    'IntVar',\n    'Literal',\n    'NewType',\n    'overload',\n    'Protocol',\n    'runtime',\n    'runtime_checkable',\n    'Text',\n    'TypeAlias',\n    'TypeGuard',\n    'TYPE_CHECKING',\n]\n\nif PEP_560:\n    __all__.extend([\"get_args\", \"get_origin\", \"get_type_hints\"])\n\n# 3.6.2+\nif hasattr(typing, 'NoReturn'):\n    NoReturn = typing.NoReturn\n# 3.6.0-3.6.1\nelse:\n    class _NoReturn(typing._FinalTypingBase, _root=True):\n        \"\"\"Special type indicating functions that never return.\n        Example::\n\n          from typing import NoReturn\n\n          def stop() -> NoReturn:\n              raise Exception('no way')\n\n        This type is invalid in other positions, e.g., ``List[NoReturn]``\n        will fail in static type checkers.\n        \"\"\"\n        __slots__ = ()\n\n        def __instancecheck__(self, obj):\n            raise TypeError(\"NoReturn cannot be used with isinstance().\")\n\n        def __subclasscheck__(self, cls):\n            raise TypeError(\"NoReturn cannot be used with issubclass().\")\n\n    NoReturn = _NoReturn(_root=True)\n\n# Some unconstrained type variables.  These are used by the container types.\n# (These are not for export.)\nT = typing.TypeVar('T')  # Any type.\nKT = typing.TypeVar('KT')  # Key type.\nVT = typing.TypeVar('VT')  # Value type.\nT_co = typing.TypeVar('T_co', covariant=True)  # Any type covariant containers.\nT_contra = typing.TypeVar('T_contra', contravariant=True)  # Ditto contravariant.\n\nClassVar = typing.ClassVar\n\n# On older versions of typing there is an internal class named \"Final\".\n# 3.8+\nif hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):\n    Final = typing.Final\n# 3.7\nelif sys.version_info[:2] >= (3, 7):\n    class _FinalForm(typing._SpecialForm, _root=True):\n\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n        def __getitem__(self, parameters):\n            item = typing._type_check(parameters,\n                                      f'{self._name} accepts only single type')\n            return typing._GenericAlias(self, (item,))\n\n    Final = _FinalForm('Final',\n                       doc=\"\"\"A special typing construct to indicate that a name\n                       cannot be re-assigned or overridden in a subclass.\n                       For example:\n\n                           MAX_SIZE: Final = 9000\n                           MAX_SIZE += 1  # Error reported by type checker\n\n                           class Connection:\n                               TIMEOUT: Final[int] = 10\n                           class FastConnector(Connection):\n                               TIMEOUT = 1  # Error reported by type checker\n\n                       There is no runtime checking of these properties.\"\"\")\n# 3.6\nelse:\n    class _Final(typing._FinalTypingBase, _root=True):\n        \"\"\"A special typing construct to indicate that a name\n        cannot be re-assigned or overridden in a subclass.\n        For example:\n\n            MAX_SIZE: Final = 9000\n            MAX_SIZE += 1  # Error reported by type checker\n\n            class Connection:\n                TIMEOUT: Final[int] = 10\n            class FastConnector(Connection):\n                TIMEOUT = 1  # Error reported by type checker\n\n        There is no runtime checking of these properties.\n        \"\"\"\n\n        __slots__ = ('__type__',)\n\n        def __init__(self, tp=None, **kwds):\n            self.__type__ = tp\n\n        def __getitem__(self, item):\n            cls = type(self)\n            if self.__type__ is None:\n                return cls(typing._type_check(item,\n                           f'{cls.__name__[1:]} accepts only single type.'),\n                           _root=True)\n            raise TypeError(f'{cls.__name__[1:]} cannot be further subscripted')\n\n        def _eval_type(self, globalns, localns):\n            new_tp = typing._eval_type(self.__type__, globalns, localns)\n            if new_tp == self.__type__:\n                return self\n            return type(self)(new_tp, _root=True)\n\n        def __repr__(self):\n            r = super().__repr__()\n            if self.__type__ is not None:\n                r += f'[{typing._type_repr(self.__type__)}]'\n            return r\n\n        def __hash__(self):\n            return hash((type(self).__name__, self.__type__))\n\n        def __eq__(self, other):\n            if not isinstance(other, _Final):\n                return NotImplemented\n            if self.__type__ is not None:\n                return self.__type__ == other.__type__\n            return self is other\n\n    Final = _Final(_root=True)\n\n\n# 3.8+\nif hasattr(typing, 'final'):\n    final = typing.final\n# 3.6-3.7\nelse:\n    def final(f):\n        \"\"\"This decorator can be used to indicate to type checkers that\n        the decorated method cannot be overridden, and decorated class\n        cannot be subclassed. For example:\n\n            class Base:\n                @final\n                def done(self) -> None:\n                    ...\n            class Sub(Base):\n                def done(self) -> None:  # Error reported by type checker\n                    ...\n            @final\n            class Leaf:\n                ...\n            class Other(Leaf):  # Error reported by type checker\n                ...\n\n        There is no runtime checking of these properties.\n        \"\"\"\n        return f\n\n\ndef IntVar(name):\n    return typing.TypeVar(name)\n\n\n# 3.8+:\nif hasattr(typing, 'Literal'):\n    Literal = typing.Literal\n# 3.7:\nelif sys.version_info[:2] >= (3, 7):\n    class _LiteralForm(typing._SpecialForm, _root=True):\n\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n        def __getitem__(self, parameters):\n            return typing._GenericAlias(self, parameters)\n\n    Literal = _LiteralForm('Literal',\n                           doc=\"\"\"A type that can be used to indicate to type checkers\n                           that the corresponding value has a value literally equivalent\n                           to the provided parameter. For example:\n\n                               var: Literal[4] = 4\n\n                           The type checker understands that 'var' is literally equal to\n                           the value 4 and no other value.\n\n                           Literal[...] cannot be subclassed. There is no runtime\n                           checking verifying that the parameter is actually a value\n                           instead of a type.\"\"\")\n# 3.6:\nelse:\n    class _Literal(typing._FinalTypingBase, _root=True):\n        \"\"\"A type that can be used to indicate to type checkers that the\n        corresponding value has a value literally equivalent to the\n        provided parameter. For example:\n\n            var: Literal[4] = 4\n\n        The type checker understands that 'var' is literally equal to the\n        value 4 and no other value.\n\n        Literal[...] cannot be subclassed. There is no runtime checking\n        verifying that the parameter is actually a value instead of a type.\n        \"\"\"\n\n        __slots__ = ('__values__',)\n\n        def __init__(self, values=None, **kwds):\n            self.__values__ = values\n\n        def __getitem__(self, values):\n            cls = type(self)\n            if self.__values__ is None:\n                if not isinstance(values, tuple):\n                    values = (values,)\n                return cls(values, _root=True)\n            raise TypeError(f'{cls.__name__[1:]} cannot be further subscripted')\n\n        def _eval_type(self, globalns, localns):\n            return self\n\n        def __repr__(self):\n            r = super().__repr__()\n            if self.__values__ is not None:\n                r += f'[{\", \".join(map(typing._type_repr, self.__values__))}]'\n            return r\n\n        def __hash__(self):\n            return hash((type(self).__name__, self.__values__))\n\n        def __eq__(self, other):\n            if not isinstance(other, _Literal):\n                return NotImplemented\n            if self.__values__ is not None:\n                return self.__values__ == other.__values__\n            return self is other\n\n    Literal = _Literal(_root=True)\n\n\n_overload_dummy = typing._overload_dummy  # noqa\noverload = typing.overload\n\n\n# This is not a real generic class.  Don't use outside annotations.\nType = typing.Type\n\n# Various ABCs mimicking those in collections.abc.\n# A few are simply re-exported for completeness.\n\n\nclass _ExtensionsGenericMeta(GenericMeta):\n    def __subclasscheck__(self, subclass):\n        \"\"\"This mimics a more modern GenericMeta.__subclasscheck__() logic\n        (that does not have problems with recursion) to work around interactions\n        between collections, typing, and typing_extensions on older\n        versions of Python, see https://github.com/python/typing/issues/501.\n        \"\"\"\n        if self.__origin__ is not None:\n            if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:\n                raise TypeError(\"Parameterized generics cannot be used with class \"\n                                \"or instance checks\")\n            return False\n        if not self.__extra__:\n            return super().__subclasscheck__(subclass)\n        res = self.__extra__.__subclasshook__(subclass)\n        if res is not NotImplemented:\n            return res\n        if self.__extra__ in subclass.__mro__:\n            return True\n        for scls in self.__extra__.__subclasses__():\n            if isinstance(scls, GenericMeta):\n                continue\n            if issubclass(subclass, scls):\n                return True\n        return False\n\n\nAwaitable = typing.Awaitable\nCoroutine = typing.Coroutine\nAsyncIterable = typing.AsyncIterable\nAsyncIterator = typing.AsyncIterator\n\n# 3.6.1+\nif hasattr(typing, 'Deque'):\n    Deque = typing.Deque\n# 3.6.0\nelse:\n    class Deque(collections.deque, typing.MutableSequence[T],\n                metaclass=_ExtensionsGenericMeta,\n                extra=collections.deque):\n        __slots__ = ()\n\n        def __new__(cls, *args, **kwds):\n            if cls._gorg is Deque:\n                return collections.deque(*args, **kwds)\n            return typing._generic_new(collections.deque, cls, *args, **kwds)\n\nContextManager = typing.ContextManager\n# 3.6.2+\nif hasattr(typing, 'AsyncContextManager'):\n    AsyncContextManager = typing.AsyncContextManager\n# 3.6.0-3.6.1\nelse:\n    from _collections_abc import _check_methods as _check_methods_in_mro  # noqa\n\n    class AsyncContextManager(typing.Generic[T_co]):\n        __slots__ = ()\n\n        async def __aenter__(self):\n            return self\n\n        @abc.abstractmethod\n        async def __aexit__(self, exc_type, exc_value, traceback):\n            return None\n\n        @classmethod\n        def __subclasshook__(cls, C):\n            if cls is AsyncContextManager:\n                return _check_methods_in_mro(C, \"__aenter__\", \"__aexit__\")\n            return NotImplemented\n\nDefaultDict = typing.DefaultDict\n\n# 3.7.2+\nif hasattr(typing, 'OrderedDict'):\n    OrderedDict = typing.OrderedDict\n# 3.7.0-3.7.2\nelif (3, 7, 0) <= sys.version_info[:3] < (3, 7, 2):\n    OrderedDict = typing._alias(collections.OrderedDict, (KT, VT))\n# 3.6\nelse:\n    class OrderedDict(collections.OrderedDict, typing.MutableMapping[KT, VT],\n                      metaclass=_ExtensionsGenericMeta,\n                      extra=collections.OrderedDict):\n\n        __slots__ = ()\n\n        def __new__(cls, *args, **kwds):\n            if cls._gorg is OrderedDict:\n                return collections.OrderedDict(*args, **kwds)\n            return typing._generic_new(collections.OrderedDict, cls, *args, **kwds)\n\n# 3.6.2+\nif hasattr(typing, 'Counter'):\n    Counter = typing.Counter\n# 3.6.0-3.6.1\nelse:\n    class Counter(collections.Counter,\n                  typing.Dict[T, int],\n                  metaclass=_ExtensionsGenericMeta, extra=collections.Counter):\n\n        __slots__ = ()\n\n        def __new__(cls, *args, **kwds):\n            if cls._gorg is Counter:\n                return collections.Counter(*args, **kwds)\n            return typing._generic_new(collections.Counter, cls, *args, **kwds)\n\n# 3.6.1+\nif hasattr(typing, 'ChainMap'):\n    ChainMap = typing.ChainMap\nelif hasattr(collections, 'ChainMap'):\n    class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT],\n                   metaclass=_ExtensionsGenericMeta,\n                   extra=collections.ChainMap):\n\n        __slots__ = ()\n\n        def __new__(cls, *args, **kwds):\n            if cls._gorg is ChainMap:\n                return collections.ChainMap(*args, **kwds)\n            return typing._generic_new(collections.ChainMap, cls, *args, **kwds)\n\n# 3.6.1+\nif hasattr(typing, 'AsyncGenerator'):\n    AsyncGenerator = typing.AsyncGenerator\n# 3.6.0\nelse:\n    class AsyncGenerator(AsyncIterator[T_co], typing.Generic[T_co, T_contra],\n                         metaclass=_ExtensionsGenericMeta,\n                         extra=collections.abc.AsyncGenerator):\n        __slots__ = ()\n\nNewType = typing.NewType\nText = typing.Text\nTYPE_CHECKING = typing.TYPE_CHECKING\n\n\ndef _gorg(cls):\n    \"\"\"This function exists for compatibility with old typing versions.\"\"\"\n    assert isinstance(cls, GenericMeta)\n    if hasattr(cls, '_gorg'):\n        return cls._gorg\n    while cls.__origin__ is not None:\n        cls = cls.__origin__\n    return cls\n\n\n_PROTO_WHITELIST = ['Callable', 'Awaitable',\n                    'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',\n                    'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',\n                    'ContextManager', 'AsyncContextManager']\n\n\ndef _get_protocol_attrs(cls):\n    attrs = set()\n    for base in cls.__mro__[:-1]:  # without object\n        if base.__name__ in ('Protocol', 'Generic'):\n            continue\n        annotations = getattr(base, '__annotations__', {})\n        for attr in list(base.__dict__.keys()) + list(annotations.keys()):\n            if (not attr.startswith('_abc_') and attr not in (\n                    '__abstractmethods__', '__annotations__', '__weakref__',\n                    '_is_protocol', '_is_runtime_protocol', '__dict__',\n                    '__args__', '__slots__',\n                    '__next_in_mro__', '__parameters__', '__origin__',\n                    '__orig_bases__', '__extra__', '__tree_hash__',\n                    '__doc__', '__subclasshook__', '__init__', '__new__',\n                    '__module__', '_MutableMapping__marker', '_gorg')):\n                attrs.add(attr)\n    return attrs\n\n\ndef _is_callable_members_only(cls):\n    return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))\n\n\n# 3.8+\nif hasattr(typing, 'Protocol'):\n    Protocol = typing.Protocol\n# 3.7\nelif PEP_560:\n    from typing import _collect_type_vars  # noqa\n\n    def _no_init(self, *args, **kwargs):\n        if type(self)._is_protocol:\n            raise TypeError('Protocols cannot be instantiated')\n\n    class _ProtocolMeta(abc.ABCMeta):\n        # This metaclass is a bit unfortunate and exists only because of the lack\n        # of __instancehook__.\n        def __instancecheck__(cls, instance):\n            # We need this method for situations where attributes are\n            # assigned in __init__.\n            if ((not getattr(cls, '_is_protocol', False) or\n                 _is_callable_members_only(cls)) and\n                    issubclass(instance.__class__, cls)):\n                return True\n            if cls._is_protocol:\n                if all(hasattr(instance, attr) and\n                       (not callable(getattr(cls, attr, None)) or\n                        getattr(instance, attr) is not None)\n                       for attr in _get_protocol_attrs(cls)):\n                    return True\n            return super().__instancecheck__(instance)\n\n    class Protocol(metaclass=_ProtocolMeta):\n        # There is quite a lot of overlapping code with typing.Generic.\n        # Unfortunately it is hard to avoid this while these live in two different\n        # modules. The duplicated code will be removed when Protocol is moved to typing.\n        \"\"\"Base class for protocol classes. Protocol classes are defined as::\n\n            class Proto(Protocol):\n                def meth(self) -> int:\n                    ...\n\n        Such classes are primarily used with static type checkers that recognize\n        structural subtyping (static duck-typing), for example::\n\n            class C:\n                def meth(self) -> int:\n                    return 0\n\n            def func(x: Proto) -> int:\n                return x.meth()\n\n            func(C())  # Passes static type check\n\n        See PEP 544 for details. Protocol classes decorated with\n        @typing_extensions.runtime act as simple-minded runtime protocol that checks\n        only the presence of given attributes, ignoring their type signatures.\n\n        Protocol classes can be generic, they are defined as::\n\n            class GenProto(Protocol[T]):\n                def meth(self) -> T:\n                    ...\n        \"\"\"\n        __slots__ = ()\n        _is_protocol = True\n\n        def __new__(cls, *args, **kwds):\n            if cls is Protocol:\n                raise TypeError(\"Type Protocol cannot be instantiated; \"\n                                \"it can only be used as a base class\")\n            return super().__new__(cls)\n\n        @typing._tp_cache\n        def __class_getitem__(cls, params):\n            if not isinstance(params, tuple):\n                params = (params,)\n            if not params and cls is not typing.Tuple:\n                raise TypeError(\n                    f\"Parameter list to {cls.__qualname__}[...] cannot be empty\")\n            msg = \"Parameters to generic types must be types.\"\n            params = tuple(typing._type_check(p, msg) for p in params)  # noqa\n            if cls is Protocol:\n                # Generic can only be subscripted with unique type variables.\n                if not all(isinstance(p, typing.TypeVar) for p in params):\n                    i = 0\n                    while isinstance(params[i], typing.TypeVar):\n                        i += 1\n                    raise TypeError(\n                        \"Parameters to Protocol[...] must all be type variables.\"\n                        f\" Parameter {i + 1} is {params[i]}\")\n                if len(set(params)) != len(params):\n                    raise TypeError(\n                        \"Parameters to Protocol[...] must all be unique\")\n            else:\n                # Subscripting a regular Generic subclass.\n                _check_generic(cls, params)\n            return typing._GenericAlias(cls, params)\n\n        def __init_subclass__(cls, *args, **kwargs):\n            tvars = []\n            if '__orig_bases__' in cls.__dict__:\n                error = typing.Generic in cls.__orig_bases__\n            else:\n                error = typing.Generic in cls.__bases__\n            if error:\n                raise TypeError(\"Cannot inherit from plain Generic\")\n            if '__orig_bases__' in cls.__dict__:\n                tvars = _collect_type_vars(cls.__orig_bases__)\n                # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].\n                # If found, tvars must be a subset of it.\n                # If not found, tvars is it.\n                # Also check for and reject plain Generic,\n                # and reject multiple Generic[...] and/or Protocol[...].\n                gvars = None\n                for base in cls.__orig_bases__:\n                    if (isinstance(base, typing._GenericAlias) and\n                            base.__origin__ in (typing.Generic, Protocol)):\n                        # for error messages\n                        the_base = base.__origin__.__name__\n                        if gvars is not None:\n                            raise TypeError(\n                                \"Cannot inherit from Generic[...]\"\n                                \" and/or Protocol[...] multiple types.\")\n                        gvars = base.__parameters__\n                if gvars is None:\n                    gvars = tvars\n                else:\n                    tvarset = set(tvars)\n                    gvarset = set(gvars)\n                    if not tvarset <= gvarset:\n                        s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)\n                        s_args = ', '.join(str(g) for g in gvars)\n                        raise TypeError(f\"Some type variables ({s_vars}) are\"\n                                        f\" not listed in {the_base}[{s_args}]\")\n                    tvars = gvars\n            cls.__parameters__ = tuple(tvars)\n\n            # Determine if this is a protocol or a concrete subclass.\n            if not cls.__dict__.get('_is_protocol', None):\n                cls._is_protocol = any(b is Protocol for b in cls.__bases__)\n\n            # Set (or override) the protocol subclass hook.\n            def _proto_hook(other):\n                if not cls.__dict__.get('_is_protocol', None):\n                    return NotImplemented\n                if not getattr(cls, '_is_runtime_protocol', False):\n                    if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:\n                        return NotImplemented\n                    raise TypeError(\"Instance and class checks can only be used with\"\n                                    \" @runtime protocols\")\n                if not _is_callable_members_only(cls):\n                    if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:\n                        return NotImplemented\n                    raise TypeError(\"Protocols with non-method members\"\n                                    \" don't support issubclass()\")\n                if not isinstance(other, type):\n                    # Same error as for issubclass(1, int)\n                    raise TypeError('issubclass() arg 1 must be a class')\n                for attr in _get_protocol_attrs(cls):\n                    for base in other.__mro__:\n                        if attr in base.__dict__:\n                            if base.__dict__[attr] is None:\n                                return NotImplemented\n                            break\n                        annotations = getattr(base, '__annotations__', {})\n                        if (isinstance(annotations, typing.Mapping) and\n                                attr in annotations and\n                                isinstance(other, _ProtocolMeta) and\n                                other._is_protocol):\n                            break\n                    else:\n                        return NotImplemented\n                return True\n            if '__subclasshook__' not in cls.__dict__:\n                cls.__subclasshook__ = _proto_hook\n\n            # We have nothing more to do for non-protocols.\n            if not cls._is_protocol:\n                return\n\n            # Check consistency of bases.\n            for base in cls.__bases__:\n                if not (base in (object, typing.Generic) or\n                        base.__module__ == 'collections.abc' and\n                        base.__name__ in _PROTO_WHITELIST or\n                        isinstance(base, _ProtocolMeta) and base._is_protocol):\n                    raise TypeError('Protocols can only inherit from other'\n                                    f' protocols, got {repr(base)}')\n            cls.__init__ = _no_init\n# 3.6\nelse:\n    from typing import _next_in_mro, _type_check  # noqa\n\n    def _no_init(self, *args, **kwargs):\n        if type(self)._is_protocol:\n            raise TypeError('Protocols cannot be instantiated')\n\n    class _ProtocolMeta(GenericMeta):\n        \"\"\"Internal metaclass for Protocol.\n\n        This exists so Protocol classes can be generic without deriving\n        from Generic.\n        \"\"\"\n        def __new__(cls, name, bases, namespace,\n                    tvars=None, args=None, origin=None, extra=None, orig_bases=None):\n            # This is just a version copied from GenericMeta.__new__ that\n            # includes \"Protocol\" special treatment. (Comments removed for brevity.)\n            assert extra is None  # Protocols should not have extra\n            if tvars is not None:\n                assert origin is not None\n                assert all(isinstance(t, typing.TypeVar) for t in tvars), tvars\n            else:\n                tvars = _type_vars(bases)\n                gvars = None\n                for base in bases:\n                    if base is typing.Generic:\n                        raise TypeError(\"Cannot inherit from plain Generic\")\n                    if (isinstance(base, GenericMeta) and\n                            base.__origin__ in (typing.Generic, Protocol)):\n                        if gvars is not None:\n                            raise TypeError(\n                                \"Cannot inherit from Generic[...] or\"\n                                \" Protocol[...] multiple times.\")\n                        gvars = base.__parameters__\n                if gvars is None:\n                    gvars = tvars\n                else:\n                    tvarset = set(tvars)\n                    gvarset = set(gvars)\n                    if not tvarset <= gvarset:\n                        s_vars = \", \".join(str(t) for t in tvars if t not in gvarset)\n                        s_args = \", \".join(str(g) for g in gvars)\n                        cls_name = \"Generic\" if any(b.__origin__ is typing.Generic\n                                                    for b in bases) else \"Protocol\"\n                        raise TypeError(f\"Some type variables ({s_vars}) are\"\n                                        f\" not listed in {cls_name}[{s_args}]\")\n                    tvars = gvars\n\n            initial_bases = bases\n            if (extra is not None and type(extra) is abc.ABCMeta and\n                    extra not in bases):\n                bases = (extra,) + bases\n            bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b\n                          for b in bases)\n            if any(isinstance(b, GenericMeta) and b is not typing.Generic for b in bases):\n                bases = tuple(b for b in bases if b is not typing.Generic)\n            namespace.update({'__origin__': origin, '__extra__': extra})\n            self = super(GenericMeta, cls).__new__(cls, name, bases, namespace,\n                                                   _root=True)\n            super(GenericMeta, self).__setattr__('_gorg',\n                                                 self if not origin else\n                                                 _gorg(origin))\n            self.__parameters__ = tvars\n            self.__args__ = tuple(... if a is typing._TypingEllipsis else\n                                  () if a is typing._TypingEmpty else\n                                  a for a in args) if args else None\n            self.__next_in_mro__ = _next_in_mro(self)\n            if orig_bases is None:\n                self.__orig_bases__ = initial_bases\n            elif origin is not None:\n                self._abc_registry = origin._abc_registry\n                self._abc_cache = origin._abc_cache\n            if hasattr(self, '_subs_tree'):\n                self.__tree_hash__ = (hash(self._subs_tree()) if origin else\n                                      super(GenericMeta, self).__hash__())\n            return self\n\n        def __init__(cls, *args, **kwargs):\n            super().__init__(*args, **kwargs)\n            if not cls.__dict__.get('_is_protocol', None):\n                cls._is_protocol = any(b is Protocol or\n                                       isinstance(b, _ProtocolMeta) and\n                                       b.__origin__ is Protocol\n                                       for b in cls.__bases__)\n            if cls._is_protocol:\n                for base in cls.__mro__[1:]:\n                    if not (base in (object, typing.Generic) or\n                            base.__module__ == 'collections.abc' and\n                            base.__name__ in _PROTO_WHITELIST or\n                            isinstance(base, typing.TypingMeta) and base._is_protocol or\n                            isinstance(base, GenericMeta) and\n                            base.__origin__ is typing.Generic):\n                        raise TypeError(f'Protocols can only inherit from other'\n                                        f' protocols, got {repr(base)}')\n\n                cls.__init__ = _no_init\n\n            def _proto_hook(other):\n                if not cls.__dict__.get('_is_protocol', None):\n                    return NotImplemented\n                if not isinstance(other, type):\n                    # Same error as for issubclass(1, int)\n                    raise TypeError('issubclass() arg 1 must be a class')\n                for attr in _get_protocol_attrs(cls):\n                    for base in other.__mro__:\n                        if attr in base.__dict__:\n                            if base.__dict__[attr] is None:\n                                return NotImplemented\n                            break\n                        annotations = getattr(base, '__annotations__', {})\n                        if (isinstance(annotations, typing.Mapping) and\n                                attr in annotations and\n                                isinstance(other, _ProtocolMeta) and\n                                other._is_protocol):\n                            break\n                    else:\n                        return NotImplemented\n                return True\n            if '__subclasshook__' not in cls.__dict__:\n                cls.__subclasshook__ = _proto_hook\n\n        def __instancecheck__(self, instance):\n            # We need this method for situations where attributes are\n            # assigned in __init__.\n            if ((not getattr(self, '_is_protocol', False) or\n                    _is_callable_members_only(self)) and\n                    issubclass(instance.__class__, self)):\n                return True\n            if self._is_protocol:\n                if all(hasattr(instance, attr) and\n                        (not callable(getattr(self, attr, None)) or\n                         getattr(instance, attr) is not None)\n                        for attr in _get_protocol_attrs(self)):\n                    return True\n            return super(GenericMeta, self).__instancecheck__(instance)\n\n        def __subclasscheck__(self, cls):\n            if self.__origin__ is not None:\n                if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:\n                    raise TypeError(\"Parameterized generics cannot be used with class \"\n                                    \"or instance checks\")\n                return False\n            if (self.__dict__.get('_is_protocol', None) and\n                    not self.__dict__.get('_is_runtime_protocol', None)):\n                if sys._getframe(1).f_globals['__name__'] in ['abc',\n                                                              'functools',\n                                                              'typing']:\n                    return False\n                raise TypeError(\"Instance and class checks can only be used with\"\n                                \" @runtime protocols\")\n            if (self.__dict__.get('_is_runtime_protocol', None) and\n                    not _is_callable_members_only(self)):\n                if sys._getframe(1).f_globals['__name__'] in ['abc',\n                                                              'functools',\n                                                              'typing']:\n                    return super(GenericMeta, self).__subclasscheck__(cls)\n                raise TypeError(\"Protocols with non-method members\"\n                                \" don't support issubclass()\")\n            return super(GenericMeta, self).__subclasscheck__(cls)\n\n        @typing._tp_cache\n        def __getitem__(self, params):\n            # We also need to copy this from GenericMeta.__getitem__ to get\n            # special treatment of \"Protocol\". (Comments removed for brevity.)\n            if not isinstance(params, tuple):\n                params = (params,)\n            if not params and _gorg(self) is not typing.Tuple:\n                raise TypeError(\n                    f\"Parameter list to {self.__qualname__}[...] cannot be empty\")\n            msg = \"Parameters to generic types must be types.\"\n            params = tuple(_type_check(p, msg) for p in params)\n            if self in (typing.Generic, Protocol):\n                if not all(isinstance(p, typing.TypeVar) for p in params):\n                    raise TypeError(\n                        f\"Parameters to {repr(self)}[...] must all be type variables\")\n                if len(set(params)) != len(params):\n                    raise TypeError(\n                        f\"Parameters to {repr(self)}[...] must all be unique\")\n                tvars = params\n                args = params\n            elif self in (typing.Tuple, typing.Callable):\n                tvars = _type_vars(params)\n                args = params\n            elif self.__origin__ in (typing.Generic, Protocol):\n                raise TypeError(f\"Cannot subscript already-subscripted {repr(self)}\")\n            else:\n                _check_generic(self, params)\n                tvars = _type_vars(params)\n                args = params\n\n            prepend = (self,) if self.__origin__ is None else ()\n            return self.__class__(self.__name__,\n                                  prepend + self.__bases__,\n                                  _no_slots_copy(self.__dict__),\n                                  tvars=tvars,\n                                  args=args,\n                                  origin=self,\n                                  extra=self.__extra__,\n                                  orig_bases=self.__orig_bases__)\n\n    class Protocol(metaclass=_ProtocolMeta):\n        \"\"\"Base class for protocol classes. Protocol classes are defined as::\n\n          class Proto(Protocol):\n              def meth(self) -> int:\n                  ...\n\n        Such classes are primarily used with static type checkers that recognize\n        structural subtyping (static duck-typing), for example::\n\n          class C:\n              def meth(self) -> int:\n                  return 0\n\n          def func(x: Proto) -> int:\n              return x.meth()\n\n          func(C())  # Passes static type check\n\n        See PEP 544 for details. Protocol classes decorated with\n        @typing_extensions.runtime act as simple-minded runtime protocol that checks\n        only the presence of given attributes, ignoring their type signatures.\n\n        Protocol classes can be generic, they are defined as::\n\n          class GenProto(Protocol[T]):\n              def meth(self) -> T:\n                  ...\n        \"\"\"\n        __slots__ = ()\n        _is_protocol = True\n\n        def __new__(cls, *args, **kwds):\n            if _gorg(cls) is Protocol:\n                raise TypeError(\"Type Protocol cannot be instantiated; \"\n                                \"it can be used only as a base class\")\n            return typing._generic_new(cls.__next_in_mro__, cls, *args, **kwds)\n\n\n# 3.8+\nif hasattr(typing, 'runtime_checkable'):\n    runtime_checkable = typing.runtime_checkable\n# 3.6-3.7\nelse:\n    def runtime_checkable(cls):\n        \"\"\"Mark a protocol class as a runtime protocol, so that it\n        can be used with isinstance() and issubclass(). Raise TypeError\n        if applied to a non-protocol class.\n\n        This allows a simple-minded structural check very similar to the\n        one-offs in collections.abc such as Hashable.\n        \"\"\"\n        if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol:\n            raise TypeError('@runtime_checkable can be only applied to protocol classes,'\n                            f' got {cls!r}')\n        cls._is_runtime_protocol = True\n        return cls\n\n\n# Exists for backwards compatibility.\nruntime = runtime_checkable\n\n\n# 3.8+\nif hasattr(typing, 'SupportsIndex'):\n    SupportsIndex = typing.SupportsIndex\n# 3.6-3.7\nelse:\n    @runtime_checkable\n    class SupportsIndex(Protocol):\n        __slots__ = ()\n\n        @abc.abstractmethod\n        def __index__(self) -> int:\n            pass\n\n\nif sys.version_info >= (3, 9, 2):\n    # The standard library TypedDict in Python 3.8 does not store runtime information\n    # about which (if any) keys are optional.  See https://bugs.python.org/issue38834\n    # The standard library TypedDict in Python 3.9.0/1 does not honour the \"total\"\n    # keyword with old-style TypedDict().  See https://bugs.python.org/issue42059\n    TypedDict = typing.TypedDict\nelse:\n    def _check_fails(cls, other):\n        try:\n            if sys._getframe(1).f_globals['__name__'] not in ['abc',\n                                                              'functools',\n                                                              'typing']:\n                # Typed dicts are only for static structural subtyping.\n                raise TypeError('TypedDict does not support instance and class checks')\n        except (AttributeError, ValueError):\n            pass\n        return False\n\n    def _dict_new(*args, **kwargs):\n        if not args:\n            raise TypeError('TypedDict.__new__(): not enough arguments')\n        _, args = args[0], args[1:]  # allow the \"cls\" keyword be passed\n        return dict(*args, **kwargs)\n\n    _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)'\n\n    def _typeddict_new(*args, total=True, **kwargs):\n        if not args:\n            raise TypeError('TypedDict.__new__(): not enough arguments')\n        _, args = args[0], args[1:]  # allow the \"cls\" keyword be passed\n        if args:\n            typename, args = args[0], args[1:]  # allow the \"_typename\" keyword be passed\n        elif '_typename' in kwargs:\n            typename = kwargs.pop('_typename')\n            import warnings\n            warnings.warn(\"Passing '_typename' as keyword argument is deprecated\",\n                          DeprecationWarning, stacklevel=2)\n        else:\n            raise TypeError(\"TypedDict.__new__() missing 1 required positional \"\n                            \"argument: '_typename'\")\n        if args:\n            try:\n                fields, = args  # allow the \"_fields\" keyword be passed\n            except ValueError:\n                raise TypeError('TypedDict.__new__() takes from 2 to 3 '\n                                f'positional arguments but {len(args) + 2} '\n                                'were given')\n        elif '_fields' in kwargs and len(kwargs) == 1:\n            fields = kwargs.pop('_fields')\n            import warnings\n            warnings.warn(\"Passing '_fields' as keyword argument is deprecated\",\n                          DeprecationWarning, stacklevel=2)\n        else:\n            fields = None\n\n        if fields is None:\n            fields = kwargs\n        elif kwargs:\n            raise TypeError(\"TypedDict takes either a dict or keyword arguments,\"\n                            \" but not both\")\n\n        ns = {'__annotations__': dict(fields)}\n        try:\n            # Setting correct module is necessary to make typed dict classes pickleable.\n            ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')\n        except (AttributeError, ValueError):\n            pass\n\n        return _TypedDictMeta(typename, (), ns, total=total)\n\n    _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,'\n                                         ' /, *, total=True, **kwargs)')\n\n    class _TypedDictMeta(type):\n        def __init__(cls, name, bases, ns, total=True):\n            super().__init__(name, bases, ns)\n\n        def __new__(cls, name, bases, ns, total=True):\n            # Create new typed dict class object.\n            # This method is called directly when TypedDict is subclassed,\n            # or via _typeddict_new when TypedDict is instantiated. This way\n            # TypedDict supports all three syntaxes described in its docstring.\n            # Subclasses and instances of TypedDict return actual dictionaries\n            # via _dict_new.\n            ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new\n            tp_dict = super().__new__(cls, name, (dict,), ns)\n\n            annotations = {}\n            own_annotations = ns.get('__annotations__', {})\n            own_annotation_keys = set(own_annotations.keys())\n            msg = \"TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type\"\n            own_annotations = {\n                n: typing._type_check(tp, msg) for n, tp in own_annotations.items()\n            }\n            required_keys = set()\n            optional_keys = set()\n\n            for base in bases:\n                annotations.update(base.__dict__.get('__annotations__', {}))\n                required_keys.update(base.__dict__.get('__required_keys__', ()))\n                optional_keys.update(base.__dict__.get('__optional_keys__', ()))\n\n            annotations.update(own_annotations)\n            if total:\n                required_keys.update(own_annotation_keys)\n            else:\n                optional_keys.update(own_annotation_keys)\n\n            tp_dict.__annotations__ = annotations\n            tp_dict.__required_keys__ = frozenset(required_keys)\n            tp_dict.__optional_keys__ = frozenset(optional_keys)\n            if not hasattr(tp_dict, '__total__'):\n                tp_dict.__total__ = total\n            return tp_dict\n\n        __instancecheck__ = __subclasscheck__ = _check_fails\n\n    TypedDict = _TypedDictMeta('TypedDict', (dict,), {})\n    TypedDict.__module__ = __name__\n    TypedDict.__doc__ = \\\n        \"\"\"A simple typed name space. At runtime it is equivalent to a plain dict.\n\n        TypedDict creates a dictionary type that expects all of its\n        instances to have a certain set of keys, with each key\n        associated with a value of a consistent type. This expectation\n        is not checked at runtime but is only enforced by type checkers.\n        Usage::\n\n            class Point2D(TypedDict):\n                x: int\n                y: int\n                label: str\n\n            a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK\n            b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check\n\n            assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')\n\n        The type info can be accessed via the Point2D.__annotations__ dict, and\n        the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.\n        TypedDict supports two additional equivalent forms::\n\n            Point2D = TypedDict('Point2D', x=int, y=int, label=str)\n            Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})\n\n        The class syntax is only supported in Python 3.6+, while two other\n        syntax forms work for Python 2.7 and 3.2+\n        \"\"\"\n\n\n# Python 3.9+ has PEP 593 (Annotated and modified get_type_hints)\nif hasattr(typing, 'Annotated'):\n    Annotated = typing.Annotated\n    get_type_hints = typing.get_type_hints\n    # Not exported and not a public API, but needed for get_origin() and get_args()\n    # to work.\n    _AnnotatedAlias = typing._AnnotatedAlias\n# 3.7-3.8\nelif PEP_560:\n    class _AnnotatedAlias(typing._GenericAlias, _root=True):\n        \"\"\"Runtime representation of an annotated type.\n\n        At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'\n        with extra annotations. The alias behaves like a normal typing alias,\n        instantiating is the same as instantiating the underlying type, binding\n        it to types is also the same.\n        \"\"\"\n        def __init__(self, origin, metadata):\n            if isinstance(origin, _AnnotatedAlias):\n                metadata = origin.__metadata__ + metadata\n                origin = origin.__origin__\n            super().__init__(origin, origin)\n            self.__metadata__ = metadata\n\n        def copy_with(self, params):\n            assert len(params) == 1\n            new_type = params[0]\n            return _AnnotatedAlias(new_type, self.__metadata__)\n\n        def __repr__(self):\n            return (f\"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, \"\n                    f\"{', '.join(repr(a) for a in self.__metadata__)}]\")\n\n        def __reduce__(self):\n            return operator.getitem, (\n                Annotated, (self.__origin__,) + self.__metadata__\n            )\n\n        def __eq__(self, other):\n            if not isinstance(other, _AnnotatedAlias):\n                return NotImplemented\n            if self.__origin__ != other.__origin__:\n                return False\n            return self.__metadata__ == other.__metadata__\n\n        def __hash__(self):\n            return hash((self.__origin__, self.__metadata__))\n\n    class Annotated:\n        \"\"\"Add context specific metadata to a type.\n\n        Example: Annotated[int, runtime_check.Unsigned] indicates to the\n        hypothetical runtime_check module that this type is an unsigned int.\n        Every other consumer of this type can ignore this metadata and treat\n        this type as int.\n\n        The first argument to Annotated must be a valid type (and will be in\n        the __origin__ field), the remaining arguments are kept as a tuple in\n        the __extra__ field.\n\n        Details:\n\n        - It's an error to call `Annotated` with less than two arguments.\n        - Nested Annotated are flattened::\n\n            Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]\n\n        - Instantiating an annotated type is equivalent to instantiating the\n        underlying type::\n\n            Annotated[C, Ann1](5) == C(5)\n\n        - Annotated can be used as a generic type alias::\n\n            Optimized = Annotated[T, runtime.Optimize()]\n            Optimized[int] == Annotated[int, runtime.Optimize()]\n\n            OptimizedList = Annotated[List[T], runtime.Optimize()]\n            OptimizedList[int] == Annotated[List[int], runtime.Optimize()]\n        \"\"\"\n\n        __slots__ = ()\n\n        def __new__(cls, *args, **kwargs):\n            raise TypeError(\"Type Annotated cannot be instantiated.\")\n\n        @typing._tp_cache\n        def __class_getitem__(cls, params):\n            if not isinstance(params, tuple) or len(params) < 2:\n                raise TypeError(\"Annotated[...] should be used \"\n                                \"with at least two arguments (a type and an \"\n                                \"annotation).\")\n            msg = \"Annotated[t, ...]: t must be a type.\"\n            origin = typing._type_check(params[0], msg)\n            metadata = tuple(params[1:])\n            return _AnnotatedAlias(origin, metadata)\n\n        def __init_subclass__(cls, *args, **kwargs):\n            raise TypeError(\n                f\"Cannot subclass {cls.__module__}.Annotated\"\n            )\n\n    def _strip_annotations(t):\n        \"\"\"Strips the annotations from a given type.\n        \"\"\"\n        if isinstance(t, _AnnotatedAlias):\n            return _strip_annotations(t.__origin__)\n        if isinstance(t, typing._GenericAlias):\n            stripped_args = tuple(_strip_annotations(a) for a in t.__args__)\n            if stripped_args == t.__args__:\n                return t\n            res = t.copy_with(stripped_args)\n            res._special = t._special\n            return res\n        return t\n\n    def get_type_hints(obj, globalns=None, localns=None, include_extras=False):\n        \"\"\"Return type hints for an object.\n\n        This is often the same as obj.__annotations__, but it handles\n        forward references encoded as string literals, adds Optional[t] if a\n        default value equal to None is set and recursively replaces all\n        'Annotated[T, ...]' with 'T' (unless 'include_extras=True').\n\n        The argument may be a module, class, method, or function. The annotations\n        are returned as a dictionary. For classes, annotations include also\n        inherited members.\n\n        TypeError is raised if the argument is not of a type that can contain\n        annotations, and an empty dictionary is returned if no annotations are\n        present.\n\n        BEWARE -- the behavior of globalns and localns is counterintuitive\n        (unless you are familiar with how eval() and exec() work).  The\n        search order is locals first, then globals.\n\n        - If no dict arguments are passed, an attempt is made to use the\n          globals from obj (or the respective module's globals for classes),\n          and these are also used as the locals.  If the object does not appear\n          to have globals, an empty dictionary is used.\n\n        - If one dict argument is passed, it is used for both globals and\n          locals.\n\n        - If two dict arguments are passed, they specify globals and\n          locals, respectively.\n        \"\"\"\n        hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)\n        if include_extras:\n            return hint\n        return {k: _strip_annotations(t) for k, t in hint.items()}\n# 3.6\nelse:\n\n    def _is_dunder(name):\n        \"\"\"Returns True if name is a __dunder_variable_name__.\"\"\"\n        return len(name) > 4 and name.startswith('__') and name.endswith('__')\n\n    # Prior to Python 3.7 types did not have `copy_with`. A lot of the equality\n    # checks, argument expansion etc. are done on the _subs_tre. As a result we\n    # can't provide a get_type_hints function that strips out annotations.\n\n    class AnnotatedMeta(typing.GenericMeta):\n        \"\"\"Metaclass for Annotated\"\"\"\n\n        def __new__(cls, name, bases, namespace, **kwargs):\n            if any(b is not object for b in bases):\n                raise TypeError(\"Cannot subclass \" + str(Annotated))\n            return super().__new__(cls, name, bases, namespace, **kwargs)\n\n        @property\n        def __metadata__(self):\n            return self._subs_tree()[2]\n\n        def _tree_repr(self, tree):\n            cls, origin, metadata = tree\n            if not isinstance(origin, tuple):\n                tp_repr = typing._type_repr(origin)\n            else:\n                tp_repr = origin[0]._tree_repr(origin)\n            metadata_reprs = \", \".join(repr(arg) for arg in metadata)\n            return f'{cls}[{tp_repr}, {metadata_reprs}]'\n\n        def _subs_tree(self, tvars=None, args=None):  # noqa\n            if self is Annotated:\n                return Annotated\n            res = super()._subs_tree(tvars=tvars, args=args)\n            # Flatten nested Annotated\n            if isinstance(res[1], tuple) and res[1][0] is Annotated:\n                sub_tp = res[1][1]\n                sub_annot = res[1][2]\n                return (Annotated, sub_tp, sub_annot + res[2])\n            return res\n\n        def _get_cons(self):\n            \"\"\"Return the class used to create instance of this type.\"\"\"\n            if self.__origin__ is None:\n                raise TypeError(\"Cannot get the underlying type of a \"\n                                \"non-specialized Annotated type.\")\n            tree = self._subs_tree()\n            while isinstance(tree, tuple) and tree[0] is Annotated:\n                tree = tree[1]\n            if isinstance(tree, tuple):\n                return tree[0]\n            else:\n                return tree\n\n        @typing._tp_cache\n        def __getitem__(self, params):\n            if not isinstance(params, tuple):\n                params = (params,)\n            if self.__origin__ is not None:  # specializing an instantiated type\n                return super().__getitem__(params)\n            elif not isinstance(params, tuple) or len(params) < 2:\n                raise TypeError(\"Annotated[...] should be instantiated \"\n                                \"with at least two arguments (a type and an \"\n                                \"annotation).\")\n            else:\n                msg = \"Annotated[t, ...]: t must be a type.\"\n                tp = typing._type_check(params[0], msg)\n                metadata = tuple(params[1:])\n            return self.__class__(\n                self.__name__,\n                self.__bases__,\n                _no_slots_copy(self.__dict__),\n                tvars=_type_vars((tp,)),\n                # Metadata is a tuple so it won't be touched by _replace_args et al.\n                args=(tp, metadata),\n                origin=self,\n            )\n\n        def __call__(self, *args, **kwargs):\n            cons = self._get_cons()\n            result = cons(*args, **kwargs)\n            try:\n                result.__orig_class__ = self\n            except AttributeError:\n                pass\n            return result\n\n        def __getattr__(self, attr):\n            # For simplicity we just don't relay all dunder names\n            if self.__origin__ is not None and not _is_dunder(attr):\n                return getattr(self._get_cons(), attr)\n            raise AttributeError(attr)\n\n        def __setattr__(self, attr, value):\n            if _is_dunder(attr) or attr.startswith('_abc_'):\n                super().__setattr__(attr, value)\n            elif self.__origin__ is None:\n                raise AttributeError(attr)\n            else:\n                setattr(self._get_cons(), attr, value)\n\n        def __instancecheck__(self, obj):\n            raise TypeError(\"Annotated cannot be used with isinstance().\")\n\n        def __subclasscheck__(self, cls):\n            raise TypeError(\"Annotated cannot be used with issubclass().\")\n\n    class Annotated(metaclass=AnnotatedMeta):\n        \"\"\"Add context specific metadata to a type.\n\n        Example: Annotated[int, runtime_check.Unsigned] indicates to the\n        hypothetical runtime_check module that this type is an unsigned int.\n        Every other consumer of this type can ignore this metadata and treat\n        this type as int.\n\n        The first argument to Annotated must be a valid type, the remaining\n        arguments are kept as a tuple in the __metadata__ field.\n\n        Details:\n\n        - It's an error to call `Annotated` with less than two arguments.\n        - Nested Annotated are flattened::\n\n            Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]\n\n        - Instantiating an annotated type is equivalent to instantiating the\n        underlying type::\n\n            Annotated[C, Ann1](5) == C(5)\n\n        - Annotated can be used as a generic type alias::\n\n            Optimized = Annotated[T, runtime.Optimize()]\n            Optimized[int] == Annotated[int, runtime.Optimize()]\n\n            OptimizedList = Annotated[List[T], runtime.Optimize()]\n            OptimizedList[int] == Annotated[List[int], runtime.Optimize()]\n        \"\"\"\n\n# Python 3.8 has get_origin() and get_args() but those implementations aren't\n# Annotated-aware, so we can't use those. Python 3.9's versions don't support\n# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.\nif sys.version_info[:2] >= (3, 10):\n    get_origin = typing.get_origin\n    get_args = typing.get_args\n# 3.7-3.9\nelif PEP_560:\n    try:\n        # 3.9+\n        from typing import _BaseGenericAlias\n    except ImportError:\n        _BaseGenericAlias = typing._GenericAlias\n    try:\n        # 3.9+\n        from typing import GenericAlias\n    except ImportError:\n        GenericAlias = typing._GenericAlias\n\n    def get_origin(tp):\n        \"\"\"Get the unsubscripted version of a type.\n\n        This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar\n        and Annotated. Return None for unsupported types. Examples::\n\n            get_origin(Literal[42]) is Literal\n            get_origin(int) is None\n            get_origin(ClassVar[int]) is ClassVar\n            get_origin(Generic) is Generic\n            get_origin(Generic[T]) is Generic\n            get_origin(Union[T, int]) is Union\n            get_origin(List[Tuple[T, T]][int]) == list\n            get_origin(P.args) is P\n        \"\"\"\n        if isinstance(tp, _AnnotatedAlias):\n            return Annotated\n        if isinstance(tp, (typing._GenericAlias, GenericAlias, _BaseGenericAlias,\n                           ParamSpecArgs, ParamSpecKwargs)):\n            return tp.__origin__\n        if tp is typing.Generic:\n            return typing.Generic\n        return None\n\n    def get_args(tp):\n        \"\"\"Get type arguments with all substitutions performed.\n\n        For unions, basic simplifications used by Union constructor are performed.\n        Examples::\n            get_args(Dict[str, int]) == (str, int)\n            get_args(int) == ()\n            get_args(Union[int, Union[T, int], str][int]) == (int, str)\n            get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])\n            get_args(Callable[[], T][int]) == ([], int)\n        \"\"\"\n        if isinstance(tp, _AnnotatedAlias):\n            return (tp.__origin__,) + tp.__metadata__\n        if isinstance(tp, (typing._GenericAlias, GenericAlias)):\n            if getattr(tp, \"_special\", False):\n                return ()\n            res = tp.__args__\n            if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:\n                res = (list(res[:-1]), res[-1])\n            return res\n        return ()\n\n\n# 3.10+\nif hasattr(typing, 'TypeAlias'):\n    TypeAlias = typing.TypeAlias\n# 3.9\nelif sys.version_info[:2] >= (3, 9):\n    class _TypeAliasForm(typing._SpecialForm, _root=True):\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n    @_TypeAliasForm\n    def TypeAlias(self, parameters):\n        \"\"\"Special marker indicating that an assignment should\n        be recognized as a proper type alias definition by type\n        checkers.\n\n        For example::\n\n            Predicate: TypeAlias = Callable[..., bool]\n\n        It's invalid when used anywhere except as in the example above.\n        \"\"\"\n        raise TypeError(f\"{self} is not subscriptable\")\n# 3.7-3.8\nelif sys.version_info[:2] >= (3, 7):\n    class _TypeAliasForm(typing._SpecialForm, _root=True):\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n    TypeAlias = _TypeAliasForm('TypeAlias',\n                               doc=\"\"\"Special marker indicating that an assignment should\n                               be recognized as a proper type alias definition by type\n                               checkers.\n\n                               For example::\n\n                                   Predicate: TypeAlias = Callable[..., bool]\n\n                               It's invalid when used anywhere except as in the example\n                               above.\"\"\")\n# 3.6\nelse:\n    class _TypeAliasMeta(typing.TypingMeta):\n        \"\"\"Metaclass for TypeAlias\"\"\"\n\n        def __repr__(self):\n            return 'typing_extensions.TypeAlias'\n\n    class _TypeAliasBase(typing._FinalTypingBase, metaclass=_TypeAliasMeta, _root=True):\n        \"\"\"Special marker indicating that an assignment should\n        be recognized as a proper type alias definition by type\n        checkers.\n\n        For example::\n\n            Predicate: TypeAlias = Callable[..., bool]\n\n        It's invalid when used anywhere except as in the example above.\n        \"\"\"\n        __slots__ = ()\n\n        def __instancecheck__(self, obj):\n            raise TypeError(\"TypeAlias cannot be used with isinstance().\")\n\n        def __subclasscheck__(self, cls):\n            raise TypeError(\"TypeAlias cannot be used with issubclass().\")\n\n        def __repr__(self):\n            return 'typing_extensions.TypeAlias'\n\n    TypeAlias = _TypeAliasBase(_root=True)\n\n\n# Python 3.10+ has PEP 612\nif hasattr(typing, 'ParamSpecArgs'):\n    ParamSpecArgs = typing.ParamSpecArgs\n    ParamSpecKwargs = typing.ParamSpecKwargs\n# 3.6-3.9\nelse:\n    class _Immutable:\n        \"\"\"Mixin to indicate that object should not be copied.\"\"\"\n        __slots__ = ()\n\n        def __copy__(self):\n            return self\n\n        def __deepcopy__(self, memo):\n            return self\n\n    class ParamSpecArgs(_Immutable):\n        \"\"\"The args for a ParamSpec object.\n\n        Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.\n\n        ParamSpecArgs objects have a reference back to their ParamSpec:\n\n        P.args.__origin__ is P\n\n        This type is meant for runtime introspection and has no special meaning to\n        static type checkers.\n        \"\"\"\n        def __init__(self, origin):\n            self.__origin__ = origin\n\n        def __repr__(self):\n            return f\"{self.__origin__.__name__}.args\"\n\n    class ParamSpecKwargs(_Immutable):\n        \"\"\"The kwargs for a ParamSpec object.\n\n        Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.\n\n        ParamSpecKwargs objects have a reference back to their ParamSpec:\n\n        P.kwargs.__origin__ is P\n\n        This type is meant for runtime introspection and has no special meaning to\n        static type checkers.\n        \"\"\"\n        def __init__(self, origin):\n            self.__origin__ = origin\n\n        def __repr__(self):\n            return f\"{self.__origin__.__name__}.kwargs\"\n\n# 3.10+\nif hasattr(typing, 'ParamSpec'):\n    ParamSpec = typing.ParamSpec\n# 3.6-3.9\nelse:\n\n    # Inherits from list as a workaround for Callable checks in Python < 3.9.2.\n    class ParamSpec(list):\n        \"\"\"Parameter specification variable.\n\n        Usage::\n\n           P = ParamSpec('P')\n\n        Parameter specification variables exist primarily for the benefit of static\n        type checkers.  They are used to forward the parameter types of one\n        callable to another callable, a pattern commonly found in higher order\n        functions and decorators.  They are only valid when used in ``Concatenate``,\n        or s the first argument to ``Callable``. In Python 3.10 and higher,\n        they are also supported in user-defined Generics at runtime.\n        See class Generic for more information on generic types.  An\n        example for annotating a decorator::\n\n           T = TypeVar('T')\n           P = ParamSpec('P')\n\n           def add_logging(f: Callable[P, T]) -> Callable[P, T]:\n               '''A type-safe decorator to add logging to a function.'''\n               def inner(*args: P.args, **kwargs: P.kwargs) -> T:\n                   logging.info(f'{f.__name__} was called')\n                   return f(*args, **kwargs)\n               return inner\n\n           @add_logging\n           def add_two(x: float, y: float) -> float:\n               '''Add two numbers together.'''\n               return x + y\n\n        Parameter specification variables defined with covariant=True or\n        contravariant=True can be used to declare covariant or contravariant\n        generic types.  These keyword arguments are valid, but their actual semantics\n        are yet to be decided.  See PEP 612 for details.\n\n        Parameter specification variables can be introspected. e.g.:\n\n           P.__name__ == 'T'\n           P.__bound__ == None\n           P.__covariant__ == False\n           P.__contravariant__ == False\n\n        Note that only parameter specification variables defined in global scope can\n        be pickled.\n        \"\"\"\n\n        # Trick Generic __parameters__.\n        __class__ = typing.TypeVar\n\n        @property\n        def args(self):\n            return ParamSpecArgs(self)\n\n        @property\n        def kwargs(self):\n            return ParamSpecKwargs(self)\n\n        def __init__(self, name, *, bound=None, covariant=False, contravariant=False):\n            super().__init__([self])\n            self.__name__ = name\n            self.__covariant__ = bool(covariant)\n            self.__contravariant__ = bool(contravariant)\n            if bound:\n                self.__bound__ = typing._type_check(bound, 'Bound must be a type.')\n            else:\n                self.__bound__ = None\n\n            # for pickling:\n            try:\n                def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')\n            except (AttributeError, ValueError):\n                def_mod = None\n            if def_mod != 'typing_extensions':\n                self.__module__ = def_mod\n\n        def __repr__(self):\n            if self.__covariant__:\n                prefix = '+'\n            elif self.__contravariant__:\n                prefix = '-'\n            else:\n                prefix = '~'\n            return prefix + self.__name__\n\n        def __hash__(self):\n            return object.__hash__(self)\n\n        def __eq__(self, other):\n            return self is other\n\n        def __reduce__(self):\n            return self.__name__\n\n        # Hack to get typing._type_check to pass.\n        def __call__(self, *args, **kwargs):\n            pass\n\n        if not PEP_560:\n            # Only needed in 3.6.\n            def _get_type_vars(self, tvars):\n                if self not in tvars:\n                    tvars.append(self)\n\n\n# 3.6-3.9\nif not hasattr(typing, 'Concatenate'):\n    # Inherits from list as a workaround for Callable checks in Python < 3.9.2.\n    class _ConcatenateGenericAlias(list):\n\n        # Trick Generic into looking into this for __parameters__.\n        if PEP_560:\n            __class__ = typing._GenericAlias\n        else:\n            __class__ = typing._TypingBase\n\n        # Flag in 3.8.\n        _special = False\n        # Attribute in 3.6 and earlier.\n        _gorg = typing.Generic\n\n        def __init__(self, origin, args):\n            super().__init__(args)\n            self.__origin__ = origin\n            self.__args__ = args\n\n        def __repr__(self):\n            _type_repr = typing._type_repr\n            return (f'{_type_repr(self.__origin__)}'\n                    f'[{\", \".join(_type_repr(arg) for arg in self.__args__)}]')\n\n        def __hash__(self):\n            return hash((self.__origin__, self.__args__))\n\n        # Hack to get typing._type_check to pass in Generic.\n        def __call__(self, *args, **kwargs):\n            pass\n\n        @property\n        def __parameters__(self):\n            return tuple(\n                tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))\n            )\n\n        if not PEP_560:\n            # Only required in 3.6.\n            def _get_type_vars(self, tvars):\n                if self.__origin__ and self.__parameters__:\n                    typing._get_type_vars(self.__parameters__, tvars)\n\n\n# 3.6-3.9\n@typing._tp_cache\ndef _concatenate_getitem(self, parameters):\n    if parameters == ():\n        raise TypeError(\"Cannot take a Concatenate of no types.\")\n    if not isinstance(parameters, tuple):\n        parameters = (parameters,)\n    if not isinstance(parameters[-1], ParamSpec):\n        raise TypeError(\"The last parameter to Concatenate should be a \"\n                        \"ParamSpec variable.\")\n    msg = \"Concatenate[arg, ...]: each arg must be a type.\"\n    parameters = tuple(typing._type_check(p, msg) for p in parameters)\n    return _ConcatenateGenericAlias(self, parameters)\n\n\n# 3.10+\nif hasattr(typing, 'Concatenate'):\n    Concatenate = typing.Concatenate\n    _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa\n# 3.9\nelif sys.version_info[:2] >= (3, 9):\n    @_TypeAliasForm\n    def Concatenate(self, parameters):\n        \"\"\"Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a\n        higher order function which adds, removes or transforms parameters of a\n        callable.\n\n        For example::\n\n           Callable[Concatenate[int, P], int]\n\n        See PEP 612 for detailed information.\n        \"\"\"\n        return _concatenate_getitem(self, parameters)\n# 3.7-8\nelif sys.version_info[:2] >= (3, 7):\n    class _ConcatenateForm(typing._SpecialForm, _root=True):\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n        def __getitem__(self, parameters):\n            return _concatenate_getitem(self, parameters)\n\n    Concatenate = _ConcatenateForm(\n        'Concatenate',\n        doc=\"\"\"Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a\n        higher order function which adds, removes or transforms parameters of a\n        callable.\n\n        For example::\n\n           Callable[Concatenate[int, P], int]\n\n        See PEP 612 for detailed information.\n        \"\"\")\n# 3.6\nelse:\n    class _ConcatenateAliasMeta(typing.TypingMeta):\n        \"\"\"Metaclass for Concatenate.\"\"\"\n\n        def __repr__(self):\n            return 'typing_extensions.Concatenate'\n\n    class _ConcatenateAliasBase(typing._FinalTypingBase,\n                                metaclass=_ConcatenateAliasMeta,\n                                _root=True):\n        \"\"\"Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a\n        higher order function which adds, removes or transforms parameters of a\n        callable.\n\n        For example::\n\n           Callable[Concatenate[int, P], int]\n\n        See PEP 612 for detailed information.\n        \"\"\"\n        __slots__ = ()\n\n        def __instancecheck__(self, obj):\n            raise TypeError(\"Concatenate cannot be used with isinstance().\")\n\n        def __subclasscheck__(self, cls):\n            raise TypeError(\"Concatenate cannot be used with issubclass().\")\n\n        def __repr__(self):\n            return 'typing_extensions.Concatenate'\n\n        def __getitem__(self, parameters):\n            return _concatenate_getitem(self, parameters)\n\n    Concatenate = _ConcatenateAliasBase(_root=True)\n\n# 3.10+\nif hasattr(typing, 'TypeGuard'):\n    TypeGuard = typing.TypeGuard\n# 3.9\nelif sys.version_info[:2] >= (3, 9):\n    class _TypeGuardForm(typing._SpecialForm, _root=True):\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n    @_TypeGuardForm\n    def TypeGuard(self, parameters):\n        \"\"\"Special typing form used to annotate the return type of a user-defined\n        type guard function.  ``TypeGuard`` only accepts a single type argument.\n        At runtime, functions marked this way should return a boolean.\n\n        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static\n        type checkers to determine a more precise type of an expression within a\n        program's code flow.  Usually type narrowing is done by analyzing\n        conditional code flow and applying the narrowing to a block of code.  The\n        conditional expression here is sometimes referred to as a \"type guard\".\n\n        Sometimes it would be convenient to use a user-defined boolean function\n        as a type guard.  Such a function should use ``TypeGuard[...]`` as its\n        return type to alert static type checkers to this intention.\n\n        Using  ``-> TypeGuard`` tells the static type checker that for a given\n        function:\n\n        1. The return value is a boolean.\n        2. If the return value is ``True``, the type of its argument\n        is the type inside ``TypeGuard``.\n\n        For example::\n\n            def is_str(val: Union[str, float]):\n                # \"isinstance\" type guard\n                if isinstance(val, str):\n                    # Type of ``val`` is narrowed to ``str``\n                    ...\n                else:\n                    # Else, type of ``val`` is narrowed to ``float``.\n                    ...\n\n        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower\n        form of ``TypeA`` (it can even be a wider form) and this may lead to\n        type-unsafe results.  The main reason is to allow for things like\n        narrowing ``List[object]`` to ``List[str]`` even though the latter is not\n        a subtype of the former, since ``List`` is invariant.  The responsibility of\n        writing type-safe type guards is left to the user.\n\n        ``TypeGuard`` also works with type variables.  For more information, see\n        PEP 647 (User-Defined Type Guards).\n        \"\"\"\n        item = typing._type_check(parameters, f'{self} accepts only single type.')\n        return typing._GenericAlias(self, (item,))\n# 3.7-3.8\nelif sys.version_info[:2] >= (3, 7):\n    class _TypeGuardForm(typing._SpecialForm, _root=True):\n\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n        def __getitem__(self, parameters):\n            item = typing._type_check(parameters,\n                                      f'{self._name} accepts only a single type')\n            return typing._GenericAlias(self, (item,))\n\n    TypeGuard = _TypeGuardForm(\n        'TypeGuard',\n        doc=\"\"\"Special typing form used to annotate the return type of a user-defined\n        type guard function.  ``TypeGuard`` only accepts a single type argument.\n        At runtime, functions marked this way should return a boolean.\n\n        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static\n        type checkers to determine a more precise type of an expression within a\n        program's code flow.  Usually type narrowing is done by analyzing\n        conditional code flow and applying the narrowing to a block of code.  The\n        conditional expression here is sometimes referred to as a \"type guard\".\n\n        Sometimes it would be convenient to use a user-defined boolean function\n        as a type guard.  Such a function should use ``TypeGuard[...]`` as its\n        return type to alert static type checkers to this intention.\n\n        Using  ``-> TypeGuard`` tells the static type checker that for a given\n        function:\n\n        1. The return value is a boolean.\n        2. If the return value is ``True``, the type of its argument\n        is the type inside ``TypeGuard``.\n\n        For example::\n\n            def is_str(val: Union[str, float]):\n                # \"isinstance\" type guard\n                if isinstance(val, str):\n                    # Type of ``val`` is narrowed to ``str``\n                    ...\n                else:\n                    # Else, type of ``val`` is narrowed to ``float``.\n                    ...\n\n        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower\n        form of ``TypeA`` (it can even be a wider form) and this may lead to\n        type-unsafe results.  The main reason is to allow for things like\n        narrowing ``List[object]`` to ``List[str]`` even though the latter is not\n        a subtype of the former, since ``List`` is invariant.  The responsibility of\n        writing type-safe type guards is left to the user.\n\n        ``TypeGuard`` also works with type variables.  For more information, see\n        PEP 647 (User-Defined Type Guards).\n        \"\"\")\n# 3.6\nelse:\n    class _TypeGuard(typing._FinalTypingBase, _root=True):\n        \"\"\"Special typing form used to annotate the return type of a user-defined\n        type guard function.  ``TypeGuard`` only accepts a single type argument.\n        At runtime, functions marked this way should return a boolean.\n\n        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static\n        type checkers to determine a more precise type of an expression within a\n        program's code flow.  Usually type narrowing is done by analyzing\n        conditional code flow and applying the narrowing to a block of code.  The\n        conditional expression here is sometimes referred to as a \"type guard\".\n\n        Sometimes it would be convenient to use a user-defined boolean function\n        as a type guard.  Such a function should use ``TypeGuard[...]`` as its\n        return type to alert static type checkers to this intention.\n\n        Using  ``-> TypeGuard`` tells the static type checker that for a given\n        function:\n\n        1. The return value is a boolean.\n        2. If the return value is ``True``, the type of its argument\n        is the type inside ``TypeGuard``.\n\n        For example::\n\n            def is_str(val: Union[str, float]):\n                # \"isinstance\" type guard\n                if isinstance(val, str):\n                    # Type of ``val`` is narrowed to ``str``\n                    ...\n                else:\n                    # Else, type of ``val`` is narrowed to ``float``.\n                    ...\n\n        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower\n        form of ``TypeA`` (it can even be a wider form) and this may lead to\n        type-unsafe results.  The main reason is to allow for things like\n        narrowing ``List[object]`` to ``List[str]`` even though the latter is not\n        a subtype of the former, since ``List`` is invariant.  The responsibility of\n        writing type-safe type guards is left to the user.\n\n        ``TypeGuard`` also works with type variables.  For more information, see\n        PEP 647 (User-Defined Type Guards).\n        \"\"\"\n\n        __slots__ = ('__type__',)\n\n        def __init__(self, tp=None, **kwds):\n            self.__type__ = tp\n\n        def __getitem__(self, item):\n            cls = type(self)\n            if self.__type__ is None:\n                return cls(typing._type_check(item,\n                           f'{cls.__name__[1:]} accepts only a single type.'),\n                           _root=True)\n            raise TypeError(f'{cls.__name__[1:]} cannot be further subscripted')\n\n        def _eval_type(self, globalns, localns):\n            new_tp = typing._eval_type(self.__type__, globalns, localns)\n            if new_tp == self.__type__:\n                return self\n            return type(self)(new_tp, _root=True)\n\n        def __repr__(self):\n            r = super().__repr__()\n            if self.__type__ is not None:\n                r += f'[{typing._type_repr(self.__type__)}]'\n            return r\n\n        def __hash__(self):\n            return hash((type(self).__name__, self.__type__))\n\n        def __eq__(self, other):\n            if not isinstance(other, _TypeGuard):\n                return NotImplemented\n            if self.__type__ is not None:\n                return self.__type__ == other.__type__\n            return self is other\n\n    TypeGuard = _TypeGuard(_root=True)\n\nif hasattr(typing, \"Self\"):\n    Self = typing.Self\nelif sys.version_info[:2] >= (3, 7):\n    # Vendored from cpython typing._SpecialFrom\n    class _SpecialForm(typing._Final, _root=True):\n        __slots__ = ('_name', '__doc__', '_getitem')\n\n        def __init__(self, getitem):\n            self._getitem = getitem\n            self._name = getitem.__name__\n            self.__doc__ = getitem.__doc__\n\n        def __getattr__(self, item):\n            if item in {'__name__', '__qualname__'}:\n                return self._name\n\n            raise AttributeError(item)\n\n        def __mro_entries__(self, bases):\n            raise TypeError(f\"Cannot subclass {self!r}\")\n\n        def __repr__(self):\n            return f'typing_extensions.{self._name}'\n\n        def __reduce__(self):\n            return self._name\n\n        def __call__(self, *args, **kwds):\n            raise TypeError(f\"Cannot instantiate {self!r}\")\n\n        def __or__(self, other):\n            return typing.Union[self, other]\n\n        def __ror__(self, other):\n            return typing.Union[other, self]\n\n        def __instancecheck__(self, obj):\n            raise TypeError(f\"{self} cannot be used with isinstance()\")\n\n        def __subclasscheck__(self, cls):\n            raise TypeError(f\"{self} cannot be used with issubclass()\")\n\n        @typing._tp_cache\n        def __getitem__(self, parameters):\n            return self._getitem(self, parameters)\n\n    @_SpecialForm\n    def Self(self, params):\n        \"\"\"Used to spell the type of \"self\" in classes.\n\n        Example::\n\n          from typing import Self\n\n          class ReturnsSelf:\n              def parse(self, data: bytes) -> Self:\n                  ...\n                  return self\n\n        \"\"\"\n\n        raise TypeError(f\"{self} is not subscriptable\")\nelse:\n    class _Self(typing._FinalTypingBase, _root=True):\n        \"\"\"Used to spell the type of \"self\" in classes.\n\n        Example::\n\n          from typing import Self\n\n          class ReturnsSelf:\n              def parse(self, data: bytes) -> Self:\n                  ...\n                  return self\n\n        \"\"\"\n\n        __slots__ = ()\n\n        def __instancecheck__(self, obj):\n            raise TypeError(f\"{self} cannot be used with isinstance().\")\n\n        def __subclasscheck__(self, cls):\n            raise TypeError(f\"{self} cannot be used with issubclass().\")\n\n    Self = _Self(_root=True)\n\n\nif hasattr(typing, 'Required'):\n    Required = typing.Required\n    NotRequired = typing.NotRequired\nelif sys.version_info[:2] >= (3, 9):\n    class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n    @_ExtensionsSpecialForm\n    def Required(self, parameters):\n        \"\"\"A special typing construct to mark a key of a total=False TypedDict\n        as required. For example:\n\n            class Movie(TypedDict, total=False):\n                title: Required[str]\n                year: int\n\n            m = Movie(\n                title='The Matrix',  # typechecker error if key is omitted\n                year=1999,\n            )\n\n        There is no runtime checking that a required key is actually provided\n        when instantiating a related TypedDict.\n        \"\"\"\n        item = typing._type_check(parameters, f'{self._name} accepts only single type')\n        return typing._GenericAlias(self, (item,))\n\n    @_ExtensionsSpecialForm\n    def NotRequired(self, parameters):\n        \"\"\"A special typing construct to mark a key of a TypedDict as\n        potentially missing. For example:\n\n            class Movie(TypedDict):\n                title: str\n                year: NotRequired[int]\n\n            m = Movie(\n                title='The Matrix',  # typechecker error if key is omitted\n                year=1999,\n            )\n        \"\"\"\n        item = typing._type_check(parameters, f'{self._name} accepts only single type')\n        return typing._GenericAlias(self, (item,))\n\nelif sys.version_info[:2] >= (3, 7):\n    class _RequiredForm(typing._SpecialForm, _root=True):\n        def __repr__(self):\n            return 'typing_extensions.' + self._name\n\n        def __getitem__(self, parameters):\n            item = typing._type_check(parameters,\n                                      '{} accepts only single type'.format(self._name))\n            return typing._GenericAlias(self, (item,))\n\n    Required = _RequiredForm(\n        'Required',\n        doc=\"\"\"A special typing construct to mark a key of a total=False TypedDict\n        as required. For example:\n\n            class Movie(TypedDict, total=False):\n                title: Required[str]\n                year: int\n\n            m = Movie(\n                title='The Matrix',  # typechecker error if key is omitted\n                year=1999,\n            )\n\n        There is no runtime checking that a required key is actually provided\n        when instantiating a related TypedDict.\n        \"\"\")\n    NotRequired = _RequiredForm(\n        'NotRequired',\n        doc=\"\"\"A special typing construct to mark a key of a TypedDict as\n        potentially missing. For example:\n\n            class Movie(TypedDict):\n                title: str\n                year: NotRequired[int]\n\n            m = Movie(\n                title='The Matrix',  # typechecker error if key is omitted\n                year=1999,\n            )\n        \"\"\")\nelse:\n    # NOTE: Modeled after _Final's implementation when _FinalTypingBase available\n    class _MaybeRequired(typing._FinalTypingBase, _root=True):\n        __slots__ = ('__type__',)\n\n        def __init__(self, tp=None, **kwds):\n            self.__type__ = tp\n\n        def __getitem__(self, item):\n            cls = type(self)\n            if self.__type__ is None:\n                return cls(typing._type_check(item,\n                           '{} accepts only single type.'.format(cls.__name__[1:])),\n                           _root=True)\n            raise TypeError('{} cannot be further subscripted'\n                            .format(cls.__name__[1:]))\n\n        def _eval_type(self, globalns, localns):\n            new_tp = typing._eval_type(self.__type__, globalns, localns)\n            if new_tp == self.__type__:\n                return self\n            return type(self)(new_tp, _root=True)\n\n        def __repr__(self):\n            r = super().__repr__()\n            if self.__type__ is not None:\n                r += '[{}]'.format(typing._type_repr(self.__type__))\n            return r\n\n        def __hash__(self):\n            return hash((type(self).__name__, self.__type__))\n\n        def __eq__(self, other):\n            if not isinstance(other, type(self)):\n                return NotImplemented\n            if self.__type__ is not None:\n                return self.__type__ == other.__type__\n            return self is other\n\n    class _Required(_MaybeRequired, _root=True):\n        \"\"\"A special typing construct to mark a key of a total=False TypedDict\n        as required. For example:\n\n            class Movie(TypedDict, total=False):\n                title: Required[str]\n                year: int\n\n            m = Movie(\n                title='The Matrix',  # typechecker error if key is omitted\n                year=1999,\n            )\n\n        There is no runtime checking that a required key is actually provided\n        when instantiating a related TypedDict.\n        \"\"\"\n\n    class _NotRequired(_MaybeRequired, _root=True):\n        \"\"\"A special typing construct to mark a key of a TypedDict as\n        potentially missing. For example:\n\n            class Movie(TypedDict):\n                title: str\n                year: NotRequired[int]\n\n            m = Movie(\n                title='The Matrix',  # typechecker error if key is omitted\n                year=1999,\n            )\n        \"\"\"\n\n    Required = _Required(_root=True)\n    NotRequired = _NotRequired(_root=True)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/_vendor/zipp.py",
    "content": "import io\nimport posixpath\nimport zipfile\nimport itertools\nimport contextlib\nimport sys\nimport pathlib\n\nif sys.version_info < (3, 7):\n    from collections import OrderedDict\nelse:\n    OrderedDict = dict\n\n\n__all__ = ['Path']\n\n\ndef _parents(path):\n    \"\"\"\n    Given a path with elements separated by\n    posixpath.sep, generate all parents of that path.\n\n    >>> list(_parents('b/d'))\n    ['b']\n    >>> list(_parents('/b/d/'))\n    ['/b']\n    >>> list(_parents('b/d/f/'))\n    ['b/d', 'b']\n    >>> list(_parents('b'))\n    []\n    >>> list(_parents(''))\n    []\n    \"\"\"\n    return itertools.islice(_ancestry(path), 1, None)\n\n\ndef _ancestry(path):\n    \"\"\"\n    Given a path with elements separated by\n    posixpath.sep, generate all elements of that path\n\n    >>> list(_ancestry('b/d'))\n    ['b/d', 'b']\n    >>> list(_ancestry('/b/d/'))\n    ['/b/d', '/b']\n    >>> list(_ancestry('b/d/f/'))\n    ['b/d/f', 'b/d', 'b']\n    >>> list(_ancestry('b'))\n    ['b']\n    >>> list(_ancestry(''))\n    []\n    \"\"\"\n    path = path.rstrip(posixpath.sep)\n    while path and path != posixpath.sep:\n        yield path\n        path, tail = posixpath.split(path)\n\n\n_dedupe = OrderedDict.fromkeys\n\"\"\"Deduplicate an iterable in original order\"\"\"\n\n\ndef _difference(minuend, subtrahend):\n    \"\"\"\n    Return items in minuend not in subtrahend, retaining order\n    with O(1) lookup.\n    \"\"\"\n    return itertools.filterfalse(set(subtrahend).__contains__, minuend)\n\n\nclass CompleteDirs(zipfile.ZipFile):\n    \"\"\"\n    A ZipFile subclass that ensures that implied directories\n    are always included in the namelist.\n    \"\"\"\n\n    @staticmethod\n    def _implied_dirs(names):\n        parents = itertools.chain.from_iterable(map(_parents, names))\n        as_dirs = (p + posixpath.sep for p in parents)\n        return _dedupe(_difference(as_dirs, names))\n\n    def namelist(self):\n        names = super(CompleteDirs, self).namelist()\n        return names + list(self._implied_dirs(names))\n\n    def _name_set(self):\n        return set(self.namelist())\n\n    def resolve_dir(self, name):\n        \"\"\"\n        If the name represents a directory, return that name\n        as a directory (with the trailing slash).\n        \"\"\"\n        names = self._name_set()\n        dirname = name + '/'\n        dir_match = name not in names and dirname in names\n        return dirname if dir_match else name\n\n    @classmethod\n    def make(cls, source):\n        \"\"\"\n        Given a source (filename or zipfile), return an\n        appropriate CompleteDirs subclass.\n        \"\"\"\n        if isinstance(source, CompleteDirs):\n            return source\n\n        if not isinstance(source, zipfile.ZipFile):\n            return cls(_pathlib_compat(source))\n\n        # Only allow for FastLookup when supplied zipfile is read-only\n        if 'r' not in source.mode:\n            cls = CompleteDirs\n\n        source.__class__ = cls\n        return source\n\n\nclass FastLookup(CompleteDirs):\n    \"\"\"\n    ZipFile subclass to ensure implicit\n    dirs exist and are resolved rapidly.\n    \"\"\"\n\n    def namelist(self):\n        with contextlib.suppress(AttributeError):\n            return self.__names\n        self.__names = super(FastLookup, self).namelist()\n        return self.__names\n\n    def _name_set(self):\n        with contextlib.suppress(AttributeError):\n            return self.__lookup\n        self.__lookup = super(FastLookup, self)._name_set()\n        return self.__lookup\n\n\ndef _pathlib_compat(path):\n    \"\"\"\n    For path-like objects, convert to a filename for compatibility\n    on Python 3.6.1 and earlier.\n    \"\"\"\n    try:\n        return path.__fspath__()\n    except AttributeError:\n        return str(path)\n\n\nclass Path:\n    \"\"\"\n    A pathlib-compatible interface for zip files.\n\n    Consider a zip file with this structure::\n\n        .\n        ├── a.txt\n        └── b\n            ├── c.txt\n            └── d\n                └── e.txt\n\n    >>> data = io.BytesIO()\n    >>> zf = zipfile.ZipFile(data, 'w')\n    >>> zf.writestr('a.txt', 'content of a')\n    >>> zf.writestr('b/c.txt', 'content of c')\n    >>> zf.writestr('b/d/e.txt', 'content of e')\n    >>> zf.filename = 'mem/abcde.zip'\n\n    Path accepts the zipfile object itself or a filename\n\n    >>> root = Path(zf)\n\n    From there, several path operations are available.\n\n    Directory iteration (including the zip file itself):\n\n    >>> a, b = root.iterdir()\n    >>> a\n    Path('mem/abcde.zip', 'a.txt')\n    >>> b\n    Path('mem/abcde.zip', 'b/')\n\n    name property:\n\n    >>> b.name\n    'b'\n\n    join with divide operator:\n\n    >>> c = b / 'c.txt'\n    >>> c\n    Path('mem/abcde.zip', 'b/c.txt')\n    >>> c.name\n    'c.txt'\n\n    Read text:\n\n    >>> c.read_text()\n    'content of c'\n\n    existence:\n\n    >>> c.exists()\n    True\n    >>> (b / 'missing.txt').exists()\n    False\n\n    Coercion to string:\n\n    >>> import os\n    >>> str(c).replace(os.sep, posixpath.sep)\n    'mem/abcde.zip/b/c.txt'\n\n    At the root, ``name``, ``filename``, and ``parent``\n    resolve to the zipfile. Note these attributes are not\n    valid and will raise a ``ValueError`` if the zipfile\n    has no filename.\n\n    >>> root.name\n    'abcde.zip'\n    >>> str(root.filename).replace(os.sep, posixpath.sep)\n    'mem/abcde.zip'\n    >>> str(root.parent)\n    'mem'\n    \"\"\"\n\n    __repr = \"{self.__class__.__name__}({self.root.filename!r}, {self.at!r})\"\n\n    def __init__(self, root, at=\"\"):\n        \"\"\"\n        Construct a Path from a ZipFile or filename.\n\n        Note: When the source is an existing ZipFile object,\n        its type (__class__) will be mutated to a\n        specialized type. If the caller wishes to retain the\n        original type, the caller should either create a\n        separate ZipFile object or pass a filename.\n        \"\"\"\n        self.root = FastLookup.make(root)\n        self.at = at\n\n    def open(self, mode='r', *args, pwd=None, **kwargs):\n        \"\"\"\n        Open this entry as text or binary following the semantics\n        of ``pathlib.Path.open()`` by passing arguments through\n        to io.TextIOWrapper().\n        \"\"\"\n        if self.is_dir():\n            raise IsADirectoryError(self)\n        zip_mode = mode[0]\n        if not self.exists() and zip_mode == 'r':\n            raise FileNotFoundError(self)\n        stream = self.root.open(self.at, zip_mode, pwd=pwd)\n        if 'b' in mode:\n            if args or kwargs:\n                raise ValueError(\"encoding args invalid for binary operation\")\n            return stream\n        return io.TextIOWrapper(stream, *args, **kwargs)\n\n    @property\n    def name(self):\n        return pathlib.Path(self.at).name or self.filename.name\n\n    @property\n    def suffix(self):\n        return pathlib.Path(self.at).suffix or self.filename.suffix\n\n    @property\n    def suffixes(self):\n        return pathlib.Path(self.at).suffixes or self.filename.suffixes\n\n    @property\n    def stem(self):\n        return pathlib.Path(self.at).stem or self.filename.stem\n\n    @property\n    def filename(self):\n        return pathlib.Path(self.root.filename).joinpath(self.at)\n\n    def read_text(self, *args, **kwargs):\n        with self.open('r', *args, **kwargs) as strm:\n            return strm.read()\n\n    def read_bytes(self):\n        with self.open('rb') as strm:\n            return strm.read()\n\n    def _is_child(self, path):\n        return posixpath.dirname(path.at.rstrip(\"/\")) == self.at.rstrip(\"/\")\n\n    def _next(self, at):\n        return self.__class__(self.root, at)\n\n    def is_dir(self):\n        return not self.at or self.at.endswith(\"/\")\n\n    def is_file(self):\n        return self.exists() and not self.is_dir()\n\n    def exists(self):\n        return self.at in self.root._name_set()\n\n    def iterdir(self):\n        if not self.is_dir():\n            raise ValueError(\"Can't listdir a file\")\n        subs = map(self._next, self.root.namelist())\n        return filter(self._is_child, subs)\n\n    def __str__(self):\n        return posixpath.join(self.root.filename, self.at)\n\n    def __repr__(self):\n        return self.__repr.format(self=self)\n\n    def joinpath(self, *other):\n        next = posixpath.join(self.at, *map(_pathlib_compat, other))\n        return self._next(self.root.resolve_dir(next))\n\n    __truediv__ = joinpath\n\n    @property\n    def parent(self):\n        if not self.at:\n            return self.filename.parent\n        parent_at = posixpath.dirname(self.at.rstrip('/'))\n        if parent_at:\n            parent_at += '/'\n        return self._next(parent_at)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/archive_util.py",
    "content": "\"\"\"Utilities for extracting common archive formats\"\"\"\n\nimport zipfile\nimport tarfile\nimport os\nimport shutil\nimport posixpath\nimport contextlib\nfrom distutils.errors import DistutilsError\n\nfrom ._path import ensure_directory\n\n__all__ = [\n    \"unpack_archive\", \"unpack_zipfile\", \"unpack_tarfile\", \"default_filter\",\n    \"UnrecognizedFormat\", \"extraction_drivers\", \"unpack_directory\",\n]\n\n\nclass UnrecognizedFormat(DistutilsError):\n    \"\"\"Couldn't recognize the archive type\"\"\"\n\n\ndef default_filter(src, dst):\n    \"\"\"The default progress/filter callback; returns True for all files\"\"\"\n    return dst\n\n\ndef unpack_archive(\n        filename, extract_dir, progress_filter=default_filter,\n        drivers=None):\n    \"\"\"Unpack `filename` to `extract_dir`, or raise ``UnrecognizedFormat``\n\n    `progress_filter` is a function taking two arguments: a source path\n    internal to the archive ('/'-separated), and a filesystem path where it\n    will be extracted.  The callback must return the desired extract path\n    (which may be the same as the one passed in), or else ``None`` to skip\n    that file or directory.  The callback can thus be used to report on the\n    progress of the extraction, as well as to filter the items extracted or\n    alter their extraction paths.\n\n    `drivers`, if supplied, must be a non-empty sequence of functions with the\n    same signature as this function (minus the `drivers` argument), that raise\n    ``UnrecognizedFormat`` if they do not support extracting the designated\n    archive type.  The `drivers` are tried in sequence until one is found that\n    does not raise an error, or until all are exhausted (in which case\n    ``UnrecognizedFormat`` is raised).  If you do not supply a sequence of\n    drivers, the module's ``extraction_drivers`` constant will be used, which\n    means that ``unpack_zipfile`` and ``unpack_tarfile`` will be tried, in that\n    order.\n    \"\"\"\n    for driver in drivers or extraction_drivers:\n        try:\n            driver(filename, extract_dir, progress_filter)\n        except UnrecognizedFormat:\n            continue\n        else:\n            return\n    else:\n        raise UnrecognizedFormat(\n            \"Not a recognized archive type: %s\" % filename\n        )\n\n\ndef unpack_directory(filename, extract_dir, progress_filter=default_filter):\n    \"\"\"\"Unpack\" a directory, using the same interface as for archives\n\n    Raises ``UnrecognizedFormat`` if `filename` is not a directory\n    \"\"\"\n    if not os.path.isdir(filename):\n        raise UnrecognizedFormat(\"%s is not a directory\" % filename)\n\n    paths = {\n        filename: ('', extract_dir),\n    }\n    for base, dirs, files in os.walk(filename):\n        src, dst = paths[base]\n        for d in dirs:\n            paths[os.path.join(base, d)] = src + d + '/', os.path.join(dst, d)\n        for f in files:\n            target = os.path.join(dst, f)\n            target = progress_filter(src + f, target)\n            if not target:\n                # skip non-files\n                continue\n            ensure_directory(target)\n            f = os.path.join(base, f)\n            shutil.copyfile(f, target)\n            shutil.copystat(f, target)\n\n\ndef unpack_zipfile(filename, extract_dir, progress_filter=default_filter):\n    \"\"\"Unpack zip `filename` to `extract_dir`\n\n    Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined\n    by ``zipfile.is_zipfile()``).  See ``unpack_archive()`` for an explanation\n    of the `progress_filter` argument.\n    \"\"\"\n\n    if not zipfile.is_zipfile(filename):\n        raise UnrecognizedFormat(\"%s is not a zip file\" % (filename,))\n\n    with zipfile.ZipFile(filename) as z:\n        _unpack_zipfile_obj(z, extract_dir, progress_filter)\n\n\ndef _unpack_zipfile_obj(zipfile_obj, extract_dir, progress_filter=default_filter):\n    \"\"\"Internal/private API used by other parts of setuptools.\n    Similar to ``unpack_zipfile``, but receives an already opened :obj:`zipfile.ZipFile`\n    object instead of a filename.\n    \"\"\"\n    for info in zipfile_obj.infolist():\n        name = info.filename\n\n        # don't extract absolute paths or ones with .. in them\n        if name.startswith('/') or '..' in name.split('/'):\n            continue\n\n        target = os.path.join(extract_dir, *name.split('/'))\n        target = progress_filter(name, target)\n        if not target:\n            continue\n        if name.endswith('/'):\n            # directory\n            ensure_directory(target)\n        else:\n            # file\n            ensure_directory(target)\n            data = zipfile_obj.read(info.filename)\n            with open(target, 'wb') as f:\n                f.write(data)\n        unix_attributes = info.external_attr >> 16\n        if unix_attributes:\n            os.chmod(target, unix_attributes)\n\n\ndef _resolve_tar_file_or_dir(tar_obj, tar_member_obj):\n    \"\"\"Resolve any links and extract link targets as normal files.\"\"\"\n    while tar_member_obj is not None and (\n            tar_member_obj.islnk() or tar_member_obj.issym()):\n        linkpath = tar_member_obj.linkname\n        if tar_member_obj.issym():\n            base = posixpath.dirname(tar_member_obj.name)\n            linkpath = posixpath.join(base, linkpath)\n            linkpath = posixpath.normpath(linkpath)\n        tar_member_obj = tar_obj._getmember(linkpath)\n\n    is_file_or_dir = (\n        tar_member_obj is not None and\n        (tar_member_obj.isfile() or tar_member_obj.isdir())\n    )\n    if is_file_or_dir:\n        return tar_member_obj\n\n    raise LookupError('Got unknown file type')\n\n\ndef _iter_open_tar(tar_obj, extract_dir, progress_filter):\n    \"\"\"Emit member-destination pairs from a tar archive.\"\"\"\n    # don't do any chowning!\n    tar_obj.chown = lambda *args: None\n\n    with contextlib.closing(tar_obj):\n        for member in tar_obj:\n            name = member.name\n            # don't extract absolute paths or ones with .. in them\n            if name.startswith('/') or '..' in name.split('/'):\n                continue\n\n            prelim_dst = os.path.join(extract_dir, *name.split('/'))\n\n            try:\n                member = _resolve_tar_file_or_dir(tar_obj, member)\n            except LookupError:\n                continue\n\n            final_dst = progress_filter(name, prelim_dst)\n            if not final_dst:\n                continue\n\n            if final_dst.endswith(os.sep):\n                final_dst = final_dst[:-1]\n\n            yield member, final_dst\n\n\ndef unpack_tarfile(filename, extract_dir, progress_filter=default_filter):\n    \"\"\"Unpack tar/tar.gz/tar.bz2 `filename` to `extract_dir`\n\n    Raises ``UnrecognizedFormat`` if `filename` is not a tarfile (as determined\n    by ``tarfile.open()``).  See ``unpack_archive()`` for an explanation\n    of the `progress_filter` argument.\n    \"\"\"\n    try:\n        tarobj = tarfile.open(filename)\n    except tarfile.TarError as e:\n        raise UnrecognizedFormat(\n            \"%s is not a compressed or uncompressed tar file\" % (filename,)\n        ) from e\n\n    for member, final_dst in _iter_open_tar(\n            tarobj, extract_dir, progress_filter,\n    ):\n        try:\n            # XXX Ugh\n            tarobj._extract_member(member, final_dst)\n        except tarfile.ExtractError:\n            # chown/chmod/mkfifo/mknode/makedev failed\n            pass\n\n    return True\n\n\nextraction_drivers = unpack_directory, unpack_zipfile, unpack_tarfile\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/build_meta.py",
    "content": "\"\"\"A PEP 517 interface to setuptools\n\nPreviously, when a user or a command line tool (let's call it a \"frontend\")\nneeded to make a request of setuptools to take a certain action, for\nexample, generating a list of installation requirements, the frontend would\nwould call \"setup.py egg_info\" or \"setup.py bdist_wheel\" on the command line.\n\nPEP 517 defines a different method of interfacing with setuptools. Rather\nthan calling \"setup.py\" directly, the frontend should:\n\n  1. Set the current directory to the directory with a setup.py file\n  2. Import this module into a safe python interpreter (one in which\n     setuptools can potentially set global variables or crash hard).\n  3. Call one of the functions defined in PEP 517.\n\nWhat each function does is defined in PEP 517. However, here is a \"casual\"\ndefinition of the functions (this definition should not be relied on for\nbug reports or API stability):\n\n  - `build_wheel`: build a wheel in the folder and return the basename\n  - `get_requires_for_build_wheel`: get the `setup_requires` to build\n  - `prepare_metadata_for_build_wheel`: get the `install_requires`\n  - `build_sdist`: build an sdist in the folder and return the basename\n  - `get_requires_for_build_sdist`: get the `setup_requires` to build\n\nAgain, this is not a formal definition! Just a \"taste\" of the module.\n\"\"\"\n\nimport io\nimport os\nimport shlex\nimport sys\nimport tokenize\nimport shutil\nimport contextlib\nimport tempfile\nimport warnings\nfrom pathlib import Path\nfrom typing import Dict, Iterator, List, Optional, Union\n\nimport setuptools\nimport distutils\nfrom . import errors\nfrom ._path import same_path\nfrom ._reqs import parse_strings\nfrom ._deprecation_warning import SetuptoolsDeprecationWarning\nfrom distutils.util import strtobool\n\n\n__all__ = ['get_requires_for_build_sdist',\n           'get_requires_for_build_wheel',\n           'prepare_metadata_for_build_wheel',\n           'build_wheel',\n           'build_sdist',\n           'get_requires_for_build_editable',\n           'prepare_metadata_for_build_editable',\n           'build_editable',\n           '__legacy__',\n           'SetupRequirementsError']\n\nSETUPTOOLS_ENABLE_FEATURES = os.getenv(\"SETUPTOOLS_ENABLE_FEATURES\", \"\").lower()\nLEGACY_EDITABLE = \"legacy-editable\" in SETUPTOOLS_ENABLE_FEATURES.replace(\"_\", \"-\")\n\n\nclass SetupRequirementsError(BaseException):\n    def __init__(self, specifiers):\n        self.specifiers = specifiers\n\n\nclass Distribution(setuptools.dist.Distribution):\n    def fetch_build_eggs(self, specifiers):\n        specifier_list = list(parse_strings(specifiers))\n\n        raise SetupRequirementsError(specifier_list)\n\n    @classmethod\n    @contextlib.contextmanager\n    def patch(cls):\n        \"\"\"\n        Replace\n        distutils.dist.Distribution with this class\n        for the duration of this context.\n        \"\"\"\n        orig = distutils.core.Distribution\n        distutils.core.Distribution = cls\n        try:\n            yield\n        finally:\n            distutils.core.Distribution = orig\n\n\n@contextlib.contextmanager\ndef no_install_setup_requires():\n    \"\"\"Temporarily disable installing setup_requires\n\n    Under PEP 517, the backend reports build dependencies to the frontend,\n    and the frontend is responsible for ensuring they're installed.\n    So setuptools (acting as a backend) should not try to install them.\n    \"\"\"\n    orig = setuptools._install_setup_requires\n    setuptools._install_setup_requires = lambda attrs: None\n    try:\n        yield\n    finally:\n        setuptools._install_setup_requires = orig\n\n\ndef _get_immediate_subdirectories(a_dir):\n    return [name for name in os.listdir(a_dir)\n            if os.path.isdir(os.path.join(a_dir, name))]\n\n\ndef _file_with_extension(directory, extension):\n    matching = (\n        f for f in os.listdir(directory)\n        if f.endswith(extension)\n    )\n    try:\n        file, = matching\n    except ValueError:\n        raise ValueError(\n            'No distribution was found. Ensure that `setup.py` '\n            'is not empty and that it calls `setup()`.')\n    return file\n\n\ndef _open_setup_script(setup_script):\n    if not os.path.exists(setup_script):\n        # Supply a default setup.py\n        return io.StringIO(u\"from setuptools import setup; setup()\")\n\n    return getattr(tokenize, 'open', open)(setup_script)\n\n\n@contextlib.contextmanager\ndef suppress_known_deprecation():\n    with warnings.catch_warnings():\n        warnings.filterwarnings('ignore', 'setup.py install is deprecated')\n        yield\n\n\n_ConfigSettings = Optional[Dict[str, Union[str, List[str], None]]]\n\"\"\"\nCurrently the user can run::\n\n    pip install -e . --config-settings key=value\n    python -m build -C--key=value -C key=value\n\n- pip will pass both key and value as strings and overwriting repeated keys\n  (pypa/pip#11059).\n- build will accumulate values associated with repeated keys in a list.\n  It will also accept keys with no associated value.\n  This means that an option passed by build can be ``str | list[str] | None``.\n- PEP 517 specifies that ``config_settings`` is an optional dict.\n\"\"\"\n\n\nclass _ConfigSettingsTranslator:\n    \"\"\"Translate ``config_settings`` into distutils-style command arguments.\n    Only a limited number of options is currently supported.\n    \"\"\"\n    # See pypa/setuptools#1928 pypa/setuptools#2491\n\n    def _get_config(self, key: str, config_settings: _ConfigSettings) -> List[str]:\n        \"\"\"\n        Get the value of a specific key in ``config_settings`` as a list of strings.\n\n        >>> fn = _ConfigSettingsTranslator()._get_config\n        >>> fn(\"--global-option\", None)\n        []\n        >>> fn(\"--global-option\", {})\n        []\n        >>> fn(\"--global-option\", {'--global-option': 'foo'})\n        ['foo']\n        >>> fn(\"--global-option\", {'--global-option': ['foo']})\n        ['foo']\n        >>> fn(\"--global-option\", {'--global-option': 'foo'})\n        ['foo']\n        >>> fn(\"--global-option\", {'--global-option': 'foo bar'})\n        ['foo', 'bar']\n        \"\"\"\n        cfg = config_settings or {}\n        opts = cfg.get(key) or []\n        return shlex.split(opts) if isinstance(opts, str) else opts\n\n    def _valid_global_options(self):\n        \"\"\"Global options accepted by setuptools (e.g. quiet or verbose).\"\"\"\n        options = (opt[:2] for opt in setuptools.dist.Distribution.global_options)\n        return {flag for long_and_short in options for flag in long_and_short if flag}\n\n    def _global_args(self, config_settings: _ConfigSettings) -> Iterator[str]:\n        \"\"\"\n        Let the user specify ``verbose`` or ``quiet`` + escape hatch via\n        ``--global-option``.\n        Note: ``-v``, ``-vv``, ``-vvv`` have similar effects in setuptools,\n        so we just have to cover the basic scenario ``-v``.\n\n        >>> fn = _ConfigSettingsTranslator()._global_args\n        >>> list(fn(None))\n        []\n        >>> list(fn({\"verbose\": \"False\"}))\n        ['-q']\n        >>> list(fn({\"verbose\": \"1\"}))\n        ['-v']\n        >>> list(fn({\"--verbose\": None}))\n        ['-v']\n        >>> list(fn({\"verbose\": \"true\", \"--global-option\": \"-q --no-user-cfg\"}))\n        ['-v', '-q', '--no-user-cfg']\n        >>> list(fn({\"--quiet\": None}))\n        ['-q']\n        \"\"\"\n        cfg = config_settings or {}\n        falsey = {\"false\", \"no\", \"0\", \"off\"}\n        if \"verbose\" in cfg or \"--verbose\" in cfg:\n            level = str(cfg.get(\"verbose\") or cfg.get(\"--verbose\") or \"1\")\n            yield (\"-q\" if level.lower() in falsey else \"-v\")\n        if \"quiet\" in cfg or \"--quiet\" in cfg:\n            level = str(cfg.get(\"quiet\") or cfg.get(\"--quiet\") or \"1\")\n            yield (\"-v\" if level.lower() in falsey else \"-q\")\n\n        valid = self._valid_global_options()\n        args = self._get_config(\"--global-option\", config_settings)\n        yield from (arg for arg in args if arg.strip(\"-\") in valid)\n\n    def __dist_info_args(self, config_settings: _ConfigSettings) -> Iterator[str]:\n        \"\"\"\n        The ``dist_info`` command accepts ``tag-date`` and ``tag-build``.\n\n        .. warning::\n           We cannot use this yet as it requires the ``sdist`` and ``bdist_wheel``\n           commands run in ``build_sdist`` and ``build_wheel`` to re-use the egg-info\n           directory created in ``prepare_metadata_for_build_wheel``.\n\n        >>> fn = _ConfigSettingsTranslator()._ConfigSettingsTranslator__dist_info_args\n        >>> list(fn(None))\n        []\n        >>> list(fn({\"tag-date\": \"False\"}))\n        ['--no-date']\n        >>> list(fn({\"tag-date\": None}))\n        ['--no-date']\n        >>> list(fn({\"tag-date\": \"true\", \"tag-build\": \".a\"}))\n        ['--tag-date', '--tag-build', '.a']\n        \"\"\"\n        cfg = config_settings or {}\n        if \"tag-date\" in cfg:\n            val = strtobool(str(cfg[\"tag-date\"] or \"false\"))\n            yield (\"--tag-date\" if val else \"--no-date\")\n        if \"tag-build\" in cfg:\n            yield from [\"--tag-build\", str(cfg[\"tag-build\"])]\n\n    def _editable_args(self, config_settings: _ConfigSettings) -> Iterator[str]:\n        \"\"\"\n        The ``editable_wheel`` command accepts ``editable-mode=strict``.\n\n        >>> fn = _ConfigSettingsTranslator()._editable_args\n        >>> list(fn(None))\n        []\n        >>> list(fn({\"editable-mode\": \"strict\"}))\n        ['--mode', 'strict']\n        \"\"\"\n        cfg = config_settings or {}\n        mode = cfg.get(\"editable-mode\") or cfg.get(\"editable_mode\")\n        if not mode:\n            return\n        yield from [\"--mode\", str(mode)]\n\n    def _arbitrary_args(self, config_settings: _ConfigSettings) -> Iterator[str]:\n        \"\"\"\n        Users may expect to pass arbitrary lists of arguments to a command\n        via \"--global-option\" (example provided in PEP 517 of a \"escape hatch\").\n\n        >>> fn = _ConfigSettingsTranslator()._arbitrary_args\n        >>> list(fn(None))\n        []\n        >>> list(fn({}))\n        []\n        >>> list(fn({'--build-option': 'foo'}))\n        ['foo']\n        >>> list(fn({'--build-option': ['foo']}))\n        ['foo']\n        >>> list(fn({'--build-option': 'foo'}))\n        ['foo']\n        >>> list(fn({'--build-option': 'foo bar'}))\n        ['foo', 'bar']\n        >>> warnings.simplefilter('error', SetuptoolsDeprecationWarning)\n        >>> list(fn({'--global-option': 'foo'}))  # doctest: +IGNORE_EXCEPTION_DETAIL\n        Traceback (most recent call last):\n        SetuptoolsDeprecationWarning: ...arguments given via `--global-option`...\n        \"\"\"\n        args = self._get_config(\"--global-option\", config_settings)\n        global_opts = self._valid_global_options()\n        bad_args = []\n\n        for arg in args:\n            if arg.strip(\"-\") not in global_opts:\n                bad_args.append(arg)\n                yield arg\n\n        yield from self._get_config(\"--build-option\", config_settings)\n\n        if bad_args:\n            msg = f\"\"\"\n            The arguments {bad_args!r} were given via `--global-option`.\n            Please use `--build-option` instead,\n            `--global-option` is reserved to flags like `--verbose` or `--quiet`.\n            \"\"\"\n            warnings.warn(msg, SetuptoolsDeprecationWarning)\n\n\nclass _BuildMetaBackend(_ConfigSettingsTranslator):\n    def _get_build_requires(self, config_settings, requirements):\n        sys.argv = [\n            *sys.argv[:1],\n            *self._global_args(config_settings),\n            \"egg_info\",\n            *self._arbitrary_args(config_settings),\n        ]\n        try:\n            with Distribution.patch():\n                self.run_setup()\n        except SetupRequirementsError as e:\n            requirements += e.specifiers\n\n        return requirements\n\n    def run_setup(self, setup_script='setup.py'):\n        # Note that we can reuse our build directory between calls\n        # Correctness comes first, then optimization later\n        __file__ = setup_script\n        __name__ = '__main__'\n\n        with _open_setup_script(__file__) as f:\n            code = f.read().replace(r'\\r\\n', r'\\n')\n\n        exec(code, locals())\n\n    def get_requires_for_build_wheel(self, config_settings=None):\n        return self._get_build_requires(config_settings, requirements=['wheel'])\n\n    def get_requires_for_build_sdist(self, config_settings=None):\n        return self._get_build_requires(config_settings, requirements=[])\n\n    def _bubble_up_info_directory(self, metadata_directory: str, suffix: str) -> str:\n        \"\"\"\n        PEP 517 requires that the .dist-info directory be placed in the\n        metadata_directory. To comply, we MUST copy the directory to the root.\n\n        Returns the basename of the info directory, e.g. `proj-0.0.0.dist-info`.\n        \"\"\"\n        info_dir = self._find_info_directory(metadata_directory, suffix)\n        if not same_path(info_dir.parent, metadata_directory):\n            shutil.move(str(info_dir), metadata_directory)\n            # PEP 517 allow other files and dirs to exist in metadata_directory\n        return info_dir.name\n\n    def _find_info_directory(self, metadata_directory: str, suffix: str) -> Path:\n        for parent, dirs, _ in os.walk(metadata_directory):\n            candidates = [f for f in dirs if f.endswith(suffix)]\n\n            if len(candidates) != 0 or len(dirs) != 1:\n                assert len(candidates) == 1, f\"Multiple {suffix} directories found\"\n                return Path(parent, candidates[0])\n\n        msg = f\"No {suffix} directory found in {metadata_directory}\"\n        raise errors.InternalError(msg)\n\n    def prepare_metadata_for_build_wheel(self, metadata_directory,\n                                         config_settings=None):\n        sys.argv = [\n            *sys.argv[:1],\n            *self._global_args(config_settings),\n            \"dist_info\",\n            \"--output-dir\", metadata_directory,\n            \"--keep-egg-info\",\n        ]\n        with no_install_setup_requires():\n            self.run_setup()\n\n        self._bubble_up_info_directory(metadata_directory, \".egg-info\")\n        return self._bubble_up_info_directory(metadata_directory, \".dist-info\")\n\n    def _build_with_temp_dir(self, setup_command, result_extension,\n                             result_directory, config_settings):\n        result_directory = os.path.abspath(result_directory)\n\n        # Build in a temporary directory, then copy to the target.\n        os.makedirs(result_directory, exist_ok=True)\n        with tempfile.TemporaryDirectory(dir=result_directory) as tmp_dist_dir:\n            sys.argv = [\n                *sys.argv[:1],\n                *self._global_args(config_settings),\n                *setup_command,\n                \"--dist-dir\", tmp_dist_dir,\n                *self._arbitrary_args(config_settings),\n            ]\n            with no_install_setup_requires():\n                self.run_setup()\n\n            result_basename = _file_with_extension(\n                tmp_dist_dir, result_extension)\n            result_path = os.path.join(result_directory, result_basename)\n            if os.path.exists(result_path):\n                # os.rename will fail overwriting on non-Unix.\n                os.remove(result_path)\n            os.rename(os.path.join(tmp_dist_dir, result_basename), result_path)\n\n        return result_basename\n\n    def build_wheel(self, wheel_directory, config_settings=None,\n                    metadata_directory=None):\n        with suppress_known_deprecation():\n            return self._build_with_temp_dir(['bdist_wheel'], '.whl',\n                                             wheel_directory, config_settings)\n\n    def build_sdist(self, sdist_directory, config_settings=None):\n        return self._build_with_temp_dir(['sdist', '--formats', 'gztar'],\n                                         '.tar.gz', sdist_directory,\n                                         config_settings)\n\n    def _get_dist_info_dir(self, metadata_directory: Optional[str]) -> Optional[str]:\n        if not metadata_directory:\n            return None\n        dist_info_candidates = list(Path(metadata_directory).glob(\"*.dist-info\"))\n        assert len(dist_info_candidates) <= 1\n        return str(dist_info_candidates[0]) if dist_info_candidates else None\n\n    if not LEGACY_EDITABLE:\n\n        # PEP660 hooks:\n        # build_editable\n        # get_requires_for_build_editable\n        # prepare_metadata_for_build_editable\n        def build_editable(\n            self, wheel_directory, config_settings=None, metadata_directory=None\n        ):\n            # XXX can or should we hide our editable_wheel command normally?\n            info_dir = self._get_dist_info_dir(metadata_directory)\n            opts = [\"--dist-info-dir\", info_dir] if info_dir else []\n            cmd = [\"editable_wheel\", *opts, *self._editable_args(config_settings)]\n            with suppress_known_deprecation():\n                return self._build_with_temp_dir(\n                    cmd, \".whl\", wheel_directory, config_settings\n                )\n\n        def get_requires_for_build_editable(self, config_settings=None):\n            return self.get_requires_for_build_wheel(config_settings)\n\n        def prepare_metadata_for_build_editable(self, metadata_directory,\n                                                config_settings=None):\n            return self.prepare_metadata_for_build_wheel(\n                metadata_directory, config_settings\n            )\n\n\nclass _BuildMetaLegacyBackend(_BuildMetaBackend):\n    \"\"\"Compatibility backend for setuptools\n\n    This is a version of setuptools.build_meta that endeavors\n    to maintain backwards\n    compatibility with pre-PEP 517 modes of invocation. It\n    exists as a temporary\n    bridge between the old packaging mechanism and the new\n    packaging mechanism,\n    and will eventually be removed.\n    \"\"\"\n    def run_setup(self, setup_script='setup.py'):\n        # In order to maintain compatibility with scripts assuming that\n        # the setup.py script is in a directory on the PYTHONPATH, inject\n        # '' into sys.path. (pypa/setuptools#1642)\n        sys_path = list(sys.path)           # Save the original path\n\n        script_dir = os.path.dirname(os.path.abspath(setup_script))\n        if script_dir not in sys.path:\n            sys.path.insert(0, script_dir)\n\n        # Some setup.py scripts (e.g. in pygame and numpy) use sys.argv[0] to\n        # get the directory of the source code. They expect it to refer to the\n        # setup.py script.\n        sys_argv_0 = sys.argv[0]\n        sys.argv[0] = setup_script\n\n        try:\n            super(_BuildMetaLegacyBackend,\n                  self).run_setup(setup_script=setup_script)\n        finally:\n            # While PEP 517 frontends should be calling each hook in a fresh\n            # subprocess according to the standard (and thus it should not be\n            # strictly necessary to restore the old sys.path), we'll restore\n            # the original path so that the path manipulation does not persist\n            # within the hook after run_setup is called.\n            sys.path[:] = sys_path\n            sys.argv[0] = sys_argv_0\n\n\n# The primary backend\n_BACKEND = _BuildMetaBackend()\n\nget_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel\nget_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist\nprepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel\nbuild_wheel = _BACKEND.build_wheel\nbuild_sdist = _BACKEND.build_sdist\n\nif not LEGACY_EDITABLE:\n    get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable\n    prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable\n    build_editable = _BACKEND.build_editable\n\n\n# The legacy backend\n__legacy__ = _BuildMetaLegacyBackend()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/__init__.py",
    "content": "from distutils.command.bdist import bdist\nimport sys\n\nif 'egg' not in bdist.format_commands:\n    try:\n        bdist.format_commands['egg'] = ('bdist_egg', \"Python .egg file\")\n    except TypeError:\n        # For backward compatibility with older distutils (stdlib)\n        bdist.format_command['egg'] = ('bdist_egg', \"Python .egg file\")\n        bdist.format_commands.append('egg')\n\ndel bdist, sys\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/alias.py",
    "content": "from distutils.errors import DistutilsOptionError\n\nfrom setuptools.command.setopt import edit_config, option_base, config_file\n\n\ndef shquote(arg):\n    \"\"\"Quote an argument for later parsing by shlex.split()\"\"\"\n    for c in '\"', \"'\", \"\\\\\", \"#\":\n        if c in arg:\n            return repr(arg)\n    if arg.split() != [arg]:\n        return repr(arg)\n    return arg\n\n\nclass alias(option_base):\n    \"\"\"Define a shortcut that invokes one or more commands\"\"\"\n\n    description = \"define a shortcut to invoke one or more commands\"\n    command_consumes_arguments = True\n\n    user_options = [\n        ('remove', 'r', 'remove (unset) the alias'),\n    ] + option_base.user_options\n\n    boolean_options = option_base.boolean_options + ['remove']\n\n    def initialize_options(self):\n        option_base.initialize_options(self)\n        self.args = None\n        self.remove = None\n\n    def finalize_options(self):\n        option_base.finalize_options(self)\n        if self.remove and len(self.args) != 1:\n            raise DistutilsOptionError(\n                \"Must specify exactly one argument (the alias name) when \"\n                \"using --remove\"\n            )\n\n    def run(self):\n        aliases = self.distribution.get_option_dict('aliases')\n\n        if not self.args:\n            print(\"Command Aliases\")\n            print(\"---------------\")\n            for alias in aliases:\n                print(\"setup.py alias\", format_alias(alias, aliases))\n            return\n\n        elif len(self.args) == 1:\n            alias, = self.args\n            if self.remove:\n                command = None\n            elif alias in aliases:\n                print(\"setup.py alias\", format_alias(alias, aliases))\n                return\n            else:\n                print(\"No alias definition found for %r\" % alias)\n                return\n        else:\n            alias = self.args[0]\n            command = ' '.join(map(shquote, self.args[1:]))\n\n        edit_config(self.filename, {'aliases': {alias: command}}, self.dry_run)\n\n\ndef format_alias(name, aliases):\n    source, command = aliases[name]\n    if source == config_file('global'):\n        source = '--global-config '\n    elif source == config_file('user'):\n        source = '--user-config '\n    elif source == config_file('local'):\n        source = ''\n    else:\n        source = '--filename=%r' % source\n    return source + name + ' ' + command\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/bdist_egg.py",
    "content": "\"\"\"setuptools.command.bdist_egg\n\nBuild .egg distributions\"\"\"\n\nfrom distutils.dir_util import remove_tree, mkpath\nfrom distutils import log\nfrom types import CodeType\nimport sys\nimport os\nimport re\nimport textwrap\nimport marshal\n\nfrom pkg_resources import get_build_platform, Distribution\nfrom setuptools.extension import Library\nfrom setuptools import Command\nfrom .._path import ensure_directory\n\nfrom sysconfig import get_path, get_python_version\n\n\ndef _get_purelib():\n    return get_path(\"purelib\")\n\n\ndef strip_module(filename):\n    if '.' in filename:\n        filename = os.path.splitext(filename)[0]\n    if filename.endswith('module'):\n        filename = filename[:-6]\n    return filename\n\n\ndef sorted_walk(dir):\n    \"\"\"Do os.walk in a reproducible way,\n    independent of indeterministic filesystem readdir order\n    \"\"\"\n    for base, dirs, files in os.walk(dir):\n        dirs.sort()\n        files.sort()\n        yield base, dirs, files\n\n\ndef write_stub(resource, pyfile):\n    _stub_template = textwrap.dedent(\"\"\"\n        def __bootstrap__():\n            global __bootstrap__, __loader__, __file__\n            import sys, pkg_resources, importlib.util\n            __file__ = pkg_resources.resource_filename(__name__, %r)\n            __loader__ = None; del __bootstrap__, __loader__\n            spec = importlib.util.spec_from_file_location(__name__,__file__)\n            mod = importlib.util.module_from_spec(spec)\n            spec.loader.exec_module(mod)\n        __bootstrap__()\n        \"\"\").lstrip()\n    with open(pyfile, 'w') as f:\n        f.write(_stub_template % resource)\n\n\nclass bdist_egg(Command):\n    description = \"create an \\\"egg\\\" distribution\"\n\n    user_options = [\n        ('bdist-dir=', 'b',\n         \"temporary directory for creating the distribution\"),\n        ('plat-name=', 'p', \"platform name to embed in generated filenames \"\n                            \"(default: %s)\" % get_build_platform()),\n        ('exclude-source-files', None,\n         \"remove all .py files from the generated egg\"),\n        ('keep-temp', 'k',\n         \"keep the pseudo-installation tree around after \" +\n         \"creating the distribution archive\"),\n        ('dist-dir=', 'd',\n         \"directory to put final built distributions in\"),\n        ('skip-build', None,\n         \"skip rebuilding everything (for testing/debugging)\"),\n    ]\n\n    boolean_options = [\n        'keep-temp', 'skip-build', 'exclude-source-files'\n    ]\n\n    def initialize_options(self):\n        self.bdist_dir = None\n        self.plat_name = None\n        self.keep_temp = 0\n        self.dist_dir = None\n        self.skip_build = 0\n        self.egg_output = None\n        self.exclude_source_files = None\n\n    def finalize_options(self):\n        ei_cmd = self.ei_cmd = self.get_finalized_command(\"egg_info\")\n        self.egg_info = ei_cmd.egg_info\n\n        if self.bdist_dir is None:\n            bdist_base = self.get_finalized_command('bdist').bdist_base\n            self.bdist_dir = os.path.join(bdist_base, 'egg')\n\n        if self.plat_name is None:\n            self.plat_name = get_build_platform()\n\n        self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))\n\n        if self.egg_output is None:\n\n            # Compute filename of the output egg\n            basename = Distribution(\n                None, None, ei_cmd.egg_name, ei_cmd.egg_version,\n                get_python_version(),\n                self.distribution.has_ext_modules() and self.plat_name\n            ).egg_name()\n\n            self.egg_output = os.path.join(self.dist_dir, basename + '.egg')\n\n    def do_install_data(self):\n        # Hack for packages that install data to install's --install-lib\n        self.get_finalized_command('install').install_lib = self.bdist_dir\n\n        site_packages = os.path.normcase(os.path.realpath(_get_purelib()))\n        old, self.distribution.data_files = self.distribution.data_files, []\n\n        for item in old:\n            if isinstance(item, tuple) and len(item) == 2:\n                if os.path.isabs(item[0]):\n                    realpath = os.path.realpath(item[0])\n                    normalized = os.path.normcase(realpath)\n                    if normalized == site_packages or normalized.startswith(\n                        site_packages + os.sep\n                    ):\n                        item = realpath[len(site_packages) + 1:], item[1]\n                        # XXX else: raise ???\n            self.distribution.data_files.append(item)\n\n        try:\n            log.info(\"installing package data to %s\", self.bdist_dir)\n            self.call_command('install_data', force=0, root=None)\n        finally:\n            self.distribution.data_files = old\n\n    def get_outputs(self):\n        return [self.egg_output]\n\n    def call_command(self, cmdname, **kw):\n        \"\"\"Invoke reinitialized command `cmdname` with keyword args\"\"\"\n        for dirname in INSTALL_DIRECTORY_ATTRS:\n            kw.setdefault(dirname, self.bdist_dir)\n        kw.setdefault('skip_build', self.skip_build)\n        kw.setdefault('dry_run', self.dry_run)\n        cmd = self.reinitialize_command(cmdname, **kw)\n        self.run_command(cmdname)\n        return cmd\n\n    def run(self):  # noqa: C901  # is too complex (14)  # FIXME\n        # Generate metadata first\n        self.run_command(\"egg_info\")\n        # We run install_lib before install_data, because some data hacks\n        # pull their data path from the install_lib command.\n        log.info(\"installing library code to %s\", self.bdist_dir)\n        instcmd = self.get_finalized_command('install')\n        old_root = instcmd.root\n        instcmd.root = None\n        if self.distribution.has_c_libraries() and not self.skip_build:\n            self.run_command('build_clib')\n        cmd = self.call_command('install_lib', warn_dir=0)\n        instcmd.root = old_root\n\n        all_outputs, ext_outputs = self.get_ext_outputs()\n        self.stubs = []\n        to_compile = []\n        for (p, ext_name) in enumerate(ext_outputs):\n            filename, ext = os.path.splitext(ext_name)\n            pyfile = os.path.join(self.bdist_dir, strip_module(filename) +\n                                  '.py')\n            self.stubs.append(pyfile)\n            log.info(\"creating stub loader for %s\", ext_name)\n            if not self.dry_run:\n                write_stub(os.path.basename(ext_name), pyfile)\n            to_compile.append(pyfile)\n            ext_outputs[p] = ext_name.replace(os.sep, '/')\n\n        if to_compile:\n            cmd.byte_compile(to_compile)\n        if self.distribution.data_files:\n            self.do_install_data()\n\n        # Make the EGG-INFO directory\n        archive_root = self.bdist_dir\n        egg_info = os.path.join(archive_root, 'EGG-INFO')\n        self.mkpath(egg_info)\n        if self.distribution.scripts:\n            script_dir = os.path.join(egg_info, 'scripts')\n            log.info(\"installing scripts to %s\", script_dir)\n            self.call_command('install_scripts', install_dir=script_dir,\n                              no_ep=1)\n\n        self.copy_metadata_to(egg_info)\n        native_libs = os.path.join(egg_info, \"native_libs.txt\")\n        if all_outputs:\n            log.info(\"writing %s\", native_libs)\n            if not self.dry_run:\n                ensure_directory(native_libs)\n                libs_file = open(native_libs, 'wt')\n                libs_file.write('\\n'.join(all_outputs))\n                libs_file.write('\\n')\n                libs_file.close()\n        elif os.path.isfile(native_libs):\n            log.info(\"removing %s\", native_libs)\n            if not self.dry_run:\n                os.unlink(native_libs)\n\n        write_safety_flag(\n            os.path.join(archive_root, 'EGG-INFO'), self.zip_safe()\n        )\n\n        if os.path.exists(os.path.join(self.egg_info, 'depends.txt')):\n            log.warn(\n                \"WARNING: 'depends.txt' will not be used by setuptools 0.6!\\n\"\n                \"Use the install_requires/extras_require setup() args instead.\"\n            )\n\n        if self.exclude_source_files:\n            self.zap_pyfiles()\n\n        # Make the archive\n        make_zipfile(self.egg_output, archive_root, verbose=self.verbose,\n                     dry_run=self.dry_run, mode=self.gen_header())\n        if not self.keep_temp:\n            remove_tree(self.bdist_dir, dry_run=self.dry_run)\n\n        # Add to 'Distribution.dist_files' so that the \"upload\" command works\n        getattr(self.distribution, 'dist_files', []).append(\n            ('bdist_egg', get_python_version(), self.egg_output))\n\n    def zap_pyfiles(self):\n        log.info(\"Removing .py files from temporary directory\")\n        for base, dirs, files in walk_egg(self.bdist_dir):\n            for name in files:\n                path = os.path.join(base, name)\n\n                if name.endswith('.py'):\n                    log.debug(\"Deleting %s\", path)\n                    os.unlink(path)\n\n                if base.endswith('__pycache__'):\n                    path_old = path\n\n                    pattern = r'(?P<name>.+)\\.(?P<magic>[^.]+)\\.pyc'\n                    m = re.match(pattern, name)\n                    path_new = os.path.join(\n                        base, os.pardir, m.group('name') + '.pyc')\n                    log.info(\n                        \"Renaming file from [%s] to [%s]\"\n                        % (path_old, path_new))\n                    try:\n                        os.remove(path_new)\n                    except OSError:\n                        pass\n                    os.rename(path_old, path_new)\n\n    def zip_safe(self):\n        safe = getattr(self.distribution, 'zip_safe', None)\n        if safe is not None:\n            return safe\n        log.warn(\"zip_safe flag not set; analyzing archive contents...\")\n        return analyze_egg(self.bdist_dir, self.stubs)\n\n    def gen_header(self):\n        return 'w'\n\n    def copy_metadata_to(self, target_dir):\n        \"Copy metadata (egg info) to the target_dir\"\n        # normalize the path (so that a forward-slash in egg_info will\n        # match using startswith below)\n        norm_egg_info = os.path.normpath(self.egg_info)\n        prefix = os.path.join(norm_egg_info, '')\n        for path in self.ei_cmd.filelist.files:\n            if path.startswith(prefix):\n                target = os.path.join(target_dir, path[len(prefix):])\n                ensure_directory(target)\n                self.copy_file(path, target)\n\n    def get_ext_outputs(self):\n        \"\"\"Get a list of relative paths to C extensions in the output distro\"\"\"\n\n        all_outputs = []\n        ext_outputs = []\n\n        paths = {self.bdist_dir: ''}\n        for base, dirs, files in sorted_walk(self.bdist_dir):\n            for filename in files:\n                if os.path.splitext(filename)[1].lower() in NATIVE_EXTENSIONS:\n                    all_outputs.append(paths[base] + filename)\n            for filename in dirs:\n                paths[os.path.join(base, filename)] = (paths[base] +\n                                                       filename + '/')\n\n        if self.distribution.has_ext_modules():\n            build_cmd = self.get_finalized_command('build_ext')\n            for ext in build_cmd.extensions:\n                if isinstance(ext, Library):\n                    continue\n                fullname = build_cmd.get_ext_fullname(ext.name)\n                filename = build_cmd.get_ext_filename(fullname)\n                if not os.path.basename(filename).startswith('dl-'):\n                    if os.path.exists(os.path.join(self.bdist_dir, filename)):\n                        ext_outputs.append(filename)\n\n        return all_outputs, ext_outputs\n\n\nNATIVE_EXTENSIONS = dict.fromkeys('.dll .so .dylib .pyd'.split())\n\n\ndef walk_egg(egg_dir):\n    \"\"\"Walk an unpacked egg's contents, skipping the metadata directory\"\"\"\n    walker = sorted_walk(egg_dir)\n    base, dirs, files = next(walker)\n    if 'EGG-INFO' in dirs:\n        dirs.remove('EGG-INFO')\n    yield base, dirs, files\n    for bdf in walker:\n        yield bdf\n\n\ndef analyze_egg(egg_dir, stubs):\n    # check for existing flag in EGG-INFO\n    for flag, fn in safety_flags.items():\n        if os.path.exists(os.path.join(egg_dir, 'EGG-INFO', fn)):\n            return flag\n    if not can_scan():\n        return False\n    safe = True\n    for base, dirs, files in walk_egg(egg_dir):\n        for name in files:\n            if name.endswith('.py') or name.endswith('.pyw'):\n                continue\n            elif name.endswith('.pyc') or name.endswith('.pyo'):\n                # always scan, even if we already know we're not safe\n                safe = scan_module(egg_dir, base, name, stubs) and safe\n    return safe\n\n\ndef write_safety_flag(egg_dir, safe):\n    # Write or remove zip safety flag file(s)\n    for flag, fn in safety_flags.items():\n        fn = os.path.join(egg_dir, fn)\n        if os.path.exists(fn):\n            if safe is None or bool(safe) != flag:\n                os.unlink(fn)\n        elif safe is not None and bool(safe) == flag:\n            f = open(fn, 'wt')\n            f.write('\\n')\n            f.close()\n\n\nsafety_flags = {\n    True: 'zip-safe',\n    False: 'not-zip-safe',\n}\n\n\ndef scan_module(egg_dir, base, name, stubs):\n    \"\"\"Check whether module possibly uses unsafe-for-zipfile stuff\"\"\"\n\n    filename = os.path.join(base, name)\n    if filename[:-1] in stubs:\n        return True  # Extension module\n    pkg = base[len(egg_dir) + 1:].replace(os.sep, '.')\n    module = pkg + (pkg and '.' or '') + os.path.splitext(name)[0]\n    if sys.version_info < (3, 7):\n        skip = 12  # skip magic & date & file size\n    else:\n        skip = 16  # skip magic & reserved? & date & file size\n    f = open(filename, 'rb')\n    f.read(skip)\n    code = marshal.load(f)\n    f.close()\n    safe = True\n    symbols = dict.fromkeys(iter_symbols(code))\n    for bad in ['__file__', '__path__']:\n        if bad in symbols:\n            log.warn(\"%s: module references %s\", module, bad)\n            safe = False\n    if 'inspect' in symbols:\n        for bad in [\n            'getsource', 'getabsfile', 'getsourcefile', 'getfile'\n            'getsourcelines', 'findsource', 'getcomments', 'getframeinfo',\n            'getinnerframes', 'getouterframes', 'stack', 'trace'\n        ]:\n            if bad in symbols:\n                log.warn(\"%s: module MAY be using inspect.%s\", module, bad)\n                safe = False\n    return safe\n\n\ndef iter_symbols(code):\n    \"\"\"Yield names and strings used by `code` and its nested code objects\"\"\"\n    for name in code.co_names:\n        yield name\n    for const in code.co_consts:\n        if isinstance(const, str):\n            yield const\n        elif isinstance(const, CodeType):\n            for name in iter_symbols(const):\n                yield name\n\n\ndef can_scan():\n    if not sys.platform.startswith('java') and sys.platform != 'cli':\n        # CPython, PyPy, etc.\n        return True\n    log.warn(\"Unable to analyze compiled code on this platform.\")\n    log.warn(\"Please ask the author to include a 'zip_safe'\"\n             \" setting (either True or False) in the package's setup.py\")\n\n\n# Attribute names of options for commands that might need to be convinced to\n# install to the egg build directory\n\nINSTALL_DIRECTORY_ATTRS = [\n    'install_lib', 'install_dir', 'install_data', 'install_base'\n]\n\n\ndef make_zipfile(zip_filename, base_dir, verbose=0, dry_run=0, compress=True,\n                 mode='w'):\n    \"\"\"Create a zip file from all the files under 'base_dir'.  The output\n    zip file will be named 'base_dir' + \".zip\".  Uses either the \"zipfile\"\n    Python module (if available) or the InfoZIP \"zip\" utility (if installed\n    and found on the default search path).  If neither tool is available,\n    raises DistutilsExecError.  Returns the name of the output zip file.\n    \"\"\"\n    import zipfile\n\n    mkpath(os.path.dirname(zip_filename), dry_run=dry_run)\n    log.info(\"creating '%s' and adding '%s' to it\", zip_filename, base_dir)\n\n    def visit(z, dirname, names):\n        for name in names:\n            path = os.path.normpath(os.path.join(dirname, name))\n            if os.path.isfile(path):\n                p = path[len(base_dir) + 1:]\n                if not dry_run:\n                    z.write(path, p)\n                log.debug(\"adding '%s'\", p)\n\n    compression = zipfile.ZIP_DEFLATED if compress else zipfile.ZIP_STORED\n    if not dry_run:\n        z = zipfile.ZipFile(zip_filename, mode, compression=compression)\n        for dirname, dirs, files in sorted_walk(base_dir):\n            visit(z, dirname, files)\n        z.close()\n    else:\n        for dirname, dirs, files in sorted_walk(base_dir):\n            visit(None, dirname, files)\n    return zip_filename\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/bdist_rpm.py",
    "content": "import distutils.command.bdist_rpm as orig\nimport warnings\n\nfrom setuptools import SetuptoolsDeprecationWarning\n\n\nclass bdist_rpm(orig.bdist_rpm):\n    \"\"\"\n    Override the default bdist_rpm behavior to do the following:\n\n    1. Run egg_info to ensure the name and version are properly calculated.\n    2. Always run 'install' using --single-version-externally-managed to\n       disable eggs in RPM distributions.\n    \"\"\"\n\n    def run(self):\n        warnings.warn(\n            \"bdist_rpm is deprecated and will be removed in a future \"\n            \"version. Use bdist_wheel (wheel packages) instead.\",\n            SetuptoolsDeprecationWarning,\n        )\n\n        # ensure distro name is up-to-date\n        self.run_command('egg_info')\n\n        orig.bdist_rpm.run(self)\n\n    def _make_spec_file(self):\n        spec = orig.bdist_rpm._make_spec_file(self)\n        spec = [\n            line.replace(\n                \"setup.py install \",\n                \"setup.py install --single-version-externally-managed \"\n            ).replace(\n                \"%setup\",\n                \"%setup -n %{name}-%{unmangled_version}\"\n            )\n            for line in spec\n        ]\n        return spec\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/build.py",
    "content": "import sys\nimport warnings\nfrom typing import TYPE_CHECKING, List, Dict\nfrom distutils.command.build import build as _build\n\nfrom setuptools import SetuptoolsDeprecationWarning\n\nif sys.version_info >= (3, 8):\n    from typing import Protocol\nelif TYPE_CHECKING:\n    from typing_extensions import Protocol\nelse:\n    from abc import ABC as Protocol\n\n\n_ORIGINAL_SUBCOMMANDS = {\"build_py\", \"build_clib\", \"build_ext\", \"build_scripts\"}\n\n\nclass build(_build):\n    # copy to avoid sharing the object with parent class\n    sub_commands = _build.sub_commands[:]\n\n    def get_sub_commands(self):\n        subcommands = {cmd[0] for cmd in _build.sub_commands}\n        if subcommands - _ORIGINAL_SUBCOMMANDS:\n            msg = \"\"\"\n            It seems that you are using `distutils.command.build` to add\n            new subcommands. Using `distutils` directly is considered deprecated,\n            please use `setuptools.command.build`.\n            \"\"\"\n            warnings.warn(msg, SetuptoolsDeprecationWarning)\n            self.sub_commands = _build.sub_commands\n        return super().get_sub_commands()\n\n\nclass SubCommand(Protocol):\n    \"\"\"In order to support editable installations (see :pep:`660`) all\n    build subcommands **SHOULD** implement this protocol. They also **MUST** inherit\n    from ``setuptools.Command``.\n\n    When creating an :pep:`editable wheel <660>`, ``setuptools`` will try to evaluate\n    custom ``build`` subcommands using the following procedure:\n\n    1. ``setuptools`` will set the ``editable_mode`` attribute to ``True``\n    2. ``setuptools`` will execute the ``run()`` command.\n\n       .. important::\n          Subcommands **SHOULD** take advantage of ``editable_mode=True`` to adequate\n          its behaviour or perform optimisations.\n\n          For example, if a subcommand doesn't need to generate an extra file and\n          all it does is to copy a source file into the build directory,\n          ``run()`` **SHOULD** simply \"early return\".\n\n          Similarly, if the subcommand creates files that would be placed alongside\n          Python files in the final distribution, during an editable install\n          the command **SHOULD** generate these files \"in place\" (i.e. write them to\n          the original source directory, instead of using the build directory).\n          Note that ``get_output_mapping()`` should reflect that and include mappings\n          for \"in place\" builds accordingly.\n\n    3. ``setuptools`` use any knowledge it can derive from the return values of\n       ``get_outputs()`` and ``get_output_mapping()`` to create an editable wheel.\n       When relevant ``setuptools`` **MAY** attempt to use file links based on the value\n       of ``get_output_mapping()``. Alternatively, ``setuptools`` **MAY** attempt to use\n       :doc:`import hooks <python:reference/import>` to redirect any attempt to import\n       to the directory with the original source code and other files built in place.\n\n    Please note that custom sub-commands **SHOULD NOT** rely on ``run()`` being\n    executed (or not) to provide correct return values for ``get_outputs()``,\n    ``get_output_mapping()`` or ``get_source_files()``. The ``get_*`` methods should\n    work independently of ``run()``.\n    \"\"\"\n\n    editable_mode: bool = False\n    \"\"\"Boolean flag that will be set to ``True`` when setuptools is used for an\n    editable installation (see :pep:`660`).\n    Implementations **SHOULD** explicitly set the default value of this attribute to\n    ``False``.\n    When subcommands run, they can use this flag to perform optimizations or change\n    their behaviour accordingly.\n    \"\"\"\n\n    build_lib: str\n    \"\"\"String representing the directory where the build artifacts should be stored,\n    e.g. ``build/lib``.\n    For example, if a distribution wants to provide a Python module named ``pkg.mod``,\n    then a corresponding file should be written to ``{build_lib}/package/module.py``.\n    A way of thinking about this is that the files saved under ``build_lib``\n    would be eventually copied to one of the directories in :obj:`site.PREFIXES`\n    upon installation.\n\n    A command that produces platform-independent files (e.g. compiling text templates\n    into Python functions), **CAN** initialize ``build_lib`` by copying its value from\n    the ``build_py`` command. On the other hand, a command that produces\n    platform-specific files **CAN** initialize ``build_lib`` by copying its value from\n    the ``build_ext`` command. In general this is done inside the ``finalize_options``\n    method with the help of the ``set_undefined_options`` command::\n\n        def finalize_options(self):\n            self.set_undefined_options(\"build_py\", (\"build_lib\", \"build_lib\"))\n            ...\n    \"\"\"\n\n    def initialize_options(self):\n        \"\"\"(Required by the original :class:`setuptools.Command` interface)\"\"\"\n\n    def finalize_options(self):\n        \"\"\"(Required by the original :class:`setuptools.Command` interface)\"\"\"\n\n    def run(self):\n        \"\"\"(Required by the original :class:`setuptools.Command` interface)\"\"\"\n\n    def get_source_files(self) -> List[str]:\n        \"\"\"\n        Return a list of all files that are used by the command to create the expected\n        outputs.\n        For example, if your build command transpiles Java files into Python, you should\n        list here all the Java files.\n        The primary purpose of this function is to help populating the ``sdist``\n        with all the files necessary to build the distribution.\n        All files should be strings relative to the project root directory.\n        \"\"\"\n\n    def get_outputs(self) -> List[str]:\n        \"\"\"\n        Return a list of files intended for distribution as they would have been\n        produced by the build.\n        These files should be strings in the form of\n        ``\"{build_lib}/destination/file/path\"``.\n\n        .. note::\n           The return value of ``get_output()`` should include all files used as keys\n           in ``get_output_mapping()`` plus files that are generated during the build\n           and don't correspond to any source file already present in the project.\n        \"\"\"\n\n    def get_output_mapping(self) -> Dict[str, str]:\n        \"\"\"\n        Return a mapping between destination files as they would be produced by the\n        build (dict keys) into the respective existing (source) files (dict values).\n        Existing (source) files should be represented as strings relative to the project\n        root directory.\n        Destination files should be strings in the form of\n        ``\"{build_lib}/destination/file/path\"``.\n        \"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/build_clib.py",
    "content": "import distutils.command.build_clib as orig\nfrom distutils.errors import DistutilsSetupError\nfrom distutils import log\nfrom setuptools.dep_util import newer_pairwise_group\n\n\nclass build_clib(orig.build_clib):\n    \"\"\"\n    Override the default build_clib behaviour to do the following:\n\n    1. Implement a rudimentary timestamp-based dependency system\n       so 'compile()' doesn't run every time.\n    2. Add more keys to the 'build_info' dictionary:\n        * obj_deps - specify dependencies for each object compiled.\n                     this should be a dictionary mapping a key\n                     with the source filename to a list of\n                     dependencies. Use an empty string for global\n                     dependencies.\n        * cflags   - specify a list of additional flags to pass to\n                     the compiler.\n    \"\"\"\n\n    def build_libraries(self, libraries):\n        for (lib_name, build_info) in libraries:\n            sources = build_info.get('sources')\n            if sources is None or not isinstance(sources, (list, tuple)):\n                raise DistutilsSetupError(\n                    \"in 'libraries' option (library '%s'), \"\n                    \"'sources' must be present and must be \"\n                    \"a list of source filenames\" % lib_name)\n            sources = list(sources)\n\n            log.info(\"building '%s' library\", lib_name)\n\n            # Make sure everything is the correct type.\n            # obj_deps should be a dictionary of keys as sources\n            # and a list/tuple of files that are its dependencies.\n            obj_deps = build_info.get('obj_deps', dict())\n            if not isinstance(obj_deps, dict):\n                raise DistutilsSetupError(\n                    \"in 'libraries' option (library '%s'), \"\n                    \"'obj_deps' must be a dictionary of \"\n                    \"type 'source: list'\" % lib_name)\n            dependencies = []\n\n            # Get the global dependencies that are specified by the '' key.\n            # These will go into every source's dependency list.\n            global_deps = obj_deps.get('', list())\n            if not isinstance(global_deps, (list, tuple)):\n                raise DistutilsSetupError(\n                    \"in 'libraries' option (library '%s'), \"\n                    \"'obj_deps' must be a dictionary of \"\n                    \"type 'source: list'\" % lib_name)\n\n            # Build the list to be used by newer_pairwise_group\n            # each source will be auto-added to its dependencies.\n            for source in sources:\n                src_deps = [source]\n                src_deps.extend(global_deps)\n                extra_deps = obj_deps.get(source, list())\n                if not isinstance(extra_deps, (list, tuple)):\n                    raise DistutilsSetupError(\n                        \"in 'libraries' option (library '%s'), \"\n                        \"'obj_deps' must be a dictionary of \"\n                        \"type 'source: list'\" % lib_name)\n                src_deps.extend(extra_deps)\n                dependencies.append(src_deps)\n\n            expected_objects = self.compiler.object_filenames(\n                sources,\n                output_dir=self.build_temp,\n            )\n\n            if (\n                newer_pairwise_group(dependencies, expected_objects)\n                != ([], [])\n            ):\n                # First, compile the source code to object files in the library\n                # directory.  (This should probably change to putting object\n                # files in a temporary build directory.)\n                macros = build_info.get('macros')\n                include_dirs = build_info.get('include_dirs')\n                cflags = build_info.get('cflags')\n                self.compiler.compile(\n                    sources,\n                    output_dir=self.build_temp,\n                    macros=macros,\n                    include_dirs=include_dirs,\n                    extra_postargs=cflags,\n                    debug=self.debug\n                )\n\n            # Now \"link\" the object files together into a static library.\n            # (On Unix at least, this isn't really linking -- it just\n            # builds an archive.  Whatever.)\n            self.compiler.create_static_lib(\n                expected_objects,\n                lib_name,\n                output_dir=self.build_clib,\n                debug=self.debug\n            )\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/build_ext.py",
    "content": "import os\nimport sys\nimport itertools\nfrom importlib.machinery import EXTENSION_SUFFIXES\nfrom importlib.util import cache_from_source as _compiled_file_name\nfrom typing import Dict, Iterator, List, Tuple\n\nfrom distutils.command.build_ext import build_ext as _du_build_ext\nfrom distutils.ccompiler import new_compiler\nfrom distutils.sysconfig import customize_compiler, get_config_var\nfrom distutils import log\n\nfrom setuptools.errors import BaseError\nfrom setuptools.extension import Extension, Library\n\ntry:\n    # Attempt to use Cython for building extensions, if available\n    from Cython.Distutils.build_ext import build_ext as _build_ext\n    # Additionally, assert that the compiler module will load\n    # also. Ref #1229.\n    __import__('Cython.Compiler.Main')\nexcept ImportError:\n    _build_ext = _du_build_ext\n\n# make sure _config_vars is initialized\nget_config_var(\"LDSHARED\")\nfrom distutils.sysconfig import _config_vars as _CONFIG_VARS  # noqa\n\n\ndef _customize_compiler_for_shlib(compiler):\n    if sys.platform == \"darwin\":\n        # building .dylib requires additional compiler flags on OSX; here we\n        # temporarily substitute the pyconfig.h variables so that distutils'\n        # 'customize_compiler' uses them before we build the shared libraries.\n        tmp = _CONFIG_VARS.copy()\n        try:\n            # XXX Help!  I don't have any idea whether these are right...\n            _CONFIG_VARS['LDSHARED'] = (\n                \"gcc -Wl,-x -dynamiclib -undefined dynamic_lookup\")\n            _CONFIG_VARS['CCSHARED'] = \" -dynamiclib\"\n            _CONFIG_VARS['SO'] = \".dylib\"\n            customize_compiler(compiler)\n        finally:\n            _CONFIG_VARS.clear()\n            _CONFIG_VARS.update(tmp)\n    else:\n        customize_compiler(compiler)\n\n\nhave_rtld = False\nuse_stubs = False\nlibtype = 'shared'\n\nif sys.platform == \"darwin\":\n    use_stubs = True\nelif os.name != 'nt':\n    try:\n        import dl\n        use_stubs = have_rtld = hasattr(dl, 'RTLD_NOW')\n    except ImportError:\n        pass\n\n\ndef if_dl(s):\n    return s if have_rtld else ''\n\n\ndef get_abi3_suffix():\n    \"\"\"Return the file extension for an abi3-compliant Extension()\"\"\"\n    for suffix in EXTENSION_SUFFIXES:\n        if '.abi3' in suffix:  # Unix\n            return suffix\n        elif suffix == '.pyd':  # Windows\n            return suffix\n\n\nclass build_ext(_build_ext):\n    editable_mode: bool = False\n    inplace: bool = False\n\n    def run(self):\n        \"\"\"Build extensions in build directory, then copy if --inplace\"\"\"\n        old_inplace, self.inplace = self.inplace, 0\n        _build_ext.run(self)\n        self.inplace = old_inplace\n        if old_inplace:\n            self.copy_extensions_to_source()\n\n    def _get_inplace_equivalent(self, build_py, ext: Extension) -> Tuple[str, str]:\n        fullname = self.get_ext_fullname(ext.name)\n        filename = self.get_ext_filename(fullname)\n        modpath = fullname.split('.')\n        package = '.'.join(modpath[:-1])\n        package_dir = build_py.get_package_dir(package)\n        inplace_file = os.path.join(package_dir, os.path.basename(filename))\n        regular_file = os.path.join(self.build_lib, filename)\n        return (inplace_file, regular_file)\n\n    def copy_extensions_to_source(self):\n        build_py = self.get_finalized_command('build_py')\n        for ext in self.extensions:\n            inplace_file, regular_file = self._get_inplace_equivalent(build_py, ext)\n\n            # Always copy, even if source is older than destination, to ensure\n            # that the right extensions for the current Python/platform are\n            # used.\n            if os.path.exists(regular_file) or not ext.optional:\n                self.copy_file(regular_file, inplace_file, level=self.verbose)\n\n            if ext._needs_stub:\n                inplace_stub = self._get_equivalent_stub(ext, inplace_file)\n                self._write_stub_file(inplace_stub, ext, compile=True)\n                # Always compile stub and remove the original (leave the cache behind)\n                # (this behaviour was observed in previous iterations of the code)\n\n    def _get_equivalent_stub(self, ext: Extension, output_file: str) -> str:\n        dir_ = os.path.dirname(output_file)\n        _, _, name = ext.name.rpartition(\".\")\n        return f\"{os.path.join(dir_, name)}.py\"\n\n    def _get_output_mapping(self) -> Iterator[Tuple[str, str]]:\n        if not self.inplace:\n            return\n\n        build_py = self.get_finalized_command('build_py')\n        opt = self.get_finalized_command('install_lib').optimize or \"\"\n\n        for ext in self.extensions:\n            inplace_file, regular_file = self._get_inplace_equivalent(build_py, ext)\n            yield (regular_file, inplace_file)\n\n            if ext._needs_stub:\n                # This version of `build_ext` always builds artifacts in another dir,\n                # when \"inplace=True\" is given it just copies them back.\n                # This is done in the `copy_extensions_to_source` function, which\n                # always compile stub files via `_compile_and_remove_stub`.\n                # At the end of the process, a `.pyc` stub file is created without the\n                # corresponding `.py`.\n\n                inplace_stub = self._get_equivalent_stub(ext, inplace_file)\n                regular_stub = self._get_equivalent_stub(ext, regular_file)\n                inplace_cache = _compiled_file_name(inplace_stub, optimization=opt)\n                output_cache = _compiled_file_name(regular_stub, optimization=opt)\n                yield (output_cache, inplace_cache)\n\n    def get_ext_filename(self, fullname):\n        so_ext = os.getenv('SETUPTOOLS_EXT_SUFFIX')\n        if so_ext:\n            filename = os.path.join(*fullname.split('.')) + so_ext\n        else:\n            filename = _build_ext.get_ext_filename(self, fullname)\n            so_ext = get_config_var('EXT_SUFFIX')\n\n        if fullname in self.ext_map:\n            ext = self.ext_map[fullname]\n            use_abi3 = getattr(ext, 'py_limited_api') and get_abi3_suffix()\n            if use_abi3:\n                filename = filename[:-len(so_ext)]\n                so_ext = get_abi3_suffix()\n                filename = filename + so_ext\n            if isinstance(ext, Library):\n                fn, ext = os.path.splitext(filename)\n                return self.shlib_compiler.library_filename(fn, libtype)\n            elif use_stubs and ext._links_to_dynamic:\n                d, fn = os.path.split(filename)\n                return os.path.join(d, 'dl-' + fn)\n        return filename\n\n    def initialize_options(self):\n        _build_ext.initialize_options(self)\n        self.shlib_compiler = None\n        self.shlibs = []\n        self.ext_map = {}\n        self.editable_mode = False\n\n    def finalize_options(self):\n        _build_ext.finalize_options(self)\n        self.extensions = self.extensions or []\n        self.check_extensions_list(self.extensions)\n        self.shlibs = [ext for ext in self.extensions\n                       if isinstance(ext, Library)]\n        if self.shlibs:\n            self.setup_shlib_compiler()\n        for ext in self.extensions:\n            ext._full_name = self.get_ext_fullname(ext.name)\n        for ext in self.extensions:\n            fullname = ext._full_name\n            self.ext_map[fullname] = ext\n\n            # distutils 3.1 will also ask for module names\n            # XXX what to do with conflicts?\n            self.ext_map[fullname.split('.')[-1]] = ext\n\n            ltd = self.shlibs and self.links_to_dynamic(ext) or False\n            ns = ltd and use_stubs and not isinstance(ext, Library)\n            ext._links_to_dynamic = ltd\n            ext._needs_stub = ns\n            filename = ext._file_name = self.get_ext_filename(fullname)\n            libdir = os.path.dirname(os.path.join(self.build_lib, filename))\n            if ltd and libdir not in ext.library_dirs:\n                ext.library_dirs.append(libdir)\n            if ltd and use_stubs and os.curdir not in ext.runtime_library_dirs:\n                ext.runtime_library_dirs.append(os.curdir)\n\n        if self.editable_mode:\n            self.inplace = True\n\n    def setup_shlib_compiler(self):\n        compiler = self.shlib_compiler = new_compiler(\n            compiler=self.compiler, dry_run=self.dry_run, force=self.force\n        )\n        _customize_compiler_for_shlib(compiler)\n\n        if self.include_dirs is not None:\n            compiler.set_include_dirs(self.include_dirs)\n        if self.define is not None:\n            # 'define' option is a list of (name,value) tuples\n            for (name, value) in self.define:\n                compiler.define_macro(name, value)\n        if self.undef is not None:\n            for macro in self.undef:\n                compiler.undefine_macro(macro)\n        if self.libraries is not None:\n            compiler.set_libraries(self.libraries)\n        if self.library_dirs is not None:\n            compiler.set_library_dirs(self.library_dirs)\n        if self.rpath is not None:\n            compiler.set_runtime_library_dirs(self.rpath)\n        if self.link_objects is not None:\n            compiler.set_link_objects(self.link_objects)\n\n        # hack so distutils' build_extension() builds a library instead\n        compiler.link_shared_object = link_shared_object.__get__(compiler)\n\n    def get_export_symbols(self, ext):\n        if isinstance(ext, Library):\n            return ext.export_symbols\n        return _build_ext.get_export_symbols(self, ext)\n\n    def build_extension(self, ext):\n        ext._convert_pyx_sources_to_lang()\n        _compiler = self.compiler\n        try:\n            if isinstance(ext, Library):\n                self.compiler = self.shlib_compiler\n            _build_ext.build_extension(self, ext)\n            if ext._needs_stub:\n                build_lib = self.get_finalized_command('build_py').build_lib\n                self.write_stub(build_lib, ext)\n        finally:\n            self.compiler = _compiler\n\n    def links_to_dynamic(self, ext):\n        \"\"\"Return true if 'ext' links to a dynamic lib in the same package\"\"\"\n        # XXX this should check to ensure the lib is actually being built\n        # XXX as dynamic, and not just using a locally-found version or a\n        # XXX static-compiled version\n        libnames = dict.fromkeys([lib._full_name for lib in self.shlibs])\n        pkg = '.'.join(ext._full_name.split('.')[:-1] + [''])\n        return any(pkg + libname in libnames for libname in ext.libraries)\n\n    def get_outputs(self) -> List[str]:\n        if self.inplace:\n            return list(self.get_output_mapping().keys())\n        return sorted(_build_ext.get_outputs(self) + self.__get_stubs_outputs())\n\n    def get_output_mapping(self) -> Dict[str, str]:\n        \"\"\"See :class:`setuptools.commands.build.SubCommand`\"\"\"\n        mapping = self._get_output_mapping()\n        return dict(sorted(mapping, key=lambda x: x[0]))\n\n    def __get_stubs_outputs(self):\n        # assemble the base name for each extension that needs a stub\n        ns_ext_bases = (\n            os.path.join(self.build_lib, *ext._full_name.split('.'))\n            for ext in self.extensions\n            if ext._needs_stub\n        )\n        # pair each base with the extension\n        pairs = itertools.product(ns_ext_bases, self.__get_output_extensions())\n        return list(base + fnext for base, fnext in pairs)\n\n    def __get_output_extensions(self):\n        yield '.py'\n        yield '.pyc'\n        if self.get_finalized_command('build_py').optimize:\n            yield '.pyo'\n\n    def write_stub(self, output_dir, ext, compile=False):\n        stub_file = os.path.join(output_dir, *ext._full_name.split('.')) + '.py'\n        self._write_stub_file(stub_file, ext, compile)\n\n    def _write_stub_file(self, stub_file: str, ext: Extension, compile=False):\n        log.info(\"writing stub loader for %s to %s\", ext._full_name, stub_file)\n        if compile and os.path.exists(stub_file):\n            raise BaseError(stub_file + \" already exists! Please delete.\")\n        if not self.dry_run:\n            f = open(stub_file, 'w')\n            f.write(\n                '\\n'.join([\n                    \"def __bootstrap__():\",\n                    \"   global __bootstrap__, __file__, __loader__\",\n                    \"   import sys, os, pkg_resources, importlib.util\" +\n                    if_dl(\", dl\"),\n                    \"   __file__ = pkg_resources.resource_filename\"\n                    \"(__name__,%r)\"\n                    % os.path.basename(ext._file_name),\n                    \"   del __bootstrap__\",\n                    \"   if '__loader__' in globals():\",\n                    \"       del __loader__\",\n                    if_dl(\"   old_flags = sys.getdlopenflags()\"),\n                    \"   old_dir = os.getcwd()\",\n                    \"   try:\",\n                    \"     os.chdir(os.path.dirname(__file__))\",\n                    if_dl(\"     sys.setdlopenflags(dl.RTLD_NOW)\"),\n                    \"     spec = importlib.util.spec_from_file_location(\",\n                    \"                __name__, __file__)\",\n                    \"     mod = importlib.util.module_from_spec(spec)\",\n                    \"     spec.loader.exec_module(mod)\",\n                    \"   finally:\",\n                    if_dl(\"     sys.setdlopenflags(old_flags)\"),\n                    \"     os.chdir(old_dir)\",\n                    \"__bootstrap__()\",\n                    \"\"  # terminal \\n\n                ])\n            )\n            f.close()\n        if compile:\n            self._compile_and_remove_stub(stub_file)\n\n    def _compile_and_remove_stub(self, stub_file: str):\n        from distutils.util import byte_compile\n\n        byte_compile([stub_file], optimize=0,\n                     force=True, dry_run=self.dry_run)\n        optimize = self.get_finalized_command('install_lib').optimize\n        if optimize > 0:\n            byte_compile([stub_file], optimize=optimize,\n                         force=True, dry_run=self.dry_run)\n        if os.path.exists(stub_file) and not self.dry_run:\n            os.unlink(stub_file)\n\n\nif use_stubs or os.name == 'nt':\n    # Build shared libraries\n    #\n    def link_shared_object(\n            self, objects, output_libname, output_dir=None, libraries=None,\n            library_dirs=None, runtime_library_dirs=None, export_symbols=None,\n            debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,\n            target_lang=None):\n        self.link(\n            self.SHARED_LIBRARY, objects, output_libname,\n            output_dir, libraries, library_dirs, runtime_library_dirs,\n            export_symbols, debug, extra_preargs, extra_postargs,\n            build_temp, target_lang\n        )\nelse:\n    # Build static libraries everywhere else\n    libtype = 'static'\n\n    def link_shared_object(\n            self, objects, output_libname, output_dir=None, libraries=None,\n            library_dirs=None, runtime_library_dirs=None, export_symbols=None,\n            debug=0, extra_preargs=None, extra_postargs=None, build_temp=None,\n            target_lang=None):\n        # XXX we need to either disallow these attrs on Library instances,\n        # or warn/abort here if set, or something...\n        # libraries=None, library_dirs=None, runtime_library_dirs=None,\n        # export_symbols=None, extra_preargs=None, extra_postargs=None,\n        # build_temp=None\n\n        assert output_dir is None  # distutils build_ext doesn't pass this\n        output_dir, filename = os.path.split(output_libname)\n        basename, ext = os.path.splitext(filename)\n        if self.library_filename(\"x\").startswith('lib'):\n            # strip 'lib' prefix; this is kludgy if some platform uses\n            # a different prefix\n            basename = basename[3:]\n\n        self.create_static_lib(\n            objects, basename, output_dir, debug, target_lang\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/build_py.py",
    "content": "from functools import partial\nfrom glob import glob\nfrom distutils.util import convert_path\nimport distutils.command.build_py as orig\nimport os\nimport fnmatch\nimport textwrap\nimport io\nimport distutils.errors\nimport itertools\nimport stat\nimport warnings\nfrom pathlib import Path\nfrom typing import Dict, Iterable, Iterator, List, Optional, Tuple\n\nfrom setuptools._deprecation_warning import SetuptoolsDeprecationWarning\nfrom setuptools.extern.more_itertools import unique_everseen\n\n\ndef make_writable(target):\n    os.chmod(target, os.stat(target).st_mode | stat.S_IWRITE)\n\n\nclass build_py(orig.build_py):\n    \"\"\"Enhanced 'build_py' command that includes data files with packages\n\n    The data files are specified via a 'package_data' argument to 'setup()'.\n    See 'setuptools.dist.Distribution' for more details.\n\n    Also, this version of the 'build_py' command allows you to specify both\n    'py_modules' and 'packages' in the same setup operation.\n    \"\"\"\n    editable_mode: bool = False\n    existing_egg_info_dir: Optional[str] = None  #: Private API, internal use only.\n\n    def finalize_options(self):\n        orig.build_py.finalize_options(self)\n        self.package_data = self.distribution.package_data\n        self.exclude_package_data = self.distribution.exclude_package_data or {}\n        if 'data_files' in self.__dict__:\n            del self.__dict__['data_files']\n        self.__updated_files = []\n\n    def copy_file(self, infile, outfile, preserve_mode=1, preserve_times=1,\n                  link=None, level=1):\n        # Overwrite base class to allow using links\n        if link:\n            infile = str(Path(infile).resolve())\n            outfile = str(Path(outfile).resolve())\n        return super().copy_file(infile, outfile, preserve_mode, preserve_times,\n                                 link, level)\n\n    def run(self):\n        \"\"\"Build modules, packages, and copy data files to build directory\"\"\"\n        if not (self.py_modules or self.packages) or self.editable_mode:\n            return\n\n        if self.py_modules:\n            self.build_modules()\n\n        if self.packages:\n            self.build_packages()\n            self.build_package_data()\n\n        # Only compile actual .py files, using our base class' idea of what our\n        # output files are.\n        self.byte_compile(orig.build_py.get_outputs(self, include_bytecode=0))\n\n    def __getattr__(self, attr):\n        \"lazily compute data files\"\n        if attr == 'data_files':\n            self.data_files = self._get_data_files()\n            return self.data_files\n        return orig.build_py.__getattr__(self, attr)\n\n    def build_module(self, module, module_file, package):\n        outfile, copied = orig.build_py.build_module(self, module, module_file, package)\n        if copied:\n            self.__updated_files.append(outfile)\n        return outfile, copied\n\n    def _get_data_files(self):\n        \"\"\"Generate list of '(package,src_dir,build_dir,filenames)' tuples\"\"\"\n        self.analyze_manifest()\n        return list(map(self._get_pkg_data_files, self.packages or ()))\n\n    def get_data_files_without_manifest(self):\n        \"\"\"\n        Generate list of ``(package,src_dir,build_dir,filenames)`` tuples,\n        but without triggering any attempt to analyze or build the manifest.\n        \"\"\"\n        # Prevent eventual errors from unset `manifest_files`\n        # (that would otherwise be set by `analyze_manifest`)\n        self.__dict__.setdefault('manifest_files', {})\n        return list(map(self._get_pkg_data_files, self.packages or ()))\n\n    def _get_pkg_data_files(self, package):\n        # Locate package source directory\n        src_dir = self.get_package_dir(package)\n\n        # Compute package build directory\n        build_dir = os.path.join(*([self.build_lib] + package.split('.')))\n\n        # Strip directory from globbed filenames\n        filenames = [\n            os.path.relpath(file, src_dir)\n            for file in self.find_data_files(package, src_dir)\n        ]\n        return package, src_dir, build_dir, filenames\n\n    def find_data_files(self, package, src_dir):\n        \"\"\"Return filenames for package's data files in 'src_dir'\"\"\"\n        patterns = self._get_platform_patterns(\n            self.package_data,\n            package,\n            src_dir,\n        )\n        globs_expanded = map(partial(glob, recursive=True), patterns)\n        # flatten the expanded globs into an iterable of matches\n        globs_matches = itertools.chain.from_iterable(globs_expanded)\n        glob_files = filter(os.path.isfile, globs_matches)\n        files = itertools.chain(\n            self.manifest_files.get(package, []),\n            glob_files,\n        )\n        return self.exclude_data_files(package, src_dir, files)\n\n    def get_outputs(self, include_bytecode=1) -> List[str]:\n        \"\"\"See :class:`setuptools.commands.build.SubCommand`\"\"\"\n        if self.editable_mode:\n            return list(self.get_output_mapping().keys())\n        return super().get_outputs(include_bytecode)\n\n    def get_output_mapping(self) -> Dict[str, str]:\n        \"\"\"See :class:`setuptools.commands.build.SubCommand`\"\"\"\n        mapping = itertools.chain(\n            self._get_package_data_output_mapping(),\n            self._get_module_mapping(),\n        )\n        return dict(sorted(mapping, key=lambda x: x[0]))\n\n    def _get_module_mapping(self) -> Iterator[Tuple[str, str]]:\n        \"\"\"Iterate over all modules producing (dest, src) pairs.\"\"\"\n        for (package, module, module_file) in self.find_all_modules():\n            package = package.split('.')\n            filename = self.get_module_outfile(self.build_lib, package, module)\n            yield (filename, module_file)\n\n    def _get_package_data_output_mapping(self) -> Iterator[Tuple[str, str]]:\n        \"\"\"Iterate over package data producing (dest, src) pairs.\"\"\"\n        for package, src_dir, build_dir, filenames in self.data_files:\n            for filename in filenames:\n                target = os.path.join(build_dir, filename)\n                srcfile = os.path.join(src_dir, filename)\n                yield (target, srcfile)\n\n    def build_package_data(self):\n        \"\"\"Copy data files into build directory\"\"\"\n        for target, srcfile in self._get_package_data_output_mapping():\n            self.mkpath(os.path.dirname(target))\n            _outf, _copied = self.copy_file(srcfile, target)\n            make_writable(target)\n\n    def analyze_manifest(self):\n        self.manifest_files = mf = {}\n        if not self.distribution.include_package_data:\n            return\n        src_dirs = {}\n        for package in self.packages or ():\n            # Locate package source directory\n            src_dirs[assert_relative(self.get_package_dir(package))] = package\n\n        if (\n            getattr(self, 'existing_egg_info_dir', None)\n            and Path(self.existing_egg_info_dir, \"SOURCES.txt\").exists()\n        ):\n            egg_info_dir = self.existing_egg_info_dir\n            manifest = Path(egg_info_dir, \"SOURCES.txt\")\n            files = manifest.read_text(encoding=\"utf-8\").splitlines()\n        else:\n            self.run_command('egg_info')\n            ei_cmd = self.get_finalized_command('egg_info')\n            egg_info_dir = ei_cmd.egg_info\n            files = ei_cmd.filelist.files\n\n        check = _IncludePackageDataAbuse()\n        for path in self._filter_build_files(files, egg_info_dir):\n            d, f = os.path.split(assert_relative(path))\n            prev = None\n            oldf = f\n            while d and d != prev and d not in src_dirs:\n                prev = d\n                d, df = os.path.split(d)\n                f = os.path.join(df, f)\n            if d in src_dirs:\n                if f == oldf:\n                    if check.is_module(f):\n                        continue  # it's a module, not data\n                else:\n                    importable = check.importable_subpackage(src_dirs[d], f)\n                    if importable:\n                        check.warn(importable)\n                mf.setdefault(src_dirs[d], []).append(path)\n\n    def _filter_build_files(self, files: Iterable[str], egg_info: str) -> Iterator[str]:\n        \"\"\"\n        ``build_meta`` may try to create egg_info outside of the project directory,\n        and this can be problematic for certain plugins (reported in issue #3500).\n\n        Extensions might also include between their sources files created on the\n        ``build_lib`` and ``build_temp`` directories.\n\n        This function should filter this case of invalid files out.\n        \"\"\"\n        build = self.get_finalized_command(\"build\")\n        build_dirs = (egg_info, self.build_lib, build.build_temp, build.build_base)\n        norm_dirs = [os.path.normpath(p) for p in build_dirs if p]\n\n        for file in files:\n            norm_path = os.path.normpath(file)\n            if not os.path.isabs(file) or all(d not in norm_path for d in norm_dirs):\n                yield file\n\n    def get_data_files(self):\n        pass  # Lazily compute data files in _get_data_files() function.\n\n    def check_package(self, package, package_dir):\n        \"\"\"Check namespace packages' __init__ for declare_namespace\"\"\"\n        try:\n            return self.packages_checked[package]\n        except KeyError:\n            pass\n\n        init_py = orig.build_py.check_package(self, package, package_dir)\n        self.packages_checked[package] = init_py\n\n        if not init_py or not self.distribution.namespace_packages:\n            return init_py\n\n        for pkg in self.distribution.namespace_packages:\n            if pkg == package or pkg.startswith(package + '.'):\n                break\n        else:\n            return init_py\n\n        with io.open(init_py, 'rb') as f:\n            contents = f.read()\n        if b'declare_namespace' not in contents:\n            raise distutils.errors.DistutilsError(\n                \"Namespace package problem: %s is a namespace package, but \"\n                \"its\\n__init__.py does not call declare_namespace()! Please \"\n                'fix it.\\n(See the setuptools manual under '\n                '\"Namespace Packages\" for details.)\\n\"' % (package,)\n            )\n        return init_py\n\n    def initialize_options(self):\n        self.packages_checked = {}\n        orig.build_py.initialize_options(self)\n        self.editable_mode = False\n        self.existing_egg_info_dir = None\n\n    def get_package_dir(self, package):\n        res = orig.build_py.get_package_dir(self, package)\n        if self.distribution.src_root is not None:\n            return os.path.join(self.distribution.src_root, res)\n        return res\n\n    def exclude_data_files(self, package, src_dir, files):\n        \"\"\"Filter filenames for package's data files in 'src_dir'\"\"\"\n        files = list(files)\n        patterns = self._get_platform_patterns(\n            self.exclude_package_data,\n            package,\n            src_dir,\n        )\n        match_groups = (fnmatch.filter(files, pattern) for pattern in patterns)\n        # flatten the groups of matches into an iterable of matches\n        matches = itertools.chain.from_iterable(match_groups)\n        bad = set(matches)\n        keepers = (fn for fn in files if fn not in bad)\n        # ditch dupes\n        return list(unique_everseen(keepers))\n\n    @staticmethod\n    def _get_platform_patterns(spec, package, src_dir):\n        \"\"\"\n        yield platform-specific path patterns (suitable for glob\n        or fn_match) from a glob-based spec (such as\n        self.package_data or self.exclude_package_data)\n        matching package in src_dir.\n        \"\"\"\n        raw_patterns = itertools.chain(\n            spec.get('', []),\n            spec.get(package, []),\n        )\n        return (\n            # Each pattern has to be converted to a platform-specific path\n            os.path.join(src_dir, convert_path(pattern))\n            for pattern in raw_patterns\n        )\n\n\ndef assert_relative(path):\n    if not os.path.isabs(path):\n        return path\n    from distutils.errors import DistutilsSetupError\n\n    msg = (\n        textwrap.dedent(\n            \"\"\"\n        Error: setup script specifies an absolute path:\n\n            %s\n\n        setup() arguments must *always* be /-separated paths relative to the\n        setup.py directory, *never* absolute paths.\n        \"\"\"\n        ).lstrip()\n        % path\n    )\n    raise DistutilsSetupError(msg)\n\n\nclass _IncludePackageDataAbuse:\n    \"\"\"Inform users that package or module is included as 'data file'\"\"\"\n\n    MESSAGE = \"\"\"\\\n    Installing {importable!r} as data is deprecated, please list it in `packages`.\n    !!\\n\\n\n    ############################\n    # Package would be ignored #\n    ############################\n    Python recognizes {importable!r} as an importable package,\n    but it is not listed in the `packages` configuration of setuptools.\n\n    {importable!r} has been automatically added to the distribution only\n    because it may contain data files, but this behavior is likely to change\n    in future versions of setuptools (and therefore is considered deprecated).\n\n    Please make sure that {importable!r} is included as a package by using\n    the `packages` configuration field or the proper discovery methods\n    (for example by using `find_namespace_packages(...)`/`find_namespace:`\n    instead of `find_packages(...)`/`find:`).\n\n    You can read more about \"package discovery\" and \"data files\" on setuptools\n    documentation page.\n    \\n\\n!!\n    \"\"\"\n\n    def __init__(self):\n        self._already_warned = set()\n\n    def is_module(self, file):\n        return file.endswith(\".py\") and file[:-len(\".py\")].isidentifier()\n\n    def importable_subpackage(self, parent, file):\n        pkg = Path(file).parent\n        parts = list(itertools.takewhile(str.isidentifier, pkg.parts))\n        if parts:\n            return \".\".join([parent, *parts])\n        return None\n\n    def warn(self, importable):\n        if importable not in self._already_warned:\n            msg = textwrap.dedent(self.MESSAGE).format(importable=importable)\n            warnings.warn(msg, SetuptoolsDeprecationWarning, stacklevel=2)\n            self._already_warned.add(importable)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/develop.py",
    "content": "from distutils.util import convert_path\nfrom distutils import log\nfrom distutils.errors import DistutilsError, DistutilsOptionError\nimport os\nimport glob\nimport io\n\nimport pkg_resources\nfrom setuptools.command.easy_install import easy_install\nfrom setuptools import namespaces\nimport setuptools\n\n\nclass develop(namespaces.DevelopInstaller, easy_install):\n    \"\"\"Set up package for development\"\"\"\n\n    description = \"install package in 'development mode'\"\n\n    user_options = easy_install.user_options + [\n        (\"uninstall\", \"u\", \"Uninstall this source package\"),\n        (\"egg-path=\", None, \"Set the path to be used in the .egg-link file\"),\n    ]\n\n    boolean_options = easy_install.boolean_options + ['uninstall']\n\n    command_consumes_arguments = False  # override base\n\n    def run(self):\n        if self.uninstall:\n            self.multi_version = True\n            self.uninstall_link()\n            self.uninstall_namespaces()\n        else:\n            self.install_for_development()\n        self.warn_deprecated_options()\n\n    def initialize_options(self):\n        self.uninstall = None\n        self.egg_path = None\n        easy_install.initialize_options(self)\n        self.setup_path = None\n        self.always_copy_from = '.'  # always copy eggs installed in curdir\n\n    def finalize_options(self):\n        ei = self.get_finalized_command(\"egg_info\")\n        if ei.broken_egg_info:\n            template = \"Please rename %r to %r before using 'develop'\"\n            args = ei.egg_info, ei.broken_egg_info\n            raise DistutilsError(template % args)\n        self.args = [ei.egg_name]\n\n        easy_install.finalize_options(self)\n        self.expand_basedirs()\n        self.expand_dirs()\n        # pick up setup-dir .egg files only: no .egg-info\n        self.package_index.scan(glob.glob('*.egg'))\n\n        egg_link_fn = ei.egg_name + '.egg-link'\n        self.egg_link = os.path.join(self.install_dir, egg_link_fn)\n        self.egg_base = ei.egg_base\n        if self.egg_path is None:\n            self.egg_path = os.path.abspath(ei.egg_base)\n\n        target = pkg_resources.normalize_path(self.egg_base)\n        egg_path = pkg_resources.normalize_path(\n            os.path.join(self.install_dir, self.egg_path)\n        )\n        if egg_path != target:\n            raise DistutilsOptionError(\n                \"--egg-path must be a relative path from the install\"\n                \" directory to \" + target\n            )\n\n        # Make a distribution for the package's source\n        self.dist = pkg_resources.Distribution(\n            target,\n            pkg_resources.PathMetadata(target, os.path.abspath(ei.egg_info)),\n            project_name=ei.egg_name,\n        )\n\n        self.setup_path = self._resolve_setup_path(\n            self.egg_base,\n            self.install_dir,\n            self.egg_path,\n        )\n\n    @staticmethod\n    def _resolve_setup_path(egg_base, install_dir, egg_path):\n        \"\"\"\n        Generate a path from egg_base back to '.' where the\n        setup script resides and ensure that path points to the\n        setup path from $install_dir/$egg_path.\n        \"\"\"\n        path_to_setup = egg_base.replace(os.sep, '/').rstrip('/')\n        if path_to_setup != os.curdir:\n            path_to_setup = '../' * (path_to_setup.count('/') + 1)\n        resolved = pkg_resources.normalize_path(\n            os.path.join(install_dir, egg_path, path_to_setup)\n        )\n        if resolved != pkg_resources.normalize_path(os.curdir):\n            raise DistutilsOptionError(\n                \"Can't get a consistent path to setup script from\"\n                \" installation directory\",\n                resolved,\n                pkg_resources.normalize_path(os.curdir),\n            )\n        return path_to_setup\n\n    def install_for_development(self):\n        self.run_command('egg_info')\n\n        # Build extensions in-place\n        self.reinitialize_command('build_ext', inplace=1)\n        self.run_command('build_ext')\n\n        if setuptools.bootstrap_install_from:\n            self.easy_install(setuptools.bootstrap_install_from)\n            setuptools.bootstrap_install_from = None\n\n        self.install_namespaces()\n\n        # create an .egg-link in the installation dir, pointing to our egg\n        log.info(\"Creating %s (link to %s)\", self.egg_link, self.egg_base)\n        if not self.dry_run:\n            with open(self.egg_link, \"w\") as f:\n                f.write(self.egg_path + \"\\n\" + self.setup_path)\n        # postprocess the installed distro, fixing up .pth, installing scripts,\n        # and handling requirements\n        self.process_distribution(None, self.dist, not self.no_deps)\n\n    def uninstall_link(self):\n        if os.path.exists(self.egg_link):\n            log.info(\"Removing %s (link to %s)\", self.egg_link, self.egg_base)\n            egg_link_file = open(self.egg_link)\n            contents = [line.rstrip() for line in egg_link_file]\n            egg_link_file.close()\n            if contents not in ([self.egg_path], [self.egg_path, self.setup_path]):\n                log.warn(\"Link points to %s: uninstall aborted\", contents)\n                return\n            if not self.dry_run:\n                os.unlink(self.egg_link)\n        if not self.dry_run:\n            self.update_pth(self.dist)  # remove any .pth link to us\n        if self.distribution.scripts:\n            # XXX should also check for entry point scripts!\n            log.warn(\"Note: you must uninstall or replace scripts manually!\")\n\n    def install_egg_scripts(self, dist):\n        if dist is not self.dist:\n            # Installing a dependency, so fall back to normal behavior\n            return easy_install.install_egg_scripts(self, dist)\n\n        # create wrapper scripts in the script dir, pointing to dist.scripts\n\n        # new-style...\n        self.install_wrapper_scripts(dist)\n\n        # ...and old-style\n        for script_name in self.distribution.scripts or []:\n            script_path = os.path.abspath(convert_path(script_name))\n            script_name = os.path.basename(script_path)\n            with io.open(script_path) as strm:\n                script_text = strm.read()\n            self.install_script(dist, script_name, script_text, script_path)\n\n    def install_wrapper_scripts(self, dist):\n        dist = VersionlessRequirement(dist)\n        return easy_install.install_wrapper_scripts(self, dist)\n\n\nclass VersionlessRequirement:\n    \"\"\"\n    Adapt a pkg_resources.Distribution to simply return the project\n    name as the 'requirement' so that scripts will work across\n    multiple versions.\n\n    >>> from pkg_resources import Distribution\n    >>> dist = Distribution(project_name='foo', version='1.0')\n    >>> str(dist.as_requirement())\n    'foo==1.0'\n    >>> adapted_dist = VersionlessRequirement(dist)\n    >>> str(adapted_dist.as_requirement())\n    'foo'\n    \"\"\"\n\n    def __init__(self, dist):\n        self.__dist = dist\n\n    def __getattr__(self, name):\n        return getattr(self.__dist, name)\n\n    def as_requirement(self):\n        return self.project_name\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/dist_info.py",
    "content": "\"\"\"\nCreate a dist_info directory\nAs defined in the wheel specification\n\"\"\"\n\nimport os\nimport re\nimport shutil\nimport sys\nimport warnings\nfrom contextlib import contextmanager\nfrom inspect import cleandoc\nfrom pathlib import Path\n\nfrom distutils.core import Command\nfrom distutils import log\nfrom setuptools.extern import packaging\nfrom setuptools._deprecation_warning import SetuptoolsDeprecationWarning\n\n\nclass dist_info(Command):\n\n    description = 'create a .dist-info directory'\n\n    user_options = [\n        ('egg-base=', 'e', \"directory containing .egg-info directories\"\n                           \" (default: top of the source tree)\"\n                           \" DEPRECATED: use --output-dir.\"),\n        ('output-dir=', 'o', \"directory inside of which the .dist-info will be\"\n                             \"created (default: top of the source tree)\"),\n        ('tag-date', 'd', \"Add date stamp (e.g. 20050528) to version number\"),\n        ('tag-build=', 'b', \"Specify explicit tag to add to version number\"),\n        ('no-date', 'D', \"Don't include date stamp [default]\"),\n        ('keep-egg-info', None, \"*TRANSITIONAL* will be removed in the future\"),\n    ]\n\n    boolean_options = ['tag-date', 'keep-egg-info']\n    negative_opt = {'no-date': 'tag-date'}\n\n    def initialize_options(self):\n        self.egg_base = None\n        self.output_dir = None\n        self.name = None\n        self.dist_info_dir = None\n        self.tag_date = None\n        self.tag_build = None\n        self.keep_egg_info = False\n\n    def finalize_options(self):\n        if self.egg_base:\n            msg = \"--egg-base is deprecated for dist_info command. Use --output-dir.\"\n            warnings.warn(msg, SetuptoolsDeprecationWarning)\n            self.output_dir = self.egg_base or self.output_dir\n\n        dist = self.distribution\n        project_dir = dist.src_root or os.curdir\n        self.output_dir = Path(self.output_dir or project_dir)\n\n        egg_info = self.reinitialize_command(\"egg_info\")\n        egg_info.egg_base = str(self.output_dir)\n\n        if self.tag_date:\n            egg_info.tag_date = self.tag_date\n        else:\n            self.tag_date = egg_info.tag_date\n\n        if self.tag_build:\n            egg_info.tag_build = self.tag_build\n        else:\n            self.tag_build = egg_info.tag_build\n\n        egg_info.finalize_options()\n        self.egg_info = egg_info\n\n        name = _safe(dist.get_name())\n        version = _version(dist.get_version())\n        self.name = f\"{name}-{version}\"\n        self.dist_info_dir = os.path.join(self.output_dir, f\"{self.name}.dist-info\")\n\n    @contextmanager\n    def _maybe_bkp_dir(self, dir_path: str, requires_bkp: bool):\n        if requires_bkp:\n            bkp_name = f\"{dir_path}.__bkp__\"\n            _rm(bkp_name, ignore_errors=True)\n            _copy(dir_path, bkp_name, dirs_exist_ok=True, symlinks=True)\n            try:\n                yield\n            finally:\n                _rm(dir_path, ignore_errors=True)\n                shutil.move(bkp_name, dir_path)\n        else:\n            yield\n\n    def run(self):\n        self.output_dir.mkdir(parents=True, exist_ok=True)\n        self.egg_info.run()\n        egg_info_dir = self.egg_info.egg_info\n        assert os.path.isdir(egg_info_dir), \".egg-info dir should have been created\"\n\n        log.info(\"creating '{}'\".format(os.path.abspath(self.dist_info_dir)))\n        bdist_wheel = self.get_finalized_command('bdist_wheel')\n\n        # TODO: if bdist_wheel if merged into setuptools, just add \"keep_egg_info\" there\n        with self._maybe_bkp_dir(egg_info_dir, self.keep_egg_info):\n            bdist_wheel.egg2dist(egg_info_dir, self.dist_info_dir)\n\n\ndef _safe(component: str) -> str:\n    \"\"\"Escape a component used to form a wheel name according to PEP 491\"\"\"\n    return re.sub(r\"[^\\w\\d.]+\", \"_\", component)\n\n\ndef _version(version: str) -> str:\n    \"\"\"Convert an arbitrary string to a version string.\"\"\"\n    v = version.replace(' ', '.')\n    try:\n        return str(packaging.version.Version(v)).replace(\"-\", \"_\")\n    except packaging.version.InvalidVersion:\n        msg = f\"\"\"Invalid version: {version!r}.\n        !!\\n\\n\n        ###################\n        # Invalid version #\n        ###################\n        {version!r} is not valid according to PEP 440.\\n\n        Please make sure specify a valid version for your package.\n        Also note that future releases of setuptools may halt the build process\n        if an invalid version is given.\n        \\n\\n!!\n        \"\"\"\n        warnings.warn(cleandoc(msg))\n        return _safe(v).strip(\"_\")\n\n\ndef _rm(dir_name, **opts):\n    if os.path.isdir(dir_name):\n        shutil.rmtree(dir_name, **opts)\n\n\ndef _copy(src, dst, **opts):\n    if sys.version_info < (3, 8):\n        opts.pop(\"dirs_exist_ok\", None)\n    shutil.copytree(src, dst, **opts)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/easy_install.py",
    "content": "\"\"\"\nEasy Install\n------------\n\nA tool for doing automatic download/extract/build of distutils-based Python\npackages.  For detailed documentation, see the accompanying EasyInstall.txt\nfile, or visit the `EasyInstall home page`__.\n\n__ https://setuptools.pypa.io/en/latest/deprecated/easy_install.html\n\n\"\"\"\n\nfrom glob import glob\nfrom distutils.util import get_platform\nfrom distutils.util import convert_path, subst_vars\nfrom distutils.errors import (\n    DistutilsArgError, DistutilsOptionError,\n    DistutilsError, DistutilsPlatformError,\n)\nfrom distutils import log, dir_util\nfrom distutils.command.build_scripts import first_line_re\nfrom distutils.spawn import find_executable\nfrom distutils.command import install\nimport sys\nimport os\nimport zipimport\nimport shutil\nimport tempfile\nimport zipfile\nimport re\nimport stat\nimport random\nimport textwrap\nimport warnings\nimport site\nimport struct\nimport contextlib\nimport subprocess\nimport shlex\nimport io\nimport configparser\nimport sysconfig\n\n\nfrom sysconfig import get_path\n\nfrom setuptools import SetuptoolsDeprecationWarning\n\nfrom setuptools import Command\nfrom setuptools.sandbox import run_setup\nfrom setuptools.command import setopt\nfrom setuptools.archive_util import unpack_archive\nfrom setuptools.package_index import (\n    PackageIndex, parse_requirement_arg, URL_SCHEME,\n)\nfrom setuptools.command import bdist_egg, egg_info\nfrom setuptools.wheel import Wheel\nfrom pkg_resources import (\n    normalize_path, resource_string,\n    get_distribution, find_distributions, Environment, Requirement,\n    Distribution, PathMetadata, EggMetadata, WorkingSet, DistributionNotFound,\n    VersionConflict, DEVELOP_DIST,\n)\nimport pkg_resources\nfrom .._path import ensure_directory\nfrom ..extern.jaraco.text import yield_lines\n\n\n# Turn on PEP440Warnings\nwarnings.filterwarnings(\"default\", category=pkg_resources.PEP440Warning)\n\n__all__ = [\n    'easy_install', 'PthDistributions', 'extract_wininst_cfg',\n    'get_exe_prefixes',\n]\n\n\ndef is_64bit():\n    return struct.calcsize(\"P\") == 8\n\n\ndef _to_bytes(s):\n    return s.encode('utf8')\n\n\ndef isascii(s):\n    try:\n        s.encode('ascii')\n        return True\n    except UnicodeError:\n        return False\n\n\ndef _one_liner(text):\n    return textwrap.dedent(text).strip().replace('\\n', '; ')\n\n\nclass easy_install(Command):\n    \"\"\"Manage a download/build/install process\"\"\"\n    description = \"Find/get/install Python packages\"\n    command_consumes_arguments = True\n\n    user_options = [\n        ('prefix=', None, \"installation prefix\"),\n        (\"zip-ok\", \"z\", \"install package as a zipfile\"),\n        (\"multi-version\", \"m\", \"make apps have to require() a version\"),\n        (\"upgrade\", \"U\", \"force upgrade (searches PyPI for latest versions)\"),\n        (\"install-dir=\", \"d\", \"install package to DIR\"),\n        (\"script-dir=\", \"s\", \"install scripts to DIR\"),\n        (\"exclude-scripts\", \"x\", \"Don't install scripts\"),\n        (\"always-copy\", \"a\", \"Copy all needed packages to install dir\"),\n        (\"index-url=\", \"i\", \"base URL of Python Package Index\"),\n        (\"find-links=\", \"f\", \"additional URL(s) to search for packages\"),\n        (\"build-directory=\", \"b\",\n         \"download/extract/build in DIR; keep the results\"),\n        ('optimize=', 'O',\n         \"also compile with optimization: -O1 for \\\"python -O\\\", \"\n         \"-O2 for \\\"python -OO\\\", and -O0 to disable [default: -O0]\"),\n        ('record=', None,\n         \"filename in which to record list of installed files\"),\n        ('always-unzip', 'Z', \"don't install as a zipfile, no matter what\"),\n        ('site-dirs=', 'S', \"list of directories where .pth files work\"),\n        ('editable', 'e', \"Install specified packages in editable form\"),\n        ('no-deps', 'N', \"don't install dependencies\"),\n        ('allow-hosts=', 'H', \"pattern(s) that hostnames must match\"),\n        ('local-snapshots-ok', 'l',\n         \"allow building eggs from local checkouts\"),\n        ('version', None, \"print version information and exit\"),\n        ('no-find-links', None,\n         \"Don't load find-links defined in packages being installed\"),\n        ('user', None, \"install in user site-package '%s'\" % site.USER_SITE)\n    ]\n    boolean_options = [\n        'zip-ok', 'multi-version', 'exclude-scripts', 'upgrade', 'always-copy',\n        'editable',\n        'no-deps', 'local-snapshots-ok', 'version',\n        'user'\n    ]\n\n    negative_opt = {'always-unzip': 'zip-ok'}\n    create_index = PackageIndex\n\n    def initialize_options(self):\n        warnings.warn(\n            \"easy_install command is deprecated. \"\n            \"Use build and pip and other standards-based tools.\",\n            EasyInstallDeprecationWarning,\n        )\n\n        # the --user option seems to be an opt-in one,\n        # so the default should be False.\n        self.user = 0\n        self.zip_ok = self.local_snapshots_ok = None\n        self.install_dir = self.script_dir = self.exclude_scripts = None\n        self.index_url = None\n        self.find_links = None\n        self.build_directory = None\n        self.args = None\n        self.optimize = self.record = None\n        self.upgrade = self.always_copy = self.multi_version = None\n        self.editable = self.no_deps = self.allow_hosts = None\n        self.root = self.prefix = self.no_report = None\n        self.version = None\n        self.install_purelib = None  # for pure module distributions\n        self.install_platlib = None  # non-pure (dists w/ extensions)\n        self.install_headers = None  # for C/C++ headers\n        self.install_lib = None  # set to either purelib or platlib\n        self.install_scripts = None\n        self.install_data = None\n        self.install_base = None\n        self.install_platbase = None\n        self.install_userbase = site.USER_BASE\n        self.install_usersite = site.USER_SITE\n        self.no_find_links = None\n\n        # Options not specifiable via command line\n        self.package_index = None\n        self.pth_file = self.always_copy_from = None\n        self.site_dirs = None\n        self.installed_projects = {}\n        # Always read easy_install options, even if we are subclassed, or have\n        # an independent instance created.  This ensures that defaults will\n        # always come from the standard configuration file(s)' \"easy_install\"\n        # section, even if this is a \"develop\" or \"install\" command, or some\n        # other embedding.\n        self._dry_run = None\n        self.verbose = self.distribution.verbose\n        self.distribution._set_command_options(\n            self, self.distribution.get_option_dict('easy_install')\n        )\n\n    def delete_blockers(self, blockers):\n        extant_blockers = (\n            filename for filename in blockers\n            if os.path.exists(filename) or os.path.islink(filename)\n        )\n        list(map(self._delete_path, extant_blockers))\n\n    def _delete_path(self, path):\n        log.info(\"Deleting %s\", path)\n        if self.dry_run:\n            return\n\n        is_tree = os.path.isdir(path) and not os.path.islink(path)\n        remover = rmtree if is_tree else os.unlink\n        remover(path)\n\n    @staticmethod\n    def _render_version():\n        \"\"\"\n        Render the Setuptools version and installation details, then exit.\n        \"\"\"\n        ver = '{}.{}'.format(*sys.version_info)\n        dist = get_distribution('setuptools')\n        tmpl = 'setuptools {dist.version} from {dist.location} (Python {ver})'\n        print(tmpl.format(**locals()))\n        raise SystemExit()\n\n    def finalize_options(self):  # noqa: C901  # is too complex (25)  # FIXME\n        self.version and self._render_version()\n\n        py_version = sys.version.split()[0]\n\n        self.config_vars = dict(sysconfig.get_config_vars())\n\n        self.config_vars.update({\n            'dist_name': self.distribution.get_name(),\n            'dist_version': self.distribution.get_version(),\n            'dist_fullname': self.distribution.get_fullname(),\n            'py_version': py_version,\n            'py_version_short': f'{sys.version_info.major}.{sys.version_info.minor}',\n            'py_version_nodot': f'{sys.version_info.major}{sys.version_info.minor}',\n            'sys_prefix': self.config_vars['prefix'],\n            'sys_exec_prefix': self.config_vars['exec_prefix'],\n            # Only python 3.2+ has abiflags\n            'abiflags': getattr(sys, 'abiflags', ''),\n            'platlibdir': getattr(sys, 'platlibdir', 'lib'),\n        })\n        with contextlib.suppress(AttributeError):\n            # only for distutils outside stdlib\n            self.config_vars.update({\n                'implementation_lower': install._get_implementation().lower(),\n                'implementation': install._get_implementation(),\n            })\n\n        # pypa/distutils#113 Python 3.9 compat\n        self.config_vars.setdefault(\n            'py_version_nodot_plat',\n            getattr(sys, 'windir', '').replace('.', ''),\n        )\n\n        self.config_vars['userbase'] = self.install_userbase\n        self.config_vars['usersite'] = self.install_usersite\n        if self.user and not site.ENABLE_USER_SITE:\n            log.warn(\"WARNING: The user site-packages directory is disabled.\")\n\n        self._fix_install_dir_for_user_site()\n\n        self.expand_basedirs()\n        self.expand_dirs()\n\n        self._expand(\n            'install_dir', 'script_dir', 'build_directory',\n            'site_dirs',\n        )\n        # If a non-default installation directory was specified, default the\n        # script directory to match it.\n        if self.script_dir is None:\n            self.script_dir = self.install_dir\n\n        if self.no_find_links is None:\n            self.no_find_links = False\n\n        # Let install_dir get set by install_lib command, which in turn\n        # gets its info from the install command, and takes into account\n        # --prefix and --home and all that other crud.\n        self.set_undefined_options(\n            'install_lib', ('install_dir', 'install_dir')\n        )\n        # Likewise, set default script_dir from 'install_scripts.install_dir'\n        self.set_undefined_options(\n            'install_scripts', ('install_dir', 'script_dir')\n        )\n\n        if self.user and self.install_purelib:\n            self.install_dir = self.install_purelib\n            self.script_dir = self.install_scripts\n        # default --record from the install command\n        self.set_undefined_options('install', ('record', 'record'))\n        self.all_site_dirs = get_site_dirs()\n        self.all_site_dirs.extend(self._process_site_dirs(self.site_dirs))\n\n        if not self.editable:\n            self.check_site_dir()\n        default_index = os.getenv(\"__EASYINSTALL_INDEX\", \"https://pypi.org/simple/\")\n        # ^ Private API for testing purposes only\n        self.index_url = self.index_url or default_index\n        self.shadow_path = self.all_site_dirs[:]\n        for path_item in self.install_dir, normalize_path(self.script_dir):\n            if path_item not in self.shadow_path:\n                self.shadow_path.insert(0, path_item)\n\n        if self.allow_hosts is not None:\n            hosts = [s.strip() for s in self.allow_hosts.split(',')]\n        else:\n            hosts = ['*']\n        if self.package_index is None:\n            self.package_index = self.create_index(\n                self.index_url, search_path=self.shadow_path, hosts=hosts,\n            )\n        self.local_index = Environment(self.shadow_path + sys.path)\n\n        if self.find_links is not None:\n            if isinstance(self.find_links, str):\n                self.find_links = self.find_links.split()\n        else:\n            self.find_links = []\n        if self.local_snapshots_ok:\n            self.package_index.scan_egg_links(self.shadow_path + sys.path)\n        if not self.no_find_links:\n            self.package_index.add_find_links(self.find_links)\n        self.set_undefined_options('install_lib', ('optimize', 'optimize'))\n        self.optimize = self._validate_optimize(self.optimize)\n\n        if self.editable and not self.build_directory:\n            raise DistutilsArgError(\n                \"Must specify a build directory (-b) when using --editable\"\n            )\n        if not self.args:\n            raise DistutilsArgError(\n                \"No urls, filenames, or requirements specified (see --help)\")\n\n        self.outputs = []\n\n    @staticmethod\n    def _process_site_dirs(site_dirs):\n        if site_dirs is None:\n            return\n\n        normpath = map(normalize_path, sys.path)\n        site_dirs = [\n            os.path.expanduser(s.strip()) for s in\n            site_dirs.split(',')\n        ]\n        for d in site_dirs:\n            if not os.path.isdir(d):\n                log.warn(\"%s (in --site-dirs) does not exist\", d)\n            elif normalize_path(d) not in normpath:\n                raise DistutilsOptionError(\n                    d + \" (in --site-dirs) is not on sys.path\"\n                )\n            else:\n                yield normalize_path(d)\n\n    @staticmethod\n    def _validate_optimize(value):\n        try:\n            value = int(value)\n            if value not in range(3):\n                raise ValueError\n        except ValueError as e:\n            raise DistutilsOptionError(\n                \"--optimize must be 0, 1, or 2\"\n            ) from e\n\n        return value\n\n    def _fix_install_dir_for_user_site(self):\n        \"\"\"\n        Fix the install_dir if \"--user\" was used.\n        \"\"\"\n        if not self.user:\n            return\n\n        self.create_home_path()\n        if self.install_userbase is None:\n            msg = \"User base directory is not specified\"\n            raise DistutilsPlatformError(msg)\n        self.install_base = self.install_platbase = self.install_userbase\n        scheme_name = f'{os.name}_user'\n        self.select_scheme(scheme_name)\n\n    def _expand_attrs(self, attrs):\n        for attr in attrs:\n            val = getattr(self, attr)\n            if val is not None:\n                if os.name == 'posix' or os.name == 'nt':\n                    val = os.path.expanduser(val)\n                val = subst_vars(val, self.config_vars)\n                setattr(self, attr, val)\n\n    def expand_basedirs(self):\n        \"\"\"Calls `os.path.expanduser` on install_base, install_platbase and\n        root.\"\"\"\n        self._expand_attrs(['install_base', 'install_platbase', 'root'])\n\n    def expand_dirs(self):\n        \"\"\"Calls `os.path.expanduser` on install dirs.\"\"\"\n        dirs = [\n            'install_purelib',\n            'install_platlib',\n            'install_lib',\n            'install_headers',\n            'install_scripts',\n            'install_data',\n        ]\n        self._expand_attrs(dirs)\n\n    def run(self, show_deprecation=True):\n        if show_deprecation:\n            self.announce(\n                \"WARNING: The easy_install command is deprecated \"\n                \"and will be removed in a future version.\",\n                log.WARN,\n            )\n        if self.verbose != self.distribution.verbose:\n            log.set_verbosity(self.verbose)\n        try:\n            for spec in self.args:\n                self.easy_install(spec, not self.no_deps)\n            if self.record:\n                outputs = self.outputs\n                if self.root:  # strip any package prefix\n                    root_len = len(self.root)\n                    for counter in range(len(outputs)):\n                        outputs[counter] = outputs[counter][root_len:]\n                from distutils import file_util\n\n                self.execute(\n                    file_util.write_file, (self.record, outputs),\n                    \"writing list of installed files to '%s'\" %\n                    self.record\n                )\n            self.warn_deprecated_options()\n        finally:\n            log.set_verbosity(self.distribution.verbose)\n\n    def pseudo_tempname(self):\n        \"\"\"Return a pseudo-tempname base in the install directory.\n        This code is intentionally naive; if a malicious party can write to\n        the target directory you're already in deep doodoo.\n        \"\"\"\n        try:\n            pid = os.getpid()\n        except Exception:\n            pid = random.randint(0, sys.maxsize)\n        return os.path.join(self.install_dir, \"test-easy-install-%s\" % pid)\n\n    def warn_deprecated_options(self):\n        pass\n\n    def check_site_dir(self):  # noqa: C901  # is too complex (12)  # FIXME\n        \"\"\"Verify that self.install_dir is .pth-capable dir, if needed\"\"\"\n\n        instdir = normalize_path(self.install_dir)\n        pth_file = os.path.join(instdir, 'easy-install.pth')\n\n        if not os.path.exists(instdir):\n            try:\n                os.makedirs(instdir)\n            except (OSError, IOError):\n                self.cant_write_to_target()\n\n        # Is it a configured, PYTHONPATH, implicit, or explicit site dir?\n        is_site_dir = instdir in self.all_site_dirs\n\n        if not is_site_dir and not self.multi_version:\n            # No?  Then directly test whether it does .pth file processing\n            is_site_dir = self.check_pth_processing()\n        else:\n            # make sure we can write to target dir\n            testfile = self.pseudo_tempname() + '.write-test'\n            test_exists = os.path.exists(testfile)\n            try:\n                if test_exists:\n                    os.unlink(testfile)\n                open(testfile, 'w').close()\n                os.unlink(testfile)\n            except (OSError, IOError):\n                self.cant_write_to_target()\n\n        if not is_site_dir and not self.multi_version:\n            # Can't install non-multi to non-site dir with easy_install\n            pythonpath = os.environ.get('PYTHONPATH', '')\n            log.warn(self.__no_default_msg, self.install_dir, pythonpath)\n\n        if is_site_dir:\n            if self.pth_file is None:\n                self.pth_file = PthDistributions(pth_file, self.all_site_dirs)\n        else:\n            self.pth_file = None\n\n        if self.multi_version and not os.path.exists(pth_file):\n            self.pth_file = None  # don't create a .pth file\n        self.install_dir = instdir\n\n    __cant_write_msg = textwrap.dedent(\"\"\"\n        can't create or remove files in install directory\n\n        The following error occurred while trying to add or remove files in the\n        installation directory:\n\n            %s\n\n        The installation directory you specified (via --install-dir, --prefix, or\n        the distutils default setting) was:\n\n            %s\n        \"\"\").lstrip()  # noqa\n\n    __not_exists_id = textwrap.dedent(\"\"\"\n        This directory does not currently exist.  Please create it and try again, or\n        choose a different installation directory (using the -d or --install-dir\n        option).\n        \"\"\").lstrip()  # noqa\n\n    __access_msg = textwrap.dedent(\"\"\"\n        Perhaps your account does not have write access to this directory?  If the\n        installation directory is a system-owned directory, you may need to sign in\n        as the administrator or \"root\" account.  If you do not have administrative\n        access to this machine, you may wish to choose a different installation\n        directory, preferably one that is listed in your PYTHONPATH environment\n        variable.\n\n        For information on other options, you may wish to consult the\n        documentation at:\n\n          https://setuptools.pypa.io/en/latest/deprecated/easy_install.html\n\n        Please make the appropriate changes for your system and try again.\n        \"\"\").lstrip()  # noqa\n\n    def cant_write_to_target(self):\n        msg = self.__cant_write_msg % (sys.exc_info()[1], self.install_dir,)\n\n        if not os.path.exists(self.install_dir):\n            msg += '\\n' + self.__not_exists_id\n        else:\n            msg += '\\n' + self.__access_msg\n        raise DistutilsError(msg)\n\n    def check_pth_processing(self):\n        \"\"\"Empirically verify whether .pth files are supported in inst. dir\"\"\"\n        instdir = self.install_dir\n        log.info(\"Checking .pth file support in %s\", instdir)\n        pth_file = self.pseudo_tempname() + \".pth\"\n        ok_file = pth_file + '.ok'\n        ok_exists = os.path.exists(ok_file)\n        tmpl = _one_liner(\"\"\"\n            import os\n            f = open({ok_file!r}, 'w')\n            f.write('OK')\n            f.close()\n            \"\"\") + '\\n'\n        try:\n            if ok_exists:\n                os.unlink(ok_file)\n            dirname = os.path.dirname(ok_file)\n            os.makedirs(dirname, exist_ok=True)\n            f = open(pth_file, 'w')\n        except (OSError, IOError):\n            self.cant_write_to_target()\n        else:\n            try:\n                f.write(tmpl.format(**locals()))\n                f.close()\n                f = None\n                executable = sys.executable\n                if os.name == 'nt':\n                    dirname, basename = os.path.split(executable)\n                    alt = os.path.join(dirname, 'pythonw.exe')\n                    use_alt = (\n                        basename.lower() == 'python.exe' and\n                        os.path.exists(alt)\n                    )\n                    if use_alt:\n                        # use pythonw.exe to avoid opening a console window\n                        executable = alt\n\n                from distutils.spawn import spawn\n\n                spawn([executable, '-E', '-c', 'pass'], 0)\n\n                if os.path.exists(ok_file):\n                    log.info(\n                        \"TEST PASSED: %s appears to support .pth files\",\n                        instdir\n                    )\n                    return True\n            finally:\n                if f:\n                    f.close()\n                if os.path.exists(ok_file):\n                    os.unlink(ok_file)\n                if os.path.exists(pth_file):\n                    os.unlink(pth_file)\n        if not self.multi_version:\n            log.warn(\"TEST FAILED: %s does NOT support .pth files\", instdir)\n        return False\n\n    def install_egg_scripts(self, dist):\n        \"\"\"Write all the scripts for `dist`, unless scripts are excluded\"\"\"\n        if not self.exclude_scripts and dist.metadata_isdir('scripts'):\n            for script_name in dist.metadata_listdir('scripts'):\n                if dist.metadata_isdir('scripts/' + script_name):\n                    # The \"script\" is a directory, likely a Python 3\n                    # __pycache__ directory, so skip it.\n                    continue\n                self.install_script(\n                    dist, script_name,\n                    dist.get_metadata('scripts/' + script_name)\n                )\n        self.install_wrapper_scripts(dist)\n\n    def add_output(self, path):\n        if os.path.isdir(path):\n            for base, dirs, files in os.walk(path):\n                for filename in files:\n                    self.outputs.append(os.path.join(base, filename))\n        else:\n            self.outputs.append(path)\n\n    def not_editable(self, spec):\n        if self.editable:\n            raise DistutilsArgError(\n                \"Invalid argument %r: you can't use filenames or URLs \"\n                \"with --editable (except via the --find-links option).\"\n                % (spec,)\n            )\n\n    def check_editable(self, spec):\n        if not self.editable:\n            return\n\n        if os.path.exists(os.path.join(self.build_directory, spec.key)):\n            raise DistutilsArgError(\n                \"%r already exists in %s; can't do a checkout there\" %\n                (spec.key, self.build_directory)\n            )\n\n    @contextlib.contextmanager\n    def _tmpdir(self):\n        tmpdir = tempfile.mkdtemp(prefix=u\"easy_install-\")\n        try:\n            # cast to str as workaround for #709 and #710 and #712\n            yield str(tmpdir)\n        finally:\n            os.path.exists(tmpdir) and rmtree(tmpdir)\n\n    def easy_install(self, spec, deps=False):\n        with self._tmpdir() as tmpdir:\n            if not isinstance(spec, Requirement):\n                if URL_SCHEME(spec):\n                    # It's a url, download it to tmpdir and process\n                    self.not_editable(spec)\n                    dl = self.package_index.download(spec, tmpdir)\n                    return self.install_item(None, dl, tmpdir, deps, True)\n\n                elif os.path.exists(spec):\n                    # Existing file or directory, just process it directly\n                    self.not_editable(spec)\n                    return self.install_item(None, spec, tmpdir, deps, True)\n                else:\n                    spec = parse_requirement_arg(spec)\n\n            self.check_editable(spec)\n            dist = self.package_index.fetch_distribution(\n                spec, tmpdir, self.upgrade, self.editable,\n                not self.always_copy, self.local_index\n            )\n            if dist is None:\n                msg = \"Could not find suitable distribution for %r\" % spec\n                if self.always_copy:\n                    msg += \" (--always-copy skips system and development eggs)\"\n                raise DistutilsError(msg)\n            elif dist.precedence == DEVELOP_DIST:\n                # .egg-info dists don't need installing, just process deps\n                self.process_distribution(spec, dist, deps, \"Using\")\n                return dist\n            else:\n                return self.install_item(spec, dist.location, tmpdir, deps)\n\n    def install_item(self, spec, download, tmpdir, deps, install_needed=False):\n\n        # Installation is also needed if file in tmpdir or is not an egg\n        install_needed = install_needed or self.always_copy\n        install_needed = install_needed or os.path.dirname(download) == tmpdir\n        install_needed = install_needed or not download.endswith('.egg')\n        install_needed = install_needed or (\n            self.always_copy_from is not None and\n            os.path.dirname(normalize_path(download)) ==\n            normalize_path(self.always_copy_from)\n        )\n\n        if spec and not install_needed:\n            # at this point, we know it's a local .egg, we just don't know if\n            # it's already installed.\n            for dist in self.local_index[spec.project_name]:\n                if dist.location == download:\n                    break\n            else:\n                install_needed = True  # it's not in the local index\n\n        log.info(\"Processing %s\", os.path.basename(download))\n\n        if install_needed:\n            dists = self.install_eggs(spec, download, tmpdir)\n            for dist in dists:\n                self.process_distribution(spec, dist, deps)\n        else:\n            dists = [self.egg_distribution(download)]\n            self.process_distribution(spec, dists[0], deps, \"Using\")\n\n        if spec is not None:\n            for dist in dists:\n                if dist in spec:\n                    return dist\n\n    def select_scheme(self, name):\n        try:\n            install._select_scheme(self, name)\n        except AttributeError:\n            # stdlib distutils\n            install.install.select_scheme(self, name.replace('posix', 'unix'))\n\n    # FIXME: 'easy_install.process_distribution' is too complex (12)\n    def process_distribution(  # noqa: C901\n            self, requirement, dist, deps=True, *info,\n    ):\n        self.update_pth(dist)\n        self.package_index.add(dist)\n        if dist in self.local_index[dist.key]:\n            self.local_index.remove(dist)\n        self.local_index.add(dist)\n        self.install_egg_scripts(dist)\n        self.installed_projects[dist.key] = dist\n        log.info(self.installation_report(requirement, dist, *info))\n        if (dist.has_metadata('dependency_links.txt') and\n                not self.no_find_links):\n            self.package_index.add_find_links(\n                dist.get_metadata_lines('dependency_links.txt')\n            )\n        if not deps and not self.always_copy:\n            return\n        elif requirement is not None and dist.key != requirement.key:\n            log.warn(\"Skipping dependencies for %s\", dist)\n            return  # XXX this is not the distribution we were looking for\n        elif requirement is None or dist not in requirement:\n            # if we wound up with a different version, resolve what we've got\n            distreq = dist.as_requirement()\n            requirement = Requirement(str(distreq))\n        log.info(\"Processing dependencies for %s\", requirement)\n        try:\n            distros = WorkingSet([]).resolve(\n                [requirement], self.local_index, self.easy_install\n            )\n        except DistributionNotFound as e:\n            raise DistutilsError(str(e)) from e\n        except VersionConflict as e:\n            raise DistutilsError(e.report()) from e\n        if self.always_copy or self.always_copy_from:\n            # Force all the relevant distros to be copied or activated\n            for dist in distros:\n                if dist.key not in self.installed_projects:\n                    self.easy_install(dist.as_requirement())\n        log.info(\"Finished processing dependencies for %s\", requirement)\n\n    def should_unzip(self, dist):\n        if self.zip_ok is not None:\n            return not self.zip_ok\n        if dist.has_metadata('not-zip-safe'):\n            return True\n        if not dist.has_metadata('zip-safe'):\n            return True\n        return False\n\n    def maybe_move(self, spec, dist_filename, setup_base):\n        dst = os.path.join(self.build_directory, spec.key)\n        if os.path.exists(dst):\n            msg = (\n                \"%r already exists in %s; build directory %s will not be kept\"\n            )\n            log.warn(msg, spec.key, self.build_directory, setup_base)\n            return setup_base\n        if os.path.isdir(dist_filename):\n            setup_base = dist_filename\n        else:\n            if os.path.dirname(dist_filename) == setup_base:\n                os.unlink(dist_filename)  # get it out of the tmp dir\n            contents = os.listdir(setup_base)\n            if len(contents) == 1:\n                dist_filename = os.path.join(setup_base, contents[0])\n                if os.path.isdir(dist_filename):\n                    # if the only thing there is a directory, move it instead\n                    setup_base = dist_filename\n        ensure_directory(dst)\n        shutil.move(setup_base, dst)\n        return dst\n\n    def install_wrapper_scripts(self, dist):\n        if self.exclude_scripts:\n            return\n        for args in ScriptWriter.best().get_args(dist):\n            self.write_script(*args)\n\n    def install_script(self, dist, script_name, script_text, dev_path=None):\n        \"\"\"Generate a legacy script wrapper and install it\"\"\"\n        spec = str(dist.as_requirement())\n        is_script = is_python_script(script_text, script_name)\n\n        if is_script:\n            body = self._load_template(dev_path) % locals()\n            script_text = ScriptWriter.get_header(script_text) + body\n        self.write_script(script_name, _to_bytes(script_text), 'b')\n\n    @staticmethod\n    def _load_template(dev_path):\n        \"\"\"\n        There are a couple of template scripts in the package. This\n        function loads one of them and prepares it for use.\n        \"\"\"\n        # See https://github.com/pypa/setuptools/issues/134 for info\n        # on script file naming and downstream issues with SVR4\n        name = 'script.tmpl'\n        if dev_path:\n            name = name.replace('.tmpl', ' (dev).tmpl')\n\n        raw_bytes = resource_string('setuptools', name)\n        return raw_bytes.decode('utf-8')\n\n    def write_script(self, script_name, contents, mode=\"t\", blockers=()):\n        \"\"\"Write an executable file to the scripts directory\"\"\"\n        self.delete_blockers(  # clean up old .py/.pyw w/o a script\n            [os.path.join(self.script_dir, x) for x in blockers]\n        )\n        log.info(\"Installing %s script to %s\", script_name, self.script_dir)\n        target = os.path.join(self.script_dir, script_name)\n        self.add_output(target)\n\n        if self.dry_run:\n            return\n\n        mask = current_umask()\n        ensure_directory(target)\n        if os.path.exists(target):\n            os.unlink(target)\n        with open(target, \"w\" + mode) as f:\n            f.write(contents)\n        chmod(target, 0o777 - mask)\n\n    def install_eggs(self, spec, dist_filename, tmpdir):\n        # .egg dirs or files are already built, so just return them\n        installer_map = {\n            '.egg': self.install_egg,\n            '.exe': self.install_exe,\n            '.whl': self.install_wheel,\n        }\n        try:\n            install_dist = installer_map[\n                dist_filename.lower()[-4:]\n            ]\n        except KeyError:\n            pass\n        else:\n            return [install_dist(dist_filename, tmpdir)]\n\n        # Anything else, try to extract and build\n        setup_base = tmpdir\n        if os.path.isfile(dist_filename) and not dist_filename.endswith('.py'):\n            unpack_archive(dist_filename, tmpdir, self.unpack_progress)\n        elif os.path.isdir(dist_filename):\n            setup_base = os.path.abspath(dist_filename)\n\n        if (setup_base.startswith(tmpdir)  # something we downloaded\n                and self.build_directory and spec is not None):\n            setup_base = self.maybe_move(spec, dist_filename, setup_base)\n\n        # Find the setup.py file\n        setup_script = os.path.join(setup_base, 'setup.py')\n\n        if not os.path.exists(setup_script):\n            setups = glob(os.path.join(setup_base, '*', 'setup.py'))\n            if not setups:\n                raise DistutilsError(\n                    \"Couldn't find a setup script in %s\" %\n                    os.path.abspath(dist_filename)\n                )\n            if len(setups) > 1:\n                raise DistutilsError(\n                    \"Multiple setup scripts in %s\" %\n                    os.path.abspath(dist_filename)\n                )\n            setup_script = setups[0]\n\n        # Now run it, and return the result\n        if self.editable:\n            log.info(self.report_editable(spec, setup_script))\n            return []\n        else:\n            return self.build_and_install(setup_script, setup_base)\n\n    def egg_distribution(self, egg_path):\n        if os.path.isdir(egg_path):\n            metadata = PathMetadata(egg_path, os.path.join(egg_path,\n                                                           'EGG-INFO'))\n        else:\n            metadata = EggMetadata(zipimport.zipimporter(egg_path))\n        return Distribution.from_filename(egg_path, metadata=metadata)\n\n    # FIXME: 'easy_install.install_egg' is too complex (11)\n    def install_egg(self, egg_path, tmpdir):  # noqa: C901\n        destination = os.path.join(\n            self.install_dir,\n            os.path.basename(egg_path),\n        )\n        destination = os.path.abspath(destination)\n        if not self.dry_run:\n            ensure_directory(destination)\n\n        dist = self.egg_distribution(egg_path)\n        if not (\n            os.path.exists(destination) and os.path.samefile(egg_path, destination)\n        ):\n            if os.path.isdir(destination) and not os.path.islink(destination):\n                dir_util.remove_tree(destination, dry_run=self.dry_run)\n            elif os.path.exists(destination):\n                self.execute(\n                    os.unlink,\n                    (destination,),\n                    \"Removing \" + destination,\n                )\n            try:\n                new_dist_is_zipped = False\n                if os.path.isdir(egg_path):\n                    if egg_path.startswith(tmpdir):\n                        f, m = shutil.move, \"Moving\"\n                    else:\n                        f, m = shutil.copytree, \"Copying\"\n                elif self.should_unzip(dist):\n                    self.mkpath(destination)\n                    f, m = self.unpack_and_compile, \"Extracting\"\n                else:\n                    new_dist_is_zipped = True\n                    if egg_path.startswith(tmpdir):\n                        f, m = shutil.move, \"Moving\"\n                    else:\n                        f, m = shutil.copy2, \"Copying\"\n                self.execute(\n                    f,\n                    (egg_path, destination),\n                    (m + \" %s to %s\") % (\n                        os.path.basename(egg_path),\n                        os.path.dirname(destination)\n                    ),\n                )\n                update_dist_caches(\n                    destination,\n                    fix_zipimporter_caches=new_dist_is_zipped,\n                )\n            except Exception:\n                update_dist_caches(destination, fix_zipimporter_caches=False)\n                raise\n\n        self.add_output(destination)\n        return self.egg_distribution(destination)\n\n    def install_exe(self, dist_filename, tmpdir):\n        # See if it's valid, get data\n        cfg = extract_wininst_cfg(dist_filename)\n        if cfg is None:\n            raise DistutilsError(\n                \"%s is not a valid distutils Windows .exe\" % dist_filename\n            )\n        # Create a dummy distribution object until we build the real distro\n        dist = Distribution(\n            None,\n            project_name=cfg.get('metadata', 'name'),\n            version=cfg.get('metadata', 'version'), platform=get_platform(),\n        )\n\n        # Convert the .exe to an unpacked egg\n        egg_path = os.path.join(tmpdir, dist.egg_name() + '.egg')\n        dist.location = egg_path\n        egg_tmp = egg_path + '.tmp'\n        _egg_info = os.path.join(egg_tmp, 'EGG-INFO')\n        pkg_inf = os.path.join(_egg_info, 'PKG-INFO')\n        ensure_directory(pkg_inf)  # make sure EGG-INFO dir exists\n        dist._provider = PathMetadata(egg_tmp, _egg_info)  # XXX\n        self.exe_to_egg(dist_filename, egg_tmp)\n\n        # Write EGG-INFO/PKG-INFO\n        if not os.path.exists(pkg_inf):\n            f = open(pkg_inf, 'w')\n            f.write('Metadata-Version: 1.0\\n')\n            for k, v in cfg.items('metadata'):\n                if k != 'target_version':\n                    f.write('%s: %s\\n' % (k.replace('_', '-').title(), v))\n            f.close()\n        script_dir = os.path.join(_egg_info, 'scripts')\n        # delete entry-point scripts to avoid duping\n        self.delete_blockers([\n            os.path.join(script_dir, args[0])\n            for args in ScriptWriter.get_args(dist)\n        ])\n        # Build .egg file from tmpdir\n        bdist_egg.make_zipfile(\n            egg_path, egg_tmp, verbose=self.verbose, dry_run=self.dry_run,\n        )\n        # install the .egg\n        return self.install_egg(egg_path, tmpdir)\n\n    # FIXME: 'easy_install.exe_to_egg' is too complex (12)\n    def exe_to_egg(self, dist_filename, egg_tmp):  # noqa: C901\n        \"\"\"Extract a bdist_wininst to the directories an egg would use\"\"\"\n        # Check for .pth file and set up prefix translations\n        prefixes = get_exe_prefixes(dist_filename)\n        to_compile = []\n        native_libs = []\n        top_level = {}\n\n        def process(src, dst):\n            s = src.lower()\n            for old, new in prefixes:\n                if s.startswith(old):\n                    src = new + src[len(old):]\n                    parts = src.split('/')\n                    dst = os.path.join(egg_tmp, *parts)\n                    dl = dst.lower()\n                    if dl.endswith('.pyd') or dl.endswith('.dll'):\n                        parts[-1] = bdist_egg.strip_module(parts[-1])\n                        top_level[os.path.splitext(parts[0])[0]] = 1\n                        native_libs.append(src)\n                    elif dl.endswith('.py') and old != 'SCRIPTS/':\n                        top_level[os.path.splitext(parts[0])[0]] = 1\n                        to_compile.append(dst)\n                    return dst\n            if not src.endswith('.pth'):\n                log.warn(\"WARNING: can't process %s\", src)\n            return None\n\n        # extract, tracking .pyd/.dll->native_libs and .py -> to_compile\n        unpack_archive(dist_filename, egg_tmp, process)\n        stubs = []\n        for res in native_libs:\n            if res.lower().endswith('.pyd'):  # create stubs for .pyd's\n                parts = res.split('/')\n                resource = parts[-1]\n                parts[-1] = bdist_egg.strip_module(parts[-1]) + '.py'\n                pyfile = os.path.join(egg_tmp, *parts)\n                to_compile.append(pyfile)\n                stubs.append(pyfile)\n                bdist_egg.write_stub(resource, pyfile)\n        self.byte_compile(to_compile)  # compile .py's\n        bdist_egg.write_safety_flag(\n            os.path.join(egg_tmp, 'EGG-INFO'),\n            bdist_egg.analyze_egg(egg_tmp, stubs))  # write zip-safety flag\n\n        for name in 'top_level', 'native_libs':\n            if locals()[name]:\n                txt = os.path.join(egg_tmp, 'EGG-INFO', name + '.txt')\n                if not os.path.exists(txt):\n                    f = open(txt, 'w')\n                    f.write('\\n'.join(locals()[name]) + '\\n')\n                    f.close()\n\n    def install_wheel(self, wheel_path, tmpdir):\n        wheel = Wheel(wheel_path)\n        assert wheel.is_compatible()\n        destination = os.path.join(self.install_dir, wheel.egg_name())\n        destination = os.path.abspath(destination)\n        if not self.dry_run:\n            ensure_directory(destination)\n        if os.path.isdir(destination) and not os.path.islink(destination):\n            dir_util.remove_tree(destination, dry_run=self.dry_run)\n        elif os.path.exists(destination):\n            self.execute(\n                os.unlink,\n                (destination,),\n                \"Removing \" + destination,\n            )\n        try:\n            self.execute(\n                wheel.install_as_egg,\n                (destination,),\n                (\"Installing %s to %s\") % (\n                    os.path.basename(wheel_path),\n                    os.path.dirname(destination)\n                ),\n            )\n        finally:\n            update_dist_caches(destination, fix_zipimporter_caches=False)\n        self.add_output(destination)\n        return self.egg_distribution(destination)\n\n    __mv_warning = textwrap.dedent(\"\"\"\n        Because this distribution was installed --multi-version, before you can\n        import modules from this package in an application, you will need to\n        'import pkg_resources' and then use a 'require()' call similar to one of\n        these examples, in order to select the desired version:\n\n            pkg_resources.require(\"%(name)s\")  # latest installed version\n            pkg_resources.require(\"%(name)s==%(version)s\")  # this exact version\n            pkg_resources.require(\"%(name)s>=%(version)s\")  # this version or higher\n        \"\"\").lstrip()  # noqa\n\n    __id_warning = textwrap.dedent(\"\"\"\n        Note also that the installation directory must be on sys.path at runtime for\n        this to work.  (e.g. by being the application's script directory, by being on\n        PYTHONPATH, or by being added to sys.path by your code.)\n        \"\"\")  # noqa\n\n    def installation_report(self, req, dist, what=\"Installed\"):\n        \"\"\"Helpful installation message for display to package users\"\"\"\n        msg = \"\\n%(what)s %(eggloc)s%(extras)s\"\n        if self.multi_version and not self.no_report:\n            msg += '\\n' + self.__mv_warning\n            if self.install_dir not in map(normalize_path, sys.path):\n                msg += '\\n' + self.__id_warning\n\n        eggloc = dist.location\n        name = dist.project_name\n        version = dist.version\n        extras = ''  # TODO: self.report_extras(req, dist)\n        return msg % locals()\n\n    __editable_msg = textwrap.dedent(\"\"\"\n        Extracted editable version of %(spec)s to %(dirname)s\n\n        If it uses setuptools in its setup script, you can activate it in\n        \"development\" mode by going to that directory and running::\n\n            %(python)s setup.py develop\n\n        See the setuptools documentation for the \"develop\" command for more info.\n        \"\"\").lstrip()  # noqa\n\n    def report_editable(self, spec, setup_script):\n        dirname = os.path.dirname(setup_script)\n        python = sys.executable\n        return '\\n' + self.__editable_msg % locals()\n\n    def run_setup(self, setup_script, setup_base, args):\n        sys.modules.setdefault('distutils.command.bdist_egg', bdist_egg)\n        sys.modules.setdefault('distutils.command.egg_info', egg_info)\n\n        args = list(args)\n        if self.verbose > 2:\n            v = 'v' * (self.verbose - 1)\n            args.insert(0, '-' + v)\n        elif self.verbose < 2:\n            args.insert(0, '-q')\n        if self.dry_run:\n            args.insert(0, '-n')\n        log.info(\n            \"Running %s %s\", setup_script[len(setup_base) + 1:], ' '.join(args)\n        )\n        try:\n            run_setup(setup_script, args)\n        except SystemExit as v:\n            raise DistutilsError(\n                \"Setup script exited with %s\" % (v.args[0],)\n            ) from v\n\n    def build_and_install(self, setup_script, setup_base):\n        args = ['bdist_egg', '--dist-dir']\n\n        dist_dir = tempfile.mkdtemp(\n            prefix='egg-dist-tmp-', dir=os.path.dirname(setup_script)\n        )\n        try:\n            self._set_fetcher_options(os.path.dirname(setup_script))\n            args.append(dist_dir)\n\n            self.run_setup(setup_script, setup_base, args)\n            all_eggs = Environment([dist_dir])\n            eggs = []\n            for key in all_eggs:\n                for dist in all_eggs[key]:\n                    eggs.append(self.install_egg(dist.location, setup_base))\n            if not eggs and not self.dry_run:\n                log.warn(\"No eggs found in %s (setup script problem?)\",\n                         dist_dir)\n            return eggs\n        finally:\n            rmtree(dist_dir)\n            log.set_verbosity(self.verbose)  # restore our log verbosity\n\n    def _set_fetcher_options(self, base):\n        \"\"\"\n        When easy_install is about to run bdist_egg on a source dist, that\n        source dist might have 'setup_requires' directives, requiring\n        additional fetching. Ensure the fetcher options given to easy_install\n        are available to that command as well.\n        \"\"\"\n        # find the fetch options from easy_install and write them out\n        # to the setup.cfg file.\n        ei_opts = self.distribution.get_option_dict('easy_install').copy()\n        fetch_directives = (\n            'find_links', 'site_dirs', 'index_url', 'optimize', 'allow_hosts',\n        )\n        fetch_options = {}\n        for key, val in ei_opts.items():\n            if key not in fetch_directives:\n                continue\n            fetch_options[key] = val[1]\n        # create a settings dictionary suitable for `edit_config`\n        settings = dict(easy_install=fetch_options)\n        cfg_filename = os.path.join(base, 'setup.cfg')\n        setopt.edit_config(cfg_filename, settings)\n\n    def update_pth(self, dist):  # noqa: C901  # is too complex (11)  # FIXME\n        if self.pth_file is None:\n            return\n\n        for d in self.pth_file[dist.key]:  # drop old entries\n            if not self.multi_version and d.location == dist.location:\n                continue\n\n            log.info(\"Removing %s from easy-install.pth file\", d)\n            self.pth_file.remove(d)\n            if d.location in self.shadow_path:\n                self.shadow_path.remove(d.location)\n\n        if not self.multi_version:\n            if dist.location in self.pth_file.paths:\n                log.info(\n                    \"%s is already the active version in easy-install.pth\",\n                    dist,\n                )\n            else:\n                log.info(\"Adding %s to easy-install.pth file\", dist)\n                self.pth_file.add(dist)  # add new entry\n                if dist.location not in self.shadow_path:\n                    self.shadow_path.append(dist.location)\n\n        if self.dry_run:\n            return\n\n        self.pth_file.save()\n\n        if dist.key != 'setuptools':\n            return\n\n        # Ensure that setuptools itself never becomes unavailable!\n        # XXX should this check for latest version?\n        filename = os.path.join(self.install_dir, 'setuptools.pth')\n        if os.path.islink(filename):\n            os.unlink(filename)\n        with open(filename, 'wt') as f:\n            f.write(self.pth_file.make_relative(dist.location) + '\\n')\n\n    def unpack_progress(self, src, dst):\n        # Progress filter for unpacking\n        log.debug(\"Unpacking %s to %s\", src, dst)\n        return dst  # only unpack-and-compile skips files for dry run\n\n    def unpack_and_compile(self, egg_path, destination):\n        to_compile = []\n        to_chmod = []\n\n        def pf(src, dst):\n            if dst.endswith('.py') and not src.startswith('EGG-INFO/'):\n                to_compile.append(dst)\n            elif dst.endswith('.dll') or dst.endswith('.so'):\n                to_chmod.append(dst)\n            self.unpack_progress(src, dst)\n            return not self.dry_run and dst or None\n\n        unpack_archive(egg_path, destination, pf)\n        self.byte_compile(to_compile)\n        if not self.dry_run:\n            for f in to_chmod:\n                mode = ((os.stat(f)[stat.ST_MODE]) | 0o555) & 0o7755\n                chmod(f, mode)\n\n    def byte_compile(self, to_compile):\n        if sys.dont_write_bytecode:\n            return\n\n        from distutils.util import byte_compile\n\n        try:\n            # try to make the byte compile messages quieter\n            log.set_verbosity(self.verbose - 1)\n\n            byte_compile(to_compile, optimize=0, force=1, dry_run=self.dry_run)\n            if self.optimize:\n                byte_compile(\n                    to_compile, optimize=self.optimize, force=1,\n                    dry_run=self.dry_run,\n                )\n        finally:\n            log.set_verbosity(self.verbose)  # restore original verbosity\n\n    __no_default_msg = textwrap.dedent(\"\"\"\n        bad install directory or PYTHONPATH\n\n        You are attempting to install a package to a directory that is not\n        on PYTHONPATH and which Python does not read \".pth\" files from.  The\n        installation directory you specified (via --install-dir, --prefix, or\n        the distutils default setting) was:\n\n            %s\n\n        and your PYTHONPATH environment variable currently contains:\n\n            %r\n\n        Here are some of your options for correcting the problem:\n\n        * You can choose a different installation directory, i.e., one that is\n          on PYTHONPATH or supports .pth files\n\n        * You can add the installation directory to the PYTHONPATH environment\n          variable.  (It must then also be on PYTHONPATH whenever you run\n          Python and want to use the package(s) you are installing.)\n\n        * You can set up the installation directory to support \".pth\" files by\n          using one of the approaches described here:\n\n          https://setuptools.pypa.io/en/latest/deprecated/easy_install.html#custom-installation-locations\n\n\n        Please make the appropriate changes for your system and try again.\n        \"\"\").strip()\n\n    def create_home_path(self):\n        \"\"\"Create directories under ~.\"\"\"\n        if not self.user:\n            return\n        home = convert_path(os.path.expanduser(\"~\"))\n        for path in only_strs(self.config_vars.values()):\n            if path.startswith(home) and not os.path.isdir(path):\n                self.debug_print(\"os.makedirs('%s', 0o700)\" % path)\n                os.makedirs(path, 0o700)\n\n    INSTALL_SCHEMES = dict(\n        posix=dict(\n            install_dir='$base/lib/python$py_version_short/site-packages',\n            script_dir='$base/bin',\n        ),\n    )\n\n    DEFAULT_SCHEME = dict(\n        install_dir='$base/Lib/site-packages',\n        script_dir='$base/Scripts',\n    )\n\n    def _expand(self, *attrs):\n        config_vars = self.get_finalized_command('install').config_vars\n\n        if self.prefix:\n            # Set default install_dir/scripts from --prefix\n            config_vars = dict(config_vars)\n            config_vars['base'] = self.prefix\n            scheme = self.INSTALL_SCHEMES.get(os.name, self.DEFAULT_SCHEME)\n            for attr, val in scheme.items():\n                if getattr(self, attr, None) is None:\n                    setattr(self, attr, val)\n\n        from distutils.util import subst_vars\n\n        for attr in attrs:\n            val = getattr(self, attr)\n            if val is not None:\n                val = subst_vars(val, config_vars)\n                if os.name == 'posix':\n                    val = os.path.expanduser(val)\n                setattr(self, attr, val)\n\n\ndef _pythonpath():\n    items = os.environ.get('PYTHONPATH', '').split(os.pathsep)\n    return filter(None, items)\n\n\ndef get_site_dirs():\n    \"\"\"\n    Return a list of 'site' dirs\n    \"\"\"\n\n    sitedirs = []\n\n    # start with PYTHONPATH\n    sitedirs.extend(_pythonpath())\n\n    prefixes = [sys.prefix]\n    if sys.exec_prefix != sys.prefix:\n        prefixes.append(sys.exec_prefix)\n    for prefix in prefixes:\n        if not prefix:\n            continue\n\n        if sys.platform in ('os2emx', 'riscos'):\n            sitedirs.append(os.path.join(prefix, \"Lib\", \"site-packages\"))\n        elif os.sep == '/':\n            sitedirs.extend([\n                os.path.join(\n                    prefix,\n                    \"lib\",\n                    \"python{}.{}\".format(*sys.version_info),\n                    \"site-packages\",\n                ),\n                os.path.join(prefix, \"lib\", \"site-python\"),\n            ])\n        else:\n            sitedirs.extend([\n                prefix,\n                os.path.join(prefix, \"lib\", \"site-packages\"),\n            ])\n        if sys.platform != 'darwin':\n            continue\n\n        # for framework builds *only* we add the standard Apple\n        # locations. Currently only per-user, but /Library and\n        # /Network/Library could be added too\n        if 'Python.framework' not in prefix:\n            continue\n\n        home = os.environ.get('HOME')\n        if not home:\n            continue\n\n        home_sp = os.path.join(\n            home,\n            'Library',\n            'Python',\n            '{}.{}'.format(*sys.version_info),\n            'site-packages',\n        )\n        sitedirs.append(home_sp)\n    lib_paths = get_path('purelib'), get_path('platlib')\n\n    sitedirs.extend(s for s in lib_paths if s not in sitedirs)\n\n    if site.ENABLE_USER_SITE:\n        sitedirs.append(site.USER_SITE)\n\n    with contextlib.suppress(AttributeError):\n        sitedirs.extend(site.getsitepackages())\n\n    sitedirs = list(map(normalize_path, sitedirs))\n\n    return sitedirs\n\n\ndef expand_paths(inputs):  # noqa: C901  # is too complex (11)  # FIXME\n    \"\"\"Yield sys.path directories that might contain \"old-style\" packages\"\"\"\n\n    seen = {}\n\n    for dirname in inputs:\n        dirname = normalize_path(dirname)\n        if dirname in seen:\n            continue\n\n        seen[dirname] = 1\n        if not os.path.isdir(dirname):\n            continue\n\n        files = os.listdir(dirname)\n        yield dirname, files\n\n        for name in files:\n            if not name.endswith('.pth'):\n                # We only care about the .pth files\n                continue\n            if name in ('easy-install.pth', 'setuptools.pth'):\n                # Ignore .pth files that we control\n                continue\n\n            # Read the .pth file\n            f = open(os.path.join(dirname, name))\n            lines = list(yield_lines(f))\n            f.close()\n\n            # Yield existing non-dupe, non-import directory lines from it\n            for line in lines:\n                if line.startswith(\"import\"):\n                    continue\n\n                line = normalize_path(line.rstrip())\n                if line in seen:\n                    continue\n\n                seen[line] = 1\n                if not os.path.isdir(line):\n                    continue\n\n                yield line, os.listdir(line)\n\n\ndef extract_wininst_cfg(dist_filename):\n    \"\"\"Extract configuration data from a bdist_wininst .exe\n\n    Returns a configparser.RawConfigParser, or None\n    \"\"\"\n    f = open(dist_filename, 'rb')\n    try:\n        endrec = zipfile._EndRecData(f)\n        if endrec is None:\n            return None\n\n        prepended = (endrec[9] - endrec[5]) - endrec[6]\n        if prepended < 12:  # no wininst data here\n            return None\n        f.seek(prepended - 12)\n\n        tag, cfglen, bmlen = struct.unpack(\"<iii\", f.read(12))\n        if tag not in (0x1234567A, 0x1234567B):\n            return None  # not a valid tag\n\n        f.seek(prepended - (12 + cfglen))\n        init = {'version': '', 'target_version': ''}\n        cfg = configparser.RawConfigParser(init)\n        try:\n            part = f.read(cfglen)\n            # Read up to the first null byte.\n            config = part.split(b'\\0', 1)[0]\n            # Now the config is in bytes, but for RawConfigParser, it should\n            #  be text, so decode it.\n            config = config.decode(sys.getfilesystemencoding())\n            cfg.read_file(io.StringIO(config))\n        except configparser.Error:\n            return None\n        if not cfg.has_section('metadata') or not cfg.has_section('Setup'):\n            return None\n        return cfg\n\n    finally:\n        f.close()\n\n\ndef get_exe_prefixes(exe_filename):\n    \"\"\"Get exe->egg path translations for a given .exe file\"\"\"\n\n    prefixes = [\n        ('PURELIB/', ''),\n        ('PLATLIB/pywin32_system32', ''),\n        ('PLATLIB/', ''),\n        ('SCRIPTS/', 'EGG-INFO/scripts/'),\n        ('DATA/lib/site-packages', ''),\n    ]\n    z = zipfile.ZipFile(exe_filename)\n    try:\n        for info in z.infolist():\n            name = info.filename\n            parts = name.split('/')\n            if len(parts) == 3 and parts[2] == 'PKG-INFO':\n                if parts[1].endswith('.egg-info'):\n                    prefixes.insert(0, ('/'.join(parts[:2]), 'EGG-INFO/'))\n                    break\n            if len(parts) != 2 or not name.endswith('.pth'):\n                continue\n            if name.endswith('-nspkg.pth'):\n                continue\n            if parts[0].upper() in ('PURELIB', 'PLATLIB'):\n                contents = z.read(name).decode()\n                for pth in yield_lines(contents):\n                    pth = pth.strip().replace('\\\\', '/')\n                    if not pth.startswith('import'):\n                        prefixes.append((('%s/%s/' % (parts[0], pth)), ''))\n    finally:\n        z.close()\n    prefixes = [(x.lower(), y) for x, y in prefixes]\n    prefixes.sort()\n    prefixes.reverse()\n    return prefixes\n\n\nclass PthDistributions(Environment):\n    \"\"\"A .pth file with Distribution paths in it\"\"\"\n\n    dirty = False\n\n    def __init__(self, filename, sitedirs=()):\n        self.filename = filename\n        self.sitedirs = list(map(normalize_path, sitedirs))\n        self.basedir = normalize_path(os.path.dirname(self.filename))\n        self._load()\n        super().__init__([], None, None)\n        for path in yield_lines(self.paths):\n            list(map(self.add, find_distributions(path, True)))\n\n    def _load(self):\n        self.paths = []\n        saw_import = False\n        seen = dict.fromkeys(self.sitedirs)\n        if os.path.isfile(self.filename):\n            f = open(self.filename, 'rt')\n            for line in f:\n                if line.startswith('import'):\n                    saw_import = True\n                    continue\n                path = line.rstrip()\n                self.paths.append(path)\n                if not path.strip() or path.strip().startswith('#'):\n                    continue\n                # skip non-existent paths, in case somebody deleted a package\n                # manually, and duplicate paths as well\n                path = self.paths[-1] = normalize_path(\n                    os.path.join(self.basedir, path)\n                )\n                if not os.path.exists(path) or path in seen:\n                    self.paths.pop()  # skip it\n                    self.dirty = True  # we cleaned up, so we're dirty now :)\n                    continue\n                seen[path] = 1\n            f.close()\n\n        if self.paths and not saw_import:\n            self.dirty = True  # ensure anything we touch has import wrappers\n        while self.paths and not self.paths[-1].strip():\n            self.paths.pop()\n\n    def save(self):\n        \"\"\"Write changed .pth file back to disk\"\"\"\n        if not self.dirty:\n            return\n\n        rel_paths = list(map(self.make_relative, self.paths))\n        if rel_paths:\n            log.debug(\"Saving %s\", self.filename)\n            lines = self._wrap_lines(rel_paths)\n            data = '\\n'.join(lines) + '\\n'\n\n            if os.path.islink(self.filename):\n                os.unlink(self.filename)\n            with open(self.filename, 'wt') as f:\n                f.write(data)\n\n        elif os.path.exists(self.filename):\n            log.debug(\"Deleting empty %s\", self.filename)\n            os.unlink(self.filename)\n\n        self.dirty = False\n\n    @staticmethod\n    def _wrap_lines(lines):\n        return lines\n\n    def add(self, dist):\n        \"\"\"Add `dist` to the distribution map\"\"\"\n        new_path = (\n            dist.location not in self.paths and (\n                dist.location not in self.sitedirs or\n                # account for '.' being in PYTHONPATH\n                dist.location == os.getcwd()\n            )\n        )\n        if new_path:\n            self.paths.append(dist.location)\n            self.dirty = True\n        super().add(dist)\n\n    def remove(self, dist):\n        \"\"\"Remove `dist` from the distribution map\"\"\"\n        while dist.location in self.paths:\n            self.paths.remove(dist.location)\n            self.dirty = True\n        super().remove(dist)\n\n    def make_relative(self, path):\n        npath, last = os.path.split(normalize_path(path))\n        baselen = len(self.basedir)\n        parts = [last]\n        sep = os.altsep == '/' and '/' or os.sep\n        while len(npath) >= baselen:\n            if npath == self.basedir:\n                parts.append(os.curdir)\n                parts.reverse()\n                return sep.join(parts)\n            npath, last = os.path.split(npath)\n            parts.append(last)\n        else:\n            return path\n\n\nclass RewritePthDistributions(PthDistributions):\n    @classmethod\n    def _wrap_lines(cls, lines):\n        yield cls.prelude\n        for line in lines:\n            yield line\n        yield cls.postlude\n\n    prelude = _one_liner(\"\"\"\n        import sys\n        sys.__plen = len(sys.path)\n        \"\"\")\n    postlude = _one_liner(\"\"\"\n        import sys\n        new = sys.path[sys.__plen:]\n        del sys.path[sys.__plen:]\n        p = getattr(sys, '__egginsert', 0)\n        sys.path[p:p] = new\n        sys.__egginsert = p + len(new)\n        \"\"\")\n\n\nif os.environ.get('SETUPTOOLS_SYS_PATH_TECHNIQUE', 'raw') == 'rewrite':\n    PthDistributions = RewritePthDistributions\n\n\ndef _first_line_re():\n    \"\"\"\n    Return a regular expression based on first_line_re suitable for matching\n    strings.\n    \"\"\"\n    if isinstance(first_line_re.pattern, str):\n        return first_line_re\n\n    # first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.\n    return re.compile(first_line_re.pattern.decode())\n\n\ndef auto_chmod(func, arg, exc):\n    if func in [os.unlink, os.remove] and os.name == 'nt':\n        chmod(arg, stat.S_IWRITE)\n        return func(arg)\n    et, ev, _ = sys.exc_info()\n    # TODO: This code doesn't make sense. What is it trying to do?\n    raise (ev[0], ev[1] + (\" %s %s\" % (func, arg)))\n\n\ndef update_dist_caches(dist_path, fix_zipimporter_caches):\n    \"\"\"\n    Fix any globally cached `dist_path` related data\n\n    `dist_path` should be a path of a newly installed egg distribution (zipped\n    or unzipped).\n\n    sys.path_importer_cache contains finder objects that have been cached when\n    importing data from the original distribution. Any such finders need to be\n    cleared since the replacement distribution might be packaged differently,\n    e.g. a zipped egg distribution might get replaced with an unzipped egg\n    folder or vice versa. Having the old finders cached may then cause Python\n    to attempt loading modules from the replacement distribution using an\n    incorrect loader.\n\n    zipimport.zipimporter objects are Python loaders charged with importing\n    data packaged inside zip archives. If stale loaders referencing the\n    original distribution, are left behind, they can fail to load modules from\n    the replacement distribution. E.g. if an old zipimport.zipimporter instance\n    is used to load data from a new zipped egg archive, it may cause the\n    operation to attempt to locate the requested data in the wrong location -\n    one indicated by the original distribution's zip archive directory\n    information. Such an operation may then fail outright, e.g. report having\n    read a 'bad local file header', or even worse, it may fail silently &\n    return invalid data.\n\n    zipimport._zip_directory_cache contains cached zip archive directory\n    information for all existing zipimport.zipimporter instances and all such\n    instances connected to the same archive share the same cached directory\n    information.\n\n    If asked, and the underlying Python implementation allows it, we can fix\n    all existing zipimport.zipimporter instances instead of having to track\n    them down and remove them one by one, by updating their shared cached zip\n    archive directory information. This, of course, assumes that the\n    replacement distribution is packaged as a zipped egg.\n\n    If not asked to fix existing zipimport.zipimporter instances, we still do\n    our best to clear any remaining zipimport.zipimporter related cached data\n    that might somehow later get used when attempting to load data from the new\n    distribution and thus cause such load operations to fail. Note that when\n    tracking down such remaining stale data, we can not catch every conceivable\n    usage from here, and we clear only those that we know of and have found to\n    cause problems if left alive. Any remaining caches should be updated by\n    whomever is in charge of maintaining them, i.e. they should be ready to\n    handle us replacing their zip archives with new distributions at runtime.\n\n    \"\"\"\n    # There are several other known sources of stale zipimport.zipimporter\n    # instances that we do not clear here, but might if ever given a reason to\n    # do so:\n    # * Global setuptools pkg_resources.working_set (a.k.a. 'master working\n    # set') may contain distributions which may in turn contain their\n    #   zipimport.zipimporter loaders.\n    # * Several zipimport.zipimporter loaders held by local variables further\n    #   up the function call stack when running the setuptools installation.\n    # * Already loaded modules may have their __loader__ attribute set to the\n    #   exact loader instance used when importing them. Python 3.4 docs state\n    #   that this information is intended mostly for introspection and so is\n    #   not expected to cause us problems.\n    normalized_path = normalize_path(dist_path)\n    _uncache(normalized_path, sys.path_importer_cache)\n    if fix_zipimporter_caches:\n        _replace_zip_directory_cache_data(normalized_path)\n    else:\n        # Here, even though we do not want to fix existing and now stale\n        # zipimporter cache information, we still want to remove it. Related to\n        # Python's zip archive directory information cache, we clear each of\n        # its stale entries in two phases:\n        #   1. Clear the entry so attempting to access zip archive information\n        #      via any existing stale zipimport.zipimporter instances fails.\n        #   2. Remove the entry from the cache so any newly constructed\n        #      zipimport.zipimporter instances do not end up using old stale\n        #      zip archive directory information.\n        # This whole stale data removal step does not seem strictly necessary,\n        # but has been left in because it was done before we started replacing\n        # the zip archive directory information cache content if possible, and\n        # there are no relevant unit tests that we can depend on to tell us if\n        # this is really needed.\n        _remove_and_clear_zip_directory_cache_data(normalized_path)\n\n\ndef _collect_zipimporter_cache_entries(normalized_path, cache):\n    \"\"\"\n    Return zipimporter cache entry keys related to a given normalized path.\n\n    Alternative path spellings (e.g. those using different character case or\n    those using alternative path separators) related to the same path are\n    included. Any sub-path entries are included as well, i.e. those\n    corresponding to zip archives embedded in other zip archives.\n\n    \"\"\"\n    result = []\n    prefix_len = len(normalized_path)\n    for p in cache:\n        np = normalize_path(p)\n        if (np.startswith(normalized_path) and\n                np[prefix_len:prefix_len + 1] in (os.sep, '')):\n            result.append(p)\n    return result\n\n\ndef _update_zipimporter_cache(normalized_path, cache, updater=None):\n    \"\"\"\n    Update zipimporter cache data for a given normalized path.\n\n    Any sub-path entries are processed as well, i.e. those corresponding to zip\n    archives embedded in other zip archives.\n\n    Given updater is a callable taking a cache entry key and the original entry\n    (after already removing the entry from the cache), and expected to update\n    the entry and possibly return a new one to be inserted in its place.\n    Returning None indicates that the entry should not be replaced with a new\n    one. If no updater is given, the cache entries are simply removed without\n    any additional processing, the same as if the updater simply returned None.\n\n    \"\"\"\n    for p in _collect_zipimporter_cache_entries(normalized_path, cache):\n        # N.B. pypy's custom zipimport._zip_directory_cache implementation does\n        # not support the complete dict interface:\n        # * Does not support item assignment, thus not allowing this function\n        #    to be used only for removing existing cache entries.\n        #  * Does not support the dict.pop() method, forcing us to use the\n        #    get/del patterns instead. For more detailed information see the\n        #    following links:\n        #      https://github.com/pypa/setuptools/issues/202#issuecomment-202913420\n        #      http://bit.ly/2h9itJX\n        old_entry = cache[p]\n        del cache[p]\n        new_entry = updater and updater(p, old_entry)\n        if new_entry is not None:\n            cache[p] = new_entry\n\n\ndef _uncache(normalized_path, cache):\n    _update_zipimporter_cache(normalized_path, cache)\n\n\ndef _remove_and_clear_zip_directory_cache_data(normalized_path):\n    def clear_and_remove_cached_zip_archive_directory_data(path, old_entry):\n        old_entry.clear()\n\n    _update_zipimporter_cache(\n        normalized_path, zipimport._zip_directory_cache,\n        updater=clear_and_remove_cached_zip_archive_directory_data)\n\n\n# PyPy Python implementation does not allow directly writing to the\n# zipimport._zip_directory_cache and so prevents us from attempting to correct\n# its content. The best we can do there is clear the problematic cache content\n# and have PyPy repopulate it as needed. The downside is that if there are any\n# stale zipimport.zipimporter instances laying around, attempting to use them\n# will fail due to not having its zip archive directory information available\n# instead of being automatically corrected to use the new correct zip archive\n# directory information.\nif '__pypy__' in sys.builtin_module_names:\n    _replace_zip_directory_cache_data = \\\n        _remove_and_clear_zip_directory_cache_data\nelse:\n\n    def _replace_zip_directory_cache_data(normalized_path):\n        def replace_cached_zip_archive_directory_data(path, old_entry):\n            # N.B. In theory, we could load the zip directory information just\n            # once for all updated path spellings, and then copy it locally and\n            # update its contained path strings to contain the correct\n            # spelling, but that seems like a way too invasive move (this cache\n            # structure is not officially documented anywhere and could in\n            # theory change with new Python releases) for no significant\n            # benefit.\n            old_entry.clear()\n            zipimport.zipimporter(path)\n            old_entry.update(zipimport._zip_directory_cache[path])\n            return old_entry\n\n        _update_zipimporter_cache(\n            normalized_path, zipimport._zip_directory_cache,\n            updater=replace_cached_zip_archive_directory_data)\n\n\ndef is_python(text, filename='<string>'):\n    \"Is this string a valid Python script?\"\n    try:\n        compile(text, filename, 'exec')\n    except (SyntaxError, TypeError):\n        return False\n    else:\n        return True\n\n\ndef is_sh(executable):\n    \"\"\"Determine if the specified executable is a .sh (contains a #! line)\"\"\"\n    try:\n        with io.open(executable, encoding='latin-1') as fp:\n            magic = fp.read(2)\n    except (OSError, IOError):\n        return executable\n    return magic == '#!'\n\n\ndef nt_quote_arg(arg):\n    \"\"\"Quote a command line argument according to Windows parsing rules\"\"\"\n    return subprocess.list2cmdline([arg])\n\n\ndef is_python_script(script_text, filename):\n    \"\"\"Is this text, as a whole, a Python script? (as opposed to shell/bat/etc.\n    \"\"\"\n    if filename.endswith('.py') or filename.endswith('.pyw'):\n        return True  # extension says it's Python\n    if is_python(script_text, filename):\n        return True  # it's syntactically valid Python\n    if script_text.startswith('#!'):\n        # It begins with a '#!' line, so check if 'python' is in it somewhere\n        return 'python' in script_text.splitlines()[0].lower()\n\n    return False  # Not any Python I can recognize\n\n\ntry:\n    from os import chmod as _chmod\nexcept ImportError:\n    # Jython compatibility\n    def _chmod(*args):\n        pass\n\n\ndef chmod(path, mode):\n    log.debug(\"changing mode of %s to %o\", path, mode)\n    try:\n        _chmod(path, mode)\n    except os.error as e:\n        log.debug(\"chmod failed: %s\", e)\n\n\nclass CommandSpec(list):\n    \"\"\"\n    A command spec for a #! header, specified as a list of arguments akin to\n    those passed to Popen.\n    \"\"\"\n\n    options = []\n    split_args = dict()\n\n    @classmethod\n    def best(cls):\n        \"\"\"\n        Choose the best CommandSpec class based on environmental conditions.\n        \"\"\"\n        return cls\n\n    @classmethod\n    def _sys_executable(cls):\n        _default = os.path.normpath(sys.executable)\n        return os.environ.get('__PYVENV_LAUNCHER__', _default)\n\n    @classmethod\n    def from_param(cls, param):\n        \"\"\"\n        Construct a CommandSpec from a parameter to build_scripts, which may\n        be None.\n        \"\"\"\n        if isinstance(param, cls):\n            return param\n        if isinstance(param, list):\n            return cls(param)\n        if param is None:\n            return cls.from_environment()\n        # otherwise, assume it's a string.\n        return cls.from_string(param)\n\n    @classmethod\n    def from_environment(cls):\n        return cls([cls._sys_executable()])\n\n    @classmethod\n    def from_string(cls, string):\n        \"\"\"\n        Construct a command spec from a simple string representing a command\n        line parseable by shlex.split.\n        \"\"\"\n        items = shlex.split(string, **cls.split_args)\n        return cls(items)\n\n    def install_options(self, script_text):\n        self.options = shlex.split(self._extract_options(script_text))\n        cmdline = subprocess.list2cmdline(self)\n        if not isascii(cmdline):\n            self.options[:0] = ['-x']\n\n    @staticmethod\n    def _extract_options(orig_script):\n        \"\"\"\n        Extract any options from the first line of the script.\n        \"\"\"\n        first = (orig_script + '\\n').splitlines()[0]\n        match = _first_line_re().match(first)\n        options = match.group(1) or '' if match else ''\n        return options.strip()\n\n    def as_header(self):\n        return self._render(self + list(self.options))\n\n    @staticmethod\n    def _strip_quotes(item):\n        _QUOTES = '\"\\''\n        for q in _QUOTES:\n            if item.startswith(q) and item.endswith(q):\n                return item[1:-1]\n        return item\n\n    @staticmethod\n    def _render(items):\n        cmdline = subprocess.list2cmdline(\n            CommandSpec._strip_quotes(item.strip()) for item in items)\n        return '#!' + cmdline + '\\n'\n\n\n# For pbr compat; will be removed in a future version.\nsys_executable = CommandSpec._sys_executable()\n\n\nclass WindowsCommandSpec(CommandSpec):\n    split_args = dict(posix=False)\n\n\nclass ScriptWriter:\n    \"\"\"\n    Encapsulates behavior around writing entry point scripts for console and\n    gui apps.\n    \"\"\"\n\n    template = textwrap.dedent(r\"\"\"\n        # EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r\n        import re\n        import sys\n\n        # for compatibility with easy_install; see #2198\n        __requires__ = %(spec)r\n\n        try:\n            from importlib.metadata import distribution\n        except ImportError:\n            try:\n                from importlib_metadata import distribution\n            except ImportError:\n                from pkg_resources import load_entry_point\n\n\n        def importlib_load_entry_point(spec, group, name):\n            dist_name, _, _ = spec.partition('==')\n            matches = (\n                entry_point\n                for entry_point in distribution(dist_name).entry_points\n                if entry_point.group == group and entry_point.name == name\n            )\n            return next(matches).load()\n\n\n        globals().setdefault('load_entry_point', importlib_load_entry_point)\n\n\n        if __name__ == '__main__':\n            sys.argv[0] = re.sub(r'(-script\\.pyw?|\\.exe)?$', '', sys.argv[0])\n            sys.exit(load_entry_point(%(spec)r, %(group)r, %(name)r)())\n        \"\"\").lstrip()\n\n    command_spec_class = CommandSpec\n\n    @classmethod\n    def get_script_args(cls, dist, executable=None, wininst=False):\n        # for backward compatibility\n        warnings.warn(\"Use get_args\", EasyInstallDeprecationWarning)\n        writer = (WindowsScriptWriter if wininst else ScriptWriter).best()\n        header = cls.get_script_header(\"\", executable, wininst)\n        return writer.get_args(dist, header)\n\n    @classmethod\n    def get_script_header(cls, script_text, executable=None, wininst=False):\n        # for backward compatibility\n        warnings.warn(\n            \"Use get_header\", EasyInstallDeprecationWarning, stacklevel=2)\n        if wininst:\n            executable = \"python.exe\"\n        return cls.get_header(script_text, executable)\n\n    @classmethod\n    def get_args(cls, dist, header=None):\n        \"\"\"\n        Yield write_script() argument tuples for a distribution's\n        console_scripts and gui_scripts entry points.\n        \"\"\"\n        if header is None:\n            header = cls.get_header()\n        spec = str(dist.as_requirement())\n        for type_ in 'console', 'gui':\n            group = type_ + '_scripts'\n            for name, ep in dist.get_entry_map(group).items():\n                cls._ensure_safe_name(name)\n                script_text = cls.template % locals()\n                args = cls._get_script_args(type_, name, header, script_text)\n                for res in args:\n                    yield res\n\n    @staticmethod\n    def _ensure_safe_name(name):\n        \"\"\"\n        Prevent paths in *_scripts entry point names.\n        \"\"\"\n        has_path_sep = re.search(r'[\\\\/]', name)\n        if has_path_sep:\n            raise ValueError(\"Path separators not allowed in script names\")\n\n    @classmethod\n    def get_writer(cls, force_windows):\n        # for backward compatibility\n        warnings.warn(\"Use best\", EasyInstallDeprecationWarning)\n        return WindowsScriptWriter.best() if force_windows else cls.best()\n\n    @classmethod\n    def best(cls):\n        \"\"\"\n        Select the best ScriptWriter for this environment.\n        \"\"\"\n        if sys.platform == 'win32' or (os.name == 'java' and os._name == 'nt'):\n            return WindowsScriptWriter.best()\n        else:\n            return cls\n\n    @classmethod\n    def _get_script_args(cls, type_, name, header, script_text):\n        # Simply write the stub with no extension.\n        yield (name, header + script_text)\n\n    @classmethod\n    def get_header(cls, script_text=\"\", executable=None):\n        \"\"\"Create a #! line, getting options (if any) from script_text\"\"\"\n        cmd = cls.command_spec_class.best().from_param(executable)\n        cmd.install_options(script_text)\n        return cmd.as_header()\n\n\nclass WindowsScriptWriter(ScriptWriter):\n    command_spec_class = WindowsCommandSpec\n\n    @classmethod\n    def get_writer(cls):\n        # for backward compatibility\n        warnings.warn(\"Use best\", EasyInstallDeprecationWarning)\n        return cls.best()\n\n    @classmethod\n    def best(cls):\n        \"\"\"\n        Select the best ScriptWriter suitable for Windows\n        \"\"\"\n        writer_lookup = dict(\n            executable=WindowsExecutableLauncherWriter,\n            natural=cls,\n        )\n        # for compatibility, use the executable launcher by default\n        launcher = os.environ.get('SETUPTOOLS_LAUNCHER', 'executable')\n        return writer_lookup[launcher]\n\n    @classmethod\n    def _get_script_args(cls, type_, name, header, script_text):\n        \"For Windows, add a .py extension\"\n        ext = dict(console='.pya', gui='.pyw')[type_]\n        if ext not in os.environ['PATHEXT'].lower().split(';'):\n            msg = (\n                \"{ext} not listed in PATHEXT; scripts will not be \"\n                \"recognized as executables.\"\n            ).format(**locals())\n            warnings.warn(msg, UserWarning)\n        old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe']\n        old.remove(ext)\n        header = cls._adjust_header(type_, header)\n        blockers = [name + x for x in old]\n        yield name + ext, header + script_text, 't', blockers\n\n    @classmethod\n    def _adjust_header(cls, type_, orig_header):\n        \"\"\"\n        Make sure 'pythonw' is used for gui and 'python' is used for\n        console (regardless of what sys.executable is).\n        \"\"\"\n        pattern = 'pythonw.exe'\n        repl = 'python.exe'\n        if type_ == 'gui':\n            pattern, repl = repl, pattern\n        pattern_ob = re.compile(re.escape(pattern), re.IGNORECASE)\n        new_header = pattern_ob.sub(string=orig_header, repl=repl)\n        return new_header if cls._use_header(new_header) else orig_header\n\n    @staticmethod\n    def _use_header(new_header):\n        \"\"\"\n        Should _adjust_header use the replaced header?\n\n        On non-windows systems, always use. On\n        Windows systems, only use the replaced header if it resolves\n        to an executable on the system.\n        \"\"\"\n        clean_header = new_header[2:-1].strip('\"')\n        return sys.platform != 'win32' or find_executable(clean_header)\n\n\nclass WindowsExecutableLauncherWriter(WindowsScriptWriter):\n    @classmethod\n    def _get_script_args(cls, type_, name, header, script_text):\n        \"\"\"\n        For Windows, add a .py extension and an .exe launcher\n        \"\"\"\n        if type_ == 'gui':\n            launcher_type = 'gui'\n            ext = '-script.pyw'\n            old = ['.pyw']\n        else:\n            launcher_type = 'cli'\n            ext = '-script.py'\n            old = ['.py', '.pyc', '.pyo']\n        hdr = cls._adjust_header(type_, header)\n        blockers = [name + x for x in old]\n        yield (name + ext, hdr + script_text, 't', blockers)\n        yield (\n            name + '.exe', get_win_launcher(launcher_type),\n            'b'  # write in binary mode\n        )\n        if not is_64bit():\n            # install a manifest for the launcher to prevent Windows\n            # from detecting it as an installer (which it will for\n            #  launchers like easy_install.exe). Consider only\n            #  adding a manifest for launchers detected as installers.\n            #  See Distribute #143 for details.\n            m_name = name + '.exe.manifest'\n            yield (m_name, load_launcher_manifest(name), 't')\n\n\n# for backward-compatibility\nget_script_args = ScriptWriter.get_script_args\nget_script_header = ScriptWriter.get_script_header\n\n\ndef get_win_launcher(type):\n    \"\"\"\n    Load the Windows launcher (executable) suitable for launching a script.\n\n    `type` should be either 'cli' or 'gui'\n\n    Returns the executable as a byte string.\n    \"\"\"\n    launcher_fn = '%s.exe' % type\n    if is_64bit():\n        if get_platform() == \"win-arm64\":\n            launcher_fn = launcher_fn.replace(\".\", \"-arm64.\")\n        else:\n            launcher_fn = launcher_fn.replace(\".\", \"-64.\")\n    else:\n        launcher_fn = launcher_fn.replace(\".\", \"-32.\")\n    return resource_string('setuptools', launcher_fn)\n\n\ndef load_launcher_manifest(name):\n    manifest = pkg_resources.resource_string(__name__, 'launcher manifest.xml')\n    return manifest.decode('utf-8') % vars()\n\n\ndef rmtree(path, ignore_errors=False, onerror=auto_chmod):\n    return shutil.rmtree(path, ignore_errors, onerror)\n\n\ndef current_umask():\n    tmp = os.umask(0o022)\n    os.umask(tmp)\n    return tmp\n\n\ndef only_strs(values):\n    \"\"\"\n    Exclude non-str values. Ref #3063.\n    \"\"\"\n    return filter(lambda val: isinstance(val, str), values)\n\n\nclass EasyInstallDeprecationWarning(SetuptoolsDeprecationWarning):\n    \"\"\"\n    Warning for EasyInstall deprecations, bypassing suppression.\n    \"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/editable_wheel.py",
    "content": "\"\"\"\nCreate a wheel that, when installed, will make the source package 'editable'\n(add it to the interpreter's path, including metadata) per PEP 660. Replaces\n'setup.py develop'.\n\n.. note::\n   One of the mechanisms briefly mentioned in PEP 660 to implement editable installs is\n   to create a separated directory inside ``build`` and use a .pth file to point to that\n   directory. In the context of this file such directory is referred as\n   *auxiliary build directory* or ``auxiliary_dir``.\n\"\"\"\n\nimport logging\nimport os\nimport re\nimport shutil\nimport sys\nimport traceback\nimport warnings\nfrom contextlib import suppress\nfrom enum import Enum\nfrom inspect import cleandoc\nfrom itertools import chain\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\nfrom typing import (\n    TYPE_CHECKING,\n    Dict,\n    Iterable,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n    Tuple,\n    TypeVar,\n    Union,\n)\n\nfrom setuptools import Command, SetuptoolsDeprecationWarning, errors, namespaces\nfrom setuptools.command.build_py import build_py as build_py_cls\nfrom setuptools.discovery import find_package_path\nfrom setuptools.dist import Distribution\n\nif TYPE_CHECKING:\n    from wheel.wheelfile import WheelFile  # noqa\n\nif sys.version_info >= (3, 8):\n    from typing import Protocol\nelif TYPE_CHECKING:\n    from typing_extensions import Protocol\nelse:\n    from abc import ABC as Protocol\n\n_Path = Union[str, Path]\n_P = TypeVar(\"_P\", bound=_Path)\n_logger = logging.getLogger(__name__)\n\n\nclass _EditableMode(Enum):\n    \"\"\"\n    Possible editable installation modes:\n    `lenient` (new files automatically added to the package - DEFAULT);\n    `strict` (requires a new installation when files are added/removed); or\n    `compat` (attempts to emulate `python setup.py develop` - DEPRECATED).\n    \"\"\"\n\n    STRICT = \"strict\"\n    LENIENT = \"lenient\"\n    COMPAT = \"compat\"  # TODO: Remove `compat` after Dec/2022.\n\n    @classmethod\n    def convert(cls, mode: Optional[str]) -> \"_EditableMode\":\n        if not mode:\n            return _EditableMode.LENIENT  # default\n\n        _mode = mode.upper()\n        if _mode not in _EditableMode.__members__:\n            raise errors.OptionError(f\"Invalid editable mode: {mode!r}. Try: 'strict'.\")\n\n        if _mode == \"COMPAT\":\n            msg = \"\"\"\n            The 'compat' editable mode is transitional and will be removed\n            in future versions of `setuptools`.\n            Please adapt your code accordingly to use either the 'strict' or the\n            'lenient' modes.\n\n            For more information, please check:\n            https://setuptools.pypa.io/en/latest/userguide/development_mode.html\n            \"\"\"\n            warnings.warn(msg, SetuptoolsDeprecationWarning)\n\n        return _EditableMode[_mode]\n\n\n_STRICT_WARNING = \"\"\"\nNew or renamed files may not be automatically picked up without a new installation.\n\"\"\"\n\n_LENIENT_WARNING = \"\"\"\nOptions like `package-data`, `include/exclude-package-data` or\n`packages.find.exclude/include` may have no effect.\n\"\"\"\n\n\nclass editable_wheel(Command):\n    \"\"\"Build 'editable' wheel for development.\n    (This command is reserved for internal use of setuptools).\n    \"\"\"\n\n    description = \"create a PEP 660 'editable' wheel\"\n\n    user_options = [\n        (\"dist-dir=\", \"d\", \"directory to put final built distributions in\"),\n        (\"dist-info-dir=\", \"I\", \"path to a pre-build .dist-info directory\"),\n        (\"mode=\", None, cleandoc(_EditableMode.__doc__ or \"\")),\n    ]\n\n    def initialize_options(self):\n        self.dist_dir = None\n        self.dist_info_dir = None\n        self.project_dir = None\n        self.mode = None\n\n    def finalize_options(self):\n        dist = self.distribution\n        self.project_dir = dist.src_root or os.curdir\n        self.package_dir = dist.package_dir or {}\n        self.dist_dir = Path(self.dist_dir or os.path.join(self.project_dir, \"dist\"))\n\n    def run(self):\n        try:\n            self.dist_dir.mkdir(exist_ok=True)\n            self._ensure_dist_info()\n\n            # Add missing dist_info files\n            self.reinitialize_command(\"bdist_wheel\")\n            bdist_wheel = self.get_finalized_command(\"bdist_wheel\")\n            bdist_wheel.write_wheelfile(self.dist_info_dir)\n\n            self._create_wheel_file(bdist_wheel)\n        except Exception as ex:\n            traceback.print_exc()\n            msg = \"\"\"\n            Support for editable installs via PEP 660 was recently introduced\n            in `setuptools`. If you are seeing this error, please report to:\n\n            https://github.com/pypa/setuptools/issues\n\n            Meanwhile you can try the legacy behavior by setting an\n            environment variable and trying to install again:\n\n            SETUPTOOLS_ENABLE_FEATURES=\"legacy-editable\"\n            \"\"\"\n            raise errors.InternalError(cleandoc(msg)) from ex\n\n    def _ensure_dist_info(self):\n        if self.dist_info_dir is None:\n            dist_info = self.reinitialize_command(\"dist_info\")\n            dist_info.output_dir = self.dist_dir\n            dist_info.ensure_finalized()\n            dist_info.run()\n            self.dist_info_dir = dist_info.dist_info_dir\n        else:\n            assert str(self.dist_info_dir).endswith(\".dist-info\")\n            assert Path(self.dist_info_dir, \"METADATA\").exists()\n\n    def _install_namespaces(self, installation_dir, pth_prefix):\n        # XXX: Only required to support the deprecated namespace practice\n        dist = self.distribution\n        if not dist.namespace_packages:\n            return\n\n        src_root = Path(self.project_dir, self.package_dir.get(\"\", \".\")).resolve()\n        installer = _NamespaceInstaller(dist, installation_dir, pth_prefix, src_root)\n        installer.install_namespaces()\n\n    def _find_egg_info_dir(self) -> Optional[str]:\n        parent_dir = Path(self.dist_info_dir).parent if self.dist_info_dir else Path()\n        candidates = map(str, parent_dir.glob(\"*.egg-info\"))\n        return next(candidates, None)\n\n    def _configure_build(\n        self, name: str, unpacked_wheel: _Path, build_lib: _Path, tmp_dir: _Path\n    ):\n        \"\"\"Configure commands to behave in the following ways:\n\n        - Build commands can write to ``build_lib`` if they really want to...\n          (but this folder is expected to be ignored and modules are expected to live\n          in the project directory...)\n        - Binary extensions should be built in-place (editable_mode = True)\n        - Data/header/script files are not part of the \"editable\" specification\n          so they are written directly to the unpacked_wheel directory.\n        \"\"\"\n        # Non-editable files (data, headers, scripts) are written directly to the\n        # unpacked_wheel\n\n        dist = self.distribution\n        wheel = str(unpacked_wheel)\n        build_lib = str(build_lib)\n        data = str(Path(unpacked_wheel, f\"{name}.data\", \"data\"))\n        headers = str(Path(unpacked_wheel, f\"{name}.data\", \"headers\"))\n        scripts = str(Path(unpacked_wheel, f\"{name}.data\", \"scripts\"))\n\n        # egg-info may be generated again to create a manifest (used for package data)\n        egg_info = dist.reinitialize_command(\"egg_info\", reinit_subcommands=True)\n        egg_info.egg_base = str(tmp_dir)\n        egg_info.ignore_egg_info_in_manifest = True\n\n        build = dist.reinitialize_command(\"build\", reinit_subcommands=True)\n        install = dist.reinitialize_command(\"install\", reinit_subcommands=True)\n\n        build.build_platlib = build.build_purelib = build.build_lib = build_lib\n        install.install_purelib = install.install_platlib = install.install_lib = wheel\n        install.install_scripts = build.build_scripts = scripts\n        install.install_headers = headers\n        install.install_data = data\n\n        install_scripts = dist.get_command_obj(\"install_scripts\")\n        install_scripts.no_ep = True\n\n        build.build_temp = str(tmp_dir)\n\n        build_py = dist.get_command_obj(\"build_py\")\n        build_py.compile = False\n        build_py.existing_egg_info_dir = self._find_egg_info_dir()\n\n        self._set_editable_mode()\n\n        build.ensure_finalized()\n        install.ensure_finalized()\n\n    def _set_editable_mode(self):\n        \"\"\"Set the ``editable_mode`` flag in the build sub-commands\"\"\"\n        dist = self.distribution\n        build = dist.get_command_obj(\"build\")\n        for cmd_name in build.get_sub_commands():\n            cmd = dist.get_command_obj(cmd_name)\n            if hasattr(cmd, \"editable_mode\"):\n                cmd.editable_mode = True\n            elif hasattr(cmd, \"inplace\"):\n                cmd.inplace = True  # backward compatibility with distutils\n\n    def _collect_build_outputs(self) -> Tuple[List[str], Dict[str, str]]:\n        files: List[str] = []\n        mapping: Dict[str, str] = {}\n        build = self.get_finalized_command(\"build\")\n\n        for cmd_name in build.get_sub_commands():\n            cmd = self.get_finalized_command(cmd_name)\n            if hasattr(cmd, \"get_outputs\"):\n                files.extend(cmd.get_outputs() or [])\n            if hasattr(cmd, \"get_output_mapping\"):\n                mapping.update(cmd.get_output_mapping() or {})\n\n        return files, mapping\n\n    def _run_build_commands(\n        self, dist_name: str, unpacked_wheel: _Path, build_lib: _Path, tmp_dir: _Path\n    ) -> Tuple[List[str], Dict[str, str]]:\n        self._configure_build(dist_name, unpacked_wheel, build_lib, tmp_dir)\n        self._run_build_subcommands()\n        files, mapping = self._collect_build_outputs()\n        self._run_install(\"headers\")\n        self._run_install(\"scripts\")\n        self._run_install(\"data\")\n        return files, mapping\n\n    def _run_build_subcommands(self):\n        \"\"\"\n        Issue #3501 indicates that some plugins/customizations might rely on:\n\n        1. ``build_py`` not running\n        2. ``build_py`` always copying files to ``build_lib``\n\n        However both these assumptions may be false in editable_wheel.\n        This method implements a temporary workaround to support the ecosystem\n        while the implementations catch up.\n        \"\"\"\n        # TODO: Once plugins/customisations had the chance to catch up, replace\n        #       `self._run_build_subcommands()` with `self.run_command(\"build\")`.\n        #       Also remove _safely_run, TestCustomBuildPy. Suggested date: Aug/2023.\n        build: Command = self.get_finalized_command(\"build\")\n        for name in build.get_sub_commands():\n            cmd = self.get_finalized_command(name)\n            if name == \"build_py\" and type(cmd) != build_py_cls:\n                self._safely_run(name)\n            else:\n                self.run_command(name)\n\n    def _safely_run(self, cmd_name: str):\n        try:\n            return self.run_command(cmd_name)\n        except Exception:\n            msg = f\"\"\"{traceback.format_exc()}\\n\n            If you are seeing this warning it is very likely that a setuptools\n            plugin or customization overrides the `{cmd_name}` command, without\n            taking into consideration how editable installs run build steps\n            starting from v64.0.0.\n\n            Plugin authors and developers relying on custom build steps are encouraged\n            to update their `{cmd_name}` implementation considering the information in\n            https://setuptools.pypa.io/en/latest/userguide/extension.html\n            about editable installs.\n\n            For the time being `setuptools` will silence this error and ignore\n            the faulty command, but this behaviour will change in future versions.\\n\n            \"\"\"\n            warnings.warn(msg, SetuptoolsDeprecationWarning, stacklevel=2)\n\n    def _create_wheel_file(self, bdist_wheel):\n        from wheel.wheelfile import WheelFile\n\n        dist_info = self.get_finalized_command(\"dist_info\")\n        dist_name = dist_info.name\n        tag = \"-\".join(bdist_wheel.get_tag())\n        build_tag = \"0.editable\"  # According to PEP 427 needs to start with digit\n        archive_name = f\"{dist_name}-{build_tag}-{tag}.whl\"\n        wheel_path = Path(self.dist_dir, archive_name)\n        if wheel_path.exists():\n            wheel_path.unlink()\n\n        unpacked_wheel = TemporaryDirectory(suffix=archive_name)\n        build_lib = TemporaryDirectory(suffix=\".build-lib\")\n        build_tmp = TemporaryDirectory(suffix=\".build-temp\")\n\n        with unpacked_wheel as unpacked, build_lib as lib, build_tmp as tmp:\n            unpacked_dist_info = Path(unpacked, Path(self.dist_info_dir).name)\n            shutil.copytree(self.dist_info_dir, unpacked_dist_info)\n            self._install_namespaces(unpacked, dist_info.name)\n            files, mapping = self._run_build_commands(dist_name, unpacked, lib, tmp)\n            strategy = self._select_strategy(dist_name, tag, lib)\n            with strategy, WheelFile(wheel_path, \"w\") as wheel_obj:\n                strategy(wheel_obj, files, mapping)\n                wheel_obj.write_files(unpacked)\n\n        return wheel_path\n\n    def _run_install(self, category: str):\n        has_category = getattr(self.distribution, f\"has_{category}\", None)\n        if has_category and has_category():\n            _logger.info(f\"Installing {category} as non editable\")\n            self.run_command(f\"install_{category}\")\n\n    def _select_strategy(\n        self,\n        name: str,\n        tag: str,\n        build_lib: _Path,\n    ) -> \"EditableStrategy\":\n        \"\"\"Decides which strategy to use to implement an editable installation.\"\"\"\n        build_name = f\"__editable__.{name}-{tag}\"\n        project_dir = Path(self.project_dir)\n        mode = _EditableMode.convert(self.mode)\n\n        if mode is _EditableMode.STRICT:\n            auxiliary_dir = _empty_dir(Path(self.project_dir, \"build\", build_name))\n            return _LinkTree(self.distribution, name, auxiliary_dir, build_lib)\n\n        packages = _find_packages(self.distribution)\n        has_simple_layout = _simple_layout(packages, self.package_dir, project_dir)\n        is_compat_mode = mode is _EditableMode.COMPAT\n        if set(self.package_dir) == {\"\"} and has_simple_layout or is_compat_mode:\n            # src-layout(ish) is relatively safe for a simple pth file\n            src_dir = self.package_dir.get(\"\", \".\")\n            return _StaticPth(self.distribution, name, [Path(project_dir, src_dir)])\n\n        # Use a MetaPathFinder to avoid adding accidental top-level packages/modules\n        return _TopLevelFinder(self.distribution, name)\n\n\nclass EditableStrategy(Protocol):\n    def __call__(self, wheel: \"WheelFile\", files: List[str], mapping: Dict[str, str]):\n        ...\n\n    def __enter__(self):\n        ...\n\n    def __exit__(self, _exc_type, _exc_value, _traceback):\n        ...\n\n\nclass _StaticPth:\n    def __init__(self, dist: Distribution, name: str, path_entries: List[Path]):\n        self.dist = dist\n        self.name = name\n        self.path_entries = path_entries\n\n    def __call__(self, wheel: \"WheelFile\", files: List[str], mapping: Dict[str, str]):\n        entries = \"\\n\".join((str(p.resolve()) for p in self.path_entries))\n        contents = bytes(f\"{entries}\\n\", \"utf-8\")\n        wheel.writestr(f\"__editable__.{self.name}.pth\", contents)\n\n    def __enter__(self):\n        msg = f\"\"\"\n        Editable install will be performed using .pth file to extend `sys.path` with:\n        {list(map(os.fspath, self.path_entries))!r}\n        \"\"\"\n        _logger.warning(msg + _LENIENT_WARNING)\n        return self\n\n    def __exit__(self, _exc_type, _exc_value, _traceback):\n        ...\n\n\nclass _LinkTree(_StaticPth):\n    \"\"\"\n    Creates a ``.pth`` file that points to a link tree in the ``auxiliary_dir``.\n\n    This strategy will only link files (not dirs), so it can be implemented in\n    any OS, even if that means using hardlinks instead of symlinks.\n\n    By collocating ``auxiliary_dir`` and the original source code, limitations\n    with hardlinks should be avoided.\n    \"\"\"\n    def __init__(\n        self, dist: Distribution,\n        name: str,\n        auxiliary_dir: _Path,\n        build_lib: _Path,\n    ):\n        self.auxiliary_dir = Path(auxiliary_dir)\n        self.build_lib = Path(build_lib).resolve()\n        self._file = dist.get_command_obj(\"build_py\").copy_file\n        super().__init__(dist, name, [self.auxiliary_dir])\n\n    def __call__(self, wheel: \"WheelFile\", files: List[str], mapping: Dict[str, str]):\n        self._create_links(files, mapping)\n        super().__call__(wheel, files, mapping)\n\n    def _normalize_output(self, file: str) -> Optional[str]:\n        # Files relative to build_lib will be normalized to None\n        with suppress(ValueError):\n            path = Path(file).resolve().relative_to(self.build_lib)\n            return str(path).replace(os.sep, '/')\n        return None\n\n    def _create_file(self, relative_output: str, src_file: str, link=None):\n        dest = self.auxiliary_dir / relative_output\n        if not dest.parent.is_dir():\n            dest.parent.mkdir(parents=True)\n        self._file(src_file, dest, link=link)\n\n    def _create_links(self, outputs, output_mapping):\n        self.auxiliary_dir.mkdir(parents=True, exist_ok=True)\n        link_type = \"sym\" if _can_symlink_files(self.auxiliary_dir) else \"hard\"\n        mappings = {\n            self._normalize_output(k): v\n            for k, v in output_mapping.items()\n        }\n        mappings.pop(None, None)  # remove files that are not relative to build_lib\n\n        for output in outputs:\n            relative = self._normalize_output(output)\n            if relative and relative not in mappings:\n                self._create_file(relative, output)\n\n        for relative, src in mappings.items():\n            self._create_file(relative, src, link=link_type)\n\n    def __enter__(self):\n        msg = \"Strict editable install will be performed using a link tree.\\n\"\n        _logger.warning(msg + _STRICT_WARNING)\n        return self\n\n    def __exit__(self, _exc_type, _exc_value, _traceback):\n        msg = f\"\"\"\\n\n        Strict editable installation performed using the auxiliary directory:\n            {self.auxiliary_dir}\n\n        Please be careful to not remove this directory, otherwise you might not be able\n        to import/use your package.\n        \"\"\"\n        warnings.warn(msg, InformationOnly)\n\n\nclass _TopLevelFinder:\n    def __init__(self, dist: Distribution, name: str):\n        self.dist = dist\n        self.name = name\n\n    def __call__(self, wheel: \"WheelFile\", files: List[str], mapping: Dict[str, str]):\n        src_root = self.dist.src_root or os.curdir\n        top_level = chain(_find_packages(self.dist), _find_top_level_modules(self.dist))\n        package_dir = self.dist.package_dir or {}\n        roots = _find_package_roots(top_level, package_dir, src_root)\n\n        namespaces_: Dict[str, List[str]] = dict(chain(\n            _find_namespaces(self.dist.packages or [], roots),\n            ((ns, []) for ns in _find_virtual_namespaces(roots)),\n        ))\n\n        name = f\"__editable__.{self.name}.finder\"\n        finder = _make_identifier(name)\n        content = bytes(_finder_template(name, roots, namespaces_), \"utf-8\")\n        wheel.writestr(f\"{finder}.py\", content)\n\n        content = bytes(f\"import {finder}; {finder}.install()\", \"utf-8\")\n        wheel.writestr(f\"__editable__.{self.name}.pth\", content)\n\n    def __enter__(self):\n        msg = \"Editable install will be performed using a meta path finder.\\n\"\n        _logger.warning(msg + _LENIENT_WARNING)\n        return self\n\n    def __exit__(self, _exc_type, _exc_value, _traceback):\n        msg = \"\"\"\\n\n        Please be careful with folders in your working directory with the same\n        name as your package as they may take precedence during imports.\n        \"\"\"\n        warnings.warn(msg, InformationOnly)\n\n\ndef _can_symlink_files(base_dir: Path) -> bool:\n    with TemporaryDirectory(dir=str(base_dir.resolve())) as tmp:\n        path1, path2 = Path(tmp, \"file1.txt\"), Path(tmp, \"file2.txt\")\n        path1.write_text(\"file1\", encoding=\"utf-8\")\n        with suppress(AttributeError, NotImplementedError, OSError):\n            os.symlink(path1, path2)\n            if path2.is_symlink() and path2.read_text(encoding=\"utf-8\") == \"file1\":\n                return True\n\n        try:\n            os.link(path1, path2)  # Ensure hard links can be created\n        except Exception as ex:\n            msg = (\n                \"File system does not seem to support either symlinks or hard links. \"\n                \"Strict editable installs require one of them to be supported.\"\n            )\n            raise LinksNotSupported(msg) from ex\n        return False\n\n\ndef _simple_layout(\n    packages: Iterable[str], package_dir: Dict[str, str], project_dir: Path\n) -> bool:\n    \"\"\"Return ``True`` if:\n    - all packages are contained by the same parent directory, **and**\n    - all packages become importable if the parent directory is added to ``sys.path``.\n\n    >>> _simple_layout(['a'], {\"\": \"src\"}, \"/tmp/myproj\")\n    True\n    >>> _simple_layout(['a', 'a.b'], {\"\": \"src\"}, \"/tmp/myproj\")\n    True\n    >>> _simple_layout(['a', 'a.b'], {}, \"/tmp/myproj\")\n    True\n    >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {\"\": \"src\"}, \"/tmp/myproj\")\n    True\n    >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {\"a\": \"a\", \"b\": \"b\"}, \".\")\n    True\n    >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {\"a\": \"_a\", \"b\": \"_b\"}, \".\")\n    False\n    >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {\"a\": \"_a\"}, \"/tmp/myproj\")\n    False\n    >>> _simple_layout(['a', 'a.a1', 'a.a1.a2', 'b'], {\"a.a1.a2\": \"_a2\"}, \".\")\n    False\n    >>> _simple_layout(['a', 'a.b'], {\"\": \"src\", \"a.b\": \"_ab\"}, \"/tmp/myproj\")\n    False\n    >>> # Special cases, no packages yet:\n    >>> _simple_layout([], {\"\": \"src\"}, \"/tmp/myproj\")\n    True\n    >>> _simple_layout([], {\"a\": \"_a\", \"\": \"src\"}, \"/tmp/myproj\")\n    False\n    \"\"\"\n    layout = {\n        pkg: find_package_path(pkg, package_dir, project_dir)\n        for pkg in packages\n    }\n    if not layout:\n        return set(package_dir) in ({}, {\"\"})\n    parent = os.path.commonpath([_parent_path(k, v) for k, v in layout.items()])\n    return all(\n        _normalize_path(Path(parent, *key.split('.'))) == _normalize_path(value)\n        for key, value in layout.items()\n    )\n\n\ndef _parent_path(pkg, pkg_path):\n    \"\"\"Infer the parent path containing a package, that if added to ``sys.path`` would\n    allow importing that package.\n    When ``pkg`` is directly mapped into a directory with a different name, return its\n    own path.\n    >>> _parent_path(\"a\", \"src/a\")\n    'src'\n    >>> _parent_path(\"b\", \"src/c\")\n    'src/c'\n    \"\"\"\n    parent = pkg_path[:-len(pkg)] if pkg_path.endswith(pkg) else pkg_path\n    return parent.rstrip(\"/\" + os.sep)\n\n\ndef _find_packages(dist: Distribution) -> Iterator[str]:\n    yield from iter(dist.packages or [])\n\n    py_modules = dist.py_modules or []\n    nested_modules = [mod for mod in py_modules if \".\" in mod]\n    if dist.ext_package:\n        yield dist.ext_package\n    else:\n        ext_modules = dist.ext_modules or []\n        nested_modules += [x.name for x in ext_modules if \".\" in x.name]\n\n    for module in nested_modules:\n        package, _, _ = module.rpartition(\".\")\n        yield package\n\n\ndef _find_top_level_modules(dist: Distribution) -> Iterator[str]:\n    py_modules = dist.py_modules or []\n    yield from (mod for mod in py_modules if \".\" not in mod)\n\n    if not dist.ext_package:\n        ext_modules = dist.ext_modules or []\n        yield from (x.name for x in ext_modules if \".\" not in x.name)\n\n\ndef _find_package_roots(\n    packages: Iterable[str],\n    package_dir: Mapping[str, str],\n    src_root: _Path,\n) -> Dict[str, str]:\n    pkg_roots: Dict[str, str] = {\n        pkg: _absolute_root(find_package_path(pkg, package_dir, src_root))\n        for pkg in sorted(packages)\n    }\n\n    return _remove_nested(pkg_roots)\n\n\ndef _absolute_root(path: _Path) -> str:\n    \"\"\"Works for packages and top-level modules\"\"\"\n    path_ = Path(path)\n    parent = path_.parent\n\n    if path_.exists():\n        return str(path_.resolve())\n    else:\n        return str(parent.resolve() / path_.name)\n\n\ndef _find_virtual_namespaces(pkg_roots: Dict[str, str]) -> Iterator[str]:\n    \"\"\"By carefully designing ``package_dir``, it is possible to implement the logical\n    structure of PEP 420 in a package without the corresponding directories.\n\n    Moreover a parent package can be purposefully/accidentally skipped in the discovery\n    phase (e.g. ``find_packages(include=[\"mypkg.*\"])``, when ``mypkg.foo`` is included\n    by ``mypkg`` itself is not).\n    We consider this case to also be a virtual namespace (ignoring the original\n    directory) to emulate a non-editable installation.\n\n    This function will try to find these kinds of namespaces.\n    \"\"\"\n    for pkg in pkg_roots:\n        if \".\" not in pkg:\n            continue\n        parts = pkg.split(\".\")\n        for i in range(len(parts) - 1, 0, -1):\n            partial_name = \".\".join(parts[:i])\n            path = Path(find_package_path(partial_name, pkg_roots, \"\"))\n            if not path.exists() or partial_name not in pkg_roots:\n                # partial_name not in pkg_roots ==> purposefully/accidentally skipped\n                yield partial_name\n\n\ndef _find_namespaces(\n    packages: List[str], pkg_roots: Dict[str, str]\n) -> Iterator[Tuple[str, List[str]]]:\n    for pkg in packages:\n        path = find_package_path(pkg, pkg_roots, \"\")\n        if Path(path).exists() and not Path(path, \"__init__.py\").exists():\n            yield (pkg, [path])\n\n\ndef _remove_nested(pkg_roots: Dict[str, str]) -> Dict[str, str]:\n    output = dict(pkg_roots.copy())\n\n    for pkg, path in reversed(list(pkg_roots.items())):\n        if any(\n            pkg != other and _is_nested(pkg, path, other, other_path)\n            for other, other_path in pkg_roots.items()\n        ):\n            output.pop(pkg)\n\n    return output\n\n\ndef _is_nested(pkg: str, pkg_path: str, parent: str, parent_path: str) -> bool:\n    \"\"\"\n    Return ``True`` if ``pkg`` is nested inside ``parent`` both logically and in the\n    file system.\n    >>> _is_nested(\"a.b\", \"path/a/b\", \"a\", \"path/a\")\n    True\n    >>> _is_nested(\"a.b\", \"path/a/b\", \"a\", \"otherpath/a\")\n    False\n    >>> _is_nested(\"a.b\", \"path/a/b\", \"c\", \"path/c\")\n    False\n    >>> _is_nested(\"a.a\", \"path/a/a\", \"a\", \"path/a\")\n    True\n    >>> _is_nested(\"b.a\", \"path/b/a\", \"a\", \"path/a\")\n    False\n    \"\"\"\n    norm_pkg_path = _normalize_path(pkg_path)\n    rest = pkg.replace(parent, \"\", 1).strip(\".\").split(\".\")\n    return (\n        pkg.startswith(parent)\n        and norm_pkg_path == _normalize_path(Path(parent_path, *rest))\n    )\n\n\ndef _normalize_path(filename: _Path) -> str:\n    \"\"\"Normalize a file/dir name for comparison purposes\"\"\"\n    # See pkg_resources.normalize_path\n    file = os.path.abspath(filename) if sys.platform == 'cygwin' else filename\n    return os.path.normcase(os.path.realpath(os.path.normpath(file)))\n\n\ndef _empty_dir(dir_: _P) -> _P:\n    \"\"\"Create a directory ensured to be empty. Existing files may be removed.\"\"\"\n    shutil.rmtree(dir_, ignore_errors=True)\n    os.makedirs(dir_)\n    return dir_\n\n\ndef _make_identifier(name: str) -> str:\n    \"\"\"Make a string safe to be used as Python identifier.\n    >>> _make_identifier(\"12abc\")\n    '_12abc'\n    >>> _make_identifier(\"__editable__.myns.pkg-78.9.3_local\")\n    '__editable___myns_pkg_78_9_3_local'\n    \"\"\"\n    safe = re.sub(r'\\W|^(?=\\d)', '_', name)\n    assert safe.isidentifier()\n    return safe\n\n\nclass _NamespaceInstaller(namespaces.Installer):\n    def __init__(self, distribution, installation_dir, editable_name, src_root):\n        self.distribution = distribution\n        self.src_root = src_root\n        self.installation_dir = installation_dir\n        self.editable_name = editable_name\n        self.outputs = []\n        self.dry_run = False\n\n    def _get_target(self):\n        \"\"\"Installation target.\"\"\"\n        return os.path.join(self.installation_dir, self.editable_name)\n\n    def _get_root(self):\n        \"\"\"Where the modules/packages should be loaded from.\"\"\"\n        return repr(str(self.src_root))\n\n\n_FINDER_TEMPLATE = \"\"\"\\\nimport sys\nfrom importlib.machinery import ModuleSpec\nfrom importlib.machinery import all_suffixes as module_suffixes\nfrom importlib.util import spec_from_file_location\nfrom itertools import chain\nfrom pathlib import Path\n\nMAPPING = {mapping!r}\nNAMESPACES = {namespaces!r}\nPATH_PLACEHOLDER = {name!r} + \".__path_hook__\"\n\n\nclass _EditableFinder:  # MetaPathFinder\n    @classmethod\n    def find_spec(cls, fullname, path=None, target=None):\n        for pkg, pkg_path in reversed(list(MAPPING.items())):\n            if fullname == pkg or fullname.startswith(f\"{{pkg}}.\"):\n                rest = fullname.replace(pkg, \"\", 1).strip(\".\").split(\".\")\n                return cls._find_spec(fullname, Path(pkg_path, *rest))\n\n        return None\n\n    @classmethod\n    def _find_spec(cls, fullname, candidate_path):\n        init = candidate_path / \"__init__.py\"\n        candidates = (candidate_path.with_suffix(x) for x in module_suffixes())\n        for candidate in chain([init], candidates):\n            if candidate.exists():\n                return spec_from_file_location(fullname, candidate)\n\n\nclass _EditableNamespaceFinder:  # PathEntryFinder\n    @classmethod\n    def _path_hook(cls, path):\n        if path == PATH_PLACEHOLDER:\n            return cls\n        raise ImportError\n\n    @classmethod\n    def _paths(cls, fullname):\n        # Ensure __path__ is not empty for the spec to be considered a namespace.\n        return NAMESPACES[fullname] or MAPPING.get(fullname) or [PATH_PLACEHOLDER]\n\n    @classmethod\n    def find_spec(cls, fullname, target=None):\n        if fullname in NAMESPACES:\n            spec = ModuleSpec(fullname, None, is_package=True)\n            spec.submodule_search_locations = cls._paths(fullname)\n            return spec\n        return None\n\n    @classmethod\n    def find_module(cls, fullname):\n        return None\n\n\ndef install():\n    if not any(finder == _EditableFinder for finder in sys.meta_path):\n        sys.meta_path.append(_EditableFinder)\n\n    if not NAMESPACES:\n        return\n\n    if not any(hook == _EditableNamespaceFinder._path_hook for hook in sys.path_hooks):\n        # PathEntryFinder is needed to create NamespaceSpec without private APIS\n        sys.path_hooks.append(_EditableNamespaceFinder._path_hook)\n    if PATH_PLACEHOLDER not in sys.path:\n        sys.path.append(PATH_PLACEHOLDER)  # Used just to trigger the path hook\n\"\"\"\n\n\ndef _finder_template(\n    name: str, mapping: Mapping[str, str], namespaces: Dict[str, List[str]]\n) -> str:\n    \"\"\"Create a string containing the code for the``MetaPathFinder`` and\n    ``PathEntryFinder``.\n    \"\"\"\n    mapping = dict(sorted(mapping.items(), key=lambda p: p[0]))\n    return _FINDER_TEMPLATE.format(name=name, mapping=mapping, namespaces=namespaces)\n\n\nclass InformationOnly(UserWarning):\n    \"\"\"Currently there is no clear way of displaying messages to the users\n    that use the setuptools backend directly via ``pip``.\n    The only thing that might work is a warning, although it is not the\n    most appropriate tool for the job...\n    \"\"\"\n\n\nclass LinksNotSupported(errors.FileError):\n    \"\"\"File system does not seem to support either symlinks or hard links.\"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/egg_info.py",
    "content": "\"\"\"setuptools.command.egg_info\n\nCreate a distribution's .egg-info directory and contents\"\"\"\n\nfrom distutils.filelist import FileList as _FileList\nfrom distutils.errors import DistutilsInternalError\nfrom distutils.util import convert_path\nfrom distutils import log\nimport distutils.errors\nimport distutils.filelist\nimport functools\nimport os\nimport re\nimport sys\nimport io\nimport warnings\nimport time\nimport collections\n\nfrom .._importlib import metadata\nfrom .. import _entry_points\n\nfrom setuptools import Command\nfrom setuptools.command.sdist import sdist\nfrom setuptools.command.sdist import walk_revctrl\nfrom setuptools.command.setopt import edit_config\nfrom setuptools.command import bdist_egg\nfrom pkg_resources import (\n    Requirement, safe_name, parse_version,\n    safe_version, to_filename)\nimport setuptools.unicode_utils as unicode_utils\nfrom setuptools.glob import glob\n\nfrom setuptools.extern import packaging\nfrom setuptools.extern.jaraco.text import yield_lines\nfrom setuptools import SetuptoolsDeprecationWarning\n\n\ndef translate_pattern(glob):  # noqa: C901  # is too complex (14)  # FIXME\n    \"\"\"\n    Translate a file path glob like '*.txt' in to a regular expression.\n    This differs from fnmatch.translate which allows wildcards to match\n    directory separators. It also knows about '**/' which matches any number of\n    directories.\n    \"\"\"\n    pat = ''\n\n    # This will split on '/' within [character classes]. This is deliberate.\n    chunks = glob.split(os.path.sep)\n\n    sep = re.escape(os.sep)\n    valid_char = '[^%s]' % (sep,)\n\n    for c, chunk in enumerate(chunks):\n        last_chunk = c == len(chunks) - 1\n\n        # Chunks that are a literal ** are globstars. They match anything.\n        if chunk == '**':\n            if last_chunk:\n                # Match anything if this is the last component\n                pat += '.*'\n            else:\n                # Match '(name/)*'\n                pat += '(?:%s+%s)*' % (valid_char, sep)\n            continue  # Break here as the whole path component has been handled\n\n        # Find any special characters in the remainder\n        i = 0\n        chunk_len = len(chunk)\n        while i < chunk_len:\n            char = chunk[i]\n            if char == '*':\n                # Match any number of name characters\n                pat += valid_char + '*'\n            elif char == '?':\n                # Match a name character\n                pat += valid_char\n            elif char == '[':\n                # Character class\n                inner_i = i + 1\n                # Skip initial !/] chars\n                if inner_i < chunk_len and chunk[inner_i] == '!':\n                    inner_i = inner_i + 1\n                if inner_i < chunk_len and chunk[inner_i] == ']':\n                    inner_i = inner_i + 1\n\n                # Loop till the closing ] is found\n                while inner_i < chunk_len and chunk[inner_i] != ']':\n                    inner_i = inner_i + 1\n\n                if inner_i >= chunk_len:\n                    # Got to the end of the string without finding a closing ]\n                    # Do not treat this as a matching group, but as a literal [\n                    pat += re.escape(char)\n                else:\n                    # Grab the insides of the [brackets]\n                    inner = chunk[i + 1:inner_i]\n                    char_class = ''\n\n                    # Class negation\n                    if inner[0] == '!':\n                        char_class = '^'\n                        inner = inner[1:]\n\n                    char_class += re.escape(inner)\n                    pat += '[%s]' % (char_class,)\n\n                    # Skip to the end ]\n                    i = inner_i\n            else:\n                pat += re.escape(char)\n            i += 1\n\n        # Join each chunk with the dir separator\n        if not last_chunk:\n            pat += sep\n\n    pat += r'\\Z'\n    return re.compile(pat, flags=re.MULTILINE | re.DOTALL)\n\n\nclass InfoCommon:\n    tag_build = None\n    tag_date = None\n\n    @property\n    def name(self):\n        return safe_name(self.distribution.get_name())\n\n    def tagged_version(self):\n        return safe_version(self._maybe_tag(self.distribution.get_version()))\n\n    def _maybe_tag(self, version):\n        \"\"\"\n        egg_info may be called more than once for a distribution,\n        in which case the version string already contains all tags.\n        \"\"\"\n        return (\n            version if self.vtags and self._already_tagged(version)\n            else version + self.vtags\n        )\n\n    def _already_tagged(self, version: str) -> bool:\n        # Depending on their format, tags may change with version normalization.\n        # So in addition the regular tags, we have to search for the normalized ones.\n        return version.endswith(self.vtags) or version.endswith(self._safe_tags())\n\n    def _safe_tags(self) -> str:\n        # To implement this we can rely on `safe_version` pretending to be version 0\n        # followed by tags. Then we simply discard the starting 0 (fake version number)\n        return safe_version(f\"0{self.vtags}\")[1:]\n\n    def tags(self) -> str:\n        version = ''\n        if self.tag_build:\n            version += self.tag_build\n        if self.tag_date:\n            version += time.strftime(\"-%Y%m%d\")\n        return version\n    vtags = property(tags)\n\n\nclass egg_info(InfoCommon, Command):\n    description = \"create a distribution's .egg-info directory\"\n\n    user_options = [\n        ('egg-base=', 'e', \"directory containing .egg-info directories\"\n                           \" (default: top of the source tree)\"),\n        ('tag-date', 'd', \"Add date stamp (e.g. 20050528) to version number\"),\n        ('tag-build=', 'b', \"Specify explicit tag to add to version number\"),\n        ('no-date', 'D', \"Don't include date stamp [default]\"),\n    ]\n\n    boolean_options = ['tag-date']\n    negative_opt = {\n        'no-date': 'tag-date',\n    }\n\n    def initialize_options(self):\n        self.egg_base = None\n        self.egg_name = None\n        self.egg_info = None\n        self.egg_version = None\n        self.broken_egg_info = False\n        self.ignore_egg_info_in_manifest = False\n\n    ####################################\n    # allow the 'tag_svn_revision' to be detected and\n    # set, supporting sdists built on older Setuptools.\n    @property\n    def tag_svn_revision(self):\n        pass\n\n    @tag_svn_revision.setter\n    def tag_svn_revision(self, value):\n        pass\n    ####################################\n\n    def save_version_info(self, filename):\n        \"\"\"\n        Materialize the value of date into the\n        build tag. Install build keys in a deterministic order\n        to avoid arbitrary reordering on subsequent builds.\n        \"\"\"\n        egg_info = collections.OrderedDict()\n        # follow the order these keys would have been added\n        # when PYTHONHASHSEED=0\n        egg_info['tag_build'] = self.tags()\n        egg_info['tag_date'] = 0\n        edit_config(filename, dict(egg_info=egg_info))\n\n    def finalize_options(self):\n        # Note: we need to capture the current value returned\n        # by `self.tagged_version()`, so we can later update\n        # `self.distribution.metadata.version` without\n        # repercussions.\n        self.egg_name = self.name\n        self.egg_version = self.tagged_version()\n        parsed_version = parse_version(self.egg_version)\n\n        try:\n            is_version = isinstance(parsed_version, packaging.version.Version)\n            spec = \"%s==%s\" if is_version else \"%s===%s\"\n            Requirement(spec % (self.egg_name, self.egg_version))\n        except ValueError as e:\n            raise distutils.errors.DistutilsOptionError(\n                \"Invalid distribution name or version syntax: %s-%s\" %\n                (self.egg_name, self.egg_version)\n            ) from e\n\n        if self.egg_base is None:\n            dirs = self.distribution.package_dir\n            self.egg_base = (dirs or {}).get('', os.curdir)\n\n        self.ensure_dirname('egg_base')\n        self.egg_info = to_filename(self.egg_name) + '.egg-info'\n        if self.egg_base != os.curdir:\n            self.egg_info = os.path.join(self.egg_base, self.egg_info)\n        if '-' in self.egg_name:\n            self.check_broken_egg_info()\n\n        # Set package version for the benefit of dumber commands\n        # (e.g. sdist, bdist_wininst, etc.)\n        #\n        self.distribution.metadata.version = self.egg_version\n\n        # If we bootstrapped around the lack of a PKG-INFO, as might be the\n        # case in a fresh checkout, make sure that any special tags get added\n        # to the version info\n        #\n        pd = self.distribution._patched_dist\n        if pd is not None and pd.key == self.egg_name.lower():\n            pd._version = self.egg_version\n            pd._parsed_version = parse_version(self.egg_version)\n            self.distribution._patched_dist = None\n\n    def write_or_delete_file(self, what, filename, data, force=False):\n        \"\"\"Write `data` to `filename` or delete if empty\n\n        If `data` is non-empty, this routine is the same as ``write_file()``.\n        If `data` is empty but not ``None``, this is the same as calling\n        ``delete_file(filename)`.  If `data` is ``None``, then this is a no-op\n        unless `filename` exists, in which case a warning is issued about the\n        orphaned file (if `force` is false), or deleted (if `force` is true).\n        \"\"\"\n        if data:\n            self.write_file(what, filename, data)\n        elif os.path.exists(filename):\n            if data is None and not force:\n                log.warn(\n                    \"%s not set in setup(), but %s exists\", what, filename\n                )\n                return\n            else:\n                self.delete_file(filename)\n\n    def write_file(self, what, filename, data):\n        \"\"\"Write `data` to `filename` (if not a dry run) after announcing it\n\n        `what` is used in a log message to identify what is being written\n        to the file.\n        \"\"\"\n        log.info(\"writing %s to %s\", what, filename)\n        data = data.encode(\"utf-8\")\n        if not self.dry_run:\n            f = open(filename, 'wb')\n            f.write(data)\n            f.close()\n\n    def delete_file(self, filename):\n        \"\"\"Delete `filename` (if not a dry run) after announcing it\"\"\"\n        log.info(\"deleting %s\", filename)\n        if not self.dry_run:\n            os.unlink(filename)\n\n    def run(self):\n        self.mkpath(self.egg_info)\n        os.utime(self.egg_info, None)\n        for ep in metadata.entry_points(group='egg_info.writers'):\n            writer = ep.load()\n            writer(self, ep.name, os.path.join(self.egg_info, ep.name))\n\n        # Get rid of native_libs.txt if it was put there by older bdist_egg\n        nl = os.path.join(self.egg_info, \"native_libs.txt\")\n        if os.path.exists(nl):\n            self.delete_file(nl)\n\n        self.find_sources()\n\n    def find_sources(self):\n        \"\"\"Generate SOURCES.txt manifest file\"\"\"\n        manifest_filename = os.path.join(self.egg_info, \"SOURCES.txt\")\n        mm = manifest_maker(self.distribution)\n        mm.ignore_egg_info_dir = self.ignore_egg_info_in_manifest\n        mm.manifest = manifest_filename\n        mm.run()\n        self.filelist = mm.filelist\n\n    def check_broken_egg_info(self):\n        bei = self.egg_name + '.egg-info'\n        if self.egg_base != os.curdir:\n            bei = os.path.join(self.egg_base, bei)\n        if os.path.exists(bei):\n            log.warn(\n                \"-\" * 78 + '\\n'\n                \"Note: Your current .egg-info directory has a '-' in its name;\"\n                '\\nthis will not work correctly with \"setup.py develop\".\\n\\n'\n                'Please rename %s to %s to correct this problem.\\n' + '-' * 78,\n                bei, self.egg_info\n            )\n            self.broken_egg_info = self.egg_info\n            self.egg_info = bei  # make it work for now\n\n\nclass FileList(_FileList):\n    # Implementations of the various MANIFEST.in commands\n\n    def __init__(self, warn=None, debug_print=None, ignore_egg_info_dir=False):\n        super().__init__(warn, debug_print)\n        self.ignore_egg_info_dir = ignore_egg_info_dir\n\n    def process_template_line(self, line):\n        # Parse the line: split it up, make sure the right number of words\n        # is there, and return the relevant words.  'action' is always\n        # defined: it's the first word of the line.  Which of the other\n        # three are defined depends on the action; it'll be either\n        # patterns, (dir and patterns), or (dir_pattern).\n        (action, patterns, dir, dir_pattern) = self._parse_template_line(line)\n\n        action_map = {\n            'include': self.include,\n            'exclude': self.exclude,\n            'global-include': self.global_include,\n            'global-exclude': self.global_exclude,\n            'recursive-include': functools.partial(\n                self.recursive_include, dir,\n            ),\n            'recursive-exclude': functools.partial(\n                self.recursive_exclude, dir,\n            ),\n            'graft': self.graft,\n            'prune': self.prune,\n        }\n        log_map = {\n            'include': \"warning: no files found matching '%s'\",\n            'exclude': (\n                \"warning: no previously-included files found \"\n                \"matching '%s'\"\n            ),\n            'global-include': (\n                \"warning: no files found matching '%s' \"\n                \"anywhere in distribution\"\n            ),\n            'global-exclude': (\n                \"warning: no previously-included files matching \"\n                \"'%s' found anywhere in distribution\"\n            ),\n            'recursive-include': (\n                \"warning: no files found matching '%s' \"\n                \"under directory '%s'\"\n            ),\n            'recursive-exclude': (\n                \"warning: no previously-included files matching \"\n                \"'%s' found under directory '%s'\"\n            ),\n            'graft': \"warning: no directories found matching '%s'\",\n            'prune': \"no previously-included directories found matching '%s'\",\n        }\n\n        try:\n            process_action = action_map[action]\n        except KeyError:\n            raise DistutilsInternalError(\n                \"this cannot happen: invalid action '{action!s}'\".\n                format(action=action),\n            )\n\n        # OK, now we know that the action is valid and we have the\n        # right number of words on the line for that action -- so we\n        # can proceed with minimal error-checking.\n\n        action_is_recursive = action.startswith('recursive-')\n        if action in {'graft', 'prune'}:\n            patterns = [dir_pattern]\n        extra_log_args = (dir, ) if action_is_recursive else ()\n        log_tmpl = log_map[action]\n\n        self.debug_print(\n            ' '.join(\n                [action] +\n                ([dir] if action_is_recursive else []) +\n                patterns,\n            )\n        )\n        for pattern in patterns:\n            if not process_action(pattern):\n                log.warn(log_tmpl, pattern, *extra_log_args)\n\n    def _remove_files(self, predicate):\n        \"\"\"\n        Remove all files from the file list that match the predicate.\n        Return True if any matching files were removed\n        \"\"\"\n        found = False\n        for i in range(len(self.files) - 1, -1, -1):\n            if predicate(self.files[i]):\n                self.debug_print(\" removing \" + self.files[i])\n                del self.files[i]\n                found = True\n        return found\n\n    def include(self, pattern):\n        \"\"\"Include files that match 'pattern'.\"\"\"\n        found = [f for f in glob(pattern) if not os.path.isdir(f)]\n        self.extend(found)\n        return bool(found)\n\n    def exclude(self, pattern):\n        \"\"\"Exclude files that match 'pattern'.\"\"\"\n        match = translate_pattern(pattern)\n        return self._remove_files(match.match)\n\n    def recursive_include(self, dir, pattern):\n        \"\"\"\n        Include all files anywhere in 'dir/' that match the pattern.\n        \"\"\"\n        full_pattern = os.path.join(dir, '**', pattern)\n        found = [f for f in glob(full_pattern, recursive=True)\n                 if not os.path.isdir(f)]\n        self.extend(found)\n        return bool(found)\n\n    def recursive_exclude(self, dir, pattern):\n        \"\"\"\n        Exclude any file anywhere in 'dir/' that match the pattern.\n        \"\"\"\n        match = translate_pattern(os.path.join(dir, '**', pattern))\n        return self._remove_files(match.match)\n\n    def graft(self, dir):\n        \"\"\"Include all files from 'dir/'.\"\"\"\n        found = [\n            item\n            for match_dir in glob(dir)\n            for item in distutils.filelist.findall(match_dir)\n        ]\n        self.extend(found)\n        return bool(found)\n\n    def prune(self, dir):\n        \"\"\"Filter out files from 'dir/'.\"\"\"\n        match = translate_pattern(os.path.join(dir, '**'))\n        return self._remove_files(match.match)\n\n    def global_include(self, pattern):\n        \"\"\"\n        Include all files anywhere in the current directory that match the\n        pattern. This is very inefficient on large file trees.\n        \"\"\"\n        if self.allfiles is None:\n            self.findall()\n        match = translate_pattern(os.path.join('**', pattern))\n        found = [f for f in self.allfiles if match.match(f)]\n        self.extend(found)\n        return bool(found)\n\n    def global_exclude(self, pattern):\n        \"\"\"\n        Exclude all files anywhere that match the pattern.\n        \"\"\"\n        match = translate_pattern(os.path.join('**', pattern))\n        return self._remove_files(match.match)\n\n    def append(self, item):\n        if item.endswith('\\r'):  # Fix older sdists built on Windows\n            item = item[:-1]\n        path = convert_path(item)\n\n        if self._safe_path(path):\n            self.files.append(path)\n\n    def extend(self, paths):\n        self.files.extend(filter(self._safe_path, paths))\n\n    def _repair(self):\n        \"\"\"\n        Replace self.files with only safe paths\n\n        Because some owners of FileList manipulate the underlying\n        ``files`` attribute directly, this method must be called to\n        repair those paths.\n        \"\"\"\n        self.files = list(filter(self._safe_path, self.files))\n\n    def _safe_path(self, path):\n        enc_warn = \"'%s' not %s encodable -- skipping\"\n\n        # To avoid accidental trans-codings errors, first to unicode\n        u_path = unicode_utils.filesys_decode(path)\n        if u_path is None:\n            log.warn(\"'%s' in unexpected encoding -- skipping\" % path)\n            return False\n\n        # Must ensure utf-8 encodability\n        utf8_path = unicode_utils.try_encode(u_path, \"utf-8\")\n        if utf8_path is None:\n            log.warn(enc_warn, path, 'utf-8')\n            return False\n\n        try:\n            # ignore egg-info paths\n            is_egg_info = \".egg-info\" in u_path or b\".egg-info\" in utf8_path\n            if self.ignore_egg_info_dir and is_egg_info:\n                return False\n            # accept is either way checks out\n            if os.path.exists(u_path) or os.path.exists(utf8_path):\n                return True\n        # this will catch any encode errors decoding u_path\n        except UnicodeEncodeError:\n            log.warn(enc_warn, path, sys.getfilesystemencoding())\n\n\nclass manifest_maker(sdist):\n    template = \"MANIFEST.in\"\n\n    def initialize_options(self):\n        self.use_defaults = 1\n        self.prune = 1\n        self.manifest_only = 1\n        self.force_manifest = 1\n        self.ignore_egg_info_dir = False\n\n    def finalize_options(self):\n        pass\n\n    def run(self):\n        self.filelist = FileList(ignore_egg_info_dir=self.ignore_egg_info_dir)\n        if not os.path.exists(self.manifest):\n            self.write_manifest()  # it must exist so it'll get in the list\n        self.add_defaults()\n        if os.path.exists(self.template):\n            self.read_template()\n        self.add_license_files()\n        self.prune_file_list()\n        self.filelist.sort()\n        self.filelist.remove_duplicates()\n        self.write_manifest()\n\n    def _manifest_normalize(self, path):\n        path = unicode_utils.filesys_decode(path)\n        return path.replace(os.sep, '/')\n\n    def write_manifest(self):\n        \"\"\"\n        Write the file list in 'self.filelist' to the manifest file\n        named by 'self.manifest'.\n        \"\"\"\n        self.filelist._repair()\n\n        # Now _repairs should encodability, but not unicode\n        files = [self._manifest_normalize(f) for f in self.filelist.files]\n        msg = \"writing manifest file '%s'\" % self.manifest\n        self.execute(write_file, (self.manifest, files), msg)\n\n    def warn(self, msg):\n        if not self._should_suppress_warning(msg):\n            sdist.warn(self, msg)\n\n    @staticmethod\n    def _should_suppress_warning(msg):\n        \"\"\"\n        suppress missing-file warnings from sdist\n        \"\"\"\n        return re.match(r\"standard file .*not found\", msg)\n\n    def add_defaults(self):\n        sdist.add_defaults(self)\n        self.filelist.append(self.template)\n        self.filelist.append(self.manifest)\n        rcfiles = list(walk_revctrl())\n        if rcfiles:\n            self.filelist.extend(rcfiles)\n        elif os.path.exists(self.manifest):\n            self.read_manifest()\n\n        if os.path.exists(\"setup.py\"):\n            # setup.py should be included by default, even if it's not\n            # the script called to create the sdist\n            self.filelist.append(\"setup.py\")\n\n        ei_cmd = self.get_finalized_command('egg_info')\n        self.filelist.graft(ei_cmd.egg_info)\n\n    def add_license_files(self):\n        license_files = self.distribution.metadata.license_files or []\n        for lf in license_files:\n            log.info(\"adding license file '%s'\", lf)\n            pass\n        self.filelist.extend(license_files)\n\n    def prune_file_list(self):\n        build = self.get_finalized_command('build')\n        base_dir = self.distribution.get_fullname()\n        self.filelist.prune(build.build_base)\n        self.filelist.prune(base_dir)\n        sep = re.escape(os.sep)\n        self.filelist.exclude_pattern(r'(^|' + sep + r')(RCS|CVS|\\.svn)' + sep,\n                                      is_regex=1)\n\n    def _safe_data_files(self, build_py):\n        \"\"\"\n        The parent class implementation of this method\n        (``sdist``) will try to include data files, which\n        might cause recursion problems when\n        ``include_package_data=True``.\n\n        Therefore, avoid triggering any attempt of\n        analyzing/building the manifest again.\n        \"\"\"\n        if hasattr(build_py, 'get_data_files_without_manifest'):\n            return build_py.get_data_files_without_manifest()\n\n        warnings.warn(\n            \"Custom 'build_py' does not implement \"\n            \"'get_data_files_without_manifest'.\\nPlease extend command classes\"\n            \" from setuptools instead of distutils.\",\n            SetuptoolsDeprecationWarning\n        )\n        return build_py.get_data_files()\n\n\ndef write_file(filename, contents):\n    \"\"\"Create a file with the specified name and write 'contents' (a\n    sequence of strings without line terminators) to it.\n    \"\"\"\n    contents = \"\\n\".join(contents)\n\n    # assuming the contents has been vetted for utf-8 encoding\n    contents = contents.encode(\"utf-8\")\n\n    with open(filename, \"wb\") as f:  # always write POSIX-style manifest\n        f.write(contents)\n\n\ndef write_pkg_info(cmd, basename, filename):\n    log.info(\"writing %s\", filename)\n    if not cmd.dry_run:\n        metadata = cmd.distribution.metadata\n        metadata.version, oldver = cmd.egg_version, metadata.version\n        metadata.name, oldname = cmd.egg_name, metadata.name\n\n        try:\n            # write unescaped data to PKG-INFO, so older pkg_resources\n            # can still parse it\n            metadata.write_pkg_info(cmd.egg_info)\n        finally:\n            metadata.name, metadata.version = oldname, oldver\n\n        safe = getattr(cmd.distribution, 'zip_safe', None)\n\n        bdist_egg.write_safety_flag(cmd.egg_info, safe)\n\n\ndef warn_depends_obsolete(cmd, basename, filename):\n    if os.path.exists(filename):\n        log.warn(\n            \"WARNING: 'depends.txt' is not used by setuptools 0.6!\\n\"\n            \"Use the install_requires/extras_require setup() args instead.\"\n        )\n\n\ndef _write_requirements(stream, reqs):\n    lines = yield_lines(reqs or ())\n\n    def append_cr(line):\n        return line + '\\n'\n    lines = map(append_cr, lines)\n    stream.writelines(lines)\n\n\ndef write_requirements(cmd, basename, filename):\n    dist = cmd.distribution\n    data = io.StringIO()\n    _write_requirements(data, dist.install_requires)\n    extras_require = dist.extras_require or {}\n    for extra in sorted(extras_require):\n        data.write('\\n[{extra}]\\n'.format(**vars()))\n        _write_requirements(data, extras_require[extra])\n    cmd.write_or_delete_file(\"requirements\", filename, data.getvalue())\n\n\ndef write_setup_requirements(cmd, basename, filename):\n    data = io.StringIO()\n    _write_requirements(data, cmd.distribution.setup_requires)\n    cmd.write_or_delete_file(\"setup-requirements\", filename, data.getvalue())\n\n\ndef write_toplevel_names(cmd, basename, filename):\n    pkgs = dict.fromkeys(\n        [\n            k.split('.', 1)[0]\n            for k in cmd.distribution.iter_distribution_names()\n        ]\n    )\n    cmd.write_file(\"top-level names\", filename, '\\n'.join(sorted(pkgs)) + '\\n')\n\n\ndef overwrite_arg(cmd, basename, filename):\n    write_arg(cmd, basename, filename, True)\n\n\ndef write_arg(cmd, basename, filename, force=False):\n    argname = os.path.splitext(basename)[0]\n    value = getattr(cmd.distribution, argname, None)\n    if value is not None:\n        value = '\\n'.join(value) + '\\n'\n    cmd.write_or_delete_file(argname, filename, value, force)\n\n\ndef write_entries(cmd, basename, filename):\n    eps = _entry_points.load(cmd.distribution.entry_points)\n    defn = _entry_points.render(eps)\n    cmd.write_or_delete_file('entry points', filename, defn, True)\n\n\ndef get_pkg_info_revision():\n    \"\"\"\n    Get a -r### off of PKG-INFO Version in case this is an sdist of\n    a subversion revision.\n    \"\"\"\n    warnings.warn(\n        \"get_pkg_info_revision is deprecated.\", EggInfoDeprecationWarning)\n    if os.path.exists('PKG-INFO'):\n        with io.open('PKG-INFO') as f:\n            for line in f:\n                match = re.match(r\"Version:.*-r(\\d+)\\s*$\", line)\n                if match:\n                    return int(match.group(1))\n    return 0\n\n\nclass EggInfoDeprecationWarning(SetuptoolsDeprecationWarning):\n    \"\"\"Deprecated behavior warning for EggInfo, bypassing suppression.\"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/install.py",
    "content": "from distutils.errors import DistutilsArgError\nimport inspect\nimport glob\nimport warnings\nimport platform\nimport distutils.command.install as orig\n\nimport setuptools\n\n# Prior to numpy 1.9, NumPy relies on the '_install' name, so provide it for\n# now. See https://github.com/pypa/setuptools/issues/199/\n_install = orig.install\n\n\nclass install(orig.install):\n    \"\"\"Use easy_install to install the package, w/dependencies\"\"\"\n\n    user_options = orig.install.user_options + [\n        ('old-and-unmanageable', None, \"Try not to use this!\"),\n        ('single-version-externally-managed', None,\n         \"used by system package builders to create 'flat' eggs\"),\n    ]\n    boolean_options = orig.install.boolean_options + [\n        'old-and-unmanageable', 'single-version-externally-managed',\n    ]\n    new_commands = [\n        ('install_egg_info', lambda self: True),\n        ('install_scripts', lambda self: True),\n    ]\n    _nc = dict(new_commands)\n\n    def initialize_options(self):\n\n        warnings.warn(\n            \"setup.py install is deprecated. \"\n            \"Use build and pip and other standards-based tools.\",\n            setuptools.SetuptoolsDeprecationWarning,\n        )\n\n        orig.install.initialize_options(self)\n        self.old_and_unmanageable = None\n        self.single_version_externally_managed = None\n\n    def finalize_options(self):\n        orig.install.finalize_options(self)\n        if self.root:\n            self.single_version_externally_managed = True\n        elif self.single_version_externally_managed:\n            if not self.root and not self.record:\n                raise DistutilsArgError(\n                    \"You must specify --record or --root when building system\"\n                    \" packages\"\n                )\n\n    def handle_extra_path(self):\n        if self.root or self.single_version_externally_managed:\n            # explicit backward-compatibility mode, allow extra_path to work\n            return orig.install.handle_extra_path(self)\n\n        # Ignore extra_path when installing an egg (or being run by another\n        # command without --root or --single-version-externally-managed\n        self.path_file = None\n        self.extra_dirs = ''\n\n    def run(self):\n        # Explicit request for old-style install?  Just do it\n        if self.old_and_unmanageable or self.single_version_externally_managed:\n            return orig.install.run(self)\n\n        if not self._called_from_setup(inspect.currentframe()):\n            # Run in backward-compatibility mode to support bdist_* commands.\n            orig.install.run(self)\n        else:\n            self.do_egg_install()\n\n    @staticmethod\n    def _called_from_setup(run_frame):\n        \"\"\"\n        Attempt to detect whether run() was called from setup() or by another\n        command.  If called by setup(), the parent caller will be the\n        'run_command' method in 'distutils.dist', and *its* caller will be\n        the 'run_commands' method.  If called any other way, the\n        immediate caller *might* be 'run_command', but it won't have been\n        called by 'run_commands'. Return True in that case or if a call stack\n        is unavailable. Return False otherwise.\n        \"\"\"\n        if run_frame is None:\n            msg = \"Call stack not available. bdist_* commands may fail.\"\n            warnings.warn(msg)\n            if platform.python_implementation() == 'IronPython':\n                msg = \"For best results, pass -X:Frames to enable call stack.\"\n                warnings.warn(msg)\n            return True\n\n        frames = inspect.getouterframes(run_frame)\n        for frame in frames[2:4]:\n            caller, = frame[:1]\n            info = inspect.getframeinfo(caller)\n            caller_module = caller.f_globals.get('__name__', '')\n\n            if caller_module == \"setuptools.dist\" and info.function == \"run_command\":\n                # Starting from v61.0.0 setuptools overwrites dist.run_command\n                continue\n\n            return (\n                caller_module == 'distutils.dist'\n                and info.function == 'run_commands'\n            )\n\n    def do_egg_install(self):\n\n        easy_install = self.distribution.get_command_class('easy_install')\n\n        cmd = easy_install(\n            self.distribution, args=\"x\", root=self.root, record=self.record,\n        )\n        cmd.ensure_finalized()  # finalize before bdist_egg munges install cmd\n        cmd.always_copy_from = '.'  # make sure local-dir eggs get installed\n\n        # pick up setup-dir .egg files only: no .egg-info\n        cmd.package_index.scan(glob.glob('*.egg'))\n\n        self.run_command('bdist_egg')\n        args = [self.distribution.get_command_obj('bdist_egg').egg_output]\n\n        if setuptools.bootstrap_install_from:\n            # Bootstrap self-installation of setuptools\n            args.insert(0, setuptools.bootstrap_install_from)\n\n        cmd.args = args\n        cmd.run(show_deprecation=False)\n        setuptools.bootstrap_install_from = None\n\n\n# XXX Python 3.1 doesn't see _nc if this is inside the class\ninstall.sub_commands = (\n    [cmd for cmd in orig.install.sub_commands if cmd[0] not in install._nc] +\n    install.new_commands\n)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/install_egg_info.py",
    "content": "from distutils import log, dir_util\nimport os\n\nfrom setuptools import Command\nfrom setuptools import namespaces\nfrom setuptools.archive_util import unpack_archive\nfrom .._path import ensure_directory\nimport pkg_resources\n\n\nclass install_egg_info(namespaces.Installer, Command):\n    \"\"\"Install an .egg-info directory for the package\"\"\"\n\n    description = \"Install an .egg-info directory for the package\"\n\n    user_options = [\n        ('install-dir=', 'd', \"directory to install to\"),\n    ]\n\n    def initialize_options(self):\n        self.install_dir = None\n\n    def finalize_options(self):\n        self.set_undefined_options('install_lib',\n                                   ('install_dir', 'install_dir'))\n        ei_cmd = self.get_finalized_command(\"egg_info\")\n        basename = pkg_resources.Distribution(\n            None, None, ei_cmd.egg_name, ei_cmd.egg_version\n        ).egg_name() + '.egg-info'\n        self.source = ei_cmd.egg_info\n        self.target = os.path.join(self.install_dir, basename)\n        self.outputs = []\n\n    def run(self):\n        self.run_command('egg_info')\n        if os.path.isdir(self.target) and not os.path.islink(self.target):\n            dir_util.remove_tree(self.target, dry_run=self.dry_run)\n        elif os.path.exists(self.target):\n            self.execute(os.unlink, (self.target,), \"Removing \" + self.target)\n        if not self.dry_run:\n            ensure_directory(self.target)\n        self.execute(\n            self.copytree, (), \"Copying %s to %s\" % (self.source, self.target)\n        )\n        self.install_namespaces()\n\n    def get_outputs(self):\n        return self.outputs\n\n    def copytree(self):\n        # Copy the .egg-info tree to site-packages\n        def skimmer(src, dst):\n            # filter out source-control directories; note that 'src' is always\n            # a '/'-separated path, regardless of platform.  'dst' is a\n            # platform-specific path.\n            for skip in '.svn/', 'CVS/':\n                if src.startswith(skip) or '/' + skip in src:\n                    return None\n            self.outputs.append(dst)\n            log.debug(\"Copying %s to %s\", src, dst)\n            return dst\n\n        unpack_archive(self.source, self.target, skimmer)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/install_lib.py",
    "content": "import os\nimport sys\nfrom itertools import product, starmap\nimport distutils.command.install_lib as orig\n\n\nclass install_lib(orig.install_lib):\n    \"\"\"Don't add compiled flags to filenames of non-Python files\"\"\"\n\n    def run(self):\n        self.build()\n        outfiles = self.install()\n        if outfiles is not None:\n            # always compile, in case we have any extension stubs to deal with\n            self.byte_compile(outfiles)\n\n    def get_exclusions(self):\n        \"\"\"\n        Return a collections.Sized collections.Container of paths to be\n        excluded for single_version_externally_managed installations.\n        \"\"\"\n        all_packages = (\n            pkg\n            for ns_pkg in self._get_SVEM_NSPs()\n            for pkg in self._all_packages(ns_pkg)\n        )\n\n        excl_specs = product(all_packages, self._gen_exclusion_paths())\n        return set(starmap(self._exclude_pkg_path, excl_specs))\n\n    def _exclude_pkg_path(self, pkg, exclusion_path):\n        \"\"\"\n        Given a package name and exclusion path within that package,\n        compute the full exclusion path.\n        \"\"\"\n        parts = pkg.split('.') + [exclusion_path]\n        return os.path.join(self.install_dir, *parts)\n\n    @staticmethod\n    def _all_packages(pkg_name):\n        \"\"\"\n        >>> list(install_lib._all_packages('foo.bar.baz'))\n        ['foo.bar.baz', 'foo.bar', 'foo']\n        \"\"\"\n        while pkg_name:\n            yield pkg_name\n            pkg_name, sep, child = pkg_name.rpartition('.')\n\n    def _get_SVEM_NSPs(self):\n        \"\"\"\n        Get namespace packages (list) but only for\n        single_version_externally_managed installations and empty otherwise.\n        \"\"\"\n        # TODO: is it necessary to short-circuit here? i.e. what's the cost\n        # if get_finalized_command is called even when namespace_packages is\n        # False?\n        if not self.distribution.namespace_packages:\n            return []\n\n        install_cmd = self.get_finalized_command('install')\n        svem = install_cmd.single_version_externally_managed\n\n        return self.distribution.namespace_packages if svem else []\n\n    @staticmethod\n    def _gen_exclusion_paths():\n        \"\"\"\n        Generate file paths to be excluded for namespace packages (bytecode\n        cache files).\n        \"\"\"\n        # always exclude the package module itself\n        yield '__init__.py'\n\n        yield '__init__.pyc'\n        yield '__init__.pyo'\n\n        if not hasattr(sys, 'implementation'):\n            return\n\n        base = os.path.join(\n            '__pycache__', '__init__.' + sys.implementation.cache_tag)\n        yield base + '.pyc'\n        yield base + '.pyo'\n        yield base + '.opt-1.pyc'\n        yield base + '.opt-2.pyc'\n\n    def copy_tree(\n            self, infile, outfile,\n            preserve_mode=1, preserve_times=1, preserve_symlinks=0, level=1\n    ):\n        assert preserve_mode and preserve_times and not preserve_symlinks\n        exclude = self.get_exclusions()\n\n        if not exclude:\n            return orig.install_lib.copy_tree(self, infile, outfile)\n\n        # Exclude namespace package __init__.py* files from the output\n\n        from setuptools.archive_util import unpack_directory\n        from distutils import log\n\n        outfiles = []\n\n        def pf(src, dst):\n            if dst in exclude:\n                log.warn(\"Skipping installation of %s (namespace package)\",\n                         dst)\n                return False\n\n            log.info(\"copying %s -> %s\", src, os.path.dirname(dst))\n            outfiles.append(dst)\n            return dst\n\n        unpack_directory(infile, outfile, pf)\n        return outfiles\n\n    def get_outputs(self):\n        outputs = orig.install_lib.get_outputs(self)\n        exclude = self.get_exclusions()\n        if exclude:\n            return [f for f in outputs if f not in exclude]\n        return outputs\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/install_scripts.py",
    "content": "from distutils import log\nimport distutils.command.install_scripts as orig\nfrom distutils.errors import DistutilsModuleError\nimport os\nimport sys\n\nfrom pkg_resources import Distribution, PathMetadata\nfrom .._path import ensure_directory\n\n\nclass install_scripts(orig.install_scripts):\n    \"\"\"Do normal script install, plus any egg_info wrapper scripts\"\"\"\n\n    def initialize_options(self):\n        orig.install_scripts.initialize_options(self)\n        self.no_ep = False\n\n    def run(self):\n        import setuptools.command.easy_install as ei\n\n        self.run_command(\"egg_info\")\n        if self.distribution.scripts:\n            orig.install_scripts.run(self)  # run first to set up self.outfiles\n        else:\n            self.outfiles = []\n        if self.no_ep:\n            # don't install entry point scripts into .egg file!\n            return\n\n        ei_cmd = self.get_finalized_command(\"egg_info\")\n        dist = Distribution(\n            ei_cmd.egg_base, PathMetadata(ei_cmd.egg_base, ei_cmd.egg_info),\n            ei_cmd.egg_name, ei_cmd.egg_version,\n        )\n        bs_cmd = self.get_finalized_command('build_scripts')\n        exec_param = getattr(bs_cmd, 'executable', None)\n        try:\n            bw_cmd = self.get_finalized_command(\"bdist_wininst\")\n            is_wininst = getattr(bw_cmd, '_is_running', False)\n        except (ImportError, DistutilsModuleError):\n            is_wininst = False\n        writer = ei.ScriptWriter\n        if is_wininst:\n            exec_param = \"python.exe\"\n            writer = ei.WindowsScriptWriter\n        if exec_param == sys.executable:\n            # In case the path to the Python executable contains a space, wrap\n            # it so it's not split up.\n            exec_param = [exec_param]\n        # resolve the writer to the environment\n        writer = writer.best()\n        cmd = writer.command_spec_class.best().from_param(exec_param)\n        for args in writer.get_args(dist, cmd.as_header()):\n            self.write_script(*args)\n\n    def write_script(self, script_name, contents, mode=\"t\", *ignored):\n        \"\"\"Write an executable file to the scripts directory\"\"\"\n        from setuptools.command.easy_install import chmod, current_umask\n\n        log.info(\"Installing %s script to %s\", script_name, self.install_dir)\n        target = os.path.join(self.install_dir, script_name)\n        self.outfiles.append(target)\n\n        mask = current_umask()\n        if not self.dry_run:\n            ensure_directory(target)\n            f = open(target, \"w\" + mode)\n            f.write(contents)\n            f.close()\n            chmod(target, 0o777 - mask)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/launcher manifest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n    <assemblyIdentity version=\"1.0.0.0\"\n                      processorArchitecture=\"X86\"\n                      name=\"%(name)s\"\n                      type=\"win32\"/>\n    <!-- Identify the application security requirements. -->\n    <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n        <security>\n            <requestedPrivileges>\n                <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"/>\n            </requestedPrivileges>\n        </security>\n    </trustInfo>\n</assembly>\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/py36compat.py",
    "content": "import os\nfrom glob import glob\nfrom distutils.util import convert_path\nfrom distutils.command import sdist\n\n\nclass sdist_add_defaults:\n    \"\"\"\n    Mix-in providing forward-compatibility for functionality as found in\n    distutils on Python 3.7.\n\n    Do not edit the code in this class except to update functionality\n    as implemented in distutils. Instead, override in the subclass.\n    \"\"\"\n\n    def add_defaults(self):\n        \"\"\"Add all the default files to self.filelist:\n          - README or README.txt\n          - setup.py\n          - test/test*.py\n          - all pure Python modules mentioned in setup script\n          - all files pointed by package_data (build_py)\n          - all files defined in data_files.\n          - all files defined as scripts.\n          - all C sources listed as part of extensions or C libraries\n            in the setup script (doesn't catch C headers!)\n        Warns if (README or README.txt) or setup.py are missing; everything\n        else is optional.\n        \"\"\"\n        self._add_defaults_standards()\n        self._add_defaults_optional()\n        self._add_defaults_python()\n        self._add_defaults_data_files()\n        self._add_defaults_ext()\n        self._add_defaults_c_libs()\n        self._add_defaults_scripts()\n\n    @staticmethod\n    def _cs_path_exists(fspath):\n        \"\"\"\n        Case-sensitive path existence check\n\n        >>> sdist_add_defaults._cs_path_exists(__file__)\n        True\n        >>> sdist_add_defaults._cs_path_exists(__file__.upper())\n        False\n        \"\"\"\n        if not os.path.exists(fspath):\n            return False\n        # make absolute so we always have a directory\n        abspath = os.path.abspath(fspath)\n        directory, filename = os.path.split(abspath)\n        return filename in os.listdir(directory)\n\n    def _add_defaults_standards(self):\n        standards = [self.READMES, self.distribution.script_name]\n        for fn in standards:\n            if isinstance(fn, tuple):\n                alts = fn\n                got_it = False\n                for fn in alts:\n                    if self._cs_path_exists(fn):\n                        got_it = True\n                        self.filelist.append(fn)\n                        break\n\n                if not got_it:\n                    self.warn(\"standard file not found: should have one of \" +\n                              ', '.join(alts))\n            else:\n                if self._cs_path_exists(fn):\n                    self.filelist.append(fn)\n                else:\n                    self.warn(\"standard file '%s' not found\" % fn)\n\n    def _add_defaults_optional(self):\n        optional = ['test/test*.py', 'setup.cfg']\n        for pattern in optional:\n            files = filter(os.path.isfile, glob(pattern))\n            self.filelist.extend(files)\n\n    def _add_defaults_python(self):\n        # build_py is used to get:\n        #  - python modules\n        #  - files defined in package_data\n        build_py = self.get_finalized_command('build_py')\n\n        # getting python files\n        if self.distribution.has_pure_modules():\n            self.filelist.extend(build_py.get_source_files())\n\n        # getting package_data files\n        # (computed in build_py.data_files by build_py.finalize_options)\n        for pkg, src_dir, build_dir, filenames in build_py.data_files:\n            for filename in filenames:\n                self.filelist.append(os.path.join(src_dir, filename))\n\n    def _add_defaults_data_files(self):\n        # getting distribution.data_files\n        if self.distribution.has_data_files():\n            for item in self.distribution.data_files:\n                if isinstance(item, str):\n                    # plain file\n                    item = convert_path(item)\n                    if os.path.isfile(item):\n                        self.filelist.append(item)\n                else:\n                    # a (dirname, filenames) tuple\n                    dirname, filenames = item\n                    for f in filenames:\n                        f = convert_path(f)\n                        if os.path.isfile(f):\n                            self.filelist.append(f)\n\n    def _add_defaults_ext(self):\n        if self.distribution.has_ext_modules():\n            build_ext = self.get_finalized_command('build_ext')\n            self.filelist.extend(build_ext.get_source_files())\n\n    def _add_defaults_c_libs(self):\n        if self.distribution.has_c_libraries():\n            build_clib = self.get_finalized_command('build_clib')\n            self.filelist.extend(build_clib.get_source_files())\n\n    def _add_defaults_scripts(self):\n        if self.distribution.has_scripts():\n            build_scripts = self.get_finalized_command('build_scripts')\n            self.filelist.extend(build_scripts.get_source_files())\n\n\nif hasattr(sdist.sdist, '_add_defaults_standards'):\n    # disable the functionality already available upstream\n    class sdist_add_defaults:  # noqa\n        pass\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/register.py",
    "content": "from distutils import log\nimport distutils.command.register as orig\n\nfrom setuptools.errors import RemovedCommandError\n\n\nclass register(orig.register):\n    \"\"\"Formerly used to register packages on PyPI.\"\"\"\n\n    def run(self):\n        msg = (\n            \"The register command has been removed, use twine to upload \"\n            + \"instead (https://pypi.org/p/twine)\"\n        )\n\n        self.announce(\"ERROR: \" + msg, log.ERROR)\n\n        raise RemovedCommandError(msg)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/rotate.py",
    "content": "from distutils.util import convert_path\nfrom distutils import log\nfrom distutils.errors import DistutilsOptionError\nimport os\nimport shutil\n\nfrom setuptools import Command\n\n\nclass rotate(Command):\n    \"\"\"Delete older distributions\"\"\"\n\n    description = \"delete older distributions, keeping N newest files\"\n    user_options = [\n        ('match=', 'm', \"patterns to match (required)\"),\n        ('dist-dir=', 'd', \"directory where the distributions are\"),\n        ('keep=', 'k', \"number of matching distributions to keep\"),\n    ]\n\n    boolean_options = []\n\n    def initialize_options(self):\n        self.match = None\n        self.dist_dir = None\n        self.keep = None\n\n    def finalize_options(self):\n        if self.match is None:\n            raise DistutilsOptionError(\n                \"Must specify one or more (comma-separated) match patterns \"\n                \"(e.g. '.zip' or '.egg')\"\n            )\n        if self.keep is None:\n            raise DistutilsOptionError(\"Must specify number of files to keep\")\n        try:\n            self.keep = int(self.keep)\n        except ValueError as e:\n            raise DistutilsOptionError(\"--keep must be an integer\") from e\n        if isinstance(self.match, str):\n            self.match = [\n                convert_path(p.strip()) for p in self.match.split(',')\n            ]\n        self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'))\n\n    def run(self):\n        self.run_command(\"egg_info\")\n        from glob import glob\n\n        for pattern in self.match:\n            pattern = self.distribution.get_name() + '*' + pattern\n            files = glob(os.path.join(self.dist_dir, pattern))\n            files = [(os.path.getmtime(f), f) for f in files]\n            files.sort()\n            files.reverse()\n\n            log.info(\"%d file(s) matching %s\", len(files), pattern)\n            files = files[self.keep:]\n            for (t, f) in files:\n                log.info(\"Deleting %s\", f)\n                if not self.dry_run:\n                    if os.path.isdir(f):\n                        shutil.rmtree(f)\n                    else:\n                        os.unlink(f)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/saveopts.py",
    "content": "from setuptools.command.setopt import edit_config, option_base\n\n\nclass saveopts(option_base):\n    \"\"\"Save command-line options to a file\"\"\"\n\n    description = \"save supplied options to setup.cfg or other config file\"\n\n    def run(self):\n        dist = self.distribution\n        settings = {}\n\n        for cmd in dist.command_options:\n\n            if cmd == 'saveopts':\n                continue  # don't save our own options!\n\n            for opt, (src, val) in dist.get_option_dict(cmd).items():\n                if src == \"command line\":\n                    settings.setdefault(cmd, {})[opt] = val\n\n        edit_config(self.filename, settings, self.dry_run)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/sdist.py",
    "content": "from distutils import log\nimport distutils.command.sdist as orig\nimport os\nimport sys\nimport io\nimport contextlib\nfrom itertools import chain\n\nfrom .py36compat import sdist_add_defaults\n\nfrom .._importlib import metadata\nfrom .build import _ORIGINAL_SUBCOMMANDS\n\n_default_revctrl = list\n\n\ndef walk_revctrl(dirname=''):\n    \"\"\"Find all files under revision control\"\"\"\n    for ep in metadata.entry_points(group='setuptools.file_finders'):\n        for item in ep.load()(dirname):\n            yield item\n\n\nclass sdist(sdist_add_defaults, orig.sdist):\n    \"\"\"Smart sdist that finds anything supported by revision control\"\"\"\n\n    user_options = [\n        ('formats=', None,\n         \"formats for source distribution (comma-separated list)\"),\n        ('keep-temp', 'k',\n         \"keep the distribution tree around after creating \" +\n         \"archive file(s)\"),\n        ('dist-dir=', 'd',\n         \"directory to put the source distribution archive(s) in \"\n         \"[default: dist]\"),\n        ('owner=', 'u',\n         \"Owner name used when creating a tar file [default: current user]\"),\n        ('group=', 'g',\n         \"Group name used when creating a tar file [default: current group]\"),\n    ]\n\n    negative_opt = {}\n\n    README_EXTENSIONS = ['', '.rst', '.txt', '.md']\n    READMES = tuple('README{0}'.format(ext) for ext in README_EXTENSIONS)\n\n    def run(self):\n        self.run_command('egg_info')\n        ei_cmd = self.get_finalized_command('egg_info')\n        self.filelist = ei_cmd.filelist\n        self.filelist.append(os.path.join(ei_cmd.egg_info, 'SOURCES.txt'))\n        self.check_readme()\n\n        # Run sub commands\n        for cmd_name in self.get_sub_commands():\n            self.run_command(cmd_name)\n\n        self.make_distribution()\n\n        dist_files = getattr(self.distribution, 'dist_files', [])\n        for file in self.archive_files:\n            data = ('sdist', '', file)\n            if data not in dist_files:\n                dist_files.append(data)\n\n    def initialize_options(self):\n        orig.sdist.initialize_options(self)\n\n        self._default_to_gztar()\n\n    def _default_to_gztar(self):\n        # only needed on Python prior to 3.6.\n        if sys.version_info >= (3, 6, 0, 'beta', 1):\n            return\n        self.formats = ['gztar']\n\n    def make_distribution(self):\n        \"\"\"\n        Workaround for #516\n        \"\"\"\n        with self._remove_os_link():\n            orig.sdist.make_distribution(self)\n\n    @staticmethod\n    @contextlib.contextmanager\n    def _remove_os_link():\n        \"\"\"\n        In a context, remove and restore os.link if it exists\n        \"\"\"\n\n        class NoValue:\n            pass\n\n        orig_val = getattr(os, 'link', NoValue)\n        try:\n            del os.link\n        except Exception:\n            pass\n        try:\n            yield\n        finally:\n            if orig_val is not NoValue:\n                setattr(os, 'link', orig_val)\n\n    def add_defaults(self):\n        super().add_defaults()\n        self._add_defaults_build_sub_commands()\n\n    def _add_defaults_optional(self):\n        super()._add_defaults_optional()\n        if os.path.isfile('pyproject.toml'):\n            self.filelist.append('pyproject.toml')\n\n    def _add_defaults_python(self):\n        \"\"\"getting python files\"\"\"\n        if self.distribution.has_pure_modules():\n            build_py = self.get_finalized_command('build_py')\n            self.filelist.extend(build_py.get_source_files())\n            self._add_data_files(self._safe_data_files(build_py))\n\n    def _add_defaults_build_sub_commands(self):\n        build = self.get_finalized_command(\"build\")\n        missing_cmds = set(build.get_sub_commands()) - _ORIGINAL_SUBCOMMANDS\n        # ^-- the original built-in sub-commands are already handled by default.\n        cmds = (self.get_finalized_command(c) for c in missing_cmds)\n        files = (c.get_source_files() for c in cmds if hasattr(c, \"get_source_files\"))\n        self.filelist.extend(chain.from_iterable(files))\n\n    def _safe_data_files(self, build_py):\n        \"\"\"\n        Since the ``sdist`` class is also used to compute the MANIFEST\n        (via :obj:`setuptools.command.egg_info.manifest_maker`),\n        there might be recursion problems when trying to obtain the list of\n        data_files and ``include_package_data=True`` (which in turn depends on\n        the files included in the MANIFEST).\n\n        To avoid that, ``manifest_maker`` should be able to overwrite this\n        method and avoid recursive attempts to build/analyze the MANIFEST.\n        \"\"\"\n        return build_py.data_files\n\n    def _add_data_files(self, data_files):\n        \"\"\"\n        Add data files as found in build_py.data_files.\n        \"\"\"\n        self.filelist.extend(\n            os.path.join(src_dir, name)\n            for _, src_dir, _, filenames in data_files\n            for name in filenames\n        )\n\n    def _add_defaults_data_files(self):\n        try:\n            super()._add_defaults_data_files()\n        except TypeError:\n            log.warn(\"data_files contains unexpected objects\")\n\n    def check_readme(self):\n        for f in self.READMES:\n            if os.path.exists(f):\n                return\n        else:\n            self.warn(\n                \"standard file not found: should have one of \" +\n                ', '.join(self.READMES)\n            )\n\n    def make_release_tree(self, base_dir, files):\n        orig.sdist.make_release_tree(self, base_dir, files)\n\n        # Save any egg_info command line options used to create this sdist\n        dest = os.path.join(base_dir, 'setup.cfg')\n        if hasattr(os, 'link') and os.path.exists(dest):\n            # unlink and re-copy, since it might be hard-linked, and\n            # we don't want to change the source version\n            os.unlink(dest)\n            self.copy_file('setup.cfg', dest)\n\n        self.get_finalized_command('egg_info').save_version_info(dest)\n\n    def _manifest_is_not_generated(self):\n        # check for special comment used in 2.7.1 and higher\n        if not os.path.isfile(self.manifest):\n            return False\n\n        with io.open(self.manifest, 'rb') as fp:\n            first_line = fp.readline()\n        return (first_line !=\n                '# file GENERATED by distutils, do NOT edit\\n'.encode())\n\n    def read_manifest(self):\n        \"\"\"Read the manifest file (named by 'self.manifest') and use it to\n        fill in 'self.filelist', the list of files to include in the source\n        distribution.\n        \"\"\"\n        log.info(\"reading manifest file '%s'\", self.manifest)\n        manifest = open(self.manifest, 'rb')\n        for line in manifest:\n            # The manifest must contain UTF-8. See #303.\n            try:\n                line = line.decode('UTF-8')\n            except UnicodeDecodeError:\n                log.warn(\"%r not UTF-8 decodable -- skipping\" % line)\n                continue\n            # ignore comments and blank lines\n            line = line.strip()\n            if line.startswith('#') or not line:\n                continue\n            self.filelist.append(line)\n        manifest.close()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/setopt.py",
    "content": "from distutils.util import convert_path\nfrom distutils import log\nfrom distutils.errors import DistutilsOptionError\nimport distutils\nimport os\nimport configparser\n\nfrom setuptools import Command\n\n__all__ = ['config_file', 'edit_config', 'option_base', 'setopt']\n\n\ndef config_file(kind=\"local\"):\n    \"\"\"Get the filename of the distutils, local, global, or per-user config\n\n    `kind` must be one of \"local\", \"global\", or \"user\"\n    \"\"\"\n    if kind == 'local':\n        return 'setup.cfg'\n    if kind == 'global':\n        return os.path.join(\n            os.path.dirname(distutils.__file__), 'distutils.cfg'\n        )\n    if kind == 'user':\n        dot = os.name == 'posix' and '.' or ''\n        return os.path.expanduser(convert_path(\"~/%spydistutils.cfg\" % dot))\n    raise ValueError(\n        \"config_file() type must be 'local', 'global', or 'user'\", kind\n    )\n\n\ndef edit_config(filename, settings, dry_run=False):\n    \"\"\"Edit a configuration file to include `settings`\n\n    `settings` is a dictionary of dictionaries or ``None`` values, keyed by\n    command/section name.  A ``None`` value means to delete the entire section,\n    while a dictionary lists settings to be changed or deleted in that section.\n    A setting of ``None`` means to delete that setting.\n    \"\"\"\n    log.debug(\"Reading configuration from %s\", filename)\n    opts = configparser.RawConfigParser()\n    opts.optionxform = lambda x: x\n    opts.read([filename])\n    for section, options in settings.items():\n        if options is None:\n            log.info(\"Deleting section [%s] from %s\", section, filename)\n            opts.remove_section(section)\n        else:\n            if not opts.has_section(section):\n                log.debug(\"Adding new section [%s] to %s\", section, filename)\n                opts.add_section(section)\n            for option, value in options.items():\n                if value is None:\n                    log.debug(\n                        \"Deleting %s.%s from %s\",\n                        section, option, filename\n                    )\n                    opts.remove_option(section, option)\n                    if not opts.options(section):\n                        log.info(\"Deleting empty [%s] section from %s\",\n                                 section, filename)\n                        opts.remove_section(section)\n                else:\n                    log.debug(\n                        \"Setting %s.%s to %r in %s\",\n                        section, option, value, filename\n                    )\n                    opts.set(section, option, value)\n\n    log.info(\"Writing %s\", filename)\n    if not dry_run:\n        with open(filename, 'w') as f:\n            opts.write(f)\n\n\nclass option_base(Command):\n    \"\"\"Abstract base class for commands that mess with config files\"\"\"\n\n    user_options = [\n        ('global-config', 'g',\n         \"save options to the site-wide distutils.cfg file\"),\n        ('user-config', 'u',\n         \"save options to the current user's pydistutils.cfg file\"),\n        ('filename=', 'f',\n         \"configuration file to use (default=setup.cfg)\"),\n    ]\n\n    boolean_options = [\n        'global-config', 'user-config',\n    ]\n\n    def initialize_options(self):\n        self.global_config = None\n        self.user_config = None\n        self.filename = None\n\n    def finalize_options(self):\n        filenames = []\n        if self.global_config:\n            filenames.append(config_file('global'))\n        if self.user_config:\n            filenames.append(config_file('user'))\n        if self.filename is not None:\n            filenames.append(self.filename)\n        if not filenames:\n            filenames.append(config_file('local'))\n        if len(filenames) > 1:\n            raise DistutilsOptionError(\n                \"Must specify only one configuration file option\",\n                filenames\n            )\n        self.filename, = filenames\n\n\nclass setopt(option_base):\n    \"\"\"Save command-line options to a file\"\"\"\n\n    description = \"set an option in setup.cfg or another config file\"\n\n    user_options = [\n        ('command=', 'c', 'command to set an option for'),\n        ('option=', 'o', 'option to set'),\n        ('set-value=', 's', 'value of the option'),\n        ('remove', 'r', 'remove (unset) the value'),\n    ] + option_base.user_options\n\n    boolean_options = option_base.boolean_options + ['remove']\n\n    def initialize_options(self):\n        option_base.initialize_options(self)\n        self.command = None\n        self.option = None\n        self.set_value = None\n        self.remove = None\n\n    def finalize_options(self):\n        option_base.finalize_options(self)\n        if self.command is None or self.option is None:\n            raise DistutilsOptionError(\"Must specify --command *and* --option\")\n        if self.set_value is None and not self.remove:\n            raise DistutilsOptionError(\"Must specify --set-value or --remove\")\n\n    def run(self):\n        edit_config(\n            self.filename, {\n                self.command: {self.option.replace('-', '_'): self.set_value}\n            },\n            self.dry_run\n        )\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/test.py",
    "content": "import os\nimport operator\nimport sys\nimport contextlib\nimport itertools\nimport unittest\nfrom distutils.errors import DistutilsError, DistutilsOptionError\nfrom distutils import log\nfrom unittest import TestLoader\n\nfrom pkg_resources import (\n    resource_listdir,\n    resource_exists,\n    normalize_path,\n    working_set,\n    evaluate_marker,\n    add_activation_listener,\n    require,\n)\nfrom .._importlib import metadata\nfrom setuptools import Command\nfrom setuptools.extern.more_itertools import unique_everseen\nfrom setuptools.extern.jaraco.functools import pass_none\n\n\nclass ScanningLoader(TestLoader):\n    def __init__(self):\n        TestLoader.__init__(self)\n        self._visited = set()\n\n    def loadTestsFromModule(self, module, pattern=None):\n        \"\"\"Return a suite of all tests cases contained in the given module\n\n        If the module is a package, load tests from all the modules in it.\n        If the module has an ``additional_tests`` function, call it and add\n        the return value to the tests.\n        \"\"\"\n        if module in self._visited:\n            return None\n        self._visited.add(module)\n\n        tests = []\n        tests.append(TestLoader.loadTestsFromModule(self, module))\n\n        if hasattr(module, \"additional_tests\"):\n            tests.append(module.additional_tests())\n\n        if hasattr(module, '__path__'):\n            for file in resource_listdir(module.__name__, ''):\n                if file.endswith('.py') and file != '__init__.py':\n                    submodule = module.__name__ + '.' + file[:-3]\n                else:\n                    if resource_exists(module.__name__, file + '/__init__.py'):\n                        submodule = module.__name__ + '.' + file\n                    else:\n                        continue\n                tests.append(self.loadTestsFromName(submodule))\n\n        if len(tests) != 1:\n            return self.suiteClass(tests)\n        else:\n            return tests[0]  # don't create a nested suite for only one return\n\n\n# adapted from jaraco.classes.properties:NonDataProperty\nclass NonDataProperty:\n    def __init__(self, fget):\n        self.fget = fget\n\n    def __get__(self, obj, objtype=None):\n        if obj is None:\n            return self\n        return self.fget(obj)\n\n\nclass test(Command):\n    \"\"\"Command to run unit tests after in-place build\"\"\"\n\n    description = \"run unit tests after in-place build (deprecated)\"\n\n    user_options = [\n        ('test-module=', 'm', \"Run 'test_suite' in specified module\"),\n        (\n            'test-suite=',\n            's',\n            \"Run single test, case or suite (e.g. 'module.test_suite')\",\n        ),\n        ('test-runner=', 'r', \"Test runner to use\"),\n    ]\n\n    def initialize_options(self):\n        self.test_suite = None\n        self.test_module = None\n        self.test_loader = None\n        self.test_runner = None\n\n    def finalize_options(self):\n\n        if self.test_suite and self.test_module:\n            msg = \"You may specify a module or a suite, but not both\"\n            raise DistutilsOptionError(msg)\n\n        if self.test_suite is None:\n            if self.test_module is None:\n                self.test_suite = self.distribution.test_suite\n            else:\n                self.test_suite = self.test_module + \".test_suite\"\n\n        if self.test_loader is None:\n            self.test_loader = getattr(self.distribution, 'test_loader', None)\n        if self.test_loader is None:\n            self.test_loader = \"setuptools.command.test:ScanningLoader\"\n        if self.test_runner is None:\n            self.test_runner = getattr(self.distribution, 'test_runner', None)\n\n    @NonDataProperty\n    def test_args(self):\n        return list(self._test_args())\n\n    def _test_args(self):\n        if not self.test_suite:\n            yield 'discover'\n        if self.verbose:\n            yield '--verbose'\n        if self.test_suite:\n            yield self.test_suite\n\n    def with_project_on_sys_path(self, func):\n        \"\"\"\n        Backward compatibility for project_on_sys_path context.\n        \"\"\"\n        with self.project_on_sys_path():\n            func()\n\n    @contextlib.contextmanager\n    def project_on_sys_path(self, include_dists=[]):\n        self.run_command('egg_info')\n\n        # Build extensions in-place\n        self.reinitialize_command('build_ext', inplace=1)\n        self.run_command('build_ext')\n\n        ei_cmd = self.get_finalized_command(\"egg_info\")\n\n        old_path = sys.path[:]\n        old_modules = sys.modules.copy()\n\n        try:\n            project_path = normalize_path(ei_cmd.egg_base)\n            sys.path.insert(0, project_path)\n            working_set.__init__()\n            add_activation_listener(lambda dist: dist.activate())\n            require('%s==%s' % (ei_cmd.egg_name, ei_cmd.egg_version))\n            with self.paths_on_pythonpath([project_path]):\n                yield\n        finally:\n            sys.path[:] = old_path\n            sys.modules.clear()\n            sys.modules.update(old_modules)\n            working_set.__init__()\n\n    @staticmethod\n    @contextlib.contextmanager\n    def paths_on_pythonpath(paths):\n        \"\"\"\n        Add the indicated paths to the head of the PYTHONPATH environment\n        variable so that subprocesses will also see the packages at\n        these paths.\n\n        Do this in a context that restores the value on exit.\n        \"\"\"\n        nothing = object()\n        orig_pythonpath = os.environ.get('PYTHONPATH', nothing)\n        current_pythonpath = os.environ.get('PYTHONPATH', '')\n        try:\n            prefix = os.pathsep.join(unique_everseen(paths))\n            to_join = filter(None, [prefix, current_pythonpath])\n            new_path = os.pathsep.join(to_join)\n            if new_path:\n                os.environ['PYTHONPATH'] = new_path\n            yield\n        finally:\n            if orig_pythonpath is nothing:\n                os.environ.pop('PYTHONPATH', None)\n            else:\n                os.environ['PYTHONPATH'] = orig_pythonpath\n\n    @staticmethod\n    def install_dists(dist):\n        \"\"\"\n        Install the requirements indicated by self.distribution and\n        return an iterable of the dists that were built.\n        \"\"\"\n        ir_d = dist.fetch_build_eggs(dist.install_requires)\n        tr_d = dist.fetch_build_eggs(dist.tests_require or [])\n        er_d = dist.fetch_build_eggs(\n            v\n            for k, v in dist.extras_require.items()\n            if k.startswith(':') and evaluate_marker(k[1:])\n        )\n        return itertools.chain(ir_d, tr_d, er_d)\n\n    def run(self):\n        self.announce(\n            \"WARNING: Testing via this command is deprecated and will be \"\n            \"removed in a future version. Users looking for a generic test \"\n            \"entry point independent of test runner are encouraged to use \"\n            \"tox.\",\n            log.WARN,\n        )\n\n        installed_dists = self.install_dists(self.distribution)\n\n        cmd = ' '.join(self._argv)\n        if self.dry_run:\n            self.announce('skipping \"%s\" (dry run)' % cmd)\n            return\n\n        self.announce('running \"%s\"' % cmd)\n\n        paths = map(operator.attrgetter('location'), installed_dists)\n        with self.paths_on_pythonpath(paths):\n            with self.project_on_sys_path():\n                self.run_tests()\n\n    def run_tests(self):\n        test = unittest.main(\n            None,\n            None,\n            self._argv,\n            testLoader=self._resolve_as_ep(self.test_loader),\n            testRunner=self._resolve_as_ep(self.test_runner),\n            exit=False,\n        )\n        if not test.result.wasSuccessful():\n            msg = 'Test failed: %s' % test.result\n            self.announce(msg, log.ERROR)\n            raise DistutilsError(msg)\n\n    @property\n    def _argv(self):\n        return ['unittest'] + self.test_args\n\n    @staticmethod\n    @pass_none\n    def _resolve_as_ep(val):\n        \"\"\"\n        Load the indicated attribute value, called, as a as if it were\n        specified as an entry point.\n        \"\"\"\n        return metadata.EntryPoint(value=val, name=None, group=None).load()()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/upload.py",
    "content": "from distutils import log\nfrom distutils.command import upload as orig\n\nfrom setuptools.errors import RemovedCommandError\n\n\nclass upload(orig.upload):\n    \"\"\"Formerly used to upload packages to PyPI.\"\"\"\n\n    def run(self):\n        msg = (\n            \"The upload command has been removed, use twine to upload \"\n            + \"instead (https://pypi.org/p/twine)\"\n        )\n\n        self.announce(\"ERROR: \" + msg, log.ERROR)\n        raise RemovedCommandError(msg)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/command/upload_docs.py",
    "content": "# -*- coding: utf-8 -*-\n\"\"\"upload_docs\n\nImplements a Distutils 'upload_docs' subcommand (upload documentation to\nsites other than PyPi such as devpi).\n\"\"\"\n\nfrom base64 import standard_b64encode\nfrom distutils import log\nfrom distutils.errors import DistutilsOptionError\nimport os\nimport socket\nimport zipfile\nimport tempfile\nimport shutil\nimport itertools\nimport functools\nimport http.client\nimport urllib.parse\nimport warnings\n\nfrom .._importlib import metadata\nfrom .. import SetuptoolsDeprecationWarning\n\nfrom .upload import upload\n\n\ndef _encode(s):\n    return s.encode('utf-8', 'surrogateescape')\n\n\nclass upload_docs(upload):\n    # override the default repository as upload_docs isn't\n    # supported by Warehouse (and won't be).\n    DEFAULT_REPOSITORY = 'https://pypi.python.org/pypi/'\n\n    description = 'Upload documentation to sites other than PyPi such as devpi'\n\n    user_options = [\n        ('repository=', 'r',\n         \"url of repository [default: %s]\" % upload.DEFAULT_REPOSITORY),\n        ('show-response', None,\n         'display full response text from server'),\n        ('upload-dir=', None, 'directory to upload'),\n    ]\n    boolean_options = upload.boolean_options\n\n    def has_sphinx(self):\n        return bool(\n            self.upload_dir is None\n            and metadata.entry_points(group='distutils.commands', name='build_sphinx')\n        )\n\n    sub_commands = [('build_sphinx', has_sphinx)]\n\n    def initialize_options(self):\n        upload.initialize_options(self)\n        self.upload_dir = None\n        self.target_dir = None\n\n    def finalize_options(self):\n        log.warn(\n            \"Upload_docs command is deprecated. Use Read the Docs \"\n            \"(https://readthedocs.org) instead.\")\n        upload.finalize_options(self)\n        if self.upload_dir is None:\n            if self.has_sphinx():\n                build_sphinx = self.get_finalized_command('build_sphinx')\n                self.target_dir = dict(build_sphinx.builder_target_dirs)['html']\n            else:\n                build = self.get_finalized_command('build')\n                self.target_dir = os.path.join(build.build_base, 'docs')\n        else:\n            self.ensure_dirname('upload_dir')\n            self.target_dir = self.upload_dir\n        self.announce('Using upload directory %s' % self.target_dir)\n\n    def create_zipfile(self, filename):\n        zip_file = zipfile.ZipFile(filename, \"w\")\n        try:\n            self.mkpath(self.target_dir)  # just in case\n            for root, dirs, files in os.walk(self.target_dir):\n                if root == self.target_dir and not files:\n                    tmpl = \"no files found in upload directory '%s'\"\n                    raise DistutilsOptionError(tmpl % self.target_dir)\n                for name in files:\n                    full = os.path.join(root, name)\n                    relative = root[len(self.target_dir):].lstrip(os.path.sep)\n                    dest = os.path.join(relative, name)\n                    zip_file.write(full, dest)\n        finally:\n            zip_file.close()\n\n    def run(self):\n        warnings.warn(\n            \"upload_docs is deprecated and will be removed in a future \"\n            \"version. Use tools like httpie or curl instead.\",\n            SetuptoolsDeprecationWarning,\n        )\n\n        # Run sub commands\n        for cmd_name in self.get_sub_commands():\n            self.run_command(cmd_name)\n\n        tmp_dir = tempfile.mkdtemp()\n        name = self.distribution.metadata.get_name()\n        zip_file = os.path.join(tmp_dir, \"%s.zip\" % name)\n        try:\n            self.create_zipfile(zip_file)\n            self.upload_file(zip_file)\n        finally:\n            shutil.rmtree(tmp_dir)\n\n    @staticmethod\n    def _build_part(item, sep_boundary):\n        key, values = item\n        title = '\\nContent-Disposition: form-data; name=\"%s\"' % key\n        # handle multiple entries for the same name\n        if not isinstance(values, list):\n            values = [values]\n        for value in values:\n            if isinstance(value, tuple):\n                title += '; filename=\"%s\"' % value[0]\n                value = value[1]\n            else:\n                value = _encode(value)\n            yield sep_boundary\n            yield _encode(title)\n            yield b\"\\n\\n\"\n            yield value\n            if value and value[-1:] == b'\\r':\n                yield b'\\n'  # write an extra newline (lurve Macs)\n\n    @classmethod\n    def _build_multipart(cls, data):\n        \"\"\"\n        Build up the MIME payload for the POST data\n        \"\"\"\n        boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'\n        sep_boundary = b'\\n--' + boundary.encode('ascii')\n        end_boundary = sep_boundary + b'--'\n        end_items = end_boundary, b\"\\n\",\n        builder = functools.partial(\n            cls._build_part,\n            sep_boundary=sep_boundary,\n        )\n        part_groups = map(builder, data.items())\n        parts = itertools.chain.from_iterable(part_groups)\n        body_items = itertools.chain(parts, end_items)\n        content_type = 'multipart/form-data; boundary=%s' % boundary\n        return b''.join(body_items), content_type\n\n    def upload_file(self, filename):\n        with open(filename, 'rb') as f:\n            content = f.read()\n        meta = self.distribution.metadata\n        data = {\n            ':action': 'doc_upload',\n            'name': meta.get_name(),\n            'content': (os.path.basename(filename), content),\n        }\n        # set up the authentication\n        credentials = _encode(self.username + ':' + self.password)\n        credentials = standard_b64encode(credentials).decode('ascii')\n        auth = \"Basic \" + credentials\n\n        body, ct = self._build_multipart(data)\n\n        msg = \"Submitting documentation to %s\" % (self.repository)\n        self.announce(msg, log.INFO)\n\n        # build the Request\n        # We can't use urllib2 since we need to send the Basic\n        # auth right with the first request\n        schema, netloc, url, params, query, fragments = \\\n            urllib.parse.urlparse(self.repository)\n        assert not params and not query and not fragments\n        if schema == 'http':\n            conn = http.client.HTTPConnection(netloc)\n        elif schema == 'https':\n            conn = http.client.HTTPSConnection(netloc)\n        else:\n            raise AssertionError(\"unsupported schema \" + schema)\n\n        data = ''\n        try:\n            conn.connect()\n            conn.putrequest(\"POST\", url)\n            content_type = ct\n            conn.putheader('Content-type', content_type)\n            conn.putheader('Content-length', str(len(body)))\n            conn.putheader('Authorization', auth)\n            conn.endheaders()\n            conn.send(body)\n        except socket.error as e:\n            self.announce(str(e), log.ERROR)\n            return\n\n        r = conn.getresponse()\n        if r.status == 200:\n            msg = 'Server response (%s): %s' % (r.status, r.reason)\n            self.announce(msg, log.INFO)\n        elif r.status == 301:\n            location = r.getheader('Location')\n            if location is None:\n                location = 'https://pythonhosted.org/%s/' % meta.get_name()\n            msg = 'Upload successful. Visit %s' % location\n            self.announce(msg, log.INFO)\n        else:\n            msg = 'Upload failed (%s): %s' % (r.status, r.reason)\n            self.announce(msg, log.ERROR)\n        if self.show_response:\n            print('-' * 75, r.read(), '-' * 75)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/config/__init__.py",
    "content": "\"\"\"For backward compatibility, expose main functions from\n``setuptools.config.setupcfg``\n\"\"\"\nimport warnings\nfrom functools import wraps\nfrom textwrap import dedent\nfrom typing import Callable, TypeVar, cast\n\nfrom .._deprecation_warning import SetuptoolsDeprecationWarning\nfrom . import setupcfg\n\nFn = TypeVar(\"Fn\", bound=Callable)\n\n__all__ = ('parse_configuration', 'read_configuration')\n\n\ndef _deprecation_notice(fn: Fn) -> Fn:\n    @wraps(fn)\n    def _wrapper(*args, **kwargs):\n        msg = f\"\"\"\\\n        As setuptools moves its configuration towards `pyproject.toml`,\n        `{__name__}.{fn.__name__}` became deprecated.\n\n        For the time being, you can use the `{setupcfg.__name__}` module\n        to access a backward compatible API, but this module is provisional\n        and might be removed in the future.\n        \"\"\"\n        warnings.warn(dedent(msg), SetuptoolsDeprecationWarning, stacklevel=2)\n        return fn(*args, **kwargs)\n\n    return cast(Fn, _wrapper)\n\n\nread_configuration = _deprecation_notice(setupcfg.read_configuration)\nparse_configuration = _deprecation_notice(setupcfg.parse_configuration)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/config/_apply_pyprojecttoml.py",
    "content": "\"\"\"Translation layer between pyproject config and setuptools distribution and\nmetadata objects.\n\nThe distribution and metadata objects are modeled after (an old version of)\ncore metadata, therefore configs in the format specified for ``pyproject.toml``\nneed to be processed before being applied.\n\n**PRIVATE MODULE**: API reserved for setuptools internal usage only.\n\"\"\"\nimport logging\nimport os\nimport warnings\nfrom collections.abc import Mapping\nfrom email.headerregistry import Address\nfrom functools import partial, reduce\nfrom itertools import chain\nfrom types import MappingProxyType\nfrom typing import (TYPE_CHECKING, Any, Callable, Dict, List, Optional, Set, Tuple,\n                    Type, Union)\n\nfrom setuptools._deprecation_warning import SetuptoolsDeprecationWarning\n\nif TYPE_CHECKING:\n    from setuptools._importlib import metadata  # noqa\n    from setuptools.dist import Distribution  # noqa\n\nEMPTY: Mapping = MappingProxyType({})  # Immutable dict-like\n_Path = Union[os.PathLike, str]\n_DictOrStr = Union[dict, str]\n_CorrespFn = Callable[[\"Distribution\", Any, _Path], None]\n_Correspondence = Union[str, _CorrespFn]\n\n_logger = logging.getLogger(__name__)\n\n\ndef apply(dist: \"Distribution\", config: dict, filename: _Path) -> \"Distribution\":\n    \"\"\"Apply configuration dict read with :func:`read_configuration`\"\"\"\n\n    if not config:\n        return dist  # short-circuit unrelated pyproject.toml file\n\n    root_dir = os.path.dirname(filename) or \".\"\n\n    _apply_project_table(dist, config, root_dir)\n    _apply_tool_table(dist, config, filename)\n\n    current_directory = os.getcwd()\n    os.chdir(root_dir)\n    try:\n        dist._finalize_requires()\n        dist._finalize_license_files()\n    finally:\n        os.chdir(current_directory)\n\n    return dist\n\n\ndef _apply_project_table(dist: \"Distribution\", config: dict, root_dir: _Path):\n    project_table = config.get(\"project\", {}).copy()\n    if not project_table:\n        return  # short-circuit\n\n    _handle_missing_dynamic(dist, project_table)\n    _unify_entry_points(project_table)\n\n    for field, value in project_table.items():\n        norm_key = json_compatible_key(field)\n        corresp = PYPROJECT_CORRESPONDENCE.get(norm_key, norm_key)\n        if callable(corresp):\n            corresp(dist, value, root_dir)\n        else:\n            _set_config(dist, corresp, value)\n\n\ndef _apply_tool_table(dist: \"Distribution\", config: dict, filename: _Path):\n    tool_table = config.get(\"tool\", {}).get(\"setuptools\", {})\n    if not tool_table:\n        return  # short-circuit\n\n    for field, value in tool_table.items():\n        norm_key = json_compatible_key(field)\n\n        if norm_key in TOOL_TABLE_DEPRECATIONS:\n            suggestion = TOOL_TABLE_DEPRECATIONS[norm_key]\n            msg = f\"The parameter `{norm_key}` is deprecated, {suggestion}\"\n            warnings.warn(msg, SetuptoolsDeprecationWarning)\n\n        norm_key = TOOL_TABLE_RENAMES.get(norm_key, norm_key)\n        _set_config(dist, norm_key, value)\n\n    _copy_command_options(config, dist, filename)\n\n\ndef _handle_missing_dynamic(dist: \"Distribution\", project_table: dict):\n    \"\"\"Be temporarily forgiving with ``dynamic`` fields not listed in ``dynamic``\"\"\"\n    # TODO: Set fields back to `None` once the feature stabilizes\n    dynamic = set(project_table.get(\"dynamic\", []))\n    for field, getter in _PREVIOUSLY_DEFINED.items():\n        if not (field in project_table or field in dynamic):\n            value = getter(dist)\n            if value:\n                msg = _WouldIgnoreField.message(field, value)\n                warnings.warn(msg, _WouldIgnoreField)\n\n\ndef json_compatible_key(key: str) -> str:\n    \"\"\"As defined in :pep:`566#json-compatible-metadata`\"\"\"\n    return key.lower().replace(\"-\", \"_\")\n\n\ndef _set_config(dist: \"Distribution\", field: str, value: Any):\n    setter = getattr(dist.metadata, f\"set_{field}\", None)\n    if setter:\n        setter(value)\n    elif hasattr(dist.metadata, field) or field in SETUPTOOLS_PATCHES:\n        setattr(dist.metadata, field, value)\n    else:\n        setattr(dist, field, value)\n\n\n_CONTENT_TYPES = {\n    \".md\": \"text/markdown\",\n    \".rst\": \"text/x-rst\",\n    \".txt\": \"text/plain\",\n}\n\n\ndef _guess_content_type(file: str) -> Optional[str]:\n    _, ext = os.path.splitext(file.lower())\n    if not ext:\n        return None\n\n    if ext in _CONTENT_TYPES:\n        return _CONTENT_TYPES[ext]\n\n    valid = \", \".join(f\"{k} ({v})\" for k, v in _CONTENT_TYPES.items())\n    msg = f\"only the following file extensions are recognized: {valid}.\"\n    raise ValueError(f\"Undefined content type for {file}, {msg}\")\n\n\ndef _long_description(dist: \"Distribution\", val: _DictOrStr, root_dir: _Path):\n    from setuptools.config import expand\n\n    if isinstance(val, str):\n        text = expand.read_files(val, root_dir)\n        ctype = _guess_content_type(val)\n    else:\n        text = val.get(\"text\") or expand.read_files(val.get(\"file\", []), root_dir)\n        ctype = val[\"content-type\"]\n\n    _set_config(dist, \"long_description\", text)\n    if ctype:\n        _set_config(dist, \"long_description_content_type\", ctype)\n\n\ndef _license(dist: \"Distribution\", val: dict, root_dir: _Path):\n    from setuptools.config import expand\n\n    if \"file\" in val:\n        _set_config(dist, \"license\", expand.read_files([val[\"file\"]], root_dir))\n    else:\n        _set_config(dist, \"license\", val[\"text\"])\n\n\ndef _people(dist: \"Distribution\", val: List[dict], _root_dir: _Path, kind: str):\n    field = []\n    email_field = []\n    for person in val:\n        if \"name\" not in person:\n            email_field.append(person[\"email\"])\n        elif \"email\" not in person:\n            field.append(person[\"name\"])\n        else:\n            addr = Address(display_name=person[\"name\"], addr_spec=person[\"email\"])\n            email_field.append(str(addr))\n\n    if field:\n        _set_config(dist, kind, \", \".join(field))\n    if email_field:\n        _set_config(dist, f\"{kind}_email\", \", \".join(email_field))\n\n\ndef _project_urls(dist: \"Distribution\", val: dict, _root_dir):\n    _set_config(dist, \"project_urls\", val)\n\n\ndef _python_requires(dist: \"Distribution\", val: dict, _root_dir):\n    from setuptools.extern.packaging.specifiers import SpecifierSet\n\n    _set_config(dist, \"python_requires\", SpecifierSet(val))\n\n\ndef _dependencies(dist: \"Distribution\", val: list, _root_dir):\n    if getattr(dist, \"install_requires\", []):\n        msg = \"`install_requires` overwritten in `pyproject.toml` (dependencies)\"\n        warnings.warn(msg)\n    _set_config(dist, \"install_requires\", val)\n\n\ndef _optional_dependencies(dist: \"Distribution\", val: dict, _root_dir):\n    existing = getattr(dist, \"extras_require\", {})\n    _set_config(dist, \"extras_require\", {**existing, **val})\n\n\ndef _unify_entry_points(project_table: dict):\n    project = project_table\n    entry_points = project.pop(\"entry-points\", project.pop(\"entry_points\", {}))\n    renaming = {\"scripts\": \"console_scripts\", \"gui_scripts\": \"gui_scripts\"}\n    for key, value in list(project.items()):  # eager to allow modifications\n        norm_key = json_compatible_key(key)\n        if norm_key in renaming and value:\n            entry_points[renaming[norm_key]] = project.pop(key)\n\n    if entry_points:\n        project[\"entry-points\"] = {\n            name: [f\"{k} = {v}\" for k, v in group.items()]\n            for name, group in entry_points.items()\n        }\n\n\ndef _copy_command_options(pyproject: dict, dist: \"Distribution\", filename: _Path):\n    tool_table = pyproject.get(\"tool\", {})\n    cmdclass = tool_table.get(\"setuptools\", {}).get(\"cmdclass\", {})\n    valid_options = _valid_command_options(cmdclass)\n\n    cmd_opts = dist.command_options\n    for cmd, config in pyproject.get(\"tool\", {}).get(\"distutils\", {}).items():\n        cmd = json_compatible_key(cmd)\n        valid = valid_options.get(cmd, set())\n        cmd_opts.setdefault(cmd, {})\n        for key, value in config.items():\n            key = json_compatible_key(key)\n            cmd_opts[cmd][key] = (str(filename), value)\n            if key not in valid:\n                # To avoid removing options that are specified dynamically we\n                # just log a warn...\n                _logger.warning(f\"Command option {cmd}.{key} is not defined\")\n\n\ndef _valid_command_options(cmdclass: Mapping = EMPTY) -> Dict[str, Set[str]]:\n    from .._importlib import metadata\n    from setuptools.dist import Distribution\n\n    valid_options = {\"global\": _normalise_cmd_options(Distribution.global_options)}\n\n    unloaded_entry_points = metadata.entry_points(group='distutils.commands')\n    loaded_entry_points = (_load_ep(ep) for ep in unloaded_entry_points)\n    entry_points = (ep for ep in loaded_entry_points if ep)\n    for cmd, cmd_class in chain(entry_points, cmdclass.items()):\n        opts = valid_options.get(cmd, set())\n        opts = opts | _normalise_cmd_options(getattr(cmd_class, \"user_options\", []))\n        valid_options[cmd] = opts\n\n    return valid_options\n\n\ndef _load_ep(ep: \"metadata.EntryPoint\") -> Optional[Tuple[str, Type]]:\n    # Ignore all the errors\n    try:\n        return (ep.name, ep.load())\n    except Exception as ex:\n        msg = f\"{ex.__class__.__name__} while trying to load entry-point {ep.name}\"\n        _logger.warning(f\"{msg}: {ex}\")\n        return None\n\n\ndef _normalise_cmd_option_key(name: str) -> str:\n    return json_compatible_key(name).strip(\"_=\")\n\n\ndef _normalise_cmd_options(desc: List[Tuple[str, Optional[str], str]]) -> Set[str]:\n    return {_normalise_cmd_option_key(fancy_option[0]) for fancy_option in desc}\n\n\ndef _attrgetter(attr):\n    \"\"\"\n    Similar to ``operator.attrgetter`` but returns None if ``attr`` is not found\n    >>> from types import SimpleNamespace\n    >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13))\n    >>> _attrgetter(\"a\")(obj)\n    42\n    >>> _attrgetter(\"b.c\")(obj)\n    13\n    >>> _attrgetter(\"d\")(obj) is None\n    True\n    \"\"\"\n    return partial(reduce, lambda acc, x: getattr(acc, x, None), attr.split(\".\"))\n\n\ndef _some_attrgetter(*items):\n    \"\"\"\n    Return the first \"truth-y\" attribute or None\n    >>> from types import SimpleNamespace\n    >>> obj = SimpleNamespace(a=42, b=SimpleNamespace(c=13))\n    >>> _some_attrgetter(\"d\", \"a\", \"b.c\")(obj)\n    42\n    >>> _some_attrgetter(\"d\", \"e\", \"b.c\", \"a\")(obj)\n    13\n    >>> _some_attrgetter(\"d\", \"e\", \"f\")(obj) is None\n    True\n    \"\"\"\n    def _acessor(obj):\n        values = (_attrgetter(i)(obj) for i in items)\n        return next((i for i in values if i is not None), None)\n    return _acessor\n\n\nPYPROJECT_CORRESPONDENCE: Dict[str, _Correspondence] = {\n    \"readme\": _long_description,\n    \"license\": _license,\n    \"authors\": partial(_people, kind=\"author\"),\n    \"maintainers\": partial(_people, kind=\"maintainer\"),\n    \"urls\": _project_urls,\n    \"dependencies\": _dependencies,\n    \"optional_dependencies\": _optional_dependencies,\n    \"requires_python\": _python_requires,\n}\n\nTOOL_TABLE_RENAMES = {\"script_files\": \"scripts\"}\nTOOL_TABLE_DEPRECATIONS = {\n    \"namespace_packages\": \"consider using implicit namespaces instead (PEP 420).\"\n}\n\nSETUPTOOLS_PATCHES = {\"long_description_content_type\", \"project_urls\",\n                      \"provides_extras\", \"license_file\", \"license_files\"}\n\n_PREVIOUSLY_DEFINED = {\n    \"name\": _attrgetter(\"metadata.name\"),\n    \"version\": _attrgetter(\"metadata.version\"),\n    \"description\": _attrgetter(\"metadata.description\"),\n    \"readme\": _attrgetter(\"metadata.long_description\"),\n    \"requires-python\": _some_attrgetter(\"python_requires\", \"metadata.python_requires\"),\n    \"license\": _attrgetter(\"metadata.license\"),\n    \"authors\": _some_attrgetter(\"metadata.author\", \"metadata.author_email\"),\n    \"maintainers\": _some_attrgetter(\"metadata.maintainer\", \"metadata.maintainer_email\"),\n    \"keywords\": _attrgetter(\"metadata.keywords\"),\n    \"classifiers\": _attrgetter(\"metadata.classifiers\"),\n    \"urls\": _attrgetter(\"metadata.project_urls\"),\n    \"entry-points\": _attrgetter(\"entry_points\"),\n    \"dependencies\": _some_attrgetter(\"_orig_install_requires\", \"install_requires\"),\n    \"optional-dependencies\": _some_attrgetter(\"_orig_extras_require\", \"extras_require\"),\n}\n\n\nclass _WouldIgnoreField(UserWarning):\n    \"\"\"Inform users that ``pyproject.toml`` would overwrite previous metadata.\"\"\"\n\n    MESSAGE = \"\"\"\\\n    {field!r} defined outside of `pyproject.toml` would be ignored.\n    !!\\n\\n\n    ##########################################################################\n    # configuration would be ignored/result in error due to `pyproject.toml` #\n    ##########################################################################\n\n    The following seems to be defined outside of `pyproject.toml`:\n\n    `{field} = {value!r}`\n\n    According to the spec (see the link below), however, setuptools CANNOT\n    consider this value unless {field!r} is listed as `dynamic`.\n\n    https://packaging.python.org/en/latest/specifications/declaring-project-metadata/\n\n    For the time being, `setuptools` will still consider the given value (as a\n    **transitional** measure), but please note that future releases of setuptools will\n    follow strictly the standard.\n\n    To prevent this warning, you can list {field!r} under `dynamic` or alternatively\n    remove the `[project]` table from your file and rely entirely on other means of\n    configuration.\n    \\n\\n!!\n    \"\"\"\n\n    @classmethod\n    def message(cls, field, value):\n        from inspect import cleandoc\n        return cleandoc(cls.MESSAGE.format(field=field, value=value))\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/config/_validate_pyproject/__init__.py",
    "content": "from functools import reduce\nfrom typing import Any, Callable, Dict\n\nfrom . import formats\nfrom .error_reporting import detailed_errors, ValidationError\nfrom .extra_validations import EXTRA_VALIDATIONS\nfrom .fastjsonschema_exceptions import JsonSchemaException, JsonSchemaValueException\nfrom .fastjsonschema_validations import validate as _validate\n\n__all__ = [\n    \"validate\",\n    \"FORMAT_FUNCTIONS\",\n    \"EXTRA_VALIDATIONS\",\n    \"ValidationError\",\n    \"JsonSchemaException\",\n    \"JsonSchemaValueException\",\n]\n\n\nFORMAT_FUNCTIONS: Dict[str, Callable[[str], bool]] = {\n    fn.__name__.replace(\"_\", \"-\"): fn\n    for fn in formats.__dict__.values()\n    if callable(fn) and not fn.__name__.startswith(\"_\")\n}\n\n\ndef validate(data: Any) -> bool:\n    \"\"\"Validate the given ``data`` object using JSON Schema\n    This function raises ``ValidationError`` if ``data`` is invalid.\n    \"\"\"\n    with detailed_errors():\n        _validate(data, custom_formats=FORMAT_FUNCTIONS)\n    reduce(lambda acc, fn: fn(acc), EXTRA_VALIDATIONS, data)\n    return True\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/config/_validate_pyproject/error_reporting.py",
    "content": "import io\nimport json\nimport logging\nimport os\nimport re\nfrom contextlib import contextmanager\nfrom textwrap import indent, wrap\nfrom typing import Any, Dict, Iterator, List, Optional, Sequence, Union, cast\n\nfrom .fastjsonschema_exceptions import JsonSchemaValueException\n\n_logger = logging.getLogger(__name__)\n\n_MESSAGE_REPLACEMENTS = {\n    \"must be named by propertyName definition\": \"keys must be named by\",\n    \"one of contains definition\": \"at least one item that matches\",\n    \" same as const definition:\": \"\",\n    \"only specified items\": \"only items matching the definition\",\n}\n\n_SKIP_DETAILS = (\n    \"must not be empty\",\n    \"is always invalid\",\n    \"must not be there\",\n)\n\n_NEED_DETAILS = {\"anyOf\", \"oneOf\", \"anyOf\", \"contains\", \"propertyNames\", \"not\", \"items\"}\n\n_CAMEL_CASE_SPLITTER = re.compile(r\"\\W+|([A-Z][^A-Z\\W]*)\")\n_IDENTIFIER = re.compile(r\"^[\\w_]+$\", re.I)\n\n_TOML_JARGON = {\n    \"object\": \"table\",\n    \"property\": \"key\",\n    \"properties\": \"keys\",\n    \"property names\": \"keys\",\n}\n\n\nclass ValidationError(JsonSchemaValueException):\n    \"\"\"Report violations of a given JSON schema.\n\n    This class extends :exc:`~fastjsonschema.JsonSchemaValueException`\n    by adding the following properties:\n\n    - ``summary``: an improved version of the ``JsonSchemaValueException`` error message\n      with only the necessary information)\n\n    - ``details``: more contextual information about the error like the failing schema\n      itself and the value that violates the schema.\n\n    Depending on the level of the verbosity of the ``logging`` configuration\n    the exception message will be only ``summary`` (default) or a combination of\n    ``summary`` and ``details`` (when the logging level is set to :obj:`logging.DEBUG`).\n    \"\"\"\n\n    summary = \"\"\n    details = \"\"\n    _original_message = \"\"\n\n    @classmethod\n    def _from_jsonschema(cls, ex: JsonSchemaValueException):\n        formatter = _ErrorFormatting(ex)\n        obj = cls(str(formatter), ex.value, formatter.name, ex.definition, ex.rule)\n        debug_code = os.getenv(\"JSONSCHEMA_DEBUG_CODE_GENERATION\", \"false\").lower()\n        if debug_code != \"false\":  # pragma: no cover\n            obj.__cause__, obj.__traceback__ = ex.__cause__, ex.__traceback__\n        obj._original_message = ex.message\n        obj.summary = formatter.summary\n        obj.details = formatter.details\n        return obj\n\n\n@contextmanager\ndef detailed_errors():\n    try:\n        yield\n    except JsonSchemaValueException as ex:\n        raise ValidationError._from_jsonschema(ex) from None\n\n\nclass _ErrorFormatting:\n    def __init__(self, ex: JsonSchemaValueException):\n        self.ex = ex\n        self.name = f\"`{self._simplify_name(ex.name)}`\"\n        self._original_message = self.ex.message.replace(ex.name, self.name)\n        self._summary = \"\"\n        self._details = \"\"\n\n    def __str__(self) -> str:\n        if _logger.getEffectiveLevel() <= logging.DEBUG and self.details:\n            return f\"{self.summary}\\n\\n{self.details}\"\n\n        return self.summary\n\n    @property\n    def summary(self) -> str:\n        if not self._summary:\n            self._summary = self._expand_summary()\n\n        return self._summary\n\n    @property\n    def details(self) -> str:\n        if not self._details:\n            self._details = self._expand_details()\n\n        return self._details\n\n    def _simplify_name(self, name):\n        x = len(\"data.\")\n        return name[x:] if name.startswith(\"data.\") else name\n\n    def _expand_summary(self):\n        msg = self._original_message\n\n        for bad, repl in _MESSAGE_REPLACEMENTS.items():\n            msg = msg.replace(bad, repl)\n\n        if any(substring in msg for substring in _SKIP_DETAILS):\n            return msg\n\n        schema = self.ex.rule_definition\n        if self.ex.rule in _NEED_DETAILS and schema:\n            summary = _SummaryWriter(_TOML_JARGON)\n            return f\"{msg}:\\n\\n{indent(summary(schema), '    ')}\"\n\n        return msg\n\n    def _expand_details(self) -> str:\n        optional = []\n        desc_lines = self.ex.definition.pop(\"$$description\", [])\n        desc = self.ex.definition.pop(\"description\", None) or \" \".join(desc_lines)\n        if desc:\n            description = \"\\n\".join(\n                wrap(\n                    desc,\n                    width=80,\n                    initial_indent=\"    \",\n                    subsequent_indent=\"    \",\n                    break_long_words=False,\n                )\n            )\n            optional.append(f\"DESCRIPTION:\\n{description}\")\n        schema = json.dumps(self.ex.definition, indent=4)\n        value = json.dumps(self.ex.value, indent=4)\n        defaults = [\n            f\"GIVEN VALUE:\\n{indent(value, '    ')}\",\n            f\"OFFENDING RULE: {self.ex.rule!r}\",\n            f\"DEFINITION:\\n{indent(schema, '    ')}\",\n        ]\n        return \"\\n\\n\".join(optional + defaults)\n\n\nclass _SummaryWriter:\n    _IGNORE = {\"description\", \"default\", \"title\", \"examples\"}\n\n    def __init__(self, jargon: Optional[Dict[str, str]] = None):\n        self.jargon: Dict[str, str] = jargon or {}\n        # Clarify confusing terms\n        self._terms = {\n            \"anyOf\": \"at least one of the following\",\n            \"oneOf\": \"exactly one of the following\",\n            \"allOf\": \"all of the following\",\n            \"not\": \"(*NOT* the following)\",\n            \"prefixItems\": f\"{self._jargon('items')} (in order)\",\n            \"items\": \"items\",\n            \"contains\": \"contains at least one of\",\n            \"propertyNames\": (\n                f\"non-predefined acceptable {self._jargon('property names')}\"\n            ),\n            \"patternProperties\": f\"{self._jargon('properties')} named via pattern\",\n            \"const\": \"predefined value\",\n            \"enum\": \"one of\",\n        }\n        # Attributes that indicate that the definition is easy and can be done\n        # inline (e.g. string and number)\n        self._guess_inline_defs = [\n            \"enum\",\n            \"const\",\n            \"maxLength\",\n            \"minLength\",\n            \"pattern\",\n            \"format\",\n            \"minimum\",\n            \"maximum\",\n            \"exclusiveMinimum\",\n            \"exclusiveMaximum\",\n            \"multipleOf\",\n        ]\n\n    def _jargon(self, term: Union[str, List[str]]) -> Union[str, List[str]]:\n        if isinstance(term, list):\n            return [self.jargon.get(t, t) for t in term]\n        return self.jargon.get(term, term)\n\n    def __call__(\n        self,\n        schema: Union[dict, List[dict]],\n        prefix: str = \"\",\n        *,\n        _path: Sequence[str] = (),\n    ) -> str:\n        if isinstance(schema, list):\n            return self._handle_list(schema, prefix, _path)\n\n        filtered = self._filter_unecessary(schema, _path)\n        simple = self._handle_simple_dict(filtered, _path)\n        if simple:\n            return f\"{prefix}{simple}\"\n\n        child_prefix = self._child_prefix(prefix, \"  \")\n        item_prefix = self._child_prefix(prefix, \"- \")\n        indent = len(prefix) * \" \"\n        with io.StringIO() as buffer:\n            for i, (key, value) in enumerate(filtered.items()):\n                child_path = [*_path, key]\n                line_prefix = prefix if i == 0 else indent\n                buffer.write(f\"{line_prefix}{self._label(child_path)}:\")\n                # ^  just the first item should receive the complete prefix\n                if isinstance(value, dict):\n                    filtered = self._filter_unecessary(value, child_path)\n                    simple = self._handle_simple_dict(filtered, child_path)\n                    buffer.write(\n                        f\" {simple}\"\n                        if simple\n                        else f\"\\n{self(value, child_prefix, _path=child_path)}\"\n                    )\n                elif isinstance(value, list) and (\n                    key != \"type\" or self._is_property(child_path)\n                ):\n                    children = self._handle_list(value, item_prefix, child_path)\n                    sep = \" \" if children.startswith(\"[\") else \"\\n\"\n                    buffer.write(f\"{sep}{children}\")\n                else:\n                    buffer.write(f\" {self._value(value, child_path)}\\n\")\n            return buffer.getvalue()\n\n    def _is_unecessary(self, path: Sequence[str]) -> bool:\n        if self._is_property(path) or not path:  # empty path => instruction @ root\n            return False\n        key = path[-1]\n        return any(key.startswith(k) for k in \"$_\") or key in self._IGNORE\n\n    def _filter_unecessary(self, schema: dict, path: Sequence[str]):\n        return {\n            key: value\n            for key, value in schema.items()\n            if not self._is_unecessary([*path, key])\n        }\n\n    def _handle_simple_dict(self, value: dict, path: Sequence[str]) -> Optional[str]:\n        inline = any(p in value for p in self._guess_inline_defs)\n        simple = not any(isinstance(v, (list, dict)) for v in value.values())\n        if inline or simple:\n            return f\"{{{', '.join(self._inline_attrs(value, path))}}}\\n\"\n        return None\n\n    def _handle_list(\n        self, schemas: list, prefix: str = \"\", path: Sequence[str] = ()\n    ) -> str:\n        if self._is_unecessary(path):\n            return \"\"\n\n        repr_ = repr(schemas)\n        if all(not isinstance(e, (dict, list)) for e in schemas) and len(repr_) < 60:\n            return f\"{repr_}\\n\"\n\n        item_prefix = self._child_prefix(prefix, \"- \")\n        return \"\".join(\n            self(v, item_prefix, _path=[*path, f\"[{i}]\"]) for i, v in enumerate(schemas)\n        )\n\n    def _is_property(self, path: Sequence[str]):\n        \"\"\"Check if the given path can correspond to an arbitrarily named property\"\"\"\n        counter = 0\n        for key in path[-2::-1]:\n            if key not in {\"properties\", \"patternProperties\"}:\n                break\n            counter += 1\n\n        # If the counter if even, the path correspond to a JSON Schema keyword\n        # otherwise it can be any arbitrary string naming a property\n        return counter % 2 == 1\n\n    def _label(self, path: Sequence[str]) -> str:\n        *parents, key = path\n        if not self._is_property(path):\n            norm_key = _separate_terms(key)\n            return self._terms.get(key) or \" \".join(self._jargon(norm_key))\n\n        if parents[-1] == \"patternProperties\":\n            return f\"(regex {key!r})\"\n        return repr(key)  # property name\n\n    def _value(self, value: Any, path: Sequence[str]) -> str:\n        if path[-1] == \"type\" and not self._is_property(path):\n            type_ = self._jargon(value)\n            return (\n                f\"[{', '.join(type_)}]\" if isinstance(value, list) else cast(str, type_)\n            )\n        return repr(value)\n\n    def _inline_attrs(self, schema: dict, path: Sequence[str]) -> Iterator[str]:\n        for key, value in schema.items():\n            child_path = [*path, key]\n            yield f\"{self._label(child_path)}: {self._value(value, child_path)}\"\n\n    def _child_prefix(self, parent_prefix: str, child_prefix: str) -> str:\n        return len(parent_prefix) * \" \" + child_prefix\n\n\ndef _separate_terms(word: str) -> List[str]:\n    \"\"\"\n    >>> _separate_terms(\"FooBar-foo\")\n    ['foo', 'bar', 'foo']\n    \"\"\"\n    return [w.lower() for w in _CAMEL_CASE_SPLITTER.split(word) if w]\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/config/_validate_pyproject/extra_validations.py",
    "content": "\"\"\"The purpose of this module is implement PEP 621 validations that are\ndifficult to express as a JSON Schema (or that are not supported by the current\nJSON Schema library).\n\"\"\"\n\nfrom typing import Mapping, TypeVar\n\nfrom .error_reporting import ValidationError\n\nT = TypeVar(\"T\", bound=Mapping)\n\n\nclass RedefiningStaticFieldAsDynamic(ValidationError):\n    \"\"\"According to PEP 621:\n\n    Build back-ends MUST raise an error if the metadata specifies a field\n    statically as well as being listed in dynamic.\n    \"\"\"\n\n\ndef validate_project_dynamic(pyproject: T) -> T:\n    project_table = pyproject.get(\"project\", {})\n    dynamic = project_table.get(\"dynamic\", [])\n\n    for field in dynamic:\n        if field in project_table:\n            msg = f\"You cannot provide a value for `project.{field}` and \"\n            msg += \"list it under `project.dynamic` at the same time\"\n            name = f\"data.project.{field}\"\n            value = {field: project_table[field], \"...\": \" # ...\", \"dynamic\": dynamic}\n            raise RedefiningStaticFieldAsDynamic(msg, value, name, rule=\"PEP 621\")\n\n    return pyproject\n\n\nEXTRA_VALIDATIONS = (validate_project_dynamic,)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_exceptions.py",
    "content": "import re\n\n\nSPLIT_RE = re.compile(r'[\\.\\[\\]]+')\n\n\nclass JsonSchemaException(ValueError):\n    \"\"\"\n    Base exception of ``fastjsonschema`` library.\n    \"\"\"\n\n\nclass JsonSchemaValueException(JsonSchemaException):\n    \"\"\"\n    Exception raised by validation function. Available properties:\n\n     * ``message`` containing human-readable information what is wrong (e.g. ``data.property[index] must be smaller than or equal to 42``),\n     * invalid ``value`` (e.g. ``60``),\n     * ``name`` of a path in the data structure (e.g. ``data.property[index]``),\n     * ``path`` as an array in the data structure (e.g. ``['data', 'property', 'index']``),\n     * the whole ``definition`` which the ``value`` has to fulfil (e.g. ``{'type': 'number', 'maximum': 42}``),\n     * ``rule`` which the ``value`` is breaking (e.g. ``maximum``)\n     * and ``rule_definition`` (e.g. ``42``).\n\n    .. versionchanged:: 2.14.0\n        Added all extra properties.\n    \"\"\"\n\n    def __init__(self, message, value=None, name=None, definition=None, rule=None):\n        super().__init__(message)\n        self.message = message\n        self.value = value\n        self.name = name\n        self.definition = definition\n        self.rule = rule\n\n    @property\n    def path(self):\n        return [item for item in SPLIT_RE.split(self.name) if item != '']\n\n    @property\n    def rule_definition(self):\n        if not self.rule or not self.definition:\n            return None\n        return self.definition.get(self.rule)\n\n\nclass JsonSchemaDefinitionException(JsonSchemaException):\n    \"\"\"\n    Exception raised by generator of validation function.\n    \"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/config/_validate_pyproject/fastjsonschema_validations.py",
    "content": "# noqa\n# type: ignore\n# flake8: noqa\n# pylint: skip-file\n# mypy: ignore-errors\n# yapf: disable\n# pylama:skip=1\n\n\n# *** PLEASE DO NOT MODIFY DIRECTLY: Automatically generated code *** \n\n\nVERSION = \"2.15.3\"\nimport re\nfrom .fastjsonschema_exceptions import JsonSchemaValueException\n\n\nREGEX_PATTERNS = {\n    '^.*$': re.compile('^.*$'),\n    '.+': re.compile('.+'),\n    '^.+$': re.compile('^.+$'),\n    'idn-email_re_pattern': re.compile('^[^@]+@[^@]+\\\\.[^@]+\\\\Z')\n}\n\nNoneType = type(None)\n\ndef validate(data, custom_formats={}, name_prefix=None):\n    validate_https___packaging_python_org_en_latest_specifications_declaring_build_dependencies(data, custom_formats, (name_prefix or \"data\") + \"\")\n    return data\n\ndef validate_https___packaging_python_org_en_latest_specifications_declaring_build_dependencies(data, custom_formats={}, name_prefix=None):\n    if not isinstance(data, (dict)):\n        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must be object\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-build-dependencies/', 'title': 'Data structure for ``pyproject.toml`` files', '$$description': ['File format containing build-time configurations for the Python ecosystem. ', ':pep:`517` initially defined a build-system independent format for source trees', 'which was complemented by :pep:`518` to provide a way of specifying dependencies ', 'for building Python projects.', 'Please notice the ``project`` table (as initially defined in  :pep:`621`) is not included', 'in this schema and should be considered separately.'], 'type': 'object', 'additionalProperties': False, 'properties': {'build-system': {'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-project-metadata/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '<https://packaging.python.org/specifications/core-metadata/#summary>`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '<https://www.python.org/dev/peps/pep-0621/#readme>`_', \"with meaning similar to the one defined in `core metadata's Description\", '<https://packaging.python.org/specifications/core-metadata/#description>`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '<https://packaging.python.org/specifications/core-metadata/#requires-python>`_.']}, 'license': {'description': '`Project license <https://www.python.org/dev/peps/pep-0621/#license>`_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '<https://packaging.python.org/specifications/core-metadata/#license>`_.']}}, 'required': ['text']}]}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': [\"The people or organizations considered to be the 'authors' of the project.\", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': [\"The people or organizations considered to be the 'maintainers' of the project.\", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier <https://pypi.org/classifiers/>`_.'}, '$$description': ['`Trove classifiers <https://pypi.org/classifiers/>`_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points <https://packaging.python.org/specifications/entry-points/>`_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points <https://packaging.python.org/specifications/entry-points/>`_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '<https://packaging.python.org/specifications/entry-points/>`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as \"Required\", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, 'tool': {'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://docs.python.org/3/install/', 'title': '``tool.distutils`` table', '$$description': ['Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` scripts via `distutils configuration files', '<https://docs.python.org/3/install/#distutils-configuration-files>`_.', '``tool.distutils`` subtables could be used with the same purpose', '(NOT CURRENTLY IMPLEMENTED).'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://setuptools.pypa.io/en/latest/references/keywords.html', 'title': '``tool.setuptools`` table', '$$description': ['Please notice for the time being the ``setuptools`` project does not specify', 'a way of configuring builds via ``pyproject.toml``.', 'Therefore this schema should be taken just as a *\"thought experiment\"* on how', 'this *might be done*, by following the principles established in', '`ini2toml <https://ini2toml.readthedocs.io/en/latest/setuptools_pep621.html>`_.', 'It considers only ``setuptools`` `parameters', '<https://setuptools.pypa.io/en/latest/userguide/declarative_config.html>`_', 'that can currently be configured via ``setup.cfg`` and are not covered by :pep:`621`', 'but intentionally excludes ``dependency_links`` and ``setup_requires``.', 'NOTE: ``scripts`` was renamed to ``script-files`` to avoid confusion with', 'entry-point based scripts (defined in :pep:`621`).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'description': 'Whether the project can be safely installed and run from a zip file.', 'type': 'boolean'}, 'script-files': {'description': 'Legacy way of defining scripts (entry-points are preferred).', 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': ''}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'data-files': {'$$description': ['**DEPRECATED**: dict-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', \"Please notice this don't work with wheels. See `data files support\", '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., \"dotted\" form with module), e.g.::\\n\\n', '    cmdclass = {mycmd = \"pkg.subpkg.module.CommandClass\"}\\n\\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['PROVISIONAL: List of glob patterns for all license files being distributed.', '(might become standard with PEP 639).'], 'default': ['LICEN[CS]E*', ' COPYING*', ' NOTICE*', 'AUTHORS*'], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive'}}}, 'readme': {'anyOf': [{'$ref': '#/definitions/file-directive'}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}}}}, 'definitions': {'file-directive': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'attr-directive': {'title': \"'attr:' directive\", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': \"'find:' directive\", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '<https://setuptools.pypa.io/en/latest/userguide/package_discovery.html>`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-project-metadata/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '<https://packaging.python.org/specifications/core-metadata/#summary>`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '<https://www.python.org/dev/peps/pep-0621/#readme>`_', \"with meaning similar to the one defined in `core metadata's Description\", '<https://packaging.python.org/specifications/core-metadata/#description>`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '<https://packaging.python.org/specifications/core-metadata/#requires-python>`_.']}, 'license': {'description': '`Project license <https://www.python.org/dev/peps/pep-0621/#license>`_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '<https://packaging.python.org/specifications/core-metadata/#license>`_.']}}, 'required': ['text']}]}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': [\"The people or organizations considered to be the 'authors' of the project.\", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': [\"The people or organizations considered to be the 'maintainers' of the project.\", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier <https://pypi.org/classifiers/>`_.'}, '$$description': ['`Trove classifiers <https://pypi.org/classifiers/>`_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points <https://packaging.python.org/specifications/entry-points/>`_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points <https://packaging.python.org/specifications/entry-points/>`_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '<https://packaging.python.org/specifications/entry-points/>`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as \"Required\", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='type')\n    data_is_dict = isinstance(data, dict)\n    if data_is_dict:\n        data_keys = set(data.keys())\n        if \"build-system\" in data_keys:\n            data_keys.remove(\"build-system\")\n            data__buildsystem = data[\"build-system\"]\n            if not isinstance(data__buildsystem, (dict)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".build-system must be object\", value=data__buildsystem, name=\"\" + (name_prefix or \"data\") + \".build-system\", definition={'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, rule='type')\n            data__buildsystem_is_dict = isinstance(data__buildsystem, dict)\n            if data__buildsystem_is_dict:\n                data__buildsystem_len = len(data__buildsystem)\n                if not all(prop in data__buildsystem for prop in ['requires']):\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".build-system must contain ['requires'] properties\", value=data__buildsystem, name=\"\" + (name_prefix or \"data\") + \".build-system\", definition={'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, rule='required')\n                data__buildsystem_keys = set(data__buildsystem.keys())\n                if \"requires\" in data__buildsystem_keys:\n                    data__buildsystem_keys.remove(\"requires\")\n                    data__buildsystem__requires = data__buildsystem[\"requires\"]\n                    if not isinstance(data__buildsystem__requires, (list, tuple)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".build-system.requires must be array\", value=data__buildsystem__requires, name=\"\" + (name_prefix or \"data\") + \".build-system.requires\", definition={'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, rule='type')\n                    data__buildsystem__requires_is_list = isinstance(data__buildsystem__requires, (list, tuple))\n                    if data__buildsystem__requires_is_list:\n                        data__buildsystem__requires_len = len(data__buildsystem__requires)\n                        for data__buildsystem__requires_x, data__buildsystem__requires_item in enumerate(data__buildsystem__requires):\n                            if not isinstance(data__buildsystem__requires_item, (str)):\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".build-system.requires[{data__buildsystem__requires_x}]\".format(**locals()) + \" must be string\", value=data__buildsystem__requires_item, name=\"\" + (name_prefix or \"data\") + \".build-system.requires[{data__buildsystem__requires_x}]\".format(**locals()) + \"\", definition={'type': 'string'}, rule='type')\n                if \"build-backend\" in data__buildsystem_keys:\n                    data__buildsystem_keys.remove(\"build-backend\")\n                    data__buildsystem__buildbackend = data__buildsystem[\"build-backend\"]\n                    if not isinstance(data__buildsystem__buildbackend, (str)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".build-system.build-backend must be string\", value=data__buildsystem__buildbackend, name=\"\" + (name_prefix or \"data\") + \".build-system.build-backend\", definition={'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, rule='type')\n                    if isinstance(data__buildsystem__buildbackend, str):\n                        if not custom_formats[\"pep517-backend-reference\"](data__buildsystem__buildbackend):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".build-system.build-backend must be pep517-backend-reference\", value=data__buildsystem__buildbackend, name=\"\" + (name_prefix or \"data\") + \".build-system.build-backend\", definition={'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, rule='format')\n                if \"backend-path\" in data__buildsystem_keys:\n                    data__buildsystem_keys.remove(\"backend-path\")\n                    data__buildsystem__backendpath = data__buildsystem[\"backend-path\"]\n                    if not isinstance(data__buildsystem__backendpath, (list, tuple)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".build-system.backend-path must be array\", value=data__buildsystem__backendpath, name=\"\" + (name_prefix or \"data\") + \".build-system.backend-path\", definition={'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}, rule='type')\n                    data__buildsystem__backendpath_is_list = isinstance(data__buildsystem__backendpath, (list, tuple))\n                    if data__buildsystem__backendpath_is_list:\n                        data__buildsystem__backendpath_len = len(data__buildsystem__backendpath)\n                        for data__buildsystem__backendpath_x, data__buildsystem__backendpath_item in enumerate(data__buildsystem__backendpath):\n                            if not isinstance(data__buildsystem__backendpath_item, (str)):\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".build-system.backend-path[{data__buildsystem__backendpath_x}]\".format(**locals()) + \" must be string\", value=data__buildsystem__backendpath_item, name=\"\" + (name_prefix or \"data\") + \".build-system.backend-path[{data__buildsystem__backendpath_x}]\".format(**locals()) + \"\", definition={'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}, rule='type')\n                if data__buildsystem_keys:\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".build-system must not contain \"+str(data__buildsystem_keys)+\" properties\", value=data__buildsystem, name=\"\" + (name_prefix or \"data\") + \".build-system\", definition={'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, rule='additionalProperties')\n        if \"project\" in data_keys:\n            data_keys.remove(\"project\")\n            data__project = data[\"project\"]\n            validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata(data__project, custom_formats, (name_prefix or \"data\") + \".project\")\n        if \"tool\" in data_keys:\n            data_keys.remove(\"tool\")\n            data__tool = data[\"tool\"]\n            if not isinstance(data__tool, (dict)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".tool must be object\", value=data__tool, name=\"\" + (name_prefix or \"data\") + \".tool\", definition={'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://docs.python.org/3/install/', 'title': '``tool.distutils`` table', '$$description': ['Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` scripts via `distutils configuration files', '<https://docs.python.org/3/install/#distutils-configuration-files>`_.', '``tool.distutils`` subtables could be used with the same purpose', '(NOT CURRENTLY IMPLEMENTED).'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://setuptools.pypa.io/en/latest/references/keywords.html', 'title': '``tool.setuptools`` table', '$$description': ['Please notice for the time being the ``setuptools`` project does not specify', 'a way of configuring builds via ``pyproject.toml``.', 'Therefore this schema should be taken just as a *\"thought experiment\"* on how', 'this *might be done*, by following the principles established in', '`ini2toml <https://ini2toml.readthedocs.io/en/latest/setuptools_pep621.html>`_.', 'It considers only ``setuptools`` `parameters', '<https://setuptools.pypa.io/en/latest/userguide/declarative_config.html>`_', 'that can currently be configured via ``setup.cfg`` and are not covered by :pep:`621`', 'but intentionally excludes ``dependency_links`` and ``setup_requires``.', 'NOTE: ``scripts`` was renamed to ``script-files`` to avoid confusion with', 'entry-point based scripts (defined in :pep:`621`).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'description': 'Whether the project can be safely installed and run from a zip file.', 'type': 'boolean'}, 'script-files': {'description': 'Legacy way of defining scripts (entry-points are preferred).', 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': ''}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'data-files': {'$$description': ['**DEPRECATED**: dict-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', \"Please notice this don't work with wheels. See `data files support\", '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., \"dotted\" form with module), e.g.::\\n\\n', '    cmdclass = {mycmd = \"pkg.subpkg.module.CommandClass\"}\\n\\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['PROVISIONAL: List of glob patterns for all license files being distributed.', '(might become standard with PEP 639).'], 'default': ['LICEN[CS]E*', ' COPYING*', ' NOTICE*', 'AUTHORS*'], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive'}}}, 'readme': {'anyOf': [{'$ref': '#/definitions/file-directive'}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}}}}, 'definitions': {'file-directive': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'attr-directive': {'title': \"'attr:' directive\", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': \"'find:' directive\", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '<https://setuptools.pypa.io/en/latest/userguide/package_discovery.html>`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}, rule='type')\n            data__tool_is_dict = isinstance(data__tool, dict)\n            if data__tool_is_dict:\n                data__tool_keys = set(data__tool.keys())\n                if \"distutils\" in data__tool_keys:\n                    data__tool_keys.remove(\"distutils\")\n                    data__tool__distutils = data__tool[\"distutils\"]\n                    validate_https___docs_python_org_3_install(data__tool__distutils, custom_formats, (name_prefix or \"data\") + \".tool.distutils\")\n                if \"setuptools\" in data__tool_keys:\n                    data__tool_keys.remove(\"setuptools\")\n                    data__tool__setuptools = data__tool[\"setuptools\"]\n                    validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data__tool__setuptools, custom_formats, (name_prefix or \"data\") + \".tool.setuptools\")\n        if data_keys:\n            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must not contain \"+str(data_keys)+\" properties\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-build-dependencies/', 'title': 'Data structure for ``pyproject.toml`` files', '$$description': ['File format containing build-time configurations for the Python ecosystem. ', ':pep:`517` initially defined a build-system independent format for source trees', 'which was complemented by :pep:`518` to provide a way of specifying dependencies ', 'for building Python projects.', 'Please notice the ``project`` table (as initially defined in  :pep:`621`) is not included', 'in this schema and should be considered separately.'], 'type': 'object', 'additionalProperties': False, 'properties': {'build-system': {'type': 'object', 'description': 'Table used to store build-related data', 'additionalProperties': False, 'properties': {'requires': {'type': 'array', '$$description': ['List of dependencies in the :pep:`508` format required to execute the build', 'system. Please notice that the resulting dependency graph', '**MUST NOT contain cycles**'], 'items': {'type': 'string'}}, 'build-backend': {'type': 'string', 'description': 'Python object that will be used to perform the build according to :pep:`517`', 'format': 'pep517-backend-reference'}, 'backend-path': {'type': 'array', '$$description': ['List of directories to be prepended to ``sys.path`` when loading the', 'back-end, and running its hooks'], 'items': {'type': 'string', '$comment': 'Should be a path (TODO: enforce it with format?)'}}}, 'required': ['requires']}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-project-metadata/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '<https://packaging.python.org/specifications/core-metadata/#summary>`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '<https://www.python.org/dev/peps/pep-0621/#readme>`_', \"with meaning similar to the one defined in `core metadata's Description\", '<https://packaging.python.org/specifications/core-metadata/#description>`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '<https://packaging.python.org/specifications/core-metadata/#requires-python>`_.']}, 'license': {'description': '`Project license <https://www.python.org/dev/peps/pep-0621/#license>`_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '<https://packaging.python.org/specifications/core-metadata/#license>`_.']}}, 'required': ['text']}]}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': [\"The people or organizations considered to be the 'authors' of the project.\", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': [\"The people or organizations considered to be the 'maintainers' of the project.\", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier <https://pypi.org/classifiers/>`_.'}, '$$description': ['`Trove classifiers <https://pypi.org/classifiers/>`_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points <https://packaging.python.org/specifications/entry-points/>`_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points <https://packaging.python.org/specifications/entry-points/>`_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '<https://packaging.python.org/specifications/entry-points/>`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as \"Required\", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, 'tool': {'type': 'object', 'properties': {'distutils': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://docs.python.org/3/install/', 'title': '``tool.distutils`` table', '$$description': ['Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` scripts via `distutils configuration files', '<https://docs.python.org/3/install/#distutils-configuration-files>`_.', '``tool.distutils`` subtables could be used with the same purpose', '(NOT CURRENTLY IMPLEMENTED).'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, 'setuptools': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://setuptools.pypa.io/en/latest/references/keywords.html', 'title': '``tool.setuptools`` table', '$$description': ['Please notice for the time being the ``setuptools`` project does not specify', 'a way of configuring builds via ``pyproject.toml``.', 'Therefore this schema should be taken just as a *\"thought experiment\"* on how', 'this *might be done*, by following the principles established in', '`ini2toml <https://ini2toml.readthedocs.io/en/latest/setuptools_pep621.html>`_.', 'It considers only ``setuptools`` `parameters', '<https://setuptools.pypa.io/en/latest/userguide/declarative_config.html>`_', 'that can currently be configured via ``setup.cfg`` and are not covered by :pep:`621`', 'but intentionally excludes ``dependency_links`` and ``setup_requires``.', 'NOTE: ``scripts`` was renamed to ``script-files`` to avoid confusion with', 'entry-point based scripts (defined in :pep:`621`).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'description': 'Whether the project can be safely installed and run from a zip file.', 'type': 'boolean'}, 'script-files': {'description': 'Legacy way of defining scripts (entry-points are preferred).', 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}}, {'$ref': '#/definitions/find-directive'}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': ''}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'data-files': {'$$description': ['**DEPRECATED**: dict-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', \"Please notice this don't work with wheels. See `data files support\", '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., \"dotted\" form with module), e.g.::\\n\\n', '    cmdclass = {mycmd = \"pkg.subpkg.module.CommandClass\"}\\n\\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['PROVISIONAL: List of glob patterns for all license files being distributed.', '(might become standard with PEP 639).'], 'default': ['LICEN[CS]E*', ' COPYING*', ' NOTICE*', 'AUTHORS*'], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'$ref': '#/definitions/attr-directive'}, {'$ref': '#/definitions/file-directive'}]}, 'classifiers': {'$ref': '#/definitions/file-directive'}, 'description': {'$ref': '#/definitions/file-directive'}, 'dependencies': {'$ref': '#/definitions/file-directive'}, 'entry-points': {'$ref': '#/definitions/file-directive'}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$ref': '#/definitions/file-directive'}}}, 'readme': {'anyOf': [{'$ref': '#/definitions/file-directive'}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}}}}, 'definitions': {'file-directive': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'attr-directive': {'title': \"'attr:' directive\", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': \"'find:' directive\", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '<https://setuptools.pypa.io/en/latest/userguide/package_discovery.html>`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}}}}, 'project': {'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-project-metadata/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '<https://packaging.python.org/specifications/core-metadata/#summary>`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '<https://www.python.org/dev/peps/pep-0621/#readme>`_', \"with meaning similar to the one defined in `core metadata's Description\", '<https://packaging.python.org/specifications/core-metadata/#description>`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '<https://packaging.python.org/specifications/core-metadata/#requires-python>`_.']}, 'license': {'description': '`Project license <https://www.python.org/dev/peps/pep-0621/#license>`_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '<https://packaging.python.org/specifications/core-metadata/#license>`_.']}}, 'required': ['text']}]}, 'authors': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': [\"The people or organizations considered to be the 'authors' of the project.\", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$ref': '#/definitions/author'}, '$$description': [\"The people or organizations considered to be the 'maintainers' of the project.\", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier <https://pypi.org/classifiers/>`_.'}, '$$description': ['`Trove classifiers <https://pypi.org/classifiers/>`_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create command-line wrappers for the given', '`entry points <https://packaging.python.org/specifications/entry-points/>`_.']}, 'gui-scripts': {'$ref': '#/definitions/entry-point-group', '$$description': ['Instruct the installer to create GUI wrappers for the given', '`entry points <https://packaging.python.org/specifications/entry-points/>`_.', 'The difference between ``scripts`` and ``gui-scripts`` is only relevant in', 'Windows.']}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '<https://packaging.python.org/specifications/entry-points/>`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$ref': '#/definitions/entry-point-group'}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$ref': '#/definitions/dependency'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$ref': '#/definitions/dependency'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as \"Required\", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='additionalProperties')\n    return data\n\ndef validate_https___setuptools_pypa_io_en_latest_references_keywords_html(data, custom_formats={}, name_prefix=None):\n    if not isinstance(data, (dict)):\n        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must be object\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://setuptools.pypa.io/en/latest/references/keywords.html', 'title': '``tool.setuptools`` table', '$$description': ['Please notice for the time being the ``setuptools`` project does not specify', 'a way of configuring builds via ``pyproject.toml``.', 'Therefore this schema should be taken just as a *\"thought experiment\"* on how', 'this *might be done*, by following the principles established in', '`ini2toml <https://ini2toml.readthedocs.io/en/latest/setuptools_pep621.html>`_.', 'It considers only ``setuptools`` `parameters', '<https://setuptools.pypa.io/en/latest/userguide/declarative_config.html>`_', 'that can currently be configured via ``setup.cfg`` and are not covered by :pep:`621`', 'but intentionally excludes ``dependency_links`` and ``setup_requires``.', 'NOTE: ``scripts`` was renamed to ``script-files`` to avoid confusion with', 'entry-point based scripts (defined in :pep:`621`).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'description': 'Whether the project can be safely installed and run from a zip file.', 'type': 'boolean'}, 'script-files': {'description': 'Legacy way of defining scripts (entry-points are preferred).', 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}}, {'$id': '#/definitions/find-directive', 'title': \"'find:' directive\", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '<https://setuptools.pypa.io/en/latest/userguide/package_discovery.html>`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': ''}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'data-files': {'$$description': ['**DEPRECATED**: dict-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', \"Please notice this don't work with wheels. See `data files support\", '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., \"dotted\" form with module), e.g.::\\n\\n', '    cmdclass = {mycmd = \"pkg.subpkg.module.CommandClass\"}\\n\\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['PROVISIONAL: List of glob patterns for all license files being distributed.', '(might become standard with PEP 639).'], 'default': ['LICEN[CS]E*', ' COPYING*', ' NOTICE*', 'AUTHORS*'], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'title': \"'attr:' directive\", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}}}, 'readme': {'anyOf': [{'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}}}}, 'definitions': {'file-directive': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'attr-directive': {'title': \"'attr:' directive\", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': \"'find:' directive\", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '<https://setuptools.pypa.io/en/latest/userguide/package_discovery.html>`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}, rule='type')\n    data_is_dict = isinstance(data, dict)\n    if data_is_dict:\n        data_keys = set(data.keys())\n        if \"platforms\" in data_keys:\n            data_keys.remove(\"platforms\")\n            data__platforms = data[\"platforms\"]\n            if not isinstance(data__platforms, (list, tuple)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".platforms must be array\", value=data__platforms, name=\"\" + (name_prefix or \"data\") + \".platforms\", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')\n            data__platforms_is_list = isinstance(data__platforms, (list, tuple))\n            if data__platforms_is_list:\n                data__platforms_len = len(data__platforms)\n                for data__platforms_x, data__platforms_item in enumerate(data__platforms):\n                    if not isinstance(data__platforms_item, (str)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".platforms[{data__platforms_x}]\".format(**locals()) + \" must be string\", value=data__platforms_item, name=\"\" + (name_prefix or \"data\") + \".platforms[{data__platforms_x}]\".format(**locals()) + \"\", definition={'type': 'string'}, rule='type')\n        if \"provides\" in data_keys:\n            data_keys.remove(\"provides\")\n            data__provides = data[\"provides\"]\n            if not isinstance(data__provides, (list, tuple)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".provides must be array\", value=data__provides, name=\"\" + (name_prefix or \"data\") + \".provides\", definition={'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, rule='type')\n            data__provides_is_list = isinstance(data__provides, (list, tuple))\n            if data__provides_is_list:\n                data__provides_len = len(data__provides)\n                for data__provides_x, data__provides_item in enumerate(data__provides):\n                    if not isinstance(data__provides_item, (str)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".provides[{data__provides_x}]\".format(**locals()) + \" must be string\", value=data__provides_item, name=\"\" + (name_prefix or \"data\") + \".provides[{data__provides_x}]\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='type')\n                    if isinstance(data__provides_item, str):\n                        if not custom_formats[\"pep508-identifier\"](data__provides_item):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".provides[{data__provides_x}]\".format(**locals()) + \" must be pep508-identifier\", value=data__provides_item, name=\"\" + (name_prefix or \"data\") + \".provides[{data__provides_x}]\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='format')\n        if \"obsoletes\" in data_keys:\n            data_keys.remove(\"obsoletes\")\n            data__obsoletes = data[\"obsoletes\"]\n            if not isinstance(data__obsoletes, (list, tuple)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".obsoletes must be array\", value=data__obsoletes, name=\"\" + (name_prefix or \"data\") + \".obsoletes\", definition={'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, rule='type')\n            data__obsoletes_is_list = isinstance(data__obsoletes, (list, tuple))\n            if data__obsoletes_is_list:\n                data__obsoletes_len = len(data__obsoletes)\n                for data__obsoletes_x, data__obsoletes_item in enumerate(data__obsoletes):\n                    if not isinstance(data__obsoletes_item, (str)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".obsoletes[{data__obsoletes_x}]\".format(**locals()) + \" must be string\", value=data__obsoletes_item, name=\"\" + (name_prefix or \"data\") + \".obsoletes[{data__obsoletes_x}]\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='type')\n                    if isinstance(data__obsoletes_item, str):\n                        if not custom_formats[\"pep508-identifier\"](data__obsoletes_item):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".obsoletes[{data__obsoletes_x}]\".format(**locals()) + \" must be pep508-identifier\", value=data__obsoletes_item, name=\"\" + (name_prefix or \"data\") + \".obsoletes[{data__obsoletes_x}]\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'pep508-identifier'}, rule='format')\n        if \"zip-safe\" in data_keys:\n            data_keys.remove(\"zip-safe\")\n            data__zipsafe = data[\"zip-safe\"]\n            if not isinstance(data__zipsafe, (bool)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".zip-safe must be boolean\", value=data__zipsafe, name=\"\" + (name_prefix or \"data\") + \".zip-safe\", definition={'description': 'Whether the project can be safely installed and run from a zip file.', 'type': 'boolean'}, rule='type')\n        if \"script-files\" in data_keys:\n            data_keys.remove(\"script-files\")\n            data__scriptfiles = data[\"script-files\"]\n            if not isinstance(data__scriptfiles, (list, tuple)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".script-files must be array\", value=data__scriptfiles, name=\"\" + (name_prefix or \"data\") + \".script-files\", definition={'description': 'Legacy way of defining scripts (entry-points are preferred).', 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, rule='type')\n            data__scriptfiles_is_list = isinstance(data__scriptfiles, (list, tuple))\n            if data__scriptfiles_is_list:\n                data__scriptfiles_len = len(data__scriptfiles)\n                for data__scriptfiles_x, data__scriptfiles_item in enumerate(data__scriptfiles):\n                    if not isinstance(data__scriptfiles_item, (str)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".script-files[{data__scriptfiles_x}]\".format(**locals()) + \" must be string\", value=data__scriptfiles_item, name=\"\" + (name_prefix or \"data\") + \".script-files[{data__scriptfiles_x}]\".format(**locals()) + \"\", definition={'type': 'string'}, rule='type')\n        if \"eager-resources\" in data_keys:\n            data_keys.remove(\"eager-resources\")\n            data__eagerresources = data[\"eager-resources\"]\n            if not isinstance(data__eagerresources, (list, tuple)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".eager-resources must be array\", value=data__eagerresources, name=\"\" + (name_prefix or \"data\") + \".eager-resources\", definition={'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.'], 'type': 'array', 'items': {'type': 'string'}}, rule='type')\n            data__eagerresources_is_list = isinstance(data__eagerresources, (list, tuple))\n            if data__eagerresources_is_list:\n                data__eagerresources_len = len(data__eagerresources)\n                for data__eagerresources_x, data__eagerresources_item in enumerate(data__eagerresources):\n                    if not isinstance(data__eagerresources_item, (str)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".eager-resources[{data__eagerresources_x}]\".format(**locals()) + \" must be string\", value=data__eagerresources_item, name=\"\" + (name_prefix or \"data\") + \".eager-resources[{data__eagerresources_x}]\".format(**locals()) + \"\", definition={'type': 'string'}, rule='type')\n        if \"packages\" in data_keys:\n            data_keys.remove(\"packages\")\n            data__packages = data[\"packages\"]\n            data__packages_one_of_count1 = 0\n            if data__packages_one_of_count1 < 2:\n                try:\n                    if not isinstance(data__packages, (list, tuple)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".packages must be array\", value=data__packages, name=\"\" + (name_prefix or \"data\") + \".packages\", definition={'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}}, rule='type')\n                    data__packages_is_list = isinstance(data__packages, (list, tuple))\n                    if data__packages_is_list:\n                        data__packages_len = len(data__packages)\n                        for data__packages_x, data__packages_item in enumerate(data__packages):\n                            if not isinstance(data__packages_item, (str)):\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".packages[{data__packages_x}]\".format(**locals()) + \" must be string\", value=data__packages_item, name=\"\" + (name_prefix or \"data\") + \".packages[{data__packages_x}]\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'python-module-name'}, rule='type')\n                            if isinstance(data__packages_item, str):\n                                if not custom_formats[\"python-module-name\"](data__packages_item):\n                                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".packages[{data__packages_x}]\".format(**locals()) + \" must be python-module-name\", value=data__packages_item, name=\"\" + (name_prefix or \"data\") + \".packages[{data__packages_x}]\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'python-module-name'}, rule='format')\n                    data__packages_one_of_count1 += 1\n                except JsonSchemaValueException: pass\n            if data__packages_one_of_count1 < 2:\n                try:\n                    validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_find_directive(data__packages, custom_formats, (name_prefix or \"data\") + \".packages\")\n                    data__packages_one_of_count1 += 1\n                except JsonSchemaValueException: pass\n            if data__packages_one_of_count1 != 1:\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".packages must be valid exactly by one definition\" + (\" (\" + str(data__packages_one_of_count1) + \" matches found)\"), value=data__packages, name=\"\" + (name_prefix or \"data\") + \".packages\", definition={'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}}, {'$id': '#/definitions/find-directive', 'title': \"'find:' directive\", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '<https://setuptools.pypa.io/en/latest/userguide/package_discovery.html>`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, rule='oneOf')\n        if \"package-dir\" in data_keys:\n            data_keys.remove(\"package-dir\")\n            data__packagedir = data[\"package-dir\"]\n            if not isinstance(data__packagedir, (dict)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-dir must be object\", value=data__packagedir, name=\"\" + (name_prefix or \"data\") + \".package-dir\", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': ''}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='type')\n            data__packagedir_is_dict = isinstance(data__packagedir, dict)\n            if data__packagedir_is_dict:\n                data__packagedir_keys = set(data__packagedir.keys())\n                for data__packagedir_key, data__packagedir_val in data__packagedir.items():\n                    if REGEX_PATTERNS['^.*$'].search(data__packagedir_key):\n                        if data__packagedir_key in data__packagedir_keys:\n                            data__packagedir_keys.remove(data__packagedir_key)\n                        if not isinstance(data__packagedir_val, (str)):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-dir.{data__packagedir_key}\".format(**locals()) + \" must be string\", value=data__packagedir_val, name=\"\" + (name_prefix or \"data\") + \".package-dir.{data__packagedir_key}\".format(**locals()) + \"\", definition={'type': 'string'}, rule='type')\n                if data__packagedir_keys:\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-dir must not contain \"+str(data__packagedir_keys)+\" properties\", value=data__packagedir, name=\"\" + (name_prefix or \"data\") + \".package-dir\", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': ''}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='additionalProperties')\n                data__packagedir_len = len(data__packagedir)\n                if data__packagedir_len != 0:\n                    data__packagedir_property_names = True\n                    for data__packagedir_key in data__packagedir:\n                        try:\n                            data__packagedir_key_one_of_count2 = 0\n                            if data__packagedir_key_one_of_count2 < 2:\n                                try:\n                                    if isinstance(data__packagedir_key, str):\n                                        if not custom_formats[\"python-module-name\"](data__packagedir_key):\n                                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-dir must be python-module-name\", value=data__packagedir_key, name=\"\" + (name_prefix or \"data\") + \".package-dir\", definition={'format': 'python-module-name'}, rule='format')\n                                    data__packagedir_key_one_of_count2 += 1\n                                except JsonSchemaValueException: pass\n                            if data__packagedir_key_one_of_count2 < 2:\n                                try:\n                                    if data__packagedir_key != \"\":\n                                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-dir must be same as const definition: \", value=data__packagedir_key, name=\"\" + (name_prefix or \"data\") + \".package-dir\", definition={'const': ''}, rule='const')\n                                    data__packagedir_key_one_of_count2 += 1\n                                except JsonSchemaValueException: pass\n                            if data__packagedir_key_one_of_count2 != 1:\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-dir must be valid exactly by one definition\" + (\" (\" + str(data__packagedir_key_one_of_count2) + \" matches found)\"), value=data__packagedir_key, name=\"\" + (name_prefix or \"data\") + \".package-dir\", definition={'oneOf': [{'format': 'python-module-name'}, {'const': ''}]}, rule='oneOf')\n                        except JsonSchemaValueException:\n                            data__packagedir_property_names = False\n                    if not data__packagedir_property_names:\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-dir must be named by propertyName definition\", value=data__packagedir, name=\"\" + (name_prefix or \"data\") + \".package-dir\", definition={'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': ''}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, rule='propertyNames')\n        if \"package-data\" in data_keys:\n            data_keys.remove(\"package-data\")\n            data__packagedata = data[\"package-data\"]\n            if not isinstance(data__packagedata, (dict)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-data must be object\", value=data__packagedata, name=\"\" + (name_prefix or \"data\") + \".package-data\", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')\n            data__packagedata_is_dict = isinstance(data__packagedata, dict)\n            if data__packagedata_is_dict:\n                data__packagedata_keys = set(data__packagedata.keys())\n                for data__packagedata_key, data__packagedata_val in data__packagedata.items():\n                    if REGEX_PATTERNS['^.*$'].search(data__packagedata_key):\n                        if data__packagedata_key in data__packagedata_keys:\n                            data__packagedata_keys.remove(data__packagedata_key)\n                        if not isinstance(data__packagedata_val, (list, tuple)):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-data.{data__packagedata_key}\".format(**locals()) + \" must be array\", value=data__packagedata_val, name=\"\" + (name_prefix or \"data\") + \".package-data.{data__packagedata_key}\".format(**locals()) + \"\", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')\n                        data__packagedata_val_is_list = isinstance(data__packagedata_val, (list, tuple))\n                        if data__packagedata_val_is_list:\n                            data__packagedata_val_len = len(data__packagedata_val)\n                            for data__packagedata_val_x, data__packagedata_val_item in enumerate(data__packagedata_val):\n                                if not isinstance(data__packagedata_val_item, (str)):\n                                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-data.{data__packagedata_key}[{data__packagedata_val_x}]\".format(**locals()) + \" must be string\", value=data__packagedata_val_item, name=\"\" + (name_prefix or \"data\") + \".package-data.{data__packagedata_key}[{data__packagedata_val_x}]\".format(**locals()) + \"\", definition={'type': 'string'}, rule='type')\n                if data__packagedata_keys:\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-data must not contain \"+str(data__packagedata_keys)+\" properties\", value=data__packagedata, name=\"\" + (name_prefix or \"data\") + \".package-data\", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='additionalProperties')\n                data__packagedata_len = len(data__packagedata)\n                if data__packagedata_len != 0:\n                    data__packagedata_property_names = True\n                    for data__packagedata_key in data__packagedata:\n                        try:\n                            data__packagedata_key_one_of_count3 = 0\n                            if data__packagedata_key_one_of_count3 < 2:\n                                try:\n                                    if isinstance(data__packagedata_key, str):\n                                        if not custom_formats[\"python-module-name\"](data__packagedata_key):\n                                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-data must be python-module-name\", value=data__packagedata_key, name=\"\" + (name_prefix or \"data\") + \".package-data\", definition={'format': 'python-module-name'}, rule='format')\n                                    data__packagedata_key_one_of_count3 += 1\n                                except JsonSchemaValueException: pass\n                            if data__packagedata_key_one_of_count3 < 2:\n                                try:\n                                    if data__packagedata_key != \"*\":\n                                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-data must be same as const definition: *\", value=data__packagedata_key, name=\"\" + (name_prefix or \"data\") + \".package-data\", definition={'const': '*'}, rule='const')\n                                    data__packagedata_key_one_of_count3 += 1\n                                except JsonSchemaValueException: pass\n                            if data__packagedata_key_one_of_count3 != 1:\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-data must be valid exactly by one definition\" + (\" (\" + str(data__packagedata_key_one_of_count3) + \" matches found)\"), value=data__packagedata_key, name=\"\" + (name_prefix or \"data\") + \".package-data\", definition={'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, rule='oneOf')\n                        except JsonSchemaValueException:\n                            data__packagedata_property_names = False\n                    if not data__packagedata_property_names:\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".package-data must be named by propertyName definition\", value=data__packagedata, name=\"\" + (name_prefix or \"data\") + \".package-data\", definition={'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='propertyNames')\n        if \"include-package-data\" in data_keys:\n            data_keys.remove(\"include-package-data\")\n            data__includepackagedata = data[\"include-package-data\"]\n            if not isinstance(data__includepackagedata, (bool)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".include-package-data must be boolean\", value=data__includepackagedata, name=\"\" + (name_prefix or \"data\") + \".include-package-data\", definition={'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'boolean'}, rule='type')\n        if \"exclude-package-data\" in data_keys:\n            data_keys.remove(\"exclude-package-data\")\n            data__excludepackagedata = data[\"exclude-package-data\"]\n            if not isinstance(data__excludepackagedata, (dict)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".exclude-package-data must be object\", value=data__excludepackagedata, name=\"\" + (name_prefix or \"data\") + \".exclude-package-data\", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')\n            data__excludepackagedata_is_dict = isinstance(data__excludepackagedata, dict)\n            if data__excludepackagedata_is_dict:\n                data__excludepackagedata_keys = set(data__excludepackagedata.keys())\n                for data__excludepackagedata_key, data__excludepackagedata_val in data__excludepackagedata.items():\n                    if REGEX_PATTERNS['^.*$'].search(data__excludepackagedata_key):\n                        if data__excludepackagedata_key in data__excludepackagedata_keys:\n                            data__excludepackagedata_keys.remove(data__excludepackagedata_key)\n                        if not isinstance(data__excludepackagedata_val, (list, tuple)):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".exclude-package-data.{data__excludepackagedata_key}\".format(**locals()) + \" must be array\", value=data__excludepackagedata_val, name=\"\" + (name_prefix or \"data\") + \".exclude-package-data.{data__excludepackagedata_key}\".format(**locals()) + \"\", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')\n                        data__excludepackagedata_val_is_list = isinstance(data__excludepackagedata_val, (list, tuple))\n                        if data__excludepackagedata_val_is_list:\n                            data__excludepackagedata_val_len = len(data__excludepackagedata_val)\n                            for data__excludepackagedata_val_x, data__excludepackagedata_val_item in enumerate(data__excludepackagedata_val):\n                                if not isinstance(data__excludepackagedata_val_item, (str)):\n                                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".exclude-package-data.{data__excludepackagedata_key}[{data__excludepackagedata_val_x}]\".format(**locals()) + \" must be string\", value=data__excludepackagedata_val_item, name=\"\" + (name_prefix or \"data\") + \".exclude-package-data.{data__excludepackagedata_key}[{data__excludepackagedata_val_x}]\".format(**locals()) + \"\", definition={'type': 'string'}, rule='type')\n                if data__excludepackagedata_keys:\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".exclude-package-data must not contain \"+str(data__excludepackagedata_keys)+\" properties\", value=data__excludepackagedata, name=\"\" + (name_prefix or \"data\") + \".exclude-package-data\", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='additionalProperties')\n                data__excludepackagedata_len = len(data__excludepackagedata)\n                if data__excludepackagedata_len != 0:\n                    data__excludepackagedata_property_names = True\n                    for data__excludepackagedata_key in data__excludepackagedata:\n                        try:\n                            data__excludepackagedata_key_one_of_count4 = 0\n                            if data__excludepackagedata_key_one_of_count4 < 2:\n                                try:\n                                    if isinstance(data__excludepackagedata_key, str):\n                                        if not custom_formats[\"python-module-name\"](data__excludepackagedata_key):\n                                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".exclude-package-data must be python-module-name\", value=data__excludepackagedata_key, name=\"\" + (name_prefix or \"data\") + \".exclude-package-data\", definition={'format': 'python-module-name'}, rule='format')\n                                    data__excludepackagedata_key_one_of_count4 += 1\n                                except JsonSchemaValueException: pass\n                            if data__excludepackagedata_key_one_of_count4 < 2:\n                                try:\n                                    if data__excludepackagedata_key != \"*\":\n                                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".exclude-package-data must be same as const definition: *\", value=data__excludepackagedata_key, name=\"\" + (name_prefix or \"data\") + \".exclude-package-data\", definition={'const': '*'}, rule='const')\n                                    data__excludepackagedata_key_one_of_count4 += 1\n                                except JsonSchemaValueException: pass\n                            if data__excludepackagedata_key_one_of_count4 != 1:\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".exclude-package-data must be valid exactly by one definition\" + (\" (\" + str(data__excludepackagedata_key_one_of_count4) + \" matches found)\"), value=data__excludepackagedata_key, name=\"\" + (name_prefix or \"data\") + \".exclude-package-data\", definition={'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, rule='oneOf')\n                        except JsonSchemaValueException:\n                            data__excludepackagedata_property_names = False\n                    if not data__excludepackagedata_property_names:\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".exclude-package-data must be named by propertyName definition\", value=data__excludepackagedata, name=\"\" + (name_prefix or \"data\") + \".exclude-package-data\", definition={'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='propertyNames')\n        if \"namespace-packages\" in data_keys:\n            data_keys.remove(\"namespace-packages\")\n            data__namespacepackages = data[\"namespace-packages\"]\n            if not isinstance(data__namespacepackages, (list, tuple)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".namespace-packages must be array\", value=data__namespacepackages, name=\"\" + (name_prefix or \"data\") + \".namespace-packages\", definition={'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html'}, rule='type')\n            data__namespacepackages_is_list = isinstance(data__namespacepackages, (list, tuple))\n            if data__namespacepackages_is_list:\n                data__namespacepackages_len = len(data__namespacepackages)\n                for data__namespacepackages_x, data__namespacepackages_item in enumerate(data__namespacepackages):\n                    if not isinstance(data__namespacepackages_item, (str)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".namespace-packages[{data__namespacepackages_x}]\".format(**locals()) + \" must be string\", value=data__namespacepackages_item, name=\"\" + (name_prefix or \"data\") + \".namespace-packages[{data__namespacepackages_x}]\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'python-module-name'}, rule='type')\n                    if isinstance(data__namespacepackages_item, str):\n                        if not custom_formats[\"python-module-name\"](data__namespacepackages_item):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".namespace-packages[{data__namespacepackages_x}]\".format(**locals()) + \" must be python-module-name\", value=data__namespacepackages_item, name=\"\" + (name_prefix or \"data\") + \".namespace-packages[{data__namespacepackages_x}]\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'python-module-name'}, rule='format')\n        if \"py-modules\" in data_keys:\n            data_keys.remove(\"py-modules\")\n            data__pymodules = data[\"py-modules\"]\n            if not isinstance(data__pymodules, (list, tuple)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".py-modules must be array\", value=data__pymodules, name=\"\" + (name_prefix or \"data\") + \".py-modules\", definition={'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, rule='type')\n            data__pymodules_is_list = isinstance(data__pymodules, (list, tuple))\n            if data__pymodules_is_list:\n                data__pymodules_len = len(data__pymodules)\n                for data__pymodules_x, data__pymodules_item in enumerate(data__pymodules):\n                    if not isinstance(data__pymodules_item, (str)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".py-modules[{data__pymodules_x}]\".format(**locals()) + \" must be string\", value=data__pymodules_item, name=\"\" + (name_prefix or \"data\") + \".py-modules[{data__pymodules_x}]\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'python-module-name'}, rule='type')\n                    if isinstance(data__pymodules_item, str):\n                        if not custom_formats[\"python-module-name\"](data__pymodules_item):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".py-modules[{data__pymodules_x}]\".format(**locals()) + \" must be python-module-name\", value=data__pymodules_item, name=\"\" + (name_prefix or \"data\") + \".py-modules[{data__pymodules_x}]\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'python-module-name'}, rule='format')\n        if \"data-files\" in data_keys:\n            data_keys.remove(\"data-files\")\n            data__datafiles = data[\"data-files\"]\n            if not isinstance(data__datafiles, (dict)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".data-files must be object\", value=data__datafiles, name=\"\" + (name_prefix or \"data\") + \".data-files\", definition={'$$description': ['**DEPRECATED**: dict-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', \"Please notice this don't work with wheels. See `data files support\", '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, rule='type')\n            data__datafiles_is_dict = isinstance(data__datafiles, dict)\n            if data__datafiles_is_dict:\n                data__datafiles_keys = set(data__datafiles.keys())\n                for data__datafiles_key, data__datafiles_val in data__datafiles.items():\n                    if REGEX_PATTERNS['^.*$'].search(data__datafiles_key):\n                        if data__datafiles_key in data__datafiles_keys:\n                            data__datafiles_keys.remove(data__datafiles_key)\n                        if not isinstance(data__datafiles_val, (list, tuple)):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".data-files.{data__datafiles_key}\".format(**locals()) + \" must be array\", value=data__datafiles_val, name=\"\" + (name_prefix or \"data\") + \".data-files.{data__datafiles_key}\".format(**locals()) + \"\", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')\n                        data__datafiles_val_is_list = isinstance(data__datafiles_val, (list, tuple))\n                        if data__datafiles_val_is_list:\n                            data__datafiles_val_len = len(data__datafiles_val)\n                            for data__datafiles_val_x, data__datafiles_val_item in enumerate(data__datafiles_val):\n                                if not isinstance(data__datafiles_val_item, (str)):\n                                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".data-files.{data__datafiles_key}[{data__datafiles_val_x}]\".format(**locals()) + \" must be string\", value=data__datafiles_val_item, name=\"\" + (name_prefix or \"data\") + \".data-files.{data__datafiles_key}[{data__datafiles_val_x}]\".format(**locals()) + \"\", definition={'type': 'string'}, rule='type')\n        if \"cmdclass\" in data_keys:\n            data_keys.remove(\"cmdclass\")\n            data__cmdclass = data[\"cmdclass\"]\n            if not isinstance(data__cmdclass, (dict)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".cmdclass must be object\", value=data__cmdclass, name=\"\" + (name_prefix or \"data\") + \".cmdclass\", definition={'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., \"dotted\" form with module), e.g.::\\n\\n', '    cmdclass = {mycmd = \"pkg.subpkg.module.CommandClass\"}\\n\\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, rule='type')\n            data__cmdclass_is_dict = isinstance(data__cmdclass, dict)\n            if data__cmdclass_is_dict:\n                data__cmdclass_keys = set(data__cmdclass.keys())\n                for data__cmdclass_key, data__cmdclass_val in data__cmdclass.items():\n                    if REGEX_PATTERNS['^.*$'].search(data__cmdclass_key):\n                        if data__cmdclass_key in data__cmdclass_keys:\n                            data__cmdclass_keys.remove(data__cmdclass_key)\n                        if not isinstance(data__cmdclass_val, (str)):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".cmdclass.{data__cmdclass_key}\".format(**locals()) + \" must be string\", value=data__cmdclass_val, name=\"\" + (name_prefix or \"data\") + \".cmdclass.{data__cmdclass_key}\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'python-qualified-identifier'}, rule='type')\n                        if isinstance(data__cmdclass_val, str):\n                            if not custom_formats[\"python-qualified-identifier\"](data__cmdclass_val):\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".cmdclass.{data__cmdclass_key}\".format(**locals()) + \" must be python-qualified-identifier\", value=data__cmdclass_val, name=\"\" + (name_prefix or \"data\") + \".cmdclass.{data__cmdclass_key}\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'python-qualified-identifier'}, rule='format')\n        if \"license-files\" in data_keys:\n            data_keys.remove(\"license-files\")\n            data__licensefiles = data[\"license-files\"]\n            if not isinstance(data__licensefiles, (list, tuple)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".license-files must be array\", value=data__licensefiles, name=\"\" + (name_prefix or \"data\") + \".license-files\", definition={'type': 'array', 'items': {'type': 'string'}, '$$description': ['PROVISIONAL: List of glob patterns for all license files being distributed.', '(might become standard with PEP 639).'], 'default': ['LICEN[CS]E*', ' COPYING*', ' NOTICE*', 'AUTHORS*'], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, rule='type')\n            data__licensefiles_is_list = isinstance(data__licensefiles, (list, tuple))\n            if data__licensefiles_is_list:\n                data__licensefiles_len = len(data__licensefiles)\n                for data__licensefiles_x, data__licensefiles_item in enumerate(data__licensefiles):\n                    if not isinstance(data__licensefiles_item, (str)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".license-files[{data__licensefiles_x}]\".format(**locals()) + \" must be string\", value=data__licensefiles_item, name=\"\" + (name_prefix or \"data\") + \".license-files[{data__licensefiles_x}]\".format(**locals()) + \"\", definition={'type': 'string'}, rule='type')\n        else: data[\"license-files\"] = ['LICEN[CS]E*', ' COPYING*', ' NOTICE*', 'AUTHORS*']\n        if \"dynamic\" in data_keys:\n            data_keys.remove(\"dynamic\")\n            data__dynamic = data[\"dynamic\"]\n            if not isinstance(data__dynamic, (dict)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dynamic must be object\", value=data__dynamic, name=\"\" + (name_prefix or \"data\") + \".dynamic\", definition={'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'title': \"'attr:' directive\", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}}}, 'readme': {'anyOf': [{'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}}}, rule='type')\n            data__dynamic_is_dict = isinstance(data__dynamic, dict)\n            if data__dynamic_is_dict:\n                data__dynamic_keys = set(data__dynamic.keys())\n                if \"version\" in data__dynamic_keys:\n                    data__dynamic_keys.remove(\"version\")\n                    data__dynamic__version = data__dynamic[\"version\"]\n                    data__dynamic__version_one_of_count5 = 0\n                    if data__dynamic__version_one_of_count5 < 2:\n                        try:\n                            validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_attr_directive(data__dynamic__version, custom_formats, (name_prefix or \"data\") + \".dynamic.version\")\n                            data__dynamic__version_one_of_count5 += 1\n                        except JsonSchemaValueException: pass\n                    if data__dynamic__version_one_of_count5 < 2:\n                        try:\n                            validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data__dynamic__version, custom_formats, (name_prefix or \"data\") + \".dynamic.version\")\n                            data__dynamic__version_one_of_count5 += 1\n                        except JsonSchemaValueException: pass\n                    if data__dynamic__version_one_of_count5 != 1:\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dynamic.version must be valid exactly by one definition\" + (\" (\" + str(data__dynamic__version_one_of_count5) + \" matches found)\"), value=data__dynamic__version, name=\"\" + (name_prefix or \"data\") + \".dynamic.version\", definition={'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'title': \"'attr:' directive\", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, rule='oneOf')\n                if \"classifiers\" in data__dynamic_keys:\n                    data__dynamic_keys.remove(\"classifiers\")\n                    data__dynamic__classifiers = data__dynamic[\"classifiers\"]\n                    validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data__dynamic__classifiers, custom_formats, (name_prefix or \"data\") + \".dynamic.classifiers\")\n                if \"description\" in data__dynamic_keys:\n                    data__dynamic_keys.remove(\"description\")\n                    data__dynamic__description = data__dynamic[\"description\"]\n                    validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data__dynamic__description, custom_formats, (name_prefix or \"data\") + \".dynamic.description\")\n                if \"dependencies\" in data__dynamic_keys:\n                    data__dynamic_keys.remove(\"dependencies\")\n                    data__dynamic__dependencies = data__dynamic[\"dependencies\"]\n                    validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data__dynamic__dependencies, custom_formats, (name_prefix or \"data\") + \".dynamic.dependencies\")\n                if \"entry-points\" in data__dynamic_keys:\n                    data__dynamic_keys.remove(\"entry-points\")\n                    data__dynamic__entrypoints = data__dynamic[\"entry-points\"]\n                    validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data__dynamic__entrypoints, custom_formats, (name_prefix or \"data\") + \".dynamic.entry-points\")\n                if \"optional-dependencies\" in data__dynamic_keys:\n                    data__dynamic_keys.remove(\"optional-dependencies\")\n                    data__dynamic__optionaldependencies = data__dynamic[\"optional-dependencies\"]\n                    if not isinstance(data__dynamic__optionaldependencies, (dict)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dynamic.optional-dependencies must be object\", value=data__dynamic__optionaldependencies, name=\"\" + (name_prefix or \"data\") + \".dynamic.optional-dependencies\", definition={'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}}}, rule='type')\n                    data__dynamic__optionaldependencies_is_dict = isinstance(data__dynamic__optionaldependencies, dict)\n                    if data__dynamic__optionaldependencies_is_dict:\n                        data__dynamic__optionaldependencies_keys = set(data__dynamic__optionaldependencies.keys())\n                        for data__dynamic__optionaldependencies_key, data__dynamic__optionaldependencies_val in data__dynamic__optionaldependencies.items():\n                            if REGEX_PATTERNS['.+'].search(data__dynamic__optionaldependencies_key):\n                                if data__dynamic__optionaldependencies_key in data__dynamic__optionaldependencies_keys:\n                                    data__dynamic__optionaldependencies_keys.remove(data__dynamic__optionaldependencies_key)\n                                validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data__dynamic__optionaldependencies_val, custom_formats, (name_prefix or \"data\") + \".dynamic.optional-dependencies.{data__dynamic__optionaldependencies_key}\")\n                        if data__dynamic__optionaldependencies_keys:\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dynamic.optional-dependencies must not contain \"+str(data__dynamic__optionaldependencies_keys)+\" properties\", value=data__dynamic__optionaldependencies, name=\"\" + (name_prefix or \"data\") + \".dynamic.optional-dependencies\", definition={'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}}}, rule='additionalProperties')\n                        data__dynamic__optionaldependencies_len = len(data__dynamic__optionaldependencies)\n                        if data__dynamic__optionaldependencies_len != 0:\n                            data__dynamic__optionaldependencies_property_names = True\n                            for data__dynamic__optionaldependencies_key in data__dynamic__optionaldependencies:\n                                try:\n                                    if isinstance(data__dynamic__optionaldependencies_key, str):\n                                        if not custom_formats[\"python-identifier\"](data__dynamic__optionaldependencies_key):\n                                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dynamic.optional-dependencies must be python-identifier\", value=data__dynamic__optionaldependencies_key, name=\"\" + (name_prefix or \"data\") + \".dynamic.optional-dependencies\", definition={'format': 'python-identifier'}, rule='format')\n                                except JsonSchemaValueException:\n                                    data__dynamic__optionaldependencies_property_names = False\n                            if not data__dynamic__optionaldependencies_property_names:\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dynamic.optional-dependencies must be named by propertyName definition\", value=data__dynamic__optionaldependencies, name=\"\" + (name_prefix or \"data\") + \".dynamic.optional-dependencies\", definition={'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}}}, rule='propertyNames')\n                if \"readme\" in data__dynamic_keys:\n                    data__dynamic_keys.remove(\"readme\")\n                    data__dynamic__readme = data__dynamic[\"readme\"]\n                    data__dynamic__readme_any_of_count6 = 0\n                    if not data__dynamic__readme_any_of_count6:\n                        try:\n                            validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data__dynamic__readme, custom_formats, (name_prefix or \"data\") + \".dynamic.readme\")\n                            data__dynamic__readme_any_of_count6 += 1\n                        except JsonSchemaValueException: pass\n                    if not data__dynamic__readme_any_of_count6:\n                        try:\n                            data__dynamic__readme_is_dict = isinstance(data__dynamic__readme, dict)\n                            if data__dynamic__readme_is_dict:\n                                data__dynamic__readme_keys = set(data__dynamic__readme.keys())\n                                if \"content-type\" in data__dynamic__readme_keys:\n                                    data__dynamic__readme_keys.remove(\"content-type\")\n                                    data__dynamic__readme__contenttype = data__dynamic__readme[\"content-type\"]\n                                    if not isinstance(data__dynamic__readme__contenttype, (str)):\n                                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dynamic.readme.content-type must be string\", value=data__dynamic__readme__contenttype, name=\"\" + (name_prefix or \"data\") + \".dynamic.readme.content-type\", definition={'type': 'string'}, rule='type')\n                            data__dynamic__readme_any_of_count6 += 1\n                        except JsonSchemaValueException: pass\n                    if not data__dynamic__readme_any_of_count6:\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dynamic.readme cannot be validated by any definition\", value=data__dynamic__readme, name=\"\" + (name_prefix or \"data\") + \".dynamic.readme\", definition={'anyOf': [{'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}, rule='anyOf')\n                    data__dynamic__readme_is_dict = isinstance(data__dynamic__readme, dict)\n                    if data__dynamic__readme_is_dict:\n                        data__dynamic__readme_len = len(data__dynamic__readme)\n                        if not all(prop in data__dynamic__readme for prop in ['file']):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dynamic.readme must contain ['file'] properties\", value=data__dynamic__readme, name=\"\" + (name_prefix or \"data\") + \".dynamic.readme\", definition={'anyOf': [{'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}, rule='required')\n                if data__dynamic_keys:\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dynamic must not contain \"+str(data__dynamic_keys)+\" properties\", value=data__dynamic, name=\"\" + (name_prefix or \"data\") + \".dynamic\", definition={'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'title': \"'attr:' directive\", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}}}, 'readme': {'anyOf': [{'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}}}, rule='additionalProperties')\n        if data_keys:\n            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must not contain \"+str(data_keys)+\" properties\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://setuptools.pypa.io/en/latest/references/keywords.html', 'title': '``tool.setuptools`` table', '$$description': ['Please notice for the time being the ``setuptools`` project does not specify', 'a way of configuring builds via ``pyproject.toml``.', 'Therefore this schema should be taken just as a *\"thought experiment\"* on how', 'this *might be done*, by following the principles established in', '`ini2toml <https://ini2toml.readthedocs.io/en/latest/setuptools_pep621.html>`_.', 'It considers only ``setuptools`` `parameters', '<https://setuptools.pypa.io/en/latest/userguide/declarative_config.html>`_', 'that can currently be configured via ``setup.cfg`` and are not covered by :pep:`621`', 'but intentionally excludes ``dependency_links`` and ``setup_requires``.', 'NOTE: ``scripts`` was renamed to ``script-files`` to avoid confusion with', 'entry-point based scripts (defined in :pep:`621`).'], 'type': 'object', 'additionalProperties': False, 'properties': {'platforms': {'type': 'array', 'items': {'type': 'string'}}, 'provides': {'$$description': ['Package and virtual package names contained within this package', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'obsoletes': {'$$description': ['Packages which this package renders obsolete', '**(not supported by pip)**'], 'type': 'array', 'items': {'type': 'string', 'format': 'pep508-identifier'}}, 'zip-safe': {'description': 'Whether the project can be safely installed and run from a zip file.', 'type': 'boolean'}, 'script-files': {'description': 'Legacy way of defining scripts (entry-points are preferred).', 'type': 'array', 'items': {'type': 'string'}, '$comment': 'TODO: is this field deprecated/should be removed?'}, 'eager-resources': {'$$description': ['Resources that should be extracted together, if any of them is needed,', 'or if any C extensions included in the project are imported.'], 'type': 'array', 'items': {'type': 'string'}}, 'packages': {'$$description': ['Packages that should be included in the distribution.', 'It can be given either as a list of package identifiers', 'or as a ``dict``-like structure with a single key ``find``', 'which corresponds to a dynamic call to', '``setuptools.config.expand.find_packages`` function.', 'The ``find`` key is associated with a nested ``dict``-like structure that can', 'contain ``where``, ``include``, ``exclude`` and ``namespaces`` keys,', 'mimicking the keyword arguments of the associated function.'], 'oneOf': [{'title': 'Array of Python package identifiers', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}}, {'$id': '#/definitions/find-directive', 'title': \"'find:' directive\", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '<https://setuptools.pypa.io/en/latest/userguide/package_discovery.html>`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}]}, 'package-dir': {'$$description': [':class:`dict`-like structure mapping from package names to directories where their', 'code can be found.', 'The empty string (as key) means that all packages are contained inside', 'the given directory will be included in the distribution.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': ''}]}, 'patternProperties': {'^.*$': {'type': 'string'}}}, 'package-data': {'$$description': ['Mapping from package names to lists of glob patterns.', 'Usually this option is not needed when using ``include-package-data = true``', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'include-package-data': {'$$description': ['Automatically include any data files inside the package directories', 'that are specified by ``MANIFEST.in``', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'boolean'}, 'exclude-package-data': {'$$description': ['Mapping from package names to lists of glob patterns that should be excluded', 'For more information on how to include data files, check ``setuptools`` `docs', '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_.'], 'type': 'object', 'additionalProperties': False, 'propertyNames': {'oneOf': [{'format': 'python-module-name'}, {'const': '*'}]}, 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'namespace-packages': {'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'https://setuptools.pypa.io/en/latest/userguide/package_discovery.html'}, 'py-modules': {'description': 'Modules that setuptools will manipulate', 'type': 'array', 'items': {'type': 'string', 'format': 'python-module-name'}, '$comment': 'TODO: clarify the relationship with ``packages``'}, 'data-files': {'$$description': ['**DEPRECATED**: dict-like structure where each key represents a directory and', 'the value is a list of glob patterns that should be installed in them.', \"Please notice this don't work with wheels. See `data files support\", '<https://setuptools.pypa.io/en/latest/userguide/datafiles.html>`_'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'array', 'items': {'type': 'string'}}}}, 'cmdclass': {'$$description': ['Mapping of distutils-style command names to ``setuptools.Command`` subclasses', 'which in turn should be represented by strings with a qualified class name', '(i.e., \"dotted\" form with module), e.g.::\\n\\n', '    cmdclass = {mycmd = \"pkg.subpkg.module.CommandClass\"}\\n\\n', 'The command class should be a directly defined at the top-level of the', 'containing module (no class nesting).'], 'type': 'object', 'patternProperties': {'^.*$': {'type': 'string', 'format': 'python-qualified-identifier'}}}, 'license-files': {'type': 'array', 'items': {'type': 'string'}, '$$description': ['PROVISIONAL: List of glob patterns for all license files being distributed.', '(might become standard with PEP 639).'], 'default': ['LICEN[CS]E*', ' COPYING*', ' NOTICE*', 'AUTHORS*'], '$comment': 'TODO: revise if PEP 639 is accepted. Probably ``project.license-files``?'}, 'dynamic': {'type': 'object', 'description': 'Instructions for loading :pep:`621`-related metadata dynamically', 'additionalProperties': False, 'properties': {'version': {'$$description': ['A version dynamically loaded via either the ``attr:`` or ``file:``', 'directives. Please make sure the given file or attribute respects :pep:`440`.'], 'oneOf': [{'title': \"'attr:' directive\", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}]}, 'classifiers': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'description': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'dependencies': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'entry-points': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'optional-dependencies': {'type': 'object', 'propertyNames': {'format': 'python-identifier'}, 'additionalProperties': False, 'patternProperties': {'.+': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}}}, 'readme': {'anyOf': [{'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, {'properties': {'content-type': {'type': 'string'}}}], 'required': ['file']}}}}, 'definitions': {'file-directive': {'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, 'attr-directive': {'title': \"'attr:' directive\", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, 'find-directive': {'$id': '#/definitions/find-directive', 'title': \"'find:' directive\", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '<https://setuptools.pypa.io/en/latest/userguide/package_discovery.html>`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}}}, rule='additionalProperties')\n    return data\n\ndef validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_file_directive(data, custom_formats={}, name_prefix=None):\n    if not isinstance(data, (dict)):\n        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must be object\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, rule='type')\n    data_is_dict = isinstance(data, dict)\n    if data_is_dict:\n        data_len = len(data)\n        if not all(prop in data for prop in ['file']):\n            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must contain ['file'] properties\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, rule='required')\n        data_keys = set(data.keys())\n        if \"file\" in data_keys:\n            data_keys.remove(\"file\")\n            data__file = data[\"file\"]\n            data__file_one_of_count7 = 0\n            if data__file_one_of_count7 < 2:\n                try:\n                    if not isinstance(data__file, (str)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".file must be string\", value=data__file, name=\"\" + (name_prefix or \"data\") + \".file\", definition={'type': 'string'}, rule='type')\n                    data__file_one_of_count7 += 1\n                except JsonSchemaValueException: pass\n            if data__file_one_of_count7 < 2:\n                try:\n                    if not isinstance(data__file, (list, tuple)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".file must be array\", value=data__file, name=\"\" + (name_prefix or \"data\") + \".file\", definition={'type': 'array', 'items': {'type': 'string'}}, rule='type')\n                    data__file_is_list = isinstance(data__file, (list, tuple))\n                    if data__file_is_list:\n                        data__file_len = len(data__file)\n                        for data__file_x, data__file_item in enumerate(data__file):\n                            if not isinstance(data__file_item, (str)):\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".file[{data__file_x}]\".format(**locals()) + \" must be string\", value=data__file_item, name=\"\" + (name_prefix or \"data\") + \".file[{data__file_x}]\".format(**locals()) + \"\", definition={'type': 'string'}, rule='type')\n                    data__file_one_of_count7 += 1\n                except JsonSchemaValueException: pass\n            if data__file_one_of_count7 != 1:\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".file must be valid exactly by one definition\" + (\" (\" + str(data__file_one_of_count7) + \" matches found)\"), value=data__file, name=\"\" + (name_prefix or \"data\") + \".file\", definition={'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}, rule='oneOf')\n        if data_keys:\n            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must not contain \"+str(data_keys)+\" properties\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$id': '#/definitions/file-directive', 'title': \"'file:' directive\", 'description': 'Value is read from a file (or list of files and then concatenated)', 'type': 'object', 'additionalProperties': False, 'properties': {'file': {'oneOf': [{'type': 'string'}, {'type': 'array', 'items': {'type': 'string'}}]}}, 'required': ['file']}, rule='additionalProperties')\n    return data\n\ndef validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_attr_directive(data, custom_formats={}, name_prefix=None):\n    if not isinstance(data, (dict)):\n        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must be object\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'title': \"'attr:' directive\", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, rule='type')\n    data_is_dict = isinstance(data, dict)\n    if data_is_dict:\n        data_len = len(data)\n        if not all(prop in data for prop in ['attr']):\n            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must contain ['attr'] properties\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'title': \"'attr:' directive\", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, rule='required')\n        data_keys = set(data.keys())\n        if \"attr\" in data_keys:\n            data_keys.remove(\"attr\")\n            data__attr = data[\"attr\"]\n            if not isinstance(data__attr, (str)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".attr must be string\", value=data__attr, name=\"\" + (name_prefix or \"data\") + \".attr\", definition={'type': 'string'}, rule='type')\n        if data_keys:\n            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must not contain \"+str(data_keys)+\" properties\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'title': \"'attr:' directive\", '$id': '#/definitions/attr-directive', '$$description': ['Value is read from a module attribute. Supports callables and iterables;', 'unsupported types are cast via ``str()``'], 'type': 'object', 'additionalProperties': False, 'properties': {'attr': {'type': 'string'}}, 'required': ['attr']}, rule='additionalProperties')\n    return data\n\ndef validate_https___setuptools_pypa_io_en_latest_references_keywords_html__definitions_find_directive(data, custom_formats={}, name_prefix=None):\n    if not isinstance(data, (dict)):\n        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must be object\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$id': '#/definitions/find-directive', 'title': \"'find:' directive\", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '<https://setuptools.pypa.io/en/latest/userguide/package_discovery.html>`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}, rule='type')\n    data_is_dict = isinstance(data, dict)\n    if data_is_dict:\n        data_keys = set(data.keys())\n        if \"find\" in data_keys:\n            data_keys.remove(\"find\")\n            data__find = data[\"find\"]\n            if not isinstance(data__find, (dict)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".find must be object\", value=data__find, name=\"\" + (name_prefix or \"data\") + \".find\", definition={'type': 'object', '$$description': ['Dynamic `package discovery', '<https://setuptools.pypa.io/en/latest/userguide/package_discovery.html>`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}, rule='type')\n            data__find_is_dict = isinstance(data__find, dict)\n            if data__find_is_dict:\n                data__find_keys = set(data__find.keys())\n                if \"where\" in data__find_keys:\n                    data__find_keys.remove(\"where\")\n                    data__find__where = data__find[\"where\"]\n                    if not isinstance(data__find__where, (list, tuple)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".find.where must be array\", value=data__find__where, name=\"\" + (name_prefix or \"data\") + \".find.where\", definition={'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, rule='type')\n                    data__find__where_is_list = isinstance(data__find__where, (list, tuple))\n                    if data__find__where_is_list:\n                        data__find__where_len = len(data__find__where)\n                        for data__find__where_x, data__find__where_item in enumerate(data__find__where):\n                            if not isinstance(data__find__where_item, (str)):\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".find.where[{data__find__where_x}]\".format(**locals()) + \" must be string\", value=data__find__where_item, name=\"\" + (name_prefix or \"data\") + \".find.where[{data__find__where_x}]\".format(**locals()) + \"\", definition={'type': 'string'}, rule='type')\n                if \"exclude\" in data__find_keys:\n                    data__find_keys.remove(\"exclude\")\n                    data__find__exclude = data__find[\"exclude\"]\n                    if not isinstance(data__find__exclude, (list, tuple)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".find.exclude must be array\", value=data__find__exclude, name=\"\" + (name_prefix or \"data\") + \".find.exclude\", definition={'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, rule='type')\n                    data__find__exclude_is_list = isinstance(data__find__exclude, (list, tuple))\n                    if data__find__exclude_is_list:\n                        data__find__exclude_len = len(data__find__exclude)\n                        for data__find__exclude_x, data__find__exclude_item in enumerate(data__find__exclude):\n                            if not isinstance(data__find__exclude_item, (str)):\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".find.exclude[{data__find__exclude_x}]\".format(**locals()) + \" must be string\", value=data__find__exclude_item, name=\"\" + (name_prefix or \"data\") + \".find.exclude[{data__find__exclude_x}]\".format(**locals()) + \"\", definition={'type': 'string'}, rule='type')\n                if \"include\" in data__find_keys:\n                    data__find_keys.remove(\"include\")\n                    data__find__include = data__find[\"include\"]\n                    if not isinstance(data__find__include, (list, tuple)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".find.include must be array\", value=data__find__include, name=\"\" + (name_prefix or \"data\") + \".find.include\", definition={'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, rule='type')\n                    data__find__include_is_list = isinstance(data__find__include, (list, tuple))\n                    if data__find__include_is_list:\n                        data__find__include_len = len(data__find__include)\n                        for data__find__include_x, data__find__include_item in enumerate(data__find__include):\n                            if not isinstance(data__find__include_item, (str)):\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".find.include[{data__find__include_x}]\".format(**locals()) + \" must be string\", value=data__find__include_item, name=\"\" + (name_prefix or \"data\") + \".find.include[{data__find__include_x}]\".format(**locals()) + \"\", definition={'type': 'string'}, rule='type')\n                if \"namespaces\" in data__find_keys:\n                    data__find_keys.remove(\"namespaces\")\n                    data__find__namespaces = data__find[\"namespaces\"]\n                    if not isinstance(data__find__namespaces, (bool)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".find.namespaces must be boolean\", value=data__find__namespaces, name=\"\" + (name_prefix or \"data\") + \".find.namespaces\", definition={'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}, rule='type')\n                if data__find_keys:\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".find must not contain \"+str(data__find_keys)+\" properties\", value=data__find, name=\"\" + (name_prefix or \"data\") + \".find\", definition={'type': 'object', '$$description': ['Dynamic `package discovery', '<https://setuptools.pypa.io/en/latest/userguide/package_discovery.html>`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}, rule='additionalProperties')\n        if data_keys:\n            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must not contain \"+str(data_keys)+\" properties\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$id': '#/definitions/find-directive', 'title': \"'find:' directive\", 'type': 'object', 'additionalProperties': False, 'properties': {'find': {'type': 'object', '$$description': ['Dynamic `package discovery', '<https://setuptools.pypa.io/en/latest/userguide/package_discovery.html>`_.'], 'additionalProperties': False, 'properties': {'where': {'description': 'Directories to be searched for packages (Unix-style relative path)', 'type': 'array', 'items': {'type': 'string'}}, 'exclude': {'type': 'array', '$$description': ['Exclude packages that match the values listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'include': {'type': 'array', '$$description': ['Restrict the found packages to just the ones listed in this field.', \"Can container shell-style wildcards (e.g. ``'pkg.*'``)\"], 'items': {'type': 'string'}}, 'namespaces': {'type': 'boolean', '$$description': ['When ``True``, directories without a ``__init__.py`` file will also', 'be scanned for :pep:`420`-style implicit namespaces']}}}}}, rule='additionalProperties')\n    return data\n\ndef validate_https___docs_python_org_3_install(data, custom_formats={}, name_prefix=None):\n    if not isinstance(data, (dict)):\n        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must be object\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://docs.python.org/3/install/', 'title': '``tool.distutils`` table', '$$description': ['Originally, ``distutils`` allowed developers to configure arguments for', '``setup.py`` scripts via `distutils configuration files', '<https://docs.python.org/3/install/#distutils-configuration-files>`_.', '``tool.distutils`` subtables could be used with the same purpose', '(NOT CURRENTLY IMPLEMENTED).'], 'type': 'object', 'properties': {'global': {'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}}, 'patternProperties': {'.+': {'type': 'object'}}, '$comment': 'TODO: Is there a practical way of making this schema more specific?'}, rule='type')\n    data_is_dict = isinstance(data, dict)\n    if data_is_dict:\n        data_keys = set(data.keys())\n        if \"global\" in data_keys:\n            data_keys.remove(\"global\")\n            data__global = data[\"global\"]\n            if not isinstance(data__global, (dict)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".global must be object\", value=data__global, name=\"\" + (name_prefix or \"data\") + \".global\", definition={'type': 'object', 'description': 'Global options applied to all ``distutils`` commands'}, rule='type')\n        for data_key, data_val in data.items():\n            if REGEX_PATTERNS['.+'].search(data_key):\n                if data_key in data_keys:\n                    data_keys.remove(data_key)\n                if not isinstance(data_val, (dict)):\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".{data_key}\".format(**locals()) + \" must be object\", value=data_val, name=\"\" + (name_prefix or \"data\") + \".{data_key}\".format(**locals()) + \"\", definition={'type': 'object'}, rule='type')\n    return data\n\ndef validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata(data, custom_formats={}, name_prefix=None):\n    if not isinstance(data, (dict)):\n        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must be object\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-project-metadata/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '<https://packaging.python.org/specifications/core-metadata/#summary>`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '<https://www.python.org/dev/peps/pep-0621/#readme>`_', \"with meaning similar to the one defined in `core metadata's Description\", '<https://packaging.python.org/specifications/core-metadata/#description>`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '<https://packaging.python.org/specifications/core-metadata/#requires-python>`_.']}, 'license': {'description': '`Project license <https://www.python.org/dev/peps/pep-0621/#license>`_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '<https://packaging.python.org/specifications/core-metadata/#license>`_.']}}, 'required': ['text']}]}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': [\"The people or organizations considered to be the 'authors' of the project.\", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': [\"The people or organizations considered to be the 'maintainers' of the project.\", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier <https://pypi.org/classifiers/>`_.'}, '$$description': ['`Trove classifiers <https://pypi.org/classifiers/>`_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '<https://packaging.python.org/specifications/entry-points/>`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as \"Required\", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='type')\n    data_is_dict = isinstance(data, dict)\n    if data_is_dict:\n        data_len = len(data)\n        if not all(prop in data for prop in ['name']):\n            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must contain ['name'] properties\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-project-metadata/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '<https://packaging.python.org/specifications/core-metadata/#summary>`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '<https://www.python.org/dev/peps/pep-0621/#readme>`_', \"with meaning similar to the one defined in `core metadata's Description\", '<https://packaging.python.org/specifications/core-metadata/#description>`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '<https://packaging.python.org/specifications/core-metadata/#requires-python>`_.']}, 'license': {'description': '`Project license <https://www.python.org/dev/peps/pep-0621/#license>`_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '<https://packaging.python.org/specifications/core-metadata/#license>`_.']}}, 'required': ['text']}]}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': [\"The people or organizations considered to be the 'authors' of the project.\", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': [\"The people or organizations considered to be the 'maintainers' of the project.\", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier <https://pypi.org/classifiers/>`_.'}, '$$description': ['`Trove classifiers <https://pypi.org/classifiers/>`_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '<https://packaging.python.org/specifications/entry-points/>`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as \"Required\", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='required')\n        data_keys = set(data.keys())\n        if \"name\" in data_keys:\n            data_keys.remove(\"name\")\n            data__name = data[\"name\"]\n            if not isinstance(data__name, (str)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".name must be string\", value=data__name, name=\"\" + (name_prefix or \"data\") + \".name\", definition={'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, rule='type')\n            if isinstance(data__name, str):\n                if not custom_formats[\"pep508-identifier\"](data__name):\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".name must be pep508-identifier\", value=data__name, name=\"\" + (name_prefix or \"data\") + \".name\", definition={'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, rule='format')\n        if \"version\" in data_keys:\n            data_keys.remove(\"version\")\n            data__version = data[\"version\"]\n            if not isinstance(data__version, (str)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".version must be string\", value=data__version, name=\"\" + (name_prefix or \"data\") + \".version\", definition={'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, rule='type')\n            if isinstance(data__version, str):\n                if not custom_formats[\"pep440\"](data__version):\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".version must be pep440\", value=data__version, name=\"\" + (name_prefix or \"data\") + \".version\", definition={'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, rule='format')\n        if \"description\" in data_keys:\n            data_keys.remove(\"description\")\n            data__description = data[\"description\"]\n            if not isinstance(data__description, (str)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".description must be string\", value=data__description, name=\"\" + (name_prefix or \"data\") + \".description\", definition={'type': 'string', '$$description': ['The `summary description of the project', '<https://packaging.python.org/specifications/core-metadata/#summary>`_']}, rule='type')\n        if \"readme\" in data_keys:\n            data_keys.remove(\"readme\")\n            data__readme = data[\"readme\"]\n            data__readme_one_of_count8 = 0\n            if data__readme_one_of_count8 < 2:\n                try:\n                    if not isinstance(data__readme, (str)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".readme must be string\", value=data__readme, name=\"\" + (name_prefix or \"data\") + \".readme\", definition={'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, rule='type')\n                    data__readme_one_of_count8 += 1\n                except JsonSchemaValueException: pass\n            if data__readme_one_of_count8 < 2:\n                try:\n                    if not isinstance(data__readme, (dict)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".readme must be object\", value=data__readme, name=\"\" + (name_prefix or \"data\") + \".readme\", definition={'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}, rule='type')\n                    data__readme_any_of_count9 = 0\n                    if not data__readme_any_of_count9:\n                        try:\n                            data__readme_is_dict = isinstance(data__readme, dict)\n                            if data__readme_is_dict:\n                                data__readme_len = len(data__readme)\n                                if not all(prop in data__readme for prop in ['file']):\n                                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".readme must contain ['file'] properties\", value=data__readme, name=\"\" + (name_prefix or \"data\") + \".readme\", definition={'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, rule='required')\n                                data__readme_keys = set(data__readme.keys())\n                                if \"file\" in data__readme_keys:\n                                    data__readme_keys.remove(\"file\")\n                                    data__readme__file = data__readme[\"file\"]\n                                    if not isinstance(data__readme__file, (str)):\n                                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".readme.file must be string\", value=data__readme__file, name=\"\" + (name_prefix or \"data\") + \".readme.file\", definition={'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}, rule='type')\n                            data__readme_any_of_count9 += 1\n                        except JsonSchemaValueException: pass\n                    if not data__readme_any_of_count9:\n                        try:\n                            data__readme_is_dict = isinstance(data__readme, dict)\n                            if data__readme_is_dict:\n                                data__readme_len = len(data__readme)\n                                if not all(prop in data__readme for prop in ['text']):\n                                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".readme must contain ['text'] properties\", value=data__readme, name=\"\" + (name_prefix or \"data\") + \".readme\", definition={'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}, rule='required')\n                                data__readme_keys = set(data__readme.keys())\n                                if \"text\" in data__readme_keys:\n                                    data__readme_keys.remove(\"text\")\n                                    data__readme__text = data__readme[\"text\"]\n                                    if not isinstance(data__readme__text, (str)):\n                                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".readme.text must be string\", value=data__readme__text, name=\"\" + (name_prefix or \"data\") + \".readme.text\", definition={'type': 'string', 'description': 'Full text describing the project.'}, rule='type')\n                            data__readme_any_of_count9 += 1\n                        except JsonSchemaValueException: pass\n                    if not data__readme_any_of_count9:\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".readme cannot be validated by any definition\", value=data__readme, name=\"\" + (name_prefix or \"data\") + \".readme\", definition={'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, rule='anyOf')\n                    data__readme_is_dict = isinstance(data__readme, dict)\n                    if data__readme_is_dict:\n                        data__readme_len = len(data__readme)\n                        if not all(prop in data__readme for prop in ['content-type']):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".readme must contain ['content-type'] properties\", value=data__readme, name=\"\" + (name_prefix or \"data\") + \".readme\", definition={'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}, rule='required')\n                        data__readme_keys = set(data__readme.keys())\n                        if \"content-type\" in data__readme_keys:\n                            data__readme_keys.remove(\"content-type\")\n                            data__readme__contenttype = data__readme[\"content-type\"]\n                            if not isinstance(data__readme__contenttype, (str)):\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".readme.content-type must be string\", value=data__readme__contenttype, name=\"\" + (name_prefix or \"data\") + \".readme.content-type\", definition={'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}, rule='type')\n                    data__readme_one_of_count8 += 1\n                except JsonSchemaValueException: pass\n            if data__readme_one_of_count8 != 1:\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".readme must be valid exactly by one definition\" + (\" (\" + str(data__readme_one_of_count8) + \" matches found)\"), value=data__readme, name=\"\" + (name_prefix or \"data\") + \".readme\", definition={'$$description': ['`Full/detailed description of the project in the form of a README', '<https://www.python.org/dev/peps/pep-0621/#readme>`_', \"with meaning similar to the one defined in `core metadata's Description\", '<https://packaging.python.org/specifications/core-metadata/#description>`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, rule='oneOf')\n        if \"requires-python\" in data_keys:\n            data_keys.remove(\"requires-python\")\n            data__requirespython = data[\"requires-python\"]\n            if not isinstance(data__requirespython, (str)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".requires-python must be string\", value=data__requirespython, name=\"\" + (name_prefix or \"data\") + \".requires-python\", definition={'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '<https://packaging.python.org/specifications/core-metadata/#requires-python>`_.']}, rule='type')\n            if isinstance(data__requirespython, str):\n                if not custom_formats[\"pep508-versionspec\"](data__requirespython):\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".requires-python must be pep508-versionspec\", value=data__requirespython, name=\"\" + (name_prefix or \"data\") + \".requires-python\", definition={'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '<https://packaging.python.org/specifications/core-metadata/#requires-python>`_.']}, rule='format')\n        if \"license\" in data_keys:\n            data_keys.remove(\"license\")\n            data__license = data[\"license\"]\n            data__license_one_of_count10 = 0\n            if data__license_one_of_count10 < 2:\n                try:\n                    data__license_is_dict = isinstance(data__license, dict)\n                    if data__license_is_dict:\n                        data__license_len = len(data__license)\n                        if not all(prop in data__license for prop in ['file']):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".license must contain ['file'] properties\", value=data__license, name=\"\" + (name_prefix or \"data\") + \".license\", definition={'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, rule='required')\n                        data__license_keys = set(data__license.keys())\n                        if \"file\" in data__license_keys:\n                            data__license_keys.remove(\"file\")\n                            data__license__file = data__license[\"file\"]\n                            if not isinstance(data__license__file, (str)):\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".license.file must be string\", value=data__license__file, name=\"\" + (name_prefix or \"data\") + \".license.file\", definition={'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}, rule='type')\n                    data__license_one_of_count10 += 1\n                except JsonSchemaValueException: pass\n            if data__license_one_of_count10 < 2:\n                try:\n                    data__license_is_dict = isinstance(data__license, dict)\n                    if data__license_is_dict:\n                        data__license_len = len(data__license)\n                        if not all(prop in data__license for prop in ['text']):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".license must contain ['text'] properties\", value=data__license, name=\"\" + (name_prefix or \"data\") + \".license\", definition={'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '<https://packaging.python.org/specifications/core-metadata/#license>`_.']}}, 'required': ['text']}, rule='required')\n                        data__license_keys = set(data__license.keys())\n                        if \"text\" in data__license_keys:\n                            data__license_keys.remove(\"text\")\n                            data__license__text = data__license[\"text\"]\n                            if not isinstance(data__license__text, (str)):\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".license.text must be string\", value=data__license__text, name=\"\" + (name_prefix or \"data\") + \".license.text\", definition={'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '<https://packaging.python.org/specifications/core-metadata/#license>`_.']}, rule='type')\n                    data__license_one_of_count10 += 1\n                except JsonSchemaValueException: pass\n            if data__license_one_of_count10 != 1:\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".license must be valid exactly by one definition\" + (\" (\" + str(data__license_one_of_count10) + \" matches found)\"), value=data__license, name=\"\" + (name_prefix or \"data\") + \".license\", definition={'description': '`Project license <https://www.python.org/dev/peps/pep-0621/#license>`_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '<https://packaging.python.org/specifications/core-metadata/#license>`_.']}}, 'required': ['text']}]}, rule='oneOf')\n        if \"authors\" in data_keys:\n            data_keys.remove(\"authors\")\n            data__authors = data[\"authors\"]\n            if not isinstance(data__authors, (list, tuple)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".authors must be array\", value=data__authors, name=\"\" + (name_prefix or \"data\") + \".authors\", definition={'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': [\"The people or organizations considered to be the 'authors' of the project.\", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, rule='type')\n            data__authors_is_list = isinstance(data__authors, (list, tuple))\n            if data__authors_is_list:\n                data__authors_len = len(data__authors)\n                for data__authors_x, data__authors_item in enumerate(data__authors):\n                    validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_author(data__authors_item, custom_formats, (name_prefix or \"data\") + \".authors[{data__authors_x}]\")\n        if \"maintainers\" in data_keys:\n            data_keys.remove(\"maintainers\")\n            data__maintainers = data[\"maintainers\"]\n            if not isinstance(data__maintainers, (list, tuple)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".maintainers must be array\", value=data__maintainers, name=\"\" + (name_prefix or \"data\") + \".maintainers\", definition={'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': [\"The people or organizations considered to be the 'maintainers' of the project.\", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, rule='type')\n            data__maintainers_is_list = isinstance(data__maintainers, (list, tuple))\n            if data__maintainers_is_list:\n                data__maintainers_len = len(data__maintainers)\n                for data__maintainers_x, data__maintainers_item in enumerate(data__maintainers):\n                    validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_author(data__maintainers_item, custom_formats, (name_prefix or \"data\") + \".maintainers[{data__maintainers_x}]\")\n        if \"keywords\" in data_keys:\n            data_keys.remove(\"keywords\")\n            data__keywords = data[\"keywords\"]\n            if not isinstance(data__keywords, (list, tuple)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".keywords must be array\", value=data__keywords, name=\"\" + (name_prefix or \"data\") + \".keywords\", definition={'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, rule='type')\n            data__keywords_is_list = isinstance(data__keywords, (list, tuple))\n            if data__keywords_is_list:\n                data__keywords_len = len(data__keywords)\n                for data__keywords_x, data__keywords_item in enumerate(data__keywords):\n                    if not isinstance(data__keywords_item, (str)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".keywords[{data__keywords_x}]\".format(**locals()) + \" must be string\", value=data__keywords_item, name=\"\" + (name_prefix or \"data\") + \".keywords[{data__keywords_x}]\".format(**locals()) + \"\", definition={'type': 'string'}, rule='type')\n        if \"classifiers\" in data_keys:\n            data_keys.remove(\"classifiers\")\n            data__classifiers = data[\"classifiers\"]\n            if not isinstance(data__classifiers, (list, tuple)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".classifiers must be array\", value=data__classifiers, name=\"\" + (name_prefix or \"data\") + \".classifiers\", definition={'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier <https://pypi.org/classifiers/>`_.'}, '$$description': ['`Trove classifiers <https://pypi.org/classifiers/>`_', 'which apply to the project.']}, rule='type')\n            data__classifiers_is_list = isinstance(data__classifiers, (list, tuple))\n            if data__classifiers_is_list:\n                data__classifiers_len = len(data__classifiers)\n                for data__classifiers_x, data__classifiers_item in enumerate(data__classifiers):\n                    if not isinstance(data__classifiers_item, (str)):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".classifiers[{data__classifiers_x}]\".format(**locals()) + \" must be string\", value=data__classifiers_item, name=\"\" + (name_prefix or \"data\") + \".classifiers[{data__classifiers_x}]\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier <https://pypi.org/classifiers/>`_.'}, rule='type')\n                    if isinstance(data__classifiers_item, str):\n                        if not custom_formats[\"trove-classifier\"](data__classifiers_item):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".classifiers[{data__classifiers_x}]\".format(**locals()) + \" must be trove-classifier\", value=data__classifiers_item, name=\"\" + (name_prefix or \"data\") + \".classifiers[{data__classifiers_x}]\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier <https://pypi.org/classifiers/>`_.'}, rule='format')\n        if \"urls\" in data_keys:\n            data_keys.remove(\"urls\")\n            data__urls = data[\"urls\"]\n            if not isinstance(data__urls, (dict)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".urls must be object\", value=data__urls, name=\"\" + (name_prefix or \"data\") + \".urls\", definition={'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, rule='type')\n            data__urls_is_dict = isinstance(data__urls, dict)\n            if data__urls_is_dict:\n                data__urls_keys = set(data__urls.keys())\n                for data__urls_key, data__urls_val in data__urls.items():\n                    if REGEX_PATTERNS['^.+$'].search(data__urls_key):\n                        if data__urls_key in data__urls_keys:\n                            data__urls_keys.remove(data__urls_key)\n                        if not isinstance(data__urls_val, (str)):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".urls.{data__urls_key}\".format(**locals()) + \" must be string\", value=data__urls_val, name=\"\" + (name_prefix or \"data\") + \".urls.{data__urls_key}\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'url'}, rule='type')\n                        if isinstance(data__urls_val, str):\n                            if not custom_formats[\"url\"](data__urls_val):\n                                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".urls.{data__urls_key}\".format(**locals()) + \" must be url\", value=data__urls_val, name=\"\" + (name_prefix or \"data\") + \".urls.{data__urls_key}\".format(**locals()) + \"\", definition={'type': 'string', 'format': 'url'}, rule='format')\n                if data__urls_keys:\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".urls must not contain \"+str(data__urls_keys)+\" properties\", value=data__urls, name=\"\" + (name_prefix or \"data\") + \".urls\", definition={'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, rule='additionalProperties')\n        if \"scripts\" in data_keys:\n            data_keys.remove(\"scripts\")\n            data__scripts = data[\"scripts\"]\n            validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_entry_point_group(data__scripts, custom_formats, (name_prefix or \"data\") + \".scripts\")\n        if \"gui-scripts\" in data_keys:\n            data_keys.remove(\"gui-scripts\")\n            data__guiscripts = data[\"gui-scripts\"]\n            validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_entry_point_group(data__guiscripts, custom_formats, (name_prefix or \"data\") + \".gui-scripts\")\n        if \"entry-points\" in data_keys:\n            data_keys.remove(\"entry-points\")\n            data__entrypoints = data[\"entry-points\"]\n            data__entrypoints_is_dict = isinstance(data__entrypoints, dict)\n            if data__entrypoints_is_dict:\n                data__entrypoints_keys = set(data__entrypoints.keys())\n                for data__entrypoints_key, data__entrypoints_val in data__entrypoints.items():\n                    if REGEX_PATTERNS['^.+$'].search(data__entrypoints_key):\n                        if data__entrypoints_key in data__entrypoints_keys:\n                            data__entrypoints_keys.remove(data__entrypoints_key)\n                        validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_entry_point_group(data__entrypoints_val, custom_formats, (name_prefix or \"data\") + \".entry-points.{data__entrypoints_key}\")\n                if data__entrypoints_keys:\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".entry-points must not contain \"+str(data__entrypoints_keys)+\" properties\", value=data__entrypoints, name=\"\" + (name_prefix or \"data\") + \".entry-points\", definition={'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '<https://packaging.python.org/specifications/entry-points/>`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, rule='additionalProperties')\n                data__entrypoints_len = len(data__entrypoints)\n                if data__entrypoints_len != 0:\n                    data__entrypoints_property_names = True\n                    for data__entrypoints_key in data__entrypoints:\n                        try:\n                            if isinstance(data__entrypoints_key, str):\n                                if not custom_formats[\"python-entrypoint-group\"](data__entrypoints_key):\n                                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".entry-points must be python-entrypoint-group\", value=data__entrypoints_key, name=\"\" + (name_prefix or \"data\") + \".entry-points\", definition={'format': 'python-entrypoint-group'}, rule='format')\n                        except JsonSchemaValueException:\n                            data__entrypoints_property_names = False\n                    if not data__entrypoints_property_names:\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".entry-points must be named by propertyName definition\", value=data__entrypoints, name=\"\" + (name_prefix or \"data\") + \".entry-points\", definition={'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '<https://packaging.python.org/specifications/entry-points/>`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, rule='propertyNames')\n        if \"dependencies\" in data_keys:\n            data_keys.remove(\"dependencies\")\n            data__dependencies = data[\"dependencies\"]\n            if not isinstance(data__dependencies, (list, tuple)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dependencies must be array\", value=data__dependencies, name=\"\" + (name_prefix or \"data\") + \".dependencies\", definition={'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, rule='type')\n            data__dependencies_is_list = isinstance(data__dependencies, (list, tuple))\n            if data__dependencies_is_list:\n                data__dependencies_len = len(data__dependencies)\n                for data__dependencies_x, data__dependencies_item in enumerate(data__dependencies):\n                    validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_dependency(data__dependencies_item, custom_formats, (name_prefix or \"data\") + \".dependencies[{data__dependencies_x}]\")\n        if \"optional-dependencies\" in data_keys:\n            data_keys.remove(\"optional-dependencies\")\n            data__optionaldependencies = data[\"optional-dependencies\"]\n            if not isinstance(data__optionaldependencies, (dict)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".optional-dependencies must be object\", value=data__optionaldependencies, name=\"\" + (name_prefix or \"data\") + \".optional-dependencies\", definition={'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='type')\n            data__optionaldependencies_is_dict = isinstance(data__optionaldependencies, dict)\n            if data__optionaldependencies_is_dict:\n                data__optionaldependencies_keys = set(data__optionaldependencies.keys())\n                for data__optionaldependencies_key, data__optionaldependencies_val in data__optionaldependencies.items():\n                    if REGEX_PATTERNS['^.+$'].search(data__optionaldependencies_key):\n                        if data__optionaldependencies_key in data__optionaldependencies_keys:\n                            data__optionaldependencies_keys.remove(data__optionaldependencies_key)\n                        if not isinstance(data__optionaldependencies_val, (list, tuple)):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".optional-dependencies.{data__optionaldependencies_key}\".format(**locals()) + \" must be array\", value=data__optionaldependencies_val, name=\"\" + (name_prefix or \"data\") + \".optional-dependencies.{data__optionaldependencies_key}\".format(**locals()) + \"\", definition={'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, rule='type')\n                        data__optionaldependencies_val_is_list = isinstance(data__optionaldependencies_val, (list, tuple))\n                        if data__optionaldependencies_val_is_list:\n                            data__optionaldependencies_val_len = len(data__optionaldependencies_val)\n                            for data__optionaldependencies_val_x, data__optionaldependencies_val_item in enumerate(data__optionaldependencies_val):\n                                validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_dependency(data__optionaldependencies_val_item, custom_formats, (name_prefix or \"data\") + \".optional-dependencies.{data__optionaldependencies_key}[{data__optionaldependencies_val_x}]\")\n                if data__optionaldependencies_keys:\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".optional-dependencies must not contain \"+str(data__optionaldependencies_keys)+\" properties\", value=data__optionaldependencies, name=\"\" + (name_prefix or \"data\") + \".optional-dependencies\", definition={'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='additionalProperties')\n                data__optionaldependencies_len = len(data__optionaldependencies)\n                if data__optionaldependencies_len != 0:\n                    data__optionaldependencies_property_names = True\n                    for data__optionaldependencies_key in data__optionaldependencies:\n                        try:\n                            if isinstance(data__optionaldependencies_key, str):\n                                if not custom_formats[\"pep508-identifier\"](data__optionaldependencies_key):\n                                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".optional-dependencies must be pep508-identifier\", value=data__optionaldependencies_key, name=\"\" + (name_prefix or \"data\") + \".optional-dependencies\", definition={'format': 'pep508-identifier'}, rule='format')\n                        except JsonSchemaValueException:\n                            data__optionaldependencies_property_names = False\n                    if not data__optionaldependencies_property_names:\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".optional-dependencies must be named by propertyName definition\", value=data__optionaldependencies, name=\"\" + (name_prefix or \"data\") + \".optional-dependencies\", definition={'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, rule='propertyNames')\n        if \"dynamic\" in data_keys:\n            data_keys.remove(\"dynamic\")\n            data__dynamic = data[\"dynamic\"]\n            if not isinstance(data__dynamic, (list, tuple)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dynamic must be array\", value=data__dynamic, name=\"\" + (name_prefix or \"data\") + \".dynamic\", definition={'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}, rule='type')\n            data__dynamic_is_list = isinstance(data__dynamic, (list, tuple))\n            if data__dynamic_is_list:\n                data__dynamic_len = len(data__dynamic)\n                for data__dynamic_x, data__dynamic_item in enumerate(data__dynamic):\n                    if data__dynamic_item not in ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']:\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dynamic[{data__dynamic_x}]\".format(**locals()) + \" must be one of ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']\", value=data__dynamic_item, name=\"\" + (name_prefix or \"data\") + \".dynamic[{data__dynamic_x}]\".format(**locals()) + \"\", definition={'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}, rule='enum')\n        if data_keys:\n            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must not contain \"+str(data_keys)+\" properties\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$schema': 'http://json-schema.org/draft-07/schema', '$id': 'https://packaging.python.org/en/latest/specifications/declaring-project-metadata/', 'title': 'Package metadata stored in the ``project`` table', '$$description': ['Data structure for the **project** table inside ``pyproject.toml``', '(as initially defined in :pep:`621`)'], 'type': 'object', 'properties': {'name': {'type': 'string', 'description': 'The name (primary identifier) of the project. MUST be statically defined.', 'format': 'pep508-identifier'}, 'version': {'type': 'string', 'description': 'The version of the project as supported by :pep:`440`.', 'format': 'pep440'}, 'description': {'type': 'string', '$$description': ['The `summary description of the project', '<https://packaging.python.org/specifications/core-metadata/#summary>`_']}, 'readme': {'$$description': ['`Full/detailed description of the project in the form of a README', '<https://www.python.org/dev/peps/pep-0621/#readme>`_', \"with meaning similar to the one defined in `core metadata's Description\", '<https://packaging.python.org/specifications/core-metadata/#description>`_'], 'oneOf': [{'type': 'string', '$$description': ['Relative path to a text file (UTF-8) containing the full description', 'of the project. If the file path ends in case-insensitive ``.md`` or', '``.rst`` suffixes, then the content-type is respectively', '``text/markdown`` or ``text/x-rst``']}, {'type': 'object', 'allOf': [{'anyOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to a text file containing the full description', 'of the project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', 'description': 'Full text describing the project.'}}, 'required': ['text']}]}, {'properties': {'content-type': {'type': 'string', '$$description': ['Content-type (:rfc:`1341`) of the full description', '(e.g. ``text/markdown``). The ``charset`` parameter is assumed', 'UTF-8 when not present.'], '$comment': 'TODO: add regex pattern or format?'}}, 'required': ['content-type']}]}]}, 'requires-python': {'type': 'string', 'format': 'pep508-versionspec', '$$description': ['`The Python version requirements of the project', '<https://packaging.python.org/specifications/core-metadata/#requires-python>`_.']}, 'license': {'description': '`Project license <https://www.python.org/dev/peps/pep-0621/#license>`_.', 'oneOf': [{'properties': {'file': {'type': 'string', '$$description': ['Relative path to the file (UTF-8) which contains the license for the', 'project.']}}, 'required': ['file']}, {'properties': {'text': {'type': 'string', '$$description': ['The license of the project whose meaning is that of the', '`License field from the core metadata', '<https://packaging.python.org/specifications/core-metadata/#license>`_.']}}, 'required': ['text']}]}, 'authors': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': [\"The people or organizations considered to be the 'authors' of the project.\", 'The exact meaning is open to interpretation (e.g. original or primary authors,', 'current maintainers, or owners of the package).']}, 'maintainers': {'type': 'array', 'items': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, '$$description': [\"The people or organizations considered to be the 'maintainers' of the project.\", 'Similarly to ``authors``, the exact meaning is open to interpretation.']}, 'keywords': {'type': 'array', 'items': {'type': 'string'}, 'description': 'List of keywords to assist searching for the distribution in a larger catalog.'}, 'classifiers': {'type': 'array', 'items': {'type': 'string', 'format': 'trove-classifier', 'description': '`PyPI classifier <https://pypi.org/classifiers/>`_.'}, '$$description': ['`Trove classifiers <https://pypi.org/classifiers/>`_', 'which apply to the project.']}, 'urls': {'type': 'object', 'description': 'URLs associated with the project in the form ``label => value``.', 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', 'format': 'url'}}}, 'scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'gui-scripts': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'entry-points': {'$$description': ['Instruct the installer to expose the given modules/functions via', '``entry-point`` discovery mechanism (useful for plugins).', 'More information available in the `Python packaging guide', '<https://packaging.python.org/specifications/entry-points/>`_.'], 'propertyNames': {'format': 'python-entrypoint-group'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}}}, 'dependencies': {'type': 'array', 'description': 'Project (mandatory) dependencies.', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}, 'optional-dependencies': {'type': 'object', 'description': 'Optional dependency for the project', 'propertyNames': {'format': 'pep508-identifier'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'array', 'items': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}}, 'dynamic': {'type': 'array', '$$description': ['Specifies which fields are intentionally unspecified and expected to be', 'dynamically provided by build tools'], 'items': {'enum': ['version', 'description', 'readme', 'requires-python', 'license', 'authors', 'maintainers', 'keywords', 'classifiers', 'urls', 'scripts', 'gui-scripts', 'entry-points', 'dependencies', 'optional-dependencies']}}}, 'required': ['name'], 'additionalProperties': False, 'if': {'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as \"Required\", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, 'then': {'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, 'definitions': {'author': {'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, 'entry-point-group': {'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, 'dependency': {'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}}}, rule='additionalProperties')\n    try:\n        try:\n            data_is_dict = isinstance(data, dict)\n            if data_is_dict:\n                data_len = len(data)\n                if not all(prop in data for prop in ['dynamic']):\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must contain ['dynamic'] properties\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, rule='required')\n                data_keys = set(data.keys())\n                if \"dynamic\" in data_keys:\n                    data_keys.remove(\"dynamic\")\n                    data__dynamic = data[\"dynamic\"]\n                    data__dynamic_is_list = isinstance(data__dynamic, (list, tuple))\n                    if data__dynamic_is_list:\n                        data__dynamic_contains = False\n                        for data__dynamic_key in data__dynamic:\n                            try:\n                                if data__dynamic_key != \"version\":\n                                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dynamic must be same as const definition: version\", value=data__dynamic_key, name=\"\" + (name_prefix or \"data\") + \".dynamic\", definition={'const': 'version'}, rule='const')\n                                data__dynamic_contains = True\n                                break\n                            except JsonSchemaValueException: pass\n                        if not data__dynamic_contains:\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".dynamic must contain one of contains definition\", value=data__dynamic, name=\"\" + (name_prefix or \"data\") + \".dynamic\", definition={'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}, rule='contains')\n        except JsonSchemaValueException: pass\n        else:\n            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must NOT match a disallowed definition\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'not': {'required': ['dynamic'], 'properties': {'dynamic': {'contains': {'const': 'version'}, '$$description': ['version is listed in ``dynamic``']}}}, '$$comment': ['According to :pep:`621`:', '    If the core metadata specification lists a field as \"Required\", then', '    the metadata MUST specify the field statically or list it in dynamic', 'In turn, `core metadata`_ defines:', '    The required fields are: Metadata-Version, Name, Version.', '    All the other fields are optional.', 'Since ``Metadata-Version`` is defined by the build back-end, ``name`` and', '``version`` are the only mandatory information in ``pyproject.toml``.', '.. _core metadata: https://packaging.python.org/specifications/core-metadata/']}, rule='not')\n    except JsonSchemaValueException:\n        pass\n    else:\n        data_is_dict = isinstance(data, dict)\n        if data_is_dict:\n            data_len = len(data)\n            if not all(prop in data for prop in ['version']):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must contain ['version'] properties\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'required': ['version'], '$$description': ['version should be statically defined in the ``version`` field']}, rule='required')\n    return data\n\ndef validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_dependency(data, custom_formats={}, name_prefix=None):\n    if not isinstance(data, (str)):\n        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must be string\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}, rule='type')\n    if isinstance(data, str):\n        if not custom_formats[\"pep508\"](data):\n            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must be pep508\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$id': '#/definitions/dependency', 'title': 'Dependency', 'type': 'string', 'description': 'Project dependency specification according to PEP 508', 'format': 'pep508'}, rule='format')\n    return data\n\ndef validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_entry_point_group(data, custom_formats={}, name_prefix=None):\n    if not isinstance(data, (dict)):\n        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must be object\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, rule='type')\n    data_is_dict = isinstance(data, dict)\n    if data_is_dict:\n        data_keys = set(data.keys())\n        for data_key, data_val in data.items():\n            if REGEX_PATTERNS['^.+$'].search(data_key):\n                if data_key in data_keys:\n                    data_keys.remove(data_key)\n                if not isinstance(data_val, (str)):\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".{data_key}\".format(**locals()) + \" must be string\", value=data_val, name=\"\" + (name_prefix or \"data\") + \".{data_key}\".format(**locals()) + \"\", definition={'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}, rule='type')\n                if isinstance(data_val, str):\n                    if not custom_formats[\"python-entrypoint-reference\"](data_val):\n                        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".{data_key}\".format(**locals()) + \" must be python-entrypoint-reference\", value=data_val, name=\"\" + (name_prefix or \"data\") + \".{data_key}\".format(**locals()) + \"\", definition={'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}, rule='format')\n        if data_keys:\n            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must not contain \"+str(data_keys)+\" properties\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, rule='additionalProperties')\n        data_len = len(data)\n        if data_len != 0:\n            data_property_names = True\n            for data_key in data:\n                try:\n                    if isinstance(data_key, str):\n                        if not custom_formats[\"python-entrypoint-name\"](data_key):\n                            raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must be python-entrypoint-name\", value=data_key, name=\"\" + (name_prefix or \"data\") + \"\", definition={'format': 'python-entrypoint-name'}, rule='format')\n                except JsonSchemaValueException:\n                    data_property_names = False\n            if not data_property_names:\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must be named by propertyName definition\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$id': '#/definitions/entry-point-group', 'title': 'Entry-points', 'type': 'object', '$$description': ['Entry-points are grouped together to indicate what sort of capabilities they', 'provide.', 'See the `packaging guides', '<https://packaging.python.org/specifications/entry-points/>`_', 'and `setuptools docs', '<https://setuptools.pypa.io/en/latest/userguide/entry_point.html>`_', 'for more information.'], 'propertyNames': {'format': 'python-entrypoint-name'}, 'additionalProperties': False, 'patternProperties': {'^.+$': {'type': 'string', '$$description': ['Reference to a Python object. It is either in the form', '``importable.module``, or ``importable.module:object.attr``.'], 'format': 'python-entrypoint-reference', '$comment': 'https://packaging.python.org/specifications/entry-points/'}}}, rule='propertyNames')\n    return data\n\ndef validate_https___packaging_python_org_en_latest_specifications_declaring_project_metadata___definitions_author(data, custom_formats={}, name_prefix=None):\n    if not isinstance(data, (dict)):\n        raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \" must be object\", value=data, name=\"\" + (name_prefix or \"data\") + \"\", definition={'$id': '#/definitions/author', 'title': 'Author or Maintainer', '$comment': 'https://www.python.org/dev/peps/pep-0621/#authors-maintainers', 'type': 'object', 'properties': {'name': {'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, 'email': {'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}}}, rule='type')\n    data_is_dict = isinstance(data, dict)\n    if data_is_dict:\n        data_keys = set(data.keys())\n        if \"name\" in data_keys:\n            data_keys.remove(\"name\")\n            data__name = data[\"name\"]\n            if not isinstance(data__name, (str)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".name must be string\", value=data__name, name=\"\" + (name_prefix or \"data\") + \".name\", definition={'type': 'string', '$$description': ['MUST be a valid email name, i.e. whatever can be put as a name, before an', 'email, in :rfc:`822`.']}, rule='type')\n        if \"email\" in data_keys:\n            data_keys.remove(\"email\")\n            data__email = data[\"email\"]\n            if not isinstance(data__email, (str)):\n                raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".email must be string\", value=data__email, name=\"\" + (name_prefix or \"data\") + \".email\", definition={'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}, rule='type')\n            if isinstance(data__email, str):\n                if not REGEX_PATTERNS[\"idn-email_re_pattern\"].match(data__email):\n                    raise JsonSchemaValueException(\"\" + (name_prefix or \"data\") + \".email must be idn-email\", value=data__email, name=\"\" + (name_prefix or \"data\") + \".email\", definition={'type': 'string', 'format': 'idn-email', 'description': 'MUST be a valid email address'}, rule='format')\n    return data"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/config/_validate_pyproject/formats.py",
    "content": "import logging\nimport os\nimport re\nimport string\nimport typing\nfrom itertools import chain as _chain\n\n_logger = logging.getLogger(__name__)\n\n# -------------------------------------------------------------------------------------\n# PEP 440\n\nVERSION_PATTERN = r\"\"\"\n    v?\n    (?:\n        (?:(?P<epoch>[0-9]+)!)?                           # epoch\n        (?P<release>[0-9]+(?:\\.[0-9]+)*)                  # release segment\n        (?P<pre>                                          # pre-release\n            [-_\\.]?\n            (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))\n            [-_\\.]?\n            (?P<pre_n>[0-9]+)?\n        )?\n        (?P<post>                                         # post release\n            (?:-(?P<post_n1>[0-9]+))\n            |\n            (?:\n                [-_\\.]?\n                (?P<post_l>post|rev|r)\n                [-_\\.]?\n                (?P<post_n2>[0-9]+)?\n            )\n        )?\n        (?P<dev>                                          # dev release\n            [-_\\.]?\n            (?P<dev_l>dev)\n            [-_\\.]?\n            (?P<dev_n>[0-9]+)?\n        )?\n    )\n    (?:\\+(?P<local>[a-z0-9]+(?:[-_\\.][a-z0-9]+)*))?       # local version\n\"\"\"\n\nVERSION_REGEX = re.compile(r\"^\\s*\" + VERSION_PATTERN + r\"\\s*$\", re.X | re.I)\n\n\ndef pep440(version: str) -> bool:\n    return VERSION_REGEX.match(version) is not None\n\n\n# -------------------------------------------------------------------------------------\n# PEP 508\n\nPEP508_IDENTIFIER_PATTERN = r\"([A-Z0-9]|[A-Z0-9][A-Z0-9._-]*[A-Z0-9])\"\nPEP508_IDENTIFIER_REGEX = re.compile(f\"^{PEP508_IDENTIFIER_PATTERN}$\", re.I)\n\n\ndef pep508_identifier(name: str) -> bool:\n    return PEP508_IDENTIFIER_REGEX.match(name) is not None\n\n\ntry:\n    try:\n        from packaging import requirements as _req\n    except ImportError:  # pragma: no cover\n        # let's try setuptools vendored version\n        from setuptools._vendor.packaging import requirements as _req  # type: ignore\n\n    def pep508(value: str) -> bool:\n        try:\n            _req.Requirement(value)\n            return True\n        except _req.InvalidRequirement:\n            return False\n\nexcept ImportError:  # pragma: no cover\n    _logger.warning(\n        \"Could not find an installation of `packaging`. Requirements, dependencies and \"\n        \"versions might not be validated. \"\n        \"To enforce validation, please install `packaging`.\"\n    )\n\n    def pep508(value: str) -> bool:\n        return True\n\n\ndef pep508_versionspec(value: str) -> bool:\n    \"\"\"Expression that can be used to specify/lock versions (including ranges)\"\"\"\n    if any(c in value for c in (\";\", \"]\", \"@\")):\n        # In PEP 508:\n        # conditional markers, extras and URL specs are not included in the\n        # versionspec\n        return False\n    # Let's pretend we have a dependency called `requirement` with the given\n    # version spec, then we can re-use the pep508 function for validation:\n    return pep508(f\"requirement{value}\")\n\n\n# -------------------------------------------------------------------------------------\n# PEP 517\n\n\ndef pep517_backend_reference(value: str) -> bool:\n    module, _, obj = value.partition(\":\")\n    identifiers = (i.strip() for i in _chain(module.split(\".\"), obj.split(\".\")))\n    return all(python_identifier(i) for i in identifiers if i)\n\n\n# -------------------------------------------------------------------------------------\n# Classifiers - PEP 301\n\n\ndef _download_classifiers() -> str:\n    import ssl\n    from email.message import Message\n    from urllib.request import urlopen\n\n    url = \"https://pypi.org/pypi?:action=list_classifiers\"\n    context = ssl.create_default_context()\n    with urlopen(url, context=context) as response:\n        headers = Message()\n        headers[\"content_type\"] = response.getheader(\"content-type\", \"text/plain\")\n        return response.read().decode(headers.get_param(\"charset\", \"utf-8\"))\n\n\nclass _TroveClassifier:\n    \"\"\"The ``trove_classifiers`` package is the official way of validating classifiers,\n    however this package might not be always available.\n    As a workaround we can still download a list from PyPI.\n    We also don't want to be over strict about it, so simply skipping silently is an\n    option (classifiers will be validated anyway during the upload to PyPI).\n    \"\"\"\n\n    def __init__(self):\n        self.downloaded: typing.Union[None, False, typing.Set[str]] = None\n        self._skip_download = False\n        # None => not cached yet\n        # False => cache not available\n        self.__name__ = \"trove_classifier\"  # Emulate a public function\n\n    def _disable_download(self):\n        # This is a private API. Only setuptools has the consent of using it.\n        self._skip_download = True\n\n    def __call__(self, value: str) -> bool:\n        if self.downloaded is False or self._skip_download is True:\n            return True\n\n        if os.getenv(\"NO_NETWORK\") or os.getenv(\"VALIDATE_PYPROJECT_NO_NETWORK\"):\n            self.downloaded = False\n            msg = (\n                \"Install ``trove-classifiers`` to ensure proper validation. \"\n                \"Skipping download of classifiers list from PyPI (NO_NETWORK).\"\n            )\n            _logger.debug(msg)\n            return True\n\n        if self.downloaded is None:\n            msg = (\n                \"Install ``trove-classifiers`` to ensure proper validation. \"\n                \"Meanwhile a list of classifiers will be downloaded from PyPI.\"\n            )\n            _logger.debug(msg)\n            try:\n                self.downloaded = set(_download_classifiers().splitlines())\n            except Exception:\n                self.downloaded = False\n                _logger.debug(\"Problem with download, skipping validation\")\n                return True\n\n        return value in self.downloaded or value.lower().startswith(\"private ::\")\n\n\ntry:\n    from trove_classifiers import classifiers as _trove_classifiers\n\n    def trove_classifier(value: str) -> bool:\n        return value in _trove_classifiers or value.lower().startswith(\"private ::\")\n\nexcept ImportError:  # pragma: no cover\n    trove_classifier = _TroveClassifier()\n\n\n# -------------------------------------------------------------------------------------\n# Non-PEP related\n\n\ndef url(value: str) -> bool:\n    from urllib.parse import urlparse\n\n    try:\n        parts = urlparse(value)\n        if not parts.scheme:\n            _logger.warning(\n                \"For maximum compatibility please make sure to include a \"\n                \"`scheme` prefix in your URL (e.g. 'http://'). \"\n                f\"Given value: {value}\"\n            )\n            if not (value.startswith(\"/\") or value.startswith(\"\\\\\") or \"@\" in value):\n                parts = urlparse(f\"http://{value}\")\n\n        return bool(parts.scheme and parts.netloc)\n    except Exception:\n        return False\n\n\n# https://packaging.python.org/specifications/entry-points/\nENTRYPOINT_PATTERN = r\"[^\\[\\s=]([^=]*[^\\s=])?\"\nENTRYPOINT_REGEX = re.compile(f\"^{ENTRYPOINT_PATTERN}$\", re.I)\nRECOMMEDED_ENTRYPOINT_PATTERN = r\"[\\w.-]+\"\nRECOMMEDED_ENTRYPOINT_REGEX = re.compile(f\"^{RECOMMEDED_ENTRYPOINT_PATTERN}$\", re.I)\nENTRYPOINT_GROUP_PATTERN = r\"\\w+(\\.\\w+)*\"\nENTRYPOINT_GROUP_REGEX = re.compile(f\"^{ENTRYPOINT_GROUP_PATTERN}$\", re.I)\n\n\ndef python_identifier(value: str) -> bool:\n    return value.isidentifier()\n\n\ndef python_qualified_identifier(value: str) -> bool:\n    if value.startswith(\".\") or value.endswith(\".\"):\n        return False\n    return all(python_identifier(m) for m in value.split(\".\"))\n\n\ndef python_module_name(value: str) -> bool:\n    return python_qualified_identifier(value)\n\n\ndef python_entrypoint_group(value: str) -> bool:\n    return ENTRYPOINT_GROUP_REGEX.match(value) is not None\n\n\ndef python_entrypoint_name(value: str) -> bool:\n    if not ENTRYPOINT_REGEX.match(value):\n        return False\n    if not RECOMMEDED_ENTRYPOINT_REGEX.match(value):\n        msg = f\"Entry point `{value}` does not follow recommended pattern: \"\n        msg += RECOMMEDED_ENTRYPOINT_PATTERN\n        _logger.warning(msg)\n    return True\n\n\ndef python_entrypoint_reference(value: str) -> bool:\n    module, _, rest = value.partition(\":\")\n    if \"[\" in rest:\n        obj, _, extras_ = rest.partition(\"[\")\n        if extras_.strip()[-1] != \"]\":\n            return False\n        extras = (x.strip() for x in extras_.strip(string.whitespace + \"[]\").split(\",\"))\n        if not all(pep508_identifier(e) for e in extras):\n            return False\n        _logger.warning(f\"`{value}` - using extras for entry points is not recommended\")\n    else:\n        obj = rest\n\n    module_parts = module.split(\".\")\n    identifiers = _chain(module_parts, obj.split(\".\")) if rest else module_parts\n    return all(python_identifier(i.strip()) for i in identifiers)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/config/expand.py",
    "content": "\"\"\"Utility functions to expand configuration directives or special values\n(such glob patterns).\n\nWe can split the process of interpreting configuration files into 2 steps:\n\n1. The parsing the file contents from strings to value objects\n   that can be understand by Python (for example a string with a comma\n   separated list of keywords into an actual Python list of strings).\n\n2. The expansion (or post-processing) of these values according to the\n   semantics ``setuptools`` assign to them (for example a configuration field\n   with the ``file:`` directive should be expanded from a list of file paths to\n   a single string with the contents of those files concatenated)\n\nThis module focus on the second step, and therefore allow sharing the expansion\nfunctions among several configuration file formats.\n\n**PRIVATE MODULE**: API reserved for setuptools internal usage only.\n\"\"\"\nimport ast\nimport importlib\nimport io\nimport os\nimport pathlib\nimport sys\nimport warnings\nfrom glob import iglob\nfrom configparser import ConfigParser\nfrom importlib.machinery import ModuleSpec\nfrom itertools import chain\nfrom typing import (\n    TYPE_CHECKING,\n    Callable,\n    Dict,\n    Iterable,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n    Tuple,\n    TypeVar,\n    Union,\n    cast\n)\nfrom pathlib import Path\nfrom types import ModuleType\n\nfrom distutils.errors import DistutilsOptionError\n\nfrom .._path import same_path as _same_path\n\nif TYPE_CHECKING:\n    from setuptools.dist import Distribution  # noqa\n    from setuptools.discovery import ConfigDiscovery  # noqa\n    from distutils.dist import DistributionMetadata  # noqa\n\nchain_iter = chain.from_iterable\n_Path = Union[str, os.PathLike]\n_K = TypeVar(\"_K\")\n_V = TypeVar(\"_V\", covariant=True)\n\n\nclass StaticModule:\n    \"\"\"Proxy to a module object that avoids executing arbitrary code.\"\"\"\n\n    def __init__(self, name: str, spec: ModuleSpec):\n        module = ast.parse(pathlib.Path(spec.origin).read_bytes())\n        vars(self).update(locals())\n        del self.self\n\n    def _find_assignments(self) -> Iterator[Tuple[ast.AST, ast.AST]]:\n        for statement in self.module.body:\n            if isinstance(statement, ast.Assign):\n                yield from ((target, statement.value) for target in statement.targets)\n            elif isinstance(statement, ast.AnnAssign) and statement.value:\n                yield (statement.target, statement.value)\n\n    def __getattr__(self, attr):\n        \"\"\"Attempt to load an attribute \"statically\", via :func:`ast.literal_eval`.\"\"\"\n        try:\n            return next(\n                ast.literal_eval(value)\n                for target, value in self._find_assignments()\n                if isinstance(target, ast.Name) and target.id == attr\n            )\n        except Exception as e:\n            raise AttributeError(f\"{self.name} has no attribute {attr}\") from e\n\n\ndef glob_relative(\n    patterns: Iterable[str], root_dir: Optional[_Path] = None\n) -> List[str]:\n    \"\"\"Expand the list of glob patterns, but preserving relative paths.\n\n    :param list[str] patterns: List of glob patterns\n    :param str root_dir: Path to which globs should be relative\n                         (current directory by default)\n    :rtype: list\n    \"\"\"\n    glob_characters = {'*', '?', '[', ']', '{', '}'}\n    expanded_values = []\n    root_dir = root_dir or os.getcwd()\n    for value in patterns:\n\n        # Has globby characters?\n        if any(char in value for char in glob_characters):\n            # then expand the glob pattern while keeping paths *relative*:\n            glob_path = os.path.abspath(os.path.join(root_dir, value))\n            expanded_values.extend(sorted(\n                os.path.relpath(path, root_dir).replace(os.sep, \"/\")\n                for path in iglob(glob_path, recursive=True)))\n\n        else:\n            # take the value as-is\n            path = os.path.relpath(value, root_dir).replace(os.sep, \"/\")\n            expanded_values.append(path)\n\n    return expanded_values\n\n\ndef read_files(filepaths: Union[str, bytes, Iterable[_Path]], root_dir=None) -> str:\n    \"\"\"Return the content of the files concatenated using ``\\n`` as str\n\n    This function is sandboxed and won't reach anything outside ``root_dir``\n\n    (By default ``root_dir`` is the current directory).\n    \"\"\"\n    from setuptools.extern.more_itertools import always_iterable\n\n    root_dir = os.path.abspath(root_dir or os.getcwd())\n    _filepaths = (os.path.join(root_dir, path) for path in always_iterable(filepaths))\n    return '\\n'.join(\n        _read_file(path)\n        for path in _filter_existing_files(_filepaths)\n        if _assert_local(path, root_dir)\n    )\n\n\ndef _filter_existing_files(filepaths: Iterable[_Path]) -> Iterator[_Path]:\n    for path in filepaths:\n        if os.path.isfile(path):\n            yield path\n        else:\n            warnings.warn(f\"File {path!r} cannot be found\")\n\n\ndef _read_file(filepath: Union[bytes, _Path]) -> str:\n    with io.open(filepath, encoding='utf-8') as f:\n        return f.read()\n\n\ndef _assert_local(filepath: _Path, root_dir: str):\n    if Path(os.path.abspath(root_dir)) not in Path(os.path.abspath(filepath)).parents:\n        msg = f\"Cannot access {filepath!r} (or anything outside {root_dir!r})\"\n        raise DistutilsOptionError(msg)\n\n    return True\n\n\ndef read_attr(\n    attr_desc: str,\n    package_dir: Optional[Mapping[str, str]] = None,\n    root_dir: Optional[_Path] = None\n):\n    \"\"\"Reads the value of an attribute from a module.\n\n    This function will try to read the attributed statically first\n    (via :func:`ast.literal_eval`), and only evaluate the module if it fails.\n\n    Examples:\n        read_attr(\"package.attr\")\n        read_attr(\"package.module.attr\")\n\n    :param str attr_desc: Dot-separated string describing how to reach the\n        attribute (see examples above)\n    :param dict[str, str] package_dir: Mapping of package names to their\n        location in disk (represented by paths relative to ``root_dir``).\n    :param str root_dir: Path to directory containing all the packages in\n        ``package_dir`` (current directory by default).\n    :rtype: str\n    \"\"\"\n    root_dir = root_dir or os.getcwd()\n    attrs_path = attr_desc.strip().split('.')\n    attr_name = attrs_path.pop()\n    module_name = '.'.join(attrs_path)\n    module_name = module_name or '__init__'\n    _parent_path, path, module_name = _find_module(module_name, package_dir, root_dir)\n    spec = _find_spec(module_name, path)\n\n    try:\n        return getattr(StaticModule(module_name, spec), attr_name)\n    except Exception:\n        # fallback to evaluate module\n        module = _load_spec(spec, module_name)\n        return getattr(module, attr_name)\n\n\ndef _find_spec(module_name: str, module_path: Optional[_Path]) -> ModuleSpec:\n    spec = importlib.util.spec_from_file_location(module_name, module_path)\n    spec = spec or importlib.util.find_spec(module_name)\n\n    if spec is None:\n        raise ModuleNotFoundError(module_name)\n\n    return spec\n\n\ndef _load_spec(spec: ModuleSpec, module_name: str) -> ModuleType:\n    name = getattr(spec, \"__name__\", module_name)\n    if name in sys.modules:\n        return sys.modules[name]\n    module = importlib.util.module_from_spec(spec)\n    sys.modules[name] = module  # cache (it also ensures `==` works on loaded items)\n    spec.loader.exec_module(module)  # type: ignore\n    return module\n\n\ndef _find_module(\n    module_name: str, package_dir: Optional[Mapping[str, str]], root_dir: _Path\n) -> Tuple[_Path, Optional[str], str]:\n    \"\"\"Given a module (that could normally be imported by ``module_name``\n    after the build is complete), find the path to the parent directory where\n    it is contained and the canonical name that could be used to import it\n    considering the ``package_dir`` in the build configuration and ``root_dir``\n    \"\"\"\n    parent_path = root_dir\n    module_parts = module_name.split('.')\n    if package_dir:\n        if module_parts[0] in package_dir:\n            # A custom path was specified for the module we want to import\n            custom_path = package_dir[module_parts[0]]\n            parts = custom_path.rsplit('/', 1)\n            if len(parts) > 1:\n                parent_path = os.path.join(root_dir, parts[0])\n                parent_module = parts[1]\n            else:\n                parent_module = custom_path\n            module_name = \".\".join([parent_module, *module_parts[1:]])\n        elif '' in package_dir:\n            # A custom parent directory was specified for all root modules\n            parent_path = os.path.join(root_dir, package_dir[''])\n\n    path_start = os.path.join(parent_path, *module_name.split(\".\"))\n    candidates = chain(\n        (f\"{path_start}.py\", os.path.join(path_start, \"__init__.py\")),\n        iglob(f\"{path_start}.*\")\n    )\n    module_path = next((x for x in candidates if os.path.isfile(x)), None)\n    return parent_path, module_path, module_name\n\n\ndef resolve_class(\n    qualified_class_name: str,\n    package_dir: Optional[Mapping[str, str]] = None,\n    root_dir: Optional[_Path] = None\n) -> Callable:\n    \"\"\"Given a qualified class name, return the associated class object\"\"\"\n    root_dir = root_dir or os.getcwd()\n    idx = qualified_class_name.rfind('.')\n    class_name = qualified_class_name[idx + 1 :]\n    pkg_name = qualified_class_name[:idx]\n\n    _parent_path, path, module_name = _find_module(pkg_name, package_dir, root_dir)\n    module = _load_spec(_find_spec(module_name, path), module_name)\n    return getattr(module, class_name)\n\n\ndef cmdclass(\n    values: Dict[str, str],\n    package_dir: Optional[Mapping[str, str]] = None,\n    root_dir: Optional[_Path] = None\n) -> Dict[str, Callable]:\n    \"\"\"Given a dictionary mapping command names to strings for qualified class\n    names, apply :func:`resolve_class` to the dict values.\n    \"\"\"\n    return {k: resolve_class(v, package_dir, root_dir) for k, v in values.items()}\n\n\ndef find_packages(\n    *,\n    namespaces=True,\n    fill_package_dir: Optional[Dict[str, str]] = None,\n    root_dir: Optional[_Path] = None,\n    **kwargs\n) -> List[str]:\n    \"\"\"Works similarly to :func:`setuptools.find_packages`, but with all\n    arguments given as keyword arguments. Moreover, ``where`` can be given\n    as a list (the results will be simply concatenated).\n\n    When the additional keyword argument ``namespaces`` is ``True``, it will\n    behave like :func:`setuptools.find_namespace_packages`` (i.e. include\n    implicit namespaces as per :pep:`420`).\n\n    The ``where`` argument will be considered relative to ``root_dir`` (or the current\n    working directory when ``root_dir`` is not given).\n\n    If the ``fill_package_dir`` argument is passed, this function will consider it as a\n    similar data structure to the ``package_dir`` configuration parameter add fill-in\n    any missing package location.\n\n    :rtype: list\n    \"\"\"\n    from setuptools.discovery import construct_package_dir\n    from setuptools.extern.more_itertools import unique_everseen, always_iterable\n\n    if namespaces:\n        from setuptools.discovery import PEP420PackageFinder as PackageFinder\n    else:\n        from setuptools.discovery import PackageFinder  # type: ignore\n\n    root_dir = root_dir or os.curdir\n    where = kwargs.pop('where', ['.'])\n    packages: List[str] = []\n    fill_package_dir = {} if fill_package_dir is None else fill_package_dir\n    search = list(unique_everseen(always_iterable(where)))\n\n    if len(search) == 1 and all(not _same_path(search[0], x) for x in (\".\", root_dir)):\n        fill_package_dir.setdefault(\"\", search[0])\n\n    for path in search:\n        package_path = _nest_path(root_dir, path)\n        pkgs = PackageFinder.find(package_path, **kwargs)\n        packages.extend(pkgs)\n        if pkgs and not (\n            fill_package_dir.get(\"\") == path\n            or os.path.samefile(package_path, root_dir)\n        ):\n            fill_package_dir.update(construct_package_dir(pkgs, path))\n\n    return packages\n\n\ndef _nest_path(parent: _Path, path: _Path) -> str:\n    path = parent if path in {\".\", \"\"} else os.path.join(parent, path)\n    return os.path.normpath(path)\n\n\ndef version(value: Union[Callable, Iterable[Union[str, int]], str]) -> str:\n    \"\"\"When getting the version directly from an attribute,\n    it should be normalised to string.\n    \"\"\"\n    if callable(value):\n        value = value()\n\n    value = cast(Iterable[Union[str, int]], value)\n\n    if not isinstance(value, str):\n        if hasattr(value, '__iter__'):\n            value = '.'.join(map(str, value))\n        else:\n            value = '%s' % value\n\n    return value\n\n\ndef canonic_package_data(package_data: dict) -> dict:\n    if \"*\" in package_data:\n        package_data[\"\"] = package_data.pop(\"*\")\n    return package_data\n\n\ndef canonic_data_files(\n    data_files: Union[list, dict], root_dir: Optional[_Path] = None\n) -> List[Tuple[str, List[str]]]:\n    \"\"\"For compatibility with ``setup.py``, ``data_files`` should be a list\n    of pairs instead of a dict.\n\n    This function also expands glob patterns.\n    \"\"\"\n    if isinstance(data_files, list):\n        return data_files\n\n    return [\n        (dest, glob_relative(patterns, root_dir))\n        for dest, patterns in data_files.items()\n    ]\n\n\ndef entry_points(text: str, text_source=\"entry-points\") -> Dict[str, dict]:\n    \"\"\"Given the contents of entry-points file,\n    process it into a 2-level dictionary (``dict[str, dict[str, str]]``).\n    The first level keys are entry-point groups, the second level keys are\n    entry-point names, and the second level values are references to objects\n    (that correspond to the entry-point value).\n    \"\"\"\n    parser = ConfigParser(default_section=None, delimiters=(\"=\",))  # type: ignore\n    parser.optionxform = str  # case sensitive\n    parser.read_string(text, text_source)\n    groups = {k: dict(v.items()) for k, v in parser.items()}\n    groups.pop(parser.default_section, None)\n    return groups\n\n\nclass EnsurePackagesDiscovered:\n    \"\"\"Some expand functions require all the packages to already be discovered before\n    they run, e.g. :func:`read_attr`, :func:`resolve_class`, :func:`cmdclass`.\n\n    Therefore in some cases we will need to run autodiscovery during the evaluation of\n    the configuration. However, it is better to postpone calling package discovery as\n    much as possible, because some parameters can influence it (e.g. ``package_dir``),\n    and those might not have been processed yet.\n    \"\"\"\n\n    def __init__(self, distribution: \"Distribution\"):\n        self._dist = distribution\n        self._called = False\n\n    def __call__(self):\n        \"\"\"Trigger the automatic package discovery, if it is still necessary.\"\"\"\n        if not self._called:\n            self._called = True\n            self._dist.set_defaults(name=False)  # Skip name, we can still be parsing\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, _exc_type, _exc_value, _traceback):\n        if self._called:\n            self._dist.set_defaults.analyse_name()  # Now we can set a default name\n\n    def _get_package_dir(self) -> Mapping[str, str]:\n        self()\n        pkg_dir = self._dist.package_dir\n        return {} if pkg_dir is None else pkg_dir\n\n    @property\n    def package_dir(self) -> Mapping[str, str]:\n        \"\"\"Proxy to ``package_dir`` that may trigger auto-discovery when used.\"\"\"\n        return LazyMappingProxy(self._get_package_dir)\n\n\nclass LazyMappingProxy(Mapping[_K, _V]):\n    \"\"\"Mapping proxy that delays resolving the target object, until really needed.\n\n    >>> def obtain_mapping():\n    ...     print(\"Running expensive function!\")\n    ...     return {\"key\": \"value\", \"other key\": \"other value\"}\n    >>> mapping = LazyMappingProxy(obtain_mapping)\n    >>> mapping[\"key\"]\n    Running expensive function!\n    'value'\n    >>> mapping[\"other key\"]\n    'other value'\n    \"\"\"\n\n    def __init__(self, obtain_mapping_value: Callable[[], Mapping[_K, _V]]):\n        self._obtain = obtain_mapping_value\n        self._value: Optional[Mapping[_K, _V]] = None\n\n    def _target(self) -> Mapping[_K, _V]:\n        if self._value is None:\n            self._value = self._obtain()\n        return self._value\n\n    def __getitem__(self, key: _K) -> _V:\n        return self._target()[key]\n\n    def __len__(self) -> int:\n        return len(self._target())\n\n    def __iter__(self) -> Iterator[_K]:\n        return iter(self._target())\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/config/pyprojecttoml.py",
    "content": "\"\"\"\nLoad setuptools configuration from ``pyproject.toml`` files.\n\n**PRIVATE MODULE**: API reserved for setuptools internal usage only.\n\"\"\"\nimport logging\nimport os\nimport warnings\nfrom contextlib import contextmanager\nfrom functools import partial\nfrom typing import TYPE_CHECKING, Callable, Dict, Optional, Mapping, Union\n\nfrom setuptools.errors import FileError, OptionError\n\nfrom . import expand as _expand\nfrom ._apply_pyprojecttoml import apply as _apply\nfrom ._apply_pyprojecttoml import _PREVIOUSLY_DEFINED, _WouldIgnoreField\n\nif TYPE_CHECKING:\n    from setuptools.dist import Distribution  # noqa\n\n_Path = Union[str, os.PathLike]\n_logger = logging.getLogger(__name__)\n\n\ndef load_file(filepath: _Path) -> dict:\n    from setuptools.extern import tomli  # type: ignore\n\n    with open(filepath, \"rb\") as file:\n        return tomli.load(file)\n\n\ndef validate(config: dict, filepath: _Path) -> bool:\n    from . import _validate_pyproject as validator\n\n    trove_classifier = validator.FORMAT_FUNCTIONS.get(\"trove-classifier\")\n    if hasattr(trove_classifier, \"_disable_download\"):\n        # Improve reproducibility by default. See issue 31 for validate-pyproject.\n        trove_classifier._disable_download()  # type: ignore\n\n    try:\n        return validator.validate(config)\n    except validator.ValidationError as ex:\n        summary = f\"configuration error: {ex.summary}\"\n        if ex.name.strip(\"`\") != \"project\":\n            # Probably it is just a field missing/misnamed, not worthy the verbosity...\n            _logger.debug(summary)\n            _logger.debug(ex.details)\n\n        error = f\"invalid pyproject.toml config: {ex.name}.\"\n        raise ValueError(f\"{error}\\n{summary}\") from None\n\n\ndef apply_configuration(\n    dist: \"Distribution\",\n    filepath: _Path,\n    ignore_option_errors=False,\n) -> \"Distribution\":\n    \"\"\"Apply the configuration from a ``pyproject.toml`` file into an existing\n    distribution object.\n    \"\"\"\n    config = read_configuration(filepath, True, ignore_option_errors, dist)\n    return _apply(dist, config, filepath)\n\n\ndef read_configuration(\n    filepath: _Path,\n    expand=True,\n    ignore_option_errors=False,\n    dist: Optional[\"Distribution\"] = None,\n):\n    \"\"\"Read given configuration file and returns options from it as a dict.\n\n    :param str|unicode filepath: Path to configuration file in the ``pyproject.toml``\n        format.\n\n    :param bool expand: Whether to expand directives and other computed values\n        (i.e. post-process the given configuration)\n\n    :param bool ignore_option_errors: Whether to silently ignore\n        options, values of which could not be resolved (e.g. due to exceptions\n        in directives such as file:, attr:, etc.).\n        If False exceptions are propagated as expected.\n\n    :param Distribution|None: Distribution object to which the configuration refers.\n        If not given a dummy object will be created and discarded after the\n        configuration is read. This is used for auto-discovery of packages in the case\n        a dynamic configuration (e.g. ``attr`` or ``cmdclass``) is expanded.\n        When ``expand=False`` this object is simply ignored.\n\n    :rtype: dict\n    \"\"\"\n    filepath = os.path.abspath(filepath)\n\n    if not os.path.isfile(filepath):\n        raise FileError(f\"Configuration file {filepath!r} does not exist.\")\n\n    asdict = load_file(filepath) or {}\n    project_table = asdict.get(\"project\", {})\n    tool_table = asdict.get(\"tool\", {})\n    setuptools_table = tool_table.get(\"setuptools\", {})\n    if not asdict or not (project_table or setuptools_table):\n        return {}  # User is not using pyproject to configure setuptools\n\n    if setuptools_table:\n        # TODO: Remove the following once the feature stabilizes:\n        msg = \"Support for `[tool.setuptools]` in `pyproject.toml` is still *beta*.\"\n        warnings.warn(msg, _BetaConfiguration)\n\n    # There is an overall sense in the community that making include_package_data=True\n    # the default would be an improvement.\n    # `ini2toml` backfills include_package_data=False when nothing is explicitly given,\n    # therefore setting a default here is backwards compatible.\n    orig_setuptools_table = setuptools_table.copy()\n    if dist and getattr(dist, \"include_package_data\") is not None:\n        setuptools_table.setdefault(\"include-package-data\", dist.include_package_data)\n    else:\n        setuptools_table.setdefault(\"include-package-data\", True)\n    # Persist changes:\n    asdict[\"tool\"] = tool_table\n    tool_table[\"setuptools\"] = setuptools_table\n\n    try:\n        # Don't complain about unrelated errors (e.g. tools not using the \"tool\" table)\n        subset = {\"project\": project_table, \"tool\": {\"setuptools\": setuptools_table}}\n        validate(subset, filepath)\n    except Exception as ex:\n        # TODO: Remove the following once the feature stabilizes:\n        if _skip_bad_config(project_table, orig_setuptools_table, dist):\n            return {}\n        # TODO: After the previous statement is removed the try/except can be replaced\n        # by the _ignore_errors context manager.\n        if ignore_option_errors:\n            _logger.debug(f\"ignored error: {ex.__class__.__name__} - {ex}\")\n        else:\n            raise  # re-raise exception\n\n    if expand:\n        root_dir = os.path.dirname(filepath)\n        return expand_configuration(asdict, root_dir, ignore_option_errors, dist)\n\n    return asdict\n\n\ndef _skip_bad_config(\n    project_cfg: dict, setuptools_cfg: dict, dist: Optional[\"Distribution\"]\n) -> bool:\n    \"\"\"Be temporarily forgiving with invalid ``pyproject.toml``\"\"\"\n    # See pypa/setuptools#3199 and pypa/cibuildwheel#1064\n\n    if dist is None or (\n        dist.metadata.name is None\n        and dist.metadata.version is None\n        and dist.install_requires is None\n    ):\n        # It seems that the build is not getting any configuration from other places\n        return False\n\n    if setuptools_cfg:\n        # If `[tool.setuptools]` is set, then `pyproject.toml` config is intentional\n        return False\n\n    given_config = set(project_cfg.keys())\n    popular_subset = {\"name\", \"version\", \"python_requires\", \"requires-python\"}\n    if given_config <= popular_subset:\n        # It seems that the docs in cibuildtool has been inadvertently encouraging users\n        # to create `pyproject.toml` files that are not compliant with the standards.\n        # Let's be forgiving for the time being.\n        warnings.warn(_InvalidFile.message(), _InvalidFile, stacklevel=2)\n        return True\n\n    return False\n\n\ndef expand_configuration(\n    config: dict,\n    root_dir: Optional[_Path] = None,\n    ignore_option_errors: bool = False,\n    dist: Optional[\"Distribution\"] = None,\n) -> dict:\n    \"\"\"Given a configuration with unresolved fields (e.g. dynamic, cmdclass, ...)\n    find their final values.\n\n    :param dict config: Dict containing the configuration for the distribution\n    :param str root_dir: Top-level directory for the distribution/project\n        (the same directory where ``pyproject.toml`` is place)\n    :param bool ignore_option_errors: see :func:`read_configuration`\n    :param Distribution|None: Distribution object to which the configuration refers.\n        If not given a dummy object will be created and discarded after the\n        configuration is read. Used in the case a dynamic configuration\n        (e.g. ``attr`` or ``cmdclass``).\n\n    :rtype: dict\n    \"\"\"\n    return _ConfigExpander(config, root_dir, ignore_option_errors, dist).expand()\n\n\nclass _ConfigExpander:\n    def __init__(\n        self,\n        config: dict,\n        root_dir: Optional[_Path] = None,\n        ignore_option_errors: bool = False,\n        dist: Optional[\"Distribution\"] = None,\n    ):\n        self.config = config\n        self.root_dir = root_dir or os.getcwd()\n        self.project_cfg = config.get(\"project\", {})\n        self.dynamic = self.project_cfg.get(\"dynamic\", [])\n        self.setuptools_cfg = config.get(\"tool\", {}).get(\"setuptools\", {})\n        self.dynamic_cfg = self.setuptools_cfg.get(\"dynamic\", {})\n        self.ignore_option_errors = ignore_option_errors\n        self._dist = dist\n\n    def _ensure_dist(self) -> \"Distribution\":\n        from setuptools.dist import Distribution\n\n        attrs = {\"src_root\": self.root_dir, \"name\": self.project_cfg.get(\"name\", None)}\n        return self._dist or Distribution(attrs)\n\n    def _process_field(self, container: dict, field: str, fn: Callable):\n        if field in container:\n            with _ignore_errors(self.ignore_option_errors):\n                container[field] = fn(container[field])\n\n    def _canonic_package_data(self, field=\"package-data\"):\n        package_data = self.setuptools_cfg.get(field, {})\n        return _expand.canonic_package_data(package_data)\n\n    def expand(self):\n        self._expand_packages()\n        self._canonic_package_data()\n        self._canonic_package_data(\"exclude-package-data\")\n\n        # A distribution object is required for discovering the correct package_dir\n        dist = self._ensure_dist()\n        ctx = _EnsurePackagesDiscovered(dist, self.project_cfg, self.setuptools_cfg)\n        with ctx as ensure_discovered:\n            package_dir = ensure_discovered.package_dir\n            self._expand_data_files()\n            self._expand_cmdclass(package_dir)\n            self._expand_all_dynamic(dist, package_dir)\n\n        return self.config\n\n    def _expand_packages(self):\n        packages = self.setuptools_cfg.get(\"packages\")\n        if packages is None or isinstance(packages, (list, tuple)):\n            return\n\n        find = packages.get(\"find\")\n        if isinstance(find, dict):\n            find[\"root_dir\"] = self.root_dir\n            find[\"fill_package_dir\"] = self.setuptools_cfg.setdefault(\"package-dir\", {})\n            with _ignore_errors(self.ignore_option_errors):\n                self.setuptools_cfg[\"packages\"] = _expand.find_packages(**find)\n\n    def _expand_data_files(self):\n        data_files = partial(_expand.canonic_data_files, root_dir=self.root_dir)\n        self._process_field(self.setuptools_cfg, \"data-files\", data_files)\n\n    def _expand_cmdclass(self, package_dir: Mapping[str, str]):\n        root_dir = self.root_dir\n        cmdclass = partial(_expand.cmdclass, package_dir=package_dir, root_dir=root_dir)\n        self._process_field(self.setuptools_cfg, \"cmdclass\", cmdclass)\n\n    def _expand_all_dynamic(self, dist: \"Distribution\", package_dir: Mapping[str, str]):\n        special = (  # need special handling\n            \"version\",\n            \"readme\",\n            \"entry-points\",\n            \"scripts\",\n            \"gui-scripts\",\n            \"classifiers\",\n            \"dependencies\",\n            \"optional-dependencies\",\n        )\n        # `_obtain` functions are assumed to raise appropriate exceptions/warnings.\n        obtained_dynamic = {\n            field: self._obtain(dist, field, package_dir)\n            for field in self.dynamic\n            if field not in special\n        }\n        obtained_dynamic.update(\n            self._obtain_entry_points(dist, package_dir) or {},\n            version=self._obtain_version(dist, package_dir),\n            readme=self._obtain_readme(dist),\n            classifiers=self._obtain_classifiers(dist),\n            dependencies=self._obtain_dependencies(dist),\n            optional_dependencies=self._obtain_optional_dependencies(dist),\n        )\n        # `None` indicates there is nothing in `tool.setuptools.dynamic` but the value\n        # might have already been set by setup.py/extensions, so avoid overwriting.\n        updates = {k: v for k, v in obtained_dynamic.items() if v is not None}\n        self.project_cfg.update(updates)\n\n    def _ensure_previously_set(self, dist: \"Distribution\", field: str):\n        previous = _PREVIOUSLY_DEFINED[field](dist)\n        if previous is None and not self.ignore_option_errors:\n            msg = (\n                f\"No configuration found for dynamic {field!r}.\\n\"\n                \"Some dynamic fields need to be specified via `tool.setuptools.dynamic`\"\n                \"\\nothers must be specified via the equivalent attribute in `setup.py`.\"\n            )\n            raise OptionError(msg)\n\n    def _expand_directive(\n        self, specifier: str, directive, package_dir: Mapping[str, str]\n    ):\n        with _ignore_errors(self.ignore_option_errors):\n            root_dir = self.root_dir\n            if \"file\" in directive:\n                return _expand.read_files(directive[\"file\"], root_dir)\n            if \"attr\" in directive:\n                return _expand.read_attr(directive[\"attr\"], package_dir, root_dir)\n            raise ValueError(f\"invalid `{specifier}`: {directive!r}\")\n        return None\n\n    def _obtain(self, dist: \"Distribution\", field: str, package_dir: Mapping[str, str]):\n        if field in self.dynamic_cfg:\n            return self._expand_directive(\n                f\"tool.setuptools.dynamic.{field}\",\n                self.dynamic_cfg[field],\n                package_dir,\n            )\n        self._ensure_previously_set(dist, field)\n        return None\n\n    def _obtain_version(self, dist: \"Distribution\", package_dir: Mapping[str, str]):\n        # Since plugins can set version, let's silently skip if it cannot be obtained\n        if \"version\" in self.dynamic and \"version\" in self.dynamic_cfg:\n            return _expand.version(self._obtain(dist, \"version\", package_dir))\n        return None\n\n    def _obtain_readme(self, dist: \"Distribution\") -> Optional[Dict[str, str]]:\n        if \"readme\" not in self.dynamic:\n            return None\n\n        dynamic_cfg = self.dynamic_cfg\n        if \"readme\" in dynamic_cfg:\n            return {\n                \"text\": self._obtain(dist, \"readme\", {}),\n                \"content-type\": dynamic_cfg[\"readme\"].get(\"content-type\", \"text/x-rst\"),\n            }\n\n        self._ensure_previously_set(dist, \"readme\")\n        return None\n\n    def _obtain_entry_points(\n        self, dist: \"Distribution\", package_dir: Mapping[str, str]\n    ) -> Optional[Dict[str, dict]]:\n        fields = (\"entry-points\", \"scripts\", \"gui-scripts\")\n        if not any(field in self.dynamic for field in fields):\n            return None\n\n        text = self._obtain(dist, \"entry-points\", package_dir)\n        if text is None:\n            return None\n\n        groups = _expand.entry_points(text)\n        expanded = {\"entry-points\": groups}\n\n        def _set_scripts(field: str, group: str):\n            if group in groups:\n                value = groups.pop(group)\n                if field not in self.dynamic:\n                    msg = _WouldIgnoreField.message(field, value)\n                    warnings.warn(msg, _WouldIgnoreField)\n                # TODO: Don't set field when support for pyproject.toml stabilizes\n                #       instead raise an error as specified in PEP 621\n                expanded[field] = value\n\n        _set_scripts(\"scripts\", \"console_scripts\")\n        _set_scripts(\"gui-scripts\", \"gui_scripts\")\n\n        return expanded\n\n    def _obtain_classifiers(self, dist: \"Distribution\"):\n        if \"classifiers\" in self.dynamic:\n            value = self._obtain(dist, \"classifiers\", {})\n            if value:\n                return value.splitlines()\n        return None\n\n    def _obtain_dependencies(self, dist: \"Distribution\"):\n        if \"dependencies\" in self.dynamic:\n            value = self._obtain(dist, \"dependencies\", {})\n            if value:\n                return _parse_requirements_list(value)\n        return None\n\n    def _obtain_optional_dependencies(self, dist: \"Distribution\"):\n        if \"optional-dependencies\" not in self.dynamic:\n            return None\n        if \"optional-dependencies\" in self.dynamic_cfg:\n            optional_dependencies_map = self.dynamic_cfg[\"optional-dependencies\"]\n            assert isinstance(optional_dependencies_map, dict)\n            return {\n                group: _parse_requirements_list(self._expand_directive(\n                    f\"tool.setuptools.dynamic.optional-dependencies.{group}\",\n                    directive,\n                    {},\n                ))\n                for group, directive in optional_dependencies_map.items()\n            }\n        self._ensure_previously_set(dist, \"optional-dependencies\")\n        return None\n\n\ndef _parse_requirements_list(value):\n    return [\n        line\n        for line in value.splitlines()\n        if line.strip() and not line.strip().startswith(\"#\")\n    ]\n\n\n@contextmanager\ndef _ignore_errors(ignore_option_errors: bool):\n    if not ignore_option_errors:\n        yield\n        return\n\n    try:\n        yield\n    except Exception as ex:\n        _logger.debug(f\"ignored error: {ex.__class__.__name__} - {ex}\")\n\n\nclass _EnsurePackagesDiscovered(_expand.EnsurePackagesDiscovered):\n    def __init__(\n        self, distribution: \"Distribution\", project_cfg: dict, setuptools_cfg: dict\n    ):\n        super().__init__(distribution)\n        self._project_cfg = project_cfg\n        self._setuptools_cfg = setuptools_cfg\n\n    def __enter__(self):\n        \"\"\"When entering the context, the values of ``packages``, ``py_modules`` and\n        ``package_dir`` that are missing in ``dist`` are copied from ``setuptools_cfg``.\n        \"\"\"\n        dist, cfg = self._dist, self._setuptools_cfg\n        package_dir: Dict[str, str] = cfg.setdefault(\"package-dir\", {})\n        package_dir.update(dist.package_dir or {})\n        dist.package_dir = package_dir  # needs to be the same object\n\n        dist.set_defaults._ignore_ext_modules()  # pyproject.toml-specific behaviour\n\n        # Set `name`, `py_modules` and `packages` in dist to short-circuit\n        # auto-discovery, but avoid overwriting empty lists purposefully set by users.\n        if dist.metadata.name is None:\n            dist.metadata.name = self._project_cfg.get(\"name\")\n        if dist.py_modules is None:\n            dist.py_modules = cfg.get(\"py-modules\")\n        if dist.packages is None:\n            dist.packages = cfg.get(\"packages\")\n\n        return super().__enter__()\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        \"\"\"When exiting the context, if values of ``packages``, ``py_modules`` and\n        ``package_dir`` are missing in ``setuptools_cfg``, copy from ``dist``.\n        \"\"\"\n        # If anything was discovered set them back, so they count in the final config.\n        self._setuptools_cfg.setdefault(\"packages\", self._dist.packages)\n        self._setuptools_cfg.setdefault(\"py-modules\", self._dist.py_modules)\n        return super().__exit__(exc_type, exc_value, traceback)\n\n\nclass _BetaConfiguration(UserWarning):\n    \"\"\"Explicitly inform users that some `pyproject.toml` configuration is *beta*\"\"\"\n\n\nclass _InvalidFile(UserWarning):\n    \"\"\"The given `pyproject.toml` file is invalid and would be ignored.\n    !!\\n\\n\n    ############################\n    # Invalid `pyproject.toml` #\n    ############################\n\n    Any configurations in `pyproject.toml` will be ignored.\n    Please note that future releases of setuptools will halt the build process\n    if an invalid file is given.\n\n    To prevent setuptools from considering `pyproject.toml` please\n    DO NOT include the `[project]` or `[tool.setuptools]` tables in your file.\n    \\n\\n!!\n    \"\"\"\n\n    @classmethod\n    def message(cls):\n        from inspect import cleandoc\n        return cleandoc(cls.__doc__)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/config/setupcfg.py",
    "content": "\"\"\"\nLoad setuptools configuration from ``setup.cfg`` files.\n\n**API will be made private in the future**\n\"\"\"\nimport os\n\nimport contextlib\nimport functools\nimport warnings\nfrom collections import defaultdict\nfrom functools import partial\nfrom functools import wraps\nfrom typing import (TYPE_CHECKING, Callable, Any, Dict, Generic, Iterable, List,\n                    Optional, Tuple, TypeVar, Union)\n\nfrom distutils.errors import DistutilsOptionError, DistutilsFileError\nfrom setuptools.extern.packaging.requirements import Requirement, InvalidRequirement\nfrom setuptools.extern.packaging.version import Version, InvalidVersion\nfrom setuptools.extern.packaging.specifiers import SpecifierSet\nfrom setuptools._deprecation_warning import SetuptoolsDeprecationWarning\n\nfrom . import expand\n\nif TYPE_CHECKING:\n    from setuptools.dist import Distribution  # noqa\n    from distutils.dist import DistributionMetadata  # noqa\n\n_Path = Union[str, os.PathLike]\nSingleCommandOptions = Dict[\"str\", Tuple[\"str\", Any]]\n\"\"\"Dict that associate the name of the options of a particular command to a\ntuple. The first element of the tuple indicates the origin of the option value\n(e.g. the name of the configuration file where it was read from),\nwhile the second element of the tuple is the option value itself\n\"\"\"\nAllCommandOptions = Dict[\"str\", SingleCommandOptions]  # cmd name => its options\nTarget = TypeVar(\"Target\", bound=Union[\"Distribution\", \"DistributionMetadata\"])\n\n\ndef read_configuration(\n    filepath: _Path,\n    find_others=False,\n    ignore_option_errors=False\n) -> dict:\n    \"\"\"Read given configuration file and returns options from it as a dict.\n\n    :param str|unicode filepath: Path to configuration file\n        to get options from.\n\n    :param bool find_others: Whether to search for other configuration files\n        which could be on in various places.\n\n    :param bool ignore_option_errors: Whether to silently ignore\n        options, values of which could not be resolved (e.g. due to exceptions\n        in directives such as file:, attr:, etc.).\n        If False exceptions are propagated as expected.\n\n    :rtype: dict\n    \"\"\"\n    from setuptools.dist import Distribution\n\n    dist = Distribution()\n    filenames = dist.find_config_files() if find_others else []\n    handlers = _apply(dist, filepath, filenames, ignore_option_errors)\n    return configuration_to_dict(handlers)\n\n\ndef apply_configuration(dist: \"Distribution\", filepath: _Path) -> \"Distribution\":\n    \"\"\"Apply the configuration from a ``setup.cfg`` file into an existing\n    distribution object.\n    \"\"\"\n    _apply(dist, filepath)\n    dist._finalize_requires()\n    return dist\n\n\ndef _apply(\n    dist: \"Distribution\", filepath: _Path,\n    other_files: Iterable[_Path] = (),\n    ignore_option_errors: bool = False,\n) -> Tuple[\"ConfigHandler\", ...]:\n    \"\"\"Read configuration from ``filepath`` and applies to the ``dist`` object.\"\"\"\n    from setuptools.dist import _Distribution\n\n    filepath = os.path.abspath(filepath)\n\n    if not os.path.isfile(filepath):\n        raise DistutilsFileError('Configuration file %s does not exist.' % filepath)\n\n    current_directory = os.getcwd()\n    os.chdir(os.path.dirname(filepath))\n    filenames = [*other_files, filepath]\n\n    try:\n        _Distribution.parse_config_files(dist, filenames=filenames)\n        handlers = parse_configuration(\n            dist, dist.command_options, ignore_option_errors=ignore_option_errors\n        )\n        dist._finalize_license_files()\n    finally:\n        os.chdir(current_directory)\n\n    return handlers\n\n\ndef _get_option(target_obj: Target, key: str):\n    \"\"\"\n    Given a target object and option key, get that option from\n    the target object, either through a get_{key} method or\n    from an attribute directly.\n    \"\"\"\n    getter_name = 'get_{key}'.format(**locals())\n    by_attribute = functools.partial(getattr, target_obj, key)\n    getter = getattr(target_obj, getter_name, by_attribute)\n    return getter()\n\n\ndef configuration_to_dict(handlers: Tuple[\"ConfigHandler\", ...]) -> dict:\n    \"\"\"Returns configuration data gathered by given handlers as a dict.\n\n    :param list[ConfigHandler] handlers: Handlers list,\n        usually from parse_configuration()\n\n    :rtype: dict\n    \"\"\"\n    config_dict: dict = defaultdict(dict)\n\n    for handler in handlers:\n        for option in handler.set_options:\n            value = _get_option(handler.target_obj, option)\n            config_dict[handler.section_prefix][option] = value\n\n    return config_dict\n\n\ndef parse_configuration(\n    distribution: \"Distribution\",\n    command_options: AllCommandOptions,\n    ignore_option_errors=False\n) -> Tuple[\"ConfigMetadataHandler\", \"ConfigOptionsHandler\"]:\n    \"\"\"Performs additional parsing of configuration options\n    for a distribution.\n\n    Returns a list of used option handlers.\n\n    :param Distribution distribution:\n    :param dict command_options:\n    :param bool ignore_option_errors: Whether to silently ignore\n        options, values of which could not be resolved (e.g. due to exceptions\n        in directives such as file:, attr:, etc.).\n        If False exceptions are propagated as expected.\n    :rtype: list\n    \"\"\"\n    with expand.EnsurePackagesDiscovered(distribution) as ensure_discovered:\n        options = ConfigOptionsHandler(\n            distribution,\n            command_options,\n            ignore_option_errors,\n            ensure_discovered,\n        )\n\n        options.parse()\n        if not distribution.package_dir:\n            distribution.package_dir = options.package_dir  # Filled by `find_packages`\n\n        meta = ConfigMetadataHandler(\n            distribution.metadata,\n            command_options,\n            ignore_option_errors,\n            ensure_discovered,\n            distribution.package_dir,\n            distribution.src_root,\n        )\n        meta.parse()\n\n    return meta, options\n\n\ndef _warn_accidental_env_marker_misconfig(label: str, orig_value: str, parsed: list):\n    \"\"\"Because users sometimes misinterpret this configuration:\n\n    [options.extras_require]\n    foo = bar;python_version<\"4\"\n\n    It looks like one requirement with an environment marker\n    but because there is no newline, it's parsed as two requirements\n    with a semicolon as separator.\n\n    Therefore, if:\n        * input string does not contain a newline AND\n        * parsed result contains two requirements AND\n        * parsing of the two parts from the result (\"<first>;<second>\")\n        leads in a valid Requirement with a valid marker\n    a UserWarning is shown to inform the user about the possible problem.\n    \"\"\"\n    if \"\\n\" in orig_value or len(parsed) != 2:\n        return\n\n    with contextlib.suppress(InvalidRequirement):\n        original_requirements_str = \";\".join(parsed)\n        req = Requirement(original_requirements_str)\n        if req.marker is not None:\n            msg = (\n                f\"One of the parsed requirements in `{label}` \"\n                f\"looks like a valid environment marker: '{parsed[1]}'\\n\"\n                \"Make sure that the config is correct and check \"\n                \"https://setuptools.pypa.io/en/latest/userguide/declarative_config.html#opt-2\"  # noqa: E501\n            )\n            warnings.warn(msg, UserWarning)\n\n\nclass ConfigHandler(Generic[Target]):\n    \"\"\"Handles metadata supplied in configuration files.\"\"\"\n\n    section_prefix: str\n    \"\"\"Prefix for config sections handled by this handler.\n    Must be provided by class heirs.\n\n    \"\"\"\n\n    aliases: Dict[str, str] = {}\n    \"\"\"Options aliases.\n    For compatibility with various packages. E.g.: d2to1 and pbr.\n    Note: `-` in keys is replaced with `_` by config parser.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        target_obj: Target,\n        options: AllCommandOptions,\n        ignore_option_errors,\n        ensure_discovered: expand.EnsurePackagesDiscovered,\n    ):\n        sections: AllCommandOptions = {}\n\n        section_prefix = self.section_prefix\n        for section_name, section_options in options.items():\n            if not section_name.startswith(section_prefix):\n                continue\n\n            section_name = section_name.replace(section_prefix, '').strip('.')\n            sections[section_name] = section_options\n\n        self.ignore_option_errors = ignore_option_errors\n        self.target_obj = target_obj\n        self.sections = sections\n        self.set_options: List[str] = []\n        self.ensure_discovered = ensure_discovered\n\n    @property\n    def parsers(self):\n        \"\"\"Metadata item name to parser function mapping.\"\"\"\n        raise NotImplementedError(\n            '%s must provide .parsers property' % self.__class__.__name__\n        )\n\n    def __setitem__(self, option_name, value):\n        unknown = tuple()\n        target_obj = self.target_obj\n\n        # Translate alias into real name.\n        option_name = self.aliases.get(option_name, option_name)\n\n        current_value = getattr(target_obj, option_name, unknown)\n\n        if current_value is unknown:\n            raise KeyError(option_name)\n\n        if current_value:\n            # Already inhabited. Skipping.\n            return\n\n        skip_option = False\n        parser = self.parsers.get(option_name)\n        if parser:\n            try:\n                value = parser(value)\n\n            except Exception:\n                skip_option = True\n                if not self.ignore_option_errors:\n                    raise\n\n        if skip_option:\n            return\n\n        setter = getattr(target_obj, 'set_%s' % option_name, None)\n        if setter is None:\n            setattr(target_obj, option_name, value)\n        else:\n            setter(value)\n\n        self.set_options.append(option_name)\n\n    @classmethod\n    def _parse_list(cls, value, separator=','):\n        \"\"\"Represents value as a list.\n\n        Value is split either by separator (defaults to comma) or by lines.\n\n        :param value:\n        :param separator: List items separator character.\n        :rtype: list\n        \"\"\"\n        if isinstance(value, list):  # _get_parser_compound case\n            return value\n\n        if '\\n' in value:\n            value = value.splitlines()\n        else:\n            value = value.split(separator)\n\n        return [chunk.strip() for chunk in value if chunk.strip()]\n\n    @classmethod\n    def _parse_dict(cls, value):\n        \"\"\"Represents value as a dict.\n\n        :param value:\n        :rtype: dict\n        \"\"\"\n        separator = '='\n        result = {}\n        for line in cls._parse_list(value):\n            key, sep, val = line.partition(separator)\n            if sep != separator:\n                raise DistutilsOptionError(\n                    'Unable to parse option value to dict: %s' % value\n                )\n            result[key.strip()] = val.strip()\n\n        return result\n\n    @classmethod\n    def _parse_bool(cls, value):\n        \"\"\"Represents value as boolean.\n\n        :param value:\n        :rtype: bool\n        \"\"\"\n        value = value.lower()\n        return value in ('1', 'true', 'yes')\n\n    @classmethod\n    def _exclude_files_parser(cls, key):\n        \"\"\"Returns a parser function to make sure field inputs\n        are not files.\n\n        Parses a value after getting the key so error messages are\n        more informative.\n\n        :param key:\n        :rtype: callable\n        \"\"\"\n\n        def parser(value):\n            exclude_directive = 'file:'\n            if value.startswith(exclude_directive):\n                raise ValueError(\n                    'Only strings are accepted for the {0} field, '\n                    'files are not accepted'.format(key)\n                )\n            return value\n\n        return parser\n\n    @classmethod\n    def _parse_file(cls, value, root_dir: _Path):\n        \"\"\"Represents value as a string, allowing including text\n        from nearest files using `file:` directive.\n\n        Directive is sandboxed and won't reach anything outside\n        directory with setup.py.\n\n        Examples:\n            file: README.rst, CHANGELOG.md, src/file.txt\n\n        :param str value:\n        :rtype: str\n        \"\"\"\n        include_directive = 'file:'\n\n        if not isinstance(value, str):\n            return value\n\n        if not value.startswith(include_directive):\n            return value\n\n        spec = value[len(include_directive) :]\n        filepaths = (path.strip() for path in spec.split(','))\n        return expand.read_files(filepaths, root_dir)\n\n    def _parse_attr(self, value, package_dir, root_dir: _Path):\n        \"\"\"Represents value as a module attribute.\n\n        Examples:\n            attr: package.attr\n            attr: package.module.attr\n\n        :param str value:\n        :rtype: str\n        \"\"\"\n        attr_directive = 'attr:'\n        if not value.startswith(attr_directive):\n            return value\n\n        attr_desc = value.replace(attr_directive, '')\n\n        # Make sure package_dir is populated correctly, so `attr:` directives can work\n        package_dir.update(self.ensure_discovered.package_dir)\n        return expand.read_attr(attr_desc, package_dir, root_dir)\n\n    @classmethod\n    def _get_parser_compound(cls, *parse_methods):\n        \"\"\"Returns parser function to represents value as a list.\n\n        Parses a value applying given methods one after another.\n\n        :param parse_methods:\n        :rtype: callable\n        \"\"\"\n\n        def parse(value):\n            parsed = value\n\n            for method in parse_methods:\n                parsed = method(parsed)\n\n            return parsed\n\n        return parse\n\n    @classmethod\n    def _parse_section_to_dict_with_key(cls, section_options, values_parser):\n        \"\"\"Parses section options into a dictionary.\n\n        Applies a given parser to each option in a section.\n\n        :param dict section_options:\n        :param callable values_parser: function with 2 args corresponding to key, value\n        :rtype: dict\n        \"\"\"\n        value = {}\n        for key, (_, val) in section_options.items():\n            value[key] = values_parser(key, val)\n        return value\n\n    @classmethod\n    def _parse_section_to_dict(cls, section_options, values_parser=None):\n        \"\"\"Parses section options into a dictionary.\n\n        Optionally applies a given parser to each value.\n\n        :param dict section_options:\n        :param callable values_parser: function with 1 arg corresponding to option value\n        :rtype: dict\n        \"\"\"\n        parser = (lambda _, v: values_parser(v)) if values_parser else (lambda _, v: v)\n        return cls._parse_section_to_dict_with_key(section_options, parser)\n\n    def parse_section(self, section_options):\n        \"\"\"Parses configuration file section.\n\n        :param dict section_options:\n        \"\"\"\n        for (name, (_, value)) in section_options.items():\n            with contextlib.suppress(KeyError):\n                # Keep silent for a new option may appear anytime.\n                self[name] = value\n\n    def parse(self):\n        \"\"\"Parses configuration file items from one\n        or more related sections.\n\n        \"\"\"\n        for section_name, section_options in self.sections.items():\n\n            method_postfix = ''\n            if section_name:  # [section.option] variant\n                method_postfix = '_%s' % section_name\n\n            section_parser_method: Optional[Callable] = getattr(\n                self,\n                # Dots in section names are translated into dunderscores.\n                ('parse_section%s' % method_postfix).replace('.', '__'),\n                None,\n            )\n\n            if section_parser_method is None:\n                raise DistutilsOptionError(\n                    'Unsupported distribution option section: [%s.%s]'\n                    % (self.section_prefix, section_name)\n                )\n\n            section_parser_method(section_options)\n\n    def _deprecated_config_handler(self, func, msg, warning_class):\n        \"\"\"this function will wrap around parameters that are deprecated\n\n        :param msg: deprecation message\n        :param warning_class: class of warning exception to be raised\n        :param func: function to be wrapped around\n        \"\"\"\n\n        @wraps(func)\n        def config_handler(*args, **kwargs):\n            warnings.warn(msg, warning_class)\n            return func(*args, **kwargs)\n\n        return config_handler\n\n\nclass ConfigMetadataHandler(ConfigHandler[\"DistributionMetadata\"]):\n\n    section_prefix = 'metadata'\n\n    aliases = {\n        'home_page': 'url',\n        'summary': 'description',\n        'classifier': 'classifiers',\n        'platform': 'platforms',\n    }\n\n    strict_mode = False\n    \"\"\"We need to keep it loose, to be partially compatible with\n    `pbr` and `d2to1` packages which also uses `metadata` section.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        target_obj: \"DistributionMetadata\",\n        options: AllCommandOptions,\n        ignore_option_errors: bool,\n        ensure_discovered: expand.EnsurePackagesDiscovered,\n        package_dir: Optional[dict] = None,\n        root_dir: _Path = os.curdir\n    ):\n        super().__init__(target_obj, options, ignore_option_errors, ensure_discovered)\n        self.package_dir = package_dir\n        self.root_dir = root_dir\n\n    @property\n    def parsers(self):\n        \"\"\"Metadata item name to parser function mapping.\"\"\"\n        parse_list = self._parse_list\n        parse_file = partial(self._parse_file, root_dir=self.root_dir)\n        parse_dict = self._parse_dict\n        exclude_files_parser = self._exclude_files_parser\n\n        return {\n            'platforms': parse_list,\n            'keywords': parse_list,\n            'provides': parse_list,\n            'requires': self._deprecated_config_handler(\n                parse_list,\n                \"The requires parameter is deprecated, please use \"\n                \"install_requires for runtime dependencies.\",\n                SetuptoolsDeprecationWarning,\n            ),\n            'obsoletes': parse_list,\n            'classifiers': self._get_parser_compound(parse_file, parse_list),\n            'license': exclude_files_parser('license'),\n            'license_file': self._deprecated_config_handler(\n                exclude_files_parser('license_file'),\n                \"The license_file parameter is deprecated, \"\n                \"use license_files instead.\",\n                SetuptoolsDeprecationWarning,\n            ),\n            'license_files': parse_list,\n            'description': parse_file,\n            'long_description': parse_file,\n            'version': self._parse_version,\n            'project_urls': parse_dict,\n        }\n\n    def _parse_version(self, value):\n        \"\"\"Parses `version` option value.\n\n        :param value:\n        :rtype: str\n\n        \"\"\"\n        version = self._parse_file(value, self.root_dir)\n\n        if version != value:\n            version = version.strip()\n            # Be strict about versions loaded from file because it's easy to\n            # accidentally include newlines and other unintended content\n            try:\n                Version(version)\n            except InvalidVersion:\n                tmpl = (\n                    'Version loaded from {value} does not '\n                    'comply with PEP 440: {version}'\n                )\n                raise DistutilsOptionError(tmpl.format(**locals()))\n\n            return version\n\n        return expand.version(self._parse_attr(value, self.package_dir, self.root_dir))\n\n\nclass ConfigOptionsHandler(ConfigHandler[\"Distribution\"]):\n\n    section_prefix = 'options'\n\n    def __init__(\n        self,\n        target_obj: \"Distribution\",\n        options: AllCommandOptions,\n        ignore_option_errors: bool,\n        ensure_discovered: expand.EnsurePackagesDiscovered,\n    ):\n        super().__init__(target_obj, options, ignore_option_errors, ensure_discovered)\n        self.root_dir = target_obj.src_root\n        self.package_dir: Dict[str, str] = {}  # To be filled by `find_packages`\n\n    @classmethod\n    def _parse_list_semicolon(cls, value):\n        return cls._parse_list(value, separator=';')\n\n    def _parse_file_in_root(self, value):\n        return self._parse_file(value, root_dir=self.root_dir)\n\n    def _parse_requirements_list(self, label: str, value: str):\n        # Parse a requirements list, either by reading in a `file:`, or a list.\n        parsed = self._parse_list_semicolon(self._parse_file_in_root(value))\n        _warn_accidental_env_marker_misconfig(label, value, parsed)\n        # Filter it to only include lines that are not comments. `parse_list`\n        # will have stripped each line and filtered out empties.\n        return [line for line in parsed if not line.startswith(\"#\")]\n\n    @property\n    def parsers(self):\n        \"\"\"Metadata item name to parser function mapping.\"\"\"\n        parse_list = self._parse_list\n        parse_bool = self._parse_bool\n        parse_dict = self._parse_dict\n        parse_cmdclass = self._parse_cmdclass\n\n        return {\n            'zip_safe': parse_bool,\n            'include_package_data': parse_bool,\n            'package_dir': parse_dict,\n            'scripts': parse_list,\n            'eager_resources': parse_list,\n            'dependency_links': parse_list,\n            'namespace_packages': self._deprecated_config_handler(\n                parse_list,\n                \"The namespace_packages parameter is deprecated, \"\n                \"consider using implicit namespaces instead (PEP 420).\",\n                SetuptoolsDeprecationWarning,\n            ),\n            'install_requires': partial(\n                self._parse_requirements_list, \"install_requires\"\n            ),\n            'setup_requires': self._parse_list_semicolon,\n            'tests_require': self._parse_list_semicolon,\n            'packages': self._parse_packages,\n            'entry_points': self._parse_file_in_root,\n            'py_modules': parse_list,\n            'python_requires': SpecifierSet,\n            'cmdclass': parse_cmdclass,\n        }\n\n    def _parse_cmdclass(self, value):\n        package_dir = self.ensure_discovered.package_dir\n        return expand.cmdclass(self._parse_dict(value), package_dir, self.root_dir)\n\n    def _parse_packages(self, value):\n        \"\"\"Parses `packages` option value.\n\n        :param value:\n        :rtype: list\n        \"\"\"\n        find_directives = ['find:', 'find_namespace:']\n        trimmed_value = value.strip()\n\n        if trimmed_value not in find_directives:\n            return self._parse_list(value)\n\n        # Read function arguments from a dedicated section.\n        find_kwargs = self.parse_section_packages__find(\n            self.sections.get('packages.find', {})\n        )\n\n        find_kwargs.update(\n            namespaces=(trimmed_value == find_directives[1]),\n            root_dir=self.root_dir,\n            fill_package_dir=self.package_dir,\n        )\n\n        return expand.find_packages(**find_kwargs)\n\n    def parse_section_packages__find(self, section_options):\n        \"\"\"Parses `packages.find` configuration file section.\n\n        To be used in conjunction with _parse_packages().\n\n        :param dict section_options:\n        \"\"\"\n        section_data = self._parse_section_to_dict(section_options, self._parse_list)\n\n        valid_keys = ['where', 'include', 'exclude']\n\n        find_kwargs = dict(\n            [(k, v) for k, v in section_data.items() if k in valid_keys and v]\n        )\n\n        where = find_kwargs.get('where')\n        if where is not None:\n            find_kwargs['where'] = where[0]  # cast list to single val\n\n        return find_kwargs\n\n    def parse_section_entry_points(self, section_options):\n        \"\"\"Parses `entry_points` configuration file section.\n\n        :param dict section_options:\n        \"\"\"\n        parsed = self._parse_section_to_dict(section_options, self._parse_list)\n        self['entry_points'] = parsed\n\n    def _parse_package_data(self, section_options):\n        package_data = self._parse_section_to_dict(section_options, self._parse_list)\n        return expand.canonic_package_data(package_data)\n\n    def parse_section_package_data(self, section_options):\n        \"\"\"Parses `package_data` configuration file section.\n\n        :param dict section_options:\n        \"\"\"\n        self['package_data'] = self._parse_package_data(section_options)\n\n    def parse_section_exclude_package_data(self, section_options):\n        \"\"\"Parses `exclude_package_data` configuration file section.\n\n        :param dict section_options:\n        \"\"\"\n        self['exclude_package_data'] = self._parse_package_data(section_options)\n\n    def parse_section_extras_require(self, section_options):\n        \"\"\"Parses `extras_require` configuration file section.\n\n        :param dict section_options:\n        \"\"\"\n        parsed = self._parse_section_to_dict_with_key(\n            section_options,\n            lambda k, v: self._parse_requirements_list(f\"extras_require[{k}]\", v)\n        )\n\n        self['extras_require'] = parsed\n\n    def parse_section_data_files(self, section_options):\n        \"\"\"Parses `data_files` configuration file section.\n\n        :param dict section_options:\n        \"\"\"\n        parsed = self._parse_section_to_dict(section_options, self._parse_list)\n        self['data_files'] = expand.canonic_data_files(parsed, self.root_dir)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/dep_util.py",
    "content": "from distutils.dep_util import newer_group\n\n\n# yes, this is was almost entirely copy-pasted from\n# 'newer_pairwise()', this is just another convenience\n# function.\ndef newer_pairwise_group(sources_groups, targets):\n    \"\"\"Walk both arguments in parallel, testing if each source group is newer\n    than its corresponding target. Returns a pair of lists (sources_groups,\n    targets) where sources is newer than target, according to the semantics\n    of 'newer_group()'.\n    \"\"\"\n    if len(sources_groups) != len(targets):\n        raise ValueError(\n            \"'sources_group' and 'targets' must be the same length\")\n\n    # build a pair of lists (sources_groups, targets) where source is newer\n    n_sources = []\n    n_targets = []\n    for i in range(len(sources_groups)):\n        if newer_group(sources_groups[i], targets[i]):\n            n_sources.append(sources_groups[i])\n            n_targets.append(targets[i])\n\n    return n_sources, n_targets\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/depends.py",
    "content": "import sys\nimport marshal\nimport contextlib\nimport dis\n\nfrom setuptools.extern.packaging import version\n\nfrom ._imp import find_module, PY_COMPILED, PY_FROZEN, PY_SOURCE\nfrom . import _imp\n\n\n__all__ = [\n    'Require', 'find_module', 'get_module_constant', 'extract_constant'\n]\n\n\nclass Require:\n    \"\"\"A prerequisite to building or installing a distribution\"\"\"\n\n    def __init__(\n            self, name, requested_version, module, homepage='',\n            attribute=None, format=None):\n\n        if format is None and requested_version is not None:\n            format = version.Version\n\n        if format is not None:\n            requested_version = format(requested_version)\n            if attribute is None:\n                attribute = '__version__'\n\n        self.__dict__.update(locals())\n        del self.self\n\n    def full_name(self):\n        \"\"\"Return full package/distribution name, w/version\"\"\"\n        if self.requested_version is not None:\n            return '%s-%s' % (self.name, self.requested_version)\n        return self.name\n\n    def version_ok(self, version):\n        \"\"\"Is 'version' sufficiently up-to-date?\"\"\"\n        return self.attribute is None or self.format is None or \\\n            str(version) != \"unknown\" and self.format(version) >= self.requested_version\n\n    def get_version(self, paths=None, default=\"unknown\"):\n        \"\"\"Get version number of installed module, 'None', or 'default'\n\n        Search 'paths' for module.  If not found, return 'None'.  If found,\n        return the extracted version attribute, or 'default' if no version\n        attribute was specified, or the value cannot be determined without\n        importing the module.  The version is formatted according to the\n        requirement's version format (if any), unless it is 'None' or the\n        supplied 'default'.\n        \"\"\"\n\n        if self.attribute is None:\n            try:\n                f, p, i = find_module(self.module, paths)\n                if f:\n                    f.close()\n                return default\n            except ImportError:\n                return None\n\n        v = get_module_constant(self.module, self.attribute, default, paths)\n\n        if v is not None and v is not default and self.format is not None:\n            return self.format(v)\n\n        return v\n\n    def is_present(self, paths=None):\n        \"\"\"Return true if dependency is present on 'paths'\"\"\"\n        return self.get_version(paths) is not None\n\n    def is_current(self, paths=None):\n        \"\"\"Return true if dependency is present and up-to-date on 'paths'\"\"\"\n        version = self.get_version(paths)\n        if version is None:\n            return False\n        return self.version_ok(str(version))\n\n\ndef maybe_close(f):\n    @contextlib.contextmanager\n    def empty():\n        yield\n        return\n    if not f:\n        return empty()\n\n    return contextlib.closing(f)\n\n\ndef get_module_constant(module, symbol, default=-1, paths=None):\n    \"\"\"Find 'module' by searching 'paths', and extract 'symbol'\n\n    Return 'None' if 'module' does not exist on 'paths', or it does not define\n    'symbol'.  If the module defines 'symbol' as a constant, return the\n    constant.  Otherwise, return 'default'.\"\"\"\n\n    try:\n        f, path, (suffix, mode, kind) = info = find_module(module, paths)\n    except ImportError:\n        # Module doesn't exist\n        return None\n\n    with maybe_close(f):\n        if kind == PY_COMPILED:\n            f.read(8)  # skip magic & date\n            code = marshal.load(f)\n        elif kind == PY_FROZEN:\n            code = _imp.get_frozen_object(module, paths)\n        elif kind == PY_SOURCE:\n            code = compile(f.read(), path, 'exec')\n        else:\n            # Not something we can parse; we'll have to import it.  :(\n            imported = _imp.get_module(module, paths, info)\n            return getattr(imported, symbol, None)\n\n    return extract_constant(code, symbol, default)\n\n\ndef extract_constant(code, symbol, default=-1):\n    \"\"\"Extract the constant value of 'symbol' from 'code'\n\n    If the name 'symbol' is bound to a constant value by the Python code\n    object 'code', return that value.  If 'symbol' is bound to an expression,\n    return 'default'.  Otherwise, return 'None'.\n\n    Return value is based on the first assignment to 'symbol'.  'symbol' must\n    be a global, or at least a non-\"fast\" local in the code block.  That is,\n    only 'STORE_NAME' and 'STORE_GLOBAL' opcodes are checked, and 'symbol'\n    must be present in 'code.co_names'.\n    \"\"\"\n    if symbol not in code.co_names:\n        # name's not there, can't possibly be an assignment\n        return None\n\n    name_idx = list(code.co_names).index(symbol)\n\n    STORE_NAME = 90\n    STORE_GLOBAL = 97\n    LOAD_CONST = 100\n\n    const = default\n\n    for byte_code in dis.Bytecode(code):\n        op = byte_code.opcode\n        arg = byte_code.arg\n\n        if op == LOAD_CONST:\n            const = code.co_consts[arg]\n        elif arg == name_idx and (op == STORE_NAME or op == STORE_GLOBAL):\n            return const\n        else:\n            const = default\n\n\ndef _update_globals():\n    \"\"\"\n    Patch the globals to remove the objects not available on some platforms.\n\n    XXX it'd be better to test assertions about bytecode instead.\n    \"\"\"\n\n    if not sys.platform.startswith('java') and sys.platform != 'cli':\n        return\n    incompatible = 'extract_constant', 'get_module_constant'\n    for name in incompatible:\n        del globals()[name]\n        __all__.remove(name)\n\n\n_update_globals()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/discovery.py",
    "content": "\"\"\"Automatic discovery of Python modules and packages (for inclusion in the\ndistribution) and other config values.\n\nFor the purposes of this module, the following nomenclature is used:\n\n- \"src-layout\": a directory representing a Python project that contains a \"src\"\n  folder. Everything under the \"src\" folder is meant to be included in the\n  distribution when packaging the project. Example::\n\n    .\n    ├── tox.ini\n    ├── pyproject.toml\n    └── src/\n        └── mypkg/\n            ├── __init__.py\n            ├── mymodule.py\n            └── my_data_file.txt\n\n- \"flat-layout\": a Python project that does not use \"src-layout\" but instead\n  have a directory under the project root for each package::\n\n    .\n    ├── tox.ini\n    ├── pyproject.toml\n    └── mypkg/\n        ├── __init__.py\n        ├── mymodule.py\n        └── my_data_file.txt\n\n- \"single-module\": a project that contains a single Python script direct under\n  the project root (no directory used)::\n\n    .\n    ├── tox.ini\n    ├── pyproject.toml\n    └── mymodule.py\n\n\"\"\"\n\nimport itertools\nimport os\nfrom fnmatch import fnmatchcase\nfrom glob import glob\nfrom pathlib import Path\nfrom typing import (\n    TYPE_CHECKING,\n    Callable,\n    Dict,\n    Iterable,\n    Iterator,\n    List,\n    Mapping,\n    Optional,\n    Tuple,\n    Union\n)\n\nimport _distutils_hack.override  # noqa: F401\n\nfrom distutils import log\nfrom distutils.util import convert_path\n\n_Path = Union[str, os.PathLike]\n_Filter = Callable[[str], bool]\nStrIter = Iterator[str]\n\nchain_iter = itertools.chain.from_iterable\n\nif TYPE_CHECKING:\n    from setuptools import Distribution  # noqa\n\n\ndef _valid_name(path: _Path) -> bool:\n    # Ignore invalid names that cannot be imported directly\n    return os.path.basename(path).isidentifier()\n\n\nclass _Finder:\n    \"\"\"Base class that exposes functionality for module/package finders\"\"\"\n\n    ALWAYS_EXCLUDE: Tuple[str, ...] = ()\n    DEFAULT_EXCLUDE: Tuple[str, ...] = ()\n\n    @classmethod\n    def find(\n        cls,\n        where: _Path = '.',\n        exclude: Iterable[str] = (),\n        include: Iterable[str] = ('*',)\n    ) -> List[str]:\n        \"\"\"Return a list of all Python items (packages or modules, depending on\n        the finder implementation) found within directory 'where'.\n\n        'where' is the root directory which will be searched.\n        It should be supplied as a \"cross-platform\" (i.e. URL-style) path;\n        it will be converted to the appropriate local path syntax.\n\n        'exclude' is a sequence of names to exclude; '*' can be used\n        as a wildcard in the names.\n        When finding packages, 'foo.*' will exclude all subpackages of 'foo'\n        (but not 'foo' itself).\n\n        'include' is a sequence of names to include.\n        If it's specified, only the named items will be included.\n        If it's not specified, all found items will be included.\n        'include' can contain shell style wildcard patterns just like\n        'exclude'.\n        \"\"\"\n\n        exclude = exclude or cls.DEFAULT_EXCLUDE\n        return list(\n            cls._find_iter(\n                convert_path(str(where)),\n                cls._build_filter(*cls.ALWAYS_EXCLUDE, *exclude),\n                cls._build_filter(*include),\n            )\n        )\n\n    @classmethod\n    def _find_iter(cls, where: _Path, exclude: _Filter, include: _Filter) -> StrIter:\n        raise NotImplementedError\n\n    @staticmethod\n    def _build_filter(*patterns: str) -> _Filter:\n        \"\"\"\n        Given a list of patterns, return a callable that will be true only if\n        the input matches at least one of the patterns.\n        \"\"\"\n        return lambda name: any(fnmatchcase(name, pat) for pat in patterns)\n\n\nclass PackageFinder(_Finder):\n    \"\"\"\n    Generate a list of all Python packages found within a directory\n    \"\"\"\n\n    ALWAYS_EXCLUDE = (\"ez_setup\", \"*__pycache__\")\n\n    @classmethod\n    def _find_iter(cls, where: _Path, exclude: _Filter, include: _Filter) -> StrIter:\n        \"\"\"\n        All the packages found in 'where' that pass the 'include' filter, but\n        not the 'exclude' filter.\n        \"\"\"\n        for root, dirs, files in os.walk(str(where), followlinks=True):\n            # Copy dirs to iterate over it, then empty dirs.\n            all_dirs = dirs[:]\n            dirs[:] = []\n\n            for dir in all_dirs:\n                full_path = os.path.join(root, dir)\n                rel_path = os.path.relpath(full_path, where)\n                package = rel_path.replace(os.path.sep, '.')\n\n                # Skip directory trees that are not valid packages\n                if '.' in dir or not cls._looks_like_package(full_path, package):\n                    continue\n\n                # Should this package be included?\n                if include(package) and not exclude(package):\n                    yield package\n\n                # Keep searching subdirectories, as there may be more packages\n                # down there, even if the parent was excluded.\n                dirs.append(dir)\n\n    @staticmethod\n    def _looks_like_package(path: _Path, _package_name: str) -> bool:\n        \"\"\"Does a directory look like a package?\"\"\"\n        return os.path.isfile(os.path.join(path, '__init__.py'))\n\n\nclass PEP420PackageFinder(PackageFinder):\n    @staticmethod\n    def _looks_like_package(_path: _Path, _package_name: str) -> bool:\n        return True\n\n\nclass ModuleFinder(_Finder):\n    \"\"\"Find isolated Python modules.\n    This function will **not** recurse subdirectories.\n    \"\"\"\n\n    @classmethod\n    def _find_iter(cls, where: _Path, exclude: _Filter, include: _Filter) -> StrIter:\n        for file in glob(os.path.join(where, \"*.py\")):\n            module, _ext = os.path.splitext(os.path.basename(file))\n\n            if not cls._looks_like_module(module):\n                continue\n\n            if include(module) and not exclude(module):\n                yield module\n\n    _looks_like_module = staticmethod(_valid_name)\n\n\n# We have to be extra careful in the case of flat layout to not include files\n# and directories not meant for distribution (e.g. tool-related)\n\n\nclass FlatLayoutPackageFinder(PEP420PackageFinder):\n    _EXCLUDE = (\n        \"ci\",\n        \"bin\",\n        \"doc\",\n        \"docs\",\n        \"documentation\",\n        \"manpages\",\n        \"news\",\n        \"changelog\",\n        \"test\",\n        \"tests\",\n        \"unit_test\",\n        \"unit_tests\",\n        \"example\",\n        \"examples\",\n        \"scripts\",\n        \"tools\",\n        \"util\",\n        \"utils\",\n        \"python\",\n        \"build\",\n        \"dist\",\n        \"venv\",\n        \"env\",\n        \"requirements\",\n        # ---- Task runners / Build tools ----\n        \"tasks\",  # invoke\n        \"fabfile\",  # fabric\n        \"site_scons\",  # SCons\n        # ---- Other tools ----\n        \"benchmark\",\n        \"benchmarks\",\n        \"exercise\",\n        \"exercises\",\n        # ---- Hidden directories/Private packages ----\n        \"[._]*\",\n    )\n\n    DEFAULT_EXCLUDE = tuple(chain_iter((p, f\"{p}.*\") for p in _EXCLUDE))\n    \"\"\"Reserved package names\"\"\"\n\n    @staticmethod\n    def _looks_like_package(_path: _Path, package_name: str) -> bool:\n        names = package_name.split('.')\n        # Consider PEP 561\n        root_pkg_is_valid = names[0].isidentifier() or names[0].endswith(\"-stubs\")\n        return root_pkg_is_valid and all(name.isidentifier() for name in names[1:])\n\n\nclass FlatLayoutModuleFinder(ModuleFinder):\n    DEFAULT_EXCLUDE = (\n        \"setup\",\n        \"conftest\",\n        \"test\",\n        \"tests\",\n        \"example\",\n        \"examples\",\n        \"build\",\n        # ---- Task runners ----\n        \"toxfile\",\n        \"noxfile\",\n        \"pavement\",\n        \"dodo\",\n        \"tasks\",\n        \"fabfile\",\n        # ---- Other tools ----\n        \"[Ss][Cc]onstruct\",  # SCons\n        \"conanfile\",  # Connan: C/C++ build tool\n        \"manage\",  # Django\n        \"benchmark\",\n        \"benchmarks\",\n        \"exercise\",\n        \"exercises\",\n        # ---- Hidden files/Private modules ----\n        \"[._]*\",\n    )\n    \"\"\"Reserved top-level module names\"\"\"\n\n\ndef _find_packages_within(root_pkg: str, pkg_dir: _Path) -> List[str]:\n    nested = PEP420PackageFinder.find(pkg_dir)\n    return [root_pkg] + [\".\".join((root_pkg, n)) for n in nested]\n\n\nclass ConfigDiscovery:\n    \"\"\"Fill-in metadata and options that can be automatically derived\n    (from other metadata/options, the file system or conventions)\n    \"\"\"\n\n    def __init__(self, distribution: \"Distribution\"):\n        self.dist = distribution\n        self._called = False\n        self._disabled = False\n        self._skip_ext_modules = False\n\n    def _disable(self):\n        \"\"\"Internal API to disable automatic discovery\"\"\"\n        self._disabled = True\n\n    def _ignore_ext_modules(self):\n        \"\"\"Internal API to disregard ext_modules.\n\n        Normally auto-discovery would not be triggered if ``ext_modules`` are set\n        (this is done for backward compatibility with existing packages relying on\n        ``setup.py`` or ``setup.cfg``). However, ``setuptools`` can call this function\n        to ignore given ``ext_modules`` and proceed with the auto-discovery if\n        ``packages`` and ``py_modules`` are not given (e.g. when using pyproject.toml\n        metadata).\n        \"\"\"\n        self._skip_ext_modules = True\n\n    @property\n    def _root_dir(self) -> _Path:\n        # The best is to wait until `src_root` is set in dist, before using _root_dir.\n        return self.dist.src_root or os.curdir\n\n    @property\n    def _package_dir(self) -> Dict[str, str]:\n        if self.dist.package_dir is None:\n            return {}\n        return self.dist.package_dir\n\n    def __call__(self, force=False, name=True, ignore_ext_modules=False):\n        \"\"\"Automatically discover missing configuration fields\n        and modifies the given ``distribution`` object in-place.\n\n        Note that by default this will only have an effect the first time the\n        ``ConfigDiscovery`` object is called.\n\n        To repeatedly invoke automatic discovery (e.g. when the project\n        directory changes), please use ``force=True`` (or create a new\n        ``ConfigDiscovery`` instance).\n        \"\"\"\n        if force is False and (self._called or self._disabled):\n            # Avoid overhead of multiple calls\n            return\n\n        self._analyse_package_layout(ignore_ext_modules)\n        if name:\n            self.analyse_name()  # depends on ``packages`` and ``py_modules``\n\n        self._called = True\n\n    def _explicitly_specified(self, ignore_ext_modules: bool) -> bool:\n        \"\"\"``True`` if the user has specified some form of package/module listing\"\"\"\n        ignore_ext_modules = ignore_ext_modules or self._skip_ext_modules\n        ext_modules = not (self.dist.ext_modules is None or ignore_ext_modules)\n        return (\n            self.dist.packages is not None\n            or self.dist.py_modules is not None\n            or ext_modules\n            or hasattr(self.dist, \"configuration\") and self.dist.configuration\n            # ^ Some projects use numpy.distutils.misc_util.Configuration\n        )\n\n    def _analyse_package_layout(self, ignore_ext_modules: bool) -> bool:\n        if self._explicitly_specified(ignore_ext_modules):\n            # For backward compatibility, just try to find modules/packages\n            # when nothing is given\n            return True\n\n        log.debug(\n            \"No `packages` or `py_modules` configuration, performing \"\n            \"automatic discovery.\"\n        )\n\n        return (\n            self._analyse_explicit_layout()\n            or self._analyse_src_layout()\n            # flat-layout is the trickiest for discovery so it should be last\n            or self._analyse_flat_layout()\n        )\n\n    def _analyse_explicit_layout(self) -> bool:\n        \"\"\"The user can explicitly give a package layout via ``package_dir``\"\"\"\n        package_dir = self._package_dir.copy()  # don't modify directly\n        package_dir.pop(\"\", None)  # This falls under the \"src-layout\" umbrella\n        root_dir = self._root_dir\n\n        if not package_dir:\n            return False\n\n        log.debug(f\"`explicit-layout` detected -- analysing {package_dir}\")\n        pkgs = chain_iter(\n            _find_packages_within(pkg, os.path.join(root_dir, parent_dir))\n            for pkg, parent_dir in package_dir.items()\n        )\n        self.dist.packages = list(pkgs)\n        log.debug(f\"discovered packages -- {self.dist.packages}\")\n        return True\n\n    def _analyse_src_layout(self) -> bool:\n        \"\"\"Try to find all packages or modules under the ``src`` directory\n        (or anything pointed by ``package_dir[\"\"]``).\n\n        The \"src-layout\" is relatively safe for automatic discovery.\n        We assume that everything within is meant to be included in the\n        distribution.\n\n        If ``package_dir[\"\"]`` is not given, but the ``src`` directory exists,\n        this function will set ``package_dir[\"\"] = \"src\"``.\n        \"\"\"\n        package_dir = self._package_dir\n        src_dir = os.path.join(self._root_dir, package_dir.get(\"\", \"src\"))\n        if not os.path.isdir(src_dir):\n            return False\n\n        log.debug(f\"`src-layout` detected -- analysing {src_dir}\")\n        package_dir.setdefault(\"\", os.path.basename(src_dir))\n        self.dist.package_dir = package_dir  # persist eventual modifications\n        self.dist.packages = PEP420PackageFinder.find(src_dir)\n        self.dist.py_modules = ModuleFinder.find(src_dir)\n        log.debug(f\"discovered packages -- {self.dist.packages}\")\n        log.debug(f\"discovered py_modules -- {self.dist.py_modules}\")\n        return True\n\n    def _analyse_flat_layout(self) -> bool:\n        \"\"\"Try to find all packages and modules under the project root.\n\n        Since the ``flat-layout`` is more dangerous in terms of accidentally including\n        extra files/directories, this function is more conservative and will raise an\n        error if multiple packages or modules are found.\n\n        This assumes that multi-package dists are uncommon and refuse to support that\n        use case in order to be able to prevent unintended errors.\n        \"\"\"\n        log.debug(f\"`flat-layout` detected -- analysing {self._root_dir}\")\n        return self._analyse_flat_packages() or self._analyse_flat_modules()\n\n    def _analyse_flat_packages(self) -> bool:\n        self.dist.packages = FlatLayoutPackageFinder.find(self._root_dir)\n        top_level = remove_nested_packages(remove_stubs(self.dist.packages))\n        log.debug(f\"discovered packages -- {self.dist.packages}\")\n        self._ensure_no_accidental_inclusion(top_level, \"packages\")\n        return bool(top_level)\n\n    def _analyse_flat_modules(self) -> bool:\n        self.dist.py_modules = FlatLayoutModuleFinder.find(self._root_dir)\n        log.debug(f\"discovered py_modules -- {self.dist.py_modules}\")\n        self._ensure_no_accidental_inclusion(self.dist.py_modules, \"modules\")\n        return bool(self.dist.py_modules)\n\n    def _ensure_no_accidental_inclusion(self, detected: List[str], kind: str):\n        if len(detected) > 1:\n            from inspect import cleandoc\n\n            from setuptools.errors import PackageDiscoveryError\n\n            msg = f\"\"\"Multiple top-level {kind} discovered in a flat-layout: {detected}.\n\n            To avoid accidental inclusion of unwanted files or directories,\n            setuptools will not proceed with this build.\n\n            If you are trying to create a single distribution with multiple {kind}\n            on purpose, you should not rely on automatic discovery.\n            Instead, consider the following options:\n\n            1. set up custom discovery (`find` directive with `include` or `exclude`)\n            2. use a `src-layout`\n            3. explicitly set `py_modules` or `packages` with a list of names\n\n            To find more information, look for \"package discovery\" on setuptools docs.\n            \"\"\"\n            raise PackageDiscoveryError(cleandoc(msg))\n\n    def analyse_name(self):\n        \"\"\"The packages/modules are the essential contribution of the author.\n        Therefore the name of the distribution can be derived from them.\n        \"\"\"\n        if self.dist.metadata.name or self.dist.name:\n            # get_name() is not reliable (can return \"UNKNOWN\")\n            return None\n\n        log.debug(\"No `name` configuration, performing automatic discovery\")\n\n        name = (\n            self._find_name_single_package_or_module()\n            or self._find_name_from_packages()\n        )\n        if name:\n            self.dist.metadata.name = name\n\n    def _find_name_single_package_or_module(self) -> Optional[str]:\n        \"\"\"Exactly one module or package\"\"\"\n        for field in ('packages', 'py_modules'):\n            items = getattr(self.dist, field, None) or []\n            if items and len(items) == 1:\n                log.debug(f\"Single module/package detected, name: {items[0]}\")\n                return items[0]\n\n        return None\n\n    def _find_name_from_packages(self) -> Optional[str]:\n        \"\"\"Try to find the root package that is not a PEP 420 namespace\"\"\"\n        if not self.dist.packages:\n            return None\n\n        packages = remove_stubs(sorted(self.dist.packages, key=len))\n        package_dir = self.dist.package_dir or {}\n\n        parent_pkg = find_parent_package(packages, package_dir, self._root_dir)\n        if parent_pkg:\n            log.debug(f\"Common parent package detected, name: {parent_pkg}\")\n            return parent_pkg\n\n        log.warn(\"No parent package detected, impossible to derive `name`\")\n        return None\n\n\ndef remove_nested_packages(packages: List[str]) -> List[str]:\n    \"\"\"Remove nested packages from a list of packages.\n\n    >>> remove_nested_packages([\"a\", \"a.b1\", \"a.b2\", \"a.b1.c1\"])\n    ['a']\n    >>> remove_nested_packages([\"a\", \"b\", \"c.d\", \"c.d.e.f\", \"g.h\", \"a.a1\"])\n    ['a', 'b', 'c.d', 'g.h']\n    \"\"\"\n    pkgs = sorted(packages, key=len)\n    top_level = pkgs[:]\n    size = len(pkgs)\n    for i, name in enumerate(reversed(pkgs)):\n        if any(name.startswith(f\"{other}.\") for other in top_level):\n            top_level.pop(size - i - 1)\n\n    return top_level\n\n\ndef remove_stubs(packages: List[str]) -> List[str]:\n    \"\"\"Remove type stubs (:pep:`561`) from a list of packages.\n\n    >>> remove_stubs([\"a\", \"a.b\", \"a-stubs\", \"a-stubs.b.c\", \"b\", \"c-stubs\"])\n    ['a', 'a.b', 'b']\n    \"\"\"\n    return [pkg for pkg in packages if not pkg.split(\".\")[0].endswith(\"-stubs\")]\n\n\ndef find_parent_package(\n    packages: List[str], package_dir: Mapping[str, str], root_dir: _Path\n) -> Optional[str]:\n    \"\"\"Find the parent package that is not a namespace.\"\"\"\n    packages = sorted(packages, key=len)\n    common_ancestors = []\n    for i, name in enumerate(packages):\n        if not all(n.startswith(f\"{name}.\") for n in packages[i+1:]):\n            # Since packages are sorted by length, this condition is able\n            # to find a list of all common ancestors.\n            # When there is divergence (e.g. multiple root packages)\n            # the list will be empty\n            break\n        common_ancestors.append(name)\n\n    for name in common_ancestors:\n        pkg_path = find_package_path(name, package_dir, root_dir)\n        init = os.path.join(pkg_path, \"__init__.py\")\n        if os.path.isfile(init):\n            return name\n\n    return None\n\n\ndef find_package_path(\n    name: str, package_dir: Mapping[str, str], root_dir: _Path\n) -> str:\n    \"\"\"Given a package name, return the path where it should be found on\n    disk, considering the ``package_dir`` option.\n\n    >>> path = find_package_path(\"my.pkg\", {\"\": \"root/is/nested\"}, \".\")\n    >>> path.replace(os.sep, \"/\")\n    './root/is/nested/my/pkg'\n\n    >>> path = find_package_path(\"my.pkg\", {\"my\": \"root/is/nested\"}, \".\")\n    >>> path.replace(os.sep, \"/\")\n    './root/is/nested/pkg'\n\n    >>> path = find_package_path(\"my.pkg\", {\"my.pkg\": \"root/is/nested\"}, \".\")\n    >>> path.replace(os.sep, \"/\")\n    './root/is/nested'\n\n    >>> path = find_package_path(\"other.pkg\", {\"my.pkg\": \"root/is/nested\"}, \".\")\n    >>> path.replace(os.sep, \"/\")\n    './other/pkg'\n    \"\"\"\n    parts = name.split(\".\")\n    for i in range(len(parts), 0, -1):\n        # Look backwards, the most specific package_dir first\n        partial_name = \".\".join(parts[:i])\n        if partial_name in package_dir:\n            parent = package_dir[partial_name]\n            return os.path.join(root_dir, parent, *parts[i:])\n\n    parent = package_dir.get(\"\") or \"\"\n    return os.path.join(root_dir, *parent.split(\"/\"), *parts)\n\n\ndef construct_package_dir(packages: List[str], package_path: _Path) -> Dict[str, str]:\n    parent_pkgs = remove_nested_packages(packages)\n    prefix = Path(package_path).parts\n    return {pkg: \"/\".join([*prefix, *pkg.split(\".\")]) for pkg in parent_pkgs}\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/dist.py",
    "content": "# -*- coding: utf-8 -*-\n__all__ = ['Distribution']\n\nimport io\nimport sys\nimport re\nimport os\nimport warnings\nimport numbers\nimport distutils.log\nimport distutils.core\nimport distutils.cmd\nimport distutils.dist\nimport distutils.command\nfrom distutils.util import strtobool\nfrom distutils.debug import DEBUG\nfrom distutils.fancy_getopt import translate_longopt\nfrom glob import iglob\nimport itertools\nimport textwrap\nfrom typing import List, Optional, TYPE_CHECKING\nfrom pathlib import Path\n\nfrom collections import defaultdict\nfrom email import message_from_file\n\nfrom distutils.errors import DistutilsOptionError, DistutilsSetupError\nfrom distutils.util import rfc822_escape\n\nfrom setuptools.extern import packaging\nfrom setuptools.extern import ordered_set\nfrom setuptools.extern.more_itertools import unique_everseen, partition\n\nfrom ._importlib import metadata\n\nfrom . import SetuptoolsDeprecationWarning\n\nimport setuptools\nimport setuptools.command\nfrom setuptools import windows_support\nfrom setuptools.monkey import get_unpatched\nfrom setuptools.config import setupcfg, pyprojecttoml\nfrom setuptools.discovery import ConfigDiscovery\n\nimport pkg_resources\nfrom setuptools.extern.packaging import version\nfrom . import _reqs\nfrom . import _entry_points\n\nif TYPE_CHECKING:\n    from email.message import Message\n\n__import__('setuptools.extern.packaging.specifiers')\n__import__('setuptools.extern.packaging.version')\n\n\ndef _get_unpatched(cls):\n    warnings.warn(\"Do not call this function\", DistDeprecationWarning)\n    return get_unpatched(cls)\n\n\ndef get_metadata_version(self):\n    mv = getattr(self, 'metadata_version', None)\n    if mv is None:\n        mv = version.Version('2.1')\n        self.metadata_version = mv\n    return mv\n\n\ndef rfc822_unescape(content: str) -> str:\n    \"\"\"Reverse RFC-822 escaping by removing leading whitespaces from content.\"\"\"\n    lines = content.splitlines()\n    if len(lines) == 1:\n        return lines[0].lstrip()\n    return '\\n'.join((lines[0].lstrip(), textwrap.dedent('\\n'.join(lines[1:]))))\n\n\ndef _read_field_from_msg(msg: \"Message\", field: str) -> Optional[str]:\n    \"\"\"Read Message header field.\"\"\"\n    value = msg[field]\n    if value == 'UNKNOWN':\n        return None\n    return value\n\n\ndef _read_field_unescaped_from_msg(msg: \"Message\", field: str) -> Optional[str]:\n    \"\"\"Read Message header field and apply rfc822_unescape.\"\"\"\n    value = _read_field_from_msg(msg, field)\n    if value is None:\n        return value\n    return rfc822_unescape(value)\n\n\ndef _read_list_from_msg(msg: \"Message\", field: str) -> Optional[List[str]]:\n    \"\"\"Read Message header field and return all results as list.\"\"\"\n    values = msg.get_all(field, None)\n    if values == []:\n        return None\n    return values\n\n\ndef _read_payload_from_msg(msg: \"Message\") -> Optional[str]:\n    value = msg.get_payload().strip()\n    if value == 'UNKNOWN' or not value:\n        return None\n    return value\n\n\ndef read_pkg_file(self, file):\n    \"\"\"Reads the metadata values from a file object.\"\"\"\n    msg = message_from_file(file)\n\n    self.metadata_version = version.Version(msg['metadata-version'])\n    self.name = _read_field_from_msg(msg, 'name')\n    self.version = _read_field_from_msg(msg, 'version')\n    self.description = _read_field_from_msg(msg, 'summary')\n    # we are filling author only.\n    self.author = _read_field_from_msg(msg, 'author')\n    self.maintainer = None\n    self.author_email = _read_field_from_msg(msg, 'author-email')\n    self.maintainer_email = None\n    self.url = _read_field_from_msg(msg, 'home-page')\n    self.download_url = _read_field_from_msg(msg, 'download-url')\n    self.license = _read_field_unescaped_from_msg(msg, 'license')\n\n    self.long_description = _read_field_unescaped_from_msg(msg, 'description')\n    if (\n        self.long_description is None and\n        self.metadata_version >= version.Version('2.1')\n    ):\n        self.long_description = _read_payload_from_msg(msg)\n    self.description = _read_field_from_msg(msg, 'summary')\n\n    if 'keywords' in msg:\n        self.keywords = _read_field_from_msg(msg, 'keywords').split(',')\n\n    self.platforms = _read_list_from_msg(msg, 'platform')\n    self.classifiers = _read_list_from_msg(msg, 'classifier')\n\n    # PEP 314 - these fields only exist in 1.1\n    if self.metadata_version == version.Version('1.1'):\n        self.requires = _read_list_from_msg(msg, 'requires')\n        self.provides = _read_list_from_msg(msg, 'provides')\n        self.obsoletes = _read_list_from_msg(msg, 'obsoletes')\n    else:\n        self.requires = None\n        self.provides = None\n        self.obsoletes = None\n\n    self.license_files = _read_list_from_msg(msg, 'license-file')\n\n\ndef single_line(val):\n    \"\"\"\n    Quick and dirty validation for Summary pypa/setuptools#1390.\n    \"\"\"\n    if '\\n' in val:\n        # TODO: Replace with `raise ValueError(\"newlines not allowed\")`\n        # after reviewing #2893.\n        warnings.warn(\"newlines not allowed and will break in the future\")\n        val = val.strip().split('\\n')[0]\n    return val\n\n\n# Based on Python 3.5 version\ndef write_pkg_file(self, file):  # noqa: C901  # is too complex (14)  # FIXME\n    \"\"\"Write the PKG-INFO format data to a file object.\"\"\"\n    version = self.get_metadata_version()\n\n    def write_field(key, value):\n        file.write(\"%s: %s\\n\" % (key, value))\n\n    write_field('Metadata-Version', str(version))\n    write_field('Name', self.get_name())\n    write_field('Version', self.get_version())\n\n    summary = self.get_description()\n    if summary:\n        write_field('Summary', single_line(summary))\n\n    optional_fields = (\n        ('Home-page', 'url'),\n        ('Download-URL', 'download_url'),\n        ('Author', 'author'),\n        ('Author-email', 'author_email'),\n        ('Maintainer', 'maintainer'),\n        ('Maintainer-email', 'maintainer_email'),\n    )\n\n    for field, attr in optional_fields:\n        attr_val = getattr(self, attr, None)\n        if attr_val is not None:\n            write_field(field, attr_val)\n\n    license = self.get_license()\n    if license:\n        write_field('License', rfc822_escape(license))\n\n    for project_url in self.project_urls.items():\n        write_field('Project-URL', '%s, %s' % project_url)\n\n    keywords = ','.join(self.get_keywords())\n    if keywords:\n        write_field('Keywords', keywords)\n\n    platforms = self.get_platforms() or []\n    for platform in platforms:\n        write_field('Platform', platform)\n\n    self._write_list(file, 'Classifier', self.get_classifiers())\n\n    # PEP 314\n    self._write_list(file, 'Requires', self.get_requires())\n    self._write_list(file, 'Provides', self.get_provides())\n    self._write_list(file, 'Obsoletes', self.get_obsoletes())\n\n    # Setuptools specific for PEP 345\n    if hasattr(self, 'python_requires'):\n        write_field('Requires-Python', self.python_requires)\n\n    # PEP 566\n    if self.long_description_content_type:\n        write_field('Description-Content-Type', self.long_description_content_type)\n    if self.provides_extras:\n        for extra in self.provides_extras:\n            write_field('Provides-Extra', extra)\n\n    self._write_list(file, 'License-File', self.license_files or [])\n\n    long_description = self.get_long_description()\n    if long_description:\n        file.write(\"\\n%s\" % long_description)\n        if not long_description.endswith(\"\\n\"):\n            file.write(\"\\n\")\n\n\nsequence = tuple, list\n\n\ndef check_importable(dist, attr, value):\n    try:\n        ep = metadata.EntryPoint(value=value, name=None, group=None)\n        assert not ep.extras\n    except (TypeError, ValueError, AttributeError, AssertionError) as e:\n        raise DistutilsSetupError(\n            \"%r must be importable 'module:attrs' string (got %r)\" % (attr, value)\n        ) from e\n\n\ndef assert_string_list(dist, attr, value):\n    \"\"\"Verify that value is a string list\"\"\"\n    try:\n        # verify that value is a list or tuple to exclude unordered\n        # or single-use iterables\n        assert isinstance(value, (list, tuple))\n        # verify that elements of value are strings\n        assert ''.join(value) != value\n    except (TypeError, ValueError, AttributeError, AssertionError) as e:\n        raise DistutilsSetupError(\n            \"%r must be a list of strings (got %r)\" % (attr, value)\n        ) from e\n\n\ndef check_nsp(dist, attr, value):\n    \"\"\"Verify that namespace packages are valid\"\"\"\n    ns_packages = value\n    assert_string_list(dist, attr, ns_packages)\n    for nsp in ns_packages:\n        if not dist.has_contents_for(nsp):\n            raise DistutilsSetupError(\n                \"Distribution contains no modules or packages for \"\n                + \"namespace package %r\" % nsp\n            )\n        parent, sep, child = nsp.rpartition('.')\n        if parent and parent not in ns_packages:\n            distutils.log.warn(\n                \"WARNING: %r is declared as a package namespace, but %r\"\n                \" is not: please correct this in setup.py\",\n                nsp,\n                parent,\n            )\n        msg = (\n            \"The namespace_packages parameter is deprecated, \"\n            \"consider using implicit namespaces instead (PEP 420).\"\n        )\n        warnings.warn(msg, SetuptoolsDeprecationWarning)\n\n\ndef check_extras(dist, attr, value):\n    \"\"\"Verify that extras_require mapping is valid\"\"\"\n    try:\n        list(itertools.starmap(_check_extra, value.items()))\n    except (TypeError, ValueError, AttributeError) as e:\n        raise DistutilsSetupError(\n            \"'extras_require' must be a dictionary whose values are \"\n            \"strings or lists of strings containing valid project/version \"\n            \"requirement specifiers.\"\n        ) from e\n\n\ndef _check_extra(extra, reqs):\n    name, sep, marker = extra.partition(':')\n    if marker and pkg_resources.invalid_marker(marker):\n        raise DistutilsSetupError(\"Invalid environment marker: \" + marker)\n    list(_reqs.parse(reqs))\n\n\ndef assert_bool(dist, attr, value):\n    \"\"\"Verify that value is True, False, 0, or 1\"\"\"\n    if bool(value) != value:\n        tmpl = \"{attr!r} must be a boolean value (got {value!r})\"\n        raise DistutilsSetupError(tmpl.format(attr=attr, value=value))\n\n\ndef invalid_unless_false(dist, attr, value):\n    if not value:\n        warnings.warn(f\"{attr} is ignored.\", DistDeprecationWarning)\n        return\n    raise DistutilsSetupError(f\"{attr} is invalid.\")\n\n\ndef check_requirements(dist, attr, value):\n    \"\"\"Verify that install_requires is a valid requirements list\"\"\"\n    try:\n        list(_reqs.parse(value))\n        if isinstance(value, (dict, set)):\n            raise TypeError(\"Unordered types are not allowed\")\n    except (TypeError, ValueError) as error:\n        tmpl = (\n            \"{attr!r} must be a string or list of strings \"\n            \"containing valid project/version requirement specifiers; {error}\"\n        )\n        raise DistutilsSetupError(tmpl.format(attr=attr, error=error)) from error\n\n\ndef check_specifier(dist, attr, value):\n    \"\"\"Verify that value is a valid version specifier\"\"\"\n    try:\n        packaging.specifiers.SpecifierSet(value)\n    except (packaging.specifiers.InvalidSpecifier, AttributeError) as error:\n        tmpl = (\n            \"{attr!r} must be a string \" \"containing valid version specifiers; {error}\"\n        )\n        raise DistutilsSetupError(tmpl.format(attr=attr, error=error)) from error\n\n\ndef check_entry_points(dist, attr, value):\n    \"\"\"Verify that entry_points map is parseable\"\"\"\n    try:\n        _entry_points.load(value)\n    except Exception as e:\n        raise DistutilsSetupError(e) from e\n\n\ndef check_test_suite(dist, attr, value):\n    if not isinstance(value, str):\n        raise DistutilsSetupError(\"test_suite must be a string\")\n\n\ndef check_package_data(dist, attr, value):\n    \"\"\"Verify that value is a dictionary of package names to glob lists\"\"\"\n    if not isinstance(value, dict):\n        raise DistutilsSetupError(\n            \"{!r} must be a dictionary mapping package names to lists of \"\n            \"string wildcard patterns\".format(attr)\n        )\n    for k, v in value.items():\n        if not isinstance(k, str):\n            raise DistutilsSetupError(\n                \"keys of {!r} dict must be strings (got {!r})\".format(attr, k)\n            )\n        assert_string_list(dist, 'values of {!r} dict'.format(attr), v)\n\n\ndef check_packages(dist, attr, value):\n    for pkgname in value:\n        if not re.match(r'\\w+(\\.\\w+)*', pkgname):\n            distutils.log.warn(\n                \"WARNING: %r not a valid package name; please use only \"\n                \".-separated package names in setup.py\",\n                pkgname,\n            )\n\n\n_Distribution = get_unpatched(distutils.core.Distribution)\n\n\nclass Distribution(_Distribution):\n    \"\"\"Distribution with support for tests and package data\n\n    This is an enhanced version of 'distutils.dist.Distribution' that\n    effectively adds the following new optional keyword arguments to 'setup()':\n\n     'install_requires' -- a string or sequence of strings specifying project\n        versions that the distribution requires when installed, in the format\n        used by 'pkg_resources.require()'.  They will be installed\n        automatically when the package is installed.  If you wish to use\n        packages that are not available in PyPI, or want to give your users an\n        alternate download location, you can add a 'find_links' option to the\n        '[easy_install]' section of your project's 'setup.cfg' file, and then\n        setuptools will scan the listed web pages for links that satisfy the\n        requirements.\n\n     'extras_require' -- a dictionary mapping names of optional \"extras\" to the\n        additional requirement(s) that using those extras incurs. For example,\n        this::\n\n            extras_require = dict(reST = [\"docutils>=0.3\", \"reSTedit\"])\n\n        indicates that the distribution can optionally provide an extra\n        capability called \"reST\", but it can only be used if docutils and\n        reSTedit are installed.  If the user installs your package using\n        EasyInstall and requests one of your extras, the corresponding\n        additional requirements will be installed if needed.\n\n     'test_suite' -- the name of a test suite to run for the 'test' command.\n        If the user runs 'python setup.py test', the package will be installed,\n        and the named test suite will be run.  The format is the same as\n        would be used on a 'unittest.py' command line.  That is, it is the\n        dotted name of an object to import and call to generate a test suite.\n\n     'package_data' -- a dictionary mapping package names to lists of filenames\n        or globs to use to find data files contained in the named packages.\n        If the dictionary has filenames or globs listed under '\"\"' (the empty\n        string), those names will be searched for in every package, in addition\n        to any names for the specific package.  Data files found using these\n        names/globs will be installed along with the package, in the same\n        location as the package.  Note that globs are allowed to reference\n        the contents of non-package subdirectories, as long as you use '/' as\n        a path separator.  (Globs are automatically converted to\n        platform-specific paths at runtime.)\n\n    In addition to these new keywords, this class also has several new methods\n    for manipulating the distribution's contents.  For example, the 'include()'\n    and 'exclude()' methods can be thought of as in-place add and subtract\n    commands that add or remove packages, modules, extensions, and so on from\n    the distribution.\n    \"\"\"\n\n    _DISTUTILS_UNSUPPORTED_METADATA = {\n        'long_description_content_type': lambda: None,\n        'project_urls': dict,\n        'provides_extras': ordered_set.OrderedSet,\n        'license_file': lambda: None,\n        'license_files': lambda: None,\n    }\n\n    _patched_dist = None\n\n    def patch_missing_pkg_info(self, attrs):\n        # Fake up a replacement for the data that would normally come from\n        # PKG-INFO, but which might not yet be built if this is a fresh\n        # checkout.\n        #\n        if not attrs or 'name' not in attrs or 'version' not in attrs:\n            return\n        key = pkg_resources.safe_name(str(attrs['name'])).lower()\n        dist = pkg_resources.working_set.by_key.get(key)\n        if dist is not None and not dist.has_metadata('PKG-INFO'):\n            dist._version = pkg_resources.safe_version(str(attrs['version']))\n            self._patched_dist = dist\n\n    def __init__(self, attrs=None):\n        have_package_data = hasattr(self, \"package_data\")\n        if not have_package_data:\n            self.package_data = {}\n        attrs = attrs or {}\n        self.dist_files = []\n        # Filter-out setuptools' specific options.\n        self.src_root = attrs.pop(\"src_root\", None)\n        self.patch_missing_pkg_info(attrs)\n        self.dependency_links = attrs.pop('dependency_links', [])\n        self.setup_requires = attrs.pop('setup_requires', [])\n        for ep in metadata.entry_points(group='distutils.setup_keywords'):\n            vars(self).setdefault(ep.name, None)\n        _Distribution.__init__(\n            self,\n            {\n                k: v\n                for k, v in attrs.items()\n                if k not in self._DISTUTILS_UNSUPPORTED_METADATA\n            },\n        )\n\n        # Save the original dependencies before they are processed into the egg format\n        self._orig_extras_require = {}\n        self._orig_install_requires = []\n        self._tmp_extras_require = defaultdict(ordered_set.OrderedSet)\n\n        self.set_defaults = ConfigDiscovery(self)\n\n        self._set_metadata_defaults(attrs)\n\n        self.metadata.version = self._normalize_version(\n            self._validate_version(self.metadata.version)\n        )\n        self._finalize_requires()\n\n    def _validate_metadata(self):\n        required = {\"name\"}\n        provided = {\n            key\n            for key in vars(self.metadata)\n            if getattr(self.metadata, key, None) is not None\n        }\n        missing = required - provided\n\n        if missing:\n            msg = f\"Required package metadata is missing: {missing}\"\n            raise DistutilsSetupError(msg)\n\n    def _set_metadata_defaults(self, attrs):\n        \"\"\"\n        Fill-in missing metadata fields not supported by distutils.\n        Some fields may have been set by other tools (e.g. pbr).\n        Those fields (vars(self.metadata)) take precedence to\n        supplied attrs.\n        \"\"\"\n        for option, default in self._DISTUTILS_UNSUPPORTED_METADATA.items():\n            vars(self.metadata).setdefault(option, attrs.get(option, default()))\n\n    @staticmethod\n    def _normalize_version(version):\n        if isinstance(version, setuptools.sic) or version is None:\n            return version\n\n        normalized = str(packaging.version.Version(version))\n        if version != normalized:\n            tmpl = \"Normalizing '{version}' to '{normalized}'\"\n            warnings.warn(tmpl.format(**locals()))\n            return normalized\n        return version\n\n    @staticmethod\n    def _validate_version(version):\n        if isinstance(version, numbers.Number):\n            # Some people apparently take \"version number\" too literally :)\n            version = str(version)\n\n        if version is not None:\n            try:\n                packaging.version.Version(version)\n            except (packaging.version.InvalidVersion, TypeError):\n                warnings.warn(\n                    \"The version specified (%r) is an invalid version, this \"\n                    \"may not work as expected with newer versions of \"\n                    \"setuptools, pip, and PyPI. Please see PEP 440 for more \"\n                    \"details.\" % version\n                )\n                return setuptools.sic(version)\n        return version\n\n    def _finalize_requires(self):\n        \"\"\"\n        Set `metadata.python_requires` and fix environment markers\n        in `install_requires` and `extras_require`.\n        \"\"\"\n        if getattr(self, 'python_requires', None):\n            self.metadata.python_requires = self.python_requires\n\n        if getattr(self, 'extras_require', None):\n            # Save original before it is messed by _convert_extras_requirements\n            self._orig_extras_require = self._orig_extras_require or self.extras_require\n            for extra in self.extras_require.keys():\n                # Since this gets called multiple times at points where the\n                # keys have become 'converted' extras, ensure that we are only\n                # truly adding extras we haven't seen before here.\n                extra = extra.split(':')[0]\n                if extra:\n                    self.metadata.provides_extras.add(extra)\n\n        if getattr(self, 'install_requires', None) and not self._orig_install_requires:\n            # Save original before it is messed by _move_install_requirements_markers\n            self._orig_install_requires = self.install_requires\n\n        self._convert_extras_requirements()\n        self._move_install_requirements_markers()\n\n    def _convert_extras_requirements(self):\n        \"\"\"\n        Convert requirements in `extras_require` of the form\n        `\"extra\": [\"barbazquux; {marker}\"]` to\n        `\"extra:{marker}\": [\"barbazquux\"]`.\n        \"\"\"\n        spec_ext_reqs = getattr(self, 'extras_require', None) or {}\n        tmp = defaultdict(ordered_set.OrderedSet)\n        self._tmp_extras_require = getattr(self, '_tmp_extras_require', tmp)\n        for section, v in spec_ext_reqs.items():\n            # Do not strip empty sections.\n            self._tmp_extras_require[section]\n            for r in _reqs.parse(v):\n                suffix = self._suffix_for(r)\n                self._tmp_extras_require[section + suffix].append(r)\n\n    @staticmethod\n    def _suffix_for(req):\n        \"\"\"\n        For a requirement, return the 'extras_require' suffix for\n        that requirement.\n        \"\"\"\n        return ':' + str(req.marker) if req.marker else ''\n\n    def _move_install_requirements_markers(self):\n        \"\"\"\n        Move requirements in `install_requires` that are using environment\n        markers `extras_require`.\n        \"\"\"\n\n        # divide the install_requires into two sets, simple ones still\n        # handled by install_requires and more complex ones handled\n        # by extras_require.\n\n        def is_simple_req(req):\n            return not req.marker\n\n        spec_inst_reqs = getattr(self, 'install_requires', None) or ()\n        inst_reqs = list(_reqs.parse(spec_inst_reqs))\n        simple_reqs = filter(is_simple_req, inst_reqs)\n        complex_reqs = itertools.filterfalse(is_simple_req, inst_reqs)\n        self.install_requires = list(map(str, simple_reqs))\n\n        for r in complex_reqs:\n            self._tmp_extras_require[':' + str(r.marker)].append(r)\n        self.extras_require = dict(\n            # list(dict.fromkeys(...))  ensures a list of unique strings\n            (k, list(dict.fromkeys(str(r) for r in map(self._clean_req, v))))\n            for k, v in self._tmp_extras_require.items()\n        )\n\n    def _clean_req(self, req):\n        \"\"\"\n        Given a Requirement, remove environment markers and return it.\n        \"\"\"\n        req.marker = None\n        return req\n\n    def _finalize_license_files(self):\n        \"\"\"Compute names of all license files which should be included.\"\"\"\n        license_files: Optional[List[str]] = self.metadata.license_files\n        patterns: List[str] = license_files if license_files else []\n\n        license_file: Optional[str] = self.metadata.license_file\n        if license_file and license_file not in patterns:\n            patterns.append(license_file)\n\n        if license_files is None and license_file is None:\n            # Default patterns match the ones wheel uses\n            # See https://wheel.readthedocs.io/en/stable/user_guide.html\n            # -> 'Including license files in the generated wheel file'\n            patterns = ('LICEN[CS]E*', 'COPYING*', 'NOTICE*', 'AUTHORS*')\n\n        self.metadata.license_files = list(\n            unique_everseen(self._expand_patterns(patterns))\n        )\n\n    @staticmethod\n    def _expand_patterns(patterns):\n        \"\"\"\n        >>> list(Distribution._expand_patterns(['LICENSE']))\n        ['LICENSE']\n        >>> list(Distribution._expand_patterns(['setup.cfg', 'LIC*']))\n        ['setup.cfg', 'LICENSE']\n        \"\"\"\n        return (\n            path\n            for pattern in patterns\n            for path in sorted(iglob(pattern))\n            if not path.endswith('~') and os.path.isfile(path)\n        )\n\n    # FIXME: 'Distribution._parse_config_files' is too complex (14)\n    def _parse_config_files(self, filenames=None):  # noqa: C901\n        \"\"\"\n        Adapted from distutils.dist.Distribution.parse_config_files,\n        this method provides the same functionality in subtly-improved\n        ways.\n        \"\"\"\n        from configparser import ConfigParser\n\n        # Ignore install directory options if we have a venv\n        ignore_options = (\n            []\n            if sys.prefix == sys.base_prefix\n            else [\n                'install-base',\n                'install-platbase',\n                'install-lib',\n                'install-platlib',\n                'install-purelib',\n                'install-headers',\n                'install-scripts',\n                'install-data',\n                'prefix',\n                'exec-prefix',\n                'home',\n                'user',\n                'root',\n            ]\n        )\n\n        ignore_options = frozenset(ignore_options)\n\n        if filenames is None:\n            filenames = self.find_config_files()\n\n        if DEBUG:\n            self.announce(\"Distribution.parse_config_files():\")\n\n        parser = ConfigParser()\n        parser.optionxform = str\n        for filename in filenames:\n            with io.open(filename, encoding='utf-8') as reader:\n                if DEBUG:\n                    self.announce(\"  reading {filename}\".format(**locals()))\n                parser.read_file(reader)\n            for section in parser.sections():\n                options = parser.options(section)\n                opt_dict = self.get_option_dict(section)\n\n                for opt in options:\n                    if opt == '__name__' or opt in ignore_options:\n                        continue\n\n                    val = parser.get(section, opt)\n                    opt = self.warn_dash_deprecation(opt, section)\n                    opt = self.make_option_lowercase(opt, section)\n                    opt_dict[opt] = (filename, val)\n\n            # Make the ConfigParser forget everything (so we retain\n            # the original filenames that options come from)\n            parser.__init__()\n\n        if 'global' not in self.command_options:\n            return\n\n        # If there was a \"global\" section in the config file, use it\n        # to set Distribution options.\n\n        for (opt, (src, val)) in self.command_options['global'].items():\n            alias = self.negative_opt.get(opt)\n            if alias:\n                val = not strtobool(val)\n            elif opt in ('verbose', 'dry_run'):  # ugh!\n                val = strtobool(val)\n\n            try:\n                setattr(self, alias or opt, val)\n            except ValueError as e:\n                raise DistutilsOptionError(e) from e\n\n    def warn_dash_deprecation(self, opt, section):\n        if section in (\n            'options.extras_require',\n            'options.data_files',\n        ):\n            return opt\n\n        underscore_opt = opt.replace('-', '_')\n        commands = list(itertools.chain(\n            distutils.command.__all__,\n            self._setuptools_commands(),\n        ))\n        if (\n            not section.startswith('options')\n            and section != 'metadata'\n            and section not in commands\n        ):\n            return underscore_opt\n\n        if '-' in opt:\n            warnings.warn(\n                \"Usage of dash-separated '%s' will not be supported in future \"\n                \"versions. Please use the underscore name '%s' instead\"\n                % (opt, underscore_opt)\n            )\n        return underscore_opt\n\n    def _setuptools_commands(self):\n        try:\n            return metadata.distribution('setuptools').entry_points.names\n        except metadata.PackageNotFoundError:\n            # during bootstrapping, distribution doesn't exist\n            return []\n\n    def make_option_lowercase(self, opt, section):\n        if section != 'metadata' or opt.islower():\n            return opt\n\n        lowercase_opt = opt.lower()\n        warnings.warn(\n            \"Usage of uppercase key '%s' in '%s' will be deprecated in future \"\n            \"versions. Please use lowercase '%s' instead\"\n            % (opt, section, lowercase_opt)\n        )\n        return lowercase_opt\n\n    # FIXME: 'Distribution._set_command_options' is too complex (14)\n    def _set_command_options(self, command_obj, option_dict=None):  # noqa: C901\n        \"\"\"\n        Set the options for 'command_obj' from 'option_dict'.  Basically\n        this means copying elements of a dictionary ('option_dict') to\n        attributes of an instance ('command').\n\n        'command_obj' must be a Command instance.  If 'option_dict' is not\n        supplied, uses the standard option dictionary for this command\n        (from 'self.command_options').\n\n        (Adopted from distutils.dist.Distribution._set_command_options)\n        \"\"\"\n        command_name = command_obj.get_command_name()\n        if option_dict is None:\n            option_dict = self.get_option_dict(command_name)\n\n        if DEBUG:\n            self.announce(\"  setting options for '%s' command:\" % command_name)\n        for (option, (source, value)) in option_dict.items():\n            if DEBUG:\n                self.announce(\"    %s = %s (from %s)\" % (option, value, source))\n            try:\n                bool_opts = [translate_longopt(o) for o in command_obj.boolean_options]\n            except AttributeError:\n                bool_opts = []\n            try:\n                neg_opt = command_obj.negative_opt\n            except AttributeError:\n                neg_opt = {}\n\n            try:\n                is_string = isinstance(value, str)\n                if option in neg_opt and is_string:\n                    setattr(command_obj, neg_opt[option], not strtobool(value))\n                elif option in bool_opts and is_string:\n                    setattr(command_obj, option, strtobool(value))\n                elif hasattr(command_obj, option):\n                    setattr(command_obj, option, value)\n                else:\n                    raise DistutilsOptionError(\n                        \"error in %s: command '%s' has no such option '%s'\"\n                        % (source, command_name, option)\n                    )\n            except ValueError as e:\n                raise DistutilsOptionError(e) from e\n\n    def _get_project_config_files(self, filenames):\n        \"\"\"Add default file and split between INI and TOML\"\"\"\n        tomlfiles = []\n        standard_project_metadata = Path(self.src_root or os.curdir, \"pyproject.toml\")\n        if filenames is not None:\n            parts = partition(lambda f: Path(f).suffix == \".toml\", filenames)\n            filenames = list(parts[0])  # 1st element => predicate is False\n            tomlfiles = list(parts[1])  # 2nd element => predicate is True\n        elif standard_project_metadata.exists():\n            tomlfiles = [standard_project_metadata]\n        return filenames, tomlfiles\n\n    def parse_config_files(self, filenames=None, ignore_option_errors=False):\n        \"\"\"Parses configuration files from various levels\n        and loads configuration.\n        \"\"\"\n        inifiles, tomlfiles = self._get_project_config_files(filenames)\n\n        self._parse_config_files(filenames=inifiles)\n\n        setupcfg.parse_configuration(\n            self, self.command_options, ignore_option_errors=ignore_option_errors\n        )\n        for filename in tomlfiles:\n            pyprojecttoml.apply_configuration(self, filename, ignore_option_errors)\n\n        self._finalize_requires()\n        self._finalize_license_files()\n\n    def fetch_build_eggs(self, requires):\n        \"\"\"Resolve pre-setup requirements\"\"\"\n        resolved_dists = pkg_resources.working_set.resolve(\n            _reqs.parse(requires),\n            installer=self.fetch_build_egg,\n            replace_conflicting=True,\n        )\n        for dist in resolved_dists:\n            pkg_resources.working_set.add(dist, replace=True)\n        return resolved_dists\n\n    def finalize_options(self):\n        \"\"\"\n        Allow plugins to apply arbitrary operations to the\n        distribution. Each hook may optionally define a 'order'\n        to influence the order of execution. Smaller numbers\n        go first and the default is 0.\n        \"\"\"\n        group = 'setuptools.finalize_distribution_options'\n\n        def by_order(hook):\n            return getattr(hook, 'order', 0)\n\n        defined = metadata.entry_points(group=group)\n        filtered = itertools.filterfalse(self._removed, defined)\n        loaded = map(lambda e: e.load(), filtered)\n        for ep in sorted(loaded, key=by_order):\n            ep(self)\n\n    @staticmethod\n    def _removed(ep):\n        \"\"\"\n        When removing an entry point, if metadata is loaded\n        from an older version of Setuptools, that removed\n        entry point will attempt to be loaded and will fail.\n        See #2765 for more details.\n        \"\"\"\n        removed = {\n            # removed 2021-09-05\n            '2to3_doctests',\n        }\n        return ep.name in removed\n\n    def _finalize_setup_keywords(self):\n        for ep in metadata.entry_points(group='distutils.setup_keywords'):\n            value = getattr(self, ep.name, None)\n            if value is not None:\n                ep.load()(self, ep.name, value)\n\n    def get_egg_cache_dir(self):\n        egg_cache_dir = os.path.join(os.curdir, '.eggs')\n        if not os.path.exists(egg_cache_dir):\n            os.mkdir(egg_cache_dir)\n            windows_support.hide_file(egg_cache_dir)\n            readme_txt_filename = os.path.join(egg_cache_dir, 'README.txt')\n            with open(readme_txt_filename, 'w') as f:\n                f.write(\n                    'This directory contains eggs that were downloaded '\n                    'by setuptools to build, test, and run plug-ins.\\n\\n'\n                )\n                f.write(\n                    'This directory caches those eggs to prevent '\n                    'repeated downloads.\\n\\n'\n                )\n                f.write('However, it is safe to delete this directory.\\n\\n')\n\n        return egg_cache_dir\n\n    def fetch_build_egg(self, req):\n        \"\"\"Fetch an egg needed for building\"\"\"\n        from setuptools.installer import fetch_build_egg\n\n        return fetch_build_egg(self, req)\n\n    def get_command_class(self, command):\n        \"\"\"Pluggable version of get_command_class()\"\"\"\n        if command in self.cmdclass:\n            return self.cmdclass[command]\n\n        eps = metadata.entry_points(group='distutils.commands', name=command)\n        for ep in eps:\n            self.cmdclass[command] = cmdclass = ep.load()\n            return cmdclass\n        else:\n            return _Distribution.get_command_class(self, command)\n\n    def print_commands(self):\n        for ep in metadata.entry_points(group='distutils.commands'):\n            if ep.name not in self.cmdclass:\n                cmdclass = ep.load()\n                self.cmdclass[ep.name] = cmdclass\n        return _Distribution.print_commands(self)\n\n    def get_command_list(self):\n        for ep in metadata.entry_points(group='distutils.commands'):\n            if ep.name not in self.cmdclass:\n                cmdclass = ep.load()\n                self.cmdclass[ep.name] = cmdclass\n        return _Distribution.get_command_list(self)\n\n    def include(self, **attrs):\n        \"\"\"Add items to distribution that are named in keyword arguments\n\n        For example, 'dist.include(py_modules=[\"x\"])' would add 'x' to\n        the distribution's 'py_modules' attribute, if it was not already\n        there.\n\n        Currently, this method only supports inclusion for attributes that are\n        lists or tuples.  If you need to add support for adding to other\n        attributes in this or a subclass, you can add an '_include_X' method,\n        where 'X' is the name of the attribute.  The method will be called with\n        the value passed to 'include()'.  So, 'dist.include(foo={\"bar\":\"baz\"})'\n        will try to call 'dist._include_foo({\"bar\":\"baz\"})', which can then\n        handle whatever special inclusion logic is needed.\n        \"\"\"\n        for k, v in attrs.items():\n            include = getattr(self, '_include_' + k, None)\n            if include:\n                include(v)\n            else:\n                self._include_misc(k, v)\n\n    def exclude_package(self, package):\n        \"\"\"Remove packages, modules, and extensions in named package\"\"\"\n\n        pfx = package + '.'\n        if self.packages:\n            self.packages = [\n                p for p in self.packages if p != package and not p.startswith(pfx)\n            ]\n\n        if self.py_modules:\n            self.py_modules = [\n                p for p in self.py_modules if p != package and not p.startswith(pfx)\n            ]\n\n        if self.ext_modules:\n            self.ext_modules = [\n                p\n                for p in self.ext_modules\n                if p.name != package and not p.name.startswith(pfx)\n            ]\n\n    def has_contents_for(self, package):\n        \"\"\"Return true if 'exclude_package(package)' would do something\"\"\"\n\n        pfx = package + '.'\n\n        for p in self.iter_distribution_names():\n            if p == package or p.startswith(pfx):\n                return True\n\n    def _exclude_misc(self, name, value):\n        \"\"\"Handle 'exclude()' for list/tuple attrs without a special handler\"\"\"\n        if not isinstance(value, sequence):\n            raise DistutilsSetupError(\n                \"%s: setting must be a list or tuple (%r)\" % (name, value)\n            )\n        try:\n            old = getattr(self, name)\n        except AttributeError as e:\n            raise DistutilsSetupError(\"%s: No such distribution setting\" % name) from e\n        if old is not None and not isinstance(old, sequence):\n            raise DistutilsSetupError(\n                name + \": this setting cannot be changed via include/exclude\"\n            )\n        elif old:\n            setattr(self, name, [item for item in old if item not in value])\n\n    def _include_misc(self, name, value):\n        \"\"\"Handle 'include()' for list/tuple attrs without a special handler\"\"\"\n\n        if not isinstance(value, sequence):\n            raise DistutilsSetupError(\"%s: setting must be a list (%r)\" % (name, value))\n        try:\n            old = getattr(self, name)\n        except AttributeError as e:\n            raise DistutilsSetupError(\"%s: No such distribution setting\" % name) from e\n        if old is None:\n            setattr(self, name, value)\n        elif not isinstance(old, sequence):\n            raise DistutilsSetupError(\n                name + \": this setting cannot be changed via include/exclude\"\n            )\n        else:\n            new = [item for item in value if item not in old]\n            setattr(self, name, old + new)\n\n    def exclude(self, **attrs):\n        \"\"\"Remove items from distribution that are named in keyword arguments\n\n        For example, 'dist.exclude(py_modules=[\"x\"])' would remove 'x' from\n        the distribution's 'py_modules' attribute.  Excluding packages uses\n        the 'exclude_package()' method, so all of the package's contained\n        packages, modules, and extensions are also excluded.\n\n        Currently, this method only supports exclusion from attributes that are\n        lists or tuples.  If you need to add support for excluding from other\n        attributes in this or a subclass, you can add an '_exclude_X' method,\n        where 'X' is the name of the attribute.  The method will be called with\n        the value passed to 'exclude()'.  So, 'dist.exclude(foo={\"bar\":\"baz\"})'\n        will try to call 'dist._exclude_foo({\"bar\":\"baz\"})', which can then\n        handle whatever special exclusion logic is needed.\n        \"\"\"\n        for k, v in attrs.items():\n            exclude = getattr(self, '_exclude_' + k, None)\n            if exclude:\n                exclude(v)\n            else:\n                self._exclude_misc(k, v)\n\n    def _exclude_packages(self, packages):\n        if not isinstance(packages, sequence):\n            raise DistutilsSetupError(\n                \"packages: setting must be a list or tuple (%r)\" % (packages,)\n            )\n        list(map(self.exclude_package, packages))\n\n    def _parse_command_opts(self, parser, args):\n        # Remove --with-X/--without-X options when processing command args\n        self.global_options = self.__class__.global_options\n        self.negative_opt = self.__class__.negative_opt\n\n        # First, expand any aliases\n        command = args[0]\n        aliases = self.get_option_dict('aliases')\n        while command in aliases:\n            src, alias = aliases[command]\n            del aliases[command]  # ensure each alias can expand only once!\n            import shlex\n\n            args[:1] = shlex.split(alias, True)\n            command = args[0]\n\n        nargs = _Distribution._parse_command_opts(self, parser, args)\n\n        # Handle commands that want to consume all remaining arguments\n        cmd_class = self.get_command_class(command)\n        if getattr(cmd_class, 'command_consumes_arguments', None):\n            self.get_option_dict(command)['args'] = (\"command line\", nargs)\n            if nargs is not None:\n                return []\n\n        return nargs\n\n    def get_cmdline_options(self):\n        \"\"\"Return a '{cmd: {opt:val}}' map of all command-line options\n\n        Option names are all long, but do not include the leading '--', and\n        contain dashes rather than underscores.  If the option doesn't take\n        an argument (e.g. '--quiet'), the 'val' is 'None'.\n\n        Note that options provided by config files are intentionally excluded.\n        \"\"\"\n\n        d = {}\n\n        for cmd, opts in self.command_options.items():\n\n            for opt, (src, val) in opts.items():\n\n                if src != \"command line\":\n                    continue\n\n                opt = opt.replace('_', '-')\n\n                if val == 0:\n                    cmdobj = self.get_command_obj(cmd)\n                    neg_opt = self.negative_opt.copy()\n                    neg_opt.update(getattr(cmdobj, 'negative_opt', {}))\n                    for neg, pos in neg_opt.items():\n                        if pos == opt:\n                            opt = neg\n                            val = None\n                            break\n                    else:\n                        raise AssertionError(\"Shouldn't be able to get here\")\n\n                elif val == 1:\n                    val = None\n\n                d.setdefault(cmd, {})[opt] = val\n\n        return d\n\n    def iter_distribution_names(self):\n        \"\"\"Yield all packages, modules, and extension names in distribution\"\"\"\n\n        for pkg in self.packages or ():\n            yield pkg\n\n        for module in self.py_modules or ():\n            yield module\n\n        for ext in self.ext_modules or ():\n            if isinstance(ext, tuple):\n                name, buildinfo = ext\n            else:\n                name = ext.name\n            if name.endswith('module'):\n                name = name[:-6]\n            yield name\n\n    def handle_display_options(self, option_order):\n        \"\"\"If there were any non-global \"display-only\" options\n        (--help-commands or the metadata display options) on the command\n        line, display the requested info and return true; else return\n        false.\n        \"\"\"\n        import sys\n\n        if self.help_commands:\n            return _Distribution.handle_display_options(self, option_order)\n\n        # Stdout may be StringIO (e.g. in tests)\n        if not isinstance(sys.stdout, io.TextIOWrapper):\n            return _Distribution.handle_display_options(self, option_order)\n\n        # Don't wrap stdout if utf-8 is already the encoding. Provides\n        #  workaround for #334.\n        if sys.stdout.encoding.lower() in ('utf-8', 'utf8'):\n            return _Distribution.handle_display_options(self, option_order)\n\n        # Print metadata in UTF-8 no matter the platform\n        encoding = sys.stdout.encoding\n        errors = sys.stdout.errors\n        newline = sys.platform != 'win32' and '\\n' or None\n        line_buffering = sys.stdout.line_buffering\n\n        sys.stdout = io.TextIOWrapper(\n            sys.stdout.detach(), 'utf-8', errors, newline, line_buffering\n        )\n        try:\n            return _Distribution.handle_display_options(self, option_order)\n        finally:\n            sys.stdout = io.TextIOWrapper(\n                sys.stdout.detach(), encoding, errors, newline, line_buffering\n            )\n\n    def run_command(self, command):\n        self.set_defaults()\n        # Postpone defaults until all explicit configuration is considered\n        # (setup() args, config files, command line and plugins)\n\n        super().run_command(command)\n\n\nclass DistDeprecationWarning(SetuptoolsDeprecationWarning):\n    \"\"\"Class for warning about deprecations in dist in\n    setuptools. Not ignored by default, unlike DeprecationWarning.\"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/errors.py",
    "content": "\"\"\"setuptools.errors\n\nProvides exceptions used by setuptools modules.\n\"\"\"\n\nfrom distutils import errors as _distutils_errors\n\n\n# Re-export errors from distutils to facilitate the migration to PEP632\n\nByteCompileError = _distutils_errors.DistutilsByteCompileError\nCCompilerError = _distutils_errors.CCompilerError\nClassError = _distutils_errors.DistutilsClassError\nCompileError = _distutils_errors.CompileError\nExecError = _distutils_errors.DistutilsExecError\nFileError = _distutils_errors.DistutilsFileError\nInternalError = _distutils_errors.DistutilsInternalError\nLibError = _distutils_errors.LibError\nLinkError = _distutils_errors.LinkError\nModuleError = _distutils_errors.DistutilsModuleError\nOptionError = _distutils_errors.DistutilsOptionError\nPlatformError = _distutils_errors.DistutilsPlatformError\nPreprocessError = _distutils_errors.PreprocessError\nSetupError = _distutils_errors.DistutilsSetupError\nTemplateError = _distutils_errors.DistutilsTemplateError\nUnknownFileError = _distutils_errors.UnknownFileError\n\n# The root error class in the hierarchy\nBaseError = _distutils_errors.DistutilsError\n\n\nclass RemovedCommandError(BaseError, RuntimeError):\n    \"\"\"Error used for commands that have been removed in setuptools.\n\n    Since ``setuptools`` is built on ``distutils``, simply removing a command\n    from ``setuptools`` will make the behavior fall back to ``distutils``; this\n    error is raised if a command exists in ``distutils`` but has been actively\n    removed in ``setuptools``.\n    \"\"\"\n\n\nclass PackageDiscoveryError(BaseError, RuntimeError):\n    \"\"\"Impossible to perform automatic discovery of packages and/or modules.\n\n    The current project layout or given discovery options can lead to problems when\n    scanning the project directory.\n\n    Setuptools might also refuse to complete auto-discovery if an error prone condition\n    is detected (e.g. when a project is organised as a flat-layout but contains\n    multiple directories that can be taken as top-level packages inside a single\n    distribution [*]_). In these situations the users are encouraged to be explicit\n    about which packages to include or to make the discovery parameters more specific.\n\n    .. [*] Since multi-package distributions are uncommon it is very likely that the\n       developers did not intend for all the directories to be packaged, and are just\n       leaving auxiliary code in the repository top-level, such as maintenance-related\n       scripts.\n    \"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/extension.py",
    "content": "import re\nimport functools\nimport distutils.core\nimport distutils.errors\nimport distutils.extension\n\nfrom .monkey import get_unpatched\n\n\ndef _have_cython():\n    \"\"\"\n    Return True if Cython can be imported.\n    \"\"\"\n    cython_impl = 'Cython.Distutils.build_ext'\n    try:\n        # from (cython_impl) import build_ext\n        __import__(cython_impl, fromlist=['build_ext']).build_ext\n        return True\n    except Exception:\n        pass\n    return False\n\n\n# for compatibility\nhave_pyrex = _have_cython\n\n_Extension = get_unpatched(distutils.core.Extension)\n\n\nclass Extension(_Extension):\n    \"\"\"\n    Describes a single extension module.\n\n    This means that all source files will be compiled into a single binary file\n    ``<module path>.<suffix>`` (with ``<module path>`` derived from ``name`` and\n    ``<suffix>`` defined by one of the values in\n    ``importlib.machinery.EXTENSION_SUFFIXES``).\n\n    In the case ``.pyx`` files are passed as ``sources and`` ``Cython`` is **not**\n    installed in the build environment, ``setuptools`` may also try to look for the\n    equivalent ``.cpp`` or ``.c`` files.\n\n    :arg str name:\n      the full name of the extension, including any packages -- ie.\n      *not* a filename or pathname, but Python dotted name\n\n    :arg list[str] sources:\n      list of source filenames, relative to the distribution root\n      (where the setup script lives), in Unix form (slash-separated)\n      for portability.  Source files may be C, C++, SWIG (.i),\n      platform-specific resource files, or whatever else is recognized\n      by the \"build_ext\" command as source for a Python extension.\n\n    :keyword list[str] include_dirs:\n      list of directories to search for C/C++ header files (in Unix\n      form for portability)\n\n    :keyword list[tuple[str, str|None]] define_macros:\n      list of macros to define; each macro is defined using a 2-tuple:\n      the first item corresponding to the name of the macro and the second\n      item either a string with its value or None to\n      define it without a particular value (equivalent of \"#define\n      FOO\" in source or -DFOO on Unix C compiler command line)\n\n    :keyword list[str] undef_macros:\n      list of macros to undefine explicitly\n\n    :keyword list[str] library_dirs:\n      list of directories to search for C/C++ libraries at link time\n\n    :keyword list[str] libraries:\n      list of library names (not filenames or paths) to link against\n\n    :keyword list[str] runtime_library_dirs:\n      list of directories to search for C/C++ libraries at run time\n      (for shared extensions, this is when the extension is loaded).\n      Setting this will cause an exception during build on Windows\n      platforms.\n\n    :keyword list[str] extra_objects:\n      list of extra files to link with (eg. object files not implied\n      by 'sources', static library that must be explicitly specified,\n      binary resource files, etc.)\n\n    :keyword list[str] extra_compile_args:\n      any extra platform- and compiler-specific information to use\n      when compiling the source files in 'sources'.  For platforms and\n      compilers where \"command line\" makes sense, this is typically a\n      list of command-line arguments, but for other platforms it could\n      be anything.\n\n    :keyword list[str] extra_link_args:\n      any extra platform- and compiler-specific information to use\n      when linking object files together to create the extension (or\n      to create a new static Python interpreter).  Similar\n      interpretation as for 'extra_compile_args'.\n\n    :keyword list[str] export_symbols:\n      list of symbols to be exported from a shared extension.  Not\n      used on all platforms, and not generally necessary for Python\n      extensions, which typically export exactly one symbol: \"init\" +\n      extension_name.\n\n    :keyword list[str] swig_opts:\n      any extra options to pass to SWIG if a source file has the .i\n      extension.\n\n    :keyword list[str] depends:\n      list of files that the extension depends on\n\n    :keyword str language:\n      extension language (i.e. \"c\", \"c++\", \"objc\"). Will be detected\n      from the source extensions if not provided.\n\n    :keyword bool optional:\n      specifies that a build failure in the extension should not abort the\n      build process, but simply not install the failing extension.\n\n    :keyword bool py_limited_api:\n      opt-in flag for the usage of :doc:`Python's limited API <python:c-api/stable>`.\n\n    :raises setuptools.errors.PlatformError: if 'runtime_library_dirs' is\n      specified on Windows. (since v63)\n    \"\"\"\n\n    def __init__(self, name, sources, *args, **kw):\n        # The *args is needed for compatibility as calls may use positional\n        # arguments. py_limited_api may be set only via keyword.\n        self.py_limited_api = kw.pop(\"py_limited_api\", False)\n        super().__init__(name, sources, *args, **kw)\n\n    def _convert_pyx_sources_to_lang(self):\n        \"\"\"\n        Replace sources with .pyx extensions to sources with the target\n        language extension. This mechanism allows language authors to supply\n        pre-converted sources but to prefer the .pyx sources.\n        \"\"\"\n        if _have_cython():\n            # the build has Cython, so allow it to compile the .pyx files\n            return\n        lang = self.language or ''\n        target_ext = '.cpp' if lang.lower() == 'c++' else '.c'\n        sub = functools.partial(re.sub, '.pyx$', target_ext)\n        self.sources = list(map(sub, self.sources))\n\n\nclass Library(Extension):\n    \"\"\"Just like a regular Extension, but built as a library instead\"\"\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/extern/__init__.py",
    "content": "import importlib.util\nimport sys\n\n\nclass VendorImporter:\n    \"\"\"\n    A PEP 302 meta path importer for finding optionally-vendored\n    or otherwise naturally-installed packages from root_name.\n    \"\"\"\n\n    def __init__(self, root_name, vendored_names=(), vendor_pkg=None):\n        self.root_name = root_name\n        self.vendored_names = set(vendored_names)\n        self.vendor_pkg = vendor_pkg or root_name.replace('extern', '_vendor')\n\n    @property\n    def search_path(self):\n        \"\"\"\n        Search first the vendor package then as a natural package.\n        \"\"\"\n        yield self.vendor_pkg + '.'\n        yield ''\n\n    def _module_matches_namespace(self, fullname):\n        \"\"\"Figure out if the target module is vendored.\"\"\"\n        root, base, target = fullname.partition(self.root_name + '.')\n        return not root and any(map(target.startswith, self.vendored_names))\n\n    def load_module(self, fullname):\n        \"\"\"\n        Iterate over the search path to locate and load fullname.\n        \"\"\"\n        root, base, target = fullname.partition(self.root_name + '.')\n        for prefix in self.search_path:\n            try:\n                extant = prefix + target\n                __import__(extant)\n                mod = sys.modules[extant]\n                sys.modules[fullname] = mod\n                return mod\n            except ImportError:\n                pass\n        else:\n            raise ImportError(\n                \"The '{target}' package is required; \"\n                \"normally this is bundled with this package so if you get \"\n                \"this warning, consult the packager of your \"\n                \"distribution.\".format(**locals())\n            )\n\n    def create_module(self, spec):\n        return self.load_module(spec.name)\n\n    def exec_module(self, module):\n        pass\n\n    def find_spec(self, fullname, path=None, target=None):\n        \"\"\"Return a module spec for vendored names.\"\"\"\n        return (\n            importlib.util.spec_from_loader(fullname, self)\n            if self._module_matches_namespace(fullname) else None\n        )\n\n    def install(self):\n        \"\"\"\n        Install this importer into sys.meta_path if not already present.\n        \"\"\"\n        if self not in sys.meta_path:\n            sys.meta_path.append(self)\n\n\nnames = (\n    'packaging', 'pyparsing', 'ordered_set', 'more_itertools', 'importlib_metadata',\n    'zipp', 'importlib_resources', 'jaraco', 'typing_extensions', 'tomli',\n)\nVendorImporter(__name__, names, 'setuptools._vendor').install()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/glob.py",
    "content": "\"\"\"\nFilename globbing utility. Mostly a copy of `glob` from Python 3.5.\n\nChanges include:\n * `yield from` and PEP3102 `*` removed.\n * Hidden files are not ignored.\n\"\"\"\n\nimport os\nimport re\nimport fnmatch\n\n__all__ = [\"glob\", \"iglob\", \"escape\"]\n\n\ndef glob(pathname, recursive=False):\n    \"\"\"Return a list of paths matching a pathname pattern.\n\n    The pattern may contain simple shell-style wildcards a la\n    fnmatch. However, unlike fnmatch, filenames starting with a\n    dot are special cases that are not matched by '*' and '?'\n    patterns.\n\n    If recursive is true, the pattern '**' will match any files and\n    zero or more directories and subdirectories.\n    \"\"\"\n    return list(iglob(pathname, recursive=recursive))\n\n\ndef iglob(pathname, recursive=False):\n    \"\"\"Return an iterator which yields the paths matching a pathname pattern.\n\n    The pattern may contain simple shell-style wildcards a la\n    fnmatch. However, unlike fnmatch, filenames starting with a\n    dot are special cases that are not matched by '*' and '?'\n    patterns.\n\n    If recursive is true, the pattern '**' will match any files and\n    zero or more directories and subdirectories.\n    \"\"\"\n    it = _iglob(pathname, recursive)\n    if recursive and _isrecursive(pathname):\n        s = next(it)  # skip empty string\n        assert not s\n    return it\n\n\ndef _iglob(pathname, recursive):\n    dirname, basename = os.path.split(pathname)\n    glob_in_dir = glob2 if recursive and _isrecursive(basename) else glob1\n\n    if not has_magic(pathname):\n        if basename:\n            if os.path.lexists(pathname):\n                yield pathname\n        else:\n            # Patterns ending with a slash should match only directories\n            if os.path.isdir(dirname):\n                yield pathname\n        return\n\n    if not dirname:\n        yield from glob_in_dir(dirname, basename)\n        return\n    # `os.path.split()` returns the argument itself as a dirname if it is a\n    # drive or UNC path.  Prevent an infinite recursion if a drive or UNC path\n    # contains magic characters (i.e. r'\\\\?\\C:').\n    if dirname != pathname and has_magic(dirname):\n        dirs = _iglob(dirname, recursive)\n    else:\n        dirs = [dirname]\n    if not has_magic(basename):\n        glob_in_dir = glob0\n    for dirname in dirs:\n        for name in glob_in_dir(dirname, basename):\n            yield os.path.join(dirname, name)\n\n\n# These 2 helper functions non-recursively glob inside a literal directory.\n# They return a list of basenames. `glob1` accepts a pattern while `glob0`\n# takes a literal basename (so it only has to check for its existence).\n\n\ndef glob1(dirname, pattern):\n    if not dirname:\n        if isinstance(pattern, bytes):\n            dirname = os.curdir.encode('ASCII')\n        else:\n            dirname = os.curdir\n    try:\n        names = os.listdir(dirname)\n    except OSError:\n        return []\n    return fnmatch.filter(names, pattern)\n\n\ndef glob0(dirname, basename):\n    if not basename:\n        # `os.path.split()` returns an empty basename for paths ending with a\n        # directory separator.  'q*x/' should match only directories.\n        if os.path.isdir(dirname):\n            return [basename]\n    else:\n        if os.path.lexists(os.path.join(dirname, basename)):\n            return [basename]\n    return []\n\n\n# This helper function recursively yields relative pathnames inside a literal\n# directory.\n\n\ndef glob2(dirname, pattern):\n    assert _isrecursive(pattern)\n    yield pattern[:0]\n    for x in _rlistdir(dirname):\n        yield x\n\n\n# Recursively yields relative pathnames inside a literal directory.\ndef _rlistdir(dirname):\n    if not dirname:\n        if isinstance(dirname, bytes):\n            dirname = os.curdir.encode('ASCII')\n        else:\n            dirname = os.curdir\n    try:\n        names = os.listdir(dirname)\n    except os.error:\n        return\n    for x in names:\n        yield x\n        path = os.path.join(dirname, x) if dirname else x\n        for y in _rlistdir(path):\n            yield os.path.join(x, y)\n\n\nmagic_check = re.compile('([*?[])')\nmagic_check_bytes = re.compile(b'([*?[])')\n\n\ndef has_magic(s):\n    if isinstance(s, bytes):\n        match = magic_check_bytes.search(s)\n    else:\n        match = magic_check.search(s)\n    return match is not None\n\n\ndef _isrecursive(pattern):\n    if isinstance(pattern, bytes):\n        return pattern == b'**'\n    else:\n        return pattern == '**'\n\n\ndef escape(pathname):\n    \"\"\"Escape all special characters.\n    \"\"\"\n    # Escaping is done by wrapping any of \"*?[\" between square brackets.\n    # Metacharacters do not work in the drive part and shouldn't be escaped.\n    drive, pathname = os.path.splitdrive(pathname)\n    if isinstance(pathname, bytes):\n        pathname = magic_check_bytes.sub(br'[\\1]', pathname)\n    else:\n        pathname = magic_check.sub(r'[\\1]', pathname)\n    return drive + pathname\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/installer.py",
    "content": "import glob\nimport os\nimport subprocess\nimport sys\nimport tempfile\nimport warnings\nfrom distutils import log\nfrom distutils.errors import DistutilsError\n\nimport pkg_resources\nfrom setuptools.wheel import Wheel\nfrom ._deprecation_warning import SetuptoolsDeprecationWarning\n\n\ndef _fixup_find_links(find_links):\n    \"\"\"Ensure find-links option end-up being a list of strings.\"\"\"\n    if isinstance(find_links, str):\n        return find_links.split()\n    assert isinstance(find_links, (tuple, list))\n    return find_links\n\n\ndef fetch_build_egg(dist, req):  # noqa: C901  # is too complex (16)  # FIXME\n    \"\"\"Fetch an egg needed for building.\n\n    Use pip/wheel to fetch/build a wheel.\"\"\"\n    warnings.warn(\n        \"setuptools.installer is deprecated. Requirements should \"\n        \"be satisfied by a PEP 517 installer.\",\n        SetuptoolsDeprecationWarning,\n    )\n    # Warn if wheel is not available\n    try:\n        pkg_resources.get_distribution('wheel')\n    except pkg_resources.DistributionNotFound:\n        dist.announce('WARNING: The wheel package is not available.', log.WARN)\n    # Ignore environment markers; if supplied, it is required.\n    req = strip_marker(req)\n    # Take easy_install options into account, but do not override relevant\n    # pip environment variables (like PIP_INDEX_URL or PIP_QUIET); they'll\n    # take precedence.\n    opts = dist.get_option_dict('easy_install')\n    if 'allow_hosts' in opts:\n        raise DistutilsError('the `allow-hosts` option is not supported '\n                             'when using pip to install requirements.')\n    quiet = 'PIP_QUIET' not in os.environ and 'PIP_VERBOSE' not in os.environ\n    if 'PIP_INDEX_URL' in os.environ:\n        index_url = None\n    elif 'index_url' in opts:\n        index_url = opts['index_url'][1]\n    else:\n        index_url = None\n    find_links = (\n        _fixup_find_links(opts['find_links'][1])[:] if 'find_links' in opts\n        else []\n    )\n    if dist.dependency_links:\n        find_links.extend(dist.dependency_links)\n    eggs_dir = os.path.realpath(dist.get_egg_cache_dir())\n    environment = pkg_resources.Environment()\n    for egg_dist in pkg_resources.find_distributions(eggs_dir):\n        if egg_dist in req and environment.can_add(egg_dist):\n            return egg_dist\n    with tempfile.TemporaryDirectory() as tmpdir:\n        cmd = [\n            sys.executable, '-m', 'pip',\n            '--disable-pip-version-check',\n            'wheel', '--no-deps',\n            '-w', tmpdir,\n        ]\n        if quiet:\n            cmd.append('--quiet')\n        if index_url is not None:\n            cmd.extend(('--index-url', index_url))\n        for link in find_links or []:\n            cmd.extend(('--find-links', link))\n        # If requirement is a PEP 508 direct URL, directly pass\n        # the URL to pip, as `req @ url` does not work on the\n        # command line.\n        cmd.append(req.url or str(req))\n        try:\n            subprocess.check_call(cmd)\n        except subprocess.CalledProcessError as e:\n            raise DistutilsError(str(e)) from e\n        wheel = Wheel(glob.glob(os.path.join(tmpdir, '*.whl'))[0])\n        dist_location = os.path.join(eggs_dir, wheel.egg_name())\n        wheel.install_as_egg(dist_location)\n        dist_metadata = pkg_resources.PathMetadata(\n            dist_location, os.path.join(dist_location, 'EGG-INFO'))\n        dist = pkg_resources.Distribution.from_filename(\n            dist_location, metadata=dist_metadata)\n        return dist\n\n\ndef strip_marker(req):\n    \"\"\"\n    Return a new requirement without the environment marker to avoid\n    calling pip with something like `babel; extra == \"i18n\"`, which\n    would always be ignored.\n    \"\"\"\n    # create a copy to avoid mutating the input\n    req = pkg_resources.Requirement.parse(str(req))\n    req.marker = None\n    return req\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/launch.py",
    "content": "\"\"\"\nLaunch the Python script on the command line after\nsetuptools is bootstrapped via import.\n\"\"\"\n\n# Note that setuptools gets imported implicitly by the\n# invocation of this script using python -m setuptools.launch\n\nimport tokenize\nimport sys\n\n\ndef run():\n    \"\"\"\n    Run the script in sys.argv[1] as if it had\n    been invoked naturally.\n    \"\"\"\n    __builtins__\n    script_name = sys.argv[1]\n    namespace = dict(\n        __file__=script_name,\n        __name__='__main__',\n        __doc__=None,\n    )\n    sys.argv[:] = sys.argv[1:]\n\n    open_ = getattr(tokenize, 'open', open)\n    with open_(script_name) as fid:\n        script = fid.read()\n    norm_script = script.replace('\\\\r\\\\n', '\\\\n')\n    code = compile(norm_script, script_name, 'exec')\n    exec(code, namespace)\n\n\nif __name__ == '__main__':\n    run()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/logging.py",
    "content": "import sys\nimport logging\nimport distutils.log\nfrom . import monkey\n\n\ndef _not_warning(record):\n    return record.levelno < logging.WARNING\n\n\ndef configure():\n    \"\"\"\n    Configure logging to emit warning and above to stderr\n    and everything else to stdout. This behavior is provided\n    for compatibility with distutils.log but may change in\n    the future.\n    \"\"\"\n    err_handler = logging.StreamHandler()\n    err_handler.setLevel(logging.WARNING)\n    out_handler = logging.StreamHandler(sys.stdout)\n    out_handler.addFilter(_not_warning)\n    handlers = err_handler, out_handler\n    logging.basicConfig(\n        format=\"{message}\", style='{', handlers=handlers, level=logging.DEBUG)\n    if hasattr(distutils.log, 'Log'):\n        monkey.patch_func(set_threshold, distutils.log, 'set_threshold')\n        # For some reason `distutils.log` module is getting cached in `distutils.dist`\n        # and then loaded again when patched,\n        # implying: id(distutils.log) != id(distutils.dist.log).\n        # Make sure the same module object is used everywhere:\n        distutils.dist.log = distutils.log\n\n\ndef set_threshold(level):\n    logging.root.setLevel(level*10)\n    return set_threshold.unpatched(level)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/monkey.py",
    "content": "\"\"\"\nMonkey patching of distutils.\n\"\"\"\n\nimport sys\nimport distutils.filelist\nimport platform\nimport types\nimport functools\nfrom importlib import import_module\nimport inspect\n\nimport setuptools\n\n__all__ = []\n\"\"\"\nEverything is private. Contact the project team\nif you think you need this functionality.\n\"\"\"\n\n\ndef _get_mro(cls):\n    \"\"\"\n    Returns the bases classes for cls sorted by the MRO.\n\n    Works around an issue on Jython where inspect.getmro will not return all\n    base classes if multiple classes share the same name. Instead, this\n    function will return a tuple containing the class itself, and the contents\n    of cls.__bases__. See https://github.com/pypa/setuptools/issues/1024.\n    \"\"\"\n    if platform.python_implementation() == \"Jython\":\n        return (cls,) + cls.__bases__\n    return inspect.getmro(cls)\n\n\ndef get_unpatched(item):\n    lookup = (\n        get_unpatched_class if isinstance(item, type) else\n        get_unpatched_function if isinstance(item, types.FunctionType) else\n        lambda item: None\n    )\n    return lookup(item)\n\n\ndef get_unpatched_class(cls):\n    \"\"\"Protect against re-patching the distutils if reloaded\n\n    Also ensures that no other distutils extension monkeypatched the distutils\n    first.\n    \"\"\"\n    external_bases = (\n        cls\n        for cls in _get_mro(cls)\n        if not cls.__module__.startswith('setuptools')\n    )\n    base = next(external_bases)\n    if not base.__module__.startswith('distutils'):\n        msg = \"distutils has already been patched by %r\" % cls\n        raise AssertionError(msg)\n    return base\n\n\ndef patch_all():\n    # we can't patch distutils.cmd, alas\n    distutils.core.Command = setuptools.Command\n\n    has_issue_12885 = sys.version_info <= (3, 5, 3)\n\n    if has_issue_12885:\n        # fix findall bug in distutils (http://bugs.python.org/issue12885)\n        distutils.filelist.findall = setuptools.findall\n\n    needs_warehouse = (\n        (3, 4) < sys.version_info < (3, 4, 6)\n        or\n        (3, 5) < sys.version_info <= (3, 5, 3)\n    )\n\n    if needs_warehouse:\n        warehouse = 'https://upload.pypi.org/legacy/'\n        distutils.config.PyPIRCCommand.DEFAULT_REPOSITORY = warehouse\n\n    _patch_distribution_metadata()\n\n    # Install Distribution throughout the distutils\n    for module in distutils.dist, distutils.core, distutils.cmd:\n        module.Distribution = setuptools.dist.Distribution\n\n    # Install the patched Extension\n    distutils.core.Extension = setuptools.extension.Extension\n    distutils.extension.Extension = setuptools.extension.Extension\n    if 'distutils.command.build_ext' in sys.modules:\n        sys.modules['distutils.command.build_ext'].Extension = (\n            setuptools.extension.Extension\n        )\n\n    patch_for_msvc_specialized_compiler()\n\n\ndef _patch_distribution_metadata():\n    \"\"\"Patch write_pkg_file and read_pkg_file for higher metadata standards\"\"\"\n    for attr in ('write_pkg_file', 'read_pkg_file', 'get_metadata_version'):\n        new_val = getattr(setuptools.dist, attr)\n        setattr(distutils.dist.DistributionMetadata, attr, new_val)\n\n\ndef patch_func(replacement, target_mod, func_name):\n    \"\"\"\n    Patch func_name in target_mod with replacement\n\n    Important - original must be resolved by name to avoid\n    patching an already patched function.\n    \"\"\"\n    original = getattr(target_mod, func_name)\n\n    # set the 'unpatched' attribute on the replacement to\n    # point to the original.\n    vars(replacement).setdefault('unpatched', original)\n\n    # replace the function in the original module\n    setattr(target_mod, func_name, replacement)\n\n\ndef get_unpatched_function(candidate):\n    return getattr(candidate, 'unpatched')\n\n\ndef patch_for_msvc_specialized_compiler():\n    \"\"\"\n    Patch functions in distutils to use standalone Microsoft Visual C++\n    compilers.\n    \"\"\"\n    # import late to avoid circular imports on Python < 3.5\n    msvc = import_module('setuptools.msvc')\n\n    if platform.system() != 'Windows':\n        # Compilers only available on Microsoft Windows\n        return\n\n    def patch_params(mod_name, func_name):\n        \"\"\"\n        Prepare the parameters for patch_func to patch indicated function.\n        \"\"\"\n        repl_prefix = 'msvc14_'\n        repl_name = repl_prefix + func_name.lstrip('_')\n        repl = getattr(msvc, repl_name)\n        mod = import_module(mod_name)\n        if not hasattr(mod, func_name):\n            raise ImportError(func_name)\n        return repl, mod, func_name\n\n    # Python 3.5+\n    msvc14 = functools.partial(patch_params, 'distutils._msvccompiler')\n\n    try:\n        # Patch distutils._msvccompiler._get_vc_env\n        patch_func(*msvc14('_get_vc_env'))\n    except ImportError:\n        pass\n\n    try:\n        # Patch distutils._msvccompiler.gen_lib_options for Numpy\n        patch_func(*msvc14('gen_lib_options'))\n    except ImportError:\n        pass\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/msvc.py",
    "content": "\"\"\"\nImproved support for Microsoft Visual C++ compilers.\n\nKnown supported compilers:\n--------------------------\nMicrosoft Visual C++ 14.X:\n    Microsoft Visual C++ Build Tools 2015 (x86, x64, arm)\n    Microsoft Visual Studio Build Tools 2017 (x86, x64, arm, arm64)\n    Microsoft Visual Studio Build Tools 2019 (x86, x64, arm, arm64)\n\nThis may also support compilers shipped with compatible Visual Studio versions.\n\"\"\"\n\nimport json\nfrom io import open\nfrom os import listdir, pathsep\nfrom os.path import join, isfile, isdir, dirname\nimport sys\nimport contextlib\nimport platform\nimport itertools\nimport subprocess\nimport distutils.errors\nfrom setuptools.extern.packaging.version import LegacyVersion\nfrom setuptools.extern.more_itertools import unique_everseen\n\nfrom .monkey import get_unpatched\n\nif platform.system() == 'Windows':\n    import winreg\n    from os import environ\nelse:\n    # Mock winreg and environ so the module can be imported on this platform.\n\n    class winreg:\n        HKEY_USERS = None\n        HKEY_CURRENT_USER = None\n        HKEY_LOCAL_MACHINE = None\n        HKEY_CLASSES_ROOT = None\n\n    environ = dict()\n\n\ndef _msvc14_find_vc2015():\n    \"\"\"Python 3.8 \"distutils/_msvccompiler.py\" backport\"\"\"\n    try:\n        key = winreg.OpenKey(\n            winreg.HKEY_LOCAL_MACHINE,\n            r\"Software\\Microsoft\\VisualStudio\\SxS\\VC7\",\n            0,\n            winreg.KEY_READ | winreg.KEY_WOW64_32KEY\n        )\n    except OSError:\n        return None, None\n\n    best_version = 0\n    best_dir = None\n    with key:\n        for i in itertools.count():\n            try:\n                v, vc_dir, vt = winreg.EnumValue(key, i)\n            except OSError:\n                break\n            if v and vt == winreg.REG_SZ and isdir(vc_dir):\n                try:\n                    version = int(float(v))\n                except (ValueError, TypeError):\n                    continue\n                if version >= 14 and version > best_version:\n                    best_version, best_dir = version, vc_dir\n    return best_version, best_dir\n\n\ndef _msvc14_find_vc2017():\n    \"\"\"Python 3.8 \"distutils/_msvccompiler.py\" backport\n\n    Returns \"15, path\" based on the result of invoking vswhere.exe\n    If no install is found, returns \"None, None\"\n\n    The version is returned to avoid unnecessarily changing the function\n    result. It may be ignored when the path is not None.\n\n    If vswhere.exe is not available, by definition, VS 2017 is not\n    installed.\n    \"\"\"\n    root = environ.get(\"ProgramFiles(x86)\") or environ.get(\"ProgramFiles\")\n    if not root:\n        return None, None\n\n    try:\n        path = subprocess.check_output([\n            join(root, \"Microsoft Visual Studio\", \"Installer\", \"vswhere.exe\"),\n            \"-latest\",\n            \"-prerelease\",\n            \"-requiresAny\",\n            \"-requires\", \"Microsoft.VisualStudio.Component.VC.Tools.x86.x64\",\n            \"-requires\", \"Microsoft.VisualStudio.Workload.WDExpress\",\n            \"-property\", \"installationPath\",\n            \"-products\", \"*\",\n        ]).decode(encoding=\"mbcs\", errors=\"strict\").strip()\n    except (subprocess.CalledProcessError, OSError, UnicodeDecodeError):\n        return None, None\n\n    path = join(path, \"VC\", \"Auxiliary\", \"Build\")\n    if isdir(path):\n        return 15, path\n\n    return None, None\n\n\nPLAT_SPEC_TO_RUNTIME = {\n    'x86': 'x86',\n    'x86_amd64': 'x64',\n    'x86_arm': 'arm',\n    'x86_arm64': 'arm64'\n}\n\n\ndef _msvc14_find_vcvarsall(plat_spec):\n    \"\"\"Python 3.8 \"distutils/_msvccompiler.py\" backport\"\"\"\n    _, best_dir = _msvc14_find_vc2017()\n    vcruntime = None\n\n    if plat_spec in PLAT_SPEC_TO_RUNTIME:\n        vcruntime_plat = PLAT_SPEC_TO_RUNTIME[plat_spec]\n    else:\n        vcruntime_plat = 'x64' if 'amd64' in plat_spec else 'x86'\n\n    if best_dir:\n        vcredist = join(best_dir, \"..\", \"..\", \"redist\", \"MSVC\", \"**\",\n                        vcruntime_plat, \"Microsoft.VC14*.CRT\",\n                        \"vcruntime140.dll\")\n        try:\n            import glob\n            vcruntime = glob.glob(vcredist, recursive=True)[-1]\n        except (ImportError, OSError, LookupError):\n            vcruntime = None\n\n    if not best_dir:\n        best_version, best_dir = _msvc14_find_vc2015()\n        if best_version:\n            vcruntime = join(best_dir, 'redist', vcruntime_plat,\n                             \"Microsoft.VC140.CRT\", \"vcruntime140.dll\")\n\n    if not best_dir:\n        return None, None\n\n    vcvarsall = join(best_dir, \"vcvarsall.bat\")\n    if not isfile(vcvarsall):\n        return None, None\n\n    if not vcruntime or not isfile(vcruntime):\n        vcruntime = None\n\n    return vcvarsall, vcruntime\n\n\ndef _msvc14_get_vc_env(plat_spec):\n    \"\"\"Python 3.8 \"distutils/_msvccompiler.py\" backport\"\"\"\n    if \"DISTUTILS_USE_SDK\" in environ:\n        return {\n            key.lower(): value\n            for key, value in environ.items()\n        }\n\n    vcvarsall, vcruntime = _msvc14_find_vcvarsall(plat_spec)\n    if not vcvarsall:\n        raise distutils.errors.DistutilsPlatformError(\n            \"Unable to find vcvarsall.bat\"\n        )\n\n    try:\n        out = subprocess.check_output(\n            'cmd /u /c \"{}\" {} && set'.format(vcvarsall, plat_spec),\n            stderr=subprocess.STDOUT,\n        ).decode('utf-16le', errors='replace')\n    except subprocess.CalledProcessError as exc:\n        raise distutils.errors.DistutilsPlatformError(\n            \"Error executing {}\".format(exc.cmd)\n        ) from exc\n\n    env = {\n        key.lower(): value\n        for key, _, value in\n        (line.partition('=') for line in out.splitlines())\n        if key and value\n    }\n\n    if vcruntime:\n        env['py_vcruntime_redist'] = vcruntime\n    return env\n\n\ndef msvc14_get_vc_env(plat_spec):\n    \"\"\"\n    Patched \"distutils._msvccompiler._get_vc_env\" for support extra\n    Microsoft Visual C++ 14.X compilers.\n\n    Set environment without use of \"vcvarsall.bat\".\n\n    Parameters\n    ----------\n    plat_spec: str\n        Target architecture.\n\n    Return\n    ------\n    dict\n        environment\n    \"\"\"\n\n    # Always use backport from CPython 3.8\n    try:\n        return _msvc14_get_vc_env(plat_spec)\n    except distutils.errors.DistutilsPlatformError as exc:\n        _augment_exception(exc, 14.0)\n        raise\n\n\ndef msvc14_gen_lib_options(*args, **kwargs):\n    \"\"\"\n    Patched \"distutils._msvccompiler.gen_lib_options\" for fix\n    compatibility between \"numpy.distutils\" and \"distutils._msvccompiler\"\n    (for Numpy < 1.11.2)\n    \"\"\"\n    if \"numpy.distutils\" in sys.modules:\n        import numpy as np\n        if LegacyVersion(np.__version__) < LegacyVersion('1.11.2'):\n            return np.distutils.ccompiler.gen_lib_options(*args, **kwargs)\n    return get_unpatched(msvc14_gen_lib_options)(*args, **kwargs)\n\n\ndef _augment_exception(exc, version, arch=''):\n    \"\"\"\n    Add details to the exception message to help guide the user\n    as to what action will resolve it.\n    \"\"\"\n    # Error if MSVC++ directory not found or environment not set\n    message = exc.args[0]\n\n    if \"vcvarsall\" in message.lower() or \"visual c\" in message.lower():\n        # Special error message if MSVC++ not installed\n        tmpl = 'Microsoft Visual C++ {version:0.1f} or greater is required.'\n        message = tmpl.format(**locals())\n        msdownload = 'www.microsoft.com/download/details.aspx?id=%d'\n        if version == 9.0:\n            if arch.lower().find('ia64') > -1:\n                # For VC++ 9.0, if IA64 support is needed, redirect user\n                # to Windows SDK 7.0.\n                # Note: No download link available from Microsoft.\n                message += ' Get it with \"Microsoft Windows SDK 7.0\"'\n            else:\n                # For VC++ 9.0 redirect user to Vc++ for Python 2.7 :\n                # This redirection link is maintained by Microsoft.\n                # Contact vspython@microsoft.com if it needs updating.\n                message += ' Get it from http://aka.ms/vcpython27'\n        elif version == 10.0:\n            # For VC++ 10.0 Redirect user to Windows SDK 7.1\n            message += ' Get it with \"Microsoft Windows SDK 7.1\": '\n            message += msdownload % 8279\n        elif version >= 14.0:\n            # For VC++ 14.X Redirect user to latest Visual C++ Build Tools\n            message += (' Get it with \"Microsoft C++ Build Tools\": '\n                        r'https://visualstudio.microsoft.com'\n                        r'/visual-cpp-build-tools/')\n\n    exc.args = (message, )\n\n\nclass PlatformInfo:\n    \"\"\"\n    Current and Target Architectures information.\n\n    Parameters\n    ----------\n    arch: str\n        Target architecture.\n    \"\"\"\n    current_cpu = environ.get('processor_architecture', '').lower()\n\n    def __init__(self, arch):\n        self.arch = arch.lower().replace('x64', 'amd64')\n\n    @property\n    def target_cpu(self):\n        \"\"\"\n        Return Target CPU architecture.\n\n        Return\n        ------\n        str\n            Target CPU\n        \"\"\"\n        return self.arch[self.arch.find('_') + 1:]\n\n    def target_is_x86(self):\n        \"\"\"\n        Return True if target CPU is x86 32 bits..\n\n        Return\n        ------\n        bool\n            CPU is x86 32 bits\n        \"\"\"\n        return self.target_cpu == 'x86'\n\n    def current_is_x86(self):\n        \"\"\"\n        Return True if current CPU is x86 32 bits..\n\n        Return\n        ------\n        bool\n            CPU is x86 32 bits\n        \"\"\"\n        return self.current_cpu == 'x86'\n\n    def current_dir(self, hidex86=False, x64=False):\n        \"\"\"\n        Current platform specific subfolder.\n\n        Parameters\n        ----------\n        hidex86: bool\n            return '' and not '\\x86' if architecture is x86.\n        x64: bool\n            return '\\x64' and not '\\amd64' if architecture is amd64.\n\n        Return\n        ------\n        str\n            subfolder: '\\target', or '' (see hidex86 parameter)\n        \"\"\"\n        return (\n            '' if (self.current_cpu == 'x86' and hidex86) else\n            r'\\x64' if (self.current_cpu == 'amd64' and x64) else\n            r'\\%s' % self.current_cpu\n        )\n\n    def target_dir(self, hidex86=False, x64=False):\n        r\"\"\"\n        Target platform specific subfolder.\n\n        Parameters\n        ----------\n        hidex86: bool\n            return '' and not '\\x86' if architecture is x86.\n        x64: bool\n            return '\\x64' and not '\\amd64' if architecture is amd64.\n\n        Return\n        ------\n        str\n            subfolder: '\\current', or '' (see hidex86 parameter)\n        \"\"\"\n        return (\n            '' if (self.target_cpu == 'x86' and hidex86) else\n            r'\\x64' if (self.target_cpu == 'amd64' and x64) else\n            r'\\%s' % self.target_cpu\n        )\n\n    def cross_dir(self, forcex86=False):\n        r\"\"\"\n        Cross platform specific subfolder.\n\n        Parameters\n        ----------\n        forcex86: bool\n            Use 'x86' as current architecture even if current architecture is\n            not x86.\n\n        Return\n        ------\n        str\n            subfolder: '' if target architecture is current architecture,\n            '\\current_target' if not.\n        \"\"\"\n        current = 'x86' if forcex86 else self.current_cpu\n        return (\n            '' if self.target_cpu == current else\n            self.target_dir().replace('\\\\', '\\\\%s_' % current)\n        )\n\n\nclass RegistryInfo:\n    \"\"\"\n    Microsoft Visual Studio related registry information.\n\n    Parameters\n    ----------\n    platform_info: PlatformInfo\n        \"PlatformInfo\" instance.\n    \"\"\"\n    HKEYS = (winreg.HKEY_USERS,\n             winreg.HKEY_CURRENT_USER,\n             winreg.HKEY_LOCAL_MACHINE,\n             winreg.HKEY_CLASSES_ROOT)\n\n    def __init__(self, platform_info):\n        self.pi = platform_info\n\n    @property\n    def visualstudio(self):\n        \"\"\"\n        Microsoft Visual Studio root registry key.\n\n        Return\n        ------\n        str\n            Registry key\n        \"\"\"\n        return 'VisualStudio'\n\n    @property\n    def sxs(self):\n        \"\"\"\n        Microsoft Visual Studio SxS registry key.\n\n        Return\n        ------\n        str\n            Registry key\n        \"\"\"\n        return join(self.visualstudio, 'SxS')\n\n    @property\n    def vc(self):\n        \"\"\"\n        Microsoft Visual C++ VC7 registry key.\n\n        Return\n        ------\n        str\n            Registry key\n        \"\"\"\n        return join(self.sxs, 'VC7')\n\n    @property\n    def vs(self):\n        \"\"\"\n        Microsoft Visual Studio VS7 registry key.\n\n        Return\n        ------\n        str\n            Registry key\n        \"\"\"\n        return join(self.sxs, 'VS7')\n\n    @property\n    def vc_for_python(self):\n        \"\"\"\n        Microsoft Visual C++ for Python registry key.\n\n        Return\n        ------\n        str\n            Registry key\n        \"\"\"\n        return r'DevDiv\\VCForPython'\n\n    @property\n    def microsoft_sdk(self):\n        \"\"\"\n        Microsoft SDK registry key.\n\n        Return\n        ------\n        str\n            Registry key\n        \"\"\"\n        return 'Microsoft SDKs'\n\n    @property\n    def windows_sdk(self):\n        \"\"\"\n        Microsoft Windows/Platform SDK registry key.\n\n        Return\n        ------\n        str\n            Registry key\n        \"\"\"\n        return join(self.microsoft_sdk, 'Windows')\n\n    @property\n    def netfx_sdk(self):\n        \"\"\"\n        Microsoft .NET Framework SDK registry key.\n\n        Return\n        ------\n        str\n            Registry key\n        \"\"\"\n        return join(self.microsoft_sdk, 'NETFXSDK')\n\n    @property\n    def windows_kits_roots(self):\n        \"\"\"\n        Microsoft Windows Kits Roots registry key.\n\n        Return\n        ------\n        str\n            Registry key\n        \"\"\"\n        return r'Windows Kits\\Installed Roots'\n\n    def microsoft(self, key, x86=False):\n        \"\"\"\n        Return key in Microsoft software registry.\n\n        Parameters\n        ----------\n        key: str\n            Registry key path where look.\n        x86: str\n            Force x86 software registry.\n\n        Return\n        ------\n        str\n            Registry key\n        \"\"\"\n        node64 = '' if self.pi.current_is_x86() or x86 else 'Wow6432Node'\n        return join('Software', node64, 'Microsoft', key)\n\n    def lookup(self, key, name):\n        \"\"\"\n        Look for values in registry in Microsoft software registry.\n\n        Parameters\n        ----------\n        key: str\n            Registry key path where look.\n        name: str\n            Value name to find.\n\n        Return\n        ------\n        str\n            value\n        \"\"\"\n        key_read = winreg.KEY_READ\n        openkey = winreg.OpenKey\n        closekey = winreg.CloseKey\n        ms = self.microsoft\n        for hkey in self.HKEYS:\n            bkey = None\n            try:\n                bkey = openkey(hkey, ms(key), 0, key_read)\n            except (OSError, IOError):\n                if not self.pi.current_is_x86():\n                    try:\n                        bkey = openkey(hkey, ms(key, True), 0, key_read)\n                    except (OSError, IOError):\n                        continue\n                else:\n                    continue\n            try:\n                return winreg.QueryValueEx(bkey, name)[0]\n            except (OSError, IOError):\n                pass\n            finally:\n                if bkey:\n                    closekey(bkey)\n\n\nclass SystemInfo:\n    \"\"\"\n    Microsoft Windows and Visual Studio related system information.\n\n    Parameters\n    ----------\n    registry_info: RegistryInfo\n        \"RegistryInfo\" instance.\n    vc_ver: float\n        Required Microsoft Visual C++ version.\n    \"\"\"\n\n    # Variables and properties in this class use originals CamelCase variables\n    # names from Microsoft source files for more easy comparison.\n    WinDir = environ.get('WinDir', '')\n    ProgramFiles = environ.get('ProgramFiles', '')\n    ProgramFilesx86 = environ.get('ProgramFiles(x86)', ProgramFiles)\n\n    def __init__(self, registry_info, vc_ver=None):\n        self.ri = registry_info\n        self.pi = self.ri.pi\n\n        self.known_vs_paths = self.find_programdata_vs_vers()\n\n        # Except for VS15+, VC version is aligned with VS version\n        self.vs_ver = self.vc_ver = (\n            vc_ver or self._find_latest_available_vs_ver())\n\n    def _find_latest_available_vs_ver(self):\n        \"\"\"\n        Find the latest VC version\n\n        Return\n        ------\n        float\n            version\n        \"\"\"\n        reg_vc_vers = self.find_reg_vs_vers()\n\n        if not (reg_vc_vers or self.known_vs_paths):\n            raise distutils.errors.DistutilsPlatformError(\n                'No Microsoft Visual C++ version found')\n\n        vc_vers = set(reg_vc_vers)\n        vc_vers.update(self.known_vs_paths)\n        return sorted(vc_vers)[-1]\n\n    def find_reg_vs_vers(self):\n        \"\"\"\n        Find Microsoft Visual Studio versions available in registry.\n\n        Return\n        ------\n        list of float\n            Versions\n        \"\"\"\n        ms = self.ri.microsoft\n        vckeys = (self.ri.vc, self.ri.vc_for_python, self.ri.vs)\n        vs_vers = []\n        for hkey, key in itertools.product(self.ri.HKEYS, vckeys):\n            try:\n                bkey = winreg.OpenKey(hkey, ms(key), 0, winreg.KEY_READ)\n            except (OSError, IOError):\n                continue\n            with bkey:\n                subkeys, values, _ = winreg.QueryInfoKey(bkey)\n                for i in range(values):\n                    with contextlib.suppress(ValueError):\n                        ver = float(winreg.EnumValue(bkey, i)[0])\n                        if ver not in vs_vers:\n                            vs_vers.append(ver)\n                for i in range(subkeys):\n                    with contextlib.suppress(ValueError):\n                        ver = float(winreg.EnumKey(bkey, i))\n                        if ver not in vs_vers:\n                            vs_vers.append(ver)\n        return sorted(vs_vers)\n\n    def find_programdata_vs_vers(self):\n        r\"\"\"\n        Find Visual studio 2017+ versions from information in\n        \"C:\\ProgramData\\Microsoft\\VisualStudio\\Packages\\_Instances\".\n\n        Return\n        ------\n        dict\n            float version as key, path as value.\n        \"\"\"\n        vs_versions = {}\n        instances_dir = \\\n            r'C:\\ProgramData\\Microsoft\\VisualStudio\\Packages\\_Instances'\n\n        try:\n            hashed_names = listdir(instances_dir)\n\n        except (OSError, IOError):\n            # Directory not exists with all Visual Studio versions\n            return vs_versions\n\n        for name in hashed_names:\n            try:\n                # Get VS installation path from \"state.json\" file\n                state_path = join(instances_dir, name, 'state.json')\n                with open(state_path, 'rt', encoding='utf-8') as state_file:\n                    state = json.load(state_file)\n                vs_path = state['installationPath']\n\n                # Raises OSError if this VS installation does not contain VC\n                listdir(join(vs_path, r'VC\\Tools\\MSVC'))\n\n                # Store version and path\n                vs_versions[self._as_float_version(\n                    state['installationVersion'])] = vs_path\n\n            except (OSError, IOError, KeyError):\n                # Skip if \"state.json\" file is missing or bad format\n                continue\n\n        return vs_versions\n\n    @staticmethod\n    def _as_float_version(version):\n        \"\"\"\n        Return a string version as a simplified float version (major.minor)\n\n        Parameters\n        ----------\n        version: str\n            Version.\n\n        Return\n        ------\n        float\n            version\n        \"\"\"\n        return float('.'.join(version.split('.')[:2]))\n\n    @property\n    def VSInstallDir(self):\n        \"\"\"\n        Microsoft Visual Studio directory.\n\n        Return\n        ------\n        str\n            path\n        \"\"\"\n        # Default path\n        default = join(self.ProgramFilesx86,\n                       'Microsoft Visual Studio %0.1f' % self.vs_ver)\n\n        # Try to get path from registry, if fail use default path\n        return self.ri.lookup(self.ri.vs, '%0.1f' % self.vs_ver) or default\n\n    @property\n    def VCInstallDir(self):\n        \"\"\"\n        Microsoft Visual C++ directory.\n\n        Return\n        ------\n        str\n            path\n        \"\"\"\n        path = self._guess_vc() or self._guess_vc_legacy()\n\n        if not isdir(path):\n            msg = 'Microsoft Visual C++ directory not found'\n            raise distutils.errors.DistutilsPlatformError(msg)\n\n        return path\n\n    def _guess_vc(self):\n        \"\"\"\n        Locate Visual C++ for VS2017+.\n\n        Return\n        ------\n        str\n            path\n        \"\"\"\n        if self.vs_ver <= 14.0:\n            return ''\n\n        try:\n            # First search in known VS paths\n            vs_dir = self.known_vs_paths[self.vs_ver]\n        except KeyError:\n            # Else, search with path from registry\n            vs_dir = self.VSInstallDir\n\n        guess_vc = join(vs_dir, r'VC\\Tools\\MSVC')\n\n        # Subdir with VC exact version as name\n        try:\n            # Update the VC version with real one instead of VS version\n            vc_ver = listdir(guess_vc)[-1]\n            self.vc_ver = self._as_float_version(vc_ver)\n            return join(guess_vc, vc_ver)\n        except (OSError, IOError, IndexError):\n            return ''\n\n    def _guess_vc_legacy(self):\n        \"\"\"\n        Locate Visual C++ for versions prior to 2017.\n\n        Return\n        ------\n        str\n            path\n        \"\"\"\n        default = join(self.ProgramFilesx86,\n                       r'Microsoft Visual Studio %0.1f\\VC' % self.vs_ver)\n\n        # Try to get \"VC++ for Python\" path from registry as default path\n        reg_path = join(self.ri.vc_for_python, '%0.1f' % self.vs_ver)\n        python_vc = self.ri.lookup(reg_path, 'installdir')\n        default_vc = join(python_vc, 'VC') if python_vc else default\n\n        # Try to get path from registry, if fail use default path\n        return self.ri.lookup(self.ri.vc, '%0.1f' % self.vs_ver) or default_vc\n\n    @property\n    def WindowsSdkVersion(self):\n        \"\"\"\n        Microsoft Windows SDK versions for specified MSVC++ version.\n\n        Return\n        ------\n        tuple of str\n            versions\n        \"\"\"\n        if self.vs_ver <= 9.0:\n            return '7.0', '6.1', '6.0a'\n        elif self.vs_ver == 10.0:\n            return '7.1', '7.0a'\n        elif self.vs_ver == 11.0:\n            return '8.0', '8.0a'\n        elif self.vs_ver == 12.0:\n            return '8.1', '8.1a'\n        elif self.vs_ver >= 14.0:\n            return '10.0', '8.1'\n\n    @property\n    def WindowsSdkLastVersion(self):\n        \"\"\"\n        Microsoft Windows SDK last version.\n\n        Return\n        ------\n        str\n            version\n        \"\"\"\n        return self._use_last_dir_name(join(self.WindowsSdkDir, 'lib'))\n\n    @property  # noqa: C901\n    def WindowsSdkDir(self):  # noqa: C901  # is too complex (12)  # FIXME\n        \"\"\"\n        Microsoft Windows SDK directory.\n\n        Return\n        ------\n        str\n            path\n        \"\"\"\n        sdkdir = ''\n        for ver in self.WindowsSdkVersion:\n            # Try to get it from registry\n            loc = join(self.ri.windows_sdk, 'v%s' % ver)\n            sdkdir = self.ri.lookup(loc, 'installationfolder')\n            if sdkdir:\n                break\n        if not sdkdir or not isdir(sdkdir):\n            # Try to get \"VC++ for Python\" version from registry\n            path = join(self.ri.vc_for_python, '%0.1f' % self.vc_ver)\n            install_base = self.ri.lookup(path, 'installdir')\n            if install_base:\n                sdkdir = join(install_base, 'WinSDK')\n        if not sdkdir or not isdir(sdkdir):\n            # If fail, use default new path\n            for ver in self.WindowsSdkVersion:\n                intver = ver[:ver.rfind('.')]\n                path = r'Microsoft SDKs\\Windows Kits\\%s' % intver\n                d = join(self.ProgramFiles, path)\n                if isdir(d):\n                    sdkdir = d\n        if not sdkdir or not isdir(sdkdir):\n            # If fail, use default old path\n            for ver in self.WindowsSdkVersion:\n                path = r'Microsoft SDKs\\Windows\\v%s' % ver\n                d = join(self.ProgramFiles, path)\n                if isdir(d):\n                    sdkdir = d\n        if not sdkdir:\n            # If fail, use Platform SDK\n            sdkdir = join(self.VCInstallDir, 'PlatformSDK')\n        return sdkdir\n\n    @property\n    def WindowsSDKExecutablePath(self):\n        \"\"\"\n        Microsoft Windows SDK executable directory.\n\n        Return\n        ------\n        str\n            path\n        \"\"\"\n        # Find WinSDK NetFx Tools registry dir name\n        if self.vs_ver <= 11.0:\n            netfxver = 35\n            arch = ''\n        else:\n            netfxver = 40\n            hidex86 = True if self.vs_ver <= 12.0 else False\n            arch = self.pi.current_dir(x64=True, hidex86=hidex86)\n        fx = 'WinSDK-NetFx%dTools%s' % (netfxver, arch.replace('\\\\', '-'))\n\n        # list all possibles registry paths\n        regpaths = []\n        if self.vs_ver >= 14.0:\n            for ver in self.NetFxSdkVersion:\n                regpaths += [join(self.ri.netfx_sdk, ver, fx)]\n\n        for ver in self.WindowsSdkVersion:\n            regpaths += [join(self.ri.windows_sdk, 'v%sA' % ver, fx)]\n\n        # Return installation folder from the more recent path\n        for path in regpaths:\n            execpath = self.ri.lookup(path, 'installationfolder')\n            if execpath:\n                return execpath\n\n    @property\n    def FSharpInstallDir(self):\n        \"\"\"\n        Microsoft Visual F# directory.\n\n        Return\n        ------\n        str\n            path\n        \"\"\"\n        path = join(self.ri.visualstudio, r'%0.1f\\Setup\\F#' % self.vs_ver)\n        return self.ri.lookup(path, 'productdir') or ''\n\n    @property\n    def UniversalCRTSdkDir(self):\n        \"\"\"\n        Microsoft Universal CRT SDK directory.\n\n        Return\n        ------\n        str\n            path\n        \"\"\"\n        # Set Kit Roots versions for specified MSVC++ version\n        vers = ('10', '81') if self.vs_ver >= 14.0 else ()\n\n        # Find path of the more recent Kit\n        for ver in vers:\n            sdkdir = self.ri.lookup(self.ri.windows_kits_roots,\n                                    'kitsroot%s' % ver)\n            if sdkdir:\n                return sdkdir or ''\n\n    @property\n    def UniversalCRTSdkLastVersion(self):\n        \"\"\"\n        Microsoft Universal C Runtime SDK last version.\n\n        Return\n        ------\n        str\n            version\n        \"\"\"\n        return self._use_last_dir_name(join(self.UniversalCRTSdkDir, 'lib'))\n\n    @property\n    def NetFxSdkVersion(self):\n        \"\"\"\n        Microsoft .NET Framework SDK versions.\n\n        Return\n        ------\n        tuple of str\n            versions\n        \"\"\"\n        # Set FxSdk versions for specified VS version\n        return (('4.7.2', '4.7.1', '4.7',\n                 '4.6.2', '4.6.1', '4.6',\n                 '4.5.2', '4.5.1', '4.5')\n                if self.vs_ver >= 14.0 else ())\n\n    @property\n    def NetFxSdkDir(self):\n        \"\"\"\n        Microsoft .NET Framework SDK directory.\n\n        Return\n        ------\n        str\n            path\n        \"\"\"\n        sdkdir = ''\n        for ver in self.NetFxSdkVersion:\n            loc = join(self.ri.netfx_sdk, ver)\n            sdkdir = self.ri.lookup(loc, 'kitsinstallationfolder')\n            if sdkdir:\n                break\n        return sdkdir\n\n    @property\n    def FrameworkDir32(self):\n        \"\"\"\n        Microsoft .NET Framework 32bit directory.\n\n        Return\n        ------\n        str\n            path\n        \"\"\"\n        # Default path\n        guess_fw = join(self.WinDir, r'Microsoft.NET\\Framework')\n\n        # Try to get path from registry, if fail use default path\n        return self.ri.lookup(self.ri.vc, 'frameworkdir32') or guess_fw\n\n    @property\n    def FrameworkDir64(self):\n        \"\"\"\n        Microsoft .NET Framework 64bit directory.\n\n        Return\n        ------\n        str\n            path\n        \"\"\"\n        # Default path\n        guess_fw = join(self.WinDir, r'Microsoft.NET\\Framework64')\n\n        # Try to get path from registry, if fail use default path\n        return self.ri.lookup(self.ri.vc, 'frameworkdir64') or guess_fw\n\n    @property\n    def FrameworkVersion32(self):\n        \"\"\"\n        Microsoft .NET Framework 32bit versions.\n\n        Return\n        ------\n        tuple of str\n            versions\n        \"\"\"\n        return self._find_dot_net_versions(32)\n\n    @property\n    def FrameworkVersion64(self):\n        \"\"\"\n        Microsoft .NET Framework 64bit versions.\n\n        Return\n        ------\n        tuple of str\n            versions\n        \"\"\"\n        return self._find_dot_net_versions(64)\n\n    def _find_dot_net_versions(self, bits):\n        \"\"\"\n        Find Microsoft .NET Framework versions.\n\n        Parameters\n        ----------\n        bits: int\n            Platform number of bits: 32 or 64.\n\n        Return\n        ------\n        tuple of str\n            versions\n        \"\"\"\n        # Find actual .NET version in registry\n        reg_ver = self.ri.lookup(self.ri.vc, 'frameworkver%d' % bits)\n        dot_net_dir = getattr(self, 'FrameworkDir%d' % bits)\n        ver = reg_ver or self._use_last_dir_name(dot_net_dir, 'v') or ''\n\n        # Set .NET versions for specified MSVC++ version\n        if self.vs_ver >= 12.0:\n            return ver, 'v4.0'\n        elif self.vs_ver >= 10.0:\n            return 'v4.0.30319' if ver.lower()[:2] != 'v4' else ver, 'v3.5'\n        elif self.vs_ver == 9.0:\n            return 'v3.5', 'v2.0.50727'\n        elif self.vs_ver == 8.0:\n            return 'v3.0', 'v2.0.50727'\n\n    @staticmethod\n    def _use_last_dir_name(path, prefix=''):\n        \"\"\"\n        Return name of the last dir in path or '' if no dir found.\n\n        Parameters\n        ----------\n        path: str\n            Use dirs in this path\n        prefix: str\n            Use only dirs starting by this prefix\n\n        Return\n        ------\n        str\n            name\n        \"\"\"\n        matching_dirs = (\n            dir_name\n            for dir_name in reversed(listdir(path))\n            if isdir(join(path, dir_name)) and\n            dir_name.startswith(prefix)\n        )\n        return next(matching_dirs, None) or ''\n\n\nclass EnvironmentInfo:\n    \"\"\"\n    Return environment variables for specified Microsoft Visual C++ version\n    and platform : Lib, Include, Path and libpath.\n\n    This function is compatible with Microsoft Visual C++ 9.0 to 14.X.\n\n    Script created by analysing Microsoft environment configuration files like\n    \"vcvars[...].bat\", \"SetEnv.Cmd\", \"vcbuildtools.bat\", ...\n\n    Parameters\n    ----------\n    arch: str\n        Target architecture.\n    vc_ver: float\n        Required Microsoft Visual C++ version. If not set, autodetect the last\n        version.\n    vc_min_ver: float\n        Minimum Microsoft Visual C++ version.\n    \"\"\"\n\n    # Variables and properties in this class use originals CamelCase variables\n    # names from Microsoft source files for more easy comparison.\n\n    def __init__(self, arch, vc_ver=None, vc_min_ver=0):\n        self.pi = PlatformInfo(arch)\n        self.ri = RegistryInfo(self.pi)\n        self.si = SystemInfo(self.ri, vc_ver)\n\n        if self.vc_ver < vc_min_ver:\n            err = 'No suitable Microsoft Visual C++ version found'\n            raise distutils.errors.DistutilsPlatformError(err)\n\n    @property\n    def vs_ver(self):\n        \"\"\"\n        Microsoft Visual Studio.\n\n        Return\n        ------\n        float\n            version\n        \"\"\"\n        return self.si.vs_ver\n\n    @property\n    def vc_ver(self):\n        \"\"\"\n        Microsoft Visual C++ version.\n\n        Return\n        ------\n        float\n            version\n        \"\"\"\n        return self.si.vc_ver\n\n    @property\n    def VSTools(self):\n        \"\"\"\n        Microsoft Visual Studio Tools.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        paths = [r'Common7\\IDE', r'Common7\\Tools']\n\n        if self.vs_ver >= 14.0:\n            arch_subdir = self.pi.current_dir(hidex86=True, x64=True)\n            paths += [r'Common7\\IDE\\CommonExtensions\\Microsoft\\TestWindow']\n            paths += [r'Team Tools\\Performance Tools']\n            paths += [r'Team Tools\\Performance Tools%s' % arch_subdir]\n\n        return [join(self.si.VSInstallDir, path) for path in paths]\n\n    @property\n    def VCIncludes(self):\n        \"\"\"\n        Microsoft Visual C++ & Microsoft Foundation Class Includes.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        return [join(self.si.VCInstallDir, 'Include'),\n                join(self.si.VCInstallDir, r'ATLMFC\\Include')]\n\n    @property\n    def VCLibraries(self):\n        \"\"\"\n        Microsoft Visual C++ & Microsoft Foundation Class Libraries.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        if self.vs_ver >= 15.0:\n            arch_subdir = self.pi.target_dir(x64=True)\n        else:\n            arch_subdir = self.pi.target_dir(hidex86=True)\n        paths = ['Lib%s' % arch_subdir, r'ATLMFC\\Lib%s' % arch_subdir]\n\n        if self.vs_ver >= 14.0:\n            paths += [r'Lib\\store%s' % arch_subdir]\n\n        return [join(self.si.VCInstallDir, path) for path in paths]\n\n    @property\n    def VCStoreRefs(self):\n        \"\"\"\n        Microsoft Visual C++ store references Libraries.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        if self.vs_ver < 14.0:\n            return []\n        return [join(self.si.VCInstallDir, r'Lib\\store\\references')]\n\n    @property\n    def VCTools(self):\n        \"\"\"\n        Microsoft Visual C++ Tools.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        si = self.si\n        tools = [join(si.VCInstallDir, 'VCPackages')]\n\n        forcex86 = True if self.vs_ver <= 10.0 else False\n        arch_subdir = self.pi.cross_dir(forcex86)\n        if arch_subdir:\n            tools += [join(si.VCInstallDir, 'Bin%s' % arch_subdir)]\n\n        if self.vs_ver == 14.0:\n            path = 'Bin%s' % self.pi.current_dir(hidex86=True)\n            tools += [join(si.VCInstallDir, path)]\n\n        elif self.vs_ver >= 15.0:\n            host_dir = (r'bin\\HostX86%s' if self.pi.current_is_x86() else\n                        r'bin\\HostX64%s')\n            tools += [join(\n                si.VCInstallDir, host_dir % self.pi.target_dir(x64=True))]\n\n            if self.pi.current_cpu != self.pi.target_cpu:\n                tools += [join(\n                    si.VCInstallDir, host_dir % self.pi.current_dir(x64=True))]\n\n        else:\n            tools += [join(si.VCInstallDir, 'Bin')]\n\n        return tools\n\n    @property\n    def OSLibraries(self):\n        \"\"\"\n        Microsoft Windows SDK Libraries.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        if self.vs_ver <= 10.0:\n            arch_subdir = self.pi.target_dir(hidex86=True, x64=True)\n            return [join(self.si.WindowsSdkDir, 'Lib%s' % arch_subdir)]\n\n        else:\n            arch_subdir = self.pi.target_dir(x64=True)\n            lib = join(self.si.WindowsSdkDir, 'lib')\n            libver = self._sdk_subdir\n            return [join(lib, '%sum%s' % (libver, arch_subdir))]\n\n    @property\n    def OSIncludes(self):\n        \"\"\"\n        Microsoft Windows SDK Include.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        include = join(self.si.WindowsSdkDir, 'include')\n\n        if self.vs_ver <= 10.0:\n            return [include, join(include, 'gl')]\n\n        else:\n            if self.vs_ver >= 14.0:\n                sdkver = self._sdk_subdir\n            else:\n                sdkver = ''\n            return [join(include, '%sshared' % sdkver),\n                    join(include, '%sum' % sdkver),\n                    join(include, '%swinrt' % sdkver)]\n\n    @property\n    def OSLibpath(self):\n        \"\"\"\n        Microsoft Windows SDK Libraries Paths.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        ref = join(self.si.WindowsSdkDir, 'References')\n        libpath = []\n\n        if self.vs_ver <= 9.0:\n            libpath += self.OSLibraries\n\n        if self.vs_ver >= 11.0:\n            libpath += [join(ref, r'CommonConfiguration\\Neutral')]\n\n        if self.vs_ver >= 14.0:\n            libpath += [\n                ref,\n                join(self.si.WindowsSdkDir, 'UnionMetadata'),\n                join(\n                    ref, 'Windows.Foundation.UniversalApiContract', '1.0.0.0'),\n                join(ref, 'Windows.Foundation.FoundationContract', '1.0.0.0'),\n                join(\n                    ref, 'Windows.Networking.Connectivity.WwanContract',\n                    '1.0.0.0'),\n                join(\n                    self.si.WindowsSdkDir, 'ExtensionSDKs', 'Microsoft.VCLibs',\n                    '%0.1f' % self.vs_ver, 'References', 'CommonConfiguration',\n                    'neutral'),\n            ]\n        return libpath\n\n    @property\n    def SdkTools(self):\n        \"\"\"\n        Microsoft Windows SDK Tools.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        return list(self._sdk_tools())\n\n    def _sdk_tools(self):\n        \"\"\"\n        Microsoft Windows SDK Tools paths generator.\n\n        Return\n        ------\n        generator of str\n            paths\n        \"\"\"\n        if self.vs_ver < 15.0:\n            bin_dir = 'Bin' if self.vs_ver <= 11.0 else r'Bin\\x86'\n            yield join(self.si.WindowsSdkDir, bin_dir)\n\n        if not self.pi.current_is_x86():\n            arch_subdir = self.pi.current_dir(x64=True)\n            path = 'Bin%s' % arch_subdir\n            yield join(self.si.WindowsSdkDir, path)\n\n        if self.vs_ver in (10.0, 11.0):\n            if self.pi.target_is_x86():\n                arch_subdir = ''\n            else:\n                arch_subdir = self.pi.current_dir(hidex86=True, x64=True)\n            path = r'Bin\\NETFX 4.0 Tools%s' % arch_subdir\n            yield join(self.si.WindowsSdkDir, path)\n\n        elif self.vs_ver >= 15.0:\n            path = join(self.si.WindowsSdkDir, 'Bin')\n            arch_subdir = self.pi.current_dir(x64=True)\n            sdkver = self.si.WindowsSdkLastVersion\n            yield join(path, '%s%s' % (sdkver, arch_subdir))\n\n        if self.si.WindowsSDKExecutablePath:\n            yield self.si.WindowsSDKExecutablePath\n\n    @property\n    def _sdk_subdir(self):\n        \"\"\"\n        Microsoft Windows SDK version subdir.\n\n        Return\n        ------\n        str\n            subdir\n        \"\"\"\n        ucrtver = self.si.WindowsSdkLastVersion\n        return ('%s\\\\' % ucrtver) if ucrtver else ''\n\n    @property\n    def SdkSetup(self):\n        \"\"\"\n        Microsoft Windows SDK Setup.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        if self.vs_ver > 9.0:\n            return []\n\n        return [join(self.si.WindowsSdkDir, 'Setup')]\n\n    @property\n    def FxTools(self):\n        \"\"\"\n        Microsoft .NET Framework Tools.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        pi = self.pi\n        si = self.si\n\n        if self.vs_ver <= 10.0:\n            include32 = True\n            include64 = not pi.target_is_x86() and not pi.current_is_x86()\n        else:\n            include32 = pi.target_is_x86() or pi.current_is_x86()\n            include64 = pi.current_cpu == 'amd64' or pi.target_cpu == 'amd64'\n\n        tools = []\n        if include32:\n            tools += [join(si.FrameworkDir32, ver)\n                      for ver in si.FrameworkVersion32]\n        if include64:\n            tools += [join(si.FrameworkDir64, ver)\n                      for ver in si.FrameworkVersion64]\n        return tools\n\n    @property\n    def NetFxSDKLibraries(self):\n        \"\"\"\n        Microsoft .Net Framework SDK Libraries.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        if self.vs_ver < 14.0 or not self.si.NetFxSdkDir:\n            return []\n\n        arch_subdir = self.pi.target_dir(x64=True)\n        return [join(self.si.NetFxSdkDir, r'lib\\um%s' % arch_subdir)]\n\n    @property\n    def NetFxSDKIncludes(self):\n        \"\"\"\n        Microsoft .Net Framework SDK Includes.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        if self.vs_ver < 14.0 or not self.si.NetFxSdkDir:\n            return []\n\n        return [join(self.si.NetFxSdkDir, r'include\\um')]\n\n    @property\n    def VsTDb(self):\n        \"\"\"\n        Microsoft Visual Studio Team System Database.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        return [join(self.si.VSInstallDir, r'VSTSDB\\Deploy')]\n\n    @property\n    def MSBuild(self):\n        \"\"\"\n        Microsoft Build Engine.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        if self.vs_ver < 12.0:\n            return []\n        elif self.vs_ver < 15.0:\n            base_path = self.si.ProgramFilesx86\n            arch_subdir = self.pi.current_dir(hidex86=True)\n        else:\n            base_path = self.si.VSInstallDir\n            arch_subdir = ''\n\n        path = r'MSBuild\\%0.1f\\bin%s' % (self.vs_ver, arch_subdir)\n        build = [join(base_path, path)]\n\n        if self.vs_ver >= 15.0:\n            # Add Roslyn C# & Visual Basic Compiler\n            build += [join(base_path, path, 'Roslyn')]\n\n        return build\n\n    @property\n    def HTMLHelpWorkshop(self):\n        \"\"\"\n        Microsoft HTML Help Workshop.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        if self.vs_ver < 11.0:\n            return []\n\n        return [join(self.si.ProgramFilesx86, 'HTML Help Workshop')]\n\n    @property\n    def UCRTLibraries(self):\n        \"\"\"\n        Microsoft Universal C Runtime SDK Libraries.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        if self.vs_ver < 14.0:\n            return []\n\n        arch_subdir = self.pi.target_dir(x64=True)\n        lib = join(self.si.UniversalCRTSdkDir, 'lib')\n        ucrtver = self._ucrt_subdir\n        return [join(lib, '%sucrt%s' % (ucrtver, arch_subdir))]\n\n    @property\n    def UCRTIncludes(self):\n        \"\"\"\n        Microsoft Universal C Runtime SDK Include.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        if self.vs_ver < 14.0:\n            return []\n\n        include = join(self.si.UniversalCRTSdkDir, 'include')\n        return [join(include, '%sucrt' % self._ucrt_subdir)]\n\n    @property\n    def _ucrt_subdir(self):\n        \"\"\"\n        Microsoft Universal C Runtime SDK version subdir.\n\n        Return\n        ------\n        str\n            subdir\n        \"\"\"\n        ucrtver = self.si.UniversalCRTSdkLastVersion\n        return ('%s\\\\' % ucrtver) if ucrtver else ''\n\n    @property\n    def FSharp(self):\n        \"\"\"\n        Microsoft Visual F#.\n\n        Return\n        ------\n        list of str\n            paths\n        \"\"\"\n        if 11.0 > self.vs_ver > 12.0:\n            return []\n\n        return [self.si.FSharpInstallDir]\n\n    @property\n    def VCRuntimeRedist(self):\n        \"\"\"\n        Microsoft Visual C++ runtime redistributable dll.\n\n        Return\n        ------\n        str\n            path\n        \"\"\"\n        vcruntime = 'vcruntime%d0.dll' % self.vc_ver\n        arch_subdir = self.pi.target_dir(x64=True).strip('\\\\')\n\n        # Installation prefixes candidates\n        prefixes = []\n        tools_path = self.si.VCInstallDir\n        redist_path = dirname(tools_path.replace(r'\\Tools', r'\\Redist'))\n        if isdir(redist_path):\n            # Redist version may not be exactly the same as tools\n            redist_path = join(redist_path, listdir(redist_path)[-1])\n            prefixes += [redist_path, join(redist_path, 'onecore')]\n\n        prefixes += [join(tools_path, 'redist')]  # VS14 legacy path\n\n        # CRT directory\n        crt_dirs = ('Microsoft.VC%d.CRT' % (self.vc_ver * 10),\n                    # Sometime store in directory with VS version instead of VC\n                    'Microsoft.VC%d.CRT' % (int(self.vs_ver) * 10))\n\n        # vcruntime path\n        for prefix, crt_dir in itertools.product(prefixes, crt_dirs):\n            path = join(prefix, arch_subdir, crt_dir, vcruntime)\n            if isfile(path):\n                return path\n\n    def return_env(self, exists=True):\n        \"\"\"\n        Return environment dict.\n\n        Parameters\n        ----------\n        exists: bool\n            It True, only return existing paths.\n\n        Return\n        ------\n        dict\n            environment\n        \"\"\"\n        env = dict(\n            include=self._build_paths('include',\n                                      [self.VCIncludes,\n                                       self.OSIncludes,\n                                       self.UCRTIncludes,\n                                       self.NetFxSDKIncludes],\n                                      exists),\n            lib=self._build_paths('lib',\n                                  [self.VCLibraries,\n                                   self.OSLibraries,\n                                   self.FxTools,\n                                   self.UCRTLibraries,\n                                   self.NetFxSDKLibraries],\n                                  exists),\n            libpath=self._build_paths('libpath',\n                                      [self.VCLibraries,\n                                       self.FxTools,\n                                       self.VCStoreRefs,\n                                       self.OSLibpath],\n                                      exists),\n            path=self._build_paths('path',\n                                   [self.VCTools,\n                                    self.VSTools,\n                                    self.VsTDb,\n                                    self.SdkTools,\n                                    self.SdkSetup,\n                                    self.FxTools,\n                                    self.MSBuild,\n                                    self.HTMLHelpWorkshop,\n                                    self.FSharp],\n                                   exists),\n        )\n        if self.vs_ver >= 14 and isfile(self.VCRuntimeRedist):\n            env['py_vcruntime_redist'] = self.VCRuntimeRedist\n        return env\n\n    def _build_paths(self, name, spec_path_lists, exists):\n        \"\"\"\n        Given an environment variable name and specified paths,\n        return a pathsep-separated string of paths containing\n        unique, extant, directories from those paths and from\n        the environment variable. Raise an error if no paths\n        are resolved.\n\n        Parameters\n        ----------\n        name: str\n            Environment variable name\n        spec_path_lists: list of str\n            Paths\n        exists: bool\n            It True, only return existing paths.\n\n        Return\n        ------\n        str\n            Pathsep-separated paths\n        \"\"\"\n        # flatten spec_path_lists\n        spec_paths = itertools.chain.from_iterable(spec_path_lists)\n        env_paths = environ.get(name, '').split(pathsep)\n        paths = itertools.chain(spec_paths, env_paths)\n        extant_paths = list(filter(isdir, paths)) if exists else paths\n        if not extant_paths:\n            msg = \"%s environment variable is empty\" % name.upper()\n            raise distutils.errors.DistutilsPlatformError(msg)\n        unique_paths = unique_everseen(extant_paths)\n        return pathsep.join(unique_paths)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/namespaces.py",
    "content": "import os\nfrom distutils import log\nimport itertools\n\n\nflatten = itertools.chain.from_iterable\n\n\nclass Installer:\n\n    nspkg_ext = '-nspkg.pth'\n\n    def install_namespaces(self):\n        nsp = self._get_all_ns_packages()\n        if not nsp:\n            return\n        filename, ext = os.path.splitext(self._get_target())\n        filename += self.nspkg_ext\n        self.outputs.append(filename)\n        log.info(\"Installing %s\", filename)\n        lines = map(self._gen_nspkg_line, nsp)\n\n        if self.dry_run:\n            # always generate the lines, even in dry run\n            list(lines)\n            return\n\n        with open(filename, 'wt') as f:\n            f.writelines(lines)\n\n    def uninstall_namespaces(self):\n        filename, ext = os.path.splitext(self._get_target())\n        filename += self.nspkg_ext\n        if not os.path.exists(filename):\n            return\n        log.info(\"Removing %s\", filename)\n        os.remove(filename)\n\n    def _get_target(self):\n        return self.target\n\n    _nspkg_tmpl = (\n        \"import sys, types, os\",\n        \"has_mfs = sys.version_info > (3, 5)\",\n        \"p = os.path.join(%(root)s, *%(pth)r)\",\n        \"importlib = has_mfs and __import__('importlib.util')\",\n        \"has_mfs and __import__('importlib.machinery')\",\n        (\n            \"m = has_mfs and \"\n            \"sys.modules.setdefault(%(pkg)r, \"\n            \"importlib.util.module_from_spec(\"\n            \"importlib.machinery.PathFinder.find_spec(%(pkg)r, \"\n            \"[os.path.dirname(p)])))\"\n        ),\n        (\n            \"m = m or \"\n            \"sys.modules.setdefault(%(pkg)r, types.ModuleType(%(pkg)r))\"\n        ),\n        \"mp = (m or []) and m.__dict__.setdefault('__path__',[])\",\n        \"(p not in mp) and mp.append(p)\",\n    )\n    \"lines for the namespace installer\"\n\n    _nspkg_tmpl_multi = (\n        'm and setattr(sys.modules[%(parent)r], %(child)r, m)',\n    )\n    \"additional line(s) when a parent package is indicated\"\n\n    def _get_root(self):\n        return \"sys._getframe(1).f_locals['sitedir']\"\n\n    def _gen_nspkg_line(self, pkg):\n        pth = tuple(pkg.split('.'))\n        root = self._get_root()\n        tmpl_lines = self._nspkg_tmpl\n        parent, sep, child = pkg.rpartition('.')\n        if parent:\n            tmpl_lines += self._nspkg_tmpl_multi\n        return ';'.join(tmpl_lines) % locals() + '\\n'\n\n    def _get_all_ns_packages(self):\n        \"\"\"Return sorted list of all package namespaces\"\"\"\n        pkgs = self.distribution.namespace_packages or []\n        return sorted(flatten(map(self._pkg_names, pkgs)))\n\n    @staticmethod\n    def _pkg_names(pkg):\n        \"\"\"\n        Given a namespace package, yield the components of that\n        package.\n\n        >>> names = Installer._pkg_names('a.b.c')\n        >>> set(names) == set(['a', 'a.b', 'a.b.c'])\n        True\n        \"\"\"\n        parts = pkg.split('.')\n        while parts:\n            yield '.'.join(parts)\n            parts.pop()\n\n\nclass DevelopInstaller(Installer):\n    def _get_root(self):\n        return repr(str(self.egg_path))\n\n    def _get_target(self):\n        return self.egg_link\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/package_index.py",
    "content": "\"\"\"PyPI and direct package downloading.\"\"\"\n\nimport sys\nimport os\nimport re\nimport io\nimport shutil\nimport socket\nimport base64\nimport hashlib\nimport itertools\nimport warnings\nimport configparser\nimport html\nimport http.client\nimport urllib.parse\nimport urllib.request\nimport urllib.error\nfrom functools import wraps\n\nimport setuptools\nfrom pkg_resources import (\n    CHECKOUT_DIST,\n    Distribution,\n    BINARY_DIST,\n    normalize_path,\n    SOURCE_DIST,\n    Environment,\n    find_distributions,\n    safe_name,\n    safe_version,\n    to_filename,\n    Requirement,\n    DEVELOP_DIST,\n    EGG_DIST,\n    parse_version,\n)\nfrom distutils import log\nfrom distutils.errors import DistutilsError\nfrom fnmatch import translate\nfrom setuptools.wheel import Wheel\nfrom setuptools.extern.more_itertools import unique_everseen\n\n\nEGG_FRAGMENT = re.compile(r'^egg=([-A-Za-z0-9_.+!]+)$')\nHREF = re.compile(r\"\"\"href\\s*=\\s*['\"]?([^'\"> ]+)\"\"\", re.I)\nPYPI_MD5 = re.compile(\n    r'<a href=\"([^\"#]+)\">([^<]+)</a>\\n\\s+\\(<a (?:title=\"MD5 hash\"\\n\\s+)'\n    r'href=\"[^?]+\\?:action=show_md5&amp;digest=([0-9a-f]{32})\">md5</a>\\)'\n)\nURL_SCHEME = re.compile('([-+.a-z0-9]{2,}):', re.I).match\nEXTENSIONS = \".tar.gz .tar.bz2 .tar .zip .tgz\".split()\n\n__all__ = [\n    'PackageIndex',\n    'distros_for_url',\n    'parse_bdist_wininst',\n    'interpret_distro_name',\n]\n\n_SOCKET_TIMEOUT = 15\n\n_tmpl = \"setuptools/{setuptools.__version__} Python-urllib/{py_major}\"\nuser_agent = _tmpl.format(\n    py_major='{}.{}'.format(*sys.version_info), setuptools=setuptools\n)\n\n\ndef parse_requirement_arg(spec):\n    try:\n        return Requirement.parse(spec)\n    except ValueError as e:\n        raise DistutilsError(\n            \"Not a URL, existing file, or requirement spec: %r\" % (spec,)\n        ) from e\n\n\ndef parse_bdist_wininst(name):\n    \"\"\"Return (base,pyversion) or (None,None) for possible .exe name\"\"\"\n\n    lower = name.lower()\n    base, py_ver, plat = None, None, None\n\n    if lower.endswith('.exe'):\n        if lower.endswith('.win32.exe'):\n            base = name[:-10]\n            plat = 'win32'\n        elif lower.startswith('.win32-py', -16):\n            py_ver = name[-7:-4]\n            base = name[:-16]\n            plat = 'win32'\n        elif lower.endswith('.win-amd64.exe'):\n            base = name[:-14]\n            plat = 'win-amd64'\n        elif lower.startswith('.win-amd64-py', -20):\n            py_ver = name[-7:-4]\n            base = name[:-20]\n            plat = 'win-amd64'\n    return base, py_ver, plat\n\n\ndef egg_info_for_url(url):\n    parts = urllib.parse.urlparse(url)\n    scheme, server, path, parameters, query, fragment = parts\n    base = urllib.parse.unquote(path.split('/')[-1])\n    if server == 'sourceforge.net' and base == 'download':  # XXX Yuck\n        base = urllib.parse.unquote(path.split('/')[-2])\n    if '#' in base:\n        base, fragment = base.split('#', 1)\n    return base, fragment\n\n\ndef distros_for_url(url, metadata=None):\n    \"\"\"Yield egg or source distribution objects that might be found at a URL\"\"\"\n    base, fragment = egg_info_for_url(url)\n    for dist in distros_for_location(url, base, metadata):\n        yield dist\n    if fragment:\n        match = EGG_FRAGMENT.match(fragment)\n        if match:\n            for dist in interpret_distro_name(\n                url, match.group(1), metadata, precedence=CHECKOUT_DIST\n            ):\n                yield dist\n\n\ndef distros_for_location(location, basename, metadata=None):\n    \"\"\"Yield egg or source distribution objects based on basename\"\"\"\n    if basename.endswith('.egg.zip'):\n        basename = basename[:-4]  # strip the .zip\n    if basename.endswith('.egg') and '-' in basename:\n        # only one, unambiguous interpretation\n        return [Distribution.from_location(location, basename, metadata)]\n    if basename.endswith('.whl') and '-' in basename:\n        wheel = Wheel(basename)\n        if not wheel.is_compatible():\n            return []\n        return [\n            Distribution(\n                location=location,\n                project_name=wheel.project_name,\n                version=wheel.version,\n                # Increase priority over eggs.\n                precedence=EGG_DIST + 1,\n            )\n        ]\n    if basename.endswith('.exe'):\n        win_base, py_ver, platform = parse_bdist_wininst(basename)\n        if win_base is not None:\n            return interpret_distro_name(\n                location, win_base, metadata, py_ver, BINARY_DIST, platform\n            )\n    # Try source distro extensions (.zip, .tgz, etc.)\n    #\n    for ext in EXTENSIONS:\n        if basename.endswith(ext):\n            basename = basename[: -len(ext)]\n            return interpret_distro_name(location, basename, metadata)\n    return []  # no extension matched\n\n\ndef distros_for_filename(filename, metadata=None):\n    \"\"\"Yield possible egg or source distribution objects based on a filename\"\"\"\n    return distros_for_location(\n        normalize_path(filename), os.path.basename(filename), metadata\n    )\n\n\ndef interpret_distro_name(\n    location, basename, metadata, py_version=None, precedence=SOURCE_DIST, platform=None\n):\n    \"\"\"Generate alternative interpretations of a source distro name\n\n    Note: if `location` is a filesystem filename, you should call\n    ``pkg_resources.normalize_path()`` on it before passing it to this\n    routine!\n    \"\"\"\n    # Generate alternative interpretations of a source distro name\n    # Because some packages are ambiguous as to name/versions split\n    # e.g. \"adns-python-1.1.0\", \"egenix-mx-commercial\", etc.\n    # So, we generate each possible interpretation (e.g. \"adns, python-1.1.0\"\n    # \"adns-python, 1.1.0\", and \"adns-python-1.1.0, no version\").  In practice,\n    # the spurious interpretations should be ignored, because in the event\n    # there's also an \"adns\" package, the spurious \"python-1.1.0\" version will\n    # compare lower than any numeric version number, and is therefore unlikely\n    # to match a request for it.  It's still a potential problem, though, and\n    # in the long run PyPI and the distutils should go for \"safe\" names and\n    # versions in distribution archive names (sdist and bdist).\n\n    parts = basename.split('-')\n    if not py_version and any(re.match(r'py\\d\\.\\d$', p) for p in parts[2:]):\n        # it is a bdist_dumb, not an sdist -- bail out\n        return\n\n    for p in range(1, len(parts) + 1):\n        yield Distribution(\n            location,\n            metadata,\n            '-'.join(parts[:p]),\n            '-'.join(parts[p:]),\n            py_version=py_version,\n            precedence=precedence,\n            platform=platform,\n        )\n\n\ndef unique_values(func):\n    \"\"\"\n    Wrap a function returning an iterable such that the resulting iterable\n    only ever yields unique items.\n    \"\"\"\n\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        return unique_everseen(func(*args, **kwargs))\n\n    return wrapper\n\n\nREL = re.compile(r\"\"\"<([^>]*\\srel\\s{0,10}=\\s{0,10}['\"]?([^'\" >]+)[^>]*)>\"\"\", re.I)\n\"\"\"\nRegex for an HTML tag with 'rel=\"val\"' attributes.\n\"\"\"\n\n\n@unique_values\ndef find_external_links(url, page):\n    \"\"\"Find rel=\"homepage\" and rel=\"download\" links in `page`, yielding URLs\"\"\"\n\n    for match in REL.finditer(page):\n        tag, rel = match.groups()\n        rels = set(map(str.strip, rel.lower().split(',')))\n        if 'homepage' in rels or 'download' in rels:\n            for match in HREF.finditer(tag):\n                yield urllib.parse.urljoin(url, htmldecode(match.group(1)))\n\n    for tag in (\"<th>Home Page\", \"<th>Download URL\"):\n        pos = page.find(tag)\n        if pos != -1:\n            match = HREF.search(page, pos)\n            if match:\n                yield urllib.parse.urljoin(url, htmldecode(match.group(1)))\n\n\nclass ContentChecker:\n    \"\"\"\n    A null content checker that defines the interface for checking content\n    \"\"\"\n\n    def feed(self, block):\n        \"\"\"\n        Feed a block of data to the hash.\n        \"\"\"\n        return\n\n    def is_valid(self):\n        \"\"\"\n        Check the hash. Return False if validation fails.\n        \"\"\"\n        return True\n\n    def report(self, reporter, template):\n        \"\"\"\n        Call reporter with information about the checker (hash name)\n        substituted into the template.\n        \"\"\"\n        return\n\n\nclass HashChecker(ContentChecker):\n    pattern = re.compile(\n        r'(?P<hash_name>sha1|sha224|sha384|sha256|sha512|md5)='\n        r'(?P<expected>[a-f0-9]+)'\n    )\n\n    def __init__(self, hash_name, expected):\n        self.hash_name = hash_name\n        self.hash = hashlib.new(hash_name)\n        self.expected = expected\n\n    @classmethod\n    def from_url(cls, url):\n        \"Construct a (possibly null) ContentChecker from a URL\"\n        fragment = urllib.parse.urlparse(url)[-1]\n        if not fragment:\n            return ContentChecker()\n        match = cls.pattern.search(fragment)\n        if not match:\n            return ContentChecker()\n        return cls(**match.groupdict())\n\n    def feed(self, block):\n        self.hash.update(block)\n\n    def is_valid(self):\n        return self.hash.hexdigest() == self.expected\n\n    def report(self, reporter, template):\n        msg = template % self.hash_name\n        return reporter(msg)\n\n\nclass PackageIndex(Environment):\n    \"\"\"A distribution index that scans web pages for download URLs\"\"\"\n\n    def __init__(\n        self,\n        index_url=\"https://pypi.org/simple/\",\n        hosts=('*',),\n        ca_bundle=None,\n        verify_ssl=True,\n        *args,\n        **kw\n    ):\n        super().__init__(*args, **kw)\n        self.index_url = index_url + \"/\"[: not index_url.endswith('/')]\n        self.scanned_urls = {}\n        self.fetched_urls = {}\n        self.package_pages = {}\n        self.allows = re.compile('|'.join(map(translate, hosts))).match\n        self.to_scan = []\n        self.opener = urllib.request.urlopen\n\n    def add(self, dist):\n        # ignore invalid versions\n        try:\n            parse_version(dist.version)\n        except Exception:\n            return\n        return super().add(dist)\n\n    # FIXME: 'PackageIndex.process_url' is too complex (14)\n    def process_url(self, url, retrieve=False):  # noqa: C901\n        \"\"\"Evaluate a URL as a possible download, and maybe retrieve it\"\"\"\n        if url in self.scanned_urls and not retrieve:\n            return\n        self.scanned_urls[url] = True\n        if not URL_SCHEME(url):\n            self.process_filename(url)\n            return\n        else:\n            dists = list(distros_for_url(url))\n            if dists:\n                if not self.url_ok(url):\n                    return\n                self.debug(\"Found link: %s\", url)\n\n        if dists or not retrieve or url in self.fetched_urls:\n            list(map(self.add, dists))\n            return  # don't need the actual page\n\n        if not self.url_ok(url):\n            self.fetched_urls[url] = True\n            return\n\n        self.info(\"Reading %s\", url)\n        self.fetched_urls[url] = True  # prevent multiple fetch attempts\n        tmpl = \"Download error on %s: %%s -- Some packages may not be found!\"\n        f = self.open_url(url, tmpl % url)\n        if f is None:\n            return\n        if isinstance(f, urllib.error.HTTPError) and f.code == 401:\n            self.info(\"Authentication error: %s\" % f.msg)\n        self.fetched_urls[f.url] = True\n        if 'html' not in f.headers.get('content-type', '').lower():\n            f.close()  # not html, we can't process it\n            return\n\n        base = f.url  # handle redirects\n        page = f.read()\n        if not isinstance(page, str):\n            # In Python 3 and got bytes but want str.\n            if isinstance(f, urllib.error.HTTPError):\n                # Errors have no charset, assume latin1:\n                charset = 'latin-1'\n            else:\n                charset = f.headers.get_param('charset') or 'latin-1'\n            page = page.decode(charset, \"ignore\")\n        f.close()\n        for match in HREF.finditer(page):\n            link = urllib.parse.urljoin(base, htmldecode(match.group(1)))\n            self.process_url(link)\n        if url.startswith(self.index_url) and getattr(f, 'code', None) != 404:\n            page = self.process_index(url, page)\n\n    def process_filename(self, fn, nested=False):\n        # process filenames or directories\n        if not os.path.exists(fn):\n            self.warn(\"Not found: %s\", fn)\n            return\n\n        if os.path.isdir(fn) and not nested:\n            path = os.path.realpath(fn)\n            for item in os.listdir(path):\n                self.process_filename(os.path.join(path, item), True)\n\n        dists = distros_for_filename(fn)\n        if dists:\n            self.debug(\"Found: %s\", fn)\n            list(map(self.add, dists))\n\n    def url_ok(self, url, fatal=False):\n        s = URL_SCHEME(url)\n        is_file = s and s.group(1).lower() == 'file'\n        if is_file or self.allows(urllib.parse.urlparse(url)[1]):\n            return True\n        msg = (\n            \"\\nNote: Bypassing %s (disallowed host; see \"\n            \"http://bit.ly/2hrImnY for details).\\n\"\n        )\n        if fatal:\n            raise DistutilsError(msg % url)\n        else:\n            self.warn(msg, url)\n\n    def scan_egg_links(self, search_path):\n        dirs = filter(os.path.isdir, search_path)\n        egg_links = (\n            (path, entry)\n            for path in dirs\n            for entry in os.listdir(path)\n            if entry.endswith('.egg-link')\n        )\n        list(itertools.starmap(self.scan_egg_link, egg_links))\n\n    def scan_egg_link(self, path, entry):\n        with open(os.path.join(path, entry)) as raw_lines:\n            # filter non-empty lines\n            lines = list(filter(None, map(str.strip, raw_lines)))\n\n        if len(lines) != 2:\n            # format is not recognized; punt\n            return\n\n        egg_path, setup_path = lines\n\n        for dist in find_distributions(os.path.join(path, egg_path)):\n            dist.location = os.path.join(path, *lines)\n            dist.precedence = SOURCE_DIST\n            self.add(dist)\n\n    def _scan(self, link):\n        # Process a URL to see if it's for a package page\n        NO_MATCH_SENTINEL = None, None\n        if not link.startswith(self.index_url):\n            return NO_MATCH_SENTINEL\n\n        parts = list(map(urllib.parse.unquote, link[len(self.index_url) :].split('/')))\n        if len(parts) != 2 or '#' in parts[1]:\n            return NO_MATCH_SENTINEL\n\n        # it's a package page, sanitize and index it\n        pkg = safe_name(parts[0])\n        ver = safe_version(parts[1])\n        self.package_pages.setdefault(pkg.lower(), {})[link] = True\n        return to_filename(pkg), to_filename(ver)\n\n    def process_index(self, url, page):\n        \"\"\"Process the contents of a PyPI page\"\"\"\n\n        # process an index page into the package-page index\n        for match in HREF.finditer(page):\n            try:\n                self._scan(urllib.parse.urljoin(url, htmldecode(match.group(1))))\n            except ValueError:\n                pass\n\n        pkg, ver = self._scan(url)  # ensure this page is in the page index\n        if not pkg:\n            return \"\"  # no sense double-scanning non-package pages\n\n        # process individual package page\n        for new_url in find_external_links(url, page):\n            # Process the found URL\n            base, frag = egg_info_for_url(new_url)\n            if base.endswith('.py') and not frag:\n                if ver:\n                    new_url += '#egg=%s-%s' % (pkg, ver)\n                else:\n                    self.need_version_info(url)\n            self.scan_url(new_url)\n\n        return PYPI_MD5.sub(\n            lambda m: '<a href=\"%s#md5=%s\">%s</a>' % m.group(1, 3, 2), page\n        )\n\n    def need_version_info(self, url):\n        self.scan_all(\n            \"Page at %s links to .py file(s) without version info; an index \"\n            \"scan is required.\",\n            url,\n        )\n\n    def scan_all(self, msg=None, *args):\n        if self.index_url not in self.fetched_urls:\n            if msg:\n                self.warn(msg, *args)\n            self.info(\"Scanning index of all packages (this may take a while)\")\n        self.scan_url(self.index_url)\n\n    def find_packages(self, requirement):\n        self.scan_url(self.index_url + requirement.unsafe_name + '/')\n\n        if not self.package_pages.get(requirement.key):\n            # Fall back to safe version of the name\n            self.scan_url(self.index_url + requirement.project_name + '/')\n\n        if not self.package_pages.get(requirement.key):\n            # We couldn't find the target package, so search the index page too\n            self.not_found_in_index(requirement)\n\n        for url in list(self.package_pages.get(requirement.key, ())):\n            # scan each page that might be related to the desired package\n            self.scan_url(url)\n\n    def obtain(self, requirement, installer=None):\n        self.prescan()\n        self.find_packages(requirement)\n        for dist in self[requirement.key]:\n            if dist in requirement:\n                return dist\n            self.debug(\"%s does not match %s\", requirement, dist)\n        return super(PackageIndex, self).obtain(requirement, installer)\n\n    def check_hash(self, checker, filename, tfp):\n        \"\"\"\n        checker is a ContentChecker\n        \"\"\"\n        checker.report(self.debug, \"Validating %%s checksum for %s\" % filename)\n        if not checker.is_valid():\n            tfp.close()\n            os.unlink(filename)\n            raise DistutilsError(\n                \"%s validation failed for %s; \"\n                \"possible download problem?\"\n                % (checker.hash.name, os.path.basename(filename))\n            )\n\n    def add_find_links(self, urls):\n        \"\"\"Add `urls` to the list that will be prescanned for searches\"\"\"\n        for url in urls:\n            if (\n                self.to_scan is None  # if we have already \"gone online\"\n                or not URL_SCHEME(url)  # or it's a local file/directory\n                or url.startswith('file:')\n                or list(distros_for_url(url))  # or a direct package link\n            ):\n                # then go ahead and process it now\n                self.scan_url(url)\n            else:\n                # otherwise, defer retrieval till later\n                self.to_scan.append(url)\n\n    def prescan(self):\n        \"\"\"Scan urls scheduled for prescanning (e.g. --find-links)\"\"\"\n        if self.to_scan:\n            list(map(self.scan_url, self.to_scan))\n        self.to_scan = None  # from now on, go ahead and process immediately\n\n    def not_found_in_index(self, requirement):\n        if self[requirement.key]:  # we've seen at least one distro\n            meth, msg = self.info, \"Couldn't retrieve index page for %r\"\n        else:  # no distros seen for this name, might be misspelled\n            meth, msg = (\n                self.warn,\n                \"Couldn't find index page for %r (maybe misspelled?)\",\n            )\n        meth(msg, requirement.unsafe_name)\n        self.scan_all()\n\n    def download(self, spec, tmpdir):\n        \"\"\"Locate and/or download `spec` to `tmpdir`, returning a local path\n\n        `spec` may be a ``Requirement`` object, or a string containing a URL,\n        an existing local filename, or a project/version requirement spec\n        (i.e. the string form of a ``Requirement`` object).  If it is the URL\n        of a .py file with an unambiguous ``#egg=name-version`` tag (i.e., one\n        that escapes ``-`` as ``_`` throughout), a trivial ``setup.py`` is\n        automatically created alongside the downloaded file.\n\n        If `spec` is a ``Requirement`` object or a string containing a\n        project/version requirement spec, this method returns the location of\n        a matching distribution (possibly after downloading it to `tmpdir`).\n        If `spec` is a locally existing file or directory name, it is simply\n        returned unchanged.  If `spec` is a URL, it is downloaded to a subpath\n        of `tmpdir`, and the local filename is returned.  Various errors may be\n        raised if a problem occurs during downloading.\n        \"\"\"\n        if not isinstance(spec, Requirement):\n            scheme = URL_SCHEME(spec)\n            if scheme:\n                # It's a url, download it to tmpdir\n                found = self._download_url(scheme.group(1), spec, tmpdir)\n                base, fragment = egg_info_for_url(spec)\n                if base.endswith('.py'):\n                    found = self.gen_setup(found, fragment, tmpdir)\n                return found\n            elif os.path.exists(spec):\n                # Existing file or directory, just return it\n                return spec\n            else:\n                spec = parse_requirement_arg(spec)\n        return getattr(self.fetch_distribution(spec, tmpdir), 'location', None)\n\n    def fetch_distribution(  # noqa: C901  # is too complex (14)  # FIXME\n        self,\n        requirement,\n        tmpdir,\n        force_scan=False,\n        source=False,\n        develop_ok=False,\n        local_index=None,\n    ):\n        \"\"\"Obtain a distribution suitable for fulfilling `requirement`\n\n        `requirement` must be a ``pkg_resources.Requirement`` instance.\n        If necessary, or if the `force_scan` flag is set, the requirement is\n        searched for in the (online) package index as well as the locally\n        installed packages.  If a distribution matching `requirement` is found,\n        the returned distribution's ``location`` is the value you would have\n        gotten from calling the ``download()`` method with the matching\n        distribution's URL or filename.  If no matching distribution is found,\n        ``None`` is returned.\n\n        If the `source` flag is set, only source distributions and source\n        checkout links will be considered.  Unless the `develop_ok` flag is\n        set, development and system eggs (i.e., those using the ``.egg-info``\n        format) will be ignored.\n        \"\"\"\n        # process a Requirement\n        self.info(\"Searching for %s\", requirement)\n        skipped = {}\n        dist = None\n\n        def find(req, env=None):\n            if env is None:\n                env = self\n            # Find a matching distribution; may be called more than once\n\n            for dist in env[req.key]:\n\n                if dist.precedence == DEVELOP_DIST and not develop_ok:\n                    if dist not in skipped:\n                        self.warn(\n                            \"Skipping development or system egg: %s\",\n                            dist,\n                        )\n                        skipped[dist] = 1\n                    continue\n\n                test = dist in req and (dist.precedence <= SOURCE_DIST or not source)\n                if test:\n                    loc = self.download(dist.location, tmpdir)\n                    dist.download_location = loc\n                    if os.path.exists(dist.download_location):\n                        return dist\n\n        if force_scan:\n            self.prescan()\n            self.find_packages(requirement)\n            dist = find(requirement)\n\n        if not dist and local_index is not None:\n            dist = find(requirement, local_index)\n\n        if dist is None:\n            if self.to_scan is not None:\n                self.prescan()\n            dist = find(requirement)\n\n        if dist is None and not force_scan:\n            self.find_packages(requirement)\n            dist = find(requirement)\n\n        if dist is None:\n            self.warn(\n                \"No local packages or working download links found for %s%s\",\n                (source and \"a source distribution of \" or \"\"),\n                requirement,\n            )\n        else:\n            self.info(\"Best match: %s\", dist)\n            return dist.clone(location=dist.download_location)\n\n    def fetch(self, requirement, tmpdir, force_scan=False, source=False):\n        \"\"\"Obtain a file suitable for fulfilling `requirement`\n\n        DEPRECATED; use the ``fetch_distribution()`` method now instead.  For\n        backward compatibility, this routine is identical but returns the\n        ``location`` of the downloaded distribution instead of a distribution\n        object.\n        \"\"\"\n        dist = self.fetch_distribution(requirement, tmpdir, force_scan, source)\n        if dist is not None:\n            return dist.location\n        return None\n\n    def gen_setup(self, filename, fragment, tmpdir):\n        match = EGG_FRAGMENT.match(fragment)\n        dists = (\n            match\n            and [\n                d\n                for d in interpret_distro_name(filename, match.group(1), None)\n                if d.version\n            ]\n            or []\n        )\n\n        if len(dists) == 1:  # unambiguous ``#egg`` fragment\n            basename = os.path.basename(filename)\n\n            # Make sure the file has been downloaded to the temp dir.\n            if os.path.dirname(filename) != tmpdir:\n                dst = os.path.join(tmpdir, basename)\n                if not (os.path.exists(dst) and os.path.samefile(filename, dst)):\n                    shutil.copy2(filename, dst)\n                    filename = dst\n\n            with open(os.path.join(tmpdir, 'setup.py'), 'w') as file:\n                file.write(\n                    \"from setuptools import setup\\n\"\n                    \"setup(name=%r, version=%r, py_modules=[%r])\\n\"\n                    % (\n                        dists[0].project_name,\n                        dists[0].version,\n                        os.path.splitext(basename)[0],\n                    )\n                )\n            return filename\n\n        elif match:\n            raise DistutilsError(\n                \"Can't unambiguously interpret project/version identifier %r; \"\n                \"any dashes in the name or version should be escaped using \"\n                \"underscores. %r\" % (fragment, dists)\n            )\n        else:\n            raise DistutilsError(\n                \"Can't process plain .py files without an '#egg=name-version'\"\n                \" suffix to enable automatic setup script generation.\"\n            )\n\n    dl_blocksize = 8192\n\n    def _download_to(self, url, filename):\n        self.info(\"Downloading %s\", url)\n        # Download the file\n        fp = None\n        try:\n            checker = HashChecker.from_url(url)\n            fp = self.open_url(url)\n            if isinstance(fp, urllib.error.HTTPError):\n                raise DistutilsError(\n                    \"Can't download %s: %s %s\" % (url, fp.code, fp.msg)\n                )\n            headers = fp.info()\n            blocknum = 0\n            bs = self.dl_blocksize\n            size = -1\n            if \"content-length\" in headers:\n                # Some servers return multiple Content-Length headers :(\n                sizes = headers.get_all('Content-Length')\n                size = max(map(int, sizes))\n                self.reporthook(url, filename, blocknum, bs, size)\n            with open(filename, 'wb') as tfp:\n                while True:\n                    block = fp.read(bs)\n                    if block:\n                        checker.feed(block)\n                        tfp.write(block)\n                        blocknum += 1\n                        self.reporthook(url, filename, blocknum, bs, size)\n                    else:\n                        break\n                self.check_hash(checker, filename, tfp)\n            return headers\n        finally:\n            if fp:\n                fp.close()\n\n    def reporthook(self, url, filename, blocknum, blksize, size):\n        pass  # no-op\n\n    # FIXME:\n    def open_url(self, url, warning=None):  # noqa: C901  # is too complex (12)\n        if url.startswith('file:'):\n            return local_open(url)\n        try:\n            return open_with_auth(url, self.opener)\n        except (ValueError, http.client.InvalidURL) as v:\n            msg = ' '.join([str(arg) for arg in v.args])\n            if warning:\n                self.warn(warning, msg)\n            else:\n                raise DistutilsError('%s %s' % (url, msg)) from v\n        except urllib.error.HTTPError as v:\n            return v\n        except urllib.error.URLError as v:\n            if warning:\n                self.warn(warning, v.reason)\n            else:\n                raise DistutilsError(\n                    \"Download error for %s: %s\" % (url, v.reason)\n                ) from v\n        except http.client.BadStatusLine as v:\n            if warning:\n                self.warn(warning, v.line)\n            else:\n                raise DistutilsError(\n                    '%s returned a bad status line. The server might be '\n                    'down, %s' % (url, v.line)\n                ) from v\n        except (http.client.HTTPException, socket.error) as v:\n            if warning:\n                self.warn(warning, v)\n            else:\n                raise DistutilsError(\"Download error for %s: %s\" % (url, v)) from v\n\n    def _download_url(self, scheme, url, tmpdir):\n        # Determine download filename\n        #\n        name, fragment = egg_info_for_url(url)\n        if name:\n            while '..' in name:\n                name = name.replace('..', '.').replace('\\\\', '_')\n        else:\n            name = \"__downloaded__\"  # default if URL has no path contents\n\n        if name.endswith('.egg.zip'):\n            name = name[:-4]  # strip the extra .zip before download\n\n        filename = os.path.join(tmpdir, name)\n\n        # Download the file\n        #\n        if scheme == 'svn' or scheme.startswith('svn+'):\n            return self._download_svn(url, filename)\n        elif scheme == 'git' or scheme.startswith('git+'):\n            return self._download_git(url, filename)\n        elif scheme.startswith('hg+'):\n            return self._download_hg(url, filename)\n        elif scheme == 'file':\n            return urllib.request.url2pathname(urllib.parse.urlparse(url)[2])\n        else:\n            self.url_ok(url, True)  # raises error if not allowed\n            return self._attempt_download(url, filename)\n\n    def scan_url(self, url):\n        self.process_url(url, True)\n\n    def _attempt_download(self, url, filename):\n        headers = self._download_to(url, filename)\n        if 'html' in headers.get('content-type', '').lower():\n            return self._download_html(url, headers, filename)\n        else:\n            return filename\n\n    def _download_html(self, url, headers, filename):\n        file = open(filename)\n        for line in file:\n            if line.strip():\n                # Check for a subversion index page\n                if re.search(r'<title>([^- ]+ - )?Revision \\d+:', line):\n                    # it's a subversion index page:\n                    file.close()\n                    os.unlink(filename)\n                    return self._download_svn(url, filename)\n                break  # not an index page\n        file.close()\n        os.unlink(filename)\n        raise DistutilsError(\"Unexpected HTML page found at \" + url)\n\n    def _download_svn(self, url, filename):\n        warnings.warn(\"SVN download support is deprecated\", UserWarning)\n        url = url.split('#', 1)[0]  # remove any fragment for svn's sake\n        creds = ''\n        if url.lower().startswith('svn:') and '@' in url:\n            scheme, netloc, path, p, q, f = urllib.parse.urlparse(url)\n            if not netloc and path.startswith('//') and '/' in path[2:]:\n                netloc, path = path[2:].split('/', 1)\n                auth, host = _splituser(netloc)\n                if auth:\n                    if ':' in auth:\n                        user, pw = auth.split(':', 1)\n                        creds = \" --username=%s --password=%s\" % (user, pw)\n                    else:\n                        creds = \" --username=\" + auth\n                    netloc = host\n                    parts = scheme, netloc, url, p, q, f\n                    url = urllib.parse.urlunparse(parts)\n        self.info(\"Doing subversion checkout from %s to %s\", url, filename)\n        os.system(\"svn checkout%s -q %s %s\" % (creds, url, filename))\n        return filename\n\n    @staticmethod\n    def _vcs_split_rev_from_url(url, pop_prefix=False):\n        scheme, netloc, path, query, frag = urllib.parse.urlsplit(url)\n\n        scheme = scheme.split('+', 1)[-1]\n\n        # Some fragment identification fails\n        path = path.split('#', 1)[0]\n\n        rev = None\n        if '@' in path:\n            path, rev = path.rsplit('@', 1)\n\n        # Also, discard fragment\n        url = urllib.parse.urlunsplit((scheme, netloc, path, query, ''))\n\n        return url, rev\n\n    def _download_git(self, url, filename):\n        filename = filename.split('#', 1)[0]\n        url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)\n\n        self.info(\"Doing git clone from %s to %s\", url, filename)\n        os.system(\"git clone --quiet %s %s\" % (url, filename))\n\n        if rev is not None:\n            self.info(\"Checking out %s\", rev)\n            os.system(\n                \"git -C %s checkout --quiet %s\"\n                % (\n                    filename,\n                    rev,\n                )\n            )\n\n        return filename\n\n    def _download_hg(self, url, filename):\n        filename = filename.split('#', 1)[0]\n        url, rev = self._vcs_split_rev_from_url(url, pop_prefix=True)\n\n        self.info(\"Doing hg clone from %s to %s\", url, filename)\n        os.system(\"hg clone --quiet %s %s\" % (url, filename))\n\n        if rev is not None:\n            self.info(\"Updating to %s\", rev)\n            os.system(\n                \"hg --cwd %s up -C -r %s -q\"\n                % (\n                    filename,\n                    rev,\n                )\n            )\n\n        return filename\n\n    def debug(self, msg, *args):\n        log.debug(msg, *args)\n\n    def info(self, msg, *args):\n        log.info(msg, *args)\n\n    def warn(self, msg, *args):\n        log.warn(msg, *args)\n\n\n# This pattern matches a character entity reference (a decimal numeric\n# references, a hexadecimal numeric reference, or a named reference).\nentity_sub = re.compile(r'&(#(\\d+|x[\\da-fA-F]+)|[\\w.:-]+);?').sub\n\n\ndef decode_entity(match):\n    what = match.group(0)\n    return html.unescape(what)\n\n\ndef htmldecode(text):\n    \"\"\"\n    Decode HTML entities in the given text.\n\n    >>> htmldecode(\n    ...     'https://../package_name-0.1.2.tar.gz'\n    ...     '?tokena=A&amp;tokenb=B\">package_name-0.1.2.tar.gz')\n    'https://../package_name-0.1.2.tar.gz?tokena=A&tokenb=B\">package_name-0.1.2.tar.gz'\n    \"\"\"\n    return entity_sub(decode_entity, text)\n\n\ndef socket_timeout(timeout=15):\n    def _socket_timeout(func):\n        def _socket_timeout(*args, **kwargs):\n            old_timeout = socket.getdefaulttimeout()\n            socket.setdefaulttimeout(timeout)\n            try:\n                return func(*args, **kwargs)\n            finally:\n                socket.setdefaulttimeout(old_timeout)\n\n        return _socket_timeout\n\n    return _socket_timeout\n\n\ndef _encode_auth(auth):\n    \"\"\"\n    Encode auth from a URL suitable for an HTTP header.\n    >>> str(_encode_auth('username%3Apassword'))\n    'dXNlcm5hbWU6cGFzc3dvcmQ='\n\n    Long auth strings should not cause a newline to be inserted.\n    >>> long_auth = 'username:' + 'password'*10\n    >>> chr(10) in str(_encode_auth(long_auth))\n    False\n    \"\"\"\n    auth_s = urllib.parse.unquote(auth)\n    # convert to bytes\n    auth_bytes = auth_s.encode()\n    encoded_bytes = base64.b64encode(auth_bytes)\n    # convert back to a string\n    encoded = encoded_bytes.decode()\n    # strip the trailing carriage return\n    return encoded.replace('\\n', '')\n\n\nclass Credential:\n    \"\"\"\n    A username/password pair. Use like a namedtuple.\n    \"\"\"\n\n    def __init__(self, username, password):\n        self.username = username\n        self.password = password\n\n    def __iter__(self):\n        yield self.username\n        yield self.password\n\n    def __str__(self):\n        return '%(username)s:%(password)s' % vars(self)\n\n\nclass PyPIConfig(configparser.RawConfigParser):\n    def __init__(self):\n        \"\"\"\n        Load from ~/.pypirc\n        \"\"\"\n        defaults = dict.fromkeys(['username', 'password', 'repository'], '')\n        super().__init__(defaults)\n\n        rc = os.path.join(os.path.expanduser('~'), '.pypirc')\n        if os.path.exists(rc):\n            self.read(rc)\n\n    @property\n    def creds_by_repository(self):\n        sections_with_repositories = [\n            section\n            for section in self.sections()\n            if self.get(section, 'repository').strip()\n        ]\n\n        return dict(map(self._get_repo_cred, sections_with_repositories))\n\n    def _get_repo_cred(self, section):\n        repo = self.get(section, 'repository').strip()\n        return repo, Credential(\n            self.get(section, 'username').strip(),\n            self.get(section, 'password').strip(),\n        )\n\n    def find_credential(self, url):\n        \"\"\"\n        If the URL indicated appears to be a repository defined in this\n        config, return the credential for that repository.\n        \"\"\"\n        for repository, cred in self.creds_by_repository.items():\n            if url.startswith(repository):\n                return cred\n\n\ndef open_with_auth(url, opener=urllib.request.urlopen):\n    \"\"\"Open a urllib2 request, handling HTTP authentication\"\"\"\n\n    parsed = urllib.parse.urlparse(url)\n    scheme, netloc, path, params, query, frag = parsed\n\n    # Double scheme does not raise on macOS as revealed by a\n    # failing test. We would expect \"nonnumeric port\". Refs #20.\n    if netloc.endswith(':'):\n        raise http.client.InvalidURL(\"nonnumeric port: ''\")\n\n    if scheme in ('http', 'https'):\n        auth, address = _splituser(netloc)\n    else:\n        auth = None\n\n    if not auth:\n        cred = PyPIConfig().find_credential(url)\n        if cred:\n            auth = str(cred)\n            info = cred.username, url\n            log.info('Authenticating as %s for %s (from .pypirc)', *info)\n\n    if auth:\n        auth = \"Basic \" + _encode_auth(auth)\n        parts = scheme, address, path, params, query, frag\n        new_url = urllib.parse.urlunparse(parts)\n        request = urllib.request.Request(new_url)\n        request.add_header(\"Authorization\", auth)\n    else:\n        request = urllib.request.Request(url)\n\n    request.add_header('User-Agent', user_agent)\n    fp = opener(request)\n\n    if auth:\n        # Put authentication info back into request URL if same host,\n        # so that links found on the page will work\n        s2, h2, path2, param2, query2, frag2 = urllib.parse.urlparse(fp.url)\n        if s2 == scheme and h2 == address:\n            parts = s2, netloc, path2, param2, query2, frag2\n            fp.url = urllib.parse.urlunparse(parts)\n\n    return fp\n\n\n# copy of urllib.parse._splituser from Python 3.8\ndef _splituser(host):\n    \"\"\"splituser('user[:passwd]@host[:port]')\n    --> 'user[:passwd]', 'host[:port]'.\"\"\"\n    user, delim, host = host.rpartition('@')\n    return (user if delim else None), host\n\n\n# adding a timeout to avoid freezing package_index\nopen_with_auth = socket_timeout(_SOCKET_TIMEOUT)(open_with_auth)\n\n\ndef fix_sf_url(url):\n    return url  # backward compatibility\n\n\ndef local_open(url):\n    \"\"\"Read a local path, with special support for directories\"\"\"\n    scheme, server, path, param, query, frag = urllib.parse.urlparse(url)\n    filename = urllib.request.url2pathname(path)\n    if os.path.isfile(filename):\n        return urllib.request.urlopen(url)\n    elif path.endswith('/') and os.path.isdir(filename):\n        files = []\n        for f in os.listdir(filename):\n            filepath = os.path.join(filename, f)\n            if f == 'index.html':\n                with open(filepath, 'r') as fp:\n                    body = fp.read()\n                break\n            elif os.path.isdir(filepath):\n                f += '/'\n            files.append('<a href=\"{name}\">{name}</a>'.format(name=f))\n        else:\n            tmpl = (\n                \"<html><head><title>{url}</title>\" \"</head><body>{files}</body></html>\"\n            )\n            body = tmpl.format(url=url, files='\\n'.join(files))\n        status, message = 200, \"OK\"\n    else:\n        status, message, body = 404, \"Path not found\", \"Not found\"\n\n    headers = {'content-type': 'text/html'}\n    body_stream = io.StringIO(body)\n    return urllib.error.HTTPError(url, status, message, headers, body_stream)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/py34compat.py",
    "content": "import importlib\n\ntry:\n    import importlib.util\nexcept ImportError:\n    pass\n\n\ntry:\n    module_from_spec = importlib.util.module_from_spec\nexcept AttributeError:\n    def module_from_spec(spec):\n        return spec.loader.load_module(spec.name)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/sandbox.py",
    "content": "import os\nimport sys\nimport tempfile\nimport operator\nimport functools\nimport itertools\nimport re\nimport contextlib\nimport pickle\nimport textwrap\nimport builtins\n\nimport pkg_resources\nfrom distutils.errors import DistutilsError\nfrom pkg_resources import working_set\n\nif sys.platform.startswith('java'):\n    import org.python.modules.posix.PosixModule as _os\nelse:\n    _os = sys.modules[os.name]\ntry:\n    _file = file\nexcept NameError:\n    _file = None\n_open = open\n\n\n__all__ = [\n    \"AbstractSandbox\",\n    \"DirectorySandbox\",\n    \"SandboxViolation\",\n    \"run_setup\",\n]\n\n\ndef _execfile(filename, globals, locals=None):\n    \"\"\"\n    Python 3 implementation of execfile.\n    \"\"\"\n    mode = 'rb'\n    with open(filename, mode) as stream:\n        script = stream.read()\n    if locals is None:\n        locals = globals\n    code = compile(script, filename, 'exec')\n    exec(code, globals, locals)\n\n\n@contextlib.contextmanager\ndef save_argv(repl=None):\n    saved = sys.argv[:]\n    if repl is not None:\n        sys.argv[:] = repl\n    try:\n        yield saved\n    finally:\n        sys.argv[:] = saved\n\n\n@contextlib.contextmanager\ndef save_path():\n    saved = sys.path[:]\n    try:\n        yield saved\n    finally:\n        sys.path[:] = saved\n\n\n@contextlib.contextmanager\ndef override_temp(replacement):\n    \"\"\"\n    Monkey-patch tempfile.tempdir with replacement, ensuring it exists\n    \"\"\"\n    os.makedirs(replacement, exist_ok=True)\n\n    saved = tempfile.tempdir\n\n    tempfile.tempdir = replacement\n\n    try:\n        yield\n    finally:\n        tempfile.tempdir = saved\n\n\n@contextlib.contextmanager\ndef pushd(target):\n    saved = os.getcwd()\n    os.chdir(target)\n    try:\n        yield saved\n    finally:\n        os.chdir(saved)\n\n\nclass UnpickleableException(Exception):\n    \"\"\"\n    An exception representing another Exception that could not be pickled.\n    \"\"\"\n\n    @staticmethod\n    def dump(type, exc):\n        \"\"\"\n        Always return a dumped (pickled) type and exc. If exc can't be pickled,\n        wrap it in UnpickleableException first.\n        \"\"\"\n        try:\n            return pickle.dumps(type), pickle.dumps(exc)\n        except Exception:\n            # get UnpickleableException inside the sandbox\n            from setuptools.sandbox import UnpickleableException as cls\n\n            return cls.dump(cls, cls(repr(exc)))\n\n\nclass ExceptionSaver:\n    \"\"\"\n    A Context Manager that will save an exception, serialized, and restore it\n    later.\n    \"\"\"\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, type, exc, tb):\n        if not exc:\n            return\n\n        # dump the exception\n        self._saved = UnpickleableException.dump(type, exc)\n        self._tb = tb\n\n        # suppress the exception\n        return True\n\n    def resume(self):\n        \"restore and re-raise any exception\"\n\n        if '_saved' not in vars(self):\n            return\n\n        type, exc = map(pickle.loads, self._saved)\n        raise exc.with_traceback(self._tb)\n\n\n@contextlib.contextmanager\ndef save_modules():\n    \"\"\"\n    Context in which imported modules are saved.\n\n    Translates exceptions internal to the context into the equivalent exception\n    outside the context.\n    \"\"\"\n    saved = sys.modules.copy()\n    with ExceptionSaver() as saved_exc:\n        yield saved\n\n    sys.modules.update(saved)\n    # remove any modules imported since\n    del_modules = (\n        mod_name\n        for mod_name in sys.modules\n        if mod_name not in saved\n        # exclude any encodings modules. See #285\n        and not mod_name.startswith('encodings.')\n    )\n    _clear_modules(del_modules)\n\n    saved_exc.resume()\n\n\ndef _clear_modules(module_names):\n    for mod_name in list(module_names):\n        del sys.modules[mod_name]\n\n\n@contextlib.contextmanager\ndef save_pkg_resources_state():\n    saved = pkg_resources.__getstate__()\n    try:\n        yield saved\n    finally:\n        pkg_resources.__setstate__(saved)\n\n\n@contextlib.contextmanager\ndef setup_context(setup_dir):\n    temp_dir = os.path.join(setup_dir, 'temp')\n    with save_pkg_resources_state():\n        with save_modules():\n            with save_path():\n                hide_setuptools()\n                with save_argv():\n                    with override_temp(temp_dir):\n                        with pushd(setup_dir):\n                            # ensure setuptools commands are available\n                            __import__('setuptools')\n                            yield\n\n\n_MODULES_TO_HIDE = {\n    'setuptools',\n    'distutils',\n    'pkg_resources',\n    'Cython',\n    '_distutils_hack',\n}\n\n\ndef _needs_hiding(mod_name):\n    \"\"\"\n    >>> _needs_hiding('setuptools')\n    True\n    >>> _needs_hiding('pkg_resources')\n    True\n    >>> _needs_hiding('setuptools_plugin')\n    False\n    >>> _needs_hiding('setuptools.__init__')\n    True\n    >>> _needs_hiding('distutils')\n    True\n    >>> _needs_hiding('os')\n    False\n    >>> _needs_hiding('Cython')\n    True\n    \"\"\"\n    base_module = mod_name.split('.', 1)[0]\n    return base_module in _MODULES_TO_HIDE\n\n\ndef hide_setuptools():\n    \"\"\"\n    Remove references to setuptools' modules from sys.modules to allow the\n    invocation to import the most appropriate setuptools. This technique is\n    necessary to avoid issues such as #315 where setuptools upgrading itself\n    would fail to find a function declared in the metadata.\n    \"\"\"\n    _distutils_hack = sys.modules.get('_distutils_hack', None)\n    if _distutils_hack is not None:\n        _distutils_hack.remove_shim()\n\n    modules = filter(_needs_hiding, sys.modules)\n    _clear_modules(modules)\n\n\ndef run_setup(setup_script, args):\n    \"\"\"Run a distutils setup script, sandboxed in its directory\"\"\"\n    setup_dir = os.path.abspath(os.path.dirname(setup_script))\n    with setup_context(setup_dir):\n        try:\n            sys.argv[:] = [setup_script] + list(args)\n            sys.path.insert(0, setup_dir)\n            # reset to include setup dir, w/clean callback list\n            working_set.__init__()\n            working_set.callbacks.append(lambda dist: dist.activate())\n\n            with DirectorySandbox(setup_dir):\n                ns = dict(__file__=setup_script, __name__='__main__')\n                _execfile(setup_script, ns)\n        except SystemExit as v:\n            if v.args and v.args[0]:\n                raise\n            # Normal exit, just return\n\n\nclass AbstractSandbox:\n    \"\"\"Wrap 'os' module and 'open()' builtin for virtualizing setup scripts\"\"\"\n\n    _active = False\n\n    def __init__(self):\n        self._attrs = [\n            name\n            for name in dir(_os)\n            if not name.startswith('_') and hasattr(self, name)\n        ]\n\n    def _copy(self, source):\n        for name in self._attrs:\n            setattr(os, name, getattr(source, name))\n\n    def __enter__(self):\n        self._copy(self)\n        if _file:\n            builtins.file = self._file\n        builtins.open = self._open\n        self._active = True\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        self._active = False\n        if _file:\n            builtins.file = _file\n        builtins.open = _open\n        self._copy(_os)\n\n    def run(self, func):\n        \"\"\"Run 'func' under os sandboxing\"\"\"\n        with self:\n            return func()\n\n    def _mk_dual_path_wrapper(name):\n        original = getattr(_os, name)\n\n        def wrap(self, src, dst, *args, **kw):\n            if self._active:\n                src, dst = self._remap_pair(name, src, dst, *args, **kw)\n            return original(src, dst, *args, **kw)\n\n        return wrap\n\n    for name in [\"rename\", \"link\", \"symlink\"]:\n        if hasattr(_os, name):\n            locals()[name] = _mk_dual_path_wrapper(name)\n\n    def _mk_single_path_wrapper(name, original=None):\n        original = original or getattr(_os, name)\n\n        def wrap(self, path, *args, **kw):\n            if self._active:\n                path = self._remap_input(name, path, *args, **kw)\n            return original(path, *args, **kw)\n\n        return wrap\n\n    if _file:\n        _file = _mk_single_path_wrapper('file', _file)\n    _open = _mk_single_path_wrapper('open', _open)\n    for name in [\n        \"stat\",\n        \"listdir\",\n        \"chdir\",\n        \"open\",\n        \"chmod\",\n        \"chown\",\n        \"mkdir\",\n        \"remove\",\n        \"unlink\",\n        \"rmdir\",\n        \"utime\",\n        \"lchown\",\n        \"chroot\",\n        \"lstat\",\n        \"startfile\",\n        \"mkfifo\",\n        \"mknod\",\n        \"pathconf\",\n        \"access\",\n    ]:\n        if hasattr(_os, name):\n            locals()[name] = _mk_single_path_wrapper(name)\n\n    def _mk_single_with_return(name):\n        original = getattr(_os, name)\n\n        def wrap(self, path, *args, **kw):\n            if self._active:\n                path = self._remap_input(name, path, *args, **kw)\n                return self._remap_output(name, original(path, *args, **kw))\n            return original(path, *args, **kw)\n\n        return wrap\n\n    for name in ['readlink', 'tempnam']:\n        if hasattr(_os, name):\n            locals()[name] = _mk_single_with_return(name)\n\n    def _mk_query(name):\n        original = getattr(_os, name)\n\n        def wrap(self, *args, **kw):\n            retval = original(*args, **kw)\n            if self._active:\n                return self._remap_output(name, retval)\n            return retval\n\n        return wrap\n\n    for name in ['getcwd', 'tmpnam']:\n        if hasattr(_os, name):\n            locals()[name] = _mk_query(name)\n\n    def _validate_path(self, path):\n        \"\"\"Called to remap or validate any path, whether input or output\"\"\"\n        return path\n\n    def _remap_input(self, operation, path, *args, **kw):\n        \"\"\"Called for path inputs\"\"\"\n        return self._validate_path(path)\n\n    def _remap_output(self, operation, path):\n        \"\"\"Called for path outputs\"\"\"\n        return self._validate_path(path)\n\n    def _remap_pair(self, operation, src, dst, *args, **kw):\n        \"\"\"Called for path pairs like rename, link, and symlink operations\"\"\"\n        return (\n            self._remap_input(operation + '-from', src, *args, **kw),\n            self._remap_input(operation + '-to', dst, *args, **kw),\n        )\n\n\nif hasattr(os, 'devnull'):\n    _EXCEPTIONS = [os.devnull]\nelse:\n    _EXCEPTIONS = []\n\n\nclass DirectorySandbox(AbstractSandbox):\n    \"\"\"Restrict operations to a single subdirectory - pseudo-chroot\"\"\"\n\n    write_ops = dict.fromkeys(\n        [\n            \"open\",\n            \"chmod\",\n            \"chown\",\n            \"mkdir\",\n            \"remove\",\n            \"unlink\",\n            \"rmdir\",\n            \"utime\",\n            \"lchown\",\n            \"chroot\",\n            \"mkfifo\",\n            \"mknod\",\n            \"tempnam\",\n        ]\n    )\n\n    _exception_patterns = []\n    \"exempt writing to paths that match the pattern\"\n\n    def __init__(self, sandbox, exceptions=_EXCEPTIONS):\n        self._sandbox = os.path.normcase(os.path.realpath(sandbox))\n        self._prefix = os.path.join(self._sandbox, '')\n        self._exceptions = [\n            os.path.normcase(os.path.realpath(path)) for path in exceptions\n        ]\n        AbstractSandbox.__init__(self)\n\n    def _violation(self, operation, *args, **kw):\n        from setuptools.sandbox import SandboxViolation\n\n        raise SandboxViolation(operation, args, kw)\n\n    if _file:\n\n        def _file(self, path, mode='r', *args, **kw):\n            if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):\n                self._violation(\"file\", path, mode, *args, **kw)\n            return _file(path, mode, *args, **kw)\n\n    def _open(self, path, mode='r', *args, **kw):\n        if mode not in ('r', 'rt', 'rb', 'rU', 'U') and not self._ok(path):\n            self._violation(\"open\", path, mode, *args, **kw)\n        return _open(path, mode, *args, **kw)\n\n    def tmpnam(self):\n        self._violation(\"tmpnam\")\n\n    def _ok(self, path):\n        active = self._active\n        try:\n            self._active = False\n            realpath = os.path.normcase(os.path.realpath(path))\n            return (\n                self._exempted(realpath)\n                or realpath == self._sandbox\n                or realpath.startswith(self._prefix)\n            )\n        finally:\n            self._active = active\n\n    def _exempted(self, filepath):\n        start_matches = (\n            filepath.startswith(exception) for exception in self._exceptions\n        )\n        pattern_matches = (\n            re.match(pattern, filepath) for pattern in self._exception_patterns\n        )\n        candidates = itertools.chain(start_matches, pattern_matches)\n        return any(candidates)\n\n    def _remap_input(self, operation, path, *args, **kw):\n        \"\"\"Called for path inputs\"\"\"\n        if operation in self.write_ops and not self._ok(path):\n            self._violation(operation, os.path.realpath(path), *args, **kw)\n        return path\n\n    def _remap_pair(self, operation, src, dst, *args, **kw):\n        \"\"\"Called for path pairs like rename, link, and symlink operations\"\"\"\n        if not self._ok(src) or not self._ok(dst):\n            self._violation(operation, src, dst, *args, **kw)\n        return (src, dst)\n\n    def open(self, file, flags, mode=0o777, *args, **kw):\n        \"\"\"Called for low-level os.open()\"\"\"\n        if flags & WRITE_FLAGS and not self._ok(file):\n            self._violation(\"os.open\", file, flags, mode, *args, **kw)\n        return _os.open(file, flags, mode, *args, **kw)\n\n\nWRITE_FLAGS = functools.reduce(\n    operator.or_,\n    [\n        getattr(_os, a, 0)\n        for a in \"O_WRONLY O_RDWR O_APPEND O_CREAT O_TRUNC O_TEMPORARY\".split()\n    ],\n)\n\n\nclass SandboxViolation(DistutilsError):\n    \"\"\"A setup script attempted to modify the filesystem outside the sandbox\"\"\"\n\n    tmpl = textwrap.dedent(\n        \"\"\"\n        SandboxViolation: {cmd}{args!r} {kwargs}\n\n        The package setup script has attempted to modify files on your system\n        that are not within the EasyInstall build area, and has been aborted.\n\n        This package cannot be safely installed by EasyInstall, and may not\n        support alternate installation locations even if you run its setup\n        script by hand.  Please inform the package's author and the EasyInstall\n        maintainers to find out if a fix or workaround is available.\n        \"\"\"\n    ).lstrip()\n\n    def __str__(self):\n        cmd, args, kwargs = self.args\n        return self.tmpl.format(**locals())\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/script (dev).tmpl",
    "content": "# EASY-INSTALL-DEV-SCRIPT: %(spec)r,%(script_name)r\n__requires__ = %(spec)r\n__import__('pkg_resources').require(%(spec)r)\n__file__ = %(dev_path)r\nwith open(__file__) as f:\n    exec(compile(f.read(), __file__, 'exec'))\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/script.tmpl",
    "content": "# EASY-INSTALL-SCRIPT: %(spec)r,%(script_name)r\n__requires__ = %(spec)r\n__import__('pkg_resources').run_script(%(spec)r, %(script_name)r)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/unicode_utils.py",
    "content": "import unicodedata\nimport sys\n\n\n# HFS Plus uses decomposed UTF-8\ndef decompose(path):\n    if isinstance(path, str):\n        return unicodedata.normalize('NFD', path)\n    try:\n        path = path.decode('utf-8')\n        path = unicodedata.normalize('NFD', path)\n        path = path.encode('utf-8')\n    except UnicodeError:\n        pass  # Not UTF-8\n    return path\n\n\ndef filesys_decode(path):\n    \"\"\"\n    Ensure that the given path is decoded,\n    NONE when no expected encoding works\n    \"\"\"\n\n    if isinstance(path, str):\n        return path\n\n    fs_enc = sys.getfilesystemencoding() or 'utf-8'\n    candidates = fs_enc, 'utf-8'\n\n    for enc in candidates:\n        try:\n            return path.decode(enc)\n        except UnicodeDecodeError:\n            continue\n\n\ndef try_encode(string, enc):\n    \"turn unicode encoding into a functional routine\"\n    try:\n        return string.encode(enc)\n    except UnicodeEncodeError:\n        return None\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/version.py",
    "content": "import pkg_resources\n\ntry:\n    __version__ = pkg_resources.get_distribution('setuptools').version\nexcept Exception:\n    __version__ = 'unknown'\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/wheel.py",
    "content": "\"\"\"Wheels support.\"\"\"\n\nimport email\nimport itertools\nimport os\nimport posixpath\nimport re\nimport zipfile\nimport contextlib\n\nfrom distutils.util import get_platform\n\nimport pkg_resources\nimport setuptools\nfrom pkg_resources import parse_version\nfrom setuptools.extern.packaging.tags import sys_tags\nfrom setuptools.extern.packaging.utils import canonicalize_name\nfrom setuptools.command.egg_info import write_requirements\nfrom setuptools.archive_util import _unpack_zipfile_obj\n\n\nWHEEL_NAME = re.compile(\n    r\"\"\"^(?P<project_name>.+?)-(?P<version>\\d.*?)\n    ((-(?P<build>\\d.*?))?-(?P<py_version>.+?)-(?P<abi>.+?)-(?P<platform>.+?)\n    )\\.whl$\"\"\",\n    re.VERBOSE).match\n\nNAMESPACE_PACKAGE_INIT = \\\n    \"__import__('pkg_resources').declare_namespace(__name__)\\n\"\n\n\ndef unpack(src_dir, dst_dir):\n    '''Move everything under `src_dir` to `dst_dir`, and delete the former.'''\n    for dirpath, dirnames, filenames in os.walk(src_dir):\n        subdir = os.path.relpath(dirpath, src_dir)\n        for f in filenames:\n            src = os.path.join(dirpath, f)\n            dst = os.path.join(dst_dir, subdir, f)\n            os.renames(src, dst)\n        for n, d in reversed(list(enumerate(dirnames))):\n            src = os.path.join(dirpath, d)\n            dst = os.path.join(dst_dir, subdir, d)\n            if not os.path.exists(dst):\n                # Directory does not exist in destination,\n                # rename it and prune it from os.walk list.\n                os.renames(src, dst)\n                del dirnames[n]\n    # Cleanup.\n    for dirpath, dirnames, filenames in os.walk(src_dir, topdown=True):\n        assert not filenames\n        os.rmdir(dirpath)\n\n\n@contextlib.contextmanager\ndef disable_info_traces():\n    \"\"\"\n    Temporarily disable info traces.\n    \"\"\"\n    from distutils import log\n    saved = log.set_threshold(log.WARN)\n    try:\n        yield\n    finally:\n        log.set_threshold(saved)\n\n\nclass Wheel:\n\n    def __init__(self, filename):\n        match = WHEEL_NAME(os.path.basename(filename))\n        if match is None:\n            raise ValueError('invalid wheel name: %r' % filename)\n        self.filename = filename\n        for k, v in match.groupdict().items():\n            setattr(self, k, v)\n\n    def tags(self):\n        '''List tags (py_version, abi, platform) supported by this wheel.'''\n        return itertools.product(\n            self.py_version.split('.'),\n            self.abi.split('.'),\n            self.platform.split('.'),\n        )\n\n    def is_compatible(self):\n        '''Is the wheel is compatible with the current platform?'''\n        supported_tags = set(\n            (t.interpreter, t.abi, t.platform) for t in sys_tags())\n        return next((True for t in self.tags() if t in supported_tags), False)\n\n    def egg_name(self):\n        return pkg_resources.Distribution(\n            project_name=self.project_name, version=self.version,\n            platform=(None if self.platform == 'any' else get_platform()),\n        ).egg_name() + '.egg'\n\n    def get_dist_info(self, zf):\n        # find the correct name of the .dist-info dir in the wheel file\n        for member in zf.namelist():\n            dirname = posixpath.dirname(member)\n            if (dirname.endswith('.dist-info') and\n                    canonicalize_name(dirname).startswith(\n                        canonicalize_name(self.project_name))):\n                return dirname\n        raise ValueError(\"unsupported wheel format. .dist-info not found\")\n\n    def install_as_egg(self, destination_eggdir):\n        '''Install wheel as an egg directory.'''\n        with zipfile.ZipFile(self.filename) as zf:\n            self._install_as_egg(destination_eggdir, zf)\n\n    def _install_as_egg(self, destination_eggdir, zf):\n        dist_basename = '%s-%s' % (self.project_name, self.version)\n        dist_info = self.get_dist_info(zf)\n        dist_data = '%s.data' % dist_basename\n        egg_info = os.path.join(destination_eggdir, 'EGG-INFO')\n\n        self._convert_metadata(zf, destination_eggdir, dist_info, egg_info)\n        self._move_data_entries(destination_eggdir, dist_data)\n        self._fix_namespace_packages(egg_info, destination_eggdir)\n\n    @staticmethod\n    def _convert_metadata(zf, destination_eggdir, dist_info, egg_info):\n        def get_metadata(name):\n            with zf.open(posixpath.join(dist_info, name)) as fp:\n                value = fp.read().decode('utf-8')\n                return email.parser.Parser().parsestr(value)\n\n        wheel_metadata = get_metadata('WHEEL')\n        # Check wheel format version is supported.\n        wheel_version = parse_version(wheel_metadata.get('Wheel-Version'))\n        wheel_v1 = (\n            parse_version('1.0') <= wheel_version < parse_version('2.0dev0')\n        )\n        if not wheel_v1:\n            raise ValueError(\n                'unsupported wheel format version: %s' % wheel_version)\n        # Extract to target directory.\n        _unpack_zipfile_obj(zf, destination_eggdir)\n        # Convert metadata.\n        dist_info = os.path.join(destination_eggdir, dist_info)\n        dist = pkg_resources.Distribution.from_location(\n            destination_eggdir, dist_info,\n            metadata=pkg_resources.PathMetadata(destination_eggdir, dist_info),\n        )\n\n        # Note: Evaluate and strip markers now,\n        # as it's difficult to convert back from the syntax:\n        # foobar; \"linux\" in sys_platform and extra == 'test'\n        def raw_req(req):\n            req.marker = None\n            return str(req)\n        install_requires = list(map(raw_req, dist.requires()))\n        extras_require = {\n            extra: [\n                req\n                for req in map(raw_req, dist.requires((extra,)))\n                if req not in install_requires\n            ]\n            for extra in dist.extras\n        }\n        os.rename(dist_info, egg_info)\n        os.rename(\n            os.path.join(egg_info, 'METADATA'),\n            os.path.join(egg_info, 'PKG-INFO'),\n        )\n        setup_dist = setuptools.Distribution(\n            attrs=dict(\n                install_requires=install_requires,\n                extras_require=extras_require,\n            ),\n        )\n        with disable_info_traces():\n            write_requirements(\n                setup_dist.get_command_obj('egg_info'),\n                None,\n                os.path.join(egg_info, 'requires.txt'),\n            )\n\n    @staticmethod\n    def _move_data_entries(destination_eggdir, dist_data):\n        \"\"\"Move data entries to their correct location.\"\"\"\n        dist_data = os.path.join(destination_eggdir, dist_data)\n        dist_data_scripts = os.path.join(dist_data, 'scripts')\n        if os.path.exists(dist_data_scripts):\n            egg_info_scripts = os.path.join(\n                destination_eggdir, 'EGG-INFO', 'scripts')\n            os.mkdir(egg_info_scripts)\n            for entry in os.listdir(dist_data_scripts):\n                # Remove bytecode, as it's not properly handled\n                # during easy_install scripts install phase.\n                if entry.endswith('.pyc'):\n                    os.unlink(os.path.join(dist_data_scripts, entry))\n                else:\n                    os.rename(\n                        os.path.join(dist_data_scripts, entry),\n                        os.path.join(egg_info_scripts, entry),\n                    )\n            os.rmdir(dist_data_scripts)\n        for subdir in filter(os.path.exists, (\n            os.path.join(dist_data, d)\n            for d in ('data', 'headers', 'purelib', 'platlib')\n        )):\n            unpack(subdir, destination_eggdir)\n        if os.path.exists(dist_data):\n            os.rmdir(dist_data)\n\n    @staticmethod\n    def _fix_namespace_packages(egg_info, destination_eggdir):\n        namespace_packages = os.path.join(\n            egg_info, 'namespace_packages.txt')\n        if os.path.exists(namespace_packages):\n            with open(namespace_packages) as fp:\n                namespace_packages = fp.read().split()\n            for mod in namespace_packages:\n                mod_dir = os.path.join(destination_eggdir, *mod.split('.'))\n                mod_init = os.path.join(mod_dir, '__init__.py')\n                if not os.path.exists(mod_dir):\n                    os.mkdir(mod_dir)\n                if not os.path.exists(mod_init):\n                    with open(mod_init, 'w') as fp:\n                        fp.write(NAMESPACE_PACKAGE_INIT)\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools/windows_support.py",
    "content": "import platform\n\n\ndef windows_only(func):\n    if platform.system() != 'Windows':\n        return lambda *args, **kwargs: None\n    return func\n\n\n@windows_only\ndef hide_file(path):\n    \"\"\"\n    Set the hidden attribute on a file or directory.\n\n    From http://stackoverflow.com/questions/19622133/\n\n    `path` must be text.\n    \"\"\"\n    import ctypes\n    __import__('ctypes.wintypes')\n    SetFileAttributes = ctypes.windll.kernel32.SetFileAttributesW\n    SetFileAttributes.argtypes = ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD\n    SetFileAttributes.restype = ctypes.wintypes.BOOL\n\n    FILE_ATTRIBUTE_HIDDEN = 0x02\n\n    ret = SetFileAttributes(path, FILE_ATTRIBUTE_HIDDEN)\n    if not ret:\n        raise ctypes.WinError()\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools-65.5.1.dist-info/INSTALLER",
    "content": "pip\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools-65.5.1.dist-info/LICENSE",
    "content": "Copyright Jason R. Coombs\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to\ndeal in the Software without restriction, including without limitation the\nrights to use, copy, modify, merge, publish, distribute, sublicense, and/or\nsell copies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\nIN THE SOFTWARE.\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools-65.5.1.dist-info/METADATA",
    "content": "Metadata-Version: 2.1\nName: setuptools\nVersion: 65.5.1\nSummary: Easily download, build, install, upgrade, and uninstall Python packages\nHome-page: https://github.com/pypa/setuptools\nAuthor: Python Packaging Authority\nAuthor-email: distutils-sig@python.org\nProject-URL: Documentation, https://setuptools.pypa.io/\nProject-URL: Changelog, https://setuptools.pypa.io/en/stable/history.html\nKeywords: CPAN PyPI distutils eggs package management\nClassifier: Development Status :: 5 - Production/Stable\nClassifier: Intended Audience :: Developers\nClassifier: License :: OSI Approved :: MIT License\nClassifier: Programming Language :: Python :: 3\nClassifier: Programming Language :: Python :: 3 :: Only\nClassifier: Topic :: Software Development :: Libraries :: Python Modules\nClassifier: Topic :: System :: Archiving :: Packaging\nClassifier: Topic :: System :: Systems Administration\nClassifier: Topic :: Utilities\nRequires-Python: >=3.7\nLicense-File: LICENSE\nProvides-Extra: certs\nProvides-Extra: docs\nRequires-Dist: sphinx (>=3.5) ; extra == 'docs'\nRequires-Dist: jaraco.packaging (>=9) ; extra == 'docs'\nRequires-Dist: rst.linker (>=1.9) ; extra == 'docs'\nRequires-Dist: furo ; extra == 'docs'\nRequires-Dist: jaraco.tidelift (>=1.4) ; extra == 'docs'\nRequires-Dist: pygments-github-lexers (==0.0.5) ; extra == 'docs'\nRequires-Dist: sphinx-favicon ; extra == 'docs'\nRequires-Dist: sphinx-inline-tabs ; extra == 'docs'\nRequires-Dist: sphinx-reredirects ; extra == 'docs'\nRequires-Dist: sphinxcontrib-towncrier ; extra == 'docs'\nRequires-Dist: sphinx-notfound-page (==0.8.3) ; extra == 'docs'\nRequires-Dist: sphinx-hoverxref (<2) ; extra == 'docs'\nProvides-Extra: ssl\nProvides-Extra: testing\nRequires-Dist: pytest (>=6) ; extra == 'testing'\nRequires-Dist: pytest-checkdocs (>=2.4) ; extra == 'testing'\nRequires-Dist: pytest-flake8 ; extra == 'testing'\nRequires-Dist: flake8 (<5) ; extra == 'testing'\nRequires-Dist: pytest-enabler (>=1.3) ; extra == 'testing'\nRequires-Dist: pytest-perf ; extra == 'testing'\nRequires-Dist: flake8-2020 ; extra == 'testing'\nRequires-Dist: virtualenv (>=13.0.0) ; extra == 'testing'\nRequires-Dist: wheel ; extra == 'testing'\nRequires-Dist: pip (>=19.1) ; extra == 'testing'\nRequires-Dist: jaraco.envs (>=2.2) ; extra == 'testing'\nRequires-Dist: pytest-xdist ; extra == 'testing'\nRequires-Dist: jaraco.path (>=3.2.0) ; extra == 'testing'\nRequires-Dist: build[virtualenv] ; extra == 'testing'\nRequires-Dist: filelock (>=3.4.0) ; extra == 'testing'\nRequires-Dist: pip-run (>=8.8) ; extra == 'testing'\nRequires-Dist: ini2toml[lite] (>=0.9) ; extra == 'testing'\nRequires-Dist: tomli-w (>=1.0.0) ; extra == 'testing'\nRequires-Dist: pytest-timeout ; extra == 'testing'\nProvides-Extra: testing-integration\nRequires-Dist: pytest ; extra == 'testing-integration'\nRequires-Dist: pytest-xdist ; extra == 'testing-integration'\nRequires-Dist: pytest-enabler ; extra == 'testing-integration'\nRequires-Dist: virtualenv (>=13.0.0) ; extra == 'testing-integration'\nRequires-Dist: tomli ; extra == 'testing-integration'\nRequires-Dist: wheel ; extra == 'testing-integration'\nRequires-Dist: jaraco.path (>=3.2.0) ; extra == 'testing-integration'\nRequires-Dist: jaraco.envs (>=2.2) ; extra == 'testing-integration'\nRequires-Dist: build[virtualenv] ; extra == 'testing-integration'\nRequires-Dist: filelock (>=3.4.0) ; extra == 'testing-integration'\nRequires-Dist: pytest-black (>=0.3.7) ; (platform_python_implementation != \"PyPy\") and extra == 'testing'\nRequires-Dist: pytest-cov ; (platform_python_implementation != \"PyPy\") and extra == 'testing'\nRequires-Dist: pytest-mypy (>=0.9.1) ; (platform_python_implementation != \"PyPy\") and extra == 'testing'\n\n.. image:: https://raw.githubusercontent.com/pypa/setuptools/main/docs/images/banner-640x320.svg\n   :align: center\n\n|\n\n.. image:: https://img.shields.io/pypi/v/setuptools.svg\n   :target: `PyPI link`_\n\n.. image:: https://img.shields.io/pypi/pyversions/setuptools.svg\n   :target: `PyPI link`_\n\n.. _PyPI link: https://pypi.org/project/setuptools\n\n.. image:: https://github.com/pypa/setuptools/workflows/tests/badge.svg\n   :target: https://github.com/pypa/setuptools/actions?query=workflow%3A%22tests%22\n   :alt: tests\n\n.. image:: https://img.shields.io/badge/code%20style-black-000000.svg\n   :target: https://github.com/psf/black\n   :alt: Code style: Black\n\n.. image:: https://img.shields.io/readthedocs/setuptools/latest.svg\n    :target: https://setuptools.pypa.io\n\n.. image:: https://img.shields.io/badge/skeleton-2022-informational\n   :target: https://blog.jaraco.com/skeleton\n\n.. image:: https://img.shields.io/codecov/c/github/pypa/setuptools/master.svg?logo=codecov&logoColor=white\n   :target: https://codecov.io/gh/pypa/setuptools\n\n.. image:: https://tidelift.com/badges/github/pypa/setuptools?style=flat\n   :target: https://tidelift.com/subscription/pkg/pypi-setuptools?utm_source=pypi-setuptools&utm_medium=readme\n\n.. image:: https://img.shields.io/discord/803025117553754132\n   :target: https://discord.com/channels/803025117553754132/815945031150993468\n   :alt: Discord\n\nSee the `Installation Instructions\n<https://packaging.python.org/installing/>`_ in the Python Packaging\nUser's Guide for instructions on installing, upgrading, and uninstalling\nSetuptools.\n\nQuestions and comments should be directed to `GitHub Discussions\n<https://github.com/pypa/setuptools/discussions>`_.\nBug reports and especially tested patches may be\nsubmitted directly to the `bug tracker\n<https://github.com/pypa/setuptools/issues>`_.\n\n\nCode of Conduct\n===============\n\nEveryone interacting in the setuptools project's codebases, issue trackers,\nchat rooms, and fora is expected to follow the\n`PSF Code of Conduct <https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md>`_.\n\n\nFor Enterprise\n==============\n\nAvailable as part of the Tidelift Subscription.\n\nSetuptools and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.\n\n`Learn more <https://tidelift.com/subscription/pkg/pypi-setuptools?utm_source=pypi-setuptools&utm_medium=referral&utm_campaign=github>`_.\n\n\nSecurity Contact\n================\n\nTo report a security vulnerability, please use the\n`Tidelift security contact <https://tidelift.com/security>`_.\nTidelift will coordinate the fix and disclosure.\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools-65.5.1.dist-info/RECORD",
    "content": "distutils-precedence.pth,sha256=JjjOniUA5XKl4N5_rtZmHrVp0baW_LoHsN0iPaX10iQ,151\n_distutils_hack/__init__.py,sha256=TSekhUW1fdE3rjU3b88ybSBkJxCEpIeWBob4cEuU3ko,6128\n_distutils_hack/override.py,sha256=Eu_s-NF6VIZ4Cqd0tbbA5wtWky2IZPNd8et6GLt1mzo,44\npkg_resources/__init__.py,sha256=fT5Y3P1tcSX8sJomClUU10WHeFmvqyNZM4UZHzdpAvg,108568\npkg_resources/_vendor/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npkg_resources/_vendor/appdirs.py,sha256=MievUEuv3l_mQISH5SF0shDk_BNhHHzYiAPrT3ITN4I,24701\npkg_resources/_vendor/zipp.py,sha256=ajztOH-9I7KA_4wqDYygtHa6xUBVZgFpmZ8FE74HHHI,8425\npkg_resources/_vendor/importlib_resources/__init__.py,sha256=evPm12kLgYqTm-pbzm60bOuumumT8IpBNWFp0uMyrzE,506\npkg_resources/_vendor/importlib_resources/_adapters.py,sha256=o51tP2hpVtohP33gSYyAkGNpLfYDBqxxYsadyiRZi1E,4504\npkg_resources/_vendor/importlib_resources/_common.py,sha256=iIxAaQhotSh6TLLUEfL_ynU2fzEeyHMz9JcL46mUhLg,2741\npkg_resources/_vendor/importlib_resources/_compat.py,sha256=nFBCGMvImglrqgYkb9aPgOj68-h6xbw-ca94XOv1-zs,2706\npkg_resources/_vendor/importlib_resources/_itertools.py,sha256=WCdJ1Gs_kNFwKENyIG7TO0Y434IWCu0zjVVSsSbZwU8,884\npkg_resources/_vendor/importlib_resources/_legacy.py,sha256=TMLkx6aEM6U8xIREPXqGZrMbUhTiPUuPl6ESD7RdYj4,3494\npkg_resources/_vendor/importlib_resources/abc.py,sha256=MvTJJXajbl74s36Gyeesf76egtbFnh-TMtzQMVhFWXo,3886\npkg_resources/_vendor/importlib_resources/readers.py,sha256=_9QLGQ5AzrED3PY8S2Zf8V6yLR0-nqqYqtQmgleDJzY,3566\npkg_resources/_vendor/importlib_resources/simple.py,sha256=xt0qhXbwt3bZ86zuaaKbTiE9A0mDbwu0saRjUq_pcY0,2836\npkg_resources/_vendor/jaraco/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\npkg_resources/_vendor/jaraco/context.py,sha256=7X1tpCLc5EN45iWGzGcsH0Unx62REIkvtRvglj0SiUA,5420\npkg_resources/_vendor/jaraco/functools.py,sha256=eLwPh8FWY7rQ_cj1YxCekUkibTuerwyoJ_41H7Q7oWM,13515\npkg_resources/_vendor/jaraco/text/__init__.py,sha256=cN55bFcceW4wTHG5ruv5IuEDRarP-4hBYX8zl94_c30,15526\npkg_resources/_vendor/more_itertools/__init__.py,sha256=ZQYu_9H6stSG7viUgT32TFqslqcZwq82kWRZooKiI8Y,83\npkg_resources/_vendor/more_itertools/more.py,sha256=oave_26jctLsuF30e1SOWMgW0bEuwS-t08wkaLUwvXc,132569\npkg_resources/_vendor/more_itertools/recipes.py,sha256=N6aCDwoIPvE-aiqpGU-nbFwqiM3X8MKRcxBM84naW88,18410\npkg_resources/_vendor/packaging/__about__.py,sha256=ugASIO2w1oUyH8_COqQ2X_s0rDhjbhQC3yJocD03h2c,661\npkg_resources/_vendor/packaging/__init__.py,sha256=b9Kk5MF7KxhhLgcDmiUWukN-LatWFxPdNug0joPhHSk,497\npkg_resources/_vendor/packaging/_manylinux.py,sha256=XcbiXB-qcjv3bcohp6N98TMpOP4_j3m-iOA8ptK2GWY,11488\npkg_resources/_vendor/packaging/_musllinux.py,sha256=_KGgY_qc7vhMGpoqss25n2hiLCNKRtvz9mCrS7gkqyc,4378\npkg_resources/_vendor/packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431\npkg_resources/_vendor/packaging/markers.py,sha256=gFSKoBTb0sKDw1v_apJy15lPr0v2mEvuEkfooTtcWx4,8496\npkg_resources/_vendor/packaging/requirements.py,sha256=uJ4cjwm3_nrfHJLCcGU9mT5aw8SXfw8v1aBUD7OFuVs,4706\npkg_resources/_vendor/packaging/specifiers.py,sha256=LRQ0kFsHrl5qfcFNEEJrIFYsnIHQUJXY9fIsakTrrqE,30110\npkg_resources/_vendor/packaging/tags.py,sha256=lmsnGNiJ8C4D_Pf9PbM0qgbZvD9kmB9lpZBQUZa3R_Y,15699\npkg_resources/_vendor/packaging/utils.py,sha256=dJjeat3BS-TYn1RrUFVwufUMasbtzLfYRoy_HXENeFQ,4200\npkg_resources/_vendor/packaging/version.py,sha256=_fLRNrFrxYcHVfyo8vk9j8s6JM8N_xsSxVFr6RJyco8,14665\npkg_resources/_vendor/pyparsing/__init__.py,sha256=52QH3lgPbJhba0estckoGPHRH8JvQSSCGoWiEn2m0bU,9159\npkg_resources/_vendor/pyparsing/actions.py,sha256=wU9i32e0y1ymxKE3OUwSHO-SFIrt1h_wv6Ws0GQjpNU,6426\npkg_resources/_vendor/pyparsing/common.py,sha256=lFL97ooIeR75CmW5hjURZqwDCTgruqltcTCZ-ulLO2Q,12936\npkg_resources/_vendor/pyparsing/core.py,sha256=u8GptQE_H6wMkl8OZhxeK1aAPIDXXNgwdShORBwBVS4,213310\npkg_resources/_vendor/pyparsing/exceptions.py,sha256=3LbSafD32NYb1Tzt85GHNkhEAU1eZkTtNSk24cPMemo,9023\npkg_resources/_vendor/pyparsing/helpers.py,sha256=QpUOjW0-psvueMwWb9bQpU2noqKCv98_wnw1VSzSdVo,39129\npkg_resources/_vendor/pyparsing/results.py,sha256=HgNvWVXBdQP-Q6PtJfoCEeOJk2nwEvG-2KVKC5sGA30,25341\npkg_resources/_vendor/pyparsing/testing.py,sha256=7tu4Abp4uSeJV0N_yEPRmmNUhpd18ZQP3CrX41DM814,13402\npkg_resources/_vendor/pyparsing/unicode.py,sha256=fwuhMj30SQ165Cv7HJpu-rSxGbRm93kN9L4Ei7VGc1Y,10787\npkg_resources/_vendor/pyparsing/util.py,sha256=kq772O5YSeXOSdP-M31EWpbH_ayj7BMHImBYo9xPD5M,6805\npkg_resources/_vendor/pyparsing/diagram/__init__.py,sha256=f_EfxahqrdkRVahmTwLJXkZ9EEDKNd-O7lBbpJYlE1g,23668\npkg_resources/extern/__init__.py,sha256=inFoCK9jn_yRFqkbNSOxOYyZD0aB3awch_xtbwIW_-Y,2426\nsetuptools/__init__.py,sha256=DqL4WTwyXFp0OakiBKz0HfB0nH4Fm06b3PX8sJWUg88,8429\nsetuptools/_deprecation_warning.py,sha256=jU9-dtfv6cKmtQJOXN8nP1mm7gONw5kKEtiPtbwnZyI,218\nsetuptools/_entry_points.py,sha256=5rRyEuiC0tdEsoCRJ6NWii5RET134mtDtjoSTFdLCwA,1972\nsetuptools/_imp.py,sha256=HmF91IbitRfsD5z-g4_wmcuH-RahyIONbPgiCOFgtzA,2392\nsetuptools/_importlib.py,sha256=1RLRzpNCPKEJRbUPVIPU1-H9dzUXulyL6N_ryxnjEwc,1311\nsetuptools/_itertools.py,sha256=pZAgXNz6tRPUFnHAaKJ90xAgD0gLPemcE1396Zgz73o,675\nsetuptools/_path.py,sha256=9GdbEur6f_lWmokar-Y-DDyds-XmzYnXrcBy0DExwDw,749\nsetuptools/_reqs.py,sha256=ApdTOmDFyK7hbHDnAH8VwhtVD5kvnOthyMNTmrUeFXs,501\nsetuptools/archive_util.py,sha256=6WShpDR_uGZOaORRfzBmJyTYtX9xtrhmXTFPqE8kL8s,7346\nsetuptools/build_meta.py,sha256=Lw6LmKQVASeUGcSsRa7fQl3RZNkxNgSk4eRRUwcuJGs,19539\nsetuptools/cli-32.exe,sha256=dfEuovMNnA2HLa3jRfMPVi5tk4R7alCbpTvuxtCyw0Y,65536\nsetuptools/cli-64.exe,sha256=KLABu5pyrnokJCv6skjXZ6GsXeyYHGcqOUT3oHI3Xpo,74752\nsetuptools/cli-arm64.exe,sha256=o9amxowudZ98NvNWh_a2DRY8LhoIRqTAekxABqltiMc,137216\nsetuptools/cli.exe,sha256=dfEuovMNnA2HLa3jRfMPVi5tk4R7alCbpTvuxtCyw0Y,65536\nsetuptools/dep_util.py,sha256=BDx1BkzNQntvAB4alypHbW5UVBzjqths000PrUL4Zqc,949\nsetuptools/depends.py,sha256=QYQIadr5DwLxPzkErhNt5hmRhvGhWxoXZMRXCm_jcQ0,5499\nsetuptools/discovery.py,sha256=UZCeULUrV21xBTFBTTLNbta_rq2yjKa9kRwNXUIafRA,20799\nsetuptools/dist.py,sha256=olE_CMNlg5_NGAPy7UWmaQ5Ev35_PQNiywtripWLtyU,45578\nsetuptools/errors.py,sha256=2uToNIRA7dG995pf8ox8a4r7nJtP62-hpLhzsRirnx0,2464\nsetuptools/extension.py,sha256=jpsAdQvCBCkAuvmEXYI90TV4kNGO2Y13NqDr_PrvdhA,5591\nsetuptools/glob.py,sha256=1oZjbfjAHSXbgdhSuR6YGU8jKob9L8NtEmBYqcPTLYk,4873\nsetuptools/gui-32.exe,sha256=XBr0bHMA6Hpz2s9s9Bzjl-PwXfa9nH4ie0rFn4V2kWA,65536\nsetuptools/gui-64.exe,sha256=aYKMhX1IJLn4ULHgWX0sE0yREUt6B3TEHf_jOw6yNyE,75264\nsetuptools/gui-arm64.exe,sha256=TEFnOKDi-mq3ZszxqbCoCXTnM_lhUWjdIqBpr6fVs40,137728\nsetuptools/gui.exe,sha256=XBr0bHMA6Hpz2s9s9Bzjl-PwXfa9nH4ie0rFn4V2kWA,65536\nsetuptools/installer.py,sha256=s6DQfsoICBJxbUqbduhOJtl1oG0S4yegRCg3EAs0i3M,3824\nsetuptools/launch.py,sha256=TyPT-Ic1T2EnYvGO26gfNRP4ysBlrhpbRjQxWsiO414,812\nsetuptools/logging.py,sha256=a8IDhV55qyEGDP6DTLNMxzSQaz-h4EfvnWfeBUJh0Nc,1210\nsetuptools/monkey.py,sha256=t6To7LEhTyOWRRZLwiFv7Eeg2mjHZlVmTdHD1DC94QM,4857\nsetuptools/msvc.py,sha256=x6jsjA9JdUew6VAfHapIHgEjAjy-T5dxqjPCZr0Tt04,47724\nsetuptools/namespaces.py,sha256=PMqGVPXPYQgjUTvEg9bGccRAkIODrQ6NmsDg_fwErwI,3093\nsetuptools/package_index.py,sha256=NfCNavs6DWe7gZzBcLYYNCIeCYA_pzqLw-ayyKU8hRk,40329\nsetuptools/py34compat.py,sha256=KYOd6ybRxjBW8NJmYD8t_UyyVmysppFXqHpFLdslGXU,245\nsetuptools/sandbox.py,sha256=mR83i-mu-ZUU_7TaMgYCeRSyzkqv8loJ_GR9xhS2DDw,14348\nsetuptools/script (dev).tmpl,sha256=RUzQzCQUaXtwdLtYHWYbIQmOaES5Brqq1FvUA_tu-5I,218\nsetuptools/script.tmpl,sha256=WGTt5piezO27c-Dbx6l5Q4T3Ff20A5z7872hv3aAhYY,138\nsetuptools/unicode_utils.py,sha256=aOOFo4JGwAsiBttGYDsqFS7YqWQeZ2j6DWiCuctR_00,941\nsetuptools/version.py,sha256=og_cuZQb0QI6ukKZFfZWPlr1HgJBPPn2vO2m_bI9ZTE,144\nsetuptools/wheel.py,sha256=6LphzUKYfdLnIp9kIUzLGPY-F7MTJr4hiabB5almLps,8376\nsetuptools/windows_support.py,sha256=KXrFWrteXjhIou0gGwlfBy0ttAszHP52ETq-2pc0mes,718\nsetuptools/_distutils/__init__.py,sha256=3TQPLqYDwgPwPP3WxYGrW19zjkyPkDGt0su31fdT0tA,537\nsetuptools/_distutils/_collections.py,sha256=s7zkSh7QUyJWEYSt5n10ouAZNDYvux8YCHnnY3k0wmQ,1330\nsetuptools/_distutils/_functools.py,sha256=ABZ-Lyw-igKwBFoLF3QYtFmfutwZLiAdWcpRMbcacGU,411\nsetuptools/_distutils/_macos_compat.py,sha256=-v_Z0M1LEH5k-VhSBBbuz_pDp3nSZ4rzU9E7iIskPDc,239\nsetuptools/_distutils/_msvccompiler.py,sha256=mGmlhw7uCSr-naH-kq2t3DTzn9Zul6miF75QjzkTq3k,19672\nsetuptools/_distutils/archive_util.py,sha256=kXxjRKAqwKjeraYVWmzMD1ylRmVowtRaO_f-arIPvPE,8603\nsetuptools/_distutils/bcppcompiler.py,sha256=w0VwvAmyt2jIAdUlvoAciZ1y8KHZjG4-WVagHPLSNhI,14789\nsetuptools/_distutils/ccompiler.py,sha256=r0JMuNfApR5YYGcyPNS1A9QwmmHQULYfQtGBClBYH_c,47369\nsetuptools/_distutils/cmd.py,sha256=8cx-WB6UsaDFrxMJxhddrQBGiuz6Jg74m_5nz31JxVs,17973\nsetuptools/_distutils/config.py,sha256=0MJdEXAnP5Hogox3Vc7wAPotM5eXptvMBQ_GDJTye9Y,4920\nsetuptools/_distutils/core.py,sha256=sc2pALG3HsxUZovkvh4YywABlJ_r-FnnM2UqKfrPlI4,9451\nsetuptools/_distutils/cygwinccompiler.py,sha256=H9N5ImWVvV0ktYfos1uEcTOK9KaVXvXaUf1lAa74mQ8,12537\nsetuptools/_distutils/debug.py,sha256=N6MrTAqK6l9SVk6tWweR108PM8Ol7qNlfyV-nHcLhsY,139\nsetuptools/_distutils/dep_util.py,sha256=RBh8ksJHdBNu9kG1Ivd0lRTpETNDgzjOwfrRjio1RGc,3423\nsetuptools/_distutils/dir_util.py,sha256=GfAMvlEPkvrvolgJ0u_2oISCKsmOFP3I1WrxPGHgFhY,8082\nsetuptools/_distutils/dist.py,sha256=JTHHae0rwFVo2Vm9u6-pn1Hos9NyKWcjGUKjEj_Ta7o,50186\nsetuptools/_distutils/errors.py,sha256=ZtBwnhDpQA2bxIazPXNDQ25uNxM4p2omsaSRNpV3rpE,3589\nsetuptools/_distutils/extension.py,sha256=F0TBNjYkMmte_Yg1bhKVHXSNWWNFEPIDUgwhuHdkox8,10270\nsetuptools/_distutils/fancy_getopt.py,sha256=kxVQOEBg2AfuBmyVEwvApPdYmJ3JpIcneIwQFlCHnsw,17910\nsetuptools/_distutils/file_util.py,sha256=OURpiLPhWmVhPJZ5n6DB462kcG7mosr2FDmp91R9kW8,8226\nsetuptools/_distutils/filelist.py,sha256=N5zJXHnprT_lUPzn9LCTe35q-Pkcd5D77vbzflj8iyA,13713\nsetuptools/_distutils/log.py,sha256=prAQJ_iy4HACk3rx5Ynl9L99DrFyYWJpYGmLtbiqLKg,1972\nsetuptools/_distutils/msvc9compiler.py,sha256=1BvnnUIJ1RcYRjK1uCOCjoAes0WTxatxgIpQSZjLy2w,30235\nsetuptools/_distutils/msvccompiler.py,sha256=NH0KkKJ0ZE9T-uMBcOjfpZrSFDYuPINszQPHZJEWCW8,23602\nsetuptools/_distutils/py38compat.py,sha256=gZ-NQ5c6ufwVEkJ0BwkbrqG9TvWirVJIrVGqhgvaY-Q,217\nsetuptools/_distutils/py39compat.py,sha256=vkxjv22H1bhToalClz3M0UUD8Xr21klbUBTQoVQxx20,639\nsetuptools/_distutils/spawn.py,sha256=XZQ9jfawr20Q5i0cv0Qxy0wY6YfQsJwtjyLcKOnz1wU,3517\nsetuptools/_distutils/sysconfig.py,sha256=Xg6K4abFhVD9vB3tWheXNGylEZxbKUkL4mzMXFsEN1g,18858\nsetuptools/_distutils/text_file.py,sha256=tLjIJVBu7VMY2ZamSpQ9aBv0kbvX9_Abt26cjAAgHiQ,12096\nsetuptools/_distutils/unixccompiler.py,sha256=0g8rPNK1-xRIycIavxdf-1gFDZXkWETS7rLqHqiZmrI,15641\nsetuptools/_distutils/util.py,sha256=kkZvfAXiehXnlJ0tcyLPDMWfyzdjtK1BMCvk_VMyD3Q,18128\nsetuptools/_distutils/version.py,sha256=6HV4l0tHESXxMJMDwd5Fn8Y9_U8ivZIowFCNXhCSnRM,12952\nsetuptools/_distutils/versionpredicate.py,sha256=jwMtNwKtEqjiZPBFRDiMwgKcNMHAYyakpIyVdp-WRAU,5248\nsetuptools/_distutils/command/__init__.py,sha256=fVUps4DJhvShMAod0y7xl02m46bd7r31irEhNofPrrs,430\nsetuptools/_distutils/command/_framework_compat.py,sha256=HW84Z1cWmg4b6aMJvlMI9o6sGZSEH_aWMTlDKstL8lY,1614\nsetuptools/_distutils/command/bdist.py,sha256=juqMz8WUyGZi8QEYSIReynjxyEmsOyrpAftLdwsmE5o,5441\nsetuptools/_distutils/command/bdist_dumb.py,sha256=Ik1_7m9IPfc_bTDuaf32juKOtWQOjjitzTkuXShJ5Bk,4701\nsetuptools/_distutils/command/bdist_rpm.py,sha256=HFny7hHrvfPBbhdQp7c7kST5W6xM3dP8YivWq9YI6Qw,22051\nsetuptools/_distutils/command/build.py,sha256=K6nfwP1TYF62ARyJf5kurhpc6aFyOf8HcGyrbdcjPX8,5617\nsetuptools/_distutils/command/build_clib.py,sha256=2leXQANbcKoQ91FRYi00P4HtF-amRE67JkPAl6R3OhE,7728\nsetuptools/_distutils/command/build_ext.py,sha256=mFIERa96pJVmXi6WSod_PMspSD8s_izBYLFSHxKpEcc,31558\nsetuptools/_distutils/command/build_py.py,sha256=A-kUuLRXf-MWJMFMLFmwGo9zwIQ-BMRYzki9CRybKZc,16568\nsetuptools/_distutils/command/build_scripts.py,sha256=VYSLutq7hWskla0HeVuXYATaqvuuG2vqLiGoRP2Za08,5624\nsetuptools/_distutils/command/check.py,sha256=2Pb7m1jOjY4iWiqbhyn8GEaOmgtbpobXH34ugkkXJYE,4888\nsetuptools/_distutils/command/clean.py,sha256=952TxGe0ZyhkrOSpKmzixXePWN6rocIWFQbI7OwAh7I,2603\nsetuptools/_distutils/command/config.py,sha256=dzPncgVTq6QOnNMpZ5IhUeNCTeJDJlk9SvR2XZ0oRy8,13137\nsetuptools/_distutils/command/install.py,sha256=4Lq4aVSSfNBU1twLT5c9meHt_JBp0MD7zAetE6Kp8d0,30221\nsetuptools/_distutils/command/install_data.py,sha256=mzduSrxl3IxmQiG-TBrPOWIVHGB4h7INjbiiq868bcU,2779\nsetuptools/_distutils/command/install_egg_info.py,sha256=dOjNNytTUcr97jG1BZkE7t1OZJ0U4bxx0HhqnwBJrUc,2785\nsetuptools/_distutils/command/install_headers.py,sha256=d8RICcQ8NgfNB2IFQi_DOMcge5lY-41QsEycmRoqwbI,1189\nsetuptools/_distutils/command/install_lib.py,sha256=a-iS1F160bApBsrs0DsVaHVRH1mVTk84BM27g9NMQzk,8434\nsetuptools/_distutils/command/install_scripts.py,sha256=6IIwz8xJj5aeEUqD-QWiVGGU1OEU0qMJQytJH5kNEOc,1936\nsetuptools/_distutils/command/py37compat.py,sha256=EoJC8gVYMIv2tA1NpVA2XDyCT1qGp4BEn7aX_5ve1gw,672\nsetuptools/_distutils/command/register.py,sha256=Sytr6ABBudvAp0lI2AUFBs3F55kbpkz0YxbhsmKoGTI,11765\nsetuptools/_distutils/command/sdist.py,sha256=zMFkdvdxk9ezitmR0jGDO0w3P-BG2ohtUgzSllCbf3Q,19241\nsetuptools/_distutils/command/upload.py,sha256=fJ5nBueGciB24ofXf7Rw4pzuFGM4a3JfTjbJi3iXxqE,7477\nsetuptools/_vendor/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nsetuptools/_vendor/ordered_set.py,sha256=dbaCcs27dyN9gnMWGF5nA_BrVn6Q-NrjKYJpV9_fgBs,15130\nsetuptools/_vendor/typing_extensions.py,sha256=1uqi_RSlI7gos4eJB_NEV3d5wQwzTUQHd3_jrkbTo8Q,87149\nsetuptools/_vendor/zipp.py,sha256=ajztOH-9I7KA_4wqDYygtHa6xUBVZgFpmZ8FE74HHHI,8425\nsetuptools/_vendor/importlib_metadata/__init__.py,sha256=xRXwTtvg4EAYuBotYeGawbjraQD4GFIvKgMClxApCDY,30130\nsetuptools/_vendor/importlib_metadata/_adapters.py,sha256=B6fCi5-8mLVDFUZj3krI5nAo-mKp1dH_qIavyIyFrJs,1862\nsetuptools/_vendor/importlib_metadata/_collections.py,sha256=CJ0OTCHIjWA0ZIVS4voORAsn2R4R2cQBEtPsZEJpASY,743\nsetuptools/_vendor/importlib_metadata/_compat.py,sha256=cotBaMUB-2pIRZboQnWp9fEqm6Dwlypndn-EEn0bj5M,1828\nsetuptools/_vendor/importlib_metadata/_functools.py,sha256=PsY2-4rrKX4RVeRC1oGp1lB1pmC9eKN88_f-bD9uOoA,2895\nsetuptools/_vendor/importlib_metadata/_itertools.py,sha256=cvr_2v8BRbxcIl5x5ldfqdHjhI8Yi8s8yk50G_nm6jQ,2068\nsetuptools/_vendor/importlib_metadata/_meta.py,sha256=_F48Hu_jFxkfKWz5wcYS8vO23qEygbVdF9r-6qh-hjE,1154\nsetuptools/_vendor/importlib_metadata/_text.py,sha256=HCsFksZpJLeTP3NEk_ngrAeXVRRtTrtyh9eOABoRP4A,2166\nsetuptools/_vendor/importlib_resources/__init__.py,sha256=evPm12kLgYqTm-pbzm60bOuumumT8IpBNWFp0uMyrzE,506\nsetuptools/_vendor/importlib_resources/_adapters.py,sha256=o51tP2hpVtohP33gSYyAkGNpLfYDBqxxYsadyiRZi1E,4504\nsetuptools/_vendor/importlib_resources/_common.py,sha256=iIxAaQhotSh6TLLUEfL_ynU2fzEeyHMz9JcL46mUhLg,2741\nsetuptools/_vendor/importlib_resources/_compat.py,sha256=nFBCGMvImglrqgYkb9aPgOj68-h6xbw-ca94XOv1-zs,2706\nsetuptools/_vendor/importlib_resources/_itertools.py,sha256=WCdJ1Gs_kNFwKENyIG7TO0Y434IWCu0zjVVSsSbZwU8,884\nsetuptools/_vendor/importlib_resources/_legacy.py,sha256=TMLkx6aEM6U8xIREPXqGZrMbUhTiPUuPl6ESD7RdYj4,3494\nsetuptools/_vendor/importlib_resources/abc.py,sha256=MvTJJXajbl74s36Gyeesf76egtbFnh-TMtzQMVhFWXo,3886\nsetuptools/_vendor/importlib_resources/readers.py,sha256=_9QLGQ5AzrED3PY8S2Zf8V6yLR0-nqqYqtQmgleDJzY,3566\nsetuptools/_vendor/importlib_resources/simple.py,sha256=xt0qhXbwt3bZ86zuaaKbTiE9A0mDbwu0saRjUq_pcY0,2836\nsetuptools/_vendor/jaraco/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nsetuptools/_vendor/jaraco/context.py,sha256=7X1tpCLc5EN45iWGzGcsH0Unx62REIkvtRvglj0SiUA,5420\nsetuptools/_vendor/jaraco/functools.py,sha256=ap1qoXaNABOx897366NTMEd2objrqAoSO1zuxZPjcmM,13512\nsetuptools/_vendor/jaraco/text/__init__.py,sha256=KfFGMerrkN_0V0rgtJVx-9dHt3tW7i_uJypjwEcLtC0,15517\nsetuptools/_vendor/more_itertools/__init__.py,sha256=C7sXffHTXM3P-iaLPPfqfmDoxOflQMJLcM7ed9p3jak,82\nsetuptools/_vendor/more_itertools/more.py,sha256=0rB_mibFR51sq33UlAI_bWfaNdsYNnJr1v6S0CaW7QA,117959\nsetuptools/_vendor/more_itertools/recipes.py,sha256=UkNkrsZyqiwgLHANBTmvMhCvaNSvSNYhyOpz_Jc55DY,16256\nsetuptools/_vendor/packaging/__about__.py,sha256=ugASIO2w1oUyH8_COqQ2X_s0rDhjbhQC3yJocD03h2c,661\nsetuptools/_vendor/packaging/__init__.py,sha256=b9Kk5MF7KxhhLgcDmiUWukN-LatWFxPdNug0joPhHSk,497\nsetuptools/_vendor/packaging/_manylinux.py,sha256=XcbiXB-qcjv3bcohp6N98TMpOP4_j3m-iOA8ptK2GWY,11488\nsetuptools/_vendor/packaging/_musllinux.py,sha256=_KGgY_qc7vhMGpoqss25n2hiLCNKRtvz9mCrS7gkqyc,4378\nsetuptools/_vendor/packaging/_structures.py,sha256=q3eVNmbWJGG_S0Dit_S3Ao8qQqz_5PYTXFAKBZe5yr4,1431\nsetuptools/_vendor/packaging/markers.py,sha256=lihRgqpZjLM-JW-vxlLPqU3kmVe79g9vypy1kxmTRuQ,8493\nsetuptools/_vendor/packaging/requirements.py,sha256=Opd0FjqgdEiWkzBLyo1oLU0Dj01uIFwTAnAJQrr6j2A,4700\nsetuptools/_vendor/packaging/specifiers.py,sha256=LRQ0kFsHrl5qfcFNEEJrIFYsnIHQUJXY9fIsakTrrqE,30110\nsetuptools/_vendor/packaging/tags.py,sha256=lmsnGNiJ8C4D_Pf9PbM0qgbZvD9kmB9lpZBQUZa3R_Y,15699\nsetuptools/_vendor/packaging/utils.py,sha256=dJjeat3BS-TYn1RrUFVwufUMasbtzLfYRoy_HXENeFQ,4200\nsetuptools/_vendor/packaging/version.py,sha256=_fLRNrFrxYcHVfyo8vk9j8s6JM8N_xsSxVFr6RJyco8,14665\nsetuptools/_vendor/pyparsing/__init__.py,sha256=52QH3lgPbJhba0estckoGPHRH8JvQSSCGoWiEn2m0bU,9159\nsetuptools/_vendor/pyparsing/actions.py,sha256=wU9i32e0y1ymxKE3OUwSHO-SFIrt1h_wv6Ws0GQjpNU,6426\nsetuptools/_vendor/pyparsing/common.py,sha256=lFL97ooIeR75CmW5hjURZqwDCTgruqltcTCZ-ulLO2Q,12936\nsetuptools/_vendor/pyparsing/core.py,sha256=u8GptQE_H6wMkl8OZhxeK1aAPIDXXNgwdShORBwBVS4,213310\nsetuptools/_vendor/pyparsing/exceptions.py,sha256=3LbSafD32NYb1Tzt85GHNkhEAU1eZkTtNSk24cPMemo,9023\nsetuptools/_vendor/pyparsing/helpers.py,sha256=QpUOjW0-psvueMwWb9bQpU2noqKCv98_wnw1VSzSdVo,39129\nsetuptools/_vendor/pyparsing/results.py,sha256=HgNvWVXBdQP-Q6PtJfoCEeOJk2nwEvG-2KVKC5sGA30,25341\nsetuptools/_vendor/pyparsing/testing.py,sha256=7tu4Abp4uSeJV0N_yEPRmmNUhpd18ZQP3CrX41DM814,13402\nsetuptools/_vendor/pyparsing/unicode.py,sha256=fwuhMj30SQ165Cv7HJpu-rSxGbRm93kN9L4Ei7VGc1Y,10787\nsetuptools/_vendor/pyparsing/util.py,sha256=kq772O5YSeXOSdP-M31EWpbH_ayj7BMHImBYo9xPD5M,6805\nsetuptools/_vendor/pyparsing/diagram/__init__.py,sha256=f_EfxahqrdkRVahmTwLJXkZ9EEDKNd-O7lBbpJYlE1g,23668\nsetuptools/_vendor/tomli/__init__.py,sha256=JhUwV66DB1g4Hvt1UQCVMdfCu-IgAV8FXmvDU9onxd4,396\nsetuptools/_vendor/tomli/_parser.py,sha256=g9-ENaALS-B8dokYpCuzUFalWlog7T-SIYMjLZSWrtM,22633\nsetuptools/_vendor/tomli/_re.py,sha256=dbjg5ChZT23Ka9z9DHOXfdtSpPwUfdgMXnj8NOoly-w,2943\nsetuptools/_vendor/tomli/_types.py,sha256=-GTG2VUqkpxwMqzmVO4F7ybKddIbAnuAHXfmWQcTi3Q,254\nsetuptools/command/__init__.py,sha256=HZlSppOB8Vro73ffvP-xrORuMrh4GnVkOqJspFRG8Pg,396\nsetuptools/command/alias.py,sha256=1sLQxZcNh6dDQpDmm4G7UGGTol83nY1NTPmNBbm2siI,2381\nsetuptools/command/bdist_egg.py,sha256=QEIu1AkgS02j6ejonJY7kwGp6LNxfMeYZ3sxkd55ftA,16623\nsetuptools/command/bdist_rpm.py,sha256=PxrgoHPNaw2Pw2qNjjHDPC-Ay_IaDbCqP3d_5N-cj2A,1182\nsetuptools/command/build.py,sha256=cgkmzJhXFXw5lHMPgohJFyEByz8L7H9JurCnk2iRnFI,6589\nsetuptools/command/build_clib.py,sha256=fWHSFGkk10VCddBWCszvNhowbG9Z9CZXVjQ2uSInoOs,4415\nsetuptools/command/build_ext.py,sha256=cYm4OvllPf6I9YE3cWlnjPqqE546Mc7nQTpdJ-yH3jg,15821\nsetuptools/command/build_py.py,sha256=CMoD9Gxd5vs8KfPVNFFD1cmJsCd3l0NJS5kdDTlx4Y4,14115\nsetuptools/command/develop.py,sha256=5_Ss7ENd1_B_jVMY1tF5UV_y1Xu6jbVzAPG8oKeluGA,7012\nsetuptools/command/dist_info.py,sha256=VdcNHtbPFGdPD_t20wxcROa4uALbyz1RnJMJEHQmrQU,4800\nsetuptools/command/easy_install.py,sha256=sx7_Rwpa2wUvPZZTa7jLpY3shEL4Ti2d2u1yIUMahHs,85662\nsetuptools/command/editable_wheel.py,sha256=yUCwBNcS75sBqcEOkW9CvRypgQ0dsMTn9646yXftAhk,31188\nsetuptools/command/egg_info.py,sha256=BWo5Fw2_BT-vM3p3fgheRQP4zwym1TH38wqKPr5dmWs,26795\nsetuptools/command/install.py,sha256=CBdw9iITHAc0Zt1YE_8dSWY5BscuTJGrCe2jtEsnepk,5163\nsetuptools/command/install_egg_info.py,sha256=pgZ64m_-kmtx3QISHN_kRtMiZC_Y8x1Nr1j38jXEbXQ,2226\nsetuptools/command/install_lib.py,sha256=Uz42McsyHZAjrB6cw9E7Bz0xsaTbzxnM1PI9CBhiPtE,3875\nsetuptools/command/install_scripts.py,sha256=APFFpt_lYUEo-viMtpXr-Hkwycwq8knTxSTNUu_TwHo,2612\nsetuptools/command/launcher manifest.xml,sha256=xlLbjWrB01tKC0-hlVkOKkiSPbzMml2eOPtJ_ucCnbE,628\nsetuptools/command/py36compat.py,sha256=7yLWzQj179Enx3pJ8V1cDDCzeLMFMd9XJXlK-iZTq5Y,4946\nsetuptools/command/register.py,sha256=kk3DxXCb5lXTvqnhfwx2g6q7iwbUmgTyXUCaBooBOUk,468\nsetuptools/command/rotate.py,sha256=SvsQPasezIojPjvMnfkqzh8P0U0tCj0daczF8uc3NQM,2128\nsetuptools/command/saveopts.py,sha256=za7QCBcQimKKriWcoCcbhxPjUz30gSB74zuTL47xpP4,658\nsetuptools/command/sdist.py,sha256=d8Ty0eCiUKfWh4VTjqV9e8g-02Zsy8L4BcMe1OzIIn8,7071\nsetuptools/command/setopt.py,sha256=okxhqD1NM1nQlbSVDCNv6P7Y7g680sc2r-tUW7wPH1Y,5086\nsetuptools/command/test.py,sha256=ZWoIUdm6u2Zv-WhvSC5If1rPouxm5JmygwsajNA8WWI,8102\nsetuptools/command/upload.py,sha256=XT3YFVfYPAmA5qhGg0euluU98ftxRUW-PzKcODMLxUs,462\nsetuptools/command/upload_docs.py,sha256=1gHSs8Cyte2fSWwJPbAFD17eOdNxPWoBiHOJd1gdpaI,7494\nsetuptools/config/__init__.py,sha256=Jg48Ac6C8AtdjkAFhe4Kh_xwNUfK6q04CJlJ5LbVMB0,1121\nsetuptools/config/_apply_pyprojecttoml.py,sha256=Ev1RwtQbPiD2za3di5T7ExY8T7TAvMIFot0efIHYzAY,13398\nsetuptools/config/expand.py,sha256=FQja-T8zG9bV_G1b7SBjWjsZNjvSbhg5vxFWhusSYoE,16319\nsetuptools/config/pyprojecttoml.py,sha256=3dYGfZB_fjlwkumOQ2bhH2L4UJ3rDu0hN7HJjmd1Akc,19304\nsetuptools/config/setupcfg.py,sha256=aqXdUuB5llJz9hZmQUjganZAyo34lHrRsK6wV1NzX2M,25198\nsetuptools/config/_validate_pyproject/__init__.py,sha256=5YXPW1sabVn5jpZ25sUjeF6ij3_4odJiwUWi4nRD2Dc,1038\nsetuptools/config/_validate_pyproject/error_reporting.py,sha256=vWiDs0hjlCBjZ_g4Xszsh97lIP9M4_JaLQ6MCQ26W9U,11266\nsetuptools/config/_validate_pyproject/extra_validations.py,sha256=wHzrgfdZUMRPBR1ke1lg5mhqRsBSbjEYOMsuFXQH9jY,1153\nsetuptools/config/_validate_pyproject/fastjsonschema_exceptions.py,sha256=w749JgqKi8clBFcObdcbZVqsmF4oJ_QByhZ1SGbUFNw,1612\nsetuptools/config/_validate_pyproject/fastjsonschema_validations.py,sha256=oqXSDfYecymwM2I40JGcTB-1P9vd7CtfSIW5kDxZQPM,269900\nsetuptools/config/_validate_pyproject/formats.py,sha256=uMUnp4mLIjrQCTe6-LDjtqglmEFLfOW9E1ZZLqOzhMI,8736\nsetuptools/extern/__init__.py,sha256=LYHS20uf-nl_zBPmrIzTxokYdiVMZNZBYVu6hd8c5zg,2512\nsetuptools-65.5.1.dist-info/LICENSE,sha256=2z8CRrH5J48VhFuZ_sR4uLUG63ZIeZNyL4xuJUKF-vg,1050\nsetuptools-65.5.1.dist-info/METADATA,sha256=Gte2p_BLawLXnXmAZ-1HL2vFrx5WvV1c9v16LpqW3FQ,6311\nsetuptools-65.5.1.dist-info/WHEEL,sha256=00yskusixUoUt5ob_CiUp6LsnN5lqzTJpoqOFg_FVIc,92\nsetuptools-65.5.1.dist-info/entry_points.txt,sha256=3siAu4kYm1ybFJHJ7ooqpX5TAW70Gitp9dcdHC-7BFM,2740\nsetuptools-65.5.1.dist-info/top_level.txt,sha256=d9yL39v_W7qmKDDSH6sT4bE0j_Ls1M3P161OGgdsm4g,41\nsetuptools-65.5.1.dist-info/RECORD,,\nsetuptools/_distutils/command/install_egg_info.cpython-37.pyc,,\nsetuptools/glob.cpython-37.pyc,,\nsetuptools/monkey.cpython-37.pyc,,\nsetuptools/_distutils/filelist.cpython-37.pyc,,\nsetuptools/_distutils/extension.cpython-37.pyc,,\nsetuptools/_vendor/pyparsing/actions.cpython-37.pyc,,\nsetuptools/_vendor/jaraco/functools.cpython-37.pyc,,\nsetuptools/_vendor/packaging/__about__.cpython-37.pyc,,\nsetuptools/_distutils/msvccompiler.cpython-37.pyc,,\nsetuptools/config/__init__.cpython-37.pyc,,\npkg_resources/_vendor/jaraco/text/__init__.cpython-37.pyc,,\npkg_resources/_vendor/importlib_resources/__init__.cpython-37.pyc,,\nsetuptools/config/_validate_pyproject/fastjsonschema_exceptions.cpython-37.pyc,,\npkg_resources/__pycache__,,\nsetuptools/command/editable_wheel.cpython-37.pyc,,\nsetuptools/_vendor/packaging/tags.cpython-37.pyc,,\nsetuptools/_distutils/command/install_lib.cpython-37.pyc,,\nsetuptools/_distutils/bcppcompiler.cpython-37.pyc,,\npkg_resources/__init__.cpython-37.pyc,,\npkg_resources/_vendor/importlib_resources/simple.cpython-37.pyc,,\nsetuptools/_distutils/command/install_scripts.cpython-37.pyc,,\nsetuptools/command/develop.cpython-37.pyc,,\npkg_resources/_vendor/jaraco/__init__.cpython-37.pyc,,\nsetuptools/_distutils/ccompiler.cpython-37.pyc,,\npkg_resources/_vendor/packaging/_musllinux.cpython-37.pyc,,\nsetuptools/discovery.cpython-37.pyc,,\npkg_resources/_vendor/importlib_resources/readers.cpython-37.pyc,,\nsetuptools/_vendor/pyparsing/__pycache__,,\nsetuptools/_distutils/dist.cpython-37.pyc,,\nsetuptools/_distutils/command/build_scripts.cpython-37.pyc,,\npkg_resources/_vendor/__pycache__,,\npkg_resources/_vendor/packaging/utils.cpython-37.pyc,,\nsetuptools/_distutils/_macos_compat.cpython-37.pyc,,\nsetuptools/extern/__pycache__,,\nsetuptools/command/bdist_rpm.cpython-37.pyc,,\nsetuptools/_imp.cpython-37.pyc,,\nsetuptools/_vendor/more_itertools/__init__.cpython-37.pyc,,\nsetuptools/_vendor/pyparsing/diagram/__init__.cpython-37.pyc,,\nsetuptools/_vendor/packaging/markers.cpython-37.pyc,,\nsetuptools/launch.cpython-37.pyc,,\nsetuptools/namespaces.cpython-37.pyc,,\nsetuptools/_distutils/command/build.cpython-37.pyc,,\npkg_resources/_vendor/pyparsing/__pycache__,,\npkg_resources/_vendor/zipp.cpython-37.pyc,,\nsetuptools/_distutils/command/build_clib.cpython-37.pyc,,\nsetuptools/_distutils/command/build_ext.cpython-37.pyc,,\nsetuptools/_vendor/pyparsing/__init__.cpython-37.pyc,,\nsetuptools/command/test.cpython-37.pyc,,\nsetuptools/_distutils/spawn.cpython-37.pyc,,\nsetuptools/_vendor/__pycache__,,\npkg_resources/_vendor/more_itertools/more.cpython-37.pyc,,\nsetuptools/installer.cpython-37.pyc,,\nsetuptools/_distutils/command/check.cpython-37.pyc,,\nsetuptools/_distutils/cygwinccompiler.cpython-37.pyc,,\nsetuptools/_distutils/command/__init__.cpython-37.pyc,,\nsetuptools/_distutils/command/register.cpython-37.pyc,,\nsetuptools/__pycache__,,\nsetuptools/__init__.cpython-37.pyc,,\nsetuptools/command/register.cpython-37.pyc,,\nsetuptools/_distutils/versionpredicate.cpython-37.pyc,,\npkg_resources/_vendor/pyparsing/testing.cpython-37.pyc,,\nsetuptools/command/sdist.cpython-37.pyc,,\nsetuptools/_distutils/command/build_py.cpython-37.pyc,,\nsetuptools/_vendor/importlib_resources/_itertools.cpython-37.pyc,,\nsetuptools/_vendor/packaging/__pycache__,,\nsetuptools/_vendor/pyparsing/helpers.cpython-37.pyc,,\nsetuptools/_vendor/tomli/__init__.cpython-37.pyc,,\nsetuptools/errors.cpython-37.pyc,,\npkg_resources/_vendor/packaging/requirements.cpython-37.pyc,,\nsetuptools/_distutils/command/config.cpython-37.pyc,,\nsetuptools/_vendor/importlib_resources/__pycache__,,\nsetuptools/_distutils/command/install.cpython-37.pyc,,\npkg_resources/_vendor/pyparsing/actions.cpython-37.pyc,,\npkg_resources/_vendor/packaging/specifiers.cpython-37.pyc,,\nsetuptools/_distutils/dep_util.cpython-37.pyc,,\nsetuptools/_distutils/debug.cpython-37.pyc,,\nsetuptools/command/dist_info.cpython-37.pyc,,\nsetuptools/command/install_scripts.cpython-37.pyc,,\nsetuptools/_vendor/importlib_resources/abc.cpython-37.pyc,,\nsetuptools-65.5.1.dist-info/INSTALLER,,\nsetuptools/command/bdist_egg.cpython-37.pyc,,\nsetuptools/_vendor/tomli/_parser.cpython-37.pyc,,\nsetuptools/dep_util.cpython-37.pyc,,\nsetuptools/config/expand.cpython-37.pyc,,\nsetuptools/command/rotate.cpython-37.pyc,,\nsetuptools/command/install.cpython-37.pyc,,\nsetuptools/_vendor/packaging/_structures.cpython-37.pyc,,\nsetuptools/_vendor/packaging/requirements.cpython-37.pyc,,\npkg_resources/_vendor/importlib_resources/_adapters.cpython-37.pyc,,\nsetuptools/_distutils/__init__.cpython-37.pyc,,\nsetuptools/_vendor/importlib_metadata/_compat.cpython-37.pyc,,\nsetuptools/_vendor/pyparsing/results.cpython-37.pyc,,\nsetuptools/_vendor/jaraco/context.cpython-37.pyc,,\nsetuptools/sandbox.cpython-37.pyc,,\nsetuptools/_distutils/unixccompiler.cpython-37.pyc,,\n_distutils_hack/override.cpython-37.pyc,,\npkg_resources/_vendor/packaging/tags.cpython-37.pyc,,\nsetuptools/version.cpython-37.pyc,,\nsetuptools/command/build_clib.cpython-37.pyc,,\nsetuptools/_vendor/more_itertools/recipes.cpython-37.pyc,,\nsetuptools/command/__init__.cpython-37.pyc,,\nsetuptools/_vendor/importlib_resources/_common.cpython-37.pyc,,\nsetuptools/command/upload_docs.cpython-37.pyc,,\nsetuptools/_vendor/importlib_metadata/_itertools.cpython-37.pyc,,\npkg_resources/_vendor/packaging/_structures.cpython-37.pyc,,\nsetuptools/_vendor/zipp.cpython-37.pyc,,\nsetuptools/_distutils/command/bdist_dumb.cpython-37.pyc,,\nsetuptools/_vendor/importlib_metadata/_functools.cpython-37.pyc,,\npkg_resources/extern/__pycache__,,\n_distutils_hack/__init__.cpython-37.pyc,,\nsetuptools/_distutils/util.cpython-37.pyc,,\npkg_resources/_vendor/pyparsing/exceptions.cpython-37.pyc,,\nsetuptools/_importlib.cpython-37.pyc,,\n_distutils_hack/__pycache__,,\nsetuptools/command/alias.cpython-37.pyc,,\npkg_resources/_vendor/pyparsing/__init__.cpython-37.pyc,,\nsetuptools/_distutils/py39compat.cpython-37.pyc,,\nsetuptools/_distutils/command/install_data.cpython-37.pyc,,\npkg_resources/_vendor/pyparsing/util.cpython-37.pyc,,\npkg_resources/_vendor/packaging/markers.cpython-37.pyc,,\npkg_resources/_vendor/importlib_resources/_common.cpython-37.pyc,,\nsetuptools/_distutils/command/install_headers.cpython-37.pyc,,\nsetuptools/_distutils/version.cpython-37.pyc,,\nsetuptools/_distutils/command/py37compat.cpython-37.pyc,,\nsetuptools/_deprecation_warning.cpython-37.pyc,,\nsetuptools/_distutils/_msvccompiler.cpython-37.pyc,,\nsetuptools/command/install_egg_info.cpython-37.pyc,,\nsetuptools/_distutils/config.cpython-37.pyc,,\nsetuptools/_distutils/__pycache__,,\nsetuptools/command/saveopts.cpython-37.pyc,,\nsetuptools/config/pyprojecttoml.cpython-37.pyc,,\nsetuptools/_distutils/command/__pycache__,,\nsetuptools/windows_support.cpython-37.pyc,,\nsetuptools/_vendor/importlib_metadata/_text.cpython-37.pyc,,\nsetuptools/dist.cpython-37.pyc,,\nsetuptools/_distutils/command/bdist.cpython-37.pyc,,\nsetuptools/_vendor/packaging/_manylinux.cpython-37.pyc,,\nsetuptools/command/setopt.cpython-37.pyc,,\nsetuptools/config/_validate_pyproject/extra_validations.cpython-37.pyc,,\npkg_resources/_vendor/pyparsing/helpers.cpython-37.pyc,,\nsetuptools/_distutils/command/sdist.cpython-37.pyc,,\nsetuptools/config/_apply_pyprojecttoml.cpython-37.pyc,,\nsetuptools/config/__pycache__,,\npkg_resources/_vendor/packaging/__pycache__,,\nsetuptools/_distutils/_collections.cpython-37.pyc,,\nsetuptools/_vendor/packaging/__init__.cpython-37.pyc,,\nsetuptools/_distutils/command/upload.cpython-37.pyc,,\nsetuptools/_vendor/tomli/_types.cpython-37.pyc,,\nsetuptools/_distutils/dir_util.cpython-37.pyc,,\nsetuptools/_vendor/pyparsing/core.cpython-37.pyc,,\nsetuptools/_vendor/packaging/version.cpython-37.pyc,,\nsetuptools/config/_validate_pyproject/fastjsonschema_validations.cpython-37.pyc,,\nsetuptools/_vendor/importlib_metadata/__pycache__,,\nsetuptools/py34compat.cpython-37.pyc,,\npkg_resources/_vendor/jaraco/functools.cpython-37.pyc,,\nsetuptools/_vendor/importlib_resources/__init__.cpython-37.pyc,,\nsetuptools/_vendor/jaraco/__pycache__,,\nsetuptools/_vendor/pyparsing/unicode.cpython-37.pyc,,\nsetuptools/_distutils/_functools.cpython-37.pyc,,\nsetuptools/_itertools.cpython-37.pyc,,\npkg_resources/_vendor/importlib_resources/abc.cpython-37.pyc,,\nsetuptools/_vendor/importlib_resources/simple.cpython-37.pyc,,\nsetuptools/_vendor/typing_extensions.cpython-37.pyc,,\npkg_resources/_vendor/packaging/__init__.cpython-37.pyc,,\nsetuptools/command/py36compat.cpython-37.pyc,,\npkg_resources/_vendor/__init__.cpython-37.pyc,,\npkg_resources/_vendor/pyparsing/core.cpython-37.pyc,,\nsetuptools/config/_validate_pyproject/error_reporting.cpython-37.pyc,,\nsetuptools/_vendor/importlib_resources/readers.cpython-37.pyc,,\npkg_resources/_vendor/packaging/version.cpython-37.pyc,,\nsetuptools/_distutils/core.cpython-37.pyc,,\nsetuptools/extern/__init__.cpython-37.pyc,,\nsetuptools/_vendor/packaging/_musllinux.cpython-37.pyc,,\nsetuptools/unicode_utils.cpython-37.pyc,,\nsetuptools/_distutils/errors.cpython-37.pyc,,\nsetuptools-65.5.1.virtualenv,,\nsetuptools/_distutils/command/_framework_compat.cpython-37.pyc,,\npkg_resources/_vendor/jaraco/__pycache__,,\nsetuptools/_reqs.cpython-37.pyc,,\nsetuptools/command/build_ext.cpython-37.pyc,,\npkg_resources/_vendor/more_itertools/__pycache__,,\npkg_resources/_vendor/pyparsing/unicode.cpython-37.pyc,,\nsetuptools/_vendor/jaraco/__init__.cpython-37.pyc,,\nsetuptools/depends.cpython-37.pyc,,\nsetuptools/config/_validate_pyproject/formats.cpython-37.pyc,,\npkg_resources/_vendor/more_itertools/recipes.cpython-37.pyc,,\nsetuptools/_path.cpython-37.pyc,,\nsetuptools/command/build_py.cpython-37.pyc,,\npkg_resources/_vendor/jaraco/text/__pycache__,,\npkg_resources/_vendor/pyparsing/results.cpython-37.pyc,,\npkg_resources/_vendor/pyparsing/diagram/__pycache__,,\nsetuptools/command/egg_info.cpython-37.pyc,,\nsetuptools/config/_validate_pyproject/__init__.cpython-37.pyc,,\nsetuptools/_distutils/fancy_getopt.cpython-37.pyc,,\nsetuptools/_vendor/jaraco/text/__pycache__,,\nsetuptools/_vendor/importlib_resources/_adapters.cpython-37.pyc,,\nsetuptools/_vendor/__init__.cpython-37.pyc,,\npkg_resources/_vendor/pyparsing/diagram/__init__.cpython-37.pyc,,\nsetuptools/_distutils/msvc9compiler.cpython-37.pyc,,\nsetuptools/_entry_points.cpython-37.pyc,,\nsetuptools/command/easy_install.cpython-37.pyc,,\nsetuptools/archive_util.cpython-37.pyc,,\nsetuptools/command/upload.cpython-37.pyc,,\nsetuptools/_vendor/packaging/utils.cpython-37.pyc,,\npkg_resources/_vendor/jaraco/context.cpython-37.pyc,,\nsetuptools/command/install_lib.cpython-37.pyc,,\nsetuptools/_vendor/jaraco/text/__init__.cpython-37.pyc,,\nsetuptools/_vendor/more_itertools/__pycache__,,\nsetuptools/_distutils/py38compat.cpython-37.pyc,,\nsetuptools/_distutils/text_file.cpython-37.pyc,,\npkg_resources/_vendor/more_itertools/__init__.cpython-37.pyc,,\nsetuptools/msvc.cpython-37.pyc,,\nsetuptools/wheel.cpython-37.pyc,,\nsetuptools/logging.cpython-37.pyc,,\nsetuptools/_distutils/archive_util.cpython-37.pyc,,\nsetuptools/_vendor/importlib_metadata/_meta.cpython-37.pyc,,\nsetuptools/config/setupcfg.cpython-37.pyc,,\nsetuptools/_vendor/more_itertools/more.cpython-37.pyc,,\npkg_resources/_vendor/pyparsing/common.cpython-37.pyc,,\nsetuptools/_vendor/pyparsing/exceptions.cpython-37.pyc,,\nsetuptools/command/__pycache__,,\nsetuptools/extension.cpython-37.pyc,,\nsetuptools/config/_validate_pyproject/__pycache__,,\nsetuptools/_vendor/pyparsing/diagram/__pycache__,,\nsetuptools/_distutils/file_util.cpython-37.pyc,,\nsetuptools/_vendor/ordered_set.cpython-37.pyc,,\nsetuptools-65.5.1.dist-info/__pycache__,,\nsetuptools/_distutils/command/bdist_rpm.cpython-37.pyc,,\nsetuptools/_vendor/importlib_resources/_compat.cpython-37.pyc,,\nsetuptools/build_meta.cpython-37.pyc,,\npkg_resources/extern/__init__.cpython-37.pyc,,\npkg_resources/_vendor/importlib_resources/_itertools.cpython-37.pyc,,\nsetuptools/_vendor/pyparsing/util.cpython-37.pyc,,\nsetuptools/_distutils/sysconfig.cpython-37.pyc,,\npkg_resources/_vendor/appdirs.cpython-37.pyc,,\nsetuptools/_vendor/pyparsing/testing.cpython-37.pyc,,\nsetuptools/_distutils/command/clean.cpython-37.pyc,,\nsetuptools/command/build.cpython-37.pyc,,\npkg_resources/_vendor/importlib_resources/_legacy.cpython-37.pyc,,\nsetuptools/_vendor/pyparsing/common.cpython-37.pyc,,\nsetuptools/_vendor/tomli/_re.cpython-37.pyc,,\nsetuptools/_vendor/packaging/specifiers.cpython-37.pyc,,\npkg_resources/_vendor/packaging/__about__.cpython-37.pyc,,\nsetuptools/_distutils/log.cpython-37.pyc,,\nsetuptools/_vendor/importlib_metadata/_adapters.cpython-37.pyc,,\npkg_resources/_vendor/importlib_resources/__pycache__,,\npkg_resources/_vendor/importlib_resources/_compat.cpython-37.pyc,,\nsetuptools/_vendor/tomli/__pycache__,,\nsetuptools/package_index.cpython-37.pyc,,\npkg_resources/_vendor/packaging/_manylinux.cpython-37.pyc,,\nsetuptools/_distutils/cmd.cpython-37.pyc,,\nsetuptools/_vendor/importlib_metadata/__init__.cpython-37.pyc,,\nsetuptools/_vendor/importlib_resources/_legacy.cpython-37.pyc,,\nsetuptools/_vendor/importlib_metadata/_collections.cpython-37.pyc,,"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools-65.5.1.dist-info/WHEEL",
    "content": "Wheel-Version: 1.0\nGenerator: bdist_wheel (0.38.1)\nRoot-Is-Purelib: true\nTag: py3-none-any\n\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools-65.5.1.dist-info/entry_points.txt",
    "content": "[distutils.commands]\nalias = setuptools.command.alias:alias\nbdist_egg = setuptools.command.bdist_egg:bdist_egg\nbdist_rpm = setuptools.command.bdist_rpm:bdist_rpm\nbuild = setuptools.command.build:build\nbuild_clib = setuptools.command.build_clib:build_clib\nbuild_ext = setuptools.command.build_ext:build_ext\nbuild_py = setuptools.command.build_py:build_py\ndevelop = setuptools.command.develop:develop\ndist_info = setuptools.command.dist_info:dist_info\neasy_install = setuptools.command.easy_install:easy_install\neditable_wheel = setuptools.command.editable_wheel:editable_wheel\negg_info = setuptools.command.egg_info:egg_info\ninstall = setuptools.command.install:install\ninstall_egg_info = setuptools.command.install_egg_info:install_egg_info\ninstall_lib = setuptools.command.install_lib:install_lib\ninstall_scripts = setuptools.command.install_scripts:install_scripts\nrotate = setuptools.command.rotate:rotate\nsaveopts = setuptools.command.saveopts:saveopts\nsdist = setuptools.command.sdist:sdist\nsetopt = setuptools.command.setopt:setopt\ntest = setuptools.command.test:test\nupload_docs = setuptools.command.upload_docs:upload_docs\n\n[distutils.setup_keywords]\ndependency_links = setuptools.dist:assert_string_list\neager_resources = setuptools.dist:assert_string_list\nentry_points = setuptools.dist:check_entry_points\nexclude_package_data = setuptools.dist:check_package_data\nextras_require = setuptools.dist:check_extras\ninclude_package_data = setuptools.dist:assert_bool\ninstall_requires = setuptools.dist:check_requirements\nnamespace_packages = setuptools.dist:check_nsp\npackage_data = setuptools.dist:check_package_data\npackages = setuptools.dist:check_packages\npython_requires = setuptools.dist:check_specifier\nsetup_requires = setuptools.dist:check_requirements\ntest_loader = setuptools.dist:check_importable\ntest_runner = setuptools.dist:check_importable\ntest_suite = setuptools.dist:check_test_suite\ntests_require = setuptools.dist:check_requirements\nuse_2to3 = setuptools.dist:invalid_unless_false\nzip_safe = setuptools.dist:assert_bool\n\n[egg_info.writers]\nPKG-INFO = setuptools.command.egg_info:write_pkg_info\ndependency_links.txt = setuptools.command.egg_info:overwrite_arg\ndepends.txt = setuptools.command.egg_info:warn_depends_obsolete\neager_resources.txt = setuptools.command.egg_info:overwrite_arg\nentry_points.txt = setuptools.command.egg_info:write_entries\nnamespace_packages.txt = setuptools.command.egg_info:overwrite_arg\nrequires.txt = setuptools.command.egg_info:write_requirements\ntop_level.txt = setuptools.command.egg_info:write_toplevel_names\n\n[setuptools.finalize_distribution_options]\nkeywords = setuptools.dist:Distribution._finalize_setup_keywords\nparent_finalize = setuptools.dist:_Distribution.finalize_options\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools-65.5.1.dist-info/top_level.txt",
    "content": "_distutils_hack\npkg_resources\nsetuptools\n"
  },
  {
    "path": "lib/python3.7/site-packages/setuptools-65.5.1.virtualenv",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/wheel/__init__.py",
    "content": "from __future__ import annotations\n\n__version__ = \"0.38.4\"\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel/__main__.py",
    "content": "\"\"\"\nWheel command line tool (enable python -m wheel syntax)\n\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\n\n\ndef main():  # needed for console script\n    if __package__ == \"\":\n        # To be able to run 'python wheel-0.9.whl/wheel':\n        import os.path\n\n        path = os.path.dirname(os.path.dirname(__file__))\n        sys.path[0:0] = [path]\n    import wheel.cli\n\n    sys.exit(wheel.cli.main())\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel/_setuptools_logging.py",
    "content": "# copied from setuptools.logging, omitting monkeypatching\nfrom __future__ import annotations\n\nimport logging\nimport sys\n\n\ndef _not_warning(record):\n    return record.levelno < logging.WARNING\n\n\ndef configure():\n    \"\"\"\n    Configure logging to emit warning and above to stderr\n    and everything else to stdout. This behavior is provided\n    for compatibility with distutils.log but may change in\n    the future.\n    \"\"\"\n    err_handler = logging.StreamHandler()\n    err_handler.setLevel(logging.WARNING)\n    out_handler = logging.StreamHandler(sys.stdout)\n    out_handler.addFilter(_not_warning)\n    handlers = err_handler, out_handler\n    logging.basicConfig(\n        format=\"{message}\", style=\"{\", handlers=handlers, level=logging.DEBUG\n    )\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel/bdist_wheel.py",
    "content": "\"\"\"\nCreate a wheel (.whl) distribution.\n\nA wheel is a built archive format.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport re\nimport shutil\nimport stat\nimport sys\nimport sysconfig\nimport warnings\nfrom collections import OrderedDict\nfrom email.generator import BytesGenerator, Generator\nfrom email.policy import EmailPolicy\nfrom glob import iglob\nfrom io import BytesIO\nfrom shutil import rmtree\nfrom zipfile import ZIP_DEFLATED, ZIP_STORED\n\nimport pkg_resources\nfrom setuptools import Command\n\nfrom . import __version__ as wheel_version\nfrom .macosx_libfile import calculate_macosx_platform_tag\nfrom .metadata import pkginfo_to_metadata\nfrom .util import log\nfrom .vendored.packaging import tags\nfrom .wheelfile import WheelFile\n\nsafe_name = pkg_resources.safe_name\nsafe_version = pkg_resources.safe_version\nsetuptools_major_version = int(\n    pkg_resources.get_distribution(\"setuptools\").version.split(\".\")[0]\n)\n\nPY_LIMITED_API_PATTERN = r\"cp3\\d\"\n\n\ndef python_tag():\n    return f\"py{sys.version_info[0]}\"\n\n\ndef get_platform(archive_root):\n    \"\"\"Return our platform name 'win32', 'linux_x86_64'\"\"\"\n    result = sysconfig.get_platform()\n    if result.startswith(\"macosx\") and archive_root is not None:\n        result = calculate_macosx_platform_tag(archive_root, result)\n    elif result == \"linux-x86_64\" and sys.maxsize == 2147483647:\n        # pip pull request #3497\n        result = \"linux-i686\"\n\n    return result.replace(\"-\", \"_\")\n\n\ndef get_flag(var, fallback, expected=True, warn=True):\n    \"\"\"Use a fallback value for determining SOABI flags if the needed config\n    var is unset or unavailable.\"\"\"\n    val = sysconfig.get_config_var(var)\n    if val is None:\n        if warn:\n            warnings.warn(\n                \"Config variable '{}' is unset, Python ABI tag may \"\n                \"be incorrect\".format(var),\n                RuntimeWarning,\n                2,\n            )\n        return fallback\n    return val == expected\n\n\ndef get_abi_tag():\n    \"\"\"Return the ABI tag based on SOABI (if available) or emulate SOABI (PyPy2).\"\"\"\n    soabi = sysconfig.get_config_var(\"SOABI\")\n    impl = tags.interpreter_name()\n    if not soabi and impl in (\"cp\", \"pp\") and hasattr(sys, \"maxunicode\"):\n        d = \"\"\n        m = \"\"\n        u = \"\"\n        if get_flag(\"Py_DEBUG\", hasattr(sys, \"gettotalrefcount\"), warn=(impl == \"cp\")):\n            d = \"d\"\n\n        if get_flag(\n            \"WITH_PYMALLOC\",\n            impl == \"cp\",\n            warn=(impl == \"cp\" and sys.version_info < (3, 8)),\n        ) and sys.version_info < (3, 8):\n            m = \"m\"\n\n        abi = f\"{impl}{tags.interpreter_version()}{d}{m}{u}\"\n    elif soabi and impl == \"cp\":\n        abi = \"cp\" + soabi.split(\"-\")[1]\n    elif soabi and impl == \"pp\":\n        # we want something like pypy36-pp73\n        abi = \"-\".join(soabi.split(\"-\")[:2])\n        abi = abi.replace(\".\", \"_\").replace(\"-\", \"_\")\n    elif soabi:\n        abi = soabi.replace(\".\", \"_\").replace(\"-\", \"_\")\n    else:\n        abi = None\n\n    return abi\n\n\ndef safer_name(name):\n    return safe_name(name).replace(\"-\", \"_\")\n\n\ndef safer_version(version):\n    return safe_version(version).replace(\"-\", \"_\")\n\n\ndef remove_readonly(func, path, excinfo):\n    print(str(excinfo[1]))\n    os.chmod(path, stat.S_IWRITE)\n    func(path)\n\n\nclass bdist_wheel(Command):\n\n    description = \"create a wheel distribution\"\n\n    supported_compressions = OrderedDict(\n        [(\"stored\", ZIP_STORED), (\"deflated\", ZIP_DEFLATED)]\n    )\n\n    user_options = [\n        (\"bdist-dir=\", \"b\", \"temporary directory for creating the distribution\"),\n        (\n            \"plat-name=\",\n            \"p\",\n            \"platform name to embed in generated filenames \"\n            \"(default: %s)\" % get_platform(None),\n        ),\n        (\n            \"keep-temp\",\n            \"k\",\n            \"keep the pseudo-installation tree around after \"\n            + \"creating the distribution archive\",\n        ),\n        (\"dist-dir=\", \"d\", \"directory to put final built distributions in\"),\n        (\"skip-build\", None, \"skip rebuilding everything (for testing/debugging)\"),\n        (\n            \"relative\",\n            None,\n            \"build the archive using relative paths \" \"(default: false)\",\n        ),\n        (\n            \"owner=\",\n            \"u\",\n            \"Owner name used when creating a tar file\" \" [default: current user]\",\n        ),\n        (\n            \"group=\",\n            \"g\",\n            \"Group name used when creating a tar file\" \" [default: current group]\",\n        ),\n        (\"universal\", None, \"make a universal wheel\" \" (default: false)\"),\n        (\n            \"compression=\",\n            None,\n            \"zipfile compression (one of: {})\"\n            \" (default: 'deflated')\".format(\", \".join(supported_compressions)),\n        ),\n        (\n            \"python-tag=\",\n            None,\n            \"Python implementation compatibility tag\"\n            \" (default: '%s')\" % (python_tag()),\n        ),\n        (\n            \"build-number=\",\n            None,\n            \"Build number for this particular version. \"\n            \"As specified in PEP-0427, this must start with a digit. \"\n            \"[default: None]\",\n        ),\n        (\n            \"py-limited-api=\",\n            None,\n            \"Python tag (cp32|cp33|cpNN) for abi3 wheel tag\" \" (default: false)\",\n        ),\n    ]\n\n    boolean_options = [\"keep-temp\", \"skip-build\", \"relative\", \"universal\"]\n\n    def initialize_options(self):\n        self.bdist_dir = None\n        self.data_dir = None\n        self.plat_name = None\n        self.plat_tag = None\n        self.format = \"zip\"\n        self.keep_temp = False\n        self.dist_dir = None\n        self.egginfo_dir = None\n        self.root_is_pure = None\n        self.skip_build = None\n        self.relative = False\n        self.owner = None\n        self.group = None\n        self.universal = False\n        self.compression = \"deflated\"\n        self.python_tag = python_tag()\n        self.build_number = None\n        self.py_limited_api = False\n        self.plat_name_supplied = False\n\n    def finalize_options(self):\n        if self.bdist_dir is None:\n            bdist_base = self.get_finalized_command(\"bdist\").bdist_base\n            self.bdist_dir = os.path.join(bdist_base, \"wheel\")\n\n        self.data_dir = self.wheel_dist_name + \".data\"\n        self.plat_name_supplied = self.plat_name is not None\n\n        try:\n            self.compression = self.supported_compressions[self.compression]\n        except KeyError:\n            raise ValueError(f\"Unsupported compression: {self.compression}\")\n\n        need_options = (\"dist_dir\", \"plat_name\", \"skip_build\")\n\n        self.set_undefined_options(\"bdist\", *zip(need_options, need_options))\n\n        self.root_is_pure = not (\n            self.distribution.has_ext_modules() or self.distribution.has_c_libraries()\n        )\n\n        if self.py_limited_api and not re.match(\n            PY_LIMITED_API_PATTERN, self.py_limited_api\n        ):\n            raise ValueError(\"py-limited-api must match '%s'\" % PY_LIMITED_API_PATTERN)\n\n        # Support legacy [wheel] section for setting universal\n        wheel = self.distribution.get_option_dict(\"wheel\")\n        if \"universal\" in wheel:\n            # please don't define this in your global configs\n            log.warning(\n                \"The [wheel] section is deprecated. Use [bdist_wheel] instead.\",\n            )\n            val = wheel[\"universal\"][1].strip()\n            if val.lower() in (\"1\", \"true\", \"yes\"):\n                self.universal = True\n\n        if self.build_number is not None and not self.build_number[:1].isdigit():\n            raise ValueError(\"Build tag (build-number) must start with a digit.\")\n\n    @property\n    def wheel_dist_name(self):\n        \"\"\"Return distribution full name with - replaced with _\"\"\"\n        components = (\n            safer_name(self.distribution.get_name()),\n            safer_version(self.distribution.get_version()),\n        )\n        if self.build_number:\n            components += (self.build_number,)\n        return \"-\".join(components)\n\n    def get_tag(self):\n        # bdist sets self.plat_name if unset, we should only use it for purepy\n        # wheels if the user supplied it.\n        if self.plat_name_supplied:\n            plat_name = self.plat_name\n        elif self.root_is_pure:\n            plat_name = \"any\"\n        else:\n            # macosx contains system version in platform name so need special handle\n            if self.plat_name and not self.plat_name.startswith(\"macosx\"):\n                plat_name = self.plat_name\n            else:\n                # on macosx always limit the platform name to comply with any\n                # c-extension modules in bdist_dir, since the user can specify\n                # a higher MACOSX_DEPLOYMENT_TARGET via tools like CMake\n\n                # on other platforms, and on macosx if there are no c-extension\n                # modules, use the default platform name.\n                plat_name = get_platform(self.bdist_dir)\n\n            if (\n                plat_name in (\"linux-x86_64\", \"linux_x86_64\")\n                and sys.maxsize == 2147483647\n            ):\n                plat_name = \"linux_i686\"\n\n        plat_name = plat_name.lower().replace(\"-\", \"_\").replace(\".\", \"_\")\n\n        if self.root_is_pure:\n            if self.universal:\n                impl = \"py2.py3\"\n            else:\n                impl = self.python_tag\n            tag = (impl, \"none\", plat_name)\n        else:\n            impl_name = tags.interpreter_name()\n            impl_ver = tags.interpreter_version()\n            impl = impl_name + impl_ver\n            # We don't work on CPython 3.1, 3.0.\n            if self.py_limited_api and (impl_name + impl_ver).startswith(\"cp3\"):\n                impl = self.py_limited_api\n                abi_tag = \"abi3\"\n            else:\n                abi_tag = str(get_abi_tag()).lower()\n            tag = (impl, abi_tag, plat_name)\n            # issue gh-374: allow overriding plat_name\n            supported_tags = [\n                (t.interpreter, t.abi, plat_name) for t in tags.sys_tags()\n            ]\n            assert (\n                tag in supported_tags\n            ), f\"would build wheel with unsupported tag {tag}\"\n        return tag\n\n    def run(self):\n        build_scripts = self.reinitialize_command(\"build_scripts\")\n        build_scripts.executable = \"python\"\n        build_scripts.force = True\n\n        build_ext = self.reinitialize_command(\"build_ext\")\n        build_ext.inplace = False\n\n        if not self.skip_build:\n            self.run_command(\"build\")\n\n        install = self.reinitialize_command(\"install\", reinit_subcommands=True)\n        install.root = self.bdist_dir\n        install.compile = False\n        install.skip_build = self.skip_build\n        install.warn_dir = False\n\n        # A wheel without setuptools scripts is more cross-platform.\n        # Use the (undocumented) `no_ep` option to setuptools'\n        # install_scripts command to avoid creating entry point scripts.\n        install_scripts = self.reinitialize_command(\"install_scripts\")\n        install_scripts.no_ep = True\n\n        # Use a custom scheme for the archive, because we have to decide\n        # at installation time which scheme to use.\n        for key in (\"headers\", \"scripts\", \"data\", \"purelib\", \"platlib\"):\n            setattr(install, \"install_\" + key, os.path.join(self.data_dir, key))\n\n        basedir_observed = \"\"\n\n        if os.name == \"nt\":\n            # win32 barfs if any of these are ''; could be '.'?\n            # (distutils.command.install:change_roots bug)\n            basedir_observed = os.path.normpath(os.path.join(self.data_dir, \"..\"))\n            self.install_libbase = self.install_lib = basedir_observed\n\n        setattr(\n            install,\n            \"install_purelib\" if self.root_is_pure else \"install_platlib\",\n            basedir_observed,\n        )\n\n        log.info(f\"installing to {self.bdist_dir}\")\n\n        self.run_command(\"install\")\n\n        impl_tag, abi_tag, plat_tag = self.get_tag()\n        archive_basename = f\"{self.wheel_dist_name}-{impl_tag}-{abi_tag}-{plat_tag}\"\n        if not self.relative:\n            archive_root = self.bdist_dir\n        else:\n            archive_root = os.path.join(\n                self.bdist_dir, self._ensure_relative(install.install_base)\n            )\n\n        self.set_undefined_options(\"install_egg_info\", (\"target\", \"egginfo_dir\"))\n        distinfo_dirname = \"{}-{}.dist-info\".format(\n            safer_name(self.distribution.get_name()),\n            safer_version(self.distribution.get_version()),\n        )\n        distinfo_dir = os.path.join(self.bdist_dir, distinfo_dirname)\n        self.egg2dist(self.egginfo_dir, distinfo_dir)\n\n        self.write_wheelfile(distinfo_dir)\n\n        # Make the archive\n        if not os.path.exists(self.dist_dir):\n            os.makedirs(self.dist_dir)\n\n        wheel_path = os.path.join(self.dist_dir, archive_basename + \".whl\")\n        with WheelFile(wheel_path, \"w\", self.compression) as wf:\n            wf.write_files(archive_root)\n\n        # Add to 'Distribution.dist_files' so that the \"upload\" command works\n        getattr(self.distribution, \"dist_files\", []).append(\n            (\n                \"bdist_wheel\",\n                \"{}.{}\".format(*sys.version_info[:2]),  # like 3.7\n                wheel_path,\n            )\n        )\n\n        if not self.keep_temp:\n            log.info(f\"removing {self.bdist_dir}\")\n            if not self.dry_run:\n                rmtree(self.bdist_dir, onerror=remove_readonly)\n\n    def write_wheelfile(\n        self, wheelfile_base, generator=\"bdist_wheel (\" + wheel_version + \")\"\n    ):\n        from email.message import Message\n\n        msg = Message()\n        msg[\"Wheel-Version\"] = \"1.0\"  # of the spec\n        msg[\"Generator\"] = generator\n        msg[\"Root-Is-Purelib\"] = str(self.root_is_pure).lower()\n        if self.build_number is not None:\n            msg[\"Build\"] = self.build_number\n\n        # Doesn't work for bdist_wininst\n        impl_tag, abi_tag, plat_tag = self.get_tag()\n        for impl in impl_tag.split(\".\"):\n            for abi in abi_tag.split(\".\"):\n                for plat in plat_tag.split(\".\"):\n                    msg[\"Tag\"] = \"-\".join((impl, abi, plat))\n\n        wheelfile_path = os.path.join(wheelfile_base, \"WHEEL\")\n        log.info(f\"creating {wheelfile_path}\")\n        buffer = BytesIO()\n        BytesGenerator(buffer, maxheaderlen=0).flatten(msg)\n        with open(wheelfile_path, \"wb\") as f:\n            f.write(buffer.getvalue().replace(b\"\\r\\n\", b\"\\r\"))\n\n    def _ensure_relative(self, path):\n        # copied from dir_util, deleted\n        drive, path = os.path.splitdrive(path)\n        if path[0:1] == os.sep:\n            path = drive + path[1:]\n        return path\n\n    @property\n    def license_paths(self):\n        if setuptools_major_version >= 57:\n            # Setuptools has resolved any patterns to actual file names\n            return self.distribution.metadata.license_files or ()\n\n        files = set()\n        metadata = self.distribution.get_option_dict(\"metadata\")\n        if setuptools_major_version >= 42:\n            # Setuptools recognizes the license_files option but does not do globbing\n            patterns = self.distribution.metadata.license_files\n        else:\n            # Prior to those, wheel is entirely responsible for handling license files\n            if \"license_files\" in metadata:\n                patterns = metadata[\"license_files\"][1].split()\n            else:\n                patterns = ()\n\n        if \"license_file\" in metadata:\n            warnings.warn(\n                'The \"license_file\" option is deprecated. Use \"license_files\" instead.',\n                DeprecationWarning,\n            )\n            files.add(metadata[\"license_file\"][1])\n\n        if not files and not patterns and not isinstance(patterns, list):\n            patterns = (\"LICEN[CS]E*\", \"COPYING*\", \"NOTICE*\", \"AUTHORS*\")\n\n        for pattern in patterns:\n            for path in iglob(pattern):\n                if path.endswith(\"~\"):\n                    log.debug(\n                        f'ignoring license file \"{path}\" as it looks like a backup'\n                    )\n                    continue\n\n                if path not in files and os.path.isfile(path):\n                    log.info(\n                        f'adding license file \"{path}\" (matched pattern \"{pattern}\")'\n                    )\n                    files.add(path)\n\n        return files\n\n    def egg2dist(self, egginfo_path, distinfo_path):\n        \"\"\"Convert an .egg-info directory into a .dist-info directory\"\"\"\n\n        def adios(p):\n            \"\"\"Appropriately delete directory, file or link.\"\"\"\n            if os.path.exists(p) and not os.path.islink(p) and os.path.isdir(p):\n                shutil.rmtree(p)\n            elif os.path.exists(p):\n                os.unlink(p)\n\n        adios(distinfo_path)\n\n        if not os.path.exists(egginfo_path):\n            # There is no egg-info. This is probably because the egg-info\n            # file/directory is not named matching the distribution name used\n            # to name the archive file. Check for this case and report\n            # accordingly.\n            import glob\n\n            pat = os.path.join(os.path.dirname(egginfo_path), \"*.egg-info\")\n            possible = glob.glob(pat)\n            err = f\"Egg metadata expected at {egginfo_path} but not found\"\n            if possible:\n                alt = os.path.basename(possible[0])\n                err += f\" ({alt} found - possible misnamed archive file?)\"\n\n            raise ValueError(err)\n\n        if os.path.isfile(egginfo_path):\n            # .egg-info is a single file\n            pkginfo_path = egginfo_path\n            pkg_info = pkginfo_to_metadata(egginfo_path, egginfo_path)\n            os.mkdir(distinfo_path)\n        else:\n            # .egg-info is a directory\n            pkginfo_path = os.path.join(egginfo_path, \"PKG-INFO\")\n            pkg_info = pkginfo_to_metadata(egginfo_path, pkginfo_path)\n\n            # ignore common egg metadata that is useless to wheel\n            shutil.copytree(\n                egginfo_path,\n                distinfo_path,\n                ignore=lambda x, y: {\n                    \"PKG-INFO\",\n                    \"requires.txt\",\n                    \"SOURCES.txt\",\n                    \"not-zip-safe\",\n                },\n            )\n\n            # delete dependency_links if it is only whitespace\n            dependency_links_path = os.path.join(distinfo_path, \"dependency_links.txt\")\n            with open(dependency_links_path) as dependency_links_file:\n                dependency_links = dependency_links_file.read().strip()\n            if not dependency_links:\n                adios(dependency_links_path)\n\n        pkg_info_path = os.path.join(distinfo_path, \"METADATA\")\n        serialization_policy = EmailPolicy(\n            utf8=True,\n            mangle_from_=False,\n            max_line_length=0,\n        )\n        with open(pkg_info_path, \"w\", encoding=\"utf-8\") as out:\n            Generator(out, policy=serialization_policy).flatten(pkg_info)\n\n        for license_path in self.license_paths:\n            filename = os.path.basename(license_path)\n            shutil.copy(license_path, os.path.join(distinfo_path, filename))\n\n        adios(egginfo_path)\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel/cli/__init__.py",
    "content": "\"\"\"\nWheel command-line utility.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport os\nimport sys\n\n\nclass WheelError(Exception):\n    pass\n\n\ndef unpack_f(args):\n    from .unpack import unpack\n\n    unpack(args.wheelfile, args.dest)\n\n\ndef pack_f(args):\n    from .pack import pack\n\n    pack(args.directory, args.dest_dir, args.build_number)\n\n\ndef convert_f(args):\n    from .convert import convert\n\n    convert(args.files, args.dest_dir, args.verbose)\n\n\ndef version_f(args):\n    from .. import __version__\n\n    print(\"wheel %s\" % __version__)\n\n\ndef parser():\n    p = argparse.ArgumentParser()\n    s = p.add_subparsers(help=\"commands\")\n\n    unpack_parser = s.add_parser(\"unpack\", help=\"Unpack wheel\")\n    unpack_parser.add_argument(\n        \"--dest\", \"-d\", help=\"Destination directory\", default=\".\"\n    )\n    unpack_parser.add_argument(\"wheelfile\", help=\"Wheel file\")\n    unpack_parser.set_defaults(func=unpack_f)\n\n    repack_parser = s.add_parser(\"pack\", help=\"Repack wheel\")\n    repack_parser.add_argument(\"directory\", help=\"Root directory of the unpacked wheel\")\n    repack_parser.add_argument(\n        \"--dest-dir\",\n        \"-d\",\n        default=os.path.curdir,\n        help=\"Directory to store the wheel (default %(default)s)\",\n    )\n    repack_parser.add_argument(\n        \"--build-number\", help=\"Build tag to use in the wheel name\"\n    )\n    repack_parser.set_defaults(func=pack_f)\n\n    convert_parser = s.add_parser(\"convert\", help=\"Convert egg or wininst to wheel\")\n    convert_parser.add_argument(\"files\", nargs=\"*\", help=\"Files to convert\")\n    convert_parser.add_argument(\n        \"--dest-dir\",\n        \"-d\",\n        default=os.path.curdir,\n        help=\"Directory to store wheels (default %(default)s)\",\n    )\n    convert_parser.add_argument(\"--verbose\", \"-v\", action=\"store_true\")\n    convert_parser.set_defaults(func=convert_f)\n\n    version_parser = s.add_parser(\"version\", help=\"Print version and exit\")\n    version_parser.set_defaults(func=version_f)\n\n    help_parser = s.add_parser(\"help\", help=\"Show this help\")\n    help_parser.set_defaults(func=lambda args: p.print_help())\n\n    return p\n\n\ndef main():\n    p = parser()\n    args = p.parse_args()\n    if not hasattr(args, \"func\"):\n        p.print_help()\n    else:\n        try:\n            args.func(args)\n            return 0\n        except WheelError as e:\n            print(e, file=sys.stderr)\n\n    return 1\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel/cli/convert.py",
    "content": "from __future__ import annotations\n\nimport os.path\nimport re\nimport shutil\nimport tempfile\nimport zipfile\nfrom glob import iglob\n\nfrom ..bdist_wheel import bdist_wheel\nfrom ..wheelfile import WheelFile\nfrom . import WheelError\n\ntry:\n    from setuptools import Distribution\nexcept ImportError:\n    from distutils.dist import Distribution\n\negg_info_re = re.compile(\n    r\"\"\"\n    (?P<name>.+?)-(?P<ver>.+?)\n    (-(?P<pyver>py\\d\\.\\d+)\n     (-(?P<arch>.+?))?\n    )?.egg$\"\"\",\n    re.VERBOSE,\n)\n\n\nclass _bdist_wheel_tag(bdist_wheel):\n    # allow the client to override the default generated wheel tag\n    # The default bdist_wheel implementation uses python and abi tags\n    # of the running python process. This is not suitable for\n    # generating/repackaging prebuild binaries.\n\n    full_tag_supplied = False\n    full_tag = None  # None or a (pytag, soabitag, plattag) triple\n\n    def get_tag(self):\n        if self.full_tag_supplied and self.full_tag is not None:\n            return self.full_tag\n        else:\n            return bdist_wheel.get_tag(self)\n\n\ndef egg2wheel(egg_path: str, dest_dir: str):\n    filename = os.path.basename(egg_path)\n    match = egg_info_re.match(filename)\n    if not match:\n        raise WheelError(f\"Invalid egg file name: {filename}\")\n\n    egg_info = match.groupdict()\n    dir = tempfile.mkdtemp(suffix=\"_e2w\")\n    if os.path.isfile(egg_path):\n        # assume we have a bdist_egg otherwise\n        with zipfile.ZipFile(egg_path) as egg:\n            egg.extractall(dir)\n    else:\n        # support buildout-style installed eggs directories\n        for pth in os.listdir(egg_path):\n            src = os.path.join(egg_path, pth)\n            if os.path.isfile(src):\n                shutil.copy2(src, dir)\n            else:\n                shutil.copytree(src, os.path.join(dir, pth))\n\n    pyver = egg_info[\"pyver\"]\n    if pyver:\n        pyver = egg_info[\"pyver\"] = pyver.replace(\".\", \"\")\n\n    arch = (egg_info[\"arch\"] or \"any\").replace(\".\", \"_\").replace(\"-\", \"_\")\n\n    # assume all binary eggs are for CPython\n    abi = \"cp\" + pyver[2:] if arch != \"any\" else \"none\"\n\n    root_is_purelib = egg_info[\"arch\"] is None\n    if root_is_purelib:\n        bw = bdist_wheel(Distribution())\n    else:\n        bw = _bdist_wheel_tag(Distribution())\n\n    bw.root_is_pure = root_is_purelib\n    bw.python_tag = pyver\n    bw.plat_name_supplied = True\n    bw.plat_name = egg_info[\"arch\"] or \"any\"\n    if not root_is_purelib:\n        bw.full_tag_supplied = True\n        bw.full_tag = (pyver, abi, arch)\n\n    dist_info_dir = os.path.join(dir, \"{name}-{ver}.dist-info\".format(**egg_info))\n    bw.egg2dist(os.path.join(dir, \"EGG-INFO\"), dist_info_dir)\n    bw.write_wheelfile(dist_info_dir, generator=\"egg2wheel\")\n    wheel_name = \"{name}-{ver}-{pyver}-{}-{}.whl\".format(abi, arch, **egg_info)\n    with WheelFile(os.path.join(dest_dir, wheel_name), \"w\") as wf:\n        wf.write_files(dir)\n\n    shutil.rmtree(dir)\n\n\ndef parse_wininst_info(wininfo_name, egginfo_name):\n    \"\"\"Extract metadata from filenames.\n\n    Extracts the 4 metadataitems needed (name, version, pyversion, arch) from\n    the installer filename and the name of the egg-info directory embedded in\n    the zipfile (if any).\n\n    The egginfo filename has the format::\n\n        name-ver(-pyver)(-arch).egg-info\n\n    The installer filename has the format::\n\n        name-ver.arch(-pyver).exe\n\n    Some things to note:\n\n    1. The installer filename is not definitive. An installer can be renamed\n       and work perfectly well as an installer. So more reliable data should\n       be used whenever possible.\n    2. The egg-info data should be preferred for the name and version, because\n       these come straight from the distutils metadata, and are mandatory.\n    3. The pyver from the egg-info data should be ignored, as it is\n       constructed from the version of Python used to build the installer,\n       which is irrelevant - the installer filename is correct here (even to\n       the point that when it's not there, any version is implied).\n    4. The architecture must be taken from the installer filename, as it is\n       not included in the egg-info data.\n    5. Architecture-neutral installers still have an architecture because the\n       installer format itself (being executable) is architecture-specific. We\n       should therefore ignore the architecture if the content is pure-python.\n    \"\"\"\n\n    egginfo = None\n    if egginfo_name:\n        egginfo = egg_info_re.search(egginfo_name)\n        if not egginfo:\n            raise ValueError(f\"Egg info filename {egginfo_name} is not valid\")\n\n    # Parse the wininst filename\n    # 1. Distribution name (up to the first '-')\n    w_name, sep, rest = wininfo_name.partition(\"-\")\n    if not sep:\n        raise ValueError(f\"Installer filename {wininfo_name} is not valid\")\n\n    # Strip '.exe'\n    rest = rest[:-4]\n    # 2. Python version (from the last '-', must start with 'py')\n    rest2, sep, w_pyver = rest.rpartition(\"-\")\n    if sep and w_pyver.startswith(\"py\"):\n        rest = rest2\n        w_pyver = w_pyver.replace(\".\", \"\")\n    else:\n        # Not version specific - use py2.py3. While it is possible that\n        # pure-Python code is not compatible with both Python 2 and 3, there\n        # is no way of knowing from the wininst format, so we assume the best\n        # here (the user can always manually rename the wheel to be more\n        # restrictive if needed).\n        w_pyver = \"py2.py3\"\n    # 3. Version and architecture\n    w_ver, sep, w_arch = rest.rpartition(\".\")\n    if not sep:\n        raise ValueError(f\"Installer filename {wininfo_name} is not valid\")\n\n    if egginfo:\n        w_name = egginfo.group(\"name\")\n        w_ver = egginfo.group(\"ver\")\n\n    return {\"name\": w_name, \"ver\": w_ver, \"arch\": w_arch, \"pyver\": w_pyver}\n\n\ndef wininst2wheel(path, dest_dir):\n    with zipfile.ZipFile(path) as bdw:\n        # Search for egg-info in the archive\n        egginfo_name = None\n        for filename in bdw.namelist():\n            if \".egg-info\" in filename:\n                egginfo_name = filename\n                break\n\n        info = parse_wininst_info(os.path.basename(path), egginfo_name)\n\n        root_is_purelib = True\n        for zipinfo in bdw.infolist():\n            if zipinfo.filename.startswith(\"PLATLIB\"):\n                root_is_purelib = False\n                break\n        if root_is_purelib:\n            paths = {\"purelib\": \"\"}\n        else:\n            paths = {\"platlib\": \"\"}\n\n        dist_info = \"%(name)s-%(ver)s\" % info\n        datadir = \"%s.data/\" % dist_info\n\n        # rewrite paths to trick ZipFile into extracting an egg\n        # XXX grab wininst .ini - between .exe, padding, and first zip file.\n        members = []\n        egginfo_name = \"\"\n        for zipinfo in bdw.infolist():\n            key, basename = zipinfo.filename.split(\"/\", 1)\n            key = key.lower()\n            basepath = paths.get(key, None)\n            if basepath is None:\n                basepath = datadir + key.lower() + \"/\"\n            oldname = zipinfo.filename\n            newname = basepath + basename\n            zipinfo.filename = newname\n            del bdw.NameToInfo[oldname]\n            bdw.NameToInfo[newname] = zipinfo\n            # Collect member names, but omit '' (from an entry like \"PLATLIB/\"\n            if newname:\n                members.append(newname)\n            # Remember egg-info name for the egg2dist call below\n            if not egginfo_name:\n                if newname.endswith(\".egg-info\"):\n                    egginfo_name = newname\n                elif \".egg-info/\" in newname:\n                    egginfo_name, sep, _ = newname.rpartition(\"/\")\n        dir = tempfile.mkdtemp(suffix=\"_b2w\")\n        bdw.extractall(dir, members)\n\n    # egg2wheel\n    abi = \"none\"\n    pyver = info[\"pyver\"]\n    arch = (info[\"arch\"] or \"any\").replace(\".\", \"_\").replace(\"-\", \"_\")\n    # Wininst installers always have arch even if they are not\n    # architecture-specific (because the format itself is).\n    # So, assume the content is architecture-neutral if root is purelib.\n    if root_is_purelib:\n        arch = \"any\"\n    # If the installer is architecture-specific, it's almost certainly also\n    # CPython-specific.\n    if arch != \"any\":\n        pyver = pyver.replace(\"py\", \"cp\")\n    wheel_name = \"-\".join((dist_info, pyver, abi, arch))\n    if root_is_purelib:\n        bw = bdist_wheel(Distribution())\n    else:\n        bw = _bdist_wheel_tag(Distribution())\n\n    bw.root_is_pure = root_is_purelib\n    bw.python_tag = pyver\n    bw.plat_name_supplied = True\n    bw.plat_name = info[\"arch\"] or \"any\"\n\n    if not root_is_purelib:\n        bw.full_tag_supplied = True\n        bw.full_tag = (pyver, abi, arch)\n\n    dist_info_dir = os.path.join(dir, \"%s.dist-info\" % dist_info)\n    bw.egg2dist(os.path.join(dir, egginfo_name), dist_info_dir)\n    bw.write_wheelfile(dist_info_dir, generator=\"wininst2wheel\")\n\n    wheel_path = os.path.join(dest_dir, wheel_name)\n    with WheelFile(wheel_path, \"w\") as wf:\n        wf.write_files(dir)\n\n    shutil.rmtree(dir)\n\n\ndef convert(files, dest_dir, verbose):\n    for pat in files:\n        for installer in iglob(pat):\n            if os.path.splitext(installer)[1] == \".egg\":\n                conv = egg2wheel\n            else:\n                conv = wininst2wheel\n\n            if verbose:\n                print(f\"{installer}... \", flush=True)\n\n            conv(installer, dest_dir)\n            if verbose:\n                print(\"OK\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel/cli/pack.py",
    "content": "from __future__ import annotations\n\nimport os.path\nimport re\n\nfrom wheel.cli import WheelError\nfrom wheel.wheelfile import WheelFile\n\nDIST_INFO_RE = re.compile(r\"^(?P<namever>(?P<name>.+?)-(?P<ver>\\d.*?))\\.dist-info$\")\nBUILD_NUM_RE = re.compile(rb\"Build: (\\d\\w*)$\")\n\n\ndef pack(directory: str, dest_dir: str, build_number: str | None):\n    \"\"\"Repack a previously unpacked wheel directory into a new wheel file.\n\n    The .dist-info/WHEEL file must contain one or more tags so that the target\n    wheel file name can be determined.\n\n    :param directory: The unpacked wheel directory\n    :param dest_dir: Destination directory (defaults to the current directory)\n    \"\"\"\n    # Find the .dist-info directory\n    dist_info_dirs = [\n        fn\n        for fn in os.listdir(directory)\n        if os.path.isdir(os.path.join(directory, fn)) and DIST_INFO_RE.match(fn)\n    ]\n    if len(dist_info_dirs) > 1:\n        raise WheelError(f\"Multiple .dist-info directories found in {directory}\")\n    elif not dist_info_dirs:\n        raise WheelError(f\"No .dist-info directories found in {directory}\")\n\n    # Determine the target wheel filename\n    dist_info_dir = dist_info_dirs[0]\n    name_version = DIST_INFO_RE.match(dist_info_dir).group(\"namever\")\n\n    # Read the tags and the existing build number from .dist-info/WHEEL\n    existing_build_number = None\n    wheel_file_path = os.path.join(directory, dist_info_dir, \"WHEEL\")\n    with open(wheel_file_path) as f:\n        tags = []\n        for line in f:\n            if line.startswith(\"Tag: \"):\n                tags.append(line.split(\" \")[1].rstrip())\n            elif line.startswith(\"Build: \"):\n                existing_build_number = line.split(\" \")[1].rstrip()\n\n        if not tags:\n            raise WheelError(\n                \"No tags present in {}/WHEEL; cannot determine target wheel \"\n                \"filename\".format(dist_info_dir)\n            )\n\n    # Set the wheel file name and add/replace/remove the Build tag in .dist-info/WHEEL\n    build_number = build_number if build_number is not None else existing_build_number\n    if build_number is not None:\n        if build_number:\n            name_version += \"-\" + build_number\n\n        if build_number != existing_build_number:\n            replacement = (\n                (\"Build: %s\\r\\n\" % build_number).encode(\"ascii\")\n                if build_number\n                else b\"\"\n            )\n            with open(wheel_file_path, \"rb+\") as f:\n                wheel_file_content = f.read()\n                wheel_file_content, num_replaced = BUILD_NUM_RE.subn(\n                    replacement, wheel_file_content\n                )\n                if not num_replaced:\n                    wheel_file_content += replacement\n\n                f.seek(0)\n                f.truncate()\n                f.write(wheel_file_content)\n\n    # Reassemble the tags for the wheel file\n    impls = sorted({tag.split(\"-\")[0] for tag in tags})\n    abivers = sorted({tag.split(\"-\")[1] for tag in tags})\n    platforms = sorted({tag.split(\"-\")[2] for tag in tags})\n    tagline = \"-\".join([\".\".join(impls), \".\".join(abivers), \".\".join(platforms)])\n\n    # Repack the wheel\n    wheel_path = os.path.join(dest_dir, f\"{name_version}-{tagline}.whl\")\n    with WheelFile(wheel_path, \"w\") as wf:\n        print(f\"Repacking wheel as {wheel_path}...\", end=\"\", flush=True)\n        wf.write_files(directory)\n\n    print(\"OK\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel/cli/unpack.py",
    "content": "from __future__ import annotations\n\nfrom pathlib import Path\n\nfrom ..wheelfile import WheelFile\n\n\ndef unpack(path: str, dest: str = \".\") -> None:\n    \"\"\"Unpack a wheel.\n\n    Wheel content will be unpacked to {dest}/{name}-{ver}, where {name}\n    is the package name and {ver} its version.\n\n    :param path: The path to the wheel.\n    :param dest: Destination directory (default to current directory).\n    \"\"\"\n    with WheelFile(path) as wf:\n        namever = wf.parsed_filename.group(\"namever\")\n        destination = Path(dest) / namever\n        print(f\"Unpacking to: {destination}...\", end=\"\", flush=True)\n        wf.extractall(destination)\n\n    print(\"OK\")\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel/macosx_libfile.py",
    "content": "\"\"\"\nThis module contains function to analyse dynamic library\nheaders to extract system information\n\nCurrently only for MacOSX\n\nLibrary file on macosx system starts with Mach-O or Fat field.\nThis can be distinguish by first 32 bites and it is called magic number.\nProper value of magic number is with suffix _MAGIC. Suffix _CIGAM means\nreversed bytes order.\nBoth fields can occur in two types: 32 and 64 bytes.\n\nFAT field inform that this library contains few version of library\n(typically for different types version). It contains\ninformation where Mach-O headers starts.\n\nEach section started with Mach-O header contains one library\n(So if file starts with this field it contains only one version).\n\nAfter filed Mach-O there are section fields.\nEach of them starts with two fields:\ncmd - magic number for this command\ncmdsize - total size occupied by this section information.\n\nIn this case only sections LC_VERSION_MIN_MACOSX (for macosx 10.13 and earlier)\nand LC_BUILD_VERSION (for macosx 10.14 and newer) are interesting,\nbecause them contains information about minimal system version.\n\nImportant remarks:\n- For fat files this implementation looks for maximum number version.\n  It not check if it is 32 or 64 and do not compare it with currently built package.\n  So it is possible to false report higher version that needed.\n- All structures signatures are taken form macosx header files.\n- I think that binary format will be more stable than `otool` output.\n  and if apple introduce some changes both implementation will need to be updated.\n- The system compile will set the deployment target no lower than\n  11.0 for arm64 builds. For \"Universal 2\" builds use the x86_64 deployment\n  target when the arm64 target is 11.0.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport ctypes\nimport os\nimport sys\n\n\"\"\"here the needed const and struct from mach-o header files\"\"\"\n\nFAT_MAGIC = 0xCAFEBABE\nFAT_CIGAM = 0xBEBAFECA\nFAT_MAGIC_64 = 0xCAFEBABF\nFAT_CIGAM_64 = 0xBFBAFECA\nMH_MAGIC = 0xFEEDFACE\nMH_CIGAM = 0xCEFAEDFE\nMH_MAGIC_64 = 0xFEEDFACF\nMH_CIGAM_64 = 0xCFFAEDFE\n\nLC_VERSION_MIN_MACOSX = 0x24\nLC_BUILD_VERSION = 0x32\n\nCPU_TYPE_ARM64 = 0x0100000C\n\nmach_header_fields = [\n    (\"magic\", ctypes.c_uint32),\n    (\"cputype\", ctypes.c_int),\n    (\"cpusubtype\", ctypes.c_int),\n    (\"filetype\", ctypes.c_uint32),\n    (\"ncmds\", ctypes.c_uint32),\n    (\"sizeofcmds\", ctypes.c_uint32),\n    (\"flags\", ctypes.c_uint32),\n]\n\"\"\"\nstruct mach_header {\n    uint32_t\tmagic;\t\t/* mach magic number identifier */\n    cpu_type_t\tcputype;\t/* cpu specifier */\n    cpu_subtype_t\tcpusubtype;\t/* machine specifier */\n    uint32_t\tfiletype;\t/* type of file */\n    uint32_t\tncmds;\t\t/* number of load commands */\n    uint32_t\tsizeofcmds;\t/* the size of all the load commands */\n    uint32_t\tflags;\t\t/* flags */\n};\ntypedef integer_t cpu_type_t;\ntypedef integer_t cpu_subtype_t;\n\"\"\"\n\nmach_header_fields_64 = mach_header_fields + [(\"reserved\", ctypes.c_uint32)]\n\"\"\"\nstruct mach_header_64 {\n    uint32_t\tmagic;\t\t/* mach magic number identifier */\n    cpu_type_t\tcputype;\t/* cpu specifier */\n    cpu_subtype_t\tcpusubtype;\t/* machine specifier */\n    uint32_t\tfiletype;\t/* type of file */\n    uint32_t\tncmds;\t\t/* number of load commands */\n    uint32_t\tsizeofcmds;\t/* the size of all the load commands */\n    uint32_t\tflags;\t\t/* flags */\n    uint32_t\treserved;\t/* reserved */\n};\n\"\"\"\n\nfat_header_fields = [(\"magic\", ctypes.c_uint32), (\"nfat_arch\", ctypes.c_uint32)]\n\"\"\"\nstruct fat_header {\n    uint32_t\tmagic;\t\t/* FAT_MAGIC or FAT_MAGIC_64 */\n    uint32_t\tnfat_arch;\t/* number of structs that follow */\n};\n\"\"\"\n\nfat_arch_fields = [\n    (\"cputype\", ctypes.c_int),\n    (\"cpusubtype\", ctypes.c_int),\n    (\"offset\", ctypes.c_uint32),\n    (\"size\", ctypes.c_uint32),\n    (\"align\", ctypes.c_uint32),\n]\n\"\"\"\nstruct fat_arch {\n    cpu_type_t\tcputype;\t/* cpu specifier (int) */\n    cpu_subtype_t\tcpusubtype;\t/* machine specifier (int) */\n    uint32_t\toffset;\t\t/* file offset to this object file */\n    uint32_t\tsize;\t\t/* size of this object file */\n    uint32_t\talign;\t\t/* alignment as a power of 2 */\n};\n\"\"\"\n\nfat_arch_64_fields = [\n    (\"cputype\", ctypes.c_int),\n    (\"cpusubtype\", ctypes.c_int),\n    (\"offset\", ctypes.c_uint64),\n    (\"size\", ctypes.c_uint64),\n    (\"align\", ctypes.c_uint32),\n    (\"reserved\", ctypes.c_uint32),\n]\n\"\"\"\nstruct fat_arch_64 {\n    cpu_type_t\tcputype;\t/* cpu specifier (int) */\n    cpu_subtype_t\tcpusubtype;\t/* machine specifier (int) */\n    uint64_t\toffset;\t\t/* file offset to this object file */\n    uint64_t\tsize;\t\t/* size of this object file */\n    uint32_t\talign;\t\t/* alignment as a power of 2 */\n    uint32_t\treserved;\t/* reserved */\n};\n\"\"\"\n\nsegment_base_fields = [(\"cmd\", ctypes.c_uint32), (\"cmdsize\", ctypes.c_uint32)]\n\"\"\"base for reading segment info\"\"\"\n\nsegment_command_fields = [\n    (\"cmd\", ctypes.c_uint32),\n    (\"cmdsize\", ctypes.c_uint32),\n    (\"segname\", ctypes.c_char * 16),\n    (\"vmaddr\", ctypes.c_uint32),\n    (\"vmsize\", ctypes.c_uint32),\n    (\"fileoff\", ctypes.c_uint32),\n    (\"filesize\", ctypes.c_uint32),\n    (\"maxprot\", ctypes.c_int),\n    (\"initprot\", ctypes.c_int),\n    (\"nsects\", ctypes.c_uint32),\n    (\"flags\", ctypes.c_uint32),\n]\n\"\"\"\nstruct segment_command { /* for 32-bit architectures */\n    uint32_t\tcmd;\t\t/* LC_SEGMENT */\n    uint32_t\tcmdsize;\t/* includes sizeof section structs */\n    char\t\tsegname[16];\t/* segment name */\n    uint32_t\tvmaddr;\t\t/* memory address of this segment */\n    uint32_t\tvmsize;\t\t/* memory size of this segment */\n    uint32_t\tfileoff;\t/* file offset of this segment */\n    uint32_t\tfilesize;\t/* amount to map from the file */\n    vm_prot_t\tmaxprot;\t/* maximum VM protection */\n    vm_prot_t\tinitprot;\t/* initial VM protection */\n    uint32_t\tnsects;\t\t/* number of sections in segment */\n    uint32_t\tflags;\t\t/* flags */\n};\ntypedef int vm_prot_t;\n\"\"\"\n\nsegment_command_fields_64 = [\n    (\"cmd\", ctypes.c_uint32),\n    (\"cmdsize\", ctypes.c_uint32),\n    (\"segname\", ctypes.c_char * 16),\n    (\"vmaddr\", ctypes.c_uint64),\n    (\"vmsize\", ctypes.c_uint64),\n    (\"fileoff\", ctypes.c_uint64),\n    (\"filesize\", ctypes.c_uint64),\n    (\"maxprot\", ctypes.c_int),\n    (\"initprot\", ctypes.c_int),\n    (\"nsects\", ctypes.c_uint32),\n    (\"flags\", ctypes.c_uint32),\n]\n\"\"\"\nstruct segment_command_64 { /* for 64-bit architectures */\n    uint32_t\tcmd;\t\t/* LC_SEGMENT_64 */\n    uint32_t\tcmdsize;\t/* includes sizeof section_64 structs */\n    char\t\tsegname[16];\t/* segment name */\n    uint64_t\tvmaddr;\t\t/* memory address of this segment */\n    uint64_t\tvmsize;\t\t/* memory size of this segment */\n    uint64_t\tfileoff;\t/* file offset of this segment */\n    uint64_t\tfilesize;\t/* amount to map from the file */\n    vm_prot_t\tmaxprot;\t/* maximum VM protection */\n    vm_prot_t\tinitprot;\t/* initial VM protection */\n    uint32_t\tnsects;\t\t/* number of sections in segment */\n    uint32_t\tflags;\t\t/* flags */\n};\n\"\"\"\n\nversion_min_command_fields = segment_base_fields + [\n    (\"version\", ctypes.c_uint32),\n    (\"sdk\", ctypes.c_uint32),\n]\n\"\"\"\nstruct version_min_command {\n    uint32_t\tcmd;\t\t/* LC_VERSION_MIN_MACOSX or\n                               LC_VERSION_MIN_IPHONEOS or\n                               LC_VERSION_MIN_WATCHOS or\n                               LC_VERSION_MIN_TVOS */\n    uint32_t\tcmdsize;\t/* sizeof(struct min_version_command) */\n    uint32_t\tversion;\t/* X.Y.Z is encoded in nibbles xxxx.yy.zz */\n    uint32_t\tsdk;\t\t/* X.Y.Z is encoded in nibbles xxxx.yy.zz */\n};\n\"\"\"\n\nbuild_version_command_fields = segment_base_fields + [\n    (\"platform\", ctypes.c_uint32),\n    (\"minos\", ctypes.c_uint32),\n    (\"sdk\", ctypes.c_uint32),\n    (\"ntools\", ctypes.c_uint32),\n]\n\"\"\"\nstruct build_version_command {\n    uint32_t\tcmd;\t\t/* LC_BUILD_VERSION */\n    uint32_t\tcmdsize;\t/* sizeof(struct build_version_command) plus */\n                                /* ntools * sizeof(struct build_tool_version) */\n    uint32_t\tplatform;\t/* platform */\n    uint32_t\tminos;\t\t/* X.Y.Z is encoded in nibbles xxxx.yy.zz */\n    uint32_t\tsdk;\t\t/* X.Y.Z is encoded in nibbles xxxx.yy.zz */\n    uint32_t\tntools;\t\t/* number of tool entries following this */\n};\n\"\"\"\n\n\ndef swap32(x):\n    return (\n        ((x << 24) & 0xFF000000)\n        | ((x << 8) & 0x00FF0000)\n        | ((x >> 8) & 0x0000FF00)\n        | ((x >> 24) & 0x000000FF)\n    )\n\n\ndef get_base_class_and_magic_number(lib_file, seek=None):\n    if seek is None:\n        seek = lib_file.tell()\n    else:\n        lib_file.seek(seek)\n    magic_number = ctypes.c_uint32.from_buffer_copy(\n        lib_file.read(ctypes.sizeof(ctypes.c_uint32))\n    ).value\n\n    # Handle wrong byte order\n    if magic_number in [FAT_CIGAM, FAT_CIGAM_64, MH_CIGAM, MH_CIGAM_64]:\n        if sys.byteorder == \"little\":\n            BaseClass = ctypes.BigEndianStructure\n        else:\n            BaseClass = ctypes.LittleEndianStructure\n\n        magic_number = swap32(magic_number)\n    else:\n        BaseClass = ctypes.Structure\n\n    lib_file.seek(seek)\n    return BaseClass, magic_number\n\n\ndef read_data(struct_class, lib_file):\n    return struct_class.from_buffer_copy(lib_file.read(ctypes.sizeof(struct_class)))\n\n\ndef extract_macosx_min_system_version(path_to_lib):\n    with open(path_to_lib, \"rb\") as lib_file:\n        BaseClass, magic_number = get_base_class_and_magic_number(lib_file, 0)\n        if magic_number not in [FAT_MAGIC, FAT_MAGIC_64, MH_MAGIC, MH_MAGIC_64]:\n            return\n\n        if magic_number in [FAT_MAGIC, FAT_CIGAM_64]:\n\n            class FatHeader(BaseClass):\n                _fields_ = fat_header_fields\n\n            fat_header = read_data(FatHeader, lib_file)\n            if magic_number == FAT_MAGIC:\n\n                class FatArch(BaseClass):\n                    _fields_ = fat_arch_fields\n\n            else:\n\n                class FatArch(BaseClass):\n                    _fields_ = fat_arch_64_fields\n\n            fat_arch_list = [\n                read_data(FatArch, lib_file) for _ in range(fat_header.nfat_arch)\n            ]\n\n            versions_list = []\n            for el in fat_arch_list:\n                try:\n                    version = read_mach_header(lib_file, el.offset)\n                    if version is not None:\n                        if el.cputype == CPU_TYPE_ARM64 and len(fat_arch_list) != 1:\n                            # Xcode will not set the deployment target below 11.0.0\n                            # for the arm64 architecture. Ignore the arm64 deployment\n                            # in fat binaries when the target is 11.0.0, that way\n                            # the other architectures can select a lower deployment\n                            # target.\n                            # This is safe because there is no arm64 variant for\n                            # macOS 10.15 or earlier.\n                            if version == (11, 0, 0):\n                                continue\n                        versions_list.append(version)\n                except ValueError:\n                    pass\n\n            if len(versions_list) > 0:\n                return max(versions_list)\n            else:\n                return None\n\n        else:\n            try:\n                return read_mach_header(lib_file, 0)\n            except ValueError:\n                \"\"\"when some error during read library files\"\"\"\n                return None\n\n\ndef read_mach_header(lib_file, seek=None):\n    \"\"\"\n    This funcition parse mach-O header and extract\n    information about minimal system version\n\n    :param lib_file: reference to opened library file with pointer\n    \"\"\"\n    if seek is not None:\n        lib_file.seek(seek)\n    base_class, magic_number = get_base_class_and_magic_number(lib_file)\n    arch = \"32\" if magic_number == MH_MAGIC else \"64\"\n\n    class SegmentBase(base_class):\n        _fields_ = segment_base_fields\n\n    if arch == \"32\":\n\n        class MachHeader(base_class):\n            _fields_ = mach_header_fields\n\n    else:\n\n        class MachHeader(base_class):\n            _fields_ = mach_header_fields_64\n\n    mach_header = read_data(MachHeader, lib_file)\n    for _i in range(mach_header.ncmds):\n        pos = lib_file.tell()\n        segment_base = read_data(SegmentBase, lib_file)\n        lib_file.seek(pos)\n        if segment_base.cmd == LC_VERSION_MIN_MACOSX:\n\n            class VersionMinCommand(base_class):\n                _fields_ = version_min_command_fields\n\n            version_info = read_data(VersionMinCommand, lib_file)\n            return parse_version(version_info.version)\n        elif segment_base.cmd == LC_BUILD_VERSION:\n\n            class VersionBuild(base_class):\n                _fields_ = build_version_command_fields\n\n            version_info = read_data(VersionBuild, lib_file)\n            return parse_version(version_info.minos)\n        else:\n            lib_file.seek(pos + segment_base.cmdsize)\n            continue\n\n\ndef parse_version(version):\n    x = (version & 0xFFFF0000) >> 16\n    y = (version & 0x0000FF00) >> 8\n    z = version & 0x000000FF\n    return x, y, z\n\n\ndef calculate_macosx_platform_tag(archive_root, platform_tag):\n    \"\"\"\n    Calculate proper macosx platform tag basing on files which are included to wheel\n\n    Example platform tag `macosx-10.14-x86_64`\n    \"\"\"\n    prefix, base_version, suffix = platform_tag.split(\"-\")\n    base_version = tuple(int(x) for x in base_version.split(\".\"))\n    base_version = base_version[:2]\n    if base_version[0] > 10:\n        base_version = (base_version[0], 0)\n    assert len(base_version) == 2\n    if \"MACOSX_DEPLOYMENT_TARGET\" in os.environ:\n        deploy_target = tuple(\n            int(x) for x in os.environ[\"MACOSX_DEPLOYMENT_TARGET\"].split(\".\")\n        )\n        deploy_target = deploy_target[:2]\n        if deploy_target[0] > 10:\n            deploy_target = (deploy_target[0], 0)\n        if deploy_target < base_version:\n            sys.stderr.write(\n                \"[WARNING] MACOSX_DEPLOYMENT_TARGET is set to a lower value ({}) than \"\n                \"the version on which the Python interpreter was compiled ({}), and \"\n                \"will be ignored.\\n\".format(\n                    \".\".join(str(x) for x in deploy_target),\n                    \".\".join(str(x) for x in base_version),\n                )\n            )\n        else:\n            base_version = deploy_target\n\n    assert len(base_version) == 2\n    start_version = base_version\n    versions_dict = {}\n    for (dirpath, _dirnames, filenames) in os.walk(archive_root):\n        for filename in filenames:\n            if filename.endswith(\".dylib\") or filename.endswith(\".so\"):\n                lib_path = os.path.join(dirpath, filename)\n                min_ver = extract_macosx_min_system_version(lib_path)\n                if min_ver is not None:\n                    min_ver = min_ver[0:2]\n                    if min_ver[0] > 10:\n                        min_ver = (min_ver[0], 0)\n                    versions_dict[lib_path] = min_ver\n\n    if len(versions_dict) > 0:\n        base_version = max(base_version, max(versions_dict.values()))\n\n    # macosx platform tag do not support minor bugfix release\n    fin_base_version = \"_\".join([str(x) for x in base_version])\n    if start_version < base_version:\n        problematic_files = [k for k, v in versions_dict.items() if v > start_version]\n        problematic_files = \"\\n\".join(problematic_files)\n        if len(problematic_files) == 1:\n            files_form = \"this file\"\n        else:\n            files_form = \"these files\"\n        error_message = (\n            \"[WARNING] This wheel needs a higher macOS version than {}  \"\n            \"To silence this warning, set MACOSX_DEPLOYMENT_TARGET to at least \"\n            + fin_base_version\n            + \" or recreate \"\n            + files_form\n            + \" with lower \"\n            \"MACOSX_DEPLOYMENT_TARGET:  \\n\" + problematic_files\n        )\n\n        if \"MACOSX_DEPLOYMENT_TARGET\" in os.environ:\n            error_message = error_message.format(\n                \"is set in MACOSX_DEPLOYMENT_TARGET variable.\"\n            )\n        else:\n            error_message = error_message.format(\n                \"the version your Python interpreter is compiled against.\"\n            )\n\n        sys.stderr.write(error_message)\n\n    platform_tag = prefix + \"_\" + fin_base_version + \"_\" + suffix\n    return platform_tag\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel/metadata.py",
    "content": "\"\"\"\nTools for converting old- to new-style metadata.\n\"\"\"\nfrom __future__ import annotations\n\nimport os.path\nimport textwrap\nfrom email.message import Message\nfrom email.parser import Parser\nfrom typing import Iterator\n\nfrom pkg_resources import Requirement, safe_extra, split_sections\n\n\ndef requires_to_requires_dist(requirement: Requirement) -> str:\n    \"\"\"Return the version specifier for a requirement in PEP 345/566 fashion.\"\"\"\n    if getattr(requirement, \"url\", None):\n        return \" @ \" + requirement.url\n\n    requires_dist = []\n    for op, ver in requirement.specs:\n        requires_dist.append(op + ver)\n\n    if requires_dist:\n        return \" (\" + \",\".join(sorted(requires_dist)) + \")\"\n    else:\n        return \"\"\n\n\ndef convert_requirements(requirements: list[str]) -> Iterator[str]:\n    \"\"\"Yield Requires-Dist: strings for parsed requirements strings.\"\"\"\n    for req in requirements:\n        parsed_requirement = Requirement.parse(req)\n        spec = requires_to_requires_dist(parsed_requirement)\n        extras = \",\".join(sorted(parsed_requirement.extras))\n        if extras:\n            extras = f\"[{extras}]\"\n\n        yield parsed_requirement.project_name + extras + spec\n\n\ndef generate_requirements(\n    extras_require: dict[str, list[str]]\n) -> Iterator[tuple[str, str]]:\n    \"\"\"\n    Convert requirements from a setup()-style dictionary to\n    ('Requires-Dist', 'requirement') and ('Provides-Extra', 'extra') tuples.\n\n    extras_require is a dictionary of {extra: [requirements]} as passed to setup(),\n    using the empty extra {'': [requirements]} to hold install_requires.\n    \"\"\"\n    for extra, depends in extras_require.items():\n        condition = \"\"\n        extra = extra or \"\"\n        if \":\" in extra:  # setuptools extra:condition syntax\n            extra, condition = extra.split(\":\", 1)\n\n        extra = safe_extra(extra)\n        if extra:\n            yield \"Provides-Extra\", extra\n            if condition:\n                condition = \"(\" + condition + \") and \"\n            condition += \"extra == '%s'\" % extra\n\n        if condition:\n            condition = \" ; \" + condition\n\n        for new_req in convert_requirements(depends):\n            yield \"Requires-Dist\", new_req + condition\n\n\ndef pkginfo_to_metadata(egg_info_path: str, pkginfo_path: str) -> Message:\n    \"\"\"\n    Convert .egg-info directory with PKG-INFO to the Metadata 2.1 format\n    \"\"\"\n    with open(pkginfo_path, encoding=\"utf-8\") as headers:\n        pkg_info = Parser().parse(headers)\n\n    pkg_info.replace_header(\"Metadata-Version\", \"2.1\")\n    # Those will be regenerated from `requires.txt`.\n    del pkg_info[\"Provides-Extra\"]\n    del pkg_info[\"Requires-Dist\"]\n    requires_path = os.path.join(egg_info_path, \"requires.txt\")\n    if os.path.exists(requires_path):\n        with open(requires_path) as requires_file:\n            requires = requires_file.read()\n\n        parsed_requirements = sorted(split_sections(requires), key=lambda x: x[0] or \"\")\n        for extra, reqs in parsed_requirements:\n            for key, value in generate_requirements({extra: reqs}):\n                if (key, value) not in pkg_info.items():\n                    pkg_info[key] = value\n\n    description = pkg_info[\"Description\"]\n    if description:\n        description_lines = pkg_info[\"Description\"].splitlines()\n        dedented_description = \"\\n\".join(\n            # if the first line of long_description is blank,\n            # the first line here will be indented.\n            (\n                description_lines[0].lstrip(),\n                textwrap.dedent(\"\\n\".join(description_lines[1:])),\n                \"\\n\",\n            )\n        )\n        pkg_info.set_payload(dedented_description)\n        del pkg_info[\"Description\"]\n\n    return pkg_info\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel/util.py",
    "content": "from __future__ import annotations\n\nimport base64\nimport logging\n\nlog = logging.getLogger(\"wheel\")\n\n# ensure Python logging is configured\ntry:\n    __import__(\"setuptools.logging\")\nexcept ImportError:\n    # setuptools < ??\n    from . import _setuptools_logging\n\n    _setuptools_logging.configure()\n\n\ndef urlsafe_b64encode(data: bytes) -> bytes:\n    \"\"\"urlsafe_b64encode without padding\"\"\"\n    return base64.urlsafe_b64encode(data).rstrip(b\"=\")\n\n\ndef urlsafe_b64decode(data: bytes) -> bytes:\n    \"\"\"urlsafe_b64decode without padding\"\"\"\n    pad = b\"=\" * (4 - (len(data) & 3))\n    return base64.urlsafe_b64decode(data + pad)\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel/vendored/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/wheel/vendored/packaging/__init__.py",
    "content": ""
  },
  {
    "path": "lib/python3.7/site-packages/wheel/vendored/packaging/_manylinux.py",
    "content": "from __future__ import annotations\n\nimport collections\nimport functools\nimport os\nimport re\nimport struct\nimport sys\nimport warnings\nfrom typing import IO, Iterator, NamedTuple\n\n\n# Python does not provide platform information at sufficient granularity to\n# identify the architecture of the running executable in some cases, so we\n# determine it dynamically by reading the information from the running\n# process. This only applies on Linux, which uses the ELF format.\nclass _ELFFileHeader:\n    # https://en.wikipedia.org/wiki/Executable_and_Linkable_Format#File_header\n    class _InvalidELFFileHeader(ValueError):\n        \"\"\"\n        An invalid ELF file header was found.\n        \"\"\"\n\n    ELF_MAGIC_NUMBER = 0x7F454C46\n    ELFCLASS32 = 1\n    ELFCLASS64 = 2\n    ELFDATA2LSB = 1\n    ELFDATA2MSB = 2\n    EM_386 = 3\n    EM_S390 = 22\n    EM_ARM = 40\n    EM_X86_64 = 62\n    EF_ARM_ABIMASK = 0xFF000000\n    EF_ARM_ABI_VER5 = 0x05000000\n    EF_ARM_ABI_FLOAT_HARD = 0x00000400\n\n    def __init__(self, file: IO[bytes]) -> None:\n        def unpack(fmt: str) -> int:\n            try:\n                data = file.read(struct.calcsize(fmt))\n                result: tuple[int, ...] = struct.unpack(fmt, data)\n            except struct.error:\n                raise _ELFFileHeader._InvalidELFFileHeader()\n            return result[0]\n\n        self.e_ident_magic = unpack(\">I\")\n        if self.e_ident_magic != self.ELF_MAGIC_NUMBER:\n            raise _ELFFileHeader._InvalidELFFileHeader()\n        self.e_ident_class = unpack(\"B\")\n        if self.e_ident_class not in {self.ELFCLASS32, self.ELFCLASS64}:\n            raise _ELFFileHeader._InvalidELFFileHeader()\n        self.e_ident_data = unpack(\"B\")\n        if self.e_ident_data not in {self.ELFDATA2LSB, self.ELFDATA2MSB}:\n            raise _ELFFileHeader._InvalidELFFileHeader()\n        self.e_ident_version = unpack(\"B\")\n        self.e_ident_osabi = unpack(\"B\")\n        self.e_ident_abiversion = unpack(\"B\")\n        self.e_ident_pad = file.read(7)\n        format_h = \"<H\" if self.e_ident_data == self.ELFDATA2LSB else \">H\"\n        format_i = \"<I\" if self.e_ident_data == self.ELFDATA2LSB else \">I\"\n        format_q = \"<Q\" if self.e_ident_data == self.ELFDATA2LSB else \">Q\"\n        format_p = format_i if self.e_ident_class == self.ELFCLASS32 else format_q\n        self.e_type = unpack(format_h)\n        self.e_machine = unpack(format_h)\n        self.e_version = unpack(format_i)\n        self.e_entry = unpack(format_p)\n        self.e_phoff = unpack(format_p)\n        self.e_shoff = unpack(format_p)\n        self.e_flags = unpack(format_i)\n        self.e_ehsize = unpack(format_h)\n        self.e_phentsize = unpack(format_h)\n        self.e_phnum = unpack(format_h)\n        self.e_shentsize = unpack(format_h)\n        self.e_shnum = unpack(format_h)\n        self.e_shstrndx = unpack(format_h)\n\n\ndef _get_elf_header() -> _ELFFileHeader | None:\n    try:\n        with open(sys.executable, \"rb\") as f:\n            elf_header = _ELFFileHeader(f)\n    except (OSError, TypeError, _ELFFileHeader._InvalidELFFileHeader):\n        return None\n    return elf_header\n\n\ndef _is_linux_armhf() -> bool:\n    # hard-float ABI can be detected from the ELF header of the running\n    # process\n    # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf\n    elf_header = _get_elf_header()\n    if elf_header is None:\n        return False\n    result = elf_header.e_ident_class == elf_header.ELFCLASS32\n    result &= elf_header.e_ident_data == elf_header.ELFDATA2LSB\n    result &= elf_header.e_machine == elf_header.EM_ARM\n    result &= (\n        elf_header.e_flags & elf_header.EF_ARM_ABIMASK\n    ) == elf_header.EF_ARM_ABI_VER5\n    result &= (\n        elf_header.e_flags & elf_header.EF_ARM_ABI_FLOAT_HARD\n    ) == elf_header.EF_ARM_ABI_FLOAT_HARD\n    return result\n\n\ndef _is_linux_i686() -> bool:\n    elf_header = _get_elf_header()\n    if elf_header is None:\n        return False\n    result = elf_header.e_ident_class == elf_header.ELFCLASS32\n    result &= elf_header.e_ident_data == elf_header.ELFDATA2LSB\n    result &= elf_header.e_machine == elf_header.EM_386\n    return result\n\n\ndef _have_compatible_abi(arch: str) -> bool:\n    if arch == \"armv7l\":\n        return _is_linux_armhf()\n    if arch == \"i686\":\n        return _is_linux_i686()\n    return arch in {\"x86_64\", \"aarch64\", \"ppc64\", \"ppc64le\", \"s390x\"}\n\n\n# If glibc ever changes its major version, we need to know what the last\n# minor version was, so we can build the complete list of all versions.\n# For now, guess what the highest minor version might be, assume it will\n# be 50 for testing. Once this actually happens, update the dictionary\n# with the actual value.\n_LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50)\n\n\nclass _GLibCVersion(NamedTuple):\n    major: int\n    minor: int\n\n\ndef _glibc_version_string_confstr() -> str | None:\n    \"\"\"\n    Primary implementation of glibc_version_string using os.confstr.\n    \"\"\"\n    # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely\n    # to be broken or missing. This strategy is used in the standard library\n    # platform module.\n    # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183\n    try:\n        # os.confstr(\"CS_GNU_LIBC_VERSION\") returns a string like \"glibc 2.17\".\n        version_string = os.confstr(\"CS_GNU_LIBC_VERSION\")\n        assert version_string is not None\n        _, version = version_string.split()\n    except (AssertionError, AttributeError, OSError, ValueError):\n        # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...\n        return None\n    return version\n\n\ndef _glibc_version_string_ctypes() -> str | None:\n    \"\"\"\n    Fallback implementation of glibc_version_string using ctypes.\n    \"\"\"\n    try:\n        import ctypes\n    except ImportError:\n        return None\n\n    # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen\n    # manpage says, \"If filename is NULL, then the returned handle is for the\n    # main program\". This way we can let the linker do the work to figure out\n    # which libc our process is actually using.\n    #\n    # We must also handle the special case where the executable is not a\n    # dynamically linked executable. This can occur when using musl libc,\n    # for example. In this situation, dlopen() will error, leading to an\n    # OSError. Interestingly, at least in the case of musl, there is no\n    # errno set on the OSError. The single string argument used to construct\n    # OSError comes from libc itself and is therefore not portable to\n    # hard code here. In any case, failure to call dlopen() means we\n    # can proceed, so we bail on our attempt.\n    try:\n        process_namespace = ctypes.CDLL(None)\n    except OSError:\n        return None\n\n    try:\n        gnu_get_libc_version = process_namespace.gnu_get_libc_version\n    except AttributeError:\n        # Symbol doesn't exist -> therefore, we are not linked to\n        # glibc.\n        return None\n\n    # Call gnu_get_libc_version, which returns a string like \"2.5\"\n    gnu_get_libc_version.restype = ctypes.c_char_p\n    version_str: str = gnu_get_libc_version()\n    # py2 / py3 compatibility:\n    if not isinstance(version_str, str):\n        version_str = version_str.decode(\"ascii\")\n\n    return version_str\n\n\ndef _glibc_version_string() -> str | None:\n    \"\"\"Returns glibc version string, or None if not using glibc.\"\"\"\n    return _glibc_version_string_confstr() or _glibc_version_string_ctypes()\n\n\ndef _parse_glibc_version(version_str: str) -> tuple[int, int]:\n    \"\"\"Parse glibc version.\n\n    We use a regexp instead of str.split because we want to discard any\n    random junk that might come after the minor version -- this might happen\n    in patched/forked versions of glibc (e.g. Linaro's version of glibc\n    uses version strings like \"2.20-2014.11\"). See gh-3588.\n    \"\"\"\n    m = re.match(r\"(?P<major>[0-9]+)\\.(?P<minor>[0-9]+)\", version_str)\n    if not m:\n        warnings.warn(\n            \"Expected glibc version with 2 components major.minor,\"\n            \" got: %s\" % version_str,\n            RuntimeWarning,\n        )\n        return -1, -1\n    return int(m.group(\"major\")), int(m.group(\"minor\"))\n\n\n@functools.lru_cache()\ndef _get_glibc_version() -> tuple[int, int]:\n    version_str = _glibc_version_string()\n    if version_str is None:\n        return (-1, -1)\n    return _parse_glibc_version(version_str)\n\n\n# From PEP 513, PEP 600\ndef _is_compatible(name: str, arch: str, version: _GLibCVersion) -> bool:\n    sys_glibc = _get_glibc_version()\n    if sys_glibc < version:\n        return False\n    # Check for presence of _manylinux module.\n    try:\n        import _manylinux  # noqa\n    except ImportError:\n        return True\n    if hasattr(_manylinux, \"manylinux_compatible\"):\n        result = _manylinux.manylinux_compatible(version[0], version[1], arch)\n        if result is not None:\n            return bool(result)\n        return True\n    if version == _GLibCVersion(2, 5):\n        if hasattr(_manylinux, \"manylinux1_compatible\"):\n            return bool(_manylinux.manylinux1_compatible)\n    if version == _GLibCVersion(2, 12):\n        if hasattr(_manylinux, \"manylinux2010_compatible\"):\n            return bool(_manylinux.manylinux2010_compatible)\n    if version == _GLibCVersion(2, 17):\n        if hasattr(_manylinux, \"manylinux2014_compatible\"):\n            return bool(_manylinux.manylinux2014_compatible)\n    return True\n\n\n_LEGACY_MANYLINUX_MAP = {\n    # CentOS 7 w/ glibc 2.17 (PEP 599)\n    (2, 17): \"manylinux2014\",\n    # CentOS 6 w/ glibc 2.12 (PEP 571)\n    (2, 12): \"manylinux2010\",\n    # CentOS 5 w/ glibc 2.5 (PEP 513)\n    (2, 5): \"manylinux1\",\n}\n\n\ndef platform_tags(linux: str, arch: str) -> Iterator[str]:\n    if not _have_compatible_abi(arch):\n        return\n    # Oldest glibc to be supported regardless of architecture is (2, 17).\n    too_old_glibc2 = _GLibCVersion(2, 16)\n    if arch in {\"x86_64\", \"i686\"}:\n        # On x86/i686 also oldest glibc to be supported is (2, 5).\n        too_old_glibc2 = _GLibCVersion(2, 4)\n    current_glibc = _GLibCVersion(*_get_glibc_version())\n    glibc_max_list = [current_glibc]\n    # We can assume compatibility across glibc major versions.\n    # https://sourceware.org/bugzilla/show_bug.cgi?id=24636\n    #\n    # Build a list of maximum glibc versions so that we can\n    # output the canonical list of all glibc from current_glibc\n    # down to too_old_glibc2, including all intermediary versions.\n    for glibc_major in range(current_glibc.major - 1, 1, -1):\n        glibc_minor = _LAST_GLIBC_MINOR[glibc_major]\n        glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))\n    for glibc_max in glibc_max_list:\n        if glibc_max.major == too_old_glibc2.major:\n            min_minor = too_old_glibc2.minor\n        else:\n            # For other glibc major versions oldest supported is (x, 0).\n            min_minor = -1\n        for glibc_minor in range(glibc_max.minor, min_minor, -1):\n            glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)\n            tag = \"manylinux_{}_{}\".format(*glibc_version)\n            if _is_compatible(tag, arch, glibc_version):\n                yield linux.replace(\"linux\", tag)\n            # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.\n            if glibc_version in _LEGACY_MANYLINUX_MAP:\n                legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version]\n                if _is_compatible(legacy_tag, arch, glibc_version):\n                    yield linux.replace(\"linux\", legacy_tag)\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel/vendored/packaging/_musllinux.py",
    "content": "\"\"\"PEP 656 support.\n\nThis module implements logic to detect if the currently running Python is\nlinked against musl, and what musl version is used.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nimport functools\nimport operator\nimport os\nimport re\nimport struct\nimport subprocess\nimport sys\nfrom typing import IO, Iterator, NamedTuple\n\n\ndef _read_unpacked(f: IO[bytes], fmt: str) -> tuple[int, ...]:\n    return struct.unpack(fmt, f.read(struct.calcsize(fmt)))\n\n\ndef _parse_ld_musl_from_elf(f: IO[bytes]) -> str | None:\n    \"\"\"Detect musl libc location by parsing the Python executable.\n\n    Based on: https://gist.github.com/lyssdod/f51579ae8d93c8657a5564aefc2ffbca\n    ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html\n    \"\"\"\n    f.seek(0)\n    try:\n        ident = _read_unpacked(f, \"16B\")\n    except struct.error:\n        return None\n    if ident[:4] != tuple(b\"\\x7fELF\"):  # Invalid magic, not ELF.\n        return None\n    f.seek(struct.calcsize(\"HHI\"), 1)  # Skip file type, machine, and version.\n\n    try:\n        # e_fmt: Format for program header.\n        # p_fmt: Format for section header.\n        # p_idx: Indexes to find p_type, p_offset, and p_filesz.\n        e_fmt, p_fmt, p_idx = {\n            1: (\"IIIIHHH\", \"IIIIIIII\", (0, 1, 4)),  # 32-bit.\n            2: (\"QQQIHHH\", \"IIQQQQQQ\", (0, 2, 5)),  # 64-bit.\n        }[ident[4]]\n    except KeyError:\n        return None\n    else:\n        p_get = operator.itemgetter(*p_idx)\n\n    # Find the interpreter section and return its content.\n    try:\n        _, e_phoff, _, _, _, e_phentsize, e_phnum = _read_unpacked(f, e_fmt)\n    except struct.error:\n        return None\n    for i in range(e_phnum + 1):\n        f.seek(e_phoff + e_phentsize * i)\n        try:\n            p_type, p_offset, p_filesz = p_get(_read_unpacked(f, p_fmt))\n        except struct.error:\n            return None\n        if p_type != 3:  # Not PT_INTERP.\n            continue\n        f.seek(p_offset)\n        interpreter = os.fsdecode(f.read(p_filesz)).strip(\"\\0\")\n        if \"musl\" not in interpreter:\n            return None\n        return interpreter\n    return None\n\n\nclass _MuslVersion(NamedTuple):\n    major: int\n    minor: int\n\n\ndef _parse_musl_version(output: str) -> _MuslVersion | None:\n    lines = [n for n in (n.strip() for n in output.splitlines()) if n]\n    if len(lines) < 2 or lines[0][:4] != \"musl\":\n        return None\n    m = re.match(r\"Version (\\d+)\\.(\\d+)\", lines[1])\n    if not m:\n        return None\n    return _MuslVersion(major=int(m.group(1)), minor=int(m.group(2)))\n\n\n@functools.lru_cache()\ndef _get_musl_version(executable: str) -> _MuslVersion | None:\n    \"\"\"Detect currently-running musl runtime version.\n\n    This is done by checking the specified executable's dynamic linking\n    information, and invoking the loader to parse its output for a version\n    string. If the loader is musl, the output would be something like::\n\n        musl libc (x86_64)\n        Version 1.2.2\n        Dynamic Program Loader\n    \"\"\"\n    with contextlib.ExitStack() as stack:\n        try:\n            f = stack.enter_context(open(executable, \"rb\"))\n        except OSError:\n            return None\n        ld = _parse_ld_musl_from_elf(f)\n    if not ld:\n        return None\n    proc = subprocess.run([ld], stderr=subprocess.PIPE, text=True)\n    return _parse_musl_version(proc.stderr)\n\n\ndef platform_tags(arch: str) -> Iterator[str]:\n    \"\"\"Generate musllinux tags compatible to the current platform.\n\n    :param arch: Should be the part of platform tag after the ``linux_``\n        prefix, e.g. ``x86_64``. The ``linux_`` prefix is assumed as a\n        prerequisite for the current platform to be musllinux-compatible.\n\n    :returns: An iterator of compatible musllinux tags.\n    \"\"\"\n    sys_musl = _get_musl_version(sys.executable)\n    if sys_musl is None:  # Python not dynamically linked against musl.\n        return\n    for minor in range(sys_musl.minor, -1, -1):\n        yield f\"musllinux_{sys_musl.major}_{minor}_{arch}\"\n\n\nif __name__ == \"__main__\":  # pragma: no cover\n    import sysconfig\n\n    plat = sysconfig.get_platform()\n    assert plat.startswith(\"linux-\"), \"not linux\"\n\n    print(\"plat:\", plat)\n    print(\"musl:\", _get_musl_version(sys.executable))\n    print(\"tags:\", end=\" \")\n    for t in platform_tags(re.sub(r\"[.-]\", \"_\", plat.split(\"-\", 1)[-1])):\n        print(t, end=\"\\n      \")\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel/vendored/packaging/tags.py",
    "content": "# This file is dual licensed under the terms of the Apache License, Version\n# 2.0, and the BSD License. See the LICENSE file in the root of this repository\n# for complete details.\n\nfrom __future__ import annotations\n\nimport logging\nimport platform\nimport sys\nimport sysconfig\nfrom importlib.machinery import EXTENSION_SUFFIXES\nfrom typing import Iterable, Iterator, Sequence, Tuple, cast\n\nfrom . import _manylinux, _musllinux\n\nlogger = logging.getLogger(__name__)\n\nPythonVersion = Sequence[int]\nMacVersion = Tuple[int, int]\n\nINTERPRETER_SHORT_NAMES: dict[str, str] = {\n    \"python\": \"py\",  # Generic.\n    \"cpython\": \"cp\",\n    \"pypy\": \"pp\",\n    \"ironpython\": \"ip\",\n    \"jython\": \"jy\",\n}\n\n\n_32_BIT_INTERPRETER = sys.maxsize <= 2 ** 32\n\n\nclass Tag:\n    \"\"\"\n    A representation of the tag triple for a wheel.\n\n    Instances are considered immutable and thus are hashable. Equality checking\n    is also supported.\n    \"\"\"\n\n    __slots__ = [\"_interpreter\", \"_abi\", \"_platform\", \"_hash\"]\n\n    def __init__(self, interpreter: str, abi: str, platform: str) -> None:\n        self._interpreter = interpreter.lower()\n        self._abi = abi.lower()\n        self._platform = platform.lower()\n        # The __hash__ of every single element in a Set[Tag] will be evaluated each time\n        # that a set calls its `.disjoint()` method, which may be called hundreds of\n        # times when scanning a page of links for packages with tags matching that\n        # Set[Tag]. Pre-computing the value here produces significant speedups for\n        # downstream consumers.\n        self._hash = hash((self._interpreter, self._abi, self._platform))\n\n    @property\n    def interpreter(self) -> str:\n        return self._interpreter\n\n    @property\n    def abi(self) -> str:\n        return self._abi\n\n    @property\n    def platform(self) -> str:\n        return self._platform\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Tag):\n            return NotImplemented\n\n        return (\n            (self._hash == other._hash)  # Short-circuit ASAP for perf reasons.\n            and (self._platform == other._platform)\n            and (self._abi == other._abi)\n            and (self._interpreter == other._interpreter)\n        )\n\n    def __hash__(self) -> int:\n        return self._hash\n\n    def __str__(self) -> str:\n        return f\"{self._interpreter}-{self._abi}-{self._platform}\"\n\n    def __repr__(self) -> str:\n        return f\"<{self} @ {id(self)}>\"\n\n\ndef parse_tag(tag: str) -> frozenset[Tag]:\n    \"\"\"\n    Parses the provided tag (e.g. `py3-none-any`) into a frozenset of Tag instances.\n\n    Returning a set is required due to the possibility that the tag is a\n    compressed tag set.\n    \"\"\"\n    tags = set()\n    interpreters, abis, platforms = tag.split(\"-\")\n    for interpreter in interpreters.split(\".\"):\n        for abi in abis.split(\".\"):\n            for platform_ in platforms.split(\".\"):\n                tags.add(Tag(interpreter, abi, platform_))\n    return frozenset(tags)\n\n\ndef _get_config_var(name: str, warn: bool = False) -> int | str | None:\n    value = sysconfig.get_config_var(name)\n    if value is None and warn:\n        logger.debug(\n            \"Config variable '%s' is unset, Python ABI tag may be incorrect\", name\n        )\n    return value\n\n\ndef _normalize_string(string: str) -> str:\n    return string.replace(\".\", \"_\").replace(\"-\", \"_\")\n\n\ndef _abi3_applies(python_version: PythonVersion) -> bool:\n    \"\"\"\n    Determine if the Python version supports abi3.\n\n    PEP 384 was first implemented in Python 3.2.\n    \"\"\"\n    return len(python_version) > 1 and tuple(python_version) >= (3, 2)\n\n\ndef _cpython_abis(py_version: PythonVersion, warn: bool = False) -> list[str]:\n    py_version = tuple(py_version)  # To allow for version comparison.\n    abis = []\n    version = _version_nodot(py_version[:2])\n    debug = pymalloc = ucs4 = \"\"\n    with_debug = _get_config_var(\"Py_DEBUG\", warn)\n    has_refcount = hasattr(sys, \"gettotalrefcount\")\n    # Windows doesn't set Py_DEBUG, so checking for support of debug-compiled\n    # extension modules is the best option.\n    # https://github.com/pypa/pip/issues/3383#issuecomment-173267692\n    has_ext = \"_d.pyd\" in EXTENSION_SUFFIXES\n    if with_debug or (with_debug is None and (has_refcount or has_ext)):\n        debug = \"d\"\n    if py_version < (3, 8):\n        with_pymalloc = _get_config_var(\"WITH_PYMALLOC\", warn)\n        if with_pymalloc or with_pymalloc is None:\n            pymalloc = \"m\"\n        if py_version < (3, 3):\n            unicode_size = _get_config_var(\"Py_UNICODE_SIZE\", warn)\n            if unicode_size == 4 or (\n                unicode_size is None and sys.maxunicode == 0x10FFFF\n            ):\n                ucs4 = \"u\"\n    elif debug:\n        # Debug builds can also load \"normal\" extension modules.\n        # We can also assume no UCS-4 or pymalloc requirement.\n        abis.append(f\"cp{version}\")\n    abis.insert(\n        0,\n        \"cp{version}{debug}{pymalloc}{ucs4}\".format(\n            version=version, debug=debug, pymalloc=pymalloc, ucs4=ucs4\n        ),\n    )\n    return abis\n\n\ndef cpython_tags(\n    python_version: PythonVersion | None = None,\n    abis: Iterable[str] | None = None,\n    platforms: Iterable[str] | None = None,\n    *,\n    warn: bool = False,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the tags for a CPython interpreter.\n\n    The tags consist of:\n    - cp<python_version>-<abi>-<platform>\n    - cp<python_version>-abi3-<platform>\n    - cp<python_version>-none-<platform>\n    - cp<less than python_version>-abi3-<platform>  # Older Python versions down to 3.2.\n\n    If python_version only specifies a major version then user-provided ABIs and\n    the 'none' ABItag will be used.\n\n    If 'abi3' or 'none' are specified in 'abis' then they will be yielded at\n    their normal position and not at the beginning.\n    \"\"\"\n    if not python_version:\n        python_version = sys.version_info[:2]\n\n    interpreter = f\"cp{_version_nodot(python_version[:2])}\"\n\n    if abis is None:\n        if len(python_version) > 1:\n            abis = _cpython_abis(python_version, warn)\n        else:\n            abis = []\n    abis = list(abis)\n    # 'abi3' and 'none' are explicitly handled later.\n    for explicit_abi in (\"abi3\", \"none\"):\n        try:\n            abis.remove(explicit_abi)\n        except ValueError:\n            pass\n\n    platforms = list(platforms or platform_tags())\n    for abi in abis:\n        for platform_ in platforms:\n            yield Tag(interpreter, abi, platform_)\n    if _abi3_applies(python_version):\n        yield from (Tag(interpreter, \"abi3\", platform_) for platform_ in platforms)\n    yield from (Tag(interpreter, \"none\", platform_) for platform_ in platforms)\n\n    if _abi3_applies(python_version):\n        for minor_version in range(python_version[1] - 1, 1, -1):\n            for platform_ in platforms:\n                interpreter = \"cp{version}\".format(\n                    version=_version_nodot((python_version[0], minor_version))\n                )\n                yield Tag(interpreter, \"abi3\", platform_)\n\n\ndef _generic_abi() -> Iterator[str]:\n    abi = sysconfig.get_config_var(\"SOABI\")\n    if abi:\n        yield _normalize_string(abi)\n\n\ndef generic_tags(\n    interpreter: str | None = None,\n    abis: Iterable[str] | None = None,\n    platforms: Iterable[str] | None = None,\n    *,\n    warn: bool = False,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the tags for a generic interpreter.\n\n    The tags consist of:\n    - <interpreter>-<abi>-<platform>\n\n    The \"none\" ABI will be added if it was not explicitly provided.\n    \"\"\"\n    if not interpreter:\n        interp_name = interpreter_name()\n        interp_version = interpreter_version(warn=warn)\n        interpreter = \"\".join([interp_name, interp_version])\n    if abis is None:\n        abis = _generic_abi()\n    platforms = list(platforms or platform_tags())\n    abis = list(abis)\n    if \"none\" not in abis:\n        abis.append(\"none\")\n    for abi in abis:\n        for platform_ in platforms:\n            yield Tag(interpreter, abi, platform_)\n\n\ndef _py_interpreter_range(py_version: PythonVersion) -> Iterator[str]:\n    \"\"\"\n    Yields Python versions in descending order.\n\n    After the latest version, the major-only version will be yielded, and then\n    all previous versions of that major version.\n    \"\"\"\n    if len(py_version) > 1:\n        yield f\"py{_version_nodot(py_version[:2])}\"\n    yield f\"py{py_version[0]}\"\n    if len(py_version) > 1:\n        for minor in range(py_version[1] - 1, -1, -1):\n            yield f\"py{_version_nodot((py_version[0], minor))}\"\n\n\ndef compatible_tags(\n    python_version: PythonVersion | None = None,\n    interpreter: str | None = None,\n    platforms: Iterable[str] | None = None,\n) -> Iterator[Tag]:\n    \"\"\"\n    Yields the sequence of tags that are compatible with a specific version of Python.\n\n    The tags consist of:\n    - py*-none-<platform>\n    - <interpreter>-none-any  # ... if `interpreter` is provided.\n    - py*-none-any\n    \"\"\"\n    if not python_version:\n        python_version = sys.version_info[:2]\n    platforms = list(platforms or platform_tags())\n    for version in _py_interpreter_range(python_version):\n        for platform_ in platforms:\n            yield Tag(version, \"none\", platform_)\n    if interpreter:\n        yield Tag(interpreter, \"none\", \"any\")\n    for version in _py_interpreter_range(python_version):\n        yield Tag(version, \"none\", \"any\")\n\n\ndef _mac_arch(arch: str, is_32bit: bool = _32_BIT_INTERPRETER) -> str:\n    if not is_32bit:\n        return arch\n\n    if arch.startswith(\"ppc\"):\n        return \"ppc\"\n\n    return \"i386\"\n\n\ndef _mac_binary_formats(version: MacVersion, cpu_arch: str) -> list[str]:\n    formats = [cpu_arch]\n    if cpu_arch == \"x86_64\":\n        if version < (10, 4):\n            return []\n        formats.extend([\"intel\", \"fat64\", \"fat32\"])\n\n    elif cpu_arch == \"i386\":\n        if version < (10, 4):\n            return []\n        formats.extend([\"intel\", \"fat32\", \"fat\"])\n\n    elif cpu_arch == \"ppc64\":\n        # TODO: Need to care about 32-bit PPC for ppc64 through 10.2?\n        if version > (10, 5) or version < (10, 4):\n            return []\n        formats.append(\"fat64\")\n\n    elif cpu_arch == \"ppc\":\n        if version > (10, 6):\n            return []\n        formats.extend([\"fat32\", \"fat\"])\n\n    if cpu_arch in {\"arm64\", \"x86_64\"}:\n        formats.append(\"universal2\")\n\n    if cpu_arch in {\"x86_64\", \"i386\", \"ppc64\", \"ppc\", \"intel\"}:\n        formats.append(\"universal\")\n\n    return formats\n\n\ndef mac_platforms(\n    version: MacVersion | None = None, arch: str | None = None\n) -> Iterator[str]:\n    \"\"\"\n    Yields the platform tags for a macOS system.\n\n    The `version` parameter is a two-item tuple specifying the macOS version to\n    generate platform tags for. The `arch` parameter is the CPU architecture to\n    generate platform tags for. Both parameters default to the appropriate value\n    for the current system.\n    \"\"\"\n    version_str, _, cpu_arch = platform.mac_ver()\n    if version is None:\n        version = cast(\"MacVersion\", tuple(map(int, version_str.split(\".\")[:2])))\n    else:\n        version = version\n    if arch is None:\n        arch = _mac_arch(cpu_arch)\n    else:\n        arch = arch\n\n    if (10, 0) <= version and version < (11, 0):\n        # Prior to Mac OS 11, each yearly release of Mac OS bumped the\n        # \"minor\" version number.  The major version was always 10.\n        for minor_version in range(version[1], -1, -1):\n            compat_version = 10, minor_version\n            binary_formats = _mac_binary_formats(compat_version, arch)\n            for binary_format in binary_formats:\n                yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                    major=10, minor=minor_version, binary_format=binary_format\n                )\n\n    if version >= (11, 0):\n        # Starting with Mac OS 11, each yearly release bumps the major version\n        # number.   The minor versions are now the midyear updates.\n        for major_version in range(version[0], 10, -1):\n            compat_version = major_version, 0\n            binary_formats = _mac_binary_formats(compat_version, arch)\n            for binary_format in binary_formats:\n                yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                    major=major_version, minor=0, binary_format=binary_format\n                )\n\n    if version >= (11, 0):\n        # Mac OS 11 on x86_64 is compatible with binaries from previous releases.\n        # Arm64 support was introduced in 11.0, so no Arm binaries from previous\n        # releases exist.\n        #\n        # However, the \"universal2\" binary format can have a\n        # macOS version earlier than 11.0 when the x86_64 part of the binary supports\n        # that version of macOS.\n        if arch == \"x86_64\":\n            for minor_version in range(16, 3, -1):\n                compat_version = 10, minor_version\n                binary_formats = _mac_binary_formats(compat_version, arch)\n                for binary_format in binary_formats:\n                    yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                        major=compat_version[0],\n                        minor=compat_version[1],\n                        binary_format=binary_format,\n                    )\n        else:\n            for minor_version in range(16, 3, -1):\n                compat_version = 10, minor_version\n                binary_format = \"universal2\"\n                yield \"macosx_{major}_{minor}_{binary_format}\".format(\n                    major=compat_version[0],\n                    minor=compat_version[1],\n                    binary_format=binary_format,\n                )\n\n\ndef _linux_platforms(is_32bit: bool = _32_BIT_INTERPRETER) -> Iterator[str]:\n    linux = _normalize_string(sysconfig.get_platform())\n    if is_32bit:\n        if linux == \"linux_x86_64\":\n            linux = \"linux_i686\"\n        elif linux == \"linux_aarch64\":\n            linux = \"linux_armv7l\"\n    _, arch = linux.split(\"_\", 1)\n    yield from _manylinux.platform_tags(linux, arch)\n    yield from _musllinux.platform_tags(arch)\n    yield linux\n\n\ndef _generic_platforms() -> Iterator[str]:\n    yield _normalize_string(sysconfig.get_platform())\n\n\ndef platform_tags() -> Iterator[str]:\n    \"\"\"\n    Provides the platform tags for this installation.\n    \"\"\"\n    if platform.system() == \"Darwin\":\n        return mac_platforms()\n    elif platform.system() == \"Linux\":\n        return _linux_platforms()\n    else:\n        return _generic_platforms()\n\n\ndef interpreter_name() -> str:\n    \"\"\"\n    Returns the name of the running interpreter.\n    \"\"\"\n    name = sys.implementation.name\n    return INTERPRETER_SHORT_NAMES.get(name) or name\n\n\ndef interpreter_version(*, warn: bool = False) -> str:\n    \"\"\"\n    Returns the version of the running interpreter.\n    \"\"\"\n    version = _get_config_var(\"py_version_nodot\", warn=warn)\n    if version:\n        version = str(version)\n    else:\n        version = _version_nodot(sys.version_info[:2])\n    return version\n\n\ndef _version_nodot(version: PythonVersion) -> str:\n    return \"\".join(map(str, version))\n\n\ndef sys_tags(*, warn: bool = False) -> Iterator[Tag]:\n    \"\"\"\n    Returns the sequence of tag triples for the running interpreter.\n\n    The order of the sequence corresponds to priority order for the\n    interpreter, from most to least important.\n    \"\"\"\n\n    interp_name = interpreter_name()\n    if interp_name == \"cp\":\n        yield from cpython_tags(warn=warn)\n    else:\n        yield from generic_tags()\n\n    if interp_name == \"pp\":\n        yield from compatible_tags(interpreter=\"pp3\")\n    else:\n        yield from compatible_tags()\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel/wheelfile.py",
    "content": "from __future__ import annotations\n\nimport csv\nimport hashlib\nimport os.path\nimport re\nimport stat\nimport time\nfrom collections import OrderedDict\nfrom io import StringIO, TextIOWrapper\nfrom zipfile import ZIP_DEFLATED, ZipFile, ZipInfo\n\nfrom wheel.cli import WheelError\nfrom wheel.util import log, urlsafe_b64decode, urlsafe_b64encode\n\n# Non-greedy matching of an optional build number may be too clever (more\n# invalid wheel filenames will match). Separate regex for .dist-info?\nWHEEL_INFO_RE = re.compile(\n    r\"\"\"^(?P<namever>(?P<name>[^\\s-]+?)-(?P<ver>[^\\s-]+?))(-(?P<build>\\d[^\\s-]*))?\n     -(?P<pyver>[^\\s-]+?)-(?P<abi>[^\\s-]+?)-(?P<plat>\\S+)\\.whl$\"\"\",\n    re.VERBOSE,\n)\nMINIMUM_TIMESTAMP = 315532800  # 1980-01-01 00:00:00 UTC\n\n\ndef get_zipinfo_datetime(timestamp=None):\n    # Some applications need reproducible .whl files, but they can't do this without\n    # forcing the timestamp of the individual ZipInfo objects. See issue #143.\n    timestamp = int(os.environ.get(\"SOURCE_DATE_EPOCH\", timestamp or time.time()))\n    timestamp = max(timestamp, MINIMUM_TIMESTAMP)\n    return time.gmtime(timestamp)[0:6]\n\n\nclass WheelFile(ZipFile):\n    \"\"\"A ZipFile derivative class that also reads SHA-256 hashes from\n    .dist-info/RECORD and checks any read files against those.\n    \"\"\"\n\n    _default_algorithm = hashlib.sha256\n\n    def __init__(self, file, mode=\"r\", compression=ZIP_DEFLATED):\n        basename = os.path.basename(file)\n        self.parsed_filename = WHEEL_INFO_RE.match(basename)\n        if not basename.endswith(\".whl\") or self.parsed_filename is None:\n            raise WheelError(f\"Bad wheel filename {basename!r}\")\n\n        ZipFile.__init__(self, file, mode, compression=compression, allowZip64=True)\n\n        self.dist_info_path = \"{}.dist-info\".format(\n            self.parsed_filename.group(\"namever\")\n        )\n        self.record_path = self.dist_info_path + \"/RECORD\"\n        self._file_hashes = OrderedDict()\n        self._file_sizes = {}\n        if mode == \"r\":\n            # Ignore RECORD and any embedded wheel signatures\n            self._file_hashes[self.record_path] = None, None\n            self._file_hashes[self.record_path + \".jws\"] = None, None\n            self._file_hashes[self.record_path + \".p7s\"] = None, None\n\n            # Fill in the expected hashes by reading them from RECORD\n            try:\n                record = self.open(self.record_path)\n            except KeyError:\n                raise WheelError(f\"Missing {self.record_path} file\")\n\n            with record:\n                for line in csv.reader(\n                    TextIOWrapper(record, newline=\"\", encoding=\"utf-8\")\n                ):\n                    path, hash_sum, size = line\n                    if not hash_sum:\n                        continue\n\n                    algorithm, hash_sum = hash_sum.split(\"=\")\n                    try:\n                        hashlib.new(algorithm)\n                    except ValueError:\n                        raise WheelError(f\"Unsupported hash algorithm: {algorithm}\")\n\n                    if algorithm.lower() in {\"md5\", \"sha1\"}:\n                        raise WheelError(\n                            \"Weak hash algorithm ({}) is not permitted by PEP \"\n                            \"427\".format(algorithm)\n                        )\n\n                    self._file_hashes[path] = (\n                        algorithm,\n                        urlsafe_b64decode(hash_sum.encode(\"ascii\")),\n                    )\n\n    def open(self, name_or_info, mode=\"r\", pwd=None):\n        def _update_crc(newdata):\n            eof = ef._eof\n            update_crc_orig(newdata)\n            running_hash.update(newdata)\n            if eof and running_hash.digest() != expected_hash:\n                raise WheelError(f\"Hash mismatch for file '{ef_name}'\")\n\n        ef_name = (\n            name_or_info.filename if isinstance(name_or_info, ZipInfo) else name_or_info\n        )\n        if (\n            mode == \"r\"\n            and not ef_name.endswith(\"/\")\n            and ef_name not in self._file_hashes\n        ):\n            raise WheelError(f\"No hash found for file '{ef_name}'\")\n\n        ef = ZipFile.open(self, name_or_info, mode, pwd)\n        if mode == \"r\" and not ef_name.endswith(\"/\"):\n            algorithm, expected_hash = self._file_hashes[ef_name]\n            if expected_hash is not None:\n                # Monkey patch the _update_crc method to also check for the hash from\n                # RECORD\n                running_hash = hashlib.new(algorithm)\n                update_crc_orig, ef._update_crc = ef._update_crc, _update_crc\n\n        return ef\n\n    def write_files(self, base_dir):\n        log.info(f\"creating '{self.filename}' and adding '{base_dir}' to it\")\n        deferred = []\n        for root, dirnames, filenames in os.walk(base_dir):\n            # Sort the directory names so that `os.walk` will walk them in a\n            # defined order on the next iteration.\n            dirnames.sort()\n            for name in sorted(filenames):\n                path = os.path.normpath(os.path.join(root, name))\n                if os.path.isfile(path):\n                    arcname = os.path.relpath(path, base_dir).replace(os.path.sep, \"/\")\n                    if arcname == self.record_path:\n                        pass\n                    elif root.endswith(\".dist-info\"):\n                        deferred.append((path, arcname))\n                    else:\n                        self.write(path, arcname)\n\n        deferred.sort()\n        for path, arcname in deferred:\n            self.write(path, arcname)\n\n    def write(self, filename, arcname=None, compress_type=None):\n        with open(filename, \"rb\") as f:\n            st = os.fstat(f.fileno())\n            data = f.read()\n\n        zinfo = ZipInfo(\n            arcname or filename, date_time=get_zipinfo_datetime(st.st_mtime)\n        )\n        zinfo.external_attr = (stat.S_IMODE(st.st_mode) | stat.S_IFMT(st.st_mode)) << 16\n        zinfo.compress_type = compress_type or self.compression\n        self.writestr(zinfo, data, compress_type)\n\n    def writestr(self, zinfo_or_arcname, data, compress_type=None):\n        if isinstance(data, str):\n            data = data.encode(\"utf-8\")\n\n        ZipFile.writestr(self, zinfo_or_arcname, data, compress_type)\n        fname = (\n            zinfo_or_arcname.filename\n            if isinstance(zinfo_or_arcname, ZipInfo)\n            else zinfo_or_arcname\n        )\n        log.info(f\"adding '{fname}'\")\n        if fname != self.record_path:\n            hash_ = self._default_algorithm(data)\n            self._file_hashes[fname] = (\n                hash_.name,\n                urlsafe_b64encode(hash_.digest()).decode(\"ascii\"),\n            )\n            self._file_sizes[fname] = len(data)\n\n    def close(self):\n        # Write RECORD\n        if self.fp is not None and self.mode == \"w\" and self._file_hashes:\n            data = StringIO()\n            writer = csv.writer(data, delimiter=\",\", quotechar='\"', lineterminator=\"\\n\")\n            writer.writerows(\n                (\n                    (fname, algorithm + \"=\" + hash_, self._file_sizes[fname])\n                    for fname, (algorithm, hash_) in self._file_hashes.items()\n                )\n            )\n            writer.writerow((format(self.record_path), \"\", \"\"))\n            zinfo = ZipInfo(self.record_path, date_time=get_zipinfo_datetime())\n            zinfo.compress_type = self.compression\n            zinfo.external_attr = 0o664 << 16\n            self.writestr(zinfo, data.getvalue())\n\n        ZipFile.close(self)\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel-0.38.4.dist-info/INSTALLER",
    "content": "pip\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel-0.38.4.dist-info/LICENSE.txt",
    "content": "MIT License\n\nCopyright (c) 2012 Daniel Holth <dholth@fastmail.fm> and contributors\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\nOTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\nARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel-0.38.4.dist-info/METADATA",
    "content": "Metadata-Version: 2.1\nName: wheel\nVersion: 0.38.4\nSummary: A built-package format for Python\nHome-page: https://github.com/pypa/wheel\nAuthor: Daniel Holth\nAuthor-email: dholth@fastmail.fm\nMaintainer: Alex Grönholm\nMaintainer-email: alex.gronholm@nextday.fi\nLicense: MIT\nProject-URL: Documentation, https://wheel.readthedocs.io/\nProject-URL: Changelog, https://wheel.readthedocs.io/en/stable/news.html\nProject-URL: Issue Tracker, https://github.com/pypa/wheel/issues\nKeywords: wheel,packaging\nClassifier: Development Status :: 5 - Production/Stable\nClassifier: Intended Audience :: Developers\nClassifier: Topic :: System :: Archiving :: Packaging\nClassifier: License :: OSI Approved :: MIT License\nClassifier: Programming Language :: Python\nClassifier: Programming Language :: Python :: 3 :: Only\nClassifier: Programming Language :: Python :: 3.7\nClassifier: Programming Language :: Python :: 3.8\nClassifier: Programming Language :: Python :: 3.9\nClassifier: Programming Language :: Python :: 3.10\nClassifier: Programming Language :: Python :: 3.11\nRequires-Python: >=3.7\nLicense-File: LICENSE.txt\nProvides-Extra: test\nRequires-Dist: pytest (>=3.0.0) ; extra == 'test'\n\nwheel\n=====\n\nThis library is the reference implementation of the Python wheel packaging\nstandard, as defined in `PEP 427`_.\n\nIt has two different roles:\n\n#. A setuptools_ extension for building wheels that provides the\n   ``bdist_wheel`` setuptools command\n#. A command line tool for working with wheel files\n\nIt should be noted that wheel is **not** intended to be used as a library, and\nas such there is no stable, public API.\n\n.. _PEP 427: https://www.python.org/dev/peps/pep-0427/\n.. _setuptools: https://pypi.org/project/setuptools/\n\nDocumentation\n-------------\n\nThe documentation_ can be found on Read The Docs.\n\n.. _documentation: https://wheel.readthedocs.io/\n\nCode of Conduct\n---------------\n\nEveryone interacting in the wheel project's codebases, issue trackers, chat\nrooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.\n\n.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel-0.38.4.dist-info/RECORD",
    "content": "wheel/__init__.py,sha256=2wJrg-twJVHIbVXveZjxyMtxjelZOVff9bnhTBt3eec,59\nwheel/__main__.py,sha256=NkMUnuTCGcOkgY0IBLgBCVC_BGGcWORx2K8jYGS12UE,455\nwheel/_setuptools_logging.py,sha256=NoCnjJ4DFEZ45Eo-2BdXLsWJCwGkait1tp_17paleVw,746\nwheel/bdist_wheel.py,sha256=k_gee2yY4TfDr_dRODcyCso6ItpidTLj6JZfbvZ93qk,19293\nwheel/macosx_libfile.py,sha256=OXM6OTx1O_ACLGBE2Q9prIHj47uWkZSZSuM_756W89Q,16145\nwheel/metadata.py,sha256=-6n1-hH8YtmUV8zsrRf206iXPJJWyE9tqlqZv5XGpSg,3727\nwheel/util.py,sha256=e0jpnsbbM9QhaaMSyap-_ZgUxcxwpyLDk6RHcrduPLg,621\nwheel/wheelfile.py,sha256=9iWWOWcvVXSx26YdfK9QptRA1OHeRRjqEo7PEb631mI,7536\nwheel/cli/__init__.py,sha256=NVh8x79QGybwZpL5VMQgQv-zwSg_6uKsYVXbIVRkpQ4,2384\nwheel/cli/convert.py,sha256=skUf4TuZcksqG75J-_KUkFXdmYDxTJpP311O16cNJ50,9427\nwheel/cli/pack.py,sha256=zQ1zmJouN8Y86hCJ3lTaKh6g7SbqgA2MuKP1wY-vjfw,3383\nwheel/cli/unpack.py,sha256=QU_OVMCvYWtrjQa18Z5ZKaZwGBImAqJIzQokYt2u3bI,659\nwheel/vendored/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nwheel/vendored/packaging/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nwheel/vendored/packaging/_manylinux.py,sha256=1OWKAD6xtgTgOGVEhujFWqF35JWqMvQLxZEZ2QlHI9g,11489\nwheel/vendored/packaging/_musllinux.py,sha256=k9vZj4tmx0ElF-2y8h7gbz09zCfhEjZ9ZQbeZr5sVds,4374\nwheel/vendored/packaging/tags.py,sha256=M_DQI4zGnPq3hsRV9QWYf5SoMJmBB91gqqG9Jtyv-m8,15612\nwheel-0.38.4.dist-info/LICENSE.txt,sha256=MMI2GGeRCPPo6h0qZYx8pBe9_IkcmO8aifpP8MmChlQ,1107\nwheel-0.38.4.dist-info/METADATA,sha256=3j4KgVZCY7eZyOrwDKYoTuAcfr_gXAbxx1yGhR9DssA,2110\nwheel-0.38.4.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92\nwheel-0.38.4.dist-info/entry_points.txt,sha256=krg-iHKefnsk1qvNLDkZP3-4Aq3J0F_zJaathht0JBI,107\nwheel-0.38.4.dist-info/top_level.txt,sha256=HxSBIbgEstMPe4eFawhA66Mq-QYHMopXVoAncfjb_1c,6\nwheel-0.38.4.dist-info/RECORD,,\nwheel/cli/unpack.cpython-37.pyc,,\nwheel/__main__.cpython-37.pyc,,\nwheel/metadata.cpython-37.pyc,,\nwheel/vendored/packaging/_musllinux.cpython-37.pyc,,\nwheel/vendored/__init__.cpython-37.pyc,,\nwheel/vendored/packaging/__init__.cpython-37.pyc,,\nwheel-0.38.4.dist-info/INSTALLER,,\nwheel/wheelfile.cpython-37.pyc,,\n../../../bin/wheel-3.7,,\n../../../bin/wheel3.7,,\nwheel/cli/convert.cpython-37.pyc,,\nwheel/cli/__pycache__,,\nwheel/vendored/packaging/_manylinux.cpython-37.pyc,,\nwheel/vendored/packaging/tags.cpython-37.pyc,,\nwheel/__pycache__,,\nwheel/__init__.cpython-37.pyc,,\n../../../bin/wheel,,\nwheel/vendored/__pycache__,,\nwheel/util.cpython-37.pyc,,\nwheel/cli/pack.cpython-37.pyc,,\nwheel-0.38.4.virtualenv,,\nwheel/bdist_wheel.cpython-37.pyc,,\nwheel/macosx_libfile.cpython-37.pyc,,\n../../../bin/wheel3,,\nwheel-0.38.4.dist-info/__pycache__,,\nwheel/cli/__init__.cpython-37.pyc,,\nwheel/vendored/packaging/__pycache__,,\nwheel/_setuptools_logging.cpython-37.pyc,,"
  },
  {
    "path": "lib/python3.7/site-packages/wheel-0.38.4.dist-info/WHEEL",
    "content": "Wheel-Version: 1.0\nGenerator: bdist_wheel (0.38.4)\nRoot-Is-Purelib: true\nTag: py3-none-any\n\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel-0.38.4.dist-info/entry_points.txt",
    "content": "[console_scripts]\nwheel = wheel.cli:main\n\n[distutils.commands]\nbdist_wheel = wheel.bdist_wheel:bdist_wheel\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel-0.38.4.dist-info/top_level.txt",
    "content": "wheel\n"
  },
  {
    "path": "lib/python3.7/site-packages/wheel-0.38.4.virtualenv",
    "content": ""
  },
  {
    "path": "mkdocs.yml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nsite_name: Ultralytics YOLOv8 Docs\nsite_url: https://docs.ultralytics.com\nsite_description: Explore Ultralytics YOLOv8, a cutting-edge real-time object detection and image segmentation model for various applications and hardware platforms.\nsite_author: Ultralytics\nrepo_url: https://github.com/ultralytics/ultralytics\nedit_uri: https://github.com/ultralytics/ultralytics/tree/main/docs\nrepo_name: ultralytics/ultralytics\nremote_name: https://github.com/ultralytics/docs\n\ntheme:\n  name: material\n  custom_dir: docs/overrides\n  logo: https://github.com/ultralytics/assets/raw/main/logo/Ultralytics_Logotype_Reverse.svg\n  favicon: assets/favicon.ico\n  icon:\n    repo: fontawesome/brands/github\n  font:\n    text: Roboto\n    code: Roboto Mono\n\n  palette:\n    # Palette toggle for light mode\n    - scheme: default\n      # primary: grey\n      toggle:\n        icon: material/brightness-7\n        name: Switch to dark mode\n\n    # Palette toggle for dark mode\n    - scheme: slate\n      # primary: black\n      toggle:\n        icon: material/brightness-4\n        name: Switch to light mode\n  features:\n    - content.action.edit\n    - content.code.annotate\n    - content.code.copy\n    - content.tooltips\n    - search.highlight\n    - search.share\n    - search.suggest\n    - toc.follow\n    - toc.integrate\n    - navigation.top\n    - navigation.tabs\n    - navigation.tabs.sticky\n    - navigation.expand\n    - navigation.footer\n    - navigation.tracking\n    - navigation.instant\n    - navigation.indexes\n    - content.tabs.link  # all code tabs change simultaneously\n\n# Customization\ncopyright: <a href=\"https://ultralytics.com\" target=\"_blank\">Ultralytics 2023.</a> All rights reserved.\nextra:\n  # version:\n  #   provider: mike  #  version drop-down menu\n  robots: robots.txt\n  analytics:\n    provider: google\n    property: G-2M5EHKC0BH\n  #    feedback:\n  #      title: Was this page helpful?\n  #      ratings:\n  #        - icon: material/heart\n  #          name: This page was helpful\n  #          data: 1\n  #          note: Thanks for your feedback!\n  #        - icon: material/heart-broken\n  #          name: This page could be improved\n  #          data: 0\n  #          note: >-\n  #            Thanks for your feedback!<br>\n  #            <a href=\"https://github.com/ultralytics/ultralytics/issues/new?title=Docs+Feedback+for+{title}+page+at+https://docs.ultralytics.com/{url}&labels=enhancement&template=feature-request.yml\" target=\"_blank\" rel=\"noopener\">Tell us what we can improve.</a>\n\n  social:\n    - icon: fontawesome/brands/github\n      link: https://github.com/ultralytics\n    - icon: fontawesome/brands/linkedin\n      link: https://www.linkedin.com/company/ultralytics/\n    - icon: fontawesome/brands/twitter\n      link: https://twitter.com/ultralytics\n    - icon: fontawesome/brands/youtube\n      link: https://www.youtube.com/ultralytics\n    - icon: fontawesome/brands/docker\n      link: https://hub.docker.com/r/ultralytics/ultralytics/\n    - icon: fontawesome/brands/python\n      link: https://pypi.org/project/ultralytics/\n    - icon: fontawesome/brands/discord\n      link: https://discord.gg/n6cFeSPZdD\n\nextra_css:\n  - stylesheets/style.css\n  - https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css\n\nmarkdown_extensions:\n  # Div text decorators\n  - admonition\n  - md_in_html\n  - pymdownx.details\n  - pymdownx.superfences\n  - tables\n  - attr_list\n  - def_list\n  # Syntax highlight\n  - pymdownx.highlight:\n      anchor_linenums: true\n  - pymdownx.inlinehilite\n  - pymdownx.snippets:\n      base_path: ./\n  - pymdownx.emoji:\n      emoji_index: !!python/name:materialx.emoji.twemoji  # noqa\n      emoji_generator: !!python/name:materialx.emoji.to_svg\n  - pymdownx.tabbed:\n      alternate_style: true\n\n  # Highlight\n  - pymdownx.critic\n  - pymdownx.caret\n  - pymdownx.keys\n  - pymdownx.mark\n  - pymdownx.tilde\n\n# Primary navigation ---------------------------------------------------------------------------------------------------\nnav:\n  - Home:\n      - Home: index.md\n      - Quickstart: quickstart.md\n      - Modes:\n          - modes/index.md\n          - Train: modes/train.md\n          - Val: modes/val.md\n          - Predict: modes/predict.md\n          - Export: modes/export.md\n          - Track: modes/track.md\n          - Benchmark: modes/benchmark.md\n      - Tasks:\n          - tasks/index.md\n          - Detect: tasks/detect.md\n          - Segment: tasks/segment.md\n          - Classify: tasks/classify.md\n          - Pose: tasks/pose.md\n  - Quickstart: quickstart.md\n  - Modes:\n      - modes/index.md\n      - Train: modes/train.md\n      - Val: modes/val.md\n      - Predict: modes/predict.md\n      - Export: modes/export.md\n      - Track: modes/track.md\n      - Benchmark: modes/benchmark.md\n  - Tasks:\n      - tasks/index.md\n      - Detect: tasks/detect.md\n      - Segment: tasks/segment.md\n      - Classify: tasks/classify.md\n      - Pose: tasks/pose.md\n  - Models:\n      - models/index.md\n      - YOLOv3: models/yolov3.md\n      - YOLOv5: models/yolov5.md\n      - YOLOv8: models/yolov8.md\n      - SAM (Segment Anything Model): models/sam.md\n      - RT-DETR (Realtime Detection Transformer): models/rtdetr.md\n  - Datasets:\n      - datasets/index.md\n      - Detection:\n          - datasets/detect/index.md\n          - Argoverse: datasets/detect/argoverse.md\n          - COCO: datasets/detect/coco.md\n          - COCO8: datasets/detect/coco8.md\n          - GlobalWheat2020: datasets/detect/globalwheat2020.md\n          - Objects365: datasets/detect/objects365.md\n          - SKU-110K: datasets/detect/sku-110k.md\n          - VisDrone: datasets/detect/visdrone.md\n          - VOC: datasets/detect/voc.md\n          - xView: datasets/detect/xview.md\n      - Segmentation:\n          - datasets/segment/index.md\n          - COCO: datasets/segment/coco.md\n          - COCO8-seg: datasets/segment/coco8-seg.md\n      - Pose:\n          - datasets/pose/index.md\n          - COCO: datasets/pose/coco.md\n          - COCO8-pose: datasets/pose/coco8-pose.md\n      - Classification:\n          - datasets/classify/index.md\n          - Caltech 101: datasets/classify/caltech101.md\n          - Caltech 256: datasets/classify/caltech256.md\n          - CIFAR-10: datasets/classify/cifar10.md\n          - CIFAR-100: datasets/classify/cifar100.md\n          - Fashion-MNIST: datasets/classify/fashion-mnist.md\n          - ImageNet: datasets/classify/imagenet.md\n          - ImageNet-10: datasets/classify/imagenet10.md\n          - Imagenette: datasets/classify/imagenette.md\n          - Imagewoof: datasets/classify/imagewoof.md\n          - MNIST: datasets/classify/mnist.md\n      - Multi-Object Tracking:\n          - datasets/track/index.md\n  - Usage:\n      - CLI: usage/cli.md\n      - Python: usage/python.md\n      - Callbacks: usage/callbacks.md\n      - Configuration: usage/cfg.md\n      - Advanced Customization: usage/engine.md\n  - YOLOv5:\n      - yolov5/index.md\n      - Quickstart: yolov5/quickstart_tutorial.md\n      - Environments:\n          - Amazon Web Services (AWS): yolov5/environments/aws_quickstart_tutorial.md\n          - Google Cloud (GCP): yolov5/environments/google_cloud_quickstart_tutorial.md\n          - Docker Image: yolov5/environments/docker_image_quickstart_tutorial.md\n      - Tutorials:\n          - Train Custom Data: yolov5/tutorials/train_custom_data.md\n          - Tips for Best Training Results: yolov5/tutorials/tips_for_best_training_results.md\n          - Multi-GPU Training: yolov5/tutorials/multi_gpu_training.md\n          - PyTorch Hub: yolov5/tutorials/pytorch_hub_model_loading.md\n          - TFLite, ONNX, CoreML, TensorRT Export: yolov5/tutorials/model_export.md\n          - NVIDIA Jetson Nano Deployment: yolov5/tutorials/running_on_jetson_nano.md\n          - Test-Time Augmentation (TTA): yolov5/tutorials/test_time_augmentation.md\n          - Model Ensembling: yolov5/tutorials/model_ensembling.md\n          - Pruning/Sparsity Tutorial: yolov5/tutorials/model_pruning_and_sparsity.md\n          - Hyperparameter evolution: yolov5/tutorials/hyperparameter_evolution.md\n          - Transfer learning with frozen layers: yolov5/tutorials/transfer_learning_with_frozen_layers.md\n          - Architecture Summary: yolov5/tutorials/architecture_description.md\n          - Roboflow Datasets: yolov5/tutorials/roboflow_datasets_integration.md\n          - Neural Magic's DeepSparse: yolov5/tutorials/neural_magic_pruning_quantization.md\n          - Comet Logging: yolov5/tutorials/comet_logging_integration.md\n          - Clearml Logging: yolov5/tutorials/clearml_logging_integration.md\n  - Ultralytics HUB:\n      - hub/index.md\n      - Quickstart: hub/quickstart.md\n      - Datasets: hub/datasets.md\n      - Projects: hub/projects.md\n      - Models: hub/models.md\n      - Integrations: hub/integrations.md\n      - Ultralytics HUB App:\n          - hub/app/index.md\n          - 'iOS': hub/app/ios.md\n          - 'Android': hub/app/android.md\n      - Inference API: hub/inference_api.md\n  - Reference:\n      - hub:\n          - auth: reference/hub/auth.md\n          - session: reference/hub/session.md\n          - utils: reference/hub/utils.md\n      - nn:\n          - autobackend: reference/nn/autobackend.md\n          - autoshape: reference/nn/autoshape.md\n          - modules:\n              - blocks: reference/nn/modules/block.md\n              - convs: reference/nn/modules/conv.md\n              - head: reference/nn/modules/head.md\n              - transformer: reference/nn/modules/transformer.md\n              - utils: reference/nn/modules/utils.md\n          - tasks: reference/nn/tasks.md\n      - tracker:\n          - track: reference/tracker/track.md\n          - trackers:\n              - basetrack: reference/tracker/trackers/basetrack.md\n              - bot_sort: reference/tracker/trackers/bot_sort.md\n              - byte_tracker: reference/tracker/trackers/byte_tracker.md\n          - utils:\n              - gmc: reference/tracker/utils/gmc.md\n              - kalman_filter: reference/tracker/utils/kalman_filter.md\n              - matching: reference/tracker/utils/matching.md\n      - yolo:\n          - data:\n              - annotator: reference/yolo/data/annotator.md\n              - augment: reference/yolo/data/augment.md\n              - base: reference/yolo/data/base.md\n              - build: reference/yolo/data/build.md\n              - converter: reference/yolo/data/converter.md\n              - dataloaders:\n                  - stream_loaders: reference/yolo/data/dataloaders/stream_loaders.md\n                  - v5augmentations: reference/yolo/data/dataloaders/v5augmentations.md\n                  - v5loader: reference/yolo/data/dataloaders/v5loader.md\n              - dataset: reference/yolo/data/dataset.md\n              - dataset_wrappers: reference/yolo/data/dataset_wrappers.md\n              - utils: reference/yolo/data/utils.md\n          - engine:\n              - exporter: reference/yolo/engine/exporter.md\n              - model: reference/yolo/engine/model.md\n              - predictor: reference/yolo/engine/predictor.md\n              - results: reference/yolo/engine/results.md\n              - trainer: reference/yolo/engine/trainer.md\n              - validator: reference/yolo/engine/validator.md\n          - utils:\n              - autobatch: reference/yolo/utils/autobatch.md\n              - benchmarks: reference/yolo/utils/benchmarks.md\n              - callbacks:\n                  - base: reference/yolo/utils/callbacks/base.md\n                  - clearml: reference/yolo/utils/callbacks/clearml.md\n                  - comet: reference/yolo/utils/callbacks/comet.md\n                  - hub: reference/yolo/utils/callbacks/hub.md\n                  - mlflow: reference/yolo/utils/callbacks/mlflow.md\n                  - neptune: reference/yolo/utils/callbacks/neptune.md\n                  - raytune: reference/yolo/utils/callbacks/raytune.md\n                  - tensorboard: reference/yolo/utils/callbacks/tensorboard.md\n                  - wb: reference/yolo/utils/callbacks/wb.md\n              - checks: reference/yolo/utils/checks.md\n              - dist: reference/yolo/utils/dist.md\n              - downloads: reference/yolo/utils/downloads.md\n              - errors: reference/yolo/utils/errors.md\n              - files: reference/yolo/utils/files.md\n              - instance: reference/yolo/utils/instance.md\n              - loss: reference/yolo/utils/loss.md\n              - metrics: reference/yolo/utils/metrics.md\n              - ops: reference/yolo/utils/ops.md\n              - plotting: reference/yolo/utils/plotting.md\n              - tal: reference/yolo/utils/tal.md\n              - torch_utils: reference/yolo/utils/torch_utils.md\n          - v8:\n              - classify:\n                  - predict: reference/yolo/v8/classify/predict.md\n                  - train: reference/yolo/v8/classify/train.md\n                  - val: reference/yolo/v8/classify/val.md\n              - detect:\n                  - predict: reference/yolo/v8/detect/predict.md\n                  - train: reference/yolo/v8/detect/train.md\n                  - val: reference/yolo/v8/detect/val.md\n              - pose:\n                  - predict: reference/yolo/v8/pose/predict.md\n                  - train: reference/yolo/v8/pose/train.md\n                  - val: reference/yolo/v8/pose/val.md\n              - segment:\n                  - predict: reference/yolo/v8/segment/predict.md\n                  - train: reference/yolo/v8/segment/train.md\n                  - val: reference/yolo/v8/segment/val.md\n  - Help:\n      - Help: help/index.md\n      - Frequently Asked Questions (FAQ): help/FAQ.md\n      - Contributing Guide: help/contributing.md\n      - Contributor License Agreement (CLA): help/CLA.md\n      - Minimum Reproducible Example (MRE) Guide: help/minimum_reproducible_example.md\n      - Code of Conduct: help/code_of_conduct.md\n      - Security Policy: SECURITY.md\n\n# Plugins including 301 redirects navigation ---------------------------------------------------------------------------\nplugins:\n  - mkdocstrings\n  - search\n  - ultralytics:\n      add_desc: False\n      add_image: True\n      add_share_buttons: True\n      default_image: https://github.com/ultralytics/ultralytics/assets/26833433/6d09221c-c52a-4234-9a5d-b862e93c6529\n  - redirects:\n      redirect_maps:\n        callbacks.md: usage/callbacks.md\n        cfg.md: usage/cfg.md\n        cli.md: usage/cli.md\n        config.md: usage/cfg.md\n        engine.md: usage/engine.md\n        environments/AWS-Quickstart.md: yolov5/environments/aws_quickstart_tutorial.md\n        environments/Docker-Quickstart.md: yolov5/environments/docker_image_quickstart_tutorial.md\n        environments/GCP-Quickstart.md: yolov5/environments/google_cloud_quickstart_tutorial.md\n        FAQ/augmentation.md: yolov5/tutorials/tips_for_best_training_results.md\n        package-framework.md: index.md\n        package-framework/mock_detector.md: index.md\n        predict.md: modes/predict.md\n        python.md: usage/python.md\n        quick-start.md: quickstart.md\n        app.md: hub/app/index.md\n        sdk.md: index.md\n        reference/base_pred.md: reference/yolo/engine/predictor.md\n        reference/base_trainer.md: reference/yolo/engine/trainer.md\n        reference/exporter.md: reference/yolo/engine/exporter.md\n        reference/model.md: reference/yolo/engine/model.md\n        reference/nn.md: reference/nn/modules/head.md\n        reference/ops.md: reference/yolo/utils/ops.md\n        reference/results.md: reference/yolo/engine/results.md\n        reference/base_val.md: index.md\n        tasks/classification.md: tasks/classify.md\n        tasks/detection.md: tasks/detect.md\n        tasks/segmentation.md: tasks/segment.md\n        tasks/keypoints.md: tasks/pose.md\n        tasks/tracking.md: modes/track.md\n        tutorials/architecture-summary.md: yolov5/tutorials/architecture_description.md\n        tutorials/clearml-logging.md: yolov5/tutorials/clearml_logging_integration.md\n        tutorials/comet-logging.md: yolov5/tutorials/comet_logging_integration.md\n        tutorials/hyperparameter-evolution.md: yolov5/tutorials/hyperparameter_evolution.md\n        tutorials/model-ensembling.md: yolov5/tutorials/model_ensembling.md\n        tutorials/multi-gpu-training.md: yolov5/tutorials/multi_gpu_training.md\n        tutorials/nvidia-jetson.md: yolov5/tutorials/running_on_jetson_nano.md\n        tutorials/pruning-sparsity.md: yolov5/tutorials/model_pruning_and_sparsity.md\n        tutorials/pytorch-hub.md: yolov5/tutorials/pytorch_hub_model_loading.md\n        tutorials/roboflow.md: yolov5/tutorials/roboflow_datasets_integration.md\n        tutorials/test-time-augmentation.md: yolov5/tutorials/test_time_augmentation.md\n        tutorials/torchscript-onnx-coreml-export.md: yolov5/tutorials/model_export.md\n        tutorials/train-custom-datasets.md: yolov5/tutorials/train_custom_data.md\n        tutorials/training-tips-best-results.md: yolov5/tutorials/tips_for_best_training_results.md\n        tutorials/transfer-learning-froze-layers.md: yolov5/tutorials/transfer_learning_with_frozen_layers.md\n        tutorials/weights-and-biasis-logging.md: yolov5/tutorials/comet_logging_integration.md\n        yolov5/pytorch_hub.md: yolov5/tutorials/pytorch_hub_model_loading.md\n        yolov5/hyp_evolution.md: yolov5/tutorials/hyperparameter_evolution.md\n        yolov5/pruning_sparsity.md: yolov5/tutorials/model_pruning_and_sparsity.md\n        yolov5/comet.md: yolov5/tutorials/comet_logging_integration.md\n        yolov5/clearml.md: yolov5/tutorials/clearml_logging_integration.md\n        yolov5/tta.md: yolov5/tutorials/test_time_augmentation.md\n        yolov5/multi_gpu_training.md: yolov5/tutorials/multi_gpu_training.md\n        yolov5/ensemble.md: yolov5/tutorials/model_ensembling.md\n        yolov5/jetson_nano.md: yolov5/tutorials/running_on_jetson_nano.md\n        yolov5/transfer_learn_frozen.md: yolov5/tutorials/transfer_learning_with_frozen_layers.md\n        yolov5/neural_magic.md: yolov5/tutorials/neural_magic_pruning_quantization.md\n        yolov5/train_custom_data.md: yolov5/tutorials/train_custom_data.md\n        yolov5/architecture.md: yolov5/tutorials/architecture_description.md\n        yolov5/export.md: yolov5/tutorials/model_export.md\n        yolov5/yolov5_quickstart_tutorial.md: yolov5/quickstart_tutorial.md\n        yolov5/tips_for_best_training_results.md: yolov5/tutorials/tips_for_best_training_results.md\n        yolov5/tutorials/yolov5_neural_magic_tutorial.md: yolov5/tutorials/neural_magic_pruning_quantization.md\n        yolov5/tutorials/model_ensembling_tutorial.md: yolov5/tutorials/model_ensembling.md\n        yolov5/tutorials/pytorch_hub_tutorial.md: yolov5/tutorials/pytorch_hub_model_loading.md\n        yolov5/tutorials/yolov5_architecture_tutorial.md: yolov5/tutorials/architecture_description.md\n        yolov5/tutorials/multi_gpu_training_tutorial.md: yolov5/tutorials/multi_gpu_training.md\n        yolov5/tutorials/yolov5_pytorch_hub_tutorial.md: yolov5/tutorials/pytorch_hub_model_loading.md\n        yolov5/tutorials/model_export_tutorial.md: yolov5/tutorials/model_export.md\n        yolov5/tutorials/jetson_nano_tutorial.md: yolov5/tutorials/running_on_jetson_nano.md\n        yolov5/tutorials/yolov5_model_ensembling_tutorial.md: yolov5/tutorials/model_ensembling.md\n        yolov5/tutorials/roboflow_integration.md: yolov5/tutorials/roboflow_datasets_integration.md\n        yolov5/tutorials/pruning_and_sparsity_tutorial.md: yolov5/tutorials/model_pruning_and_sparsity.md\n        yolov5/tutorials/yolov5_transfer_learning_with_frozen_layers_tutorial.md: yolov5/tutorials/transfer_learning_with_frozen_layers.md\n        yolov5/tutorials/transfer_learning_with_frozen_layers_tutorial.md: yolov5/tutorials/transfer_learning_with_frozen_layers.md\n        yolov5/tutorials/yolov5_model_export_tutorial.md: yolov5/tutorials/model_export.md\n        yolov5/tutorials/neural_magic_tutorial.md: yolov5/tutorials/neural_magic_pruning_quantization.md\n        yolov5/tutorials/yolov5_clearml_integration_tutorial.md: yolov5/tutorials/clearml_logging_integration.md\n        yolov5/tutorials/yolov5_train_custom_data.md: yolov5/tutorials/train_custom_data.md\n        yolov5/tutorials/comet_integration_tutorial.md: yolov5/tutorials/comet_logging_integration.md\n        yolov5/tutorials/yolov5_pruning_and_sparsity_tutorial.md: yolov5/tutorials/model_pruning_and_sparsity.md\n        yolov5/tutorials/yolov5_jetson_nano_tutorial.md: yolov5/tutorials/running_on_jetson_nano.md\n        yolov5/tutorials/yolov5_roboflow_integration.md: yolov5/tutorials/roboflow_datasets_integration.md\n        yolov5/tutorials/hyperparameter_evolution_tutorial.md: yolov5/tutorials/hyperparameter_evolution.md\n        yolov5/tutorials/yolov5_hyperparameter_evolution_tutorial.md: yolov5/tutorials/hyperparameter_evolution.md\n        yolov5/tutorials/clearml_integration_tutorial.md: yolov5/tutorials/clearml_logging_integration.md\n        yolov5/tutorials/test_time_augmentation_tutorial.md: yolov5/tutorials/test_time_augmentation.md\n        yolov5/tutorials/yolov5_test_time_augmentation_tutorial.md: yolov5/tutorials/test_time_augmentation.md\n        yolov5/environments/yolov5_amazon_web_services_quickstart_tutorial.md: yolov5/environments/aws_quickstart_tutorial.md\n        yolov5/environments/yolov5_google_cloud_platform_quickstart_tutorial.md: yolov5/environments/google_cloud_quickstart_tutorial.md\n        yolov5/environments/yolov5_docker_image_quickstart_tutorial.md: yolov5/environments/docker_image_quickstart_tutorial.md\n"
  },
  {
    "path": "pyvenv.cfg",
    "content": "home = /home/jiayuan/anaconda3/envs/yolo8/bin\nimplementation = CPython\nversion_info = 3.7.16.final.0\nvirtualenv = 20.16.7\ninclude-system-site-packages = false\nbase-prefix = /home/jiayuan/anaconda3/envs/yolo8\nbase-exec-prefix = /home/jiayuan/anaconda3/envs/yolo8\nbase-executable = /home/jiayuan/anaconda3/envs/yolo8/bin/python3\n"
  },
  {
    "path": "requirements.txt",
    "content": "# Ultralytics requirements\n# Usage: pip install -r requirements.txt\n\n# Base ----------------------------------------\nmatplotlib>=3.2.2\nopencv-python>=4.6.0\nPillow>=7.1.2\nPyYAML>=5.3.1\nrequests>=2.23.0\nscipy>=1.4.1\ntorch>=1.7.0\ntorchvision>=0.8.1\ntqdm>=4.64.0\n\n# Logging -------------------------------------\n# tensorboard>=2.13.0\n# clearml\n# comet\n\n# Plotting ------------------------------------\npandas>=1.1.4\nseaborn>=0.11.0\n\n# Export --------------------------------------\n# coremltools>=6.0  # CoreML export\n# onnx>=1.12.0  # ONNX export\n# onnxsim>=0.4.1  # ONNX simplifier\n# nvidia-pyindex  # TensorRT export\n# nvidia-tensorrt  # TensorRT export\n# scikit-learn==0.19.2  # CoreML quantization\n# tensorflow>=2.4.1  # TF exports (-cpu, -aarch64, -macos)\n# tflite-support\n# tensorflowjs>=3.9.0  # TF.js export\n# openvino-dev>=2022.3  # OpenVINO export\n\n# Extras --------------------------------------\npsutil  # system utilization\n# thop>=0.1.1  # FLOPs computation\n# ipython  # interactive notebook\n# albumentations>=1.0.3\n# pycocotools>=2.0.6  # COCO mAP\n# roboflow\n"
  },
  {
    "path": "setup.cfg",
    "content": "# Project-wide configuration file, can be used for package metadata and other toll configurations\n# Example usage: global configuration for PEP8 (via flake8) setting or default pytest arguments\n# Local usage: pip install pre-commit, pre-commit run --all-files\n\n[metadata]\nlicense_files = LICENSE\ndescription_file = README.md\n\n[tool:pytest]\nnorecursedirs =\n    .git\n    dist\n    build\naddopts =\n    --doctest-modules\n    --durations=25\n    --color=yes\n\n[flake8]\nmax-line-length = 120\nexclude = .tox,*.egg,build,temp\nselect = E,W,F\ndoctests = True\nverbose = 2\n# https://pep8.readthedocs.io/en/latest/intro.html#error-codes\nformat = pylint\n# see: https://www.flake8rules.com/\nignore = E731,F405,E402,W504,E501\n    # E731: Do not assign a lambda expression, use a def\n    # F405: name may be undefined, or defined from star imports: module\n    # E402: module level import not at top of file\n    # W504: line break after binary operator\n    # E501: line too long\n    # removed:\n    # F401: module imported but unused\n    # E231: missing whitespace after ‘,’, ‘;’, or ‘:’\n    # E127: continuation line over-indented for visual indent\n    # F403: ‘from module import *’ used; unable to detect undefined names\n\n\n[isort]\n# https://pycqa.github.io/isort/docs/configuration/options.html\nline_length = 120\n# see: https://pycqa.github.io/isort/docs/configuration/multi_line_output_modes.html\nmulti_line_output = 0\n\n[yapf]\nbased_on_style = pep8\nspaces_before_comment = 2\nCOLUMN_LIMIT = 120\nCOALESCE_BRACKETS = True\nSPACES_AROUND_POWER_OPERATOR = True\nSPACE_BETWEEN_ENDING_COMMA_AND_CLOSING_BRACKET = True\nSPLIT_BEFORE_CLOSING_BRACKET = False\nSPLIT_BEFORE_FIRST_ARGUMENT = False\n# EACH_DICT_ENTRY_ON_SEPARATE_LINE = False\n"
  },
  {
    "path": "setup.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport re\nfrom pathlib import Path\n\nimport pkg_resources as pkg\nfrom setuptools import find_packages, setup\n\n# Settings\nFILE = Path(__file__).resolve()\nPARENT = FILE.parent  # root directory\nREADME = (PARENT / 'README.md').read_text(encoding='utf-8')\nREQUIREMENTS = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements((PARENT / 'requirements.txt').read_text())]\nPKG_REQUIREMENTS = ['sentry_sdk']  # pip-only requirements\n\n\ndef get_version():\n    file = PARENT / 'ultralytics/__init__.py'\n    return re.search(r'^__version__ = [\\'\"]([^\\'\"]*)[\\'\"]', file.read_text(encoding='utf-8'), re.M)[1]\n\n\nsetup(\n    name='ultralytics',  # name of pypi package\n    version=get_version(),  # version of pypi package\n    python_requires='>=3.7',\n    license='AGPL-3.0',\n    description=('Ultralytics YOLOv8 for SOTA object detection, multi-object tracking, instance segmentation, '\n                 'pose estimation and image classification.'),\n    long_description=README,\n    long_description_content_type='text/markdown',\n    url='https://github.com/ultralytics/ultralytics',\n    project_urls={\n        'Bug Reports': 'https://github.com/ultralytics/ultralytics/issues',\n        'Funding': 'https://ultralytics.com',\n        'Source': 'https://github.com/ultralytics/ultralytics'},\n    author='Ultralytics',\n    author_email='hello@ultralytics.com',\n    packages=find_packages(),  # required\n    include_package_data=True,\n    install_requires=REQUIREMENTS + PKG_REQUIREMENTS,\n    extras_require={\n        'dev': [\n            'check-manifest',\n            'pytest',\n            'pytest-cov',\n            'coverage',\n            'mkdocs-material',\n            'mkdocstrings[python]',\n            'mkdocs-redirects',  # for 301 redirects\n            'mkdocs-ultralytics-plugin',  # for meta descriptions and images, dates and authors\n        ],\n        'export': ['coremltools>=6.0', 'openvino-dev>=2022.3', 'tensorflowjs'],  # automatically installs tensorflow\n    },\n    classifiers=[\n        'Development Status :: 4 - Beta',\n        'Intended Audience :: Developers',\n        'Intended Audience :: Education',\n        'Intended Audience :: Science/Research',\n        'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',\n        'Programming Language :: Python :: 3',\n        'Programming Language :: Python :: 3.7',\n        'Programming Language :: Python :: 3.8',\n        'Programming Language :: Python :: 3.9',\n        'Programming Language :: Python :: 3.10',\n        'Programming Language :: Python :: 3.11',\n        'Topic :: Software Development',\n        'Topic :: Scientific/Engineering',\n        'Topic :: Scientific/Engineering :: Artificial Intelligence',\n        'Topic :: Scientific/Engineering :: Image Recognition',\n        'Operating System :: POSIX :: Linux',\n        'Operating System :: MacOS',\n        'Operating System :: Microsoft :: Windows', ],\n    keywords='machine-learning, deep-learning, vision, ML, DL, AI, YOLO, YOLOv3, YOLOv5, YOLOv8, HUB, Ultralytics',\n    entry_points={\n        'console_scripts': ['yolo = ultralytics.yolo.cfg:entrypoint', 'ultralytics = ultralytics.yolo.cfg:entrypoint']})\n"
  },
  {
    "path": "tests/conftest.py",
    "content": "import pytest\n\n\ndef pytest_addoption(parser):\n    parser.addoption('--runslow', action='store_true', default=False, help='run slow tests')\n\n\ndef pytest_configure(config):\n    config.addinivalue_line('markers', 'slow: mark test as slow to run')\n\n\ndef pytest_collection_modifyitems(config, items):\n    if config.getoption('--runslow'):\n        # --runslow given in cli: do not skip slow tests\n        return\n    skip_slow = pytest.mark.skip(reason='need --runslow option to run')\n    for item in items:\n        if 'slow' in item.keywords:\n            item.add_marker(skip_slow)\n"
  },
  {
    "path": "tests/test_cli.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport subprocess\nfrom pathlib import Path\n\nimport pytest\n\nfrom ultralytics.yolo.utils import ONLINE, ROOT, SETTINGS\n\nWEIGHT_DIR = Path(SETTINGS['weights_dir'])\nTASK_ARGS = [  # (task, model, data)\n    ('detect', 'yolov8n', 'coco8.yaml'), ('segment', 'yolov8n-seg', 'coco8-seg.yaml'),\n    ('classify', 'yolov8n-cls', 'imagenet10'), ('pose', 'yolov8n-pose', 'coco8-pose.yaml')]\nEXPORT_ARGS = [  # (model, format)\n    ('yolov8n', 'torchscript'), ('yolov8n-seg', 'torchscript'), ('yolov8n-cls', 'torchscript'),\n    ('yolov8n-pose', 'torchscript')]\n\n\ndef run(cmd):\n    # Run a subprocess command with check=True\n    subprocess.run(cmd.split(), check=True)\n\n\ndef test_special_modes():\n    run('yolo checks')\n    run('yolo settings')\n    run('yolo help')\n\n\n@pytest.mark.parametrize('task,model,data', TASK_ARGS)\ndef test_train(task, model, data):\n    run(f'yolo train {task} model={model}.yaml data={data} imgsz=32 epochs=1')\n\n\n@pytest.mark.parametrize('task,model,data', TASK_ARGS)\ndef test_val(task, model, data):\n    run(f'yolo val {task} model={model}.pt data={data} imgsz=32')\n\n\n@pytest.mark.parametrize('task,model,data', TASK_ARGS)\ndef test_predict(task, model, data):\n    run(f\"yolo predict model={model}.pt source={ROOT / 'assets'} imgsz=32 save save_crop save_txt\")\n    if ONLINE:\n        run(f'yolo predict model={model}.pt source=https://ultralytics.com/images/bus.jpg imgsz=32')\n        run(f'yolo predict model={model}.pt source=https://ultralytics.com/assets/decelera_landscape_min.mov imgsz=32')\n        run(f'yolo predict model={model}.pt source=https://ultralytics.com/assets/decelera_portrait_min.mov imgsz=32')\n\n\n@pytest.mark.parametrize('model,format', EXPORT_ARGS)\ndef test_export(model, format):\n    run(f'yolo export model={model}.pt format={format}')\n\n\n# Slow Tests\n@pytest.mark.slow\n@pytest.mark.parametrize('task,model,data', TASK_ARGS)\ndef test_train_gpu(task, model, data):\n    run(f'yolo train {task} model={model}.yaml data={data} imgsz=32 epochs=1 device=\"0\"')  # single GPU\n    run(f'yolo train {task} model={model}.pt data={data} imgsz=32 epochs=1 device=\"0,1\"')  # Multi GPU\n"
  },
  {
    "path": "tests/test_engine.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom pathlib import Path\n\nfrom ultralytics import YOLO\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.engine.exporter import Exporter\nfrom ultralytics.yolo.utils import DEFAULT_CFG, ROOT, SETTINGS\nfrom ultralytics.yolo.v8 import classify, detect, segment\n\nCFG_DET = 'yolov8n.yaml'\nCFG_SEG = 'yolov8n-seg.yaml'\nCFG_CLS = 'squeezenet1_0'\nCFG = get_cfg(DEFAULT_CFG)\nMODEL = Path(SETTINGS['weights_dir']) / 'yolov8n'\nSOURCE = ROOT / 'assets'\n\n\ndef test_func(model=None):\n    print('callback test passed')\n\n\ndef test_export():\n    exporter = Exporter()\n    exporter.add_callback('on_export_start', test_func)\n    assert test_func in exporter.callbacks['on_export_start'], 'callback test failed'\n    f = exporter(model=YOLO(CFG_DET).model)\n    YOLO(f)(SOURCE)  # exported model inference\n\n\ndef test_detect():\n    overrides = {'data': 'coco8.yaml', 'model': CFG_DET, 'imgsz': 32, 'epochs': 1, 'save': False}\n    CFG.data = 'coco8.yaml'\n\n    # Trainer\n    trainer = detect.DetectionTrainer(overrides=overrides)\n    trainer.add_callback('on_train_start', test_func)\n    assert test_func in trainer.callbacks['on_train_start'], 'callback test failed'\n    trainer.train()\n\n    # Validator\n    val = detect.DetectionValidator(args=CFG)\n    val.add_callback('on_val_start', test_func)\n    assert test_func in val.callbacks['on_val_start'], 'callback test failed'\n    val(model=trainer.best)  # validate best.pt\n\n    # Predictor\n    pred = detect.DetectionPredictor(overrides={'imgsz': [64, 64]})\n    pred.add_callback('on_predict_start', test_func)\n    assert test_func in pred.callbacks['on_predict_start'], 'callback test failed'\n    result = pred(source=SOURCE, model=f'{MODEL}.pt')\n    assert len(result), 'predictor test failed'\n\n    overrides['resume'] = trainer.last\n    trainer = detect.DetectionTrainer(overrides=overrides)\n    try:\n        trainer.train()\n    except Exception as e:\n        print(f'Expected exception caught: {e}')\n        return\n\n    Exception('Resume test failed!')\n\n\ndef test_segment():\n    overrides = {'data': 'coco8-seg.yaml', 'model': CFG_SEG, 'imgsz': 32, 'epochs': 1, 'save': False}\n    CFG.data = 'coco8-seg.yaml'\n    CFG.v5loader = False\n    # YOLO(CFG_SEG).train(**overrides)  # works\n\n    # trainer\n    trainer = segment.SegmentationTrainer(overrides=overrides)\n    trainer.add_callback('on_train_start', test_func)\n    assert test_func in trainer.callbacks['on_train_start'], 'callback test failed'\n    trainer.train()\n\n    # Validator\n    val = segment.SegmentationValidator(args=CFG)\n    val.add_callback('on_val_start', test_func)\n    assert test_func in val.callbacks['on_val_start'], 'callback test failed'\n    val(model=trainer.best)  # validate best.pt\n\n    # Predictor\n    pred = segment.SegmentationPredictor(overrides={'imgsz': [64, 64]})\n    pred.add_callback('on_predict_start', test_func)\n    assert test_func in pred.callbacks['on_predict_start'], 'callback test failed'\n    result = pred(source=SOURCE, model=f'{MODEL}-seg.pt')\n    assert len(result), 'predictor test failed'\n\n    # Test resume\n    overrides['resume'] = trainer.last\n    trainer = segment.SegmentationTrainer(overrides=overrides)\n    try:\n        trainer.train()\n    except Exception as e:\n        print(f'Expected exception caught: {e}')\n        return\n\n    Exception('Resume test failed!')\n\n\ndef test_classify():\n    overrides = {'data': 'imagenet10', 'model': 'yolov8n-cls.yaml', 'imgsz': 32, 'epochs': 1, 'save': False}\n    CFG.data = 'imagenet10'\n    CFG.imgsz = 32\n    # YOLO(CFG_SEG).train(**overrides)  # works\n\n    # Trainer\n    trainer = classify.ClassificationTrainer(overrides=overrides)\n    trainer.add_callback('on_train_start', test_func)\n    assert test_func in trainer.callbacks['on_train_start'], 'callback test failed'\n    trainer.train()\n\n    # Validator\n    val = classify.ClassificationValidator(args=CFG)\n    val.add_callback('on_val_start', test_func)\n    assert test_func in val.callbacks['on_val_start'], 'callback test failed'\n    val(model=trainer.best)\n\n    # Predictor\n    pred = classify.ClassificationPredictor(overrides={'imgsz': [64, 64]})\n    pred.add_callback('on_predict_start', test_func)\n    assert test_func in pred.callbacks['on_predict_start'], 'callback test failed'\n    result = pred(source=SOURCE, model=trainer.best)\n    assert len(result), 'predictor test failed'\n"
  },
  {
    "path": "tests/test_python.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport torch\nfrom PIL import Image\n\nfrom ultralytics import YOLO\nfrom ultralytics.yolo.data.build import load_inference_source\nfrom ultralytics.yolo.utils import LINUX, ONLINE, ROOT, SETTINGS\n\nMODEL = Path(SETTINGS['weights_dir']) / 'yolov8n.pt'\nCFG = 'yolov8n.yaml'\nSOURCE = ROOT / 'assets/bus.jpg'\nSOURCE_GREYSCALE = Path(f'{SOURCE.parent / SOURCE.stem}_greyscale.jpg')\nSOURCE_RGBA = Path(f'{SOURCE.parent / SOURCE.stem}_4ch.png')\n\n# Convert SOURCE to greyscale and 4-ch\nim = Image.open(SOURCE)\nim.convert('L').save(SOURCE_GREYSCALE)  # greyscale\nim.convert('RGBA').save(SOURCE_RGBA)  # 4-ch PNG with alpha\n\n\ndef test_model_forward():\n    model = YOLO(CFG)\n    model(SOURCE)\n\n\ndef test_model_info():\n    model = YOLO(CFG)\n    model.info()\n    model = YOLO(MODEL)\n    model.info(verbose=True)\n\n\ndef test_model_fuse():\n    model = YOLO(CFG)\n    model.fuse()\n    model = YOLO(MODEL)\n    model.fuse()\n\n\ndef test_predict_dir():\n    model = YOLO(MODEL)\n    model(source=ROOT / 'assets')\n\n\ndef test_predict_img():\n    model = YOLO(MODEL)\n    seg_model = YOLO('yolov8n-seg.pt')\n    cls_model = YOLO('yolov8n-cls.pt')\n    pose_model = YOLO('yolov8n-pose.pt')\n    im = cv2.imread(str(SOURCE))\n    assert len(model(source=Image.open(SOURCE), save=True, verbose=True)) == 1  # PIL\n    assert len(model(source=im, save=True, save_txt=True)) == 1  # ndarray\n    assert len(model(source=[im, im], save=True, save_txt=True)) == 2  # batch\n    assert len(list(model(source=[im, im], save=True, stream=True))) == 2  # stream\n    assert len(model(torch.zeros(320, 640, 3).numpy())) == 1  # tensor to numpy\n    batch = [\n        str(SOURCE),  # filename\n        Path(SOURCE),  # Path\n        'https://ultralytics.com/images/zidane.jpg' if ONLINE else SOURCE,  # URI\n        cv2.imread(str(SOURCE)),  # OpenCV\n        Image.open(SOURCE),  # PIL\n        np.zeros((320, 640, 3))]  # numpy\n    assert len(model(batch, visualize=True)) == len(batch)  # multiple sources in a batch\n\n    # Test tensor inference\n    im = cv2.imread(str(SOURCE))  # OpenCV\n    t = cv2.resize(im, (32, 32))\n    t = torch.from_numpy(t.transpose((2, 0, 1)))\n    t = torch.stack([t, t, t, t])\n    results = model(t, visualize=True)\n    assert len(results) == t.shape[0]\n    results = seg_model(t, visualize=True)\n    assert len(results) == t.shape[0]\n    results = cls_model(t, visualize=True)\n    assert len(results) == t.shape[0]\n    results = pose_model(t, visualize=True)\n    assert len(results) == t.shape[0]\n\n\ndef test_predict_grey_and_4ch():\n    model = YOLO(MODEL)\n    for f in SOURCE_RGBA, SOURCE_GREYSCALE:\n        for source in Image.open(f), cv2.imread(str(f)), f:\n            model(source, save=True, verbose=True)\n\n\ndef test_val():\n    model = YOLO(MODEL)\n    model.val(data='coco8.yaml', imgsz=32)\n\n\ndef test_val_scratch():\n    model = YOLO(CFG)\n    model.val(data='coco8.yaml', imgsz=32)\n\n\ndef test_amp():\n    if torch.cuda.is_available():\n        from ultralytics.yolo.engine.trainer import check_amp\n        model = YOLO(MODEL).model.cuda()\n        assert check_amp(model)\n\n\ndef test_train_scratch():\n    model = YOLO(CFG)\n    model.train(data='coco8.yaml', epochs=1, imgsz=32)\n    model(SOURCE)\n\n\ndef test_train_pretrained():\n    model = YOLO(MODEL)\n    model.train(data='coco8.yaml', epochs=1, imgsz=32)\n    model(SOURCE)\n\n\ndef test_export_torchscript():\n    model = YOLO(MODEL)\n    f = model.export(format='torchscript')\n    YOLO(f)(SOURCE)  # exported model inference\n\n\ndef test_export_torchscript_scratch():\n    model = YOLO(CFG)\n    f = model.export(format='torchscript')\n    YOLO(f)(SOURCE)  # exported model inference\n\n\ndef test_export_onnx():\n    model = YOLO(MODEL)\n    f = model.export(format='onnx')\n    YOLO(f)(SOURCE)  # exported model inference\n\n\ndef test_export_openvino():\n    model = YOLO(MODEL)\n    f = model.export(format='openvino')\n    YOLO(f)(SOURCE)  # exported model inference\n\n\ndef test_export_coreml():  # sourcery skip: move-assign\n    model = YOLO(MODEL)\n    model.export(format='coreml')\n    # if MACOS:\n    #    YOLO(f)(SOURCE)  # model prediction only supported on macOS\n\n\ndef test_export_tflite(enabled=False):\n    # TF suffers from install conflicts on Windows and macOS\n    if enabled and LINUX:\n        model = YOLO(MODEL)\n        f = model.export(format='tflite')\n        YOLO(f)(SOURCE)\n\n\ndef test_export_pb(enabled=False):\n    # TF suffers from install conflicts on Windows and macOS\n    if enabled and LINUX:\n        model = YOLO(MODEL)\n        f = model.export(format='pb')\n        YOLO(f)(SOURCE)\n\n\ndef test_export_paddle(enabled=False):\n    # Paddle protobuf requirements conflicting with onnx protobuf requirements\n    if enabled:\n        model = YOLO(MODEL)\n        model.export(format='paddle')\n\n\ndef test_all_model_yamls():\n    for m in list((ROOT / 'models').rglob('yolo*.yaml')):\n        YOLO(m.name)\n\n\ndef test_workflow():\n    model = YOLO(MODEL)\n    model.train(data='coco8.yaml', epochs=1, imgsz=32)\n    model.val()\n    model.predict(SOURCE)\n    model.export(format='onnx')  # export a model to ONNX format\n\n\ndef test_predict_callback_and_setup():\n    # test callback addition for prediction\n    def on_predict_batch_end(predictor):  # results -> List[batch_size]\n        path, im0s, _, _ = predictor.batch\n        # print('on_predict_batch_end', im0s[0].shape)\n        im0s = im0s if isinstance(im0s, list) else [im0s]\n        bs = [predictor.dataset.bs for _ in range(len(path))]\n        predictor.results = zip(predictor.results, im0s, bs)\n\n    model = YOLO(MODEL)\n    model.add_callback('on_predict_batch_end', on_predict_batch_end)\n\n    dataset = load_inference_source(source=SOURCE)\n    bs = dataset.bs  # noqa access predictor properties\n    results = model.predict(dataset, stream=True)  # source already setup\n    for _, (result, im0, bs) in enumerate(results):\n        print('test_callback', im0.shape)\n        print('test_callback', bs)\n        boxes = result.boxes  # Boxes object for bbox outputs\n        print(boxes)\n\n\ndef test_result():\n    model = YOLO('yolov8n-pose.pt')\n    res = model([SOURCE, SOURCE])\n    res[0].plot(conf=True, boxes=False)\n    res[0].plot(pil=True)\n    res[0] = res[0].cpu().numpy()\n    print(res[0].path, res[0].keypoints)\n\n    model = YOLO('yolov8n-seg.pt')\n    res = model([SOURCE, SOURCE])\n    res[0].plot(conf=True, boxes=False, masks=True)\n    res[0].plot(pil=True)\n    res[0] = res[0].cpu().numpy()\n    print(res[0].path, res[0].masks.data)\n\n    model = YOLO('yolov8n.pt')\n    res = model(SOURCE)\n    res[0].plot(pil=True)\n    res[0].plot()\n    res[0] = res[0].cpu().numpy()\n    print(res[0].path)\n\n    model = YOLO('yolov8n-cls.pt')\n    res = model(SOURCE)\n    res[0].plot(probs=False)\n    res[0].plot(pil=True)\n    res[0].plot()\n    res[0] = res[0].cpu().numpy()\n    print(res[0].path)\n\n\ndef test_track():\n    im = cv2.imread(str(SOURCE))\n    model = YOLO(MODEL)\n    seg_model = YOLO('yolov8n-seg.pt')\n    pose_model = YOLO('yolov8n-pose.pt')\n    model.track(source=im)\n    seg_model.track(source=im)\n    pose_model.track(source=im)\n"
  },
  {
    "path": "ultralytics/.ipynb_checkpoints/predict-checkpoint.py",
    "content": "import sys\nsys.path.insert(0, \"/home/jiayuan/yolom/ultralytics\")\n# 现在就可以导入Yolo类了\nfrom ultralytics import YOLO\n\n# model = YOLO('yolov8s-seg.pt')\nnumber = 3 #input how many tasks in your work\nmodel = YOLO('/home/jiayuan/ultralytics-main/ultralytics/runs/best.pt')  # 加载自己训练的模型# Validate the model\nmodel.predict(source='/data/jiayuan/yolo8_multi/images/val2017', imgsz=(1280,740), device=[0,2],name='bdd-multi-pre', save=True, classes=[2,3,4,9,10,11], conf=0.25, iou=0.45, show_labels=False,boxes=False)\n# metrics = model.val(data='/home/jiayuan/ultralytics-main/ultralytics/datasets/bdd-multi.yaml',device=[0,1,2,3],task='multi',classes=[2,3,4,9,10,11], iou=0.6,conf=0.001)  # no arguments needed, dataset and settings remembered\n# for i in range(number):\n#     print(f'This is for {i} work')\n#     print(metrics[i].box.map)    # map50-95\n#     print(metrics[i].box.map50)  # map50\n#     print(metrics[i].box.map75)  # map75\n#     print(metrics[i].box.maps)   # a list contains map50-95 of each category"
  },
  {
    "path": "ultralytics/.ipynb_checkpoints/resum_training-checkpoint.py",
    "content": "import sys\nsys.path.insert(0, \"/home/jiayuan/yolom/ultralytics\")\n# 现在就可以导入Yolo类了\nfrom ultralytics import YOLO\n\n# Load a model\nmodel = YOLO('/home/jiayuan/ultralytics-main/ultralytics/runs/multi/bddmulti-v3-640/weights/last.pt', task='multi')  # build a new model from YAML\n# model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n# model = YOLO('yolov8n.yaml').load('yolov8n.pt')  # build from YAML and transfer weights\n\n# Train the model\nmodel.train(resume=True,batch=12, device=[1,2,3],epochs=200, imgsz=(640,640),name='bddmulti-v3-640', val=True, task='multi')\n"
  },
  {
    "path": "ultralytics/.ipynb_checkpoints/train-checkpoint.py",
    "content": "import sys\nsys.path.insert(0, \"/home/jiayuan/yolom/ultralytics\")\n# 现在就可以导入Yolo类了\nfrom ultralytics import YOLO\n\n# Load a model\nmodel = YOLO('/home/jiayuan/yolom/ultralytics/models/v8/yolov8-bdd-v4-one-dropout-individual-n.yaml', task='multi')  # build a new model from YAML\n# model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n# model = YOLO('yolov8n.yaml').load('yolov8n.pt')  # build from YAML and transfer weights\n\n# Train the model\nmodel.train(data='/home/jiayuan/yolom/ultralytics/datasets/bdd-multi.yaml', batch=12, epochs=300, imgsz=(640,640), device=[0,1,2], name='yolopm', val=True, task='multi',classes=[2,3,4,9,10,11],combine_class=[2,3,4,9],single_cls=True)\n"
  },
  {
    "path": "ultralytics/.ipynb_checkpoints/val-checkpoint.py",
    "content": "import sys\nsys.path.insert(0, \"/home/jiayuan/yolom/ultralytics\")\n# 现在就可以导入Yolo类了\nfrom ultralytics import YOLO\n\n# model = YOLO('yolov8s-seg.pt')\n# number = 3 #input how many tasks in your work\nmodel = YOLO('/home/jiayuan/ultralytics-main/ultralytics/runs/best.pt')  # 加载自己训练的模型# Validate the model\n# metrics = model.val(data='/home/jiayuan/ultralytics-main/ultralytics/datasets/bdd-multi.yaml',device=[4],task='multi',name='v3-model-val',iou=0.6,conf=0.001, imgsz=(640,640),classes=[2,3,4,9,10,11],combine_class=[2,3,4,9],single_cls=True)  # no arguments needed, dataset and settings remembered\n\nmetrics = model.val(data='/home/jiayuan/ultralytics-main/ultralytics/datasets/bdd-multi.yaml',device=[3],task='multi',name='val',iou=0.6,conf=0.001, imgsz=(640,640),classes=[2,3,4,9,10,11],combine_class=[2,3,4,9],single_cls=True)  # no arguments needed, dataset and settings remembered\n# for i in range(number):\n#     print(f'This is for {i} work')\n#     print(metrics[i].box.map)    # map50-95\n#     print(metrics[i].box.map50)  # map50\n#     print(metrics[i].box.map75)  # map75\n#     print(metrics[i].box.maps)   # a list contains map50-95 of each category"
  },
  {
    "path": "ultralytics/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\n__version__ = '8.0.105'\n\nfrom ultralytics.hub import start\nfrom ultralytics.vit.rtdetr import RTDETR\nfrom ultralytics.vit.sam import SAM\nfrom ultralytics.yolo.engine.model import YOLO\nfrom ultralytics.yolo.utils.checks import check_yolo as checks\n\n__all__ = '__version__', 'YOLO', 'SAM', 'RTDETR', 'checks', 'start'  # allow simpler import\n"
  },
  {
    "path": "ultralytics/datasets/.ipynb_checkpoints/bdd-multi-checkpoint.yaml",
    "content": "# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\n#path: /data/jiayuan/BDDcoco/yolo_v8_toy  # dataset root dir\npath: /data/jiayuan/yolo8_multi  # dataset root dir\n\n# Train/val/test image paths for all tasks\ntrain: images/train2017  # train images for object detection (relative to 'path')\n\n\nval: images/val2017  # val images for object detection (relative to 'path')\n\n\ntest: images/val2017  # test images for object detection (relative to 'path')\n\nlabels_list:\n  - detection-object\n  - seg-drivable-10\n  - seg-lane-11\n\ntnc: 3  # number of classes\nnc_list: [1,1,1]\nmap: [None,{'10':'0'},{'11':'0'}]\n\n# Classes for all tasks\nnames:\n  0: person\n  1: rider\n  2: car\n  3: bus\n  4: truck\n  5: bike\n  6: motor\n  7: traffic light\n  8: traffic sign\n  9: train\n  10: drivable  # Add drivable class for drivable segmentation\n  11: lane  # Add lane class for lane segmentation\n"
  },
  {
    "path": "ultralytics/datasets/.ipynb_checkpoints/create_toy_dataset-checkpoint.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"id\": \"dbed36fc\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import os\\n\",\n    \"import shutil\\n\",\n    \"import random\\n\",\n    \"\\n\",\n    \"def select_and_copy_files(source_dir_images, source_dir_labels, dest_dir_images, dest_dir_labels, num_files, categories):\\n\",\n    \"    for category in categories:\\n\",\n    \"        source_subdir_images = os.path.join(source_dir_images, category)\\n\",\n    \"        source_subdir_labels = os.path.join(source_dir_labels, category)\\n\",\n    \"        dest_subdir_images = os.path.join(dest_dir_images, category)\\n\",\n    \"        dest_subdir_labels = os.path.join(dest_dir_labels, category)\\n\",\n    \"\\n\",\n    \"        # 创建目标子目录，如果它们不存在的话\\n\",\n    \"        os.makedirs(dest_subdir_images, exist_ok=True)\\n\",\n    \"        os.makedirs(dest_subdir_labels, exist_ok=True)\\n\",\n    \"\\n\",\n    \"        # 获取源目录中的所有.jpg和.txt文件\\n\",\n    \"        all_images = [f[:-4] for f in os.listdir(source_subdir_images) if os.path.isfile(os.path.join(source_subdir_images, f)) and f.endswith('.jpg')]\\n\",\n    \"        all_labels = [f[:-4] for f in os.listdir(source_subdir_labels) if os.path.isfile(os.path.join(source_subdir_labels, f)) and f.endswith('.txt')]\\n\",\n    \"\\n\",\n    \"        # 找到同时存在于两个目录中的文件\\n\",\n    \"        common_files = list(set(all_images) & set(all_labels))\\n\",\n    \"\\n\",\n    \"        if len(common_files) < num_files[category]:\\n\",\n    \"            raise ValueError(f\\\"Only {len(common_files)} common files found in {category}. Cannot select {num_files[category]} files.\\\")\\n\",\n    \"\\n\",\n    \"        selected_files = random.sample(common_files, num_files[category])\\n\",\n    \"\\n\",\n    \"        for file in selected_files:\\n\",\n    \"            src_file_image = os.path.join(source_subdir_images, file + '.jpg')\\n\",\n    \"            src_file_label = os.path.join(source_subdir_labels, file + '.txt')\\n\",\n    \"            dst_file_image = os.path.join(dest_subdir_images, file + '.jpg')\\n\",\n    \"            dst_file_label = os.path.join(dest_subdir_labels, file + '.txt')\\n\",\n    \"\\n\",\n    \"            shutil.copy(src_file_image, dst_file_image)\\n\",\n    \"            shutil.copy(src_file_label, dst_file_label)\\n\",\n    \"\\n\",\n    \"# 在以下目录进行操作\\n\",\n    \"source_directory_images = \\\"/data/jiayuan/BDDcoco/yolo_v8/images\\\"\\n\",\n    \"source_directory_labels = \\\"/data/jiayuan/BDDcoco/yolo_v8/labels\\\"\\n\",\n    \"destination_directory_images = \\\"/data/jiayuan/BDDcoco/yolo_v8_toy/images\\\"\\n\",\n    \"destination_directory_labels = \\\"/data/jiayuan/BDDcoco/yolo_v8_toy/labels\\\"\\n\",\n    \"\\n\",\n    \"# 你想从中选择文件的子目录，以及每个子目录下要选择的文件数量\\n\",\n    \"categories = ['train2017', 'val2017']\\n\",\n    \"num_of_files = {'train2017': 100, 'val2017': 10}\\n\",\n    \"\\n\",\n    \"# 选择并复制.jpg和.txt文件\\n\",\n    \"select_and_copy_files(source_directory_images, source_directory_labels, destination_directory_images, destination_directory_labels, num_of_files, categories)\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"3193eea8\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python [conda env:yolo8]\",\n   \"language\": \"python\",\n   \"name\": \"conda-env-yolo8-py\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.7.16\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
  },
  {
    "path": "ultralytics/datasets/Argoverse.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/ by Argo AI\n# Example usage: yolo train data=Argoverse.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── Argoverse  ← downloads here (31.3 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/Argoverse  # dataset root dir\ntrain: Argoverse-1.1/images/train/  # train images (relative to 'path') 39384 images\nval: Argoverse-1.1/images/val/  # val images (relative to 'path') 15062 images\ntest: Argoverse-1.1/images/test/  # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview\n\n# Classes\nnames:\n  0: person\n  1: bicycle\n  2: car\n  3: motorcycle\n  4: bus\n  5: truck\n  6: traffic_light\n  7: stop_sign\n\n\n# Download script/URL (optional) ---------------------------------------------------------------------------------------\ndownload: |\n  import json\n  from tqdm import tqdm\n  from ultralytics.yolo.utils.downloads import download\n  from pathlib import Path\n\n  def argoverse2yolo(set):\n      labels = {}\n      a = json.load(open(set, \"rb\"))\n      for annot in tqdm(a['annotations'], desc=f\"Converting {set} to YOLOv5 format...\"):\n          img_id = annot['image_id']\n          img_name = a['images'][img_id]['name']\n          img_label_name = f'{img_name[:-3]}txt'\n\n          cls = annot['category_id']  # instance class id\n          x_center, y_center, width, height = annot['bbox']\n          x_center = (x_center + width / 2) / 1920.0  # offset and scale\n          y_center = (y_center + height / 2) / 1200.0  # offset and scale\n          width /= 1920.0  # scale\n          height /= 1200.0  # scale\n\n          img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']]\n          if not img_dir.exists():\n              img_dir.mkdir(parents=True, exist_ok=True)\n\n          k = str(img_dir / img_label_name)\n          if k not in labels:\n              labels[k] = []\n          labels[k].append(f\"{cls} {x_center} {y_center} {width} {height}\\n\")\n\n      for k in labels:\n          with open(k, \"w\") as f:\n              f.writelines(labels[k])\n\n\n  # Download\n  dir = Path(yaml['path'])  # dataset root dir\n  urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip']\n  download(urls, dir=dir)\n\n  # Convert\n  annotations_dir = 'Argoverse-HD/annotations/'\n  (dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images')  # rename 'tracking' to 'images'\n  for d in \"train.json\", \"val.json\":\n      argoverse2yolo(dir / annotations_dir / d)  # convert VisDrone annotations to YOLO labels\n"
  },
  {
    "path": "ultralytics/datasets/GlobalWheat2020.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Global Wheat 2020 dataset http://www.global-wheat.com/ by University of Saskatchewan\n# Example usage: yolo train data=GlobalWheat2020.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── GlobalWheat2020  ← downloads here (7.0 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/GlobalWheat2020  # dataset root dir\ntrain: # train images (relative to 'path') 3422 images\n  - images/arvalis_1\n  - images/arvalis_2\n  - images/arvalis_3\n  - images/ethz_1\n  - images/rres_1\n  - images/inrae_1\n  - images/usask_1\nval: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1)\n  - images/ethz_1\ntest: # test images (optional) 1276 images\n  - images/utokyo_1\n  - images/utokyo_2\n  - images/nau_1\n  - images/uq_1\n\n# Classes\nnames:\n  0: wheat_head\n\n\n# Download script/URL (optional) ---------------------------------------------------------------------------------------\ndownload: |\n  from ultralytics.yolo.utils.downloads import download\n  from pathlib import Path\n\n  # Download\n  dir = Path(yaml['path'])  # dataset root dir\n  urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip',\n          'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip']\n  download(urls, dir=dir)\n\n  # Make Directories\n  for p in 'annotations', 'images', 'labels':\n      (dir / p).mkdir(parents=True, exist_ok=True)\n\n  # Move\n  for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \\\n           'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1':\n      (dir / p).rename(dir / 'images' / p)  # move to /images\n      f = (dir / p).with_suffix('.json')  # json file\n      if f.exists():\n          f.rename((dir / 'annotations' / p).with_suffix('.json'))  # move to /annotations\n"
  },
  {
    "path": "ultralytics/datasets/ImageNet.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# ImageNet-1k dataset https://www.image-net.org/index.php by Stanford University\n# Simplified class names from https://github.com/anishathalye/imagenet-simple-labels\n# Example usage: yolo train task=classify data=imagenet\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── imagenet  ← downloads here (144 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/imagenet  # dataset root dir\ntrain: train  # train images (relative to 'path') 1281167 images\nval: val  # val images (relative to 'path') 50000 images\ntest:  # test images (optional)\n\n# Classes\nnames:\n  0: tench\n  1: goldfish\n  2: great white shark\n  3: tiger shark\n  4: hammerhead shark\n  5: electric ray\n  6: stingray\n  7: cock\n  8: hen\n  9: ostrich\n  10: brambling\n  11: goldfinch\n  12: house finch\n  13: junco\n  14: indigo bunting\n  15: American robin\n  16: bulbul\n  17: jay\n  18: magpie\n  19: chickadee\n  20: American dipper\n  21: kite\n  22: bald eagle\n  23: vulture\n  24: great grey owl\n  25: fire salamander\n  26: smooth newt\n  27: newt\n  28: spotted salamander\n  29: axolotl\n  30: American bullfrog\n  31: tree frog\n  32: tailed frog\n  33: loggerhead sea turtle\n  34: leatherback sea turtle\n  35: mud turtle\n  36: terrapin\n  37: box turtle\n  38: banded gecko\n  39: green iguana\n  40: Carolina anole\n  41: desert grassland whiptail lizard\n  42: agama\n  43: frilled-necked lizard\n  44: alligator lizard\n  45: Gila monster\n  46: European green lizard\n  47: chameleon\n  48: Komodo dragon\n  49: Nile crocodile\n  50: American alligator\n  51: triceratops\n  52: worm snake\n  53: ring-necked snake\n  54: eastern hog-nosed snake\n  55: smooth green snake\n  56: kingsnake\n  57: garter snake\n  58: water snake\n  59: vine snake\n  60: night snake\n  61: boa constrictor\n  62: African rock python\n  63: Indian cobra\n  64: green mamba\n  65: sea snake\n  66: Saharan horned viper\n  67: eastern diamondback rattlesnake\n  68: sidewinder\n  69: trilobite\n  70: harvestman\n  71: scorpion\n  72: yellow garden spider\n  73: barn spider\n  74: European garden spider\n  75: southern black widow\n  76: tarantula\n  77: wolf spider\n  78: tick\n  79: centipede\n  80: black grouse\n  81: ptarmigan\n  82: ruffed grouse\n  83: prairie grouse\n  84: peacock\n  85: quail\n  86: partridge\n  87: grey parrot\n  88: macaw\n  89: sulphur-crested cockatoo\n  90: lorikeet\n  91: coucal\n  92: bee eater\n  93: hornbill\n  94: hummingbird\n  95: jacamar\n  96: toucan\n  97: duck\n  98: red-breasted merganser\n  99: goose\n  100: black swan\n  101: tusker\n  102: echidna\n  103: platypus\n  104: wallaby\n  105: koala\n  106: wombat\n  107: jellyfish\n  108: sea anemone\n  109: brain coral\n  110: flatworm\n  111: nematode\n  112: conch\n  113: snail\n  114: slug\n  115: sea slug\n  116: chiton\n  117: chambered nautilus\n  118: Dungeness crab\n  119: rock crab\n  120: fiddler crab\n  121: red king crab\n  122: American lobster\n  123: spiny lobster\n  124: crayfish\n  125: hermit crab\n  126: isopod\n  127: white stork\n  128: black stork\n  129: spoonbill\n  130: flamingo\n  131: little blue heron\n  132: great egret\n  133: bittern\n  134: crane (bird)\n  135: limpkin\n  136: common gallinule\n  137: American coot\n  138: bustard\n  139: ruddy turnstone\n  140: dunlin\n  141: common redshank\n  142: dowitcher\n  143: oystercatcher\n  144: pelican\n  145: king penguin\n  146: albatross\n  147: grey whale\n  148: killer whale\n  149: dugong\n  150: sea lion\n  151: Chihuahua\n  152: Japanese Chin\n  153: Maltese\n  154: Pekingese\n  155: Shih Tzu\n  156: King Charles Spaniel\n  157: Papillon\n  158: toy terrier\n  159: Rhodesian Ridgeback\n  160: Afghan Hound\n  161: Basset Hound\n  162: Beagle\n  163: Bloodhound\n  164: Bluetick Coonhound\n  165: Black and Tan Coonhound\n  166: Treeing Walker Coonhound\n  167: English foxhound\n  168: Redbone Coonhound\n  169: borzoi\n  170: Irish Wolfhound\n  171: Italian Greyhound\n  172: Whippet\n  173: Ibizan Hound\n  174: Norwegian Elkhound\n  175: Otterhound\n  176: Saluki\n  177: Scottish Deerhound\n  178: Weimaraner\n  179: Staffordshire Bull Terrier\n  180: American Staffordshire Terrier\n  181: Bedlington Terrier\n  182: Border Terrier\n  183: Kerry Blue Terrier\n  184: Irish Terrier\n  185: Norfolk Terrier\n  186: Norwich Terrier\n  187: Yorkshire Terrier\n  188: Wire Fox Terrier\n  189: Lakeland Terrier\n  190: Sealyham Terrier\n  191: Airedale Terrier\n  192: Cairn Terrier\n  193: Australian Terrier\n  194: Dandie Dinmont Terrier\n  195: Boston Terrier\n  196: Miniature Schnauzer\n  197: Giant Schnauzer\n  198: Standard Schnauzer\n  199: Scottish Terrier\n  200: Tibetan Terrier\n  201: Australian Silky Terrier\n  202: Soft-coated Wheaten Terrier\n  203: West Highland White Terrier\n  204: Lhasa Apso\n  205: Flat-Coated Retriever\n  206: Curly-coated Retriever\n  207: Golden Retriever\n  208: Labrador Retriever\n  209: Chesapeake Bay Retriever\n  210: German Shorthaired Pointer\n  211: Vizsla\n  212: English Setter\n  213: Irish Setter\n  214: Gordon Setter\n  215: Brittany\n  216: Clumber Spaniel\n  217: English Springer Spaniel\n  218: Welsh Springer Spaniel\n  219: Cocker Spaniels\n  220: Sussex Spaniel\n  221: Irish Water Spaniel\n  222: Kuvasz\n  223: Schipperke\n  224: Groenendael\n  225: Malinois\n  226: Briard\n  227: Australian Kelpie\n  228: Komondor\n  229: Old English Sheepdog\n  230: Shetland Sheepdog\n  231: collie\n  232: Border Collie\n  233: Bouvier des Flandres\n  234: Rottweiler\n  235: German Shepherd Dog\n  236: Dobermann\n  237: Miniature Pinscher\n  238: Greater Swiss Mountain Dog\n  239: Bernese Mountain Dog\n  240: Appenzeller Sennenhund\n  241: Entlebucher Sennenhund\n  242: Boxer\n  243: Bullmastiff\n  244: Tibetan Mastiff\n  245: French Bulldog\n  246: Great Dane\n  247: St. Bernard\n  248: husky\n  249: Alaskan Malamute\n  250: Siberian Husky\n  251: Dalmatian\n  252: Affenpinscher\n  253: Basenji\n  254: pug\n  255: Leonberger\n  256: Newfoundland\n  257: Pyrenean Mountain Dog\n  258: Samoyed\n  259: Pomeranian\n  260: Chow Chow\n  261: Keeshond\n  262: Griffon Bruxellois\n  263: Pembroke Welsh Corgi\n  264: Cardigan Welsh Corgi\n  265: Toy Poodle\n  266: Miniature Poodle\n  267: Standard Poodle\n  268: Mexican hairless dog\n  269: grey wolf\n  270: Alaskan tundra wolf\n  271: red wolf\n  272: coyote\n  273: dingo\n  274: dhole\n  275: African wild dog\n  276: hyena\n  277: red fox\n  278: kit fox\n  279: Arctic fox\n  280: grey fox\n  281: tabby cat\n  282: tiger cat\n  283: Persian cat\n  284: Siamese cat\n  285: Egyptian Mau\n  286: cougar\n  287: lynx\n  288: leopard\n  289: snow leopard\n  290: jaguar\n  291: lion\n  292: tiger\n  293: cheetah\n  294: brown bear\n  295: American black bear\n  296: polar bear\n  297: sloth bear\n  298: mongoose\n  299: meerkat\n  300: tiger beetle\n  301: ladybug\n  302: ground beetle\n  303: longhorn beetle\n  304: leaf beetle\n  305: dung beetle\n  306: rhinoceros beetle\n  307: weevil\n  308: fly\n  309: bee\n  310: ant\n  311: grasshopper\n  312: cricket\n  313: stick insect\n  314: cockroach\n  315: mantis\n  316: cicada\n  317: leafhopper\n  318: lacewing\n  319: dragonfly\n  320: damselfly\n  321: red admiral\n  322: ringlet\n  323: monarch butterfly\n  324: small white\n  325: sulphur butterfly\n  326: gossamer-winged butterfly\n  327: starfish\n  328: sea urchin\n  329: sea cucumber\n  330: cottontail rabbit\n  331: hare\n  332: Angora rabbit\n  333: hamster\n  334: porcupine\n  335: fox squirrel\n  336: marmot\n  337: beaver\n  338: guinea pig\n  339: common sorrel\n  340: zebra\n  341: pig\n  342: wild boar\n  343: warthog\n  344: hippopotamus\n  345: ox\n  346: water buffalo\n  347: bison\n  348: ram\n  349: bighorn sheep\n  350: Alpine ibex\n  351: hartebeest\n  352: impala\n  353: gazelle\n  354: dromedary\n  355: llama\n  356: weasel\n  357: mink\n  358: European polecat\n  359: black-footed ferret\n  360: otter\n  361: skunk\n  362: badger\n  363: armadillo\n  364: three-toed sloth\n  365: orangutan\n  366: gorilla\n  367: chimpanzee\n  368: gibbon\n  369: siamang\n  370: guenon\n  371: patas monkey\n  372: baboon\n  373: macaque\n  374: langur\n  375: black-and-white colobus\n  376: proboscis monkey\n  377: marmoset\n  378: white-headed capuchin\n  379: howler monkey\n  380: titi\n  381: Geoffroy's spider monkey\n  382: common squirrel monkey\n  383: ring-tailed lemur\n  384: indri\n  385: Asian elephant\n  386: African bush elephant\n  387: red panda\n  388: giant panda\n  389: snoek\n  390: eel\n  391: coho salmon\n  392: rock beauty\n  393: clownfish\n  394: sturgeon\n  395: garfish\n  396: lionfish\n  397: pufferfish\n  398: abacus\n  399: abaya\n  400: academic gown\n  401: accordion\n  402: acoustic guitar\n  403: aircraft carrier\n  404: airliner\n  405: airship\n  406: altar\n  407: ambulance\n  408: amphibious vehicle\n  409: analog clock\n  410: apiary\n  411: apron\n  412: waste container\n  413: assault rifle\n  414: backpack\n  415: bakery\n  416: balance beam\n  417: balloon\n  418: ballpoint pen\n  419: Band-Aid\n  420: banjo\n  421: baluster\n  422: barbell\n  423: barber chair\n  424: barbershop\n  425: barn\n  426: barometer\n  427: barrel\n  428: wheelbarrow\n  429: baseball\n  430: basketball\n  431: bassinet\n  432: bassoon\n  433: swimming cap\n  434: bath towel\n  435: bathtub\n  436: station wagon\n  437: lighthouse\n  438: beaker\n  439: military cap\n  440: beer bottle\n  441: beer glass\n  442: bell-cot\n  443: bib\n  444: tandem bicycle\n  445: bikini\n  446: ring binder\n  447: binoculars\n  448: birdhouse\n  449: boathouse\n  450: bobsleigh\n  451: bolo tie\n  452: poke bonnet\n  453: bookcase\n  454: bookstore\n  455: bottle cap\n  456: bow\n  457: bow tie\n  458: brass\n  459: bra\n  460: breakwater\n  461: breastplate\n  462: broom\n  463: bucket\n  464: buckle\n  465: bulletproof vest\n  466: high-speed train\n  467: butcher shop\n  468: taxicab\n  469: cauldron\n  470: candle\n  471: cannon\n  472: canoe\n  473: can opener\n  474: cardigan\n  475: car mirror\n  476: carousel\n  477: tool kit\n  478: carton\n  479: car wheel\n  480: automated teller machine\n  481: cassette\n  482: cassette player\n  483: castle\n  484: catamaran\n  485: CD player\n  486: cello\n  487: mobile phone\n  488: chain\n  489: chain-link fence\n  490: chain mail\n  491: chainsaw\n  492: chest\n  493: chiffonier\n  494: chime\n  495: china cabinet\n  496: Christmas stocking\n  497: church\n  498: movie theater\n  499: cleaver\n  500: cliff dwelling\n  501: cloak\n  502: clogs\n  503: cocktail shaker\n  504: coffee mug\n  505: coffeemaker\n  506: coil\n  507: combination lock\n  508: computer keyboard\n  509: confectionery store\n  510: container ship\n  511: convertible\n  512: corkscrew\n  513: cornet\n  514: cowboy boot\n  515: cowboy hat\n  516: cradle\n  517: crane (machine)\n  518: crash helmet\n  519: crate\n  520: infant bed\n  521: Crock Pot\n  522: croquet ball\n  523: crutch\n  524: cuirass\n  525: dam\n  526: desk\n  527: desktop computer\n  528: rotary dial telephone\n  529: diaper\n  530: digital clock\n  531: digital watch\n  532: dining table\n  533: dishcloth\n  534: dishwasher\n  535: disc brake\n  536: dock\n  537: dog sled\n  538: dome\n  539: doormat\n  540: drilling rig\n  541: drum\n  542: drumstick\n  543: dumbbell\n  544: Dutch oven\n  545: electric fan\n  546: electric guitar\n  547: electric locomotive\n  548: entertainment center\n  549: envelope\n  550: espresso machine\n  551: face powder\n  552: feather boa\n  553: filing cabinet\n  554: fireboat\n  555: fire engine\n  556: fire screen sheet\n  557: flagpole\n  558: flute\n  559: folding chair\n  560: football helmet\n  561: forklift\n  562: fountain\n  563: fountain pen\n  564: four-poster bed\n  565: freight car\n  566: French horn\n  567: frying pan\n  568: fur coat\n  569: garbage truck\n  570: gas mask\n  571: gas pump\n  572: goblet\n  573: go-kart\n  574: golf ball\n  575: golf cart\n  576: gondola\n  577: gong\n  578: gown\n  579: grand piano\n  580: greenhouse\n  581: grille\n  582: grocery store\n  583: guillotine\n  584: barrette\n  585: hair spray\n  586: half-track\n  587: hammer\n  588: hamper\n  589: hair dryer\n  590: hand-held computer\n  591: handkerchief\n  592: hard disk drive\n  593: harmonica\n  594: harp\n  595: harvester\n  596: hatchet\n  597: holster\n  598: home theater\n  599: honeycomb\n  600: hook\n  601: hoop skirt\n  602: horizontal bar\n  603: horse-drawn vehicle\n  604: hourglass\n  605: iPod\n  606: clothes iron\n  607: jack-o'-lantern\n  608: jeans\n  609: jeep\n  610: T-shirt\n  611: jigsaw puzzle\n  612: pulled rickshaw\n  613: joystick\n  614: kimono\n  615: knee pad\n  616: knot\n  617: lab coat\n  618: ladle\n  619: lampshade\n  620: laptop computer\n  621: lawn mower\n  622: lens cap\n  623: paper knife\n  624: library\n  625: lifeboat\n  626: lighter\n  627: limousine\n  628: ocean liner\n  629: lipstick\n  630: slip-on shoe\n  631: lotion\n  632: speaker\n  633: loupe\n  634: sawmill\n  635: magnetic compass\n  636: mail bag\n  637: mailbox\n  638: tights\n  639: tank suit\n  640: manhole cover\n  641: maraca\n  642: marimba\n  643: mask\n  644: match\n  645: maypole\n  646: maze\n  647: measuring cup\n  648: medicine chest\n  649: megalith\n  650: microphone\n  651: microwave oven\n  652: military uniform\n  653: milk can\n  654: minibus\n  655: miniskirt\n  656: minivan\n  657: missile\n  658: mitten\n  659: mixing bowl\n  660: mobile home\n  661: Model T\n  662: modem\n  663: monastery\n  664: monitor\n  665: moped\n  666: mortar\n  667: square academic cap\n  668: mosque\n  669: mosquito net\n  670: scooter\n  671: mountain bike\n  672: tent\n  673: computer mouse\n  674: mousetrap\n  675: moving van\n  676: muzzle\n  677: nail\n  678: neck brace\n  679: necklace\n  680: nipple\n  681: notebook computer\n  682: obelisk\n  683: oboe\n  684: ocarina\n  685: odometer\n  686: oil filter\n  687: organ\n  688: oscilloscope\n  689: overskirt\n  690: bullock cart\n  691: oxygen mask\n  692: packet\n  693: paddle\n  694: paddle wheel\n  695: padlock\n  696: paintbrush\n  697: pajamas\n  698: palace\n  699: pan flute\n  700: paper towel\n  701: parachute\n  702: parallel bars\n  703: park bench\n  704: parking meter\n  705: passenger car\n  706: patio\n  707: payphone\n  708: pedestal\n  709: pencil case\n  710: pencil sharpener\n  711: perfume\n  712: Petri dish\n  713: photocopier\n  714: plectrum\n  715: Pickelhaube\n  716: picket fence\n  717: pickup truck\n  718: pier\n  719: piggy bank\n  720: pill bottle\n  721: pillow\n  722: ping-pong ball\n  723: pinwheel\n  724: pirate ship\n  725: pitcher\n  726: hand plane\n  727: planetarium\n  728: plastic bag\n  729: plate rack\n  730: plow\n  731: plunger\n  732: Polaroid camera\n  733: pole\n  734: police van\n  735: poncho\n  736: billiard table\n  737: soda bottle\n  738: pot\n  739: potter's wheel\n  740: power drill\n  741: prayer rug\n  742: printer\n  743: prison\n  744: projectile\n  745: projector\n  746: hockey puck\n  747: punching bag\n  748: purse\n  749: quill\n  750: quilt\n  751: race car\n  752: racket\n  753: radiator\n  754: radio\n  755: radio telescope\n  756: rain barrel\n  757: recreational vehicle\n  758: reel\n  759: reflex camera\n  760: refrigerator\n  761: remote control\n  762: restaurant\n  763: revolver\n  764: rifle\n  765: rocking chair\n  766: rotisserie\n  767: eraser\n  768: rugby ball\n  769: ruler\n  770: running shoe\n  771: safe\n  772: safety pin\n  773: salt shaker\n  774: sandal\n  775: sarong\n  776: saxophone\n  777: scabbard\n  778: weighing scale\n  779: school bus\n  780: schooner\n  781: scoreboard\n  782: CRT screen\n  783: screw\n  784: screwdriver\n  785: seat belt\n  786: sewing machine\n  787: shield\n  788: shoe store\n  789: shoji\n  790: shopping basket\n  791: shopping cart\n  792: shovel\n  793: shower cap\n  794: shower curtain\n  795: ski\n  796: ski mask\n  797: sleeping bag\n  798: slide rule\n  799: sliding door\n  800: slot machine\n  801: snorkel\n  802: snowmobile\n  803: snowplow\n  804: soap dispenser\n  805: soccer ball\n  806: sock\n  807: solar thermal collector\n  808: sombrero\n  809: soup bowl\n  810: space bar\n  811: space heater\n  812: space shuttle\n  813: spatula\n  814: motorboat\n  815: spider web\n  816: spindle\n  817: sports car\n  818: spotlight\n  819: stage\n  820: steam locomotive\n  821: through arch bridge\n  822: steel drum\n  823: stethoscope\n  824: scarf\n  825: stone wall\n  826: stopwatch\n  827: stove\n  828: strainer\n  829: tram\n  830: stretcher\n  831: couch\n  832: stupa\n  833: submarine\n  834: suit\n  835: sundial\n  836: sunglass\n  837: sunglasses\n  838: sunscreen\n  839: suspension bridge\n  840: mop\n  841: sweatshirt\n  842: swimsuit\n  843: swing\n  844: switch\n  845: syringe\n  846: table lamp\n  847: tank\n  848: tape player\n  849: teapot\n  850: teddy bear\n  851: television\n  852: tennis ball\n  853: thatched roof\n  854: front curtain\n  855: thimble\n  856: threshing machine\n  857: throne\n  858: tile roof\n  859: toaster\n  860: tobacco shop\n  861: toilet seat\n  862: torch\n  863: totem pole\n  864: tow truck\n  865: toy store\n  866: tractor\n  867: semi-trailer truck\n  868: tray\n  869: trench coat\n  870: tricycle\n  871: trimaran\n  872: tripod\n  873: triumphal arch\n  874: trolleybus\n  875: trombone\n  876: tub\n  877: turnstile\n  878: typewriter keyboard\n  879: umbrella\n  880: unicycle\n  881: upright piano\n  882: vacuum cleaner\n  883: vase\n  884: vault\n  885: velvet\n  886: vending machine\n  887: vestment\n  888: viaduct\n  889: violin\n  890: volleyball\n  891: waffle iron\n  892: wall clock\n  893: wallet\n  894: wardrobe\n  895: military aircraft\n  896: sink\n  897: washing machine\n  898: water bottle\n  899: water jug\n  900: water tower\n  901: whiskey jug\n  902: whistle\n  903: wig\n  904: window screen\n  905: window shade\n  906: Windsor tie\n  907: wine bottle\n  908: wing\n  909: wok\n  910: wooden spoon\n  911: wool\n  912: split-rail fence\n  913: shipwreck\n  914: yawl\n  915: yurt\n  916: website\n  917: comic book\n  918: crossword\n  919: traffic sign\n  920: traffic light\n  921: dust jacket\n  922: menu\n  923: plate\n  924: guacamole\n  925: consomme\n  926: hot pot\n  927: trifle\n  928: ice cream\n  929: ice pop\n  930: baguette\n  931: bagel\n  932: pretzel\n  933: cheeseburger\n  934: hot dog\n  935: mashed potato\n  936: cabbage\n  937: broccoli\n  938: cauliflower\n  939: zucchini\n  940: spaghetti squash\n  941: acorn squash\n  942: butternut squash\n  943: cucumber\n  944: artichoke\n  945: bell pepper\n  946: cardoon\n  947: mushroom\n  948: Granny Smith\n  949: strawberry\n  950: orange\n  951: lemon\n  952: fig\n  953: pineapple\n  954: banana\n  955: jackfruit\n  956: custard apple\n  957: pomegranate\n  958: hay\n  959: carbonara\n  960: chocolate syrup\n  961: dough\n  962: meatloaf\n  963: pizza\n  964: pot pie\n  965: burrito\n  966: red wine\n  967: espresso\n  968: cup\n  969: eggnog\n  970: alp\n  971: bubble\n  972: cliff\n  973: coral reef\n  974: geyser\n  975: lakeshore\n  976: promontory\n  977: shoal\n  978: seashore\n  979: valley\n  980: volcano\n  981: baseball player\n  982: bridegroom\n  983: scuba diver\n  984: rapeseed\n  985: daisy\n  986: yellow lady's slipper\n  987: corn\n  988: acorn\n  989: rose hip\n  990: horse chestnut seed\n  991: coral fungus\n  992: agaric\n  993: gyromitra\n  994: stinkhorn mushroom\n  995: earth star\n  996: hen-of-the-woods\n  997: bolete\n  998: ear\n  999: toilet paper\n\n# Imagenet class codes to human-readable names\nmap:\n  n01440764: tench\n  n01443537: goldfish\n  n01484850: great_white_shark\n  n01491361: tiger_shark\n  n01494475: hammerhead\n  n01496331: electric_ray\n  n01498041: stingray\n  n01514668: cock\n  n01514859: hen\n  n01518878: ostrich\n  n01530575: brambling\n  n01531178: goldfinch\n  n01532829: house_finch\n  n01534433: junco\n  n01537544: indigo_bunting\n  n01558993: robin\n  n01560419: bulbul\n  n01580077: jay\n  n01582220: magpie\n  n01592084: chickadee\n  n01601694: water_ouzel\n  n01608432: kite\n  n01614925: bald_eagle\n  n01616318: vulture\n  n01622779: great_grey_owl\n  n01629819: European_fire_salamander\n  n01630670: common_newt\n  n01631663: eft\n  n01632458: spotted_salamander\n  n01632777: axolotl\n  n01641577: bullfrog\n  n01644373: tree_frog\n  n01644900: tailed_frog\n  n01664065: loggerhead\n  n01665541: leatherback_turtle\n  n01667114: mud_turtle\n  n01667778: terrapin\n  n01669191: box_turtle\n  n01675722: banded_gecko\n  n01677366: common_iguana\n  n01682714: American_chameleon\n  n01685808: whiptail\n  n01687978: agama\n  n01688243: frilled_lizard\n  n01689811: alligator_lizard\n  n01692333: Gila_monster\n  n01693334: green_lizard\n  n01694178: African_chameleon\n  n01695060: Komodo_dragon\n  n01697457: African_crocodile\n  n01698640: American_alligator\n  n01704323: triceratops\n  n01728572: thunder_snake\n  n01728920: ringneck_snake\n  n01729322: hognose_snake\n  n01729977: green_snake\n  n01734418: king_snake\n  n01735189: garter_snake\n  n01737021: water_snake\n  n01739381: vine_snake\n  n01740131: night_snake\n  n01742172: boa_constrictor\n  n01744401: rock_python\n  n01748264: Indian_cobra\n  n01749939: green_mamba\n  n01751748: sea_snake\n  n01753488: horned_viper\n  n01755581: diamondback\n  n01756291: sidewinder\n  n01768244: trilobite\n  n01770081: harvestman\n  n01770393: scorpion\n  n01773157: black_and_gold_garden_spider\n  n01773549: barn_spider\n  n01773797: garden_spider\n  n01774384: black_widow\n  n01774750: tarantula\n  n01775062: wolf_spider\n  n01776313: tick\n  n01784675: centipede\n  n01795545: black_grouse\n  n01796340: ptarmigan\n  n01797886: ruffed_grouse\n  n01798484: prairie_chicken\n  n01806143: peacock\n  n01806567: quail\n  n01807496: partridge\n  n01817953: African_grey\n  n01818515: macaw\n  n01819313: sulphur-crested_cockatoo\n  n01820546: lorikeet\n  n01824575: coucal\n  n01828970: bee_eater\n  n01829413: hornbill\n  n01833805: hummingbird\n  n01843065: jacamar\n  n01843383: toucan\n  n01847000: drake\n  n01855032: red-breasted_merganser\n  n01855672: goose\n  n01860187: black_swan\n  n01871265: tusker\n  n01872401: echidna\n  n01873310: platypus\n  n01877812: wallaby\n  n01882714: koala\n  n01883070: wombat\n  n01910747: jellyfish\n  n01914609: sea_anemone\n  n01917289: brain_coral\n  n01924916: flatworm\n  n01930112: nematode\n  n01943899: conch\n  n01944390: snail\n  n01945685: slug\n  n01950731: sea_slug\n  n01955084: chiton\n  n01968897: chambered_nautilus\n  n01978287: Dungeness_crab\n  n01978455: rock_crab\n  n01980166: fiddler_crab\n  n01981276: king_crab\n  n01983481: American_lobster\n  n01984695: spiny_lobster\n  n01985128: crayfish\n  n01986214: hermit_crab\n  n01990800: isopod\n  n02002556: white_stork\n  n02002724: black_stork\n  n02006656: spoonbill\n  n02007558: flamingo\n  n02009229: little_blue_heron\n  n02009912: American_egret\n  n02011460: bittern\n  n02012849: crane_(bird)\n  n02013706: limpkin\n  n02017213: European_gallinule\n  n02018207: American_coot\n  n02018795: bustard\n  n02025239: ruddy_turnstone\n  n02027492: red-backed_sandpiper\n  n02028035: redshank\n  n02033041: dowitcher\n  n02037110: oystercatcher\n  n02051845: pelican\n  n02056570: king_penguin\n  n02058221: albatross\n  n02066245: grey_whale\n  n02071294: killer_whale\n  n02074367: dugong\n  n02077923: sea_lion\n  n02085620: Chihuahua\n  n02085782: Japanese_spaniel\n  n02085936: Maltese_dog\n  n02086079: Pekinese\n  n02086240: Shih-Tzu\n  n02086646: Blenheim_spaniel\n  n02086910: papillon\n  n02087046: toy_terrier\n  n02087394: Rhodesian_ridgeback\n  n02088094: Afghan_hound\n  n02088238: basset\n  n02088364: beagle\n  n02088466: bloodhound\n  n02088632: bluetick\n  n02089078: black-and-tan_coonhound\n  n02089867: Walker_hound\n  n02089973: English_foxhound\n  n02090379: redbone\n  n02090622: borzoi\n  n02090721: Irish_wolfhound\n  n02091032: Italian_greyhound\n  n02091134: whippet\n  n02091244: Ibizan_hound\n  n02091467: Norwegian_elkhound\n  n02091635: otterhound\n  n02091831: Saluki\n  n02092002: Scottish_deerhound\n  n02092339: Weimaraner\n  n02093256: Staffordshire_bullterrier\n  n02093428: American_Staffordshire_terrier\n  n02093647: Bedlington_terrier\n  n02093754: Border_terrier\n  n02093859: Kerry_blue_terrier\n  n02093991: Irish_terrier\n  n02094114: Norfolk_terrier\n  n02094258: Norwich_terrier\n  n02094433: Yorkshire_terrier\n  n02095314: wire-haired_fox_terrier\n  n02095570: Lakeland_terrier\n  n02095889: Sealyham_terrier\n  n02096051: Airedale\n  n02096177: cairn\n  n02096294: Australian_terrier\n  n02096437: Dandie_Dinmont\n  n02096585: Boston_bull\n  n02097047: miniature_schnauzer\n  n02097130: giant_schnauzer\n  n02097209: standard_schnauzer\n  n02097298: Scotch_terrier\n  n02097474: Tibetan_terrier\n  n02097658: silky_terrier\n  n02098105: soft-coated_wheaten_terrier\n  n02098286: West_Highland_white_terrier\n  n02098413: Lhasa\n  n02099267: flat-coated_retriever\n  n02099429: curly-coated_retriever\n  n02099601: golden_retriever\n  n02099712: Labrador_retriever\n  n02099849: Chesapeake_Bay_retriever\n  n02100236: German_short-haired_pointer\n  n02100583: vizsla\n  n02100735: English_setter\n  n02100877: Irish_setter\n  n02101006: Gordon_setter\n  n02101388: Brittany_spaniel\n  n02101556: clumber\n  n02102040: English_springer\n  n02102177: Welsh_springer_spaniel\n  n02102318: cocker_spaniel\n  n02102480: Sussex_spaniel\n  n02102973: Irish_water_spaniel\n  n02104029: kuvasz\n  n02104365: schipperke\n  n02105056: groenendael\n  n02105162: malinois\n  n02105251: briard\n  n02105412: kelpie\n  n02105505: komondor\n  n02105641: Old_English_sheepdog\n  n02105855: Shetland_sheepdog\n  n02106030: collie\n  n02106166: Border_collie\n  n02106382: Bouvier_des_Flandres\n  n02106550: Rottweiler\n  n02106662: German_shepherd\n  n02107142: Doberman\n  n02107312: miniature_pinscher\n  n02107574: Greater_Swiss_Mountain_dog\n  n02107683: Bernese_mountain_dog\n  n02107908: Appenzeller\n  n02108000: EntleBucher\n  n02108089: boxer\n  n02108422: bull_mastiff\n  n02108551: Tibetan_mastiff\n  n02108915: French_bulldog\n  n02109047: Great_Dane\n  n02109525: Saint_Bernard\n  n02109961: Eskimo_dog\n  n02110063: malamute\n  n02110185: Siberian_husky\n  n02110341: dalmatian\n  n02110627: affenpinscher\n  n02110806: basenji\n  n02110958: pug\n  n02111129: Leonberg\n  n02111277: Newfoundland\n  n02111500: Great_Pyrenees\n  n02111889: Samoyed\n  n02112018: Pomeranian\n  n02112137: chow\n  n02112350: keeshond\n  n02112706: Brabancon_griffon\n  n02113023: Pembroke\n  n02113186: Cardigan\n  n02113624: toy_poodle\n  n02113712: miniature_poodle\n  n02113799: standard_poodle\n  n02113978: Mexican_hairless\n  n02114367: timber_wolf\n  n02114548: white_wolf\n  n02114712: red_wolf\n  n02114855: coyote\n  n02115641: dingo\n  n02115913: dhole\n  n02116738: African_hunting_dog\n  n02117135: hyena\n  n02119022: red_fox\n  n02119789: kit_fox\n  n02120079: Arctic_fox\n  n02120505: grey_fox\n  n02123045: tabby\n  n02123159: tiger_cat\n  n02123394: Persian_cat\n  n02123597: Siamese_cat\n  n02124075: Egyptian_cat\n  n02125311: cougar\n  n02127052: lynx\n  n02128385: leopard\n  n02128757: snow_leopard\n  n02128925: jaguar\n  n02129165: lion\n  n02129604: tiger\n  n02130308: cheetah\n  n02132136: brown_bear\n  n02133161: American_black_bear\n  n02134084: ice_bear\n  n02134418: sloth_bear\n  n02137549: mongoose\n  n02138441: meerkat\n  n02165105: tiger_beetle\n  n02165456: ladybug\n  n02167151: ground_beetle\n  n02168699: long-horned_beetle\n  n02169497: leaf_beetle\n  n02172182: dung_beetle\n  n02174001: rhinoceros_beetle\n  n02177972: weevil\n  n02190166: fly\n  n02206856: bee\n  n02219486: ant\n  n02226429: grasshopper\n  n02229544: cricket\n  n02231487: walking_stick\n  n02233338: cockroach\n  n02236044: mantis\n  n02256656: cicada\n  n02259212: leafhopper\n  n02264363: lacewing\n  n02268443: dragonfly\n  n02268853: damselfly\n  n02276258: admiral\n  n02277742: ringlet\n  n02279972: monarch\n  n02280649: cabbage_butterfly\n  n02281406: sulphur_butterfly\n  n02281787: lycaenid\n  n02317335: starfish\n  n02319095: sea_urchin\n  n02321529: sea_cucumber\n  n02325366: wood_rabbit\n  n02326432: hare\n  n02328150: Angora\n  n02342885: hamster\n  n02346627: porcupine\n  n02356798: fox_squirrel\n  n02361337: marmot\n  n02363005: beaver\n  n02364673: guinea_pig\n  n02389026: sorrel\n  n02391049: zebra\n  n02395406: hog\n  n02396427: wild_boar\n  n02397096: warthog\n  n02398521: hippopotamus\n  n02403003: ox\n  n02408429: water_buffalo\n  n02410509: bison\n  n02412080: ram\n  n02415577: bighorn\n  n02417914: ibex\n  n02422106: hartebeest\n  n02422699: impala\n  n02423022: gazelle\n  n02437312: Arabian_camel\n  n02437616: llama\n  n02441942: weasel\n  n02442845: mink\n  n02443114: polecat\n  n02443484: black-footed_ferret\n  n02444819: otter\n  n02445715: skunk\n  n02447366: badger\n  n02454379: armadillo\n  n02457408: three-toed_sloth\n  n02480495: orangutan\n  n02480855: gorilla\n  n02481823: chimpanzee\n  n02483362: gibbon\n  n02483708: siamang\n  n02484975: guenon\n  n02486261: patas\n  n02486410: baboon\n  n02487347: macaque\n  n02488291: langur\n  n02488702: colobus\n  n02489166: proboscis_monkey\n  n02490219: marmoset\n  n02492035: capuchin\n  n02492660: howler_monkey\n  n02493509: titi\n  n02493793: spider_monkey\n  n02494079: squirrel_monkey\n  n02497673: Madagascar_cat\n  n02500267: indri\n  n02504013: Indian_elephant\n  n02504458: African_elephant\n  n02509815: lesser_panda\n  n02510455: giant_panda\n  n02514041: barracouta\n  n02526121: eel\n  n02536864: coho\n  n02606052: rock_beauty\n  n02607072: anemone_fish\n  n02640242: sturgeon\n  n02641379: gar\n  n02643566: lionfish\n  n02655020: puffer\n  n02666196: abacus\n  n02667093: abaya\n  n02669723: academic_gown\n  n02672831: accordion\n  n02676566: acoustic_guitar\n  n02687172: aircraft_carrier\n  n02690373: airliner\n  n02692877: airship\n  n02699494: altar\n  n02701002: ambulance\n  n02704792: amphibian\n  n02708093: analog_clock\n  n02727426: apiary\n  n02730930: apron\n  n02747177: ashcan\n  n02749479: assault_rifle\n  n02769748: backpack\n  n02776631: bakery\n  n02777292: balance_beam\n  n02782093: balloon\n  n02783161: ballpoint\n  n02786058: Band_Aid\n  n02787622: banjo\n  n02788148: bannister\n  n02790996: barbell\n  n02791124: barber_chair\n  n02791270: barbershop\n  n02793495: barn\n  n02794156: barometer\n  n02795169: barrel\n  n02797295: barrow\n  n02799071: baseball\n  n02802426: basketball\n  n02804414: bassinet\n  n02804610: bassoon\n  n02807133: bathing_cap\n  n02808304: bath_towel\n  n02808440: bathtub\n  n02814533: beach_wagon\n  n02814860: beacon\n  n02815834: beaker\n  n02817516: bearskin\n  n02823428: beer_bottle\n  n02823750: beer_glass\n  n02825657: bell_cote\n  n02834397: bib\n  n02835271: bicycle-built-for-two\n  n02837789: bikini\n  n02840245: binder\n  n02841315: binoculars\n  n02843684: birdhouse\n  n02859443: boathouse\n  n02860847: bobsled\n  n02865351: bolo_tie\n  n02869837: bonnet\n  n02870880: bookcase\n  n02871525: bookshop\n  n02877765: bottlecap\n  n02879718: bow\n  n02883205: bow_tie\n  n02892201: brass\n  n02892767: brassiere\n  n02894605: breakwater\n  n02895154: breastplate\n  n02906734: broom\n  n02909870: bucket\n  n02910353: buckle\n  n02916936: bulletproof_vest\n  n02917067: bullet_train\n  n02927161: butcher_shop\n  n02930766: cab\n  n02939185: caldron\n  n02948072: candle\n  n02950826: cannon\n  n02951358: canoe\n  n02951585: can_opener\n  n02963159: cardigan\n  n02965783: car_mirror\n  n02966193: carousel\n  n02966687: carpenter's_kit\n  n02971356: carton\n  n02974003: car_wheel\n  n02977058: cash_machine\n  n02978881: cassette\n  n02979186: cassette_player\n  n02980441: castle\n  n02981792: catamaran\n  n02988304: CD_player\n  n02992211: cello\n  n02992529: cellular_telephone\n  n02999410: chain\n  n03000134: chainlink_fence\n  n03000247: chain_mail\n  n03000684: chain_saw\n  n03014705: chest\n  n03016953: chiffonier\n  n03017168: chime\n  n03018349: china_cabinet\n  n03026506: Christmas_stocking\n  n03028079: church\n  n03032252: cinema\n  n03041632: cleaver\n  n03042490: cliff_dwelling\n  n03045698: cloak\n  n03047690: clog\n  n03062245: cocktail_shaker\n  n03063599: coffee_mug\n  n03063689: coffeepot\n  n03065424: coil\n  n03075370: combination_lock\n  n03085013: computer_keyboard\n  n03089624: confectionery\n  n03095699: container_ship\n  n03100240: convertible\n  n03109150: corkscrew\n  n03110669: cornet\n  n03124043: cowboy_boot\n  n03124170: cowboy_hat\n  n03125729: cradle\n  n03126707: crane_(machine)\n  n03127747: crash_helmet\n  n03127925: crate\n  n03131574: crib\n  n03133878: Crock_Pot\n  n03134739: croquet_ball\n  n03141823: crutch\n  n03146219: cuirass\n  n03160309: dam\n  n03179701: desk\n  n03180011: desktop_computer\n  n03187595: dial_telephone\n  n03188531: diaper\n  n03196217: digital_clock\n  n03197337: digital_watch\n  n03201208: dining_table\n  n03207743: dishrag\n  n03207941: dishwasher\n  n03208938: disk_brake\n  n03216828: dock\n  n03218198: dogsled\n  n03220513: dome\n  n03223299: doormat\n  n03240683: drilling_platform\n  n03249569: drum\n  n03250847: drumstick\n  n03255030: dumbbell\n  n03259280: Dutch_oven\n  n03271574: electric_fan\n  n03272010: electric_guitar\n  n03272562: electric_locomotive\n  n03290653: entertainment_center\n  n03291819: envelope\n  n03297495: espresso_maker\n  n03314780: face_powder\n  n03325584: feather_boa\n  n03337140: file\n  n03344393: fireboat\n  n03345487: fire_engine\n  n03347037: fire_screen\n  n03355925: flagpole\n  n03372029: flute\n  n03376595: folding_chair\n  n03379051: football_helmet\n  n03384352: forklift\n  n03388043: fountain\n  n03388183: fountain_pen\n  n03388549: four-poster\n  n03393912: freight_car\n  n03394916: French_horn\n  n03400231: frying_pan\n  n03404251: fur_coat\n  n03417042: garbage_truck\n  n03424325: gasmask\n  n03425413: gas_pump\n  n03443371: goblet\n  n03444034: go-kart\n  n03445777: golf_ball\n  n03445924: golfcart\n  n03447447: gondola\n  n03447721: gong\n  n03450230: gown\n  n03452741: grand_piano\n  n03457902: greenhouse\n  n03459775: grille\n  n03461385: grocery_store\n  n03467068: guillotine\n  n03476684: hair_slide\n  n03476991: hair_spray\n  n03478589: half_track\n  n03481172: hammer\n  n03482405: hamper\n  n03483316: hand_blower\n  n03485407: hand-held_computer\n  n03485794: handkerchief\n  n03492542: hard_disc\n  n03494278: harmonica\n  n03495258: harp\n  n03496892: harvester\n  n03498962: hatchet\n  n03527444: holster\n  n03529860: home_theater\n  n03530642: honeycomb\n  n03532672: hook\n  n03534580: hoopskirt\n  n03535780: horizontal_bar\n  n03538406: horse_cart\n  n03544143: hourglass\n  n03584254: iPod\n  n03584829: iron\n  n03590841: jack-o'-lantern\n  n03594734: jean\n  n03594945: jeep\n  n03595614: jersey\n  n03598930: jigsaw_puzzle\n  n03599486: jinrikisha\n  n03602883: joystick\n  n03617480: kimono\n  n03623198: knee_pad\n  n03627232: knot\n  n03630383: lab_coat\n  n03633091: ladle\n  n03637318: lampshade\n  n03642806: laptop\n  n03649909: lawn_mower\n  n03657121: lens_cap\n  n03658185: letter_opener\n  n03661043: library\n  n03662601: lifeboat\n  n03666591: lighter\n  n03670208: limousine\n  n03673027: liner\n  n03676483: lipstick\n  n03680355: Loafer\n  n03690938: lotion\n  n03691459: loudspeaker\n  n03692522: loupe\n  n03697007: lumbermill\n  n03706229: magnetic_compass\n  n03709823: mailbag\n  n03710193: mailbox\n  n03710637: maillot_(tights)\n  n03710721: maillot_(tank_suit)\n  n03717622: manhole_cover\n  n03720891: maraca\n  n03721384: marimba\n  n03724870: mask\n  n03729826: matchstick\n  n03733131: maypole\n  n03733281: maze\n  n03733805: measuring_cup\n  n03742115: medicine_chest\n  n03743016: megalith\n  n03759954: microphone\n  n03761084: microwave\n  n03763968: military_uniform\n  n03764736: milk_can\n  n03769881: minibus\n  n03770439: miniskirt\n  n03770679: minivan\n  n03773504: missile\n  n03775071: mitten\n  n03775546: mixing_bowl\n  n03776460: mobile_home\n  n03777568: Model_T\n  n03777754: modem\n  n03781244: monastery\n  n03782006: monitor\n  n03785016: moped\n  n03786901: mortar\n  n03787032: mortarboard\n  n03788195: mosque\n  n03788365: mosquito_net\n  n03791053: motor_scooter\n  n03792782: mountain_bike\n  n03792972: mountain_tent\n  n03793489: mouse\n  n03794056: mousetrap\n  n03796401: moving_van\n  n03803284: muzzle\n  n03804744: nail\n  n03814639: neck_brace\n  n03814906: necklace\n  n03825788: nipple\n  n03832673: notebook\n  n03837869: obelisk\n  n03838899: oboe\n  n03840681: ocarina\n  n03841143: odometer\n  n03843555: oil_filter\n  n03854065: organ\n  n03857828: oscilloscope\n  n03866082: overskirt\n  n03868242: oxcart\n  n03868863: oxygen_mask\n  n03871628: packet\n  n03873416: paddle\n  n03874293: paddlewheel\n  n03874599: padlock\n  n03876231: paintbrush\n  n03877472: pajama\n  n03877845: palace\n  n03884397: panpipe\n  n03887697: paper_towel\n  n03888257: parachute\n  n03888605: parallel_bars\n  n03891251: park_bench\n  n03891332: parking_meter\n  n03895866: passenger_car\n  n03899768: patio\n  n03902125: pay-phone\n  n03903868: pedestal\n  n03908618: pencil_box\n  n03908714: pencil_sharpener\n  n03916031: perfume\n  n03920288: Petri_dish\n  n03924679: photocopier\n  n03929660: pick\n  n03929855: pickelhaube\n  n03930313: picket_fence\n  n03930630: pickup\n  n03933933: pier\n  n03935335: piggy_bank\n  n03937543: pill_bottle\n  n03938244: pillow\n  n03942813: ping-pong_ball\n  n03944341: pinwheel\n  n03947888: pirate\n  n03950228: pitcher\n  n03954731: plane\n  n03956157: planetarium\n  n03958227: plastic_bag\n  n03961711: plate_rack\n  n03967562: plow\n  n03970156: plunger\n  n03976467: Polaroid_camera\n  n03976657: pole\n  n03977966: police_van\n  n03980874: poncho\n  n03982430: pool_table\n  n03983396: pop_bottle\n  n03991062: pot\n  n03992509: potter's_wheel\n  n03995372: power_drill\n  n03998194: prayer_rug\n  n04004767: printer\n  n04005630: prison\n  n04008634: projectile\n  n04009552: projector\n  n04019541: puck\n  n04023962: punching_bag\n  n04026417: purse\n  n04033901: quill\n  n04033995: quilt\n  n04037443: racer\n  n04039381: racket\n  n04040759: radiator\n  n04041544: radio\n  n04044716: radio_telescope\n  n04049303: rain_barrel\n  n04065272: recreational_vehicle\n  n04067472: reel\n  n04069434: reflex_camera\n  n04070727: refrigerator\n  n04074963: remote_control\n  n04081281: restaurant\n  n04086273: revolver\n  n04090263: rifle\n  n04099969: rocking_chair\n  n04111531: rotisserie\n  n04116512: rubber_eraser\n  n04118538: rugby_ball\n  n04118776: rule\n  n04120489: running_shoe\n  n04125021: safe\n  n04127249: safety_pin\n  n04131690: saltshaker\n  n04133789: sandal\n  n04136333: sarong\n  n04141076: sax\n  n04141327: scabbard\n  n04141975: scale\n  n04146614: school_bus\n  n04147183: schooner\n  n04149813: scoreboard\n  n04152593: screen\n  n04153751: screw\n  n04154565: screwdriver\n  n04162706: seat_belt\n  n04179913: sewing_machine\n  n04192698: shield\n  n04200800: shoe_shop\n  n04201297: shoji\n  n04204238: shopping_basket\n  n04204347: shopping_cart\n  n04208210: shovel\n  n04209133: shower_cap\n  n04209239: shower_curtain\n  n04228054: ski\n  n04229816: ski_mask\n  n04235860: sleeping_bag\n  n04238763: slide_rule\n  n04239074: sliding_door\n  n04243546: slot\n  n04251144: snorkel\n  n04252077: snowmobile\n  n04252225: snowplow\n  n04254120: soap_dispenser\n  n04254680: soccer_ball\n  n04254777: sock\n  n04258138: solar_dish\n  n04259630: sombrero\n  n04263257: soup_bowl\n  n04264628: space_bar\n  n04265275: space_heater\n  n04266014: space_shuttle\n  n04270147: spatula\n  n04273569: speedboat\n  n04275548: spider_web\n  n04277352: spindle\n  n04285008: sports_car\n  n04286575: spotlight\n  n04296562: stage\n  n04310018: steam_locomotive\n  n04311004: steel_arch_bridge\n  n04311174: steel_drum\n  n04317175: stethoscope\n  n04325704: stole\n  n04326547: stone_wall\n  n04328186: stopwatch\n  n04330267: stove\n  n04332243: strainer\n  n04335435: streetcar\n  n04336792: stretcher\n  n04344873: studio_couch\n  n04346328: stupa\n  n04347754: submarine\n  n04350905: suit\n  n04355338: sundial\n  n04355933: sunglass\n  n04356056: sunglasses\n  n04357314: sunscreen\n  n04366367: suspension_bridge\n  n04367480: swab\n  n04370456: sweatshirt\n  n04371430: swimming_trunks\n  n04371774: swing\n  n04372370: switch\n  n04376876: syringe\n  n04380533: table_lamp\n  n04389033: tank\n  n04392985: tape_player\n  n04398044: teapot\n  n04399382: teddy\n  n04404412: television\n  n04409515: tennis_ball\n  n04417672: thatch\n  n04418357: theater_curtain\n  n04423845: thimble\n  n04428191: thresher\n  n04429376: throne\n  n04435653: tile_roof\n  n04442312: toaster\n  n04443257: tobacco_shop\n  n04447861: toilet_seat\n  n04456115: torch\n  n04458633: totem_pole\n  n04461696: tow_truck\n  n04462240: toyshop\n  n04465501: tractor\n  n04467665: trailer_truck\n  n04476259: tray\n  n04479046: trench_coat\n  n04482393: tricycle\n  n04483307: trimaran\n  n04485082: tripod\n  n04486054: triumphal_arch\n  n04487081: trolleybus\n  n04487394: trombone\n  n04493381: tub\n  n04501370: turnstile\n  n04505470: typewriter_keyboard\n  n04507155: umbrella\n  n04509417: unicycle\n  n04515003: upright\n  n04517823: vacuum\n  n04522168: vase\n  n04523525: vault\n  n04525038: velvet\n  n04525305: vending_machine\n  n04532106: vestment\n  n04532670: viaduct\n  n04536866: violin\n  n04540053: volleyball\n  n04542943: waffle_iron\n  n04548280: wall_clock\n  n04548362: wallet\n  n04550184: wardrobe\n  n04552348: warplane\n  n04553703: washbasin\n  n04554684: washer\n  n04557648: water_bottle\n  n04560804: water_jug\n  n04562935: water_tower\n  n04579145: whiskey_jug\n  n04579432: whistle\n  n04584207: wig\n  n04589890: window_screen\n  n04590129: window_shade\n  n04591157: Windsor_tie\n  n04591713: wine_bottle\n  n04592741: wing\n  n04596742: wok\n  n04597913: wooden_spoon\n  n04599235: wool\n  n04604644: worm_fence\n  n04606251: wreck\n  n04612504: yawl\n  n04613696: yurt\n  n06359193: web_site\n  n06596364: comic_book\n  n06785654: crossword_puzzle\n  n06794110: street_sign\n  n06874185: traffic_light\n  n07248320: book_jacket\n  n07565083: menu\n  n07579787: plate\n  n07583066: guacamole\n  n07584110: consomme\n  n07590611: hot_pot\n  n07613480: trifle\n  n07614500: ice_cream\n  n07615774: ice_lolly\n  n07684084: French_loaf\n  n07693725: bagel\n  n07695742: pretzel\n  n07697313: cheeseburger\n  n07697537: hotdog\n  n07711569: mashed_potato\n  n07714571: head_cabbage\n  n07714990: broccoli\n  n07715103: cauliflower\n  n07716358: zucchini\n  n07716906: spaghetti_squash\n  n07717410: acorn_squash\n  n07717556: butternut_squash\n  n07718472: cucumber\n  n07718747: artichoke\n  n07720875: bell_pepper\n  n07730033: cardoon\n  n07734744: mushroom\n  n07742313: Granny_Smith\n  n07745940: strawberry\n  n07747607: orange\n  n07749582: lemon\n  n07753113: fig\n  n07753275: pineapple\n  n07753592: banana\n  n07754684: jackfruit\n  n07760859: custard_apple\n  n07768694: pomegranate\n  n07802026: hay\n  n07831146: carbonara\n  n07836838: chocolate_sauce\n  n07860988: dough\n  n07871810: meat_loaf\n  n07873807: pizza\n  n07875152: potpie\n  n07880968: burrito\n  n07892512: red_wine\n  n07920052: espresso\n  n07930864: cup\n  n07932039: eggnog\n  n09193705: alp\n  n09229709: bubble\n  n09246464: cliff\n  n09256479: coral_reef\n  n09288635: geyser\n  n09332890: lakeside\n  n09399592: promontory\n  n09421951: sandbar\n  n09428293: seashore\n  n09468604: valley\n  n09472597: volcano\n  n09835506: ballplayer\n  n10148035: groom\n  n10565667: scuba_diver\n  n11879895: rapeseed\n  n11939491: daisy\n  n12057211: yellow_lady's_slipper\n  n12144580: corn\n  n12267677: acorn\n  n12620546: hip\n  n12768682: buckeye\n  n12985857: coral_fungus\n  n12998815: agaric\n  n13037406: gyromitra\n  n13040303: stinkhorn\n  n13044778: earthstar\n  n13052670: hen-of-the-woods\n  n13054560: bolete\n  n13133613: ear\n  n15075141: toilet_tissue\n\n\n# Download script/URL (optional)\ndownload: yolo/data/scripts/get_imagenet.sh\n"
  },
  {
    "path": "ultralytics/datasets/Objects365.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Objects365 dataset https://www.objects365.org/ by Megvii\n# Example usage: yolo train data=Objects365.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── Objects365  ← downloads here (712 GB = 367G data + 345G zips)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/Objects365  # dataset root dir\ntrain: images/train  # train images (relative to 'path') 1742289 images\nval: images/val # val images (relative to 'path') 80000 images\ntest:  # test images (optional)\n\n# Classes\nnames:\n  0: Person\n  1: Sneakers\n  2: Chair\n  3: Other Shoes\n  4: Hat\n  5: Car\n  6: Lamp\n  7: Glasses\n  8: Bottle\n  9: Desk\n  10: Cup\n  11: Street Lights\n  12: Cabinet/shelf\n  13: Handbag/Satchel\n  14: Bracelet\n  15: Plate\n  16: Picture/Frame\n  17: Helmet\n  18: Book\n  19: Gloves\n  20: Storage box\n  21: Boat\n  22: Leather Shoes\n  23: Flower\n  24: Bench\n  25: Potted Plant\n  26: Bowl/Basin\n  27: Flag\n  28: Pillow\n  29: Boots\n  30: Vase\n  31: Microphone\n  32: Necklace\n  33: Ring\n  34: SUV\n  35: Wine Glass\n  36: Belt\n  37: Monitor/TV\n  38: Backpack\n  39: Umbrella\n  40: Traffic Light\n  41: Speaker\n  42: Watch\n  43: Tie\n  44: Trash bin Can\n  45: Slippers\n  46: Bicycle\n  47: Stool\n  48: Barrel/bucket\n  49: Van\n  50: Couch\n  51: Sandals\n  52: Basket\n  53: Drum\n  54: Pen/Pencil\n  55: Bus\n  56: Wild Bird\n  57: High Heels\n  58: Motorcycle\n  59: Guitar\n  60: Carpet\n  61: Cell Phone\n  62: Bread\n  63: Camera\n  64: Canned\n  65: Truck\n  66: Traffic cone\n  67: Cymbal\n  68: Lifesaver\n  69: Towel\n  70: Stuffed Toy\n  71: Candle\n  72: Sailboat\n  73: Laptop\n  74: Awning\n  75: Bed\n  76: Faucet\n  77: Tent\n  78: Horse\n  79: Mirror\n  80: Power outlet\n  81: Sink\n  82: Apple\n  83: Air Conditioner\n  84: Knife\n  85: Hockey Stick\n  86: Paddle\n  87: Pickup Truck\n  88: Fork\n  89: Traffic Sign\n  90: Balloon\n  91: Tripod\n  92: Dog\n  93: Spoon\n  94: Clock\n  95: Pot\n  96: Cow\n  97: Cake\n  98: Dinning Table\n  99: Sheep\n  100: Hanger\n  101: Blackboard/Whiteboard\n  102: Napkin\n  103: Other Fish\n  104: Orange/Tangerine\n  105: Toiletry\n  106: Keyboard\n  107: Tomato\n  108: Lantern\n  109: Machinery Vehicle\n  110: Fan\n  111: Green Vegetables\n  112: Banana\n  113: Baseball Glove\n  114: Airplane\n  115: Mouse\n  116: Train\n  117: Pumpkin\n  118: Soccer\n  119: Skiboard\n  120: Luggage\n  121: Nightstand\n  122: Tea pot\n  123: Telephone\n  124: Trolley\n  125: Head Phone\n  126: Sports Car\n  127: Stop Sign\n  128: Dessert\n  129: Scooter\n  130: Stroller\n  131: Crane\n  132: Remote\n  133: Refrigerator\n  134: Oven\n  135: Lemon\n  136: Duck\n  137: Baseball Bat\n  138: Surveillance Camera\n  139: Cat\n  140: Jug\n  141: Broccoli\n  142: Piano\n  143: Pizza\n  144: Elephant\n  145: Skateboard\n  146: Surfboard\n  147: Gun\n  148: Skating and Skiing shoes\n  149: Gas stove\n  150: Donut\n  151: Bow Tie\n  152: Carrot\n  153: Toilet\n  154: Kite\n  155: Strawberry\n  156: Other Balls\n  157: Shovel\n  158: Pepper\n  159: Computer Box\n  160: Toilet Paper\n  161: Cleaning Products\n  162: Chopsticks\n  163: Microwave\n  164: Pigeon\n  165: Baseball\n  166: Cutting/chopping Board\n  167: Coffee Table\n  168: Side Table\n  169: Scissors\n  170: Marker\n  171: Pie\n  172: Ladder\n  173: Snowboard\n  174: Cookies\n  175: Radiator\n  176: Fire Hydrant\n  177: Basketball\n  178: Zebra\n  179: Grape\n  180: Giraffe\n  181: Potato\n  182: Sausage\n  183: Tricycle\n  184: Violin\n  185: Egg\n  186: Fire Extinguisher\n  187: Candy\n  188: Fire Truck\n  189: Billiards\n  190: Converter\n  191: Bathtub\n  192: Wheelchair\n  193: Golf Club\n  194: Briefcase\n  195: Cucumber\n  196: Cigar/Cigarette\n  197: Paint Brush\n  198: Pear\n  199: Heavy Truck\n  200: Hamburger\n  201: Extractor\n  202: Extension Cord\n  203: Tong\n  204: Tennis Racket\n  205: Folder\n  206: American Football\n  207: earphone\n  208: Mask\n  209: Kettle\n  210: Tennis\n  211: Ship\n  212: Swing\n  213: Coffee Machine\n  214: Slide\n  215: Carriage\n  216: Onion\n  217: Green beans\n  218: Projector\n  219: Frisbee\n  220: Washing Machine/Drying Machine\n  221: Chicken\n  222: Printer\n  223: Watermelon\n  224: Saxophone\n  225: Tissue\n  226: Toothbrush\n  227: Ice cream\n  228: Hot-air balloon\n  229: Cello\n  230: French Fries\n  231: Scale\n  232: Trophy\n  233: Cabbage\n  234: Hot dog\n  235: Blender\n  236: Peach\n  237: Rice\n  238: Wallet/Purse\n  239: Volleyball\n  240: Deer\n  241: Goose\n  242: Tape\n  243: Tablet\n  244: Cosmetics\n  245: Trumpet\n  246: Pineapple\n  247: Golf Ball\n  248: Ambulance\n  249: Parking meter\n  250: Mango\n  251: Key\n  252: Hurdle\n  253: Fishing Rod\n  254: Medal\n  255: Flute\n  256: Brush\n  257: Penguin\n  258: Megaphone\n  259: Corn\n  260: Lettuce\n  261: Garlic\n  262: Swan\n  263: Helicopter\n  264: Green Onion\n  265: Sandwich\n  266: Nuts\n  267: Speed Limit Sign\n  268: Induction Cooker\n  269: Broom\n  270: Trombone\n  271: Plum\n  272: Rickshaw\n  273: Goldfish\n  274: Kiwi fruit\n  275: Router/modem\n  276: Poker Card\n  277: Toaster\n  278: Shrimp\n  279: Sushi\n  280: Cheese\n  281: Notepaper\n  282: Cherry\n  283: Pliers\n  284: CD\n  285: Pasta\n  286: Hammer\n  287: Cue\n  288: Avocado\n  289: Hamimelon\n  290: Flask\n  291: Mushroom\n  292: Screwdriver\n  293: Soap\n  294: Recorder\n  295: Bear\n  296: Eggplant\n  297: Board Eraser\n  298: Coconut\n  299: Tape Measure/Ruler\n  300: Pig\n  301: Showerhead\n  302: Globe\n  303: Chips\n  304: Steak\n  305: Crosswalk Sign\n  306: Stapler\n  307: Camel\n  308: Formula 1\n  309: Pomegranate\n  310: Dishwasher\n  311: Crab\n  312: Hoverboard\n  313: Meat ball\n  314: Rice Cooker\n  315: Tuba\n  316: Calculator\n  317: Papaya\n  318: Antelope\n  319: Parrot\n  320: Seal\n  321: Butterfly\n  322: Dumbbell\n  323: Donkey\n  324: Lion\n  325: Urinal\n  326: Dolphin\n  327: Electric Drill\n  328: Hair Dryer\n  329: Egg tart\n  330: Jellyfish\n  331: Treadmill\n  332: Lighter\n  333: Grapefruit\n  334: Game board\n  335: Mop\n  336: Radish\n  337: Baozi\n  338: Target\n  339: French\n  340: Spring Rolls\n  341: Monkey\n  342: Rabbit\n  343: Pencil Case\n  344: Yak\n  345: Red Cabbage\n  346: Binoculars\n  347: Asparagus\n  348: Barbell\n  349: Scallop\n  350: Noddles\n  351: Comb\n  352: Dumpling\n  353: Oyster\n  354: Table Tennis paddle\n  355: Cosmetics Brush/Eyeliner Pencil\n  356: Chainsaw\n  357: Eraser\n  358: Lobster\n  359: Durian\n  360: Okra\n  361: Lipstick\n  362: Cosmetics Mirror\n  363: Curling\n  364: Table Tennis\n\n\n# Download script/URL (optional) ---------------------------------------------------------------------------------------\ndownload: |\n  from tqdm import tqdm\n\n  from ultralytics.yolo.utils.checks import check_requirements\n  from ultralytics.yolo.utils.downloads import download\n  from ultralytics.yolo.utils.ops import xyxy2xywhn\n\n  import numpy as np\n  from pathlib import Path\n\n  check_requirements(('pycocotools>=2.0',))\n  from pycocotools.coco import COCO\n\n  # Make Directories\n  dir = Path(yaml['path'])  # dataset root dir\n  for p in 'images', 'labels':\n      (dir / p).mkdir(parents=True, exist_ok=True)\n      for q in 'train', 'val':\n          (dir / p / q).mkdir(parents=True, exist_ok=True)\n\n  # Train, Val Splits\n  for split, patches in [('train', 50 + 1), ('val', 43 + 1)]:\n      print(f\"Processing {split} in {patches} patches ...\")\n      images, labels = dir / 'images' / split, dir / 'labels' / split\n\n      # Download\n      url = f\"https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/{split}/\"\n      if split == 'train':\n          download([f'{url}zhiyuan_objv2_{split}.tar.gz'], dir=dir)  # annotations json\n          download([f'{url}patch{i}.tar.gz' for i in range(patches)], dir=images, curl=True, threads=8)\n      elif split == 'val':\n          download([f'{url}zhiyuan_objv2_{split}.json'], dir=dir)  # annotations json\n          download([f'{url}images/v1/patch{i}.tar.gz' for i in range(15 + 1)], dir=images, curl=True, threads=8)\n          download([f'{url}images/v2/patch{i}.tar.gz' for i in range(16, patches)], dir=images, curl=True, threads=8)\n\n      # Move\n      for f in tqdm(images.rglob('*.jpg'), desc=f'Moving {split} images'):\n          f.rename(images / f.name)  # move to /images/{split}\n\n      # Labels\n      coco = COCO(dir / f'zhiyuan_objv2_{split}.json')\n      names = [x[\"name\"] for x in coco.loadCats(coco.getCatIds())]\n      for cid, cat in enumerate(names):\n          catIds = coco.getCatIds(catNms=[cat])\n          imgIds = coco.getImgIds(catIds=catIds)\n          for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'):\n              width, height = im[\"width\"], im[\"height\"]\n              path = Path(im[\"file_name\"])  # image filename\n              try:\n                  with open(labels / path.with_suffix('.txt').name, 'a') as file:\n                      annIds = coco.getAnnIds(imgIds=im[\"id\"], catIds=catIds, iscrowd=None)\n                      for a in coco.loadAnns(annIds):\n                          x, y, w, h = a['bbox']  # bounding box in xywh (xy top-left corner)\n                          xyxy = np.array([x, y, x + w, y + h])[None]  # pixels(1,4)\n                          x, y, w, h = xyxy2xywhn(xyxy, w=width, h=height, clip=True)[0]  # normalized and clipped\n                          file.write(f\"{cid} {x:.5f} {y:.5f} {w:.5f} {h:.5f}\\n\")\n              except Exception as e:\n                  print(e)\n"
  },
  {
    "path": "ultralytics/datasets/SKU-110K.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19 by Trax Retail\n# Example usage: yolo train data=SKU-110K.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── SKU-110K  ← downloads here (13.6 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/SKU-110K  # dataset root dir\ntrain: train.txt  # train images (relative to 'path')  8219 images\nval: val.txt  # val images (relative to 'path')  588 images\ntest: test.txt  # test images (optional)  2936 images\n\n# Classes\nnames:\n  0: object\n\n\n# Download script/URL (optional) ---------------------------------------------------------------------------------------\ndownload: |\n  import shutil\n  from pathlib import Path\n\n  import numpy as np\n  import pandas as pd\n  from tqdm import tqdm\n\n  from ultralytics.yolo.utils.downloads import download\n  from ultralytics.yolo.utils.ops import xyxy2xywh\n\n  # Download\n  dir = Path(yaml['path'])  # dataset root dir\n  parent = Path(dir.parent)  # download dir\n  urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz']\n  download(urls, dir=parent)\n\n  # Rename directories\n  if dir.exists():\n      shutil.rmtree(dir)\n  (parent / 'SKU110K_fixed').rename(dir)  # rename dir\n  (dir / 'labels').mkdir(parents=True, exist_ok=True)  # create labels dir\n\n  # Convert labels\n  names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height'  # column names\n  for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv':\n      x = pd.read_csv(dir / 'annotations' / d, names=names).values  # annotations\n      images, unique_images = x[:, 0], np.unique(x[:, 0])\n      with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f:\n          f.writelines(f'./images/{s}\\n' for s in unique_images)\n      for im in tqdm(unique_images, desc=f'Converting {dir / d}'):\n          cls = 0  # single-class dataset\n          with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f:\n              for r in x[images == im]:\n                  w, h = r[6], r[7]  # image width, height\n                  xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0]  # instance\n                  f.write(f\"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\\n\")  # write label\n"
  },
  {
    "path": "ultralytics/datasets/VOC.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC by University of Oxford\n# Example usage: yolo train data=VOC.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── VOC  ← downloads here (2.8 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/VOC\ntrain: # train images (relative to 'path')  16551 images\n  - images/train2012\n  - images/train2007\n  - images/val2012\n  - images/val2007\nval: # val images (relative to 'path')  4952 images\n  - images/test2007\ntest: # test images (optional)\n  - images/test2007\n\n# Classes\nnames:\n  0: aeroplane\n  1: bicycle\n  2: bird\n  3: boat\n  4: bottle\n  5: bus\n  6: car\n  7: cat\n  8: chair\n  9: cow\n  10: diningtable\n  11: dog\n  12: horse\n  13: motorbike\n  14: person\n  15: pottedplant\n  16: sheep\n  17: sofa\n  18: train\n  19: tvmonitor\n\n\n# Download script/URL (optional) ---------------------------------------------------------------------------------------\ndownload: |\n  import xml.etree.ElementTree as ET\n\n  from tqdm import tqdm\n  from ultralytics.yolo.utils.downloads import download\n  from pathlib import Path\n\n  def convert_label(path, lb_path, year, image_id):\n      def convert_box(size, box):\n          dw, dh = 1. / size[0], 1. / size[1]\n          x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2]\n          return x * dw, y * dh, w * dw, h * dh\n\n      in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml')\n      out_file = open(lb_path, 'w')\n      tree = ET.parse(in_file)\n      root = tree.getroot()\n      size = root.find('size')\n      w = int(size.find('width').text)\n      h = int(size.find('height').text)\n\n      names = list(yaml['names'].values())  # names list\n      for obj in root.iter('object'):\n          cls = obj.find('name').text\n          if cls in names and int(obj.find('difficult').text) != 1:\n              xmlbox = obj.find('bndbox')\n              bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')])\n              cls_id = names.index(cls)  # class id\n              out_file.write(\" \".join([str(a) for a in (cls_id, *bb)]) + '\\n')\n\n\n  # Download\n  dir = Path(yaml['path'])  # dataset root dir\n  url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'\n  urls = [f'{url}VOCtrainval_06-Nov-2007.zip',  # 446MB, 5012 images\n          f'{url}VOCtest_06-Nov-2007.zip',  # 438MB, 4953 images\n          f'{url}VOCtrainval_11-May-2012.zip']  # 1.95GB, 17126 images\n  download(urls, dir=dir / 'images', curl=True, threads=3)\n\n  # Convert\n  path = dir / 'images/VOCdevkit'\n  for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'):\n      imgs_path = dir / 'images' / f'{image_set}{year}'\n      lbs_path = dir / 'labels' / f'{image_set}{year}'\n      imgs_path.mkdir(exist_ok=True, parents=True)\n      lbs_path.mkdir(exist_ok=True, parents=True)\n\n      with open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt') as f:\n          image_ids = f.read().strip().split()\n      for id in tqdm(image_ids, desc=f'{image_set}{year}'):\n          f = path / f'VOC{year}/JPEGImages/{id}.jpg'  # old img path\n          lb_path = (lbs_path / f.name).with_suffix('.txt')  # new label path\n          f.rename(imgs_path / f.name)  # move image\n          convert_label(path, lb_path, year, id)  # convert labels to YOLO format\n"
  },
  {
    "path": "ultralytics/datasets/VisDrone.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset by Tianjin University\n# Example usage: yolo train data=VisDrone.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── VisDrone  ← downloads here (2.3 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/VisDrone  # dataset root dir\ntrain: VisDrone2019-DET-train/images  # train images (relative to 'path')  6471 images\nval: VisDrone2019-DET-val/images  # val images (relative to 'path')  548 images\ntest: VisDrone2019-DET-test-dev/images  # test images (optional)  1610 images\n\n# Classes\nnames:\n  0: pedestrian\n  1: people\n  2: bicycle\n  3: car\n  4: van\n  5: truck\n  6: tricycle\n  7: awning-tricycle\n  8: bus\n  9: motor\n\n\n# Download script/URL (optional) ---------------------------------------------------------------------------------------\ndownload: |\n  import os\n  from pathlib import Path\n\n  from ultralytics.yolo.utils.downloads import download\n\n  def visdrone2yolo(dir):\n      from PIL import Image\n      from tqdm import tqdm\n\n      def convert_box(size, box):\n          # Convert VisDrone box to YOLO xywh box\n          dw = 1. / size[0]\n          dh = 1. / size[1]\n          return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh\n\n      (dir / 'labels').mkdir(parents=True, exist_ok=True)  # make labels directory\n      pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}')\n      for f in pbar:\n          img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size\n          lines = []\n          with open(f, 'r') as file:  # read annotation.txt\n              for row in [x.split(',') for x in file.read().strip().splitlines()]:\n                  if row[4] == '0':  # VisDrone 'ignored regions' class 0\n                      continue\n                  cls = int(row[5]) - 1\n                  box = convert_box(img_size, tuple(map(int, row[:4])))\n                  lines.append(f\"{cls} {' '.join(f'{x:.6f}' for x in box)}\\n\")\n                  with open(str(f).replace(f'{os.sep}annotations{os.sep}', f'{os.sep}labels{os.sep}'), 'w') as fl:\n                      fl.writelines(lines)  # write label.txt\n\n\n  # Download\n  dir = Path(yaml['path'])  # dataset root dir\n  urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip',\n          'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip',\n          'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip',\n          'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip']\n  download(urls, dir=dir, curl=True, threads=4)\n\n  # Convert\n  for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev':\n      visdrone2yolo(dir / d)  # convert VisDrone annotations to YOLO labels\n"
  },
  {
    "path": "ultralytics/datasets/bdd-drivable-seg-toy.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO 2017 dataset http://cocodataset.org by Microsoft\n# Example usage: yolo train data=coco.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco  ← downloads here (20.1 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: /data/jiayuan/BDDcoco/yolo_v8_toy/dataset-drivable-0  # dataset root dir\ntrain: images/train2017  # train images (relative to 'path') 4 images\nval: images/val2017  # val images (relative to 'path') 4 images\ntest: images/val2017 # test images (optional)\n\n# Classes (80 COCO classes)\nnames:\n  0: drivable  # Add drivable class for drivable segmentation\n\n\n\n  \n\n\n\n# Download script/URL (optional)\n# download: |\n#   from ultralytics.yolo.utils.downloads import download\n#   from pathlib import Path\n\n#   # Download labels\n#   segments = True  # segment or box labels\n#   dir = Path(yaml['path'])  # dataset root dir\n#   url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'\n#   urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')]  # labels\n#   download(urls, dir=dir.parent)\n#   # Download data\n#   urls = ['http://images.cocodataset.org/zips/train2017.zip',  # 19G, 118k images\n#           'http://images.cocodataset.org/zips/val2017.zip',  # 1G, 5k images\n#           'http://images.cocodataset.org/zips/test2017.zip']  # 7G, 41k images (optional)\n#   download(urls, dir=dir / 'images', threads=3)\n"
  },
  {
    "path": "ultralytics/datasets/bdd-lane-seg-toy.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO 2017 dataset http://cocodataset.org by Microsoft\n# Example usage: yolo train data=coco.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco  ← downloads here (20.1 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: /data/jiayuan/BDDcoco/yolo_v8_toy/dataset-lane-0  # dataset root dir\ntrain: images/train2017  # train images (relative to 'path') 4 images\nval: images/val2017  # val images (relative to 'path') 4 images\ntest: images/val2017 # test images (optional)\n\n# Classes (80 COCO classes)\nnames:\n  0: lane\n\n\n  \n\n\n\n# Download script/URL (optional)\n# download: |\n#   from ultralytics.yolo.utils.downloads import download\n#   from pathlib import Path\n\n#   # Download labels\n#   segments = True  # segment or box labels\n#   dir = Path(yaml['path'])  # dataset root dir\n#   url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'\n#   urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')]  # labels\n#   download(urls, dir=dir.parent)\n#   # Download data\n#   urls = ['http://images.cocodataset.org/zips/train2017.zip',  # 19G, 118k images\n#           'http://images.cocodataset.org/zips/val2017.zip',  # 1G, 5k images\n#           'http://images.cocodataset.org/zips/test2017.zip']  # 7G, 41k images (optional)\n#   download(urls, dir=dir / 'images', threads=3)\n"
  },
  {
    "path": "ultralytics/datasets/bdd-multi-toy.yaml",
    "content": "# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\n#path: /data/jiayuan/BDDcoco/yolo_v8_toy  # dataset root dir\npath: /data/jiayuan/BDDcoco/yolo_v8_toy  # dataset root dir\n\n# Train/val/test image paths for all tasks\ntrain: images/train2017  # train images for object detection (relative to 'path')\n\n\nval: images/val2017  # val images for object detection (relative to 'path')\n\n\ntest: images/val2017  # test images for object detection (relative to 'path')\n\nlabels_list:\n  - detection-object\n  - seg-drivable\n  - seg-lane\n\ntnc: 3  # number of classes\nnc_list: [1,1,1]\nmap: [None,{'10':'0'},{'11':'0'}]\n\n# Classes for all tasks\nnames:\n  0: person\n  1: rider\n  2: car\n  3: bus\n  4: truck\n  5: bike\n  6: motor\n  7: traffic light\n  8: traffic sign\n  9: train\n  10: drivable  # Add drivable class for drivable segmentation\n  11: lane  # Add lane class for lane segmentation\n"
  },
  {
    "path": "ultralytics/datasets/bdd-multi.yaml",
    "content": "# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\n#path: /data/jiayuan/BDDcoco/yolo_v8_toy  # dataset root dir\npath: /data/jiayuan/yolo8_multi  # dataset root dir\n\n# Train/val/test image paths for all tasks\ntrain: images/train2017  # train images for object detection (relative to 'path')\n\n\nval: images/val2017  # val images for object detection (relative to 'path')\n\n\ntest: images/val2017  # test images for object detection (relative to 'path')\n\nlabels_list:\n  - detection-object\n  - seg-drivable-10\n  - seg-lane-11\n\ntnc: 3  # number of classes\nnc_list: [1,1,1]\nmap: [None,{'10':'0'},{'11':'0'}]\n\n# Classes for all tasks\nnames:\n  0: person\n  1: rider\n  2: car\n  3: bus\n  4: truck\n  5: bike\n  6: motor\n  7: traffic light\n  8: traffic sign\n  9: train\n  10: drivable  # Add drivable class for drivable segmentation\n  11: lane  # Add lane class for lane segmentation\n"
  },
  {
    "path": "ultralytics/datasets/coco-pose.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO 2017 dataset http://cocodataset.org by Microsoft\n# Example usage: yolo train data=coco-pose.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco-pose  ← downloads here (20.1 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/coco-pose  # dataset root dir\ntrain: train2017.txt  # train images (relative to 'path') 118287 images\nval: val2017.txt  # val images (relative to 'path') 5000 images\ntest: test-dev2017.txt  # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794\n\n# Keypoints\nkpt_shape: [17, 3]  # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)\nflip_idx: [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15]\n\n# Classes\nnames:\n  0: person\n\n# Download script/URL (optional)\ndownload: |\n  from ultralytics.yolo.utils.downloads import download\n  from pathlib import Path\n\n  # Download labels\n  dir = Path(yaml['path'])  # dataset root dir\n  url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'\n  urls = [url + 'coco2017labels-pose.zip']  # labels\n  download(urls, dir=dir.parent)\n  # Download data\n  urls = ['http://images.cocodataset.org/zips/train2017.zip',  # 19G, 118k images\n          'http://images.cocodataset.org/zips/val2017.zip',  # 1G, 5k images\n          'http://images.cocodataset.org/zips/test2017.zip']  # 7G, 41k images (optional)\n  download(urls, dir=dir / 'images', threads=3)\n"
  },
  {
    "path": "ultralytics/datasets/coco-toy.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO 2017 dataset http://cocodataset.org by Microsoft\n# Example usage: yolo train data=coco.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco  ← downloads here (20.1 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: /data/jiayuan/BDDcoco/yolo_v8_toy  # dataset root dir\ntrain: dataset-detection/images/train2017  # train images (relative to 'path') 118287 images\nval: dataset-detection/images/val2017  # val images (relative to 'path') 5000 images\ntest: dataset-detection/images/val2017  # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794\n\n# Classes\nnames:\n  0: person\n  1: rider\n  2: car\n  3: bus\n  4: truck\n  5: bike\n  6: motor\n  7: traffic light\n  8: traffic sign\n  9: train\n  \n\n\n\n# Download script/URL (optional)\n# download: |\n#   from ultralytics.yolo.utils.downloads import download\n#   from pathlib import Path\n\n#   # Download labels\n#   segments = True  # segment or box labels\n#   dir = Path(yaml['path'])  # dataset root dir\n#   url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'\n#   urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')]  # labels\n#   download(urls, dir=dir.parent)\n#   # Download data\n#   urls = ['http://images.cocodataset.org/zips/train2017.zip',  # 19G, 118k images\n#           'http://images.cocodataset.org/zips/val2017.zip',  # 1G, 5k images\n#           'http://images.cocodataset.org/zips/test2017.zip']  # 7G, 41k images (optional)\n#   download(urls, dir=dir / 'images', threads=3)\n"
  },
  {
    "path": "ultralytics/datasets/coco.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO 2017 dataset http://cocodataset.org by Microsoft\n# Example usage: yolo train data=coco.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco  ← downloads here (20.1 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: /data/jiayuan/BDDcoco/yolo_v8  # dataset root dir\ntrain: images/train2017  # train images (relative to 'path') 118287 images\nval: images/val2017  # val images (relative to 'path') 5000 images\ntest: images/val2017  # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794\n\n# Classes\nnames:\n  0: person\n  1: rider\n  2: car\n  3: bus\n  4: truck\n  5: bike\n  6: motor\n  7: traffic light\n  8: traffic sign\n  9: train\n  \n\n\n\n# Download script/URL (optional)\n# download: |\n#   from ultralytics.yolo.utils.downloads import download\n#   from pathlib import Path\n\n#   # Download labels\n#   segments = True  # segment or box labels\n#   dir = Path(yaml['path'])  # dataset root dir\n#   url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'\n#   urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')]  # labels\n#   download(urls, dir=dir.parent)\n#   # Download data\n#   urls = ['http://images.cocodataset.org/zips/train2017.zip',  # 19G, 118k images\n#           'http://images.cocodataset.org/zips/val2017.zip',  # 1G, 5k images\n#           'http://images.cocodataset.org/zips/test2017.zip']  # 7G, 41k images (optional)\n#   download(urls, dir=dir / 'images', threads=3)\n"
  },
  {
    "path": "ultralytics/datasets/coco128-seg.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO128-seg dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) by Ultralytics\n# Example usage: yolo train data=coco128.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco128-seg  ← downloads here (7 MB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/coco128-seg  # dataset root dir\ntrain: images/train2017  # train images (relative to 'path') 128 images\nval: images/train2017  # val images (relative to 'path') 128 images\ntest:  # test images (optional)\n\n# Classes\nnames:\n  0: person\n  1: bicycle\n  2: car\n  3: motorcycle\n  4: airplane\n  5: bus\n  6: train\n  7: truck\n  8: boat\n  9: traffic light\n  10: fire hydrant\n  11: stop sign\n  12: parking meter\n  13: bench\n  14: bird\n  15: cat\n  16: dog\n  17: horse\n  18: sheep\n  19: cow\n  20: elephant\n  21: bear\n  22: zebra\n  23: giraffe\n  24: backpack\n  25: umbrella\n  26: handbag\n  27: tie\n  28: suitcase\n  29: frisbee\n  30: skis\n  31: snowboard\n  32: sports ball\n  33: kite\n  34: baseball bat\n  35: baseball glove\n  36: skateboard\n  37: surfboard\n  38: tennis racket\n  39: bottle\n  40: wine glass\n  41: cup\n  42: fork\n  43: knife\n  44: spoon\n  45: bowl\n  46: banana\n  47: apple\n  48: sandwich\n  49: orange\n  50: broccoli\n  51: carrot\n  52: hot dog\n  53: pizza\n  54: donut\n  55: cake\n  56: chair\n  57: couch\n  58: potted plant\n  59: bed\n  60: dining table\n  61: toilet\n  62: tv\n  63: laptop\n  64: mouse\n  65: remote\n  66: keyboard\n  67: cell phone\n  68: microwave\n  69: oven\n  70: toaster\n  71: sink\n  72: refrigerator\n  73: book\n  74: clock\n  75: vase\n  76: scissors\n  77: teddy bear\n  78: hair drier\n  79: toothbrush\n\n\n# Download script/URL (optional)\ndownload: https://ultralytics.com/assets/coco128-seg.zip\n"
  },
  {
    "path": "ultralytics/datasets/coco128.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) by Ultralytics\n# Example usage: yolo train data=coco128.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco128  ← downloads here (7 MB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/coco128  # dataset root dir\ntrain: images/train2017  # train images (relative to 'path') 128 images\nval: images/train2017  # val images (relative to 'path') 128 images\ntest:  # test images (optional)\n\n# Classes\nnames:\n  0: person\n  1: bicycle\n  2: car\n  3: motorcycle\n  4: airplane\n  5: bus\n  6: train\n  7: truck\n  8: boat\n  9: traffic light\n  10: fire hydrant\n  11: stop sign\n  12: parking meter\n  13: bench\n  14: bird\n  15: cat\n  16: dog\n  17: horse\n  18: sheep\n  19: cow\n  20: elephant\n  21: bear\n  22: zebra\n  23: giraffe\n  24: backpack\n  25: umbrella\n  26: handbag\n  27: tie\n  28: suitcase\n  29: frisbee\n  30: skis\n  31: snowboard\n  32: sports ball\n  33: kite\n  34: baseball bat\n  35: baseball glove\n  36: skateboard\n  37: surfboard\n  38: tennis racket\n  39: bottle\n  40: wine glass\n  41: cup\n  42: fork\n  43: knife\n  44: spoon\n  45: bowl\n  46: banana\n  47: apple\n  48: sandwich\n  49: orange\n  50: broccoli\n  51: carrot\n  52: hot dog\n  53: pizza\n  54: donut\n  55: cake\n  56: chair\n  57: couch\n  58: potted plant\n  59: bed\n  60: dining table\n  61: toilet\n  62: tv\n  63: laptop\n  64: mouse\n  65: remote\n  66: keyboard\n  67: cell phone\n  68: microwave\n  69: oven\n  70: toaster\n  71: sink\n  72: refrigerator\n  73: book\n  74: clock\n  75: vase\n  76: scissors\n  77: teddy bear\n  78: hair drier\n  79: toothbrush\n\n\n# Download script/URL (optional)\ndownload: https://ultralytics.com/assets/coco128.zip\n"
  },
  {
    "path": "ultralytics/datasets/coco8-pose.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO8-pose dataset (first 8 images from COCO train2017) by Ultralytics\n# Example usage: yolo train data=coco8-pose.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco8-pose  ← downloads here (1 MB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/coco8-pose  # dataset root dir\ntrain: images/train  # train images (relative to 'path') 4 images\nval: images/val  # val images (relative to 'path') 4 images\ntest:  # test images (optional)\n\n# Keypoints\nkpt_shape: [17, 3]  # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)\nflip_idx: [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15]\n\n# Classes\nnames:\n  0: person\n\n# Download script/URL (optional)\ndownload: https://ultralytics.com/assets/coco8-pose.zip\n"
  },
  {
    "path": "ultralytics/datasets/coco8-seg.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO8-seg dataset (first 8 images from COCO train2017) by Ultralytics\n# Example usage: yolo train data=coco8-seg.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco8-seg  ← downloads here (1 MB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/coco8-seg  # dataset root dir\ntrain: images/train  # train images (relative to 'path') 4 images\nval: images/val  # val images (relative to 'path') 4 images\ntest:  # test images (optional)\n\n# Classes\nnames:\n  0: person\n  1: bicycle\n  2: car\n  3: motorcycle\n  4: airplane\n  5: bus\n  6: train\n  7: truck\n  8: boat\n  9: traffic light\n  10: fire hydrant\n  11: stop sign\n  12: parking meter\n  13: bench\n  14: bird\n  15: cat\n  16: dog\n  17: horse\n  18: sheep\n  19: cow\n  20: elephant\n  21: bear\n  22: zebra\n  23: giraffe\n  24: backpack\n  25: umbrella\n  26: handbag\n  27: tie\n  28: suitcase\n  29: frisbee\n  30: skis\n  31: snowboard\n  32: sports ball\n  33: kite\n  34: baseball bat\n  35: baseball glove\n  36: skateboard\n  37: surfboard\n  38: tennis racket\n  39: bottle\n  40: wine glass\n  41: cup\n  42: fork\n  43: knife\n  44: spoon\n  45: bowl\n  46: banana\n  47: apple\n  48: sandwich\n  49: orange\n  50: broccoli\n  51: carrot\n  52: hot dog\n  53: pizza\n  54: donut\n  55: cake\n  56: chair\n  57: couch\n  58: potted plant\n  59: bed\n  60: dining table\n  61: toilet\n  62: tv\n  63: laptop\n  64: mouse\n  65: remote\n  66: keyboard\n  67: cell phone\n  68: microwave\n  69: oven\n  70: toaster\n  71: sink\n  72: refrigerator\n  73: book\n  74: clock\n  75: vase\n  76: scissors\n  77: teddy bear\n  78: hair drier\n  79: toothbrush\n\n\n# Download script/URL (optional)\ndownload: https://ultralytics.com/assets/coco8-seg.zip\n"
  },
  {
    "path": "ultralytics/datasets/coco8.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# COCO8 dataset (first 8 images from COCO train2017) by Ultralytics\n# Example usage: yolo train data=coco8.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco8  ← downloads here (1 MB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/coco8  # dataset root dir\ntrain: images/train  # train images (relative to 'path') 4 images\nval: images/val  # val images (relative to 'path') 4 images\ntest:  # test images (optional)\n\n# Classes\nnames:\n  0: person\n  1: bicycle\n  2: car\n  3: motorcycle\n  4: airplane\n  5: bus\n  6: train\n  7: truck\n  8: boat\n  9: traffic light\n  10: fire hydrant\n  11: stop sign\n  12: parking meter\n  13: bench\n  14: bird\n  15: cat\n  16: dog\n  17: horse\n  18: sheep\n  19: cow\n  20: elephant\n  21: bear\n  22: zebra\n  23: giraffe\n  24: backpack\n  25: umbrella\n  26: handbag\n  27: tie\n  28: suitcase\n  29: frisbee\n  30: skis\n  31: snowboard\n  32: sports ball\n  33: kite\n  34: baseball bat\n  35: baseball glove\n  36: skateboard\n  37: surfboard\n  38: tennis racket\n  39: bottle\n  40: wine glass\n  41: cup\n  42: fork\n  43: knife\n  44: spoon\n  45: bowl\n  46: banana\n  47: apple\n  48: sandwich\n  49: orange\n  50: broccoli\n  51: carrot\n  52: hot dog\n  53: pizza\n  54: donut\n  55: cake\n  56: chair\n  57: couch\n  58: potted plant\n  59: bed\n  60: dining table\n  61: toilet\n  62: tv\n  63: laptop\n  64: mouse\n  65: remote\n  66: keyboard\n  67: cell phone\n  68: microwave\n  69: oven\n  70: toaster\n  71: sink\n  72: refrigerator\n  73: book\n  74: clock\n  75: vase\n  76: scissors\n  77: teddy bear\n  78: hair drier\n  79: toothbrush\n\n\n# Download script/URL (optional)\ndownload: https://ultralytics.com/assets/coco8.zip\n"
  },
  {
    "path": "ultralytics/datasets/create_toy_dataset.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": 11,\n   \"id\": \"dbed36fc\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import os\\n\",\n    \"import shutil\\n\",\n    \"import random\\n\",\n    \"\\n\",\n    \"def select_and_copy_files(source_dir_images, source_dir_labels, dest_dir_images, dest_dir_labels, num_files, categories):\\n\",\n    \"    for category in categories:\\n\",\n    \"        source_subdir_images = os.path.join(source_dir_images, category)\\n\",\n    \"        source_subdir_labels = os.path.join(source_dir_labels, category)\\n\",\n    \"        dest_subdir_images = os.path.join(dest_dir_images, category)\\n\",\n    \"        dest_subdir_labels = os.path.join(dest_dir_labels, category)\\n\",\n    \"\\n\",\n    \"        # 创建目标子目录，如果它们不存在的话\\n\",\n    \"        os.makedirs(dest_subdir_images, exist_ok=True)\\n\",\n    \"        os.makedirs(dest_subdir_labels, exist_ok=True)\\n\",\n    \"\\n\",\n    \"        # 获取源目录中的所有.jpg和.txt文件\\n\",\n    \"        all_images = [f[:-4] for f in os.listdir(source_subdir_images) if os.path.isfile(os.path.join(source_subdir_images, f)) and f.endswith('.jpg')]\\n\",\n    \"        all_labels = [f[:-4] for f in os.listdir(source_subdir_labels) if os.path.isfile(os.path.join(source_subdir_labels, f)) and f.endswith('.txt')]\\n\",\n    \"\\n\",\n    \"        # 找到同时存在于两个目录中的文件\\n\",\n    \"        common_files = list(set(all_images) & set(all_labels))\\n\",\n    \"\\n\",\n    \"        if len(common_files) < num_files[category]:\\n\",\n    \"            raise ValueError(f\\\"Only {len(common_files)} common files found in {category}. Cannot select {num_files[category]} files.\\\")\\n\",\n    \"\\n\",\n    \"        selected_files = random.sample(common_files, num_files[category])\\n\",\n    \"\\n\",\n    \"        for file in selected_files:\\n\",\n    \"            src_file_image = os.path.join(source_subdir_images, file + '.jpg')\\n\",\n    \"            src_file_label = os.path.join(source_subdir_labels, file + '.txt')\\n\",\n    \"            dst_file_image = os.path.join(dest_subdir_images, file + '.jpg')\\n\",\n    \"            dst_file_label = os.path.join(dest_subdir_labels, file + '.txt')\\n\",\n    \"\\n\",\n    \"            shutil.copy(src_file_image, dst_file_image)\\n\",\n    \"            shutil.copy(src_file_label, dst_file_label)\\n\",\n    \"\\n\",\n    \"# 在以下目录进行操作\\n\",\n    \"source_directory_images = \\\"/data/jiayuan/BDDcoco/yolo_v8/images\\\"\\n\",\n    \"source_directory_labels = \\\"/data/jiayuan/BDDcoco/yolo_v8/labels\\\"\\n\",\n    \"destination_directory_images = \\\"/data/jiayuan/BDDcoco/yolo_v8_toy/images\\\"\\n\",\n    \"destination_directory_labels = \\\"/data/jiayuan/BDDcoco/yolo_v8_toy/labels\\\"\\n\",\n    \"\\n\",\n    \"# 你想从中选择文件的子目录，以及每个子目录下要选择的文件数量\\n\",\n    \"categories = ['train2017', 'val2017']\\n\",\n    \"num_of_files = {'train2017': 100, 'val2017': 10}\\n\",\n    \"\\n\",\n    \"# 选择并复制.jpg和.txt文件\\n\",\n    \"select_and_copy_files(source_directory_images, source_directory_labels, destination_directory_images, destination_directory_labels, num_of_files, categories)\\n\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"3193eea8\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python [conda env:yolo8]\",\n   \"language\": \"python\",\n   \"name\": \"conda-env-yolo8-py\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.7.16\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
  },
  {
    "path": "ultralytics/datasets/xView.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# DIUx xView 2018 Challenge https://challenge.xviewdataset.org by U.S. National Geospatial-Intelligence Agency (NGA)\n# --------  DOWNLOAD DATA MANUALLY and jar xf val_images.zip to 'datasets/xView' before running train command!  --------\n# Example usage: yolo train data=xView.yaml\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── xView  ← downloads here (20.7 GB)\n\n\n# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]\npath: ../datasets/xView  # dataset root dir\ntrain: images/autosplit_train.txt  # train images (relative to 'path') 90% of 847 train images\nval: images/autosplit_val.txt  # train images (relative to 'path') 10% of 847 train images\n\n# Classes\nnames:\n  0: Fixed-wing Aircraft\n  1: Small Aircraft\n  2: Cargo Plane\n  3: Helicopter\n  4: Passenger Vehicle\n  5: Small Car\n  6: Bus\n  7: Pickup Truck\n  8: Utility Truck\n  9: Truck\n  10: Cargo Truck\n  11: Truck w/Box\n  12: Truck Tractor\n  13: Trailer\n  14: Truck w/Flatbed\n  15: Truck w/Liquid\n  16: Crane Truck\n  17: Railway Vehicle\n  18: Passenger Car\n  19: Cargo Car\n  20: Flat Car\n  21: Tank car\n  22: Locomotive\n  23: Maritime Vessel\n  24: Motorboat\n  25: Sailboat\n  26: Tugboat\n  27: Barge\n  28: Fishing Vessel\n  29: Ferry\n  30: Yacht\n  31: Container Ship\n  32: Oil Tanker\n  33: Engineering Vehicle\n  34: Tower crane\n  35: Container Crane\n  36: Reach Stacker\n  37: Straddle Carrier\n  38: Mobile Crane\n  39: Dump Truck\n  40: Haul Truck\n  41: Scraper/Tractor\n  42: Front loader/Bulldozer\n  43: Excavator\n  44: Cement Mixer\n  45: Ground Grader\n  46: Hut/Tent\n  47: Shed\n  48: Building\n  49: Aircraft Hangar\n  50: Damaged Building\n  51: Facility\n  52: Construction Site\n  53: Vehicle Lot\n  54: Helipad\n  55: Storage Tank\n  56: Shipping container lot\n  57: Shipping Container\n  58: Pylon\n  59: Tower\n\n\n# Download script/URL (optional) ---------------------------------------------------------------------------------------\ndownload: |\n  import json\n  import os\n  from pathlib import Path\n\n  import numpy as np\n  from PIL import Image\n  from tqdm import tqdm\n\n  from ultralytics.yolo.data.dataloaders.v5loader import autosplit\n  from ultralytics.yolo.utils.ops import xyxy2xywhn\n\n\n  def convert_labels(fname=Path('xView/xView_train.geojson')):\n      # Convert xView geoJSON labels to YOLO format\n      path = fname.parent\n      with open(fname) as f:\n          print(f'Loading {fname}...')\n          data = json.load(f)\n\n      # Make dirs\n      labels = Path(path / 'labels' / 'train')\n      os.system(f'rm -rf {labels}')\n      labels.mkdir(parents=True, exist_ok=True)\n\n      # xView classes 11-94 to 0-59\n      xview_class2index = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, -1, 9, 10, 11,\n                           12, 13, 14, 15, -1, -1, 16, 17, 18, 19, 20, 21, 22, -1, 23, 24, 25, -1, 26, 27, -1, 28, -1,\n                           29, 30, 31, 32, 33, 34, 35, 36, 37, -1, 38, 39, 40, 41, 42, 43, 44, 45, -1, -1, -1, -1, 46,\n                           47, 48, 49, -1, 50, 51, -1, 52, -1, -1, -1, 53, 54, -1, 55, -1, -1, 56, -1, 57, -1, 58, 59]\n\n      shapes = {}\n      for feature in tqdm(data['features'], desc=f'Converting {fname}'):\n          p = feature['properties']\n          if p['bounds_imcoords']:\n              id = p['image_id']\n              file = path / 'train_images' / id\n              if file.exists():  # 1395.tif missing\n                  try:\n                      box = np.array([int(num) for num in p['bounds_imcoords'].split(\",\")])\n                      assert box.shape[0] == 4, f'incorrect box shape {box.shape[0]}'\n                      cls = p['type_id']\n                      cls = xview_class2index[int(cls)]  # xView class to 0-60\n                      assert 59 >= cls >= 0, f'incorrect class index {cls}'\n\n                      # Write YOLO label\n                      if id not in shapes:\n                          shapes[id] = Image.open(file).size\n                      box = xyxy2xywhn(box[None].astype(np.float), w=shapes[id][0], h=shapes[id][1], clip=True)\n                      with open((labels / id).with_suffix('.txt'), 'a') as f:\n                          f.write(f\"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\\n\")  # write label.txt\n                  except Exception as e:\n                      print(f'WARNING: skipping one label for {file}: {e}')\n\n\n  # Download manually from https://challenge.xviewdataset.org\n  dir = Path(yaml['path'])  # dataset root dir\n  # urls = ['https://d307kc0mrhucc3.cloudfront.net/train_labels.zip',  # train labels\n  #         'https://d307kc0mrhucc3.cloudfront.net/train_images.zip',  # 15G, 847 train images\n  #         'https://d307kc0mrhucc3.cloudfront.net/val_images.zip']  # 5G, 282 val images (no labels)\n  # download(urls, dir=dir)\n\n  # Convert labels\n  convert_labels(dir / 'xView_train.geojson')\n\n  # Move images\n  images = Path(dir / 'images')\n  images.mkdir(parents=True, exist_ok=True)\n  Path(dir / 'train_images').rename(dir / 'images' / 'train')\n  Path(dir / 'val_images').rename(dir / 'images' / 'val')\n\n  # Split\n  autosplit(dir / 'images' / 'train')\n"
  },
  {
    "path": "ultralytics/hub/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport requests\n\nfrom ultralytics.hub.auth import Auth\nfrom ultralytics.hub.utils import PREFIX\nfrom ultralytics.yolo.data.utils import HUBDatasetStats\nfrom ultralytics.yolo.utils import LOGGER, SETTINGS, USER_CONFIG_DIR, yaml_save\n\n\ndef login(api_key=''):\n    \"\"\"\n    Log in to the Ultralytics HUB API using the provided API key.\n\n    Args:\n        api_key (str, optional): May be an API key or a combination API key and model ID, i.e. key_id\n\n    Example:\n        from ultralytics import hub\n        hub.login('API_KEY')\n    \"\"\"\n    Auth(api_key, verbose=True)\n\n\ndef logout():\n    \"\"\"\n    Log out of Ultralytics HUB by removing the API key from the settings file. To log in again, use 'yolo hub login'.\n\n    Example:\n        from ultralytics import hub\n        hub.logout()\n    \"\"\"\n    SETTINGS['api_key'] = ''\n    yaml_save(USER_CONFIG_DIR / 'settings.yaml', SETTINGS)\n    LOGGER.info(f\"{PREFIX}logged out ✅. To log in again, use 'yolo hub login'.\")\n\n\ndef start(key=''):\n    \"\"\"\n    Start training models with Ultralytics HUB (DEPRECATED).\n\n    Args:\n        key (str, optional): A string containing either the API key and model ID combination (apikey_modelid),\n                               or the full model URL (https://hub.ultralytics.com/models/apikey_modelid).\n    \"\"\"\n    api_key, model_id = key.split('_')\n    LOGGER.warning(f\"\"\"\nWARNING ⚠️ ultralytics.start() is deprecated after 8.0.60. Updated usage to train Ultralytics HUB models is:\n\nfrom ultralytics import YOLO, hub\n\nhub.login('{api_key}')\nmodel = YOLO('https://hub.ultralytics.com/models/{model_id}')\nmodel.train()\"\"\")\n\n\ndef reset_model(model_id=''):\n    \"\"\"Reset a trained model to an untrained state.\"\"\"\n    r = requests.post('https://api.ultralytics.com/model-reset', json={'apiKey': Auth().api_key, 'modelId': model_id})\n    if r.status_code == 200:\n        LOGGER.info(f'{PREFIX}Model reset successfully')\n        return\n    LOGGER.warning(f'{PREFIX}Model reset failure {r.status_code} {r.reason}')\n\n\ndef export_fmts_hub():\n    \"\"\"Returns a list of HUB-supported export formats.\"\"\"\n    from ultralytics.yolo.engine.exporter import export_formats\n    return list(export_formats()['Argument'][1:]) + ['ultralytics_tflite', 'ultralytics_coreml']\n\n\ndef export_model(model_id='', format='torchscript'):\n    \"\"\"Export a model to all formats.\"\"\"\n    assert format in export_fmts_hub(), f\"Unsupported export format '{format}', valid formats are {export_fmts_hub()}\"\n    r = requests.post(f'https://api.ultralytics.com/v1/models/{model_id}/export',\n                      json={'format': format},\n                      headers={'x-api-key': Auth().api_key})\n    assert r.status_code == 200, f'{PREFIX}{format} export failure {r.status_code} {r.reason}'\n    LOGGER.info(f'{PREFIX}{format} export started ✅')\n\n\ndef get_export(model_id='', format='torchscript'):\n    \"\"\"Get an exported model dictionary with download URL.\"\"\"\n    assert format in export_fmts_hub(), f\"Unsupported export format '{format}', valid formats are {export_fmts_hub()}\"\n    r = requests.post('https://api.ultralytics.com/get-export',\n                      json={\n                          'apiKey': Auth().api_key,\n                          'modelId': model_id,\n                          'format': format})\n    assert r.status_code == 200, f'{PREFIX}{format} get_export failure {r.status_code} {r.reason}'\n    return r.json()\n\n\ndef check_dataset(path='', task='detect'):\n    \"\"\"\n    Function for error-checking HUB dataset Zip file before upload\n\n    Arguments\n        path:           Path to data.zip (with data.yaml inside data.zip)\n        task:           Dataset task. Options are 'detect', 'segment', 'pose', 'classify'.\n\n    Usage\n        from ultralytics.hub import check_dataset\n        check_dataset('path/to/coco8.zip', task='detect')  # detect dataset\n        check_dataset('path/to/coco8-seg.zip', task='segment')  # segment dataset\n        check_dataset('path/to/coco8-pose.zip', task='pose')  # pose dataset\n    \"\"\"\n    HUBDatasetStats(path=path, task=task).get_json()\n    LOGGER.info('Checks completed correctly ✅. Upload this dataset to https://hub.ultralytics.com/datasets/.')\n\n\nif __name__ == '__main__':\n    start()\n"
  },
  {
    "path": "ultralytics/hub/auth.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport requests\n\nfrom ultralytics.hub.utils import HUB_API_ROOT, PREFIX, request_with_credentials\nfrom ultralytics.yolo.utils import LOGGER, SETTINGS, emojis, is_colab, set_settings\n\nAPI_KEY_URL = 'https://hub.ultralytics.com/settings?tab=api+keys'\n\n\nclass Auth:\n    id_token = api_key = model_key = False\n\n    def __init__(self, api_key='', verbose=False):\n        \"\"\"\n        Initialize the Auth class with an optional API key.\n\n        Args:\n            api_key (str, optional): May be an API key or a combination API key and model ID, i.e. key_id\n        \"\"\"\n        # Split the input API key in case it contains a combined key_model and keep only the API key part\n        api_key = api_key.split('_')[0]\n\n        # Set API key attribute as value passed or SETTINGS API key if none passed\n        self.api_key = api_key or SETTINGS.get('api_key', '')\n\n        # If an API key is provided\n        if self.api_key:\n            # If the provided API key matches the API key in the SETTINGS\n            if self.api_key == SETTINGS.get('api_key'):\n                # Log that the user is already logged in\n                if verbose:\n                    LOGGER.info(f'{PREFIX}Authenticated ✅')\n                return\n            else:\n                # Attempt to authenticate with the provided API key\n                success = self.authenticate()\n        # If the API key is not provided and the environment is a Google Colab notebook\n        elif is_colab():\n            # Attempt to authenticate using browser cookies\n            success = self.auth_with_cookies()\n        else:\n            # Request an API key\n            success = self.request_api_key()\n\n        # Update SETTINGS with the new API key after successful authentication\n        if success:\n            set_settings({'api_key': self.api_key})\n            # Log that the new login was successful\n            if verbose:\n                LOGGER.info(f'{PREFIX}New authentication successful ✅')\n        elif verbose:\n            LOGGER.info(f'{PREFIX}Retrieve API key from {API_KEY_URL}')\n\n    def request_api_key(self, max_attempts=3):\n        \"\"\"\n        Prompt the user to input their API key. Returns the model ID.\n        \"\"\"\n        import getpass\n        for attempts in range(max_attempts):\n            LOGGER.info(f'{PREFIX}Login. Attempt {attempts + 1} of {max_attempts}')\n            input_key = getpass.getpass(f'Enter API key from {API_KEY_URL} ')\n            self.api_key = input_key.split('_')[0]  # remove model id if present\n            if self.authenticate():\n                return True\n        raise ConnectionError(emojis(f'{PREFIX}Failed to authenticate ❌'))\n\n    def authenticate(self) -> bool:\n        \"\"\"\n        Attempt to authenticate with the server using either id_token or API key.\n\n        Returns:\n            bool: True if authentication is successful, False otherwise.\n        \"\"\"\n        try:\n            header = self.get_auth_header()\n            if header:\n                r = requests.post(f'{HUB_API_ROOT}/v1/auth', headers=header)\n                if not r.json().get('success', False):\n                    raise ConnectionError('Unable to authenticate.')\n                return True\n            raise ConnectionError('User has not authenticated locally.')\n        except ConnectionError:\n            self.id_token = self.api_key = False  # reset invalid\n            LOGGER.warning(f'{PREFIX}Invalid API key ⚠️')\n            return False\n\n    def auth_with_cookies(self) -> bool:\n        \"\"\"\n        Attempt to fetch authentication via cookies and set id_token.\n        User must be logged in to HUB and running in a supported browser.\n\n        Returns:\n            bool: True if authentication is successful, False otherwise.\n        \"\"\"\n        if not is_colab():\n            return False  # Currently only works with Colab\n        try:\n            authn = request_with_credentials(f'{HUB_API_ROOT}/v1/auth/auto')\n            if authn.get('success', False):\n                self.id_token = authn.get('data', {}).get('idToken', None)\n                self.authenticate()\n                return True\n            raise ConnectionError('Unable to fetch browser authentication details.')\n        except ConnectionError:\n            self.id_token = False  # reset invalid\n            return False\n\n    def get_auth_header(self):\n        \"\"\"\n        Get the authentication header for making API requests.\n\n        Returns:\n            (dict): The authentication header if id_token or API key is set, None otherwise.\n        \"\"\"\n        if self.id_token:\n            return {'authorization': f'Bearer {self.id_token}'}\n        elif self.api_key:\n            return {'x-api-key': self.api_key}\n        else:\n            return None\n\n    def get_state(self) -> bool:\n        \"\"\"\n        Get the authentication state.\n\n        Returns:\n            bool: True if either id_token or API key is set, False otherwise.\n        \"\"\"\n        return self.id_token or self.api_key\n\n    def set_api_key(self, key: str):\n        \"\"\"\n        Set the API key for authentication.\n\n        Args:\n            key (str): The API key string.\n        \"\"\"\n        self.api_key = key\n"
  },
  {
    "path": "ultralytics/hub/session.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nimport signal\nimport sys\nfrom pathlib import Path\nfrom time import sleep\n\nimport requests\n\nfrom ultralytics.hub.utils import HUB_API_ROOT, PREFIX, smart_request\nfrom ultralytics.yolo.utils import LOGGER, __version__, checks, emojis, is_colab, threaded\nfrom ultralytics.yolo.utils.errors import HUBModelError\n\nAGENT_NAME = f'python-{__version__}-colab' if is_colab() else f'python-{__version__}-local'\n\n\nclass HUBTrainingSession:\n    \"\"\"\n    HUB training session for Ultralytics HUB YOLO models. Handles model initialization, heartbeats, and checkpointing.\n\n    Args:\n        url (str): Model identifier used to initialize the HUB training session.\n\n    Attributes:\n        agent_id (str): Identifier for the instance communicating with the server.\n        model_id (str): Identifier for the YOLOv5 model being trained.\n        model_url (str): URL for the model in Ultralytics HUB.\n        api_url (str): API URL for the model in Ultralytics HUB.\n        auth_header (Dict): Authentication header for the Ultralytics HUB API requests.\n        rate_limits (Dict): Rate limits for different API calls (in seconds).\n        timers (Dict): Timers for rate limiting.\n        metrics_queue (Dict): Queue for the model's metrics.\n        model (Dict): Model data fetched from Ultralytics HUB.\n        alive (bool): Indicates if the heartbeat loop is active.\n    \"\"\"\n\n    def __init__(self, url):\n        \"\"\"\n        Initialize the HUBTrainingSession with the provided model identifier.\n\n        Args:\n            url (str): Model identifier used to initialize the HUB training session.\n                         It can be a URL string or a model key with specific format.\n\n        Raises:\n            ValueError: If the provided model identifier is invalid.\n            ConnectionError: If connecting with global API key is not supported.\n        \"\"\"\n\n        from ultralytics.hub.auth import Auth\n\n        # Parse input\n        if url.startswith('https://hub.ultralytics.com/models/'):\n            url = url.split('https://hub.ultralytics.com/models/')[-1]\n        if [len(x) for x in url.split('_')] == [42, 20]:\n            key, model_id = url.split('_')\n        elif len(url) == 20:\n            key, model_id = '', url\n        else:\n            raise HUBModelError(f\"model='{url}' not found. Check format is correct, i.e. \"\n                                f\"model='https://hub.ultralytics.com/models/MODEL_ID' and try again.\")\n\n        # Authorize\n        auth = Auth(key)\n        self.agent_id = None  # identifies which instance is communicating with server\n        self.model_id = model_id\n        self.model_url = f'https://hub.ultralytics.com/models/{model_id}'\n        self.api_url = f'{HUB_API_ROOT}/v1/models/{model_id}'\n        self.auth_header = auth.get_auth_header()\n        self.rate_limits = {'metrics': 3.0, 'ckpt': 900.0, 'heartbeat': 300.0}  # rate limits (seconds)\n        self.timers = {}  # rate limit timers (seconds)\n        self.metrics_queue = {}  # metrics queue\n        self.model = self._get_model()\n        self.alive = True\n        self._start_heartbeat()  # start heartbeats\n        self._register_signal_handlers()\n        LOGGER.info(f'{PREFIX}View model at {self.model_url} 🚀')\n\n    def _register_signal_handlers(self):\n        \"\"\"Register signal handlers for SIGTERM and SIGINT signals to gracefully handle termination.\"\"\"\n        signal.signal(signal.SIGTERM, self._handle_signal)\n        signal.signal(signal.SIGINT, self._handle_signal)\n\n    def _handle_signal(self, signum, frame):\n        \"\"\"\n        Handle kill signals and prevent heartbeats from being sent on Colab after termination.\n        This method does not use frame, it is included as it is passed by signal.\n        \"\"\"\n        if self.alive is True:\n            LOGGER.info(f'{PREFIX}Kill signal received! ❌')\n            self._stop_heartbeat()\n            sys.exit(signum)\n\n    def _stop_heartbeat(self):\n        \"\"\"Terminate the heartbeat loop.\"\"\"\n        self.alive = False\n\n    def upload_metrics(self):\n        \"\"\"Upload model metrics to Ultralytics HUB.\"\"\"\n        payload = {'metrics': self.metrics_queue.copy(), 'type': 'metrics'}\n        smart_request('post', self.api_url, json=payload, headers=self.auth_header, code=2)\n\n    def _get_model(self):\n        \"\"\"Fetch and return model data from Ultralytics HUB.\"\"\"\n        api_url = f'{HUB_API_ROOT}/v1/models/{self.model_id}'\n\n        try:\n            response = smart_request('get', api_url, headers=self.auth_header, thread=False, code=0)\n            data = response.json().get('data', None)\n\n            if data.get('status', None) == 'trained':\n                raise ValueError(emojis(f'Model is already trained and uploaded to {self.model_url} 🚀'))\n\n            if not data.get('data', None):\n                raise ValueError('Dataset may still be processing. Please wait a minute and try again.')  # RF fix\n            self.model_id = data['id']\n\n            if data['status'] == 'new':  # new model to start training\n                self.train_args = {\n                    # TODO: deprecate 'batch_size' key for 'batch' in 3Q23\n                    'batch': data['batch' if ('batch' in data) else 'batch_size'],\n                    'epochs': data['epochs'],\n                    'imgsz': data['imgsz'],\n                    'patience': data['patience'],\n                    'device': data['device'],\n                    'cache': data['cache'],\n                    'data': data['data']}\n                self.model_file = data.get('cfg') or data.get('weights')  # cfg for pretrained=False\n                self.model_file = checks.check_yolov5u_filename(self.model_file, verbose=False)  # YOLOv5->YOLOv5u\n            elif data['status'] == 'training':  # existing model to resume training\n                self.train_args = {'data': data['data'], 'resume': True}\n                self.model_file = data['resume']\n\n            return data\n        except requests.exceptions.ConnectionError as e:\n            raise ConnectionRefusedError('ERROR: The HUB server is not online. Please try again later.') from e\n        except Exception:\n            raise\n\n    def upload_model(self, epoch, weights, is_best=False, map=0.0, final=False):\n        \"\"\"\n        Upload a model checkpoint to Ultralytics HUB.\n\n        Args:\n            epoch (int): The current training epoch.\n            weights (str): Path to the model weights file.\n            is_best (bool): Indicates if the current model is the best one so far.\n            map (float): Mean average precision of the model.\n            final (bool): Indicates if the model is the final model after training.\n        \"\"\"\n        if Path(weights).is_file():\n            with open(weights, 'rb') as f:\n                file = f.read()\n        else:\n            LOGGER.warning(f'{PREFIX}WARNING ⚠️ Model upload issue. Missing model {weights}.')\n            file = None\n        url = f'{self.api_url}/upload'\n        # url = 'http://httpbin.org/post'  # for debug\n        data = {'epoch': epoch}\n        if final:\n            data.update({'type': 'final', 'map': map})\n            smart_request('post',\n                          url,\n                          data=data,\n                          files={'best.pt': file},\n                          headers=self.auth_header,\n                          retry=10,\n                          timeout=3600,\n                          thread=False,\n                          progress=True,\n                          code=4)\n        else:\n            data.update({'type': 'epoch', 'isBest': bool(is_best)})\n            smart_request('post', url, data=data, files={'last.pt': file}, headers=self.auth_header, code=3)\n\n    @threaded\n    def _start_heartbeat(self):\n        \"\"\"Begin a threaded heartbeat loop to report the agent's status to Ultralytics HUB.\"\"\"\n        while self.alive:\n            r = smart_request('post',\n                              f'{HUB_API_ROOT}/v1/agent/heartbeat/models/{self.model_id}',\n                              json={\n                                  'agent': AGENT_NAME,\n                                  'agentId': self.agent_id},\n                              headers=self.auth_header,\n                              retry=0,\n                              code=5,\n                              thread=False)  # already in a thread\n            self.agent_id = r.json().get('data', {}).get('agentId', None)\n            sleep(self.rate_limits['heartbeat'])\n"
  },
  {
    "path": "ultralytics/hub/utils.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport os\nimport platform\nimport random\nimport sys\nimport threading\nimport time\nfrom pathlib import Path\n\nimport requests\nfrom tqdm import tqdm\n\nfrom ultralytics.yolo.utils import (ENVIRONMENT, LOGGER, ONLINE, RANK, SETTINGS, TESTS_RUNNING, TQDM_BAR_FORMAT,\n                                    TryExcept, __version__, colorstr, get_git_origin_url, is_colab, is_git_dir,\n                                    is_pip_package)\n\nPREFIX = colorstr('Ultralytics HUB: ')\nHELP_MSG = 'If this issue persists please visit https://github.com/ultralytics/hub/issues for assistance.'\nHUB_API_ROOT = os.environ.get('ULTRALYTICS_HUB_API', 'https://api.ultralytics.com')\n\n\ndef request_with_credentials(url: str) -> any:\n    \"\"\"\n    Make an AJAX request with cookies attached in a Google Colab environment.\n\n    Args:\n        url (str): The URL to make the request to.\n\n    Returns:\n        (any): The response data from the AJAX request.\n\n    Raises:\n        OSError: If the function is not run in a Google Colab environment.\n    \"\"\"\n    if not is_colab():\n        raise OSError('request_with_credentials() must run in a Colab environment')\n    from google.colab import output  # noqa\n    from IPython import display  # noqa\n    display.display(\n        display.Javascript(\"\"\"\n            window._hub_tmp = new Promise((resolve, reject) => {\n                const timeout = setTimeout(() => reject(\"Failed authenticating existing browser session\"), 5000)\n                fetch(\"%s\", {\n                    method: 'POST',\n                    credentials: 'include'\n                })\n                    .then((response) => resolve(response.json()))\n                    .then((json) => {\n                    clearTimeout(timeout);\n                    }).catch((err) => {\n                    clearTimeout(timeout);\n                    reject(err);\n                });\n            });\n            \"\"\" % url))\n    return output.eval_js('_hub_tmp')\n\n\ndef requests_with_progress(method, url, **kwargs):\n    \"\"\"\n    Make an HTTP request using the specified method and URL, with an optional progress bar.\n\n    Args:\n        method (str): The HTTP method to use (e.g. 'GET', 'POST').\n        url (str): The URL to send the request to.\n        **kwargs (dict): Additional keyword arguments to pass to the underlying `requests.request` function.\n\n    Returns:\n        (requests.Response): The response object from the HTTP request.\n\n    Note:\n        If 'progress' is set to True, the progress bar will display the download progress\n        for responses with a known content length.\n    \"\"\"\n    progress = kwargs.pop('progress', False)\n    if not progress:\n        return requests.request(method, url, **kwargs)\n    response = requests.request(method, url, stream=True, **kwargs)\n    total = int(response.headers.get('content-length', 0))  # total size\n    pbar = tqdm(total=total, unit='B', unit_scale=True, unit_divisor=1024, bar_format=TQDM_BAR_FORMAT)\n    for data in response.iter_content(chunk_size=1024):\n        pbar.update(len(data))\n    pbar.close()\n    return response\n\n\ndef smart_request(method, url, retry=3, timeout=30, thread=True, code=-1, verbose=True, progress=False, **kwargs):\n    \"\"\"\n    Makes an HTTP request using the 'requests' library, with exponential backoff retries up to a specified timeout.\n\n    Args:\n        method (str): The HTTP method to use for the request. Choices are 'post' and 'get'.\n        url (str): The URL to make the request to.\n        retry (int, optional): Number of retries to attempt before giving up. Default is 3.\n        timeout (int, optional): Timeout in seconds after which the function will give up retrying. Default is 30.\n        thread (bool, optional): Whether to execute the request in a separate daemon thread. Default is True.\n        code (int, optional): An identifier for the request, used for logging purposes. Default is -1.\n        verbose (bool, optional): A flag to determine whether to print out to console or not. Default is True.\n        progress (bool, optional): Whether to show a progress bar during the request. Default is False.\n        **kwargs (dict): Keyword arguments to be passed to the requests function specified in method.\n\n    Returns:\n        (requests.Response): The HTTP response object. If the request is executed in a separate thread, returns None.\n    \"\"\"\n    retry_codes = (408, 500)  # retry only these codes\n\n    @TryExcept(verbose=verbose)\n    def func(func_method, func_url, **func_kwargs):\n        \"\"\"Make HTTP requests with retries and timeouts, with optional progress tracking.\"\"\"\n        r = None  # response\n        t0 = time.time()  # initial time for timer\n        for i in range(retry + 1):\n            if (time.time() - t0) > timeout:\n                break\n            r = requests_with_progress(func_method, func_url, **func_kwargs)  # i.e. get(url, data, json, files)\n            if r.status_code < 300:  # return codes in the 2xx range are generally considered \"good\" or \"successful\"\n                break\n            try:\n                m = r.json().get('message', 'No JSON message.')\n            except AttributeError:\n                m = 'Unable to read JSON.'\n            if i == 0:\n                if r.status_code in retry_codes:\n                    m += f' Retrying {retry}x for {timeout}s.' if retry else ''\n                elif r.status_code == 429:  # rate limit\n                    h = r.headers  # response headers\n                    m = f\"Rate limit reached ({h['X-RateLimit-Remaining']}/{h['X-RateLimit-Limit']}). \" \\\n                        f\"Please retry after {h['Retry-After']}s.\"\n                if verbose:\n                    LOGGER.warning(f'{PREFIX}{m} {HELP_MSG} ({r.status_code} #{code})')\n                if r.status_code not in retry_codes:\n                    return r\n            time.sleep(2 ** i)  # exponential standoff\n        return r\n\n    args = method, url\n    kwargs['progress'] = progress\n    if thread:\n        threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True).start()\n    else:\n        return func(*args, **kwargs)\n\n\nclass Events:\n    \"\"\"\n    A class for collecting anonymous event analytics. Event analytics are enabled when sync=True in settings and\n    disabled when sync=False. Run 'yolo settings' to see and update settings YAML file.\n\n    Attributes:\n        url (str): The URL to send anonymous events.\n        rate_limit (float): The rate limit in seconds for sending events.\n        metadata (dict): A dictionary containing metadata about the environment.\n        enabled (bool): A flag to enable or disable Events based on certain conditions.\n    \"\"\"\n\n    url = 'https://www.google-analytics.com/mp/collect?measurement_id=G-X8NCJYTQXM&api_secret=QLQrATrNSwGRFRLE-cbHJw'\n\n    def __init__(self):\n        \"\"\"\n        Initializes the Events object with default values for events, rate_limit, and metadata.\n        \"\"\"\n        self.events = []  # events list\n        self.rate_limit = 60.0  # rate limit (seconds)\n        self.t = 0.0  # rate limit timer (seconds)\n        self.metadata = {\n            'cli': Path(sys.argv[0]).name == 'yolo',\n            'install': 'git' if is_git_dir() else 'pip' if is_pip_package() else 'other',\n            'python': '.'.join(platform.python_version_tuple()[:2]),  # i.e. 3.10\n            'version': __version__,\n            'env': ENVIRONMENT,\n            'session_id': round(random.random() * 1E15),\n            'engagement_time_msec': 1000}\n        self.enabled = \\\n            SETTINGS['sync'] and \\\n            RANK in (-1, 0) and \\\n            not TESTS_RUNNING and \\\n            ONLINE and \\\n            (is_pip_package() or get_git_origin_url() == 'https://github.com/ultralytics/ultralytics.git')\n\n    def __call__(self, cfg):\n        \"\"\"\n        Attempts to add a new event to the events list and send events if the rate limit is reached.\n\n        Args:\n            cfg (IterableSimpleNamespace): The configuration object containing mode and task information.\n        \"\"\"\n        if not self.enabled:\n            # Events disabled, do nothing\n            return\n\n        # Attempt to add to events\n        if len(self.events) < 25:  # Events list limited to 25 events (drop any events past this)\n            params = {**self.metadata, **{'task': cfg.task}}\n            if cfg.mode == 'export':\n                params['format'] = cfg.format\n            self.events.append({'name': cfg.mode, 'params': params})\n\n        # Check rate limit\n        t = time.time()\n        if (t - self.t) < self.rate_limit:\n            # Time is under rate limiter, wait to send\n            return\n\n        # Time is over rate limiter, send now\n        data = {'client_id': SETTINGS['uuid'], 'events': self.events}  # SHA-256 anonymized UUID hash and events list\n\n        # POST equivalent to requests.post(self.url, json=data)\n        smart_request('post', self.url, json=data, retry=0, verbose=False)\n\n        # Reset events and rate limit timer\n        self.events = []\n        self.t = t\n\n\n# Run below code on hub/utils init -------------------------------------------------------------------------------------\nevents = Events()\n"
  },
  {
    "path": "ultralytics/models/README.md",
    "content": "## Models\n\nWelcome to the Ultralytics Models directory! Here you will find a wide variety of pre-configured model configuration\nfiles (`*.yaml`s) that can be used to create custom YOLO models. The models in this directory have been expertly crafted\nand fine-tuned by the Ultralytics team to provide the best performance for a wide range of object detection and image\nsegmentation tasks.\n\nThese model configurations cover a wide range of scenarios, from simple object detection to more complex tasks like\ninstance segmentation and object tracking. They are also designed to run efficiently on a variety of hardware platforms,\nfrom CPUs to GPUs. Whether you are a seasoned machine learning practitioner or just getting started with YOLO, this\ndirectory provides a great starting point for your custom model development needs.\n\nTo get started, simply browse through the models in this directory and find one that best suits your needs. Once you've\nselected a model, you can use the provided `*.yaml` file to train and deploy your custom YOLO model with ease. See full\ndetails at the Ultralytics [Docs](https://docs.ultralytics.com/models), and if you need help or have any questions, feel free\nto reach out to the Ultralytics team for support. So, don't wait, start creating your custom YOLO model now!\n\n### Usage\n\nModel `*.yaml` files may be used directly in the Command Line Interface (CLI) with a `yolo` command:\n\n```bash\nyolo task=detect mode=train model=yolov8n.yaml data=coco128.yaml epochs=100\n```\n\nThey may also be used directly in a Python environment, and accepts the same\n[arguments](https://docs.ultralytics.com/usage/cfg/) as in the CLI example above:\n\n```python\nfrom ultralytics import YOLO\n\nmodel = YOLO(\"model.yaml\")  # build a YOLOv8n model from scratch\n# YOLO(\"model.pt\")  use pre-trained model if available\nmodel.info()  # display model information\nmodel.train(data=\"coco128.yaml\", epochs=100)  # train the model\n```\n\n## Pre-trained Model Architectures\n\nUltralytics supports many model architectures. Visit https://docs.ultralytics.com/models to view detailed information\nand usage. Any of these models can be used by loading their configs or pretrained checkpoints if available.\n\n## Contributing New Models\n\nIf you've developed a new model architecture or have improvements for existing models that you'd like to contribute to the Ultralytics community, please submit your contribution in a new Pull Request. For more details, visit our [Contributing Guide](https://docs.ultralytics.com/help/contributing).\n"
  },
  {
    "path": "ultralytics/models/rt-detr/rt-detr-l.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n-cls.yaml' will call yolov8-cls.yaml with scale 'n'\n  # [depth, width, max_channels]\n  l: [1.00, 1.00, 1024]\n\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, HGStem, [32, 48]]  # 0-P2/4\n  - [-1, 6, HGBlock, [48, 128, 3]]  # stage 1\n\n  - [-1, 1, DWConv, [128, 3, 2, 1, False]]  # 2-P3/8\n  - [-1, 6, HGBlock, [96, 512, 3]]   # stage 2\n\n  - [-1, 1, DWConv, [512, 3, 2, 1, False]]  # 4-P3/16\n  - [-1, 6, HGBlock, [192, 1024, 5, True, False]]  # cm, c2, k, light, shortcut\n  - [-1, 6, HGBlock, [192, 1024, 5, True, True]]\n  - [-1, 6, HGBlock, [192, 1024, 5, True, True]]  # stage 3\n\n  - [-1, 1, DWConv, [1024, 3, 2, 1, False]]  # 8-P4/32\n  - [-1, 6, HGBlock, [384, 2048, 5, True, False]]  # stage 4\n\nhead:\n  - [-1, 1, Conv, [256, 1, 1, None, 1, 1, False]]  # 10 input_proj.2\n  - [-1, 1, AIFI, [1024, 8]]\n  - [-1, 1, Conv, [256, 1, 1]]   # 12, Y5, lateral_convs.0\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [7, 1, Conv, [256, 1, 1, None, 1, 1, False]]  # 14 input_proj.1\n  - [[-2, -1], 1, Concat, [1]]\n  - [-1, 3, RepC3, [256]]  # 16, fpn_blocks.0\n  - [-1, 1, Conv, [256, 1, 1]]   # 17, Y4, lateral_convs.1\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [3, 1, Conv, [256, 1, 1, None, 1, 1, False]]  # 19 input_proj.0\n  - [[-2, -1], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, RepC3, [256]]    # X3 (21), fpn_blocks.1\n\n  - [-1, 1, Conv, [256, 3, 2]]   # 22, downsample_convs.0\n  - [[-1, 17], 1, Concat, [1]]  # cat Y4\n  - [-1, 3, RepC3, [256]]    # F4 (24), pan_blocks.0\n\n  - [-1, 1, Conv, [256, 3, 2]]   # 25, downsample_convs.1\n  - [[-1, 12], 1, Concat, [1]]  # cat Y5\n  - [-1, 3, RepC3, [256]]    # F5 (27), pan_blocks.1\n\n  - [[21, 24, 27], 1, RTDETRDecoder, [nc]]  # Detect(P3, P4, P5)\n"
  },
  {
    "path": "ultralytics/models/rt-detr/rt-detr-x.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n-cls.yaml' will call yolov8-cls.yaml with scale 'n'\n  # [depth, width, max_channels]\n  x: [1.00, 1.00, 2048]\n\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, HGStem, [32, 64]]  # 0-P2/4\n  - [-1, 6, HGBlock, [64, 128, 3]]  # stage 1\n\n  - [-1, 1, DWConv, [128, 3, 2, 1, False]]  # 2-P3/8\n  - [-1, 6, HGBlock, [128, 512, 3]]\n  - [-1, 6, HGBlock, [128, 512, 3, False, True]]   # 4-stage 2\n\n  - [-1, 1, DWConv, [512, 3, 2, 1, False]]  # 5-P3/16\n  - [-1, 6, HGBlock, [256, 1024, 5, True, False]]  # cm, c2, k, light, shortcut\n  - [-1, 6, HGBlock, [256, 1024, 5, True, True]]\n  - [-1, 6, HGBlock, [256, 1024, 5, True, True]]\n  - [-1, 6, HGBlock, [256, 1024, 5, True, True]]\n  - [-1, 6, HGBlock, [256, 1024, 5, True, True]]  # 10-stage 3\n\n  - [-1, 1, DWConv, [1024, 3, 2, 1, False]]  # 11-P4/32\n  - [-1, 6, HGBlock, [512, 2048, 5, True, False]]\n  - [-1, 6, HGBlock, [512, 2048, 5, True, True]]  # 13-stage 4\n\nhead:\n  - [-1, 1, Conv, [384, 1, 1, None, 1, 1, False]]  # 14 input_proj.2\n  - [-1, 1, AIFI, [2048, 8]]\n  - [-1, 1, Conv, [384, 1, 1]]   # 16, Y5, lateral_convs.0\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [10, 1, Conv, [384, 1, 1, None, 1, 1, False]]  # 18 input_proj.1\n  - [[-2, -1], 1, Concat, [1]]\n  - [-1, 3, RepC3, [384]]  # 20, fpn_blocks.0\n  - [-1, 1, Conv, [384, 1, 1]]   # 21, Y4, lateral_convs.1\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [4, 1, Conv, [384, 1, 1, None, 1, 1, False]]  # 23 input_proj.0\n  - [[-2, -1], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, RepC3, [384]]    # X3 (25), fpn_blocks.1\n\n  - [-1, 1, Conv, [384, 3, 2]]   # 26, downsample_convs.0\n  - [[-1, 21], 1, Concat, [1]]  # cat Y4\n  - [-1, 3, RepC3, [384]]    # F4 (28), pan_blocks.0\n\n  - [-1, 1, Conv, [384, 3, 2]]   # 29, downsample_convs.1\n  - [[-1, 16], 1, Concat, [1]]  # cat Y5\n  - [-1, 3, RepC3, [384]]    # F5 (31), pan_blocks.1\n\n  - [[25, 28, 31], 1, RTDETRDecoder, [nc]]  # Detect(P3, P4, P5)\n"
  },
  {
    "path": "ultralytics/models/v3/yolov3-spp.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\n\n# darknet53 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [32, 3, 1]],  # 0\n   [-1, 1, Conv, [64, 3, 2]],  # 1-P1/2\n   [-1, 1, Bottleneck, [64]],\n   [-1, 1, Conv, [128, 3, 2]],  # 3-P2/4\n   [-1, 2, Bottleneck, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 5-P3/8\n   [-1, 8, Bottleneck, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 7-P4/16\n   [-1, 8, Bottleneck, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P5/32\n   [-1, 4, Bottleneck, [1024]],  # 10\n  ]\n\n# YOLOv3-SPP head\nhead:\n  [[-1, 1, Bottleneck, [1024, False]],\n   [-1, 1, SPP, [512, [5, 9, 13]]],\n   [-1, 1, Conv, [1024, 3, 1]],\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, Conv, [1024, 3, 1]],  # 15 (P5/32-large)\n\n   [-2, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P4\n   [-1, 1, Bottleneck, [512, False]],\n   [-1, 1, Bottleneck, [512, False]],\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, Conv, [512, 3, 1]],  # 22 (P4/16-medium)\n\n   [-2, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P3\n   [-1, 1, Bottleneck, [256, False]],\n   [-1, 2, Bottleneck, [256, False]],  # 27 (P3/8-small)\n\n   [[27, 22, 15], 1, Detect, [nc]],   # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "ultralytics/models/v3/yolov3-tiny.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\n\n# YOLOv3-tiny backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [16, 3, 1]],  # 0\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 1-P1/2\n   [-1, 1, Conv, [32, 3, 1]],\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 3-P2/4\n   [-1, 1, Conv, [64, 3, 1]],\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 5-P3/8\n   [-1, 1, Conv, [128, 3, 1]],\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 7-P4/16\n   [-1, 1, Conv, [256, 3, 1]],\n   [-1, 1, nn.MaxPool2d, [2, 2, 0]],  # 9-P5/32\n   [-1, 1, Conv, [512, 3, 1]],\n   [-1, 1, nn.ZeroPad2d, [[0, 1, 0, 1]]],  # 11\n   [-1, 1, nn.MaxPool2d, [2, 1, 0]],  # 12\n  ]\n\n# YOLOv3-tiny head\nhead:\n  [[-1, 1, Conv, [1024, 3, 1]],\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, Conv, [512, 3, 1]],  # 15 (P5/32-large)\n\n   [-2, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P4\n   [-1, 1, Conv, [256, 3, 1]],  # 19 (P4/16-medium)\n\n   [[19, 15], 1, Detect, [nc]],  # Detect(P4, P5)\n  ]\n"
  },
  {
    "path": "ultralytics/models/v3/yolov3.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\ndepth_multiple: 1.0  # model depth multiple\nwidth_multiple: 1.0  # layer channel multiple\n\n# darknet53 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [32, 3, 1]],  # 0\n   [-1, 1, Conv, [64, 3, 2]],  # 1-P1/2\n   [-1, 1, Bottleneck, [64]],\n   [-1, 1, Conv, [128, 3, 2]],  # 3-P2/4\n   [-1, 2, Bottleneck, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 5-P3/8\n   [-1, 8, Bottleneck, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 7-P4/16\n   [-1, 8, Bottleneck, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P5/32\n   [-1, 4, Bottleneck, [1024]],  # 10\n  ]\n\n# YOLOv3 head\nhead:\n  [[-1, 1, Bottleneck, [1024, False]],\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, Conv, [1024, 3, 1]],\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, Conv, [1024, 3, 1]],  # 15 (P5/32-large)\n\n   [-2, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P4\n   [-1, 1, Bottleneck, [512, False]],\n   [-1, 1, Bottleneck, [512, False]],\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, Conv, [512, 3, 1]],  # 22 (P4/16-medium)\n\n   [-2, 1, Conv, [128, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P3\n   [-1, 1, Bottleneck, [256, False]],\n   [-1, 2, Bottleneck, [256, False]],  # 27 (P3/8-small)\n\n   [[27, 22, 15], 1, Detect, [nc]],   # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "ultralytics/models/v5/yolov5-p6.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov5n-p6.yaml' will call yolov5-p6.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 1024]\n  l: [1.00, 1.00, 1024]\n  x: [1.33, 1.25, 1024]\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [768, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [768]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 9-P6/64\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 11\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [768, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 8], 1, Concat, [1]],  # cat backbone P5\n   [-1, 3, C3, [768, False]],  # 15\n\n   [-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 19\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 23 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 20], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 26 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 16], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [768, False]],  # 29 (P5/32-large)\n\n   [-1, 1, Conv, [768, 3, 2]],\n   [[-1, 12], 1, Concat, [1]],  # cat head P6\n   [-1, 3, C3, [1024, False]],  # 32 (P6/64-xlarge)\n\n   [[23, 26, 29, 32], 1, Detect, [nc]],  # Detect(P3, P4, P5, P6)\n  ]\n"
  },
  {
    "path": "ultralytics/models/v5/yolov5.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov5n.yaml' will call yolov5.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 1024]\n  l: [1.00, 1.00, 1024]\n  x: [1.33, 1.25, 1024]\n\n# YOLOv5 v6.0 backbone\nbackbone:\n  # [from, number, module, args]\n  [[-1, 1, Conv, [64, 6, 2, 2]],  # 0-P1/2\n   [-1, 1, Conv, [128, 3, 2]],  # 1-P2/4\n   [-1, 3, C3, [128]],\n   [-1, 1, Conv, [256, 3, 2]],  # 3-P3/8\n   [-1, 6, C3, [256]],\n   [-1, 1, Conv, [512, 3, 2]],  # 5-P4/16\n   [-1, 9, C3, [512]],\n   [-1, 1, Conv, [1024, 3, 2]],  # 7-P5/32\n   [-1, 3, C3, [1024]],\n   [-1, 1, SPPF, [1024, 5]],  # 9\n  ]\n\n# YOLOv5 v6.0 head\nhead:\n  [[-1, 1, Conv, [512, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 6], 1, Concat, [1]],  # cat backbone P4\n   [-1, 3, C3, [512, False]],  # 13\n\n   [-1, 1, Conv, [256, 1, 1]],\n   [-1, 1, nn.Upsample, [None, 2, 'nearest']],\n   [[-1, 4], 1, Concat, [1]],  # cat backbone P3\n   [-1, 3, C3, [256, False]],  # 17 (P3/8-small)\n\n   [-1, 1, Conv, [256, 3, 2]],\n   [[-1, 14], 1, Concat, [1]],  # cat head P4\n   [-1, 3, C3, [512, False]],  # 20 (P4/16-medium)\n\n   [-1, 1, Conv, [512, 3, 2]],\n   [[-1, 10], 1, Concat, [1]],  # cat head P5\n   [-1, 3, C3, [1024, False]],  # 23 (P5/32-large)\n\n   [[17, 20, 23], 1, Detect, [nc]],  # Detect(P3, P4, P5)\n  ]\n"
  },
  {
    "path": "ultralytics/models/v8/.ipynb_checkpoints/yolov8-bdd-v4-one-dropout-individual-n-checkpoint.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect\n\n# Parameters\n######Jiayuan\ntnc: 3  # number of classes\n#######\nscales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call yolov8.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]  # YOLOv8n summary: 225 layers,  3157200 parameters,  3157184 gradients,   8.9 GFLOPs\n  s: [0.33, 0.50, 1024]  # YOLOv8s summary: 225 layers, 11166560 parameters, 11166544 gradients,  28.8 GFLOPs\n  m: [0.67, 0.75, 768]   # YOLOv8m summary: 295 layers, 25902640 parameters, 25902624 gradients,  79.3 GFLOPs\n  l: [1.00, 1.00, 512]   # YOLOv8l summary: 365 layers, 43691520 parameters, 43691504 gradients, 165.7 GFLOPs\n  x: [1.00, 1.25, 512]   # YOLOv8x summary: 365 layers, 68229648 parameters, 68229632 gradients, 258.5 GFLOPs\n\nscale: n\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 18 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 21 (P5/32-large)\n\n\n # lane\n  - [9, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat_dropout, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 24\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat_dropout, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 27 (P3/8-small)\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]  #  for lane segmentation\n  - [[-1, 2], 1, Concat_dropout, [1]]  #  cat backbone P2\n  - [-1, 3, C2f, [128]]  # 30 (P2)\n  \n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #\n  - [[-1, 0], 1, Concat_dropout, [1]]  #  cat backbone P1\n  - [-1, 3, C2f, [64]]  # 33 (P1)\n  \n#  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #28\n#  - [-1, 3, C2f, [32]]  # 29 (original)\n  \n  \n # drivable\n  - [9, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat_dropout, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 36\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat_dropout, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 39 (P3/8-small)\n \n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]  # 30 for drivable segmentation\n  - [[-1, 2], 1, Concat_dropout, [1]]\n  - [-1, 3, C2f, [128]]  # 42 (P2)\n  \n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #\n  - [[-1, 0], 1, Concat_dropout, [1]]\n  - [-1, 3, C2f, [64]]  # 45 (P1)\n  \n#  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #34\n#  - [-1, 3, C2f, [32]]  # 35 (original)\n#\n \n \n \n# tasks\n  - [[15, 18, 21], 1, Detect, [1]]  # 36 Detect(P3, P4, P5)\n\n  - [[45], 1, Segment, [1, 32, 256]]  # 37 drivable-Segment [1,32,256] was not working, you should change the head.py\n  \n  - [[33], 1, Segment, [1, 32, 256]]  # 38 lane-Segment [1,32,256] was not working, you should change the head.py\n\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-bdd-one.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect\n\n# Parameters\n######Jiayuan\ntnc: 12  # number of classes\n#######\nscales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call yolov8.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]  # YOLOv8n summary: 225 layers,  3157200 parameters,  3157184 gradients,   8.9 GFLOPs\n  s: [0.33, 0.50, 1024]  # YOLOv8s summary: 225 layers, 11166560 parameters, 11166544 gradients,  28.8 GFLOPs\n  m: [0.67, 0.75, 768]   # YOLOv8m summary: 295 layers, 25902640 parameters, 25902624 gradients,  79.3 GFLOPs\n  l: [1.00, 1.00, 512]   # YOLOv8l summary: 365 layers, 43691520 parameters, 43691504 gradients, 165.7 GFLOPs\n  x: [1.00, 1.25, 512]   # YOLOv8x summary: 365 layers, 68229648 parameters, 68229632 gradients, 258.5 GFLOPs\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 18 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 21 (P5/32-large)\n\n\n # lane\n  - [15, 1, nn.Upsample, [None, 2, 'nearest']]  # 22 for lane segmentation \n  - [[-1, 2], 1, Concat, [1]]  # 23 cat backbone P2\n  - [-1, 3, C2f, [128]]  # 24 (P2)\n  \n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #25\n  - [[-1, 0], 1, Concat, [1]]  # 26 cat backbone P1\n  - [-1, 3, C2f, [64]]  # 27 (P1)\n  \n#  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #28\n#  - [-1, 3, C2f, [32]]  # 29 (original)\n  \n  \n # drivable\n  - [15, 1, nn.Upsample, [None, 2, 'nearest']]  # 30 for drivable segmentation \n  - [-1, 3, C2f, [128]]  # 31 (P2)\n  \n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #32\n  - [-1, 3, C2f, [64]]  # 33 (P1)\n  \n#  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #34\n#  - [-1, 3, C2f, [32]]  # 35 (original)\n \n \n \n \n# tasks\n  - [[15, 18, 21], 1, Detect, [10]]  # 36 Detect(P3, P4, P5)\n\n  - [[31], 1, Segment, [1, 32, 256]]  # 37 drivable-Segment\n  \n  - [[27], 1, Segment, [1, 32, 256]]  # 38 lane-Segment\n\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-bdd-v3-one.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect\n\n# Parameters\n######Jiayuan\ntnc: 3  # number of classes\n#######\nscales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call yolov8.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]  # YOLOv8n summary: 225 layers,  3157200 parameters,  3157184 gradients,   8.9 GFLOPs\n  s: [0.33, 0.50, 1024]  # YOLOv8s summary: 225 layers, 11166560 parameters, 11166544 gradients,  28.8 GFLOPs\n  m: [0.67, 0.75, 768]   # YOLOv8m summary: 295 layers, 25902640 parameters, 25902624 gradients,  79.3 GFLOPs\n  l: [1.00, 1.00, 512]   # YOLOv8l summary: 365 layers, 43691520 parameters, 43691504 gradients, 165.7 GFLOPs\n  x: [1.00, 1.25, 512]   # YOLOv8x summary: 365 layers, 68229648 parameters, 68229632 gradients, 258.5 GFLOPs\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 18 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 21 (P5/32-large)\n\n\n # lane\n  - [15, 1, nn.Upsample, [None, 2, 'nearest']]  # 22 for lane segmentation \n  - [[-1, 2], 1, Concat, [1]]  # 23 cat backbone P2\n  - [-1, 3, C2f, [128]]  # 24 (P2)\n  \n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #25\n  - [[-1, 0], 1, Concat, [1]]  # 26 cat backbone P1\n  - [-1, 3, C2f, [64]]  # 27 (P1)\n  \n#  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #28\n#  - [-1, 3, C2f, [32]]  # 29 (original)\n  \n  \n # drivable\n  - [15, 1, nn.Upsample, [None, 2, 'nearest']]  # 30 for drivable segmentation \n  - [-1, 3, C2f, [128]]  # 31 (P2)\n  \n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #32\n  - [-1, 3, C2f, [64]]  # 33 (P1)\n  \n#  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #34\n#  - [-1, 3, C2f, [32]]  # 35 (original)\n#\n \n \n \n# tasks\n  - [[15, 18, 21], 1, Detect, [1]]  # 36 Detect(P3, P4, P5)\n\n  - [[31], 1, Segment, [1, 32, 256]]  # 37 drivable-Segment [1,32,256] was not working, you should change the head.py\n  \n  - [[27], 1, Segment, [1, 32, 256]]  # 38 lane-Segment [1,32,256] was not working, you should change the head.py\n\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-bdd-v4-one-dropout-individual-n.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect\n\n# Parameters\n######Jiayuan\ntnc: 3  # number of classes\n#######\nscales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call yolov8.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]  # YOLOv8n summary: 225 layers,  3157200 parameters,  3157184 gradients,   8.9 GFLOPs\n  s: [0.33, 0.50, 1024]  # YOLOv8s summary: 225 layers, 11166560 parameters, 11166544 gradients,  28.8 GFLOPs\n  m: [0.67, 0.75, 768]   # YOLOv8m summary: 295 layers, 25902640 parameters, 25902624 gradients,  79.3 GFLOPs\n  l: [1.00, 1.00, 512]   # YOLOv8l summary: 365 layers, 43691520 parameters, 43691504 gradients, 165.7 GFLOPs\n  x: [1.00, 1.25, 512]   # YOLOv8x summary: 365 layers, 68229648 parameters, 68229632 gradients, 258.5 GFLOPs\n\nscale: n\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 18 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 21 (P5/32-large)\n\n\n # lane\n  - [9, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat_dropout, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 24\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat_dropout, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 27 (P3/8-small)\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]  #  for lane segmentation\n  - [[-1, 2], 1, Concat_dropout, [1]]  #  cat backbone P2\n  - [-1, 3, C2f, [128]]  # 30 (P2)\n  \n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #\n  - [[-1, 0], 1, Concat_dropout, [1]]  #  cat backbone P1\n  - [-1, 3, C2f, [64]]  # 33 (P1)\n  \n#  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #28\n#  - [-1, 3, C2f, [32]]  # 29 (original)\n  \n  \n # drivable\n  - [9, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat_dropout, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 36\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat_dropout, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 39 (P3/8-small)\n \n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]  # 30 for drivable segmentation\n  - [[-1, 2], 1, Concat_dropout, [1]]\n  - [-1, 3, C2f, [128]]  # 42 (P2)\n  \n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #\n  - [[-1, 0], 1, Concat_dropout, [1]]\n  - [-1, 3, C2f, [64]]  # 45 (P1)\n  \n#  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #34\n#  - [-1, 3, C2f, [32]]  # 35 (original)\n#\n \n \n \n# tasks\n  - [[15, 18, 21], 1, Detect, [1]]  # 36 Detect(P3, P4, P5)\n\n  - [[45], 1, Segment, [1, 32, 256]]  # 37 drivable-Segment [1,32,256] was not working, you should change the head.py\n  \n  - [[33], 1, Segment, [1, 32, 256]]  # 38 lane-Segment [1,32,256] was not working, you should change the head.py\n\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-bdd-v4-one-dropout-individual-s.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect\n\n# Parameters\n######Jiayuan\ntnc: 3  # number of classes\n#######\nscales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call yolov8.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]  # YOLOv8n summary: 225 layers,  3157200 parameters,  3157184 gradients,   8.9 GFLOPs\n  s: [0.33, 0.50, 1024]  # YOLOv8s summary: 225 layers, 11166560 parameters, 11166544 gradients,  28.8 GFLOPs\n  m: [0.67, 0.75, 768]   # YOLOv8m summary: 295 layers, 25902640 parameters, 25902624 gradients,  79.3 GFLOPs\n  l: [1.00, 1.00, 512]   # YOLOv8l summary: 365 layers, 43691520 parameters, 43691504 gradients, 165.7 GFLOPs\n  x: [1.00, 1.25, 512]   # YOLOv8x summary: 365 layers, 68229648 parameters, 68229632 gradients, 258.5 GFLOPs\n\nscale: s\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 18 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 21 (P5/32-large)\n\n\n # lane\n  - [9, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat_dropout, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 24\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat_dropout, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 27 (P3/8-small)\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]  #  for lane segmentation\n  - [[-1, 2], 1, Concat_dropout, [1]]  #  cat backbone P2\n  - [-1, 3, C2f, [128]]  # 30 (P2)\n  \n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #\n  - [[-1, 0], 1, Concat_dropout, [1]]  #  cat backbone P1\n  - [-1, 3, C2f, [64]]  # 33 (P1)\n  \n#  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #28\n#  - [-1, 3, C2f, [32]]  # 29 (original)\n  \n  \n # drivable\n  - [9, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat_dropout, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 36\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat_dropout, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 39 (P3/8-small)\n \n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]  # 30 for drivable segmentation\n  - [[-1, 2], 1, Concat_dropout, [1]]\n  - [-1, 3, C2f, [128]]  # 42 (P2)\n  \n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #\n  - [[-1, 0], 1, Concat_dropout, [1]]\n  - [-1, 3, C2f, [64]]  # 45 (P1)\n  \n#  - [-1, 1, nn.Upsample, [None, 2, 'nearest']] #34\n#  - [-1, 3, C2f, [32]]  # 35 (original)\n#\n \n \n \n# tasks\n  - [[15, 18, 21], 1, Detect, [1]]  # 36 Detect(P3, P4, P5)\n\n  - [[45], 1, Segment, [1, 32, 256]]  # 37 drivable-Segment [1,32,256] was not working, you should change the head.py\n  \n  - [[33], 1, Segment, [1, 32, 256]]  # 38 lane-Segment [1,32,256] was not working, you should change the head.py\n\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-bdd.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect\n\n# Parameters\n######Jiayuan\ntnc: 12  # number of classes\n#######\nscales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call yolov8.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]  # YOLOv8n summary: 225 layers,  3157200 parameters,  3157184 gradients,   8.9 GFLOPs\n  s: [0.33, 0.50, 1024]  # YOLOv8s summary: 225 layers, 11166560 parameters, 11166544 gradients,  28.8 GFLOPs\n  m: [0.67, 0.75, 768]   # YOLOv8m summary: 295 layers, 25902640 parameters, 25902624 gradients,  79.3 GFLOPs\n  l: [1.00, 1.00, 512]   # YOLOv8l summary: 365 layers, 43691520 parameters, 43691504 gradients, 165.7 GFLOPs\n  x: [1.00, 1.25, 512]   # YOLOv8x summary: 365 layers, 68229648 parameters, 68229632 gradients, 258.5 GFLOPs\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 18 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 21 (P5/32-large)\n\n  - [[15, 18, 21], 1, Detect, [10]]  # 22 Detect(P3, P4, P5)\n\n  - [[15, 18, 21], 1, Segment, [1, 32, 256]]  # 23 drivable-Segment(P3, P4, P5)\n  \n  - [[15, 18, 21], 1, Segment, [1, 32, 256]]  # 24 lane-Segment(P3, P4, P5)\n\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-cls.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8-cls image classification model. For Usage examples see https://docs.ultralytics.com/tasks/classify\n\n# Parameters\nnc: 1000  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n-cls.yaml' will call yolov8-cls.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 1024]\n  l: [1.00, 1.00, 1024]\n  x: [1.00, 1.25, 1024]\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, Classify, [nc]]  # Classify\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-p2.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8 object detection model with P2-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call yolov8.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 768]\n  l: [1.00, 1.00, 512]\n  x: [1.00, 1.25, 512]\n\n# YOLOv8.0 backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0-p2 head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 2], 1, Concat, [1]]  # cat backbone P2\n  - [-1, 3, C2f, [128]]  # 18 (P2/4-xsmall)\n\n  - [-1, 1, Conv, [128, 3, 2]]\n  - [[-1, 15], 1, Concat, [1]]  # cat head P3\n  - [-1, 3, C2f, [256]]  # 21 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 24 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 27 (P5/32-large)\n\n  - [[18, 21, 24, 27], 1, Detect, [nc]]  # Detect(P2, P3, P4, P5)\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-p6.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8 object detection model with P3-P6 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n-p6.yaml' will call yolov8-p6.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 768]\n  l: [1.00, 1.00, 512]\n  x: [1.00, 1.25, 512]\n\n# YOLOv8.0x6 backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [768, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [768, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 9-P6/64\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 11\n\n# YOLOv8.0x6 head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 8], 1, Concat, [1]]  # cat backbone P5\n  - [-1, 3, C2, [768, False]]  # 14\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2, [512, False]]  # 17\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2, [256, False]]  # 20 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 17], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2, [512, False]]  # 23 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 14], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2, [768, False]]  # 26 (P5/32-large)\n\n  - [-1, 1, Conv, [768, 3, 2]]\n  - [[-1, 11], 1, Concat, [1]]  # cat head P6\n  - [-1, 3, C2, [1024, False]]  # 29 (P6/64-xlarge)\n\n  - [[20, 23, 26, 29], 1, Detect, [nc]]  # Detect(P3, P4, P5, P6)\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-pose.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8-pose keypoints/pose estimation model. For Usage examples see https://docs.ultralytics.com/tasks/pose\n\n# Parameters\nnc: 1  # number of classes\nkpt_shape: [17, 3]  # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)\nscales: # model compound scaling constants, i.e. 'model=yolov8n-pose.yaml' will call yolov8-pose.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 768]\n  l: [1.00, 1.00, 512]\n  x: [1.00, 1.25, 512]\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 18 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 21 (P5/32-large)\n\n  - [[15, 18, 21], 1, Pose, [nc, kpt_shape]]  # Pose(P3, P4, P5)\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8-seg.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8-seg instance segmentation model. For Usage examples see https://docs.ultralytics.com/tasks/segment\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n-seg.yaml' will call yolov8-seg.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]\n  s: [0.33, 0.50, 1024]\n  m: [0.67, 0.75, 768]\n  l: [1.00, 1.00, 512]\n  x: [1.00, 1.25, 512]\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 18 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 21 (P5/32-large)\n\n  - [[15, 18, 21], 1, Segment, [nc, 32, 256]]  # Segment(P3, P4, P5)\n"
  },
  {
    "path": "ultralytics/models/v8/yolov8.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# YOLOv8 object detection model with P3-P5 outputs. For Usage examples see https://docs.ultralytics.com/tasks/detect\n\n# Parameters\nnc: 80  # number of classes\nscales: # model compound scaling constants, i.e. 'model=yolov8n.yaml' will call yolov8.yaml with scale 'n'\n  # [depth, width, max_channels]\n  n: [0.33, 0.25, 1024]  # YOLOv8n summary: 225 layers,  3157200 parameters,  3157184 gradients,   8.9 GFLOPs\n  s: [0.33, 0.50, 1024]  # YOLOv8s summary: 225 layers, 11166560 parameters, 11166544 gradients,  28.8 GFLOPs\n  m: [0.67, 0.75, 768]   # YOLOv8m summary: 295 layers, 25902640 parameters, 25902624 gradients,  79.3 GFLOPs\n  l: [1.00, 1.00, 512]   # YOLOv8l summary: 365 layers, 43691520 parameters, 43691504 gradients, 165.7 GFLOPs\n  x: [1.00, 1.25, 512]   # YOLOv8x summary: 365 layers, 68229648 parameters, 68229632 gradients, 258.5 GFLOPs\n\n# YOLOv8.0n backbone\nbackbone:\n  # [from, repeats, module, args]\n  - [-1, 1, Conv, [64, 3, 2]]  # 0-P1/2\n  - [-1, 1, Conv, [128, 3, 2]]  # 1-P2/4\n  - [-1, 3, C2f, [128, True]]\n  - [-1, 1, Conv, [256, 3, 2]]  # 3-P3/8\n  - [-1, 6, C2f, [256, True]]\n  - [-1, 1, Conv, [512, 3, 2]]  # 5-P4/16\n  - [-1, 6, C2f, [512, True]]\n  - [-1, 1, Conv, [1024, 3, 2]]  # 7-P5/32\n  - [-1, 3, C2f, [1024, True]]\n  - [-1, 1, SPPF, [1024, 5]]  # 9\n\n# YOLOv8.0n head\nhead:\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 6], 1, Concat, [1]]  # cat backbone P4\n  - [-1, 3, C2f, [512]]  # 12\n\n  - [-1, 1, nn.Upsample, [None, 2, 'nearest']]\n  - [[-1, 4], 1, Concat, [1]]  # cat backbone P3\n  - [-1, 3, C2f, [256]]  # 15 (P3/8-small)\n\n  - [-1, 1, Conv, [256, 3, 2]]\n  - [[-1, 12], 1, Concat, [1]]  # cat head P4\n  - [-1, 3, C2f, [512]]  # 18 (P4/16-medium)\n\n  - [-1, 1, Conv, [512, 3, 2]]\n  - [[-1, 9], 1, Concat, [1]]  # cat head P5\n  - [-1, 3, C2f, [1024]]  # 21 (P5/32-large)\n\n  - [[15, 18, 21], 1, Detect, [nc]]  # Detect(P3, P4, P5)\n"
  },
  {
    "path": "ultralytics/nn/.ipynb_checkpoints/tasks-checkpoint.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nfrom copy import deepcopy\nfrom pathlib import Path\n\nimport torch\nimport torch.nn as nn\n\nfrom ultralytics.nn.modules import (AIFI, C1, C2, C3, C3TR, SPP, SPPF, Bottleneck, BottleneckCSP, C2f, C3Ghost, C3x,\n                                    Classify, Concat, Conv, ConvTranspose, Detect, DWConv, DWConvTranspose2d, Focus,\n                                    GhostBottleneck, GhostConv, HGBlock, HGStem, Pose, RepC3, RepConv, RTDETRDecoder,\n                                    Segment, Concat_dropout)\nfrom ultralytics.yolo.utils import DEFAULT_CFG_DICT, DEFAULT_CFG_KEYS, LOGGER, colorstr, emojis, yaml_load\nfrom ultralytics.yolo.utils.checks import check_requirements, check_suffix, check_yaml\nfrom ultralytics.yolo.utils.plotting import feature_visualization\nfrom ultralytics.yolo.utils.torch_utils import (fuse_conv_and_bn, fuse_deconv_and_bn, initialize_weights,\n                                                intersect_dicts, make_divisible, model_info, scale_img, time_sync)\n\ntry:\n    import thop\nexcept ImportError:\n    thop = None\n\n\nclass BaseModel(nn.Module):\n    \"\"\"\n    The BaseModel class serves as a base class for all the models in the Ultralytics YOLO family.\n    \"\"\"\n\n    def forward(self, x, profile=False, visualize=False):\n        \"\"\"\n        Forward pass of the model on a single scale.\n        Wrapper for `_forward_once` method.\n\n        Args:\n            x (torch.Tensor): The input image tensor\n            profile (bool): Whether to profile the model, defaults to False\n            visualize (bool): Whether to return the intermediate feature maps, defaults to False\n\n        Returns:\n            (torch.Tensor): The output of the network.\n        \"\"\"\n        return self._forward_once(x, profile, visualize)\n\n    def _forward_once(self, x, profile=False, visualize=False):\n        \"\"\"\n        Perform a forward pass through the network.\n\n        Args:\n            x (torch.Tensor): The input tensor to the model\n            profile (bool):  Print the computation time of each layer if True, defaults to False.\n            visualize (bool): Save the feature maps of the model if True, defaults to False\n\n        Returns:\n            (torch.Tensor): The last output of the model.\n        \"\"\"\n        y, dt = [], []  # outputs\n        for m in self.model:\n            if m.f != -1:  # if not from previous layer\n                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers\n            if profile:\n                self._profile_one_layer(m, x, dt)\n            x = m(x)  # run\n            y.append(x if m.i in self.save else None)  # save output\n            if visualize:\n                feature_visualization(x, m.type, m.i, save_dir=visualize)\n        return x\n\n    def _profile_one_layer(self, m, x, dt):\n        \"\"\"\n        Profile the computation time and FLOPs of a single layer of the model on a given input.\n        Appends the results to the provided list.\n\n        Args:\n            m (nn.Module): The layer to be profiled.\n            x (torch.Tensor): The input data to the layer.\n            dt (list): A list to store the computation time of the layer.\n\n        Returns:\n            None\n        \"\"\"\n        c = m == self.model[-1]  # is final layer, copy input as inplace fix\n        o = thop.profile(m, inputs=[x.clone() if c else x], verbose=False)[0] / 1E9 * 2 if thop else 0  # FLOPs\n        t = time_sync()\n        for _ in range(10):\n            m(x.clone() if c else x)\n        dt.append((time_sync() - t) * 100)\n        if m == self.model[0]:\n            LOGGER.info(f\"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s}  module\")\n        LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f}  {m.type}')\n        if c:\n            LOGGER.info(f\"{sum(dt):10.2f} {'-':>10s} {'-':>10s}  Total\")\n\n    def fuse(self, verbose=True):\n        \"\"\"\n        Fuse the `Conv2d()` and `BatchNorm2d()` layers of the model into a single layer, in order to improve the\n        computation efficiency.\n\n        Returns:\n            (nn.Module): The fused model is returned.\n        \"\"\"\n        if not self.is_fused():\n            for m in self.model.modules():\n                if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):\n                    m.conv = fuse_conv_and_bn(m.conv, m.bn)  # update conv\n                    delattr(m, 'bn')  # remove batchnorm\n                    m.forward = m.forward_fuse  # update forward\n                if isinstance(m, ConvTranspose) and hasattr(m, 'bn'):\n                    m.conv_transpose = fuse_deconv_and_bn(m.conv_transpose, m.bn)\n                    delattr(m, 'bn')  # remove batchnorm\n                    m.forward = m.forward_fuse  # update forward\n                if isinstance(m, RepConv):\n                    m.fuse_convs()\n                    m.forward = m.forward_fuse  # update forward\n            self.info(verbose=verbose)\n\n        return self\n\n    def is_fused(self, thresh=10):\n        \"\"\"\n        Check if the model has less than a certain threshold of BatchNorm layers.\n\n        Args:\n            thresh (int, optional): The threshold number of BatchNorm layers. Default is 10.\n\n        Returns:\n            (bool): True if the number of BatchNorm layers in the model is less than the threshold, False otherwise.\n        \"\"\"\n        bn = tuple(v for k, v in nn.__dict__.items() if 'Norm' in k)  # normalization layers, i.e. BatchNorm2d()\n        return sum(isinstance(v, bn) for v in self.modules()) < thresh  # True if < 'thresh' BatchNorm layers in model\n\n    def info(self, detailed=False, verbose=True, imgsz=640):\n        \"\"\"\n        Prints model information\n\n        Args:\n            verbose (bool): if True, prints out the model information. Defaults to False\n            imgsz (int): the size of the image that the model will be trained on. Defaults to 640\n        \"\"\"\n        return model_info(self, detailed=detailed, verbose=verbose, imgsz=imgsz)\n\n    def _apply(self, fn):\n        \"\"\"\n        `_apply()` is a function that applies a function to all the tensors in the model that are not\n        parameters or registered buffers\n\n        Args:\n            fn: the function to apply to the model\n\n        Returns:\n            A model that is a Detect() object.\n        \"\"\"\n        self = super()._apply(fn)\n        m = self.model[-1]  # Detect()\n        if isinstance(m, (Detect, Segment)):\n            m.stride = fn(m.stride)\n            m.anchors = fn(m.anchors)\n            m.strides = fn(m.strides)\n        return self\n\n    def load(self, weights, verbose=True):\n        \"\"\"Load the weights into the model.\n\n        Args:\n            weights (dict) or (torch.nn.Module): The pre-trained weights to be loaded.\n            verbose (bool, optional): Whether to log the transfer progress. Defaults to True.\n        \"\"\"\n        model = weights['model'] if isinstance(weights, dict) else weights  # torchvision models are not dicts\n        csd = model.float().state_dict()  # checkpoint state_dict as FP32\n        csd = intersect_dicts(csd, self.state_dict())  # intersect\n        self.load_state_dict(csd, strict=False)  # load\n        if verbose:\n            LOGGER.info(f'Transferred {len(csd)}/{len(self.model.state_dict())} items from pretrained weights')\n            \n\nclass MultiBaseModel(nn.Module):\n    \"\"\"\n    The BaseModel class serves as a base class for all the models in the Ultralytics YOLO family.\n    \"\"\"\n\n    def forward(self, x, profile=False, visualize=False):\n        \"\"\"\n        Forward pass of the model on a single scale.\n        Wrapper for `_forward_once` method.\n\n        Args:\n            x (torch.Tensor): The input image tensor\n            profile (bool): Whether to profile the model, defaults to False\n            visualize (bool): Whether to return the intermediate feature maps, defaults to False\n\n        Returns:\n            (torch.Tensor): The output of the network.\n        \"\"\"\n        return self._forward_once(x, profile, visualize)\n\n#     def _forward_once(self, x, profile=False, visualize=False):\n#         \"\"\"\n#         Perform a forward pass through the network.\n\n#         Args:\n#             x (torch.Tensor): The input tensor to the model\n#             profile (bool):  Print the computation time of each layer if True, defaults to False.\n#             visualize (bool): Save the feature maps of the model if True, defaults to False\n\n#         Returns:\n#             (torch.Tensor): The last output of the model.\n#         \"\"\"\n#         y, dt = [], []  # outputs\n#         for m in self.model:\n#             if m.f != -1:  # if not from previous layer\n#                 x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers\n#             if profile:\n#                 self._profile_one_layer(m, x, dt)\n#             x = m(x)  # run\n#             y.append(x if m.i in self.save else None)  # save output\n#             if visualize:\n#                 feature_visualization(x, m.type, m.i, save_dir=visualize)\n#         return x\n    \n    \n    def _forward_once(self, x, profile=False, visualize=False):\n        \"\"\"\n        This output will return whole head result. the sequence is object detection, drivable area seg and lane seg. \n        \"\"\"\n        outputs, y = [], []\n        for m in self.model:\n            if m.f != -1:  # if not from previous layer\n                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers\n            x = m(x)  # run\n\n            if isinstance(m, (Detect, Segment)):  # if it's a task head\n                outputs.append(x)\n            # y.append(x)\n            y.append(x if m.i in self.save else None)  # save output\n            if visualize:\n                feature_visualization(x, m.type, m.i, save_dir=visualize)\n        return outputs\n\n\n    def _profile_one_layer(self, m, x, dt):\n        \"\"\"\n        Profile the computation time and FLOPs of a single layer of the model on a given input.\n        Appends the results to the provided list.\n\n        Args:\n            m (nn.Module): The layer to be profiled.\n            x (torch.Tensor): The input data to the layer.\n            dt (list): A list to store the computation time of the layer.\n\n        Returns:\n            None\n        \"\"\"\n        c = m in self.model[-3:]  # is final layer, copy input as inplace fix\n        o = thop.profile(m, inputs=[x.clone() if c else x], verbose=False)[0] / 1E9 * 2 if thop else 0  # FLOPs\n        t = time_sync()\n        for _ in range(10):\n            m(x.clone() if c else x)\n        dt.append((time_sync() - t) * 100)\n        if m == self.model[0]:\n            LOGGER.info(f\"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s}  module\")\n        LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f}  {m.type}')\n        if c:\n            LOGGER.info(f\"{sum(dt):10.2f} {'-':>10s} {'-':>10s}  Total\")\n\n    def fuse(self, verbose=True):\n        \"\"\"\n        Fuse the `Conv2d()` and `BatchNorm2d()` layers of the model into a single layer, in order to improve the\n        computation efficiency.\n\n        Returns:\n            (nn.Module): The fused model is returned.\n        \"\"\"\n        if not self.is_fused():\n            for m in self.model.modules():\n                if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):\n                    m.conv = fuse_conv_and_bn(m.conv, m.bn)  # update conv\n                    delattr(m, 'bn')  # remove batchnorm\n                    m.forward = m.forward_fuse  # update forward\n                if isinstance(m, ConvTranspose) and hasattr(m, 'bn'):\n                    m.conv_transpose = fuse_deconv_and_bn(m.conv_transpose, m.bn)\n                    delattr(m, 'bn')  # remove batchnorm\n                    m.forward = m.forward_fuse  # update forward\n                if isinstance(m, RepConv):\n                    m.fuse_convs()\n                    m.forward = m.forward_fuse  # update forward\n            self.info(verbose=verbose)\n\n        return self\n\n    def is_fused(self, thresh=10):\n        \"\"\"\n        Check if the model has less than a certain threshold of BatchNorm layers.\n\n        Args:\n            thresh (int, optional): The threshold number of BatchNorm layers. Default is 10.\n\n        Returns:\n            (bool): True if the number of BatchNorm layers in the model is less than the threshold, False otherwise.\n        \"\"\"\n        bn = tuple(v for k, v in nn.__dict__.items() if 'Norm' in k)  # normalization layers, i.e. BatchNorm2d()\n        return sum(isinstance(v, bn) for v in self.modules()) < thresh  # True if < 'thresh' BatchNorm layers in model\n\n    def info(self, detailed=False, verbose=True, imgsz=640):\n        \"\"\"\n        Prints model information\n\n        Args:\n            verbose (bool): if True, prints out the model information. Defaults to False\n            imgsz (int): the size of the image that the model will be trained on. Defaults to 640\n        \"\"\"\n        return model_info(self, detailed=detailed, verbose=verbose, imgsz=imgsz)\n\n#     def _apply(self, fn):\n#         \"\"\"\n#         `_apply()` is a function that applies a function to all the tensors in the model that are not\n#         parameters or registered buffers\n\n#         Args:\n#             fn: the function to apply to the model\n\n#         Returns:\n#             A model that is a Detect() object.\n#         \"\"\"\n#         self = super()._apply(fn)\n#         m = self.model[-1]  # Detect()\n#         if isinstance(m, (Detect, Segment)):\n#             m.stride = fn(m.stride)\n#             m.anchors = fn(m.anchors)\n#             m.strides = fn(m.strides)\n#         return self\n    \n    def _apply(self, fn):\n        \"\"\"\n        `_apply()` is a function that applies a function to all the tensors in the model that are not\n        parameters or registered buffers\n\n        Args:\n            fn: the function to apply to the model\n\n        Returns:\n            A model that is a Detect() object.\n        \"\"\"\n        self = super()._apply(fn)\n        for m in self.model[-3:]:  # Iterate over the last three layers\n            if isinstance(m, (Detect, Segment)):\n                m.stride = fn(m.stride)\n                m.anchors = fn(m.anchors)\n                m.strides = fn(m.strides)\n        return self\n\n\n    def load(self, weights, verbose=True):\n        \"\"\"Load the weights into the model.\n\n        Args:\n            weights (dict) or (torch.nn.Module): The pre-trained weights to be loaded.\n            verbose (bool, optional): Whether to log the transfer progress. Defaults to True.\n        \"\"\"\n        model = weights['model'] if isinstance(weights, dict) else weights  # torchvision models are not dicts\n        csd = model.float().state_dict()  # checkpoint state_dict as FP32\n        csd = intersect_dicts(csd, self.state_dict())  # intersect\n        self.load_state_dict(csd, strict=False)  # load\n        if verbose:\n            LOGGER.info(f'Transferred {len(csd)}/{len(self.model.state_dict())} items from pretrained weights')\n\n\nclass DetectionModel(BaseModel):\n    \"\"\"YOLOv8 detection model.\"\"\"\n\n    def __init__(self, cfg='yolov8n.yaml', ch=3, nc=None, verbose=True):  # model, input channels, number of classes\n        super().__init__()\n        self.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg)  # cfg dict\n\n        # Define model\n        ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels\n        if nc and nc != self.yaml['nc']:\n            LOGGER.info(f\"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}\")\n            self.yaml['nc'] = nc  # override yaml value\n        self.model, self.save = parse_model(deepcopy(self.yaml), ch=ch, verbose=verbose)  # model, savelist\n        self.names = {i: f'{i}' for i in range(self.yaml['tnc'])}  # default names dict\n        self.inplace = self.yaml.get('inplace', True)\n\n        # Build strides\n        for m in self.model:\n            if isinstance(m, (Detect, Segment, Pose)):\n                s = 256  # 2x min stride\n                m.inplace = self.inplace\n                forward = lambda x: self.forward(x)[0] if isinstance(m, (Segment, Pose)) else self.forward(x)\n                m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))])  # forward\n                self.stride = m.stride\n                m.bias_init()  # only run once\n\n        # Init weights, biases\n        initialize_weights(self)\n        if verbose:\n            self.info()\n            LOGGER.info('')\n\n    def forward(self, x, augment=False, profile=False, visualize=False):\n        \"\"\"Run forward pass on input image(s) with optional augmentation and profiling.\"\"\"\n        if augment:\n            return self._forward_augment(x)  # augmented inference, None\n        return self._forward_once(x, profile, visualize)  # single-scale inference, train\n\n    def _forward_augment(self, x):\n        \"\"\"Perform augmentations on input image x and return augmented inference and train outputs.\"\"\"\n        img_size = x.shape[-2:]  # height, width\n        s = [1, 0.83, 0.67]  # scales\n        f = [None, 3, None]  # flips (2-ud, 3-lr)\n        y = []  # outputs\n        for si, fi in zip(s, f):\n            xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))\n            yi = self._forward_once(xi)[0]  # forward\n            # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1])  # save\n            yi = self._descale_pred(yi, fi, si, img_size)\n            y.append(yi)\n        y = self._clip_augmented(y)  # clip augmented tails\n        return torch.cat(y, -1), None  # augmented inference, train\n\n    @staticmethod\n    def _descale_pred(p, flips, scale, img_size, dim=1):\n        \"\"\"De-scale predictions following augmented inference (inverse operation).\"\"\"\n        p[:, :4] /= scale  # de-scale\n        x, y, wh, cls = p.split((1, 1, 2, p.shape[dim] - 4), dim)\n        if flips == 2:\n            y = img_size[0] - y  # de-flip ud\n        elif flips == 3:\n            x = img_size[1] - x  # de-flip lr\n        return torch.cat((x, y, wh, cls), dim)\n\n    def _clip_augmented(self, y):\n        \"\"\"Clip YOLOv5 augmented inference tails.\"\"\"\n        nl = self.model[-1].nl  # number of detection layers (P3-P5)\n        g = sum(4 ** x for x in range(nl))  # grid points\n        e = 1  # exclude layer count\n        i = (y[0].shape[-1] // g) * sum(4 ** x for x in range(e))  # indices\n        y[0] = y[0][..., :-i]  # large\n        i = (y[-1].shape[-1] // g) * sum(4 ** (nl - 1 - x) for x in range(e))  # indices\n        y[-1] = y[-1][..., i:]  # small\n        return y\n\n    \nclass MultiModel(MultiBaseModel):\n    \"\"\"YOLOv8 detection and segmentation model.\"\"\"\n\n    def __init__(self, cfg='yolov8-bdd.yaml', ch=3, nc=None, verbose=True):  # model, input channels, number of classes\n        super().__init__()\n        self.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg)  # cfg dict\n\n        # Define model\n        ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels\n        if nc and nc != self.yaml['tnc']:\n            LOGGER.info(f\"Overriding model.yaml nc={self.yaml['tnc']} with nc={tnc}\")\n            self.yaml['tnc'] = nc  # override yaml value\n        self.model, self.save = parse_model(deepcopy(self.yaml), ch=ch, verbose=verbose)  # model, savelist\n        self.names = {i: f'{i}' for i in range(self.yaml['tnc'])}  # default names dict\n        self.inplace = self.yaml.get('inplace', True)\n        self.stride = []\n\n        # Build strides\n        count = 0\n        for m in self.model:\n        # m = self.model[-1]  # Detect()\n            if isinstance(m, (Detect, Segment, Pose)):\n                s = 256  # 2x min stride\n                m.inplace = self.inplace\n\n                forward = lambda x: self.forward(x)[count][0] if isinstance(m, (Segment, Pose)) else self.forward(x)[count]\n                m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))])  # forward\n\n                # outputs = forward(torch.zeros(1, ch, s, s))\n                # # if isinstance(m, (Detect)):\n                # #     outputs = outputs[count]\n                # strides = []\n                #\n                # for x in outputs:\n                #     stride = s / x.shape[-2]\n                #\n                #     strides.append(stride)\n                #\n                # m.stride = torch.tensor(strides)\n\n                # self.stride = m.stride\n                self.stride.append(m.stride)\n                ###### Jiayuan: do not move, otherwise the gradient will not backward to segmentation head. Only detection head will implement\n                try:\n                    m.bias_init()  # only run once for detection\n                except:\n                    pass\n                count = count+1\n\n        # Init weights, biases\n        initialize_weights(self)\n        if verbose:\n            self.info()\n            LOGGER.info('')\n\n    def forward(self, x, augment=False, profile=False, visualize=False):\n        \"\"\"Run forward pass on input image(s) with optional augmentation and profiling.\"\"\"\n        if augment:\n            return self._forward_augment(x)  # augmented inference, None\n        return self._forward_once(x, profile, visualize)  # single-scale inference, train\n\n\n    def _forward_augment(self, x):\n        \"\"\"Perform augmentations on input image x and return augmented inference and train outputs.\"\"\"\n        img_size = x.shape[-2:]  # height, width\n        s = [1, 0.83, 0.67]  # scales\n        f = [None, 3, None]  # flips (2-ud, 3-lr)\n        f = [None, 3, None]  # flips (2-ud, 3-lr)\n        y = []  # outputs\n        for si, fi in zip(s, f):\n            xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))\n            yi = self._forward_once(xi)  # forward\n            # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1])  # save\n            yi = [self._descale_pred(yij, fi, si, img_size) for yij in yi]\n            y.append(yi)\n        y = [self._clip_augmented(yij) for yij in zip(*y)]  # clip augmented tails\n        return [torch.cat(yij, -1) for yij in y], None  # augmented inference, train\n\n    @staticmethod\n    def _descale_pred(p, flips, scale, img_size, dim=1):\n        \"\"\"De-scale predictions following augmented inference (inverse operation).\"\"\"\n        p[:, :4] /= scale  # de-scale\n        x, y, wh, cls = p.split((1, 1, 2, p.shape[dim] - 4), dim)\n        if flips == 2:\n            y = img_size[0] - y  # de-flip ud\n        elif flips == 3:\n            x = img_size[1] - x  # de-flip lr\n        return torch.cat((x, y, wh, cls), dim)\n\n    def _clip_augmented(self, y):\n        \"\"\"Clip YOLOv8 augmented inference tails.\"\"\"\n        nl = self.model[-1].nl  # number of detection layers (P3-P5)\n        g = [sum(4 ** x for x in range(nl)) for _ in range(nl)]  # grid points for each head\n        e = 1  # exclude layer count\n        for i in range(len(y)):  # for each head\n            indices = (y[i].shape[-1] // g[i]) * sum(4 ** x for x in range(e))  # indices\n            y[i] = y[i][..., :-indices] if i == 0 else y[i][..., indices:]  # clip tails\n        return y\n\n\n\n#     def _forward_augment(self, x):\n#         \"\"\"Perform augmentations on input image x and return augmented inference and train outputs.\"\"\"\n#         img_size = x.shape[-2:]  # height, width\n#         s = [1, 0.83, 0.67]  # scales\n#         f = [None, 3, None]  # flips (2-ud, 3-lr)\n#         y = []  # outputs\n#         for si, fi in zip(s, f):\n#             xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))\n#             yi = self._forward_once(xi)[0]  # forward\n#             # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1])  # save\n#             yi = self._descale_pred(yi, fi, si, img_size)\n#             y.append(yi)\n#         y = self._clip_augmented(y)  # clip augmented tails\n#         return torch.cat(y, -1), None  # augmented inference, train\n\n#     @staticmethod\n#     def _descale_pred(p, flips, scale, img_size, dim=1):\n#         \"\"\"De-scale predictions following augmented inference (inverse operation).\"\"\"\n#         p[:, :4] /= scale  # de-scale\n#         x, y, wh, cls = p.split((1, 1, 2, p.shape[dim] - 4), dim)\n#         if flips == 2:\n#             y = img_size[0] - y  # de-flip ud\n#         elif flips == 3:\n#             x = img_size[1] - x  # de-flip lr\n#         return torch.cat((x, y, wh, cls), dim)\n\n#     def _clip_augmented(self, y):\n#         \"\"\"Clip YOLOv5 augmented inference tails.\"\"\"\n#         nl = self.model[-1].nl  # number of detection layers (P3-P5)\n#         g = sum(4 ** x for x in range(nl))  # grid points\n#         e = 1  # exclude layer count\n#         i = (y[0].shape[-1] // g) * sum(4 ** x for x in range(e))  # indices\n#         y[0] = y[0][..., :-i]  # large\n#         i = (y[-1].shape[-1] // g) * sum(4 ** (nl - 1 - x) for x in range(e))  # indices\n#         y[-1] = y[-1][..., i:]  # small\n#         return y\n\n\nclass SegmentationModel(DetectionModel):\n    \"\"\"YOLOv8 segmentation model.\"\"\"\n\n    def __init__(self, cfg='yolov8n-seg.yaml', ch=3, nc=None, verbose=True):\n        \"\"\"Initialize YOLOv8 segmentation model with given config and parameters.\"\"\"\n        super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)\n\n    def _forward_augment(self, x):\n        \"\"\"Undocumented function.\"\"\"\n        raise NotImplementedError(emojis('WARNING ⚠️ SegmentationModel has not supported augment inference yet!'))\n\n\nclass PoseModel(DetectionModel):\n    \"\"\"YOLOv8 pose model.\"\"\"\n\n    def __init__(self, cfg='yolov8n-pose.yaml', ch=3, nc=None, data_kpt_shape=(None, None), verbose=True):\n        \"\"\"Initialize YOLOv8 Pose model.\"\"\"\n        if not isinstance(cfg, dict):\n            cfg = yaml_model_load(cfg)  # load model YAML\n        if any(data_kpt_shape) and list(data_kpt_shape) != list(cfg['kpt_shape']):\n            LOGGER.info(f\"Overriding model.yaml kpt_shape={cfg['kpt_shape']} with kpt_shape={data_kpt_shape}\")\n            cfg['kpt_shape'] = data_kpt_shape\n        super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)\n\n\nclass ClassificationModel(BaseModel):\n    \"\"\"YOLOv8 classification model.\"\"\"\n\n    def __init__(self,\n                 cfg=None,\n                 model=None,\n                 ch=3,\n                 nc=None,\n                 cutoff=10,\n                 verbose=True):  # yaml, model, channels, number of classes, cutoff index, verbose flag\n        super().__init__()\n        self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg, ch, nc, verbose)\n\n    def _from_detection_model(self, model, nc=1000, cutoff=10):\n        \"\"\"Create a YOLOv5 classification model from a YOLOv5 detection model.\"\"\"\n        from ultralytics.nn.autobackend import AutoBackend\n        if isinstance(model, AutoBackend):\n            model = model.model  # unwrap DetectMultiBackend\n        model.model = model.model[:cutoff]  # backbone\n        m = model.model[-1]  # last layer\n        ch = m.conv.in_channels if hasattr(m, 'conv') else m.cv1.conv.in_channels  # ch into module\n        c = Classify(ch, nc)  # Classify()\n        c.i, c.f, c.type = m.i, m.f, 'models.common.Classify'  # index, from, type\n        model.model[-1] = c  # replace\n        self.model = model.model\n        self.stride = model.stride\n        self.save = []\n        self.nc = nc\n\n    def _from_yaml(self, cfg, ch, nc, verbose):\n        \"\"\"Set YOLOv8 model configurations and define the model architecture.\"\"\"\n        self.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg)  # cfg dict\n\n        # Define model\n        ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels\n        if nc and nc != self.yaml['nc']:\n            LOGGER.info(f\"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}\")\n            self.yaml['nc'] = nc  # override yaml value\n        elif not nc and not self.yaml.get('nc', None):\n            raise ValueError('nc not specified. Must specify nc in model.yaml or function arguments.')\n        self.model, self.save = parse_model(deepcopy(self.yaml), ch=ch, verbose=verbose)  # model, savelist\n        self.stride = torch.Tensor([1])  # no stride constraints\n        self.names = {i: f'{i}' for i in range(self.yaml['nc'])}  # default names dict\n        self.info()\n\n    @staticmethod\n    def reshape_outputs(model, nc):\n        \"\"\"Update a TorchVision classification model to class count 'n' if required.\"\"\"\n        name, m = list((model.model if hasattr(model, 'model') else model).named_children())[-1]  # last module\n        if isinstance(m, Classify):  # YOLO Classify() head\n            if m.linear.out_features != nc:\n                m.linear = nn.Linear(m.linear.in_features, nc)\n        elif isinstance(m, nn.Linear):  # ResNet, EfficientNet\n            if m.out_features != nc:\n                setattr(model, name, nn.Linear(m.in_features, nc))\n        elif isinstance(m, nn.Sequential):\n            types = [type(x) for x in m]\n            if nn.Linear in types:\n                i = types.index(nn.Linear)  # nn.Linear index\n                if m[i].out_features != nc:\n                    m[i] = nn.Linear(m[i].in_features, nc)\n            elif nn.Conv2d in types:\n                i = types.index(nn.Conv2d)  # nn.Conv2d index\n                if m[i].out_channels != nc:\n                    m[i] = nn.Conv2d(m[i].in_channels, nc, m[i].kernel_size, m[i].stride, bias=m[i].bias is not None)\n\n\nclass Ensemble(nn.ModuleList):\n    \"\"\"Ensemble of models.\"\"\"\n\n    def __init__(self):\n        \"\"\"Initialize an ensemble of models.\"\"\"\n        super().__init__()\n\n    def forward(self, x, augment=False, profile=False, visualize=False):\n        \"\"\"Function generates the YOLOv5 network's final layer.\"\"\"\n        y = [module(x, augment, profile, visualize)[0] for module in self]\n        # y = torch.stack(y).max(0)[0]  # max ensemble\n        # y = torch.stack(y).mean(0)  # mean ensemble\n        y = torch.cat(y, 2)  # nms ensemble, y shape(B, HW, C)\n        return y, None  # inference, train output\n\n\n# Functions ------------------------------------------------------------------------------------------------------------\n\n\ndef torch_safe_load(weight):\n    \"\"\"\n    This function attempts to load a PyTorch model with the torch.load() function. If a ModuleNotFoundError is raised,\n    it catches the error, logs a warning message, and attempts to install the missing module via the\n    check_requirements() function. After installation, the function again attempts to load the model using torch.load().\n\n    Args:\n        weight (str): The file path of the PyTorch model.\n\n    Returns:\n        (dict): The loaded PyTorch model.\n    \"\"\"\n    from ultralytics.yolo.utils.downloads import attempt_download_asset\n\n    check_suffix(file=weight, suffix='.pt')\n    file = attempt_download_asset(weight)  # search online if missing locally\n    try:\n        return torch.load(file, map_location='cpu'), file  # load\n    except ModuleNotFoundError as e:  # e.name is missing module name\n        if e.name == 'models':\n            raise TypeError(\n                emojis(f'ERROR ❌️ {weight} appears to be an Ultralytics YOLOv5 model originally trained '\n                       f'with https://github.com/ultralytics/yolov5.\\nThis model is NOT forwards compatible with '\n                       f'YOLOv8 at https://github.com/ultralytics/ultralytics.'\n                       f\"\\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to \"\n                       f\"run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt'\")) from e\n        LOGGER.warning(f\"WARNING ⚠️ {weight} appears to require '{e.name}', which is not in ultralytics requirements.\"\n                       f\"\\nAutoInstall will run now for '{e.name}' but this feature will be removed in the future.\"\n                       f\"\\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to \"\n                       f\"run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt'\")\n        check_requirements(e.name)  # install missing module\n\n        return torch.load(file, map_location='cpu'), file  # load\n\n\ndef attempt_load_weights(weights, device=None, inplace=True, fuse=False):\n    \"\"\"Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a.\"\"\"\n\n    ensemble = Ensemble()\n    for w in weights if isinstance(weights, list) else [weights]:\n        ckpt, w = torch_safe_load(w)  # load ckpt\n        args = {**DEFAULT_CFG_DICT, **ckpt['train_args']}  # combine model and default args, preferring model args\n        model = (ckpt.get('ema') or ckpt['model']).to(device).float()  # FP32 model\n\n        # Model compatibility updates\n        model.args = args  # attach args to model\n        model.pt_path = w  # attach *.pt file path to model\n        model.task = guess_model_task(model)\n        if not hasattr(model, 'stride'):\n            model.stride = torch.tensor([32.])\n\n        # Append\n        ensemble.append(model.fuse().eval() if fuse and hasattr(model, 'fuse') else model.eval())  # model in eval mode\n\n    # Module compatibility updates\n    for m in ensemble.modules():\n        t = type(m)\n        if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Segment):\n            m.inplace = inplace  # torch 1.7.0 compatibility\n        elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):\n            m.recompute_scale_factor = None  # torch 1.11.0 compatibility\n\n    # Return model\n    if len(ensemble) == 1:\n        return ensemble[-1]\n\n    # Return ensemble\n    LOGGER.info(f'Ensemble created with {weights}\\n')\n    for k in 'names', 'nc', 'yaml':\n        setattr(ensemble, k, getattr(ensemble[0], k))\n    ensemble.stride = ensemble[torch.argmax(torch.tensor([m.stride.max() for m in ensemble])).int()].stride\n    assert all(ensemble[0].nc == m.nc for m in ensemble), f'Models differ in class counts {[m.nc for m in ensemble]}'\n    return ensemble\n\n\ndef attempt_load_one_weight(weight, device=None, inplace=True, fuse=False):\n    \"\"\"Loads a single model weights.\"\"\"\n    ckpt, weight = torch_safe_load(weight)  # load ckpt\n    args = {**DEFAULT_CFG_DICT, **(ckpt.get('train_args', {}))}  # combine model and default args, preferring model args\n    model = (ckpt.get('ema') or ckpt['model']).to(device).float()  # FP32 model\n\n    # Model compatibility updates\n    model.args = {k: v for k, v in args.items() if k in DEFAULT_CFG_KEYS}  # attach args to model\n    model.pt_path = weight  # attach *.pt file path to model\n    model.task = guess_model_task(model)\n    if not hasattr(model, 'stride'):\n        model.stride = torch.tensor([32.])\n\n    model = model.fuse().eval() if fuse and hasattr(model, 'fuse') else model.eval()  # model in eval mode\n\n    # Module compatibility updates\n    for m in model.modules():\n        t = type(m)\n        if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Segment):\n            m.inplace = inplace  # torch 1.7.0 compatibility\n        elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):\n            m.recompute_scale_factor = None  # torch 1.11.0 compatibility\n\n    # Return model and ckpt\n    return model, ckpt\n\n\ndef parse_model(d, ch, verbose=True):  # model_dict, input_channels(3)\n    # Parse a YOLO model.yaml dictionary into a PyTorch model\n    import ast\n\n    # Args\n    max_channels = float('inf')\n    nc, act, scales = (d.get(x) for x in ('nc', 'act', 'scales'))\n    depth, width, kpt_shape = (d.get(x, 1.0) for x in ('depth_multiple', 'width_multiple', 'kpt_shape'))\n    if scales:\n        scale = d.get('scale')\n        if not scale:\n            scale = tuple(scales.keys())[0]\n            LOGGER.warning(f\"WARNING ⚠️ no model scale passed. Assuming scale='{scale}'.\")\n        depth, width, max_channels = scales[scale]\n\n    if act:\n        Conv.default_act = eval(act)  # redefine default activation, i.e. Conv.default_act = nn.SiLU()\n        if verbose:\n            LOGGER.info(f\"{colorstr('activation:')} {act}\")  # print\n\n    if verbose:\n        LOGGER.info(f\"\\n{'':>3}{'from':>20}{'n':>3}{'params':>10}  {'module':<45}{'arguments':<30}\")\n    ch = [ch]\n    layers, save, c2 = [], [], ch[-1]  # layers, savelist, ch out\n    for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']):  # from, number, module, args\n        m = getattr(torch.nn, m[3:]) if 'nn.' in m else globals()[m]  # get module\n        for j, a in enumerate(args):\n            if isinstance(a, str):\n                with contextlib.suppress(ValueError):\n                    args[j] = locals()[a] if a in locals() else ast.literal_eval(a)\n\n        n = n_ = max(round(n * depth), 1) if n > 1 else n  # depth gain\n        if m in (Classify, Conv, ConvTranspose, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, Focus,\n                 BottleneckCSP, C1, C2, C2f, C3, C3TR, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x, RepC3):\n            c1, c2 = ch[f], args[0]\n            if c2 != nc:  # if c2 not equal to number of classes (i.e. for Classify() output)\n                c2 = make_divisible(min(c2, max_channels) * width, 8)\n\n            args = [c1, c2, *args[1:]]\n            if m in (BottleneckCSP, C1, C2, C2f, C3, C3TR, C3Ghost, C3x, RepC3):\n                args.insert(2, n)  # number of repeats\n                n = 1\n        elif m is AIFI:\n            args = [ch[f], *args]\n        elif m in (HGStem, HGBlock):\n            c1, cm, c2 = ch[f], args[0], args[1]\n            args = [c1, cm, c2, *args[2:]]\n            if m is HGBlock:\n                args.insert(4, n)  # number of repeats\n                n = 1\n\n        elif m is nn.BatchNorm2d:\n            args = [ch[f]]\n        elif m is Concat:\n            c2 = sum(ch[x] for x in f)\n        elif m is Concat_dropout:\n            c2 = ch[-1]\n            ch_list = [ch[x] for x in f]\n        elif m in (Detect, Segment, Pose, RTDETRDecoder):\n            args.append([ch[x] for x in f])\n            if m is Segment:\n                args[2] = make_divisible(min(args[2], max_channels) * width, 8)\n        else:\n            c2 = ch[f]\n        ###### Jiayuan\n        if 'Concat_dropout' in str(m):\n            m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args,ch=ch_list)\n        else:\n            m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args)  # module\n        ######\n        t = str(m)[8:-2].replace('__main__.', '')  # module type\n        m.np = sum(x.numel() for x in m_.parameters())  # number params\n        m_.i, m_.f, m_.type = i, f, t  # attach index, 'from' index, type\n        if verbose:\n            LOGGER.info(f'{i:>3}{str(f):>20}{n_:>3}{m.np:10.0f}  {t:<45}{str(args):<30}')  # print\n        save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1)  # append to savelist\n        layers.append(m_)\n        if i == 0:\n            ch = []\n        ch.append(c2)\n    return nn.Sequential(*layers), sorted(save)\n\n\ndef yaml_model_load(path):\n    \"\"\"Load a YOLOv8 model from a YAML file.\"\"\"\n    import re\n\n    path = Path(path)\n    if path.stem in (f'yolov{d}{x}6' for x in 'nsmlx' for d in (5, 8)):\n        new_stem = re.sub(r'(\\d+)([nslmx])6(.+)?$', r'\\1\\2-p6\\3', path.stem)\n        LOGGER.warning(f'WARNING ⚠️ Ultralytics YOLO P6 models now use -p6 suffix. Renaming {path.stem} to {new_stem}.')\n        path = path.with_stem(new_stem)\n\n    unified_path = re.sub(r'(\\d+)([nslmx])(.+)?$', r'\\1\\3', str(path))  # i.e. yolov8x.yaml -> yolov8.yaml\n    yaml_file = check_yaml(unified_path, hard=False) or check_yaml(path)\n    d = yaml_load(yaml_file)  # model dict\n    if not d.get('scale', False):\n        d['scale'] = guess_model_scale(path)\n    d['yaml_file'] = str(path)\n    return d\n\n\ndef guess_model_scale(model_path):\n    \"\"\"\n    Takes a path to a YOLO model's YAML file as input and extracts the size character of the model's scale.\n    The function uses regular expression matching to find the pattern of the model scale in the YAML file name,\n    which is denoted by n, s, m, l, or x. The function returns the size character of the model scale as a string.\n\n    Args:\n        model_path (str) or (Path): The path to the YOLO model's YAML file.\n\n    Returns:\n        (str): The size character of the model's scale, which can be n, s, m, l, or x.\n    \"\"\"\n    with contextlib.suppress(AttributeError):\n        import re\n        return re.search(r'yolov\\d+([nslmx])', Path(model_path).stem).group(1)  # n, s, m, l, or x\n    return ''\n\n\ndef guess_model_task(model):\n    \"\"\"\n    Guess the task of a PyTorch model from its architecture or configuration.\n\n    Args:\n        model (nn.Module) or (dict): PyTorch model or model configuration in YAML format.\n\n    Returns:\n        (str): Task of the model ('detect', 'segment', 'classify', 'pose').\n\n    Raises:\n        SyntaxError: If the task of the model could not be determined.\n    \"\"\"\n\n    def cfg2task(cfg):\n        \"\"\"Guess from YAML dictionary.\"\"\"\n        m = cfg['head'][-1][-2].lower()  # output module name\n        if m in ('classify', 'classifier', 'cls', 'fc'):\n            return 'classify'\n        if m == 'detect':\n            return 'detect'\n        if m == 'segment':\n            return 'segment'\n        if m == 'pose':\n            return 'pose'\n\n    # Guess from model cfg\n    if isinstance(model, dict):\n        with contextlib.suppress(Exception):\n            return cfg2task(model)\n\n    # Guess from PyTorch model\n    if isinstance(model, nn.Module):  # PyTorch model\n        for x in 'model.args', 'model.model.args', 'model.model.model.args':\n            with contextlib.suppress(Exception):\n                return eval(x)['task']\n        for x in 'model.yaml', 'model.model.yaml', 'model.model.model.yaml':\n            with contextlib.suppress(Exception):\n                return cfg2task(eval(x))\n\n        for m in model.modules():\n            if isinstance(m, Detect):\n                return 'detect'\n            elif isinstance(m, Segment):\n                return 'segment'\n            elif isinstance(m, Classify):\n                return 'classify'\n            elif isinstance(m, Pose):\n                return 'pose'\n\n    # Guess from model filename\n    if isinstance(model, (str, Path)):\n        model = Path(model)\n        if '-seg' in model.stem or 'segment' in model.parts:\n            return 'segment'\n        elif '-cls' in model.stem or 'classify' in model.parts:\n            return 'classify'\n        elif '-pose' in model.stem or 'pose' in model.parts:\n            return 'pose'\n        elif 'detect' in model.parts:\n            return 'detect'\n\n    # Unable to determine task from model\n    LOGGER.warning(\"WARNING ⚠️ Unable to automatically guess model task, assuming 'task=detect'. \"\n                   \"Explicitly define task for your model, i.e. 'task=detect', 'segment', 'classify', or 'pose'.\")\n    return 'detect'  # assume detect\n"
  },
  {
    "path": "ultralytics/nn/__init__.py",
    "content": ""
  },
  {
    "path": "ultralytics/nn/autobackend.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport ast\nimport contextlib\nimport json\nimport platform\nimport zipfile\nfrom collections import OrderedDict, namedtuple\nfrom pathlib import Path\nfrom urllib.parse import urlparse\nimport itertools\nimport cv2\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom PIL import Image\n\nfrom ultralytics.yolo.utils import LINUX, LOGGER, ROOT, yaml_load\nfrom ultralytics.yolo.utils.checks import check_requirements, check_suffix, check_version, check_yaml\nfrom ultralytics.yolo.utils.downloads import attempt_download_asset, is_url\nfrom ultralytics.yolo.utils.ops import xywh2xyxy\n\n\ndef check_class_names(names):\n    \"\"\"Check class names. Map imagenet class codes to human-readable names if required. Convert lists to dicts.\"\"\"\n    if isinstance(names, list):  # names is a list\n        names = dict(enumerate(names))  # convert to dict\n    if isinstance(names, dict):\n        # Convert 1) string keys to int, i.e. '0' to 0, and non-string values to strings, i.e. True to 'True'\n        names = {int(k): str(v) for k, v in names.items()}\n        n = len(names)\n        if max(names.keys()) >= n:\n            raise KeyError(f'{n}-class dataset requires class indices 0-{n - 1}, but you have invalid class indices '\n                           f'{min(names.keys())}-{max(names.keys())} defined in your dataset YAML.')\n        if isinstance(names[0], str) and names[0].startswith('n0'):  # imagenet class codes, i.e. 'n01440764'\n            map = yaml_load(ROOT / 'datasets/ImageNet.yaml')['map']  # human-readable names\n            names = {k: map[v] for k, v in names.items()}\n    return names\n\n\nclass AutoBackend(nn.Module):\n\n    def __init__(self,\n                 weights='yolov8n.pt',\n                 device=torch.device('cpu'),\n                 dnn=False,\n                 data=None,\n                 fp16=False,\n                 fuse=True,\n                 verbose=True):\n        \"\"\"\n        MultiBackend class for python inference on various platforms using Ultralytics YOLO.\n\n        Args:\n            weights (str): The path to the weights file. Default: 'yolov8n.pt'\n            device (torch.device): The device to run the model on.\n            dnn (bool): Use OpenCV's DNN module for inference if True, defaults to False.\n            data (str), (Path): Additional data.yaml file for class names, optional\n            fp16 (bool): If True, use half precision. Default: False\n            fuse (bool): Whether to fuse the model or not. Default: True\n            verbose (bool): Whether to run in verbose mode or not. Default: True\n\n        Supported formats and their naming conventions:\n            | Format                | Suffix           |\n            |-----------------------|------------------|\n            | PyTorch               | *.pt             |\n            | TorchScript           | *.torchscript    |\n            | ONNX Runtime          | *.onnx           |\n            | ONNX OpenCV DNN       | *.onnx dnn=True  |\n            | OpenVINO              | *.xml            |\n            | CoreML                | *.mlmodel        |\n            | TensorRT              | *.engine         |\n            | TensorFlow SavedModel | *_saved_model    |\n            | TensorFlow GraphDef   | *.pb             |\n            | TensorFlow Lite       | *.tflite         |\n            | TensorFlow Edge TPU   | *_edgetpu.tflite |\n            | PaddlePaddle          | *_paddle_model   |\n        \"\"\"\n        super().__init__()\n        w = str(weights[0] if isinstance(weights, list) else weights)\n        nn_module = isinstance(weights, torch.nn.Module)\n        pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle, triton = self._model_type(w)\n        fp16 &= pt or jit or onnx or engine or nn_module or triton  # FP16\n        nhwc = coreml or saved_model or pb or tflite or edgetpu  # BHWC formats (vs torch BCWH)\n        stride = 32  # default stride\n        model, metadata = None, None\n        cuda = torch.cuda.is_available() and device.type != 'cpu'  # use CUDA\n        if not (pt or triton or nn_module):\n            w = attempt_download_asset(w)  # download if not local\n\n        # NOTE: special case: in-memory pytorch model\n        if nn_module:\n            model = weights.to(device)\n            model = model.fuse(verbose=verbose) if fuse else model\n            if hasattr(model, 'kpt_shape'):\n                kpt_shape = model.kpt_shape  # pose-only\n            try:\n                stride = max(int(model.stride.max()), 32)\n            except:\n                stride = max(max(itertools.chain.from_iterable(model.stride)), 32)\n            # stride = max(int(model.stride.max()), 32)  # model stride\n            names = model.module.names if hasattr(model, 'module') else model.names  # get class names\n            model.half() if fp16 else model.float()\n            self.model = model  # explicitly assign for to(), cpu(), cuda(), half()\n            pt = True\n        elif pt:  # PyTorch\n            from ultralytics.nn.tasks import attempt_load_weights\n            model = attempt_load_weights(weights if isinstance(weights, list) else w,\n                                         device=device,\n                                         inplace=True,\n                                         fuse=fuse)\n            if hasattr(model, 'kpt_shape'):\n                kpt_shape = model.kpt_shape  # pose-only\n            try:\n                stride = max(int(model.stride.max()), 32)\n            except:\n                stride = max(max(itertools.chain.from_iterable(model.stride)), 32)\n            # stride = max(int(model.stride.max()), 32)  # model stride\n            names = model.module.names if hasattr(model, 'module') else model.names  # get class names\n            model.half() if fp16 else model.float()\n            self.model = model  # explicitly assign for to(), cpu(), cuda(), half()\n        elif jit:  # TorchScript\n            LOGGER.info(f'Loading {w} for TorchScript inference...')\n            extra_files = {'config.txt': ''}  # model metadata\n            model = torch.jit.load(w, _extra_files=extra_files, map_location=device)\n            model.half() if fp16 else model.float()\n            if extra_files['config.txt']:  # load metadata dict\n                metadata = json.loads(extra_files['config.txt'], object_hook=lambda x: dict(x.items()))\n        elif dnn:  # ONNX OpenCV DNN\n            LOGGER.info(f'Loading {w} for ONNX OpenCV DNN inference...')\n            check_requirements('opencv-python>=4.5.4')\n            net = cv2.dnn.readNetFromONNX(w)\n        elif onnx:  # ONNX Runtime\n            LOGGER.info(f'Loading {w} for ONNX Runtime inference...')\n            check_requirements(('onnx', 'onnxruntime-gpu' if cuda else 'onnxruntime'))\n            import onnxruntime\n            providers = ['CUDAExecutionProvider', 'CPUExecutionProvider'] if cuda else ['CPUExecutionProvider']\n            session = onnxruntime.InferenceSession(w, providers=providers)\n            output_names = [x.name for x in session.get_outputs()]\n            metadata = session.get_modelmeta().custom_metadata_map  # metadata\n        elif xml:  # OpenVINO\n            LOGGER.info(f'Loading {w} for OpenVINO inference...')\n            check_requirements('openvino')  # requires openvino-dev: https://pypi.org/project/openvino-dev/\n            from openvino.runtime import Core, Layout, get_batch  # noqa\n            ie = Core()\n            w = Path(w)\n            if not w.is_file():  # if not *.xml\n                w = next(w.glob('*.xml'))  # get *.xml file from *_openvino_model dir\n            network = ie.read_model(model=str(w), weights=w.with_suffix('.bin'))\n            if network.get_parameters()[0].get_layout().empty:\n                network.get_parameters()[0].set_layout(Layout('NCHW'))\n            batch_dim = get_batch(network)\n            if batch_dim.is_static:\n                batch_size = batch_dim.get_length()\n            executable_network = ie.compile_model(network, device_name='CPU')  # device_name=\"MYRIAD\" for NCS2\n            metadata = w.parent / 'metadata.yaml'\n        elif engine:  # TensorRT\n            LOGGER.info(f'Loading {w} for TensorRT inference...')\n            try:\n                import tensorrt as trt  # noqa https://developer.nvidia.com/nvidia-tensorrt-download\n            except ImportError:\n                if LINUX:\n                    check_requirements('nvidia-tensorrt', cmds='-U --index-url https://pypi.ngc.nvidia.com')\n                import tensorrt as trt  # noqa\n            check_version(trt.__version__, '7.0.0', hard=True)  # require tensorrt>=7.0.0\n            if device.type == 'cpu':\n                device = torch.device('cuda:0')\n            Binding = namedtuple('Binding', ('name', 'dtype', 'shape', 'data', 'ptr'))\n            logger = trt.Logger(trt.Logger.INFO)\n            # Read file\n            with open(w, 'rb') as f, trt.Runtime(logger) as runtime:\n                meta_len = int.from_bytes(f.read(4), byteorder='little')  # read metadata length\n                metadata = json.loads(f.read(meta_len).decode('utf-8'))  # read metadata\n                model = runtime.deserialize_cuda_engine(f.read())  # read engine\n            context = model.create_execution_context()\n            bindings = OrderedDict()\n            output_names = []\n            fp16 = False  # default updated below\n            dynamic = False\n            for i in range(model.num_bindings):\n                name = model.get_binding_name(i)\n                dtype = trt.nptype(model.get_binding_dtype(i))\n                if model.binding_is_input(i):\n                    if -1 in tuple(model.get_binding_shape(i)):  # dynamic\n                        dynamic = True\n                        context.set_binding_shape(i, tuple(model.get_profile_shape(0, i)[2]))\n                    if dtype == np.float16:\n                        fp16 = True\n                else:  # output\n                    output_names.append(name)\n                shape = tuple(context.get_binding_shape(i))\n                im = torch.from_numpy(np.empty(shape, dtype=dtype)).to(device)\n                bindings[name] = Binding(name, dtype, shape, im, int(im.data_ptr()))\n            binding_addrs = OrderedDict((n, d.ptr) for n, d in bindings.items())\n            batch_size = bindings['images'].shape[0]  # if dynamic, this is instead max batch size\n        elif coreml:  # CoreML\n            LOGGER.info(f'Loading {w} for CoreML inference...')\n            import coremltools as ct\n            model = ct.models.MLModel(w)\n            metadata = dict(model.user_defined_metadata)\n        elif saved_model:  # TF SavedModel\n            LOGGER.info(f'Loading {w} for TensorFlow SavedModel inference...')\n            import tensorflow as tf\n            keras = False  # assume TF1 saved_model\n            model = tf.keras.models.load_model(w) if keras else tf.saved_model.load(w)\n            metadata = Path(w) / 'metadata.yaml'\n        elif pb:  # GraphDef https://www.tensorflow.org/guide/migrate#a_graphpb_or_graphpbtxt\n            LOGGER.info(f'Loading {w} for TensorFlow GraphDef inference...')\n            import tensorflow as tf\n\n            from ultralytics.yolo.engine.exporter import gd_outputs\n\n            def wrap_frozen_graph(gd, inputs, outputs):\n                \"\"\"Wrap frozen graphs for deployment.\"\"\"\n                x = tf.compat.v1.wrap_function(lambda: tf.compat.v1.import_graph_def(gd, name=''), [])  # wrapped\n                ge = x.graph.as_graph_element\n                return x.prune(tf.nest.map_structure(ge, inputs), tf.nest.map_structure(ge, outputs))\n\n            gd = tf.Graph().as_graph_def()  # TF GraphDef\n            with open(w, 'rb') as f:\n                gd.ParseFromString(f.read())\n            frozen_func = wrap_frozen_graph(gd, inputs='x:0', outputs=gd_outputs(gd))\n        elif tflite or edgetpu:  # https://www.tensorflow.org/lite/guide/python#install_tensorflow_lite_for_python\n            try:  # https://coral.ai/docs/edgetpu/tflite-python/#update-existing-tf-lite-code-for-the-edge-tpu\n                from tflite_runtime.interpreter import Interpreter, load_delegate\n            except ImportError:\n                import tensorflow as tf\n                Interpreter, load_delegate = tf.lite.Interpreter, tf.lite.experimental.load_delegate\n            if edgetpu:  # TF Edge TPU https://coral.ai/software/#edgetpu-runtime\n                LOGGER.info(f'Loading {w} for TensorFlow Lite Edge TPU inference...')\n                delegate = {\n                    'Linux': 'libedgetpu.so.1',\n                    'Darwin': 'libedgetpu.1.dylib',\n                    'Windows': 'edgetpu.dll'}[platform.system()]\n                interpreter = Interpreter(model_path=w, experimental_delegates=[load_delegate(delegate)])\n            else:  # TFLite\n                LOGGER.info(f'Loading {w} for TensorFlow Lite inference...')\n                interpreter = Interpreter(model_path=w)  # load TFLite model\n            interpreter.allocate_tensors()  # allocate\n            input_details = interpreter.get_input_details()  # inputs\n            output_details = interpreter.get_output_details()  # outputs\n            # Load metadata\n            with contextlib.suppress(zipfile.BadZipFile):\n                with zipfile.ZipFile(w, 'r') as model:\n                    meta_file = model.namelist()[0]\n                    metadata = ast.literal_eval(model.read(meta_file).decode('utf-8'))\n        elif tfjs:  # TF.js\n            raise NotImplementedError('YOLOv8 TF.js inference is not supported')\n        elif paddle:  # PaddlePaddle\n            LOGGER.info(f'Loading {w} for PaddlePaddle inference...')\n            check_requirements('paddlepaddle-gpu' if cuda else 'paddlepaddle')\n            import paddle.inference as pdi  # noqa\n            w = Path(w)\n            if not w.is_file():  # if not *.pdmodel\n                w = next(w.rglob('*.pdmodel'))  # get *.pdmodel file from *_paddle_model dir\n            config = pdi.Config(str(w), str(w.with_suffix('.pdiparams')))\n            if cuda:\n                config.enable_use_gpu(memory_pool_init_size_mb=2048, device_id=0)\n            predictor = pdi.create_predictor(config)\n            input_handle = predictor.get_input_handle(predictor.get_input_names()[0])\n            output_names = predictor.get_output_names()\n            metadata = w.parents[1] / 'metadata.yaml'\n        elif triton:  # NVIDIA Triton Inference Server\n            LOGGER.info('Triton Inference Server not supported...')\n            '''\n            TODO:\n            check_requirements('tritonclient[all]')\n            from utils.triton import TritonRemoteModel\n            model = TritonRemoteModel(url=w)\n            nhwc = model.runtime.startswith(\"tensorflow\")\n            '''\n        else:\n            from ultralytics.yolo.engine.exporter import export_formats\n            raise TypeError(f\"model='{w}' is not a supported model format. \"\n                            'See https://docs.ultralytics.com/modes/predict for help.'\n                            f'\\n\\n{export_formats()}')\n\n        # Load external metadata YAML\n        if isinstance(metadata, (str, Path)) and Path(metadata).exists():\n            metadata = yaml_load(metadata)\n        if metadata:\n            for k, v in metadata.items():\n                if k in ('stride', 'batch'):\n                    metadata[k] = int(v)\n                elif k in ('imgsz', 'names', 'kpt_shape') and isinstance(v, str):\n                    metadata[k] = eval(v)\n            stride = metadata['stride']\n            task = metadata['task']\n            batch = metadata['batch']\n            imgsz = metadata['imgsz']\n            names = metadata['names']\n            kpt_shape = metadata.get('kpt_shape')\n        elif not (pt or triton or nn_module):\n            LOGGER.warning(f\"WARNING ⚠️ Metadata not found for 'model={weights}'\")\n\n        # Check names\n        if 'names' not in locals():  # names missing\n            names = self._apply_default_class_names(data)\n        names = check_class_names(names)\n\n        self.__dict__.update(locals())  # assign all variables to self\n\n    def forward(self, im, augment=False, visualize=False):\n        \"\"\"\n        Runs inference on the YOLOv8 MultiBackend model.\n\n        Args:\n            im (torch.Tensor): The image tensor to perform inference on.\n            augment (bool): whether to perform data augmentation during inference, defaults to False\n            visualize (bool): whether to visualize the output predictions, defaults to False\n\n        Returns:\n            (tuple): Tuple containing the raw output tensor, and processed output for visualization (if visualize=True)\n        \"\"\"\n        b, ch, h, w = im.shape  # batch, channel, height, width\n        if self.fp16 and im.dtype != torch.float16:\n            im = im.half()  # to FP16\n        if self.nhwc:\n            im = im.permute(0, 2, 3, 1)  # torch BCHW to numpy BHWC shape(1,320,192,3)\n\n        if self.pt or self.nn_module:  # PyTorch\n            y = self.model(im, augment=augment, visualize=visualize) if augment or visualize else self.model(im)\n        elif self.jit:  # TorchScript\n            y = self.model(im)\n        elif self.dnn:  # ONNX OpenCV DNN\n            im = im.cpu().numpy()  # torch to numpy\n            self.net.setInput(im)\n            y = self.net.forward()\n        elif self.onnx:  # ONNX Runtime\n            im = im.cpu().numpy()  # torch to numpy\n            y = self.session.run(self.output_names, {self.session.get_inputs()[0].name: im})\n        elif self.xml:  # OpenVINO\n            im = im.cpu().numpy()  # FP32\n            y = list(self.executable_network([im]).values())\n        elif self.engine:  # TensorRT\n            if self.dynamic and im.shape != self.bindings['images'].shape:\n                i = self.model.get_binding_index('images')\n                self.context.set_binding_shape(i, im.shape)  # reshape if dynamic\n                self.bindings['images'] = self.bindings['images']._replace(shape=im.shape)\n                for name in self.output_names:\n                    i = self.model.get_binding_index(name)\n                    self.bindings[name].data.resize_(tuple(self.context.get_binding_shape(i)))\n            s = self.bindings['images'].shape\n            assert im.shape == s, f\"input size {im.shape} {'>' if self.dynamic else 'not equal to'} max model size {s}\"\n            self.binding_addrs['images'] = int(im.data_ptr())\n            self.context.execute_v2(list(self.binding_addrs.values()))\n            y = [self.bindings[x].data for x in sorted(self.output_names)]\n        elif self.coreml:  # CoreML\n            im = im[0].cpu().numpy()\n            im_pil = Image.fromarray((im * 255).astype('uint8'))\n            # im = im.resize((192, 320), Image.ANTIALIAS)\n            y = self.model.predict({'image': im_pil})  # coordinates are xywh normalized\n            if 'confidence' in y:\n                box = xywh2xyxy(y['coordinates'] * [[w, h, w, h]])  # xyxy pixels\n                conf, cls = y['confidence'].max(1), y['confidence'].argmax(1).astype(np.float)\n                y = np.concatenate((box, conf.reshape(-1, 1), cls.reshape(-1, 1)), 1)\n            elif len(y) == 1:  # classification model\n                y = list(y.values())\n            elif len(y) == 2:  # segmentation model\n                y = list(reversed(y.values()))  # reversed for segmentation models (pred, proto)\n        elif self.paddle:  # PaddlePaddle\n            im = im.cpu().numpy().astype(np.float32)\n            self.input_handle.copy_from_cpu(im)\n            self.predictor.run()\n            y = [self.predictor.get_output_handle(x).copy_to_cpu() for x in self.output_names]\n        elif self.triton:  # NVIDIA Triton Inference Server\n            y = self.model(im)\n        else:  # TensorFlow (SavedModel, GraphDef, Lite, Edge TPU)\n            im = im.cpu().numpy()\n            if self.saved_model:  # SavedModel\n                y = self.model(im, training=False) if self.keras else self.model(im)\n                if not isinstance(y, list):\n                    y = [y]\n            elif self.pb:  # GraphDef\n                y = self.frozen_func(x=self.tf.constant(im))\n                if len(y) == 2 and len(self.names) == 999:  # segments and names not defined\n                    ip, ib = (0, 1) if len(y[0].shape) == 4 else (1, 0)  # index of protos, boxes\n                    nc = y[ib].shape[1] - y[ip].shape[3] - 4  # y = (1, 160, 160, 32), (1, 116, 8400)\n                    self.names = {i: f'class{i}' for i in range(nc)}\n            else:  # Lite or Edge TPU\n                input = self.input_details[0]\n                int8 = input['dtype'] == np.int8  # is TFLite quantized int8 model\n                if int8:\n                    scale, zero_point = input['quantization']\n                    im = (im / scale + zero_point).astype(np.int8)  # de-scale\n                self.interpreter.set_tensor(input['index'], im)\n                self.interpreter.invoke()\n                y = []\n                for output in self.output_details:\n                    x = self.interpreter.get_tensor(output['index'])\n                    if int8:\n                        scale, zero_point = output['quantization']\n                        x = (x.astype(np.float32) - zero_point) * scale  # re-scale\n                    y.append(x)\n            # TF segment fixes: export is reversed vs ONNX export and protos are transposed\n            if len(y) == 2:  # segment with (det, proto) output order reversed\n                if len(y[1].shape) != 4:\n                    y = list(reversed(y))  # should be y = (1, 116, 8400), (1, 160, 160, 32)\n                y[1] = np.transpose(y[1], (0, 3, 1, 2))  # should be y = (1, 116, 8400), (1, 32, 160, 160)\n            y = [x if isinstance(x, np.ndarray) else x.numpy() for x in y]\n            # y[0][..., :4] *= [w, h, w, h]  # xywh normalized to pixels\n\n        # for x in y:\n        #     print(type(x), len(x)) if isinstance(x, (list, tuple)) else print(type(x), x.shape)  # debug shapes\n        if isinstance(y, (list, tuple)):\n            return self.from_numpy(y[0]) if len(y) == 1 else [self.from_numpy(x) for x in y]\n        else:\n            return self.from_numpy(y)\n\n    def from_numpy(self, x):\n        \"\"\"\n         Convert a numpy array to a tensor.\n\n         Args:\n             x (np.ndarray): The array to be converted.\n\n         Returns:\n             (torch.Tensor): The converted tensor\n         \"\"\"\n        return torch.tensor(x).to(self.device) if isinstance(x, np.ndarray) else x\n\n    def warmup(self, imgsz=(1, 3, 640, 640)):\n        \"\"\"\n        Warm up the model by running one forward pass with a dummy input.\n\n        Args:\n            imgsz (tuple): The shape of the dummy input tensor in the format (batch_size, channels, height, width)\n\n        Returns:\n            (None): This method runs the forward pass and don't return any value\n        \"\"\"\n        warmup_types = self.pt, self.jit, self.onnx, self.engine, self.saved_model, self.pb, self.triton, self.nn_module\n        if any(warmup_types) and (self.device.type != 'cpu' or self.triton):\n            im = torch.empty(*imgsz, dtype=torch.half if self.fp16 else torch.float, device=self.device)  # input\n            for _ in range(2 if self.jit else 1):  #\n                self.forward(im)  # warmup\n\n    @staticmethod\n    def _apply_default_class_names(data):\n        \"\"\"Applies default class names to an input YAML file or returns numerical class names.\"\"\"\n        with contextlib.suppress(Exception):\n            return yaml_load(check_yaml(data))['names']\n        return {i: f'class{i}' for i in range(999)}  # return default if above errors\n\n    @staticmethod\n    def _model_type(p='path/to/model.pt'):\n        \"\"\"\n        This function takes a path to a model file and returns the model type\n\n        Args:\n            p: path to the model file. Defaults to path/to/model.pt\n        \"\"\"\n        # Return model type from model path, i.e. path='path/to/model.onnx' -> type=onnx\n        # types = [pt, jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle]\n        from ultralytics.yolo.engine.exporter import export_formats\n        sf = list(export_formats().Suffix)  # export suffixes\n        if not is_url(p, check=False) and not isinstance(p, str):\n            check_suffix(p, sf)  # checks\n        url = urlparse(p)  # if url may be Triton inference server\n        types = [s in Path(p).name for s in sf]\n        types[8] &= not types[9]  # tflite &= not edgetpu\n        triton = not any(types) and all([any(s in url.scheme for s in ['http', 'grpc']), url.netloc])\n        return types + [triton]\n"
  },
  {
    "path": "ultralytics/nn/autoshape.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nCommon modules\n\"\"\"\n\nfrom copy import copy\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport requests\nimport torch\nimport torch.nn as nn\nfrom PIL import Image, ImageOps\nfrom torch.cuda import amp\n\nfrom ultralytics.nn.autobackend import AutoBackend\nfrom ultralytics.yolo.data.augment import LetterBox\nfrom ultralytics.yolo.utils import LOGGER, colorstr\nfrom ultralytics.yolo.utils.files import increment_path\nfrom ultralytics.yolo.utils.ops import Profile, make_divisible, non_max_suppression, scale_boxes, xyxy2xywh\nfrom ultralytics.yolo.utils.plotting import Annotator, colors, save_one_box\nfrom ultralytics.yolo.utils.torch_utils import copy_attr, smart_inference_mode\n\n\nclass AutoShape(nn.Module):\n    \"\"\"YOLOv8 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS.\"\"\"\n    conf = 0.25  # NMS confidence threshold\n    iou = 0.45  # NMS IoU threshold\n    agnostic = False  # NMS class-agnostic\n    multi_label = False  # NMS multiple labels per box\n    classes = None  # (optional list) filter by class, i.e. = [0, 15, 16] for COCO persons, cats and dogs\n    max_det = 1000  # maximum number of detections per image\n    amp = False  # Automatic Mixed Precision (AMP) inference\n\n    def __init__(self, model, verbose=True):\n        \"\"\"Initializes object and copies attributes from model object.\"\"\"\n        super().__init__()\n        if verbose:\n            LOGGER.info('Adding AutoShape... ')\n        copy_attr(self, model, include=('yaml', 'nc', 'hyp', 'names', 'stride', 'abc'), exclude=())  # copy attributes\n        self.dmb = isinstance(model, AutoBackend)  # DetectMultiBackend() instance\n        self.pt = not self.dmb or model.pt  # PyTorch model\n        self.model = model.eval()\n        if self.pt:\n            m = self.model.model.model[-1] if self.dmb else self.model.model[-1]  # Detect()\n            m.inplace = False  # Detect.inplace=False for safe multithread inference\n            m.export = True  # do not output loss values\n\n    def _apply(self, fn):\n        \"\"\"Apply to(), cpu(), cuda(), half() to model tensors that are not parameters or registered buffers.\"\"\"\n        self = super()._apply(fn)\n        if self.pt:\n            m = self.model.model.model[-1] if self.dmb else self.model.model[-1]  # Detect()\n            m.stride = fn(m.stride)\n            m.grid = list(map(fn, m.grid))\n            if isinstance(m.anchor_grid, list):\n                m.anchor_grid = list(map(fn, m.anchor_grid))\n        return self\n\n    @smart_inference_mode()\n    def forward(self, ims, size=640, augment=False, profile=False):\n        \"\"\"Inference from various sources. For size(height=640, width=1280), RGB images example inputs are:.\"\"\"\n        #   file:        ims = 'data/images/zidane.jpg'  # str or PosixPath\n        #   URI:             = 'https://ultralytics.com/images/zidane.jpg'\n        #   OpenCV:          = cv2.imread('image.jpg')[:,:,::-1]  # HWC BGR to RGB x(640,1280,3)\n        #   PIL:             = Image.open('image.jpg') or ImageGrab.grab()  # HWC x(640,1280,3)\n        #   numpy:           = np.zeros((640,1280,3))  # HWC\n        #   torch:           = torch.zeros(16,3,320,640)  # BCHW (scaled to size=640, 0-1 values)\n        #   multiple:        = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...]  # list of images\n\n        dt = (Profile(), Profile(), Profile())\n        with dt[0]:\n            if isinstance(size, int):  # expand\n                size = (size, size)\n            p = next(self.model.parameters()) if self.pt else torch.empty(1, device=self.model.device)  # param\n            autocast = self.amp and (p.device.type != 'cpu')  # Automatic Mixed Precision (AMP) inference\n            if isinstance(ims, torch.Tensor):  # torch\n                with amp.autocast(autocast):\n                    return self.model(ims.to(p.device).type_as(p), augment=augment)  # inference\n\n            # Preprocess\n            n, ims = (len(ims), list(ims)) if isinstance(ims, (list, tuple)) else (1, [ims])  # number, list of images\n            shape0, shape1, files = [], [], []  # image and inference shapes, filenames\n            for i, im in enumerate(ims):\n                f = f'image{i}'  # filename\n                if isinstance(im, (str, Path)):  # filename or uri\n                    im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im\n                    im = np.asarray(ImageOps.exif_transpose(im))\n                elif isinstance(im, Image.Image):  # PIL Image\n                    im, f = np.asarray(ImageOps.exif_transpose(im)), getattr(im, 'filename', f) or f\n                files.append(Path(f).with_suffix('.jpg').name)\n                if im.shape[0] < 5:  # image in CHW\n                    im = im.transpose((1, 2, 0))  # reverse dataloader .transpose(2, 0, 1)\n                im = im[..., :3] if im.ndim == 3 else cv2.cvtColor(im, cv2.COLOR_GRAY2BGR)  # enforce 3ch input\n                s = im.shape[:2]  # HWC\n                shape0.append(s)  # image shape\n                g = max(size) / max(s)  # gain\n                shape1.append([y * g for y in s])\n                ims[i] = im if im.data.contiguous else np.ascontiguousarray(im)  # update\n            shape1 = [make_divisible(x, self.stride) for x in np.array(shape1).max(0)] if self.pt else size  # inf shape\n            x = [LetterBox(shape1, auto=False)(image=im)['img'] for im in ims]  # pad\n            x = np.ascontiguousarray(np.array(x).transpose((0, 3, 1, 2)))  # stack and BHWC to BCHW\n            x = torch.from_numpy(x).to(p.device).type_as(p) / 255  # uint8 to fp16/32\n\n        with amp.autocast(autocast):\n            # Inference\n            with dt[1]:\n                y = self.model(x, augment=augment)  # forward\n\n            # Postprocess\n            with dt[2]:\n                y = non_max_suppression(y if self.dmb else y[0],\n                                        self.conf,\n                                        self.iou,\n                                        self.classes,\n                                        self.agnostic,\n                                        self.multi_label,\n                                        max_det=self.max_det)  # NMS\n                for i in range(n):\n                    scale_boxes(shape1, y[i][:, :4], shape0[i])\n\n            return Detections(ims, y, files, dt, self.names, x.shape)\n\n\nclass Detections:\n    # YOLOv8 detections class for inference results\n    def __init__(self, ims, pred, files, times=(0, 0, 0), names=None, shape=None):\n        \"\"\"Initialize object attributes for YOLO detection results.\"\"\"\n        super().__init__()\n        d = pred[0].device  # device\n        gn = [torch.tensor([*(im.shape[i] for i in [1, 0, 1, 0]), 1, 1], device=d) for im in ims]  # normalizations\n        self.ims = ims  # list of images as numpy arrays\n        self.pred = pred  # list of tensors pred[0] = (xyxy, conf, cls)\n        self.names = names  # class names\n        self.files = files  # image filenames\n        self.times = times  # profiling times\n        self.xyxy = pred  # xyxy pixels\n        self.xywh = [xyxy2xywh(x) for x in pred]  # xywh pixels\n        self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)]  # xyxy normalized\n        self.xywhn = [x / g for x, g in zip(self.xywh, gn)]  # xywh normalized\n        self.n = len(self.pred)  # number of images (batch size)\n        self.t = tuple(x.t / self.n * 1E3 for x in times)  # timestamps (ms)\n        self.s = tuple(shape)  # inference BCHW shape\n\n    def _run(self, pprint=False, show=False, save=False, crop=False, render=False, labels=True, save_dir=Path('')):\n        \"\"\"Return performance metrics and optionally cropped/save images or results.\"\"\"\n        s, crops = '', []\n        for i, (im, pred) in enumerate(zip(self.ims, self.pred)):\n            s += f'\\nimage {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} '  # string\n            if pred.shape[0]:\n                for c in pred[:, -1].unique():\n                    n = (pred[:, -1] == c).sum()  # detections per class\n                    s += f\"{n} {self.names[int(c)]}{'s' * (n > 1)}, \"  # add to string\n                s = s.rstrip(', ')\n                if show or save or render or crop:\n                    annotator = Annotator(im, example=str(self.names))\n                    for *box, conf, cls in reversed(pred):  # xyxy, confidence, class\n                        label = f'{self.names[int(cls)]} {conf:.2f}'\n                        if crop:\n                            file = save_dir / 'crops' / self.names[int(cls)] / self.files[i] if save else None\n                            crops.append({\n                                'box': box,\n                                'conf': conf,\n                                'cls': cls,\n                                'label': label,\n                                'im': save_one_box(box, im, file=file, save=save)})\n                        else:  # all others\n                            annotator.box_label(box, label if labels else '', color=colors(cls))\n                    im = annotator.im\n            else:\n                s += '(no detections)'\n\n            im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im  # from np\n            if show:\n                im.show(self.files[i])  # show\n            if save:\n                f = self.files[i]\n                im.save(save_dir / f)  # save\n                if i == self.n - 1:\n                    LOGGER.info(f\"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}\")\n            if render:\n                self.ims[i] = np.asarray(im)\n        if pprint:\n            s = s.lstrip('\\n')\n            return f'{s}\\nSpeed: %.1fms preprocess, %.1fms inference, %.1fms NMS per image at shape {self.s}' % self.t\n        if crop:\n            if save:\n                LOGGER.info(f'Saved results to {save_dir}\\n')\n            return crops\n\n    def show(self, labels=True):\n        \"\"\"Displays YOLO results with detected bounding boxes.\"\"\"\n        self._run(show=True, labels=labels)  # show results\n\n    def save(self, labels=True, save_dir='runs/detect/exp', exist_ok=False):\n        \"\"\"Save detection results with optional labels to specified directory.\"\"\"\n        save_dir = increment_path(save_dir, exist_ok, mkdir=True)  # increment save_dir\n        self._run(save=True, labels=labels, save_dir=save_dir)  # save results\n\n    def crop(self, save=True, save_dir='runs/detect/exp', exist_ok=False):\n        \"\"\"Crops images into detections and saves them if 'save' is True.\"\"\"\n        save_dir = increment_path(save_dir, exist_ok, mkdir=True) if save else None\n        return self._run(crop=True, save=save, save_dir=save_dir)  # crop results\n\n    def render(self, labels=True):\n        \"\"\"Renders detected objects and returns images.\"\"\"\n        self._run(render=True, labels=labels)  # render results\n        return self.ims\n\n    def pandas(self):\n        \"\"\"Return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0]).\"\"\"\n        import pandas\n        new = copy(self)  # return copy\n        ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name'  # xyxy columns\n        cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name'  # xywh columns\n        for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):\n            a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)]  # update\n            setattr(new, k, [pandas.DataFrame(x, columns=c) for x in a])\n        return new\n\n    def tolist(self):\n        \"\"\"Return a list of Detections objects, i.e. 'for result in results.tolist():'.\"\"\"\n        r = range(self.n)  # iterable\n        x = [Detections([self.ims[i]], [self.pred[i]], [self.files[i]], self.times, self.names, self.s) for i in r]\n        # for d in x:\n        #    for k in ['ims', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:\n        #        setattr(d, k, getattr(d, k)[0])  # pop out of list\n        return x\n\n    def print(self):\n        \"\"\"Print the results of the `self._run()` function.\"\"\"\n        LOGGER.info(self.__str__())\n\n    def __len__(self):  # override len(results)\n        return self.n\n\n    def __str__(self):  # override print(results)\n        return self._run(pprint=True)  # print results\n\n    def __repr__(self):\n        \"\"\"Returns a printable representation of the object.\"\"\"\n        return f'YOLOv8 {self.__class__} instance\\n' + self.__str__()\n"
  },
  {
    "path": "ultralytics/nn/modules/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .block import (C1, C2, C3, C3TR, DFL, SPP, SPPF, Bottleneck, BottleneckCSP, C2f, C3Ghost, C3x, GhostBottleneck,\n                    HGBlock, HGStem, Proto, RepC3)\nfrom .conv import (CBAM, ChannelAttention, Concat, Conv, ConvTranspose, DWConv, DWConvTranspose2d, Focus, GhostConv,\n                   LightConv, RepConv, SpatialAttention, Concat_dropout)\nfrom .head import Classify, Detect, Pose, RTDETRDecoder, Segment\nfrom .transformer import (AIFI, MLP, DeformableTransformerDecoder, DeformableTransformerDecoderLayer, LayerNorm2d,\n                          MLPBlock, MSDeformAttn, TransformerBlock, TransformerEncoderLayer, TransformerLayer)\n\n__all__ = [\n    'Conv', 'LightConv', 'RepConv', 'DWConv', 'DWConvTranspose2d', 'ConvTranspose', 'Focus', 'GhostConv',\n    'ChannelAttention', 'SpatialAttention', 'CBAM', 'Concat', 'TransformerLayer', 'TransformerBlock', 'MLPBlock',\n    'LayerNorm2d', 'DFL', 'HGBlock', 'HGStem', 'SPP', 'SPPF', 'C1', 'C2', 'C3', 'C2f', 'C3x', 'C3TR', 'C3Ghost',\n    'GhostBottleneck', 'Bottleneck', 'BottleneckCSP', 'Proto', 'Detect', 'Segment', 'Pose', 'Classify',\n    'TransformerEncoderLayer', 'RepC3', 'RTDETRDecoder', 'AIFI', 'DeformableTransformerDecoder',\n    'DeformableTransformerDecoderLayer', 'MSDeformAttn', 'MLP', 'Concat_dropout']\n"
  },
  {
    "path": "ultralytics/nn/modules/block.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nBlock modules\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .conv import Conv, DWConv, GhostConv, LightConv, RepConv\nfrom .transformer import TransformerBlock\n\n__all__ = [\n    'DFL', 'HGBlock', 'HGStem', 'SPP', 'SPPF', 'C1', 'C2', 'C3', 'C2f', 'C3x', 'C3TR', 'C3Ghost', 'GhostBottleneck',\n    'Bottleneck', 'BottleneckCSP', 'Proto', 'RepC3']\n\n\nclass DFL(nn.Module):\n    \"\"\"\n    Integral module of Distribution Focal Loss (DFL).\n    Proposed in Generalized Focal Loss https://ieeexplore.ieee.org/document/9792391\n    \"\"\"\n\n    def __init__(self, c1=16):\n        \"\"\"Initialize a convolutional layer with a given number of input channels.\"\"\"\n        super().__init__()\n        self.conv = nn.Conv2d(c1, 1, 1, bias=False).requires_grad_(False)\n        x = torch.arange(c1, dtype=torch.float)\n        self.conv.weight.data[:] = nn.Parameter(x.view(1, c1, 1, 1))\n        self.c1 = c1\n\n    def forward(self, x):\n        \"\"\"Applies a transformer layer on input tensor 'x' and returns a tensor.\"\"\"\n        b, c, a = x.shape  # batch, channels, anchors\n        return self.conv(x.view(b, 4, self.c1, a).transpose(2, 1).softmax(1)).view(b, 4, a)\n        # return self.conv(x.view(b, self.c1, 4, a).softmax(1)).view(b, 4, a)\n\n\nclass Proto(nn.Module):\n    \"\"\"YOLOv8 mask Proto module for segmentation models.\"\"\"\n\n    def __init__(self, c1, c_=256, c2=32):  # ch_in, number of protos, number of masks\n        super().__init__()\n        self.cv1 = Conv(c1, c_, k=3)\n        self.upsample = nn.ConvTranspose2d(c_, c_, 2, 2, 0, bias=True)  # nn.Upsample(scale_factor=2, mode='nearest')\n        self.cv2 = Conv(c_, c_, k=3)\n        self.cv3 = Conv(c_, c2)\n\n    def forward(self, x):\n        \"\"\"Performs a forward pass through layers using an upsampled input image.\"\"\"\n        return self.cv3(self.cv2(self.upsample(self.cv1(x)))) ######Jiayuan here has a upsampled\n\n\nclass HGStem(nn.Module):\n    \"\"\"StemBlock of PPHGNetV2 with 5 convolutions and one maxpool2d.\n    https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/backbones/hgnet_v2.py\n    \"\"\"\n\n    def __init__(self, c1, cm, c2):\n        super().__init__()\n        self.stem1 = Conv(c1, cm, 3, 2, act=nn.ReLU())\n        self.stem2a = Conv(cm, cm // 2, 2, 1, 0, act=nn.ReLU())\n        self.stem2b = Conv(cm // 2, cm, 2, 1, 0, act=nn.ReLU())\n        self.stem3 = Conv(cm * 2, cm, 3, 2, act=nn.ReLU())\n        self.stem4 = Conv(cm, c2, 1, 1, act=nn.ReLU())\n        self.pool = nn.MaxPool2d(kernel_size=2, stride=1, padding=0, ceil_mode=True)\n\n    def forward(self, x):\n        \"\"\"Forward pass of a PPHGNetV2 backbone layer.\"\"\"\n        x = self.stem1(x)\n        x = F.pad(x, [0, 1, 0, 1])\n        x2 = self.stem2a(x)\n        x2 = F.pad(x2, [0, 1, 0, 1])\n        x2 = self.stem2b(x2)\n        x1 = self.pool(x)\n        x = torch.cat([x1, x2], dim=1)\n        x = self.stem3(x)\n        x = self.stem4(x)\n        return x\n\n\nclass HGBlock(nn.Module):\n    \"\"\"HG_Block of PPHGNetV2 with 2 convolutions and LightConv.\n    https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/backbones/hgnet_v2.py\n    \"\"\"\n\n    def __init__(self, c1, cm, c2, k=3, n=6, lightconv=False, shortcut=False, act=nn.ReLU()):\n        super().__init__()\n        block = LightConv if lightconv else Conv\n        self.m = nn.ModuleList(block(c1 if i == 0 else cm, cm, k=k, act=act) for i in range(n))\n        self.sc = Conv(c1 + n * cm, c2 // 2, 1, 1, act=act)  # squeeze conv\n        self.ec = Conv(c2 // 2, c2, 1, 1, act=act)  # excitation conv\n        self.add = shortcut and c1 == c2\n\n    def forward(self, x):\n        \"\"\"Forward pass of a PPHGNetV2 backbone layer.\"\"\"\n        y = [x]\n        y.extend(m(y[-1]) for m in self.m)\n        y = self.ec(self.sc(torch.cat(y, 1)))\n        return y + x if self.add else y\n\n\nclass SPP(nn.Module):\n    \"\"\"Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729.\"\"\"\n\n    def __init__(self, c1, c2, k=(5, 9, 13)):\n        \"\"\"Initialize the SPP layer with input/output channels and pooling kernel sizes.\"\"\"\n        super().__init__()\n        c_ = c1 // 2  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)\n        self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])\n\n    def forward(self, x):\n        \"\"\"Forward pass of the SPP layer, performing spatial pyramid pooling.\"\"\"\n        x = self.cv1(x)\n        return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))\n\n\nclass SPPF(nn.Module):\n    \"\"\"Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher.\"\"\"\n\n    def __init__(self, c1, c2, k=5):  # equivalent to SPP(k=(5, 9, 13))\n        super().__init__()\n        c_ = c1 // 2  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = Conv(c_ * 4, c2, 1, 1)\n        self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)\n\n    def forward(self, x):\n        \"\"\"Forward pass through Ghost Convolution block.\"\"\"\n        x = self.cv1(x)\n        y1 = self.m(x)\n        y2 = self.m(y1)\n        return self.cv2(torch.cat((x, y1, y2, self.m(y2)), 1))\n\n\nclass C1(nn.Module):\n    \"\"\"CSP Bottleneck with 1 convolution.\"\"\"\n\n    def __init__(self, c1, c2, n=1):  # ch_in, ch_out, number\n        super().__init__()\n        self.cv1 = Conv(c1, c2, 1, 1)\n        self.m = nn.Sequential(*(Conv(c2, c2, 3) for _ in range(n)))\n\n    def forward(self, x):\n        \"\"\"Applies cross-convolutions to input in the C3 module.\"\"\"\n        y = self.cv1(x)\n        return self.m(y) + y\n\n\nclass C2(nn.Module):\n    \"\"\"CSP Bottleneck with 2 convolutions.\"\"\"\n\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion\n        super().__init__()\n        self.c = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, 2 * self.c, 1, 1)\n        self.cv2 = Conv(2 * self.c, c2, 1)  # optional act=FReLU(c2)\n        # self.attention = ChannelAttention(2 * self.c)  # or SpatialAttention()\n        self.m = nn.Sequential(*(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n)))\n\n    def forward(self, x):\n        \"\"\"Forward pass through the CSP bottleneck with 2 convolutions.\"\"\"\n        a, b = self.cv1(x).chunk(2, 1)\n        return self.cv2(torch.cat((self.m(a), b), 1))\n\n\nclass C2f(nn.Module):\n    \"\"\"CSP Bottleneck with 2 convolutions.\"\"\"\n\n    def __init__(self, c1, c2, n=1, shortcut=False, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion\n        super().__init__()\n        self.c = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, 2 * self.c, 1, 1)\n        self.cv2 = Conv((2 + n) * self.c, c2, 1)  # optional act=FReLU(c2)\n        self.m = nn.ModuleList(Bottleneck(self.c, self.c, shortcut, g, k=((3, 3), (3, 3)), e=1.0) for _ in range(n))\n\n    def forward(self, x):\n        \"\"\"Forward pass through C2f layer.\"\"\"\n        y = list(self.cv1(x).chunk(2, 1))\n        y.extend(m(y[-1]) for m in self.m)\n        return self.cv2(torch.cat(y, 1))\n\n    def forward_split(self, x):\n        \"\"\"Forward pass using split() instead of chunk().\"\"\"\n        y = list(self.cv1(x).split((self.c, self.c), 1))\n        y.extend(m(y[-1]) for m in self.m)\n        return self.cv2(torch.cat(y, 1))\n\n\nclass C3(nn.Module):\n    \"\"\"CSP Bottleneck with 3 convolutions.\"\"\"\n\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = Conv(c1, c_, 1, 1)\n        self.cv3 = Conv(2 * c_, c2, 1)  # optional act=FReLU(c2)\n        self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, k=((1, 1), (3, 3)), e=1.0) for _ in range(n)))\n\n    def forward(self, x):\n        \"\"\"Forward pass through the CSP bottleneck with 2 convolutions.\"\"\"\n        return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), 1))\n\n\nclass C3x(C3):\n    \"\"\"C3 module with cross-convolutions.\"\"\"\n\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):\n        \"\"\"Initialize C3TR instance and set default parameters.\"\"\"\n        super().__init__(c1, c2, n, shortcut, g, e)\n        self.c_ = int(c2 * e)\n        self.m = nn.Sequential(*(Bottleneck(self.c_, self.c_, shortcut, g, k=((1, 3), (3, 1)), e=1) for _ in range(n)))\n\n\nclass RepC3(nn.Module):\n    \"\"\"Rep C3.\"\"\"\n\n    def __init__(self, c1, c2, n=3, e=1.0):\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c2, 1, 1)\n        self.cv2 = Conv(c1, c2, 1, 1)\n        self.m = nn.Sequential(*[RepConv(c_, c_) for _ in range(n)])\n        self.cv3 = Conv(c_, c2, 1, 1) if c_ != c2 else nn.Identity()\n\n    def forward(self, x):\n        \"\"\"Forward pass of RT-DETR neck layer.\"\"\"\n        return self.cv3(self.m(self.cv1(x)) + self.cv2(x))\n\n\nclass C3TR(C3):\n    \"\"\"C3 module with TransformerBlock().\"\"\"\n\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):\n        \"\"\"Initialize C3Ghost module with GhostBottleneck().\"\"\"\n        super().__init__(c1, c2, n, shortcut, g, e)\n        c_ = int(c2 * e)\n        self.m = TransformerBlock(c_, c_, 4, n)\n\n\nclass C3Ghost(C3):\n    \"\"\"C3 module with GhostBottleneck().\"\"\"\n\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):\n        \"\"\"Initialize 'SPP' module with various pooling sizes for spatial pyramid pooling.\"\"\"\n        super().__init__(c1, c2, n, shortcut, g, e)\n        c_ = int(c2 * e)  # hidden channels\n        self.m = nn.Sequential(*(GhostBottleneck(c_, c_) for _ in range(n)))\n\n\nclass GhostBottleneck(nn.Module):\n    \"\"\"Ghost Bottleneck https://github.com/huawei-noah/ghostnet.\"\"\"\n\n    def __init__(self, c1, c2, k=3, s=1):  # ch_in, ch_out, kernel, stride\n        super().__init__()\n        c_ = c2 // 2\n        self.conv = nn.Sequential(\n            GhostConv(c1, c_, 1, 1),  # pw\n            DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(),  # dw\n            GhostConv(c_, c2, 1, 1, act=False))  # pw-linear\n        self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False), Conv(c1, c2, 1, 1,\n                                                                            act=False)) if s == 2 else nn.Identity()\n\n    def forward(self, x):\n        \"\"\"Applies skip connection and concatenation to input tensor.\"\"\"\n        return self.conv(x) + self.shortcut(x)\n\n\nclass Bottleneck(nn.Module):\n    \"\"\"Standard bottleneck.\"\"\"\n\n    def __init__(self, c1, c2, shortcut=True, g=1, k=(3, 3), e=0.5):  # ch_in, ch_out, shortcut, groups, kernels, expand\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c_, k[0], 1)\n        self.cv2 = Conv(c_, c2, k[1], 1, g=g)\n        self.add = shortcut and c1 == c2\n\n    def forward(self, x):\n        \"\"\"'forward()' applies the YOLOv5 FPN to input data.\"\"\"\n        return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))\n\n\nclass BottleneckCSP(nn.Module):\n    \"\"\"CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks.\"\"\"\n\n    def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):  # ch_in, ch_out, number, shortcut, groups, expansion\n        super().__init__()\n        c_ = int(c2 * e)  # hidden channels\n        self.cv1 = Conv(c1, c_, 1, 1)\n        self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)\n        self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)\n        self.cv4 = Conv(2 * c_, c2, 1, 1)\n        self.bn = nn.BatchNorm2d(2 * c_)  # applied to cat(cv2, cv3)\n        self.act = nn.SiLU()\n        self.m = nn.Sequential(*(Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)))\n\n    def forward(self, x):\n        \"\"\"Applies a CSP bottleneck with 3 convolutions.\"\"\"\n        y1 = self.cv3(self.m(self.cv1(x)))\n        y2 = self.cv2(x)\n        return self.cv4(self.act(self.bn(torch.cat((y1, y2), 1))))\n"
  },
  {
    "path": "ultralytics/nn/modules/conv.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nConvolution modules\n\"\"\"\n\nimport math\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\n__all__ = [\n    'Conv', 'LightConv', 'DWConv', 'DWConvTranspose2d', 'ConvTranspose', 'Focus', 'GhostConv', 'ChannelAttention',\n    'SpatialAttention', 'CBAM', 'Concat', 'RepConv','Concat_dropout']\n\n\ndef autopad(k, p=None, d=1):  # kernel, padding, dilation\n    \"\"\"Pad to 'same' shape outputs.\"\"\"\n    if d > 1:\n        k = d * (k - 1) + 1 if isinstance(k, int) else [d * (x - 1) + 1 for x in k]  # actual kernel-size\n    if p is None:\n        p = k // 2 if isinstance(k, int) else [x // 2 for x in k]  # auto-pad\n    return p\n\n\nclass Conv(nn.Module):\n    \"\"\"Standard convolution with args(ch_in, ch_out, kernel, stride, padding, groups, dilation, activation).\"\"\"\n    default_act = nn.SiLU()  # default activation\n\n    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, d=1, act=True):\n        \"\"\"Initialize Conv layer with given arguments including activation.\"\"\"\n        super().__init__()\n        self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p, d), groups=g, dilation=d, bias=False)\n        self.bn = nn.BatchNorm2d(c2)\n        self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()\n\n    def forward(self, x):\n        \"\"\"Apply convolution, batch normalization and activation to input tensor.\"\"\"\n        return self.act(self.bn(self.conv(x)))\n\n    def forward_fuse(self, x):\n        \"\"\"Perform transposed convolution of 2D data.\"\"\"\n        return self.act(self.conv(x))\n\n\nclass LightConv(nn.Module):\n    \"\"\"Light convolution with args(ch_in, ch_out, kernel).\n    https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/backbones/hgnet_v2.py\n    \"\"\"\n\n    def __init__(self, c1, c2, k=1, act=nn.ReLU()):\n        \"\"\"Initialize Conv layer with given arguments including activation.\"\"\"\n        super().__init__()\n        self.conv1 = Conv(c1, c2, 1, act=False)\n        self.conv2 = DWConv(c2, c2, k, act=act)\n\n    def forward(self, x):\n        \"\"\"Apply 2 convolutions to input tensor.\"\"\"\n        return self.conv2(self.conv1(x))\n\n\nclass DWConv(Conv):\n    \"\"\"Depth-wise convolution.\"\"\"\n\n    def __init__(self, c1, c2, k=1, s=1, d=1, act=True):  # ch_in, ch_out, kernel, stride, dilation, activation\n        super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), d=d, act=act)\n\n\nclass DWConvTranspose2d(nn.ConvTranspose2d):\n    \"\"\"Depth-wise transpose convolution.\"\"\"\n\n    def __init__(self, c1, c2, k=1, s=1, p1=0, p2=0):  # ch_in, ch_out, kernel, stride, padding, padding_out\n        super().__init__(c1, c2, k, s, p1, p2, groups=math.gcd(c1, c2))\n\n\nclass ConvTranspose(nn.Module):\n    \"\"\"Convolution transpose 2d layer.\"\"\"\n    default_act = nn.SiLU()  # default activation\n\n    def __init__(self, c1, c2, k=2, s=2, p=0, bn=True, act=True):\n        \"\"\"Initialize ConvTranspose2d layer with batch normalization and activation function.\"\"\"\n        super().__init__()\n        self.conv_transpose = nn.ConvTranspose2d(c1, c2, k, s, p, bias=not bn)\n        self.bn = nn.BatchNorm2d(c2) if bn else nn.Identity()\n        self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()\n\n    def forward(self, x):\n        \"\"\"Applies transposed convolutions, batch normalization and activation to input.\"\"\"\n        return self.act(self.bn(self.conv_transpose(x)))\n\n    def forward_fuse(self, x):\n        \"\"\"Applies activation and convolution transpose operation to input.\"\"\"\n        return self.act(self.conv_transpose(x))\n\n\nclass Focus(nn.Module):\n    \"\"\"Focus wh information into c-space.\"\"\"\n\n    def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True):  # ch_in, ch_out, kernel, stride, padding, groups\n        super().__init__()\n        self.conv = Conv(c1 * 4, c2, k, s, p, g, act=act)\n        # self.contract = Contract(gain=2)\n\n    def forward(self, x):  # x(b,c,w,h) -> y(b,4c,w/2,h/2)\n        return self.conv(torch.cat((x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]), 1))\n        # return self.conv(self.contract(x))\n\n\nclass GhostConv(nn.Module):\n    \"\"\"Ghost Convolution https://github.com/huawei-noah/ghostnet.\"\"\"\n\n    def __init__(self, c1, c2, k=1, s=1, g=1, act=True):  # ch_in, ch_out, kernel, stride, groups\n        super().__init__()\n        c_ = c2 // 2  # hidden channels\n        self.cv1 = Conv(c1, c_, k, s, None, g, act=act)\n        self.cv2 = Conv(c_, c_, 5, 1, None, c_, act=act)\n\n    def forward(self, x):\n        \"\"\"Forward propagation through a Ghost Bottleneck layer with skip connection.\"\"\"\n        y = self.cv1(x)\n        return torch.cat((y, self.cv2(y)), 1)\n\n\nclass RepConv(nn.Module):\n    \"\"\"RepConv is a basic rep-style block, including training and deploy status\n    This code is based on https://github.com/DingXiaoH/RepVGG/blob/main/repvgg.py\n    \"\"\"\n    default_act = nn.SiLU()  # default activation\n\n    def __init__(self, c1, c2, k=3, s=1, p=1, g=1, d=1, act=True, bn=False, deploy=False):\n        super().__init__()\n        assert k == 3 and p == 1\n        self.g = g\n        self.c1 = c1\n        self.c2 = c2\n        self.act = self.default_act if act is True else act if isinstance(act, nn.Module) else nn.Identity()\n\n        self.bn = nn.BatchNorm2d(num_features=c1) if bn and c2 == c1 and s == 1 else None\n        self.conv1 = Conv(c1, c2, k, s, p=p, g=g, act=False)\n        self.conv2 = Conv(c1, c2, 1, s, p=(p - k // 2), g=g, act=False)\n\n    def forward_fuse(self, x):\n        \"\"\"Forward process\"\"\"\n        return self.act(self.conv(x))\n\n    def forward(self, x):\n        \"\"\"Forward process\"\"\"\n        id_out = 0 if self.bn is None else self.bn(x)\n        return self.act(self.conv1(x) + self.conv2(x) + id_out)\n\n    def get_equivalent_kernel_bias(self):\n        kernel3x3, bias3x3 = self._fuse_bn_tensor(self.conv1)\n        kernel1x1, bias1x1 = self._fuse_bn_tensor(self.conv2)\n        kernelid, biasid = self._fuse_bn_tensor(self.bn)\n        return kernel3x3 + self._pad_1x1_to_3x3_tensor(kernel1x1) + kernelid, bias3x3 + bias1x1 + biasid\n\n    def _avg_to_3x3_tensor(self, avgp):\n        channels = self.c1\n        groups = self.g\n        kernel_size = avgp.kernel_size\n        input_dim = channels // groups\n        k = torch.zeros((channels, input_dim, kernel_size, kernel_size))\n        k[np.arange(channels), np.tile(np.arange(input_dim), groups), :, :] = 1.0 / kernel_size ** 2\n        return k\n\n    def _pad_1x1_to_3x3_tensor(self, kernel1x1):\n        if kernel1x1 is None:\n            return 0\n        else:\n            return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1])\n\n    def _fuse_bn_tensor(self, branch):\n        if branch is None:\n            return 0, 0\n        if isinstance(branch, Conv):\n            kernel = branch.conv.weight\n            running_mean = branch.bn.running_mean\n            running_var = branch.bn.running_var\n            gamma = branch.bn.weight\n            beta = branch.bn.bias\n            eps = branch.bn.eps\n        elif isinstance(branch, nn.BatchNorm2d):\n            if not hasattr(self, 'id_tensor'):\n                input_dim = self.c1 // self.g\n                kernel_value = np.zeros((self.c1, input_dim, 3, 3), dtype=np.float32)\n                for i in range(self.c1):\n                    kernel_value[i, i % input_dim, 1, 1] = 1\n                self.id_tensor = torch.from_numpy(kernel_value).to(branch.weight.device)\n            kernel = self.id_tensor\n            running_mean = branch.running_mean\n            running_var = branch.running_var\n            gamma = branch.weight\n            beta = branch.bias\n            eps = branch.eps\n        std = (running_var + eps).sqrt()\n        t = (gamma / std).reshape(-1, 1, 1, 1)\n        return kernel * t, beta - running_mean * gamma / std\n\n    def fuse_convs(self):\n        if hasattr(self, 'conv'):\n            return\n        kernel, bias = self.get_equivalent_kernel_bias()\n        self.conv = nn.Conv2d(in_channels=self.conv1.conv.in_channels,\n                              out_channels=self.conv1.conv.out_channels,\n                              kernel_size=self.conv1.conv.kernel_size,\n                              stride=self.conv1.conv.stride,\n                              padding=self.conv1.conv.padding,\n                              dilation=self.conv1.conv.dilation,\n                              groups=self.conv1.conv.groups,\n                              bias=True).requires_grad_(False)\n        self.conv.weight.data = kernel\n        self.conv.bias.data = bias\n        for para in self.parameters():\n            para.detach_()\n        self.__delattr__('conv1')\n        self.__delattr__('conv2')\n        if hasattr(self, 'nm'):\n            self.__delattr__('nm')\n        if hasattr(self, 'bn'):\n            self.__delattr__('bn')\n        if hasattr(self, 'id_tensor'):\n            self.__delattr__('id_tensor')\n\n\nclass ChannelAttention(nn.Module):\n    \"\"\"Channel-attention module https://github.com/open-mmlab/mmdetection/tree/v3.0.0rc1/configs/rtmdet.\"\"\"\n\n    def __init__(self, channels: int) -> None:\n        super().__init__()\n        self.pool = nn.AdaptiveAvgPool2d(1)\n        self.fc = nn.Conv2d(channels, channels, 1, 1, 0, bias=True)\n        self.act = nn.Sigmoid()\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        return x * self.act(self.fc(self.pool(x)))\n\n\nclass SpatialAttention(nn.Module):\n    \"\"\"Spatial-attention module.\"\"\"\n\n    def __init__(self, kernel_size=7):\n        \"\"\"Initialize Spatial-attention module with kernel size argument.\"\"\"\n        super().__init__()\n        assert kernel_size in (3, 7), 'kernel size must be 3 or 7'\n        padding = 3 if kernel_size == 7 else 1\n        self.cv1 = nn.Conv2d(2, 1, kernel_size, padding=padding, bias=False)\n        self.act = nn.Sigmoid()\n\n    def forward(self, x):\n        \"\"\"Apply channel and spatial attention on input for feature recalibration.\"\"\"\n        return x * self.act(self.cv1(torch.cat([torch.mean(x, 1, keepdim=True), torch.max(x, 1, keepdim=True)[0]], 1)))\n\n\nclass CBAM(nn.Module):\n    \"\"\"Convolutional Block Attention Module.\"\"\"\n\n    def __init__(self, c1, kernel_size=7):  # ch_in, kernels\n        super().__init__()\n        self.channel_attention = ChannelAttention(c1)\n        self.spatial_attention = SpatialAttention(kernel_size)\n\n    def forward(self, x):\n        \"\"\"Applies the forward pass through C1 module.\"\"\"\n        return self.spatial_attention(self.channel_attention(x))\n\n\nclass Concat(nn.Module):\n    \"\"\"Concatenate a list of tensors along dimension.\"\"\"\n\n    def __init__(self, dimension=1):\n        \"\"\"Concatenates a list of tensors along a specified dimension.\"\"\"\n        super().__init__()\n        self.d = dimension\n\n    def forward(self, x):\n        \"\"\"Forward pass for the YOLOv8 mask Proto module.\"\"\"\n        return torch.cat(x, self.d)\n\n\n###### Jiayuan learnable dropout in concat\nclass Concat_dropout(nn.Module):\n    \"\"\"Concatenate a list of tensors along dimension.\"\"\"\n    def __init__(self, dimension=1, ch=None):\n        \"\"\"Concatenates a list of tensors along a specified dimension.\"\"\"\n        super().__init__()\n        self.d = dimension\n        self.weight = nn.Parameter(torch.tensor([5.0]))\n\n        self.conv = nn.Conv2d(sum(ch),\n                               ch[0],\n                               kernel_size=1,\n                               stride=1)\n\n    def forward(self, x):\n        \"\"\"Forward pass for the YOLOv8 mask Proto module.\"\"\"\n        if torch.sigmoid(self.weight) > 0.5:\n            concatenated = torch.cat(x, self.d)\n            return self.conv(concatenated)\n        else:\n            return x[0]\n############\n\n"
  },
  {
    "path": "ultralytics/nn/modules/head.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nModel head modules\n\"\"\"\n\nimport math\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn.init import constant_, xavier_uniform_\n\nfrom ultralytics.yolo.utils.tal import dist2bbox, make_anchors\n\nfrom .block import DFL, Proto\nfrom .conv import Conv\nfrom .transformer import MLP, DeformableTransformerDecoder, DeformableTransformerDecoderLayer\nfrom .utils import bias_init_with_prob, linear_init_\n\n__all__ = ['Detect', 'Segment', 'Pose', 'Classify', 'RTDETRDecoder']\n\n\nclass Detect(nn.Module):\n    \"\"\"YOLOv8 Detect head for detection models.\"\"\"\n    dynamic = False  # force grid reconstruction\n    export = False  # export mode\n    shape = None\n    anchors = torch.empty(0)  # init\n    strides = torch.empty(0)  # init\n\n    def __init__(self, nc=80, ch=()):  # detection layer\n        super().__init__()\n        self.nc = nc  # number of classes\n        self.nl = len(ch)  # number of detection layers\n        self.reg_max = 16  # DFL channels (ch[0] // 16 to scale 4/8/12/16/20 for n/s/m/l/x)\n        self.no = nc + self.reg_max * 4  # number of outputs per anchor\n        self.stride = torch.zeros(self.nl)  # strides computed during build\n        c2, c3 = max((16, ch[0] // 4, self.reg_max * 4)), max(ch[0], self.nc)  # channels\n        self.cv2 = nn.ModuleList(\n            nn.Sequential(Conv(x, c2, 3), Conv(c2, c2, 3), nn.Conv2d(c2, 4 * self.reg_max, 1)) for x in ch)\n        self.cv3 = nn.ModuleList(nn.Sequential(Conv(x, c3, 3), Conv(c3, c3, 3), nn.Conv2d(c3, self.nc, 1)) for x in ch)\n        self.dfl = DFL(self.reg_max) if self.reg_max > 1 else nn.Identity()\n\n    def forward(self, x):\n        \"\"\"Concatenates and returns predicted bounding boxes and class probabilities.\"\"\"\n        shape = x[0].shape  # BCHW\n        for i in range(self.nl):\n            x[i] = torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1)\n        if self.training:\n            return x\n        elif self.dynamic or self.shape != shape:\n            self.anchors, self.strides = (x.transpose(0, 1) for x in make_anchors(x, self.stride, 0.5))\n            self.shape = shape\n\n        x_cat = torch.cat([xi.view(shape[0], self.no, -1) for xi in x], 2)\n        if self.export and self.format in ('saved_model', 'pb', 'tflite', 'edgetpu', 'tfjs'):  # avoid TF FlexSplitV ops\n            box = x_cat[:, :self.reg_max * 4]\n            cls = x_cat[:, self.reg_max * 4:]\n        else:\n            box, cls = x_cat.split((self.reg_max * 4, self.nc), 1)\n        dbox = dist2bbox(self.dfl(box), self.anchors.unsqueeze(0), xywh=True, dim=1) * self.strides\n        y = torch.cat((dbox, cls.sigmoid()), 1)\n        return y if self.export else (y, x)\n\n    def bias_init(self):\n        \"\"\"Initialize Detect() biases, WARNING: requires stride availability.\"\"\"\n        m = self  # self.model[-1]  # Detect() module\n        # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1\n        # ncf = math.log(0.6 / (m.nc - 0.999999)) if cf is None else torch.log(cf / cf.sum())  # nominal class frequency\n        for a, b, s in zip(m.cv2, m.cv3, m.stride):  # from\n            a[-1].bias.data[:] = 1.0  # box\n            b[-1].bias.data[:m.nc] = math.log(5 / m.nc / (640 / s) ** 2)  # cls (.01 objects, 80 classes, 640 img)\n\n\nclass Segment(Detect):\n    \"\"\"YOLOv8 Segment head for segmentation models.\"\"\"\n\n    def __init__(self, nc=80, nm=32, npr=256, ch=()):\n        super().__init__(nc, ch)\n        ###### Jiayuan changed self.nm to self.nc\n        self.npr = 32  # intermediate convolutional feature dimension\n        self.cv1 = Conv(ch[0], self.npr, k=3)\n        self.upsample = nn.ConvTranspose2d(self.npr, self.npr//2, 2, 2, 0, bias=True)  # nn.Upsample(scale_factor=2, mode='nearest')\n        self.cv2 = Conv(self.npr//2, self.npr//4, k=3)\n        self.cv3 = Conv(self.npr//4, self.nc+1) ###### self.nc+1 means add the background\n        self.sigmoid = nn.Sigmoid()\n        # self.detect = Detect.forward\n        #\n        # c4 = max(ch[0] // 4, self.nm)\n        # self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.nm, 1)) for x in ch)\n\n    def forward(self, x):\n        \"\"\"Return model outputs and mask coefficients if training, otherwise return outputs and mask coefficients.\"\"\"\n        p = self.cv3(self.cv2(self.upsample(self.cv1(x[0])))) # mask protos\n        if self.training:\n            return p\n        return p\n        # bs = p.shape[0]  # batch size\n        #\n        # mc = torch.cat([self.cv4[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2)  # mask coefficients\n        # x = self.detect(self, x)\n        # if self.training:\n        #     return x, mc, p\n        # return (torch.cat([x, mc], 1), p) if self.export else (torch.cat([x[0], mc], 1), (x[1], mc, p))\n\n\nclass Pose(Detect):\n    \"\"\"YOLOv8 Pose head for keypoints models.\"\"\"\n\n    def __init__(self, nc=80, kpt_shape=(17, 3), ch=()):\n        \"\"\"Initialize YOLO network with default parameters and Convolutional Layers.\"\"\"\n        super().__init__(nc, ch)\n        self.kpt_shape = kpt_shape  # number of keypoints, number of dims (2 for x,y or 3 for x,y,visible)\n        self.nk = kpt_shape[0] * kpt_shape[1]  # number of keypoints total\n        self.detect = Detect.forward\n\n        c4 = max(ch[0] // 4, self.nk)\n        self.cv4 = nn.ModuleList(nn.Sequential(Conv(x, c4, 3), Conv(c4, c4, 3), nn.Conv2d(c4, self.nk, 1)) for x in ch)\n\n    def forward(self, x):\n        \"\"\"Perform forward pass through YOLO model and return predictions.\"\"\"\n        bs = x[0].shape[0]  # batch size\n        kpt = torch.cat([self.cv4[i](x[i]).view(bs, self.nk, -1) for i in range(self.nl)], -1)  # (bs, 17*3, h*w)\n        x = self.detect(self, x)\n        if self.training:\n            return x, kpt\n        pred_kpt = self.kpts_decode(bs, kpt)\n        return torch.cat([x, pred_kpt], 1) if self.export else (torch.cat([x[0], pred_kpt], 1), (x[1], kpt))\n\n    def kpts_decode(self, bs, kpts):\n        \"\"\"Decodes keypoints.\"\"\"\n        ndim = self.kpt_shape[1]\n        if self.export:  # required for TFLite export to avoid 'PLACEHOLDER_FOR_GREATER_OP_CODES' bug\n            y = kpts.view(bs, *self.kpt_shape, -1)\n            a = (y[:, :, :2] * 2.0 + (self.anchors - 0.5)) * self.strides\n            if ndim == 3:\n                a = torch.cat((a, y[:, :, 1:2].sigmoid()), 2)\n            return a.view(bs, self.nk, -1)\n        else:\n            y = kpts.clone()\n            if ndim == 3:\n                y[:, 2::3].sigmoid_()  # inplace sigmoid\n            y[:, 0::ndim] = (y[:, 0::ndim] * 2.0 + (self.anchors[0] - 0.5)) * self.strides\n            y[:, 1::ndim] = (y[:, 1::ndim] * 2.0 + (self.anchors[1] - 0.5)) * self.strides\n            return y\n\n\nclass Classify(nn.Module):\n    \"\"\"YOLOv8 classification head, i.e. x(b,c1,20,20) to x(b,c2).\"\"\"\n\n    def __init__(self, c1, c2, k=1, s=1, p=None, g=1):  # ch_in, ch_out, kernel, stride, padding, groups\n        super().__init__()\n        c_ = 1280  # efficientnet_b0 size\n        self.conv = Conv(c1, c_, k, s, p, g)\n        self.pool = nn.AdaptiveAvgPool2d(1)  # to x(b,c_,1,1)\n        self.drop = nn.Dropout(p=0.0, inplace=True)\n        self.linear = nn.Linear(c_, c2)  # to x(b,c2)\n\n    def forward(self, x):\n        \"\"\"Performs a forward pass of the YOLO model on input image data.\"\"\"\n        if isinstance(x, list):\n            x = torch.cat(x, 1)\n        x = self.linear(self.drop(self.pool(self.conv(x)).flatten(1)))\n        return x if self.training else x.softmax(1)\n\n\nclass RTDETRDecoder(nn.Module):\n\n    def __init__(\n            self,\n            nc=80,\n            ch=(512, 1024, 2048),\n            hidden_dim=256,\n            num_queries=300,\n            strides=(8, 16, 32),  # TODO\n            nl=3,\n            num_decoder_points=4,\n            nhead=8,\n            num_decoder_layers=6,\n            dim_feedforward=1024,\n            dropout=0.,\n            act=nn.ReLU(),\n            eval_idx=-1,\n            # training args\n            num_denoising=100,\n            label_noise_ratio=0.5,\n            box_noise_scale=1.0,\n            learnt_init_query=False):\n        super().__init__()\n        assert len(ch) <= nl\n        assert len(strides) == len(ch)\n        for _ in range(nl - len(strides)):\n            strides.append(strides[-1] * 2)\n\n        self.hidden_dim = hidden_dim\n        self.nhead = nhead\n        self.feat_strides = strides\n        self.nl = nl\n        self.nc = nc\n        self.num_queries = num_queries\n        self.num_decoder_layers = num_decoder_layers\n\n        # backbone feature projection\n        self._build_input_proj_layer(ch)\n\n        # Transformer module\n        decoder_layer = DeformableTransformerDecoderLayer(hidden_dim, nhead, dim_feedforward, dropout, act, nl,\n                                                          num_decoder_points)\n        self.decoder = DeformableTransformerDecoder(hidden_dim, decoder_layer, num_decoder_layers, eval_idx)\n\n        # denoising part\n        self.denoising_class_embed = nn.Embedding(nc, hidden_dim)\n        self.num_denoising = num_denoising\n        self.label_noise_ratio = label_noise_ratio\n        self.box_noise_scale = box_noise_scale\n\n        # decoder embedding\n        self.learnt_init_query = learnt_init_query\n        if learnt_init_query:\n            self.tgt_embed = nn.Embedding(num_queries, hidden_dim)\n        self.query_pos_head = MLP(4, 2 * hidden_dim, hidden_dim, num_layers=2)\n\n        # encoder head\n        self.enc_output = nn.Sequential(nn.Linear(hidden_dim, hidden_dim), nn.LayerNorm(hidden_dim))\n        self.enc_score_head = nn.Linear(hidden_dim, nc)\n        self.enc_bbox_head = MLP(hidden_dim, hidden_dim, 4, num_layers=3)\n\n        # decoder head\n        self.dec_score_head = nn.ModuleList([nn.Linear(hidden_dim, nc) for _ in range(num_decoder_layers)])\n        self.dec_bbox_head = nn.ModuleList([\n            MLP(hidden_dim, hidden_dim, 4, num_layers=3) for _ in range(num_decoder_layers)])\n\n        self._reset_parameters()\n\n    def forward(self, feats, gt_meta=None):\n        # input projection and embedding\n        memory, spatial_shapes, _ = self._get_encoder_input(feats)\n\n        # prepare denoising training\n        if self.training:\n            raise NotImplementedError\n            # denoising_class, denoising_bbox_unact, attn_mask, dn_meta = \\\n            #     get_contrastive_denoising_training_group(gt_meta,\n            #                                 self.num_classes,\n            #                                 self.num_queries,\n            #                                 self.denoising_class_embed.weight,\n            #                                 self.num_denoising,\n            #                                 self.label_noise_ratio,\n            #                                 self.box_noise_scale)\n        else:\n            denoising_class, denoising_bbox_unact, attn_mask = None, None, None\n\n        target, init_ref_points_unact, enc_topk_bboxes, enc_topk_logits = \\\n            self._get_decoder_input(memory, spatial_shapes, denoising_class, denoising_bbox_unact)\n\n        # decoder\n        out_bboxes, out_logits = self.decoder(target,\n                                              init_ref_points_unact,\n                                              memory,\n                                              spatial_shapes,\n                                              self.dec_bbox_head,\n                                              self.dec_score_head,\n                                              self.query_pos_head,\n                                              attn_mask=attn_mask)\n        if not self.training:\n            out_logits = out_logits.sigmoid_()\n        return out_bboxes, out_logits  # enc_topk_bboxes, enc_topk_logits, dn_meta\n\n    def _reset_parameters(self):\n        # class and bbox head init\n        bias_cls = bias_init_with_prob(0.01)\n        linear_init_(self.enc_score_head)\n        constant_(self.enc_score_head.bias, bias_cls)\n        constant_(self.enc_bbox_head.layers[-1].weight, 0.)\n        constant_(self.enc_bbox_head.layers[-1].bias, 0.)\n        for cls_, reg_ in zip(self.dec_score_head, self.dec_bbox_head):\n            linear_init_(cls_)\n            constant_(cls_.bias, bias_cls)\n            constant_(reg_.layers[-1].weight, 0.)\n            constant_(reg_.layers[-1].bias, 0.)\n\n        linear_init_(self.enc_output[0])\n        xavier_uniform_(self.enc_output[0].weight)\n        if self.learnt_init_query:\n            xavier_uniform_(self.tgt_embed.weight)\n        xavier_uniform_(self.query_pos_head.layers[0].weight)\n        xavier_uniform_(self.query_pos_head.layers[1].weight)\n        for layer in self.input_proj:\n            xavier_uniform_(layer[0].weight)\n\n    def _build_input_proj_layer(self, ch):\n        self.input_proj = nn.ModuleList()\n        for in_channels in ch:\n            self.input_proj.append(\n                nn.Sequential(nn.Conv2d(in_channels, self.hidden_dim, kernel_size=1, bias=False),\n                              nn.BatchNorm2d(self.hidden_dim)))\n        in_channels = ch[-1]\n        for _ in range(self.nl - len(ch)):\n            self.input_proj.append(\n                nn.Sequential(nn.Conv2D(in_channels, self.hidden_dim, kernel_size=3, stride=2, padding=1, bias=False),\n                              nn.BatchNorm2d(self.hidden_dim)))\n            in_channels = self.hidden_dim\n\n    def _generate_anchors(self, spatial_shapes, grid_size=0.05, dtype=torch.float32, device='cpu', eps=1e-2):\n        anchors = []\n        for lvl, (h, w) in enumerate(spatial_shapes):\n            grid_y, grid_x = torch.meshgrid(torch.arange(end=h, dtype=torch.float32),\n                                            torch.arange(end=w, dtype=torch.float32),\n                                            indexing='ij')\n            grid_xy = torch.stack([grid_x, grid_y], -1)\n\n            valid_WH = torch.tensor([h, w]).to(torch.float32)\n            grid_xy = (grid_xy.unsqueeze(0) + 0.5) / valid_WH\n            wh = torch.ones_like(grid_xy) * grid_size * (2.0 ** lvl)\n            anchors.append(torch.concat([grid_xy, wh], -1).reshape([-1, h * w, 4]))\n\n        anchors = torch.concat(anchors, 1)\n        valid_mask = ((anchors > eps) * (anchors < 1 - eps)).all(-1, keepdim=True)\n        anchors = torch.log(anchors / (1 - anchors))\n        anchors = torch.where(valid_mask, anchors, torch.inf)\n        return anchors.to(device=device, dtype=dtype), valid_mask.to(device=device)\n\n    def _get_encoder_input(self, feats):\n        # get projection features\n        proj_feats = [self.input_proj[i](feat) for i, feat in enumerate(feats)]\n        if self.nl > len(proj_feats):\n            len_srcs = len(proj_feats)\n            for i in range(len_srcs, self.nl):\n                if i == len_srcs:\n                    proj_feats.append(self.input_proj[i](feats[-1]))\n                else:\n                    proj_feats.append(self.input_proj[i](proj_feats[-1]))\n\n        # get encoder inputs\n        feat_flatten = []\n        spatial_shapes = []\n        level_start_index = [0]\n        for feat in proj_feats:\n            _, _, h, w = feat.shape\n            # [b, c, h, w] -> [b, h*w, c]\n            feat_flatten.append(feat.flatten(2).permute(0, 2, 1))\n            # [nl, 2]\n            spatial_shapes.append([h, w])\n            # [l], start index of each level\n            level_start_index.append(h * w + level_start_index[-1])\n\n        # [b, l, c]\n        feat_flatten = torch.concat(feat_flatten, 1)\n        level_start_index.pop()\n        return feat_flatten, spatial_shapes, level_start_index\n\n    def _get_decoder_input(self, memory, spatial_shapes, denoising_class=None, denoising_bbox_unact=None):\n        bs, _, _ = memory.shape\n        # prepare input for decoder\n        anchors, valid_mask = self._generate_anchors(spatial_shapes, dtype=memory.dtype, device=memory.device)\n        memory = torch.where(valid_mask, memory, 0)\n        output_memory = self.enc_output(memory)\n\n        enc_outputs_class = self.enc_score_head(output_memory)  # (bs, h*w, nc)\n        enc_outputs_coord_unact = self.enc_bbox_head(output_memory) + anchors  # (bs, h*w, 4)\n\n        # (bs, topk)\n        _, topk_ind = torch.topk(enc_outputs_class.max(-1).values, self.num_queries, dim=1)\n        # extract region proposal boxes\n        # (bs, topk_ind)\n        batch_ind = torch.arange(end=bs, dtype=topk_ind.dtype).unsqueeze(-1).repeat(1, self.num_queries).view(-1)\n        topk_ind = topk_ind.view(-1)\n\n        # Unsigmoided\n        reference_points_unact = enc_outputs_coord_unact[batch_ind, topk_ind].view(bs, self.num_queries, -1)\n\n        enc_topk_bboxes = torch.sigmoid(reference_points_unact)\n        if denoising_bbox_unact is not None:\n            reference_points_unact = torch.concat([denoising_bbox_unact, reference_points_unact], 1)\n        if self.training:\n            reference_points_unact = reference_points_unact.detach()\n        enc_topk_logits = enc_outputs_class[batch_ind, topk_ind].view(bs, self.num_queries, -1)\n\n        # extract region features\n        if self.learnt_init_query:\n            target = self.tgt_embed.weight.unsqueeze(0).repeat(bs, 1, 1)\n        else:\n            target = output_memory[batch_ind, topk_ind].view(bs, self.num_queries, -1)\n            if self.training:\n                target = target.detach()\n        if denoising_class is not None:\n            target = torch.concat([denoising_class, target], 1)\n\n        return target, reference_points_unact, enc_topk_bboxes, enc_topk_logits\n"
  },
  {
    "path": "ultralytics/nn/modules/transformer.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nTransformer modules\n\"\"\"\n\nimport math\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.init import constant_, xavier_uniform_\n\nfrom .conv import Conv\nfrom .utils import _get_clones, inverse_sigmoid, multi_scale_deformable_attn_pytorch\n\n__all__ = [\n    'TransformerEncoderLayer', 'TransformerLayer', 'TransformerBlock', 'MLPBlock', 'LayerNorm2d', 'AIFI',\n    'DeformableTransformerDecoder', 'DeformableTransformerDecoderLayer', 'MSDeformAttn', 'MLP']\n\n\nclass TransformerEncoderLayer(nn.Module):\n    \"\"\"Transformer Encoder.\"\"\"\n\n    def __init__(self, c1, cm=2048, num_heads=8, dropout=0.0, act=nn.GELU(), normalize_before=False):\n        super().__init__()\n        self.ma = nn.MultiheadAttention(c1, num_heads, dropout=dropout, batch_first=True)\n        # Implementation of Feedforward model\n        self.fc1 = nn.Linear(c1, cm)\n        self.fc2 = nn.Linear(cm, c1)\n\n        self.norm1 = nn.LayerNorm(c1)\n        self.norm2 = nn.LayerNorm(c1)\n        self.dropout = nn.Dropout(dropout)\n        self.dropout1 = nn.Dropout(dropout)\n        self.dropout2 = nn.Dropout(dropout)\n\n        self.act = act\n        self.normalize_before = normalize_before\n\n    def with_pos_embed(self, tensor, pos=None):\n        \"\"\"Add position embeddings if given.\"\"\"\n        return tensor if pos is None else tensor + pos\n\n    def forward_post(self, src, src_mask=None, src_key_padding_mask=None, pos=None):\n        q = k = self.with_pos_embed(src, pos)\n        src2 = self.ma(q, k, value=src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0]\n        src = src + self.dropout1(src2)\n        src = self.norm1(src)\n        src2 = self.fc2(self.dropout(self.act(self.fc1(src))))\n        src = src + self.dropout2(src2)\n        src = self.norm2(src)\n        return src\n\n    def forward_pre(self, src, src_mask=None, src_key_padding_mask=None, pos=None):\n        src2 = self.norm1(src)\n        q = k = self.with_pos_embed(src2, pos)\n        src2 = self.ma(q, k, value=src2, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0]\n        src = src + self.dropout1(src2)\n        src2 = self.norm2(src)\n        src2 = self.fc2(self.dropout(self.act(self.fc1(src2))))\n        src = src + self.dropout2(src2)\n        return src\n\n    def forward(self, src, src_mask=None, src_key_padding_mask=None, pos=None):\n        \"\"\"Forward propagates the input through the encoder module.\"\"\"\n        if self.normalize_before:\n            return self.forward_pre(src, src_mask, src_key_padding_mask, pos)\n        return self.forward_post(src, src_mask, src_key_padding_mask, pos)\n\n\nclass AIFI(TransformerEncoderLayer):\n\n    def __init__(self, c1, cm=2048, num_heads=8, dropout=0, act=nn.GELU(), normalize_before=False):\n        super().__init__(c1, cm, num_heads, dropout, act, normalize_before)\n\n    def forward(self, x):\n        c, h, w = x.shape[1:]\n        pos_embed = self.build_2d_sincos_position_embedding(w, h, c)\n        # flatten [B, C, H, W] to [B, HxW, C]\n        x = super().forward(x.flatten(2).permute(0, 2, 1), pos=pos_embed.to(device=x.device, dtype=x.dtype))\n        return x.permute((0, 2, 1)).view([-1, c, h, w])\n\n    @staticmethod\n    def build_2d_sincos_position_embedding(w, h, embed_dim=256, temperature=10000.):\n        grid_w = torch.arange(int(w), dtype=torch.float32)\n        grid_h = torch.arange(int(h), dtype=torch.float32)\n        grid_w, grid_h = torch.meshgrid(grid_w, grid_h, indexing='ij')\n        assert embed_dim % 4 == 0, \\\n            'Embed dimension must be divisible by 4 for 2D sin-cos position embedding'\n        pos_dim = embed_dim // 4\n        omega = torch.arange(pos_dim, dtype=torch.float32) / pos_dim\n        omega = 1. / (temperature ** omega)\n\n        out_w = grid_w.flatten()[..., None] @ omega[None]\n        out_h = grid_h.flatten()[..., None] @ omega[None]\n\n        return torch.concat([torch.sin(out_w), torch.cos(out_w),\n                             torch.sin(out_h), torch.cos(out_h)], axis=1)[None, :, :]\n\n\nclass TransformerLayer(nn.Module):\n    \"\"\"Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance).\"\"\"\n\n    def __init__(self, c, num_heads):\n        \"\"\"Initializes a self-attention mechanism using linear transformations and multi-head attention.\"\"\"\n        super().__init__()\n        self.q = nn.Linear(c, c, bias=False)\n        self.k = nn.Linear(c, c, bias=False)\n        self.v = nn.Linear(c, c, bias=False)\n        self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)\n        self.fc1 = nn.Linear(c, c, bias=False)\n        self.fc2 = nn.Linear(c, c, bias=False)\n\n    def forward(self, x):\n        \"\"\"Apply a transformer block to the input x and return the output.\"\"\"\n        x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x\n        x = self.fc2(self.fc1(x)) + x\n        return x\n\n\nclass TransformerBlock(nn.Module):\n    \"\"\"Vision Transformer https://arxiv.org/abs/2010.11929.\"\"\"\n\n    def __init__(self, c1, c2, num_heads, num_layers):\n        \"\"\"Initialize a Transformer module with position embedding and specified number of heads and layers.\"\"\"\n        super().__init__()\n        self.conv = None\n        if c1 != c2:\n            self.conv = Conv(c1, c2)\n        self.linear = nn.Linear(c2, c2)  # learnable position embedding\n        self.tr = nn.Sequential(*(TransformerLayer(c2, num_heads) for _ in range(num_layers)))\n        self.c2 = c2\n\n    def forward(self, x):\n        \"\"\"Forward propagates the input through the bottleneck module.\"\"\"\n        if self.conv is not None:\n            x = self.conv(x)\n        b, _, w, h = x.shape\n        p = x.flatten(2).permute(2, 0, 1)\n        return self.tr(p + self.linear(p)).permute(1, 2, 0).reshape(b, self.c2, w, h)\n\n\nclass MLPBlock(nn.Module):\n\n    def __init__(self, embedding_dim, mlp_dim, act=nn.GELU):\n        super().__init__()\n        self.lin1 = nn.Linear(embedding_dim, mlp_dim)\n        self.lin2 = nn.Linear(mlp_dim, embedding_dim)\n        self.act = act()\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        return self.lin2(self.act(self.lin1(x)))\n\n\nclass MLP(nn.Module):\n    \"\"\" Very simple multi-layer perceptron (also called FFN)\"\"\"\n\n    def __init__(self, input_dim, hidden_dim, output_dim, num_layers):\n        super().__init__()\n        self.num_layers = num_layers\n        h = [hidden_dim] * (num_layers - 1)\n        self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))\n\n    def forward(self, x):\n        for i, layer in enumerate(self.layers):\n            x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)\n        return x\n\n\n# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa\n# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119  # noqa\nclass LayerNorm2d(nn.Module):\n\n    def __init__(self, num_channels, eps=1e-6):\n        super().__init__()\n        self.weight = nn.Parameter(torch.ones(num_channels))\n        self.bias = nn.Parameter(torch.zeros(num_channels))\n        self.eps = eps\n\n    def forward(self, x):\n        u = x.mean(1, keepdim=True)\n        s = (x - u).pow(2).mean(1, keepdim=True)\n        x = (x - u) / torch.sqrt(s + self.eps)\n        x = self.weight[:, None, None] * x + self.bias[:, None, None]\n        return x\n\n\nclass MSDeformAttn(nn.Module):\n    \"\"\"\n    Original Multi-Scale Deformable Attention Module.\n    https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/modules/ms_deform_attn.py\n    \"\"\"\n\n    def __init__(self, d_model=256, n_levels=4, n_heads=8, n_points=4):\n        super().__init__()\n        if d_model % n_heads != 0:\n            raise ValueError(f'd_model must be divisible by n_heads, but got {d_model} and {n_heads}')\n        _d_per_head = d_model // n_heads\n        # you'd better set _d_per_head to a power of 2 which is more efficient in our CUDA implementation\n        assert _d_per_head * n_heads == d_model, '`d_model` must be divisible by `n_heads`'\n\n        self.im2col_step = 64\n\n        self.d_model = d_model\n        self.n_levels = n_levels\n        self.n_heads = n_heads\n        self.n_points = n_points\n\n        self.sampling_offsets = nn.Linear(d_model, n_heads * n_levels * n_points * 2)\n        self.attention_weights = nn.Linear(d_model, n_heads * n_levels * n_points)\n        self.value_proj = nn.Linear(d_model, d_model)\n        self.output_proj = nn.Linear(d_model, d_model)\n\n        self._reset_parameters()\n\n    def _reset_parameters(self):\n        constant_(self.sampling_offsets.weight.data, 0.)\n        thetas = torch.arange(self.n_heads, dtype=torch.float32) * (2.0 * math.pi / self.n_heads)\n        grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)\n        grid_init = (grid_init / grid_init.abs().max(-1, keepdim=True)[0]).view(self.n_heads, 1, 1, 2).repeat(\n            1, self.n_levels, self.n_points, 1)\n        for i in range(self.n_points):\n            grid_init[:, :, i, :] *= i + 1\n        with torch.no_grad():\n            self.sampling_offsets.bias = nn.Parameter(grid_init.view(-1))\n        constant_(self.attention_weights.weight.data, 0.)\n        constant_(self.attention_weights.bias.data, 0.)\n        xavier_uniform_(self.value_proj.weight.data)\n        constant_(self.value_proj.bias.data, 0.)\n        xavier_uniform_(self.output_proj.weight.data)\n        constant_(self.output_proj.bias.data, 0.)\n\n    def forward(self, query, reference_points, value, value_spatial_shapes, value_mask=None):\n        \"\"\"\n        https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py\n        Args:\n            query (Tensor): [bs, query_length, C]\n            reference_points (Tensor): [bs, query_length, n_levels, 2], range in [0, 1], top-left (0,0),\n                bottom-right (1, 1), including padding area\n            value (Tensor): [bs, value_length, C]\n            value_spatial_shapes (List): [n_levels, 2], [(H_0, W_0), (H_1, W_1), ..., (H_{L-1}, W_{L-1})]\n            value_mask (Tensor): [bs, value_length], True for non-padding elements, False for padding elements\n\n        Returns:\n            output (Tensor): [bs, Length_{query}, C]\n        \"\"\"\n        bs, len_q = query.shape[:2]\n        _, len_v = value.shape[:2]\n        assert sum(s[0] * s[1] for s in value_spatial_shapes) == len_v\n\n        value = self.value_proj(value)\n        if value_mask is not None:\n            value = value.masked_fill(value_mask[..., None], float(0))\n        value = value.view(bs, len_v, self.n_heads, self.d_model // self.n_heads)\n        sampling_offsets = self.sampling_offsets(query).view(bs, len_q, self.n_heads, self.n_levels, self.n_points, 2)\n        attention_weights = self.attention_weights(query).view(bs, len_q, self.n_heads, self.n_levels * self.n_points)\n        attention_weights = F.softmax(attention_weights, -1).view(bs, len_q, self.n_heads, self.n_levels, self.n_points)\n        # N, Len_q, n_heads, n_levels, n_points, 2\n        n = reference_points.shape[-1]\n        if n == 2:\n            offset_normalizer = torch.as_tensor(value_spatial_shapes, dtype=query.dtype, device=query.device).flip(-1)\n            add = sampling_offsets / offset_normalizer[None, None, None, :, None, :]\n            sampling_locations = reference_points[:, :, None, :, None, :] + add\n\n        elif n == 4:\n            add = sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5\n            sampling_locations = reference_points[:, :, None, :, None, :2] + add\n        else:\n            raise ValueError(f'Last dim of reference_points must be 2 or 4, but got {n}.')\n        output = multi_scale_deformable_attn_pytorch(value, value_spatial_shapes, sampling_locations, attention_weights)\n        output = self.output_proj(output)\n        return output\n\n\nclass DeformableTransformerDecoderLayer(nn.Module):\n    \"\"\"\n    https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py\n    https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/deformable_transformer.py\n    \"\"\"\n\n    def __init__(self, d_model=256, n_heads=8, d_ffn=1024, dropout=0., act=nn.ReLU(), n_levels=4, n_points=4):\n        super().__init__()\n\n        # self attention\n        self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)\n        self.dropout1 = nn.Dropout(dropout)\n        self.norm1 = nn.LayerNorm(d_model)\n\n        # cross attention\n        self.cross_attn = MSDeformAttn(d_model, n_levels, n_heads, n_points)\n        self.dropout2 = nn.Dropout(dropout)\n        self.norm2 = nn.LayerNorm(d_model)\n\n        # ffn\n        self.linear1 = nn.Linear(d_model, d_ffn)\n        self.act = act\n        self.dropout3 = nn.Dropout(dropout)\n        self.linear2 = nn.Linear(d_ffn, d_model)\n        self.dropout4 = nn.Dropout(dropout)\n        self.norm3 = nn.LayerNorm(d_model)\n\n    @staticmethod\n    def with_pos_embed(tensor, pos):\n        return tensor if pos is None else tensor + pos\n\n    def forward_ffn(self, tgt):\n        tgt2 = self.linear2(self.dropout3(self.act(self.linear1(tgt))))\n        tgt = tgt + self.dropout4(tgt2)\n        tgt = self.norm3(tgt)\n        return tgt\n\n    def forward(self,\n                tgt,\n                reference_points,\n                src,\n                src_spatial_shapes,\n                src_padding_mask=None,\n                attn_mask=None,\n                query_pos=None):\n        # self attention\n        q = k = self.with_pos_embed(tgt, query_pos)\n        if attn_mask is not None:\n            attn_mask = torch.where(attn_mask.astype('bool'), torch.zeros(attn_mask.shape, tgt.dtype),\n                                    torch.full(attn_mask.shape, float('-inf'), tgt.dtype))\n        tgt2 = self.self_attn(q.transpose(0, 1), k.transpose(0, 1), tgt.transpose(0, 1))[0].transpose(0, 1)\n        tgt = tgt + self.dropout1(tgt2)\n        tgt = self.norm1(tgt)\n\n        # cross attention\n        tgt2 = self.cross_attn(self.with_pos_embed(tgt, query_pos), reference_points, src, src_spatial_shapes,\n                               src_padding_mask)\n        tgt = tgt + self.dropout2(tgt2)\n        tgt = self.norm2(tgt)\n\n        # ffn\n        tgt = self.forward_ffn(tgt)\n\n        return tgt\n\n\nclass DeformableTransformerDecoder(nn.Module):\n    \"\"\"\n    https://github.com/PaddlePaddle/PaddleDetection/blob/develop/ppdet/modeling/transformers/deformable_transformer.py\n    \"\"\"\n\n    def __init__(self, hidden_dim, decoder_layer, num_layers, eval_idx=-1):\n        super().__init__()\n        self.layers = _get_clones(decoder_layer, num_layers)\n        self.num_layers = num_layers\n        self.hidden_dim = hidden_dim\n        self.eval_idx = eval_idx if eval_idx >= 0 else num_layers + eval_idx\n\n    def forward(self,\n                tgt,\n                reference_points,\n                src,\n                src_spatial_shapes,\n                bbox_head,\n                score_head,\n                query_pos_head,\n                attn_mask=None,\n                src_padding_mask=None):\n        output = tgt\n        dec_out_bboxes = []\n        dec_out_logits = []\n        ref_points = None\n        ref_points_detach = torch.sigmoid(reference_points)\n        for i, layer in enumerate(self.layers):\n            ref_points_input = ref_points_detach.unsqueeze(2)\n            query_pos_embed = query_pos_head(ref_points_detach)\n            output = layer(output, ref_points_input, src, src_spatial_shapes, src_padding_mask, attn_mask,\n                           query_pos_embed)\n\n            inter_ref_bbox = torch.sigmoid(bbox_head[i](output) + inverse_sigmoid(ref_points_detach))\n\n            if self.training:\n                dec_out_logits.append(score_head[i](output))\n                if i == 0:\n                    dec_out_bboxes.append(inter_ref_bbox)\n                else:\n                    dec_out_bboxes.append(torch.sigmoid(bbox_head[i](output) + inverse_sigmoid(ref_points)))\n            elif i == self.eval_idx:\n                dec_out_logits.append(score_head[i](output))\n                dec_out_bboxes.append(inter_ref_bbox)\n                break\n\n            ref_points = inter_ref_bbox\n            ref_points_detach = inter_ref_bbox.detach() if self.training else inter_ref_bbox\n\n        return torch.stack(dec_out_bboxes), torch.stack(dec_out_logits)\n"
  },
  {
    "path": "ultralytics/nn/modules/utils.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nModule utils\n\"\"\"\n\nimport copy\nimport math\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.init import uniform_\n\n__all__ = ['multi_scale_deformable_attn_pytorch', 'inverse_sigmoid']\n\n\ndef _get_clones(module, n):\n    return nn.ModuleList([copy.deepcopy(module) for _ in range(n)])\n\n\ndef bias_init_with_prob(prior_prob=0.01):\n    \"\"\"initialize conv/fc bias value according to a given probability value.\"\"\"\n    return float(-np.log((1 - prior_prob) / prior_prob))  # return bias_init\n\n\ndef linear_init_(module):\n    bound = 1 / math.sqrt(module.weight.shape[0])\n    uniform_(module.weight, -bound, bound)\n    if hasattr(module, 'bias') and module.bias is not None:\n        uniform_(module.bias, -bound, bound)\n\n\ndef inverse_sigmoid(x, eps=1e-5):\n    x = x.clamp(min=0, max=1)\n    x1 = x.clamp(min=eps)\n    x2 = (1 - x).clamp(min=eps)\n    return torch.log(x1 / x2)\n\n\ndef multi_scale_deformable_attn_pytorch(value: torch.Tensor, value_spatial_shapes: torch.Tensor,\n                                        sampling_locations: torch.Tensor,\n                                        attention_weights: torch.Tensor) -> torch.Tensor:\n    \"\"\"\n    Multi-scale deformable attention.\n    https://github.com/IDEA-Research/detrex/blob/main/detrex/layers/multi_scale_deform_attn.py\n    \"\"\"\n\n    bs, _, num_heads, embed_dims = value.shape\n    _, num_queries, num_heads, num_levels, num_points, _ = sampling_locations.shape\n    value_list = value.split([H_ * W_ for H_, W_ in value_spatial_shapes], dim=1)\n    sampling_grids = 2 * sampling_locations - 1\n    sampling_value_list = []\n    for level, (H_, W_) in enumerate(value_spatial_shapes):\n        # bs, H_*W_, num_heads, embed_dims ->\n        # bs, H_*W_, num_heads*embed_dims ->\n        # bs, num_heads*embed_dims, H_*W_ ->\n        # bs*num_heads, embed_dims, H_, W_\n        value_l_ = (value_list[level].flatten(2).transpose(1, 2).reshape(bs * num_heads, embed_dims, H_, W_))\n        # bs, num_queries, num_heads, num_points, 2 ->\n        # bs, num_heads, num_queries, num_points, 2 ->\n        # bs*num_heads, num_queries, num_points, 2\n        sampling_grid_l_ = sampling_grids[:, :, :, level].transpose(1, 2).flatten(0, 1)\n        # bs*num_heads, embed_dims, num_queries, num_points\n        sampling_value_l_ = F.grid_sample(value_l_,\n                                          sampling_grid_l_,\n                                          mode='bilinear',\n                                          padding_mode='zeros',\n                                          align_corners=False)\n        sampling_value_list.append(sampling_value_l_)\n    # (bs, num_queries, num_heads, num_levels, num_points) ->\n    # (bs, num_heads, num_queries, num_levels, num_points) ->\n    # (bs, num_heads, 1, num_queries, num_levels*num_points)\n    attention_weights = attention_weights.transpose(1, 2).reshape(bs * num_heads, 1, num_queries,\n                                                                  num_levels * num_points)\n    output = ((torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights).sum(-1).view(\n        bs, num_heads * embed_dims, num_queries))\n    return output.transpose(1, 2).contiguous()\n"
  },
  {
    "path": "ultralytics/nn/tasks.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nfrom copy import deepcopy\nfrom pathlib import Path\n\nimport torch\nimport torch.nn as nn\n\nfrom ultralytics.nn.modules import (AIFI, C1, C2, C3, C3TR, SPP, SPPF, Bottleneck, BottleneckCSP, C2f, C3Ghost, C3x,\n                                    Classify, Concat, Conv, ConvTranspose, Detect, DWConv, DWConvTranspose2d, Focus,\n                                    GhostBottleneck, GhostConv, HGBlock, HGStem, Pose, RepC3, RepConv, RTDETRDecoder,\n                                    Segment, Concat_dropout)\nfrom ultralytics.yolo.utils import DEFAULT_CFG_DICT, DEFAULT_CFG_KEYS, LOGGER, colorstr, emojis, yaml_load\nfrom ultralytics.yolo.utils.checks import check_requirements, check_suffix, check_yaml\nfrom ultralytics.yolo.utils.plotting import feature_visualization\nfrom ultralytics.yolo.utils.torch_utils import (fuse_conv_and_bn, fuse_deconv_and_bn, initialize_weights,\n                                                intersect_dicts, make_divisible, model_info, scale_img, time_sync)\n\ntry:\n    import thop\nexcept ImportError:\n    thop = None\n\n\nclass BaseModel(nn.Module):\n    \"\"\"\n    The BaseModel class serves as a base class for all the models in the Ultralytics YOLO family.\n    \"\"\"\n\n    def forward(self, x, profile=False, visualize=False):\n        \"\"\"\n        Forward pass of the model on a single scale.\n        Wrapper for `_forward_once` method.\n\n        Args:\n            x (torch.Tensor): The input image tensor\n            profile (bool): Whether to profile the model, defaults to False\n            visualize (bool): Whether to return the intermediate feature maps, defaults to False\n\n        Returns:\n            (torch.Tensor): The output of the network.\n        \"\"\"\n        return self._forward_once(x, profile, visualize)\n\n    def _forward_once(self, x, profile=False, visualize=False):\n        \"\"\"\n        Perform a forward pass through the network.\n\n        Args:\n            x (torch.Tensor): The input tensor to the model\n            profile (bool):  Print the computation time of each layer if True, defaults to False.\n            visualize (bool): Save the feature maps of the model if True, defaults to False\n\n        Returns:\n            (torch.Tensor): The last output of the model.\n        \"\"\"\n        y, dt = [], []  # outputs\n        for m in self.model:\n            if m.f != -1:  # if not from previous layer\n                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers\n            if profile:\n                self._profile_one_layer(m, x, dt)\n            x = m(x)  # run\n            y.append(x if m.i in self.save else None)  # save output\n            if visualize:\n                feature_visualization(x, m.type, m.i, save_dir=visualize)\n        return x\n\n    def _profile_one_layer(self, m, x, dt):\n        \"\"\"\n        Profile the computation time and FLOPs of a single layer of the model on a given input.\n        Appends the results to the provided list.\n\n        Args:\n            m (nn.Module): The layer to be profiled.\n            x (torch.Tensor): The input data to the layer.\n            dt (list): A list to store the computation time of the layer.\n\n        Returns:\n            None\n        \"\"\"\n        c = m == self.model[-1]  # is final layer, copy input as inplace fix\n        o = thop.profile(m, inputs=[x.clone() if c else x], verbose=False)[0] / 1E9 * 2 if thop else 0  # FLOPs\n        t = time_sync()\n        for _ in range(10):\n            m(x.clone() if c else x)\n        dt.append((time_sync() - t) * 100)\n        if m == self.model[0]:\n            LOGGER.info(f\"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s}  module\")\n        LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f}  {m.type}')\n        if c:\n            LOGGER.info(f\"{sum(dt):10.2f} {'-':>10s} {'-':>10s}  Total\")\n\n    def fuse(self, verbose=True):\n        \"\"\"\n        Fuse the `Conv2d()` and `BatchNorm2d()` layers of the model into a single layer, in order to improve the\n        computation efficiency.\n\n        Returns:\n            (nn.Module): The fused model is returned.\n        \"\"\"\n        if not self.is_fused():\n            for m in self.model.modules():\n                if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):\n                    m.conv = fuse_conv_and_bn(m.conv, m.bn)  # update conv\n                    delattr(m, 'bn')  # remove batchnorm\n                    m.forward = m.forward_fuse  # update forward\n                if isinstance(m, ConvTranspose) and hasattr(m, 'bn'):\n                    m.conv_transpose = fuse_deconv_and_bn(m.conv_transpose, m.bn)\n                    delattr(m, 'bn')  # remove batchnorm\n                    m.forward = m.forward_fuse  # update forward\n                if isinstance(m, RepConv):\n                    m.fuse_convs()\n                    m.forward = m.forward_fuse  # update forward\n            self.info(verbose=verbose)\n\n        return self\n\n    def is_fused(self, thresh=10):\n        \"\"\"\n        Check if the model has less than a certain threshold of BatchNorm layers.\n\n        Args:\n            thresh (int, optional): The threshold number of BatchNorm layers. Default is 10.\n\n        Returns:\n            (bool): True if the number of BatchNorm layers in the model is less than the threshold, False otherwise.\n        \"\"\"\n        bn = tuple(v for k, v in nn.__dict__.items() if 'Norm' in k)  # normalization layers, i.e. BatchNorm2d()\n        return sum(isinstance(v, bn) for v in self.modules()) < thresh  # True if < 'thresh' BatchNorm layers in model\n\n    def info(self, detailed=False, verbose=True, imgsz=640):\n        \"\"\"\n        Prints model information\n\n        Args:\n            verbose (bool): if True, prints out the model information. Defaults to False\n            imgsz (int): the size of the image that the model will be trained on. Defaults to 640\n        \"\"\"\n        return model_info(self, detailed=detailed, verbose=verbose, imgsz=imgsz)\n\n    def _apply(self, fn):\n        \"\"\"\n        `_apply()` is a function that applies a function to all the tensors in the model that are not\n        parameters or registered buffers\n\n        Args:\n            fn: the function to apply to the model\n\n        Returns:\n            A model that is a Detect() object.\n        \"\"\"\n        self = super()._apply(fn)\n        m = self.model[-1]  # Detect()\n        if isinstance(m, (Detect, Segment)):\n            m.stride = fn(m.stride)\n            m.anchors = fn(m.anchors)\n            m.strides = fn(m.strides)\n        return self\n\n    def load(self, weights, verbose=True):\n        \"\"\"Load the weights into the model.\n\n        Args:\n            weights (dict) or (torch.nn.Module): The pre-trained weights to be loaded.\n            verbose (bool, optional): Whether to log the transfer progress. Defaults to True.\n        \"\"\"\n        model = weights['model'] if isinstance(weights, dict) else weights  # torchvision models are not dicts\n        csd = model.float().state_dict()  # checkpoint state_dict as FP32\n        csd = intersect_dicts(csd, self.state_dict())  # intersect\n        self.load_state_dict(csd, strict=False)  # load\n        if verbose:\n            LOGGER.info(f'Transferred {len(csd)}/{len(self.model.state_dict())} items from pretrained weights')\n            \n\nclass MultiBaseModel(nn.Module):\n    \"\"\"\n    The BaseModel class serves as a base class for all the models in the Ultralytics YOLO family.\n    \"\"\"\n\n    def forward(self, x, profile=False, visualize=False):\n        \"\"\"\n        Forward pass of the model on a single scale.\n        Wrapper for `_forward_once` method.\n\n        Args:\n            x (torch.Tensor): The input image tensor\n            profile (bool): Whether to profile the model, defaults to False\n            visualize (bool): Whether to return the intermediate feature maps, defaults to False\n\n        Returns:\n            (torch.Tensor): The output of the network.\n        \"\"\"\n        return self._forward_once(x, profile, visualize)\n\n#     def _forward_once(self, x, profile=False, visualize=False):\n#         \"\"\"\n#         Perform a forward pass through the network.\n\n#         Args:\n#             x (torch.Tensor): The input tensor to the model\n#             profile (bool):  Print the computation time of each layer if True, defaults to False.\n#             visualize (bool): Save the feature maps of the model if True, defaults to False\n\n#         Returns:\n#             (torch.Tensor): The last output of the model.\n#         \"\"\"\n#         y, dt = [], []  # outputs\n#         for m in self.model:\n#             if m.f != -1:  # if not from previous layer\n#                 x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers\n#             if profile:\n#                 self._profile_one_layer(m, x, dt)\n#             x = m(x)  # run\n#             y.append(x if m.i in self.save else None)  # save output\n#             if visualize:\n#                 feature_visualization(x, m.type, m.i, save_dir=visualize)\n#         return x\n    \n    \n    def _forward_once(self, x, profile=False, visualize=False):\n        \"\"\"\n        This output will return whole head result. the sequence is object detection, drivable area seg and lane seg. \n        \"\"\"\n        outputs, y = [], []\n        for m in self.model:\n            if m.f != -1:  # if not from previous layer\n                x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f]  # from earlier layers\n            x = m(x)  # run\n\n            if isinstance(m, (Detect, Segment)):  # if it's a task head\n                outputs.append(x)\n            # y.append(x)\n            y.append(x if m.i in self.save else None)  # save output\n            if visualize:\n                feature_visualization(x, m.type, m.i, save_dir=visualize)\n        return outputs\n\n\n    def _profile_one_layer(self, m, x, dt):\n        \"\"\"\n        Profile the computation time and FLOPs of a single layer of the model on a given input.\n        Appends the results to the provided list.\n\n        Args:\n            m (nn.Module): The layer to be profiled.\n            x (torch.Tensor): The input data to the layer.\n            dt (list): A list to store the computation time of the layer.\n\n        Returns:\n            None\n        \"\"\"\n        c = m in self.model[-3:]  # is final layer, copy input as inplace fix\n        o = thop.profile(m, inputs=[x.clone() if c else x], verbose=False)[0] / 1E9 * 2 if thop else 0  # FLOPs\n        t = time_sync()\n        for _ in range(10):\n            m(x.clone() if c else x)\n        dt.append((time_sync() - t) * 100)\n        if m == self.model[0]:\n            LOGGER.info(f\"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s}  module\")\n        LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f}  {m.type}')\n        if c:\n            LOGGER.info(f\"{sum(dt):10.2f} {'-':>10s} {'-':>10s}  Total\")\n\n    def fuse(self, verbose=True):\n        \"\"\"\n        Fuse the `Conv2d()` and `BatchNorm2d()` layers of the model into a single layer, in order to improve the\n        computation efficiency.\n\n        Returns:\n            (nn.Module): The fused model is returned.\n        \"\"\"\n        if not self.is_fused():\n            for m in self.model.modules():\n                if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):\n                    m.conv = fuse_conv_and_bn(m.conv, m.bn)  # update conv\n                    delattr(m, 'bn')  # remove batchnorm\n                    m.forward = m.forward_fuse  # update forward\n                if isinstance(m, ConvTranspose) and hasattr(m, 'bn'):\n                    m.conv_transpose = fuse_deconv_and_bn(m.conv_transpose, m.bn)\n                    delattr(m, 'bn')  # remove batchnorm\n                    m.forward = m.forward_fuse  # update forward\n                if isinstance(m, RepConv):\n                    m.fuse_convs()\n                    m.forward = m.forward_fuse  # update forward\n            self.info(verbose=verbose)\n\n        return self\n\n    def is_fused(self, thresh=10):\n        \"\"\"\n        Check if the model has less than a certain threshold of BatchNorm layers.\n\n        Args:\n            thresh (int, optional): The threshold number of BatchNorm layers. Default is 10.\n\n        Returns:\n            (bool): True if the number of BatchNorm layers in the model is less than the threshold, False otherwise.\n        \"\"\"\n        bn = tuple(v for k, v in nn.__dict__.items() if 'Norm' in k)  # normalization layers, i.e. BatchNorm2d()\n        return sum(isinstance(v, bn) for v in self.modules()) < thresh  # True if < 'thresh' BatchNorm layers in model\n\n    def info(self, detailed=False, verbose=True, imgsz=640):\n        \"\"\"\n        Prints model information\n\n        Args:\n            verbose (bool): if True, prints out the model information. Defaults to False\n            imgsz (int): the size of the image that the model will be trained on. Defaults to 640\n        \"\"\"\n        return model_info(self, detailed=detailed, verbose=verbose, imgsz=imgsz)\n\n#     def _apply(self, fn):\n#         \"\"\"\n#         `_apply()` is a function that applies a function to all the tensors in the model that are not\n#         parameters or registered buffers\n\n#         Args:\n#             fn: the function to apply to the model\n\n#         Returns:\n#             A model that is a Detect() object.\n#         \"\"\"\n#         self = super()._apply(fn)\n#         m = self.model[-1]  # Detect()\n#         if isinstance(m, (Detect, Segment)):\n#             m.stride = fn(m.stride)\n#             m.anchors = fn(m.anchors)\n#             m.strides = fn(m.strides)\n#         return self\n    \n    def _apply(self, fn):\n        \"\"\"\n        `_apply()` is a function that applies a function to all the tensors in the model that are not\n        parameters or registered buffers\n\n        Args:\n            fn: the function to apply to the model\n\n        Returns:\n            A model that is a Detect() object.\n        \"\"\"\n        self = super()._apply(fn)\n        for m in self.model[-3:]:  # Iterate over the last three layers\n            if isinstance(m, (Detect, Segment)):\n                m.stride = fn(m.stride)\n                m.anchors = fn(m.anchors)\n                m.strides = fn(m.strides)\n        return self\n\n\n    def load(self, weights, verbose=True):\n        \"\"\"Load the weights into the model.\n\n        Args:\n            weights (dict) or (torch.nn.Module): The pre-trained weights to be loaded.\n            verbose (bool, optional): Whether to log the transfer progress. Defaults to True.\n        \"\"\"\n        model = weights['model'] if isinstance(weights, dict) else weights  # torchvision models are not dicts\n        csd = model.float().state_dict()  # checkpoint state_dict as FP32\n        csd = intersect_dicts(csd, self.state_dict())  # intersect\n        self.load_state_dict(csd, strict=False)  # load\n        if verbose:\n            LOGGER.info(f'Transferred {len(csd)}/{len(self.model.state_dict())} items from pretrained weights')\n\n\nclass DetectionModel(BaseModel):\n    \"\"\"YOLOv8 detection model.\"\"\"\n\n    def __init__(self, cfg='yolov8n.yaml', ch=3, nc=None, verbose=True):  # model, input channels, number of classes\n        super().__init__()\n        self.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg)  # cfg dict\n\n        # Define model\n        ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels\n        if nc and nc != self.yaml['nc']:\n            LOGGER.info(f\"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}\")\n            self.yaml['nc'] = nc  # override yaml value\n        self.model, self.save = parse_model(deepcopy(self.yaml), ch=ch, verbose=verbose)  # model, savelist\n        self.names = {i: f'{i}' for i in range(self.yaml['tnc'])}  # default names dict\n        self.inplace = self.yaml.get('inplace', True)\n\n        # Build strides\n        for m in self.model:\n            if isinstance(m, (Detect, Segment, Pose)):\n                s = 256  # 2x min stride\n                m.inplace = self.inplace\n                forward = lambda x: self.forward(x)[0] if isinstance(m, (Segment, Pose)) else self.forward(x)\n                m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))])  # forward\n                self.stride = m.stride\n                m.bias_init()  # only run once\n\n        # Init weights, biases\n        initialize_weights(self)\n        if verbose:\n            self.info()\n            LOGGER.info('')\n\n    def forward(self, x, augment=False, profile=False, visualize=False):\n        \"\"\"Run forward pass on input image(s) with optional augmentation and profiling.\"\"\"\n        if augment:\n            return self._forward_augment(x)  # augmented inference, None\n        return self._forward_once(x, profile, visualize)  # single-scale inference, train\n\n    def _forward_augment(self, x):\n        \"\"\"Perform augmentations on input image x and return augmented inference and train outputs.\"\"\"\n        img_size = x.shape[-2:]  # height, width\n        s = [1, 0.83, 0.67]  # scales\n        f = [None, 3, None]  # flips (2-ud, 3-lr)\n        y = []  # outputs\n        for si, fi in zip(s, f):\n            xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))\n            yi = self._forward_once(xi)[0]  # forward\n            # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1])  # save\n            yi = self._descale_pred(yi, fi, si, img_size)\n            y.append(yi)\n        y = self._clip_augmented(y)  # clip augmented tails\n        return torch.cat(y, -1), None  # augmented inference, train\n\n    @staticmethod\n    def _descale_pred(p, flips, scale, img_size, dim=1):\n        \"\"\"De-scale predictions following augmented inference (inverse operation).\"\"\"\n        p[:, :4] /= scale  # de-scale\n        x, y, wh, cls = p.split((1, 1, 2, p.shape[dim] - 4), dim)\n        if flips == 2:\n            y = img_size[0] - y  # de-flip ud\n        elif flips == 3:\n            x = img_size[1] - x  # de-flip lr\n        return torch.cat((x, y, wh, cls), dim)\n\n    def _clip_augmented(self, y):\n        \"\"\"Clip YOLOv5 augmented inference tails.\"\"\"\n        nl = self.model[-1].nl  # number of detection layers (P3-P5)\n        g = sum(4 ** x for x in range(nl))  # grid points\n        e = 1  # exclude layer count\n        i = (y[0].shape[-1] // g) * sum(4 ** x for x in range(e))  # indices\n        y[0] = y[0][..., :-i]  # large\n        i = (y[-1].shape[-1] // g) * sum(4 ** (nl - 1 - x) for x in range(e))  # indices\n        y[-1] = y[-1][..., i:]  # small\n        return y\n\n    \nclass MultiModel(MultiBaseModel):\n    \"\"\"YOLOv8 detection and segmentation model.\"\"\"\n\n    def __init__(self, cfg='yolov8-bdd.yaml', ch=3, nc=None, verbose=True):  # model, input channels, number of classes\n        super().__init__()\n        self.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg)  # cfg dict\n\n        # Define model\n        ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels\n        if nc and nc != self.yaml['tnc']:\n            LOGGER.info(f\"Overriding model.yaml nc={self.yaml['tnc']} with nc={tnc}\")\n            self.yaml['tnc'] = nc  # override yaml value\n        self.model, self.save = parse_model(deepcopy(self.yaml), ch=ch, verbose=verbose)  # model, savelist\n        self.names = {i: f'{i}' for i in range(self.yaml['tnc'])}  # default names dict\n        self.inplace = self.yaml.get('inplace', True)\n        self.stride = []\n\n        # Build strides\n        count = 0\n        for m in self.model:\n        # m = self.model[-1]  # Detect()\n            if isinstance(m, (Detect, Segment, Pose)):\n                s = 256  # 2x min stride\n                m.inplace = self.inplace\n\n                forward = lambda x: self.forward(x)[count][0] if isinstance(m, (Segment, Pose)) else self.forward(x)[count]\n                m.stride = torch.tensor([s / x.shape[-2] for x in forward(torch.zeros(1, ch, s, s))])  # forward\n\n                # outputs = forward(torch.zeros(1, ch, s, s))\n                # # if isinstance(m, (Detect)):\n                # #     outputs = outputs[count]\n                # strides = []\n                #\n                # for x in outputs:\n                #     stride = s / x.shape[-2]\n                #\n                #     strides.append(stride)\n                #\n                # m.stride = torch.tensor(strides)\n\n                # self.stride = m.stride\n                self.stride.append(m.stride)\n                ###### Jiayuan: do not move, otherwise the gradient will not backward to segmentation head. Only detection head will implement\n                try:\n                    m.bias_init()  # only run once for detection\n                except:\n                    pass\n                count = count+1\n\n        # Init weights, biases\n        initialize_weights(self)\n        if verbose:\n            self.info()\n            LOGGER.info('')\n\n    def forward(self, x, augment=False, profile=False, visualize=False):\n        \"\"\"Run forward pass on input image(s) with optional augmentation and profiling.\"\"\"\n        if augment:\n            return self._forward_augment(x)  # augmented inference, None\n        return self._forward_once(x, profile, visualize)  # single-scale inference, train\n\n\n    def _forward_augment(self, x):\n        \"\"\"Perform augmentations on input image x and return augmented inference and train outputs.\"\"\"\n        img_size = x.shape[-2:]  # height, width\n        s = [1, 0.83, 0.67]  # scales\n        f = [None, 3, None]  # flips (2-ud, 3-lr)\n        f = [None, 3, None]  # flips (2-ud, 3-lr)\n        y = []  # outputs\n        for si, fi in zip(s, f):\n            xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))\n            yi = self._forward_once(xi)  # forward\n            # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1])  # save\n            yi = [self._descale_pred(yij, fi, si, img_size) for yij in yi]\n            y.append(yi)\n        y = [self._clip_augmented(yij) for yij in zip(*y)]  # clip augmented tails\n        return [torch.cat(yij, -1) for yij in y], None  # augmented inference, train\n\n    @staticmethod\n    def _descale_pred(p, flips, scale, img_size, dim=1):\n        \"\"\"De-scale predictions following augmented inference (inverse operation).\"\"\"\n        p[:, :4] /= scale  # de-scale\n        x, y, wh, cls = p.split((1, 1, 2, p.shape[dim] - 4), dim)\n        if flips == 2:\n            y = img_size[0] - y  # de-flip ud\n        elif flips == 3:\n            x = img_size[1] - x  # de-flip lr\n        return torch.cat((x, y, wh, cls), dim)\n\n    def _clip_augmented(self, y):\n        \"\"\"Clip YOLOv8 augmented inference tails.\"\"\"\n        nl = self.model[-1].nl  # number of detection layers (P3-P5)\n        g = [sum(4 ** x for x in range(nl)) for _ in range(nl)]  # grid points for each head\n        e = 1  # exclude layer count\n        for i in range(len(y)):  # for each head\n            indices = (y[i].shape[-1] // g[i]) * sum(4 ** x for x in range(e))  # indices\n            y[i] = y[i][..., :-indices] if i == 0 else y[i][..., indices:]  # clip tails\n        return y\n\n\n\n#     def _forward_augment(self, x):\n#         \"\"\"Perform augmentations on input image x and return augmented inference and train outputs.\"\"\"\n#         img_size = x.shape[-2:]  # height, width\n#         s = [1, 0.83, 0.67]  # scales\n#         f = [None, 3, None]  # flips (2-ud, 3-lr)\n#         y = []  # outputs\n#         for si, fi in zip(s, f):\n#             xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))\n#             yi = self._forward_once(xi)[0]  # forward\n#             # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1])  # save\n#             yi = self._descale_pred(yi, fi, si, img_size)\n#             y.append(yi)\n#         y = self._clip_augmented(y)  # clip augmented tails\n#         return torch.cat(y, -1), None  # augmented inference, train\n\n#     @staticmethod\n#     def _descale_pred(p, flips, scale, img_size, dim=1):\n#         \"\"\"De-scale predictions following augmented inference (inverse operation).\"\"\"\n#         p[:, :4] /= scale  # de-scale\n#         x, y, wh, cls = p.split((1, 1, 2, p.shape[dim] - 4), dim)\n#         if flips == 2:\n#             y = img_size[0] - y  # de-flip ud\n#         elif flips == 3:\n#             x = img_size[1] - x  # de-flip lr\n#         return torch.cat((x, y, wh, cls), dim)\n\n#     def _clip_augmented(self, y):\n#         \"\"\"Clip YOLOv5 augmented inference tails.\"\"\"\n#         nl = self.model[-1].nl  # number of detection layers (P3-P5)\n#         g = sum(4 ** x for x in range(nl))  # grid points\n#         e = 1  # exclude layer count\n#         i = (y[0].shape[-1] // g) * sum(4 ** x for x in range(e))  # indices\n#         y[0] = y[0][..., :-i]  # large\n#         i = (y[-1].shape[-1] // g) * sum(4 ** (nl - 1 - x) for x in range(e))  # indices\n#         y[-1] = y[-1][..., i:]  # small\n#         return y\n\n\nclass SegmentationModel(DetectionModel):\n    \"\"\"YOLOv8 segmentation model.\"\"\"\n\n    def __init__(self, cfg='yolov8n-seg.yaml', ch=3, nc=None, verbose=True):\n        \"\"\"Initialize YOLOv8 segmentation model with given config and parameters.\"\"\"\n        super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)\n\n    def _forward_augment(self, x):\n        \"\"\"Undocumented function.\"\"\"\n        raise NotImplementedError(emojis('WARNING ⚠️ SegmentationModel has not supported augment inference yet!'))\n\n\nclass PoseModel(DetectionModel):\n    \"\"\"YOLOv8 pose model.\"\"\"\n\n    def __init__(self, cfg='yolov8n-pose.yaml', ch=3, nc=None, data_kpt_shape=(None, None), verbose=True):\n        \"\"\"Initialize YOLOv8 Pose model.\"\"\"\n        if not isinstance(cfg, dict):\n            cfg = yaml_model_load(cfg)  # load model YAML\n        if any(data_kpt_shape) and list(data_kpt_shape) != list(cfg['kpt_shape']):\n            LOGGER.info(f\"Overriding model.yaml kpt_shape={cfg['kpt_shape']} with kpt_shape={data_kpt_shape}\")\n            cfg['kpt_shape'] = data_kpt_shape\n        super().__init__(cfg=cfg, ch=ch, nc=nc, verbose=verbose)\n\n\nclass ClassificationModel(BaseModel):\n    \"\"\"YOLOv8 classification model.\"\"\"\n\n    def __init__(self,\n                 cfg=None,\n                 model=None,\n                 ch=3,\n                 nc=None,\n                 cutoff=10,\n                 verbose=True):  # yaml, model, channels, number of classes, cutoff index, verbose flag\n        super().__init__()\n        self._from_detection_model(model, nc, cutoff) if model is not None else self._from_yaml(cfg, ch, nc, verbose)\n\n    def _from_detection_model(self, model, nc=1000, cutoff=10):\n        \"\"\"Create a YOLOv5 classification model from a YOLOv5 detection model.\"\"\"\n        from ultralytics.nn.autobackend import AutoBackend\n        if isinstance(model, AutoBackend):\n            model = model.model  # unwrap DetectMultiBackend\n        model.model = model.model[:cutoff]  # backbone\n        m = model.model[-1]  # last layer\n        ch = m.conv.in_channels if hasattr(m, 'conv') else m.cv1.conv.in_channels  # ch into module\n        c = Classify(ch, nc)  # Classify()\n        c.i, c.f, c.type = m.i, m.f, 'models.common.Classify'  # index, from, type\n        model.model[-1] = c  # replace\n        self.model = model.model\n        self.stride = model.stride\n        self.save = []\n        self.nc = nc\n\n    def _from_yaml(self, cfg, ch, nc, verbose):\n        \"\"\"Set YOLOv8 model configurations and define the model architecture.\"\"\"\n        self.yaml = cfg if isinstance(cfg, dict) else yaml_model_load(cfg)  # cfg dict\n\n        # Define model\n        ch = self.yaml['ch'] = self.yaml.get('ch', ch)  # input channels\n        if nc and nc != self.yaml['nc']:\n            LOGGER.info(f\"Overriding model.yaml nc={self.yaml['nc']} with nc={nc}\")\n            self.yaml['nc'] = nc  # override yaml value\n        elif not nc and not self.yaml.get('nc', None):\n            raise ValueError('nc not specified. Must specify nc in model.yaml or function arguments.')\n        self.model, self.save = parse_model(deepcopy(self.yaml), ch=ch, verbose=verbose)  # model, savelist\n        self.stride = torch.Tensor([1])  # no stride constraints\n        self.names = {i: f'{i}' for i in range(self.yaml['nc'])}  # default names dict\n        self.info()\n\n    @staticmethod\n    def reshape_outputs(model, nc):\n        \"\"\"Update a TorchVision classification model to class count 'n' if required.\"\"\"\n        name, m = list((model.model if hasattr(model, 'model') else model).named_children())[-1]  # last module\n        if isinstance(m, Classify):  # YOLO Classify() head\n            if m.linear.out_features != nc:\n                m.linear = nn.Linear(m.linear.in_features, nc)\n        elif isinstance(m, nn.Linear):  # ResNet, EfficientNet\n            if m.out_features != nc:\n                setattr(model, name, nn.Linear(m.in_features, nc))\n        elif isinstance(m, nn.Sequential):\n            types = [type(x) for x in m]\n            if nn.Linear in types:\n                i = types.index(nn.Linear)  # nn.Linear index\n                if m[i].out_features != nc:\n                    m[i] = nn.Linear(m[i].in_features, nc)\n            elif nn.Conv2d in types:\n                i = types.index(nn.Conv2d)  # nn.Conv2d index\n                if m[i].out_channels != nc:\n                    m[i] = nn.Conv2d(m[i].in_channels, nc, m[i].kernel_size, m[i].stride, bias=m[i].bias is not None)\n\n\nclass Ensemble(nn.ModuleList):\n    \"\"\"Ensemble of models.\"\"\"\n\n    def __init__(self):\n        \"\"\"Initialize an ensemble of models.\"\"\"\n        super().__init__()\n\n    def forward(self, x, augment=False, profile=False, visualize=False):\n        \"\"\"Function generates the YOLOv5 network's final layer.\"\"\"\n        y = [module(x, augment, profile, visualize)[0] for module in self]\n        # y = torch.stack(y).max(0)[0]  # max ensemble\n        # y = torch.stack(y).mean(0)  # mean ensemble\n        y = torch.cat(y, 2)  # nms ensemble, y shape(B, HW, C)\n        return y, None  # inference, train output\n\n\n# Functions ------------------------------------------------------------------------------------------------------------\n\n\ndef torch_safe_load(weight):\n    \"\"\"\n    This function attempts to load a PyTorch model with the torch.load() function. If a ModuleNotFoundError is raised,\n    it catches the error, logs a warning message, and attempts to install the missing module via the\n    check_requirements() function. After installation, the function again attempts to load the model using torch.load().\n\n    Args:\n        weight (str): The file path of the PyTorch model.\n\n    Returns:\n        (dict): The loaded PyTorch model.\n    \"\"\"\n    from ultralytics.yolo.utils.downloads import attempt_download_asset\n\n    check_suffix(file=weight, suffix='.pt')\n    file = attempt_download_asset(weight)  # search online if missing locally\n    try:\n        return torch.load(file, map_location='cpu'), file  # load\n    except ModuleNotFoundError as e:  # e.name is missing module name\n        if e.name == 'models':\n            raise TypeError(\n                emojis(f'ERROR ❌️ {weight} appears to be an Ultralytics YOLOv5 model originally trained '\n                       f'with https://github.com/ultralytics/yolov5.\\nThis model is NOT forwards compatible with '\n                       f'YOLOv8 at https://github.com/ultralytics/ultralytics.'\n                       f\"\\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to \"\n                       f\"run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt'\")) from e\n        LOGGER.warning(f\"WARNING ⚠️ {weight} appears to require '{e.name}', which is not in ultralytics requirements.\"\n                       f\"\\nAutoInstall will run now for '{e.name}' but this feature will be removed in the future.\"\n                       f\"\\nRecommend fixes are to train a new model using the latest 'ultralytics' package or to \"\n                       f\"run a command with an official YOLOv8 model, i.e. 'yolo predict model=yolov8n.pt'\")\n        check_requirements(e.name)  # install missing module\n\n        return torch.load(file, map_location='cpu'), file  # load\n\n\ndef attempt_load_weights(weights, device=None, inplace=True, fuse=False):\n    \"\"\"Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a.\"\"\"\n\n    ensemble = Ensemble()\n    for w in weights if isinstance(weights, list) else [weights]:\n        ckpt, w = torch_safe_load(w)  # load ckpt\n        args = {**DEFAULT_CFG_DICT, **ckpt['train_args']}  # combine model and default args, preferring model args\n        model = (ckpt.get('ema') or ckpt['model']).to(device).float()  # FP32 model\n\n        # Model compatibility updates\n        model.args = args  # attach args to model\n        model.pt_path = w  # attach *.pt file path to model\n        model.task = guess_model_task(model)\n        if not hasattr(model, 'stride'):\n            model.stride = torch.tensor([32.])\n\n        # Append\n        ensemble.append(model.fuse().eval() if fuse and hasattr(model, 'fuse') else model.eval())  # model in eval mode\n\n    # Module compatibility updates\n    for m in ensemble.modules():\n        t = type(m)\n        if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Segment):\n            m.inplace = inplace  # torch 1.7.0 compatibility\n        elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):\n            m.recompute_scale_factor = None  # torch 1.11.0 compatibility\n\n    # Return model\n    if len(ensemble) == 1:\n        return ensemble[-1]\n\n    # Return ensemble\n    LOGGER.info(f'Ensemble created with {weights}\\n')\n    for k in 'names', 'nc', 'yaml':\n        setattr(ensemble, k, getattr(ensemble[0], k))\n    ensemble.stride = ensemble[torch.argmax(torch.tensor([m.stride.max() for m in ensemble])).int()].stride\n    assert all(ensemble[0].nc == m.nc for m in ensemble), f'Models differ in class counts {[m.nc for m in ensemble]}'\n    return ensemble\n\n\ndef attempt_load_one_weight(weight, device=None, inplace=True, fuse=False):\n    \"\"\"Loads a single model weights.\"\"\"\n    ckpt, weight = torch_safe_load(weight)  # load ckpt\n    args = {**DEFAULT_CFG_DICT, **(ckpt.get('train_args', {}))}  # combine model and default args, preferring model args\n    model = (ckpt.get('ema') or ckpt['model']).to(device).float()  # FP32 model\n\n    # Model compatibility updates\n    model.args = {k: v for k, v in args.items() if k in DEFAULT_CFG_KEYS}  # attach args to model\n    model.pt_path = weight  # attach *.pt file path to model\n    model.task = guess_model_task(model)\n    if not hasattr(model, 'stride'):\n        model.stride = torch.tensor([32.])\n\n    model = model.fuse().eval() if fuse and hasattr(model, 'fuse') else model.eval()  # model in eval mode\n\n    # Module compatibility updates\n    for m in model.modules():\n        t = type(m)\n        if t in (nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Segment):\n            m.inplace = inplace  # torch 1.7.0 compatibility\n        elif t is nn.Upsample and not hasattr(m, 'recompute_scale_factor'):\n            m.recompute_scale_factor = None  # torch 1.11.0 compatibility\n\n    # Return model and ckpt\n    return model, ckpt\n\n\ndef parse_model(d, ch, verbose=True):  # model_dict, input_channels(3)\n    # Parse a YOLO model.yaml dictionary into a PyTorch model\n    import ast\n\n    # Args\n    max_channels = float('inf')\n    nc, act, scales = (d.get(x) for x in ('nc', 'act', 'scales'))\n    depth, width, kpt_shape = (d.get(x, 1.0) for x in ('depth_multiple', 'width_multiple', 'kpt_shape'))\n    if scales:\n        scale = d.get('scale')\n        if not scale:\n            scale = tuple(scales.keys())[0]\n            LOGGER.warning(f\"WARNING ⚠️ no model scale passed. Assuming scale='{scale}'.\")\n        depth, width, max_channels = scales[scale]\n\n    if act:\n        Conv.default_act = eval(act)  # redefine default activation, i.e. Conv.default_act = nn.SiLU()\n        if verbose:\n            LOGGER.info(f\"{colorstr('activation:')} {act}\")  # print\n\n    if verbose:\n        LOGGER.info(f\"\\n{'':>3}{'from':>20}{'n':>3}{'params':>10}  {'module':<45}{'arguments':<30}\")\n    ch = [ch]\n    layers, save, c2 = [], [], ch[-1]  # layers, savelist, ch out\n    for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']):  # from, number, module, args\n        m = getattr(torch.nn, m[3:]) if 'nn.' in m else globals()[m]  # get module\n        for j, a in enumerate(args):\n            if isinstance(a, str):\n                with contextlib.suppress(ValueError):\n                    args[j] = locals()[a] if a in locals() else ast.literal_eval(a)\n\n        n = n_ = max(round(n * depth), 1) if n > 1 else n  # depth gain\n        if m in (Classify, Conv, ConvTranspose, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, Focus,\n                 BottleneckCSP, C1, C2, C2f, C3, C3TR, C3Ghost, nn.ConvTranspose2d, DWConvTranspose2d, C3x, RepC3):\n            c1, c2 = ch[f], args[0]\n            if c2 != nc:  # if c2 not equal to number of classes (i.e. for Classify() output)\n                c2 = make_divisible(min(c2, max_channels) * width, 8)\n\n            args = [c1, c2, *args[1:]]\n            if m in (BottleneckCSP, C1, C2, C2f, C3, C3TR, C3Ghost, C3x, RepC3):\n                args.insert(2, n)  # number of repeats\n                n = 1\n        elif m is AIFI:\n            args = [ch[f], *args]\n        elif m in (HGStem, HGBlock):\n            c1, cm, c2 = ch[f], args[0], args[1]\n            args = [c1, cm, c2, *args[2:]]\n            if m is HGBlock:\n                args.insert(4, n)  # number of repeats\n                n = 1\n\n        elif m is nn.BatchNorm2d:\n            args = [ch[f]]\n        elif m is Concat:\n            c2 = sum(ch[x] for x in f)\n        elif m is Concat_dropout:\n            c2 = ch[-1]\n            ch_list = [ch[x] for x in f]\n        elif m in (Detect, Segment, Pose, RTDETRDecoder):\n            args.append([ch[x] for x in f])\n            if m is Segment:\n                args[2] = make_divisible(min(args[2], max_channels) * width, 8)\n        else:\n            c2 = ch[f]\n        ###### Jiayuan\n        if 'Concat_dropout' in str(m):\n            m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args,ch=ch_list)\n        else:\n            m_ = nn.Sequential(*(m(*args) for _ in range(n))) if n > 1 else m(*args)  # module\n        ######\n        t = str(m)[8:-2].replace('__main__.', '')  # module type\n        m.np = sum(x.numel() for x in m_.parameters())  # number params\n        m_.i, m_.f, m_.type = i, f, t  # attach index, 'from' index, type\n        if verbose:\n            LOGGER.info(f'{i:>3}{str(f):>20}{n_:>3}{m.np:10.0f}  {t:<45}{str(args):<30}')  # print\n        save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1)  # append to savelist\n        layers.append(m_)\n        if i == 0:\n            ch = []\n        ch.append(c2)\n    return nn.Sequential(*layers), sorted(save)\n\n\ndef yaml_model_load(path):\n    \"\"\"Load a YOLOv8 model from a YAML file.\"\"\"\n    import re\n\n    path = Path(path)\n    if path.stem in (f'yolov{d}{x}6' for x in 'nsmlx' for d in (5, 8)):\n        new_stem = re.sub(r'(\\d+)([nslmx])6(.+)?$', r'\\1\\2-p6\\3', path.stem)\n        LOGGER.warning(f'WARNING ⚠️ Ultralytics YOLO P6 models now use -p6 suffix. Renaming {path.stem} to {new_stem}.')\n        path = path.with_stem(new_stem)\n\n    unified_path = re.sub(r'(\\d+)([nslmx])(.+)?$', r'\\1\\3', str(path))  # i.e. yolov8x.yaml -> yolov8.yaml\n    yaml_file = check_yaml(unified_path, hard=False) or check_yaml(path)\n    d = yaml_load(yaml_file)  # model dict\n    if not d.get('scale', False):\n        d['scale'] = guess_model_scale(path)\n    d['yaml_file'] = str(path)\n    return d\n\n\ndef guess_model_scale(model_path):\n    \"\"\"\n    Takes a path to a YOLO model's YAML file as input and extracts the size character of the model's scale.\n    The function uses regular expression matching to find the pattern of the model scale in the YAML file name,\n    which is denoted by n, s, m, l, or x. The function returns the size character of the model scale as a string.\n\n    Args:\n        model_path (str) or (Path): The path to the YOLO model's YAML file.\n\n    Returns:\n        (str): The size character of the model's scale, which can be n, s, m, l, or x.\n    \"\"\"\n    with contextlib.suppress(AttributeError):\n        import re\n        return re.search(r'yolov\\d+([nslmx])', Path(model_path).stem).group(1)  # n, s, m, l, or x\n    return ''\n\n\ndef guess_model_task(model):\n    \"\"\"\n    Guess the task of a PyTorch model from its architecture or configuration.\n\n    Args:\n        model (nn.Module) or (dict): PyTorch model or model configuration in YAML format.\n\n    Returns:\n        (str): Task of the model ('detect', 'segment', 'classify', 'pose').\n\n    Raises:\n        SyntaxError: If the task of the model could not be determined.\n    \"\"\"\n\n    def cfg2task(cfg):\n        \"\"\"Guess from YAML dictionary.\"\"\"\n        m = cfg['head'][-1][-2].lower()  # output module name\n        if m in ('classify', 'classifier', 'cls', 'fc'):\n            return 'classify'\n        if m == 'detect':\n            return 'detect'\n        if m == 'segment':\n            return 'segment'\n        if m == 'pose':\n            return 'pose'\n\n    # Guess from model cfg\n    if isinstance(model, dict):\n        with contextlib.suppress(Exception):\n            return cfg2task(model)\n\n    # Guess from PyTorch model\n    if isinstance(model, nn.Module):  # PyTorch model\n        for x in 'model.args', 'model.model.args', 'model.model.model.args':\n            with contextlib.suppress(Exception):\n                return eval(x)['task']\n        for x in 'model.yaml', 'model.model.yaml', 'model.model.model.yaml':\n            with contextlib.suppress(Exception):\n                return cfg2task(eval(x))\n\n        for m in model.modules():\n            if isinstance(m, Detect):\n                return 'detect'\n            elif isinstance(m, Segment):\n                return 'segment'\n            elif isinstance(m, Classify):\n                return 'classify'\n            elif isinstance(m, Pose):\n                return 'pose'\n\n    # Guess from model filename\n    if isinstance(model, (str, Path)):\n        model = Path(model)\n        if '-seg' in model.stem or 'segment' in model.parts:\n            return 'segment'\n        elif '-cls' in model.stem or 'classify' in model.parts:\n            return 'classify'\n        elif '-pose' in model.stem or 'pose' in model.parts:\n            return 'pose'\n        elif 'detect' in model.parts:\n            return 'detect'\n\n    # Unable to determine task from model\n    LOGGER.warning(\"WARNING ⚠️ Unable to automatically guess model task, assuming 'task=detect'. \"\n                   \"Explicitly define task for your model, i.e. 'task=detect', 'segment', 'classify', or 'pose'.\")\n    return 'detect'  # assume detect\n"
  },
  {
    "path": "ultralytics/predict.py",
    "content": "import sys\nsys.path.insert(0, \"/home/jiayuan/ultralytics-main/ultralytics\")\n\nfrom ultralytics import YOLO\n\n\nnumber = 3 #input how many tasks in your work\nmodel = YOLO('/home/jiayuan/ultralytics-main/ultralytics/runs/best.pt')  # Validate the model\nmodel.predict(source='/data/jiayuan/dash_camara_dataset/daytime', imgsz=(384,672), device=[3],name='v4_daytime', save=True, conf=0.25, iou=0.45, show_labels=False)\n"
  },
  {
    "path": "ultralytics/resum_training.py",
    "content": "import sys\nsys.path.insert(0, \"/home/jiayuan/yolom/ultralytics\")\n# 现在就可以导入Yolo类了\nfrom ultralytics import YOLO\n\n# Load a model\nmodel = YOLO('/home/jiayuan/ultralytics-main/ultralytics/runs/multi/bddmulti-v3-640/weights/last.pt', task='multi')  # build a new model from YAML\n# model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n# model = YOLO('yolov8n.yaml').load('yolov8n.pt')  # build from YAML and transfer weights\n\n# Train the model\nmodel.train(resume=True,batch=12, device=[1,2,3],epochs=200, imgsz=(640,640),name='bddmulti-v3-640', val=True, task='multi')\n"
  },
  {
    "path": "ultralytics/tracker/README.md",
    "content": "# Tracker\n\n## Supported Trackers\n\n- [x] ByteTracker\n- [x] BoT-SORT\n\n## Usage\n\n### python interface:\n\nYou can use the Python interface to track objects using the YOLO model.\n\n```python\nfrom ultralytics import YOLO\n\nmodel = YOLO(\"yolov8n.pt\")  # or a segmentation model .i.e yolov8n-seg.pt\nmodel.track(\n    source=\"video/streams\",\n    stream=True,\n    tracker=\"botsort.yaml\",  # or 'bytetrack.yaml'\n    show=True,\n)\n```\n\nYou can get the IDs of the tracked objects using the following code:\n\n```python\nfrom ultralytics import YOLO\n\nmodel = YOLO(\"yolov8n.pt\")\n\nfor result in model.track(source=\"video.mp4\"):\n    print(\n        result.boxes.id.cpu().numpy().astype(int)\n    )  # this will print the IDs of the tracked objects in the frame\n```\n\nIf you want to use the tracker with a folder of images or when you loop on the video frames, you should use the `persist` parameter to tell the model that these frames are related to each other so the IDs will be fixed for the same objects. Otherwise, the IDs will be different in each frame because in each loop, the model creates a new object for tracking, but the `persist` parameter makes it use the same object for tracking.\n\n```python\nimport cv2\nfrom ultralytics import YOLO\n\ncap = cv2.VideoCapture(\"video.mp4\")\nmodel = YOLO(\"yolov8n.pt\")\nwhile True:\n    ret, frame = cap.read()\n    if not ret:\n        break\n    results = model.track(frame, persist=True)\n    boxes = results[0].boxes.xyxy.cpu().numpy().astype(int)\n    ids = results[0].boxes.id.cpu().numpy().astype(int)\n    for box, id in zip(boxes, ids):\n        cv2.rectangle(frame, (box[0], box[1]), (box[2], box[3]), (0, 255, 0), 2)\n        cv2.putText(\n            frame,\n            f\"Id {id}\",\n            (box[0], box[1]),\n            cv2.FONT_HERSHEY_SIMPLEX,\n            1,\n            (0, 0, 255),\n            2,\n        )\n    cv2.imshow(\"frame\", frame)\n    if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n        break\n```\n\n## Change tracker parameters\n\nYou can change the tracker parameters by eding the `tracker.yaml` file which is located in the ultralytics/tracker/cfg folder.\n\n## Command Line Interface (CLI)\n\nYou can also use the command line interface to track objects using the YOLO model.\n\n```bash\nyolo detect track source=... tracker=...\nyolo segment track source=... tracker=...\nyolo pose track source=... tracker=...\n```\n\nBy default, trackers will use the configuration in `ultralytics/tracker/cfg`.\nWe also support using a modified tracker config file. Please refer to the tracker config files\nin `ultralytics/tracker/cfg`.<br>\n"
  },
  {
    "path": "ultralytics/tracker/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .track import register_tracker\nfrom .trackers import BOTSORT, BYTETracker\n\n__all__ = 'register_tracker', 'BOTSORT', 'BYTETracker'  # allow simpler import\n"
  },
  {
    "path": "ultralytics/tracker/cfg/botsort.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Default YOLO tracker settings for BoT-SORT tracker https://github.com/NirAharon/BoT-SORT\n\ntracker_type: botsort  # tracker type, ['botsort', 'bytetrack']\ntrack_high_thresh: 0.5  # threshold for the first association\ntrack_low_thresh: 0.1  # threshold for the second association\nnew_track_thresh: 0.6  # threshold for init new track if the detection does not match any tracks\ntrack_buffer: 30  # buffer to calculate the time when to remove tracks\nmatch_thresh: 0.8  # threshold for matching tracks\n# min_box_area: 10  # threshold for min box areas(for tracker evaluation, not used for now)\n# mot20: False  # for tracker evaluation(not used for now)\n\n# BoT-SORT settings\ncmc_method: sparseOptFlow  # method of global motion compensation\n# ReID model related thresh (not supported yet)\nproximity_thresh: 0.5\nappearance_thresh: 0.25\nwith_reid: False\n"
  },
  {
    "path": "ultralytics/tracker/cfg/bytetrack.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Default YOLO tracker settings for ByteTrack tracker https://github.com/ifzhang/ByteTrack\n\ntracker_type: bytetrack  # tracker type, ['botsort', 'bytetrack']\ntrack_high_thresh: 0.5  # threshold for the first association\ntrack_low_thresh: 0.1  # threshold for the second association\nnew_track_thresh: 0.6  # threshold for init new track if the detection does not match any tracks\ntrack_buffer: 30  # buffer to calculate the time when to remove tracks\nmatch_thresh: 0.8  # threshold for matching tracks\n# min_box_area: 10  # threshold for min box areas(for tracker evaluation, not used for now)\n# mot20: False  # for tracker evaluation(not used for now)\n"
  },
  {
    "path": "ultralytics/tracker/track.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom functools import partial\n\nimport torch\n\nfrom ultralytics.yolo.utils import IterableSimpleNamespace, yaml_load\nfrom ultralytics.yolo.utils.checks import check_yaml\n\nfrom .trackers import BOTSORT, BYTETracker\n\nTRACKER_MAP = {'bytetrack': BYTETracker, 'botsort': BOTSORT}\n\n\ndef on_predict_start(predictor, persist=False):\n    \"\"\"\n    Initialize trackers for object tracking during prediction.\n\n    Args:\n        predictor (object): The predictor object to initialize trackers for.\n        persist (bool, optional): Whether to persist the trackers if they already exist. Defaults to False.\n\n    Raises:\n        AssertionError: If the tracker_type is not 'bytetrack' or 'botsort'.\n    \"\"\"\n    if hasattr(predictor, 'trackers') and persist:\n        return\n    tracker = check_yaml(predictor.args.tracker)\n    cfg = IterableSimpleNamespace(**yaml_load(tracker))\n    assert cfg.tracker_type in ['bytetrack', 'botsort'], \\\n        f\"Only support 'bytetrack' and 'botsort' for now, but got '{cfg.tracker_type}'\"\n    trackers = []\n    for _ in range(predictor.dataset.bs):\n        tracker = TRACKER_MAP[cfg.tracker_type](args=cfg, frame_rate=30)\n        trackers.append(tracker)\n    predictor.trackers = trackers\n\n\ndef on_predict_postprocess_end(predictor):\n    \"\"\"Postprocess detected boxes and update with object tracking.\"\"\"\n    bs = predictor.dataset.bs\n    im0s = predictor.batch[1]\n    for i in range(bs):\n        det = predictor.results[i].boxes.cpu().numpy()\n        if len(det) == 0:\n            continue\n        tracks = predictor.trackers[i].update(det, im0s[i])\n        if len(tracks) == 0:\n            continue\n        idx = tracks[:, -1].astype(int)\n        predictor.results[i] = predictor.results[i][idx]\n        predictor.results[i].update(boxes=torch.as_tensor(tracks[:, :-1]))\n\n\ndef register_tracker(model, persist):\n    \"\"\"\n    Register tracking callbacks to the model for object tracking during prediction.\n\n    Args:\n        model (object): The model object to register tracking callbacks for.\n        persist (bool): Whether to persist the trackers if they already exist.\n\n    \"\"\"\n    model.add_callback('on_predict_start', partial(on_predict_start, persist=persist))\n    model.add_callback('on_predict_postprocess_end', on_predict_postprocess_end)\n"
  },
  {
    "path": "ultralytics/tracker/trackers/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .bot_sort import BOTSORT\nfrom .byte_tracker import BYTETracker\n\n__all__ = 'BOTSORT', 'BYTETracker'  # allow simpler import\n"
  },
  {
    "path": "ultralytics/tracker/trackers/basetrack.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom collections import OrderedDict\n\nimport numpy as np\n\n\nclass TrackState:\n    \"\"\"Enumeration of possible object tracking states.\"\"\"\n\n    New = 0\n    Tracked = 1\n    Lost = 2\n    Removed = 3\n\n\nclass BaseTrack:\n    \"\"\"Base class for object tracking, handling basic track attributes and operations.\"\"\"\n\n    _count = 0\n\n    track_id = 0\n    is_activated = False\n    state = TrackState.New\n\n    history = OrderedDict()\n    features = []\n    curr_feature = None\n    score = 0\n    start_frame = 0\n    frame_id = 0\n    time_since_update = 0\n\n    # Multi-camera\n    location = (np.inf, np.inf)\n\n    @property\n    def end_frame(self):\n        \"\"\"Return the last frame ID of the track.\"\"\"\n        return self.frame_id\n\n    @staticmethod\n    def next_id():\n        \"\"\"Increment and return the global track ID counter.\"\"\"\n        BaseTrack._count += 1\n        return BaseTrack._count\n\n    def activate(self, *args):\n        \"\"\"Activate the track with the provided arguments.\"\"\"\n        raise NotImplementedError\n\n    def predict(self):\n        \"\"\"Predict the next state of the track.\"\"\"\n        raise NotImplementedError\n\n    def update(self, *args, **kwargs):\n        \"\"\"Update the track with new observations.\"\"\"\n        raise NotImplementedError\n\n    def mark_lost(self):\n        \"\"\"Mark the track as lost.\"\"\"\n        self.state = TrackState.Lost\n\n    def mark_removed(self):\n        \"\"\"Mark the track as removed.\"\"\"\n        self.state = TrackState.Removed\n\n    @staticmethod\n    def reset_id():\n        \"\"\"Reset the global track ID counter.\"\"\"\n        BaseTrack._count = 0\n"
  },
  {
    "path": "ultralytics/tracker/trackers/bot_sort.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom collections import deque\n\nimport numpy as np\n\nfrom ..utils import matching\nfrom ..utils.gmc import GMC\nfrom ..utils.kalman_filter import KalmanFilterXYWH\nfrom .basetrack import TrackState\nfrom .byte_tracker import BYTETracker, STrack\n\n\nclass BOTrack(STrack):\n    shared_kalman = KalmanFilterXYWH()\n\n    def __init__(self, tlwh, score, cls, feat=None, feat_history=50):\n        \"\"\"Initialize YOLOv8 object with temporal parameters, such as feature history, alpha and current features.\"\"\"\n        super().__init__(tlwh, score, cls)\n\n        self.smooth_feat = None\n        self.curr_feat = None\n        if feat is not None:\n            self.update_features(feat)\n        self.features = deque([], maxlen=feat_history)\n        self.alpha = 0.9\n\n    def update_features(self, feat):\n        \"\"\"Update features vector and smooth it using exponential moving average.\"\"\"\n        feat /= np.linalg.norm(feat)\n        self.curr_feat = feat\n        if self.smooth_feat is None:\n            self.smooth_feat = feat\n        else:\n            self.smooth_feat = self.alpha * self.smooth_feat + (1 - self.alpha) * feat\n        self.features.append(feat)\n        self.smooth_feat /= np.linalg.norm(self.smooth_feat)\n\n    def predict(self):\n        \"\"\"Predicts the mean and covariance using Kalman filter.\"\"\"\n        mean_state = self.mean.copy()\n        if self.state != TrackState.Tracked:\n            mean_state[6] = 0\n            mean_state[7] = 0\n\n        self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)\n\n    def re_activate(self, new_track, frame_id, new_id=False):\n        \"\"\"Reactivates a track with updated features and optionally assigns a new ID.\"\"\"\n        if new_track.curr_feat is not None:\n            self.update_features(new_track.curr_feat)\n        super().re_activate(new_track, frame_id, new_id)\n\n    def update(self, new_track, frame_id):\n        \"\"\"Update the YOLOv8 instance with new track and frame ID.\"\"\"\n        if new_track.curr_feat is not None:\n            self.update_features(new_track.curr_feat)\n        super().update(new_track, frame_id)\n\n    @property\n    def tlwh(self):\n        \"\"\"Get current position in bounding box format `(top left x, top left y,\n        width, height)`.\n        \"\"\"\n        if self.mean is None:\n            return self._tlwh.copy()\n        ret = self.mean[:4].copy()\n        ret[:2] -= ret[2:] / 2\n        return ret\n\n    @staticmethod\n    def multi_predict(stracks):\n        \"\"\"Predicts the mean and covariance of multiple object tracks using shared Kalman filter.\"\"\"\n        if len(stracks) <= 0:\n            return\n        multi_mean = np.asarray([st.mean.copy() for st in stracks])\n        multi_covariance = np.asarray([st.covariance for st in stracks])\n        for i, st in enumerate(stracks):\n            if st.state != TrackState.Tracked:\n                multi_mean[i][6] = 0\n                multi_mean[i][7] = 0\n        multi_mean, multi_covariance = BOTrack.shared_kalman.multi_predict(multi_mean, multi_covariance)\n        for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):\n            stracks[i].mean = mean\n            stracks[i].covariance = cov\n\n    def convert_coords(self, tlwh):\n        \"\"\"Converts Top-Left-Width-Height bounding box coordinates to X-Y-Width-Height format.\"\"\"\n        return self.tlwh_to_xywh(tlwh)\n\n    @staticmethod\n    def tlwh_to_xywh(tlwh):\n        \"\"\"Convert bounding box to format `(center x, center y, width,\n        height)`.\n        \"\"\"\n        ret = np.asarray(tlwh).copy()\n        ret[:2] += ret[2:] / 2\n        return ret\n\n\nclass BOTSORT(BYTETracker):\n\n    def __init__(self, args, frame_rate=30):\n        \"\"\"Initialize YOLOv8 object with ReID module and GMC algorithm.\"\"\"\n        super().__init__(args, frame_rate)\n        # ReID module\n        self.proximity_thresh = args.proximity_thresh\n        self.appearance_thresh = args.appearance_thresh\n\n        if args.with_reid:\n            # Haven't supported BoT-SORT(reid) yet\n            self.encoder = None\n        # self.gmc = GMC(method=args.cmc_method, verbose=[args.name, args.ablation])\n        self.gmc = GMC(method=args.cmc_method)\n\n    def get_kalmanfilter(self):\n        \"\"\"Returns an instance of KalmanFilterXYWH for object tracking.\"\"\"\n        return KalmanFilterXYWH()\n\n    def init_track(self, dets, scores, cls, img=None):\n        \"\"\"Initialize track with detections, scores, and classes.\"\"\"\n        if len(dets) == 0:\n            return []\n        if self.args.with_reid and self.encoder is not None:\n            features_keep = self.encoder.inference(img, dets)\n            return [BOTrack(xyxy, s, c, f) for (xyxy, s, c, f) in zip(dets, scores, cls, features_keep)]  # detections\n        else:\n            return [BOTrack(xyxy, s, c) for (xyxy, s, c) in zip(dets, scores, cls)]  # detections\n\n    def get_dists(self, tracks, detections):\n        \"\"\"Get distances between tracks and detections using IoU and (optionally) ReID embeddings.\"\"\"\n        dists = matching.iou_distance(tracks, detections)\n        dists_mask = (dists > self.proximity_thresh)\n\n        # TODO: mot20\n        # if not self.args.mot20:\n        dists = matching.fuse_score(dists, detections)\n\n        if self.args.with_reid and self.encoder is not None:\n            emb_dists = matching.embedding_distance(tracks, detections) / 2.0\n            emb_dists[emb_dists > self.appearance_thresh] = 1.0\n            emb_dists[dists_mask] = 1.0\n            dists = np.minimum(dists, emb_dists)\n        return dists\n\n    def multi_predict(self, tracks):\n        \"\"\"Predict and track multiple objects with YOLOv8 model.\"\"\"\n        BOTrack.multi_predict(tracks)\n"
  },
  {
    "path": "ultralytics/tracker/trackers/byte_tracker.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport numpy as np\n\nfrom ..utils import matching\nfrom ..utils.kalman_filter import KalmanFilterXYAH\nfrom .basetrack import BaseTrack, TrackState\n\n\nclass STrack(BaseTrack):\n    shared_kalman = KalmanFilterXYAH()\n\n    def __init__(self, tlwh, score, cls):\n        \"\"\"wait activate.\"\"\"\n        self._tlwh = np.asarray(self.tlbr_to_tlwh(tlwh[:-1]), dtype=np.float32)\n        self.kalman_filter = None\n        self.mean, self.covariance = None, None\n        self.is_activated = False\n\n        self.score = score\n        self.tracklet_len = 0\n        self.cls = cls\n        self.idx = tlwh[-1]\n\n    def predict(self):\n        \"\"\"Predicts mean and covariance using Kalman filter.\"\"\"\n        mean_state = self.mean.copy()\n        if self.state != TrackState.Tracked:\n            mean_state[7] = 0\n        self.mean, self.covariance = self.kalman_filter.predict(mean_state, self.covariance)\n\n    @staticmethod\n    def multi_predict(stracks):\n        \"\"\"Perform multi-object predictive tracking using Kalman filter for given stracks.\"\"\"\n        if len(stracks) <= 0:\n            return\n        multi_mean = np.asarray([st.mean.copy() for st in stracks])\n        multi_covariance = np.asarray([st.covariance for st in stracks])\n        for i, st in enumerate(stracks):\n            if st.state != TrackState.Tracked:\n                multi_mean[i][7] = 0\n        multi_mean, multi_covariance = STrack.shared_kalman.multi_predict(multi_mean, multi_covariance)\n        for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):\n            stracks[i].mean = mean\n            stracks[i].covariance = cov\n\n    @staticmethod\n    def multi_gmc(stracks, H=np.eye(2, 3)):\n        \"\"\"Update state tracks positions and covariances using a homography matrix.\"\"\"\n        if len(stracks) > 0:\n            multi_mean = np.asarray([st.mean.copy() for st in stracks])\n            multi_covariance = np.asarray([st.covariance for st in stracks])\n\n            R = H[:2, :2]\n            R8x8 = np.kron(np.eye(4, dtype=float), R)\n            t = H[:2, 2]\n\n            for i, (mean, cov) in enumerate(zip(multi_mean, multi_covariance)):\n                mean = R8x8.dot(mean)\n                mean[:2] += t\n                cov = R8x8.dot(cov).dot(R8x8.transpose())\n\n                stracks[i].mean = mean\n                stracks[i].covariance = cov\n\n    def activate(self, kalman_filter, frame_id):\n        \"\"\"Start a new tracklet.\"\"\"\n        self.kalman_filter = kalman_filter\n        self.track_id = self.next_id()\n        self.mean, self.covariance = self.kalman_filter.initiate(self.convert_coords(self._tlwh))\n\n        self.tracklet_len = 0\n        self.state = TrackState.Tracked\n        if frame_id == 1:\n            self.is_activated = True\n        self.frame_id = frame_id\n        self.start_frame = frame_id\n\n    def re_activate(self, new_track, frame_id, new_id=False):\n        \"\"\"Reactivates a previously lost track with a new detection.\"\"\"\n        self.mean, self.covariance = self.kalman_filter.update(self.mean, self.covariance,\n                                                               self.convert_coords(new_track.tlwh))\n        self.tracklet_len = 0\n        self.state = TrackState.Tracked\n        self.is_activated = True\n        self.frame_id = frame_id\n        if new_id:\n            self.track_id = self.next_id()\n        self.score = new_track.score\n        self.cls = new_track.cls\n        self.idx = new_track.idx\n\n    def update(self, new_track, frame_id):\n        \"\"\"\n        Update a matched track\n        :type new_track: STrack\n        :type frame_id: int\n        :return:\n        \"\"\"\n        self.frame_id = frame_id\n        self.tracklet_len += 1\n\n        new_tlwh = new_track.tlwh\n        self.mean, self.covariance = self.kalman_filter.update(self.mean, self.covariance,\n                                                               self.convert_coords(new_tlwh))\n        self.state = TrackState.Tracked\n        self.is_activated = True\n\n        self.score = new_track.score\n        self.cls = new_track.cls\n        self.idx = new_track.idx\n\n    def convert_coords(self, tlwh):\n        \"\"\"Convert a bounding box's top-left-width-height format to its x-y-angle-height equivalent.\"\"\"\n        return self.tlwh_to_xyah(tlwh)\n\n    @property\n    def tlwh(self):\n        \"\"\"Get current position in bounding box format `(top left x, top left y,\n        width, height)`.\n        \"\"\"\n        if self.mean is None:\n            return self._tlwh.copy()\n        ret = self.mean[:4].copy()\n        ret[2] *= ret[3]\n        ret[:2] -= ret[2:] / 2\n        return ret\n\n    @property\n    def tlbr(self):\n        \"\"\"Convert bounding box to format `(min x, min y, max x, max y)`, i.e.,\n        `(top left, bottom right)`.\n        \"\"\"\n        ret = self.tlwh.copy()\n        ret[2:] += ret[:2]\n        return ret\n\n    @staticmethod\n    def tlwh_to_xyah(tlwh):\n        \"\"\"Convert bounding box to format `(center x, center y, aspect ratio,\n        height)`, where the aspect ratio is `width / height`.\n        \"\"\"\n        ret = np.asarray(tlwh).copy()\n        ret[:2] += ret[2:] / 2\n        ret[2] /= ret[3]\n        return ret\n\n    @staticmethod\n    def tlbr_to_tlwh(tlbr):\n        \"\"\"Converts top-left bottom-right format to top-left width height format.\"\"\"\n        ret = np.asarray(tlbr).copy()\n        ret[2:] -= ret[:2]\n        return ret\n\n    @staticmethod\n    def tlwh_to_tlbr(tlwh):\n        \"\"\"Converts tlwh bounding box format to tlbr format.\"\"\"\n        ret = np.asarray(tlwh).copy()\n        ret[2:] += ret[:2]\n        return ret\n\n    def __repr__(self):\n        \"\"\"Return a string representation of the BYTETracker object with start and end frames and track ID.\"\"\"\n        return f'OT_{self.track_id}_({self.start_frame}-{self.end_frame})'\n\n\nclass BYTETracker:\n\n    def __init__(self, args, frame_rate=30):\n        \"\"\"Initialize a YOLOv8 object to track objects with given arguments and frame rate.\"\"\"\n        self.tracked_stracks = []  # type: list[STrack]\n        self.lost_stracks = []  # type: list[STrack]\n        self.removed_stracks = []  # type: list[STrack]\n\n        self.frame_id = 0\n        self.args = args\n        self.max_time_lost = int(frame_rate / 30.0 * args.track_buffer)\n        self.kalman_filter = self.get_kalmanfilter()\n        self.reset_id()\n\n    def update(self, results, img=None):\n        \"\"\"Updates object tracker with new detections and returns tracked object bounding boxes.\"\"\"\n        self.frame_id += 1\n        activated_stracks = []\n        refind_stracks = []\n        lost_stracks = []\n        removed_stracks = []\n\n        scores = results.conf\n        bboxes = results.xyxy\n        # Add index\n        bboxes = np.concatenate([bboxes, np.arange(len(bboxes)).reshape(-1, 1)], axis=-1)\n        cls = results.cls\n\n        remain_inds = scores > self.args.track_high_thresh\n        inds_low = scores > self.args.track_low_thresh\n        inds_high = scores < self.args.track_high_thresh\n\n        inds_second = np.logical_and(inds_low, inds_high)\n        dets_second = bboxes[inds_second]\n        dets = bboxes[remain_inds]\n        scores_keep = scores[remain_inds]\n        scores_second = scores[inds_second]\n        cls_keep = cls[remain_inds]\n        cls_second = cls[inds_second]\n\n        detections = self.init_track(dets, scores_keep, cls_keep, img)\n        # Add newly detected tracklets to tracked_stracks\n        unconfirmed = []\n        tracked_stracks = []  # type: list[STrack]\n        for track in self.tracked_stracks:\n            if not track.is_activated:\n                unconfirmed.append(track)\n            else:\n                tracked_stracks.append(track)\n        # Step 2: First association, with high score detection boxes\n        strack_pool = self.joint_stracks(tracked_stracks, self.lost_stracks)\n        # Predict the current location with KF\n        self.multi_predict(strack_pool)\n        if hasattr(self, 'gmc') and img is not None:\n            warp = self.gmc.apply(img, dets)\n            STrack.multi_gmc(strack_pool, warp)\n            STrack.multi_gmc(unconfirmed, warp)\n\n        dists = self.get_dists(strack_pool, detections)\n        matches, u_track, u_detection = matching.linear_assignment(dists, thresh=self.args.match_thresh)\n\n        for itracked, idet in matches:\n            track = strack_pool[itracked]\n            det = detections[idet]\n            if track.state == TrackState.Tracked:\n                track.update(det, self.frame_id)\n                activated_stracks.append(track)\n            else:\n                track.re_activate(det, self.frame_id, new_id=False)\n                refind_stracks.append(track)\n        # Step 3: Second association, with low score detection boxes\n        # association the untrack to the low score detections\n        detections_second = self.init_track(dets_second, scores_second, cls_second, img)\n        r_tracked_stracks = [strack_pool[i] for i in u_track if strack_pool[i].state == TrackState.Tracked]\n        # TODO\n        dists = matching.iou_distance(r_tracked_stracks, detections_second)\n        matches, u_track, u_detection_second = matching.linear_assignment(dists, thresh=0.5)\n        for itracked, idet in matches:\n            track = r_tracked_stracks[itracked]\n            det = detections_second[idet]\n            if track.state == TrackState.Tracked:\n                track.update(det, self.frame_id)\n                activated_stracks.append(track)\n            else:\n                track.re_activate(det, self.frame_id, new_id=False)\n                refind_stracks.append(track)\n\n        for it in u_track:\n            track = r_tracked_stracks[it]\n            if track.state != TrackState.Lost:\n                track.mark_lost()\n                lost_stracks.append(track)\n        # Deal with unconfirmed tracks, usually tracks with only one beginning frame\n        detections = [detections[i] for i in u_detection]\n        dists = self.get_dists(unconfirmed, detections)\n        matches, u_unconfirmed, u_detection = matching.linear_assignment(dists, thresh=0.7)\n        for itracked, idet in matches:\n            unconfirmed[itracked].update(detections[idet], self.frame_id)\n            activated_stracks.append(unconfirmed[itracked])\n        for it in u_unconfirmed:\n            track = unconfirmed[it]\n            track.mark_removed()\n            removed_stracks.append(track)\n        # Step 4: Init new stracks\n        for inew in u_detection:\n            track = detections[inew]\n            if track.score < self.args.new_track_thresh:\n                continue\n            track.activate(self.kalman_filter, self.frame_id)\n            activated_stracks.append(track)\n        # Step 5: Update state\n        for track in self.lost_stracks:\n            if self.frame_id - track.end_frame > self.max_time_lost:\n                track.mark_removed()\n                removed_stracks.append(track)\n\n        self.tracked_stracks = [t for t in self.tracked_stracks if t.state == TrackState.Tracked]\n        self.tracked_stracks = self.joint_stracks(self.tracked_stracks, activated_stracks)\n        self.tracked_stracks = self.joint_stracks(self.tracked_stracks, refind_stracks)\n        self.lost_stracks = self.sub_stracks(self.lost_stracks, self.tracked_stracks)\n        self.lost_stracks.extend(lost_stracks)\n        self.lost_stracks = self.sub_stracks(self.lost_stracks, self.removed_stracks)\n        self.tracked_stracks, self.lost_stracks = self.remove_duplicate_stracks(self.tracked_stracks, self.lost_stracks)\n        self.removed_stracks.extend(removed_stracks)\n        if len(self.removed_stracks) > 1000:\n            self.removed_stracks = self.removed_stracks[-999:]  # clip remove stracks to 1000 maximum\n        return np.asarray(\n            [x.tlbr.tolist() + [x.track_id, x.score, x.cls, x.idx] for x in self.tracked_stracks if x.is_activated],\n            dtype=np.float32)\n\n    def get_kalmanfilter(self):\n        \"\"\"Returns a Kalman filter object for tracking bounding boxes.\"\"\"\n        return KalmanFilterXYAH()\n\n    def init_track(self, dets, scores, cls, img=None):\n        \"\"\"Initialize object tracking with detections and scores using STrack algorithm.\"\"\"\n        return [STrack(xyxy, s, c) for (xyxy, s, c) in zip(dets, scores, cls)] if len(dets) else []  # detections\n\n    def get_dists(self, tracks, detections):\n        \"\"\"Calculates the distance between tracks and detections using IOU and fuses scores.\"\"\"\n        dists = matching.iou_distance(tracks, detections)\n        # TODO: mot20\n        # if not self.args.mot20:\n        dists = matching.fuse_score(dists, detections)\n        return dists\n\n    def multi_predict(self, tracks):\n        \"\"\"Returns the predicted tracks using the YOLOv8 network.\"\"\"\n        STrack.multi_predict(tracks)\n\n    def reset_id(self):\n        \"\"\"Resets the ID counter of STrack.\"\"\"\n        STrack.reset_id()\n\n    @staticmethod\n    def joint_stracks(tlista, tlistb):\n        \"\"\"Combine two lists of stracks into a single one.\"\"\"\n        exists = {}\n        res = []\n        for t in tlista:\n            exists[t.track_id] = 1\n            res.append(t)\n        for t in tlistb:\n            tid = t.track_id\n            if not exists.get(tid, 0):\n                exists[tid] = 1\n                res.append(t)\n        return res\n\n    @staticmethod\n    def sub_stracks(tlista, tlistb):\n        \"\"\"DEPRECATED CODE in https://github.com/ultralytics/ultralytics/pull/1890/\n        stracks = {t.track_id: t for t in tlista}\n        for t in tlistb:\n            tid = t.track_id\n            if stracks.get(tid, 0):\n                del stracks[tid]\n        return list(stracks.values())\n        \"\"\"\n        track_ids_b = {t.track_id for t in tlistb}\n        return [t for t in tlista if t.track_id not in track_ids_b]\n\n    @staticmethod\n    def remove_duplicate_stracks(stracksa, stracksb):\n        \"\"\"Remove duplicate stracks with non-maximum IOU distance.\"\"\"\n        pdist = matching.iou_distance(stracksa, stracksb)\n        pairs = np.where(pdist < 0.15)\n        dupa, dupb = [], []\n        for p, q in zip(*pairs):\n            timep = stracksa[p].frame_id - stracksa[p].start_frame\n            timeq = stracksb[q].frame_id - stracksb[q].start_frame\n            if timep > timeq:\n                dupb.append(q)\n            else:\n                dupa.append(p)\n        resa = [t for i, t in enumerate(stracksa) if i not in dupa]\n        resb = [t for i, t in enumerate(stracksb) if i not in dupb]\n        return resa, resb\n"
  },
  {
    "path": "ultralytics/tracker/utils/__init__.py",
    "content": ""
  },
  {
    "path": "ultralytics/tracker/utils/gmc.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport copy\n\nimport cv2\nimport numpy as np\n\nfrom ultralytics.yolo.utils import LOGGER\n\n\nclass GMC:\n\n    def __init__(self, method='sparseOptFlow', downscale=2, verbose=None):\n        \"\"\"Initialize a video tracker with specified parameters.\"\"\"\n        super().__init__()\n\n        self.method = method\n        self.downscale = max(1, int(downscale))\n\n        if self.method == 'orb':\n            self.detector = cv2.FastFeatureDetector_create(20)\n            self.extractor = cv2.ORB_create()\n            self.matcher = cv2.BFMatcher(cv2.NORM_HAMMING)\n\n        elif self.method == 'sift':\n            self.detector = cv2.SIFT_create(nOctaveLayers=3, contrastThreshold=0.02, edgeThreshold=20)\n            self.extractor = cv2.SIFT_create(nOctaveLayers=3, contrastThreshold=0.02, edgeThreshold=20)\n            self.matcher = cv2.BFMatcher(cv2.NORM_L2)\n\n        elif self.method == 'ecc':\n            number_of_iterations = 5000\n            termination_eps = 1e-6\n            self.warp_mode = cv2.MOTION_EUCLIDEAN\n            self.criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, number_of_iterations, termination_eps)\n\n        elif self.method == 'sparseOptFlow':\n            self.feature_params = dict(maxCorners=1000,\n                                       qualityLevel=0.01,\n                                       minDistance=1,\n                                       blockSize=3,\n                                       useHarrisDetector=False,\n                                       k=0.04)\n            # self.gmc_file = open('GMC_results.txt', 'w')\n\n        elif self.method in ['file', 'files']:\n            seqName = verbose[0]\n            ablation = verbose[1]\n            if ablation:\n                filePath = r'tracker/GMC_files/MOT17_ablation'\n            else:\n                filePath = r'tracker/GMC_files/MOTChallenge'\n\n            if '-FRCNN' in seqName:\n                seqName = seqName[:-6]\n            elif '-DPM' in seqName or '-SDP' in seqName:\n                seqName = seqName[:-4]\n            self.gmcFile = open(f'{filePath}/GMC-{seqName}.txt')\n\n            if self.gmcFile is None:\n                raise ValueError(f'Error: Unable to open GMC file in directory:{filePath}')\n        elif self.method in ['none', 'None']:\n            self.method = 'none'\n        else:\n            raise ValueError(f'Error: Unknown CMC method:{method}')\n\n        self.prevFrame = None\n        self.prevKeyPoints = None\n        self.prevDescriptors = None\n\n        self.initializedFirstFrame = False\n\n    def apply(self, raw_frame, detections=None):\n        \"\"\"Apply object detection on a raw frame using specified method.\"\"\"\n        if self.method in ['orb', 'sift']:\n            return self.applyFeatures(raw_frame, detections)\n        elif self.method == 'ecc':\n            return self.applyEcc(raw_frame, detections)\n        elif self.method == 'sparseOptFlow':\n            return self.applySparseOptFlow(raw_frame, detections)\n        elif self.method == 'file':\n            return self.applyFile(raw_frame, detections)\n        elif self.method == 'none':\n            return np.eye(2, 3)\n        else:\n            return np.eye(2, 3)\n\n    def applyEcc(self, raw_frame, detections=None):\n        \"\"\"Initialize.\"\"\"\n        height, width, _ = raw_frame.shape\n        frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY)\n        H = np.eye(2, 3, dtype=np.float32)\n\n        # Downscale image (TODO: consider using pyramids)\n        if self.downscale > 1.0:\n            frame = cv2.GaussianBlur(frame, (3, 3), 1.5)\n            frame = cv2.resize(frame, (width // self.downscale, height // self.downscale))\n            width = width // self.downscale\n            height = height // self.downscale\n\n        # Handle first frame\n        if not self.initializedFirstFrame:\n            # Initialize data\n            self.prevFrame = frame.copy()\n\n            # Initialization done\n            self.initializedFirstFrame = True\n\n            return H\n\n        # Run the ECC algorithm. The results are stored in warp_matrix.\n        # (cc, H) = cv2.findTransformECC(self.prevFrame, frame, H, self.warp_mode, self.criteria)\n        try:\n            (cc, H) = cv2.findTransformECC(self.prevFrame, frame, H, self.warp_mode, self.criteria, None, 1)\n        except Exception as e:\n            LOGGER.warning(f'WARNING: find transform failed. Set warp as identity {e}')\n\n        return H\n\n    def applyFeatures(self, raw_frame, detections=None):\n        \"\"\"Initialize.\"\"\"\n        height, width, _ = raw_frame.shape\n        frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY)\n        H = np.eye(2, 3)\n\n        # Downscale image (TODO: consider using pyramids)\n        if self.downscale > 1.0:\n            # frame = cv2.GaussianBlur(frame, (3, 3), 1.5)\n            frame = cv2.resize(frame, (width // self.downscale, height // self.downscale))\n            width = width // self.downscale\n            height = height // self.downscale\n\n        # Find the keypoints\n        mask = np.zeros_like(frame)\n        # mask[int(0.05 * height): int(0.95 * height), int(0.05 * width): int(0.95 * width)] = 255\n        mask[int(0.02 * height):int(0.98 * height), int(0.02 * width):int(0.98 * width)] = 255\n        if detections is not None:\n            for det in detections:\n                tlbr = (det[:4] / self.downscale).astype(np.int_)\n                mask[tlbr[1]:tlbr[3], tlbr[0]:tlbr[2]] = 0\n\n        keypoints = self.detector.detect(frame, mask)\n\n        # Compute the descriptors\n        keypoints, descriptors = self.extractor.compute(frame, keypoints)\n\n        # Handle first frame\n        if not self.initializedFirstFrame:\n            # Initialize data\n            self.prevFrame = frame.copy()\n            self.prevKeyPoints = copy.copy(keypoints)\n            self.prevDescriptors = copy.copy(descriptors)\n\n            # Initialization done\n            self.initializedFirstFrame = True\n\n            return H\n\n        # Match descriptors.\n        knnMatches = self.matcher.knnMatch(self.prevDescriptors, descriptors, 2)\n\n        # Filtered matches based on smallest spatial distance\n        matches = []\n        spatialDistances = []\n\n        maxSpatialDistance = 0.25 * np.array([width, height])\n\n        # Handle empty matches case\n        if len(knnMatches) == 0:\n            # Store to next iteration\n            self.prevFrame = frame.copy()\n            self.prevKeyPoints = copy.copy(keypoints)\n            self.prevDescriptors = copy.copy(descriptors)\n\n            return H\n\n        for m, n in knnMatches:\n            if m.distance < 0.9 * n.distance:\n                prevKeyPointLocation = self.prevKeyPoints[m.queryIdx].pt\n                currKeyPointLocation = keypoints[m.trainIdx].pt\n\n                spatialDistance = (prevKeyPointLocation[0] - currKeyPointLocation[0],\n                                   prevKeyPointLocation[1] - currKeyPointLocation[1])\n\n                if (np.abs(spatialDistance[0]) < maxSpatialDistance[0]) and \\\n                        (np.abs(spatialDistance[1]) < maxSpatialDistance[1]):\n                    spatialDistances.append(spatialDistance)\n                    matches.append(m)\n\n        meanSpatialDistances = np.mean(spatialDistances, 0)\n        stdSpatialDistances = np.std(spatialDistances, 0)\n\n        inliers = (spatialDistances - meanSpatialDistances) < 2.5 * stdSpatialDistances\n\n        goodMatches = []\n        prevPoints = []\n        currPoints = []\n        for i in range(len(matches)):\n            if inliers[i, 0] and inliers[i, 1]:\n                goodMatches.append(matches[i])\n                prevPoints.append(self.prevKeyPoints[matches[i].queryIdx].pt)\n                currPoints.append(keypoints[matches[i].trainIdx].pt)\n\n        prevPoints = np.array(prevPoints)\n        currPoints = np.array(currPoints)\n\n        # Draw the keypoint matches on the output image\n        # if False:\n        #     import matplotlib.pyplot as plt\n        #     matches_img = np.hstack((self.prevFrame, frame))\n        #     matches_img = cv2.cvtColor(matches_img, cv2.COLOR_GRAY2BGR)\n        #     W = np.size(self.prevFrame, 1)\n        #     for m in goodMatches:\n        #         prev_pt = np.array(self.prevKeyPoints[m.queryIdx].pt, dtype=np.int_)\n        #         curr_pt = np.array(keypoints[m.trainIdx].pt, dtype=np.int_)\n        #         curr_pt[0] += W\n        #         color = np.random.randint(0, 255, 3)\n        #         color = (int(color[0]), int(color[1]), int(color[2]))\n        #\n        #         matches_img = cv2.line(matches_img, prev_pt, curr_pt, tuple(color), 1, cv2.LINE_AA)\n        #         matches_img = cv2.circle(matches_img, prev_pt, 2, tuple(color), -1)\n        #         matches_img = cv2.circle(matches_img, curr_pt, 2, tuple(color), -1)\n        #\n        #     plt.figure()\n        #     plt.imshow(matches_img)\n        #     plt.show()\n\n        # Find rigid matrix\n        if (np.size(prevPoints, 0) > 4) and (np.size(prevPoints, 0) == np.size(prevPoints, 0)):\n            H, inliers = cv2.estimateAffinePartial2D(prevPoints, currPoints, cv2.RANSAC)\n\n            # Handle downscale\n            if self.downscale > 1.0:\n                H[0, 2] *= self.downscale\n                H[1, 2] *= self.downscale\n        else:\n            LOGGER.warning('WARNING: not enough matching points')\n\n        # Store to next iteration\n        self.prevFrame = frame.copy()\n        self.prevKeyPoints = copy.copy(keypoints)\n        self.prevDescriptors = copy.copy(descriptors)\n\n        return H\n\n    def applySparseOptFlow(self, raw_frame, detections=None):\n        \"\"\"Initialize.\"\"\"\n        # t0 = time.time()\n        height, width, _ = raw_frame.shape\n        frame = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY)\n        H = np.eye(2, 3)\n\n        # Downscale image\n        if self.downscale > 1.0:\n            # frame = cv2.GaussianBlur(frame, (3, 3), 1.5)\n            frame = cv2.resize(frame, (width // self.downscale, height // self.downscale))\n\n        # Find the keypoints\n        keypoints = cv2.goodFeaturesToTrack(frame, mask=None, **self.feature_params)\n\n        # Handle first frame\n        if not self.initializedFirstFrame:\n            # Initialize data\n            self.prevFrame = frame.copy()\n            self.prevKeyPoints = copy.copy(keypoints)\n\n            # Initialization done\n            self.initializedFirstFrame = True\n\n            return H\n\n        # Find correspondences\n        matchedKeypoints, status, err = cv2.calcOpticalFlowPyrLK(self.prevFrame, frame, self.prevKeyPoints, None)\n\n        # Leave good correspondences only\n        prevPoints = []\n        currPoints = []\n\n        for i in range(len(status)):\n            if status[i]:\n                prevPoints.append(self.prevKeyPoints[i])\n                currPoints.append(matchedKeypoints[i])\n\n        prevPoints = np.array(prevPoints)\n        currPoints = np.array(currPoints)\n\n        # Find rigid matrix\n        if (np.size(prevPoints, 0) > 4) and (np.size(prevPoints, 0) == np.size(prevPoints, 0)):\n            H, inliers = cv2.estimateAffinePartial2D(prevPoints, currPoints, cv2.RANSAC)\n\n            # Handle downscale\n            if self.downscale > 1.0:\n                H[0, 2] *= self.downscale\n                H[1, 2] *= self.downscale\n        else:\n            LOGGER.warning('WARNING: not enough matching points')\n\n        # Store to next iteration\n        self.prevFrame = frame.copy()\n        self.prevKeyPoints = copy.copy(keypoints)\n\n        # gmc_line = str(1000 * (time.time() - t0)) + \"\\t\" + str(H[0, 0]) + \"\\t\" + str(H[0, 1]) + \"\\t\" + str(\n        #     H[0, 2]) + \"\\t\" + str(H[1, 0]) + \"\\t\" + str(H[1, 1]) + \"\\t\" + str(H[1, 2]) + \"\\n\"\n        # self.gmc_file.write(gmc_line)\n\n        return H\n\n    def applyFile(self, raw_frame, detections=None):\n        \"\"\"Return the homography matrix based on the GCPs in the next line of the input GMC file.\"\"\"\n        line = self.gmcFile.readline()\n        tokens = line.split('\\t')\n        H = np.eye(2, 3, dtype=np.float_)\n        H[0, 0] = float(tokens[1])\n        H[0, 1] = float(tokens[2])\n        H[0, 2] = float(tokens[3])\n        H[1, 0] = float(tokens[4])\n        H[1, 1] = float(tokens[5])\n        H[1, 2] = float(tokens[6])\n\n        return H\n"
  },
  {
    "path": "ultralytics/tracker/utils/kalman_filter.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport numpy as np\nimport scipy.linalg\n\n# Table for the 0.95 quantile of the chi-square distribution with N degrees of freedom (contains values for N=1, ..., 9)\n# Taken from MATLAB/Octave's chi2inv function and used as Mahalanobis gating threshold.\nchi2inv95 = {1: 3.8415, 2: 5.9915, 3: 7.8147, 4: 9.4877, 5: 11.070, 6: 12.592, 7: 14.067, 8: 15.507, 9: 16.919}\n\n\nclass KalmanFilterXYAH:\n    \"\"\"\n    For bytetrack\n    A simple Kalman filter for tracking bounding boxes in image space.\n\n    The 8-dimensional state space\n\n        x, y, a, h, vx, vy, va, vh\n\n    contains the bounding box center position (x, y), aspect ratio a, height h,\n    and their respective velocities.\n\n    Object motion follows a constant velocity model. The bounding box location\n    (x, y, a, h) is taken as direct observation of the state space (linear\n    observation model).\n\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"Initialize Kalman filter model matrices with motion and observation uncertainty weights.\"\"\"\n        ndim, dt = 4, 1.\n\n        # Create Kalman filter model matrices.\n        self._motion_mat = np.eye(2 * ndim, 2 * ndim)\n        for i in range(ndim):\n            self._motion_mat[i, ndim + i] = dt\n        self._update_mat = np.eye(ndim, 2 * ndim)\n\n        # Motion and observation uncertainty are chosen relative to the current\n        # state estimate. These weights control the amount of uncertainty in\n        # the model. This is a bit hacky.\n        self._std_weight_position = 1. / 20\n        self._std_weight_velocity = 1. / 160\n\n    def initiate(self, measurement):\n        \"\"\"Create track from unassociated measurement.\n\n        Parameters\n        ----------\n        measurement : ndarray\n            Bounding box coordinates (x, y, a, h) with center position (x, y),\n            aspect ratio a, and height h.\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the mean vector (8 dimensional) and covariance matrix (8x8\n            dimensional) of the new track. Unobserved velocities are initialized\n            to 0 mean.\n\n        \"\"\"\n        mean_pos = measurement\n        mean_vel = np.zeros_like(mean_pos)\n        mean = np.r_[mean_pos, mean_vel]\n\n        std = [\n            2 * self._std_weight_position * measurement[3], 2 * self._std_weight_position * measurement[3], 1e-2,\n            2 * self._std_weight_position * measurement[3], 10 * self._std_weight_velocity * measurement[3],\n            10 * self._std_weight_velocity * measurement[3], 1e-5, 10 * self._std_weight_velocity * measurement[3]]\n        covariance = np.diag(np.square(std))\n        return mean, covariance\n\n    def predict(self, mean, covariance):\n        \"\"\"Run Kalman filter prediction step.\n\n        Parameters\n        ----------\n        mean : ndarray\n            The 8 dimensional mean vector of the object state at the previous\n            time step.\n        covariance : ndarray\n            The 8x8 dimensional covariance matrix of the object state at the\n            previous time step.\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the mean vector and covariance matrix of the predicted\n            state. Unobserved velocities are initialized to 0 mean.\n\n        \"\"\"\n        std_pos = [\n            self._std_weight_position * mean[3], self._std_weight_position * mean[3], 1e-2,\n            self._std_weight_position * mean[3]]\n        std_vel = [\n            self._std_weight_velocity * mean[3], self._std_weight_velocity * mean[3], 1e-5,\n            self._std_weight_velocity * mean[3]]\n        motion_cov = np.diag(np.square(np.r_[std_pos, std_vel]))\n\n        # mean = np.dot(self._motion_mat, mean)\n        mean = np.dot(mean, self._motion_mat.T)\n        covariance = np.linalg.multi_dot((self._motion_mat, covariance, self._motion_mat.T)) + motion_cov\n\n        return mean, covariance\n\n    def project(self, mean, covariance):\n        \"\"\"Project state distribution to measurement space.\n\n        Parameters\n        ----------\n        mean : ndarray\n            The state's mean vector (8 dimensional array).\n        covariance : ndarray\n            The state's covariance matrix (8x8 dimensional).\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the projected mean and covariance matrix of the given state\n            estimate.\n\n        \"\"\"\n        std = [\n            self._std_weight_position * mean[3], self._std_weight_position * mean[3], 1e-1,\n            self._std_weight_position * mean[3]]\n        innovation_cov = np.diag(np.square(std))\n\n        mean = np.dot(self._update_mat, mean)\n        covariance = np.linalg.multi_dot((self._update_mat, covariance, self._update_mat.T))\n        return mean, covariance + innovation_cov\n\n    def multi_predict(self, mean, covariance):\n        \"\"\"Run Kalman filter prediction step (Vectorized version).\n        Parameters\n        ----------\n        mean : ndarray\n            The Nx8 dimensional mean matrix of the object states at the previous\n            time step.\n        covariance : ndarray\n            The Nx8x8 dimensional covariance matrix of the object states at the\n            previous time step.\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the mean vector and covariance matrix of the predicted\n            state. Unobserved velocities are initialized to 0 mean.\n        \"\"\"\n        std_pos = [\n            self._std_weight_position * mean[:, 3], self._std_weight_position * mean[:, 3],\n            1e-2 * np.ones_like(mean[:, 3]), self._std_weight_position * mean[:, 3]]\n        std_vel = [\n            self._std_weight_velocity * mean[:, 3], self._std_weight_velocity * mean[:, 3],\n            1e-5 * np.ones_like(mean[:, 3]), self._std_weight_velocity * mean[:, 3]]\n        sqr = np.square(np.r_[std_pos, std_vel]).T\n\n        motion_cov = [np.diag(sqr[i]) for i in range(len(mean))]\n        motion_cov = np.asarray(motion_cov)\n\n        mean = np.dot(mean, self._motion_mat.T)\n        left = np.dot(self._motion_mat, covariance).transpose((1, 0, 2))\n        covariance = np.dot(left, self._motion_mat.T) + motion_cov\n\n        return mean, covariance\n\n    def update(self, mean, covariance, measurement):\n        \"\"\"Run Kalman filter correction step.\n\n        Parameters\n        ----------\n        mean : ndarray\n            The predicted state's mean vector (8 dimensional).\n        covariance : ndarray\n            The state's covariance matrix (8x8 dimensional).\n        measurement : ndarray\n            The 4 dimensional measurement vector (x, y, a, h), where (x, y)\n            is the center position, a the aspect ratio, and h the height of the\n            bounding box.\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the measurement-corrected state distribution.\n\n        \"\"\"\n        projected_mean, projected_cov = self.project(mean, covariance)\n\n        chol_factor, lower = scipy.linalg.cho_factor(projected_cov, lower=True, check_finite=False)\n        kalman_gain = scipy.linalg.cho_solve((chol_factor, lower),\n                                             np.dot(covariance, self._update_mat.T).T,\n                                             check_finite=False).T\n        innovation = measurement - projected_mean\n\n        new_mean = mean + np.dot(innovation, kalman_gain.T)\n        new_covariance = covariance - np.linalg.multi_dot((kalman_gain, projected_cov, kalman_gain.T))\n        return new_mean, new_covariance\n\n    def gating_distance(self, mean, covariance, measurements, only_position=False, metric='maha'):\n        \"\"\"Compute gating distance between state distribution and measurements.\n        A suitable distance threshold can be obtained from `chi2inv95`. If\n        `only_position` is False, the chi-square distribution has 4 degrees of\n        freedom, otherwise 2.\n        Parameters\n        ----------\n        mean : ndarray\n            Mean vector over the state distribution (8 dimensional).\n        covariance : ndarray\n            Covariance of the state distribution (8x8 dimensional).\n        measurements : ndarray\n            An Nx4 dimensional matrix of N measurements, each in\n            format (x, y, a, h) where (x, y) is the bounding box center\n            position, a the aspect ratio, and h the height.\n        only_position : Optional[bool]\n            If True, distance computation is done with respect to the bounding\n            box center position only.\n        Returns\n        -------\n        ndarray\n            Returns an array of length N, where the i-th element contains the\n            squared Mahalanobis distance between (mean, covariance) and\n            `measurements[i]`.\n        \"\"\"\n        mean, covariance = self.project(mean, covariance)\n        if only_position:\n            mean, covariance = mean[:2], covariance[:2, :2]\n            measurements = measurements[:, :2]\n\n        d = measurements - mean\n        if metric == 'gaussian':\n            return np.sum(d * d, axis=1)\n        elif metric == 'maha':\n            cholesky_factor = np.linalg.cholesky(covariance)\n            z = scipy.linalg.solve_triangular(cholesky_factor, d.T, lower=True, check_finite=False, overwrite_b=True)\n            return np.sum(z * z, axis=0)  # square maha\n        else:\n            raise ValueError('invalid distance metric')\n\n\nclass KalmanFilterXYWH:\n    \"\"\"\n    For BoT-SORT\n    A simple Kalman filter for tracking bounding boxes in image space.\n\n    The 8-dimensional state space\n\n        x, y, w, h, vx, vy, vw, vh\n\n    contains the bounding box center position (x, y), width w, height h,\n    and their respective velocities.\n\n    Object motion follows a constant velocity model. The bounding box location\n    (x, y, w, h) is taken as direct observation of the state space (linear\n    observation model).\n\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"Initialize Kalman filter model matrices with motion and observation uncertainties.\"\"\"\n        ndim, dt = 4, 1.\n\n        # Create Kalman filter model matrices.\n        self._motion_mat = np.eye(2 * ndim, 2 * ndim)\n        for i in range(ndim):\n            self._motion_mat[i, ndim + i] = dt\n        self._update_mat = np.eye(ndim, 2 * ndim)\n\n        # Motion and observation uncertainty are chosen relative to the current\n        # state estimate. These weights control the amount of uncertainty in\n        # the model. This is a bit hacky.\n        self._std_weight_position = 1. / 20\n        self._std_weight_velocity = 1. / 160\n\n    def initiate(self, measurement):\n        \"\"\"Create track from unassociated measurement.\n\n        Parameters\n        ----------\n        measurement : ndarray\n            Bounding box coordinates (x, y, w, h) with center position (x, y),\n            width w, and height h.\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the mean vector (8 dimensional) and covariance matrix (8x8\n            dimensional) of the new track. Unobserved velocities are initialized\n            to 0 mean.\n\n        \"\"\"\n        mean_pos = measurement\n        mean_vel = np.zeros_like(mean_pos)\n        mean = np.r_[mean_pos, mean_vel]\n\n        std = [\n            2 * self._std_weight_position * measurement[2], 2 * self._std_weight_position * measurement[3],\n            2 * self._std_weight_position * measurement[2], 2 * self._std_weight_position * measurement[3],\n            10 * self._std_weight_velocity * measurement[2], 10 * self._std_weight_velocity * measurement[3],\n            10 * self._std_weight_velocity * measurement[2], 10 * self._std_weight_velocity * measurement[3]]\n        covariance = np.diag(np.square(std))\n        return mean, covariance\n\n    def predict(self, mean, covariance):\n        \"\"\"Run Kalman filter prediction step.\n\n        Parameters\n        ----------\n        mean : ndarray\n            The 8 dimensional mean vector of the object state at the previous\n            time step.\n        covariance : ndarray\n            The 8x8 dimensional covariance matrix of the object state at the\n            previous time step.\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the mean vector and covariance matrix of the predicted\n            state. Unobserved velocities are initialized to 0 mean.\n\n        \"\"\"\n        std_pos = [\n            self._std_weight_position * mean[2], self._std_weight_position * mean[3],\n            self._std_weight_position * mean[2], self._std_weight_position * mean[3]]\n        std_vel = [\n            self._std_weight_velocity * mean[2], self._std_weight_velocity * mean[3],\n            self._std_weight_velocity * mean[2], self._std_weight_velocity * mean[3]]\n        motion_cov = np.diag(np.square(np.r_[std_pos, std_vel]))\n\n        mean = np.dot(mean, self._motion_mat.T)\n        covariance = np.linalg.multi_dot((self._motion_mat, covariance, self._motion_mat.T)) + motion_cov\n\n        return mean, covariance\n\n    def project(self, mean, covariance):\n        \"\"\"Project state distribution to measurement space.\n\n        Parameters\n        ----------\n        mean : ndarray\n            The state's mean vector (8 dimensional array).\n        covariance : ndarray\n            The state's covariance matrix (8x8 dimensional).\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the projected mean and covariance matrix of the given state\n            estimate.\n\n        \"\"\"\n        std = [\n            self._std_weight_position * mean[2], self._std_weight_position * mean[3],\n            self._std_weight_position * mean[2], self._std_weight_position * mean[3]]\n        innovation_cov = np.diag(np.square(std))\n\n        mean = np.dot(self._update_mat, mean)\n        covariance = np.linalg.multi_dot((self._update_mat, covariance, self._update_mat.T))\n        return mean, covariance + innovation_cov\n\n    def multi_predict(self, mean, covariance):\n        \"\"\"Run Kalman filter prediction step (Vectorized version).\n        Parameters\n        ----------\n        mean : ndarray\n            The Nx8 dimensional mean matrix of the object states at the previous\n            time step.\n        covariance : ndarray\n            The Nx8x8 dimensional covariance matrix of the object states at the\n            previous time step.\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the mean vector and covariance matrix of the predicted\n            state. Unobserved velocities are initialized to 0 mean.\n        \"\"\"\n        std_pos = [\n            self._std_weight_position * mean[:, 2], self._std_weight_position * mean[:, 3],\n            self._std_weight_position * mean[:, 2], self._std_weight_position * mean[:, 3]]\n        std_vel = [\n            self._std_weight_velocity * mean[:, 2], self._std_weight_velocity * mean[:, 3],\n            self._std_weight_velocity * mean[:, 2], self._std_weight_velocity * mean[:, 3]]\n        sqr = np.square(np.r_[std_pos, std_vel]).T\n\n        motion_cov = [np.diag(sqr[i]) for i in range(len(mean))]\n        motion_cov = np.asarray(motion_cov)\n\n        mean = np.dot(mean, self._motion_mat.T)\n        left = np.dot(self._motion_mat, covariance).transpose((1, 0, 2))\n        covariance = np.dot(left, self._motion_mat.T) + motion_cov\n\n        return mean, covariance\n\n    def update(self, mean, covariance, measurement):\n        \"\"\"Run Kalman filter correction step.\n\n        Parameters\n        ----------\n        mean : ndarray\n            The predicted state's mean vector (8 dimensional).\n        covariance : ndarray\n            The state's covariance matrix (8x8 dimensional).\n        measurement : ndarray\n            The 4 dimensional measurement vector (x, y, w, h), where (x, y)\n            is the center position, w the width, and h the height of the\n            bounding box.\n\n        Returns\n        -------\n        (ndarray, ndarray)\n            Returns the measurement-corrected state distribution.\n\n        \"\"\"\n        projected_mean, projected_cov = self.project(mean, covariance)\n\n        chol_factor, lower = scipy.linalg.cho_factor(projected_cov, lower=True, check_finite=False)\n        kalman_gain = scipy.linalg.cho_solve((chol_factor, lower),\n                                             np.dot(covariance, self._update_mat.T).T,\n                                             check_finite=False).T\n        innovation = measurement - projected_mean\n\n        new_mean = mean + np.dot(innovation, kalman_gain.T)\n        new_covariance = covariance - np.linalg.multi_dot((kalman_gain, projected_cov, kalman_gain.T))\n        return new_mean, new_covariance\n\n    def gating_distance(self, mean, covariance, measurements, only_position=False, metric='maha'):\n        \"\"\"Compute gating distance between state distribution and measurements.\n        A suitable distance threshold can be obtained from `chi2inv95`. If\n        `only_position` is False, the chi-square distribution has 4 degrees of\n        freedom, otherwise 2.\n        Parameters\n        ----------\n        mean : ndarray\n            Mean vector over the state distribution (8 dimensional).\n        covariance : ndarray\n            Covariance of the state distribution (8x8 dimensional).\n        measurements : ndarray\n            An Nx4 dimensional matrix of N measurements, each in\n            format (x, y, a, h) where (x, y) is the bounding box center\n            position, a the aspect ratio, and h the height.\n        only_position : Optional[bool]\n            If True, distance computation is done with respect to the bounding\n            box center position only.\n        Returns\n        -------\n        ndarray\n            Returns an array of length N, where the i-th element contains the\n            squared Mahalanobis distance between (mean, covariance) and\n            `measurements[i]`.\n        \"\"\"\n        mean, covariance = self.project(mean, covariance)\n        if only_position:\n            mean, covariance = mean[:2], covariance[:2, :2]\n            measurements = measurements[:, :2]\n\n        d = measurements - mean\n        if metric == 'gaussian':\n            return np.sum(d * d, axis=1)\n        elif metric == 'maha':\n            cholesky_factor = np.linalg.cholesky(covariance)\n            z = scipy.linalg.solve_triangular(cholesky_factor, d.T, lower=True, check_finite=False, overwrite_b=True)\n            return np.sum(z * z, axis=0)  # square maha\n        else:\n            raise ValueError('invalid distance metric')\n"
  },
  {
    "path": "ultralytics/tracker/utils/matching.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport numpy as np\nimport scipy\nfrom scipy.spatial.distance import cdist\n\nfrom .kalman_filter import chi2inv95\n\ntry:\n    import lap  # for linear_assignment\n\n    assert lap.__version__  # verify package is not directory\nexcept (ImportError, AssertionError, AttributeError):\n    from ultralytics.yolo.utils.checks import check_requirements\n\n    check_requirements('lap>=0.4')  # install\n    import lap\n\n\ndef merge_matches(m1, m2, shape):\n    \"\"\"Merge two sets of matches and return matched and unmatched indices.\"\"\"\n    O, P, Q = shape\n    m1 = np.asarray(m1)\n    m2 = np.asarray(m2)\n\n    M1 = scipy.sparse.coo_matrix((np.ones(len(m1)), (m1[:, 0], m1[:, 1])), shape=(O, P))\n    M2 = scipy.sparse.coo_matrix((np.ones(len(m2)), (m2[:, 0], m2[:, 1])), shape=(P, Q))\n\n    mask = M1 * M2\n    match = mask.nonzero()\n    match = list(zip(match[0], match[1]))\n    unmatched_O = tuple(set(range(O)) - {i for i, j in match})\n    unmatched_Q = tuple(set(range(Q)) - {j for i, j in match})\n\n    return match, unmatched_O, unmatched_Q\n\n\ndef _indices_to_matches(cost_matrix, indices, thresh):\n    \"\"\"_indices_to_matches: Return matched and unmatched indices given a cost matrix, indices, and a threshold.\"\"\"\n    matched_cost = cost_matrix[tuple(zip(*indices))]\n    matched_mask = (matched_cost <= thresh)\n\n    matches = indices[matched_mask]\n    unmatched_a = tuple(set(range(cost_matrix.shape[0])) - set(matches[:, 0]))\n    unmatched_b = tuple(set(range(cost_matrix.shape[1])) - set(matches[:, 1]))\n\n    return matches, unmatched_a, unmatched_b\n\n\ndef linear_assignment(cost_matrix, thresh, use_lap=True):\n    \"\"\"Linear assignment implementations with scipy and lap.lapjv.\"\"\"\n    if cost_matrix.size == 0:\n        return np.empty((0, 2), dtype=int), tuple(range(cost_matrix.shape[0])), tuple(range(cost_matrix.shape[1]))\n\n    if use_lap:\n        _, x, y = lap.lapjv(cost_matrix, extend_cost=True, cost_limit=thresh)\n        matches = [[ix, mx] for ix, mx in enumerate(x) if mx >= 0]\n        unmatched_a = np.where(x < 0)[0]\n        unmatched_b = np.where(y < 0)[0]\n    else:\n        # Scipy linear sum assignment is NOT working correctly, DO NOT USE\n        y, x = scipy.optimize.linear_sum_assignment(cost_matrix)  # row y, col x\n        matches = np.asarray([[i, x] for i, x in enumerate(x) if cost_matrix[i, x] <= thresh])\n        unmatched = np.ones(cost_matrix.shape)\n        for i, xi in matches:\n            unmatched[i, xi] = 0.0\n        unmatched_a = np.where(unmatched.all(1))[0]\n        unmatched_b = np.where(unmatched.all(0))[0]\n\n    return matches, unmatched_a, unmatched_b\n\n\ndef ious(atlbrs, btlbrs):\n    \"\"\"\n    Compute cost based on IoU\n    :type atlbrs: list[tlbr] | np.ndarray\n    :type atlbrs: list[tlbr] | np.ndarray\n\n    :rtype ious np.ndarray\n    \"\"\"\n    ious = np.zeros((len(atlbrs), len(btlbrs)), dtype=np.float32)\n    if ious.size == 0:\n        return ious\n\n    ious = bbox_ious(np.ascontiguousarray(atlbrs, dtype=np.float32), np.ascontiguousarray(btlbrs, dtype=np.float32))\n    return ious\n\n\ndef iou_distance(atracks, btracks):\n    \"\"\"\n    Compute cost based on IoU\n    :type atracks: list[STrack]\n    :type btracks: list[STrack]\n\n    :rtype cost_matrix np.ndarray\n    \"\"\"\n\n    if (len(atracks) > 0 and isinstance(atracks[0], np.ndarray)) \\\n            or (len(btracks) > 0 and isinstance(btracks[0], np.ndarray)):\n        atlbrs = atracks\n        btlbrs = btracks\n    else:\n        atlbrs = [track.tlbr for track in atracks]\n        btlbrs = [track.tlbr for track in btracks]\n    _ious = ious(atlbrs, btlbrs)\n    return 1 - _ious  # cost matrix\n\n\ndef v_iou_distance(atracks, btracks):\n    \"\"\"\n    Compute cost based on IoU\n    :type atracks: list[STrack]\n    :type btracks: list[STrack]\n\n    :rtype cost_matrix np.ndarray\n    \"\"\"\n\n    if (len(atracks) > 0 and isinstance(atracks[0], np.ndarray)) \\\n            or (len(btracks) > 0 and isinstance(btracks[0], np.ndarray)):\n        atlbrs = atracks\n        btlbrs = btracks\n    else:\n        atlbrs = [track.tlwh_to_tlbr(track.pred_bbox) for track in atracks]\n        btlbrs = [track.tlwh_to_tlbr(track.pred_bbox) for track in btracks]\n    _ious = ious(atlbrs, btlbrs)\n    return 1 - _ious  # cost matrix\n\n\ndef embedding_distance(tracks, detections, metric='cosine'):\n    \"\"\"\n    :param tracks: list[STrack]\n    :param detections: list[BaseTrack]\n    :param metric:\n    :return: cost_matrix np.ndarray\n    \"\"\"\n\n    cost_matrix = np.zeros((len(tracks), len(detections)), dtype=np.float32)\n    if cost_matrix.size == 0:\n        return cost_matrix\n    det_features = np.asarray([track.curr_feat for track in detections], dtype=np.float32)\n    # for i, track in enumerate(tracks):\n    # cost_matrix[i, :] = np.maximum(0.0, cdist(track.smooth_feat.reshape(1,-1), det_features, metric))\n    track_features = np.asarray([track.smooth_feat for track in tracks], dtype=np.float32)\n    cost_matrix = np.maximum(0.0, cdist(track_features, det_features, metric))  # Normalized features\n    return cost_matrix\n\n\ndef gate_cost_matrix(kf, cost_matrix, tracks, detections, only_position=False):\n    \"\"\"Apply gating to the cost matrix based on predicted tracks and detected objects.\"\"\"\n    if cost_matrix.size == 0:\n        return cost_matrix\n    gating_dim = 2 if only_position else 4\n    gating_threshold = chi2inv95[gating_dim]\n    measurements = np.asarray([det.to_xyah() for det in detections])\n    for row, track in enumerate(tracks):\n        gating_distance = kf.gating_distance(track.mean, track.covariance, measurements, only_position)\n        cost_matrix[row, gating_distance > gating_threshold] = np.inf\n    return cost_matrix\n\n\ndef fuse_motion(kf, cost_matrix, tracks, detections, only_position=False, lambda_=0.98):\n    \"\"\"Fuse motion between tracks and detections with gating and Kalman filtering.\"\"\"\n    if cost_matrix.size == 0:\n        return cost_matrix\n    gating_dim = 2 if only_position else 4\n    gating_threshold = chi2inv95[gating_dim]\n    measurements = np.asarray([det.to_xyah() for det in detections])\n    for row, track in enumerate(tracks):\n        gating_distance = kf.gating_distance(track.mean, track.covariance, measurements, only_position, metric='maha')\n        cost_matrix[row, gating_distance > gating_threshold] = np.inf\n        cost_matrix[row] = lambda_ * cost_matrix[row] + (1 - lambda_) * gating_distance\n    return cost_matrix\n\n\ndef fuse_iou(cost_matrix, tracks, detections):\n    \"\"\"Fuses ReID and IoU similarity matrices to yield a cost matrix for object tracking.\"\"\"\n    if cost_matrix.size == 0:\n        return cost_matrix\n    reid_sim = 1 - cost_matrix\n    iou_dist = iou_distance(tracks, detections)\n    iou_sim = 1 - iou_dist\n    fuse_sim = reid_sim * (1 + iou_sim) / 2\n    # det_scores = np.array([det.score for det in detections])\n    # det_scores = np.expand_dims(det_scores, axis=0).repeat(cost_matrix.shape[0], axis=0)\n    return 1 - fuse_sim  # fuse cost\n\n\ndef fuse_score(cost_matrix, detections):\n    \"\"\"Fuses cost matrix with detection scores to produce a single similarity matrix.\"\"\"\n    if cost_matrix.size == 0:\n        return cost_matrix\n    iou_sim = 1 - cost_matrix\n    det_scores = np.array([det.score for det in detections])\n    det_scores = np.expand_dims(det_scores, axis=0).repeat(cost_matrix.shape[0], axis=0)\n    fuse_sim = iou_sim * det_scores\n    return 1 - fuse_sim  # fuse_cost\n\n\ndef bbox_ious(box1, box2, eps=1e-7):\n    \"\"\"\n    Calculate the Intersection over Union (IoU) between pairs of bounding boxes.\n\n    Args:\n        box1 (np.array): A numpy array of shape (n, 4) representing 'n' bounding boxes.\n                         Each row is in the format (x1, y1, x2, y2).\n        box2 (np.array): A numpy array of shape (m, 4) representing 'm' bounding boxes.\n                         Each row is in the format (x1, y1, x2, y2).\n        eps (float, optional): A small constant to prevent division by zero. Defaults to 1e-7.\n\n    Returns:\n        (np.array): A numpy array of shape (n, m) representing the IoU scores for each pair\n                    of bounding boxes from box1 and box2.\n\n    Note:\n        The bounding box coordinates are expected to be in the format (x1, y1, x2, y2).\n    \"\"\"\n\n    # Get the coordinates of bounding boxes\n    b1_x1, b1_y1, b1_x2, b1_y2 = box1.T\n    b2_x1, b2_y1, b2_x2, b2_y2 = box2.T\n\n    # Intersection area\n    inter_area = (np.minimum(b1_x2[:, None], b2_x2) - np.maximum(b1_x1[:, None], b2_x1)).clip(0) * \\\n                 (np.minimum(b1_y2[:, None], b2_y2) - np.maximum(b1_y1[:, None], b2_y1)).clip(0)\n\n    # box2 area\n    box1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)\n    box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)\n    return inter_area / (box2_area + box1_area[:, None] - inter_area + eps)\n"
  },
  {
    "path": "ultralytics/train.py",
    "content": "import sys\nsys.path.insert(0, \"/home/jiayuan/yolom/ultralytics\")\n# 现在就可以导入Yolo类了\nfrom ultralytics import YOLO\n\n# Load a model\nmodel = YOLO('/home/jiayuan/yolom/ultralytics/models/v8/yolov8-bdd-v4-one-dropout-individual-n.yaml', task='multi')  # build a new model from YAML\n# model = YOLO('yolov8n.pt')  # load a pretrained model (recommended for training)\n# model = YOLO('yolov8n.yaml').load('yolov8n.pt')  # build from YAML and transfer weights\n\n# Train the model\nmodel.train(data='/home/jiayuan/yolom/ultralytics/datasets/bdd-multi.yaml', batch=12, epochs=300, imgsz=(640,640), device=[0,1,2], name='yolopm', val=True, task='multi',classes=[2,3,4,9,10,11],combine_class=[2,3,4,9],single_cls=True)\n"
  },
  {
    "path": "ultralytics/val.py",
    "content": "import sys\nsys.path.insert(0, \"/home/jiayuan/yolom/ultralytics\")\n# 现在就可以导入Yolo类了\nfrom ultralytics import YOLO\n\n# model = YOLO('yolov8s-seg.pt')\n# number = 3 #input how many tasks in your work\nmodel = YOLO('/home/jiayuan/ultralytics-main/ultralytics/runs/best.pt')  # 加载自己训练的模型# Validate the model\n# metrics = model.val(data='/home/jiayuan/ultralytics-main/ultralytics/datasets/bdd-multi.yaml',device=[4],task='multi',name='v3-model-val',iou=0.6,conf=0.001, imgsz=(640,640),classes=[2,3,4,9,10,11],combine_class=[2,3,4,9],single_cls=True)  # no arguments needed, dataset and settings remembered\n\nmetrics = model.val(data='/home/jiayuan/ultralytics-main/ultralytics/datasets/bdd-multi.yaml',device=[3],task='multi',name='val',iou=0.6,conf=0.001, imgsz=(640,640),classes=[2,3,4,9,10,11],combine_class=[2,3,4,9],single_cls=True)  # no arguments needed, dataset and settings remembered\n# for i in range(number):\n#     print(f'This is for {i} work')\n#     print(metrics[i].box.map)    # map50-95\n#     print(metrics[i].box.map50)  # map50\n#     print(metrics[i].box.map75)  # map75\n#     print(metrics[i].box.maps)   # a list contains map50-95 of each category"
  },
  {
    "path": "ultralytics/vit/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .rtdetr import RTDETR\nfrom .sam import SAM\n\n__all__ = 'RTDETR', 'SAM', 'SAM'  # allow simpler import\n"
  },
  {
    "path": "ultralytics/vit/rtdetr/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .model import RTDETR\nfrom .predict import RTDETRPredictor\nfrom .val import RTDETRValidator\n\n__all__ = 'RTDETRPredictor', 'RTDETRValidator', 'RTDETR'\n"
  },
  {
    "path": "ultralytics/vit/rtdetr/model.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\n# RT-DETR model interface\n\"\"\"\n\nfrom pathlib import Path\n\nfrom ultralytics.nn.tasks import DetectionModel, attempt_load_one_weight, yaml_model_load\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.engine.exporter import Exporter\nfrom ultralytics.yolo.utils import DEFAULT_CFG, DEFAULT_CFG_DICT, LOGGER, ROOT, is_git_dir\nfrom ultralytics.yolo.utils.checks import check_imgsz\nfrom ultralytics.yolo.utils.torch_utils import model_info\n\nfrom ...yolo.utils.torch_utils import smart_inference_mode\nfrom .predict import RTDETRPredictor\nfrom .val import RTDETRValidator\n\n\nclass RTDETR:\n\n    def __init__(self, model='rtdetr-l.pt') -> None:\n        if model and not model.endswith('.pt') and not model.endswith('.yaml'):\n            raise NotImplementedError('RT-DETR only supports creating from pt file or yaml file.')\n        # Load or create new YOLO model\n        self.predictor = None\n        suffix = Path(model).suffix\n        if suffix == '.yaml':\n            self._new(model)\n        else:\n            self._load(model)\n\n    def _new(self, cfg: str, verbose=True):\n        cfg_dict = yaml_model_load(cfg)\n        self.cfg = cfg\n        self.task = 'detect'\n        self.model = DetectionModel(cfg_dict, verbose=verbose)  # build model\n\n        # Below added to allow export from yamls\n        self.model.args = DEFAULT_CFG_DICT  # attach args to model\n        self.model.task = self.task\n\n    @smart_inference_mode()\n    def _load(self, weights: str):\n        self.model, _ = attempt_load_one_weight(weights)\n        self.model.args = DEFAULT_CFG_DICT  # attach args to model\n        self.task = self.model.args['task']\n\n    @smart_inference_mode()\n    def predict(self, source=None, stream=False, **kwargs):\n        \"\"\"\n        Perform prediction using the YOLO model.\n\n        Args:\n            source (str | int | PIL | np.ndarray): The source of the image to make predictions on.\n                          Accepts all source types accepted by the YOLO model.\n            stream (bool): Whether to stream the predictions or not. Defaults to False.\n            **kwargs : Additional keyword arguments passed to the predictor.\n                       Check the 'configuration' section in the documentation for all available options.\n\n        Returns:\n            (List[ultralytics.yolo.engine.results.Results]): The prediction results.\n        \"\"\"\n        if source is None:\n            source = ROOT / 'assets' if is_git_dir() else 'https://ultralytics.com/images/bus.jpg'\n            LOGGER.warning(f\"WARNING ⚠️ 'source' is missing. Using 'source={source}'.\")\n        overrides = dict(conf=0.25, task='detect', mode='predict')\n        overrides.update(kwargs)  # prefer kwargs\n        if not self.predictor:\n            self.predictor = RTDETRPredictor(overrides=overrides)\n            self.predictor.setup_model(model=self.model)\n        else:  # only update args if predictor is already setup\n            self.predictor.args = get_cfg(self.predictor.args, overrides)\n        return self.predictor(source, stream=stream)\n\n    def train(self, **kwargs):\n        \"\"\"Function trains models but raises an error as RTDETR models do not support training.\"\"\"\n        raise NotImplementedError(\"RTDETR models don't support training\")\n\n    def val(self, **kwargs):\n        \"\"\"Run validation given dataset.\"\"\"\n        overrides = dict(task='detect', mode='val')\n        overrides.update(kwargs)  # prefer kwargs\n        args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)\n        args.imgsz = check_imgsz(args.imgsz, max_dim=1)\n        validator = RTDETRValidator(args=args)\n        validator(model=self.model)\n        self.metrics = validator.metrics\n        return validator.metrics\n\n    def info(self, verbose=True):\n        \"\"\"Get model info\"\"\"\n        return model_info(self.model, verbose=verbose)\n\n    @smart_inference_mode()\n    def export(self, **kwargs):\n        \"\"\"\n        Export model.\n\n        Args:\n            **kwargs : Any other args accepted by the predictors. To see all args check 'configuration' section in docs\n        \"\"\"\n        overrides = dict(task='detect')\n        overrides.update(kwargs)\n        overrides['mode'] = 'export'\n        args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)\n        args.task = self.task\n        if args.imgsz == DEFAULT_CFG.imgsz:\n            args.imgsz = self.model.args['imgsz']  # use trained imgsz unless custom value is passed\n        if args.batch == DEFAULT_CFG.batch:\n            args.batch = 1  # default to 1 if not modified\n        return Exporter(overrides=args)(model=self.model)\n"
  },
  {
    "path": "ultralytics/vit/rtdetr/predict.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\n\nfrom ultralytics.yolo.data.augment import LetterBox\nfrom ultralytics.yolo.engine.predictor import BasePredictor\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils import ops\n\n\nclass RTDETRPredictor(BasePredictor):\n\n    def postprocess(self, preds, img, orig_imgs):\n        \"\"\"Postprocess predictions and returns a list of Results objects.\"\"\"\n        bboxes, scores = preds[:2]  # (1, bs, 300, 4), (1, bs, 300, nc)\n        bboxes, scores = bboxes.squeeze_(0), scores.squeeze_(0)\n        results = []\n        for i, bbox in enumerate(bboxes):  # (300, 4)\n            bbox = ops.xywh2xyxy(bbox)\n            score, cls = scores[i].max(-1)  # (300, )\n            idx = score > self.args.conf\n            pred = torch.cat([bbox, score[..., None], cls[..., None]], dim=-1)[idx]  # filter\n            orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs\n            oh, ow = orig_img.shape[:2]\n            if not isinstance(orig_imgs, torch.Tensor):\n                pred[..., [0, 2]] *= ow\n                pred[..., [1, 3]] *= oh\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            results.append(Results(orig_img=orig_img, path=img_path, names=self.model.names, boxes=pred))\n        return results\n\n    def pre_transform(self, im):\n        \"\"\"Pre-transform input image before inference.\n\n        Args:\n            im (List(np.ndarray)): (N, 3, h, w) for tensor, [(h, w, 3) x N] for list.\n\n        Return: A list of transformed imgs.\n        \"\"\"\n        # The size must be square(640) and scaleFilled.\n        return [LetterBox(self.imgsz, auto=False, scaleFill=True)(image=x) for x in im]\n"
  },
  {
    "path": "ultralytics/vit/rtdetr/val.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom pathlib import Path\n\nimport torch\n\nfrom ultralytics.yolo.data import YOLODataset\nfrom ultralytics.yolo.data.augment import Compose, Format, LetterBox\nfrom ultralytics.yolo.utils import colorstr, ops\nfrom ultralytics.yolo.v8.detect import DetectionValidator\n\n__all__ = ['RTDETRValidator']\n\n\n# TODO: Temporarily, RT-DETR does not need padding.\nclass RTDETRDataset(YOLODataset):\n\n    def __init__(self, *args, data=None, **kwargs):\n        super().__init__(*args, data=data, use_segments=False, use_keypoints=False, **kwargs)\n\n    def build_transforms(self, hyp=None):\n        \"\"\"Temporarily, only for evaluation.\"\"\"\n        transforms = Compose([LetterBox(new_shape=(self.imgsz, self.imgsz), auto=False, scaleFill=True)])\n        transforms.append(\n            Format(bbox_format='xywh',\n                   normalize=True,\n                   return_mask=self.use_segments,\n                   return_keypoint=self.use_keypoints,\n                   batch_idx=True,\n                   mask_ratio=hyp.mask_ratio,\n                   mask_overlap=hyp.overlap_mask))\n        return transforms\n\n\nclass RTDETRValidator(DetectionValidator):\n\n    def build_dataset(self, img_path, mode='val', batch=None):\n        \"\"\"Build YOLO Dataset\n\n        Args:\n            img_path (str): Path to the folder containing images.\n            mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.\n            batch (int, optional): Size of batches, this is for `rect`. Defaults to None.\n        \"\"\"\n        return RTDETRDataset(\n            img_path=img_path,\n            imgsz=self.args.imgsz,\n            batch_size=batch,\n            augment=False,  # no augmentation\n            hyp=self.args,\n            rect=False,  # no rect\n            cache=self.args.cache or None,\n            prefix=colorstr(f'{mode}: '),\n            data=self.data)\n\n    def postprocess(self, preds):\n        \"\"\"Apply Non-maximum suppression to prediction outputs.\"\"\"\n        bboxes, scores = preds[:2]  # (1, bs, 300, 4), (1, bs, 300, nc)\n        bboxes, scores = bboxes.squeeze_(0), scores.squeeze_(0)  # (bs, 300, 4)\n        bs = len(bboxes)\n        outputs = [torch.zeros((0, 6), device=bboxes.device)] * bs\n        for i, bbox in enumerate(bboxes):  # (300, 4)\n            bbox = ops.xywh2xyxy(bbox)\n            score, cls = scores[i].max(-1)  # (300, )\n            # Do not need threshold for evaluation as only got 300 boxes here.\n            # idx = score > self.args.conf\n            pred = torch.cat([bbox, score[..., None], cls[..., None]], dim=-1)  # filter\n            outputs[i] = pred  # [idx]\n\n        return outputs\n\n    def update_metrics(self, preds, batch):\n        \"\"\"Metrics.\"\"\"\n        for si, pred in enumerate(preds):\n            idx = batch['batch_idx'] == si\n            cls = batch['cls'][idx]\n            bbox = batch['bboxes'][idx]\n            nl, npr = cls.shape[0], pred.shape[0]  # number of labels, predictions\n            shape = batch['ori_shape'][si]\n            correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n            self.seen += 1\n\n            if npr == 0:\n                if nl:\n                    self.stats.append((correct_bboxes, *torch.zeros((2, 0), device=self.device), cls.squeeze(-1)))\n                    if self.args.plots:\n                        self.confusion_matrix.process_batch(detections=None, labels=cls.squeeze(-1))\n                continue\n\n            # Predictions\n            if self.args.single_cls:\n                pred[:, 5] = 0\n            predn = pred.clone()\n            predn[..., [0, 2]] *= shape[1]  # native-space pred\n            predn[..., [1, 3]] *= shape[0]  # native-space pred\n\n            # Evaluate\n            if nl:\n                tbox = ops.xywh2xyxy(bbox)  # target boxes\n                tbox[..., [0, 2]] *= shape[1]  # native-space pred\n                tbox[..., [1, 3]] *= shape[0]  # native-space pred\n                labelsn = torch.cat((cls, tbox), 1)  # native-space labels\n                correct_bboxes = self._process_batch(predn, labelsn)\n                # TODO: maybe remove these `self.` arguments as they already are member variable\n                if self.args.plots:\n                    self.confusion_matrix.process_batch(predn, labelsn)\n            self.stats.append((correct_bboxes, pred[:, 4], pred[:, 5], cls.squeeze(-1)))  # (conf, pcls, tcls)\n\n            # Save\n            if self.args.save_json:\n                self.pred_to_json(predn, batch['im_file'][si])\n            if self.args.save_txt:\n                file = self.save_dir / 'labels' / f'{Path(batch[\"im_file\"][si]).stem}.txt'\n                self.save_one_txt(predn, self.args.save_conf, shape, file)\n"
  },
  {
    "path": "ultralytics/vit/sam/__init__.py",
    "content": "from .build import build_sam  # noqa\nfrom .model import SAM  # noqa\nfrom .modules.prompt_predictor import PromptPredictor  # noqa\n"
  },
  {
    "path": "ultralytics/vit/sam/amg.py",
    "content": "import math\nfrom copy import deepcopy\nfrom itertools import product\nfrom typing import Any, Dict, Generator, ItemsView, List, Tuple\n\nimport numpy as np\nimport torch\n\n\nclass MaskData:\n    \"\"\"\n    A structure for storing masks and their related data in batched format.\n    Implements basic filtering and concatenation.\n    \"\"\"\n\n    def __init__(self, **kwargs) -> None:\n        \"\"\"Initialize a MaskData object, ensuring all values are supported types.\"\"\"\n        for v in kwargs.values():\n            assert isinstance(\n                v, (list, np.ndarray, torch.Tensor)), 'MaskData only supports list, numpy arrays, and torch tensors.'\n        self._stats = dict(**kwargs)\n\n    def __setitem__(self, key: str, item: Any) -> None:\n        \"\"\"Set an item in the MaskData object, ensuring it is a supported type.\"\"\"\n        assert isinstance(\n            item, (list, np.ndarray, torch.Tensor)), 'MaskData only supports list, numpy arrays, and torch tensors.'\n        self._stats[key] = item\n\n    def __delitem__(self, key: str) -> None:\n        \"\"\"Delete an item from the MaskData object.\"\"\"\n        del self._stats[key]\n\n    def __getitem__(self, key: str) -> Any:\n        \"\"\"Get an item from the MaskData object.\"\"\"\n        return self._stats[key]\n\n    def items(self) -> ItemsView[str, Any]:\n        \"\"\"Return an ItemsView of the MaskData object.\"\"\"\n        return self._stats.items()\n\n    def filter(self, keep: torch.Tensor) -> None:\n        \"\"\"Filter the MaskData object based on the given boolean tensor.\"\"\"\n        for k, v in self._stats.items():\n            if v is None:\n                self._stats[k] = None\n            elif isinstance(v, torch.Tensor):\n                self._stats[k] = v[torch.as_tensor(keep, device=v.device)]\n            elif isinstance(v, np.ndarray):\n                self._stats[k] = v[keep.detach().cpu().numpy()]\n            elif isinstance(v, list) and keep.dtype == torch.bool:\n                self._stats[k] = [a for i, a in enumerate(v) if keep[i]]\n            elif isinstance(v, list):\n                self._stats[k] = [v[i] for i in keep]\n            else:\n                raise TypeError(f'MaskData key {k} has an unsupported type {type(v)}.')\n\n    def cat(self, new_stats: 'MaskData') -> None:\n        \"\"\"Concatenate a new MaskData object to the current one.\"\"\"\n        for k, v in new_stats.items():\n            if k not in self._stats or self._stats[k] is None:\n                self._stats[k] = deepcopy(v)\n            elif isinstance(v, torch.Tensor):\n                self._stats[k] = torch.cat([self._stats[k], v], dim=0)\n            elif isinstance(v, np.ndarray):\n                self._stats[k] = np.concatenate([self._stats[k], v], axis=0)\n            elif isinstance(v, list):\n                self._stats[k] = self._stats[k] + deepcopy(v)\n            else:\n                raise TypeError(f'MaskData key {k} has an unsupported type {type(v)}.')\n\n    def to_numpy(self) -> None:\n        \"\"\"Convert all torch tensors in the MaskData object to numpy arrays.\"\"\"\n        for k, v in self._stats.items():\n            if isinstance(v, torch.Tensor):\n                self._stats[k] = v.detach().cpu().numpy()\n\n\ndef is_box_near_crop_edge(boxes: torch.Tensor,\n                          crop_box: List[int],\n                          orig_box: List[int],\n                          atol: float = 20.0) -> torch.Tensor:\n    \"\"\"Return a boolean tensor indicating if boxes are near the crop edge.\"\"\"\n    crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device)\n    orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device)\n    boxes = uncrop_boxes_xyxy(boxes, crop_box).float()\n    near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0)\n    near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0)\n    near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge)\n    return torch.any(near_crop_edge, dim=1)\n\n\ndef box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor:\n    \"\"\"Convert bounding boxes from XYXY format to XYWH format.\"\"\"\n    box_xywh = deepcopy(box_xyxy)\n    box_xywh[2] = box_xywh[2] - box_xywh[0]\n    box_xywh[3] = box_xywh[3] - box_xywh[1]\n    return box_xywh\n\n\ndef batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]:\n    \"\"\"Yield batches of data from the input arguments.\"\"\"\n    assert args and all(len(a) == len(args[0]) for a in args), 'Batched iteration must have same-size inputs.'\n    n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0)\n    for b in range(n_batches):\n        yield [arg[b * batch_size:(b + 1) * batch_size] for arg in args]\n\n\ndef mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]:\n    \"\"\"Encode masks as uncompressed RLEs in the format expected by pycocotools.\"\"\"\n    # Put in fortran order and flatten h,w\n    b, h, w = tensor.shape\n    tensor = tensor.permute(0, 2, 1).flatten(1)\n\n    # Compute change indices\n    diff = tensor[:, 1:] ^ tensor[:, :-1]\n    change_indices = diff.nonzero()\n\n    # Encode run length\n    out = []\n    for i in range(b):\n        cur_idxs = change_indices[change_indices[:, 0] == i, 1]\n        cur_idxs = torch.cat([\n            torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device),\n            cur_idxs + 1,\n            torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device), ])\n        btw_idxs = cur_idxs[1:] - cur_idxs[:-1]\n        counts = [] if tensor[i, 0] == 0 else [0]\n        counts.extend(btw_idxs.detach().cpu().tolist())\n        out.append({'size': [h, w], 'counts': counts})\n    return out\n\n\ndef rle_to_mask(rle: Dict[str, Any]) -> np.ndarray:\n    \"\"\"Compute a binary mask from an uncompressed RLE.\"\"\"\n    h, w = rle['size']\n    mask = np.empty(h * w, dtype=bool)\n    idx = 0\n    parity = False\n    for count in rle['counts']:\n        mask[idx:idx + count] = parity\n        idx += count\n        parity ^= True\n    mask = mask.reshape(w, h)\n    return mask.transpose()  # Put in C order\n\n\ndef area_from_rle(rle: Dict[str, Any]) -> int:\n    \"\"\"Calculate the area of a mask from its uncompressed RLE.\"\"\"\n    return sum(rle['counts'][1::2])\n\n\ndef calculate_stability_score(masks: torch.Tensor, mask_threshold: float, threshold_offset: float) -> torch.Tensor:\n    \"\"\"\n    Computes the stability score for a batch of masks. The stability\n    score is the IoU between the binary masks obtained by thresholding\n    the predicted mask logits at high and low values.\n    \"\"\"\n    # One mask is always contained inside the other.\n    # Save memory by preventing unnecessary cast to torch.int64\n    intersections = ((masks > (mask_threshold + threshold_offset)).sum(-1, dtype=torch.int16).sum(-1,\n                                                                                                  dtype=torch.int32))\n    unions = ((masks > (mask_threshold - threshold_offset)).sum(-1, dtype=torch.int16).sum(-1, dtype=torch.int32))\n    return intersections / unions\n\n\ndef build_point_grid(n_per_side: int) -> np.ndarray:\n    \"\"\"Generate a 2D grid of evenly spaced points in the range [0,1]x[0,1].\"\"\"\n    offset = 1 / (2 * n_per_side)\n    points_one_side = np.linspace(offset, 1 - offset, n_per_side)\n    points_x = np.tile(points_one_side[None, :], (n_per_side, 1))\n    points_y = np.tile(points_one_side[:, None], (1, n_per_side))\n    return np.stack([points_x, points_y], axis=-1).reshape(-1, 2)\n\n\ndef build_all_layer_point_grids(n_per_side: int, n_layers: int, scale_per_layer: int) -> List[np.ndarray]:\n    \"\"\"Generate point grids for all crop layers.\"\"\"\n    return [build_point_grid(int(n_per_side / (scale_per_layer ** i))) for i in range(n_layers + 1)]\n\n\ndef generate_crop_boxes(im_size: Tuple[int, ...], n_layers: int,\n                        overlap_ratio: float) -> Tuple[List[List[int]], List[int]]:\n    \"\"\"Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.\"\"\"\n    crop_boxes, layer_idxs = [], []\n    im_h, im_w = im_size\n    short_side = min(im_h, im_w)\n\n    # Original image\n    crop_boxes.append([0, 0, im_w, im_h])\n    layer_idxs.append(0)\n\n    def crop_len(orig_len, n_crops, overlap):\n        \"\"\"Crops bounding boxes to the size of the input image.\"\"\"\n        return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops))\n\n    for i_layer in range(n_layers):\n        n_crops_per_side = 2 ** (i_layer + 1)\n        overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side))\n\n        crop_w = crop_len(im_w, n_crops_per_side, overlap)\n        crop_h = crop_len(im_h, n_crops_per_side, overlap)\n\n        crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)]\n        crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)]\n\n        # Crops in XYWH format\n        for x0, y0 in product(crop_box_x0, crop_box_y0):\n            box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)]\n            crop_boxes.append(box)\n            layer_idxs.append(i_layer + 1)\n\n    return crop_boxes, layer_idxs\n\n\ndef uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor:\n    \"\"\"Uncrop bounding boxes by adding the crop box offset.\"\"\"\n    x0, y0, _, _ = crop_box\n    offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device)\n    # Check if boxes has a channel dimension\n    if len(boxes.shape) == 3:\n        offset = offset.unsqueeze(1)\n    return boxes + offset\n\n\ndef uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor:\n    \"\"\"Uncrop points by adding the crop box offset.\"\"\"\n    x0, y0, _, _ = crop_box\n    offset = torch.tensor([[x0, y0]], device=points.device)\n    # Check if points has a channel dimension\n    if len(points.shape) == 3:\n        offset = offset.unsqueeze(1)\n    return points + offset\n\n\ndef uncrop_masks(masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int) -> torch.Tensor:\n    \"\"\"Uncrop masks by padding them to the original image size.\"\"\"\n    x0, y0, x1, y1 = crop_box\n    if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h:\n        return masks\n    # Coordinate transform masks\n    pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0)\n    pad = (x0, pad_x - x0, y0, pad_y - y0)\n    return torch.nn.functional.pad(masks, pad, value=0)\n\n\ndef remove_small_regions(mask: np.ndarray, area_thresh: float, mode: str) -> Tuple[np.ndarray, bool]:\n    \"\"\"Remove small disconnected regions or holes in a mask, returning the mask and a modification indicator.\"\"\"\n    import cv2  # type: ignore\n\n    assert mode in {'holes', 'islands'}\n    correct_holes = mode == 'holes'\n    working_mask = (correct_holes ^ mask).astype(np.uint8)\n    n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8)\n    sizes = stats[:, -1][1:]  # Row 0 is background label\n    small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh]\n    if not small_regions:\n        return mask, False\n    fill_labels = [0] + small_regions\n    if not correct_holes:\n        fill_labels = [i for i in range(n_labels) if i not in fill_labels]\n        # If every region is below threshold, keep largest\n        if not fill_labels:\n            fill_labels = [int(np.argmax(sizes)) + 1]\n    mask = np.isin(regions, fill_labels)\n    return mask, True\n\n\ndef coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]:\n    \"\"\"Encode uncompressed RLE (run-length encoding) to COCO RLE format.\"\"\"\n    from pycocotools import mask as mask_utils  # type: ignore\n\n    h, w = uncompressed_rle['size']\n    rle = mask_utils.frPyObjects(uncompressed_rle, h, w)\n    rle['counts'] = rle['counts'].decode('utf-8')  # Necessary to serialize with json\n    return rle\n\n\ndef batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor:\n    \"\"\"\n    Calculates boxes in XYXY format around masks. Return [0,0,0,0] for\n    an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.\n    \"\"\"\n    # torch.max below raises an error on empty inputs, just skip in this case\n    if torch.numel(masks) == 0:\n        return torch.zeros(*masks.shape[:-2], 4, device=masks.device)\n\n    # Normalize shape to CxHxW\n    shape = masks.shape\n    h, w = shape[-2:]\n    masks = masks.flatten(0, -3) if len(shape) > 2 else masks.unsqueeze(0)\n    # Get top and bottom edges\n    in_height, _ = torch.max(masks, dim=-1)\n    in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :]\n    bottom_edges, _ = torch.max(in_height_coords, dim=-1)\n    in_height_coords = in_height_coords + h * (~in_height)\n    top_edges, _ = torch.min(in_height_coords, dim=-1)\n\n    # Get left and right edges\n    in_width, _ = torch.max(masks, dim=-2)\n    in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :]\n    right_edges, _ = torch.max(in_width_coords, dim=-1)\n    in_width_coords = in_width_coords + w * (~in_width)\n    left_edges, _ = torch.min(in_width_coords, dim=-1)\n\n    # If the mask is empty the right edge will be to the left of the left edge.\n    # Replace these boxes with [0, 0, 0, 0]\n    empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)\n    out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1)\n    out = out * (~empty_filter).unsqueeze(-1)\n\n    # Return to original shape\n    return out.reshape(*shape[:-2], 4) if len(shape) > 2 else out[0]\n"
  },
  {
    "path": "ultralytics/vit/sam/autosize.py",
    "content": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom copy import deepcopy\nfrom typing import Tuple\n\nimport numpy as np\nimport torch\nfrom torch.nn import functional as F\nfrom torchvision.transforms.functional import resize, to_pil_image  # type: ignore\n\n\nclass ResizeLongestSide:\n    \"\"\"\n    Resizes images to the longest side 'target_length', as well as provides\n    methods for resizing coordinates and boxes. Provides methods for\n    transforming both numpy array and batched torch tensors.\n    \"\"\"\n\n    def __init__(self, target_length: int) -> None:\n        self.target_length = target_length\n\n    def apply_image(self, image: np.ndarray) -> np.ndarray:\n        \"\"\"\n        Expects a numpy array with shape HxWxC in uint8 format.\n        \"\"\"\n        target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length)\n        return np.array(resize(to_pil_image(image), target_size))\n\n    def apply_coords(self, coords: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray:\n        \"\"\"\n        Expects a numpy array of length 2 in the final dimension. Requires the\n        original image size in (H, W) format.\n        \"\"\"\n        old_h, old_w = original_size\n        new_h, new_w = self.get_preprocess_shape(original_size[0], original_size[1], self.target_length)\n        coords = deepcopy(coords).astype(float)\n        coords[..., 0] = coords[..., 0] * (new_w / old_w)\n        coords[..., 1] = coords[..., 1] * (new_h / old_h)\n        return coords\n\n    def apply_boxes(self, boxes: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray:\n        \"\"\"\n        Expects a numpy array shape Bx4. Requires the original image size\n        in (H, W) format.\n        \"\"\"\n        boxes = self.apply_coords(boxes.reshape(-1, 2, 2), original_size)\n        return boxes.reshape(-1, 4)\n\n    def apply_image_torch(self, image: torch.Tensor) -> torch.Tensor:\n        \"\"\"\n        Expects batched images with shape BxCxHxW and float format. This\n        transformation may not exactly match apply_image. apply_image is\n        the transformation expected by the model.\n        \"\"\"\n        # Expects an image in BCHW format. May not exactly match apply_image.\n        target_size = self.get_preprocess_shape(image.shape[2], image.shape[3], self.target_length)\n        return F.interpolate(image, target_size, mode='bilinear', align_corners=False, antialias=True)\n\n    def apply_coords_torch(self, coords: torch.Tensor, original_size: Tuple[int, ...]) -> torch.Tensor:\n        \"\"\"\n        Expects a torch tensor with length 2 in the last dimension. Requires the\n        original image size in (H, W) format.\n        \"\"\"\n        old_h, old_w = original_size\n        new_h, new_w = self.get_preprocess_shape(original_size[0], original_size[1], self.target_length)\n        coords = deepcopy(coords).to(torch.float)\n        coords[..., 0] = coords[..., 0] * (new_w / old_w)\n        coords[..., 1] = coords[..., 1] * (new_h / old_h)\n        return coords\n\n    def apply_boxes_torch(self, boxes: torch.Tensor, original_size: Tuple[int, ...]) -> torch.Tensor:\n        \"\"\"\n        Expects a torch tensor with shape Bx4. Requires the original image\n        size in (H, W) format.\n        \"\"\"\n        boxes = self.apply_coords_torch(boxes.reshape(-1, 2, 2), original_size)\n        return boxes.reshape(-1, 4)\n\n    @staticmethod\n    def get_preprocess_shape(oldh: int, oldw: int, long_side_length: int) -> Tuple[int, int]:\n        \"\"\"\n        Compute the output size given input size and target long side length.\n        \"\"\"\n        scale = long_side_length * 1.0 / max(oldh, oldw)\n        newh, neww = oldh * scale, oldw * scale\n        neww = int(neww + 0.5)\n        newh = int(newh + 0.5)\n        return (newh, neww)\n"
  },
  {
    "path": "ultralytics/vit/sam/build.py",
    "content": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom functools import partial\n\nimport torch\n\nfrom ...yolo.utils.downloads import attempt_download_asset\nfrom .modules.decoders import MaskDecoder\nfrom .modules.encoders import ImageEncoderViT, PromptEncoder\nfrom .modules.sam import Sam\nfrom .modules.transformer import TwoWayTransformer\n\n\ndef build_sam_vit_h(checkpoint=None):\n    \"\"\"Build and return a Segment Anything Model (SAM) h-size model.\"\"\"\n    return _build_sam(\n        encoder_embed_dim=1280,\n        encoder_depth=32,\n        encoder_num_heads=16,\n        encoder_global_attn_indexes=[7, 15, 23, 31],\n        checkpoint=checkpoint,\n    )\n\n\ndef build_sam_vit_l(checkpoint=None):\n    \"\"\"Build and return a Segment Anything Model (SAM) l-size model.\"\"\"\n    return _build_sam(\n        encoder_embed_dim=1024,\n        encoder_depth=24,\n        encoder_num_heads=16,\n        encoder_global_attn_indexes=[5, 11, 17, 23],\n        checkpoint=checkpoint,\n    )\n\n\ndef build_sam_vit_b(checkpoint=None):\n    \"\"\"Build and return a Segment Anything Model (SAM) b-size model.\"\"\"\n    return _build_sam(\n        encoder_embed_dim=768,\n        encoder_depth=12,\n        encoder_num_heads=12,\n        encoder_global_attn_indexes=[2, 5, 8, 11],\n        checkpoint=checkpoint,\n    )\n\n\ndef _build_sam(\n    encoder_embed_dim,\n    encoder_depth,\n    encoder_num_heads,\n    encoder_global_attn_indexes,\n    checkpoint=None,\n):\n    \"\"\"Builds the selected SAM model architecture.\"\"\"\n    prompt_embed_dim = 256\n    image_size = 1024\n    vit_patch_size = 16\n    image_embedding_size = image_size // vit_patch_size\n    sam = Sam(\n        image_encoder=ImageEncoderViT(\n            depth=encoder_depth,\n            embed_dim=encoder_embed_dim,\n            img_size=image_size,\n            mlp_ratio=4,\n            norm_layer=partial(torch.nn.LayerNorm, eps=1e-6),\n            num_heads=encoder_num_heads,\n            patch_size=vit_patch_size,\n            qkv_bias=True,\n            use_rel_pos=True,\n            global_attn_indexes=encoder_global_attn_indexes,\n            window_size=14,\n            out_chans=prompt_embed_dim,\n        ),\n        prompt_encoder=PromptEncoder(\n            embed_dim=prompt_embed_dim,\n            image_embedding_size=(image_embedding_size, image_embedding_size),\n            input_image_size=(image_size, image_size),\n            mask_in_chans=16,\n        ),\n        mask_decoder=MaskDecoder(\n            num_multimask_outputs=3,\n            transformer=TwoWayTransformer(\n                depth=2,\n                embedding_dim=prompt_embed_dim,\n                mlp_dim=2048,\n                num_heads=8,\n            ),\n            transformer_dim=prompt_embed_dim,\n            iou_head_depth=3,\n            iou_head_hidden_dim=256,\n        ),\n        pixel_mean=[123.675, 116.28, 103.53],\n        pixel_std=[58.395, 57.12, 57.375],\n    )\n    sam.eval()\n    if checkpoint is not None:\n        attempt_download_asset(checkpoint)\n        with open(checkpoint, 'rb') as f:\n            state_dict = torch.load(f)\n        sam.load_state_dict(state_dict)\n    return sam\n\n\nsam_model_map = {\n    # \"default\": build_sam_vit_h,\n    'sam_h.pt': build_sam_vit_h,\n    'sam_l.pt': build_sam_vit_l,\n    'sam_b.pt': build_sam_vit_b, }\n\n\ndef build_sam(ckpt='sam_b.pt'):\n    \"\"\"Build a SAM model specified by ckpt.\"\"\"\n    model_builder = None\n    for k in sam_model_map.keys():\n        if ckpt.endswith(k):\n            model_builder = sam_model_map.get(k)\n\n    if not model_builder:\n        raise FileNotFoundError(f'{ckpt} is not a supported sam model. Available models are: \\n {sam_model_map.keys()}')\n\n    return model_builder(ckpt)\n"
  },
  {
    "path": "ultralytics/vit/sam/model.py",
    "content": "# SAM model interface\n\nfrom ultralytics.yolo.cfg import get_cfg\n\nfrom .build import build_sam\nfrom .predict import Predictor\n\n\nclass SAM:\n\n    def __init__(self, model='sam_b.pt') -> None:\n        if model and not model.endswith('.pt') and not model.endswith('.pth'):\n            # Should raise AssertionError instead?\n            raise NotImplementedError('Segment anything prediction requires pre-trained checkpoint')\n        self.model = build_sam(model)\n        self.predictor = None  # reuse predictor\n\n    def predict(self, source, stream=False, **kwargs):\n        \"\"\"Predicts and returns segmentation masks for given image or video source.\"\"\"\n        overrides = dict(conf=0.25, task='segment', mode='predict')\n        overrides.update(kwargs)  # prefer kwargs\n        if not self.predictor:\n            self.predictor = Predictor(overrides=overrides)\n            self.predictor.setup_model(model=self.model)\n        else:  # only update args if predictor is already setup\n            self.predictor.args = get_cfg(self.predictor.args, overrides)\n        return self.predictor(source, stream=stream)\n\n    def train(self, **kwargs):\n        \"\"\"Function trains models but raises an error as SAM models do not support training.\"\"\"\n        raise NotImplementedError(\"SAM models don't support training\")\n\n    def val(self, **kwargs):\n        \"\"\"Run validation given dataset.\"\"\"\n        raise NotImplementedError(\"SAM models don't support validation\")\n"
  },
  {
    "path": "ultralytics/vit/sam/modules/__init__.py",
    "content": ""
  },
  {
    "path": "ultralytics/vit/sam/modules/decoders.py",
    "content": "from typing import List, Tuple, Type\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom ultralytics.nn.modules import LayerNorm2d\n\n\nclass MaskDecoder(nn.Module):\n\n    def __init__(\n        self,\n        *,\n        transformer_dim: int,\n        transformer: nn.Module,\n        num_multimask_outputs: int = 3,\n        activation: Type[nn.Module] = nn.GELU,\n        iou_head_depth: int = 3,\n        iou_head_hidden_dim: int = 256,\n    ) -> None:\n        \"\"\"\n        Predicts masks given an image and prompt embeddings, using a\n        transformer architecture.\n\n        Arguments:\n          transformer_dim (int): the channel dimension of the transformer\n          transformer (nn.Module): the transformer used to predict masks\n          num_multimask_outputs (int): the number of masks to predict\n            when disambiguating masks\n          activation (nn.Module): the type of activation to use when\n            upscaling masks\n          iou_head_depth (int): the depth of the MLP used to predict\n            mask quality\n          iou_head_hidden_dim (int): the hidden dimension of the MLP\n            used to predict mask quality\n        \"\"\"\n        super().__init__()\n        self.transformer_dim = transformer_dim\n        self.transformer = transformer\n\n        self.num_multimask_outputs = num_multimask_outputs\n\n        self.iou_token = nn.Embedding(1, transformer_dim)\n        self.num_mask_tokens = num_multimask_outputs + 1\n        self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)\n\n        self.output_upscaling = nn.Sequential(\n            nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2),\n            LayerNorm2d(transformer_dim // 4),\n            activation(),\n            nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2),\n            activation(),\n        )\n        self.output_hypernetworks_mlps = nn.ModuleList([\n            MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) for _ in range(self.num_mask_tokens)])\n\n        self.iou_prediction_head = MLP(transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth)\n\n    def forward(\n        self,\n        image_embeddings: torch.Tensor,\n        image_pe: torch.Tensor,\n        sparse_prompt_embeddings: torch.Tensor,\n        dense_prompt_embeddings: torch.Tensor,\n        multimask_output: bool,\n    ) -> Tuple[torch.Tensor, torch.Tensor]:\n        \"\"\"\n        Predict masks given image and prompt embeddings.\n\n        Arguments:\n          image_embeddings (torch.Tensor): the embeddings from the image encoder\n          image_pe (torch.Tensor): positional encoding with the shape of image_embeddings\n          sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes\n          dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs\n          multimask_output (bool): Whether to return multiple masks or a single\n            mask.\n\n        Returns:\n          torch.Tensor: batched predicted masks\n          torch.Tensor: batched predictions of mask quality\n        \"\"\"\n        masks, iou_pred = self.predict_masks(\n            image_embeddings=image_embeddings,\n            image_pe=image_pe,\n            sparse_prompt_embeddings=sparse_prompt_embeddings,\n            dense_prompt_embeddings=dense_prompt_embeddings,\n        )\n\n        # Select the correct mask or masks for output\n        mask_slice = slice(1, None) if multimask_output else slice(0, 1)\n        masks = masks[:, mask_slice, :, :]\n        iou_pred = iou_pred[:, mask_slice]\n\n        # Prepare output\n        return masks, iou_pred\n\n    def predict_masks(\n        self,\n        image_embeddings: torch.Tensor,\n        image_pe: torch.Tensor,\n        sparse_prompt_embeddings: torch.Tensor,\n        dense_prompt_embeddings: torch.Tensor,\n    ) -> Tuple[torch.Tensor, torch.Tensor]:\n        \"\"\"Predicts masks. See 'forward' for more details.\"\"\"\n        # Concatenate output tokens\n        output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)\n        output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1)\n        tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)\n\n        # Expand per-image data in batch direction to be per-mask\n        src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)\n        src = src + dense_prompt_embeddings\n        pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)\n        b, c, h, w = src.shape\n\n        # Run the transformer\n        hs, src = self.transformer(src, pos_src, tokens)\n        iou_token_out = hs[:, 0, :]\n        mask_tokens_out = hs[:, 1:(1 + self.num_mask_tokens), :]\n\n        # Upscale mask embeddings and predict masks using the mask tokens\n        src = src.transpose(1, 2).view(b, c, h, w)\n        upscaled_embedding = self.output_upscaling(src)\n        hyper_in_list: List[torch.Tensor] = [\n            self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]) for i in range(self.num_mask_tokens)]\n        hyper_in = torch.stack(hyper_in_list, dim=1)\n        b, c, h, w = upscaled_embedding.shape\n        masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)\n\n        # Generate mask quality predictions\n        iou_pred = self.iou_prediction_head(iou_token_out)\n\n        return masks, iou_pred\n\n\n# Lightly adapted from\n# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa\nclass MLP(nn.Module):\n\n    def __init__(\n        self,\n        input_dim: int,\n        hidden_dim: int,\n        output_dim: int,\n        num_layers: int,\n        sigmoid_output: bool = False,\n    ) -> None:\n        super().__init__()\n        self.num_layers = num_layers\n        h = [hidden_dim] * (num_layers - 1)\n        self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))\n        self.sigmoid_output = sigmoid_output\n\n    def forward(self, x):\n        \"\"\"Executes feedforward within the neural network module and applies activation.\"\"\"\n        for i, layer in enumerate(self.layers):\n            x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)\n        if self.sigmoid_output:\n            x = torch.sigmoid(x)\n        return x\n"
  },
  {
    "path": "ultralytics/vit/sam/modules/encoders.py",
    "content": "from typing import Any, Optional, Tuple, Type\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom ultralytics.nn.modules import LayerNorm2d, MLPBlock\n\n\n# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa\nclass ImageEncoderViT(nn.Module):\n\n    def __init__(\n            self,\n            img_size: int = 1024,\n            patch_size: int = 16,\n            in_chans: int = 3,\n            embed_dim: int = 768,\n            depth: int = 12,\n            num_heads: int = 12,\n            mlp_ratio: float = 4.0,\n            out_chans: int = 256,\n            qkv_bias: bool = True,\n            norm_layer: Type[nn.Module] = nn.LayerNorm,\n            act_layer: Type[nn.Module] = nn.GELU,\n            use_abs_pos: bool = True,\n            use_rel_pos: bool = False,\n            rel_pos_zero_init: bool = True,\n            window_size: int = 0,\n            global_attn_indexes: Tuple[int, ...] = (),\n    ) -> None:\n        \"\"\"\n        Args:\n            img_size (int): Input image size.\n            patch_size (int): Patch size.\n            in_chans (int): Number of input image channels.\n            embed_dim (int): Patch embedding dimension.\n            depth (int): Depth of ViT.\n            num_heads (int): Number of attention heads in each ViT block.\n            mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.\n            qkv_bias (bool): If True, add a learnable bias to query, key, value.\n            norm_layer (nn.Module): Normalization layer.\n            act_layer (nn.Module): Activation layer.\n            use_abs_pos (bool): If True, use absolute positional embeddings.\n            use_rel_pos (bool): If True, add relative positional embeddings to the attention map.\n            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.\n            window_size (int): Window size for window attention blocks.\n            global_attn_indexes (list): Indexes for blocks using global attention.\n        \"\"\"\n        super().__init__()\n        self.img_size = img_size\n\n        self.patch_embed = PatchEmbed(\n            kernel_size=(patch_size, patch_size),\n            stride=(patch_size, patch_size),\n            in_chans=in_chans,\n            embed_dim=embed_dim,\n        )\n\n        self.pos_embed: Optional[nn.Parameter] = None\n        if use_abs_pos:\n            # Initialize absolute positional embedding with pretrain image size.\n            self.pos_embed = nn.Parameter(torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim))\n\n        self.blocks = nn.ModuleList()\n        for i in range(depth):\n            block = Block(\n                dim=embed_dim,\n                num_heads=num_heads,\n                mlp_ratio=mlp_ratio,\n                qkv_bias=qkv_bias,\n                norm_layer=norm_layer,\n                act_layer=act_layer,\n                use_rel_pos=use_rel_pos,\n                rel_pos_zero_init=rel_pos_zero_init,\n                window_size=window_size if i not in global_attn_indexes else 0,\n                input_size=(img_size // patch_size, img_size // patch_size),\n            )\n            self.blocks.append(block)\n\n        self.neck = nn.Sequential(\n            nn.Conv2d(\n                embed_dim,\n                out_chans,\n                kernel_size=1,\n                bias=False,\n            ),\n            LayerNorm2d(out_chans),\n            nn.Conv2d(\n                out_chans,\n                out_chans,\n                kernel_size=3,\n                padding=1,\n                bias=False,\n            ),\n            LayerNorm2d(out_chans),\n        )\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.patch_embed(x)\n        if self.pos_embed is not None:\n            x = x + self.pos_embed\n\n        for blk in self.blocks:\n            x = blk(x)\n\n        x = self.neck(x.permute(0, 3, 1, 2))\n\n        return x\n\n\nclass PromptEncoder(nn.Module):\n\n    def __init__(\n        self,\n        embed_dim: int,\n        image_embedding_size: Tuple[int, int],\n        input_image_size: Tuple[int, int],\n        mask_in_chans: int,\n        activation: Type[nn.Module] = nn.GELU,\n    ) -> None:\n        \"\"\"\n        Encodes prompts for input to SAM's mask decoder.\n\n        Arguments:\n          embed_dim (int): The prompts' embedding dimension\n          image_embedding_size (tuple(int, int)): The spatial size of the\n            image embedding, as (H, W).\n          input_image_size (int): The padded size of the image as input\n            to the image encoder, as (H, W).\n          mask_in_chans (int): The number of hidden channels used for\n            encoding input masks.\n          activation (nn.Module): The activation to use when encoding\n            input masks.\n        \"\"\"\n        super().__init__()\n        self.embed_dim = embed_dim\n        self.input_image_size = input_image_size\n        self.image_embedding_size = image_embedding_size\n        self.pe_layer = PositionEmbeddingRandom(embed_dim // 2)\n\n        self.num_point_embeddings: int = 4  # pos/neg point + 2 box corners\n        point_embeddings = [nn.Embedding(1, embed_dim) for _ in range(self.num_point_embeddings)]\n        self.point_embeddings = nn.ModuleList(point_embeddings)\n        self.not_a_point_embed = nn.Embedding(1, embed_dim)\n\n        self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1])\n        self.mask_downscaling = nn.Sequential(\n            nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2),\n            LayerNorm2d(mask_in_chans // 4),\n            activation(),\n            nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2),\n            LayerNorm2d(mask_in_chans),\n            activation(),\n            nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1),\n        )\n        self.no_mask_embed = nn.Embedding(1, embed_dim)\n\n    def get_dense_pe(self) -> torch.Tensor:\n        \"\"\"\n        Returns the positional encoding used to encode point prompts,\n        applied to a dense set of points the shape of the image encoding.\n\n        Returns:\n          torch.Tensor: Positional encoding with shape\n            1x(embed_dim)x(embedding_h)x(embedding_w)\n        \"\"\"\n        return self.pe_layer(self.image_embedding_size).unsqueeze(0)\n\n    def _embed_points(\n        self,\n        points: torch.Tensor,\n        labels: torch.Tensor,\n        pad: bool,\n    ) -> torch.Tensor:\n        \"\"\"Embeds point prompts.\"\"\"\n        points = points + 0.5  # Shift to center of pixel\n        if pad:\n            padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device)\n            padding_label = -torch.ones((labels.shape[0], 1), device=labels.device)\n            points = torch.cat([points, padding_point], dim=1)\n            labels = torch.cat([labels, padding_label], dim=1)\n        point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size)\n        point_embedding[labels == -1] = 0.0\n        point_embedding[labels == -1] += self.not_a_point_embed.weight\n        point_embedding[labels == 0] += self.point_embeddings[0].weight\n        point_embedding[labels == 1] += self.point_embeddings[1].weight\n        return point_embedding\n\n    def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:\n        \"\"\"Embeds box prompts.\"\"\"\n        boxes = boxes + 0.5  # Shift to center of pixel\n        coords = boxes.reshape(-1, 2, 2)\n        corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size)\n        corner_embedding[:, 0, :] += self.point_embeddings[2].weight\n        corner_embedding[:, 1, :] += self.point_embeddings[3].weight\n        return corner_embedding\n\n    def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor:\n        \"\"\"Embeds mask inputs.\"\"\"\n        return self.mask_downscaling(masks)\n\n    def _get_batch_size(\n        self,\n        points: Optional[Tuple[torch.Tensor, torch.Tensor]],\n        boxes: Optional[torch.Tensor],\n        masks: Optional[torch.Tensor],\n    ) -> int:\n        \"\"\"\n        Gets the batch size of the output given the batch size of the input prompts.\n        \"\"\"\n        if points is not None:\n            return points[0].shape[0]\n        elif boxes is not None:\n            return boxes.shape[0]\n        elif masks is not None:\n            return masks.shape[0]\n        else:\n            return 1\n\n    def _get_device(self) -> torch.device:\n        return self.point_embeddings[0].weight.device\n\n    def forward(\n        self,\n        points: Optional[Tuple[torch.Tensor, torch.Tensor]],\n        boxes: Optional[torch.Tensor],\n        masks: Optional[torch.Tensor],\n    ) -> Tuple[torch.Tensor, torch.Tensor]:\n        \"\"\"\n        Embeds different types of prompts, returning both sparse and dense\n        embeddings.\n\n        Arguments:\n          points (tuple(torch.Tensor, torch.Tensor), None): point coordinates\n            and labels to embed.\n          boxes (torch.Tensor, None): boxes to embed\n          masks (torch.Tensor, None): masks to embed\n\n        Returns:\n          torch.Tensor: sparse embeddings for the points and boxes, with shape\n            BxNx(embed_dim), where N is determined by the number of input points\n            and boxes.\n          torch.Tensor: dense embeddings for the masks, in the shape\n            Bx(embed_dim)x(embed_H)x(embed_W)\n        \"\"\"\n        bs = self._get_batch_size(points, boxes, masks)\n        sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device())\n        if points is not None:\n            coords, labels = points\n            point_embeddings = self._embed_points(coords, labels, pad=(boxes is None))\n            sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1)\n        if boxes is not None:\n            box_embeddings = self._embed_boxes(boxes)\n            sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1)\n\n        if masks is not None:\n            dense_embeddings = self._embed_masks(masks)\n        else:\n            dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1,\n                                                                 1).expand(bs, -1, self.image_embedding_size[0],\n                                                                           self.image_embedding_size[1])\n\n        return sparse_embeddings, dense_embeddings\n\n\nclass PositionEmbeddingRandom(nn.Module):\n    \"\"\"\n    Positional encoding using random spatial frequencies.\n    \"\"\"\n\n    def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None:\n        super().__init__()\n        if scale is None or scale <= 0.0:\n            scale = 1.0\n        self.register_buffer(\n            'positional_encoding_gaussian_matrix',\n            scale * torch.randn((2, num_pos_feats)),\n        )\n\n    def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor:\n        \"\"\"Positionally encode points that are normalized to [0,1].\"\"\"\n        # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape\n        coords = 2 * coords - 1\n        coords = coords @ self.positional_encoding_gaussian_matrix\n        coords = 2 * np.pi * coords\n        # outputs d_1 x ... x d_n x C shape\n        return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)\n\n    def forward(self, size: Tuple[int, int]) -> torch.Tensor:\n        \"\"\"Generate positional encoding for a grid of the specified size.\"\"\"\n        h, w = size\n        device: Any = self.positional_encoding_gaussian_matrix.device\n        grid = torch.ones((h, w), device=device, dtype=torch.float32)\n        y_embed = grid.cumsum(dim=0) - 0.5\n        x_embed = grid.cumsum(dim=1) - 0.5\n        y_embed = y_embed / h\n        x_embed = x_embed / w\n\n        pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1))\n        return pe.permute(2, 0, 1)  # C x H x W\n\n    def forward_with_coords(self, coords_input: torch.Tensor, image_size: Tuple[int, int]) -> torch.Tensor:\n        \"\"\"Positionally encode points that are not normalized to [0,1].\"\"\"\n        coords = coords_input.clone()\n        coords[:, :, 0] = coords[:, :, 0] / image_size[1]\n        coords[:, :, 1] = coords[:, :, 1] / image_size[0]\n        return self._pe_encoding(coords.to(torch.float))  # B x N x C\n\n\nclass Block(nn.Module):\n    \"\"\"Transformer blocks with support of window attention and residual propagation blocks\"\"\"\n\n    def __init__(\n        self,\n        dim: int,\n        num_heads: int,\n        mlp_ratio: float = 4.0,\n        qkv_bias: bool = True,\n        norm_layer: Type[nn.Module] = nn.LayerNorm,\n        act_layer: Type[nn.Module] = nn.GELU,\n        use_rel_pos: bool = False,\n        rel_pos_zero_init: bool = True,\n        window_size: int = 0,\n        input_size: Optional[Tuple[int, int]] = None,\n    ) -> None:\n        \"\"\"\n        Args:\n            dim (int): Number of input channels.\n            num_heads (int): Number of attention heads in each ViT block.\n            mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.\n            qkv_bias (bool): If True, add a learnable bias to query, key, value.\n            norm_layer (nn.Module): Normalization layer.\n            act_layer (nn.Module): Activation layer.\n            use_rel_pos (bool): If True, add relative positional embeddings to the attention map.\n            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.\n            window_size (int): Window size for window attention blocks. If it equals 0, then\n                use global attention.\n            input_size (tuple(int, int), None): Input resolution for calculating the relative\n                positional parameter size.\n        \"\"\"\n        super().__init__()\n        self.norm1 = norm_layer(dim)\n        self.attn = Attention(\n            dim,\n            num_heads=num_heads,\n            qkv_bias=qkv_bias,\n            use_rel_pos=use_rel_pos,\n            rel_pos_zero_init=rel_pos_zero_init,\n            input_size=input_size if window_size == 0 else (window_size, window_size),\n        )\n\n        self.norm2 = norm_layer(dim)\n        self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer)\n\n        self.window_size = window_size\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        shortcut = x\n        x = self.norm1(x)\n        # Window partition\n        if self.window_size > 0:\n            H, W = x.shape[1], x.shape[2]\n            x, pad_hw = window_partition(x, self.window_size)\n\n        x = self.attn(x)\n        # Reverse window partition\n        if self.window_size > 0:\n            x = window_unpartition(x, self.window_size, pad_hw, (H, W))\n\n        x = shortcut + x\n        x = x + self.mlp(self.norm2(x))\n\n        return x\n\n\nclass Attention(nn.Module):\n    \"\"\"Multi-head Attention block with relative position embeddings.\"\"\"\n\n    def __init__(\n        self,\n        dim: int,\n        num_heads: int = 8,\n        qkv_bias: bool = True,\n        use_rel_pos: bool = False,\n        rel_pos_zero_init: bool = True,\n        input_size: Optional[Tuple[int, int]] = None,\n    ) -> None:\n        \"\"\"\n        Args:\n            dim (int): Number of input channels.\n            num_heads (int): Number of attention heads.\n            qkv_bias (bool):  If True, add a learnable bias to query, key, value.\n            rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.\n            input_size (tuple(int, int), None): Input resolution for calculating the relative\n                positional parameter size.\n        \"\"\"\n        super().__init__()\n        self.num_heads = num_heads\n        head_dim = dim // num_heads\n        self.scale = head_dim ** -0.5\n\n        self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)\n        self.proj = nn.Linear(dim, dim)\n\n        self.use_rel_pos = use_rel_pos\n        if self.use_rel_pos:\n            assert (input_size is not None), 'Input size must be provided if using relative positional encoding.'\n            # initialize relative positional embeddings\n            self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))\n            self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        B, H, W, _ = x.shape\n        # qkv with shape (3, B, nHead, H * W, C)\n        qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)\n        # q, k, v with shape (B * nHead, H * W, C)\n        q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)\n\n        attn = (q * self.scale) @ k.transpose(-2, -1)\n\n        if self.use_rel_pos:\n            attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W))\n\n        attn = attn.softmax(dim=-1)\n        x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)\n        x = self.proj(x)\n\n        return x\n\n\ndef window_partition(x: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]:\n    \"\"\"\n    Partition into non-overlapping windows with padding if needed.\n    Args:\n        x (tensor): input tokens with [B, H, W, C].\n        window_size (int): window size.\n\n    Returns:\n        windows: windows after partition with [B * num_windows, window_size, window_size, C].\n        (Hp, Wp): padded height and width before partition\n    \"\"\"\n    B, H, W, C = x.shape\n\n    pad_h = (window_size - H % window_size) % window_size\n    pad_w = (window_size - W % window_size) % window_size\n    if pad_h > 0 or pad_w > 0:\n        x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))\n    Hp, Wp = H + pad_h, W + pad_w\n\n    x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)\n    windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)\n    return windows, (Hp, Wp)\n\n\ndef window_unpartition(windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int],\n                       hw: Tuple[int, int]) -> torch.Tensor:\n    \"\"\"\n    Window unpartition into original sequences and removing padding.\n    Args:\n        windows (tensor): input tokens with [B * num_windows, window_size, window_size, C].\n        window_size (int): window size.\n        pad_hw (Tuple): padded height and width (Hp, Wp).\n        hw (Tuple): original height and width (H, W) before padding.\n\n    Returns:\n        x: unpartitioned sequences with [B, H, W, C].\n    \"\"\"\n    Hp, Wp = pad_hw\n    H, W = hw\n    B = windows.shape[0] // (Hp * Wp // window_size // window_size)\n    x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1)\n    x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)\n\n    if Hp > H or Wp > W:\n        x = x[:, :H, :W, :].contiguous()\n    return x\n\n\ndef get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:\n    \"\"\"\n    Get relative positional embeddings according to the relative positions of\n        query and key sizes.\n    Args:\n        q_size (int): size of query q.\n        k_size (int): size of key k.\n        rel_pos (Tensor): relative position embeddings (L, C).\n\n    Returns:\n        Extracted positional embeddings according to relative positions.\n    \"\"\"\n    max_rel_dist = int(2 * max(q_size, k_size) - 1)\n    # Interpolate rel pos if needed.\n    if rel_pos.shape[0] != max_rel_dist:\n        # Interpolate rel pos.\n        rel_pos_resized = F.interpolate(\n            rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),\n            size=max_rel_dist,\n            mode='linear',\n        )\n        rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)\n    else:\n        rel_pos_resized = rel_pos\n\n    # Scale the coords with short length if shapes for q and k are different.\n    q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)\n    k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)\n    relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)\n\n    return rel_pos_resized[relative_coords.long()]\n\n\ndef add_decomposed_rel_pos(\n    attn: torch.Tensor,\n    q: torch.Tensor,\n    rel_pos_h: torch.Tensor,\n    rel_pos_w: torch.Tensor,\n    q_size: Tuple[int, int],\n    k_size: Tuple[int, int],\n) -> torch.Tensor:\n    \"\"\"\n    Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.\n    https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py   # noqa B950\n    Args:\n        attn (Tensor): attention map.\n        q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C).\n        rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis.\n        rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis.\n        q_size (Tuple): spatial sequence size of query q with (q_h, q_w).\n        k_size (Tuple): spatial sequence size of key k with (k_h, k_w).\n\n    Returns:\n        attn (Tensor): attention map with added relative positional embeddings.\n    \"\"\"\n    q_h, q_w = q_size\n    k_h, k_w = k_size\n    Rh = get_rel_pos(q_h, k_h, rel_pos_h)\n    Rw = get_rel_pos(q_w, k_w, rel_pos_w)\n\n    B, _, dim = q.shape\n    r_q = q.reshape(B, q_h, q_w, dim)\n    rel_h = torch.einsum('bhwc,hkc->bhwk', r_q, Rh)\n    rel_w = torch.einsum('bhwc,wkc->bhwk', r_q, Rw)\n\n    attn = (attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]).view(\n        B, q_h * q_w, k_h * k_w)\n\n    return attn\n\n\nclass PatchEmbed(nn.Module):\n    \"\"\"\n    Image to Patch Embedding.\n    \"\"\"\n\n    def __init__(\n            self,\n            kernel_size: Tuple[int, int] = (16, 16),\n            stride: Tuple[int, int] = (16, 16),\n            padding: Tuple[int, int] = (0, 0),\n            in_chans: int = 3,\n            embed_dim: int = 768,\n    ) -> None:\n        \"\"\"\n        Args:\n            kernel_size (Tuple): kernel size of the projection layer.\n            stride (Tuple): stride of the projection layer.\n            padding (Tuple): padding size of the projection layer.\n            in_chans (int): Number of input image channels.\n            embed_dim (int): Patch embedding dimension.\n        \"\"\"\n        super().__init__()\n\n        self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding)\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.proj(x)\n        # B C H W -> B H W C\n        x = x.permute(0, 2, 3, 1)\n        return x\n"
  },
  {
    "path": "ultralytics/vit/sam/modules/mask_generator.py",
    "content": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport numpy as np\nimport torch\nfrom torchvision.ops.boxes import batched_nms, box_area  # type: ignore\n\nfrom ..amg import (MaskData, area_from_rle, batch_iterator, batched_mask_to_box, box_xyxy_to_xywh,\n                   build_all_layer_point_grids, calculate_stability_score, coco_encode_rle, generate_crop_boxes,\n                   is_box_near_crop_edge, mask_to_rle_pytorch, remove_small_regions, rle_to_mask, uncrop_boxes_xyxy,\n                   uncrop_masks, uncrop_points)\nfrom .prompt_predictor import PromptPredictor\nfrom .sam import Sam\n\n\nclass SamAutomaticMaskGenerator:\n\n    def __init__(\n        self,\n        model: Sam,\n        points_per_side: Optional[int] = 32,\n        points_per_batch: int = 64,\n        pred_iou_thresh: float = 0.88,\n        stability_score_thresh: float = 0.95,\n        stability_score_offset: float = 1.0,\n        box_nms_thresh: float = 0.7,\n        crop_n_layers: int = 0,\n        crop_nms_thresh: float = 0.7,\n        crop_overlap_ratio: float = 512 / 1500,\n        crop_n_points_downscale_factor: int = 1,\n        point_grids: Optional[List[np.ndarray]] = None,\n        min_mask_region_area: int = 0,\n        output_mode: str = 'binary_mask',\n    ) -> None:\n        \"\"\"\n        Using a SAM model, generates masks for the entire image.\n        Generates a grid of point prompts over the image, then filters\n        low quality and duplicate masks. The default settings are chosen\n        for SAM with a ViT-H backbone.\n\n        Arguments:\n          model (Sam): The SAM model to use for mask prediction.\n          points_per_side (int, None): The number of points to be sampled\n            along one side of the image. The total number of points is\n            points_per_side**2. If None, 'point_grids' must provide explicit\n            point sampling.\n          points_per_batch (int): Sets the number of points run simultaneously\n            by the model. Higher numbers may be faster but use more GPU memory.\n          pred_iou_thresh (float): A filtering threshold in [0,1], using the\n            model's predicted mask quality.\n          stability_score_thresh (float): A filtering threshold in [0,1], using\n            the stability of the mask under changes to the cutoff used to binarize\n            the model's mask predictions.\n          stability_score_offset (float): The amount to shift the cutoff when\n            calculated the stability score.\n          box_nms_thresh (float): The box IoU cutoff used by non-maximal\n            suppression to filter duplicate masks.\n          crop_n_layers (int): If >0, mask prediction will be run again on\n            crops of the image. Sets the number of layers to run, where each\n            layer has 2**i_layer number of image crops.\n          crop_nms_thresh (float): The box IoU cutoff used by non-maximal\n            suppression to filter duplicate masks between different crops.\n          crop_overlap_ratio (float): Sets the degree to which crops overlap.\n            In the first crop layer, crops will overlap by this fraction of\n            the image length. Later layers with more crops scale down this overlap.\n          crop_n_points_downscale_factor (int): The number of points-per-side\n            sampled in layer n is scaled down by crop_n_points_downscale_factor**n.\n          point_grids (list(np.ndarray), None): A list over explicit grids\n            of points used for sampling, normalized to [0,1]. The nth grid in the\n            list is used in the nth crop layer. Exclusive with points_per_side.\n          min_mask_region_area (int): If >0, postprocessing will be applied\n            to remove disconnected regions and holes in masks with area smaller\n            than min_mask_region_area. Requires opencv.\n          output_mode (str): The form masks are returned in. Can be 'binary_mask',\n            'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools.\n            For large resolutions, 'binary_mask' may consume large amounts of\n            memory.\n        \"\"\"\n\n        assert (points_per_side is None) != (point_grids is None), \\\n            'Exactly one of points_per_side or point_grid must be provided.'\n        if points_per_side is not None:\n            self.point_grids = build_all_layer_point_grids(\n                points_per_side,\n                crop_n_layers,\n                crop_n_points_downscale_factor,\n            )\n        elif point_grids is not None:\n            self.point_grids = point_grids\n        else:\n            raise ValueError(\"Can't have both points_per_side and point_grid be None.\")\n\n        assert output_mode in {'binary_mask', 'uncompressed_rle', 'coco_rle'}, f'Unknown output_mode {output_mode}.'\n        if output_mode == 'coco_rle':\n            from pycocotools import mask as mask_utils  # type: ignore # noqa: F401\n\n        if min_mask_region_area > 0:\n            import cv2  # type: ignore # noqa: F401\n\n        self.predictor = PromptPredictor(model)\n        self.points_per_batch = points_per_batch\n        self.pred_iou_thresh = pred_iou_thresh\n        self.stability_score_thresh = stability_score_thresh\n        self.stability_score_offset = stability_score_offset\n        self.box_nms_thresh = box_nms_thresh\n        self.crop_n_layers = crop_n_layers\n        self.crop_nms_thresh = crop_nms_thresh\n        self.crop_overlap_ratio = crop_overlap_ratio\n        self.crop_n_points_downscale_factor = crop_n_points_downscale_factor\n        self.min_mask_region_area = min_mask_region_area\n        self.output_mode = output_mode\n\n    # TODO: Temporary implementation for compatibility\n    def __call__(self, image: np.ndarray, augment=False, visualize=False) -> List[Dict[str, Any]]:\n        return self.generate(image)\n\n    @torch.no_grad()\n    def generate(self, image: np.ndarray) -> List[Dict[str, Any]]:\n        \"\"\"\n        Generates masks for the given image.\n\n        Arguments:\n          image (np.ndarray): The image to generate masks for, in HWC uint8 format.\n\n        Returns:\n           list(dict(str, any)): A list over records for masks. Each record is a dict containing the following keys:\n               segmentation (dict(str, any), np.ndarray): The mask. If\n                 output_mode='binary_mask', is an array of shape HW. Otherwise,\n                 is a dictionary containing the RLE.\n               bbox (list(float)): The box around the mask, in XYWH format.\n               area (int): The area in pixels of the mask.\n               predicted_iou (float): The model's own prediction of the mask's\n                 quality. This is filtered by the pred_iou_thresh parameter.\n               point_coords (list(list(float))): The point coordinates input\n                 to the model to generate this mask.\n               stability_score (float): A measure of the mask's quality. This\n                 is filtered on using the stability_score_thresh parameter.\n               crop_box (list(float)): The crop of the image used to generate\n                 the mask, given in XYWH format.\n        \"\"\"\n\n        # Generate masks\n        mask_data = self._generate_masks(image)\n\n        # Filter small disconnected regions and holes in masks\n        if self.min_mask_region_area > 0:\n            mask_data = self.postprocess_small_regions(\n                mask_data,\n                self.min_mask_region_area,\n                max(self.box_nms_thresh, self.crop_nms_thresh),\n            )\n\n        # Encode masks\n        if self.output_mode == 'coco_rle':\n            mask_data['segmentations'] = [coco_encode_rle(rle) for rle in mask_data['rles']]\n        elif self.output_mode == 'binary_mask':\n            mask_data['segmentations'] = [rle_to_mask(rle) for rle in mask_data['rles']]\n        else:\n            mask_data['segmentations'] = mask_data['rles']\n\n        # Write mask records\n        curr_anns = []\n        for idx in range(len(mask_data['segmentations'])):\n            ann = {\n                'segmentation': mask_data['segmentations'][idx],\n                'area': area_from_rle(mask_data['rles'][idx]),\n                'bbox': box_xyxy_to_xywh(mask_data['boxes'][idx]).tolist(),\n                'predicted_iou': mask_data['iou_preds'][idx].item(),\n                'point_coords': [mask_data['points'][idx].tolist()],\n                'stability_score': mask_data['stability_score'][idx].item(),\n                'crop_box': box_xyxy_to_xywh(mask_data['crop_boxes'][idx]).tolist(), }\n            curr_anns.append(ann)\n\n        return curr_anns\n\n    def _generate_masks(self, image: np.ndarray) -> MaskData:\n        orig_size = image.shape[:2]\n        crop_boxes, layer_idxs = generate_crop_boxes(orig_size, self.crop_n_layers, self.crop_overlap_ratio)\n\n        # Iterate over image crops\n        data = MaskData()\n        for crop_box, layer_idx in zip(crop_boxes, layer_idxs):\n            crop_data = self._process_crop(image, crop_box, layer_idx, orig_size)\n            data.cat(crop_data)\n\n        # Remove duplicate masks between crops\n        if len(crop_boxes) > 1:\n            # Prefer masks from smaller crops\n            scores = 1 / box_area(data['crop_boxes'])\n            scores = scores.to(data['boxes'].device)\n            keep_by_nms = batched_nms(\n                data['boxes'].float(),\n                scores,\n                torch.zeros_like(data['boxes'][:, 0]),  # categories\n                iou_threshold=self.crop_nms_thresh,\n            )\n            data.filter(keep_by_nms)\n\n        data.to_numpy()\n        return data\n\n    def _process_crop(\n        self,\n        image: np.ndarray,\n        crop_box: List[int],\n        crop_layer_idx: int,\n        orig_size: Tuple[int, ...],\n    ) -> MaskData:\n        # Crop the image and calculate embeddings\n        x0, y0, x1, y1 = crop_box\n        cropped_im = image[y0:y1, x0:x1, :]\n        cropped_im_size = cropped_im.shape[:2]\n        self.predictor.set_image(cropped_im)\n\n        # Get points for this crop\n        points_scale = np.array(cropped_im_size)[None, ::-1]\n        points_for_image = self.point_grids[crop_layer_idx] * points_scale\n\n        # Generate masks for this crop in batches\n        data = MaskData()\n        for (points, ) in batch_iterator(self.points_per_batch, points_for_image):\n            batch_data = self._process_batch(points, cropped_im_size, crop_box, orig_size)\n            data.cat(batch_data)\n            del batch_data\n        self.predictor.reset_image()\n\n        # Remove duplicates within this crop.\n        keep_by_nms = batched_nms(\n            data['boxes'].float(),\n            data['iou_preds'],\n            torch.zeros_like(data['boxes'][:, 0]),  # categories\n            iou_threshold=self.box_nms_thresh,\n        )\n        data.filter(keep_by_nms)\n\n        # Return to the original image frame\n        data['boxes'] = uncrop_boxes_xyxy(data['boxes'], crop_box)\n        data['points'] = uncrop_points(data['points'], crop_box)\n        data['crop_boxes'] = torch.tensor([crop_box for _ in range(len(data['rles']))])\n\n        return data\n\n    def _process_batch(\n        self,\n        points: np.ndarray,\n        im_size: Tuple[int, ...],\n        crop_box: List[int],\n        orig_size: Tuple[int, ...],\n    ) -> MaskData:\n        orig_h, orig_w = orig_size\n\n        # Run model on this batch\n        transformed_points = self.predictor.transform.apply_coords(points, im_size)\n        in_points = torch.as_tensor(transformed_points, device=self.predictor.device)\n        in_labels = torch.ones(in_points.shape[0], dtype=torch.int, device=in_points.device)\n        masks, iou_preds, _ = self.predictor.predict_torch(\n            in_points[:, None, :],\n            in_labels[:, None],\n            multimask_output=True,\n            return_logits=True,\n        )\n\n        # Serialize predictions and store in MaskData\n        data = MaskData(\n            masks=masks.flatten(0, 1),\n            iou_preds=iou_preds.flatten(0, 1),\n            points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)),\n        )\n        del masks\n\n        # Filter by predicted IoU\n        if self.pred_iou_thresh > 0.0:\n            keep_mask = data['iou_preds'] > self.pred_iou_thresh\n            data.filter(keep_mask)\n\n        # Calculate stability score\n        data['stability_score'] = calculate_stability_score(data['masks'], self.predictor.model.mask_threshold,\n                                                            self.stability_score_offset)\n        if self.stability_score_thresh > 0.0:\n            keep_mask = data['stability_score'] >= self.stability_score_thresh\n            data.filter(keep_mask)\n\n        # Threshold masks and calculate boxes\n        data['masks'] = data['masks'] > self.predictor.model.mask_threshold\n        data['boxes'] = batched_mask_to_box(data['masks'])\n\n        # Filter boxes that touch crop boundaries\n        keep_mask = ~is_box_near_crop_edge(data['boxes'], crop_box, [0, 0, orig_w, orig_h])\n        if not torch.all(keep_mask):\n            data.filter(keep_mask)\n\n        # Compress to RLE\n        data['masks'] = uncrop_masks(data['masks'], crop_box, orig_h, orig_w)\n        data['rles'] = mask_to_rle_pytorch(data['masks'])\n        del data['masks']\n\n        return data\n\n    @staticmethod\n    def postprocess_small_regions(mask_data: MaskData, min_area: int, nms_thresh: float) -> MaskData:\n        \"\"\"\n        Removes small disconnected regions and holes in masks, then reruns\n        box NMS to remove any new duplicates.\n\n        Edits mask_data in place.\n\n        Requires open-cv as a dependency.\n        \"\"\"\n        if len(mask_data['rles']) == 0:\n            return mask_data\n\n        # Filter small disconnected regions and holes\n        new_masks = []\n        scores = []\n        for rle in mask_data['rles']:\n            mask = rle_to_mask(rle)\n\n            mask, changed = remove_small_regions(mask, min_area, mode='holes')\n            unchanged = not changed\n            mask, changed = remove_small_regions(mask, min_area, mode='islands')\n            unchanged = unchanged and not changed\n\n            new_masks.append(torch.as_tensor(mask).unsqueeze(0))\n            # Give score=0 to changed masks and score=1 to unchanged masks\n            # so NMS will prefer ones that didn't need postprocessing\n            scores.append(float(unchanged))\n\n        # Recalculate boxes and remove any new duplicates\n        masks = torch.cat(new_masks, dim=0)\n        boxes = batched_mask_to_box(masks)\n        keep_by_nms = batched_nms(\n            boxes.float(),\n            torch.as_tensor(scores),\n            torch.zeros_like(boxes[:, 0]),  # categories\n            iou_threshold=nms_thresh,\n        )\n\n        # Only recalculate RLEs for masks that have changed\n        for i_mask in keep_by_nms:\n            if scores[i_mask] == 0.0:\n                mask_torch = masks[i_mask].unsqueeze(0)\n                mask_data['rles'][i_mask] = mask_to_rle_pytorch(mask_torch)[0]\n                mask_data['boxes'][i_mask] = boxes[i_mask]  # update res directly\n        mask_data.filter(keep_by_nms)\n\n        return mask_data\n"
  },
  {
    "path": "ultralytics/vit/sam/modules/prompt_predictor.py",
    "content": "from typing import Optional, Tuple\n\nimport numpy as np\nimport torch\n\nfrom ..autosize import ResizeLongestSide\nfrom .sam import Sam\n\n\nclass PromptPredictor:\n\n    def __init__(self, sam_model: Sam) -> None:\n        \"\"\"\n        Uses SAM to calculate the image embedding for an image, and then\n        allow repeated, efficient mask prediction given prompts.\n\n        Arguments:\n          sam_model (Sam): The model to use for mask prediction.\n        \"\"\"\n        super().__init__()\n        self.model = sam_model\n        self.transform = ResizeLongestSide(sam_model.image_encoder.img_size)\n        self.reset_image()\n\n    def set_image(self, image: np.ndarray, image_format: str = 'RGB') -> None:\n        \"\"\"\n        Calculates the image embeddings for the provided image, allowing\n        masks to be predicted with the 'predict' method.\n\n        Arguments:\n          image (np.ndarray): The image for calculating masks. Expects an\n            image in HWC uint8 format, with pixel values in [0, 255].\n          image_format (str): The color format of the image, in ['RGB', 'BGR'].\n        \"\"\"\n        assert image_format in {'RGB', 'BGR'}, f\"image_format must be in ['RGB', 'BGR'], is {image_format}.\"\n        if image_format != self.model.image_format:\n            image = image[..., ::-1]\n\n        # Transform the image to the form expected by the model\n        input_image = self.transform.apply_image(image)\n        input_image_torch = torch.as_tensor(input_image, device=self.device)\n        input_image_torch = input_image_torch.permute(2, 0, 1).contiguous()[None, :, :, :]\n\n        self.set_torch_image(input_image_torch, image.shape[:2])\n\n    @torch.no_grad()\n    def set_torch_image(self, transformed_image: torch.Tensor, original_image_size: Tuple[int, ...]) -> None:\n        \"\"\"\n        Calculates the image embeddings for the provided image, allowing\n        masks to be predicted with the 'predict' method. Expects the input\n        image to be already transformed to the format expected by the model.\n\n        Arguments:\n          transformed_image (torch.Tensor): The input image, with shape\n            1x3xHxW, which has been transformed with ResizeLongestSide.\n          original_image_size (tuple(int, int)): The size of the image\n            before transformation, in (H, W) format.\n        \"\"\"\n        if len(transformed_image.shape) != 4 \\\n                or transformed_image.shape[1] != 3 \\\n                or max(*transformed_image.shape[2:]) != self.model.image_encoder.img_size:\n            raise ValueError('set_torch_image input must be BCHW with long side {self.model.image_encoder.img_size}.')\n        self.reset_image()\n\n        self.original_size = original_image_size\n        self.input_size = tuple(transformed_image.shape[-2:])\n        input_image = self.model.preprocess(transformed_image)\n        self.features = self.model.image_encoder(input_image)\n        self.is_image_set = True\n\n    def predict(\n        self,\n        point_coords: Optional[np.ndarray] = None,\n        point_labels: Optional[np.ndarray] = None,\n        box: Optional[np.ndarray] = None,\n        mask_input: Optional[np.ndarray] = None,\n        multimask_output: bool = True,\n        return_logits: bool = False,\n    ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:\n        \"\"\"\n        Predict masks for the given input prompts, using the currently set image.\n\n        Arguments:\n          point_coords (np.ndarray, None): A Nx2 array of point prompts to the\n            model. Each point is in (X,Y) in pixels.\n          point_labels (np.ndarray, None): A length N array of labels for the\n            point prompts. 1 indicates a foreground point and 0 indicates a\n            background point.\n          box (np.ndarray, None): A length 4 array given a box prompt to the\n            model, in XYXY format.\n          mask_input (np.ndarray): A low resolution mask input to the model, typically\n            coming from a previous prediction iteration. Has form 1xHxW, where\n            for SAM, H=W=256.\n          multimask_output (bool): If true, the model will return three masks.\n            For ambiguous input prompts (such as a single click), this will often\n            produce better masks than a single prediction. If only a single\n            mask is needed, the model's predicted quality score can be used\n            to select the best mask. For non-ambiguous prompts, such as multiple\n            input prompts, multimask_output=False can give better results.\n          return_logits (bool): If true, returns un-thresholded masks logits\n            instead of a binary mask.\n\n        Returns:\n          (np.ndarray): The output masks in CxHxW format, where C is the\n            number of masks, and (H, W) is the original image size.\n          (np.ndarray): An array of length C containing the model's\n            predictions for the quality of each mask.\n          (np.ndarray): An array of shape CxHxW, where C is the number\n            of masks and H=W=256. These low resolution logits can be passed to\n            a subsequent iteration as mask input.\n        \"\"\"\n        if not self.is_image_set:\n            raise RuntimeError('An image must be set with .set_image(...) before mask prediction.')\n\n        # Transform input prompts\n        coords_torch, labels_torch, box_torch, mask_input_torch = None, None, None, None\n        if point_coords is not None:\n            assert (point_labels is not None), 'point_labels must be supplied if point_coords is supplied.'\n            point_coords = self.transform.apply_coords(point_coords, self.original_size)\n            coords_torch = torch.as_tensor(point_coords, dtype=torch.float, device=self.device)\n            labels_torch = torch.as_tensor(point_labels, dtype=torch.int, device=self.device)\n            coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :]\n        if box is not None:\n            box = self.transform.apply_boxes(box, self.original_size)\n            box_torch = torch.as_tensor(box, dtype=torch.float, device=self.device)\n            box_torch = box_torch[None, :]\n        if mask_input is not None:\n            mask_input_torch = torch.as_tensor(mask_input, dtype=torch.float, device=self.device)\n            mask_input_torch = mask_input_torch[None, :, :, :]\n\n        masks, iou_predictions, low_res_masks = self.predict_torch(\n            coords_torch,\n            labels_torch,\n            box_torch,\n            mask_input_torch,\n            multimask_output,\n            return_logits=return_logits,\n        )\n\n        masks_np = masks[0].detach().cpu().numpy()\n        iou_predictions_np = iou_predictions[0].detach().cpu().numpy()\n        low_res_masks_np = low_res_masks[0].detach().cpu().numpy()\n        return masks_np, iou_predictions_np, low_res_masks_np\n\n    @torch.no_grad()\n    def predict_torch(\n        self,\n        point_coords: Optional[torch.Tensor],\n        point_labels: Optional[torch.Tensor],\n        boxes: Optional[torch.Tensor] = None,\n        mask_input: Optional[torch.Tensor] = None,\n        multimask_output: bool = True,\n        return_logits: bool = False,\n    ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n        \"\"\"\n        Predict masks for the given input prompts, using the currently set image.\n        Input prompts are batched torch tensors and are expected to already be\n        transformed to the input frame using ResizeLongestSide.\n\n        Arguments:\n          point_coords (torch.Tensor, None): A BxNx2 array of point prompts to the\n            model. Each point is in (X,Y) in pixels.\n          point_labels (torch.Tensor, None): A BxN array of labels for the\n            point prompts. 1 indicates a foreground point and 0 indicates a\n            background point.\n          boxes (np.ndarray, None): A Bx4 array given a box prompt to the\n            model, in XYXY format.\n          mask_input (np.ndarray): A low resolution mask input to the model, typically\n            coming from a previous prediction iteration. Has form Bx1xHxW, where\n            for SAM, H=W=256. Masks returned by a previous iteration of the\n            predict method do not need further transformation.\n          multimask_output (bool): If true, the model will return three masks.\n            For ambiguous input prompts (such as a single click), this will often\n            produce better masks than a single prediction. If only a single\n            mask is needed, the model's predicted quality score can be used\n            to select the best mask. For non-ambiguous prompts, such as multiple\n            input prompts, multimask_output=False can give better results.\n          return_logits (bool): If true, returns un-thresholded masks logits\n            instead of a binary mask.\n\n        Returns:\n          (torch.Tensor): The output masks in BxCxHxW format, where C is the\n            number of masks, and (H, W) is the original image size.\n          (torch.Tensor): An array of shape BxC containing the model's\n            predictions for the quality of each mask.\n          (torch.Tensor): An array of shape BxCxHxW, where C is the number\n            of masks and H=W=256. These low res logits can be passed to\n            a subsequent iteration as mask input.\n        \"\"\"\n        if not self.is_image_set:\n            raise RuntimeError('An image must be set with .set_image(...) before mask prediction.')\n\n        points = (point_coords, point_labels) if point_coords is not None else None\n        # Embed prompts\n        sparse_embeddings, dense_embeddings = self.model.prompt_encoder(\n            points=points,\n            boxes=boxes,\n            masks=mask_input,\n        )\n\n        # Predict masks\n        low_res_masks, iou_predictions = self.model.mask_decoder(\n            image_embeddings=self.features,\n            image_pe=self.model.prompt_encoder.get_dense_pe(),\n            sparse_prompt_embeddings=sparse_embeddings,\n            dense_prompt_embeddings=dense_embeddings,\n            multimask_output=multimask_output,\n        )\n\n        # Upscale the masks to the original image resolution\n        masks = self.model.postprocess_masks(low_res_masks, self.input_size, self.original_size)\n\n        if not return_logits:\n            masks = masks > self.model.mask_threshold\n\n        return masks, iou_predictions, low_res_masks\n\n    def get_image_embedding(self) -> torch.Tensor:\n        \"\"\"\n        Returns the image embeddings for the currently set image, with\n        shape 1xCxHxW, where C is the embedding dimension and (H,W) are\n        the embedding spatial dimension of SAM (typically C=256, H=W=64).\n        \"\"\"\n        if not self.is_image_set:\n            raise RuntimeError('An image must be set with .set_image(...) to generate an embedding.')\n        assert self.features is not None, 'Features must exist if an image has been set.'\n        return self.features\n\n    @property\n    def device(self) -> torch.device:\n        return self.model.device\n\n    def reset_image(self) -> None:\n        \"\"\"Resets the currently set image.\"\"\"\n        self.is_image_set = False\n        self.features = None\n        self.orig_h = None\n        self.orig_w = None\n        self.input_h = None\n        self.input_w = None\n"
  },
  {
    "path": "ultralytics/vit/sam/modules/sam.py",
    "content": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom typing import Any, Dict, List, Tuple\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom .decoders import MaskDecoder\nfrom .encoders import ImageEncoderViT, PromptEncoder\n\n\nclass Sam(nn.Module):\n    mask_threshold: float = 0.0\n    image_format: str = 'RGB'\n\n    def __init__(\n        self,\n        image_encoder: ImageEncoderViT,\n        prompt_encoder: PromptEncoder,\n        mask_decoder: MaskDecoder,\n        pixel_mean: List[float] = [123.675, 116.28, 103.53],\n        pixel_std: List[float] = [58.395, 57.12, 57.375],\n    ) -> None:\n        \"\"\"\n        SAM predicts object masks from an image and input prompts.\n\n        Arguments:\n          image_encoder (ImageEncoderViT): The backbone used to encode the\n            image into image embeddings that allow for efficient mask prediction.\n          prompt_encoder (PromptEncoder): Encodes various types of input prompts.\n          mask_decoder (MaskDecoder): Predicts masks from the image embeddings\n            and encoded prompts.\n          pixel_mean (list(float)): Mean values for normalizing pixels in the input image.\n          pixel_std (list(float)): Std values for normalizing pixels in the input image.\n        \"\"\"\n        super().__init__()\n        self.image_encoder = image_encoder\n        self.prompt_encoder = prompt_encoder\n        self.mask_decoder = mask_decoder\n        self.register_buffer('pixel_mean', torch.Tensor(pixel_mean).view(-1, 1, 1), False)\n        self.register_buffer('pixel_std', torch.Tensor(pixel_std).view(-1, 1, 1), False)\n\n    @property\n    def device(self) -> Any:\n        return self.pixel_mean.device\n\n    @torch.no_grad()\n    def forward(\n        self,\n        batched_input: List[Dict[str, Any]],\n        multimask_output: bool,\n    ) -> List[Dict[str, torch.Tensor]]:\n        \"\"\"\n        Predicts masks end-to-end from provided images and prompts.\n        If prompts are not known in advance, using SamPredictor is\n        recommended over calling the model directly.\n\n        Arguments:\n          batched_input (list(dict)): A list over input images, each a\n            dictionary with the following keys. A prompt key can be\n            excluded if it is not present.\n              'image': The image as a torch tensor in 3xHxW format,\n                already transformed for input to the model.\n              'original_size': (tuple(int, int)) The original size of\n                the image before transformation, as (H, W).\n              'point_coords': (torch.Tensor) Batched point prompts for\n                this image, with shape BxNx2. Already transformed to the\n                input frame of the model.\n              'point_labels': (torch.Tensor) Batched labels for point prompts,\n                with shape BxN.\n              'boxes': (torch.Tensor) Batched box inputs, with shape Bx4.\n                Already transformed to the input frame of the model.\n              'mask_inputs': (torch.Tensor) Batched mask inputs to the model,\n                in the form Bx1xHxW.\n          multimask_output (bool): Whether the model should predict multiple\n            disambiguating masks, or return a single mask.\n\n        Returns:\n          (list(dict)): A list over input images, where each element is\n            as dictionary with the following keys.\n              'masks': (torch.Tensor) Batched binary mask predictions,\n                with shape BxCxHxW, where B is the number of input prompts,\n                C is determined by multimask_output, and (H, W) is the\n                original size of the image.\n              'iou_predictions': (torch.Tensor) The model's predictions\n                of mask quality, in shape BxC.\n              'low_res_logits': (torch.Tensor) Low resolution logits with\n                shape BxCxHxW, where H=W=256. Can be passed as mask input\n                to subsequent iterations of prediction.\n        \"\"\"\n        input_images = torch.stack([self.preprocess(x['image']) for x in batched_input], dim=0)\n        image_embeddings = self.image_encoder(input_images)\n\n        outputs = []\n        for image_record, curr_embedding in zip(batched_input, image_embeddings):\n            if 'point_coords' in image_record:\n                points = (image_record['point_coords'], image_record['point_labels'])\n            else:\n                points = None\n            sparse_embeddings, dense_embeddings = self.prompt_encoder(\n                points=points,\n                boxes=image_record.get('boxes', None),\n                masks=image_record.get('mask_inputs', None),\n            )\n            low_res_masks, iou_predictions = self.mask_decoder(\n                image_embeddings=curr_embedding.unsqueeze(0),\n                image_pe=self.prompt_encoder.get_dense_pe(),\n                sparse_prompt_embeddings=sparse_embeddings,\n                dense_prompt_embeddings=dense_embeddings,\n                multimask_output=multimask_output,\n            )\n            masks = self.postprocess_masks(\n                low_res_masks,\n                input_size=image_record['image'].shape[-2:],\n                original_size=image_record['original_size'],\n            )\n            masks = masks > self.mask_threshold\n            outputs.append({\n                'masks': masks,\n                'iou_predictions': iou_predictions,\n                'low_res_logits': low_res_masks, })\n        return outputs\n\n    def postprocess_masks(\n        self,\n        masks: torch.Tensor,\n        input_size: Tuple[int, ...],\n        original_size: Tuple[int, ...],\n    ) -> torch.Tensor:\n        \"\"\"\n        Remove padding and upscale masks to the original image size.\n\n        Arguments:\n          masks (torch.Tensor): Batched masks from the mask_decoder,\n            in BxCxHxW format.\n          input_size (tuple(int, int)): The size of the image input to the\n            model, in (H, W) format. Used to remove padding.\n          original_size (tuple(int, int)): The original size of the image\n            before resizing for input to the model, in (H, W) format.\n\n        Returns:\n          (torch.Tensor): Batched masks in BxCxHxW format, where (H, W)\n            is given by original_size.\n        \"\"\"\n        masks = F.interpolate(\n            masks,\n            (self.image_encoder.img_size, self.image_encoder.img_size),\n            mode='bilinear',\n            align_corners=False,\n        )\n        masks = masks[..., :input_size[0], :input_size[1]]\n        masks = F.interpolate(masks, original_size, mode='bilinear', align_corners=False)\n        return masks\n\n    def preprocess(self, x: torch.Tensor) -> torch.Tensor:\n        \"\"\"Normalize pixel values and pad to a square input.\"\"\"\n        # Normalize colors\n        x = (x - self.pixel_mean) / self.pixel_std\n\n        # Pad\n        h, w = x.shape[-2:]\n        padh = self.image_encoder.img_size - h\n        padw = self.image_encoder.img_size - w\n        return F.pad(x, (0, padw, 0, padh))\n"
  },
  {
    "path": "ultralytics/vit/sam/modules/transformer.py",
    "content": "import math\nfrom typing import Tuple, Type\n\nimport torch\nfrom torch import Tensor, nn\n\nfrom ultralytics.nn.modules import MLPBlock\n\n\nclass TwoWayTransformer(nn.Module):\n\n    def __init__(\n        self,\n        depth: int,\n        embedding_dim: int,\n        num_heads: int,\n        mlp_dim: int,\n        activation: Type[nn.Module] = nn.ReLU,\n        attention_downsample_rate: int = 2,\n    ) -> None:\n        \"\"\"\n        A transformer decoder that attends to an input image using\n        queries whose positional embedding is supplied.\n\n        Args:\n          depth (int): number of layers in the transformer\n          embedding_dim (int): the channel dimension for the input embeddings\n          num_heads (int): the number of heads for multihead attention. Must\n            divide embedding_dim\n          mlp_dim (int): the channel dimension internal to the MLP block\n          activation (nn.Module): the activation to use in the MLP block\n        \"\"\"\n        super().__init__()\n        self.depth = depth\n        self.embedding_dim = embedding_dim\n        self.num_heads = num_heads\n        self.mlp_dim = mlp_dim\n        self.layers = nn.ModuleList()\n\n        for i in range(depth):\n            self.layers.append(\n                TwoWayAttentionBlock(\n                    embedding_dim=embedding_dim,\n                    num_heads=num_heads,\n                    mlp_dim=mlp_dim,\n                    activation=activation,\n                    attention_downsample_rate=attention_downsample_rate,\n                    skip_first_layer_pe=(i == 0),\n                ))\n\n        self.final_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)\n        self.norm_final_attn = nn.LayerNorm(embedding_dim)\n\n    def forward(\n        self,\n        image_embedding: Tensor,\n        image_pe: Tensor,\n        point_embedding: Tensor,\n    ) -> Tuple[Tensor, Tensor]:\n        \"\"\"\n        Args:\n          image_embedding (torch.Tensor): image to attend to. Should be shape\n            B x embedding_dim x h x w for any h and w.\n          image_pe (torch.Tensor): the positional encoding to add to the image. Must\n            have the same shape as image_embedding.\n          point_embedding (torch.Tensor): the embedding to add to the query points.\n            Must have shape B x N_points x embedding_dim for any N_points.\n\n        Returns:\n          torch.Tensor: the processed point_embedding\n          torch.Tensor: the processed image_embedding\n        \"\"\"\n        # BxCxHxW -> BxHWxC == B x N_image_tokens x C\n        bs, c, h, w = image_embedding.shape\n        image_embedding = image_embedding.flatten(2).permute(0, 2, 1)\n        image_pe = image_pe.flatten(2).permute(0, 2, 1)\n\n        # Prepare queries\n        queries = point_embedding\n        keys = image_embedding\n\n        # Apply transformer blocks and final layernorm\n        for layer in self.layers:\n            queries, keys = layer(\n                queries=queries,\n                keys=keys,\n                query_pe=point_embedding,\n                key_pe=image_pe,\n            )\n\n        # Apply the final attention layer from the points to the image\n        q = queries + point_embedding\n        k = keys + image_pe\n        attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)\n        queries = queries + attn_out\n        queries = self.norm_final_attn(queries)\n\n        return queries, keys\n\n\nclass TwoWayAttentionBlock(nn.Module):\n\n    def __init__(\n        self,\n        embedding_dim: int,\n        num_heads: int,\n        mlp_dim: int = 2048,\n        activation: Type[nn.Module] = nn.ReLU,\n        attention_downsample_rate: int = 2,\n        skip_first_layer_pe: bool = False,\n    ) -> None:\n        \"\"\"\n        A transformer block with four layers: (1) self-attention of sparse\n        inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp\n        block on sparse inputs, and (4) cross attention of dense inputs to sparse\n        inputs.\n\n        Arguments:\n          embedding_dim (int): the channel dimension of the embeddings\n          num_heads (int): the number of heads in the attention layers\n          mlp_dim (int): the hidden dimension of the mlp block\n          activation (nn.Module): the activation of the mlp block\n          skip_first_layer_pe (bool): skip the PE on the first layer\n        \"\"\"\n        super().__init__()\n        self.self_attn = Attention(embedding_dim, num_heads)\n        self.norm1 = nn.LayerNorm(embedding_dim)\n\n        self.cross_attn_token_to_image = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)\n        self.norm2 = nn.LayerNorm(embedding_dim)\n\n        self.mlp = MLPBlock(embedding_dim, mlp_dim, activation)\n        self.norm3 = nn.LayerNorm(embedding_dim)\n\n        self.norm4 = nn.LayerNorm(embedding_dim)\n        self.cross_attn_image_to_token = Attention(embedding_dim, num_heads, downsample_rate=attention_downsample_rate)\n\n        self.skip_first_layer_pe = skip_first_layer_pe\n\n    def forward(self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor) -> Tuple[Tensor, Tensor]:\n        \"\"\"Apply self-attention and cross-attention to queries and keys and return the processed embeddings.\"\"\"\n\n        # Self attention block\n        if self.skip_first_layer_pe:\n            queries = self.self_attn(q=queries, k=queries, v=queries)\n        else:\n            q = queries + query_pe\n            attn_out = self.self_attn(q=q, k=q, v=queries)\n            queries = queries + attn_out\n        queries = self.norm1(queries)\n\n        # Cross attention block, tokens attending to image embedding\n        q = queries + query_pe\n        k = keys + key_pe\n        attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)\n        queries = queries + attn_out\n        queries = self.norm2(queries)\n\n        # MLP block\n        mlp_out = self.mlp(queries)\n        queries = queries + mlp_out\n        queries = self.norm3(queries)\n\n        # Cross attention block, image embedding attending to tokens\n        q = queries + query_pe\n        k = keys + key_pe\n        attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)\n        keys = keys + attn_out\n        keys = self.norm4(keys)\n\n        return queries, keys\n\n\nclass Attention(nn.Module):\n    \"\"\"\n    An attention layer that allows for downscaling the size of the embedding\n    after projection to queries, keys, and values.\n    \"\"\"\n\n    def __init__(\n        self,\n        embedding_dim: int,\n        num_heads: int,\n        downsample_rate: int = 1,\n    ) -> None:\n        super().__init__()\n        self.embedding_dim = embedding_dim\n        self.internal_dim = embedding_dim // downsample_rate\n        self.num_heads = num_heads\n        assert self.internal_dim % num_heads == 0, 'num_heads must divide embedding_dim.'\n\n        self.q_proj = nn.Linear(embedding_dim, self.internal_dim)\n        self.k_proj = nn.Linear(embedding_dim, self.internal_dim)\n        self.v_proj = nn.Linear(embedding_dim, self.internal_dim)\n        self.out_proj = nn.Linear(self.internal_dim, embedding_dim)\n\n    def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor:\n        \"\"\"Separate the input tensor into the specified number of attention heads.\"\"\"\n        b, n, c = x.shape\n        x = x.reshape(b, n, num_heads, c // num_heads)\n        return x.transpose(1, 2)  # B x N_heads x N_tokens x C_per_head\n\n    def _recombine_heads(self, x: Tensor) -> Tensor:\n        \"\"\"Recombine the separated attention heads into a single tensor.\"\"\"\n        b, n_heads, n_tokens, c_per_head = x.shape\n        x = x.transpose(1, 2)\n        return x.reshape(b, n_tokens, n_heads * c_per_head)  # B x N_tokens x C\n\n    def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:\n        \"\"\"Compute the attention output given the input query, key, and value tensors.\"\"\"\n\n        # Input projections\n        q = self.q_proj(q)\n        k = self.k_proj(k)\n        v = self.v_proj(v)\n\n        # Separate into heads\n        q = self._separate_heads(q, self.num_heads)\n        k = self._separate_heads(k, self.num_heads)\n        v = self._separate_heads(v, self.num_heads)\n\n        # Attention\n        _, _, _, c_per_head = q.shape\n        attn = q @ k.permute(0, 1, 3, 2)  # B x N_heads x N_tokens x N_tokens\n        attn = attn / math.sqrt(c_per_head)\n        attn = torch.softmax(attn, dim=-1)\n\n        # Get output\n        out = attn @ v\n        out = self._recombine_heads(out)\n        out = self.out_proj(out)\n\n        return out\n"
  },
  {
    "path": "ultralytics/vit/sam/predict.py",
    "content": "import numpy as np\nimport torch\n\nfrom ultralytics.yolo.engine.predictor import BasePredictor\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils.torch_utils import select_device\n\nfrom .modules.mask_generator import SamAutomaticMaskGenerator\n\n\nclass Predictor(BasePredictor):\n\n    def preprocess(self, im):\n        \"\"\"Prepares input image for inference.\"\"\"\n        # TODO: Only support bs=1 for now\n        # im = ResizeLongestSide(1024).apply_image(im[0])\n        # im = torch.as_tensor(im, device=self.device)\n        # im = im.permute(2, 0, 1).contiguous()[None, :, :, :]\n        return im[0]\n\n    def setup_model(self, model):\n        \"\"\"Set up YOLO model with specified thresholds and device.\"\"\"\n        device = select_device(self.args.device)\n        model.eval()\n        self.model = SamAutomaticMaskGenerator(model.to(device),\n                                               pred_iou_thresh=self.args.conf,\n                                               box_nms_thresh=self.args.iou)\n        self.device = device\n        # TODO: Temporary settings for compatibility\n        self.model.pt = False\n        self.model.triton = False\n        self.model.stride = 32\n        self.model.fp16 = False\n        self.done_warmup = True\n\n    def postprocess(self, preds, path, orig_imgs):\n        \"\"\"Postprocesses inference output predictions to create detection masks for objects.\"\"\"\n        names = dict(enumerate(list(range(len(preds)))))\n        results = []\n        # TODO\n        for i, pred in enumerate([preds]):\n            masks = torch.from_numpy(np.stack([p['segmentation'] for p in pred], axis=0))\n            orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            results.append(Results(orig_img=orig_img, path=img_path, names=names, masks=masks))\n        return results\n\n    # def __call__(self, source=None, model=None, stream=False):\n    #     frame = cv2.imread(source)\n    #     preds = self.model.generate(frame)\n    #     return self.postprocess(preds, source, frame)\n"
  },
  {
    "path": "ultralytics/yolo/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom . import v8\n\n__all__ = 'v8',  # tuple or list\n"
  },
  {
    "path": "ultralytics/yolo/cfg/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nimport contextlib\nimport re\nimport shutil\nimport sys\nfrom difflib import get_close_matches\nfrom pathlib import Path\nfrom types import SimpleNamespace\nfrom typing import Dict, List, Union\n\nfrom ultralytics.yolo.utils import (DEFAULT_CFG, DEFAULT_CFG_DICT, DEFAULT_CFG_PATH, LOGGER, ROOT, USER_CONFIG_DIR,\n                                    IterableSimpleNamespace, __version__, checks, colorstr, deprecation_warn,\n                                    get_settings, yaml_load, yaml_print)\n\n# Define valid tasks and modes\nMODES = 'train', 'val', 'predict', 'export', 'track', 'benchmark'\nTASKS = 'detect', 'segment', 'classify', 'pose'\nTASK2DATA = {\n    'detect': 'coco128.yaml',\n    'segment': 'coco128-seg.yaml',\n    'classify': 'imagenet100',\n    'pose': 'coco8-pose.yaml'}\nTASK2MODEL = {\n    'detect': 'yolov8n.pt',\n    'segment': 'yolov8n-seg.pt',\n    'classify': 'yolov8n-cls.pt',\n    'pose': 'yolov8n-pose.pt'}\n\nCLI_HELP_MSG = \\\n    f\"\"\"\n    Arguments received: {str(['yolo'] + sys.argv[1:])}. Ultralytics 'yolo' commands use the following syntax:\n\n        yolo TASK MODE ARGS\n\n        Where   TASK (optional) is one of {TASKS}\n                MODE (required) is one of {MODES}\n                ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.\n                    See all ARGS at https://docs.ultralytics.com/usage/cfg or with 'yolo cfg'\n\n    1. Train a detection model for 10 epochs with an initial learning_rate of 0.01\n        yolo train data=coco128.yaml model=yolov8n.pt epochs=10 lr0=0.01\n\n    2. Predict a YouTube video using a pretrained segmentation model at image size 320:\n        yolo predict model=yolov8n-seg.pt source='https://youtu.be/Zgi9g1ksQHc' imgsz=320\n\n    3. Val a pretrained detection model at batch-size 1 and image size 640:\n        yolo val model=yolov8n.pt data=coco128.yaml batch=1 imgsz=640\n\n    4. Export a YOLOv8n classification model to ONNX format at image size 224 by 128 (no TASK required)\n        yolo export model=yolov8n-cls.pt format=onnx imgsz=224,128\n\n    5. Run special commands:\n        yolo help\n        yolo checks\n        yolo version\n        yolo settings\n        yolo copy-cfg\n        yolo cfg\n\n    Docs: https://docs.ultralytics.com\n    Community: https://community.ultralytics.com\n    GitHub: https://github.com/ultralytics/ultralytics\n    \"\"\"\n\n# Define keys for arg type checks\nCFG_FLOAT_KEYS = 'warmup_epochs', 'box', 'cls', 'dfl', 'degrees', 'shear'\nCFG_FRACTION_KEYS = ('dropout', 'iou', 'lr0', 'lrf', 'momentum', 'weight_decay', 'warmup_momentum', 'warmup_bias_lr',\n                     'label_smoothing', 'hsv_h', 'hsv_s', 'hsv_v', 'translate', 'scale', 'perspective', 'flipud',\n                     'fliplr', 'mosaic', 'mixup', 'copy_paste', 'conf', 'iou')  # fractional floats limited to 0.0 - 1.0\nCFG_INT_KEYS = ('epochs', 'patience', 'batch', 'workers', 'seed', 'close_mosaic', 'mask_ratio', 'max_det', 'vid_stride',\n                'line_width', 'workspace', 'nbs', 'save_period')\nCFG_BOOL_KEYS = ('save', 'exist_ok', 'verbose', 'deterministic', 'single_cls', 'rect', 'cos_lr', 'overlap_mask', 'val',\n                 'save_json', 'save_hybrid', 'half', 'dnn', 'plots', 'show', 'save_txt', 'save_conf', 'save_crop',\n                 'show_labels', 'show_conf', 'visualize', 'augment', 'agnostic_nms', 'retina_masks', 'boxes', 'keras',\n                 'optimize', 'int8', 'dynamic', 'simplify', 'nms', 'v5loader')\n\n\ndef cfg2dict(cfg):\n    \"\"\"\n    Convert a configuration object to a dictionary, whether it is a file path, a string, or a SimpleNamespace object.\n\n    Inputs:\n        cfg (str) or (Path) or (SimpleNamespace): Configuration object to be converted to a dictionary.\n\n    Returns:\n        cfg (dict): Configuration object in dictionary format.\n    \"\"\"\n    if isinstance(cfg, (str, Path)):\n        cfg = yaml_load(cfg)  # load dict\n    elif isinstance(cfg, SimpleNamespace):\n        cfg = vars(cfg)  # convert to dict\n    return cfg\n\n\ndef get_cfg(cfg: Union[str, Path, Dict, SimpleNamespace] = DEFAULT_CFG_DICT, overrides: Dict = None):\n    \"\"\"\n    Load and merge configuration data from a file or dictionary.\n\n    Args:\n        cfg (str) or (Path) or (Dict) or (SimpleNamespace): Configuration data.\n        overrides (str) or (Dict), optional: Overrides in the form of a file name or a dictionary. Default is None.\n\n    Returns:\n        (SimpleNamespace): Training arguments namespace.\n    \"\"\"\n    cfg = cfg2dict(cfg)\n\n    # Merge overrides\n    if overrides:\n        overrides = cfg2dict(overrides)\n        check_cfg_mismatch(cfg, overrides)\n        cfg = {**cfg, **overrides}  # merge cfg and overrides dicts (prefer overrides)\n\n    # Special handling for numeric project/names\n    for k in 'project', 'name':\n        if k in cfg and isinstance(cfg[k], (int, float)):\n            cfg[k] = str(cfg[k])\n\n    # Type and Value checks\n    for k, v in cfg.items():\n        if v is not None:  # None values may be from optional args\n            if k in CFG_FLOAT_KEYS and not isinstance(v, (int, float)):\n                raise TypeError(f\"'{k}={v}' is of invalid type {type(v).__name__}. \"\n                                f\"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')\")\n            elif k in CFG_FRACTION_KEYS:\n                if not isinstance(v, (int, float)):\n                    raise TypeError(f\"'{k}={v}' is of invalid type {type(v).__name__}. \"\n                                    f\"Valid '{k}' types are int (i.e. '{k}=0') or float (i.e. '{k}=0.5')\")\n                if not (0.0 <= v <= 1.0):\n                    raise ValueError(f\"'{k}={v}' is an invalid value. \"\n                                     f\"Valid '{k}' values are between 0.0 and 1.0.\")\n            elif k in CFG_INT_KEYS and not isinstance(v, int):\n                raise TypeError(f\"'{k}={v}' is of invalid type {type(v).__name__}. \"\n                                f\"'{k}' must be an int (i.e. '{k}=8')\")\n            elif k in CFG_BOOL_KEYS and not isinstance(v, bool):\n                raise TypeError(f\"'{k}={v}' is of invalid type {type(v).__name__}. \"\n                                f\"'{k}' must be a bool (i.e. '{k}=True' or '{k}=False')\")\n\n    # Return instance\n    return IterableSimpleNamespace(**cfg)\n\n\ndef _handle_deprecation(custom):\n    \"\"\"\n    Hardcoded function to handle deprecated config keys\n    \"\"\"\n\n    for key in custom.copy().keys():\n        if key == 'hide_labels':\n            deprecation_warn(key, 'show_labels')\n            custom['show_labels'] = custom.pop('hide_labels') == 'False'\n        if key == 'hide_conf':\n            deprecation_warn(key, 'show_conf')\n            custom['show_conf'] = custom.pop('hide_conf') == 'False'\n        if key == 'line_thickness':\n            deprecation_warn(key, 'line_width')\n            custom['line_width'] = custom.pop('line_thickness')\n\n    return custom\n\n\ndef check_cfg_mismatch(base: Dict, custom: Dict, e=None):\n    \"\"\"\n    This function checks for any mismatched keys between a custom configuration list and a base configuration list.\n    If any mismatched keys are found, the function prints out similar keys from the base list and exits the program.\n\n    Inputs:\n        - custom (Dict): a dictionary of custom configuration options\n        - base (Dict): a dictionary of base configuration options\n    \"\"\"\n    custom = _handle_deprecation(custom)\n    base, custom = (set(x.keys()) for x in (base, custom))\n    mismatched = [x for x in custom if x not in base]\n    if mismatched:\n        string = ''\n        for x in mismatched:\n            matches = get_close_matches(x, base)  # key list\n            matches = [f'{k}={DEFAULT_CFG_DICT[k]}' if DEFAULT_CFG_DICT.get(k) is not None else k for k in matches]\n            match_str = f'Similar arguments are i.e. {matches}.' if matches else ''\n            string += f\"'{colorstr('red', 'bold', x)}' is not a valid YOLO argument. {match_str}\\n\"\n        raise SyntaxError(string + CLI_HELP_MSG) from e\n\n\ndef merge_equals_args(args: List[str]) -> List[str]:\n    \"\"\"\n    Merges arguments around isolated '=' args in a list of strings.\n    The function considers cases where the first argument ends with '=' or the second starts with '=',\n    as well as when the middle one is an equals sign.\n\n    Args:\n        args (List[str]): A list of strings where each element is an argument.\n\n    Returns:\n        List[str]: A list of strings where the arguments around isolated '=' are merged.\n    \"\"\"\n    new_args = []\n    for i, arg in enumerate(args):\n        if arg == '=' and 0 < i < len(args) - 1:  # merge ['arg', '=', 'val']\n            new_args[-1] += f'={args[i + 1]}'\n            del args[i + 1]\n        elif arg.endswith('=') and i < len(args) - 1 and '=' not in args[i + 1]:  # merge ['arg=', 'val']\n            new_args.append(f'{arg}{args[i + 1]}')\n            del args[i + 1]\n        elif arg.startswith('=') and i > 0:  # merge ['arg', '=val']\n            new_args[-1] += arg\n        else:\n            new_args.append(arg)\n    return new_args\n\n\ndef handle_yolo_hub(args: List[str]) -> None:\n    \"\"\"\n    Handle Ultralytics HUB command-line interface (CLI) commands.\n\n    This function processes Ultralytics HUB CLI commands such as login and logout.\n    It should be called when executing a script with arguments related to HUB authentication.\n\n    Args:\n        args (List[str]): A list of command line arguments\n\n    Example:\n        python my_script.py hub login your_api_key\n    \"\"\"\n    from ultralytics import hub\n\n    if args[0] == 'login':\n        key = args[1] if len(args) > 1 else ''\n        # Log in to Ultralytics HUB using the provided API key\n        hub.login(key)\n    elif args[0] == 'logout':\n        # Log out from Ultralytics HUB\n        hub.logout()\n\n\ndef handle_yolo_settings(args: List[str]) -> None:\n    \"\"\"\n    Handle YOLO settings command-line interface (CLI) commands.\n\n    This function processes YOLO settings CLI commands such as reset.\n    It should be called when executing a script with arguments related to YOLO settings management.\n\n    Args:\n        args (List[str]): A list of command line arguments for YOLO settings management.\n\n    Example:\n        python my_script.py yolo settings reset\n    \"\"\"\n    path = USER_CONFIG_DIR / 'settings.yaml'  # get SETTINGS YAML file path\n    if any(args) and args[0] == 'reset':\n        path.unlink()  # delete the settings file\n        get_settings()  # create new settings\n        LOGGER.info('Settings reset successfully')  # inform the user that settings have been reset\n    yaml_print(path)  # print the current settings\n\n\ndef entrypoint(debug=''):\n    \"\"\"\n    This function is the ultralytics package entrypoint, it's responsible for parsing the command line arguments passed\n    to the package.\n\n    This function allows for:\n    - passing mandatory YOLO args as a list of strings\n    - specifying the task to be performed, either 'detect', 'segment' or 'classify'\n    - specifying the mode, either 'train', 'val', 'test', or 'predict'\n    - running special modes like 'checks'\n    - passing overrides to the package's configuration\n\n    It uses the package's default cfg and initializes it using the passed overrides.\n    Then it calls the CLI function with the composed cfg\n    \"\"\"\n    args = (debug.split(' ') if debug else sys.argv)[1:]\n    if not args:  # no arguments passed\n        LOGGER.info(CLI_HELP_MSG)\n        return\n\n    special = {\n        'help': lambda: LOGGER.info(CLI_HELP_MSG),\n        'checks': checks.check_yolo,\n        'version': lambda: LOGGER.info(__version__),\n        'settings': lambda: handle_yolo_settings(args[1:]),\n        'cfg': lambda: yaml_print(DEFAULT_CFG_PATH),\n        'hub': lambda: handle_yolo_hub(args[1:]),\n        'login': lambda: handle_yolo_hub(args),\n        'copy-cfg': copy_default_cfg}\n    full_args_dict = {**DEFAULT_CFG_DICT, **{k: None for k in TASKS}, **{k: None for k in MODES}, **special}\n\n    # Define common mis-uses of special commands, i.e. -h, -help, --help\n    special.update({k[0]: v for k, v in special.items()})  # singular\n    special.update({k[:-1]: v for k, v in special.items() if len(k) > 1 and k.endswith('s')})  # singular\n    special = {**special, **{f'-{k}': v for k, v in special.items()}, **{f'--{k}': v for k, v in special.items()}}\n\n    overrides = {}  # basic overrides, i.e. imgsz=320\n    for a in merge_equals_args(args):  # merge spaces around '=' sign\n        if a.startswith('--'):\n            LOGGER.warning(f\"WARNING ⚠️ '{a}' does not require leading dashes '--', updating to '{a[2:]}'.\")\n            a = a[2:]\n        if a.endswith(','):\n            LOGGER.warning(f\"WARNING ⚠️ '{a}' does not require trailing comma ',', updating to '{a[:-1]}'.\")\n            a = a[:-1]\n        if '=' in a:\n            try:\n                re.sub(r' *= *', '=', a)  # remove spaces around equals sign\n                k, v = a.split('=', 1)  # split on first '=' sign\n                assert v, f\"missing '{k}' value\"\n                if k == 'cfg':  # custom.yaml passed\n                    LOGGER.info(f'Overriding {DEFAULT_CFG_PATH} with {v}')\n                    overrides = {k: val for k, val in yaml_load(checks.check_yaml(v)).items() if k != 'cfg'}\n                else:\n                    if v.lower() == 'none':\n                        v = None\n                    elif v.lower() == 'true':\n                        v = True\n                    elif v.lower() == 'false':\n                        v = False\n                    else:\n                        with contextlib.suppress(Exception):\n                            v = eval(v)\n                    overrides[k] = v\n            except (NameError, SyntaxError, ValueError, AssertionError) as e:\n                check_cfg_mismatch(full_args_dict, {a: ''}, e)\n\n        elif a in TASKS:\n            overrides['task'] = a\n        elif a in MODES:\n            overrides['mode'] = a\n        elif a.lower() in special:\n            special[a.lower()]()\n            return\n        elif a in DEFAULT_CFG_DICT and isinstance(DEFAULT_CFG_DICT[a], bool):\n            overrides[a] = True  # auto-True for default bool args, i.e. 'yolo show' sets show=True\n        elif a in DEFAULT_CFG_DICT:\n            raise SyntaxError(f\"'{colorstr('red', 'bold', a)}' is a valid YOLO argument but is missing an '=' sign \"\n                              f\"to set its value, i.e. try '{a}={DEFAULT_CFG_DICT[a]}'\\n{CLI_HELP_MSG}\")\n        else:\n            check_cfg_mismatch(full_args_dict, {a: ''})\n\n    # Check keys\n    check_cfg_mismatch(full_args_dict, overrides)\n\n    # Mode\n    mode = overrides.get('mode', None)\n    if mode is None:\n        mode = DEFAULT_CFG.mode or 'predict'\n        LOGGER.warning(f\"WARNING ⚠️ 'mode' is missing. Valid modes are {MODES}. Using default 'mode={mode}'.\")\n    elif mode not in MODES:\n        if mode not in ('checks', checks):\n            raise ValueError(f\"Invalid 'mode={mode}'. Valid modes are {MODES}.\\n{CLI_HELP_MSG}\")\n        LOGGER.warning(\"WARNING ⚠️ 'yolo mode=checks' is deprecated. Use 'yolo checks' instead.\")\n        checks.check_yolo()\n        return\n\n    # Task\n    task = overrides.pop('task', None)\n    if task:\n        if task not in TASKS:\n            raise ValueError(f\"Invalid 'task={task}'. Valid tasks are {TASKS}.\\n{CLI_HELP_MSG}\")\n        if 'model' not in overrides:\n            overrides['model'] = TASK2MODEL[task]\n\n    # Model\n    model = overrides.pop('model', DEFAULT_CFG.model)\n    if model is None:\n        model = 'yolov8n.pt'\n        LOGGER.warning(f\"WARNING ⚠️ 'model' is missing. Using default 'model={model}'.\")\n    from ultralytics.yolo.engine.model import YOLO\n    overrides['model'] = model\n    model = YOLO(model, task=task)\n    if isinstance(overrides.get('pretrained'), str):\n        model.load(overrides['pretrained'])\n\n    # Task Update\n    if task != model.task:\n        if task:\n            LOGGER.warning(f\"WARNING ⚠️ conflicting 'task={task}' passed with 'task={model.task}' model. \"\n                           f\"Ignoring 'task={task}' and updating to 'task={model.task}' to match model.\")\n        task = model.task\n\n    # Mode\n    if mode in ('predict', 'track') and 'source' not in overrides:\n        overrides['source'] = DEFAULT_CFG.source or ROOT / 'assets' if (ROOT / 'assets').exists() \\\n            else 'https://ultralytics.com/images/bus.jpg'\n        LOGGER.warning(f\"WARNING ⚠️ 'source' is missing. Using default 'source={overrides['source']}'.\")\n    elif mode in ('train', 'val'):\n        if 'data' not in overrides:\n            overrides['data'] = TASK2DATA.get(task or DEFAULT_CFG.task, DEFAULT_CFG.data)\n            LOGGER.warning(f\"WARNING ⚠️ 'data' is missing. Using default 'data={overrides['data']}'.\")\n    elif mode == 'export':\n        if 'format' not in overrides:\n            overrides['format'] = DEFAULT_CFG.format or 'torchscript'\n            LOGGER.warning(f\"WARNING ⚠️ 'format' is missing. Using default 'format={overrides['format']}'.\")\n\n    # Run command in python\n    # getattr(model, mode)(**vars(get_cfg(overrides=overrides)))  # default args using default.yaml\n    getattr(model, mode)(**overrides)  # default args from model\n\n\n# Special modes --------------------------------------------------------------------------------------------------------\ndef copy_default_cfg():\n    \"\"\"Copy and create a new default configuration file with '_copy' appended to its name.\"\"\"\n    new_file = Path.cwd() / DEFAULT_CFG_PATH.name.replace('.yaml', '_copy.yaml')\n    shutil.copy2(DEFAULT_CFG_PATH, new_file)\n    LOGGER.info(f'{DEFAULT_CFG_PATH} copied to {new_file}\\n'\n                f\"Example YOLO command with this new custom cfg:\\n    yolo cfg='{new_file}' imgsz=320 batch=8\")\n\n\nif __name__ == '__main__':\n    # Example Usage: entrypoint(debug='yolo predict model=yolov8n.pt')\n    entrypoint(debug='')\n"
  },
  {
    "path": "ultralytics/yolo/cfg/default.yaml",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Default training settings and hyperparameters for medium-augmentation COCO training\n\ntask: detect  # YOLO task, i.e. detect, segment, classify, pose\nmode: train  # YOLO mode, i.e. train, val, predict, export, track, benchmark\n\n# Train settings -------------------------------------------------------------------------------------------------------\nmodel:  # path to model file, i.e. yolov8n.pt, yolov8n.yaml\ndata:  # path to data file, i.e. coco128.yaml\nepochs: 100  # number of epochs to train for\npatience: 50  # epochs to wait for no observable improvement for early stopping of training\nbatch: 16  # number of images per batch (-1 for AutoBatch)\nimgsz: 640  # size of input images as integer or w,h\nsave: True  # save train checkpoints and predict results\nsave_period: -1 # Save checkpoint every x epochs (disabled if < 1)\ncache: False  # True/ram, disk or False. Use cache for data loading\ndevice:  # device to run on, i.e. cuda device=0 or device=0,1,2,3 or device=cpu\nworkers: 8  # number of worker threads for data loading (per RANK if DDP)\nproject:  # project name\nname:  # experiment name, results saved to 'project/name' directory\nexist_ok: False  # whether to overwrite existing experiment\npretrained: False  # whether to use a pretrained model\noptimizer: SGD  # optimizer to use, choices=['SGD', 'Adam', 'AdamW', 'RMSProp']\nverbose: True  # whether to print verbose output\nseed: 0  # random seed for reproducibility\ndeterministic: True  # whether to enable deterministic mode\nsingle_cls: False  # train multi-class data as single-class\ncombine_class: None\nrect: False  # rectangular training if mode='train' or rectangular validation if mode='val'\ncos_lr: False  # use cosine learning rate scheduler\nclose_mosaic: 0  # (int) disable mosaic augmentation for final epochs\nresume: False  # resume training from last checkpoint\namp: True  # Automatic Mixed Precision (AMP) training, choices=[True, False], True runs AMP check\n# Segmentation\noverlap_mask: True  # masks should overlap during training (segment train only)\nmask_ratio: 1  # mask downsample ratio (segment train only)\n# Classification\ndropout: 0.0  # use dropout regularization (classify train only)\n\n# Val/Test settings ----------------------------------------------------------------------------------------------------\nval: True  # validate/test during training\nsplit: val  # dataset split to use for validation, i.e. 'val', 'test' or 'train'\nsave_json: False  # save results to JSON file\nsave_hybrid: False  # save hybrid version of labels (labels + additional predictions)\nconf:  # object confidence threshold for detection (default 0.25 predict, 0.001 val)\niou: 0.7  # intersection over union (IoU) threshold for NMS\nmax_det: 300  # maximum number of detections per image\nhalf: False  # use half precision (FP16)\ndnn: False  # use OpenCV DNN for ONNX inference\nplots: True  # save plots during train/val\nspeed: False # calculate the fps follow the hybridnet https://github.com/datvuthanh/HybridNets/blob/main/hybridnets_test.py#L211\n\n# Prediction settings --------------------------------------------------------------------------------------------------\nsource:  # source directory for images or videos\nshow: False  # show results if possible\nsave_txt: False  # save results as .txt file\nsave_conf: False  # save results with confidence scores\nsave_crop: False  # save cropped images with results\nshow_labels: True  # show object labels in plots\nshow_conf: True  # show object confidence scores in plots\nvid_stride: 1  # video frame-rate stride\nline_width:   # line width of the bounding boxes\nvisualize: False  # visualize model features\naugment: False  # apply image augmentation to prediction sources\nagnostic_nms: False  # class-agnostic NMS\nclasses:  # filter results by class, i.e. class=0, or class=[0,2,3]\nretina_masks: False  # use high-resolution segmentation masks\nboxes: True  # Show boxes in segmentation predictions\n\n# Export settings ------------------------------------------------------------------------------------------------------\nformat: torchscript  # format to export to\nkeras: False  # use Keras\noptimize: False  # TorchScript: optimize for mobile\nint8: False  # CoreML/TF INT8 quantization\ndynamic: False  # ONNX/TF/TensorRT: dynamic axes\nsimplify: False  # ONNX: simplify model\nopset:  # ONNX: opset version (optional)\nworkspace: 4  # TensorRT: workspace size (GB)\nnms: False  # CoreML: add NMS\n\n# Hyperparameters ------------------------------------------------------------------------------------------------------\nlr0: 0.01  # initial learning rate (i.e. SGD=1E-2, Adam=1E-3)\nlrf: 0.01  # final learning rate (lr0 * lrf)\nmomentum: 0.937  # SGD momentum/Adam beta1\nweight_decay: 0.0005  # optimizer weight decay 5e-4\nwarmup_epochs: 3.0  # warmup epochs (fractions ok)\nwarmup_momentum: 0.8  # warmup initial momentum\nwarmup_bias_lr: 0.1  # warmup initial bias lr\nbox: 7.5  # box loss gain\ncls: 0.5  # cls loss gain (scale with pixels)\ndfl: 1.5  # dfl loss gain\nTL: 8.0 # TL loss gain\nFL: 24.0 # FL loss for segment gain\npose: 12.0  # pose loss gain\nkobj: 1.0  # keypoint obj loss gain\nlabel_smoothing: 0.0  # label smoothing (fraction)\nnbs: 64  # nominal batch size\nhsv_h: 0.015  # image HSV-Hue augmentation (fraction)\nhsv_s: 0.7  # image HSV-Saturation augmentation (fraction)\nhsv_v: 0.4  # image HSV-Value augmentation (fraction)\ndegrees: 0.0  # image rotation (+/- deg)\ntranslate: 0.1  # image translation (+/- fraction)\nscale: 0.5  # image scale (+/- gain)\nshear: 0.0  # image shear (+/- deg)\nperspective: 0.0  # image perspective (+/- fraction), range 0-0.001\nflipud: 0.0  # image flip up-down (probability)\nfliplr: 0.5  # image flip left-right (probability)\nmosaic: 1.0  # image mosaic (probability)\nmixup: 0.0  # image mixup (probability)\ncopy_paste: 0.0  # segment copy-paste (probability)\nbinary_mask_threshold: 0.5  # segment task binary mask threshold\n\n# Custom config.yaml ---------------------------------------------------------------------------------------------------\ncfg:  # for overriding defaults.yaml\n\n# Debug, do not modify -------------------------------------------------------------------------------------------------\nv5loader: False  # use legacy YOLOv5 dataloader\n\n# Tracker settings ------------------------------------------------------------------------------------------------------\ntracker: botsort.yaml  # tracker type, ['botsort.yaml', 'bytetrack.yaml']\n"
  },
  {
    "path": "ultralytics/yolo/data/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\n\nfrom .base import BaseDataset\nfrom .build import build_dataloader, build_yolo_dataset, load_inference_source\nfrom .dataset import ClassificationDataset, SemanticDataset, YOLODataset\nfrom .dataset_wrappers import MixAndRectDataset\n\n__all__ = ('BaseDataset', 'ClassificationDataset', 'MixAndRectDataset', 'SemanticDataset', 'YOLODataset',\n           'build_yolo_dataset', 'build_dataloader', 'load_inference_source')\n"
  },
  {
    "path": "ultralytics/yolo/data/annotator.py",
    "content": "from pathlib import Path\n\nfrom ultralytics import YOLO\nfrom ultralytics.vit.sam import PromptPredictor, build_sam\nfrom ultralytics.yolo.utils.torch_utils import select_device\n\n\ndef auto_annotate(data, det_model='yolov8x.pt', sam_model='sam_b.pt', device='', output_dir=None):\n    \"\"\"\n    Automatically annotates images using a YOLO object detection model and a SAM segmentation model.\n    Args:\n        data (str): Path to a folder containing images to be annotated.\n        det_model (str, optional): Pre-trained YOLO detection model. Defaults to 'yolov8x.pt'.\n        sam_model (str, optional): Pre-trained SAM segmentation model. Defaults to 'sam_b.pt'.\n        device (str, optional): Device to run the models on. Defaults to an empty string (CPU or GPU, if available).\n        output_dir (str, None, optional): Directory to save the annotated results.\n            Defaults to a 'labels' folder in the same directory as 'data'.\n    \"\"\"\n    device = select_device(device)\n    det_model = YOLO(det_model)\n    sam_model = build_sam(sam_model)\n    det_model.to(device)\n    sam_model.to(device)\n\n    if not output_dir:\n        output_dir = Path(str(data)).parent / 'labels'\n    Path(output_dir).mkdir(exist_ok=True, parents=True)\n\n    prompt_predictor = PromptPredictor(sam_model)\n    det_results = det_model(data, stream=True)\n\n    for result in det_results:\n        boxes = result.boxes.xyxy  # Boxes object for bbox outputs\n        class_ids = result.boxes.cls.int().tolist()  # noqa\n        if len(class_ids):\n            prompt_predictor.set_image(result.orig_img)\n            masks, _, _ = prompt_predictor.predict_torch(\n                point_coords=None,\n                point_labels=None,\n                boxes=prompt_predictor.transform.apply_boxes_torch(boxes, result.orig_shape[:2]),\n                multimask_output=False,\n            )\n\n            result.update(masks=masks.squeeze(1))\n            segments = result.masks.xyn  # noqa\n\n            with open(str(Path(output_dir) / Path(result.path).stem) + '.txt', 'w') as f:\n                for i in range(len(segments)):\n                    s = segments[i]\n                    if len(s) == 0:\n                        continue\n                    segment = map(str, segments[i].reshape(-1).tolist())\n                    f.write(f'{class_ids[i]} ' + ' '.join(segment) + '\\n')\n"
  },
  {
    "path": "ultralytics/yolo/data/augment.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport math\nimport random\nfrom copy import deepcopy\n\nimport cv2\nimport numpy as np\nimport torch\nimport torchvision.transforms as T\n\nfrom ..utils import LOGGER, colorstr\nfrom ..utils.checks import check_version\nfrom ..utils.instance import Instances\nfrom ..utils.metrics import bbox_ioa\nfrom ..utils.ops import segment2box\nfrom .utils import polygons2masks, polygons2masks_overlap\n\nPOSE_FLIPLR_INDEX = [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15]\n\n\n# TODO: we might need a BaseTransform to make all these augments be compatible with both classification and semantic\nclass BaseTransform:\n\n    def __init__(self) -> None:\n        pass\n\n    def apply_image(self, labels):\n        \"\"\"Applies image transformation to labels.\"\"\"\n        pass\n\n    def apply_instances(self, labels):\n        \"\"\"Applies transformations to input 'labels' and returns object instances.\"\"\"\n        pass\n\n    def apply_semantic(self, labels):\n        \"\"\"Applies semantic segmentation to an image.\"\"\"\n        pass\n\n    def __call__(self, labels):\n        \"\"\"Applies label transformations to an image, instances and semantic masks.\"\"\"\n        self.apply_image(labels)\n        self.apply_instances(labels)\n        self.apply_semantic(labels)\n\n\nclass Compose:\n\n    def __init__(self, transforms):\n        \"\"\"Initializes the Compose object with a list of transforms.\"\"\"\n        self.transforms = transforms\n\n    def __call__(self, data):\n        \"\"\"Applies a series of transformations to input data.\"\"\"\n        for t in self.transforms:\n            data = t(data)\n        return data\n\n    def append(self, transform):\n        \"\"\"Appends a new transform to the existing list of transforms.\"\"\"\n        self.transforms.append(transform)\n\n    def tolist(self):\n        \"\"\"Converts list of transforms to a standard Python list.\"\"\"\n        return self.transforms\n\n    def __repr__(self):\n        \"\"\"Return string representation of object.\"\"\"\n        format_string = f'{self.__class__.__name__}('\n        for t in self.transforms:\n            format_string += '\\n'\n            format_string += f'    {t}'\n        format_string += '\\n)'\n        return format_string\n\n\nclass BaseMixTransform:\n    \"\"\"This implementation is from mmyolo.\"\"\"\n\n    def __init__(self, dataset, pre_transform=None, p=0.0) -> None:\n        self.dataset = dataset\n        self.pre_transform = pre_transform\n        self.p = p\n\n    def __call__(self, labels):\n        \"\"\"Applies pre-processing transforms and mixup/mosaic transforms to labels data.\"\"\"\n        if random.uniform(0, 1) > self.p:\n            return labels\n\n        # Get index of one or three other images\n        indexes = self.get_indexes()\n        if isinstance(indexes, int):\n            indexes = [indexes]\n\n        # Get images information will be used for Mosaic or MixUp\n        mix_labels = [self.dataset.get_label_info(i) for i in indexes]\n\n        ########Jiayuan\n        if hasattr(self.dataset, 'global_count'):\n            tem_list = [file[self.dataset.global_count] for file in mix_labels]\n            mix_labels = tem_list\n        ########\n\n        elif self.dataset.together:\n            mix_labels_list = list(zip(*mix_labels))\n            # mix_labels_list = []\n            # for count in range(len(indexes)):\n            #     tem_list = [file[count] for file in mix_labels]\n            #     mix_labels_list.append(tem_list)\n\n        if self.pre_transform is not None:\n            for mix_labels in mix_labels_list:\n                for i, data in enumerate(mix_labels):\n                    mix_labels[i] = self.pre_transform(data)\n        for i, mix_labels in enumerate(mix_labels_list):\n            labels[i]['mix_labels'] = mix_labels\n\n        # Mosaic or MixUp\n        labels = self._mix_transform(labels)\n        for label in labels:\n            label.pop('mix_labels', None)\n        return labels\n\n\n\n\n\n\n\n\n\n\n\n\n\n        # ########Jiayuan\n        # if hasattr(self.dataset, 'global_count'):\n        #     tem_list = [file[self.dataset.global_count] for file in mix_labels]\n        #     mix_labels = tem_list\n        # ########\n        #\n        # if self.pre_transform is not None:\n        #     for i, data in enumerate(mix_labels):\n        #         mix_labels[i] = self.pre_transform(data)\n        # labels['mix_labels'] = mix_labels\n        #\n        # # Mosaic or MixUp\n        # labels = self._mix_transform(labels)\n        # labels.pop('mix_labels', None)\n        # return labels\n\n    def _mix_transform(self, labels):\n        \"\"\"Applies MixUp or Mosaic augmentation to the label dictionary.\"\"\"\n        raise NotImplementedError\n\n    def get_indexes(self):\n        \"\"\"Gets a list of shuffled indexes for mosaic augmentation.\"\"\"\n        raise NotImplementedError\n\n\nclass Mosaic(BaseMixTransform):\n    \"\"\"\n    Mosaic augmentation.\n\n    This class performs mosaic augmentation by combining multiple (4 or 9) images into a single mosaic image.\n    The augmentation is applied to a dataset with a given probability.\n\n    Attributes:\n        dataset: The dataset on which the mosaic augmentation is applied.\n        imgsz (int, optional): Image size (height and width) after mosaic pipeline of a single image. Default to 640.\n        p (float, optional): Probability of applying the mosaic augmentation. Must be in the range 0-1. Default to 1.0.\n        n (int, optional): The grid size, either 4 (for 2x2) or 9 (for 3x3).\n    \"\"\"\n\n    def __init__(self, dataset, imgsz=640, p=1.0, n=4):\n        \"\"\"Initializes the object with a dataset, image size, probability, and border.\"\"\"\n        assert 0 <= p <= 1.0, f'The probability should be in range [0, 1], but got {p}.'\n        assert n in (4, 9), 'grid must be equal to 4 or 9.'\n        super().__init__(dataset=dataset, p=p)\n        self.dataset = dataset\n        self.imgsz = imgsz\n        self.border = [-imgsz // 2, -imgsz // 2] if n == 4 else [-imgsz, -imgsz]\n        self.n = n\n\n    def get_indexes(self):\n        \"\"\"Return a list of random indexes from the dataset.\"\"\"\n        return [random.randint(0, len(self.dataset) - 1) for _ in range(self.n - 1)]\n\n    def _mix_transform(self, labels_list):\n        \"\"\"Apply mixup transformation to the input image and labels.\"\"\"\n        for labels in labels_list:\n            assert labels.get('rect_shape', None) is None, 'rect and mosaic are mutually exclusive.'\n            assert len(labels.get('mix_labels', [])), 'There are no other images for mosaic augment.'\n        return self._mosaic4(labels_list) if self.n == 4 else self._mosaic9(labels_list)  ###### Jiayuan: only support mosaic4.\n\n    def _mosaic4(self, labels_list):\n        \"\"\"Create a 2x2 image mosaic.\"\"\"\n        new_labels_list = []\n        s = self.imgsz\n        yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.border)  # mosaic center x, y\n\n        for labels in labels_list:\n            mosaic_labels = []\n            for i in range(4):\n                labels_patch = labels if i == 0 else labels['mix_labels'][i - 1]\n                # Load image\n                img = labels_patch['img']\n                h, w = labels_patch.pop('resized_shape')\n\n                # Place img in img4\n                if i == 0:  # top left\n                    img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8)  # base image with 4 tiles\n                    x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc  # xmin, ymin, xmax, ymax (large image)\n                    x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h  # xmin, ymin, xmax, ymax (small image)\n                elif i == 1:  # top right\n                    x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc\n                    x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h\n                elif i == 2:  # bottom left\n                    x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)\n                    x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)\n                elif i == 3:  # bottom right\n                    x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)\n                    x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)\n\n                img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b]  # img4[ymin:ymax, xmin:xmax]\n                padw = x1a - x1b\n                padh = y1a - y1b\n\n                labels_patch = self._update_labels(labels_patch, padw, padh)\n                mosaic_labels.append(labels_patch)\n            final_labels = self._cat_labels(mosaic_labels)\n            final_labels['img'] = img4\n            new_labels_list.append(final_labels)\n        return new_labels_list\n\n    def _mosaic9(self, labels):\n        \"\"\"Create a 3x3 image mosaic.\"\"\"\n        mosaic_labels = []\n        s = self.imgsz\n        hp, wp = -1, -1  # height, width previous\n        for i in range(9):\n            labels_patch = labels if i == 0 else labels['mix_labels'][i - 1]\n            # Load image\n            img = labels_patch['img']\n            h, w = labels_patch.pop('resized_shape')\n\n            # Place img in img9\n            if i == 0:  # center\n                img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8)  # base image with 4 tiles\n                h0, w0 = h, w\n                c = s, s, s + w, s + h  # xmin, ymin, xmax, ymax (base) coordinates\n            elif i == 1:  # top\n                c = s, s - h, s + w, s\n            elif i == 2:  # top right\n                c = s + wp, s - h, s + wp + w, s\n            elif i == 3:  # right\n                c = s + w0, s, s + w0 + w, s + h\n            elif i == 4:  # bottom right\n                c = s + w0, s + hp, s + w0 + w, s + hp + h\n            elif i == 5:  # bottom\n                c = s + w0 - w, s + h0, s + w0, s + h0 + h\n            elif i == 6:  # bottom left\n                c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h\n            elif i == 7:  # left\n                c = s - w, s + h0 - h, s, s + h0\n            elif i == 8:  # top left\n                c = s - w, s + h0 - hp - h, s, s + h0 - hp\n\n            padw, padh = c[:2]\n            x1, y1, x2, y2 = (max(x, 0) for x in c)  # allocate coords\n\n            # Image\n            img9[y1:y2, x1:x2] = img[y1 - padh:, x1 - padw:]  # img9[ymin:ymax, xmin:xmax]\n            hp, wp = h, w  # height, width previous for next iteration\n\n            labels_patch = self._update_labels(labels_patch, padw, padh)\n            mosaic_labels.append(labels_patch)\n        final_labels = self._cat_labels(mosaic_labels)\n        final_labels['img'] = img9\n        return final_labels\n\n    @staticmethod\n    def _update_labels(labels, padw, padh):\n        \"\"\"Update labels.\"\"\"\n        nh, nw = labels['img'].shape[:2]\n        labels['instances'].convert_bbox(format='xyxy')\n        labels['instances'].denormalize(nw, nh)\n        labels['instances'].add_padding(padw, padh)\n        return labels\n\n    def _cat_labels(self, mosaic_labels):\n        \"\"\"Return labels with mosaic border instances clipped.\"\"\"\n        if len(mosaic_labels) == 0:\n            return {}\n        cls = []\n        instances = []\n        for labels in mosaic_labels:\n            cls.append(labels['cls'])\n            instances.append(labels['instances'])\n        final_labels = {\n            'im_file': mosaic_labels[0]['im_file'],\n            'ori_shape': mosaic_labels[0]['ori_shape'],\n            'resized_shape': (self.imgsz * 2, self.imgsz * 2),\n            'cls': np.concatenate(cls, 0),\n            'instances': Instances.concatenate(instances, axis=0),\n            'mosaic_border': self.border}  # final_labels\n        clip_size = self.imgsz * (2 if self.n == 4 else 3)\n        final_labels['instances'].clip(clip_size, clip_size)\n        return final_labels\n\n\nclass MixUp(BaseMixTransform):\n\n    def __init__(self, dataset, pre_transform=None, p=0.0) -> None:\n        super().__init__(dataset=dataset, pre_transform=pre_transform, p=p)\n\n    def get_indexes(self):\n        \"\"\"Get a random index from the dataset.\"\"\"\n        return random.randint(0, len(self.dataset) - 1)\n\n    def _mix_transform(self, labels):\n        \"\"\"Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf.\"\"\"\n        r = np.random.beta(32.0, 32.0)  # mixup ratio, alpha=beta=32.0\n        labels2 = labels['mix_labels'][0]\n        labels['img'] = (labels['img'] * r + labels2['img'] * (1 - r)).astype(np.uint8)\n        labels['instances'] = Instances.concatenate([labels['instances'], labels2['instances']], axis=0)\n        labels['cls'] = np.concatenate([labels['cls'], labels2['cls']], 0)\n        return labels\n\n\nclass RandomPerspective:\n\n    def __init__(self,\n                 degrees=0.0,\n                 translate=0.1,\n                 scale=0.5,\n                 shear=0.0,\n                 perspective=0.0,\n                 border=(0, 0),\n                 pre_transform=None):\n        self.degrees = degrees\n        self.translate = translate\n        self.scale = scale\n        self.shear = shear\n        self.perspective = perspective\n        # Mosaic border\n        self.border = border\n        self.pre_transform = pre_transform\n\n    def affine_transform(self, img, border):\n        \"\"\"Center.\"\"\"\n        C = np.eye(3, dtype=np.float32)\n\n        C[0, 2] = -img.shape[1] / 2  # x translation (pixels)\n        C[1, 2] = -img.shape[0] / 2  # y translation (pixels)\n\n        # Perspective\n        P = np.eye(3, dtype=np.float32)\n        P[2, 0] = random.uniform(-self.perspective, self.perspective)  # x perspective (about y)\n        P[2, 1] = random.uniform(-self.perspective, self.perspective)  # y perspective (about x)\n\n        # Rotation and Scale\n        R = np.eye(3, dtype=np.float32)\n        a = random.uniform(-self.degrees, self.degrees)\n        # a += random.choice([-180, -90, 0, 90])  # add 90deg rotations to small rotations\n        s = random.uniform(1 - self.scale, 1 + self.scale)\n        # s = 2 ** random.uniform(-scale, scale)\n        R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)\n\n        # Shear\n        S = np.eye(3, dtype=np.float32)\n        S[0, 1] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180)  # x shear (deg)\n        S[1, 0] = math.tan(random.uniform(-self.shear, self.shear) * math.pi / 180)  # y shear (deg)\n\n        # Translation\n        T = np.eye(3, dtype=np.float32)\n        T[0, 2] = random.uniform(0.5 - self.translate, 0.5 + self.translate) * self.size[0]  # x translation (pixels)\n        T[1, 2] = random.uniform(0.5 - self.translate, 0.5 + self.translate) * self.size[1]  # y translation (pixels)\n\n        # Combined rotation matrix\n        M = T @ S @ R @ P @ C  # order of operations (right to left) is IMPORTANT\n        # Affine image\n        if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any():  # image changed\n            if self.perspective:\n                img = cv2.warpPerspective(img, M, dsize=self.size, borderValue=(114, 114, 114))\n            else:  # affine\n                img = cv2.warpAffine(img, M[:2], dsize=self.size, borderValue=(114, 114, 114))\n        return img, M, s\n\n    def apply_bboxes(self, bboxes, M):\n        \"\"\"\n        Apply affine to bboxes only.\n\n        Args:\n            bboxes (ndarray): list of bboxes, xyxy format, with shape (num_bboxes, 4).\n            M (ndarray): affine matrix.\n\n        Returns:\n            new_bboxes (ndarray): bboxes after affine, [num_bboxes, 4].\n        \"\"\"\n        n = len(bboxes)\n        if n == 0:\n            return bboxes\n\n        xy = np.ones((n * 4, 3), dtype=bboxes.dtype)\n        xy[:, :2] = bboxes[:, [0, 1, 2, 3, 0, 3, 2, 1]].reshape(n * 4, 2)  # x1y1, x2y2, x1y2, x2y1\n        xy = xy @ M.T  # transform\n        xy = (xy[:, :2] / xy[:, 2:3] if self.perspective else xy[:, :2]).reshape(n, 8)  # perspective rescale or affine\n\n        # Create new boxes\n        x = xy[:, [0, 2, 4, 6]]\n        y = xy[:, [1, 3, 5, 7]]\n        return np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1)), dtype=bboxes.dtype).reshape(4, n).T\n\n    def apply_segments(self, segments, M):\n        \"\"\"\n        Apply affine to segments and generate new bboxes from segments.\n\n        Args:\n            segments (ndarray): list of segments, [num_samples, 500, 2].\n            M (ndarray): affine matrix.\n\n        Returns:\n            new_segments (ndarray): list of segments after affine, [num_samples, 500, 2].\n            new_bboxes (ndarray): bboxes after affine, [N, 4].\n        \"\"\"\n        n, num = segments.shape[:2]\n        if n == 0:\n            return [], segments\n\n        xy = np.ones((n * num, 3), dtype=segments.dtype)\n        segments = segments.reshape(-1, 2)\n        xy[:, :2] = segments\n        xy = xy @ M.T  # transform\n        xy = xy[:, :2] / xy[:, 2:3]\n        segments = xy.reshape(n, -1, 2)\n        bboxes = np.stack([segment2box(xy, self.size[0], self.size[1]) for xy in segments], 0)\n        return bboxes, segments\n\n    def apply_keypoints(self, keypoints, M):\n        \"\"\"\n        Apply affine to keypoints.\n\n        Args:\n            keypoints (ndarray): keypoints, [N, 17, 3].\n            M (ndarray): affine matrix.\n\n        Return:\n            new_keypoints (ndarray): keypoints after affine, [N, 17, 3].\n        \"\"\"\n        n, nkpt = keypoints.shape[:2]\n        if n == 0:\n            return keypoints\n        xy = np.ones((n * nkpt, 3), dtype=keypoints.dtype)\n        visible = keypoints[..., 2].reshape(n * nkpt, 1)\n        xy[:, :2] = keypoints[..., :2].reshape(n * nkpt, 2)\n        xy = xy @ M.T  # transform\n        xy = xy[:, :2] / xy[:, 2:3]  # perspective rescale or affine\n        out_mask = (xy[:, 0] < 0) | (xy[:, 1] < 0) | (xy[:, 0] > self.size[0]) | (xy[:, 1] > self.size[1])\n        visible[out_mask] = 0\n        return np.concatenate([xy, visible], axis=-1).reshape(n, nkpt, 3)\n\n    def __call__(self, labels_list):\n        \"\"\"\n        Affine images and targets.\n\n        Args:\n            labels (dict): a dict of `bboxes`, `segments`, `keypoints`.\n        \"\"\"\n        for count, labels in enumerate(labels_list):\n            if self.pre_transform and 'mosaic_border' not in labels:\n                labels = self.pre_transform(labels)\n                labels.pop('ratio_pad')  # do not need ratio pad\n\n            img = labels['img']\n            cls = labels['cls']\n            instances = labels.pop('instances')\n            # Make sure the coord formats are right\n            instances.convert_bbox(format='xyxy')\n            instances.denormalize(*img.shape[:2][::-1])\n\n            border = labels.pop('mosaic_border', self.border)\n            self.size = img.shape[1] + border[1] * 2, img.shape[0] + border[0] * 2  # w, h\n            # M is affine matrix\n            # scale for func:`box_candidates`\n            if count == 0:\n                img_affine, M_affine, scale_affine = self.affine_transform(img, border)\n\n            bboxes = self.apply_bboxes(instances.bboxes, M_affine)\n\n            segments = instances.segments\n            keypoints = instances.keypoints\n            # Update bboxes if there are segments.\n            if len(segments):\n                bboxes, segments = self.apply_segments(segments, M_affine)\n\n            if keypoints is not None:\n                keypoints = self.apply_keypoints(keypoints, M_affine)\n            new_instances = Instances(bboxes, segments, keypoints, bbox_format='xyxy', normalized=False)\n            # Clip\n            new_instances.clip(*self.size)\n\n            # Filter instances\n            instances.scale(scale_w=scale_affine, scale_h=scale_affine, bbox_only=True)\n            # Make the bboxes have the same scale with new_bboxes\n            # print(labels[\"im_file\"])\n            i = self.box_candidates(box1=instances.bboxes.T,\n                                    box2=new_instances.bboxes.T,\n                                    area_thr=0.01 if len(segments) else 0.10)\n            labels['instances'] = new_instances[i]\n            labels['cls'] = cls[i]\n            labels['img'] = img_affine.copy()\n            labels['resized_shape'] = img_affine.shape[:2]\n        return labels_list\n\n    def box_candidates(self, box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16):  # box1(4,n), box2(4,n)\n        # Compute box candidates: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio\n        w1, h1 = box1[2] - box1[0], box1[3] - box1[1]\n        w2, h2 = box2[2] - box2[0], box2[3] - box2[1]\n        ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps))  # aspect ratio\n        # try:\n        #     (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr)\n        # except:\n        #     print('=====================')\n        #     print(w1)\n        #     print(h1)\n        #     print('---------------------')\n        #     print(w2)\n        #     print(h2)\n        #     print('*********************')\n        return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr)  # candidates\n\n\nclass RandomHSV:\n\n    def __init__(self, hgain=0.5, sgain=0.5, vgain=0.5) -> None:\n        self.hgain = hgain\n        self.sgain = sgain\n        self.vgain = vgain\n\n    def __call__(self, labels_list):\n        \"\"\"Applies random horizontal or vertical flip to an image with a given probability.\"\"\"\n        labels = labels_list[0]\n        img = labels['img']\n        if self.hgain or self.sgain or self.vgain:\n            r = np.random.uniform(-1, 1, 3) * [self.hgain, self.sgain, self.vgain] + 1  # random gains\n            hue, sat, val = cv2.split(cv2.cvtColor(img, cv2.COLOR_BGR2HSV))\n            dtype = img.dtype  # uint8\n\n            x = np.arange(0, 256, dtype=r.dtype)\n            lut_hue = ((x * r[0]) % 180).astype(dtype)\n            lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)\n            lut_val = np.clip(x * r[2], 0, 255).astype(dtype)\n\n            im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))\n            cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=img)  # no return needed\n        for label in labels_list:\n            label['img'] = labels['img'].copy()\n        return labels_list\n\n\nclass RandomFlip:\n\n    def __init__(self, p=0.5, direction='horizontal', flip_idx=None) -> None:\n        assert direction in ['horizontal', 'vertical'], f'Support direction `horizontal` or `vertical`, got {direction}'\n        assert 0 <= p <= 1.0\n\n        self.p = p\n        self.direction = direction\n        self.flip_idx = flip_idx\n\n    def __call__(self, labels_list):\n        \"\"\"Resize image and padding for detection, instance segmentation, pose.\"\"\"\n        horizontal = None\n        vertical = None\n        if self.direction == 'horizontal' and random.random() < self.p:\n            horizontal = True\n        if self.direction == 'vertical' and random.random() < self.p:\n            vertical = True\n        for labels in labels_list:\n            img = labels['img']\n            instances = labels.pop('instances')\n            instances.convert_bbox(format='xywh')\n            h, w = img.shape[:2]\n            h = 1 if instances.normalized else h\n            w = 1 if instances.normalized else w\n\n            # Flip up-down\n            if vertical:\n                img = np.flipud(img)\n                instances.flipud(h)\n            if horizontal:\n                img = np.fliplr(img)\n                instances.fliplr(w)\n                # For keypoints\n                if self.flip_idx is not None and instances.keypoints is not None:\n                    instances.keypoints = np.ascontiguousarray(instances.keypoints[:, self.flip_idx, :])\n            labels['img'] = np.ascontiguousarray(img)\n            labels['instances'] = instances\n        return labels_list\n\n\nclass LetterBox:\n    \"\"\"Resize image and padding for detection, instance segmentation, pose.\"\"\"\n\n    def __init__(self, new_shape=(640, 640), auto=False, scaleFill=False, scaleup=True, stride=32):\n        \"\"\"Initialize LetterBox object with specific parameters.\"\"\"\n        self.new_shape = new_shape\n        self.auto = auto\n        self.scaleFill = scaleFill\n        self.scaleup = scaleup\n        self.stride = stride\n\n    def __call__(self, labels=None, image=None):\n        \"\"\"Return updated labels and image with added border.\"\"\"\n        if labels is None:\n            labels = {}\n        img = labels.get('img') if image is None else image\n        shape = img.shape[:2]  # current shape [height, width]\n        new_shape = labels.pop('rect_shape', self.new_shape)\n        if isinstance(new_shape, int):\n            new_shape = (new_shape, new_shape)\n\n        # Scale ratio (new / old)\n        r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])\n        if not self.scaleup:  # only scale down, do not scale up (for better val mAP)\n            r = min(r, 1.0)\n\n        # Compute padding\n        ratio = r, r  # width, height ratios\n        new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))\n        dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding\n        if self.auto:  # minimum rectangle\n            dw, dh = np.mod(dw, self.stride), np.mod(dh, self.stride)  # wh padding\n        elif self.scaleFill:  # stretch\n            dw, dh = 0.0, 0.0\n            new_unpad = (new_shape[1], new_shape[0])\n            ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios\n\n        dw /= 2  # divide padding into 2 sides\n        dh /= 2\n        if labels.get('ratio_pad'):\n            labels['ratio_pad'] = (labels['ratio_pad'], (dw, dh))  # for evaluation\n\n        if shape[::-1] != new_unpad:  # resize\n            img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)\n        top, bottom = int(round(dh.item() - 0.1)), int(round(dh.item() + 0.1))\n        left, right = int(round(dw.item() - 0.1)), int(round(dw.item() + 0.1))\n        img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT,\n                                 value=(114, 114, 114))  # add border\n\n        if len(labels):\n            labels = self._update_labels(labels, ratio, dw, dh)\n            labels['img'] = img\n            labels['resized_shape'] = new_shape\n            return labels\n        else:\n            return img\n\n    def _update_labels(self, labels, ratio, padw, padh):\n        \"\"\"Update labels.\"\"\"\n        labels['instances'].convert_bbox(format='xyxy')\n        labels['instances'].denormalize(*labels['img'].shape[:2][::-1])\n        labels['instances'].scale(*ratio)\n        labels['instances'].add_padding(padw, padh)\n        return labels\n\n\nclass CopyPaste:\n\n    def __init__(self, p=0.5) -> None:\n        self.p = p\n\n    def __call__(self, labels_list):\n        \"\"\"Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy).\"\"\"\n        for labels in labels_list:\n            im = labels['img']\n            cls = labels['cls']\n            h, w = im.shape[:2]\n            instances = labels.pop('instances')\n            instances.convert_bbox(format='xyxy')\n            instances.denormalize(w, h)\n            if self.p and len(instances.segments):\n                n = len(instances)\n                _, w, _ = im.shape  # height, width, channels\n                im_new = np.zeros(im.shape, np.uint8)\n\n                # Calculate ioa first then select indexes randomly\n                ins_flip = deepcopy(instances)\n                ins_flip.fliplr(w)\n\n                ioa = bbox_ioa(ins_flip.bboxes, instances.bboxes)  # intersection over area, (N, M)\n                indexes = np.nonzero((ioa < 0.30).all(1))[0]  # (N, )\n                n = len(indexes)\n                for j in random.sample(list(indexes), k=round(self.p * n)):\n                    cls = np.concatenate((cls, cls[[j]]), axis=0)\n                    instances = Instances.concatenate((instances, ins_flip[[j]]), axis=0)\n                    cv2.drawContours(im_new, instances.segments[[j]].astype(np.int32), -1, (1, 1, 1), cv2.FILLED)\n\n                result = cv2.flip(im, 1)  # augment segments (flip left-right)\n                i = cv2.flip(im_new, 1).astype(bool)\n                im[i] = result[i]  # cv2.imwrite('debug.jpg', im)  # debug\n\n            labels['img'] = im\n            labels['cls'] = cls\n            labels['instances'] = instances\n        return labels_list\n\n\nclass Albumentations:\n    # YOLOv8 Albumentations class (optional, only used if package is installed)\n    def __init__(self, p=1.0):\n        \"\"\"Initialize the transform object for YOLO bbox formatted params.\"\"\"\n        self.p = p\n        self.transform = None\n        prefix = colorstr('albumentations: ')\n        try:\n            import albumentations as A\n\n            check_version(A.__version__, '1.0.3', hard=True)  # version requirement\n\n            T = [\n                A.Blur(p=0.01),\n                A.MedianBlur(p=0.01),\n                A.ToGray(p=0.01),\n                A.CLAHE(p=0.01),\n                A.RandomBrightnessContrast(p=0.0),\n                A.RandomGamma(p=0.0),\n                A.ImageCompression(quality_lower=75, p=0.0)]  # transforms\n            self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))\n\n            LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))\n        except ImportError:  # package not installed, skip\n            pass\n        except Exception as e:\n            LOGGER.info(f'{prefix}{e}')\n\n    def __call__(self, labels_list):\n        \"\"\"Generates object detections and returns a dictionary with detection results.\"\"\"\n        for labels in labels_list:\n            im = labels['img']\n            cls = labels['cls']\n            if len(cls):\n                labels['instances'].convert_bbox('xywh')\n                labels['instances'].normalize(*im.shape[:2][::-1])\n                bboxes = labels['instances'].bboxes\n                # TODO: add supports of segments and keypoints\n                if self.transform and random.random() < self.p:\n                    print('This is wrong beacsue I did not change Albumentations code for multi task ')\n                    new = self.transform(image=im, bboxes=bboxes, class_labels=cls)  # transformed\n                    if len(new['class_labels']) > 0:  # skip update if no bbox in new im\n                        labels['img'] = new['image']\n                        labels['cls'] = np.array(new['class_labels'])\n                        bboxes = np.array(new['bboxes'])\n                labels['instances'].update(bboxes=bboxes)\n        return labels_list\n\n\n# TODO: technically this is not an augmentation, maybe we should put this to another files\nclass Format:\n\n    def __init__(self,\n                 bbox_format='xywh',\n                 normalize=True,\n                 return_mask=False,\n                 return_keypoint=False,\n                 mask_ratio=4,\n                 mask_overlap=True,\n                 batch_idx=True,\n                 labels_name=None):\n        self.bbox_format = bbox_format\n        self.normalize = normalize\n        self.return_mask = return_mask  # set False when training detection only\n        self.return_keypoint = return_keypoint\n        self.mask_ratio = mask_ratio\n        self.mask_overlap = mask_overlap\n        self.batch_idx = batch_idx # keep the batch indexes\n        self.labels_name = labels_name\n\n    def __call__(self, labels_list):\n        \"\"\"Return formatted image, classes, bounding boxes & keypoints to be used by 'collate_fn'.\"\"\"\n        if isinstance(labels_list,list):\n            for count, labels in enumerate(labels_list):\n                img = labels.pop('img')\n                h, w = img.shape[:2]\n                cls = labels.pop('cls')\n                instances = labels.pop('instances')\n                instances.convert_bbox(format=self.bbox_format)\n                instances.denormalize(w, h)\n                nl = len(instances)\n\n                if 'seg' in self.labels_name[count]:\n                    if nl:\n                        masks, instances, cls = self._format_segments(instances, cls, w, h)\n                        masks = torch.from_numpy(masks)\n                    else:\n                        masks = torch.zeros(1 if self.mask_overlap else nl, img.shape[0] // self.mask_ratio,\n                                            img.shape[1] // self.mask_ratio)\n                    labels['masks'] = masks\n                if self.normalize:\n                    instances.normalize(w, h)\n                labels['img'] = self._format_img(img)\n                labels['cls'] = torch.from_numpy(cls) if nl else torch.zeros(nl)\n                labels['bboxes'] = torch.from_numpy(instances.bboxes) if nl else torch.zeros((nl, 4))\n                if self.return_keypoint:\n                    labels['keypoints'] = torch.from_numpy(instances.keypoints)\n                # Then we can use collate_fn\n                if self.batch_idx:\n                    labels['batch_idx'] = torch.zeros(nl)\n            return labels_list\n        else:\n            labels = labels_list\n            img = labels.pop('img')\n            h, w = img.shape[:2]\n            cls = labels.pop('cls')\n            instances = labels.pop('instances')\n            instances.convert_bbox(format=self.bbox_format)\n            instances.denormalize(w, h)\n            nl = len(instances)\n\n            if self.return_mask:\n                if nl:\n                    masks, instances, cls = self._format_segments(instances, cls, w, h)\n                    masks = torch.from_numpy(masks)\n                else:\n                    masks = torch.zeros(1 if self.mask_overlap else nl, img.shape[0] // self.mask_ratio,\n                                        img.shape[1] // self.mask_ratio)\n                labels['masks'] = masks\n            if self.normalize:\n                instances.normalize(w, h)\n            labels['img'] = self._format_img(img)\n            labels['cls'] = torch.from_numpy(cls) if nl else torch.zeros(nl)\n            labels['bboxes'] = torch.from_numpy(instances.bboxes) if nl else torch.zeros((nl, 4))\n            if self.return_keypoint:\n                labels['keypoints'] = torch.from_numpy(instances.keypoints)\n            # Then we can use collate_fn\n            if self.batch_idx:\n                labels['batch_idx'] = torch.zeros(nl)\n            return labels\n\n    def _format_img(self, img):\n        \"\"\"Format the image for YOLOv5 from Numpy array to PyTorch tensor.\"\"\"\n        if len(img.shape) < 3:\n            img = np.expand_dims(img, -1)\n        img = np.ascontiguousarray(img.transpose(2, 0, 1)[::-1])\n        img = torch.from_numpy(img)\n        return img\n\n    def _format_segments(self, instances, cls, w, h):\n        \"\"\"convert polygon points to bitmap.\"\"\"\n        segments = instances.segments\n        if self.mask_overlap:\n            masks, sorted_idx = polygons2masks_overlap((h, w), segments, downsample_ratio=self.mask_ratio)\n            masks = masks[None]  # (640, 640) -> (1, 640, 640)\n            instances = instances[sorted_idx]\n            cls = cls[sorted_idx]\n        else:\n            masks = polygons2masks((h, w), segments, color=1, downsample_ratio=self.mask_ratio)\n\n        return masks, instances, cls\n\n\ndef v8_transforms(dataset, imgsz, hyp):\n    \"\"\"Convert images to a size suitable for YOLOv8 training.\"\"\"\n    pre_transform = Compose([\n        Mosaic(dataset, imgsz=imgsz, p=hyp.mosaic),\n        CopyPaste(p=hyp.copy_paste),\n        RandomPerspective(\n            degrees=hyp.degrees,\n            translate=hyp.translate,\n            scale=hyp.scale,\n            shear=hyp.shear,\n            perspective=hyp.perspective,\n            pre_transform=LetterBox(new_shape=(imgsz, imgsz)),\n        )])\n    flip_idx = dataset.data.get('flip_idx', None)  # for keypoints augmentation\n    if dataset.use_keypoints and flip_idx is None and hyp.fliplr > 0.0:\n        hyp.fliplr = 0.0\n        LOGGER.warning(\"WARNING ⚠️ No `flip_idx` provided while training keypoints, setting augmentation 'fliplr=0.0'\")\n    return Compose([\n        pre_transform,\n        MixUp(dataset, pre_transform=pre_transform, p=hyp.mixup),\n        Albumentations(p=1.0),\n        RandomHSV(hgain=hyp.hsv_h, sgain=hyp.hsv_s, vgain=hyp.hsv_v),\n        RandomFlip(direction='vertical', p=hyp.flipud),\n        RandomFlip(direction='horizontal', p=hyp.fliplr, flip_idx=flip_idx)])  # transforms\n\n\n# Classification augmentations -----------------------------------------------------------------------------------------\ndef classify_transforms(size=224, mean=(0.0, 0.0, 0.0), std=(1.0, 1.0, 1.0)):  # IMAGENET_MEAN, IMAGENET_STD\n    # Transforms to apply if albumentations not installed\n    if not isinstance(size, int):\n        raise TypeError(f'classify_transforms() size {size} must be integer, not (list, tuple)')\n    if any(mean) or any(std):\n        return T.Compose([CenterCrop(size), ToTensor(), T.Normalize(mean, std, inplace=True)])\n    else:\n        return T.Compose([CenterCrop(size), ToTensor()])\n\n\ndef hsv2colorjitter(h, s, v):\n    \"\"\"Map HSV (hue, saturation, value) jitter into ColorJitter values (brightness, contrast, saturation, hue)\"\"\"\n    return v, v, s, h\n\n\ndef classify_albumentations(\n        augment=True,\n        size=224,\n        scale=(0.08, 1.0),\n        hflip=0.5,\n        vflip=0.0,\n        hsv_h=0.015,  # image HSV-Hue augmentation (fraction)\n        hsv_s=0.7,  # image HSV-Saturation augmentation (fraction)\n        hsv_v=0.4,  # image HSV-Value augmentation (fraction)\n        mean=(0.0, 0.0, 0.0),  # IMAGENET_MEAN\n        std=(1.0, 1.0, 1.0),  # IMAGENET_STD\n        auto_aug=False,\n):\n    # YOLOv8 classification Albumentations (optional, only used if package is installed)\n    prefix = colorstr('albumentations: ')\n    try:\n        import albumentations as A\n        from albumentations.pytorch import ToTensorV2\n\n        check_version(A.__version__, '1.0.3', hard=True)  # version requirement\n        if augment:  # Resize and crop\n            T = [A.RandomResizedCrop(height=size, width=size, scale=scale)]\n            if auto_aug:\n                # TODO: implement AugMix, AutoAug & RandAug in albumentations\n                LOGGER.info(f'{prefix}auto augmentations are currently not supported')\n            else:\n                if hflip > 0:\n                    T += [A.HorizontalFlip(p=hflip)]\n                if vflip > 0:\n                    T += [A.VerticalFlip(p=vflip)]\n                if any((hsv_h, hsv_s, hsv_v)):\n                    T += [A.ColorJitter(*hsv2colorjitter(hsv_h, hsv_s, hsv_v))]  # brightness, contrast, saturation, hue\n        else:  # Use fixed crop for eval set (reproducibility)\n            T = [A.SmallestMaxSize(max_size=size), A.CenterCrop(height=size, width=size)]\n        T += [A.Normalize(mean=mean, std=std), ToTensorV2()]  # Normalize and convert to Tensor\n        LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))\n        return A.Compose(T)\n\n    except ImportError:  # package not installed, skip\n        pass\n    except Exception as e:\n        LOGGER.info(f'{prefix}{e}')\n\n\nclass ClassifyLetterBox:\n    # YOLOv8 LetterBox class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])\n    def __init__(self, size=(640, 640), auto=False, stride=32):\n        \"\"\"Resizes image and crops it to center with max dimensions 'h' and 'w'.\"\"\"\n        super().__init__()\n        self.h, self.w = (size, size) if isinstance(size, int) else size\n        self.auto = auto  # pass max size integer, automatically solve for short side using stride\n        self.stride = stride  # used with auto\n\n    def __call__(self, im):  # im = np.array HWC\n        imh, imw = im.shape[:2]\n        r = min(self.h / imh, self.w / imw)  # ratio of new/old\n        h, w = round(imh * r), round(imw * r)  # resized image\n        hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else self.h, self.w\n        top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)\n        im_out = np.full((self.h, self.w, 3), 114, dtype=im.dtype)\n        im_out[top:top + h, left:left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)\n        return im_out\n\n\nclass CenterCrop:\n    # YOLOv8 CenterCrop class for image preprocessing, i.e. T.Compose([CenterCrop(size), ToTensor()])\n    def __init__(self, size=640):\n        \"\"\"Converts an image from numpy array to PyTorch tensor.\"\"\"\n        super().__init__()\n        self.h, self.w = (size, size) if isinstance(size, int) else size\n\n    def __call__(self, im):  # im = np.array HWC\n        imh, imw = im.shape[:2]\n        m = min(imh, imw)  # min dimension\n        top, left = (imh - m) // 2, (imw - m) // 2\n        return cv2.resize(im[top:top + m, left:left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)\n\n\nclass ToTensor:\n    # YOLOv8 ToTensor class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])\n    def __init__(self, half=False):\n        \"\"\"Initialize YOLOv8 ToTensor object with optional half-precision support.\"\"\"\n        super().__init__()\n        self.half = half\n\n    def __call__(self, im):  # im = np.array HWC in BGR order\n        im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1])  # HWC to CHW -> BGR to RGB -> contiguous\n        im = torch.from_numpy(im)  # to torch\n        im = im.half() if self.half else im.float()  # uint8 to fp16/32\n        im /= 255.0  # 0-255 to 0.0-1.0\n        return im\n"
  },
  {
    "path": "ultralytics/yolo/data/base.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport glob\nimport math\nimport os\nimport random\nfrom copy import deepcopy\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\nfrom typing import Optional\n\nimport cv2\nimport numpy as np\nimport psutil\nfrom torch.utils.data import Dataset\nfrom tqdm import tqdm\nimport torch\nfrom ..utils import DEFAULT_CFG, LOCAL_RANK, LOGGER, NUM_THREADS, TQDM_BAR_FORMAT\nfrom .utils import HELP_URL, IMG_FORMATS\n\n\nclass BaseDataset(Dataset):\n    \"\"\"\n    Base dataset class for loading and processing image data.\n\n    Args:\n        img_path (str): Path to the folder containing images.\n        imgsz (int, optional): Image size. Defaults to 640.\n        cache (bool, optional): Cache images to RAM or disk during training. Defaults to False.\n        augment (bool, optional): If True, data augmentation is applied. Defaults to True.\n        hyp (dict, optional): Hyperparameters to apply data augmentation. Defaults to None.\n        prefix (str, optional): Prefix to print in log messages. Defaults to ''.\n        rect (bool, optional): If True, rectangular training is used. Defaults to False.\n        batch_size (int, optional): Size of batches. Defaults to None.\n        stride (int, optional): Stride. Defaults to 32.\n        pad (float, optional): Padding. Defaults to 0.0.\n        single_cls (bool, optional): If True, single class training is used. Defaults to False.\n        classes (list): List of included classes. Default is None.\n\n    Attributes:\n        im_files (list): List of image file paths.\n        labels (list): List of label data dictionaries.\n        ni (int): Number of images in the dataset.\n        ims (list): List of loaded images.\n        npy_files (list): List of numpy file paths.\n        transforms (callable): Image transformation function.\n    \"\"\"\n\n    def __init__(self,\n                 img_path,\n                 imgsz=640,\n                 cache=False,\n                 augment=True,\n                 hyp=DEFAULT_CFG,\n                 prefix='',\n                 rect=False,\n                 batch_size=None,\n                 stride=32,\n                 pad=0.5,\n                 single_cls=False,\n                 classes=None):\n        super().__init__()\n        self.img_path = img_path\n        self.imgsz = imgsz\n        self.augment = augment\n        self.single_cls = single_cls\n        self.prefix = prefix\n        self.im_files = self.get_img_files(self.img_path)\n        if self.task_type == \"multi\":\n            self.labels = self.get_multi_labels()\n            self.update_multi_labels(include_class=classes)  # single_cls and include_class\n            self.ni = len(self.labels[0])  # number of images\n        else:\n            self.labels = self.get_labels()\n            self.update_labels(include_class=classes)  # single_cls and include_class\n            self.ni = len(self.labels)  # number of images\n        self.rect = rect\n        self.batch_size = batch_size\n        self.stride = stride\n        self.pad = pad\n        if self.rect:\n            assert self.batch_size is not None\n            self.set_rectangle()\n\n        # Cache stuff\n        if cache == 'ram' and not self.check_cache_ram():\n            cache = False\n        self.ims = [None] * self.ni\n        self.npy_files = [Path(f).with_suffix('.npy') for f in self.im_files]\n        if cache:\n            self.cache_images(cache)\n\n        # Transforms\n        self.transforms = self.build_transforms(hyp=hyp)\n        self.seg_transforms = self.build_seg_transforms(hyp=hyp)\n\n    def get_img_files(self, img_path):\n        \"\"\"Read image files.\"\"\"\n        try:\n            f = []  # image files\n            for p in img_path if isinstance(img_path, list) else [img_path]:\n                p = Path(p)  # os-agnostic\n                if p.is_dir():  # dir\n                    f += glob.glob(str(p / '**' / '*.*'), recursive=True)\n                    # F = list(p.rglob('*.*'))  # pathlib\n                elif p.is_file():  # file\n                    with open(p) as t:\n                        t = t.read().strip().splitlines()\n                        parent = str(p.parent) + os.sep\n                        f += [x.replace('./', parent) if x.startswith('./') else x for x in t]  # local to global path\n                        # F += [p.parent / x.lstrip(os.sep) for x in t]  # local to global path (pathlib)\n                else:\n                    raise FileNotFoundError(f'{self.prefix}{p} does not exist')\n            im_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS)\n            # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS])  # pathlib\n            assert im_files, f'{self.prefix}No images found'\n        except Exception as e:\n            raise FileNotFoundError(f'{self.prefix}Error loading data from {img_path}\\n{HELP_URL}') from e\n        return im_files\n\n    def update_labels(self, include_class: Optional[list]):\n        \"\"\"include_class, filter labels to include only these classes (optional).\"\"\"\n        include_class_array = np.array(include_class).reshape(1, -1)\n        for i in range(len(self.labels)):\n            if include_class is not None:\n                cls = self.labels[i]['cls']\n                bboxes = self.labels[i]['bboxes']\n                segments = self.labels[i]['segments']\n                keypoints = self.labels[i]['keypoints']\n                j = (cls == include_class_array).any(1)\n                self.labels[i]['cls'] = cls[j]\n                self.labels[i]['bboxes'] = bboxes[j]\n                if segments:\n                    self.labels[i]['segments'] = [segments[si] for si, idx in enumerate(j) if idx]\n                if keypoints is not None:\n                    self.labels[i]['keypoints'] = keypoints[j]\n            if self.single_cls:\n                self.labels[i]['cls'][:, 0] = 0\n\n    def update_multi_labels(self, include_class: Optional[list]):\n        \"\"\"include_class, filter labels to include only these classes (optional).\"\"\"\n        include_class_array = np.array(include_class).reshape(1, -1)\n        for task_labels in self.labels:  # 修改这里遍历每个任务的标签列表\n            for i in range(len(task_labels)):  # 对每个任务标签列表进行遍历\n                if include_class is not None:\n                    cls = task_labels[i]['cls']\n                    bboxes = task_labels[i]['bboxes']\n                    segments = task_labels[i]['segments']\n                    keypoints = task_labels[i]['keypoints']\n                    j = (cls == include_class_array).any(1)\n                    task_labels[i]['cls'] = cls[j]\n                    task_labels[i]['bboxes'] = bboxes[j]\n                    if segments:\n                        task_labels[i]['segments'] = [segments[si] for si, idx in enumerate(j) if idx]\n                    if keypoints is not None:\n                        task_labels[i]['keypoints'] = keypoints[j]\n                if self.single_cls:\n                    task_labels[i]['cls'][:, 0] = 0\n\n    def load_image(self, i):\n        \"\"\"Loads 1 image from dataset index 'i', returns (im, resized hw).\"\"\"\n        im, f, fn = self.ims[i], self.im_files[i], self.npy_files[i]\n        if im is None:  # not cached in RAM\n            if fn.exists():  # load npy\n                im = np.load(fn)\n            else:  # read image\n                im = cv2.imread(f)  # BGR\n                if im is None:\n                    raise FileNotFoundError(f'Image Not Found {f}')\n            h0, w0 = im.shape[:2]  # orig hw\n            r = self.imgsz / max(h0, w0)  # ratio\n            if r != 1:  # if sizes are not equal\n                interp = cv2.INTER_LINEAR if (self.augment or r > 1) else cv2.INTER_AREA\n                im = cv2.resize(im, (min(math.ceil(w0 * r), self.imgsz), min(math.ceil(h0 * r), self.imgsz)),\n                                interpolation=interp)\n            return im, (h0, w0), im.shape[:2]  # im, hw_original, hw_resized\n        return self.ims[i], self.im_hw0[i], self.im_hw[i]  # im, hw_original, hw_resized\n\n    def cache_images(self, cache):\n        \"\"\"Cache images to memory or disk.\"\"\"\n        b, gb = 0, 1 << 30  # bytes of cached images, bytes per gigabytes\n        self.im_hw0, self.im_hw = [None] * self.ni, [None] * self.ni\n        fcn = self.cache_images_to_disk if cache == 'disk' else self.load_image\n        with ThreadPool(NUM_THREADS) as pool:\n            results = pool.imap(fcn, range(self.ni))\n            pbar = tqdm(enumerate(results), total=self.ni, bar_format=TQDM_BAR_FORMAT, disable=LOCAL_RANK > 0)\n            for i, x in pbar:\n                if cache == 'disk':\n                    b += self.npy_files[i].stat().st_size\n                else:  # 'ram'\n                    self.ims[i], self.im_hw0[i], self.im_hw[i] = x  # im, hw_orig, hw_resized = load_image(self, i)\n                    b += self.ims[i].nbytes\n                pbar.desc = f'{self.prefix}Caching images ({b / gb:.1f}GB {cache})'\n            pbar.close()\n\n    def cache_images_to_disk(self, i):\n        \"\"\"Saves an image as an *.npy file for faster loading.\"\"\"\n        f = self.npy_files[i]\n        if not f.exists():\n            np.save(f.as_posix(), cv2.imread(self.im_files[i]))\n\n    def check_cache_ram(self, safety_margin=0.5):\n        \"\"\"Check image caching requirements vs available memory.\"\"\"\n        b, gb = 0, 1 << 30  # bytes of cached images, bytes per gigabytes\n        n = min(self.ni, 30)  # extrapolate from 30 random images\n        for _ in range(n):\n            im = cv2.imread(random.choice(self.im_files))  # sample image\n            ratio = self.imgsz / max(im.shape[0], im.shape[1])  # max(h, w)  # ratio\n            b += im.nbytes * ratio ** 2\n        mem_required = b * self.ni / n * (1 + safety_margin)  # GB required to cache dataset into RAM\n        mem = psutil.virtual_memory()\n        cache = mem_required < mem.available  # to cache or not to cache, that is the question\n        if not cache:\n            LOGGER.info(f'{self.prefix}{mem_required / gb:.1f}GB RAM required to cache images '\n                        f'with {int(safety_margin * 100)}% safety margin but only '\n                        f'{mem.available / gb:.1f}/{mem.total / gb:.1f}GB available, '\n                        f\"{'caching images ✅' if cache else 'not caching images ⚠️'}\")\n        return cache\n\n    def set_rectangle(self):\n        \"\"\"Sets the shape of bounding boxes for YOLO detections as rectangles.\"\"\"\n        if self.task_type == \"multi\":\n            bi = np.floor(np.arange(self.ni) / self.batch_size).astype(int)  # batch index\n            nb = bi[-1] + 1  # number of batches\n            s = np.array([x.pop('shape') for x in self.labels[0]])  # hw\n            ar = s[:, 0] / s[:, 1]  # aspect ratio\n            irect = ar.argsort()\n            self.im_files = [self.im_files[i] for i in irect]\n            for label_index in range(len(self.labels)):\n                self.labels[label_index] = [self.labels[label_index][i] for i in irect]\n            ar = ar[irect]\n\n            # Set training image shapes\n            shapes = [[1, 1]] * nb\n            for i in range(nb):\n                ari = ar[bi == i]\n                mini, maxi = ari.min(), ari.max()\n                if maxi < 1:\n                    shapes[i] = [maxi, 1]\n                elif mini > 1:\n                    shapes[i] = [1, 1 / mini]\n\n            self.batch_shapes = np.ceil(np.array(shapes) * self.imgsz / self.stride + self.pad).astype(\n                int) * self.stride\n            self.batch = bi  # batch index of image\n\n        else:\n            bi = np.floor(np.arange(self.ni) / self.batch_size).astype(int)  # batch index\n            nb = bi[-1] + 1  # number of batches\n            s = np.array([x.pop('shape') for x in self.labels])  # hw\n            ar = s[:, 0] / s[:, 1]  # aspect ratio\n            irect = ar.argsort()\n            self.im_files = [self.im_files[i] for i in irect]\n            self.labels = [self.labels[i] for i in irect]\n            ar = ar[irect]\n\n            # Set training image shapes\n            shapes = [[1, 1]] * nb\n            for i in range(nb):\n                ari = ar[bi == i]\n                mini, maxi = ari.min(), ari.max()\n                if maxi < 1:\n                    shapes[i] = [maxi, 1]\n                elif mini > 1:\n                    shapes[i] = [1, 1 / mini]\n\n            self.batch_shapes = np.ceil(np.array(shapes) * self.imgsz / self.stride + self.pad).astype(\n                int) * self.stride\n            self.batch = bi  # batch index of image\n\n    def __getitem__(self, index):\n        \"\"\"Returns transformed label information for given index.\"\"\"\n        ######Jiayuan\n        if self.task_type == 'multi':\n            label_list = self.get_label_info(index)\n            transfer_lable = []\n\n            # is_equal = np.array_equal(label_list[0]['img'], label_list[1]['img'])\n\n            if self.augment:\n                self.together = True  # the signal for augment\n                transfer = self.transforms(label_list)\n                self.together = False\n                return transfer\n            for i in range(len(label_list)):\n                self.global_count = i\n\n                if 'seg' in self.data['labels_list'][i]:\n                    transfer_lable.append(self.seg_transforms(label_list[i]))\n                    # transfer_lable.append(self.transforms(label_list[0]))\n                else:\n                    # test = self.transforms(label_list[i])\n                    transfer_lable.append(self.transforms(label_list[i]))\n            return transfer_lable\n        ######\n        else:\n            label = self.get_label_info(index)\n            # test = self.transforms(label)\n            return self.transforms(label)\n\n    def get_label_info(self, index):\n        if self.task_type == 'multi':\n            \"\"\"Get and return label information from the dataset.\"\"\"\n            label_list = []\n            for i in range(len(self.data['labels_list'])):\n                label = deepcopy(\n                    self.labels[i][index])  # requires deepcopy() https://github.com/ultralytics/ultralytics/pull/1948\n                label.pop('shape', None)  # shape is for rect, remove it\n                label['img'], label['ori_shape'], label['resized_shape'] = self.load_image(index)\n                label['ratio_pad'] = (label['resized_shape'][0] / label['ori_shape'][0],\n                                      label['resized_shape'][1] / label['ori_shape'][1])  # for evaluation\n                if self.rect:\n                    label['rect_shape'] = self.batch_shapes[self.batch[index]]\n                label = self.update_labels_info(label)\n                label_list.append(label)\n            return label_list\n        else:\n            \"\"\"Get and return label information from the dataset.\"\"\"\n            label = deepcopy(self.labels[index])  # requires deepcopy() https://github.com/ultralytics/ultralytics/pull/1948\n            label.pop('shape', None)  # shape is for rect, remove it\n            label['img'], label['ori_shape'], label['resized_shape'] = self.load_image(index)\n            label['ratio_pad'] = (label['resized_shape'][0] / label['ori_shape'][0],\n                                  label['resized_shape'][1] / label['ori_shape'][1])  # for evaluation\n            if self.rect:\n                label['rect_shape'] = self.batch_shapes[self.batch[index]]\n            label = self.update_labels_info(label)\n            return label\n\n    def __len__(self):\n        \"\"\"Returns the length of the labels list for the dataset.\"\"\"\n        if self.task_type == \"multi\":\n            return len(self.labels[0])\n        else:\n            return len(self.labels)\n\n    def update_labels_info(self, label):\n        \"\"\"custom your label format here.\"\"\"\n        return label\n\n    def build_transforms(self, hyp=None):\n        \"\"\"Users can custom augmentations here\n        like:\n            if self.augment:\n                # Training transforms\n                return Compose([])\n            else:\n                # Val transforms\n                return Compose([])\n        \"\"\"\n        raise NotImplementedError\n\n    def get_labels(self):\n        \"\"\"Users can custom their own format here.\n        Make sure your output is a list with each element like below:\n            dict(\n                im_file=im_file,\n                shape=shape,  # format: (height, width)\n                cls=cls,\n                bboxes=bboxes, # xywh\n                segments=segments,  # xy\n                keypoints=keypoints, # xy\n                normalized=True, # or False\n                bbox_format=\"xyxy\",  # or xywh, ltwh\n            )\n        \"\"\"\n        raise NotImplementedError\n"
  },
  {
    "path": "ultralytics/yolo/data/build.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport os\nimport random\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch.utils.data import dataloader, distributed\n\nfrom ultralytics.yolo.data.dataloaders.stream_loaders import (LOADERS, LoadImages, LoadPilAndNumpy, LoadScreenshots,\n                                                              LoadStreams, LoadTensor, SourceTypes, autocast_list)\nfrom ultralytics.yolo.data.utils import IMG_FORMATS, VID_FORMATS\nfrom ultralytics.yolo.utils.checks import check_file\n\nfrom ..utils import RANK, colorstr\nfrom .dataset import YOLODataset\nfrom .utils import PIN_MEMORY\n\n\nclass InfiniteDataLoader(dataloader.DataLoader):\n    \"\"\"Dataloader that reuses workers. Uses same syntax as vanilla DataLoader.\"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"Dataloader that infinitely recycles workers, inherits from DataLoader.\"\"\"\n        super().__init__(*args, **kwargs)\n        object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))\n        self.iterator = super().__iter__()\n\n    def __len__(self):\n        \"\"\"Returns the length of the batch sampler's sampler.\"\"\"\n        return len(self.batch_sampler.sampler)\n\n    def __iter__(self):\n        \"\"\"Creates a sampler that repeats indefinitely.\"\"\"\n        for _ in range(len(self)):\n            yield next(self.iterator)\n\n    def reset(self):\n        \"\"\"Reset iterator.\n        This is useful when we want to modify settings of dataset while training.\n        \"\"\"\n        self.iterator = self._get_iterator()\n\n\nclass _RepeatSampler:\n    \"\"\"\n    Sampler that repeats forever.\n\n    Args:\n        sampler (Dataset.sampler): The sampler to repeat.\n    \"\"\"\n\n    def __init__(self, sampler):\n        \"\"\"Initializes an object that repeats a given sampler indefinitely.\"\"\"\n        self.sampler = sampler\n\n    def __iter__(self):\n        \"\"\"Iterates over the 'sampler' and yields its contents.\"\"\"\n        while True:\n            yield from iter(self.sampler)\n\n\ndef seed_worker(worker_id):  # noqa\n    # Set dataloader worker seed https://pytorch.org/docs/stable/notes/randomness.html#dataloader\n    worker_seed = torch.initial_seed() % 2 ** 32\n    np.random.seed(worker_seed)\n    random.seed(worker_seed)\n\n\ndef build_yolo_dataset(cfg, img_path, batch, data_info, mode='train', rect=False, stride=32):\n    \"\"\"Build YOLO Dataset\"\"\"\n    return YOLODataset(\n        img_path=img_path,\n        imgsz=cfg.imgsz,\n        batch_size=batch,\n        augment=mode == 'train',  # augmentation\n        hyp=cfg,  # TODO: probably add a get_hyps_from_cfg function\n        rect=cfg.rect or rect,  # rectangular batches\n        cache=cfg.cache or None,\n        single_cls=cfg.single_cls or False,\n        stride=int(stride),\n        pad=0.0 if mode == 'train' else 0.5,\n        prefix=colorstr(f'{mode}: '),\n        task_type = cfg.task,\n        use_segments=cfg.task == 'segment',\n        use_keypoints=cfg.task == 'pose',\n        classes=cfg.classes,\n        data=data_info)\n\n\ndef build_dataloader(dataset, batch, workers, shuffle=True, rank=-1, collate_fn=None):\n    \"\"\"Return an InfiniteDataLoader or DataLoader for training or validation set.\"\"\"\n    batch = min(batch, len(dataset))\n    nd = torch.cuda.device_count()  # number of CUDA devices\n    nw = min([os.cpu_count() // max(nd, 1), batch if batch > 1 else 0, workers])  # number of workers\n    sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)\n    generator = torch.Generator()\n    generator.manual_seed(6148914691236517205 + RANK)\n    if collate_fn==None:\n        return InfiniteDataLoader(dataset=dataset,\n                                  batch_size=batch,\n                                  shuffle=shuffle and sampler is None,\n                                  num_workers=nw,\n                                  sampler=sampler,\n                                  pin_memory=PIN_MEMORY,\n                                  collate_fn=getattr(dataset, 'collate_fn', None),\n                                  worker_init_fn=seed_worker,\n                                  generator=generator)\n    else:\n        return InfiniteDataLoader(dataset=dataset,\n                                  batch_size=batch,\n                                  shuffle=shuffle and sampler is None,\n                                  num_workers=nw,\n                                  sampler=sampler,\n                                  pin_memory=PIN_MEMORY,\n                                  collate_fn=collate_fn,\n                                  worker_init_fn=seed_worker,\n                                  generator=generator)\n\n\ndef check_source(source):\n    \"\"\"Check source type and return corresponding flag values.\"\"\"\n    webcam, screenshot, from_img, in_memory, tensor = False, False, False, False, False\n    if isinstance(source, (str, int, Path)):  # int for local usb camera\n        source = str(source)\n        is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)\n        is_url = source.lower().startswith(('https://', 'http://', 'rtsp://', 'rtmp://'))\n        webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)\n        screenshot = source.lower().startswith('screen')\n        if is_url and is_file:\n            source = check_file(source)  # download\n    elif isinstance(source, tuple(LOADERS)):\n        in_memory = True\n    elif isinstance(source, (list, tuple)):\n        source = autocast_list(source)  # convert all list elements to PIL or np arrays\n        from_img = True\n    elif isinstance(source, (Image.Image, np.ndarray)):\n        from_img = True\n    elif isinstance(source, torch.Tensor):\n        tensor = True\n    else:\n        raise TypeError('Unsupported image type. For supported types see https://docs.ultralytics.com/modes/predict')\n\n    return source, webcam, screenshot, from_img, in_memory, tensor\n\n\ndef load_inference_source(source=None, imgsz=640, vid_stride=1):\n    \"\"\"\n    Loads an inference source for object detection and applies necessary transformations.\n\n    Args:\n        source (str, Path, Tensor, PIL.Image, np.ndarray): The input source for inference.\n        imgsz (int, optional): The size of the image for inference. Default is 640.\n        vid_stride (int, optional): The frame interval for video sources. Default is 1.\n\n    Returns:\n        dataset (Dataset): A dataset object for the specified input source.\n    \"\"\"\n    source, webcam, screenshot, from_img, in_memory, tensor = check_source(source)\n    source_type = source.source_type if in_memory else SourceTypes(webcam, screenshot, from_img, tensor)\n\n    # Dataloader\n    if tensor:\n        dataset = LoadTensor(source)\n    elif in_memory:\n        dataset = source\n    elif webcam:\n        dataset = LoadStreams(source, imgsz=imgsz, vid_stride=vid_stride)\n    elif screenshot:\n        dataset = LoadScreenshots(source, imgsz=imgsz)\n    elif from_img:\n        dataset = LoadPilAndNumpy(source, imgsz=imgsz)\n    else:\n        dataset = LoadImages(source, imgsz=imgsz, vid_stride=vid_stride)\n\n    # Attach source types to the dataset\n    setattr(dataset, 'source_type', source_type)\n\n    return dataset\n"
  },
  {
    "path": "ultralytics/yolo/data/converter.py",
    "content": "import json\nfrom collections import defaultdict\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom ultralytics.yolo.utils.checks import check_requirements\nfrom ultralytics.yolo.utils.files import make_dirs\n\n\ndef coco91_to_coco80_class():\n    \"\"\"Converts 91-index COCO class IDs to 80-index COCO class IDs.\n\n    Returns:\n        (list): A list of 91 class IDs where the index represents the 80-index class ID and the value is the\n            corresponding 91-index class ID.\n\n    \"\"\"\n    return [\n        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, None, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, None, 24, 25, None,\n        None, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, None, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50,\n        51, 52, 53, 54, 55, 56, 57, 58, 59, None, 60, None, None, 61, None, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72,\n        None, 73, 74, 75, 76, 77, 78, 79, None]\n\n\ndef convert_coco(labels_dir='../coco/annotations/', use_segments=False, use_keypoints=False, cls91to80=True):\n    \"\"\"Converts COCO dataset annotations to a format suitable for training YOLOv5 models.\n\n    Args:\n        labels_dir (str, optional): Path to directory containing COCO dataset annotation files.\n        use_segments (bool, optional): Whether to include segmentation masks in the output.\n        use_keypoints (bool, optional): Whether to include keypoint annotations in the output.\n        cls91to80 (bool, optional): Whether to map 91 COCO class IDs to the corresponding 80 COCO class IDs.\n\n    Raises:\n        FileNotFoundError: If the labels_dir path does not exist.\n\n    Example Usage:\n        convert_coco(labels_dir='../coco/annotations/', use_segments=True, use_keypoints=True, cls91to80=True)\n\n    Output:\n        Generates output files in the specified output directory.\n    \"\"\"\n\n    save_dir = make_dirs('yolo_labels')  # output directory\n    coco80 = coco91_to_coco80_class()\n\n    # Import json\n    for json_file in sorted(Path(labels_dir).resolve().glob('*.json')):\n        fn = Path(save_dir) / 'labels' / json_file.stem.replace('instances_', '')  # folder name\n        fn.mkdir(parents=True, exist_ok=True)\n        with open(json_file) as f:\n            data = json.load(f)\n\n        # Create image dict\n        images = {'%g' % x['id']: x for x in data['images']}\n        # Create image-annotations dict\n        imgToAnns = defaultdict(list)\n        for ann in data['annotations']:\n            imgToAnns[ann['image_id']].append(ann)\n\n        # Write labels file\n        for img_id, anns in tqdm(imgToAnns.items(), desc=f'Annotations {json_file}'):\n            img = images['%g' % img_id]\n            h, w, f = img['height'], img['width'], img['file_name']\n\n            bboxes = []\n            segments = []\n            keypoints = []\n            for ann in anns:\n                if ann['iscrowd']:\n                    continue\n                # The COCO box format is [top left x, top left y, width, height]\n                box = np.array(ann['bbox'], dtype=np.float64)\n                box[:2] += box[2:] / 2  # xy top-left corner to center\n                box[[0, 2]] /= w  # normalize x\n                box[[1, 3]] /= h  # normalize y\n                if box[2] <= 0 or box[3] <= 0:  # if w <= 0 and h <= 0\n                    continue\n\n                cls = coco80[ann['category_id'] - 1] if cls91to80 else ann['category_id'] - 1  # class\n                box = [cls] + box.tolist()\n                if box not in bboxes:\n                    bboxes.append(box)\n                if use_segments and ann.get('segmentation') is not None:\n                    if len(ann['segmentation']) == 0:\n                        segments.append([])\n                        continue\n                    if isinstance(ann['segmentation'], dict):\n                        ann['segmentation'] = rle2polygon(ann['segmentation'])\n                    if len(ann['segmentation']) > 1:\n                        s = merge_multi_segment(ann['segmentation'])\n                        s = (np.concatenate(s, axis=0) / np.array([w, h])).reshape(-1).tolist()\n                    else:\n                        s = [j for i in ann['segmentation'] for j in i]  # all segments concatenated\n                        s = (np.array(s).reshape(-1, 2) / np.array([w, h])).reshape(-1).tolist()\n                    s = [cls] + s\n                    if s not in segments:\n                        segments.append(s)\n                if use_keypoints and ann.get('keypoints') is not None:\n                    k = (np.array(ann['keypoints']).reshape(-1, 3) / np.array([w, h, 1])).reshape(-1).tolist()\n                    k = box + k\n                    keypoints.append(k)\n\n            # Write\n            with open((fn / f).with_suffix('.txt'), 'a') as file:\n                for i in range(len(bboxes)):\n                    if use_keypoints:\n                        line = *(keypoints[i]),  # cls, box, keypoints\n                    else:\n                        line = *(segments[i]\n                                 if use_segments and len(segments[i]) > 0 else bboxes[i]),  # cls, box or segments\n                    file.write(('%g ' * len(line)).rstrip() % line + '\\n')\n\n\ndef rle2polygon(segmentation):\n    \"\"\"\n    Convert Run-Length Encoding (RLE) mask to polygon coordinates.\n\n    Args:\n        segmentation (dict, list): RLE mask representation of the object segmentation.\n\n    Returns:\n        (list): A list of lists representing the polygon coordinates for each contour.\n\n    Note:\n        Requires the 'pycocotools' package to be installed.\n    \"\"\"\n    check_requirements('pycocotools')\n    from pycocotools import mask\n\n    m = mask.decode(segmentation)\n    m[m > 0] = 255\n    contours, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS)\n    polygons = []\n    for contour in contours:\n        epsilon = 0.001 * cv2.arcLength(contour, True)\n        contour_approx = cv2.approxPolyDP(contour, epsilon, True)\n        polygon = contour_approx.flatten().tolist()\n        polygons.append(polygon)\n    return polygons\n\n\ndef min_index(arr1, arr2):\n    \"\"\"\n    Find a pair of indexes with the shortest distance between two arrays of 2D points.\n\n    Args:\n        arr1 (np.array): A NumPy array of shape (N, 2) representing N 2D points.\n        arr2 (np.array): A NumPy array of shape (M, 2) representing M 2D points.\n\n    Returns:\n        (tuple): A tuple containing the indexes of the points with the shortest distance in arr1 and arr2 respectively.\n    \"\"\"\n    dis = ((arr1[:, None, :] - arr2[None, :, :]) ** 2).sum(-1)\n    return np.unravel_index(np.argmin(dis, axis=None), dis.shape)\n\n\ndef merge_multi_segment(segments):\n    \"\"\"\n    Merge multiple segments into one list by connecting the coordinates with the minimum distance between each segment.\n    This function connects these coordinates with a thin line to merge all segments into one.\n\n    Args:\n        segments (List[List]): Original segmentations in COCO's JSON file.\n                               Each element is a list of coordinates, like [segmentation1, segmentation2,...].\n\n    Returns:\n        s (List[np.ndarray]): A list of connected segments represented as NumPy arrays.\n    \"\"\"\n    s = []\n    segments = [np.array(i).reshape(-1, 2) for i in segments]\n    idx_list = [[] for _ in range(len(segments))]\n\n    # record the indexes with min distance between each segment\n    for i in range(1, len(segments)):\n        idx1, idx2 = min_index(segments[i - 1], segments[i])\n        idx_list[i - 1].append(idx1)\n        idx_list[i].append(idx2)\n\n    # use two round to connect all the segments\n    for k in range(2):\n        # forward connection\n        if k == 0:\n            for i, idx in enumerate(idx_list):\n                # middle segments have two indexes\n                # reverse the index of middle segments\n                if len(idx) == 2 and idx[0] > idx[1]:\n                    idx = idx[::-1]\n                    segments[i] = segments[i][::-1, :]\n\n                segments[i] = np.roll(segments[i], -idx[0], axis=0)\n                segments[i] = np.concatenate([segments[i], segments[i][:1]])\n                # deal with the first segment and the last one\n                if i in [0, len(idx_list) - 1]:\n                    s.append(segments[i])\n                else:\n                    idx = [0, idx[1] - idx[0]]\n                    s.append(segments[i][idx[0]:idx[1] + 1])\n\n        else:\n            for i in range(len(idx_list) - 1, -1, -1):\n                if i not in [0, len(idx_list) - 1]:\n                    idx = idx_list[i]\n                    nidx = abs(idx[1] - idx[0])\n                    s.append(segments[i][nidx:])\n    return s\n\n\ndef delete_dsstore(path='../datasets'):\n    \"\"\"Delete Apple .DS_Store files in the specified directory and its subdirectories.\"\"\"\n    from pathlib import Path\n\n    files = list(Path(path).rglob('.DS_store'))\n    print(files)\n    for f in files:\n        f.unlink()\n\n\nif __name__ == '__main__':\n    source = 'COCO'\n\n    if source == 'COCO':\n        convert_coco(\n            '../datasets/coco/annotations',  # directory with *.json\n            use_segments=False,\n            use_keypoints=True,\n            cls91to80=False)\n"
  },
  {
    "path": "ultralytics/yolo/data/dataloaders/__init__.py",
    "content": ""
  },
  {
    "path": "ultralytics/yolo/data/dataloaders/stream_loaders.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport glob\nimport math\nimport os\nimport time\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom threading import Thread\nfrom urllib.parse import urlparse\n\nimport cv2\nimport numpy as np\nimport requests\nimport torch\nfrom PIL import Image\n\nfrom ultralytics.yolo.data.utils import IMG_FORMATS, VID_FORMATS\nfrom ultralytics.yolo.utils import LOGGER, ROOT, is_colab, is_kaggle, ops\nfrom ultralytics.yolo.utils.checks import check_requirements\n\n\n@dataclass\nclass SourceTypes:\n    webcam: bool = False\n    screenshot: bool = False\n    from_img: bool = False\n    tensor: bool = False\n\n\nclass LoadStreams:\n    # YOLOv8 streamloader, i.e. `yolo predict source='rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP streams`\n    def __init__(self, sources='file.streams', imgsz=640, vid_stride=1):\n        \"\"\"Initialize instance variables and check for consistent input stream shapes.\"\"\"\n        torch.backends.cudnn.benchmark = True  # faster for fixed-size inference\n        self.mode = 'stream'\n        self.imgsz = imgsz\n        self.vid_stride = vid_stride  # video frame-rate stride\n        sources = Path(sources).read_text().rsplit() if os.path.isfile(sources) else [sources]\n        n = len(sources)\n        self.sources = [ops.clean_str(x) for x in sources]  # clean source names for later\n        self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n\n        for i, s in enumerate(sources):  # index, source\n            # Start thread to read frames from video stream\n            st = f'{i + 1}/{n}: {s}... '\n            if urlparse(s).hostname in ('www.youtube.com', 'youtube.com', 'youtu.be'):  # if source is YouTube video\n                # YouTube format i.e. 'https://www.youtube.com/watch?v=Zgi9g1ksQHc' or 'https://youtu.be/Zgi9g1ksQHc'\n                check_requirements(('pafy', 'youtube_dl==2020.12.2'))\n                import pafy  # noqa\n                s = pafy.new(s).getbest(preftype='mp4').url  # YouTube URL\n            s = eval(s) if s.isnumeric() else s  # i.e. s = '0' local webcam\n            if s == 0 and (is_colab() or is_kaggle()):\n                raise NotImplementedError(\"'source=0' webcam not supported in Colab and Kaggle notebooks. \"\n                                          \"Try running 'source=0' in a local environment.\")\n            cap = cv2.VideoCapture(s)\n            if not cap.isOpened():\n                raise ConnectionError(f'{st}Failed to open {s}')\n            w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n            h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n            fps = cap.get(cv2.CAP_PROP_FPS)  # warning: may return 0 or nan\n            self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf')  # infinite stream fallback\n            self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30  # 30 FPS fallback\n\n            success, self.imgs[i] = cap.read()  # guarantee first frame\n            if not success or self.imgs[i] is None:\n                raise ConnectionError(f'{st}Failed to read images from {s}')\n            self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True)\n            LOGGER.info(f'{st}Success ✅ ({self.frames[i]} frames of shape {w}x{h} at {self.fps[i]:.2f} FPS)')\n            self.threads[i].start()\n        LOGGER.info('')  # newline\n\n        # Check for common shapes\n        self.bs = self.__len__()\n\n    def update(self, i, cap, stream):\n        \"\"\"Read stream `i` frames in daemon thread.\"\"\"\n        n, f = 0, self.frames[i]  # frame number, frame array\n        while cap.isOpened() and n < f:\n            n += 1\n            cap.grab()  # .read() = .grab() followed by .retrieve()\n            if n % self.vid_stride == 0:\n                success, im = cap.retrieve()\n                if success:\n                    self.imgs[i] = im\n                else:\n                    LOGGER.warning('WARNING ⚠️ Video stream unresponsive, please check your IP camera connection.')\n                    self.imgs[i] = np.zeros_like(self.imgs[i])\n                    cap.open(stream)  # re-open stream if signal was lost\n            time.sleep(0.0)  # wait time\n\n    def __iter__(self):\n        \"\"\"Iterates through YOLO image feed and re-opens unresponsive streams.\"\"\"\n        self.count = -1\n        return self\n\n    def __next__(self):\n        \"\"\"Returns source paths, transformed and original images for processing YOLOv5.\"\"\"\n        self.count += 1\n        if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'):  # q to quit\n            cv2.destroyAllWindows()\n            raise StopIteration\n\n        im0 = self.imgs.copy()\n        return self.sources, im0, None, ''\n\n    def __len__(self):\n        \"\"\"Return the length of the sources object.\"\"\"\n        return len(self.sources)  # 1E12 frames = 32 streams at 30 FPS for 30 years\n\n\nclass LoadScreenshots:\n    # YOLOv8 screenshot dataloader, i.e. `yolo predict source=screen`\n    def __init__(self, source, imgsz=640):\n        \"\"\"source = [screen_number left top width height] (pixels).\"\"\"\n        check_requirements('mss')\n        import mss  # noqa\n\n        source, *params = source.split()\n        self.screen, left, top, width, height = 0, None, None, None, None  # default to full screen 0\n        if len(params) == 1:\n            self.screen = int(params[0])\n        elif len(params) == 4:\n            left, top, width, height = (int(x) for x in params)\n        elif len(params) == 5:\n            self.screen, left, top, width, height = (int(x) for x in params)\n        self.imgsz = imgsz\n        self.mode = 'stream'\n        self.frame = 0\n        self.sct = mss.mss()\n        self.bs = 1\n\n        # Parse monitor shape\n        monitor = self.sct.monitors[self.screen]\n        self.top = monitor['top'] if top is None else (monitor['top'] + top)\n        self.left = monitor['left'] if left is None else (monitor['left'] + left)\n        self.width = width or monitor['width']\n        self.height = height or monitor['height']\n        self.monitor = {'left': self.left, 'top': self.top, 'width': self.width, 'height': self.height}\n\n    def __iter__(self):\n        \"\"\"Returns an iterator of the object.\"\"\"\n        return self\n\n    def __next__(self):\n        \"\"\"mss screen capture: get raw pixels from the screen as np array.\"\"\"\n        im0 = np.array(self.sct.grab(self.monitor))[:, :, :3]  # [:, :, :3] BGRA to BGR\n        s = f'screen {self.screen} (LTWH): {self.left},{self.top},{self.width},{self.height}: '\n\n        self.frame += 1\n        return str(self.screen), im0, None, s  # screen, img, original img, im0s, s\n\n\nclass LoadImages:\n    # YOLOv8 image/video dataloader, i.e. `yolo predict source=image.jpg/vid.mp4`\n    def __init__(self, path, imgsz=640, vid_stride=1):\n        \"\"\"Initialize the Dataloader and raise FileNotFoundError if file not found.\"\"\"\n        if isinstance(path, str) and Path(path).suffix == '.txt':  # *.txt file with img/vid/dir on each line\n            path = Path(path).read_text().rsplit()\n        files = []\n        for p in sorted(path) if isinstance(path, (list, tuple)) else [path]:\n            p = str(Path(p).resolve())\n            if '*' in p:\n                files.extend(sorted(glob.glob(p, recursive=True)))  # glob\n            elif os.path.isdir(p):\n                files.extend(sorted(glob.glob(os.path.join(p, '*.*'))))  # dir\n            elif os.path.isfile(p):\n                files.append(p)  # files\n            else:\n                raise FileNotFoundError(f'{p} does not exist')\n\n        images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]\n        videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]\n        ni, nv = len(images), len(videos)\n\n        self.imgsz = imgsz\n        self.files = images + videos\n        self.nf = ni + nv  # number of files\n        self.video_flag = [False] * ni + [True] * nv\n        self.mode = 'image'\n        self.vid_stride = vid_stride  # video frame-rate stride\n        self.bs = 1\n        if any(videos):\n            self.orientation = None  # rotation degrees\n            self._new_video(videos[0])  # new video\n        else:\n            self.cap = None\n        if self.nf == 0:\n            raise FileNotFoundError(f'No images or videos found in {p}. '\n                                    f'Supported formats are:\\nimages: {IMG_FORMATS}\\nvideos: {VID_FORMATS}')\n\n    def __iter__(self):\n        \"\"\"Returns an iterator object for VideoStream or ImageFolder.\"\"\"\n        self.count = 0\n        return self\n\n    def __next__(self):\n        \"\"\"Return next image, path and metadata from dataset.\"\"\"\n        if self.count == self.nf:\n            raise StopIteration\n        path = self.files[self.count]\n\n        if self.video_flag[self.count]:\n            # Read video\n            self.mode = 'video'\n            for _ in range(self.vid_stride):\n                self.cap.grab()\n            success, im0 = self.cap.retrieve()\n            while not success:\n                self.count += 1\n                self.cap.release()\n                if self.count == self.nf:  # last video\n                    raise StopIteration\n                path = self.files[self.count]\n                self._new_video(path)\n                success, im0 = self.cap.read()\n\n            self.frame += 1\n            # im0 = self._cv2_rotate(im0)  # for use if cv2 autorotation is False\n            s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: '\n\n        else:\n            # Read image\n            self.count += 1\n            im0 = cv2.imread(path)  # BGR\n            if im0 is None:\n                raise FileNotFoundError(f'Image Not Found {path}')\n            s = f'image {self.count}/{self.nf} {path}: '\n\n        return [path], [im0], self.cap, s\n\n    def _new_video(self, path):\n        \"\"\"Create a new video capture object.\"\"\"\n        self.frame = 0\n        self.cap = cv2.VideoCapture(path)\n        self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT) / self.vid_stride)\n        if hasattr(cv2, 'CAP_PROP_ORIENTATION_META'):  # cv2<4.6.0 compatibility\n            self.orientation = int(self.cap.get(cv2.CAP_PROP_ORIENTATION_META))  # rotation degrees\n            # Disable auto-orientation due to known issues in https://github.com/ultralytics/yolov5/issues/8493\n            # self.cap.set(cv2.CAP_PROP_ORIENTATION_AUTO, 0)\n\n    def _cv2_rotate(self, im):\n        \"\"\"Rotate a cv2 video manually.\"\"\"\n        if self.orientation == 0:\n            return cv2.rotate(im, cv2.ROTATE_90_CLOCKWISE)\n        elif self.orientation == 180:\n            return cv2.rotate(im, cv2.ROTATE_90_COUNTERCLOCKWISE)\n        elif self.orientation == 90:\n            return cv2.rotate(im, cv2.ROTATE_180)\n        return im\n\n    def __len__(self):\n        \"\"\"Returns the number of files in the object.\"\"\"\n        return self.nf  # number of files\n\n\nclass LoadPilAndNumpy:\n\n    def __init__(self, im0, imgsz=640):\n        \"\"\"Initialize PIL and Numpy Dataloader.\"\"\"\n        if not isinstance(im0, list):\n            im0 = [im0]\n        self.paths = [getattr(im, 'filename', f'image{i}.jpg') for i, im in enumerate(im0)]\n        self.im0 = [self._single_check(im) for im in im0]\n        self.imgsz = imgsz\n        self.mode = 'image'\n        # Generate fake paths\n        self.bs = len(self.im0)\n\n    @staticmethod\n    def _single_check(im):\n        \"\"\"Validate and format an image to numpy array.\"\"\"\n        assert isinstance(im, (Image.Image, np.ndarray)), f'Expected PIL/np.ndarray image type, but got {type(im)}'\n        if isinstance(im, Image.Image):\n            if im.mode != 'RGB':\n                im = im.convert('RGB')\n            im = np.asarray(im)[:, :, ::-1]\n            im = np.ascontiguousarray(im)  # contiguous\n        return im\n\n    def __len__(self):\n        \"\"\"Returns the length of the 'im0' attribute.\"\"\"\n        return len(self.im0)\n\n    def __next__(self):\n        \"\"\"Returns batch paths, images, processed images, None, ''.\"\"\"\n        if self.count == 1:  # loop only once as it's batch inference\n            raise StopIteration\n        self.count += 1\n        return self.paths, self.im0, None, ''\n\n    def __iter__(self):\n        \"\"\"Enables iteration for class LoadPilAndNumpy.\"\"\"\n        self.count = 0\n        return self\n\n\nclass LoadTensor:\n\n    def __init__(self, imgs) -> None:\n        self.im0 = imgs\n        self.bs = imgs.shape[0]\n        self.mode = 'image'\n\n    def __iter__(self):\n        \"\"\"Returns an iterator object.\"\"\"\n        self.count = 0\n        return self\n\n    def __next__(self):\n        \"\"\"Return next item in the iterator.\"\"\"\n        if self.count == 1:\n            raise StopIteration\n        self.count += 1\n        return None, self.im0, None, ''  # self.paths, im, self.im0, None, ''\n\n    def __len__(self):\n        \"\"\"Returns the batch size.\"\"\"\n        return self.bs\n\n\ndef autocast_list(source):\n    \"\"\"\n    Merges a list of source of different types into a list of numpy arrays or PIL images\n    \"\"\"\n    files = []\n    for im in source:\n        if isinstance(im, (str, Path)):  # filename or uri\n            files.append(Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im))\n        elif isinstance(im, (Image.Image, np.ndarray)):  # PIL or np Image\n            files.append(im)\n        else:\n            raise TypeError(f'type {type(im).__name__} is not a supported Ultralytics prediction source type. \\n'\n                            f'See https://docs.ultralytics.com/modes/predict for supported source types.')\n\n    return files\n\n\nLOADERS = [LoadStreams, LoadPilAndNumpy, LoadImages, LoadScreenshots]\n\nif __name__ == '__main__':\n    img = cv2.imread(str(ROOT / 'assets/bus.jpg'))\n    dataset = LoadPilAndNumpy(im0=img)\n    for d in dataset:\n        print(d[0])\n"
  },
  {
    "path": "ultralytics/yolo/data/dataloaders/v5augmentations.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nImage augmentation functions\n\"\"\"\n\nimport math\nimport random\n\nimport cv2\nimport numpy as np\nimport torch\nimport torchvision.transforms as T\nimport torchvision.transforms.functional as TF\n\nfrom ultralytics.yolo.utils import LOGGER, colorstr\nfrom ultralytics.yolo.utils.checks import check_version\nfrom ultralytics.yolo.utils.metrics import bbox_ioa\nfrom ultralytics.yolo.utils.ops import resample_segments, segment2box, xywhn2xyxy\n\nIMAGENET_MEAN = 0.485, 0.456, 0.406  # RGB mean\nIMAGENET_STD = 0.229, 0.224, 0.225  # RGB standard deviation\n\n\nclass Albumentations:\n    # YOLOv5 Albumentations class (optional, only used if package is installed)\n    def __init__(self, size=640):\n        \"\"\"Instantiate object with image augmentations for YOLOv5.\"\"\"\n        self.transform = None\n        prefix = colorstr('albumentations: ')\n        try:\n            import albumentations as A\n            check_version(A.__version__, '1.0.3', hard=True)  # version requirement\n\n            T = [\n                A.RandomResizedCrop(height=size, width=size, scale=(0.8, 1.0), ratio=(0.9, 1.11), p=0.0),\n                A.Blur(p=0.01),\n                A.MedianBlur(p=0.01),\n                A.ToGray(p=0.01),\n                A.CLAHE(p=0.01),\n                A.RandomBrightnessContrast(p=0.0),\n                A.RandomGamma(p=0.0),\n                A.ImageCompression(quality_lower=75, p=0.0)]  # transforms\n            self.transform = A.Compose(T, bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))\n\n            LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))\n        except ImportError:  # package not installed, skip\n            pass\n        except Exception as e:\n            LOGGER.info(f'{prefix}{e}')\n\n    def __call__(self, im, labels, p=1.0):\n        \"\"\"Transforms input image and labels with probability 'p'.\"\"\"\n        if self.transform and random.random() < p:\n            new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0])  # transformed\n            im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])\n        return im, labels\n\n\ndef normalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD, inplace=False):\n    \"\"\"Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = (x - mean) / std.\"\"\"\n    return TF.normalize(x, mean, std, inplace=inplace)\n\n\ndef denormalize(x, mean=IMAGENET_MEAN, std=IMAGENET_STD):\n    \"\"\"Denormalize RGB images x per ImageNet stats in BCHW format, i.e. = x * std + mean.\"\"\"\n    for i in range(3):\n        x[:, i] = x[:, i] * std[i] + mean[i]\n    return x\n\n\ndef augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):\n    \"\"\"HSV color-space augmentation.\"\"\"\n    if hgain or sgain or vgain:\n        r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1  # random gains\n        hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))\n        dtype = im.dtype  # uint8\n\n        x = np.arange(0, 256, dtype=r.dtype)\n        lut_hue = ((x * r[0]) % 180).astype(dtype)\n        lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)\n        lut_val = np.clip(x * r[2], 0, 255).astype(dtype)\n\n        im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))\n        cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im)  # no return needed\n\n\ndef hist_equalize(im, clahe=True, bgr=False):\n    \"\"\"Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255.\"\"\"\n    yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)\n    if clahe:\n        c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n        yuv[:, :, 0] = c.apply(yuv[:, :, 0])\n    else:\n        yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0])  # equalize Y channel histogram\n    return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB)  # convert YUV image to RGB\n\n\ndef replicate(im, labels):\n    \"\"\"Replicate labels.\"\"\"\n    h, w = im.shape[:2]\n    boxes = labels[:, 1:].astype(int)\n    x1, y1, x2, y2 = boxes.T\n    s = ((x2 - x1) + (y2 - y1)) / 2  # side length (pixels)\n    for i in s.argsort()[:round(s.size * 0.5)]:  # smallest indices\n        x1b, y1b, x2b, y2b = boxes[i]\n        bh, bw = y2b - y1b, x2b - x1b\n        yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw))  # offset x, y\n        x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]\n        im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b]  # im4[ymin:ymax, xmin:xmax]\n        labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)\n\n    return im, labels\n\n\ndef letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):\n    \"\"\"Resize and pad image while meeting stride-multiple constraints.\"\"\"\n    shape = im.shape[:2]  # current shape [height, width]\n    if isinstance(new_shape, int):\n        new_shape = (new_shape, new_shape)\n\n    # Scale ratio (new / old)\n    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])\n    if not scaleup:  # only scale down, do not scale up (for better val mAP)\n        r = min(r, 1.0)\n\n    # Compute padding\n    ratio = r, r  # width, height ratios\n    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))\n    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding\n    if auto:  # minimum rectangle\n        dw, dh = np.mod(dw, stride), np.mod(dh, stride)  # wh padding\n    elif scaleFill:  # stretch\n        dw, dh = 0.0, 0.0\n        new_unpad = (new_shape[1], new_shape[0])\n        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios\n\n    dw /= 2  # divide padding into 2 sides\n    dh /= 2\n\n    if shape[::-1] != new_unpad:  # resize\n        im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)\n    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))\n    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))\n    im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border\n    return im, ratio, (dw, dh)\n\n\ndef random_perspective(im,\n                       targets=(),\n                       segments=(),\n                       degrees=10,\n                       translate=.1,\n                       scale=.1,\n                       shear=10,\n                       perspective=0.0,\n                       border=(0, 0)):\n    # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(0.1, 0.1), scale=(0.9, 1.1), shear=(-10, 10))\n    # targets = [cls, xyxy]\n\n    height = im.shape[0] + border[0] * 2  # shape(h,w,c)\n    width = im.shape[1] + border[1] * 2\n\n    # Center\n    C = np.eye(3)\n    C[0, 2] = -im.shape[1] / 2  # x translation (pixels)\n    C[1, 2] = -im.shape[0] / 2  # y translation (pixels)\n\n    # Perspective\n    P = np.eye(3)\n    P[2, 0] = random.uniform(-perspective, perspective)  # x perspective (about y)\n    P[2, 1] = random.uniform(-perspective, perspective)  # y perspective (about x)\n\n    # Rotation and Scale\n    R = np.eye(3)\n    a = random.uniform(-degrees, degrees)\n    # a += random.choice([-180, -90, 0, 90])  # add 90deg rotations to small rotations\n    s = random.uniform(1 - scale, 1 + scale)\n    # s = 2 ** random.uniform(-scale, scale)\n    R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)\n\n    # Shear\n    S = np.eye(3)\n    S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # x shear (deg)\n    S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # y shear (deg)\n\n    # Translation\n    T = np.eye(3)\n    T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width  # x translation (pixels)\n    T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height  # y translation (pixels)\n\n    # Combined rotation matrix\n    M = T @ S @ R @ P @ C  # order of operations (right to left) is IMPORTANT\n    if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any():  # image changed\n        if perspective:\n            im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))\n        else:  # affine\n            im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))\n\n    # Visualize\n    # import matplotlib.pyplot as plt\n    # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()\n    # ax[0].imshow(im[:, :, ::-1])  # base\n    # ax[1].imshow(im2[:, :, ::-1])  # warped\n\n    # Transform label coordinates\n    n = len(targets)\n    if n:\n        use_segments = any(x.any() for x in segments)\n        new = np.zeros((n, 4))\n        if use_segments:  # warp segments\n            segments = resample_segments(segments)  # upsample\n            for i, segment in enumerate(segments):\n                xy = np.ones((len(segment), 3))\n                xy[:, :2] = segment\n                xy = xy @ M.T  # transform\n                xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]  # perspective rescale or affine\n\n                # Clip\n                new[i] = segment2box(xy, width, height)\n\n        else:  # warp boxes\n            xy = np.ones((n * 4, 3))\n            xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2)  # x1y1, x2y2, x1y2, x2y1\n            xy = xy @ M.T  # transform\n            xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8)  # perspective rescale or affine\n\n            # Create new boxes\n            x = xy[:, [0, 2, 4, 6]]\n            y = xy[:, [1, 3, 5, 7]]\n            new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T\n\n            # Clip\n            new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)\n            new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)\n\n        # Filter candidates\n        i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)\n        targets = targets[i]\n        targets[:, 1:5] = new[i]\n\n    return im, targets\n\n\ndef copy_paste(im, labels, segments, p=0.5):\n    \"\"\"Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy).\"\"\"\n    n = len(segments)\n    if p and n:\n        h, w, c = im.shape  # height, width, channels\n        im_new = np.zeros(im.shape, np.uint8)\n\n        # Calculate ioa first then select indexes randomly\n        boxes = np.stack([w - labels[:, 3], labels[:, 2], w - labels[:, 1], labels[:, 4]], axis=-1)  # (n, 4)\n        ioa = bbox_ioa(boxes, labels[:, 1:5])  # intersection over area\n        indexes = np.nonzero((ioa < 0.30).all(1))[0]  # (N, )\n        n = len(indexes)\n        for j in random.sample(list(indexes), k=round(p * n)):\n            l, box, s = labels[j], boxes[j], segments[j]\n            labels = np.concatenate((labels, [[l[0], *box]]), 0)\n            segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))\n            cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (1, 1, 1), cv2.FILLED)\n\n        result = cv2.flip(im, 1)  # augment segments (flip left-right)\n        i = cv2.flip(im_new, 1).astype(bool)\n        im[i] = result[i]  # cv2.imwrite('debug.jpg', im)  # debug\n\n    return im, labels, segments\n\n\ndef cutout(im, labels, p=0.5):\n    \"\"\"Applies image cutout augmentation https://arxiv.org/abs/1708.04552.\"\"\"\n    if random.random() < p:\n        h, w = im.shape[:2]\n        scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16  # image size fraction\n        for s in scales:\n            mask_h = random.randint(1, int(h * s))  # create random masks\n            mask_w = random.randint(1, int(w * s))\n\n            # Box\n            xmin = max(0, random.randint(0, w) - mask_w // 2)\n            ymin = max(0, random.randint(0, h) - mask_h // 2)\n            xmax = min(w, xmin + mask_w)\n            ymax = min(h, ymin + mask_h)\n\n            # Apply random color mask\n            im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]\n\n            # Return unobscured labels\n            if len(labels) and s > 0.03:\n                box = np.array([[xmin, ymin, xmax, ymax]], dtype=np.float32)\n                ioa = bbox_ioa(box, xywhn2xyxy(labels[:, 1:5], w, h))[0]  # intersection over area\n                labels = labels[ioa < 0.60]  # remove >60% obscured labels\n\n    return labels\n\n\ndef mixup(im, labels, im2, labels2):\n    \"\"\"Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf.\"\"\"\n    r = np.random.beta(32.0, 32.0)  # mixup ratio, alpha=beta=32.0\n    im = (im * r + im2 * (1 - r)).astype(np.uint8)\n    labels = np.concatenate((labels, labels2), 0)\n    return im, labels\n\n\ndef box_candidates(box1, box2, wh_thr=2, ar_thr=100, area_thr=0.1, eps=1e-16):  # box1(4,n), box2(4,n)\n    # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio\n    w1, h1 = box1[2] - box1[0], box1[3] - box1[1]\n    w2, h2 = box2[2] - box2[0], box2[3] - box2[1]\n    ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps))  # aspect ratio\n    return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr)  # candidates\n\n\ndef classify_albumentations(\n        augment=True,\n        size=224,\n        scale=(0.08, 1.0),\n        ratio=(0.75, 1.0 / 0.75),  # 0.75, 1.33\n        hflip=0.5,\n        vflip=0.0,\n        jitter=0.4,\n        mean=IMAGENET_MEAN,\n        std=IMAGENET_STD,\n        auto_aug=False):\n    # YOLOv5 classification Albumentations (optional, only used if package is installed)\n    prefix = colorstr('albumentations: ')\n    try:\n        import albumentations as A\n        from albumentations.pytorch import ToTensorV2\n        check_version(A.__version__, '1.0.3', hard=True)  # version requirement\n        if augment:  # Resize and crop\n            T = [A.RandomResizedCrop(height=size, width=size, scale=scale, ratio=ratio)]\n            if auto_aug:\n                # TODO: implement AugMix, AutoAug & RandAug in albumentation\n                LOGGER.info(f'{prefix}auto augmentations are currently not supported')\n            else:\n                if hflip > 0:\n                    T += [A.HorizontalFlip(p=hflip)]\n                if vflip > 0:\n                    T += [A.VerticalFlip(p=vflip)]\n                if jitter > 0:\n                    jitter = float(jitter)\n                    T += [A.ColorJitter(jitter, jitter, jitter, 0)]  # brightness, contrast, satuaration, 0 hue\n        else:  # Use fixed crop for eval set (reproducibility)\n            T = [A.SmallestMaxSize(max_size=size), A.CenterCrop(height=size, width=size)]\n        T += [A.Normalize(mean=mean, std=std), ToTensorV2()]  # Normalize and convert to Tensor\n        LOGGER.info(prefix + ', '.join(f'{x}'.replace('always_apply=False, ', '') for x in T if x.p))\n        return A.Compose(T)\n\n    except ImportError:  # package not installed, skip\n        LOGGER.warning(f'{prefix}⚠️ not found, install with `pip install albumentations` (recommended)')\n    except Exception as e:\n        LOGGER.info(f'{prefix}{e}')\n\n\ndef classify_transforms(size=224):\n    \"\"\"Transforms to apply if albumentations not installed.\"\"\"\n    assert isinstance(size, int), f'ERROR: classify_transforms size {size} must be integer, not (list, tuple)'\n    # T.Compose([T.ToTensor(), T.Resize(size), T.CenterCrop(size), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])\n    return T.Compose([CenterCrop(size), ToTensor(), T.Normalize(IMAGENET_MEAN, IMAGENET_STD)])\n\n\nclass LetterBox:\n    # YOLOv5 LetterBox class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])\n    def __init__(self, size=(640, 640), auto=False, stride=32):\n        \"\"\"Resizes and crops an image to a specified size for YOLOv5 preprocessing.\"\"\"\n        super().__init__()\n        self.h, self.w = (size, size) if isinstance(size, int) else size\n        self.auto = auto  # pass max size integer, automatically solve for short side using stride\n        self.stride = stride  # used with auto\n\n    def __call__(self, im):  # im = np.array HWC\n        imh, imw = im.shape[:2]\n        r = min(self.h / imh, self.w / imw)  # ratio of new/old\n        h, w = round(imh * r), round(imw * r)  # resized image\n        hs, ws = (math.ceil(x / self.stride) * self.stride for x in (h, w)) if self.auto else self.h, self.w\n        top, left = round((hs - h) / 2 - 0.1), round((ws - w) / 2 - 0.1)\n        im_out = np.full((self.h, self.w, 3), 114, dtype=im.dtype)\n        im_out[top:top + h, left:left + w] = cv2.resize(im, (w, h), interpolation=cv2.INTER_LINEAR)\n        return im_out\n\n\nclass CenterCrop:\n    # YOLOv5 CenterCrop class for image preprocessing, i.e. T.Compose([CenterCrop(size), ToTensor()])\n    def __init__(self, size=640):\n        \"\"\"Converts input image into tensor for YOLOv5 processing.\"\"\"\n        super().__init__()\n        self.h, self.w = (size, size) if isinstance(size, int) else size\n\n    def __call__(self, im):  # im = np.array HWC\n        imh, imw = im.shape[:2]\n        m = min(imh, imw)  # min dimension\n        top, left = (imh - m) // 2, (imw - m) // 2\n        return cv2.resize(im[top:top + m, left:left + m], (self.w, self.h), interpolation=cv2.INTER_LINEAR)\n\n\nclass ToTensor:\n    # YOLOv5 ToTensor class for image preprocessing, i.e. T.Compose([LetterBox(size), ToTensor()])\n    def __init__(self, half=False):\n        \"\"\"Initialize ToTensor class for YOLOv5 image preprocessing.\"\"\"\n        super().__init__()\n        self.half = half\n\n    def __call__(self, im):  # im = np.array HWC in BGR order\n        im = np.ascontiguousarray(im.transpose((2, 0, 1))[::-1])  # HWC to CHW -> BGR to RGB -> contiguous\n        im = torch.from_numpy(im)  # to torch\n        im = im.half() if self.half else im.float()  # uint8 to fp16/32\n        im /= 255.0  # 0-255 to 0.0-1.0\n        return im\n"
  },
  {
    "path": "ultralytics/yolo/data/dataloaders/v5loader.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nDataloaders and dataset utils\n\"\"\"\n\nimport contextlib\nimport glob\nimport hashlib\nimport math\nimport os\nimport random\nimport shutil\nimport time\nfrom itertools import repeat\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\nfrom threading import Thread\nfrom urllib.parse import urlparse\n\nimport cv2\nimport numpy as np\nimport psutil\nimport torch\nimport torchvision\nfrom PIL import ExifTags, Image, ImageOps\nfrom torch.utils.data import DataLoader, Dataset, dataloader, distributed\nfrom tqdm import tqdm\n\nfrom ultralytics.yolo.utils import (DATASETS_DIR, LOGGER, NUM_THREADS, TQDM_BAR_FORMAT, is_colab, is_dir_writeable,\n                                    is_kaggle)\nfrom ultralytics.yolo.utils.checks import check_requirements\nfrom ultralytics.yolo.utils.ops import clean_str, segments2boxes, xyn2xy, xywh2xyxy, xywhn2xyxy, xyxy2xywhn\nfrom ultralytics.yolo.utils.torch_utils import torch_distributed_zero_first\n\nfrom .v5augmentations import (Albumentations, augment_hsv, classify_albumentations, classify_transforms, copy_paste,\n                              letterbox, mixup, random_perspective)\n\n# Parameters\nHELP_URL = 'See https://docs.ultralytics.com/yolov5/tutorials/train_custom_data'\nIMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp', 'pfm'  # include image suffixes\nVID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv'  # include video suffixes\nLOCAL_RANK = int(os.getenv('LOCAL_RANK', -1))  # https://pytorch.org/docs/stable/elastic/run.html\nRANK = int(os.getenv('RANK', -1))\nPIN_MEMORY = str(os.getenv('PIN_MEMORY', True)).lower() == 'true'  # global pin_memory for dataloaders\n\n# Get orientation exif tag\nfor orientation in ExifTags.TAGS.keys():\n    if ExifTags.TAGS[orientation] == 'Orientation':\n        break\n\n\ndef get_hash(paths):\n    \"\"\"Returns a single hash value of a list of paths (files or dirs).\"\"\"\n    size = sum(os.path.getsize(p) for p in paths if os.path.exists(p))  # sizes\n    h = hashlib.sha256(str(size).encode())  # hash sizes\n    h.update(''.join(paths).encode())  # hash paths\n    return h.hexdigest()  # return hash\n\n\ndef exif_size(img):\n    \"\"\"Returns exif-corrected PIL size.\"\"\"\n    s = img.size  # (width, height)\n    with contextlib.suppress(Exception):\n        rotation = dict(img._getexif().items())[orientation]\n        if rotation in [6, 8]:  # rotation 270 or 90\n            s = (s[1], s[0])\n    return s\n\n\ndef exif_transpose(image):\n    \"\"\"\n    Transpose a PIL image accordingly if it has an EXIF Orientation tag.\n    Inplace version of https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py exif_transpose()\n\n    :param image: The image to transpose.\n    :return: An image.\n    \"\"\"\n    exif = image.getexif()\n    orientation = exif.get(0x0112, 1)  # default 1\n    if orientation > 1:\n        method = {\n            2: Image.FLIP_LEFT_RIGHT,\n            3: Image.ROTATE_180,\n            4: Image.FLIP_TOP_BOTTOM,\n            5: Image.TRANSPOSE,\n            6: Image.ROTATE_270,\n            7: Image.TRANSVERSE,\n            8: Image.ROTATE_90}.get(orientation)\n        if method is not None:\n            image = image.transpose(method)\n            del exif[0x0112]\n            image.info['exif'] = exif.tobytes()\n    return image\n\n\ndef seed_worker(worker_id):\n    \"\"\"Set dataloader worker seed https://pytorch.org/docs/stable/notes/randomness.html#dataloader.\"\"\"\n    worker_seed = torch.initial_seed() % 2 ** 32\n    np.random.seed(worker_seed)\n    random.seed(worker_seed)\n\n\ndef create_dataloader(path,\n                      imgsz,\n                      batch_size,\n                      stride,\n                      single_cls=False,\n                      hyp=None,\n                      augment=False,\n                      cache=False,\n                      pad=0.0,\n                      rect=False,\n                      rank=-1,\n                      workers=8,\n                      image_weights=False,\n                      close_mosaic=False,\n                      min_items=0,\n                      prefix='',\n                      shuffle=False,\n                      seed=0,):\n    if rect and shuffle:\n        LOGGER.warning('WARNING ⚠️ --rect is incompatible with DataLoader shuffle, setting shuffle=False')\n        shuffle = False\n    with torch_distributed_zero_first(rank):  # init dataset *.cache only once if DDP\n        dataset = LoadImagesAndLabels(\n            path,\n            imgsz,\n            batch_size,\n            augment=augment,  # augmentation\n            hyp=hyp,  # hyperparameters\n            rect=rect,  # rectangular batches\n            cache_images=cache,\n            single_cls=single_cls,\n            stride=int(stride),\n            pad=pad,\n            image_weights=image_weights,\n            min_items=min_items,\n            prefix=prefix)\n\n    batch_size = min(batch_size, len(dataset))\n    nd = torch.cuda.device_count()  # number of CUDA devices\n    nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers])  # number of workers\n    sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)\n    loader = DataLoader if image_weights or close_mosaic else InfiniteDataLoader  # DataLoader allows attribute updates\n    generator = torch.Generator()\n    generator.manual_seed(6148914691236517205 + seed + RANK)\n    return loader(dataset,\n                  batch_size=batch_size,\n                  shuffle=shuffle and sampler is None,\n                  num_workers=nw,\n                  sampler=sampler,\n                  pin_memory=PIN_MEMORY,\n                  collate_fn=LoadImagesAndLabels.collate_fn,\n                  worker_init_fn=seed_worker,\n                  generator=generator), dataset\n\n\n\nclass InfiniteDataLoader(dataloader.DataLoader):\n    \"\"\"Dataloader that reuses workers\n\n    Uses same syntax as vanilla DataLoader\n    \"\"\"\n\n    def __init__(self, *args, **kwargs):\n        \"\"\"Dataloader that reuses workers for same syntax as vanilla DataLoader.\"\"\"\n        super().__init__(*args, **kwargs)\n        object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))\n        self.iterator = super().__iter__()\n\n    def __len__(self):\n        \"\"\"Returns the length of batch_sampler's sampler.\"\"\"\n        return len(self.batch_sampler.sampler)\n\n    def __iter__(self):\n        \"\"\"Creates a sampler that infinitely repeats.\"\"\"\n        for _ in range(len(self)):\n            yield next(self.iterator)\n\n\nclass _RepeatSampler:\n    \"\"\"Sampler that repeats forever\n\n    Args:\n        sampler (Dataset.sampler): The sampler to repeat.\n    \"\"\"\n\n    def __init__(self, sampler):\n        \"\"\"Sampler that repeats dataset samples infinitely.\"\"\"\n        self.sampler = sampler\n\n    def __iter__(self):\n        \"\"\"Infinite loop iterating over a given sampler.\"\"\"\n        while True:\n            yield from iter(self.sampler)\n\n\nclass LoadScreenshots:\n    # YOLOv5 screenshot dataloader, i.e. `python detect.py --source \"screen 0 100 100 512 256\"`\n    def __init__(self, source, img_size=640, stride=32, auto=True, transforms=None):\n        \"\"\"source = [screen_number left top width height] (pixels).\"\"\"\n        check_requirements('mss')\n        import mss\n\n        source, *params = source.split()\n        self.screen, left, top, width, height = 0, None, None, None, None  # default to full screen 0\n        if len(params) == 1:\n            self.screen = int(params[0])\n        elif len(params) == 4:\n            left, top, width, height = (int(x) for x in params)\n        elif len(params) == 5:\n            self.screen, left, top, width, height = (int(x) for x in params)\n        self.img_size = img_size\n        self.stride = stride\n        self.transforms = transforms\n        self.auto = auto\n        self.mode = 'stream'\n        self.frame = 0\n        self.sct = mss.mss()\n\n        # Parse monitor shape\n        monitor = self.sct.monitors[self.screen]\n        self.top = monitor['top'] if top is None else (monitor['top'] + top)\n        self.left = monitor['left'] if left is None else (monitor['left'] + left)\n        self.width = width or monitor['width']\n        self.height = height or monitor['height']\n        self.monitor = {'left': self.left, 'top': self.top, 'width': self.width, 'height': self.height}\n\n    def __iter__(self):\n        \"\"\"Iterates over objects with the same structure as the monitor attribute.\"\"\"\n        return self\n\n    def __next__(self):\n        \"\"\"mss screen capture: get raw pixels from the screen as np array.\"\"\"\n        im0 = np.array(self.sct.grab(self.monitor))[:, :, :3]  # [:, :, :3] BGRA to BGR\n        s = f'screen {self.screen} (LTWH): {self.left},{self.top},{self.width},{self.height}: '\n\n        if self.transforms:\n            im = self.transforms(im0)  # transforms\n        else:\n            im = letterbox(im0, self.img_size, stride=self.stride, auto=self.auto)[0]  # padded resize\n            im = im.transpose((2, 0, 1))[::-1]  # HWC to CHW, BGR to RGB\n            im = np.ascontiguousarray(im)  # contiguous\n        self.frame += 1\n        return str(self.screen), im, im0, None, s  # screen, img, original img, im0s, s\n\n\nclass LoadImages:\n    # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4`\n    def __init__(self, path, img_size=640, stride=32, auto=True, transforms=None, vid_stride=1):\n        \"\"\"Initialize instance variables and check for valid input.\"\"\"\n        if isinstance(path, str) and Path(path).suffix == '.txt':  # *.txt file with img/vid/dir on each line\n            path = Path(path).read_text().rsplit()\n        files = []\n        for p in sorted(path) if isinstance(path, (list, tuple)) else [path]:\n            p = str(Path(p).resolve())\n            if '*' in p:\n                files.extend(sorted(glob.glob(p, recursive=True)))  # glob\n            elif os.path.isdir(p):\n                files.extend(sorted(glob.glob(os.path.join(p, '*.*'))))  # dir\n            elif os.path.isfile(p):\n                files.append(p)  # files\n            else:\n                raise FileNotFoundError(f'{p} does not exist')\n\n        images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]\n        videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]\n        ni, nv = len(images), len(videos)\n\n        self.img_size = img_size\n        self.stride = stride\n        self.files = images + videos\n        self.nf = ni + nv  # number of files\n        self.video_flag = [False] * ni + [True] * nv\n        self.mode = 'image'\n        self.auto = auto\n        self.transforms = transforms  # optional\n        self.vid_stride = vid_stride  # video frame-rate stride\n        if any(videos):\n            self._new_video(videos[0])  # new video\n        else:\n            self.cap = None\n        assert self.nf > 0, f'No images or videos found in {p}. ' \\\n                            f'Supported formats are:\\nimages: {IMG_FORMATS}\\nvideos: {VID_FORMATS}'\n\n    def __iter__(self):\n        \"\"\"Returns an iterator object for iterating over images or videos found in a directory.\"\"\"\n        self.count = 0\n        return self\n\n    def __next__(self):\n        \"\"\"Iterator's next item, performs transformation on image and returns path, transformed image, original image, capture and size.\"\"\"\n        if self.count == self.nf:\n            raise StopIteration\n        path = self.files[self.count]\n\n        if self.video_flag[self.count]:\n            # Read video\n            self.mode = 'video'\n            for _ in range(self.vid_stride):\n                self.cap.grab()\n            ret_val, im0 = self.cap.retrieve()\n            while not ret_val:\n                self.count += 1\n                self.cap.release()\n                if self.count == self.nf:  # last video\n                    raise StopIteration\n                path = self.files[self.count]\n                self._new_video(path)\n                ret_val, im0 = self.cap.read()\n\n            self.frame += 1\n            # im0 = self._cv2_rotate(im0)  # for use if cv2 autorotation is False\n            s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: '\n\n        else:\n            # Read image\n            self.count += 1\n            im0 = cv2.imread(path)  # BGR\n            assert im0 is not None, f'Image Not Found {path}'\n            s = f'image {self.count}/{self.nf} {path}: '\n\n        if self.transforms:\n            im = self.transforms(im0)  # transforms\n        else:\n            im = letterbox(im0, self.img_size, stride=self.stride, auto=self.auto)[0]  # padded resize\n            im = im.transpose((2, 0, 1))[::-1]  # HWC to CHW, BGR to RGB\n            im = np.ascontiguousarray(im)  # contiguous\n\n        return path, im, im0, self.cap, s\n\n    def _new_video(self, path):\n        \"\"\"Create a new video capture object.\"\"\"\n        self.frame = 0\n        self.cap = cv2.VideoCapture(path)\n        self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT) / self.vid_stride)\n        self.orientation = int(self.cap.get(cv2.CAP_PROP_ORIENTATION_META))  # rotation degrees\n        # self.cap.set(cv2.CAP_PROP_ORIENTATION_AUTO, 0)  # disable https://github.com/ultralytics/yolov5/issues/8493\n\n    def _cv2_rotate(self, im):\n        \"\"\"Rotate a cv2 video manually.\"\"\"\n        if self.orientation == 0:\n            return cv2.rotate(im, cv2.ROTATE_90_CLOCKWISE)\n        elif self.orientation == 180:\n            return cv2.rotate(im, cv2.ROTATE_90_COUNTERCLOCKWISE)\n        elif self.orientation == 90:\n            return cv2.rotate(im, cv2.ROTATE_180)\n        return im\n\n    def __len__(self):\n        \"\"\"Returns the number of files in the class instance.\"\"\"\n        return self.nf  # number of files\n\n\nclass LoadStreams:\n    # YOLOv5 streamloader, i.e. `python detect.py --source 'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP streams`\n    def __init__(self, sources='file.streams', img_size=640, stride=32, auto=True, transforms=None, vid_stride=1):\n        \"\"\"Initialize YOLO detector with optional transforms and check input shapes.\"\"\"\n        torch.backends.cudnn.benchmark = True  # faster for fixed-size inference\n        self.mode = 'stream'\n        self.img_size = img_size\n        self.stride = stride\n        self.vid_stride = vid_stride  # video frame-rate stride\n        sources = Path(sources).read_text().rsplit() if os.path.isfile(sources) else [sources]\n        n = len(sources)\n        self.sources = [clean_str(x) for x in sources]  # clean source names for later\n        self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n\n        for i, s in enumerate(sources):  # index, source\n            # Start thread to read frames from video stream\n            st = f'{i + 1}/{n}: {s}... '\n            if urlparse(s).hostname in ('www.youtube.com', 'youtube.com', 'youtu.be'):  # if source is YouTube video\n                # YouTube format i.e. 'https://www.youtube.com/watch?v=Zgi9g1ksQHc' or 'https://youtu.be/Zgi9g1ksQHc'\n                check_requirements(('pafy', 'youtube_dl==2020.12.2'))\n                import pafy\n                s = pafy.new(s).getbest(preftype='mp4').url  # YouTube URL\n            s = eval(s) if s.isnumeric() else s  # i.e. s = '0' local webcam\n            if s == 0:\n                assert not is_colab(), '--source 0 webcam unsupported on Colab. Rerun command in a local environment.'\n                assert not is_kaggle(), '--source 0 webcam unsupported on Kaggle. Rerun command in a local environment.'\n            cap = cv2.VideoCapture(s)\n            assert cap.isOpened(), f'{st}Failed to open {s}'\n            w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n            h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n            fps = cap.get(cv2.CAP_PROP_FPS)  # warning: may return 0 or nan\n            self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf')  # infinite stream fallback\n            self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30  # 30 FPS fallback\n\n            _, self.imgs[i] = cap.read()  # guarantee first frame\n            self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True)\n            LOGGER.info(f'{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)')\n            self.threads[i].start()\n        LOGGER.info('')  # newline\n\n        # Check for common shapes\n        s = np.stack([letterbox(x, img_size, stride=stride, auto=auto)[0].shape for x in self.imgs])\n        self.rect = np.unique(s, axis=0).shape[0] == 1  # rect inference if all shapes equal\n        self.auto = auto and self.rect\n        self.transforms = transforms  # optional\n        if not self.rect:\n            LOGGER.warning('WARNING ⚠️ Stream shapes differ. For optimal performance supply similarly-shaped streams.')\n\n    def update(self, i, cap, stream):\n        \"\"\"Read stream `i` frames in daemon thread.\"\"\"\n        n, f = 0, self.frames[i]  # frame number, frame array\n        while cap.isOpened() and n < f:\n            n += 1\n            cap.grab()  # .read() = .grab() followed by .retrieve()\n            if n % self.vid_stride == 0:\n                success, im = cap.retrieve()\n                if success:\n                    self.imgs[i] = im\n                else:\n                    LOGGER.warning('WARNING ⚠️ Video stream unresponsive, please check your IP camera connection.')\n                    self.imgs[i] = np.zeros_like(self.imgs[i])\n                    cap.open(stream)  # re-open stream if signal was lost\n            time.sleep(0.0)  # wait time\n\n    def __iter__(self):\n        \"\"\"Iterator that returns the class instance.\"\"\"\n        self.count = -1\n        return self\n\n    def __next__(self):\n        \"\"\"Return a tuple containing transformed and resized image data.\"\"\"\n        self.count += 1\n        if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'):  # q to quit\n            cv2.destroyAllWindows()\n            raise StopIteration\n\n        im0 = self.imgs.copy()\n        if self.transforms:\n            im = np.stack([self.transforms(x) for x in im0])  # transforms\n        else:\n            im = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0] for x in im0])  # resize\n            im = im[..., ::-1].transpose((0, 3, 1, 2))  # BGR to RGB, BHWC to BCHW\n            im = np.ascontiguousarray(im)  # contiguous\n\n        return self.sources, im, im0, None, ''\n\n    def __len__(self):\n        \"\"\"Returns the number of sources as the length of the object.\"\"\"\n        return len(self.sources)  # 1E12 frames = 32 streams at 30 FPS for 30 years\n\n\ndef img2label_paths(img_paths):\n    \"\"\"Define label paths as a function of image paths.\"\"\"\n    sa, sb = f'{os.sep}images{os.sep}', f'{os.sep}labels{os.sep}'  # /images/, /labels/ substrings\n    return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]\n\n\nclass LoadImagesAndLabels(Dataset):\n    \"\"\"YOLOv5 train_loader/val_loader, loads images and labels for training and validation.\"\"\"\n    cache_version = 0.6  # dataset labels *.cache version\n    rand_interp_methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]\n\n    def __init__(self,\n                 path,\n                 img_size=640,\n                 batch_size=16,\n                 augment=False,\n                 hyp=None,\n                 rect=False,\n                 image_weights=False,\n                 cache_images=False,\n                 single_cls=False,\n                 stride=32,\n                 pad=0.0,\n                 min_items=0,\n                 prefix=''):\n        self.img_size = img_size\n        self.augment = augment\n        self.hyp = hyp\n        self.image_weights = image_weights\n        self.rect = False if image_weights else rect\n        self.mosaic = self.augment and not self.rect  # load 4 images at a time into a mosaic (only during training)\n        self.mosaic_border = [-img_size // 2, -img_size // 2]\n        self.stride = stride\n        self.path = path\n        self.albumentations = Albumentations(size=img_size) if augment else None\n\n        try:\n            f = []  # image files\n            for p in path if isinstance(path, list) else [path]:\n                p = Path(p)  # os-agnostic\n                if p.is_dir():  # dir\n                    f += glob.glob(str(p / '**' / '*.*'), recursive=True)\n                    # f = list(p.rglob('*.*'))  # pathlib\n                elif p.is_file():  # file\n                    with open(p) as t:\n                        t = t.read().strip().splitlines()\n                        parent = str(p.parent) + os.sep\n                        f += [x.replace('./', parent, 1) if x.startswith('./') else x for x in t]  # to global path\n                        # f += [p.parent / x.lstrip(os.sep) for x in t]  # to global path (pathlib)\n                else:\n                    raise FileNotFoundError(f'{prefix}{p} does not exist')\n            self.im_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS)\n            # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS])  # pathlib\n            assert self.im_files, f'{prefix}No images found'\n        except Exception as e:\n            raise FileNotFoundError(f'{prefix}Error loading data from {path}: {e}\\n{HELP_URL}') from e\n\n        # Check cache\n        self.label_files = img2label_paths(self.im_files)  # labels\n        cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache')\n        try:\n            cache, exists = np.load(cache_path, allow_pickle=True).item(), True  # load dict\n            assert cache['version'] == self.cache_version  # matches current version\n            assert cache['hash'] == get_hash(self.label_files + self.im_files)  # identical hash\n        except (FileNotFoundError, AssertionError, AttributeError):\n            cache, exists = self.cache_labels(cache_path, prefix), False  # run cache ops\n\n        # Display cache\n        nf, nm, ne, nc, n = cache.pop('results')  # found, missing, empty, corrupt, total\n        if exists and LOCAL_RANK in (-1, 0):\n            d = f'Scanning {cache_path}... {nf} images, {nm + ne} backgrounds, {nc} corrupt'\n            tqdm(None, desc=prefix + d, total=n, initial=n, bar_format=TQDM_BAR_FORMAT)  # display cache results\n            if cache['msgs']:\n                LOGGER.info('\\n'.join(cache['msgs']))  # display warnings\n        assert nf > 0 or not augment, f'{prefix}No labels found in {cache_path}, can not start training. {HELP_URL}'\n\n        # Read cache\n        [cache.pop(k) for k in ('hash', 'version', 'msgs')]  # remove items\n        labels, shapes, self.segments = zip(*cache.values())\n        nl = len(np.concatenate(labels, 0))  # number of labels\n        assert nl > 0 or not augment, f'{prefix}All labels empty in {cache_path}, can not start training. {HELP_URL}'\n        self.labels = list(labels)\n        self.shapes = np.array(shapes)\n        self.im_files = list(cache.keys())  # update\n        self.label_files = img2label_paths(cache.keys())  # update\n\n        # Filter images\n        if min_items:\n            include = np.array([len(x) >= min_items for x in self.labels]).nonzero()[0].astype(int)\n            LOGGER.info(f'{prefix}{n - len(include)}/{n} images filtered from dataset')\n            self.im_files = [self.im_files[i] for i in include]\n            self.label_files = [self.label_files[i] for i in include]\n            self.labels = [self.labels[i] for i in include]\n            self.segments = [self.segments[i] for i in include]\n            self.shapes = self.shapes[include]  # wh\n\n        # Create indices\n        n = len(self.shapes)  # number of images\n        bi = np.floor(np.arange(n) / batch_size).astype(int)  # batch index\n        nb = bi[-1] + 1  # number of batches\n        self.batch = bi  # batch index of image\n        self.n = n\n        self.indices = range(n)\n\n        # Update labels\n        include_class = []  # filter labels to include only these classes (optional)\n        include_class_array = np.array(include_class).reshape(1, -1)\n        for i, (label, segment) in enumerate(zip(self.labels, self.segments)):\n            if include_class:\n                j = (label[:, 0:1] == include_class_array).any(1)\n                self.labels[i] = label[j]\n                if segment:\n                    self.segments[i] = [segment[si] for si, idx in enumerate(j) if idx]\n            if single_cls:  # single-class training, merge all classes into 0\n                self.labels[i][:, 0] = 0\n\n        # Rectangular Training\n        if self.rect:\n            # Sort by aspect ratio\n            s = self.shapes  # wh\n            ar = s[:, 1] / s[:, 0]  # aspect ratio\n            irect = ar.argsort()\n            self.im_files = [self.im_files[i] for i in irect]\n            self.label_files = [self.label_files[i] for i in irect]\n            self.labels = [self.labels[i] for i in irect]\n            self.segments = [self.segments[i] for i in irect]\n            self.shapes = s[irect]  # wh\n            ar = ar[irect]\n\n            # Set training image shapes\n            shapes = [[1, 1]] * nb\n            for i in range(nb):\n                ari = ar[bi == i]\n                mini, maxi = ari.min(), ari.max()\n                if maxi < 1:\n                    shapes[i] = [maxi, 1]\n                elif mini > 1:\n                    shapes[i] = [1, 1 / mini]\n\n            self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(int) * stride\n\n        # Cache images into RAM/disk for faster training\n        if cache_images == 'ram' and not self.check_cache_ram(prefix=prefix):\n            cache_images = False\n        self.ims = [None] * n\n        self.npy_files = [Path(f).with_suffix('.npy') for f in self.im_files]\n        if cache_images:\n            b, gb = 0, 1 << 30  # bytes of cached images, bytes per gigabytes\n            self.im_hw0, self.im_hw = [None] * n, [None] * n\n            fcn = self.cache_images_to_disk if cache_images == 'disk' else self.load_image\n            with ThreadPool(NUM_THREADS) as pool:\n                results = pool.imap(fcn, range(n))\n                pbar = tqdm(enumerate(results), total=n, bar_format=TQDM_BAR_FORMAT, disable=LOCAL_RANK > 0)\n                for i, x in pbar:\n                    if cache_images == 'disk':\n                        b += self.npy_files[i].stat().st_size\n                    else:  # 'ram'\n                        self.ims[i], self.im_hw0[i], self.im_hw[i] = x  # im, hw_orig, hw_resized = load_image(self, i)\n                        b += self.ims[i].nbytes\n                    pbar.desc = f'{prefix}Caching images ({b / gb:.1f}GB {cache_images})'\n                pbar.close()\n\n    def check_cache_ram(self, safety_margin=0.1, prefix=''):\n        \"\"\"Check image caching requirements vs available memory.\"\"\"\n        b, gb = 0, 1 << 30  # bytes of cached images, bytes per gigabytes\n        n = min(self.n, 30)  # extrapolate from 30 random images\n        for _ in range(n):\n            im = cv2.imread(random.choice(self.im_files))  # sample image\n            ratio = self.img_size / max(im.shape[0], im.shape[1])  # max(h, w)  # ratio\n            b += im.nbytes * ratio ** 2\n        mem_required = b * self.n / n  # GB required to cache dataset into RAM\n        mem = psutil.virtual_memory()\n        cache = mem_required * (1 + safety_margin) < mem.available  # to cache or not to cache, that is the question\n        if not cache:\n            LOGGER.info(f'{prefix}{mem_required / gb:.1f}GB RAM required, '\n                        f'{mem.available / gb:.1f}/{mem.total / gb:.1f}GB available, '\n                        f\"{'caching images ✅' if cache else 'not caching images ⚠️'}\")\n        return cache\n\n    def cache_labels(self, path=Path('./labels.cache'), prefix=''):\n        \"\"\"Cache labels and save as numpy file for next time.\"\"\"\n        # Cache dataset labels, check images and read shapes\n        if path.exists():\n            path.unlink()  # remove *.cache file if exists\n        x = {}  # dict\n        nm, nf, ne, nc, msgs = 0, 0, 0, 0, []  # number missing, found, empty, corrupt, messages\n        desc = f'{prefix}Scanning {path.parent / path.stem}...'\n        total = len(self.im_files)\n        with ThreadPool(NUM_THREADS) as pool:\n            results = pool.imap(verify_image_label, zip(self.im_files, self.label_files, repeat(prefix)))\n            pbar = tqdm(results, desc=desc, total=total, bar_format=TQDM_BAR_FORMAT)\n            for im_file, lb, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:\n                nm += nm_f\n                nf += nf_f\n                ne += ne_f\n                nc += nc_f\n                if im_file:\n                    x[im_file] = [lb, shape, segments]\n                if msg:\n                    msgs.append(msg)\n                pbar.desc = f'{desc} {nf} images, {nm + ne} backgrounds, {nc} corrupt'\n            pbar.close()\n\n        if msgs:\n            LOGGER.info('\\n'.join(msgs))\n        if nf == 0:\n            LOGGER.warning(f'{prefix}WARNING ⚠️ No labels found in {path}. {HELP_URL}')\n        x['hash'] = get_hash(self.label_files + self.im_files)\n        x['results'] = nf, nm, ne, nc, len(self.im_files)\n        x['msgs'] = msgs  # warnings\n        x['version'] = self.cache_version  # cache version\n        if is_dir_writeable(path.parent):\n            np.save(str(path), x)  # save cache for next time\n            path.with_suffix('.cache.npy').rename(path)  # remove .npy suffix\n            LOGGER.info(f'{prefix}New cache created: {path}')\n        else:\n            LOGGER.warning(f'{prefix}WARNING ⚠️ Cache directory {path.parent} is not writeable')  # not writeable\n        return x\n\n    def __len__(self):\n        \"\"\"Returns the length of 'im_files' attribute.\"\"\"\n        return len(self.im_files)\n\n    def __getitem__(self, index):\n        \"\"\"Get a sample and its corresponding label, filename and shape from the dataset.\"\"\"\n        index = self.indices[index]  # linear, shuffled, or image_weights\n\n        hyp = self.hyp\n        mosaic = self.mosaic and random.random() < hyp['mosaic']\n        if mosaic:\n            # Load mosaic\n            img, labels = self.load_mosaic(index)\n            shapes = None\n\n            # MixUp augmentation\n            if random.random() < hyp['mixup']:\n                img, labels = mixup(img, labels, *self.load_mosaic(random.randint(0, self.n - 1)))\n\n        else:\n            # Load image\n            img, (h0, w0), (h, w) = self.load_image(index)\n\n            # Letterbox\n            shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size  # final letterboxed shape\n            img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)\n            shapes = (h0, w0), ((h / h0, w / w0), pad)  # for COCO mAP rescaling\n\n            labels = self.labels[index].copy()\n            if labels.size:  # normalized xywh to pixel xyxy format\n                labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])\n\n            if self.augment:\n                img, labels = random_perspective(img,\n                                                 labels,\n                                                 degrees=hyp['degrees'],\n                                                 translate=hyp['translate'],\n                                                 scale=hyp['scale'],\n                                                 shear=hyp['shear'],\n                                                 perspective=hyp['perspective'])\n\n        nl = len(labels)  # number of labels\n        if nl:\n            labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3)\n\n        if self.augment:\n            # Albumentations\n            img, labels = self.albumentations(img, labels)\n            nl = len(labels)  # update after albumentations\n\n            # HSV color-space\n            augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])\n\n            # Flip up-down\n            if random.random() < hyp['flipud']:\n                img = np.flipud(img)\n                if nl:\n                    labels[:, 2] = 1 - labels[:, 2]\n\n            # Flip left-right\n            if random.random() < hyp['fliplr']:\n                img = np.fliplr(img)\n                if nl:\n                    labels[:, 1] = 1 - labels[:, 1]\n\n            # Cutouts\n            # labels = cutout(img, labels, p=0.5)\n            # nl = len(labels)  # update after cutout\n\n        labels_out = torch.zeros((nl, 6))\n        if nl:\n            labels_out[:, 1:] = torch.from_numpy(labels)\n\n        # Convert\n        img = img.transpose((2, 0, 1))[::-1]  # HWC to CHW, BGR to RGB\n        img = np.ascontiguousarray(img)\n\n        return torch.from_numpy(img), labels_out, self.im_files[index], shapes\n\n    def load_image(self, i):\n        \"\"\"Loads 1 image from dataset index 'i', returns (im, original hw, resized hw).\"\"\"\n        im, f, fn = self.ims[i], self.im_files[i], self.npy_files[i],\n        if im is None:  # not cached in RAM\n            if fn.exists():  # load npy\n                im = np.load(fn)\n            else:  # read image\n                im = cv2.imread(f)  # BGR\n                assert im is not None, f'Image Not Found {f}'\n            h0, w0 = im.shape[:2]  # orig hw\n            r = self.img_size / max(h0, w0)  # ratio\n            if r != 1:  # if sizes are not equal\n                interp = cv2.INTER_LINEAR if (self.augment or r > 1) else cv2.INTER_AREA\n                im = cv2.resize(im, (math.ceil(w0 * r), math.ceil(h0 * r)), interpolation=interp)\n            return im, (h0, w0), im.shape[:2]  # im, hw_original, hw_resized\n        return self.ims[i], self.im_hw0[i], self.im_hw[i]  # im, hw_original, hw_resized\n\n    def cache_images_to_disk(self, i):\n        \"\"\"Saves an image as an *.npy file for faster loading.\"\"\"\n        f = self.npy_files[i]\n        if not f.exists():\n            np.save(f.as_posix(), cv2.imread(self.im_files[i]))\n\n    def load_mosaic(self, index):\n        \"\"\"YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic.\"\"\"\n        labels4, segments4 = [], []\n        s = self.img_size\n        yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border)  # mosaic center x, y\n        indices = [index] + random.choices(self.indices, k=3)  # 3 additional image indices\n        random.shuffle(indices)\n        for i, index in enumerate(indices):\n            # Load image\n            img, _, (h, w) = self.load_image(index)\n\n            # Place img in img4\n            if i == 0:  # top left\n                img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8)  # base image with 4 tiles\n                x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc  # xmin, ymin, xmax, ymax (large image)\n                x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h  # xmin, ymin, xmax, ymax (small image)\n            elif i == 1:  # top right\n                x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc\n                x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h\n            elif i == 2:  # bottom left\n                x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)\n                x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)\n            elif i == 3:  # bottom right\n                x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)\n                x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)\n\n            img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b]  # img4[ymin:ymax, xmin:xmax]\n            padw = x1a - x1b\n            padh = y1a - y1b\n\n            # Labels\n            labels, segments = self.labels[index].copy(), self.segments[index].copy()\n            if labels.size:\n                labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh)  # normalized xywh to pixel xyxy format\n                segments = [xyn2xy(x, w, h, padw, padh) for x in segments]\n            labels4.append(labels)\n            segments4.extend(segments)\n\n        # Concat/clip labels\n        labels4 = np.concatenate(labels4, 0)\n        for x in (labels4[:, 1:], *segments4):\n            np.clip(x, 0, 2 * s, out=x)  # clip when using random_perspective()\n        # img4, labels4 = replicate(img4, labels4)  # replicate\n\n        # Augment\n        img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste'])\n        img4, labels4 = random_perspective(img4,\n                                           labels4,\n                                           segments4,\n                                           degrees=self.hyp['degrees'],\n                                           translate=self.hyp['translate'],\n                                           scale=self.hyp['scale'],\n                                           shear=self.hyp['shear'],\n                                           perspective=self.hyp['perspective'],\n                                           border=self.mosaic_border)  # border to remove\n\n        return img4, labels4\n\n    def load_mosaic9(self, index):\n        \"\"\"YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic.\"\"\"\n        labels9, segments9 = [], []\n        s = self.img_size\n        indices = [index] + random.choices(self.indices, k=8)  # 8 additional image indices\n        random.shuffle(indices)\n        hp, wp = -1, -1  # height, width previous\n        for i, index in enumerate(indices):\n            # Load image\n            img, _, (h, w) = self.load_image(index)\n\n            # Place img in img9\n            if i == 0:  # center\n                img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8)  # base image with 4 tiles\n                h0, w0 = h, w\n                c = s, s, s + w, s + h  # xmin, ymin, xmax, ymax (base) coordinates\n            elif i == 1:  # top\n                c = s, s - h, s + w, s\n            elif i == 2:  # top right\n                c = s + wp, s - h, s + wp + w, s\n            elif i == 3:  # right\n                c = s + w0, s, s + w0 + w, s + h\n            elif i == 4:  # bottom right\n                c = s + w0, s + hp, s + w0 + w, s + hp + h\n            elif i == 5:  # bottom\n                c = s + w0 - w, s + h0, s + w0, s + h0 + h\n            elif i == 6:  # bottom left\n                c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h\n            elif i == 7:  # left\n                c = s - w, s + h0 - h, s, s + h0\n            elif i == 8:  # top left\n                c = s - w, s + h0 - hp - h, s, s + h0 - hp\n\n            padx, pady = c[:2]\n            x1, y1, x2, y2 = (max(x, 0) for x in c)  # allocate coords\n\n            # Labels\n            labels, segments = self.labels[index].copy(), self.segments[index].copy()\n            if labels.size:\n                labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady)  # normalized xywh to pixel xyxy format\n                segments = [xyn2xy(x, w, h, padx, pady) for x in segments]\n            labels9.append(labels)\n            segments9.extend(segments)\n\n            # Image\n            img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:]  # img9[ymin:ymax, xmin:xmax]\n            hp, wp = h, w  # height, width previous\n\n        # Offset\n        yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border)  # mosaic center x, y\n        img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]\n\n        # Concat/clip labels\n        labels9 = np.concatenate(labels9, 0)\n        labels9[:, [1, 3]] -= xc\n        labels9[:, [2, 4]] -= yc\n        c = np.array([xc, yc])  # centers\n        segments9 = [x - c for x in segments9]\n\n        for x in (labels9[:, 1:], *segments9):\n            np.clip(x, 0, 2 * s, out=x)  # clip when using random_perspective()\n        # img9, labels9 = replicate(img9, labels9)  # replicate\n\n        # Augment\n        img9, labels9, segments9 = copy_paste(img9, labels9, segments9, p=self.hyp['copy_paste'])\n        img9, labels9 = random_perspective(img9,\n                                           labels9,\n                                           segments9,\n                                           degrees=self.hyp['degrees'],\n                                           translate=self.hyp['translate'],\n                                           scale=self.hyp['scale'],\n                                           shear=self.hyp['shear'],\n                                           perspective=self.hyp['perspective'],\n                                           border=self.mosaic_border)  # border to remove\n\n        return img9, labels9\n\n    @staticmethod\n    def collate_fn(batch):\n        \"\"\"YOLOv8 collate function, outputs dict.\"\"\"\n        im, label, path, shapes = zip(*batch)  # transposed\n        for i, lb in enumerate(label):\n            lb[:, 0] = i  # add target image index for build_targets()\n        batch_idx, cls, bboxes = torch.cat(label, 0).split((1, 1, 4), dim=1)\n        return {\n            'ori_shape': tuple((x[0] if x else None) for x in shapes),\n            'ratio_pad': tuple((x[1] if x else None) for x in shapes),\n            'im_file': path,\n            'img': torch.stack(im, 0),\n            'cls': cls,\n            'bboxes': bboxes,\n            'batch_idx': batch_idx.view(-1)}\n\n    @staticmethod\n    def collate_fn_old(batch):\n        \"\"\"YOLOv5 original collate function.\"\"\"\n        im, label, path, shapes = zip(*batch)  # transposed\n        for i, lb in enumerate(label):\n            lb[:, 0] = i  # add target image index for build_targets()\n        return torch.stack(im, 0), torch.cat(label, 0), path, shapes\n\n\n# Ancillary functions --------------------------------------------------------------------------------------------------\ndef flatten_recursive(path=DATASETS_DIR / 'coco128'):\n    \"\"\"Flatten a recursive directory by bringing all files to top level.\"\"\"\n    new_path = Path(f'{str(path)}_flat')\n    if os.path.exists(new_path):\n        shutil.rmtree(new_path)  # delete output folder\n    os.makedirs(new_path)  # make new output folder\n    for file in tqdm(glob.glob(f'{str(Path(path))}/**/*.*', recursive=True)):\n        shutil.copyfile(file, new_path / Path(file).name)\n\n\ndef extract_boxes(path=DATASETS_DIR / 'coco128'):  # from utils.dataloaders import *; extract_boxes()\n    # Convert detection dataset into classification dataset, with one directory per class\n    path = Path(path)  # images dir\n    shutil.rmtree(path / 'classification') if (path / 'classification').is_dir() else None  # remove existing\n    files = list(path.rglob('*.*'))\n    n = len(files)  # number of files\n    for im_file in tqdm(files, total=n):\n        if im_file.suffix[1:] in IMG_FORMATS:\n            # Image\n            im = cv2.imread(str(im_file))[..., ::-1]  # BGR to RGB\n            h, w = im.shape[:2]\n\n            # Labels\n            lb_file = Path(img2label_paths([str(im_file)])[0])\n            if Path(lb_file).exists():\n                with open(lb_file) as f:\n                    lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32)  # labels\n\n                for j, x in enumerate(lb):\n                    c = int(x[0])  # class\n                    f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg'  # new filename\n                    if not f.parent.is_dir():\n                        f.parent.mkdir(parents=True)\n\n                    b = x[1:] * [w, h, w, h]  # box\n                    # B[2:] = b[2:].max()  # rectangle to square\n                    b[2:] = b[2:] * 1.2 + 3  # pad\n                    b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(int)\n\n                    b[[0, 2]] = np.clip(b[[0, 2]], 0, w)  # clip boxes outside of image\n                    b[[1, 3]] = np.clip(b[[1, 3]], 0, h)\n                    assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'\n\n\ndef autosplit(path=DATASETS_DIR / 'coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False):\n    \"\"\"Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files\n    Usage: from utils.dataloaders import *; autosplit()\n    Arguments\n        path:            Path to images directory\n        weights:         Train, val, test weights (list, tuple)\n        annotated_only:  Only use images with an annotated txt file\n    \"\"\"\n    path = Path(path)  # images dir\n    files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS)  # image files only\n    n = len(files)  # number of files\n    random.seed(0)  # for reproducibility\n    indices = random.choices([0, 1, 2], weights=weights, k=n)  # assign each image to a split\n\n    txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt']  # 3 txt files\n    for x in txt:\n        if (path.parent / x).exists():\n            (path.parent / x).unlink()  # remove existing\n\n    print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)\n    for i, img in tqdm(zip(indices, files), total=n):\n        if not annotated_only or Path(img2label_paths([str(img)])[0]).exists():  # check label\n            with open(path.parent / txt[i], 'a') as f:\n                f.write(f'./{img.relative_to(path.parent).as_posix()}' + '\\n')  # add image to txt file\n\n\ndef verify_image_label(args):\n    \"\"\"Verify one image-label pair.\"\"\"\n    im_file, lb_file, prefix = args\n    nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', []  # number (missing, found, empty, corrupt), message, segments\n    try:\n        # Verify images\n        im = Image.open(im_file)\n        im.verify()  # PIL verify\n        shape = exif_size(im)  # image size\n        assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'\n        assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}'\n        if im.format.lower() in ('jpg', 'jpeg'):\n            with open(im_file, 'rb') as f:\n                f.seek(-2, 2)\n                if f.read() != b'\\xff\\xd9':  # corrupt JPEG\n                    ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100)\n                    msg = f'{prefix}WARNING ⚠️ {im_file}: corrupt JPEG restored and saved'\n\n        # Verify labels\n        if os.path.isfile(lb_file):\n            nf = 1  # label found\n            with open(lb_file) as f:\n                lb = [x.split() for x in f.read().strip().splitlines() if len(x)]\n                if any(len(x) > 6 for x in lb):  # is segment\n                    classes = np.array([x[0] for x in lb], dtype=np.float32)\n                    segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb]  # (cls, xy1...)\n                    lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1)  # (cls, xywh)\n                lb = np.array(lb, dtype=np.float32)\n            nl = len(lb)\n            if nl:\n                assert lb.shape[1] == 5, f'labels require 5 columns, {lb.shape[1]} columns detected'\n                assert (lb >= 0).all(), f'negative label values {lb[lb < 0]}'\n                assert (lb[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}'\n                _, i = np.unique(lb, axis=0, return_index=True)\n                if len(i) < nl:  # duplicate row check\n                    lb = lb[i]  # remove duplicates\n                    if segments:\n                        segments = [segments[x] for x in i]\n                    msg = f'{prefix}WARNING ⚠️ {im_file}: {nl - len(i)} duplicate labels removed'\n            else:\n                ne = 1  # label empty\n                lb = np.zeros((0, 5), dtype=np.float32)\n        else:\n            nm = 1  # label missing\n            lb = np.zeros((0, 5), dtype=np.float32)\n        return im_file, lb, shape, segments, nm, nf, ne, nc, msg\n    except Exception as e:\n        nc = 1\n        msg = f'{prefix}WARNING ⚠️ {im_file}: ignoring corrupt image/label: {e}'\n        return [None, None, None, None, nm, nf, ne, nc, msg]\n\n\n# Classification dataloaders -------------------------------------------------------------------------------------------\nclass ClassificationDataset(torchvision.datasets.ImageFolder):\n    \"\"\"\n    YOLOv5 Classification Dataset.\n    Arguments\n        root:  Dataset path\n        transform:  torchvision transforms, used by default\n        album_transform: Albumentations transforms, used if installed\n    \"\"\"\n\n    def __init__(self, root, augment, imgsz, cache=False):\n        \"\"\"Initialize YOLO dataset with root, augmentation, image size, and cache parameters.\"\"\"\n        super().__init__(root=root)\n        self.torch_transforms = classify_transforms(imgsz)\n        self.album_transforms = classify_albumentations(augment, imgsz) if augment else None\n        self.cache_ram = cache is True or cache == 'ram'\n        self.cache_disk = cache == 'disk'\n        self.samples = [list(x) + [Path(x[0]).with_suffix('.npy'), None] for x in self.samples]  # file, index, npy, im\n\n    def __getitem__(self, i):\n        \"\"\"Retrieves data items of 'dataset' via indices & creates InfiniteDataLoader.\"\"\"\n        f, j, fn, im = self.samples[i]  # filename, index, filename.with_suffix('.npy'), image\n        if self.cache_ram and im is None:\n            im = self.samples[i][3] = cv2.imread(f)\n        elif self.cache_disk:\n            if not fn.exists():  # load npy\n                np.save(fn.as_posix(), cv2.imread(f))\n            im = np.load(fn)\n        else:  # read image\n            im = cv2.imread(f)  # BGR\n        if self.album_transforms:\n            sample = self.album_transforms(image=cv2.cvtColor(im, cv2.COLOR_BGR2RGB))['image']\n        else:\n            sample = self.torch_transforms(im)\n        return sample, j\n\n\ndef create_classification_dataloader(path,\n                                     imgsz=224,\n                                     batch_size=16,\n                                     augment=True,\n                                     cache=False,\n                                     rank=-1,\n                                     workers=8,\n                                     shuffle=True):\n    \"\"\"Returns Dataloader object to be used with YOLOv5 Classifier.\"\"\"\n    with torch_distributed_zero_first(rank):  # init dataset *.cache only once if DDP\n        dataset = ClassificationDataset(root=path, imgsz=imgsz, augment=augment, cache=cache)\n    batch_size = min(batch_size, len(dataset))\n    nd = torch.cuda.device_count()\n    nw = min([os.cpu_count() // max(nd, 1), batch_size if batch_size > 1 else 0, workers])\n    sampler = None if rank == -1 else distributed.DistributedSampler(dataset, shuffle=shuffle)\n    generator = torch.Generator()\n    generator.manual_seed(6148914691236517205 + RANK)\n    return InfiniteDataLoader(dataset,\n                              batch_size=batch_size,\n                              shuffle=shuffle and sampler is None,\n                              num_workers=nw,\n                              sampler=sampler,\n                              pin_memory=PIN_MEMORY,\n                              worker_init_fn=seed_worker,\n                              generator=generator)  # or DataLoader(persistent_workers=True)\n"
  },
  {
    "path": "ultralytics/yolo/data/dataset.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom itertools import repeat\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport torch\nimport torchvision\nfrom tqdm import tqdm\n\nfrom ..utils import LOCAL_RANK, NUM_THREADS, TQDM_BAR_FORMAT, is_dir_writeable\nfrom .augment import Compose, Format, Instances, LetterBox, classify_albumentations, classify_transforms, v8_transforms\nfrom .base import BaseDataset\nfrom .utils import HELP_URL, LOGGER, get_hash, img2label_paths, verify_image_label, multi_img2label_paths\n\n\nclass YOLODataset(BaseDataset):\n    \"\"\"\n    Dataset class for loading object detection and/or segmentation labels in YOLO format.\n\n    Args:\n        data (dict, optional): A dataset YAML dictionary. Defaults to None.\n        use_segments (bool, optional): If True, segmentation masks are used as labels. Defaults to False.\n        use_keypoints (bool, optional): If True, keypoints are used as labels. Defaults to False.\n\n    Returns:\n        (torch.utils.data.Dataset): A PyTorch dataset object that can be used for training an object detection model.\n    \"\"\"\n    cache_version = '1.0.2'  # dataset labels *.cache version, >= 1.0.0 for YOLOv8\n    rand_interp_methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]\n\n    def __init__(self, *args, data=None, task_type=False, use_segments=False, use_keypoints=False, **kwargs):\n        self.task_type = task_type\n        self.use_segments = use_segments\n        self.use_keypoints = use_keypoints\n        self.data = data\n        assert not (self.use_segments and self.use_keypoints), 'Can not use both segments and keypoints.'\n        super().__init__(*args, **kwargs)\n    def cache_labels(self, path=Path('./labels.cache')):\n        \"\"\"Cache dataset labels, check images and read shapes.\n        Args:\n            path (Path): path where to save the cache file (default: Path('./labels.cache')).\n        Returns:\n            (dict): labels.\n        \"\"\"\n        x = {'labels': []}\n        nm, nf, ne, nc, msgs = 0, 0, 0, 0, []  # number missing, found, empty, corrupt, messages\n        desc = f'{self.prefix}Scanning {path.parent / path.stem}...'\n        total = len(self.im_files)\n        nkpt, ndim = self.data.get('kpt_shape', (0, 0))\n        if self.use_keypoints and (nkpt <= 0 or ndim not in (2, 3)):\n            raise ValueError(\"'kpt_shape' in data.yaml missing or incorrect. Should be a list with [number of \"\n                             \"keypoints, number of dims (2 for x,y or 3 for x,y,visible)], i.e. 'kpt_shape: [17, 3]'\")\n        with ThreadPool(NUM_THREADS) as pool:\n            results = pool.imap(func=verify_image_label,\n                                iterable=zip(self.im_files, self.label_files, repeat(self.prefix),\n                                             repeat(self.use_keypoints), repeat(len(self.data['names'])), repeat(nkpt),\n                                             repeat(ndim)))\n            pbar = tqdm(results, desc=desc, total=total, bar_format=TQDM_BAR_FORMAT)\n            for im_file, lb, shape, segments, keypoint, nm_f, nf_f, ne_f, nc_f, msg in pbar:\n                nm += nm_f\n                nf += nf_f\n                ne += ne_f\n                nc += nc_f\n                if im_file:\n                    x['labels'].append(\n                        dict(\n                            im_file=im_file,\n                            shape=shape,\n                            cls=lb[:, 0:1],  # n, 1\n                            bboxes=lb[:, 1:],  # n, 4\n                            segments=segments,\n                            keypoints=keypoint,\n                            normalized=True,\n                            bbox_format='xywh'))\n                if msg:\n                    msgs.append(msg)\n                pbar.desc = f'{desc} {nf} images, {nm + ne} backgrounds, {nc} corrupt'\n            pbar.close()\n\n        if msgs:\n            LOGGER.info('\\n'.join(msgs))\n        if nf == 0:\n            LOGGER.warning(f'{self.prefix}WARNING ⚠️ No labels found in {path}. {HELP_URL}')\n        x['hash'] = get_hash(self.label_files + self.im_files)\n        x['results'] = nf, nm, ne, nc, len(self.im_files)\n        x['msgs'] = msgs  # warnings\n        x['version'] = self.cache_version  # cache version\n        if is_dir_writeable(path.parent):\n            if path.exists():\n                path.unlink()  # remove *.cache file if exists\n            np.save(str(path), x)  # save cache for next time\n            path.with_suffix('.cache.npy').rename(path)  # remove .npy suffix\n            LOGGER.info(f'{self.prefix}New cache created: {path}')\n        else:\n            LOGGER.warning(f'{self.prefix}WARNING ⚠️ Cache directory {path.parent} is not writeable, cache not saved.')\n        return x\n\n    def get_labels(self):\n        \"\"\"Returns dictionary of labels for YOLO training.\"\"\"\n        self.label_files = img2label_paths(self.im_files)\n        cache_path = Path(self.label_files[0]).parent.with_suffix('.cache')\n        try:\n            import gc\n            gc.disable()  # reduce pickle load time https://github.com/ultralytics/ultralytics/pull/1585\n            cache, exists = np.load(str(cache_path), allow_pickle=True).item(), True  # load dict\n            gc.enable()\n            assert cache['version'] == self.cache_version  # matches current version\n            assert cache['hash'] == get_hash(self.label_files + self.im_files)  # identical hash\n        except (FileNotFoundError, AssertionError, AttributeError):\n            cache, exists = self.cache_labels(cache_path), False  # run cache ops\n\n        # Display cache\n        nf, nm, ne, nc, n = cache.pop('results')  # found, missing, empty, corrupt, total\n        if exists and LOCAL_RANK in (-1, 0):\n            d = f'Scanning {cache_path}... {nf} images, {nm + ne} backgrounds, {nc} corrupt'\n            tqdm(None, desc=self.prefix + d, total=n, initial=n, bar_format=TQDM_BAR_FORMAT)  # display cache results\n            if cache['msgs']:\n                LOGGER.info('\\n'.join(cache['msgs']))  # display warnings\n        if nf == 0:  # number of labels found\n            raise FileNotFoundError(f'{self.prefix}No labels found in {cache_path}, can not start training. {HELP_URL}')\n\n        # Read cache\n        [cache.pop(k) for k in ('hash', 'version', 'msgs')]  # remove items\n        labels = cache['labels']\n        self.im_files = [lb['im_file'] for lb in labels]  # update im_files\n\n        # Check if the dataset is all boxes or all segments\n        lengths = ((len(lb['cls']), len(lb['bboxes']), len(lb['segments'])) for lb in labels)\n        len_cls, len_boxes, len_segments = (sum(x) for x in zip(*lengths))\n        if len_segments and len_boxes != len_segments:\n            LOGGER.warning(\n                f'WARNING ⚠️ Box and segment counts should be equal, but got len(segments) = {len_segments}, '\n                f'len(boxes) = {len_boxes}. To resolve this only boxes will be used and all segments will be removed. '\n                'To avoid this please supply either a detect or segment dataset, not a detect-segment mixed dataset.')\n            for lb in labels:\n                lb['segments'] = []\n        if len_cls == 0:\n            raise ValueError(f'All labels empty in {cache_path}, can not start training without labels. {HELP_URL}')\n        return labels\n\n    def get_multi_labels(self):\n        \"\"\"Returns dictionary of labels for YOLO training.\"\"\"\n        label_list = []\n        label_files = []\n        for task_name in self.data['labels_list']:\n            self.label_files = multi_img2label_paths(self.im_files,task_name)\n            label_files.append(self.label_files)\n            cache_path = Path(self.label_files[0]).parent.with_suffix('.cache')\n            try:\n                import gc\n                gc.disable()  # reduce pickle load time https://github.com/ultralytics/ultralytics/pull/1585\n                cache, exists = np.load(str(cache_path), allow_pickle=True).item(), True  # load dict\n                gc.enable()\n                assert cache['version'] == self.cache_version  # matches current version\n                assert cache['hash'] == get_hash(self.label_files + self.im_files)  # identical hash\n            except (FileNotFoundError, AssertionError, AttributeError):\n                cache, exists = self.cache_labels(cache_path), False  # run cache ops\n\n            # Display cache\n            nf, nm, ne, nc, n = cache.pop('results')  # found, missing, empty, corrupt, total\n            if exists and LOCAL_RANK in (-1, 0):\n                d = f'Scanning {cache_path}... {nf} images, {nm + ne} backgrounds, {nc} corrupt'\n                tqdm(None, desc=self.prefix + d, total=n, initial=n, bar_format=TQDM_BAR_FORMAT)  # display cache results\n                if cache['msgs']:\n                    LOGGER.info('\\n'.join(cache['msgs']))  # display warnings\n            if nf == 0:  # number of labels found\n                raise FileNotFoundError(f'{self.prefix}No labels found in {cache_path}, can not start training. {HELP_URL}')\n\n            # Read cache\n            [cache.pop(k) for k in ('hash', 'version', 'msgs')]  # remove items\n            labels = cache['labels']\n            self.im_files = [lb['im_file'] for lb in labels]  # update im_files\n\n            # Check if the dataset is all boxes or all segments\n            lengths = ((len(lb['cls']), len(lb['bboxes']), len(lb['segments'])) for lb in labels)\n            len_cls, len_boxes, len_segments = (sum(x) for x in zip(*lengths))\n            if len_segments and len_boxes != len_segments:\n                LOGGER.warning(\n                    f'WARNING ⚠️ Box and segment counts should be equal, but got len(segments) = {len_segments}, '\n                    f'len(boxes) = {len_boxes}. To resolve this only boxes will be used and all segments will be removed. '\n                    'To avoid this please supply either a detect or segment dataset, not a detect-segment mixed dataset.')\n                for lb in labels:\n                    lb['segments'] = []\n            if len_cls == 0:\n                raise ValueError(f'All labels empty in {cache_path}, can not start training without labels. {HELP_URL}')\n            label_list.append(labels)\n\n        self.label_files = label_files\n        return label_list\n\n    # TODO: use hyp config to set all these augmentations\n    def build_transforms(self, hyp=None):\n        \"\"\"Builds and appends transforms to the list.\"\"\"\n        if self.augment:\n            hyp.mosaic = hyp.mosaic if self.augment and not self.rect else 0.0\n            hyp.mixup = hyp.mixup if self.augment and not self.rect else 0.0\n            transforms = v8_transforms(self, self.imgsz, hyp)\n        else:\n            transforms = Compose([LetterBox(new_shape=(self.imgsz, self.imgsz), scaleup=False)])\n        transforms.append(\n            Format(bbox_format='xywh',\n                   normalize=True,\n                   return_mask=self.use_segments,\n                   return_keypoint=self.use_keypoints,\n                   batch_idx=True,\n                   mask_ratio=hyp.mask_ratio,\n                   mask_overlap=hyp.overlap_mask,\n                   labels_name=self.data['labels_list']))\n        return transforms\n\n    def build_seg_transforms(self, hyp=None):\n        \"\"\"Builds and appends transforms to the list.\"\"\"\n        if self.augment:\n            hyp.mosaic = hyp.mosaic if self.augment and not self.rect else 0.0\n            hyp.mixup = hyp.mixup if self.augment and not self.rect else 0.0\n            transforms = v8_transforms(self, self.imgsz, hyp)\n        else:\n            transforms = Compose([LetterBox(new_shape=(self.imgsz, self.imgsz), scaleup=False)])\n        transforms.append(\n            Format(bbox_format='xywh',\n                   normalize=True,\n                   return_mask=True,\n                   return_keypoint=self.use_keypoints,\n                   batch_idx=True,\n                   mask_ratio=hyp.mask_ratio,\n                   mask_overlap=hyp.overlap_mask))\n        return transforms\n\n\n    def close_mosaic(self, hyp):\n        \"\"\"Sets mosaic, copy_paste and mixup options to 0.0 and builds transformations.\"\"\"\n        hyp.mosaic = 0.0  # set mosaic ratio=0.0\n        hyp.copy_paste = 0.0  # keep the same behavior as previous v8 close-mosaic\n        hyp.mixup = 0.0  # keep the same behavior as previous v8 close-mosaic\n        self.transforms = self.build_transforms(hyp)\n\n    def update_labels_info(self, label):\n        \"\"\"custom your label format here.\"\"\"\n        # NOTE: cls is not with bboxes now, classification and semantic segmentation need an independent cls label\n        # we can make it also support classification and semantic segmentation by add or remove some dict keys there.\n        bboxes = label.pop('bboxes')\n        segments = label.pop('segments')\n        keypoints = label.pop('keypoints', None)\n        bbox_format = label.pop('bbox_format')\n        normalized = label.pop('normalized')\n        label['instances'] = Instances(bboxes, segments, keypoints, bbox_format=bbox_format, normalized=normalized)\n        return label\n\n    @staticmethod\n    def collate_fn(batch):\n        \"\"\"Collates data samples into batches.\"\"\"\n        new_batch = {}\n        new_batch_list = []\n        ############Jiayuan\n        if isinstance(batch[0], list):  ## judgement is multi or single task.\n            values_list = [list(zip(*[list(b[i].values()) for b in batch])) for i in range(len(batch[0]))]\n            key_list = [batch[0][count].keys() for count in range(len(batch[0]))]\n\n\n            # values = list(zip(*[list(b.values()) for b in batch]))\n            # keys = batch[0].keys()\n            for count, keys in enumerate(key_list):\n                new_batch = {}\n                for i, k in enumerate(keys):\n                    value = values_list[count][i]\n                    if k == 'img':\n                        value = torch.stack(value, 0)\n                    if k in ['masks', 'keypoints', 'bboxes', 'cls']:\n                        value = torch.cat(value, 0)\n                    new_batch[k] = value\n                new_batch['batch_idx'] = list(new_batch['batch_idx'])\n                for i in range(len(new_batch['batch_idx'])):\n                    new_batch['batch_idx'][i] += i  # add target image index for build_targets()\n                new_batch['batch_idx'] = torch.cat(new_batch['batch_idx'], 0)\n\n                new_batch_list.append(new_batch)\n            return new_batch_list\n        ############\n        else:\n            keys = batch[0].keys()\n            values = list(zip(*[list(b.values()) for b in batch]))\n            for i, k in enumerate(keys):\n                value = values[i]\n                if k == 'img':\n                    value = torch.stack(value, 0)\n                if k in ['masks', 'keypoints', 'bboxes', 'cls']:\n                    value = torch.cat(value, 0)\n                new_batch[k] = value\n            new_batch['batch_idx'] = list(new_batch['batch_idx'])\n            for i in range(len(new_batch['batch_idx'])):\n                new_batch['batch_idx'][i] += i  # add target image index for build_targets()\n            new_batch['batch_idx'] = torch.cat(new_batch['batch_idx'], 0)\n            return new_batch\n\n\n# Classification dataloaders -------------------------------------------------------------------------------------------\nclass ClassificationDataset(torchvision.datasets.ImageFolder):\n    \"\"\"\n    YOLO Classification Dataset.\n\n    Args:\n        root (str): Dataset path.\n        transform (callable, optional): torchvision transforms, used by default.\n        album_transform (callable, optional): Albumentations transforms, used if installed.\n\n    Attributes:\n        cache_ram (bool): True if images should be cached in RAM, False otherwise.\n        cache_disk (bool): True if images should be cached on disk, False otherwise.\n        samples (list): List of samples containing file, index, npy, and im.\n        torch_transforms (callable): torchvision transforms applied to the dataset.\n        album_transforms (callable, optional): Albumentations transforms applied to the dataset if augment is True.\n    \"\"\"\n\n    def __init__(self, root, args, augment=False, cache=False):\n        \"\"\"\n        Initialize YOLO object with root, image size, augmentations, and cache settings.\n\n        Args:\n            root (str): Dataset path.\n            args (Namespace): Argument parser containing dataset related settings.\n            augment (bool, optional): True if dataset should be augmented, False otherwise. Defaults to False.\n            cache (Union[bool, str], optional): Cache setting, can be True, False, 'ram' or 'disk'. Defaults to False.\n        \"\"\"\n        super().__init__(root=root)\n        self.cache_ram = cache is True or cache == 'ram'\n        self.cache_disk = cache == 'disk'\n        self.samples = [list(x) + [Path(x[0]).with_suffix('.npy'), None] for x in self.samples]  # file, index, npy, im\n        self.torch_transforms = classify_transforms(args.imgsz)\n        self.album_transforms = classify_albumentations(\n            augment=augment,\n            size=args.imgsz,\n            scale=(1.0 - args.scale, 1.0),  # (0.08, 1.0)\n            hflip=args.fliplr,\n            vflip=args.flipud,\n            hsv_h=args.hsv_h,  # HSV-Hue augmentation (fraction)\n            hsv_s=args.hsv_s,  # HSV-Saturation augmentation (fraction)\n            hsv_v=args.hsv_v,  # HSV-Value augmentation (fraction)\n            mean=(0.0, 0.0, 0.0),  # IMAGENET_MEAN\n            std=(1.0, 1.0, 1.0),  # IMAGENET_STD\n            auto_aug=False) if augment else None\n\n    def __getitem__(self, i):\n        \"\"\"Returns subset of data and targets corresponding to given indices.\"\"\"\n        f, j, fn, im = self.samples[i]  # filename, index, filename.with_suffix('.npy'), image\n        if self.cache_ram and im is None:\n            im = self.samples[i][3] = cv2.imread(f)\n        elif self.cache_disk:\n            if not fn.exists():  # load npy\n                np.save(fn.as_posix(), cv2.imread(f))\n            im = np.load(fn)\n        else:  # read image\n            im = cv2.imread(f)  # BGR\n        if self.album_transforms:\n            sample = self.album_transforms(image=cv2.cvtColor(im, cv2.COLOR_BGR2RGB))['image']\n        else:\n            sample = self.torch_transforms(im)\n        return {'img': sample, 'cls': j}\n\n    def __len__(self) -> int:\n        return len(self.samples)\n\n\n# TODO: support semantic segmentation\nclass SemanticDataset(BaseDataset):\n\n    def __init__(self):\n        \"\"\"Initialize a SemanticDataset object.\"\"\"\n        pass\n"
  },
  {
    "path": "ultralytics/yolo/data/dataset_wrappers.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport collections\nfrom copy import deepcopy\n\nfrom .augment import LetterBox\n\n\nclass MixAndRectDataset:\n    \"\"\"\n    A dataset class that applies mosaic and mixup transformations as well as rectangular training.\n\n    Attributes:\n        dataset: The base dataset.\n        imgsz: The size of the images in the dataset.\n    \"\"\"\n\n    def __init__(self, dataset):\n        \"\"\"\n        Args:\n            dataset (BaseDataset): The base dataset to apply transformations to.\n        \"\"\"\n        self.dataset = dataset\n        self.imgsz = dataset.imgsz\n\n    def __len__(self):\n        \"\"\"Returns the number of items in the dataset.\"\"\"\n        return len(self.dataset)\n\n    def __getitem__(self, index):\n        \"\"\"\n        Applies mosaic, mixup and rectangular training transformations to an item in the dataset.\n\n        Args:\n            index (int): Index of the item in the dataset.\n\n        Returns:\n            (dict): A dictionary containing the transformed item data.\n        \"\"\"\n        labels = deepcopy(self.dataset[index])\n        for transform in self.dataset.transforms.tolist():\n            # Mosaic and mixup\n            if hasattr(transform, 'get_indexes'):\n                indexes = transform.get_indexes(self.dataset)\n                if not isinstance(indexes, collections.abc.Sequence):\n                    indexes = [indexes]\n                labels['mix_labels'] = [deepcopy(self.dataset[index]) for index in indexes]\n            if self.dataset.rect and isinstance(transform, LetterBox):\n                transform.new_shape = self.dataset.batch_shapes[self.dataset.batch[index]]\n            labels = transform(labels)\n            if 'mix_labels' in labels:\n                labels.pop('mix_labels')\n        return labels\n"
  },
  {
    "path": "ultralytics/yolo/data/scripts/download_weights.sh",
    "content": "#!/bin/bash\n# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Download latest models from https://github.com/ultralytics/assets/releases\n# Example usage: bash ultralytics/yolo/data/scripts/download_weights.sh\n# parent\n# └── weights\n#     ├── yolov8n.pt  ← downloads here\n#     ├── yolov8s.pt\n#     └── ...\n\npython - <<EOF\nfrom ultralytics.yolo.utils.downloads import attempt_download_asset\n\nassets = [f'yolov8{size}{suffix}.pt' for size in 'nsmlx' for suffix in ('', '-cls', '-seg')]\nfor x in assets:\n    attempt_download_asset(f'weights/{x}')\n\nEOF\n"
  },
  {
    "path": "ultralytics/yolo/data/scripts/get_coco.sh",
    "content": "#!/bin/bash\n# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Download COCO 2017 dataset http://cocodataset.org\n# Example usage: bash data/scripts/get_coco.sh\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco  ← downloads here\n\n# Arguments (optional) Usage: bash data/scripts/get_coco.sh --train --val --test --segments\nif [ \"$#\" -gt 0 ]; then\n  for opt in \"$@\"; do\n    case \"${opt}\" in\n    --train) train=true ;;\n    --val) val=true ;;\n    --test) test=true ;;\n    --segments) segments=true ;;\n    --sama) sama=true ;;\n    esac\n  done\nelse\n  train=true\n  val=true\n  test=false\n  segments=false\n  sama=false\nfi\n\n# Download/unzip labels\nd='../datasets' # unzip directory\nurl=https://github.com/ultralytics/yolov5/releases/download/v1.0/\nif [ \"$segments\" == \"true\" ]; then\n  f='coco2017labels-segments.zip' # 169 MB\nelif [ \"$sama\" == \"true\" ]; then\n  f='coco2017labels-segments-sama.zip' # 199 MB https://www.sama.com/sama-coco-dataset/\nelse\n  f='coco2017labels.zip' # 46 MB\nfi\necho 'Downloading' $url$f ' ...'\ncurl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &\n\n# Download/unzip images\nd='../datasets/coco/images' # unzip directory\nurl=http://images.cocodataset.org/zips/\nif [ \"$train\" == \"true\" ]; then\n  f='train2017.zip' # 19G, 118k images\n  echo 'Downloading' $url$f '...'\n  curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &\nfi\nif [ \"$val\" == \"true\" ]; then\n  f='val2017.zip' # 1G, 5k images\n  echo 'Downloading' $url$f '...'\n  curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &\nfi\nif [ \"$test\" == \"true\" ]; then\n  f='test2017.zip' # 7G, 41k images (optional)\n  echo 'Downloading' $url$f '...'\n  curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &\nfi\nwait # finish background tasks\n"
  },
  {
    "path": "ultralytics/yolo/data/scripts/get_coco128.sh",
    "content": "#!/bin/bash\n# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Download COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017)\n# Example usage: bash data/scripts/get_coco128.sh\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── coco128  ← downloads here\n\n# Download/unzip images and labels\nd='../datasets' # unzip directory\nurl=https://github.com/ultralytics/yolov5/releases/download/v1.0/\nf='coco128.zip' # or 'coco128-segments.zip', 68 MB\necho 'Downloading' $url$f ' ...'\ncurl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &\n\nwait # finish background tasks\n"
  },
  {
    "path": "ultralytics/yolo/data/scripts/get_imagenet.sh",
    "content": "#!/bin/bash\n# Ultralytics YOLO 🚀, AGPL-3.0 license\n# Download ILSVRC2012 ImageNet dataset https://image-net.org\n# Example usage: bash data/scripts/get_imagenet.sh\n# parent\n# ├── ultralytics\n# └── datasets\n#     └── imagenet  ← downloads here\n\n# Arguments (optional) Usage: bash data/scripts/get_imagenet.sh --train --val\nif [ \"$#\" -gt 0 ]; then\n  for opt in \"$@\"; do\n    case \"${opt}\" in\n    --train) train=true ;;\n    --val) val=true ;;\n    esac\n  done\nelse\n  train=true\n  val=true\nfi\n\n# Make dir\nd='../datasets/imagenet' # unzip directory\nmkdir -p $d && cd $d\n\n# Download/unzip train\nif [ \"$train\" == \"true\" ]; then\n  wget https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_train.tar # download 138G, 1281167 images\n  mkdir train && mv ILSVRC2012_img_train.tar train/ && cd train\n  tar -xf ILSVRC2012_img_train.tar && rm -f ILSVRC2012_img_train.tar\n  find . -name \"*.tar\" | while read NAME; do\n    mkdir -p \"${NAME%.tar}\"\n    tar -xf \"${NAME}\" -C \"${NAME%.tar}\"\n    rm -f \"${NAME}\"\n  done\n  cd ..\nfi\n\n# Download/unzip val\nif [ \"$val\" == \"true\" ]; then\n  wget https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_val.tar # download 6.3G, 50000 images\n  mkdir val && mv ILSVRC2012_img_val.tar val/ && cd val && tar -xf ILSVRC2012_img_val.tar\n  wget -qO- https://raw.githubusercontent.com/soumith/imagenetloader.torch/master/valprep.sh | bash # move into subdirs\nfi\n\n# Delete corrupted image (optional: PNG under JPEG name that may cause dataloaders to fail)\n# rm train/n04266014/n04266014_10835.JPEG\n\n# TFRecords (optional)\n# wget https://raw.githubusercontent.com/tensorflow/models/master/research/slim/datasets/imagenet_lsvrc_2015_synsets.txt\n"
  },
  {
    "path": "ultralytics/yolo/data/utils.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nimport hashlib\nimport json\nimport os\nimport subprocess\nimport time\nimport zipfile\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\nfrom tarfile import is_tarfile\n\nimport cv2\nimport numpy as np\nfrom PIL import ExifTags, Image, ImageOps\nfrom tqdm import tqdm\n\nfrom ultralytics.nn.autobackend import check_class_names\nfrom ultralytics.yolo.utils import (DATASETS_DIR, LOGGER, NUM_THREADS, ROOT, SETTINGS_YAML, clean_url, colorstr, emojis,\n                                    yaml_load)\nfrom ultralytics.yolo.utils.checks import check_file, check_font, is_ascii\nfrom ultralytics.yolo.utils.downloads import download, safe_download, unzip_file\nfrom ultralytics.yolo.utils.ops import segments2boxes\n\nHELP_URL = 'See https://docs.ultralytics.com/yolov5/tutorials/train_custom_data'\nIMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp', 'pfm'  # image suffixes\nVID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv', 'webm'  # video suffixes\nPIN_MEMORY = str(os.getenv('PIN_MEMORY', True)).lower() == 'true'  # global pin_memory for dataloaders\nIMAGENET_MEAN = 0.485, 0.456, 0.406  # RGB mean\nIMAGENET_STD = 0.229, 0.224, 0.225  # RGB standard deviation\n\n# Get orientation exif tag\nfor orientation in ExifTags.TAGS.keys():\n    if ExifTags.TAGS[orientation] == 'Orientation':\n        break\n\n\ndef img2label_paths(img_paths):\n    \"\"\"Define label paths as a function of image paths.\"\"\"\n    sa, sb = f'{os.sep}images{os.sep}', f'{os.sep}labels{os.sep}'  # /images/, /labels/ substrings\n    return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]\n\ndef multi_img2label_paths(img_paths,task_name):\n    \"\"\"Define label paths as a function of image paths.\"\"\"\n    sa, sb = f'{os.sep}images{os.sep}', f'{os.sep}{task_name}/labels{os.sep}'  # /images/, /labels/ substrings\n    return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths]\n\n\ndef get_hash(paths):\n    \"\"\"Returns a single hash value of a list of paths (files or dirs).\"\"\"\n    size = sum(os.path.getsize(p) for p in paths if os.path.exists(p))  # sizes\n    h = hashlib.sha256(str(size).encode())  # hash sizes\n    h.update(''.join(paths).encode())  # hash paths\n    return h.hexdigest()  # return hash\n\n\ndef exif_size(img):\n    \"\"\"Returns exif-corrected PIL size.\"\"\"\n    s = img.size  # (width, height)\n    with contextlib.suppress(Exception):\n        rotation = dict(img._getexif().items())[orientation]\n        if rotation in [6, 8]:  # rotation 270 or 90\n            s = (s[1], s[0])\n    return s\n\n\ndef verify_image_label(args):\n    \"\"\"Verify one image-label pair.\"\"\"\n    im_file, lb_file, prefix, keypoint, num_cls, nkpt, ndim = args\n    # Number (missing, found, empty, corrupt), message, segments, keypoints\n    nm, nf, ne, nc, msg, segments, keypoints = 0, 0, 0, 0, '', [], None\n    try:\n        # Verify images\n        im = Image.open(im_file)\n        im.verify()  # PIL verify\n        shape = exif_size(im)  # image size\n        shape = (shape[1], shape[0])  # hw\n        assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'\n        assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}'\n        if im.format.lower() in ('jpg', 'jpeg'):\n            with open(im_file, 'rb') as f:\n                f.seek(-2, 2)\n                if f.read() != b'\\xff\\xd9':  # corrupt JPEG\n                    ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100)\n                    msg = f'{prefix}WARNING ⚠️ {im_file}: corrupt JPEG restored and saved'\n\n        # Verify labels\n        if os.path.isfile(lb_file):\n            nf = 1  # label found\n            with open(lb_file) as f:\n                lb = [x.split() for x in f.read().strip().splitlines() if len(x)]\n                if any(len(x) > 6 for x in lb) and (not keypoint):  # is segment\n                    classes = np.array([x[0] for x in lb], dtype=np.float32)\n                    segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in lb]  # (cls, xy1...)\n                    lb = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1)  # (cls, xywh)\n                lb = np.array(lb, dtype=np.float32)\n            nl = len(lb)\n            if nl:\n                if keypoint:\n                    assert lb.shape[1] == (5 + nkpt * ndim), f'labels require {(5 + nkpt * ndim)} columns each'\n                    assert (lb[:, 5::ndim] <= 1).all(), 'non-normalized or out of bounds coordinate labels'\n                    assert (lb[:, 6::ndim] <= 1).all(), 'non-normalized or out of bounds coordinate labels'\n                else:\n                    assert lb.shape[1] == 5, f'labels require 5 columns, {lb.shape[1]} columns detected'\n                    assert (lb[:, 1:] <= 1).all(), \\\n                        f'non-normalized or out of bounds coordinates {lb[:, 1:][lb[:, 1:] > 1]}'\n                    assert (lb >= 0).all(), f'negative label values {lb[lb < 0]}'\n                # All labels\n                max_cls = int(lb[:, 0].max())  # max label count\n                assert max_cls <= num_cls, \\\n                    f'Label class {max_cls} exceeds dataset class count {num_cls}. ' \\\n                    f'Possible class labels are 0-{num_cls - 1}'\n                _, i = np.unique(lb, axis=0, return_index=True)\n                if len(i) < nl:  # duplicate row check\n                    lb = lb[i]  # remove duplicates\n                    if segments:\n                        segments = [segments[x] for x in i]\n                    msg = f'{prefix}WARNING ⚠️ {im_file}: {nl - len(i)} duplicate labels removed'\n            else:\n                ne = 1  # label empty\n                lb = np.zeros((0, (5 + nkpt * ndim)), dtype=np.float32) if keypoint else np.zeros(\n                    (0, 5), dtype=np.float32)\n        else:\n            nm = 1  # label missing\n            lb = np.zeros((0, (5 + nkpt * ndim)), dtype=np.float32) if keypoint else np.zeros((0, 5), dtype=np.float32)\n        if keypoint:\n            keypoints = lb[:, 5:].reshape(-1, nkpt, ndim)\n            if ndim == 2:\n                kpt_mask = np.ones(keypoints.shape[:2], dtype=np.float32)\n                kpt_mask = np.where(keypoints[..., 0] < 0, 0.0, kpt_mask)\n                kpt_mask = np.where(keypoints[..., 1] < 0, 0.0, kpt_mask)\n                keypoints = np.concatenate([keypoints, kpt_mask[..., None]], axis=-1)  # (nl, nkpt, 3)\n        lb = lb[:, :5]\n        return im_file, lb, shape, segments, keypoints, nm, nf, ne, nc, msg\n    except Exception as e:\n        nc = 1\n        msg = f'{prefix}WARNING ⚠️ {im_file}: ignoring corrupt image/label: {e}'\n        return [None, None, None, None, None, nm, nf, ne, nc, msg]\n\n\ndef polygon2mask(imgsz, polygons, color=1, downsample_ratio=1):\n    \"\"\"\n    Args:\n        imgsz (tuple): The image size.\n        polygons (np.ndarray): [N, M], N is the number of polygons, M is the number of points(Be divided by 2).\n        color (int): color\n        downsample_ratio (int): downsample ratio\n    \"\"\"\n    mask = np.zeros(imgsz, dtype=np.uint8)\n    polygons = np.asarray(polygons)\n    polygons = polygons.astype(np.int32)\n    shape = polygons.shape\n    polygons = polygons.reshape(shape[0], -1, 2)\n    cv2.fillPoly(mask, polygons, color=color)\n    nh, nw = (imgsz[0] // downsample_ratio, imgsz[1] // downsample_ratio)\n    # NOTE: fillPoly firstly then resize is trying the keep the same way\n    # of loss calculation when mask-ratio=1.\n    mask = cv2.resize(mask, (nw, nh))\n    return mask\n\n\ndef polygons2masks(imgsz, polygons, color, downsample_ratio=1):\n    \"\"\"\n    Args:\n        imgsz (tuple): The image size.\n        polygons (list[np.ndarray]): each polygon is [N, M], N is number of polygons, M is number of points (M % 2 = 0)\n        color (int): color\n        downsample_ratio (int): downsample ratio\n    \"\"\"\n    masks = []\n    for si in range(len(polygons)):\n        mask = polygon2mask(imgsz, [polygons[si].reshape(-1)], color, downsample_ratio)\n        masks.append(mask)\n    return np.array(masks)\n\n\ndef polygons2masks_overlap(imgsz, segments, downsample_ratio=1):\n    \"\"\"Return a (640, 640) overlap mask.\"\"\"\n    masks = np.zeros((imgsz[0] // downsample_ratio, imgsz[1] // downsample_ratio),\n                     dtype=np.int32 if len(segments) > 255 else np.uint8)\n    areas = []\n    ms = []\n    for si in range(len(segments)):\n        mask = polygon2mask(imgsz, [segments[si].reshape(-1)], downsample_ratio=downsample_ratio, color=1)\n        ms.append(mask)\n        areas.append(mask.sum())\n    areas = np.asarray(areas)\n    index = np.argsort(-areas)\n    ms = np.array(ms)[index]\n    for i in range(len(segments)):\n        mask = ms[i] * (i + 1)\n        masks = masks + mask\n        masks = np.clip(masks, a_min=0, a_max=i + 1)\n    return masks, index\n\n\ndef check_det_dataset(dataset, autodownload=True):\n    \"\"\"Download, check and/or unzip dataset if not found locally.\"\"\"\n    data = check_file(dataset)\n\n    # Download (optional)\n    extract_dir = ''\n    if isinstance(data, (str, Path)) and (zipfile.is_zipfile(data) or is_tarfile(data)):\n        new_dir = safe_download(data, dir=DATASETS_DIR, unzip=True, delete=False, curl=False)\n        data = next((DATASETS_DIR / new_dir).rglob('*.yaml'))\n        extract_dir, autodownload = data.parent, False\n\n    # Read yaml (optional)\n    if isinstance(data, (str, Path)):\n        data = yaml_load(data, append_filename=True)  # dictionary\n\n    # Checks\n    for k in 'train', 'val':\n        if k not in data:\n            raise SyntaxError(\n                emojis(f\"{dataset} '{k}:' key missing ❌.\\n'train' and 'val' are required in all data YAMLs.\"))\n    if 'names' not in data and 'nc' not in data:\n        raise SyntaxError(emojis(f\"{dataset} key missing ❌.\\n either 'names' or 'nc' are required in all data YAMLs.\"))\n    if 'names' in data and 'nc' in data and len(data['names']) != data['nc']:\n        raise SyntaxError(emojis(f\"{dataset} 'names' length {len(data['names'])} and 'nc: {data['nc']}' must match.\"))\n    if 'names' not in data:\n        data['names'] = [f'class_{i}' for i in range(data['nc'])]\n    else:\n        data['nc'] = len(data['names'])\n\n    data['names'] = check_class_names(data['names'])\n\n    # Resolve paths\n    path = Path(extract_dir or data.get('path') or Path(data.get('yaml_file', '')).parent)  # dataset root\n\n    if not path.is_absolute():\n        path = (DATASETS_DIR / path).resolve()\n        data['path'] = path  # download scripts\n    for k in 'train', 'val', 'test':\n        if data.get(k):  # prepend path\n            if isinstance(data[k], str):\n                x = (path / data[k]).resolve()\n                if not x.exists() and data[k].startswith('../'):\n                    x = (path / data[k][3:]).resolve()\n                data[k] = str(x)\n            else:\n                data[k] = [str((path / x).resolve()) for x in data[k]]\n\n    # Parse yaml\n    train, val, test, s = (data.get(x) for x in ('train', 'val', 'test', 'download'))\n    if val:\n        val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])]  # val path\n        if not all(x.exists() for x in val):\n            name = clean_url(dataset)  # dataset name with URL auth stripped\n            m = f\"\\nDataset '{name}' images not found ⚠️, missing paths %s\" % [str(x) for x in val if not x.exists()]\n            if s and autodownload:\n                LOGGER.warning(m)\n            else:\n                m += f\"\\nNote dataset download directory is '{DATASETS_DIR}'. You can update this in '{SETTINGS_YAML}'\"\n                raise FileNotFoundError(m)\n            t = time.time()\n            if s.startswith('http') and s.endswith('.zip'):  # URL\n                safe_download(url=s, dir=DATASETS_DIR, delete=True)\n                r = None  # success\n            elif s.startswith('bash '):  # bash script\n                LOGGER.info(f'Running {s} ...')\n                r = os.system(s)\n            else:  # python script\n                r = exec(s, {'yaml': data})  # return None\n            dt = f'({round(time.time() - t, 1)}s)'\n            s = f\"success ✅ {dt}, saved to {colorstr('bold', DATASETS_DIR)}\" if r in (0, None) else f'failure {dt} ❌'\n            LOGGER.info(f'Dataset download {s}\\n')\n    check_font('Arial.ttf' if is_ascii(data['names']) else 'Arial.Unicode.ttf')  # download fonts\n\n    return data  # dictionary\n\n\ndef check_cls_dataset(dataset: str):\n    \"\"\"\n    Check a classification dataset such as Imagenet.\n\n    This function takes a `dataset` name as input and returns a dictionary containing information about the dataset.\n    If the dataset is not found, it attempts to download the dataset from the internet and save it locally.\n\n    Args:\n        dataset (str): Name of the dataset.\n\n    Returns:\n        data (dict): A dictionary containing the following keys and values:\n            'train': Path object for the directory containing the training set of the dataset\n            'val': Path object for the directory containing the validation set of the dataset\n            'test': Path object for the directory containing the test set of the dataset\n            'nc': Number of classes in the dataset\n            'names': List of class names in the dataset\n    \"\"\"\n    data_dir = (DATASETS_DIR / dataset).resolve()\n    if not data_dir.is_dir():\n        LOGGER.info(f'\\nDataset not found ⚠️, missing path {data_dir}, attempting download...')\n        t = time.time()\n        if dataset == 'imagenet':\n            subprocess.run(f\"bash {ROOT / 'yolo/data/scripts/get_imagenet.sh'}\", shell=True, check=True)\n        else:\n            url = f'https://github.com/ultralytics/yolov5/releases/download/v1.0/{dataset}.zip'\n            download(url, dir=data_dir.parent)\n        s = f\"Dataset download success ✅ ({time.time() - t:.1f}s), saved to {colorstr('bold', data_dir)}\\n\"\n        LOGGER.info(s)\n    train_set = data_dir / 'train'\n    val_set = data_dir / 'val' if (data_dir / 'val').exists() else None  # data/test or data/val\n    test_set = data_dir / 'test' if (data_dir / 'test').exists() else None  # data/val or data/test\n    nc = len([x for x in (data_dir / 'train').glob('*') if x.is_dir()])  # number of classes\n    names = [x.name for x in (data_dir / 'train').iterdir() if x.is_dir()]  # class names list\n    names = dict(enumerate(sorted(names)))\n    return {'train': train_set, 'val': val_set, 'test': test_set, 'nc': nc, 'names': names}\n\n\nclass HUBDatasetStats():\n    \"\"\"\n    Class for generating HUB dataset JSON and `-hub` dataset directory\n\n    Arguments\n        path:           Path to data.yaml or data.zip (with data.yaml inside data.zip)\n        task:           Dataset task. Options are 'detect', 'segment', 'pose', 'classify'.\n        autodownload:   Attempt to download dataset if not found locally\n\n    Usage\n        from ultralytics.yolo.data.utils import HUBDatasetStats\n        stats = HUBDatasetStats('/Users/glennjocher/Downloads/coco8.zip', task='detect')  # detect dataset\n        stats = HUBDatasetStats('/Users/glennjocher/Downloads/coco8-seg.zip', task='segment')  # segment dataset\n        stats = HUBDatasetStats('/Users/glennjocher/Downloads/coco8-pose.zip', task='pose')  # pose dataset\n        stats.get_json(save=False)\n        stats.process_images()\n    \"\"\"\n\n    def __init__(self, path='coco128.yaml', task='detect', autodownload=False):\n        \"\"\"Initialize class.\"\"\"\n        LOGGER.info(f'Starting HUB dataset checks for {path}....')\n        zipped, data_dir, yaml_path = self._unzip(Path(path))\n        try:\n            # data = yaml_load(check_yaml(yaml_path))  # data dict\n            data = check_det_dataset(yaml_path, autodownload)  # data dict\n            if zipped:\n                data['path'] = data_dir\n        except Exception as e:\n            raise Exception('error/HUB/dataset_stats/yaml_load') from e\n\n        self.hub_dir = Path(str(data['path']) + '-hub')\n        self.im_dir = self.hub_dir / 'images'\n        self.im_dir.mkdir(parents=True, exist_ok=True)  # makes /images\n        self.stats = {'nc': len(data['names']), 'names': list(data['names'].values())}  # statistics dictionary\n        self.data = data\n        self.task = task  # detect, segment, pose, classify\n\n    @staticmethod\n    def _find_yaml(dir):\n        \"\"\"Return data.yaml file.\"\"\"\n        files = list(dir.glob('*.yaml')) or list(dir.rglob('*.yaml'))  # try root level first and then recursive\n        assert files, f'No *.yaml file found in {dir}'\n        if len(files) > 1:\n            files = [f for f in files if f.stem == dir.stem]  # prefer *.yaml files that match dir name\n            assert files, f'Multiple *.yaml files found in {dir}, only 1 *.yaml file allowed'\n        assert len(files) == 1, f'Multiple *.yaml files found: {files}, only 1 *.yaml file allowed in {dir}'\n        return files[0]\n\n    def _unzip(self, path):\n        \"\"\"Unzip data.zip.\"\"\"\n        if not str(path).endswith('.zip'):  # path is data.yaml\n            return False, None, path\n        unzip_dir = unzip_file(path, path=path.parent)\n        assert unzip_dir.is_dir(), f'Error unzipping {path}, {unzip_dir} not found. ' \\\n                                   f'path/to/abc.zip MUST unzip to path/to/abc/'\n        return True, str(unzip_dir), self._find_yaml(unzip_dir)  # zipped, data_dir, yaml_path\n\n    def _hub_ops(self, f):\n        \"\"\"Saves a compressed image for HUB previews.\"\"\"\n        compress_one_image(f, self.im_dir / Path(f).name)  # save to dataset-hub\n\n    def get_json(self, save=False, verbose=False):\n        \"\"\"Return dataset JSON for Ultralytics HUB.\"\"\"\n        from ultralytics.yolo.data import YOLODataset  # ClassificationDataset\n\n        def _round(labels):\n            \"\"\"Update labels to integer class and 4 decimal place floats.\"\"\"\n            if self.task == 'detect':\n                coordinates = labels['bboxes']\n            elif self.task == 'segment':\n                coordinates = [x.flatten() for x in labels['segments']]\n            elif self.task == 'pose':\n                n = labels['keypoints'].shape[0]\n                coordinates = np.concatenate((labels['bboxes'], labels['keypoints'].reshape(n, -1)), 1)\n            else:\n                raise ValueError('Undefined dataset task.')\n            zipped = zip(labels['cls'], coordinates)\n            return [[int(c), *(round(float(x), 4) for x in points)] for c, points in zipped]\n\n        for split in 'train', 'val', 'test':\n            if self.data.get(split) is None:\n                self.stats[split] = None  # i.e. no test set\n                continue\n\n            dataset = YOLODataset(img_path=self.data[split],\n                                  data=self.data,\n                                  use_segments=self.task == 'segment',\n                                  use_keypoints=self.task == 'pose')\n            x = np.array([\n                np.bincount(label['cls'].astype(int).flatten(), minlength=self.data['nc'])\n                for label in tqdm(dataset.labels, total=len(dataset), desc='Statistics')])  # shape(128x80)\n            self.stats[split] = {\n                'instance_stats': {\n                    'total': int(x.sum()),\n                    'per_class': x.sum(0).tolist()},\n                'image_stats': {\n                    'total': len(dataset),\n                    'unlabelled': int(np.all(x == 0, 1).sum()),\n                    'per_class': (x > 0).sum(0).tolist()},\n                'labels': [{\n                    Path(k).name: _round(v)} for k, v in zip(dataset.im_files, dataset.labels)]}\n\n        # Save, print and return\n        if save:\n            stats_path = self.hub_dir / 'stats.json'\n            LOGGER.info(f'Saving {stats_path.resolve()}...')\n            with open(stats_path, 'w') as f:\n                json.dump(self.stats, f)  # save stats.json\n        if verbose:\n            LOGGER.info(json.dumps(self.stats, indent=2, sort_keys=False))\n        return self.stats\n\n    def process_images(self):\n        \"\"\"Compress images for Ultralytics HUB.\"\"\"\n        from ultralytics.yolo.data import YOLODataset  # ClassificationDataset\n\n        for split in 'train', 'val', 'test':\n            if self.data.get(split) is None:\n                continue\n            dataset = YOLODataset(img_path=self.data[split], data=self.data)\n            with ThreadPool(NUM_THREADS) as pool:\n                for _ in tqdm(pool.imap(self._hub_ops, dataset.im_files), total=len(dataset), desc=f'{split} images'):\n                    pass\n        LOGGER.info(f'Done. All images saved to {self.im_dir}')\n        return self.im_dir\n\n\ndef compress_one_image(f, f_new=None, max_dim=1920, quality=50):\n    \"\"\"\n    Compresses a single image file to reduced size while preserving its aspect ratio and quality using either the\n    Python Imaging Library (PIL) or OpenCV library. If the input image is smaller than the maximum dimension, it will\n    not be resized.\n\n    Args:\n        f (str): The path to the input image file.\n        f_new (str, optional): The path to the output image file. If not specified, the input file will be overwritten.\n        max_dim (int, optional): The maximum dimension (width or height) of the output image. Default is 1920 pixels.\n        quality (int, optional): The image compression quality as a percentage. Default is 50%.\n\n    Usage:\n        from pathlib import Path\n        from ultralytics.yolo.data.utils import compress_one_image\n        for f in Path('/Users/glennjocher/Downloads/dataset').rglob('*.jpg'):\n            compress_one_image(f)\n    \"\"\"\n    try:  # use PIL\n        im = Image.open(f)\n        r = max_dim / max(im.height, im.width)  # ratio\n        if r < 1.0:  # image too large\n            im = im.resize((int(im.width * r), int(im.height * r)))\n        im.save(f_new or f, 'JPEG', quality=quality, optimize=True)  # save\n    except Exception as e:  # use OpenCV\n        LOGGER.info(f'WARNING ⚠️ HUB ops PIL failure {f}: {e}')\n        im = cv2.imread(f)\n        im_height, im_width = im.shape[:2]\n        r = max_dim / max(im_height, im_width)  # ratio\n        if r < 1.0:  # image too large\n            im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_AREA)\n        cv2.imwrite(str(f_new or f), im)\n\n\ndef delete_dsstore(path):\n    \"\"\"\n    Deletes all \".DS_store\" files under a specified directory.\n\n    Args:\n        path (str, optional): The directory path where the \".DS_store\" files should be deleted.\n\n    Usage:\n        from ultralytics.yolo.data.utils import delete_dsstore\n        delete_dsstore('/Users/glennjocher/Downloads/dataset')\n\n    Note:\n        \".DS_store\" files are created by the Apple operating system and contain metadata about folders and files. They\n        are hidden system files and can cause issues when transferring files between different operating systems.\n    \"\"\"\n    # Delete Apple .DS_store files\n    files = list(Path(path).rglob('.DS_store'))\n    LOGGER.info(f'Deleting *.DS_store files: {files}')\n    for f in files:\n        f.unlink()\n\n\ndef zip_directory(dir, use_zipfile_library=True):\n    \"\"\"\n    Zips a directory and saves the archive to the specified output path.\n\n    Args:\n        dir (str): The path to the directory to be zipped.\n        use_zipfile_library (bool): Whether to use zipfile library or shutil for zipping.\n\n    Usage:\n        from ultralytics.yolo.data.utils import zip_directory\n        zip_directory('/Users/glennjocher/Downloads/playground')\n\n        zip -r coco8-pose.zip coco8-pose\n    \"\"\"\n    delete_dsstore(dir)\n    if use_zipfile_library:\n        dir = Path(dir)\n        with zipfile.ZipFile(dir.with_suffix('.zip'), 'w', zipfile.ZIP_DEFLATED) as zip_file:\n            for file_path in dir.glob('**/*'):\n                if file_path.is_file():\n                    zip_file.write(file_path, file_path.relative_to(dir))\n    else:\n        import shutil\n        shutil.make_archive(dir, 'zip', dir)\n"
  },
  {
    "path": "ultralytics/yolo/engine/__init__.py",
    "content": ""
  },
  {
    "path": "ultralytics/yolo/engine/exporter.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nExport a YOLOv8 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit\n\nFormat                  | `format=argument`         | Model\n---                     | ---                       | ---\nPyTorch                 | -                         | yolov8n.pt\nTorchScript             | `torchscript`             | yolov8n.torchscript\nONNX                    | `onnx`                    | yolov8n.onnx\nOpenVINO                | `openvino`                | yolov8n_openvino_model/\nTensorRT                | `engine`                  | yolov8n.engine\nCoreML                  | `coreml`                  | yolov8n.mlmodel\nTensorFlow SavedModel   | `saved_model`             | yolov8n_saved_model/\nTensorFlow GraphDef     | `pb`                      | yolov8n.pb\nTensorFlow Lite         | `tflite`                  | yolov8n.tflite\nTensorFlow Edge TPU     | `edgetpu`                 | yolov8n_edgetpu.tflite\nTensorFlow.js           | `tfjs`                    | yolov8n_web_model/\nPaddlePaddle            | `paddle`                  | yolov8n_paddle_model/\n\nRequirements:\n    $ pip install ultralytics[export]\n\nPython:\n    from ultralytics import YOLO\n    model = YOLO('yolov8n.pt')\n    results = model.export(format='onnx')\n\nCLI:\n    $ yolo mode=export model=yolov8n.pt format=onnx\n\nInference:\n    $ yolo predict model=yolov8n.pt                 # PyTorch\n                         yolov8n.torchscript        # TorchScript\n                         yolov8n.onnx               # ONNX Runtime or OpenCV DNN with --dnn\n                         yolov8n_openvino_model     # OpenVINO\n                         yolov8n.engine             # TensorRT\n                         yolov8n.mlmodel            # CoreML (macOS-only)\n                         yolov8n_saved_model        # TensorFlow SavedModel\n                         yolov8n.pb                 # TensorFlow GraphDef\n                         yolov8n.tflite             # TensorFlow Lite\n                         yolov8n_edgetpu.tflite     # TensorFlow Edge TPU\n                         yolov8n_paddle_model       # PaddlePaddle\n\nTensorFlow.js:\n    $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example\n    $ npm install\n    $ ln -s ../../yolov5/yolov8n_web_model public/yolov8n_web_model\n    $ npm start\n\"\"\"\nimport json\nimport os\nimport platform\nimport subprocess\nimport time\nimport warnings\nfrom copy import deepcopy\nfrom pathlib import Path\n\nimport torch\n\nfrom ultralytics.nn.autobackend import check_class_names\nfrom ultralytics.nn.modules import C2f, Detect, Segment\nfrom ultralytics.nn.tasks import DetectionModel, SegmentationModel\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.utils import (DEFAULT_CFG, LINUX, LOGGER, MACOS, __version__, callbacks, colorstr,\n                                    get_default_args, yaml_save)\nfrom ultralytics.yolo.utils.checks import check_imgsz, check_requirements, check_version\nfrom ultralytics.yolo.utils.files import file_size\nfrom ultralytics.yolo.utils.ops import Profile\nfrom ultralytics.yolo.utils.torch_utils import get_latest_opset, select_device, smart_inference_mode\n\nARM64 = platform.machine() in ('arm64', 'aarch64')\n\n\ndef export_formats():\n    \"\"\"YOLOv8 export formats.\"\"\"\n    import pandas\n    x = [\n        ['PyTorch', '-', '.pt', True, True],\n        ['TorchScript', 'torchscript', '.torchscript', True, True],\n        ['ONNX', 'onnx', '.onnx', True, True],\n        ['OpenVINO', 'openvino', '_openvino_model', True, False],\n        ['TensorRT', 'engine', '.engine', False, True],\n        ['CoreML', 'coreml', '.mlmodel', True, False],\n        ['TensorFlow SavedModel', 'saved_model', '_saved_model', True, True],\n        ['TensorFlow GraphDef', 'pb', '.pb', True, True],\n        ['TensorFlow Lite', 'tflite', '.tflite', True, False],\n        ['TensorFlow Edge TPU', 'edgetpu', '_edgetpu.tflite', True, False],\n        ['TensorFlow.js', 'tfjs', '_web_model', True, False],\n        ['PaddlePaddle', 'paddle', '_paddle_model', True, True], ]\n    return pandas.DataFrame(x, columns=['Format', 'Argument', 'Suffix', 'CPU', 'GPU'])\n\n\ndef gd_outputs(gd):\n    \"\"\"TensorFlow GraphDef model output node names.\"\"\"\n    name_list, input_list = [], []\n    for node in gd.node:  # tensorflow.core.framework.node_def_pb2.NodeDef\n        name_list.append(node.name)\n        input_list.extend(node.input)\n    return sorted(f'{x}:0' for x in list(set(name_list) - set(input_list)) if not x.startswith('NoOp'))\n\n\ndef try_export(inner_func):\n    \"\"\"YOLOv8 export decorator, i..e @try_export.\"\"\"\n    inner_args = get_default_args(inner_func)\n\n    def outer_func(*args, **kwargs):\n        \"\"\"Export a model.\"\"\"\n        prefix = inner_args['prefix']\n        try:\n            with Profile() as dt:\n                f, model = inner_func(*args, **kwargs)\n            LOGGER.info(f'{prefix} export success ✅ {dt.t:.1f}s, saved as {f} ({file_size(f):.1f} MB)')\n            return f, model\n        except Exception as e:\n            LOGGER.info(f'{prefix} export failure ❌ {dt.t:.1f}s: {e}')\n            return None, None\n\n    return outer_func\n\n\nclass Exporter:\n    \"\"\"\n    A class for exporting a model.\n\n    Attributes:\n        args (SimpleNamespace): Configuration for the exporter.\n        save_dir (Path): Directory to save results.\n    \"\"\"\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        \"\"\"\n        Initializes the Exporter class.\n\n        Args:\n            cfg (str, optional): Path to a configuration file. Defaults to DEFAULT_CFG.\n            overrides (dict, optional): Configuration overrides. Defaults to None.\n            _callbacks (list, optional): List of callback functions. Defaults to None.\n        \"\"\"\n        self.args = get_cfg(cfg, overrides)\n        self.callbacks = _callbacks or callbacks.get_default_callbacks()\n        callbacks.add_integration_callbacks(self)\n\n    @smart_inference_mode()\n    def __call__(self, model=None):\n        \"\"\"Returns list of exported files/dirs after running callbacks.\"\"\"\n        self.run_callbacks('on_export_start')\n        t = time.time()\n        format = self.args.format.lower()  # to lowercase\n        if format in ('tensorrt', 'trt'):  # engine aliases\n            format = 'engine'\n        fmts = tuple(export_formats()['Argument'][1:])  # available export formats\n        flags = [x == format for x in fmts]\n        if sum(flags) != 1:\n            raise ValueError(f\"Invalid export format='{format}'. Valid formats are {fmts}\")\n        jit, onnx, xml, engine, coreml, saved_model, pb, tflite, edgetpu, tfjs, paddle = flags  # export booleans\n\n        # Load PyTorch model\n        self.device = select_device('cpu' if self.args.device is None else self.args.device)\n        if self.args.half and onnx and self.device.type == 'cpu':\n            LOGGER.warning('WARNING ⚠️ half=True only compatible with GPU export, i.e. use device=0')\n            self.args.half = False\n            assert not self.args.dynamic, 'half=True not compatible with dynamic=True, i.e. use only one.'\n\n        # Checks\n        model.names = check_class_names(model.names)\n        self.imgsz = check_imgsz(self.args.imgsz, stride=model.stride, min_dim=2)  # check image size\n        if self.args.optimize:\n            assert self.device.type == 'cpu', '--optimize not compatible with cuda devices, i.e. use --device cpu'\n        if edgetpu and not LINUX:\n            raise SystemError('Edge TPU export only supported on Linux. See https://coral.ai/docs/edgetpu/compiler/')\n\n        # Input\n        im = torch.zeros(self.args.batch, 3, *self.imgsz).to(self.device)\n        file = Path(getattr(model, 'pt_path', None) or getattr(model, 'yaml_file', None) or model.yaml['yaml_file'])\n        if file.suffix == '.yaml':\n            file = Path(file.name)\n\n        # Update model\n        model = deepcopy(model).to(self.device)\n        for p in model.parameters():\n            p.requires_grad = False\n        model.eval()\n        model.float()\n        model = model.fuse()\n        for k, m in model.named_modules():\n            if isinstance(m, (Detect, Segment)):\n                m.dynamic = self.args.dynamic\n                m.export = True\n                m.format = self.args.format\n            elif isinstance(m, C2f) and not any((saved_model, pb, tflite, edgetpu, tfjs)):\n                # EdgeTPU does not support FlexSplitV while split provides cleaner ONNX graph\n                m.forward = m.forward_split\n\n        y = None\n        for _ in range(2):\n            y = model(im)  # dry runs\n        if self.args.half and (engine or onnx) and self.device.type != 'cpu':\n            im, model = im.half(), model.half()  # to FP16\n\n        # Warnings\n        warnings.filterwarnings('ignore', category=torch.jit.TracerWarning)  # suppress TracerWarning\n        warnings.filterwarnings('ignore', category=UserWarning)  # suppress shape prim::Constant missing ONNX warning\n        warnings.filterwarnings('ignore', category=DeprecationWarning)  # suppress CoreML np.bool deprecation warning\n\n        # Assign\n        self.im = im\n        self.model = model\n        self.file = file\n        self.output_shape = tuple(y.shape) if isinstance(y, torch.Tensor) else tuple(tuple(x.shape) for x in y)\n        self.pretty_name = Path(self.model.yaml.get('yaml_file', self.file)).stem.replace('yolo', 'YOLO')\n        trained_on = f'trained on {Path(self.args.data).name}' if self.args.data else '(untrained)'\n        description = f'Ultralytics {self.pretty_name} model {trained_on}'\n        self.metadata = {\n            'description': description,\n            'author': 'Ultralytics',\n            'license': 'AGPL-3.0 https://ultralytics.com/license',\n            'version': __version__,\n            'stride': int(max(model.stride)),\n            'task': model.task,\n            'batch': self.args.batch,\n            'imgsz': self.imgsz,\n            'names': model.names}  # model metadata\n        if model.task == 'pose':\n            self.metadata['kpt_shape'] = model.kpt_shape\n\n        LOGGER.info(f\"\\n{colorstr('PyTorch:')} starting from {file} with input shape {tuple(im.shape)} BCHW and \"\n                    f'output shape(s) {self.output_shape} ({file_size(file):.1f} MB)')\n\n        # Exports\n        f = [''] * len(fmts)  # exported filenames\n        if jit:  # TorchScript\n            f[0], _ = self.export_torchscript()\n        if engine:  # TensorRT required before ONNX\n            f[1], _ = self.export_engine()\n        if onnx or xml:  # OpenVINO requires ONNX\n            f[2], _ = self.export_onnx()\n        if xml:  # OpenVINO\n            f[3], _ = self.export_openvino()\n        if coreml:  # CoreML\n            f[4], _ = self.export_coreml()\n        if any((saved_model, pb, tflite, edgetpu, tfjs)):  # TensorFlow formats\n            self.args.int8 |= edgetpu\n            f[5], s_model = self.export_saved_model()\n            if pb or tfjs:  # pb prerequisite to tfjs\n                f[6], _ = self.export_pb(s_model)\n            if tflite:\n                f[7], _ = self.export_tflite(s_model, nms=False, agnostic_nms=self.args.agnostic_nms)\n            if edgetpu:\n                f[8], _ = self.export_edgetpu(tflite_model=Path(f[5]) / f'{self.file.stem}_full_integer_quant.tflite')\n            if tfjs:\n                f[9], _ = self.export_tfjs()\n        if paddle:  # PaddlePaddle\n            f[10], _ = self.export_paddle()\n\n        # Finish\n        f = [str(x) for x in f if x]  # filter out '' and None\n        if any(f):\n            f = str(Path(f[-1]))\n            square = self.imgsz[0] == self.imgsz[1]\n            s = '' if square else f\"WARNING ⚠️ non-PyTorch val requires square images, 'imgsz={self.imgsz}' will not \" \\\n                                  f\"work. Use export 'imgsz={max(self.imgsz)}' if val is required.\"\n            imgsz = self.imgsz[0] if square else str(self.imgsz)[1:-1].replace(' ', '')\n            data = f'data={self.args.data}' if model.task == 'segment' and format == 'pb' else ''\n            LOGGER.info(\n                f'\\nExport complete ({time.time() - t:.1f}s)'\n                f\"\\nResults saved to {colorstr('bold', file.parent.resolve())}\"\n                f'\\nPredict:         yolo predict task={model.task} model={f} imgsz={imgsz} {data}'\n                f'\\nValidate:        yolo val task={model.task} model={f} imgsz={imgsz} data={self.args.data} {s}'\n                f'\\nVisualize:       https://netron.app')\n\n        self.run_callbacks('on_export_end')\n        return f  # return list of exported files/dirs\n\n    @try_export\n    def export_torchscript(self, prefix=colorstr('TorchScript:')):\n        \"\"\"YOLOv8 TorchScript model export.\"\"\"\n        LOGGER.info(f'\\n{prefix} starting export with torch {torch.__version__}...')\n        f = self.file.with_suffix('.torchscript')\n\n        ts = torch.jit.trace(self.model, self.im, strict=False)\n        extra_files = {'config.txt': json.dumps(self.metadata)}  # torch._C.ExtraFilesMap()\n        if self.args.optimize:  # https://pytorch.org/tutorials/recipes/mobile_interpreter.html\n            LOGGER.info(f'{prefix} optimizing for mobile...')\n            from torch.utils.mobile_optimizer import optimize_for_mobile\n            optimize_for_mobile(ts)._save_for_lite_interpreter(str(f), _extra_files=extra_files)\n        else:\n            ts.save(str(f), _extra_files=extra_files)\n        return f, None\n\n    @try_export\n    def export_onnx(self, prefix=colorstr('ONNX:')):\n        \"\"\"YOLOv8 ONNX export.\"\"\"\n        requirements = ['onnx>=1.12.0']\n        if self.args.simplify:\n            requirements += ['onnxsim>=0.4.17', 'onnxruntime-gpu' if torch.cuda.is_available() else 'onnxruntime']\n        check_requirements(requirements)\n        import onnx  # noqa\n\n        opset_version = self.args.opset or get_latest_opset()\n        LOGGER.info(f'\\n{prefix} starting export with onnx {onnx.__version__} opset {opset_version}...')\n        f = str(self.file.with_suffix('.onnx'))\n\n        output_names = ['output0', 'output1'] if isinstance(self.model, SegmentationModel) else ['output0']\n        dynamic = self.args.dynamic\n        if dynamic:\n            dynamic = {'images': {0: 'batch', 2: 'height', 3: 'width'}}  # shape(1,3,640,640)\n            if isinstance(self.model, SegmentationModel):\n                dynamic['output0'] = {0: 'batch', 1: 'anchors'}  # shape(1,25200,85)\n                dynamic['output1'] = {0: 'batch', 2: 'mask_height', 3: 'mask_width'}  # shape(1,32,160,160)\n            elif isinstance(self.model, DetectionModel):\n                dynamic['output0'] = {0: 'batch', 1: 'anchors'}  # shape(1,25200,85)\n\n        torch.onnx.export(\n            self.model.cpu() if dynamic else self.model,  # --dynamic only compatible with cpu\n            self.im.cpu() if dynamic else self.im,\n            f,\n            verbose=False,\n            opset_version=opset_version,\n            do_constant_folding=True,  # WARNING: DNN inference with torch>=1.12 may require do_constant_folding=False\n            input_names=['images'],\n            output_names=output_names,\n            dynamic_axes=dynamic or None)\n\n        # Checks\n        model_onnx = onnx.load(f)  # load onnx model\n        # onnx.checker.check_model(model_onnx)  # check onnx model\n\n        # Simplify\n        if self.args.simplify:\n            try:\n                import onnxsim\n\n                LOGGER.info(f'{prefix} simplifying with onnxsim {onnxsim.__version__}...')\n                # subprocess.run(f'onnxsim {f} {f}', shell=True)\n                model_onnx, check = onnxsim.simplify(model_onnx)\n                assert check, 'Simplified ONNX model could not be validated'\n            except Exception as e:\n                LOGGER.info(f'{prefix} simplifier failure: {e}')\n\n        # Metadata\n        for k, v in self.metadata.items():\n            meta = model_onnx.metadata_props.add()\n            meta.key, meta.value = k, str(v)\n\n        onnx.save(model_onnx, f)\n        return f, model_onnx\n\n    @try_export\n    def export_openvino(self, prefix=colorstr('OpenVINO:')):\n        \"\"\"YOLOv8 OpenVINO export.\"\"\"\n        check_requirements('openvino-dev>=2022.3')  # requires openvino-dev: https://pypi.org/project/openvino-dev/\n        import openvino.runtime as ov  # noqa\n        from openvino.tools import mo  # noqa\n\n        LOGGER.info(f'\\n{prefix} starting export with openvino {ov.__version__}...')\n        f = str(self.file).replace(self.file.suffix, f'_openvino_model{os.sep}')\n        f_onnx = self.file.with_suffix('.onnx')\n        f_ov = str(Path(f) / self.file.with_suffix('.xml').name)\n\n        ov_model = mo.convert_model(f_onnx,\n                                    model_name=self.pretty_name,\n                                    framework='onnx',\n                                    compress_to_fp16=self.args.half)  # export\n        ov.serialize(ov_model, f_ov)  # save\n        yaml_save(Path(f) / 'metadata.yaml', self.metadata)  # add metadata.yaml\n        return f, None\n\n    @try_export\n    def export_paddle(self, prefix=colorstr('PaddlePaddle:')):\n        \"\"\"YOLOv8 Paddle export.\"\"\"\n        check_requirements(('paddlepaddle', 'x2paddle'))\n        import x2paddle  # noqa\n        from x2paddle.convert import pytorch2paddle  # noqa\n\n        LOGGER.info(f'\\n{prefix} starting export with X2Paddle {x2paddle.__version__}...')\n        f = str(self.file).replace(self.file.suffix, f'_paddle_model{os.sep}')\n\n        pytorch2paddle(module=self.model, save_dir=f, jit_type='trace', input_examples=[self.im])  # export\n        yaml_save(Path(f) / 'metadata.yaml', self.metadata)  # add metadata.yaml\n        return f, None\n\n    @try_export\n    def export_coreml(self, prefix=colorstr('CoreML:')):\n        \"\"\"YOLOv8 CoreML export.\"\"\"\n        check_requirements('coremltools>=6.0')\n        import coremltools as ct  # noqa\n\n        LOGGER.info(f'\\n{prefix} starting export with coremltools {ct.__version__}...')\n        f = self.file.with_suffix('.mlmodel')\n\n        bias = [0.0, 0.0, 0.0]\n        scale = 1 / 255\n        classifier_config = None\n        if self.model.task == 'classify':\n            classifier_config = ct.ClassifierConfig(list(self.model.names.values())) if self.args.nms else None\n            model = self.model\n        elif self.model.task == 'detect':\n            model = iOSDetectModel(self.model, self.im) if self.args.nms else self.model\n        else:\n            # TODO CoreML Segment and Pose model pipelining\n            model = self.model\n\n        ts = torch.jit.trace(model.eval(), self.im, strict=False)  # TorchScript model\n        ct_model = ct.convert(ts,\n                              inputs=[ct.ImageType('image', shape=self.im.shape, scale=scale, bias=bias)],\n                              classifier_config=classifier_config)\n        bits, mode = (8, 'kmeans_lut') if self.args.int8 else (16, 'linear') if self.args.half else (32, None)\n        if bits < 32:\n            if 'kmeans' in mode:\n                check_requirements('scikit-learn')  # scikit-learn package required for k-means quantization\n            ct_model = ct.models.neural_network.quantization_utils.quantize_weights(ct_model, bits, mode)\n        if self.args.nms and self.model.task == 'detect':\n            ct_model = self._pipeline_coreml(ct_model)\n\n        m = self.metadata  # metadata dict\n        ct_model.short_description = m.pop('description')\n        ct_model.author = m.pop('author')\n        ct_model.license = m.pop('license')\n        ct_model.version = m.pop('version')\n        ct_model.user_defined_metadata.update({k: str(v) for k, v in m.items()})\n        ct_model.save(str(f))\n        return f, ct_model\n\n    @try_export\n    def export_engine(self, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):\n        \"\"\"YOLOv8 TensorRT export https://developer.nvidia.com/tensorrt.\"\"\"\n        assert self.im.device.type != 'cpu', \"export running on CPU but must be on GPU, i.e. use 'device=0'\"\n        try:\n            import tensorrt as trt  # noqa\n        except ImportError:\n            if LINUX:\n                check_requirements('nvidia-tensorrt', cmds='-U --index-url https://pypi.ngc.nvidia.com')\n            import tensorrt as trt  # noqa\n\n        check_version(trt.__version__, '7.0.0', hard=True)  # require tensorrt>=8.0.0\n        self.args.simplify = True\n        f_onnx, _ = self.export_onnx()\n\n        LOGGER.info(f'\\n{prefix} starting export with TensorRT {trt.__version__}...')\n        assert Path(f_onnx).exists(), f'failed to export ONNX file: {f_onnx}'\n        f = self.file.with_suffix('.engine')  # TensorRT engine file\n        logger = trt.Logger(trt.Logger.INFO)\n        if verbose:\n            logger.min_severity = trt.Logger.Severity.VERBOSE\n\n        builder = trt.Builder(logger)\n        config = builder.create_builder_config()\n        config.max_workspace_size = workspace * 1 << 30\n        # config.set_memory_pool_limit(trt.MemoryPoolType.WORKSPACE, workspace << 30)  # fix TRT 8.4 deprecation notice\n\n        flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))\n        network = builder.create_network(flag)\n        parser = trt.OnnxParser(network, logger)\n        if not parser.parse_from_file(f_onnx):\n            raise RuntimeError(f'failed to load ONNX file: {f_onnx}')\n\n        inputs = [network.get_input(i) for i in range(network.num_inputs)]\n        outputs = [network.get_output(i) for i in range(network.num_outputs)]\n        for inp in inputs:\n            LOGGER.info(f'{prefix} input \"{inp.name}\" with shape{inp.shape} {inp.dtype}')\n        for out in outputs:\n            LOGGER.info(f'{prefix} output \"{out.name}\" with shape{out.shape} {out.dtype}')\n\n        if self.args.dynamic:\n            shape = self.im.shape\n            if shape[0] <= 1:\n                LOGGER.warning(f'{prefix} WARNING ⚠️ --dynamic model requires maximum --batch-size argument')\n            profile = builder.create_optimization_profile()\n            for inp in inputs:\n                profile.set_shape(inp.name, (1, *shape[1:]), (max(1, shape[0] // 2), *shape[1:]), shape)\n            config.add_optimization_profile(profile)\n\n        LOGGER.info(\n            f'{prefix} building FP{16 if builder.platform_has_fast_fp16 and self.args.half else 32} engine as {f}')\n        if builder.platform_has_fast_fp16 and self.args.half:\n            config.set_flag(trt.BuilderFlag.FP16)\n\n        # Write file\n        with builder.build_engine(network, config) as engine, open(f, 'wb') as t:\n            # Metadata\n            meta = json.dumps(self.metadata)\n            t.write(len(meta).to_bytes(4, byteorder='little', signed=True))\n            t.write(meta.encode())\n            # Model\n            t.write(engine.serialize())\n\n        return f, None\n\n    @try_export\n    def export_saved_model(self, prefix=colorstr('TensorFlow SavedModel:')):\n        \"\"\"YOLOv8 TensorFlow SavedModel export.\"\"\"\n        try:\n            import tensorflow as tf  # noqa\n        except ImportError:\n            cuda = torch.cuda.is_available()\n            check_requirements(f\"tensorflow{'-macos' if MACOS else '-aarch64' if ARM64 else '' if cuda else '-cpu'}\")\n            import tensorflow as tf  # noqa\n        check_requirements(('onnx', 'onnx2tf>=1.7.7', 'sng4onnx>=1.0.1', 'onnxsim>=0.4.17', 'onnx_graphsurgeon>=0.3.26',\n                            'tflite_support', 'onnxruntime-gpu' if torch.cuda.is_available() else 'onnxruntime'),\n                           cmds='--extra-index-url https://pypi.ngc.nvidia.com')\n\n        LOGGER.info(f'\\n{prefix} starting export with tensorflow {tf.__version__}...')\n        f = Path(str(self.file).replace(self.file.suffix, '_saved_model'))\n        if f.is_dir():\n            import shutil\n            shutil.rmtree(f)  # delete output folder\n\n        # Export to ONNX\n        self.args.simplify = True\n        f_onnx, _ = self.export_onnx()\n\n        # Export to TF\n        int8 = '-oiqt -qt per-tensor' if self.args.int8 else ''\n        cmd = f'onnx2tf -i {f_onnx} -o {f} -nuo --non_verbose {int8}'\n        LOGGER.info(f\"\\n{prefix} running '{cmd.strip()}'\")\n        subprocess.run(cmd, shell=True)\n        yaml_save(f / 'metadata.yaml', self.metadata)  # add metadata.yaml\n\n        # Remove/rename TFLite models\n        if self.args.int8:\n            for file in f.rglob('*_dynamic_range_quant.tflite'):\n                file.rename(file.with_stem(file.stem.replace('_dynamic_range_quant', '_int8')))\n            for file in f.rglob('*_integer_quant_with_int16_act.tflite'):\n                file.unlink()  # delete extra fp16 activation TFLite files\n\n        # Add TFLite metadata\n        for file in f.rglob('*.tflite'):\n            f.unlink() if 'quant_with_int16_act.tflite' in str(f) else self._add_tflite_metadata(file)\n\n        # Load saved_model\n        keras_model = tf.saved_model.load(f, tags=None, options=None)\n\n        return str(f), keras_model\n\n    @try_export\n    def export_pb(self, keras_model, prefix=colorstr('TensorFlow GraphDef:')):\n        \"\"\"YOLOv8 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow.\"\"\"\n        import tensorflow as tf  # noqa\n        from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2  # noqa\n\n        LOGGER.info(f'\\n{prefix} starting export with tensorflow {tf.__version__}...')\n        f = self.file.with_suffix('.pb')\n\n        m = tf.function(lambda x: keras_model(x))  # full model\n        m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))\n        frozen_func = convert_variables_to_constants_v2(m)\n        frozen_func.graph.as_graph_def()\n        tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)\n        return f, None\n\n    @try_export\n    def export_tflite(self, keras_model, nms, agnostic_nms, prefix=colorstr('TensorFlow Lite:')):\n        \"\"\"YOLOv8 TensorFlow Lite export.\"\"\"\n        import tensorflow as tf  # noqa\n\n        LOGGER.info(f'\\n{prefix} starting export with tensorflow {tf.__version__}...')\n        saved_model = Path(str(self.file).replace(self.file.suffix, '_saved_model'))\n        if self.args.int8:\n            f = saved_model / f'{self.file.stem}_int8.tflite'  # fp32 in/out\n        elif self.args.half:\n            f = saved_model / f'{self.file.stem}_float16.tflite'  # fp32 in/out\n        else:\n            f = saved_model / f'{self.file.stem}_float32.tflite'\n        return str(f), None\n\n    @try_export\n    def export_edgetpu(self, tflite_model='', prefix=colorstr('Edge TPU:')):\n        \"\"\"YOLOv8 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/.\"\"\"\n        LOGGER.warning(f'{prefix} WARNING ⚠️ Edge TPU known bug https://github.com/ultralytics/ultralytics/issues/1185')\n\n        cmd = 'edgetpu_compiler --version'\n        help_url = 'https://coral.ai/docs/edgetpu/compiler/'\n        assert LINUX, f'export only supported on Linux. See {help_url}'\n        if subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, shell=True).returncode != 0:\n            LOGGER.info(f'\\n{prefix} export requires Edge TPU compiler. Attempting install from {help_url}')\n            sudo = subprocess.run('sudo --version >/dev/null', shell=True).returncode == 0  # sudo installed on system\n            for c in (\n                    'curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -',\n                    'echo \"deb https://packages.cloud.google.com/apt coral-edgetpu-stable main\" | sudo tee /etc/apt/sources.list.d/coral-edgetpu.list',\n                    'sudo apt-get update', 'sudo apt-get install edgetpu-compiler'):\n                subprocess.run(c if sudo else c.replace('sudo ', ''), shell=True, check=True)\n        ver = subprocess.run(cmd, shell=True, capture_output=True, check=True).stdout.decode().split()[-1]\n\n        LOGGER.info(f'\\n{prefix} starting export with Edge TPU compiler {ver}...')\n        f = str(tflite_model).replace('.tflite', '_edgetpu.tflite')  # Edge TPU model\n\n        cmd = f'edgetpu_compiler -s -d -k 10 --out_dir {Path(f).parent} {tflite_model}'\n        LOGGER.info(f\"{prefix} running '{cmd}'\")\n        subprocess.run(cmd.split(), check=True)\n        self._add_tflite_metadata(f)\n        return f, None\n\n    @try_export\n    def export_tfjs(self, prefix=colorstr('TensorFlow.js:')):\n        \"\"\"YOLOv8 TensorFlow.js export.\"\"\"\n        check_requirements('tensorflowjs')\n        import tensorflow as tf\n        import tensorflowjs as tfjs  # noqa\n\n        LOGGER.info(f'\\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')\n        f = str(self.file).replace(self.file.suffix, '_web_model')  # js dir\n        f_pb = self.file.with_suffix('.pb')  # *.pb path\n\n        gd = tf.Graph().as_graph_def()  # TF GraphDef\n        with open(f_pb, 'rb') as file:\n            gd.ParseFromString(file.read())\n        outputs = ','.join(gd_outputs(gd))\n        LOGGER.info(f'\\n{prefix} output node names: {outputs}')\n\n        cmd = f'tensorflowjs_converter --input_format=tf_frozen_model --output_node_names={outputs} {f_pb} {f}'\n        subprocess.run(cmd.split(), check=True)\n\n        # f_json = Path(f) / 'model.json'  # *.json path\n        # with open(f_json, 'w') as j:  # sort JSON Identity_* in ascending order\n        #     subst = re.sub(\n        #         r'{\"outputs\": {\"Identity.?.?\": {\"name\": \"Identity.?.?\"}, '\n        #         r'\"Identity.?.?\": {\"name\": \"Identity.?.?\"}, '\n        #         r'\"Identity.?.?\": {\"name\": \"Identity.?.?\"}, '\n        #         r'\"Identity.?.?\": {\"name\": \"Identity.?.?\"}}}',\n        #         r'{\"outputs\": {\"Identity\": {\"name\": \"Identity\"}, '\n        #         r'\"Identity_1\": {\"name\": \"Identity_1\"}, '\n        #         r'\"Identity_2\": {\"name\": \"Identity_2\"}, '\n        #         r'\"Identity_3\": {\"name\": \"Identity_3\"}}}',\n        #         f_json.read_text(),\n        #     )\n        #     j.write(subst)\n        yaml_save(Path(f) / 'metadata.yaml', self.metadata)  # add metadata.yaml\n        return f, None\n\n    def _add_tflite_metadata(self, file):\n        \"\"\"Add metadata to *.tflite models per https://www.tensorflow.org/lite/models/convert/metadata.\"\"\"\n        from tflite_support import flatbuffers  # noqa\n        from tflite_support import metadata as _metadata  # noqa\n        from tflite_support import metadata_schema_py_generated as _metadata_fb  # noqa\n\n        # Create model info\n        model_meta = _metadata_fb.ModelMetadataT()\n        model_meta.name = self.metadata['description']\n        model_meta.version = self.metadata['version']\n        model_meta.author = self.metadata['author']\n        model_meta.license = self.metadata['license']\n\n        # Label file\n        tmp_file = Path(file).parent / 'temp_meta.txt'\n        with open(tmp_file, 'w') as f:\n            f.write(str(self.metadata))\n\n        label_file = _metadata_fb.AssociatedFileT()\n        label_file.name = tmp_file.name\n        label_file.type = _metadata_fb.AssociatedFileType.TENSOR_AXIS_LABELS\n\n        # Create input info\n        input_meta = _metadata_fb.TensorMetadataT()\n        input_meta.name = 'image'\n        input_meta.description = 'Input image to be detected.'\n        input_meta.content = _metadata_fb.ContentT()\n        input_meta.content.contentProperties = _metadata_fb.ImagePropertiesT()\n        input_meta.content.contentProperties.colorSpace = _metadata_fb.ColorSpaceType.RGB\n        input_meta.content.contentPropertiesType = _metadata_fb.ContentProperties.ImageProperties\n\n        # Create output info\n        output1 = _metadata_fb.TensorMetadataT()\n        output1.name = 'output'\n        output1.description = 'Coordinates of detected objects, class labels, and confidence score'\n        output1.associatedFiles = [label_file]\n        if self.model.task == 'segment':\n            output2 = _metadata_fb.TensorMetadataT()\n            output2.name = 'output'\n            output2.description = 'Mask protos'\n            output2.associatedFiles = [label_file]\n\n        # Create subgraph info\n        subgraph = _metadata_fb.SubGraphMetadataT()\n        subgraph.inputTensorMetadata = [input_meta]\n        subgraph.outputTensorMetadata = [output1, output2] if self.model.task == 'segment' else [output1]\n        model_meta.subgraphMetadata = [subgraph]\n\n        b = flatbuffers.Builder(0)\n        b.Finish(model_meta.Pack(b), _metadata.MetadataPopulator.METADATA_FILE_IDENTIFIER)\n        metadata_buf = b.Output()\n\n        populator = _metadata.MetadataPopulator.with_model_file(str(file))\n        populator.load_metadata_buffer(metadata_buf)\n        populator.load_associated_files([str(tmp_file)])\n        populator.populate()\n        tmp_file.unlink()\n\n    def _pipeline_coreml(self, model, prefix=colorstr('CoreML Pipeline:')):\n        \"\"\"YOLOv8 CoreML pipeline.\"\"\"\n        import coremltools as ct  # noqa\n\n        LOGGER.info(f'{prefix} starting pipeline with coremltools {ct.__version__}...')\n        batch_size, ch, h, w = list(self.im.shape)  # BCHW\n\n        # Output shapes\n        spec = model.get_spec()\n        out0, out1 = iter(spec.description.output)\n        if MACOS:\n            from PIL import Image\n            img = Image.new('RGB', (w, h))  # img(192 width, 320 height)\n            # img = torch.zeros((*opt.img_size, 3)).numpy()  # img size(320,192,3) iDetection\n            out = model.predict({'image': img})\n            out0_shape = out[out0.name].shape\n            out1_shape = out[out1.name].shape\n        else:  # linux and windows can not run model.predict(), get sizes from pytorch output y\n            out0_shape = self.output_shape[2], self.output_shape[1] - 4  # (3780, 80)\n            out1_shape = self.output_shape[2], 4  # (3780, 4)\n\n        # Checks\n        names = self.metadata['names']\n        nx, ny = spec.description.input[0].type.imageType.width, spec.description.input[0].type.imageType.height\n        na, nc = out0_shape\n        # na, nc = out0.type.multiArrayType.shape  # number anchors, classes\n        assert len(names) == nc, f'{len(names)} names found for nc={nc}'  # check\n\n        # Define output shapes (missing)\n        out0.type.multiArrayType.shape[:] = out0_shape  # (3780, 80)\n        out1.type.multiArrayType.shape[:] = out1_shape  # (3780, 4)\n        # spec.neuralNetwork.preprocessing[0].featureName = '0'\n\n        # Flexible input shapes\n        # from coremltools.models.neural_network import flexible_shape_utils\n        # s = [] # shapes\n        # s.append(flexible_shape_utils.NeuralNetworkImageSize(320, 192))\n        # s.append(flexible_shape_utils.NeuralNetworkImageSize(640, 384))  # (height, width)\n        # flexible_shape_utils.add_enumerated_image_sizes(spec, feature_name='image', sizes=s)\n        # r = flexible_shape_utils.NeuralNetworkImageSizeRange()  # shape ranges\n        # r.add_height_range((192, 640))\n        # r.add_width_range((192, 640))\n        # flexible_shape_utils.update_image_size_range(spec, feature_name='image', size_range=r)\n\n        # Print\n        # print(spec.description)\n\n        # Model from spec\n        model = ct.models.MLModel(spec)\n\n        # 3. Create NMS protobuf\n        nms_spec = ct.proto.Model_pb2.Model()\n        nms_spec.specificationVersion = 5\n        for i in range(2):\n            decoder_output = model._spec.description.output[i].SerializeToString()\n            nms_spec.description.input.add()\n            nms_spec.description.input[i].ParseFromString(decoder_output)\n            nms_spec.description.output.add()\n            nms_spec.description.output[i].ParseFromString(decoder_output)\n\n        nms_spec.description.output[0].name = 'confidence'\n        nms_spec.description.output[1].name = 'coordinates'\n\n        output_sizes = [nc, 4]\n        for i in range(2):\n            ma_type = nms_spec.description.output[i].type.multiArrayType\n            ma_type.shapeRange.sizeRanges.add()\n            ma_type.shapeRange.sizeRanges[0].lowerBound = 0\n            ma_type.shapeRange.sizeRanges[0].upperBound = -1\n            ma_type.shapeRange.sizeRanges.add()\n            ma_type.shapeRange.sizeRanges[1].lowerBound = output_sizes[i]\n            ma_type.shapeRange.sizeRanges[1].upperBound = output_sizes[i]\n            del ma_type.shape[:]\n\n        nms = nms_spec.nonMaximumSuppression\n        nms.confidenceInputFeatureName = out0.name  # 1x507x80\n        nms.coordinatesInputFeatureName = out1.name  # 1x507x4\n        nms.confidenceOutputFeatureName = 'confidence'\n        nms.coordinatesOutputFeatureName = 'coordinates'\n        nms.iouThresholdInputFeatureName = 'iouThreshold'\n        nms.confidenceThresholdInputFeatureName = 'confidenceThreshold'\n        nms.iouThreshold = 0.45\n        nms.confidenceThreshold = 0.25\n        nms.pickTop.perClass = True\n        nms.stringClassLabels.vector.extend(names.values())\n        nms_model = ct.models.MLModel(nms_spec)\n\n        # 4. Pipeline models together\n        pipeline = ct.models.pipeline.Pipeline(input_features=[('image', ct.models.datatypes.Array(3, ny, nx)),\n                                                               ('iouThreshold', ct.models.datatypes.Double()),\n                                                               ('confidenceThreshold', ct.models.datatypes.Double())],\n                                               output_features=['confidence', 'coordinates'])\n        pipeline.add_model(model)\n        pipeline.add_model(nms_model)\n\n        # Correct datatypes\n        pipeline.spec.description.input[0].ParseFromString(model._spec.description.input[0].SerializeToString())\n        pipeline.spec.description.output[0].ParseFromString(nms_model._spec.description.output[0].SerializeToString())\n        pipeline.spec.description.output[1].ParseFromString(nms_model._spec.description.output[1].SerializeToString())\n\n        # Update metadata\n        pipeline.spec.specificationVersion = 5\n        pipeline.spec.description.metadata.userDefined.update({\n            'IoU threshold': str(nms.iouThreshold),\n            'Confidence threshold': str(nms.confidenceThreshold)})\n\n        # Save the model\n        model = ct.models.MLModel(pipeline.spec)\n        model.input_description['image'] = 'Input image'\n        model.input_description['iouThreshold'] = f'(optional) IOU threshold override (default: {nms.iouThreshold})'\n        model.input_description['confidenceThreshold'] = \\\n            f'(optional) Confidence threshold override (default: {nms.confidenceThreshold})'\n        model.output_description['confidence'] = 'Boxes × Class confidence (see user-defined metadata \"classes\")'\n        model.output_description['coordinates'] = 'Boxes × [x, y, width, height] (relative to image size)'\n        LOGGER.info(f'{prefix} pipeline success')\n        return model\n\n    def add_callback(self, event: str, callback):\n        \"\"\"\n        Appends the given callback.\n        \"\"\"\n        self.callbacks[event].append(callback)\n\n    def run_callbacks(self, event: str):\n        \"\"\"Execute all callbacks for a given event.\"\"\"\n        for callback in self.callbacks.get(event, []):\n            callback(self)\n\n\nclass iOSDetectModel(torch.nn.Module):\n    \"\"\"Wrap an Ultralytics YOLO model for iOS export.\"\"\"\n\n    def __init__(self, model, im):\n        \"\"\"Initialize the iOSDetectModel class with a YOLO model and example image.\"\"\"\n        super().__init__()\n        b, c, h, w = im.shape  # batch, channel, height, width\n        self.model = model\n        self.nc = len(model.names)  # number of classes\n        if w == h:\n            self.normalize = 1.0 / w  # scalar\n        else:\n            self.normalize = torch.tensor([1.0 / w, 1.0 / h, 1.0 / w, 1.0 / h])  # broadcast (slower, smaller)\n\n    def forward(self, x):\n        \"\"\"Normalize predictions of object detection model with input size-dependent factors.\"\"\"\n        xywh, cls = self.model(x)[0].transpose(0, 1).split((4, self.nc), 1)\n        return cls, xywh * self.normalize  # confidence (3780, 80), coordinates (3780, 4)\n\n\ndef export(cfg=DEFAULT_CFG):\n    \"\"\"Export a YOLOv model to a specific format.\"\"\"\n    cfg.model = cfg.model or 'yolov8n.yaml'\n    cfg.format = cfg.format or 'torchscript'\n\n    from ultralytics import YOLO\n    model = YOLO(cfg.model)\n    model.export(**vars(cfg))\n\n\nif __name__ == '__main__':\n    \"\"\"\n    CLI:\n    yolo mode=export model=yolov8n.yaml format=onnx\n    \"\"\"\n    export()\n"
  },
  {
    "path": "ultralytics/yolo/engine/model.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport sys\nfrom pathlib import Path\nfrom typing import Union\n\nfrom ultralytics import yolo  # noqa\nfrom ultralytics.nn.tasks import (ClassificationModel, DetectionModel, PoseModel, SegmentationModel, MultiModel,\n                                  attempt_load_one_weight, guess_model_task, nn, yaml_model_load)\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.engine.exporter import Exporter\nfrom ultralytics.yolo.utils import (DEFAULT_CFG, DEFAULT_CFG_DICT, DEFAULT_CFG_KEYS, LOGGER, RANK, ROOT, callbacks,\n                                    is_git_dir, yaml_load)\nfrom ultralytics.yolo.utils.checks import check_file, check_imgsz, check_pip_update_available, check_yaml\nfrom ultralytics.yolo.utils.downloads import GITHUB_ASSET_STEMS\nfrom ultralytics.yolo.utils.torch_utils import smart_inference_mode\n\n# Map head to model, trainer, validator, and predictor classes\n# TASK_MAP = {\n#     'classify': [\n#         ClassificationModel, yolo.v8.classify.ClassificationTrainer, yolo.v8.classify.ClassificationValidator,\n#         yolo.v8.classify.ClassificationPredictor],\n#     'detect': [\n#         DetectionModel, yolo.v8.detect.DetectionTrainer, yolo.v8.detect.DetectionValidator,\n#         yolo.v8.detect.DetectionPredictor],\n#     'segment': [\n#         SegmentationModel, yolo.v8.segment.SegmentationTrainer, yolo.v8.segment.SegmentationValidator,\n#         yolo.v8.segment.SegmentationPredictor],\n#     'pose': [PoseModel, yolo.v8.pose.PoseTrainer, yolo.v8.pose.PoseValidator, yolo.v8.pose.PosePredictor]}\n\nTASK_MAP = {\n    'classify': [\n        ClassificationModel, yolo.v8.classify.ClassificationTrainer, yolo.v8.classify.ClassificationValidator,\n        yolo.v8.classify.ClassificationPredictor],\n    'detect': [\n        DetectionModel, yolo.v8.detect.DetectionTrainer, yolo.v8.detect.DetectionValidator,\n        yolo.v8.detect.DetectionPredictor],\n    'segment': [\n        SegmentationModel, yolo.v8.segment.SegmentationTrainer, yolo.v8.segment.SegmentationValidator,\n        yolo.v8.segment.SegmentationPredictor],\n    'pose': [PoseModel, yolo.v8.pose.PoseTrainer, yolo.v8.pose.PoseValidator, yolo.v8.pose.PosePredictor],\n    'multi': [\n        MultiModel, yolo.v8.DecSeg.DetectionSegmentationTrainer, yolo.v8.DecSeg.MultiValidator,\n        yolo.v8.DecSeg.MultiPredictor]\n}\n\n\nclass YOLO:\n    \"\"\"\n    YOLO (You Only Look Once) object detection model.\n\n    Args:\n        model (str, Path): Path to the model file to load or create.\n        task (Any, optional): Task type for the YOLO model. Defaults to None.\n\n    Attributes:\n        predictor (Any): The predictor object.\n        model (Any): The model object.\n        trainer (Any): The trainer object.\n        task (str): The type of model task.\n        ckpt (Any): The checkpoint object if the model loaded from *.pt file.\n        cfg (str): The model configuration if loaded from *.yaml file.\n        ckpt_path (str): The checkpoint file path.\n        overrides (dict): Overrides for the trainer object.\n        metrics (Any): The data for metrics.\n\n    Methods:\n        __call__(source=None, stream=False, **kwargs):\n            Alias for the predict method.\n        _new(cfg:str, verbose:bool=True) -> None:\n            Initializes a new model and infers the task type from the model definitions.\n        _load(weights:str, task:str='') -> None:\n            Initializes a new model and infers the task type from the model head.\n        _check_is_pytorch_model() -> None:\n            Raises TypeError if the model is not a PyTorch model.\n        reset() -> None:\n            Resets the model modules.\n        info(verbose:bool=False) -> None:\n            Logs the model info.\n        fuse() -> None:\n            Fuses the model for faster inference.\n        predict(source=None, stream=False, **kwargs) -> List[ultralytics.yolo.engine.results.Results]:\n            Performs prediction using the YOLO model.\n\n    Returns:\n        list(ultralytics.yolo.engine.results.Results): The prediction results.\n    \"\"\"\n\n    def __init__(self, model: Union[str, Path] = 'yolov8n.pt', task=None) -> None:\n        \"\"\"\n        Initializes the YOLO model.\n\n        Args:\n            model (Union[str, Path], optional): Path or name of the model to load or create. Defaults to 'yolov8n.pt'.\n            task (Any, optional): Task type for the YOLO model. Defaults to None.\n        \"\"\"\n        self.callbacks = callbacks.get_default_callbacks()\n        self.predictor = None  # reuse predictor\n        self.model = None  # model object\n        self.trainer = None  # trainer object\n        self.task = None  # task type\n        self.ckpt = None  # if loaded from *.pt\n        self.cfg = None  # if loaded from *.yaml\n        self.ckpt_path = None\n        self.overrides = {}  # overrides for trainer object\n        self.metrics = None  # validation/training metrics\n        self.session = None  # HUB session\n        model = str(model).strip()  # strip spaces\n\n        # Check if Ultralytics HUB model from https://hub.ultralytics.com\n        if self.is_hub_model(model):\n            from ultralytics.hub.session import HUBTrainingSession\n            self.session = HUBTrainingSession(model)\n            model = self.session.model_file\n\n        # Load or create new YOLO model\n        suffix = Path(model).suffix\n        if not suffix and Path(model).stem in GITHUB_ASSET_STEMS:\n            model, suffix = Path(model).with_suffix('.pt'), '.pt'  # add suffix, i.e. yolov8n -> yolov8n.pt\n        if suffix == '.yaml':\n            self._new(model, task)\n        else:\n            self._load(model, task)\n\n    def __call__(self, source=None, stream=False, **kwargs):\n        \"\"\"Calls the 'predict' function with given arguments to perform object detection.\"\"\"\n        return self.predict(source, stream, **kwargs)\n\n    def __getattr__(self, attr):\n        \"\"\"Raises error if object has no requested attribute.\"\"\"\n        name = self.__class__.__name__\n        raise AttributeError(f\"'{name}' object has no attribute '{attr}'. See valid attributes below.\\n{self.__doc__}\")\n\n    @staticmethod\n    def is_hub_model(model):\n        \"\"\"Check if the provided model is a HUB model.\"\"\"\n        return any((\n            model.startswith('https://hub.ultra'),  # i.e. https://hub.ultralytics.com/models/MODEL_ID\n            [len(x) for x in model.split('_')] == [42, 20],  # APIKEY_MODELID\n            len(model) == 20 and not Path(model).exists() and all(x not in model for x in './\\\\')))  # MODELID\n\n    def _new(self, cfg: str, task=None, verbose=True):\n        \"\"\"\n        Initializes a new model and infers the task type from the model definitions.\n\n        Args:\n            cfg (str): model configuration file\n            task (str) or (None): model task\n            verbose (bool): display model info on load\n        \"\"\"\n        cfg_dict = yaml_model_load(cfg)\n        self.cfg = cfg\n        self.task = task or guess_model_task(cfg_dict)\n        self.model = TASK_MAP[self.task][0](cfg_dict, verbose=verbose and RANK == -1)  # build model\n        self.overrides['model'] = self.cfg\n\n        # Below added to allow export from yamls\n        args = {**DEFAULT_CFG_DICT, **self.overrides}  # combine model and default args, preferring model args\n        self.model.args = {k: v for k, v in args.items() if k in DEFAULT_CFG_KEYS}  # attach args to model\n        self.model.task = self.task\n\n    def _load(self, weights: str, task=None):\n        \"\"\"\n        Initializes a new model and infers the task type from the model head.\n\n        Args:\n            weights (str): model checkpoint to be loaded\n            task (str) or (None): model task\n        \"\"\"\n        suffix = Path(weights).suffix\n        if suffix == '.pt':\n            self.model, self.ckpt = attempt_load_one_weight(weights)\n            self.task = self.model.args['task']\n            self.overrides = self.model.args = self._reset_ckpt_args(self.model.args)\n            self.ckpt_path = self.model.pt_path\n        else:\n            weights = check_file(weights)\n            self.model, self.ckpt = weights, None\n            self.task = task or guess_model_task(weights)\n            self.ckpt_path = weights\n        self.overrides['model'] = weights\n        self.overrides['task'] = self.task\n\n    def _check_is_pytorch_model(self):\n        \"\"\"\n        Raises TypeError is model is not a PyTorch model\n        \"\"\"\n        pt_str = isinstance(self.model, (str, Path)) and Path(self.model).suffix == '.pt'\n        pt_module = isinstance(self.model, nn.Module)\n        if not (pt_module or pt_str):\n            raise TypeError(f\"model='{self.model}' must be a *.pt PyTorch model, but is a different type. \"\n                            f'PyTorch models can be used to train, val, predict and export, i.e. '\n                            f\"'yolo export model=yolov8n.pt', but exported formats like ONNX, TensorRT etc. only \"\n                            f\"support 'predict' and 'val' modes, i.e. 'yolo predict model=yolov8n.onnx'.\")\n\n    @smart_inference_mode()\n    def reset_weights(self):\n        \"\"\"\n        Resets the model modules parameters to randomly initialized values, losing all training information.\n        \"\"\"\n        self._check_is_pytorch_model()\n        for m in self.model.modules():\n            if hasattr(m, 'reset_parameters'):\n                m.reset_parameters()\n        for p in self.model.parameters():\n            p.requires_grad = True\n        return self\n\n    @smart_inference_mode()\n    def load(self, weights='yolov8n.pt'):\n        \"\"\"\n        Transfers parameters with matching names and shapes from 'weights' to model.\n        \"\"\"\n        self._check_is_pytorch_model()\n        if isinstance(weights, (str, Path)):\n            weights, self.ckpt = attempt_load_one_weight(weights)\n        self.model.load(weights)\n        return self\n\n    def info(self, detailed=False, verbose=True):\n        \"\"\"\n        Logs model info.\n\n        Args:\n            detailed (bool): Show detailed information about model.\n            verbose (bool): Controls verbosity.\n        \"\"\"\n        self._check_is_pytorch_model()\n        return self.model.info(detailed=detailed, verbose=verbose)\n\n    def fuse(self):\n        \"\"\"Fuse PyTorch Conv2d and BatchNorm2d layers.\"\"\"\n        self._check_is_pytorch_model()\n        self.model.fuse()\n\n    @smart_inference_mode()\n    def predict(self, source=None, stream=False, **kwargs):\n        \"\"\"\n        Perform prediction using the YOLO model.\n\n        Args:\n            source (str | int | PIL | np.ndarray): The source of the image to make predictions on.\n                          Accepts all source types accepted by the YOLO model.\n            stream (bool): Whether to stream the predictions or not. Defaults to False.\n            **kwargs : Additional keyword arguments passed to the predictor.\n                       Check the 'configuration' section in the documentation for all available options.\n\n        Returns:\n            (List[ultralytics.yolo.engine.results.Results]): The prediction results.\n        \"\"\"\n        if source is None:\n            source = ROOT / 'assets' if is_git_dir() else 'https://ultralytics.com/images/bus.jpg'\n            LOGGER.warning(f\"WARNING ⚠️ 'source' is missing. Using 'source={source}'.\")\n        is_cli = (sys.argv[0].endswith('yolo') or sys.argv[0].endswith('ultralytics')) and any(\n            x in sys.argv for x in ('predict', 'track', 'mode=predict', 'mode=track'))\n        overrides = self.overrides.copy()\n        overrides['conf'] = 0.25\n        overrides.update(kwargs)  # prefer kwargs\n        overrides['mode'] = kwargs.get('mode', 'predict')\n        assert overrides['mode'] in ['track', 'predict']\n        if not is_cli:\n            overrides['save'] = kwargs.get('save', False)  # do not save by default if called in Python\n        if not self.predictor:\n            self.task = overrides.get('task') or self.task\n            self.predictor = TASK_MAP[self.task][3](overrides=overrides, _callbacks=self.callbacks)\n            self.predictor.setup_model(model=self.model, verbose=is_cli)\n        else:  # only update args if predictor is already setup\n            self.predictor.args = get_cfg(self.predictor.args, overrides)\n        return self.predictor.predict_cli(source=source) if is_cli else self.predictor(source=source, stream=stream)\n\n    def track(self, source=None, stream=False, persist=False, **kwargs):\n        \"\"\"\n        Perform object tracking on the input source using the registered trackers.\n\n        Args:\n            source (str, optional): The input source for object tracking. Can be a file path or a video stream.\n            stream (bool, optional): Whether the input source is a video stream. Defaults to False.\n            persist (bool, optional): Whether to persist the trackers if they already exist. Defaults to False.\n            **kwargs (optional): Additional keyword arguments for the tracking process.\n\n        Returns:\n            (List[ultralytics.yolo.engine.results.Results]): The tracking results.\n\n        \"\"\"\n        if not hasattr(self.predictor, 'trackers'):\n            from ultralytics.tracker import register_tracker\n            register_tracker(self, persist)\n        # ByteTrack-based method needs low confidence predictions as input\n        conf = kwargs.get('conf') or 0.1\n        kwargs['conf'] = conf\n        kwargs['mode'] = 'track'\n        return self.predict(source=source, stream=stream, **kwargs)\n\n    @smart_inference_mode()\n    def val(self, data=None, **kwargs):\n        \"\"\"\n        Validate a model on a given dataset.\n\n        Args:\n            data (str): The dataset to validate on. Accepts all formats accepted by yolo\n            **kwargs : Any other args accepted by the validators. To see all args check 'configuration' section in docs\n        \"\"\"\n        overrides = self.overrides.copy()\n        overrides['rect'] = True  # rect batches as default\n        overrides.update(kwargs)\n        overrides['mode'] = 'val'\n        args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)\n        args.data = data or args.data\n        if 'task' in overrides:\n            self.task = args.task\n        else:\n            args.task = self.task\n        if args.imgsz == DEFAULT_CFG.imgsz and not isinstance(self.model, (str, Path)):\n            args.imgsz = self.model.args['imgsz']  # use trained imgsz unless custom value is passed\n        args.imgsz = check_imgsz(args.imgsz, max_dim=1)\n\n        validator = TASK_MAP[self.task][2](args=args, _callbacks=self.callbacks)\n        validator(model=self.model)\n        self.metrics = validator.metrics\n\n        return validator.metrics\n\n    @smart_inference_mode()\n    def benchmark(self, **kwargs):\n        \"\"\"\n        Benchmark a model on all export formats.\n\n        Args:\n            **kwargs : Any other args accepted by the validators. To see all args check 'configuration' section in docs\n        \"\"\"\n        self._check_is_pytorch_model()\n        from ultralytics.yolo.utils.benchmarks import benchmark\n        overrides = self.model.args.copy()\n        overrides.update(kwargs)\n        overrides['mode'] = 'benchmark'\n        overrides = {**DEFAULT_CFG_DICT, **overrides}  # fill in missing overrides keys with defaults\n        return benchmark(model=self, imgsz=overrides['imgsz'], half=overrides['half'], device=overrides['device'])\n\n    def export(self, **kwargs):\n        \"\"\"\n        Export model.\n\n        Args:\n            **kwargs : Any other args accepted by the predictors. To see all args check 'configuration' section in docs\n        \"\"\"\n        self._check_is_pytorch_model()\n        overrides = self.overrides.copy()\n        overrides.update(kwargs)\n        overrides['mode'] = 'export'\n        args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)\n        args.task = self.task\n        if args.imgsz == DEFAULT_CFG.imgsz:\n            args.imgsz = self.model.args['imgsz']  # use trained imgsz unless custom value is passed\n        if args.batch == DEFAULT_CFG.batch:\n            args.batch = 1  # default to 1 if not modified\n        return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model)\n\n    def train(self, **kwargs):\n        \"\"\"\n        Trains the model on a given dataset.\n\n        Args:\n            **kwargs (Any): Any number of arguments representing the training configuration.\n        \"\"\"\n        self._check_is_pytorch_model()\n        if self.session:  # Ultralytics HUB session\n            if any(kwargs):\n                LOGGER.warning('WARNING ⚠️ using HUB training arguments, ignoring local training arguments.')\n            kwargs = self.session.train_args\n        check_pip_update_available()\n        overrides = self.overrides.copy()\n        overrides.update(kwargs)\n        if kwargs.get('cfg'):\n            LOGGER.info(f\"cfg file passed. Overriding default params with {kwargs['cfg']}.\")\n            overrides = yaml_load(check_yaml(kwargs['cfg']))\n        overrides['mode'] = 'train'\n        if not overrides.get('data'):\n            raise AttributeError(\"Dataset required but missing, i.e. pass 'data=coco128.yaml'\")\n        if overrides.get('resume'):\n            overrides['resume'] = self.ckpt_path\n        self.task = overrides.get('task') or self.task\n        self.trainer = TASK_MAP[self.task][1](overrides=overrides, _callbacks=self.callbacks)\n        if not overrides.get('resume'):  # manually set model only if not resuming\n            self.trainer.model = self.trainer.get_model(weights=self.model if self.ckpt else None, cfg=self.model.yaml)\n            self.model = self.trainer.model\n        self.trainer.hub_session = self.session  # attach optional HUB session\n        self.trainer.train()\n        # Update model and cfg after training\n        if RANK in (-1, 0):\n            if self.trainer.args.val:\n                self.model, _ = attempt_load_one_weight(str(self.trainer.best))\n            else:\n                self.model, _ = attempt_load_one_weight(str(self.trainer.last))\n            self.overrides = self.model.args\n            self.metrics = getattr(self.trainer.validator, 'metrics', None)  # TODO: no metrics returned by DDP\n\n    def to(self, device):\n        \"\"\"\n        Sends the model to the given device.\n\n        Args:\n            device (str): device\n        \"\"\"\n        self._check_is_pytorch_model()\n        self.model.to(device)\n\n    def tune(self,\n             data: str,\n             space: dict = None,\n             grace_period: int = 10,\n             gpu_per_trial: int = None,\n             max_samples: int = 10,\n             train_args: dict = {}):\n        \"\"\"\n        Runs hyperparameter tuning using Ray Tune.\n\n        Args:\n            data (str): The dataset to run the tuner on.\n            space (dict, optional): The hyperparameter search space. Defaults to None.\n            grace_period (int, optional): The grace period in epochs of the ASHA scheduler. Defaults to 10.\n            gpu_per_trial (int, optional): The number of GPUs to allocate per trial. Defaults to None.\n            max_samples (int, optional): The maximum number of trials to run. Defaults to 10.\n            train_args (dict, optional): Additional arguments to pass to the `train()` method. Defaults to {}.\n\n        Returns:\n            (dict): A dictionary containing the results of the hyperparameter search.\n\n        Raises:\n            ModuleNotFoundError: If Ray Tune is not installed.\n        \"\"\"\n\n        try:\n            from ultralytics.yolo.utils.tuner import (ASHAScheduler, RunConfig, WandbLoggerCallback, default_space,\n                                                      task_metric_map, tune)\n        except ImportError:\n            raise ModuleNotFoundError(\"Install Ray Tune: `pip install 'ray[tune]'`\")\n\n        try:\n            import wandb\n            from wandb import __version__  # noqa\n        except ImportError:\n            wandb = False\n\n        def _tune(config):\n            \"\"\"\n            Trains the YOLO model with the specified hyperparameters and additional arguments.\n\n            Args:\n                config (dict): A dictionary of hyperparameters to use for training.\n\n            Returns:\n                None.\n            \"\"\"\n            self._reset_callbacks()\n            config.update(train_args)\n            self.train(**config)\n\n        if not space:\n            LOGGER.warning('WARNING: search space not provided. Using default search space')\n            space = default_space\n\n        space['data'] = data\n\n        # Define the trainable function with allocated resources\n        trainable_with_resources = tune.with_resources(_tune, {'cpu': 8, 'gpu': gpu_per_trial if gpu_per_trial else 0})\n\n        # Define the ASHA scheduler for hyperparameter search\n        asha_scheduler = ASHAScheduler(time_attr='epoch',\n                                       metric=task_metric_map[self.task],\n                                       mode='max',\n                                       max_t=train_args.get('epochs') or 100,\n                                       grace_period=grace_period,\n                                       reduction_factor=3)\n\n        # Define the callbacks for the hyperparameter search\n        tuner_callbacks = [WandbLoggerCallback(project='yolov8_tune')] if wandb else []\n\n        # Create the Ray Tune hyperparameter search tuner\n        tuner = tune.Tuner(trainable_with_resources,\n                           param_space=space,\n                           tune_config=tune.TuneConfig(scheduler=asha_scheduler, num_samples=max_samples),\n                           run_config=RunConfig(callbacks=tuner_callbacks, local_dir='./runs'))\n\n        # Run the hyperparameter search\n        tuner.fit()\n\n        # Return the results of the hyperparameter search\n        return tuner.get_results()\n\n    @property\n    def names(self):\n        \"\"\"Returns class names of the loaded model.\"\"\"\n        return self.model.names if hasattr(self.model, 'names') else None\n\n    @property\n    def device(self):\n        \"\"\"Returns device if PyTorch model.\"\"\"\n        return next(self.model.parameters()).device if isinstance(self.model, nn.Module) else None\n\n    @property\n    def transforms(self):\n        \"\"\"Returns transform of the loaded model.\"\"\"\n        return self.model.transforms if hasattr(self.model, 'transforms') else None\n\n    def add_callback(self, event: str, func):\n        \"\"\"Add a callback.\"\"\"\n        self.callbacks[event].append(func)\n\n    def clear_callback(self, event: str):\n        \"\"\"Clear all event callbacks.\"\"\"\n        self.callbacks[event] = []\n\n    @staticmethod\n    def _reset_ckpt_args(args):\n        \"\"\"Reset arguments when loading a PyTorch model.\"\"\"\n        include = {'imgsz', 'data', 'task', 'single_cls'}  # only remember these arguments when loading a PyTorch model\n        return {k: v for k, v in args.items() if k in include}\n\n    def _reset_callbacks(self):\n        \"\"\"Reset all registered callbacks.\"\"\"\n        for event in callbacks.default_callbacks.keys():\n            self.callbacks[event] = [callbacks.default_callbacks[event][0]]\n"
  },
  {
    "path": "ultralytics/yolo/engine/predictor.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nRun prediction on images, videos, directories, globs, YouTube, webcam, streams, etc.\n\nUsage - sources:\n    $ yolo mode=predict model=yolov8n.pt source=0                               # webcam\n                                                img.jpg                         # image\n                                                vid.mp4                         # video\n                                                screen                          # screenshot\n                                                path/                           # directory\n                                                list.txt                        # list of images\n                                                list.streams                    # list of streams\n                                                'path/*.jpg'                    # glob\n                                                'https://youtu.be/Zgi9g1ksQHc'  # YouTube\n                                                'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP stream\n\nUsage - formats:\n    $ yolo mode=predict model=yolov8n.pt                 # PyTorch\n                              yolov8n.torchscript        # TorchScript\n                              yolov8n.onnx               # ONNX Runtime or OpenCV DNN with dnn=True\n                              yolov8n_openvino_model     # OpenVINO\n                              yolov8n.engine             # TensorRT\n                              yolov8n.mlmodel            # CoreML (macOS-only)\n                              yolov8n_saved_model        # TensorFlow SavedModel\n                              yolov8n.pb                 # TensorFlow GraphDef\n                              yolov8n.tflite             # TensorFlow Lite\n                              yolov8n_edgetpu.tflite     # TensorFlow Edge TPU\n                              yolov8n_paddle_model       # PaddlePaddle\n\"\"\"\nimport platform\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport torch\n\nfrom ultralytics.nn.autobackend import AutoBackend\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.data import load_inference_source\nfrom ultralytics.yolo.data.augment import LetterBox, classify_transforms\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, SETTINGS, callbacks, colorstr, ops\nfrom ultralytics.yolo.utils.checks import check_imgsz, check_imshow\nfrom ultralytics.yolo.utils.files import increment_path\nfrom ultralytics.yolo.utils.torch_utils import select_device, smart_inference_mode\n\nSTREAM_WARNING = \"\"\"\n    WARNING ⚠️ stream/video/webcam/dir predict source will accumulate results in RAM unless `stream=True` is passed,\n    causing potential out-of-memory errors for large sources or long-running streams/videos.\n\n    Usage:\n        results = model(source=..., stream=True)  # generator of Results objects\n        for r in results:\n            boxes = r.boxes  # Boxes object for bbox outputs\n            masks = r.masks  # Masks object for segment masks outputs\n            probs = r.probs  # Class probabilities for classification outputs\n\"\"\"\n\n\nclass BasePredictor:\n    \"\"\"\n    BasePredictor\n\n    A base class for creating predictors.\n\n    Attributes:\n        args (SimpleNamespace): Configuration for the predictor.\n        save_dir (Path): Directory to save results.\n        done_setup (bool): Whether the predictor has finished setup.\n        model (nn.Module): Model used for prediction.\n        data (dict): Data configuration.\n        device (torch.device): Device used for prediction.\n        dataset (Dataset): Dataset used for prediction.\n        vid_path (str): Path to video file.\n        vid_writer (cv2.VideoWriter): Video writer for saving video output.\n        annotator (Annotator): Annotator used for prediction.\n        data_path (str): Path to data.\n    \"\"\"\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        \"\"\"\n        Initializes the BasePredictor class.\n\n        Args:\n            cfg (str, optional): Path to a configuration file. Defaults to DEFAULT_CFG.\n            overrides (dict, optional): Configuration overrides. Defaults to None.\n        \"\"\"\n        self.args = get_cfg(cfg, overrides)\n        project = self.args.project or Path(SETTINGS['runs_dir']) / self.args.task\n        name = self.args.name or f'{self.args.mode}'\n        self.save_dir = increment_path(Path(project) / name, exist_ok=self.args.exist_ok)\n        if self.args.conf is None:\n            self.args.conf = 0.25  # default conf=0.25\n        self.done_warmup = False\n        if self.args.show:\n            self.args.show = check_imshow(warn=True)\n\n        # Usable if setup is done\n        self.model = None\n        self.data = self.args.data  # data_dict\n        self.imgsz = None\n        self.device = None\n        self.dataset = None\n        self.vid_path, self.vid_writer = None, None\n        self.plotted_img = None\n        self.data_path = None\n        self.source_type = None\n        self.batch = None\n        self.callbacks = _callbacks or callbacks.get_default_callbacks()\n        callbacks.add_integration_callbacks(self)\n\n    def preprocess(self, im):\n        \"\"\"Prepares input image before inference.\n\n        Args:\n            im (torch.Tensor | List(np.ndarray)): (N, 3, h, w) for tensor, [(h, w, 3) x N] for list.\n        \"\"\"\n        if not isinstance(im, torch.Tensor):\n            im = np.stack(self.pre_transform(im))\n            im = im[..., ::-1].transpose((0, 3, 1, 2))  # BGR to RGB, BHWC to BCHW, (n, 3, h, w)\n            im = np.ascontiguousarray(im)  # contiguous\n            im = torch.from_numpy(im)\n        # NOTE: assuming im with (b, 3, h, w) if it's a tensor\n        img = im.to(self.device)\n        img = img.half() if self.model.fp16 else img.float()  # uint8 to fp16/32\n        img /= 255  # 0 - 255 to 0.0 - 1.0\n        return img\n\n    def pre_transform(self, im):\n        \"\"\"Pre-tranform input image before inference.\n\n        Args:\n            im (List(np.ndarray)): (N, 3, h, w) for tensor, [(h, w, 3) x N] for list.\n\n        Return: A list of transformed imgs.\n        \"\"\"\n        same_shapes = all(x.shape == im[0].shape for x in im)\n        auto = same_shapes and self.model.pt\n        return [LetterBox(self.imgsz, auto=auto, stride=self.model.stride)(image=x) for x in im]\n\n    def write_results(self, idx, results, batch):\n        \"\"\"Write inference results to a file or directory.\"\"\"\n        p, im, _ = batch\n        log_string = ''\n        if len(im.shape) == 3:\n            im = im[None]  # expand for batch dim\n        self.seen += 1\n        if self.source_type.webcam or self.source_type.from_img:  # batch_size >= 1\n            log_string += f'{idx}: '\n            frame = self.dataset.count\n        else:\n            frame = getattr(self.dataset, 'frame', 0)\n        self.data_path = p\n        self.txt_path = str(self.save_dir / 'labels' / p.stem) + ('' if self.dataset.mode == 'image' else f'_{frame}')\n        log_string += '%gx%g ' % im.shape[2:]  # print string\n        result = results[idx]\n        log_string += result.verbose()\n\n        if self.args.save or self.args.show:  # Add bbox to image\n            plot_args = dict(line_width=self.args.line_width,\n                             boxes=self.args.boxes,\n                             conf=self.args.show_conf,\n                             labels=self.args.show_labels)\n            if not self.args.retina_masks:\n                plot_args['im_gpu'] = im[idx]\n            self.plotted_img = result.plot(**plot_args)\n        # Write\n        if self.args.save_txt:\n            result.save_txt(f'{self.txt_path}.txt', save_conf=self.args.save_conf)\n        if self.args.save_crop:\n            result.save_crop(save_dir=self.save_dir / 'crops', file_name=self.data_path.stem)\n\n        return log_string\n\n    def postprocess(self, preds, img, orig_img):\n        \"\"\"Post-processes predictions for an image and returns them.\"\"\"\n        return preds\n\n    def __call__(self, source=None, model=None, stream=False):\n        \"\"\"Performs inference on an image or stream.\"\"\"\n        self.stream = stream\n        if stream:\n            return self.stream_inference(source, model)\n        else:\n            return list(self.stream_inference(source, model))  # merge list of Result into one\n\n    def predict_cli(self, source=None, model=None):\n        \"\"\"Method used for CLI prediction. It uses always generator as outputs as not required by CLI mode.\"\"\"\n        gen = self.stream_inference(source, model)\n        for _ in gen:  # running CLI inference without accumulating any outputs (do not modify)\n            pass\n\n    def setup_source(self, source):\n        \"\"\"Sets up source and inference mode.\"\"\"\n        self.imgsz = check_imgsz(self.args.imgsz, stride=self.model.stride, min_dim=2)  # check image size\n        self.transforms = getattr(self.model.model, 'transforms', classify_transforms(\n            self.imgsz[0])) if self.args.task == 'classify' else None\n        self.dataset = load_inference_source(source=source, imgsz=self.imgsz, vid_stride=self.args.vid_stride)\n        self.source_type = self.dataset.source_type\n        if not getattr(self, 'stream', True) and (self.dataset.mode == 'stream' or  # streams\n                                                  len(self.dataset) > 1000 or  # images\n                                                  any(getattr(self.dataset, 'video_flag', [False]))):  # videos\n            LOGGER.warning(STREAM_WARNING)\n        self.vid_path, self.vid_writer = [None] * self.dataset.bs, [None] * self.dataset.bs\n\n    @smart_inference_mode()\n    def stream_inference(self, source=None, model=None):\n        \"\"\"Streams real-time inference on camera feed and saves results to file.\"\"\"\n        if self.args.verbose:\n            LOGGER.info('')\n\n        # Setup model\n        if not self.model:\n            self.setup_model(model)\n        # Setup source every time predict is called\n        self.setup_source(source if source is not None else self.args.source)\n\n        # Check if save_dir/ label file exists\n        if self.args.save or self.args.save_txt:\n            (self.save_dir / 'labels' if self.args.save_txt else self.save_dir).mkdir(parents=True, exist_ok=True)\n        # Warmup model\n        if not self.done_warmup:\n            self.model.warmup(imgsz=(1 if self.model.pt or self.model.triton else self.dataset.bs, 3, *self.imgsz))\n            self.done_warmup = True\n\n        self.seen, self.windows, self.batch, profilers = 0, [], None, (ops.Profile(), ops.Profile(), ops.Profile())\n        self.run_callbacks('on_predict_start')\n        for batch in self.dataset:\n            self.run_callbacks('on_predict_batch_start')\n            self.batch = batch\n            path, im0s, vid_cap, s = batch\n            visualize = increment_path(self.save_dir / Path(path[0]).stem,\n                                       mkdir=True) if self.args.visualize and (not self.source_type.tensor) else False\n\n            # Preprocess\n            with profilers[0]:\n                im = self.preprocess(im0s)\n\n            # Inference\n            with profilers[1]:\n                preds = self.model(im, augment=self.args.augment, visualize=visualize)\n\n            # Postprocess\n            with profilers[2]:\n                self.results = self.postprocess(preds, im, im0s)\n            self.run_callbacks('on_predict_postprocess_end')\n\n            # Visualize, save, write results\n            n = len(im0s)\n            for i in range(n):\n                self.results[i].speed = {\n                    'preprocess': profilers[0].dt * 1E3 / n,\n                    'inference': profilers[1].dt * 1E3 / n,\n                    'postprocess': profilers[2].dt * 1E3 / n}\n                if self.source_type.tensor:  # skip write, show and plot operations if input is raw tensor\n                    continue\n                p, im0 = path[i], im0s[i].copy()\n                p = Path(p)\n\n                if self.args.verbose or self.args.save or self.args.save_txt or self.args.show:\n                    s += self.write_results(i, self.results, (p, im, im0))\n\n                if self.args.show and self.plotted_img is not None:\n                    self.show(p)\n\n                if self.args.save and self.plotted_img is not None:\n                    self.save_preds(vid_cap, i, str(self.save_dir / p.name))\n            self.run_callbacks('on_predict_batch_end')\n            yield from self.results\n\n            # Print time (inference-only)\n            if self.args.verbose:\n                LOGGER.info(f'{s}{profilers[1].dt * 1E3:.1f}ms')\n\n        # Release assets\n        if isinstance(self.vid_writer[-1], cv2.VideoWriter):\n            self.vid_writer[-1].release()  # release final video writer\n\n        # Print results\n        if self.args.verbose and self.seen:\n            t = tuple(x.t / self.seen * 1E3 for x in profilers)  # speeds per image\n            LOGGER.info(f'Speed: %.1fms preprocess, %.1fms inference, %.1fms postprocess per image at shape '\n                        f'{(1, 3, *self.imgsz)}' % t)\n        if self.args.save or self.args.save_txt or self.args.save_crop:\n            nl = len(list(self.save_dir.glob('labels/*.txt')))  # number of labels\n            s = f\"\\n{nl} label{'s' * (nl > 1)} saved to {self.save_dir / 'labels'}\" if self.args.save_txt else ''\n            LOGGER.info(f\"Results saved to {colorstr('bold', self.save_dir)}{s}\")\n\n        self.run_callbacks('on_predict_end')\n\n    def setup_model(self, model, verbose=True):\n        \"\"\"Initialize YOLO model with given parameters and set it to evaluation mode.\"\"\"\n        device = select_device(self.args.device, verbose=verbose)\n        model = model or self.args.model\n        self.args.half &= device.type != 'cpu'  # half precision only supported on CUDA\n        self.model = AutoBackend(model,\n                                 device=device,\n                                 dnn=self.args.dnn,\n                                 data=self.args.data,\n                                 fp16=self.args.half,\n                                 fuse=True,\n                                 verbose=verbose)\n        self.device = device\n        self.model.eval()\n\n    def show(self, p):\n        \"\"\"Display an image in a window using OpenCV imshow().\"\"\"\n        im0 = self.plotted_img\n        if platform.system() == 'Linux' and p not in self.windows:\n            self.windows.append(p)\n            cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)\n            cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])\n        cv2.imshow(str(p), im0)\n        cv2.waitKey(500 if self.batch[3].startswith('image') else 1)  # 1 millisecond\n\n    def save_preds(self, vid_cap, idx, save_path):\n        \"\"\"Save video predictions as mp4 at specified path.\"\"\"\n        im0 = self.plotted_img\n        # Save imgs\n        if self.dataset.mode == 'image':\n            cv2.imwrite(save_path, im0)\n        else:  # 'video' or 'stream'\n            if self.vid_path[idx] != save_path:  # new video\n                self.vid_path[idx] = save_path\n                if isinstance(self.vid_writer[idx], cv2.VideoWriter):\n                    self.vid_writer[idx].release()  # release previous video writer\n                if vid_cap:  # video\n                    fps = int(vid_cap.get(cv2.CAP_PROP_FPS))  # integer required, floats produce error in MP4 codec\n                    w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n                    h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n                else:  # stream\n                    fps, w, h = 30, im0.shape[1], im0.shape[0]\n                save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos\n                self.vid_writer[idx] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))\n            self.vid_writer[idx].write(im0)\n\n    def run_callbacks(self, event: str):\n        \"\"\"Runs all registered callbacks for a specific event.\"\"\"\n        for callback in self.callbacks.get(event, []):\n            callback(self)\n\n    def add_callback(self, event: str, func):\n        \"\"\"\n        Add callback\n        \"\"\"\n        self.callbacks[event].append(func)\n"
  },
  {
    "path": "ultralytics/yolo/engine/predictor_multi.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nRun prediction on images, videos, directories, globs, YouTube, webcam, streams, etc.\n\nUsage - sources:\n    $ yolo mode=predict model=yolov8n.pt source=0                               # webcam\n                                                img.jpg                         # image\n                                                vid.mp4                         # video\n                                                screen                          # screenshot\n                                                path/                           # directory\n                                                list.txt                        # list of images\n                                                list.streams                    # list of streams\n                                                'path/*.jpg'                    # glob\n                                                'https://youtu.be/Zgi9g1ksQHc'  # YouTube\n                                                'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP stream\n\nUsage - formats:\n    $ yolo mode=predict model=yolov8n.pt                 # PyTorch\n                              yolov8n.torchscript        # TorchScript\n                              yolov8n.onnx               # ONNX Runtime or OpenCV DNN with dnn=True\n                              yolov8n_openvino_model     # OpenVINO\n                              yolov8n.engine             # TensorRT\n                              yolov8n.mlmodel            # CoreML (macOS-only)\n                              yolov8n_saved_model        # TensorFlow SavedModel\n                              yolov8n.pb                 # TensorFlow GraphDef\n                              yolov8n.tflite             # TensorFlow Lite\n                              yolov8n_edgetpu.tflite     # TensorFlow Edge TPU\n                              yolov8n_paddle_model       # PaddlePaddle\n\"\"\"\nimport platform\nfrom pathlib import Path\n\nimport cv2\nimport numpy as np\nimport torch\n\nfrom ultralytics.nn.autobackend import AutoBackend\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.data import load_inference_source\nfrom ultralytics.yolo.data.augment import LetterBox, classify_transforms\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, SETTINGS, callbacks, colorstr, ops\nfrom ultralytics.yolo.utils.checks import check_imgsz, check_imshow\nfrom ultralytics.yolo.utils.files import increment_path\nfrom ultralytics.yolo.utils.torch_utils import select_device, smart_inference_mode\nimport torch.nn as nn\n\nSTREAM_WARNING = \"\"\"\n    WARNING ⚠️ stream/video/webcam/dir predict source will accumulate results in RAM unless `stream=True` is passed,\n    causing potential out-of-memory errors for large sources or long-running streams/videos.\n\n    Usage:\n        results = model(source=..., stream=True)  # generator of Results objects\n        for r in results:\n            boxes = r.boxes  # Boxes object for bbox outputs\n            masks = r.masks  # Masks object for segment masks outputs\n            probs = r.probs  # Class probabilities for classification outputs\n\"\"\"\n\n\nclass BasePredictor:\n    \"\"\"\n    BasePredictor\n\n    A base class for creating predictors.\n\n    Attributes:\n        args (SimpleNamespace): Configuration for the predictor.\n        save_dir (Path): Directory to save results.\n        done_setup (bool): Whether the predictor has finished setup.\n        model (nn.Module): Model used for prediction.\n        data (dict): Data configuration.\n        device (torch.device): Device used for prediction.\n        dataset (Dataset): Dataset used for prediction.\n        vid_path (str): Path to video file.\n        vid_writer (cv2.VideoWriter): Video writer for saving video output.\n        annotator (Annotator): Annotator used for prediction.\n        data_path (str): Path to data.\n    \"\"\"\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        \"\"\"\n        Initializes the BasePredictor class.\n\n        Args:\n            cfg (str, optional): Path to a configuration file. Defaults to DEFAULT_CFG.\n            overrides (dict, optional): Configuration overrides. Defaults to None.\n        \"\"\"\n        self.args = get_cfg(cfg, overrides)\n        project = self.args.project or Path(SETTINGS['runs_dir']) / self.args.task\n        name = self.args.name or f'{self.args.mode}'\n        self.save_dir = increment_path(Path(project) / name, exist_ok=self.args.exist_ok)\n        if self.args.conf is None:\n            self.args.conf = 0.25  # default conf=0.25\n        self.done_warmup = False\n        if self.args.show:\n            self.args.show = check_imshow(warn=True)\n\n        # Usable if setup is done\n        self.model = None\n        self.data = self.args.data  # data_dict\n        self.imgsz = None\n        self.device = None\n        self.dataset = None\n        self.vid_path, self.vid_writer = None, None\n        self.plotted_img = None\n        self.data_path = None\n        self.source_type = None\n        self.batch = None\n        self.sigmoid = nn.Sigmoid()\n        self.callbacks = _callbacks or callbacks.get_default_callbacks()\n        callbacks.add_integration_callbacks(self)\n\n    def preprocess(self, im):\n        \"\"\"Prepares input image before inference.\n\n        Args:\n            im (torch.Tensor | List(np.ndarray)): (N, 3, h, w) for tensor, [(h, w, 3) x N] for list.\n        \"\"\"\n        if not isinstance(im, torch.Tensor):\n            im = np.stack(self.pre_transform(im))\n            im = im[..., ::-1].transpose((0, 3, 1, 2))  # BGR to RGB, BHWC to BCHW, (n, 3, h, w)\n            im = np.ascontiguousarray(im)  # contiguous\n            im = torch.from_numpy(im)\n        # NOTE: assuming im with (b, 3, h, w) if it's a tensor\n        img = im.to(self.device)\n        img = img.half() if self.model.fp16 else img.float()  # uint8 to fp16/32\n        img /= 255  # 0 - 255 to 0.0 - 1.0\n        return img\n\n    def pre_transform(self, im):\n        \"\"\"Pre-tranform input image before inference.\n\n        Args:\n            im (List(np.ndarray)): (N, 3, h, w) for tensor, [(h, w, 3) x N] for list.\n\n        Return: A list of transformed imgs.\n        \"\"\"\n        same_shapes = all(x.shape == im[0].shape for x in im)\n        auto = same_shapes and self.model.pt\n        return [LetterBox(self.imgsz, auto=auto, stride=self.model.stride)(image=x) for x in im]\n\n    def write_results(self, idx, results_list, batch):\n        \"\"\"Write inference results to a file or directory.\"\"\"\n        p, im, _ = batch\n        log_string = ''\n        if len(im.shape) == 3:\n            im = im[None]  # expand for batch dim\n        self.seen += 1\n        if self.source_type.webcam or self.source_type.from_img:  # batch_size >= 1\n            log_string += f'{idx}: '\n            frame = self.dataset.count\n        else:\n            frame = getattr(self.dataset, 'frame', 0)\n        self.data_path = p\n        self.txt_path = str(self.save_dir / 'labels' / p.stem) + ('' if self.dataset.mode == 'image' else f'_{frame}')\n        log_string += '%gx%g ' % im.shape[2:]  # print string\n        plotted_img = []\n        for i,results in enumerate(results_list):\n            if isinstance(results,list):\n                result = results[idx]\n                try:\n                    log_string += result.verbose()\n                except:\n                    pass\n\n                if self.args.save or self.args.show:  # Add bbox to image\n                    plot_args = dict(line_width=self.args.line_width,\n                                     boxes=self.args.boxes,\n                                     conf=self.args.show_conf,\n                                     labels=self.args.show_labels)\n                    if not self.args.retina_masks:\n                        plot_args['im_gpu'] = im[idx]\n                        plotted_img.append(result.plot(**plot_args))\n            else:\n                plotted_img.append(results)\n        self.plotted_img=plotted_img\n\n        # Write\n        # if self.args.save_txt:\n        #     result.save_txt(f'{self.txt_path}.txt', save_conf=self.args.save_conf)\n        # if self.args.save_crop:\n        #     result.save_crop(save_dir=self.save_dir / 'crops', file_name=self.data_path.stem)\n\n        return log_string\n\n    def postprocess(self, preds, img, orig_img):\n        \"\"\"Post-processes predictions for an image and returns them.\"\"\"\n        return preds\n\n    def __call__(self, source=None, model=None, stream=False):\n        \"\"\"Performs inference on an image or stream.\"\"\"\n        self.stream = stream\n        if stream:\n            return self.stream_inference(source, model)\n        else:\n            return list(self.stream_inference(source, model)) # merge list of Result into one\n\n    def predict_cli(self, source=None, model=None):\n        \"\"\"Method used for CLI prediction. It uses always generator as outputs as not required by CLI mode.\"\"\"\n        gen = self.stream_inference(source, model)\n        for _ in gen:  # running CLI inference without accumulating any outputs (do not modify)\n            pass\n\n    def setup_source(self, source):\n        \"\"\"Sets up source and inference mode.\"\"\"\n        self.imgsz = check_imgsz(self.args.imgsz, stride=self.model.stride, min_dim=2)  # check image size\n        self.transforms = getattr(self.model.model, 'transforms', classify_transforms(\n            self.imgsz[0])) if self.args.task == 'classify' else None\n        self.dataset = load_inference_source(source=source, imgsz=self.imgsz, vid_stride=self.args.vid_stride)\n        self.source_type = self.dataset.source_type\n        if not getattr(self, 'stream', True) and (self.dataset.mode == 'stream' or  # streams\n                                                  len(self.dataset) > 1000 or  # images\n                                                  any(getattr(self.dataset, 'video_flag', [False]))):  # videos\n            LOGGER.warning(STREAM_WARNING)\n        self.vid_path, self.vid_writer = [None] * self.dataset.bs, [None] * self.dataset.bs\n\n    @smart_inference_mode()\n    def stream_inference(self, source=None, model=None):\n        \"\"\"Streams real-time inference on camera feed and saves results to file.\"\"\"\n        if self.args.verbose:\n            LOGGER.info('')\n\n        # Setup model\n        if not self.model:\n            self.setup_model(model)\n        # Setup source every time predict is called\n        self.setup_source(source if source is not None else self.args.source)\n\n        # Check if save_dir/ label file exists\n        if self.args.save or self.args.save_txt:\n            (self.save_dir / 'labels' if self.args.save_txt else self.save_dir).mkdir(parents=True, exist_ok=True)\n        # Warmup model\n        if not self.done_warmup:\n            self.model.warmup(imgsz=(1 if self.model.pt or self.model.triton else self.dataset.bs, 3, *self.imgsz))\n            self.done_warmup = True\n\n        self.seen, self.windows, self.batch, profilers = 0, [], None, (ops.Profile(), ops.Profile(), ops.Profile())\n        self.run_callbacks('on_predict_start')\n        for batch in self.dataset:\n            # self.run_callbacks('on_predict_batch_start')\n            self.batch = batch\n            path, im0s, vid_cap, s = batch\n            visualize = increment_path(self.save_dir / Path(path[0]).stem,\n                                       mkdir=True) if self.args.visualize and (not self.source_type.tensor) else False\n\n            # Preprocess\n            with profilers[0]:\n                im = self.preprocess(im0s)\n\n            # Inference\n            with profilers[1]:\n                preds = self.model(im, augment=self.args.augment, visualize=visualize)\n\n            # Postprocess\n            with profilers[2]:\n                if self.args.task == 'multi':\n                    self.results = []\n                    for i, pred in enumerate(preds):\n                        if isinstance(pred, tuple):\n                            pred = self.postprocess_det(pred, im, im0s)\n                            self.results.append(pred)\n                        else:\n                            pred = self.postprocess_seg(pred)\n                            self.results.append(pred)\n                else:\n                    self.results = self.postprocess(preds, im, im0s)\n\n            # self.run_callbacks('on_predict_postprocess_end')\n\n            # Visualize, save, write results\n            n = len(im0s)\n            for i in range(n):\n                # self.results[i].speed = {\n                #     'preprocess': profilers[0].dt * 1E3 / n,\n                #     'inference': profilers[1].dt * 1E3 / n,\n                #     'postprocess': profilers[2].dt * 1E3 / n}\n                if self.source_type.tensor:  # skip write, show and plot operations if input is raw tensor\n                    continue\n                p, im0 = path[i], im0s[i].copy()\n                p = Path(p)\n\n                if self.args.verbose or self.args.save or self.args.save_txt or self.args.show:\n                    s += self.write_results(i, self.results, (p, im, im0))\n\n                # if self.args.show and self.plotted_img is not None:\n                #     self.show(p)\n\n                if self.args.save and self.plotted_img is not None:\n                    self.save_preds(vid_cap, i, str(self.save_dir / p.name))\n            # self.run_callbacks('on_predict_batch_end')\n            yield from self.results\n\n\n            # Print time (inference-only)\n            if self.args.verbose:\n                LOGGER.info(f'{s}{profilers[1].dt * 1E3:.1f}ms')\n\n        # Release assets\n        # if isinstance(self.vid_writer[-1], cv2.VideoWriter):\n        #     self.vid_writer[-1].release()  # release final video writer\n\n        # Print results\n        # if self.args.verbose and self.seen:\n        #     t = tuple(x.t / self.seen * 1E3 for x in profilers)  # speeds per image\n        #     LOGGER.info(f'Speed: %.1fms preprocess, %.1fms inference, %.1fms postprocess per image at shape '\n        #                 f'{(1, 3, *self.imgsz)}' % t)\n        # if self.args.save or self.args.save_txt or self.args.save_crop:\n        #     nl = len(list(self.save_dir.glob('labels/*.txt')))  # number of labels\n        #     s = f\"\\n{nl} label{'s' * (nl > 1)} saved to {self.save_dir / 'labels'}\" if self.args.save_txt else ''\n        #     LOGGER.info(f\"Results saved to {colorstr('bold', self.save_dir)}{s}\")\n\n        # self.run_callbacks('on_predict_end')\n\n    def setup_model(self, model, verbose=True):\n        \"\"\"Initialize YOLO model with given parameters and set it to evaluation mode.\"\"\"\n        device = select_device(self.args.device, verbose=verbose)\n        model = model or self.args.model\n        self.args.half &= device.type != 'cpu'  # half precision only supported on CUDA\n        self.model = AutoBackend(model,\n                                 device=device,\n                                 dnn=self.args.dnn,\n                                 data=self.args.data,\n                                 fp16=self.args.half,\n                                 fuse=True,\n                                 verbose=verbose)\n        self.device = device\n        self.model.eval()\n\n    def show(self, p):\n        \"\"\"Display an image in a window using OpenCV imshow().\"\"\"\n        im0 = self.plotted_img\n        if platform.system() == 'Linux' and p not in self.windows:\n            self.windows.append(p)\n            cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)\n            cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])\n        cv2.imshow(str(p), im0)\n        cv2.waitKey(500 if self.batch[3].startswith('image') else 1)  # 1 millisecond\n\n    def save_preds(self, vid_cap, idx, save_path):\n        \"\"\"Save video predictions as mp4 at specified path.\"\"\"\n        im0_list = self.plotted_img\n\n        # Save imgs\n        if self.dataset.mode == 'image':\n            im0 = im0_list[0].copy()  # We create a copy so that we don't modify the original image\n\n            # Convert tensor to ndarray and remove the first dimension\n            mask1 = im0_list[1][0].to(torch.uint8).cpu().numpy()\n            mask2 = im0_list[2][0].to(torch.uint8).cpu().numpy()\n\n            # Convert mask to RGB\n            color_mask1 = np.stack([mask1 * 0, mask1 * 255, mask1 * 0], axis=-1)\n            color_mask2 = np.stack([mask2 * 255, mask2 * 0, mask2 * 0], axis=-1)\n\n            alpha = 0.5  # transparency factor\n\n            # Overlay masks on im0 with transparency\n            im0[np.any(color_mask1 != [0, 0, 0], axis=-1)] = (1 - alpha) * im0[\n                np.any(color_mask1 != [0, 0, 0], axis=-1)] + alpha * color_mask1[\n                                                                 np.any(color_mask1 != [0, 0, 0], axis=-1)]\n            im0[np.any(color_mask2 != [0, 0, 0], axis=-1)] = (1 - alpha) * im0[\n                np.any(color_mask2 != [0, 0, 0], axis=-1)] + alpha * color_mask2[\n                                                                 np.any(color_mask2 != [0, 0, 0], axis=-1)]\n\n            # Save the final image\n            cv2.imwrite(save_path, im0)\n\n\n\n\n        else:  # 'video' or 'stream'\n            if self.vid_path[idx] != save_path:  # new video\n                self.vid_path[idx] = save_path\n                if isinstance(self.vid_writer[idx], cv2.VideoWriter):\n                    self.vid_writer[idx].release()  # release previous video writer\n                if vid_cap:  # video\n                    fps = int(vid_cap.get(cv2.CAP_PROP_FPS))  # integer required, floats produce error in MP4 codec\n                    w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n                    h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n                else:  # stream\n                    fps, w, h = 30, im0.shape[1], im0.shape[0]\n                save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos\n                self.vid_writer[idx] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))\n            self.vid_writer[idx].write(im0)\n\n    def run_callbacks(self, event: str):\n        \"\"\"Runs all registered callbacks for a specific event.\"\"\"\n        for callback in self.callbacks.get(event, []):\n            callback(self)\n\n    def add_callback(self, event: str, func):\n        \"\"\"\n        Add callback\n        \"\"\"\n        self.callbacks[event].append(func)\n"
  },
  {
    "path": "ultralytics/yolo/engine/results.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nUltralytics Results, Boxes and Masks classes for handling inference results\n\nUsage: See https://docs.ultralytics.com/modes/predict/\n\"\"\"\n\nfrom copy import deepcopy\nfrom functools import lru_cache\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\n\nfrom ultralytics.yolo.data.augment import LetterBox\nfrom ultralytics.yolo.utils import LOGGER, SimpleClass, deprecation_warn, ops\nfrom ultralytics.yolo.utils.plotting import Annotator, colors, save_one_box\n\n\nclass BaseTensor(SimpleClass):\n    \"\"\"\n    Base tensor class with additional methods for easy manipulation and device handling.\n    \"\"\"\n\n    def __init__(self, data, orig_shape) -> None:\n        \"\"\"Initialize BaseTensor with data and original shape.\"\"\"\n        self.data = data\n        self.orig_shape = orig_shape\n\n    @property\n    def shape(self):\n        \"\"\"Return the shape of the data tensor.\"\"\"\n        return self.data.shape\n\n    def cpu(self):\n        \"\"\"Return a copy of the tensor on CPU memory.\"\"\"\n        return self.__class__(self.data.cpu(), self.orig_shape)\n\n    def numpy(self):\n        \"\"\"Return a copy of the tensor as a numpy array.\"\"\"\n        return self.__class__(self.data.numpy(), self.orig_shape)\n\n    def cuda(self):\n        \"\"\"Return a copy of the tensor on GPU memory.\"\"\"\n        return self.__class__(self.data.cuda(), self.orig_shape)\n\n    def to(self, *args, **kwargs):\n        \"\"\"Return a copy of the tensor with the specified device and dtype.\"\"\"\n        return self.__class__(self.data.to(*args, **kwargs), self.orig_shape)\n\n    def __len__(self):  # override len(results)\n        \"\"\"Return the length of the data tensor.\"\"\"\n        return len(self.data)\n\n    def __getitem__(self, idx):\n        \"\"\"Return a BaseTensor with the specified index of the data tensor.\"\"\"\n        return self.__class__(self.data[idx], self.orig_shape)\n\n\nclass Results(SimpleClass):\n    \"\"\"\n    A class for storing and manipulating inference results.\n\n    Args:\n        orig_img (numpy.ndarray): The original image as a numpy array.\n        path (str): The path to the image file.\n        names (dict): A dictionary of class names.\n        boxes (List[List[float]], optional): A list of bounding box coordinates for each detection.\n        masks (numpy.ndarray, optional): A 3D numpy array of detection masks, where each mask is a binary image.\n        probs (numpy.ndarray, optional): A 2D numpy array of detection probabilities for each class.\n        keypoints (List[List[float]], optional): A list of detected keypoints for each object.\n\n\n    Attributes:\n        orig_img (numpy.ndarray): The original image as a numpy array.\n        orig_shape (tuple): The original image shape in (height, width) format.\n        boxes (Boxes, optional): A Boxes object containing the detection bounding boxes.\n        masks (Masks, optional): A Masks object containing the detection masks.\n        probs (numpy.ndarray, optional): A 2D numpy array of detection probabilities for each class.\n        names (dict): A dictionary of class names.\n        path (str): The path to the image file.\n        keypoints (List[List[float]], optional): A list of detected keypoints for each object.\n        speed (dict): A dictionary of preprocess, inference and postprocess speeds in milliseconds per image.\n        _keys (tuple): A tuple of attribute names for non-empty attributes.\n    \"\"\"\n\n    def __init__(self, orig_img, path, names, boxes=None, masks=None, probs=None, keypoints=None) -> None:\n        \"\"\"Initialize the Results class.\"\"\"\n        self.orig_img = orig_img\n        self.orig_shape = orig_img.shape[:2]\n        self.boxes = Boxes(boxes, self.orig_shape) if boxes is not None else None  # native size boxes\n        self.masks = Masks(masks, self.orig_shape) if masks is not None else None  # native size or imgsz masks\n        self.probs = probs if probs is not None else None\n        self.keypoints = keypoints if keypoints is not None else None\n        self.speed = {'preprocess': None, 'inference': None, 'postprocess': None}  # milliseconds per image\n        self.names = names\n        self.path = path\n        self._keys = ('boxes', 'masks', 'probs', 'keypoints')\n\n    def __getitem__(self, idx):\n        \"\"\"Return a Results object for the specified index.\"\"\"\n        r = self.new()\n        for k in self.keys:\n            setattr(r, k, getattr(self, k)[idx])\n        return r\n\n    def update(self, boxes=None, masks=None, probs=None):\n        \"\"\"Update the boxes, masks, and probs attributes of the Results object.\"\"\"\n        if boxes is not None:\n            self.boxes = Boxes(boxes, self.orig_shape)\n        if masks is not None:\n            self.masks = Masks(masks, self.orig_shape)\n        if probs is not None:\n            self.probs = probs\n\n    def cpu(self):\n        \"\"\"Return a copy of the Results object with all tensors on CPU memory.\"\"\"\n        r = self.new()\n        for k in self.keys:\n            setattr(r, k, getattr(self, k).cpu())\n        return r\n\n    def numpy(self):\n        \"\"\"Return a copy of the Results object with all tensors as numpy arrays.\"\"\"\n        r = self.new()\n        for k in self.keys:\n            setattr(r, k, getattr(self, k).numpy())\n        return r\n\n    def cuda(self):\n        \"\"\"Return a copy of the Results object with all tensors on GPU memory.\"\"\"\n        r = self.new()\n        for k in self.keys:\n            setattr(r, k, getattr(self, k).cuda())\n        return r\n\n    def to(self, *args, **kwargs):\n        \"\"\"Return a copy of the Results object with tensors on the specified device and dtype.\"\"\"\n        r = self.new()\n        for k in self.keys:\n            setattr(r, k, getattr(self, k).to(*args, **kwargs))\n        return r\n\n    def __len__(self):\n        \"\"\"Return the number of detections in the Results object.\"\"\"\n        for k in self.keys:\n            return len(getattr(self, k))\n\n    def new(self):\n        \"\"\"Return a new Results object with the same image, path, and names.\"\"\"\n        return Results(orig_img=self.orig_img, path=self.path, names=self.names)\n\n    @property\n    def keys(self):\n        \"\"\"Return a list of non-empty attribute names.\"\"\"\n        return [k for k in self._keys if getattr(self, k) is not None]\n\n    def plot(\n            self,\n            conf=True,\n            line_width=None,\n            font_size=None,\n            font='Arial.ttf',\n            pil=False,\n            img=None,\n            img_gpu=None,\n            kpt_line=True,\n            labels=True,\n            boxes=True,\n            masks=True,\n            probs=True,\n            **kwargs  # deprecated args TODO: remove support in 8.2\n    ):\n        \"\"\"\n        Plots the detection results on an input RGB image. Accepts a numpy array (cv2) or a PIL Image.\n\n        Args:\n            conf (bool): Whether to plot the detection confidence score.\n            line_width (float, optional): The line width of the bounding boxes. If None, it is scaled to the image size.\n            font_size (float, optional): The font size of the text. If None, it is scaled to the image size.\n            font (str): The font to use for the text.\n            pil (bool): Whether to return the image as a PIL Image.\n            img (numpy.ndarray): Plot to another image. if not, plot to original image.\n            img_gpu (torch.Tensor): Normalized image in gpu with shape (1, 3, 640, 640), for faster mask plotting.\n            kpt_line (bool): Whether to draw lines connecting keypoints.\n            labels (bool): Whether to plot the label of bounding boxes.\n            boxes (bool): Whether to plot the bounding boxes.\n            masks (bool): Whether to plot the masks.\n            probs (bool): Whether to plot classification probability\n\n        Returns:\n            (numpy.ndarray): A numpy array of the annotated image.\n        \"\"\"\n        # Deprecation warn TODO: remove in 8.2\n        if 'show_conf' in kwargs:\n            deprecation_warn('show_conf', 'conf')\n            conf = kwargs['show_conf']\n            assert type(conf) == bool, '`show_conf` should be of boolean type, i.e, show_conf=True/False'\n\n        if 'show_conf' in kwargs:\n            deprecation_warn('line_thickness', 'line_width')\n            line_width = kwargs['line_thickness']\n            assert type(line_width) == int, '`line_width` should be of int type, i.e, line_width=3'\n\n        names = self.names\n        annotator = Annotator(deepcopy(self.orig_img if img is None else img),\n                              line_width,\n                              font_size,\n                              font,\n                              pil,\n                              example=names)\n        pred_boxes, show_boxes = self.boxes, boxes\n        pred_masks, show_masks = self.masks, masks\n        pred_probs, show_probs = self.probs, probs\n        keypoints = self.keypoints\n        if pred_masks and show_masks:\n            if img_gpu is None:\n                img = LetterBox(pred_masks.shape[1:])(image=annotator.result())\n                img_gpu = torch.as_tensor(img, dtype=torch.float16, device=pred_masks.data.device).permute(\n                    2, 0, 1).flip(0).contiguous() / 255\n            idx = pred_boxes.cls if pred_boxes else range(len(pred_masks))\n            annotator.masks(pred_masks.data, colors=[colors(x, True) for x in idx], im_gpu=img_gpu)\n\n        if pred_boxes and show_boxes:\n            for d in reversed(pred_boxes):\n                c, conf, id = int(d.cls), float(d.conf) if conf else None, None if d.id is None else int(d.id.item())\n                name = ('' if id is None else f'id:{id} ') + names[c]\n                label = (f'{name} {conf:.2f}' if conf else name) if labels else None\n                annotator.box_label(d.xyxy.squeeze(), label, color=colors(c, True))\n\n        if pred_probs is not None and show_probs:\n            n5 = min(len(names), 5)\n            top5i = pred_probs.argsort(0, descending=True)[:n5].tolist()  # top 5 indices\n            text = f\"{', '.join(f'{names[j] if names else j} {pred_probs[j]:.2f}' for j in top5i)}, \"\n            annotator.text((32, 32), text, txt_color=(255, 255, 255))  # TODO: allow setting colors\n\n        if keypoints is not None:\n            for k in reversed(keypoints):\n                annotator.kpts(k, self.orig_shape, kpt_line=kpt_line)\n\n        return annotator.result()\n\n    def verbose(self):\n        \"\"\"\n        Return log string for each task.\n        \"\"\"\n        log_string = ''\n        probs = self.probs\n        boxes = self.boxes\n        if len(self) == 0:\n            return log_string if probs is not None else f'{log_string}(no detections), '\n        if probs is not None:\n            n5 = min(len(self.names), 5)\n            top5i = probs.argsort(0, descending=True)[:n5].tolist()  # top 5 indices\n            log_string += f\"{', '.join(f'{self.names[j]} {probs[j]:.2f}' for j in top5i)}, \"\n        if boxes:\n            for c in boxes.cls.unique():\n                n = (boxes.cls == c).sum()  # detections per class\n                log_string += f\"{n} {self.names[int(c)]}{'s' * (n > 1)}, \"\n        return log_string\n\n    def save_txt(self, txt_file, save_conf=False):\n        \"\"\"\n        Save predictions into txt file.\n\n        Args:\n            txt_file (str): txt file path.\n            save_conf (bool): save confidence score or not.\n        \"\"\"\n        boxes = self.boxes\n        masks = self.masks\n        probs = self.probs\n        kpts = self.keypoints\n        texts = []\n        if probs is not None:\n            # Classify\n            n5 = min(len(self.names), 5)\n            top5i = probs.argsort(0, descending=True)[:n5].tolist()  # top 5 indices\n            [texts.append(f'{probs[j]:.2f} {self.names[j]}') for j in top5i]\n        elif boxes:\n            # Detect/segment/pose\n            for j, d in enumerate(boxes):\n                c, conf, id = int(d.cls), float(d.conf), None if d.id is None else int(d.id.item())\n                line = (c, *d.xywhn.view(-1))\n                if masks:\n                    seg = masks[j].xyn[0].copy().reshape(-1)  # reversed mask.xyn, (n,2) to (n*2)\n                    line = (c, *seg)\n                if kpts is not None:\n                    kpt = (kpts[j][:, :2] / d.orig_shape[[1, 0]]).reshape(-1).tolist()\n                    line += (*kpt, )\n                line += (conf, ) * save_conf + (() if id is None else (id, ))\n                texts.append(('%g ' * len(line)).rstrip() % line)\n\n        if texts:\n            with open(txt_file, 'a') as f:\n                f.writelines(text + '\\n' for text in texts)\n\n    def save_crop(self, save_dir, file_name=Path('im.jpg')):\n        \"\"\"\n        Save cropped predictions to `save_dir/cls/file_name.jpg`.\n\n        Args:\n            save_dir (str | pathlib.Path): Save path.\n            file_name (str | pathlib.Path): File name.\n        \"\"\"\n        if self.probs is not None:\n            LOGGER.warning('Warning: Classify task do not support `save_crop`.')\n            return\n        if isinstance(save_dir, str):\n            save_dir = Path(save_dir)\n        if isinstance(file_name, str):\n            file_name = Path(file_name)\n        for d in self.boxes:\n            save_one_box(d.xyxy,\n                         self.orig_img.copy(),\n                         file=save_dir / self.names[int(d.cls)] / f'{file_name.stem}.jpg',\n                         BGR=True)\n\n    def pandas(self):\n        \"\"\"Convert the object to a pandas DataFrame (not yet implemented).\"\"\"\n        LOGGER.warning(\"WARNING ⚠️ 'Results.pandas' method is not yet implemented.\")\n\n    def tojson(self, normalize=False):\n        \"\"\"Convert the object to JSON format.\"\"\"\n        import json\n\n        # Create list of detection dictionaries\n        results = []\n        data = self.boxes.data.cpu().tolist()\n        h, w = self.orig_shape if normalize else (1, 1)\n        for i, row in enumerate(data):\n            box = {'x1': row[0] / w, 'y1': row[1] / h, 'x2': row[2] / w, 'y2': row[3] / h}\n            conf = row[4]\n            id = int(row[5])\n            name = self.names[id]\n            result = {'name': name, 'class': id, 'confidence': conf, 'box': box}\n            if self.masks:\n                x, y = self.masks.xy[i][:, 0], self.masks.xy[i][:, 1]  # numpy array\n                result['segments'] = {'x': (x / w).tolist(), 'y': (y / h).tolist()}\n            if self.keypoints is not None:\n                x, y, visible = self.keypoints[i].cpu().unbind(dim=1)  # torch Tensor\n                result['keypoints'] = {'x': (x / w).tolist(), 'y': (y / h).tolist(), 'visible': visible.tolist()}\n            results.append(result)\n\n        # Convert detections to JSON\n        return json.dumps(results, indent=2)\n\n\nclass Boxes(BaseTensor):\n    \"\"\"\n    A class for storing and manipulating detection boxes.\n\n    Args:\n        boxes (torch.Tensor) or (numpy.ndarray): A tensor or numpy array containing the detection boxes,\n            with shape (num_boxes, 6). The last two columns should contain confidence and class values.\n        orig_shape (tuple): Original image size, in the format (height, width).\n\n    Attributes:\n        boxes (torch.Tensor) or (numpy.ndarray): The detection boxes with shape (num_boxes, 6).\n        orig_shape (torch.Tensor) or (numpy.ndarray): Original image size, in the format (height, width).\n        is_track (bool): True if the boxes also include track IDs, False otherwise.\n\n    Properties:\n        xyxy (torch.Tensor) or (numpy.ndarray): The boxes in xyxy format.\n        conf (torch.Tensor) or (numpy.ndarray): The confidence values of the boxes.\n        cls (torch.Tensor) or (numpy.ndarray): The class values of the boxes.\n        id (torch.Tensor) or (numpy.ndarray): The track IDs of the boxes (if available).\n        xywh (torch.Tensor) or (numpy.ndarray): The boxes in xywh format.\n        xyxyn (torch.Tensor) or (numpy.ndarray): The boxes in xyxy format normalized by original image size.\n        xywhn (torch.Tensor) or (numpy.ndarray): The boxes in xywh format normalized by original image size.\n        data (torch.Tensor): The raw bboxes tensor\n\n    Methods:\n        cpu(): Move the object to CPU memory.\n        numpy(): Convert the object to a numpy array.\n        cuda(): Move the object to CUDA memory.\n        to(*args, **kwargs): Move the object to the specified device.\n        pandas(): Convert the object to a pandas DataFrame (not yet implemented).\n    \"\"\"\n\n    def __init__(self, boxes, orig_shape) -> None:\n        \"\"\"Initialize the Boxes class.\"\"\"\n        if boxes.ndim == 1:\n            boxes = boxes[None, :]\n        n = boxes.shape[-1]\n        assert n in (6, 7), f'expected `n` in [6, 7], but got {n}'  # xyxy, (track_id), conf, cls\n        super().__init__(boxes, orig_shape)\n        self.is_track = n == 7\n        self.orig_shape = torch.as_tensor(orig_shape, device=boxes.device) if isinstance(boxes, torch.Tensor) \\\n            else np.asarray(orig_shape)\n\n    @property\n    def xyxy(self):\n        \"\"\"Return the boxes in xyxy format.\"\"\"\n        return self.data[:, :4]\n\n    @property\n    def conf(self):\n        \"\"\"Return the confidence values of the boxes.\"\"\"\n        return self.data[:, -2]\n\n    @property\n    def cls(self):\n        \"\"\"Return the class values of the boxes.\"\"\"\n        return self.data[:, -1]\n\n    @property\n    def id(self):\n        \"\"\"Return the track IDs of the boxes (if available).\"\"\"\n        return self.data[:, -3] if self.is_track else None\n\n    @property\n    @lru_cache(maxsize=2)  # maxsize 1 should suffice\n    def xywh(self):\n        \"\"\"Return the boxes in xywh format.\"\"\"\n        return ops.xyxy2xywh(self.xyxy)\n\n    @property\n    @lru_cache(maxsize=2)\n    def xyxyn(self):\n        \"\"\"Return the boxes in xyxy format normalized by original image size.\"\"\"\n        return self.xyxy / self.orig_shape[[1, 0, 1, 0]]\n\n    @property\n    @lru_cache(maxsize=2)\n    def xywhn(self):\n        \"\"\"Return the boxes in xywh format normalized by original image size.\"\"\"\n        return self.xywh / self.orig_shape[[1, 0, 1, 0]]\n\n    @property\n    def boxes(self):\n        \"\"\"Return the raw bboxes tensor (deprecated).\"\"\"\n        LOGGER.warning(\"WARNING ⚠️ 'Boxes.boxes' is deprecated. Use 'Boxes.data' instead.\")\n        return self.data\n\n\nclass Masks(BaseTensor):\n    \"\"\"\n    A class for storing and manipulating detection masks.\n\n    Args:\n        masks (torch.Tensor): A tensor containing the detection masks, with shape (num_masks, height, width).\n        orig_shape (tuple): Original image size, in the format (height, width).\n\n    Attributes:\n        masks (torch.Tensor): A tensor containing the detection masks, with shape (num_masks, height, width).\n        orig_shape (tuple): Original image size, in the format (height, width).\n\n    Properties:\n        xy (list): A list of segments (pixels) which includes x, y segments of each detection.\n        xyn (list): A list of segments (normalized) which includes x, y segments of each detection.\n\n    Methods:\n        cpu(): Returns a copy of the masks tensor on CPU memory.\n        numpy(): Returns a copy of the masks tensor as a numpy array.\n        cuda(): Returns a copy of the masks tensor on GPU memory.\n        to(): Returns a copy of the masks tensor with the specified device and dtype.\n    \"\"\"\n\n    def __init__(self, masks, orig_shape) -> None:\n        \"\"\"Initialize the Masks class.\"\"\"\n        if masks.ndim == 2:\n            masks = masks[None, :]\n        super().__init__(masks, orig_shape)\n\n    @property\n    @lru_cache(maxsize=1)\n    def segments(self):\n        \"\"\"Return segments (deprecated; normalized).\"\"\"\n        LOGGER.warning(\"WARNING ⚠️ 'Masks.segments' is deprecated. Use 'Masks.xyn' for segments (normalized) and \"\n                       \"'Masks.xy' for segments (pixels) instead.\")\n        return self.xyn\n\n    @property\n    @lru_cache(maxsize=1)\n    def xyn(self):\n        \"\"\"Return segments (normalized).\"\"\"\n        return [\n            ops.scale_coords(self.data.shape[1:], x, self.orig_shape, normalize=True)\n            for x in ops.masks2segments(self.data)]\n\n    @property\n    @lru_cache(maxsize=1)\n    def xy(self):\n        \"\"\"Return segments (pixels).\"\"\"\n        return [\n            ops.scale_coords(self.data.shape[1:], x, self.orig_shape, normalize=False)\n            for x in ops.masks2segments(self.data)]\n\n    @property\n    def masks(self):\n        \"\"\"Return the raw masks tensor (deprecated).\"\"\"\n        LOGGER.warning(\"WARNING ⚠️ 'Masks.masks' is deprecated. Use 'Masks.data' instead.\")\n        return self.data\n\n    def pandas(self):\n        \"\"\"Convert the object to a pandas DataFrame (not yet implemented).\"\"\"\n        LOGGER.warning(\"WARNING ⚠️ 'Masks.pandas' method is not yet implemented.\")\n"
  },
  {
    "path": "ultralytics/yolo/engine/trainer.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nTrain a model on a dataset\n\nUsage:\n    $ yolo mode=train model=yolov8n.pt data=coco128.yaml imgsz=640 epochs=100 batch=16\n\"\"\"\nimport os\nimport subprocess\nimport time\nfrom copy import deepcopy\nfrom datetime import datetime, timedelta\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nfrom torch.cuda import amp\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.optim import lr_scheduler\nfrom tqdm import tqdm\n\nfrom ultralytics.nn.tasks import attempt_load_one_weight, attempt_load_weights\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.data.utils import check_cls_dataset, check_det_dataset\nfrom ultralytics.yolo.utils import (DEFAULT_CFG, LOGGER, ONLINE, RANK, ROOT, SETTINGS, TQDM_BAR_FORMAT, __version__,\n                                    callbacks, clean_url, colorstr, emojis, yaml_save)\nfrom ultralytics.yolo.utils.autobatch import check_train_batch_size\nfrom ultralytics.yolo.utils.checks import check_file, check_imgsz, print_args\nfrom ultralytics.yolo.utils.dist import ddp_cleanup, generate_ddp_command\nfrom ultralytics.yolo.utils.files import get_latest_run, increment_path\nfrom ultralytics.yolo.utils.torch_utils import (EarlyStopping, ModelEMA, de_parallel, init_seeds, one_cycle,\n                                                select_device, strip_optimizer)\nimport itertools\n\nclass BaseTrainer:\n    \"\"\"\n    BaseTrainer\n\n    A base class for creating trainers.\n\n    Attributes:\n        args (SimpleNamespace): Configuration for the trainer.\n        check_resume (method): Method to check if training should be resumed from a saved checkpoint.\n        validator (BaseValidator): Validator instance.\n        model (nn.Module): Model instance.\n        callbacks (defaultdict): Dictionary of callbacks.\n        save_dir (Path): Directory to save results.\n        wdir (Path): Directory to save weights.\n        last (Path): Path to last checkpoint.\n        best (Path): Path to best checkpoint.\n        save_period (int): Save checkpoint every x epochs (disabled if < 1).\n        batch_size (int): Batch size for training.\n        epochs (int): Number of epochs to train for.\n        start_epoch (int): Starting epoch for training.\n        device (torch.device): Device to use for training.\n        amp (bool): Flag to enable AMP (Automatic Mixed Precision).\n        scaler (amp.GradScaler): Gradient scaler for AMP.\n        data (str): Path to data.\n        trainset (torch.utils.data.Dataset): Training dataset.\n        testset (torch.utils.data.Dataset): Testing dataset.\n        ema (nn.Module): EMA (Exponential Moving Average) of the model.\n        lf (nn.Module): Loss function.\n        scheduler (torch.optim.lr_scheduler._LRScheduler): Learning rate scheduler.\n        best_fitness (float): The best fitness value achieved.\n        fitness (float): Current fitness value.\n        loss (float): Current loss value.\n        tloss (float): Total loss value.\n        loss_names (list): List of loss names.\n        csv (Path): Path to results CSV file.\n    \"\"\"\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        \"\"\"\n        Initializes the BaseTrainer class.\n\n        Args:\n            cfg (str, optional): Path to a configuration file. Defaults to DEFAULT_CFG.\n            overrides (dict, optional): Configuration overrides. Defaults to None.\n        \"\"\"\n        self.args = get_cfg(cfg, overrides)\n        self.device = select_device(self.args.device, self.args.batch)\n        self.check_resume()\n        self.validator = None\n        self.model = None\n        self.metrics = None\n        self.plots = {}\n        init_seeds(self.args.seed + 1 + RANK, deterministic=self.args.deterministic)\n\n        # Dirs\n        project = self.args.project or Path(SETTINGS['runs_dir']) / self.args.task\n        name = self.args.name or f'{self.args.mode}'\n        if hasattr(self.args, 'save_dir'):\n            self.save_dir = Path(self.args.save_dir)\n        else:\n            self.save_dir = Path(\n                increment_path(Path(project) / name, exist_ok=self.args.exist_ok if RANK in (-1, 0) else True))\n        self.wdir = self.save_dir / 'weights'  # weights dir\n        if RANK in (-1, 0):\n            self.wdir.mkdir(parents=True, exist_ok=True)  # make dir\n            self.args.save_dir = str(self.save_dir)\n            yaml_save(self.save_dir / 'args.yaml', vars(self.args))  # save run args\n        self.last, self.best = self.wdir / 'last.pt', self.wdir / 'best.pt'  # checkpoint paths\n        self.save_period = self.args.save_period\n\n        self.batch_size = self.args.batch\n        self.epochs = self.args.epochs\n        self.start_epoch = 0\n        if RANK == -1:\n            print_args(vars(self.args))\n\n        # Device\n        if self.device.type == 'cpu':\n            self.args.workers = 0  # faster CPU training as time dominated by inference, not dataloading\n\n        # Model and Dataset\n        self.model = self.args.model\n        try:\n            if self.args.task == 'classify':\n                self.data = check_cls_dataset(self.args.data)\n            elif self.args.data.endswith('.yaml') or self.args.task in ('detect', 'segment'):\n                self.data = check_det_dataset(self.args.data)\n                if 'yaml_file' in self.data:\n                    self.args.data = self.data['yaml_file']  # for validating 'yolo train data=url.zip' usage\n        except Exception as e:\n            raise RuntimeError(emojis(f\"Dataset '{clean_url(self.args.data)}' error ❌ {e}\")) from e\n\n        self.trainset, self.testset = self.get_dataset(self.data)\n        self.ema = None\n\n        # Optimization utils init\n        self.lf = None\n        self.scheduler = None\n\n        # Epoch level metrics\n        self.best_fitness = None\n        self.fitness = None\n        self.loss = None\n        self.tloss = None\n        self.loss_names = ['Loss']\n        self.mul_loss = []\n        self.mul_loss_items = []\n        self.subloss = [None for _ in range(len(self.data['labels_list']))]\n        self.csv = self.save_dir / 'results.csv'\n        self.plot_idx = [0, 1, 2]\n\n        # Callbacks\n        self.callbacks = _callbacks or callbacks.get_default_callbacks()\n        if RANK in (-1, 0):\n            callbacks.add_integration_callbacks(self)\n\n    def add_callback(self, event: str, callback):\n        \"\"\"\n        Appends the given callback.\n        \"\"\"\n        self.callbacks[event].append(callback)\n\n    def set_callback(self, event: str, callback):\n        \"\"\"\n        Overrides the existing callbacks with the given callback.\n        \"\"\"\n        self.callbacks[event] = [callback]\n\n    def run_callbacks(self, event: str):\n        \"\"\"Run all existing callbacks associated with a particular event.\"\"\"\n        for callback in self.callbacks.get(event, []):\n            callback(self)\n\n    def train(self):\n        \"\"\"Allow device='', device=None on Multi-GPU systems to default to device=0.\"\"\"\n        if isinstance(self.args.device, int) or self.args.device:  # i.e. device=0 or device=[0,1,2,3]\n            world_size = torch.cuda.device_count()\n        elif torch.cuda.is_available():  # i.e. device=None or device=''\n            world_size = 1  # default to device 0\n        else:  # i.e. device='cpu' or 'mps'\n            world_size = 0\n\n        # Run subprocess if DDP training, else train normally\n        if world_size > 1 and 'LOCAL_RANK' not in os.environ:\n            # Argument checks\n            if self.args.rect:\n                LOGGER.warning(\"WARNING ⚠️ 'rect=True' is incompatible with Multi-GPU training, setting rect=False\")\n                self.args.rect = False\n            # Command\n            cmd, file = generate_ddp_command(world_size, self)\n            try:\n                LOGGER.info(f'Running DDP command {cmd}')\n                subprocess.run(cmd, check=True)\n            except Exception as e:\n                raise e\n            finally:\n                ddp_cleanup(self, str(file))\n        else:\n            self._do_train(world_size)\n\n    def _setup_ddp(self, world_size):\n        \"\"\"Initializes and sets the DistributedDataParallel parameters for training.\"\"\"\n        torch.cuda.set_device(RANK)\n        self.device = torch.device('cuda', RANK)\n        LOGGER.info(f'DDP settings: RANK {RANK}, WORLD_SIZE {world_size}, DEVICE {self.device}')\n        os.environ['NCCL_BLOCKING_WAIT'] = '1'  # set to enforce timeout\n        dist.init_process_group('nccl' if dist.is_nccl_available() else 'gloo',\n                                timeout=timedelta(seconds=3600),\n                                rank=RANK,\n                                world_size=world_size)\n\n    def _setup_train(self, world_size):\n        \"\"\"\n        Builds dataloaders and optimizer on correct rank process.\n        \"\"\"\n        # Model\n        self.run_callbacks('on_pretrain_routine_start')\n        ckpt = self.setup_model()\n        self.model = self.model.to(self.device)\n        self.set_model_attributes()\n        # Check AMP\n        self.amp = torch.tensor(self.args.amp).to(self.device)  # True or False\n        if self.amp and RANK in (-1, 0):  # Single-GPU and DDP\n            callbacks_backup = callbacks.default_callbacks.copy()  # backup callbacks as check_amp() resets them\n            self.amp = torch.tensor(check_amp(self.model), device=self.device)\n            callbacks.default_callbacks = callbacks_backup  # restore callbacks\n        if RANK > -1:  # DDP\n            dist.broadcast(self.amp, src=0)  # broadcast the tensor from rank 0 to all other ranks (returns None)\n        self.amp = bool(self.amp)  # as boolean\n        self.scaler = amp.GradScaler(enabled=self.amp)\n        if world_size > 1:\n            ######Jiayuan\n            self.model = DDP(self.model, device_ids=[RANK],broadcast_buffers=False, find_unused_parameters=True)\n            ######\n        # Check imgsz\n        try:\n            gs = max(int(self.model.stride.max() if hasattr(self.model, 'stride') else 32), 32) # grid size (max stride)\n        except:\n            gs = max(max(itertools.chain.from_iterable(self.model.stride)) if hasattr(self.model, 'stride') else 0, 32)\n        self.args.imgsz = check_imgsz(self.args.imgsz, stride=gs, floor=gs, max_dim=1)\n        # Batch size\n        if self.batch_size == -1:\n            if RANK == -1:  # single-GPU only, estimate best batch size\n                self.batch_size = check_train_batch_size(self.model, self.args.imgsz, self.amp)\n            else:\n                SyntaxError('batch=-1 to use AutoBatch is only available in Single-GPU training. '\n                            'Please pass a valid batch size value for Multi-GPU DDP training, i.e. batch=16')\n\n        # Optimizer\n        self.accumulate = max(round(self.args.nbs / self.batch_size), 1)  # accumulate loss before optimizing\n        weight_decay = self.args.weight_decay * self.batch_size * self.accumulate / self.args.nbs  # scale weight_decay\n        self.optimizer = self.build_optimizer(model=self.model,\n                                              name=self.args.optimizer,\n                                              lr=self.args.lr0,\n                                              momentum=self.args.momentum,\n                                              decay=weight_decay)\n        # Scheduler\n        if self.args.cos_lr:\n            self.lf = one_cycle(1, self.args.lrf, self.epochs)  # cosine 1->hyp['lrf']\n        else:\n            self.lf = lambda x: (1 - x / self.epochs) * (1.0 - self.args.lrf) + self.args.lrf  # linear\n        self.scheduler = lr_scheduler.LambdaLR(self.optimizer, lr_lambda=self.lf)\n        self.stopper, self.stop = EarlyStopping(patience=self.args.patience), False\n\n        # Dataloaders\n        batch_size = self.batch_size // world_size if world_size > 1 else self.batch_size\n        self.train_loader = self.get_dataloader(self.trainset, batch_size=batch_size, rank=RANK, mode='train')\n        if RANK in (-1, 0):\n            if self.args.task == \"multi\":\n                self.test_loader = self.get_dataloader(self.testset, batch_size=batch_size * 2, rank=-1, mode='val')\n                self.validator = self.get_validator()\n                metric_keys_det = self.validator.metrics_det.keys + self.label_loss_items(prefix='val', task = 'det')\n                metric_keys_seg = self.validator.metrics_seg.keys + self.label_loss_items(prefix='val', task = 'seg')\n                self.metrics_det = dict(zip(metric_keys_det, [0] * len(metric_keys_det)))  # TODO: init metrics for plot_results()?\n                self.metrics_seg = dict(zip(metric_keys_seg, [0] * len(metric_keys_seg)))  # TODO: init metrics for plot_results()?\n                self.ema = ModelEMA(self.model)\n                if self.args.plots and not self.args.v5loader:\n                    self.plot_training_labels()\n            else:\n                self.test_loader = self.get_dataloader(self.testset, batch_size=batch_size * 2, rank=-1, mode='val')\n                self.validator = self.get_validator()\n                metric_keys = self.validator.metrics.keys + self.label_loss_items(prefix='val')\n                self.metrics = dict(zip(metric_keys, [0] * len(metric_keys)))  # TODO: init metrics for plot_results()?\n                self.ema = ModelEMA(self.model)\n                if self.args.plots and not self.args.v5loader:\n                    self.plot_training_labels()\n        self.resume_training(ckpt)\n        self.scheduler.last_epoch = self.start_epoch - 1  # do not move\n        self.run_callbacks('on_pretrain_routine_end')\n\n    def _do_train(self, world_size=1):\n        \"\"\"Train completed, evaluate and plot if specified by arguments.\"\"\"\n        if world_size > 1:\n            self._setup_ddp(world_size)\n\n        self._setup_train(world_size)\n\n        self.epoch_time = None\n        self.epoch_time_start = time.time()\n        self.train_time_start = time.time()\n        nb = len(self.train_loader)  # number of batches\n        nw = max(round(self.args.warmup_epochs * nb), 100)  # number of warmup iterations\n        last_opt_step = -1\n        self.run_callbacks('on_train_start')\n        LOGGER.info(f'Image sizes {self.args.imgsz} train, {self.args.imgsz} val\\n'\n                    f'Using {self.train_loader.num_workers * (world_size or 1)} dataloader workers\\n'\n                    f\"Logging results to {colorstr('bold', self.save_dir)}\\n\"\n                    f'Starting training for {self.epochs} epochs...')\n        if self.args.close_mosaic:\n            base_idx = (self.epochs - self.args.close_mosaic) * nb\n            self.plot_idx.extend([base_idx, base_idx + 1, base_idx + 2])\n        epoch = self.epochs  # predefine for resume fully trained model edge cases\n        for epoch in range(self.start_epoch, self.epochs):\n            self.epoch = epoch\n            self.run_callbacks('on_train_epoch_start')\n            self.model.train()\n            if RANK != -1:\n                self.train_loader.sampler.set_epoch(epoch)\n            pbar = enumerate(self.train_loader)\n            # Update dataloader attributes (optional)\n            if epoch == (self.epochs - self.args.close_mosaic):\n                LOGGER.info('Closing dataloader mosaic')\n                if hasattr(self.train_loader.dataset, 'mosaic'):\n                    self.train_loader.dataset.mosaic = False\n                if hasattr(self.train_loader.dataset, 'close_mosaic'):\n                    self.train_loader.dataset.close_mosaic(hyp=self.args)\n                self.train_loader.reset()\n\n            if RANK in (-1, 0):\n                LOGGER.info(self.progress_string())\n                ######Jiayuan\n                # pbar = tqdm(enumerate(self.train_loader), total=nb, bar_format=TQDM_BAR_FORMAT)\n                # ncols will control the width for tqdm. it should be larger than original. Otherwise, it can not display fully.\n                pbar = tqdm(enumerate(self.train_loader), total=nb, ncols=300, bar_format=TQDM_BAR_FORMAT)\n                ######\n            self.tloss = None\n            self.optimizer.zero_grad()\n            for i, batch in pbar:\n                self.run_callbacks('on_train_batch_start')\n                ######Jiayuan switch the seg labels\n                # for count, map in enumerate(self.data['map']):\n                #     if map!='None':\n                #         replacement_dict_float = {float(key): float(value) for key, value in map.items()}\n                #         for key, value in replacement_dict_float.items():\n                #             replacement_tensor = torch.full_like(batch[count]['cls'], value)\n                #             batch[count]['cls'] = torch.where(batch[count]['cls'] == key, replacement_tensor, batch[count]['cls'])\n                #######\n                # Warmup\n                ni = i + nb * epoch\n                if ni <= nw:\n                    xi = [0, nw]  # x interp\n                    self.accumulate = max(1, np.interp(ni, xi, [1, self.args.nbs / self.batch_size]).round())\n                    for j, x in enumerate(self.optimizer.param_groups):\n                        # Bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0\n                        x['lr'] = np.interp(\n                            ni, xi, [self.args.warmup_bias_lr if j == 0 else 0.0, x['initial_lr'] * self.lf(epoch)])\n                        if 'momentum' in x:\n                            x['momentum'] = np.interp(ni, xi, [self.args.warmup_momentum, self.args.momentum])\n\n\n                # Forward\n                with torch.cuda.amp.autocast(self.amp):\n                    batch = self.preprocess_batch(batch)\n                    self.mul_loss = [None for _ in range(len(batch))]\n                    self.mul_loss_items = [None for _ in range(len(batch))]\n                    ######Jiayuan\n                    if self.args.task == \"multi\":\n                        preds = self.model(batch[0]['img'])\n                        for count in range(len(batch)):\n                            self.mul_loss[count], self.mul_loss_items[count] = self.criterion(preds[count], batch[count], self.data['labels_list'][count],count)\n                            if RANK != -1:\n                                self.mul_loss[count] *= world_size\n                            self.subloss[count] = (self.subloss[count] * i + self.mul_loss_items[count]) / (i + 1) if self.subloss[count] is not None \\\n                                else self.mul_loss_items[count]\n                        self.loss = sum(self.mul_loss)\n                        self.tloss = self.subloss\n                    else:\n                        preds = self.model(batch['img'])\n                        self.loss, self.loss_items = self.criterion(preds, batch)\n                        if RANK != -1:\n                            self.loss *= world_size\n                        self.tloss = (self.tloss * i + self.loss_items) / (i + 1) if self.tloss is not None \\\n                            else self.loss_items\n                    ######\n\n                # Backward\n                # self.scaler.scale(self.loss).backward(retain_graph=True)\n                # for name, param in self.model.named_parameters():\n                #     if param.grad is None:\n                #         print(f\"Parameter '{name}' does not have a gradient.\")\n\n                self.scaler.scale(self.loss).backward(retain_graph=False)  ######Jiayuan retain_graph=False Free the GPU memory,\n                ###### Due to we just use backward once, so we can safely set the retain_graph=False\n\n                # Optimize - https://pytorch.org/docs/master/notes/amp_examples.html\n                if ni - last_opt_step >= self.accumulate:\n                    self.optimizer_step()\n                    last_opt_step = ni\n                self.loss = self.loss.detach()  ######Jiayuan Free the GPU memory\n                torch.cuda.empty_cache()\n\n                # Log\n                ######Jiayuan\n                if self.args.task == 'multi':\n                    mem = f'{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G'  # (GB)\n                    losses = [loss_withdraw for loss_withdraw in self.tloss]\n                    loss_values = list(itertools.chain(*[l.tolist() for l in losses]))\n                    loss_len = len(loss_values)\n                    batch_cls = 0\n                    for count in batch:\n                        batch_cls += count['cls'].shape[0]\n                    if RANK in (-1, 0):\n                        pbar.set_description(\n                            ('%11s' * 2 + '%11.4g' * (2 + loss_len)) %\n                            (f'{epoch + 1}/{self.epochs}', mem, *loss_values, batch_cls, batch[0]['img'].shape[-1]))\n                        self.run_callbacks('on_batch_end')\n                        if self.args.plots and ni in self.plot_idx:\n                            for count in range(len(self.tloss)):\n                                self.plot_training_samples(batch[count], ni, count)\n\n                    self.run_callbacks('on_train_batch_end')\n                ######\n                else:\n                    mem = f'{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G'  # (GB)\n                    loss_len = self.tloss.shape[0] if len(self.tloss.size()) else 1\n                    losses = self.tloss if loss_len > 1 else torch.unsqueeze(self.tloss, 0)\n                    if RANK in (-1, 0):\n                        pbar.set_description(\n                            ('%11s' * 2 + '%11.4g' * (2 + loss_len)) %\n                            (f'{epoch + 1}/{self.epochs}', mem, *losses, batch['cls'].shape[0], batch['img'].shape[-1]))\n                        self.run_callbacks('on_batch_end')\n                        if self.args.plots and ni in self.plot_idx:\n                            self.plot_training_samples(batch, ni)\n\n                    self.run_callbacks('on_train_batch_end')\n\n            self.lr = {f'lr/pg{ir}': x['lr'] for ir, x in enumerate(self.optimizer.param_groups)}  # for loggers\n\n            self.scheduler.step()\n            self.run_callbacks('on_train_epoch_end')\n\n            if RANK in (-1, 0):\n\n                # Validation\n                self.ema.update_attr(self.model, include=['yaml', 'nc', 'args', 'names', 'stride', 'class_weights'])\n                final_epoch = (epoch + 1 == self.epochs) or self.stopper.possible_stop\n\n                if self.args.val or final_epoch:\n                    self.metrics, self.fitness = self.validate()\n                ######Jiayuan\n                if self.args.task == 'multi':\n                    if self.args.val:\n                        for i in range(len(losses)):\n                            self.save_metrics(metrics={**self.label_loss_items_val(self.tloss[i],prefix='train',task=self.data['labels_list'][i]), **self.metrics[i], **self.lr})\n                        self.stop = self.stopper(epoch + 1, sum(self.fitness))\n                else:\n                    self.save_metrics(metrics={**self.label_loss_items(self.tloss), **self.metrics, **self.lr})\n                    self.stop = self.stopper(epoch + 1, self.fitness)\n                ######\n                # Save model\n                if self.args.save or (epoch + 1 == self.epochs):\n                    self.save_model()\n                    self.run_callbacks('on_model_save')\n\n            tnow = time.time()\n            self.epoch_time = tnow - self.epoch_time_start\n            self.epoch_time_start = tnow\n            self.run_callbacks('on_fit_epoch_end')\n            torch.cuda.empty_cache()  # clears GPU vRAM at end of epoch, can help with out of memory errors\n\n            # Early Stopping\n            if RANK != -1:  # if DDP training\n                broadcast_list = [self.stop if RANK == 0 else None]\n                dist.broadcast_object_list(broadcast_list, 0)  # broadcast 'stop' to all ranks\n                if RANK != 0:\n                    self.stop = broadcast_list[0]\n            if self.stop:\n                break  # must break all DDP ranks\n\n        if RANK in (-1, 0):\n            # Do final val with best.pt\n            LOGGER.info(f'\\n{epoch - self.start_epoch + 1} epochs completed in '\n                        f'{(time.time() - self.train_time_start) / 3600:.3f} hours.')\n            self.final_eval()\n            if self.args.plots:\n                self.plot_metrics()\n            self.run_callbacks('on_train_end')\n        torch.cuda.empty_cache()\n        self.run_callbacks('teardown')\n\n    def save_model(self):\n        \"\"\"Save model checkpoints based on various conditions.\"\"\"\n        ckpt = {\n            'epoch': self.epoch,\n            'best_fitness': self.best_fitness,\n            'model': deepcopy(de_parallel(self.model)).half(),\n            'ema': deepcopy(self.ema.ema).half(),\n            'updates': self.ema.updates,\n            'optimizer': self.optimizer.state_dict(),\n            'train_args': vars(self.args),  # save as dict\n            'date': datetime.now().isoformat(),\n            'version': __version__}\n\n        # Save last, best and delete\n        torch.save(ckpt, self.last)\n        if not self.args.val:\n            return\n        if self.args.task == 'multi':\n            if self.best_fitness == sum(self.fitness):\n                torch.save(ckpt, self.best)\n            if (self.epoch > 0) and (self.save_period > 0) and (self.epoch % self.save_period == 0):\n                torch.save(ckpt, self.wdir / f'epoch{self.epoch}.pt')\n            del ckpt\n        else:\n            if self.best_fitness == self.fitness:\n                torch.save(ckpt, self.best)\n            if (self.epoch > 0) and (self.save_period > 0) and (self.epoch % self.save_period == 0):\n                torch.save(ckpt, self.wdir / f'epoch{self.epoch}.pt')\n            del ckpt\n\n    @staticmethod\n    def get_dataset(data):\n        \"\"\"\n        Get train, val path from data dict if it exists. Returns None if data format is not recognized.\n        \"\"\"\n        return data['train'], data.get('val') or data.get('test')\n\n    def setup_model(self):\n        \"\"\"\n        load/create/download model for any task.\n        \"\"\"\n        if isinstance(self.model, torch.nn.Module):  # if model is loaded beforehand. No setup needed\n            return\n\n        model, weights = self.model, None\n        ckpt = None\n        if str(model).endswith('.pt'):\n            weights, ckpt = attempt_load_one_weight(model)\n            cfg = ckpt['model'].yaml\n        else:\n            cfg = model\n        self.model = self.get_model(cfg=cfg, weights=weights, verbose=RANK == -1)  # calls Model(cfg, weights)\n        return ckpt\n\n    def optimizer_step(self):\n        \"\"\"Perform a single step of the training optimizer with gradient clipping and EMA update.\"\"\"\n        self.scaler.unscale_(self.optimizer)  # unscale gradients\n        torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=10.0)  # clip gradients\n        self.scaler.step(self.optimizer)\n        self.scaler.update()\n        self.optimizer.zero_grad()\n        if self.ema:\n            self.ema.update(self.model)\n\n    def preprocess_batch(self, batch):\n        \"\"\"\n        Allows custom preprocessing model inputs and ground truths depending on task type.\n        \"\"\"\n        return batch\n\n    def validate(self):\n        \"\"\"\n        Runs validation on test set using self.validator. The returned dict is expected to contain \"fitness\" key.\n        \"\"\"\n        if self.args.task == 'multi':\n            metrics_list = self.validator(self)\n            fitness_list = []\n            for metrics in metrics_list:\n                fitness_list.append(metrics.pop('fitness',\n                                      -self.loss.detach().cpu().numpy()))  # use loss as fitness measure if not found\n            fitness = sum(fitness_list)\n            if not self.best_fitness or self.best_fitness < fitness:\n                self.best_fitness = fitness\n            return metrics_list, fitness_list\n        else:\n            metrics = self.validator(self)\n            fitness = metrics.pop('fitness', -self.loss.detach().cpu().numpy())  # use loss as fitness measure if not found\n            if not self.best_fitness or self.best_fitness < fitness:\n                self.best_fitness = fitness\n            return metrics, fitness\n\n    def get_model(self, cfg=None, weights=None, verbose=True):\n        \"\"\"Get model and raise NotImplementedError for loading cfg files.\"\"\"\n        raise NotImplementedError(\"This task trainer doesn't support loading cfg files\")\n\n    def get_validator(self):\n        \"\"\"Returns a NotImplementedError when the get_validator function is called.\"\"\"\n        raise NotImplementedError('get_validator function not implemented in trainer')\n\n    def get_dataloader(self, dataset_path, batch_size=16, rank=0, mode='train'):\n        \"\"\"\n        Returns dataloader derived from torch.data.Dataloader.\n        \"\"\"\n        raise NotImplementedError('get_dataloader function not implemented in trainer')\n\n    def build_dataset(self, img_path, mode='train', batch=None):\n        \"\"\"Build dataset\"\"\"\n        raise NotImplementedError('build_dataset function not implemented in trainer')\n\n    def criterion(self, preds, batch):\n        \"\"\"\n        Returns loss and individual loss items as Tensor.\n        \"\"\"\n        raise NotImplementedError('criterion function not implemented in trainer')\n\n    def label_loss_items(self, loss_items=None, prefix='train'):\n        \"\"\"\n        Returns a loss dict with labelled training loss items tensor\n        \"\"\"\n        # Not needed for classification but necessary for segmentation & detection\n        return {'loss': loss_items} if loss_items is not None else ['loss']\n\n    def set_model_attributes(self):\n        \"\"\"\n        To set or update model parameters before training.\n        \"\"\"\n        self.model.names = self.data['names']\n\n    def build_targets(self, preds, targets):\n        \"\"\"Builds target tensors for training YOLO model.\"\"\"\n        pass\n\n    def progress_string(self):\n        \"\"\"Returns a string describing training progress.\"\"\"\n        return ''\n\n    # TODO: may need to put these following functions into callback\n    def plot_training_samples(self, batch, ni):\n        \"\"\"Plots training samples during YOLOv5 training.\"\"\"\n        pass\n\n    def plot_training_labels(self):\n        \"\"\"Plots training labels for YOLO model.\"\"\"\n        pass\n\n    def save_metrics(self, metrics):\n        \"\"\"Saves training metrics to a CSV file.\"\"\"\n        keys, vals = list(metrics.keys()), list(metrics.values())\n        n = len(metrics) + 1  # number of cols\n        s = '' if self.csv.exists() else (('%23s,' * n % tuple(['epoch'] + keys)).rstrip(',') + '\\n')  # header\n        with open(self.csv, 'a') as f:\n            f.write(s + ('%23.5g,' * n % tuple([self.epoch] + vals)).rstrip(',') + '\\n')\n\n    def plot_metrics(self):\n        \"\"\"Plot and display metrics visually.\"\"\"\n        pass\n\n    def on_plot(self, name, data=None):\n        \"\"\"Registers plots (e.g. to be consumed in callbacks)\"\"\"\n        self.plots[name] = {'data': data, 'timestamp': time.time()}\n\n    def final_eval(self):\n        \"\"\"Performs final evaluation and validation for object detection YOLO model.\"\"\"\n        for f in self.last, self.best:\n            if f.exists():\n                strip_optimizer(f)  # strip optimizers\n                if f is self.best:\n                    LOGGER.info(f'\\nValidating {f}...')\n                    self.metrics = self.validator(model=f)\n                    ######Jiayuan\n                    if self.args.task == 'multi':\n                        for metrics in self.metrics:\n                            metrics.pop('fitness', None)\n                    else:\n                        self.metrics.pop('fitness', None)\n                    ######\n                    self.run_callbacks('on_fit_epoch_end')\n\n    def check_resume(self):\n        \"\"\"Check if resume checkpoint exists and update arguments accordingly.\"\"\"\n        resume = self.args.resume\n        if resume:\n            try:\n                exists = isinstance(resume, (str, Path)) and Path(resume).exists()\n                last = Path(check_file(resume) if exists else get_latest_run())\n\n                # Check that resume data YAML exists, otherwise strip to force re-download of dataset\n                ckpt_args = attempt_load_weights(last).args\n                if not Path(ckpt_args['data']).exists():\n                    ckpt_args['data'] = self.args.data\n\n                self.args = get_cfg(ckpt_args)\n                self.args.model, resume = str(last), True  # reinstate\n            except Exception as e:\n                raise FileNotFoundError('Resume checkpoint not found. Please pass a valid checkpoint to resume from, '\n                                        \"i.e. 'yolo train resume model=path/to/last.pt'\") from e\n        self.resume = resume\n\n    def resume_training(self, ckpt):\n        \"\"\"Resume YOLO training from given epoch and best fitness.\"\"\"\n        if ckpt is None:\n            return\n        best_fitness = 0.0\n        start_epoch = ckpt['epoch'] + 1\n        if ckpt['optimizer'] is not None:\n            self.optimizer.load_state_dict(ckpt['optimizer'])  # optimizer\n            best_fitness = ckpt['best_fitness']\n        if self.ema and ckpt.get('ema'):\n            self.ema.ema.load_state_dict(ckpt['ema'].float().state_dict())  # EMA\n            self.ema.updates = ckpt['updates']\n        if self.resume:\n            assert start_epoch > 0, \\\n                f'{self.args.model} training to {self.epochs} epochs is finished, nothing to resume.\\n' \\\n                f\"Start a new training without resuming, i.e. 'yolo train model={self.args.model}'\"\n            LOGGER.info(\n                f'Resuming training from {self.args.model} from epoch {start_epoch + 1} to {self.epochs} total epochs')\n        if self.epochs < start_epoch:\n            LOGGER.info(\n                f\"{self.model} has been trained for {ckpt['epoch']} epochs. Fine-tuning for {self.epochs} more epochs.\")\n            self.epochs += ckpt['epoch']  # finetune additional epochs\n        self.best_fitness = best_fitness\n        self.start_epoch = start_epoch\n        if start_epoch > (self.epochs - self.args.close_mosaic):\n            LOGGER.info('Closing dataloader mosaic')\n            if hasattr(self.train_loader.dataset, 'mosaic'):\n                self.train_loader.dataset.mosaic = False\n            if hasattr(self.train_loader.dataset, 'close_mosaic'):\n                self.train_loader.dataset.close_mosaic(hyp=self.args)\n\n    @staticmethod\n    def build_optimizer(model, name='Adam', lr=0.001, momentum=0.9, decay=1e-5):\n        \"\"\"\n        Builds an optimizer with the specified parameters and parameter groups.\n\n        Args:\n            model (nn.Module): model to optimize\n            name (str): name of the optimizer to use\n            lr (float): learning rate\n            momentum (float): momentum\n            decay (float): weight decay\n\n        Returns:\n            optimizer (torch.optim.Optimizer): the built optimizer\n        \"\"\"\n        g = [], [], []  # optimizer parameter groups\n        bn = tuple(v for k, v in nn.__dict__.items() if 'Norm' in k)  # normalization layers, i.e. BatchNorm2d()\n        for v in model.modules():\n            if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter):  # bias (no decay)\n                g[2].append(v.bias)\n            if isinstance(v, bn):  # weight (no decay)\n                g[1].append(v.weight)\n            elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter):  # weight (with decay)\n                g[0].append(v.weight)\n\n        if name == 'Adam':\n            optimizer = torch.optim.Adam(g[2], lr=lr, betas=(momentum, 0.999))  # adjust beta1 to momentum\n        elif name == 'AdamW':\n            optimizer = torch.optim.AdamW(g[2], lr=lr, betas=(momentum, 0.999), weight_decay=0.0)\n        elif name == 'RMSProp':\n            optimizer = torch.optim.RMSprop(g[2], lr=lr, momentum=momentum)\n        elif name == 'SGD':\n            optimizer = torch.optim.SGD(g[2], lr=lr, momentum=momentum, nesterov=True)\n        else:\n            raise NotImplementedError(f'Optimizer {name} not implemented.')\n\n        optimizer.add_param_group({'params': g[0], 'weight_decay': decay})  # add g0 with weight_decay\n        optimizer.add_param_group({'params': g[1], 'weight_decay': 0.0})  # add g1 (BatchNorm2d weights)\n        LOGGER.info(f\"{colorstr('optimizer:')} {type(optimizer).__name__}(lr={lr}) with parameter groups \"\n                    f'{len(g[1])} weight(decay=0.0), {len(g[0])} weight(decay={decay}), {len(g[2])} bias')\n        return optimizer\n\n\ndef check_amp(model):\n    \"\"\"\n    This function checks the PyTorch Automatic Mixed Precision (AMP) functionality of a YOLOv8 model.\n    If the checks fail, it means there are anomalies with AMP on the system that may cause NaN losses or zero-mAP\n    results, so AMP will be disabled during training.\n\n    Args:\n        model (nn.Module): A YOLOv8 model instance.\n\n    Returns:\n        (bool): Returns True if the AMP functionality works correctly with YOLOv8 model, else False.\n\n    Raises:\n        AssertionError: If the AMP checks fail, indicating anomalies with the AMP functionality on the system.\n    \"\"\"\n    device = next(model.parameters()).device  # get model device\n    if device.type in ('cpu', 'mps'):\n        return False  # AMP only used on CUDA devices\n\n    def amp_allclose(m, im):\n        \"\"\"All close FP32 vs AMP results.\"\"\"\n        a = m(im, device=device, verbose=False)[0].boxes.data  # FP32 inference\n        with torch.cuda.amp.autocast(True):\n            b = m(im, device=device, verbose=False)[0].boxes.data  # AMP inference\n        del m\n        return a.shape == b.shape and torch.allclose(a, b.float(), atol=0.5)  # close to 0.5 absolute tolerance\n\n    f = ROOT / 'assets/bus.jpg'  # image to check\n    im = f if f.exists() else 'https://ultralytics.com/images/bus.jpg' if ONLINE else np.ones((640, 640, 3))\n    prefix = colorstr('AMP: ')\n    LOGGER.info(f'{prefix}running Automatic Mixed Precision (AMP) checks with YOLOv8n...')\n    try:\n        from ultralytics import YOLO\n        assert amp_allclose(YOLO('yolov8n.pt'), im)\n        LOGGER.info(f'{prefix}checks passed ✅')\n    except ConnectionError:\n        LOGGER.warning(f\"{prefix}checks skipped ⚠️, offline and unable to download YOLOv8n. Setting 'amp=True'.\")\n    except AssertionError:\n        LOGGER.warning(f'{prefix}checks failed ❌. Anomalies were detected with AMP on your system that may lead to '\n                       f'NaN losses or zero-mAP results, so AMP will be disabled during training.')\n        return False\n    return True\n"
  },
  {
    "path": "ultralytics/yolo/engine/validator.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nCheck a model's accuracy on a test or val split of a dataset\n\nUsage:\n    $ yolo mode=val model=yolov8n.pt data=coco128.yaml imgsz=640\n\nUsage - formats:\n    $ yolo mode=val model=yolov8n.pt                 # PyTorch\n                          yolov8n.torchscript        # TorchScript\n                          yolov8n.onnx               # ONNX Runtime or OpenCV DNN with dnn=True\n                          yolov8n_openvino_model     # OpenVINO\n                          yolov8n.engine             # TensorRT\n                          yolov8n.mlmodel            # CoreML (macOS-only)\n                          yolov8n_saved_model        # TensorFlow SavedModel\n                          yolov8n.pb                 # TensorFlow GraphDef\n                          yolov8n.tflite             # TensorFlow Lite\n                          yolov8n_edgetpu.tflite     # TensorFlow Edge TPU\n                          yolov8n_paddle_model       # PaddlePaddle\n\"\"\"\nimport json\nimport time\nfrom pathlib import Path\n\nimport torch\nfrom tqdm import tqdm\nimport torch.nn as nn\nfrom ultralytics.nn.autobackend import AutoBackend\nfrom ultralytics.yolo.cfg import get_cfg\nfrom ultralytics.yolo.data.utils import check_cls_dataset, check_det_dataset\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, RANK, SETTINGS, TQDM_BAR_FORMAT, callbacks, colorstr, emojis\nfrom ultralytics.yolo.utils.checks import check_imgsz\nfrom ultralytics.yolo.utils.files import increment_path\nfrom ultralytics.yolo.utils.ops import Profile\nfrom ultralytics.yolo.utils.torch_utils import de_parallel, select_device, smart_inference_mode\nfrom ultralytics.yolo.utils.metrics import DetMetrics, SegmentMetrics, SegmentationMetric, AverageMeter\n\nclass BaseValidator:\n    \"\"\"\n    BaseValidator\n\n    A base class for creating validators.\n\n    Attributes:\n        dataloader (DataLoader): Dataloader to use for validation.\n        pbar (tqdm): Progress bar to update during validation.\n        args (SimpleNamespace): Configuration for the validator.\n        model (nn.Module): Model to validate.\n        data (dict): Data dictionary.\n        device (torch.device): Device to use for validation.\n        batch_i (int): Current batch index.\n        training (bool): Whether the model is in training mode.\n        speed (float): Batch processing speed in seconds.\n        jdict (dict): Dictionary to store validation results.\n        save_dir (Path): Directory to save results.\n    \"\"\"\n\n    def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):\n        \"\"\"\n        Initializes a BaseValidator instance.\n\n        Args:\n            dataloader (torch.utils.data.DataLoader): Dataloader to be used for validation.\n            save_dir (Path): Directory to save results.\n            pbar (tqdm.tqdm): Progress bar for displaying progress.\n            args (SimpleNamespace): Configuration for the validator.\n        \"\"\"\n        self.dataloader = dataloader\n        self.pbar = pbar\n        self.args = args or get_cfg(DEFAULT_CFG)\n        self.model = None\n        self.data = None\n        self.device = None\n        self.batch_i = None\n        self.training = True\n        self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}\n        self.jdict = None\n\n\n        project = self.args.project or Path(SETTINGS['runs_dir']) / self.args.task\n        name = self.args.name or f'{self.args.mode}'\n        self.save_dir = save_dir or increment_path(Path(project) / name,\n                                                   exist_ok=self.args.exist_ok if RANK in (-1, 0) else True)\n        (self.save_dir / 'labels' if self.args.save_txt else self.save_dir).mkdir(parents=True, exist_ok=True)\n\n        if self.args.conf is None:\n            self.args.conf = 0.001  # default conf=0.001\n\n        self.plots = {}\n        self.callbacks = _callbacks or callbacks.get_default_callbacks()\n\n    @smart_inference_mode()\n    def __call__(self, trainer=None, model=None):\n        \"\"\"\n        Supports validation of a pre-trained model if passed or a model being trained\n        if trainer is passed (trainer gets priority).\n        \"\"\"\n        self.training = trainer is not None\n        if self.training:\n            self.device = trainer.device\n            self.data = trainer.data\n            model = trainer.ema.ema or trainer.model\n            self.args.half = self.device.type != 'cpu'  # force FP16 val during training\n            model = model.half() if self.args.half else model.float()\n            self.model = model\n            ######Jiayuan\n            losses = []\n            if trainer.args.task == 'multi':\n                for tensor in trainer.mul_loss_items:\n                    losses.append(torch.zeros_like(tensor, device=trainer.device))\n                self.loss = losses\n                self.seg_metrics = {name: SegmentationMetric(self.data['nc_list'][count] + 1) for count, name in\n                                    enumerate(self.data['labels_list']) if 'seg' in name}\n                self.seg_result = {name: {'pixacc': AverageMeter(), 'subacc': AverageMeter(), 'IoU': AverageMeter(),\n                                          'mIoU': AverageMeter()} for count, name in\n                                   enumerate(self.data['labels_list']) if 'seg' in name}\n            else:\n                self.loss = torch.zeros_like(trainer.loss_items, device=trainer.device)\n            self.args.plots = trainer.stopper.possible_stop or (trainer.epoch == trainer.epochs - 1)\n            ######\n            model.eval()\n        else:\n            callbacks.add_integration_callbacks(self)\n            self.run_callbacks('on_val_start')\n            assert model is not None, 'Either trainer or model is needed for validation'\n            self.device = select_device(self.args.device, self.args.batch)\n            self.args.half &= self.device.type != 'cpu'\n            model = AutoBackend(model, device=self.device, dnn=self.args.dnn, data=self.args.data, fp16=self.args.half)\n            self.model = model\n            stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine\n            imgsz = check_imgsz(self.args.imgsz, stride=stride)\n            if engine:\n                self.args.batch = model.batch_size\n            else:\n                self.device = model.device\n                if not pt and not jit:\n                    self.args.batch = 1  # export.py models default to batch-size 1\n                    LOGGER.info(f'Forcing batch=1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models')\n\n            if isinstance(self.args.data, str) and self.args.data.endswith('.yaml'):\n                self.data = check_det_dataset(self.args.data)\n            elif self.args.task == 'classify':\n                self.data = check_cls_dataset(self.args.data)\n            else:\n                raise FileNotFoundError(emojis(f\"Dataset '{self.args.data}' for task={self.args.task} not found ❌\"))\n\n            if self.device.type == 'cpu':\n                self.args.workers = 0  # faster CPU val as time dominated by inference, not dataloading\n            if not pt:\n                self.args.rect = False\n            self.dataloader = self.dataloader or self.get_dataloader(self.data.get(self.args.split), self.args.batch)\n            if self.args.task == 'multi':\n                self.seg_metrics = {name: SegmentationMetric(self.data['nc_list'][count]+1) for count, name in enumerate(self.data['labels_list']) if 'seg' in name}\n                self.seg_result = {name: {'pixacc': AverageMeter(), 'subacc': AverageMeter(),'IoU': AverageMeter(), 'mIoU': AverageMeter()} for count, name in enumerate(self.data['labels_list']) if 'seg' in name}\n\n            model.eval()\n            model.warmup(imgsz=(1 if pt else self.args.batch, 3, imgsz, imgsz))  # warmup\n\n        if not self.metrics:\n            for name in self.data['labels_list']:\n                if 'det' in name:\n                    self.metrics.append(DetMetrics(save_dir=self.save_dir, on_plot=self.on_plot))\n                if 'seg' in name:\n                    self.metrics.append(SegmentMetrics(save_dir=self.save_dir, on_plot=self.on_plot))\n        dt = Profile(), Profile(), Profile(), Profile()\n        n_batches = len(self.dataloader)\n        desc = self.get_desc()\n        # NOTE: keeping `not self.training` in tqdm will eliminate pbar after segmentation evaluation during training,\n        # which may affect classification task since this arg is in yolov5/classify/val.py.\n        # bar = tqdm(self.dataloader, desc, n_batches, not self.training, bar_format=TQDM_BAR_FORMAT)\n        bar = tqdm(self.dataloader, desc, n_batches, bar_format=TQDM_BAR_FORMAT)\n        self.init_metrics(de_parallel(model))\n        self.jdict = []  # empty before each val\n        for batch_i, batch in enumerate(bar):\n            self.run_callbacks('on_val_batch_start')\n            self.batch_i = batch_i\n            ######Jiayuan\n            # if self.args.task == 'multi':\n            #     for count, map in enumerate(self.data['map']):\n            #         if map != 'None':\n            #             replacement_dict_float = {float(key): float(value) for key, value in map.items()}\n            #             for key, value in replacement_dict_float.items():\n            #                 replacement_tensor = torch.full_like(batch[count]['cls'], value)\n            #                 batch[count]['cls'] = torch.where(batch[count]['cls'] == key, replacement_tensor,\n            #                                               batch[count]['cls'])\n            ######\n            # Preprocess\n            with dt[0]:\n                batch = self.preprocess(batch)\n\n            if self.args.speed and batch_i==0:\n                device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n                model = model.to(device)\n\n                with torch.no_grad():\n                    x = batch[0]['img'][0, ...].to(device)\n                    x.unsqueeze_(0)\n                    # Pre-warming\n                    for _ in range(5):\n                        _ = model(x)\n\n                    # Test for batch_size = 1\n                    print('test1: model inferring')\n                    print('inferring 1 image for 1000 times...')\n\n                    torch.cuda.synchronize()\n                    start_time = time.time()\n\n                    for _ in range(1000):\n                        _ = model(x)\n\n                    torch.cuda.synchronize()\n                    end_time = time.time()\n                    elapsed_time = (end_time - start_time) / 1000\n                    print(f'{elapsed_time} seconds, {1 / elapsed_time} FPS, @batch_size 1')\n\n                    # Test for batch_size = 32\n                    print('test2: model inferring only')\n                    print('inferring images for batch_size 32 for 1000 times...')\n                    x = torch.cat([x] * 32, 0).to(device)\n\n                    torch.cuda.synchronize()\n                    start_time = time.time()\n\n                    for _ in range(1000):\n                        _ = model(x)\n\n                    torch.cuda.synchronize()\n                    end_time = time.time()\n                    elapsed_time = (end_time - start_time) / 1000\n                    print(f'{elapsed_time} seconds, {32 / elapsed_time} FPS, @batch_size 32')\n\n\n            # Inference\n            with dt[1]:\n                if self.args.task == 'multi':\n                    preds_list = model(batch[0]['img'])\n                else:\n                    preds = model(batch['img'])\n\n            # Loss\n            with dt[2]:\n                if self.training:\n                    if self.args.task == 'multi':\n                        for i,preds in enumerate(preds_list):\n                            self.loss[i] += trainer.criterion(preds, batch[i],self.data['labels_list'][i],i)[1]\n                    else:\n                        self.loss += trainer.criterion(preds, batch)[1]\n            # Postprocess\n            with dt[3]:\n                if self.args.task == 'multi':\n                    preds_list_post = []\n                    for i, preds in enumerate(preds_list):\n                        if 'det' in self.data['labels_list'][i]:\n                            preds = self.postprocess_det(preds)\n                            preds_list_post.append(preds)\n                        elif 'seg' in self.data['labels_list'][i]:\n                            preds = self.postprocess_seg(preds,i)\n                            preds_list_post.append(preds)\n                else:\n                    preds = self.postprocess(preds)\n\n            if self.args.task == 'multi':\n                for i,label_name in enumerate(self.data['labels_list']):\n                    if 'det' in label_name:\n                        self.update_metrics_det(preds_list_post[i], batch[i], label_name)\n                    elif 'seg' in label_name:\n                        self.update_metrics_seg(preds_list_post[i], batch[i], label_name)\n            else:\n                self.update_metrics(preds, batch)\n            if self.args.plots and batch_i < 3:\n                if self.args.task == 'multi':\n                    for i, label_name in enumerate(self.data['labels_list']):\n                        self.plot_val_samples(batch[i], batch_i, label_name)\n                        self.plot_predictions(batch[i], preds_list_post[i], batch_i, label_name)\n                else:\n                    self.plot_val_samples(batch, batch_i)\n                    self.plot_predictions(batch, preds, batch_i)\n\n            self.run_callbacks('on_val_batch_end')\n        if self.args.task == 'multi':\n            stats = self.get_stats()\n            # self.check_stats(stats)\n            self.speed = dict(zip(self.speed.keys(), (x.t / len(self.dataloader.dataset) * 1E3 / len(self.data['labels_list']) for x in dt)))\n            self.finalize_metrics()\n            self.print_results()\n        else:\n            stats = self.get_stats()\n            self.check_stats(stats)\n            self.speed = dict(zip(self.speed.keys(), (x.t / len(self.dataloader.dataset) * 1E3 for x in dt)))\n            self.finalize_metrics()\n            self.print_results()\n        self.run_callbacks('on_val_end')\n\n        if self.args.task == 'multi':\n            if self.training:\n                model.float()\n                results_list = []\n                for i, label_name in enumerate(self.data['labels_list']):\n                    try:\n                        results = {**stats[i], **trainer.label_loss_items_val(self.loss[i].cpu() / len(self.dataloader), prefix='val',task=label_name)}\n                        results_list.append({k: round(float(v), 5) for k, v in results.items()})\n                    except:\n                        key_values = [(key, value.avg) for key, value in self.seg_result[label_name].items()]\n                        result = key_values[2][1]+key_values[3][1]\n                        dic = {'fitness':result}\n                        results_list.append(dic)\n                return results_list  # return results as 5 decimal place floats\n            else:\n                LOGGER.info('Speed: %.1fms preprocess, %.1fms inference, %.1fms loss, %.1fms postprocess per image' %\n                            tuple(self.speed.values()))\n                if self.args.save_json and self.jdict:\n                    with open(str(self.save_dir / 'predictions.json'), 'w') as f:\n                        LOGGER.info(f'Saving {f.name}...')\n                        json.dump(self.jdict, f)  # flatten and save\n                    stats = self.eval_json(stats)  # update stats\n                if self.args.plots or self.args.save_json:\n                    LOGGER.info(f\"Results saved to {colorstr('bold', self.save_dir)}\")\n                return stats\n        else:\n            if self.training:\n                model.float()\n                results = {**stats, **trainer.label_loss_items(self.loss.cpu() / len(self.dataloader), prefix='val')}\n                return {k: round(float(v), 5) for k, v in results.items()}  # return results as 5 decimal place floats\n            else:\n                LOGGER.info('Speed: %.1fms preprocess, %.1fms inference, %.1fms loss, %.1fms postprocess per image' %\n                            tuple(self.speed.values()))\n                if self.args.save_json and self.jdict:\n                    with open(str(self.save_dir / 'predictions.json'), 'w') as f:\n                        LOGGER.info(f'Saving {f.name}...')\n                        json.dump(self.jdict, f)  # flatten and save\n                    stats = self.eval_json(stats)  # update stats\n                if self.args.plots or self.args.save_json:\n                    LOGGER.info(f\"Results saved to {colorstr('bold', self.save_dir)}\")\n                return stats\n\n    def add_callback(self, event: str, callback):\n        \"\"\"Appends the given callback.\"\"\"\n        self.callbacks[event].append(callback)\n\n    def run_callbacks(self, event: str):\n        \"\"\"Runs all callbacks associated with a specified event.\"\"\"\n        for callback in self.callbacks.get(event, []):\n            callback(self)\n\n    def get_dataloader(self, dataset_path, batch_size):\n        \"\"\"Get data loader from dataset path and batch size.\"\"\"\n        raise NotImplementedError('get_dataloader function not implemented for this validator')\n\n    def build_dataset(self, img_path):\n        \"\"\"Build dataset\"\"\"\n        raise NotImplementedError('build_dataset function not implemented in validator')\n\n    def preprocess(self, batch):\n        \"\"\"Preprocesses an input batch.\"\"\"\n        return batch\n\n    def postprocess(self, preds):\n        \"\"\"Describes and summarizes the purpose of 'postprocess()' but no details mentioned.\"\"\"\n        return preds\n\n    def init_metrics(self, model):\n        \"\"\"Initialize performance metrics for the YOLO model.\"\"\"\n        pass\n\n    def update_metrics(self, preds, batch):\n        \"\"\"Updates metrics based on predictions and batch.\"\"\"\n        pass\n\n    def finalize_metrics(self, *args, **kwargs):\n        \"\"\"Finalizes and returns all metrics.\"\"\"\n        pass\n\n    def get_stats(self):\n        \"\"\"Returns statistics about the model's performance.\"\"\"\n        return {}\n\n    def check_stats(self, stats):\n        \"\"\"Checks statistics.\"\"\"\n        pass\n\n    def print_results(self):\n        \"\"\"Prints the results of the model's predictions.\"\"\"\n        pass\n\n    def get_desc(self):\n        \"\"\"Get description of the YOLO model.\"\"\"\n        pass\n\n    @property\n    def metric_keys(self):\n        \"\"\"Returns the metric keys used in YOLO training/validation.\"\"\"\n        return []\n\n    def on_plot(self, name, data=None):\n        \"\"\"Registers plots (e.g. to be consumed in callbacks)\"\"\"\n        self.plots[name] = {'data': data, 'timestamp': time.time()}\n\n    # TODO: may need to put these following functions into callback\n    def plot_val_samples(self, batch, ni):\n        \"\"\"Plots validation samples during training.\"\"\"\n        pass\n\n    def plot_predictions(self, batch, preds, ni):\n        \"\"\"Plots YOLO model predictions on batch images.\"\"\"\n        pass\n\n    def pred_to_json(self, preds, batch):\n        \"\"\"Convert predictions to JSON format.\"\"\"\n        pass\n\n    def eval_json(self, stats):\n        \"\"\"Evaluate and return JSON format of prediction statistics.\"\"\"\n        pass\n"
  },
  {
    "path": "ultralytics/yolo/utils/.ipynb_checkpoints/metrics-checkpoint.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nModel validation metrics\n\"\"\"\nimport math\nimport warnings\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom ultralytics.yolo.utils import LOGGER, SimpleClass, TryExcept, plt_settings\n\nOKS_SIGMA = np.array([.26, .25, .25, .35, .35, .79, .79, .72, .72, .62, .62, 1.07, 1.07, .87, .87, .89, .89]) / 10.0\n\n\n# Boxes\ndef box_area(box):\n    \"\"\"Return box area, where box shape is xyxy(4,n).\"\"\"\n    return (box[2] - box[0]) * (box[3] - box[1])\n\n\ndef bbox_ioa(box1, box2, eps=1e-7):\n    \"\"\"\n    Calculate the intersection over box2 area given box1 and box2. Boxes are in x1y1x2y2 format.\n\n    Args:\n        box1 (np.array): A numpy array of shape (n, 4) representing n bounding boxes.\n        box2 (np.array): A numpy array of shape (m, 4) representing m bounding boxes.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (np.array): A numpy array of shape (n, m) representing the intersection over box2 area.\n    \"\"\"\n\n    # Get the coordinates of bounding boxes\n    b1_x1, b1_y1, b1_x2, b1_y2 = box1.T\n    b2_x1, b2_y1, b2_x2, b2_y2 = box2.T\n\n    # Intersection area\n    inter_area = (np.minimum(b1_x2[:, None], b2_x2) - np.maximum(b1_x1[:, None], b2_x1)).clip(0) * \\\n                 (np.minimum(b1_y2[:, None], b2_y2) - np.maximum(b1_y1[:, None], b2_y1)).clip(0)\n\n    # box2 area\n    box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps\n\n    # Intersection over box2 area\n    return inter_area / box2_area\n\n\ndef box_iou(box1, box2, eps=1e-7):\n    \"\"\"\n    Calculate intersection-over-union (IoU) of boxes.\n    Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n    Based on https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py\n\n    Args:\n        box1 (torch.Tensor): A tensor of shape (N, 4) representing N bounding boxes.\n        box2 (torch.Tensor): A tensor of shape (M, 4) representing M bounding boxes.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (torch.Tensor): An NxM tensor containing the pairwise IoU values for every element in box1 and box2.\n    \"\"\"\n\n    # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)\n    (a1, a2), (b1, b2) = box1.unsqueeze(1).chunk(2, 2), box2.unsqueeze(0).chunk(2, 2)\n    inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2)\n\n    # IoU = inter / (area1 + area2 - inter)\n    return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)\n\n\ndef bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):\n    \"\"\"\n    Calculate Intersection over Union (IoU) of box1(1, 4) to box2(n, 4).\n\n    Args:\n        box1 (torch.Tensor): A tensor representing a single bounding box with shape (1, 4).\n        box2 (torch.Tensor): A tensor representing n bounding boxes with shape (n, 4).\n        xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in\n                               (x1, y1, x2, y2) format. Defaults to True.\n        GIoU (bool, optional): If True, calculate Generalized IoU. Defaults to False.\n        DIoU (bool, optional): If True, calculate Distance IoU. Defaults to False.\n        CIoU (bool, optional): If True, calculate Complete IoU. Defaults to False.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.\n    \"\"\"\n\n    # Get the coordinates of bounding boxes\n    if xywh:  # transform from xywh to xyxy\n        (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)\n        w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2\n        b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_\n        b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_\n    else:  # x1, y1, x2, y2 = box1\n        b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)\n        b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)\n        w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps\n        w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps\n\n    # Intersection area\n    inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp(0) * \\\n            (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp(0)\n\n    # Union Area\n    union = w1 * h1 + w2 * h2 - inter + eps\n\n    # IoU\n    iou = inter / union\n    if CIoU or DIoU or GIoU:\n        cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1)  # convex (smallest enclosing box) width\n        ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1)  # convex height\n        if CIoU or DIoU:  # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1\n            c2 = cw ** 2 + ch ** 2 + eps  # convex diagonal squared\n            rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4  # center dist ** 2\n            if CIoU:  # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47\n                v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)\n                with torch.no_grad():\n                    alpha = v / (v - iou + (1 + eps))\n                return iou - (rho2 / c2 + v * alpha)  # CIoU\n            return iou - rho2 / c2  # DIoU\n        c_area = cw * ch + eps  # convex area\n        return iou - (c_area - union) / c_area  # GIoU https://arxiv.org/pdf/1902.09630.pdf\n    return iou  # IoU\n\n\ndef mask_iou(mask1, mask2, eps=1e-7):\n    \"\"\"\n    Calculate masks IoU.\n\n    Args:\n        mask1 (torch.Tensor): A tensor of shape (N, n) where N is the number of ground truth objects and n is the\n                        product of image width and height.\n        mask2 (torch.Tensor): A tensor of shape (M, n) where M is the number of predicted objects and n is the\n                        product of image width and height.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (torch.Tensor): A tensor of shape (N, M) representing masks IoU.\n    \"\"\"\n    intersection = torch.matmul(mask1, mask2.t()).clamp(0)\n    union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection  # (area1 + area2) - intersection\n    return intersection / (union + eps)\n\n\ndef kpt_iou(kpt1, kpt2, area, sigma, eps=1e-7):\n    \"\"\"\n    Calculate Object Keypoint Similarity (OKS).\n\n    Args:\n        kpt1 (torch.Tensor): A tensor of shape (N, 17, 3) representing ground truth keypoints.\n        kpt2 (torch.Tensor): A tensor of shape (M, 17, 3) representing predicted keypoints.\n        area (torch.Tensor): A tensor of shape (N,) representing areas from ground truth.\n        sigma (list): A list containing 17 values representing keypoint scales.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (torch.Tensor): A tensor of shape (N, M) representing keypoint similarities.\n    \"\"\"\n    d = (kpt1[:, None, :, 0] - kpt2[..., 0]) ** 2 + (kpt1[:, None, :, 1] - kpt2[..., 1]) ** 2  # (N, M, 17)\n    sigma = torch.tensor(sigma, device=kpt1.device, dtype=kpt1.dtype)  # (17, )\n    kpt_mask = kpt1[..., 2] != 0  # (N, 17)\n    e = d / (2 * sigma) ** 2 / (area[:, None, None] + eps) / 2  # from cocoeval\n    # e = d / ((area[None, :, None] + eps) * sigma) ** 2 / 2  # from formula\n    return (torch.exp(-e) * kpt_mask[:, None]).sum(-1) / (kpt_mask.sum(-1)[:, None] + eps)\n\n\ndef smooth_BCE(eps=0.1):  # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441\n    # return positive, negative label smoothing BCE targets\n    return 1.0 - 0.5 * eps, 0.5 * eps\n\n\n# Losses\nclass FocalLoss(nn.Module):\n    \"\"\"Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5).\"\"\"\n\n    def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):\n        \"\"\"Initialize FocalLoss object with given loss function and hyperparameters.\"\"\"\n        super().__init__()\n        self.loss_fcn = loss_fcn  # must be nn.BCEWithLogitsLoss()\n        self.gamma = gamma\n        self.alpha = alpha\n        self.reduction = loss_fcn.reduction\n        self.loss_fcn.reduction = 'none'  # required to apply FL to each element\n\n    def forward(self, pred, true):\n        \"\"\"Calculates and updates confusion matrix for object detection/classification tasks.\"\"\"\n        loss = self.loss_fcn(pred, true)\n        # p_t = torch.exp(-loss)\n        # loss *= self.alpha * (1.000001 - p_t) ** self.gamma  # non-zero power for gradient stability\n\n        # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py\n        pred_prob = torch.sigmoid(pred)  # prob from logits\n        p_t = true * pred_prob + (1 - true) * (1 - pred_prob)\n        alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)\n        modulating_factor = (1.0 - p_t) ** self.gamma\n        loss *= alpha_factor * modulating_factor\n\n        if self.reduction == 'mean':\n            return loss.mean()\n        elif self.reduction == 'sum':\n            return loss.sum()\n        else:  # 'None'\n            return loss\n\n\nclass ConfusionMatrix:\n    \"\"\"\n    A class for calculating and updating a confusion matrix for object detection and classification tasks.\n\n    Attributes:\n        task (str): The type of task, either 'detect' or 'classify'.\n        matrix (np.array): The confusion matrix, with dimensions depending on the task.\n        nc (int): The number of classes.\n        conf (float): The confidence threshold for detections.\n        iou_thres (float): The Intersection over Union threshold.\n    \"\"\"\n\n    def __init__(self, nc, conf=0.25, iou_thres=0.45, task='detect'):\n        \"\"\"Initialize attributes for the YOLO model.\"\"\"\n        self.task = task\n        self.matrix = np.zeros((nc + 1, nc + 1)) if self.task == 'detect' else np.zeros((nc, nc))\n        self.nc = nc  # number of classes\n        self.conf = conf\n        self.iou_thres = iou_thres\n\n    def process_cls_preds(self, preds, targets):\n        \"\"\"\n        Update confusion matrix for classification task\n\n        Args:\n            preds (Array[N, min(nc,5)]): Predicted class labels.\n            targets (Array[N, 1]): Ground truth class labels.\n        \"\"\"\n        preds, targets = torch.cat(preds)[:, 0], torch.cat(targets)\n        for p, t in zip(preds.cpu().numpy(), targets.cpu().numpy()):\n            self.matrix[t][p] += 1\n\n    def process_batch(self, detections, labels):\n        \"\"\"\n        Update confusion matrix for object detection task.\n\n        Args:\n            detections (Array[N, 6]): Detected bounding boxes and their associated information.\n                                      Each row should contain (x1, y1, x2, y2, conf, class).\n            labels (Array[M, 5]): Ground truth bounding boxes and their associated class labels.\n                                  Each row should contain (class, x1, y1, x2, y2).\n        \"\"\"\n        if detections is None:\n            gt_classes = labels.int()\n            for gc in gt_classes:\n                self.matrix[self.nc, gc] += 1  # background FN\n            return\n\n        detections = detections[detections[:, 4] > self.conf]\n        gt_classes = labels[:, 0].int()\n        detection_classes = detections[:, 5].int()\n        iou = box_iou(labels[:, 1:], detections[:, :4])\n\n        x = torch.where(iou > self.iou_thres)\n        if x[0].shape[0]:\n            matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()\n            if x[0].shape[0] > 1:\n                matches = matches[matches[:, 2].argsort()[::-1]]\n                matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                matches = matches[matches[:, 2].argsort()[::-1]]\n                matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n        else:\n            matches = np.zeros((0, 3))\n\n        n = matches.shape[0] > 0\n        m0, m1, _ = matches.transpose().astype(int)\n        for i, gc in enumerate(gt_classes):\n            j = m0 == i\n            if n and sum(j) == 1:\n                self.matrix[detection_classes[m1[j]], gc] += 1  # correct\n            else:\n                self.matrix[self.nc, gc] += 1  # true background\n\n        if n:\n            for i, dc in enumerate(detection_classes):\n                if not any(m1 == i):\n                    self.matrix[dc, self.nc] += 1  # predicted background\n\n    def matrix(self):\n        \"\"\"Returns the confusion matrix.\"\"\"\n        return self.matrix\n\n    def tp_fp(self):\n        \"\"\"Returns true positives and false positives.\"\"\"\n        tp = self.matrix.diagonal()  # true positives\n        fp = self.matrix.sum(1) - tp  # false positives\n        # fn = self.matrix.sum(0) - tp  # false negatives (missed detections)\n        return (tp[:-1], fp[:-1]) if self.task == 'detect' else (tp, fp)  # remove background class if task=detect\n\n    @TryExcept('WARNING ⚠️ ConfusionMatrix plot failure')\n    @plt_settings()\n    def plot(self, normalize=True, save_dir='', names=(), on_plot=None):\n        \"\"\"\n        Plot the confusion matrix using seaborn and save it to a file.\n\n        Args:\n            normalize (bool): Whether to normalize the confusion matrix.\n            save_dir (str): Directory where the plot will be saved.\n            names (tuple): Names of classes, used as labels on the plot.\n            on_plot (func): An optional callback to pass plots path and data when they are rendered.\n        \"\"\"\n        import seaborn as sn\n\n        array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1)  # normalize columns\n        array[array < 0.005] = np.nan  # don't annotate (would appear as 0.00)\n\n        fig, ax = plt.subplots(1, 1, figsize=(12, 9), tight_layout=True)\n        nc, nn = self.nc, len(names)  # number of classes, names\n        sn.set(font_scale=1.0 if nc < 50 else 0.8)  # for label size\n        labels = (0 < nn < 99) and (nn == nc)  # apply names to ticklabels\n        ticklabels = (list(names) + ['background']) if labels else 'auto'\n        with warnings.catch_warnings():\n            warnings.simplefilter('ignore')  # suppress empty matrix RuntimeWarning: All-NaN slice encountered\n            sn.heatmap(array,\n                       ax=ax,\n                       annot=nc < 30,\n                       annot_kws={\n                           'size': 8},\n                       cmap='Blues',\n                       fmt='.2f' if normalize else '.0f',\n                       square=True,\n                       vmin=0.0,\n                       xticklabels=ticklabels,\n                       yticklabels=ticklabels).set_facecolor((1, 1, 1))\n        title = 'Confusion Matrix' + ' Normalized' * normalize\n        ax.set_xlabel('True')\n        ax.set_ylabel('Predicted')\n        ax.set_title(title)\n        plot_fname = Path(save_dir) / f'{title.lower().replace(\" \", \"_\")}.png'\n        fig.savefig(plot_fname, dpi=250)\n        plt.close(fig)\n        if on_plot:\n            on_plot(plot_fname)\n\n    def print(self):\n        \"\"\"\n        Print the confusion matrix to the console.\n        \"\"\"\n        for i in range(self.nc + 1):\n            LOGGER.info(' '.join(map(str, self.matrix[i])))\n\ndef smooth(y, f=0.05):\n    \"\"\"Box filter of fraction f.\"\"\"\n    nf = round(len(y) * f * 2) // 2 + 1  # number of filter elements (must be odd)\n    p = np.ones(nf // 2)  # ones padding\n    yp = np.concatenate((p * y[0], y, p * y[-1]), 0)  # y padded\n    return np.convolve(yp, np.ones(nf) / nf, mode='valid')  # y-smoothed\n\n\n@plt_settings()\ndef plot_pr_curve(px, py, ap, save_dir=Path('pr_curve.png'), names=(), on_plot=None):\n    \"\"\"Plots a precision-recall curve.\"\"\"\n    fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)\n    py = np.stack(py, axis=1)\n\n    if 0 < len(names) < 21:  # display per-class legend if < 21 classes\n        for i, y in enumerate(py.T):\n            ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}')  # plot(recall, precision)\n    else:\n        ax.plot(px, py, linewidth=1, color='grey')  # plot(recall, precision)\n\n    ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())\n    ax.set_xlabel('Recall')\n    ax.set_ylabel('Precision')\n    ax.set_xlim(0, 1)\n    ax.set_ylim(0, 1)\n    ax.legend(bbox_to_anchor=(1.04, 1), loc='upper left')\n    ax.set_title('Precision-Recall Curve')\n    fig.savefig(save_dir, dpi=250)\n    plt.close(fig)\n    if on_plot:\n        on_plot(save_dir)\n\n\n@plt_settings()\ndef plot_mc_curve(px, py, save_dir=Path('mc_curve.png'), names=(), xlabel='Confidence', ylabel='Metric', on_plot=None):\n    \"\"\"Plots a metric-confidence curve.\"\"\"\n    fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)\n\n    if 0 < len(names) < 21:  # display per-class legend if < 21 classes\n        for i, y in enumerate(py):\n            ax.plot(px, y, linewidth=1, label=f'{names[i]}')  # plot(confidence, metric)\n    else:\n        ax.plot(px, py.T, linewidth=1, color='grey')  # plot(confidence, metric)\n\n    y = smooth(py.mean(0), 0.05)\n    ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')\n    ax.set_xlabel(xlabel)\n    ax.set_ylabel(ylabel)\n    ax.set_xlim(0, 1)\n    ax.set_ylim(0, 1)\n    ax.legend(bbox_to_anchor=(1.04, 1), loc='upper left')\n    ax.set_title(f'{ylabel}-Confidence Curve')\n    fig.savefig(save_dir, dpi=250)\n    plt.close(fig)\n    if on_plot:\n        on_plot(save_dir)\n\n\ndef compute_ap(recall, precision):\n    \"\"\"\n    Compute the average precision (AP) given the recall and precision curves.\n\n    Arguments:\n        recall (list): The recall curve.\n        precision (list): The precision curve.\n\n    Returns:\n        (float): Average precision.\n        (np.ndarray): Precision envelope curve.\n        (np.ndarray): Modified recall curve with sentinel values added at the beginning and end.\n    \"\"\"\n\n    # Append sentinel values to beginning and end\n    mrec = np.concatenate(([0.0], recall, [1.0]))\n    mpre = np.concatenate(([1.0], precision, [0.0]))\n\n    # Compute the precision envelope\n    mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))\n\n    # Integrate area under curve\n    method = 'interp'  # methods: 'continuous', 'interp'\n    if method == 'interp':\n        x = np.linspace(0, 1, 101)  # 101-point interp (COCO)\n        ap = np.trapz(np.interp(x, mrec, mpre), x)  # integrate\n    else:  # 'continuous'\n        i = np.where(mrec[1:] != mrec[:-1])[0]  # points where x-axis (recall) changes\n        ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])  # area under curve\n\n    return ap, mpre, mrec\n\n\ndef ap_per_class(tp,\n                 conf,\n                 pred_cls,\n                 target_cls,\n                 plot=False,\n                 on_plot=None,\n                 save_dir=Path(),\n                 names=(),\n                 eps=1e-16,\n                 prefix=''):\n    \"\"\"\n    Computes the average precision per class for object detection evaluation.\n\n    Args:\n        tp (np.ndarray): Binary array indicating whether the detection is correct (True) or not (False).\n        conf (np.ndarray): Array of confidence scores of the detections.\n        pred_cls (np.ndarray): Array of predicted classes of the detections.\n        target_cls (np.ndarray): Array of true classes of the detections.\n        plot (bool, optional): Whether to plot PR curves or not. Defaults to False.\n        on_plot (func, optional): A callback to pass plots path and data when they are rendered. Defaults to None.\n        save_dir (Path, optional): Directory to save the PR curves. Defaults to an empty path.\n        names (tuple, optional): Tuple of class names to plot PR curves. Defaults to an empty tuple.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-16.\n        prefix (str, optional): A prefix string for saving the plot files. Defaults to an empty string.\n\n    Returns:\n        (tuple): A tuple of six arrays and one array of unique classes, where:\n            tp (np.ndarray): True positive counts for each class.\n            fp (np.ndarray): False positive counts for each class.\n            p (np.ndarray): Precision values at each confidence threshold.\n            r (np.ndarray): Recall values at each confidence threshold.\n            f1 (np.ndarray): F1-score values at each confidence threshold.\n            ap (np.ndarray): Average precision for each class at different IoU thresholds.\n            unique_classes (np.ndarray): An array of unique classes that have data.\n\n    \"\"\"\n\n    # Sort by objectness\n    i = np.argsort(-conf)\n    tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]\n\n    # Find unique classes\n    unique_classes, nt = np.unique(target_cls, return_counts=True)\n    nc = unique_classes.shape[0]  # number of classes, number of detections\n\n    # Create Precision-Recall curve and compute AP for each class\n    px, py = np.linspace(0, 1, 1000), []  # for plotting\n    ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))\n    for ci, c in enumerate(unique_classes):\n        i = pred_cls == c\n        n_l = nt[ci]  # number of labels\n        n_p = i.sum()  # number of predictions\n        if n_p == 0 or n_l == 0:\n            continue\n\n        # Accumulate FPs and TPs\n        fpc = (1 - tp[i]).cumsum(0)\n        tpc = tp[i].cumsum(0)\n\n        # Recall\n        recall = tpc / (n_l + eps)  # recall curve\n        r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0)  # negative x, xp because xp decreases\n\n        # Precision\n        precision = tpc / (tpc + fpc)  # precision curve\n        p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1)  # p at pr_score\n\n        # AP from recall-precision curve\n        for j in range(tp.shape[1]):\n            ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])\n            if plot and j == 0:\n                py.append(np.interp(px, mrec, mpre))  # precision at mAP@0.5\n\n    # Compute F1 (harmonic mean of precision and recall)\n    f1 = 2 * p * r / (p + r + eps)\n    names = [v for k, v in names.items() if k in unique_classes]  # list: only classes that have data\n    names = dict(enumerate(names))  # to dict\n    if plot:\n        plot_pr_curve(px, py, ap, save_dir / f'{prefix}PR_curve.png', names, on_plot=on_plot)\n        plot_mc_curve(px, f1, save_dir / f'{prefix}F1_curve.png', names, ylabel='F1', on_plot=on_plot)\n        plot_mc_curve(px, p, save_dir / f'{prefix}P_curve.png', names, ylabel='Precision', on_plot=on_plot)\n        plot_mc_curve(px, r, save_dir / f'{prefix}R_curve.png', names, ylabel='Recall', on_plot=on_plot)\n\n    # i = smooth(f1.mean(0), 0.1).argmax()  # max F1 index\n    i = r.mean(0).argmax()  ###### Jiayuan This is follow the Yolop setting. https://github.com/hustvl/YOLOP/blob/main/lib/core/evaluate.py#L72C5-L72C27\n    p, r, f1 = p[:, i], r[:, i], f1[:, i]\n    tp = (r * nt).round()  # true positives\n    fp = (tp / (p + eps) - tp).round()  # false positives\n    return tp, fp, p, r, f1, ap, unique_classes.astype(int)\n\n###### Jiayuan\nclass SegmentationMetric(object):\n    '''\n    imgLabel [batch_size, height(144), width(256)]\n    confusionMatrix [[0(TN),1(FP)],\n                     [2(FN),3(TP)]]\n    '''\n\n    def __init__(self, numClass):\n        self.numClass = numClass\n        self.confusionMatrix = np.zeros((self.numClass,) * 2)\n\n    def pixelAccuracy(self):\n        # return all class overall pixel accuracy\n        # acc = (TP + TN) / (TP + TN + FP + TN)\n        acc = np.diag(self.confusionMatrix).sum() / self.confusionMatrix.sum()\n        return acc\n\n    # def lineAccuracy(self):\n    #     Acc = np.diag(self.confusionMatrix) / (self.confusionMatrix.sum(axis=1) + 1e-12)\n    #     return Acc[1]\n\n    def _get_values(self):\n        # Extracting values based on the provided structure\n        tn = self.confusionMatrix[0, 0]\n        fp = self.confusionMatrix[0, 1]\n        fn = self.confusionMatrix[1, 0]\n        tp = self.confusionMatrix[1, 1]\n        return tp, fp, fn, tn\n\n    def sensitivity(self):\n        tp, fp, fn, tn = self._get_values()\n        return tp / (tp + fn + 1e-12)\n\n    def specificity(self):\n        tp, fp, fn, tn = self._get_values()\n        return tn / (tn + fp + 1e-12)\n\n    def lineAccuracy(self):\n        test = (self.sensitivity() + self.specificity()) / 2\n        return test\n    def classPixelAccuracy(self):\n        # return each category pixel accuracy(A more accurate way to call it precision)\n        # acc = (TP) / TP + FP\n        classAcc = np.diag(self.confusionMatrix) / (self.confusionMatrix.sum(axis=0) + 1e-12)\n        return classAcc\n\n    def meanPixelAccuracy(self):\n        classAcc = self.classPixelAccuracy()\n        meanAcc = np.nanmean(classAcc)\n        return meanAcc\n\n    def meanIntersectionOverUnion(self):\n        # Intersection = TP Union = TP + FP + FN\n        # IoU = TP / (TP + FP + FN)\n        epsilon = 1e-9\n        intersection = np.diag(self.confusionMatrix)\n        union = np.sum(self.confusionMatrix, axis=1) + np.sum(self.confusionMatrix, axis=0) - np.diag(\n            self.confusionMatrix)\n        IoU = intersection / (union+epsilon)\n        IoU[np.isnan(IoU)] = 0\n        mIoU = np.nanmean(IoU)\n        return mIoU\n\n    def IntersectionOverUnion(self):\n        epsilon = 1e-9\n        intersection = np.diag(self.confusionMatrix)\n        union = np.sum(self.confusionMatrix, axis=1) + np.sum(self.confusionMatrix, axis=0) - np.diag(self.confusionMatrix)\n        IoU = intersection / (union+epsilon)\n        IoU[np.isnan(IoU)] = 0\n        return IoU[1]\n\n    def genConfusionMatrix(self, imgPredict, imgLabel):\n        # remove classes from unlabeled pixels in gt image and predict\n        # print(imgLabel.shape)\n        mask = (imgLabel >= 0) & (imgLabel < self.numClass)\n        label = self.numClass * imgLabel[mask] + imgPredict[mask]\n        count = np.bincount(label, minlength=self.numClass ** 2)\n        confusionMatrix = count.reshape(self.numClass, self.numClass)\n        return confusionMatrix\n\n    def Frequency_Weighted_Intersection_over_Union(self):\n        # FWIOU =     [(TP+FN)/(TP+FP+TN+FN)] *[TP / (TP + FP + FN)]\n        freq = np.sum(self.confusionMatrix, axis=1) / np.sum(self.confusionMatrix)\n        iu = np.diag(self.confusionMatrix) / (\n                np.sum(self.confusionMatrix, axis=1) + np.sum(self.confusionMatrix, axis=0) -\n                np.diag(self.confusionMatrix))\n        FWIoU = (freq[freq > 0] * iu[freq > 0]).sum()\n        return FWIoU\n\n    def addBatch(self, imgPredict, imgLabel):\n        assert imgPredict.shape == imgLabel.shape\n        # import numpy as np\n        #\n        # # Dummy data for demonstration\n        #\n        # # Plotting and saving imgPredict\n        # plt.imshow(imgPredict[0], cmap='gray')\n        # plt.title('imgPredict')\n        # plt.axis('off')\n        # plt.savefig('/home/jiayuan/ultralytics-main/ultralytics/runs/imgPredict.png')\n        #\n        #\n        # # Plotting and saving imgLabel\n        # plt.imshow(imgLabel[0], cmap='gray')\n        # plt.title('imgLabel')\n        # plt.axis('off')\n        # plt.savefig('/home/jiayuan/ultralytics-main/ultralytics/runs/imgLabel.png')\n\n\n\n        self.confusionMatrix += self.genConfusionMatrix(imgPredict, imgLabel)\n\n    def reset(self):\n        self.confusionMatrix = np.zeros((self.numClass, self.numClass))\n\nclass AverageMeter(object):\n    \"\"\"Computes and stores the average and current value\"\"\"\n    def __init__(self):\n        self.reset()\n\n    def reset(self):\n        self.val = 0\n        self.avg = 0\n        self.sum = 0\n        self.count = 0\n\n    def update(self, val, n=1):\n        self.val = val\n        self.sum += val * n\n        self.count += n\n        self.avg = self.sum / self.count if self.count != 0 else 0\n######\nclass Metric(SimpleClass):\n    \"\"\"\n        Class for computing evaluation metrics for YOLOv8 model.\n\n        Attributes:\n            p (list): Precision for each class. Shape: (nc,).\n            r (list): Recall for each class. Shape: (nc,).\n            f1 (list): F1 score for each class. Shape: (nc,).\n            all_ap (list): AP scores for all classes and all IoU thresholds. Shape: (nc, 10).\n            ap_class_index (list): Index of class for each AP score. Shape: (nc,).\n            nc (int): Number of classes.\n\n        Methods:\n            ap50(): AP at IoU threshold of 0.5 for all classes. Returns: List of AP scores. Shape: (nc,) or [].\n            ap(): AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: List of AP scores. Shape: (nc,) or [].\n            mp(): Mean precision of all classes. Returns: Float.\n            mr(): Mean recall of all classes. Returns: Float.\n            map50(): Mean AP at IoU threshold of 0.5 for all classes. Returns: Float.\n            map75(): Mean AP at IoU threshold of 0.75 for all classes. Returns: Float.\n            map(): Mean AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: Float.\n            mean_results(): Mean of results, returns mp, mr, map50, map.\n            class_result(i): Class-aware result, returns p[i], r[i], ap50[i], ap[i].\n            maps(): mAP of each class. Returns: Array of mAP scores, shape: (nc,).\n            fitness(): Model fitness as a weighted combination of metrics. Returns: Float.\n            update(results): Update metric attributes with new evaluation results.\n\n        \"\"\"\n\n    def __init__(self) -> None:\n        self.p = []  # (nc, )\n        self.r = []  # (nc, )\n        self.f1 = []  # (nc, )\n        self.all_ap = []  # (nc, 10)\n        self.ap_class_index = []  # (nc, )\n        self.nc = 0\n\n    @property\n    def ap50(self):\n        \"\"\"\n        Returns the Average Precision (AP) at an IoU threshold of 0.5 for all classes.\n\n        Returns:\n            (np.ndarray, list): Array of shape (nc,) with AP50 values per class, or an empty list if not available.\n        \"\"\"\n        return self.all_ap[:, 0] if len(self.all_ap) else []\n\n    @property\n    def ap(self):\n        \"\"\"\n        Returns the Average Precision (AP) at an IoU threshold of 0.5-0.95 for all classes.\n\n        Returns:\n            (np.ndarray, list): Array of shape (nc,) with AP50-95 values per class, or an empty list if not available.\n        \"\"\"\n        return self.all_ap.mean(1) if len(self.all_ap) else []\n\n    @property\n    def mp(self):\n        \"\"\"\n        Returns the Mean Precision of all classes.\n\n        Returns:\n            (float): The mean precision of all classes.\n        \"\"\"\n        return self.p.mean() if len(self.p) else 0.0\n\n    @property\n    def mr(self):\n        \"\"\"\n        Returns the Mean Recall of all classes.\n\n        Returns:\n            (float): The mean recall of all classes.\n        \"\"\"\n        return self.r.mean() if len(self.r) else 0.0\n\n    @property\n    def map50(self):\n        \"\"\"\n        Returns the mean Average Precision (mAP) at an IoU threshold of 0.5.\n\n        Returns:\n            (float): The mAP50 at an IoU threshold of 0.5.\n        \"\"\"\n        return self.all_ap[:, 0].mean() if len(self.all_ap) else 0.0\n\n    @property\n    def map75(self):\n        \"\"\"\n        Returns the mean Average Precision (mAP) at an IoU threshold of 0.75.\n\n        Returns:\n            (float): The mAP50 at an IoU threshold of 0.75.\n        \"\"\"\n        return self.all_ap[:, 5].mean() if len(self.all_ap) else 0.0\n\n    @property\n    def map(self):\n        \"\"\"\n        Returns the mean Average Precision (mAP) over IoU thresholds of 0.5 - 0.95 in steps of 0.05.\n\n        Returns:\n            (float): The mAP over IoU thresholds of 0.5 - 0.95 in steps of 0.05.\n        \"\"\"\n        return self.all_ap.mean() if len(self.all_ap) else 0.0\n\n    def mean_results(self):\n        \"\"\"Mean of results, return mp, mr, map50, map.\"\"\"\n        return [self.mp, self.mr, self.map50, self.map]\n\n    def class_result(self, i):\n        \"\"\"class-aware result, return p[i], r[i], ap50[i], ap[i].\"\"\"\n        ######Jiayuan\n        try:\n            a = self.p[i]\n        except:\n            a = 0\n        try:\n            b = self.r[i]\n        except:\n            b = 0\n        try:\n            c = self.ap50[i]\n        except:\n            c = 0\n        try:\n            d = self.ap[i]\n        except:\n            d = 0\n        return a, b, c, d\n        ######\n    @property\n    def maps(self):\n        \"\"\"mAP of each class.\"\"\"\n        maps = np.zeros(self.nc) + self.map\n        for i, c in enumerate(self.ap_class_index):\n            maps[c] = self.ap[i]\n        return maps\n\n    def fitness(self):\n        \"\"\"Model fitness as a weighted combination of metrics.\"\"\"\n        w = [0.0, 0.0, 0.1, 0.9]  # weights for [P, R, mAP@0.5, mAP@0.5:0.95]\n        return (np.array(self.mean_results()) * w).sum()\n\n    def update(self, results):\n        \"\"\"\n        Args:\n            results (tuple): A tuple of (p, r, ap, f1, ap_class)\n        \"\"\"\n        self.p, self.r, self.f1, self.all_ap, self.ap_class_index = results\n\n\nclass DetMetrics(SimpleClass):\n    \"\"\"\n    This class is a utility class for computing detection metrics such as precision, recall, and mean average precision\n    (mAP) of an object detection model.\n\n    Args:\n        save_dir (Path): A path to the directory where the output plots will be saved. Defaults to current directory.\n        plot (bool): A flag that indicates whether to plot precision-recall curves for each class. Defaults to False.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.\n        names (tuple of str): A tuple of strings that represents the names of the classes. Defaults to an empty tuple.\n\n    Attributes:\n        save_dir (Path): A path to the directory where the output plots will be saved.\n        plot (bool): A flag that indicates whether to plot the precision-recall curves for each class.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered.\n        names (tuple of str): A tuple of strings that represents the names of the classes.\n        box (Metric): An instance of the Metric class for storing the results of the detection metrics.\n        speed (dict): A dictionary for storing the execution time of different parts of the detection process.\n\n    Methods:\n        process(tp, conf, pred_cls, target_cls): Updates the metric results with the latest batch of predictions.\n        keys: Returns a list of keys for accessing the computed detection metrics.\n        mean_results: Returns a list of mean values for the computed detection metrics.\n        class_result(i): Returns a list of values for the computed detection metrics for a specific class.\n        maps: Returns a dictionary of mean average precision (mAP) values for different IoU thresholds.\n        fitness: Computes the fitness score based on the computed detection metrics.\n        ap_class_index: Returns a list of class indices sorted by their average precision (AP) values.\n        results_dict: Returns a dictionary that maps detection metric keys to their computed values.\n    \"\"\"\n\n    def __init__(self, save_dir=Path('.'), plot=False, on_plot=None, names=()) -> None:\n        self.save_dir = save_dir\n        self.plot = plot\n        self.on_plot = on_plot\n        self.names = names\n        self.box = Metric()\n        self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}\n\n    def process(self, tp, conf, pred_cls, target_cls):\n        \"\"\"Process predicted results for object detection and update metrics.\"\"\"\n        results = ap_per_class(tp, conf, pred_cls, target_cls, plot=self.plot, save_dir=self.save_dir,\n                               names=self.names)[2:]\n        self.box.nc = len(self.names)\n        self.box.update(results)\n\n    @property\n    def keys(self):\n        \"\"\"Returns a list of keys for accessing specific metrics.\"\"\"\n        return ['metrics/precision(B)', 'metrics/recall(B)', 'metrics/mAP50(B)', 'metrics/mAP50-95(B)']\n\n    def mean_results(self):\n        \"\"\"Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.\"\"\"\n        return self.box.mean_results()\n\n    def class_result(self, i):\n        \"\"\"Return the result of evaluating the performance of an object detection model on a specific class.\"\"\"\n        return self.box.class_result(i)\n\n    @property\n    def maps(self):\n        \"\"\"Returns mean Average Precision (mAP) scores per class.\"\"\"\n        return self.box.maps\n\n    @property\n    def fitness(self):\n        \"\"\"Returns the fitness of box object.\"\"\"\n        return self.box.fitness()\n\n    @property\n    def ap_class_index(self):\n        \"\"\"Returns the average precision index per class.\"\"\"\n        return self.box.ap_class_index\n\n    @property\n    def results_dict(self):\n        \"\"\"Returns dictionary of computed performance metrics and statistics.\"\"\"\n        return dict(zip(self.keys + ['fitness'], self.mean_results() + [self.fitness]))\n\n\nclass SegmentMetrics(SimpleClass):\n    \"\"\"\n    Calculates and aggregates detection and segmentation metrics over a given set of classes.\n\n    Args:\n        save_dir (Path): Path to the directory where the output plots should be saved. Default is the current directory.\n        plot (bool): Whether to save the detection and segmentation plots. Default is False.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.\n        names (list): List of class names. Default is an empty list.\n\n    Attributes:\n        save_dir (Path): Path to the directory where the output plots should be saved.\n        plot (bool): Whether to save the detection and segmentation plots.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered.\n        names (list): List of class names.\n        box (Metric): An instance of the Metric class to calculate box detection metrics.\n        seg (Metric): An instance of the Metric class to calculate mask segmentation metrics.\n        speed (dict): Dictionary to store the time taken in different phases of inference.\n\n    Methods:\n        process(tp_m, tp_b, conf, pred_cls, target_cls): Processes metrics over the given set of predictions.\n        mean_results(): Returns the mean of the detection and segmentation metrics over all the classes.\n        class_result(i): Returns the detection and segmentation metrics of class `i`.\n        maps: Returns the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95.\n        fitness: Returns the fitness scores, which are a single weighted combination of metrics.\n        ap_class_index: Returns the list of indices of classes used to compute Average Precision (AP).\n        results_dict: Returns the dictionary containing all the detection and segmentation metrics and fitness score.\n    \"\"\"\n\n    def __init__(self, save_dir=Path('.'), plot=False, on_plot=None, names=()) -> None:\n        self.save_dir = save_dir\n        self.plot = plot\n        self.on_plot = on_plot\n        self.names = names\n        self.box = Metric()\n        self.seg = Metric()\n        self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}\n\n    def process(self, tp_b, tp_m, conf, pred_cls, target_cls):\n        \"\"\"\n        Processes the detection and segmentation metrics over the given set of predictions.\n\n        Args:\n            tp_b (list): List of True Positive boxes.\n            tp_m (list): List of True Positive masks.\n            conf (list): List of confidence scores.\n            pred_cls (list): List of predicted classes.\n            target_cls (list): List of target classes.\n        \"\"\"\n\n        results_mask = ap_per_class(tp_m,\n                                    conf,\n                                    pred_cls,\n                                    target_cls,\n                                    plot=self.plot,\n                                    on_plot=self.on_plot,\n                                    save_dir=self.save_dir,\n                                    names=self.names,\n                                    prefix='Mask')[2:]\n        self.seg.nc = len(self.names)\n        self.seg.update(results_mask)\n        results_box = ap_per_class(tp_b,\n                                   conf,\n                                   pred_cls,\n                                   target_cls,\n                                   plot=self.plot,\n                                   on_plot=self.on_plot,\n                                   save_dir=self.save_dir,\n                                   names=self.names,\n                                   prefix='Box')[2:]\n        self.box.nc = len(self.names)\n        self.box.update(results_box)\n\n    @property\n    def keys(self):\n        \"\"\"Returns a list of keys for accessing metrics.\"\"\"\n        return [\n            'metrics/precision(B)', 'metrics/recall(B)', 'metrics/mAP50(B)', 'metrics/mAP50-95(B)',\n            'metrics/precision(M)', 'metrics/recall(M)', 'metrics/mAP50(M)', 'metrics/mAP50-95(M)']\n\n    def mean_results(self):\n        \"\"\"Return the mean metrics for bounding box and segmentation results.\"\"\"\n        return self.box.mean_results() + self.seg.mean_results()\n\n    def class_result(self, i):\n        \"\"\"Returns classification results for a specified class index.\"\"\"\n        return self.box.class_result(i) + self.seg.class_result(i)\n\n    @property\n    def maps(self):\n        \"\"\"Returns mAP scores for object detection and semantic segmentation models.\"\"\"\n        return self.box.maps + self.seg.maps\n\n    @property\n    def fitness(self):\n        \"\"\"Get the fitness score for both segmentation and bounding box models.\"\"\"\n        return self.seg.fitness() + self.box.fitness()\n\n    @property\n    def ap_class_index(self):\n        \"\"\"Boxes and masks have the same ap_class_index.\"\"\"\n        return self.box.ap_class_index\n\n    @property\n    def results_dict(self):\n        \"\"\"Returns results of object detection model for evaluation.\"\"\"\n        return dict(zip(self.keys + ['fitness'], self.mean_results() + [self.fitness]))\n\n\nclass PoseMetrics(SegmentMetrics):\n    \"\"\"\n    Calculates and aggregates detection and pose metrics over a given set of classes.\n\n    Args:\n        save_dir (Path): Path to the directory where the output plots should be saved. Default is the current directory.\n        plot (bool): Whether to save the detection and segmentation plots. Default is False.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.\n        names (list): List of class names. Default is an empty list.\n\n    Attributes:\n        save_dir (Path): Path to the directory where the output plots should be saved.\n        plot (bool): Whether to save the detection and segmentation plots.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered.\n        names (list): List of class names.\n        box (Metric): An instance of the Metric class to calculate box detection metrics.\n        pose (Metric): An instance of the Metric class to calculate mask segmentation metrics.\n        speed (dict): Dictionary to store the time taken in different phases of inference.\n\n    Methods:\n        process(tp_m, tp_b, conf, pred_cls, target_cls): Processes metrics over the given set of predictions.\n        mean_results(): Returns the mean of the detection and segmentation metrics over all the classes.\n        class_result(i): Returns the detection and segmentation metrics of class `i`.\n        maps: Returns the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95.\n        fitness: Returns the fitness scores, which are a single weighted combination of metrics.\n        ap_class_index: Returns the list of indices of classes used to compute Average Precision (AP).\n        results_dict: Returns the dictionary containing all the detection and segmentation metrics and fitness score.\n    \"\"\"\n\n    def __init__(self, save_dir=Path('.'), plot=False, on_plot=None, names=()) -> None:\n        super().__init__(save_dir, plot, names)\n        self.save_dir = save_dir\n        self.plot = plot\n        self.on_plot = on_plot\n        self.names = names\n        self.box = Metric()\n        self.pose = Metric()\n        self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}\n\n    def __getattr__(self, attr):\n        \"\"\"Raises an AttributeError if an invalid attribute is accessed.\"\"\"\n        name = self.__class__.__name__\n        raise AttributeError(f\"'{name}' object has no attribute '{attr}'. See valid attributes below.\\n{self.__doc__}\")\n\n    def process(self, tp_b, tp_p, conf, pred_cls, target_cls):\n        \"\"\"\n        Processes the detection and pose metrics over the given set of predictions.\n\n        Args:\n            tp_b (list): List of True Positive boxes.\n            tp_p (list): List of True Positive keypoints.\n            conf (list): List of confidence scores.\n            pred_cls (list): List of predicted classes.\n            target_cls (list): List of target classes.\n        \"\"\"\n\n        results_pose = ap_per_class(tp_p,\n                                    conf,\n                                    pred_cls,\n                                    target_cls,\n                                    plot=self.plot,\n                                    on_plot=self.on_plot,\n                                    save_dir=self.save_dir,\n                                    names=self.names,\n                                    prefix='Pose')[2:]\n        self.pose.nc = len(self.names)\n        self.pose.update(results_pose)\n        results_box = ap_per_class(tp_b,\n                                   conf,\n                                   pred_cls,\n                                   target_cls,\n                                   plot=self.plot,\n                                   on_plot=self.on_plot,\n                                   save_dir=self.save_dir,\n                                   names=self.names,\n                                   prefix='Box')[2:]\n        self.box.nc = len(self.names)\n        self.box.update(results_box)\n\n    @property\n    def keys(self):\n        \"\"\"Returns list of evaluation metric keys.\"\"\"\n        return [\n            'metrics/precision(B)', 'metrics/recall(B)', 'metrics/mAP50(B)', 'metrics/mAP50-95(B)',\n            'metrics/precision(P)', 'metrics/recall(P)', 'metrics/mAP50(P)', 'metrics/mAP50-95(P)']\n\n    def mean_results(self):\n        \"\"\"Return the mean results of box and pose.\"\"\"\n        return self.box.mean_results() + self.pose.mean_results()\n\n    def class_result(self, i):\n        \"\"\"Return the class-wise detection results for a specific class i.\"\"\"\n        return self.box.class_result(i) + self.pose.class_result(i)\n\n    @property\n    def maps(self):\n        \"\"\"Returns the mean average precision (mAP) per class for both box and pose detections.\"\"\"\n        return self.box.maps + self.pose.maps\n\n    @property\n    def fitness(self):\n        \"\"\"Computes classification metrics and speed using the `targets` and `pred` inputs.\"\"\"\n        return self.pose.fitness() + self.box.fitness()\n\n\nclass ClassifyMetrics(SimpleClass):\n    \"\"\"\n    Class for computing classification metrics including top-1 and top-5 accuracy.\n\n    Attributes:\n        top1 (float): The top-1 accuracy.\n        top5 (float): The top-5 accuracy.\n        speed (Dict[str, float]): A dictionary containing the time taken for each step in the pipeline.\n\n    Properties:\n        fitness (float): The fitness of the model, which is equal to top-5 accuracy.\n        results_dict (Dict[str, Union[float, str]]): A dictionary containing the classification metrics and fitness.\n        keys (List[str]): A list of keys for the results_dict.\n\n    Methods:\n        process(targets, pred): Processes the targets and predictions to compute classification metrics.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.top1 = 0\n        self.top5 = 0\n        self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}\n\n    def process(self, targets, pred):\n        \"\"\"Target classes and predicted classes.\"\"\"\n        pred, targets = torch.cat(pred), torch.cat(targets)\n        correct = (targets[:, None] == pred).float()\n        acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1)  # (top1, top5) accuracy\n        self.top1, self.top5 = acc.mean(0).tolist()\n\n    @property\n    def fitness(self):\n        \"\"\"Returns top-5 accuracy as fitness score.\"\"\"\n        return self.top5\n\n    @property\n    def results_dict(self):\n        \"\"\"Returns a dictionary with model's performance metrics and fitness score.\"\"\"\n        return dict(zip(self.keys + ['fitness'], [self.top1, self.top5, self.fitness]))\n\n    @property\n    def keys(self):\n        \"\"\"Returns a list of keys for the results_dict property.\"\"\"\n        return ['metrics/accuracy_top1', 'metrics/accuracy_top5']\n"
  },
  {
    "path": "ultralytics/yolo/utils/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nimport inspect\nimport logging.config\nimport os\nimport platform\nimport re\nimport subprocess\nimport sys\nimport threading\nimport urllib\nimport uuid\nfrom pathlib import Path\nfrom types import SimpleNamespace\nfrom typing import Union\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport yaml\n\nfrom ultralytics import __version__\n\n# PyTorch Multi-GPU DDP Constants\nRANK = int(os.getenv('RANK', -1))\nLOCAL_RANK = int(os.getenv('LOCAL_RANK', -1))  # https://pytorch.org/docs/stable/elastic/run.html\nWORLD_SIZE = int(os.getenv('WORLD_SIZE', 1))\n\n# Other Constants\nFILE = Path(__file__).resolve()\nROOT = FILE.parents[2]  # YOLO\nDEFAULT_CFG_PATH = ROOT / 'yolo/cfg/default.yaml'\nNUM_THREADS = min(8, max(1, os.cpu_count() - 1))  # number of YOLOv5 multiprocessing threads\nAUTOINSTALL = str(os.getenv('YOLO_AUTOINSTALL', True)).lower() == 'true'  # global auto-install mode\nVERBOSE = str(os.getenv('YOLO_VERBOSE', True)).lower() == 'true'  # global verbose mode\nTQDM_BAR_FORMAT = '{l_bar}{bar:10}{r_bar}'  # tqdm bar format\nLOGGING_NAME = 'ultralytics'\nMACOS, LINUX, WINDOWS = (platform.system() == x for x in ['Darwin', 'Linux', 'Windows'])  # environment booleans\nHELP_MSG = \\\n    \"\"\"\n    Usage examples for running YOLOv8:\n\n    1. Install the ultralytics package:\n\n        pip install ultralytics\n\n    2. Use the Python SDK:\n\n        from ultralytics import YOLO\n\n        # Load a model\n        model = YOLO('yolov8n.yaml')  # build a new model from scratch\n        model = YOLO(\"yolov8n.pt\")  # load a pretrained model (recommended for training)\n\n        # Use the model\n        results = model.train(data=\"coco128.yaml\", epochs=3)  # train the model\n        results = model.val()  # evaluate model performance on the validation set\n        results = model('https://ultralytics.com/images/bus.jpg')  # predict on an image\n        success = model.export(format='onnx')  # export the model to ONNX format\n\n    3. Use the command line interface (CLI):\n\n        YOLOv8 'yolo' CLI commands use the following syntax:\n\n            yolo TASK MODE ARGS\n\n            Where   TASK (optional) is one of [detect, segment, classify]\n                    MODE (required) is one of [train, val, predict, export]\n                    ARGS (optional) are any number of custom 'arg=value' pairs like 'imgsz=320' that override defaults.\n                        See all ARGS at https://docs.ultralytics.com/usage/cfg or with 'yolo cfg'\n\n        - Train a detection model for 10 epochs with an initial learning_rate of 0.01\n            yolo detect train data=coco128.yaml model=yolov8n.pt epochs=10 lr0=0.01\n\n        - Predict a YouTube video using a pretrained segmentation model at image size 320:\n            yolo segment predict model=yolov8n-seg.pt source='https://youtu.be/Zgi9g1ksQHc' imgsz=320\n\n        - Val a pretrained detection model at batch-size 1 and image size 640:\n            yolo detect val model=yolov8n.pt data=coco128.yaml batch=1 imgsz=640\n\n        - Export a YOLOv8n classification model to ONNX format at image size 224 by 128 (no TASK required)\n            yolo export model=yolov8n-cls.pt format=onnx imgsz=224,128\n\n        - Run special commands:\n            yolo help\n            yolo checks\n            yolo version\n            yolo settings\n            yolo copy-cfg\n            yolo cfg\n\n    Docs: https://docs.ultralytics.com\n    Community: https://community.ultralytics.com\n    GitHub: https://github.com/ultralytics/ultralytics\n    \"\"\"\n\n# Settings\ntorch.set_printoptions(linewidth=320, precision=4, profile='default')\nnp.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format})  # format short g, %precision=5\ncv2.setNumThreads(0)  # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)\nos.environ['NUMEXPR_MAX_THREADS'] = str(NUM_THREADS)  # NumExpr max threads\nos.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'  # for deterministic training\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # suppress verbose TF compiler warnings in Colab\n\n\nclass SimpleClass:\n    \"\"\"\n    Ultralytics SimpleClass is a base class providing helpful string representation, error reporting, and attribute\n    access methods for easier debugging and usage.\n    \"\"\"\n\n    def __str__(self):\n        \"\"\"Return a human-readable string representation of the object.\"\"\"\n        attr = []\n        for a in dir(self):\n            v = getattr(self, a)\n            if not callable(v) and not a.startswith('_'):\n                if isinstance(v, SimpleClass):\n                    # Display only the module and class name for subclasses\n                    s = f'{a}: {v.__module__}.{v.__class__.__name__} object'\n                else:\n                    s = f'{a}: {repr(v)}'\n                attr.append(s)\n        return f'{self.__module__}.{self.__class__.__name__} object with attributes:\\n\\n' + '\\n'.join(attr)\n\n    def __repr__(self):\n        \"\"\"Return a machine-readable string representation of the object.\"\"\"\n        return self.__str__()\n\n    def __getattr__(self, attr):\n        \"\"\"Custom attribute access error message with helpful information.\"\"\"\n        name = self.__class__.__name__\n        raise AttributeError(f\"'{name}' object has no attribute '{attr}'. See valid attributes below.\\n{self.__doc__}\")\n\n\nclass IterableSimpleNamespace(SimpleNamespace):\n    \"\"\"\n    Ultralytics IterableSimpleNamespace is an extension class of SimpleNamespace that adds iterable functionality and\n    enables usage with dict() and for loops.\n    \"\"\"\n\n    def __iter__(self):\n        \"\"\"Return an iterator of key-value pairs from the namespace's attributes.\"\"\"\n        return iter(vars(self).items())\n\n    def __str__(self):\n        \"\"\"Return a human-readable string representation of the object.\"\"\"\n        return '\\n'.join(f'{k}={v}' for k, v in vars(self).items())\n\n    def __getattr__(self, attr):\n        \"\"\"Custom attribute access error message with helpful information.\"\"\"\n        name = self.__class__.__name__\n        raise AttributeError(f\"\"\"\n            '{name}' object has no attribute '{attr}'. This may be caused by a modified or out of date ultralytics\n            'default.yaml' file.\\nPlease update your code with 'pip install -U ultralytics' and if necessary replace\n            {DEFAULT_CFG_PATH} with the latest version from\n            https://github.com/ultralytics/ultralytics/blob/main/ultralytics/yolo/cfg/default.yaml\n            \"\"\")\n\n    def get(self, key, default=None):\n        \"\"\"Return the value of the specified key if it exists; otherwise, return the default value.\"\"\"\n        return getattr(self, key, default)\n\n\ndef plt_settings(rcparams={'font.size': 11}, backend='Agg'):\n    \"\"\"\n    Decorator to temporarily set rc parameters and the backend for a plotting function.\n\n    Usage:\n        decorator: @plt_settings({\"font.size\": 12})\n        context manager: with plt_settings({\"font.size\": 12}):\n\n    Args:\n        rcparams (dict): Dictionary of rc parameters to set.\n        backend (str, optional): Name of the backend to use. Defaults to 'Agg'.\n\n    Returns:\n        callable: Decorated function with temporarily set rc parameters and backend.\n    \"\"\"\n\n    def decorator(func):\n        \"\"\"Decorator to apply temporary rc parameters and backend to a function.\"\"\"\n\n        def wrapper(*args, **kwargs):\n            \"\"\"Sets rc parameters and backend, calls the original function, and restores the settings.\"\"\"\n            original_backend = plt.get_backend()\n            plt.switch_backend(backend)\n\n            with plt.rc_context(rcparams):\n                result = func(*args, **kwargs)\n\n            plt.switch_backend(original_backend)\n            return result\n\n        return wrapper\n\n    return decorator\n\n\ndef set_logging(name=LOGGING_NAME, verbose=True):\n    \"\"\"Sets up logging for the given name.\"\"\"\n    rank = int(os.getenv('RANK', -1))  # rank in world for Multi-GPU trainings\n    level = logging.INFO if verbose and rank in {-1, 0} else logging.ERROR\n    logging.config.dictConfig({\n        'version': 1,\n        'disable_existing_loggers': False,\n        'formatters': {\n            name: {\n                'format': '%(message)s'}},\n        'handlers': {\n            name: {\n                'class': 'logging.StreamHandler',\n                'formatter': name,\n                'level': level}},\n        'loggers': {\n            name: {\n                'level': level,\n                'handlers': [name],\n                'propagate': False}}})\n\n\nclass EmojiFilter(logging.Filter):\n    \"\"\"\n    A custom logging filter class for removing emojis in log messages.\n\n    This filter is particularly useful for ensuring compatibility with Windows terminals\n    that may not support the display of emojis in log messages.\n    \"\"\"\n\n    def filter(self, record):\n        \"\"\"Filter logs by emoji unicode characters on windows.\"\"\"\n        record.msg = emojis(record.msg)\n        return super().filter(record)\n\n\n# Set logger\nset_logging(LOGGING_NAME, verbose=VERBOSE)  # run before defining LOGGER\nLOGGER = logging.getLogger(LOGGING_NAME)  # define globally (used in train.py, val.py, detect.py, etc.)\nif WINDOWS:  # emoji-safe logging\n    LOGGER.addFilter(EmojiFilter())\n\n\ndef yaml_save(file='data.yaml', data={}):\n    \"\"\"\n    Save YAML data to a file.\n\n    Args:\n        file (str, optional): File name. Default is 'data.yaml'.\n        data (dict): Data to save in YAML format.\n\n    Returns:\n        None: Data is saved to the specified file.\n    \"\"\"\n    file = Path(file)\n    if not file.parent.exists():\n        # Create parent directories if they don't exist\n        file.parent.mkdir(parents=True, exist_ok=True)\n\n    # Convert Path objects to strings\n    for k, v in data.items():\n        if isinstance(v, Path):\n            data[k] = str(v)\n\n    # Dump data to file in YAML format\n    with open(file, 'w') as f:\n        yaml.safe_dump(data, f, sort_keys=False, allow_unicode=True)\n\n\ndef yaml_load(file='data.yaml', append_filename=False):\n    \"\"\"\n    Load YAML data from a file.\n\n    Args:\n        file (str, optional): File name. Default is 'data.yaml'.\n        append_filename (bool): Add the YAML filename to the YAML dictionary. Default is False.\n\n    Returns:\n        dict: YAML data and file name.\n    \"\"\"\n    with open(file, errors='ignore', encoding='utf-8') as f:\n        s = f.read()  # string\n\n        # Remove special characters\n        if not s.isprintable():\n            s = re.sub(r'[^\\x09\\x0A\\x0D\\x20-\\x7E\\x85\\xA0-\\uD7FF\\uE000-\\uFFFD\\U00010000-\\U0010ffff]+', '', s)\n\n        # Add YAML filename to dict and return\n        return {**yaml.safe_load(s), 'yaml_file': str(file)} if append_filename else yaml.safe_load(s)\n\n\ndef yaml_print(yaml_file: Union[str, Path, dict]) -> None:\n    \"\"\"\n    Pretty prints a yaml file or a yaml-formatted dictionary.\n\n    Args:\n        yaml_file: The file path of the yaml file or a yaml-formatted dictionary.\n\n    Returns:\n        None\n    \"\"\"\n    yaml_dict = yaml_load(yaml_file) if isinstance(yaml_file, (str, Path)) else yaml_file\n    dump = yaml.dump(yaml_dict, sort_keys=False, allow_unicode=True)\n    LOGGER.info(f\"Printing '{colorstr('bold', 'black', yaml_file)}'\\n\\n{dump}\")\n\n\n# Default configuration\nDEFAULT_CFG_DICT = yaml_load(DEFAULT_CFG_PATH)\nfor k, v in DEFAULT_CFG_DICT.items():\n    if isinstance(v, str) and v.lower() == 'none':\n        DEFAULT_CFG_DICT[k] = None\nDEFAULT_CFG_KEYS = DEFAULT_CFG_DICT.keys()\nDEFAULT_CFG = IterableSimpleNamespace(**DEFAULT_CFG_DICT)\n\n\ndef is_colab():\n    \"\"\"\n    Check if the current script is running inside a Google Colab notebook.\n\n    Returns:\n        bool: True if running inside a Colab notebook, False otherwise.\n    \"\"\"\n    return 'COLAB_RELEASE_TAG' in os.environ or 'COLAB_BACKEND_VERSION' in os.environ\n\n\ndef is_kaggle():\n    \"\"\"\n    Check if the current script is running inside a Kaggle kernel.\n\n    Returns:\n        bool: True if running inside a Kaggle kernel, False otherwise.\n    \"\"\"\n    return os.environ.get('PWD') == '/kaggle/working' and os.environ.get('KAGGLE_URL_BASE') == 'https://www.kaggle.com'\n\n\ndef is_jupyter():\n    \"\"\"\n    Check if the current script is running inside a Jupyter Notebook.\n    Verified on Colab, Jupyterlab, Kaggle, Paperspace.\n\n    Returns:\n        bool: True if running inside a Jupyter Notebook, False otherwise.\n    \"\"\"\n    with contextlib.suppress(Exception):\n        from IPython import get_ipython\n        return get_ipython() is not None\n    return False\n\n\ndef is_docker() -> bool:\n    \"\"\"\n    Determine if the script is running inside a Docker container.\n\n    Returns:\n        bool: True if the script is running inside a Docker container, False otherwise.\n    \"\"\"\n    file = Path('/proc/self/cgroup')\n    if file.exists():\n        with open(file) as f:\n            return 'docker' in f.read()\n    else:\n        return False\n\n\ndef is_online() -> bool:\n    \"\"\"\n    Check internet connectivity by attempting to connect to a known online host.\n\n    Returns:\n        bool: True if connection is successful, False otherwise.\n    \"\"\"\n    import socket\n\n    for server in '1.1.1.1', '8.8.8.8', '223.5.5.5':  # Cloudflare, Google, AliDNS:\n        try:\n            socket.create_connection((server, 53), timeout=2)  # connect to (server, port=53)\n            return True\n        except (socket.timeout, socket.gaierror, OSError):\n            continue\n    return False\n\n\nONLINE = is_online()\n\n\ndef is_pip_package(filepath: str = __name__) -> bool:\n    \"\"\"\n    Determines if the file at the given filepath is part of a pip package.\n\n    Args:\n        filepath (str): The filepath to check.\n\n    Returns:\n        bool: True if the file is part of a pip package, False otherwise.\n    \"\"\"\n    import importlib.util\n\n    # Get the spec for the module\n    spec = importlib.util.find_spec(filepath)\n\n    # Return whether the spec is not None and the origin is not None (indicating it is a package)\n    return spec is not None and spec.origin is not None\n\n\ndef is_dir_writeable(dir_path: Union[str, Path]) -> bool:\n    \"\"\"\n    Check if a directory is writeable.\n\n    Args:\n        dir_path (str) or (Path): The path to the directory.\n\n    Returns:\n        bool: True if the directory is writeable, False otherwise.\n    \"\"\"\n    return os.access(str(dir_path), os.W_OK)\n\n\ndef is_pytest_running():\n    \"\"\"\n    Determines whether pytest is currently running or not.\n\n    Returns:\n        (bool): True if pytest is running, False otherwise.\n    \"\"\"\n    return ('PYTEST_CURRENT_TEST' in os.environ) or ('pytest' in sys.modules) or ('pytest' in Path(sys.argv[0]).stem)\n\n\ndef is_github_actions_ci() -> bool:\n    \"\"\"\n    Determine if the current environment is a GitHub Actions CI Python runner.\n\n    Returns:\n        (bool): True if the current environment is a GitHub Actions CI Python runner, False otherwise.\n    \"\"\"\n    return 'GITHUB_ACTIONS' in os.environ and 'RUNNER_OS' in os.environ and 'RUNNER_TOOL_CACHE' in os.environ\n\n\ndef is_git_dir():\n    \"\"\"\n    Determines whether the current file is part of a git repository.\n    If the current file is not part of a git repository, returns None.\n\n    Returns:\n        (bool): True if current file is part of a git repository.\n    \"\"\"\n    return get_git_dir() is not None\n\n\ndef get_git_dir():\n    \"\"\"\n    Determines whether the current file is part of a git repository and if so, returns the repository root directory.\n    If the current file is not part of a git repository, returns None.\n\n    Returns:\n        (Path) or (None): Git root directory if found or None if not found.\n    \"\"\"\n    for d in Path(__file__).parents:\n        if (d / '.git').is_dir():\n            return d\n    return None  # no .git dir found\n\n\ndef get_git_origin_url():\n    \"\"\"\n    Retrieves the origin URL of a git repository.\n\n    Returns:\n        (str) or (None): The origin URL of the git repository.\n    \"\"\"\n    if is_git_dir():\n        with contextlib.suppress(subprocess.CalledProcessError):\n            origin = subprocess.check_output(['git', 'config', '--get', 'remote.origin.url'])\n            return origin.decode().strip()\n    return None  # if not git dir or on error\n\n\ndef get_git_branch():\n    \"\"\"\n    Returns the current git branch name. If not in a git repository, returns None.\n\n    Returns:\n        (str) or (None): The current git branch name.\n    \"\"\"\n    if is_git_dir():\n        with contextlib.suppress(subprocess.CalledProcessError):\n            origin = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])\n            return origin.decode().strip()\n    return None  # if not git dir or on error\n\n\ndef get_default_args(func):\n    \"\"\"Returns a dictionary of default arguments for a function.\n\n    Args:\n        func (callable): The function to inspect.\n\n    Returns:\n        dict: A dictionary where each key is a parameter name, and each value is the default value of that parameter.\n    \"\"\"\n    signature = inspect.signature(func)\n    return {k: v.default for k, v in signature.parameters.items() if v.default is not inspect.Parameter.empty}\n\n\ndef get_user_config_dir(sub_dir='Ultralytics'):\n    \"\"\"\n    Get the user config directory.\n\n    Args:\n        sub_dir (str): The name of the subdirectory to create.\n\n    Returns:\n        Path: The path to the user config directory.\n    \"\"\"\n    # Return the appropriate config directory for each operating system\n    if WINDOWS:\n        path = Path.home() / 'AppData' / 'Roaming' / sub_dir\n    elif MACOS:  # macOS\n        path = Path.home() / 'Library' / 'Application Support' / sub_dir\n    elif LINUX:\n        path = Path.home() / '.config' / sub_dir\n    else:\n        raise ValueError(f'Unsupported operating system: {platform.system()}')\n\n    # GCP and AWS lambda fix, only /tmp is writeable\n    if not is_dir_writeable(str(path.parent)):\n        path = Path('/tmp') / sub_dir\n\n    # Create the subdirectory if it does not exist\n    path.mkdir(parents=True, exist_ok=True)\n\n    return path\n\n\nUSER_CONFIG_DIR = Path(os.getenv('YOLO_CONFIG_DIR', get_user_config_dir()))  # Ultralytics settings dir\nSETTINGS_YAML = USER_CONFIG_DIR / 'settings.yaml'\n\n\ndef emojis(string=''):\n    \"\"\"Return platform-dependent emoji-safe version of string.\"\"\"\n    return string.encode().decode('ascii', 'ignore') if WINDOWS else string\n\n\ndef colorstr(*input):\n    \"\"\"Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e.  colorstr('blue', 'hello world').\"\"\"\n    *args, string = input if len(input) > 1 else ('blue', 'bold', input[0])  # color arguments, string\n    colors = {\n        'black': '\\033[30m',  # basic colors\n        'red': '\\033[31m',\n        'green': '\\033[32m',\n        'yellow': '\\033[33m',\n        'blue': '\\033[34m',\n        'magenta': '\\033[35m',\n        'cyan': '\\033[36m',\n        'white': '\\033[37m',\n        'bright_black': '\\033[90m',  # bright colors\n        'bright_red': '\\033[91m',\n        'bright_green': '\\033[92m',\n        'bright_yellow': '\\033[93m',\n        'bright_blue': '\\033[94m',\n        'bright_magenta': '\\033[95m',\n        'bright_cyan': '\\033[96m',\n        'bright_white': '\\033[97m',\n        'end': '\\033[0m',  # misc\n        'bold': '\\033[1m',\n        'underline': '\\033[4m'}\n    return ''.join(colors[x] for x in args) + f'{string}' + colors['end']\n\n\nclass TryExcept(contextlib.ContextDecorator):\n    \"\"\"YOLOv8 TryExcept class. Usage: @TryExcept() decorator or 'with TryExcept():' context manager.\"\"\"\n\n    def __init__(self, msg='', verbose=True):\n        \"\"\"Initialize TryExcept class with optional message and verbosity settings.\"\"\"\n        self.msg = msg\n        self.verbose = verbose\n\n    def __enter__(self):\n        \"\"\"Executes when entering TryExcept context, initializes instance.\"\"\"\n        pass\n\n    def __exit__(self, exc_type, value, traceback):\n        \"\"\"Defines behavior when exiting a 'with' block, prints error message if necessary.\"\"\"\n        if self.verbose and value:\n            print(emojis(f\"{self.msg}{': ' if self.msg else ''}{value}\"))\n        return True\n\n\ndef threaded(func):\n    \"\"\"Multi-threads a target function and returns thread. Usage: @threaded decorator.\"\"\"\n\n    def wrapper(*args, **kwargs):\n        \"\"\"Multi-threads a given function and returns the thread.\"\"\"\n        thread = threading.Thread(target=func, args=args, kwargs=kwargs, daemon=True)\n        thread.start()\n        return thread\n\n    return wrapper\n\n\ndef set_sentry():\n    \"\"\"\n    Initialize the Sentry SDK for error tracking and reporting. Enabled when sync=True in settings and\n    disabled when sync=False. Run 'yolo settings' to see and update settings YAML file.\n\n    Conditions required to send errors:\n        - sync=True in YOLO settings\n        - pytest is not running\n        - running in a pip package installation\n        - running in a non-git directory\n        - running with rank -1 or 0\n        - online environment\n        - CLI used to run package (checked with 'yolo' as the name of the main CLI command)\n\n    The function also configures Sentry SDK to ignore KeyboardInterrupt and FileNotFoundError\n    exceptions and to exclude events with 'out of memory' in their exception message.\n\n    Additionally, the function sets custom tags and user information for Sentry events.\n    \"\"\"\n\n    def before_send(event, hint):\n        \"\"\"\n        Modify the event before sending it to Sentry based on specific exception types and messages.\n\n        Args:\n            event (dict): The event dictionary containing information about the error.\n            hint (dict): A dictionary containing additional information about the error.\n\n        Returns:\n            dict: The modified event or None if the event should not be sent to Sentry.\n        \"\"\"\n        if 'exc_info' in hint:\n            exc_type, exc_value, tb = hint['exc_info']\n            if exc_type in (KeyboardInterrupt, FileNotFoundError) \\\n                    or 'out of memory' in str(exc_value):\n                return None  # do not send event\n\n        event['tags'] = {\n            'sys_argv': sys.argv[0],\n            'sys_argv_name': Path(sys.argv[0]).name,\n            'install': 'git' if is_git_dir() else 'pip' if is_pip_package() else 'other',\n            'os': ENVIRONMENT}\n        return event\n\n    if SETTINGS['sync'] and \\\n            RANK in (-1, 0) and \\\n            Path(sys.argv[0]).name == 'yolo' and \\\n            not TESTS_RUNNING and \\\n            ONLINE and \\\n            is_pip_package() and \\\n            not is_git_dir():\n\n        import sentry_sdk  # noqa\n        sentry_sdk.init(\n            dsn='https://5ff1556b71594bfea135ff0203a0d290@o4504521589325824.ingest.sentry.io/4504521592406016',\n            debug=False,\n            traces_sample_rate=1.0,\n            release=__version__,\n            environment='production',  # 'dev' or 'production'\n            before_send=before_send,\n            ignore_errors=[KeyboardInterrupt, FileNotFoundError])\n        sentry_sdk.set_user({'id': SETTINGS['uuid']})  # SHA-256 anonymized UUID hash\n\n        # Disable all sentry logging\n        for logger in 'sentry_sdk', 'sentry_sdk.errors':\n            logging.getLogger(logger).setLevel(logging.CRITICAL)\n\n\ndef get_settings(file=SETTINGS_YAML, version='0.0.3'):\n    \"\"\"\n    Loads a global Ultralytics settings YAML file or creates one with default values if it does not exist.\n\n    Args:\n        file (Path): Path to the Ultralytics settings YAML file. Defaults to 'settings.yaml' in the USER_CONFIG_DIR.\n        version (str): Settings version. If min settings version not met, new default settings will be saved.\n\n    Returns:\n        dict: Dictionary of settings key-value pairs.\n    \"\"\"\n    import hashlib\n\n    from ultralytics.yolo.utils.checks import check_version\n    from ultralytics.yolo.utils.torch_utils import torch_distributed_zero_first\n\n    git_dir = get_git_dir()\n    root = git_dir or Path()\n    datasets_root = (root.parent if git_dir and is_dir_writeable(root.parent) else root).resolve()\n    defaults = {\n        'datasets_dir': str(datasets_root / 'datasets'),  # default datasets directory.\n        'weights_dir': str(root / 'weights'),  # default weights directory.\n        'runs_dir': str(root / 'runs'),  # default runs directory.\n        'uuid': hashlib.sha256(str(uuid.getnode()).encode()).hexdigest(),  # SHA-256 anonymized UUID hash\n        'sync': True,  # sync analytics to help with YOLO development\n        'api_key': '',  # Ultralytics HUB API key (https://hub.ultralytics.com/)\n        'settings_version': version}  # Ultralytics settings version\n\n    with torch_distributed_zero_first(RANK):\n        if not file.exists():\n            yaml_save(file, defaults)\n        settings = yaml_load(file)\n\n        # Check that settings keys and types match defaults\n        correct = \\\n            settings \\\n            and settings.keys() == defaults.keys() \\\n            and all(type(a) == type(b) for a, b in zip(settings.values(), defaults.values())) \\\n            and check_version(settings['settings_version'], version)\n        if not correct:\n            LOGGER.warning('WARNING ⚠️ Ultralytics settings reset to defaults. This is normal and may be due to a '\n                           'recent ultralytics package update, but may have overwritten previous settings. '\n                           f\"\\nView and update settings with 'yolo settings' or at '{file}'\")\n            settings = defaults  # merge **defaults with **settings (prefer **settings)\n            yaml_save(file, settings)  # save updated defaults\n\n        return settings\n\n\ndef set_settings(kwargs, file=SETTINGS_YAML):\n    \"\"\"\n    Function that runs on a first-time ultralytics package installation to set up global settings and create necessary\n    directories.\n    \"\"\"\n    SETTINGS.update(kwargs)\n    yaml_save(file, SETTINGS)\n\n\ndef deprecation_warn(arg, new_arg, version=None):\n    \"\"\"Issue a deprecation warning when a deprecated argument is used, suggesting an updated argument.\"\"\"\n    if not version:\n        version = float(__version__[:3]) + 0.2  # deprecate after 2nd major release\n    LOGGER.warning(f\"WARNING ⚠️ '{arg}' is deprecated and will be removed in 'ultralytics {version}' in the future. \"\n                   f\"Please use '{new_arg}' instead.\")\n\n\ndef clean_url(url):\n    \"\"\"Strip auth from URL, i.e. https://url.com/file.txt?auth -> https://url.com/file.txt.\"\"\"\n    url = str(Path(url)).replace(':/', '://')  # Pathlib turns :// -> :/\n    return urllib.parse.unquote(url).split('?')[0]  # '%2F' to '/', split https://url.com/file.txt?auth\n\n\ndef url2file(url):\n    \"\"\"Convert URL to filename, i.e. https://url.com/file.txt?auth -> file.txt.\"\"\"\n    return Path(clean_url(url)).name\n\n\n# Run below code on yolo/utils init ------------------------------------------------------------------------------------\n\n# Check first-install steps\nPREFIX = colorstr('Ultralytics: ')\nSETTINGS = get_settings()\nDATASETS_DIR = Path(SETTINGS['datasets_dir'])  # global datasets directory\nENVIRONMENT = 'Colab' if is_colab() else 'Kaggle' if is_kaggle() else 'Jupyter' if is_jupyter() else \\\n    'Docker' if is_docker() else platform.system()\nTESTS_RUNNING = is_pytest_running() or is_github_actions_ci()\nset_sentry()\n\n# OpenCV Multilanguage-friendly functions ------------------------------------------------------------------------------\nimshow_ = cv2.imshow  # copy to avoid recursion errors\n\n\ndef imread(filename, flags=cv2.IMREAD_COLOR):\n    return cv2.imdecode(np.fromfile(filename, np.uint8), flags)\n\n\ndef imwrite(filename, img):\n    try:\n        cv2.imencode(Path(filename).suffix, img)[1].tofile(filename)\n        return True\n    except Exception:\n        return False\n\n\ndef imshow(path, im):\n    imshow_(path.encode('unicode_escape').decode(), im)\n\n\nif Path(inspect.stack()[0].filename).parent.parent.as_posix() in inspect.stack()[-1].filename:\n    cv2.imread, cv2.imwrite, cv2.imshow = imread, imwrite, imshow  # redefine\n"
  },
  {
    "path": "ultralytics/yolo/utils/autobatch.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nFunctions for estimating the best YOLO batch size to use a fraction of the available CUDA memory in PyTorch.\n\"\"\"\n\nfrom copy import deepcopy\n\nimport numpy as np\nimport torch\n\nfrom ultralytics.yolo.utils import LOGGER, colorstr\nfrom ultralytics.yolo.utils.torch_utils import profile\n\n\ndef check_train_batch_size(model, imgsz=640, amp=True):\n    \"\"\"\n    Check YOLO training batch size using the autobatch() function.\n\n    Args:\n        model (torch.nn.Module): YOLO model to check batch size for.\n        imgsz (int): Image size used for training.\n        amp (bool): If True, use automatic mixed precision (AMP) for training.\n\n    Returns:\n        (int): Optimal batch size computed using the autobatch() function.\n    \"\"\"\n\n    with torch.cuda.amp.autocast(amp):\n        return autobatch(deepcopy(model).train(), imgsz)  # compute optimal batch size\n\n\ndef autobatch(model, imgsz=640, fraction=0.67, batch_size=16):\n    \"\"\"\n    Automatically estimate the best YOLO batch size to use a fraction of the available CUDA memory.\n\n    Args:\n        model (torch.nn.module): YOLO model to compute batch size for.\n        imgsz (int, optional): The image size used as input for the YOLO model. Defaults to 640.\n        fraction (float, optional): The fraction of available CUDA memory to use. Defaults to 0.67.\n        batch_size (int, optional): The default batch size to use if an error is detected. Defaults to 16.\n\n    Returns:\n        (int): The optimal batch size.\n    \"\"\"\n\n    # Check device\n    prefix = colorstr('AutoBatch: ')\n    LOGGER.info(f'{prefix}Computing optimal batch size for imgsz={imgsz}')\n    device = next(model.parameters()).device  # get model device\n    if device.type == 'cpu':\n        LOGGER.info(f'{prefix}CUDA not detected, using default CPU batch-size {batch_size}')\n        return batch_size\n    if torch.backends.cudnn.benchmark:\n        LOGGER.info(f'{prefix} ⚠️ Requires torch.backends.cudnn.benchmark=False, using default batch-size {batch_size}')\n        return batch_size\n\n    # Inspect CUDA memory\n    gb = 1 << 30  # bytes to GiB (1024 ** 3)\n    d = str(device).upper()  # 'CUDA:0'\n    properties = torch.cuda.get_device_properties(device)  # device properties\n    t = properties.total_memory / gb  # GiB total\n    r = torch.cuda.memory_reserved(device) / gb  # GiB reserved\n    a = torch.cuda.memory_allocated(device) / gb  # GiB allocated\n    f = t - (r + a)  # GiB free\n    LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free')\n\n    # Profile batch sizes\n    batch_sizes = [1, 2, 4, 8, 16]\n    try:\n        img = [torch.empty(b, 3, imgsz, imgsz) for b in batch_sizes]\n        results = profile(img, model, n=3, device=device)\n\n        # Fit a solution\n        y = [x[2] for x in results if x]  # memory [2]\n        p = np.polyfit(batch_sizes[:len(y)], y, deg=1)  # first degree polynomial fit\n        b = int((f * fraction - p[1]) / p[0])  # y intercept (optimal batch size)\n        if None in results:  # some sizes failed\n            i = results.index(None)  # first fail index\n            if b >= batch_sizes[i]:  # y intercept above failure point\n                b = batch_sizes[max(i - 1, 0)]  # select prior safe point\n        if b < 1 or b > 1024:  # b outside of safe range\n            b = batch_size\n            LOGGER.info(f'{prefix}WARNING ⚠️ CUDA anomaly detected, using default batch-size {batch_size}.')\n\n        fraction = (np.polyval(p, b) + r + a) / t  # actual fraction predicted\n        LOGGER.info(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅')\n        return b\n    except Exception as e:\n        LOGGER.warning(f'{prefix}WARNING ⚠️ error detected: {e},  using default batch-size {batch_size}.')\n        return batch_size\n"
  },
  {
    "path": "ultralytics/yolo/utils/benchmarks.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nBenchmark a YOLO model formats for speed and accuracy\n\nUsage:\n    from ultralytics.yolo.utils.benchmarks import run_benchmarks\n    run_benchmarks(model='yolov8n.pt', imgsz=160)\n\nFormat                  | `format=argument`         | Model\n---                     | ---                       | ---\nPyTorch                 | -                         | yolov8n.pt\nTorchScript             | `torchscript`             | yolov8n.torchscript\nONNX                    | `onnx`                    | yolov8n.onnx\nOpenVINO                | `openvino`                | yolov8n_openvino_model/\nTensorRT                | `engine`                  | yolov8n.engine\nCoreML                  | `coreml`                  | yolov8n.mlmodel\nTensorFlow SavedModel   | `saved_model`             | yolov8n_saved_model/\nTensorFlow GraphDef     | `pb`                      | yolov8n.pb\nTensorFlow Lite         | `tflite`                  | yolov8n.tflite\nTensorFlow Edge TPU     | `edgetpu`                 | yolov8n_edgetpu.tflite\nTensorFlow.js           | `tfjs`                    | yolov8n_web_model/\nPaddlePaddle            | `paddle`                  | yolov8n_paddle_model/\n\"\"\"\n\nimport platform\nimport time\nfrom pathlib import Path\n\nfrom ultralytics import YOLO\nfrom ultralytics.yolo.engine.exporter import export_formats\nfrom ultralytics.yolo.utils import LINUX, LOGGER, MACOS, ROOT, SETTINGS\nfrom ultralytics.yolo.utils.checks import check_yolo\nfrom ultralytics.yolo.utils.downloads import download\nfrom ultralytics.yolo.utils.files import file_size\nfrom ultralytics.yolo.utils.torch_utils import select_device\n\n\ndef benchmark(model=Path(SETTINGS['weights_dir']) / 'yolov8n.pt',\n              imgsz=160,\n              half=False,\n              int8=False,\n              device='cpu',\n              hard_fail=False):\n    \"\"\"\n    Benchmark a YOLO model across different formats for speed and accuracy.\n\n    Args:\n        model (Union[str, Path], optional): Path to the model file or directory. Default is\n            Path(SETTINGS['weights_dir']) / 'yolov8n.pt'.\n        imgsz (int, optional): Image size for the benchmark. Default is 160.\n        half (bool, optional): Use half-precision for the model if True. Default is False.\n        int8 (bool, optional): Use int8-precision for the model if True. Default is False.\n        device (str, optional): Device to run the benchmark on, either 'cpu' or 'cuda'. Default is 'cpu'.\n        hard_fail (Union[bool, float], optional): If True or a float, assert benchmarks pass with given metric.\n            Default is False.\n\n    Returns:\n        df (pandas.DataFrame): A pandas DataFrame with benchmark results for each format, including file size,\n            metric, and inference time.\n    \"\"\"\n\n    import pandas as pd\n    pd.options.display.max_columns = 10\n    pd.options.display.width = 120\n    device = select_device(device, verbose=False)\n    if isinstance(model, (str, Path)):\n        model = YOLO(model)\n\n    y = []\n    t0 = time.time()\n    for i, (name, format, suffix, cpu, gpu) in export_formats().iterrows():  # index, (name, format, suffix, CPU, GPU)\n        emoji, filename = '❌', None  # export defaults\n        try:\n            assert i != 9 or LINUX, 'Edge TPU export only supported on Linux'\n            if i == 10:\n                assert MACOS or LINUX, 'TF.js export only supported on macOS and Linux'\n            if 'cpu' in device.type:\n                assert cpu, 'inference not supported on CPU'\n            if 'cuda' in device.type:\n                assert gpu, 'inference not supported on GPU'\n\n            # Export\n            if format == '-':\n                filename = model.ckpt_path or model.cfg\n                export = model  # PyTorch format\n            else:\n                filename = model.export(imgsz=imgsz, format=format, half=half, int8=int8, device=device)  # all others\n                export = YOLO(filename, task=model.task)\n                assert suffix in str(filename), 'export failed'\n            emoji = '❎'  # indicates export succeeded\n\n            # Predict\n            assert i not in (9, 10), 'inference not supported'  # Edge TPU and TF.js are unsupported\n            assert i != 5 or platform.system() == 'Darwin', 'inference only supported on macOS>=10.13'  # CoreML\n            if not (ROOT / 'assets/bus.jpg').exists():\n                download(url='https://ultralytics.com/images/bus.jpg', dir=ROOT / 'assets')\n            export.predict(ROOT / 'assets/bus.jpg', imgsz=imgsz, device=device, half=half)\n\n            # Validate\n            if model.task == 'detect':\n                data, key = 'coco8.yaml', 'metrics/mAP50-95(B)'\n            elif model.task == 'segment':\n                data, key = 'coco8-seg.yaml', 'metrics/mAP50-95(M)'\n            elif model.task == 'classify':\n                data, key = 'imagenet100', 'metrics/accuracy_top5'\n            elif model.task == 'pose':\n                data, key = 'coco8-pose.yaml', 'metrics/mAP50-95(P)'\n\n            results = export.val(data=data,\n                                 batch=1,\n                                 imgsz=imgsz,\n                                 plots=False,\n                                 device=device,\n                                 half=half,\n                                 int8=int8,\n                                 verbose=False)\n            metric, speed = results.results_dict[key], results.speed['inference']\n            y.append([name, '✅', round(file_size(filename), 1), round(metric, 4), round(speed, 2)])\n        except Exception as e:\n            if hard_fail:\n                assert type(e) is AssertionError, f'Benchmark hard_fail for {name}: {e}'\n            LOGGER.warning(f'ERROR ❌️ Benchmark failure for {name}: {e}')\n            y.append([name, emoji, round(file_size(filename), 1), None, None])  # mAP, t_inference\n\n    # Print results\n    check_yolo(device=device)  # print system info\n    df = pd.DataFrame(y, columns=['Format', 'Status❔', 'Size (MB)', key, 'Inference time (ms/im)'])\n\n    name = Path(model.ckpt_path).name\n    s = f'\\nBenchmarks complete for {name} on {data} at imgsz={imgsz} ({time.time() - t0:.2f}s)\\n{df}\\n'\n    LOGGER.info(s)\n    with open('benchmarks.log', 'a', errors='ignore', encoding='utf-8') as f:\n        f.write(s)\n\n    if hard_fail and isinstance(hard_fail, float):\n        metrics = df[key].array  # values to compare to floor\n        floor = hard_fail  # minimum metric floor to pass, i.e. = 0.29 mAP for YOLOv5n\n        assert all(x > floor for x in metrics if pd.notna(x)), f'HARD FAIL: one or more metric(s) < floor {floor}'\n\n    return df\n\n\nif __name__ == '__main__':\n    benchmark()\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/__init__.py",
    "content": "from .base import add_integration_callbacks, default_callbacks, get_default_callbacks\n\n__all__ = 'add_integration_callbacks', 'default_callbacks', 'get_default_callbacks'\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/base.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nBase callbacks\n\"\"\"\n\nfrom collections import defaultdict\nfrom copy import deepcopy\n\n# Trainer callbacks ----------------------------------------------------------------------------------------------------\n\n\ndef on_pretrain_routine_start(trainer):\n    \"\"\"Called before the pretraining routine starts.\"\"\"\n    pass\n\n\ndef on_pretrain_routine_end(trainer):\n    \"\"\"Called after the pretraining routine ends.\"\"\"\n    pass\n\n\ndef on_train_start(trainer):\n    \"\"\"Called when the training starts.\"\"\"\n    pass\n\n\ndef on_train_epoch_start(trainer):\n    \"\"\"Called at the start of each training epoch.\"\"\"\n    pass\n\n\ndef on_train_batch_start(trainer):\n    \"\"\"Called at the start of each training batch.\"\"\"\n    pass\n\n\ndef optimizer_step(trainer):\n    \"\"\"Called when the optimizer takes a step.\"\"\"\n    pass\n\n\ndef on_before_zero_grad(trainer):\n    \"\"\"Called before the gradients are set to zero.\"\"\"\n    pass\n\n\ndef on_train_batch_end(trainer):\n    \"\"\"Called at the end of each training batch.\"\"\"\n    pass\n\n\ndef on_train_epoch_end(trainer):\n    \"\"\"Called at the end of each training epoch.\"\"\"\n    pass\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Called at the end of each fit epoch (train + val).\"\"\"\n    pass\n\n\ndef on_model_save(trainer):\n    \"\"\"Called when the model is saved.\"\"\"\n    pass\n\n\ndef on_train_end(trainer):\n    \"\"\"Called when the training ends.\"\"\"\n    pass\n\n\ndef on_params_update(trainer):\n    \"\"\"Called when the model parameters are updated.\"\"\"\n    pass\n\n\ndef teardown(trainer):\n    \"\"\"Called during the teardown of the training process.\"\"\"\n    pass\n\n\n# Validator callbacks --------------------------------------------------------------------------------------------------\n\n\ndef on_val_start(validator):\n    \"\"\"Called when the validation starts.\"\"\"\n    pass\n\n\ndef on_val_batch_start(validator):\n    \"\"\"Called at the start of each validation batch.\"\"\"\n    pass\n\n\ndef on_val_batch_end(validator):\n    \"\"\"Called at the end of each validation batch.\"\"\"\n    pass\n\n\ndef on_val_end(validator):\n    \"\"\"Called when the validation ends.\"\"\"\n    pass\n\n\n# Predictor callbacks --------------------------------------------------------------------------------------------------\n\n\ndef on_predict_start(predictor):\n    \"\"\"Called when the prediction starts.\"\"\"\n    pass\n\n\ndef on_predict_batch_start(predictor):\n    \"\"\"Called at the start of each prediction batch.\"\"\"\n    pass\n\n\ndef on_predict_batch_end(predictor):\n    \"\"\"Called at the end of each prediction batch.\"\"\"\n    pass\n\n\ndef on_predict_postprocess_end(predictor):\n    \"\"\"Called after the post-processing of the prediction ends.\"\"\"\n    pass\n\n\ndef on_predict_end(predictor):\n    \"\"\"Called when the prediction ends.\"\"\"\n    pass\n\n\n# Exporter callbacks ---------------------------------------------------------------------------------------------------\n\n\ndef on_export_start(exporter):\n    \"\"\"Called when the model export starts.\"\"\"\n    pass\n\n\ndef on_export_end(exporter):\n    \"\"\"Called when the model export ends.\"\"\"\n    pass\n\n\ndefault_callbacks = {\n    # Run in trainer\n    'on_pretrain_routine_start': [on_pretrain_routine_start],\n    'on_pretrain_routine_end': [on_pretrain_routine_end],\n    'on_train_start': [on_train_start],\n    'on_train_epoch_start': [on_train_epoch_start],\n    'on_train_batch_start': [on_train_batch_start],\n    'optimizer_step': [optimizer_step],\n    'on_before_zero_grad': [on_before_zero_grad],\n    'on_train_batch_end': [on_train_batch_end],\n    'on_train_epoch_end': [on_train_epoch_end],\n    'on_fit_epoch_end': [on_fit_epoch_end],  # fit = train + val\n    'on_model_save': [on_model_save],\n    'on_train_end': [on_train_end],\n    'on_params_update': [on_params_update],\n    'teardown': [teardown],\n\n    # Run in validator\n    'on_val_start': [on_val_start],\n    'on_val_batch_start': [on_val_batch_start],\n    'on_val_batch_end': [on_val_batch_end],\n    'on_val_end': [on_val_end],\n\n    # Run in predictor\n    'on_predict_start': [on_predict_start],\n    'on_predict_batch_start': [on_predict_batch_start],\n    'on_predict_postprocess_end': [on_predict_postprocess_end],\n    'on_predict_batch_end': [on_predict_batch_end],\n    'on_predict_end': [on_predict_end],\n\n    # Run in exporter\n    'on_export_start': [on_export_start],\n    'on_export_end': [on_export_end]}\n\n\ndef get_default_callbacks():\n    \"\"\"\n    Return a copy of the default_callbacks dictionary with lists as default values.\n\n    Returns:\n        (defaultdict): A defaultdict with keys from default_callbacks and empty lists as default values.\n    \"\"\"\n    return defaultdict(list, deepcopy(default_callbacks))\n\n\ndef add_integration_callbacks(instance):\n    \"\"\"\n    Add integration callbacks from various sources to the instance's callbacks.\n\n    Args:\n        instance (Trainer, Predictor, Validator, Exporter): An object with a 'callbacks' attribute that is a dictionary\n            of callback lists.\n    \"\"\"\n    from .clearml import callbacks as clearml_cb\n    from .comet import callbacks as comet_cb\n    from .hub import callbacks as hub_cb\n    from .mlflow import callbacks as mlflow_cb\n    from .neptune import callbacks as neptune_cb\n    from .raytune import callbacks as tune_cb\n    from .tensorboard import callbacks as tensorboard_cb\n    from .wb import callbacks as wb_cb\n\n    for x in clearml_cb, comet_cb, hub_cb, mlflow_cb, neptune_cb, tune_cb, tensorboard_cb, wb_cb:\n        for k, v in x.items():\n            if v not in instance.callbacks[k]:  # prevent duplicate callbacks addition\n                instance.callbacks[k].append(v)  # callback[name].append(func)\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/clearml.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nimport re\n\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\nfrom ultralytics.yolo.utils import LOGGER, TESTS_RUNNING\nfrom ultralytics.yolo.utils.torch_utils import get_flops, get_num_params\n\ntry:\n    import clearml\n    from clearml import Task\n    from clearml.binding.frameworks.pytorch_bind import PatchPyTorchModelIO\n    from clearml.binding.matplotlib_bind import PatchedMatplotlib\n\n    assert hasattr(clearml, '__version__')  # verify package is not directory\n    assert not TESTS_RUNNING  # do not log pytest\nexcept (ImportError, AssertionError):\n    clearml = None\n\n\ndef _log_debug_samples(files, title='Debug Samples') -> None:\n    \"\"\"\n    Log files (images) as debug samples in the ClearML task.\n\n    Args:\n        files (list): A list of file paths in PosixPath format.\n        title (str): A title that groups together images with the same values.\n    \"\"\"\n    task = Task.current_task()\n    if task:\n        for f in files:\n            if f.exists():\n                it = re.search(r'_batch(\\d+)', f.name)\n                iteration = int(it.groups()[0]) if it else 0\n                task.get_logger().report_image(title=title,\n                                               series=f.name.replace(it.group(), ''),\n                                               local_path=str(f),\n                                               iteration=iteration)\n\n\ndef _log_plot(title, plot_path) -> None:\n    \"\"\"\n    Log an image as a plot in the plot section of ClearML.\n\n    Args:\n        title (str): The title of the plot.\n        plot_path (str): The path to the saved image file.\n    \"\"\"\n    img = mpimg.imread(plot_path)\n    fig = plt.figure()\n    ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect='auto', xticks=[], yticks=[])  # no ticks\n    ax.imshow(img)\n\n    Task.current_task().get_logger().report_matplotlib_figure(title=title,\n                                                              series='',\n                                                              figure=fig,\n                                                              report_interactive=False)\n\n\ndef on_pretrain_routine_start(trainer):\n    \"\"\"Runs at start of pretraining routine; initializes and connects/ logs task to ClearML.\"\"\"\n    try:\n        task = Task.current_task()\n        if task:\n            # Make sure the automatic pytorch and matplotlib bindings are disabled!\n            # We are logging these plots and model files manually in the integration\n            PatchPyTorchModelIO.update_current_task(None)\n            PatchedMatplotlib.update_current_task(None)\n        else:\n            task = Task.init(project_name=trainer.args.project or 'YOLOv8',\n                             task_name=trainer.args.name,\n                             tags=['YOLOv8'],\n                             output_uri=True,\n                             reuse_last_task_id=False,\n                             auto_connect_frameworks={\n                                 'pytorch': False,\n                                 'matplotlib': False})\n            LOGGER.warning('ClearML Initialized a new task. If you want to run remotely, '\n                           'please add clearml-init and connect your arguments before initializing YOLO.')\n        task.connect(vars(trainer.args), name='General')\n    except Exception as e:\n        LOGGER.warning(f'WARNING ⚠️ ClearML installed but not initialized correctly, not logging this run. {e}')\n\n\ndef on_train_epoch_end(trainer):\n    task = Task.current_task()\n\n    if task:\n        \"\"\"Logs debug samples for the first epoch of YOLO training.\"\"\"\n        if trainer.epoch == 1:\n            _log_debug_samples(sorted(trainer.save_dir.glob('train_batch*.jpg')), 'Mosaic')\n        \"\"\"Report the current training progress.\"\"\"\n        for k, v in trainer.validator.metrics.results_dict.items():\n            task.get_logger().report_scalar('train', k, v, iteration=trainer.epoch)\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Reports model information to logger at the end of an epoch.\"\"\"\n    task = Task.current_task()\n    if task:\n        # You should have access to the validation bboxes under jdict\n        task.get_logger().report_scalar(title='Epoch Time',\n                                        series='Epoch Time',\n                                        value=trainer.epoch_time,\n                                        iteration=trainer.epoch)\n        if trainer.epoch == 0:\n            model_info = {\n                'model/parameters': get_num_params(trainer.model),\n                'model/GFLOPs': round(get_flops(trainer.model), 3),\n                'model/speed(ms)': round(trainer.validator.speed['inference'], 3)}\n            for k, v in model_info.items():\n                task.get_logger().report_single_value(k, v)\n\n\ndef on_val_end(validator):\n    \"\"\"Logs validation results including labels and predictions.\"\"\"\n    if Task.current_task():\n        # Log val_labels and val_pred\n        _log_debug_samples(sorted(validator.save_dir.glob('val*.jpg')), 'Validation')\n\n\ndef on_train_end(trainer):\n    \"\"\"Logs final model and its name on training completion.\"\"\"\n    task = Task.current_task()\n    if task:\n        # Log final results, CM matrix + PR plots\n        files = [\n            'results.png', 'confusion_matrix.png', 'confusion_matrix_normalized.png',\n            *(f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R'))]\n        files = [(trainer.save_dir / f) for f in files if (trainer.save_dir / f).exists()]  # filter\n        for f in files:\n            _log_plot(title=f.stem, plot_path=f)\n        # Report final metrics\n        for k, v in trainer.validator.metrics.results_dict.items():\n            task.get_logger().report_single_value(k, v)\n        # Log the final model\n        task.update_output_model(model_path=str(trainer.best), model_name=trainer.args.name, auto_delete_file=False)\n\n\ncallbacks = {\n    'on_pretrain_routine_start': on_pretrain_routine_start,\n    'on_train_epoch_end': on_train_epoch_end,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_val_end': on_val_end,\n    'on_train_end': on_train_end} if clearml else {}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/comet.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nimport os\nfrom pathlib import Path\n\nfrom ultralytics.yolo.utils import LOGGER, RANK, TESTS_RUNNING, ops\nfrom ultralytics.yolo.utils.torch_utils import get_flops, get_num_params\n\ntry:\n    import comet_ml\n\n    assert not TESTS_RUNNING  # do not log pytest\n    assert hasattr(comet_ml, '__version__')  # verify package is not directory\nexcept (ImportError, AssertionError):\n    comet_ml = None\n\n# Ensures certain logging functions only run for supported tasks\nCOMET_SUPPORTED_TASKS = ['detect']\n\n# Names of plots created by YOLOv8 that are logged to Comet\nEVALUATION_PLOT_NAMES = 'F1_curve', 'P_curve', 'R_curve', 'PR_curve', 'confusion_matrix'\nLABEL_PLOT_NAMES = 'labels', 'labels_correlogram'\n\n_comet_image_prediction_count = 0\n\n\ndef _get_comet_mode():\n    return os.getenv('COMET_MODE', 'online')\n\n\ndef _get_comet_model_name():\n    return os.getenv('COMET_MODEL_NAME', 'YOLOv8')\n\n\ndef _get_eval_batch_logging_interval():\n    return int(os.getenv('COMET_EVAL_BATCH_LOGGING_INTERVAL', 1))\n\n\ndef _get_max_image_predictions_to_log():\n    return int(os.getenv('COMET_MAX_IMAGE_PREDICTIONS', 100))\n\n\ndef _scale_confidence_score(score):\n    scale = float(os.getenv('COMET_MAX_CONFIDENCE_SCORE', 100.0))\n    return score * scale\n\n\ndef _should_log_confusion_matrix():\n    return os.getenv('COMET_EVAL_LOG_CONFUSION_MATRIX', 'true').lower() == 'true'\n\n\ndef _should_log_image_predictions():\n    return os.getenv('COMET_EVAL_LOG_IMAGE_PREDICTIONS', 'true').lower() == 'true'\n\n\ndef _get_experiment_type(mode, project_name):\n    \"\"\"Return an experiment based on mode and project name.\"\"\"\n    if mode == 'offline':\n        return comet_ml.OfflineExperiment(project_name=project_name)\n\n    return comet_ml.Experiment(project_name=project_name)\n\n\ndef _create_experiment(args):\n    \"\"\"Ensures that the experiment object is only created in a single process during distributed training.\"\"\"\n    if RANK not in (-1, 0):\n        return\n    try:\n        comet_mode = _get_comet_mode()\n        experiment = _get_experiment_type(comet_mode, args.project)\n        experiment.log_parameters(vars(args))\n        experiment.log_others({\n            'eval_batch_logging_interval': _get_eval_batch_logging_interval(),\n            'log_confusion_matrix': _should_log_confusion_matrix(),\n            'log_image_predictions': _should_log_image_predictions(),\n            'max_image_predictions': _get_max_image_predictions_to_log(), })\n        experiment.log_other('Created from', 'yolov8')\n\n    except Exception as e:\n        LOGGER.warning(f'WARNING ⚠️ Comet installed but not initialized correctly, not logging this run. {e}')\n\n\ndef _fetch_trainer_metadata(trainer):\n    \"\"\"Returns metadata for YOLO training including epoch and asset saving status.\"\"\"\n    curr_epoch = trainer.epoch + 1\n\n    train_num_steps_per_epoch = len(trainer.train_loader.dataset) // trainer.batch_size\n    curr_step = curr_epoch * train_num_steps_per_epoch\n    final_epoch = curr_epoch == trainer.epochs\n\n    save = trainer.args.save\n    save_period = trainer.args.save_period\n    save_interval = curr_epoch % save_period == 0\n    save_assets = save and save_period > 0 and save_interval and not final_epoch\n\n    return dict(\n        curr_epoch=curr_epoch,\n        curr_step=curr_step,\n        save_assets=save_assets,\n        final_epoch=final_epoch,\n    )\n\n\ndef _scale_bounding_box_to_original_image_shape(box, resized_image_shape, original_image_shape, ratio_pad):\n    \"\"\"YOLOv8 resizes images during training and the label values\n    are normalized based on this resized shape. This function rescales the\n    bounding box labels to the original image shape.\n    \"\"\"\n\n    resized_image_height, resized_image_width = resized_image_shape\n\n    # Convert normalized xywh format predictions to xyxy in resized scale format\n    box = ops.xywhn2xyxy(box, h=resized_image_height, w=resized_image_width)\n    # Scale box predictions from resized image scale back to original image scale\n    box = ops.scale_boxes(resized_image_shape, box, original_image_shape, ratio_pad)\n    # Convert bounding box format from xyxy to xywh for Comet logging\n    box = ops.xyxy2xywh(box)\n    # Adjust xy center to correspond top-left corner\n    box[:2] -= box[2:] / 2\n    box = box.tolist()\n\n    return box\n\n\ndef _format_ground_truth_annotations_for_detection(img_idx, image_path, batch, class_name_map=None):\n    \"\"\"Format ground truth annotations for detection.\"\"\"\n    indices = batch['batch_idx'] == img_idx\n    bboxes = batch['bboxes'][indices]\n    if len(bboxes) == 0:\n        LOGGER.debug(f'COMET WARNING: Image: {image_path} has no bounding boxes labels')\n        return None\n\n    cls_labels = batch['cls'][indices].squeeze(1).tolist()\n    if class_name_map:\n        cls_labels = [str(class_name_map[label]) for label in cls_labels]\n\n    original_image_shape = batch['ori_shape'][img_idx]\n    resized_image_shape = batch['resized_shape'][img_idx]\n    ratio_pad = batch['ratio_pad'][img_idx]\n\n    data = []\n    for box, label in zip(bboxes, cls_labels):\n        box = _scale_bounding_box_to_original_image_shape(box, resized_image_shape, original_image_shape, ratio_pad)\n        data.append({\n            'boxes': [box],\n            'label': f'gt_{label}',\n            'score': _scale_confidence_score(1.0), })\n\n    return {'name': 'ground_truth', 'data': data}\n\n\ndef _format_prediction_annotations_for_detection(image_path, metadata, class_label_map=None):\n    \"\"\"Format YOLO predictions for object detection visualization.\"\"\"\n    stem = image_path.stem\n    image_id = int(stem) if stem.isnumeric() else stem\n\n    predictions = metadata.get(image_id)\n    if not predictions:\n        LOGGER.debug(f'COMET WARNING: Image: {image_path} has no bounding boxes predictions')\n        return None\n\n    data = []\n    for prediction in predictions:\n        boxes = prediction['bbox']\n        score = _scale_confidence_score(prediction['score'])\n        cls_label = prediction['category_id']\n        if class_label_map:\n            cls_label = str(class_label_map[cls_label])\n\n        data.append({'boxes': [boxes], 'label': cls_label, 'score': score})\n\n    return {'name': 'prediction', 'data': data}\n\n\ndef _fetch_annotations(img_idx, image_path, batch, prediction_metadata_map, class_label_map):\n    \"\"\"Join the ground truth and prediction annotations if they exist.\"\"\"\n    ground_truth_annotations = _format_ground_truth_annotations_for_detection(img_idx, image_path, batch,\n                                                                              class_label_map)\n    prediction_annotations = _format_prediction_annotations_for_detection(image_path, prediction_metadata_map,\n                                                                          class_label_map)\n\n    annotations = [\n        annotation for annotation in [ground_truth_annotations, prediction_annotations] if annotation is not None]\n    return [annotations] if annotations else None\n\n\ndef _create_prediction_metadata_map(model_predictions):\n    \"\"\"Create metadata map for model predictions by groupings them based on image ID.\"\"\"\n    pred_metadata_map = {}\n    for prediction in model_predictions:\n        pred_metadata_map.setdefault(prediction['image_id'], [])\n        pred_metadata_map[prediction['image_id']].append(prediction)\n\n    return pred_metadata_map\n\n\ndef _log_confusion_matrix(experiment, trainer, curr_step, curr_epoch):\n    \"\"\"Log the confusion matrix to Weights and Biases experiment.\"\"\"\n    conf_mat = trainer.validator.confusion_matrix.matrix\n    names = list(trainer.data['names'].values()) + ['background']\n    experiment.log_confusion_matrix(\n        matrix=conf_mat,\n        labels=names,\n        max_categories=len(names),\n        epoch=curr_epoch,\n        step=curr_step,\n    )\n\n\ndef _log_images(experiment, image_paths, curr_step, annotations=None):\n    \"\"\"Logs images to the experiment with optional annotations.\"\"\"\n    if annotations:\n        for image_path, annotation in zip(image_paths, annotations):\n            experiment.log_image(image_path, name=image_path.stem, step=curr_step, annotations=annotation)\n\n    else:\n        for image_path in image_paths:\n            experiment.log_image(image_path, name=image_path.stem, step=curr_step)\n\n\ndef _log_image_predictions(experiment, validator, curr_step):\n    \"\"\"Logs predicted boxes for a single image during training.\"\"\"\n    global _comet_image_prediction_count\n\n    task = validator.args.task\n    if task not in COMET_SUPPORTED_TASKS:\n        return\n\n    jdict = validator.jdict\n    if not jdict:\n        return\n\n    predictions_metadata_map = _create_prediction_metadata_map(jdict)\n    dataloader = validator.dataloader\n    class_label_map = validator.names\n\n    batch_logging_interval = _get_eval_batch_logging_interval()\n    max_image_predictions = _get_max_image_predictions_to_log()\n\n    for batch_idx, batch in enumerate(dataloader):\n        if (batch_idx + 1) % batch_logging_interval != 0:\n            continue\n\n        image_paths = batch['im_file']\n        for img_idx, image_path in enumerate(image_paths):\n            if _comet_image_prediction_count >= max_image_predictions:\n                return\n\n            image_path = Path(image_path)\n            annotations = _fetch_annotations(\n                img_idx,\n                image_path,\n                batch,\n                predictions_metadata_map,\n                class_label_map,\n            )\n            _log_images(\n                experiment,\n                [image_path],\n                curr_step,\n                annotations=annotations,\n            )\n            _comet_image_prediction_count += 1\n\n\ndef _log_plots(experiment, trainer):\n    \"\"\"Logs evaluation plots and label plots for the experiment.\"\"\"\n    plot_filenames = [trainer.save_dir / f'{plots}.png' for plots in EVALUATION_PLOT_NAMES]\n    _log_images(experiment, plot_filenames, None)\n\n    label_plot_filenames = [trainer.save_dir / f'{labels}.jpg' for labels in LABEL_PLOT_NAMES]\n    _log_images(experiment, label_plot_filenames, None)\n\n\ndef _log_model(experiment, trainer):\n    \"\"\"Log the best-trained model to Comet.ml.\"\"\"\n    model_name = _get_comet_model_name()\n    experiment.log_model(\n        model_name,\n        file_or_folder=str(trainer.best),\n        file_name='best.pt',\n        overwrite=True,\n    )\n\n\ndef on_pretrain_routine_start(trainer):\n    \"\"\"Creates or resumes a CometML experiment at the start of a YOLO pre-training routine.\"\"\"\n    experiment = comet_ml.get_global_experiment()\n    is_alive = getattr(experiment, 'alive', False)\n    if not experiment or not is_alive:\n        _create_experiment(trainer.args)\n\n\ndef on_train_epoch_end(trainer):\n    \"\"\"Log metrics and save batch images at the end of training epochs.\"\"\"\n    experiment = comet_ml.get_global_experiment()\n    if not experiment:\n        return\n\n    metadata = _fetch_trainer_metadata(trainer)\n    curr_epoch = metadata['curr_epoch']\n    curr_step = metadata['curr_step']\n\n    experiment.log_metrics(\n        trainer.label_loss_items(trainer.tloss, prefix='train'),\n        step=curr_step,\n        epoch=curr_epoch,\n    )\n\n    if curr_epoch == 1:\n        _log_images(experiment, trainer.save_dir.glob('train_batch*.jpg'), curr_step)\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Logs model assets at the end of each epoch.\"\"\"\n    experiment = comet_ml.get_global_experiment()\n    if not experiment:\n        return\n\n    metadata = _fetch_trainer_metadata(trainer)\n    curr_epoch = metadata['curr_epoch']\n    curr_step = metadata['curr_step']\n    save_assets = metadata['save_assets']\n\n    experiment.log_metrics(trainer.metrics, step=curr_step, epoch=curr_epoch)\n    experiment.log_metrics(trainer.lr, step=curr_step, epoch=curr_epoch)\n    if curr_epoch == 1:\n        model_info = {\n            'model/parameters': get_num_params(trainer.model),\n            'model/GFLOPs': round(get_flops(trainer.model), 3),\n            'model/speed(ms)': round(trainer.validator.speed['inference'], 3), }\n        experiment.log_metrics(model_info, step=curr_step, epoch=curr_epoch)\n\n    if not save_assets:\n        return\n\n    _log_model(experiment, trainer)\n    if _should_log_confusion_matrix():\n        _log_confusion_matrix(experiment, trainer, curr_step, curr_epoch)\n    if _should_log_image_predictions():\n        _log_image_predictions(experiment, trainer.validator, curr_step)\n\n\ndef on_train_end(trainer):\n    \"\"\"Perform operations at the end of training.\"\"\"\n    experiment = comet_ml.get_global_experiment()\n    if not experiment:\n        return\n\n    metadata = _fetch_trainer_metadata(trainer)\n    curr_epoch = metadata['curr_epoch']\n    curr_step = metadata['curr_step']\n    plots = trainer.args.plots\n\n    _log_model(experiment, trainer)\n    if plots:\n        _log_plots(experiment, trainer)\n\n    _log_confusion_matrix(experiment, trainer, curr_step, curr_epoch)\n    _log_image_predictions(experiment, trainer.validator, curr_step)\n    experiment.end()\n\n    global _comet_image_prediction_count\n    _comet_image_prediction_count = 0\n\n\ncallbacks = {\n    'on_pretrain_routine_start': on_pretrain_routine_start,\n    'on_train_epoch_end': on_train_epoch_end,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_train_end': on_train_end} if comet_ml else {}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/hub.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport json\nfrom time import time\n\nfrom ultralytics.hub.utils import PREFIX, events\nfrom ultralytics.yolo.utils import LOGGER\nfrom ultralytics.yolo.utils.torch_utils import get_flops, get_num_params\n\n\ndef on_pretrain_routine_end(trainer):\n    \"\"\"Logs info before starting timer for upload rate limit.\"\"\"\n    session = getattr(trainer, 'hub_session', None)\n    if session:\n        # Start timer for upload rate limit\n        LOGGER.info(f'{PREFIX}View model at https://hub.ultralytics.com/models/{session.model_id} 🚀')\n        session.timers = {'metrics': time(), 'ckpt': time()}  # start timer on session.rate_limit\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Uploads training progress metrics at the end of each epoch.\"\"\"\n    session = getattr(trainer, 'hub_session', None)\n    if session:\n        # Upload metrics after val end\n        all_plots = {**trainer.label_loss_items(trainer.tloss, prefix='train'), **trainer.metrics}\n        if trainer.epoch == 0:\n            model_info = {\n                'model/parameters': get_num_params(trainer.model),\n                'model/GFLOPs': round(get_flops(trainer.model), 3),\n                'model/speed(ms)': round(trainer.validator.speed['inference'], 3)}\n            all_plots = {**all_plots, **model_info}\n        session.metrics_queue[trainer.epoch] = json.dumps(all_plots)\n        if time() - session.timers['metrics'] > session.rate_limits['metrics']:\n            session.upload_metrics()\n            session.timers['metrics'] = time()  # reset timer\n            session.metrics_queue = {}  # reset queue\n\n\ndef on_model_save(trainer):\n    \"\"\"Saves checkpoints to Ultralytics HUB with rate limiting.\"\"\"\n    session = getattr(trainer, 'hub_session', None)\n    if session:\n        # Upload checkpoints with rate limiting\n        is_best = trainer.best_fitness == trainer.fitness\n        if time() - session.timers['ckpt'] > session.rate_limits['ckpt']:\n            LOGGER.info(f'{PREFIX}Uploading checkpoint https://hub.ultralytics.com/models/{session.model_id}')\n            session.upload_model(trainer.epoch, trainer.last, is_best)\n            session.timers['ckpt'] = time()  # reset timer\n\n\ndef on_train_end(trainer):\n    \"\"\"Upload final model and metrics to Ultralytics HUB at the end of training.\"\"\"\n    session = getattr(trainer, 'hub_session', None)\n    if session:\n        # Upload final model and metrics with exponential standoff\n        LOGGER.info(f'{PREFIX}Syncing final model...')\n        session.upload_model(trainer.epoch, trainer.best, map=trainer.metrics.get('metrics/mAP50-95(B)', 0), final=True)\n        session.alive = False  # stop heartbeats\n        LOGGER.info(f'{PREFIX}Done ✅\\n'\n                    f'{PREFIX}View model at https://hub.ultralytics.com/models/{session.model_id} 🚀')\n\n\ndef on_train_start(trainer):\n    \"\"\"Run events on train start.\"\"\"\n    events(trainer.args)\n\n\ndef on_val_start(validator):\n    \"\"\"Runs events on validation start.\"\"\"\n    events(validator.args)\n\n\ndef on_predict_start(predictor):\n    \"\"\"Run events on predict start.\"\"\"\n    events(predictor.args)\n\n\ndef on_export_start(exporter):\n    \"\"\"Run events on export start.\"\"\"\n    events(exporter.args)\n\n\ncallbacks = {\n    'on_pretrain_routine_end': on_pretrain_routine_end,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_model_save': on_model_save,\n    'on_train_end': on_train_end,\n    'on_train_start': on_train_start,\n    'on_val_start': on_val_start,\n    'on_predict_start': on_predict_start,\n    'on_export_start': on_export_start}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/mlflow.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport os\nimport re\nfrom pathlib import Path\n\nfrom ultralytics.yolo.utils import LOGGER, TESTS_RUNNING, colorstr\n\ntry:\n    import mlflow\n\n    assert not TESTS_RUNNING  # do not log pytest\n    assert hasattr(mlflow, '__version__')  # verify package is not directory\nexcept (ImportError, AssertionError):\n    mlflow = None\n\n\ndef on_pretrain_routine_end(trainer):\n    \"\"\"Logs training parameters to MLflow.\"\"\"\n    global mlflow, run, run_id, experiment_name\n\n    if os.environ.get('MLFLOW_TRACKING_URI') is None:\n        mlflow = None\n\n    if mlflow:\n        mlflow_location = os.environ['MLFLOW_TRACKING_URI']  # \"http://192.168.xxx.xxx:5000\"\n        mlflow.set_tracking_uri(mlflow_location)\n\n        experiment_name = trainer.args.project or '/Shared/YOLOv8'\n        experiment = mlflow.get_experiment_by_name(experiment_name)\n        if experiment is None:\n            mlflow.create_experiment(experiment_name)\n        mlflow.set_experiment(experiment_name)\n\n        prefix = colorstr('MLFlow: ')\n        try:\n            run, active_run = mlflow, mlflow.active_run()\n            if not active_run:\n                active_run = mlflow.start_run(experiment_id=experiment.experiment_id)\n            run_id = active_run.info.run_id\n            LOGGER.info(f'{prefix}Using run_id({run_id}) at {mlflow_location}')\n            run.log_params(vars(trainer.model.args))\n        except Exception as err:\n            LOGGER.error(f'{prefix}Failing init - {repr(err)}')\n            LOGGER.warning(f'{prefix}Continuing without Mlflow')\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Logs training metrics to Mlflow.\"\"\"\n    if mlflow:\n        metrics_dict = {f\"{re.sub('[()]', '', k)}\": float(v) for k, v in trainer.metrics.items()}\n        run.log_metrics(metrics=metrics_dict, step=trainer.epoch)\n\n\ndef on_train_end(trainer):\n    \"\"\"Called at end of train loop to log model artifact info.\"\"\"\n    if mlflow:\n        root_dir = Path(__file__).resolve().parents[3]\n        run.log_artifact(trainer.last)\n        run.log_artifact(trainer.best)\n        run.pyfunc.log_model(artifact_path=experiment_name,\n                             code_path=[str(root_dir)],\n                             artifacts={'model_path': str(trainer.save_dir)},\n                             python_model=run.pyfunc.PythonModel())\n\n\ncallbacks = {\n    'on_pretrain_routine_end': on_pretrain_routine_end,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_train_end': on_train_end} if mlflow else {}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/neptune.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nimport matplotlib.image as mpimg\nimport matplotlib.pyplot as plt\n\nfrom ultralytics.yolo.utils import LOGGER, TESTS_RUNNING\nfrom ultralytics.yolo.utils.torch_utils import get_flops, get_num_params\n\ntry:\n    import neptune\n    from neptune.types import File\n\n    assert not TESTS_RUNNING  # do not log pytest\n    assert hasattr(neptune, '__version__')\nexcept (ImportError, AssertionError):\n    neptune = None\n\nrun = None  # NeptuneAI experiment logger instance\n\n\ndef _log_scalars(scalars, step=0):\n    \"\"\"Log scalars to the NeptuneAI experiment logger.\"\"\"\n    if run:\n        for k, v in scalars.items():\n            run[k].append(value=v, step=step)\n\n\ndef _log_images(imgs_dict, group=''):\n    \"\"\"Log scalars to the NeptuneAI experiment logger.\"\"\"\n    if run:\n        for k, v in imgs_dict.items():\n            run[f'{group}/{k}'].upload(File(v))\n\n\ndef _log_plot(title, plot_path):\n    \"\"\"Log plots to the NeptuneAI experiment logger.\"\"\"\n    \"\"\"\n        Log image as plot in the plot section of NeptuneAI\n\n        arguments:\n        title (str) Title of the plot\n        plot_path (PosixPath or str) Path to the saved image file\n        \"\"\"\n    img = mpimg.imread(plot_path)\n    fig = plt.figure()\n    ax = fig.add_axes([0, 0, 1, 1], frameon=False, aspect='auto', xticks=[], yticks=[])  # no ticks\n    ax.imshow(img)\n    run[f'Plots/{title}'].upload(fig)\n\n\ndef on_pretrain_routine_start(trainer):\n    \"\"\"Callback function called before the training routine starts.\"\"\"\n    try:\n        global run\n        run = neptune.init_run(project=trainer.args.project or 'YOLOv8', name=trainer.args.name, tags=['YOLOv8'])\n        run['Configuration/Hyperparameters'] = {k: '' if v is None else v for k, v in vars(trainer.args).items()}\n    except Exception as e:\n        LOGGER.warning(f'WARNING ⚠️ NeptuneAI installed but not initialized correctly, not logging this run. {e}')\n\n\ndef on_train_epoch_end(trainer):\n    \"\"\"Callback function called at end of each training epoch.\"\"\"\n    _log_scalars(trainer.label_loss_items(trainer.tloss, prefix='train'), trainer.epoch + 1)\n    _log_scalars(trainer.lr, trainer.epoch + 1)\n    if trainer.epoch == 1:\n        _log_images({f.stem: str(f) for f in trainer.save_dir.glob('train_batch*.jpg')}, 'Mosaic')\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Callback function called at end of each fit (train+val) epoch.\"\"\"\n    if run and trainer.epoch == 0:\n        model_info = {\n            'parameters': get_num_params(trainer.model),\n            'GFLOPs': round(get_flops(trainer.model), 3),\n            'speed(ms)': round(trainer.validator.speed['inference'], 3)}\n        run['Configuration/Model'] = model_info\n    _log_scalars(trainer.metrics, trainer.epoch + 1)\n\n\ndef on_val_end(validator):\n    \"\"\"Callback function called at end of each validation.\"\"\"\n    if run:\n        # Log val_labels and val_pred\n        _log_images({f.stem: str(f) for f in validator.save_dir.glob('val*.jpg')}, 'Validation')\n\n\ndef on_train_end(trainer):\n    \"\"\"Callback function called at end of training.\"\"\"\n    if run:\n        # Log final results, CM matrix + PR plots\n        files = [\n            'results.png', 'confusion_matrix.png', 'confusion_matrix_normalized.png',\n            *(f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R'))]\n        files = [(trainer.save_dir / f) for f in files if (trainer.save_dir / f).exists()]  # filter\n        for f in files:\n            _log_plot(title=f.stem, plot_path=f)\n        # Log the final model\n        run[f'weights/{trainer.args.name or trainer.args.task}/{str(trainer.best.name)}'].upload(File(str(\n            trainer.best)))\n        run.stop()\n\n\ncallbacks = {\n    'on_pretrain_routine_start': on_pretrain_routine_start,\n    'on_train_epoch_end': on_train_epoch_end,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_val_end': on_val_end,\n    'on_train_end': on_train_end} if neptune else {}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/raytune.py",
    "content": "try:\n    import ray\n    from ray import tune\n    from ray.air import session\nexcept (ImportError, AssertionError):\n    tune = None\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Sends training metrics to Ray Tune at end of each epoch.\"\"\"\n    if ray.tune.is_session_enabled():\n        metrics = trainer.metrics\n        metrics['epoch'] = trainer.epoch\n        session.report(metrics)\n\n\ncallbacks = {\n    'on_fit_epoch_end': on_fit_epoch_end, } if tune else {}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/tensorboard.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nfrom ultralytics.yolo.utils import LOGGER, TESTS_RUNNING, colorstr\n\ntry:\n    from torch.utils.tensorboard import SummaryWriter\n\n    assert not TESTS_RUNNING  # do not log pytest\nexcept (ImportError, AssertionError):\n    SummaryWriter = None\n\nwriter = None  # TensorBoard SummaryWriter instance\n\n\ndef _log_scalars(scalars, step=0):\n    \"\"\"Logs scalar values to TensorBoard.\"\"\"\n    if writer:\n        for k, v in scalars.items():\n            writer.add_scalar(k, v, step)\n\n\ndef on_pretrain_routine_start(trainer):\n    \"\"\"Initialize TensorBoard logging with SummaryWriter.\"\"\"\n    if SummaryWriter:\n        try:\n            global writer\n            writer = SummaryWriter(str(trainer.save_dir))\n            prefix = colorstr('TensorBoard: ')\n            LOGGER.info(f\"{prefix}Start with 'tensorboard --logdir {trainer.save_dir}', view at http://localhost:6006/\")\n        except Exception as e:\n            LOGGER.warning(f'WARNING ⚠️ TensorBoard not initialized correctly, not logging this run. {e}')\n\n\ndef on_batch_end(trainer):\n    \"\"\"Logs scalar statistics at the end of a training batch.\"\"\"\n    _log_scalars(trainer.label_loss_items(trainer.tloss, prefix='train'), trainer.epoch + 1)\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Logs epoch metrics at end of training epoch.\"\"\"\n    _log_scalars(trainer.metrics, trainer.epoch + 1)\n\n\ncallbacks = {\n    'on_pretrain_routine_start': on_pretrain_routine_start,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_batch_end': on_batch_end}\n"
  },
  {
    "path": "ultralytics/yolo/utils/callbacks/wb.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom ultralytics.yolo.utils.torch_utils import get_flops, get_num_params\n\ntry:\n    import wandb as wb\n\n    assert hasattr(wb, '__version__')\nexcept (ImportError, AssertionError):\n    wb = None\n\n\ndef on_pretrain_routine_start(trainer):\n    \"\"\"Initiate and start project if module is present.\"\"\"\n    wb.init(project=trainer.args.project or 'YOLOv8', name=trainer.args.name, config=vars(\n        trainer.args)) if not wb.run else wb.run\n\n\ndef on_fit_epoch_end(trainer):\n    \"\"\"Logs training metrics and model information at the end of an epoch.\"\"\"\n    wb.run.log(trainer.metrics, step=trainer.epoch + 1)\n    if trainer.epoch == 0:\n        model_info = {\n            'model/parameters': get_num_params(trainer.model),\n            'model/GFLOPs': round(get_flops(trainer.model), 3),\n            'model/speed(ms)': round(trainer.validator.speed['inference'], 3)}\n        wb.run.log(model_info, step=trainer.epoch + 1)\n\n\ndef on_train_epoch_end(trainer):\n    \"\"\"Log metrics and save images at the end of each training epoch.\"\"\"\n    wb.run.log(trainer.label_loss_items(trainer.tloss, prefix='train'), step=trainer.epoch + 1)\n    wb.run.log(trainer.lr, step=trainer.epoch + 1)\n    if trainer.epoch == 1:\n        wb.run.log({f.stem: wb.Image(str(f))\n                    for f in trainer.save_dir.glob('train_batch*.jpg')},\n                   step=trainer.epoch + 1)\n\n\ndef on_train_end(trainer):\n    \"\"\"Save the best model as an artifact at end of training.\"\"\"\n    art = wb.Artifact(type='model', name=f'run_{wb.run.id}_model')\n    if trainer.best.exists():\n        art.add_file(trainer.best)\n        wb.run.log_artifact(art)\n\n\ncallbacks = {\n    'on_pretrain_routine_start': on_pretrain_routine_start,\n    'on_train_epoch_end': on_train_epoch_end,\n    'on_fit_epoch_end': on_fit_epoch_end,\n    'on_train_end': on_train_end} if wb else {}\n"
  },
  {
    "path": "ultralytics/yolo/utils/checks.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nimport contextlib\nimport glob\nimport inspect\nimport math\nimport os\nimport platform\nimport re\nimport shutil\nimport subprocess\nfrom pathlib import Path\nfrom typing import Optional\n\nimport cv2\nimport numpy as np\nimport pkg_resources as pkg\nimport psutil\nimport requests\nimport torch\nfrom matplotlib import font_manager\n\nfrom ultralytics.yolo.utils import (AUTOINSTALL, LOGGER, ONLINE, ROOT, USER_CONFIG_DIR, TryExcept, clean_url, colorstr,\n                                    downloads, emojis, is_colab, is_docker, is_kaggle, is_online, is_pip_package,\n                                    url2file)\n\n\ndef is_ascii(s) -> bool:\n    \"\"\"\n    Check if a string is composed of only ASCII characters.\n\n    Args:\n        s (str): String to be checked.\n\n    Returns:\n        bool: True if the string is composed only of ASCII characters, False otherwise.\n    \"\"\"\n    # Convert list, tuple, None, etc. to string\n    s = str(s)\n\n    # Check if the string is composed of only ASCII characters\n    return all(ord(c) < 128 for c in s)\n\n\ndef check_imgsz(imgsz, stride=32, min_dim=1, max_dim=2, floor=0):\n    \"\"\"\n    Verify image size is a multiple of the given stride in each dimension. If the image size is not a multiple of the\n    stride, update it to the nearest multiple of the stride that is greater than or equal to the given floor value.\n\n    Args:\n        imgsz (int) or (cList[int]): Image size.\n        stride (int): Stride value.\n        min_dim (int): Minimum number of dimensions.\n        floor (int): Minimum allowed value for image size.\n\n    Returns:\n        (List[int]): Updated image size.\n    \"\"\"\n    # Convert stride to integer if it is a tensor\n    stride = int(stride.max() if isinstance(stride, torch.Tensor) else stride)\n\n    # Convert image size to list if it is an integer\n    if isinstance(imgsz, int):\n        imgsz = [imgsz]\n    elif isinstance(imgsz, (list, tuple)):\n        imgsz = list(imgsz)\n    else:\n        raise TypeError(f\"'imgsz={imgsz}' is of invalid type {type(imgsz).__name__}. \"\n                        f\"Valid imgsz types are int i.e. 'imgsz=640' or list i.e. 'imgsz=[640,640]'\")\n\n    # Apply max_dim\n    if len(imgsz) > max_dim:\n        msg = \"'train' and 'val' imgsz must be an integer, while 'predict' and 'export' imgsz may be a [h, w] list \" \\\n              \"or an integer, i.e. 'yolo export imgsz=640,480' or 'yolo export imgsz=640'\"\n        if max_dim != 1:\n            raise ValueError(f'imgsz={imgsz} is not a valid image size. {msg}')\n        LOGGER.warning(f\"WARNING ⚠️ updating to 'imgsz={max(imgsz)}'. {msg}\")\n        imgsz = [max(imgsz)]\n    # Make image size a multiple of the stride\n    sz = [max(math.ceil(x / stride) * stride, floor) for x in imgsz]\n\n    # Print warning message if image size was updated\n    if sz != imgsz:\n        LOGGER.warning(f'WARNING ⚠️ imgsz={imgsz} must be multiple of max stride {stride}, updating to {sz}')\n\n    # Add missing dimensions if necessary\n    sz = [sz[0], sz[0]] if min_dim == 2 and len(sz) == 1 else sz[0] if min_dim == 1 and len(sz) == 1 else sz\n\n    return sz\n\n\ndef check_version(current: str = '0.0.0',\n                  minimum: str = '0.0.0',\n                  name: str = 'version ',\n                  pinned: bool = False,\n                  hard: bool = False,\n                  verbose: bool = False) -> bool:\n    \"\"\"\n    Check current version against the required minimum version.\n\n    Args:\n        current (str): Current version.\n        minimum (str): Required minimum version.\n        name (str): Name to be used in warning message.\n        pinned (bool): If True, versions must match exactly. If False, minimum version must be satisfied.\n        hard (bool): If True, raise an AssertionError if the minimum version is not met.\n        verbose (bool): If True, print warning message if minimum version is not met.\n\n    Returns:\n        (bool): True if minimum version is met, False otherwise.\n    \"\"\"\n    current, minimum = (pkg.parse_version(x) for x in (current, minimum))\n    result = (current == minimum) if pinned else (current >= minimum)  # bool\n    warning_message = f'WARNING ⚠️ {name}{minimum} is required by YOLOv8, but {name}{current} is currently installed'\n    if hard:\n        assert result, emojis(warning_message)  # assert min requirements met\n    if verbose and not result:\n        LOGGER.warning(warning_message)\n    return result\n\n\ndef check_latest_pypi_version(package_name='ultralytics'):\n    \"\"\"\n    Returns the latest version of a PyPI package without downloading or installing it.\n\n    Parameters:\n        package_name (str): The name of the package to find the latest version for.\n\n    Returns:\n        (str): The latest version of the package.\n    \"\"\"\n    with contextlib.suppress(Exception):\n        requests.packages.urllib3.disable_warnings()  # Disable the InsecureRequestWarning\n        response = requests.get(f'https://pypi.org/pypi/{package_name}/json', timeout=3)\n        if response.status_code == 200:\n            return response.json()['info']['version']\n    return None\n\n\ndef check_pip_update_available():\n    \"\"\"\n    Checks if a new version of the ultralytics package is available on PyPI.\n\n    Returns:\n        (bool): True if an update is available, False otherwise.\n    \"\"\"\n    if ONLINE and is_pip_package():\n        with contextlib.suppress(Exception):\n            from ultralytics import __version__\n            latest = check_latest_pypi_version()\n            if pkg.parse_version(__version__) < pkg.parse_version(latest):  # update is available\n                LOGGER.info(f'New https://pypi.org/project/ultralytics/{latest} available 😃 '\n                            f\"Update with 'pip install -U ultralytics'\")\n                return True\n    return False\n\n\ndef check_font(font='Arial.ttf'):\n    \"\"\"\n    Find font locally or download to user's configuration directory if it does not already exist.\n\n    Args:\n        font (str): Path or name of font.\n\n    Returns:\n        file (Path): Resolved font file path.\n    \"\"\"\n    name = Path(font).name\n\n    # Check USER_CONFIG_DIR\n    file = USER_CONFIG_DIR / name\n    if file.exists():\n        return file\n\n    # Check system fonts\n    matches = [s for s in font_manager.findSystemFonts() if font in s]\n    if any(matches):\n        return matches[0]\n\n    # Download to USER_CONFIG_DIR if missing\n    url = f'https://ultralytics.com/assets/{name}'\n    if downloads.is_url(url):\n        downloads.safe_download(url=url, file=file)\n        return file\n\n\ndef check_python(minimum: str = '3.7.0') -> bool:\n    \"\"\"\n    Check current python version against the required minimum version.\n\n    Args:\n        minimum (str): Required minimum version of python.\n\n    Returns:\n        None\n    \"\"\"\n    return check_version(platform.python_version(), minimum, name='Python ', hard=True)\n\n\n@TryExcept()\ndef check_requirements(requirements=ROOT.parent / 'requirements.txt', exclude=(), install=True, cmds=''):\n    \"\"\"\n    Check if installed dependencies meet YOLOv8 requirements and attempt to auto-update if needed.\n\n    Args:\n        requirements (Union[Path, str, List[str]]): Path to a requirements.txt file, a single package requirement as a\n            string, or a list of package requirements as strings.\n        exclude (Tuple[str]): Tuple of package names to exclude from checking.\n        install (bool): If True, attempt to auto-update packages that don't meet requirements.\n        cmds (str): Additional commands to pass to the pip install command when auto-updating.\n    \"\"\"\n    prefix = colorstr('red', 'bold', 'requirements:')\n    check_python()  # check python version\n    file = None\n    if isinstance(requirements, Path):  # requirements.txt file\n        file = requirements.resolve()\n        assert file.exists(), f'{prefix} {file} not found, check failed.'\n        with file.open() as f:\n            requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(f) if x.name not in exclude]\n    elif isinstance(requirements, str):\n        requirements = [requirements]\n\n    s = ''  # console string\n    n = 0  # number of packages updates\n    for r in requirements:\n        try:\n            pkg.require(r)\n        except (pkg.VersionConflict, pkg.DistributionNotFound):  # exception if requirements not met\n            try:  # attempt to import (slower but more accurate)\n                import importlib\n                importlib.import_module(next(pkg.parse_requirements(r)).name)\n            except ImportError:\n                s += f'\"{r}\" '\n                n += 1\n\n    if s and install and AUTOINSTALL:  # check environment variable\n        LOGGER.info(f\"{prefix} Ultralytics requirement{'s' * (n > 1)} {s}not found, attempting AutoUpdate...\")\n        try:\n            assert is_online(), 'AutoUpdate skipped (offline)'\n            LOGGER.info(subprocess.check_output(f'pip install --no-cache {s} {cmds}', shell=True).decode())\n            s = f\"{prefix} {n} package{'s' * (n > 1)} updated per {file or requirements}\\n\" \\\n                f\"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\\n\"\n            LOGGER.info(s)\n        except Exception as e:\n            LOGGER.warning(f'{prefix} ❌ {e}')\n\n\ndef check_suffix(file='yolov8n.pt', suffix='.pt', msg=''):\n    \"\"\"Check file(s) for acceptable suffix.\"\"\"\n    if file and suffix:\n        if isinstance(suffix, str):\n            suffix = (suffix, )\n        for f in file if isinstance(file, (list, tuple)) else [file]:\n            s = Path(f).suffix.lower().strip()  # file suffix\n            if len(s):\n                assert s in suffix, f'{msg}{f} acceptable suffix is {suffix}, not {s}'\n\n\ndef check_yolov5u_filename(file: str, verbose: bool = True):\n    \"\"\"Replace legacy YOLOv5 filenames with updated YOLOv5u filenames.\"\"\"\n    if ('yolov3' in file or 'yolov5' in file) and 'u' not in file:\n        original_file = file\n        file = re.sub(r'(.*yolov5([nsmlx]))\\.pt', '\\\\1u.pt', file)  # i.e. yolov5n.pt -> yolov5nu.pt\n        file = re.sub(r'(.*yolov5([nsmlx])6)\\.pt', '\\\\1u.pt', file)  # i.e. yolov5n6.pt -> yolov5n6u.pt\n        file = re.sub(r'(.*yolov3(|-tiny|-spp))\\.pt', '\\\\1u.pt', file)  # i.e. yolov3-spp.pt -> yolov3-sppu.pt\n        if file != original_file and verbose:\n            LOGGER.info(f\"PRO TIP 💡 Replace 'model={original_file}' with new 'model={file}'.\\nYOLOv5 'u' models are \"\n                        f'trained with https://github.com/ultralytics/ultralytics and feature improved performance vs '\n                        f'standard YOLOv5 models trained with https://github.com/ultralytics/yolov5.\\n')\n    return file\n\n\ndef check_file(file, suffix='', download=True, hard=True):\n    \"\"\"Search/download file (if necessary) and return path.\"\"\"\n    check_suffix(file, suffix)  # optional\n    file = str(file).strip()  # convert to string and strip spaces\n    file = check_yolov5u_filename(file)  # yolov5n -> yolov5nu\n    if not file or ('://' not in file and Path(file).exists()):  # exists ('://' check required in Windows Python<3.10)\n        return file\n    elif download and file.lower().startswith(('https://', 'http://', 'rtsp://', 'rtmp://')):  # download\n        url = file  # warning: Pathlib turns :// -> :/\n        file = url2file(file)  # '%2F' to '/', split https://url.com/file.txt?auth\n        if Path(file).exists():\n            LOGGER.info(f'Found {clean_url(url)} locally at {file}')  # file already exists\n        else:\n            downloads.safe_download(url=url, file=file, unzip=False)\n        return file\n    else:  # search\n        files = []\n        for d in 'models', 'datasets', 'tracker/cfg', 'yolo/cfg':  # search directories\n            files.extend(glob.glob(str(ROOT / d / '**' / file), recursive=True))  # find file\n        if not files and hard:\n            raise FileNotFoundError(f\"'{file}' does not exist\")\n        elif len(files) > 1 and hard:\n            raise FileNotFoundError(f\"Multiple files match '{file}', specify exact path: {files}\")\n        return files[0] if len(files) else []  # return file\n\n\ndef check_yaml(file, suffix=('.yaml', '.yml'), hard=True):\n    \"\"\"Search/download YAML file (if necessary) and return path, checking suffix.\"\"\"\n    return check_file(file, suffix, hard=hard)\n\n\ndef check_imshow(warn=False):\n    \"\"\"Check if environment supports image displays.\"\"\"\n    try:\n        assert not any((is_colab(), is_kaggle(), is_docker()))\n        cv2.imshow('test', np.zeros((1, 1, 3)))\n        cv2.waitKey(1)\n        cv2.destroyAllWindows()\n        cv2.waitKey(1)\n        return True\n    except Exception as e:\n        if warn:\n            LOGGER.warning(f'WARNING ⚠️ Environment does not support cv2.imshow() or PIL Image.show()\\n{e}')\n        return False\n\n\ndef check_yolo(verbose=True, device=''):\n    \"\"\"Return a human-readable YOLO software and hardware summary.\"\"\"\n    from ultralytics.yolo.utils.torch_utils import select_device\n\n    if is_colab():\n        shutil.rmtree('sample_data', ignore_errors=True)  # remove colab /sample_data directory\n\n    if verbose:\n        # System info\n        gib = 1 << 30  # bytes per GiB\n        ram = psutil.virtual_memory().total\n        total, used, free = shutil.disk_usage('/')\n        s = f'({os.cpu_count()} CPUs, {ram / gib:.1f} GB RAM, {(total - free) / gib:.1f}/{total / gib:.1f} GB disk)'\n        with contextlib.suppress(Exception):  # clear display if ipython is installed\n            from IPython import display\n            display.clear_output()\n    else:\n        s = ''\n\n    select_device(device=device, newline=False)\n    LOGGER.info(f'Setup complete ✅ {s}')\n\n\ndef git_describe(path=ROOT):  # path must be a directory\n    # Return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe\n    try:\n        assert (Path(path) / '.git').is_dir()\n        return subprocess.check_output(f'git -C {path} describe --tags --long --always', shell=True).decode()[:-1]\n    except AssertionError:\n        return ''\n\n\ndef print_args(args: Optional[dict] = None, show_file=True, show_func=False):\n    \"\"\"Print function arguments (optional args dict).\"\"\"\n\n    def strip_auth(v):\n        \"\"\"Clean longer Ultralytics HUB URLs by stripping potential authentication information.\"\"\"\n        return clean_url(v) if (isinstance(v, str) and v.startswith('http') and len(v) > 100) else v\n\n    x = inspect.currentframe().f_back  # previous frame\n    file, _, func, _, _ = inspect.getframeinfo(x)\n    if args is None:  # get args automatically\n        args, _, _, frm = inspect.getargvalues(x)\n        args = {k: v for k, v in frm.items() if k in args}\n    try:\n        file = Path(file).resolve().relative_to(ROOT).with_suffix('')\n    except ValueError:\n        file = Path(file).stem\n    s = (f'{file}: ' if show_file else '') + (f'{func}: ' if show_func else '')\n    LOGGER.info(colorstr(s) + ', '.join(f'{k}={strip_auth(v)}' for k, v in args.items()))\n"
  },
  {
    "path": "ultralytics/yolo/utils/dist.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport os\nimport re\nimport shutil\nimport socket\nimport sys\nimport tempfile\nfrom pathlib import Path\n\nfrom . import USER_CONFIG_DIR\nfrom .torch_utils import TORCH_1_9\n\n\ndef find_free_network_port() -> int:\n    \"\"\"Finds a free port on localhost.\n\n    It is useful in single-node training when we don't want to connect to a real main node but have to set the\n    `MASTER_PORT` environment variable.\n    \"\"\"\n    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n        s.bind(('127.0.0.1', 0))\n        return s.getsockname()[1]  # port\n\n\ndef generate_ddp_file(trainer):\n    \"\"\"Generates a DDP file and returns its file name.\"\"\"\n    module, name = f'{trainer.__class__.__module__}.{trainer.__class__.__name__}'.rsplit('.', 1)\n\n    content = f'''cfg = {vars(trainer.args)} \\nif __name__ == \"__main__\":\n    from {module} import {name}\n\n    trainer = {name}(cfg=cfg)\n    trainer.train()'''\n    (USER_CONFIG_DIR / 'DDP').mkdir(exist_ok=True)\n    with tempfile.NamedTemporaryFile(prefix='_temp_',\n                                     suffix=f'{id(trainer)}.py',\n                                     mode='w+',\n                                     encoding='utf-8',\n                                     dir=USER_CONFIG_DIR / 'DDP',\n                                     delete=False) as file:\n        file.write(content)\n    return file.name\n\n\ndef generate_ddp_command(world_size, trainer):\n    \"\"\"Generates and returns command for distributed training.\"\"\"\n    import __main__  # noqa local import to avoid https://github.com/Lightning-AI/lightning/issues/15218\n    if not trainer.resume:\n        shutil.rmtree(trainer.save_dir)  # remove the save_dir\n    file = str(Path(sys.argv[0]).resolve())\n    safe_pattern = re.compile(r'^[a-zA-Z0-9_. /\\\\-]{1,128}$')  # allowed characters and maximum of 100 characters\n    if not (safe_pattern.match(file) and Path(file).exists() and file.endswith('.py')):  # using CLI\n        file = generate_ddp_file(trainer)\n    dist_cmd = 'torch.distributed.run' if TORCH_1_9 else 'torch.distributed.launch'\n    port = find_free_network_port()\n    exclude_args = ['save_dir']\n    args = [f'{k}={v}' for k, v in vars(trainer.args).items() if k not in exclude_args]\n    cmd = [sys.executable, '-m', dist_cmd, '--nproc_per_node', f'{world_size}', '--master_port', f'{port}', file] + args\n    return cmd, file\n\n\ndef ddp_cleanup(trainer, file):\n    \"\"\"Delete temp file if created.\"\"\"\n    if f'{id(trainer)}.py' in file:  # if temp_file suffix in file\n        os.remove(file)\n"
  },
  {
    "path": "ultralytics/yolo/utils/downloads.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nimport shutil\nimport subprocess\nfrom itertools import repeat\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\nfrom urllib import parse, request\nfrom zipfile import BadZipFile, ZipFile, is_zipfile\n\nimport requests\nimport torch\nfrom tqdm import tqdm\n\nfrom ultralytics.yolo.utils import LOGGER, checks, clean_url, emojis, is_online, url2file\n\nGITHUB_ASSET_NAMES = [f'yolov8{k}{suffix}.pt' for k in 'nsmlx' for suffix in ('', '6', '-cls', '-seg', '-pose')] + \\\n                     [f'yolov5{k}u.pt' for k in 'nsmlx'] + \\\n                     [f'yolov3{k}u.pt' for k in ('', '-spp', '-tiny')] + \\\n                     [f'sam_{k}.pt' for k in 'bl'] + \\\n                     [f'rtdetr-{k}.pt' for k in 'lx']\nGITHUB_ASSET_STEMS = [Path(k).stem for k in GITHUB_ASSET_NAMES]\n\n\ndef is_url(url, check=True):\n    \"\"\"Check if string is URL and check if URL exists.\"\"\"\n    with contextlib.suppress(Exception):\n        url = str(url)\n        result = parse.urlparse(url)\n        assert all([result.scheme, result.netloc])  # check if is url\n        if check:\n            with request.urlopen(url) as response:\n                return response.getcode() == 200  # check if exists online\n        return True\n    return False\n\n\ndef unzip_file(file, path=None, exclude=('.DS_Store', '__MACOSX')):\n    \"\"\"\n    Unzips a *.zip file to the specified path, excluding files containing strings in the exclude list.\n\n    If the zipfile does not contain a single top-level directory, the function will create a new\n    directory with the same name as the zipfile (without the extension) to extract its contents.\n    If a path is not provided, the function will use the parent directory of the zipfile as the default path.\n\n    Args:\n        file (str): The path to the zipfile to be extracted.\n        path (str, optional): The path to extract the zipfile to. Defaults to None.\n        exclude (tuple, optional): A tuple of filename strings to be excluded. Defaults to ('.DS_Store', '__MACOSX').\n\n    Raises:\n        BadZipFile: If the provided file does not exist or is not a valid zipfile.\n\n    Returns:\n        (Path): The path to the directory where the zipfile was extracted.\n    \"\"\"\n    if not (Path(file).exists() and is_zipfile(file)):\n        raise BadZipFile(f\"File '{file}' does not exist or is a bad zip file.\")\n    if path is None:\n        path = Path(file).parent  # default path\n\n    with ZipFile(file) as zipObj:\n        file_list = [f for f in zipObj.namelist() if all(x not in f for x in exclude)]\n        top_level_dirs = {Path(f).parts[0] for f in file_list}\n\n        if len(top_level_dirs) > 1 or not file_list[0].endswith('/'):\n            path = Path(path) / Path(file).stem  # define new unzip directory\n\n        for f in file_list:\n            zipObj.extract(f, path=path)\n\n    return path  # return unzip dir\n\n\ndef check_disk_space(url='https://ultralytics.com/assets/coco128.zip', sf=1.5, hard=True):\n    \"\"\"\n    Check if there is sufficient disk space to download and store a file.\n\n    Args:\n        url (str, optional): The URL to the file. Defaults to 'https://ultralytics.com/assets/coco128.zip'.\n        sf (float, optional): Safety factor, the multiplier for the required free space. Defaults to 2.0.\n        hard (bool, optional): Whether to throw an error or not on insufficient disk space. Defaults to True.\n\n    Returns:\n        (bool): True if there is sufficient disk space, False otherwise.\n    \"\"\"\n    with contextlib.suppress(Exception):\n        gib = 1 << 30  # bytes per GiB\n        data = int(requests.head(url).headers['Content-Length']) / gib  # file size (GB)\n        total, used, free = (x / gib for x in shutil.disk_usage('/'))  # bytes\n        if data * sf < free:\n            return True  # sufficient space\n\n        # Insufficient space\n        text = (f'WARNING ⚠️ Insufficient free disk space {free:.1f} GB < {data * sf:.3f} GB required, '\n                f'Please free {data * sf - free:.1f} GB additional disk space and try again.')\n        if hard:\n            raise MemoryError(text)\n        else:\n            LOGGER.warning(text)\n            return False\n\n            # Pass if error\n    return True\n\n\ndef safe_download(url,\n                  file=None,\n                  dir=None,\n                  unzip=True,\n                  delete=False,\n                  curl=False,\n                  retry=3,\n                  min_bytes=1E0,\n                  progress=True):\n    \"\"\"\n    Downloads files from a URL, with options for retrying, unzipping, and deleting the downloaded file.\n\n    Args:\n        url (str): The URL of the file to be downloaded.\n        file (str, optional): The filename of the downloaded file.\n            If not provided, the file will be saved with the same name as the URL.\n        dir (str, optional): The directory to save the downloaded file.\n            If not provided, the file will be saved in the current working directory.\n        unzip (bool, optional): Whether to unzip the downloaded file. Default: True.\n        delete (bool, optional): Whether to delete the downloaded file after unzipping. Default: False.\n        curl (bool, optional): Whether to use curl command line tool for downloading. Default: False.\n        retry (int, optional): The number of times to retry the download in case of failure. Default: 3.\n        min_bytes (float, optional): The minimum number of bytes that the downloaded file should have, to be considered\n            a successful download. Default: 1E0.\n        progress (bool, optional): Whether to display a progress bar during the download. Default: True.\n    \"\"\"\n    if '://' not in str(url) and Path(url).is_file():  # exists ('://' check required in Windows Python<3.10)\n        f = Path(url)  # filename\n    else:  # does not exist\n        assert dir or file, 'dir or file required for download'\n        f = dir / url2file(url) if dir else Path(file)\n        desc = f'Downloading {clean_url(url)} to {f}'\n        LOGGER.info(f'{desc}...')\n        f.parent.mkdir(parents=True, exist_ok=True)  # make directory if missing\n        check_disk_space(url)\n        for i in range(retry + 1):\n            try:\n                if curl or i > 0:  # curl download with retry, continue\n                    s = 'sS' * (not progress)  # silent\n                    r = subprocess.run(['curl', '-#', f'-{s}L', url, '-o', f, '--retry', '3', '-C', '-']).returncode\n                    assert r == 0, f'Curl return value {r}'\n                else:  # urllib download\n                    method = 'torch'\n                    if method == 'torch':\n                        torch.hub.download_url_to_file(url, f, progress=progress)\n                    else:\n                        from ultralytics.yolo.utils import TQDM_BAR_FORMAT\n                        with request.urlopen(url) as response, tqdm(total=int(response.getheader('Content-Length', 0)),\n                                                                    desc=desc,\n                                                                    disable=not progress,\n                                                                    unit='B',\n                                                                    unit_scale=True,\n                                                                    unit_divisor=1024,\n                                                                    bar_format=TQDM_BAR_FORMAT) as pbar:\n                            with open(f, 'wb') as f_opened:\n                                for data in response:\n                                    f_opened.write(data)\n                                    pbar.update(len(data))\n\n                if f.exists():\n                    if f.stat().st_size > min_bytes:\n                        break  # success\n                    f.unlink()  # remove partial downloads\n            except Exception as e:\n                if i == 0 and not is_online():\n                    raise ConnectionError(emojis(f'❌  Download failure for {url}. Environment is not online.')) from e\n                elif i >= retry:\n                    raise ConnectionError(emojis(f'❌  Download failure for {url}. Retry limit reached.')) from e\n                LOGGER.warning(f'⚠️ Download failure, retrying {i + 1}/{retry} {url}...')\n\n    if unzip and f.exists() and f.suffix in ('', '.zip', '.tar', '.gz'):\n        unzip_dir = dir or f.parent  # unzip to dir if provided else unzip in place\n        LOGGER.info(f'Unzipping {f} to {unzip_dir}...')\n        if is_zipfile(f):\n            unzip_dir = unzip_file(file=f, path=unzip_dir)  # unzip\n        elif f.suffix == '.tar':\n            subprocess.run(['tar', 'xf', f, '--directory', unzip_dir], check=True)  # unzip\n        elif f.suffix == '.gz':\n            subprocess.run(['tar', 'xfz', f, '--directory', unzip_dir], check=True)  # unzip\n        if delete:\n            f.unlink()  # remove zip\n        return unzip_dir\n\n\ndef attempt_download_asset(file, repo='ultralytics/assets', release='v0.0.0'):\n    \"\"\"Attempt file download from GitHub release assets if not found locally. release = 'latest', 'v6.2', etc.\"\"\"\n    from ultralytics.yolo.utils import SETTINGS  # scoped for circular import\n\n    def github_assets(repository, version='latest'):\n        \"\"\"Return GitHub repo tag and assets (i.e. ['yolov8n.pt', 'yolov8s.pt', ...]).\"\"\"\n        if version != 'latest':\n            version = f'tags/{version}'  # i.e. tags/v6.2\n        response = requests.get(f'https://api.github.com/repos/{repository}/releases/{version}').json()  # github api\n        return response['tag_name'], [x['name'] for x in response['assets']]  # tag, assets\n\n    # YOLOv3/5u updates\n    file = str(file)\n    file = checks.check_yolov5u_filename(file)\n    file = Path(file.strip().replace(\"'\", ''))\n    if file.exists():\n        return str(file)\n    elif (SETTINGS['weights_dir'] / file).exists():\n        return str(SETTINGS['weights_dir'] / file)\n    else:\n        # URL specified\n        name = Path(parse.unquote(str(file))).name  # decode '%2F' to '/' etc.\n        if str(file).startswith(('http:/', 'https:/')):  # download\n            url = str(file).replace(':/', '://')  # Pathlib turns :// -> :/\n            file = url2file(name)  # parse authentication https://url.com/file.txt?auth...\n            if Path(file).is_file():\n                LOGGER.info(f'Found {clean_url(url)} locally at {file}')  # file already exists\n            else:\n                safe_download(url=url, file=file, min_bytes=1E5)\n            return file\n\n        # GitHub assets\n        assets = GITHUB_ASSET_NAMES\n        try:\n            tag, assets = github_assets(repo, release)\n        except Exception:\n            try:\n                tag, assets = github_assets(repo)  # latest release\n            except Exception:\n                try:\n                    tag = subprocess.check_output(['git', 'tag']).decode().split()[-1]\n                except Exception:\n                    tag = release\n\n        file.parent.mkdir(parents=True, exist_ok=True)  # make parent dir (if required)\n        if name in assets:\n            safe_download(url=f'https://github.com/{repo}/releases/download/{tag}/{name}', file=file, min_bytes=1E5)\n\n        return str(file)\n\n\ndef download(url, dir=Path.cwd(), unzip=True, delete=False, curl=False, threads=1, retry=3):\n    \"\"\"Downloads and unzips files concurrently if threads > 1, else sequentially.\"\"\"\n    dir = Path(dir)\n    dir.mkdir(parents=True, exist_ok=True)  # make directory\n    if threads > 1:\n        with ThreadPool(threads) as pool:\n            pool.map(\n                lambda x: safe_download(\n                    url=x[0], dir=x[1], unzip=unzip, delete=delete, curl=curl, retry=retry, progress=threads <= 1),\n                zip(url, repeat(dir)))\n            pool.close()\n            pool.join()\n    else:\n        for u in [url] if isinstance(url, (str, Path)) else url:\n            safe_download(url=u, dir=dir, unzip=unzip, delete=delete, curl=curl, retry=retry)\n"
  },
  {
    "path": "ultralytics/yolo/utils/errors.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom ultralytics.yolo.utils import emojis\n\n\nclass HUBModelError(Exception):\n\n    def __init__(self, message='Model not found. Please check model URL and try again.'):\n        \"\"\"Create an exception for when a model is not found.\"\"\"\n        super().__init__(emojis(message))\n"
  },
  {
    "path": "ultralytics/yolo/utils/files.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nimport glob\nimport os\nimport shutil\nfrom datetime import datetime\nfrom pathlib import Path\n\n\nclass WorkingDirectory(contextlib.ContextDecorator):\n    \"\"\"Usage: @WorkingDirectory(dir) decorator or 'with WorkingDirectory(dir):' context manager.\"\"\"\n\n    def __init__(self, new_dir):\n        \"\"\"Sets the working directory to 'new_dir' upon instantiation.\"\"\"\n        self.dir = new_dir  # new dir\n        self.cwd = Path.cwd().resolve()  # current dir\n\n    def __enter__(self):\n        \"\"\"Changes the current directory to the specified directory.\"\"\"\n        os.chdir(self.dir)\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        \"\"\"Restore the current working directory on context exit.\"\"\"\n        os.chdir(self.cwd)\n\n\ndef increment_path(path, exist_ok=False, sep='', mkdir=False):\n    \"\"\"\n    Increments a file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.\n\n    If the path exists and exist_ok is not set to True, the path will be incremented by appending a number and sep to\n    the end of the path. If the path is a file, the file extension will be preserved. If the path is a directory, the\n    number will be appended directly to the end of the path. If mkdir is set to True, the path will be created as a\n    directory if it does not already exist.\n\n    Args:\n        path (str, pathlib.Path): Path to increment.\n        exist_ok (bool, optional): If True, the path will not be incremented and returned as-is. Defaults to False.\n        sep (str, optional): Separator to use between the path and the incrementation number. Defaults to ''.\n        mkdir (bool, optional): Create a directory if it does not exist. Defaults to False.\n\n    Returns:\n        (pathlib.Path): Incremented path.\n    \"\"\"\n    path = Path(path)  # os-agnostic\n    if path.exists() and not exist_ok:\n        path, suffix = (path.with_suffix(''), path.suffix) if path.is_file() else (path, '')\n\n        # Method 1\n        for n in range(2, 9999):\n            p = f'{path}{sep}{n}{suffix}'  # increment path\n            if not os.path.exists(p):  #\n                break\n        path = Path(p)\n\n    if mkdir:\n        path.mkdir(parents=True, exist_ok=True)  # make directory\n\n    return path\n\n\ndef file_age(path=__file__):\n    \"\"\"Return days since last file update.\"\"\"\n    dt = (datetime.now() - datetime.fromtimestamp(Path(path).stat().st_mtime))  # delta\n    return dt.days  # + dt.seconds / 86400  # fractional days\n\n\ndef file_date(path=__file__):\n    \"\"\"Return human-readable file modification date, i.e. '2021-3-26'.\"\"\"\n    t = datetime.fromtimestamp(Path(path).stat().st_mtime)\n    return f'{t.year}-{t.month}-{t.day}'\n\n\ndef file_size(path):\n    \"\"\"Return file/dir size (MB).\"\"\"\n    if isinstance(path, (str, Path)):\n        mb = 1 << 20  # bytes to MiB (1024 ** 2)\n        path = Path(path)\n        if path.is_file():\n            return path.stat().st_size / mb\n        elif path.is_dir():\n            return sum(f.stat().st_size for f in path.glob('**/*') if f.is_file()) / mb\n    return 0.0\n\n\ndef get_latest_run(search_dir='.'):\n    \"\"\"Return path to most recent 'last.pt' in /runs (i.e. to --resume from).\"\"\"\n    last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)\n    return max(last_list, key=os.path.getctime) if last_list else ''\n\n\ndef make_dirs(dir='new_dir/'):\n    # Create folders\n    dir = Path(dir)\n    if dir.exists():\n        shutil.rmtree(dir)  # delete dir\n    for p in dir, dir / 'labels', dir / 'images':\n        p.mkdir(parents=True, exist_ok=True)  # make dir\n    return dir\n"
  },
  {
    "path": "ultralytics/yolo/utils/instance.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom collections import abc\nfrom itertools import repeat\nfrom numbers import Number\nfrom typing import List\n\nimport numpy as np\n\nfrom .ops import ltwh2xywh, ltwh2xyxy, resample_segments, xywh2ltwh, xywh2xyxy, xyxy2ltwh, xyxy2xywh\n\n\ndef _ntuple(n):\n    \"\"\"From PyTorch internals.\"\"\"\n\n    def parse(x):\n        \"\"\"Parse bounding boxes format between XYWH and LTWH.\"\"\"\n        return x if isinstance(x, abc.Iterable) else tuple(repeat(x, n))\n\n    return parse\n\n\nto_4tuple = _ntuple(4)\n\n# `xyxy` means left top and right bottom\n# `xywh` means center x, center y and width, height(yolo format)\n# `ltwh` means left top and width, height(coco format)\n_formats = ['xyxy', 'xywh', 'ltwh']\n\n__all__ = 'Bboxes',  # tuple or list\n\n\nclass Bboxes:\n    \"\"\"Now only numpy is supported.\"\"\"\n\n    def __init__(self, bboxes, format='xyxy') -> None:\n        assert format in _formats, f'Invalid bounding box format: {format}, format must be one of {_formats}'\n        bboxes = bboxes[None, :] if bboxes.ndim == 1 else bboxes\n        assert bboxes.ndim == 2\n        assert bboxes.shape[1] == 4\n        self.bboxes = bboxes\n        self.format = format\n        # self.normalized = normalized\n\n    # def convert(self, format):\n    #     assert format in _formats\n    #     if self.format == format:\n    #         bboxes = self.bboxes\n    #     elif self.format == \"xyxy\":\n    #         if format == \"xywh\":\n    #             bboxes = xyxy2xywh(self.bboxes)\n    #         else:\n    #             bboxes = xyxy2ltwh(self.bboxes)\n    #     elif self.format == \"xywh\":\n    #         if format == \"xyxy\":\n    #             bboxes = xywh2xyxy(self.bboxes)\n    #         else:\n    #             bboxes = xywh2ltwh(self.bboxes)\n    #     else:\n    #         if format == \"xyxy\":\n    #             bboxes = ltwh2xyxy(self.bboxes)\n    #         else:\n    #             bboxes = ltwh2xywh(self.bboxes)\n    #\n    #     return Bboxes(bboxes, format)\n\n    def convert(self, format):\n        \"\"\"Converts bounding box format from one type to another.\"\"\"\n        assert format in _formats, f'Invalid bounding box format: {format}, format must be one of {_formats}'\n        if self.format == format:\n            return\n        elif self.format == 'xyxy':\n            bboxes = xyxy2xywh(self.bboxes) if format == 'xywh' else xyxy2ltwh(self.bboxes)\n        elif self.format == 'xywh':\n            bboxes = xywh2xyxy(self.bboxes) if format == 'xyxy' else xywh2ltwh(self.bboxes)\n        else:\n            bboxes = ltwh2xyxy(self.bboxes) if format == 'xyxy' else ltwh2xywh(self.bboxes)\n        self.bboxes = bboxes\n        self.format = format\n\n    def areas(self):\n        \"\"\"Return box areas.\"\"\"\n        self.convert('xyxy')\n        return (self.bboxes[:, 2] - self.bboxes[:, 0]) * (self.bboxes[:, 3] - self.bboxes[:, 1])\n\n    # def denormalize(self, w, h):\n    #    if not self.normalized:\n    #         return\n    #     assert (self.bboxes <= 1.0).all()\n    #     self.bboxes[:, 0::2] *= w\n    #     self.bboxes[:, 1::2] *= h\n    #     self.normalized = False\n    #\n    # def normalize(self, w, h):\n    #     if self.normalized:\n    #         return\n    #     assert (self.bboxes > 1.0).any()\n    #     self.bboxes[:, 0::2] /= w\n    #     self.bboxes[:, 1::2] /= h\n    #     self.normalized = True\n\n    def mul(self, scale):\n        \"\"\"\n        Args:\n            scale (tuple) or (list) or (int): the scale for four coords.\n        \"\"\"\n        if isinstance(scale, Number):\n            scale = to_4tuple(scale)\n        assert isinstance(scale, (tuple, list))\n        assert len(scale) == 4\n        self.bboxes[:, 0] *= scale[0]\n        self.bboxes[:, 1] *= scale[1]\n        self.bboxes[:, 2] *= scale[2]\n        self.bboxes[:, 3] *= scale[3]\n\n    def add(self, offset):\n        \"\"\"\n        Args:\n            offset (tuple) or (list) or (int): the offset for four coords.\n        \"\"\"\n        if isinstance(offset, Number):\n            offset = to_4tuple(offset)\n        assert isinstance(offset, (tuple, list))\n        assert len(offset) == 4\n        self.bboxes[:, 0] += offset[0]\n        self.bboxes[:, 1] += offset[1]\n        self.bboxes[:, 2] += offset[2]\n        self.bboxes[:, 3] += offset[3]\n\n    def __len__(self):\n        \"\"\"Return the number of boxes.\"\"\"\n        return len(self.bboxes)\n\n    @classmethod\n    def concatenate(cls, boxes_list: List['Bboxes'], axis=0) -> 'Bboxes':\n        \"\"\"\n        Concatenate a list of Bboxes objects into a single Bboxes object.\n\n        Args:\n            boxes_list (List[Bboxes]): A list of Bboxes objects to concatenate.\n            axis (int, optional): The axis along which to concatenate the bounding boxes.\n                                   Defaults to 0.\n\n        Returns:\n            Bboxes: A new Bboxes object containing the concatenated bounding boxes.\n\n        Note:\n            The input should be a list or tuple of Bboxes objects.\n        \"\"\"\n        assert isinstance(boxes_list, (list, tuple))\n        if not boxes_list:\n            return cls(np.empty(0))\n        assert all(isinstance(box, Bboxes) for box in boxes_list)\n\n        if len(boxes_list) == 1:\n            return boxes_list[0]\n        return cls(np.concatenate([b.bboxes for b in boxes_list], axis=axis))\n\n    def __getitem__(self, index) -> 'Bboxes':\n        \"\"\"\n        Retrieve a specific bounding box or a set of bounding boxes using indexing.\n\n        Args:\n            index (int, slice, or np.ndarray): The index, slice, or boolean array to select\n                                               the desired bounding boxes.\n\n        Returns:\n            Bboxes: A new Bboxes object containing the selected bounding boxes.\n\n        Raises:\n            AssertionError: If the indexed bounding boxes do not form a 2-dimensional matrix.\n\n        Note:\n            When using boolean indexing, make sure to provide a boolean array with the same\n            length as the number of bounding boxes.\n        \"\"\"\n        if isinstance(index, int):\n            return Bboxes(self.bboxes[index].view(1, -1))\n        b = self.bboxes[index]\n        assert b.ndim == 2, f'Indexing on Bboxes with {index} failed to return a matrix!'\n        return Bboxes(b)\n\n\nclass Instances:\n\n    def __init__(self, bboxes, segments=None, keypoints=None, bbox_format='xywh', normalized=True) -> None:\n        \"\"\"\n        Args:\n            bboxes (ndarray): bboxes with shape [N, 4].\n            segments (list | ndarray): segments.\n            keypoints (ndarray): keypoints(x, y, visible) with shape [N, 17, 3].\n        \"\"\"\n        if segments is None:\n            segments = []\n        self._bboxes = Bboxes(bboxes=bboxes, format=bbox_format)\n        self.keypoints = keypoints\n        self.normalized = normalized\n\n        if len(segments) > 0:\n            # list[np.array(1000, 2)] * num_samples\n            segments = resample_segments(segments)\n            # (N, 1000, 2)\n            segments = np.stack(segments, axis=0)\n        else:\n            segments = np.zeros((0, 1000, 2), dtype=np.float32)\n        self.segments = segments\n\n    def convert_bbox(self, format):\n        \"\"\"Convert bounding box format.\"\"\"\n        self._bboxes.convert(format=format)\n\n    def bbox_areas(self):\n        \"\"\"Calculate the area of bounding boxes.\"\"\"\n        self._bboxes.areas()\n\n    def scale(self, scale_w, scale_h, bbox_only=False):\n        \"\"\"this might be similar with denormalize func but without normalized sign.\"\"\"\n        self._bboxes.mul(scale=(scale_w, scale_h, scale_w, scale_h))\n        if bbox_only:\n            return\n        self.segments[..., 0] *= scale_w\n        self.segments[..., 1] *= scale_h\n        if self.keypoints is not None:\n            self.keypoints[..., 0] *= scale_w\n            self.keypoints[..., 1] *= scale_h\n\n    def denormalize(self, w, h):\n        \"\"\"Denormalizes boxes, segments, and keypoints from normalized coordinates.\"\"\"\n        if not self.normalized:\n            return\n        self._bboxes.mul(scale=(w, h, w, h))\n        self.segments[..., 0] *= w\n        self.segments[..., 1] *= h\n        if self.keypoints is not None:\n            self.keypoints[..., 0] *= w\n            self.keypoints[..., 1] *= h\n        self.normalized = False\n\n    def normalize(self, w, h):\n        \"\"\"Normalize bounding boxes, segments, and keypoints to image dimensions.\"\"\"\n        if self.normalized:\n            return\n        self._bboxes.mul(scale=(1 / w, 1 / h, 1 / w, 1 / h))\n        self.segments[..., 0] /= w\n        self.segments[..., 1] /= h\n        if self.keypoints is not None:\n            self.keypoints[..., 0] /= w\n            self.keypoints[..., 1] /= h\n        self.normalized = True\n\n    def add_padding(self, padw, padh):\n        \"\"\"Handle rect and mosaic situation.\"\"\"\n        assert not self.normalized, 'you should add padding with absolute coordinates.'\n        self._bboxes.add(offset=(padw, padh, padw, padh))\n        self.segments[..., 0] += padw\n        self.segments[..., 1] += padh\n        if self.keypoints is not None:\n            self.keypoints[..., 0] += padw\n            self.keypoints[..., 1] += padh\n\n    def __getitem__(self, index) -> 'Instances':\n        \"\"\"\n        Retrieve a specific instance or a set of instances using indexing.\n\n        Args:\n            index (int, slice, or np.ndarray): The index, slice, or boolean array to select\n                                               the desired instances.\n\n        Returns:\n            Instances: A new Instances object containing the selected bounding boxes,\n                       segments, and keypoints if present.\n\n        Note:\n            When using boolean indexing, make sure to provide a boolean array with the same\n            length as the number of instances.\n        \"\"\"\n        segments = self.segments[index] if len(self.segments) else self.segments\n        keypoints = self.keypoints[index] if self.keypoints is not None else None\n        bboxes = self.bboxes[index]\n        bbox_format = self._bboxes.format\n        return Instances(\n            bboxes=bboxes,\n            segments=segments,\n            keypoints=keypoints,\n            bbox_format=bbox_format,\n            normalized=self.normalized,\n        )\n\n    def flipud(self, h):\n        \"\"\"Flips the coordinates of bounding boxes, segments, and keypoints vertically.\"\"\"\n        if self._bboxes.format == 'xyxy':\n            y1 = self.bboxes[:, 1].copy()\n            y2 = self.bboxes[:, 3].copy()\n            self.bboxes[:, 1] = h - y2\n            self.bboxes[:, 3] = h - y1\n        else:\n            self.bboxes[:, 1] = h - self.bboxes[:, 1]\n        self.segments[..., 1] = h - self.segments[..., 1]\n        if self.keypoints is not None:\n            self.keypoints[..., 1] = h - self.keypoints[..., 1]\n\n    def fliplr(self, w):\n        \"\"\"Reverses the order of the bounding boxes and segments horizontally.\"\"\"\n        if self._bboxes.format == 'xyxy':\n            x1 = self.bboxes[:, 0].copy()\n            x2 = self.bboxes[:, 2].copy()\n            self.bboxes[:, 0] = w - x2\n            self.bboxes[:, 2] = w - x1\n        else:\n            self.bboxes[:, 0] = w - self.bboxes[:, 0]\n        self.segments[..., 0] = w - self.segments[..., 0]\n        if self.keypoints is not None:\n            self.keypoints[..., 0] = w - self.keypoints[..., 0]\n\n    def clip(self, w, h):\n        \"\"\"Clips bounding boxes, segments, and keypoints values to stay within image boundaries.\"\"\"\n        ori_format = self._bboxes.format\n        self.convert_bbox(format='xyxy')\n        self.bboxes[:, [0, 2]] = self.bboxes[:, [0, 2]].clip(0, w)\n        self.bboxes[:, [1, 3]] = self.bboxes[:, [1, 3]].clip(0, h)\n        if ori_format != 'xyxy':\n            self.convert_bbox(format=ori_format)\n        self.segments[..., 0] = self.segments[..., 0].clip(0, w)\n        self.segments[..., 1] = self.segments[..., 1].clip(0, h)\n        if self.keypoints is not None:\n            self.keypoints[..., 0] = self.keypoints[..., 0].clip(0, w)\n            self.keypoints[..., 1] = self.keypoints[..., 1].clip(0, h)\n\n    def update(self, bboxes, segments=None, keypoints=None):\n        \"\"\"Updates instance variables.\"\"\"\n        new_bboxes = Bboxes(bboxes, format=self._bboxes.format)\n        self._bboxes = new_bboxes\n        if segments is not None:\n            self.segments = segments\n        if keypoints is not None:\n            self.keypoints = keypoints\n\n    def __len__(self):\n        \"\"\"Return the length of the instance list.\"\"\"\n        return len(self.bboxes)\n\n    @classmethod\n    def concatenate(cls, instances_list: List['Instances'], axis=0) -> 'Instances':\n        \"\"\"\n        Concatenates a list of Instances objects into a single Instances object.\n\n        Args:\n            instances_list (List[Instances]): A list of Instances objects to concatenate.\n            axis (int, optional): The axis along which the arrays will be concatenated. Defaults to 0.\n\n        Returns:\n            Instances: A new Instances object containing the concatenated bounding boxes,\n                       segments, and keypoints if present.\n\n        Note:\n            The `Instances` objects in the list should have the same properties, such as\n            the format of the bounding boxes, whether keypoints are present, and if the\n            coordinates are normalized.\n        \"\"\"\n        assert isinstance(instances_list, (list, tuple))\n        if not instances_list:\n            return cls(np.empty(0))\n        assert all(isinstance(instance, Instances) for instance in instances_list)\n\n        if len(instances_list) == 1:\n            return instances_list[0]\n\n        use_keypoint = instances_list[0].keypoints is not None\n        bbox_format = instances_list[0]._bboxes.format\n        normalized = instances_list[0].normalized\n\n        cat_boxes = np.concatenate([ins.bboxes for ins in instances_list], axis=axis)\n        cat_segments = np.concatenate([b.segments for b in instances_list], axis=axis)\n        cat_keypoints = np.concatenate([b.keypoints for b in instances_list], axis=axis) if use_keypoint else None\n        return cls(cat_boxes, cat_segments, cat_keypoints, bbox_format, normalized)\n\n    @property\n    def bboxes(self):\n        \"\"\"Return bounding boxes.\"\"\"\n        return self._bboxes.bboxes\n"
  },
  {
    "path": "ultralytics/yolo/utils/loss.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom .metrics import bbox_iou\nfrom .tal import bbox2dist\n\nclass FocalLossV1(nn.Module):\n    \"\"\"https://github.com/CoinCheung/pytorch-loss/blob/master/focal_loss.py\"\"\"\n    def __init__(self,\n                 alpha=0.25,\n                 gamma=2,\n                 reduction='mean',):\n        super(FocalLossV1, self).__init__()\n        self.alpha = alpha\n        self.gamma = gamma\n        self.reduction = reduction\n        self.crit = nn.BCEWithLogitsLoss(reduction='none')\n\n    def forward(self, logits, label):\n        '''\n        Usage is same as nn.BCEWithLogits:\n            >>> criteria = FocalLossV1()\n            >>> logits = torch.randn(8, 19, 384, 384)\n            >>> lbs = torch.randint(0, 2, (8, 19, 384, 384)).float()\n            >>> loss = criteria(logits, lbs)\n        '''\n        probs = torch.sigmoid(logits)\n        coeff = torch.abs(label - probs).pow(self.gamma).neg()\n        log_probs = torch.where(logits >= 0,\n                F.softplus(logits, -1, 50),\n                logits - F.softplus(logits, 1, 50))\n        log_1_probs = torch.where(logits >= 0,\n                -logits + F.softplus(logits, -1, 50),\n                -F.softplus(logits, 1, 50))\n        loss = label * self.alpha * log_probs + (1. - label) * (1. - self.alpha) * log_1_probs\n        loss = loss * coeff\n\n        if self.reduction == 'mean':\n            loss = loss.mean()\n        if self.reduction == 'sum':\n            loss = loss.sum()\n        return loss\n\n\n\nclass tversky(nn.Module):\n    def __init__(self, smooth=1):\n        super(tversky, self).__init__()\n        self.smooth = smooth\n\n\n\n    def forward(self, logits, label,alpha=0.7):\n        '''\n        args: logits: tensor of shape (1, H, W)\n        args: label: tensor of shape (1, H, W)\n        '''\n        probs = torch.sigmoid(logits)\n\n        true_pos = torch.sum(label * probs)\n        false_neg = torch.sum(label * (1 - probs))\n        false_pos = torch.sum((1 - label) * probs)\n        loss = (true_pos + self.smooth)/(true_pos + alpha*false_neg + (1-alpha)*false_pos + self.smooth)\n\n        return 1-loss\nclass DiceLoss(nn.Module):\n    def __init__(self, smooth=1, reduction='mean', weight=None, ignore_lb=255):\n        super(DiceLoss, self).__init__()\n        self.smooth = smooth\n        self.reduction = reduction\n        self.weight = None if weight is None else torch.tensor(weight)\n        self.ignore_lb = ignore_lb\n\n    def forward(self, logits, label):\n        '''\n        args: logits: tensor of shape (1, H, W)\n        args: label: tensor of shape (1, H, W)\n        '''\n        # Convert logits to probabilities\n        probs = torch.sigmoid(logits)\n\n\n        ignore_mask = label == self.ignore_lb\n        lb_one_hot = torch.zeros_like(probs)\n        lb_one_hot[label == 1] = 1\n        lb_one_hot[ignore_mask] = 0\n\n        # Compute loss\n        numer = torch.sum(probs * lb_one_hot)\n        denom = torch.sum(probs + lb_one_hot)\n\n        loss = 1 - (2 * numer + self.smooth) / (denom + self.smooth)\n\n        return loss\n\n\n\nclass IoULoss(nn.Module):\n    '''https://blog.csdn.net/lwf1881/article/details/123725202'''\n    def __init__(self, weight=None, size_average=True):\n        super(IoULoss, self).__init__()\n\n    def forward(self, inputs, targets, smooth=1):\n        # comment out if your model contains a sigmoid or equivalent activation layer\n        inputs = torch.sigmoid(inputs)\n\n        # flatten label and prediction tensors\n        inputs = inputs.view(-1)\n        targets = targets.view(-1)\n\n        # intersection is equivalent to True Positive count\n        # union is the mutually inclusive area of all labels & predictions\n        intersection = (inputs * targets).sum()\n        total = (inputs + targets).sum()\n        union = total - intersection\n\n        IoU = (intersection + smooth) / (union + smooth)\n\n        return 1 - IoU\n\n\nclass VarifocalLoss(nn.Module):\n    \"\"\"Varifocal loss by Zhang et al. https://arxiv.org/abs/2008.13367.\"\"\"\n\n    def __init__(self):\n        \"\"\"Initialize the VarifocalLoss class.\"\"\"\n        super().__init__()\n\n    def forward(self, pred_score, gt_score, label, alpha=0.75, gamma=2.0):\n        \"\"\"Computes varfocal loss.\"\"\"\n        weight = alpha * pred_score.sigmoid().pow(gamma) * (1 - label) + gt_score * label\n        with torch.cuda.amp.autocast(enabled=False):\n            loss = (F.binary_cross_entropy_with_logits(pred_score.float(), gt_score.float(), reduction='none') *\n                    weight).sum()\n        return loss\n\n\nclass BboxLoss(nn.Module):\n\n    def __init__(self, reg_max, use_dfl=False):\n        \"\"\"Initialize the BboxLoss module with regularization maximum and DFL settings.\"\"\"\n        super().__init__()\n        self.reg_max = reg_max\n        self.use_dfl = use_dfl\n\n    def forward(self, pred_dist, pred_bboxes, anchor_points, target_bboxes, target_scores, target_scores_sum, fg_mask):\n        \"\"\"IoU loss.\"\"\"\n        weight = target_scores.sum(-1)[fg_mask].unsqueeze(-1)\n        iou = bbox_iou(pred_bboxes[fg_mask], target_bboxes[fg_mask], xywh=False, CIoU=True)\n        loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum\n\n        # DFL loss\n        if self.use_dfl:\n            target_ltrb = bbox2dist(anchor_points, target_bboxes, self.reg_max)\n            loss_dfl = self._df_loss(pred_dist[fg_mask].view(-1, self.reg_max + 1), target_ltrb[fg_mask]) * weight\n            loss_dfl = loss_dfl.sum() / target_scores_sum\n        else:\n            loss_dfl = torch.tensor(0.0).to(pred_dist.device)\n\n        return loss_iou, loss_dfl\n\n    @staticmethod\n    def _df_loss(pred_dist, target):\n        \"\"\"Return sum of left and right DFL losses.\"\"\"\n        # Distribution Focal Loss (DFL) proposed in Generalized Focal Loss https://ieeexplore.ieee.org/document/9792391\n        tl = target.long()  # target left\n        tr = tl + 1  # target right\n        wl = tr - target  # weight left\n        wr = 1 - wl  # weight right\n        return (F.cross_entropy(pred_dist, tl.view(-1), reduction='none').view(tl.shape) * wl +\n                F.cross_entropy(pred_dist, tr.view(-1), reduction='none').view(tl.shape) * wr).mean(-1, keepdim=True)\n\n\nclass KeypointLoss(nn.Module):\n\n    def __init__(self, sigmas) -> None:\n        super().__init__()\n        self.sigmas = sigmas\n\n    def forward(self, pred_kpts, gt_kpts, kpt_mask, area):\n        \"\"\"Calculates keypoint loss factor and Euclidean distance loss for predicted and actual keypoints.\"\"\"\n        d = (pred_kpts[..., 0] - gt_kpts[..., 0]) ** 2 + (pred_kpts[..., 1] - gt_kpts[..., 1]) ** 2\n        kpt_loss_factor = (torch.sum(kpt_mask != 0) + torch.sum(kpt_mask == 0)) / (torch.sum(kpt_mask != 0) + 1e-9)\n        # e = d / (2 * (area * self.sigmas) ** 2 + 1e-9)  # from formula\n        e = d / (2 * self.sigmas) ** 2 / (area + 1e-9) / 2  # from cocoeval\n        return kpt_loss_factor * ((1 - torch.exp(-e)) * kpt_mask).mean()\n"
  },
  {
    "path": "ultralytics/yolo/utils/metrics.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\"\"\"\nModel validation metrics\n\"\"\"\nimport math\nimport warnings\nfrom pathlib import Path\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom ultralytics.yolo.utils import LOGGER, SimpleClass, TryExcept, plt_settings\n\nOKS_SIGMA = np.array([.26, .25, .25, .35, .35, .79, .79, .72, .72, .62, .62, 1.07, 1.07, .87, .87, .89, .89]) / 10.0\n\n\n# Boxes\ndef box_area(box):\n    \"\"\"Return box area, where box shape is xyxy(4,n).\"\"\"\n    return (box[2] - box[0]) * (box[3] - box[1])\n\n\ndef bbox_ioa(box1, box2, eps=1e-7):\n    \"\"\"\n    Calculate the intersection over box2 area given box1 and box2. Boxes are in x1y1x2y2 format.\n\n    Args:\n        box1 (np.array): A numpy array of shape (n, 4) representing n bounding boxes.\n        box2 (np.array): A numpy array of shape (m, 4) representing m bounding boxes.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (np.array): A numpy array of shape (n, m) representing the intersection over box2 area.\n    \"\"\"\n\n    # Get the coordinates of bounding boxes\n    b1_x1, b1_y1, b1_x2, b1_y2 = box1.T\n    b2_x1, b2_y1, b2_x2, b2_y2 = box2.T\n\n    # Intersection area\n    inter_area = (np.minimum(b1_x2[:, None], b2_x2) - np.maximum(b1_x1[:, None], b2_x1)).clip(0) * \\\n                 (np.minimum(b1_y2[:, None], b2_y2) - np.maximum(b1_y1[:, None], b2_y1)).clip(0)\n\n    # box2 area\n    box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps\n\n    # Intersection over box2 area\n    return inter_area / box2_area\n\n\ndef box_iou(box1, box2, eps=1e-7):\n    \"\"\"\n    Calculate intersection-over-union (IoU) of boxes.\n    Both sets of boxes are expected to be in (x1, y1, x2, y2) format.\n    Based on https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py\n\n    Args:\n        box1 (torch.Tensor): A tensor of shape (N, 4) representing N bounding boxes.\n        box2 (torch.Tensor): A tensor of shape (M, 4) representing M bounding boxes.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (torch.Tensor): An NxM tensor containing the pairwise IoU values for every element in box1 and box2.\n    \"\"\"\n\n    # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)\n    (a1, a2), (b1, b2) = box1.unsqueeze(1).chunk(2, 2), box2.unsqueeze(0).chunk(2, 2)\n    inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp(0).prod(2)\n\n    # IoU = inter / (area1 + area2 - inter)\n    return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)\n\n\ndef bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):\n    \"\"\"\n    Calculate Intersection over Union (IoU) of box1(1, 4) to box2(n, 4).\n\n    Args:\n        box1 (torch.Tensor): A tensor representing a single bounding box with shape (1, 4).\n        box2 (torch.Tensor): A tensor representing n bounding boxes with shape (n, 4).\n        xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in\n                               (x1, y1, x2, y2) format. Defaults to True.\n        GIoU (bool, optional): If True, calculate Generalized IoU. Defaults to False.\n        DIoU (bool, optional): If True, calculate Distance IoU. Defaults to False.\n        CIoU (bool, optional): If True, calculate Complete IoU. Defaults to False.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.\n    \"\"\"\n\n    # Get the coordinates of bounding boxes\n    if xywh:  # transform from xywh to xyxy\n        (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)\n        w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2\n        b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_\n        b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_\n    else:  # x1, y1, x2, y2 = box1\n        b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)\n        b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)\n        w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps\n        w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps\n\n    # Intersection area\n    inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp(0) * \\\n            (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp(0)\n\n    # Union Area\n    union = w1 * h1 + w2 * h2 - inter + eps\n\n    # IoU\n    iou = inter / union\n    if CIoU or DIoU or GIoU:\n        cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1)  # convex (smallest enclosing box) width\n        ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1)  # convex height\n        if CIoU or DIoU:  # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1\n            c2 = cw ** 2 + ch ** 2 + eps  # convex diagonal squared\n            rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4  # center dist ** 2\n            if CIoU:  # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47\n                v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)\n                with torch.no_grad():\n                    alpha = v / (v - iou + (1 + eps))\n                return iou - (rho2 / c2 + v * alpha)  # CIoU\n            return iou - rho2 / c2  # DIoU\n        c_area = cw * ch + eps  # convex area\n        return iou - (c_area - union) / c_area  # GIoU https://arxiv.org/pdf/1902.09630.pdf\n    return iou  # IoU\n\n\ndef mask_iou(mask1, mask2, eps=1e-7):\n    \"\"\"\n    Calculate masks IoU.\n\n    Args:\n        mask1 (torch.Tensor): A tensor of shape (N, n) where N is the number of ground truth objects and n is the\n                        product of image width and height.\n        mask2 (torch.Tensor): A tensor of shape (M, n) where M is the number of predicted objects and n is the\n                        product of image width and height.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (torch.Tensor): A tensor of shape (N, M) representing masks IoU.\n    \"\"\"\n    intersection = torch.matmul(mask1, mask2.t()).clamp(0)\n    union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection  # (area1 + area2) - intersection\n    return intersection / (union + eps)\n\n\ndef kpt_iou(kpt1, kpt2, area, sigma, eps=1e-7):\n    \"\"\"\n    Calculate Object Keypoint Similarity (OKS).\n\n    Args:\n        kpt1 (torch.Tensor): A tensor of shape (N, 17, 3) representing ground truth keypoints.\n        kpt2 (torch.Tensor): A tensor of shape (M, 17, 3) representing predicted keypoints.\n        area (torch.Tensor): A tensor of shape (N,) representing areas from ground truth.\n        sigma (list): A list containing 17 values representing keypoint scales.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.\n\n    Returns:\n        (torch.Tensor): A tensor of shape (N, M) representing keypoint similarities.\n    \"\"\"\n    d = (kpt1[:, None, :, 0] - kpt2[..., 0]) ** 2 + (kpt1[:, None, :, 1] - kpt2[..., 1]) ** 2  # (N, M, 17)\n    sigma = torch.tensor(sigma, device=kpt1.device, dtype=kpt1.dtype)  # (17, )\n    kpt_mask = kpt1[..., 2] != 0  # (N, 17)\n    e = d / (2 * sigma) ** 2 / (area[:, None, None] + eps) / 2  # from cocoeval\n    # e = d / ((area[None, :, None] + eps) * sigma) ** 2 / 2  # from formula\n    return (torch.exp(-e) * kpt_mask[:, None]).sum(-1) / (kpt_mask.sum(-1)[:, None] + eps)\n\n\ndef smooth_BCE(eps=0.1):  # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441\n    # return positive, negative label smoothing BCE targets\n    return 1.0 - 0.5 * eps, 0.5 * eps\n\n\n# Losses\nclass FocalLoss(nn.Module):\n    \"\"\"Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5).\"\"\"\n\n    def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):\n        \"\"\"Initialize FocalLoss object with given loss function and hyperparameters.\"\"\"\n        super().__init__()\n        self.loss_fcn = loss_fcn  # must be nn.BCEWithLogitsLoss()\n        self.gamma = gamma\n        self.alpha = alpha\n        self.reduction = loss_fcn.reduction\n        self.loss_fcn.reduction = 'none'  # required to apply FL to each element\n\n    def forward(self, pred, true):\n        \"\"\"Calculates and updates confusion matrix for object detection/classification tasks.\"\"\"\n        loss = self.loss_fcn(pred, true)\n        # p_t = torch.exp(-loss)\n        # loss *= self.alpha * (1.000001 - p_t) ** self.gamma  # non-zero power for gradient stability\n\n        # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py\n        pred_prob = torch.sigmoid(pred)  # prob from logits\n        p_t = true * pred_prob + (1 - true) * (1 - pred_prob)\n        alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)\n        modulating_factor = (1.0 - p_t) ** self.gamma\n        loss *= alpha_factor * modulating_factor\n\n        if self.reduction == 'mean':\n            return loss.mean()\n        elif self.reduction == 'sum':\n            return loss.sum()\n        else:  # 'None'\n            return loss\n\n\nclass ConfusionMatrix:\n    \"\"\"\n    A class for calculating and updating a confusion matrix for object detection and classification tasks.\n\n    Attributes:\n        task (str): The type of task, either 'detect' or 'classify'.\n        matrix (np.array): The confusion matrix, with dimensions depending on the task.\n        nc (int): The number of classes.\n        conf (float): The confidence threshold for detections.\n        iou_thres (float): The Intersection over Union threshold.\n    \"\"\"\n\n    def __init__(self, nc, conf=0.25, iou_thres=0.45, task='detect'):\n        \"\"\"Initialize attributes for the YOLO model.\"\"\"\n        self.task = task\n        self.matrix = np.zeros((nc + 1, nc + 1)) if self.task == 'detect' else np.zeros((nc, nc))\n        self.nc = nc  # number of classes\n        self.conf = conf\n        self.iou_thres = iou_thres\n\n    def process_cls_preds(self, preds, targets):\n        \"\"\"\n        Update confusion matrix for classification task\n\n        Args:\n            preds (Array[N, min(nc,5)]): Predicted class labels.\n            targets (Array[N, 1]): Ground truth class labels.\n        \"\"\"\n        preds, targets = torch.cat(preds)[:, 0], torch.cat(targets)\n        for p, t in zip(preds.cpu().numpy(), targets.cpu().numpy()):\n            self.matrix[t][p] += 1\n\n    def process_batch(self, detections, labels):\n        \"\"\"\n        Update confusion matrix for object detection task.\n\n        Args:\n            detections (Array[N, 6]): Detected bounding boxes and their associated information.\n                                      Each row should contain (x1, y1, x2, y2, conf, class).\n            labels (Array[M, 5]): Ground truth bounding boxes and their associated class labels.\n                                  Each row should contain (class, x1, y1, x2, y2).\n        \"\"\"\n        if detections is None:\n            gt_classes = labels.int()\n            for gc in gt_classes:\n                self.matrix[self.nc, gc] += 1  # background FN\n            return\n\n        detections = detections[detections[:, 4] > self.conf]\n        gt_classes = labels[:, 0].int()\n        detection_classes = detections[:, 5].int()\n        iou = box_iou(labels[:, 1:], detections[:, :4])\n\n        x = torch.where(iou > self.iou_thres)\n        if x[0].shape[0]:\n            matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()\n            if x[0].shape[0] > 1:\n                matches = matches[matches[:, 2].argsort()[::-1]]\n                matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                matches = matches[matches[:, 2].argsort()[::-1]]\n                matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n        else:\n            matches = np.zeros((0, 3))\n\n        n = matches.shape[0] > 0\n        m0, m1, _ = matches.transpose().astype(int)\n        for i, gc in enumerate(gt_classes):\n            j = m0 == i\n            if n and sum(j) == 1:\n                self.matrix[detection_classes[m1[j]], gc] += 1  # correct\n            else:\n                self.matrix[self.nc, gc] += 1  # true background\n\n        if n:\n            for i, dc in enumerate(detection_classes):\n                if not any(m1 == i):\n                    self.matrix[dc, self.nc] += 1  # predicted background\n\n    def matrix(self):\n        \"\"\"Returns the confusion matrix.\"\"\"\n        return self.matrix\n\n    def tp_fp(self):\n        \"\"\"Returns true positives and false positives.\"\"\"\n        tp = self.matrix.diagonal()  # true positives\n        fp = self.matrix.sum(1) - tp  # false positives\n        # fn = self.matrix.sum(0) - tp  # false negatives (missed detections)\n        return (tp[:-1], fp[:-1]) if self.task == 'detect' else (tp, fp)  # remove background class if task=detect\n\n    @TryExcept('WARNING ⚠️ ConfusionMatrix plot failure')\n    @plt_settings()\n    def plot(self, normalize=True, save_dir='', names=(), on_plot=None):\n        \"\"\"\n        Plot the confusion matrix using seaborn and save it to a file.\n\n        Args:\n            normalize (bool): Whether to normalize the confusion matrix.\n            save_dir (str): Directory where the plot will be saved.\n            names (tuple): Names of classes, used as labels on the plot.\n            on_plot (func): An optional callback to pass plots path and data when they are rendered.\n        \"\"\"\n        import seaborn as sn\n\n        array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1)  # normalize columns\n        array[array < 0.005] = np.nan  # don't annotate (would appear as 0.00)\n\n        fig, ax = plt.subplots(1, 1, figsize=(12, 9), tight_layout=True)\n        nc, nn = self.nc, len(names)  # number of classes, names\n        sn.set(font_scale=1.0 if nc < 50 else 0.8)  # for label size\n        labels = (0 < nn < 99) and (nn == nc)  # apply names to ticklabels\n        ticklabels = (list(names) + ['background']) if labels else 'auto'\n        with warnings.catch_warnings():\n            warnings.simplefilter('ignore')  # suppress empty matrix RuntimeWarning: All-NaN slice encountered\n            sn.heatmap(array,\n                       ax=ax,\n                       annot=nc < 30,\n                       annot_kws={\n                           'size': 8},\n                       cmap='Blues',\n                       fmt='.2f' if normalize else '.0f',\n                       square=True,\n                       vmin=0.0,\n                       xticklabels=ticklabels,\n                       yticklabels=ticklabels).set_facecolor((1, 1, 1))\n        title = 'Confusion Matrix' + ' Normalized' * normalize\n        ax.set_xlabel('True')\n        ax.set_ylabel('Predicted')\n        ax.set_title(title)\n        plot_fname = Path(save_dir) / f'{title.lower().replace(\" \", \"_\")}.png'\n        fig.savefig(plot_fname, dpi=250)\n        plt.close(fig)\n        if on_plot:\n            on_plot(plot_fname)\n\n    def print(self):\n        \"\"\"\n        Print the confusion matrix to the console.\n        \"\"\"\n        for i in range(self.nc + 1):\n            LOGGER.info(' '.join(map(str, self.matrix[i])))\n\ndef smooth(y, f=0.05):\n    \"\"\"Box filter of fraction f.\"\"\"\n    nf = round(len(y) * f * 2) // 2 + 1  # number of filter elements (must be odd)\n    p = np.ones(nf // 2)  # ones padding\n    yp = np.concatenate((p * y[0], y, p * y[-1]), 0)  # y padded\n    return np.convolve(yp, np.ones(nf) / nf, mode='valid')  # y-smoothed\n\n\n@plt_settings()\ndef plot_pr_curve(px, py, ap, save_dir=Path('pr_curve.png'), names=(), on_plot=None):\n    \"\"\"Plots a precision-recall curve.\"\"\"\n    fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)\n    py = np.stack(py, axis=1)\n\n    if 0 < len(names) < 21:  # display per-class legend if < 21 classes\n        for i, y in enumerate(py.T):\n            ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}')  # plot(recall, precision)\n    else:\n        ax.plot(px, py, linewidth=1, color='grey')  # plot(recall, precision)\n\n    ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())\n    ax.set_xlabel('Recall')\n    ax.set_ylabel('Precision')\n    ax.set_xlim(0, 1)\n    ax.set_ylim(0, 1)\n    ax.legend(bbox_to_anchor=(1.04, 1), loc='upper left')\n    ax.set_title('Precision-Recall Curve')\n    fig.savefig(save_dir, dpi=250)\n    plt.close(fig)\n    if on_plot:\n        on_plot(save_dir)\n\n\n@plt_settings()\ndef plot_mc_curve(px, py, save_dir=Path('mc_curve.png'), names=(), xlabel='Confidence', ylabel='Metric', on_plot=None):\n    \"\"\"Plots a metric-confidence curve.\"\"\"\n    fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)\n\n    if 0 < len(names) < 21:  # display per-class legend if < 21 classes\n        for i, y in enumerate(py):\n            ax.plot(px, y, linewidth=1, label=f'{names[i]}')  # plot(confidence, metric)\n    else:\n        ax.plot(px, py.T, linewidth=1, color='grey')  # plot(confidence, metric)\n\n    y = smooth(py.mean(0), 0.05)\n    ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')\n    ax.set_xlabel(xlabel)\n    ax.set_ylabel(ylabel)\n    ax.set_xlim(0, 1)\n    ax.set_ylim(0, 1)\n    ax.legend(bbox_to_anchor=(1.04, 1), loc='upper left')\n    ax.set_title(f'{ylabel}-Confidence Curve')\n    fig.savefig(save_dir, dpi=250)\n    plt.close(fig)\n    if on_plot:\n        on_plot(save_dir)\n\n\ndef compute_ap(recall, precision):\n    \"\"\"\n    Compute the average precision (AP) given the recall and precision curves.\n\n    Arguments:\n        recall (list): The recall curve.\n        precision (list): The precision curve.\n\n    Returns:\n        (float): Average precision.\n        (np.ndarray): Precision envelope curve.\n        (np.ndarray): Modified recall curve with sentinel values added at the beginning and end.\n    \"\"\"\n\n    # Append sentinel values to beginning and end\n    mrec = np.concatenate(([0.0], recall, [1.0]))\n    mpre = np.concatenate(([1.0], precision, [0.0]))\n\n    # Compute the precision envelope\n    mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))\n\n    # Integrate area under curve\n    method = 'interp'  # methods: 'continuous', 'interp'\n    if method == 'interp':\n        x = np.linspace(0, 1, 101)  # 101-point interp (COCO)\n        ap = np.trapz(np.interp(x, mrec, mpre), x)  # integrate\n    else:  # 'continuous'\n        i = np.where(mrec[1:] != mrec[:-1])[0]  # points where x-axis (recall) changes\n        ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])  # area under curve\n\n    return ap, mpre, mrec\n\n\ndef ap_per_class(tp,\n                 conf,\n                 pred_cls,\n                 target_cls,\n                 plot=False,\n                 on_plot=None,\n                 save_dir=Path(),\n                 names=(),\n                 eps=1e-16,\n                 prefix=''):\n    \"\"\"\n    Computes the average precision per class for object detection evaluation.\n\n    Args:\n        tp (np.ndarray): Binary array indicating whether the detection is correct (True) or not (False).\n        conf (np.ndarray): Array of confidence scores of the detections.\n        pred_cls (np.ndarray): Array of predicted classes of the detections.\n        target_cls (np.ndarray): Array of true classes of the detections.\n        plot (bool, optional): Whether to plot PR curves or not. Defaults to False.\n        on_plot (func, optional): A callback to pass plots path and data when they are rendered. Defaults to None.\n        save_dir (Path, optional): Directory to save the PR curves. Defaults to an empty path.\n        names (tuple, optional): Tuple of class names to plot PR curves. Defaults to an empty tuple.\n        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-16.\n        prefix (str, optional): A prefix string for saving the plot files. Defaults to an empty string.\n\n    Returns:\n        (tuple): A tuple of six arrays and one array of unique classes, where:\n            tp (np.ndarray): True positive counts for each class.\n            fp (np.ndarray): False positive counts for each class.\n            p (np.ndarray): Precision values at each confidence threshold.\n            r (np.ndarray): Recall values at each confidence threshold.\n            f1 (np.ndarray): F1-score values at each confidence threshold.\n            ap (np.ndarray): Average precision for each class at different IoU thresholds.\n            unique_classes (np.ndarray): An array of unique classes that have data.\n\n    \"\"\"\n\n    # Sort by objectness\n    i = np.argsort(-conf)\n    tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]\n\n    # Find unique classes\n    unique_classes, nt = np.unique(target_cls, return_counts=True)\n    nc = unique_classes.shape[0]  # number of classes, number of detections\n\n    # Create Precision-Recall curve and compute AP for each class\n    px, py = np.linspace(0, 1, 1000), []  # for plotting\n    ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))\n    for ci, c in enumerate(unique_classes):\n        i = pred_cls == c\n        n_l = nt[ci]  # number of labels\n        n_p = i.sum()  # number of predictions\n        if n_p == 0 or n_l == 0:\n            continue\n\n        # Accumulate FPs and TPs\n        fpc = (1 - tp[i]).cumsum(0)\n        tpc = tp[i].cumsum(0)\n\n        # Recall\n        recall = tpc / (n_l + eps)  # recall curve\n        r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0)  # negative x, xp because xp decreases\n\n        # Precision\n        precision = tpc / (tpc + fpc)  # precision curve\n        p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1)  # p at pr_score\n\n        # AP from recall-precision curve\n        for j in range(tp.shape[1]):\n            ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])\n            if plot and j == 0:\n                py.append(np.interp(px, mrec, mpre))  # precision at mAP@0.5\n\n    # Compute F1 (harmonic mean of precision and recall)\n    f1 = 2 * p * r / (p + r + eps)\n    names = [v for k, v in names.items() if k in unique_classes]  # list: only classes that have data\n    names = dict(enumerate(names))  # to dict\n    if plot:\n        plot_pr_curve(px, py, ap, save_dir / f'{prefix}PR_curve.png', names, on_plot=on_plot)\n        plot_mc_curve(px, f1, save_dir / f'{prefix}F1_curve.png', names, ylabel='F1', on_plot=on_plot)\n        plot_mc_curve(px, p, save_dir / f'{prefix}P_curve.png', names, ylabel='Precision', on_plot=on_plot)\n        plot_mc_curve(px, r, save_dir / f'{prefix}R_curve.png', names, ylabel='Recall', on_plot=on_plot)\n\n    # i = smooth(f1.mean(0), 0.1).argmax()  # max F1 index\n    i = r.mean(0).argmax()  ###### Jiayuan This is follow the Yolop setting. https://github.com/hustvl/YOLOP/blob/main/lib/core/evaluate.py#L72C5-L72C27\n    p, r, f1 = p[:, i], r[:, i], f1[:, i]\n    tp = (r * nt).round()  # true positives\n    fp = (tp / (p + eps) - tp).round()  # false positives\n    return tp, fp, p, r, f1, ap, unique_classes.astype(int)\n\n###### Jiayuan\nclass SegmentationMetric(object):\n    '''\n    imgLabel [batch_size, height(144), width(256)]\n    confusionMatrix [[0(TN),1(FP)],\n                     [2(FN),3(TP)]]\n    '''\n\n    def __init__(self, numClass):\n        self.numClass = numClass\n        self.confusionMatrix = np.zeros((self.numClass,) * 2)\n\n    def pixelAccuracy(self):\n        # return all class overall pixel accuracy\n        # acc = (TP + TN) / (TP + TN + FP + TN)\n        acc = np.diag(self.confusionMatrix).sum() / self.confusionMatrix.sum()\n        return acc\n\n    # def lineAccuracy(self):\n    #     Acc = np.diag(self.confusionMatrix) / (self.confusionMatrix.sum(axis=1) + 1e-12)\n    #     return Acc[1]\n\n    def _get_values(self):\n        # Extracting values based on the provided structure\n        tn = self.confusionMatrix[0, 0]\n        fp = self.confusionMatrix[0, 1]\n        fn = self.confusionMatrix[1, 0]\n        tp = self.confusionMatrix[1, 1]\n        return tp, fp, fn, tn\n\n    def sensitivity(self):\n        tp, fp, fn, tn = self._get_values()\n        return tp / (tp + fn + 1e-12)\n\n    def specificity(self):\n        tp, fp, fn, tn = self._get_values()\n        return tn / (tn + fp + 1e-12)\n\n    def lineAccuracy(self):\n        test = (self.sensitivity() + self.specificity()) / 2\n        return test\n    def classPixelAccuracy(self):\n        # return each category pixel accuracy(A more accurate way to call it precision)\n        # acc = (TP) / TP + FP\n        classAcc = np.diag(self.confusionMatrix) / (self.confusionMatrix.sum(axis=0) + 1e-12)\n        return classAcc\n\n    def meanPixelAccuracy(self):\n        classAcc = self.classPixelAccuracy()\n        meanAcc = np.nanmean(classAcc)\n        return meanAcc\n\n    def meanIntersectionOverUnion(self):\n        # Intersection = TP Union = TP + FP + FN\n        # IoU = TP / (TP + FP + FN)\n        epsilon = 1e-9\n        intersection = np.diag(self.confusionMatrix)\n        union = np.sum(self.confusionMatrix, axis=1) + np.sum(self.confusionMatrix, axis=0) - np.diag(\n            self.confusionMatrix)\n        IoU = intersection / (union+epsilon)\n        IoU[np.isnan(IoU)] = 0\n        mIoU = np.nanmean(IoU)\n        return mIoU\n\n    def IntersectionOverUnion(self):\n        epsilon = 1e-9\n        intersection = np.diag(self.confusionMatrix)\n        union = np.sum(self.confusionMatrix, axis=1) + np.sum(self.confusionMatrix, axis=0) - np.diag(self.confusionMatrix)\n        IoU = intersection / (union+epsilon)\n        IoU[np.isnan(IoU)] = 0\n        return IoU[1]\n\n    def genConfusionMatrix(self, imgPredict, imgLabel):\n        # remove classes from unlabeled pixels in gt image and predict\n        # print(imgLabel.shape)\n        mask = (imgLabel >= 0) & (imgLabel < self.numClass)\n        label = self.numClass * imgLabel[mask] + imgPredict[mask]\n        count = np.bincount(label, minlength=self.numClass ** 2)\n        confusionMatrix = count.reshape(self.numClass, self.numClass)\n        return confusionMatrix\n\n    def Frequency_Weighted_Intersection_over_Union(self):\n        # FWIOU =     [(TP+FN)/(TP+FP+TN+FN)] *[TP / (TP + FP + FN)]\n        freq = np.sum(self.confusionMatrix, axis=1) / np.sum(self.confusionMatrix)\n        iu = np.diag(self.confusionMatrix) / (\n                np.sum(self.confusionMatrix, axis=1) + np.sum(self.confusionMatrix, axis=0) -\n                np.diag(self.confusionMatrix))\n        FWIoU = (freq[freq > 0] * iu[freq > 0]).sum()\n        return FWIoU\n\n    def addBatch(self, imgPredict, imgLabel):\n        assert imgPredict.shape == imgLabel.shape\n        # import numpy as np\n        #\n        # # Dummy data for demonstration\n        #\n        # # Plotting and saving imgPredict\n        # plt.imshow(imgPredict[0], cmap='gray')\n        # plt.title('imgPredict')\n        # plt.axis('off')\n        # plt.savefig('/home/jiayuan/ultralytics-main/ultralytics/runs/imgPredict.png')\n        #\n        #\n        # # Plotting and saving imgLabel\n        # plt.imshow(imgLabel[0], cmap='gray')\n        # plt.title('imgLabel')\n        # plt.axis('off')\n        # plt.savefig('/home/jiayuan/ultralytics-main/ultralytics/runs/imgLabel.png')\n\n\n\n        self.confusionMatrix += self.genConfusionMatrix(imgPredict, imgLabel)\n\n    def reset(self):\n        self.confusionMatrix = np.zeros((self.numClass, self.numClass))\n\nclass AverageMeter(object):\n    \"\"\"Computes and stores the average and current value\"\"\"\n    def __init__(self):\n        self.reset()\n\n    def reset(self):\n        self.val = 0\n        self.avg = 0\n        self.sum = 0\n        self.count = 0\n\n    def update(self, val, n=1):\n        self.val = val\n        self.sum += val * n\n        self.count += n\n        self.avg = self.sum / self.count if self.count != 0 else 0\n######\nclass Metric(SimpleClass):\n    \"\"\"\n        Class for computing evaluation metrics for YOLOv8 model.\n\n        Attributes:\n            p (list): Precision for each class. Shape: (nc,).\n            r (list): Recall for each class. Shape: (nc,).\n            f1 (list): F1 score for each class. Shape: (nc,).\n            all_ap (list): AP scores for all classes and all IoU thresholds. Shape: (nc, 10).\n            ap_class_index (list): Index of class for each AP score. Shape: (nc,).\n            nc (int): Number of classes.\n\n        Methods:\n            ap50(): AP at IoU threshold of 0.5 for all classes. Returns: List of AP scores. Shape: (nc,) or [].\n            ap(): AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: List of AP scores. Shape: (nc,) or [].\n            mp(): Mean precision of all classes. Returns: Float.\n            mr(): Mean recall of all classes. Returns: Float.\n            map50(): Mean AP at IoU threshold of 0.5 for all classes. Returns: Float.\n            map75(): Mean AP at IoU threshold of 0.75 for all classes. Returns: Float.\n            map(): Mean AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: Float.\n            mean_results(): Mean of results, returns mp, mr, map50, map.\n            class_result(i): Class-aware result, returns p[i], r[i], ap50[i], ap[i].\n            maps(): mAP of each class. Returns: Array of mAP scores, shape: (nc,).\n            fitness(): Model fitness as a weighted combination of metrics. Returns: Float.\n            update(results): Update metric attributes with new evaluation results.\n\n        \"\"\"\n\n    def __init__(self) -> None:\n        self.p = []  # (nc, )\n        self.r = []  # (nc, )\n        self.f1 = []  # (nc, )\n        self.all_ap = []  # (nc, 10)\n        self.ap_class_index = []  # (nc, )\n        self.nc = 0\n\n    @property\n    def ap50(self):\n        \"\"\"\n        Returns the Average Precision (AP) at an IoU threshold of 0.5 for all classes.\n\n        Returns:\n            (np.ndarray, list): Array of shape (nc,) with AP50 values per class, or an empty list if not available.\n        \"\"\"\n        return self.all_ap[:, 0] if len(self.all_ap) else []\n\n    @property\n    def ap(self):\n        \"\"\"\n        Returns the Average Precision (AP) at an IoU threshold of 0.5-0.95 for all classes.\n\n        Returns:\n            (np.ndarray, list): Array of shape (nc,) with AP50-95 values per class, or an empty list if not available.\n        \"\"\"\n        return self.all_ap.mean(1) if len(self.all_ap) else []\n\n    @property\n    def mp(self):\n        \"\"\"\n        Returns the Mean Precision of all classes.\n\n        Returns:\n            (float): The mean precision of all classes.\n        \"\"\"\n        return self.p.mean() if len(self.p) else 0.0\n\n    @property\n    def mr(self):\n        \"\"\"\n        Returns the Mean Recall of all classes.\n\n        Returns:\n            (float): The mean recall of all classes.\n        \"\"\"\n        return self.r.mean() if len(self.r) else 0.0\n\n    @property\n    def map50(self):\n        \"\"\"\n        Returns the mean Average Precision (mAP) at an IoU threshold of 0.5.\n\n        Returns:\n            (float): The mAP50 at an IoU threshold of 0.5.\n        \"\"\"\n        return self.all_ap[:, 0].mean() if len(self.all_ap) else 0.0\n\n    @property\n    def map75(self):\n        \"\"\"\n        Returns the mean Average Precision (mAP) at an IoU threshold of 0.75.\n\n        Returns:\n            (float): The mAP50 at an IoU threshold of 0.75.\n        \"\"\"\n        return self.all_ap[:, 5].mean() if len(self.all_ap) else 0.0\n\n    @property\n    def map(self):\n        \"\"\"\n        Returns the mean Average Precision (mAP) over IoU thresholds of 0.5 - 0.95 in steps of 0.05.\n\n        Returns:\n            (float): The mAP over IoU thresholds of 0.5 - 0.95 in steps of 0.05.\n        \"\"\"\n        return self.all_ap.mean() if len(self.all_ap) else 0.0\n\n    def mean_results(self):\n        \"\"\"Mean of results, return mp, mr, map50, map.\"\"\"\n        return [self.mp, self.mr, self.map50, self.map]\n\n    def class_result(self, i):\n        \"\"\"class-aware result, return p[i], r[i], ap50[i], ap[i].\"\"\"\n        ######Jiayuan\n        try:\n            a = self.p[i]\n        except:\n            a = 0\n        try:\n            b = self.r[i]\n        except:\n            b = 0\n        try:\n            c = self.ap50[i]\n        except:\n            c = 0\n        try:\n            d = self.ap[i]\n        except:\n            d = 0\n        return a, b, c, d\n        ######\n    @property\n    def maps(self):\n        \"\"\"mAP of each class.\"\"\"\n        maps = np.zeros(self.nc) + self.map\n        for i, c in enumerate(self.ap_class_index):\n            maps[c] = self.ap[i]\n        return maps\n\n    def fitness(self):\n        \"\"\"Model fitness as a weighted combination of metrics.\"\"\"\n        w = [0.0, 0.0, 0.1, 0.9]  # weights for [P, R, mAP@0.5, mAP@0.5:0.95]\n        return (np.array(self.mean_results()) * w).sum()\n\n    def update(self, results):\n        \"\"\"\n        Args:\n            results (tuple): A tuple of (p, r, ap, f1, ap_class)\n        \"\"\"\n        self.p, self.r, self.f1, self.all_ap, self.ap_class_index = results\n\n\nclass DetMetrics(SimpleClass):\n    \"\"\"\n    This class is a utility class for computing detection metrics such as precision, recall, and mean average precision\n    (mAP) of an object detection model.\n\n    Args:\n        save_dir (Path): A path to the directory where the output plots will be saved. Defaults to current directory.\n        plot (bool): A flag that indicates whether to plot precision-recall curves for each class. Defaults to False.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.\n        names (tuple of str): A tuple of strings that represents the names of the classes. Defaults to an empty tuple.\n\n    Attributes:\n        save_dir (Path): A path to the directory where the output plots will be saved.\n        plot (bool): A flag that indicates whether to plot the precision-recall curves for each class.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered.\n        names (tuple of str): A tuple of strings that represents the names of the classes.\n        box (Metric): An instance of the Metric class for storing the results of the detection metrics.\n        speed (dict): A dictionary for storing the execution time of different parts of the detection process.\n\n    Methods:\n        process(tp, conf, pred_cls, target_cls): Updates the metric results with the latest batch of predictions.\n        keys: Returns a list of keys for accessing the computed detection metrics.\n        mean_results: Returns a list of mean values for the computed detection metrics.\n        class_result(i): Returns a list of values for the computed detection metrics for a specific class.\n        maps: Returns a dictionary of mean average precision (mAP) values for different IoU thresholds.\n        fitness: Computes the fitness score based on the computed detection metrics.\n        ap_class_index: Returns a list of class indices sorted by their average precision (AP) values.\n        results_dict: Returns a dictionary that maps detection metric keys to their computed values.\n    \"\"\"\n\n    def __init__(self, save_dir=Path('.'), plot=False, on_plot=None, names=()) -> None:\n        self.save_dir = save_dir\n        self.plot = plot\n        self.on_plot = on_plot\n        self.names = names\n        self.box = Metric()\n        self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}\n\n    def process(self, tp, conf, pred_cls, target_cls):\n        \"\"\"Process predicted results for object detection and update metrics.\"\"\"\n        results = ap_per_class(tp, conf, pred_cls, target_cls, plot=self.plot, save_dir=self.save_dir,\n                               names=self.names)[2:]\n        self.box.nc = len(self.names)\n        self.box.update(results)\n\n    @property\n    def keys(self):\n        \"\"\"Returns a list of keys for accessing specific metrics.\"\"\"\n        return ['metrics/precision(B)', 'metrics/recall(B)', 'metrics/mAP50(B)', 'metrics/mAP50-95(B)']\n\n    def mean_results(self):\n        \"\"\"Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.\"\"\"\n        return self.box.mean_results()\n\n    def class_result(self, i):\n        \"\"\"Return the result of evaluating the performance of an object detection model on a specific class.\"\"\"\n        return self.box.class_result(i)\n\n    @property\n    def maps(self):\n        \"\"\"Returns mean Average Precision (mAP) scores per class.\"\"\"\n        return self.box.maps\n\n    @property\n    def fitness(self):\n        \"\"\"Returns the fitness of box object.\"\"\"\n        return self.box.fitness()\n\n    @property\n    def ap_class_index(self):\n        \"\"\"Returns the average precision index per class.\"\"\"\n        return self.box.ap_class_index\n\n    @property\n    def results_dict(self):\n        \"\"\"Returns dictionary of computed performance metrics and statistics.\"\"\"\n        return dict(zip(self.keys + ['fitness'], self.mean_results() + [self.fitness]))\n\n\nclass SegmentMetrics(SimpleClass):\n    \"\"\"\n    Calculates and aggregates detection and segmentation metrics over a given set of classes.\n\n    Args:\n        save_dir (Path): Path to the directory where the output plots should be saved. Default is the current directory.\n        plot (bool): Whether to save the detection and segmentation plots. Default is False.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.\n        names (list): List of class names. Default is an empty list.\n\n    Attributes:\n        save_dir (Path): Path to the directory where the output plots should be saved.\n        plot (bool): Whether to save the detection and segmentation plots.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered.\n        names (list): List of class names.\n        box (Metric): An instance of the Metric class to calculate box detection metrics.\n        seg (Metric): An instance of the Metric class to calculate mask segmentation metrics.\n        speed (dict): Dictionary to store the time taken in different phases of inference.\n\n    Methods:\n        process(tp_m, tp_b, conf, pred_cls, target_cls): Processes metrics over the given set of predictions.\n        mean_results(): Returns the mean of the detection and segmentation metrics over all the classes.\n        class_result(i): Returns the detection and segmentation metrics of class `i`.\n        maps: Returns the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95.\n        fitness: Returns the fitness scores, which are a single weighted combination of metrics.\n        ap_class_index: Returns the list of indices of classes used to compute Average Precision (AP).\n        results_dict: Returns the dictionary containing all the detection and segmentation metrics and fitness score.\n    \"\"\"\n\n    def __init__(self, save_dir=Path('.'), plot=False, on_plot=None, names=()) -> None:\n        self.save_dir = save_dir\n        self.plot = plot\n        self.on_plot = on_plot\n        self.names = names\n        self.box = Metric()\n        self.seg = Metric()\n        self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}\n\n    def process(self, tp_b, tp_m, conf, pred_cls, target_cls):\n        \"\"\"\n        Processes the detection and segmentation metrics over the given set of predictions.\n\n        Args:\n            tp_b (list): List of True Positive boxes.\n            tp_m (list): List of True Positive masks.\n            conf (list): List of confidence scores.\n            pred_cls (list): List of predicted classes.\n            target_cls (list): List of target classes.\n        \"\"\"\n\n        results_mask = ap_per_class(tp_m,\n                                    conf,\n                                    pred_cls,\n                                    target_cls,\n                                    plot=self.plot,\n                                    on_plot=self.on_plot,\n                                    save_dir=self.save_dir,\n                                    names=self.names,\n                                    prefix='Mask')[2:]\n        self.seg.nc = len(self.names)\n        self.seg.update(results_mask)\n        results_box = ap_per_class(tp_b,\n                                   conf,\n                                   pred_cls,\n                                   target_cls,\n                                   plot=self.plot,\n                                   on_plot=self.on_plot,\n                                   save_dir=self.save_dir,\n                                   names=self.names,\n                                   prefix='Box')[2:]\n        self.box.nc = len(self.names)\n        self.box.update(results_box)\n\n    @property\n    def keys(self):\n        \"\"\"Returns a list of keys for accessing metrics.\"\"\"\n        return [\n            'metrics/precision(B)', 'metrics/recall(B)', 'metrics/mAP50(B)', 'metrics/mAP50-95(B)',\n            'metrics/precision(M)', 'metrics/recall(M)', 'metrics/mAP50(M)', 'metrics/mAP50-95(M)']\n\n    def mean_results(self):\n        \"\"\"Return the mean metrics for bounding box and segmentation results.\"\"\"\n        return self.box.mean_results() + self.seg.mean_results()\n\n    def class_result(self, i):\n        \"\"\"Returns classification results for a specified class index.\"\"\"\n        return self.box.class_result(i) + self.seg.class_result(i)\n\n    @property\n    def maps(self):\n        \"\"\"Returns mAP scores for object detection and semantic segmentation models.\"\"\"\n        return self.box.maps + self.seg.maps\n\n    @property\n    def fitness(self):\n        \"\"\"Get the fitness score for both segmentation and bounding box models.\"\"\"\n        return self.seg.fitness() + self.box.fitness()\n\n    @property\n    def ap_class_index(self):\n        \"\"\"Boxes and masks have the same ap_class_index.\"\"\"\n        return self.box.ap_class_index\n\n    @property\n    def results_dict(self):\n        \"\"\"Returns results of object detection model for evaluation.\"\"\"\n        return dict(zip(self.keys + ['fitness'], self.mean_results() + [self.fitness]))\n\n\nclass PoseMetrics(SegmentMetrics):\n    \"\"\"\n    Calculates and aggregates detection and pose metrics over a given set of classes.\n\n    Args:\n        save_dir (Path): Path to the directory where the output plots should be saved. Default is the current directory.\n        plot (bool): Whether to save the detection and segmentation plots. Default is False.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.\n        names (list): List of class names. Default is an empty list.\n\n    Attributes:\n        save_dir (Path): Path to the directory where the output plots should be saved.\n        plot (bool): Whether to save the detection and segmentation plots.\n        on_plot (func): An optional callback to pass plots path and data when they are rendered.\n        names (list): List of class names.\n        box (Metric): An instance of the Metric class to calculate box detection metrics.\n        pose (Metric): An instance of the Metric class to calculate mask segmentation metrics.\n        speed (dict): Dictionary to store the time taken in different phases of inference.\n\n    Methods:\n        process(tp_m, tp_b, conf, pred_cls, target_cls): Processes metrics over the given set of predictions.\n        mean_results(): Returns the mean of the detection and segmentation metrics over all the classes.\n        class_result(i): Returns the detection and segmentation metrics of class `i`.\n        maps: Returns the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95.\n        fitness: Returns the fitness scores, which are a single weighted combination of metrics.\n        ap_class_index: Returns the list of indices of classes used to compute Average Precision (AP).\n        results_dict: Returns the dictionary containing all the detection and segmentation metrics and fitness score.\n    \"\"\"\n\n    def __init__(self, save_dir=Path('.'), plot=False, on_plot=None, names=()) -> None:\n        super().__init__(save_dir, plot, names)\n        self.save_dir = save_dir\n        self.plot = plot\n        self.on_plot = on_plot\n        self.names = names\n        self.box = Metric()\n        self.pose = Metric()\n        self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}\n\n    def __getattr__(self, attr):\n        \"\"\"Raises an AttributeError if an invalid attribute is accessed.\"\"\"\n        name = self.__class__.__name__\n        raise AttributeError(f\"'{name}' object has no attribute '{attr}'. See valid attributes below.\\n{self.__doc__}\")\n\n    def process(self, tp_b, tp_p, conf, pred_cls, target_cls):\n        \"\"\"\n        Processes the detection and pose metrics over the given set of predictions.\n\n        Args:\n            tp_b (list): List of True Positive boxes.\n            tp_p (list): List of True Positive keypoints.\n            conf (list): List of confidence scores.\n            pred_cls (list): List of predicted classes.\n            target_cls (list): List of target classes.\n        \"\"\"\n\n        results_pose = ap_per_class(tp_p,\n                                    conf,\n                                    pred_cls,\n                                    target_cls,\n                                    plot=self.plot,\n                                    on_plot=self.on_plot,\n                                    save_dir=self.save_dir,\n                                    names=self.names,\n                                    prefix='Pose')[2:]\n        self.pose.nc = len(self.names)\n        self.pose.update(results_pose)\n        results_box = ap_per_class(tp_b,\n                                   conf,\n                                   pred_cls,\n                                   target_cls,\n                                   plot=self.plot,\n                                   on_plot=self.on_plot,\n                                   save_dir=self.save_dir,\n                                   names=self.names,\n                                   prefix='Box')[2:]\n        self.box.nc = len(self.names)\n        self.box.update(results_box)\n\n    @property\n    def keys(self):\n        \"\"\"Returns list of evaluation metric keys.\"\"\"\n        return [\n            'metrics/precision(B)', 'metrics/recall(B)', 'metrics/mAP50(B)', 'metrics/mAP50-95(B)',\n            'metrics/precision(P)', 'metrics/recall(P)', 'metrics/mAP50(P)', 'metrics/mAP50-95(P)']\n\n    def mean_results(self):\n        \"\"\"Return the mean results of box and pose.\"\"\"\n        return self.box.mean_results() + self.pose.mean_results()\n\n    def class_result(self, i):\n        \"\"\"Return the class-wise detection results for a specific class i.\"\"\"\n        return self.box.class_result(i) + self.pose.class_result(i)\n\n    @property\n    def maps(self):\n        \"\"\"Returns the mean average precision (mAP) per class for both box and pose detections.\"\"\"\n        return self.box.maps + self.pose.maps\n\n    @property\n    def fitness(self):\n        \"\"\"Computes classification metrics and speed using the `targets` and `pred` inputs.\"\"\"\n        return self.pose.fitness() + self.box.fitness()\n\n\nclass ClassifyMetrics(SimpleClass):\n    \"\"\"\n    Class for computing classification metrics including top-1 and top-5 accuracy.\n\n    Attributes:\n        top1 (float): The top-1 accuracy.\n        top5 (float): The top-5 accuracy.\n        speed (Dict[str, float]): A dictionary containing the time taken for each step in the pipeline.\n\n    Properties:\n        fitness (float): The fitness of the model, which is equal to top-5 accuracy.\n        results_dict (Dict[str, Union[float, str]]): A dictionary containing the classification metrics and fitness.\n        keys (List[str]): A list of keys for the results_dict.\n\n    Methods:\n        process(targets, pred): Processes the targets and predictions to compute classification metrics.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.top1 = 0\n        self.top5 = 0\n        self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}\n\n    def process(self, targets, pred):\n        \"\"\"Target classes and predicted classes.\"\"\"\n        pred, targets = torch.cat(pred), torch.cat(targets)\n        correct = (targets[:, None] == pred).float()\n        acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1)  # (top1, top5) accuracy\n        self.top1, self.top5 = acc.mean(0).tolist()\n\n    @property\n    def fitness(self):\n        \"\"\"Returns top-5 accuracy as fitness score.\"\"\"\n        return self.top5\n\n    @property\n    def results_dict(self):\n        \"\"\"Returns a dictionary with model's performance metrics and fitness score.\"\"\"\n        return dict(zip(self.keys + ['fitness'], [self.top1, self.top5, self.fitness]))\n\n    @property\n    def keys(self):\n        \"\"\"Returns a list of keys for the results_dict property.\"\"\"\n        return ['metrics/accuracy_top1', 'metrics/accuracy_top5']\n"
  },
  {
    "path": "ultralytics/yolo/utils/ops.py",
    "content": "import contextlib\nimport math\nimport re\nimport time\n\nimport cv2\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torchvision\n\nfrom ultralytics.yolo.utils import LOGGER\n\nfrom .metrics import box_iou\n\n\nclass Profile(contextlib.ContextDecorator):\n    \"\"\"\n    YOLOv8 Profile class.\n    Usage: as a decorator with @Profile() or as a context manager with 'with Profile():'\n    \"\"\"\n\n    def __init__(self, t=0.0):\n        \"\"\"\n        Initialize the Profile class.\n\n        Args:\n            t (float): Initial time. Defaults to 0.0.\n        \"\"\"\n        self.t = t\n        self.cuda = torch.cuda.is_available()\n\n    def __enter__(self):\n        \"\"\"\n        Start timing.\n        \"\"\"\n        self.start = self.time()\n        return self\n\n    def __exit__(self, type, value, traceback):\n        \"\"\"\n        Stop timing.\n        \"\"\"\n        self.dt = self.time() - self.start  # delta-time\n        self.t += self.dt  # accumulate dt\n\n    def time(self):\n        \"\"\"\n        Get current time.\n        \"\"\"\n        if self.cuda:\n            torch.cuda.synchronize()\n        return time.time()\n\n\ndef coco80_to_coco91_class():  # converts 80-index (val2014) to 91-index (paper)\n    # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/\n    # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\\n')\n    # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\\n')\n    # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)]  # darknet to coco\n    # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)]  # coco to darknet\n    return [\n        1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,\n        35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,\n        64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]\n\n\ndef segment2box(segment, width=640, height=640):\n    \"\"\"\n    Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)\n\n    Args:\n      segment (torch.Tensor): the segment label\n      width (int): the width of the image. Defaults to 640\n      height (int): The height of the image. Defaults to 640\n\n    Returns:\n      (np.ndarray): the minimum and maximum x and y values of the segment.\n    \"\"\"\n    # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)\n    x, y = segment.T  # segment xy\n    inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height)\n    x, y, = x[inside], y[inside]\n    return np.array([x.min(), y.min(), x.max(), y.max()], dtype=segment.dtype) if any(x) else np.zeros(\n        4, dtype=segment.dtype)  # xyxy\n\n\ndef scale_boxes(img1_shape, boxes, img0_shape, ratio_pad=None):\n    \"\"\"\n    Rescales bounding boxes (in the format of xyxy) from the shape of the image they were originally specified in\n    (img1_shape) to the shape of a different image (img0_shape).\n\n    Args:\n      img1_shape (tuple): The shape of the image that the bounding boxes are for, in the format of (height, width).\n      boxes (torch.Tensor): the bounding boxes of the objects in the image, in the format of (x1, y1, x2, y2)\n      img0_shape (tuple): the shape of the target image, in the format of (height, width).\n      ratio_pad (tuple): a tuple of (ratio, pad) for scaling the boxes. If not provided, the ratio and pad will be\n                         calculated based on the size difference between the two images.\n\n    Returns:\n      boxes (torch.Tensor): The scaled bounding boxes, in the format of (x1, y1, x2, y2)\n    \"\"\"\n    if ratio_pad is None:  # calculate from img0_shape\n        gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1])  # gain  = old / new\n        pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2  # wh padding\n    else:\n        gain = ratio_pad[0][0]\n        pad = ratio_pad[1]\n\n    boxes[..., [0, 2]] -= pad[0]  # x padding\n    boxes[..., [1, 3]] -= pad[1]  # y padding\n    boxes[..., :4] /= gain\n    clip_boxes(boxes, img0_shape)\n    return boxes\n\n\ndef make_divisible(x, divisor):\n    \"\"\"\n    Returns the nearest number that is divisible by the given divisor.\n\n    Args:\n        x (int): The number to make divisible.\n        divisor (int) or (torch.Tensor): The divisor.\n\n    Returns:\n        (int): The nearest number divisible by the divisor.\n    \"\"\"\n    if isinstance(divisor, torch.Tensor):\n        divisor = int(divisor.max())  # to int\n    return math.ceil(x / divisor) * divisor\n\n\ndef non_max_suppression(\n        prediction,\n        conf_thres=0.25,\n        iou_thres=0.45,\n        classes=None,\n        agnostic=False,\n        multi_label=False,\n        labels=(),\n        max_det=300,\n        nc=0,  # number of classes (optional)\n        max_time_img=0.05,\n        max_nms=30000,\n        max_wh=7680,\n):\n    \"\"\"\n    Perform non-maximum suppression (NMS) on a set of boxes, with support for masks and multiple labels per box.\n\n    Arguments:\n        prediction (torch.Tensor): A tensor of shape (batch_size, num_classes + 4 + num_masks, num_boxes)\n            containing the predicted boxes, classes, and masks. The tensor should be in the format\n            output by a model, such as YOLO.\n        conf_thres (float): The confidence threshold below which boxes will be filtered out.\n            Valid values are between 0.0 and 1.0.\n        iou_thres (float): The IoU threshold below which boxes will be filtered out during NMS.\n            Valid values are between 0.0 and 1.0.\n        classes (List[int]): A list of class indices to consider. If None, all classes will be considered.\n        agnostic (bool): If True, the model is agnostic to the number of classes, and all\n            classes will be considered as one.\n        multi_label (bool): If True, each box may have multiple labels.\n        labels (List[List[Union[int, float, torch.Tensor]]]): A list of lists, where each inner\n            list contains the apriori labels for a given image. The list should be in the format\n            output by a dataloader, with each label being a tuple of (class_index, x1, y1, x2, y2).\n        max_det (int): The maximum number of boxes to keep after NMS.\n        nc (int): (optional) The number of classes output by the model. Any indices after this will be considered masks.\n        max_time_img (float): The maximum time (seconds) for processing one image.\n        max_nms (int): The maximum number of boxes into torchvision.ops.nms().\n        max_wh (int): The maximum box width and height in pixels\n\n    Returns:\n        (List[torch.Tensor]): A list of length batch_size, where each element is a tensor of\n            shape (num_boxes, 6 + num_masks) containing the kept boxes, with columns\n            (x1, y1, x2, y2, confidence, class, mask1, mask2, ...).\n    \"\"\"\n\n    # Checks\n    assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'\n    assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'\n    if isinstance(prediction, (list, tuple)):  # YOLOv8 model in validation model, output = (inference_out, loss_out)\n        prediction = prediction[0]  # select only inference output\n\n    device = prediction.device\n    mps = 'mps' in device.type  # Apple MPS\n    if mps:  # MPS not fully supported yet, convert tensors to CPU before NMS\n        prediction = prediction.cpu()\n    bs = prediction.shape[0]  # batch size\n    nc = nc or (prediction.shape[1] - 4)  # number of classes\n    nm = prediction.shape[1] - nc - 4\n    mi = 4 + nc  # mask start index\n    xc = prediction[:, 4:mi].amax(1) > conf_thres  # candidates\n\n    # Settings\n    # min_wh = 2  # (pixels) minimum box width and height\n    time_limit = 0.5 + max_time_img * bs  # seconds to quit after\n    redundant = True  # require redundant detections\n    multi_label &= nc > 1  # multiple labels per box (adds 0.5ms/img)\n    merge = False  # use merge-NMS\n\n    t = time.time()\n    output = [torch.zeros((0, 6 + nm), device=prediction.device)] * bs\n    for xi, x in enumerate(prediction):  # image index, image inference\n        # Apply constraints\n        # x[((x[:, 2:4] < min_wh) | (x[:, 2:4] > max_wh)).any(1), 4] = 0  # width-height\n        x = x.transpose(0, -1)[xc[xi]]  # confidence\n\n        # Cat apriori labels if autolabelling\n        if labels and len(labels[xi]):\n            lb = labels[xi]\n            v = torch.zeros((len(lb), nc + nm + 5), device=x.device)\n            v[:, :4] = lb[:, 1:5]  # box\n            v[range(len(lb)), lb[:, 0].long() + 4] = 1.0  # cls\n            x = torch.cat((x, v), 0)\n\n        # If none remain process next image\n        if not x.shape[0]:\n            continue\n\n        # Detections matrix nx6 (xyxy, conf, cls)\n        box, cls, mask = x.split((4, nc, nm), 1)\n        box = xywh2xyxy(box)  # center_x, center_y, width, height) to (x1, y1, x2, y2)\n        if multi_label:\n            i, j = (cls > conf_thres).nonzero(as_tuple=False).T\n            x = torch.cat((box[i], x[i, 4 + j, None], j[:, None].float(), mask[i]), 1)\n        else:  # best class only\n            conf, j = cls.max(1, keepdim=True)\n            x = torch.cat((box, conf, j.float(), mask), 1)[conf.view(-1) > conf_thres]\n\n        # Filter by class\n        if classes is not None:\n            x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]\n\n        # Apply finite constraint\n        # if not torch.isfinite(x).all():\n        #     x = x[torch.isfinite(x).all(1)]\n\n        # Check shape\n        n = x.shape[0]  # number of boxes\n        if not n:  # no boxes\n            continue\n        x = x[x[:, 4].argsort(descending=True)[:max_nms]]  # sort by confidence and remove excess boxes\n\n        # Batched NMS\n        c = x[:, 5:6] * (0 if agnostic else max_wh)  # classes\n        boxes, scores = x[:, :4] + c, x[:, 4]  # boxes (offset by class), scores\n        i = torchvision.ops.nms(boxes, scores, iou_thres)  # NMS\n        i = i[:max_det]  # limit detections\n        if merge and (1 < n < 3E3):  # Merge NMS (boxes merged using weighted mean)\n            # Update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)\n            iou = box_iou(boxes[i], boxes) > iou_thres  # iou matrix\n            weights = iou * scores[None]  # box weights\n            x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True)  # merged boxes\n            if redundant:\n                i = i[iou.sum(1) > 1]  # require redundancy\n\n        output[xi] = x[i]\n        if mps:\n            output[xi] = output[xi].to(device)\n        if (time.time() - t) > time_limit:\n            LOGGER.warning(f'WARNING ⚠️ NMS time limit {time_limit:.3f}s exceeded')\n            break  # time limit exceeded\n\n    return output\n\n\ndef clip_boxes(boxes, shape):\n    \"\"\"\n    It takes a list of bounding boxes and a shape (height, width) and clips the bounding boxes to the\n    shape\n\n    Args:\n      boxes (torch.Tensor): the bounding boxes to clip\n      shape (tuple): the shape of the image\n    \"\"\"\n    if isinstance(boxes, torch.Tensor):  # faster individually\n        boxes[..., 0].clamp_(0, shape[1])  # x1\n        boxes[..., 1].clamp_(0, shape[0])  # y1\n        boxes[..., 2].clamp_(0, shape[1])  # x2\n        boxes[..., 3].clamp_(0, shape[0])  # y2\n    else:  # np.array (faster grouped)\n        boxes[..., [0, 2]] = boxes[..., [0, 2]].clip(0, shape[1])  # x1, x2\n        boxes[..., [1, 3]] = boxes[..., [1, 3]].clip(0, shape[0])  # y1, y2\n\n\ndef clip_coords(coords, shape):\n    \"\"\"\n    Clip line coordinates to the image boundaries.\n\n    Args:\n        coords (torch.Tensor) or (numpy.ndarray): A list of line coordinates.\n        shape (tuple): A tuple of integers representing the size of the image in the format (height, width).\n\n    Returns:\n        (None): The function modifies the input `coordinates` in place, by clipping each coordinate to the image boundaries.\n    \"\"\"\n    if isinstance(coords, torch.Tensor):  # faster individually\n        coords[..., 0].clamp_(0, shape[1])  # x\n        coords[..., 1].clamp_(0, shape[0])  # y\n    else:  # np.array (faster grouped)\n        coords[..., 0] = coords[..., 0].clip(0, shape[1])  # x\n        coords[..., 1] = coords[..., 1].clip(0, shape[0])  # y\n\n\ndef scale_image(masks, im0_shape, ratio_pad=None):\n    \"\"\"\n    Takes a mask, and resizes it to the original image size\n\n    Args:\n      masks (torch.Tensor): resized and padded masks/images, [h, w, num]/[h, w, 3].\n      im0_shape (tuple): the original image shape\n      ratio_pad (tuple): the ratio of the padding to the original image.\n\n    Returns:\n      masks (torch.Tensor): The masks that are being returned.\n    \"\"\"\n    # Rescale coordinates (xyxy) from im1_shape to im0_shape\n    im1_shape = masks.shape\n    if im1_shape[:2] == im0_shape[:2]:\n        return masks\n    if ratio_pad is None:  # calculate from im0_shape\n        gain = min(im1_shape[0] / im0_shape[0], im1_shape[1] / im0_shape[1])  # gain  = old / new\n        pad = (im1_shape[1] - im0_shape[1] * gain) / 2, (im1_shape[0] - im0_shape[0] * gain) / 2  # wh padding\n    else:\n        gain = ratio_pad[0][0]\n        pad = ratio_pad[1]\n    top, left = int(pad[1]), int(pad[0])  # y, x\n    bottom, right = int(im1_shape[0] - pad[1]), int(im1_shape[1] - pad[0])\n\n    if len(masks.shape) < 2:\n        raise ValueError(f'\"len of masks shape\" should be 2 or 3, but got {len(masks.shape)}')\n    masks = masks[top:bottom, left:right]\n    # masks = masks.permute(2, 0, 1).contiguous()\n    # masks = F.interpolate(masks[None], im0_shape[:2], mode='bilinear', align_corners=False)[0]\n    # masks = masks.permute(1, 2, 0).contiguous()\n    masks = cv2.resize(masks, (im0_shape[1], im0_shape[0]))\n    if len(masks.shape) == 2:\n        masks = masks[:, :, None]\n\n    return masks\n\n\ndef xyxy2xywh(x):\n    \"\"\"\n    Convert bounding box coordinates from (x1, y1, x2, y2) format to (x, y, width, height) format.\n\n    Args:\n        x (np.ndarray) or (torch.Tensor): The input bounding box coordinates in (x1, y1, x2, y2) format.\n    Returns:\n       y (np.ndarray) or (torch.Tensor): The bounding box coordinates in (x, y, width, height) format.\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[..., 0] = (x[..., 0] + x[..., 2]) / 2  # x center\n    y[..., 1] = (x[..., 1] + x[..., 3]) / 2  # y center\n    y[..., 2] = x[..., 2] - x[..., 0]  # width\n    y[..., 3] = x[..., 3] - x[..., 1]  # height\n    return y\n\n\ndef xywh2xyxy(x):\n    \"\"\"\n    Convert bounding box coordinates from (x, y, width, height) format to (x1, y1, x2, y2) format where (x1, y1) is the\n    top-left corner and (x2, y2) is the bottom-right corner.\n\n    Args:\n        x (np.ndarray) or (torch.Tensor): The input bounding box coordinates in (x, y, width, height) format.\n    Returns:\n        y (np.ndarray) or (torch.Tensor): The bounding box coordinates in (x1, y1, x2, y2) format.\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[..., 0] = x[..., 0] - x[..., 2] / 2  # top left x\n    y[..., 1] = x[..., 1] - x[..., 3] / 2  # top left y\n    y[..., 2] = x[..., 0] + x[..., 2] / 2  # bottom right x\n    y[..., 3] = x[..., 1] + x[..., 3] / 2  # bottom right y\n    return y\n\n\ndef xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):\n    \"\"\"\n    Convert normalized bounding box coordinates to pixel coordinates.\n\n    Args:\n        x (np.ndarray) or (torch.Tensor): The bounding box coordinates.\n        w (int): Width of the image. Defaults to 640\n        h (int): Height of the image. Defaults to 640\n        padw (int): Padding width. Defaults to 0\n        padh (int): Padding height. Defaults to 0\n    Returns:\n        y (np.ndarray) or (torch.Tensor): The coordinates of the bounding box in the format [x1, y1, x2, y2] where\n            x1,y1 is the top-left corner, x2,y2 is the bottom-right corner of the bounding box.\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[..., 0] = w * (x[..., 0] - x[..., 2] / 2) + padw  # top left x\n    y[..., 1] = h * (x[..., 1] - x[..., 3] / 2) + padh  # top left y\n    y[..., 2] = w * (x[..., 0] + x[..., 2] / 2) + padw  # bottom right x\n    y[..., 3] = h * (x[..., 1] + x[..., 3] / 2) + padh  # bottom right y\n    return y\n\n\ndef xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):\n    \"\"\"\n    Convert bounding box coordinates from (x1, y1, x2, y2) format to (x, y, width, height, normalized) format.\n    x, y, width and height are normalized to image dimensions\n\n    Args:\n        x (np.ndarray) or (torch.Tensor): The input bounding box coordinates in (x1, y1, x2, y2) format.\n        w (int): The width of the image. Defaults to 640\n        h (int): The height of the image. Defaults to 640\n        clip (bool): If True, the boxes will be clipped to the image boundaries. Defaults to False\n        eps (float): The minimum value of the box's width and height. Defaults to 0.0\n    Returns:\n        y (np.ndarray) or (torch.Tensor): The bounding box coordinates in (x, y, width, height, normalized) format\n    \"\"\"\n    if clip:\n        clip_boxes(x, (h - eps, w - eps))  # warning: inplace clip\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[..., 0] = ((x[..., 0] + x[..., 2]) / 2) / w  # x center\n    y[..., 1] = ((x[..., 1] + x[..., 3]) / 2) / h  # y center\n    y[..., 2] = (x[..., 2] - x[..., 0]) / w  # width\n    y[..., 3] = (x[..., 3] - x[..., 1]) / h  # height\n    return y\n\n\ndef xyn2xy(x, w=640, h=640, padw=0, padh=0):\n    \"\"\"\n    Convert normalized coordinates to pixel coordinates of shape (n,2)\n\n    Args:\n        x (np.ndarray) or (torch.Tensor): The input tensor of normalized bounding box coordinates\n        w (int): The width of the image. Defaults to 640\n        h (int): The height of the image. Defaults to 640\n        padw (int): The width of the padding. Defaults to 0\n        padh (int): The height of the padding. Defaults to 0\n    Returns:\n        y (np.ndarray) or (torch.Tensor): The x and y coordinates of the top left corner of the bounding box\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[..., 0] = w * x[..., 0] + padw  # top left x\n    y[..., 1] = h * x[..., 1] + padh  # top left y\n    return y\n\n\ndef xywh2ltwh(x):\n    \"\"\"\n    Convert the bounding box format from [x, y, w, h] to [x1, y1, w, h], where x1, y1 are the top-left coordinates.\n\n    Args:\n        x (np.ndarray) or (torch.Tensor): The input tensor with the bounding box coordinates in the xywh format\n    Returns:\n        y (np.ndarray) or (torch.Tensor): The bounding box coordinates in the xyltwh format\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 0] = x[:, 0] - x[:, 2] / 2  # top left x\n    y[:, 1] = x[:, 1] - x[:, 3] / 2  # top left y\n    return y\n\n\ndef xyxy2ltwh(x):\n    \"\"\"\n    Convert nx4 bounding boxes from [x1, y1, x2, y2] to [x1, y1, w, h], where xy1=top-left, xy2=bottom-right\n\n    Args:\n      x (np.ndarray) or (torch.Tensor): The input tensor with the bounding boxes coordinates in the xyxy format\n    Returns:\n      y (np.ndarray) or (torch.Tensor): The bounding box coordinates in the xyltwh format.\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 2] = x[:, 2] - x[:, 0]  # width\n    y[:, 3] = x[:, 3] - x[:, 1]  # height\n    return y\n\n\ndef ltwh2xywh(x):\n    \"\"\"\n    Convert nx4 boxes from [x1, y1, w, h] to [x, y, w, h] where xy1=top-left, xy=center\n\n    Args:\n      x (torch.Tensor): the input tensor\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 0] = x[:, 0] + x[:, 2] / 2  # center x\n    y[:, 1] = x[:, 1] + x[:, 3] / 2  # center y\n    return y\n\n\ndef ltwh2xyxy(x):\n    \"\"\"\n    It converts the bounding box from [x1, y1, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n\n    Args:\n      x (np.ndarray) or (torch.Tensor): the input image\n\n    Returns:\n      y (np.ndarray) or (torch.Tensor): the xyxy coordinates of the bounding boxes.\n    \"\"\"\n    y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)\n    y[:, 2] = x[:, 2] + x[:, 0]  # width\n    y[:, 3] = x[:, 3] + x[:, 1]  # height\n    return y\n\n\ndef segments2boxes(segments):\n    \"\"\"\n    It converts segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh)\n\n    Args:\n      segments (list): list of segments, each segment is a list of points, each point is a list of x, y coordinates\n\n    Returns:\n      (np.ndarray): the xywh coordinates of the bounding boxes.\n    \"\"\"\n    boxes = []\n    for s in segments:\n        x, y = s.T  # segment xy\n        boxes.append([x.min(), y.min(), x.max(), y.max()])  # cls, xyxy\n    return xyxy2xywh(np.array(boxes))  # cls, xywh\n\n\ndef resample_segments(segments, n=1000):\n    \"\"\"\n    Inputs a list of segments (n,2) and returns a list of segments (n,2) up-sampled to n points each.\n\n    Args:\n      segments (list): a list of (n,2) arrays, where n is the number of points in the segment.\n      n (int): number of points to resample the segment to. Defaults to 1000\n\n    Returns:\n      segments (list): the resampled segments.\n    \"\"\"\n    for i, s in enumerate(segments):\n        s = np.concatenate((s, s[0:1, :]), axis=0)\n        x = np.linspace(0, len(s) - 1, n)\n        xp = np.arange(len(s))\n        segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)],\n                                     dtype=np.float32).reshape(2, -1).T  # segment xy\n    return segments\n\n\ndef crop_mask(masks, boxes):\n    \"\"\"\n    It takes a mask and a bounding box, and returns a mask that is cropped to the bounding box\n\n    Args:\n      masks (torch.Tensor): [h, w, n] tensor of masks\n      boxes (torch.Tensor): [n, 4] tensor of bbox coordinates in relative point form\n\n    Returns:\n      (torch.Tensor): The masks are being cropped to the bounding box.\n    \"\"\"\n    n, h, w = masks.shape\n    x1, y1, x2, y2 = torch.chunk(boxes[:, :, None], 4, 1)  # x1 shape(n,1,1)\n    r = torch.arange(w, device=masks.device, dtype=x1.dtype)[None, None, :]  # rows shape(1,1,w)\n    c = torch.arange(h, device=masks.device, dtype=x1.dtype)[None, :, None]  # cols shape(1,h,1)\n\n    return masks * ((r >= x1) * (r < x2) * (c >= y1) * (c < y2))\n\n\ndef process_mask_upsample(protos, masks_in, bboxes, shape):\n    \"\"\"\n    It takes the output of the mask head, and applies the mask to the bounding boxes. This produces masks of higher\n    quality but is slower.\n\n    Args:\n      protos (torch.Tensor): [mask_dim, mask_h, mask_w]\n      masks_in (torch.Tensor): [n, mask_dim], n is number of masks after nms\n      bboxes (torch.Tensor): [n, 4], n is number of masks after nms\n      shape (tuple): the size of the input image (h,w)\n\n    Returns:\n      (torch.Tensor): The upsampled masks.\n    \"\"\"\n    c, mh, mw = protos.shape  # CHW\n    masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw)\n    masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0]  # CHW\n    masks = crop_mask(masks, bboxes)  # CHW\n    return masks.gt_(0.5)\n\n\ndef process_mask(protos, masks_in, bboxes, shape, upsample=False):\n    \"\"\"\n    Apply masks to bounding boxes using the output of the mask head.\n\n    Args:\n        protos (torch.Tensor): A tensor of shape [mask_dim, mask_h, mask_w].\n        masks_in (torch.Tensor): A tensor of shape [n, mask_dim], where n is the number of masks after NMS.\n        bboxes (torch.Tensor): A tensor of shape [n, 4], where n is the number of masks after NMS.\n        shape (tuple): A tuple of integers representing the size of the input image in the format (h, w).\n        upsample (bool): A flag to indicate whether to upsample the mask to the original image size. Default is False.\n\n    Returns:\n        (torch.Tensor): A binary mask tensor of shape [n, h, w], where n is the number of masks after NMS, and h and w\n            are the height and width of the input image. The mask is applied to the bounding boxes.\n    \"\"\"\n\n    c, mh, mw = protos.shape  # CHW\n    ih, iw = shape\n    masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw)  # CHW\n\n    downsampled_bboxes = bboxes.clone()\n    downsampled_bboxes[:, 0] *= mw / iw\n    downsampled_bboxes[:, 2] *= mw / iw\n    downsampled_bboxes[:, 3] *= mh / ih\n    downsampled_bboxes[:, 1] *= mh / ih\n\n    masks = crop_mask(masks, downsampled_bboxes)  # CHW\n    if upsample:\n        masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0]  # CHW\n    return masks.gt_(0.5)\n\n\ndef process_mask_native(protos, masks_in, bboxes, shape):\n    \"\"\"\n    It takes the output of the mask head, and crops it after upsampling to the bounding boxes.\n\n    Args:\n      protos (torch.Tensor): [mask_dim, mask_h, mask_w]\n      masks_in (torch.Tensor): [n, mask_dim], n is number of masks after nms\n      bboxes (torch.Tensor): [n, 4], n is number of masks after nms\n      shape (tuple): the size of the input image (h,w)\n\n    Returns:\n      masks (torch.Tensor): The returned masks with dimensions [h, w, n]\n    \"\"\"\n    c, mh, mw = protos.shape  # CHW\n    masks = (masks_in @ protos.float().view(c, -1)).sigmoid().view(-1, mh, mw)\n    gain = min(mh / shape[0], mw / shape[1])  # gain  = old / new\n    pad = (mw - shape[1] * gain) / 2, (mh - shape[0] * gain) / 2  # wh padding\n    top, left = int(pad[1]), int(pad[0])  # y, x\n    bottom, right = int(mh - pad[1]), int(mw - pad[0])\n    masks = masks[:, top:bottom, left:right]\n\n    masks = F.interpolate(masks[None], shape, mode='bilinear', align_corners=False)[0]  # CHW\n    masks = crop_mask(masks, bboxes)  # CHW\n    return masks.gt_(0.5)\n\n\ndef scale_coords(img1_shape, coords, img0_shape, ratio_pad=None, normalize=False):\n    \"\"\"\n    Rescale segment coordinates (xyxy) from img1_shape to img0_shape\n\n    Args:\n      img1_shape (tuple): The shape of the image that the coords are from.\n      coords (torch.Tensor): the coords to be scaled\n      img0_shape (tuple): the shape of the image that the segmentation is being applied to\n      ratio_pad (tuple): the ratio of the image size to the padded image size.\n      normalize (bool): If True, the coordinates will be normalized to the range [0, 1]. Defaults to False\n\n    Returns:\n      coords (torch.Tensor): the segmented image.\n    \"\"\"\n    if ratio_pad is None:  # calculate from img0_shape\n        gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1])  # gain  = old / new\n        pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2  # wh padding\n    else:\n        gain = ratio_pad[0][0]\n        pad = ratio_pad[1]\n\n    coords[..., 0] -= pad[0]  # x padding\n    coords[..., 1] -= pad[1]  # y padding\n    coords[..., 0] /= gain\n    coords[..., 1] /= gain\n    clip_coords(coords, img0_shape)\n    if normalize:\n        coords[..., 0] /= img0_shape[1]  # width\n        coords[..., 1] /= img0_shape[0]  # height\n    return coords\n\n\ndef masks2segments(masks, strategy='largest'):\n    \"\"\"\n    It takes a list of masks(n,h,w) and returns a list of segments(n,xy)\n\n    Args:\n      masks (torch.Tensor): the output of the model, which is a tensor of shape (batch_size, 160, 160)\n      strategy (str): 'concat' or 'largest'. Defaults to largest\n\n    Returns:\n      segments (List): list of segment masks\n    \"\"\"\n    segments = []\n    for x in masks.int().cpu().numpy().astype('uint8'):\n        c = cv2.findContours(x, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]\n        if c:\n            if strategy == 'concat':  # concatenate all segments\n                c = np.concatenate([x.reshape(-1, 2) for x in c])\n            elif strategy == 'largest':  # select largest segment\n                c = np.array(c[np.array([len(x) for x in c]).argmax()]).reshape(-1, 2)\n        else:\n            c = np.zeros((0, 2))  # no segments found\n        segments.append(c.astype('float32'))\n    return segments\n\n\ndef clean_str(s):\n    \"\"\"\n    Cleans a string by replacing special characters with underscore _\n\n    Args:\n      s (str): a string needing special characters replaced\n\n    Returns:\n      (str): a string with special characters replaced by an underscore _\n    \"\"\"\n    return re.sub(pattern='[|@#!¡·$€%&()=?¿^*;:,¨´><+]', repl='_', string=s)\n"
  },
  {
    "path": "ultralytics/yolo/utils/plotting.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport contextlib\nimport math\nfrom pathlib import Path\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom PIL import Image, ImageDraw, ImageFont\nfrom PIL import __version__ as pil_version\n\nfrom ultralytics.yolo.utils import LOGGER, TryExcept, plt_settings, threaded\n\nfrom .checks import check_font, check_version, is_ascii\nfrom .files import increment_path\nfrom .ops import clip_boxes, scale_image, xywh2xyxy, xyxy2xywh\n\n\nclass Colors:\n    # Ultralytics color palette https://ultralytics.com/\n    def __init__(self):\n        \"\"\"Initialize colors as hex = matplotlib.colors.TABLEAU_COLORS.values().\"\"\"\n        hexs = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',\n                '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')\n        self.palette = [self.hex2rgb(f'#{c}') for c in hexs]\n        self.n = len(self.palette)\n        self.pose_palette = np.array([[255, 128, 0], [255, 153, 51], [255, 178, 102], [230, 230, 0], [255, 153, 255],\n                                      [153, 204, 255], [255, 102, 255], [255, 51, 255], [102, 178, 255], [51, 153, 255],\n                                      [255, 153, 153], [255, 102, 102], [255, 51, 51], [153, 255, 153], [102, 255, 102],\n                                      [51, 255, 51], [0, 255, 0], [0, 0, 255], [255, 0, 0], [255, 255, 255]],\n                                     dtype=np.uint8)\n\n    def __call__(self, i, bgr=False):\n        \"\"\"Converts hex color codes to rgb values.\"\"\"\n        c = self.palette[int(i) % self.n]\n        return (c[2], c[1], c[0]) if bgr else c\n\n    @staticmethod\n    def hex2rgb(h):  # rgb order (PIL)\n        return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))\n\n\ncolors = Colors()  # create instance for 'from utils.plots import colors'\n\n\nclass Annotator:\n    # YOLOv8 Annotator for train/val mosaics and jpgs and detect/hub inference annotations\n    def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=False, example='abc'):\n        \"\"\"Initialize the Annotator class with image and line width along with color palette for keypoints and limbs.\"\"\"\n        assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.'\n        non_ascii = not is_ascii(example)  # non-latin labels, i.e. asian, arabic, cyrillic\n        self.pil = pil or non_ascii\n        if self.pil:  # use PIL\n            self.pil_9_2_0_check = check_version(pil_version, '9.2.0')  # deprecation check\n            self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)\n            self.draw = ImageDraw.Draw(self.im)\n            try:\n                font = check_font('Arial.Unicode.ttf' if non_ascii else font)\n                size = font_size or max(round(sum(self.im.size) / 2 * 0.035), 12)\n                self.font = ImageFont.truetype(str(font), size)\n            except Exception:\n                self.font = ImageFont.load_default()\n        else:  # use cv2\n            self.im = im\n        self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2)  # line width\n        # Pose\n        self.skeleton = [[16, 14], [14, 12], [17, 15], [15, 13], [12, 13], [6, 12], [7, 13], [6, 7], [6, 8], [7, 9],\n                         [8, 10], [9, 11], [2, 3], [1, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7]]\n\n        self.limb_color = colors.pose_palette[[9, 9, 9, 9, 7, 7, 7, 0, 0, 0, 0, 0, 16, 16, 16, 16, 16, 16, 16]]\n        self.kpt_color = colors.pose_palette[[16, 16, 16, 16, 16, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9]]\n\n    def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)):\n        \"\"\"Add one xyxy box to image with label.\"\"\"\n        if isinstance(box, torch.Tensor):\n            box = box.tolist()\n        if self.pil or not is_ascii(label):\n            self.draw.rectangle(box, width=self.lw, outline=color)  # box\n            if label:\n                if self.pil_9_2_0_check:\n                    _, _, w, h = self.font.getbbox(label)  # text width, height (New)\n                else:\n                    w, h = self.font.getsize(label)  # text width, height (Old, deprecated in 9.2.0)\n                outside = box[1] - h >= 0  # label fits outside box\n                self.draw.rectangle(\n                    (box[0], box[1] - h if outside else box[1], box[0] + w + 1,\n                     box[1] + 1 if outside else box[1] + h + 1),\n                    fill=color,\n                )\n                # self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls')  # for PIL>8.0\n                self.draw.text((box[0], box[1] - h if outside else box[1]), label, fill=txt_color, font=self.font)\n        else:  # cv2\n            p1, p2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))\n            cv2.rectangle(self.im, p1, p2, color, thickness=self.lw, lineType=cv2.LINE_AA)\n            if label:\n                tf = max(self.lw - 1, 1)  # font thickness\n                w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0]  # text width, height\n                outside = p1[1] - h >= 3\n                p2 = p1[0] + w, p1[1] - h - 3 if outside else p1[1] + h + 3\n                cv2.rectangle(self.im, p1, p2, color, -1, cv2.LINE_AA)  # filled\n                cv2.putText(self.im,\n                            label, (p1[0], p1[1] - 2 if outside else p1[1] + h + 2),\n                            0,\n                            self.lw / 3,\n                            txt_color,\n                            thickness=tf,\n                            lineType=cv2.LINE_AA)\n\n    def masks(self, masks, colors, im_gpu, alpha=0.5, retina_masks=False):\n        \"\"\"Plot masks at once.\n        Args:\n            masks (tensor): predicted masks on cuda, shape: [n, h, w]\n            colors (List[List[Int]]): colors for predicted masks, [[r, g, b] * n]\n            im_gpu (tensor): img is in cuda, shape: [3, h, w], range: [0, 1]\n            alpha (float): mask transparency: 0.0 fully transparent, 1.0 opaque\n        \"\"\"\n        if self.pil:\n            # Convert to numpy first\n            self.im = np.asarray(self.im).copy()\n        if len(masks) == 0:\n            self.im[:] = im_gpu.permute(1, 2, 0).contiguous().cpu().numpy() * 255\n        if im_gpu.device != masks.device:\n            im_gpu = im_gpu.to(masks.device)\n        colors = torch.tensor(colors, device=masks.device, dtype=torch.float32) / 255.0  # shape(n,3)\n        colors = colors[:, None, None]  # shape(n,1,1,3)\n        masks = masks.unsqueeze(3)  # shape(n,h,w,1)\n        masks_color = masks * (colors * alpha)  # shape(n,h,w,3)\n\n        inv_alph_masks = (1 - masks * alpha).cumprod(0)  # shape(n,h,w,1)\n        mcs = masks_color.max(dim=0).values  # shape(n,h,w,3)\n\n        im_gpu = im_gpu.flip(dims=[0])  # flip channel\n        im_gpu = im_gpu.permute(1, 2, 0).contiguous()  # shape(h,w,3)\n        im_gpu = im_gpu * inv_alph_masks[-1] + mcs\n        im_mask = (im_gpu * 255)\n        im_mask_np = im_mask.byte().cpu().numpy()\n        self.im[:] = im_mask_np if retina_masks else scale_image(im_mask_np, self.im.shape)\n        if self.pil:\n            # Convert im back to PIL and update draw\n            self.fromarray(self.im)\n\n    def kpts(self, kpts, shape=(640, 640), radius=5, kpt_line=True):\n        \"\"\"Plot keypoints on the image.\n\n        Args:\n            kpts (tensor): Predicted keypoints with shape [17, 3]. Each keypoint has (x, y, confidence).\n            shape (tuple): Image shape as a tuple (h, w), where h is the height and w is the width.\n            radius (int, optional): Radius of the drawn keypoints. Default is 5.\n            kpt_line (bool, optional): If True, the function will draw lines connecting keypoints\n                                       for human pose. Default is True.\n\n        Note: `kpt_line=True` currently only supports human pose plotting.\n        \"\"\"\n        if self.pil:\n            # Convert to numpy first\n            self.im = np.asarray(self.im).copy()\n        nkpt, ndim = kpts.shape\n        is_pose = nkpt == 17 and ndim == 3\n        kpt_line &= is_pose  # `kpt_line=True` for now only supports human pose plotting\n        for i, k in enumerate(kpts):\n            color_k = [int(x) for x in self.kpt_color[i]] if is_pose else colors(i)\n            x_coord, y_coord = k[0], k[1]\n            if x_coord % shape[1] != 0 and y_coord % shape[0] != 0:\n                if len(k) == 3:\n                    conf = k[2]\n                    if conf < 0.5:\n                        continue\n                cv2.circle(self.im, (int(x_coord), int(y_coord)), radius, color_k, -1, lineType=cv2.LINE_AA)\n\n        if kpt_line:\n            ndim = kpts.shape[-1]\n            for i, sk in enumerate(self.skeleton):\n                pos1 = (int(kpts[(sk[0] - 1), 0]), int(kpts[(sk[0] - 1), 1]))\n                pos2 = (int(kpts[(sk[1] - 1), 0]), int(kpts[(sk[1] - 1), 1]))\n                if ndim == 3:\n                    conf1 = kpts[(sk[0] - 1), 2]\n                    conf2 = kpts[(sk[1] - 1), 2]\n                    if conf1 < 0.5 or conf2 < 0.5:\n                        continue\n                if pos1[0] % shape[1] == 0 or pos1[1] % shape[0] == 0 or pos1[0] < 0 or pos1[1] < 0:\n                    continue\n                if pos2[0] % shape[1] == 0 or pos2[1] % shape[0] == 0 or pos2[0] < 0 or pos2[1] < 0:\n                    continue\n                cv2.line(self.im, pos1, pos2, [int(x) for x in self.limb_color[i]], thickness=2, lineType=cv2.LINE_AA)\n        if self.pil:\n            # Convert im back to PIL and update draw\n            self.fromarray(self.im)\n\n    def rectangle(self, xy, fill=None, outline=None, width=1):\n        \"\"\"Add rectangle to image (PIL-only).\"\"\"\n        self.draw.rectangle(xy, fill, outline, width)\n\n    def text(self, xy, text, txt_color=(255, 255, 255), anchor='top', box_style=False):\n        \"\"\"Adds text to an image using PIL or cv2.\"\"\"\n        if anchor == 'bottom':  # start y from font bottom\n            w, h = self.font.getsize(text)  # text width, height\n            xy[1] += 1 - h\n        if self.pil:\n            if box_style:\n                w, h = self.font.getsize(text)\n                self.draw.rectangle((xy[0], xy[1], xy[0] + w + 1, xy[1] + h + 1), fill=txt_color)\n                # Using `txt_color` for background and draw fg with white color\n                txt_color = (255, 255, 255)\n            self.draw.text(xy, text, fill=txt_color, font=self.font)\n        else:\n            if box_style:\n                tf = max(self.lw - 1, 1)  # font thickness\n                w, h = cv2.getTextSize(text, 0, fontScale=self.lw / 3, thickness=tf)[0]  # text width, height\n                outside = xy[1] - h >= 3\n                p2 = xy[0] + w, xy[1] - h - 3 if outside else xy[1] + h + 3\n                cv2.rectangle(self.im, xy, p2, txt_color, -1, cv2.LINE_AA)  # filled\n                # Using `txt_color` for background and draw fg with white color\n                txt_color = (255, 255, 255)\n            tf = max(self.lw - 1, 1)  # font thickness\n            cv2.putText(self.im, text, xy, 0, self.lw / 3, txt_color, thickness=tf, lineType=cv2.LINE_AA)\n\n    def fromarray(self, im):\n        \"\"\"Update self.im from a numpy array.\"\"\"\n        self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)\n        self.draw = ImageDraw.Draw(self.im)\n\n    def result(self):\n        \"\"\"Return annotated image as array.\"\"\"\n        return np.asarray(self.im)\n\n\n@TryExcept()  # known issue https://github.com/ultralytics/yolov5/issues/5395\n@plt_settings()\ndef plot_labels(boxes, cls, names=(), save_dir=Path(''), on_plot=None):\n    \"\"\"Save and plot image with no axis or spines.\"\"\"\n    import pandas as pd\n    import seaborn as sn\n\n    # Plot dataset labels\n    LOGGER.info(f\"Plotting labels to {save_dir / 'labels.jpg'}... \")\n    b = boxes.transpose()  # classes, boxes\n    nc = int(cls.max() + 1)  # number of classes\n    x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])\n\n    # Seaborn correlogram\n    sn.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))\n    fname = save_dir / 'labels_correlogram_0.jpg'\n    count = 0\n    while True:\n        if not os.path.exists(fname):\n            break\n        count += 1\n        fname = save_dir / f'labels_correlogram_{count}.jpg'\n    plt.savefig(fname, dpi=200)\n    plt.close()\n\n    # Matplotlib labels\n    ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()\n    y = ax[0].hist(cls, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)\n    with contextlib.suppress(Exception):  # color histogram bars by class\n        [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)]  # known issue #3195\n    ax[0].set_ylabel('instances')\n    if 0 < len(names) < 30:\n        ax[0].set_xticks(range(len(names)))\n        ax[0].set_xticklabels(list(names.values()), rotation=90, fontsize=10)\n    else:\n        ax[0].set_xlabel('classes')\n    sn.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)\n    sn.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)\n\n    # Rectangles\n    boxes[:, 0:2] = 0.5  # center\n    boxes = xywh2xyxy(boxes) * 1000\n    img = Image.fromarray(np.ones((1000, 1000, 3), dtype=np.uint8) * 255)\n    for cls, box in zip(cls[:500], boxes[:500]):\n        ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls))  # plot\n    ax[1].imshow(img)\n    ax[1].axis('off')\n\n    for a in [0, 1, 2, 3]:\n        for s in ['top', 'right', 'left', 'bottom']:\n            ax[a].spines[s].set_visible(False)\n\n    fname = save_dir / 'labels_0.jpg'\n    count = 0\n    while True:\n        if not os.path.exists(fname):\n            break\n        count += 1\n        fname = save_dir / f'labels_{count}.jpg'\n\n    plt.savefig(fname, dpi=200)\n    plt.close()\n    if on_plot:\n        on_plot(fname)\n\n\ndef save_one_box(xyxy, im, file=Path('im.jpg'), gain=1.02, pad=10, square=False, BGR=False, save=True):\n    \"\"\"Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop.\"\"\"\n    b = xyxy2xywh(xyxy.view(-1, 4))  # boxes\n    if square:\n        b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1)  # attempt rectangle to square\n    b[:, 2:] = b[:, 2:] * gain + pad  # box wh * gain + pad\n    xyxy = xywh2xyxy(b).long()\n    clip_boxes(xyxy, im.shape)\n    crop = im[int(xyxy[0, 1]):int(xyxy[0, 3]), int(xyxy[0, 0]):int(xyxy[0, 2]), ::(1 if BGR else -1)]\n    if save:\n        file.parent.mkdir(parents=True, exist_ok=True)  # make directory\n        f = str(increment_path(file).with_suffix('.jpg'))\n        # cv2.imwrite(f, crop)  # save BGR, https://github.com/ultralytics/yolov5/issues/7007 chroma subsampling issue\n        Image.fromarray(crop[..., ::-1]).save(f, quality=95, subsampling=0)  # save RGB\n    return crop\n\n@threaded\ndef plot_images(images,\n                batch_idx,\n                cls,\n                bboxes=np.zeros(0, dtype=np.float32),\n                masks=np.zeros(0, dtype=np.uint8),\n                kpts=np.zeros((0, 51), dtype=np.float32),\n                paths=None,\n                fname='images.jpg',\n                names=None,\n                on_plot=None):\n    # Plot image grid with labels\n    if isinstance(images, torch.Tensor):\n        images = images.cpu().float().numpy()\n    if isinstance(cls, torch.Tensor):\n        cls = cls.cpu().numpy()\n    if isinstance(bboxes, torch.Tensor):\n        bboxes = bboxes.cpu().numpy()\n    if isinstance(masks, torch.Tensor):\n        masks = masks.cpu().numpy().astype(int)\n    if isinstance(kpts, torch.Tensor):\n        kpts = kpts.cpu().numpy()\n    if isinstance(batch_idx, torch.Tensor):\n        batch_idx = batch_idx.cpu().numpy()\n\n    max_size = 1920  # max image size\n    max_subplots = 16  # max image subplots, i.e. 4x4\n    bs, _, h, w = images.shape  # batch size, _, height, width\n    bs = min(bs, max_subplots)  # limit plot images\n    ns = np.ceil(bs ** 0.5)  # number of subplots (square)\n    if np.max(images[0]) <= 1:\n        images *= 255  # de-normalise (optional)\n\n    # Build Image\n    mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8)  # init\n    for i, im in enumerate(images):\n        if i == max_subplots:  # if last batch has fewer images than we expect\n            break\n        x, y = int(w * (i // ns)), int(h * (i % ns))  # block origin\n        im = im.transpose(1, 2, 0)\n        mosaic[y:y + h, x:x + w, :] = im\n\n    # Resize (optional)\n    scale = max_size / ns / max(h, w)\n    if scale < 1:\n        h = math.ceil(scale * h)\n        w = math.ceil(scale * w)\n        mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))\n\n    # Annotate\n    fs = int((h + w) * ns * 0.01)  # font size\n    annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=names)\n    for i in range(i + 1):\n        x, y = int(w * (i // ns)), int(h * (i % ns))  # block origin\n        annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2)  # borders\n        if paths:\n            annotator.text((x + 5, y + 5), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220))  # filenames\n        if len(cls) > 0:\n            idx = batch_idx == i\n            classes = cls[idx].astype('int')\n\n            if len(bboxes):\n                boxes = xywh2xyxy(bboxes[idx, :4]).T\n                labels = bboxes.shape[1] == 4  # labels if no conf column\n                conf = None if labels else bboxes[idx, 4]  # check for confidence presence (label vs pred)\n\n                if boxes.shape[1]:\n                    if boxes.max() <= 1.01:  # if normalized with tolerance 0.01\n                        boxes[[0, 2]] *= w  # scale to pixels\n                        boxes[[1, 3]] *= h\n                    elif scale < 1:  # absolute coords need scale if image scales\n                        boxes *= scale\n                boxes[[0, 2]] += x\n                boxes[[1, 3]] += y\n                for j, box in enumerate(boxes.T.tolist()):\n                    c = classes[j]\n                    color = colors(c)\n                    c = names.get(c, c) if names else c\n                    if labels or conf[j] > 0.25:  # 0.25 conf thresh\n                        label = f'{c}' if labels else f'{c} {conf[j]:.1f}'\n                        # annotator.box_label(box, label, color=color)\n                        annotator.box_label(box, color=color)\n            elif len(classes):\n                for c in classes:\n                    color = colors(c)\n                    c = names.get(c, c) if names else c\n                    annotator.text((x, y), f'{c}', txt_color=color, box_style=True)\n\n            # Plot keypoints\n            if len(kpts):\n                kpts_ = kpts[idx].copy()\n                if len(kpts_):\n                    if kpts_[..., 0].max() <= 1.01 or kpts_[..., 1].max() <= 1.01:  # if normalized with tolerance .01\n                        kpts_[..., 0] *= w  # scale to pixels\n                        kpts_[..., 1] *= h\n                    elif scale < 1:  # absolute coords need scale if image scales\n                        kpts_ *= scale\n                kpts_[..., 0] += x\n                kpts_[..., 1] += y\n                for j in range(len(kpts_)):\n                    if labels or conf[j] > 0.25:  # 0.25 conf thresh\n                        annotator.kpts(kpts_[j])\n\n            # Plot masks\n            if len(masks):\n                if idx.shape[0] == masks.shape[0]:  # overlap_masks=False\n                    image_masks = masks[idx]\n                else:  # overlap_masks=True\n                    image_masks = masks[[i]]  # (1, 640, 640)\n                    nl = idx.sum()\n                    index = np.arange(nl).reshape((nl, 1, 1)) + 1\n                    image_masks = np.repeat(image_masks, nl, axis=0)\n                    image_masks = np.where(image_masks == index, 1.0, 0.0)\n\n                im = np.asarray(annotator.im).copy()\n                for j, box in enumerate(boxes.T.tolist()):\n                    if labels or conf[j] > 0.25:  # 0.25 conf thresh\n                        color = colors(classes[j])\n                        mh, mw = image_masks[j].shape\n                        if mh != h or mw != w:\n                            mask = image_masks[j].astype(np.uint8)\n                            mask = cv2.resize(mask, (w, h))\n                            mask = mask.astype(bool)\n                        else:\n                            mask = image_masks[j].astype(bool)\n                        with contextlib.suppress(Exception):\n                            im[y:y + h, x:x + w, :][mask] = im[y:y + h, x:x + w, :][mask] * 0.4 + np.array(color) * 0.6\n                annotator.fromarray(im)\n    annotator.im.save(fname)  # save\n    if on_plot:\n        on_plot(fname)\n\n\n@threaded\ndef plot_images_seg(images,\n                masks=np.zeros(0, dtype=np.uint8),\n                paths=None,\n                fname='images.jpg',\n                on_plot=None):\n    # Plot image grid with labels\n    if isinstance(images, torch.Tensor):\n        images = images.cpu().float().numpy()\n\n\n    if isinstance(masks, torch.Tensor):\n        masks = masks.cpu().numpy().astype(int)\n\n\n    max_size = 1920  # max image size\n    max_subplots = 16  # max image subplots, i.e. 4x4\n    bs, _, h, w = images.shape  # batch size, _, height, width\n    bs = min(bs, max_subplots)  # limit plot images\n    ns = np.ceil(bs ** 0.5)  # number of subplots (square)\n    if np.max(images[0]) <= 1:\n        images *= 255  # de-normalise (optional)\n\n    # Build Image\n    mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8)  # init\n    for i, im in enumerate(images):\n        if i == max_subplots:  # if last batch has fewer images than we expect\n            break\n        x, y = int(w * (i // ns)), int(h * (i % ns))  # block origin\n        im = im.transpose(1, 2, 0)\n        mosaic[y:y + h, x:x + w, :] = im\n\n    # Resize (optional)\n    scale = max_size / ns / max(h, w)\n    if scale < 1:\n        h = math.ceil(scale * h)\n        w = math.ceil(scale * w)\n        mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))\n\n    # Annotate\n    fs = int((h + w) * ns * 0.01)  # font size\n    annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=names)\n    for i in range(bs):\n        x, y = int(w * (i // ns)), int(h * (i % ns))  # block origin\n        annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2)  # borders\n        if paths:\n            annotator.text((x + 5, y + 5), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220))  # filenames\n            # Plot masks\n\n            image_masks = masks[i]\n            im = np.asarray(annotator.im).copy()\n            mh, mw = image_masks.shape\n            color = colors(0)\n            if mh != h or mw != w:\n                mask = image_masks.astype(np.uint8)\n                mask = cv2.resize(mask, (w, h))\n                mask = mask.astype(bool)\n            else:\n                mask = image_masks.astype(bool)\n            with contextlib.suppress(Exception):\n                im[y:y + h, x:x + w, :][mask] = im[y:y + h, x:x + w, :][mask] * 0.4 + np.array(color) * 0.6\n            annotator.fromarray(im)\n    annotator.im.save(fname)  # save\n    if on_plot:\n        on_plot(fname)\n\n\n@plt_settings()\ndef plot_results(file='path/to/results.csv', dir='', segment=False, pose=False, classify=False, on_plot=None):\n    \"\"\"Plot training results.csv. Usage: from utils.plots import *; plot_results('path/to/results.csv').\"\"\"\n    import pandas as pd\n    save_dir = Path(file).parent if file else Path(dir)\n    if classify:\n        fig, ax = plt.subplots(2, 2, figsize=(6, 6), tight_layout=True)\n        index = [1, 4, 2, 3]\n    elif segment:\n        fig, ax = plt.subplots(2, 8, figsize=(18, 6), tight_layout=True)\n        index = [1, 2, 3, 4, 5, 6, 9, 10, 13, 14, 15, 16, 7, 8, 11, 12]\n    elif pose:\n        fig, ax = plt.subplots(2, 9, figsize=(21, 6), tight_layout=True)\n        index = [1, 2, 3, 4, 5, 6, 7, 10, 11, 14, 15, 16, 17, 18, 8, 9, 12, 13]\n    else:\n        fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)\n        index = [1, 2, 3, 4, 5, 8, 9, 10, 6, 7]\n    ax = ax.ravel()\n    files = list(save_dir.glob('results*.csv'))\n    assert len(files), f'No results.csv files found in {save_dir.resolve()}, nothing to plot.'\n    for f in files:\n        try:\n            data = pd.read_csv(f)\n            s = [x.strip() for x in data.columns]\n            x = data.values[:, 0]\n            for i, j in enumerate(index):\n                y = data.values[:, j].astype('float')\n                # y[y == 0] = np.nan  # don't show zero values\n                ax[i].plot(x, y, marker='.', label=f.stem, linewidth=2, markersize=8)\n                ax[i].set_title(s[j], fontsize=12)\n                # if j in [8, 9, 10]:  # share train and val loss y axes\n                #     ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])\n        except Exception as e:\n            LOGGER.warning(f'WARNING: Plotting error for {f}: {e}')\n    ax[1].legend()\n    fname = save_dir / 'results.png'\n    fig.savefig(fname, dpi=200)\n    plt.close()\n    if on_plot:\n        on_plot(fname)\n\n\ndef output_to_target(output, max_det=300):\n    \"\"\"Convert model output to target format [batch_id, class_id, x, y, w, h, conf] for plotting.\"\"\"\n    targets = []\n    for i, o in enumerate(output):\n        box, conf, cls = o[:max_det, :6].cpu().split((4, 1, 1), 1)\n        j = torch.full((conf.shape[0], 1), i)\n        targets.append(torch.cat((j, cls, xyxy2xywh(box), conf), 1))\n    targets = torch.cat(targets, 0).numpy()\n    return targets[:, 0], targets[:, 1], targets[:, 2:]\n\n\ndef feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')):\n    \"\"\"\n    Visualize feature maps of a given model module during inference.\n\n    Args:\n        x (torch.Tensor): Features to be visualized.\n        module_type (str): Module type.\n        stage (int): Module stage within the model.\n        n (int, optional): Maximum number of feature maps to plot. Defaults to 32.\n        save_dir (Path, optional): Directory to save results. Defaults to Path('runs/detect/exp').\n    \"\"\"\n    for m in ['Detect', 'Pose', 'Segment']:\n        if m in module_type:\n            return\n    batch, channels, height, width = x.shape  # batch, channels, height, width\n    if height > 1 and width > 1:\n        f = save_dir / f\"stage{stage}_{module_type.split('.')[-1]}_features.png\"  # filename\n\n        blocks = torch.chunk(x[0].cpu(), channels, dim=0)  # select batch index 0, block by channels\n        n = min(n, channels)  # number of plots\n        fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True)  # 8 rows x n/8 cols\n        ax = ax.ravel()\n        plt.subplots_adjust(wspace=0.05, hspace=0.05)\n        for i in range(n):\n            ax[i].imshow(blocks[i].squeeze())  # cmap='gray'\n            ax[i].axis('off')\n\n        LOGGER.info(f'Saving {f}... ({n}/{channels})')\n        plt.savefig(f, dpi=300, bbox_inches='tight')\n        plt.close()\n        np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy())  # npy save\n"
  },
  {
    "path": "ultralytics/yolo/utils/tal.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\nimport torch.nn as nn\n\nfrom .checks import check_version\nfrom .metrics import bbox_iou\n\nTORCH_1_10 = check_version(torch.__version__, '1.10.0')\n\n\ndef select_candidates_in_gts(xy_centers, gt_bboxes, eps=1e-9):\n    \"\"\"select the positive anchor center in gt\n\n    Args:\n        xy_centers (Tensor): shape(h*w, 4)\n        gt_bboxes (Tensor): shape(b, n_boxes, 4)\n    Return:\n        (Tensor): shape(b, n_boxes, h*w)\n    \"\"\"\n    n_anchors = xy_centers.shape[0]\n    bs, n_boxes, _ = gt_bboxes.shape\n    lt, rb = gt_bboxes.view(-1, 1, 4).chunk(2, 2)  # left-top, right-bottom\n    bbox_deltas = torch.cat((xy_centers[None] - lt, rb - xy_centers[None]), dim=2).view(bs, n_boxes, n_anchors, -1)\n    # return (bbox_deltas.min(3)[0] > eps).to(gt_bboxes.dtype)\n    return bbox_deltas.amin(3).gt_(eps)\n\n\ndef select_highest_overlaps(mask_pos, overlaps, n_max_boxes):\n    \"\"\"if an anchor box is assigned to multiple gts,\n        the one with the highest iou will be selected.\n\n    Args:\n        mask_pos (Tensor): shape(b, n_max_boxes, h*w)\n        overlaps (Tensor): shape(b, n_max_boxes, h*w)\n    Return:\n        target_gt_idx (Tensor): shape(b, h*w)\n        fg_mask (Tensor): shape(b, h*w)\n        mask_pos (Tensor): shape(b, n_max_boxes, h*w)\n    \"\"\"\n    # (b, n_max_boxes, h*w) -> (b, h*w)\n    fg_mask = mask_pos.sum(-2)\n    if fg_mask.max() > 1:  # one anchor is assigned to multiple gt_bboxes\n        mask_multi_gts = (fg_mask.unsqueeze(1) > 1).repeat([1, n_max_boxes, 1])  # (b, n_max_boxes, h*w)\n        max_overlaps_idx = overlaps.argmax(1)  # (b, h*w)\n\n        is_max_overlaps = torch.zeros(mask_pos.shape, dtype=mask_pos.dtype, device=mask_pos.device)\n        is_max_overlaps.scatter_(1, max_overlaps_idx.unsqueeze(1), 1)\n\n        mask_pos = torch.where(mask_multi_gts, is_max_overlaps, mask_pos).float()  # (b, n_max_boxes, h*w)\n        fg_mask = mask_pos.sum(-2)\n    # Find each grid serve which gt(index)\n    target_gt_idx = mask_pos.argmax(-2)  # (b, h*w)\n    return target_gt_idx, fg_mask, mask_pos\n\n\nclass TaskAlignedAssigner(nn.Module):\n    \"\"\"\n    A task-aligned assigner for object detection.\n\n    This class assigns ground-truth (gt) objects to anchors based on the task-aligned metric,\n    which combines both classification and localization information.\n\n    Attributes:\n        topk (int): The number of top candidates to consider.\n        num_classes (int): The number of object classes.\n        alpha (float): The alpha parameter for the classification component of the task-aligned metric.\n        beta (float): The beta parameter for the localization component of the task-aligned metric.\n        eps (float): A small value to prevent division by zero.\n    \"\"\"\n\n    def __init__(self, topk=13, num_classes=80, alpha=1.0, beta=6.0, eps=1e-9):\n        \"\"\"Initialize a TaskAlignedAssigner object with customizable hyperparameters.\"\"\"\n        super().__init__()\n        self.topk = topk\n        self.num_classes = num_classes\n        self.bg_idx = num_classes\n        self.alpha = alpha\n        self.beta = beta\n        self.eps = eps\n\n    @torch.no_grad()\n    def forward(self, pd_scores, pd_bboxes, anc_points, gt_labels, gt_bboxes, mask_gt):\n        \"\"\"\n        Compute the task-aligned assignment.\n        Reference https://github.com/Nioolek/PPYOLOE_pytorch/blob/master/ppyoloe/assigner/tal_assigner.py\n\n        Args:\n            pd_scores (Tensor): shape(bs, num_total_anchors, num_classes)\n            pd_bboxes (Tensor): shape(bs, num_total_anchors, 4)\n            anc_points (Tensor): shape(num_total_anchors, 2)\n            gt_labels (Tensor): shape(bs, n_max_boxes, 1)\n            gt_bboxes (Tensor): shape(bs, n_max_boxes, 4)\n            mask_gt (Tensor): shape(bs, n_max_boxes, 1)\n\n        Returns:\n            target_labels (Tensor): shape(bs, num_total_anchors)\n            target_bboxes (Tensor): shape(bs, num_total_anchors, 4)\n            target_scores (Tensor): shape(bs, num_total_anchors, num_classes)\n            fg_mask (Tensor): shape(bs, num_total_anchors)\n            target_gt_idx (Tensor): shape(bs, num_total_anchors)\n        \"\"\"\n        self.bs = pd_scores.size(0)\n        self.n_max_boxes = gt_bboxes.size(1)\n\n        if self.n_max_boxes == 0:\n            device = gt_bboxes.device\n            return (torch.full_like(pd_scores[..., 0], self.bg_idx).to(device), torch.zeros_like(pd_bboxes).to(device),\n                    torch.zeros_like(pd_scores).to(device), torch.zeros_like(pd_scores[..., 0]).to(device),\n                    torch.zeros_like(pd_scores[..., 0]).to(device))\n\n        mask_pos, align_metric, overlaps = self.get_pos_mask(pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points,\n                                                             mask_gt)\n\n        target_gt_idx, fg_mask, mask_pos = select_highest_overlaps(mask_pos, overlaps, self.n_max_boxes)\n\n        # Assigned target\n        target_labels, target_bboxes, target_scores = self.get_targets(gt_labels, gt_bboxes, target_gt_idx, fg_mask)\n\n        # Normalize\n        align_metric *= mask_pos\n        pos_align_metrics = align_metric.amax(axis=-1, keepdim=True)  # b, max_num_obj\n        pos_overlaps = (overlaps * mask_pos).amax(axis=-1, keepdim=True)  # b, max_num_obj\n        norm_align_metric = (align_metric * pos_overlaps / (pos_align_metrics + self.eps)).amax(-2).unsqueeze(-1)\n        target_scores = target_scores * norm_align_metric\n\n        return target_labels, target_bboxes, target_scores, fg_mask.bool(), target_gt_idx\n\n    def get_pos_mask(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, anc_points, mask_gt):\n        \"\"\"Get in_gts mask, (b, max_num_obj, h*w).\"\"\"\n        mask_in_gts = select_candidates_in_gts(anc_points, gt_bboxes)\n        # Get anchor_align metric, (b, max_num_obj, h*w)\n        align_metric, overlaps = self.get_box_metrics(pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_in_gts * mask_gt)\n        # Get topk_metric mask, (b, max_num_obj, h*w)\n        mask_topk = self.select_topk_candidates(align_metric, topk_mask=mask_gt.repeat([1, 1, self.topk]).bool())\n        # Merge all mask to a final mask, (b, max_num_obj, h*w)\n        mask_pos = mask_topk * mask_in_gts * mask_gt\n\n        return mask_pos, align_metric, overlaps\n\n    def get_box_metrics(self, pd_scores, pd_bboxes, gt_labels, gt_bboxes, mask_gt):\n        \"\"\"Compute alignment metric given predicted and ground truth bounding boxes.\"\"\"\n        na = pd_bboxes.shape[-2]\n        mask_gt = mask_gt.bool()  # b, max_num_obj, h*w\n        overlaps = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_bboxes.dtype, device=pd_bboxes.device)\n        bbox_scores = torch.zeros([self.bs, self.n_max_boxes, na], dtype=pd_scores.dtype, device=pd_scores.device)\n\n        ind = torch.zeros([2, self.bs, self.n_max_boxes], dtype=torch.long)  # 2, b, max_num_obj\n        ind[0] = torch.arange(end=self.bs).view(-1, 1).repeat(1, self.n_max_boxes)  # b, max_num_obj\n        ind[1] = gt_labels.long().squeeze(-1)  # b, max_num_obj\n        # Get the scores of each grid for each gt cls\n        bbox_scores[mask_gt] = pd_scores[ind[0], :, ind[1]][mask_gt]  # b, max_num_obj, h*w\n\n        # (b, max_num_obj, 1, 4), (b, 1, h*w, 4)\n        pd_boxes = pd_bboxes.unsqueeze(1).repeat(1, self.n_max_boxes, 1, 1)[mask_gt]\n        gt_boxes = gt_bboxes.unsqueeze(2).repeat(1, 1, na, 1)[mask_gt]\n        overlaps[mask_gt] = bbox_iou(gt_boxes, pd_boxes, xywh=False, CIoU=True).squeeze(-1).clamp(0)\n\n        align_metric = bbox_scores.pow(self.alpha) * overlaps.pow(self.beta)\n        return align_metric, overlaps\n\n    def select_topk_candidates(self, metrics, largest=True, topk_mask=None):\n        \"\"\"\n        Select the top-k candidates based on the given metrics.\n\n        Args:\n            metrics (Tensor): A tensor of shape (b, max_num_obj, h*w), where b is the batch size,\n                              max_num_obj is the maximum number of objects, and h*w represents the\n                              total number of anchor points.\n            largest (bool): If True, select the largest values; otherwise, select the smallest values.\n            topk_mask (Tensor): An optional boolean tensor of shape (b, max_num_obj, topk), where\n                                topk is the number of top candidates to consider. If not provided,\n                                the top-k values are automatically computed based on the given metrics.\n\n        Returns:\n            (Tensor): A tensor of shape (b, max_num_obj, h*w) containing the selected top-k candidates.\n        \"\"\"\n\n        # (b, max_num_obj, topk)\n        topk_metrics, topk_idxs = torch.topk(metrics, self.topk, dim=-1, largest=largest)\n        if topk_mask is None:\n            topk_mask = (topk_metrics.max(-1, keepdim=True)[0] > self.eps).expand_as(topk_idxs)\n        # (b, max_num_obj, topk)\n        topk_idxs.masked_fill_(~topk_mask, 0)\n\n        # (b, max_num_obj, topk, h*w) -> (b, max_num_obj, h*w)\n        count_tensor = torch.zeros(metrics.shape, dtype=torch.int8, device=topk_idxs.device)\n        ones = torch.ones_like(topk_idxs[:, :, :1], dtype=torch.int8, device=topk_idxs.device)\n        for k in range(self.topk):\n            # Expand topk_idxs for each value of k and add 1 at the specified positions\n            count_tensor.scatter_add_(-1, topk_idxs[:, :, k:k + 1], ones)\n        # count_tensor.scatter_add_(-1, topk_idxs, torch.ones_like(topk_idxs, dtype=torch.int8, device=topk_idxs.device))\n        # filter invalid bboxes\n        count_tensor.masked_fill_(count_tensor > 1, 0)\n\n        return count_tensor.to(metrics.dtype)\n\n    def get_targets(self, gt_labels, gt_bboxes, target_gt_idx, fg_mask):\n        \"\"\"\n        Compute target labels, target bounding boxes, and target scores for the positive anchor points.\n\n        Args:\n            gt_labels (Tensor): Ground truth labels of shape (b, max_num_obj, 1), where b is the\n                                batch size and max_num_obj is the maximum number of objects.\n            gt_bboxes (Tensor): Ground truth bounding boxes of shape (b, max_num_obj, 4).\n            target_gt_idx (Tensor): Indices of the assigned ground truth objects for positive\n                                    anchor points, with shape (b, h*w), where h*w is the total\n                                    number of anchor points.\n            fg_mask (Tensor): A boolean tensor of shape (b, h*w) indicating the positive\n                              (foreground) anchor points.\n\n        Returns:\n            (Tuple[Tensor, Tensor, Tensor]): A tuple containing the following tensors:\n                - target_labels (Tensor): Shape (b, h*w), containing the target labels for\n                                          positive anchor points.\n                - target_bboxes (Tensor): Shape (b, h*w, 4), containing the target bounding boxes\n                                          for positive anchor points.\n                - target_scores (Tensor): Shape (b, h*w, num_classes), containing the target scores\n                                          for positive anchor points, where num_classes is the number\n                                          of object classes.\n        \"\"\"\n\n        # Assigned target labels, (b, 1)\n        batch_ind = torch.arange(end=self.bs, dtype=torch.int64, device=gt_labels.device)[..., None]\n        target_gt_idx = target_gt_idx + batch_ind * self.n_max_boxes  # (b, h*w)\n        target_labels = gt_labels.long().flatten()[target_gt_idx]  # (b, h*w)\n\n        # Assigned target boxes, (b, max_num_obj, 4) -> (b, h*w)\n        target_bboxes = gt_bboxes.view(-1, 4)[target_gt_idx]\n\n        # Assigned target scores\n        target_labels.clamp_(0)\n\n        # 10x faster than F.one_hot()\n        target_scores = torch.zeros((target_labels.shape[0], target_labels.shape[1], self.num_classes),\n                                    dtype=torch.int64,\n                                    device=target_labels.device)  # (b, h*w, 80)\n        target_scores.scatter_(2, target_labels.unsqueeze(-1), 1)\n\n        fg_scores_mask = fg_mask[:, :, None].repeat(1, 1, self.num_classes)  # (b, h*w, 80)\n        target_scores = torch.where(fg_scores_mask > 0, target_scores, 0)\n\n        return target_labels, target_bboxes, target_scores\n\n\ndef make_anchors(feats, strides, grid_cell_offset=0.5):\n    \"\"\"Generate anchors from features.\"\"\"\n    anchor_points, stride_tensor = [], []\n    assert feats is not None\n    dtype, device = feats[0].dtype, feats[0].device\n    for i, stride in enumerate(strides):\n        _, _, h, w = feats[i].shape\n        sx = torch.arange(end=w, device=device, dtype=dtype) + grid_cell_offset  # shift x\n        sy = torch.arange(end=h, device=device, dtype=dtype) + grid_cell_offset  # shift y\n        sy, sx = torch.meshgrid(sy, sx, indexing='ij') if TORCH_1_10 else torch.meshgrid(sy, sx)\n        anchor_points.append(torch.stack((sx, sy), -1).view(-1, 2))\n        stride_tensor.append(torch.full((h * w, 1), stride, dtype=dtype, device=device))\n    return torch.cat(anchor_points), torch.cat(stride_tensor)\n\n\ndef dist2bbox(distance, anchor_points, xywh=True, dim=-1):\n    \"\"\"Transform distance(ltrb) to box(xywh or xyxy).\"\"\"\n    lt, rb = distance.chunk(2, dim)\n    x1y1 = anchor_points - lt\n    x2y2 = anchor_points + rb\n    if xywh:\n        c_xy = (x1y1 + x2y2) / 2\n        wh = x2y2 - x1y1\n        return torch.cat((c_xy, wh), dim)  # xywh bbox\n    return torch.cat((x1y1, x2y2), dim)  # xyxy bbox\n\n\ndef bbox2dist(anchor_points, bbox, reg_max):\n    \"\"\"Transform bbox(xyxy) to dist(ltrb).\"\"\"\n    x1y1, x2y2 = bbox.chunk(2, -1)\n    return torch.cat((anchor_points - x1y1, x2y2 - anchor_points), -1).clamp(0, reg_max - 0.01)  # dist (lt, rb)\n"
  },
  {
    "path": "ultralytics/yolo/utils/torch_utils.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport math\nimport os\nimport platform\nimport random\nimport time\nfrom contextlib import contextmanager\nfrom copy import deepcopy\nfrom pathlib import Path\nfrom typing import Union\n\nimport numpy as np\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\n\nfrom ultralytics.yolo.utils import DEFAULT_CFG_DICT, DEFAULT_CFG_KEYS, LOGGER, RANK, __version__\nfrom ultralytics.yolo.utils.checks import check_version\n\ntry:\n    import thop\nexcept ImportError:\n    thop = None\n\nTORCHVISION_0_10 = check_version(torchvision.__version__, '0.10.0')\nTORCH_1_9 = check_version(torch.__version__, '1.9.0')\nTORCH_1_11 = check_version(torch.__version__, '1.11.0')\nTORCH_1_12 = check_version(torch.__version__, '1.12.0')\nTORCH_2_0 = check_version(torch.__version__, minimum='2.0')\n\n\n@contextmanager\ndef torch_distributed_zero_first(local_rank: int):\n    \"\"\"Decorator to make all processes in distributed training wait for each local_master to do something.\"\"\"\n    initialized = torch.distributed.is_available() and torch.distributed.is_initialized()\n    if initialized and local_rank not in (-1, 0):\n        dist.barrier(device_ids=[local_rank])\n    yield\n    if initialized and local_rank == 0:\n        dist.barrier(device_ids=[0])\n\n\ndef smart_inference_mode():\n    \"\"\"Applies torch.inference_mode() decorator if torch>=1.9.0 else torch.no_grad() decorator.\"\"\"\n\n    def decorate(fn):\n        \"\"\"Applies appropriate torch decorator for inference mode based on torch version.\"\"\"\n        return (torch.inference_mode if TORCH_1_9 else torch.no_grad)()(fn)\n\n    return decorate\n\n\ndef select_device(device='', batch=0, newline=False, verbose=True):\n    \"\"\"Selects PyTorch Device. Options are device = None or 'cpu' or 0 or '0' or '0,1,2,3'.\"\"\"\n    s = f'Ultralytics YOLOv{__version__} 🚀 Python-{platform.python_version()} torch-{torch.__version__} '\n    device = str(device).lower()\n    for remove in 'cuda:', 'none', '(', ')', '[', ']', \"'\", ' ':\n        device = device.replace(remove, '')  # to string, 'cuda:0' -> '0' and '(0, 1)' -> '0,1'\n    cpu = device == 'cpu'\n    mps = device == 'mps'  # Apple Metal Performance Shaders (MPS)\n    if cpu or mps:\n        os.environ['CUDA_VISIBLE_DEVICES'] = '-1'  # force torch.cuda.is_available() = False\n    elif device:  # non-cpu device requested\n        visible = os.environ.get('CUDA_VISIBLE_DEVICES', None)\n        os.environ['CUDA_VISIBLE_DEVICES'] = device  # set environment variable - must be before assert is_available()\n        if not (torch.cuda.is_available() and torch.cuda.device_count() >= len(device.replace(',', ''))):\n            LOGGER.info(s)\n            install = 'See https://pytorch.org/get-started/locally/ for up-to-date torch install instructions if no ' \\\n                      'CUDA devices are seen by torch.\\n' if torch.cuda.device_count() == 0 else ''\n            raise ValueError(f\"Invalid CUDA 'device={device}' requested.\"\n                             f\" Use 'device=cpu' or pass valid CUDA device(s) if available,\"\n                             f\" i.e. 'device=0' or 'device=0,1,2,3' for Multi-GPU.\\n\"\n                             f'\\ntorch.cuda.is_available(): {torch.cuda.is_available()}'\n                             f'\\ntorch.cuda.device_count(): {torch.cuda.device_count()}'\n                             f\"\\nos.environ['CUDA_VISIBLE_DEVICES']: {visible}\\n\"\n                             f'{install}')\n\n    if not cpu and not mps and torch.cuda.is_available():  # prefer GPU if available\n        devices = device.split(',') if device else '0'  # range(torch.cuda.device_count())  # i.e. 0,1,6,7\n        n = len(devices)  # device count\n        if n > 1 and batch > 0 and batch % n != 0:  # check batch_size is divisible by device_count\n            raise ValueError(f\"'batch={batch}' must be a multiple of GPU count {n}. Try 'batch={batch // n * n}' or \"\n                             f\"'batch={batch // n * n + n}', the nearest batch sizes evenly divisible by {n}.\")\n        space = ' ' * (len(s) + 1)\n        for i, d in enumerate(devices):\n            p = torch.cuda.get_device_properties(i)\n            s += f\"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / (1 << 20):.0f}MiB)\\n\"  # bytes to MB\n        arg = 'cuda:0'\n    elif mps and getattr(torch, 'has_mps', False) and torch.backends.mps.is_available() and TORCH_2_0:\n        # Prefer MPS if available\n        s += 'MPS\\n'\n        arg = 'mps'\n    else:  # revert to CPU\n        s += 'CPU\\n'\n        arg = 'cpu'\n\n    if verbose and RANK == -1:\n        LOGGER.info(s if newline else s.rstrip())\n    return torch.device(arg)\n\n\ndef time_sync():\n    \"\"\"PyTorch-accurate time.\"\"\"\n    if torch.cuda.is_available():\n        torch.cuda.synchronize()\n    return time.time()\n\n\ndef fuse_conv_and_bn(conv, bn):\n    \"\"\"Fuse Conv2d() and BatchNorm2d() layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/.\"\"\"\n    fusedconv = nn.Conv2d(conv.in_channels,\n                          conv.out_channels,\n                          kernel_size=conv.kernel_size,\n                          stride=conv.stride,\n                          padding=conv.padding,\n                          dilation=conv.dilation,\n                          groups=conv.groups,\n                          bias=True).requires_grad_(False).to(conv.weight.device)\n\n    # Prepare filters\n    w_conv = conv.weight.clone().view(conv.out_channels, -1)\n    w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))\n    fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))\n\n    # Prepare spatial bias\n    b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias\n    b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))\n    fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)\n\n    return fusedconv\n\n\ndef fuse_deconv_and_bn(deconv, bn):\n    \"\"\"Fuse ConvTranspose2d() and BatchNorm2d() layers.\"\"\"\n    fuseddconv = nn.ConvTranspose2d(deconv.in_channels,\n                                    deconv.out_channels,\n                                    kernel_size=deconv.kernel_size,\n                                    stride=deconv.stride,\n                                    padding=deconv.padding,\n                                    output_padding=deconv.output_padding,\n                                    dilation=deconv.dilation,\n                                    groups=deconv.groups,\n                                    bias=True).requires_grad_(False).to(deconv.weight.device)\n\n    # Prepare filters\n    w_deconv = deconv.weight.clone().view(deconv.out_channels, -1)\n    w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))\n    fuseddconv.weight.copy_(torch.mm(w_bn, w_deconv).view(fuseddconv.weight.shape))\n\n    # Prepare spatial bias\n    b_conv = torch.zeros(deconv.weight.size(1), device=deconv.weight.device) if deconv.bias is None else deconv.bias\n    b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))\n    fuseddconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)\n\n    return fuseddconv\n\n\ndef model_info(model, detailed=False, verbose=True, imgsz=640):\n    \"\"\"Model information. imgsz may be int or list, i.e. imgsz=640 or imgsz=[640, 320].\"\"\"\n    if not verbose:\n        return\n    n_p = get_num_params(model)\n    n_g = get_num_gradients(model)  # number gradients\n    if detailed:\n        LOGGER.info(\n            f\"{'layer':>5} {'name':>40} {'gradient':>9} {'parameters':>12} {'shape':>20} {'mu':>10} {'sigma':>10}\")\n        for i, (name, p) in enumerate(model.named_parameters()):\n            name = name.replace('module_list.', '')\n            LOGGER.info('%5g %40s %9s %12g %20s %10.3g %10.3g %10s' %\n                        (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std(), p.dtype))\n\n    flops = get_flops(model, imgsz)\n    fused = ' (fused)' if model.is_fused() else ''\n    fs = f', {flops:.1f} GFLOPs' if flops else ''\n    m = Path(getattr(model, 'yaml_file', '') or model.yaml.get('yaml_file', '')).stem.replace('yolo', 'YOLO') or 'Model'\n    LOGGER.info(f'{m} summary{fused}: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}')\n    return n_p, flops\n\n\ndef get_num_params(model):\n    \"\"\"Return the total number of parameters in a YOLO model.\"\"\"\n    return sum(x.numel() for x in model.parameters())\n\n\ndef get_num_gradients(model):\n    \"\"\"Return the total number of parameters with gradients in a YOLO model.\"\"\"\n    return sum(x.numel() for x in model.parameters() if x.requires_grad)\n\n\ndef get_flops(model, imgsz=640):\n    \"\"\"Return a YOLO model's FLOPs.\"\"\"\n    try:\n        model = de_parallel(model)\n        p = next(model.parameters())\n        stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32  # max stride\n        im = torch.empty((1, p.shape[1], stride, stride), device=p.device)  # input image in BCHW format\n        flops = thop.profile(deepcopy(model), inputs=[im], verbose=False)[0] / 1E9 * 2 if thop else 0  # stride GFLOPs\n        imgsz = imgsz if isinstance(imgsz, list) else [imgsz, imgsz]  # expand if int/float\n        flops = flops * imgsz[0] / stride * imgsz[1] / stride  # 640x640 GFLOPs\n        return flops\n    except Exception:\n        return 0\n\n\ndef initialize_weights(model):\n    \"\"\"Initialize model weights to random values.\"\"\"\n    for m in model.modules():\n        t = type(m)\n        if t is nn.Conv2d:\n            pass  # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n        elif t is nn.BatchNorm2d:\n            m.eps = 1e-3\n            m.momentum = 0.03\n        elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]:\n            m.inplace = True\n\n\ndef scale_img(img, ratio=1.0, same_shape=False, gs=32):  # img(16,3,256,416)\n    # Scales img(bs,3,y,x) by ratio constrained to gs-multiple\n    if ratio == 1.0:\n        return img\n    h, w = img.shape[2:]\n    s = (int(h * ratio), int(w * ratio))  # new size\n    img = F.interpolate(img, size=s, mode='bilinear', align_corners=False)  # resize\n    if not same_shape:  # pad/crop img\n        h, w = (math.ceil(x * ratio / gs) * gs for x in (h, w))\n    return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447)  # value = imagenet mean\n\n\ndef make_divisible(x, divisor):\n    \"\"\"Returns nearest x divisible by divisor.\"\"\"\n    if isinstance(divisor, torch.Tensor):\n        divisor = int(divisor.max())  # to int\n    return math.ceil(x / divisor) * divisor\n\n\ndef copy_attr(a, b, include=(), exclude=()):\n    \"\"\"Copies attributes from object 'b' to object 'a', with options to include/exclude certain attributes.\"\"\"\n    for k, v in b.__dict__.items():\n        if (len(include) and k not in include) or k.startswith('_') or k in exclude:\n            continue\n        else:\n            setattr(a, k, v)\n\n\ndef get_latest_opset():\n    \"\"\"Return second-most (for maturity) recently supported ONNX opset by this version of torch.\"\"\"\n    return max(int(k[14:]) for k in vars(torch.onnx) if 'symbolic_opset' in k) - 1  # opset\n\n\ndef intersect_dicts(da, db, exclude=()):\n    \"\"\"Returns a dictionary of intersecting keys with matching shapes, excluding 'exclude' keys, using da values.\"\"\"\n    return {k: v for k, v in da.items() if k in db and all(x not in k for x in exclude) and v.shape == db[k].shape}\n\n\ndef is_parallel(model):\n    \"\"\"Returns True if model is of type DP or DDP.\"\"\"\n    return isinstance(model, (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel))\n\n\ndef de_parallel(model):\n    \"\"\"De-parallelize a model: returns single-GPU model if model is of type DP or DDP.\"\"\"\n    return model.module if is_parallel(model) else model\n\n\ndef one_cycle(y1=0.0, y2=1.0, steps=100):\n    \"\"\"Returns a lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf.\"\"\"\n    return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1\n\n\ndef init_seeds(seed=0, deterministic=False):\n    \"\"\"Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html.\"\"\"\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)  # for Multi-GPU, exception safe\n    # torch.backends.cudnn.benchmark = True  # AutoBatch problem https://github.com/ultralytics/yolov5/issues/9287\n    if deterministic:  # https://github.com/ultralytics/yolov5/pull/8213\n        if TORCH_2_0:\n            torch.use_deterministic_algorithms(True)\n            torch.backends.cudnn.deterministic = True\n            os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8'\n            os.environ['PYTHONHASHSEED'] = str(seed)\n        else:\n            LOGGER.warning('WARNING ⚠️ Upgrade to torch>=2.0.0 for deterministic training.')\n\n\nclass ModelEMA:\n    \"\"\"Updated Exponential Moving Average (EMA) from https://github.com/rwightman/pytorch-image-models\n    Keeps a moving average of everything in the model state_dict (parameters and buffers)\n    For EMA details see https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage\n    To disable EMA set the `enabled` attribute to `False`.\n    \"\"\"\n\n    def __init__(self, model, decay=0.9999, tau=2000, updates=0):\n        \"\"\"Create EMA.\"\"\"\n        self.ema = deepcopy(de_parallel(model)).eval()  # FP32 EMA\n        self.updates = updates  # number of EMA updates\n        self.decay = lambda x: decay * (1 - math.exp(-x / tau))  # decay exponential ramp (to help early epochs)\n        for p in self.ema.parameters():\n            p.requires_grad_(False)\n        self.enabled = True\n\n    def update(self, model):\n        \"\"\"Update EMA parameters.\"\"\"\n        if self.enabled:\n            self.updates += 1\n            d = self.decay(self.updates)\n\n            msd = de_parallel(model).state_dict()  # model state_dict\n            for k, v in self.ema.state_dict().items():\n                if v.dtype.is_floating_point:  # true for FP16 and FP32\n                    v *= d\n                    v += (1 - d) * msd[k].detach()\n                    # assert v.dtype == msd[k].dtype == torch.float32, f'{k}: EMA {v.dtype},  model {msd[k].dtype}'\n\n    def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):\n        \"\"\"Updates attributes and saves stripped model with optimizer removed.\"\"\"\n        if self.enabled:\n            copy_attr(self.ema, model, include, exclude)\n\n\ndef strip_optimizer(f: Union[str, Path] = 'best.pt', s: str = '') -> None:\n    \"\"\"\n    Strip optimizer from 'f' to finalize training, optionally save as 's'.\n\n    Args:\n        f (str): file path to model to strip the optimizer from. Default is 'best.pt'.\n        s (str): file path to save the model with stripped optimizer to. If not provided, 'f' will be overwritten.\n\n    Returns:\n        None\n\n    Usage:\n        from pathlib import Path\n        from ultralytics.yolo.utils.torch_utils import strip_optimizer\n        for f in Path('/Users/glennjocher/Downloads/weights').rglob('*.pt'):\n            strip_optimizer(f)\n    \"\"\"\n    x = torch.load(f, map_location=torch.device('cpu'))\n    args = {**DEFAULT_CFG_DICT, **x['train_args']}  # combine model args with default args, preferring model args\n    if x.get('ema'):\n        x['model'] = x['ema']  # replace model with ema\n    for k in 'optimizer', 'best_fitness', 'ema', 'updates':  # keys\n        x[k] = None\n    x['epoch'] = -1\n    x['model'].half()  # to FP16\n    for p in x['model'].parameters():\n        p.requires_grad = False\n    x['train_args'] = {k: v for k, v in args.items() if k in DEFAULT_CFG_KEYS}  # strip non-default keys\n    # x['model'].args = x['train_args']\n    torch.save(x, s or f)\n    mb = os.path.getsize(s or f) / 1E6  # filesize\n    LOGGER.info(f\"Optimizer stripped from {f},{f' saved as {s},' if s else ''} {mb:.1f}MB\")\n\n\ndef profile(input, ops, n=10, device=None):\n    \"\"\"\n    YOLOv8 speed/memory/FLOPs profiler\n\n    Usage:\n        input = torch.randn(16, 3, 640, 640)\n        m1 = lambda x: x * torch.sigmoid(x)\n        m2 = nn.SiLU()\n        profile(input, [m1, m2], n=100)  # profile over 100 iterations\n    \"\"\"\n    results = []\n    if not isinstance(device, torch.device):\n        device = select_device(device)\n    LOGGER.info(f\"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}\"\n                f\"{'input':>24s}{'output':>24s}\")\n\n    for x in input if isinstance(input, list) else [input]:\n        x = x.to(device)\n        x.requires_grad = True\n        for m in ops if isinstance(ops, list) else [ops]:\n            m = m.to(device) if hasattr(m, 'to') else m  # device\n            m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m\n            tf, tb, t = 0, 0, [0, 0, 0]  # dt forward, backward\n            try:\n                flops = thop.profile(m, inputs=[x], verbose=False)[0] / 1E9 * 2 if thop else 0  # GFLOPs\n            except Exception:\n                flops = 0\n\n            try:\n                for _ in range(n):\n                    t[0] = time_sync()\n                    y = m(x)\n                    t[1] = time_sync()\n                    try:\n                        _ = (sum(yi.sum() for yi in y) if isinstance(y, list) else y).sum().backward()\n                        t[2] = time_sync()\n                    except Exception:  # no backward method\n                        # print(e)  # for debug\n                        t[2] = float('nan')\n                    tf += (t[1] - t[0]) * 1000 / n  # ms per op forward\n                    tb += (t[2] - t[1]) * 1000 / n  # ms per op backward\n                mem = torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0  # (GB)\n                s_in, s_out = (tuple(x.shape) if isinstance(x, torch.Tensor) else 'list' for x in (x, y))  # shapes\n                p = sum(x.numel() for x in m.parameters()) if isinstance(m, nn.Module) else 0  # parameters\n                LOGGER.info(f'{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{str(s_in):>24s}{str(s_out):>24s}')\n                results.append([p, flops, mem, tf, tb, s_in, s_out])\n            except Exception as e:\n                LOGGER.info(e)\n                results.append(None)\n            torch.cuda.empty_cache()\n    return results\n\n\nclass EarlyStopping:\n    \"\"\"\n    Early stopping class that stops training when a specified number of epochs have passed without improvement.\n    \"\"\"\n\n    def __init__(self, patience=50):\n        \"\"\"\n        Initialize early stopping object\n\n        Args:\n            patience (int, optional): Number of epochs to wait after fitness stops improving before stopping.\n        \"\"\"\n        self.best_fitness = 0.0  # i.e. mAP\n        self.best_epoch = 0\n        self.patience = patience or float('inf')  # epochs to wait after fitness stops improving to stop\n        self.possible_stop = False  # possible stop may occur next epoch\n\n    def __call__(self, epoch, fitness):\n        \"\"\"\n        Check whether to stop training\n\n        Args:\n            epoch (int): Current epoch of training\n            fitness (float): Fitness value of current epoch\n\n        Returns:\n            (bool): True if training should stop, False otherwise\n        \"\"\"\n        if fitness is None:  # check if fitness=None (happens when val=False)\n            return False\n\n        if fitness >= self.best_fitness:  # >= 0 to allow for early zero-fitness stage of training\n            self.best_epoch = epoch\n            self.best_fitness = fitness\n        delta = epoch - self.best_epoch  # epochs without improvement\n        self.possible_stop = delta >= (self.patience - 1)  # possible stop may occur next epoch\n        stop = delta >= self.patience  # stop training if patience exceeded\n        if stop:\n            LOGGER.info(f'Stopping training early as no improvement observed in last {self.patience} epochs. '\n                        f'Best results observed at epoch {self.best_epoch}, best model saved as best.pt.\\n'\n                        f'To update EarlyStopping(patience={self.patience}) pass a new patience value, '\n                        f'i.e. `patience=300` or use `patience=0` to disable EarlyStopping.')\n        return stop\n"
  },
  {
    "path": "ultralytics/yolo/utils/tuner.py",
    "content": "from ultralytics.yolo.utils import LOGGER\n\ntry:\n    from ray import tune\n    from ray.air import RunConfig, session  # noqa\n    from ray.air.integrations.wandb import WandbLoggerCallback  # noqa\n    from ray.tune.schedulers import ASHAScheduler  # noqa\n    from ray.tune.schedulers import AsyncHyperBandScheduler as AHB  # noqa\n\nexcept ImportError:\n    LOGGER.info(\"Tuning hyperparameters requires ray/tune. Install using `pip install 'ray[tune]'`\")\n    tune = None\n\ndefault_space = {\n    # 'optimizer': tune.choice(['SGD', 'Adam', 'AdamW', 'RMSProp']),\n    'lr0': tune.uniform(1e-5, 1e-1),\n    'lrf': tune.uniform(0.01, 1.0),  # final OneCycleLR learning rate (lr0 * lrf)\n    'momentum': tune.uniform(0.6, 0.98),  # SGD momentum/Adam beta1\n    'weight_decay': tune.uniform(0.0, 0.001),  # optimizer weight decay 5e-4\n    'warmup_epochs': tune.uniform(0.0, 5.0),  # warmup epochs (fractions ok)\n    'warmup_momentum': tune.uniform(0.0, 0.95),  # warmup initial momentum\n    'box': tune.uniform(0.02, 0.2),  # box loss gain\n    'cls': tune.uniform(0.2, 4.0),  # cls loss gain (scale with pixels)\n    'hsv_h': tune.uniform(0.0, 0.1),  # image HSV-Hue augmentation (fraction)\n    'hsv_s': tune.uniform(0.0, 0.9),  # image HSV-Saturation augmentation (fraction)\n    'hsv_v': tune.uniform(0.0, 0.9),  # image HSV-Value augmentation (fraction)\n    'degrees': tune.uniform(0.0, 45.0),  # image rotation (+/- deg)\n    'translate': tune.uniform(0.0, 0.9),  # image translation (+/- fraction)\n    'scale': tune.uniform(0.0, 0.9),  # image scale (+/- gain)\n    'shear': tune.uniform(0.0, 10.0),  # image shear (+/- deg)\n    'perspective': tune.uniform(0.0, 0.001),  # image perspective (+/- fraction), range 0-0.001\n    'flipud': tune.uniform(0.0, 1.0),  # image flip up-down (probability)\n    'fliplr': tune.uniform(0.0, 1.0),  # image flip left-right (probability)\n    'mosaic': tune.uniform(0.0, 1.0),  # image mixup (probability)\n    'mixup': tune.uniform(0.0, 1.0),  # image mixup (probability)\n    'copy_paste': tune.uniform(0.0, 1.0)}  # segment copy-paste (probability)\n\ntask_metric_map = {\n    'detect': 'metrics/mAP50-95(B)',\n    'segment': 'metrics/mAP50-95(M)',\n    'classify': 'metrics/accuracy_top1',\n    'pose': 'metrics/mAP50-95(P)'}\n"
  },
  {
    "path": "ultralytics/yolo/v8/DecSeg/.ipynb_checkpoints/val-checkpoint.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport os\nfrom pathlib import Path\nimport cv2\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom multiprocessing.pool import ThreadPool\nimport posixpath\nfrom ultralytics.yolo.data import build_dataloader, build_yolo_dataset\nfrom ultralytics.yolo.data.dataloaders.v5loader import create_dataloader\nfrom ultralytics.yolo.engine.validator import BaseValidator\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, colorstr, ops, NUM_THREADS\nfrom ultralytics.yolo.utils.checks import check_requirements\nfrom ultralytics.yolo.utils.metrics import ConfusionMatrix, DetMetrics, box_iou, SegmentMetrics, mask_iou\nfrom ultralytics.yolo.utils.plotting import output_to_target, plot_images, Annotator, Colors\nfrom ultralytics.yolo.utils.torch_utils import de_parallel\nimport torch.nn as nn\nimport math\nimport contextlib\nclass MultiValidator(BaseValidator):\n\n    def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):\n        \"\"\"Initialize detection model with necessary variables and settings.\"\"\"\n        super().__init__(dataloader, save_dir, pbar, args, _callbacks)\n        self.args.task = 'multi'\n        self.is_coco = False\n        self.class_map = None\n        self.metrics = []\n        try:\n            for name in dataloader.dataset.data['labels_list']:\n                if 'det' in name:\n                    self.metrics.append(DetMetrics(save_dir=self.save_dir, on_plot=self.on_plot))\n                if 'seg' in name:\n                    self.metrics.append(SegmentMetrics(save_dir=self.save_dir, on_plot=self.on_plot))\n        except:\n            pass\n        self.metrics_det = DetMetrics(save_dir=self.save_dir, on_plot=self.on_plot)\n        self.metrics_seg = SegmentMetrics(save_dir=self.save_dir, on_plot=self.on_plot)\n        self.iouv = torch.linspace(0.5, 0.95, 10)  # iou vector for mAP@0.5:0.95\n        self.niou = self.iouv.numel()\n\n    def preprocess(self, batch):\n        \"\"\"Preprocesses batch of images for YOLO training.\"\"\"\n        batch_list = []\n        for i,subbatch in enumerate(batch):\n            if 'det' in self.data['labels_list'][i]:\n                subbatch['img'] = subbatch['img'].to(self.device, non_blocking=True)\n                subbatch['img'] = (subbatch['img'].half() if self.args.half else subbatch['img'].float()) / 255\n                for k in ['batch_idx', 'cls', 'bboxes']:\n                    subbatch[k] = subbatch[k].to(self.device)\n                nb = len(subbatch['img'])\n                self.lb = [torch.cat([subbatch['cls'], subbatch['bboxes']], dim=-1)[subbatch['batch_idx'] == i]\n                           for i in range(nb)] if self.args.save_hybrid else []  # for autolabelling\n                batch_list.append(subbatch)\n            elif 'seg' in self.data['labels_list'][i]:\n                subbatch['img'] = subbatch['img'].to(self.device, non_blocking=True)\n                subbatch['img'] = (subbatch['img'].half() if self.args.half else subbatch['img'].float()) / 255\n\n                # for k in ['batch_idx', 'cls', 'bboxes']:\n                #     subbatch[k] = subbatch[k].to(self.device)\n\n                nb = len(subbatch['img'])\n                # self.lb = [torch.cat([batch['cls'], subbatch['bboxes']], dim=-1)[subbatch['batch_idx'] == i]\n                #            for i in range(nb)] if self.args.save_hybrid else []  # for autolabelling\n                subbatch['masks'] = subbatch['masks'].to(self.device).float()\n                batch_list.append(subbatch)\n        return batch_list\n\n    def init_metrics(self, model):\n        \"\"\"Initialize evaluation metrics for YOLO.\"\"\"\n        val = self.data.get(self.args.split, '')  # validation path\n        self.is_coco = isinstance(val, str) and 'coco' in val and val.endswith(f'{os.sep}val2017.txt')  # is COCO\n        self.class_map = ops.coco80_to_coco91_class() if self.is_coco else list(range(1000))\n        self.args.save_json |= self.is_coco and not self.training  # run on final val if training COCO\n        self.names = model.names\n        self.nc = len(model.names)\n        for metrics in self.metrics:\n            metrics.names = self.names\n            metrics.plot = self.args.plots\n        self.confusion_matrix={name: ConfusionMatrix(nc=self.data['nc_list'][count]) for count, name in enumerate(self.data['labels_list'])}\n        self.seen = {name: 0 for name in self.data['labels_list']}\n        self.jdict = []\n        self.stats = {name: [] for name in self.data['labels_list']}\n        self.nt_per_class = {name: [] for name in self.data['labels_list']}\n        ###################################\n        self.plot_masks = {name: [] for name in self.data['labels_list']}\n        if self.args.save_json:\n            check_requirements('pycocotools>=2.0.6')\n            self.process = ops.process_mask_upsample  # more accurate\n        else:\n            self.process = ops.process_mask  # faster\n        self.sigmoid = nn.Sigmoid()\n        self.combine = []\n\n    def get_desc_det(self):\n        \"\"\"Return a formatted string summarizing class metrics of YOLO model.\"\"\"\n        return ('%22s' + '%11s' * 6) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95)')\n\n    def get_desc_seg(self):\n        \"\"\"Return a formatted description of evaluation metrics.\"\"\"\n        return ('%22s' + '%11s' * 10) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95)', 'Mask(P',\n                                         'R', 'mAP50', 'mAP50-95)')\n\n    def postprocess_det(self, preds):\n        \"\"\"Apply Non-maximum suppression to prediction outputs.\"\"\"\n        preds = ops.non_max_suppression(preds,\n                                        self.args.conf,\n                                        self.args.iou,\n                                        labels=self.lb,\n                                        multi_label=True,\n                                        agnostic=self.args.single_cls,\n                                        max_det=self.args.max_det)\n        return preds\n\n    def postprocess_seg(self, preds,count):\n        \"\"\"Postprocesses YOLO predictions and returns output detections with proto.\"\"\"\n        preds = self.sigmoid(preds)\n        _, preds = torch.max(preds, 1)\n        return preds\n\n    def replace_elements_in_column(self, tensor, target_list, column_index):\n        target_list = torch.tensor(target_list, dtype=torch.float32, device=self.device)\n        mask = torch.any(tensor[:, column_index].unsqueeze(1) == target_list, dim=1)\n\n        replacement_tensor = tensor.clone()\n        replacement_tensor[mask, column_index] = target_list[0]\n\n        return replacement_tensor\n\n    def update_metrics_det(self, preds, batch, task_name=None):\n        \"\"\"Metrics.\"\"\"\n        if self.args.combine_class:\n            for si, pred in enumerate(preds):\n                idx = batch['batch_idx'] == si\n                cls = batch['cls'][idx]\n                cls = self.replace_elements_in_column(cls,self.args.combine_class,0)\n                bbox = batch['bboxes'][idx]\n                nl, npr = cls.shape[0], pred.shape[0]  # number of labels, predictions\n                shape = batch['ori_shape'][si]\n                correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n                self.seen[task_name] += 1\n\n                if npr == 0:\n                    if nl:\n                        self.stats[task_name].append(\n                            (correct_bboxes, *torch.zeros((2, 0), device=self.device), cls.squeeze(-1)))\n                        if self.args.plots:\n                            self.confusion_matrix[task_name].process_batch(detections=None, labels=cls.squeeze(-1))\n                    continue\n\n                # Predictions\n                if self.args.single_cls:\n                    pred[:, 5] = 0\n                predn = pred.clone()\n                predn = self.replace_elements_in_column(predn,self.args.combine_class,5)\n                ops.scale_boxes(batch['img'][si].shape[1:], predn[:, :4], shape,\n                                ratio_pad=batch['ratio_pad'][si])  # native-space pred\n\n                # Evaluate\n                if nl:\n                    height, width = batch['img'].shape[2:]\n                    tbox = ops.xywh2xyxy(bbox) * torch.tensor(\n                        (width, height, width, height), device=self.device)  # target boxes\n                    ops.scale_boxes(batch['img'][si].shape[1:], tbox, shape,\n                                    ratio_pad=batch['ratio_pad'][si])  # native-space labels\n                    labelsn = torch.cat((cls, tbox), 1)  # native-space labels\n                    correct_bboxes = self._process_batch_det(predn, labelsn)\n                    # TODO: maybe remove these `self.` arguments as they already are member variable\n                    if self.args.plots:\n                        self.confusion_matrix[task_name].process_batch(predn, labelsn)\n                self.stats[task_name].append(\n                    (correct_bboxes, pred[:, 4], pred[:, 5], cls.squeeze(-1)))  # (conf, pcls, tcls)\n\n                # Save\n                if self.args.save_json:\n                    self.pred_to_json(predn, batch['im_file'][si])\n                if self.args.save_txt:\n                    file = self.save_dir / 'labels' / f'{Path(batch[\"im_file\"][si]).stem}.txt'\n                    self.save_one_txt(predn, self.args.save_conf, shape, file)\n        else:\n            for si, pred in enumerate(preds):\n                idx = batch['batch_idx'] == si\n                cls = batch['cls'][idx]\n                bbox = batch['bboxes'][idx]\n                nl, npr = cls.shape[0], pred.shape[0]  # number of labels, predictions\n                shape = batch['ori_shape'][si]\n                correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n                self.seen[task_name] += 1\n\n                if npr == 0:\n                    if nl:\n                        self.stats[task_name].append((correct_bboxes, *torch.zeros((2, 0), device=self.device), cls.squeeze(-1)))\n                        if self.args.plots:\n                            self.confusion_matrix[task_name].process_batch(detections=None, labels=cls.squeeze(-1))\n                    continue\n\n                # Predictions\n                if self.args.single_cls:\n                    pred[:, 5] = 0\n                predn = pred.clone()\n                ops.scale_boxes(batch['img'][si].shape[1:], predn[:, :4], shape,\n                                ratio_pad=batch['ratio_pad'][si])  # native-space pred\n\n                # Evaluate\n                if nl:\n                    height, width = batch['img'].shape[2:]\n                    tbox = ops.xywh2xyxy(bbox) * torch.tensor(\n                        (width, height, width, height), device=self.device)  # target boxes\n                    ops.scale_boxes(batch['img'][si].shape[1:], tbox, shape,\n                                    ratio_pad=batch['ratio_pad'][si])  # native-space labels\n                    labelsn = torch.cat((cls, tbox), 1)  # native-space labels\n                    correct_bboxes = self._process_batch_det(predn, labelsn)\n                    # TODO: maybe remove these `self.` arguments as they already are member variable\n                    if self.args.plots:\n                        self.confusion_matrix[task_name].process_batch(predn, labelsn)\n                self.stats[task_name].append((correct_bboxes, pred[:, 4], pred[:, 5], cls.squeeze(-1)))  # (conf, pcls, tcls)\n\n                # Save\n                if self.args.save_json:\n                    self.pred_to_json(predn, batch['im_file'][si])\n                if self.args.save_txt:\n                    file = self.save_dir / 'labels' / f'{Path(batch[\"im_file\"][si]).stem}.txt'\n                    self.save_one_txt(predn, self.args.save_conf, shape, file)\n\n    def update_metrics_seg(self, preds, batch, task_name=None):\n        \"\"\"Metrics.\"\"\"\n        batch_size = len(batch['im_file'])\n        mask_list = batch['masks'].to(self.device).float()\n        for count in range(batch_size):\n            gt_mask = mask_list[count].clamp_(max=1)\n            pred_mask = preds[count].squeeze()\n            # import matplotlib.pyplot as plt\n            # gt_masks = pred_mask.cpu().numpy()\n            # plt.imshow(gt_masks, cmap='gray')\n            # plt.title('imgPredict')\n            # plt.axis('off')\n            # plt.savefig('/home/jiayuan/ultralytics-main/ultralytics/runs/test_gt.png')\n            self.seg_metrics[task_name].reset()\n            self.seg_metrics[task_name].addBatch(pred_mask.cpu(), gt_mask.cpu())\n            self.seg_result[task_name]['pixacc'].update(self.seg_metrics[task_name].pixelAccuracy())\n            self.seg_result[task_name]['subacc'].update(self.seg_metrics[task_name].lineAccuracy())\n            self.seg_result[task_name]['IoU'].update(self.seg_metrics[task_name].IntersectionOverUnion())\n            self.seg_result[task_name]['mIoU'].update(self.seg_metrics[task_name].meanIntersectionOverUnion())\n            if self.args.plots and self.batch_i < 3:\n                self.plot_masks[task_name].append(pred_mask.cpu())  # filter top 15 to plot\n\n    def finalize_metrics(self, *args, **kwargs):\n        \"\"\"Set final values for metrics speed and confusion matrix.\"\"\"\n        for i, labels_name in enumerate(self.data['labels_list']):\n\n            self.metrics[i].speed = self.speed\n            self.metrics[i].confusion_matrix = self.confusion_matrix[labels_name]\n\n    def get_stats(self):\n        \"\"\"Returns metrics statistics and results dictionary.\"\"\"\n        results_dict = []\n        for i, labels_name in enumerate(self.data['labels_list']):\n            try:\n                stats = [torch.cat(x, 0).cpu().numpy() for x in zip(*self.stats[labels_name])]  # to numpy\n                if len(stats) and stats[0].any():\n                    self.metrics[i].process(*stats)\n                self.nt_per_class[labels_name] = np.bincount(stats[-1].astype(int), minlength=self.data['nc_list'][i])  # number of targets per class\n                results_dict.append(self.metrics[i].results_dict)\n            except:\n                pass\n        return results_dict\n\n    def print_results(self):\n        \"\"\"Prints training/validation set metrics per class.\"\"\"\n        ######Jiayuan\n        for count, label_name in enumerate(self.data['labels_list']):\n            if 'seg' in label_name:\n                pf = '%22s' + ('%11s' + '%11.3g') * len(self.seg_result[label_name])\n                if self.args.verbose and self.training and self.nc > 1:\n                    class_index = int([key for key, value in self.data['map'][count].items()][0])\n                    key_values = [(key, value.avg) for key, value in self.seg_result[label_name].items()]\n                    LOGGER.info(pf % (self.names[class_index], *sum(key_values, ())))\n            else:\n                LOGGER.info(('%22s' + '%11s' * 6) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95'))\n                pf = '%22s' + '%11i' * 2 + '%11.3g' * len(self.metrics[count].keys)  # print format\n                LOGGER.info(pf % ('all', self.seen[label_name], self.nt_per_class[label_name].sum(), *self.metrics[count].mean_results()))\n                if self.nt_per_class[label_name].sum() == 0:\n                    LOGGER.warning(\n                        f'WARNING ⚠️ no labels found in {self.args.task} set, can not compute metrics without labels')\n\n            # Print results per class\n            if self.args.verbose and not self.training and self.nc > 1 and len(self.stats[label_name]):\n                for i, c in enumerate(self.metrics[count].ap_class_index):\n                    if self.data['map'][count]!='None':\n                        for key, val in self.data['map'][count].items():\n                            if val == str(c):\n                                class_index = int(key)\n                        key_values = [(key, value.avg) for key, value in self.seg_result[label_name].items()]\n                        LOGGER.info(pf % (self.names[class_index], *sum(key_values, ())))\n                    else:\n                        if self.args.single_cls:\n                            LOGGER.info(pf % (self.names[self.args.combine_class[0]], self.seen[label_name], self.nt_per_class[label_name][c],\n                                              *self.metrics[count].class_result(i)))\n                        else:\n                            LOGGER.info(pf % (self.names[c], self.seen[label_name], self.nt_per_class[label_name][c], *self.metrics[count].class_result(i)))\n            elif self.args.verbose and not self.training and self.nc > 1:\n                class_index = int([key for key, value in self.data['map'][count].items()][0])\n                key_values = [(key, value.avg) for key, value in self.seg_result[label_name].items()]\n                LOGGER.info(pf % (self.names[class_index], *sum(key_values, ())))\n\n\n\n            if self.args.plots:\n                for normalize in True, False:\n                    self.confusion_matrix[label_name].plot(save_dir=self.save_dir,\n                                               names=self.names.values(),\n                                               normalize=normalize,\n                                               on_plot=self.on_plot)\n        ######\n    def _process_batch_det(self, detections, labels):\n        \"\"\"\n        Return correct prediction matrix\n        Arguments:\n            detections (array[N, 6]), x1, y1, x2, y2, conf, class\n            labels (array[M, 5]), class, x1, y1, x2, y2\n        Returns:\n            correct (array[N, 10]), for 10 IoU levels\n        \"\"\"\n        iou = box_iou(labels[:, 1:], detections[:, :4])\n        correct = np.zeros((detections.shape[0], self.iouv.shape[0])).astype(bool)\n        correct_class = labels[:, 0:1] == detections[:, 5]\n        for i in range(len(self.iouv)):\n            x = torch.where((iou >= self.iouv[i]) & correct_class)  # IoU > threshold and classes match\n            if x[0].shape[0]:\n                matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]),\n                                    1).cpu().numpy()  # [label, detect, iou]\n                if x[0].shape[0] > 1:\n                    matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                    # matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n                correct[matches[:, 1].astype(int), i] = True\n        return torch.tensor(correct, dtype=torch.bool, device=detections.device)\n\n    def _process_batch_seg(self, detections, labels, pred_masks=None, gt_masks=None, overlap=False, masks=False):\n        \"\"\"\n        Return correct prediction matrix\n        Arguments:\n            detections (array[N, 6]), x1, y1, x2, y2, conf, class\n            labels (array[M, 5]), class, x1, y1, x2, y2\n        Returns:\n            correct (array[N, 10]), for 10 IoU levels\n        \"\"\"\n        if masks:\n            if overlap:\n                nl = len(labels)\n                index = torch.arange(nl, device=gt_masks.device).view(nl, 1, 1) + 1\n                gt_masks = gt_masks.repeat(nl, 1, 1)  # shape(1,640,640) -> (n,640,640)\n                gt_masks = torch.where(gt_masks == index, 1.0, 0.0)\n            if gt_masks.shape[1:] != pred_masks.shape[1:]:\n                gt_masks = F.interpolate(gt_masks[None], pred_masks.shape[1:], mode='bilinear', align_corners=False)[0]\n                gt_masks = gt_masks.gt_(0.5)\n            iou = mask_iou(gt_masks.view(gt_masks.shape[0], -1), pred_masks.view(pred_masks.shape[0], -1))\n            ######Jiayuan\n\n        else:  # boxes\n            iou = box_iou(labels[:, 1:], detections[:, :4])\n\n        correct = np.zeros((detections.shape[0], self.iouv.shape[0])).astype(bool)\n        correct_class = labels[:, 0:1] == detections[:, 5]\n        for i in range(len(self.iouv)):\n            x = torch.where((iou >= self.iouv[i]) & correct_class)  # IoU > threshold and classes match\n            if x[0].shape[0]:\n                matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]),\n                                    1).cpu().numpy()  # [label, detect, iou]\n                if x[0].shape[0] > 1:\n                    matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                    # matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n                correct[matches[:, 1].astype(int), i] = True\n        return torch.tensor(correct, dtype=torch.bool, device=detections.device)\n\n    def build_dataset(self, img_path, mode='val', batch=None):\n        \"\"\"Build YOLO Dataset\n\n        Args:\n            img_path (str): Path to the folder containing images.\n            mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.\n            batch (int, optional): Size of batches, this is for `rect`. Defaults to None.\n        \"\"\"\n        gs = max(int(de_parallel(self.model).stride if self.model else 0), 32)\n        return build_yolo_dataset(self.args, img_path, batch, self.data, mode=mode, stride=gs)\n\n    def get_dataloader(self, dataset_path, batch_size):\n        \"\"\"TODO: manage splits differently.\"\"\"\n        # Calculate stride - check if model is initialized\n        if self.args.v5loader:\n            LOGGER.warning(\"WARNING ⚠️ 'v5loader' feature is deprecated and will be removed soon. You can train using \"\n                           'the default YOLOv8 dataloader instead, no argument is needed.')\n            gs = max(int(de_parallel(self.model).stride if self.model else 0), 32)\n            return create_dataloader(path=dataset_path,\n                                     imgsz=self.args.imgsz,\n                                     batch_size=batch_size,\n                                     stride=gs,\n                                     hyp=vars(self.args),\n                                     cache=False,\n                                     pad=0.5,\n                                     rect=self.args.rect,\n                                     workers=self.args.workers,\n                                     prefix=colorstr(f'{self.args.mode}: '),\n                                     shuffle=False,\n                                     seed=self.args.seed)[0]\n\n        dataset = self.build_dataset(dataset_path, batch=batch_size, mode='val')\n        dataloader = build_dataloader(dataset, batch_size, self.args.workers, shuffle=False, rank=-1)\n        return dataloader\n\n\n\n    def plot_val_samples(self, batch, ni, task=None):\n        \"\"\"Plots validation samples with bounding box labels.\"\"\"\n        fname = self.save_dir / f\"val_batch{task}{ni}.jpg\" if task != None else self.save_dir / f'val_batch{ni}.jpg'\n        if 'det' in task:\n            plot_images(batch['img'],\n                        batch['batch_idx'],\n                        batch['cls'].squeeze(-1),\n                        batch['bboxes'],\n                        paths=batch['im_file'],\n                        fname=fname,\n                        names=self.names,\n                        on_plot=self.on_plot)\n        elif 'seg' in task:\n            plot_images(batch['img'],\n                        batch['batch_idx'],\n                        batch['cls'].squeeze(-1),\n                        batch['bboxes'],\n                        batch['masks'],\n                        paths=batch['im_file'],\n                        fname=fname,\n                        names=self.names,\n                        on_plot=self.on_plot)\n\n\n\n    def plot_predictions(self, batch, preds, ni, task=None):\n        \"\"\"Plots batch predictions with masks and bounding boxes.\"\"\"\n        fname = self.save_dir / f\"val_batch{task}{ni}_pred.jpg\" if task != None else self.save_dir / f'val_batch{ni}_pred.jpg'\n        if 'det' in task:\n            plot_images(batch['img'],\n                        *output_to_target(preds, max_det=15),\n                        paths=batch['im_file'],\n                        fname=fname,\n                        names=self.names,\n                        on_plot=self.on_plot)  # pred\n        # elif 'seg' in task:\n        #     self.show_seg_result_batch(batch['img'],\n        #                 self.plot_masks[task],\n        #                 fname)  # pred\n        #     self.plot_masks[task].clear()\n        elif 'seg' in task:\n            self.plot_images_seg(batch['img'],\n                            self.plot_masks[task],\n                            batch['im_file'],\n                            fname,\n                            self.on_plot)  # pred\n            self.plot_masks[task].clear()\n\n    def plot_images_seg(self,\n                        images,\n                        masks=np.zeros(0, dtype=np.uint8),\n                        paths=None,\n                        fname='images.jpg',\n                        on_plot=None):\n        # Plot image grid with labels\n        colors = Colors()\n        if isinstance(images, torch.Tensor):\n            images = images.cpu().float().numpy()\n\n        max_size = 1920  # max image size\n        max_subplots = 16  # max image subplots, i.e. 4x4\n        bs, _, h, w = images.shape  # batch size, _, height, width\n        bs = min(bs, max_subplots)  # limit plot images\n        ns = np.ceil(bs ** 0.5)  # number of subplots (square)\n        if np.max(images[0]) <= 1:\n            images *= 255  # de-normalise (optional)\n\n        # Build Image\n        mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8)  # init\n        for i, im in enumerate(images):\n            if i == max_subplots:  # if last batch has fewer images than we expect\n                break\n            x, y = int(w * (i // ns)), int(h * (i % ns))  # block origin\n            im = im.transpose(1, 2, 0)\n            mosaic[y:y + h, x:x + w, :] = im\n\n        # Resize (optional)\n        scale = max_size / ns / max(h, w)\n        if scale < 1:\n            h = math.ceil(scale * h)\n            w = math.ceil(scale * w)\n            mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))\n\n        # Annotate\n        fs = int((h + w) * ns * 0.01)  # font size\n        annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=None)\n        for i in range(bs):\n            x, y = int(w * (i // ns)), int(h * (i % ns))  # block origin\n            annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2)  # borders\n            if paths:\n                annotator.text((x + 5, y + 5), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220))  # filenames\n                # Plot masks\n\n                image_masks = masks[i]\n                image_masks = image_masks.cpu().numpy().astype(int)\n                im = np.asarray(annotator.im).copy()\n                mh, mw = image_masks.shape\n                color = colors(0)\n                if mh != h or mw != w:\n                    mask = image_masks.astype(np.uint8)\n                    mask = cv2.resize(mask, (w, h))\n                    mask = mask.astype(bool)\n                else:\n                    mask = image_masks.astype(bool)\n                with contextlib.suppress(Exception):\n                    im[y:y + h, x:x + w, :][mask] = im[y:y + h, x:x + w, :][mask] * 0.4 + np.array(color) * 0.6\n                annotator.fromarray(im)\n        annotator.im.save(fname)  # save\n        if on_plot:\n            on_plot(fname)\n\n\n    def show_seg_result_batch(self, images, results, save_dir=None, palette=None):\n        images = images.cpu().float().numpy()*255\n        if palette is None:\n            palette = np.random.randint(0, 255, size=(3, 3))\n        palette[0] = [0, 0, 0]\n        palette[1] = [0, 255, 0]\n        palette[2] = [255, 0, 0]\n        palette = np.array(palette)\n        bs, _, h, w = images.shape\n        assert palette.shape[0] == 3\n        assert palette.shape[1] == 3\n        assert len(palette.shape) == 2\n\n        batch_size = images.shape[0]\n        output_images = []\n        kernel = np.ones((5, 5), np.uint8)\n        for idx in range(batch_size):\n            img = images[idx].copy()\n            img = img.transpose(1, 2, 0)\n            result = results[idx]\n\n            color_seg = np.zeros((result.shape[0], result.shape[1], 3), dtype=np.uint8)\n            for label, color in enumerate(palette):\n                color_seg[result == label, :] = color\n\n            color_seg = color_seg[..., ::-1]\n            # color_mask = np.mean(color_seg, 2)\n            # img_copy = img.copy()  # Create a copy of the image\n            # img_copy[color_mask != 0] = img_copy[color_mask != 0] * 0.5 + color_seg[color_mask != 0] * 0.5\n            # img_copy = img_copy.astype(np.uint8)\n            # img_copy = cv2.resize(img_copy, (w, h), interpolation=cv2.INTER_LINEAR)\n            #\n            # output_images.append(img_copy)\n            color_mask = np.mean(color_seg, 2)\n            smoothed_mask = cv2.GaussianBlur(color_mask, (5, 5), 0)\n\n            # Apply erosion operation to the smoothed mask\n            eroded_mask = cv2.erode(smoothed_mask, kernel, iterations=1)\n\n            img_copy = img.copy()\n            img_copy[eroded_mask != 0] = img_copy[eroded_mask != 0] * 0.5 + color_seg[eroded_mask != 0] * 0.5\n            img_copy = img_copy.astype(np.uint8)\n            img_copy = cv2.resize(img_copy, (w, h), interpolation=cv2.INTER_LINEAR)\n\n            output_images.append(img_copy)\n\n        # Create a canvas to hold all images\n        max_images_per_row = 4  # Adjust this value as needed\n        num_rows = (batch_size + max_images_per_row - 1) // max_images_per_row\n        canvas_h = num_rows * h\n        canvas_w = max_images_per_row * w\n        canvas = np.zeros((canvas_h, canvas_w, 3), dtype=np.uint8)\n\n        for i, img in enumerate(output_images):\n            row_idx = i // max_images_per_row\n            col_idx = i % max_images_per_row\n            canvas[row_idx * h:(row_idx + 1) * h, col_idx * w:(col_idx + 1) * w, :] = img\n\n        if save_dir:\n            save_path = posixpath.abspath(save_dir)\n            cv2.imwrite(save_path, canvas)\n\n    def save_one_txt(self, predn, save_conf, shape, file):\n        \"\"\"Save YOLO detections to a txt file in normalized coordinates in a specific format.\"\"\"\n        gn = torch.tensor(shape)[[1, 0, 1, 0]]  # normalization gain whwh\n        for *xyxy, conf, cls in predn.tolist():\n            xywh = (ops.xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh\n            line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format\n            with open(file, 'a') as f:\n                f.write(('%g ' * len(line)).rstrip() % line + '\\n')\n\n    def pred_to_json_det(self, predn, filename):\n        \"\"\"Serialize YOLO predictions to COCO json format.\"\"\"\n        stem = Path(filename).stem\n        image_id = int(stem) if stem.isnumeric() else stem\n        box = ops.xyxy2xywh(predn[:, :4])  # xywh\n        box[:, :2] -= box[:, 2:] / 2  # xy center to top-left corner\n        for p, b in zip(predn.tolist(), box.tolist()):\n            self.jdict.append({\n                'image_id': image_id,\n                'category_id': self.class_map[int(p[5])],\n                'bbox': [round(x, 3) for x in b],\n                'score': round(p[4], 5)})\n\n    def pred_to_json_seg(self, predn, filename, pred_masks):\n        \"\"\"Save one JSON result.\"\"\"\n        # Example result = {\"image_id\": 42, \"category_id\": 18, \"bbox\": [258.15, 41.29, 348.26, 243.78], \"score\": 0.236}\n        from pycocotools.mask import encode  # noqa\n\n        def single_encode(x):\n            \"\"\"Encode predicted masks as RLE and append results to jdict.\"\"\"\n            rle = encode(np.asarray(x[:, :, None], order='F', dtype='uint8'))[0]\n            rle['counts'] = rle['counts'].decode('utf-8')\n            return rle\n\n        stem = Path(filename).stem\n        image_id = int(stem) if stem.isnumeric() else stem\n        box = ops.xyxy2xywh(predn[:, :4])  # xywh\n        box[:, :2] -= box[:, 2:] / 2  # xy center to top-left corner\n        pred_masks = np.transpose(pred_masks, (2, 0, 1))\n        with ThreadPool(NUM_THREADS) as pool:\n            rles = pool.map(single_encode, pred_masks)\n        for i, (p, b) in enumerate(zip(predn.tolist(), box.tolist())):\n            self.jdict.append({\n                'image_id': image_id,\n                'category_id': self.class_map[int(p[5])],\n                'bbox': [round(x, 3) for x in b],\n                'score': round(p[4], 5),\n                'segmentation': rles[i]})\n\n    def eval_json_det(self, stats):\n        \"\"\"Evaluates YOLO output in JSON format and returns performance statistics.\"\"\"\n        if self.args.save_json and self.is_coco and len(self.jdict):\n            anno_json = self.data['path'] / 'annotations/instances_val2017.json'  # annotations\n            pred_json = self.save_dir / 'predictions.json'  # predictions\n            LOGGER.info(f'\\nEvaluating pycocotools mAP using {pred_json} and {anno_json}...')\n            try:  # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n                check_requirements('pycocotools>=2.0.6')\n                from pycocotools.coco import COCO  # noqa\n                from pycocotools.cocoeval import COCOeval  # noqa\n\n                for x in anno_json, pred_json:\n                    assert x.is_file(), f'{x} file not found'\n                anno = COCO(str(anno_json))  # init annotations api\n                pred = anno.loadRes(str(pred_json))  # init predictions api (must pass string, not Path)\n                eval = COCOeval(anno, pred, 'bbox')\n                if self.is_coco:\n                    eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files]  # images to eval\n                eval.evaluate()\n                eval.accumulate()\n                eval.summarize()\n                stats[self.metrics.keys[-1]], stats[self.metrics.keys[-2]] = eval.stats[:2]  # update mAP50-95 and mAP50\n            except Exception as e:\n                LOGGER.warning(f'pycocotools unable to run: {e}')\n        return stats\n\n\n    def eval_json_seg(self, stats):\n        \"\"\"Return COCO-style object detection evaluation metrics.\"\"\"\n        if self.args.save_json and self.is_coco and len(self.jdict):\n            anno_json = self.data['path'] / 'annotations/instances_val2017.json'  # annotations\n            pred_json = self.save_dir / 'predictions.json'  # predictions\n            LOGGER.info(f'\\nEvaluating pycocotools mAP using {pred_json} and {anno_json}...')\n            try:  # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n                check_requirements('pycocotools>=2.0.6')\n                from pycocotools.coco import COCO  # noqa\n                from pycocotools.cocoeval import COCOeval  # noqa\n\n                for x in anno_json, pred_json:\n                    assert x.is_file(), f'{x} file not found'\n                anno = COCO(str(anno_json))  # init annotations api\n                pred = anno.loadRes(str(pred_json))  # init predictions api (must pass string, not Path)\n                for i, eval in enumerate([COCOeval(anno, pred, 'bbox'), COCOeval(anno, pred, 'segm')]):\n                    if self.is_coco:\n                        eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files]  # im to eval\n                    eval.evaluate()\n                    eval.accumulate()\n                    eval.summarize()\n                    idx = i * 4 + 2\n                    stats[self.metrics.keys[idx + 1]], stats[\n                        self.metrics.keys[idx]] = eval.stats[:2]  # update mAP50-95 and mAP50\n            except Exception as e:\n                LOGGER.warning(f'pycocotools unable to run: {e}')\n        return stats\n\n\ndef val(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Validate trained YOLO model on validation dataset.\"\"\"\n    model = cfg.model or 'yolov8n.pt'\n    data = cfg.data or 'coco128.yaml'\n\n    args = dict(model=model, data=data)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).val(**args)\n    else:\n        validator = MultiValidator(args=args)\n        validator(model=args['model'])\n\n\nif __name__ == '__main__':\n    val()\n"
  },
  {
    "path": "ultralytics/yolo/v8/DecSeg/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .predict import MultiPredictor, predict\nfrom .train import DetectionSegmentationTrainer, train\nfrom .val import MultiValidator, val\n\n__all__ = 'MultiPredictor', 'predict', 'DetectionSegmentationTrainer', 'train', 'MultiValidator', 'val'\n"
  },
  {
    "path": "ultralytics/yolo/v8/DecSeg/predict.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\n\nfrom ultralytics.yolo.engine.predictor_multi import BasePredictor\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils import DEFAULT_CFG, ROOT, ops\n\n\nclass MultiPredictor(BasePredictor):\n\n    def postprocess_det(self, preds, img, orig_imgs):\n        \"\"\"Postprocesses predictions and returns a list of Results objects.\"\"\"\n        preds = ops.non_max_suppression(preds,\n                                        self.args.conf,\n                                        self.args.iou,\n                                        agnostic=self.args.agnostic_nms,\n                                        max_det=self.args.max_det,\n                                        classes=self.args.classes)\n\n        results = []\n        for i, pred in enumerate(preds):\n            orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs\n            if not isinstance(orig_imgs, torch.Tensor):\n                pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            results.append(Results(orig_img=orig_img, path=img_path, names=self.model.names, boxes=pred))\n        return results\n\n    def postprocess_seg(self, preds):\n        \"\"\"Postprocesses YOLO predictions and returns output detections with proto.\"\"\"\n        preds = torch.nn.functional.interpolate(preds, size=(720, 1280), mode='bilinear', align_corners=False)\n        preds = self.sigmoid(preds)\n        _, preds = torch.max(preds, 1)\n        return preds\n\n\ndef predict(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Runs YOLO model inference on input image(s).\"\"\"\n    model = cfg.model or 'yolov8n.pt'\n    source = cfg.source if cfg.source is not None else ROOT / 'assets' if (ROOT / 'assets').exists() \\\n        else 'https://ultralytics.com/images/bus.jpg'\n\n    args = dict(model=model, source=source)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model)(**args)\n    else:\n        predictor = MultiPredictor(overrides=args)\n        predictor.predict_cli()\n\n\nif __name__ == '__main__':\n    predict()\n"
  },
  {
    "path": "ultralytics/yolo/v8/DecSeg/train.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nfrom copy import copy\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom ultralytics.nn.tasks import DetectionModel\nfrom ultralytics.yolo import v8\nfrom ultralytics.yolo.data import build_dataloader, build_yolo_dataset\nfrom ultralytics.yolo.data.dataloaders.v5loader import create_dataloader\nfrom ultralytics.yolo.engine.trainer import BaseTrainer\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, RANK, colorstr, ops\nfrom ultralytics.yolo.utils.loss import BboxLoss, FocalLossV1, tversky\nfrom ultralytics.yolo.utils.plotting import plot_images, plot_labels, plot_results\nfrom ultralytics.yolo.utils.tal import TaskAlignedAssigner, dist2bbox, make_anchors\nfrom ultralytics.yolo.utils.torch_utils import de_parallel, torch_distributed_zero_first\nfrom ultralytics.nn.tasks import MultiModel\nfrom copy import copy\nfrom ultralytics.yolo.utils.ops import crop_mask, xyxy2xywh, xywh2xyxy\nimport torch.nn.functional as F\nimport itertools\n# BaseTrainer python usage\nclass DetectionSegmentationTrainer(BaseTrainer):\n    \n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        \"\"\"Initialize a DetectionSegmentationTrainer object with given arguments.\"\"\"\n        if overrides is None:\n            overrides = {}\n        overrides['task'] = 'multi'\n        super().__init__(cfg, overrides, _callbacks)\n\n    def build_dataset(self, img_path, mode='train', batch=None):\n        \"\"\"Build YOLO Dataset\n\n        Args:\n            img_path (str): Path to the folder containing images.\n            mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.\n            batch (int, optional): Size of batches, this is for `rect`. Defaults to None.\n        \"\"\"\n        try:\n            gs = max(int(de_parallel(self.model).stride.max() if self.model else 0), 32)\n        except:\n            gs = max(max(itertools.chain.from_iterable(de_parallel(self.model).stride)) if self.model else 0, 32)\n        return build_yolo_dataset(self.args, img_path, batch, self.data, mode=mode, rect=mode == 'val', stride=gs)\n\n    def get_dataloader(self, dataset_path, batch_size=16, rank=0, mode='train'):\n        \"\"\"TODO: manage splits differently.\"\"\"\n        # Calculate stride - check if model is initialized\n        if self.args.v5loader:\n            LOGGER.warning(\"WARNING ⚠️ 'v5loader' feature is deprecated and will be removed soon. You can train using \"\n                           'the default YOLOv8 dataloader instead, no argument is needed.')\n            gs = max(int(de_parallel(self.model).stride.max() if self.model else 0), 32)\n            return create_dataloader(path=dataset_path,\n                                     imgsz=self.args.imgsz,\n                                     batch_size=batch_size,\n                                     stride=gs,\n                                     hyp=vars(self.args),\n                                     augment=mode == 'train',\n                                     cache=self.args.cache,\n                                     pad=0 if mode == 'train' else 0.5,\n                                     rect=self.args.rect or mode == 'val',\n                                     rank=rank,\n                                     workers=self.args.workers,\n                                     close_mosaic=self.args.close_mosaic != 0,\n                                     prefix=colorstr(f'{mode}: '),\n                                     shuffle=mode == 'train',\n                                     seed=self.args.seed)[0]\n        assert mode in ['train', 'val']\n        with torch_distributed_zero_first(rank):  # init dataset *.cache only once if DDP\n            dataset = self.build_dataset(dataset_path, mode, batch_size)\n        shuffle = mode == 'train'\n        if getattr(dataset, 'rect', False) and shuffle:\n            LOGGER.warning(\"WARNING ⚠️ 'rect=True' is incompatible with DataLoader shuffle, setting shuffle=False\")\n            shuffle = False\n        workers = self.args.workers if mode == 'train' else self.args.workers * 2\n        return build_dataloader(dataset, batch_size, workers, shuffle, rank)  # return dataloader\n\n    def preprocess_batch(self, batch):\n        \"\"\"Preprocesses a batch of images by scaling and converting to float.\"\"\"\n        for count in range(len(batch)):\n            batch[count]['img'] = batch[count]['img'].to(self.device, non_blocking=True).float() / 255\n        return batch\n\n    def set_model_attributes(self):\n        \"\"\"nl = de_parallel(self.model).model[-1].nl  # number of detection layers (to scale hyps).\"\"\"\n        # self.args.box *= 3 / nl  # scale to layers\n        # self.args.cls *= self.data[\"nc\"] / 80 * 3 / nl  # scale to classes and layers\n        # self.args.cls *= (self.args.imgsz / 640) ** 2 * 3 / nl  # scale to image size and layers\n        self.model.nc = self.data['nc']  # attach number of classes to model\n        self.model.names = self.data['names']  # attach class names to model\n        self.model.args = self.args  # attach hyperparameters to model\n        # TODO: self.model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc\n\n    def get_model(self, cfg=None, weights=None, verbose=True):\n        \"\"\"Return a YOLO multi model.\"\"\"\n        multi_model = MultiModel(cfg, nc=self.data['tnc'], verbose=verbose and RANK == -1)\n        if weights:\n            multi_model.load(weights)\n\n        return multi_model\n\n    def get_validator(self):\n        \"\"\"Return DetectionValidator and SegmentationValidator for validation of YOLO model.\"\"\"\n        self.loss_names = {\"det\": ['box_loss', 'cls_loss', 'dfl_loss'],\"seg\": ['Tv_loss', 'FL_loss']}\n        return v8.DecSeg.MultiValidator(self.test_loader, save_dir=self.save_dir, args=copy(self.args))\n\n    def criterion(self, preds, batch, name=None, count=None):\n        \"\"\"Compute loss for YOLO prediction and ground-truth.\"\"\"\n        if 'det' in name:\n            self.compute_loss = Loss(de_parallel(self.model),count-len(self.data['labels_list']))\n        elif 'seg' in name:\n            self.compute_loss = SegLoss(de_parallel(self.model), overlap=self.args.overlap_mask, count=count-len(self.data['labels_list']), task_name = name, map=self.data['map'][count])\n        return self.compute_loss(preds, batch)\n\n\n    def label_loss_items(self, loss_items=None, prefix='train',task=None):\n        \"\"\"\n        Returns a loss dict with labelled training loss items tensor\n        \"\"\"\n        # Not needed for classification but necessary for segmentation & detection\n        if loss_items is not None:\n            loss_names = []\n            for name in self.data['labels_list']:\n                loss_names.extend(self.loss_names[name[:3]])\n            keys = [f'{prefix}/{x}' for x in loss_names]\n            losses = [loss_withdraw for loss_withdraw in loss_items]\n            loss_values = list(itertools.chain(*[l.tolist() for l in losses]))\n            loss_items = [round(float(x), 5) for x in loss_values]  # convert tensors to 5 decimal place floats\n            return dict(zip(keys, loss_items))\n        else:\n            keys = [f'{prefix}/{x}' for x in self.loss_names[task]]\n            return keys\n\n    def label_loss_items_val(self, loss_items=None, prefix='val', task=None):\n        \"\"\"\n        Returns a loss dict with labelled training loss items tensor\n        \"\"\"\n        # Not needed for classification but necessary for segmentation & detection\n        if loss_items is not None:\n            keys = [f'{prefix}/{x}' for x in self.loss_names[task[:3]]]\n            loss_items = [round(float(x), 5) for x in loss_items]  # convert tensors to 5 decimal place floats\n            return dict(zip(keys, loss_items))\n        else:\n            keys = [f'{prefix}/{x}' for x in self.loss_names[task]]\n            return keys\n\n    def progress_string(self):\n        \"\"\"Returns a formatted string of training progress with epoch, GPU memory, loss, instances and size.\"\"\"\n        ######Jiayuan\n        loss_names = []\n        for name in self.data['labels_list']:\n            loss_names.extend(self.loss_names[name[:3]])\n        return ('\\n' + '%11s' *\n                (4 + len(loss_names))) % ('Epoch', 'GPU_mem', *loss_names, 'Instances', 'Size')\n        ######\n\n    def plot_training_samples(self, batch, ni, task=None):\n        ######Jiayuan\n        \"\"\"Plots training samples with their annotations.\"\"\"\n        fname = self.save_dir / f\"train_batch{self.data['labels_list'][task]}{ni}.jpg\" if task!=None else self.save_dir / f'train_batch{ni}.jpg'\n        if 'det' in self.data['labels_list'][task]:\n            plot_images(images=batch['img'],\n                        batch_idx=batch['batch_idx'],\n                        cls=batch['cls'].squeeze(-1),\n                        bboxes=batch['bboxes'],\n                        paths=batch['im_file'],\n                        fname=fname,\n                        on_plot=self.on_plot)\n        elif 'seg' in self.data['labels_list'][task]:\n            plot_images(images=batch['img'],\n                        batch_idx=batch['batch_idx'],\n                        cls=batch['cls'].squeeze(-1),\n                        bboxes=batch['bboxes'],\n                        masks=batch['masks'],\n                        paths=batch['im_file'],\n                        fname=fname,\n                        on_plot=self.on_plot)\n        ######\n\n    def plot_metrics(self):\n        \"\"\"Plots metrics from a CSV file.\"\"\"\n        # plot_results(file=self.csv, on_plot=self.on_plot)  # save results.png\n        # plot_results(file=self.csv, segment=True, on_plot=self.on_plot)  # save results.png\n\n    def plot_training_labels(self):\n        \"\"\"Create a labeled training plot of the YOLO model.\"\"\"\n        for i in range(len(self.train_loader.dataset.labels)):\n            boxes = np.concatenate([lb['bboxes'] for lb in self.train_loader.dataset.labels[i]], 0)\n            cls = np.concatenate([lb['cls'] for lb in self.train_loader.dataset.labels[i]], 0)\n            plot_labels(boxes, cls.squeeze(), names=self.data['names'], save_dir=self.save_dir, on_plot=self.on_plot)\n\n\n\n# Criterion class for computing training losses\nclass Loss:\n\n    def __init__(self, model,count):  # model must be de-paralleled\n\n        device = next(model.parameters()).device  # get model device\n        h = model.args  # hyperparameters\n\n        m = model.model[count]  # Detect() module_\n        self.bce = nn.BCEWithLogitsLoss(reduction='none')\n        self.hyp = h\n        self.stride = m.stride  # model strides\n        self.nc = m.nc  # number of classes\n        self.no = m.no\n        self.reg_max = m.reg_max\n        self.device = device\n\n        self.use_dfl = m.reg_max > 1\n\n        self.assigner = TaskAlignedAssigner(topk=10, num_classes=self.nc, alpha=0.5, beta=6.0)\n        self.bbox_loss = BboxLoss(m.reg_max - 1, use_dfl=self.use_dfl).to(device)\n        self.proj = torch.arange(m.reg_max, dtype=torch.float, device=device)\n\n    def preprocess(self, targets, batch_size, scale_tensor):\n        \"\"\"Preprocesses the target counts and matches with the input batch size to output a tensor.\"\"\"\n        if targets.shape[0] == 0:\n            out = torch.zeros(batch_size, 0, 5, device=self.device)\n        else:\n            i = targets[:, 0]  # image index\n            _, counts = i.unique(return_counts=True)\n            counts = counts.to(dtype=torch.int32)\n            out = torch.zeros(batch_size, counts.max(), 5, device=self.device)\n            for j in range(batch_size):\n                matches = i == j\n                n = matches.sum()\n                if n:\n                    out[j, :n] = targets[matches, 1:]\n            out[..., 1:5] = xywh2xyxy(out[..., 1:5].mul_(scale_tensor))\n        return out\n\n    def bbox_decode(self, anchor_points, pred_dist):\n        \"\"\"Decode predicted object bounding box coordinates from anchor points and distribution.\"\"\"\n        if self.use_dfl:\n            b, a, c = pred_dist.shape  # batch, anchors, channels\n            pred_dist = pred_dist.view(b, a, 4, c // 4).softmax(3).matmul(self.proj.type(pred_dist.dtype))\n            # pred_dist = pred_dist.view(b, a, c // 4, 4).transpose(2,3).softmax(3).matmul(self.proj.type(pred_dist.dtype))\n            # pred_dist = (pred_dist.view(b, a, c // 4, 4).softmax(2) * self.proj.type(pred_dist.dtype).view(1, 1, -1, 1)).sum(2)\n        return dist2bbox(pred_dist, anchor_points, xywh=False)\n\n    def __call__(self, preds, batch):\n        \"\"\"Calculate the sum of the loss for box, cls and dfl multiplied by batch size.\"\"\"\n        loss = torch.zeros(3, device=self.device)  # box, cls, dfl\n        feats = preds[1] if isinstance(preds, tuple) else preds\n        pred_distri, pred_scores = torch.cat([xi.view(feats[0].shape[0], self.no, -1) for xi in feats], 2).split(\n            (self.reg_max * 4, self.nc), 1)\n\n        pred_scores = pred_scores.permute(0, 2, 1).contiguous()\n        pred_distri = pred_distri.permute(0, 2, 1).contiguous()\n\n        dtype = pred_scores.dtype\n        batch_size = pred_scores.shape[0]\n        imgsz = torch.tensor(feats[0].shape[2:], device=self.device, dtype=dtype) * self.stride[0]  # image size (h,w)\n        anchor_points, stride_tensor = make_anchors(feats, self.stride, 0.5)\n\n        # targets\n        targets = torch.cat((batch['batch_idx'].view(-1, 1), batch['cls'].view(-1, 1), batch['bboxes']), 1)\n        targets = self.preprocess(targets.to(self.device), batch_size, scale_tensor=imgsz[[1, 0, 1, 0]])\n        gt_labels, gt_bboxes = targets.split((1, 4), 2)  # cls, xyxy\n        mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0)\n\n        # pboxes\n        pred_bboxes = self.bbox_decode(anchor_points, pred_distri)  # xyxy, (b, h*w, 4)\n\n        _, target_bboxes, target_scores, fg_mask, _ = self.assigner(\n            pred_scores.detach().sigmoid(), (pred_bboxes.detach() * stride_tensor).type(gt_bboxes.dtype),\n            anchor_points * stride_tensor, gt_labels, gt_bboxes, mask_gt)\n\n        target_scores_sum = max(target_scores.sum(), 1)\n\n        # cls loss\n        # loss[1] = self.varifocal_loss(pred_scores, target_scores, target_labels) / target_scores_sum  # VFL way\n        loss[1] = self.bce(pred_scores, target_scores.to(dtype)).sum() / target_scores_sum  # BCE\n\n        # bbox loss\n        if fg_mask.sum():\n            target_bboxes /= stride_tensor\n            loss[0], loss[2] = self.bbox_loss(pred_distri, pred_bboxes, anchor_points, target_bboxes, target_scores,\n                                              target_scores_sum, fg_mask)\n\n        loss[0] *= self.hyp.box  # box gain\n        loss[1] *= self.hyp.cls  # cls gain\n        loss[2] *= self.hyp.dfl  # dfl gain\n\n        return loss.sum() * batch_size, loss.detach()  # loss(box, cls, dfl)\n\n\n\n# Criterion class for computing training losses\nclass SegLoss(Loss):\n\n    def __init__(self, model, overlap=True, count = None, task_name=None,map=None):  # model must be de-paralleled\n        super().__init__(model,count)\n        self.overlap = overlap\n        self.map = map\n        self.focal_loss = FocalLossV1()\n        self.TL = tversky()\n        self.sigmoid = nn.Sigmoid()\n        self.task_name = task_name\n\n    def __call__(self, preds, batch):\n        \"\"\"Calculate and return the loss for the YOLO model.\"\"\"\n        ###### Jiayuan: This code only for binary segmentation. To Do: add multi seg\n        loss = torch.zeros(2, device=self.device)  # dice FL\n        batch_size = len(batch['im_file'])\n        masks = batch['masks'].to(self.device).float()\n        # import matplotlib.pyplot as plt\n        # gt_masks = masks.cpu().numpy()\n        # plt.imshow(gt_masks[0], cmap='gray')\n        # plt.title('imgPredict')\n        # plt.axis('off')\n        # plt.savefig('/home/jiayuan/ultralytics-main/ultralytics/runs/test_gt.png')\n        gt_masks = masks.unsqueeze(1).clamp_(max=1)\n        neg_mask = 1 - gt_masks\n        binary_mask = torch.cat((neg_mask, gt_masks), dim=1)\n        loss[0] = self.TL(preds, binary_mask, 0.7)\n        loss[1] = self.focal_loss(preds, binary_mask)\n        loss[0] *= self.hyp.TL    # TL gain\n        loss[1] *= self.hyp.FL  # FL gain\n        # loss[3] = (preds * 0).sum() ###### This is a auxiliary loss, do not move it. For PDD multi GPU issue.\n        return loss.sum()* batch_size, loss.detach()\n\n\n\n\ndef train(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Train and optimize YOLO model given training data and device.\"\"\"\n    model = cfg.model or 'yolov8n.pt'\n    data = cfg.data or 'coco128.yaml'  # or yolo.ClassificationDataset(\"mnist\")\n    device = cfg.device if cfg.device is not None else ''\n\n    args = dict(model=model, data=data, device=device)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).train(**args)\n    else:\n        trainer = DetectionSegmentationTrainer(overrides=args)\n        trainer.train()\n\n\nif __name__ == '__main__':\n    train()\n\n"
  },
  {
    "path": "ultralytics/yolo/v8/DecSeg/val.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport os\nfrom pathlib import Path\nimport cv2\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom multiprocessing.pool import ThreadPool\nimport posixpath\nfrom ultralytics.yolo.data import build_dataloader, build_yolo_dataset\nfrom ultralytics.yolo.data.dataloaders.v5loader import create_dataloader\nfrom ultralytics.yolo.engine.validator import BaseValidator\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, colorstr, ops, NUM_THREADS\nfrom ultralytics.yolo.utils.checks import check_requirements\nfrom ultralytics.yolo.utils.metrics import ConfusionMatrix, DetMetrics, box_iou, SegmentMetrics, mask_iou\nfrom ultralytics.yolo.utils.plotting import output_to_target, plot_images, Annotator, Colors\nfrom ultralytics.yolo.utils.torch_utils import de_parallel\nimport torch.nn as nn\nimport math\nimport contextlib\nclass MultiValidator(BaseValidator):\n\n    def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):\n        \"\"\"Initialize detection model with necessary variables and settings.\"\"\"\n        super().__init__(dataloader, save_dir, pbar, args, _callbacks)\n        self.args.task = 'multi'\n        self.is_coco = False\n        self.class_map = None\n        self.metrics = []\n        try:\n            for name in dataloader.dataset.data['labels_list']:\n                if 'det' in name:\n                    self.metrics.append(DetMetrics(save_dir=self.save_dir, on_plot=self.on_plot))\n                if 'seg' in name:\n                    self.metrics.append(SegmentMetrics(save_dir=self.save_dir, on_plot=self.on_plot))\n        except:\n            pass\n        self.metrics_det = DetMetrics(save_dir=self.save_dir, on_plot=self.on_plot)\n        self.metrics_seg = SegmentMetrics(save_dir=self.save_dir, on_plot=self.on_plot)\n        self.iouv = torch.linspace(0.5, 0.95, 10)  # iou vector for mAP@0.5:0.95\n        self.niou = self.iouv.numel()\n\n    def preprocess(self, batch):\n        \"\"\"Preprocesses batch of images for YOLO training.\"\"\"\n        batch_list = []\n        for i,subbatch in enumerate(batch):\n            if 'det' in self.data['labels_list'][i]:\n                subbatch['img'] = subbatch['img'].to(self.device, non_blocking=True)\n                subbatch['img'] = (subbatch['img'].half() if self.args.half else subbatch['img'].float()) / 255\n                for k in ['batch_idx', 'cls', 'bboxes']:\n                    subbatch[k] = subbatch[k].to(self.device)\n                nb = len(subbatch['img'])\n                self.lb = [torch.cat([subbatch['cls'], subbatch['bboxes']], dim=-1)[subbatch['batch_idx'] == i]\n                           for i in range(nb)] if self.args.save_hybrid else []  # for autolabelling\n                batch_list.append(subbatch)\n            elif 'seg' in self.data['labels_list'][i]:\n                subbatch['img'] = subbatch['img'].to(self.device, non_blocking=True)\n                subbatch['img'] = (subbatch['img'].half() if self.args.half else subbatch['img'].float()) / 255\n\n                # for k in ['batch_idx', 'cls', 'bboxes']:\n                #     subbatch[k] = subbatch[k].to(self.device)\n\n                nb = len(subbatch['img'])\n                # self.lb = [torch.cat([batch['cls'], subbatch['bboxes']], dim=-1)[subbatch['batch_idx'] == i]\n                #            for i in range(nb)] if self.args.save_hybrid else []  # for autolabelling\n                subbatch['masks'] = subbatch['masks'].to(self.device).float()\n                batch_list.append(subbatch)\n        return batch_list\n\n    def init_metrics(self, model):\n        \"\"\"Initialize evaluation metrics for YOLO.\"\"\"\n        val = self.data.get(self.args.split, '')  # validation path\n        self.is_coco = isinstance(val, str) and 'coco' in val and val.endswith(f'{os.sep}val2017.txt')  # is COCO\n        self.class_map = ops.coco80_to_coco91_class() if self.is_coco else list(range(1000))\n        self.args.save_json |= self.is_coco and not self.training  # run on final val if training COCO\n        self.names = model.names\n        self.nc = len(model.names)\n        for metrics in self.metrics:\n            metrics.names = self.names\n            metrics.plot = self.args.plots\n        self.confusion_matrix={name: ConfusionMatrix(nc=self.data['nc_list'][count]) for count, name in enumerate(self.data['labels_list'])}\n        self.seen = {name: 0 for name in self.data['labels_list']}\n        self.jdict = []\n        self.stats = {name: [] for name in self.data['labels_list']}\n        self.nt_per_class = {name: [] for name in self.data['labels_list']}\n        ###################################\n        self.plot_masks = {name: [] for name in self.data['labels_list']}\n        if self.args.save_json:\n            check_requirements('pycocotools>=2.0.6')\n            self.process = ops.process_mask_upsample  # more accurate\n        else:\n            self.process = ops.process_mask  # faster\n        self.sigmoid = nn.Sigmoid()\n        self.combine = []\n\n    def get_desc_det(self):\n        \"\"\"Return a formatted string summarizing class metrics of YOLO model.\"\"\"\n        return ('%22s' + '%11s' * 6) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95)')\n\n    def get_desc_seg(self):\n        \"\"\"Return a formatted description of evaluation metrics.\"\"\"\n        return ('%22s' + '%11s' * 10) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95)', 'Mask(P',\n                                         'R', 'mAP50', 'mAP50-95)')\n\n    def postprocess_det(self, preds):\n        \"\"\"Apply Non-maximum suppression to prediction outputs.\"\"\"\n        preds = ops.non_max_suppression(preds,\n                                        self.args.conf,\n                                        self.args.iou,\n                                        labels=self.lb,\n                                        multi_label=True,\n                                        agnostic=self.args.single_cls,\n                                        max_det=self.args.max_det)\n        return preds\n\n    def postprocess_seg(self, preds,count):\n        \"\"\"Postprocesses YOLO predictions and returns output detections with proto.\"\"\"\n        preds = self.sigmoid(preds)\n        _, preds = torch.max(preds, 1)\n        return preds\n\n    def replace_elements_in_column(self, tensor, target_list, column_index):\n        target_list = torch.tensor(target_list, dtype=torch.float32, device=self.device)\n        mask = torch.any(tensor[:, column_index].unsqueeze(1) == target_list, dim=1)\n\n        replacement_tensor = tensor.clone()\n        replacement_tensor[mask, column_index] = target_list[0]\n\n        return replacement_tensor\n\n    def update_metrics_det(self, preds, batch, task_name=None):\n        \"\"\"Metrics.\"\"\"\n        if self.args.combine_class:\n            for si, pred in enumerate(preds):\n                idx = batch['batch_idx'] == si\n                cls = batch['cls'][idx]\n                cls = self.replace_elements_in_column(cls,self.args.combine_class,0)\n                bbox = batch['bboxes'][idx]\n                nl, npr = cls.shape[0], pred.shape[0]  # number of labels, predictions\n                shape = batch['ori_shape'][si]\n                correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n                self.seen[task_name] += 1\n\n                if npr == 0:\n                    if nl:\n                        self.stats[task_name].append(\n                            (correct_bboxes, *torch.zeros((2, 0), device=self.device), cls.squeeze(-1)))\n                        if self.args.plots:\n                            self.confusion_matrix[task_name].process_batch(detections=None, labels=cls.squeeze(-1))\n                    continue\n\n                # Predictions\n                if self.args.single_cls:\n                    pred[:, 5] = 0\n                predn = pred.clone()\n                predn = self.replace_elements_in_column(predn,self.args.combine_class,5)\n                ops.scale_boxes(batch['img'][si].shape[1:], predn[:, :4], shape,\n                                ratio_pad=batch['ratio_pad'][si])  # native-space pred\n\n                # Evaluate\n                if nl:\n                    height, width = batch['img'].shape[2:]\n                    tbox = ops.xywh2xyxy(bbox) * torch.tensor(\n                        (width, height, width, height), device=self.device)  # target boxes\n                    ops.scale_boxes(batch['img'][si].shape[1:], tbox, shape,\n                                    ratio_pad=batch['ratio_pad'][si])  # native-space labels\n                    labelsn = torch.cat((cls, tbox), 1)  # native-space labels\n                    correct_bboxes = self._process_batch_det(predn, labelsn)\n                    # TODO: maybe remove these `self.` arguments as they already are member variable\n                    if self.args.plots:\n                        self.confusion_matrix[task_name].process_batch(predn, labelsn)\n                self.stats[task_name].append(\n                    (correct_bboxes, pred[:, 4], pred[:, 5], cls.squeeze(-1)))  # (conf, pcls, tcls)\n\n                # Save\n                if self.args.save_json:\n                    self.pred_to_json(predn, batch['im_file'][si])\n                if self.args.save_txt:\n                    file = self.save_dir / 'labels' / f'{Path(batch[\"im_file\"][si]).stem}.txt'\n                    self.save_one_txt(predn, self.args.save_conf, shape, file)\n        else:\n            for si, pred in enumerate(preds):\n                idx = batch['batch_idx'] == si\n                cls = batch['cls'][idx]\n                bbox = batch['bboxes'][idx]\n                nl, npr = cls.shape[0], pred.shape[0]  # number of labels, predictions\n                shape = batch['ori_shape'][si]\n                correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n                self.seen[task_name] += 1\n\n                if npr == 0:\n                    if nl:\n                        self.stats[task_name].append((correct_bboxes, *torch.zeros((2, 0), device=self.device), cls.squeeze(-1)))\n                        if self.args.plots:\n                            self.confusion_matrix[task_name].process_batch(detections=None, labels=cls.squeeze(-1))\n                    continue\n\n                # Predictions\n                if self.args.single_cls:\n                    pred[:, 5] = 0\n                predn = pred.clone()\n                ops.scale_boxes(batch['img'][si].shape[1:], predn[:, :4], shape,\n                                ratio_pad=batch['ratio_pad'][si])  # native-space pred\n\n                # Evaluate\n                if nl:\n                    height, width = batch['img'].shape[2:]\n                    tbox = ops.xywh2xyxy(bbox) * torch.tensor(\n                        (width, height, width, height), device=self.device)  # target boxes\n                    ops.scale_boxes(batch['img'][si].shape[1:], tbox, shape,\n                                    ratio_pad=batch['ratio_pad'][si])  # native-space labels\n                    labelsn = torch.cat((cls, tbox), 1)  # native-space labels\n                    correct_bboxes = self._process_batch_det(predn, labelsn)\n                    # TODO: maybe remove these `self.` arguments as they already are member variable\n                    if self.args.plots:\n                        self.confusion_matrix[task_name].process_batch(predn, labelsn)\n                self.stats[task_name].append((correct_bboxes, pred[:, 4], pred[:, 5], cls.squeeze(-1)))  # (conf, pcls, tcls)\n\n                # Save\n                if self.args.save_json:\n                    self.pred_to_json(predn, batch['im_file'][si])\n                if self.args.save_txt:\n                    file = self.save_dir / 'labels' / f'{Path(batch[\"im_file\"][si]).stem}.txt'\n                    self.save_one_txt(predn, self.args.save_conf, shape, file)\n\n    def update_metrics_seg(self, preds, batch, task_name=None):\n        \"\"\"Metrics.\"\"\"\n        batch_size = len(batch['im_file'])\n        mask_list = batch['masks'].to(self.device).float()\n        for count in range(batch_size):\n            gt_mask = mask_list[count].clamp_(max=1)\n            pred_mask = preds[count].squeeze()\n            # import matplotlib.pyplot as plt\n            # gt_masks = pred_mask.cpu().numpy()\n            # plt.imshow(gt_masks, cmap='gray')\n            # plt.title('imgPredict')\n            # plt.axis('off')\n            # plt.savefig('/home/jiayuan/ultralytics-main/ultralytics/runs/test_gt.png')\n            self.seg_metrics[task_name].reset()\n            self.seg_metrics[task_name].addBatch(pred_mask.cpu(), gt_mask.cpu())\n            self.seg_result[task_name]['pixacc'].update(self.seg_metrics[task_name].pixelAccuracy())\n            self.seg_result[task_name]['subacc'].update(self.seg_metrics[task_name].lineAccuracy())\n            self.seg_result[task_name]['IoU'].update(self.seg_metrics[task_name].IntersectionOverUnion())\n            self.seg_result[task_name]['mIoU'].update(self.seg_metrics[task_name].meanIntersectionOverUnion())\n            if self.args.plots and self.batch_i < 3:\n                self.plot_masks[task_name].append(pred_mask.cpu())  # filter top 15 to plot\n\n    def finalize_metrics(self, *args, **kwargs):\n        \"\"\"Set final values for metrics speed and confusion matrix.\"\"\"\n        for i, labels_name in enumerate(self.data['labels_list']):\n\n            self.metrics[i].speed = self.speed\n            self.metrics[i].confusion_matrix = self.confusion_matrix[labels_name]\n\n    def get_stats(self):\n        \"\"\"Returns metrics statistics and results dictionary.\"\"\"\n        results_dict = []\n        for i, labels_name in enumerate(self.data['labels_list']):\n            try:\n                stats = [torch.cat(x, 0).cpu().numpy() for x in zip(*self.stats[labels_name])]  # to numpy\n                if len(stats) and stats[0].any():\n                    self.metrics[i].process(*stats)\n                self.nt_per_class[labels_name] = np.bincount(stats[-1].astype(int), minlength=self.data['nc_list'][i])  # number of targets per class\n                results_dict.append(self.metrics[i].results_dict)\n            except:\n                pass\n        return results_dict\n\n    def print_results(self):\n        \"\"\"Prints training/validation set metrics per class.\"\"\"\n        ######Jiayuan\n        for count, label_name in enumerate(self.data['labels_list']):\n            if 'seg' in label_name:\n                pf = '%22s' + ('%11s' + '%11.3g') * len(self.seg_result[label_name])\n                if self.args.verbose and self.training and self.nc > 1:\n                    class_index = int([key for key, value in self.data['map'][count].items()][0])\n                    key_values = [(key, value.avg) for key, value in self.seg_result[label_name].items()]\n                    LOGGER.info(pf % (self.names[class_index], *sum(key_values, ())))\n            else:\n                LOGGER.info(('%22s' + '%11s' * 6) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95'))\n                pf = '%22s' + '%11i' * 2 + '%11.3g' * len(self.metrics[count].keys)  # print format\n                LOGGER.info(pf % ('all', self.seen[label_name], self.nt_per_class[label_name].sum(), *self.metrics[count].mean_results()))\n                if self.nt_per_class[label_name].sum() == 0:\n                    LOGGER.warning(\n                        f'WARNING ⚠️ no labels found in {self.args.task} set, can not compute metrics without labels')\n\n            # Print results per class\n            if self.args.verbose and not self.training and self.nc > 1 and len(self.stats[label_name]):\n                for i, c in enumerate(self.metrics[count].ap_class_index):\n                    if self.data['map'][count]!='None':\n                        for key, val in self.data['map'][count].items():\n                            if val == str(c):\n                                class_index = int(key)\n                        key_values = [(key, value.avg) for key, value in self.seg_result[label_name].items()]\n                        LOGGER.info(pf % (self.names[class_index], *sum(key_values, ())))\n                    else:\n                        if self.args.single_cls:\n                            LOGGER.info(pf % (self.names[self.args.combine_class[0]], self.seen[label_name], self.nt_per_class[label_name][c],\n                                              *self.metrics[count].class_result(i)))\n                        else:\n                            LOGGER.info(pf % (self.names[c], self.seen[label_name], self.nt_per_class[label_name][c], *self.metrics[count].class_result(i)))\n            elif self.args.verbose and not self.training and self.nc > 1:\n                class_index = int([key for key, value in self.data['map'][count].items()][0])\n                key_values = [(key, value.avg) for key, value in self.seg_result[label_name].items()]\n                LOGGER.info(pf % (self.names[class_index], *sum(key_values, ())))\n\n\n\n            if self.args.plots:\n                for normalize in True, False:\n                    self.confusion_matrix[label_name].plot(save_dir=self.save_dir,\n                                               names=self.names.values(),\n                                               normalize=normalize,\n                                               on_plot=self.on_plot)\n        ######\n    def _process_batch_det(self, detections, labels):\n        \"\"\"\n        Return correct prediction matrix\n        Arguments:\n            detections (array[N, 6]), x1, y1, x2, y2, conf, class\n            labels (array[M, 5]), class, x1, y1, x2, y2\n        Returns:\n            correct (array[N, 10]), for 10 IoU levels\n        \"\"\"\n        iou = box_iou(labels[:, 1:], detections[:, :4])\n        correct = np.zeros((detections.shape[0], self.iouv.shape[0])).astype(bool)\n        correct_class = labels[:, 0:1] == detections[:, 5]\n        for i in range(len(self.iouv)):\n            x = torch.where((iou >= self.iouv[i]) & correct_class)  # IoU > threshold and classes match\n            if x[0].shape[0]:\n                matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]),\n                                    1).cpu().numpy()  # [label, detect, iou]\n                if x[0].shape[0] > 1:\n                    matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                    # matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n                correct[matches[:, 1].astype(int), i] = True\n        return torch.tensor(correct, dtype=torch.bool, device=detections.device)\n\n    def _process_batch_seg(self, detections, labels, pred_masks=None, gt_masks=None, overlap=False, masks=False):\n        \"\"\"\n        Return correct prediction matrix\n        Arguments:\n            detections (array[N, 6]), x1, y1, x2, y2, conf, class\n            labels (array[M, 5]), class, x1, y1, x2, y2\n        Returns:\n            correct (array[N, 10]), for 10 IoU levels\n        \"\"\"\n        if masks:\n            if overlap:\n                nl = len(labels)\n                index = torch.arange(nl, device=gt_masks.device).view(nl, 1, 1) + 1\n                gt_masks = gt_masks.repeat(nl, 1, 1)  # shape(1,640,640) -> (n,640,640)\n                gt_masks = torch.where(gt_masks == index, 1.0, 0.0)\n            if gt_masks.shape[1:] != pred_masks.shape[1:]:\n                gt_masks = F.interpolate(gt_masks[None], pred_masks.shape[1:], mode='bilinear', align_corners=False)[0]\n                gt_masks = gt_masks.gt_(0.5)\n            iou = mask_iou(gt_masks.view(gt_masks.shape[0], -1), pred_masks.view(pred_masks.shape[0], -1))\n            ######Jiayuan\n\n        else:  # boxes\n            iou = box_iou(labels[:, 1:], detections[:, :4])\n\n        correct = np.zeros((detections.shape[0], self.iouv.shape[0])).astype(bool)\n        correct_class = labels[:, 0:1] == detections[:, 5]\n        for i in range(len(self.iouv)):\n            x = torch.where((iou >= self.iouv[i]) & correct_class)  # IoU > threshold and classes match\n            if x[0].shape[0]:\n                matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]),\n                                    1).cpu().numpy()  # [label, detect, iou]\n                if x[0].shape[0] > 1:\n                    matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                    # matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n                correct[matches[:, 1].astype(int), i] = True\n        return torch.tensor(correct, dtype=torch.bool, device=detections.device)\n\n    def build_dataset(self, img_path, mode='val', batch=None):\n        \"\"\"Build YOLO Dataset\n\n        Args:\n            img_path (str): Path to the folder containing images.\n            mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.\n            batch (int, optional): Size of batches, this is for `rect`. Defaults to None.\n        \"\"\"\n        gs = max(int(de_parallel(self.model).stride if self.model else 0), 32)\n        return build_yolo_dataset(self.args, img_path, batch, self.data, mode=mode, stride=gs)\n\n    def get_dataloader(self, dataset_path, batch_size):\n        \"\"\"TODO: manage splits differently.\"\"\"\n        # Calculate stride - check if model is initialized\n        if self.args.v5loader:\n            LOGGER.warning(\"WARNING ⚠️ 'v5loader' feature is deprecated and will be removed soon. You can train using \"\n                           'the default YOLOv8 dataloader instead, no argument is needed.')\n            gs = max(int(de_parallel(self.model).stride if self.model else 0), 32)\n            return create_dataloader(path=dataset_path,\n                                     imgsz=self.args.imgsz,\n                                     batch_size=batch_size,\n                                     stride=gs,\n                                     hyp=vars(self.args),\n                                     cache=False,\n                                     pad=0.5,\n                                     rect=self.args.rect,\n                                     workers=self.args.workers,\n                                     prefix=colorstr(f'{self.args.mode}: '),\n                                     shuffle=False,\n                                     seed=self.args.seed)[0]\n\n        dataset = self.build_dataset(dataset_path, batch=batch_size, mode='val')\n        dataloader = build_dataloader(dataset, batch_size, self.args.workers, shuffle=False, rank=-1)\n        return dataloader\n\n\n\n    def plot_val_samples(self, batch, ni, task=None):\n        \"\"\"Plots validation samples with bounding box labels.\"\"\"\n        fname = self.save_dir / f\"val_batch{task}{ni}.jpg\" if task != None else self.save_dir / f'val_batch{ni}.jpg'\n        if 'det' in task:\n            plot_images(batch['img'],\n                        batch['batch_idx'],\n                        batch['cls'].squeeze(-1),\n                        batch['bboxes'],\n                        paths=batch['im_file'],\n                        fname=fname,\n                        names=self.names,\n                        on_plot=self.on_plot)\n        elif 'seg' in task:\n            plot_images(batch['img'],\n                        batch['batch_idx'],\n                        batch['cls'].squeeze(-1),\n                        batch['bboxes'],\n                        batch['masks'],\n                        paths=batch['im_file'],\n                        fname=fname,\n                        names=self.names,\n                        on_plot=self.on_plot)\n\n\n\n    def plot_predictions(self, batch, preds, ni, task=None):\n        \"\"\"Plots batch predictions with masks and bounding boxes.\"\"\"\n        fname = self.save_dir / f\"val_batch{task}{ni}_pred.jpg\" if task != None else self.save_dir / f'val_batch{ni}_pred.jpg'\n        if 'det' in task:\n            plot_images(batch['img'],\n                        *output_to_target(preds, max_det=15),\n                        paths=batch['im_file'],\n                        fname=fname,\n                        names=self.names,\n                        on_plot=self.on_plot)  # pred\n        # elif 'seg' in task:\n        #     self.show_seg_result_batch(batch['img'],\n        #                 self.plot_masks[task],\n        #                 fname)  # pred\n        #     self.plot_masks[task].clear()\n        elif 'seg' in task:\n            self.plot_images_seg(batch['img'],\n                            self.plot_masks[task],\n                            batch['im_file'],\n                            fname,\n                            self.on_plot)  # pred\n            self.plot_masks[task].clear()\n\n    def plot_images_seg(self,\n                        images,\n                        masks=np.zeros(0, dtype=np.uint8),\n                        paths=None,\n                        fname='images.jpg',\n                        on_plot=None):\n        # Plot image grid with labels\n        colors = Colors()\n        if isinstance(images, torch.Tensor):\n            images = images.cpu().float().numpy()\n\n        max_size = 1920  # max image size\n        max_subplots = 16  # max image subplots, i.e. 4x4\n        bs, _, h, w = images.shape  # batch size, _, height, width\n        bs = min(bs, max_subplots)  # limit plot images\n        ns = np.ceil(bs ** 0.5)  # number of subplots (square)\n        if np.max(images[0]) <= 1:\n            images *= 255  # de-normalise (optional)\n\n        # Build Image\n        mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8)  # init\n        for i, im in enumerate(images):\n            if i == max_subplots:  # if last batch has fewer images than we expect\n                break\n            x, y = int(w * (i // ns)), int(h * (i % ns))  # block origin\n            im = im.transpose(1, 2, 0)\n            mosaic[y:y + h, x:x + w, :] = im\n\n        # Resize (optional)\n        scale = max_size / ns / max(h, w)\n        if scale < 1:\n            h = math.ceil(scale * h)\n            w = math.ceil(scale * w)\n            mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))\n\n        # Annotate\n        fs = int((h + w) * ns * 0.01)  # font size\n        annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs, pil=True, example=None)\n        for i in range(bs):\n            x, y = int(w * (i // ns)), int(h * (i % ns))  # block origin\n            annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2)  # borders\n            if paths:\n                annotator.text((x + 5, y + 5), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220))  # filenames\n                # Plot masks\n\n                image_masks = masks[i]\n                image_masks = image_masks.cpu().numpy().astype(int)\n                im = np.asarray(annotator.im).copy()\n                mh, mw = image_masks.shape\n                color = colors(0)\n                if mh != h or mw != w:\n                    mask = image_masks.astype(np.uint8)\n                    mask = cv2.resize(mask, (w, h))\n                    mask = mask.astype(bool)\n                else:\n                    mask = image_masks.astype(bool)\n                with contextlib.suppress(Exception):\n                    im[y:y + h, x:x + w, :][mask] = im[y:y + h, x:x + w, :][mask] * 0.4 + np.array(color) * 0.6\n                annotator.fromarray(im)\n        annotator.im.save(fname)  # save\n        if on_plot:\n            on_plot(fname)\n\n\n    def show_seg_result_batch(self, images, results, save_dir=None, palette=None):\n        images = images.cpu().float().numpy()*255\n        if palette is None:\n            palette = np.random.randint(0, 255, size=(3, 3))\n        palette[0] = [0, 0, 0]\n        palette[1] = [0, 255, 0]\n        palette[2] = [255, 0, 0]\n        palette = np.array(palette)\n        bs, _, h, w = images.shape\n        assert palette.shape[0] == 3\n        assert palette.shape[1] == 3\n        assert len(palette.shape) == 2\n\n        batch_size = images.shape[0]\n        output_images = []\n        kernel = np.ones((5, 5), np.uint8)\n        for idx in range(batch_size):\n            img = images[idx].copy()\n            img = img.transpose(1, 2, 0)\n            result = results[idx]\n\n            color_seg = np.zeros((result.shape[0], result.shape[1], 3), dtype=np.uint8)\n            for label, color in enumerate(palette):\n                color_seg[result == label, :] = color\n\n            color_seg = color_seg[..., ::-1]\n            # color_mask = np.mean(color_seg, 2)\n            # img_copy = img.copy()  # Create a copy of the image\n            # img_copy[color_mask != 0] = img_copy[color_mask != 0] * 0.5 + color_seg[color_mask != 0] * 0.5\n            # img_copy = img_copy.astype(np.uint8)\n            # img_copy = cv2.resize(img_copy, (w, h), interpolation=cv2.INTER_LINEAR)\n            #\n            # output_images.append(img_copy)\n            color_mask = np.mean(color_seg, 2)\n            smoothed_mask = cv2.GaussianBlur(color_mask, (5, 5), 0)\n\n            # Apply erosion operation to the smoothed mask\n            eroded_mask = cv2.erode(smoothed_mask, kernel, iterations=1)\n\n            img_copy = img.copy()\n            img_copy[eroded_mask != 0] = img_copy[eroded_mask != 0] * 0.5 + color_seg[eroded_mask != 0] * 0.5\n            img_copy = img_copy.astype(np.uint8)\n            img_copy = cv2.resize(img_copy, (w, h), interpolation=cv2.INTER_LINEAR)\n\n            output_images.append(img_copy)\n\n        # Create a canvas to hold all images\n        max_images_per_row = 4  # Adjust this value as needed\n        num_rows = (batch_size + max_images_per_row - 1) // max_images_per_row\n        canvas_h = num_rows * h\n        canvas_w = max_images_per_row * w\n        canvas = np.zeros((canvas_h, canvas_w, 3), dtype=np.uint8)\n\n        for i, img in enumerate(output_images):\n            row_idx = i // max_images_per_row\n            col_idx = i % max_images_per_row\n            canvas[row_idx * h:(row_idx + 1) * h, col_idx * w:(col_idx + 1) * w, :] = img\n\n        if save_dir:\n            save_path = posixpath.abspath(save_dir)\n            cv2.imwrite(save_path, canvas)\n\n    def save_one_txt(self, predn, save_conf, shape, file):\n        \"\"\"Save YOLO detections to a txt file in normalized coordinates in a specific format.\"\"\"\n        gn = torch.tensor(shape)[[1, 0, 1, 0]]  # normalization gain whwh\n        for *xyxy, conf, cls in predn.tolist():\n            xywh = (ops.xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh\n            line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format\n            with open(file, 'a') as f:\n                f.write(('%g ' * len(line)).rstrip() % line + '\\n')\n\n    def pred_to_json_det(self, predn, filename):\n        \"\"\"Serialize YOLO predictions to COCO json format.\"\"\"\n        stem = Path(filename).stem\n        image_id = int(stem) if stem.isnumeric() else stem\n        box = ops.xyxy2xywh(predn[:, :4])  # xywh\n        box[:, :2] -= box[:, 2:] / 2  # xy center to top-left corner\n        for p, b in zip(predn.tolist(), box.tolist()):\n            self.jdict.append({\n                'image_id': image_id,\n                'category_id': self.class_map[int(p[5])],\n                'bbox': [round(x, 3) for x in b],\n                'score': round(p[4], 5)})\n\n    def pred_to_json_seg(self, predn, filename, pred_masks):\n        \"\"\"Save one JSON result.\"\"\"\n        # Example result = {\"image_id\": 42, \"category_id\": 18, \"bbox\": [258.15, 41.29, 348.26, 243.78], \"score\": 0.236}\n        from pycocotools.mask import encode  # noqa\n\n        def single_encode(x):\n            \"\"\"Encode predicted masks as RLE and append results to jdict.\"\"\"\n            rle = encode(np.asarray(x[:, :, None], order='F', dtype='uint8'))[0]\n            rle['counts'] = rle['counts'].decode('utf-8')\n            return rle\n\n        stem = Path(filename).stem\n        image_id = int(stem) if stem.isnumeric() else stem\n        box = ops.xyxy2xywh(predn[:, :4])  # xywh\n        box[:, :2] -= box[:, 2:] / 2  # xy center to top-left corner\n        pred_masks = np.transpose(pred_masks, (2, 0, 1))\n        with ThreadPool(NUM_THREADS) as pool:\n            rles = pool.map(single_encode, pred_masks)\n        for i, (p, b) in enumerate(zip(predn.tolist(), box.tolist())):\n            self.jdict.append({\n                'image_id': image_id,\n                'category_id': self.class_map[int(p[5])],\n                'bbox': [round(x, 3) for x in b],\n                'score': round(p[4], 5),\n                'segmentation': rles[i]})\n\n    def eval_json_det(self, stats):\n        \"\"\"Evaluates YOLO output in JSON format and returns performance statistics.\"\"\"\n        if self.args.save_json and self.is_coco and len(self.jdict):\n            anno_json = self.data['path'] / 'annotations/instances_val2017.json'  # annotations\n            pred_json = self.save_dir / 'predictions.json'  # predictions\n            LOGGER.info(f'\\nEvaluating pycocotools mAP using {pred_json} and {anno_json}...')\n            try:  # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n                check_requirements('pycocotools>=2.0.6')\n                from pycocotools.coco import COCO  # noqa\n                from pycocotools.cocoeval import COCOeval  # noqa\n\n                for x in anno_json, pred_json:\n                    assert x.is_file(), f'{x} file not found'\n                anno = COCO(str(anno_json))  # init annotations api\n                pred = anno.loadRes(str(pred_json))  # init predictions api (must pass string, not Path)\n                eval = COCOeval(anno, pred, 'bbox')\n                if self.is_coco:\n                    eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files]  # images to eval\n                eval.evaluate()\n                eval.accumulate()\n                eval.summarize()\n                stats[self.metrics.keys[-1]], stats[self.metrics.keys[-2]] = eval.stats[:2]  # update mAP50-95 and mAP50\n            except Exception as e:\n                LOGGER.warning(f'pycocotools unable to run: {e}')\n        return stats\n\n\n    def eval_json_seg(self, stats):\n        \"\"\"Return COCO-style object detection evaluation metrics.\"\"\"\n        if self.args.save_json and self.is_coco and len(self.jdict):\n            anno_json = self.data['path'] / 'annotations/instances_val2017.json'  # annotations\n            pred_json = self.save_dir / 'predictions.json'  # predictions\n            LOGGER.info(f'\\nEvaluating pycocotools mAP using {pred_json} and {anno_json}...')\n            try:  # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n                check_requirements('pycocotools>=2.0.6')\n                from pycocotools.coco import COCO  # noqa\n                from pycocotools.cocoeval import COCOeval  # noqa\n\n                for x in anno_json, pred_json:\n                    assert x.is_file(), f'{x} file not found'\n                anno = COCO(str(anno_json))  # init annotations api\n                pred = anno.loadRes(str(pred_json))  # init predictions api (must pass string, not Path)\n                for i, eval in enumerate([COCOeval(anno, pred, 'bbox'), COCOeval(anno, pred, 'segm')]):\n                    if self.is_coco:\n                        eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files]  # im to eval\n                    eval.evaluate()\n                    eval.accumulate()\n                    eval.summarize()\n                    idx = i * 4 + 2\n                    stats[self.metrics.keys[idx + 1]], stats[\n                        self.metrics.keys[idx]] = eval.stats[:2]  # update mAP50-95 and mAP50\n            except Exception as e:\n                LOGGER.warning(f'pycocotools unable to run: {e}')\n        return stats\n\n\ndef val(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Validate trained YOLO model on validation dataset.\"\"\"\n    model = cfg.model or 'yolov8n.pt'\n    data = cfg.data or 'coco128.yaml'\n\n    args = dict(model=model, data=data)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).val(**args)\n    else:\n        validator = MultiValidator(args=args)\n        validator(model=args['model'])\n\n\nif __name__ == '__main__':\n    val()\n"
  },
  {
    "path": "ultralytics/yolo/v8/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom ultralytics.yolo.v8 import classify, detect, pose, segment, DecSeg\n\n__all__ = 'classify', 'segment', 'detect', 'pose', 'DecSeg'\n"
  },
  {
    "path": "ultralytics/yolo/v8/classify/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom ultralytics.yolo.v8.classify.predict import ClassificationPredictor, predict\nfrom ultralytics.yolo.v8.classify.train import ClassificationTrainer, train\nfrom ultralytics.yolo.v8.classify.val import ClassificationValidator, val\n\n__all__ = 'ClassificationPredictor', 'predict', 'ClassificationTrainer', 'train', 'ClassificationValidator', 'val'\n"
  },
  {
    "path": "ultralytics/yolo/v8/classify/predict.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\n\nfrom ultralytics.yolo.engine.predictor import BasePredictor\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils import DEFAULT_CFG, ROOT\n\n\nclass ClassificationPredictor(BasePredictor):\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        super().__init__(cfg, overrides, _callbacks)\n        self.args.task = 'classify'\n\n    def preprocess(self, img):\n        \"\"\"Converts input image to model-compatible data type.\"\"\"\n        if not isinstance(img, torch.Tensor):\n            img = torch.stack([self.transforms(im) for im in img], dim=0)\n        img = (img if isinstance(img, torch.Tensor) else torch.from_numpy(img)).to(self.model.device)\n        return img.half() if self.model.fp16 else img.float()  # uint8 to fp16/32\n\n    def postprocess(self, preds, img, orig_imgs):\n        \"\"\"Postprocesses predictions to return Results objects.\"\"\"\n        results = []\n        for i, pred in enumerate(preds):\n            orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            results.append(Results(orig_img=orig_img, path=img_path, names=self.model.names, probs=pred))\n\n        return results\n\n\ndef predict(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Run YOLO model predictions on input images/videos.\"\"\"\n    model = cfg.model or 'yolov8n-cls.pt'  # or \"resnet18\"\n    source = cfg.source if cfg.source is not None else ROOT / 'assets' if (ROOT / 'assets').exists() \\\n        else 'https://ultralytics.com/images/bus.jpg'\n\n    args = dict(model=model, source=source)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model)(**args)\n    else:\n        predictor = ClassificationPredictor(overrides=args)\n        predictor.predict_cli()\n\n\nif __name__ == '__main__':\n    predict()\n"
  },
  {
    "path": "ultralytics/yolo/v8/classify/train.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\nimport torchvision\n\nfrom ultralytics.nn.tasks import ClassificationModel, attempt_load_one_weight\nfrom ultralytics.yolo import v8\nfrom ultralytics.yolo.data import ClassificationDataset, build_dataloader\nfrom ultralytics.yolo.engine.trainer import BaseTrainer\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, RANK, colorstr\nfrom ultralytics.yolo.utils.plotting import plot_images, plot_results\nfrom ultralytics.yolo.utils.torch_utils import is_parallel, strip_optimizer, torch_distributed_zero_first\n\n\nclass ClassificationTrainer(BaseTrainer):\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        \"\"\"Initialize a ClassificationTrainer object with optional configuration overrides and callbacks.\"\"\"\n        if overrides is None:\n            overrides = {}\n        overrides['task'] = 'classify'\n        if overrides.get('imgsz') is None:\n            overrides['imgsz'] = 224\n        super().__init__(cfg, overrides, _callbacks)\n\n    def set_model_attributes(self):\n        \"\"\"Set the YOLO model's class names from the loaded dataset.\"\"\"\n        self.model.names = self.data['names']\n\n    def get_model(self, cfg=None, weights=None, verbose=True):\n        \"\"\"Returns a modified PyTorch model configured for training YOLO.\"\"\"\n        model = ClassificationModel(cfg, nc=self.data['nc'], verbose=verbose and RANK == -1)\n        if weights:\n            model.load(weights)\n\n        pretrained = self.args.pretrained\n        for m in model.modules():\n            if not pretrained and hasattr(m, 'reset_parameters'):\n                m.reset_parameters()\n            if isinstance(m, torch.nn.Dropout) and self.args.dropout:\n                m.p = self.args.dropout  # set dropout\n        for p in model.parameters():\n            p.requires_grad = True  # for training\n\n        return model\n\n    def setup_model(self):\n        \"\"\"\n        load/create/download model for any task\n        \"\"\"\n        # Classification models require special handling\n\n        if isinstance(self.model, torch.nn.Module):  # if model is loaded beforehand. No setup needed\n            return\n\n        model = str(self.model)\n        # Load a YOLO model locally, from torchvision, or from Ultralytics assets\n        if model.endswith('.pt'):\n            self.model, _ = attempt_load_one_weight(model, device='cpu')\n            for p in self.model.parameters():\n                p.requires_grad = True  # for training\n        elif model.endswith('.yaml'):\n            self.model = self.get_model(cfg=model)\n        elif model in torchvision.models.__dict__:\n            pretrained = True\n            self.model = torchvision.models.__dict__[model](weights='IMAGENET1K_V1' if pretrained else None)\n        else:\n            FileNotFoundError(f'ERROR: model={model} not found locally or online. Please check model name.')\n        ClassificationModel.reshape_outputs(self.model, self.data['nc'])\n\n        return  # dont return ckpt. Classification doesn't support resume\n\n    def build_dataset(self, img_path, mode='train', batch=None):\n        return ClassificationDataset(root=img_path, args=self.args, augment=mode == 'train')\n\n    def get_dataloader(self, dataset_path, batch_size=16, rank=0, mode='train'):\n        \"\"\"Returns PyTorch DataLoader with transforms to preprocess images for inference.\"\"\"\n        with torch_distributed_zero_first(rank):  # init dataset *.cache only once if DDP\n            dataset = self.build_dataset(dataset_path, mode)\n\n        loader = build_dataloader(dataset, batch_size, self.args.workers, rank=rank)\n        # Attach inference transforms\n        if mode != 'train':\n            if is_parallel(self.model):\n                self.model.module.transforms = loader.dataset.torch_transforms\n            else:\n                self.model.transforms = loader.dataset.torch_transforms\n        return loader\n\n    def preprocess_batch(self, batch):\n        \"\"\"Preprocesses a batch of images and classes.\"\"\"\n        batch['img'] = batch['img'].to(self.device)\n        batch['cls'] = batch['cls'].to(self.device)\n        return batch\n\n    def progress_string(self):\n        \"\"\"Returns a formatted string showing training progress.\"\"\"\n        return ('\\n' + '%11s' * (4 + len(self.loss_names))) % \\\n            ('Epoch', 'GPU_mem', *self.loss_names, 'Instances', 'Size')\n\n    def get_validator(self):\n        \"\"\"Returns an instance of ClassificationValidator for validation.\"\"\"\n        self.loss_names = ['loss']\n        return v8.classify.ClassificationValidator(self.test_loader, self.save_dir)\n\n    def criterion(self, preds, batch):\n        \"\"\"Compute the classification loss between predictions and true labels.\"\"\"\n        loss = torch.nn.functional.cross_entropy(preds, batch['cls'], reduction='sum') / self.args.nbs\n        loss_items = loss.detach()\n        return loss, loss_items\n\n    def label_loss_items(self, loss_items=None, prefix='train'):\n        \"\"\"\n        Returns a loss dict with labelled training loss items tensor\n        \"\"\"\n        # Not needed for classification but necessary for segmentation & detection\n        keys = [f'{prefix}/{x}' for x in self.loss_names]\n        if loss_items is None:\n            return keys\n        loss_items = [round(float(loss_items), 5)]\n        return dict(zip(keys, loss_items))\n\n    def resume_training(self, ckpt):\n        \"\"\"Resumes training from a given checkpoint.\"\"\"\n        pass\n\n    def plot_metrics(self):\n        \"\"\"Plots metrics from a CSV file.\"\"\"\n        plot_results(file=self.csv, classify=True, on_plot=self.on_plot)  # save results.png\n\n    def final_eval(self):\n        \"\"\"Evaluate trained model and save validation results.\"\"\"\n        for f in self.last, self.best:\n            if f.exists():\n                strip_optimizer(f)  # strip optimizers\n                # TODO: validate best.pt after training completes\n                # if f is self.best:\n                #     LOGGER.info(f'\\nValidating {f}...')\n                #     self.validator.args.save_json = True\n                #     self.metrics = self.validator(model=f)\n                #     self.metrics.pop('fitness', None)\n                #     self.run_callbacks('on_fit_epoch_end')\n        LOGGER.info(f\"Results saved to {colorstr('bold', self.save_dir)}\")\n\n    def plot_training_samples(self, batch, ni):\n        \"\"\"Plots training samples with their annotations.\"\"\"\n        plot_images(images=batch['img'],\n                    batch_idx=torch.arange(len(batch['img'])),\n                    cls=batch['cls'].squeeze(-1),\n                    fname=self.save_dir / f'train_batch{ni}.jpg',\n                    on_plot=self.on_plot)\n\n\ndef train(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Train the YOLO classification model.\"\"\"\n    model = cfg.model or 'yolov8n-cls.pt'  # or \"resnet18\"\n    data = cfg.data or 'mnist160'  # or yolo.ClassificationDataset(\"mnist\")\n    device = cfg.device if cfg.device is not None else ''\n\n    args = dict(model=model, data=data, device=device)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).train(**args)\n    else:\n        trainer = ClassificationTrainer(overrides=args)\n        trainer.train()\n\n\nif __name__ == '__main__':\n    train()\n"
  },
  {
    "path": "ultralytics/yolo/v8/classify/val.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\n\nfrom ultralytics.yolo.data import ClassificationDataset, build_dataloader\nfrom ultralytics.yolo.engine.validator import BaseValidator\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER\nfrom ultralytics.yolo.utils.metrics import ClassifyMetrics, ConfusionMatrix\nfrom ultralytics.yolo.utils.plotting import plot_images\n\n\nclass ClassificationValidator(BaseValidator):\n\n    def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):\n        \"\"\"Initializes ClassificationValidator instance with args, dataloader, save_dir, and progress bar.\"\"\"\n        super().__init__(dataloader, save_dir, pbar, args, _callbacks)\n        self.args.task = 'classify'\n        self.metrics = ClassifyMetrics()\n\n    def get_desc(self):\n        \"\"\"Returns a formatted string summarizing classification metrics.\"\"\"\n        return ('%22s' + '%11s' * 2) % ('classes', 'top1_acc', 'top5_acc')\n\n    def init_metrics(self, model):\n        \"\"\"Initialize confusion matrix, class names, and top-1 and top-5 accuracy.\"\"\"\n        self.names = model.names\n        self.nc = len(model.names)\n        self.confusion_matrix = ConfusionMatrix(nc=self.nc, task='classify')\n        self.pred = []\n        self.targets = []\n\n    def preprocess(self, batch):\n        \"\"\"Preprocesses input batch and returns it.\"\"\"\n        batch['img'] = batch['img'].to(self.device, non_blocking=True)\n        batch['img'] = batch['img'].half() if self.args.half else batch['img'].float()\n        batch['cls'] = batch['cls'].to(self.device)\n        return batch\n\n    def update_metrics(self, preds, batch):\n        \"\"\"Updates running metrics with model predictions and batch targets.\"\"\"\n        n5 = min(len(self.model.names), 5)\n        self.pred.append(preds.argsort(1, descending=True)[:, :n5])\n        self.targets.append(batch['cls'])\n\n    def finalize_metrics(self, *args, **kwargs):\n        \"\"\"Finalizes metrics of the model such as confusion_matrix and speed.\"\"\"\n        self.confusion_matrix.process_cls_preds(self.pred, self.targets)\n        if self.args.plots:\n            for normalize in True, False:\n                self.confusion_matrix.plot(save_dir=self.save_dir,\n                                           names=self.names.values(),\n                                           normalize=normalize,\n                                           on_plot=self.on_plot)\n        self.metrics.speed = self.speed\n        self.metrics.confusion_matrix = self.confusion_matrix\n\n    def get_stats(self):\n        \"\"\"Returns a dictionary of metrics obtained by processing targets and predictions.\"\"\"\n        self.metrics.process(self.targets, self.pred)\n        return self.metrics.results_dict\n\n    def build_dataset(self, img_path):\n        dataset = ClassificationDataset(root=img_path, args=self.args, augment=False)\n        return dataset\n\n    def get_dataloader(self, dataset_path, batch_size):\n        \"\"\"Builds and returns a data loader for classification tasks with given parameters.\"\"\"\n        dataset = self.build_dataset(dataset_path)\n        return build_dataloader(dataset, batch_size, self.args.workers, rank=-1)\n\n    def print_results(self):\n        \"\"\"Prints evaluation metrics for YOLO object detection model.\"\"\"\n        pf = '%22s' + '%11.3g' * len(self.metrics.keys)  # print format\n        LOGGER.info(pf % ('all', self.metrics.top1, self.metrics.top5))\n\n    def plot_val_samples(self, batch, ni):\n        \"\"\"Plot validation image samples.\"\"\"\n        plot_images(images=batch['img'],\n                    batch_idx=torch.arange(len(batch['img'])),\n                    cls=batch['cls'].squeeze(-1),\n                    fname=self.save_dir / f'val_batch{ni}_labels.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)\n\n    def plot_predictions(self, batch, preds, ni):\n        \"\"\"Plots predicted bounding boxes on input images and saves the result.\"\"\"\n        plot_images(batch['img'],\n                    batch_idx=torch.arange(len(batch['img'])),\n                    cls=torch.argmax(preds, dim=1),\n                    fname=self.save_dir / f'val_batch{ni}_pred.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)  # pred\n\n\ndef val(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Validate YOLO model using custom data.\"\"\"\n    model = cfg.model or 'yolov8n-cls.pt'  # or \"resnet18\"\n    data = cfg.data or 'mnist160'\n\n    args = dict(model=model, data=data)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).val(**args)\n    else:\n        validator = ClassificationValidator(args=args)\n        validator(model=args['model'])\n\n\nif __name__ == '__main__':\n    val()\n"
  },
  {
    "path": "ultralytics/yolo/v8/detect/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .predict import DetectionPredictor, predict\nfrom .train import DetectionTrainer, train\nfrom .val import DetectionValidator, val\n\n__all__ = 'DetectionPredictor', 'predict', 'DetectionTrainer', 'train', 'DetectionValidator', 'val'\n"
  },
  {
    "path": "ultralytics/yolo/v8/detect/predict.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\n\nfrom ultralytics.yolo.engine.predictor import BasePredictor\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils import DEFAULT_CFG, ROOT, ops\n\n\nclass DetectionPredictor(BasePredictor):\n\n    def postprocess(self, preds, img, orig_imgs):\n        \"\"\"Postprocesses predictions and returns a list of Results objects.\"\"\"\n        preds = ops.non_max_suppression(preds,\n                                        self.args.conf,\n                                        self.args.iou,\n                                        agnostic=self.args.agnostic_nms,\n                                        max_det=self.args.max_det,\n                                        classes=self.args.classes)\n\n        results = []\n        for i, pred in enumerate(preds):\n            orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs\n            if not isinstance(orig_imgs, torch.Tensor):\n                pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            results.append(Results(orig_img=orig_img, path=img_path, names=self.model.names, boxes=pred))\n        return results\n\n\ndef predict(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Runs YOLO model inference on input image(s).\"\"\"\n    model = cfg.model or 'yolov8n.pt'\n    source = cfg.source if cfg.source is not None else ROOT / 'assets' if (ROOT / 'assets').exists() \\\n        else 'https://ultralytics.com/images/bus.jpg'\n\n    args = dict(model=model, source=source)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model)(**args)\n    else:\n        predictor = DetectionPredictor(overrides=args)\n        predictor.predict_cli()\n\n\nif __name__ == '__main__':\n    predict()\n"
  },
  {
    "path": "ultralytics/yolo/v8/detect/train.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nfrom copy import copy\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom ultralytics.nn.tasks import DetectionModel\nfrom ultralytics.yolo import v8\nfrom ultralytics.yolo.data import build_dataloader, build_yolo_dataset\nfrom ultralytics.yolo.data.dataloaders.v5loader import create_dataloader\nfrom ultralytics.yolo.engine.trainer import BaseTrainer\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, RANK, colorstr\nfrom ultralytics.yolo.utils.loss import BboxLoss\nfrom ultralytics.yolo.utils.ops import xywh2xyxy\nfrom ultralytics.yolo.utils.plotting import plot_images, plot_labels, plot_results\nfrom ultralytics.yolo.utils.tal import TaskAlignedAssigner, dist2bbox, make_anchors\nfrom ultralytics.yolo.utils.torch_utils import de_parallel, torch_distributed_zero_first\n\n\n# BaseTrainer python usage\nclass DetectionTrainer(BaseTrainer):\n\n    def build_dataset(self, img_path, mode='train', batch=None):\n        \"\"\"Build YOLO Dataset\n\n        Args:\n            img_path (str): Path to the folder containing images.\n            mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.\n            batch (int, optional): Size of batches, this is for `rect`. Defaults to None.\n        \"\"\"\n        gs = max(int(de_parallel(self.model).stride.max() if self.model else 0), 32)\n        return build_yolo_dataset(self.args, img_path, batch, self.data, mode=mode, rect=mode == 'val', stride=gs)\n\n    def get_dataloader(self, dataset_path, batch_size=16, rank=0, mode='train'):\n        \"\"\"TODO: manage splits differently.\"\"\"\n        # Calculate stride - check if model is initialized\n        if self.args.v5loader:\n            LOGGER.warning(\"WARNING ⚠️ 'v5loader' feature is deprecated and will be removed soon. You can train using \"\n                           'the default YOLOv8 dataloader instead, no argument is needed.')\n            gs = max(int(de_parallel(self.model).stride.max() if self.model else 0), 32)\n            return create_dataloader(path=dataset_path,\n                                     imgsz=self.args.imgsz,\n                                     batch_size=batch_size,\n                                     stride=gs,\n                                     hyp=vars(self.args),\n                                     augment=mode == 'train',\n                                     cache=self.args.cache,\n                                     pad=0 if mode == 'train' else 0.5,\n                                     rect=self.args.rect or mode == 'val',\n                                     rank=rank,\n                                     workers=self.args.workers,\n                                     close_mosaic=self.args.close_mosaic != 0,\n                                     prefix=colorstr(f'{mode}: '),\n                                     shuffle=mode == 'train',\n                                     seed=self.args.seed)[0]\n        assert mode in ['train', 'val']\n        with torch_distributed_zero_first(rank):  # init dataset *.cache only once if DDP\n            dataset = self.build_dataset(dataset_path, mode, batch_size)\n        shuffle = mode == 'train'\n        if getattr(dataset, 'rect', False) and shuffle:\n            LOGGER.warning(\"WARNING ⚠️ 'rect=True' is incompatible with DataLoader shuffle, setting shuffle=False\")\n            shuffle = False\n        workers = self.args.workers if mode == 'train' else self.args.workers * 2\n        return build_dataloader(dataset, batch_size, workers, shuffle, rank)  # return dataloader\n\n    def preprocess_batch(self, batch):\n        \"\"\"Preprocesses a batch of images by scaling and converting to float.\"\"\"\n        batch['img'] = batch['img'].to(self.device, non_blocking=True).float() / 255\n        return batch\n\n    def set_model_attributes(self):\n        \"\"\"nl = de_parallel(self.model).model[-1].nl  # number of detection layers (to scale hyps).\"\"\"\n        # self.args.box *= 3 / nl  # scale to layers\n        # self.args.cls *= self.data[\"nc\"] / 80 * 3 / nl  # scale to classes and layers\n        # self.args.cls *= (self.args.imgsz / 640) ** 2 * 3 / nl  # scale to image size and layers\n        self.model.nc = self.data['nc']  # attach number of classes to model\n        self.model.names = self.data['names']  # attach class names to model\n        self.model.args = self.args  # attach hyperparameters to model\n        # TODO: self.model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc\n\n    def get_model(self, cfg=None, weights=None, verbose=True):\n        \"\"\"Return a YOLO detection model.\"\"\"\n        model = DetectionModel(cfg, nc=self.data['nc'], verbose=verbose and RANK == -1)\n        if weights:\n            model.load(weights)\n        return model\n\n    def get_validator(self):\n        \"\"\"Returns a DetectionValidator for YOLO model validation.\"\"\"\n        self.loss_names = 'box_loss', 'cls_loss', 'dfl_loss'\n        return v8.detect.DetectionValidator(self.test_loader, save_dir=self.save_dir, args=copy(self.args))\n\n    def criterion(self, preds, batch):\n        \"\"\"Compute loss for YOLO prediction and ground-truth.\"\"\"\n        if not hasattr(self, 'compute_loss'):\n            self.compute_loss = Loss(de_parallel(self.model))\n        return self.compute_loss(preds, batch)\n\n    def label_loss_items(self, loss_items=None, prefix='train'):\n        \"\"\"\n        Returns a loss dict with labelled training loss items tensor\n        \"\"\"\n        # Not needed for classification but necessary for segmentation & detection\n        keys = [f'{prefix}/{x}' for x in self.loss_names]\n        if loss_items is not None:\n            loss_items = [round(float(x), 5) for x in loss_items]  # convert tensors to 5 decimal place floats\n            return dict(zip(keys, loss_items))\n        else:\n            return keys\n\n    def progress_string(self):\n        \"\"\"Returns a formatted string of training progress with epoch, GPU memory, loss, instances and size.\"\"\"\n        return ('\\n' + '%11s' *\n                (4 + len(self.loss_names))) % ('Epoch', 'GPU_mem', *self.loss_names, 'Instances', 'Size')\n\n    def plot_training_samples(self, batch, ni):\n        \"\"\"Plots training samples with their annotations.\"\"\"\n        plot_images(images=batch['img'],\n                    batch_idx=batch['batch_idx'],\n                    cls=batch['cls'].squeeze(-1),\n                    bboxes=batch['bboxes'],\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'train_batch{ni}.jpg',\n                    on_plot=self.on_plot)\n\n    def plot_metrics(self):\n        \"\"\"Plots metrics from a CSV file.\"\"\"\n        plot_results(file=self.csv, on_plot=self.on_plot)  # save results.png\n\n    def plot_training_labels(self):\n        \"\"\"Create a labeled training plot of the YOLO model.\"\"\"\n        boxes = np.concatenate([lb['bboxes'] for lb in self.train_loader.dataset.labels], 0)\n        cls = np.concatenate([lb['cls'] for lb in self.train_loader.dataset.labels], 0)\n        plot_labels(boxes, cls.squeeze(), names=self.data['names'], save_dir=self.save_dir, on_plot=self.on_plot)\n\n\n# Criterion class for computing training losses\nclass Loss:\n\n    def __init__(self, model):  # model must be de-paralleled\n\n        device = next(model.parameters()).device  # get model device\n        h = model.args  # hyperparameters\n\n        m = model.model[-1]  # Detect() module\n        self.bce = nn.BCEWithLogitsLoss(reduction='none')\n        self.hyp = h\n        self.stride = m.stride  # model strides\n        self.nc = m.nc  # number of classes\n        self.no = m.no\n        self.reg_max = m.reg_max\n        self.device = device\n\n        self.use_dfl = m.reg_max > 1\n\n        self.assigner = TaskAlignedAssigner(topk=10, num_classes=self.nc, alpha=0.5, beta=6.0)\n        self.bbox_loss = BboxLoss(m.reg_max - 1, use_dfl=self.use_dfl).to(device)\n        self.proj = torch.arange(m.reg_max, dtype=torch.float, device=device)\n\n    def preprocess(self, targets, batch_size, scale_tensor):\n        \"\"\"Preprocesses the target counts and matches with the input batch size to output a tensor.\"\"\"\n        if targets.shape[0] == 0:\n            out = torch.zeros(batch_size, 0, 5, device=self.device)\n        else:\n            i = targets[:, 0]  # image index\n            _, counts = i.unique(return_counts=True)\n            counts = counts.to(dtype=torch.int32)\n            out = torch.zeros(batch_size, counts.max(), 5, device=self.device)\n            for j in range(batch_size):\n                matches = i == j\n                n = matches.sum()\n                if n:\n                    out[j, :n] = targets[matches, 1:]\n            out[..., 1:5] = xywh2xyxy(out[..., 1:5].mul_(scale_tensor))\n        return out\n\n    def bbox_decode(self, anchor_points, pred_dist):\n        \"\"\"Decode predicted object bounding box coordinates from anchor points and distribution.\"\"\"\n        if self.use_dfl:\n            b, a, c = pred_dist.shape  # batch, anchors, channels\n            pred_dist = pred_dist.view(b, a, 4, c // 4).softmax(3).matmul(self.proj.type(pred_dist.dtype))\n            # pred_dist = pred_dist.view(b, a, c // 4, 4).transpose(2,3).softmax(3).matmul(self.proj.type(pred_dist.dtype))\n            # pred_dist = (pred_dist.view(b, a, c // 4, 4).softmax(2) * self.proj.type(pred_dist.dtype).view(1, 1, -1, 1)).sum(2)\n        return dist2bbox(pred_dist, anchor_points, xywh=False)\n\n    def __call__(self, preds, batch):\n        \"\"\"Calculate the sum of the loss for box, cls and dfl multiplied by batch size.\"\"\"\n        loss = torch.zeros(3, device=self.device)  # box, cls, dfl\n        feats = preds[1] if isinstance(preds, tuple) else preds\n        pred_distri, pred_scores = torch.cat([xi.view(feats[0].shape[0], self.no, -1) for xi in feats], 2).split(\n            (self.reg_max * 4, self.nc), 1)\n\n        pred_scores = pred_scores.permute(0, 2, 1).contiguous()\n        pred_distri = pred_distri.permute(0, 2, 1).contiguous()\n\n        dtype = pred_scores.dtype\n        batch_size = pred_scores.shape[0]\n        imgsz = torch.tensor(feats[0].shape[2:], device=self.device, dtype=dtype) * self.stride[0]  # image size (h,w)\n        anchor_points, stride_tensor = make_anchors(feats, self.stride, 0.5)\n\n        # targets\n        targets = torch.cat((batch['batch_idx'].view(-1, 1), batch['cls'].view(-1, 1), batch['bboxes']), 1)\n        targets = self.preprocess(targets.to(self.device), batch_size, scale_tensor=imgsz[[1, 0, 1, 0]])\n        gt_labels, gt_bboxes = targets.split((1, 4), 2)  # cls, xyxy\n        mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0)\n\n        # pboxes\n        pred_bboxes = self.bbox_decode(anchor_points, pred_distri)  # xyxy, (b, h*w, 4)\n\n        _, target_bboxes, target_scores, fg_mask, _ = self.assigner(\n            pred_scores.detach().sigmoid(), (pred_bboxes.detach() * stride_tensor).type(gt_bboxes.dtype),\n            anchor_points * stride_tensor, gt_labels, gt_bboxes, mask_gt)\n\n        target_scores_sum = max(target_scores.sum(), 1)\n\n        # cls loss\n        # loss[1] = self.varifocal_loss(pred_scores, target_scores, target_labels) / target_scores_sum  # VFL way\n        loss[1] = self.bce(pred_scores, target_scores.to(dtype)).sum() / target_scores_sum  # BCE\n\n        # bbox loss\n        if fg_mask.sum():\n            target_bboxes /= stride_tensor\n            loss[0], loss[2] = self.bbox_loss(pred_distri, pred_bboxes, anchor_points, target_bboxes, target_scores,\n                                              target_scores_sum, fg_mask)\n\n        loss[0] *= self.hyp.box  # box gain\n        loss[1] *= self.hyp.cls  # cls gain\n        loss[2] *= self.hyp.dfl  # dfl gain\n\n        return loss.sum() * batch_size, loss.detach()  # loss(box, cls, dfl)\n\n\ndef train(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Train and optimize YOLO model given training data and device.\"\"\"\n    model = cfg.model or 'yolov8n.pt'\n    data = cfg.data or 'coco128.yaml'  # or yolo.ClassificationDataset(\"mnist\")\n    device = cfg.device if cfg.device is not None else ''\n\n    args = dict(model=model, data=data, device=device)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).train(**args)\n    else:\n        trainer = DetectionTrainer(overrides=args)\n        trainer.train()\n\n\nif __name__ == '__main__':\n    train()\n"
  },
  {
    "path": "ultralytics/yolo/v8/detect/val.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport os\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\n\nfrom ultralytics.yolo.data import build_dataloader, build_yolo_dataset\nfrom ultralytics.yolo.data.dataloaders.v5loader import create_dataloader\nfrom ultralytics.yolo.engine.validator import BaseValidator\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, colorstr, ops\nfrom ultralytics.yolo.utils.checks import check_requirements\nfrom ultralytics.yolo.utils.metrics import ConfusionMatrix, DetMetrics, box_iou\nfrom ultralytics.yolo.utils.plotting import output_to_target, plot_images\nfrom ultralytics.yolo.utils.torch_utils import de_parallel\n\n\nclass DetectionValidator(BaseValidator):\n\n    def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):\n        \"\"\"Initialize detection model with necessary variables and settings.\"\"\"\n        super().__init__(dataloader, save_dir, pbar, args, _callbacks)\n        self.args.task = 'detect'\n        self.is_coco = False\n        self.class_map = None\n        self.metrics = DetMetrics(save_dir=self.save_dir, on_plot=self.on_plot)\n        self.iouv = torch.linspace(0.5, 0.95, 10)  # iou vector for mAP@0.5:0.95\n        self.niou = self.iouv.numel()\n\n    def preprocess(self, batch):\n        \"\"\"Preprocesses batch of images for YOLO training.\"\"\"\n        batch['img'] = batch['img'].to(self.device, non_blocking=True)\n        batch['img'] = (batch['img'].half() if self.args.half else batch['img'].float()) / 255\n        for k in ['batch_idx', 'cls', 'bboxes']:\n            batch[k] = batch[k].to(self.device)\n\n        nb = len(batch['img'])\n        self.lb = [torch.cat([batch['cls'], batch['bboxes']], dim=-1)[batch['batch_idx'] == i]\n                   for i in range(nb)] if self.args.save_hybrid else []  # for autolabelling\n\n        return batch\n\n    def init_metrics(self, model):\n        \"\"\"Initialize evaluation metrics for YOLO.\"\"\"\n        val = self.data.get(self.args.split, '')  # validation path\n        self.is_coco = isinstance(val, str) and 'coco' in val and val.endswith(f'{os.sep}val2017.txt')  # is COCO\n        self.class_map = ops.coco80_to_coco91_class() if self.is_coco else list(range(1000))\n        self.args.save_json |= self.is_coco and not self.training  # run on final val if training COCO\n        self.names = model.names\n        self.nc = len(model.names)\n        self.metrics.names = self.names\n        self.metrics.plot = self.args.plots\n        self.confusion_matrix = ConfusionMatrix(nc=self.nc)\n        self.seen = 0\n        self.jdict = []\n        self.stats = []\n\n    def get_desc(self):\n        \"\"\"Return a formatted string summarizing class metrics of YOLO model.\"\"\"\n        return ('%22s' + '%11s' * 6) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95)')\n\n    def postprocess(self, preds):\n        \"\"\"Apply Non-maximum suppression to prediction outputs.\"\"\"\n        preds = ops.non_max_suppression(preds,\n                                        self.args.conf,\n                                        self.args.iou,\n                                        labels=self.lb,\n                                        multi_label=True,\n                                        agnostic=self.args.single_cls,\n                                        max_det=self.args.max_det)\n        return preds\n\n    def update_metrics(self, preds, batch):\n        \"\"\"Metrics.\"\"\"\n        for si, pred in enumerate(preds):\n            idx = batch['batch_idx'] == si\n            cls = batch['cls'][idx]\n            bbox = batch['bboxes'][idx]\n            nl, npr = cls.shape[0], pred.shape[0]  # number of labels, predictions\n            shape = batch['ori_shape'][si]\n            correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n            self.seen += 1\n\n            if npr == 0:\n                if nl:\n                    self.stats.append((correct_bboxes, *torch.zeros((2, 0), device=self.device), cls.squeeze(-1)))\n                    if self.args.plots:\n                        self.confusion_matrix.process_batch(detections=None, labels=cls.squeeze(-1))\n                continue\n\n            # Predictions\n            if self.args.single_cls:\n                pred[:, 5] = 0\n            predn = pred.clone()\n            ops.scale_boxes(batch['img'][si].shape[1:], predn[:, :4], shape,\n                            ratio_pad=batch['ratio_pad'][si])  # native-space pred\n\n            # Evaluate\n            if nl:\n                height, width = batch['img'].shape[2:]\n                tbox = ops.xywh2xyxy(bbox) * torch.tensor(\n                    (width, height, width, height), device=self.device)  # target boxes\n                ops.scale_boxes(batch['img'][si].shape[1:], tbox, shape,\n                                ratio_pad=batch['ratio_pad'][si])  # native-space labels\n                labelsn = torch.cat((cls, tbox), 1)  # native-space labels\n                correct_bboxes = self._process_batch(predn, labelsn)\n                # TODO: maybe remove these `self.` arguments as they already are member variable\n                if self.args.plots:\n                    self.confusion_matrix.process_batch(predn, labelsn)\n            self.stats.append((correct_bboxes, pred[:, 4], pred[:, 5], cls.squeeze(-1)))  # (conf, pcls, tcls)\n\n            # Save\n            if self.args.save_json:\n                self.pred_to_json(predn, batch['im_file'][si])\n            if self.args.save_txt:\n                file = self.save_dir / 'labels' / f'{Path(batch[\"im_file\"][si]).stem}.txt'\n                self.save_one_txt(predn, self.args.save_conf, shape, file)\n\n    def finalize_metrics(self, *args, **kwargs):\n        \"\"\"Set final values for metrics speed and confusion matrix.\"\"\"\n        self.metrics.speed = self.speed\n        self.metrics.confusion_matrix = self.confusion_matrix\n\n    def get_stats(self):\n        \"\"\"Returns metrics statistics and results dictionary.\"\"\"\n        stats = [torch.cat(x, 0).cpu().numpy() for x in zip(*self.stats)]  # to numpy\n        if len(stats) and stats[0].any():\n            self.metrics.process(*stats)\n        self.nt_per_class = np.bincount(stats[-1].astype(int), minlength=self.nc)  # number of targets per class\n        return self.metrics.results_dict\n\n    def print_results(self):\n        \"\"\"Prints training/validation set metrics per class.\"\"\"\n        pf = '%22s' + '%11i' * 2 + '%11.3g' * len(self.metrics.keys)  # print format\n        LOGGER.info(pf % ('all', self.seen, self.nt_per_class.sum(), *self.metrics.mean_results()))\n        if self.nt_per_class.sum() == 0:\n            LOGGER.warning(\n                f'WARNING ⚠️ no labels found in {self.args.task} set, can not compute metrics without labels')\n\n        # Print results per class\n        if self.args.verbose and not self.training and self.nc > 1 and len(self.stats):\n            for i, c in enumerate(self.metrics.ap_class_index):\n                LOGGER.info(pf % (self.names[c], self.seen, self.nt_per_class[c], *self.metrics.class_result(i)))\n\n        if self.args.plots:\n            for normalize in True, False:\n                self.confusion_matrix.plot(save_dir=self.save_dir,\n                                           names=self.names.values(),\n                                           normalize=normalize,\n                                           on_plot=self.on_plot)\n\n    def _process_batch(self, detections, labels):\n        \"\"\"\n        Return correct prediction matrix\n        Arguments:\n            detections (array[N, 6]), x1, y1, x2, y2, conf, class\n            labels (array[M, 5]), class, x1, y1, x2, y2\n        Returns:\n            correct (array[N, 10]), for 10 IoU levels\n        \"\"\"\n        iou = box_iou(labels[:, 1:], detections[:, :4])\n        correct = np.zeros((detections.shape[0], self.iouv.shape[0])).astype(bool)\n        correct_class = labels[:, 0:1] == detections[:, 5]\n        for i in range(len(self.iouv)):\n            x = torch.where((iou >= self.iouv[i]) & correct_class)  # IoU > threshold and classes match\n            if x[0].shape[0]:\n                matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]),\n                                    1).cpu().numpy()  # [label, detect, iou]\n                if x[0].shape[0] > 1:\n                    matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                    # matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n                correct[matches[:, 1].astype(int), i] = True\n        return torch.tensor(correct, dtype=torch.bool, device=detections.device)\n\n    def build_dataset(self, img_path, mode='val', batch=None):\n        \"\"\"Build YOLO Dataset\n\n        Args:\n            img_path (str): Path to the folder containing images.\n            mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.\n            batch (int, optional): Size of batches, this is for `rect`. Defaults to None.\n        \"\"\"\n        gs = max(int(de_parallel(self.model).stride if self.model else 0), 32)\n        return build_yolo_dataset(self.args, img_path, batch, self.data, mode=mode, stride=gs)\n\n    def get_dataloader(self, dataset_path, batch_size):\n        \"\"\"TODO: manage splits differently.\"\"\"\n        # Calculate stride - check if model is initialized\n        if self.args.v5loader:\n            LOGGER.warning(\"WARNING ⚠️ 'v5loader' feature is deprecated and will be removed soon. You can train using \"\n                           'the default YOLOv8 dataloader instead, no argument is needed.')\n            gs = max(int(de_parallel(self.model).stride if self.model else 0), 32)\n            return create_dataloader(path=dataset_path,\n                                     imgsz=self.args.imgsz,\n                                     batch_size=batch_size,\n                                     stride=gs,\n                                     hyp=vars(self.args),\n                                     cache=False,\n                                     pad=0.5,\n                                     rect=self.args.rect,\n                                     workers=self.args.workers,\n                                     prefix=colorstr(f'{self.args.mode}: '),\n                                     shuffle=False,\n                                     seed=self.args.seed)[0]\n\n        dataset = self.build_dataset(dataset_path, batch=batch_size, mode='val')\n        dataloader = build_dataloader(dataset, batch_size, self.args.workers, shuffle=False, rank=-1)\n        return dataloader\n\n    def plot_val_samples(self, batch, ni):\n        \"\"\"Plot validation image samples.\"\"\"\n        plot_images(batch['img'],\n                    batch['batch_idx'],\n                    batch['cls'].squeeze(-1),\n                    batch['bboxes'],\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'val_batch{ni}_labels.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)\n\n    def plot_predictions(self, batch, preds, ni):\n        \"\"\"Plots predicted bounding boxes on input images and saves the result.\"\"\"\n        plot_images(batch['img'],\n                    *output_to_target(preds, max_det=15),\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'val_batch{ni}_pred.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)  # pred\n\n    def save_one_txt(self, predn, save_conf, shape, file):\n        \"\"\"Save YOLO detections to a txt file in normalized coordinates in a specific format.\"\"\"\n        gn = torch.tensor(shape)[[1, 0, 1, 0]]  # normalization gain whwh\n        for *xyxy, conf, cls in predn.tolist():\n            xywh = (ops.xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh\n            line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format\n            with open(file, 'a') as f:\n                f.write(('%g ' * len(line)).rstrip() % line + '\\n')\n\n    def pred_to_json(self, predn, filename):\n        \"\"\"Serialize YOLO predictions to COCO json format.\"\"\"\n        stem = Path(filename).stem\n        image_id = int(stem) if stem.isnumeric() else stem\n        box = ops.xyxy2xywh(predn[:, :4])  # xywh\n        box[:, :2] -= box[:, 2:] / 2  # xy center to top-left corner\n        for p, b in zip(predn.tolist(), box.tolist()):\n            self.jdict.append({\n                'image_id': image_id,\n                'category_id': self.class_map[int(p[5])],\n                'bbox': [round(x, 3) for x in b],\n                'score': round(p[4], 5)})\n\n    def eval_json(self, stats):\n        \"\"\"Evaluates YOLO output in JSON format and returns performance statistics.\"\"\"\n        if self.args.save_json and self.is_coco and len(self.jdict):\n            anno_json = self.data['path'] / 'annotations/instances_val2017.json'  # annotations\n            pred_json = self.save_dir / 'predictions.json'  # predictions\n            LOGGER.info(f'\\nEvaluating pycocotools mAP using {pred_json} and {anno_json}...')\n            try:  # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n                check_requirements('pycocotools>=2.0.6')\n                from pycocotools.coco import COCO  # noqa\n                from pycocotools.cocoeval import COCOeval  # noqa\n\n                for x in anno_json, pred_json:\n                    assert x.is_file(), f'{x} file not found'\n                anno = COCO(str(anno_json))  # init annotations api\n                pred = anno.loadRes(str(pred_json))  # init predictions api (must pass string, not Path)\n                eval = COCOeval(anno, pred, 'bbox')\n                if self.is_coco:\n                    eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files]  # images to eval\n                eval.evaluate()\n                eval.accumulate()\n                eval.summarize()\n                stats[self.metrics.keys[-1]], stats[self.metrics.keys[-2]] = eval.stats[:2]  # update mAP50-95 and mAP50\n            except Exception as e:\n                LOGGER.warning(f'pycocotools unable to run: {e}')\n        return stats\n\n\ndef val(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Validate trained YOLO model on validation dataset.\"\"\"\n    model = cfg.model or 'yolov8n.pt'\n    data = cfg.data or 'coco128.yaml'\n\n    args = dict(model=model, data=data)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).val(**args)\n    else:\n        validator = DetectionValidator(args=args)\n        validator(model=args['model'])\n\n\nif __name__ == '__main__':\n    val()\n"
  },
  {
    "path": "ultralytics/yolo/v8/pose/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .predict import PosePredictor, predict\nfrom .train import PoseTrainer, train\nfrom .val import PoseValidator, val\n\n__all__ = 'PoseTrainer', 'train', 'PoseValidator', 'val', 'PosePredictor', 'predict'\n"
  },
  {
    "path": "ultralytics/yolo/v8/pose/predict.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils import DEFAULT_CFG, ROOT, ops\nfrom ultralytics.yolo.v8.detect.predict import DetectionPredictor\n\n\nclass PosePredictor(DetectionPredictor):\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        super().__init__(cfg, overrides, _callbacks)\n        self.args.task = 'pose'\n\n    def postprocess(self, preds, img, orig_img):\n        \"\"\"Return detection results for a given input image or list of images.\"\"\"\n        preds = ops.non_max_suppression(preds,\n                                        self.args.conf,\n                                        self.args.iou,\n                                        agnostic=self.args.agnostic_nms,\n                                        max_det=self.args.max_det,\n                                        classes=self.args.classes,\n                                        nc=len(self.model.names))\n\n        results = []\n        for i, pred in enumerate(preds):\n            orig_img = orig_img[i] if isinstance(orig_img, list) else orig_img\n            shape = orig_img.shape\n            pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], shape).round()\n            pred_kpts = pred[:, 6:].view(len(pred), *self.model.kpt_shape) if len(pred) else pred[:, 6:]\n            pred_kpts = ops.scale_coords(img.shape[2:], pred_kpts, shape)\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            results.append(\n                Results(orig_img=orig_img,\n                        path=img_path,\n                        names=self.model.names,\n                        boxes=pred[:, :6],\n                        keypoints=pred_kpts))\n        return results\n\n\ndef predict(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Runs YOLO to predict objects in an image or video.\"\"\"\n    model = cfg.model or 'yolov8n-pose.pt'\n    source = cfg.source if cfg.source is not None else ROOT / 'assets' if (ROOT / 'assets').exists() \\\n        else 'https://ultralytics.com/images/bus.jpg'\n\n    args = dict(model=model, source=source)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model)(**args)\n    else:\n        predictor = PosePredictor(overrides=args)\n        predictor.predict_cli()\n\n\nif __name__ == '__main__':\n    predict()\n"
  },
  {
    "path": "ultralytics/yolo/v8/pose/train.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom copy import copy\n\nimport torch\nimport torch.nn as nn\n\nfrom ultralytics.nn.tasks import PoseModel\nfrom ultralytics.yolo import v8\nfrom ultralytics.yolo.utils import DEFAULT_CFG\nfrom ultralytics.yolo.utils.loss import KeypointLoss\nfrom ultralytics.yolo.utils.metrics import OKS_SIGMA\nfrom ultralytics.yolo.utils.ops import xyxy2xywh\nfrom ultralytics.yolo.utils.plotting import plot_images, plot_results\nfrom ultralytics.yolo.utils.tal import make_anchors\nfrom ultralytics.yolo.utils.torch_utils import de_parallel\nfrom ultralytics.yolo.v8.detect.train import Loss\n\n\n# BaseTrainer python usage\nclass PoseTrainer(v8.detect.DetectionTrainer):\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        \"\"\"Initialize a PoseTrainer object with specified configurations and overrides.\"\"\"\n        if overrides is None:\n            overrides = {}\n        overrides['task'] = 'pose'\n        super().__init__(cfg, overrides, _callbacks)\n\n    def get_model(self, cfg=None, weights=None, verbose=True):\n        \"\"\"Get pose estimation model with specified configuration and weights.\"\"\"\n        model = PoseModel(cfg, ch=3, nc=self.data['nc'], data_kpt_shape=self.data['kpt_shape'], verbose=verbose)\n        if weights:\n            model.load(weights)\n\n        return model\n\n    def set_model_attributes(self):\n        \"\"\"Sets keypoints shape attribute of PoseModel.\"\"\"\n        super().set_model_attributes()\n        self.model.kpt_shape = self.data['kpt_shape']\n\n    def get_validator(self):\n        \"\"\"Returns an instance of the PoseValidator class for validation.\"\"\"\n        self.loss_names = 'box_loss', 'pose_loss', 'kobj_loss', 'cls_loss', 'dfl_loss'\n        return v8.pose.PoseValidator(self.test_loader, save_dir=self.save_dir, args=copy(self.args))\n\n    def criterion(self, preds, batch):\n        \"\"\"Computes pose loss for the YOLO model.\"\"\"\n        if not hasattr(self, 'compute_loss'):\n            self.compute_loss = PoseLoss(de_parallel(self.model))\n        return self.compute_loss(preds, batch)\n\n    def plot_training_samples(self, batch, ni):\n        \"\"\"Plot a batch of training samples with annotated class labels, bounding boxes, and keypoints.\"\"\"\n        images = batch['img']\n        kpts = batch['keypoints']\n        cls = batch['cls'].squeeze(-1)\n        bboxes = batch['bboxes']\n        paths = batch['im_file']\n        batch_idx = batch['batch_idx']\n        plot_images(images,\n                    batch_idx,\n                    cls,\n                    bboxes,\n                    kpts=kpts,\n                    paths=paths,\n                    fname=self.save_dir / f'train_batch{ni}.jpg',\n                    on_plot=self.on_plot)\n\n    def plot_metrics(self):\n        \"\"\"Plots training/val metrics.\"\"\"\n        plot_results(file=self.csv, pose=True, on_plot=self.on_plot)  # save results.png\n\n\n# Criterion class for computing training losses\nclass PoseLoss(Loss):\n\n    def __init__(self, model):  # model must be de-paralleled\n        super().__init__(model)\n        self.kpt_shape = model.model[-1].kpt_shape\n        self.bce_pose = nn.BCEWithLogitsLoss()\n        is_pose = self.kpt_shape == [17, 3]\n        nkpt = self.kpt_shape[0]  # number of keypoints\n        sigmas = torch.from_numpy(OKS_SIGMA).to(self.device) if is_pose else torch.ones(nkpt, device=self.device) / nkpt\n        self.keypoint_loss = KeypointLoss(sigmas=sigmas)\n\n    def __call__(self, preds, batch):\n        \"\"\"Calculate the total loss and detach it.\"\"\"\n        loss = torch.zeros(5, device=self.device)  # box, cls, dfl, kpt_location, kpt_visibility\n        feats, pred_kpts = preds if isinstance(preds[0], list) else preds[1]\n        pred_distri, pred_scores = torch.cat([xi.view(feats[0].shape[0], self.no, -1) for xi in feats], 2).split(\n            (self.reg_max * 4, self.nc), 1)\n\n        # b, grids, ..\n        pred_scores = pred_scores.permute(0, 2, 1).contiguous()\n        pred_distri = pred_distri.permute(0, 2, 1).contiguous()\n        pred_kpts = pred_kpts.permute(0, 2, 1).contiguous()\n\n        dtype = pred_scores.dtype\n        imgsz = torch.tensor(feats[0].shape[2:], device=self.device, dtype=dtype) * self.stride[0]  # image size (h,w)\n        anchor_points, stride_tensor = make_anchors(feats, self.stride, 0.5)\n\n        # targets\n        batch_size = pred_scores.shape[0]\n        batch_idx = batch['batch_idx'].view(-1, 1)\n        targets = torch.cat((batch_idx, batch['cls'].view(-1, 1), batch['bboxes']), 1)\n        targets = self.preprocess(targets.to(self.device), batch_size, scale_tensor=imgsz[[1, 0, 1, 0]])\n        gt_labels, gt_bboxes = targets.split((1, 4), 2)  # cls, xyxy\n        mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0)\n\n        # pboxes\n        pred_bboxes = self.bbox_decode(anchor_points, pred_distri)  # xyxy, (b, h*w, 4)\n        pred_kpts = self.kpts_decode(anchor_points, pred_kpts.view(batch_size, -1, *self.kpt_shape))  # (b, h*w, 17, 3)\n\n        _, target_bboxes, target_scores, fg_mask, target_gt_idx = self.assigner(\n            pred_scores.detach().sigmoid(), (pred_bboxes.detach() * stride_tensor).type(gt_bboxes.dtype),\n            anchor_points * stride_tensor, gt_labels, gt_bboxes, mask_gt)\n\n        target_scores_sum = max(target_scores.sum(), 1)\n\n        # cls loss\n        # loss[1] = self.varifocal_loss(pred_scores, target_scores, target_labels) / target_scores_sum  # VFL way\n        loss[3] = self.bce(pred_scores, target_scores.to(dtype)).sum() / target_scores_sum  # BCE\n\n        # bbox loss\n        if fg_mask.sum():\n            target_bboxes /= stride_tensor\n            loss[0], loss[4] = self.bbox_loss(pred_distri, pred_bboxes, anchor_points, target_bboxes, target_scores,\n                                              target_scores_sum, fg_mask)\n            keypoints = batch['keypoints'].to(self.device).float().clone()\n            keypoints[..., 0] *= imgsz[1]\n            keypoints[..., 1] *= imgsz[0]\n            for i in range(batch_size):\n                if fg_mask[i].sum():\n                    idx = target_gt_idx[i][fg_mask[i]]\n                    gt_kpt = keypoints[batch_idx.view(-1) == i][idx]  # (n, 51)\n                    gt_kpt[..., 0] /= stride_tensor[fg_mask[i]]\n                    gt_kpt[..., 1] /= stride_tensor[fg_mask[i]]\n                    area = xyxy2xywh(target_bboxes[i][fg_mask[i]])[:, 2:].prod(1, keepdim=True)\n                    pred_kpt = pred_kpts[i][fg_mask[i]]\n                    kpt_mask = gt_kpt[..., 2] != 0\n                    loss[1] += self.keypoint_loss(pred_kpt, gt_kpt, kpt_mask, area)  # pose loss\n                    # kpt_score loss\n                    if pred_kpt.shape[-1] == 3:\n                        loss[2] += self.bce_pose(pred_kpt[..., 2], kpt_mask.float())  # keypoint obj loss\n\n        loss[0] *= self.hyp.box  # box gain\n        loss[1] *= self.hyp.pose / batch_size  # pose gain\n        loss[2] *= self.hyp.kobj / batch_size  # kobj gain\n        loss[3] *= self.hyp.cls  # cls gain\n        loss[4] *= self.hyp.dfl  # dfl gain\n\n        return loss.sum() * batch_size, loss.detach()  # loss(box, cls, dfl)\n\n    def kpts_decode(self, anchor_points, pred_kpts):\n        \"\"\"Decodes predicted keypoints to image coordinates.\"\"\"\n        y = pred_kpts.clone()\n        y[..., :2] *= 2.0\n        y[..., 0] += anchor_points[:, [0]] - 0.5\n        y[..., 1] += anchor_points[:, [1]] - 0.5\n        return y\n\n\ndef train(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Train the YOLO model on the given data and device.\"\"\"\n    model = cfg.model or 'yolov8n-pose.yaml'\n    data = cfg.data or 'coco8-pose.yaml'\n    device = cfg.device if cfg.device is not None else ''\n\n    args = dict(model=model, data=data, device=device)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).train(**args)\n    else:\n        trainer = PoseTrainer(overrides=args)\n        trainer.train()\n\n\nif __name__ == '__main__':\n    train()\n"
  },
  {
    "path": "ultralytics/yolo/v8/pose/val.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\n\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, ops\nfrom ultralytics.yolo.utils.checks import check_requirements\nfrom ultralytics.yolo.utils.metrics import OKS_SIGMA, PoseMetrics, box_iou, kpt_iou\nfrom ultralytics.yolo.utils.plotting import output_to_target, plot_images\nfrom ultralytics.yolo.v8.detect import DetectionValidator\n\n\nclass PoseValidator(DetectionValidator):\n\n    def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):\n        \"\"\"Initialize a 'PoseValidator' object with custom parameters and assigned attributes.\"\"\"\n        super().__init__(dataloader, save_dir, pbar, args, _callbacks)\n        self.args.task = 'pose'\n        self.metrics = PoseMetrics(save_dir=self.save_dir, on_plot=self.on_plot)\n\n    def preprocess(self, batch):\n        \"\"\"Preprocesses the batch by converting the 'keypoints' data into a float and moving it to the device.\"\"\"\n        batch = super().preprocess(batch)\n        batch['keypoints'] = batch['keypoints'].to(self.device).float()\n        return batch\n\n    def get_desc(self):\n        \"\"\"Returns description of evaluation metrics in string format.\"\"\"\n        return ('%22s' + '%11s' * 10) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95)', 'Pose(P',\n                                         'R', 'mAP50', 'mAP50-95)')\n\n    def postprocess(self, preds):\n        \"\"\"Apply non-maximum suppression and return detections with high confidence scores.\"\"\"\n        preds = ops.non_max_suppression(preds,\n                                        self.args.conf,\n                                        self.args.iou,\n                                        labels=self.lb,\n                                        multi_label=True,\n                                        agnostic=self.args.single_cls,\n                                        max_det=self.args.max_det,\n                                        nc=self.nc)\n        return preds\n\n    def init_metrics(self, model):\n        \"\"\"Initiate pose estimation metrics for YOLO model.\"\"\"\n        super().init_metrics(model)\n        self.kpt_shape = self.data['kpt_shape']\n        is_pose = self.kpt_shape == [17, 3]\n        nkpt = self.kpt_shape[0]\n        self.sigma = OKS_SIGMA if is_pose else np.ones(nkpt) / nkpt\n\n    def update_metrics(self, preds, batch):\n        \"\"\"Metrics.\"\"\"\n        for si, pred in enumerate(preds):\n            idx = batch['batch_idx'] == si\n            cls = batch['cls'][idx]\n            bbox = batch['bboxes'][idx]\n            kpts = batch['keypoints'][idx]\n            nl, npr = cls.shape[0], pred.shape[0]  # number of labels, predictions\n            nk = kpts.shape[1]  # number of keypoints\n            shape = batch['ori_shape'][si]\n            correct_kpts = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n            correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n            self.seen += 1\n\n            if npr == 0:\n                if nl:\n                    self.stats.append((correct_bboxes, correct_kpts, *torch.zeros(\n                        (2, 0), device=self.device), cls.squeeze(-1)))\n                    if self.args.plots:\n                        self.confusion_matrix.process_batch(detections=None, labels=cls.squeeze(-1))\n                continue\n\n            # Predictions\n            if self.args.single_cls:\n                pred[:, 5] = 0\n            predn = pred.clone()\n            ops.scale_boxes(batch['img'][si].shape[1:], predn[:, :4], shape,\n                            ratio_pad=batch['ratio_pad'][si])  # native-space pred\n            pred_kpts = predn[:, 6:].view(npr, nk, -1)\n            ops.scale_coords(batch['img'][si].shape[1:], pred_kpts, shape, ratio_pad=batch['ratio_pad'][si])\n\n            # Evaluate\n            if nl:\n                height, width = batch['img'].shape[2:]\n                tbox = ops.xywh2xyxy(bbox) * torch.tensor(\n                    (width, height, width, height), device=self.device)  # target boxes\n                ops.scale_boxes(batch['img'][si].shape[1:], tbox, shape,\n                                ratio_pad=batch['ratio_pad'][si])  # native-space labels\n                tkpts = kpts.clone()\n                tkpts[..., 0] *= width\n                tkpts[..., 1] *= height\n                tkpts = ops.scale_coords(batch['img'][si].shape[1:], tkpts, shape, ratio_pad=batch['ratio_pad'][si])\n                labelsn = torch.cat((cls, tbox), 1)  # native-space labels\n                correct_bboxes = self._process_batch(predn[:, :6], labelsn)\n                correct_kpts = self._process_batch(predn[:, :6], labelsn, pred_kpts, tkpts)\n                if self.args.plots:\n                    self.confusion_matrix.process_batch(predn, labelsn)\n\n            # Append correct_masks, correct_boxes, pconf, pcls, tcls\n            self.stats.append((correct_bboxes, correct_kpts, pred[:, 4], pred[:, 5], cls.squeeze(-1)))\n\n            # Save\n            if self.args.save_json:\n                self.pred_to_json(predn, batch['im_file'][si])\n            # if self.args.save_txt:\n            #    save_one_txt(predn, save_conf, shape, file=save_dir / 'labels' / f'{path.stem}.txt')\n\n    def _process_batch(self, detections, labels, pred_kpts=None, gt_kpts=None):\n        \"\"\"\n        Return correct prediction matrix\n        Arguments:\n            detections (array[N, 6]), x1, y1, x2, y2, conf, class\n            labels (array[M, 5]), class, x1, y1, x2, y2\n            pred_kpts (array[N, 51]), 51 = 17 * 3\n            gt_kpts (array[N, 51])\n        Returns:\n            correct (array[N, 10]), for 10 IoU levels\n        \"\"\"\n        if pred_kpts is not None and gt_kpts is not None:\n            # `0.53` is from https://github.com/jin-s13/xtcocoapi/blob/master/xtcocotools/cocoeval.py#L384\n            area = ops.xyxy2xywh(labels[:, 1:])[:, 2:].prod(1) * 0.53\n            iou = kpt_iou(gt_kpts, pred_kpts, sigma=self.sigma, area=area)\n        else:  # boxes\n            iou = box_iou(labels[:, 1:], detections[:, :4])\n\n        correct = np.zeros((detections.shape[0], self.iouv.shape[0])).astype(bool)\n        correct_class = labels[:, 0:1] == detections[:, 5]\n        for i in range(len(self.iouv)):\n            x = torch.where((iou >= self.iouv[i]) & correct_class)  # IoU > threshold and classes match\n            if x[0].shape[0]:\n                matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]),\n                                    1).cpu().numpy()  # [label, detect, iou]\n                if x[0].shape[0] > 1:\n                    matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                    # matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n                correct[matches[:, 1].astype(int), i] = True\n        return torch.tensor(correct, dtype=torch.bool, device=detections.device)\n\n    def plot_val_samples(self, batch, ni):\n        \"\"\"Plots and saves validation set samples with predicted bounding boxes and keypoints.\"\"\"\n        plot_images(batch['img'],\n                    batch['batch_idx'],\n                    batch['cls'].squeeze(-1),\n                    batch['bboxes'],\n                    kpts=batch['keypoints'],\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'val_batch{ni}_labels.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)\n\n    def plot_predictions(self, batch, preds, ni):\n        \"\"\"Plots predictions for YOLO model.\"\"\"\n        pred_kpts = torch.cat([p[:, 6:].view(-1, *self.kpt_shape)[:15] for p in preds], 0)\n        plot_images(batch['img'],\n                    *output_to_target(preds, max_det=15),\n                    kpts=pred_kpts,\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'val_batch{ni}_pred.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)  # pred\n\n    def pred_to_json(self, predn, filename):\n        \"\"\"Converts YOLO predictions to COCO JSON format.\"\"\"\n        stem = Path(filename).stem\n        image_id = int(stem) if stem.isnumeric() else stem\n        box = ops.xyxy2xywh(predn[:, :4])  # xywh\n        box[:, :2] -= box[:, 2:] / 2  # xy center to top-left corner\n        for p, b in zip(predn.tolist(), box.tolist()):\n            self.jdict.append({\n                'image_id': image_id,\n                'category_id': self.class_map[int(p[5])],\n                'bbox': [round(x, 3) for x in b],\n                'keypoints': p[6:],\n                'score': round(p[4], 5)})\n\n    def eval_json(self, stats):\n        \"\"\"Evaluates object detection model using COCO JSON format.\"\"\"\n        if self.args.save_json and self.is_coco and len(self.jdict):\n            anno_json = self.data['path'] / 'annotations/person_keypoints_val2017.json'  # annotations\n            pred_json = self.save_dir / 'predictions.json'  # predictions\n            LOGGER.info(f'\\nEvaluating pycocotools mAP using {pred_json} and {anno_json}...')\n            try:  # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n                check_requirements('pycocotools>=2.0.6')\n                from pycocotools.coco import COCO  # noqa\n                from pycocotools.cocoeval import COCOeval  # noqa\n\n                for x in anno_json, pred_json:\n                    assert x.is_file(), f'{x} file not found'\n                anno = COCO(str(anno_json))  # init annotations api\n                pred = anno.loadRes(str(pred_json))  # init predictions api (must pass string, not Path)\n                for i, eval in enumerate([COCOeval(anno, pred, 'bbox'), COCOeval(anno, pred, 'keypoints')]):\n                    if self.is_coco:\n                        eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files]  # im to eval\n                    eval.evaluate()\n                    eval.accumulate()\n                    eval.summarize()\n                    idx = i * 4 + 2\n                    stats[self.metrics.keys[idx + 1]], stats[\n                        self.metrics.keys[idx]] = eval.stats[:2]  # update mAP50-95 and mAP50\n            except Exception as e:\n                LOGGER.warning(f'pycocotools unable to run: {e}')\n        return stats\n\n\ndef val(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Performs validation on YOLO model using given data.\"\"\"\n    model = cfg.model or 'yolov8n-pose.pt'\n    data = cfg.data or 'coco8-pose.yaml'\n\n    args = dict(model=model, data=data)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).val(**args)\n    else:\n        validator = PoseValidator(args=args)\n        validator(model=args['model'])\n\n\nif __name__ == '__main__':\n    val()\n"
  },
  {
    "path": "ultralytics/yolo/v8/segment/__init__.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom .predict import SegmentationPredictor, predict\nfrom .train import SegmentationTrainer, train\nfrom .val import SegmentationValidator, val\n\n__all__ = 'SegmentationPredictor', 'predict', 'SegmentationTrainer', 'train', 'SegmentationValidator', 'val'\n"
  },
  {
    "path": "ultralytics/yolo/v8/segment/predict.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nimport torch\n\nfrom ultralytics.yolo.engine.results import Results\nfrom ultralytics.yolo.utils import DEFAULT_CFG, ROOT, ops\nfrom ultralytics.yolo.v8.detect.predict import DetectionPredictor\n\n\nclass SegmentationPredictor(DetectionPredictor):\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        super().__init__(cfg, overrides, _callbacks)\n        self.args.task = 'segment'\n\n    def postprocess(self, preds, img, orig_imgs):\n        \"\"\"TODO: filter by classes.\"\"\"\n        p = ops.non_max_suppression(preds[0],\n                                    self.args.conf,\n                                    self.args.iou,\n                                    agnostic=self.args.agnostic_nms,\n                                    max_det=self.args.max_det,\n                                    nc=len(self.model.names),\n                                    classes=self.args.classes)\n        results = []\n        proto = preds[1][-1] if len(preds[1]) == 3 else preds[1]  # second output is len 3 if pt, but only 1 if exported\n        for i, pred in enumerate(p):\n            orig_img = orig_imgs[i] if isinstance(orig_imgs, list) else orig_imgs\n            path = self.batch[0]\n            img_path = path[i] if isinstance(path, list) else path\n            if not len(pred):  # save empty boxes\n                results.append(Results(orig_img=orig_img, path=img_path, names=self.model.names, boxes=pred[:, :6]))\n                continue\n            if self.args.retina_masks:\n                if not isinstance(orig_imgs, torch.Tensor):\n                    pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)\n                masks = ops.process_mask_native(proto[i], pred[:, 6:], pred[:, :4], orig_img.shape[:2])  # HWC\n            else:\n                masks = ops.process_mask(proto[i], pred[:, 6:], pred[:, :4], img.shape[2:], upsample=True)  # HWC\n                if not isinstance(orig_imgs, torch.Tensor):\n                    pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)\n            results.append(\n                Results(orig_img=orig_img, path=img_path, names=self.model.names, boxes=pred[:, :6], masks=masks))\n        return results\n\n\ndef predict(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Runs YOLO object detection on an image or video source.\"\"\"\n    model = cfg.model or 'yolov8n-seg.pt'\n    source = cfg.source if cfg.source is not None else ROOT / 'assets' if (ROOT / 'assets').exists() \\\n        else 'https://ultralytics.com/images/bus.jpg'\n\n    args = dict(model=model, source=source)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model)(**args)\n    else:\n        predictor = SegmentationPredictor(overrides=args)\n        predictor.predict_cli()\n\n\nif __name__ == '__main__':\n    predict()\n"
  },
  {
    "path": "ultralytics/yolo/v8/segment/train.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\nfrom copy import copy\n\nimport torch\nimport torch.nn.functional as F\n\nfrom ultralytics.nn.tasks import SegmentationModel\nfrom ultralytics.yolo import v8\nfrom ultralytics.yolo.utils import DEFAULT_CFG, RANK\nfrom ultralytics.yolo.utils.ops import crop_mask, xyxy2xywh\nfrom ultralytics.yolo.utils.plotting import plot_images, plot_results\nfrom ultralytics.yolo.utils.tal import make_anchors\nfrom ultralytics.yolo.utils.torch_utils import de_parallel\nfrom ultralytics.yolo.v8.detect.train import Loss\n\n\n# BaseTrainer python usage\nclass SegmentationTrainer(v8.detect.DetectionTrainer):\n\n    def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):\n        \"\"\"Initialize a SegmentationTrainer object with given arguments.\"\"\"\n        if overrides is None:\n            overrides = {}\n        overrides['task'] = 'segment'\n        super().__init__(cfg, overrides, _callbacks)\n\n    def get_model(self, cfg=None, weights=None, verbose=True):\n        \"\"\"Return SegmentationModel initialized with specified config and weights.\"\"\"\n        model = SegmentationModel(cfg, ch=3, nc=self.data['nc'], verbose=verbose and RANK == -1)\n        if weights:\n            model.load(weights)\n\n        return model\n\n    def get_validator(self):\n        \"\"\"Return an instance of SegmentationValidator for validation of YOLO model.\"\"\"\n        self.loss_names = 'box_loss', 'seg_loss', 'cls_loss', 'dfl_loss'\n        return v8.segment.SegmentationValidator(self.test_loader, save_dir=self.save_dir, args=copy(self.args))\n\n    def criterion(self, preds, batch):\n        \"\"\"Returns the computed loss using the SegLoss class on the given predictions and batch.\"\"\"\n        if not hasattr(self, 'compute_loss'):\n            self.compute_loss = SegLoss(de_parallel(self.model), overlap=self.args.overlap_mask)\n        return self.compute_loss(preds, batch)\n\n    def plot_training_samples(self, batch, ni):\n        \"\"\"Creates a plot of training sample images with labels and box coordinates.\"\"\"\n        plot_images(batch['img'],\n                    batch['batch_idx'],\n                    batch['cls'].squeeze(-1),\n                    batch['bboxes'],\n                    batch['masks'],\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'train_batch{ni}.jpg',\n                    on_plot=self.on_plot)\n\n    def plot_metrics(self):\n        \"\"\"Plots training/val metrics.\"\"\"\n        plot_results(file=self.csv, segment=True, on_plot=self.on_plot)  # save results.png\n\n\n# Criterion class for computing training losses\nclass SegLoss(Loss):\n\n    def __init__(self, model, overlap=True):  # model must be de-paralleled\n        super().__init__(model)\n        self.nm = model.model[-1].nm  # number of masks\n        self.overlap = overlap\n\n    def __call__(self, preds, batch):\n        \"\"\"Calculate and return the loss for the YOLO model.\"\"\"\n        loss = torch.zeros(4, device=self.device)  # box, cls, dfl\n        feats, pred_masks, proto = preds if len(preds) == 3 else preds[1]\n        batch_size, _, mask_h, mask_w = proto.shape  # batch size, number of masks, mask height, mask width\n        pred_distri, pred_scores = torch.cat([xi.view(feats[0].shape[0], self.no, -1) for xi in feats], 2).split(\n            (self.reg_max * 4, self.nc), 1)\n\n        # b, grids, ..\n        pred_scores = pred_scores.permute(0, 2, 1).contiguous()\n        pred_distri = pred_distri.permute(0, 2, 1).contiguous()\n        pred_masks = pred_masks.permute(0, 2, 1).contiguous()\n\n        dtype = pred_scores.dtype\n        imgsz = torch.tensor(feats[0].shape[2:], device=self.device, dtype=dtype) * self.stride[0]  # image size (h,w)\n        anchor_points, stride_tensor = make_anchors(feats, self.stride, 0.5)\n\n        # targets\n        try:\n            batch_idx = batch['batch_idx'].view(-1, 1)\n            targets = torch.cat((batch_idx, batch['cls'].view(-1, 1), batch['bboxes']), 1)\n            targets = self.preprocess(targets.to(self.device), batch_size, scale_tensor=imgsz[[1, 0, 1, 0]])\n            gt_labels, gt_bboxes = targets.split((1, 4), 2)  # cls, xyxy\n            mask_gt = gt_bboxes.sum(2, keepdim=True).gt_(0)\n        except RuntimeError as e:\n            raise TypeError('ERROR ❌ segment dataset incorrectly formatted or not a segment dataset.\\n'\n                            \"This error can occur when incorrectly training a 'segment' model on a 'detect' dataset, \"\n                            \"i.e. 'yolo train model=yolov8n-seg.pt data=coco128.yaml'.\\nVerify your dataset is a \"\n                            \"correctly formatted 'segment' dataset using 'data=coco128-seg.yaml' \"\n                            'as an example.\\nSee https://docs.ultralytics.com/tasks/segment/ for help.') from e\n\n        # pboxes\n        pred_bboxes = self.bbox_decode(anchor_points, pred_distri)  # xyxy, (b, h*w, 4)\n\n        _, target_bboxes, target_scores, fg_mask, target_gt_idx = self.assigner(\n            pred_scores.detach().sigmoid(), (pred_bboxes.detach() * stride_tensor).type(gt_bboxes.dtype),\n            anchor_points * stride_tensor, gt_labels, gt_bboxes, mask_gt)\n\n        target_scores_sum = max(target_scores.sum(), 1)\n\n        # cls loss\n        # loss[1] = self.varifocal_loss(pred_scores, target_scores, target_labels) / target_scores_sum  # VFL way\n        loss[2] = self.bce(pred_scores, target_scores.to(dtype)).sum() / target_scores_sum  # BCE\n\n        if fg_mask.sum():\n            # bbox loss\n            loss[0], loss[3] = self.bbox_loss(pred_distri, pred_bboxes, anchor_points, target_bboxes / stride_tensor,\n                                              target_scores, target_scores_sum, fg_mask)\n            # masks loss\n            masks = batch['masks'].to(self.device).float()\n            if tuple(masks.shape[-2:]) != (mask_h, mask_w):  # downsample\n                masks = F.interpolate(masks[None], (mask_h, mask_w), mode='nearest')[0]\n\n            for i in range(batch_size):\n                if fg_mask[i].sum():\n                    mask_idx = target_gt_idx[i][fg_mask[i]]\n                    if self.overlap:\n                        gt_mask = torch.where(masks[[i]] == (mask_idx + 1).view(-1, 1, 1), 1.0, 0.0)\n                    else:\n                        gt_mask = masks[batch_idx.view(-1) == i][mask_idx]\n                    xyxyn = target_bboxes[i][fg_mask[i]] / imgsz[[1, 0, 1, 0]]\n                    marea = xyxy2xywh(xyxyn)[:, 2:].prod(1)\n                    mxyxy = xyxyn * torch.tensor([mask_w, mask_h, mask_w, mask_h], device=self.device)\n                    loss[1] += self.single_mask_loss(gt_mask, pred_masks[i][fg_mask[i]], proto[i], mxyxy, marea)  # seg\n\n                # WARNING: lines below prevents Multi-GPU DDP 'unused gradient' PyTorch errors, do not remove\n                else:\n                    loss[1] += (proto * 0).sum() + (pred_masks * 0).sum()  # inf sums may lead to nan loss\n\n        # WARNING: lines below prevent Multi-GPU DDP 'unused gradient' PyTorch errors, do not remove\n        else:\n            loss[1] += (proto * 0).sum() + (pred_masks * 0).sum()  # inf sums may lead to nan loss\n\n        loss[0] *= self.hyp.box  # box gain\n        loss[1] *= self.hyp.box / batch_size  # seg gain\n        loss[2] *= self.hyp.cls  # cls gain\n        loss[3] *= self.hyp.dfl  # dfl gain\n\n        return loss.sum() * batch_size, loss.detach()  # loss(box, cls, dfl)\n\n    def single_mask_loss(self, gt_mask, pred, proto, xyxy, area):\n        \"\"\"Mask loss for one image.\"\"\"\n        pred_mask = (pred @ proto.view(self.nm, -1)).view(-1, *proto.shape[1:])  # (n, 32) @ (32,80,80) -> (n,80,80)\n        loss = F.binary_cross_entropy_with_logits(pred_mask, gt_mask, reduction='none')\n        return (crop_mask(loss, xyxy).mean(dim=(1, 2)) / area).mean()\n\n\ndef train(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Train a YOLO segmentation model based on passed arguments.\"\"\"\n    model = cfg.model or 'yolov8n-seg.pt'\n    data = cfg.data or 'coco128-seg.yaml'  # or yolo.ClassificationDataset(\"mnist\")\n    device = cfg.device if cfg.device is not None else ''\n\n    args = dict(model=model, data=data, device=device)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).train(**args)\n    else:\n        trainer = SegmentationTrainer(overrides=args)\n        trainer.train()\n\n\nif __name__ == '__main__':\n    train()\n"
  },
  {
    "path": "ultralytics/yolo/v8/segment/val.py",
    "content": "# Ultralytics YOLO 🚀, AGPL-3.0 license\n\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\n\nfrom ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, NUM_THREADS, ops\nfrom ultralytics.yolo.utils.checks import check_requirements\nfrom ultralytics.yolo.utils.metrics import SegmentMetrics, box_iou, mask_iou\nfrom ultralytics.yolo.utils.plotting import output_to_target, plot_images\nfrom ultralytics.yolo.v8.detect import DetectionValidator\n\n\nclass SegmentationValidator(DetectionValidator):\n\n    def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):\n        \"\"\"Initialize SegmentationValidator and set task to 'segment', metrics to SegmentMetrics.\"\"\"\n        super().__init__(dataloader, save_dir, pbar, args, _callbacks)\n        self.args.task = 'segment'\n        self.metrics = SegmentMetrics(save_dir=self.save_dir, on_plot=self.on_plot)\n\n    def preprocess(self, batch):\n        \"\"\"Preprocesses batch by converting masks to float and sending to device.\"\"\"\n        batch = super().preprocess(batch)\n        batch['masks'] = batch['masks'].to(self.device).float()\n        return batch\n\n    def init_metrics(self, model):\n        \"\"\"Initialize metrics and select mask processing function based on save_json flag.\"\"\"\n        super().init_metrics(model)\n        self.plot_masks = []\n        if self.args.save_json:\n            check_requirements('pycocotools>=2.0.6')\n            self.process = ops.process_mask_upsample  # more accurate\n        else:\n            self.process = ops.process_mask  # faster\n\n    def get_desc(self):\n        \"\"\"Return a formatted description of evaluation metrics.\"\"\"\n        return ('%22s' + '%11s' * 10) % ('Class', 'Images', 'Instances', 'Box(P', 'R', 'mAP50', 'mAP50-95)', 'Mask(P',\n                                         'R', 'mAP50', 'mAP50-95)')\n\n    def postprocess(self, preds):\n        \"\"\"Postprocesses YOLO predictions and returns output detections with proto.\"\"\"\n        p = ops.non_max_suppression(preds[0],\n                                    self.args.conf,\n                                    self.args.iou,\n                                    labels=self.lb,\n                                    multi_label=True,\n                                    agnostic=self.args.single_cls,\n                                    max_det=self.args.max_det,\n                                    nc=self.nc)\n        proto = preds[1][-1] if len(preds[1]) == 3 else preds[1]  # second output is len 3 if pt, but only 1 if exported\n        return p, proto\n\n    def update_metrics(self, preds, batch):\n        \"\"\"Metrics.\"\"\"\n        miou_global = []\n        for si, (pred, proto) in enumerate(zip(preds[0], preds[1])):\n            idx = batch['batch_idx'] == si\n            cls = batch['cls'][idx]\n            bbox = batch['bboxes'][idx]\n            nl, npr = cls.shape[0], pred.shape[0]  # number of labels, predictions\n            shape = batch['ori_shape'][si]\n            correct_masks = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n            correct_bboxes = torch.zeros(npr, self.niou, dtype=torch.bool, device=self.device)  # init\n            self.seen += 1\n\n            if npr == 0:\n                if nl:\n                    self.stats.append((correct_bboxes, correct_masks, *torch.zeros(\n                        (2, 0), device=self.device), cls.squeeze(-1)))\n                    if self.args.plots:\n                        self.confusion_matrix.process_batch(detections=None, labels=cls.squeeze(-1))\n                continue\n\n            # Masks\n            midx = [si] if self.args.overlap_mask else idx\n            gt_masks = batch['masks'][midx]\n            pred_masks = self.process(proto, pred[:, 6:], pred[:, :4], shape=batch['img'][si].shape[1:])\n\n            # Predictions\n            if self.args.single_cls:\n                pred[:, 5] = 0\n            predn = pred.clone()\n            ops.scale_boxes(batch['img'][si].shape[1:], predn[:, :4], shape,\n                            ratio_pad=batch['ratio_pad'][si])  # native-space pred\n\n            # Evaluate\n            if nl:\n                height, width = batch['img'].shape[2:]\n                tbox = ops.xywh2xyxy(bbox) * torch.tensor(\n                    (width, height, width, height), device=self.device)  # target boxes\n                ops.scale_boxes(batch['img'][si].shape[1:], tbox, shape,\n                                ratio_pad=batch['ratio_pad'][si])  # native-space labels\n                labelsn = torch.cat((cls, tbox), 1)  # native-space labels\n                correct_bboxes = self._process_batch(predn, labelsn)\n                # TODO: maybe remove these `self.` arguments as they already are member variable\n                correct_masks = self._process_batch(predn,\n                                                    labelsn,\n                                                    pred_masks,\n                                                    gt_masks,\n                                                    overlap=self.args.overlap_mask,\n                                                    masks=True)\n                if self.args.plots:\n                    self.confusion_matrix.process_batch(predn, labelsn)\n                    # print('mIoU: ', self.confusion_matrix.meanIntersectionOverUnion())\n\n            # Append correct_masks, correct_boxes, pconf, pcls, tcls\n            self.stats.append((correct_bboxes, correct_masks, pred[:, 4], pred[:, 5], cls.squeeze(-1)))\n\n            pred_masks = torch.as_tensor(pred_masks, dtype=torch.uint8)\n            if self.args.plots and self.batch_i < 3:\n                self.plot_masks.append(pred_masks[:15].cpu())  # filter top 15 to plot\n\n            # Save\n            if self.args.save_json:\n                pred_masks = ops.scale_image(pred_masks.permute(1, 2, 0).contiguous().cpu().numpy(),\n                                             shape,\n                                             ratio_pad=batch['ratio_pad'][si])\n                self.pred_to_json(predn, batch['im_file'][si], pred_masks)\n            # if self.args.save_txt:\n            #    save_one_txt(predn, save_conf, shape, file=save_dir / 'labels' / f'{path.stem}.txt')\n\n    def finalize_metrics(self, *args, **kwargs):\n        \"\"\"Sets speed and confusion matrix for evaluation metrics.\"\"\"\n        self.metrics.speed = self.speed\n        self.metrics.confusion_matrix = self.confusion_matrix\n\n    def _process_batch(self, detections, labels, pred_masks=None, gt_masks=None, overlap=False, masks=False):\n        \"\"\"\n        Return correct prediction matrix\n        Arguments:\n            detections (array[N, 6]), x1, y1, x2, y2, conf, class\n            labels (array[M, 5]), class, x1, y1, x2, y2\n        Returns:\n            correct (array[N, 10]), for 10 IoU levels\n        \"\"\"\n        \n        iou_mean = 0\n        \n        if masks:\n            if overlap:\n                nl = len(labels)\n                index = torch.arange(nl, device=gt_masks.device).view(nl, 1, 1) + 1\n                gt_masks = gt_masks.repeat(nl, 1, 1)  # shape(1,640,640) -> (n,640,640)\n                gt_masks = torch.where(gt_masks == index, 1.0, 0.0)\n            if gt_masks.shape[1:] != pred_masks.shape[1:]:\n                gt_masks = F.interpolate(gt_masks[None], pred_masks.shape[1:], mode='bilinear', align_corners=False)[0]\n                gt_masks = gt_masks.gt_(0.5)\n            iou = mask_iou(gt_masks.view(gt_masks.shape[0], -1), pred_masks.view(pred_masks.shape[0], -1))\n\n            # # below is calculate the iou_mean\n            # iou_numpy = iou.cpu().numpy()\n            # iou_mean = iou_numpy.mean()\n            # summary = iou_mean.sum()\n            # count = iou_mean.size\n            # iou_mean = summary/count\n            # iou_mean = iou.mean()\n            \n        else:  # boxes\n            iou = box_iou(labels[:, 1:], detections[:, :4])\n\n        correct = np.zeros((detections.shape[0], self.iouv.shape[0])).astype(bool)\n        correct_class = labels[:, 0:1] == detections[:, 5]\n        for i in range(len(self.iouv)):\n            x = torch.where((iou >= self.iouv[i]) & correct_class)  # IoU > threshold and classes match\n            if x[0].shape[0]:\n                matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]),\n                                    1).cpu().numpy()  # [label, detect, iou]\n                if x[0].shape[0] > 1:\n                    matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 1], return_index=True)[1]]\n                    # matches = matches[matches[:, 2].argsort()[::-1]]\n                    matches = matches[np.unique(matches[:, 0], return_index=True)[1]]\n                correct[matches[:, 1].astype(int), i] = True\n        return torch.tensor(correct, dtype=torch.bool, device=detections.device)\n\n    def plot_val_samples(self, batch, ni):\n        \"\"\"Plots validation samples with bounding box labels.\"\"\"\n        plot_images(batch['img'],\n                    batch['batch_idx'],\n                    batch['cls'].squeeze(-1),\n                    batch['bboxes'],\n                    batch['masks'],\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'val_batch{ni}_labels.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)\n\n    def plot_predictions(self, batch, preds, ni):\n        \"\"\"Plots batch predictions with masks and bounding boxes.\"\"\"\n        plot_images(batch['img'],\n                    *output_to_target(preds[0], max_det=15),\n                    torch.cat(self.plot_masks, dim=0) if len(self.plot_masks) else self.plot_masks,\n                    paths=batch['im_file'],\n                    fname=self.save_dir / f'val_batch{ni}_pred.jpg',\n                    names=self.names,\n                    on_plot=self.on_plot)  # pred\n        self.plot_masks.clear()\n\n    def pred_to_json(self, predn, filename, pred_masks):\n        \"\"\"Save one JSON result.\"\"\"\n        # Example result = {\"image_id\": 42, \"category_id\": 18, \"bbox\": [258.15, 41.29, 348.26, 243.78], \"score\": 0.236}\n        from pycocotools.mask import encode  # noqa\n\n        def single_encode(x):\n            \"\"\"Encode predicted masks as RLE and append results to jdict.\"\"\"\n            rle = encode(np.asarray(x[:, :, None], order='F', dtype='uint8'))[0]\n            rle['counts'] = rle['counts'].decode('utf-8')\n            return rle\n\n        stem = Path(filename).stem\n        image_id = int(stem) if stem.isnumeric() else stem\n        box = ops.xyxy2xywh(predn[:, :4])  # xywh\n        box[:, :2] -= box[:, 2:] / 2  # xy center to top-left corner\n        pred_masks = np.transpose(pred_masks, (2, 0, 1))\n        with ThreadPool(NUM_THREADS) as pool:\n            rles = pool.map(single_encode, pred_masks)\n        for i, (p, b) in enumerate(zip(predn.tolist(), box.tolist())):\n            self.jdict.append({\n                'image_id': image_id,\n                'category_id': self.class_map[int(p[5])],\n                'bbox': [round(x, 3) for x in b],\n                'score': round(p[4], 5),\n                'segmentation': rles[i]})\n\n    def eval_json(self, stats):\n        \"\"\"Return COCO-style object detection evaluation metrics.\"\"\"\n        if self.args.save_json and self.is_coco and len(self.jdict):\n            anno_json = self.data['path'] / 'annotations/instances_val2017.json'  # annotations\n            pred_json = self.save_dir / 'predictions.json'  # predictions\n            LOGGER.info(f'\\nEvaluating pycocotools mAP using {pred_json} and {anno_json}...')\n            try:  # https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/pycocoEvalDemo.ipynb\n                check_requirements('pycocotools>=2.0.6')\n                from pycocotools.coco import COCO  # noqa\n                from pycocotools.cocoeval import COCOeval  # noqa\n\n                for x in anno_json, pred_json:\n                    assert x.is_file(), f'{x} file not found'\n                anno = COCO(str(anno_json))  # init annotations api\n                pred = anno.loadRes(str(pred_json))  # init predictions api (must pass string, not Path)\n                for i, eval in enumerate([COCOeval(anno, pred, 'bbox'), COCOeval(anno, pred, 'segm')]):\n                    if self.is_coco:\n                        eval.params.imgIds = [int(Path(x).stem) for x in self.dataloader.dataset.im_files]  # im to eval\n                    eval.evaluate()\n                    eval.accumulate()\n                    eval.summarize()\n                    idx = i * 4 + 2\n                    stats[self.metrics.keys[idx + 1]], stats[\n                        self.metrics.keys[idx]] = eval.stats[:2]  # update mAP50-95 and mAP50\n            except Exception as e:\n                LOGGER.warning(f'pycocotools unable to run: {e}')\n        return stats\n\n\ndef val(cfg=DEFAULT_CFG, use_python=False):\n    \"\"\"Validate trained YOLO model on validation data.\"\"\"\n    model = cfg.model or 'yolov8n-seg.pt'\n    data = cfg.data or 'coco128-seg.yaml'\n\n    args = dict(model=model, data=data)\n    if use_python:\n        from ultralytics import YOLO\n        YOLO(model).val(**args)\n    else:\n        validator = SegmentationValidator(args=args)\n        validator(model=args['model'])\n\n\nif __name__ == '__main__':\n    val()\n"
  },
  {
    "path": "ultralytics.egg-info/PKG-INFO",
    "content": "Metadata-Version: 2.1\nName: ultralytics\nVersion: 8.0.105\nSummary: Ultralytics YOLOv8 for SOTA object detection, multi-object tracking, instance segmentation, pose estimation and image classification.\nHome-page: https://github.com/ultralytics/ultralytics\nAuthor: Ultralytics\nAuthor-email: hello@ultralytics.com\nLicense: AGPL-3.0\nProject-URL: Bug Reports, https://github.com/ultralytics/ultralytics/issues\nProject-URL: Funding, https://ultralytics.com\nProject-URL: Source, https://github.com/ultralytics/ultralytics\nKeywords: machine-learning,deep-learning,vision,ML,DL,AI,YOLO,YOLOv3,YOLOv5,YOLOv8,HUB,Ultralytics\nClassifier: Development Status :: 4 - Beta\nClassifier: Intended Audience :: Developers\nClassifier: Intended Audience :: Education\nClassifier: Intended Audience :: Science/Research\nClassifier: License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)\nClassifier: Programming Language :: Python :: 3\nClassifier: Programming Language :: Python :: 3.7\nClassifier: Programming Language :: Python :: 3.8\nClassifier: Programming Language :: Python :: 3.9\nClassifier: Programming Language :: Python :: 3.10\nClassifier: Programming Language :: Python :: 3.11\nClassifier: Topic :: Software Development\nClassifier: Topic :: Scientific/Engineering\nClassifier: Topic :: Scientific/Engineering :: Artificial Intelligence\nClassifier: Topic :: Scientific/Engineering :: Image Recognition\nClassifier: Operating System :: POSIX :: Linux\nClassifier: Operating System :: MacOS\nClassifier: Operating System :: Microsoft :: Windows\nRequires-Python: >=3.7\nDescription-Content-Type: text/markdown\nProvides-Extra: dev\nProvides-Extra: export\nLicense-File: LICENSE\n\n<div align=\"center\">\n  <p>\n    <a href=\"https://ultralytics.com/yolov8\" target=\"_blank\">\n      <img width=\"100%\" src=\"https://raw.githubusercontent.com/ultralytics/assets/main/yolov8/banner-yolov8.png\"></a>\n  </p>\n\n[English](README.md) | [简体中文](README.zh-CN.md)\n<br>\n\n<div>\n    <a href=\"https://github.com/ultralytics/ultralytics/actions/workflows/ci.yaml\"><img src=\"https://github.com/ultralytics/ultralytics/actions/workflows/ci.yaml/badge.svg\" alt=\"Ultralytics CI\"></a>\n    <a href=\"https://zenodo.org/badge/latestdoi/264818686\"><img src=\"https://zenodo.org/badge/264818686.svg\" alt=\"YOLOv8 Citation\"></a>\n    <a href=\"https://hub.docker.com/r/ultralytics/ultralytics\"><img src=\"https://img.shields.io/docker/pulls/ultralytics/ultralytics?logo=docker\" alt=\"Docker Pulls\"></a>\n    <br>\n    <a href=\"https://console.paperspace.com/github/ultralytics/ultralytics\"><img src=\"https://assets.paperspace.io/img/gradient-badge.svg\" alt=\"Run on Gradient\"/></a>\n    <a href=\"https://colab.research.google.com/github/ultralytics/ultralytics/blob/main/examples/tutorial.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n    <a href=\"https://www.kaggle.com/ultralytics/yolov8\"><img src=\"https://kaggle.com/static/images/open-in-kaggle.svg\" alt=\"Open In Kaggle\"></a>\n  </div>\n  <br>\n\n[Ultralytics](https://ultralytics.com) [YOLOv8](https://github.com/ultralytics/ultralytics) is a cutting-edge, state-of-the-art (SOTA) model that builds upon the success of previous YOLO versions and introduces new features and improvements to further boost performance and flexibility. YOLOv8 is designed to be fast, accurate, and easy to use, making it an excellent choice for a wide range of object detection and tracking, instance segmentation, image classification and pose estimation tasks.\n\nWe hope that the resources here will help you get the most out of YOLOv8. Please browse the YOLOv8 <a href=\"https://docs.ultralytics.com/\">Docs</a> for details, raise an issue on <a href=\"https://github.com/ultralytics/ultralytics/issues/new/choose\">GitHub</a> for support, and join our <a href=\"https://discord.gg/n6cFeSPZdD\">Discord</a> community for questions and discussions!\n\nTo request an Enterprise License please complete the form at [Ultralytics Licensing](https://ultralytics.com/license).\n\n<img width=\"100%\" src=\"https://raw.githubusercontent.com/ultralytics/assets/main/yolov8/yolo-comparison-plots.png\"></a>\n\n<div align=\"center\">\n  <a href=\"https://github.com/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-github.png\" width=\"2%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"2%\" alt=\"\" />\n  <a href=\"https://www.linkedin.com/company/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-linkedin.png\" width=\"2%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"2%\" alt=\"\" />\n  <a href=\"https://twitter.com/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-twitter.png\" width=\"2%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"2%\" alt=\"\" />\n  <a href=\"https://youtube.com/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-youtube.png\" width=\"2%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"2%\" alt=\"\" />\n  <a href=\"https://www.tiktok.com/@ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-tiktok.png\" width=\"2%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"2%\" alt=\"\" />\n  <a href=\"https://www.instagram.com/ultralytics/\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-instagram.png\" width=\"2%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"2%\" alt=\"\" />\n  <a href=\"https://discord.gg/n6cFeSPZdD\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/blob/main/social/logo-social-discord.png\" width=\"2%\" alt=\"\" /></a>\n</div>\n</div>\n\n## <div align=\"center\">Documentation</div>\n\nSee below for a quickstart installation and usage example, and see the [YOLOv8 Docs](https://docs.ultralytics.com) for full documentation on training, validation, prediction and deployment.\n\n<details open>\n<summary>Install</summary>\n\nPip install the ultralytics package including all [requirements](https://github.com/ultralytics/ultralytics/blob/main/requirements.txt) in a [**Python>=3.7**](https://www.python.org/) environment with [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/).\n\n```bash\npip install ultralytics\n```\n\n</details>\n\n<details open>\n<summary>Usage</summary>\n\n#### CLI\n\nYOLOv8 may be used directly in the Command Line Interface (CLI) with a `yolo` command:\n\n```bash\nyolo predict model=yolov8n.pt source='https://ultralytics.com/images/bus.jpg'\n```\n\n`yolo` can be used for a variety of tasks and modes and accepts additional arguments, i.e. `imgsz=640`. See the YOLOv8 [CLI Docs](https://docs.ultralytics.com/usage/cli) for examples.\n\n#### Python\n\nYOLOv8 may also be used directly in a Python environment, and accepts the same [arguments](https://docs.ultralytics.com/usage/cfg/) as in the CLI example above:\n\n```python\nfrom ultralytics import YOLO\n\n# Load a model\nmodel = YOLO(\"yolov8n.yaml\")  # build a new model from scratch\nmodel = YOLO(\"yolov8n.pt\")  # load a pretrained model (recommended for training)\n\n# Use the model\nmodel.train(data=\"coco128.yaml\", epochs=3)  # train the model\nmetrics = model.val()  # evaluate model performance on the validation set\nresults = model(\"https://ultralytics.com/images/bus.jpg\")  # predict on an image\nsuccess = model.export(format=\"onnx\")  # export the model to ONNX format\n```\n\n[Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models) download automatically from the latest Ultralytics [release](https://github.com/ultralytics/assets/releases). See YOLOv8 [Python Docs](https://docs.ultralytics.com/usage/python) for more examples.\n\n</details>\n\n## <div align=\"center\">Models</div>\n\nAll YOLOv8 pretrained models are available here. Detect, Segment and Pose models are pretrained on the [COCO](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/coco.yaml) dataset, while Classify models are pretrained on the [ImageNet](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/datasets/ImageNet.yaml) dataset.\n\n[Models](https://github.com/ultralytics/ultralytics/tree/main/ultralytics/models) download automatically from the latest Ultralytics [release](https://github.com/ultralytics/assets/releases) on first use.\n\n<details open><summary>Detection</summary>\n\nSee [Detection Docs](https://docs.ultralytics.com/tasks/detect/) for usage examples with these models.\n\n| Model                                                                                | size<br><sup>(pixels) | mAP<sup>val<br>50-95 | Speed<br><sup>CPU ONNX<br>(ms) | Speed<br><sup>A100 TensorRT<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>(B) |\n| ------------------------------------------------------------------------------------ | --------------------- | -------------------- | ------------------------------ | ----------------------------------- | ------------------ | ----------------- |\n| [YOLOv8n](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt) | 640                   | 37.3                 | 80.4                           | 0.99                                | 3.2                | 8.7               |\n| [YOLOv8s](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s.pt) | 640                   | 44.9                 | 128.4                          | 1.20                                | 11.2               | 28.6              |\n| [YOLOv8m](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m.pt) | 640                   | 50.2                 | 234.7                          | 1.83                                | 25.9               | 78.9              |\n| [YOLOv8l](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l.pt) | 640                   | 52.9                 | 375.2                          | 2.39                                | 43.7               | 165.2             |\n| [YOLOv8x](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x.pt) | 640                   | 53.9                 | 479.1                          | 3.53                                | 68.2               | 257.8             |\n\n- **mAP<sup>val</sup>** values are for single-model single-scale on [COCO val2017](http://cocodataset.org) dataset.\n  <br>Reproduce by `yolo val detect data=coco.yaml device=0`\n- **Speed** averaged over COCO val images using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/) instance.\n  <br>Reproduce by `yolo val detect data=coco128.yaml batch=1 device=0|cpu`\n\n</details>\n\n<details><summary>Segmentation</summary>\n\nSee [Segmentation Docs](https://docs.ultralytics.com/tasks/segment/) for usage examples with these models.\n\n| Model                                                                                        | size<br><sup>(pixels) | mAP<sup>box<br>50-95 | mAP<sup>mask<br>50-95 | Speed<br><sup>CPU ONNX<br>(ms) | Speed<br><sup>A100 TensorRT<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>(B) |\n| -------------------------------------------------------------------------------------------- | --------------------- | -------------------- | --------------------- | ------------------------------ | ----------------------------------- | ------------------ | ----------------- |\n| [YOLOv8n-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n-seg.pt) | 640                   | 36.7                 | 30.5                  | 96.1                           | 1.21                                | 3.4                | 12.6              |\n| [YOLOv8s-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s-seg.pt) | 640                   | 44.6                 | 36.8                  | 155.7                          | 1.47                                | 11.8               | 42.6              |\n| [YOLOv8m-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m-seg.pt) | 640                   | 49.9                 | 40.8                  | 317.0                          | 2.18                                | 27.3               | 110.2             |\n| [YOLOv8l-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l-seg.pt) | 640                   | 52.3                 | 42.6                  | 572.4                          | 2.79                                | 46.0               | 220.5             |\n| [YOLOv8x-seg](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-seg.pt) | 640                   | 53.4                 | 43.4                  | 712.1                          | 4.02                                | 71.8               | 344.1             |\n\n- **mAP<sup>val</sup>** values are for single-model single-scale on [COCO val2017](http://cocodataset.org) dataset.\n  <br>Reproduce by `yolo val segment data=coco.yaml device=0`\n- **Speed** averaged over COCO val images using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/) instance.\n  <br>Reproduce by `yolo val segment data=coco128-seg.yaml batch=1 device=0|cpu`\n\n</details>\n\n<details><summary>Classification</summary>\n\nSee [Classification Docs](https://docs.ultralytics.com/tasks/classify/) for usage examples with these models.\n\n| Model                                                                                        | size<br><sup>(pixels) | acc<br><sup>top1 | acc<br><sup>top5 | Speed<br><sup>CPU ONNX<br>(ms) | Speed<br><sup>A100 TensorRT<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>(B) at 640 |\n| -------------------------------------------------------------------------------------------- | --------------------- | ---------------- | ---------------- | ------------------------------ | ----------------------------------- | ------------------ | ------------------------ |\n| [YOLOv8n-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n-cls.pt) | 224                   | 66.6             | 87.0             | 12.9                           | 0.31                                | 2.7                | 4.3                      |\n| [YOLOv8s-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s-cls.pt) | 224                   | 72.3             | 91.1             | 23.4                           | 0.35                                | 6.4                | 13.5                     |\n| [YOLOv8m-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m-cls.pt) | 224                   | 76.4             | 93.2             | 85.4                           | 0.62                                | 17.0               | 42.7                     |\n| [YOLOv8l-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l-cls.pt) | 224                   | 78.0             | 94.1             | 163.0                          | 0.87                                | 37.5               | 99.7                     |\n| [YOLOv8x-cls](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-cls.pt) | 224                   | 78.4             | 94.3             | 232.0                          | 1.01                                | 57.4               | 154.8                    |\n\n- **acc** values are model accuracies on the [ImageNet](https://www.image-net.org/) dataset validation set.\n  <br>Reproduce by `yolo val classify data=path/to/ImageNet device=0`\n- **Speed** averaged over ImageNet val images using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/) instance.\n  <br>Reproduce by `yolo val classify data=path/to/ImageNet batch=1 device=0|cpu`\n\n</details>\n\n<details><summary>Pose</summary>\n\nSee [Pose Docs](https://docs.ultralytics.com/tasks/pose) for usage examples with these models.\n\n| Model                                                                                                | size<br><sup>(pixels) | mAP<sup>pose<br>50-95 | mAP<sup>pose<br>50 | Speed<br><sup>CPU ONNX<br>(ms) | Speed<br><sup>A100 TensorRT<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>(B) |\n| ---------------------------------------------------------------------------------------------------- | --------------------- | --------------------- | ------------------ | ------------------------------ | ----------------------------------- | ------------------ | ----------------- |\n| [YOLOv8n-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n-pose.pt)       | 640                   | 50.4                  | 80.1               | 131.8                          | 1.18                                | 3.3                | 9.2               |\n| [YOLOv8s-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8s-pose.pt)       | 640                   | 60.0                  | 86.2               | 233.2                          | 1.42                                | 11.6               | 30.2              |\n| [YOLOv8m-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8m-pose.pt)       | 640                   | 65.0                  | 88.8               | 456.3                          | 2.00                                | 26.4               | 81.0              |\n| [YOLOv8l-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8l-pose.pt)       | 640                   | 67.6                  | 90.0               | 784.5                          | 2.59                                | 44.4               | 168.6             |\n| [YOLOv8x-pose](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-pose.pt)       | 640                   | 69.2                  | 90.2               | 1607.1                         | 3.73                                | 69.4               | 263.2             |\n| [YOLOv8x-pose-p6](https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8x-pose-p6.pt) | 1280                  | 71.6                  | 91.2               | 4088.7                         | 10.04                               | 99.1               | 1066.4            |\n\n- **mAP<sup>val</sup>** values are for single-model single-scale on [COCO Keypoints val2017](http://cocodataset.org)\n  dataset.\n  <br>Reproduce by `yolo val pose data=coco-pose.yaml device=0`\n- **Speed** averaged over COCO val images using an [Amazon EC2 P4d](https://aws.amazon.com/ec2/instance-types/p4/) instance.\n  <br>Reproduce by `yolo val pose data=coco8-pose.yaml batch=1 device=0|cpu`\n\n</details>\n\n## <div align=\"center\">Integrations</div>\n\n<br>\n<a href=\"https://bit.ly/ultralytics_hub\" target=\"_blank\">\n<img width=\"100%\" src=\"https://github.com/ultralytics/assets/raw/main/yolov8/banner-integrations.png\"></a>\n<br>\n<br>\n\n<div align=\"center\">\n  <a href=\"https://roboflow.com/?ref=ultralytics\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/partners/logo-roboflow.png\" width=\"10%\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"15%\" height=\"0\" alt=\"\" />\n  <a href=\"https://cutt.ly/yolov5-readme-clearml\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/partners/logo-clearml.png\" width=\"10%\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"15%\" height=\"0\" alt=\"\" />\n  <a href=\"https://bit.ly/yolov8-readme-comet\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/partners/logo-comet.png\" width=\"10%\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"15%\" height=\"0\" alt=\"\" />\n  <a href=\"https://bit.ly/yolov5-neuralmagic\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/partners/logo-neuralmagic.png\" width=\"10%\" /></a>\n</div>\n\n|                                                           Roboflow                                                           |                                                            ClearML ⭐ NEW                                                            |                                                                        Comet ⭐ NEW                                                                        |                                           Neural Magic ⭐ NEW                                           |\n| :--------------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------: | :----------------------------------------------------------------------------------------------------: |\n| Label and export your custom datasets directly to YOLOv8 for training with [Roboflow](https://roboflow.com/?ref=ultralytics) | Automatically track, visualize and even remotely train YOLOv8 using [ClearML](https://cutt.ly/yolov5-readme-clearml) (open-source!) | Free forever, [Comet](https://bit.ly/yolov8-readme-comet) lets you save YOLOv8 models, resume training, and interactively visualize and debug predictions | Run YOLOv8 inference up to 6x faster with [Neural Magic DeepSparse](https://bit.ly/yolov5-neuralmagic) |\n\n## <div align=\"center\">Ultralytics HUB</div>\n\nExperience seamless AI with [Ultralytics HUB](https://bit.ly/ultralytics_hub) ⭐, the all-in-one solution for data visualization, YOLOv5 and YOLOv8 🚀 model training and deployment, without any coding. Transform images into actionable insights and bring your AI visions to life with ease using our cutting-edge platform and user-friendly [Ultralytics App](https://ultralytics.com/app_install). Start your journey for **Free** now!\n\n<a href=\"https://bit.ly/ultralytics_hub\" target=\"_blank\">\n<img width=\"100%\" src=\"https://github.com/ultralytics/assets/raw/main/im/ultralytics-hub.png\"></a>\n\n## <div align=\"center\">Contribute</div>\n\nWe love your input! YOLOv5 and YOLOv8 would not be possible without help from our community. Please see our [Contributing Guide](https://docs.ultralytics.com/help/contributing) to get started, and fill out our [Survey](https://ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey) to send us feedback on your experience. Thank you 🙏 to all our contributors!\n\n<!-- SVG image from https://opencollective.com/ultralytics/contributors.svg?width=990 -->\n\n<a href=\"https://github.com/ultralytics/yolov5/graphs/contributors\">\n<img width=\"100%\" src=\"https://github.com/ultralytics/assets/raw/main/im/image-contributors.png\"></a>\n\n## <div align=\"center\">License</div>\n\nYOLOv8 is available under two different licenses:\n\n- **AGPL-3.0 License**: See [LICENSE](https://github.com/ultralytics/ultralytics/blob/main/LICENSE) file for details.\n- **Enterprise License**: Provides greater flexibility for commercial product development without the open-source requirements of AGPL-3.0. Typical use cases are embedding Ultralytics software and AI models in commercial products and applications. Request an Enterprise License at [Ultralytics Licensing](https://ultralytics.com/license).\n\n## <div align=\"center\">Contact</div>\n\nFor YOLOv8 bug reports and feature requests please visit [GitHub Issues](https://github.com/ultralytics/ultralytics/issues), and join our [Discord](https://discord.gg/n6cFeSPZdD) community for questions and discussions!\n\n<br>\n<div align=\"center\">\n  <a href=\"https://github.com/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-github.png\" width=\"3%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"3%\" alt=\"\" />\n  <a href=\"https://www.linkedin.com/company/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-linkedin.png\" width=\"3%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"3%\" alt=\"\" />\n  <a href=\"https://twitter.com/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-twitter.png\" width=\"3%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"3%\" alt=\"\" />\n  <a href=\"https://youtube.com/ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-youtube.png\" width=\"3%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"3%\" alt=\"\" />\n  <a href=\"https://www.tiktok.com/@ultralytics\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-tiktok.png\" width=\"3%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"3%\" alt=\"\" />\n  <a href=\"https://www.instagram.com/ultralytics/\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-social-instagram.png\" width=\"3%\" alt=\"\" /></a>\n  <img src=\"https://github.com/ultralytics/assets/raw/main/social/logo-transparent.png\" width=\"3%\" alt=\"\" />\n  <a href=\"https://discord.gg/n6cFeSPZdD\" style=\"text-decoration:none;\">\n    <img src=\"https://github.com/ultralytics/assets/blob/main/social/logo-social-discord.png\" width=\"3%\" alt=\"\" /></a>\n</div>\n"
  },
  {
    "path": "ultralytics.egg-info/SOURCES.txt",
    "content": "CONTRIBUTING.md\nLICENSE\nMANIFEST.in\nREADME.md\nREADME.zh-CN.md\nrequirements.txt\nsetup.cfg\nsetup.py\nultralytics/__init__.py\nultralytics/predict.py\nultralytics/resum_training.py\nultralytics/train.py\nultralytics/val.py\nultralytics.egg-info/PKG-INFO\nultralytics.egg-info/SOURCES.txt\nultralytics.egg-info/dependency_links.txt\nultralytics.egg-info/entry_points.txt\nultralytics.egg-info/requires.txt\nultralytics.egg-info/top_level.txt\nultralytics/assets/bus.jpg\nultralytics/assets/zidane.jpg\nultralytics/datasets/Argoverse.yaml\nultralytics/datasets/GlobalWheat2020.yaml\nultralytics/datasets/ImageNet.yaml\nultralytics/datasets/Objects365.yaml\nultralytics/datasets/SKU-110K.yaml\nultralytics/datasets/VOC.yaml\nultralytics/datasets/VisDrone.yaml\nultralytics/datasets/bdd-drivable-seg-toy.yaml\nultralytics/datasets/bdd-lane-seg-toy.yaml\nultralytics/datasets/bdd-multi-toy.yaml\nultralytics/datasets/bdd-multi.yaml\nultralytics/datasets/coco-pose.yaml\nultralytics/datasets/coco-toy.yaml\nultralytics/datasets/coco.yaml\nultralytics/datasets/coco128-seg.yaml\nultralytics/datasets/coco128.yaml\nultralytics/datasets/coco8-pose.yaml\nultralytics/datasets/coco8-seg.yaml\nultralytics/datasets/coco8.yaml\nultralytics/datasets/xView.yaml\nultralytics/datasets/.ipynb_checkpoints/bdd-multi-checkpoint.yaml\nultralytics/hub/__init__.py\nultralytics/hub/auth.py\nultralytics/hub/session.py\nultralytics/hub/utils.py\nultralytics/models/rt-detr/rt-detr-l.yaml\nultralytics/models/rt-detr/rt-detr-x.yaml\nultralytics/models/v3/yolov3-spp.yaml\nultralytics/models/v3/yolov3-tiny.yaml\nultralytics/models/v3/yolov3.yaml\nultralytics/models/v5/yolov5-p6.yaml\nultralytics/models/v5/yolov5.yaml\nultralytics/models/v8/yolov8-bdd-one.yaml\nultralytics/models/v8/yolov8-bdd-v3-one-s.yaml\nultralytics/models/v8/yolov8-bdd-v3-one.yaml\nultralytics/models/v8/yolov8-bdd-v3.yaml\nultralytics/models/v8/yolov8-bdd-v4-one-dropout-individual-m.yaml\nultralytics/models/v8/yolov8-bdd-v4-one-dropout-individual-s.yaml\nultralytics/models/v8/yolov8-bdd-v4-one-dropout-individual.yaml\nultralytics/models/v8/yolov8-bdd-v4-one-dropout.yaml\nultralytics/models/v8/yolov8-bdd.yaml\nultralytics/models/v8/yolov8-cls.yaml\nultralytics/models/v8/yolov8-p2.yaml\nultralytics/models/v8/yolov8-p6.yaml\nultralytics/models/v8/yolov8-pose-p6.yaml\nultralytics/models/v8/yolov8-pose.yaml\nultralytics/models/v8/yolov8-seg.yaml\nultralytics/models/v8/yolov8.yaml\nultralytics/nn/__init__.py\nultralytics/nn/autobackend.py\nultralytics/nn/autoshape.py\nultralytics/nn/tasks.py\nultralytics/nn/modules/__init__.py\nultralytics/nn/modules/block.py\nultralytics/nn/modules/conv.py\nultralytics/nn/modules/head.py\nultralytics/nn/modules/transformer.py\nultralytics/nn/modules/utils.py\nultralytics/tracker/__init__.py\nultralytics/tracker/track.py\nultralytics/tracker/cfg/botsort.yaml\nultralytics/tracker/cfg/bytetrack.yaml\nultralytics/tracker/trackers/__init__.py\nultralytics/tracker/trackers/basetrack.py\nultralytics/tracker/trackers/bot_sort.py\nultralytics/tracker/trackers/byte_tracker.py\nultralytics/tracker/utils/__init__.py\nultralytics/tracker/utils/gmc.py\nultralytics/tracker/utils/kalman_filter.py\nultralytics/tracker/utils/matching.py\nultralytics/vit/__init__.py\nultralytics/vit/rtdetr/__init__.py\nultralytics/vit/rtdetr/model.py\nultralytics/vit/rtdetr/predict.py\nultralytics/vit/rtdetr/val.py\nultralytics/vit/sam/__init__.py\nultralytics/vit/sam/amg.py\nultralytics/vit/sam/autosize.py\nultralytics/vit/sam/build.py\nultralytics/vit/sam/model.py\nultralytics/vit/sam/predict.py\nultralytics/vit/sam/modules/__init__.py\nultralytics/vit/sam/modules/decoders.py\nultralytics/vit/sam/modules/encoders.py\nultralytics/vit/sam/modules/mask_generator.py\nultralytics/vit/sam/modules/prompt_predictor.py\nultralytics/vit/sam/modules/sam.py\nultralytics/vit/sam/modules/transformer.py\nultralytics/yolo/__init__.py\nultralytics/yolo/cfg/__init__.py\nultralytics/yolo/cfg/default.yaml\nultralytics/yolo/data/__init__.py\nultralytics/yolo/data/annotator.py\nultralytics/yolo/data/augment.py\nultralytics/yolo/data/base.py\nultralytics/yolo/data/build.py\nultralytics/yolo/data/converter.py\nultralytics/yolo/data/dataset.py\nultralytics/yolo/data/dataset_wrappers.py\nultralytics/yolo/data/utils.py\nultralytics/yolo/data/dataloaders/__init__.py\nultralytics/yolo/data/dataloaders/stream_loaders.py\nultralytics/yolo/data/dataloaders/v5augmentations.py\nultralytics/yolo/data/dataloaders/v5loader.py\nultralytics/yolo/engine/__init__.py\nultralytics/yolo/engine/exporter.py\nultralytics/yolo/engine/model.py\nultralytics/yolo/engine/predictor.py\nultralytics/yolo/engine/results.py\nultralytics/yolo/engine/trainer.py\nultralytics/yolo/engine/trainer_multi.py\nultralytics/yolo/engine/validator.py\nultralytics/yolo/utils/__init__.py\nultralytics/yolo/utils/autobatch.py\nultralytics/yolo/utils/benchmarks.py\nultralytics/yolo/utils/checks.py\nultralytics/yolo/utils/dist.py\nultralytics/yolo/utils/downloads.py\nultralytics/yolo/utils/errors.py\nultralytics/yolo/utils/files.py\nultralytics/yolo/utils/instance.py\nultralytics/yolo/utils/loss.py\nultralytics/yolo/utils/metrics.py\nultralytics/yolo/utils/ops.py\nultralytics/yolo/utils/plotting.py\nultralytics/yolo/utils/tal.py\nultralytics/yolo/utils/torch_utils.py\nultralytics/yolo/utils/tuner.py\nultralytics/yolo/utils/callbacks/__init__.py\nultralytics/yolo/utils/callbacks/base.py\nultralytics/yolo/utils/callbacks/clearml.py\nultralytics/yolo/utils/callbacks/comet.py\nultralytics/yolo/utils/callbacks/hub.py\nultralytics/yolo/utils/callbacks/mlflow.py\nultralytics/yolo/utils/callbacks/neptune.py\nultralytics/yolo/utils/callbacks/raytune.py\nultralytics/yolo/utils/callbacks/tensorboard.py\nultralytics/yolo/utils/callbacks/wb.py\nultralytics/yolo/v8/__init__.py\nultralytics/yolo/v8/DecSeg/__init__.py\nultralytics/yolo/v8/DecSeg/predict.py\nultralytics/yolo/v8/DecSeg/train.py\nultralytics/yolo/v8/DecSeg/val.py\nultralytics/yolo/v8/classify/__init__.py\nultralytics/yolo/v8/classify/predict.py\nultralytics/yolo/v8/classify/train.py\nultralytics/yolo/v8/classify/val.py\nultralytics/yolo/v8/detect/__init__.py\nultralytics/yolo/v8/detect/predict.py\nultralytics/yolo/v8/detect/train.py\nultralytics/yolo/v8/detect/val.py\nultralytics/yolo/v8/pose/__init__.py\nultralytics/yolo/v8/pose/predict.py\nultralytics/yolo/v8/pose/train.py\nultralytics/yolo/v8/pose/val.py\nultralytics/yolo/v8/segment/__init__.py\nultralytics/yolo/v8/segment/predict.py\nultralytics/yolo/v8/segment/train.py\nultralytics/yolo/v8/segment/val.py"
  },
  {
    "path": "ultralytics.egg-info/dependency_links.txt",
    "content": "\n"
  },
  {
    "path": "ultralytics.egg-info/entry_points.txt",
    "content": "[console_scripts]\nultralytics = ultralytics.yolo.cfg:entrypoint\nyolo = ultralytics.yolo.cfg:entrypoint\n"
  },
  {
    "path": "ultralytics.egg-info/requires.txt",
    "content": "matplotlib>=3.2.2\nopencv-python>=4.6.0\nPillow>=7.1.2\nPyYAML>=5.3.1\nrequests>=2.23.0\nscipy>=1.4.1\ntorch>=1.7.0\ntorchvision>=0.8.1\ntqdm>=4.64.0\npandas>=1.1.4\nseaborn>=0.11.0\npsutil\nsentry_sdk\n\n[dev]\ncheck-manifest\npytest\npytest-cov\ncoverage\nmkdocs-material\nmkdocstrings[python]\nmkdocs-redirects\nmkdocs-ultralytics-plugin\n\n[export]\ncoremltools>=6.0\nopenvino-dev>=2022.3\ntensorflowjs\n"
  },
  {
    "path": "ultralytics.egg-info/top_level.txt",
    "content": "ultralytics\n"
  }
]